From 5a4cc0faeecd925d06ace65cfa57582b510aedb6 Mon Sep 17 00:00:00 2001 From: Yuuki Nishiyama Date: Thu, 19 Nov 2026 08:05:20 -0800 Subject: [PATCH] Size sync requests by bytes, pace by CPU time, and sync off the main thread - Requests hold as many rows as fit in maxBatchBytes (default 4 MB for AWARE Micro, 900 KB for other servers), measured in the form the server receives. maxBatchRows caps the row count; batchSize is now the DB read chunk. - 413 halves the per-host limit and remembers it; a timeout halves it for the run and grows back; 429/503 wait for Retry-After. The same rows are resent. - The fixed 0.1 s wait between requests is replaced by a rest proportional to the CPU time of the last batch (cpuRestRatio, backgroundCpuRestRatio), longer in Low Power Mode and when the device is hot. - Sync work runs on a serial queue per table, never on the main thread, with a lower QoS in the background. - SQLiteEngine writes each upload row as JSON straight from the SQLite values (Engine.fetchUploadJSON), without a dictionary per row. Values are the same as before and REALs keep full precision (json_object() keeps only 15 digits). Load test (360,000 accelerometer rows, AWARE Micro-like server): sync time 55.6 s -> 15.8 s, requests 360 -> 23, UI response max during sync 36.9 ms -> 12.0 ms, peak phys_footprint 49 -> 56 MB, no rows lost; a server rejecting bodies over 1 MB costs two 413s, then every request fits. Co-Authored-By: Claude Opus 5.5 --- README.md | 34 +- .../db/core/DbSyncConfig.swift | 40 +- .../db/core/DbSyncHelper.swift | 370 ++++++++++++++++-- .../db/core/Engine.swift | 69 ++++ .../db/core/SyncPacing.swift | 206 ++++++++++ .../db/sqlite/SQLiteEngine.swift | 59 +++ .../DbSyncBatchingTests.swift | 232 +++++++++++ .../UploadJSONTests.swift | 155 ++++++++ .../com_awareframework_ios_coreTests.swift | 7 +- 9 files changed, 1128 insertions(+), 44 deletions(-) create mode 100644 Sources/com.awareframework.ios.core/db/core/SyncPacing.swift create mode 100644 Tests/com.awareframework.ios.coreTests/DbSyncBatchingTests.swift create mode 100644 Tests/com.awareframework.ios.coreTests/UploadJSONTests.swift diff --git a/README.md b/README.md index ce2bdf6..1ebebea 100644 --- a/README.md +++ b/README.md @@ -188,7 +188,7 @@ sensor.enable() // subscribes to sync broadcast ```swift let syncConfig = DbSyncConfig() -syncConfig.batchSize = 500 +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 @@ -324,7 +324,12 @@ 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. | -| `batchSize: Int` | `1000` | Rows per upload request. Larger backlogs are sent in several requests in one sync. | +| `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"`. | +| `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). | +| `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"`. | | `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"`). | @@ -349,15 +354,36 @@ All settings can also be given as a dictionary with `DbSyncConfig(_:)` or `set(c `DbSyncHelper` uploads each table incrementally: -1. **Progress is tracked by row ID.** Every table of every database stores the ID of the last row uploaded successfully in `UserDefaults` (see [Sync markers](#sync-markers)). A sync sends rows with `id` greater than that value, in batches of `batchSize`, in ID order. `Engine.fetch(filter:limit:)` returns rows in row ID order (`ORDER BY rowid`) unless the filter has its own `ORDER BY`, so each batch is the lowest IDs above the marker whatever query plan SQLite chooses. +1. **Progress is tracked by row ID.** Every table of every database stores the ID of the last row uploaded successfully in `UserDefaults` (see [Sync markers](#sync-markers)). A sync sends rows with `id` greater than that value, in requests of up to `maxBatchBytes`, in ID order. `Engine.fetch(filter:limit:)` returns rows in row ID order (`ORDER BY rowid`) unless the filter has its own `ORDER BY`, so each batch is the lowest IDs above the marker whatever query plan SQLite chooses. 2. **Only HTTP 2xx counts as success.** The last uploaded ID advances (and, with `removeAfterSync`, uploaded rows older than `keepDataAfterSync` are deleted) only after the server answers with a 2xx status. -3. **Failed rows are retried.** On a non-2xx status, a network error, or a timeout (30 s per request), the last uploaded ID does not change and the sync of that table stops. The same rows are sent again at the next sync. Nothing is lost while the server is down, and the backlog is sent in batches once it is back. +3. **Failed rows are retried.** On a non-2xx status, a network error, or a timeout (30 s per request), the last uploaded ID does not change and the sync of that table stops. (Exceptions within a sync: a 413 or a timeout sends the same rows again in a smaller request, and 429 or 503 sends them again after Retry-After; see [Request size](#request-size).) The same rows are sent again at the next sync. Nothing is lost while the server is down, and the backlog is sent in batches once it is back. 4. **Uploaded rows are not sent again.** Rows at or below the last uploaded ID are never selected again, whether or not they are kept locally. 5. **Delivery is at least once.** If the server stores a batch but the response does not reach the app (for example, the app is killed while waiting), that batch is sent again at the next sync. Servers should tolerate duplicates, for example by ignoring rows with the same `timestamp` and device ID. 6. **One sync per table at a time.** When a sync is requested while another sync of the same table of the same database is running (for example, `DbSyncManager.sync()` followed by `sensor.sync(force: true)`), the running sync is not stopped. Stopping it would cancel a request that the server may already have stored, and its rows would be sent again. Instead, one more sync runs after the current one, however many requests were made meanwhile, and every completion handler is called. A sync with no activity for 330 s is treated as stopped, and the next request starts a new one. The last uploaded ID survives app restarts. Deleting the app resets it. +### Request size + +Each request holds as many rows as fit in the size limit, in the form the server receives them (JSON for AWARE Micro and AWARE Light; URL-encoded form for the legacy AWARE server, where the encoding makes a row about twice as large). Each row is turned into JSON once, measured, and reused for the body. The first row of a request is always included, so a row larger than the limit is sent alone. + +| 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. | +| 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. + +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). + +### 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. + +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 With `removeAfterSync`, each successful batch is followed by a cleanup of uploaded rows (`id` at or below the last uploaded ID) whose `timestamp` is older than now minus `keepDataAfterSync`. Rows saved while a request is in flight have larger IDs and are never deleted before they are uploaded. Rows are deleted oldest first, 5,000 per transaction and at most 50,000 per batch, so sensors can keep writing and a large backlog of old rows (for example, after updating from a version that did not delete) is cleared over several syncs instead of in one long transaction. Because the cutoff uses each row's `timestamp`, a device clock that jumps forward deletes uploaded rows earlier; rows that have not been uploaded are not affected. diff --git a/Sources/com.awareframework.ios.core/db/core/DbSyncConfig.swift b/Sources/com.awareframework.ios.core/db/core/DbSyncConfig.swift index 620ff96..e9b7009 100644 --- a/Sources/com.awareframework.ios.core/db/core/DbSyncConfig.swift +++ b/Sources/com.awareframework.ios.core/db/core/DbSyncConfig.swift @@ -7,7 +7,18 @@ /// - removeAfterSync: A boolean indicating whether to remove data after synchronization. Default is `true`. /// - keepDataAfterSync: Seconds to keep uploaded data on the device before `removeAfterSync` deletes it. Default is one day (`86400`). /// - keepPeriod: `keepDataAfterSync` as a period (`.immediately`, `.hour`, `.day`, `.week`, `.month`). -/// - batchSize: An integer specifying the number of records to sync in each batch. Default is `1000`. +/// - 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`. +/// - maxBatchRows: Largest number of rows per request. Default is `20000`. +/// - 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 +/// of a CPU core). See `SyncPacing`. +/// - backgroundCpuRestRatio: The same while the app is in the background. Default is `3`. /// - markAsSynced: A boolean indicating whether to mark data as synced after synchronization. Default is `false`. /// - skipSyncedData: A boolean indicating whether to skip already synced data. Default is `false`. /// - keepLastData: A boolean indicating whether to keep the last data after synchronization. Default is `false`. @@ -109,6 +120,11 @@ 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 batchInterval: TimeInterval = 0 + public var cpuRestRatio: Double = 1 + public var backgroundCpuRestRatio: Double = 3 public var markAsSynced: Bool = false public var skipSyncedData: Bool = false public var keepLastData: Bool = false @@ -143,6 +159,11 @@ public class DbSyncConfig { c.removeAfterSync = removeAfterSync c.keepDataAfterSync = keepDataAfterSync c.batchSize = batchSize + c.maxBatchBytes = maxBatchBytes + c.maxBatchRows = maxBatchRows + c.batchInterval = batchInterval + c.cpuRestRatio = cpuRestRatio + c.backgroundCpuRestRatio = backgroundCpuRestRatio c.markAsSynced = markAsSynced c.skipSyncedData = skipSyncedData c.keepLastData = keepLastData @@ -179,6 +200,23 @@ public class DbSyncConfig { if let batchSize = config["batchSize"] as? Int { self.batchSize = batchSize } + if let bytes = config["maxBatchBytes"] as? Int { + self.maxBatchBytes = bytes + } + if let rows = config["maxBatchRows"] as? Int { + self.maxBatchRows = rows + } + if let interval = config["batchInterval"] as? Double { + self.batchInterval = interval + } else if let interval = config["batchInterval"] as? Int { + self.batchInterval = TimeInterval(interval) + } + if let ratio = config["cpuRestRatio"] as? Double { + self.cpuRestRatio = ratio + } + if let ratio = config["backgroundCpuRestRatio"] as? Double { + self.backgroundCpuRestRatio = ratio + } if let markAsSynced = config["markAsSynced"] as? Bool { self.markAsSynced = markAsSynced diff --git a/Sources/com.awareframework.ios.core/db/core/DbSyncHelper.swift b/Sources/com.awareframework.ios.core/db/core/DbSyncHelper.swift index 00f146a..d7e8210 100644 --- a/Sources/com.awareframework.ios.core/db/core/DbSyncHelper.swift +++ b/Sources/com.awareframework.ios.core/db/core/DbSyncHelper.swift @@ -27,7 +27,6 @@ private struct DbSyncConstants { // Retry and delay values static let retryDelay: TimeInterval = 1.0 - static let nextBatchDelay: TimeInterval = 0.1 // HTTP Status codes static let httpSuccessRange = 200..<300 @@ -243,6 +242,42 @@ open class DbSyncHelper: NSObject { /// Flag indicating whether this is the last batch private var isLastBatch = false + // MARK: Sync queue and pacing + + /// Serial queue for all sync work: reading rows, building requests, the URLSession callbacks and + /// deleting uploaded rows. Nothing runs on the main thread, so a sync never blocks the UI. + private let syncQueue: DispatchQueue + + /// URLSession delegate callbacks run on `syncQueue`, so the sync state is used from one queue + private let delegateQueue: OperationQueue + + /// CPU-bound time of the current batch (reading rows, building the body, deleting rows). + /// The sync rests for a multiple of it before the next batch (`SyncPacing`). + private var batchWorkSeconds: TimeInterval = 0 + + /// Size of the request body being sent, for adjusting the size limit after a 413 or a timeout + private var currentBodyBytes = 0 + + /// HTTP status and Retry-After of the last response + private var lastStatusCode: Int? + private var lastRetryAfter: TimeInterval? + + /// Retries in a row after 413, a timeout, 429 or 503 (reset by a successful request) + private var adjustRetries = 0 + + /// Host key for the learned request size limit + private var limitHost: String { AwareUtils.cleanHostName(host) } + + /// 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) + if delay > 0 { + syncQueue.asyncAfter(deadline: .now() + delay, execute: item) + } else { + syncQueue.async(execute: item) + } + } + /// Property indicating whether session is active (for improved state management convenience) private var isSessionActive: Bool { get { @@ -347,6 +382,13 @@ open class DbSyncHelper: NSObject { self.host = host.trimmingCharacters(in: .whitespacesAndNewlines) self.tableName = tableName.trimmingCharacters(in: .whitespacesAndNewlines) self.config = config + // Release temporary objects (JSON data of each row, fetched rows) after each work item; + // otherwise they pile up while a large backlog is sent + self.syncQueue = DispatchQueue(label: "com.aware.sync.\(self.tableName)", qos: .utility, + autoreleaseFrequency: .workItem) + self.delegateQueue = OperationQueue() + self.delegateQueue.maxConcurrentOperationCount = 1 + self.delegateQueue.underlyingQueue = self.syncQueue super.init() } @@ -532,7 +574,7 @@ open class DbSyncHelper: NSObject { logVerbose("→ startSyncProcess() set session active, dispatching to background queue") } - sessionQueue.async { [weak self] in + onSyncQueue { [weak self] in self?.executeSyncWorkflow() } @@ -585,24 +627,192 @@ open class DbSyncHelper: NSObject { } } - // Get target data for synchronization - let candidates = getUploadCandidates( - lastUploadedId: lastUploadedId, limit: config.batchSize) + // 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 config.debug { logVerbose( - "→ performDataSync() found \(candidates.count) candidates, dispatching to upload") + "→ performDataSync() selected \(batch.count) rows" + + (batch.body.map { " (\($0.utf8.count) bytes)" } ?? "") + ", last batch: \(batch.isLast)") } - // Start upload process on main thread - DispatchQueue.main.async { - self.logVerbose("calling upload() on main thread") - self.upload(candidates) - } + send(count: batch.count, lastId: batch.lastId, rows: batch.rows, body: batch.body, isLast: batch.isLast) logTrace("performDataSync() completed") } + // MARK: - Request size + + private struct Batch { + var count: Int + var lastId: Int64? + /// 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 isLast: Bool + } + + /// 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 + /// within the size limit (`SyncBatchLimit`) and `maxBatchRows`. Each row is turned into JSON once; + /// its size is measured in the form the body uses (JSON, or URL-encoded for the legacy AWARE server), + /// 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. + private func selectBatch() -> Batch { + let limit = SyncBatchLimit.current(host: limitHost, config: config) + 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 + + var rows: [[String: Any]] = [] // only when !exact + var pieces: [String] = [] + 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 + } + var afterId = lastUploadedId + var more = true + var invalid = false + + 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 + } + let size = (form ? formEncodedLength(json) : json.utf8.count) + (pieces.isEmpty ? 0 : separator) + if count > 0 && total + size > limit { + stop = true + break + } + pieces.append(json) + total += size + count += 1 + lastId = row.id + } + return encoded.count + } + let fetched = getUploadCandidates(lastUploadedId: afterId, limit: want) + 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 { + stop = true + break + } + pieces.append(json) + total += size + } else { + // Not valid JSON: fall back to buildRequestBody, which reports the error + invalid = true + stop = true + break + } + count += 1 + lastId = row["id"] as? Int64 + } + return fetched.count + } + if invalid { break } + if stop { more = true; break reading } + if fetchedCount == 0 { more = false; break } + guard fetchedCount == want, let id = lastId else { + more = fetchedCount == want + break + } + afterId = id + } + + if exact && !invalid { + return Batch(count: count, lastId: lastId, rows: nil, body: assembleBody(pieces, form: form), isLast: !more) + } + if invalid { + // Read the same rows again as dictionaries for buildRequestBody + rows = getUploadCandidates(lastUploadedId: lastUploadedId, limit: min(chunk, maxRows)) + more = true + } + // Build with the general builder, and remove rows until the body fits + for _ in 0..<4 { + guard rows.count > 1, let body = try? buildRequestBody(from: rows) else { break } + let bytes = body.utf8.count + if bytes <= limit { break } + let keep = max(1, Int(Double(rows.count) * Double(limit) / Double(bytes) * 0.95)) + rows = Array(rows.prefix(keep)) + more = true + } + return Batch(count: rows.count, lastId: rows.last?["id"] as? Int64, rows: rows, body: nil, isLast: !more) + } + + /// A row as it is uploaded, in JSON (nil if it cannot be turned into JSON) + private func rowJSON(_ row: [String: Any]) -> String? { + var upload = row + if config.serverType == .aware_light { upload.removeValue(forKey: "id") } + guard JSONSerialization.isValidJSONObject(upload), + let data = try? JSONSerialization.data(withJSONObject: upload, options: []) else { return nil } + return String(data: data, encoding: .utf8) + } + + /// `{"deviceId":...,"tableName":...,"timestamp":...}` for the JSON body (AWARE Micro, AWARE Light) + private func jsonEnvelope() -> String { + let params: [String: Any] = [ + "deviceId": AwareUtils.getCommonDeviceId(), + "tableName": tableName, + "timestamp": Int64(Date().timeIntervalSince1970 * 1000), + ] + let data = (try? JSONSerialization.data(withJSONObject: params, options: [])) ?? Data("{}".utf8) + 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 + } + + /// The request body from the rows' JSON, in the same form `buildRequestBody(from:)` produces + private func assembleBody(_ pieces: [String], form: Bool) -> String { + 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) + } + body.append("]}") + return body + } + // MARK: - Data Management /** @@ -621,6 +831,22 @@ open class DbSyncHelper: NSObject { return candidates ?? [] } + /** + * Get upload candidate data as JSON + * + * The rows `getUploadCandidates(lastUploadedId:limit:)` returns, each already written as the JSON + * object it is uploaded as (`id` is left out for AWARE Light). Used while choosing the rows of a + * request, so that no dictionary is made per row. Returns nil when the engine cannot do this; + * the sync then uses `getUploadCandidates`. + * + * 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. + */ + 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) + } + /// Rows deleted per transaction, and transactions per call, by `removeUploadedCandidates`. static let removeChunkSize = 5000 static let removeMaxChunks = 10 @@ -861,7 +1087,7 @@ open class DbSyncHelper: NSObject { } // Reset state to idle after completion/failure to allow future syncs - DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in + syncQueue.asyncAfter(deadline: .now() + 0.1) { [weak self] in self?.syncState = .idle if self?.config.debug == true { self?.logTrace("Sync state reset to idle") @@ -874,8 +1100,12 @@ open class DbSyncHelper: NSObject { */ private func handleNextBatch() { logInfo("A sync task is done. Execute a next sync task.") - DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DbSyncConstants.nextBatchDelay) - { [weak self] in + // Rest in proportion to the CPU time of the last batch, on the sync queue (not the main thread) + let rest = SyncPacing.rest(workSeconds: batchWorkSeconds, config: config) + if config.debug { + logVerbose(String(format: "Next batch in %.3f s (work %.3f s)", rest, batchWorkSeconds)) + } + onSyncQueue(after: rest) { [weak self] in // Calculate and report progress if let pCallback = self?.config.progressHandler { // Calculate progress based on uploaded records vs total records @@ -917,35 +1147,38 @@ open class DbSyncHelper: NSObject { * 2. JSON serialization * 3. HTTP request construction and transmission * - * @param candidates Array of data to be uploaded + * @param candidates Array of data to be uploaded. All of them are sent in one request; a sync + * started with `run(completion:)` chooses its rows by size instead (`maxBatchBytes`). */ open func upload(_ candidates: [[String: Any]]) { + send(count: candidates.count, lastId: candidates.last?["id"] as? Int64, rows: candidates, body: nil, + isLast: candidates.count < max(1, config.maxBatchRows)) + } + + /// 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) { if config.debug { - logVerbose("upload() started with \(candidates.count) candidates") + logVerbose("upload() started with \(count) candidates") } // Record current batch size - self.currentNumOfCandidates = candidates.count + self.currentNumOfCandidates = count self.lastActivity = Date().timeIntervalSince1970 // Record ID of the last data (used when sync is completed) - self.idOfLastCandidate = nil - if let lastCandidate = candidates.last { - if let candidateId = lastCandidate["id"] as? Int64 { - self.idOfLastCandidate = candidateId - if config.debug { - logTrace("idOfLastCandidate: \(candidateId)") - } - } + self.idOfLastCandidate = lastId + if let candidateId = lastId, config.debug { + logTrace("idOfLastCandidate: \(candidateId)") } // Output debug information if self.config.debug { - logInfo("Data count = \(candidates.count)") + logInfo("Data count = \(count)") } // If data is empty, process as sync completed - if candidates.count == 0 { + if count == 0 { syncState = .completed if self.config.debug { logInfo("A sync process is done: No Data") @@ -964,7 +1197,7 @@ open class DbSyncHelper: NSObject { } // Reset state to idle after completion - DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in + syncQueue.asyncAfter(deadline: .now() + 0.1) { [weak self] in self?.syncState = .idle if self?.config.debug == true { self?.logTrace("Sync state reset to idle (no data)") @@ -973,14 +1206,17 @@ open class DbSyncHelper: NSObject { return } - // Determine if this is the final batch (for controlling next run() call) - if candidates.count < self.config.batchSize { - self.isLastBatch = true - } + // Whether rows remain after this request (decided when the rows were chosen) + self.isLastBatch = isLast + self.lastStatusCode = nil + self.lastRetryAfter = nil do { - // Build HTTP request body - let requestBody = try buildRequestBody(from: candidates) + // 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) + currentBodyBytes = requestBody.utf8.count // Build HTTP request if let request = buildHTTPRequest(with: requestBody) { @@ -999,7 +1235,7 @@ open class DbSyncHelper: NSObject { // Add task description for better debugging task.taskDescription = - "Upload[\(tableName)]_Batch[\(candidates.count)]_LastID[\(idOfLastCandidate ?? 0)]" + "Upload[\(tableName)]_Batch[\(count)]_LastID[\(idOfLastCandidate ?? 0)]" // Send actual HTTP request task.resume() @@ -1018,7 +1254,7 @@ open class DbSyncHelper: NSObject { } // Reset state to idle after error - DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in + syncQueue.asyncAfter(deadline: .now() + 0.1) { [weak self] in self?.syncState = .idle if self?.config.debug == true { self?.logTrace("Sync state reset to idle (JSON error)") @@ -1076,7 +1312,8 @@ open class DbSyncHelper: NSObject { sessionConfig.sharedContainerIdentifier = DbSyncConstants.sharedContainerIdentifier } - return URLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil) + // Callbacks run on the sync queue, like the rest of the sync + return URLSession(configuration: sessionConfig, delegate: self, delegateQueue: delegateQueue) } /** @@ -1153,7 +1390,7 @@ open class DbSyncHelper: NSObject { } // Wait for completion of all task cancellations - group.notify(queue: .main) { + group.notify(queue: self?.syncQueue ?? .global(qos: .utility)) { completion() } } @@ -1178,6 +1415,11 @@ open class DbSyncHelper: NSObject { ) { if let httpResponse = response as? HTTPURLResponse { + lastStatusCode = httpResponse.statusCode + if let value = httpResponse.value(forHTTPHeaderField: "Retry-After"), + let seconds = TimeInterval(value.trimmingCharacters(in: .whitespaces)) { + lastRetryAfter = seconds + } if DbSyncConstants.httpSuccessRange.contains(httpResponse.statusCode) { // 2xx status codes are processed as success completionHandler(URLSession.ResponseDisposition.allow) @@ -1231,6 +1473,21 @@ open class DbSyncHelper: NSObject { ) { let responseState = evaluateResponseState(error: error, task: task, session: session) + // A body that was too large (413), a timeout, or a busy server (429, 503): send again, + // smaller or later, instead of ending the sync + if !responseState, let delay = retryDelayAfterFailure(error: error) { + invalidateSession(waitForTasks: false) + receivedData = Data() + onSyncQueue(after: delay) { [weak self] in + self?.performDataSync() + } + return + } + if responseState { + adjustRetries = 0 + SyncBatchLimit.recordSuccess(host: limitHost) + } + // Debug output of server response if self.config.debug { let response = String(data: receivedData, encoding: .utf8) ?? "" @@ -1256,7 +1513,9 @@ open class DbSyncHelper: NSObject { // Delete uploaded data (according to settings) if config.removeAfterSync { + let started = Date() removeUploadedCandidates(lastUploadedId: lastUploadedId, limit: config.batchSize) + batchWorkSeconds += Date().timeIntervalSince(started) } // Finally update uploaded ID @@ -1273,6 +1532,41 @@ open class DbSyncHelper: NSObject { handleUploadCompletion(responseState: responseState, error: error) } + /// 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), + /// and the batch is chosen again right away. A single row that is too large cannot be split. + /// - Timeout: the limit is halved for this run of the app, and the batch is chosen again. + /// - 429 / 503: wait for Retry-After (or 5, 10, 20 s), at most 120 s. + /// At most 8 retries in a row (3 for timeouts and 429/503); then the sync fails as before. + private func retryDelayAfterFailure(error: Error?) -> TimeInterval? { + guard adjustRetries < 8 else { return nil } + let timedOut = (error as NSError?).map { $0.domain == NSURLErrorDomain && $0.code == NSURLErrorTimedOut } ?? false + if lastStatusCode == 413 { + guard currentNumOfCandidates > 1 else { + logError("Server rejected a single row of \(currentBodyBytes) bytes as too large (413)") + return nil + } + let limit = SyncBatchLimit.recordTooLarge(host: limitHost, bodyBytes: currentBodyBytes) + adjustRetries += 1 + logWarning("Server rejected \(currentBodyBytes) bytes (413); sending again with up to \(limit) bytes") + return 0 + } + if timedOut && currentNumOfCandidates > 1 && adjustRetries < 3 { + let limit = SyncBatchLimit.recordTimeout(host: limitHost, bodyBytes: currentBodyBytes) + adjustRetries += 1 + logWarning("Request of \(currentBodyBytes) bytes timed out; sending again with up to \(limit) bytes") + return 0 + } + if let code = lastStatusCode, code == 429 || code == 503, adjustRetries < 3 { + adjustRetries += 1 + let wait = min(lastRetryAfter ?? 5 * pow(2, Double(adjustRetries - 1)), 120) + logWarning("Server is busy (\(code)); sending again in \(Int(wait)) s") + return wait + } + return nil + } + /** * Evaluate response state * diff --git a/Sources/com.awareframework.ios.core/db/core/Engine.swift b/Sources/com.awareframework.ios.core/db/core/Engine.swift index 87eca31..2f3af71 100644 --- a/Sources/com.awareframework.ios.core/db/core/Engine.swift +++ b/Sources/com.awareframework.ios.core/db/core/Engine.swift @@ -142,6 +142,75 @@ open class Engine: EngineProtocal { /// The largest row ID ever assigned in the table, or `nil` when the engine cannot tell. /// Used to check that a sync marker belongs to this database. open func maxAssignedId(tableName: String) -> Int64? { nil } + + /// Rows with an ID above `afterId`, lowest ID first, at most `limit`, each written as the JSON + /// object it is uploaded as (the columns as keys, NULL columns left out, `omitting` left out). + /// + /// 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 } +} + +/// A row ready for upload: its ID and its JSON object, or `nil` when the row cannot be written as +/// JSON (a BLOB, or a number that is not finite). +public struct UploadRowJSON { + public let id: Int64 + public let json: String? + + public init(id: Int64, json: String?) { + self.id = id + self.json = json + } +} + +/// Writes SQLite values as JSON, the same values `JSONSerialization` writes for the rows that +/// `fetch(filter:limit:)` returns. Numbers keep their full precision: a REAL is written with the +/// shortest text that reads back as the same Double. +enum UploadJSONWriter { + + /// Appends `"key":` to `out`. + static func appendKey(_ key: String, to out: inout String) { + appendString(key, to: &out) + out.append(":") + } + + /// Appends `value` as a JSON number. Returns false for infinity and NaN, which JSON cannot hold. + static func appendDouble(_ value: Double, to out: inout String) -> Bool { + guard value.isFinite else { return false } + out.append(value.description) + return true + } + + /// Appends `text` as a JSON string. + static func appendString(_ text: String, to out: inout String) { + out.append("\"") + var plainStart = text.unicodeScalars.startIndex + let scalars = text.unicodeScalars + var index = scalars.startIndex + while index < scalars.endIndex { + let scalar = scalars[index] + let escaped: String? + switch scalar { + case "\"": escaped = "\\\"" + case "\\": escaped = "\\\\" + case "\n": escaped = "\\n" + case "\r": escaped = "\\r" + case "\t": escaped = "\\t" + case _ where scalar.value < 0x20: + let hex = String(scalar.value, radix: 16) + escaped = "\\u" + String(repeating: "0", count: 4 - hex.count) + hex + default: escaped = nil + } + if let escaped { + out.unicodeScalars.append(contentsOf: scalars[plainStart.. TimeInterval { + let ratio = max(0, background ? config.backgroundCpuRestRatio : config.cpuRestRatio) + var rest = max(config.batchInterval, max(0, workSeconds) * ratio) + if lowPower { rest *= 2 } + switch thermal { + case .serious: rest = max(rest, 5) + case .critical: rest = max(rest, 30) + default: break + } + return min(rest, 120) + } + + static func rest(workSeconds: TimeInterval, config: DbSyncConfig) -> TimeInterval { + rest(workSeconds: workSeconds, config: config, background: SyncAppState.shared.isInBackground, + thermal: ProcessInfo.processInfo.thermalState, + lowPower: ProcessInfo.processInfo.isLowPowerModeEnabled) + } +} + +// MARK: - Request size limit + +/// 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. +/// - 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 + /// Never below this, so that a sync always makes progress + public static let minimumBytes = 16_384 + static let growAfterSuccesses = 20 + static let keyPrefix = "aware.sync.max_batch_bytes." + + private static let lock = NSLock() + private static var timeoutLimits: [String: Int] = [:] + private static var successes: [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 + } + + /// The limit to use for `host` now. + public static func current(host: String, config: DbSyncConfig) -> Int { + lock.lock() + defer { lock.unlock() } + var limit = configured(config) + let saved = UserDefaults.standard.integer(forKey: keyPrefix + host) + if saved > 0 { limit = min(limit, saved) } + if let t = timeoutLimits[host] { limit = min(limit, t) } + return max(minimumBytes, limit) + } + + /// The host rejected a body of `bodyBytes` as too large (413). + /// - Returns: The new limit. + @discardableResult + public static func recordTooLarge(host: String, bodyBytes: Int) -> Int { + lock.lock() + defer { lock.unlock() } + 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) + successes[host] = 0 + return limit + } + + /// A request of `bodyBytes` timed out. + @discardableResult + public static func recordTimeout(host: String, bodyBytes: Int) -> Int { + lock.lock() + defer { lock.unlock() } + let limit = max(minimumBytes, bodyBytes / 2) + timeoutLimits[host] = min(timeoutLimits[host] ?? limit, limit) + successes[host] = 0 + return limit + } + + /// A request succeeded: after `growAfterSuccesses` in a row, a timeout limit grows back by half. + public static func recordSuccess(host: String) { + lock.lock() + defer { lock.unlock() } + guard let t = timeoutLimits[host] else { return } + let n = (successes[host] ?? 0) + 1 + if n >= growAfterSuccesses { + timeoutLimits[host] = t + t / 2 + successes[host] = 0 + } else { + successes[host] = n + } + } + + /// Forget what was learned about `host` (or every host). + public static func reset(host: String? = nil) { + lock.lock() + defer { lock.unlock() } + if let host { + UserDefaults.standard.removeObject(forKey: keyPrefix + host) + timeoutLimits[host] = nil + successes[host] = nil + } else { + for key in UserDefaults.standard.dictionaryRepresentation().keys where key.hasPrefix(keyPrefix) { + UserDefaults.standard.removeObject(forKey: key) + } + timeoutLimits = [:] + successes = [:] + } + } +} diff --git a/Sources/com.awareframework.ios.core/db/sqlite/SQLiteEngine.swift b/Sources/com.awareframework.ios.core/db/sqlite/SQLiteEngine.swift index 5ede9e4..17f238f 100644 --- a/Sources/com.awareframework.ios.core/db/sqlite/SQLiteEngine.swift +++ b/Sources/com.awareframework.ios.core/db/sqlite/SQLiteEngine.swift @@ -238,6 +238,65 @@ 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]? { + guard let tableName = config.tableName, + let db = getSQLiteInstance() + else { return nil } + let sql = "SELECT * FROM \(tableName) WHERE id > ? ORDER BY rowid LIMIT ?" + 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? + var valid = true + json.removeAll(keepingCapacity: true) + json.append("{") + var first = true + for (column, value) in row { + if column == "id", case .int64(let v) = value.storage { id = v } + if omitting.contains(column) { continue } + switch value.storage { + case .null: + continue // fetch(filter:limit:) leaves NULL columns out of the row + case .blob: + valid = false + 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) + valid = UploadJSONWriter.appendDouble(v, to: &json) && valid + case .string(let v): + if !first { json.append(",") } + UploadJSONWriter.appendKey(column, to: &json) + UploadJSONWriter.appendString(v, to: &json) + } + first = false + if !valid { break } + } + // Rows without an integer id cannot be tracked by the sync marker + guard let rowId = id else { return nil } + json.append("}") + results.append(UploadRowJSON(id: rowId, json: valid ? String(json) : nil)) + if !valid { break } + } + return results + } + } + } catch { + print("[Error][SQLiteEngine] fetchUploadJSON failed: \(error)") + return nil + } + } + public override func fetch( filter: String? = nil, limit: Int? = nil, completion: (([[String: Any]]?, Error?) -> Void)? diff --git a/Tests/com.awareframework.ios.coreTests/DbSyncBatchingTests.swift b/Tests/com.awareframework.ios.coreTests/DbSyncBatchingTests.swift new file mode 100644 index 0000000..9baf28c --- /dev/null +++ b/Tests/com.awareframework.ios.coreTests/DbSyncBatchingTests.swift @@ -0,0 +1,232 @@ +// +// DbSyncBatchingTests.swift +// com.awareframework.ios.core.Tests +// +// Requests sized by bytes (maxBatchBytes), the learned per-host limit, pacing between batches, +// and sync work off the main thread. +// + +import XCTest +import Foundation +@testable import com_awareframework_ios_core + +/// MockEngine that records whether rows were read on the main thread +private final class ThreadRecordingEngine: MockEngine { + var fetchesOnMain = 0 + var fetches = 0 + override func fetch(filter: String?, limit: Int?) -> [[String: Any]]? { + fetches += 1 + if Thread.isMainThread { fetchesOnMain += 1 } + return super.fetch(filter: filter, limit: limit) + } +} + +final class DbSyncBatchingTests: XCTestCase { + + private var engine: ThreadRecordingEngine! + private var config: DbSyncConfig! + private let table = "batching_test" + private let host = "https://batching.example.com" + + override func setUp() { + super.setUp() + DbSyncUtils.clearLastUploadedId(for: table) + SyncBatchLimit.reset() + engine = ThreadRecordingEngine() + config = DbSyncConfig() + config.test = true + config.backgroundSession = false + config.removeAfterSync = false + } + + override func tearDown() { + SyncBatchLimit.reset() + DbSyncUtils.clearLastUploadedId(for: table) + super.tearDown() + } + + /// Accelerometer-like rows of about 200 bytes of JSON each + private func rows(_ n: Int) -> [[String: Any]] { + (1...n).map { i in + ["id": Int64(i), "timestamp": Int64(1_795_060_031_991 + i * 10), + "deviceId": "E2F5B9CE-EB39-498A-BA44-C391175D313C", "label": "", + "x": 0.0123456789 * Double(i % 97), "y": -0.98765432, "z": 0.00314159 * Double(i % 7)] + } + } + + /// Run a sync to the end and return the request bodies it sent + private func sync(server: ServerType, compact: Bool = false, 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() + helper.createURLRequestHandler = { request in + lock.lock(); bodies.append(request.httpBody ?? Data()); lock.unlock() + return request + } + if bodyHandler { helper.createHttpRequestBodyHandler = { $0 } } + let done = expectation(description: "sync done") + helper.run { success, _ in + XCTAssertTrue(success, file: file, line: line) + done.fulfill() + } + wait(for: [done], timeout: 60) + return (bodies, helper) + } + + private func jsonRows(_ body: Data) -> [[String: Any]] { + let object = try? JSONSerialization.jsonObject(with: body) as? [String: Any] + return object?["data"] as? [[String: Any]] ?? [] + } + + private func formRows(_ body: Data) -> [[String: Any]] { + guard let text = String(data: body, encoding: .utf8), + let data = URLComponents(string: "?" + text)?.queryItems?.first(where: { $0.name == "data" })?.value, + let rows = try? JSONSerialization.jsonObject(with: Data(data.utf8)) as? [[String: Any]] else { return [] } + return rows + } + + // MARK: - Size of requests + + func testJSONRequestsFillTheLimitAndSendEveryRowOnce() { + engine.mockData = rows(3000) + config.maxBatchBytes = 50_000 + config.batchSize = 500 + let (bodies, helper) = sync(server: .aware_micro) + + XCTAssertGreaterThan(bodies.count, 5) + for (i, body) in bodies.enumerated() { + XCTAssertLessThanOrEqual(body.count, 50_000, "request \(i)") + if i < bodies.count - 1 { + XCTAssertGreaterThan(body.count, 49_000, "request \(i) should be close to the limit") + } + } + let ids = bodies.flatMap(jsonRows).compactMap { ($0["id"] as? NSNumber)?.int64Value } + XCTAssertEqual(ids, (1...3000).map(Int64.init), "every row once, in order") + XCTAssertEqual(DbSyncUtils.getLastUploadedId(forKey: helper.markerKey), 3000) + // The body has the same fields as before + let first = try? JSONSerialization.jsonObject(with: bodies[0]) as? [String: Any] + XCTAssertEqual(first?["tableName"] as? String, table) + XCTAssertEqual(first?["deviceId"] as? String, AwareUtils.getCommonDeviceId()) + XCTAssertNotNil(first?["timestamp"]) + XCTAssertEqual(engine.fetchesOnMain, 0, "rows are read off the main thread") + } + + func testFormRequestsMeasureEncodedSize() { + engine.mockData = rows(1500) + config.maxBatchBytes = 30_000 + let (bodies, _) = sync(server: .aware) + + for (i, body) in bodies.enumerated() { + XCTAssertLessThanOrEqual(body.count, 30_000, "request \(i)") + if i < bodies.count - 1 { + XCTAssertGreaterThan(body.count, 29_000, "request \(i) should be close to the limit") + } + } + let ids = bodies.flatMap(formRows).compactMap { ($0["id"] as? NSNumber)?.int64Value } + XCTAssertEqual(ids, (1...1500).map(Int64.init)) + } + + func testCompactFormatAndBodyHandlerStayWithinLimit() { + 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) + } + + func testMaxBatchRowsCapsRequests() { + engine.mockData = rows(250) + config.maxBatchBytes = 10_000_000 + config.maxBatchRows = 100 + let (bodies, _) = sync(server: .aware_micro) + XCTAssertEqual(bodies.map { jsonRows($0).count }, [100, 100, 50]) + } + + func testRowLargerThanLimitIsSentAlone() { + var data = rows(3) + data[1]["label"] = String(repeating: "x", count: 30_000) + engine.mockData = data + config.maxBatchBytes = 20_000 + let (bodies, _) = sync(server: .aware_micro) + XCTAssertEqual(bodies.map { jsonRows($0).count }, [1, 1, 1], "the large row goes alone; the sync goes on") + } + + 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), 900_000) + legacy.maxBatchBytes = 2_000_000 + XCTAssertEqual(SyncBatchLimit.configured(legacy), 2_000_000) + } + + // MARK: - Learned limit + + 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") + // 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) + 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) + XCTAssertEqual(UserDefaults.standard.integer(forKey: SyncBatchLimit.keyPrefix + "t"), 0, "not saved") + for _ in 0.. SQLiteEngine { + 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, + deviceId TEXT, label TEXT, x REAL, y REAL, extra BLOB) + """) + for row in rows { + try db.execute(sql: "INSERT INTO \(table) (timestamp, deviceId, label, x, y, extra) VALUES (?, ?, ?, ?, ?, ?)", + arguments: StatementArguments(row)) + } + } + return engine + } + + private func object(_ json: String?) -> [String: Any]? { + guard let json else { return nil } + return try? JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any] + } + + /// Doubles compared bit for bit, other values by their JSON + private func assertSameValues(_ a: [String: Any], _ b: [String: Any], file: StaticString = #filePath, line: UInt = #line) { + XCTAssertEqual(Set(a.keys), Set(b.keys), file: file, line: line) + for (key, value) in a { + let other = b[key] + if let d = value as? Double, let e = (other as? NSNumber)?.doubleValue { + XCTAssertEqual(d.bitPattern, e.bitPattern, "\(key): \(d) vs \(e)", file: file, line: line) + } else { + XCTAssertEqual("\(value)", "\(other ?? "nil")", key, file: file, line: line) + } + } + } + + func testSameValuesAsFetch() throws { + let tricky = "quote \" backslash \\ slash / newline \n tab \t ctrl \u{01} 日本語 😀" + let engine = try makeEngine(rows: [ + [1_795_060_031_991, "dev", "", 0.1 + 0.2, -0.98765432, nil], + [1_795_060_032_001, "dev", tricky, 1795060031991.123, 5.0, nil], + [1_795_060_032_011, "dev", nil, 1e-300, 0.12345678901234567, nil], // NULL label + [Int64.max, "dev", "x", -0.0, 1e20, nil], + ]) + let fetched = try XCTUnwrap(engine.fetch(filter: "id > 0", limit: 10)) + let encoded = try XCTUnwrap(engine.fetchUploadJSON(afterId: 0, limit: 10, omitting: [])) + XCTAssertEqual(encoded.map(\.id), [1, 2, 3, 4]) + XCTAssertEqual(fetched.count, encoded.count) + for (row, enc) in zip(fetched, encoded) { + let fromJSON = try XCTUnwrap(object(enc.json), enc.json ?? "nil") + // What the old path sends: the fetched row through JSONSerialization + let old = try XCTUnwrap(object(String(data: JSONSerialization.data(withJSONObject: row), encoding: .utf8))) + assertSameValues(old, fromJSON) + } + XCTAssertNil(object(encoded[2].json)?["label"], "NULL columns are left out, as fetch does") + XCTAssertEqual(object(encoded[1].json)?["label"] as? String, tricky) + } + + func testOmittingAndLimit() throws { + let engine = try makeEngine(rows: (1...5).map { [$0, "dev", "", 0.5, 0.25, nil] }) + let encoded = try XCTUnwrap(engine.fetchUploadJSON(afterId: 2, limit: 2, omitting: ["id"])) + XCTAssertEqual(encoded.map(\.id), [3, 4], "ids after afterId, in order, at most limit") + XCTAssertNil(object(encoded[0].json)?["id"]) + } + + func testRowsJSONCannotHoldAreMarked() throws { + let engine = try makeEngine(rows: [ + [1, "dev", "", 0.5, 0.25, nil], + [2, "dev", "", 0.5, 0.25, Data([0, 1, 2])], // BLOB + [3, "dev", "", 0.5, 0.25, nil], + ]) + let encoded = try XCTUnwrap(engine.fetchUploadJSON(afterId: 0, limit: 10, omitting: [])) + XCTAssertNotNil(encoded[0].json) + XCTAssertNil(encoded[1].json, "a BLOB cannot be written as JSON") + XCTAssertEqual(encoded.count, 2, "reading stops at the row JSON cannot hold") + } + + /// A sync over SQLite with the fast path sends every row once, the same values as the rows hold + 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] + }) + let config = DbSyncConfig() + config.test = true + config.backgroundSession = false + config.removeAfterSync = false + config.serverType = .aware_micro + config.maxBatchBytes = 40_000 + let helper = DbSyncHelper(engine: engine, host: "https://upload-json.example.com", tableName: table, config: config) + var bodies: [Data] = [] + let lock = NSLock() + helper.createURLRequestHandler = { request in + lock.lock(); bodies.append(request.httpBody ?? Data()); lock.unlock() + return request + } + let done = expectation(description: "sync done") + helper.run { success, _ in + XCTAssertTrue(success) + done.fulfill() + } + wait(for: [done], timeout: 60) + + XCTAssertGreaterThan(bodies.count, 5) + bodies.forEach { XCTAssertLessThanOrEqual($0.count, 40_000) } + let rows = bodies.flatMap { body -> [[String: Any]] in + let object = try? JSONSerialization.jsonObject(with: body) as? [String: Any] + return object?["data"] as? [[String: Any]] ?? [] + } + XCTAssertEqual(rows.compactMap { ($0["id"] as? NSNumber)?.int64Value }, (1...3000).map(Int64.init)) + // The numbers as sent, read with Double(String): JSONSerialization's parser can be off by an + // ulp or two, while the text itself is exact + let regex = try NSRegularExpression(pattern: #""x":([-0-9.eE+]+)"#) + let sentX = bodies.flatMap { body -> [Double] in + let text = String(decoding: body, as: UTF8.self) + return regex.matches(in: text, range: NSRange(text.startIndex..., in: text)).compactMap { + Range($0.range(at: 1), in: text).flatMap { Double(text[$0]) } + } + } + let storedX = try XCTUnwrap(engine.fetch(filter: "id > 0", limit: nil)).compactMap { $0["x"] as? Double } + XCTAssertEqual(sentX.count, 3000) + XCTAssertEqual(sentX.map(\.bitPattern), storedX.map(\.bitPattern), "every number exactly as stored") + } +} 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 0f04f9a..c49dd1f 100644 --- a/Tests/com.awareframework.ios.coreTests/com_awareframework_ios_coreTests.swift +++ b/Tests/com.awareframework.ios.coreTests/com_awareframework_ios_coreTests.swift @@ -334,6 +334,11 @@ class UnitTests: XCTestCase { original.removeAfterSync = false original.keepDataAfterSync = 123 original.batchSize = 42 + original.maxBatchBytes = 123_456 + original.maxBatchRows = 77 + original.batchInterval = 0.5 + original.cpuRestRatio = 2 + original.backgroundCpuRestRatio = 5 original.markAsSynced = true original.skipSyncedData = true original.keepLastData = true @@ -359,7 +364,7 @@ class UnitTests: XCTestCase { }) } let defaults = values(DbSyncConfig()), originals = values(original), copies = values(copy) - XCTAssertEqual(originals.count, 18, "a property was added or removed: update copy() and this test") + XCTAssertEqual(originals.count, 23, "a property was added or removed: update copy() and this test") for (name, value) in originals { XCTAssertNotEqual(value, defaults[name], "\(name) is not set in this test") XCTAssertEqual(copies[name], value, "\(name) is not copied by copy()")