@koolbase/core 12.49.0 → 12.51.0
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/cjs/database-errors.d.ts +19 -3
- package/dist/cjs/database-errors.js +12 -3
- package/dist/cjs/database.d.ts +27 -6
- package/dist/cjs/database.js +80 -15
- package/dist/cjs/sync-engine.js +8 -2
- package/dist/cjs/types.d.ts +45 -2
- package/dist/cjs/types.js +11 -2
- package/dist/esm/database-errors.d.ts +19 -3
- package/dist/esm/database-errors.js +12 -3
- package/dist/esm/database.d.ts +27 -6
- package/dist/esm/database.js +80 -15
- package/dist/esm/sync-engine.js +8 -2
- package/dist/esm/types.d.ts +45 -2
- package/dist/esm/types.js +11 -2
- package/package.json +1 -1
|
@@ -188,11 +188,27 @@ export declare class KoolbaseProviderInvalidError extends KoolbaseDataError {
|
|
|
188
188
|
export declare class KoolbaseRevisionMismatchError extends KoolbaseDataError {
|
|
189
189
|
readonly expectedRevision?: number | undefined;
|
|
190
190
|
readonly currentRevision?: number | undefined;
|
|
191
|
-
/**
|
|
191
|
+
/**
|
|
192
|
+
* The record as the server holds it now. Absent when the caller may not
|
|
193
|
+
* read it ({@link readable} false): a failed write never discloses it.
|
|
194
|
+
*/
|
|
192
195
|
readonly current?: Record<string, unknown> | undefined;
|
|
196
|
+
/**
|
|
197
|
+
* Whether the caller may read the record now. False: the server withheld
|
|
198
|
+
* it and said only the revisions. Undefined from an older API.
|
|
199
|
+
*/
|
|
200
|
+
readonly readable?: boolean | undefined;
|
|
193
201
|
constructor(message?: string, expectedRevision?: number | undefined, currentRevision?: number | undefined,
|
|
194
|
-
/**
|
|
195
|
-
|
|
202
|
+
/**
|
|
203
|
+
* The record as the server holds it now. Absent when the caller may not
|
|
204
|
+
* read it ({@link readable} false): a failed write never discloses it.
|
|
205
|
+
*/
|
|
206
|
+
current?: Record<string, unknown> | undefined,
|
|
207
|
+
/**
|
|
208
|
+
* Whether the caller may read the record now. False: the server withheld
|
|
209
|
+
* it and said only the revisions. Undefined from an older API.
|
|
210
|
+
*/
|
|
211
|
+
readable?: boolean | undefined);
|
|
196
212
|
}
|
|
197
213
|
/**
|
|
198
214
|
* The same idempotency key sent with different data.
|
|
@@ -253,12 +253,21 @@ class KoolbaseProviderInvalidError extends KoolbaseDataError {
|
|
|
253
253
|
exports.KoolbaseProviderInvalidError = KoolbaseProviderInvalidError;
|
|
254
254
|
class KoolbaseRevisionMismatchError extends KoolbaseDataError {
|
|
255
255
|
constructor(message, expectedRevision, currentRevision,
|
|
256
|
-
/**
|
|
257
|
-
|
|
256
|
+
/**
|
|
257
|
+
* The record as the server holds it now. Absent when the caller may not
|
|
258
|
+
* read it ({@link readable} false): a failed write never discloses it.
|
|
259
|
+
*/
|
|
260
|
+
current,
|
|
261
|
+
/**
|
|
262
|
+
* Whether the caller may read the record now. False: the server withheld
|
|
263
|
+
* it and said only the revisions. Undefined from an older API.
|
|
264
|
+
*/
|
|
265
|
+
readable) {
|
|
258
266
|
super(message ?? 'The record has changed since you read it', 'revision_mismatch');
|
|
259
267
|
this.expectedRevision = expectedRevision;
|
|
260
268
|
this.currentRevision = currentRevision;
|
|
261
269
|
this.current = current;
|
|
270
|
+
this.readable = readable;
|
|
262
271
|
this.name = 'KoolbaseRevisionMismatchError';
|
|
263
272
|
Object.setPrototypeOf(this, KoolbaseRevisionMismatchError.prototype);
|
|
264
273
|
}
|
|
@@ -595,7 +604,7 @@ function koolbaseDataError(status, body, fallbackMessage = 'Request failed') {
|
|
|
595
604
|
// exactly this. attach() still puts the whole bag on the error, so
|
|
596
605
|
// nothing is lost for a caller reading it directly.
|
|
597
606
|
const d = (body?.details ?? {});
|
|
598
|
-
return attach(new KoolbaseRevisionMismatchError(message, d.expected_revision, d.current_revision, d.record));
|
|
607
|
+
return attach(new KoolbaseRevisionMismatchError(message, d.expected_revision, d.current_revision, d.record, typeof d.readable === 'boolean' ? d.readable : undefined));
|
|
599
608
|
}
|
|
600
609
|
// Two codes, one situation — the database and fiscal packages name it
|
|
601
610
|
// differently and a caller should not have to know which spoke.
|
package/dist/cjs/database.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import type { KbWhereNode } from './query-builder.js';
|
|
|
2
2
|
import { KoolbaseAggregateRequest, KoolbaseAggregateResult } from './aggregate.js';
|
|
3
3
|
import { KoolbaseConflict } from './conflict.js';
|
|
4
4
|
import { PendingWrite } from './pending-write.js';
|
|
5
|
-
import { KoolbaseConfig, KoolbaseRecord, QueryOptions, QueryResult, UpsertResult, BatchOp, BatchResult, KoolbaseVector, SemanticSearchResult, SearchMode } from './types.js';
|
|
5
|
+
import { KoolbaseConfig, KoolbaseRecord, QueryOptions, QueryResult, UpsertResult, BatchOp, BatchResult, KeyedWriteOptions, MutationResult, KoolbaseVector, SemanticSearchResult, SearchMode } from './types.js';
|
|
6
6
|
export declare class KoolbaseDatabase {
|
|
7
7
|
private config;
|
|
8
8
|
private getUserId;
|
|
@@ -66,7 +66,9 @@ export declare class KoolbaseDatabase {
|
|
|
66
66
|
* accepted optimistically: saved to the local cache and queued for sync
|
|
67
67
|
* when connectivity returns.
|
|
68
68
|
*/
|
|
69
|
-
insert(collection: string, data: Record<string, unknown
|
|
69
|
+
insert(collection: string, data: Record<string, unknown>,
|
|
70
|
+
/** idempotencyKey: run this insert exactly once (E4a). */
|
|
71
|
+
options?: KeyedWriteOptions): Promise<KoolbaseRecord>;
|
|
70
72
|
/**
|
|
71
73
|
* Insert a record, or update the existing one matching `match`.
|
|
72
74
|
*
|
|
@@ -82,7 +84,9 @@ export declare class KoolbaseDatabase {
|
|
|
82
84
|
* fetch is used (not `request`) so the status code is readable: 201 =
|
|
83
85
|
* created, 200 = updated.
|
|
84
86
|
*/
|
|
85
|
-
upsert(collection: string, match: Record<string, unknown>, data: Record<string, unknown
|
|
87
|
+
upsert(collection: string, match: Record<string, unknown>, data: Record<string, unknown>,
|
|
88
|
+
/** idempotencyKey: run this upsert exactly once (E4a). */
|
|
89
|
+
options?: KeyedWriteOptions): Promise<UpsertResult>;
|
|
86
90
|
/**
|
|
87
91
|
* Bulk-delete every record in `collection` matching `filters`.
|
|
88
92
|
*
|
|
@@ -118,7 +122,24 @@ export declare class KoolbaseDatabase {
|
|
|
118
122
|
* BatchOp.delete(cartItemId),
|
|
119
123
|
* ]);
|
|
120
124
|
*/
|
|
121
|
-
batch(operations: BatchOp[]
|
|
125
|
+
batch(operations: BatchOp[],
|
|
126
|
+
/** idempotencyKey: run this batch exactly once (E4a). */
|
|
127
|
+
options?: KeyedWriteOptions): Promise<BatchResult[]>;
|
|
128
|
+
/**
|
|
129
|
+
* Run `operations` as one atomic write, exactly once per `idempotencyKey`
|
|
130
|
+
* (E4a), and say whether this call ran it or replayed it.
|
|
131
|
+
*
|
|
132
|
+
* Use one key per logical write and send the same key on every retry of it.
|
|
133
|
+
* A first run returns `results`; a retry the server had already run returns
|
|
134
|
+
* `replayed: true` with `outcome` (what the original write did) and
|
|
135
|
+
* `current` (each record as it is now). The same key with a different write
|
|
136
|
+
* throws `KoolbaseConflictError` with code `idempotency_key_reused`.
|
|
137
|
+
*
|
|
138
|
+
* Online-only, as `batch`.
|
|
139
|
+
*/
|
|
140
|
+
mutate(operations: BatchOp[], options: {
|
|
141
|
+
idempotencyKey: string;
|
|
142
|
+
}): Promise<MutationResult>;
|
|
122
143
|
get(recordId: string): Promise<KoolbaseRecord>;
|
|
123
144
|
/**
|
|
124
145
|
* The device's saved copy of a record: what this device last read, with the
|
|
@@ -261,14 +282,14 @@ export declare class KoolbaseDatabase {
|
|
|
261
282
|
* with KoolbaseRevisionMismatchError otherwise (as the Flutter SDK). */
|
|
262
283
|
options?: {
|
|
263
284
|
expectedRevision?: number;
|
|
264
|
-
}): Promise<KoolbaseRecord>;
|
|
285
|
+
} & KeyedWriteOptions): Promise<KoolbaseRecord>;
|
|
265
286
|
delete(recordId: string,
|
|
266
287
|
/** expectedRevision: delete only if the record still carries it (as the
|
|
267
288
|
* Flutter SDK) -- removing a record someone changed a moment ago is the
|
|
268
289
|
* more destructive stale write. */
|
|
269
290
|
options?: {
|
|
270
291
|
expectedRevision?: number;
|
|
271
|
-
}): Promise<void>;
|
|
292
|
+
} & KeyedWriteOptions): Promise<void>;
|
|
272
293
|
/**
|
|
273
294
|
* Write (or replace) a vector for a record on the named `field`.
|
|
274
295
|
*
|
package/dist/cjs/database.js
CHANGED
|
@@ -15,6 +15,10 @@ const sync_engine_js_1 = require("./sync-engine.js");
|
|
|
15
15
|
const record_js_1 = require("./record.js");
|
|
16
16
|
const database_errors_js_2 = require("./database-errors.js");
|
|
17
17
|
const query_builder_js_1 = require("./query-builder.js");
|
|
18
|
+
/** The headers a keyed write sends (E4a); none without a key. */
|
|
19
|
+
function keyHeaders(options) {
|
|
20
|
+
return options.idempotencyKey ? { 'Idempotency-Key': options.idempotencyKey } : undefined;
|
|
21
|
+
}
|
|
18
22
|
function generateWriteId() {
|
|
19
23
|
return 'local_' + Math.random().toString(36).slice(2) + Date.now().toString(36);
|
|
20
24
|
}
|
|
@@ -33,9 +37,18 @@ function batchOpToWire(op) {
|
|
|
33
37
|
case 'insert':
|
|
34
38
|
return { type: 'insert', collection: op.collection, data: op.data };
|
|
35
39
|
case 'update':
|
|
36
|
-
return {
|
|
40
|
+
return {
|
|
41
|
+
type: 'update',
|
|
42
|
+
record_id: op.recordId,
|
|
43
|
+
data: op.data,
|
|
44
|
+
...(op.expectedRevision !== undefined ? { expected_revision: op.expectedRevision } : {}),
|
|
45
|
+
};
|
|
37
46
|
case 'delete':
|
|
38
|
-
return {
|
|
47
|
+
return {
|
|
48
|
+
type: 'delete',
|
|
49
|
+
record_id: op.recordId,
|
|
50
|
+
...(op.expectedRevision !== undefined ? { expected_revision: op.expectedRevision } : {}),
|
|
51
|
+
};
|
|
39
52
|
case 'upsert':
|
|
40
53
|
return {
|
|
41
54
|
type: 'upsert',
|
|
@@ -99,10 +112,10 @@ class KoolbaseDatabase {
|
|
|
99
112
|
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
100
113
|
};
|
|
101
114
|
}
|
|
102
|
-
async request(method, path, body) {
|
|
115
|
+
async request(method, path, body, extraHeaders) {
|
|
103
116
|
const res = await (0, network_js_1.sessionFetch)(`${this.config.baseUrl}${path}`, {
|
|
104
117
|
method,
|
|
105
|
-
headers: await this.buildHeaders(),
|
|
118
|
+
headers: { ...(await this.buildHeaders()), ...(extraHeaders ?? {}) },
|
|
106
119
|
body: body ? JSON.stringify(body) : undefined,
|
|
107
120
|
});
|
|
108
121
|
// A 204 carries no body, and some error responses carry none either.
|
|
@@ -137,10 +150,10 @@ class KoolbaseDatabase {
|
|
|
137
150
|
* hand-rolled their own fetch, each mapping errors slightly differently and
|
|
138
151
|
* none of them clearing a rejected session. One path, two shapes of result.
|
|
139
152
|
*/
|
|
140
|
-
async requestWithStatus(method, path, body) {
|
|
153
|
+
async requestWithStatus(method, path, body, extraHeaders) {
|
|
141
154
|
const res = await (0, network_js_1.sessionFetch)(`${this.config.baseUrl}${path}`, {
|
|
142
155
|
method,
|
|
143
|
-
headers: await this.buildHeaders(),
|
|
156
|
+
headers: { ...(await this.buildHeaders()), ...(extraHeaders ?? {}) },
|
|
144
157
|
body: body ? JSON.stringify(body) : undefined,
|
|
145
158
|
});
|
|
146
159
|
const text = await res.text();
|
|
@@ -286,13 +299,15 @@ class KoolbaseDatabase {
|
|
|
286
299
|
* accepted optimistically: saved to the local cache and queued for sync
|
|
287
300
|
* when connectivity returns.
|
|
288
301
|
*/
|
|
289
|
-
async insert(collection, data
|
|
302
|
+
async insert(collection, data,
|
|
303
|
+
/** idempotencyKey: run this insert exactly once (E4a). */
|
|
304
|
+
options = {}) {
|
|
290
305
|
const userId = this.getUserId() ?? 'anonymous';
|
|
291
306
|
try {
|
|
292
307
|
// Online path: await the server and return the authoritative record
|
|
293
308
|
// (with the server-assigned id). Refresh the collection cache so the
|
|
294
309
|
// next query sees real data instead of a stale optimistic copy.
|
|
295
|
-
const raw = await this.request('POST', '/v1/sdk/db/insert', { collection, data });
|
|
310
|
+
const raw = await this.request('POST', '/v1/sdk/db/insert', { collection, data }, keyHeaders(options));
|
|
296
311
|
const record = (0, record_js_1.recordFromWire)(raw);
|
|
297
312
|
await (0, cache_store_js_3.invalidateCache)(userId, collection);
|
|
298
313
|
void (0, query_refresh_js_1.refreshCollectionQueries)(collection);
|
|
@@ -363,8 +378,10 @@ class KoolbaseDatabase {
|
|
|
363
378
|
* fetch is used (not `request`) so the status code is readable: 201 =
|
|
364
379
|
* created, 200 = updated.
|
|
365
380
|
*/
|
|
366
|
-
async upsert(collection, match, data
|
|
367
|
-
|
|
381
|
+
async upsert(collection, match, data,
|
|
382
|
+
/** idempotencyKey: run this upsert exactly once (E4a). */
|
|
383
|
+
options = {}) {
|
|
384
|
+
const { status, data: body } = await this.requestWithStatus('POST', '/v1/sdk/db/upsert', { collection, match, data }, keyHeaders(options));
|
|
368
385
|
const created = status === 201;
|
|
369
386
|
const record = (0, record_js_1.recordFromWire)(body);
|
|
370
387
|
// Keep the cache fresh, same intent as insert's post-success invalidate.
|
|
@@ -417,7 +434,9 @@ class KoolbaseDatabase {
|
|
|
417
434
|
* BatchOp.delete(cartItemId),
|
|
418
435
|
* ]);
|
|
419
436
|
*/
|
|
420
|
-
async batch(operations
|
|
437
|
+
async batch(operations,
|
|
438
|
+
/** idempotencyKey: run this batch exactly once (E4a). */
|
|
439
|
+
options = {}) {
|
|
421
440
|
if (operations.length === 0) {
|
|
422
441
|
throw new Error('batch requires at least one operation');
|
|
423
442
|
}
|
|
@@ -433,7 +452,7 @@ class KoolbaseDatabase {
|
|
|
433
452
|
}
|
|
434
453
|
const body = await this.request('POST', '/v1/sdk/db/batch', {
|
|
435
454
|
operations: operations.map(batchOpToWire),
|
|
436
|
-
});
|
|
455
|
+
}, keyHeaders(options));
|
|
437
456
|
const results = (body.results ?? []).map(r => ({
|
|
438
457
|
type: r.type ?? '',
|
|
439
458
|
record: r.record
|
|
@@ -487,7 +506,53 @@ class KoolbaseDatabase {
|
|
|
487
506
|
void (0, query_refresh_js_1.refreshCollectionQueries)(undefined);
|
|
488
507
|
return results;
|
|
489
508
|
}
|
|
490
|
-
// ───
|
|
509
|
+
// ─── Mutate (keyed, exactly once) ───────────────────────────────────────────
|
|
510
|
+
/**
|
|
511
|
+
* Run `operations` as one atomic write, exactly once per `idempotencyKey`
|
|
512
|
+
* (E4a), and say whether this call ran it or replayed it.
|
|
513
|
+
*
|
|
514
|
+
* Use one key per logical write and send the same key on every retry of it.
|
|
515
|
+
* A first run returns `results`; a retry the server had already run returns
|
|
516
|
+
* `replayed: true` with `outcome` (what the original write did) and
|
|
517
|
+
* `current` (each record as it is now). The same key with a different write
|
|
518
|
+
* throws `KoolbaseConflictError` with code `idempotency_key_reused`.
|
|
519
|
+
*
|
|
520
|
+
* Online-only, as `batch`.
|
|
521
|
+
*/
|
|
522
|
+
async mutate(operations, options) {
|
|
523
|
+
if (operations.length === 0) {
|
|
524
|
+
throw new Error('mutate requires at least one operation');
|
|
525
|
+
}
|
|
526
|
+
const body = await this.request('POST', '/v1/sdk/db/batch', { operations: operations.map(batchOpToWire) }, { 'Idempotency-Key': options.idempotencyKey, 'Accept-Idempotency': 'v2' });
|
|
527
|
+
if (body?.replayed === true) {
|
|
528
|
+
const outcome = (body.outcome ?? []).map((o) => ({
|
|
529
|
+
type: o.type ?? '',
|
|
530
|
+
collection: o.collection,
|
|
531
|
+
id: o.id,
|
|
532
|
+
revisionBefore: o.revision_before,
|
|
533
|
+
revisionAfter: o.revision_after,
|
|
534
|
+
created: o.created,
|
|
535
|
+
record: o.record,
|
|
536
|
+
}));
|
|
537
|
+
// What the original write left behind may have changed since: live
|
|
538
|
+
// queries re-read rather than trust a cached copy.
|
|
539
|
+
void (0, query_refresh_js_1.refreshCollectionQueries)(undefined);
|
|
540
|
+
return {
|
|
541
|
+
replayed: true,
|
|
542
|
+
outcome,
|
|
543
|
+
current: body.current ?? [],
|
|
544
|
+
valuesOmitted: body.values_omitted === true,
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
const results = (body?.results ?? []).map((r) => ({
|
|
548
|
+
type: r.type ?? '',
|
|
549
|
+
record: r.record ? (0, record_js_1.recordFromWire)(r.record) : undefined,
|
|
550
|
+
created: r.created,
|
|
551
|
+
deleted: r.deleted ?? false,
|
|
552
|
+
}));
|
|
553
|
+
void (0, query_refresh_js_1.refreshCollectionQueries)(undefined);
|
|
554
|
+
return { replayed: false, results };
|
|
555
|
+
}
|
|
491
556
|
// ─── Get single record ──────────────────────────────────────────────────────
|
|
492
557
|
async get(recordId) {
|
|
493
558
|
const raw = await this.request('GET', `/v1/sdk/db/records/${recordId}`);
|
|
@@ -878,7 +943,7 @@ class KoolbaseDatabase {
|
|
|
878
943
|
// Resolved before the request, so a network failure has somewhere to go.
|
|
879
944
|
const base = await this.resolveBaseline(userId, recordId);
|
|
880
945
|
try {
|
|
881
|
-
const raw = await this.request('PATCH', `/v1/sdk/db/records/${recordId}`, { data, ...(options.expectedRevision !== undefined ? { expected_revision: options.expectedRevision } : {}) });
|
|
946
|
+
const raw = await this.request('PATCH', `/v1/sdk/db/records/${recordId}`, { data, ...(options.expectedRevision !== undefined ? { expected_revision: options.expectedRevision } : {}) }, keyHeaders(options));
|
|
882
947
|
const updated = (0, record_js_1.recordFromWire)(raw);
|
|
883
948
|
// Its collection's live queries re-run (every one, if the record's
|
|
884
949
|
// collection is not known).
|
|
@@ -944,7 +1009,7 @@ class KoolbaseDatabase {
|
|
|
944
1009
|
const userId = this.getUserId() ?? 'anonymous';
|
|
945
1010
|
const base = await this.resolveBaseline(userId, recordId);
|
|
946
1011
|
try {
|
|
947
|
-
await this.request('DELETE', `/v1/sdk/db/records/${recordId}${options.expectedRevision !== undefined ? `?expected_revision=${options.expectedRevision}` : ''}
|
|
1012
|
+
await this.request('DELETE', `/v1/sdk/db/records/${recordId}${options.expectedRevision !== undefined ? `?expected_revision=${options.expectedRevision}` : ''}`, undefined, keyHeaders(options));
|
|
948
1013
|
await (0, cache_store_js_1.removeCachedRecord)(userId, recordId);
|
|
949
1014
|
// Its collection is known from the baseline when the record was seen;
|
|
950
1015
|
// otherwise every live query re-runs, rather than a guess.
|
package/dist/cjs/sync-engine.js
CHANGED
|
@@ -276,7 +276,10 @@ class SyncEngine {
|
|
|
276
276
|
else if (write.operation === 'update') {
|
|
277
277
|
res = await (0, network_js_1.sessionFetch)(url, {
|
|
278
278
|
method: 'PATCH',
|
|
279
|
-
|
|
279
|
+
// E4a: the write's own id as its key, so an update whose response was
|
|
280
|
+
// lost replays as a success instead of meeting its own revision as a
|
|
281
|
+
// conflict on the next attempt.
|
|
282
|
+
headers: { ...headers, 'Idempotency-Key': write.id },
|
|
280
283
|
// The revision the change was composed against. The server applies it
|
|
281
284
|
// only if the record still carries that revision, so nothing can land
|
|
282
285
|
// between the client deciding the write is safe and the server applying
|
|
@@ -293,7 +296,10 @@ class SyncEngine {
|
|
|
293
296
|
const q = write.baseRevision !== undefined
|
|
294
297
|
? `?expected_revision=${write.baseRevision}`
|
|
295
298
|
: '';
|
|
296
|
-
res = await (0, network_js_1.sessionFetch)(`${url}${q}`, {
|
|
299
|
+
res = await (0, network_js_1.sessionFetch)(`${url}${q}`, {
|
|
300
|
+
method: 'DELETE',
|
|
301
|
+
headers: { ...headers, 'Idempotency-Key': write.id },
|
|
302
|
+
});
|
|
297
303
|
}
|
|
298
304
|
if (res.status === 401) {
|
|
299
305
|
// A refused app key is setup, not a session (#169): never signs out.
|
package/dist/cjs/types.d.ts
CHANGED
|
@@ -719,9 +719,13 @@ export type BatchOp = {
|
|
|
719
719
|
type: 'update';
|
|
720
720
|
recordId: string;
|
|
721
721
|
data: Record<string, unknown>;
|
|
722
|
+
/** Conditional: applies only if the record still carries this revision; a mismatch rolls back the whole batch. */
|
|
723
|
+
expectedRevision?: number;
|
|
722
724
|
} | {
|
|
723
725
|
type: 'delete';
|
|
724
726
|
recordId: string;
|
|
727
|
+
/** Conditional, as update's (needs the API with conditional batch deletes). */
|
|
728
|
+
expectedRevision?: number;
|
|
725
729
|
} | {
|
|
726
730
|
type: 'upsert';
|
|
727
731
|
collection: string;
|
|
@@ -735,13 +739,52 @@ export type BatchOp = {
|
|
|
735
739
|
*/
|
|
736
740
|
export declare const BatchOp: {
|
|
737
741
|
insert: (collection: string, data: Record<string, unknown>) => BatchOp;
|
|
738
|
-
update: (recordId: string, data: Record<string, unknown
|
|
739
|
-
|
|
742
|
+
update: (recordId: string, data: Record<string, unknown>, opts?: {
|
|
743
|
+
expectedRevision?: number;
|
|
744
|
+
}) => BatchOp;
|
|
745
|
+
delete: (recordId: string, opts?: {
|
|
746
|
+
expectedRevision?: number;
|
|
747
|
+
}) => BatchOp;
|
|
740
748
|
upsert: (collection: string, opts: {
|
|
741
749
|
match: Record<string, unknown>;
|
|
742
750
|
data: Record<string, unknown>;
|
|
743
751
|
}) => BatchOp;
|
|
744
752
|
};
|
|
753
|
+
/**
|
|
754
|
+
* Options for a write that must run exactly once (E4a).
|
|
755
|
+
*
|
|
756
|
+
* `idempotencyKey`: 16 to 128 letters, digits, `_` or `-`, one per logical
|
|
757
|
+
* write and the same on every retry of it. The server runs the write once;
|
|
758
|
+
* a retry gets the original answer, and the same key with a different write
|
|
759
|
+
* is refused with `idempotency_key_reused`.
|
|
760
|
+
*/
|
|
761
|
+
export interface KeyedWriteOptions {
|
|
762
|
+
idempotencyKey?: string;
|
|
763
|
+
}
|
|
764
|
+
/**
|
|
765
|
+
* What a keyed `mutate` returned (E4a).
|
|
766
|
+
*
|
|
767
|
+
* On a first run, `results` holds each operation's result. On a retry the
|
|
768
|
+
* server already ran, `replayed` is true and `outcome` holds what the
|
|
769
|
+
* original write did (each record as that write left it) while `current`
|
|
770
|
+
* holds each record as it is now -- never merged. A record the caller can no
|
|
771
|
+
* longer read comes back as `{ $id, readable: false }`, with no values.
|
|
772
|
+
*/
|
|
773
|
+
export interface MutationResult {
|
|
774
|
+
replayed: boolean;
|
|
775
|
+
results?: BatchResult[];
|
|
776
|
+
outcome?: Array<{
|
|
777
|
+
type: string;
|
|
778
|
+
collection?: string;
|
|
779
|
+
id?: string;
|
|
780
|
+
revisionBefore?: number;
|
|
781
|
+
revisionAfter?: number;
|
|
782
|
+
created?: boolean;
|
|
783
|
+
record?: Record<string, unknown>;
|
|
784
|
+
}>;
|
|
785
|
+
current?: Array<Record<string, unknown> | null>;
|
|
786
|
+
valuesOmitted?: boolean;
|
|
787
|
+
}
|
|
745
788
|
export interface BatchResult {
|
|
746
789
|
type: string;
|
|
747
790
|
record?: KoolbaseRecord;
|
package/dist/cjs/types.js
CHANGED
|
@@ -29,8 +29,17 @@ var FunctionRuntime;
|
|
|
29
29
|
*/
|
|
30
30
|
exports.BatchOp = {
|
|
31
31
|
insert: (collection, data) => ({ type: 'insert', collection, data }),
|
|
32
|
-
update: (recordId, data) => ({
|
|
33
|
-
|
|
32
|
+
update: (recordId, data, opts) => ({
|
|
33
|
+
type: 'update',
|
|
34
|
+
recordId,
|
|
35
|
+
data,
|
|
36
|
+
...(opts?.expectedRevision !== undefined ? { expectedRevision: opts.expectedRevision } : {}),
|
|
37
|
+
}),
|
|
38
|
+
delete: (recordId, opts) => ({
|
|
39
|
+
type: 'delete',
|
|
40
|
+
recordId,
|
|
41
|
+
...(opts?.expectedRevision !== undefined ? { expectedRevision: opts.expectedRevision } : {}),
|
|
42
|
+
}),
|
|
34
43
|
upsert: (collection, opts) => ({
|
|
35
44
|
type: 'upsert',
|
|
36
45
|
collection,
|
|
@@ -188,11 +188,27 @@ export declare class KoolbaseProviderInvalidError extends KoolbaseDataError {
|
|
|
188
188
|
export declare class KoolbaseRevisionMismatchError extends KoolbaseDataError {
|
|
189
189
|
readonly expectedRevision?: number | undefined;
|
|
190
190
|
readonly currentRevision?: number | undefined;
|
|
191
|
-
/**
|
|
191
|
+
/**
|
|
192
|
+
* The record as the server holds it now. Absent when the caller may not
|
|
193
|
+
* read it ({@link readable} false): a failed write never discloses it.
|
|
194
|
+
*/
|
|
192
195
|
readonly current?: Record<string, unknown> | undefined;
|
|
196
|
+
/**
|
|
197
|
+
* Whether the caller may read the record now. False: the server withheld
|
|
198
|
+
* it and said only the revisions. Undefined from an older API.
|
|
199
|
+
*/
|
|
200
|
+
readonly readable?: boolean | undefined;
|
|
193
201
|
constructor(message?: string, expectedRevision?: number | undefined, currentRevision?: number | undefined,
|
|
194
|
-
/**
|
|
195
|
-
|
|
202
|
+
/**
|
|
203
|
+
* The record as the server holds it now. Absent when the caller may not
|
|
204
|
+
* read it ({@link readable} false): a failed write never discloses it.
|
|
205
|
+
*/
|
|
206
|
+
current?: Record<string, unknown> | undefined,
|
|
207
|
+
/**
|
|
208
|
+
* Whether the caller may read the record now. False: the server withheld
|
|
209
|
+
* it and said only the revisions. Undefined from an older API.
|
|
210
|
+
*/
|
|
211
|
+
readable?: boolean | undefined);
|
|
196
212
|
}
|
|
197
213
|
/**
|
|
198
214
|
* The same idempotency key sent with different data.
|
|
@@ -233,12 +233,21 @@ export class KoolbaseProviderInvalidError extends KoolbaseDataError {
|
|
|
233
233
|
}
|
|
234
234
|
export class KoolbaseRevisionMismatchError extends KoolbaseDataError {
|
|
235
235
|
constructor(message, expectedRevision, currentRevision,
|
|
236
|
-
/**
|
|
237
|
-
|
|
236
|
+
/**
|
|
237
|
+
* The record as the server holds it now. Absent when the caller may not
|
|
238
|
+
* read it ({@link readable} false): a failed write never discloses it.
|
|
239
|
+
*/
|
|
240
|
+
current,
|
|
241
|
+
/**
|
|
242
|
+
* Whether the caller may read the record now. False: the server withheld
|
|
243
|
+
* it and said only the revisions. Undefined from an older API.
|
|
244
|
+
*/
|
|
245
|
+
readable) {
|
|
238
246
|
super(message ?? 'The record has changed since you read it', 'revision_mismatch');
|
|
239
247
|
this.expectedRevision = expectedRevision;
|
|
240
248
|
this.currentRevision = currentRevision;
|
|
241
249
|
this.current = current;
|
|
250
|
+
this.readable = readable;
|
|
242
251
|
this.name = 'KoolbaseRevisionMismatchError';
|
|
243
252
|
Object.setPrototypeOf(this, KoolbaseRevisionMismatchError.prototype);
|
|
244
253
|
}
|
|
@@ -557,7 +566,7 @@ export function koolbaseDataError(status, body, fallbackMessage = 'Request faile
|
|
|
557
566
|
// exactly this. attach() still puts the whole bag on the error, so
|
|
558
567
|
// nothing is lost for a caller reading it directly.
|
|
559
568
|
const d = (body?.details ?? {});
|
|
560
|
-
return attach(new KoolbaseRevisionMismatchError(message, d.expected_revision, d.current_revision, d.record));
|
|
569
|
+
return attach(new KoolbaseRevisionMismatchError(message, d.expected_revision, d.current_revision, d.record, typeof d.readable === 'boolean' ? d.readable : undefined));
|
|
561
570
|
}
|
|
562
571
|
// Two codes, one situation — the database and fiscal packages name it
|
|
563
572
|
// differently and a caller should not have to know which spoke.
|
package/dist/esm/database.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import type { KbWhereNode } from './query-builder.js';
|
|
|
2
2
|
import { KoolbaseAggregateRequest, KoolbaseAggregateResult } from './aggregate.js';
|
|
3
3
|
import { KoolbaseConflict } from './conflict.js';
|
|
4
4
|
import { PendingWrite } from './pending-write.js';
|
|
5
|
-
import { KoolbaseConfig, KoolbaseRecord, QueryOptions, QueryResult, UpsertResult, BatchOp, BatchResult, KoolbaseVector, SemanticSearchResult, SearchMode } from './types.js';
|
|
5
|
+
import { KoolbaseConfig, KoolbaseRecord, QueryOptions, QueryResult, UpsertResult, BatchOp, BatchResult, KeyedWriteOptions, MutationResult, KoolbaseVector, SemanticSearchResult, SearchMode } from './types.js';
|
|
6
6
|
export declare class KoolbaseDatabase {
|
|
7
7
|
private config;
|
|
8
8
|
private getUserId;
|
|
@@ -66,7 +66,9 @@ export declare class KoolbaseDatabase {
|
|
|
66
66
|
* accepted optimistically: saved to the local cache and queued for sync
|
|
67
67
|
* when connectivity returns.
|
|
68
68
|
*/
|
|
69
|
-
insert(collection: string, data: Record<string, unknown
|
|
69
|
+
insert(collection: string, data: Record<string, unknown>,
|
|
70
|
+
/** idempotencyKey: run this insert exactly once (E4a). */
|
|
71
|
+
options?: KeyedWriteOptions): Promise<KoolbaseRecord>;
|
|
70
72
|
/**
|
|
71
73
|
* Insert a record, or update the existing one matching `match`.
|
|
72
74
|
*
|
|
@@ -82,7 +84,9 @@ export declare class KoolbaseDatabase {
|
|
|
82
84
|
* fetch is used (not `request`) so the status code is readable: 201 =
|
|
83
85
|
* created, 200 = updated.
|
|
84
86
|
*/
|
|
85
|
-
upsert(collection: string, match: Record<string, unknown>, data: Record<string, unknown
|
|
87
|
+
upsert(collection: string, match: Record<string, unknown>, data: Record<string, unknown>,
|
|
88
|
+
/** idempotencyKey: run this upsert exactly once (E4a). */
|
|
89
|
+
options?: KeyedWriteOptions): Promise<UpsertResult>;
|
|
86
90
|
/**
|
|
87
91
|
* Bulk-delete every record in `collection` matching `filters`.
|
|
88
92
|
*
|
|
@@ -118,7 +122,24 @@ export declare class KoolbaseDatabase {
|
|
|
118
122
|
* BatchOp.delete(cartItemId),
|
|
119
123
|
* ]);
|
|
120
124
|
*/
|
|
121
|
-
batch(operations: BatchOp[]
|
|
125
|
+
batch(operations: BatchOp[],
|
|
126
|
+
/** idempotencyKey: run this batch exactly once (E4a). */
|
|
127
|
+
options?: KeyedWriteOptions): Promise<BatchResult[]>;
|
|
128
|
+
/**
|
|
129
|
+
* Run `operations` as one atomic write, exactly once per `idempotencyKey`
|
|
130
|
+
* (E4a), and say whether this call ran it or replayed it.
|
|
131
|
+
*
|
|
132
|
+
* Use one key per logical write and send the same key on every retry of it.
|
|
133
|
+
* A first run returns `results`; a retry the server had already run returns
|
|
134
|
+
* `replayed: true` with `outcome` (what the original write did) and
|
|
135
|
+
* `current` (each record as it is now). The same key with a different write
|
|
136
|
+
* throws `KoolbaseConflictError` with code `idempotency_key_reused`.
|
|
137
|
+
*
|
|
138
|
+
* Online-only, as `batch`.
|
|
139
|
+
*/
|
|
140
|
+
mutate(operations: BatchOp[], options: {
|
|
141
|
+
idempotencyKey: string;
|
|
142
|
+
}): Promise<MutationResult>;
|
|
122
143
|
get(recordId: string): Promise<KoolbaseRecord>;
|
|
123
144
|
/**
|
|
124
145
|
* The device's saved copy of a record: what this device last read, with the
|
|
@@ -261,14 +282,14 @@ export declare class KoolbaseDatabase {
|
|
|
261
282
|
* with KoolbaseRevisionMismatchError otherwise (as the Flutter SDK). */
|
|
262
283
|
options?: {
|
|
263
284
|
expectedRevision?: number;
|
|
264
|
-
}): Promise<KoolbaseRecord>;
|
|
285
|
+
} & KeyedWriteOptions): Promise<KoolbaseRecord>;
|
|
265
286
|
delete(recordId: string,
|
|
266
287
|
/** expectedRevision: delete only if the record still carries it (as the
|
|
267
288
|
* Flutter SDK) -- removing a record someone changed a moment ago is the
|
|
268
289
|
* more destructive stale write. */
|
|
269
290
|
options?: {
|
|
270
291
|
expectedRevision?: number;
|
|
271
|
-
}): Promise<void>;
|
|
292
|
+
} & KeyedWriteOptions): Promise<void>;
|
|
272
293
|
/**
|
|
273
294
|
* Write (or replace) a vector for a record on the named `field`.
|
|
274
295
|
*
|
package/dist/esm/database.js
CHANGED
|
@@ -12,6 +12,10 @@ import { SyncEngine } from './sync-engine.js';
|
|
|
12
12
|
import { recordFromWire } from './record.js';
|
|
13
13
|
import { koolbaseDataError, KoolbaseDataError } from './database-errors.js';
|
|
14
14
|
import { deviceZone, isTypedQuery } from './query-builder.js';
|
|
15
|
+
/** The headers a keyed write sends (E4a); none without a key. */
|
|
16
|
+
function keyHeaders(options) {
|
|
17
|
+
return options.idempotencyKey ? { 'Idempotency-Key': options.idempotencyKey } : undefined;
|
|
18
|
+
}
|
|
15
19
|
function generateWriteId() {
|
|
16
20
|
return 'local_' + Math.random().toString(36).slice(2) + Date.now().toString(36);
|
|
17
21
|
}
|
|
@@ -30,9 +34,18 @@ function batchOpToWire(op) {
|
|
|
30
34
|
case 'insert':
|
|
31
35
|
return { type: 'insert', collection: op.collection, data: op.data };
|
|
32
36
|
case 'update':
|
|
33
|
-
return {
|
|
37
|
+
return {
|
|
38
|
+
type: 'update',
|
|
39
|
+
record_id: op.recordId,
|
|
40
|
+
data: op.data,
|
|
41
|
+
...(op.expectedRevision !== undefined ? { expected_revision: op.expectedRevision } : {}),
|
|
42
|
+
};
|
|
34
43
|
case 'delete':
|
|
35
|
-
return {
|
|
44
|
+
return {
|
|
45
|
+
type: 'delete',
|
|
46
|
+
record_id: op.recordId,
|
|
47
|
+
...(op.expectedRevision !== undefined ? { expected_revision: op.expectedRevision } : {}),
|
|
48
|
+
};
|
|
36
49
|
case 'upsert':
|
|
37
50
|
return {
|
|
38
51
|
type: 'upsert',
|
|
@@ -96,10 +109,10 @@ export class KoolbaseDatabase {
|
|
|
96
109
|
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
97
110
|
};
|
|
98
111
|
}
|
|
99
|
-
async request(method, path, body) {
|
|
112
|
+
async request(method, path, body, extraHeaders) {
|
|
100
113
|
const res = await sessionFetch(`${this.config.baseUrl}${path}`, {
|
|
101
114
|
method,
|
|
102
|
-
headers: await this.buildHeaders(),
|
|
115
|
+
headers: { ...(await this.buildHeaders()), ...(extraHeaders ?? {}) },
|
|
103
116
|
body: body ? JSON.stringify(body) : undefined,
|
|
104
117
|
});
|
|
105
118
|
// A 204 carries no body, and some error responses carry none either.
|
|
@@ -134,10 +147,10 @@ export class KoolbaseDatabase {
|
|
|
134
147
|
* hand-rolled their own fetch, each mapping errors slightly differently and
|
|
135
148
|
* none of them clearing a rejected session. One path, two shapes of result.
|
|
136
149
|
*/
|
|
137
|
-
async requestWithStatus(method, path, body) {
|
|
150
|
+
async requestWithStatus(method, path, body, extraHeaders) {
|
|
138
151
|
const res = await sessionFetch(`${this.config.baseUrl}${path}`, {
|
|
139
152
|
method,
|
|
140
|
-
headers: await this.buildHeaders(),
|
|
153
|
+
headers: { ...(await this.buildHeaders()), ...(extraHeaders ?? {}) },
|
|
141
154
|
body: body ? JSON.stringify(body) : undefined,
|
|
142
155
|
});
|
|
143
156
|
const text = await res.text();
|
|
@@ -283,13 +296,15 @@ export class KoolbaseDatabase {
|
|
|
283
296
|
* accepted optimistically: saved to the local cache and queued for sync
|
|
284
297
|
* when connectivity returns.
|
|
285
298
|
*/
|
|
286
|
-
async insert(collection, data
|
|
299
|
+
async insert(collection, data,
|
|
300
|
+
/** idempotencyKey: run this insert exactly once (E4a). */
|
|
301
|
+
options = {}) {
|
|
287
302
|
const userId = this.getUserId() ?? 'anonymous';
|
|
288
303
|
try {
|
|
289
304
|
// Online path: await the server and return the authoritative record
|
|
290
305
|
// (with the server-assigned id). Refresh the collection cache so the
|
|
291
306
|
// next query sees real data instead of a stale optimistic copy.
|
|
292
|
-
const raw = await this.request('POST', '/v1/sdk/db/insert', { collection, data });
|
|
307
|
+
const raw = await this.request('POST', '/v1/sdk/db/insert', { collection, data }, keyHeaders(options));
|
|
293
308
|
const record = recordFromWire(raw);
|
|
294
309
|
await invalidateCache(userId, collection);
|
|
295
310
|
void refreshCollectionQueries(collection);
|
|
@@ -360,8 +375,10 @@ export class KoolbaseDatabase {
|
|
|
360
375
|
* fetch is used (not `request`) so the status code is readable: 201 =
|
|
361
376
|
* created, 200 = updated.
|
|
362
377
|
*/
|
|
363
|
-
async upsert(collection, match, data
|
|
364
|
-
|
|
378
|
+
async upsert(collection, match, data,
|
|
379
|
+
/** idempotencyKey: run this upsert exactly once (E4a). */
|
|
380
|
+
options = {}) {
|
|
381
|
+
const { status, data: body } = await this.requestWithStatus('POST', '/v1/sdk/db/upsert', { collection, match, data }, keyHeaders(options));
|
|
365
382
|
const created = status === 201;
|
|
366
383
|
const record = recordFromWire(body);
|
|
367
384
|
// Keep the cache fresh, same intent as insert's post-success invalidate.
|
|
@@ -414,7 +431,9 @@ export class KoolbaseDatabase {
|
|
|
414
431
|
* BatchOp.delete(cartItemId),
|
|
415
432
|
* ]);
|
|
416
433
|
*/
|
|
417
|
-
async batch(operations
|
|
434
|
+
async batch(operations,
|
|
435
|
+
/** idempotencyKey: run this batch exactly once (E4a). */
|
|
436
|
+
options = {}) {
|
|
418
437
|
if (operations.length === 0) {
|
|
419
438
|
throw new Error('batch requires at least one operation');
|
|
420
439
|
}
|
|
@@ -430,7 +449,7 @@ export class KoolbaseDatabase {
|
|
|
430
449
|
}
|
|
431
450
|
const body = await this.request('POST', '/v1/sdk/db/batch', {
|
|
432
451
|
operations: operations.map(batchOpToWire),
|
|
433
|
-
});
|
|
452
|
+
}, keyHeaders(options));
|
|
434
453
|
const results = (body.results ?? []).map(r => ({
|
|
435
454
|
type: r.type ?? '',
|
|
436
455
|
record: r.record
|
|
@@ -484,7 +503,53 @@ export class KoolbaseDatabase {
|
|
|
484
503
|
void refreshCollectionQueries(undefined);
|
|
485
504
|
return results;
|
|
486
505
|
}
|
|
487
|
-
// ───
|
|
506
|
+
// ─── Mutate (keyed, exactly once) ───────────────────────────────────────────
|
|
507
|
+
/**
|
|
508
|
+
* Run `operations` as one atomic write, exactly once per `idempotencyKey`
|
|
509
|
+
* (E4a), and say whether this call ran it or replayed it.
|
|
510
|
+
*
|
|
511
|
+
* Use one key per logical write and send the same key on every retry of it.
|
|
512
|
+
* A first run returns `results`; a retry the server had already run returns
|
|
513
|
+
* `replayed: true` with `outcome` (what the original write did) and
|
|
514
|
+
* `current` (each record as it is now). The same key with a different write
|
|
515
|
+
* throws `KoolbaseConflictError` with code `idempotency_key_reused`.
|
|
516
|
+
*
|
|
517
|
+
* Online-only, as `batch`.
|
|
518
|
+
*/
|
|
519
|
+
async mutate(operations, options) {
|
|
520
|
+
if (operations.length === 0) {
|
|
521
|
+
throw new Error('mutate requires at least one operation');
|
|
522
|
+
}
|
|
523
|
+
const body = await this.request('POST', '/v1/sdk/db/batch', { operations: operations.map(batchOpToWire) }, { 'Idempotency-Key': options.idempotencyKey, 'Accept-Idempotency': 'v2' });
|
|
524
|
+
if (body?.replayed === true) {
|
|
525
|
+
const outcome = (body.outcome ?? []).map((o) => ({
|
|
526
|
+
type: o.type ?? '',
|
|
527
|
+
collection: o.collection,
|
|
528
|
+
id: o.id,
|
|
529
|
+
revisionBefore: o.revision_before,
|
|
530
|
+
revisionAfter: o.revision_after,
|
|
531
|
+
created: o.created,
|
|
532
|
+
record: o.record,
|
|
533
|
+
}));
|
|
534
|
+
// What the original write left behind may have changed since: live
|
|
535
|
+
// queries re-read rather than trust a cached copy.
|
|
536
|
+
void refreshCollectionQueries(undefined);
|
|
537
|
+
return {
|
|
538
|
+
replayed: true,
|
|
539
|
+
outcome,
|
|
540
|
+
current: body.current ?? [],
|
|
541
|
+
valuesOmitted: body.values_omitted === true,
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
const results = (body?.results ?? []).map((r) => ({
|
|
545
|
+
type: r.type ?? '',
|
|
546
|
+
record: r.record ? recordFromWire(r.record) : undefined,
|
|
547
|
+
created: r.created,
|
|
548
|
+
deleted: r.deleted ?? false,
|
|
549
|
+
}));
|
|
550
|
+
void refreshCollectionQueries(undefined);
|
|
551
|
+
return { replayed: false, results };
|
|
552
|
+
}
|
|
488
553
|
// ─── Get single record ──────────────────────────────────────────────────────
|
|
489
554
|
async get(recordId) {
|
|
490
555
|
const raw = await this.request('GET', `/v1/sdk/db/records/${recordId}`);
|
|
@@ -875,7 +940,7 @@ export class KoolbaseDatabase {
|
|
|
875
940
|
// Resolved before the request, so a network failure has somewhere to go.
|
|
876
941
|
const base = await this.resolveBaseline(userId, recordId);
|
|
877
942
|
try {
|
|
878
|
-
const raw = await this.request('PATCH', `/v1/sdk/db/records/${recordId}`, { data, ...(options.expectedRevision !== undefined ? { expected_revision: options.expectedRevision } : {}) });
|
|
943
|
+
const raw = await this.request('PATCH', `/v1/sdk/db/records/${recordId}`, { data, ...(options.expectedRevision !== undefined ? { expected_revision: options.expectedRevision } : {}) }, keyHeaders(options));
|
|
879
944
|
const updated = recordFromWire(raw);
|
|
880
945
|
// Its collection's live queries re-run (every one, if the record's
|
|
881
946
|
// collection is not known).
|
|
@@ -941,7 +1006,7 @@ export class KoolbaseDatabase {
|
|
|
941
1006
|
const userId = this.getUserId() ?? 'anonymous';
|
|
942
1007
|
const base = await this.resolveBaseline(userId, recordId);
|
|
943
1008
|
try {
|
|
944
|
-
await this.request('DELETE', `/v1/sdk/db/records/${recordId}${options.expectedRevision !== undefined ? `?expected_revision=${options.expectedRevision}` : ''}
|
|
1009
|
+
await this.request('DELETE', `/v1/sdk/db/records/${recordId}${options.expectedRevision !== undefined ? `?expected_revision=${options.expectedRevision}` : ''}`, undefined, keyHeaders(options));
|
|
945
1010
|
await removeCachedRecord(userId, recordId);
|
|
946
1011
|
// Its collection is known from the baseline when the record was seen;
|
|
947
1012
|
// otherwise every live query re-runs, rather than a guess.
|
package/dist/esm/sync-engine.js
CHANGED
|
@@ -273,7 +273,10 @@ export class SyncEngine {
|
|
|
273
273
|
else if (write.operation === 'update') {
|
|
274
274
|
res = await sessionFetch(url, {
|
|
275
275
|
method: 'PATCH',
|
|
276
|
-
|
|
276
|
+
// E4a: the write's own id as its key, so an update whose response was
|
|
277
|
+
// lost replays as a success instead of meeting its own revision as a
|
|
278
|
+
// conflict on the next attempt.
|
|
279
|
+
headers: { ...headers, 'Idempotency-Key': write.id },
|
|
277
280
|
// The revision the change was composed against. The server applies it
|
|
278
281
|
// only if the record still carries that revision, so nothing can land
|
|
279
282
|
// between the client deciding the write is safe and the server applying
|
|
@@ -290,7 +293,10 @@ export class SyncEngine {
|
|
|
290
293
|
const q = write.baseRevision !== undefined
|
|
291
294
|
? `?expected_revision=${write.baseRevision}`
|
|
292
295
|
: '';
|
|
293
|
-
res = await sessionFetch(`${url}${q}`, {
|
|
296
|
+
res = await sessionFetch(`${url}${q}`, {
|
|
297
|
+
method: 'DELETE',
|
|
298
|
+
headers: { ...headers, 'Idempotency-Key': write.id },
|
|
299
|
+
});
|
|
294
300
|
}
|
|
295
301
|
if (res.status === 401) {
|
|
296
302
|
// A refused app key is setup, not a session (#169): never signs out.
|
package/dist/esm/types.d.ts
CHANGED
|
@@ -719,9 +719,13 @@ export type BatchOp = {
|
|
|
719
719
|
type: 'update';
|
|
720
720
|
recordId: string;
|
|
721
721
|
data: Record<string, unknown>;
|
|
722
|
+
/** Conditional: applies only if the record still carries this revision; a mismatch rolls back the whole batch. */
|
|
723
|
+
expectedRevision?: number;
|
|
722
724
|
} | {
|
|
723
725
|
type: 'delete';
|
|
724
726
|
recordId: string;
|
|
727
|
+
/** Conditional, as update's (needs the API with conditional batch deletes). */
|
|
728
|
+
expectedRevision?: number;
|
|
725
729
|
} | {
|
|
726
730
|
type: 'upsert';
|
|
727
731
|
collection: string;
|
|
@@ -735,13 +739,52 @@ export type BatchOp = {
|
|
|
735
739
|
*/
|
|
736
740
|
export declare const BatchOp: {
|
|
737
741
|
insert: (collection: string, data: Record<string, unknown>) => BatchOp;
|
|
738
|
-
update: (recordId: string, data: Record<string, unknown
|
|
739
|
-
|
|
742
|
+
update: (recordId: string, data: Record<string, unknown>, opts?: {
|
|
743
|
+
expectedRevision?: number;
|
|
744
|
+
}) => BatchOp;
|
|
745
|
+
delete: (recordId: string, opts?: {
|
|
746
|
+
expectedRevision?: number;
|
|
747
|
+
}) => BatchOp;
|
|
740
748
|
upsert: (collection: string, opts: {
|
|
741
749
|
match: Record<string, unknown>;
|
|
742
750
|
data: Record<string, unknown>;
|
|
743
751
|
}) => BatchOp;
|
|
744
752
|
};
|
|
753
|
+
/**
|
|
754
|
+
* Options for a write that must run exactly once (E4a).
|
|
755
|
+
*
|
|
756
|
+
* `idempotencyKey`: 16 to 128 letters, digits, `_` or `-`, one per logical
|
|
757
|
+
* write and the same on every retry of it. The server runs the write once;
|
|
758
|
+
* a retry gets the original answer, and the same key with a different write
|
|
759
|
+
* is refused with `idempotency_key_reused`.
|
|
760
|
+
*/
|
|
761
|
+
export interface KeyedWriteOptions {
|
|
762
|
+
idempotencyKey?: string;
|
|
763
|
+
}
|
|
764
|
+
/**
|
|
765
|
+
* What a keyed `mutate` returned (E4a).
|
|
766
|
+
*
|
|
767
|
+
* On a first run, `results` holds each operation's result. On a retry the
|
|
768
|
+
* server already ran, `replayed` is true and `outcome` holds what the
|
|
769
|
+
* original write did (each record as that write left it) while `current`
|
|
770
|
+
* holds each record as it is now -- never merged. A record the caller can no
|
|
771
|
+
* longer read comes back as `{ $id, readable: false }`, with no values.
|
|
772
|
+
*/
|
|
773
|
+
export interface MutationResult {
|
|
774
|
+
replayed: boolean;
|
|
775
|
+
results?: BatchResult[];
|
|
776
|
+
outcome?: Array<{
|
|
777
|
+
type: string;
|
|
778
|
+
collection?: string;
|
|
779
|
+
id?: string;
|
|
780
|
+
revisionBefore?: number;
|
|
781
|
+
revisionAfter?: number;
|
|
782
|
+
created?: boolean;
|
|
783
|
+
record?: Record<string, unknown>;
|
|
784
|
+
}>;
|
|
785
|
+
current?: Array<Record<string, unknown> | null>;
|
|
786
|
+
valuesOmitted?: boolean;
|
|
787
|
+
}
|
|
745
788
|
export interface BatchResult {
|
|
746
789
|
type: string;
|
|
747
790
|
record?: KoolbaseRecord;
|
package/dist/esm/types.js
CHANGED
|
@@ -26,8 +26,17 @@ export var FunctionRuntime;
|
|
|
26
26
|
*/
|
|
27
27
|
export const BatchOp = {
|
|
28
28
|
insert: (collection, data) => ({ type: 'insert', collection, data }),
|
|
29
|
-
update: (recordId, data) => ({
|
|
30
|
-
|
|
29
|
+
update: (recordId, data, opts) => ({
|
|
30
|
+
type: 'update',
|
|
31
|
+
recordId,
|
|
32
|
+
data,
|
|
33
|
+
...(opts?.expectedRevision !== undefined ? { expectedRevision: opts.expectedRevision } : {}),
|
|
34
|
+
}),
|
|
35
|
+
delete: (recordId, opts) => ({
|
|
36
|
+
type: 'delete',
|
|
37
|
+
recordId,
|
|
38
|
+
...(opts?.expectedRevision !== undefined ? { expectedRevision: opts.expectedRevision } : {}),
|
|
39
|
+
}),
|
|
31
40
|
upsert: (collection, opts) => ({
|
|
32
41
|
type: 'upsert',
|
|
33
42
|
collection,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@koolbase/core",
|
|
3
|
-
"version": "12.
|
|
3
|
+
"version": "12.51.0",
|
|
4
4
|
"description": "Koolbase SDK core — shared behaviour behind @koolbase/react-native and @koolbase/js. Install one of those, not this.",
|
|
5
5
|
"main": "./dist/cjs/index.js",
|
|
6
6
|
"react-native": "./dist/esm/index.js",
|