@powersync/common 0.0.0-dev-20250711131120 → 0.0.0-dev-20250714144421
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 +3 -3
- package/dist/bundle.mjs +3 -3
- package/lib/client/AbstractPowerSyncDatabase.d.ts +0 -5
- package/lib/client/AbstractPowerSyncDatabase.js +3 -13
- package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +1 -3
- package/lib/client/sync/bucket/SqliteBucketStorage.js +15 -17
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +18 -8
- package/package.json +1 -1
|
@@ -100,11 +100,6 @@ export declare const DEFAULT_LOCK_TIMEOUT_MS = 120000;
|
|
|
100
100
|
export declare const isPowerSyncDatabaseOptionsWithSettings: (test: any) => test is PowerSyncDatabaseOptionsWithSettings;
|
|
101
101
|
export declare abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDBListener> {
|
|
102
102
|
protected options: PowerSyncDatabaseOptions;
|
|
103
|
-
/**
|
|
104
|
-
* Transactions should be queued in the DBAdapter, but we also want to prevent
|
|
105
|
-
* calls to `.execute` while an async transaction is running.
|
|
106
|
-
*/
|
|
107
|
-
protected static transactionMutex: Mutex;
|
|
108
103
|
/**
|
|
109
104
|
* Returns true if the connection is closed.
|
|
110
105
|
*/
|
|
@@ -8,7 +8,6 @@ import { UploadQueueStats } from '../db/crud/UploadQueueStatus.js';
|
|
|
8
8
|
import { BaseObserver } from '../utils/BaseObserver.js';
|
|
9
9
|
import { ControlledExecutor } from '../utils/ControlledExecutor.js';
|
|
10
10
|
import { throttleTrailing } from '../utils/async.js';
|
|
11
|
-
import { mutexRunExclusive } from '../utils/mutex.js';
|
|
12
11
|
import { ConnectionManager } from './ConnectionManager.js';
|
|
13
12
|
import { isDBAdapter, isSQLOpenFactory, isSQLOpenOptions } from './SQLOpenFactory.js';
|
|
14
13
|
import { runOnSchemaChange } from './runOnSchemaChange.js';
|
|
@@ -45,11 +44,6 @@ export const isPowerSyncDatabaseOptionsWithSettings = (test) => {
|
|
|
45
44
|
};
|
|
46
45
|
export class AbstractPowerSyncDatabase extends BaseObserver {
|
|
47
46
|
options;
|
|
48
|
-
/**
|
|
49
|
-
* Transactions should be queued in the DBAdapter, but we also want to prevent
|
|
50
|
-
* calls to `.execute` while an async transaction is running.
|
|
51
|
-
*/
|
|
52
|
-
static transactionMutex = new Mutex();
|
|
53
47
|
/**
|
|
54
48
|
* Returns true if the connection is closed.
|
|
55
49
|
*/
|
|
@@ -475,8 +469,7 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
|
|
|
475
469
|
* @returns The query result as an object with structured key-value pairs
|
|
476
470
|
*/
|
|
477
471
|
async execute(sql, parameters) {
|
|
478
|
-
|
|
479
|
-
return this.database.execute(sql, parameters);
|
|
472
|
+
return this.writeLock((tx) => tx.execute(sql, parameters));
|
|
480
473
|
}
|
|
481
474
|
/**
|
|
482
475
|
* Execute a SQL write (INSERT/UPDATE/DELETE) query directly on the database without any PowerSync processing.
|
|
@@ -544,7 +537,7 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
|
|
|
544
537
|
*/
|
|
545
538
|
async readLock(callback) {
|
|
546
539
|
await this.waitForReady();
|
|
547
|
-
return
|
|
540
|
+
return this.database.readLock(callback);
|
|
548
541
|
}
|
|
549
542
|
/**
|
|
550
543
|
* Takes a global lock, without starting a transaction.
|
|
@@ -552,10 +545,7 @@ export class AbstractPowerSyncDatabase extends BaseObserver {
|
|
|
552
545
|
*/
|
|
553
546
|
async writeLock(callback) {
|
|
554
547
|
await this.waitForReady();
|
|
555
|
-
return
|
|
556
|
-
const res = await callback(this.database);
|
|
557
|
-
return res;
|
|
558
|
-
});
|
|
548
|
+
return this.database.writeLock(callback);
|
|
559
549
|
}
|
|
560
550
|
/**
|
|
561
551
|
* Open a read-only transaction.
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { Mutex } from 'async-mutex';
|
|
2
1
|
import { ILogger } from 'js-logger';
|
|
3
2
|
import { DBAdapter, Transaction } from '../../../db/DBAdapter.js';
|
|
4
3
|
import { BaseObserver } from '../../../utils/BaseObserver.js';
|
|
@@ -8,13 +7,12 @@ import { CrudEntry } from './CrudEntry.js';
|
|
|
8
7
|
import { SyncDataBatch } from './SyncDataBatch.js';
|
|
9
8
|
export declare class SqliteBucketStorage extends BaseObserver<BucketStorageListener> implements BucketStorageAdapter {
|
|
10
9
|
private db;
|
|
11
|
-
private mutex;
|
|
12
10
|
private logger;
|
|
13
11
|
tableNames: Set<string>;
|
|
14
12
|
private _hasCompletedSync;
|
|
15
13
|
private updateListener;
|
|
16
14
|
private _clientId?;
|
|
17
|
-
constructor(db: DBAdapter,
|
|
15
|
+
constructor(db: DBAdapter, logger?: ILogger);
|
|
18
16
|
init(): Promise<void>;
|
|
19
17
|
dispose(): Promise<void>;
|
|
20
18
|
_getClientId(): Promise<string>;
|
|
@@ -6,16 +6,14 @@ import { PSInternalTable } from './BucketStorageAdapter.js';
|
|
|
6
6
|
import { CrudEntry } from './CrudEntry.js';
|
|
7
7
|
export class SqliteBucketStorage extends BaseObserver {
|
|
8
8
|
db;
|
|
9
|
-
mutex;
|
|
10
9
|
logger;
|
|
11
10
|
tableNames;
|
|
12
11
|
_hasCompletedSync;
|
|
13
12
|
updateListener;
|
|
14
13
|
_clientId;
|
|
15
|
-
constructor(db,
|
|
14
|
+
constructor(db, logger = Logger.get('SqliteBucketStorage')) {
|
|
16
15
|
super();
|
|
17
16
|
this.db = db;
|
|
18
|
-
this.mutex = mutex;
|
|
19
17
|
this.logger = logger;
|
|
20
18
|
this._hasCompletedSync = false;
|
|
21
19
|
this.tableNames = new Set();
|
|
@@ -66,11 +64,11 @@ export class SqliteBucketStorage extends BaseObserver {
|
|
|
66
64
|
async saveSyncData(batch, fixedKeyFormat = false) {
|
|
67
65
|
await this.writeTransaction(async (tx) => {
|
|
68
66
|
for (const b of batch.buckets) {
|
|
69
|
-
|
|
67
|
+
await tx.execute('INSERT INTO powersync_operations(op, data) VALUES(?, ?)', [
|
|
70
68
|
'save',
|
|
71
69
|
JSON.stringify({ buckets: [b.toJSON(fixedKeyFormat)] })
|
|
72
70
|
]);
|
|
73
|
-
this.logger.debug(
|
|
71
|
+
this.logger.debug(`Saved batch of data for bucket: ${b.bucket}, operations: ${b.data.length}`);
|
|
74
72
|
}
|
|
75
73
|
});
|
|
76
74
|
}
|
|
@@ -86,7 +84,7 @@ export class SqliteBucketStorage extends BaseObserver {
|
|
|
86
84
|
await this.writeTransaction(async (tx) => {
|
|
87
85
|
await tx.execute('INSERT INTO powersync_operations(op, data) VALUES(?, ?)', ['delete_bucket', bucket]);
|
|
88
86
|
});
|
|
89
|
-
this.logger.debug(
|
|
87
|
+
this.logger.debug(`Done deleting bucket ${bucket}`);
|
|
90
88
|
}
|
|
91
89
|
async hasCompletedSync() {
|
|
92
90
|
if (this._hasCompletedSync) {
|
|
@@ -108,6 +106,12 @@ export class SqliteBucketStorage extends BaseObserver {
|
|
|
108
106
|
}
|
|
109
107
|
return { ready: false, checkpointValid: false, checkpointFailures: r.checkpointFailures };
|
|
110
108
|
}
|
|
109
|
+
if (priority == null) {
|
|
110
|
+
this.logger.debug(`Validated checksums checkpoint ${checkpoint.last_op_id}`);
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
this.logger.debug(`Validated checksums for partial checkpoint ${checkpoint.last_op_id}, priority ${priority}`);
|
|
114
|
+
}
|
|
111
115
|
let buckets = checkpoint.buckets;
|
|
112
116
|
if (priority !== undefined) {
|
|
113
117
|
buckets = buckets.filter((b) => hasMatchingPriority(priority, b));
|
|
@@ -124,7 +128,6 @@ export class SqliteBucketStorage extends BaseObserver {
|
|
|
124
128
|
});
|
|
125
129
|
const valid = await this.updateObjectsFromBuckets(checkpoint, priority);
|
|
126
130
|
if (!valid) {
|
|
127
|
-
this.logger.debug('Not at a consistent checkpoint - cannot update local db');
|
|
128
131
|
return { ready: false, checkpointValid: true };
|
|
129
132
|
}
|
|
130
133
|
return {
|
|
@@ -177,7 +180,6 @@ export class SqliteBucketStorage extends BaseObserver {
|
|
|
177
180
|
JSON.stringify({ ...checkpoint })
|
|
178
181
|
]);
|
|
179
182
|
const resultItem = rs.rows?.item(0);
|
|
180
|
-
this.logger.debug('validateChecksums priority, checkpoint, result item', priority, checkpoint, resultItem);
|
|
181
183
|
if (!resultItem) {
|
|
182
184
|
return {
|
|
183
185
|
checkpointValid: false,
|
|
@@ -210,30 +212,26 @@ export class SqliteBucketStorage extends BaseObserver {
|
|
|
210
212
|
}
|
|
211
213
|
const seqBefore = rs[0]['seq'];
|
|
212
214
|
const opId = await cb();
|
|
213
|
-
this.logger.debug(`[updateLocalTarget] Updating target to checkpoint ${opId}`);
|
|
214
215
|
return this.writeTransaction(async (tx) => {
|
|
215
216
|
const anyData = await tx.execute('SELECT 1 FROM ps_crud LIMIT 1');
|
|
216
217
|
if (anyData.rows?.length) {
|
|
217
218
|
// if isNotEmpty
|
|
218
|
-
this.logger.debug(
|
|
219
|
+
this.logger.debug(`New data uploaded since write checkpoint ${opId} - need new write checkpoint`);
|
|
219
220
|
return false;
|
|
220
221
|
}
|
|
221
222
|
const rs = await tx.execute("SELECT seq FROM sqlite_sequence WHERE name = 'ps_crud'");
|
|
222
223
|
if (!rs.rows?.length) {
|
|
223
224
|
// assert isNotEmpty
|
|
224
|
-
throw new Error('
|
|
225
|
+
throw new Error('SQLite Sequence should not be empty');
|
|
225
226
|
}
|
|
226
227
|
const seqAfter = rs.rows?.item(0)['seq'];
|
|
227
|
-
this.logger.debug('seqAfter', JSON.stringify(rs.rows?.item(0)));
|
|
228
228
|
if (seqAfter != seqBefore) {
|
|
229
|
-
this.logger.debug(
|
|
229
|
+
this.logger.debug(`New data uploaded since write checpoint ${opId} - need new write checkpoint (sequence updated)`);
|
|
230
230
|
// New crud data may have been uploaded since we got the checkpoint. Abort.
|
|
231
231
|
return false;
|
|
232
232
|
}
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
]);
|
|
236
|
-
this.logger.debug(['[updateLocalTarget] Response from updating target_op ', JSON.stringify(response)]);
|
|
233
|
+
this.logger.debug(`Updating target write checkpoint to ${opId}`);
|
|
234
|
+
await tx.execute("UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'", [opId]);
|
|
237
235
|
return true;
|
|
238
236
|
});
|
|
239
237
|
}
|
|
@@ -167,11 +167,10 @@ export class AbstractStreamingSyncImplementation extends BaseObserver {
|
|
|
167
167
|
}
|
|
168
168
|
async getWriteCheckpoint() {
|
|
169
169
|
const clientId = await this.options.adapter.getClientId();
|
|
170
|
-
this.logger.debug(`Creating write checkpoint for ${clientId}`);
|
|
171
170
|
let path = `/write-checkpoint2.json?client_id=${clientId}`;
|
|
172
171
|
const response = await this.options.remote.get(path);
|
|
173
172
|
const checkpoint = response['data']['write_checkpoint'];
|
|
174
|
-
this.logger.debug(`
|
|
173
|
+
this.logger.debug(`Created write checkpoint: ${checkpoint}`);
|
|
175
174
|
return checkpoint;
|
|
176
175
|
}
|
|
177
176
|
async _uploadAllCrud() {
|
|
@@ -211,10 +210,10 @@ The next upload iteration will be delayed.`);
|
|
|
211
210
|
}
|
|
212
211
|
else {
|
|
213
212
|
// Uploading is completed
|
|
214
|
-
this.logger.debug('Upload complete, creating write checkpoint');
|
|
215
213
|
const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint());
|
|
216
|
-
if (neededUpdate == false) {
|
|
217
|
-
this
|
|
214
|
+
if (neededUpdate == false && checkedCrudItem != null) {
|
|
215
|
+
// Only log this if there was something to upload
|
|
216
|
+
this.logger.debug('Upload complete, no write checkpoint needed.');
|
|
218
217
|
}
|
|
219
218
|
break;
|
|
220
219
|
}
|
|
@@ -522,6 +521,8 @@ The next upload iteration will be delayed.`);
|
|
|
522
521
|
}
|
|
523
522
|
if (isStreamingSyncCheckpoint(line)) {
|
|
524
523
|
targetCheckpoint = line.checkpoint;
|
|
524
|
+
// New checkpoint - existing validated checkpoint is no longer valid
|
|
525
|
+
pendingValidatedCheckpoint = null;
|
|
525
526
|
const bucketsToDelete = new Set(bucketMap.keys());
|
|
526
527
|
const newBuckets = new Map();
|
|
527
528
|
for (const checksum of line.checkpoint.buckets) {
|
|
@@ -545,8 +546,15 @@ The next upload iteration will be delayed.`);
|
|
|
545
546
|
return;
|
|
546
547
|
}
|
|
547
548
|
else if (!result.applied) {
|
|
549
|
+
// "Could not apply checkpoint due to local data". We need to retry after
|
|
550
|
+
// finishing uploads.
|
|
548
551
|
pendingValidatedCheckpoint = targetCheckpoint;
|
|
549
552
|
}
|
|
553
|
+
else {
|
|
554
|
+
// Nothing to retry later. This would likely already be null from the last
|
|
555
|
+
// checksum or checksum_diff operation, but we make sure.
|
|
556
|
+
pendingValidatedCheckpoint = null;
|
|
557
|
+
}
|
|
550
558
|
}
|
|
551
559
|
else if (isStreamingSyncCheckpointPartiallyComplete(line)) {
|
|
552
560
|
const priority = line.partial_checkpoint_complete.priority;
|
|
@@ -583,6 +591,8 @@ The next upload iteration will be delayed.`);
|
|
|
583
591
|
if (targetCheckpoint == null) {
|
|
584
592
|
throw new Error('Checkpoint diff without previous checkpoint');
|
|
585
593
|
}
|
|
594
|
+
// New checkpoint - existing validated checkpoint is no longer valid
|
|
595
|
+
pendingValidatedCheckpoint = null;
|
|
586
596
|
const diff = line.checkpoint_diff;
|
|
587
597
|
const newBuckets = new Map();
|
|
588
598
|
for (const checksum of targetCheckpoint.buckets) {
|
|
@@ -875,17 +885,17 @@ The next upload iteration will be delayed.`);
|
|
|
875
885
|
async applyCheckpoint(checkpoint) {
|
|
876
886
|
let result = await this.options.adapter.syncLocalDatabase(checkpoint);
|
|
877
887
|
if (!result.checkpointValid) {
|
|
878
|
-
this.logger.debug(
|
|
888
|
+
this.logger.debug(`Checksum mismatch in checkpoint ${checkpoint.last_op_id}, will reconnect`);
|
|
879
889
|
// This means checksums failed. Start again with a new checkpoint.
|
|
880
890
|
// TODO: better back-off
|
|
881
891
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
882
892
|
return { applied: false, endIteration: true };
|
|
883
893
|
}
|
|
884
894
|
else if (!result.ready) {
|
|
885
|
-
this.logger.debug(
|
|
895
|
+
this.logger.debug(`Could not apply checkpoint ${checkpoint.last_op_id} due to local data. We will retry applying the checkpoint after that upload is completed.`);
|
|
886
896
|
return { applied: false, endIteration: false };
|
|
887
897
|
}
|
|
888
|
-
this.logger.debug(
|
|
898
|
+
this.logger.debug(`Applied checkpoint ${checkpoint.last_op_id}`, checkpoint);
|
|
889
899
|
this.updateSyncStatus({
|
|
890
900
|
connected: true,
|
|
891
901
|
lastSyncedAt: new Date(),
|