@powersync/common 1.38.1 → 1.40.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.
@@ -2,7 +2,6 @@ import { Mutex } from 'async-mutex';
2
2
  import { EventIterator } from 'event-iterator';
3
3
  import Logger from 'js-logger';
4
4
  import { isBatchedUpdateNotification } from '../db/DBAdapter.js';
5
- import { FULL_SYNC_PRIORITY } from '../db/crud/SyncProgress.js';
6
5
  import { SyncStatus } from '../db/crud/SyncStatus.js';
7
6
  import { UploadQueueStats } from '../db/crud/UploadQueueStatus.js';
8
7
  import { BaseObserver } from '../utils/BaseObserver.js';
@@ -19,6 +18,7 @@ import { DEFAULT_CRUD_UPLOAD_THROTTLE_MS, DEFAULT_RETRY_DELAY_MS } from './sync/
19
18
  import { TriggerManagerImpl } from './triggers/TriggerManagerImpl.js';
20
19
  import { DEFAULT_WATCH_THROTTLE_MS } from './watched/WatchedQuery.js';
21
20
  import { OnChangeQueryProcessor } from './watched/processors/OnChangeQueryProcessor.js';
21
+ import { coreStatusToJs } from './sync/stream/core-instruction.js';
22
22
  const POWERSYNC_TABLE_MATCH = /(^ps_data__|^ps_data_local__)/;
