@powersync/node 0.13.0 → 0.14.1
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/dist/DefaultWorker.cjs.map +1 -1
- package/dist/bundle.cjs +38 -18
- package/dist/bundle.cjs.map +1 -1
- package/dist/worker.cjs.map +1 -1
- package/lib/db/AsyncDatabase.js +1 -0
- package/lib/db/AsyncDatabase.js.map +1 -0
- package/lib/db/BetterSqliteWorker.js +1 -0
- package/lib/db/BetterSqliteWorker.js.map +1 -0
- package/lib/db/DefaultWorker.js +1 -0
- package/lib/db/DefaultWorker.js.map +1 -0
- package/lib/db/NodeSqliteWorker.js +1 -0
- package/lib/db/NodeSqliteWorker.js.map +1 -0
- package/lib/db/PowerSyncDatabase.js +1 -0
- package/lib/db/PowerSyncDatabase.js.map +1 -0
- package/lib/db/RemoteConnection.d.ts +3 -2
- package/lib/db/RemoteConnection.js +30 -12
- package/lib/db/RemoteConnection.js.map +1 -0
- package/lib/db/SqliteWorker.js +1 -0
- package/lib/db/SqliteWorker.js.map +1 -0
- package/lib/db/WorkerConnectionPool.js +2 -1
- package/lib/db/WorkerConnectionPool.js.map +1 -0
- package/lib/db/options.js +1 -0
- package/lib/db/options.js.map +1 -0
- package/lib/index.js +1 -0
- package/lib/index.js.map +1 -0
- package/lib/sync/stream/NodeRemote.js +1 -0
- package/lib/sync/stream/NodeRemote.js.map +1 -0
- package/lib/sync/stream/NodeStreamingSyncImplementation.d.ts +3 -3
- package/lib/sync/stream/NodeStreamingSyncImplementation.js +8 -4
- package/lib/sync/stream/NodeStreamingSyncImplementation.js.map +1 -0
- package/lib/utils/modules.js +1 -0
- package/lib/utils/modules.js.map +1 -0
- package/lib/utils/modules_commonjs.js +1 -0
- package/lib/utils/modules_commonjs.js.map +1 -0
- package/lib/worker.js +1 -0
- package/lib/worker.js.map +1 -0
- package/package.json +10 -10
- package/src/db/AsyncDatabase.ts +26 -0
- package/src/db/BetterSqliteWorker.ts +72 -0
- package/src/db/DefaultWorker.ts +3 -0
- package/src/db/NodeSqliteWorker.ts +63 -0
- package/src/db/PowerSyncDatabase.ts +100 -0
- package/src/db/RemoteConnection.ts +129 -0
- package/src/db/SqliteWorker.ts +119 -0
- package/src/db/WorkerConnectionPool.ts +328 -0
- package/src/db/options.ts +51 -0
- package/src/index.ts +4 -0
- package/src/sync/stream/NodeRemote.ts +123 -0
- package/src/sync/stream/NodeStreamingSyncImplementation.ts +57 -0
- package/src/utils/modules.ts +6 -0
- package/src/utils/modules_commonjs.ts +7 -0
- package/src/worker.ts +1 -0
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import * as Comlink from 'comlink';
|
|
2
|
+
import OS from 'node:os';
|
|
3
|
+
import * as path from 'node:path';
|
|
4
|
+
import url from 'node:url';
|
|
5
|
+
import { parentPort } from 'node:worker_threads';
|
|
6
|
+
import { dynamicImport, isBundledToCommonJs } from '../utils/modules.js';
|
|
7
|
+
import { AsyncDatabase, AsyncDatabaseOpener, AsyncDatabaseOpenOptions } from './AsyncDatabase.js';
|
|
8
|
+
import { openDatabase as openBetterSqliteDatabase } from './BetterSqliteWorker.js';
|
|
9
|
+
import { openDatabase as openNodeDatabase } from './NodeSqliteWorker.js';
|
|
10
|
+
|
|
11
|
+
export interface PowerSyncWorkerOptions {
|
|
12
|
+
/**
|
|
13
|
+
* A function responsible for finding the powersync DLL/so/dylib file.
|
|
14
|
+
*
|
|
15
|
+
* @returns The absolute path of the PowerSync SQLite core extensions library.
|
|
16
|
+
*/
|
|
17
|
+
extensionPath: () => string;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* A function that returns the `Database` constructor from the `better-sqlite3` package.
|
|
21
|
+
*/
|
|
22
|
+
loadBetterSqlite3: () => Promise<any>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* @returns The relevant PowerSync extension binary filename for the current platform and architecture
|
|
27
|
+
*/
|
|
28
|
+
export function getPowerSyncExtensionFilename() {
|
|
29
|
+
const platform = OS.platform();
|
|
30
|
+
const arch = OS.arch();
|
|
31
|
+
let extensionFile: string;
|
|
32
|
+
|
|
33
|
+
if (platform == 'win32') {
|
|
34
|
+
if (arch == 'x64') {
|
|
35
|
+
extensionFile = 'powersync_x64.dll';
|
|
36
|
+
} else if (arch == 'ia32') {
|
|
37
|
+
extensionFile = 'powersync_x86.dll';
|
|
38
|
+
} else if (arch == 'arm64') {
|
|
39
|
+
extensionFile = 'powersync_aarch64.dll';
|
|
40
|
+
} else {
|
|
41
|
+
throw new Error('Windows platform only supports arm64, ia32 and x64 architecture.');
|
|
42
|
+
}
|
|
43
|
+
} else if (platform == 'linux') {
|
|
44
|
+
if (arch == 'x64') {
|
|
45
|
+
extensionFile = 'libpowersync_x64.so';
|
|
46
|
+
} else if (arch == 'arm64') {
|
|
47
|
+
// TODO detect armv7 as an option
|
|
48
|
+
extensionFile = 'libpowersync_aarch64.so';
|
|
49
|
+
} else if (arch == 'riscv64') {
|
|
50
|
+
extensionFile = 'libpowersync_riscv64gc.so';
|
|
51
|
+
} else {
|
|
52
|
+
throw new Error('Linux platform only supports x64, arm64 and riscv64 architectures.');
|
|
53
|
+
}
|
|
54
|
+
} else if (platform == 'darwin') {
|
|
55
|
+
if (arch == 'x64') {
|
|
56
|
+
extensionFile = 'libpowersync_x64.dylib';
|
|
57
|
+
} else if (arch == 'arm64') {
|
|
58
|
+
extensionFile = 'libpowersync_aarch64.dylib';
|
|
59
|
+
} else {
|
|
60
|
+
throw new Error('macOS platform only supports x64 and arm64 architectures.');
|
|
61
|
+
}
|
|
62
|
+
} else {
|
|
63
|
+
throw new Error(
|
|
64
|
+
`Unknown platform: ${platform}, PowerSync for Node.js currently supports Windows, Linux and macOS.`
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
return extensionFile;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function startPowerSyncWorker(options?: Partial<PowerSyncWorkerOptions>) {
|
|
72
|
+
const resolvedOptions: PowerSyncWorkerOptions = {
|
|
73
|
+
extensionPath() {
|
|
74
|
+
const isCommonJsModule = isBundledToCommonJs;
|
|
75
|
+
const extensionFilename = getPowerSyncExtensionFilename();
|
|
76
|
+
let resolved: string;
|
|
77
|
+
if (isCommonJsModule) {
|
|
78
|
+
resolved = path.resolve(__dirname, '../lib/', extensionFilename);
|
|
79
|
+
} else {
|
|
80
|
+
resolved = url.fileURLToPath(new URL(`../${extensionFilename}`, import.meta.url));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return resolved;
|
|
84
|
+
},
|
|
85
|
+
async loadBetterSqlite3() {
|
|
86
|
+
const module = await dynamicImport('better-sqlite3');
|
|
87
|
+
return module.default;
|
|
88
|
+
},
|
|
89
|
+
...options
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
Comlink.expose(new DatabaseOpenHelper(resolvedOptions), parentPort! as Comlink.Endpoint);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
class DatabaseOpenHelper implements AsyncDatabaseOpener {
|
|
96
|
+
private options: PowerSyncWorkerOptions;
|
|
97
|
+
|
|
98
|
+
constructor(options: PowerSyncWorkerOptions) {
|
|
99
|
+
this.options = options;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async open(options: AsyncDatabaseOpenOptions): Promise<AsyncDatabase> {
|
|
103
|
+
let database: AsyncDatabase;
|
|
104
|
+
|
|
105
|
+
const implementation = options.implementation;
|
|
106
|
+
switch (implementation.type) {
|
|
107
|
+
case 'better-sqlite3':
|
|
108
|
+
database = await openBetterSqliteDatabase(this.options, options);
|
|
109
|
+
break;
|
|
110
|
+
case 'node:sqlite':
|
|
111
|
+
database = await openNodeDatabase(this.options, options);
|
|
112
|
+
break;
|
|
113
|
+
default:
|
|
114
|
+
throw new Error(`Unknown database implementation: ${options.implementation}.`);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return Comlink.proxy(database);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import * as Comlink from 'comlink';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import * as path from 'node:path';
|
|
4
|
+
import { Worker } from 'node:worker_threads';
|
|
5
|
+
|
|
6
|
+
import {
|
|
7
|
+
BaseObserver,
|
|
8
|
+
BatchedUpdateNotification,
|
|
9
|
+
DBAdapter,
|
|
10
|
+
DBAdapterListener,
|
|
11
|
+
DBLockOptions,
|
|
12
|
+
LockContext,
|
|
13
|
+
QueryResult,
|
|
14
|
+
Transaction
|
|
15
|
+
} from '@powersync/common';
|
|
16
|
+
import { Remote } from 'comlink';
|
|
17
|
+
import { AsyncResource } from 'node:async_hooks';
|
|
18
|
+
import { isBundledToCommonJs } from '../utils/modules.js';
|
|
19
|
+
import { AsyncDatabase, AsyncDatabaseOpener } from './AsyncDatabase.js';
|
|
20
|
+
import { RemoteConnection } from './RemoteConnection.js';
|
|
21
|
+
import { NodeDatabaseImplementation, NodeSQLOpenOptions } from './options.js';
|
|
22
|
+
|
|
23
|
+
export type BetterSQLite3LockContext = LockContext & {
|
|
24
|
+
executeBatch(query: string, params?: any[][]): Promise<QueryResult>;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export type BetterSQLite3Transaction = Transaction & BetterSQLite3LockContext;
|
|
28
|
+
|
|
29
|
+
const READ_CONNECTIONS = 5;
|
|
30
|
+
|
|
31
|
+
const defaultDatabaseImplementation: NodeDatabaseImplementation = {
|
|
32
|
+
type: 'better-sqlite3'
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Adapter for better-sqlite3
|
|
37
|
+
*/
|
|
38
|
+
export class WorkerConnectionPool extends BaseObserver<DBAdapterListener> implements DBAdapter {
|
|
39
|
+
private readonly options: NodeSQLOpenOptions;
|
|
40
|
+
public readonly name: string;
|
|
41
|
+
|
|
42
|
+
private readConnections: RemoteConnection[];
|
|
43
|
+
private writeConnection: RemoteConnection;
|
|
44
|
+
|
|
45
|
+
private readonly readQueue: Array<(connection: RemoteConnection) => void> = [];
|
|
46
|
+
private readonly writeQueue: Array<() => void> = [];
|
|
47
|
+
|
|
48
|
+
constructor(options: NodeSQLOpenOptions) {
|
|
49
|
+
super();
|
|
50
|
+
|
|
51
|
+
if (options.readWorkerCount != null && options.readWorkerCount < 1) {
|
|
52
|
+
throw `Needs at least one worker for reads, got ${options.readWorkerCount}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
this.options = options;
|
|
56
|
+
this.name = options.dbFilename;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async initialize() {
|
|
60
|
+
let dbFilePath = this.options.dbFilename;
|
|
61
|
+
if (this.options.dbLocation !== undefined) {
|
|
62
|
+
// Make sure the dbLocation exists, we get a TypeError from better-sqlite3 otherwise.
|
|
63
|
+
let directoryExists = false;
|
|
64
|
+
try {
|
|
65
|
+
const stat = await fs.stat(this.options.dbLocation);
|
|
66
|
+
directoryExists = stat.isDirectory();
|
|
67
|
+
} catch (_) {
|
|
68
|
+
// If we can't even stat, the directory won't be accessible to SQLite either.
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (!directoryExists) {
|
|
72
|
+
throw new Error(
|
|
73
|
+
`The dbLocation directory at "${this.options.dbLocation}" does not exist. Please create it before opening the PowerSync database!`
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
dbFilePath = path.join(this.options.dbLocation, dbFilePath);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const openWorker = async (isWriter: boolean) => {
|
|
81
|
+
const isCommonJsModule = isBundledToCommonJs;
|
|
82
|
+
let worker: Worker;
|
|
83
|
+
const workerName = isWriter ? `write ${dbFilePath}` : `read ${dbFilePath}`;
|
|
84
|
+
|
|
85
|
+
const workerFactory = this.options.openWorker ?? ((...args) => new Worker(...args));
|
|
86
|
+
if (isCommonJsModule) {
|
|
87
|
+
worker = workerFactory(path.resolve(__dirname, 'DefaultWorker.cjs'), { name: workerName });
|
|
88
|
+
} else {
|
|
89
|
+
worker = workerFactory(new URL('./DefaultWorker.js', import.meta.url), { name: workerName });
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const listeners = new WeakMap<EventListenerOrEventListenerObject, (e: any) => void>();
|
|
93
|
+
|
|
94
|
+
const comlink = Comlink.wrap<AsyncDatabaseOpener>({
|
|
95
|
+
postMessage: worker.postMessage.bind(worker),
|
|
96
|
+
addEventListener: (type, listener) => {
|
|
97
|
+
let resolved: (event: any) => void =
|
|
98
|
+
'handleEvent' in listener ? listener.handleEvent.bind(listener) : listener;
|
|
99
|
+
|
|
100
|
+
// Comlink wants message events, but the message event on workers in Node returns the data only.
|
|
101
|
+
if (type === 'message') {
|
|
102
|
+
const original = resolved;
|
|
103
|
+
|
|
104
|
+
resolved = (data) => {
|
|
105
|
+
original({ data });
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
listeners.set(listener, resolved);
|
|
110
|
+
worker.addListener(type, resolved);
|
|
111
|
+
},
|
|
112
|
+
removeEventListener: (type, listener) => {
|
|
113
|
+
const resolved = listeners.get(listener);
|
|
114
|
+
if (!resolved) {
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
worker.removeListener(type, resolved);
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
worker.once('error', (e) => {
|
|
122
|
+
console.error('Unexpected PowerSync database worker error', e);
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
const database = (await comlink.open({
|
|
126
|
+
path: dbFilePath,
|
|
127
|
+
isWriter,
|
|
128
|
+
implementation: this.options.implementation ?? defaultDatabaseImplementation
|
|
129
|
+
})) as Remote<AsyncDatabase>;
|
|
130
|
+
if (isWriter) {
|
|
131
|
+
await database.execute("SELECT powersync_update_hooks('install');", []);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const connection = new RemoteConnection(worker, comlink, database);
|
|
135
|
+
if (this.options.initializeConnection) {
|
|
136
|
+
await this.options.initializeConnection(connection, isWriter);
|
|
137
|
+
}
|
|
138
|
+
if (!isWriter) {
|
|
139
|
+
await connection.execute('pragma query_only = true');
|
|
140
|
+
} else {
|
|
141
|
+
// We only need to enable this on the writer connection.
|
|
142
|
+
// We can get `database is locked` errors if we enable this on concurrently opening read connections.
|
|
143
|
+
await connection.execute('pragma journal_mode = WAL');
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return connection;
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
// Open the writer first to avoid multiple threads enabling WAL concurrently (causing "database is locked" errors).
|
|
150
|
+
this.writeConnection = await openWorker(true);
|
|
151
|
+
const createWorkers: Promise<RemoteConnection>[] = [];
|
|
152
|
+
const amountOfReaders = this.options.readWorkerCount ?? READ_CONNECTIONS;
|
|
153
|
+
for (let i = 0; i < amountOfReaders; i++) {
|
|
154
|
+
createWorkers.push(openWorker(false));
|
|
155
|
+
}
|
|
156
|
+
this.readConnections = await Promise.all(createWorkers);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async close() {
|
|
160
|
+
await this.writeConnection.close();
|
|
161
|
+
for (const connection of this.readConnections) {
|
|
162
|
+
await connection.close();
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
readLock<T>(fn: (tx: BetterSQLite3LockContext) => Promise<T>, _options?: DBLockOptions | undefined): Promise<T> {
|
|
167
|
+
let resolveConnectionPromise!: (connection: RemoteConnection) => void;
|
|
168
|
+
const connectionPromise = new Promise<RemoteConnection>((resolve, _reject) => {
|
|
169
|
+
resolveConnectionPromise = AsyncResource.bind(resolve);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
const connection = this.readConnections.find((connection) => !connection.isBusy);
|
|
173
|
+
if (connection) {
|
|
174
|
+
connection.isBusy = true;
|
|
175
|
+
resolveConnectionPromise(connection);
|
|
176
|
+
} else {
|
|
177
|
+
this.readQueue.push(resolveConnectionPromise);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
return (async () => {
|
|
181
|
+
const connection = await connectionPromise;
|
|
182
|
+
|
|
183
|
+
try {
|
|
184
|
+
return await fn(connection);
|
|
185
|
+
} finally {
|
|
186
|
+
const next = this.readQueue.shift();
|
|
187
|
+
if (next) {
|
|
188
|
+
next(connection);
|
|
189
|
+
} else {
|
|
190
|
+
connection.isBusy = false;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
})();
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
writeLock<T>(fn: (tx: BetterSQLite3LockContext) => Promise<T>, _options?: DBLockOptions | undefined): Promise<T> {
|
|
197
|
+
let resolveLockPromise!: () => void;
|
|
198
|
+
const lockPromise = new Promise<void>((resolve, _reject) => {
|
|
199
|
+
resolveLockPromise = AsyncResource.bind(resolve);
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
if (!this.writeConnection.isBusy) {
|
|
203
|
+
this.writeConnection.isBusy = true;
|
|
204
|
+
resolveLockPromise();
|
|
205
|
+
} else {
|
|
206
|
+
this.writeQueue.push(resolveLockPromise);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
return (async () => {
|
|
210
|
+
await lockPromise;
|
|
211
|
+
|
|
212
|
+
try {
|
|
213
|
+
try {
|
|
214
|
+
return await fn(this.writeConnection);
|
|
215
|
+
} finally {
|
|
216
|
+
const serializedUpdates = await this.writeConnection.executeRaw("SELECT powersync_update_hooks('get');", []);
|
|
217
|
+
const updates = JSON.parse(serializedUpdates[0][0] as string) as string[];
|
|
218
|
+
|
|
219
|
+
if (updates.length > 0) {
|
|
220
|
+
const event: BatchedUpdateNotification = {
|
|
221
|
+
tables: updates,
|
|
222
|
+
groupedUpdates: {},
|
|
223
|
+
rawUpdates: []
|
|
224
|
+
};
|
|
225
|
+
this.iterateListeners((cb) => cb.tablesUpdated?.(event));
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
} finally {
|
|
229
|
+
const next = this.writeQueue.shift();
|
|
230
|
+
if (next) {
|
|
231
|
+
next();
|
|
232
|
+
} else {
|
|
233
|
+
this.writeConnection.isBusy = false;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
})();
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
readTransaction<T>(
|
|
240
|
+
fn: (tx: BetterSQLite3Transaction) => Promise<T>,
|
|
241
|
+
_options?: DBLockOptions | undefined
|
|
242
|
+
): Promise<T> {
|
|
243
|
+
return this.readLock((ctx) => this.internalTransaction(ctx as RemoteConnection, fn));
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
writeTransaction<T>(
|
|
247
|
+
fn: (tx: BetterSQLite3Transaction) => Promise<T>,
|
|
248
|
+
_options?: DBLockOptions | undefined
|
|
249
|
+
): Promise<T> {
|
|
250
|
+
return this.writeLock((ctx) => this.internalTransaction(ctx as RemoteConnection, fn));
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
private async internalTransaction<T>(
|
|
254
|
+
connection: RemoteConnection,
|
|
255
|
+
fn: (tx: BetterSQLite3Transaction) => Promise<T>
|
|
256
|
+
): Promise<T> {
|
|
257
|
+
let finalized = false;
|
|
258
|
+
const commit = async (): Promise<QueryResult> => {
|
|
259
|
+
if (!finalized) {
|
|
260
|
+
finalized = true;
|
|
261
|
+
await connection.execute('COMMIT');
|
|
262
|
+
}
|
|
263
|
+
return { rowsAffected: 0 };
|
|
264
|
+
};
|
|
265
|
+
const rollback = async (): Promise<QueryResult> => {
|
|
266
|
+
if (!finalized) {
|
|
267
|
+
finalized = true;
|
|
268
|
+
await connection.execute('ROLLBACK');
|
|
269
|
+
}
|
|
270
|
+
return { rowsAffected: 0 };
|
|
271
|
+
};
|
|
272
|
+
try {
|
|
273
|
+
await connection.execute('BEGIN');
|
|
274
|
+
const result = await fn({
|
|
275
|
+
execute: (query, params) => connection.execute(query, params),
|
|
276
|
+
executeRaw: (query, params) => connection.executeRaw(query, params),
|
|
277
|
+
executeBatch: (query, params) => connection.executeBatch(query, params),
|
|
278
|
+
get: (query, params) => connection.get(query, params),
|
|
279
|
+
getAll: (query, params) => connection.getAll(query, params),
|
|
280
|
+
getOptional: (query, params) => connection.getOptional(query, params),
|
|
281
|
+
commit,
|
|
282
|
+
rollback
|
|
283
|
+
});
|
|
284
|
+
await commit();
|
|
285
|
+
return result;
|
|
286
|
+
} catch (ex) {
|
|
287
|
+
try {
|
|
288
|
+
await rollback();
|
|
289
|
+
} catch (ex2) {
|
|
290
|
+
// In rare cases, a rollback may fail.
|
|
291
|
+
// Safe to ignore.
|
|
292
|
+
}
|
|
293
|
+
throw ex;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
getAll<T>(sql: string, parameters?: any[]): Promise<T[]> {
|
|
298
|
+
return this.readLock((ctx) => ctx.getAll(sql, parameters));
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
getOptional<T>(sql: string, parameters?: any[]): Promise<T | null> {
|
|
302
|
+
return this.readLock((ctx) => ctx.getOptional(sql, parameters));
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
get<T>(sql: string, parameters?: any[]): Promise<T> {
|
|
306
|
+
return this.readLock((ctx) => ctx.get(sql, parameters));
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
execute(query: string, params?: any[] | undefined): Promise<QueryResult> {
|
|
310
|
+
return this.writeLock((ctx) => ctx.execute(query, params));
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
executeRaw(query: string, params?: any[] | undefined): Promise<any[][]> {
|
|
314
|
+
return this.writeLock((ctx) => ctx.executeRaw(query, params));
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
executeBatch(query: string, params?: any[][]): Promise<QueryResult> {
|
|
318
|
+
return this.writeTransaction((ctx) => ctx.executeBatch(query, params));
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
async refreshSchema() {
|
|
322
|
+
await this.writeConnection.refreshSchema();
|
|
323
|
+
|
|
324
|
+
for (const readConnection of this.readConnections) {
|
|
325
|
+
await readConnection.refreshSchema();
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { type Worker } from 'node:worker_threads';
|
|
2
|
+
import { LockContext, SQLOpenOptions } from '@powersync/common';
|
|
3
|
+
|
|
4
|
+
export type WorkerOpener = (...args: ConstructorParameters<typeof Worker>) => InstanceType<typeof Worker>;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Use the [better-sqlite3](https://github.com/WiseLibs/better-sqlite3) package as a SQLite driver for PowerSync.
|
|
8
|
+
*/
|
|
9
|
+
export interface BetterSqlite3Options {
|
|
10
|
+
type: 'better-sqlite3';
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Use the experimental `node:sqlite` interface as a SQLite driver for PowerSync.
|
|
15
|
+
*
|
|
16
|
+
* Note that this option is not currently tested and highly unstable.
|
|
17
|
+
*/
|
|
18
|
+
export interface NodeSqliteOptions {
|
|
19
|
+
type: 'node:sqlite';
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type NodeDatabaseImplementation = BetterSqlite3Options | NodeSqliteOptions;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The {@link SQLOpenOptions} available across all PowerSync SDKs for JavaScript extended with
|
|
26
|
+
* Node.JS-specific options.
|
|
27
|
+
*/
|
|
28
|
+
export interface NodeSQLOpenOptions extends SQLOpenOptions {
|
|
29
|
+
implementation?: NodeDatabaseImplementation;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The Node.JS SDK will use one worker to run writing queries and additional workers to run reads.
|
|
33
|
+
* This option controls how many workers to use for reads.
|
|
34
|
+
*/
|
|
35
|
+
readWorkerCount?: number;
|
|
36
|
+
/**
|
|
37
|
+
* A callback to allow customizing how the Node.JS SDK loads workers. This can be customized to
|
|
38
|
+
* use workers at different paths.
|
|
39
|
+
*
|
|
40
|
+
* @param args The arguments that would otherwise be passed to the {@link Worker} constructor.
|
|
41
|
+
* @returns the resolved worker.
|
|
42
|
+
*/
|
|
43
|
+
openWorker?: WorkerOpener;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Initializes a created database connection.
|
|
47
|
+
*
|
|
48
|
+
* This can be used to e.g. set encryption keys, if an encrypted database should be used.
|
|
49
|
+
*/
|
|
50
|
+
initializeConnection?: (db: LockContext, isWriter: boolean) => Promise<void>;
|
|
51
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import * as os from 'node:os';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
type ILogger,
|
|
5
|
+
AbstractRemote,
|
|
6
|
+
AbstractRemoteOptions,
|
|
7
|
+
BSONImplementation,
|
|
8
|
+
DEFAULT_REMOTE_LOGGER,
|
|
9
|
+
FetchImplementation,
|
|
10
|
+
FetchImplementationProvider,
|
|
11
|
+
RemoteConnector
|
|
12
|
+
} from '@powersync/common';
|
|
13
|
+
import { BSON } from 'bson';
|
|
14
|
+
import {
|
|
15
|
+
Dispatcher,
|
|
16
|
+
EnvHttpProxyAgent,
|
|
17
|
+
ErrorEvent,
|
|
18
|
+
getGlobalDispatcher,
|
|
19
|
+
ProxyAgent,
|
|
20
|
+
WebSocket as UndiciWebSocket
|
|
21
|
+
} from 'undici';
|
|
22
|
+
|
|
23
|
+
export const STREAMING_POST_TIMEOUT_MS = 30_000;
|
|
24
|
+
|
|
25
|
+
class NodeFetchProvider extends FetchImplementationProvider {
|
|
26
|
+
getFetch(): FetchImplementation {
|
|
27
|
+
return fetch.bind(globalThis);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export type NodeCustomConnectionOptions = {
|
|
32
|
+
/**
|
|
33
|
+
* Optional custom dispatcher for HTTP or WEB_SOCKET connections.
|
|
34
|
+
*
|
|
35
|
+
* This can be used to customize proxy usage (using undici ProxyAgent),
|
|
36
|
+
* or other connection options.
|
|
37
|
+
*/
|
|
38
|
+
dispatcher?: Dispatcher;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export type NodeRemoteOptions = AbstractRemoteOptions & NodeCustomConnectionOptions;
|
|
42
|
+
|
|
43
|
+
export class NodeRemote extends AbstractRemote {
|
|
44
|
+
private wsDispatcher: Dispatcher | undefined;
|
|
45
|
+
|
|
46
|
+
constructor(
|
|
47
|
+
protected connector: RemoteConnector,
|
|
48
|
+
protected logger: ILogger = DEFAULT_REMOTE_LOGGER,
|
|
49
|
+
options?: Partial<NodeRemoteOptions>
|
|
50
|
+
) {
|
|
51
|
+
const fetchDispatcher = options?.dispatcher ?? defaultFetchDispatcher();
|
|
52
|
+
|
|
53
|
+
super(connector, logger, {
|
|
54
|
+
fetchImplementation: options?.fetchImplementation ?? new NodeFetchProvider(),
|
|
55
|
+
fetchOptions: {
|
|
56
|
+
dispatcher: fetchDispatcher
|
|
57
|
+
},
|
|
58
|
+
...(options ?? {})
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
this.wsDispatcher = options?.dispatcher;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
protected createSocket(url: string): globalThis.WebSocket {
|
|
65
|
+
// Create dedicated dispatcher for this WebSocket
|
|
66
|
+
const baseDispatcher = this.getWebsocketDispatcher(url);
|
|
67
|
+
|
|
68
|
+
// Create WebSocket with dedicated dispatcher
|
|
69
|
+
const ws = new UndiciWebSocket(url, {
|
|
70
|
+
dispatcher: baseDispatcher,
|
|
71
|
+
headers: {
|
|
72
|
+
'User-Agent': this.getUserAgent()
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
return ws as globalThis.WebSocket;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
protected getWebsocketDispatcher(url: string) {
|
|
80
|
+
if (this.wsDispatcher != null) {
|
|
81
|
+
return this.wsDispatcher;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const protocol = new URL(url).protocol.replace(':', '');
|
|
85
|
+
const proxy = getProxyForProtocol(protocol);
|
|
86
|
+
if (proxy != null) {
|
|
87
|
+
return new ProxyAgent(proxy);
|
|
88
|
+
} else {
|
|
89
|
+
return getGlobalDispatcher();
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
getUserAgent(): string {
|
|
94
|
+
return [
|
|
95
|
+
super.getUserAgent(),
|
|
96
|
+
`powersync-node`,
|
|
97
|
+
`node/${process.versions.node}`,
|
|
98
|
+
`${os.platform()}/${os.release()}`
|
|
99
|
+
].join(' ');
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async getBSON(): Promise<BSONImplementation> {
|
|
103
|
+
return BSON;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function defaultFetchDispatcher(): Dispatcher {
|
|
108
|
+
// EnvHttpProxyAgent automatically uses HTTP_PROXY, HTTPS_PROXY and NO_PROXY env vars by default.
|
|
109
|
+
// We add ALL_PROXY support.
|
|
110
|
+
return new EnvHttpProxyAgent({
|
|
111
|
+
httpProxy: getProxyForProtocol('http'),
|
|
112
|
+
httpsProxy: getProxyForProtocol('https')
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function getProxyForProtocol(protocol: string): string | undefined {
|
|
117
|
+
return (
|
|
118
|
+
process.env[`${protocol.toLowerCase()}_proxy`] ??
|
|
119
|
+
process.env[`${protocol.toUpperCase()}_PROXY`] ??
|
|
120
|
+
process.env[`all_proxy`] ??
|
|
121
|
+
process.env[`ALL_PROXY`]
|
|
122
|
+
);
|
|
123
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AbstractStreamingSyncImplementation,
|
|
3
|
+
AbstractStreamingSyncImplementationOptions,
|
|
4
|
+
LockOptions,
|
|
5
|
+
LockType
|
|
6
|
+
} from '@powersync/common';
|
|
7
|
+
import { Mutex } from 'async-mutex';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Global locks which prevent multiple instances from syncing
|
|
11
|
+
* concurrently.
|
|
12
|
+
*/
|
|
13
|
+
const LOCKS = new Map<string, Map<LockType, Mutex>>();
|
|
14
|
+
|
|
15
|
+
const lockTypes = new Set(Object.values(LockType));
|
|
16
|
+
|
|
17
|
+
export class NodeStreamingSyncImplementation extends AbstractStreamingSyncImplementation {
|
|
18
|
+
locks: Map<LockType, Mutex>;
|
|
19
|
+
|
|
20
|
+
constructor(options: AbstractStreamingSyncImplementationOptions) {
|
|
21
|
+
super(options);
|
|
22
|
+
this.initLocks();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Configures global locks on sync process
|
|
27
|
+
*/
|
|
28
|
+
initLocks() {
|
|
29
|
+
const { identifier } = this.options;
|
|
30
|
+
if (identifier && LOCKS.has(identifier)) {
|
|
31
|
+
this.locks = LOCKS.get(identifier)!;
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
this.locks = new Map<LockType, Mutex>();
|
|
36
|
+
this.locks.set(LockType.CRUD, new Mutex());
|
|
37
|
+
this.locks.set(LockType.SYNC, new Mutex());
|
|
38
|
+
|
|
39
|
+
if (identifier) {
|
|
40
|
+
LOCKS.set(identifier, this.locks);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
obtainLock<T>(lockOptions: LockOptions<T>): Promise<T> {
|
|
45
|
+
const lock = this.locks.get(lockOptions.type);
|
|
46
|
+
if (!lock) {
|
|
47
|
+
throw new Error(`Lock type ${lockOptions.type} not found`);
|
|
48
|
+
}
|
|
49
|
+
return lock.runExclusive(async () => {
|
|
50
|
+
if (lockOptions.signal?.aborted) {
|
|
51
|
+
throw new Error('Aborted');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return lockOptions.callback();
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// NOTE! Do not import this file directly! We have a rollup plugin that rewrites imports to modules.js to this file when
|
|
2
|
+
// bundling to CommonJS.
|
|
3
|
+
export const isBundledToCommonJs: boolean = true;
|
|
4
|
+
|
|
5
|
+
export async function dynamicImport(path: string) {
|
|
6
|
+
return require(path);
|
|
7
|
+
}
|
package/src/worker.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './db/SqliteWorker.js';
|