@powersync/node 0.18.2 → 0.18.3
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/bundle.cjs +42 -73
- package/dist/bundle.cjs.map +1 -1
- package/lib/db/RemoteConnection.d.ts +0 -1
- package/lib/db/RemoteConnection.js +0 -1
- package/lib/db/RemoteConnection.js.map +1 -1
- package/lib/db/WorkerConnectionPool.d.ts +4 -5
- package/lib/db/WorkerConnectionPool.js +43 -73
- package/lib/db/WorkerConnectionPool.js.map +1 -1
- package/package.json +3 -3
- package/src/db/RemoteConnection.ts +0 -2
- package/src/db/WorkerConnectionPool.ts +45 -76
package/dist/bundle.cjs
CHANGED
|
@@ -8,7 +8,6 @@ var Comlink = require('comlink');
|
|
|
8
8
|
var fs = require('node:fs/promises');
|
|
9
9
|
var path = require('node:path');
|
|
10
10
|
var node_worker_threads = require('node:worker_threads');
|
|
11
|
-
var node_async_hooks = require('node:async_hooks');
|
|
12
11
|
var fs$1 = require('fs');
|
|
13
12
|
var path$1 = require('path');
|
|
14
13
|
|
|
@@ -150,7 +149,6 @@ class NodeStreamingSyncImplementation extends common.AbstractStreamingSyncImplem
|
|
|
150
149
|
* A PowerSync database connection implemented with RPC calls to a background worker.
|
|
151
150
|
*/
|
|
152
151
|
class BaseRemoteConnection {
|
|
153
|
-
isBusy = false;
|
|
154
152
|
worker;
|
|
155
153
|
comlink;
|
|
156
154
|
database;
|
|
@@ -246,10 +244,8 @@ const defaultDatabaseImplementation = {
|
|
|
246
244
|
class WorkerConnectionPool extends common.BaseObserver {
|
|
247
245
|
options;
|
|
248
246
|
name;
|
|
249
|
-
readConnections;
|
|
250
247
|
writeConnection;
|
|
251
|
-
|
|
252
|
-
writeQueue = [];
|
|
248
|
+
readConnections;
|
|
253
249
|
constructor(options) {
|
|
254
250
|
super();
|
|
255
251
|
if (options.readWorkerCount != null && options.readWorkerCount < 1) {
|
|
@@ -331,94 +327,67 @@ class WorkerConnectionPool extends common.BaseObserver {
|
|
|
331
327
|
return connection;
|
|
332
328
|
};
|
|
333
329
|
// Open the writer first to avoid multiple threads enabling WAL concurrently (causing "database is locked" errors).
|
|
334
|
-
this.writeConnection = await openWorker(true);
|
|
330
|
+
this.writeConnection = new common.Semaphore([await openWorker(true)]);
|
|
335
331
|
const createWorkers = [];
|
|
336
332
|
const amountOfReaders = this.options.readWorkerCount ?? READ_CONNECTIONS;
|
|
337
333
|
for (let i = 0; i < amountOfReaders; i++) {
|
|
338
334
|
createWorkers.push(openWorker(false));
|
|
339
335
|
}
|
|
340
|
-
this.readConnections = await Promise.all(createWorkers);
|
|
336
|
+
this.readConnections = new common.Semaphore(await Promise.all(createWorkers));
|
|
341
337
|
}
|
|
342
338
|
async close() {
|
|
343
|
-
await this.writeConnection.
|
|
344
|
-
|
|
345
|
-
|
|
339
|
+
const { item: writeConnection, release: returnWrite } = await this.writeConnection.requestOne();
|
|
340
|
+
const { items: readers, release: returnReaders } = await this.readConnections.requestAll();
|
|
341
|
+
try {
|
|
342
|
+
await writeConnection.close();
|
|
343
|
+
await Promise.all(readers.map((r) => r.close()));
|
|
344
|
+
}
|
|
345
|
+
finally {
|
|
346
|
+
returnWrite();
|
|
347
|
+
returnReaders();
|
|
346
348
|
}
|
|
347
349
|
}
|
|
348
|
-
readLock(fn,
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
});
|
|
353
|
-
const connection = this.readConnections.find((connection) => !connection.isBusy);
|
|
354
|
-
if (connection) {
|
|
355
|
-
connection.isBusy = true;
|
|
356
|
-
resolveConnectionPromise(connection);
|
|
350
|
+
async readLock(fn, options) {
|
|
351
|
+
const lease = await this.readConnections.requestOne(common.timeoutSignal(options?.timeoutMs));
|
|
352
|
+
try {
|
|
353
|
+
return await fn(lease.item);
|
|
357
354
|
}
|
|
358
|
-
|
|
359
|
-
|
|
355
|
+
finally {
|
|
356
|
+
lease.release();
|
|
360
357
|
}
|
|
361
|
-
|
|
362
|
-
|
|
358
|
+
}
|
|
359
|
+
async writeLock(fn, options) {
|
|
360
|
+
const { item, release } = await this.writeConnection.requestOne(common.timeoutSignal(options?.timeoutMs));
|
|
361
|
+
try {
|
|
363
362
|
try {
|
|
364
|
-
return await fn(
|
|
363
|
+
return await fn(item);
|
|
365
364
|
}
|
|
366
365
|
finally {
|
|
367
|
-
const
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
366
|
+
const serializedUpdates = await item.executeRaw("SELECT powersync_update_hooks('get');", []);
|
|
367
|
+
const updates = JSON.parse(serializedUpdates[0][0]);
|
|
368
|
+
if (updates.length > 0) {
|
|
369
|
+
const event = {
|
|
370
|
+
tables: updates,
|
|
371
|
+
groupedUpdates: {},
|
|
372
|
+
rawUpdates: []
|
|
373
|
+
};
|
|
374
|
+
this.iterateListeners((cb) => cb.tablesUpdated?.(event));
|
|
373
375
|
}
|
|
374
376
|
}
|
|
375
|
-
})();
|
|
376
|
-
}
|
|
377
|
-
writeLock(fn, _options) {
|
|
378
|
-
let resolveLockPromise;
|
|
379
|
-
const lockPromise = new Promise((resolve, _reject) => {
|
|
380
|
-
resolveLockPromise = node_async_hooks.AsyncResource.bind(resolve);
|
|
381
|
-
});
|
|
382
|
-
if (!this.writeConnection.isBusy) {
|
|
383
|
-
this.writeConnection.isBusy = true;
|
|
384
|
-
resolveLockPromise();
|
|
385
377
|
}
|
|
386
|
-
|
|
387
|
-
|
|
378
|
+
finally {
|
|
379
|
+
release();
|
|
388
380
|
}
|
|
389
|
-
return (async () => {
|
|
390
|
-
await lockPromise;
|
|
391
|
-
try {
|
|
392
|
-
try {
|
|
393
|
-
return await fn(this.writeConnection);
|
|
394
|
-
}
|
|
395
|
-
finally {
|
|
396
|
-
const serializedUpdates = await this.writeConnection.executeRaw("SELECT powersync_update_hooks('get');", []);
|
|
397
|
-
const updates = JSON.parse(serializedUpdates[0][0]);
|
|
398
|
-
if (updates.length > 0) {
|
|
399
|
-
const event = {
|
|
400
|
-
tables: updates,
|
|
401
|
-
groupedUpdates: {},
|
|
402
|
-
rawUpdates: []
|
|
403
|
-
};
|
|
404
|
-
this.iterateListeners((cb) => cb.tablesUpdated?.(event));
|
|
405
|
-
}
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
finally {
|
|
409
|
-
const next = this.writeQueue.shift();
|
|
410
|
-
if (next) {
|
|
411
|
-
next();
|
|
412
|
-
}
|
|
413
|
-
else {
|
|
414
|
-
this.writeConnection.isBusy = false;
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
})();
|
|
418
381
|
}
|
|
419
382
|
async refreshSchema() {
|
|
420
|
-
await this.
|
|
421
|
-
await
|
|
383
|
+
await this.writeLock((l) => l.refreshSchema());
|
|
384
|
+
const { items, release } = await this.readConnections.requestAll();
|
|
385
|
+
try {
|
|
386
|
+
await Promise.all(items.map((c) => c.refreshSchema()));
|
|
387
|
+
}
|
|
388
|
+
finally {
|
|
389
|
+
release();
|
|
390
|
+
}
|
|
422
391
|
}
|
|
423
392
|
}
|
|
424
393
|
class WorkerPoolDatabaseAdapter extends common.DBAdapterDefaultMixin(WorkerConnectionPool) {
|
package/dist/bundle.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundle.cjs","sources":["../lib/sync/stream/NodeRemote.js","../lib/sync/stream/NodeStreamingSyncImplementation.js","../lib/db/RemoteConnection.js","../lib/db/WorkerConnectionPool.js","../lib/db/PowerSyncDatabase.js","../lib/attachments/NodeFileSystemAdapter.js"],"sourcesContent":["import * as os from 'node:os';\nimport { AbstractRemote, DEFAULT_REMOTE_LOGGER, FetchImplementationProvider } from '@powersync/common';\nimport { BSON } from 'bson';\nimport { EnvHttpProxyAgent, getGlobalDispatcher, ProxyAgent, WebSocket as UndiciWebSocket } from 'undici';\nexport const STREAMING_POST_TIMEOUT_MS = 30_000;\nclass NodeFetchProvider extends FetchImplementationProvider {\n getFetch() {\n return fetch.bind(globalThis);\n }\n}\nexport class NodeRemote extends AbstractRemote {\n connector;\n logger;\n wsDispatcher;\n constructor(connector, logger = DEFAULT_REMOTE_LOGGER, options) {\n const fetchDispatcher = options?.dispatcher ?? defaultFetchDispatcher();\n super(connector, logger, {\n fetchImplementation: options?.fetchImplementation ?? new NodeFetchProvider(),\n fetchOptions: {\n dispatcher: fetchDispatcher\n },\n ...(options ?? {})\n });\n this.connector = connector;\n this.logger = logger;\n this.wsDispatcher = options?.dispatcher;\n }\n createSocket(url) {\n // Create dedicated dispatcher for this WebSocket\n const baseDispatcher = this.getWebsocketDispatcher(url);\n // Create WebSocket with dedicated dispatcher\n const ws = new UndiciWebSocket(url, {\n dispatcher: baseDispatcher,\n headers: {\n 'User-Agent': this.getUserAgent()\n }\n });\n return ws;\n }\n getWebsocketDispatcher(url) {\n if (this.wsDispatcher != null) {\n return this.wsDispatcher;\n }\n const protocol = new URL(url).protocol.replace(':', '');\n const proxy = getProxyForProtocol(protocol);\n if (proxy != null) {\n return new ProxyAgent(proxy);\n }\n else {\n return getGlobalDispatcher();\n }\n }\n getUserAgent() {\n return [\n super.getUserAgent(),\n `powersync-node`,\n `node/${process.versions.node}`,\n `${os.platform()}/${os.release()}`\n ].join(' ');\n }\n async getBSON() {\n return BSON;\n }\n}\nfunction defaultFetchDispatcher() {\n // EnvHttpProxyAgent automatically uses HTTP_PROXY, HTTPS_PROXY and NO_PROXY env vars by default.\n // We add ALL_PROXY support.\n return new EnvHttpProxyAgent({\n httpProxy: getProxyForProtocol('http'),\n httpsProxy: getProxyForProtocol('https')\n });\n}\nfunction getProxyForProtocol(protocol) {\n return (process.env[`${protocol.toLowerCase()}_proxy`] ??\n process.env[`${protocol.toUpperCase()}_PROXY`] ??\n process.env[`all_proxy`] ??\n process.env[`ALL_PROXY`]);\n}\n//# sourceMappingURL=NodeRemote.js.map","import { AbstractStreamingSyncImplementation, LockType, Mutex } from '@powersync/common';\n/**\n * Global locks which prevent multiple instances from syncing\n * concurrently.\n */\nconst LOCKS = new Map();\nexport class NodeStreamingSyncImplementation extends AbstractStreamingSyncImplementation {\n locks;\n constructor(options) {\n super(options);\n this.initLocks();\n }\n /**\n * Configures global locks on sync process\n */\n initLocks() {\n const { identifier } = this.options;\n if (identifier && LOCKS.has(identifier)) {\n this.locks = LOCKS.get(identifier);\n return;\n }\n this.locks = new Map();\n this.locks.set(LockType.CRUD, new Mutex());\n this.locks.set(LockType.SYNC, new Mutex());\n if (identifier) {\n LOCKS.set(identifier, this.locks);\n }\n }\n obtainLock(lockOptions) {\n const lock = this.locks.get(lockOptions.type);\n if (!lock) {\n throw new Error(`Lock type ${lockOptions.type} not found`);\n }\n return lock.runExclusive(async () => {\n return lockOptions.callback();\n }, lockOptions.signal);\n }\n}\n//# sourceMappingURL=NodeStreamingSyncImplementation.js.map","import { ConnectionClosedError, DBGetUtilsDefaultMixin } from '@powersync/common';\nimport { releaseProxy } from 'comlink';\n/**\n * A PowerSync database connection implemented with RPC calls to a background worker.\n */\nclass BaseRemoteConnection {\n isBusy = false;\n worker;\n comlink;\n database;\n notifyWorkerClosed = new AbortController();\n constructor(worker, comlink, database) {\n this.worker = worker;\n this.comlink = comlink;\n this.database = database;\n this.worker.once('exit', (_) => {\n this.notifyWorkerClosed.abort();\n });\n }\n /**\n * Runs the inner function, but appends the stack trace where this function was called. This is useful for workers\n * because stack traces from worker errors are otherwise unrelated to the application issue that has caused them.\n */\n withRemote(inner) {\n const trace = {};\n Error.captureStackTrace(trace);\n const controller = this.notifyWorkerClosed;\n return new Promise((resolve, reject) => {\n if (controller.signal.aborted) {\n reject(new ConnectionClosedError('Called operation on closed remote'));\n }\n function handleAbort() {\n reject(new ConnectionClosedError('Remote peer closed with request in flight'));\n }\n function completePromise(action) {\n controller.signal.removeEventListener('abort', handleAbort);\n action();\n }\n controller.signal.addEventListener('abort', handleAbort);\n inner()\n .then((data) => completePromise(() => resolve(data)))\n .catch((e) => {\n if (e instanceof Error && e.stack) {\n e.stack += trace.stack;\n }\n return completePromise(() => reject(e));\n });\n });\n }\n executeBatch(query, params = []) {\n return this.withRemote(async () => {\n const result = await this.database.executeBatch(query, params ?? []);\n return BaseRemoteConnection.wrapQueryResult(result);\n });\n }\n execute(query, params) {\n return this.withRemote(async () => {\n const result = await this.database.execute(query, params ?? []);\n return BaseRemoteConnection.wrapQueryResult(result);\n });\n }\n executeRaw(query, params) {\n return this.withRemote(async () => {\n return await this.database.executeRaw(query, params ?? []);\n });\n }\n async refreshSchema() {\n await this.execute(\"pragma table_info('sqlite_master')\");\n }\n async close() {\n await this.database.close();\n this.database[releaseProxy]();\n this.comlink[releaseProxy]();\n await this.worker.terminate();\n }\n static wrapQueryResult(result) {\n let rows = undefined;\n if (result.rows) {\n rows = {\n ...result.rows,\n item: (idx) => result.rows?._array[idx]\n };\n }\n return {\n ...result,\n rows\n };\n }\n}\nexport class RemoteConnection extends DBGetUtilsDefaultMixin(BaseRemoteConnection) {\n}\n//# sourceMappingURL=RemoteConnection.js.map","import * as Comlink from 'comlink';\nimport fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { Worker } from 'node:worker_threads';\nimport { BaseObserver, DBAdapterDefaultMixin } from '@powersync/common';\nimport { AsyncResource } from 'node:async_hooks';\nimport { isBundledToCommonJs } from '../utils/modules.js';\nimport { RemoteConnection } from './RemoteConnection.js';\nconst READ_CONNECTIONS = 5;\nconst defaultDatabaseImplementation = {\n type: 'better-sqlite3'\n};\n/**\n * Adapter for better-sqlite3\n */\nexport class WorkerConnectionPool extends BaseObserver {\n options;\n name;\n readConnections;\n writeConnection;\n readQueue = [];\n writeQueue = [];\n constructor(options) {\n super();\n if (options.readWorkerCount != null && options.readWorkerCount < 1) {\n throw `Needs at least one worker for reads, got ${options.readWorkerCount}`;\n }\n this.options = options;\n this.name = options.dbFilename;\n }\n async initialize() {\n let dbFilePath = this.options.dbFilename;\n if (this.options.dbLocation !== undefined) {\n // Make sure the dbLocation exists, we get a TypeError from better-sqlite3 otherwise.\n let directoryExists = false;\n try {\n const stat = await fs.stat(this.options.dbLocation);\n directoryExists = stat.isDirectory();\n }\n catch (_) {\n // If we can't even stat, the directory won't be accessible to SQLite either.\n }\n if (!directoryExists) {\n throw new Error(`The dbLocation directory at \"${this.options.dbLocation}\" does not exist. Please create it before opening the PowerSync database!`);\n }\n dbFilePath = path.join(this.options.dbLocation, dbFilePath);\n }\n const openWorker = async (isWriter) => {\n const isCommonJsModule = isBundledToCommonJs;\n let worker;\n const workerName = isWriter ? `write ${dbFilePath}` : `read ${dbFilePath}`;\n const workerFactory = this.options.openWorker ?? ((...args) => new Worker(...args));\n if (isCommonJsModule) {\n worker = workerFactory(path.resolve(__dirname, 'DefaultWorker.cjs'), { name: workerName });\n }\n else {\n worker = workerFactory(new URL('./DefaultWorker.js', import.meta.url), { name: workerName });\n }\n const listeners = new WeakMap();\n const comlink = Comlink.wrap({\n postMessage: worker.postMessage.bind(worker),\n addEventListener: (type, listener) => {\n let resolved = 'handleEvent' in listener ? listener.handleEvent.bind(listener) : listener;\n // Comlink wants message events, but the message event on workers in Node returns the data only.\n if (type === 'message') {\n const original = resolved;\n resolved = (data) => {\n original({ data });\n };\n }\n listeners.set(listener, resolved);\n worker.addListener(type, resolved);\n },\n removeEventListener: (type, listener) => {\n const resolved = listeners.get(listener);\n if (!resolved) {\n return;\n }\n worker.removeListener(type, resolved);\n }\n });\n worker.once('error', (e) => {\n console.error('Unexpected PowerSync database worker error', e);\n });\n const database = (await comlink.open({\n path: dbFilePath,\n isWriter,\n implementation: this.options.implementation ?? defaultDatabaseImplementation\n }));\n if (isWriter) {\n await database.execute(\"SELECT powersync_update_hooks('install');\", []);\n }\n const connection = new RemoteConnection(worker, comlink, database);\n if (this.options.initializeConnection) {\n await this.options.initializeConnection(connection, isWriter);\n }\n if (!isWriter) {\n await connection.execute('pragma query_only = true');\n }\n else {\n // We only need to enable this on the writer connection.\n // We can get `database is locked` errors if we enable this on concurrently opening read connections.\n await connection.execute('pragma journal_mode = WAL');\n }\n return connection;\n };\n // Open the writer first to avoid multiple threads enabling WAL concurrently (causing \"database is locked\" errors).\n this.writeConnection = await openWorker(true);\n const createWorkers = [];\n const amountOfReaders = this.options.readWorkerCount ?? READ_CONNECTIONS;\n for (let i = 0; i < amountOfReaders; i++) {\n createWorkers.push(openWorker(false));\n }\n this.readConnections = await Promise.all(createWorkers);\n }\n async close() {\n await this.writeConnection.close();\n for (const connection of this.readConnections) {\n await connection.close();\n }\n }\n readLock(fn, _options) {\n let resolveConnectionPromise;\n const connectionPromise = new Promise((resolve, _reject) => {\n resolveConnectionPromise = AsyncResource.bind(resolve);\n });\n const connection = this.readConnections.find((connection) => !connection.isBusy);\n if (connection) {\n connection.isBusy = true;\n resolveConnectionPromise(connection);\n }\n else {\n this.readQueue.push(resolveConnectionPromise);\n }\n return (async () => {\n const connection = await connectionPromise;\n try {\n return await fn(connection);\n }\n finally {\n const next = this.readQueue.shift();\n if (next) {\n next(connection);\n }\n else {\n connection.isBusy = false;\n }\n }\n })();\n }\n writeLock(fn, _options) {\n let resolveLockPromise;\n const lockPromise = new Promise((resolve, _reject) => {\n resolveLockPromise = AsyncResource.bind(resolve);\n });\n if (!this.writeConnection.isBusy) {\n this.writeConnection.isBusy = true;\n resolveLockPromise();\n }\n else {\n this.writeQueue.push(resolveLockPromise);\n }\n return (async () => {\n await lockPromise;\n try {\n try {\n return await fn(this.writeConnection);\n }\n finally {\n const serializedUpdates = await this.writeConnection.executeRaw(\"SELECT powersync_update_hooks('get');\", []);\n const updates = JSON.parse(serializedUpdates[0][0]);\n if (updates.length > 0) {\n const event = {\n tables: updates,\n groupedUpdates: {},\n rawUpdates: []\n };\n this.iterateListeners((cb) => cb.tablesUpdated?.(event));\n }\n }\n }\n finally {\n const next = this.writeQueue.shift();\n if (next) {\n next();\n }\n else {\n this.writeConnection.isBusy = false;\n }\n }\n })();\n }\n async refreshSchema() {\n await this.writeConnection.refreshSchema();\n await Promise.all(this.readConnections.map((c) => c.refreshSchema()));\n }\n}\nexport class WorkerPoolDatabaseAdapter extends DBAdapterDefaultMixin(WorkerConnectionPool) {\n}\n//# sourceMappingURL=WorkerConnectionPool.js.map","import { AbstractPowerSyncDatabase, SqliteBucketStorage } from '@powersync/common';\nimport { NodeRemote } from '../sync/stream/NodeRemote.js';\nimport { NodeStreamingSyncImplementation } from '../sync/stream/NodeStreamingSyncImplementation.js';\nimport { WorkerPoolDatabaseAdapter } from './WorkerConnectionPool.js';\n/**\n * A PowerSync database which provides SQLite functionality\n * which is automatically synced.\n *\n * @example\n * ```typescript\n * export const db = new PowerSyncDatabase({\n * schema: AppSchema,\n * database: {\n * dbFilename: 'example.db'\n * }\n * });\n * ```\n */\nexport class PowerSyncDatabase extends AbstractPowerSyncDatabase {\n constructor(options) {\n super(options);\n }\n async _initialize() {\n if ('initialize' in this.database) {\n await this.database.initialize();\n }\n }\n /**\n * Opens a DBAdapter using better-sqlite3 as the default SQLite open factory.\n */\n openDBAdapter(options) {\n return new WorkerPoolDatabaseAdapter(options.database);\n }\n generateBucketStorageAdapter() {\n return new SqliteBucketStorage(this.database, this.logger);\n }\n connect(connector, options) {\n return super.connect(connector, options);\n }\n generateSyncStreamImplementation(connector, options) {\n const logger = this.logger;\n const remote = new NodeRemote(connector, logger, {\n dispatcher: options.dispatcher,\n ...this.options.remoteOptions\n });\n return new NodeStreamingSyncImplementation({\n adapter: this.bucketStorageAdapter,\n remote,\n uploadCrud: async () => {\n await this.waitForReady();\n await connector.uploadData(this);\n },\n ...options,\n identifier: this.database.name,\n logger\n });\n }\n}\n//# sourceMappingURL=PowerSyncDatabase.js.map","import { promises as fs } from 'fs';\nimport * as path from 'path';\nimport { EncodingType } from '@powersync/common';\n/**\n * NodeFileSystemAdapter implements LocalStorageAdapter using Node.js filesystem.\n * Suitable for Node.js environments and Electron applications.\n */\nexport class NodeFileSystemAdapter {\n storageDirectory;\n constructor(storageDirectory = './user_data') {\n this.storageDirectory = storageDirectory;\n }\n async initialize() {\n const dir = path.resolve(this.storageDirectory);\n await fs.mkdir(dir, { recursive: true });\n }\n async clear() {\n const dir = path.resolve(this.storageDirectory);\n await fs.rmdir(dir, { recursive: true });\n }\n getLocalUri(filename) {\n return path.join(path.resolve(this.storageDirectory), filename);\n }\n async uploadFile(filePath, data, options) {\n const buffer = Buffer.from(data);\n await fs.writeFile(filePath, buffer, {\n encoding: options?.encoding\n });\n }\n async downloadFile(filePath) {\n const data = await fs.readFile(filePath);\n return new Blob([new Uint8Array(data)]);\n }\n async saveFile(filePath, data, options) {\n let buffer;\n if (typeof data === 'string') {\n buffer = Buffer.from(data, options?.encoding ?? EncodingType.Base64);\n }\n else {\n buffer = Buffer.from(data);\n }\n await fs.writeFile(filePath, buffer);\n return buffer.length;\n }\n async readFile(filePath, options) {\n const data = await fs.readFile(filePath);\n if (options?.encoding === EncodingType.Base64) {\n return Buffer.from(data.toString(), 'base64').buffer;\n }\n else {\n return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);\n }\n }\n async deleteFile(path, options) {\n await fs.unlink(path).catch((err) => {\n if (err.code !== 'ENOENT') {\n throw err;\n }\n });\n }\n async fileExists(filePath) {\n try {\n await fs.access(filePath);\n return true;\n }\n catch {\n return false;\n }\n }\n async makeDir(path) {\n await fs.mkdir(path, { recursive: true });\n }\n async rmDir(path) {\n await fs.rmdir(path, { recursive: true });\n }\n}\n//# sourceMappingURL=NodeFileSystemAdapter.js.map"],"names":["FetchImplementationProvider","AbstractRemote","DEFAULT_REMOTE_LOGGER","UndiciWebSocket","ProxyAgent","getGlobalDispatcher","os","BSON","EnvHttpProxyAgent","AbstractStreamingSyncImplementation","LockType","Mutex","ConnectionClosedError","releaseProxy","DBGetUtilsDefaultMixin","BaseObserver","path","Worker","Comlink","AsyncResource","DBAdapterDefaultMixin","AbstractPowerSyncDatabase","SqliteBucketStorage","fs","EncodingType"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,MAAM,iBAAiB,SAASA,kCAA2B,CAAC;AAC5D,IAAI,QAAQ,GAAG;AACf,QAAQ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,IAAI,MAAM,UAAU,CAAC,QAAQ,EAAE;AAC/B,QAAQ,IAAI;AACZ,YAAY,MAAMA,aAAE,CAAC,MAAM,CAAC,QAAQ,CAAC;AACrC,YAAY,OAAO,IAAI;AACvB,QAAQ;AACR,QAAQ,MAAM;AACd,YAAY,OAAO,KAAK;AACxB,QAAQ;AACR,IAAI;AACJ,IAAI,MAAM,OAAO,CAAC,IAAI,EAAE;AACxB,QAAQ,MAAMA,aAAE,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AACjD,IAAI;AACJ,IAAI,MAAM,KAAK,CAAC,IAAI,EAAE;AACtB,QAAQ,MAAMA,aAAE,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AACjD,IAAI;AACJ;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"bundle.cjs","sources":["../lib/sync/stream/NodeRemote.js","../lib/sync/stream/NodeStreamingSyncImplementation.js","../lib/db/RemoteConnection.js","../lib/db/WorkerConnectionPool.js","../lib/db/PowerSyncDatabase.js","../lib/attachments/NodeFileSystemAdapter.js"],"sourcesContent":["import * as os from 'node:os';\nimport { AbstractRemote, DEFAULT_REMOTE_LOGGER, FetchImplementationProvider } from '@powersync/common';\nimport { BSON } from 'bson';\nimport { EnvHttpProxyAgent, getGlobalDispatcher, ProxyAgent, WebSocket as UndiciWebSocket } from 'undici';\nexport const STREAMING_POST_TIMEOUT_MS = 30_000;\nclass NodeFetchProvider extends FetchImplementationProvider {\n getFetch() {\n return fetch.bind(globalThis);\n }\n}\nexport class NodeRemote extends AbstractRemote {\n connector;\n logger;\n wsDispatcher;\n constructor(connector, logger = DEFAULT_REMOTE_LOGGER, options) {\n const fetchDispatcher = options?.dispatcher ?? defaultFetchDispatcher();\n super(connector, logger, {\n fetchImplementation: options?.fetchImplementation ?? new NodeFetchProvider(),\n fetchOptions: {\n dispatcher: fetchDispatcher\n },\n ...(options ?? {})\n });\n this.connector = connector;\n this.logger = logger;\n this.wsDispatcher = options?.dispatcher;\n }\n createSocket(url) {\n // Create dedicated dispatcher for this WebSocket\n const baseDispatcher = this.getWebsocketDispatcher(url);\n // Create WebSocket with dedicated dispatcher\n const ws = new UndiciWebSocket(url, {\n dispatcher: baseDispatcher,\n headers: {\n 'User-Agent': this.getUserAgent()\n }\n });\n return ws;\n }\n getWebsocketDispatcher(url) {\n if (this.wsDispatcher != null) {\n return this.wsDispatcher;\n }\n const protocol = new URL(url).protocol.replace(':', '');\n const proxy = getProxyForProtocol(protocol);\n if (proxy != null) {\n return new ProxyAgent(proxy);\n }\n else {\n return getGlobalDispatcher();\n }\n }\n getUserAgent() {\n return [\n super.getUserAgent(),\n `powersync-node`,\n `node/${process.versions.node}`,\n `${os.platform()}/${os.release()}`\n ].join(' ');\n }\n async getBSON() {\n return BSON;\n }\n}\nfunction defaultFetchDispatcher() {\n // EnvHttpProxyAgent automatically uses HTTP_PROXY, HTTPS_PROXY and NO_PROXY env vars by default.\n // We add ALL_PROXY support.\n return new EnvHttpProxyAgent({\n httpProxy: getProxyForProtocol('http'),\n httpsProxy: getProxyForProtocol('https')\n });\n}\nfunction getProxyForProtocol(protocol) {\n return (process.env[`${protocol.toLowerCase()}_proxy`] ??\n process.env[`${protocol.toUpperCase()}_PROXY`] ??\n process.env[`all_proxy`] ??\n process.env[`ALL_PROXY`]);\n}\n//# sourceMappingURL=NodeRemote.js.map","import { AbstractStreamingSyncImplementation, LockType, Mutex } from '@powersync/common';\n/**\n * Global locks which prevent multiple instances from syncing\n * concurrently.\n */\nconst LOCKS = new Map();\nexport class NodeStreamingSyncImplementation extends AbstractStreamingSyncImplementation {\n locks;\n constructor(options) {\n super(options);\n this.initLocks();\n }\n /**\n * Configures global locks on sync process\n */\n initLocks() {\n const { identifier } = this.options;\n if (identifier && LOCKS.has(identifier)) {\n this.locks = LOCKS.get(identifier);\n return;\n }\n this.locks = new Map();\n this.locks.set(LockType.CRUD, new Mutex());\n this.locks.set(LockType.SYNC, new Mutex());\n if (identifier) {\n LOCKS.set(identifier, this.locks);\n }\n }\n obtainLock(lockOptions) {\n const lock = this.locks.get(lockOptions.type);\n if (!lock) {\n throw new Error(`Lock type ${lockOptions.type} not found`);\n }\n return lock.runExclusive(async () => {\n return lockOptions.callback();\n }, lockOptions.signal);\n }\n}\n//# sourceMappingURL=NodeStreamingSyncImplementation.js.map","import { ConnectionClosedError, DBGetUtilsDefaultMixin } from '@powersync/common';\nimport { releaseProxy } from 'comlink';\n/**\n * A PowerSync database connection implemented with RPC calls to a background worker.\n */\nclass BaseRemoteConnection {\n worker;\n comlink;\n database;\n notifyWorkerClosed = new AbortController();\n constructor(worker, comlink, database) {\n this.worker = worker;\n this.comlink = comlink;\n this.database = database;\n this.worker.once('exit', (_) => {\n this.notifyWorkerClosed.abort();\n });\n }\n /**\n * Runs the inner function, but appends the stack trace where this function was called. This is useful for workers\n * because stack traces from worker errors are otherwise unrelated to the application issue that has caused them.\n */\n withRemote(inner) {\n const trace = {};\n Error.captureStackTrace(trace);\n const controller = this.notifyWorkerClosed;\n return new Promise((resolve, reject) => {\n if (controller.signal.aborted) {\n reject(new ConnectionClosedError('Called operation on closed remote'));\n }\n function handleAbort() {\n reject(new ConnectionClosedError('Remote peer closed with request in flight'));\n }\n function completePromise(action) {\n controller.signal.removeEventListener('abort', handleAbort);\n action();\n }\n controller.signal.addEventListener('abort', handleAbort);\n inner()\n .then((data) => completePromise(() => resolve(data)))\n .catch((e) => {\n if (e instanceof Error && e.stack) {\n e.stack += trace.stack;\n }\n return completePromise(() => reject(e));\n });\n });\n }\n executeBatch(query, params = []) {\n return this.withRemote(async () => {\n const result = await this.database.executeBatch(query, params ?? []);\n return BaseRemoteConnection.wrapQueryResult(result);\n });\n }\n execute(query, params) {\n return this.withRemote(async () => {\n const result = await this.database.execute(query, params ?? []);\n return BaseRemoteConnection.wrapQueryResult(result);\n });\n }\n executeRaw(query, params) {\n return this.withRemote(async () => {\n return await this.database.executeRaw(query, params ?? []);\n });\n }\n async refreshSchema() {\n await this.execute(\"pragma table_info('sqlite_master')\");\n }\n async close() {\n await this.database.close();\n this.database[releaseProxy]();\n this.comlink[releaseProxy]();\n await this.worker.terminate();\n }\n static wrapQueryResult(result) {\n let rows = undefined;\n if (result.rows) {\n rows = {\n ...result.rows,\n item: (idx) => result.rows?._array[idx]\n };\n }\n return {\n ...result,\n rows\n };\n }\n}\nexport class RemoteConnection extends DBGetUtilsDefaultMixin(BaseRemoteConnection) {\n}\n//# sourceMappingURL=RemoteConnection.js.map","import * as Comlink from 'comlink';\nimport fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { Worker } from 'node:worker_threads';\nimport { BaseObserver, DBAdapterDefaultMixin, Semaphore, timeoutSignal } from '@powersync/common';\nimport { isBundledToCommonJs } from '../utils/modules.js';\nimport { RemoteConnection } from './RemoteConnection.js';\nconst READ_CONNECTIONS = 5;\nconst defaultDatabaseImplementation = {\n type: 'better-sqlite3'\n};\n/**\n * Adapter for better-sqlite3\n */\nexport class WorkerConnectionPool extends BaseObserver {\n options;\n name;\n writeConnection;\n readConnections;\n constructor(options) {\n super();\n if (options.readWorkerCount != null && options.readWorkerCount < 1) {\n throw `Needs at least one worker for reads, got ${options.readWorkerCount}`;\n }\n this.options = options;\n this.name = options.dbFilename;\n }\n async initialize() {\n let dbFilePath = this.options.dbFilename;\n if (this.options.dbLocation !== undefined) {\n // Make sure the dbLocation exists, we get a TypeError from better-sqlite3 otherwise.\n let directoryExists = false;\n try {\n const stat = await fs.stat(this.options.dbLocation);\n directoryExists = stat.isDirectory();\n }\n catch (_) {\n // If we can't even stat, the directory won't be accessible to SQLite either.\n }\n if (!directoryExists) {\n throw new Error(`The dbLocation directory at \"${this.options.dbLocation}\" does not exist. Please create it before opening the PowerSync database!`);\n }\n dbFilePath = path.join(this.options.dbLocation, dbFilePath);\n }\n const openWorker = async (isWriter) => {\n const isCommonJsModule = isBundledToCommonJs;\n let worker;\n const workerName = isWriter ? `write ${dbFilePath}` : `read ${dbFilePath}`;\n const workerFactory = this.options.openWorker ?? ((...args) => new Worker(...args));\n if (isCommonJsModule) {\n worker = workerFactory(path.resolve(__dirname, 'DefaultWorker.cjs'), { name: workerName });\n }\n else {\n worker = workerFactory(new URL('./DefaultWorker.js', import.meta.url), { name: workerName });\n }\n const listeners = new WeakMap();\n const comlink = Comlink.wrap({\n postMessage: worker.postMessage.bind(worker),\n addEventListener: (type, listener) => {\n let resolved = 'handleEvent' in listener ? listener.handleEvent.bind(listener) : listener;\n // Comlink wants message events, but the message event on workers in Node returns the data only.\n if (type === 'message') {\n const original = resolved;\n resolved = (data) => {\n original({ data });\n };\n }\n listeners.set(listener, resolved);\n worker.addListener(type, resolved);\n },\n removeEventListener: (type, listener) => {\n const resolved = listeners.get(listener);\n if (!resolved) {\n return;\n }\n worker.removeListener(type, resolved);\n }\n });\n worker.once('error', (e) => {\n console.error('Unexpected PowerSync database worker error', e);\n });\n const database = (await comlink.open({\n path: dbFilePath,\n isWriter,\n implementation: this.options.implementation ?? defaultDatabaseImplementation\n }));\n if (isWriter) {\n await database.execute(\"SELECT powersync_update_hooks('install');\", []);\n }\n const connection = new RemoteConnection(worker, comlink, database);\n if (this.options.initializeConnection) {\n await this.options.initializeConnection(connection, isWriter);\n }\n if (!isWriter) {\n await connection.execute('pragma query_only = true');\n }\n else {\n // We only need to enable this on the writer connection.\n // We can get `database is locked` errors if we enable this on concurrently opening read connections.\n await connection.execute('pragma journal_mode = WAL');\n }\n return connection;\n };\n // Open the writer first to avoid multiple threads enabling WAL concurrently (causing \"database is locked\" errors).\n this.writeConnection = new Semaphore([await openWorker(true)]);\n const createWorkers = [];\n const amountOfReaders = this.options.readWorkerCount ?? READ_CONNECTIONS;\n for (let i = 0; i < amountOfReaders; i++) {\n createWorkers.push(openWorker(false));\n }\n this.readConnections = new Semaphore(await Promise.all(createWorkers));\n }\n async close() {\n const { item: writeConnection, release: returnWrite } = await this.writeConnection.requestOne();\n const { items: readers, release: returnReaders } = await this.readConnections.requestAll();\n try {\n await writeConnection.close();\n await Promise.all(readers.map((r) => r.close()));\n }\n finally {\n returnWrite();\n returnReaders();\n }\n }\n async readLock(fn, options) {\n const lease = await this.readConnections.requestOne(timeoutSignal(options?.timeoutMs));\n try {\n return await fn(lease.item);\n }\n finally {\n lease.release();\n }\n }\n async writeLock(fn, options) {\n const { item, release } = await this.writeConnection.requestOne(timeoutSignal(options?.timeoutMs));\n try {\n try {\n return await fn(item);\n }\n finally {\n const serializedUpdates = await item.executeRaw(\"SELECT powersync_update_hooks('get');\", []);\n const updates = JSON.parse(serializedUpdates[0][0]);\n if (updates.length > 0) {\n const event = {\n tables: updates,\n groupedUpdates: {},\n rawUpdates: []\n };\n this.iterateListeners((cb) => cb.tablesUpdated?.(event));\n }\n }\n }\n finally {\n release();\n }\n }\n async refreshSchema() {\n await this.writeLock((l) => l.refreshSchema());\n const { items, release } = await this.readConnections.requestAll();\n try {\n await Promise.all(items.map((c) => c.refreshSchema()));\n }\n finally {\n release();\n }\n }\n}\nexport class WorkerPoolDatabaseAdapter extends DBAdapterDefaultMixin(WorkerConnectionPool) {\n}\n//# sourceMappingURL=WorkerConnectionPool.js.map","import { AbstractPowerSyncDatabase, SqliteBucketStorage } from '@powersync/common';\nimport { NodeRemote } from '../sync/stream/NodeRemote.js';\nimport { NodeStreamingSyncImplementation } from '../sync/stream/NodeStreamingSyncImplementation.js';\nimport { WorkerPoolDatabaseAdapter } from './WorkerConnectionPool.js';\n/**\n * A PowerSync database which provides SQLite functionality\n * which is automatically synced.\n *\n * @example\n * ```typescript\n * export const db = new PowerSyncDatabase({\n * schema: AppSchema,\n * database: {\n * dbFilename: 'example.db'\n * }\n * });\n * ```\n */\nexport class PowerSyncDatabase extends AbstractPowerSyncDatabase {\n constructor(options) {\n super(options);\n }\n async _initialize() {\n if ('initialize' in this.database) {\n await this.database.initialize();\n }\n }\n /**\n * Opens a DBAdapter using better-sqlite3 as the default SQLite open factory.\n */\n openDBAdapter(options) {\n return new WorkerPoolDatabaseAdapter(options.database);\n }\n generateBucketStorageAdapter() {\n return new SqliteBucketStorage(this.database, this.logger);\n }\n connect(connector, options) {\n return super.connect(connector, options);\n }\n generateSyncStreamImplementation(connector, options) {\n const logger = this.logger;\n const remote = new NodeRemote(connector, logger, {\n dispatcher: options.dispatcher,\n ...this.options.remoteOptions\n });\n return new NodeStreamingSyncImplementation({\n adapter: this.bucketStorageAdapter,\n remote,\n uploadCrud: async () => {\n await this.waitForReady();\n await connector.uploadData(this);\n },\n ...options,\n identifier: this.database.name,\n logger\n });\n }\n}\n//# sourceMappingURL=PowerSyncDatabase.js.map","import { promises as fs } from 'fs';\nimport * as path from 'path';\nimport { EncodingType } from '@powersync/common';\n/**\n * NodeFileSystemAdapter implements LocalStorageAdapter using Node.js filesystem.\n * Suitable for Node.js environments and Electron applications.\n */\nexport class NodeFileSystemAdapter {\n storageDirectory;\n constructor(storageDirectory = './user_data') {\n this.storageDirectory = storageDirectory;\n }\n async initialize() {\n const dir = path.resolve(this.storageDirectory);\n await fs.mkdir(dir, { recursive: true });\n }\n async clear() {\n const dir = path.resolve(this.storageDirectory);\n await fs.rmdir(dir, { recursive: true });\n }\n getLocalUri(filename) {\n return path.join(path.resolve(this.storageDirectory), filename);\n }\n async uploadFile(filePath, data, options) {\n const buffer = Buffer.from(data);\n await fs.writeFile(filePath, buffer, {\n encoding: options?.encoding\n });\n }\n async downloadFile(filePath) {\n const data = await fs.readFile(filePath);\n return new Blob([new Uint8Array(data)]);\n }\n async saveFile(filePath, data, options) {\n let buffer;\n if (typeof data === 'string') {\n buffer = Buffer.from(data, options?.encoding ?? EncodingType.Base64);\n }\n else {\n buffer = Buffer.from(data);\n }\n await fs.writeFile(filePath, buffer);\n return buffer.length;\n }\n async readFile(filePath, options) {\n const data = await fs.readFile(filePath);\n if (options?.encoding === EncodingType.Base64) {\n return Buffer.from(data.toString(), 'base64').buffer;\n }\n else {\n return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);\n }\n }\n async deleteFile(path, options) {\n await fs.unlink(path).catch((err) => {\n if (err.code !== 'ENOENT') {\n throw err;\n }\n });\n }\n async fileExists(filePath) {\n try {\n await fs.access(filePath);\n return true;\n }\n catch {\n return false;\n }\n }\n async makeDir(path) {\n await fs.mkdir(path, { recursive: true });\n }\n async rmDir(path) {\n await fs.rmdir(path, { recursive: true });\n }\n}\n//# sourceMappingURL=NodeFileSystemAdapter.js.map"],"names":["FetchImplementationProvider","AbstractRemote","DEFAULT_REMOTE_LOGGER","UndiciWebSocket","ProxyAgent","getGlobalDispatcher","os","BSON","EnvHttpProxyAgent","AbstractStreamingSyncImplementation","LockType","Mutex","ConnectionClosedError","releaseProxy","DBGetUtilsDefaultMixin","BaseObserver","path","Worker","Comlink","Semaphore","timeoutSignal","DBAdapterDefaultMixin","AbstractPowerSyncDatabase","SqliteBucketStorage","fs","EncodingType"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,MAAM,iBAAiB,SAASA,kCAA2B,CAAC;AAC5D,IAAI,QAAQ,GAAG;AACf,QAAQ,OAAO,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC;AACrC,IAAI;AACJ;AACO,MAAM,UAAU,SAASC,qBAAc,CAAC;AAC/C,IAAI,SAAS;AACb,IAAI,MAAM;AACV,IAAI,YAAY;AAChB,IAAI,WAAW,CAAC,SAAS,EAAE,MAAM,GAAGC,4BAAqB,EAAE,OAAO,EAAE;AACpE,QAAQ,MAAM,eAAe,GAAG,OAAO,EAAE,UAAU,IAAI,sBAAsB,EAAE;AAC/E,QAAQ,KAAK,CAAC,SAAS,EAAE,MAAM,EAAE;AACjC,YAAY,mBAAmB,EAAE,OAAO,EAAE,mBAAmB,IAAI,IAAI,iBAAiB,EAAE;AACxF,YAAY,YAAY,EAAE;AAC1B,gBAAgB,UAAU,EAAE;AAC5B,aAAa;AACb,YAAY,IAAI,OAAO,IAAI,EAAE;AAC7B,SAAS,CAAC;AACV,QAAQ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,CAAC,QAAQ,CAAC;AACrC,YAAY,OAAO,IAAI;AACvB,QAAQ;AACR,QAAQ,MAAM;AACd,YAAY,OAAO,KAAK;AACxB,QAAQ;AACR,IAAI;AACJ,IAAI,MAAM,OAAO,CAAC,IAAI,EAAE;AACxB,QAAQ,MAAMA,aAAE,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AACjD,IAAI;AACJ,IAAI,MAAM,KAAK,CAAC,IAAI,EAAE;AACtB,QAAQ,MAAMA,aAAE,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AACjD,IAAI;AACJ;;;;;;;;;;;"}
|
|
@@ -6,7 +6,6 @@ import { AsyncDatabase, AsyncDatabaseOpener, ProxiedQueryResult } from './AsyncD
|
|
|
6
6
|
* A PowerSync database connection implemented with RPC calls to a background worker.
|
|
7
7
|
*/
|
|
8
8
|
declare class BaseRemoteConnection implements SqlExecutor {
|
|
9
|
-
isBusy: boolean;
|
|
10
9
|
private readonly worker;
|
|
11
10
|
private readonly comlink;
|
|
12
11
|
private readonly database;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RemoteConnection.js","sourceRoot":"","sources":["../../src/db/RemoteConnection.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,sBAAsB,EAIvB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,YAAY,EAAU,MAAM,SAAS,CAAC;AAI/C;;GAEG;AACH,MAAM,oBAAoB;
|
|
1
|
+
{"version":3,"file":"RemoteConnection.js","sourceRoot":"","sources":["../../src/db/RemoteConnection.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,sBAAsB,EAIvB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,YAAY,EAAU,MAAM,SAAS,CAAC;AAI/C;;GAEG;AACH,MAAM,oBAAoB;IACP,MAAM,CAAS;IACf,OAAO,CA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KAAK,CAAC,KAAK;QACT,MAAM,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;QAC5B,IAAI,CAAC,QAAQ,CAAC,YAAY,CAAC,EAAE,CAAC;QAC9B,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,EAAE,CAAC;QAC7B,MAAM,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC;IAChC,CAAC;IAED,MAAM,CAAC,eAAe,CAAC,MAA0B;QAC/C,IAAI,IAAI,GAAoC,SAAS,CAAC;QACtD,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC;YAChB,IAAI,GAAG;gBACL,GAAG,MAAM,CAAC,IAAI;gBACd,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,GAAG,CAAC;aACV,CAAC;QAClC,CAAC;QAED,OAAO;YACL,GAAG,MAAM;YACT,IAAI;SACL,CAAC;IACJ,CAAC;CACF;AAED,MAAM,OAAO,gBAAiB,SAAQ,sBAAsB,CAAC,oBAAoB,CAAC;CAA0B"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { BaseObserver, ConnectionPool, DBAdapterListener, DBLockOptions, LockContext, QueryResult, Transaction } from '@powersync/common';
|
|
2
|
+
import { RemoteConnection } from './RemoteConnection.js';
|
|
2
3
|
import { NodeSQLOpenOptions } from './options.js';
|
|
3
4
|
export type BetterSQLite3LockContext = LockContext & {
|
|
4
5
|
executeBatch(query: string, params?: any[][]): Promise<QueryResult>;
|
|
@@ -10,15 +11,13 @@ export type BetterSQLite3Transaction = Transaction & BetterSQLite3LockContext;
|
|
|
10
11
|
export declare class WorkerConnectionPool extends BaseObserver<DBAdapterListener> implements ConnectionPool {
|
|
11
12
|
private readonly options;
|
|
12
13
|
readonly name: string;
|
|
13
|
-
private readConnections;
|
|
14
14
|
private writeConnection;
|
|
15
|
-
private
|
|
16
|
-
private readonly writeQueue;
|
|
15
|
+
private readConnections;
|
|
17
16
|
constructor(options: NodeSQLOpenOptions);
|
|
18
17
|
initialize(): Promise<void>;
|
|
19
18
|
close(): Promise<void>;
|
|
20
|
-
readLock<T>(fn: (tx:
|
|
21
|
-
writeLock<T>(fn: (tx:
|
|
19
|
+
readLock<T>(fn: (tx: RemoteConnection) => Promise<T>, options?: DBLockOptions | undefined): Promise<T>;
|
|
20
|
+
writeLock<T>(fn: (tx: RemoteConnection) => Promise<T>, options?: DBLockOptions | undefined): Promise<T>;
|
|
22
21
|
refreshSchema(): Promise<void>;
|
|
23
22
|
}
|
|
24
23
|
declare const WorkerPoolDatabaseAdapter_base: (new (...args: any[]) => {
|
|
@@ -2,8 +2,7 @@ import * as Comlink from 'comlink';
|
|
|
2
2
|
import fs from 'node:fs/promises';
|
|
3
3
|
import * as path from 'node:path';
|
|
4
4
|
import { Worker } from 'node:worker_threads';
|
|
5
|
-
import { BaseObserver, DBAdapterDefaultMixin } from '@powersync/common';
|
|
6
|
-
import { AsyncResource } from 'node:async_hooks';
|
|
5
|
+
import { BaseObserver, DBAdapterDefaultMixin, Semaphore, timeoutSignal } from '@powersync/common';
|
|
7
6
|
import { isBundledToCommonJs } from '../utils/modules.js';
|
|
8
7
|
import { RemoteConnection } from './RemoteConnection.js';
|
|
9
8
|
const READ_CONNECTIONS = 5;
|
|
@@ -16,10 +15,8 @@ const defaultDatabaseImplementation = {
|
|
|
16
15
|
export class WorkerConnectionPool extends BaseObserver {
|
|
17
16
|
options;
|
|
18
17
|
name;
|
|
19
|
-
readConnections;
|
|
20
18
|
writeConnection;
|
|
21
|
-
|
|
22
|
-
writeQueue = [];
|
|
19
|
+
readConnections;
|
|
23
20
|
constructor(options) {
|
|
24
21
|
super();
|
|
25
22
|
if (options.readWorkerCount != null && options.readWorkerCount < 1) {
|
|
@@ -105,94 +102,67 @@ export class WorkerConnectionPool extends BaseObserver {
|
|
|
105
102
|
return connection;
|
|
106
103
|
};
|
|
107
104
|
// Open the writer first to avoid multiple threads enabling WAL concurrently (causing "database is locked" errors).
|
|
108
|
-
this.writeConnection = await openWorker(true);
|
|
105
|
+
this.writeConnection = new Semaphore([await openWorker(true)]);
|
|
109
106
|
const createWorkers = [];
|
|
110
107
|
const amountOfReaders = this.options.readWorkerCount ?? READ_CONNECTIONS;
|
|
111
108
|
for (let i = 0; i < amountOfReaders; i++) {
|
|
112
109
|
createWorkers.push(openWorker(false));
|
|
113
110
|
}
|
|
114
|
-
this.readConnections = await Promise.all(createWorkers);
|
|
111
|
+
this.readConnections = new Semaphore(await Promise.all(createWorkers));
|
|
115
112
|
}
|
|
116
113
|
async close() {
|
|
117
|
-
await this.writeConnection.
|
|
118
|
-
|
|
119
|
-
|
|
114
|
+
const { item: writeConnection, release: returnWrite } = await this.writeConnection.requestOne();
|
|
115
|
+
const { items: readers, release: returnReaders } = await this.readConnections.requestAll();
|
|
116
|
+
try {
|
|
117
|
+
await writeConnection.close();
|
|
118
|
+
await Promise.all(readers.map((r) => r.close()));
|
|
119
|
+
}
|
|
120
|
+
finally {
|
|
121
|
+
returnWrite();
|
|
122
|
+
returnReaders();
|
|
120
123
|
}
|
|
121
124
|
}
|
|
122
|
-
readLock(fn,
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
});
|
|
127
|
-
const connection = this.readConnections.find((connection) => !connection.isBusy);
|
|
128
|
-
if (connection) {
|
|
129
|
-
connection.isBusy = true;
|
|
130
|
-
resolveConnectionPromise(connection);
|
|
125
|
+
async readLock(fn, options) {
|
|
126
|
+
const lease = await this.readConnections.requestOne(timeoutSignal(options?.timeoutMs));
|
|
127
|
+
try {
|
|
128
|
+
return await fn(lease.item);
|
|
131
129
|
}
|
|
132
|
-
|
|
133
|
-
|
|
130
|
+
finally {
|
|
131
|
+
lease.release();
|
|
134
132
|
}
|
|
135
|
-
|
|
136
|
-
|
|
133
|
+
}
|
|
134
|
+
async writeLock(fn, options) {
|
|
135
|
+
const { item, release } = await this.writeConnection.requestOne(timeoutSignal(options?.timeoutMs));
|
|
136
|
+
try {
|
|
137
137
|
try {
|
|
138
|
-
return await fn(
|
|
138
|
+
return await fn(item);
|
|
139
139
|
}
|
|
140
140
|
finally {
|
|
141
|
-
const
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
141
|
+
const serializedUpdates = await item.executeRaw("SELECT powersync_update_hooks('get');", []);
|
|
142
|
+
const updates = JSON.parse(serializedUpdates[0][0]);
|
|
143
|
+
if (updates.length > 0) {
|
|
144
|
+
const event = {
|
|
145
|
+
tables: updates,
|
|
146
|
+
groupedUpdates: {},
|
|
147
|
+
rawUpdates: []
|
|
148
|
+
};
|
|
149
|
+
this.iterateListeners((cb) => cb.tablesUpdated?.(event));
|
|
147
150
|
}
|
|
148
151
|
}
|
|
149
|
-
})();
|
|
150
|
-
}
|
|
151
|
-
writeLock(fn, _options) {
|
|
152
|
-
let resolveLockPromise;
|
|
153
|
-
const lockPromise = new Promise((resolve, _reject) => {
|
|
154
|
-
resolveLockPromise = AsyncResource.bind(resolve);
|
|
155
|
-
});
|
|
156
|
-
if (!this.writeConnection.isBusy) {
|
|
157
|
-
this.writeConnection.isBusy = true;
|
|
158
|
-
resolveLockPromise();
|
|
159
152
|
}
|
|
160
|
-
|
|
161
|
-
|
|
153
|
+
finally {
|
|
154
|
+
release();
|
|
162
155
|
}
|
|
163
|
-
return (async () => {
|
|
164
|
-
await lockPromise;
|
|
165
|
-
try {
|
|
166
|
-
try {
|
|
167
|
-
return await fn(this.writeConnection);
|
|
168
|
-
}
|
|
169
|
-
finally {
|
|
170
|
-
const serializedUpdates = await this.writeConnection.executeRaw("SELECT powersync_update_hooks('get');", []);
|
|
171
|
-
const updates = JSON.parse(serializedUpdates[0][0]);
|
|
172
|
-
if (updates.length > 0) {
|
|
173
|
-
const event = {
|
|
174
|
-
tables: updates,
|
|
175
|
-
groupedUpdates: {},
|
|
176
|
-
rawUpdates: []
|
|
177
|
-
};
|
|
178
|
-
this.iterateListeners((cb) => cb.tablesUpdated?.(event));
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
finally {
|
|
183
|
-
const next = this.writeQueue.shift();
|
|
184
|
-
if (next) {
|
|
185
|
-
next();
|
|
186
|
-
}
|
|
187
|
-
else {
|
|
188
|
-
this.writeConnection.isBusy = false;
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
})();
|
|
192
156
|
}
|
|
193
157
|
async refreshSchema() {
|
|
194
|
-
await this.
|
|
195
|
-
await
|
|
158
|
+
await this.writeLock((l) => l.refreshSchema());
|
|
159
|
+
const { items, release } = await this.readConnections.requestAll();
|
|
160
|
+
try {
|
|
161
|
+
await Promise.all(items.map((c) => c.refreshSchema()));
|
|
162
|
+
}
|
|
163
|
+
finally {
|
|
164
|
+
release();
|
|
165
|
+
}
|
|
196
166
|
}
|
|
197
167
|
}
|
|
198
168
|
export class WorkerPoolDatabaseAdapter extends DBAdapterDefaultMixin(WorkerConnectionPool) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WorkerConnectionPool.js","sourceRoot":"","sources":["../../src/db/WorkerConnectionPool.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAClC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAE7C,OAAO,EACL,YAAY,EAGZ,qBAAqB,
|
|
1
|
+
{"version":3,"file":"WorkerConnectionPool.js","sourceRoot":"","sources":["../../src/db/WorkerConnectionPool.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAClC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAE7C,OAAO,EACL,YAAY,EAGZ,qBAAq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BAAgB,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,aAAa,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;gBAC3D,CAAC;YACH,CAAC;QACH,CAAC;gBAAS,CAAC;YACT,OAAO,EAAE,CAAC;QACZ,CAAC;IACH,CAAC;IAED,KAAK,CAAC,aAAa;QACjB,MAAM,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,aAAa,EAAE,CAAC,CAAC;QAE/C,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,UAAU,EAAE,CAAC;QACnE,IAAI,CAAC;YACH,MAAM,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC;QACzD,CAAC;gBAAS,CAAC;YACT,OAAO,EAAE,CAAC;QACZ,CAAC;IACH,CAAC;CACF;AAED,MAAM,OAAO,yBAA0B,SAAQ,qBAAqB,CAAC,oBAAoB,CAAC;CAAG"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@powersync/node",
|
|
3
|
-
"version": "0.18.
|
|
3
|
+
"version": "0.18.3",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"registry": "https://registry.npmjs.org/",
|
|
6
6
|
"access": "public"
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
},
|
|
49
49
|
"homepage": "https://docs.powersync.com/",
|
|
50
50
|
"peerDependencies": {
|
|
51
|
-
"@powersync/common": "^1.
|
|
51
|
+
"@powersync/common": "^1.51.0",
|
|
52
52
|
"better-sqlite3": "12.x"
|
|
53
53
|
},
|
|
54
54
|
"peerDependenciesMeta": {
|
|
@@ -60,7 +60,7 @@
|
|
|
60
60
|
"bson": "^6.10.4",
|
|
61
61
|
"comlink": "^4.4.2",
|
|
62
62
|
"undici": "^7.11.0",
|
|
63
|
-
"@powersync/common": "1.
|
|
63
|
+
"@powersync/common": "1.51.0"
|
|
64
64
|
},
|
|
65
65
|
"devDependencies": {
|
|
66
66
|
"@types/node": "^24.0.0",
|
|
@@ -13,8 +13,6 @@ import { AsyncDatabase, AsyncDatabaseOpener, ProxiedQueryResult } from './AsyncD
|
|
|
13
13
|
* A PowerSync database connection implemented with RPC calls to a background worker.
|
|
14
14
|
*/
|
|
15
15
|
class BaseRemoteConnection implements SqlExecutor {
|
|
16
|
-
isBusy = false;
|
|
17
|
-
|
|
18
16
|
private readonly worker: Worker;
|
|
19
17
|
private readonly comlink: Remote<AsyncDatabaseOpener>;
|
|
20
18
|
private readonly database: Remote<AsyncDatabase>;
|
|
@@ -12,10 +12,11 @@ import {
|
|
|
12
12
|
DBLockOptions,
|
|
13
13
|
LockContext,
|
|
14
14
|
QueryResult,
|
|
15
|
+
Semaphore,
|
|
16
|
+
timeoutSignal,
|
|
15
17
|
Transaction
|
|
16
18
|
} from '@powersync/common';
|
|
17
19
|
import { Remote } from 'comlink';
|
|
18
|
-
import { AsyncResource } from 'node:async_hooks';
|
|
19
20
|
import { isBundledToCommonJs } from '../utils/modules.js';
|
|
20
21
|
import { AsyncDatabase, AsyncDatabaseOpener } from './AsyncDatabase.js';
|
|
21
22
|
import { RemoteConnection } from './RemoteConnection.js';
|
|
@@ -40,11 +41,8 @@ export class WorkerConnectionPool extends BaseObserver<DBAdapterListener> implem
|
|
|
40
41
|
private readonly options: NodeSQLOpenOptions;
|
|
41
42
|
public readonly name: string;
|
|
42
43
|
|
|
43
|
-
private
|
|
44
|
-
private
|
|
45
|
-
|
|
46
|
-
private readonly readQueue: Array<(connection: RemoteConnection) => void> = [];
|
|
47
|
-
private readonly writeQueue: Array<() => void> = [];
|
|
44
|
+
private writeConnection: Semaphore<RemoteConnection>;
|
|
45
|
+
private readConnections: Semaphore<RemoteConnection>;
|
|
48
46
|
|
|
49
47
|
constructor(options: NodeSQLOpenOptions) {
|
|
50
48
|
super();
|
|
@@ -148,99 +146,70 @@ export class WorkerConnectionPool extends BaseObserver<DBAdapterListener> implem
|
|
|
148
146
|
};
|
|
149
147
|
|
|
150
148
|
// Open the writer first to avoid multiple threads enabling WAL concurrently (causing "database is locked" errors).
|
|
151
|
-
this.writeConnection = await openWorker(true);
|
|
149
|
+
this.writeConnection = new Semaphore([await openWorker(true)]);
|
|
152
150
|
const createWorkers: Promise<RemoteConnection>[] = [];
|
|
153
151
|
const amountOfReaders = this.options.readWorkerCount ?? READ_CONNECTIONS;
|
|
154
152
|
for (let i = 0; i < amountOfReaders; i++) {
|
|
155
153
|
createWorkers.push(openWorker(false));
|
|
156
154
|
}
|
|
157
|
-
this.readConnections = await Promise.all(createWorkers);
|
|
155
|
+
this.readConnections = new Semaphore(await Promise.all(createWorkers));
|
|
158
156
|
}
|
|
159
157
|
|
|
160
158
|
async close() {
|
|
161
|
-
await this.writeConnection.
|
|
162
|
-
|
|
163
|
-
|
|
159
|
+
const { item: writeConnection, release: returnWrite } = await this.writeConnection.requestOne();
|
|
160
|
+
const { items: readers, release: returnReaders } = await this.readConnections.requestAll();
|
|
161
|
+
|
|
162
|
+
try {
|
|
163
|
+
await writeConnection.close();
|
|
164
|
+
await Promise.all(readers.map((r) => r.close()));
|
|
165
|
+
} finally {
|
|
166
|
+
returnWrite();
|
|
167
|
+
returnReaders();
|
|
164
168
|
}
|
|
165
169
|
}
|
|
166
170
|
|
|
167
|
-
readLock<T>(fn: (tx:
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
const connection = this.readConnections.find((connection) => !connection.isBusy);
|
|
174
|
-
if (connection) {
|
|
175
|
-
connection.isBusy = true;
|
|
176
|
-
resolveConnectionPromise(connection);
|
|
177
|
-
} else {
|
|
178
|
-
this.readQueue.push(resolveConnectionPromise);
|
|
171
|
+
async readLock<T>(fn: (tx: RemoteConnection) => Promise<T>, options?: DBLockOptions | undefined): Promise<T> {
|
|
172
|
+
const lease = await this.readConnections.requestOne(timeoutSignal(options?.timeoutMs));
|
|
173
|
+
try {
|
|
174
|
+
return await fn(lease.item);
|
|
175
|
+
} finally {
|
|
176
|
+
lease.release();
|
|
179
177
|
}
|
|
180
|
-
|
|
181
|
-
return (async () => {
|
|
182
|
-
const connection = await connectionPromise;
|
|
183
|
-
|
|
184
|
-
try {
|
|
185
|
-
return await fn(connection);
|
|
186
|
-
} finally {
|
|
187
|
-
const next = this.readQueue.shift();
|
|
188
|
-
if (next) {
|
|
189
|
-
next(connection);
|
|
190
|
-
} else {
|
|
191
|
-
connection.isBusy = false;
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
})();
|
|
195
178
|
}
|
|
196
179
|
|
|
197
|
-
writeLock<T>(fn: (tx:
|
|
198
|
-
|
|
199
|
-
const lockPromise = new Promise<void>((resolve, _reject) => {
|
|
200
|
-
resolveLockPromise = AsyncResource.bind(resolve);
|
|
201
|
-
});
|
|
202
|
-
|
|
203
|
-
if (!this.writeConnection.isBusy) {
|
|
204
|
-
this.writeConnection.isBusy = true;
|
|
205
|
-
resolveLockPromise();
|
|
206
|
-
} else {
|
|
207
|
-
this.writeQueue.push(resolveLockPromise);
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
return (async () => {
|
|
211
|
-
await lockPromise;
|
|
180
|
+
async writeLock<T>(fn: (tx: RemoteConnection) => Promise<T>, options?: DBLockOptions | undefined): Promise<T> {
|
|
181
|
+
const { item, release } = await this.writeConnection.requestOne(timeoutSignal(options?.timeoutMs));
|
|
212
182
|
|
|
183
|
+
try {
|
|
213
184
|
try {
|
|
214
|
-
|
|
215
|
-
return await fn(this.writeConnection);
|
|
216
|
-
} finally {
|
|
217
|
-
const serializedUpdates = await this.writeConnection.executeRaw("SELECT powersync_update_hooks('get');", []);
|
|
218
|
-
const updates = JSON.parse(serializedUpdates[0][0] as string) as string[];
|
|
219
|
-
|
|
220
|
-
if (updates.length > 0) {
|
|
221
|
-
const event: BatchedUpdateNotification = {
|
|
222
|
-
tables: updates,
|
|
223
|
-
groupedUpdates: {},
|
|
224
|
-
rawUpdates: []
|
|
225
|
-
};
|
|
226
|
-
this.iterateListeners((cb) => cb.tablesUpdated?.(event));
|
|
227
|
-
}
|
|
228
|
-
}
|
|
185
|
+
return await fn(item);
|
|
229
186
|
} finally {
|
|
230
|
-
const
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
187
|
+
const serializedUpdates = await item.executeRaw("SELECT powersync_update_hooks('get');", []);
|
|
188
|
+
const updates = JSON.parse(serializedUpdates[0][0] as string) as string[];
|
|
189
|
+
|
|
190
|
+
if (updates.length > 0) {
|
|
191
|
+
const event: BatchedUpdateNotification = {
|
|
192
|
+
tables: updates,
|
|
193
|
+
groupedUpdates: {},
|
|
194
|
+
rawUpdates: []
|
|
195
|
+
};
|
|
196
|
+
this.iterateListeners((cb) => cb.tablesUpdated?.(event));
|
|
235
197
|
}
|
|
236
198
|
}
|
|
237
|
-
}
|
|
199
|
+
} finally {
|
|
200
|
+
release();
|
|
201
|
+
}
|
|
238
202
|
}
|
|
239
203
|
|
|
240
204
|
async refreshSchema() {
|
|
241
|
-
await this.
|
|
205
|
+
await this.writeLock((l) => l.refreshSchema());
|
|
242
206
|
|
|
243
|
-
await
|
|
207
|
+
const { items, release } = await this.readConnections.requestAll();
|
|
208
|
+
try {
|
|
209
|
+
await Promise.all(items.map((c) => c.refreshSchema()));
|
|
210
|
+
} finally {
|
|
211
|
+
release();
|
|
212
|
+
}
|
|
244
213
|
}
|
|
245
214
|
}
|
|
246
215
|
|