-
Notifications
You must be signed in to change notification settings - Fork 10
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Upload module improvements #135
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
d25c1f5
Added ExponentialBackoff behavior for retries / fixed cache size vacu…
ArielDemarco 84a0f13
[WIP] modifying retry logic
ArielDemarco 9c08de9
Merge branch 'main' into upload-module-improvements
ArielDemarco 75e3395
Merge branch 'main' into upload-module-improvements
ArielDemarco 76395d5
Added some tests and fixed things that came out while testing (e.g Re…
ArielDemarco afa7cc5
Changes made while testing
ArielDemarco File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -15,22 +15,31 @@ public class EmbraceUpload: EmbraceLogUploader { | |
public private(set) var options: Options | ||
public private(set) var logger: InternalLogger | ||
public private(set) var queue: DispatchQueue | ||
@ThreadSafe | ||
private(set) var isRetryingCache: Bool = false | ||
|
||
private let urlSession: URLSession | ||
let cache: EmbraceUploadCache | ||
let urlSession: URLSession | ||
let operationQueue: OperationQueue | ||
var reachabilityMonitor: EmbraceReachabilityMonitor? | ||
let semaphore: DispatchSemaphore | ||
private var reachabilityMonitor: EmbraceReachabilityMonitor? | ||
|
||
/// Returns an `EmbraceUpload` instance | ||
/// - Parameters: | ||
/// - options: `EmbraceUpload.Options` instance | ||
/// - logger: `EmbraceConsoleLogger` instance | ||
/// - queue: `DispatchQueue` to be used for all upload operations | ||
public init(options: Options, logger: InternalLogger, queue: DispatchQueue) throws { | ||
public init( | ||
options: Options, | ||
logger: InternalLogger, | ||
queue: DispatchQueue, | ||
semaphore: DispatchSemaphore = .init(value: 2) | ||
) throws { | ||
|
||
self.options = options | ||
self.logger = logger | ||
self.queue = queue | ||
self.semaphore = semaphore | ||
|
||
cache = try EmbraceUploadCache(options: options.cache, logger: logger) | ||
|
||
|
@@ -54,25 +63,46 @@ public class EmbraceUpload: EmbraceLogUploader { | |
/// Attempts to upload all the available cached data. | ||
public func retryCachedData() { | ||
queue.async { [weak self] in | ||
guard let self = self else { return } | ||
do { | ||
guard let cachedObjects = try self?.cache.fetchAllUploadData() else { | ||
// in place mechanism to not retry sending cache data at the same time | ||
guard !self.isRetryingCache else { | ||
return | ||
} | ||
|
||
self.isRetryingCache = true | ||
|
||
defer { | ||
// on finishing everything, allow to retry cache (i.e. reconnection) | ||
self.isRetryingCache = false | ||
} | ||
|
||
// clear data from cache that shouldn't be retried as it's stale | ||
self.clearCacheFromStaleData() | ||
|
||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
// get all the data cached first, is the only thing that could throw | ||
let cachedObjects = try self.cache.fetchAllUploadData() | ||
|
||
// create a sempahore to allow only to send two request at a time so we don't | ||
// get throttled by the backend on cases where cache has many failed requests. | ||
|
||
for uploadData in cachedObjects { | ||
guard let type = EmbraceUploadType(rawValue: uploadData.type) else { | ||
continue | ||
} | ||
self.semaphore.wait() | ||
|
||
self?.uploadData( | ||
self.reUploadData( | ||
id: uploadData.id, | ||
data: uploadData.data, | ||
type: type, | ||
attemptCount: uploadData.attemptCount, | ||
completion: nil) | ||
attemptCount: uploadData.attemptCount | ||
) { | ||
self.semaphore.signal() | ||
} | ||
} | ||
} catch { | ||
self?.logger.debug("Error retrying cached upload data: \(error.localizedDescription)") | ||
self.logger.debug("Error retrying cached upload data: \(error.localizedDescription)") | ||
} | ||
} | ||
} | ||
|
@@ -84,7 +114,12 @@ public class EmbraceUpload: EmbraceLogUploader { | |
/// - completion: Completion block called when the data is successfully cached, or when an `Error` occurs | ||
public func uploadSpans(id: String, data: Data, completion: ((Result<(), Error>) -> Void)?) { | ||
queue.async { [weak self] in | ||
self?.uploadData(id: id, data: data, type: .spans, completion: completion) | ||
self?.uploadData( | ||
id: id, | ||
data: data, | ||
type: .spans, | ||
completion: completion | ||
) | ||
} | ||
} | ||
|
||
|
@@ -95,7 +130,12 @@ public class EmbraceUpload: EmbraceLogUploader { | |
/// - completion: Completion block called when the data is successfully cached, or when an `Error` occurs | ||
public func uploadLog(id: String, data: Data, completion: ((Result<(), Error>) -> Void)?) { | ||
queue.async { [weak self] in | ||
self?.uploadData(id: id, data: data, type: .log, completion: completion) | ||
self?.uploadData( | ||
id: id, | ||
data: data, | ||
type: .log, | ||
completion: completion | ||
) | ||
} | ||
} | ||
|
||
|
@@ -105,6 +145,7 @@ public class EmbraceUpload: EmbraceLogUploader { | |
data: Data, | ||
type: EmbraceUploadType, | ||
attemptCount: Int = 0, | ||
retryCount: Int? = nil, | ||
completion: ((Result<(), Error>) -> Void)?) { | ||
|
||
// validate identifier | ||
|
@@ -123,7 +164,7 @@ public class EmbraceUpload: EmbraceLogUploader { | |
let cacheOperation = BlockOperation { [weak self] in | ||
do { | ||
try self?.cache.saveUploadData(id: id, type: type, data: data) | ||
completion?(.success(())) | ||
completion?(.success(())) | ||
} catch { | ||
self?.logger.debug("Error caching upload data: \(error.localizedDescription)") | ||
completion?(.failure(error)) | ||
|
@@ -133,23 +174,23 @@ public class EmbraceUpload: EmbraceLogUploader { | |
// upload operation | ||
let uploadOperation = EmbraceUploadOperation( | ||
urlSession: urlSession, | ||
queue: queue, | ||
metadataOptions: options.metadata, | ||
endpoint: endpoint(for: type), | ||
identifier: id, | ||
data: data, | ||
retryCount: options.redundancy.automaticRetryCount, | ||
retryCount: retryCount ?? options.redundancy.automaticRetryCount, | ||
exponentialBackoffBehavior: options.redundancy.exponentialBackoffBehavior, | ||
attemptCount: attemptCount, | ||
logger: logger) { [weak self] (cancelled, count, error) in | ||
|
||
logger: logger) { [weak self] (result, attemptCount) in | ||
self?.queue.async { [weak self] in | ||
self?.handleOperationFinished( | ||
id: id, | ||
type: type, | ||
cancelled: cancelled, | ||
attemptCount: count, | ||
error: error | ||
result: result, | ||
attemptCount: attemptCount | ||
) | ||
self?.cleanCacheFromStaleData() | ||
self?.clearCacheFromStaleData() | ||
} | ||
} | ||
|
||
|
@@ -159,37 +200,75 @@ public class EmbraceUpload: EmbraceLogUploader { | |
operationQueue.addOperation(uploadOperation) | ||
} | ||
|
||
func reUploadData(id: String, | ||
data: Data, | ||
type: EmbraceUploadType, | ||
attemptCount: Int, | ||
completion: @escaping (() -> Void)) { | ||
let totalPendingRetries = options.redundancy.maximumAmountOfRetries - attemptCount | ||
let retries = min(options.redundancy.automaticRetryCount, totalPendingRetries) | ||
|
||
let uploadOperation = EmbraceUploadOperation( | ||
urlSession: urlSession, | ||
queue: queue, | ||
metadataOptions: options.metadata, | ||
endpoint: endpoint(for: type), | ||
identifier: id, | ||
data: data, | ||
retryCount: retries, | ||
exponentialBackoffBehavior: options.redundancy.exponentialBackoffBehavior, | ||
attemptCount: attemptCount, | ||
logger: logger) { [weak self] (result, attemptCount) in | ||
self?.queue.async { [weak self] in | ||
self?.handleOperationFinished( | ||
id: id, | ||
type: type, | ||
result: result, | ||
attemptCount: attemptCount | ||
) | ||
completion() | ||
} | ||
} | ||
operationQueue.addOperation(uploadOperation) | ||
} | ||
|
||
private func handleOperationFinished( | ||
id: String, | ||
type: EmbraceUploadType, | ||
cancelled: Bool, | ||
attemptCount: Int, | ||
error: Error?) { | ||
|
||
// error? | ||
if cancelled == true || error != nil { | ||
// update attempt count in cache | ||
operationQueue.addOperation { [weak self] in | ||
do { | ||
try self?.cache.updateAttemptCount(id: id, type: type, attemptCount: attemptCount) | ||
} catch { | ||
self?.logger.debug("Error updating cache: \(error.localizedDescription)") | ||
result: EmbraceUploadOperationResult, | ||
attemptCount: Int | ||
) { | ||
switch result { | ||
case .success: | ||
addDeleteUploadDataOperation(id: id, type: type) | ||
case .failure(let isRetriable): | ||
if isRetriable, attemptCount < options.redundancy.maximumAmountOfRetries { | ||
operationQueue.addOperation { [weak self] in | ||
do { | ||
try self?.cache.updateAttemptCount(id: id, type: type, attemptCount: attemptCount) | ||
} catch { | ||
self?.logger.debug("Error updating cache: \(error.localizedDescription)") | ||
} | ||
} | ||
return | ||
} | ||
return | ||
|
||
addDeleteUploadDataOperation(id: id, type: type) | ||
} | ||
} | ||
|
||
// success -> clear cache | ||
private func addDeleteUploadDataOperation(id: String, type: EmbraceUploadType) { | ||
operationQueue.addOperation { [weak self] in | ||
do { | ||
try self?.cache.deleteUploadData(id: id, type: type) | ||
} catch { | ||
self?.logger.debug("Error deleting cache: \(error.localizedDescription)") | ||
} | ||
} | ||
|
||
} | ||
|
||
private func cleanCacheFromStaleData() { | ||
private func clearCacheFromStaleData() { | ||
operationQueue.addOperation { [weak self] in | ||
do { | ||
try self?.cache.clearStaleDataIfNeeded() | ||
|
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
conditional_returns_on_newline
)