@powersync/shared-internals 0.0.0-dev-20260827080125

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 (152) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +5 -0
  3. package/dist/websockets.mjs +7558 -0
  4. package/dist/websockets.mjs.map +1 -0
  5. package/dist/websockets.node.mjs +5189 -0
  6. package/dist/websockets.node.mjs.map +1 -0
  7. package/legacy/sync_protocol.d.ts +103 -0
  8. package/lib/client/BasePowerSyncDatabase.d.ts +156 -0
  9. package/lib/client/BasePowerSyncDatabase.js +654 -0
  10. package/lib/client/BasePowerSyncDatabase.js.map +1 -0
  11. package/lib/client/ConnectionManager.d.ts +120 -0
  12. package/lib/client/ConnectionManager.js +324 -0
  13. package/lib/client/ConnectionManager.js.map +1 -0
  14. package/lib/client/CustomQuery.d.ts +21 -0
  15. package/lib/client/CustomQuery.js +43 -0
  16. package/lib/client/CustomQuery.js.map +1 -0
  17. package/lib/client/sync/CheckpointRequestImpl.d.ts +11 -0
  18. package/lib/client/sync/CheckpointRequestImpl.js +42 -0
  19. package/lib/client/sync/CheckpointRequestImpl.js.map +1 -0
  20. package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +58 -0
  21. package/lib/client/sync/bucket/BucketStorageAdapter.js +47 -0
  22. package/lib/client/sync/bucket/BucketStorageAdapter.js.map +1 -0
  23. package/lib/client/sync/bucket/CrudEntry.d.ts +46 -0
  24. package/lib/client/sync/bucket/CrudEntry.js +60 -0
  25. package/lib/client/sync/bucket/CrudEntry.js.map +1 -0
  26. package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +32 -0
  27. package/lib/client/sync/bucket/SqliteBucketStorage.js +160 -0
  28. package/lib/client/sync/bucket/SqliteBucketStorage.js.map +1 -0
  29. package/lib/client/sync/options.d.ts +9 -0
  30. package/lib/client/sync/options.js +17 -0
  31. package/lib/client/sync/options.js.map +1 -0
  32. package/lib/client/sync/stream/AbstractRemote.d.ts +131 -0
  33. package/lib/client/sync/stream/AbstractRemote.js +270 -0
  34. package/lib/client/sync/stream/AbstractRemote.js.map +1 -0
  35. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +156 -0
  36. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +740 -0
  37. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -0
  38. package/lib/client/sync/stream/CheckpointState.d.ts +44 -0
  39. package/lib/client/sync/stream/CheckpointState.js +106 -0
  40. package/lib/client/sync/stream/CheckpointState.js.map +1 -0
  41. package/lib/client/sync/stream/WebSocketSupport.d.ts +26 -0
  42. package/lib/client/sync/stream/WebSocketSupport.js +198 -0
  43. package/lib/client/sync/stream/WebSocketSupport.js.map +1 -0
  44. package/lib/client/sync/stream/WebsocketClientTransport.d.ts +15 -0
  45. package/lib/client/sync/stream/WebsocketClientTransport.js +62 -0
  46. package/lib/client/sync/stream/WebsocketClientTransport.js.map +1 -0
  47. package/lib/client/sync/stream/core-instruction.d.ts +81 -0
  48. package/lib/client/sync/stream/core-instruction.js +4 -0
  49. package/lib/client/sync/stream/core-instruction.js.map +1 -0
  50. package/lib/client/triggers/MemoryTriggerClaimManager.d.ts +6 -0
  51. package/lib/client/triggers/MemoryTriggerClaimManager.js +21 -0
  52. package/lib/client/triggers/MemoryTriggerClaimManager.js.map +1 -0
  53. package/lib/client/triggers/TriggerManagerImpl.d.ts +68 -0
  54. package/lib/client/triggers/TriggerManagerImpl.js +415 -0
  55. package/lib/client/triggers/TriggerManagerImpl.js.map +1 -0
  56. package/lib/client/watched/AbstractQueryProcessor.d.ts +68 -0
  57. package/lib/client/watched/AbstractQueryProcessor.js +155 -0
  58. package/lib/client/watched/AbstractQueryProcessor.js.map +1 -0
  59. package/lib/client/watched/DifferentialQueryProcessor.d.ts +50 -0
  60. package/lib/client/watched/DifferentialQueryProcessor.js +174 -0
  61. package/lib/client/watched/DifferentialQueryProcessor.js.map +1 -0
  62. package/lib/client/watched/OnChangeQueryProcessor.d.ts +22 -0
  63. package/lib/client/watched/OnChangeQueryProcessor.js +80 -0
  64. package/lib/client/watched/OnChangeQueryProcessor.js.map +1 -0
  65. package/lib/client/watched/WatchedQuery.d.ts +9 -0
  66. package/lib/client/watched/WatchedQuery.js +12 -0
  67. package/lib/client/watched/WatchedQuery.js.map +1 -0
  68. package/lib/constants.d.ts +5 -0
  69. package/lib/constants.js +6 -0
  70. package/lib/constants.js.map +1 -0
  71. package/lib/db/ConnectionClosedError.d.ts +12 -0
  72. package/lib/db/ConnectionClosedError.js +23 -0
  73. package/lib/db/ConnectionClosedError.js.map +1 -0
  74. package/lib/db/crud/SyncProgress.d.ts +10 -0
  75. package/lib/db/crud/SyncProgress.js +33 -0
  76. package/lib/db/crud/SyncProgress.js.map +1 -0
  77. package/lib/db/crud/SyncStatus.d.ts +48 -0
  78. package/lib/db/crud/SyncStatus.js +178 -0
  79. package/lib/db/crud/SyncStatus.js.map +1 -0
  80. package/lib/db/openDatabase.d.ts +7 -0
  81. package/lib/db/openDatabase.js +22 -0
  82. package/lib/db/openDatabase.js.map +1 -0
  83. package/lib/index.d.ts +22 -0
  84. package/lib/index.js +22 -0
  85. package/lib/index.js.map +1 -0
  86. package/lib/utils/AbortOperation.d.ts +11 -0
  87. package/lib/utils/AbortOperation.js +21 -0
  88. package/lib/utils/AbortOperation.js.map +1 -0
  89. package/lib/utils/ControlledExecutor.d.ts +31 -0
  90. package/lib/utils/ControlledExecutor.js +58 -0
  91. package/lib/utils/ControlledExecutor.js.map +1 -0
  92. package/lib/utils/MetaBaseObserver.d.ts +11 -0
  93. package/lib/utils/MetaBaseObserver.js +51 -0
  94. package/lib/utils/MetaBaseObserver.js.map +1 -0
  95. package/lib/utils/async.d.ts +46 -0
  96. package/lib/utils/async.js +147 -0
  97. package/lib/utils/async.js.map +1 -0
  98. package/lib/utils/compatibility.d.ts +8 -0
  99. package/lib/utils/compatibility.js +9 -0
  100. package/lib/utils/compatibility.js.map +1 -0
  101. package/lib/utils/mutex.d.ts +42 -0
  102. package/lib/utils/mutex.js +150 -0
  103. package/lib/utils/mutex.js.map +1 -0
  104. package/lib/utils/parseQuery.d.ts +12 -0
  105. package/lib/utils/parseQuery.js +20 -0
  106. package/lib/utils/parseQuery.js.map +1 -0
  107. package/lib/utils/queue.d.ts +16 -0
  108. package/lib/utils/queue.js +42 -0
  109. package/lib/utils/queue.js.map +1 -0
  110. package/lib/utils/stream_transform.d.ts +42 -0
  111. package/lib/utils/stream_transform.js +227 -0
  112. package/lib/utils/stream_transform.js.map +1 -0
  113. package/lib/version.d.ts +1 -0
  114. package/lib/version.js +4 -0
  115. package/lib/version.js.map +1 -0
  116. package/package.json +68 -0
  117. package/src/client/BasePowerSyncDatabase.ts +898 -0
  118. package/src/client/ConnectionManager.ts +441 -0
  119. package/src/client/CustomQuery.ts +60 -0
  120. package/src/client/sync/CheckpointRequestImpl.ts +54 -0
  121. package/src/client/sync/bucket/BucketStorageAdapter.ts +85 -0
  122. package/src/client/sync/bucket/CrudEntry.ts +116 -0
  123. package/src/client/sync/bucket/SqliteBucketStorage.ts +203 -0
  124. package/src/client/sync/options.ts +25 -0
  125. package/src/client/sync/stream/AbstractRemote.ts +388 -0
  126. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +948 -0
  127. package/src/client/sync/stream/CheckpointState.ts +136 -0
  128. package/src/client/sync/stream/WebSocketSupport.ts +259 -0
  129. package/src/client/sync/stream/WebsocketClientTransport.ts +82 -0
  130. package/src/client/sync/stream/core-instruction.ts +85 -0
  131. package/src/client/triggers/MemoryTriggerClaimManager.ts +25 -0
  132. package/src/client/triggers/TriggerManagerImpl.ts +538 -0
  133. package/src/client/watched/AbstractQueryProcessor.ts +231 -0
  134. package/src/client/watched/DifferentialQueryProcessor.ts +226 -0
  135. package/src/client/watched/OnChangeQueryProcessor.ts +108 -0
  136. package/src/client/watched/WatchedQuery.ts +14 -0
  137. package/src/constants.ts +6 -0
  138. package/src/db/ConnectionClosedError.ts +25 -0
  139. package/src/db/crud/SyncProgress.ts +39 -0
  140. package/src/db/crud/SyncStatus.ts +234 -0
  141. package/src/db/openDatabase.ts +23 -0
  142. package/src/index.ts +24 -0
  143. package/src/utils/AbortOperation.ts +19 -0
  144. package/src/utils/ControlledExecutor.ts +81 -0
  145. package/src/utils/MetaBaseObserver.ts +65 -0
  146. package/src/utils/async.ts +185 -0
  147. package/src/utils/compatibility.ts +9 -0
  148. package/src/utils/mutex.ts +186 -0
  149. package/src/utils/parseQuery.ts +31 -0
  150. package/src/utils/queue.ts +48 -0
  151. package/src/utils/stream_transform.ts +276 -0
  152. package/src/version.ts +3 -0
