@powersync/web 0.0.0-dev-20240506092851
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 +55 -0
- package/lib/src/db/PowerSyncDatabase.d.ts +43 -0
- package/lib/src/db/PowerSyncDatabase.js +91 -0
- package/lib/src/db/adapters/AbstractWebPowerSyncDatabaseOpenFactory.d.ts +23 -0
- package/lib/src/db/adapters/AbstractWebPowerSyncDatabaseOpenFactory.js +56 -0
- package/lib/src/db/adapters/SSRDBAdapter.d.ts +29 -0
- package/lib/src/db/adapters/SSRDBAdapter.js +85 -0
- package/lib/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.d.ts +56 -0
- package/lib/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.js +196 -0
- package/lib/src/db/adapters/wa-sqlite/WASQLitePowerSyncDatabaseOpenFactory.d.ts +6 -0
- package/lib/src/db/adapters/wa-sqlite/WASQLitePowerSyncDatabaseOpenFactory.js +11 -0
- package/lib/src/db/sync/SSRWebStreamingSyncImplementation.d.ts +8 -0
- package/lib/src/db/sync/SSRWebStreamingSyncImplementation.js +13 -0
- package/lib/src/db/sync/SharedWebStreamingSyncImplementation.d.ts +47 -0
- package/lib/src/db/sync/SharedWebStreamingSyncImplementation.js +187 -0
- package/lib/src/db/sync/WebRemote.d.ts +6 -0
- package/lib/src/db/sync/WebRemote.js +133 -0
- package/lib/src/db/sync/WebStreamingSyncImplementation.d.ts +11 -0
- package/lib/src/db/sync/WebStreamingSyncImplementation.js +15 -0
- package/lib/src/index.d.ts +8 -0
- package/lib/src/index.js +8 -0
- package/lib/src/worker/db/SharedWASQLiteDB.worker.d.ts +1 -0
- package/lib/src/worker/db/SharedWASQLiteDB.worker.js +57 -0
- package/lib/src/worker/db/WASQLiteDB.worker.d.ts +1 -0
- package/lib/src/worker/db/WASQLiteDB.worker.js +12 -0
- package/lib/src/worker/db/open-db.d.ts +20 -0
- package/lib/src/worker/db/open-db.js +192 -0
- package/lib/src/worker/db/open-worker-database.d.ts +11 -0
- package/lib/src/worker/db/open-worker-database.js +30 -0
- package/lib/src/worker/sync/AbstractSharedSyncClientProvider.d.ts +17 -0
- package/lib/src/worker/sync/AbstractSharedSyncClientProvider.js +5 -0
- package/lib/src/worker/sync/BroadcastLogger.d.ts +37 -0
- package/lib/src/worker/sync/BroadcastLogger.js +107 -0
- package/lib/src/worker/sync/SharedSyncImplementation.d.ts +88 -0
- package/lib/src/worker/sync/SharedSyncImplementation.js +247 -0
- package/lib/src/worker/sync/SharedSyncImplementation.worker.d.ts +1 -0
- package/lib/src/worker/sync/SharedSyncImplementation.worker.js +22 -0
- package/lib/tsconfig.tsbuildinfo +1 -0
- package/package.json +58 -0
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import '@journeyapps/wa-sqlite';
|
|
11
|
+
import * as Comlink from 'comlink';
|
|
12
|
+
import { v4 as uuid } from 'uuid';
|
|
13
|
+
import { _openDB } from './open-db';
|
|
14
|
+
const _self = self;
|
|
15
|
+
const DBMap = new Map();
|
|
16
|
+
const OPEN_DB_LOCK = 'open-wasqlite-db';
|
|
17
|
+
const openDB = (dbFileName) => __awaiter(void 0, void 0, void 0, function* () {
|
|
18
|
+
// Prevent multiple simultaneous opens from causing race conditions
|
|
19
|
+
return navigator.locks.request(OPEN_DB_LOCK, () => __awaiter(void 0, void 0, void 0, function* () {
|
|
20
|
+
const clientId = uuid();
|
|
21
|
+
if (!DBMap.has(dbFileName)) {
|
|
22
|
+
const clientIds = new Set();
|
|
23
|
+
const connection = yield _openDB(dbFileName);
|
|
24
|
+
DBMap.set(dbFileName, {
|
|
25
|
+
clientIds,
|
|
26
|
+
db: connection
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
const dbEntry = DBMap.get(dbFileName);
|
|
30
|
+
dbEntry.clientIds.add(clientId);
|
|
31
|
+
const { db } = dbEntry;
|
|
32
|
+
const wrappedConnection = Object.assign(Object.assign({}, db), { close: Comlink.proxy(() => {
|
|
33
|
+
var _a;
|
|
34
|
+
const { clientIds } = dbEntry;
|
|
35
|
+
clientIds.delete(clientId);
|
|
36
|
+
if (clientIds.size == 0) {
|
|
37
|
+
console.debug(`Closing connection to ${dbFileName}.`);
|
|
38
|
+
DBMap.delete(dbFileName);
|
|
39
|
+
return (_a = db.close) === null || _a === void 0 ? void 0 : _a.call(db);
|
|
40
|
+
}
|
|
41
|
+
console.debug(`Connection to ${dbFileName} not closed yet due to active clients.`);
|
|
42
|
+
}) });
|
|
43
|
+
return Comlink.proxy(wrappedConnection);
|
|
44
|
+
}));
|
|
45
|
+
});
|
|
46
|
+
_self.onconnect = function (event) {
|
|
47
|
+
const port = event.ports[0];
|
|
48
|
+
console.debug('Exposing db on port', port);
|
|
49
|
+
Comlink.expose(openDB, port);
|
|
50
|
+
};
|
|
51
|
+
addEventListener('unload', () => {
|
|
52
|
+
Array.from(DBMap.values()).forEach((dbConnection) => __awaiter(void 0, void 0, void 0, function* () {
|
|
53
|
+
var _a;
|
|
54
|
+
const db = yield dbConnection.db;
|
|
55
|
+
(_a = db.close) === null || _a === void 0 ? void 0 : _a.call(db);
|
|
56
|
+
}));
|
|
57
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import * as Comlink from 'comlink';
|
|
11
|
+
import { _openDB } from './open-db';
|
|
12
|
+
Comlink.expose((dbFileName) => __awaiter(void 0, void 0, void 0, function* () { return Comlink.proxy(yield _openDB(dbFileName)); }));
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import '@journeyapps/wa-sqlite';
|
|
2
|
+
import { QueryResult } from '@powersync/common';
|
|
3
|
+
export type WASQLExecuteResult = Omit<QueryResult, 'rows'> & {
|
|
4
|
+
rows: {
|
|
5
|
+
_array: any[];
|
|
6
|
+
length: number;
|
|
7
|
+
};
|
|
8
|
+
};
|
|
9
|
+
export type DBWorkerInterface = {
|
|
10
|
+
close?: () => void;
|
|
11
|
+
execute: WASQLiteExecuteMethod;
|
|
12
|
+
executeBatch: WASQLiteExecuteBatchMethod;
|
|
13
|
+
registerOnTableChange: (callback: OnTableChangeCallback) => void;
|
|
14
|
+
};
|
|
15
|
+
export type WASQLiteExecuteMethod = (sql: string, params?: any[]) => Promise<WASQLExecuteResult>;
|
|
16
|
+
export type WASQLiteExecuteBatchMethod = (sql: string, params?: any[]) => Promise<WASQLExecuteResult>;
|
|
17
|
+
export type OnTableChangeCallback = (opType: number, tableName: string, rowId: number) => void;
|
|
18
|
+
export type OpenDB = (dbFileName: string) => DBWorkerInterface;
|
|
19
|
+
export type SQLBatchTuple = [string] | [string, Array<any> | Array<Array<any>>];
|
|
20
|
+
export declare function _openDB(dbFileName: string): Promise<DBWorkerInterface>;
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
var __asyncValues = (this && this.__asyncValues) || function (o) {
|
|
11
|
+
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
|
|
12
|
+
var m = o[Symbol.asyncIterator], i;
|
|
13
|
+
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
|
|
14
|
+
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
|
|
15
|
+
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
|
|
16
|
+
};
|
|
17
|
+
import * as SQLite from '@journeyapps/wa-sqlite';
|
|
18
|
+
import '@journeyapps/wa-sqlite';
|
|
19
|
+
import * as Comlink from 'comlink';
|
|
20
|
+
import { v4 as uuid } from 'uuid';
|
|
21
|
+
export function _openDB(dbFileName) {
|
|
22
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
23
|
+
const { default: moduleFactory } = yield import('@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs');
|
|
24
|
+
const module = yield moduleFactory();
|
|
25
|
+
const sqlite3 = SQLite.Factory(module);
|
|
26
|
+
const { IDBBatchAtomicVFS } = yield import('@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js');
|
|
27
|
+
const vfs = new IDBBatchAtomicVFS(dbFileName);
|
|
28
|
+
sqlite3.vfs_register(vfs, true);
|
|
29
|
+
const db = yield sqlite3.open_v2(dbFileName);
|
|
30
|
+
/**
|
|
31
|
+
* Listeners are exclusive to the DB connection.
|
|
32
|
+
*/
|
|
33
|
+
const listeners = new Map();
|
|
34
|
+
sqlite3.register_table_onchange_hook(db, (opType, tableName, rowId) => {
|
|
35
|
+
Array.from(listeners.values()).forEach((l) => l(opType, tableName, rowId));
|
|
36
|
+
});
|
|
37
|
+
const registerOnTableChange = (callback) => {
|
|
38
|
+
const id = uuid();
|
|
39
|
+
listeners.set(id, callback);
|
|
40
|
+
return Comlink.proxy(() => {
|
|
41
|
+
listeners.delete(id);
|
|
42
|
+
});
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* This executes single SQL statements inside a requested lock.
|
|
46
|
+
*/
|
|
47
|
+
const execute = (sql, bindings) => __awaiter(this, void 0, void 0, function* () {
|
|
48
|
+
// Running multiple statements on the same connection concurrently should not be allowed
|
|
49
|
+
return _acquireExecuteLock(() => __awaiter(this, void 0, void 0, function* () {
|
|
50
|
+
return executeSingleStatement(sql, bindings);
|
|
51
|
+
}));
|
|
52
|
+
});
|
|
53
|
+
/**
|
|
54
|
+
* This requests a lock for executing statements.
|
|
55
|
+
* Should only be used interanlly.
|
|
56
|
+
*/
|
|
57
|
+
const _acquireExecuteLock = (callback) => {
|
|
58
|
+
return navigator.locks.request(`db-execute-${dbFileName}`, callback);
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* This executes a single statement using SQLite3.
|
|
62
|
+
*/
|
|
63
|
+
const executeSingleStatement = (sql, bindings) => __awaiter(this, void 0, void 0, function* () {
|
|
64
|
+
var _a, e_1, _b, _c;
|
|
65
|
+
const results = [];
|
|
66
|
+
try {
|
|
67
|
+
for (var _d = true, _e = __asyncValues(sqlite3.statements(db, sql)), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) {
|
|
68
|
+
_c = _f.value;
|
|
69
|
+
_d = false;
|
|
70
|
+
const stmt = _c;
|
|
71
|
+
let columns;
|
|
72
|
+
const wrappedBindings = bindings ? [bindings] : [[]];
|
|
73
|
+
for (const binding of wrappedBindings) {
|
|
74
|
+
// TODO not sure why this is needed currently, but booleans break
|
|
75
|
+
binding.forEach((b, index, arr) => {
|
|
76
|
+
if (typeof b == 'boolean') {
|
|
77
|
+
arr[index] = b ? 1 : 0;
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
sqlite3.reset(stmt);
|
|
81
|
+
if (bindings) {
|
|
82
|
+
sqlite3.bind_collection(stmt, binding);
|
|
83
|
+
}
|
|
84
|
+
const rows = [];
|
|
85
|
+
while ((yield sqlite3.step(stmt)) === SQLite.SQLITE_ROW) {
|
|
86
|
+
const row = sqlite3.row(stmt);
|
|
87
|
+
rows.push(row);
|
|
88
|
+
}
|
|
89
|
+
columns = columns !== null && columns !== void 0 ? columns : sqlite3.column_names(stmt);
|
|
90
|
+
if (columns.length) {
|
|
91
|
+
results.push({ columns, rows });
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
// When binding parameters, only a single statement is executed.
|
|
95
|
+
if (bindings) {
|
|
96
|
+
break;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
101
|
+
finally {
|
|
102
|
+
try {
|
|
103
|
+
if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
|
|
104
|
+
}
|
|
105
|
+
finally { if (e_1) throw e_1.error; }
|
|
106
|
+
}
|
|
107
|
+
const rows = [];
|
|
108
|
+
for (const resultset of results) {
|
|
109
|
+
for (const row of resultset.rows) {
|
|
110
|
+
const outRow = {};
|
|
111
|
+
resultset.columns.forEach((key, index) => {
|
|
112
|
+
outRow[key] = row[index];
|
|
113
|
+
});
|
|
114
|
+
rows.push(outRow);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
const result = {
|
|
118
|
+
insertId: sqlite3.last_insert_id(db),
|
|
119
|
+
rowsAffected: sqlite3.changes(db),
|
|
120
|
+
rows: {
|
|
121
|
+
_array: rows,
|
|
122
|
+
length: rows.length
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
return result;
|
|
126
|
+
});
|
|
127
|
+
/**
|
|
128
|
+
* This executes SQL statements in a batch.
|
|
129
|
+
*/
|
|
130
|
+
const executeBatch = (sql, bindings) => __awaiter(this, void 0, void 0, function* () {
|
|
131
|
+
return _acquireExecuteLock(() => __awaiter(this, void 0, void 0, function* () {
|
|
132
|
+
let affectedRows = 0;
|
|
133
|
+
const str = sqlite3.str_new(db, sql);
|
|
134
|
+
const query = sqlite3.str_value(str);
|
|
135
|
+
try {
|
|
136
|
+
yield executeSingleStatement('BEGIN TRANSACTION');
|
|
137
|
+
//Prepare statement once
|
|
138
|
+
const prepared = yield sqlite3.prepare_v2(db, query);
|
|
139
|
+
if (prepared === null) {
|
|
140
|
+
return {
|
|
141
|
+
rowsAffected: 0
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
const wrappedBindings = bindings ? bindings : [];
|
|
145
|
+
for (const binding of wrappedBindings) {
|
|
146
|
+
// TODO not sure why this is needed currently, but booleans break
|
|
147
|
+
for (let i = 0; i < binding.length; i++) {
|
|
148
|
+
const b = binding[i];
|
|
149
|
+
if (typeof b == 'boolean') {
|
|
150
|
+
binding[i] = b ? 1 : 0;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
//Reset bindings
|
|
154
|
+
sqlite3.reset(prepared.stmt);
|
|
155
|
+
if (bindings) {
|
|
156
|
+
sqlite3.bind_collection(prepared.stmt, binding);
|
|
157
|
+
}
|
|
158
|
+
const result = yield sqlite3.step(prepared.stmt);
|
|
159
|
+
if (result === SQLite.SQLITE_DONE) {
|
|
160
|
+
//The value returned by sqlite3_changes() immediately after an INSERT, UPDATE or DELETE statement run on a view is always zero.
|
|
161
|
+
affectedRows += sqlite3.changes(db);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
//Finalize prepared statement
|
|
165
|
+
yield sqlite3.finalize(prepared.stmt);
|
|
166
|
+
yield executeSingleStatement('COMMIT');
|
|
167
|
+
}
|
|
168
|
+
catch (err) {
|
|
169
|
+
yield executeSingleStatement('ROLLBACK');
|
|
170
|
+
return {
|
|
171
|
+
rowsAffected: 0
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
finally {
|
|
175
|
+
sqlite3.str_finish(str);
|
|
176
|
+
}
|
|
177
|
+
const result = {
|
|
178
|
+
rowsAffected: affectedRows
|
|
179
|
+
};
|
|
180
|
+
return result;
|
|
181
|
+
}));
|
|
182
|
+
});
|
|
183
|
+
return {
|
|
184
|
+
execute: Comlink.proxy(execute),
|
|
185
|
+
executeBatch: Comlink.proxy(executeBatch),
|
|
186
|
+
registerOnTableChange: Comlink.proxy(registerOnTableChange),
|
|
187
|
+
close: Comlink.proxy(() => {
|
|
188
|
+
sqlite3.close(db);
|
|
189
|
+
})
|
|
190
|
+
};
|
|
191
|
+
});
|
|
192
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import * as Comlink from 'comlink';
|
|
2
|
+
import { OpenDB } from './open-db';
|
|
3
|
+
/**
|
|
4
|
+
* Opens a shared or dedicated worker which exposes opening of database connections
|
|
5
|
+
*/
|
|
6
|
+
export declare function openWorkerDatabasePort(workerIdentifier: string, multipleTabs?: boolean): MessagePort | Worker;
|
|
7
|
+
/**
|
|
8
|
+
* @returns A function which allows for opening database connections inside
|
|
9
|
+
* a worker.
|
|
10
|
+
*/
|
|
11
|
+
export declare function getWorkerDatabaseOpener(workerIdentifier: string, multipleTabs?: boolean): Comlink.Remote<OpenDB>;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import * as Comlink from 'comlink';
|
|
2
|
+
/**
|
|
3
|
+
* Opens a shared or dedicated worker which exposes opening of database connections
|
|
4
|
+
*/
|
|
5
|
+
export function openWorkerDatabasePort(workerIdentifier, multipleTabs = true) {
|
|
6
|
+
/**
|
|
7
|
+
* Webpack V5 can bundle the worker automatically if the full Worker constructor syntax is used
|
|
8
|
+
* https://webpack.js.org/guides/web-workers/
|
|
9
|
+
* This enables multi tab support by default, but falls back if SharedWorker is not available
|
|
10
|
+
* (in the case of Android)
|
|
11
|
+
*/
|
|
12
|
+
return multipleTabs
|
|
13
|
+
? new SharedWorker(new URL('./SharedWASQLiteDB.worker.js', import.meta.url), {
|
|
14
|
+
/* @vite-ignore */
|
|
15
|
+
name: `shared-DB-worker-${workerIdentifier}`,
|
|
16
|
+
type: 'module'
|
|
17
|
+
}).port
|
|
18
|
+
: new Worker(new URL('./WASQLiteDB.worker.js', import.meta.url), {
|
|
19
|
+
/* @vite-ignore */
|
|
20
|
+
name: `DB-worker-${workerIdentifier}`,
|
|
21
|
+
type: 'module'
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* @returns A function which allows for opening database connections inside
|
|
26
|
+
* a worker.
|
|
27
|
+
*/
|
|
28
|
+
export function getWorkerDatabaseOpener(workerIdentifier, multipleTabs = true) {
|
|
29
|
+
return Comlink.wrap(openWorkerDatabasePort(workerIdentifier, multipleTabs));
|
|
30
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { PowerSyncCredentials, SyncStatusOptions } from '@powersync/common';
|
|
2
|
+
/**
|
|
3
|
+
* The client side port should provide these methods.
|
|
4
|
+
*/
|
|
5
|
+
export declare abstract class AbstractSharedSyncClientProvider {
|
|
6
|
+
abstract fetchCredentials(): Promise<PowerSyncCredentials | null>;
|
|
7
|
+
abstract uploadCrud(): Promise<void>;
|
|
8
|
+
abstract statusChanged(status: SyncStatusOptions): void;
|
|
9
|
+
abstract trace(...x: any[]): void;
|
|
10
|
+
abstract debug(...x: any[]): void;
|
|
11
|
+
abstract info(...x: any[]): void;
|
|
12
|
+
abstract log(...x: any[]): void;
|
|
13
|
+
abstract warn(...x: any[]): void;
|
|
14
|
+
abstract error(...x: any[]): void;
|
|
15
|
+
abstract time(label: string): void;
|
|
16
|
+
abstract timeEnd(label: string): void;
|
|
17
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { ILogLevel, ILogger } from 'js-logger';
|
|
2
|
+
import { type WrappedSyncPort } from './SharedSyncImplementation';
|
|
3
|
+
/**
|
|
4
|
+
* Broadcasts logs to all clients
|
|
5
|
+
*/
|
|
6
|
+
export declare class BroadcastLogger implements ILogger {
|
|
7
|
+
protected clients: WrappedSyncPort[];
|
|
8
|
+
TRACE: ILogLevel;
|
|
9
|
+
DEBUG: ILogLevel;
|
|
10
|
+
INFO: ILogLevel;
|
|
11
|
+
TIME: ILogLevel;
|
|
12
|
+
WARN: ILogLevel;
|
|
13
|
+
ERROR: ILogLevel;
|
|
14
|
+
OFF: ILogLevel;
|
|
15
|
+
constructor(clients: WrappedSyncPort[]);
|
|
16
|
+
trace(...x: any[]): void;
|
|
17
|
+
debug(...x: any[]): void;
|
|
18
|
+
info(...x: any[]): void;
|
|
19
|
+
log(...x: any[]): void;
|
|
20
|
+
warn(...x: any[]): void;
|
|
21
|
+
error(...x: any[]): void;
|
|
22
|
+
time(label: string): void;
|
|
23
|
+
timeEnd(label: string): void;
|
|
24
|
+
setLevel(level: ILogLevel): void;
|
|
25
|
+
getLevel(): ILogLevel;
|
|
26
|
+
enabledFor(level: ILogLevel): boolean;
|
|
27
|
+
/**
|
|
28
|
+
* Iterates all clients, catches individual client exceptions
|
|
29
|
+
* and proceeds to execute for all clients.
|
|
30
|
+
*/
|
|
31
|
+
protected iterateClients(callback: (client: WrappedSyncPort) => Promise<void>): Promise<void>;
|
|
32
|
+
/**
|
|
33
|
+
* Guards against any logging errors.
|
|
34
|
+
* We don't want a logging exception to cause further issues upstream
|
|
35
|
+
*/
|
|
36
|
+
protected sanitizeArgs(x: any[]): any[];
|
|
37
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import Logger from 'js-logger';
|
|
11
|
+
/**
|
|
12
|
+
* Broadcasts logs to all clients
|
|
13
|
+
*/
|
|
14
|
+
export class BroadcastLogger {
|
|
15
|
+
constructor(clients) {
|
|
16
|
+
this.clients = clients;
|
|
17
|
+
this.TRACE = Logger.TRACE;
|
|
18
|
+
this.DEBUG = Logger.DEBUG;
|
|
19
|
+
this.INFO = Logger.INFO;
|
|
20
|
+
this.TIME = Logger.TIME;
|
|
21
|
+
this.WARN = Logger.WARN;
|
|
22
|
+
this.ERROR = Logger.ERROR;
|
|
23
|
+
this.OFF = Logger.OFF;
|
|
24
|
+
}
|
|
25
|
+
trace(...x) {
|
|
26
|
+
console.trace(...x);
|
|
27
|
+
const sanitized = this.sanitizeArgs(x);
|
|
28
|
+
this.iterateClients((client) => client.clientProvider.trace(...sanitized));
|
|
29
|
+
}
|
|
30
|
+
debug(...x) {
|
|
31
|
+
console.debug(...x);
|
|
32
|
+
const sanitized = this.sanitizeArgs(x);
|
|
33
|
+
this.iterateClients((client) => client.clientProvider.debug(...sanitized));
|
|
34
|
+
}
|
|
35
|
+
info(...x) {
|
|
36
|
+
console.info(...x);
|
|
37
|
+
const sanitized = this.sanitizeArgs(x);
|
|
38
|
+
this.iterateClients((client) => client.clientProvider.info(...sanitized));
|
|
39
|
+
}
|
|
40
|
+
log(...x) {
|
|
41
|
+
console.log(...x);
|
|
42
|
+
const sanitized = this.sanitizeArgs(x);
|
|
43
|
+
this.iterateClients((client) => client.clientProvider.log(...sanitized));
|
|
44
|
+
}
|
|
45
|
+
warn(...x) {
|
|
46
|
+
console.warn(...x);
|
|
47
|
+
const sanitized = this.sanitizeArgs(x);
|
|
48
|
+
this.iterateClients((client) => client.clientProvider.warn(...sanitized));
|
|
49
|
+
}
|
|
50
|
+
error(...x) {
|
|
51
|
+
console.error(...x);
|
|
52
|
+
const sanitized = this.sanitizeArgs(x);
|
|
53
|
+
this.iterateClients((client) => client.clientProvider.error(...sanitized));
|
|
54
|
+
}
|
|
55
|
+
time(label) {
|
|
56
|
+
console.time(label);
|
|
57
|
+
this.iterateClients((client) => client.clientProvider.time(label));
|
|
58
|
+
}
|
|
59
|
+
timeEnd(label) {
|
|
60
|
+
console.timeEnd(label);
|
|
61
|
+
this.iterateClients((client) => client.clientProvider.timeEnd(label));
|
|
62
|
+
}
|
|
63
|
+
setLevel(level) {
|
|
64
|
+
// Levels are not adjustable on this level.
|
|
65
|
+
}
|
|
66
|
+
getLevel() {
|
|
67
|
+
// Levels are not adjustable on this level.
|
|
68
|
+
return Logger.INFO;
|
|
69
|
+
}
|
|
70
|
+
enabledFor(level) {
|
|
71
|
+
// Levels are not adjustable on this level.
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Iterates all clients, catches individual client exceptions
|
|
76
|
+
* and proceeds to execute for all clients.
|
|
77
|
+
*/
|
|
78
|
+
iterateClients(callback) {
|
|
79
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
80
|
+
for (let client of this.clients) {
|
|
81
|
+
try {
|
|
82
|
+
yield callback(client);
|
|
83
|
+
}
|
|
84
|
+
catch (ex) {
|
|
85
|
+
console.error('Caught exception when iterating client', ex);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Guards against any logging errors.
|
|
92
|
+
* We don't want a logging exception to cause further issues upstream
|
|
93
|
+
*/
|
|
94
|
+
sanitizeArgs(x) {
|
|
95
|
+
const sanitizedParams = x.map((param) => {
|
|
96
|
+
try {
|
|
97
|
+
// Try and clone here first. If it fails it won't be passable over a MessagePort
|
|
98
|
+
return structuredClone(param);
|
|
99
|
+
}
|
|
100
|
+
catch (ex) {
|
|
101
|
+
console.error(ex);
|
|
102
|
+
return 'Could not serialize log params. Check shared worker logs for more details.';
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
return sanitizedParams;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import * as Comlink from 'comlink';
|
|
2
|
+
import { ILogger } from 'js-logger';
|
|
3
|
+
import { AbstractStreamingSyncImplementation, StreamingSyncImplementation, BaseObserver, LockOptions, StreamingSyncImplementationListener, SyncStatus, SyncStatusOptions } from '@powersync/common';
|
|
4
|
+
import { WebStreamingSyncImplementationOptions } from '../../db/sync/WebStreamingSyncImplementation';
|
|
5
|
+
import { AbstractSharedSyncClientProvider } from './AbstractSharedSyncClientProvider';
|
|
6
|
+
/**
|
|
7
|
+
* Manual message events for shared sync clients
|
|
8
|
+
*/
|
|
9
|
+
export declare enum SharedSyncClientEvent {
|
|
10
|
+
/**
|
|
11
|
+
* This client requests the shared sync manager should
|
|
12
|
+
* close it's connection to the client.
|
|
13
|
+
*/
|
|
14
|
+
CLOSE_CLIENT = "close-client"
|
|
15
|
+
}
|
|
16
|
+
export type ManualSharedSyncPayload = {
|
|
17
|
+
event: SharedSyncClientEvent;
|
|
18
|
+
data: any;
|
|
19
|
+
};
|
|
20
|
+
export type SharedSyncInitOptions = {
|
|
21
|
+
dbName: string;
|
|
22
|
+
streamOptions: Omit<WebStreamingSyncImplementationOptions, 'adapter' | 'uploadCrud' | 'remote'>;
|
|
23
|
+
};
|
|
24
|
+
export interface SharedSyncImplementationListener extends StreamingSyncImplementationListener {
|
|
25
|
+
initialized: () => void;
|
|
26
|
+
}
|
|
27
|
+
export type WrappedSyncPort = {
|
|
28
|
+
port: MessagePort;
|
|
29
|
+
clientProvider: Comlink.Remote<AbstractSharedSyncClientProvider>;
|
|
30
|
+
};
|
|
31
|
+
export type RemoteOperationAbortController = {
|
|
32
|
+
controller: AbortController;
|
|
33
|
+
activePort: WrappedSyncPort;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Shared sync implementation which runs inside a shared webworker
|
|
37
|
+
*/
|
|
38
|
+
export declare class SharedSyncImplementation extends BaseObserver<SharedSyncImplementationListener> implements StreamingSyncImplementation {
|
|
39
|
+
protected ports: WrappedSyncPort[];
|
|
40
|
+
protected syncStreamClient?: AbstractStreamingSyncImplementation;
|
|
41
|
+
protected isInitialized: Promise<void>;
|
|
42
|
+
protected statusListener?: () => void;
|
|
43
|
+
protected fetchCredentialsController?: RemoteOperationAbortController;
|
|
44
|
+
protected uploadDataController?: RemoteOperationAbortController;
|
|
45
|
+
syncStatus: SyncStatus;
|
|
46
|
+
broadCastLogger: ILogger;
|
|
47
|
+
constructor();
|
|
48
|
+
waitForStatus(status: SyncStatusOptions): Promise<void>;
|
|
49
|
+
get lastSyncedAt(): Date | undefined;
|
|
50
|
+
get isConnected(): boolean;
|
|
51
|
+
waitForReady(): Promise<void>;
|
|
52
|
+
/**
|
|
53
|
+
* Configures the DBAdapter connection and a streaming sync client.
|
|
54
|
+
*/
|
|
55
|
+
init(dbWorkerPort: MessagePort, params: SharedSyncInitOptions): Promise<void>;
|
|
56
|
+
dispose(): Promise<void | undefined>;
|
|
57
|
+
/**
|
|
58
|
+
* Connects to the PowerSync backend instance.
|
|
59
|
+
* Multiple tabs can safely call this in their initialization.
|
|
60
|
+
* The connection will simply be reconnected whenever a new tab
|
|
61
|
+
* connects.
|
|
62
|
+
*/
|
|
63
|
+
connect(): Promise<any>;
|
|
64
|
+
disconnect(): Promise<any>;
|
|
65
|
+
/**
|
|
66
|
+
* Adds a new client tab's message port to the list of connected ports
|
|
67
|
+
*/
|
|
68
|
+
addPort(port: MessagePort): void;
|
|
69
|
+
/**
|
|
70
|
+
* Removes a message port client from this manager's managed
|
|
71
|
+
* clients.
|
|
72
|
+
*/
|
|
73
|
+
removePort(port: MessagePort): void;
|
|
74
|
+
triggerCrudUpload(): void;
|
|
75
|
+
obtainLock<T>(lockOptions: LockOptions<T>): Promise<T>;
|
|
76
|
+
hasCompletedSync(): Promise<boolean>;
|
|
77
|
+
getWriteCheckpoint(): Promise<string>;
|
|
78
|
+
/**
|
|
79
|
+
* A method to update the all shared statuses for each
|
|
80
|
+
* client.
|
|
81
|
+
*/
|
|
82
|
+
private updateAllStatuses;
|
|
83
|
+
/**
|
|
84
|
+
* A function only used for unit tests which updates the internal
|
|
85
|
+
* sync stream client and all tab client's sync status
|
|
86
|
+
*/
|
|
87
|
+
private _testUpdateAllStatuses;
|
|
88
|
+
}
|