@powersync/common 1.57.3 → 1.58.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.
@@ -12,7 +12,7 @@ import {
12
12
  SimpleAsyncIterator,
13
13
  valueResult
14
14
  } from '../../../utils/stream_transform.js';
15
- import { EventQueue } from '../../../utils/async.js';
15
+ import { EventQueue, runWithTimeout } from '../../../utils/async.js';
16
16
 
17
17
  /**
18
18
  * @internal
@@ -53,6 +53,13 @@ export type SyncStreamOptions = {
53
53
  headers?: Record<string, string>;
54
54
  abortSignal: AbortSignal;
55
55
  fetchOptions?: Request;
56
+ /**
57
+ * How long to wait for the response to start. Without it, only {@link SyncStreamOptions.abortSignal} ends a pending
58
+ * request.
59
+ *
60
+ * Ignored for WebSocket connections, which have their own timeout.
61
+ */
62
+ connectTimeoutMs?: number;
56
63
  };
57
64
 
58
65
  /**
@@ -269,14 +276,15 @@ export abstract class AbstractRemote {
269
276
  return res.json();
270
277
  }
271
278
 
272
- async get(path: string, headers?: Record<string, string>): Promise<any> {
279
+ async get(path: string, headers?: Record<string, string>, signal?: AbortSignal): Promise<any> {
273
280
  const request = await this.buildRequest(path);
274
281
  const res = await this.fetch(request.url, {
275
282
  method: 'GET',
276
283
  headers: {
277
284
  ...headers,
278
285
  ...request.headers
279
- }
286
+ },
287
+ signal
280
288
  });
281
289
 
282
290
  if (res.status === 401) {
@@ -339,10 +347,13 @@ export abstract class AbstractRemote {
339
347
  }
340
348
  });
341
349
  let didClose = false;
342
- let connectionEstablished = false;
343
350
  let pendingEventsCount = syncQueueRequestSize;
344
351
  let res: Requestable | null = null;
345
352
 
353
+ // Function to reject the promise returned by this method. Set to null while initializing the socket, and after the
354
+ // promise was resolved.
355
+ let rejectPendingQueue: ((e: Error) => void) | null = null;
356
+
346
357
  const abortRequest = () => {
347
358
  if (didClose) {
348
359
  return;
@@ -359,6 +370,11 @@ export abstract class AbstractRemote {
359
370
  rsocket.close();
360
371
  }
361
372
 
373
+ if (rejectPendingQueue) {
374
+ rejectPendingQueue(new Error('Connection aborted'));
375
+ rejectPendingQueue = null;
376
+ }
377
+
362
378
  // Send a bogus event to the queue to ensure a pending listener gets woken up. We check for didClose and would
363
379
  // return a doneEvent.
364
380
  queue.notify(null);
@@ -439,6 +455,8 @@ export abstract class AbstractRemote {
439
455
  rsocket.onClose(() => (rsocket = null));
440
456
 
441
457
  return await new Promise((resolve, reject) => {
458
+ rejectPendingQueue = reject;
459
+
442
460
  const queueAsIterator: SimpleAsyncIterator<Uint8Array> = {
443
461
  next: async () => {
444
462
  if (didClose) return doneResult;
@@ -481,14 +499,15 @@ export abstract class AbstractRemote {
481
499
  // Close the downstream stream as well - this will close the RSocket connection and WebSocket
482
500
  abortRequest();
483
501
  // Handles cases where the connection failed e.g. auth error or connection error
484
- if (!connectionEstablished) {
502
+ if (rejectPendingQueue) {
485
503
  reject(e);
504
+ rejectPendingQueue = null;
486
505
  }
487
506
  },
488
507
  onNext: (payload) => {
489
508
  // The connection is active
490
- if (!connectionEstablished) {
491
- connectionEstablished = true;
509
+ if (rejectPendingQueue) {
510
+ rejectPendingQueue = null;
492
511
  resolve(queueAsIterator);
493
512
  }
494
513
  const { data } = payload;
@@ -504,6 +523,13 @@ export abstract class AbstractRemote {
504
523
  requestMore();
505
524
  },
506
525
  onComplete: () => {
526
+ console.log('onComplete', rejectPendingQueue);
527
+ if (rejectPendingQueue) {
528
+ // Closed without ever emitting an event? Still emit an empty queue.
529
+ rejectPendingQueue = null;
530
+ resolve(queueAsIterator);
531
+ }
532
+
507
533
  abortRequest(); // this will also emit a done event
508
534
  },
509
535
  onExtension: () => {}
@@ -531,7 +557,7 @@ export abstract class AbstractRemote {
531
557
  protected async fetchStreamRaw(
532
558
  options: SyncStreamOptions
533
559
  ): Promise<{ isBson: boolean; stream: SimpleAsyncIterator<Uint8Array> }> {
534
- const { data, path, headers, abortSignal } = options;
560
+ const { data, path, headers, abortSignal, connectTimeoutMs } = options;
535
561
  const request = await this.buildRequest(path);
536
562
 
537
563
  /**
@@ -571,19 +597,25 @@ export abstract class AbstractRemote {
571
597
  const ndJson = 'application/x-ndjson';
572
598
  const bson = 'application/vnd.powersync.bson-stream';
573
599
 
574
- res = await this.fetch(request.url, {
575
- method: 'POST',
576
- headers: {
577
- ...headers,
578
- ...request.headers,
579
- accept: this.supportsStreamingBinaryResponses ? `${bson};q=0.9,${ndJson};q=0.8` : ndJson
580
- },
581
- body: JSON.stringify(data),
582
- signal: controller.signal,
583
- cache: 'no-store',
584
- ...(this.options.fetchOptions ?? {}),
585
- ...options.fetchOptions
586
- });
600
+ const postStream = (signal: AbortSignal) =>
601
+ this.fetch(request.url, {
602
+ method: 'POST',
603
+ headers: {
604
+ ...headers,
605
+ ...request.headers,
606
+ accept: this.supportsStreamingBinaryResponses ? `${bson};q=0.9,${ndJson};q=0.8` : ndJson
607
+ },
608
+ body: JSON.stringify(data),
609
+ signal,
610
+ cache: 'no-store',
611
+ ...(this.options.fetchOptions ?? {}),
612
+ ...options.fetchOptions
613
+ });
614
+
615
+ // The timeout ends once the response starts, so it never aborts the response body.
616
+ res = await (connectTimeoutMs == null
617
+ ? postStream(controller.signal)
618
+ : runWithTimeout(controller.signal, connectTimeoutMs, 'Sync stream connection', postStream));
587
619
 
588
620
  if (!res.ok || !res.body) {
589
621
  const text = await res.text();
@@ -19,7 +19,7 @@ import {
19
19
  SimpleAsyncIterator,
20
20
  valueResult
21
21
  } from '../../../utils/stream_transform.js';
22
- import { asyncNotifier } from '../../../utils/async.js';
22
+ import { asyncNotifier, runWithTimeout } from '../../../utils/async.js';
23
23
  import { StreamingSyncRequestParameterType } from './JsonValue.js';
24
24
 
25
25
  /**
@@ -161,6 +161,17 @@ export interface BaseConnectionOptions {
161
161
  */
