@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,1285 +0,0 @@
1
- import Logger, { ILogger } from 'js-logger';
2
-
3
- import { InternalProgressInformation } from '../../../db/crud/SyncProgress.js';
4
- import { SyncStatus, SyncStatusOptions } from '../../../db/crud/SyncStatus.js';
5
- import { AbortOperation } from '../../../utils/AbortOperation.js';
6
- import { BaseListener, BaseObserver, BaseObserverInterface, Disposable } from '../../../utils/BaseObserver.js';
7
- import { throttleLeadingTrailing } from '../../../utils/async.js';
8
- import {
9
- BucketChecksum,
10
- BucketDescription,
11
- BucketStorageAdapter,
12
- Checkpoint,
13
- PowerSyncControlCommand
14
- } from '../bucket/BucketStorageAdapter.js';
15
- import { CrudEntry } from '../bucket/CrudEntry.js';
16
- import { SyncDataBucket } from '../bucket/SyncDataBucket.js';
17
- import { AbstractRemote, FetchStrategy, SyncStreamOptions } from './AbstractRemote.js';
18
- import { EstablishSyncStream, Instruction, coreStatusToJs } from './core-instruction.js';
19
- import {
20
- BucketRequest,
21
- StreamingSyncLine,
22
- StreamingSyncLineOrCrudUploadComplete,
23
- StreamingSyncRequestParameterType,
24
- isStreamingKeepalive,
25
- isStreamingSyncCheckpoint,
26
- isStreamingSyncCheckpointComplete,
27
- isStreamingSyncCheckpointDiff,
28
- isStreamingSyncCheckpointPartiallyComplete,
29
- isStreamingSyncData
30
- } from './streaming-sync-types.js';
31
- import { injectable, InjectableIterator, map, SimpleAsyncIterator } from '../../../utils/stream_transform.js';
32
- import type { BSON } from 'bson';
33
-
34
- export enum LockType {
35
- CRUD = 'crud',
36
- SYNC = 'sync'
37
- }
38
-
39
- export enum SyncStreamConnectionMethod {
40
- HTTP = 'http',
41
- WEB_SOCKET = 'web-socket'
42
- }
43
-
44
- export enum SyncClientImplementation {
45
- /**
46
- * Decodes and handles sync lines received from the sync service in JavaScript.
47
- *
48
- * This is the default option.
49
- *
50
- * @deprecated We recommend the {@link RUST} client implementation for all apps. If you have issues with
51
- * the Rust client, please file an issue or reach out to us. The JavaScript client will be removed in a future
52
- * version of the PowerSync SDK.
53
- */
54
- JAVASCRIPT = 'js',
55
- /**
56
- * This implementation offloads the sync line decoding and handling into the PowerSync
57
- * core extension.
58
- *
59
- * This option is more performant than the {@link JAVASCRIPT} client, enabled by default and the
60
- * recommended client implementation for all apps.
61
- *
62
- * ## Compatibility warning
63
- *
64
- * The Rust sync client stores sync data in a format that is slightly different than the one used
65
- * by the old {@link JAVASCRIPT} implementation. When adopting the {@link RUST} client on existing
66
- * databases, the PowerSync SDK will migrate the format automatically.
67
- * Further, the {@link JAVASCRIPT} client in recent versions of the PowerSync JS SDK (starting from
68
- * the version introducing {@link RUST} as an option) also supports the new format, so you can switch
69
- * back to {@link JAVASCRIPT} later.
70
- *
71
- * __However__: Upgrading the SDK version, then adopting {@link RUST} as a sync client and later
72
- * downgrading the SDK to an older version (necessarily using the JavaScript-based implementation then)
73
- * can lead to sync issues.
74
- */
75
- RUST = 'rust'
76
- }
77
-
78
- /**
79
- * The default {@link SyncClientImplementation} to use, {@link SyncClientImplementation.RUST}.
80
- */
81
- export const DEFAULT_SYNC_CLIENT_IMPLEMENTATION = SyncClientImplementation.RUST;
82
-
83
- /**
84
- * Abstract Lock to be implemented by various JS environments
85
- */
86
- export interface LockOptions<T> {
87
- callback: () => Promise<T>;
88
- type: LockType;
89
- signal?: AbortSignal;
90
- }
91
-
92
- export interface AbstractStreamingSyncImplementationOptions extends RequiredAdditionalConnectionOptions {
93
- adapter: BucketStorageAdapter;
94
- subscriptions: SubscribedStream[];
95
- uploadCrud: () => Promise<void>;
96
- /**
97
- * An identifier for which PowerSync DB this sync implementation is
98
- * linked to. Most commonly DB name, but not restricted to DB name.
99
- */
100
- identifier?: string;
101
- logger?: ILogger;
102
- remote: AbstractRemote;
103
- }
104
-
105
- export interface StreamingSyncImplementationListener extends BaseListener {
106
- /**
107
- * Triggered whenever a status update has been attempted to be made or
108
- * refreshed.
109
- */
110
- statusUpdated?: ((statusUpdate: SyncStatusOptions) => void) | undefined;
111
- /**
112
- * Triggers whenever the status' members have changed in value
113
- */
114
- statusChanged?: ((status: SyncStatus) => void) | undefined;
115
- }
116
-
117
- /**
118
- * Configurable options to be used when connecting to the PowerSync
119
- * backend instance.
120
- */
121
- export type PowerSyncConnectionOptions = Omit<InternalConnectionOptions, 'serializedSchema'>;
122
-
123
- export interface InternalConnectionOptions extends BaseConnectionOptions, AdditionalConnectionOptions {}
124
-
125
- /** @internal */
126
- export interface BaseConnectionOptions {
127
- /**
128
- * A set of metadata to be included in service logs.
129
- */
130
- appMetadata?: Record<string, string>;
131
-
132
- /**
133
- * Whether to use a JavaScript implementation to handle received sync lines from the sync
134
- * service, or whether this work should be offloaded to the PowerSync core extension.
135
- *
136
- * This defaults to the JavaScript implementation ({@link SyncClientImplementation.JAVASCRIPT})
137
- * since the ({@link SyncClientImplementation.RUST}) implementation is experimental at the moment.
138
- */
139
- clientImplementation?: SyncClientImplementation;
140
-
141
- /**
142
- * The connection method to use when streaming updates from
143
- * the PowerSync backend instance.
144
- * Defaults to a HTTP streaming connection.
145
- */
146
- connectionMethod?: SyncStreamConnectionMethod;
147
-
148
- /**
149
- * The fetch strategy to use when streaming updates from the PowerSync backend instance.
150
- */
151
- fetchStrategy?: FetchStrategy;
152
-
153
- /**
154
- * These parameters are passed to the sync rules, and will be available under the`user_parameters` object.
155
- */
156
- params?: Record<string, StreamingSyncRequestParameterType>;
157
-
158
- /**
159
- * Whether to include streams that have `auto_subscribe: true` in their definition.
160
- *
161
- * This defaults to `true`.
162
- */
163
- includeDefaultStreams?: boolean;
164
-
165
- /**
166
- * The serialized schema - mainly used to forward information about raw tables to the sync client.
167
- */
168
- serializedSchema?: any;
169
- }
170
-
171
- /** @internal */
172
- export interface AdditionalConnectionOptions {
173
- /**
174
- * Delay for retrying sync streaming operations
175
- * from the PowerSync backend after an error occurs.
176
- */
177
- retryDelayMs?: number;
178
- /**
179
- * Backend Connector CRUD operations are throttled
180
- * to occur at most every `crudUploadThrottleMs`
181
- * milliseconds.
182
- */
183
- crudUploadThrottleMs?: number;
184
- }
185
-
186
- /** @internal */
187
- export interface RequiredAdditionalConnectionOptions extends Required<AdditionalConnectionOptions> {
188
- subscriptions: SubscribedStream[];
189
- }
190
-
191
- export interface StreamingSyncImplementation
192
- extends BaseObserverInterface<StreamingSyncImplementationListener>, Disposable {
193
- /**
194
- * Connects to the sync service
195
- */
196
- connect(options?: InternalConnectionOptions): Promise<void>;
197
- /**
198
- * Disconnects from the sync services.
199
- * @throws if not connected or if abort is not controlled internally
200
- */
201
- disconnect(): Promise<void>;
202
- getWriteCheckpoint: () => Promise<string>;
203
- hasCompletedSync: () => Promise<boolean>;
204
- isConnected: boolean;
205
- lastSyncedAt?: Date;
206
- syncStatus: SyncStatus;
207
- triggerCrudUpload: () => void;
208
- waitForReady(): Promise<void>;
209
- waitForStatus(status: SyncStatusOptions): Promise<void>;
210
- waitUntilStatusMatches(predicate: (status: SyncStatus) => boolean): Promise<void>;
211
- updateSubscriptions(subscriptions: SubscribedStream[]): void;
212
- markConnectionMayHaveChanged(): void;
213
- }
214
-
215
- export const DEFAULT_CRUD_UPLOAD_THROTTLE_MS = 1000;
216
- export const DEFAULT_RETRY_DELAY_MS = 5000;
217
-
218
- export const DEFAULT_STREAMING_SYNC_OPTIONS = {
219
- retryDelayMs: DEFAULT_RETRY_DELAY_MS,
220
- crudUploadThrottleMs: DEFAULT_CRUD_UPLOAD_THROTTLE_MS
221
- };
222
-
223
- export type RequiredPowerSyncConnectionOptions = Required<BaseConnectionOptions>;
224
-
225
- export const DEFAULT_STREAM_CONNECTION_OPTIONS: RequiredPowerSyncConnectionOptions = {
226
- appMetadata: {},
227
- connectionMethod: SyncStreamConnectionMethod.WEB_SOCKET,
228
- clientImplementation: DEFAULT_SYNC_CLIENT_IMPLEMENTATION,
229
- fetchStrategy: FetchStrategy.Buffered,
230
- params: {},
231
- serializedSchema: undefined,
232
- includeDefaultStreams: true
233
- };
234
-
235
- export type SubscribedStream = {
236
- name: string;
237
- params: Record<string, any> | null;
238
- };
239
-
240
- // The priority we assume when we receive checkpoint lines where no priority is set.
241
- // This is the default priority used by the sync service, but can be set to an arbitrary
242
- // value since sync services without priorities also won't send partial sync completion
243
- // messages.
244
- const FALLBACK_PRIORITY = 3;
245
-
246
- export abstract class AbstractStreamingSyncImplementation
247
- extends BaseObserver<StreamingSyncImplementationListener>
248
- implements StreamingSyncImplementation
249
- {
250
- protected _lastSyncedAt: Date | null;
251
- protected options: AbstractStreamingSyncImplementationOptions;
252
- protected abortController: AbortController | null;
253
- // In rare cases, mostly for tests, uploads can be triggered without being properly connected.
254
- // This allows ensuring that all upload processes can be aborted.
255
- protected uploadAbortController: AbortController | null;
256
- protected crudUpdateListener?: () => void;
257
- protected streamingSyncPromise?: Promise<void>;
258
- protected logger: ILogger;
259
- private activeStreams: SubscribedStream[];
260
- private connectionMayHaveChanged = false;
261
-
262
- private isUploadingCrud: boolean = false;
263
- private notifyCompletedUploads?: () => void;
264
- private handleActiveStreamsChange?: () => void;
265
-
266
- syncStatus: SyncStatus;
267
- triggerCrudUpload: () => void;
268
-
269
- constructor(options: AbstractStreamingSyncImplementationOptions) {
270
- super();
271
- this.options = options;
272
- this.activeStreams = options.subscriptions;
273
- this.logger = options.logger ?? Logger.get('PowerSyncStream');
274
-
275
- this.syncStatus = new SyncStatus({
276
- connected: false,
277
- connecting: false,
278
- lastSyncedAt: undefined,
279
- dataFlow: {
280
- uploading: false,
281
- downloading: false
282
- }
283
- });
284
- this.abortController = null;
285
-
286
- this.triggerCrudUpload = throttleLeadingTrailing(() => {
287
- if (!this.syncStatus.connected || this.isUploadingCrud) {
288
- return;
289
- }
290
-
291
- this.isUploadingCrud = true;
292
- this._uploadAllCrud().finally(() => {
293
- this.notifyCompletedUploads?.();
294
- this.isUploadingCrud = false;
295
- });
296
- }, this.options.crudUploadThrottleMs!);
297
- }
298
-
299
- async waitForReady() {}
300
-
301
- waitForStatus(status: SyncStatusOptions): Promise<void> {
302
- return this.waitUntilStatusMatches((currentStatus) => {
303
- /**
304
- * Match only the partial status options provided in the
305
- * matching status
306
- */
307
- const matchPartialObject = (compA: object, compB: object) => {
308
- return Object.entries(compA).every(([key, value]) => {
309
- const comparisonBValue = compB[key];
310
- if (typeof value == 'object' && typeof comparisonBValue == 'object') {
311
- return matchPartialObject(value, comparisonBValue);
312
- }
313
- return value == comparisonBValue;
314
- });
315
- };
316
-
317
- return matchPartialObject(status, currentStatus);
318
- });
319
- }
320
-
321
- waitUntilStatusMatches(predicate: (status: SyncStatus) => boolean): Promise<void> {
322
- return new Promise((resolve) => {
323
- if (predicate(this.syncStatus)) {
324
- resolve();
325
- return;
326
- }
327
-
328
- const l = this.registerListener({
329
- statusChanged: (updatedStatus) => {
330
- if (predicate(updatedStatus)) {
331
- resolve();
332
- l?.();
333
- }
334
- }
335
- });
336
- });
337
- }
338
-
339
- get lastSyncedAt() {
340
- const lastSynced = this.syncStatus.lastSyncedAt;
341
- return lastSynced && new Date(lastSynced);
342
- }
343
-
344
- get isConnected() {
345
- return this.syncStatus.connected;
346
- }
347
-
348
- async dispose() {
349
- super.dispose();
350
- this.crudUpdateListener?.();
351
- this.crudUpdateListener = undefined;
352
- this.uploadAbortController?.abort();
353
- }
354
-
355
- abstract obtainLock<T>(lockOptions: LockOptions<T>): Promise<T>;
356
-
357
- async hasCompletedSync() {
358
- return this.options.adapter.hasCompletedSync();
359
- }
360
-
361
- async getWriteCheckpoint(): Promise<string> {
362
- const clientId = await this.options.adapter.getClientId();
363
- let path = `/write-checkpoint2.json?client_id=${clientId}`;
364
- const response = await this.options.remote.get(path);
365
- const checkpoint = response['data']['write_checkpoint'] as string;
366
- this.logger.debug(`Created write checkpoint: ${checkpoint}`);
367
- return checkpoint;
368
- }
369
-
370
- protected async _uploadAllCrud(): Promise<void> {
371
- return this.obtainLock({
372
- type: LockType.CRUD,
373
- callback: async () => {
374
- /**
375
- * Keep track of the first item in the CRUD queue for the last `uploadCrud` iteration.
376
- */
377
- let checkedCrudItem: CrudEntry | undefined;
378
-
379
- const controller = new AbortController();
380
- this.uploadAbortController = controller;
381
- this.abortController?.signal.addEventListener(
382
- 'abort',
383
- () => {
384
- controller.abort();
385
- },
386
- { once: true }
387
- );
388
-
389
- while (!controller.signal.aborted) {
390
- try {
391
- /**
392
- * This is the first item in the FIFO CRUD queue.
393
- */
394
- const nextCrudItem = await this.options.adapter.nextCrudItem();
395
- if (nextCrudItem) {
396
- this.updateSyncStatus({
397
- dataFlow: {
398
- uploading: true
399
- }
400
- });
401
-
402
- if (nextCrudItem.clientId == checkedCrudItem?.clientId) {
403
- // This will force a higher log level than exceptions which are caught here.
404
- this.logger.warn(`Potentially previously uploaded CRUD entries are still present in the upload queue.
405
- Make sure to handle uploads and complete CRUD transactions or batches by calling and awaiting their [.complete()] method.
406
- The next upload iteration will be delayed.`);
407
- throw new Error('Delaying due to previously encountered CRUD item.');
408
- }
409
-
410
- checkedCrudItem = nextCrudItem;
411
- await this.options.uploadCrud();
412
- this.updateSyncStatus({
413
- dataFlow: {
414
- uploadError: undefined
415
- }
416
- });
417
- } else {
418
- // Uploading is completed
419
- const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint());
420
- if (neededUpdate == false && checkedCrudItem != null) {
421
- // Only log this if there was something to upload
422
- this.logger.debug('Upload complete, no write checkpoint needed.');
423
- }
424
- break;
425
- }
426
- } catch (ex) {
427
- checkedCrudItem = undefined;
428
- this.updateSyncStatus({
429
- dataFlow: {
430
- uploading: false,
431
- uploadError: ex
432
- }
433
- });
434
- await this.delayRetry(controller.signal);
435
- if (!this.isConnected) {
436
- // Exit the upload loop if the sync stream is no longer connected
437
- break;
438
- }
439
- this.logger.debug(
440
- `Caught exception when uploading. Upload will retry after a delay. Exception: ${ex.message}`
441
- );
442
- } finally {
443
- this.updateSyncStatus({
444
- dataFlow: {
445
- uploading: false
446
- }
447
- });
448
- }
449
- }
450
- this.uploadAbortController = null;
451
- }
452
- });
453
- }
454
-
455
- async connect(options?: PowerSyncConnectionOptions) {
456
- if (this.abortController) {
457
- await this.disconnect();
458
- }
459
-
460
- const controller = new AbortController();
461
- this.abortController = controller;
462
- this.streamingSyncPromise = this.streamingSync(this.abortController.signal, options);
463
-
464
- // Return a promise that resolves when the connection status is updated to indicate that we're connected.
465
- return new Promise<void>((resolve) => {
466
- const disposer = this.registerListener({
467
- statusChanged: (status) => {
468
- if (status.dataFlowStatus.downloadError != null) {
469
- this.logger.warn('Initial connect attempt did not successfully connect to server');
470
- } else if (status.connecting) {
471
- // Still connecting.
472
- return;
473
- }
474
-
475
- disposer();
476
- resolve();
477
- }
478
- });
479
- });
480
- }
481
-
482
- async disconnect(): Promise<void> {
483
- if (!this.abortController) {
484
- return;
485
- }
486
-
487
- // This might be called multiple times
488
- if (!this.abortController.signal.aborted) {
489
- this.abortController.abort(new AbortOperation('Disconnect has been requested'));
490
- }
491
-
492
- // Await any pending operations before completing the disconnect operation
493
- try {
494
- await this.streamingSyncPromise;
495
- } catch (ex) {
496
- // The operation might have failed, all we care about is if it has completed
497
- this.logger.warn(ex);
498
- }
499
- this.streamingSyncPromise = undefined;
500
-
501
- this.abortController = null;
502
- this.updateSyncStatus({ connected: false, connecting: false });
503
- }
504
-
505
- /**
506
- * @deprecated use [connect instead]
507
- */
508
- async streamingSync(signal?: AbortSignal, options?: PowerSyncConnectionOptions): Promise<void> {
509
- if (!signal) {
510
- this.abortController = new AbortController();
511
- signal = this.abortController.signal;
512
- }
513
-
514
- /**
515
- * Listen for CRUD updates and trigger upstream uploads
516
- */
517
- this.crudUpdateListener = this.options.adapter.registerListener({
518
- crudUpdate: () => this.triggerCrudUpload()
519
- });
520
-
521
- /**
522
- * Create a new abort controller which aborts items downstream.
523
- * This is needed to close any previous connections on exception.
524
- */
525
- let nestedAbortController = new AbortController();
526
-
527
- signal.addEventListener('abort', () => {
528
- /**
529
- * A request for disconnect was received upstream. Relay the request
530
- * to the nested abort controller.
531
- */
532
- nestedAbortController.abort(signal?.reason ?? new AbortOperation('Received command to disconnect from upstream'));
533
- this.crudUpdateListener?.();
534
- this.crudUpdateListener = undefined;
535
- this.updateSyncStatus({
536
- connected: false,
537
- connecting: false,
538
- dataFlow: {
539
- downloading: false,
540
- downloadProgress: null
541
- }
542
- });
543
- });
544
-
545
- /**
546
- * This loops runs until [retry] is false or the abort signal is set to aborted.
547
- * Aborting the nestedAbortController will:
548
- * - Abort any pending fetch requests
549
- * - Close any sync stream ReadableStreams (which will also close any established network requests)
550
- */
551
- while (true) {
552
- this.updateSyncStatus({ connecting: true });
553
- let shouldDelayRetry = true;
554
- let result: RustIterationResult | null = null;
555
-
556
- try {
557
- if (signal?.aborted) {
558
- break;
559
- }
560
- result = await this.streamingSyncIteration(nestedAbortController.signal, options);
561
- // Continue immediately, streamingSyncIteration will wait before completing if necessary.
562
- } catch (ex) {
563
- /**
564
- * Either:
565
- * - A network request failed with a failed connection or not OKAY response code.
566
- * - There was a sync processing error.
567
- * - The connection was aborted.
568
- * This loop will retry after a delay if the connection was not aborted.
569
- * The nested abort controller will cleanup any open network requests and streams.
570
- * The WebRemote should only abort pending fetch requests or close active Readable streams.
571
- */
572
-
573
- if (ex instanceof AbortOperation) {
574
- this.logger.warn(ex);
575
- shouldDelayRetry = false;
576
- // A disconnect was requested, we should not delay since there is no explicit retry
577
- } else if (this.connectionMayHaveChanged && (ex as Error).message?.indexOf('No iteration is active') >= 0) {
578
- this.connectionMayHaveChanged = false;
579
- this.logger.info('Sync error after changed connection, retrying immediately');
580
- shouldDelayRetry = false;
581
- } else {
582
- this.logger.error(ex);
583
- }
584
-
585
- this.updateSyncStatus({
586
- dataFlow: {
587
- downloadError: ex
588
- }
589
- });
590
- } finally {
591
- this.notifyCompletedUploads = undefined;
592
-
593
- if (!signal.aborted) {
594
- nestedAbortController.abort(new AbortOperation('Closing sync stream network requests before retry.'));
595
- nestedAbortController = new AbortController();
596
- }
597
-
598
- if (result?.immediateRestart != true) {
599
- this.updateSyncStatus({
600
- connected: false,
601
- connecting: true // May be unnecessary
602
- });
603
-
604
- // On error, wait a little before retrying
605
- if (shouldDelayRetry) {
606
- await this.delayRetry(nestedAbortController.signal);
607
- }
608
- }
609
- }
610
- }
611
-
612
- // Mark as disconnected if here
613
- this.updateSyncStatus({ connected: false, connecting: false });
614
- }
615
-
616
- markConnectionMayHaveChanged() {
617
- // By setting this field, we'll immediately retry if the next sync event causes an error triggered by us not having
618
- // an active sync iteration on the connection in use.
619
- this.connectionMayHaveChanged = true;
620
-
621
- // This triggers a `powersync_control` invocation if a sync iteration is currently active. This is a cheap call to
622
- // make when no subscriptions have actually changed, we're mainly interested in this immediately throwing if no
623
- // iteration is active. That allows us to reconnect ASAP, instead of having to wait for the next sync line.
624
- this.handleActiveStreamsChange?.();
625
- }
626
-
627
- private async collectLocalBucketState(): Promise<[BucketRequest[], Map<string, BucketDescription | null>]> {
628
- const bucketEntries = await this.options.adapter.getBucketStates();
629
- const req: BucketRequest[] = bucketEntries.map((entry) => ({
630
- name: entry.bucket,
631
- after: entry.op_id
632
- }));
633
- const localDescriptions = new Map<string, BucketDescription | null>();
634
- for (const entry of bucketEntries) {
635
- localDescriptions.set(entry.bucket, null);
636
- }
637
-
638
- return [req, localDescriptions];
639
- }
640
-
641
- /**
642
- * Older versions of the JS SDK used to encode subkeys as JSON in {@link OplogEntry.toJSON}.
643
- * Because subkeys are always strings, this leads to quotes being added around them in `ps_oplog`.
644
- * While this is not a problem as long as it's done consistently, it causes issues when a database
645
- * created by the JS SDK is used with other SDKs, or (more likely) when the new Rust sync client
646
- * is enabled.
647
- *
648
- * So, we add a migration from the old key format (with quotes) to the new one (no quotes). The
649
- * migration is only triggered when necessary (for now). The function returns whether the new format
650
- * should be used, so that the JS SDK is able to write to updated databases.
651
- *
652
- * @param requireFixedKeyFormat Whether we require the new format or also support the old one.
653
- * The Rust client requires the new subkey format.
654
- * @returns Whether the database is now using the new, fixed subkey format.
655
- */
656
- private async requireKeyFormat(requireFixedKeyFormat: boolean): Promise<boolean> {
657
- const hasMigrated = await this.options.adapter.hasMigratedSubkeys();
658
- if (requireFixedKeyFormat && !hasMigrated) {
659
- await this.options.adapter.migrateToFixedSubkeys();
660
- return true;
661
- } else {
662
- return hasMigrated;
663
- }
664
- }
665
-
666
- protected streamingSyncIteration(
667
- signal: AbortSignal,
668
- options?: PowerSyncConnectionOptions
669
- ): Promise<RustIterationResult | null> {
670
- return this.obtainLock({
671
- type: LockType.SYNC,
672
- signal,
673
- callback: async () => {
674
- const resolvedOptions: RequiredPowerSyncConnectionOptions = {
675
- ...DEFAULT_STREAM_CONNECTION_OPTIONS,
676
- ...(options ?? {})
677
- };
678
-
679
- // Validate app metadata
680
- const invalidMetadata = Object.entries(resolvedOptions.appMetadata).filter(
681
- ([_, value]) => typeof value != 'string'
682
- );
683
- if (invalidMetadata.length > 0) {
684
- throw new Error(
685
- `Invalid appMetadata provided. Only string values are allowed. Invalid values: ${invalidMetadata.map(([key, value]) => `${key}: ${value}`).join(', ')}`
686
- );
687
- }
688
- const clientImplementation = resolvedOptions.clientImplementation;
689
- this.updateSyncStatus({ clientImplementation });
690
-
691
- if (clientImplementation == SyncClientImplementation.JAVASCRIPT) {
692
- await this.legacyStreamingSyncIteration(signal, resolvedOptions);
693
- return null;
694
- } else {
695
- await this.requireKeyFormat(true);
696
- return await this.rustSyncIteration(signal, resolvedOptions);
697
- }
698
- }
699
- });
700
- }
701
-
702
- private async receiveSyncLines(data: {
703
- options: SyncStreamOptions;
704
- connection: RequiredPowerSyncConnectionOptions;
705
- bson?: typeof BSON;
706
- }): Promise<SimpleAsyncIterator<Uint8Array | string>> {
707
- const { options, connection, bson } = data;
708
- const remote = this.options.remote;
709
-
710
- if (connection.connectionMethod == SyncStreamConnectionMethod.HTTP) {
711
- return await remote.fetchStream(options);
712
- } else {
713
- return await this.options.remote.socketStreamRaw(
714
- {
715
- ...options,
716
- ...{ fetchStrategy: connection.fetchStrategy }
717
- },
718
- bson
719
- );
720
- }
721
- }
722
-
723
- private async legacyStreamingSyncIteration(signal: AbortSignal, resolvedOptions: RequiredPowerSyncConnectionOptions) {
724
- const rawTables = resolvedOptions.serializedSchema?.raw_tables;
725
- if (rawTables != null && rawTables.length) {
726
- this.logger.warn('Raw tables require the Rust-based sync client. The JS client will ignore them.');
727
- }
728
- if (this.activeStreams.length) {
729
- this.logger.error('Sync streams require `clientImplementation: SyncClientImplementation.RUST` when connecting.');
730
- }
731
-
732
- this.logger.debug('Streaming sync iteration started');
733
- this.options.adapter.startSession();
734
- let [req, bucketMap] = await this.collectLocalBucketState();
735
-
736
- let targetCheckpoint: Checkpoint | null = null;
737
- // A checkpoint that has been validated but not applied (e.g. due to pending local writes)
738
- let pendingValidatedCheckpoint: Checkpoint | null = null;
739
-
740
- const clientId = await this.options.adapter.getClientId();
741
- const usingFixedKeyFormat = await this.requireKeyFormat(false);
742
-
743
- this.logger.debug('Requesting stream from server');
744
-
745
- const syncOptions: SyncStreamOptions = {
746
- path: '/sync/stream',
747
- abortSignal: signal,
748
- data: {
749
- buckets: req,
750
- include_checksum: true,
751
- raw_data: true,
752
- parameters: resolvedOptions.params,
753
- app_metadata: resolvedOptions.appMetadata,
754
- client_id: clientId
755
- }
756
- };
757
-
758
- const bson = await this.options.remote.getBSON();
759
- const source = await this.receiveSyncLines({
760
- options: syncOptions,
761
- connection: resolvedOptions,
762
- bson
763
- });
764
- const stream: InjectableIterator<StreamingSyncLineOrCrudUploadComplete> = injectable(
765
- map(source, (line) => {
766
- if (typeof line == 'string') {
767
- return JSON.parse(line) as StreamingSyncLine;
768
- } else {
769
- return bson.deserialize(line) as StreamingSyncLine;
770
- }
771
- })
772
- );
773
-
774
- this.logger.debug('Stream established. Processing events');
775
-
776
- this.notifyCompletedUploads = () => {
777
- stream.inject({ crud_upload_completed: null });
778
- };
779
-
780
- while (true) {
781
- const { value: line, done } = await stream.next();
782
- if (done) {
783
- // The stream has closed while waiting
784
- return;
785
- }
786
-
787
- if ('crud_upload_completed' in line) {
788
- if (pendingValidatedCheckpoint != null) {
789
- const { applied, endIteration } = await this.applyCheckpoint(pendingValidatedCheckpoint);
790
- if (applied) {
791
- pendingValidatedCheckpoint = null;
792
- } else if (endIteration) {
793
- break;
794
- }
795
- }
796
-
797
- continue;
798
- }
799
-
800
- // A connection is active and messages are being received
801
- if (!this.syncStatus.connected) {
802
- // There is a connection now
803
- Promise.resolve().then(() => this.triggerCrudUpload());
804
- this.updateSyncStatus({
805
- connected: true
806
- });
807
- }
808
-
809
- if (isStreamingSyncCheckpoint(line)) {
810
- targetCheckpoint = line.checkpoint;
811
- // New checkpoint - existing validated checkpoint is no longer valid
812
- pendingValidatedCheckpoint = null;
813
- const bucketsToDelete = new Set<string>(bucketMap.keys());
814
- const newBuckets = new Map<string, BucketDescription>();
815
- for (const checksum of line.checkpoint.buckets) {
816
- newBuckets.set(checksum.bucket, {
817
- name: checksum.bucket,
818
- priority: checksum.priority ?? FALLBACK_PRIORITY
819
- });
820
- bucketsToDelete.delete(checksum.bucket);
821
- }
822
- if (bucketsToDelete.size > 0) {
823
- this.logger.debug('Removing buckets', [...bucketsToDelete]);
824
- }
825
- bucketMap = newBuckets;
826
- await this.options.adapter.removeBuckets([...bucketsToDelete]);
827
- await this.options.adapter.setTargetCheckpoint(targetCheckpoint);
828
- await this.updateSyncStatusForStartingCheckpoint(targetCheckpoint);
829
- } else if (isStreamingSyncCheckpointComplete(line)) {
830
- const result = await this.applyCheckpoint(targetCheckpoint!);
831
- if (result.endIteration) {
832
- return;
833
- } else if (!result.applied) {
834
- // "Could not apply checkpoint due to local data". We need to retry after
835
- // finishing uploads.
836
- pendingValidatedCheckpoint = targetCheckpoint;
837
- } else {
838
- // Nothing to retry later. This would likely already be null from the last
839
- // checksum or checksum_diff operation, but we make sure.
840
- pendingValidatedCheckpoint = null;
841
- }
842
- } else if (isStreamingSyncCheckpointPartiallyComplete(line)) {
843
- const priority = line.partial_checkpoint_complete.priority;
844
- this.logger.debug('Partial checkpoint complete', priority);
845
- const result = await this.options.adapter.syncLocalDatabase(targetCheckpoint!, priority);
846
- if (!result.checkpointValid) {
847
- // This means checksums failed. Start again with a new checkpoint.
848
- // TODO: better back-off
849
- await new Promise((resolve) => setTimeout(resolve, 50));
850
- return;
851
- } else if (!result.ready) {
852
- // If we have pending uploads, we can't complete new checkpoints outside of priority 0.
853
- // We'll resolve this for a complete checkpoint.
854
- } else {
855
- // We'll keep on downloading, but can report that this priority is synced now.
856
- this.logger.debug('partial checkpoint validation succeeded');
857
-
858
- // All states with a higher priority can be deleted since this partial sync includes them.
859
- const priorityStates = this.syncStatus.priorityStatusEntries.filter((s) => s.priority <= priority);
860
- priorityStates.push({
861
- priority,
862
- lastSyncedAt: new Date(),
863
- hasSynced: true
864
- });
865
-
866
- this.updateSyncStatus({
867
- connected: true,
868
- priorityStatusEntries: priorityStates
869
- });
870
- }
871
- } else if (isStreamingSyncCheckpointDiff(line)) {
872
- // TODO: It may be faster to just keep track of the diff, instead of the entire checkpoint
873
- if (targetCheckpoint == null) {
874
- throw new Error('Checkpoint diff without previous checkpoint');
875
- }
876
- // New checkpoint - existing validated checkpoint is no longer valid
877
- pendingValidatedCheckpoint = null;
878
- const diff = line.checkpoint_diff;
879
- const newBuckets = new Map<string, BucketChecksum>();
880
- for (const checksum of targetCheckpoint.buckets) {
881
- newBuckets.set(checksum.bucket, checksum);
882
- }
883
- for (const checksum of diff.updated_buckets) {
884
- newBuckets.set(checksum.bucket, checksum);
885
- }
886
- for (const bucket of diff.removed_buckets) {
887
- newBuckets.delete(bucket);
888
- }
889
-
890
- const newCheckpoint: Checkpoint = {
891
- last_op_id: diff.last_op_id,
892
- buckets: [...newBuckets.values()],
893
- write_checkpoint: diff.write_checkpoint
894
- };
895
- targetCheckpoint = newCheckpoint;
896
- await this.updateSyncStatusForStartingCheckpoint(targetCheckpoint);
897
-
898
- bucketMap = new Map();
899
- newBuckets.forEach((checksum, name) =>
900
- bucketMap.set(name, {
901
- name: checksum.bucket,
902
- priority: checksum.priority ?? FALLBACK_PRIORITY
903
- })
904
- );
905
-
906
- const bucketsToDelete = diff.removed_buckets;
907
- if (bucketsToDelete.length > 0) {
908
- this.logger.debug('Remove buckets', bucketsToDelete);
909
- }
910
- await this.options.adapter.removeBuckets(bucketsToDelete);
911
- await this.options.adapter.setTargetCheckpoint(targetCheckpoint);
912
- } else if (isStreamingSyncData(line)) {
913
- const { data } = line;
914
- const previousProgress = this.syncStatus.dataFlowStatus.downloadProgress;
915
- let updatedProgress: InternalProgressInformation | null = null;
916
- if (previousProgress) {
917
- updatedProgress = { ...previousProgress };
918
- const progressForBucket = updatedProgress[data.bucket];
919
- if (progressForBucket) {
920
- updatedProgress[data.bucket] = {
921
- ...progressForBucket,
922
- since_last: progressForBucket.since_last + data.data.length
923
- };
924
- }
925
- }
926
-
927
- this.updateSyncStatus({
928
- dataFlow: {
929
- downloading: true,
930
- downloadProgress: updatedProgress
931
- }
932
- });
933
- await this.options.adapter.saveSyncData({ buckets: [SyncDataBucket.fromRow(data)] }, usingFixedKeyFormat);
934
- } else if (isStreamingKeepalive(line)) {
935
- const remaining_seconds = line.token_expires_in;
936
- if (remaining_seconds == 0) {
937
- // Connection would be closed automatically right after this
938
- this.logger.debug('Token expiring; reconnect');
939
- /**
940
- * For a rare case where the backend connector does not update the token
941
- * (uses the same one), this should have some delay.
942
- */
943
- await this.delayRetry();
944
- return;
945
- } else if (remaining_seconds < 30) {
946
- this.logger.debug('Token will expire soon; reconnect');
947
- // Pre-emptively refresh the token
948
- this.options.remote.invalidateCredentials();
949
- return;
950
- }
951
- this.triggerCrudUpload();
952
- } else {
953
- this.logger.debug('Received unknown sync line', line);
954
- }
955
- }
956
- this.logger.debug('Stream input empty');
957
- // Connection closed. Likely due to auth issue.
958
- return;
959
- }
960
-
961
- private async rustSyncIteration(
962
- signal: AbortSignal,
963
- resolvedOptions: RequiredPowerSyncConnectionOptions
964
- ): Promise<RustIterationResult> {
965
- const syncImplementation = this;
966
- const adapter = this.options.adapter;
967
- const remote = this.options.remote;
968
- const controller = new AbortController();
969
- const abort = () => {
970
- return controller.abort(signal.reason);
971
- };
972
- signal.addEventListener('abort', abort);
973
- let receivingLines: Promise<void> | null = null;
974
- let hadSyncLine = false;
975
- let hideDisconnectOnRestart = false;
976
-
977
- if (signal.aborted) {
978
- throw new AbortOperation('Connection request has been aborted');
979
- }
980
-
981
- // Pending sync lines received from the service, as well as local events that trigger a powersync_control
982
- // invocation (local events include refreshed tokens and completed uploads).
983
- // This is a single data stream so that we can handle all control calls from a single place.
984
- let controlInvocations: InjectableIterator<EnqueuedCommand> | null = null;
985
-
986
- async function connect(instr: EstablishSyncStream) {
987
- const syncOptions: SyncStreamOptions = {
988
- path: '/sync/stream',
989
- abortSignal: controller.signal,
990
- data: instr.request
991
- };
992
-
993
- controlInvocations = injectable(
994
- map(
995
- await syncImplementation.receiveSyncLines({
996
- options: syncOptions,
997
- connection: resolvedOptions
998
- }),
999
- (line) => {
1000
- if (typeof line == 'string') {
1001
- return {
1002
- command: PowerSyncControlCommand.PROCESS_TEXT_LINE,
1003
- payload: line
1004
- };
1005
- } else {
1006
- return {
1007
- command: PowerSyncControlCommand.PROCESS_BSON_LINE,
1008
- payload: line
1009
- };
1010
- }
1011
- }
1012
- )
1013
- );
1014
-
1015
- // The rust client will set connected: true after the first sync line because that's when it gets invoked, but
1016
- // we're already connected here and can report that.
1017
- syncImplementation.updateSyncStatus({ connected: true });
1018
-
1019
- try {
1020
- while (true) {
1021
- let event = await controlInvocations.next();
1022
- if (event.done) {
1023
- break;
1024
- }
1025
-
1026
- const line = event.value;
1027
- await control(line.command, line.payload);
1028
-
1029
- if (!hadSyncLine) {
1030
- syncImplementation.triggerCrudUpload();
1031
- hadSyncLine = true;
1032
- }
1033
- }
1034
- } finally {
1035
- abort();
1036
- signal.removeEventListener('abort', abort);
1037
- }
1038
- }
1039
-
1040
- async function stop() {
1041
- await control(PowerSyncControlCommand.STOP);
1042
- }
1043
-
1044
- async function control(op: PowerSyncControlCommand, payload?: Uint8Array | string) {
1045
- const rawResponse = await adapter.control(op, payload ?? null);
1046
- const logger = syncImplementation.logger;
1047
- logger.trace(
1048
- 'powersync_control',
1049
- op,
1050
- payload == null || typeof payload == 'string' ? payload : '<bytes>',
1051
- rawResponse
1052
- );
1053
-
1054
- if (op != PowerSyncControlCommand.STOP) {
1055
- // Evidently we have a working connection here, otherwise powersync_control would have failed.
1056
- syncImplementation.connectionMayHaveChanged = false;
1057
- }
1058
- await handleInstructions(JSON.parse(rawResponse));
1059
- }
1060
-
1061
- async function handleInstruction(instruction: Instruction) {
1062
- if ('LogLine' in instruction) {
1063
- switch (instruction.LogLine.severity) {
1064
- case 'DEBUG':
1065
- syncImplementation.logger.debug(instruction.LogLine.line);
1066
- break;
1067
- case 'INFO':
1068
- syncImplementation.logger.info(instruction.LogLine.line);
1069
- break;
1070
- case 'WARNING':
1071
- syncImplementation.logger.warn(instruction.LogLine.line);
1072
- break;
1073
- }
1074
- } else if ('UpdateSyncStatus' in instruction) {
1075
- syncImplementation.updateSyncStatus(coreStatusToJs(instruction.UpdateSyncStatus.status));
1076
- } else if ('EstablishSyncStream' in instruction) {
1077
- if (receivingLines != null) {
1078
- // Already connected, this shouldn't happen during a single iteration.
1079
- throw 'Unexpected request to establish sync stream, already connected';
1080
- }
1081
-
1082
- receivingLines = connect(instruction.EstablishSyncStream);
1083
- } else if ('FetchCredentials' in instruction) {
1084
- if (instruction.FetchCredentials.did_expire) {
1085
- remote.invalidateCredentials();
1086
- } else {
1087
- remote.invalidateCredentials();
1088
-
1089
- // Restart iteration after the credentials have been refreshed.
1090
- remote.fetchCredentials().then(
1091
- (_) => {
1092
- controlInvocations?.inject({ command: PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED });
1093
- },
1094
- (err) => {
1095
- syncImplementation.logger.warn('Could not prefetch credentials', err);
1096
- }
1097
- );
1098
- }
1099
- } else if ('CloseSyncStream' in instruction) {
1100
- controller.abort();
1101
- hideDisconnectOnRestart = instruction.CloseSyncStream.hide_disconnect;
1102
- } else if ('FlushFileSystem' in instruction) {
1103
- // Not necessary on JS platforms.
1104
- } else if ('DidCompleteSync' in instruction) {
1105
- syncImplementation.updateSyncStatus({
1106
- dataFlow: {
1107
- downloadError: undefined
1108
- }
1109
- });
1110
- }
1111
- }
1112
-
1113
- async function handleInstructions(instructions: Instruction[]) {
1114
- for (const instr of instructions) {
1115
- await handleInstruction(instr);
1116
- }
1117
- }
1118
-
1119
- try {
1120
- const options: any = {
1121
- parameters: resolvedOptions.params,
1122
- app_metadata: resolvedOptions.appMetadata,
1123
- active_streams: this.activeStreams,
1124
- include_defaults: resolvedOptions.includeDefaultStreams
1125
- };
1126
- if (resolvedOptions.serializedSchema) {
1127
- options.schema = resolvedOptions.serializedSchema;
1128
- }
1129
-
1130
- await control(PowerSyncControlCommand.START, JSON.stringify(options));
1131
-
1132
- this.notifyCompletedUploads = () => {
1133
- controlInvocations?.inject({ command: PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });
1134
- };
1135
- this.handleActiveStreamsChange = () => {
1136
- controlInvocations?.inject({
1137
- command: PowerSyncControlCommand.UPDATE_SUBSCRIPTIONS,
1138
- payload: JSON.stringify(this.activeStreams)
1139
- });
1140
- };
1141
- await receivingLines;
1142
- } finally {
1143
- this.notifyCompletedUploads = this.handleActiveStreamsChange = undefined;
1144
- await stop();
1145
- }
1146
-
1147
- return { immediateRestart: hideDisconnectOnRestart };
1148
- }
1149
-
1150
- private async updateSyncStatusForStartingCheckpoint(checkpoint: Checkpoint) {
1151
- const localProgress = await this.options.adapter.getBucketOperationProgress();
1152
- const progress: InternalProgressInformation = {};
1153
- let invalidated = false;
1154
-
1155
- for (const bucket of checkpoint.buckets) {
1156
- const savedProgress = localProgress[bucket.bucket];
1157
- const atLast = savedProgress?.atLast ?? 0;
1158
- const sinceLast = savedProgress?.sinceLast ?? 0;
1159
-
1160
- progress[bucket.bucket] = {
1161
- // The fallback priority doesn't matter here, but 3 is the one newer versions of the sync service
1162
- // will use by default.
1163
- priority: bucket.priority ?? 3,
1164
- at_last: atLast,
1165
- since_last: sinceLast,
1166
- target_count: bucket.count ?? 0
1167
- };
1168
-
1169
- if (bucket.count != null && bucket.count < atLast + sinceLast) {
1170
- // Either due to a defrag / sync rule deploy or a compaction operation, the size
1171
- // of the bucket shrank so much that the local ops exceed the ops in the updated
1172
- // bucket. We can't prossibly report progress in this case (it would overshoot 100%).
1173
- invalidated = true;
1174
- }
1175
- }
1176
-
1177
- if (invalidated) {
1178
- for (const bucket in progress) {
1179
- const bucketProgress = progress[bucket];
1180
- bucketProgress.at_last = 0;
1181
- bucketProgress.since_last = 0;
1182
- }
1183
- }
1184
-
1185
- this.updateSyncStatus({
1186
- dataFlow: {
1187
- downloading: true,
1188
- downloadProgress: progress
1189
- }
1190
- });
1191
- }
1192
-
1193
- private async applyCheckpoint(checkpoint: Checkpoint) {
1194
- let result = await this.options.adapter.syncLocalDatabase(checkpoint);
1195
-
1196
- if (!result.checkpointValid) {
1197
- this.logger.debug(`Checksum mismatch in checkpoint ${checkpoint.last_op_id}, will reconnect`);
1198
- // This means checksums failed. Start again with a new checkpoint.
1199
- // TODO: better back-off
1200
- await new Promise((resolve) => setTimeout(resolve, 50));
1201
- return { applied: false, endIteration: true };
1202
- } else if (!result.ready) {
1203
- this.logger.debug(
1204
- `Could not apply checkpoint ${checkpoint.last_op_id} due to local data. We will retry applying the checkpoint after that upload is completed.`
1205
- );
1206
-
1207
- return { applied: false, endIteration: false };
1208
- }
1209
-
1210
- this.logger.debug(`Applied checkpoint ${checkpoint.last_op_id}`, checkpoint);
1211
- this.updateSyncStatus({
1212
- connected: true,
1213
- lastSyncedAt: new Date(),
1214
- dataFlow: {
1215
- downloading: false,
1216
- downloadProgress: null,
1217
- downloadError: undefined
1218
- }
1219
- });
1220
-
1221
- return { applied: true, endIteration: false };
1222
- }
1223
-
1224
- protected updateSyncStatus(options: SyncStatusOptions) {
1225
- const updatedStatus = new SyncStatus({
1226
- connected: options.connected ?? this.syncStatus.connected,
1227
- connecting: !options.connected && (options.connecting ?? this.syncStatus.connecting),
1228
- lastSyncedAt: options.lastSyncedAt ?? this.syncStatus.lastSyncedAt,
1229
- dataFlow: {
1230
- ...this.syncStatus.dataFlowStatus,
1231
- ...options.dataFlow
1232
- },
1233
- priorityStatusEntries: options.priorityStatusEntries ?? this.syncStatus.priorityStatusEntries,
1234
- clientImplementation: options.clientImplementation ?? this.syncStatus.clientImplementation
1235
- });
1236
-
1237
- if (!this.syncStatus.isEqual(updatedStatus)) {
1238
- this.syncStatus = updatedStatus;
1239
- // Only trigger this is there was a change
1240
- this.iterateListeners((cb) => cb.statusChanged?.(updatedStatus));
1241
- }
1242
-
1243
- // trigger this for all updates
1244
- this.iterateListeners((cb) => cb.statusUpdated?.(options));
1245
- }
1246
-
1247
- private async delayRetry(signal?: AbortSignal): Promise<void> {
1248
- return new Promise((resolve) => {
1249
- if (signal?.aborted) {
1250
- // If the signal is already aborted, resolve immediately
1251
- resolve();
1252
- return;
1253
- }
1254
- const { retryDelayMs } = this.options;
1255
-
1256
- let timeoutId: ReturnType<typeof setTimeout> | undefined;
1257
-
1258
- const endDelay = () => {
1259
- resolve();
1260
- if (timeoutId) {
1261
- clearTimeout(timeoutId);
1262
- timeoutId = undefined;
1263
- }
1264
- signal?.removeEventListener('abort', endDelay);
1265
- };
1266
-
1267
- signal?.addEventListener('abort', endDelay, { once: true });
1268
- timeoutId = setTimeout(endDelay, retryDelayMs);
1269
- });
1270
- }
1271
-
1272
- updateSubscriptions(subscriptions: SubscribedStream[]): void {
1273
- this.activeStreams = subscriptions;
1274
- this.handleActiveStreamsChange?.();
1275
- }
1276
- }
1277
-
1278
- interface EnqueuedCommand {
1279
- command: PowerSyncControlCommand;
1280
- payload?: Uint8Array | string;
1281
- }
1282
-
1283
- interface RustIterationResult {
1284
- immediateRestart: boolean;
1285
- }