@powersync/common 0.0.0-dev-20260503073249 → 0.0.0-dev-20260630141119

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (284) hide show
  1. package/lib/attachments/AttachmentContext.d.ts +9 -8
  2. package/lib/attachments/AttachmentContext.js +8 -3
  3. package/lib/attachments/AttachmentContext.js.map +1 -1
  4. package/lib/attachments/AttachmentErrorHandler.d.ts +6 -6
  5. package/lib/attachments/AttachmentQueue.d.ts +85 -36
  6. package/lib/attachments/AttachmentQueue.js +19 -21
  7. package/lib/attachments/AttachmentQueue.js.map +1 -1
  8. package/lib/attachments/AttachmentService.d.ts +3 -3
  9. package/lib/attachments/AttachmentService.js +4 -3
  10. package/lib/attachments/AttachmentService.js.map +1 -1
  11. package/lib/attachments/LocalStorageAdapter.d.ts +14 -8
  12. package/lib/attachments/LocalStorageAdapter.js +3 -0
  13. package/lib/attachments/LocalStorageAdapter.js.map +1 -1
  14. package/lib/attachments/RemoteStorageAdapter.d.ts +4 -4
  15. package/lib/attachments/Schema.d.ts +14 -6
  16. package/lib/attachments/Schema.js +8 -3
  17. package/lib/attachments/Schema.js.map +1 -1
  18. package/lib/attachments/SyncingService.d.ts +2 -2
  19. package/lib/attachments/SyncingService.js +8 -3
  20. package/lib/attachments/SyncingService.js.map +1 -1
  21. package/lib/attachments/WatchedAttachmentItem.d.ts +3 -1
  22. package/lib/client/{AbstractPowerSyncDatabase.d.ts → CommonPowerSyncDatabase.d.ts} +112 -238
  23. package/lib/client/CommonPowerSyncDatabase.js +2 -0
  24. package/lib/client/CommonPowerSyncDatabase.js.map +1 -0
  25. package/lib/client/Query.d.ts +9 -0
  26. package/lib/client/SQLOpenFactory.d.ts +44 -10
  27. package/lib/client/SQLOpenFactory.js +1 -19
  28. package/lib/client/SQLOpenFactory.js.map +1 -1
  29. package/lib/client/compilableQueryWatch.d.ts +8 -2
  30. package/lib/client/compilableQueryWatch.js +4 -2
  31. package/lib/client/compilableQueryWatch.js.map +1 -1
  32. package/lib/client/connection/PowerSyncBackendConnector.d.ts +6 -3
  33. package/lib/client/connection/PowerSyncCredentials.d.ts +3 -0
  34. package/lib/client/runOnSchemaChange.d.ts +5 -2
  35. package/lib/client/runOnSchemaChange.js +3 -0
  36. package/lib/client/runOnSchemaChange.js.map +1 -1
  37. package/lib/client/sync/bucket/CrudBatch.d.ts +2 -0
  38. package/lib/client/sync/bucket/CrudBatch.js +2 -0
  39. package/lib/client/sync/bucket/CrudBatch.js.map +1 -1
  40. package/lib/client/sync/bucket/CrudEntry.d.ts +9 -31
  41. package/lib/client/sync/bucket/CrudEntry.js +2 -97
  42. package/lib/client/sync/bucket/CrudEntry.js.map +1 -1
  43. package/lib/client/sync/bucket/CrudTransaction.d.ts +3 -0
  44. package/lib/client/sync/bucket/CrudTransaction.js +3 -0
  45. package/lib/client/sync/bucket/CrudTransaction.js.map +1 -1
  46. package/lib/client/sync/options.d.ts +65 -0
  47. package/lib/client/sync/options.js +25 -0
  48. package/lib/client/sync/options.js.map +1 -0
  49. package/lib/client/sync/stream/JsonValue.d.ts +10 -0
  50. package/lib/client/sync/stream/JsonValue.js +2 -0
  51. package/lib/client/sync/stream/JsonValue.js.map +1 -0
  52. package/lib/client/sync/sync-streams.d.ts +23 -8
  53. package/lib/client/triggers/TriggerManager.d.ts +28 -56
  54. package/lib/client/triggers/TriggerManager.js +2 -1
  55. package/lib/client/triggers/TriggerManager.js.map +1 -1
  56. package/lib/client/triggers/sanitizeSQL.d.ts +4 -0
  57. package/lib/client/triggers/sanitizeSQL.js +4 -0
  58. package/lib/client/triggers/sanitizeSQL.js.map +1 -1
  59. package/lib/client/watched/GetAllQuery.d.ts +7 -3
  60. package/lib/client/watched/GetAllQuery.js +3 -1
  61. package/lib/client/watched/GetAllQuery.js.map +1 -1
  62. package/lib/client/watched/WatchedQuery.d.ts +20 -6
  63. package/lib/client/watched/WatchedQuery.js +3 -5
  64. package/lib/client/watched/WatchedQuery.js.map +1 -1
  65. package/lib/client/watched/processors/DifferentialQueryProcessor.d.ts +15 -45
  66. package/lib/client/watched/processors/DifferentialQueryProcessor.js +1 -172
  67. package/lib/client/watched/processors/DifferentialQueryProcessor.js.map +1 -1
  68. package/lib/client/watched/processors/OnChangeQueryProcessor.d.ts +4 -22
  69. package/lib/client/watched/processors/OnChangeQueryProcessor.js +1 -82
  70. package/lib/client/watched/processors/OnChangeQueryProcessor.js.map +1 -1
  71. package/lib/client/watched/processors/comparators.d.ts +8 -0
  72. package/lib/client/watched/processors/comparators.js +4 -0
  73. package/lib/client/watched/processors/comparators.js.map +1 -1
  74. package/lib/db/DBAdapter.d.ts +90 -113
  75. package/lib/db/DBAdapter.js +70 -89
  76. package/lib/db/DBAdapter.js.map +1 -1
  77. package/lib/db/QueryResult.d.ts +104 -0
  78. package/lib/db/QueryResult.js +96 -0
  79. package/lib/db/QueryResult.js.map +1 -0
  80. package/lib/db/crud/SyncProgress.d.ts +7 -14
  81. package/lib/db/crud/SyncProgress.js +1 -60
  82. package/lib/db/crud/SyncProgress.js.map +1 -1
  83. package/lib/db/crud/SyncStatus.d.ts +54 -91
  84. package/lib/db/crud/SyncStatus.js +1 -245
  85. package/lib/db/crud/SyncStatus.js.map +1 -1
  86. package/lib/db/crud/UploadQueueStatus.d.ts +3 -0
  87. package/lib/db/crud/UploadQueueStatus.js +3 -0
  88. package/lib/db/crud/UploadQueueStatus.js.map +1 -1
  89. package/lib/db/schema/Column.d.ts +22 -1
  90. package/lib/db/schema/Column.js +10 -4
  91. package/lib/db/schema/Column.js.map +1 -1
  92. package/lib/db/schema/Index.d.ts +8 -3
  93. package/lib/db/schema/Index.js +4 -1
  94. package/lib/db/schema/Index.js.map +1 -1
  95. package/lib/db/schema/IndexedColumn.d.ts +8 -3
  96. package/lib/db/schema/IndexedColumn.js +4 -1
  97. package/lib/db/schema/IndexedColumn.js.map +1 -1
  98. package/lib/db/schema/RawTable.d.ts +7 -1
  99. package/lib/db/schema/Schema.d.ts +10 -29
  100. package/lib/db/schema/Schema.js +3 -1
  101. package/lib/db/schema/Schema.js.map +1 -1
  102. package/lib/db/schema/Table.d.ts +69 -91
  103. package/lib/db/schema/Table.js +88 -87
  104. package/lib/db/schema/Table.js.map +1 -1
  105. package/lib/index.d.ts +7 -27
  106. package/lib/index.js +6 -27
  107. package/lib/index.js.map +1 -1
  108. package/lib/types/types.d.ts +6 -0
  109. package/lib/utils/BaseObserver.d.ts +12 -0
  110. package/lib/utils/BaseObserver.js +3 -0
  111. package/lib/utils/BaseObserver.js.map +1 -1
  112. package/lib/utils/Logger.d.ts +60 -22
  113. package/lib/utils/Logger.js +38 -30
  114. package/lib/utils/Logger.js.map +1 -1
  115. package/lib/utils/MetaBaseObserver.d.ts +11 -11
  116. package/lib/utils/MetaBaseObserver.js +1 -50
  117. package/lib/utils/MetaBaseObserver.js.map +1 -1
  118. package/lib/utils/mutex.d.ts +3 -45
  119. package/lib/utils/mutex.js +1 -153
  120. package/lib/utils/mutex.js.map +1 -1
  121. package/package.json +8 -42
  122. package/src/attachments/AttachmentContext.ts +15 -13
  123. package/src/attachments/AttachmentErrorHandler.ts +6 -6
  124. package/src/attachments/AttachmentQueue.ts +99 -42
  125. package/src/attachments/AttachmentService.ts +7 -6
  126. package/src/attachments/LocalStorageAdapter.ts +14 -8
  127. package/src/attachments/README.md +2 -0
  128. package/src/attachments/RemoteStorageAdapter.ts +4 -4
  129. package/src/attachments/Schema.ts +14 -6
  130. package/src/attachments/SyncingService.ts +10 -6
  131. package/src/attachments/WatchedAttachmentItem.ts +3 -1
  132. package/src/client/CommonPowerSyncDatabase.ts +540 -0
  133. package/src/client/Query.ts +9 -0
  134. package/src/client/SQLOpenFactory.ts +47 -19
  135. package/src/client/compilableQueryWatch.ts +9 -4
  136. package/src/client/connection/PowerSyncBackendConnector.ts +6 -3
  137. package/src/client/connection/PowerSyncCredentials.ts +3 -0
  138. package/src/client/runOnSchemaChange.ts +5 -2
  139. package/src/client/sync/bucket/CrudBatch.ts +2 -0
  140. package/src/client/sync/bucket/CrudEntry.ts +10 -101
  141. package/src/client/sync/bucket/CrudTransaction.ts +3 -0
  142. package/src/client/sync/options.ts +77 -0
  143. package/src/client/sync/stream/JsonValue.ts +11 -0
  144. package/src/client/sync/sync-streams.ts +23 -10
  145. package/src/client/triggers/TriggerManager.ts +29 -59
  146. package/src/client/triggers/sanitizeSQL.ts +5 -0
  147. package/src/client/watched/GetAllQuery.ts +8 -4
  148. package/src/client/watched/WatchedQuery.ts +20 -11
  149. package/src/client/watched/processors/DifferentialQueryProcessor.ts +19 -219
  150. package/src/client/watched/processors/OnChangeQueryProcessor.ts +4 -109
  151. package/src/client/watched/processors/comparators.ts +8 -0
  152. package/src/db/DBAdapter.ts +160 -175
  153. package/src/db/QueryResult.ts +195 -0
  154. package/src/db/crud/SyncProgress.ts +8 -43
  155. package/src/db/crud/SyncStatus.ts +66 -216
  156. package/src/db/crud/UploadQueueStatus.ts +3 -0
  157. package/src/db/schema/Column.ts +22 -5
  158. package/src/db/schema/Index.ts +9 -3
  159. package/src/db/schema/IndexedColumn.ts +9 -3
  160. package/src/db/schema/RawTable.ts +7 -1
  161. package/src/db/schema/Schema.ts +12 -7
  162. package/src/db/schema/Table.ts +130 -180
  163. package/src/index.ts +7 -27
  164. package/src/types/types.ts +6 -0
  165. package/src/utils/BaseObserver.ts +12 -0
  166. package/src/utils/Logger.ts +86 -31
  167. package/src/utils/MetaBaseObserver.ts +14 -60
  168. package/src/utils/mutex.ts +4 -189
  169. package/dist/bundle.cjs +0 -14781
  170. package/dist/bundle.cjs.map +0 -1
  171. package/dist/bundle.mjs +0 -14689
  172. package/dist/bundle.mjs.map +0 -1
  173. package/dist/bundle.node.cjs +0 -12258
  174. package/dist/bundle.node.cjs.map +0 -1
  175. package/dist/bundle.node.mjs +0 -12166
  176. package/dist/bundle.node.mjs.map +0 -1
  177. package/dist/index.d.cts +0 -4391
  178. package/lib/client/AbstractPowerSyncDatabase.js +0 -987
  179. package/lib/client/AbstractPowerSyncDatabase.js.map +0 -1
  180. package/lib/client/AbstractPowerSyncOpenFactory.d.ts +0 -22
  181. package/lib/client/AbstractPowerSyncOpenFactory.js +0 -25
  182. package/lib/client/AbstractPowerSyncOpenFactory.js.map +0 -1
  183. package/lib/client/ConnectionManager.d.ts +0 -112
  184. package/lib/client/ConnectionManager.js +0 -294
  185. package/lib/client/ConnectionManager.js.map +0 -1
  186. package/lib/client/CustomQuery.d.ts +0 -22
  187. package/lib/client/CustomQuery.js +0 -43
  188. package/lib/client/CustomQuery.js.map +0 -1
  189. package/lib/client/constants.d.ts +0 -1
  190. package/lib/client/constants.js +0 -2
  191. package/lib/client/constants.js.map +0 -1
  192. package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +0 -102
  193. package/lib/client/sync/bucket/BucketStorageAdapter.js +0 -19
  194. package/lib/client/sync/bucket/BucketStorageAdapter.js.map +0 -1
  195. package/lib/client/sync/bucket/OpType.d.ts +0 -16
  196. package/lib/client/sync/bucket/OpType.js +0 -23
  197. package/lib/client/sync/bucket/OpType.js.map +0 -1
  198. package/lib/client/sync/bucket/OplogEntry.d.ts +0 -23
  199. package/lib/client/sync/bucket/OplogEntry.js +0 -36
  200. package/lib/client/sync/bucket/OplogEntry.js.map +0 -1
  201. package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +0 -61
  202. package/lib/client/sync/bucket/SqliteBucketStorage.js +0 -324
  203. package/lib/client/sync/bucket/SqliteBucketStorage.js.map +0 -1
  204. package/lib/client/sync/bucket/SyncDataBatch.d.ts +0 -6
  205. package/lib/client/sync/bucket/SyncDataBatch.js +0 -12
  206. package/lib/client/sync/bucket/SyncDataBatch.js.map +0 -1
  207. package/lib/client/sync/bucket/SyncDataBucket.d.ts +0 -40
  208. package/lib/client/sync/bucket/SyncDataBucket.js +0 -40
  209. package/lib/client/sync/bucket/SyncDataBucket.js.map +0 -1
  210. package/lib/client/sync/stream/AbstractRemote.d.ts +0 -161
  211. package/lib/client/sync/stream/AbstractRemote.js +0 -483
  212. package/lib/client/sync/stream/AbstractRemote.js.map +0 -1
  213. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +0 -244
  214. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +0 -990
  215. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +0 -1
  216. package/lib/client/sync/stream/WebsocketClientTransport.d.ts +0 -15
  217. package/lib/client/sync/stream/WebsocketClientTransport.js +0 -61
  218. package/lib/client/sync/stream/WebsocketClientTransport.js.map +0 -1
  219. package/lib/client/sync/stream/core-instruction.d.ts +0 -72
  220. package/lib/client/sync/stream/core-instruction.js +0 -27
  221. package/lib/client/sync/stream/core-instruction.js.map +0 -1
  222. package/lib/client/sync/stream/streaming-sync-types.d.ts +0 -143
  223. package/lib/client/sync/stream/streaming-sync-types.js +0 -26
  224. package/lib/client/sync/stream/streaming-sync-types.js.map +0 -1
  225. package/lib/client/triggers/MemoryTriggerClaimManager.d.ts +0 -6
  226. package/lib/client/triggers/MemoryTriggerClaimManager.js +0 -21
  227. package/lib/client/triggers/MemoryTriggerClaimManager.js.map +0 -1
  228. package/lib/client/triggers/TriggerManagerImpl.d.ts +0 -39
  229. package/lib/client/triggers/TriggerManagerImpl.js +0 -405
  230. package/lib/client/triggers/TriggerManagerImpl.js.map +0 -1
  231. package/lib/client/watched/processors/AbstractQueryProcessor.d.ts +0 -68
  232. package/lib/client/watched/processors/AbstractQueryProcessor.js +0 -151
  233. package/lib/client/watched/processors/AbstractQueryProcessor.js.map +0 -1
  234. package/lib/db/ConnectionClosedError.d.ts +0 -10
  235. package/lib/db/ConnectionClosedError.js +0 -21
  236. package/lib/db/ConnectionClosedError.js.map +0 -1
  237. package/lib/db/schema/TableV2.d.ts +0 -9
  238. package/lib/db/schema/TableV2.js +0 -9
  239. package/lib/db/schema/TableV2.js.map +0 -1
  240. package/lib/utils/AbortOperation.d.ts +0 -9
  241. package/lib/utils/AbortOperation.js +0 -19
  242. package/lib/utils/AbortOperation.js.map +0 -1
  243. package/lib/utils/ControlledExecutor.d.ts +0 -25
  244. package/lib/utils/ControlledExecutor.js +0 -51
  245. package/lib/utils/ControlledExecutor.js.map +0 -1
  246. package/lib/utils/async.d.ts +0 -14
  247. package/lib/utils/async.js +0 -46
  248. package/lib/utils/async.js.map +0 -1
  249. package/lib/utils/parseQuery.d.ts +0 -6
  250. package/lib/utils/parseQuery.js +0 -17
  251. package/lib/utils/parseQuery.js.map +0 -1
  252. package/lib/utils/queue.d.ts +0 -16
  253. package/lib/utils/queue.js +0 -42
  254. package/lib/utils/queue.js.map +0 -1
  255. package/lib/utils/stream_transform.d.ts +0 -39
  256. package/lib/utils/stream_transform.js +0 -206
  257. package/lib/utils/stream_transform.js.map +0 -1
  258. package/src/client/AbstractPowerSyncDatabase.ts +0 -1362
  259. package/src/client/AbstractPowerSyncOpenFactory.ts +0 -39
  260. package/src/client/ConnectionManager.ts +0 -402
  261. package/src/client/CustomQuery.ts +0 -56
  262. package/src/client/constants.ts +0 -1
  263. package/src/client/sync/bucket/BucketStorageAdapter.ts +0 -118
  264. package/src/client/sync/bucket/OpType.ts +0 -23
  265. package/src/client/sync/bucket/OplogEntry.ts +0 -50
  266. package/src/client/sync/bucket/SqliteBucketStorage.ts +0 -395
  267. package/src/client/sync/bucket/SyncDataBatch.ts +0 -11
  268. package/src/client/sync/bucket/SyncDataBucket.ts +0 -49
  269. package/src/client/sync/stream/AbstractRemote.ts +0 -624
  270. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +0 -1285
  271. package/src/client/sync/stream/WebsocketClientTransport.ts +0 -80
  272. package/src/client/sync/stream/core-instruction.ts +0 -99
  273. package/src/client/sync/stream/streaming-sync-types.ts +0 -210
  274. package/src/client/triggers/MemoryTriggerClaimManager.ts +0 -25
  275. package/src/client/triggers/TriggerManagerImpl.ts +0 -496
  276. package/src/client/watched/processors/AbstractQueryProcessor.ts +0 -226
  277. package/src/db/ConnectionClosedError.ts +0 -23
  278. package/src/db/schema/TableV2.ts +0 -9
  279. package/src/utils/AbortOperation.ts +0 -17
  280. package/src/utils/ControlledExecutor.ts +0 -72
  281. package/src/utils/async.ts +0 -50
  282. package/src/utils/parseQuery.ts +0 -25
  283. package/src/utils/queue.ts +0 -48
  284. package/src/utils/stream_transform.ts +0 -252