162
162
  includeDefaultStreams?: boolean;
163
163
 
164
+ /**
165
+ * How long to wait for the PowerSync Service to respond, in milliseconds. This defaults to 30 seconds.
166
+ *
167
+ * For checkpoint requests, this limits the whole request. For the sync stream over HTTP, this limits the time until
168
+ * the response starts, not how long the stream stays open. WebSocket connections use their own timeouts and ignore
169
+ * this option.
170
+ *
171
+ * A request that takes longer fails and is retried after {@link AdditionalConnectionOptions.retryDelayMs}.
172
+ */
173
+ connectTimeoutMs?: number;
174
+
164
175
  /**
165
176
  * The serialized schema - mainly used to forward information about raw tables to the sync client.
166
177
  */
@@ -201,7 +212,7 @@ export interface StreamingSyncImplementation
201
212
  * @throws if not connected or if abort is not controlled internally
202
213
  */
203
214
  disconnect(): Promise<void>;
204
- getWriteCheckpoint: () => Promise<string>;
215
+ getWriteCheckpoint: (abort?: AbortSignal) => Promise<string>;
205
216
  isConnected: boolean;
206
217
  syncStatus: SyncStatus;
207
218
  triggerCrudUpload: () => void;
@@ -244,7 +255,8 @@ export const DEFAULT_STREAM_CONNECTION_OPTIONS: RequiredPowerSyncConnectionOptio
244
255
  fetchStrategy: FetchStrategy.Buffered,
245
256
  params: {},
246
257
  serializedSchema: undefined,
247
- includeDefaultStreams: true
258
+ includeDefaultStreams: true,
259
+ connectTimeoutMs: 30_000
248
260
  };
249
261
 
