@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,4 +1,3 @@
1
- import { Mutex } from 'async-mutex';
2
1
  import { EventIterator } from 'event-iterator';
3
2
  import { Buffer } from 'node:buffer';
4
3
 
@@ -659,7 +658,7 @@ class SyncingService {
659
658
  updatedAttachments.push(downloaded);
660
659
  break;
661
660
  case AttachmentState.QUEUED_DELETE:
662
- const deleted = await this.deleteAttachment(attachment);
661
+ const deleted = await this.deleteAttachment(attachment, context);
663
662
  updatedAttachments.push(deleted);
664
663
  break;
665
664
  }
@@ -737,17 +736,16 @@ class SyncingService {
737
736
  * On failure, defers to error handler or archives.
738
737
  *
739
738
  * @param attachment - The attachment record to delete
739
+ * @param context - Attachment context for database operations
740
740
  * @returns Updated attachment record
741
741
  */
742
- async deleteAttachment(attachment) {
742
+ async deleteAttachment(attachment, context) {
743
743
  try {
744
744
  await this.remoteStorage.deleteFile(attachment);
745
745
  if (attachment.localUri) {
746
746
  await this.localStorage.deleteFile(attachment.localUri);
747
747
  }
748
- await this.attachmentService.withContext(async (ctx) => {
749
- await ctx.deleteAttachment(attachment.id);
750
- });
748
+ await context.deleteAttachment(attachment.id);
751
749
  return {
752
750
  ...attachment,
753
751
  state: AttachmentState.ARCHIVED
@@ -785,32 +783,108 @@ class SyncingService {
785
783
  }
786
784
 
787
785
  /**
788
- * Wrapper for async-mutex runExclusive, which allows for a timeout on each exclusive lock.
786
+ * An asynchronous mutex implementation.
787
+ *
788
+ * @internal This class is meant to be used in PowerSync SDKs only, and is not part of the public API.
789
789
  */
790
- async function mutexRunExclusive(mutex, callback, options) {
791
- return new Promise((resolve, reject) => {
792
- const timeout = options?.timeoutMs;
793
- let timedOut = false;
794
- const timeoutId = timeout
795
- ? setTimeout(() => {
796
- timedOut = true;
797
- reject(new Error('Timeout waiting for lock'));
798
- }, timeout)
799
- : undefined;
800
- mutex.runExclusive(async () => {
801
- if (timeoutId) {
802
- clearTimeout(timeoutId);
803
- }
804
- if (timedOut)
805
- return;
806
- try {
807
- resolve(await callback());
790
+ class Mutex {
791
+ inCriticalSection = false;
792
+ // Linked list of waiters. We don't expect the wait list to become particularly large, and this allows removing
793
+ // aborted waiters from the middle of the list efficiently.
794
+ firstWaiter;
795
+ lastWaiter;
796
+ addWaiter(onAcquire) {
797
+ const node = {
798
+ isActive: true,
799
+ onAcquire,
800
+ prev: this.lastWaiter
801
+ };
802
+ if (this.lastWaiter) {
803
+ this.lastWaiter.next = node;
804
+ this.lastWaiter = node;
805
+ }
806
+ else {
807
+ // First waiter
808
+ this.lastWaiter = this.firstWaiter = node;
809
+ }
810
+ return node;
811
+ }
812
+ deactivateWaiter(waiter) {
813
+ const { prev, next } = waiter;
814
+ waiter.isActive = false;
815
+ if (prev)
816
+ prev.next = next;
817
+ if (next)
818
+ next.prev = prev;
819
+ if (waiter == this.firstWaiter)
820
+ this.firstWaiter = next;
821
+ if (waiter == this.lastWaiter)
822
+ this.lastWaiter = prev;
823
+ }
824
+ acquire(abort) {
825
+ return new Promise((resolve, reject) => {
826
+ function rejectAborted() {
827
+ reject(abort?.reason ?? new Error('Mutex acquire aborted'));
808
828
  }
809
- catch (ex) {
810
- reject(ex);
829
+ if (abort?.aborted) {
830
+ return rejectAborted();
831
+ }
832
+ let holdsMutex = false;
833
+ const markCompleted = () => {
834
+ if (!holdsMutex)
835
+ return;
836
+ holdsMutex = false;
837
+ const waiter = this.firstWaiter;
838
+ if (waiter) {
839
+ this.deactivateWaiter(waiter);
840
+ // Still in critical section, but owned by next waiter now.
841
+ waiter.onAcquire();
842
+ }
843
+ else {
844
+ this.inCriticalSection = false;
845
+ }
846
+ };
847
+ if (!this.inCriticalSection) {
848
+ this.inCriticalSection = true;
849
+ holdsMutex = true;
850
+ return resolve(markCompleted);
851
+ }
852
+ else {
853
+ let node;
854
+ const onAbort = () => {
855
+ abort?.removeEventListener('abort', onAbort);
856
+ if (node.isActive) {
857
+ this.deactivateWaiter(node);
858
+ rejectAborted();
859
+ }
860
+ };
861
+ node = this.addWaiter(() => {
862
+ abort?.removeEventListener('abort', onAbort);
863
+ holdsMutex = true;
864
+ resolve(markCompleted);
865
+ });
866
+ abort?.addEventListener('abort', onAbort);
811
867
  }
812
868
  });
813
- });
869
+ }
870
+ async runExclusive(fn, abort) {
871
+ const returnMutex = await this.acquire(abort);
872
+ try {
873
+ return await fn();
874
+ }
875
+ finally {
876
+ returnMutex();
877
+ }
878
+ }
879
+ }
880
+ function timeoutSignal(timeout) {
881
+ if (timeout == null)
882
+ return;
883
+ if ('timeout' in AbortSignal)
884
+ return AbortSignal.timeout(timeout);
885
+ const controller = new AbortController();
886
+ setTimeout(() => controller.abort(new Error('Timeout waiting for lock')), timeout);
887
+ return controller.signal;
814
888
  }
815
889
 
816
890
  /**
@@ -859,7 +933,7 @@ class AttachmentService {
859
933
  * Executes a callback with exclusive access to the attachment context.
860
934
  */
861
935
  async withContext(callback) {
862
- return mutexRunExclusive(this.mutex, async () => {
936
+ return this.mutex.runExclusive(async () => {
863
937
  return callback(this.context);
864
938
  });
865
939
  }
@@ -895,9 +969,15 @@ class AttachmentQueue {
895
969
  tableName;
896
970
  /** Logger instance for diagnostic information */
897
971
  logger;
898
- /** Interval in milliseconds between periodic sync operations. Default: 30000 (30 seconds) */
972
+ /** Interval in milliseconds between periodic sync operations. Acts as a polling timer to retry
973
+ * failed uploads/downloads, especially after the app goes offline. Default: 30000 (30 seconds) */
899
974
  syncIntervalMs = 30 * 1000;
900
- /** Duration in milliseconds to throttle sync operations */
975
+ /** Throttle duration in milliseconds for the reactive watch query on the attachments table.
976
+ * When attachment records change, a watch query detects the change and triggers a sync.
977
+ * This throttle prevents the sync from firing too rapidly when many changes happen in
978
+ * quick succession (e.g., bulk inserts). This is distinct from syncIntervalMs — it controls
979
+ * how quickly the queue reacts to changes, while syncIntervalMs controls how often it polls
980
+ * for retries. Default: 30 (from DEFAULT_WATCH_THROTTLE_MS) */
901
981
  syncThrottleDuration;
902
982
  /** Whether to automatically download remote attachments. Default: true */
903
983
  downloadAttachments = true;
@@ -921,8 +1001,8 @@ class AttachmentQueue {
921
1001
  * @param options.watchAttachments - Callback for monitoring attachment changes in your data model
922
1002
  * @param options.tableName - Name of the table to store attachment records. Default: 'ps_attachment_queue'
923
1003
  * @param options.logger - Logger instance. Defaults to db.logger
924
- * @param options.syncIntervalMs - Interval between automatic syncs in milliseconds. Default: 30000
925
- * @param options.syncThrottleDuration - Throttle duration for sync operations in milliseconds. Default: 1000
1004
+ * @param options.syncIntervalMs - Periodic polling interval in milliseconds for retrying failed uploads/downloads. Default: 30000
1005
+ * @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
926
1006
  * @param options.downloadAttachments - Whether to automatically download remote attachments. Default: true
927
1007
  * @param options.archivedCacheLimit - Maximum archived attachments before cleanup. Default: 100
928
1008
  */
@@ -8059,7 +8139,7 @@ function requireDist () {
8059
8139
 
8060
8140
  var distExports = requireDist();
8061
8141
 
8062
- var version = "1.49.0";
8142
+ var version = "1.50.0";
8063
8143
  var PACKAGE = {
8064
8144
  version: version};
8065
8145
 
@@ -10916,6 +10996,10 @@ SELECT * FROM crud_entries;
10916
10996
  * Execute a SQL write (INSERT/UPDATE/DELETE) query
10917
10997
  * and optionally return results.
10918
10998
  *
10999
+ * When using the default client-side [JSON-based view system](https://docs.powersync.com/architecture/client-architecture#client-side-schema-and-sqlite-database-structure),
11000
+ * the returned result's `rowsAffected` may be `0` for successful `UPDATE` and `DELETE` statements.
11001
+ * Use a `RETURNING` clause and inspect `result.rows` when you need to confirm which rows changed.
11002
+ *
10919
11003
  * @param sql The SQL query to execute
10920
11004
  * @param parameters Optional array of parameters to bind to the query
10921
11005
  * @returns The query result as an object with structured key-value pairs
@@ -11012,7 +11096,7 @@ SELECT * FROM crud_entries;
11012
11096
  async readTransaction(callback, lockTimeout = DEFAULT_LOCK_TIMEOUT_MS) {
11013
11097
  await this.waitForReady();
11014
11098
  return this.database.readTransaction(async (tx) => {
11015
- const res = await callback({ ...tx });
11099
+ const res = await callback(tx);
11016
11100
  await tx.rollback();
11017
11101
  return res;
11018
11102
  }, { timeoutMs: lockTimeout });
@@ -11989,5 +12073,5 @@ const parseQuery = (query, parameters) => {
11989
12073
  return { sqlStatement, parameters: parameters };
11990
12074
  };
11991
12075
 
11992
- export { ATTACHMENT_TABLE, AbortOperation, AbstractPowerSyncDatabase, AbstractPowerSyncDatabaseOpenFactory, AbstractQueryProcessor, AbstractRemote, AbstractStreamingSyncImplementation, ArrayComparator, AttachmentContext, AttachmentQueue, AttachmentService, AttachmentState, AttachmentTable, BaseObserver, Column, ColumnType, ConnectionClosedError, ConnectionManager, ControlledExecutor, CrudBatch, CrudEntry, CrudTransaction, DBAdapterDefaultMixin, DBGetUtilsDefaultMixin, DEFAULT_CRUD_BATCH_LIMIT, DEFAULT_CRUD_UPLOAD_THROTTLE_MS, DEFAULT_INDEX_COLUMN_OPTIONS, DEFAULT_INDEX_OPTIONS, DEFAULT_LOCK_TIMEOUT_MS, DEFAULT_POWERSYNC_CLOSE_OPTIONS, DEFAULT_POWERSYNC_DB_OPTIONS, DEFAULT_PRESSURE_LIMITS, DEFAULT_REMOTE_LOGGER, DEFAULT_REMOTE_OPTIONS, DEFAULT_RETRY_DELAY_MS, DEFAULT_ROW_COMPARATOR, DEFAULT_STREAMING_SYNC_OPTIONS, DEFAULT_STREAM_CONNECTION_OPTIONS, DEFAULT_SYNC_CLIENT_IMPLEMENTATION, DEFAULT_TABLE_OPTIONS, DEFAULT_WATCH_QUERY_OPTIONS, DEFAULT_WATCH_THROTTLE_MS, DataStream, DiffTriggerOperation, DifferentialQueryProcessor, EMPTY_DIFFERENTIAL, EncodingType, FalsyComparator, FetchImplementationProvider, FetchStrategy, GetAllQuery, Index, IndexedColumn, InvalidSQLCharacters, LockType, LogLevel, MAX_AMOUNT_OF_COLUMNS, MAX_OP_ID, MEMORY_TRIGGER_CLAIM_MANAGER, OnChangeQueryProcessor, OpType, OpTypeEnum, OplogEntry, PSInternalTable, PowerSyncControlCommand, RowUpdateType, Schema, SqliteBucketStorage, SyncClientImplementation, SyncDataBatch, SyncDataBucket, SyncProgress, SyncStatus, SyncStreamConnectionMethod, SyncingService, Table, TableV2, TriggerManagerImpl, UpdateType, UploadQueueStats, WatchedQueryListenerEvent, attachmentFromSql, column, compilableQueryWatch, createBaseLogger, createLogger, extractTableUpdates, isBatchedUpdateNotification, isContinueCheckpointRequest, isDBAdapter, isPowerSyncDatabaseOptionsWithSettings, isSQLOpenFactory, isSQLOpenOptions, isStreamingKeepalive, isStreamingSyncCheckpoint, isStreamingSyncCheckpointComplete, isStreamingSyncCheckpointDiff, isStreamingSyncCheckpointPartiallyComplete, isStreamingSyncData, isSyncNewCheckpointRequest, mutexRunExclusive, parseQuery, runOnSchemaChange, sanitizeSQL, sanitizeUUID };
12076
+ export { ATTACHMENT_TABLE, AbortOperation, AbstractPowerSyncDatabase, AbstractPowerSyncDatabaseOpenFactory, AbstractQueryProcessor, AbstractRemote, AbstractStreamingSyncImplementation, ArrayComparator, AttachmentContext, AttachmentQueue, AttachmentService, AttachmentState, AttachmentTable, BaseObserver, Column, ColumnType, ConnectionClosedError, ConnectionManager, ControlledExecutor, CrudBatch, CrudEntry, CrudTransaction, DBAdapterDefaultMixin, DBGetUtilsDefaultMixin, DEFAULT_CRUD_BATCH_LIMIT, DEFAULT_CRUD_UPLOAD_THROTTLE_MS, DEFAULT_INDEX_COLUMN_OPTIONS, DEFAULT_INDEX_OPTIONS, DEFAULT_LOCK_TIMEOUT_MS, DEFAULT_POWERSYNC_CLOSE_OPTIONS, DEFAULT_POWERSYNC_DB_OPTIONS, DEFAULT_PRESSURE_LIMITS, DEFAULT_REMOTE_LOGGER, DEFAULT_REMOTE_OPTIONS, DEFAULT_RETRY_DELAY_MS, DEFAULT_ROW_COMPARATOR, DEFAULT_STREAMING_SYNC_OPTIONS, DEFAULT_STREAM_CONNECTION_OPTIONS, DEFAULT_SYNC_CLIENT_IMPLEMENTATION, DEFAULT_TABLE_OPTIONS, DEFAULT_WATCH_QUERY_OPTIONS, DEFAULT_WATCH_THROTTLE_MS, DataStream, DiffTriggerOperation, DifferentialQueryProcessor, EMPTY_DIFFERENTIAL, EncodingType, FalsyComparator, FetchImplementationProvider, FetchStrategy, GetAllQuery, Index, IndexedColumn, InvalidSQLCharacters, LockType, LogLevel, MAX_AMOUNT_OF_COLUMNS, MAX_OP_ID, MEMORY_TRIGGER_CLAIM_MANAGER, Mutex, OnChangeQueryProcessor, OpType, OpTypeEnum, OplogEntry, PSInternalTable, PowerSyncControlCommand, RowUpdateType, Schema, SqliteBucketStorage, SyncClientImplementation, SyncDataBatch, SyncDataBucket, SyncProgress, SyncStatus, SyncStreamConnectionMethod, SyncingService, Table, TableV2, TriggerManagerImpl, UpdateType, UploadQueueStats, WatchedQueryListenerEvent, attachmentFromSql, column, compilableQueryWatch, createBaseLogger, createLogger, extractTableUpdates, isBatchedUpdateNotification, isContinueCheckpointRequest, isDBAdapter, isPowerSyncDatabaseOptionsWithSettings, isSQLOpenFactory, isSQLOpenOptions, isStreamingKeepalive, isStreamingSyncCheckpoint, isStreamingSyncCheckpointComplete, isStreamingSyncCheckpointDiff, isStreamingSyncCheckpointPartiallyComplete, isStreamingSyncData, isSyncNewCheckpointRequest, parseQuery, runOnSchemaChange, sanitizeSQL, sanitizeUUID, timeoutSignal };
11993
12077
  //# sourceMappingURL=bundle.node.mjs.map