@powersync/common 0.0.0-dev-20260630144038 → 0.0.0-dev-20261015114518

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 (48) hide show
  1. package/lib/attachments/AttachmentContext.js +2 -1
  2. package/lib/attachments/AttachmentContext.js.map +1 -1
  3. package/lib/attachments/AttachmentQueue.d.ts +98 -42
  4. package/lib/attachments/AttachmentQueue.js +103 -22
  5. package/lib/attachments/AttachmentQueue.js.map +1 -1
  6. package/lib/attachments/AttachmentTransportAdapter.d.ts +47 -0
  7. package/lib/attachments/AttachmentTransportAdapter.js +2 -0
  8. package/lib/attachments/AttachmentTransportAdapter.js.map +1 -0
  9. package/lib/attachments/BufferedAttachmentTransport.d.ts +24 -0
  10. package/lib/attachments/BufferedAttachmentTransport.js +32 -0
  11. package/lib/attachments/BufferedAttachmentTransport.js.map +1 -0
  12. package/lib/attachments/LocalStorageAdapter.d.ts +19 -0
  13. package/lib/attachments/Schema.d.ts +21 -2
  14. package/lib/attachments/Schema.js +14 -10
  15. package/lib/attachments/Schema.js.map +1 -1
  16. package/lib/attachments/SyncingService.d.ts +21 -8
  17. package/lib/attachments/SyncingService.js +59 -30
  18. package/lib/attachments/SyncingService.js.map +1 -1
  19. package/lib/client/CommonPowerSyncDatabase.d.ts +25 -1
  20. package/lib/client/connection/PowerSyncBackendConnector.d.ts +11 -0
  21. package/lib/client/connection/PowerSyncCredentials.d.ts +1 -1
  22. package/lib/client/runOnSchemaChange.js +2 -0
  23. package/lib/client/runOnSchemaChange.js.map +1 -1
  24. package/lib/client/sync/CheckpointRequest.d.ts +32 -0
  25. package/lib/client/sync/CheckpointRequest.js +2 -0
  26. package/lib/client/sync/CheckpointRequest.js.map +1 -0
  27. package/lib/client/sync/options.d.ts +42 -0
  28. package/lib/client/sync/options.js.map +1 -1
  29. package/lib/db/crud/SyncStatus.d.ts +1 -1
  30. package/lib/index.d.ts +3 -1
  31. package/lib/index.js +2 -0
  32. package/lib/index.js.map +1 -1
  33. package/package.json +4 -3
  34. package/src/attachments/AttachmentContext.ts +2 -1
  35. package/src/attachments/AttachmentQueue.ts +176 -68
  36. package/src/attachments/AttachmentTransportAdapter.ts +49 -0
  37. package/src/attachments/BufferedAttachmentTransport.ts +37 -0
  38. package/src/attachments/LocalStorageAdapter.ts +20 -0
  39. package/src/attachments/Schema.ts +29 -20
  40. package/src/attachments/SyncingService.ts +67 -34
  41. package/src/client/CommonPowerSyncDatabase.ts +26 -1
  42. package/src/client/connection/PowerSyncBackendConnector.ts +12 -0
  43. package/src/client/connection/PowerSyncCredentials.ts +1 -1
  44. package/src/client/runOnSchemaChange.ts +2 -0
  45. package/src/client/sync/CheckpointRequest.ts +31 -0
  46. package/src/client/sync/options.ts +44 -0
  47. package/src/db/crud/SyncStatus.ts +1 -1
  48. package/src/index.ts +9 -1
@@ -1,7 +1,7 @@
1
1
  import { LogLevels, PowerSyncLogger } from '../utils/Logger.js';
2
2
  import { AttachmentService } from './AttachmentService.js';
3
+ import { AttachmentTransportAdapter } from './AttachmentTransportAdapter.js';
3
4
  import { LocalStorageAdapter } from './LocalStorageAdapter.js';
4
- import { RemoteStorageAdapter } from './RemoteStorageAdapter.js';
5
5
  import { AttachmentRecord, AttachmentState } from './Schema.js';
6
6
  import { AttachmentErrorHandler } from './AttachmentErrorHandler.js';
7
7
  import { AttachmentContext } from './AttachmentContext.js';
@@ -10,60 +10,96 @@ import { AttachmentContext } from './AttachmentContext.js';
10
10
  * Orchestrates attachment synchronization between local and remote storage.
