@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.
- package/LICENSE +201 -0
- package/README.md +5 -0
- package/dist/websockets.mjs +7558 -0
- package/dist/websockets.mjs.map +1 -0
- package/dist/websockets.node.mjs +5189 -0
- package/dist/websockets.node.mjs.map +1 -0
- package/legacy/sync_protocol.d.ts +103 -0
- package/lib/client/BasePowerSyncDatabase.d.ts +156 -0
- package/lib/client/BasePowerSyncDatabase.js +654 -0
- package/lib/client/BasePowerSyncDatabase.js.map +1 -0
- package/lib/client/ConnectionManager.d.ts +120 -0
- package/lib/client/ConnectionManager.js +324 -0
- package/lib/client/ConnectionManager.js.map +1 -0
- package/lib/client/CustomQuery.d.ts +21 -0
- package/lib/client/CustomQuery.js +43 -0
- package/lib/client/CustomQuery.js.map +1 -0
- package/lib/client/sync/CheckpointRequestImpl.d.ts +11 -0
- package/lib/client/sync/CheckpointRequestImpl.js +42 -0
- package/lib/client/sync/CheckpointRequestImpl.js.map +1 -0
- package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +58 -0
- package/lib/client/sync/bucket/BucketStorageAdapter.js +47 -0
- package/lib/client/sync/bucket/BucketStorageAdapter.js.map +1 -0
- package/lib/client/sync/bucket/CrudEntry.d.ts +46 -0
- package/lib/client/sync/bucket/CrudEntry.js +60 -0
- package/lib/client/sync/bucket/CrudEntry.js.map +1 -0
- package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +32 -0
- package/lib/client/sync/bucket/SqliteBucketStorage.js +160 -0
- package/lib/client/sync/bucket/SqliteBucketStorage.js.map +1 -0
- package/lib/client/sync/options.d.ts +9 -0
- package/lib/client/sync/options.js +17 -0
- package/lib/client/sync/options.js.map +1 -0
- package/lib/client/sync/stream/AbstractRemote.d.ts +131 -0
- package/lib/client/sync/stream/AbstractRemote.js +270 -0
- package/lib/client/sync/stream/AbstractRemote.js.map +1 -0
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +156 -0
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +740 -0
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -0
- package/lib/client/sync/stream/CheckpointState.d.ts +44 -0
- package/lib/client/sync/stream/CheckpointState.js +106 -0
- package/lib/client/sync/stream/CheckpointState.js.map +1 -0
- package/lib/client/sync/stream/WebSocketSupport.d.ts +26 -0
- package/lib/client/sync/stream/WebSocketSupport.js +198 -0
- package/lib/client/sync/stream/WebSocketSupport.js.map +1 -0
- package/lib/client/sync/stream/WebsocketClientTransport.d.ts +15 -0
- package/lib/client/sync/stream/WebsocketClientTransport.js +62 -0
- package/lib/client/sync/stream/WebsocketClientTransport.js.map +1 -0
- package/lib/client/sync/stream/core-instruction.d.ts +81 -0
- package/lib/client/sync/stream/core-instruction.js +4 -0
- package/lib/client/sync/stream/core-instruction.js.map +1 -0
- package/lib/client/triggers/MemoryTriggerClaimManager.d.ts +6 -0
- package/lib/client/triggers/MemoryTriggerClaimManager.js +21 -0
- package/lib/client/triggers/MemoryTriggerClaimManager.js.map +1 -0
- package/lib/client/triggers/TriggerManagerImpl.d.ts +68 -0
- package/lib/client/triggers/TriggerManagerImpl.js +415 -0
- package/lib/client/triggers/TriggerManagerImpl.js.map +1 -0
- package/lib/client/watched/AbstractQueryProcessor.d.ts +68 -0
- package/lib/client/watched/AbstractQueryProcessor.js +155 -0
- package/lib/client/watched/AbstractQueryProcessor.js.map +1 -0
- package/lib/client/watched/DifferentialQueryProcessor.d.ts +50 -0
- package/lib/client/watched/DifferentialQueryProcessor.js +174 -0
- package/lib/client/watched/DifferentialQueryProcessor.js.map +1 -0
- package/lib/client/watched/OnChangeQueryProcessor.d.ts +22 -0
- package/lib/client/watched/OnChangeQueryProcessor.js +80 -0
- package/lib/client/watched/OnChangeQueryProcessor.js.map +1 -0
- package/lib/client/watched/WatchedQuery.d.ts +9 -0
- package/lib/client/watched/WatchedQuery.js +12 -0
- package/lib/client/watched/WatchedQuery.js.map +1 -0
- package/lib/constants.d.ts +5 -0
- package/lib/constants.js +6 -0
- package/lib/constants.js.map +1 -0
- package/lib/db/ConnectionClosedError.d.ts +12 -0
- package/lib/db/ConnectionClosedError.js +23 -0
- package/lib/db/ConnectionClosedError.js.map +1 -0
- package/lib/db/crud/SyncProgress.d.ts +10 -0
- package/lib/db/crud/SyncProgress.js +33 -0
- package/lib/db/crud/SyncProgress.js.map +1 -0
- package/lib/db/crud/SyncStatus.d.ts +48 -0
- package/lib/db/crud/SyncStatus.js +178 -0
- package/lib/db/crud/SyncStatus.js.map +1 -0
- package/lib/db/openDatabase.d.ts +7 -0
- package/lib/db/openDatabase.js +22 -0
- package/lib/db/openDatabase.js.map +1 -0
- package/lib/index.d.ts +22 -0
- package/lib/index.js +22 -0
- package/lib/index.js.map +1 -0
- package/lib/utils/AbortOperation.d.ts +11 -0
- package/lib/utils/AbortOperation.js +21 -0
- package/lib/utils/AbortOperation.js.map +1 -0
- package/lib/utils/ControlledExecutor.d.ts +31 -0
- package/lib/utils/ControlledExecutor.js +58 -0
- package/lib/utils/ControlledExecutor.js.map +1 -0
- package/lib/utils/MetaBaseObserver.d.ts +11 -0
- package/lib/utils/MetaBaseObserver.js +51 -0
- package/lib/utils/MetaBaseObserver.js.map +1 -0
- package/lib/utils/async.d.ts +46 -0
- package/lib/utils/async.js +147 -0
- package/lib/utils/async.js.map +1 -0
- package/lib/utils/compatibility.d.ts +8 -0
- package/lib/utils/compatibility.js +9 -0
- package/lib/utils/compatibility.js.map +1 -0
- package/lib/utils/mutex.d.ts +42 -0
- package/lib/utils/mutex.js +150 -0
- package/lib/utils/mutex.js.map +1 -0
- package/lib/utils/parseQuery.d.ts +12 -0
- package/lib/utils/parseQuery.js +20 -0
- package/lib/utils/parseQuery.js.map +1 -0
- package/lib/utils/queue.d.ts +16 -0
- package/lib/utils/queue.js +42 -0
- package/lib/utils/queue.js.map +1 -0
- package/lib/utils/stream_transform.d.ts +42 -0
- package/lib/utils/stream_transform.js +227 -0
- package/lib/utils/stream_transform.js.map +1 -0
- package/lib/version.d.ts +1 -0
- package/lib/version.js +4 -0
- package/lib/version.js.map +1 -0
- package/package.json +68 -0
- package/src/client/BasePowerSyncDatabase.ts +898 -0
- package/src/client/ConnectionManager.ts +441 -0
- package/src/client/CustomQuery.ts +60 -0
- package/src/client/sync/CheckpointRequestImpl.ts +54 -0
- package/src/client/sync/bucket/BucketStorageAdapter.ts +85 -0
- package/src/client/sync/bucket/CrudEntry.ts +116 -0
- package/src/client/sync/bucket/SqliteBucketStorage.ts +203 -0
- package/src/client/sync/options.ts +25 -0
- package/src/client/sync/stream/AbstractRemote.ts +388 -0
- package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +948 -0
- package/src/client/sync/stream/CheckpointState.ts +136 -0
- package/src/client/sync/stream/WebSocketSupport.ts +259 -0
- package/src/client/sync/stream/WebsocketClientTransport.ts +82 -0
- package/src/client/sync/stream/core-instruction.ts +85 -0
- package/src/client/triggers/MemoryTriggerClaimManager.ts +25 -0
- package/src/client/triggers/TriggerManagerImpl.ts +538 -0
- package/src/client/watched/AbstractQueryProcessor.ts +231 -0
- package/src/client/watched/DifferentialQueryProcessor.ts +226 -0
- package/src/client/watched/OnChangeQueryProcessor.ts +108 -0
- package/src/client/watched/WatchedQuery.ts +14 -0
- package/src/constants.ts +6 -0
- package/src/db/ConnectionClosedError.ts +25 -0
- package/src/db/crud/SyncProgress.ts +39 -0
- package/src/db/crud/SyncStatus.ts +234 -0
- package/src/db/openDatabase.ts +23 -0
- package/src/index.ts +24 -0
- package/src/utils/AbortOperation.ts +19 -0
- package/src/utils/ControlledExecutor.ts +81 -0
- package/src/utils/MetaBaseObserver.ts +65 -0
- package/src/utils/async.ts +185 -0
- package/src/utils/compatibility.ts +9 -0
- package/src/utils/mutex.ts +186 -0
- package/src/utils/parseQuery.ts +31 -0
- package/src/utils/queue.ts +48 -0
- package/src/utils/stream_transform.ts +276 -0
- package/src/version.ts +3 -0
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
import { type fetch } from 'cross-fetch';
|
|
2
|
+
import { FetchStrategy, PowerSyncCredentials, LogLevels, PowerSyncLogger } from '@powersync/common';
|
|
3
|
+
|
|
4
|
+
import { AbortOperation } from '../../../utils/AbortOperation.js';
|
|
5
|
+
import {
|
|
6
|
+
doneResult,
|
|
7
|
+
extractBsonObjects,
|
|
8
|
+
extractJsonLines,
|
|
9
|
+
SimpleAsyncIterator
|
|
10
|
+
} from '../../../utils/stream_transform.js';
|
|
11
|
+
import { WebSocketSupport, WebSocketSyncStreamPlatform } from './WebSocketSupport.js';
|
|
12
|
+
import { EventQueue } from '../../../utils/async.js';
|
|
13
|
+
import { POWERSYNC_JS_VERSION } from '../../../version.js';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @internal
|
|
17
|
+
*/
|
|
18
|
+
export type RemoteConnector = {
|
|
19
|
+
fetchCredentials: () => Promise<PowerSyncCredentials | null>;
|
|
20
|
+
invalidateCredentials?: () => void;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const POWERSYNC_TRAILING_SLASH_MATCH = /\/+$/;
|
|
24
|
+
|
|
25
|
+
const webSocketPlatform: WebSocketSyncStreamPlatform = {
|
|
26
|
+
LogLevels,
|
|
27
|
+
EventQueue,
|
|
28
|
+
AbortOperation
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* @internal
|
|
33
|
+
*/
|
|
34
|
+
export type SyncStreamOptions = {
|
|
35
|
+
path: string;
|
|
36
|
+
data: unknown;
|
|
37
|
+
abortSignal: AbortSignal;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* @internal
|
|
42
|
+
*/
|
|
43
|
+
export type FetchImplementation = typeof fetch;
|
|
44
|
+
|
|
45
|
+
export function lazyFetchImplementation(getFetch: () => FetchImplementation): FetchImplementation {
|
|
46
|
+
let resolved: FetchImplementation;
|
|
47
|
+
|
|
48
|
+
return (request) => {
|
|
49
|
+
const fetch = (resolved ??= getFetch());
|
|
50
|
+
return fetch(request);
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface FetchOptions {
|
|
55
|
+
resource: string;
|
|
56
|
+
request: RequestInit;
|
|
57
|
+
expectStreamingResponse: boolean;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* @internal
|
|
62
|
+
*/
|
|
63
|
+
export interface SocketSyncStreamOptions {
|
|
64
|
+
path: string;
|
|
65
|
+
fetchStrategy: FetchStrategy;
|
|
66
|
+
abortSignal: AbortSignal;
|
|
67
|
+
data: unknown;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface PreparedRequest {
|
|
71
|
+
url: string;
|
|
72
|
+
headers: Record<string, string>;
|
|
73
|
+
userAgent: string;
|
|
74
|
+
path: string;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* @internal
|
|
79
|
+
*/
|
|
80
|
+
export abstract class AbstractRemote {
|
|
81
|
+
protected credentials: PowerSyncCredentials | null = null;
|
|
82
|
+
|
|
83
|
+
constructor(
|
|
84
|
+
protected connector: RemoteConnector,
|
|
85
|
+
readonly logger: PowerSyncLogger
|
|
86
|
+
) {}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Sends a request using a suitable `fetch` implementation for the current platform.
|
|
90
|
+
*/
|
|
91
|
+
protected abstract fetch(options: FetchOptions): Promise<Response>;
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Get credentials currently cached, or fetch new credentials if none are
|
|
95
|
+
* available.
|
|
96
|
+
*
|
|
97
|
+
* These credentials may have expired already.
|
|
98
|
+
*/
|
|
99
|
+
async getCredentials(): Promise<PowerSyncCredentials | null> {
|
|
100
|
+
if (this.credentials) {
|
|
101
|
+
return this.credentials;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return this.prefetchCredentials();
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Fetch a new set of credentials and cache it.
|
|
109
|
+
*
|
|
110
|
+
* Until this call succeeds, `getCredentials` will still return the
|
|
111
|
+
* old credentials.
|
|
112
|
+
*
|
|
113
|
+
* This may be called before the current credentials have expired.
|
|
114
|
+
*/
|
|
115
|
+
async prefetchCredentials() {
|
|
116
|
+
this.credentials = await this.fetchCredentials();
|
|
117
|
+
|
|
118
|
+
return this.credentials;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Get credentials for PowerSync.
|
|
123
|
+
*
|
|
124
|
+
* This should always fetch a fresh set of credentials - don't use cached
|
|
125
|
+
* values.
|
|
126
|
+
*/
|
|
127
|
+
async fetchCredentials() {
|
|
128
|
+
const credentials = await this.connector.fetchCredentials();
|
|
129
|
+
if (credentials?.endpoint.match(POWERSYNC_TRAILING_SLASH_MATCH)) {
|
|
130
|
+
throw new Error(
|
|
131
|
+
`A trailing forward slash "/" was found in the fetchCredentials endpoint: "${credentials.endpoint}". Remove the trailing forward slash "/" to fix this error.`
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return credentials;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/***
|
|
139
|
+
* Immediately invalidate credentials.
|
|
140
|
+
*
|
|
141
|
+
* This may be called when the current credentials have expired.
|
|
142
|
+
*/
|
|
143
|
+
invalidateCredentials() {
|
|
144
|
+
this.credentials = null;
|
|
145
|
+
this.connector.invalidateCredentials?.();
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
getUserAgent() {
|
|
149
|
+
return `powersync-js/${POWERSYNC_JS_VERSION}`;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
protected async buildRequest(path: string): Promise<PreparedRequest> {
|
|
153
|
+
const credentials = await this.getCredentials();
|
|
154
|
+
if (credentials != null && (credentials.endpoint == null || credentials.endpoint == '')) {
|
|
155
|
+
throw new Error('PowerSync endpoint not configured');
|
|
156
|
+
} else if (credentials?.token == null || credentials?.token == '') {
|
|
157
|
+
const error: any = new Error(`Not signed in`);
|
|
158
|
+
error.status = 401;
|
|
159
|
+
throw error;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const userAgent = this.getUserAgent();
|
|
163
|
+
|
|
164
|
+
return {
|
|
165
|
+
url: credentials.endpoint + path,
|
|
166
|
+
headers: {
|
|
167
|
+
'content-type': 'application/json',
|
|
168
|
+
Authorization: `Token ${credentials.token}`,
|
|
169
|
+
'x-user-agent': userAgent
|
|
170
|
+
},
|
|
171
|
+
userAgent,
|
|
172
|
+
path
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async fetchAndDecodeJson({
|
|
177
|
+
path,
|
|
178
|
+
method = 'GET',
|
|
179
|
+
headers,
|
|
180
|
+
body,
|
|
181
|
+
signal
|
|
182
|
+
}: {
|
|
183
|
+
path: string;
|
|
184
|
+
method?: string;
|
|
185
|
+
headers?: Record<string, string>;
|
|
186
|
+
body?: string;
|
|
187
|
+
signal?: AbortSignal;
|
|
188
|
+
}): Promise<any> {
|
|
189
|
+
const request = await this.buildRequest(path);
|
|
190
|
+
const res = await this.fetch({
|
|
191
|
+
resource: request.url,
|
|
192
|
+
request: {
|
|
193
|
+
method,
|
|
194
|
+
headers: {
|
|
195
|
+
...headers,
|
|
196
|
+
...request.headers
|
|
197
|
+
},
|
|
198
|
+
body,
|
|
199
|
+
signal
|
|
200
|
+
},
|
|
201
|
+
expectStreamingResponse: false
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
if (res.status === 401) {
|
|
205
|
+
this.invalidateCredentials();
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
if (!res.ok) {
|
|
209
|
+
throw new Error(`Received ${res.status} - ${res.statusText} when getting from ${path}: ${await res.text()}}`);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
return res.json();
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* @returns A text decoder decoding UTF-8. This is a method to allow patching it for Hermes which doesn't support the
|
|
217
|
+
* builtin, without forcing us to bundle a polyfill with `@powersync/common`.
|
|
218
|
+
*/
|
|
219
|
+
createTextDecoder(): TextDecoder {
|
|
220
|
+
return new TextDecoder();
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
createSocket(url: string): WebSocket {
|
|
224
|
+
return new WebSocket(url);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Loads `@powersync/shared-internals/websockets`.
|
|
229
|
+
*
|
|
230
|
+
* We prefer to load that as a lazy module with a dynamic `import()` expressions on most platforms. An exception is
|
|
231
|
+
* React Native, where WebSocket support is preferred and we want to load this directly.
|
|
232
|
+
*/
|
|
233
|
+
protected abstract loadWebSocketSupport(platform: WebSocketSyncStreamPlatform): Promise<WebSocketSupport>;
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Returns a data stream of sync line data, fetched via RSocket-over-WebSocket.
|
|
237
|
+
*
|
|
238
|
+
* The only mechanism to abort the returned stream is to use the abort signal in {@link SocketSyncStreamOptions}.
|
|
239
|
+
*/
|
|
240
|
+
async socketStreamRaw(options: SocketSyncStreamOptions): Promise<SimpleAsyncIterator<Uint8Array>> {
|
|
241
|
+
const support = await this.loadWebSocketSupport(webSocketPlatform);
|
|
242
|
+
|
|
243
|
+
const request = await this.buildRequest(options.path);
|
|
244
|
+
request.url = request.url.replace(/^https?:\/\//, function (match) {
|
|
245
|
+
return match === 'https://' ? 'wss://' : 'ws://';
|
|
246
|
+
});
|
|
247
|
+
const { fetchStrategy = FetchStrategy.Buffered, abortSignal, data } = options;
|
|
248
|
+
|
|
249
|
+
return await support.webSocketSyncStream({
|
|
250
|
+
remote: this,
|
|
251
|
+
buffered: fetchStrategy == FetchStrategy.Buffered,
|
|
252
|
+
abortSignal,
|
|
253
|
+
requestPayload: data,
|
|
254
|
+
request
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Posts a `/sync/stream` request, asserts that it completes successfully and returns the streaming response as an
|
|
260
|
+
* async iterator of byte blobs.
|
|
261
|
+
*
|
|
262
|
+
* To cancel the async iterator, use the abort signal from {@link SyncStreamOptions} passed to this method.
|
|
263
|
+
*/
|
|
264
|
+
protected async fetchStreamRaw(
|
|
265
|
+
options: SyncStreamOptions
|
|
266
|
+
): Promise<{ isBson: boolean; stream: SimpleAsyncIterator<Uint8Array> }> {
|
|
267
|
+
const { data, path, abortSignal } = options;
|
|
268
|
+
const request = await this.buildRequest(path);
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* This abort controller will abort pending fetch requests.
|
|
272
|
+
* If the request has resolved, it will be used to close the readable stream.
|
|
273
|
+
* Which will cancel the network request.
|
|
274
|
+
*
|
|
275
|
+
* This nested controller is required since:
|
|
276
|
+
* Aborting the active fetch request while it is being consumed seems to throw
|
|
277
|
+
* an unhandled exception on the window level.
|
|
278
|
+
*/
|
|
279
|
+
if (abortSignal.aborted) {
|
|
280
|
+
throw new AbortOperation('Abort request received before making fetchStreamRaw request');
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const controller = new AbortController();
|
|
284
|
+
let reader: ReadableStreamDefaultReader<Uint8Array> | null = null;
|
|
285
|
+
abortSignal.addEventListener('abort', () => {
|
|
286
|
+
const reason =
|
|
287
|
+
abortSignal.reason ??
|
|
288
|
+
new AbortOperation('Cancelling network request before it resolves. Abort signal has been received.');
|
|
289
|
+
|
|
290
|
+
if (reader == null) {
|
|
291
|
+
// Only abort via the abort controller if the request has not resolved yet
|
|
292
|
+
controller.abort(reason);
|
|
293
|
+
} else {
|
|
294
|
+
reader.cancel(reason).catch(() => {
|
|
295
|
+
// Cancelling the reader might rethrow an exception we would have handled by throwing in next(). So we can
|
|
296
|
+
// ignore it here.
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
let res: Response;
|
|
302
|
+
let responseIsBson = false;
|
|
303
|
+
try {
|
|
304
|
+
const ndJson = 'application/x-ndjson';
|
|
305
|
+
const bson = 'application/vnd.powersync.bson-stream';
|
|
306
|
+
|
|
307
|
+
res = await this.fetch({
|
|
308
|
+
resource: request.url,
|
|
309
|
+
request: {
|
|
310
|
+
method: 'POST',
|
|
311
|
+
headers: {
|
|
312
|
+
...request.headers,
|
|
313
|
+
accept: `${bson};q=0.9,${ndJson};q=0.8`
|
|
314
|
+
},
|
|
315
|
+
body: JSON.stringify(data),
|
|
316
|
+
signal: controller.signal,
|
|
317
|
+
cache: 'no-store'
|
|
318
|
+
},
|
|
319
|
+
expectStreamingResponse: true
|
|
320
|
+
});
|
|
321
|
+
|
|
322
|
+
if (!res.ok || !res.body) {
|
|
323
|
+
const text = await res.text();
|
|
324
|
+
const error: any = new Error(`HTTP ${res.statusText}: ${text}`);
|
|
325
|
+
error.status = res.status;
|
|
326
|
+
|
|
327
|
+
this.logger.log({
|
|
328
|
+
level: LogLevels.error,
|
|
329
|
+
message: `Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`,
|
|
330
|
+
error
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
if (res.status === 401) {
|
|
334
|
+
this.invalidateCredentials();
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
throw error;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
const contentType = res.headers.get('content-type');
|
|
341
|
+
responseIsBson = contentType == bson;
|
|
342
|
+
} catch (ex: any) {
|
|
343
|
+
if (ex.name == 'AbortError') {
|
|
344
|
+
throw new AbortOperation(`Pending fetch request to ${request.url} has been aborted.`);
|
|
345
|
+
}
|
|
346
|
+
throw ex;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
reader = res.body.getReader();
|
|
350
|
+
|
|
351
|
+
const stream: SimpleAsyncIterator<Uint8Array> = {
|
|
352
|
+
next: async () => {
|
|
353
|
+
if (controller.signal.aborted) {
|
|
354
|
+
return doneResult;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
try {
|
|
358
|
+
return await reader.read();
|
|
359
|
+
} catch (ex) {
|
|
360
|
+
if (controller.signal.aborted) {
|
|
361
|
+
// .read() completes with an error if we cancel the reader, which we do to disconnect. So this is just
|
|
362
|
+
// things working as intended, we can return a done event and consider the exception handled.
|
|
363
|
+
return doneResult;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
throw ex;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
};
|
|
370
|
+
|
|
371
|
+
return { isBson: responseIsBson, stream };
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Posts a `/sync/stream` request.
|
|
376
|
+
*
|
|
377
|
+
* Depending on the `Content-Type` of the response, this returns strings for sync lines or encoded BSON documents as
|
|
378
|
+
* `Uint8Array`s.
|
|
379
|
+
*/
|
|
380
|
+
async fetchStream(options: SyncStreamOptions): Promise<SimpleAsyncIterator<Uint8Array | string>> {
|
|
381
|
+
const { isBson, stream } = await this.fetchStreamRaw(options);
|
|
382
|
+
if (isBson) {
|
|
383
|
+
return extractBsonObjects(stream);
|
|
384
|
+
} else {
|
|
385
|
+
return extractJsonLines(stream, this.createTextDecoder());
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
}
|