@@ -1,990 +0,0 @@
1
- import Logger from 'js-logger';
2
- import { SyncStatus } from '../../../db/crud/SyncStatus.js';
3
- import { AbortOperation } from '../../../utils/AbortOperation.js';
4
- import { BaseObserver } from '../../../utils/BaseObserver.js';
5
- import { throttleLeadingTrailing } from '../../../utils/async.js';
6
- import { PowerSyncControlCommand } from '../bucket/BucketStorageAdapter.js';
7
- import { SyncDataBucket } from '../bucket/SyncDataBucket.js';
8
- import { FetchStrategy } from './AbstractRemote.js';
9
- import { coreStatusToJs } from './core-instruction.js';
10
- import { isStreamingKeepalive, isStreamingSyncCheckpoint, isStreamingSyncCheckpointComplete, isStreamingSyncCheckpointDiff, isStreamingSyncCheckpointPartiallyComplete, isStreamingSyncData } from './streaming-sync-types.js';
11
- import { injectable, map } from '../../../utils/stream_transform.js';
12
- export var LockType;
13
- (function (LockType) {
14
- LockType["CRUD"] = "crud";
15
- LockType["SYNC"] = "sync";
16
- })(LockType || (LockType = {}));
17
- export var SyncStreamConnectionMethod;
18
- (function (SyncStreamConnectionMethod) {
19
- SyncStreamConnectionMethod["HTTP"] = "http";
20
- SyncStreamConnectionMethod["WEB_SOCKET"] = "web-socket";
21
- })(SyncStreamConnectionMethod || (SyncStreamConnectionMethod = {}));
22
- export var SyncClientImplementation;
23
- (function (SyncClientImplementation) {
24
- /**
25
- * Decodes and handles sync lines received from the sync service in JavaScript.
26
- *
27
- * This is the default option.
28
- *
29
- * @deprecated We recommend the {@link RUST} client implementation for all apps. If you have issues with
30
- * the Rust client, please file an issue or reach out to us. The JavaScript client will be removed in a future
31
- * version of the PowerSync SDK.
32
- */
33
- SyncClientImplementation["JAVASCRIPT"] = "js";
34
- /**
35
- * This implementation offloads the sync line decoding and handling into the PowerSync
36
- * core extension.
37
- *
38
- * This option is more performant than the {@link JAVASCRIPT} client, enabled by default and the
39
- * recommended client implementation for all apps.
40
- *
41
- * ## Compatibility warning
42
- *
43
- * The Rust sync client stores sync data in a format that is slightly different than the one used
44
- * by the old {@link JAVASCRIPT} implementation. When adopting the {@link RUST} client on existing
45
- * databases, the PowerSync SDK will migrate the format automatically.
46
- * Further, the {@link JAVASCRIPT} client in recent versions of the PowerSync JS SDK (starting from
47
- * the version introducing {@link RUST} as an option) also supports the new format, so you can switch
48
- * back to {@link JAVASCRIPT} later.
49
- *
50
- * __However__: Upgrading the SDK version, then adopting {@link RUST} as a sync client and later
51
- * downgrading the SDK to an older version (necessarily using the JavaScript-based implementation then)
52
- * can lead to sync issues.
53
- */
54
- SyncClientImplementation["RUST"] = "rust";
55
- })(SyncClientImplementation || (SyncClientImplementation = {}));
56
- /**
57
- * The default {@link SyncClientImplementation} to use, {@link SyncClientImplementation.RUST}.
58
- */
59
- export const DEFAULT_SYNC_CLIENT_IMPLEMENTATION = SyncClientImplementation.RUST;
60
- export const DEFAULT_CRUD_UPLOAD_THROTTLE_MS = 1000;
61
- export const DEFAULT_RETRY_DELAY_MS = 5000;
62
- export const DEFAULT_STREAMING_SYNC_OPTIONS = {
63
- retryDelayMs: DEFAULT_RETRY_DELAY_MS,
64
- crudUploadThrottleMs: DEFAULT_CRUD_UPLOAD_THROTTLE_MS
65
- };
66
- export const DEFAULT_STREAM_CONNECTION_OPTIONS = {
67
- appMetadata: {},
68
- connectionMethod: SyncStreamConnectionMethod.WEB_SOCKET,
69
- clientImplementation: DEFAULT_SYNC_CLIENT_IMPLEMENTATION,
70
- fetchStrategy: FetchStrategy.Buffered,
71
- params: {},
72
- serializedSchema: undefined,
73
- includeDefaultStreams: true
74
- };
75
- // The priority we assume when we receive checkpoint lines where no priority is set.
76
- // This is the default priority used by the sync service, but can be set to an arbitrary
77
- // value since sync services without priorities also won't send partial sync completion
78
- // messages.
79
- const FALLBACK_PRIORITY = 3;
80
- export class AbstractStreamingSyncImplementation extends BaseObserver {
81
- _lastSyncedAt;
82
- options;
83
- abortController;
84
- // In rare cases, mostly for tests, uploads can be triggered without being properly connected.
85
- // This allows ensuring that all upload processes can be aborted.
86
- uploadAbortController;
87
- crudUpdateListener;
88
- streamingSyncPromise;
89
- logger;
90
- activeStreams;
91
- connectionMayHaveChanged = false;
92
- isUploadingCrud = false;
93
- notifyCompletedUploads;
94
- handleActiveStreamsChange;
95
- syncStatus;
96
- triggerCrudUpload;
97
- constructor(options) {
98
- super();
99
- this.options = options;
100
- this.activeStreams = options.subscriptions;
101
- this.logger = options.logger ?? Logger.get('PowerSyncStream');
102
- this.syncStatus = new SyncStatus({
103
- connected: false,
104
- connecting: false,
105
- lastSyncedAt: undefined,
106
- dataFlow: {
107
- uploading: false,
108
- downloading: false
109
- }
110
- });
111
- this.abortController = null;
112
- this.triggerCrudUpload = throttleLeadingTrailing(() => {
113
- if (!this.syncStatus.connected || this.isUploadingCrud) {
114
- return;
115
- }
116
- this.isUploadingCrud = true;
117
- this._uploadAllCrud().finally(() => {
118
- this.notifyCompletedUploads?.();
119
- this.isUploadingCrud = false;
120
- });
121
- }, this.options.crudUploadThrottleMs);
122
- }
123
- async waitForReady() { }
124
- waitForStatus(status) {
125
- return this.waitUntilStatusMatches((currentStatus) => {
126
- /**
127
- * Match only the partial status options provided in the
128
- * matching status
129
- */
130
- const matchPartialObject = (compA, compB) => {
131
- return Object.entries(compA).every(([key, value]) => {
132
- const comparisonBValue = compB[key];
133
- if (typeof value == 'object' && typeof comparisonBValue == 'object') {
134
- return matchPartialObject(value, comparisonBValue);
135
- }
136
- return value == comparisonBValue;
137
- });
138
- };
139
- return matchPartialObject(status, currentStatus);
140
- });
141
- }
142
- waitUntilStatusMatches(predicate) {
143
- return new Promise((resolve) => {
144
- if (predicate(this.syncStatus)) {
145
- resolve();
146
- return;
147
- }
148
- const l = this.registerListener({
149
- statusChanged: (updatedStatus) => {
150
- if (predicate(updatedStatus)) {
151
- resolve();
152
- l?.();
153
- }
154
- }
155
- });
156
- });
157
- }
158
- get lastSyncedAt() {
159
- const lastSynced = this.syncStatus.lastSyncedAt;
160
- return lastSynced && new Date(lastSynced);
161
- }
162
- get isConnected() {
163
- return this.syncStatus.connected;
164
- }
165
- async dispose() {
166
- super.dispose();
167
- this.crudUpdateListener?.();
168
- this.crudUpdateListener = undefined;
169
- this.uploadAbortController?.abort();
170
- }
171
- async hasCompletedSync() {
172
- return this.options.adapter.hasCompletedSync();
173
- }
174
- async getWriteCheckpoint() {
175
- const clientId = await this.options.adapter.getClientId();
176
- let path = `/write-checkpoint2.json?client_id=${clientId}`;
177
- const response = await this.options.remote.get(path);
178
- const checkpoint = response['data']['write_checkpoint'];
179
- this.logger.debug(`Created write checkpoint: ${checkpoint}`);
180
- return checkpoint;
181
- }
182
- async _uploadAllCrud() {
183
- return this.obtainLock({
184
- type: LockType.CRUD,
185
- callback: async () => {
186
- /**
187
- * Keep track of the first item in the CRUD queue for the last `uploadCrud` iteration.
188
- */
189
- let checkedCrudItem;
190
- const controller = new AbortController();
191
- this.uploadAbortController = controller;
192
- this.abortController?.signal.addEventListener('abort', () => {
193
- controller.abort();
194
- }, { once: true });
195
- while (!controller.signal.aborted) {
196
- try {
197
- /**
198
- * This is the first item in the FIFO CRUD queue.
199
- */
200
- const nextCrudItem = await this.options.adapter.nextCrudItem();
201
- if (nextCrudItem) {
202
- this.updateSyncStatus({
203
- dataFlow: {
204
- uploading: true
205
- }
206
- });
207
- if (nextCrudItem.clientId == checkedCrudItem?.clientId) {
208
- // This will force a higher log level than exceptions which are caught here.
209
- this.logger.warn(`Potentially previously uploaded CRUD entries are still present in the upload queue.
210
- Make sure to handle uploads and complete CRUD transactions or batches by calling and awaiting their [.complete()] method.
211
- The next upload iteration will be delayed.`);
212
- throw new Error('Delaying due to previously encountered CRUD item.');
213
- }
214
- checkedCrudItem = nextCrudItem;
215
- await this.options.uploadCrud();
216
- this.updateSyncStatus({
217
- dataFlow: {
218
- uploadError: undefined
219
- }
220
- });
221
- }
222
- else {
223
- // Uploading is completed
224
- const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint());
225
- if (neededUpdate == false && checkedCrudItem != null) {
226
- // Only log this if there was something to upload
227
- this.logger.debug('Upload complete, no write checkpoint needed.');
228
- }
229
- break;
230
- }
231
- }
232
- catch (ex) {
233
- checkedCrudItem = undefined;
234
- this.updateSyncStatus({
235
- dataFlow: {
236
- uploading: false,
237
- uploadError: ex
238
- }
239
- });
240
- await this.delayRetry(controller.signal);
241
- if (!this.isConnected) {
242
- // Exit the upload loop if the sync stream is no longer connected
243
- break;
244
- }
245
- this.logger.debug(`Caught exception when uploading. Upload will retry after a delay. Exception: ${ex.message}`);
246
- }
247
- finally {
248
- this.updateSyncStatus({
249
- dataFlow: {
250
- uploading: false
251
- }
252
- });
253
- }
254
- }
255
- this.uploadAbortController = null;
256
- }
257
- });
258
- }
259
- async connect(options) {
260
- if (this.abortController) {
261
- await this.disconnect();
262
- }
263
- const controller = new AbortController();
264
- this.abortController = controller;
265
- this.streamingSyncPromise = this.streamingSync(this.abortController.signal, options);
266
- // Return a promise that resolves when the connection status is updated to indicate that we're connected.
267
- return new Promise((resolve) => {
268
- const disposer = this.registerListener({
269
- statusChanged: (status) => {
270
- if (status.dataFlowStatus.downloadError != null) {
271
- this.logger.warn('Initial connect attempt did not successfully connect to server');
272
- }
273
- else if (status.connecting) {
274
- // Still connecting.
275
- return;
276
- }
277
- disposer();
278
- resolve();
279
- }
280
- });
281
- });
282
- }
283
- async disconnect() {
284
- if (!this.abortController) {
285
- return;
286
- }
287
- // This might be called multiple times
288
- if (!this.abortController.signal.aborted) {
289
- this.abortController.abort(new AbortOperation('Disconnect has been requested'));
290
- }
291
- // Await any pending operations before completing the disconnect operation
292
- try {
293
- await this.streamingSyncPromise;
294
- }
295
- catch (ex) {
296
- // The operation might have failed, all we care about is if it has completed
297
- this.logger.warn(ex);
298
- }
299
- this.streamingSyncPromise = undefined;
300
- this.abortController = null;
301
- this.updateSyncStatus({ connected: false, connecting: false });
302
- }
303
- /**
304
- * @deprecated use [connect instead]
305
- */
306
- async streamingSync(signal, options) {
307
- if (!signal) {
308
- this.abortController = new AbortController();
309
- signal = this.abortController.signal;
310
- }
311
- /**
312
- * Listen for CRUD updates and trigger upstream uploads
313
- */
314
- this.crudUpdateListener = this.options.adapter.registerListener({
315
- crudUpdate: () => this.triggerCrudUpload()
316
- });
317
- /**
318
- * Create a new abort controller which aborts items downstream.
319
- * This is needed to close any previous connections on exception.
320
- */
321
- let nestedAbortController = new AbortController();
322
- signal.addEventListener('abort', () => {
323
- /**
324
- * A request for disconnect was received upstream. Relay the request
325
- * to the nested abort controller.
326
- */
327
- nestedAbortController.abort(signal?.reason ?? new AbortOperation('Received command to disconnect from upstream'));
328
- this.crudUpdateListener?.();
329
- this.crudUpdateListener = undefined;
330
- this.updateSyncStatus({
331
- connected: false,
332
- connecting: false,
333
- dataFlow: {
334
- downloading: false,
335
- downloadProgress: null
336
- }
337
- });
338
- });
339
- /**
340
- * This loops runs until [retry] is false or the abort signal is set to aborted.
341
- * Aborting the nestedAbortController will:
342
- * - Abort any pending fetch requests
343
- * - Close any sync stream ReadableStreams (which will also close any established network requests)
344
- */
345
- while (true) {
346
- this.updateSyncStatus({ connecting: true });
347
- let shouldDelayRetry = true;
348
- let result = null;
349
- try {
350
- if (signal?.aborted) {
351
- break;
352
- }
353
- result = await this.streamingSyncIteration(nestedAbortController.signal, options);
354
- // Continue immediately, streamingSyncIteration will wait before completing if necessary.
355
- }
356
- catch (ex) {
357
- /**
358
- * Either:
359
- * - A network request failed with a failed connection or not OKAY response code.
360
- * - There was a sync processing error.
361
- * - The connection was aborted.
362
- * This loop will retry after a delay if the connection was not aborted.
363
- * The nested abort controller will cleanup any open network requests and streams.
364
- * The WebRemote should only abort pending fetch requests or close active Readable streams.
365
- */
366
- if (ex instanceof AbortOperation) {
367
- this.logger.warn(ex);
368
- shouldDelayRetry = false;
369
- // A disconnect was requested, we should not delay since there is no explicit retry
370
- }
371
- else if (this.connectionMayHaveChanged && ex.message?.indexOf('No iteration is active') >= 0) {
372
- this.connectionMayHaveChanged = false;
373
- this.logger.info('Sync error after changed connection, retrying immediately');
374
- shouldDelayRetry = false;
375
- }
376
- else {
377
- this.logger.error(ex);
378
- }
379
- this.updateSyncStatus({
380
- dataFlow: {
381
- downloadError: ex
382
- }
383
- });
384
- }
385
- finally {
386
- this.notifyCompletedUploads = undefined;
387
- if (!signal.aborted) {
388
- nestedAbortController.abort(new AbortOperation('Closing sync stream network requests before retry.'));
389
- nestedAbortController = new AbortController();
390
- }
391
- if (result?.immediateRestart != true) {
392
- this.updateSyncStatus({
393
- connected: false,
394
- connecting: true // May be unnecessary
395
- });
396
- // On error, wait a little before retrying
397
- if (shouldDelayRetry) {
398
- await this.delayRetry(nestedAbortController.signal);
399
- }
400
- }
401
- }
402
- }
403
- // Mark as disconnected if here
404
- this.updateSyncStatus({ connected: false, connecting: false });
405
- }
406
- markConnectionMayHaveChanged() {
407
- // By setting this field, we'll immediately retry if the next sync event causes an error triggered by us not having
408
- // an active sync iteration on the connection in use.
409
- this.connectionMayHaveChanged = true;
410
- // This triggers a `powersync_control` invocation if a sync iteration is currently active. This is a cheap call to
411
- // make when no subscriptions have actually changed, we're mainly interested in this immediately throwing if no
412
- // iteration is active. That allows us to reconnect ASAP, instead of having to wait for the next sync line.
413
- this.handleActiveStreamsChange?.();
414
- }
415
- async collectLocalBucketState() {
416
- const bucketEntries = await this.options.adapter.getBucketStates();
417
- const req = bucketEntries.map((entry) => ({
418
- name: entry.bucket,
419
- after: entry.op_id
420
- }));
421
- const localDescriptions = new Map();
422
- for (const entry of bucketEntries) {
423
- localDescriptions.set(entry.bucket, null);
424
- }
425
- return [req, localDescriptions];
426
- }
427
- /**
428
- * Older versions of the JS SDK used to encode subkeys as JSON in {@link OplogEntry.toJSON}.
429
- * Because subkeys are always strings, this leads to quotes being added around them in `ps_oplog`.
430
- * While this is not a problem as long as it's done consistently, it causes issues when a database
431
- * created by the JS SDK is used with other SDKs, or (more likely) when the new Rust sync client
432
- * is enabled.
433
- *
434
- * So, we add a migration from the old key format (with quotes) to the new one (no quotes). The
435
- * migration is only triggered when necessary (for now). The function returns whether the new format
436
- * should be used, so that the JS SDK is able to write to updated databases.
437
- *
438
- * @param requireFixedKeyFormat Whether we require the new format or also support the old one.
439
- * The Rust client requires the new subkey format.
440
- * @returns Whether the database is now using the new, fixed subkey format.
441
- */
442
- async requireKeyFormat(requireFixedKeyFormat) {
443
- const hasMigrated = await this.options.adapter.hasMigratedSubkeys();
444
- if (requireFixedKeyFormat && !hasMigrated) {
445
- await this.options.adapter.migrateToFixedSubkeys();
446
- return true;
447
- }
448
- else {
449
- return hasMigrated;
450
- }
451
- }
452
- streamingSyncIteration(signal, options) {
453
- return this.obtainLock({
454
- type: LockType.SYNC,
455
- signal,
456
- callback: async () => {
457
- const resolvedOptions = {
458
- ...DEFAULT_STREAM_CONNECTION_OPTIONS,
459
- ...(options ?? {})
460
- };
461
- // Validate app metadata
462
- const invalidMetadata = Object.entries(resolvedOptions.appMetadata).filter(([_, value]) => typeof value != 'string');
463
- if (invalidMetadata.length > 0) {
464
- throw new Error(`Invalid appMetadata provided. Only string values are allowed. Invalid values: ${invalidMetadata.map(([key, value]) => `${key}: ${value}`).join(', ')}`);
465
- }
466
- const clientImplementation = resolvedOptions.clientImplementation;
467
- this.updateSyncStatus({ clientImplementation });
468
- if (clientImplementation == SyncClientImplementation.JAVASCRIPT) {
469
- await this.legacyStreamingSyncIteration(signal, resolvedOptions);
470
- return null;
471
- }
472
- else {
473
- await this.requireKeyFormat(true);
474
- return await this.rustSyncIteration(signal, resolvedOptions);
475
- }
476
- }
477
- });
478
- }
479
- async receiveSyncLines(data) {
480
- const { options, connection, bson } = data;
481
- const remote = this.options.remote;
482
- if (connection.connectionMethod == SyncStreamConnectionMethod.HTTP) {
483
- return await remote.fetchStream(options);
484
- }
485
- else {
486
- return await this.options.remote.socketStreamRaw({
487
- ...options,
488
- ...{ fetchStrategy: connection.fetchStrategy }
489
- }, bson);
490
- }
491
- }
492
- async legacyStreamingSyncIteration(signal, resolvedOptions) {
493
- const rawTables = resolvedOptions.serializedSchema?.raw_tables;
494
- if (rawTables != null && rawTables.length) {
495
- this.logger.warn('Raw tables require the Rust-based sync client. The JS client will ignore them.');
496
- }
497
- if (this.activeStreams.length) {
498
- this.logger.error('Sync streams require `clientImplementation: SyncClientImplementation.RUST` when connecting.');
499
- }
500
- this.logger.debug('Streaming sync iteration started');
501
- this.options.adapter.startSession();
502
- let [req, bucketMap] = await this.collectLocalBucketState();
503
- let targetCheckpoint = null;
504
- // A checkpoint that has been validated but not applied (e.g. due to pending local writes)
505
- let pendingValidatedCheckpoint = null;
506
- const clientId = await this.options.adapter.getClientId();
507
- const usingFixedKeyFormat = await this.requireKeyFormat(false);
508
- this.logger.debug('Requesting stream from server');
509
- const syncOptions = {
510
- path: '/sync/stream',
511
- abortSignal: signal,
512
- data: {
513
- buckets: req,
514
- include_checksum: true,
515
- raw_data: true,
516
- parameters: resolvedOptions.params,
517
- app_metadata: resolvedOptions.appMetadata,
518
- client_id: clientId
519
- }
520
- };
521
- const bson = await this.options.remote.getBSON();
522
- const source = await this.receiveSyncLines({
523
- options: syncOptions,
524
- connection: resolvedOptions,
525
- bson
526
- });
527
- const stream = injectable(map(source, (line) => {
528
- if (typeof line == 'string') {
529
- return JSON.parse(line);
530
- }
531
- else {
532
- return bson.deserialize(line);
533
- }
534
- }));
535
- this.logger.debug('Stream established. Processing events');
536
- this.notifyCompletedUploads = () => {
537
- stream.inject({ crud_upload_completed: null });
538
- };
539
- while (true) {
540
- const { value: line, done } = await stream.next();
541
- if (done) {
542
- // The stream has closed while waiting
543
- return;
544
- }
545
- if ('crud_upload_completed' in line) {
546
- if (pendingValidatedCheckpoint != null) {
547
- const { applied, endIteration } = await this.applyCheckpoint(pendingValidatedCheckpoint);
548
- if (applied) {
549
- pendingValidatedCheckpoint = null;
550
- }
551
- else if (endIteration) {
552
- break;
553
- }
554
- }
555
- continue;
556
- }
557
- // A connection is active and messages are being received
558
- if (!this.syncStatus.connected) {
559
- // There is a connection now
560
- Promise.resolve().then(() => this.triggerCrudUpload());
561
- this.updateSyncStatus({
562
- connected: true
563
- });
564
- }
565
- if (isStreamingSyncCheckpoint(line)) {
566
- targetCheckpoint = line.checkpoint;
567
- // New checkpoint - existing validated checkpoint is no longer valid
568
- pendingValidatedCheckpoint = null;
569
- const bucketsToDelete = new Set(bucketMap.keys());
570
- const newBuckets = new Map();
571
- for (const checksum of line.checkpoint.buckets) {
572
- newBuckets.set(checksum.bucket, {
573
- name: checksum.bucket,
574
- priority: checksum.priority ?? FALLBACK_PRIORITY
575
- });
576
- bucketsToDelete.delete(checksum.bucket);
577
- }
578
- if (bucketsToDelete.size > 0) {
579
- this.logger.debug('Removing buckets', [...bucketsToDelete]);
580
- }
581
- bucketMap = newBuckets;
582
- await this.options.adapter.removeBuckets([...bucketsToDelete]);
583
- await this.options.adapter.setTargetCheckpoint(targetCheckpoint);
584
- await this.updateSyncStatusForStartingCheckpoint(targetCheckpoint);
585
- }
586
- else if (isStreamingSyncCheckpointComplete(line)) {
587
- const result = await this.applyCheckpoint(targetCheckpoint);
588
- if (result.endIteration) {
589
- return;
590
- }
591
- else if (!result.applied) {
592
- // "Could not apply checkpoint due to local data". We need to retry after
593
- // finishing uploads.
594
- pendingValidatedCheckpoint = targetCheckpoint;
595
- }
596
- else {
597
- // Nothing to retry later. This would likely already be null from the last
598
- // checksum or checksum_diff operation, but we make sure.
599
- pendingValidatedCheckpoint = null;
600
- }
601
- }
602
- else if (isStreamingSyncCheckpointPartiallyComplete(line)) {
603
- const priority = line.partial_checkpoint_complete.priority;
604
- this.logger.debug('Partial checkpoint complete', priority);
605
- const result = await this.options.adapter.syncLocalDatabase(targetCheckpoint, priority);
606
- if (!result.checkpointValid) {
607
- // This means checksums failed. Start again with a new checkpoint.
608
- // TODO: better back-off
609
- await new Promise((resolve) => setTimeout(resolve, 50));
610
- return;
611
- }
612
- else if (!result.ready) {
613
- // If we have pending uploads, we can't complete new checkpoints outside of priority 0.
614
- // We'll resolve this for a complete checkpoint.
615
- }
616
- else {
617
- // We'll keep on downloading, but can report that this priority is synced now.
618
- this.logger.debug('partial checkpoint validation succeeded');
619
- // All states with a higher priority can be deleted since this partial sync includes them.
620
- const priorityStates = this.syncStatus.priorityStatusEntries.filter((s) => s.priority <= priority);
621
- priorityStates.push({
622
- priority,
623
- lastSyncedAt: new Date(),
624
- hasSynced: true
625
- });
626
- this.updateSyncStatus({
627
- connected: true,
628
- priorityStatusEntries: priorityStates
629
- });
630
- }
631
- }
632
- else if (isStreamingSyncCheckpointDiff(line)) {
633
- // TODO: It may be faster to just keep track of the diff, instead of the entire checkpoint
634
- if (targetCheckpoint == null) {
635
- throw new Error('Checkpoint diff without previous checkpoint');
636
- }
637
- // New checkpoint - existing validated checkpoint is no longer valid
638
- pendingValidatedCheckpoint = null;
639
- const diff = line.checkpoint_diff;
640
- const newBuckets = new Map();
641
- for (const checksum of targetCheckpoint.buckets) {
642
- newBuckets.set(checksum.bucket, checksum);
643
- }
644
- for (const checksum of diff.updated_buckets) {
645
- newBuckets.set(checksum.bucket, checksum);
646
- }
647
- for (const bucket of diff.removed_buckets) {
648
- newBuckets.delete(bucket);
649
- }
650
- const newCheckpoint = {
651
- last_op_id: diff.last_op_id,
652
- buckets: [...newBuckets.values()],
653
- write_checkpoint: diff.write_checkpoint
654
- };
655
- targetCheckpoint = newCheckpoint;
656
- await this.updateSyncStatusForStartingCheckpoint(targetCheckpoint);
657
- bucketMap = new Map();
658
- newBuckets.forEach((checksum, name) => bucketMap.set(name, {
659
- name: checksum.bucket,
660
- priority: checksum.priority ?? FALLBACK_PRIORITY
661
- }));
662
- const bucketsToDelete = diff.removed_buckets;
663
- if (bucketsToDelete.length > 0) {
664
- this.logger.debug('Remove buckets', bucketsToDelete);
665
- }
666
- await this.options.adapter.removeBuckets(bucketsToDelete);
667
- await this.options.adapter.setTargetCheckpoint(targetCheckpoint);
668
- }
669
- else if (isStreamingSyncData(line)) {
670
- const { data } = line;
671
- const previousProgress = this.syncStatus.dataFlowStatus.downloadProgress;
672
- let updatedProgress = null;
673
- if (previousProgress) {
674
- updatedProgress = { ...previousProgress };
675
- const progressForBucket = updatedProgress[data.bucket];
676
- if (progressForBucket) {
677
- updatedProgress[data.bucket] = {
678
- ...progressForBucket,
679
- since_last: progressForBucket.since_last + data.data.length
680
- };
681
- }
682
- }
683
- this.updateSyncStatus({
684
- dataFlow: {
685
- downloading: true,
686
- downloadProgress: updatedProgress
687
- }
688
- });
689
- await this.options.adapter.saveSyncData({ buckets: [SyncDataBucket.fromRow(data)] }, usingFixedKeyFormat);
690
- }
691
- else if (isStreamingKeepalive(line)) {
692
- const remaining_seconds = line.token_expires_in;
693
- if (remaining_seconds == 0) {
694
- // Connection would be closed automatically right after this
695
- this.logger.debug('Token expiring; reconnect');
696
- /**
697
- * For a rare case where the backend connector does not update the token
698
- * (uses the same one), this should have some delay.
699
- */
700
- await this.delayRetry();
701
- return;
702
- }
703
- else if (remaining_seconds < 30) {
704
- this.logger.debug('Token will expire soon; reconnect');
705
- // Pre-emptively refresh the token
706
- this.options.remote.invalidateCredentials();
707
- return;
708
- }
709
- this.triggerCrudUpload();
710
- }
711
- else {
712
- this.logger.debug('Received unknown sync line', line);
713
- }
714
- }
715
- this.logger.debug('Stream input empty');
716
- // Connection closed. Likely due to auth issue.
717
- return;
718
- }
719
- async rustSyncIteration(signal, resolvedOptions) {
720
- const syncImplementation = this;
721
- const adapter = this.options.adapter;
722
- const remote = this.options.remote;
723
- const controller = new AbortController();
724
- const abort = () => {
725
- return controller.abort(signal.reason);
726
- };
727
- signal.addEventListener('abort', abort);
728
- let receivingLines = null;
729
- let hadSyncLine = false;
730
- let hideDisconnectOnRestart = false;
731
- if (signal.aborted) {
732
- throw new AbortOperation('Connection request has been aborted');
733
- }
734
- // Pending sync lines received from the service, as well as local events that trigger a powersync_control
735
- // invocation (local events include refreshed tokens and completed uploads).
736
- // This is a single data stream so that we can handle all control calls from a single place.
737
- let controlInvocations = null;
738
- async function connect(instr) {
739
- const syncOptions = {
740
- path: '/sync/stream',
741
- abortSignal: controller.signal,
742
- data: instr.request
743
- };
744
- controlInvocations = injectable(map(await syncImplementation.receiveSyncLines({
745
- options: syncOptions,
746
- connection: resolvedOptions
747
- }), (line) => {
748
- if (typeof line == 'string') {
749
- return {
750
- command: PowerSyncControlCommand.PROCESS_TEXT_LINE,
751
- payload: line
752
- };
753
- }
754
- else {
755
- return {
756
- command: PowerSyncControlCommand.PROCESS_BSON_LINE,
757
- payload: line
758
- };
759
- }
760
- }));
761
- // The rust client will set connected: true after the first sync line because that's when it gets invoked, but
762
- // we're already connected here and can report that.
763
- syncImplementation.updateSyncStatus({ connected: true });
764
- try {
765
- while (true) {
766
- let event = await controlInvocations.next();
767
- if (event.done) {
768
- break;
769
- }
770
- const line = event.value;
771
- await control(line.command, line.payload);
772
- if (!hadSyncLine) {
773
- syncImplementation.triggerCrudUpload();
774
- hadSyncLine = true;
775
- }
776
- }
777
- }
778
- finally {
779
- abort();
780
- signal.removeEventListener('abort', abort);
781
- }
782
- }
783
- async function stop() {
784
- await control(PowerSyncControlCommand.STOP);
785
- }
786
- async function control(op, payload) {
787
- const rawResponse = await adapter.control(op, payload ?? null);
788
- const logger = syncImplementation.logger;
789
- logger.trace('powersync_control', op, payload == null || typeof payload == 'string' ? payload : '<bytes>', rawResponse);
790
- if (op != PowerSyncControlCommand.STOP) {
791
- // Evidently we have a working connection here, otherwise powersync_control would have failed.
792
- syncImplementation.connectionMayHaveChanged = false;
793
- }
794
- await handleInstructions(JSON.parse(rawResponse));
795
- }
796
- async function handleInstruction(instruction) {
797
- if ('LogLine' in instruction) {
798
- switch (instruction.LogLine.severity) {
799
- case 'DEBUG':
800
- syncImplementation.logger.debug(instruction.LogLine.line);
801
- break;
802
- case 'INFO':
803
- syncImplementation.logger.info(instruction.LogLine.line);
804
- break;
805
- case 'WARNING':
806
- syncImplementation.logger.warn(instruction.LogLine.line);
807
- break;
808
- }
809
- }
810
- else if ('UpdateSyncStatus' in instruction) {
811
- syncImplementation.updateSyncStatus(coreStatusToJs(instruction.UpdateSyncStatus.status));
812
- }
813
- else if ('EstablishSyncStream' in instruction) {
814
- if (receivingLines != null) {
815
- // Already connected, this shouldn't happen during a single iteration.
816
- throw 'Unexpected request to establish sync stream, already connected';
817
- }
818
- receivingLines = connect(instruction.EstablishSyncStream);
819
- }
820
- else if ('FetchCredentials' in instruction) {
821
- if (instruction.FetchCredentials.did_expire) {
822
- remote.invalidateCredentials();
823
- }
824
- else {
825
- remote.invalidateCredentials();
826
- // Restart iteration after the credentials have been refreshed.
827
- remote.fetchCredentials().then((_) => {
828
- controlInvocations?.inject({ command: PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED });
829
- }, (err) => {
830
- syncImplementation.logger.warn('Could not prefetch credentials', err);
831
- });
832
- }
833
- }
834
- else if ('CloseSyncStream' in instruction) {
835
- controller.abort();
836
- hideDisconnectOnRestart = instruction.CloseSyncStream.hide_disconnect;
837
- }
838
- else if ('FlushFileSystem' in instruction) {
839
- // Not necessary on JS platforms.
840
- }
841
- else if ('DidCompleteSync' in instruction) {
842
- syncImplementation.updateSyncStatus({
843
- dataFlow: {
844
- downloadError: undefined
845
- }
846
- });
847
- }
848
- }
849
- async function handleInstructions(instructions) {
850
- for (const instr of instructions) {
851
- await handleInstruction(instr);
852
- }
853
- }
854
- try {
855
- const options = {
856
- parameters: resolvedOptions.params,
857
- app_metadata: resolvedOptions.appMetadata,
858
- active_streams: this.activeStreams,
859
- include_defaults: resolvedOptions.includeDefaultStreams
860
- };
861
- if (resolvedOptions.serializedSchema) {
862
- options.schema = resolvedOptions.serializedSchema;
863
- }
864
- await control(PowerSyncControlCommand.START, JSON.stringify(options));
865
- this.notifyCompletedUploads = () => {
866
- controlInvocations?.inject({ command: PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });
867
- };
868
- this.handleActiveStreamsChange = () => {
869
- controlInvocations?.inject({
870
- command: PowerSyncControlCommand.UPDATE_SUBSCRIPTIONS,
871
- payload: JSON.stringify(this.activeStreams)
872
- });
873
- };
874
- await receivingLines;
875
- }
876
- finally {
877
- this.notifyCompletedUploads = this.handleActiveStreamsChange = undefined;
878
- await stop();
879
- }
880
- return { immediateRestart: hideDisconnectOnRestart };
881
- }
882
- async updateSyncStatusForStartingCheckpoint(checkpoint) {
883
- const localProgress = await this.options.adapter.getBucketOperationProgress();
884
- const progress = {};
885
- let invalidated = false;
886
- for (const bucket of checkpoint.buckets) {
887
- const savedProgress = localProgress[bucket.bucket];
888
- const atLast = savedProgress?.atLast ?? 0;
889
- const sinceLast = savedProgress?.sinceLast ?? 0;
890
- progress[bucket.bucket] = {
891
- // The fallback priority doesn't matter here, but 3 is the one newer versions of the sync service
892
- // will use by default.
893
- priority: bucket.priority ?? 3,
894
- at_last: atLast,
895
- since_last: sinceLast,
896
- target_count: bucket.count ?? 0
897
- };
898
- if (bucket.count != null && bucket.count < atLast + sinceLast) {
899
- // Either due to a defrag / sync rule deploy or a compaction operation, the size
900
- // of the bucket shrank so much that the local ops exceed the ops in the updated
901
- // bucket. We can't prossibly report progress in this case (it would overshoot 100%).
902
- invalidated = true;
903
- }
904
- }
905
- if (invalidated) {
906
- for (const bucket in progress) {
907
- const bucketProgress = progress[bucket];
908
- bucketProgress.at_last = 0;
909
- bucketProgress.since_last = 0;
910
- }
911
- }
912
- this.updateSyncStatus({
913
- dataFlow: {
914
- downloading: true,
915
- downloadProgress: progress
916
- }
917
- });
918
- }
919
- async applyCheckpoint(checkpoint) {
920
- let result = await this.options.adapter.syncLocalDatabase(checkpoint);
921
- if (!result.checkpointValid) {
922
- this.logger.debug(`Checksum mismatch in checkpoint ${checkpoint.last_op_id}, will reconnect`);
923
- // This means checksums failed. Start again with a new checkpoint.
924
- // TODO: better back-off
925
- await new Promise((resolve) => setTimeout(resolve, 50));
926
- return { applied: false, endIteration: true };
927
- }
928
- else if (!result.ready) {
929
- this.logger.debug(`Could not apply checkpoint ${checkpoint.last_op_id} due to local data. We will retry applying the checkpoint after that upload is completed.`);
930
- return { applied: false, endIteration: false };
931
- }
932
- this.logger.debug(`Applied checkpoint ${checkpoint.last_op_id}`, checkpoint);
933
- this.updateSyncStatus({
934
- connected: true,
935
- lastSyncedAt: new Date(),
936
- dataFlow: {
937
- downloading: false,
938
- downloadProgress: null,
939
- downloadError: undefined
940
- }
941
- });
942
- return { applied: true, endIteration: false };
943
- }
944
- updateSyncStatus(options) {
945
- const updatedStatus = new SyncStatus({
946
- connected: options.connected ?? this.syncStatus.connected,
947
- connecting: !options.connected && (options.connecting ?? this.syncStatus.connecting),
948
- lastSyncedAt: options.lastSyncedAt ?? this.syncStatus.lastSyncedAt,
949
- dataFlow: {
950
- ...this.syncStatus.dataFlowStatus,
951
- ...options.dataFlow
952
- },
953
- priorityStatusEntries: options.priorityStatusEntries ?? this.syncStatus.priorityStatusEntries,
954
- clientImplementation: options.clientImplementation ?? this.syncStatus.clientImplementation
955
- });
956
- if (!this.syncStatus.isEqual(updatedStatus)) {
957
- this.syncStatus = updatedStatus;
958
- // Only trigger this is there was a change
959
- this.iterateListeners((cb) => cb.statusChanged?.(updatedStatus));
960
- }
961
- // trigger this for all updates
962
- this.iterateListeners((cb) => cb.statusUpdated?.(options));
963
- }
964
- async delayRetry(signal) {
965
- return new Promise((resolve) => {
966
- if (signal?.aborted) {
967
- // If the signal is already aborted, resolve immediately
968
- resolve();
969
- return;
970
- }
971
- const { retryDelayMs } = this.options;
972
- let timeoutId;
973
- const endDelay = () => {
974
- resolve();
975
- if (timeoutId) {
976
- clearTimeout(timeoutId);
977
- timeoutId = undefined;
978
- }
979
- signal?.removeEventListener('abort', endDelay);
980
- };
981
- signal?.addEventListener('abort', endDelay, { once: true });
982
- timeoutId = setTimeout(endDelay, retryDelayMs);
983
- });
984
- }
985
- updateSubscriptions(subscriptions) {
986
- this.activeStreams = subscriptions;
987
- this.handleActiveStreamsChange?.();
988
- }
989
- }
990
- //# sourceMappingURL=AbstractStreamingSyncImplementation.js.map