@@ -0,0 +1,136 @@
1
+ import { BaseListener, BaseObserver } from '@powersync/common';
2
+ import { asyncNotifier, EventQueue } from '../../../utils/async.js';
3
+ import { CoreSyncStatus } from './core-instruction.js';
4
+
5
+ export type CheckpointState =
6
+ | { state: 'pending' }
7
+ | { state: 'disconnected' }
8
+ | { state: 'ready' }
9
+ | { state: 'error'; error: unknown };
10
+
11
+ const pending: CheckpointState = { state: 'pending' };
12
+
13
+ export class CheckpointStateSignals {
14
+ private currentState: CheckpointState = pending;
15
+ private readonly stateChanged = new BaseObserver<CheckpointStateListener>();
16
+
17
+ /**
18
+ * Use to immediately restart another download iteration if it is retry delay when a new checkpoint is requested.
19
+ */
20
+ private waitingForCheckpointsReady = asyncNotifier();
21
+
22
+ private updateState(state: CheckpointState) {
23
+ this.currentState = state;
24
+ this.stateChanged.iterateListeners((l) => l.stateChanged?.());
25
+ }
26
+
27
+ /**
28
+ * Marks the current download iteration as ended, blocking new checkpoint requests until the seed performed in the
29
+ * next iteration.
30
+ */
31
+ downloadIterationEnded() {
32
+ this.updateState(pending);
33
+
34
+ // Checkpoint waiters called after this should be able to resume the download iteration.
35
+ this.waitingForCheckpointsReady = asyncNotifier();
36
+ }
37
+
38
+ /**
39
+ * Marks the sync client as disconnected, failing all outstanding checkpoint requests and preventing new ones.
40
+ */
41
+ disconnected() {
42
+ this.updateState({ state: 'disconnected' });
43
+ }
44
+
45
+ /**
46
+ * Returns a promise that resolves with the abort signal or when we have a waiter wanting to request a checkpoint.
47
+ */
48
+ waitForCheckpointWaiter(signal: AbortSignal) {
49
+ return this.waitingForCheckpointsReady.waitForNotification(signal);
50
+ }
51
+
52
+ markCheckpointsReady(completion: Promise<void>): Promise<void> {
53
+ return completion.then(
54
+ (_) => this.updateState({ state: 'ready' }),
55
+ (error) => {
56
+ this.updateState({ state: 'error', error });
57
+ throw error;
58
+ }
59
+ );
60
+ }
61
+
62
+ /**
63
+ * Waits until a download iteration is active and has seeded the checkpoint state, meaning that checkpoint ids can
64
+ * safely be allocated.
65
+ *
66
+ * @returns Turue if checkpoints are ready, false if aborted.
67
+ */
68
+ async waitForCheckpointRequestsReady(abort: AbortSignal, wakeDownloadLoop = true): Promise<boolean> {
69
+ return new Promise((resolve, reject) => {
70
+ // Resolves the promise from the current state if possible, returning true if it was.
71
+ const handleState = () => {
72
+ const state = this.currentState;
73
+ switch (state.state) {
74
+ case 'disconnected':
75
+ reject(cannotRequestDueToDisconnectedError());
76
+ return true;
77
+ case 'ready':
78
+ resolve(true);
79
+ return true;
80
+ case 'error':
81
+ reject(state.error);
82
+ return true;
83
+ case 'pending': {
84
+ // Wait for the next event.
85
+ if (wakeDownloadLoop) {
86
+ this.waitingForCheckpointsReady.notify();
87
+ }
88
+ return false;
89
+ }
90
+ }
91
+ };
92
+
93
+ if (handleState()) {
94
+ return;
95
+ }
96
+
97
+ let removeListener: () => void;
98
+ let onAbort: () => void;
99
+
100
+ function cleanup() {
101
+ removeListener();
102
+ abort.removeEventListener('abort', onAbort);
103
+ }
104
+
105
+ onAbort = () => {
106
+ resolve(false);
107
+ cleanup();
108
+ };
109
+ removeListener = this.stateChanged.registerListener({
110
+ stateChanged() {
111
+ if (handleState()) {
112
+ cleanup();
113
+ }
114
+ }
115
+ });
116
+ abort.addEventListener('abort', onAbort);
117
+ });
118
+ }
119
+ }
120
+
121
+ interface CheckpointStateListener extends BaseListener {
122
+ stateChanged(): void;
123
+ }
124
+
125
+ export function cannotRequestDueToDisconnectedError(): Error {
126
+ return new Error('Cannot request checkpoints, sync client is disconnected.');
127
+ }
128
+
129
+ export function checkpointRequestsNotEnabledError(): Error {
130
+ return new Error('Connected with legacy checkpoint mode, cannot request checkpoints.');
131
+ }
132
+
133
+ export function isCheckpointRequestApplied(status: CoreSyncStatus | null, requestId: bigint): boolean {
134
+ const applied = status?.internal_last_applied_checkpoint_request_id;
135
+ return applied != null && BigInt(applied) >= requestId;
136
+ }
@@ -0,0 +1,259 @@
1
+ // Note: This file gets bundled as a lazy import, along with all of its dependencies. For this reason, only use type
2
+ // imports and let a caller provide the implementation.
3
+ // An exception is RSocket, which we explicitly want to bundle into this file.
4
+ import type { LogLevels } from '@powersync/common';
5
+ import type { AbstractRemote, PreparedRequest } from './AbstractRemote.js';
6
+ import type { EventQueue } from '../../../utils/async.js';
7
+ import type { AbortOperation } from '../../../utils/AbortOperation.js';
8
+
9
+ // doneResult and valueResult are tiny definitions we can afford to duplicate.
10
+ import { doneResult, type SimpleAsyncIterator, valueResult } from '../../../utils/stream_transform.js';
11
+ import { Requestable, RSocket, RSocketConnector } from 'rsocket-core';
12
+ import { WebsocketClientTransport } from 'rsocket-websocket-client';
13
+
14
+ const SYNC_QUEUE_REQUEST_HIGH_WATER = 10;
15
+ const SYNC_QUEUE_REQUEST_LOW_WATER = 5;
16
+
17
+ // Keep alive message is sent every period
18
+ const KEEP_ALIVE_MS = 20_000;
19
+
20
+ // One message of any type must be received in this period.
21
+ const SOCKET_TIMEOUT_MS = 30_000;
22
+
23
+ // One keepalive message must be received in this period.
24
+ // If there is a backlog of messages (for example on slow connections), keepalive messages could be delayed
25
+ // significantly. Therefore this is longer than the socket timeout.
26
+ const KEEP_ALIVE_LIFETIME_MS = 90_000;
27
+
28
+ /**
29
+ * Symbols from the main module used in WebSockets too. We're passing those from the main module to avoid bundling them
30
+ * again.
31
+ */
32
+ export interface WebSocketSyncStreamPlatform {
33
+ LogLevels: typeof LogLevels;
34
+ EventQueue: typeof EventQueue;
35
+ AbortOperation: typeof AbortOperation;
36
+ }
37
+
38
+ export interface WebSocketSyncStreamOptions {
39
+ remote: AbstractRemote;
40
+ buffered: boolean;
41
+ abortSignal: AbortSignal;
42
+ requestPayload: unknown;
43
+ request: PreparedRequest;
44
+ }
45
+
46
+ export class WebSocketSupport {
47
+ #platform: WebSocketSyncStreamPlatform;
48
+
49
+ constructor(platform: WebSocketSyncStreamPlatform) {
50
+ this.#platform = platform;
51
+ }
52
+
53
+ async webSocketSyncStream({
54
+ remote,
55
+ buffered,
56
+ request,
57
+ abortSignal,
58
+ requestPayload
59
+ }: WebSocketSyncStreamOptions): Promise<SimpleAsyncIterator<Uint8Array>> {
60
+ const mimeType = 'application/json';
61
+ const userAgent = request.userAgent;
62
+
63
+ function toBuffer(js: any): Buffer {
64
+ return Buffer.from(JSON.stringify(js));
65
+ }
66
+
67
+ const syncQueueRequestSize = buffered ? 10 : 1;
68
+
69
+ // While we're connecting (a process that can't be aborted in RSocket), the WebSocket instance to close if we wanted
70
+ // to abort the connection.
71
+ let pendingSocket: WebSocket | null = null;
72
+ let keepAliveTimeout: any;
73
+ let rsocket: RSocket | null = null;
74
+ let paused = false;
75
+ const queue = new this.#platform.EventQueue<Uint8Array | null>({
76
+ eventDelivered: () => {
77
+ if (queue.countOutstandingEvents <= SYNC_QUEUE_REQUEST_LOW_WATER) {
78
+ paused = false;
79
+ requestMore();
80
+ }
81
+ }
82
+ });
83
+ let didClose = false;
84
+ let connectionEstablished = false;
85
+ let pendingEventsCount = syncQueueRequestSize;
86
+ let res: Requestable | null = null;
87
+
88
+ const abortRequest = () => {
89
+ if (didClose) {
90
+ return;
91
+ }
92
+ didClose = true;
93
+
94
+ clearTimeout(keepAliveTimeout);
95
+
96
+ if (pendingSocket) {
97
+ pendingSocket.close();
98
+ }
99
+
100
+ if (rsocket) {
101
+ rsocket.close();
102
+ }
103
+
104
+ // Send a bogus event to the queue to ensure a pending listener gets woken up. We check for didClose and would
105
+ // return a doneEvent.
106
+ queue.notify(null);
107
+ };
108
+
109
+ function push(event: Uint8Array) {
110
+ queue.notify(event);
111
+ if (queue.countOutstandingEvents >= SYNC_QUEUE_REQUEST_HIGH_WATER) {
112
+ paused = true;
113
+ }
114
+ }
115
+
116
+ function requestMore() {
117
+ const delta = syncQueueRequestSize - pendingEventsCount;
118
+ if (!paused && delta > 0) {
119
+ res?.request(delta);
120
+ pendingEventsCount = syncQueueRequestSize;
121
+ }
122
+ }
123
+
124
+ // Handle upstream abort
125
+ if (abortSignal.aborted) {
126
+ throw new this.#platform.AbortOperation('Connection request aborted');
127
+ } else {
128
+ abortSignal.addEventListener('abort', abortRequest);
129
+ }
130
+
131
+ const resetTimeout = () => {
132
+ clearTimeout(keepAliveTimeout);
133
+ keepAliveTimeout = setTimeout(() => {
134
+ remote.logger.log({
135
+ level: this.#platform.LogLevels.error,
136
+ message: `No data received on WebSocket in ${SOCKET_TIMEOUT_MS}ms, closing connection.`
137
+ });
138
+ abortRequest();
139
+ }, SOCKET_TIMEOUT_MS);
140
+ };
141
+ resetTimeout();
142
+
143
+ const connector = new RSocketConnector({
144
+ transport: new WebsocketClientTransport({
145
+ url: request.url,
146
+ wsCreator: (url) => {
147
+ const socket = (pendingSocket = remote.createSocket(url));
148
+
149
+ socket.addEventListener('message', () => {
150
+ resetTimeout();
151
+ });
152
+ return socket;
153
+ }
154
+ }),
155
+ setup: {
156
+ keepAlive: KEEP_ALIVE_MS,
157
+ lifetime: KEEP_ALIVE_LIFETIME_MS,
158
+ dataMimeType: mimeType,
159
+ metadataMimeType: mimeType,
160
+ payload: {
161
+ data: null,
162
+ metadata: toBuffer({
163
+ token: request.headers.Authorization,
164
+ user_agent: userAgent
165
+ })
166
+ }
167
+ }
168
+ });
169
+
170
+ try {
171
+ rsocket = await connector.connect();
172
+ // The connection is established, we no longer need to monitor the initial timeout
173
+ pendingSocket = null;
174
+ } catch (ex) {
175
+ remote.logger.log({ level: this.#platform.LogLevels.error, message: `Failed to connect WebSocket`, error: ex });
176
+ abortRequest();
177
+
178
+ throw ex;
179
+ }
180
+
181
+ resetTimeout();
182
+
183
+ // Helps to prevent double close scenarios
184
+ rsocket.onClose(() => (rsocket = null));
185
+
186
+ return await new Promise((resolve, reject) => {
187
+ const queueAsIterator: SimpleAsyncIterator<Uint8Array> = {
188
+ next: async () => {
189
+ if (didClose) return doneResult;
190
+
191
+ const notification = await queue.waitForEvent(abortSignal);
192
+ if (didClose) {
193
+ return doneResult;
194
+ } else {
195
+ return valueResult(notification!);
196
+ }
197
+ }
198
+ };
199
+
200
+ res = rsocket!.requestStream(
201
+ {
202
+ data: toBuffer(requestPayload),
203
+ metadata: toBuffer({
204
+ path: request.path
205
+ })
206
+ },
207
+ syncQueueRequestSize, // The initial N amount
208
+ {
209
+ onError: (e) => {
210
+ if (e.message.includes('PSYNC_')) {
211
+ if (e.message.includes('PSYNC_S21')) {
212
+ remote.invalidateCredentials();
213
+ }
214
+ } else {
215
+ // Possible that connection is with an older service, always invalidate to be safe
216
+ if (e.message !== 'Closed. ') {
217
+ remote.invalidateCredentials();
218
+ }
219
+ }
220
+
221
+ // Don't log closed as an error
222
+ if (e.message !== 'Closed. ') {
223
+ remote.logger.log({ level: this.#platform.LogLevels.error, message: 'RSocket error', error: e });
224
+ }
225
+ // RSocket will close the RSocket stream automatically
226
+ // Close the downstream stream as well - this will close the RSocket connection and WebSocket
227
+ abortRequest();
228
+ // Handles cases where the connection failed e.g. auth error or connection error
229
+ if (!connectionEstablished) {
230
+ reject(e);
231
+ }
232
+ },
233
+ onNext: (payload) => {
234
+ // The connection is active
235
+ if (!connectionEstablished) {
236
+ connectionEstablished = true;
237
+ resolve(queueAsIterator);
238
+ }
239
+ const { data } = payload;
240
+
241
+ if (data) {
242
+ push(data);
243
+ }
244
+
245
+ // Less events are now pending
246
+ pendingEventsCount--;
247
+
248
+ // Request another event (unless the downstream consumer is paused).
249
+ requestMore();
250
+ },
251
+ onComplete: () => {
252
+ abortRequest(); // this will also emit a done event
253
+ },
254
+ onExtension: () => {}
255
+ }
256
+ );
257
+ });
258
+ }
259
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Adapted from rsocket-websocket-client
3
+ * https://github.com/rsocket/rsocket-js/blob/e224cf379e747c4f1ddc4f2fa111854626cc8575/packages/rsocket-websocket-client/src/WebsocketClientTransport.ts#L17
4
+ * This adds additional error handling for React Native iOS.
5
+ * This particularly adds a close listener to handle cases where the WebSocket
6
+ * connection closes immediately after opening without emitting an error.
7
+ */
8
+ import {
9
+ ClientTransport,
10
+ Closeable,
11
+ Demultiplexer,
12
+ Deserializer,
13
+ DuplexConnection,
14
+ FrameHandler,
15
+ Multiplexer,
16
+ Outbound
17
+ } from 'rsocket-core';
18
+ import { ClientOptions } from 'rsocket-websocket-client';
19
+ import { WebsocketDuplexConnection } from 'rsocket-websocket-client/dist/WebsocketDuplexConnection.js';
20
+
21
+ export class WebsocketClientTransport implements ClientTransport {
22
+ private readonly url: string;
23
+ private readonly factory: (url: string) => WebSocket;
24
+
25
+ constructor(options: ClientOptions) {
26
+ this.url = options.url;
27
+ this.factory = options.wsCreator ?? ((url: string) => new WebSocket(url));
28
+ }
29
+
30
+ connect(
31
+ multiplexerDemultiplexerFactory: (outbound: Outbound & Closeable) => Multiplexer & Demultiplexer & FrameHandler
32
+ ): Promise<DuplexConnection> {
33
+ return new Promise((resolve, reject) => {
34
+ const websocket = this.factory(this.url);
35
+
36
+ websocket.binaryType = 'arraybuffer';
37
+
38
+ let removeListeners: () => void;
39
+
40
+ const openListener = () => {
41
+ removeListeners();
42
+ resolve(new WebsocketDuplexConnection(websocket, new Deserializer(), multiplexerDemultiplexerFactory));
43
+ };
44
+
45
+ const errorListener = (event: Event) => {
46
+ const ev = event as ErrorEvent;
47
+
48
+ removeListeners();
49
+ // We add a default error in that case.
50
+ if (ev.error != null) {
51
+ // undici typically provides an error object
52
+ reject(ev.error);
53
+ } else if (ev.message != null) {
54
+ // React Native typically does not provide an error object, but does provide a message
55
+ reject(new Error(`Failed to create websocket connection: ${ev.message}`));
56
+ } else {
57
+ // Browsers often provide no details at all
58
+ reject(new Error(`Failed to create websocket connection to ${this.url}`));
59
+ }
60
+ };
61
+
62
+ /**
63
+ * In some cases, such as React Native iOS, the WebSocket connection may close immediately after opening
64
+ * without and error. In such cases, we need to handle the close event to reject the promise.
65
+ */
66
+ const closeListener = () => {
67
+ removeListeners();
68
+ reject(new Error('WebSocket connection closed while opening'));
69
+ };
70
+
71
+ removeListeners = () => {
72
+ websocket.removeEventListener('open', openListener);
73
+ websocket.removeEventListener('error', errorListener);
74
+ websocket.removeEventListener('close', closeListener);
75
+ };
76
+
77
+ websocket.addEventListener('open', openListener);
78
+ websocket.addEventListener('error', errorListener);
79
+ websocket.addEventListener('close', closeListener);
80
+ });
81
+ }
82
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * An internal instruction emitted by the sync client in the core extension in response to the JS
3
+ * SDK passing sync data into the extension.
4
+ */
5
+ export type Instruction = InterruptingInstruction | NonInterruptingInstruction;
6
+
7
+ export type InterruptingInstruction =
8
+ | { EstablishSyncStream: EstablishSyncStream }
9
+ | { CloseSyncStream: { hide_disconnect: boolean } };
10
+
11
+ /**
12
+ * An {@link Instruction} that doesn't start or stop a sync iteration.
13
+ */
14
+ export type NonInterruptingInstruction =
15
+ | { LogLine: LogLine }
16
+ | { UpdateSyncStatus: UpdateSyncStatus }
17
+ | { FetchCredentials: FetchCredentials }
18
+ | { FlushFileSystem: any }
19
+ | { DidCompleteSync: any };
20
+
21
+ export interface LogLine {
22
+ severity: 'DEBUG' | 'INFO' | 'WARNING';
23
+ line: string;
24
+ }
25
+
26
+ export interface EstablishSyncStream {
27
+ request: unknown;
28
+ checkpoint_request?: CheckpointRequestPayload;
29
+ }
30
+
31
+ export interface UpdateSyncStatus {
32
+ status: CoreSyncStatus;
33
+ }
34
+
35
+ export interface CoreSyncStatus {
36
+ connected: boolean;
37
+ connecting: boolean;
38
+ priority_status: SyncPriorityStatus[];
39
+ downloading: DownloadProgress | null;
40
+ streams: CoreStreamSubscription[];
41
+ internal_last_applied_checkpoint_request_id?: string;
42
+ }
43
+
44
+ /// An `ActiveStreamSubscription` from the core extension + serialized progress information.
45
+ export interface CoreStreamSubscription {
46
+ progress: { total: number; downloaded: number };
47
+ name: string;
48
+ parameters: any;
49
+ priority: number | null;
50
+ active: boolean;
51
+ is_default: boolean;
52
+ has_explicit_subscription: boolean;
53
+ expires_at: number | null;
54
+ last_synced_at: number | null;
55
+ }
56
+
57
+ export interface SyncPriorityStatus {
58
+ priority: number;
59
+ last_synced_at: number | number;
60
+ has_synced: boolean | null;
61
+ }
62
+
63
+ export interface DownloadProgress {
64
+ buckets: Record<string, BucketProgress>;
65
+ }
66
+
67
+ export interface BucketProgress {
68
+ priority: number;
69
+ at_last: number;
70
+ since_last: number;
71
+ target_count: number;
72
+ }
73
+
74
+ export interface FetchCredentials {
75
+ did_expire: boolean;
76
+ }
77
+
78
+ export interface CheckpointRequestPayload {
79
+ client_id: string;
80
+ checkpoint_request_id: string;
81
+ }
82
+
83
+ export function isInterruptingInstruction(instruction: Instruction): instruction is InterruptingInstruction {
84
+ return 'EstablishSyncStream' in instruction || 'CloseSyncStream' in instruction;
85
+ }
@@ -0,0 +1,25 @@
1
+ import { TriggerClaimManager } from './TriggerManagerImpl.js';
2
+
3
+ const CLAIM_STORE = new Map<string, () => Promise<void>>();
4
+
5
+ /**
6
+ * @internal
7
+ * @experimental
8
+ */
9
+ export const MEMORY_TRIGGER_CLAIM_MANAGER: TriggerClaimManager = {
10
+ async obtainClaim(identifier: string): Promise<() => Promise<void>> {
11
+ if (CLAIM_STORE.has(identifier)) {
12
+ throw new Error(`A claim is already present for ${identifier}`);
13
+ }
14
+ const release = async () => {
15
+ CLAIM_STORE.delete(identifier);
16
+ };
17
+ CLAIM_STORE.set(identifier, release);
18
+
19
+ return release;
20
+ },
21
+
22
+ async checkClaim(identifier: string): Promise<boolean> {
23
+ return CLAIM_STORE.has(identifier);
24
+ }
25
+ };