250
262
  /**
@@ -270,6 +282,7 @@ export abstract class AbstractStreamingSyncImplementation
270
282
  private activeStreams: SubscribedStream[];
271
283
  private connectionMayHaveChanged = false;
272
284
  private crudUploadNotifier = asyncNotifier();
285
+ private connectTimeoutMs = DEFAULT_STREAM_CONNECTION_OPTIONS.connectTimeoutMs;
273
286
 
274
287
  private notifyCompletedUploads?: () => void;
275
288
  private handleActiveStreamsChange?: () => void;
@@ -355,10 +368,12 @@ export abstract class AbstractStreamingSyncImplementation
355
368
 
356
369
  abstract obtainLock<T>(lockOptions: LockOptions<T>): Promise<T>;
357
370
 
358
- async getWriteCheckpoint(): Promise<string> {
371
+ async getWriteCheckpoint(abort?: AbortSignal): Promise<string> {
359
372
  const clientId = await this.options.adapter.getClientId();
360
373
  let path = `/write-checkpoint2.json?client_id=${clientId}`;
361
- const response = await this.options.remote.get(path);
374
+ const response = await runWithTimeout(abort, this.connectTimeoutMs, 'Write checkpoint request', (signal) =>
375
+ this.options.remote.get(path, undefined, signal)
376
+ );
362
377
  const checkpoint = response['data']['write_checkpoint'] as string;
363
378
  this.logger.debug(`Created write checkpoint: ${checkpoint}`);
364
379
  return checkpoint;
@@ -416,7 +431,7 @@ The next upload iteration will be delayed.`);
416
431
  });
417
432
  } else {
418
433
  // Uploading is completed
419
- const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint());
434
+ const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint(signal));
420
435
  if (neededUpdate) {
421
436
  this.notifyCompletedUploads?.();
422
437
  } else if (checkedCrudItem != null) {
@@ -460,6 +475,7 @@ The next upload iteration will be delayed.`);
460
475
 
461
476
  const controller = new AbortController();
462
477
  this.abortController = controller;
478
+ this.connectTimeoutMs = options?.connectTimeoutMs ?? DEFAULT_STREAM_CONNECTION_OPTIONS.connectTimeoutMs;
463
479
  this.streamingSyncPromise = Promise.all([
464
480
  this.crudUploadLoop(controller.signal).catch((ex) => this.logger.error('Error in crud upload loop', ex)),
465
481
  this.streamingSync(controller.signal, options)
@@ -838,7 +854,8 @@ The next upload iteration will be delayed.`);
838
854
  const syncOptions: SyncStreamOptions = {
839
855
  path: '/sync/stream',
840
856
  abortSignal: signal,
841
- data: startInstruction.EstablishSyncStream.request
857
+ data: startInstruction.EstablishSyncStream.request,
858
+ connectTimeoutMs: resolvedOptions.connectTimeoutMs
842
859
  };
843
860
 
844
861
  controlInvocations = injectable(
@@ -183,3 +183,39 @@ export class EventQueue<T> {
183
183
  };
184
184
  }
185
185
  }
186
+
187
+ /**
188
+ * Runs `action` with a signal that aborts once `signal` aborts or after `timeoutMs`, whichever comes first.
189
+ *
190
+ * @param description Names the operation in the error thrown when it times out.
191
+ */
192
+ export async function runWithTimeout<T>(
193
+ signal: AbortSignal | undefined,
194
+ timeoutMs: number,
195
+ description: string,
196
+ action: (signal: AbortSignal) => Promise<T>
197
+ ): Promise<T> {
198
+ const controller = new AbortController();
199
+ const timeoutError = new Error(`${description} timed out after ${timeoutMs}ms`);
200
+ const onAbort = () => controller.abort(signal?.reason);
201
+
202
+ if (signal?.aborted) {
203
+ onAbort();
204
+ } else {
205
+ signal?.addEventListener('abort', onAbort, { once: true });
206
+ }
207
+ const timeout = setTimeout(() => controller.abort(timeoutError), timeoutMs);
208
+
209
+ try {
210
+ return await action(controller.signal);
211
+ } catch (error) {
212
+ // Some fetch implementations reject with a generic abort error instead of the signal's reason.
213
+ if (controller.signal.reason === timeoutError) {
214
+ throw timeoutError;
215
+ }
216
+ throw error;
217
+ } finally {
218
+ clearTimeout(timeout);
219
+ signal?.removeEventListener('abort', onAbort);
220
+ }
221
+ }