Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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]))
]
),
Expand Down
26 changes: 18 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -324,16 +323,18 @@ 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 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"`. |
| `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"`. |
| `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`. |
Expand All @@ -348,6 +349,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
Expand All @@ -369,19 +372,26 @@ 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.<host>`), 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 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.<host>`). 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.<host>`), 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.<host>`). |
| 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).

### 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
Expand Down
63 changes: 46 additions & 17 deletions Sources/com.awareframework.ios.core/db/core/DbSyncConfig.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 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
/// 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
Expand All @@ -26,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.
Expand Down Expand Up @@ -77,7 +82,19 @@ 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

Expand Down Expand Up @@ -120,11 +137,13 @@ 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 backgroundCpuRestRatio: Double = 3
public var cpuRestRatio: Double = DbSyncConfig.defaultCpuRestRatio
public var backgroundCpuRestRatio: Double = DbSyncConfig.defaultBackgroundCpuRestRatio
public var markAsSynced: Bool = false
public var skipSyncedData: Bool = false
public var keepLastData: Bool = false
Expand All @@ -133,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
Expand All @@ -160,7 +185,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
Expand All @@ -172,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
Expand Down Expand Up @@ -203,9 +230,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 {
Expand Down Expand Up @@ -256,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 {
Expand All @@ -285,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
}
Expand Down
Loading
Loading