From 6d26092419037dc4a49703238dbe53af46b8fb4c Mon Sep 17 00:00:00 2001 From: Yuuki Nishiyama Date: Tue, 24 Nov 2026 00:36:36 -0800 Subject: [PATCH 1/2] Add upload diagnostics, adaptive request size, and request prefetch - SyncDiagnostics: record each request (prepare, connect, send, server, delete, rest, retry wait) using URLSessionTaskMetrics, summarize each sync with its bottleneck, and post Notification.Name.Aware.dbSyncDiagnostics. - SyncBatchLimit: 4 MB default for every server type (the PHP AWARE server is retired; Flask serves its endpoints). After 3 full and fast requests in a row the limit grows by half up to maxBatchBytesCeiling (8 MB by default), like AWAREFetchSizeAdjuster. A limit learned from 413 grows back, but never above 90% of the smallest rejected size. - prefetchNextBatch: choose and build the next request while the current one is in flight. - DbSyncConfig.default* static values let an app set the request size and pacing of every sensor at once. Co-Authored-By: Claude Opus 5.5 --- README.md | 21 +- .../db/core/DbSyncConfig.swift | 32 +- .../db/core/DbSyncHelper.swift | 175 +++++++++- .../db/core/SyncDiagnostics.swift | 311 ++++++++++++++++++ .../db/core/SyncPacing.swift | 127 ++++++- .../util/AwareNotification.swift | 2 + .../DbSyncBatchingTests.swift | 93 +++++- .../com_awareframework_ios_coreTests.swift | 4 +- 8 files changed, 726 insertions(+), 39 deletions(-) create mode 100644 Sources/com.awareframework.ios.core/db/core/SyncDiagnostics.swift diff --git a/README.md b/README.md index b7774c7..3e5c2cb 100644 --- a/README.md +++ b/README.md @@ -324,11 +324,13 @@ Per-table upload settings, used by `DbSyncHelper`. | `serverType: ServerType` | `DbSyncConfig.defaultServerType` (`.aware_micro`) | Server protocol; selects the upload URL (see [Upload URL](#upload-url)). | | `studyNumber: Int` | `DbSyncConfig.defaultStudyNumber` (`1`) | Study number in the upload URL. | | `studyKey: String` | `DbSyncConfig.defaultStudyKey` (`""`) | Study key in the upload URL. | -| `maxBatchBytes: Int?` | `nil` (by server type) | Largest request body in bytes. A request holds as many rows as fit. `nil` chooses 4 MB for AWARE Micro (Google App Engine accepts up to 32 MB) and 900 KB for other servers (below the nginx default of 1 MB). See [Request size](#request-size). Dictionary key: `"maxBatchBytes"`. | -| `maxBatchRows: Int` | `20000` | Largest number of rows per request. Dictionary key: `"maxBatchRows"`. | +| `maxBatchBytes: Int?` | `DbSyncConfig.defaultMaxBatchBytes` (`nil`) | Largest request body in bytes. A request holds as many rows as fit. `nil` is 4 MB for every server type (Google App Engine accepts up to 32 MB; up to 1.7 it was 900 KB for servers other than AWARE Micro). See [Request size](#request-size). Dictionary key: `"maxBatchBytes"`. | +| `maxBatchBytesCeiling: Int?` | `DbSyncConfig.defaultMaxBatchBytesCeiling` (`nil`) | Largest size the limit grows to while requests are full and fast. `nil` is 8 MB. Set it to `maxBatchBytes` to turn growth off. Dictionary key: `"maxBatchBytesCeiling"`. | +| `maxBatchRows: Int` | `DbSyncConfig.defaultMaxBatchRows` (`20000`) | Largest number of rows per request. Dictionary key: `"maxBatchRows"`. | +| `prefetchNextBatch: Bool` | `DbSyncConfig.defaultPrefetchNextBatch` (`true`) | Choose and build the next request while the current one is in flight, so the device and the server work at the same time. Dictionary key: `"prefetchNextBatch"`. | | `batchSize: Int` | `1000` | Rows read from the database at a time while a request is built. (Up to 1.6 it was the number of rows per request; requests are now sized by `maxBatchBytes`.) | | `batchInterval: TimeInterval` | `0` | Shortest rest between requests, in seconds. 1.6 always waited 0.1 s; set `0.1` for that behaviour. | -| `cpuRestRatio: Double` | `1` | Rest between requests as a multiple of the CPU time the last request took to prepare (reading rows, building the body, deleting uploaded rows), while the app is in the foreground. `1` keeps a sync at about half of one CPU core. See [Pacing](#pacing). | +| `cpuRestRatio: Double` | `DbSyncConfig.defaultCpuRestRatio` (`1`) | Rest between requests as a multiple of the CPU time the last request took to prepare (reading rows, building the body, deleting uploaded rows), while the app is in the foreground. `1` keeps a sync at about half of one CPU core. See [Pacing](#pacing). | | `backgroundCpuRestRatio: Double` | `3` | The same while the app is in the background, where iOS may stop an app that keeps the CPU busy. | | `removeAfterSync: Bool` | `true` | Delete uploaded rows from the local database once they are older than `keepDataAfterSync`. Rows that have not been uploaded are never deleted. Set `false` to keep every row. | | `keepDataAfterSync: TimeInterval` | `86400` (one day) | Seconds to keep uploaded rows on the device, counted from each row's `timestamp`. `0` deletes them right after upload. Negative values are ignored. Dictionary key: `"keepDataAfterSync"`. | @@ -348,6 +350,8 @@ Per-table upload settings, used by `DbSyncHelper`. All settings can also be given as a dictionary with `DbSyncConfig(_:)` or `set(config:)`, e.g. `["batchSize": 500, "studyKey": "my-study-key"]`. +The `DbSyncConfig.default…` static properties set the values of configs created afterwards, so an app can change the request size and pacing of every sensor at once (sensors create their configs themselves). Set them before the sensors are created, or also set the properties of `sensor.syncConfig`. + --- ## Sync Guarantees @@ -369,8 +373,9 @@ Each request holds as many rows as fit in the size limit, in the form the server | Situation | What the sync does | |---|---| -| Default | `maxBatchBytes`, or 4 MB (AWARE Micro) / 900 KB (other servers) | -| The server answers 413 | Half of the rejected size becomes the host's limit, saved in `UserDefaults` (`aware.sync.max_batch_bytes.`), and the same rows are sent again right away. A server with nginx's default 1 MB limit costs two rejected requests once (4 MB, 2 MB), then every request fits. | +| Default | `maxBatchBytes`, or 4 MB, for every server type (the PHP version of the AWARE server is retired; its endpoints are served by Flask) | +| Requests are full and fast | After 3 requests in a row that filled at least 80 % of the limit and finished within 10 s, the limit grows by half, up to `maxBatchBytesCeiling` (8 MB by default), and is saved (`aware.sync.grown_batch_bytes.`). Like `AWAREFetchSizeAdjuster` of AWAREFramework-iOS 1.x. | +| The server answers 413 | Half of the rejected size becomes the host's limit, saved in `UserDefaults` (`aware.sync.max_batch_bytes.`), and the same rows are sent again right away. A server with nginx's default 1 MB limit costs two rejected requests once (4 MB, 2 MB), then every request fits. The limit grows back by the rule above, but never above 90 % of the smallest size the host rejected (`aware.sync.rejected_batch_bytes.`). | | A request times out | The limit is halved for this run of the app and the rows are sent again; after 20 successful requests in a row it grows back by half, up to the default. | | 429 or 503 | Wait for `Retry-After` (or 5, 10, 20 s, at most 120 s) and send again, up to 3 times. | @@ -378,10 +383,16 @@ Each request holds as many rows as fit in the size limit, in the form the server With `SQLiteEngine`, each row is written as JSON straight from the values SQLite returns (`Engine.fetchUploadJSON(afterId:limit:omitting:)`), without making a dictionary for the row first. The values are the same as before: NULL columns are left out, and a REAL is written with the shortest text that reads back as the same Double, so no precision is lost. (SQLite's own `json_object()` is not used: it keeps only 15 significant digits, so a millisecond timestamp stored as REAL would lose its last digits.) A row JSON cannot hold (a BLOB, or infinity or NaN) goes through the general builder as before. A `DbSyncHelper` subclass that overrides `getUploadCandidates(lastUploadedId:limit:)` to change the rows must also override `getUploadCandidateJSON(lastUploadedId:limit:)` (returning `nil` is enough). +### Diagnostics + +`SyncDiagnostics.shared` tells why an upload is slow. For each request it records (`SyncBatchMetrics`) the rows and bytes, the time to read rows and build the body (`prepare`), the network time split by `URLSessionTaskMetrics` into connecting, sending the body and waiting for the server (`server`), the time to delete uploaded rows, and the rest or retry wait that followed. When the sync of a table ends, it makes a `SyncRunSummary` with the share of each part and the largest one (`bottleneck`), keeps it (`latestSummaries()`), and posts `Notification.Name.Aware.dbSyncDiagnostics`. `report()` gives a text report. With `debug`, each request and summary is also logged; `SyncDiagnostics.shared.printsToConsole = true` logs them without `debug`. + ### Pacing All sync work (reading rows, building requests, the URLSession callbacks, deleting uploaded rows) runs on a serial queue per table, never on the main thread, so a sync does not freeze the UI. Completion and progress handlers are still called on the main thread. +With `prefetchNextBatch`, the next request is chosen and built while the current one is in flight, on the same serial queue. It is used only when it starts right after the rows the server accepted and was chosen with the same size limit; otherwise (a 413, a timeout, a failure) it is discarded and chosen again. + Between requests the sync rests for `cpuRestRatio` (foreground) or `backgroundCpuRestRatio` (background) times the CPU time the last request took to prepare. Waiting for the server is not counted, so on a slow network the sync does not wait longer than needed, and on a fast network it leaves the CPU idle at least half of the time (three quarters in the background). The work also runs with a lower priority in the background (`.background` instead of `.utility`). The rest is doubled in Low Power Mode, at least 5 s when the device is hot (`thermalState` serious) and 30 s when critical, and at most 120 s. ### Removing uploaded rows diff --git a/Sources/com.awareframework.ios.core/db/core/DbSyncConfig.swift b/Sources/com.awareframework.ios.core/db/core/DbSyncConfig.swift index e9b7009..b56911a 100644 --- a/Sources/com.awareframework.ios.core/db/core/DbSyncConfig.swift +++ b/Sources/com.awareframework.ios.core/db/core/DbSyncConfig.swift @@ -10,10 +10,14 @@ /// - batchSize: Rows read from the database at a time while a request is built. Default is `1000`. /// (Up to 1.6, it was the number of rows per request. A request now holds as many rows as fit /// in `maxBatchBytes`, up to `maxBatchRows`.) -/// - maxBatchBytes: Largest request body in bytes. `nil` (default) chooses by server type: 4 MB for -/// AWARE Micro (Google App Engine accepts 32 MB), 900 KB for other servers (below the nginx default -/// of 1 MB). A host that answers 413 gets a smaller limit, which is remembered. See `SyncBatchLimit`. +/// - maxBatchBytes: Largest request body in bytes. `nil` (default) is 4 MB for every server type +/// (up to 1.7: 900 KB for servers other than AWARE Micro). A host that answers 413 gets a smaller +/// limit, which is remembered. See `SyncBatchLimit`. +/// - maxBatchBytesCeiling: Largest size `maxBatchBytes` may grow to after requests in a row that were +/// full and fast (see `SyncBatchLimit`). `nil` (default): 8 MB for every server type. /// - maxBatchRows: Largest number of rows per request. Default is `20000`. +/// - prefetchNextBatch: Choose and build the next request while the current one is in flight, so the +/// server and the device work at the same time. Default is `true`. /// - batchInterval: Shortest rest between requests, in seconds. Default is `0`. (1.6 waited 0.1 s.) /// - cpuRestRatio: Rest between requests, as a multiple of the CPU time the last request took to /// prepare, while the app is in the foreground. Default is `1` (the sync uses at most about half @@ -78,6 +82,12 @@ public class DbSyncConfig { public static var defaultStudyNumber: Int = 1 public static var defaultStudyKey: String = "" public static var defaultCompactDataFormat: Bool = false + /// App-wide defaults for new configs (sensors create their configs themselves) + public static var defaultMaxBatchBytes: Int? = nil + public static var defaultMaxBatchBytesCeiling: Int? = nil + public static var defaultMaxBatchRows: Int = 20000 + public static var defaultCpuRestRatio: Double = 1 + public static var defaultPrefetchNextBatch: Bool = true public var removeAfterSync: Bool = true @@ -120,10 +130,12 @@ public class DbSyncConfig { set { if let period = newValue { keepDataAfterSync = period.seconds } } } public var batchSize: Int = 1000 - public var maxBatchBytes: Int? = nil - public var maxBatchRows: Int = 20000 + public var maxBatchBytes: Int? = DbSyncConfig.defaultMaxBatchBytes + public var maxBatchBytesCeiling: Int? = DbSyncConfig.defaultMaxBatchBytesCeiling + public var maxBatchRows: Int = DbSyncConfig.defaultMaxBatchRows + public var prefetchNextBatch: Bool = DbSyncConfig.defaultPrefetchNextBatch public var batchInterval: TimeInterval = 0 - public var cpuRestRatio: Double = 1 + public var cpuRestRatio: Double = DbSyncConfig.defaultCpuRestRatio public var backgroundCpuRestRatio: Double = 3 public var markAsSynced: Bool = false public var skipSyncedData: Bool = false @@ -160,7 +172,9 @@ public class DbSyncConfig { c.keepDataAfterSync = keepDataAfterSync c.batchSize = batchSize c.maxBatchBytes = maxBatchBytes + c.maxBatchBytesCeiling = maxBatchBytesCeiling c.maxBatchRows = maxBatchRows + c.prefetchNextBatch = prefetchNextBatch c.batchInterval = batchInterval c.cpuRestRatio = cpuRestRatio c.backgroundCpuRestRatio = backgroundCpuRestRatio @@ -203,9 +217,15 @@ public class DbSyncConfig { if let bytes = config["maxBatchBytes"] as? Int { self.maxBatchBytes = bytes } + if let bytes = config["maxBatchBytesCeiling"] as? Int { + self.maxBatchBytesCeiling = bytes + } if let rows = config["maxBatchRows"] as? Int { self.maxBatchRows = rows } + if let prefetch = config["prefetchNextBatch"] as? Bool { + self.prefetchNextBatch = prefetch + } if let interval = config["batchInterval"] as? Double { self.batchInterval = interval } else if let interval = config["batchInterval"] as? Int { diff --git a/Sources/com.awareframework.ios.core/db/core/DbSyncHelper.swift b/Sources/com.awareframework.ios.core/db/core/DbSyncHelper.swift index 32723f2..5143450 100644 --- a/Sources/com.awareframework.ios.core/db/core/DbSyncHelper.swift +++ b/Sources/com.awareframework.ios.core/db/core/DbSyncHelper.swift @@ -292,6 +292,35 @@ open class DbSyncHelper: NSObject { /// Host key for the learned request size limit private var limitHost: String { AwareUtils.cleanHostName(host) } + // MARK: Diagnostics (SyncDiagnostics) + + /// Times of the running sync, summarized when it ends + private lazy var recorder = SyncRunRecorder(table: tableName, host: limitHost) + /// Preparation time of the request in flight, and whether it was prefetched + private var currentPrepareSeconds: TimeInterval = 0 + private var currentPrefetched = false + /// The size limit the request in flight was chosen with + private var currentLimitBytes = 0 + /// When the request in flight was sent + private var requestStartedAt: Date? + /// Parts of the request in flight, from URLSessionTaskMetrics + private var currentTimings: (connect: TimeInterval?, upload: TimeInterval?, server: TimeInterval?, + download: TimeInterval?)? + private var currentDeleteSeconds: TimeInterval = 0 + /// The finished request, recorded once the rest before the next one is known + private var pendingMetrics: SyncBatchMetrics? + + // MARK: Prefetch (DbSyncConfig.prefetchNextBatch) + + /// The next request, chosen and built while the current one was in flight + private struct Prefetch { + let afterId: Int64 + let limit: Int + let batch: Batch + let seconds: TimeInterval + } + private var prefetched: Prefetch? + /// Run `work` on the sync queue, with a lower priority while the app is in the background private func onSyncQueue(after delay: TimeInterval = 0, _ work: @escaping () -> Void) { let item = DispatchWorkItem(qos: SyncAppState.shared.workQoS, flags: .enforceQoS, block: work) @@ -656,10 +685,27 @@ open class DbSyncHelper: NSObject { } } - // Choose the rows of this request: as many as fit in the size limit (on the sync queue) - let started = Date() - let batch = selectBatch() - batchWorkSeconds = Date().timeIntervalSince(started) + if recorder.startedAt == nil { recorder.startedAt = Date() } + + // Choose the rows of this request: as many as fit in the size limit (on the sync queue). + // A request prefetched while the previous one was in flight is used when it starts right + // after the uploaded rows and was chosen with the same limit. + let limit = SyncBatchLimit.current(host: limitHost, config: config) + let batch: Batch + if let p = prefetched, p.afterId == lastUploadedId, p.limit == limit { + batch = p.batch + batchWorkSeconds = 0 + currentPrepareSeconds = p.seconds + currentPrefetched = true + } else { + let started = Date() + batch = selectBatch(afterId: lastUploadedId, limit: limit) + batchWorkSeconds = Date().timeIntervalSince(started) + currentPrepareSeconds = batchWorkSeconds + currentPrefetched = false + } + prefetched = nil + currentLimitBytes = limit if config.debug { logVerbose( @@ -694,8 +740,7 @@ open class DbSyncHelper: NSObject { /// /// With `compactDataFormat` or `createHttpRequestBodyHandler` the body is not the sum of its rows, /// so it is built with `buildRequestBody(from:)` and rows are removed until it fits. - private func selectBatch() -> Batch { - let limit = SyncBatchLimit.current(host: limitHost, config: config) + private func selectBatch(afterId start: Int64, limit: Int) -> Batch { let maxRows = max(1, config.maxBatchRows) let chunk = max(1, min(config.batchSize, maxRows)) let form = !usesNewAwareServerEndpoint @@ -711,7 +756,7 @@ open class DbSyncHelper: NSObject { // Size with no rows: the envelope with an empty data array (see assembleBody) total = form ? formEnvelopeLength() : jsonEnvelope().utf8.count + ",\"data\":[]".utf8.count } - var afterId = lastUploadedId + var afterId = start var more = true var invalid = false @@ -777,7 +822,7 @@ open class DbSyncHelper: NSObject { } if invalid { // Read the same rows again as dictionaries for buildRequestBody - rows = getUploadCandidates(lastUploadedId: lastUploadedId, limit: min(chunk, maxRows)) + rows = getUploadCandidates(lastUploadedId: start, limit: min(chunk, maxRows)) more = true } // Build with the general builder, and remove rows until the body fits @@ -1089,6 +1134,9 @@ open class DbSyncHelper: NSObject { */ private func handleSyncCompletion(success: Bool, error: Error?) { guard isStopRequested == false else { return } + prefetched = nil + recordPendingMetrics(rest: 0) + emitSummary(success: success) // Set final state if success { syncState = .completed @@ -1138,6 +1186,7 @@ open class DbSyncHelper: NSObject { if config.debug { logVerbose(String(format: "Next batch in %.3f s (work %.3f s)", rest, batchWorkSeconds)) } + recordPendingMetrics(rest: rest) onSyncQueue(after: rest) { [weak self] in guard self?.isStopRequested == false else { return } // Calculate and report progress @@ -1216,6 +1265,7 @@ open class DbSyncHelper: NSObject { // If data is empty, process as sync completed if count == 0 { syncState = .completed + emitSummary(success: true) if self.config.debug { logInfo("A sync process is done: No Data") } @@ -1253,8 +1303,13 @@ open class DbSyncHelper: NSObject { // Build HTTP request body (unless it was built while choosing the rows) let started = Date() let requestBody = try prebuiltBody ?? buildRequestBody(from: rows ?? []) - batchWorkSeconds += Date().timeIntervalSince(started) + let buildSeconds = Date().timeIntervalSince(started) + batchWorkSeconds += buildSeconds + if !currentPrefetched { currentPrepareSeconds += buildSeconds } currentBodyBytes = requestBody.utf8.count + requestStartedAt = Date() + currentTimings = nil + currentDeleteSeconds = 0 // Build HTTP request if let request = buildHTTPRequest(with: requestBody) { @@ -1263,6 +1318,7 @@ open class DbSyncHelper: NSObject { // Test mode should not leave synthetic URLSession tasks behind. // A suspended task is later returned by getAllTasks() and can be // cancelled as a real network failure during the next batch. + schedulePrefetch(after: lastId, isLast: isLast) handleSuccessfulUploadCompletion() return } @@ -1286,6 +1342,9 @@ open class DbSyncHelper: NSObject { // Send actual HTTP request task.resume() stopLock.unlock() + + // Prepare the next request while this one is in flight + schedulePrefetch(after: lastId, isLast: isLast) } } catch { // Handle JSON serialization error @@ -1294,6 +1353,8 @@ open class DbSyncHelper: NSObject { } // Stop sync on error and call callback syncState = .failed(error) + prefetched = nil + emitSummary(success: false) if let callback = self.completion { DispatchQueue.main.async { [weak self] in guard self?.isStopRequested == false else { return } @@ -1323,11 +1384,14 @@ open class DbSyncHelper: NSObject { } if config.removeAfterSync { + let started = Date() removeUploadedCandidates(lastUploadedId: lastUploadedId, limit: config.batchSize) + currentDeleteSeconds = Date().timeIntervalSince(started) } updateLastUploadedId() receivedData = Data() + pendingMetrics = makeMetrics(success: true) handleUploadCompletion(responseState: true, error: nil) } @@ -1528,6 +1592,9 @@ open class DbSyncHelper: NSObject { if !responseState, let delay = retryDelayAfterFailure(error: error) { invalidateSession(waitForTasks: false) receivedData = Data() + prefetched = nil + pendingMetrics = makeMetrics(success: false) + recordPendingMetrics(rest: delay, isRetryWait: true) onSyncQueue(after: delay) { [weak self] in self?.performDataSync() } @@ -1535,7 +1602,11 @@ open class DbSyncHelper: NSObject { } if responseState { adjustRetries = 0 - SyncBatchLimit.recordSuccess(host: limitHost) + let networkSeconds = requestStartedAt.map { Date().timeIntervalSince($0) } ?? 0 + if let grown = SyncBatchLimit.recordSuccess(host: limitHost, bodyBytes: currentBodyBytes, + networkSeconds: networkSeconds, config: config) { + logInfo("Requests are full and fast; the size limit grows to \(grown) bytes") + } } // Debug output of server response @@ -1565,7 +1636,8 @@ open class DbSyncHelper: NSObject { if config.removeAfterSync { let started = Date() removeUploadedCandidates(lastUploadedId: lastUploadedId, limit: config.batchSize) - batchWorkSeconds += Date().timeIntervalSince(started) + currentDeleteSeconds = Date().timeIntervalSince(started) + batchWorkSeconds += currentDeleteSeconds } // Finally update uploaded ID @@ -1578,10 +1650,91 @@ open class DbSyncHelper: NSObject { // Clear received data buffer receivedData = Data() + pendingMetrics = makeMetrics(success: responseState) + // Execute subsequent processing handleUploadCompletion(responseState: responseState, error: error) } + /// Timings of the connection, the body, the server and the response (called before + /// `didCompleteWithError`) + open func urlSession( + _ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics + ) { + guard let t = metrics.transactionMetrics.last else { return } + func span(_ a: Date?, _ b: Date?) -> TimeInterval? { + guard let a, let b else { return nil } + return max(0, b.timeIntervalSince(a)) + } + // A reused connection has no connect dates: nothing was spent on connecting + let connect = t.isReusedConnection ? 0 : (span(t.fetchStartDate, t.connectEndDate) ?? 0) + currentTimings = (connect, span(t.requestStartDate, t.requestEndDate), + span(t.requestEndDate, t.responseStartDate), + span(t.responseStartDate, t.responseEndDate)) + } + + // MARK: - Diagnostics and prefetch + + /// The metrics of the request that just ended + private func makeMetrics(success: Bool) -> SyncBatchMetrics { + let processInfo = ProcessInfo.processInfo + return SyncBatchMetrics( + table: tableName, host: limitHost, date: Date(), rows: currentNumOfCandidates, + bodyBytes: currentBodyBytes, limitBytes: currentLimitBytes, + prepareSeconds: currentPrepareSeconds, prefetched: currentPrefetched, + networkSeconds: config.test ? 0 : (requestStartedAt.map { Date().timeIntervalSince($0) } ?? 0), + connectSeconds: currentTimings?.connect, uploadSeconds: currentTimings?.upload, + serverSeconds: currentTimings?.server, downloadSeconds: currentTimings?.download, + deleteSeconds: currentDeleteSeconds, restSeconds: 0, statusCode: lastStatusCode, + success: success, background: SyncAppState.shared.isInBackground, + lowPower: processInfo.isLowPowerModeEnabled, thermalState: processInfo.thermalState) + } + + /// Record the request that ended, with the rest (or retry wait) that follows it + private func recordPendingMetrics(rest: TimeInterval, isRetryWait: Bool = false) { + guard let m = pendingMetrics else { return } + pendingMetrics = nil + let metrics = SyncBatchMetrics( + table: m.table, host: m.host, date: m.date, rows: m.rows, bodyBytes: m.bodyBytes, + limitBytes: m.limitBytes, prepareSeconds: m.prepareSeconds, prefetched: m.prefetched, + networkSeconds: m.networkSeconds, connectSeconds: m.connectSeconds, + uploadSeconds: m.uploadSeconds, serverSeconds: m.serverSeconds, + downloadSeconds: m.downloadSeconds, deleteSeconds: m.deleteSeconds, restSeconds: rest, + statusCode: m.statusCode, success: m.success, background: m.background, + lowPower: m.lowPower, thermalState: m.thermalState) + recorder.add(metrics, isRetryWait: isRetryWait) + SyncDiagnostics.shared.record(metrics) + logInfo("Request: \(metrics)") + } + + /// Publish the summary of the sync that ended and start a new one + private func emitSummary(success: Bool) { + if let summary = recorder.summary(success: success) { + SyncDiagnostics.shared.record(summary) + logInfo("Summary: \(summary)") + } + recorder = SyncRunRecorder(table: tableName, host: limitHost) + } + + /// Choose and build the request after the rows ending with `lastId` on the sync queue, so it is + /// ready when the current request ends. The sync queue is serial, so this runs before the + /// response of the current request is handled. + private func schedulePrefetch(after lastId: Int64?, isLast: Bool) { + guard config.prefetchNextBatch, !isLast, let afterId = lastId, currentLimitBytes > 0 else { return } + let limit = currentLimitBytes + onSyncQueue { [weak self] in + guard let self, self.isStopRequested == false, self.prefetched == nil else { return } + let started = Date() + var batch = self.selectBatch(afterId: afterId, limit: limit) + guard batch.count > 0 else { return } + if batch.body == nil, let rows = batch.rows { + batch.body = try? self.buildRequestBody(from: rows) + } + self.prefetched = Prefetch(afterId: afterId, limit: limit, batch: batch, + seconds: Date().timeIntervalSince(started)) + } + } + /// Whether to send the batch again after a failure, and after how long. /// /// - 413: the host's size limit becomes half of the rejected body (`SyncBatchLimit`, remembered), diff --git a/Sources/com.awareframework.ios.core/db/core/SyncDiagnostics.swift b/Sources/com.awareframework.ios.core/db/core/SyncDiagnostics.swift new file mode 100644 index 0000000..18735e0 --- /dev/null +++ b/Sources/com.awareframework.ios.core/db/core/SyncDiagnostics.swift @@ -0,0 +1,311 @@ +// +// SyncDiagnostics.swift +// com.awareframework.ios.core +// +// Where the time of an upload goes, to tell why a sync is slow: reading rows and building the +// request on the device, opening the connection, sending the body, the server's processing, +// deleting uploaded rows, the rest between requests (SyncPacing), and waits before retries. +// +// Like the timing logs of AWAREFramework-iOS 1.x (`[sensor] SQLite ---> seconds`), but kept as +// values: `SyncDiagnostics.shared` holds the last requests and the summary of the last sync of each +// table, and `Notification.Name.Aware.dbSyncDiagnostics` is posted when a sync ends. +// + +import Foundation + +/// One request of a sync. +public struct SyncBatchMetrics: CustomStringConvertible { + public let table: String + public let host: String + public let date: Date + public let rows: Int + public let bodyBytes: Int + /// The size limit the request was chosen with (`SyncBatchLimit`) + public let limitBytes: Int + /// Reading rows and building the body (CPU and database) + public let prepareSeconds: TimeInterval + /// Whether the request was prepared while the previous one was in flight (`prefetchNextBatch`); + /// its preparation then did not delay the sync + public let prefetched: Bool + /// From sending the request to its end (connection, body, server, response) + public let networkSeconds: TimeInterval + /// Parts of `networkSeconds` from `URLSessionTaskMetrics` (nil when not reported) + public let connectSeconds: TimeInterval? + public let uploadSeconds: TimeInterval? + public let serverSeconds: TimeInterval? + public let downloadSeconds: TimeInterval? + /// Deleting uploaded rows + public let deleteSeconds: TimeInterval + /// Rest before the next request (SyncPacing), or wait before a retry + public let restSeconds: TimeInterval + public let statusCode: Int? + public let success: Bool + public let background: Bool + public let lowPower: Bool + public let thermalState: ProcessInfo.ThermalState + + /// Body bytes per second while the body was sent + public var uploadBytesPerSecond: Double? { + guard let s = uploadSeconds, s > 0 else { return nil } + return Double(bodyBytes) / s + } + + public var description: String { + var parts = [ + "\(rows) rows", SyncDiagnostics.bytes(bodyBytes) + "/" + SyncDiagnostics.bytes(limitBytes), + "prepare " + SyncDiagnostics.seconds(prepareSeconds) + (prefetched ? " (overlapped)" : ""), + "network " + SyncDiagnostics.seconds(networkSeconds), + ] + if let c = connectSeconds { parts.append("connect " + SyncDiagnostics.seconds(c)) } + if let u = uploadSeconds { parts.append("send " + SyncDiagnostics.seconds(u)) } + if let s = serverSeconds { parts.append("server " + SyncDiagnostics.seconds(s)) } + if let r = uploadBytesPerSecond { parts.append(SyncDiagnostics.bytes(Int(r)) + "/s") } + parts.append("delete " + SyncDiagnostics.seconds(deleteSeconds)) + parts.append("rest " + SyncDiagnostics.seconds(restSeconds)) + parts.append(success ? "OK" : "FAILED(\(statusCode.map(String.init) ?? "-"))") + if background { parts.append("background") } + if lowPower { parts.append("low power") } + if thermalState == .serious || thermalState == .critical { parts.append("hot") } + return parts.joined(separator: ", ") + } +} + +/// Where the time of a sync went. +public enum SyncBottleneck: String, CaseIterable { + case preparation = "device: reading rows and building requests" + case connection = "network: opening connections" + case upload = "network: sending data (bandwidth)" + case server = "server: processing requests" + case network = "network or server (no detailed timing)" + case deletion = "device: deleting uploaded rows" + case pacing = "rest between requests (background, Low Power Mode, heat or cpuRestRatio)" + case retries = "retries (413, timeouts, 429/503)" + case unknown = "unknown" +} + +/// The summary of one sync of one table. +public struct SyncRunSummary: CustomStringConvertible { + public let table: String + public let host: String + public let startedAt: Date + public let endedAt: Date + public let success: Bool + public let batches: Int + public let failedRequests: Int + public let rows: Int + public let bytes: Int + /// Preparation that delayed the sync (prefetched preparation overlaps the network and is left out) + public let prepareSeconds: TimeInterval + public let overlappedPrepareSeconds: TimeInterval + public let networkSeconds: TimeInterval + public let connectSeconds: TimeInterval + public let uploadSeconds: TimeInterval + public let serverSeconds: TimeInterval + public let deleteSeconds: TimeInterval + public let restSeconds: TimeInterval + public let retryWaitSeconds: TimeInterval + public let lastLimitBytes: Int + public let backgroundBatches: Int + + public var elapsedSeconds: TimeInterval { max(0, endedAt.timeIntervalSince(startedAt)) } + public var rowsPerSecond: Double { elapsedSeconds > 0 ? Double(rows) / elapsedSeconds : 0 } + public var bytesPerSecond: Double { elapsedSeconds > 0 ? Double(bytes) / elapsedSeconds : 0 } + /// Time not covered by the measured parts (queue hops, waiting for the database lock, ...) + public var otherSeconds: TimeInterval { + max(0, elapsedSeconds - prepareSeconds - networkSeconds - deleteSeconds - restSeconds - retryWaitSeconds) + } + + /// The share of the elapsed time of each part, largest first. + public var breakdown: [(SyncBottleneck, Double)] { + let total = max(elapsedSeconds, 1e-9) + var parts: [(SyncBottleneck, TimeInterval)] = [ + (.preparation, prepareSeconds), (.deletion, deleteSeconds), + (.pacing, restSeconds), (.retries, retryWaitSeconds), + ] + let detailed = connectSeconds + uploadSeconds + serverSeconds + if detailed > 0 { + parts += [(.connection, connectSeconds), (.upload, uploadSeconds), + (.server, serverSeconds + max(0, networkSeconds - detailed))] + } else { + parts.append((.network, networkSeconds)) + } + return parts.map { ($0.0, $0.1 / total) }.sorted { $0.1 > $1.1 } + } + + /// The part that took the most time. + public var bottleneck: SyncBottleneck { + guard let top = breakdown.first, top.1 > 0 else { return .unknown } + return top.0 + } + + public var description: String { + let shares = breakdown.filter { $0.1 >= 0.01 } + .map { "\($0.0.shortName) \(Int(($0.1 * 100).rounded()))%" }.joined(separator: ", ") + return "[\(table)] \(success ? "done" : "failed"): \(rows) rows, \(SyncDiagnostics.bytes(bytes)) " + + "in \(SyncDiagnostics.seconds(elapsedSeconds)) (\(batches) requests, " + + "\(SyncDiagnostics.bytes(Int(bytesPerSecond)))/s, \(Int(rowsPerSecond)) rows/s, " + + "limit \(SyncDiagnostics.bytes(lastLimitBytes)))" + + (failedRequests > 0 ? ", \(failedRequests) failed requests" : "") + + (backgroundBatches > 0 ? ", \(backgroundBatches) in background" : "") + + " | \(shares)" + + (overlappedPrepareSeconds > 0 ? " | overlapped prepare \(SyncDiagnostics.seconds(overlappedPrepareSeconds))" : "") + + " | bottleneck: \(bottleneck.rawValue)" + } +} + +extension SyncBottleneck { + public var shortName: String { + switch self { + case .preparation: return "prepare" + case .connection: return "connect" + case .upload: return "send" + case .server: return "server" + case .network: return "network" + case .deletion: return "delete" + case .pacing: return "rest" + case .retries: return "retry" + case .unknown: return "other" + } + } +} + +/// Collects `SyncBatchMetrics` of a running sync and makes its `SyncRunSummary`. +struct SyncRunRecorder { + let table: String + let host: String + var startedAt: Date? + var batches = 0 + var failedRequests = 0 + var rows = 0 + var bytes = 0 + var prepare: TimeInterval = 0 + var overlappedPrepare: TimeInterval = 0 + var network: TimeInterval = 0 + var connect: TimeInterval = 0 + var upload: TimeInterval = 0 + var server: TimeInterval = 0 + var delete: TimeInterval = 0 + var rest: TimeInterval = 0 + var retryWait: TimeInterval = 0 + var lastLimit = 0 + var backgroundBatches = 0 + + init(table: String, host: String) { + self.table = table + self.host = host + } + + mutating func add(_ m: SyncBatchMetrics, isRetryWait: Bool) { + if m.success { + batches += 1 + rows += m.rows + bytes += m.bodyBytes + } else { + failedRequests += 1 + } + if m.prefetched { overlappedPrepare += m.prepareSeconds } else { prepare += m.prepareSeconds } + network += m.networkSeconds + connect += m.connectSeconds ?? 0 + upload += m.uploadSeconds ?? 0 + server += m.serverSeconds ?? 0 + delete += m.deleteSeconds + if isRetryWait { retryWait += m.restSeconds } else { rest += m.restSeconds } + lastLimit = m.limitBytes + if m.background { backgroundBatches += 1 } + } + + func summary(success: Bool, endedAt: Date = Date()) -> SyncRunSummary? { + guard let startedAt, batches + failedRequests > 0 else { return nil } + return SyncRunSummary( + table: table, host: host, startedAt: startedAt, endedAt: endedAt, success: success, + batches: batches, failedRequests: failedRequests, rows: rows, bytes: bytes, + prepareSeconds: prepare, overlappedPrepareSeconds: overlappedPrepare, networkSeconds: network, + connectSeconds: connect, uploadSeconds: upload, serverSeconds: server, deleteSeconds: delete, + restSeconds: rest, retryWaitSeconds: retryWait, lastLimitBytes: lastLimit, + backgroundBatches: backgroundBatches) + } +} + +/// The last requests and the summary of the last sync of each table, readable from any thread. +public final class SyncDiagnostics { + + public static let shared = SyncDiagnostics() + + /// Requests kept (all tables together) + public var maxBatches = 300 + /// Print each request and each summary, even when `DbSyncConfig.debug` is off + public var printsToConsole = false + + private let lock = NSLock() + private var batches: [SyncBatchMetrics] = [] + private var summaries: [String: SyncRunSummary] = [:] + + private init() {} + + func record(_ batch: SyncBatchMetrics) { + lock.lock() + batches.append(batch) + if batches.count > maxBatches { batches.removeFirst(batches.count - maxBatches) } + let printing = printsToConsole + lock.unlock() + if printing { print("[AWARE::Core][SyncDiagnostics][\(batch.table)] \(batch)") } + } + + func record(_ summary: SyncRunSummary) { + lock.lock() + summaries[summary.table] = summary + let printing = printsToConsole + lock.unlock() + if printing { print("[AWARE::Core][SyncDiagnostics] \(summary)") } + NotificationCenter.default.post(name: Notification.Name.Aware.dbSyncDiagnostics, object: summary) + } + + /// The summary of the last sync of each table, newest first. + public func latestSummaries() -> [SyncRunSummary] { + lock.lock() + defer { lock.unlock() } + return summaries.values.sorted { $0.endedAt > $1.endedAt } + } + + public func latestSummary(table: String) -> SyncRunSummary? { + lock.lock() + defer { lock.unlock() } + return summaries[table] + } + + /// The last requests, oldest first (of one table, or of all tables). + public func recentBatches(table: String? = nil) -> [SyncBatchMetrics] { + lock.lock() + defer { lock.unlock() } + guard let table else { return batches } + return batches.filter { $0.table == table } + } + + /// A text report of the last syncs, for logs or for sharing. + public func report() -> String { + let list = latestSummaries() + guard list.isEmpty == false else { return "No upload has been measured yet." } + let total = list.reduce(into: [SyncBottleneck: TimeInterval]()) { result, s in + for (part, share) in s.breakdown { result[part, default: 0] += share * s.elapsedSeconds } + } + let overall = total.max { $0.value < $1.value }?.key ?? .unknown + return (["Overall bottleneck: \(overall.rawValue)"] + list.map(\.description)).joined(separator: "\n") + } + + public func reset() { + lock.lock() + batches = [] + summaries = [:] + lock.unlock() + } + + static func seconds(_ s: TimeInterval) -> String { + s < 1 ? String(format: "%.0f ms", s * 1000) : String(format: "%.1f s", s) + } + + static func bytes(_ b: Int) -> String { + if b >= 1_000_000 { return String(format: "%.1f MB", Double(b) / 1_000_000) } + if b >= 1_000 { return String(format: "%.0f KB", Double(b) / 1_000) } + return "\(b) B" + } +} diff --git a/Sources/com.awareframework.ios.core/db/core/SyncPacing.swift b/Sources/com.awareframework.ios.core/db/core/SyncPacing.swift index b717a21..ab293e9 100644 --- a/Sources/com.awareframework.ios.core/db/core/SyncPacing.swift +++ b/Sources/com.awareframework.ios.core/db/core/SyncPacing.swift @@ -111,39 +111,78 @@ enum SyncPacing { /// The largest request body a sync sends to a host. /// -/// - Default: `DbSyncConfig.maxBatchBytes`, or by server type when it is not set: 4 MB for AWARE Micro -/// (Google App Engine accepts up to 32 MB; the margin keeps uploads short on slow networks and -/// keeps memory use low), 900 KB for other servers (below the nginx default of 1 MB and the PHP -/// default `post_max_size` of 8 MB, which drops larger bodies without an error). -/// - When a host answers 413, half of the rejected body size becomes its limit. This is saved -/// (UserDefaults), so later syncs start with a size the host accepts. +/// - Default: `DbSyncConfig.maxBatchBytes`, or 4 MB when it is not set, for every server type +/// (AWARE Micro, and the AWARE server, whose PHP version is retired and whose endpoints are served +/// by Flask; Google App Engine accepts up to 32 MB). The margin keeps uploads short on slow +/// networks and keeps memory use low. A server with a smaller limit (for example nginx, 1 MB by +/// default) answers 413, and the limit is lowered and remembered (below). +/// - Growth (like `AWAREFetchSizeAdjuster` of AWAREFramework-iOS 1.x): after `growAfterFullSuccesses` +/// requests in a row that were filled up to the limit and finished within `growMaxNetworkSeconds`, +/// the limit grows by half, up to the ceiling (`DbSyncConfig.maxBatchBytesCeiling`; 8 MB by +/// default). What was learned is saved (UserDefaults), so later syncs start from it. +/// - When a host answers 413, half of the rejected body size becomes its limit. This is saved, so +/// later syncs start with a size the host accepts. It grows back by the rule above, but never above +/// 90 % of the smallest body the host rejected. /// - When a request times out, the limit is halved for the running app only (network speed /// changes), and grows back after `growAfterSuccesses` successful requests. public enum SyncBatchLimit { - public static let microDefaultBytes = 4_000_000 - public static let otherDefaultBytes = 900_000 + /// Default request size, for every server type + public static let defaultBytes = 4_000_000 + /// Default ceiling of the growth, for every server type (Google App Engine accepts 32 MB). Kept + /// well below it: each table holds the body in flight and the prefetched next one, and several + /// tables upload at the same time, so larger bodies risk the app's memory limit. + public static let defaultCeilingBytes = 8_000_000 + /// Up to 1.7 the defaults depended on the server type. They are the same now. + public static let microDefaultBytes = defaultBytes + public static let otherDefaultBytes = defaultBytes + public static let microCeilingBytes = defaultCeilingBytes /// Never below this, so that a sync always makes progress public static let minimumBytes = 16_384 static let growAfterSuccesses = 20 + /// Full requests in a row before the limit grows + static let growAfterFullSuccesses = 3 + /// A request counts toward growth only when its body was at least this part of the limit + static let fullRatio = 0.8 + /// A request counts toward growth only when it finished within this time, so that the limit + /// does not grow toward timeouts on a slow network + static let growMaxNetworkSeconds: TimeInterval = 10 + static let growthFactor = 1.5 static let keyPrefix = "aware.sync.max_batch_bytes." + static let grownKeyPrefix = "aware.sync.grown_batch_bytes." + static let rejectedKeyPrefix = "aware.sync.rejected_batch_bytes." private static let lock = NSLock() private static var timeoutLimits: [String: Int] = [:] private static var successes: [String: Int] = [:] + private static var fullSuccesses: [String: Int] = [:] /// The configured or default limit, before what was learned from the host. public static func configured(_ config: DbSyncConfig) -> Int { if let bytes = config.maxBatchBytes, bytes > 0 { return max(minimumBytes, bytes) } - return config.serverType == .aware_micro ? microDefaultBytes : otherDefaultBytes + return defaultBytes + } + + /// The largest limit the growth may reach (never below the configured limit). + public static func ceiling(_ config: DbSyncConfig) -> Int { + let base = configured(config) + if let bytes = config.maxBatchBytesCeiling, bytes > 0 { return max(base, bytes) } + return max(base, defaultCeilingBytes) } /// The limit to use for `host` now. public static func current(host: String, config: DbSyncConfig) -> Int { lock.lock() defer { lock.unlock() } + return currentLocked(host: host, config: config) + } + + private static func currentLocked(host: String, config: DbSyncConfig) -> Int { + let defaults = UserDefaults.standard var limit = configured(config) - let saved = UserDefaults.standard.integer(forKey: keyPrefix + host) + let grown = defaults.integer(forKey: grownKeyPrefix + host) + if grown > limit { limit = min(grown, ceiling(config)) } + let saved = defaults.integer(forKey: keyPrefix + host) if saved > 0 { limit = min(limit, saved) } if let t = timeoutLimits[host] { limit = min(limit, t) } return max(minimumBytes, limit) @@ -155,10 +194,17 @@ public enum SyncBatchLimit { public static func recordTooLarge(host: String, bodyBytes: Int) -> Int { lock.lock() defer { lock.unlock() } + let defaults = UserDefaults.standard let limit = max(minimumBytes, bodyBytes / 2) - let saved = UserDefaults.standard.integer(forKey: keyPrefix + host) - UserDefaults.standard.set(saved > 0 ? min(saved, limit) : limit, forKey: keyPrefix + host) + let saved = defaults.integer(forKey: keyPrefix + host) + defaults.set(saved > 0 ? min(saved, limit) : limit, forKey: keyPrefix + host) + let rejected = defaults.integer(forKey: rejectedKeyPrefix + host) + defaults.set(rejected > 0 ? min(rejected, bodyBytes) : bodyBytes, forKey: rejectedKeyPrefix + host) + if defaults.integer(forKey: grownKeyPrefix + host) >= bodyBytes { + defaults.removeObject(forKey: grownKeyPrefix + host) + } successes[host] = 0 + fullSuccesses[host] = 0 return limit } @@ -170,6 +216,7 @@ public enum SyncBatchLimit { let limit = max(minimumBytes, bodyBytes / 2) timeoutLimits[host] = min(timeoutLimits[host] ?? limit, limit) successes[host] = 0 + fullSuccesses[host] = 0 return limit } @@ -177,6 +224,51 @@ public enum SyncBatchLimit { public static func recordSuccess(host: String) { lock.lock() defer { lock.unlock() } + growBackFromTimeout(host: host) + } + + /// A request of `bodyBytes` succeeded after `networkSeconds`. Besides `recordSuccess(host:)`, the + /// limit grows after `growAfterFullSuccesses` full requests in a row (see the type's description). + /// - Returns: The new limit when it grew, otherwise nil. + @discardableResult + public static func recordSuccess(host: String, bodyBytes: Int, networkSeconds: TimeInterval, + config: DbSyncConfig) -> Int? { + lock.lock() + defer { lock.unlock() } + growBackFromTimeout(host: host) + + let limit = currentLocked(host: host, config: config) + let full = Double(bodyBytes) >= Double(limit) * fullRatio + guard full, networkSeconds <= growMaxNetworkSeconds, timeoutLimits[host] == nil else { + fullSuccesses[host] = 0 + return nil + } + let n = (fullSuccesses[host] ?? 0) + 1 + guard n >= growAfterFullSuccesses else { + fullSuccesses[host] = n + return nil + } + fullSuccesses[host] = 0 + + let defaults = UserDefaults.standard + var cap = ceiling(config) + let rejected = defaults.integer(forKey: rejectedKeyPrefix + host) + if rejected > 0 { cap = min(cap, Int(Double(rejected) * 0.9)) } + let next = min(cap, Int(Double(limit) * growthFactor)) + guard next > limit else { return nil } + + let saved = defaults.integer(forKey: keyPrefix + host) + if saved > 0 && saved <= limit { + // The limit learned from a 413 is what holds it back: raise it (still below the rejected size) + defaults.set(next, forKey: keyPrefix + host) + } + if next > configured(config) { + defaults.set(next, forKey: grownKeyPrefix + host) + } + return currentLocked(host: host, config: config) + } + + private static func growBackFromTimeout(host: String) { guard let t = timeoutLimits[host] else { return } let n = (successes[host] ?? 0) + 1 if n >= growAfterSuccesses { @@ -191,16 +283,21 @@ public enum SyncBatchLimit { public static func reset(host: String? = nil) { lock.lock() defer { lock.unlock() } + let defaults = UserDefaults.standard + let prefixes = [keyPrefix, grownKeyPrefix, rejectedKeyPrefix] if let host { - UserDefaults.standard.removeObject(forKey: keyPrefix + host) + prefixes.forEach { defaults.removeObject(forKey: $0 + host) } timeoutLimits[host] = nil successes[host] = nil + fullSuccesses[host] = nil } else { - for key in UserDefaults.standard.dictionaryRepresentation().keys where key.hasPrefix(keyPrefix) { - UserDefaults.standard.removeObject(forKey: key) + for key in defaults.dictionaryRepresentation().keys + where prefixes.contains(where: { key.hasPrefix($0) }) { + defaults.removeObject(forKey: key) } timeoutLimits = [:] successes = [:] + fullSuccesses = [:] } } } diff --git a/Sources/com.awareframework.ios.core/util/AwareNotification.swift b/Sources/com.awareframework.ios.core/util/AwareNotification.swift index 0ec8e6a..fb4b86e 100644 --- a/Sources/com.awareframework.ios.core/util/AwareNotification.swift +++ b/Sources/com.awareframework.ios.core/util/AwareNotification.swift @@ -12,5 +12,7 @@ public extension Notification.Name{ public static let dbSyncRequest = Notification.Name("AwareDBSyncRequest") public static let dbSyncStopRequest = Notification.Name("AwareDBSyncStopRequest") public static let dbSyncStopCompletion = Notification.Name("AwareDBSyncStopCompletion") + /// Posted when a sync of a table ends. `object` is the `SyncRunSummary`. + public static let dbSyncDiagnostics = Notification.Name("AwareDBSyncDiagnostics") } } diff --git a/Tests/com.awareframework.ios.coreTests/DbSyncBatchingTests.swift b/Tests/com.awareframework.ios.coreTests/DbSyncBatchingTests.swift index 9baf28c..4a935c3 100644 --- a/Tests/com.awareframework.ios.coreTests/DbSyncBatchingTests.swift +++ b/Tests/com.awareframework.ios.coreTests/DbSyncBatchingTests.swift @@ -163,7 +163,9 @@ final class DbSyncBatchingTests: XCTestCase { let micro = DbSyncConfig(); micro.serverType = .aware_micro let legacy = DbSyncConfig(); legacy.serverType = .aware XCTAssertEqual(SyncBatchLimit.configured(micro), 4_000_000) - XCTAssertEqual(SyncBatchLimit.configured(legacy), 900_000) + XCTAssertEqual(SyncBatchLimit.configured(legacy), 4_000_000, "the same for every server type") + XCTAssertEqual(SyncBatchLimit.ceiling(micro), 8_000_000) + XCTAssertEqual(SyncBatchLimit.ceiling(legacy), 8_000_000) legacy.maxBatchBytes = 2_000_000 XCTAssertEqual(SyncBatchLimit.configured(legacy), 2_000_000) } @@ -196,6 +198,95 @@ final class DbSyncBatchingTests: XCTestCase { XCTAssertEqual(SyncBatchLimit.current(host: "t", config: c), 4_000_000, "not above the configured limit") } + // MARK: - Growth (like AWAREFetchSizeAdjuster) + + private func fullSuccesses(_ n: Int, host: String, config c: DbSyncConfig, seconds: TimeInterval = 1) { + for _ in 0.. Date: Tue, 24 Nov 2026 23:33:03 -0800 Subject: [PATCH 2/2] Improve upload scheduling, encoding, and diagnostics --- Package.swift | 1 + README.md | 11 +- .../db/core/DbSyncConfig.swift | 33 +- .../db/core/DbSyncHelper.swift | 369 ++++++++++++----- .../db/core/Engine.swift | 34 ++ .../db/core/SyncDiagnostics.swift | 144 ++++++- .../db/core/SyncPacing.swift | 78 +++- .../db/core/UploadJSONBytes.swift | 165 ++++++++ .../db/sqlite/SQLiteEngine.swift | 185 +++++++-- .../manager/UploadScheduler.swift | 379 ++++++++++++++++++ .../model/SensorConfig.swift | 2 + .../AwareHubTests.swift | 97 +++++ .../DbSyncBatchingTests.swift | 92 +++-- .../DbSyncHelperTests.swift | 19 - .../SQLiteEngineSaveTests.swift | 16 + .../TrickyDataTests.swift | 120 ++++++ .../UploadJSONBytesTests.swift | 101 +++++ .../UploadJSONTests.swift | 37 ++ .../UploadSchedulerTests.swift | 57 +++ .../com_awareframework_ios_coreTests.swift | 3 +- 20 files changed, 1720 insertions(+), 223 deletions(-) create mode 100644 Sources/com.awareframework.ios.core/db/core/UploadJSONBytes.swift create mode 100644 Sources/com.awareframework.ios.core/manager/UploadScheduler.swift create mode 100644 Tests/com.awareframework.ios.coreTests/AwareHubTests.swift create mode 100644 Tests/com.awareframework.ios.coreTests/SQLiteEngineSaveTests.swift create mode 100644 Tests/com.awareframework.ios.coreTests/TrickyDataTests.swift create mode 100644 Tests/com.awareframework.ios.coreTests/UploadJSONBytesTests.swift create mode 100644 Tests/com.awareframework.ios.coreTests/UploadSchedulerTests.swift diff --git a/Package.swift b/Package.swift index 10c7ddf..816195c 100644 --- a/Package.swift +++ b/Package.swift @@ -23,6 +23,7 @@ let package = Package( dependencies: [ .product(name: "SwiftyJSON", package: "SwiftyJSON"), .product(name: "GRDB", package: "GRDB.swift"), + .product(name: "GRDBSQLite", package: "GRDB.swift"), .product(name: "Reachability", package: "Reachability.swift", condition: .when(platforms: [.iOS])) ] ), diff --git a/README.md b/README.md index 3e5c2cb..e78b4a2 100644 --- a/README.md +++ b/README.md @@ -191,7 +191,6 @@ let syncConfig = DbSyncConfig() syncConfig.maxBatchBytes = 4_000_000 // optional; by server type when not set syncConfig.removeAfterSync = true syncConfig.keepPeriod = .day // or keepDataAfterSync = 86400 (seconds) -syncConfig.compactDataFormat = false syncConfig.debug = true syncConfig.debugLevel = .verbose syncConfig.progressHandler = { progress, error in @@ -324,7 +323,7 @@ Per-table upload settings, used by `DbSyncHelper`. | `serverType: ServerType` | `DbSyncConfig.defaultServerType` (`.aware_micro`) | Server protocol; selects the upload URL (see [Upload URL](#upload-url)). | | `studyNumber: Int` | `DbSyncConfig.defaultStudyNumber` (`1`) | Study number in the upload URL. | | `studyKey: String` | `DbSyncConfig.defaultStudyKey` (`""`) | Study key in the upload URL. | -| `maxBatchBytes: Int?` | `DbSyncConfig.defaultMaxBatchBytes` (`nil`) | Largest request body in bytes. A request holds as many rows as fit. `nil` is 4 MB for every server type (Google App Engine accepts up to 32 MB; up to 1.7 it was 900 KB for servers other than AWARE Micro). See [Request size](#request-size). Dictionary key: `"maxBatchBytes"`. | +| `maxBatchBytes: Int?` | `DbSyncConfig.defaultMaxBatchBytes` (`nil`) | Largest request body in bytes. A request holds as many rows as fit. `nil` is 500 KB for every server type: Flask's default form field limit (Werkzeug 3.1 `MAX_FORM_MEMORY_SIZE`), so a server with default settings accepts the first requests (up to 1.7: 4 MB for AWARE Micro, 900 KB for other servers). See [Request size](#request-size). Dictionary key: `"maxBatchBytes"`. | | `maxBatchBytesCeiling: Int?` | `DbSyncConfig.defaultMaxBatchBytesCeiling` (`nil`) | Largest size the limit grows to while requests are full and fast. `nil` is 8 MB. Set it to `maxBatchBytes` to turn growth off. Dictionary key: `"maxBatchBytesCeiling"`. | | `maxBatchRows: Int` | `DbSyncConfig.defaultMaxBatchRows` (`20000`) | Largest number of rows per request. Dictionary key: `"maxBatchRows"`. | | `prefetchNextBatch: Bool` | `DbSyncConfig.defaultPrefetchNextBatch` (`true`) | Choose and build the next request while the current one is in flight, so the device and the server work at the same time. Dictionary key: `"prefetchNextBatch"`. | @@ -335,7 +334,7 @@ Per-table upload settings, used by `DbSyncHelper`. | `removeAfterSync: Bool` | `true` | Delete uploaded rows from the local database once they are older than `keepDataAfterSync`. Rows that have not been uploaded are never deleted. Set `false` to keep every row. | | `keepDataAfterSync: TimeInterval` | `86400` (one day) | Seconds to keep uploaded rows on the device, counted from each row's `timestamp`. `0` deletes them right after upload. Negative values are ignored. Dictionary key: `"keepDataAfterSync"`. | | `keepPeriod: DbSyncConfig.KeepPeriod?` | `.day` | `keepDataAfterSync` as a period: `.immediately` (0), `.hour`, `.day`, `.week`, `.month` (30 days). Setting it sets `keepDataAfterSync`; reading it gives `nil` for other values. Dictionary key: `"keepPeriod"` (e.g. `"week"`). | -| `compactDataFormat: Bool` | `DbSyncConfig.defaultCompactDataFormat` (`false`) | Send columns as arrays, and omit `os`, `jsonVersion`, `deviceId` and `timezone`, to reduce payload size. | +| `compactDataFormat: Bool` | — | Deprecated: the compact data format was removed. Setting it has no effect; rows are always sent one object per row. | | `backgroundSession: Bool` | `false` | Use a background `URLSession` (`URLSessionConfiguration.background`). | | `debug: Bool` | `false` | Enable debug logging. | | `debugLevel: DbSyncDebugLevel` | `.info` | Log verbosity: `.none`, `.error`, `.warning`, `.info`, `.verbose`, `.trace`. | @@ -373,13 +372,13 @@ Each request holds as many rows as fit in the size limit, in the form the server | Situation | What the sync does | |---|---| -| Default | `maxBatchBytes`, or 4 MB, for every server type (the PHP version of the AWARE server is retired; its endpoints are served by Flask) | +| Default | `maxBatchBytes`, or 500 KB, for every server type: Flask's default form field limit (the PHP version of the AWARE server is retired; its endpoints are served by Flask). A server with a higher limit gets larger requests by growth. | | Requests are full and fast | After 3 requests in a row that filled at least 80 % of the limit and finished within 10 s, the limit grows by half, up to `maxBatchBytesCeiling` (8 MB by default), and is saved (`aware.sync.grown_batch_bytes.`). Like `AWAREFetchSizeAdjuster` of AWAREFramework-iOS 1.x. | -| The server answers 413 | Half of the rejected size becomes the host's limit, saved in `UserDefaults` (`aware.sync.max_batch_bytes.`), and the same rows are sent again right away. A server with nginx's default 1 MB limit costs two rejected requests once (4 MB, 2 MB), then every request fits. The limit grows back by the rule above, but never above 90 % of the smallest size the host rejected (`aware.sync.rejected_batch_bytes.`). | +| The server answers 413 | Half of the rejected size becomes the host's limit, saved in `UserDefaults` (`aware.sync.max_batch_bytes.`), and the same rows are sent again right away. For example, a server with nginx's default 1 MB limit answers 413 once while the size grows past 1 MB, then every request fits. The limit grows back by the rule above, but never above 90 % of the smallest size the host rejected (`aware.sync.rejected_batch_bytes.`). | | A request times out | The limit is halved for this run of the app and the rows are sent again; after 20 successful requests in a row it grows back by half, up to the default. | | 429 or 503 | Wait for `Retry-After` (or 5, 10, 20 s, at most 120 s) and send again, up to 3 times. | -`SyncBatchLimit.reset(host:)` forgets what was learned. With `compactDataFormat` or `createHttpRequestBodyHandler`, the body is built as a whole and rows are removed until it fits. +`SyncBatchLimit.reset(host:)` forgets what was learned. With `createHttpRequestBodyHandler`, the body is built as a whole and rows are removed until it fits. With `SQLiteEngine`, each row is written as JSON straight from the values SQLite returns (`Engine.fetchUploadJSON(afterId:limit:omitting:)`), without making a dictionary for the row first. The values are the same as before: NULL columns are left out, and a REAL is written with the shortest text that reads back as the same Double, so no precision is lost. (SQLite's own `json_object()` is not used: it keeps only 15 significant digits, so a millisecond timestamp stored as REAL would lose its last digits.) A row JSON cannot hold (a BLOB, or infinity or NaN) goes through the general builder as before. A `DbSyncHelper` subclass that overrides `getUploadCandidates(lastUploadedId:limit:)` to change the rows must also override `getUploadCandidateJSON(lastUploadedId:limit:)` (returning `nil` is enough). diff --git a/Sources/com.awareframework.ios.core/db/core/DbSyncConfig.swift b/Sources/com.awareframework.ios.core/db/core/DbSyncConfig.swift index b56911a..f00a6b4 100644 --- a/Sources/com.awareframework.ios.core/db/core/DbSyncConfig.swift +++ b/Sources/com.awareframework.ios.core/db/core/DbSyncConfig.swift @@ -10,7 +10,7 @@ /// - batchSize: Rows read from the database at a time while a request is built. Default is `1000`. /// (Up to 1.6, it was the number of rows per request. A request now holds as many rows as fit /// in `maxBatchBytes`, up to `maxBatchRows`.) -/// - maxBatchBytes: Largest request body in bytes. `nil` (default) is 4 MB for every server type +/// - maxBatchBytes: Largest request body in bytes. `nil` (default) is 500 KB (Flask's default form limit) for every server type /// (up to 1.7: 900 KB for servers other than AWARE Micro). A host that answers 413 gets a smaller /// limit, which is remembered. See `SyncBatchLimit`. /// - maxBatchBytesCeiling: Largest size `maxBatchBytes` may grow to after requests in a row that were @@ -30,9 +30,10 @@ /// - debug: A boolean indicating whether to enable debug mode. Default is `false`. /// - completionHandler: An optional completion handler to be called after synchronization. /// - progressHandler: An optional progress handler to be called during synchronization. +/// - batchHandler: Called after each request with its `SyncBatchMetrics` (rows, bytes, times), on the +/// sync queue. Sensors that upload several tables pass it to every table, like `progressHandler`. /// - dispatchQueue: An optional dispatch queue for synchronization tasks. /// - backgroundSession: A boolean indicating whether to use a background session for synchronization. Default is `false`. -/// - compactDataFormat: A boolean indicating whether to use a compact data format for synchronization. Default is `true`. /// /// - Methods: /// - init(): Initializes a new instance of `DbSyncConfig` with default values. @@ -81,12 +82,18 @@ public class DbSyncConfig { public static var defaultServerType: ServerType = .aware_micro public static var defaultStudyNumber: Int = 1 public static var defaultStudyKey: String = "" - public static var defaultCompactDataFormat: Bool = false + /// The compact data format was removed: rows are always uploaded one object per row. + @available(*, deprecated, message: "The compact data format was removed; this setting has no effect.") + public static var defaultCompactDataFormat: Bool { + get { false } + set { } + } /// App-wide defaults for new configs (sensors create their configs themselves) public static var defaultMaxBatchBytes: Int? = nil public static var defaultMaxBatchBytesCeiling: Int? = nil public static var defaultMaxBatchRows: Int = 20000 public static var defaultCpuRestRatio: Double = 1 + public static var defaultBackgroundCpuRestRatio: Double = 3 public static var defaultPrefetchNextBatch: Bool = true public var removeAfterSync: Bool = true @@ -136,7 +143,7 @@ public class DbSyncConfig { public var prefetchNextBatch: Bool = DbSyncConfig.defaultPrefetchNextBatch public var batchInterval: TimeInterval = 0 public var cpuRestRatio: Double = DbSyncConfig.defaultCpuRestRatio - public var backgroundCpuRestRatio: Double = 3 + public var backgroundCpuRestRatio: Double = DbSyncConfig.defaultBackgroundCpuRestRatio public var markAsSynced: Bool = false public var skipSyncedData: Bool = false public var keepLastData: Bool = false @@ -145,9 +152,15 @@ public class DbSyncConfig { public var debugLevel: DbSyncDebugLevel = .info // Default to info level public var completionHandler: DbSyncCompletionHandler? = nil public var progressHandler: DbSyncProgressHandler? = nil + public var batchHandler: ((SyncBatchMetrics) -> Void)? = nil public var dispatchQueue: DispatchQueue? = nil public var backgroundSession = false - public var compactDataFormat = DbSyncConfig.defaultCompactDataFormat + /// The compact data format was removed: rows are always uploaded one object per row. + @available(*, deprecated, message: "The compact data format was removed; this setting has no effect.") + public var compactDataFormat: Bool { + get { false } + set { } + } public var serverType: ServerType = DbSyncConfig.defaultServerType public var studyNumber: Int = DbSyncConfig.defaultStudyNumber public var studyKey: String = DbSyncConfig.defaultStudyKey @@ -186,9 +199,9 @@ public class DbSyncConfig { c.debugLevel = debugLevel c.completionHandler = completionHandler c.progressHandler = progressHandler + c.batchHandler = batchHandler c.dispatchQueue = dispatchQueue c.backgroundSession = backgroundSession - c.compactDataFormat = compactDataFormat c.serverType = serverType c.studyNumber = studyNumber c.studyKey = studyKey @@ -276,12 +289,6 @@ public class DbSyncConfig { self.test = test } - if let compactDataFormat = config["compactDataFormat"] as? Bool { - self.compactDataFormat = compactDataFormat - } else if let compressionMode = config["compressionMode"] as? String { - self.compactDataFormat = compressionMode.lowercased() == "compact" - } - if let studyNumber = config["studyNumber"] as? Int { self.studyNumber = studyNumber } else if let studyNumber = config["study_number"] as? Int { @@ -305,6 +312,8 @@ public class DbSyncConfig { self.serverType = .aware_micro } else if serverType == 4 { self.serverType = .aware_light + } else if serverType == 5 { + self.serverType = .aware_hub } else { self.serverType = .aware } diff --git a/Sources/com.awareframework.ios.core/db/core/DbSyncHelper.swift b/Sources/com.awareframework.ios.core/db/core/DbSyncHelper.swift index 5143450..f804e0e 100644 --- a/Sources/com.awareframework.ios.core/db/core/DbSyncHelper.swift +++ b/Sources/com.awareframework.ios.core/db/core/DbSyncHelper.swift @@ -32,8 +32,6 @@ private struct DbSyncConstants { static let httpSuccessRange = 200..<300 static let httpNotFoundStatus = 404 - // Excluded fields for compact format - static let excludedCompactFields: Set = ["os", "jsonVersion", "deviceId", "timezone"] } /// DbSyncUtils - Utility class for database synchronization @@ -204,12 +202,6 @@ private enum ResponseResult { case serverError(Int) } -/// Data format types -private enum DataFormat { - case standard - case compact -} - /// DbSyncHelper - Main class for managing database synchronization /// /// This class handles data synchronization from local database to server. @@ -307,6 +299,8 @@ open class DbSyncHelper: NSObject { private var currentTimings: (connect: TimeInterval?, upload: TimeInterval?, server: TimeInterval?, download: TimeInterval?)? private var currentDeleteSeconds: TimeInterval = 0 + /// Phase by phase times of the request in flight + private var currentPhases = SyncPhaseTimes() /// The finished request, recorded once the rest before the next one is known private var pendingMetrics: SyncBatchMetrics? @@ -706,11 +700,12 @@ open class DbSyncHelper: NSObject { } prefetched = nil currentLimitBytes = limit + currentPhases = batch.phases if config.debug { logVerbose( "→ performDataSync() selected \(batch.count) rows" - + (batch.body.map { " (\($0.utf8.count) bytes)" } ?? "") + ", last batch: \(batch.isLast)") + + (batch.body.map { " (\($0.count) bytes)" } ?? "") + ", last batch: \(batch.isLast)") } send(count: batch.count, lastId: batch.lastId, rows: batch.rows, body: batch.body, isLast: batch.isLast) @@ -726,10 +721,20 @@ open class DbSyncHelper: NSObject { /// The rows, kept only when the body is built by `buildRequestBody(from:)` var rows: [[String: Any]]? /// The request body, or nil when it is built by `buildRequestBody(from:)` - var body: String? + var body: Data? var isLast: Bool + /// Time of each phase of choosing the rows and building the body + var phases = SyncPhaseTimes() } + /// Rows whose size is measured together: a group that fits in the limit is taken as a whole, + /// and only the group at the edge of the limit is measured row by row. For the legacy AWARE + /// server the size is the URL-encoded size, which is costly to compute for every row. + /// (Changeable for tests and benchmarks.) + public static var sizeGroupRows = 100 + + + /// Choose the rows of the next request. /// /// Rows are read `batchSize` at a time, in row ID order, and added while the request body stays @@ -738,64 +743,124 @@ open class DbSyncHelper: NSObject { /// and the JSON is reused for the body. Only the JSON is kept, not the rows, so memory stays near /// the size of the body. The first row is always taken, so a sync makes progress. /// - /// With `compactDataFormat` or `createHttpRequestBodyHandler` the body is not the sum of its rows, - /// so it is built with `buildRequestBody(from:)` and rows are removed until it fits. + /// With `createHttpRequestBodyHandler` the body is not the sum of its rows, so it is built with + /// `buildRequestBody(from:)` and rows are removed until it fits. private func selectBatch(afterId start: Int64, limit: Int) -> Batch { + let cpuStart = SyncClock.threadCPU() + var phases = SyncPhaseTimes() + var batch = selectBatchRows(afterId: start, limit: limit, phases: &phases) + phases.prepareCPU = SyncClock.seconds(SyncClock.threadCPU() &- cpuStart) + batch.phases = phases + return batch + } + + private func selectBatchRows(afterId start: Int64, limit: Int, phases: inout SyncPhaseTimes) -> Batch { let maxRows = max(1, config.maxBatchRows) let chunk = max(1, min(config.batchSize, maxRows)) let form = !usesNewAwareServerEndpoint - let separator = form ? formEncodedLength(",") : 1 - let exact = !config.compactDataFormat && createHttpRequestBodyHandler == nil + let separator = 1 // "," (not encoded in the form either) + let exact = createHttpRequestBodyHandler == nil var rows: [[String: Any]] = [] // only when !exact - var pieces: [String] = [] + var data: [UInt8] = [] // the rows' JSON joined with ",", when exact + if exact { data.reserveCapacity(min(limit, 16_000_000)) } + var chunkBuffer: [UInt8] = [] var count = 0 var lastId: Int64? - var total = 0 - if exact { - // Size with no rows: the envelope with an empty data array (see assembleBody) - total = form ? formEnvelopeLength() : jsonEnvelope().utf8.count + ",\"data\":[]".utf8.count - } + // Size with no rows: the envelope with an empty data array (see assembleBody) + var total = exact ? emptyBodySize(form: form) : 0 var afterId = start var more = true var invalid = false + /// Size of a row in the body (URL-encoded for the legacy AWARE server) + func size(_ bytes: UnsafeBufferPointer) -> Int { + form ? FormEncoding.encodedLength(bytes) : bytes.count + } + reading: while count < maxRows { let want = min(chunk, maxRows - count) var stop = false let fetchedCount: Int = autoreleasepool { - // Fast path: the engine writes each row's JSON without a dictionary per row - if exact, let encoded = getUploadCandidateJSON(lastUploadedId: afterId, limit: want) { - for row in encoded { - guard let json = row.json else { - invalid = true - stop = true - break + // Fast path: the engine writes the rows' JSON into one byte buffer + let fetchStart = SyncClock.now() + chunkBuffer.removeAll(keepingCapacity: true) + if exact, let spans = appendUploadCandidateJSON(lastUploadedId: afterId, limit: want, to: &chunkBuffer) { + if let t = engine.lastUploadJSONTiming { + phases.dbWait += t.queueWait + phases.dbRead += t.read + phases.jsonEncode += t.encode + } else { + phases.dbRead += SyncClock.since(fetchStart) + } + let sizeStart = SyncClock.now() + defer { phases.sizeCheck += SyncClock.since(sizeStart) } + chunkBuffer.withUnsafeBufferPointer { buffer in + func bytes(_ span: UploadRowSpan) -> UnsafeBufferPointer { + UnsafeBufferPointer(rebasing: buffer[span.range!]) } - let size = (form ? formEncodedLength(json) : json.utf8.count) + (pieces.isEmpty ? 0 : separator) - if count > 0 && total + size > limit { - stop = true - break + func take(_ span: UploadRowSpan) { + if !data.isEmpty { data.append(UInt8(ascii: ",")) } + data.append(contentsOf: bytes(span)) + } + var i = 0 + groups: while i < spans.count { + var end = min(i + Self.sizeGroupRows, spans.count) + // A row that cannot be written as JSON ends the fast path (see below) + if let bad = spans[i.. 0 && total + rowSize > limit { + stop = true + break groups + } + take(span) + total += rowSize + count += 1 + lastId = span.id + } + i = end } - pieces.append(json) - total += size - count += 1 - lastId = row.id } - return encoded.count + return spans.count } let fetched = getUploadCandidates(lastUploadedId: afterId, limit: want) + phases.dbRead += SyncClock.since(fetchStart) + let encodeStart = SyncClock.now() + defer { phases.jsonEncode += SyncClock.since(encodeStart) } for row in fetched { if !exact { rows.append(row) } else if let json = rowJSON(row) { - let size = (form ? formEncodedLength(json) : json.utf8.count) + (pieces.isEmpty ? 0 : separator) - if count > 0 && total + size > limit { + var json = json + let rowSize = json.withUTF8 { size($0) } + (data.isEmpty ? 0 : separator) + if count > 0 && total + rowSize > limit { stop = true break } - pieces.append(json) - total += size + if !data.isEmpty { data.append(UInt8(ascii: ",")) } + data.append(contentsOf: json.utf8) + total += rowSize } else { // Not valid JSON: fall back to buildRequestBody, which reports the error invalid = true @@ -818,7 +883,10 @@ open class DbSyncHelper: NSObject { } if exact && !invalid { - return Batch(count: count, lastId: lastId, rows: nil, body: assembleBody(pieces, form: form), isLast: !more) + let assembleStart = SyncClock.now() + let body = assembleBody(data, form: form) + phases.assemble += SyncClock.since(assembleStart) + return Batch(count: count, lastId: lastId, rows: nil, body: body, isLast: !more) } if invalid { // Read the same rows again as dictionaries for buildRequestBody @@ -826,6 +894,8 @@ open class DbSyncHelper: NSObject { more = true } // Build with the general builder, and remove rows until the body fits + let assembleStart = SyncClock.now() + defer { phases.assemble += SyncClock.since(assembleStart) } for _ in 0..<4 { guard rows.count > 1, let body = try? buildRequestBody(from: rows) else { break } let bytes = body.utf8.count @@ -857,34 +927,35 @@ open class DbSyncHelper: NSObject { return String(data: data, encoding: .utf8) ?? "{}" } - /// Length of the form body with an empty data array (legacy AWARE server) - private func formEnvelopeLength() -> Int { - buildFormRequestBody(["device_id": AwareUtils.getCommonDeviceId(), "data": "[]"]).utf8.count - } - - /// Length of `text` after URL encoding as a form value. Encoding is per character, so the encoded - /// lengths of the rows add up to the encoded length of the data array. - private func formEncodedLength(_ text: String) -> Int { - buildFormRequestBody(["v": text]).utf8.count - "v=".utf8.count + /// Size of the body with no rows (see `assembleBody`) + private func emptyBodySize(form: Bool) -> Int { + if form { + return FormEncoding.body([("device_id", AwareUtils.getCommonDeviceId()), ("data", "[]")]).utf8.count + } + return jsonEnvelope().utf8.count + ",\"data\":[]".utf8.count } - /// The request body from the rows' JSON, in the same form `buildRequestBody(from:)` produces - private func assembleBody(_ pieces: [String], form: Bool) -> String { + /// The request body from the rows' JSON joined with ",", in the same form + /// `buildRequestBody(from:)` produces + private func assembleBody(_ rows: [UInt8], form: Bool) -> Data { + var out: [UInt8] = [] if form { - let data = "[" + pieces.joined(separator: ",") + "]" - return buildFormRequestBody(["device_id": AwareUtils.getCommonDeviceId(), "data": data]) - } - // One buffer of the final size, instead of joining and then concatenating copies - let head = String(jsonEnvelope().dropLast()) + ",\"data\":[" - var body = "" - body.reserveCapacity(head.utf8.count + pieces.reduce(0) { $0 + $1.utf8.count } + pieces.count + 2) - body.append(head) - for (i, piece) in pieces.enumerated() { - if i > 0 { body.append(",") } - body.append(piece) + out.reserveCapacity(rows.count + rows.count / 2 + 128) + FormEncoding.append("device_id", to: &out) + out.append(UInt8(ascii: "=")) + FormEncoding.append(AwareUtils.getCommonDeviceId(), to: &out) + out.append(contentsOf: Array("&data=".utf8)) + FormEncoding.append("[", to: &out) + rows.withUnsafeBufferPointer { FormEncoding.append($0, to: &out) } + FormEncoding.append("]", to: &out) + } else { + let head = String(jsonEnvelope().dropLast()) + ",\"data\":[" + out.reserveCapacity(head.utf8.count + rows.count + 2) + out.append(contentsOf: head.utf8) + out.append(contentsOf: rows) + out.append(contentsOf: Array("]}".utf8)) } - body.append("]}") - return body + return Data(out) } // MARK: - Data Management @@ -916,6 +987,14 @@ open class DbSyncHelper: NSObject { * A subclass that overrides `getUploadCandidates` to change the rows must override this too * (returning nil is enough), or the rows it changes are uploaded unchanged. */ + /// The rows of `getUploadCandidateJSON(lastUploadedId:limit:)`, written into `buffer` (appended). + /// The sync builds its requests from these bytes. A subclass that overrides `getUploadCandidates` + /// to change the rows must override this too (returning nil is enough). + open func appendUploadCandidateJSON(lastUploadedId: Int64, limit: Int, to buffer: inout [UInt8]) -> [UploadRowSpan]? { + let omitting: Set = config.serverType == .aware_light ? ["id"] : [] + return engine.appendUploadJSON(afterId: lastUploadedId, limit: limit, omitting: omitting, to: &buffer) + } + open func getUploadCandidateJSON(lastUploadedId: Int64, limit: Int) -> [UploadRowJSON]? { let omitting: Set = config.serverType == .aware_light ? ["id"] : [] return engine.fetchUploadJSON(afterId: lastUploadedId, limit: limit, omitting: omitting) @@ -979,25 +1058,7 @@ open class DbSyncHelper: NSObject { uploadCandidate.removeValue(forKey: "id") return uploadCandidate } - let payloadData: Any - - // Compact data format processing - if self.config.compactDataFormat { - // Aggregate data by column (to reduce transfer volume) - var aggregatedData: [String: [Any]] = [:] - for dict in uploadCandidates { - for (key, value) in dict { - // Exclude common system fields - if !DbSyncConstants.excludedCompactFields.contains(key) { - aggregatedData[key, default: []].append(value) - } - } - } - payloadData = aggregatedData - } else { - // Standard format (row by row) - payloadData = uploadCandidates - } + let payloadData: Any = uploadCandidates let jsonData = try JSONSerialization.data(withJSONObject: payloadData, options: []) let data = String(data: jsonData, encoding: .utf8)! @@ -1015,8 +1076,8 @@ open class DbSyncHelper: NSObject { } else { // Build request body in URL-encoded format for legacy AWARE server. requestStr = buildFormRequestBody([ - "device_id": deviceId, - "data": data, + ("device_id", deviceId), + ("data", data), ]) } @@ -1028,10 +1089,10 @@ open class DbSyncHelper: NSObject { return requestStr } - private func buildFormRequestBody(_ parameters: [String: String]) -> String { - var components = URLComponents() - components.queryItems = parameters.map { URLQueryItem(name: $0.key, value: $0.value) } - return components.percentEncodedQuery ?? "" + /// A form body (`application/x-www-form-urlencoded`), fields in the given order. `+` is encoded + /// (see `FormEncoding`). + private func buildFormRequestBody(_ fields: [(String, String)]) -> String { + FormEncoding.body(fields) } /** @@ -1040,7 +1101,7 @@ open class DbSyncHelper: NSObject { * @param requestBody Request body * @return Built URLRequest */ - private func buildHTTPRequest(with requestBody: String) -> URLRequest? { + func buildHTTPRequest(with requestBody: Data) -> URLRequest? { // Send HTTP request var hostName = AwareUtils.cleanHostName(self.host) while hostName.hasSuffix("/") { @@ -1051,7 +1112,12 @@ open class DbSyncHelper: NSObject { } let urlString: String - if config.serverType == .aware_micro { + if config.serverType == .aware_hub { + let safeStudyKey = + config.studyKey.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) + ?? config.studyKey + urlString = "https://\(hostName)/v1/\(config.studyNumber)/\(safeStudyKey)/insert" + } else if config.serverType == .aware_micro { let safeStudyKey = config.studyKey.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? config.studyKey @@ -1077,7 +1143,15 @@ open class DbSyncHelper: NSObject { // Configure HTTP request var request = URLRequest(url: url) request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData - request.httpBody = requestBody.data(using: .utf8) + request.httpBody = requestBody + if config.serverType == .aware_hub { + // The body compressed (sensor data shrinks to 5-15%). The request size limits apply + // to the body before compression, as the server checks the decompressed size. + if let compressed = Self.deflate(requestBody) { + request.httpBody = compressed + request.setValue("deflate", forHTTPHeaderField: "Content-Encoding") + } + } request.timeoutInterval = DbSyncConstants.requestTimeout request.httpMethod = "POST" request.allowsCellularAccess = true @@ -1096,9 +1170,19 @@ open class DbSyncHelper: NSObject { return request } + /// The body compressed with deflate (raw deflate, which the server takes as + /// `Content-Encoding: deflate`), or nil when compression fails + static func deflate(_ data: Data) -> Data? { + guard data.isEmpty == false else { return nil } + if #available(iOS 13.0, watchOS 6.0, macOS 10.15, *) { + return try? (data as NSData).compressed(using: .zlib) as Data + } + return nil + } + private var usesNewAwareServerEndpoint: Bool { switch config.serverType { - case .aware_micro, .aware_light: + case .aware_micro, .aware_light, .aware_hub: return true case .none, .aware: return false @@ -1241,7 +1325,7 @@ open class DbSyncHelper: NSObject { /// Send one request of `count` rows ending with row `lastId`. The body is `body` when it was already /// built, otherwise it is built from `rows`. - private func send(count: Int, lastId: Int64?, rows: [[String: Any]]?, body prebuiltBody: String?, isLast: Bool) { + private func send(count: Int, lastId: Int64?, rows: [[String: Any]]?, body prebuiltBody: Data?, isLast: Bool) { guard isStopRequested == false else { return } if config.debug { logVerbose("upload() started with \(count) candidates") @@ -1302,17 +1386,21 @@ open class DbSyncHelper: NSObject { do { // Build HTTP request body (unless it was built while choosing the rows) let started = Date() - let requestBody = try prebuiltBody ?? buildRequestBody(from: rows ?? []) + let requestBody = try prebuiltBody ?? Data(buildRequestBody(from: rows ?? []).utf8) let buildSeconds = Date().timeIntervalSince(started) batchWorkSeconds += buildSeconds if !currentPrefetched { currentPrepareSeconds += buildSeconds } - currentBodyBytes = requestBody.utf8.count + if prebuiltBody == nil { currentPhases.assemble += buildSeconds } + currentBodyBytes = requestBody.count requestStartedAt = Date() currentTimings = nil currentDeleteSeconds = 0 // Build HTTP request - if let request = buildHTTPRequest(with: requestBody) { + let requestStart = SyncClock.now() + let builtRequest = buildHTTPRequest(with: requestBody) + currentPhases.toData = SyncClock.since(requestStart) + if let request = builtRequest { guard isStopRequested == false else { return } if self.config.test { // Test mode should not leave synthetic URLSession tasks behind. @@ -1678,6 +1766,9 @@ open class DbSyncHelper: NSObject { /// The metrics of the request that just ended private func makeMetrics(success: Bool) -> SyncBatchMetrics { let processInfo = ProcessInfo.processInfo + var phases = currentPhases + phases.delete = currentDeleteSeconds + let load = SyncDiagnostics.shared.sampleLoad() return SyncBatchMetrics( table: tableName, host: limitHost, date: Date(), rows: currentNumOfCandidates, bodyBytes: currentBodyBytes, limitBytes: currentLimitBytes, @@ -1687,7 +1778,8 @@ open class DbSyncHelper: NSObject { serverSeconds: currentTimings?.server, downloadSeconds: currentTimings?.download, deleteSeconds: currentDeleteSeconds, restSeconds: 0, statusCode: lastStatusCode, success: success, background: SyncAppState.shared.isInBackground, - lowPower: processInfo.isLowPowerModeEnabled, thermalState: processInfo.thermalState) + lowPower: processInfo.isLowPowerModeEnabled, thermalState: processInfo.thermalState, + phases: phases, appCPUPercent: load.cpuPercent, memoryMB: load.memoryMB) } /// Record the request that ended, with the rest (or retry wait) that follows it @@ -1701,9 +1793,11 @@ open class DbSyncHelper: NSObject { uploadSeconds: m.uploadSeconds, serverSeconds: m.serverSeconds, downloadSeconds: m.downloadSeconds, deleteSeconds: m.deleteSeconds, restSeconds: rest, statusCode: m.statusCode, success: m.success, background: m.background, - lowPower: m.lowPower, thermalState: m.thermalState) + lowPower: m.lowPower, thermalState: m.thermalState, + phases: m.phases, appCPUPercent: m.appCPUPercent, memoryMB: m.memoryMB) recorder.add(metrics, isRetryWait: isRetryWait) SyncDiagnostics.shared.record(metrics) + config.batchHandler?(metrics) logInfo("Request: \(metrics)") } @@ -1716,6 +1810,77 @@ open class DbSyncHelper: NSObject { recorder = SyncRunRecorder(table: tableName, host: limitHost) } + // MARK: - Benchmark + + /// Prepare up to `batches` requests from the rows not uploaded yet, as a sync would (reading + /// the rows, writing them as JSON, measuring their size, building the body and its bytes), and + /// return what each took (`SyncBatchMetrics.phases`). Nothing is sent, and nothing changes: + /// neither the rows, nor the sync marker. Call it off the main thread. + public func benchmarkPreparation(batches: Int) -> [SyncBatchMetrics] { + var afterId = DbSyncUtils.validatedLastUploadedId( + forKey: markerKey, maxAssignedId: engine.maxAssignedId(tableName: tableName)) + let limit = SyncBatchLimit.current(host: limitHost, config: config) + var results: [SyncBatchMetrics] = [] + for _ in 0.. 0, let lastId = batch.lastId else { break } + if batch.body == nil, let rows = batch.rows { + let buildStart = SyncClock.now() + batch.body = (try? buildRequestBody(from: rows)).map { Data($0.utf8) } + batch.phases.assemble += SyncClock.since(buildStart) + } + let dataStart = SyncClock.now() + let bytes = batch.body?.count ?? 0 + batch.phases.toData = SyncClock.since(dataStart) + let processInfo = ProcessInfo.processInfo + let load = SyncDiagnostics.shared.sampleLoad() + results.append(SyncBatchMetrics( + table: tableName, host: limitHost, date: Date(), rows: batch.count, bodyBytes: bytes, + limitBytes: limit, prepareSeconds: SyncClock.since(started), prefetched: false, + networkSeconds: 0, connectSeconds: nil, uploadSeconds: nil, serverSeconds: nil, + downloadSeconds: nil, deleteSeconds: 0, restSeconds: 0, statusCode: nil, success: true, + background: SyncAppState.shared.isInBackground, lowPower: processInfo.isLowPowerModeEnabled, + thermalState: processInfo.thermalState, phases: batch.phases, + appCPUPercent: load.cpuPercent, memoryMB: load.memoryMB)) + if batch.isLast { break } + afterId = lastId + } + return results + } + + /// A request a sync would send next, for checks (see `previewRequests(batches:)`) + public struct PreviewRequest { + public let rows: Int + public let firstId: Int64 + public let lastId: Int64 + public let limitBytes: Int + public let body: Data + } + + /// The bodies of the next `batches` requests a sync would send, built from the rows not uploaded + /// yet, without sending them and without changing anything (rows, sync marker). Call it off the + /// main thread. + public func previewRequests(batches: Int) -> [PreviewRequest] { + var afterId = DbSyncUtils.validatedLastUploadedId( + forKey: markerKey, maxAssignedId: engine.maxAssignedId(tableName: tableName)) + let limit = SyncBatchLimit.current(host: limitHost, config: config) + var results: [PreviewRequest] = [] + for _ in 0.. 0, let lastId = batch.lastId else { break } + if batch.body == nil, let rows = batch.rows { + batch.body = (try? buildRequestBody(from: rows)).map { Data($0.utf8) } + } + guard let body = batch.body else { break } + let firstId = engine.fetch(filter: "id > \(afterId)", limit: 1)?.first?["id"] as? Int64 ?? afterId + 1 + results.append(PreviewRequest(rows: batch.count, firstId: firstId, lastId: lastId, limitBytes: limit, body: body)) + if batch.isLast { break } + afterId = lastId + } + return results + } + /// Choose and build the request after the rows ending with `lastId` on the sync queue, so it is /// ready when the current request ends. The sync queue is serial, so this runs before the /// response of the current request is handled. @@ -1728,7 +1893,9 @@ open class DbSyncHelper: NSObject { var batch = self.selectBatch(afterId: afterId, limit: limit) guard batch.count > 0 else { return } if batch.body == nil, let rows = batch.rows { - batch.body = try? self.buildRequestBody(from: rows) + let buildStart = SyncClock.now() + batch.body = (try? self.buildRequestBody(from: rows)).map { Data($0.utf8) } + batch.phases.assemble += SyncClock.since(buildStart) } self.prefetched = Prefetch(afterId: afterId, limit: limit, batch: batch, seconds: Date().timeIntervalSince(started)) diff --git a/Sources/com.awareframework.ios.core/db/core/Engine.swift b/Sources/com.awareframework.ios.core/db/core/Engine.swift index 2f3af71..fa53450 100644 --- a/Sources/com.awareframework.ios.core/db/core/Engine.swift +++ b/Sources/com.awareframework.ios.core/db/core/Engine.swift @@ -11,6 +11,8 @@ public enum ServerType { case aware case aware_micro case aware_light + /// AWARE Hub: JSON uploads, compressed + case aware_hub } public protocol EngineProtocal { @@ -149,6 +151,38 @@ open class Engine: EngineProtocal { /// The sync uses this to build a request without making a dictionary for every row. Returns `nil` /// when the engine cannot do this; the sync then uses `fetch(filter:limit:)`. open func fetchUploadJSON(afterId: Int64, limit: Int, omitting: Set) -> [UploadRowJSON]? { nil } + + /// The rows of `fetchUploadJSON(afterId:limit:omitting:)`, written into `buffer` (appended) + /// instead of one string per row. The sync builds its requests from these bytes. + /// The default uses `fetchUploadJSON`; `SQLiteEngine` writes the bytes straight from SQLite. + open func appendUploadJSON(afterId: Int64, limit: Int, omitting: Set, + to buffer: inout [UInt8]) -> [UploadRowSpan]? { + guard let rows = fetchUploadJSON(afterId: afterId, limit: limit, omitting: omitting) else { return nil } + return rows.map { row in + guard let json = row.json else { return UploadRowSpan(id: row.id, range: nil) } + let start = buffer.count + buffer.append(contentsOf: json.utf8) + return UploadRowSpan(id: row.id, range: start.. UInt64 { DispatchTime.now().uptimeNanoseconds } + + /// CPU time of the current thread in nanoseconds + static func threadCPU() -> UInt64 { + #if canImport(Darwin) + return clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID) + #else + return 0 + #endif + } + + static func seconds(_ nanos: UInt64) -> TimeInterval { Double(nanos) / 1_000_000_000 } + + /// Seconds since `start` (nanoseconds from `now()`) + static func since(_ start: UInt64) -> TimeInterval { seconds(now() &- start) } + + /// CPU time of the whole app (every thread), user and system + static func processCPU() -> TimeInterval { + var usage = rusage() + getrusage(RUSAGE_SELF, &usage) + func s(_ t: timeval) -> TimeInterval { TimeInterval(t.tv_sec) + TimeInterval(t.tv_usec) / 1_000_000 } + return s(usage.ru_utime) + s(usage.ru_stime) + } + + /// Memory the app uses (what iOS counts toward its memory limit), in bytes + static func footprint() -> UInt64? { + #if canImport(Darwin) + var info = task_vm_info_data_t() + var count = mach_msg_type_number_t(MemoryLayout.size / MemoryLayout.size) + let result = withUnsafeMutablePointer(to: &info) { + $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { + task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count) + } + } + return result == KERN_SUCCESS ? info.phys_footprint : nil + #else + return nil + #endif + } +} + +// MARK: - Phases + +/// Where the device spent the time of a request, phase by phase. +public struct SyncPhaseTimes: Equatable { + /// Waiting for the database queue (the sensors' writes use it too) + public var dbWait: TimeInterval = 0 + /// Stepping through the rows in SQLite + public var dbRead: TimeInterval = 0 + /// Writing the rows as JSON + public var jsonEncode: TimeInterval = 0 + /// Measuring whether rows fit in the size limit (URL encoding for the legacy AWARE server) + public var sizeCheck: TimeInterval = 0 + /// Joining the rows into the request body + public var assemble: TimeInterval = 0 + /// Turning the body into bytes for the request + public var toData: TimeInterval = 0 + /// Deleting uploaded rows + public var delete: TimeInterval = 0 + /// CPU time of the preparation (reading to bytes) + public var prepareCPU: TimeInterval = 0 + + public init() {} + + /// Reading the rows to the bytes of the request + public var prepare: TimeInterval { dbWait + dbRead + jsonEncode + sizeCheck + assemble + toData } + + /// The phases with their names, in order + public var named: [(String, TimeInterval)] { + [("db wait", dbWait), ("db read", dbRead), ("json", jsonEncode), ("size check", sizeCheck), + ("assemble", assemble), ("to bytes", toData), ("delete", delete)] + } + + public static func + (a: SyncPhaseTimes, b: SyncPhaseTimes) -> SyncPhaseTimes { + var r = SyncPhaseTimes() + r.dbWait = a.dbWait + b.dbWait + r.dbRead = a.dbRead + b.dbRead + r.jsonEncode = a.jsonEncode + b.jsonEncode + r.sizeCheck = a.sizeCheck + b.sizeCheck + r.assemble = a.assemble + b.assemble + r.toData = a.toData + b.toData + r.delete = a.delete + b.delete + r.prepareCPU = a.prepareCPU + b.prepareCPU + return r + } + + /// Text like "db read 40 ms, json 25 ms, ... (CPU 60 ms)" + public var description: String { + named.filter { $0.1 >= 0.0005 }.map { "\($0.0) \(SyncDiagnostics.seconds($0.1))" }.joined(separator: ", ") + + " (CPU \(SyncDiagnostics.seconds(prepareCPU)))" + } +} /// One request of a sync. public struct SyncBatchMetrics: CustomStringConvertible { @@ -43,6 +144,11 @@ public struct SyncBatchMetrics: CustomStringConvertible { public let background: Bool public let lowPower: Bool public let thermalState: ProcessInfo.ThermalState + /// Phase by phase times of the preparation and the deletion on the device + public var phases = SyncPhaseTimes() + /// CPU use of the whole app since the previous request (100 = one core), and its memory + public var appCPUPercent: Double? + public var memoryMB: Double? /// Body bytes per second while the body was sent public var uploadBytesPerSecond: Double? { @@ -66,7 +172,11 @@ public struct SyncBatchMetrics: CustomStringConvertible { if background { parts.append("background") } if lowPower { parts.append("low power") } if thermalState == .serious || thermalState == .critical { parts.append("hot") } - return parts.joined(separator: ", ") + var text = parts.joined(separator: ", ") + text += " | phases: " + phases.description + if let cpu = appCPUPercent { text += String(format: " | app CPU %.0f%%", cpu) } + if let mb = memoryMB { text += String(format: ", memory %.0f MB", mb) } + return text } } @@ -106,6 +216,10 @@ public struct SyncRunSummary: CustomStringConvertible { public let retryWaitSeconds: TimeInterval public let lastLimitBytes: Int public let backgroundBatches: Int + /// Phase by phase times of every request together + public var phases = SyncPhaseTimes() + /// Largest memory use of the app during the sync + public var peakMemoryMB: Double? public var elapsedSeconds: TimeInterval { max(0, endedAt.timeIntervalSince(startedAt)) } public var rowsPerSecond: Double { elapsedSeconds > 0 ? Double(rows) / elapsedSeconds : 0 } @@ -150,6 +264,9 @@ public struct SyncRunSummary: CustomStringConvertible { + " | \(shares)" + (overlappedPrepareSeconds > 0 ? " | overlapped prepare \(SyncDiagnostics.seconds(overlappedPrepareSeconds))" : "") + " | bottleneck: \(bottleneck.rawValue)" + + " | device phases: " + phases.description + + (rows > 0 ? String(format: " | %.0f ms per 1000 rows prepared", phases.prepare / Double(rows) * 1_000_000) : "") + + (peakMemoryMB.map { String(format: " | peak memory %.0f MB", $0) } ?? "") } } @@ -189,6 +306,8 @@ struct SyncRunRecorder { var retryWait: TimeInterval = 0 var lastLimit = 0 var backgroundBatches = 0 + var phases = SyncPhaseTimes() + var peakMemoryMB: Double? init(table: String, host: String) { self.table = table @@ -212,17 +331,22 @@ struct SyncRunRecorder { if isRetryWait { retryWait += m.restSeconds } else { rest += m.restSeconds } lastLimit = m.limitBytes if m.background { backgroundBatches += 1 } + phases = phases + m.phases + if let mb = m.memoryMB { peakMemoryMB = max(peakMemoryMB ?? 0, mb) } } func summary(success: Bool, endedAt: Date = Date()) -> SyncRunSummary? { guard let startedAt, batches + failedRequests > 0 else { return nil } - return SyncRunSummary( + var summary = SyncRunSummary( table: table, host: host, startedAt: startedAt, endedAt: endedAt, success: success, batches: batches, failedRequests: failedRequests, rows: rows, bytes: bytes, prepareSeconds: prepare, overlappedPrepareSeconds: overlappedPrepare, networkSeconds: network, connectSeconds: connect, uploadSeconds: upload, serverSeconds: server, deleteSeconds: delete, restSeconds: rest, retryWaitSeconds: retryWait, lastLimitBytes: lastLimit, backgroundBatches: backgroundBatches) + summary.phases = phases + summary.peakMemoryMB = peakMemoryMB + return summary } } @@ -237,11 +361,27 @@ public final class SyncDiagnostics { public var printsToConsole = false private let lock = NSLock() + private var loadSample: (time: UInt64, cpu: TimeInterval)? private var batches: [SyncBatchMetrics] = [] private var summaries: [String: SyncRunSummary] = [:] private init() {} + /// CPU use of the whole app since the last call (100 = one core), and its memory in MB + func sampleLoad() -> (cpuPercent: Double?, memoryMB: Double?) { + let now = SyncClock.now() + let cpu = SyncClock.processCPU() + lock.lock() + let previous = loadSample + loadSample = (now, cpu) + lock.unlock() + var percent: Double? + if let previous, now > previous.time { + percent = (cpu - previous.cpu) / SyncClock.seconds(now - previous.time) * 100 + } + return (percent, SyncClock.footprint().map { Double($0) / 1_000_000 }) + } + func record(_ batch: SyncBatchMetrics) { lock.lock() batches.append(batch) diff --git a/Sources/com.awareframework.ios.core/db/core/SyncPacing.swift b/Sources/com.awareframework.ios.core/db/core/SyncPacing.swift index ab293e9..6a41e0d 100644 --- a/Sources/com.awareframework.ios.core/db/core/SyncPacing.swift +++ b/Sources/com.awareframework.ios.core/db/core/SyncPacing.swift @@ -111,11 +111,12 @@ enum SyncPacing { /// The largest request body a sync sends to a host. /// -/// - Default: `DbSyncConfig.maxBatchBytes`, or 4 MB when it is not set, for every server type +/// - Default: `DbSyncConfig.maxBatchBytes`, or 500 KB when it is not set, for every server type /// (AWARE Micro, and the AWARE server, whose PHP version is retired and whose endpoints are served -/// by Flask; Google App Engine accepts up to 32 MB). The margin keeps uploads short on slow -/// networks and keeps memory use low. A server with a smaller limit (for example nginx, 1 MB by -/// default) answers 413, and the limit is lowered and remembered (below). +/// by Flask). 500 KB is Flask's default limit of a form field (Werkzeug 3.1 `MAX_FORM_MEMORY_SIZE`), +/// and the AWARE server receives all rows of a request in one form field, so a server with default +/// settings never rejects the first requests. A server with a higher limit gets larger requests +/// by growth (below). A server with a smaller limit (413) gets a smaller size, which is remembered. /// - Growth (like `AWAREFetchSizeAdjuster` of AWAREFramework-iOS 1.x): after `growAfterFullSuccesses` /// requests in a row that were filled up to the limit and finished within `growMaxNetworkSeconds`, /// the limit grows by half, up to the ceiling (`DbSyncConfig.maxBatchBytesCeiling`; 8 MB by @@ -127,8 +128,9 @@ enum SyncPacing { /// changes), and grows back after `growAfterSuccesses` successful requests. public enum SyncBatchLimit { - /// Default request size, for every server type - public static let defaultBytes = 4_000_000 + /// Default request size, for every server type: Flask's default form field limit + /// (Werkzeug 3.1 `MAX_FORM_MEMORY_SIZE` = 500,000 bytes) + public static let defaultBytes = 500_000 /// Default ceiling of the growth, for every server type (Google App Engine accepts 32 MB). Kept /// well below it: each table holds the body in flight and the prefetched next one, and several /// tables upload at the same time, so larger bodies risk the app's memory limit. @@ -279,13 +281,75 @@ public enum SyncBatchLimit { } } + /// The key a sync uses for `host` (a server URL or host name): the host without `http://` or `https://`. + public static func hostKey(_ host: String) -> String { + AwareUtils.cleanHostName(host.trimmingCharacters(in: .whitespacesAndNewlines)) + } + + /// What is known about the request size for a host, for display. + public struct State: Equatable { + public let host: String + /// The configured or default size (`DbSyncConfig.maxBatchBytes`) + public let configuredBytes: Int + /// The largest size growth may reach (`DbSyncConfig.maxBatchBytesCeiling`) + public let ceilingBytes: Int + /// The size the next request uses + public let currentBytes: Int + /// Size reached by growth (saved), if above the configured size + public let grownBytes: Int? + /// Limit learned from a 413 (saved) + public let tooLargeLimitBytes: Int? + /// Smallest body the host rejected with 413 (saved); growth stays below 90 % of it + public let rejectedBytes: Int? + /// Limit after a timeout (this run of the app only) + public let timeoutLimitBytes: Int? + + /// Whether anything learned is in effect + public var hasLearned: Bool { + grownBytes != nil || tooLargeLimitBytes != nil || rejectedBytes != nil || timeoutLimitBytes != nil + } + } + + /// What is known about `host` (a server URL or host name) under `config`. + public static func state(host: String, config: DbSyncConfig) -> State { + let key = hostKey(host) + lock.lock() + defer { lock.unlock() } + let defaults = UserDefaults.standard + func saved(_ prefix: String) -> Int? { + let v = defaults.integer(forKey: prefix + key) + return v > 0 ? v : nil + } + let grown = saved(grownKeyPrefix).flatMap { $0 > configured(config) ? $0 : nil } + return State( + host: key, configuredBytes: configured(config), ceilingBytes: ceiling(config), + currentBytes: currentLocked(host: key, config: config), grownBytes: grown, + tooLargeLimitBytes: saved(keyPrefix), rejectedBytes: saved(rejectedKeyPrefix), + timeoutLimitBytes: timeoutLimits[key]) + } + + /// Hosts with saved learned values. + public static func learnedHosts() -> [String] { + let prefixes = [keyPrefix, grownKeyPrefix, rejectedKeyPrefix] + var hosts = Set() + for key in UserDefaults.standard.dictionaryRepresentation().keys { + if let prefix = prefixes.first(where: { key.hasPrefix($0) }) { + hosts.insert(String(key.dropFirst(prefix.count))) + } + } + lock.lock() + hosts.formUnion(timeoutLimits.keys) + lock.unlock() + return hosts.sorted() + } + /// Forget what was learned about `host` (or every host). public static func reset(host: String? = nil) { lock.lock() defer { lock.unlock() } let defaults = UserDefaults.standard let prefixes = [keyPrefix, grownKeyPrefix, rejectedKeyPrefix] - if let host { + if let host = host.map(hostKey) { prefixes.forEach { defaults.removeObject(forKey: $0 + host) } timeoutLimits[host] = nil successes[host] = nil diff --git a/Sources/com.awareframework.ios.core/db/core/UploadJSONBytes.swift b/Sources/com.awareframework.ios.core/db/core/UploadJSONBytes.swift new file mode 100644 index 0000000..6e672c0 --- /dev/null +++ b/Sources/com.awareframework.ios.core/db/core/UploadJSONBytes.swift @@ -0,0 +1,165 @@ +// +// UploadJSONBytes.swift +// com.awareframework.ios.core +// +// Upload rows written as JSON straight into one byte buffer, and the URL encoding of the form +// body for the legacy AWARE server. The text is the same as `UploadJSONWriter` writes with +// strings; bytes avoid making a string for every row and every value. +// + +import Foundation + +/// A row written into a byte buffer by `Engine.appendUploadJSON(afterId:limit:omitting:to:)`: +/// its ID, and where its JSON object is in the buffer (nil when the row cannot be written as JSON). +public struct UploadRowSpan { + public let id: Int64 + public let range: Range? + + public init(id: Int64, range: Range?) { + self.id = id + self.range = range + } +} + +/// Writes JSON values as UTF-8 bytes: the same text as `UploadJSONWriter`. +enum JSONBytes { + + /// `"key":` + static func key(_ key: String) -> [UInt8] { + var out: [UInt8] = [] + appendString(key, to: &out) + out.append(UInt8(ascii: ":")) + return out + } + + /// An integer, digit by digit (no string is made) + static func appendInt(_ value: Int64, to out: inout [UInt8]) { + if value == 0 { + out.append(UInt8(ascii: "0")) + return + } + var digits: (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, + UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) = + (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + var count = 0 + // The magnitude as UInt64, so that Int64.min has one + var magnitude = value.magnitude + withUnsafeMutableBytes(of: &digits) { buffer in + while magnitude > 0 { + buffer[count] = UInt8(ascii: "0") + UInt8(magnitude % 10) + magnitude /= 10 + count += 1 + } + } + if value < 0 { out.append(UInt8(ascii: "-")) } + withUnsafeBytes(of: &digits) { buffer in + for i in stride(from: count - 1, through: 0, by: -1) { out.append(buffer[i]) } + } + } + + /// A number with the shortest text that reads back as the same Double. Returns false for + /// infinity and NaN, which JSON cannot hold. + static func appendDouble(_ value: Double, to out: inout [UInt8]) -> Bool { + guard value.isFinite else { return false } + // Most texts fit in a small string, which needs no allocation + var text = value.description + text.withUTF8 { out.append(contentsOf: $0) } + return true + } + + /// A string from `String` + static func appendString(_ text: String, to out: inout [UInt8]) { + var text = text + text.withUTF8 { appendString(utf8: $0, to: &out) } + } + + /// A string from valid UTF-8 bytes. Only `"`, `\` and control characters are escaped; other + /// bytes, including those of non-ASCII characters, are copied. + static func appendString(utf8 bytes: UnsafeBufferPointer, to out: inout [UInt8]) { + out.append(UInt8(ascii: "\"")) + var plainStart = 0 + for i in 0..> 4)], hex[Int(b & 0x0F)]]) + } + plainStart = i + 1 + } + if plainStart < bytes.count { + out.append(contentsOf: UnsafeBufferPointer(rebasing: bytes[plainStart..) -> Int { + var length = 0 + for b in bytes { length += plain[Int(b)] ? 1 : 3 } + return length + } + + static func encodedLength(_ text: String) -> Int { + var text = text + return text.withUTF8 { encodedLength($0) } + } + + /// Appends `bytes`, encoded, to `out` + static func append(_ bytes: UnsafeBufferPointer, to out: inout [UInt8]) { + for b in bytes { + if plain[Int(b)] { + out.append(b) + } else { + out.append(UInt8(ascii: "%")) + out.append(hex[Int(b >> 4)]) + out.append(hex[Int(b & 0x0F)]) + } + } + } + + static func append(_ text: String, to out: inout [UInt8]) { + var text = text + text.withUTF8 { append($0, to: &out) } + } + + /// `name=value&name=value`, in the given order + static func body(_ fields: [(String, String)]) -> String { + var out: [UInt8] = [] + for (i, (name, value)) in fields.enumerated() { + if i > 0 { out.append(UInt8(ascii: "&")) } + append(name, to: &out) + out.append(UInt8(ascii: "=")) + append(value, to: &out) + } + return String(decoding: out, as: UTF8.self) + } +} diff --git a/Sources/com.awareframework.ios.core/db/sqlite/SQLiteEngine.swift b/Sources/com.awareframework.ios.core/db/sqlite/SQLiteEngine.swift index 098da74..c2c0e3d 100644 --- a/Sources/com.awareframework.ios.core/db/sqlite/SQLiteEngine.swift +++ b/Sources/com.awareframework.ios.core/db/sqlite/SQLiteEngine.swift @@ -1,5 +1,6 @@ import Foundation import GRDB +import GRDBSQLite private final class SQLiteSyncStopNotificationObserver: NSObject, @unchecked Sendable { static let shared = SQLiteSyncStopNotificationObserver() @@ -192,10 +193,12 @@ open class SQLiteEngine: Engine { open override func save(_ data: [any BaseDbModelSQLite], completion: ((Error?) -> Void)?) { do { - guard let queue = getSQLiteInstance() else { - completion?(nil) - return + guard let url = sqliteFileURL else { + throw CocoaError(.fileNoSuchFile, userInfo: [ + NSLocalizedDescriptionKey: "SQLite database path is not configured." + ]) } + let queue = try Self.databaseQueue(for: url.path) try Self.retryLockedDatabaseWork { try queue.write { db in try db.execute(sql: "PRAGMA busy_timeout = 10000") @@ -266,62 +269,148 @@ open class SQLiteEngine: Engine { /// Upload rows written as JSON straight from the SQLite values, without a dictionary per row. /// See `Engine.fetchUploadJSON(afterId:limit:omitting:)`. public override func fetchUploadJSON(afterId: Int64, limit: Int, omitting: Set) -> [UploadRowJSON]? { + var buffer: [UInt8] = [] + guard let spans = appendUploadJSON(afterId: afterId, limit: limit, omitting: omitting, to: &buffer) else { + return nil + } + return spans.map { span in + UploadRowJSON(id: span.id, json: span.range.map { String(decoding: buffer[$0], as: UTF8.self) }) + } + } + + /// See `Engine.appendUploadJSON(afterId:limit:omitting:to:)`. The values are read with the SQLite + /// C API and written as JSON bytes: the column keys are made once per query, numbers are written + /// without making strings, and a text column that repeats the previous row's value (device ID, + /// OS, time zone...) reuses its JSON. + public override func appendUploadJSON(afterId: Int64, limit: Int, omitting: Set, + to out: inout [UInt8]) -> [UploadRowSpan]? { guard let tableName = config.tableName, let db = getSQLiteInstance() else { return nil } let sql = "SELECT * FROM \(tableName) WHERE id > ? ORDER BY rowid LIMIT ?" + var timing = UploadJSONTiming() + let called = SyncClock.now() + defer { lastUploadJSONTiming = timing } + let rollback = out.count do { return try Self.retryLockedDatabaseWork { - try db.read { db -> [UploadRowJSON]? in - let cursor = try Row.fetchCursor(db, sql: sql, arguments: [afterId, max(0, limit)]) - var results: [UploadRowJSON] = [] - results.reserveCapacity(max(0, limit)) - var json = "" - while let row = try cursor.next() { - var id: Int64? + out.removeSubrange(rollback...) // a retried attempt starts again + return try db.read { db -> [UploadRowSpan]? in + let entered = SyncClock.now() + let cpuStart = SyncClock.threadCPU() + timing.queueWait = SyncClock.seconds(entered &- called) + var readNanos: UInt64 = 0 + var encodeNanos: UInt64 = 0 + defer { + timing.read = SyncClock.seconds(readNanos) + timing.encode = SyncClock.seconds(encodeNanos) + timing.cpu = SyncClock.seconds(SyncClock.threadCPU() &- cpuStart) + } + var t = SyncClock.now() + let statement = try db.makeStatement(sql: sql) + let stmt = statement.sqliteStatement + let columnCount = Int(sqlite3_column_count(stmt)) + var keys: [[UInt8]] = [] + var included: [Bool] = [] + var idColumn: Int32? + for i in 0..= 0x80 }) { + JSONBytes.appendString(String(decoding: bytes, as: UTF8.self), to: &out) + } else { + JSONBytes.appendString(utf8: bytes, to: &out) + } + if caching { + cacheMisses[i] += lastJSON[i].isEmpty ? 0 : 1 + lastText[i] = Array(bytes) + lastJSON[i] = Array(out[start...]) + } + } + public override func fetch( filter: String? = nil, limit: Int? = nil, completion: (([[String: Any]]?, Error?) -> Void)? @@ -427,6 +516,26 @@ open class SQLiteEngine: Engine { // MARK: - Sync + /// The bodies of the next `batches` upload requests of this table, without sending anything or + /// changing anything (see `DbSyncHelper.previewRequests(batches:)`). For checks. + public func previewUploadRequests(config syncConfig: DbSyncConfig, batches: Int, + host: String = "benchmark.invalid") -> [DbSyncHelper.PreviewRequest] { + guard let tableName = config.tableName else { return [] } + let helper = DbSyncHelper(engine: self, host: host, tableName: tableName, config: syncConfig) + return helper.previewRequests(batches: batches) + } + + /// Measure how long preparing upload requests of this table takes on this device, without + /// sending anything or changing anything (see `DbSyncHelper.benchmarkPreparation(batches:)`). + /// `host` only names the size limit to use: the default host has nothing learned, so the + /// requests have the size of `config.maxBatchBytes` (or the default). + public func benchmarkUploadPreparation(config syncConfig: DbSyncConfig, batches: Int, + host: String = "benchmark.invalid") -> [SyncBatchMetrics] { + guard let tableName = config.tableName else { return [] } + let helper = DbSyncHelper(engine: self, host: host, tableName: tableName, config: syncConfig) + return helper.benchmarkPreparation(batches: batches) + } + /// The upload of one table of one database. Shared by every engine of that table, so that two /// syncs of the same rows never run at the same time. final class SyncSlot { diff --git a/Sources/com.awareframework.ios.core/manager/UploadScheduler.swift b/Sources/com.awareframework.ios.core/manager/UploadScheduler.swift new file mode 100644 index 0000000..e15b47b --- /dev/null +++ b/Sources/com.awareframework.ios.core/manager/UploadScheduler.swift @@ -0,0 +1,379 @@ +// +// UploadScheduler.swift +// com.awareframework.ios.core +// +// When to upload: a repeating timer, the device starting to charge, and (iOS) uploads in the +// background - an upload that is running when the app leaves the screen goes on while iOS allows +// it, and iOS runs uploads later (BGProcessingTask) while the app is not running. Before an +// upload starts, the scheduler checks the conditions (Wi-Fi only, charging only, an upload that +// is already running). +// +// The app says how to upload (`performUpload`), so it can show the progress of each sensor; by +// default the scheduler posts `Notification.Name.Aware.dbSyncRequest`, which every enabled sensor +// observes (see `AwareSensor.enable()`). +// +// Usage (iOS): +// +// // application(_:didFinishLaunchingWithOptions:), before it returns +// UploadScheduler.shared.registerBackgroundTask(identifier: "com.example.app.upload") +// +// UploadScheduler.shared.performUpload = { trigger, done in +// startUploadOfAllSensors(onEnd: done) +// } +// UploadScheduler.shared.configuration = .init(automatic: true, interval: 15 * 60, wifiOnly: true) +// +// `BGTaskSchedulerPermittedIdentifiers` in Info.plist must list the identifier, and +// `UIBackgroundModes` must contain `processing`. +// + +import Foundation +import Network +#if os(iOS) + import BackgroundTasks + import UIKit +#endif + +public final class UploadScheduler { + + public static let shared = UploadScheduler() + + // MARK: Configuration + + public struct Configuration: Equatable { + /// Upload by the timer, when charging starts, and in the background. Manual uploads + /// (`requestUpload(.manual)`) work either way. + public var automatic: Bool + /// Time between automatic uploads + public var interval: TimeInterval + /// Upload only on Wi-Fi + public var wifiOnly: Bool + /// Upload only while the device is charging (or full) + public var chargingOnly: Bool + /// Also upload when the device starts charging + public var uploadOnChargingStart: Bool + /// Keep uploading in the background (iOS): finish a running upload after the app leaves the + /// screen, and let iOS run automatic uploads while the app is not running + public var inBackground: Bool + + public init(automatic: Bool = false, interval: TimeInterval = 15 * 60, wifiOnly: Bool = true, + chargingOnly: Bool = false, uploadOnChargingStart: Bool = true, inBackground: Bool = true) { + self.automatic = automatic + self.interval = max(60, interval) + self.wifiOnly = wifiOnly + self.chargingOnly = chargingOnly + self.uploadOnChargingStart = uploadOnChargingStart + self.inBackground = inBackground + } + } + + /// What started an upload + public enum Trigger: String { + case manual + case timer + case chargingStarted + case background + } + + /// Why an upload did not start + public enum SkipReason: String, Error { + case automaticUploadOff = "Automatic upload is off" + case uploadRunning = "An upload is already in progress" + case waitingForWiFi = "Skipped while waiting for Wi-Fi" + case waitingForCharging = "Skipped while waiting for charging" + case tooSoonAfterChargingUpload = "An upload started when charging started a moment ago" + } + + /// The settings. Setting them restarts the timer and the background schedule. + public var configuration = Configuration() { + didSet { + guard configuration != oldValue else { return } + onMain { self.reschedule() } + } + } + + /// How to upload. Call `done` when the upload has ended (or failed), so the scheduler knows + /// when it may start another one and when the background time can be given back. + /// Default: post `Notification.Name.Aware.dbSyncRequest` and end at once. + public var performUpload: ((_ trigger: Trigger, _ done: @escaping () -> Void) -> Void)? + + /// Called on the main thread when an upload is started or skipped (for logs and the UI) + public var onEvent: ((_ trigger: Trigger, _ skipped: SkipReason?) -> Void)? + + /// Charging that starts again within this time (a loose cable) does not start another upload + public var chargingStartInterval: TimeInterval = 10 * 60 + + // MARK: State + + /// Whether the device is on Wi-Fi (updated by NWPathMonitor) + public var isWiFiAvailable: Bool { lock.withLock { wifi } } + + /// Whether the device is charging or full + public var isCharging: Bool { + #if os(iOS) + if Thread.isMainThread { return Self.chargingState() } + return DispatchQueue.main.sync { Self.chargingState() } + #else + return true + #endif + } + + /// Whether an upload started by the scheduler, or reported with `uploadDidStart()`, is running + public var isUploading: Bool { lock.withLock { activeUploads > 0 } } + + /// When the last upload started, and why + public private(set) var lastUploadStart: (date: Date, trigger: Trigger)? + + private let lock = NSLock() + private var wifi = false + private var activeUploads = 0 + private var timer: Timer? + private var lastChargingStartUpload: Date? + private var wasCharging = false + private var started = false + private let pathMonitor = NWPathMonitor() + private var observers: [NSObjectProtocol] = [] + #if os(iOS) + private var backgroundTime: UIBackgroundTaskIdentifier = .invalid + private var backgroundTaskIdentifier: String? + #endif + + private init() { + pathMonitor.pathUpdateHandler = { [weak self] path in + let onWiFi = path.status == .satisfied && path.usesInterfaceType(.wifi) + self?.lock.withLock { self?.wifi = onWiFi } + } + pathMonitor.start(queue: DispatchQueue(label: "com.awareframework.upload-scheduler.network", qos: .utility)) + } + + // MARK: - Decisions + + /// Whether an upload may start now (pure, for tests). + public static func check(trigger: Trigger, configuration: Configuration, wifi: Bool, charging: Bool, + uploading: Bool) -> SkipReason? { + if trigger != .manual && configuration.automatic == false { return .automaticUploadOff } + if uploading { return .uploadRunning } + if configuration.wifiOnly && wifi == false { return .waitingForWiFi } + if configuration.chargingOnly && charging == false { return .waitingForCharging } + return nil + } + + // MARK: - Uploads + + /// Start an upload if the conditions allow it. + /// - Returns: Why it did not start, or nil when it started. + @discardableResult + public func requestUpload(_ trigger: Trigger) -> SkipReason? { + guard Thread.isMainThread else { + return DispatchQueue.main.sync { requestUpload(trigger) } + } + if let reason = Self.check(trigger: trigger, configuration: configuration, wifi: isWiFiAvailable, + charging: isCharging, uploading: isUploading) { + onEvent?(trigger, reason) + return reason + } + uploadDidStart() + lastUploadStart = (Date(), trigger) + onEvent?(trigger, nil) + let done: () -> Void = { [weak self] in self?.onMain { self?.uploadDidFinish() } } + if let performUpload { + performUpload(trigger, done) + } else { + NotificationCenter.default.post(name: Notification.Name.Aware.dbSyncRequest, object: nil) + done() + } + return nil + } + + /// Report an upload the app started itself (for example a single sensor), so the scheduler + /// does not start another one meanwhile and keeps it running in the background. + public func uploadDidStart() { + lock.withLock { activeUploads += 1 } + } + + /// Report the end of an upload reported with `uploadDidStart()`. + public func uploadDidFinish() { + let idle = lock.withLock { () -> Bool in + activeUploads = max(0, activeUploads - 1) + return activeUploads == 0 + } + #if os(iOS) + if idle { onMain { self.endBackgroundTime() } } + #endif + } + + // MARK: - Start and stop + + /// Start the timer and observe charging and the app state. Called by setting `configuration` + /// too; call it once at launch. + public func start() { + onMain { + guard self.started == false else { return } + self.started = true + self.observe() + self.reschedule() + } + } + + /// Stop the timer and cancel the background schedule. + public func stop() { + onMain { + self.timer?.invalidate() + self.timer = nil + #if os(iOS) + self.cancelBackgroundTask() + #endif + } + } + + private func reschedule() { + guard started else { return } + timer?.invalidate() + timer = nil + if configuration.automatic { + let t = Timer.scheduledTimer(withTimeInterval: configuration.interval, repeats: true) { [weak self] _ in + self?.requestUpload(.timer) + } + t.tolerance = min(configuration.interval * 0.1, 60) + timer = t + } + #if os(iOS) + scheduleBackgroundTask() + #endif + } + + private func observe() { + #if os(iOS) + UIDevice.current.isBatteryMonitoringEnabled = true + wasCharging = Self.chargingState() + let center = NotificationCenter.default + observers.append(center.addObserver( + forName: UIDevice.batteryStateDidChangeNotification, object: nil, queue: .main + ) { [weak self] _ in self?.batteryStateDidChange() }) + observers.append(center.addObserver( + forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main + ) { [weak self] _ in + self?.extendRunningUpload() + self?.scheduleBackgroundTask() + }) + #endif + } + + // MARK: - Charging + + #if os(iOS) + private static func chargingState() -> Bool { + let state = UIDevice.current.batteryState + return state == .charging || state == .full + } + + /// Upload when charging starts (iOS reports it only while the app runs) + private func batteryStateDidChange() { + let charging = Self.chargingState() + defer { wasCharging = charging } + guard charging, wasCharging == false, configuration.uploadOnChargingStart else { return } + if let last = lastChargingStartUpload, Date().timeIntervalSince(last) < chargingStartInterval { + onEvent?(.chargingStarted, .tooSoonAfterChargingUpload) + return + } + if requestUpload(.chargingStarted) == nil { + lastChargingStartUpload = Date() + } + } + #endif + + // MARK: - Background (iOS) + + #if os(iOS) + /// Register the background upload task. Call it before `application(_:didFinishLaunchingWithOptions:)` + /// returns. The identifier must be listed in `BGTaskSchedulerPermittedIdentifiers`. + public func registerBackgroundTask(identifier: String) { + backgroundTaskIdentifier = identifier + BGTaskScheduler.shared.register(forTaskWithIdentifier: identifier, using: .main) { [weak self] task in + guard let self, let task = task as? BGProcessingTask else { + task.setTaskCompleted(success: false) + return + } + self.runBackgroundTask(task) + } + } + + /// An upload that is running when the app enters the background goes on while iOS allows + private func extendRunningUpload() { + guard configuration.inBackground, isUploading, backgroundTime == .invalid else { return } + backgroundTime = UIApplication.shared.beginBackgroundTask(withName: "AWARE upload") { [weak self] in + // Time is up. Requests in flight end; their rows are sent again at the next upload. + self?.endBackgroundTime() + } + } + + private func endBackgroundTime() { + guard backgroundTime != .invalid else { return } + UIApplication.shared.endBackgroundTask(backgroundTime) + backgroundTime = .invalid + } + + /// Ask iOS to run an upload later, while the app may not be running. iOS chooses the time + /// (often while the device is charging and idle), never earlier than one interval from now. + private func scheduleBackgroundTask() { + guard let identifier = backgroundTaskIdentifier else { return } + guard configuration.automatic, configuration.inBackground else { + BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: identifier) + return + } + let request = BGProcessingTaskRequest(identifier: identifier) + request.requiresNetworkConnectivity = true + request.requiresExternalPower = configuration.chargingOnly + request.earliestBeginDate = Date(timeIntervalSinceNow: configuration.interval) + do { + try BGTaskScheduler.shared.submit(request) + } catch { + print("[AWARE::UploadScheduler] could not schedule the background upload: \(error)") + } + } + + private func cancelBackgroundTask() { + guard let identifier = backgroundTaskIdentifier else { return } + BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: identifier) + } + + /// Run by iOS in the background: upload, and complete the task when the upload ends + private func runBackgroundTask(_ task: BGProcessingTask) { + scheduleBackgroundTask() + var completed = false + let complete = { (success: Bool) in + guard completed == false else { return } + completed = true + task.setTaskCompleted(success: success) + } + task.expirationHandler = { + // iOS needs the time back. Requests in flight end; their rows are sent again later. + complete(false) + } + // Wait a moment for the network monitor, which starts with the app + DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [weak self] in + guard let self, completed == false else { return } + guard self.requestUpload(.background) == nil else { return complete(true) } + self.waitUntilIdle { complete(true) } + } + } + + private func waitUntilIdle(_ then: @escaping () -> Void) { + DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in + guard let self else { return then() } + self.isUploading ? self.waitUntilIdle(then) : then() + } + } + #endif + + private func onMain(_ work: @escaping () -> Void) { + Thread.isMainThread ? work() : DispatchQueue.main.async(execute: work) + } +} + +private extension NSLock { + func withLock(_ body: () -> T) -> T { + lock() + defer { unlock() } + return body() + } +} diff --git a/Sources/com.awareframework.ios.core/model/SensorConfig.swift b/Sources/com.awareframework.ios.core/model/SensorConfig.swift index 8691986..559c57a 100644 --- a/Sources/com.awareframework.ios.core/model/SensorConfig.swift +++ b/Sources/com.awareframework.ios.core/model/SensorConfig.swift @@ -80,6 +80,8 @@ open class SensorConfig{ self.serverType = .aware_micro } else if serverType == 4 { self.serverType = .aware_light + } else if serverType == 5 { + self.serverType = .aware_hub } } diff --git a/Tests/com.awareframework.ios.coreTests/AwareHubTests.swift b/Tests/com.awareframework.ios.coreTests/AwareHubTests.swift new file mode 100644 index 0000000..ef923de --- /dev/null +++ b/Tests/com.awareframework.ios.coreTests/AwareHubTests.swift @@ -0,0 +1,97 @@ +// +// AwareHubTests.swift +// com.awareframework.ios.core.Tests +// +// AWARE Hub: the upload requests (URL with the study, JSON body compressed with deflate). +// + +import XCTest +import Foundation +import GRDB +@testable import com_awareframework_ios_core + +final class AwareHubTests: XCTestCase { + + private let host = "https://Hub.Example.org/" + private let table = "hub_test" + private var path = "" + + override func setUp() { + super.setUp() + path = "hub_test_\(UUID().uuidString)" + } + + override func tearDown() { + DbSyncUtils.clearLastUploadedId(for: table) + SyncBatchLimit.reset() + super.tearDown() + } + + private func makeHelper(serverType: ServerType) throws -> DbSyncHelper { + let config = Engine.EngineConfig() + config.path = path + config.tableName = table + let engine = SQLiteEngine(config) + let queue = try XCTUnwrap(engine.getSQLiteInstance()) + try queue.write { db in + try db.execute(sql: "CREATE TABLE \(table) (id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp INTEGER, label TEXT, x REAL)") + for i in 0..<300 { + try db.execute(sql: "INSERT INTO \(table) (timestamp, label, x) VALUES (?, ?, ?)", + arguments: [1_700_000_000_000 + i, "C:\\temp\\new, \"q\" +1 日本 \(i)", Double(i) / 7]) + } + } + let sync = DbSyncConfig() + sync.serverType = serverType + sync.studyNumber = 7 + sync.studyKey = "key 7" + return DbSyncHelper(engine: engine, host: host, tableName: table, config: sync) + } + + func testHubRequestIsCompressedJSON() throws { + let helper = try makeHelper(serverType: .aware_hub) + let body = try XCTUnwrap(helper.previewRequests(batches: 1).first?.body) + let request = try XCTUnwrap(helper.buildHTTPRequest(with: body)) + + XCTAssertEqual(request.url?.absoluteString.lowercased(), "https://hub.example.org/v1/7/key%207/insert") + XCTAssertNil(request.value(forHTTPHeaderField: "Authorization")) + XCTAssertEqual(request.value(forHTTPHeaderField: "Content-Type"), "application/json") + XCTAssertEqual(request.value(forHTTPHeaderField: "Content-Encoding"), "deflate") + let sent = try XCTUnwrap(request.httpBody) + XCTAssertLessThan(sent.count, body.count / 3) + let restored = try (sent as NSData).decompressed(using: .zlib) as Data + XCTAssertEqual(restored, body) + + let envelope = try XCTUnwrap(JSONSerialization.jsonObject(with: restored) as? [String: Any]) + XCTAssertEqual(envelope["tableName"] as? String, table) + XCTAssertEqual(envelope["deviceId"] as? String, AwareUtils.getCommonDeviceId()) + let rows = try XCTUnwrap(envelope["data"] as? [[String: Any]]) + XCTAssertEqual(rows.count, 300) + XCTAssertEqual(rows[5]["label"] as? String, "C:\\temp\\new, \"q\" +1 日本 5") + + // For a check against the server (tests of AWARE Hub post it with Content-Encoding: deflate) + if let dir = ProcessInfo.processInfo.environment["AWARE_DUMP_DIR"] { + try sent.write(to: URL(fileURLWithPath: dir).appendingPathComponent("hub-request.deflate")) + try restored.write(to: URL(fileURLWithPath: dir).appendingPathComponent("hub-request.json")) + } + } + + func testOtherServersUnchanged() throws { + let helper = try makeHelper(serverType: .aware) + let body = Data("device_id=a&data=%5B%5D".utf8) + let request = try XCTUnwrap(helper.buildHTTPRequest(with: body)) + XCTAssertNil(request.value(forHTTPHeaderField: "Content-Encoding")) + XCTAssertEqual(request.httpBody, body) + XCTAssertTrue(request.url?.path.hasPrefix("/index.php/webservice/index/7/") ?? false) + } + + func testDeflateOfEmptyBody() { + XCTAssertNil(DbSyncHelper.deflate(Data())) + } + + func testServerTypeFromConfig() { + XCTAssertEqual(DbSyncConfig(["serverType": 5]).serverType, .aware_hub) + let sensor = SensorConfig() + sensor.set(config: ["serverType": 5]) + XCTAssertEqual(sensor.serverType, .aware_hub) + } +} diff --git a/Tests/com.awareframework.ios.coreTests/DbSyncBatchingTests.swift b/Tests/com.awareframework.ios.coreTests/DbSyncBatchingTests.swift index 4a935c3..d7f16e7 100644 --- a/Tests/com.awareframework.ios.coreTests/DbSyncBatchingTests.swift +++ b/Tests/com.awareframework.ios.coreTests/DbSyncBatchingTests.swift @@ -55,10 +55,9 @@ final class DbSyncBatchingTests: XCTestCase { } /// Run a sync to the end and return the request bodies it sent - private func sync(server: ServerType, compact: Bool = false, bodyHandler: Bool = false, + private func sync(server: ServerType, bodyHandler: Bool = false, file: StaticString = #filePath, line: UInt = #line) -> (bodies: [Data], helper: DbSyncHelper) { config.serverType = server - config.compactDataFormat = compact let helper = DbSyncHelper(engine: engine, host: host, tableName: table, config: config) var bodies: [Data] = [] let lock = NSLock() @@ -129,14 +128,9 @@ final class DbSyncBatchingTests: XCTestCase { XCTAssertEqual(ids, (1...1500).map(Int64.init)) } - func testCompactFormatAndBodyHandlerStayWithinLimit() { + func testBodyHandlerStaysWithinLimit() { engine.mockData = rows(2000) config.maxBatchBytes = 40_000 - let compact = sync(server: .aware_micro, compact: true).bodies - XCTAssertGreaterThan(compact.count, 1) - compact.forEach { XCTAssertLessThanOrEqual($0.count, 40_000) } - - DbSyncUtils.clearLastUploadedId(for: table) let handled = sync(server: .aware_micro, bodyHandler: true).bodies handled.forEach { XCTAssertLessThanOrEqual($0.count, 40_000) } XCTAssertEqual(handled.flatMap(jsonRows).count, 2000) @@ -162,8 +156,8 @@ final class DbSyncBatchingTests: XCTestCase { func testDefaultLimitByServerType() { let micro = DbSyncConfig(); micro.serverType = .aware_micro let legacy = DbSyncConfig(); legacy.serverType = .aware - XCTAssertEqual(SyncBatchLimit.configured(micro), 4_000_000) - XCTAssertEqual(SyncBatchLimit.configured(legacy), 4_000_000, "the same for every server type") + XCTAssertEqual(SyncBatchLimit.configured(micro), 500_000, "Flask's default form field limit") + XCTAssertEqual(SyncBatchLimit.configured(legacy), 500_000, "the same for every server type") XCTAssertEqual(SyncBatchLimit.ceiling(micro), 8_000_000) XCTAssertEqual(SyncBatchLimit.ceiling(legacy), 8_000_000) legacy.maxBatchBytes = 2_000_000 @@ -174,28 +168,28 @@ final class DbSyncBatchingTests: XCTestCase { func testTooLargeHalvesAndIsRemembered() { let c = DbSyncConfig(); c.serverType = .aware_micro - XCTAssertEqual(SyncBatchLimit.current(host: "h1", config: c), 4_000_000) - XCTAssertEqual(SyncBatchLimit.recordTooLarge(host: "h1", bodyBytes: 4_000_000), 2_000_000) - SyncBatchLimit.recordTooLarge(host: "h1", bodyBytes: 2_000_000) - XCTAssertEqual(SyncBatchLimit.current(host: "h1", config: c), 1_000_000, "4 MB -> 2 MB -> 1 MB") - XCTAssertEqual(UserDefaults.standard.integer(forKey: SyncBatchLimit.keyPrefix + "h1"), 1_000_000, "saved") - XCTAssertEqual(SyncBatchLimit.current(host: "other", config: c), 4_000_000, "per host") + XCTAssertEqual(SyncBatchLimit.current(host: "h1", config: c), 500_000) + XCTAssertEqual(SyncBatchLimit.recordTooLarge(host: "h1", bodyBytes: 500_000), 250_000) + SyncBatchLimit.recordTooLarge(host: "h1", bodyBytes: 250_000) + XCTAssertEqual(SyncBatchLimit.current(host: "h1", config: c), 125_000, "500 KB -> 250 KB -> 125 KB") + XCTAssertEqual(UserDefaults.standard.integer(forKey: SyncBatchLimit.keyPrefix + "h1"), 125_000, "saved") + XCTAssertEqual(SyncBatchLimit.current(host: "other", config: c), 500_000, "per host") // Successes do not raise a limit learned from 413 for _ in 0..<100 { SyncBatchLimit.recordSuccess(host: "h1") } - XCTAssertEqual(SyncBatchLimit.current(host: "h1", config: c), 1_000_000) + XCTAssertEqual(SyncBatchLimit.current(host: "h1", config: c), 125_000) SyncBatchLimit.recordTooLarge(host: "h1", bodyBytes: 10) XCTAssertEqual(SyncBatchLimit.current(host: "h1", config: c), SyncBatchLimit.minimumBytes, "never below the minimum") } func testTimeoutLimitGrowsBack() { let c = DbSyncConfig(); c.serverType = .aware_micro - SyncBatchLimit.recordTimeout(host: "t", bodyBytes: 4_000_000) - XCTAssertEqual(SyncBatchLimit.current(host: "t", config: c), 2_000_000) + SyncBatchLimit.recordTimeout(host: "t", bodyBytes: 500_000) + XCTAssertEqual(SyncBatchLimit.current(host: "t", config: c), 250_000) XCTAssertEqual(UserDefaults.standard.integer(forKey: SyncBatchLimit.keyPrefix + "t"), 0, "not saved") for _ in 0..", "\u{2028}", + ] + + private func makeEngine(table: String) throws -> SQLiteEngine { + let config = Engine.EngineConfig() + config.path = "tricky_\(UUID().uuidString)" + config.tableName = table + let engine = SQLiteEngine(config) + let queue = try XCTUnwrap(engine.getSQLiteInstance()) + try queue.write { db in + try db.execute(sql: """ + CREATE TABLE \(table) (id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp INTEGER, deviceId TEXT, + label TEXT, os TEXT, timezone INTEGER, jsonVersion INTEGER, x REAL, note TEXT, "odd,col\\name" TEXT) + """) + let texts = Self.texts + for i in 0..<(texts.count * 12) { + try db.execute(sql: "INSERT INTO \(table) (timestamp, deviceId, label, os, timezone, jsonVersion, x, note, \"odd,col\\name\") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + arguments: [1_795_060_031_991 + i, "dev\\ice", texts[i % texts.count], "ios", 9, 1, + i % 4 == 0 ? nil : Double(i) * 1.000001 - 50, + i % 5 == 0 ? nil : texts[(i * 7) % texts.count], texts[(i * 3) % texts.count]]) + } + } + return engine + } + + /// The rows in a request body + static func rows(in body: Data, form: Bool) throws -> [[String: Any]] { + var json = body + if form { + let text = String(decoding: body, as: UTF8.self) + guard let field = text.components(separatedBy: "&").first(where: { $0.hasPrefix("data=") }), + let value = String(field.dropFirst(5)).removingPercentEncoding else { return [] } + json = Data(value.utf8) + } + let object = try JSONSerialization.jsonObject(with: json, options: [.fragmentsAllowed]) + var data: Any = object + if !form, let envelope = object as? [String: Any] { data = envelope["data"] as Any } + return data as? [[String: Any]] ?? [] + } + + /// The same row: every stored column (not left out) with the same value + static func mismatch(sent: [String: Any], stored: [String: Any], omitted: Set) -> String? { + let expected = stored.filter { !omitted.contains($0.key) } + if Set(sent.keys) != Set(expected.keys) { + return "columns differ: \(Set(sent.keys).symmetricDifference(expected.keys).sorted())" + } + for (key, value) in expected { + let got = sent[key] + switch value { + case let v as Int64: + if (got as? NSNumber)?.int64Value != v { return "\(key): integer differs" } + case let v as Double: + guard let g = (got as? NSNumber)?.doubleValue, g == v || abs(g - v) <= abs(v) * 1e-15 else { + return "\(key): number differs" + } + case let v as String: + if got as? String != v { return "\(key): text differs" } + default: + return "\(key): unexpected type \(type(of: value))" + } + } + return nil + } + + func testTrickyTextInEveryFormat() throws { + let dumpDir = ProcessInfo.processInfo.environment["AWARE_DUMP_DIR"] + for (name, server) in [("json", ServerType.aware_micro), ("form", .aware), ("hub", .aware_hub)] { + let table = "tricky_test" + let engine = try makeEngine(table: table) + let config = DbSyncConfig() + config.serverType = server + config.maxBatchBytes = 20_000 + let requests = engine.previewUploadRequests(config: config, batches: 10_000) + let stored = try XCTUnwrap(engine.fetch(filter: "id > 0", limit: nil)) + let omitted: Set = [] + var sent: [[String: Any]] = [] + for (i, r) in requests.enumerated() { + XCTAssertLessThanOrEqual(r.body.count, r.limitBytes, "\(name) request \(i)") + let rows = try Self.rows(in: r.body, form: server == .aware) + XCTAssertEqual(rows.count, r.rows, "\(name) request \(i)") + sent += rows + if let dumpDir { + try r.body.write(to: URL(fileURLWithPath: dumpDir).appendingPathComponent("\(name)-\(i).body")) + } + } + XCTAssertEqual(sent.count, stored.count, "\(name): every row once") + for (i, (s, row)) in zip(sent, stored).enumerated() { + if let problem = Self.mismatch(sent: s, stored: row, omitted: omitted) { + XCTFail("\(name) row \(i): \(problem)") + break + } + } + if let dumpDir { + let expected = stored.map { row in row.filter { !omitted.contains($0.key) } } + let data = try JSONSerialization.data(withJSONObject: expected, options: [.sortedKeys]) + try data.write(to: URL(fileURLWithPath: dumpDir).appendingPathComponent("\(name).expected.json")) + } + } + } +} diff --git a/Tests/com.awareframework.ios.coreTests/UploadJSONBytesTests.swift b/Tests/com.awareframework.ios.coreTests/UploadJSONBytesTests.swift new file mode 100644 index 0000000..6f2a532 --- /dev/null +++ b/Tests/com.awareframework.ios.coreTests/UploadJSONBytesTests.swift @@ -0,0 +1,101 @@ +// +// UploadJSONBytesTests.swift +// The byte writer (SQLiteEngine.appendUploadJSON) writes the same text as the string writer it +// replaced, and the form encoding matches URLComponents except for "+". +// + +import XCTest +import GRDB +@testable import com_awareframework_ios_core + +final class UploadJSONBytesTests: XCTestCase { + + private let table = "bytes_test" + + /// The rows as the string writer (UploadJSONWriter) wrote them before + private func referenceJSON(_ queue: DatabaseQueue, omitting: Set) throws -> [String] { + try queue.read { db in + try Row.fetchAll(db, sql: "SELECT * FROM \(table) ORDER BY rowid").map { row in + var json = "{" + var first = true + for (column, value) in row { + if omitting.contains(column) { continue } + switch value.storage { + case .null, .blob: continue + case .int64(let v): + if !first { json.append(",") } + UploadJSONWriter.appendKey(column, to: &json) + json.append(String(v)) + case .double(let v): + if !first { json.append(",") } + UploadJSONWriter.appendKey(column, to: &json) + _ = UploadJSONWriter.appendDouble(v, to: &json) + case .string(let v): + if !first { json.append(",") } + UploadJSONWriter.appendKey(column, to: &json) + UploadJSONWriter.appendString(v, to: &json) + } + first = false + } + return json + "}" + } + } + } + + func testSameTextAsTheStringWriter() throws { + let config = Engine.EngineConfig() + config.path = "bytes_\(UUID().uuidString)" + config.tableName = table + let engine = SQLiteEngine(config) + let queue = try XCTUnwrap(engine.getSQLiteInstance()) + let ints: [Int64] = [0, 1, -1, 9, 10, 1_795_060_031_991, Int64.max, Int64.min] + let doubles: [Double] = [0, -0.0, 0.1, 0.0123456789, -0.98765432, 1e-7, 1e+20, 123456789.123, + 5e-324, 1.7976931348623157e308, 3.0, -2.5e-310] + let texts = ["", "abc", "E2F5B9CE-EB39-498A-BA44-C391175D313C", "it's \"quoted\"", "back\\slash", + "line\nbreak\r\ttab", "\u{1}\u{1f}\u{7f}", "é", "日本語", "😀 emoji", "GMT+9 a+b", "a/b?c=d&e"] + try queue.write { db in + try db.execute(sql: "CREATE TABLE \(table) (id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp INTEGER, deviceId TEXT, label TEXT, x REAL, n INTEGER, note TEXT)") + for i in 0..<120 { + try db.execute(sql: "INSERT INTO \(table) (timestamp, deviceId, label, x, n, note) VALUES (?, ?, ?, ?, ?, ?)", + arguments: [1_795_060_031_991 + Int64(i), "E2F5B9CE-EB39-498A-BA44-C391175D313C", + i % 7 == 0 ? nil : texts[i % texts.count], doubles[i % doubles.count], + ints[i % ints.count], i % 3 == 0 ? texts[(i / 3) % texts.count] : "same"]) + } + } + for omitting in [Set(), ["id"]] { + let expected = try referenceJSON(queue, omitting: omitting) + let written = try XCTUnwrap(engine.fetchUploadJSON(afterId: 0, limit: 1000, omitting: omitting)) + XCTAssertEqual(written.count, expected.count) + for (i, (w, e)) in zip(written, expected).enumerated() { + XCTAssertEqual(w.json, e, "row \(i)") + } + var buffer: [UInt8] = [1, 2, 3] // appended after what is there + let spans = try XCTUnwrap(engine.appendUploadJSON(afterId: 0, limit: 1000, omitting: omitting, to: &buffer)) + XCTAssertEqual(Array(buffer.prefix(3)), [1, 2, 3]) + XCTAssertEqual(spans.compactMap { $0.range.map { String(decoding: buffer[$0], as: UTF8.self) } }, expected) + XCTAssertEqual(spans.map(\.id), Array(1...120).map(Int64.init)) + } + } + + func testFormEncodingMatchesURLComponentsExceptPlus() { + var ascii = "" + for v in 0x20...0x7e where v != 0x2B { ascii.append(Character(UnicodeScalar(v)!)) } + let samples = [ascii, "", "é日本語😀", "{\"x\":0.1,\"label\":\"a b\"}", "[1,2]&data=x"] + for text in samples { + var c = URLComponents() + c.queryItems = [URLQueryItem(name: "v", value: text)] + XCTAssertEqual(FormEncoding.body([("v", text)]), c.percentEncodedQuery, text) + XCTAssertEqual(FormEncoding.encodedLength(text) + 2, c.percentEncodedQuery?.utf8.count) + } + XCTAssertEqual(FormEncoding.body([("v", "GMT+9")]), "v=GMT%2B9", "+ is encoded, so the server does not read a space") + XCTAssertEqual(FormEncoding.body([("a", "1"), ("b", "x y")]), "a=1&b=x%20y", "fields in order") + } + + func testIntegersWithoutStrings() { + for v: Int64 in [0, 7, -7, 10, 1_000_000, Int64.max, Int64.min] { + var out: [UInt8] = [] + JSONBytes.appendInt(v, to: &out) + XCTAssertEqual(String(decoding: out, as: UTF8.self), String(v)) + } + } +} diff --git a/Tests/com.awareframework.ios.coreTests/UploadJSONTests.swift b/Tests/com.awareframework.ios.coreTests/UploadJSONTests.swift index 3299996..c3155b9 100644 --- a/Tests/com.awareframework.ios.coreTests/UploadJSONTests.swift +++ b/Tests/com.awareframework.ios.coreTests/UploadJSONTests.swift @@ -108,6 +108,43 @@ final class UploadJSONTests: XCTestCase { } /// A sync over SQLite with the fast path sends every row once, the same values as the rows hold + /// Sizes are measured 100 rows at a time on the fast path: requests still fill the limit and + /// carry every row once, for JSON and for the URL-encoded form of the legacy AWARE server + func testGroupedSizeCheckFillsTheLimit() throws { + for server in [ServerType.aware_micro, .aware] { + path = "upload_json_\(UUID().uuidString)" + let engine = try makeEngine(rows: (1...3000).map { i in + [1_795_060_031_991 + i * 10, "dev", "it's \"x\" \(i)", 0.0123456789 * Double(i % 97), -0.98765432, nil] + }) + let config = DbSyncConfig() + config.serverType = server + config.maxBatchBytes = 40_000 + let metrics = engine.benchmarkUploadPreparation(config: config, batches: 1000) + XCTAssertEqual(metrics.map(\.rows).reduce(0, +), 3000, "\(server): every row") + for (i, m) in metrics.enumerated() { + XCTAssertLessThanOrEqual(m.bodyBytes, 40_000, "\(server) request \(i)") + if i < metrics.count - 1 { + XCTAssertGreaterThan(m.bodyBytes, 38_000, "\(server) request \(i) should be close to the limit") + } + } + XCTAssertGreaterThan(metrics[0].phases.dbRead + metrics[0].phases.jsonEncode, 0) + } + } + + /// The benchmark sends nothing and changes nothing + func testBenchmarkChangesNothing() throws { + let engine = try makeEngine(rows: (1...500).map { i in [1_795_060_031_991 + i, "dev", "", 0.1, 0.2, nil] }) + let config = DbSyncConfig() + config.maxBatchBytes = 10_000 + let key = DbSyncUtils.markerKey(for: table, database: engine.databaseIdentifier, + maxAssignedId: engine.maxAssignedId(tableName: table)) + let before = DbSyncUtils.getLastUploadedId(forKey: key) + let metrics = engine.benchmarkUploadPreparation(config: config, batches: 3) + XCTAssertEqual(metrics.count, 3) + XCTAssertEqual(DbSyncUtils.getLastUploadedId(forKey: key), before, "marker unchanged") + XCTAssertEqual(engine.count(filter: nil), 500, "rows unchanged") + } + func testSyncSendsEveryRowOnce() throws { let engine = try makeEngine(rows: (1...3000).map { i in [1_795_060_031_991 + i * 10, "dev", "", 0.0123456789 * Double(i % 97), -0.98765432, nil] diff --git a/Tests/com.awareframework.ios.coreTests/UploadSchedulerTests.swift b/Tests/com.awareframework.ios.coreTests/UploadSchedulerTests.swift new file mode 100644 index 0000000..a990d16 --- /dev/null +++ b/Tests/com.awareframework.ios.coreTests/UploadSchedulerTests.swift @@ -0,0 +1,57 @@ +// +// UploadSchedulerTests.swift +// The conditions UploadScheduler checks before an upload starts. +// + +import XCTest +@testable import com_awareframework_ios_core + +final class UploadSchedulerTests: XCTestCase { + + private func check(_ trigger: UploadScheduler.Trigger, _ c: UploadScheduler.Configuration, + wifi: Bool = true, charging: Bool = true, uploading: Bool = false) -> UploadScheduler.SkipReason? { + UploadScheduler.check(trigger: trigger, configuration: c, wifi: wifi, charging: charging, uploading: uploading) + } + + func testAutomaticTriggersNeedAutomaticUpload() { + let off = UploadScheduler.Configuration(automatic: false) + XCTAssertEqual(check(.timer, off), .automaticUploadOff) + XCTAssertEqual(check(.chargingStarted, off), .automaticUploadOff) + XCTAssertEqual(check(.background, off), .automaticUploadOff) + XCTAssertNil(check(.manual, off), "a manual upload works without automatic upload") + } + + func testConditions() { + var c = UploadScheduler.Configuration(automatic: true, wifiOnly: true, chargingOnly: false) + XCTAssertNil(check(.timer, c)) + XCTAssertEqual(check(.timer, c, wifi: false), .waitingForWiFi) + XCTAssertEqual(check(.manual, c, wifi: false), .waitingForWiFi, "manual uploads follow Wi-Fi only too") + XCTAssertEqual(check(.timer, c, uploading: true), .uploadRunning) + c.wifiOnly = false + c.chargingOnly = true + XCTAssertNil(check(.timer, c, wifi: false)) + XCTAssertEqual(check(.timer, c, charging: false), .waitingForCharging) + } + + func testIntervalIsAtLeastOneMinute() { + XCTAssertEqual(UploadScheduler.Configuration(interval: 5).interval, 60) + } + + func testRequestUploadCallsPerformUploadOnceAtATime() { + let s = UploadScheduler.shared + s.configuration = .init(automatic: true, wifiOnly: false, chargingOnly: false) + var finish: (() -> Void)? + var calls = 0 + s.performUpload = { _, done in calls += 1; finish = done } + defer { s.performUpload = nil } + XCTAssertNil(s.requestUpload(.manual)) + XCTAssertTrue(s.isUploading) + XCTAssertEqual(s.requestUpload(.timer), .uploadRunning) + XCTAssertEqual(calls, 1) + finish?() + XCTAssertFalse(s.isUploading) + XCTAssertNil(s.requestUpload(.timer)) + XCTAssertEqual(calls, 2) + finish?() + } +} diff --git a/Tests/com.awareframework.ios.coreTests/com_awareframework_ios_coreTests.swift b/Tests/com.awareframework.ios.coreTests/com_awareframework_ios_coreTests.swift index 5b1d9e2..2e3f20a 100644 --- a/Tests/com.awareframework.ios.coreTests/com_awareframework_ios_coreTests.swift +++ b/Tests/com.awareframework.ios.coreTests/com_awareframework_ios_coreTests.swift @@ -349,9 +349,9 @@ class UnitTests: XCTestCase { original.debugLevel = .trace original.completionHandler = { _, _ in } original.progressHandler = { _, _ in } + original.batchHandler = { _ in } original.dispatchQueue = DispatchQueue(label: "copy.test") original.backgroundSession = true - original.compactDataFormat = !DbSyncConfig.defaultCompactDataFormat original.serverType = DbSyncConfig.defaultServerType == .aware_micro ? .aware_light : .aware_micro original.studyNumber = DbSyncConfig.defaultStudyNumber + 1 original.studyKey = DbSyncConfig.defaultStudyKey + "-key" @@ -532,7 +532,6 @@ class UnitTests: XCTestCase { setting.removeAfterSync = true setting.debug = true setting.test = true - setting.compactDataFormat = false setting.dispatchQueue = DispatchQueue(label: "com.awareframework.ios.sensor.core.syncTask") } let helper = DbSyncHelper.init(engine: sensor.dbEngine!,