@powersync/common 1.49.0 → 1.50.0

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.
@@ -1,29 +1,105 @@
1
1
  /**
2
- * Wrapper for async-mutex runExclusive, which allows for a timeout on each exclusive lock.
2
+ * An asynchronous mutex implementation.
3
+ *
4
+ * @internal This class is meant to be used in PowerSync SDKs only, and is not part of the public API.
3
5
  */
4
- export async function mutexRunExclusive(mutex, callback, options) {
5
- return new Promise((resolve, reject) => {
6
- const timeout = options?.timeoutMs;
7
- let timedOut = false;
8
- const timeoutId = timeout
9
- ? setTimeout(() => {
10
- timedOut = true;
11
- reject(new Error('Timeout waiting for lock'));
12
- }, timeout)
13
- : undefined;
14
- mutex.runExclusive(async () => {
15
- if (timeoutId) {
16
- clearTimeout(timeoutId);
6
+ export class Mutex {
7
+ inCriticalSection = false;
8
+ // Linked list of waiters. We don't expect the wait list to become particularly large, and this allows removing
9
+ // aborted waiters from the middle of the list efficiently.
10
+ firstWaiter;
11
+ lastWaiter;
12
+ addWaiter(onAcquire) {
13
+ const node = {
14
+ isActive: true,
15
+ onAcquire,
16
+ prev: this.lastWaiter
17
+ };
18
+ if (this.lastWaiter) {
19
+ this.lastWaiter.next = node;
20
+ this.lastWaiter = node;
21
+ }
22
+ else {
23
+ // First waiter
24
+ this.lastWaiter = this.firstWaiter = node;
25
+ }
26
+ return node;
27
+ }
28
+ deactivateWaiter(waiter) {
29
+ const { prev, next } = waiter;
30
+ waiter.isActive = false;
31
+ if (prev)
32
+ prev.next = next;
33
+ if (next)
34
+ next.prev = prev;
35
+ if (waiter == this.firstWaiter)
36
+ this.firstWaiter = next;
37
+ if (waiter == this.lastWaiter)
38
+ this.lastWaiter = prev;
39
+ }
40
+ acquire(abort) {
41
+ return new Promise((resolve, reject) => {
42
+ function rejectAborted() {
43
+ reject(abort?.reason ?? new Error('Mutex acquire aborted'));
17
44
  }
18
- if (timedOut)
19
- return;
20
- try {
21
- resolve(await callback());
45
+ if (abort?.aborted) {
46
+ return rejectAborted();
22
47
  }
23
- catch (ex) {
24
- reject(ex);
48
+ let holdsMutex = false;
49
+ const markCompleted = () => {
50
+ if (!holdsMutex)
51
+ return;
52
+ holdsMutex = false;
53
+ const waiter = this.firstWaiter;
54
+ if (waiter) {
55
+ this.deactivateWaiter(waiter);
56
+ // Still in critical section, but owned by next waiter now.
57
+ waiter.onAcquire();
58
+ }
59
+ else {
60
+ this.inCriticalSection = false;
61
+ }
62
+ };
63
+ if (!this.inCriticalSection) {
64
+ this.inCriticalSection = true;
65
+ holdsMutex = true;
66
+ return resolve(markCompleted);
67
+ }
68
+ else {
69
+ let node;
70
+ const onAbort = () => {
71
+ abort?.removeEventListener('abort', onAbort);
72
+ if (node.isActive) {
73
+ this.deactivateWaiter(node);
74
+ rejectAborted();
75
+ }
76
+ };
77
+ node = this.addWaiter(() => {
78
+ abort?.removeEventListener('abort', onAbort);
79
+ holdsMutex = true;
80
+ resolve(markCompleted);
81
+ });
82
+ abort?.addEventListener('abort', onAbort);
25
83
  }
26
84
  });
27
- });
85
+ }
86
+ async runExclusive(fn, abort) {
87
+ const returnMutex = await this.acquire(abort);
88
+ try {
89
+ return await fn();
90
+ }
91
+ finally {
92
+ returnMutex();
93
+ }
94
+ }
95
+ }
96
+ export function timeoutSignal(timeout) {
97
+ if (timeout == null)
98
+ return;
99
+ if ('timeout' in AbortSignal)
100
+ return AbortSignal.timeout(timeout);
101
+ const controller = new AbortController();
102
+ setTimeout(() => controller.abort(new Error('Timeout waiting for lock')), timeout);
103
+ return controller.signal;
28
104
  }
29
105
  //# sourceMappingURL=mutex.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"mutex.js","sourceRoot":"","sources":["../../src/utils/mutex.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,KAAY,EACZ,QAA0B,EAC1B,OAAgC;IAEhC,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,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AC,OAAO,CAAC,OAAO,CAAC,CAAC;IAElE,MAAM,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;IACzC,UAAU,CAAC,GAAG,EAAE,CAAC,UAAU,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;IACnF,OAAO,UAAU,CAAC,MAAM,CAAC;AAC3B,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powersync/common",
3
- "version": "1.49.0",
3
+ "version": "1.50.0",
4
4
  "publishConfig": {
5
5
  "registry": "https://registry.npmjs.org/",
6
6
  "access": "public"
@@ -48,7 +48,6 @@
48
48
  },
49
49
  "homepage": "https://docs.powersync.com",
50
50
  "dependencies": {
51
- "async-mutex": "^0.5.0",
52
51
  "event-iterator": "^2.0.0"
53
52
  },
54
53
  "devDependencies": {
@@ -51,10 +51,16 @@ export class AttachmentQueue {
51
51
  /** Logger instance for diagnostic information */
52
52
  readonly logger: ILogger;
53
53
 
54
- /** Interval in milliseconds between periodic sync operations. Default: 30000 (30 seconds) */
54
+ /** Interval in milliseconds between periodic sync operations. Acts as a polling timer to retry
55
+ * failed uploads/downloads, especially after the app goes offline. Default: 30000 (30 seconds) */
55
56
  readonly syncIntervalMs: number = 30 * 1000;
56
57
 
57
- /** Duration in milliseconds to throttle sync operations */
58
+ /** Throttle duration in milliseconds for the reactive watch query on the attachments table.
59
+ * When attachment records change, a watch query detects the change and triggers a sync.
60
+ * This throttle prevents the sync from firing too rapidly when many changes happen in
61
+ * quick succession (e.g., bulk inserts). This is distinct from syncIntervalMs — it controls
62
+ * how quickly the queue reacts to changes, while syncIntervalMs controls how often it polls
63
+ * for retries. Default: 30 (from DEFAULT_WATCH_THROTTLE_MS) */
58
64
  readonly syncThrottleDuration: number;
59
65
 
60
66
  /** Whether to automatically download remote attachments. Default: true */
@@ -86,8 +92,8 @@ export class AttachmentQueue {
86
92
  * @param options.watchAttachments - Callback for monitoring attachment changes in your data model
87
93
  * @param options.tableName - Name of the table to store attachment records. Default: 'ps_attachment_queue'
88
94
  * @param options.logger - Logger instance. Defaults to db.logger
89
- * @param options.syncIntervalMs - Interval between automatic syncs in milliseconds. Default: 30000
90
- * @param options.syncThrottleDuration - Throttle duration for sync operations in milliseconds. Default: 1000
95
+ * @param options.syncIntervalMs - Periodic polling interval in milliseconds for retrying failed uploads/downloads. Default: 30000
96
+ * @param options.syncThrottleDuration - Throttle duration in milliseconds for the reactive watch query that detects attachment changes. Prevents rapid-fire syncs during bulk changes. Default: 30
91
97
  * @param options.downloadAttachments - Whether to automatically download remote attachments. Default: true
92
98
  * @param options.archivedCacheLimit - Maximum archived attachments before cleanup. Default: 100
93
99
  */
@@ -1,8 +1,7 @@
1
- import { Mutex } from 'async-mutex';
2
1
  import { AbstractPowerSyncDatabase } from '../client/AbstractPowerSyncDatabase.js';
3
2
  import { DifferentialWatchedQuery } from '../client/watched/processors/DifferentialQueryProcessor.js';
4
3
  import { ILogger } from '../utils/Logger.js';
5
- import { mutexRunExclusive } from '../utils/mutex.js';
4
+ import { Mutex } from '../utils/mutex.js';
6
5
  import { AttachmentContext } from './AttachmentContext.js';
7
6
  import { AttachmentRecord, AttachmentState } from './Schema.js';
8
7
 
@@ -55,7 +54,7 @@ export class AttachmentService {
55
54
  * Executes a callback with exclusive access to the attachment context.
56
55
  */
57
56
  async withContext<T>(callback: (context: AttachmentContext) => Promise<T>): Promise<T> {
58
- return mutexRunExclusive(this.mutex, async () => {
57
+ return this.mutex.runExclusive(async () => {
59
58
  return callback(this.context);
60
59
  });
61
60
  }
@@ -289,8 +289,8 @@ new AttachmentQueue(options: AttachmentQueueOptions)
289
289
  | `watchAttachments` | `(onUpdate: (attachments: WatchedAttachmentItem[]) => Promise<void>) => void` | Yes | - | Callback to determine which attachments to handle by the queue from your user defined query |
290
290
  | `tableName` | `string` | No | `'attachments'` | Name of the attachments table |
291
291
  | `logger` | `ILogger` | No | `db.logger` | Logger instance for diagnostic output |
292
- | `syncIntervalMs` | `number` | No | `30000` | Interval between automatic syncs in milliseconds |
293
- | `syncThrottleDuration` | `number` | No | `30` | Throttle duration for sync operations in milliseconds |
292
+ | `syncIntervalMs` | `number` | No | `30000` | Periodic polling interval (in milliseconds) for retrying failed uploads/downloads. A `setInterval` timer that calls `syncStorage()` on this cadence, ensuring operations are retried even if no database changes occur (e.g., after coming back online). |
293
+ | `syncThrottleDuration` | `number` | No | `30` | Throttle duration (in milliseconds) for the reactive watch query on the attachments table. When attachment records change (e.g., a new file is queued), a watch query detects the change and triggers a sync. This throttle prevents the sync from firing too rapidly when many changes happen in quick succession (e.g., bulk inserts). This is distinct from `syncIntervalMs` — it controls how quickly the queue *reacts* to changes, while `syncIntervalMs` controls how often it *polls* for retries. |
294
294
  | `downloadAttachments` | `boolean` | No | `true` | Whether to automatically download remote attachments |
295
295
  | `archivedCacheLimit` | `number` | No | `100` | Maximum number of archived attachments before cleanup |
296
296
  | `errorHandler` | `AttachmentErrorHandler` | No | `undefined` | Custom error handler for upload/download/delete operations |
@@ -676,11 +676,13 @@ Adjust sync frequency based on your needs:
676
676
  ```typescript
677
677
  const queue = new AttachmentQueue({
678
678
  // ... other options
679
- syncIntervalMs: 60000, // Sync every 60 seconds instead of 30
679
+ syncIntervalMs: 60000, // Poll for retries every 60 seconds instead of 30
680
+ syncThrottleDuration: 100, // React to attachment changes within 100ms (default: 30ms)
680
681
  });
681
682
  ```
682
683
 
683
- Set to `0` to disable periodic syncing (manual `syncStorage()` calls only).
684
+ - **`syncIntervalMs`** controls the periodic polling timer how often the queue retries failed operations.
685
+ - **`syncThrottleDuration`** controls how quickly the queue reacts to attachment table changes. The default (30ms) is fast enough for most use cases. Increase it if you see performance issues during bulk attachment operations.
684
686
 
685
687
  ### Archive and Cache Management
686
688
 
@@ -54,7 +54,7 @@ export class SyncingService {
54
54
  updatedAttachments.push(downloaded);
55
55
  break;
56
56
  case AttachmentState.QUEUED_DELETE:
57
- const deleted = await this.deleteAttachment(attachment);
57
+ const deleted = await this.deleteAttachment(attachment, context);
58
58
  updatedAttachments.push(deleted);
59
59
  break;
60
60
 
@@ -143,18 +143,17 @@ export class SyncingService {
143
143
  * On failure, defers to error handler or archives.
144
144
  *
145
145
  * @param attachment - The attachment record to delete
146
+ * @param context - Attachment context for database operations
146
147
  * @returns Updated attachment record
147
148
  */
148
- async deleteAttachment(attachment: AttachmentRecord): Promise<AttachmentRecord> {
149
+ async deleteAttachment(attachment: AttachmentRecord, context: AttachmentContext): Promise<AttachmentRecord> {
149
150
  try {
150
151
  await this.remoteStorage.deleteFile(attachment);
151
152
  if (attachment.localUri) {
152
153
  await this.localStorage.deleteFile(attachment.localUri);
153
154
  }
154
155
 
155
- await this.attachmentService.withContext(async (ctx) => {
156
- await ctx.deleteAttachment(attachment.id);
157
- });
156
+ await context.deleteAttachment(attachment.id);
158
157
 
159
158
  return {
160
159
  ...attachment,
@@ -1,4 +1,3 @@
1
- import { Mutex } from 'async-mutex';
2
1
  import { EventIterator } from 'event-iterator';
3
2
  import Logger, { ILogger } from 'js-logger';
4
3
  import {
@@ -46,6 +45,7 @@ import { TriggerManagerImpl } from './triggers/TriggerManagerImpl.js';
46
45
  import { DEFAULT_WATCH_THROTTLE_MS, WatchCompatibleQuery } from './watched/WatchedQuery.js';
47
46
  import { OnChangeQueryProcessor } from './watched/processors/OnChangeQueryProcessor.js';
48
47
  import { WatchedQueryComparator } from './watched/processors/comparators.js';
48
+ import { Mutex } from '../utils/mutex.js';
49
49
 
50
50
  export interface DisconnectAndClearOptions {
51
51
  /** When set to false, data in local-only tables is preserved. */
@@ -813,6 +813,10 @@ SELECT * FROM crud_entries;
813
813
  * Execute a SQL write (INSERT/UPDATE/DELETE) query
814
814
  * and optionally return results.
815
815
  *
816
+ * When using the default client-side [JSON-based view system](https://docs.powersync.com/architecture/client-architecture#client-side-schema-and-sqlite-database-structure),
817
+ * the returned result's `rowsAffected` may be `0` for successful `UPDATE` and `DELETE` statements.
818
+ * Use a `RETURNING` clause and inspect `result.rows` when you need to confirm which rows changed.
819
+ *
816
820
  * @param sql The SQL query to execute
817
821
  * @param parameters Optional array of parameters to bind to the query
818
822
  * @returns The query result as an object with structured key-value pairs
@@ -921,7 +925,7 @@ SELECT * FROM crud_entries;
921
925
  await this.waitForReady();
922
926
  return this.database.readTransaction(
923
927
  async (tx) => {
924
- const res = await callback({ ...tx });
928
+ const res = await callback(tx);
925
929
  await tx.rollback();
926
930
  return res;
927
931
  },
@@ -16,7 +16,13 @@ import { BaseListener, BaseObserverInterface } from '../utils/BaseObserver.js';
16
16
  export type QueryResult = {
17
17
  /** Represents the auto-generated row id if applicable. */
18
18
  insertId?: number;
19
- /** Number of affected rows if result of a update query. */
19
+ /**
20
+ * Number of affected rows reported by SQLite for a write query.
21
+ *
22
+ * When using the default client-side [JSON-based view system](https://docs.powersync.com/architecture/client-architecture#client-side-schema-and-sqlite-database-structure),
23
+ * `rowsAffected` may be `0` for successful `UPDATE` and `DELETE` statements.
24
+ * Use a `RETURNING` clause and inspect `rows` when you need to confirm which rows changed.
25
+ */
20
26
  rowsAffected: number;
21
27
  /** if status is undefined or 0 this object will contain the query results */
22
28
  rows?: {
@@ -1,34 +1,129 @@
1
- import { Mutex } from 'async-mutex';
1
+ export type UnlockFn = () => void;
2
2
 
3
3
  /**
4
- * Wrapper for async-mutex runExclusive, which allows for a timeout on each exclusive lock.
4
+ * An asynchronous mutex implementation.
5
+ *
6
+ * @internal This class is meant to be used in PowerSync SDKs only, and is not part of the public API.
5
7
  */
6
- export async function mutexRunExclusive<T>(
7
- mutex: Mutex,
8
- callback: () => Promise<T>,
9
- options?: { timeoutMs?: number }
10
- ): Promise<T> {
11
- return new Promise((resolve, reject) => {
12
- const timeout = options?.timeoutMs;
13
- let timedOut = false;
14
- const timeoutId = timeout
15
- ? setTimeout(() => {
16
- timedOut = true;
17
- reject(new Error('Timeout waiting for lock'));
18
- }, timeout)
19
- : undefined;
20
-
21
- mutex.runExclusive(async () => {
22
- if (timeoutId) {
23
- clearTimeout(timeoutId);
8
+ export class Mutex {
9
+ private inCriticalSection = false;
10
+
11
+ // Linked list of waiters. We don't expect the wait list to become particularly large, and this allows removing
12
+ // aborted waiters from the middle of the list efficiently.
13
+ private firstWaiter?: MutexWaitNode;
14
+ private lastWaiter?: MutexWaitNode;
15
+
16
+ private addWaiter(onAcquire: () => void): MutexWaitNode {
17
+ const node: MutexWaitNode = {
18
+ isActive: true,
19
+ onAcquire,
20
+ prev: this.lastWaiter
21
+ };
22
+ if (this.lastWaiter) {
23
+ this.lastWaiter.next = node;
24
+ this.lastWaiter = node;
25
+ } else {
26
+ // First waiter
27
+ this.lastWaiter = this.firstWaiter = node;
28
+ }
29
+
30
+ return node;
31
+ }
32
+
33
+ private deactivateWaiter(waiter: MutexWaitNode) {
34
+ const { prev, next } = waiter;
35
+ waiter.isActive = false;
36
+
37
+ if (prev) prev.next = next;
38
+ if (next) next.prev = prev;
39
+ if (waiter == this.firstWaiter) this.firstWaiter = next;
40
+ if (waiter == this.lastWaiter) this.lastWaiter = prev;
41
+ }
42
+
43
+ acquire(abort?: AbortSignal): Promise<UnlockFn> {
44
+ return new Promise((resolve, reject) => {
45
+ function rejectAborted() {
46
+ reject(abort?.reason ?? new Error('Mutex acquire aborted'));
24
47
  }
25
- if (timedOut) return;
48
+ if (abort?.aborted) {
49
+ return rejectAborted();
50
+ }
51
+
52
+ let holdsMutex = false;
53
+
54
+ const markCompleted = () => {
55
+ if (!holdsMutex) return;
56
+ holdsMutex = false;
57
+
58
+ const waiter = this.firstWaiter;
59
+ if (waiter) {
60
+ this.deactivateWaiter(waiter);
61
+ // Still in critical section, but owned by next waiter now.
62
+ waiter.onAcquire();
63
+ } else {
64
+ this.inCriticalSection = false;
65
+ }
66
+ };
67
+
68
+ if (!this.inCriticalSection) {
69
+ this.inCriticalSection = true;
70
+ holdsMutex = true;
71
+ return resolve(markCompleted);
72
+ } else {
73
+ let node: MutexWaitNode;
74
+
75
+ const onAbort = () => {
76
+ abort?.removeEventListener('abort', onAbort);
26
77
 
27
- try {
28
- resolve(await callback());
29
- } catch (ex) {
30
- reject(ex);
78
+ if (node.isActive) {
79
+ this.deactivateWaiter(node);
80
+ rejectAborted();
81
+ }
82
+ };
83
+
84
+ node = this.addWaiter(() => {
85
+ abort?.removeEventListener('abort', onAbort);
86
+ holdsMutex = true;
87
+ resolve(markCompleted);
88
+ });
89
+
90
+ abort?.addEventListener('abort', onAbort);
31
91
  }
32
92
  });
33
- });
93
+ }
94
+
95
+ async runExclusive<T>(fn: () => PromiseLike<T> | T, abort?: AbortSignal): Promise<T> {
96
+ const returnMutex = await this.acquire(abort);
97
+
98
+ try {
99
+ return await fn();
100
+ } finally {
101
+ returnMutex();
102
+ }
103
+ }
104
+ }
105
+
106
+ interface MutexWaitNode {
107
+ /**
108
+ * Whether the waiter is currently active (not aborted and not fullfilled).
109
+ */
110
+ isActive: boolean;
111
+ onAcquire: () => void;
112
+ prev?: MutexWaitNode;
113
+ next?: MutexWaitNode;
114
+ }
115
+
116
+ /**
117
+ * Creates a signal aborting after the set timeout.
118
+ */
119
+ export function timeoutSignal(timeout: number): AbortSignal;
120
+ export function timeoutSignal(timeout?: number): AbortSignal | undefined;
121
+
122
+ export function timeoutSignal(timeout?: number): AbortSignal | undefined {
123
+ if (timeout == null) return;
124
+ if ('timeout' in AbortSignal) return AbortSignal.timeout(timeout);
125
+
126
+ const controller = new AbortController();
127
+ setTimeout(() => controller.abort(new Error('Timeout waiting for lock')), timeout);
128
+ return controller.signal;
34
129
  }