@n-dream/builders-sdk 1.0.0 → 1.4.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/engine.js ADDED
@@ -0,0 +1,981 @@
1
+ // The data engine (docs/login-and-data.md 6.2 to 6.5, 9.2, 9.4): the calls
2
+ // of a collection on top of a small storage interface. The data service
3
+ // runs it on Firestore ("appdata"), the api's MCP tools too, and the local
4
+ // mode of the SDK runs it on the memory storage (memory-storage.ts). So the
5
+ // rules, the ids, the usage counters, the markers and the change log are
6
+ // the same code in all of them (LD15, D135).
7
+ import { CHANGES_MAX, COUNT_MAX, CURSOR_MAX_AGE_MS, FILE_HEAD_BYTES, FILE_ID, LIST_DEFAULT, LIST_MAX, MESSAGES, NS_OF, accessError, checkData, checkFileName, checkFileType, docIdOf, encodeCursor, fileDocIdOf, fileIdOf, fileObjectOf, fileSetOf, fileTypeOf, fileUrlOf, isRuleError, isoOfUs, itemRef, planQuery, publicIdOf, ruleError, ruleOf, scopeOf, slotsOf, } from "./rules.js";
8
+ // --- Storage. ---
9
+ // The commit time of the write. Firestore: FieldValue.serverTimestamp().
10
+ export const SERVER_TIME = Object.freeze({ serverTime: true });
11
+ // Removes the field in a set with merge. Firestore: FieldValue.delete().
12
+ export const DELETE_FIELD = Object.freeze({ deleteField: true });
13
+ // Fields that hold a time. Storage gives them as microseconds (a number)
14
+ // and takes a number of microseconds or SERVER_TIME.
15
+ export const TIME_FIELDS = ["createdAt", "updatedAt", "at", "removedAt", "resetAt", "expireAt"];
16
+ // --- Paths (6.2). ---
17
+ export const spaceKey = (appId, space) => `${appId}.${space}`;
18
+ export const paths = {
19
+ doc: (key, docId) => `spaces/${key}/docs/${docId}`,
20
+ removed: (key, docId) => `spaces/${key}/removed/${docId}`,
21
+ mark: (key, ns, scope) => `spaces/${key}/marks/${ns}.${scope}`,
22
+ colls: (key, ns, coll) => `spaces/${key}/colls/${ns}.${coll}`,
23
+ usage: (key, uid) => `spaces/${key}/usage/${uid}`,
24
+ // The file counts of one user (7).
25
+ fileUsage: (key, uid) => `spaces/${key}/usage/f.${uid}`,
26
+ appUsage: (key) => `spaces/${key}/usage/_app`,
27
+ file: (key, docId) => `spaces/${key}/files/${docId}`,
28
+ // The file bytes of all apps of one owner (11.1), counted as usage/_app.
29
+ ownerUsage: (ownerId) => `spaces/_owners/usage/${ownerId}`,
30
+ };
31
+ // The key of an owner's counts (AppCounters).
32
+ export const ownerKey = (ownerId) => `_owners/${ownerId}`;
33
+ // --- Errors. ---
34
+ export class RuleFailure extends Error {
35
+ rule;
36
+ constructor(rule) {
37
+ super(rule.message);
38
+ this.rule = rule;
39
+ this.name = "RuleFailure";
40
+ }
41
+ }
42
+ // The change of the counts of a file upload that committed its record
43
+ // but still ends with an error: the caller counts it all the same.
44
+ export function countedDelta(e) {
45
+ return typeof e === "object" && e !== null && e.countedDelta ? e.countedDelta : null;
46
+ }
47
+ function withDelta(e, delta) {
48
+ if (typeof e === "object" && e !== null)
49
+ e.countedDelta = delta;
50
+ return e;
51
+ }
52
+ function must(v) {
53
+ if (isRuleError(v))
54
+ throw new RuleFailure(v);
55
+ return v;
56
+ }
57
+ function allow(e) {
58
+ if (e)
59
+ throw new RuleFailure(e);
60
+ }
61
+ const COLLS_CACHE_MS = 5_000;
62
+ const COLLS_PREPARING_CACHE_MS = 1_000;
63
+ const LEASE_MS = 60_000;
64
+ // Reads of a batch can be large (items of 100 KB); the writes have only the
65
+ // slots, far below the 10 MiB of a Firestore commit.
66
+ const REINDEX_BATCH = 100;
67
+ const REMOVED_TTL_US = 86_400_000_000;
68
+ // How much earlier than its commit a stored server time can be (changes).
69
+ export const SERVER_TIME_MARGIN_US = 1_000_000;
70
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : 0);
71
+ // The file counts of a user: a doc of their own, so that the item writes
72
+ // (also of an older data service) never touch them.
73
+ const fileUsageOf = (raw) => ({ items: num(raw?.items), bytes: num(raw?.bytes) });
74
+ const usageOf = (raw) => {
75
+ const one = (u) => ({ items: num(u?.items), bytes: num(u?.bytes) });
76
+ return { m: one(raw?.m), p: one(raw?.p) };
77
+ };
78
+ export class DataEngine {
79
+ d;
80
+ colls = new Map();
81
+ running = new Map();
82
+ constructor(d) {
83
+ this.d = d;
84
+ }
85
+ // The background reindexes of this process (for tests).
86
+ async idle() {
87
+ while (this.running.size)
88
+ await Promise.allSettled([...this.running.values()]);
89
+ }
90
+ rule(ctx, coll) {
91
+ return must(ruleOf(ctx.decl, coll));
92
+ }
93
+ key(ctx) {
94
+ return spaceKey(ctx.appId, ctx.space);
95
+ }
96
+ out(access, row, viewer) {
97
+ const d = row.data;
98
+ return {
99
+ id: publicIdOf(access, row.id),
100
+ data: JSON.parse(String(d.v ?? "{}")),
101
+ createdAt: isoOfUs(num(d.createdAt)),
102
+ updatedAt: isoOfUs(num(d.updatedAt)),
103
+ createdBy: String(d.createdBy ?? ""),
104
+ mine: !!viewer && viewer.uid === d.createdBy,
105
+ rev: num(d.rev),
106
+ };
107
+ }
108
+ async get(ctx, coll, rawId) {
109
+ const rule = this.rule(ctx, coll);
110
+ const ref = must(itemRef(rule.access, rawId, ctx.viewer?.uid ?? null));
111
+ allow(accessError(coll, rule, "read", ctx.viewer, ctx.loginMode));
112
+ // A short id while signed out: the caller has no own item.
113
+ if (!ref.owner)
114
+ return { item: null, cost: { reads: 0, writes: 0 } };
115
+ const docId = docIdOf(rule.access, coll, ref.owner, ref.id);
116
+ const data = await this.d.storage.get(paths.doc(this.key(ctx), docId));
117
+ return { item: data ? this.out(rule.access, { id: docId, data }, ctx.viewer) : null, cost: { reads: 1, writes: 0 } };
118
+ }
119
+ // The checks of list, count and watch: the plan, the rights and the scope.
120
+ planRead(ctx, coll, raw, call) {
121
+ const rule = this.rule(ctx, coll);
122
+ const plan = must(planQuery(coll, rule, raw, call));
123
+ allow(accessError(coll, rule, "read", ctx.viewer, ctx.loginMode));
124
+ if (plan.mine && !ctx.viewer)
125
+ throw new RuleFailure(ruleError("sign-in-required", MESSAGES.mineSignIn2(coll)));
126
+ return { rule, plan, scope: scopeOf(rule.access, coll, ctx.viewer?.uid ?? "") };
127
+ }
128
+ async list(ctx, coll, raw) {
129
+ const { rule, plan, scope } = this.planRead(ctx, coll, raw, "list");
130
+ if ((await this.indexState(ctx, coll, rule)) === "preparing" && plan.usesSlots)
131
+ throw new RuleFailure(ruleError("preparing", MESSAGES.preparing()));
132
+ const ns = NS_OF[rule.access];
133
+ const r = await this.d.storage.query(this.key(ctx), {
134
+ ns,
135
+ scope,
136
+ ...(plan.mine ? { owner: ctx.viewer.uid } : {}),
137
+ ...plan.where,
138
+ order: plan.order,
139
+ direction: plan.direction,
140
+ limit: plan.limit + 1,
141
+ after: plan.after,
142
+ });
143
+ const rows = r.rows.slice(0, plan.limit);
144
+ const last = rows.at(-1);
145
+ const next = r.rows.length > plan.limit && last ? encodeCursor(last.data[plan.order], last.id) : null;
146
+ return { items: rows.map((row) => this.out(rule.access, row, ctx.viewer)), next, readUs: r.readUs, cost: { reads: Math.max(1, r.rows.length), writes: 0 } };
147
+ }
148
+ async count(ctx, coll, raw) {
149
+ const { rule, plan, scope } = this.planRead(ctx, coll, raw, "count");
150
+ if ((await this.indexState(ctx, coll, rule)) === "preparing" && plan.usesSlots)
151
+ throw new RuleFailure(ruleError("preparing", MESSAGES.preparing()));
152
+ const n = await this.d.storage.count(this.key(ctx), { ns: NS_OF[rule.access], scope, ...(plan.mine ? { owner: ctx.viewer.uid } : {}), ...plan.where }, COUNT_MAX);
153
+ return { count: n, cost: { reads: Math.max(1, Math.ceil(n / 1000)), writes: 0 } };
154
+ }
155
+ // The marker of the list that a watch of `coll` waits on (9.2, 9.3), after
156
+ // the checks of a read. A public list with mine or where uses the marker
157
+ // of the collection.
158
+ watchTarget(ctx, coll) {
159
+ const { rule, scope } = this.planRead(ctx, coll, {}, "watch");
160
+ return { path: paths.mark(this.key(ctx), NS_OF[rule.access], scope), access: rule.access };
161
+ }
162
+ // The changes of a list since a cursor (9.3, 9.4). resync: the cursor is
163
+ // too old, or too much changed.
164
+ async changes(ctx, coll, cursorUs) {
165
+ const { rule, scope } = this.planRead(ctx, coll, {}, "watch");
166
+ const nowUs = this.d.now() * 1000;
167
+ if (!Number.isSafeInteger(cursorUs) || cursorUs < nowUs - CURSOR_MAX_AGE_MS * 1000 || cursorUs > nowUs + 60_000_000)
168
+ return { resync: true, cost: { reads: 0, writes: 0 } };
169
+ // updatedAt is a server time: Firestore keeps it to the millisecond,
170
+ // and it can be a little earlier than the commit (the emulator: about 1
171
+ // ms). The cursor is a read time in microseconds. So a change that
172
+ // committed after the cursor can have an updatedAt before it. Read from
173
+ // SERVER_TIME_MARGIN_US before the cursor; an item that comes again is
174
+ // its current state again (the SDK skips it).
175
+ const r = await this.d.storage.changes(this.key(ctx), NS_OF[rule.access], scope, Math.floor(cursorUs / 1000) * 1000 - SERVER_TIME_MARGIN_US - 1, CHANGES_MAX + 1);
176
+ const cost = { reads: Math.max(1, r.rows.length) + Math.max(1, r.removed.length), writes: 0 };
177
+ if (r.rows.length > CHANGES_MAX || r.removed.length > CHANGES_MAX)
178
+ return { resync: true, cost };
179
+ const items = r.rows.map((row) => this.out(rule.access, row, ctx.viewer));
180
+ const present = new Set(r.rows.map((row) => row.id));
181
+ const removed = r.removed.filter((row) => !present.has(row.id)).map((row) => publicIdOf(rule.access, row.id));
182
+ return { resync: false, items, removed, cursor: r.readUs, cost };
183
+ }
184
+ async add(ctx, coll, data) {
185
+ const rule = this.rule(ctx, coll);
186
+ allow(accessError(coll, rule, "add", ctx.viewer, ctx.loginMode));
187
+ const checked = must(checkData(data, ctx.limits));
188
+ // A new random id; another one in the rare case that it is taken.
189
+ for (let i = 0;; i++) {
190
+ const r = await this.write(ctx, coll, rule, { owner: ctx.viewer.uid, id: this.d.randomId() }, checked, { mustBeNew: true, ifRev: undefined, merge: false });
191
+ if (r !== "taken")
192
+ return r;
193
+ if (i >= 3)
194
+ throw new Error("Could not make a new item id.");
195
+ }
196
+ }
197
+ async set(ctx, coll, rawId, data, ifRev) {
198
+ const rule = this.rule(ctx, coll);
199
+ const ref = this.writeRef(ctx, coll, rule, rawId, "add");
200
+ const rev = checkRev(ifRev);
201
+ // add: a new item; the write checks again with the stored item.
202
+ allow(accessError(coll, rule, "add", ctx.viewer, ctx.loginMode, ref.owner));
203
+ const checked = must(checkData(data, ctx.limits));
204
+ const r = await this.write(ctx, coll, rule, ref, checked, { mustBeNew: false, ifRev: rev, merge: false });
205
+ return r;
206
+ }
207
+ async update(ctx, coll, rawId, patch, ifRev) {
208
+ const rule = this.rule(ctx, coll);
209
+ const ref = this.writeRef(ctx, coll, rule, rawId, "change");
210
+ const rev = checkRev(ifRev);
211
+ allow(accessError(coll, rule, "change", ctx.viewer, ctx.loginMode, ref.owner));
212
+ // The patch alone is checked here; the merged item in the write.
213
+ if (typeof patch !== "object" || patch === null || Array.isArray(patch))
214
+ throw new RuleFailure(ruleError("invalid", MESSAGES.dataObject()));
215
+ const r = await this.write(ctx, coll, rule, ref, patch, { mustBeNew: false, ifRev: rev, merge: true });
216
+ return r;
217
+ }
218
+ // The item of set, update and remove: a short id while signed out has no
219
+ // owner, so the sign-in check of the call says what to do.
220
+ writeRef(ctx, coll, rule, rawId, op) {
221
+ const ref = must(itemRef(rule.access, rawId, ctx.viewer?.uid ?? null));
222
+ if (!ctx.viewer)
223
+ allow(accessError(coll, rule, op, null, ctx.loginMode));
224
+ return ref;
225
+ }
226
+ async write(ctx, coll, rule, ref, input, opts) {
227
+ const viewer = ctx.viewer;
228
+ const key = this.key(ctx);
229
+ const ns = NS_OF[rule.access];
230
+ const scope = scopeOf(rule.access, coll, ref.owner);
231
+ const docId = docIdOf(rule.access, coll, ref.owner, ref.id);
232
+ // A changed declaration starts the reindex; the write goes on with the
233
+ // fields of its own declaration.
234
+ await this.indexState(ctx, coll, rule);
235
+ const totals = ctx.appTotals ? await ctx.appTotals() : null;
236
+ const nowUs = this.d.now() * 1000;
237
+ const r = await this.d.storage.transaction(async (tx) => {
238
+ const [old, rawUsage] = await Promise.all([tx.get(paths.doc(key, docId)), tx.get(paths.usage(key, ref.owner))]);
239
+ if (old && opts.mustBeNew)
240
+ return "taken";
241
+ if (old && old.createdBy !== viewer.uid)
242
+ throw new RuleFailure(ruleError("not-allowed", MESSAGES.notOwn(coll)));
243
+ if (opts.ifRev !== undefined && num(old?.rev) !== opts.ifRev)
244
+ throw new RuleFailure(ruleError("conflict", MESSAGES.conflict(coll)));
245
+ let checked;
246
+ if (opts.merge) {
247
+ if (!old)
248
+ throw new RuleFailure(ruleError("invalid", MESSAGES.noItem(coll, ref.id), 404));
249
+ checked = must(checkData({ ...JSON.parse(String(old.v)), ...input }, ctx.limits));
250
+ }
251
+ else
252
+ checked = input;
253
+ const usage = usageOf(rawUsage);
254
+ const mine = usage[ns];
255
+ const delta = { ns, items: old ? 0 : 1, bytes: checked.size - num(old?.size) };
256
+ const next = { items: mine.items + delta.items, bytes: mine.bytes + delta.bytes };
257
+ const itemsMax = ns === "m" ? ctx.limits.mineItemsPerUser : ctx.limits.publicItemsPerUser;
258
+ const bytesMax = ns === "m" ? ctx.limits.mineBytesPerUser : ctx.limits.publicBytesPerUser;
259
+ if ((delta.items > 0 && next.items > itemsMax) || (delta.bytes > 0 && next.bytes > bytesMax))
260
+ throw new RuleFailure(ruleError("quota", MESSAGES.userFull()));
261
+ if (totals && (delta.items > 0 || delta.bytes > 0)) {
262
+ const full = ns === "m" ? totals.mBytes + delta.bytes > ctx.limits.mineBytesPerApp : totals.pItems + delta.items > ctx.limits.publicItemsPerApp || totals.pBytes + delta.bytes > ctx.limits.publicBytesPerApp;
263
+ if (full)
264
+ throw new RuleFailure(ruleError("quota", MESSAGES.appFull()));
265
+ }
266
+ const doc = {
267
+ ns,
268
+ scope,
269
+ ...(rule.access === "public" ? { owner: ref.owner } : {}),
270
+ v: checked.text,
271
+ ...slotsOf(rule, checked.value),
272
+ createdAt: old ? num(old.createdAt) : SERVER_TIME,
273
+ updatedAt: SERVER_TIME,
274
+ createdBy: ref.owner,
275
+ rev: num(old?.rev) + 1,
276
+ size: checked.size,
277
+ };
278
+ tx.set(paths.doc(key, docId), doc);
279
+ tx.set(paths.usage(key, ref.owner), { ...usage, [ns]: next });
280
+ // An add or set of the id of a removed item: the watch must not see
281
+ // it as removed (9.2).
282
+ if (!old)
283
+ tx.delete(paths.removed(key, docId));
284
+ if (rule.access === "mine")
285
+ tx.set(paths.mark(key, ns, scope), { at: SERVER_TIME, resetAt: DELETE_FIELD }, { merge: true });
286
+ return { old, checked, delta };
287
+ });
288
+ if (r === "taken")
289
+ return r;
290
+ const item = {
291
+ id: publicIdOf(rule.access, docId),
292
+ data: r.checked.value,
293
+ createdAt: isoOfUs(r.old ? num(r.old.createdAt) : nowUs),
294
+ updatedAt: isoOfUs(nowUs),
295
+ createdBy: ref.owner,
296
+ mine: true,
297
+ rev: num(r.old?.rev) + 1,
298
+ };
299
+ return {
300
+ item,
301
+ marker: rule.access === "public" ? { path: paths.mark(key, ns, scope), removed: false } : null,
302
+ delta: r.delta,
303
+ cost: { reads: 0, writes: 1 },
304
+ };
305
+ }
306
+ async remove(ctx, coll, rawId) {
307
+ const rule = this.rule(ctx, coll);
308
+ const ref = this.writeRef(ctx, coll, rule, rawId, "remove");
309
+ allow(accessError(coll, rule, "remove", ctx.viewer, ctx.loginMode, ref.owner));
310
+ const key = this.key(ctx);
311
+ const ns = NS_OF[rule.access];
312
+ const scope = scopeOf(rule.access, coll, ref.owner);
313
+ const docId = docIdOf(rule.access, coll, ref.owner, ref.id);
314
+ const nowUs = this.d.now() * 1000;
315
+ const delta = await this.d.storage.transaction(async (tx) => {
316
+ const [old, rawUsage] = await Promise.all([tx.get(paths.doc(key, docId)), tx.get(paths.usage(key, ref.owner))]);
317
+ if (!old)
318
+ return null;
319
+ // The stored owner decides, never the id alone.
320
+ allow(accessError(coll, rule, "remove", ctx.viewer, ctx.loginMode, String(old.createdBy)));
321
+ const usage = usageOf(rawUsage);
322
+ const d = { ns, items: -1, bytes: -num(old.size) };
323
+ tx.set(paths.usage(key, ref.owner), { ...usage, [ns]: { items: Math.max(0, usage[ns].items - 1), bytes: Math.max(0, usage[ns].bytes - num(old.size)) } });
324
+ tx.delete(paths.doc(key, docId));
325
+ tx.set(paths.removed(key, docId), { scope, at: SERVER_TIME, expireAt: nowUs + REMOVED_TTL_US });
326
+ if (rule.access === "mine")
327
+ tx.set(paths.mark(key, ns, scope), { at: SERVER_TIME, removedAt: SERVER_TIME, resetAt: DELETE_FIELD }, { merge: true });
328
+ return d;
329
+ });
330
+ return {
331
+ item: null,
332
+ marker: delta && rule.access === "public" ? { path: paths.mark(key, ns, scope), removed: true } : null,
333
+ delta,
334
+ cost: { reads: 0, writes: delta ? 1 : 0 },
335
+ };
336
+ }
337
+ // db.usage() (8.1): the bytes of the signed-in user in this space.
338
+ async usage(ctx) {
339
+ if (!ctx.viewer)
340
+ throw new RuleFailure(ruleError("sign-in-required", "usage() needs sign-in. Call builders.auth.signIn()."));
341
+ const [raw, rawFiles] = await Promise.all([this.d.storage.get(paths.usage(this.key(ctx), ctx.viewer.uid)), this.d.storage.get(paths.fileUsage(this.key(ctx), ctx.viewer.uid))]);
342
+ const u = usageOf(raw);
343
+ return {
344
+ bytes: u.m.bytes + u.p.bytes,
345
+ bytesLimit: ctx.limits.mineBytesPerUser + ctx.limits.publicBytesPerUser,
346
+ fileBytes: fileUsageOf(rawFiles).bytes,
347
+ fileBytesLimit: ctx.limits.fileBytesPerUser,
348
+ cost: { reads: 2, writes: 0 },
349
+ };
350
+ }
351
+ // --- Files (7, LD11): mine only, so every call needs sign-in. ---
352
+ // The checks of every file call: the set is declared and somebody is
353
+ // signed in. The data service runs them before it counts an upload.
354
+ fileUser(ctx, set) {
355
+ if (typeof set !== "string")
356
+ throw new RuleFailure(ruleError("invalid", MESSAGES.fileSetName()));
357
+ allow(fileSetOf(ctx.decl, set));
358
+ if (!ctx.viewer)
359
+ throw new RuleFailure(ruleError("sign-in-required", MESSAGES.fileSignIn(set)));
360
+ return { set, uid: ctx.viewer.uid };
361
+ }
362
+ fileOut(set, id, d) {
363
+ return { id, name: String(d.name ?? "file"), type: String(d.type ?? ""), size: num(d.size), createdAt: isoOfUs(num(d.createdAt)), url: fileUrlOf(set, id) };
364
+ }
365
+ // The app and owner limits of a file of `size` bytes.
366
+ async fileRoom(ctx, size) {
367
+ const [totals, owner] = await Promise.all([ctx.appTotals?.(), ctx.ownerFileBytes?.()]);
368
+ if ((totals && totals.fBytes + size > ctx.limits.fileBytesPerApp) || (owner !== undefined && owner + size > ctx.limits.fileBytesPerOwner)) {
369
+ throw new RuleFailure(ruleError("quota", MESSAGES.appFull()));
370
+ }
371
+ }
372
+ // Stores one file (7): the checks, the type from the first bytes, the
373
+ // bytes to the blob storage, then the record and the user's counts in one
374
+ // transaction. `size`: the length that the request gave, if any. A
375
+ // failed check after the bytes are stored deletes them.
376
+ async upload(ctx, rawSet, meta, body, blobs) {
377
+ const { set, uid } = this.fileUser(ctx, rawSet);
378
+ const name = must(checkFileName(meta.name));
379
+ const declared = fileTypeOf(meta.type);
380
+ if (declared === null)
381
+ throw new RuleFailure(ruleError("invalid", MESSAGES.fileType()));
382
+ const max = ctx.limits.fileBytes;
383
+ const tooLarge = () => new RuleFailure(ruleError("too-large", MESSAGES.fileTooLarge(Math.floor(max / (1024 * 1024)))));
384
+ const declaredSize = typeof meta.size === "number" && Number.isSafeInteger(meta.size) && meta.size >= 0 ? meta.size : null;
385
+ if (declaredSize !== null && declaredSize > max)
386
+ throw tooLarge();
387
+ const key = this.key(ctx);
388
+ // Early checks with the given length, so that a full space does not
389
+ // take the upload first. The transaction checks again.
390
+ const before = fileUsageOf(await this.d.storage.get(paths.fileUsage(key, uid)));
391
+ if (before.items + 1 > ctx.limits.filesPerUser || before.bytes + (declaredSize ?? 0) > ctx.limits.fileBytesPerUser)
392
+ throw new RuleFailure(ruleError("quota", MESSAGES.fileUserFull()));
393
+ await this.fileRoom(ctx, declaredSize ?? 0);
394
+ // The first bytes decide the type.
395
+ const it = body[Symbol.asyncIterator]();
396
+ const head = [];
397
+ let headSize = 0;
398
+ let ended = false;
399
+ while (headSize < FILE_HEAD_BYTES) {
400
+ const r = await it.next();
401
+ if (r.done) {
402
+ ended = true;
403
+ break;
404
+ }
405
+ head.push(r.value);
406
+ headSize += r.value.length;
407
+ }
408
+ const first = new Uint8Array(headSize);
409
+ let at = 0;
410
+ for (const c of head) {
411
+ first.set(c, at);
412
+ at += c.length;
413
+ }
414
+ if (headSize > max)
415
+ throw tooLarge();
416
+ const type = must(checkFileType(declared, first));
417
+ let size = 0;
418
+ let over = false;
419
+ async function* all() {
420
+ for (const c of head) {
421
+ size += c.length;
422
+ yield c;
423
+ }
424
+ if (ended)
425
+ return;
426
+ for (;;) {
427
+ const r = await it.next();
428
+ if (r.done)
429
+ return;
430
+ size += r.value.length;
431
+ if (size > max) {
432
+ over = true;
433
+ throw new Error("The file is too large.");
434
+ }
435
+ yield r.value;
436
+ }
437
+ }
438
+ const id = fileIdOf(this.d.now(), this.d.randomId());
439
+ const object = fileObjectOf(ctx.appId, ctx.space, uid, id);
440
+ let stored;
441
+ try {
442
+ stored = await blobs.write(object, all(), type);
443
+ }
444
+ catch (e) {
445
+ // The name is only this upload's: the bytes go, also when the store
446
+ // kept them before the error (a time limit, a lost answer).
447
+ await this.dropBytes(blobs, object);
448
+ if (over)
449
+ throw tooLarge();
450
+ throw e;
451
+ }
452
+ if (over) {
453
+ await blobs.delete(object);
454
+ throw tooLarge();
455
+ }
456
+ if (!stored)
457
+ throw new Error("Could not make a new file id.");
458
+ const docId = fileDocIdOf(set, uid, id);
459
+ const nowUs = this.d.now() * 1000;
460
+ // The file counts change only in a transaction that makes or deletes a
461
+ // record, by the delta that it gives back (fileRecordDelta). The nonce
462
+ // tells this upload's record from any other.
463
+ const nonce = this.d.randomId();
464
+ let made = 0;
465
+ let gone = 0;
466
+ const total = () => ({ ns: "f", items: made - gone, bytes: (made - gone) * size });
467
+ try {
468
+ await this.fileRoom(ctx, size);
469
+ made = await this.d.storage.transaction(async (tx) => {
470
+ const [rec, raw] = await Promise.all([tx.get(paths.file(key, docId)), tx.get(paths.fileUsage(key, uid))]);
471
+ // There already: a try of this transaction that committed (a retry
472
+ // of Firestore). It made the record, so it counts once.
473
+ if (rec)
474
+ return rec.nonce === nonce ? 1 : 0;
475
+ const u = fileUsageOf(raw);
476
+ const next = { items: u.items + 1, bytes: u.bytes + size };
477
+ if (next.items > ctx.limits.filesPerUser || next.bytes > ctx.limits.fileBytesPerUser)
478
+ throw new RuleFailure(ruleError("quota", MESSAGES.fileUserFull()));
479
+ tx.set(paths.file(key, docId), { set, owner: uid, name, type, size, nonce, createdAt: SERVER_TIME });
480
+ tx.set(paths.fileUsage(key, uid), next);
481
+ return 1;
482
+ });
483
+ }
484
+ catch (e) {
485
+ if (e instanceof RuleFailure) {
486
+ await this.dropBytes(blobs, object);
487
+ throw e;
488
+ }
489
+ // The answer of a commit can get lost: the record with this nonce
490
+ // tells whether this upload made it. When that read fails too, the
491
+ // upload counts as not made (the error is logged).
492
+ const rec = await this.d.storage.get(paths.file(key, docId)).catch((err) => {
493
+ console.error(JSON.stringify({ severity: "ERROR", message: "Upload: the record is not known", docId, error: String(err?.message ?? err) }));
494
+ return null;
495
+ });
496
+ if (rec?.nonce !== nonce) {
497
+ await this.dropBytes(blobs, object);
498
+ throw e;
499
+ }
500
+ made = 1;
501
+ }
502
+ // reset_test_data can delete the bytes between the write and the
503
+ // record: then the record goes again, by the same rule. A failed check
504
+ // counts as "there".
505
+ if (made && !(await blobs.exists(object).catch(() => true))) {
506
+ try {
507
+ gone = (await fileRecordDelta(this.d.storage, key, docId, { nonce })).items === -1 ? 1 : 0;
508
+ }
509
+ catch (e) {
510
+ throw withDelta(e, total());
511
+ }
512
+ throw withDelta(new RuleFailure(ruleError("conflict", MESSAGES.fileGone())), total());
513
+ }
514
+ if (!made)
515
+ throw withDelta(new RuleFailure(ruleError("conflict", MESSAGES.fileGone())), total());
516
+ return {
517
+ file: { id, name, type, size, createdAt: isoOfUs(nowUs), url: fileUrlOf(set, id) },
518
+ delta: total(),
519
+ cost: { reads: 0, writes: 1 },
520
+ };
521
+ }
522
+ async dropBytes(blobs, object) {
523
+ await blobs.delete(object).catch((err) => console.error(JSON.stringify({ severity: "ERROR", message: "Could not delete the bytes of a refused upload", object, error: String(err?.message ?? err) })));
524
+ }
525
+ // The user's files of a set, newest first (the order of the ids).
526
+ async listFiles(ctx, rawSet, raw) {
527
+ const { set, uid } = this.fileUser(ctx, rawSet);
528
+ const q = (raw ?? {});
529
+ if (typeof q !== "object" || Array.isArray(q))
530
+ throw new RuleFailure(ruleError("invalid", MESSAGES.queryKeys("list()", "limit, after")));
531
+ for (const k of Object.keys(q))
532
+ if (k !== "limit" && k !== "after")
533
+ throw new RuleFailure(ruleError("invalid", MESSAGES.queryKeys("list()", "limit, after")));
534
+ let limit = LIST_DEFAULT;
535
+ if (q.limit !== undefined) {
536
+ if (typeof q.limit !== "number" || !Number.isInteger(q.limit) || q.limit < 1 || q.limit > LIST_MAX)
537
+ throw new RuleFailure(ruleError("invalid", MESSAGES.limit(LIST_MAX)));
538
+ limit = q.limit;
539
+ }
540
+ let after = null;
541
+ if (q.after !== undefined && q.after !== null) {
542
+ if (typeof q.after !== "string" || !FILE_ID.test(q.after))
543
+ throw new RuleFailure(ruleError("invalid", MESSAGES.badCursor()));
544
+ after = fileDocIdOf(set, uid, q.after);
545
+ }
546
+ const prefix = fileDocIdOf(set, uid, "");
547
+ const rows = await this.d.storage.docsByPrefix(this.key(ctx), prefix, after, limit + 1, "files");
548
+ const page = rows.slice(0, limit);
549
+ const files = page.map((r) => this.fileOut(set, r.id.slice(prefix.length), r.data));
550
+ return { files, next: rows.length > limit ? files.at(-1).id : null, cost: { reads: Math.max(1, rows.length), writes: 0 } };
551
+ }
552
+ // One file of the signed-in user, and its object (the download).
553
+ async file(ctx, rawSet, rawId) {
554
+ const { set, uid } = this.fileUser(ctx, rawSet);
555
+ const none = () => new RuleFailure(ruleError("invalid", MESSAGES.fileNone(), 404));
556
+ if (typeof rawId !== "string" || !FILE_ID.test(rawId))
557
+ throw none();
558
+ const d = await this.d.storage.get(paths.file(this.key(ctx), fileDocIdOf(set, uid, rawId)));
559
+ if (!d)
560
+ throw none();
561
+ return { file: this.fileOut(set, rawId, d), object: fileObjectOf(ctx.appId, ctx.space, uid, rawId), cost: { reads: 1, writes: 0 } };
562
+ }
563
+ // Removes a file of the signed-in user: first the bytes, then the
564
+ // record (a failure leaves a record that a second remove ends, never
565
+ // bytes without a record). A file that is not there: no error.
566
+ async removeFile(ctx, rawSet, rawId, blobs) {
567
+ const { set, uid } = this.fileUser(ctx, rawSet);
568
+ if (typeof rawId !== "string" || !FILE_ID.test(rawId))
569
+ throw new RuleFailure(ruleError("invalid", MESSAGES.fileId()));
570
+ const key = this.key(ctx);
571
+ const path = paths.file(key, fileDocIdOf(set, uid, rawId));
572
+ if (!(await this.d.storage.get(path)))
573
+ return { delta: null, cost: { reads: 1, writes: 0 } };
574
+ await blobs.delete(fileObjectOf(ctx.appId, ctx.space, uid, rawId));
575
+ const delta = await fileRecordDelta(this.d.storage, key, fileDocIdOf(set, uid, rawId));
576
+ return { delta: delta.items ? delta : null, cost: { reads: 1, writes: delta.items ? 1 : 0 } };
577
+ }
578
+ // --- The index slots of a collection (6.2). ---
579
+ // "ready", or "preparing" while the docs get the slots of a changed
580
+ // declaration. A change starts the reindex.
581
+ async indexState(ctx, coll, rule) {
582
+ const key = this.key(ctx);
583
+ const ns = NS_OF[rule.access];
584
+ const cacheKey = `${key}/${ns}.${coll}`;
585
+ const now = this.d.now();
586
+ const cached = this.colls.get(cacheKey);
587
+ let rec = cached && cached.until > now ? cached.rec : null;
588
+ if (!rec || !sameFields(rec, rule)) {
589
+ const path = paths.colls(key, ns, coll);
590
+ rec = await this.d.storage.transaction(async (tx) => {
591
+ const have = toColl(await tx.get(path));
592
+ if (have && sameFields(have, rule))
593
+ return have;
594
+ // A new collection is ready at once; a change of fields needs the
595
+ // reindex.
596
+ const next = { filter: [...rule.filter], sort: rule.sort, state: have ? "preparing" : "ready", cursor: null, leaseBy: null, leaseUntil: 0 };
597
+ tx.set(path, { ...next });
598
+ return next;
599
+ });
600
+ this.colls.set(cacheKey, { rec, until: now + (rec.state === "ready" ? COLLS_CACHE_MS : COLLS_PREPARING_CACHE_MS) });
601
+ if (this.colls.size > 10_000)
602
+ this.colls.delete(this.colls.keys().next().value);
603
+ }
604
+ if (rec.state === "preparing")
605
+ this.kick(key, ns, coll, rule);
606
+ return rec.state;
607
+ }
608
+ kick(key, ns, coll, rule) {
609
+ const k = `${key}/${ns}.${coll}`;
610
+ if (this.running.has(k))
611
+ return;
612
+ const p = this.reindex(key, ns, coll, rule)
613
+ .catch((e) => console.error(JSON.stringify({ severity: "ERROR", message: "Reindex failed", space: key, coll, error: String(e?.message ?? e) })))
614
+ .finally(() => this.running.delete(k));
615
+ this.running.set(k, p);
616
+ }
617
+ // Rewrites f1, f2 and s of each doc of the collection, 200 at a time, with
618
+ // a lease, so that one process does it and another one goes on after a
619
+ // crash. It stops when the declaration changes again.
620
+ async reindex(key, ns, coll, rule) {
621
+ const path = paths.colls(key, ns, coll);
622
+ const prefix = `${ns}.${coll}.`;
623
+ const access = ns === "m" ? "mine" : "public";
624
+ for (;;) {
625
+ const now = this.d.now();
626
+ const lease = await this.d.storage.transaction(async (tx) => {
627
+ const rec = toColl(await tx.get(path));
628
+ if (!rec || rec.state !== "preparing" || !sameFields(rec, rule))
629
+ return null;
630
+ if (rec.leaseBy && rec.leaseBy !== this.d.instance && rec.leaseUntil > now)
631
+ return null;
632
+ tx.set(path, { ...rec, leaseBy: this.d.instance, leaseUntil: now + LEASE_MS });
633
+ return rec;
634
+ });
635
+ if (!lease)
636
+ return;
637
+ const rows = await this.d.storage.docsByPrefix(key, prefix, lease.cursor, REINDEX_BATCH);
638
+ const done = await this.d.storage.transaction(async (tx) => {
639
+ const rec = toColl(await tx.get(path));
640
+ if (!rec || rec.leaseBy !== this.d.instance || !sameFields(rec, rule))
641
+ return true;
642
+ const docs = await Promise.all(rows.map((r) => tx.get(paths.doc(key, r.id))));
643
+ rows.forEach((r, i) => {
644
+ const d = docs[i];
645
+ if (!d)
646
+ return;
647
+ const value = JSON.parse(String(d.v ?? "{}"));
648
+ // Only the slots: the item and its times do not change.
649
+ const slots = slotsOf({ access, filter: rule.filter, sort: rule.sort }, value);
650
+ tx.set(paths.doc(key, r.id), { f1: slots.f1 ?? DELETE_FIELD, f2: slots.f2 ?? DELETE_FIELD, s: slots.s ?? DELETE_FIELD }, { merge: true });
651
+ });
652
+ const last = rows.at(-1)?.id ?? rec.cursor;
653
+ const finished = rows.length < REINDEX_BATCH;
654
+ tx.set(path, { ...rec, cursor: finished ? null : last, state: finished ? "ready" : "preparing", leaseBy: finished ? null : this.d.instance, leaseUntil: finished ? 0 : this.d.now() + LEASE_MS });
655
+ return finished;
656
+ });
657
+ if (done) {
658
+ this.colls.delete(`${key}/${ns}.${coll}`);
659
+ return;
660
+ }
661
+ }
662
+ }
663
+ }
664
+ function checkRev(v) {
665
+ if (v === undefined || v === null)
666
+ return undefined;
667
+ if (typeof v !== "number" || !Number.isInteger(v) || v < 0)
668
+ throw new RuleFailure(ruleError("invalid", MESSAGES.ifRev()));
669
+ return v;
670
+ }
671
+ function toColl(raw) {
672
+ if (!raw)
673
+ return null;
674
+ return {
675
+ filter: Array.isArray(raw.filter) ? raw.filter.map(String) : [],
676
+ sort: typeof raw.sort === "string" ? raw.sort : null,
677
+ state: raw.state === "preparing" ? "preparing" : "ready",
678
+ cursor: typeof raw.cursor === "string" ? raw.cursor : null,
679
+ leaseBy: typeof raw.leaseBy === "string" ? raw.leaseBy : null,
680
+ leaseUntil: num(raw.leaseUntil),
681
+ };
682
+ }
683
+ function sameFields(rec, rule) {
684
+ return rec.sort === rule.sort && rec.filter.length === rule.filter.length && rec.filter.every((f, i) => f === rule.filter[i]);
685
+ }
686
+ // --- File counts (7): one rule. ---
687
+ //
688
+ // A file count (the user's usage/f.<uid>, the app's usage/_app fBytes, the
689
+ // owner's fBytes) changes only by the delta of a transaction that makes
690
+ // or deletes a file record: +1 and +size when it made it, -1 and -size
691
+ // when it deleted it, 0 when the record was there or gone already. The
692
+ // user's count changes in that transaction; the caller adds the delta to
693
+ // the app and the owner.
694
+ // Deletes one file record and takes it off the user's count. With
695
+ // `nonce`, only the record of that upload. The delta is 0 when the record
696
+ // is not there. `counts`: docs (usage/_app, the owner's) that take the
697
+ // delta in the same transaction (reset_test_data).
698
+ export async function fileRecordDelta(storage, key, docId, opts = {}) {
699
+ return storage.transaction(async (tx) => {
700
+ const rec = await tx.get(paths.file(key, docId));
701
+ if (!rec || (opts.nonce !== undefined && rec.nonce !== opts.nonce))
702
+ return { ns: "f", items: 0, bytes: 0 };
703
+ const uid = String(rec.owner);
704
+ const counts = opts.counts ?? [];
705
+ const [raw, ...docs] = await Promise.all([tx.get(paths.fileUsage(key, uid)), ...counts.map((p) => tx.get(p))]);
706
+ const u = fileUsageOf(raw);
707
+ const size = num(rec.size);
708
+ tx.delete(paths.file(key, docId));
709
+ tx.set(paths.fileUsage(key, uid), { items: u.items - 1, bytes: u.bytes - size });
710
+ counts.forEach((p, i) => tx.set(p, { fBytes: num(docs[i]?.fBytes) - size }, { merge: true }));
711
+ return { ns: "f", items: -1, bytes: -size };
712
+ });
713
+ }
714
+ // --- Deletes of many records (section 14, reset_test_data). ---
715
+ //
716
+ // The same rule for item counts and file counts: a count changes only in
717
+ // the transaction that deletes a record, by the exact delta of that
718
+ // record. No job sets a count to 0 or takes off a sum that it computed
719
+ // outside the transaction. The app and owner counts are stored signed and
720
+ // read as at least 0.
721
+ // The most records that one transaction of a delete job deletes: one
722
+ // write of the shared count docs per batch.
723
+ export const DELETE_BATCH = 100;
724
+ // The most bucket objects that a delete job deletes at the same time.
725
+ export const DELETE_PARALLEL = 16;
726
+ // Runs fn for each item, at most n at the same time.
727
+ export async function eachParallel(items, n, fn) {
728
+ let next = 0;
729
+ const worker = async () => {
730
+ while (next < items.length)
731
+ await fn(items[next++]);
732
+ };
733
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
734
+ }
735
+ // Deletes the file records `docIds` (at most DELETE_BATCH) in one
736
+ // transaction: each record that is there (and passes `onlyIf`) goes off
737
+ // its user's count, and the sum of their bytes goes off each doc of
738
+ // `counts` (usage/_app, the owner's). Records that are gone already count
739
+ // 0.
740
+ export async function deleteFiles(storage, key, docIds, counts = [], onlyIf) {
741
+ const ids = [...new Set(docIds)];
742
+ if (ids.length > DELETE_BATCH)
743
+ throw new Error(`At most ${DELETE_BATCH} records in one transaction.`);
744
+ if (!ids.length)
745
+ return { ns: "f", items: 0, bytes: 0 };
746
+ return storage.transaction(async (tx) => {
747
+ const recs = await Promise.all(ids.map((id) => tx.get(paths.file(key, id))));
748
+ const found = ids.flatMap((id, i) => (recs[i] && (!onlyIf || onlyIf(recs[i])) ? [{ id, rec: recs[i] }] : []));
749
+ if (!found.length)
750
+ return { ns: "f", items: 0, bytes: 0 };
751
+ const uids = [...new Set(found.map((f) => String(f.rec.owner)))];
752
+ const [users, docs] = await Promise.all([Promise.all(uids.map((u) => tx.get(paths.fileUsage(key, u)))), Promise.all(counts.map((p) => tx.get(p)))]);
753
+ const per = new Map(uids.map((u, i) => [u, fileUsageOf(users[i] ?? null)]));
754
+ let bytes = 0;
755
+ for (const f of found) {
756
+ const size = num(f.rec.size);
757
+ const u = per.get(String(f.rec.owner));
758
+ u.items -= 1;
759
+ u.bytes -= size;
760
+ bytes += size;
761
+ tx.delete(paths.file(key, f.id));
762
+ }
763
+ for (const [u, v] of per)
764
+ tx.set(paths.fileUsage(key, u), { items: v.items, bytes: v.bytes });
765
+ counts.forEach((p, i) => tx.set(p, { fBytes: num(docs[i]?.fBytes) - bytes }, { merge: true }));
766
+ return { ns: "f", items: -found.length, bytes: -bytes };
767
+ });
768
+ }
769
+ // Deletes the items `docIds` (at most DELETE_BATCH) in one transaction:
770
+ // each item that is there goes off its user's counts (usage/<uid>) and off
771
+ // the app's counts (usage/_app). With `log`, each remove is in `removed`
772
+ // and the marker of a mine list changes in the transaction, as a remove of
773
+ // the user (9.2); the caller writes the markers of the public lists after
774
+ // the commit (`markers`). Without `log` (reset_test_data, the purge), the
775
+ // caller makes the watches read again.
776
+ export async function deleteItems(storage, key, docIds, opts) {
777
+ const ids = [...new Set(docIds)];
778
+ if (ids.length > DELETE_BATCH)
779
+ throw new Error(`At most ${DELETE_BATCH} records in one transaction.`);
780
+ if (!ids.length)
781
+ return { items: 0, markers: [] };
782
+ return storage.transaction(async (tx) => {
783
+ const docs = await Promise.all(ids.map((id) => tx.get(paths.doc(key, id))));
784
+ // onlyIf: a condition on the doc as the transaction reads it (a write
785
+ // between the caller's read and the transaction can change it).
786
+ const found = ids.flatMap((id, i) => (docs[i] && (!opts.onlyIf || opts.onlyIf(docs[i])) ? [{ id, d: docs[i] }] : []));
787
+ if (!found.length)
788
+ return { items: 0, markers: [] };
789
+ const uids = [...new Set(found.map((f) => String(f.d.createdBy)))];
790
+ const [users, app] = await Promise.all([Promise.all(uids.map((u) => tx.get(paths.usage(key, u)))), tx.get(paths.appUsage(key))]);
791
+ const per = new Map(uids.map((u, i) => [u, usageOf(users[i] ?? null)]));
792
+ const sum = { mBytes: 0, pItems: 0, pBytes: 0 };
793
+ const markers = new Set();
794
+ for (const f of found) {
795
+ const ns = f.d.ns === "p" ? "p" : "m";
796
+ const size = num(f.d.size);
797
+ const u = per.get(String(f.d.createdBy))[ns];
798
+ u.items -= 1;
799
+ u.bytes -= size;
800
+ if (ns === "m")
801
+ sum.mBytes -= size;
802
+ else {
803
+ sum.pItems -= 1;
804
+ sum.pBytes -= size;
805
+ }
806
+ tx.delete(paths.doc(key, f.id));
807
+ if (!opts.log)
808
+ continue;
809
+ const scope = String(f.d.scope);
810
+ tx.set(paths.removed(key, f.id), { scope, at: SERVER_TIME, expireAt: opts.nowUs + REMOVED_TTL_US });
811
+ if (ns === "p")
812
+ markers.add(paths.mark(key, ns, scope));
813
+ else if (!markers.has(paths.mark(key, ns, scope))) {
814
+ markers.add(paths.mark(key, ns, scope));
815
+ tx.set(paths.mark(key, ns, scope), { at: SERVER_TIME, removedAt: SERVER_TIME, resetAt: DELETE_FIELD }, { merge: true });
816
+ }
817
+ }
818
+ for (const [u, v] of per)
819
+ tx.set(paths.usage(key, u), { m: v.m, p: v.p });
820
+ tx.set(paths.appUsage(key), { mBytes: num(app?.mBytes) + sum.mBytes, pItems: num(app?.pItems) + sum.pItems, pBytes: num(app?.pBytes) + sum.pBytes }, { merge: true });
821
+ return { items: found.length, markers: [...markers].filter((m) => m.includes("/marks/p.")) };
822
+ });
823
+ }
824
+ // The restore of an operator (section 12, the runbook): makes the items
825
+ // `rows` (at most DELETE_BATCH, docs as a point-in-time read gave them)
826
+ // that are not there now, in one transaction, and adds the exact delta of
827
+ // each to its user's counts and to the app's counts. An item that is there
828
+ // now stays as it is (it is newer). The watches see each restored item as
829
+ // a change (updatedAt is the commit time); the caller writes the markers
830
+ // of the public lists after the commit (`markers`).
831
+ export async function restoreItems(storage, key, rows) {
832
+ if (rows.length > DELETE_BATCH)
833
+ throw new Error(`At most ${DELETE_BATCH} records in one transaction.`);
834
+ if (!rows.length)
835
+ return { items: 0, markers: [] };
836
+ return storage.transaction(async (tx) => {
837
+ const now = await Promise.all(rows.map((r) => tx.get(paths.doc(key, r.id))));
838
+ const missing = rows.filter((_, i) => !now[i]);
839
+ if (!missing.length)
840
+ return { items: 0, markers: [] };
841
+ const uids = [...new Set(missing.map((r) => String(r.data.createdBy)))];
842
+ const [users, app] = await Promise.all([Promise.all(uids.map((u) => tx.get(paths.usage(key, u)))), tx.get(paths.appUsage(key))]);
843
+ const per = new Map(uids.map((u, i) => [u, usageOf(users[i] ?? null)]));
844
+ const sum = { mBytes: 0, pItems: 0, pBytes: 0 };
845
+ const markers = new Set();
846
+ for (const r of missing) {
847
+ const ns = r.data.ns === "p" ? "p" : "m";
848
+ const size = num(r.data.size);
849
+ const u = per.get(String(r.data.createdBy))[ns];
850
+ u.items += 1;
851
+ u.bytes += size;
852
+ if (ns === "m")
853
+ sum.mBytes += size;
854
+ else {
855
+ sum.pItems += 1;
856
+ sum.pBytes += size;
857
+ }
858
+ const scope = String(r.data.scope);
859
+ tx.set(paths.doc(key, r.id), { ...r.data, updatedAt: SERVER_TIME });
860
+ tx.delete(paths.removed(key, r.id));
861
+ if (ns === "p")
862
+ markers.add(paths.mark(key, ns, scope));
863
+ else if (!markers.has(paths.mark(key, ns, scope))) {
864
+ markers.add(paths.mark(key, ns, scope));
865
+ tx.set(paths.mark(key, ns, scope), { at: SERVER_TIME, resetAt: DELETE_FIELD }, { merge: true });
866
+ }
867
+ }
868
+ for (const [u, v] of per)
869
+ tx.set(paths.usage(key, u), { m: v.m, p: v.p });
870
+ tx.set(paths.appUsage(key), { mBytes: num(app?.mBytes) + sum.mBytes, pItems: num(app?.pItems) + sum.pItems, pBytes: num(app?.pBytes) + sum.pBytes }, { merge: true });
871
+ return { items: missing.length, markers: [...markers].filter((m) => m.includes("/marks/p.")) };
872
+ });
873
+ }
874
+ // The restore of file records (the bytes are restored first): makes the
875
+ // records `rows` (at most DELETE_BATCH) that are not there now, and adds
876
+ // the exact delta of each to its user's count and to each doc of `counts`
877
+ // (usage/_app, the owner's).
878
+ export async function restoreFiles(storage, key, rows, counts = []) {
879
+ if (rows.length > DELETE_BATCH)
880
+ throw new Error(`At most ${DELETE_BATCH} records in one transaction.`);
881
+ if (!rows.length)
882
+ return { ns: "f", items: 0, bytes: 0 };
883
+ return storage.transaction(async (tx) => {
884
+ const now = await Promise.all(rows.map((r) => tx.get(paths.file(key, r.id))));
885
+ const missing = rows.filter((_, i) => !now[i]);
886
+ if (!missing.length)
887
+ return { ns: "f", items: 0, bytes: 0 };
888
+ const uids = [...new Set(missing.map((r) => String(r.data.owner)))];
889
+ const [users, docs] = await Promise.all([Promise.all(uids.map((u) => tx.get(paths.fileUsage(key, u)))), Promise.all(counts.map((p) => tx.get(p)))]);
890
+ const per = new Map(uids.map((u, i) => [u, fileUsageOf(users[i] ?? null)]));
891
+ let bytes = 0;
892
+ for (const r of missing) {
893
+ const size = num(r.data.size);
894
+ const u = per.get(String(r.data.owner));
895
+ u.items += 1;
896
+ u.bytes += size;
897
+ bytes += size;
898
+ tx.set(paths.file(key, r.id), { ...r.data });
899
+ }
900
+ for (const [u, v] of per)
901
+ tx.set(paths.fileUsage(key, u), { items: v.items, bytes: v.bytes });
902
+ counts.forEach((p, i) => tx.set(p, { fBytes: num(docs[i]?.fBytes) + bytes }, { merge: true }));
903
+ return { ns: "f", items: missing.length, bytes };
904
+ });
905
+ }
906
+ // Deletes all items of a space in batches (deleteItems without the log),
907
+ // then resetSpace. An item that a write adds meanwhile is counted, and
908
+ // stays.
909
+ export async function emptySpace(storage, key, nowUs) {
910
+ let n = 0;
911
+ let after = null;
912
+ for (;;) {
913
+ const rows = await storage.docsByPrefix(key, "", after, DELETE_BATCH);
914
+ if (!rows.length)
915
+ break;
916
+ n += (await deleteItems(storage, key, rows.map((r) => r.id), { log: false, nowUs })).items;
917
+ if (rows.length < DELETE_BATCH)
918
+ break;
919
+ after = rows.at(-1).id;
920
+ }
921
+ await storage.resetSpace(key);
922
+ return n;
923
+ }
924
+ // Deletes all file records of a space whose id starts with `prefix`, in
925
+ // batches (deleteFiles), each batch taken off `counts`.
926
+ export async function dropFileRecords(storage, key, prefix, counts) {
927
+ const sum = { ns: "f", items: 0, bytes: 0 };
928
+ let after = null;
929
+ for (;;) {
930
+ const rows = await storage.docsByPrefix(key, prefix, after, DELETE_BATCH, "files");
931
+ if (!rows.length)
932
+ return sum;
933
+ const d = await deleteFiles(storage, key, rows.map((r) => r.id), counts);
934
+ sum.items += d.items;
935
+ sum.bytes += d.bytes;
936
+ if (rows.length < DELETE_BATCH)
937
+ return sum;
938
+ after = rows.at(-1).id;
939
+ }
940
+ }
941
+ // reset_test_data (13.4): the bytes, then the file records in batches
942
+ // (deleteFiles), then the items in batches and the rest of the space
943
+ // (emptySpace), then the bytes and the records again (an upload that
944
+ // ended meanwhile). Each batch also takes its bytes off the app and the
945
+ // owner, so an error or a cut at any point leaves the counts equal to the
946
+ // records. An upload that runs at the same time follows the same rule.
947
+ export async function resetTestSpace(storage, blobs, appId, ownerId, hooks = {}) {
948
+ const key = spaceKey(appId, "test");
949
+ const sum = { ns: "f", items: 0, bytes: 0 };
950
+ const step = hooks.step ?? (async () => { });
951
+ const counts = [paths.appUsage(key), paths.ownerUsage(ownerId)];
952
+ const drop = async () => {
953
+ const d = await dropFileRecords(storage, key, "", counts);
954
+ sum.items += d.items;
955
+ sum.bytes += d.bytes;
956
+ };
957
+ const purge = () => blobs.deletePrefix(`apps/${appId}/test/`);
958
+ await purge();
959
+ await step("purge");
960
+ await drop();
961
+ await step("drop");
962
+ await emptySpace(storage, key, hooks.nowUs ?? Date.now() * 1000);
963
+ await step("deleteSpace");
964
+ await purge();
965
+ await drop();
966
+ return sum;
967
+ }
968
+ // 20 random letters and digits (add()).
969
+ export function randomItemId() {
970
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
971
+ let out = "";
972
+ while (out.length < 20) {
973
+ const bytes = new Uint8Array(32);
974
+ globalThis.crypto.getRandomValues(bytes);
975
+ // Only bytes below 248 (4 x 62): no bias from the modulo.
976
+ for (const b of bytes)
977
+ if (b < 248 && out.length < 20)
978
+ out += chars[b % 62];
979
+ }
980
+ return out;
981
+ }