23
23
  const DEFAULT_DISCONNECT_CLEAR_OPTIONS = {
24
24
  clearLocal: true
@@ -59,9 +59,26 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
59
59
  bucketStorageAdapter;
60
60
  _isReadyPromise;
61
61
  connectionManager;
62
+ subscriptions;
62
63
  get syncStreamImplementation() {
63
64
  return this.connectionManager.syncStreamImplementation;
64
65
  }
66
+ /**
67
+ * The connector used to connect to the PowerSync service.
68
+ *
69
+ * @returns The connector used to connect to the PowerSync service or null if `connect()` has not been called.
70
+ */
71
+ get connector() {
72
+ return this.connectionManager.connector;
73
+ }
74
+ /**
75
+ * The resolved connection options used to connect to the PowerSync service.
76
+ *
77
+ * @returns The resolved connection options used to connect to the PowerSync service or null if `connect()` has not been called.
78
+ */
79
+ get connectionOptions() {
80
+ return this.connectionManager.connectionOptions;
81
+ }
65
82
  _schema;
66
83
  _database;
67
84
  runExclusiveMutex;
@@ -100,6 +117,15 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
100
117
  this.sdkVersion = '';
101
118
  this.runExclusiveMutex = new Mutex();
102
119
  // Start async init
120
+ this.subscriptions = {
121
+ firstStatusMatching: (predicate, abort) => this.waitForStatus(predicate, abort),
122
+ resolveOfflineSyncStatus: () => this.resolveOfflineSyncStatus(),
123
+ rustSubscriptionsCommand: async (payload) => {
124
+ await this.writeTransaction((tx) => {
125
+ return tx.execute('select powersync_control(?,?)', ['subscriptions', JSON.stringify(payload)]);
126
+ });
127
+ }
128
+ };
103
129
  this.connectionManager = new ConnectionManager({
104
130
  createSyncImplementation: async (connector, options) => {
105
131
  await this.waitForReady();
@@ -176,22 +202,33 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
176
202
  const statusMatches = priority === undefined
177
203
  ? (status) => status.hasSynced
178
204
  : (status) => status.statusForPriority(priority).hasSynced;
179
- if (statusMatches(this.currentStatus)) {
205
+ return this.waitForStatus(statusMatches, signal);
206
+ }
207
+ /**
208
+ * Waits for the first sync status for which the `status` callback returns a truthy value.
209
+ */
210
+ async waitForStatus(predicate, signal) {
211
+ if (predicate(this.currentStatus)) {
180
212
  return;
181
213
  }
182
214
  return new Promise((resolve) => {
183
215
  const dispose = this.registerListener({
184
216
  statusChanged: (status) => {
185
- if (statusMatches(status)) {
186
- dispose();
187
- resolve();
217
+ if (predicate(status)) {
218
+ abort();
188
219
  }
189
220
  }
190
221
  });
191
- signal?.addEventListener('abort', () => {
222
+ function abort() {
192
223
  dispose();
193
224
  resolve();
194
- });
225
+ }
226
+ if (signal?.aborted) {
227
+ abort();
228
+ }
229
+ else {
230
+ signal?.addEventListener('abort', abort);
231
+ }
195
232
  });
196
233
  }
197
234
  /**
@@ -203,7 +240,7 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
203
240
  await this.bucketStorageAdapter.init();
204
241
  await this._loadVersion();
205
242
  await this.updateSchema(this.options.schema);
206
- await this.updateHasSynced();
243
+ await this.resolveOfflineSyncStatus();
207
244
  await this.database.execute('PRAGMA RECURSIVE_TRIGGERS=TRUE');
208
245
  this.ready = true;
209
246
  this.iterateListeners((cb) => cb.initialized?.());
@@ -230,26 +267,12 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
230
267
  throw new Error(`Unsupported powersync extension version. Need >=0.4.5 <1.0.0, got: ${this.sdkVersion}`);
231
268
  }
232
269
  }
233
- async updateHasSynced() {
234
- const result = await this.database.getAll('SELECT priority, last_synced_at FROM ps_sync_state ORDER BY priority DESC');
235
- let lastCompleteSync;
236
- const priorityStatusEntries = [];
237
- for (const { priority, last_synced_at } of result) {
238
- const parsedDate = new Date(last_synced_at + 'Z');
239
- if (priority == FULL_SYNC_PRIORITY) {
240
- // This lowest-possible priority represents a complete sync.
241
- lastCompleteSync = parsedDate;
242
- }
243
- else {
244
- priorityStatusEntries.push({ priority, hasSynced: true, lastSyncedAt: parsedDate });
245
- }
246
- }
247
- const hasSynced = lastCompleteSync != null;
270
+ async resolveOfflineSyncStatus() {
271
+ const result = await this.database.get('SELECT powersync_offline_sync_status() as r');
272
+ const parsed = JSON.parse(result.r);
248
273
  const updatedStatus = new SyncStatus({
249
274
  ...this.currentStatus.toJSON(),
250
- hasSynced,
251
- priorityStatusEntries,
252
- lastSyncedAt: lastCompleteSync
275
+ ...coreStatusToJs(parsed)
253
276
  });
254
277
  if (!updatedStatus.isEqual(this.currentStatus)) {
255
278
  this.currentStatus = updatedStatus;
@@ -346,6 +369,17 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
346
369
  this.currentStatus = new SyncStatus({});
347
370
  this.iterateListeners((l) => l.statusChanged?.(this.currentStatus));
348
371
  }
372
+ /**
373
+ * Create a sync stream to query its status or to subscribe to it.
374
+ *
375
+ * @param name The name of the stream to subscribe to.
376
+ * @param params Optional parameters for the stream subscription.
377
+ * @returns A {@link SyncStream} instance that can be subscribed to.
378
+ * @experimental Sync streams are currently in alpha.
379
+ */
380
+ syncStream(name, params) {
381
+ return this.connectionManager.stream(this.subscriptions, name, params ?? null);
382
+ }
349
383
  /**
350
384
  * Close the database, releasing resources.
351
385
  *
@@ -1,7 +1,9 @@
1
1
  import { ILogger } from 'js-logger';
2
2
  import { BaseListener, BaseObserver } from '../utils/BaseObserver.js';
3
3
  import { PowerSyncBackendConnector } from './connection/PowerSyncBackendConnector.js';
4
- import { InternalConnectionOptions, StreamingSyncImplementation } from './sync/stream/AbstractStreamingSyncImplementation.js';
4
+ import { AdditionalConnectionOptions, InternalConnectionOptions, StreamingSyncImplementation, SubscribedStream } from './sync/stream/AbstractStreamingSyncImplementation.js';
5
+ import { SyncStream } from './sync/sync-streams.js';
6
+ import { SyncStatus } from '../db/crud/SyncStatus.js';
5
7
  /**
6
8
  * @internal
7
9
  */
@@ -13,11 +15,24 @@ export interface ConnectionManagerSyncImplementationResult {
13
15
  */
14
16
  onDispose: () => Promise<void> | void;
15
17
  }
18
+ /**
19
+ * The subset of {@link AbstractStreamingSyncImplementationOptions} managed by the connection manager.
20
+ *
21
+ * @internal
22
+ */
23
+ export interface CreateSyncImplementationOptions extends AdditionalConnectionOptions {
24
+ subscriptions: SubscribedStream[];
25
+ }
26
+ export interface InternalSubscriptionAdapter {
27
+ firstStatusMatching(predicate: (status: SyncStatus) => any, abort?: AbortSignal): Promise<void>;
28
+ resolveOfflineSyncStatus(): Promise<void>;
29
+ rustSubscriptionsCommand(payload: any): Promise<void>;
30
+ }
16
31
  /**
17
32
  * @internal
18
33
  */
19
34
  export interface ConnectionManagerOptions {
20
- createSyncImplementation(connector: PowerSyncBackendConnector, options: InternalConnectionOptions): Promise<ConnectionManagerSyncImplementationResult>;
35
+ createSyncImplementation(connector: PowerSyncBackendConnector, options: CreateSyncImplementationOptions): Promise<ConnectionManagerSyncImplementationResult>;
21
36
  logger: ILogger;
22
37
  }
23
38
  type StoredConnectionOptions = {
@@ -63,7 +78,15 @@ export declare class ConnectionManager extends BaseObserver<ConnectionManagerLis
63
78
  * is disposed.
64
79
  */
65
80
  protected syncDisposer: (() => Promise<void> | void) | null;
81
+ /**
82
+ * Subscriptions managed in this connection manager.
83
+ *
84
+ * On the web, these local subscriptions are merged across tabs by a shared worker.
85
+ */
86
+ private locallyActiveSubscriptions;
66
87
  constructor(options: ConnectionManagerOptions);
88
+ get connector(): PowerSyncBackendConnector | null;
89
+ get connectionOptions(): InternalConnectionOptions | null;
67
90
  get logger(): ILogger;
68
91
  close(): Promise<void>;
69
92
  connect(connector: PowerSyncBackendConnector, options: InternalConnectionOptions): Promise<void>;
@@ -76,5 +99,14 @@ export declare class ConnectionManager extends BaseObserver<ConnectionManagerLis
76
99
  disconnect(): Promise<void>;
77
100
  protected disconnectInternal(): Promise<void>;
78
101
  protected performDisconnect(): Promise<void>;
102
+ stream(adapter: InternalSubscriptionAdapter, name: string, parameters: Record<string, any> | null): SyncStream;
103
+ /**
104
+ * @internal exposed for testing
105
+ */
106
+ get activeStreams(): {
107
+ name: string;
108
+ params: Record<string, any> | null;
109
+ }[];
110
+ private subscriptionsMayHaveChanged;
79
111
  }
80
112
  export {};
@@ -32,6 +32,12 @@ export class ConnectionManager extends BaseObserver {
32
32
  * is disposed.
33
33
  */
34
34
  syncDisposer;
35
+ /**
36
+ * Subscriptions managed in this connection manager.
37
+ *
38
+ * On the web, these local subscriptions are merged across tabs by a shared worker.
39
+ */
40
+ locallyActiveSubscriptions = new Map();
35
41
  constructor(options) {
36
42
  super();
37
43
  this.options = options;
@@ -42,6 +48,12 @@ export class ConnectionManager extends BaseObserver {
42
48
  this.syncStreamImplementation = null;
43
49
  this.syncDisposer = null;
44
50
  }
51
+ get connector() {
52
+ return this.pendingConnectionOptions?.connector ?? null;
53
+ }
54
+ get connectionOptions() {
55
+ return this.pendingConnectionOptions?.options ?? null;
56
+ }
45
57
  get logger() {
46
58
  return this.options.logger;
47
59
  }
@@ -55,7 +67,7 @@ export class ConnectionManager extends BaseObserver {
55
67
  // Update pending options to the latest values
56
68
  this.pendingConnectionOptions = {
57
69
  connector,
58
- options: options ?? {}
70
+ options
59
71
  };
60
72
  // Disconnecting here provides aborting in progress connection attempts.
61
73
  // The connectInternal method will clear pending options once it starts connecting (with the options).
@@ -114,7 +126,10 @@ export class ConnectionManager extends BaseObserver {
114
126
  const { connector, options } = this.pendingConnectionOptions;
115
127
  appliedOptions = options;
116
128
  this.pendingConnectionOptions = null;
117
- const { sync, onDispose } = await this.options.createSyncImplementation(connector, options);
129
+ const { sync, onDispose } = await this.options.createSyncImplementation(connector, {
130
+ subscriptions: this.activeStreams,
131
+ ...options
132
+ });
118
133
  this.iterateListeners((l) => l.syncStreamCreated?.(sync));
119
134
  this.syncStreamImplementation = sync;
120
135
  this.syncDisposer = onDispose;
@@ -171,4 +186,108 @@ export class ConnectionManager extends BaseObserver {
171
186
  await sync?.dispose();
172
187
  await disposer?.();
173
188
  }
189
+ stream(adapter, name, parameters) {
190
+ const desc = { name, parameters };
191
+ const waitForFirstSync = (abort) => {
192
+ return adapter.firstStatusMatching((s) => s.forStream(desc)?.subscription.hasSynced, abort);
193
+ };
194
+ return {
195
+ ...desc,
196
+ subscribe: async (options) => {
197
+ // NOTE: We also run this command if a subscription already exists, because this increases the expiry date
198
+ // (relevant if the app is closed before connecting again, where the last subscribe call determines the ttl).
199
+ await adapter.rustSubscriptionsCommand({
200
+ subscribe: {
201
+ stream: {
202
+ name,
203
+ params: parameters
204
+ },
205
+ ttl: options?.ttl,
206
+ priority: options?.priority
207
+ }
208
+ });
209
+ if (!this.syncStreamImplementation) {
210
+ // We're not connected. So, update the offline sync status to reflect the new subscription.
211
+ // (With an active iteration, the sync client would include it in its state).
212
+ await adapter.resolveOfflineSyncStatus();
213
+ }
214
+ const key = `${name}|${JSON.stringify(parameters)}`;
215
+ let subscription = this.locallyActiveSubscriptions.get(key);
216
+ if (subscription == null) {
217
+ const clearSubscription = () => {
218
+ this.locallyActiveSubscriptions.delete(key);
219
+ this.subscriptionsMayHaveChanged();
220
+ };
221
+ subscription = new ActiveSubscription(name, parameters, this.logger, waitForFirstSync, clearSubscription);
222
+ this.locallyActiveSubscriptions.set(key, subscription);
223
+ this.subscriptionsMayHaveChanged();
224
+ }
225
+ return new SyncStreamSubscriptionHandle(subscription);
226
+ },
227
+ unsubscribeAll: async () => {
228
+ await adapter.rustSubscriptionsCommand({ unsubscribe: { name, params: parameters } });
229
+ this.subscriptionsMayHaveChanged();
230
+ }
231
+ };
232
+ }
233
+ /**
234
+ * @internal exposed for testing
235
+ */
236
+ get activeStreams() {
237
+ return [...this.locallyActiveSubscriptions.values()].map((a) => ({ name: a.name, params: a.parameters }));
238
+ }
239
+ subscriptionsMayHaveChanged() {
240
+ this.syncStreamImplementation?.updateSubscriptions(this.activeStreams);
241
+ }
242
+ }
243
+ class ActiveSubscription {
244
+ name;
245
+ parameters;
246
+ logger;
247
+ waitForFirstSync;
248
+ clearSubscription;
249
+ refcount = 0;
250
+ constructor(name, parameters, logger, waitForFirstSync, clearSubscription) {
251
+ this.name = name;
252
+ this.parameters = parameters;
253
+ this.logger = logger;
254
+ this.waitForFirstSync = waitForFirstSync;
255
+ this.clearSubscription = clearSubscription;
256
+ }
257
+ decrementRefCount() {
258
+ this.refcount--;
259
+ if (this.refcount == 0) {
260
+ this.clearSubscription();
261
+ }
262
+ }
263
+ }
264
+ class SyncStreamSubscriptionHandle {
265
+ subscription;
266
+ active = true;
267
+ constructor(subscription) {
268
+ this.subscription = subscription;
269
+ subscription.refcount++;
270
+ _finalizer?.register(this, subscription);
271
+ }
272
+ get name() {
273
+ return this.subscription.name;
274
+ }
275
+ get parameters() {
276
+ return this.subscription.parameters;
277
+ }
278
+ waitForFirstSync(abort) {
279
+ return this.subscription.waitForFirstSync(abort);
280
+ }
281
+ unsubscribe() {
282
+ if (this.active) {
283
+ this.active = false;
284
+ _finalizer?.unregister(this);
285
+ this.subscription.decrementRefCount();
286
+ }
287
+ }
174
288
  }
289
+ const _finalizer = 'FinalizationRegistry' in globalThis
290
+ ? new FinalizationRegistry((sub) => {
291
+ sub.logger.warn(`A subscription to ${sub.name} with params ${JSON.stringify(sub.parameters)} leaked! Please ensure calling unsubscribe() when you don't need a subscription anymore. For global subscriptions, consider storing them in global fields to avoid this warning.`);
292
+ })
293
+ : null;
@@ -10,6 +10,7 @@ export interface Checkpoint {
10
10
  last_op_id: OpId;
11
11
  buckets: BucketChecksum[];
12
12
  write_checkpoint?: string;
13
+ streams?: any[];
13
14
  }
14
15
  export interface BucketState {
15
16
  bucket: string;
@@ -43,6 +44,12 @@ export interface BucketChecksum {
43
44
  * Count of operations - informational only.
44
45
  */
45
46
  count?: number;
47
+ /**
48
+ * The JavaScript client does not use this field, which is why it's defined to be `any`. We rely on the structure of
49
+ * this interface to pass custom `BucketChecksum`s to the Rust client in unit tests, which so all fields need to be
50
+ * present.
51
+ */
52
+ subscriptions?: any;
46
53
  }
47
54
  export declare enum PSInternalTable {
48
55
  DATA = "ps_data",
@@ -57,7 +64,8 @@ export declare enum PowerSyncControlCommand {
57
64
  STOP = "stop",
58
65
  START = "start",
59
66
  NOTIFY_TOKEN_REFRESHED = "refreshed_token",
60
- NOTIFY_CRUD_UPLOAD_COMPLETED = "completed_upload"
67
+ NOTIFY_CRUD_UPLOAD_COMPLETED = "completed_upload",
68
+ UPDATE_SUBSCRIPTIONS = "update_subscriptions"
61
69
  }
62
70
  export interface BucketStorageListener extends BaseListener {
63
71
  crudUpdate: () => void;
@@ -14,4 +14,5 @@ export var PowerSyncControlCommand;
14
14
  PowerSyncControlCommand["START"] = "start";
15
15
  PowerSyncControlCommand["NOTIFY_TOKEN_REFRESHED"] = "refreshed_token";
16
16
  PowerSyncControlCommand["NOTIFY_CRUD_UPLOAD_COMPLETED"] = "completed_upload";
17
+ PowerSyncControlCommand["UPDATE_SUBSCRIPTIONS"] = "update_subscriptions";
17
18
  })(PowerSyncControlCommand || (PowerSyncControlCommand = {}));
@@ -62,8 +62,9 @@ export interface LockOptions<T> {
62
62
  type: LockType;
63
63
  signal?: AbortSignal;
64
64
  }
65
- export interface AbstractStreamingSyncImplementationOptions extends AdditionalConnectionOptions {
65
+ export interface AbstractStreamingSyncImplementationOptions extends RequiredAdditionalConnectionOptions {
66
66
  adapter: BucketStorageAdapter;
67
+ subscriptions: SubscribedStream[];
67
68
  uploadCrud: () => Promise<void>;
68
69
  /**
69
70
  * An identifier for which PowerSync DB this sync implementation is
@@ -115,6 +116,12 @@ export interface BaseConnectionOptions {
115
116
  * These parameters are passed to the sync rules, and will be available under the`user_parameters` object.
116
117
  */
117
118
  params?: Record<string, StreamingSyncRequestParameterType>;
119
+ /**
120
+ * Whether to include streams that have `auto_subscribe: true` in their definition.
121
+ *
122
+ * This defaults to `true`.
123
+ */
124
+ includeDefaultStreams?: boolean;
118
125
  /**
119
126
  * The serialized schema - mainly used to forward information about raw tables to the sync client.
120
127
  */
@@ -135,7 +142,9 @@ export interface AdditionalConnectionOptions {
135
142
  crudUploadThrottleMs?: number;
136
143
  }
137
144
  /** @internal */
138
- export type RequiredAdditionalConnectionOptions = Required<AdditionalConnectionOptions>;
145
+ export interface RequiredAdditionalConnectionOptions extends Required<AdditionalConnectionOptions> {
146
+ subscriptions: SubscribedStream[];
147
+ }
139
148
  export interface StreamingSyncImplementation extends BaseObserverInterface<StreamingSyncImplementationListener>, Disposable {
140
149
  /**
141
150
  * Connects to the sync service
@@ -155,6 +164,7 @@ export interface StreamingSyncImplementation extends BaseObserverInterface<Strea
155
164
  waitForReady(): Promise<void>;
156
165
  waitForStatus(status: SyncStatusOptions): Promise<void>;
157
166
  waitUntilStatusMatches(predicate: (status: SyncStatus) => boolean): Promise<void>;
167
+ updateSubscriptions(subscriptions: SubscribedStream[]): void;
158
168
  }
159
169
  export declare const DEFAULT_CRUD_UPLOAD_THROTTLE_MS = 1000;
160
170
  export declare const DEFAULT_RETRY_DELAY_MS = 5000;
@@ -164,6 +174,10 @@ export declare const DEFAULT_STREAMING_SYNC_OPTIONS: {
164
174
  };
165
175
  export type RequiredPowerSyncConnectionOptions = Required<BaseConnectionOptions>;
166
176
  export declare const DEFAULT_STREAM_CONNECTION_OPTIONS: RequiredPowerSyncConnectionOptions;
177
+ export type SubscribedStream = {
178
+ name: string;
179
+ params: Record<string, any> | null;
180
+ };
167
181
  export declare abstract class AbstractStreamingSyncImplementation extends BaseObserver<StreamingSyncImplementationListener> implements StreamingSyncImplementation {
168
182
  protected _lastSyncedAt: Date | null;
169
183
  protected options: AbstractStreamingSyncImplementationOptions;
@@ -172,8 +186,10 @@ export declare abstract class AbstractStreamingSyncImplementation extends BaseOb
172
186
  protected crudUpdateListener?: () => void;
173
187
  protected streamingSyncPromise?: Promise<void>;
174
188
  protected logger: ILogger;
189
+ private activeStreams;
175
190
  private isUploadingCrud;
176
191
  private notifyCompletedUploads?;
192
+ private handleActiveStreamsChange?;
177
193
  syncStatus: SyncStatus;
178
194
  triggerCrudUpload: () => void;
179
195
  constructor(options: AbstractStreamingSyncImplementationOptions);
@@ -210,11 +226,16 @@ export declare abstract class AbstractStreamingSyncImplementation extends BaseOb
210
226
  * @returns Whether the database is now using the new, fixed subkey format.
211
227
  */
212
228
  private requireKeyFormat;
213
- protected streamingSyncIteration(signal: AbortSignal, options?: PowerSyncConnectionOptions): Promise<void>;
229
+ protected streamingSyncIteration(signal: AbortSignal, options?: PowerSyncConnectionOptions): Promise<RustIterationResult | null>;
214
230
  private legacyStreamingSyncIteration;
215
231
  private rustSyncIteration;
216
232
  private updateSyncStatusForStartingCheckpoint;
217
233
  private applyCheckpoint;
218
234
  protected updateSyncStatus(options: SyncStatusOptions): void;
219
235
  private delayRetry;
236
+ updateSubscriptions(subscriptions: SubscribedStream[]): void;
237
+ }
238
+ interface RustIterationResult {
239
+ immediateRestart: boolean;
220
240
  }
241
+ export {};