11
11
  * Handles uploads, downloads, deletions, and state transitions.
12
12
  *
13
+ * Remote operations (upload/download/delete) go through the {@link AttachmentTransportAdapter};
14
+ * local file operations use the {@link LocalStorageAdapter}.
15
+ *
13
16
  * @internal
14
17
  */
15
18
  export class SyncingService {
16
19
  private attachmentService: AttachmentService;
17
20
  private localStorage: LocalStorageAdapter;
18
- private remoteStorage: RemoteStorageAdapter;
21
+ private transport: AttachmentTransportAdapter;
19
22
  private logger: PowerSyncLogger;
20
23
  private errorHandler?: AttachmentErrorHandler;
21
24
 
22
25
  constructor(
23
26
  attachmentService: AttachmentService,
24
27
  localStorage: LocalStorageAdapter,
25
- remoteStorage: RemoteStorageAdapter,
28
+ transport: AttachmentTransportAdapter,
26
29
  logger: PowerSyncLogger,
27
30
  errorHandler?: AttachmentErrorHandler
28
31
  ) {
29
32
  this.attachmentService = attachmentService;
30
33
  this.localStorage = localStorage;
31
- this.remoteStorage = remoteStorage;
34
+ this.transport = transport;
32
35
  this.logger = logger;
33
36
  this.errorHandler = errorHandler;
34
37
  }
35
38
 
36
39
  /**
37
40
  * Processes attachments based on their state (upload, download, or delete).
38
- * All updates are saved in a single batch after processing.
41
+ *
42
+ * Each attachment's I/O runs outside the attachment-service mutex, and the row's
43
+ * state transition is persisted immediately after it completes. This keeps the
44
+ * mutex available to concurrent `saveFile` / `deleteFile` / watched-attachment
45
+ * processing while a batch is in flight, and means consumer queries against the
46
+ * attachments queue see incremental progress instead of one atomic commit at the
47
+ * end of the batch.
39
48
  *
40
49
  * @param attachments - Array of attachment records to process
41
- * @param context - Attachment context for database operations
42
- * @returns Promise that resolves when all attachments have been processed and saved
50
+ * @param options - Optional controls. Pass `signal` (an `AbortSignal`) to interrupt
51
+ * the batch: it is checked between attachments and, once aborted, the
52
+ * loop exits early — letting `stopSync` stop a running batch within
53
+ * one attachment's processing time.
43
54
  */
44
- async processAttachments(attachments: AttachmentRecord[], context: AttachmentContext): Promise<void> {
45
- const updatedAttachments: AttachmentRecord[] = [];
55
+ async processAttachments(
56
+ attachments: AttachmentRecord[],
57
+ options?: {
58
+ signal?: AbortSignal;
59
+ }
60
+ ): Promise<void> {
61
+ const signal = options?.signal;
62
+ this.logger.log({
63
+ level: LogLevels.info,
64
+ message: `Starting processAttachments with ${attachments.length} attachments`
65
+ });
66
+
46
67
  for (const attachment of attachments) {
47
- switch (attachment.state) {
48
- case AttachmentState.QUEUED_UPLOAD:
49
- const uploaded = await this.uploadAttachment(attachment);
50
- updatedAttachments.push(uploaded);
51
- break;
52
- case AttachmentState.QUEUED_DOWNLOAD:
53
- const downloaded = await this.downloadAttachment(attachment);
54
- updatedAttachments.push(downloaded);
55
- break;
56
- case AttachmentState.QUEUED_DELETE:
57
- const deleted = await this.deleteAttachment(attachment, context);
58
- updatedAttachments.push(deleted);
59
- break;
60
-
61
- default:
62
- break;
68
+ if (signal?.aborted) {
69
+ this.logger.log({
70
+ level: LogLevels.info,
71
+ message: 'Sync cancelled; stopping iteration early'
72
+ });
73
+ return;
63
74
  }
64
- }
65
75
 
66
- await context.saveAttachments(updatedAttachments);
76
+ try {
77
+ let updated: AttachmentRecord;
78
+ switch (attachment.state) {
79
+ case AttachmentState.QUEUED_UPLOAD:
80
+ updated = await this.uploadAttachment(attachment);
81
+ break;
82
+ case AttachmentState.QUEUED_DOWNLOAD:
83
+ updated = await this.downloadAttachment(attachment);
84
+ break;
85
+ case AttachmentState.QUEUED_DELETE:
86
+ // `deleteAttachment` needs a context (it removes the row in a
87
+ // transaction); briefly re-acquire the mutex for just this row.
88
+ updated = await this.attachmentService.withContext((ctx) => this.deleteAttachment(attachment, ctx));
89
+ break;
90
+ default:
91
+ continue;
92
+ }
93
+
94
+ await this.attachmentService.withContext((ctx) => ctx.saveAttachments([updated]));
95
+ } catch (error) {
96
+ this.logger.log({
97
+ level: LogLevels.warn,
98
+ message: `Error during sync for ${attachment.id}`,
99
+ error
100
+ });
101
+ }
102
+ }
67
103
  }
68
104
 
69
105
  /**
@@ -81,8 +117,7 @@ export class SyncingService {
81
117
  throw new Error(`No localUri for attachment ${attachment.id}`);
82
118
  }
83
119
 
84
- const fileBlob = await this.localStorage.readFile(attachment.localUri);
85
- await this.remoteStorage.uploadFile(fileBlob, attachment);
120
+ await this.transport.upload({ ...attachment, localUri: attachment.localUri });
86
121
 
87
122
  return {
88
123
  ...attachment,
@@ -104,7 +139,7 @@ export class SyncingService {
104
139
 
105
140
  /**
106
141
  * Downloads an attachment from remote storage to local storage.
107
- * Retrieves the file, converts to base64, and saves locally.
142
+ * The destination `localUri` is assigned here and the transport writes the file to it.
108
143
  * On success, marks as SYNCED. On failure, defers to error handler or archives.
109
144
  *
110
145
  * @param attachment - The attachment record to download
@@ -113,10 +148,8 @@ export class SyncingService {
113
148
  async downloadAttachment(attachment: AttachmentRecord): Promise<AttachmentRecord> {
114
149
  this.logger.log({ level: LogLevels.info, message: `Downloading attachment ${attachment.filename}` });
115
150
  try {
116
- const fileData = await this.remoteStorage.downloadFile(attachment);
117
-
118
151
  const localUri = this.localStorage.getLocalUri(attachment.filename);
119
- await this.localStorage.saveFile(localUri, fileData);
152
+ await this.transport.download({ ...attachment, localUri });
120
153
 
121
154
  return {
122
155
  ...attachment,
@@ -148,7 +181,7 @@ export class SyncingService {
148
181
  */
149
182
  async deleteAttachment(attachment: AttachmentRecord, context: AttachmentContext): Promise<AttachmentRecord> {
150
183
  try {
151
- await this.remoteStorage.deleteFile(attachment);
184
+ await this.transport.delete(attachment);
152
185
  if (attachment.localUri) {
153
186
  await this.localStorage.deleteFile(attachment.localUri);
154
187
  }
@@ -16,13 +16,25 @@ import { ArrayQueryDefinition, Query } from './Query.js';
16
16
  import { WatchCompatibleQuery } from './watched/WatchedQuery.js';
17
17
  import { Mutex } from '../utils/mutex.js';
18
18
  import { QueryResult } from '../db/QueryResult.js';
19
+ import { CheckpointRequest } from './sync/CheckpointRequest.js';
19
20
 
20
21
  /**
22
+ * Options passed to {@link CommonPowerSyncDatabase#disconnectAndClear}.
23
+ *
21
24
  * @public
22
25
  */
23
26
  export interface DisconnectAndClearOptions {
24
27
  /** When set to false, data in local-only tables is preserved. */
25
28
  clearLocal?: boolean;
29
+ /**
30
+ * A [soft] clear deletes publicly visible tables, but keeps internal copies of data synced in the database.
31
+ *
32
+ * This usually means that if {@link CommonPowerSyncDatabase#connect} is later called again with a JWT from the same
33
+ * user, the first sync is very fast because all internal data is still available. When a different user logs in, no
34
+ * old data would be visible at any point. Using soft deletes is recommended where it's not a security issue that old
35
+ * data could be reconstructed from internal database tables.
36
+ */
37
+ soft?: boolean;
26
38
  }
27
39
 
28
40
  /**
@@ -233,6 +245,19 @@ export interface CommonPowerSyncDatabase extends BaseObserverInterface<PowerSync
233
245
  */
234
246
  syncStream(name: string, params?: Record<string, any>): SyncStream;
235
247
 
248
+ /**
249
+ * Requests a checkpoint from the PowerSync service.
250
+ *
251
+ * The returned request can be awaited (using {@link CheckpointRequest#waitForSync}) to confirm that the local
252
+ * database has applied server-side changes up to the checkpoint. This method requires an active or connecting sync
253
+ * client connected with a {@link CheckpointMode} set to `requests` and PowerSync service version 1.24.0 or later.
254
+ *
255
+ * It can throw for connection, mode, authentication, or service request failures.
256
+ *
257
+ * @alpha
258
+ */
259
+ requestCheckpoint(): Promise<CheckpointRequest>;
260
+
236
261
  /**
237
262
  * Close the database, releasing resources.
238
263
  *
@@ -343,7 +368,7 @@ export interface CommonPowerSyncDatabase extends BaseObserverInterface<PowerSync
343
368
 
344
369
  /**
345
370
  * Open a read-only transaction.
346
- * Read transactions can run concurrently to a write transaction.
371
+ * When multiple connections are available, read transactions can run concurrently to a write transaction.
347
372
  * Changes from any write transaction are not visible to read transactions started before it.
348
373
  *
349
374
  * @param callback - Function to execute within the transaction
@@ -25,4 +25,16 @@ export interface PowerSyncBackendConnector {
25
25
  * Any thrown errors will result in a retry after the configured wait period (default: 5 seconds).
26
26
  */
27
27
  uploadData: (database: CommonPowerSyncDatabase) => Promise<void>;
28
+
29
+ /**
30
+ * Posts a client-generated checkpoint request to the backend and returns the effective checkpoint request state.
31
+ *
32
+ * This method is optional. It only needs to be implemented when the selected {@link CheckpointMode} is `requests`
33
+ * and [asynchronous backend uploads](https://docs.powersync.com/client-sdks/advanced/checkpoint-requests#asynchronous-upload-backends)
34
+ * are used. In any other case, this method should not be present on backend connectors.
35
+ *
36
+ * @param requestId - The client-generated checkpoint request ID (a positive 64-bit integer encoded as a string).
37
+ * @param clientId - The PowerSync client ID for the current device.
38
+ */
39
+ postCheckpointRequest?(clientId: string, requestId: string): Promise<string>;
28
40
  }
@@ -4,5 +4,5 @@
4
4
  export interface PowerSyncCredentials {
5
5
  endpoint: string;
6
6
  token: string;
7
- expiresAt?: Date;
7
+ expiresAt?: Date | undefined;
8
8
  }
@@ -9,6 +9,8 @@ export function runOnSchemaChange(
9
9
  options?: SQLWatchOptions
10
10
  ): void {
11
11
  const triggerWatchedQuery = () => {
12
+ if (options?.signal?.aborted) return;
13
+
12
14
  const abortController = new AbortController();
13
15
  let disposeSchemaListener: (() => void) | null = null;
14
16
  const stopWatching = () => {
@@ -0,0 +1,31 @@
1
+ /**
2
+ * A checkpoint request created by {@link CommonPowerSyncDatabase#requestCheckpoint}.
3
+ *
4
+ * Use this value to wait until the local database has applied server-side changes up to the requested checkpoint. This
5
+ * is useful for explicit refresh flows where the caller wants confirmation that the local view has caught up to the
6
+ * service.
7
+ *
8
+ * Checkpoint requests are backed by request ids tracked in the local database, so they are reusable across disconnect
9
+ * and reconnect cycles. A wait interrupted by a disconnect throws an error, but the same request can be awaited again
10
+ * once a new connection is established.
11
+ *
12
+ * Requests do not survive {@link CommonPowerSyncDatabase#disconnectAndClear}, instances created before a clear should
13
+ * be discarded and requested again.
14
+ *
15
+ * @alpha
16
+ */
17
+ export interface CheckpointRequest {
18
+ /**
19
+ * Whether this checkpoint request has synced before.
20
+ */
21
+ readonly hasSynced: boolean;
22
+
23
+ /**
24
+ * Waits until this checkpoint has been synced locally.
25
+ *
26
+ * This method fails on sync errors: If a download or upload error occurs before this checkpoint request has synced,
27
+ * that error is rethrown here. This makes it easier to observe sync errors when relying on checkpoints. Once sync has
28
+ * recovered, it is valid to call this method again to await the checkpoint.
29
+ */
30
+ waitForSync(options?: { signal?: AbortSignal }): Promise<void>;
31
+ }
@@ -49,6 +49,20 @@ export interface SyncOptions {
49
49
  * milliseconds.
50
50
  */
51
51
  crudUploadThrottleMs?: number;
52
+
53
+ /**
54
+ * The mode used to request checkpoints from the service (used after uploading local data).
55
+ */
56
+ checkpointMode?: CheckpointMode;
57
+
58
+ /**
59
+ * Enables the core extension's diagnostics event stream: detailed per-bucket download stats,
60
+ * including each bucket's `target_count`, and inferred column types. Off by default.
61
+ *
62
+ * The events are internal. No public API exposes them; only PowerSync DevTools reads them, to show
63
+ * per-bucket totals. See https://docs.powersync.com/tools/devtools-overview.
64
+ */
65
+ diagnostics?: boolean;
52
66
  }
53
67
 
54
68
  /**
@@ -75,3 +89,33 @@ export enum FetchStrategy {
75
89
  */
76
90
  Sequential = 'sequential'
77
91
  }
92
+
93
+ /**
94
+ * The mechanism to request checkpoints from the PowerSync service.
95
+ *
96
+ * Checkpoint requests are used after a client uploads local mutations. The PowerSync service later references them in
97
+ * downloaded data, allowing the SDK to assume that uploaded data has been synced down again.
98
+ *
99
+ * There are two ways to send checkpoint requests: A legacy (but default and stable) format supported by all PowerSync
100
+ * service versions, and a newer (`requests`) method which is only available from PowerSync service version 1.24.0 or
101
+ * later.
102
+ *
103
+ * Note that the requests checkpoint mode is an alpha API.
104
+ *
105
+ * @public
106
+ */
107
+ export type CheckpointMode = 'legacy' | 'requests' | { requests: CheckpointRequestsOptions };
108
+
109
+ /**
110
+ * Options associated with a {@link CheckpointMode} when the requests-based checkpoint option is used.
111
+ *
112
+ * @public
113
+ */
114
+ export interface CheckpointRequestsOptions {
115
+ /**
116
+ * The delay, in milliseconds, to wait before re-sending a checkpoint request when it hasn't been applied in time.
117
+ *
118
+ * The minimum value for this is 10 seconds, lower values will be ignored.
119
+ */
120
+ retryDelay: number;
121
+ }
@@ -94,7 +94,7 @@ export interface SyncStatus {
94
94
  get hasSynced(): boolean | undefined;
95
95
 
96
96
  /**
97
- * All sync streams currently being tracked in teh database.
97
+ * All sync streams currently being tracked in the database.
98
98
  *
99
99
  * This returns null when the database is currently being opened and we don't have reliable information about all
100
100
  * included streams yet.
package/src/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export * from './attachments/AttachmentContext.js';
2
2
  export * from './attachments/AttachmentErrorHandler.js';
3
3
  export * from './attachments/AttachmentQueue.js';
4
+ export * from './attachments/AttachmentTransportAdapter.js';
4
5
  export * from './attachments/LocalStorageAdapter.js';
5
6
  export * from './attachments/RemoteStorageAdapter.js';
6
7
  export * from './attachments/Schema.js';
@@ -14,9 +15,16 @@ export * from './client/SQLOpenFactory.js';
14
15
  export * from './client/sync/bucket/CrudBatch.js';
15
16
  export { CrudEntry, OpId, UpdateType } from './client/sync/bucket/CrudEntry.js';
16
17
  export * from './client/sync/bucket/CrudTransaction.js';
18
+ export * from './client/sync/CheckpointRequest.js';
17
19
  export * from './client/sync/stream/JsonValue.js';
18
20
  export * from './client/sync/sync-streams.js';
19
- export { SyncOptions, SyncStreamConnectionMethod, FetchStrategy } from './client/sync/options.js';
21
+ export {
22
+ SyncOptions,
23
+ SyncStreamConnectionMethod,
24
+ FetchStrategy,
25
+ CheckpointMode,
26
+ CheckpointRequestsOptions
27
+ } from './client/sync/options.js';
20
28
 
21
29
  export { ProgressWithOperations, SyncProgress } from './db/crud/SyncProgress.js';
22
30
  export * from './db/crud/SyncStatus.js';