Skip to content

Commit

Permalink
Max web socket retry config (#101)
Browse files Browse the repository at this point in the history
* splits out websocket provider configuration into its own file
* expose the retry and delay settings for `find` in the repo initializers
  • Loading branch information
heckj authored May 15, 2024
1 parent 512a37e commit cf5ccf7
Show file tree
Hide file tree
Showing 3 changed files with 90 additions and 30 deletions.
41 changes: 17 additions & 24 deletions Sources/AutomergeRepo/Networking/Providers/WebSocketProvider.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,29 +11,6 @@ public final class WebSocketProvider: NetworkProvider {
/// A type that represents the configuration used to create the provider.
public typealias ProviderConfiguration = WebSocketProviderConfiguration

/// The configuration options for a WebSocket network provider.
public struct WebSocketProviderConfiguration: Sendable {
/// A Boolean value that indicates if the provider should attempt to reconnect when it fails with an error.
public let reconnectOnError: Bool
/// The verbosity of the logs sent to the unified logging system.
public let logLevel: LogVerbosity
/// The default configuration for the WebSocket network provider.
///
/// In the default configuration:
///
/// - `reconnectOnError` is `true`
public static let `default` = WebSocketProviderConfiguration(reconnectOnError: true)

/// Creates a new WebSocket network provider configuration instance.
/// - Parameter reconnectOnError: A Boolean value that indicates if the provider should attempt to reconnect
/// when it fails with an error.
/// - Parameter loggingAt: The verbosity of the logs sent to the unified logging system.
public init(reconnectOnError: Bool, loggingAt: LogVerbosity = .errorOnly) {
self.reconnectOnError = reconnectOnError
self.logLevel = loggingAt
}
}

/// The active connection for this provider.
public var peeredConnections: [PeerConnectionInfo]
var delegate: (any NetworkEventReceiver)?
Expand Down Expand Up @@ -358,8 +335,17 @@ public final class WebSocketProvider: NetworkProvider {
return websocketMsg
}

/// Infinitely loops over incoming messages from the websocket and updates the state machine based on the messages
/// Loops over incoming messages from the websocket and updates the state machine based on the messages
/// received.
///
/// If the provider configuration (``WebSocketProviderConfiguration``) has `reconnectOnError`
/// set to `true`, this function attempts to re-establish a WebSocket connection on connection
/// failure or read error. If that value is false, the connection terminates on error and the provider
/// reports the connection as ``WebSocketProviderState/disconnected``.
///
/// If `reconnectOnError`, and `maxNumberOfConnectRetries` has a positive value, a maximum number of retries
/// is enforced. After the provided maximum number of retries, the connection is fully reset and left in the
/// state ``WebSocketProviderState/disconnected``.
private func ongoingReceiveWebSocketMessages() async {
// state needed for reconnect logic:
// - should we reconnect on a receive() error/failure
Expand Down Expand Up @@ -392,6 +378,13 @@ public final class WebSocketProvider: NetworkProvider {
// if we're not currently peered, attempt to reconnect
// (if we're configured to do so)
if !peered, tryToReconnect {
if let maxRetries = config.maxNumberOfConnectRetries, maxRetries > 0, maxRetries > reconnectAttempts {
// maxNumber of connection retries is set, positive, and exceeds the
// number of attempts already made...
tryToReconnect = false
break
}

_statePublisher.send(.reconnecting)
let waitBeforeReconnect = Backoff.delay(reconnectAttempts, withJitter: true)
if config.logLevel.canTrace() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import Automerge

/// The configuration options for a WebSocket network provider.
public struct WebSocketProviderConfiguration: Sendable {
/// A Boolean value that indicates if the provider should attempt to reconnect when it fails with an error.
public let reconnectOnError: Bool
/// The maximum number of reconnections allowed before the WebSocket provider disconnects.
///
/// If ``reconnectOnError`` is `false`, this value is ignored.
/// If `nil`, the default, the WebSocketProvider does not enforce a maximum number of retries.
public let maxNumberOfConnectRetries: Int?
/// The verbosity of the logs sent to the unified logging system.
public let logLevel: LogVerbosity

/// The default configuration for the WebSocket network provider.
///
/// In the default configuration:
///
/// - `reconnectOnError` is `true`
public static let `default` = WebSocketProviderConfiguration(reconnectOnError: true)

/// Creates a new WebSocket network provider configuration instance.
/// - Parameter reconnectOnError: A Boolean value that indicates if the provider should attempt to reconnect
/// when it fails with an error.
/// - Parameter loggingAt: The verbosity of the logs sent to the unified logging system.
public init(reconnectOnError: Bool, loggingAt: LogVerbosity = .errorOnly, maxNumberOfConnectRetries: Int? = nil) {
self.reconnectOnError = reconnectOnError
self.maxNumberOfConnectRetries = maxNumberOfConnectRetries
self.logLevel = loggingAt
}
}
48 changes: 42 additions & 6 deletions Sources/AutomergeRepo/Repo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ public final class Repo {
/** @hidden */
private var peerMetadataByPeerId: [PEER_ID: PeerMetadata] = [:]

private let maxRetriesForFetch: Int = 300
private let pendingRequestWaitDuration: Duration = .seconds(1)
private let maxRetriesForFetch: Int
private let pendingRequestWaitDuration: Duration
private var pendingRequestReadAttempts: [DocumentId: Int] = [:]

private var remoteHeadsGossipingEnabled = false
Expand Down Expand Up @@ -84,12 +84,21 @@ public final class Repo {
/// - Parameter sharePolicy: The policy to use to determine if a repository shares a document.
/// - Parameter saveDebounce: The delay time to accumulate changes to a document before initiating a network sync
/// with available peers. The default is 2 seconds.
/// - Parameter maxResolveFetchIterations: The number of checks to make waiting for peers to provide a requested
/// document. The default value is 300, after which the repository throws an error from ``find(id:)`` that indicates
/// the document is unavailable.
/// - Parameter resolveFetchIterationDelay: The delay between checks while waiting for peers to provide a requested
/// document. The default is 1 second.
public nonisolated init(
sharePolicy: SharePolicy,
saveDebounce: RunLoop.SchedulerTimeType.Stride = .seconds(10)
saveDebounce: RunLoop.SchedulerTimeType.Stride = .seconds(10),
maxResolveFetchIterations: Int = 300,
resolveFetchIterationDelay: Duration = .seconds(1)
) {
peerId = UUID().uuidString
storage = nil
maxRetriesForFetch = maxResolveFetchIterations
pendingRequestWaitDuration = resolveFetchIterationDelay
localPeerMetadata = PeerMetadata(storageId: nil, isEphemeral: true)
self.sharePolicy = sharePolicy as any ShareAuthorizing
network = NetworkSubsystem(verbosity: .errorOnly)
Expand All @@ -101,12 +110,21 @@ public final class Repo {
/// a document.
/// - Parameter saveDebounce: The delay time to accumulate changes to a document before initiating a network sync
/// with available peers. The default is 2 seconds.
/// - Parameter maxResolveFetchIterations: The number of checks to make waiting for peers to provide a requested
/// document. The default value is 300, after which the repository throws an error from ``find(id:)`` that indicates
/// the document is unavailable.
/// - Parameter resolveFetchIterationDelay: The delay between checks while waiting for peers to provide a requested
/// document. The default is 1 second.
public nonisolated init(
sharePolicy: some ShareAuthorizing,
saveDebounce: RunLoop.SchedulerTimeType.Stride = .seconds(10)
saveDebounce: RunLoop.SchedulerTimeType.Stride = .seconds(10),
maxResolveFetchIterations: Int = 300,
resolveFetchIterationDelay: Duration = .seconds(1)
) {
peerId = UUID().uuidString
storage = nil
maxRetriesForFetch = maxResolveFetchIterations
pendingRequestWaitDuration = resolveFetchIterationDelay
localPeerMetadata = PeerMetadata(storageId: nil, isEphemeral: true)
self.sharePolicy = sharePolicy
network = NetworkSubsystem(verbosity: .errorOnly)
Expand All @@ -119,12 +137,21 @@ public final class Repo {
/// - storage: The storage provider for the repository.
/// - saveDebounce: The delay time to accumulate changes to a document before initiating a network sync with
/// available peers. The default is 2 seconds.
/// - maxResolveFetchIterations: The number of checks to make waiting for peers to provide a requested document.
/// The default value is 300, after which the repository throws an error from ``find(id:)`` that indicates the
/// document is unavailable.
/// - resolveFetchIterationDelay: The delay between checks while waiting for peers to provide a requested. The
/// default is 1 second.
public nonisolated init(
sharePolicy: SharePolicy,
storage: some StorageProvider,
saveDebounce: RunLoop.SchedulerTimeType.Stride = .seconds(10)
saveDebounce: RunLoop.SchedulerTimeType.Stride = .seconds(10),
maxResolveFetchIterations: Int = 300,
resolveFetchIterationDelay: Duration = .seconds(1)
) {
peerId = UUID().uuidString
maxRetriesForFetch = maxResolveFetchIterations
pendingRequestWaitDuration = resolveFetchIterationDelay
self.sharePolicy = sharePolicy as any ShareAuthorizing
network = NetworkSubsystem(verbosity: .errorOnly)
self.storage = DocumentStorage(storage, verbosity: .errorOnly)
Expand All @@ -140,14 +167,23 @@ public final class Repo {
/// - networks: A list of network providers to add.
/// - saveDebounce: The delay time to accumulate changes to a document before initiating a network sync with
/// available peers. The default is 2 seconds.
/// - maxResolveFetchIterations: The number of checks to make waiting for peers to provide a requested document.
/// The default value is 300, after which the repository throws an error from ``find(id:)`` that indicates the
/// document is unavailable.
/// - resolveFetchIterationDelay: The delay between checks while waiting for peers to provide a requested
/// document. The default is 1 second.
public init(
sharePolicy: SharePolicy,
storage: some StorageProvider,
networks: [any NetworkProvider],
saveDebounce: RunLoop.SchedulerTimeType.Stride = .seconds(10)
saveDebounce: RunLoop.SchedulerTimeType.Stride = .seconds(10),
maxResolveFetchIterations: Int = 300,
resolveFetchIterationDelay: Duration = .seconds(1)
) {
self.sharePolicy = sharePolicy as any ShareAuthorizing
peerId = UUID().uuidString
maxRetriesForFetch = maxResolveFetchIterations
pendingRequestWaitDuration = resolveFetchIterationDelay
self.storage = DocumentStorage(storage, verbosity: .errorOnly)
self.saveDebounceDelay = saveDebounce

Expand Down

0 comments on commit cf5ccf7

Please sign in to comment.