@gusto/baerly-storage 0.2.0 → 0.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/LICENSE +202 -0
- package/NOTICE +29 -0
- package/README.md +176 -70
- package/dist/API.md +213 -139
- package/dist/CHANGELOG.md +434 -0
- package/dist/RECIPES.md +125 -0
- package/dist/THIRD-PARTY-LICENSES.txt +238 -0
- package/dist/{app-config-C0Bbw_Z6.d.ts → app-config-DyiFK3_k.d.ts} +55 -11
- package/dist/app-config.d.ts +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/auth.js +301 -301
- package/dist/auth.js.map +1 -1
- package/dist/aws4fetch.esm-p7eEzLCs.js +1702 -0
- package/dist/aws4fetch.esm-p7eEzLCs.js.map +1 -0
- package/dist/baerly.js +35 -15
- package/dist/baerly.js.map +1 -1
- package/dist/baerly.spec.json +342 -0
- package/dist/bytes-BXdamO3L.js.map +1 -1
- package/dist/{client-DYZfoZb9.d.ts → client-Fe8CwB73.d.ts} +10 -10
- package/dist/client-react.d.ts +3 -3
- package/dist/client-react.js +4 -4
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +4 -4
- package/dist/client.js +3 -3
- package/dist/client.js.map +1 -1
- package/dist/{cloudflare-CINJPKCW.js → cloudflare-DzKBrUlg.js} +178 -2
- package/dist/cloudflare-DzKBrUlg.js.map +1 -0
- package/dist/cloudflare.d.ts +49 -6
- package/dist/cloudflare.js +59 -26
- package/dist/cloudflare.js.map +1 -1
- package/dist/config-1tv0-Yzm.js +2693 -0
- package/dist/config-1tv0-Yzm.js.map +1 -0
- package/dist/constants-CfeMWQWk.js +222 -0
- package/dist/constants-CfeMWQWk.js.map +1 -0
- package/dist/context-DRZ3tZ5l.js.map +1 -1
- package/dist/{cost-CQt1YRkA.js → cost-DSMIVqzL.js} +43 -42
- package/dist/cost-DSMIVqzL.js.map +1 -0
- package/dist/current-json-C6nhPOm1.js +190 -0
- package/dist/current-json-C6nhPOm1.js.map +1 -0
- package/dist/{db-BM3y2JQw.d.ts → db-DsPkOVEH.d.ts} +26 -108
- package/dist/{deploy-CrAbfgCq.js → deploy-DonTr-CV.js} +12 -5
- package/dist/deploy-DonTr-CV.js.map +1 -0
- package/dist/dev-vite.d.ts +11 -7
- package/dist/dev-vite.js +7 -6
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +1 -1
- package/dist/dev.js +1 -1
- package/dist/{doctor-Db-hzPmE.js → doctor-DSIyCDg_.js} +14 -136
- package/dist/doctor-DSIyCDg_.js.map +1 -0
- package/dist/{dump-BYA55NLP.js → dump-Bh5k26VQ.js} +10 -31
- package/dist/dump-Bh5k26VQ.js.map +1 -0
- package/dist/{errors-DOdL95kK.js → errors-Dfa3p78c.js} +25 -5
- package/dist/errors-Dfa3p78c.js.map +1 -0
- package/dist/{export-Bhbz90-z.js → export-DtF5tDIM.js} +11 -32
- package/dist/{export-Bhbz90-z.js.map → export-DtF5tDIM.js.map} +1 -1
- package/dist/{fsck-CPPZWt9p.js → fsck-D_djMO5D.js} +28 -39
- package/dist/fsck-D_djMO5D.js.map +1 -0
- package/dist/{http-Cw8p6y5b.js → http-DxM9MflO.js} +151 -79
- package/dist/http-DxM9MflO.js.map +1 -0
- package/dist/http.d.ts +42 -26
- package/dist/http.js +3 -2
- package/dist/{index-DwDTWPSU.d.ts → index-0rZcMBwy.d.ts} +10 -7
- package/dist/{index-C3JAH1Yo.d.ts → index-B6oexfOB.d.ts} +9 -9
- package/dist/{index-cUY-36AN.d.ts → index-BNRh23K9.d.ts} +21 -5
- package/dist/{index-DSvwEUeF.d.ts → index-BYk9oCNf.d.ts} +240 -202
- package/dist/index.d.ts +6 -6
- package/dist/index.js +5 -5
- package/dist/{indexes-DAu2AkTW.d.ts → indexes-Dn9hbGQG.d.ts} +2 -2
- package/dist/{inspect-Bdbzvi-_.js → inspect-6WZ-pC7-.js} +21 -36
- package/dist/inspect-6WZ-pC7-.js.map +1 -0
- package/dist/key-Di6yyxFu.js +35 -0
- package/dist/key-Di6yyxFu.js.map +1 -0
- package/dist/{snapshot-SS8USDUF.js → log-tail-D98U1JBo.js} +179 -84
- package/dist/log-tail-D98U1JBo.js.map +1 -0
- package/dist/{maintenance-ClzBC1Vv.js → maintenance-B4Dki6Ig.js} +438 -176
- package/dist/maintenance-B4Dki6Ig.js.map +1 -0
- package/dist/{maintenance-BRrThz8V.d.ts → maintenance-B_e0T99L.d.ts} +114 -26
- package/dist/{maintenance-BvOv6BMM.js → maintenance-C7coQp4c.js} +217 -94
- package/dist/maintenance-C7coQp4c.js.map +1 -0
- package/dist/maintenance.d.ts +3 -2
- package/dist/maintenance.js +3 -2
- package/dist/node.d.ts +176 -68
- package/dist/node.js +3 -2
- package/dist/{normalize-XWY25_sG.js → normalize-rjnZLwS4.js} +2 -2
- package/dist/normalize-rjnZLwS4.js.map +1 -0
- package/dist/{observability-CpOiEN0k.js → observability-wzs3-BL_.js} +279 -109
- package/dist/observability-wzs3-BL_.js.map +1 -0
- package/dist/observability.d.ts +3 -3
- package/dist/observability.js +1 -1
- package/dist/{plan-DOTl21vq.js → plan-a7PJHBCy.js} +7 -4
- package/dist/plan-a7PJHBCy.js.map +1 -0
- package/dist/{query-BmiQy328.js → query-rAtXNQQB.js} +1063 -1202
- package/dist/query-rAtXNQQB.js.map +1 -0
- package/dist/{rebuild-index-DC_nR6wP.js → rebuild-index-BVzQSZlm.js} +10 -32
- package/dist/rebuild-index-BVzQSZlm.js.map +1 -0
- package/dist/{request-BEF_OvMh.js → request-u0M51mhJ.js} +3 -3
- package/dist/{request-BEF_OvMh.js.map → request-u0M51mhJ.js.map} +1 -1
- package/dist/restore-R-4rbciV.js +778 -0
- package/dist/restore-R-4rbciV.js.map +1 -0
- package/dist/runtime-spec-qL3_lTTU.js +391 -0
- package/dist/runtime-spec-qL3_lTTU.js.map +1 -0
- package/dist/s3-http-B-z8th6O.d.ts +60 -0
- package/dist/s3.d.ts +47 -0
- package/dist/s3.js +45 -0
- package/dist/s3.js.map +1 -0
- package/dist/{shared-secret-BJdSwpgw.js → shared-secret-DgEicd3x.js} +13 -5
- package/dist/shared-secret-DgEicd3x.js.map +1 -0
- package/dist/src-BG20LZs7.js +2271 -0
- package/dist/src-BG20LZs7.js.map +1 -0
- package/dist/{src-zhEAmmF7.js → src-CYHFDrKz.js} +82 -99
- package/dist/src-CYHFDrKz.js.map +1 -0
- package/dist/{src-QQ7jDeL2.js → src-DYZ4H1aF.js} +44 -23
- package/dist/src-DYZ4H1aF.js.map +1 -0
- package/dist/subcommand-DoDA-K7d.js +197 -0
- package/dist/subcommand-DoDA-K7d.js.map +1 -0
- package/dist/time-DUqvFMHq.js +119 -0
- package/dist/time-DUqvFMHq.js.map +1 -0
- package/dist/{usage-CLjirdD-.js → usage-DBV1eQHC.js} +7 -22
- package/dist/usage-DBV1eQHC.js.map +1 -0
- package/dist/{validate-DCq_0DIn.js → validate-DtljsCh1.js} +51 -51
- package/dist/{validate-DCq_0DIn.js.map → validate-DtljsCh1.js.map} +1 -1
- package/dist/wire-izfGZDvr.js.map +1 -1
- package/package.json +77 -42
- package/dist/cloudflare-CINJPKCW.js.map +0 -1
- package/dist/config-DVfDGyw1.js +0 -278
- package/dist/config-DVfDGyw1.js.map +0 -1
- package/dist/cost-CQt1YRkA.js.map +0 -1
- package/dist/current-json-C-EyJqs0.js +0 -354
- package/dist/current-json-C-EyJqs0.js.map +0 -1
- package/dist/deploy-CrAbfgCq.js.map +0 -1
- package/dist/doctor-Db-hzPmE.js.map +0 -1
- package/dist/dump-BYA55NLP.js.map +0 -1
- package/dist/errors-DOdL95kK.js.map +0 -1
- package/dist/fsck-CPPZWt9p.js.map +0 -1
- package/dist/http-Cw8p6y5b.js.map +0 -1
- package/dist/inspect-Bdbzvi-_.js.map +0 -1
- package/dist/maintenance-BvOv6BMM.js.map +0 -1
- package/dist/maintenance-ClzBC1Vv.js.map +0 -1
- package/dist/normalize-XWY25_sG.js.map +0 -1
- package/dist/observability-CpOiEN0k.js.map +0 -1
- package/dist/plan-DOTl21vq.js.map +0 -1
- package/dist/query-BmiQy328.js.map +0 -1
- package/dist/rebuild-index-DC_nR6wP.js.map +0 -1
- package/dist/restore-C6IcmLeA.js +0 -771
- package/dist/restore-C6IcmLeA.js.map +0 -1
- package/dist/shared-secret-BJdSwpgw.js.map +0 -1
- package/dist/snapshot-SS8USDUF.js.map +0 -1
- package/dist/src-DU1sCMlr.js +0 -6236
- package/dist/src-DU1sCMlr.js.map +0 -1
- package/dist/src-QQ7jDeL2.js.map +0 -1
- package/dist/src-zhEAmmF7.js.map +0 -1
- package/dist/subcommand-DZcHcsYp.js +0 -5122
- package/dist/subcommand-DZcHcsYp.js.map +0 -1
- package/dist/usage-CLjirdD-.js.map +0 -1
- /package/dist/{chunk-EAsCxrDo.js → rolldown-runtime-EAsCxrDo.js} +0 -0
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { t as loadAppConfig } from "./config-1tv0-Yzm.js";
|
|
2
|
+
import { a as setJsonMode, c as parseArgs, n as emitError, o as BaerlyError, s as defineCommand } from "./baerly.js";
|
|
3
|
+
import "node:stream";
|
|
4
|
+
//#region ../server/src/names.ts
|
|
5
|
+
/** Reject names in the system-reserved leading-"_" namespace. See docs/adr/003-layout-versioning-cordon.md. */
|
|
6
|
+
const assertNameNotReserved = (name, context) => {
|
|
7
|
+
if (name.startsWith("_")) throw new BaerlyError("InvalidConfig", `${context}: "${name}" is reserved — names beginning with "_" are reserved for system use. See docs/adr/003-layout-versioning-cordon.md.`);
|
|
8
|
+
};
|
|
9
|
+
const utf8 = new TextEncoder();
|
|
10
|
+
const CONTROL_CHARS = /[\u0000-\u001f\u007f-\u009f]/;
|
|
11
|
+
/**
|
|
12
|
+
* The single validation rule for every caller-controlled key segment
|
|
13
|
+
* (`_id`, `collection`, `app`, `tenant`) before it becomes a written
|
|
14
|
+
* key segment or `LocalFsStorage` path. Rejects empty / `"/"` /
|
|
15
|
+
* `"."`|`".."` / C0-C1 control / leading `"_"` (ADR-003) / `> MAX_SEGMENT_BYTES`,
|
|
16
|
+
* all as `BaerlyError{code:"InvalidConfig"}`.
|
|
17
|
+
*
|
|
18
|
+
* @param role human label for the segment ("_id" | "collection" | "app" | "tenant").
|
|
19
|
+
* @param verb optional calling-context label for the message.
|
|
20
|
+
*/
|
|
21
|
+
const assertPathSegment = (value, role, verb = "") => {
|
|
22
|
+
const where = verb === "" ? role : `${verb}: ${role}`;
|
|
23
|
+
if (value.length === 0) throw new BaerlyError("InvalidConfig", `${where} must be a non-empty string`);
|
|
24
|
+
if (value.includes("/")) throw new BaerlyError("InvalidConfig", `${where} may not contain "/": ${JSON.stringify(value)}`);
|
|
25
|
+
if (value === "." || value === "..") throw new BaerlyError("InvalidConfig", `${where} may not be "." or "..": ${JSON.stringify(value)}`);
|
|
26
|
+
if (CONTROL_CHARS.test(value)) throw new BaerlyError("InvalidConfig", `${where} may not contain control characters`);
|
|
27
|
+
if (utf8.encode(value).length > 256) throw new BaerlyError("InvalidConfig", `${where} is too long (> 256 bytes)`);
|
|
28
|
+
assertNameNotReserved(value, where);
|
|
29
|
+
};
|
|
30
|
+
//#endregion
|
|
31
|
+
//#region src/subcommand.ts
|
|
32
|
+
/**
|
|
33
|
+
* Shared citty arg fragments for the flags every operator command
|
|
34
|
+
* takes with identical wording. Each subcommand spreads the ones it
|
|
35
|
+
* needs into its own `... as const satisfies ArgsDef` literal, so the
|
|
36
|
+
* `--bucket` / `--app` / `--tenant` / `--collection` / `--json`
|
|
37
|
+
* descriptions can't drift copy-to-copy (they did: `--collection` had
|
|
38
|
+
* both "Collection name" and "Collection name." variants). Bespoke
|
|
39
|
+
* flags (`--config`, `--indexes`, `--provider`, `--verbose`, …) stay
|
|
40
|
+
* inline in the command that owns them.
|
|
41
|
+
*/
|
|
42
|
+
const BUCKET_ARG = {
|
|
43
|
+
type: "string",
|
|
44
|
+
required: true,
|
|
45
|
+
description: "Bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>)",
|
|
46
|
+
valueHint: "bucket-uri"
|
|
47
|
+
};
|
|
48
|
+
const APP_ARG = {
|
|
49
|
+
type: "string",
|
|
50
|
+
required: false,
|
|
51
|
+
description: "Application name segment (defaults to baerly.config.ts).",
|
|
52
|
+
valueHint: "app"
|
|
53
|
+
};
|
|
54
|
+
const TENANT_ARG = {
|
|
55
|
+
type: "string",
|
|
56
|
+
required: false,
|
|
57
|
+
description: "Tenant name segment (defaults to baerly.config.ts).",
|
|
58
|
+
valueHint: "tenant"
|
|
59
|
+
};
|
|
60
|
+
const COLLECTION_ARG = {
|
|
61
|
+
type: "string",
|
|
62
|
+
required: true,
|
|
63
|
+
description: "Collection name.",
|
|
64
|
+
valueHint: "name"
|
|
65
|
+
};
|
|
66
|
+
const JSON_ARG = {
|
|
67
|
+
type: "boolean",
|
|
68
|
+
description: "Emit a structured JSON envelope to stdout (success) or stderr (error)"
|
|
69
|
+
};
|
|
70
|
+
/** Shared exit-code mapping for caught `BaerlyError`s. */
|
|
71
|
+
const errorToExitCode = (code) => {
|
|
72
|
+
if (code === "InvalidConfig") return 1;
|
|
73
|
+
if (code === "Conflict" || code === "Internal" || code === "InvalidResponse") return 3;
|
|
74
|
+
return 2;
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* Validate a `--collection` arg through the same shared rule the
|
|
78
|
+
* server uses for every caller-controlled key segment, before it is
|
|
79
|
+
* interpolated into a bucket key. Throws `BaerlyError("InvalidConfig",
|
|
80
|
+
* …)` on a traversal / empty / control-char / reserved value. `verb`
|
|
81
|
+
* is the operator-facing command name (e.g. `"baerly admin restore"`,
|
|
82
|
+
* `"baerly inspect"`) so the message names the exact command.
|
|
83
|
+
*
|
|
84
|
+
* (app/tenant are validated at their own chokepoint inside
|
|
85
|
+
* `resolveAppTenant`; this guards the per-command `collection` arg.)
|
|
86
|
+
*/
|
|
87
|
+
const assertCollectionArg = (collection, verb) => {
|
|
88
|
+
assertPathSegment(collection, "collection", verb);
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* Build the app/tenant resolver. Captures `name` to surface the
|
|
92
|
+
* calling subcommand in the InvalidConfig hint.
|
|
93
|
+
*/
|
|
94
|
+
const makeResolveAppTenant = (name) => {
|
|
95
|
+
return async (args) => {
|
|
96
|
+
const flagApp = typeof args.app === "string" && args.app.length > 0 ? args.app : void 0;
|
|
97
|
+
const flagTenant = typeof args.tenant === "string" && args.tenant.length > 0 ? args.tenant : void 0;
|
|
98
|
+
let app;
|
|
99
|
+
let tenant;
|
|
100
|
+
if (flagApp !== void 0 && flagTenant !== void 0) {
|
|
101
|
+
app = flagApp;
|
|
102
|
+
tenant = flagTenant;
|
|
103
|
+
} else {
|
|
104
|
+
let cfg;
|
|
105
|
+
try {
|
|
106
|
+
cfg = await loadAppConfig();
|
|
107
|
+
} catch (error) {
|
|
108
|
+
throw new BaerlyError("InvalidConfig", `baerly ${name}: --app / --tenant not supplied and no baerly.config.{ts,js,mjs,json} in cwd (${error instanceof BaerlyError ? error.message : error.message})`, error);
|
|
109
|
+
}
|
|
110
|
+
app = flagApp ?? cfg.app;
|
|
111
|
+
tenant = flagTenant ?? cfg.tenant;
|
|
112
|
+
}
|
|
113
|
+
assertPathSegment(app, "app", `baerly ${name}`);
|
|
114
|
+
assertPathSegment(tenant, "tenant", `baerly ${name}`);
|
|
115
|
+
return {
|
|
116
|
+
app,
|
|
117
|
+
tenant
|
|
118
|
+
};
|
|
119
|
+
};
|
|
120
|
+
};
|
|
121
|
+
/**
|
|
122
|
+
* Wrap `def.handler` with the standard JSON-mode toggle, unknown-key
|
|
123
|
+
* rejection, and error-to-exit-code mapping. Shared by both the citty
|
|
124
|
+
* `run({ args })` path and the test `run(argv)` path. The caller
|
|
125
|
+
* supplies the {@link SubcommandContext}; this lets each `run(argv)`
|
|
126
|
+
* invocation attach its own `streams` override without leaking across
|
|
127
|
+
* invocations.
|
|
128
|
+
*/
|
|
129
|
+
const kebabToCamel = (s) => s.replace(/-(\w)/g, (_, c) => c.toUpperCase());
|
|
130
|
+
const wrapHandler = (def) => {
|
|
131
|
+
const allowedKeys = new Set(Object.keys(def.args).flatMap((k) => k.includes("-") ? [k, kebabToCamel(k)] : [k]).concat(["_"]));
|
|
132
|
+
return async (args, ctx) => {
|
|
133
|
+
if ("json" in def.args) setJsonMode(args.json === true);
|
|
134
|
+
try {
|
|
135
|
+
for (const k of Object.keys(args)) if (!allowedKeys.has(k)) throw new BaerlyError("InvalidConfig", `baerly ${def.name}: unknown flag --${k}`);
|
|
136
|
+
return await def.handler(args, ctx);
|
|
137
|
+
} catch (error) {
|
|
138
|
+
if (error instanceof BaerlyError) {
|
|
139
|
+
emitError(def.name, error.code, error.message);
|
|
140
|
+
return errorToExitCode(error.code);
|
|
141
|
+
}
|
|
142
|
+
emitError(def.name, "Unknown", error.message);
|
|
143
|
+
return 2;
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
};
|
|
147
|
+
/**
|
|
148
|
+
* Wrap a baerly subcommand. Returns `{ cmd, run }` —
|
|
149
|
+
* - `cmd` is a citty `defineCommand` block; mount it in
|
|
150
|
+
* `baerly.ts`'s `subCommands`. It calls `process.exit(code)` on a
|
|
151
|
+
* non-zero exit so the parent process surfaces the failure.
|
|
152
|
+
* - `run(argv)` is the in-process test entry. It parses `argv` with
|
|
153
|
+
* citty's `parseArgs`, dispatches through the same wrapped
|
|
154
|
+
* handler, and returns the integer exit code (does NOT call
|
|
155
|
+
* `process.exit`).
|
|
156
|
+
*
|
|
157
|
+
* The two paths share `wrapHandler` so JSON-mode toggling,
|
|
158
|
+
* unknown-flag rejection, and error-to-exit-code mapping behave
|
|
159
|
+
* identically.
|
|
160
|
+
*/
|
|
161
|
+
const defineBaerlySubcommand = (def) => {
|
|
162
|
+
const resolveAppTenant = makeResolveAppTenant(def.name);
|
|
163
|
+
const wrapped = wrapHandler(def);
|
|
164
|
+
const cmd = defineCommand({
|
|
165
|
+
meta: {
|
|
166
|
+
name: def.name,
|
|
167
|
+
description: def.meta.description
|
|
168
|
+
},
|
|
169
|
+
args: def.args,
|
|
170
|
+
run: async ({ args }) => {
|
|
171
|
+
const code = await wrapped(args, { resolveAppTenant });
|
|
172
|
+
if (code !== 0) process.exit(code);
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
const run = async (argv, options) => {
|
|
176
|
+
let parsed;
|
|
177
|
+
try {
|
|
178
|
+
parsed = parseArgs(argv, def.args);
|
|
179
|
+
} catch (error) {
|
|
180
|
+
setJsonMode(argv.includes("--json"));
|
|
181
|
+
emitError(def.name, "InvalidConfig", error.message);
|
|
182
|
+
return 1;
|
|
183
|
+
}
|
|
184
|
+
return wrapped(parsed, {
|
|
185
|
+
resolveAppTenant,
|
|
186
|
+
streams: options?.streams
|
|
187
|
+
});
|
|
188
|
+
};
|
|
189
|
+
return {
|
|
190
|
+
cmd,
|
|
191
|
+
run
|
|
192
|
+
};
|
|
193
|
+
};
|
|
194
|
+
//#endregion
|
|
195
|
+
export { TENANT_ARG as a, assertPathSegment as c, JSON_ARG as i, assertNameNotReserved as l, BUCKET_ARG as n, assertCollectionArg as o, COLLECTION_ARG as r, defineBaerlySubcommand as s, APP_ARG as t };
|
|
196
|
+
|
|
197
|
+
//# sourceMappingURL=subcommand-DoDA-K7d.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"subcommand-DoDA-K7d.js","names":[],"sources":["../packages/server/src/names.ts","../packages/server/src/path-segment.ts","../packages/cli/src/subcommand.ts"],"sourcesContent":["import { BaerlyError } from \"@baerly/protocol\";\n\n/** Reject names in the system-reserved leading-\"_\" namespace. See docs/adr/003-layout-versioning-cordon.md. */\nexport const assertNameNotReserved = (name: string, context: string): void => {\n if (name.startsWith(\"_\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${context}: \"${name}\" is reserved — names beginning with \"_\" are reserved for system use. See docs/adr/003-layout-versioning-cordon.md.`,\n );\n }\n};\n","import { BaerlyError } from \"@baerly/protocol\";\nimport { assertNameNotReserved } from \"./names.ts\";\n\n/**\n * Per-segment byte ceiling. S3 and R2 cap a full object key at 1024\n * UTF-8 bytes; a key is several segments, so this 256 leaves real prefix\n * headroom. The assembled multi-segment key sum is bounded separately on\n * the write path, not here. This is an intentional server-local *policy*\n * value (not the protocol-level S3/R2 fact `MAX_KEY_BYTES = 1024` in\n * `@baerly/protocol`'s `constants.ts`); it lives here, co-located with the\n * one rule that uses it, to keep `protocol/constants.ts` out of the\n * validator's bundle closure.\n */\nexport const MAX_SEGMENT_BYTES = 256;\nconst utf8 = new TextEncoder();\n// C0 (U+0000-U+001F) + DEL/C1 (U+007F-U+009F).\n// eslint-disable-next-line no-control-regex -- intentional control-char class\nconst CONTROL_CHARS = /[\\u0000-\\u001f\\u007f-\\u009f]/;\n\n/**\n * The single validation rule for every caller-controlled key segment\n * (`_id`, `collection`, `app`, `tenant`) before it becomes a written\n * key segment or `LocalFsStorage` path. Rejects empty / `\"/\"` /\n * `\".\"`|`\"..\"` / C0-C1 control / leading `\"_\"` (ADR-003) / `> MAX_SEGMENT_BYTES`,\n * all as `BaerlyError{code:\"InvalidConfig\"}`.\n *\n * @param role human label for the segment (\"_id\" | \"collection\" | \"app\" | \"tenant\").\n * @param verb optional calling-context label for the message.\n */\nexport const assertPathSegment = (value: string, role: string, verb = \"\"): void => {\n const where = verb === \"\" ? role : `${verb}: ${role}`;\n if (value.length === 0) {\n throw new BaerlyError(\"InvalidConfig\", `${where} must be a non-empty string`);\n }\n if (value.includes(\"/\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${where} may not contain \"/\": ${JSON.stringify(value)}`,\n );\n }\n if (value === \".\" || value === \"..\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${where} may not be \".\" or \"..\": ${JSON.stringify(value)}`,\n );\n }\n if (CONTROL_CHARS.test(value)) {\n throw new BaerlyError(\"InvalidConfig\", `${where} may not contain control characters`);\n }\n if (utf8.encode(value).length > MAX_SEGMENT_BYTES) {\n throw new BaerlyError(\"InvalidConfig\", `${where} is too long (> ${MAX_SEGMENT_BYTES} bytes)`);\n }\n // Leading `_` is the ADR-003 reserved namespace.\n assertNameNotReserved(value, where);\n};\n","/**\n * Shared subcommand scaffolding for `baerly`.\n *\n * Every operator-facing subcommand (`inspect`, `export`, `doctor`, and\n * every `admin/*` command) was independently re-implementing the same\n * five pieces of boilerplate:\n *\n * 1. `setJsonMode(args.json === true)` before any emission.\n * 2. A `KNOWN_KEYS` whitelist asserting unknown `--flag` rejection.\n * 3. An `errorToExitCode(code)` mapping —\n * `InvalidConfig → 1`, `Conflict|Internal|InvalidResponse → 3`,\n * else `2`.\n * 4. `resolveAppTenant(args)` falling back through `baerly.config.*`\n * to either real values or hard-coded `\"app\"` / `\"tenant\"`\n * literals.\n * 5. Two parallel entry points: a citty `defineCommand` block that\n * calls `process.exit(code)` on failure, and a `runXxx(argv)`\n * function for in-process tests that returns the exit code.\n *\n * The five copies drifted: some commands suppressed protocol-level\n * errors (no `Conflict|Internal|InvalidResponse → 3` arm), and the\n * config-fallback silently produced `\"app\"` / `\"tenant\"` literals\n * (confidently-wrong output when no config is present).\n *\n * {@link defineBaerlySubcommand} centralizes the five pieces:\n * - Computes the known-keys set from `Object.keys(args)` itself, so\n * a new flag is picked up automatically.\n * - Applies the full 3-bucket exit-code mapping uniformly.\n * - {@link SubcommandContext.resolveAppTenant} throws\n * `BaerlyError(\"InvalidConfig\", …)` with a `--app` / `--tenant`\n * hint when neither flags nor a loadable `baerly.config.*` supply\n * the values.\n * - Returns a bundle of {@link SubcommandBundle.cmd} (citty wiring)\n * and {@link SubcommandBundle.run} (test entry) sharing one\n * wrapped handler.\n */\n\nimport { type Readable, type Writable } from \"node:stream\";\nimport { defineCommand, parseArgs, type ArgsDef, type ParsedArgs, type CommandDef } from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { assertPathSegment } from \"@baerly/server/_internal/testing\";\nimport { loadAppConfig } from \"./config.ts\";\nimport { emitError, setJsonMode } from \"./output.ts\";\n\n/**\n * Shared citty arg fragments for the flags every operator command\n * takes with identical wording. Each subcommand spreads the ones it\n * needs into its own `... as const satisfies ArgsDef` literal, so the\n * `--bucket` / `--app` / `--tenant` / `--collection` / `--json`\n * descriptions can't drift copy-to-copy (they did: `--collection` had\n * both \"Collection name\" and \"Collection name.\" variants). Bespoke\n * flags (`--config`, `--indexes`, `--provider`, `--verbose`, …) stay\n * inline in the command that owns them.\n */\nexport const BUCKET_ARG = {\n type: \"string\",\n required: true,\n description: \"Bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>)\",\n valueHint: \"bucket-uri\",\n} as const;\n\nexport const APP_ARG = {\n type: \"string\",\n required: false,\n description: \"Application name segment (defaults to baerly.config.ts).\",\n valueHint: \"app\",\n} as const;\n\nexport const TENANT_ARG = {\n type: \"string\",\n required: false,\n description: \"Tenant name segment (defaults to baerly.config.ts).\",\n valueHint: \"tenant\",\n} as const;\n\nexport const COLLECTION_ARG = {\n type: \"string\",\n required: true,\n description: \"Collection name.\",\n valueHint: \"name\",\n} as const;\n\nexport const JSON_ARG = {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n} as const;\n\n/**\n * Optional stdin / stdout streams that a programmatic caller (today:\n * `runDump` / `runRestore` tests, and the export round-trip\n * integration test) can divert in place of `process.stdin` /\n * `process.stdout`. The citty entry point always uses the process\n * streams; only {@link SubcommandBundle.run} accepts these overrides.\n */\nexport interface SubcommandStreams {\n readonly stdin?: Readable;\n readonly stdout?: Writable;\n}\n\n/**\n * Capabilities the subcommand handler receives. Today: app/tenant\n * resolution. Kept narrow so the handler signature stays load-bearing\n * (the helper isn't a god object).\n */\ninterface SubcommandContext {\n /**\n * Returns `{ app, tenant }` resolved from explicit flags or\n * `baerly.config.{ts,js,mjs,json}` in the cwd.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — neither flag was\n * supplied AND no loadable config was found. The error message\n * includes a hint mentioning `--app` / `--tenant`.\n */\n readonly resolveAppTenant: (args: {\n readonly app?: string;\n readonly tenant?: string;\n }) => Promise<{ app: string; tenant: string }>;\n /**\n * Programmatic stdin / stdout overrides. `undefined` (or any\n * missing field) means \"use the process stream\". Only\n * `admin dump` / `admin restore` consume this; other commands\n * ignore the field.\n */\n readonly streams?: SubcommandStreams;\n}\n\n/**\n * Definition fed to {@link defineBaerlySubcommand}. `name` is the JSON\n * envelope tag (`\"inspect\"`, `\"admin.compact\"`, etc.); `args` is the\n * citty ArgsDef; `handler` returns the integer exit code.\n */\nexport interface SubcommandDef<TArgs extends ArgsDef> {\n /** JSON envelope `command` tag and the prefix of every emitted error. */\n readonly name: string;\n readonly meta: { readonly description: string };\n readonly args: TArgs;\n readonly handler: (args: ParsedArgs<TArgs>, ctx: SubcommandContext) => Promise<number>;\n}\n\n/**\n * Output of {@link defineBaerlySubcommand}. `cmd` plugs into\n * `subCommands` in `baerly.ts`; `run` is the in-process entry for\n * unit tests.\n */\nexport interface SubcommandBundle<TArgs extends ArgsDef> {\n readonly cmd: CommandDef<TArgs>;\n readonly run: (\n argv: readonly string[],\n options?: { readonly streams?: SubcommandStreams },\n ) => Promise<number>;\n}\n\n/** Shared exit-code mapping for caught `BaerlyError`s. */\nconst errorToExitCode = (code: string): number => {\n if (code === \"InvalidConfig\") {\n return 1;\n }\n if (code === \"Conflict\" || code === \"Internal\" || code === \"InvalidResponse\") {\n return 3;\n }\n return 2;\n};\n\n/**\n * Validate a `--collection` arg through the same shared rule the\n * server uses for every caller-controlled key segment, before it is\n * interpolated into a bucket key. Throws `BaerlyError(\"InvalidConfig\",\n * …)` on a traversal / empty / control-char / reserved value. `verb`\n * is the operator-facing command name (e.g. `\"baerly admin restore\"`,\n * `\"baerly inspect\"`) so the message names the exact command.\n *\n * (app/tenant are validated at their own chokepoint inside\n * `resolveAppTenant`; this guards the per-command `collection` arg.)\n */\nexport const assertCollectionArg = (collection: string, verb: string): void => {\n assertPathSegment(collection, \"collection\", verb);\n};\n\n/**\n * Build the app/tenant resolver. Captures `name` to surface the\n * calling subcommand in the InvalidConfig hint.\n */\nconst makeResolveAppTenant = (name: string): SubcommandContext[\"resolveAppTenant\"] => {\n return async (args) => {\n const flagApp = typeof args.app === \"string\" && args.app.length > 0 ? args.app : undefined;\n const flagTenant =\n typeof args.tenant === \"string\" && args.tenant.length > 0 ? args.tenant : undefined;\n let app: string;\n let tenant: string;\n if (flagApp !== undefined && flagTenant !== undefined) {\n app = flagApp;\n tenant = flagTenant;\n } else {\n let cfg: { app: string; tenant: string };\n try {\n cfg = await loadAppConfig();\n } catch (error) {\n // Re-throw with our own wording so the operator sees the\n // calling-command name and the hint to pass --app / --tenant\n // explicitly. The underlying loadAppConfig error is preserved\n // as the cause. (Only wraps a config-LOAD failure — the\n // segment validation below is intentionally outside this catch\n // so its own InvalidConfig message survives.)\n const inner = error instanceof BaerlyError ? error.message : (error as Error).message;\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly ${name}: --app / --tenant not supplied and no baerly.config.{ts,js,mjs,json} in cwd (${inner})`,\n error,\n );\n }\n app = flagApp ?? cfg.app;\n tenant = flagTenant ?? cfg.tenant;\n }\n // Single chokepoint covering every command that calls\n // resolveAppTenant: whatever the source (flags or config), the\n // resolved segments must pass the same shared rule before they\n // become bucket-key segments. A bad-but-supplied value throws\n // InvalidConfig, consistent with the \"not supplied\" case above.\n assertPathSegment(app, \"app\", `baerly ${name}`);\n assertPathSegment(tenant, \"tenant\", `baerly ${name}`);\n return { app, tenant };\n };\n};\n\n/**\n * Wrap `def.handler` with the standard JSON-mode toggle, unknown-key\n * rejection, and error-to-exit-code mapping. Shared by both the citty\n * `run({ args })` path and the test `run(argv)` path. The caller\n * supplies the {@link SubcommandContext}; this lets each `run(argv)`\n * invocation attach its own `streams` override without leaking across\n * invocations.\n */\nconst kebabToCamel = (s: string): string => s.replace(/-(\\w)/g, (_, c: string) => c.toUpperCase());\n\nconst wrapHandler = <TArgs extends ArgsDef>(\n def: SubcommandDef<TArgs>,\n): ((args: ParsedArgs<TArgs>, ctx: SubcommandContext) => Promise<number>) => {\n // Compute the allow-list once from the ArgsDef. citty injects `_`\n // for positional captures, so it must stay allowed. citty 0.2.2\n // also auto-injects a camelCase alias for every kebab-case flag\n // (e.g. `--where-comment` produces both `whereComment` and\n // `where-comment` on the parsed args), so each kebab key is\n // expanded to its camelCase variant in the allow-list too.\n const allowedKeys: ReadonlySet<string> = new Set(\n Object.keys(def.args)\n .flatMap((k) => (k.includes(\"-\") ? [k, kebabToCamel(k)] : [k]))\n .concat([\"_\"]),\n );\n return async (args, ctx) => {\n // `json` is conventional but not required — only toggle when it's\n // both declared in the ArgsDef and truthy on the parsed args.\n if (\"json\" in def.args) {\n setJsonMode((args as ParsedArgs<TArgs> & { json?: boolean }).json === true);\n }\n try {\n for (const k of Object.keys(args)) {\n if (!allowedKeys.has(k)) {\n throw new BaerlyError(\"InvalidConfig\", `baerly ${def.name}: unknown flag --${k}`);\n }\n }\n return await def.handler(args, ctx);\n } catch (error) {\n if (error instanceof BaerlyError) {\n emitError(def.name, error.code, error.message);\n return errorToExitCode(error.code);\n }\n emitError(def.name, \"Unknown\", (error as Error).message);\n return 2;\n }\n };\n};\n\n/**\n * Wrap a baerly subcommand. Returns `{ cmd, run }` —\n * - `cmd` is a citty `defineCommand` block; mount it in\n * `baerly.ts`'s `subCommands`. It calls `process.exit(code)` on a\n * non-zero exit so the parent process surfaces the failure.\n * - `run(argv)` is the in-process test entry. It parses `argv` with\n * citty's `parseArgs`, dispatches through the same wrapped\n * handler, and returns the integer exit code (does NOT call\n * `process.exit`).\n *\n * The two paths share `wrapHandler` so JSON-mode toggling,\n * unknown-flag rejection, and error-to-exit-code mapping behave\n * identically.\n */\nexport const defineBaerlySubcommand = <TArgs extends ArgsDef>(\n def: SubcommandDef<TArgs>,\n): SubcommandBundle<TArgs> => {\n const resolveAppTenant = makeResolveAppTenant(def.name);\n const wrapped = wrapHandler(def);\n\n const cmd = defineCommand({\n meta: { name: def.name, description: def.meta.description },\n args: def.args,\n run: async ({ args }) => {\n const code = await wrapped(args as ParsedArgs<TArgs>, { resolveAppTenant });\n if (code !== 0) {\n process.exit(code);\n }\n },\n });\n\n const run = async (\n argv: readonly string[],\n options?: { readonly streams?: SubcommandStreams },\n ): Promise<number> => {\n let parsed: ParsedArgs<TArgs>;\n try {\n parsed = parseArgs<TArgs>(argv as string[], def.args);\n } catch (error) {\n // Parse-time error from citty (missing required flag,\n // malformed value). Toggle JSON mode by sniffing argv since\n // we never reached the handler.\n setJsonMode(argv.includes(\"--json\"));\n emitError(def.name, \"InvalidConfig\", (error as Error).message);\n return 1;\n }\n return wrapped(parsed, { resolveAppTenant, streams: options?.streams });\n };\n\n return { cmd, run };\n};\n"],"mappings":";;;;;AAGA,MAAa,yBAAyB,MAAc,YAA0B;CAC5E,IAAI,KAAK,WAAW,GAAG,GACrB,MAAM,IAAI,YACR,iBACA,GAAG,QAAQ,KAAK,KAAK,oHACvB;AAEJ;ACIA,MAAM,OAAO,IAAI,YAAY;AAG7B,MAAM,gBAAgB;;;;;;;;;;;AAYtB,MAAa,qBAAqB,OAAe,MAAc,OAAO,OAAa;CACjF,MAAM,QAAQ,SAAS,KAAK,OAAO,GAAG,KAAK,IAAI;CAC/C,IAAI,MAAM,WAAW,GACnB,MAAM,IAAI,YAAY,iBAAiB,GAAG,MAAM,4BAA4B;CAE9E,IAAI,MAAM,SAAS,GAAG,GACpB,MAAM,IAAI,YACR,iBACA,GAAG,MAAM,wBAAwB,KAAK,UAAU,KAAK,GACvD;CAEF,IAAI,UAAU,OAAO,UAAU,MAC7B,MAAM,IAAI,YACR,iBACA,GAAG,MAAM,2BAA2B,KAAK,UAAU,KAAK,GAC1D;CAEF,IAAI,cAAc,KAAK,KAAK,GAC1B,MAAM,IAAI,YAAY,iBAAiB,GAAG,MAAM,oCAAoC;CAEtF,IAAI,KAAK,OAAO,KAAK,CAAC,CAAC,SAAA,KACrB,MAAM,IAAI,YAAY,iBAAiB,GAAG,MAAM,2BAA4C;CAG9F,sBAAsB,OAA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,IAAI;GACF,SAAS,UAAiB,MAAkB,IAAI,IAAI;EACtD,SAAS,OAAO;GAId,YAAY,KAAK,SAAS,QAAQ,CAAC;GACnC,UAAU,IAAI,MAAM,iBAAkB,MAAgB,OAAO;GAC7D,OAAO;EACT;EACA,OAAO,QAAQ,QAAQ;GAAE;GAAkB,SAAS,SAAS;EAAQ,CAAC;CACxE;CAEA,OAAO;EAAE;EAAK;CAAI;AACpB"}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { t as BaerlyError } from "./errors-Dfa3p78c.js";
|
|
2
|
+
//#region packages/protocol/src/types.ts
|
|
3
|
+
/**
|
|
4
|
+
* Mint a fresh {@link UUID}. The cast lives here so callers don't sprinkle
|
|
5
|
+
* `<UUID>crypto.randomUUID()` throughout the codebase.
|
|
6
|
+
*/
|
|
7
|
+
const uuid = () => crypto.randomUUID();
|
|
8
|
+
/**
|
|
9
|
+
* Mint a UUIDv7 — 48-bit Unix-millis prefix + 74 bits of randomness,
|
|
10
|
+
* formatted as a standard 8-4-4-4-12 UUID string per RFC 9562 §5.7.
|
|
11
|
+
* Lex-sortable by mint time, so it pairs well with object-storage
|
|
12
|
+
* list semantics. Returns a branded {@link UUID}.
|
|
13
|
+
*
|
|
14
|
+
* Uses `crypto.getRandomValues` which is universally available
|
|
15
|
+
* (Node 19+, Workerd, Bun, browsers).
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```ts
|
|
19
|
+
* const id = uuidv7();
|
|
20
|
+
* // e.g. "01956cad-4cc8-7abc-9def-0123456789ab"
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
const uuidv7 = () => {
|
|
24
|
+
const millis = Date.now();
|
|
25
|
+
const rand = /* @__PURE__ */ new Uint8Array(10);
|
|
26
|
+
crypto.getRandomValues(rand);
|
|
27
|
+
rand[0] = rand[0] & 15 | 112;
|
|
28
|
+
rand[2] = rand[2] & 63 | 128;
|
|
29
|
+
const millisHex = millis.toString(16).padStart(12, "0");
|
|
30
|
+
const b = Array.from(rand, (n) => n.toString(16).padStart(2, "0")).join("");
|
|
31
|
+
return `${millisHex.slice(0, 8)}-${millisHex.slice(8, 12)}-${b.slice(0, 4)}-${b.slice(4, 8)}-${b.slice(8, 20)}`;
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* Mint the trailing seq segment of an LSN (`<base32-time>_<sess>_<seq>`).
|
|
35
|
+
* Uses `COUNT_BIT_WIDTH` (see `packages/protocol/src/constants.ts`) to
|
|
36
|
+
* produce an 11-char descending base-32 string with a domain of
|
|
37
|
+
* 0 .. `Number.MAX_SAFE_INTEGER` (2^53 − 1).
|
|
38
|
+
*
|
|
39
|
+
* Used together with {@link timestamp} (the descending base-32
|
|
40
|
+
* encoding of millis-since-epoch). See {@link uint2strDesc} for the
|
|
41
|
+
* lex-reversal property both rely on.
|
|
42
|
+
*/
|
|
43
|
+
const countKey = (number) => uint2strDesc(number, 53);
|
|
44
|
+
const uint2str = (num, bits) => {
|
|
45
|
+
const maxBase32Length = Math.ceil(bits / 5);
|
|
46
|
+
return num.toString(32).padStart(maxBase32Length, "0");
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* Lex-reversed base-32 encoder for an unsigned integer in `[0, 2^bits)`.
|
|
50
|
+
* Pads to `Math.ceil(bits/5)` chars so all values in the domain compare
|
|
51
|
+
* lex against each other.
|
|
52
|
+
*
|
|
53
|
+
* **Order-reversal property:** for any pair of integers `a < b` (with
|
|
54
|
+
* `a, b ∈ [0, 2^bits)`), `uint2strDesc(a, bits) > uint2strDesc(b, bits)`
|
|
55
|
+
* lexicographically. Composed into an LSN of shape
|
|
56
|
+
* `<base32-time>_<session>_<seq>` (where both `<base32-time>` and
|
|
57
|
+
* `<seq>` use this encoder), a forward `Storage.list(prefix)`
|
|
58
|
+
* returns log entries in reverse-causal order — newer entries first.
|
|
59
|
+
*
|
|
60
|
+
* This is the structural property the read path leans on:
|
|
61
|
+
* `ListObjectsV2` is forward-only on S3, but the descending encoding
|
|
62
|
+
* makes "fetch the K newest entries" a single bounded LIST with
|
|
63
|
+
* `maxKeys=K` instead of a full-population LIST + in-memory reverse.
|
|
64
|
+
*
|
|
65
|
+
* Behaviourally verified across randomized populations in
|
|
66
|
+
* `packages/protocol/src/lsn-reverse-list.test.ts`. Quantified
|
|
67
|
+
* bytes-listed reduction is in
|
|
68
|
+
* `docs/spec/attachments/lsn-reverse-walk-baseline.json`
|
|
69
|
+
* (run `pnpm bench:lsn-reverse-walk` to reproduce). Spec rationale:
|
|
70
|
+
* `docs/spec/sync-protocol.md` §"LSNs, wall clocks, and downstream
|
|
71
|
+
* consumers".
|
|
72
|
+
*/
|
|
73
|
+
const uint2strDesc = (num, bits) => {
|
|
74
|
+
return uint2str(Math.pow(2, bits) - 1 - num, bits);
|
|
75
|
+
};
|
|
76
|
+
const str2uintDesc = (str, bits) => {
|
|
77
|
+
return Math.pow(2, bits) - 1 - parseInt(str, 32);
|
|
78
|
+
};
|
|
79
|
+
//#endregion
|
|
80
|
+
//#region packages/protocol/src/time.ts
|
|
81
|
+
/**
|
|
82
|
+
* Encode an epoch-millis instant as a lexicographically-DEScending
|
|
83
|
+
* base-32 key (newer sorts first). The load-bearing LSN ordering
|
|
84
|
+
* primitive — see {@link uint2strDesc}.
|
|
85
|
+
*
|
|
86
|
+
* `epoch` is REQUIRED and validated. There is no default: an argless
|
|
87
|
+
* call used to encode `0`, which descending-sorts as the most-ancient
|
|
88
|
+
* instant and would silently invert ordering. A non-finite, negative,
|
|
89
|
+
* or out-of-range `epoch` (e.g. a broken `Date.now()` returning `NaN`)
|
|
90
|
+
* would corrupt the key silently rather than fail loud, so it throws
|
|
91
|
+
* `Internal` instead — this is an invariant violation, not caller config
|
|
92
|
+
* (the only legitimate argument is `Date.now()`).
|
|
93
|
+
*/
|
|
94
|
+
const timestamp = (epoch) => {
|
|
95
|
+
if (!Number.isInteger(epoch) || epoch < 0 || epoch >= 2 ** 42) throw new BaerlyError("Internal", `timestamp(): epoch must be a non-negative integer < 2^42 (got ${epoch})`);
|
|
96
|
+
return uint2strDesc(epoch, 42);
|
|
97
|
+
};
|
|
98
|
+
/**
|
|
99
|
+
* Delay for `ms` milliseconds, with optional cancellation. If
|
|
100
|
+
* `signal` aborts before the delay elapses, the returned promise
|
|
101
|
+
* rejects with `signal.reason`. Used by `S3HttpStorage`'s retry
|
|
102
|
+
* loop so shutdown can interrupt an in-flight backoff instead of
|
|
103
|
+
* waiting for it to complete.
|
|
104
|
+
*/
|
|
105
|
+
const delay = (ms, signal) => new Promise((resolve, reject) => {
|
|
106
|
+
if (signal?.aborted) {
|
|
107
|
+
reject(signal.reason);
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const timer = setTimeout(resolve, ms);
|
|
111
|
+
signal?.addEventListener("abort", () => {
|
|
112
|
+
clearTimeout(timer);
|
|
113
|
+
reject(signal.reason);
|
|
114
|
+
}, { once: true });
|
|
115
|
+
});
|
|
116
|
+
//#endregion
|
|
117
|
+
export { uuid as a, str2uintDesc as i, timestamp as n, uuidv7 as o, countKey as r, delay as t };
|
|
118
|
+
|
|
119
|
+
//# sourceMappingURL=time-DUqvFMHq.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"time-DUqvFMHq.js","names":[],"sources":["../packages/protocol/src/types.ts","../packages/protocol/src/time.ts"],"sourcesContent":["import { COUNT_BIT_WIDTH } from \"./constants.ts\";\n\ndeclare const brand: unique symbol;\ntype Brand<B> = { [brand]: B };\n\n/**\n * Nominal-typing helper. `Branded<string, \"UUID\">` is a `string` at\n * runtime but the type system rejects mixing it with a plain `string` or\n * a string branded as something else. Used to prevent confusion bugs at\n * protocol boundaries (UUIDs vs. content versions are both strings, but\n * using the wrong one corrupts the per-collection log).\n *\n * Construct branded values via the helpers in this file (e.g. {@link uuid})\n * or with a tagged cast at a single, deliberate boundary — never `as string`\n * to widen one back. See `docs/contributing/conventions/src.md`.\n */\nexport type Branded<T, B> = T & Brand<B>;\n\n/**\n * A v4 UUID minted by this client. Used as session IDs and content\n * identifiers in non-versioned mode.\n */\nexport type UUID = Branded<string, \"UUID\">;\n\n/**\n * SHA-256 content digest, lowercase hex truncated to\n * `VERSION_HEX_LENGTH` (32 chars). Minted by\n * `versionFromContent` in `useVersioning=false` mode and used as\n * the `<key>@<version>` suffix in content keys.\n *\n * The synthetic `local-${op}` placeholder used for in-flight\n * optimistic updates also wears this brand — it never round-trips\n * to S3, only flows through local optimistic state.\n */\nexport type ContentVersionId = Branded<string, \"ContentVersionId\">;\n\n/**\n * Mint a fresh {@link UUID}. The cast lives here so callers don't sprinkle\n * `<UUID>crypto.randomUUID()` throughout the codebase.\n */\nexport const uuid = (): UUID => crypto.randomUUID() as UUID;\n\n/**\n * Mint a UUIDv7 — 48-bit Unix-millis prefix + 74 bits of randomness,\n * formatted as a standard 8-4-4-4-12 UUID string per RFC 9562 §5.7.\n * Lex-sortable by mint time, so it pairs well with object-storage\n * list semantics. Returns a branded {@link UUID}.\n *\n * Uses `crypto.getRandomValues` which is universally available\n * (Node 19+, Workerd, Bun, browsers).\n *\n * @example\n * ```ts\n * const id = uuidv7();\n * // e.g. \"01956cad-4cc8-7abc-9def-0123456789ab\"\n * ```\n */\nexport const uuidv7 = (): UUID => {\n const millis = Date.now();\n const rand = new Uint8Array(10);\n crypto.getRandomValues(rand);\n // Version nibble: top 4 bits of rand[0] = 0b0111 (v7). The byte\n // sits at the start of the \"version-and-rand-a\" group below.\n rand[0] = (rand[0]! & 0x0f) | 0x70;\n // Variant bits: top 2 bits of rand[2] = 0b10 (RFC 4122 variant).\n // This byte starts the \"variant-and-rand-b\" group below.\n rand[2] = (rand[2]! & 0x3f) | 0x80;\n const millisHex = millis.toString(16).padStart(12, \"0\");\n const b = Array.from(rand, (n) => n.toString(16).padStart(2, \"0\")).join(\"\");\n return `${millisHex.slice(0, 8)}-${millisHex.slice(8, 12)}-${b.slice(0, 4)}-${b.slice(4, 8)}-${b.slice(8, 20)}` as UUID;\n};\n\n/**\n * Mint the trailing seq segment of an LSN (`<base32-time>_<sess>_<seq>`).\n * Uses `COUNT_BIT_WIDTH` (see `packages/protocol/src/constants.ts`) to\n * produce an 11-char descending base-32 string with a domain of\n * 0 .. `Number.MAX_SAFE_INTEGER` (2^53 − 1).\n *\n * Used together with {@link timestamp} (the descending base-32\n * encoding of millis-since-epoch). See {@link uint2strDesc} for the\n * lex-reversal property both rely on.\n */\nexport const countKey = (number: number): string => uint2strDesc(number, COUNT_BIT_WIDTH);\n\nexport const uint2str = (num: number, bits: number) => {\n const maxBase32Length = Math.ceil(bits / 5); // Change from 4 to 5 because log2(32) is roughly 5.\n const base32Representation = num.toString(32);\n return base32Representation.padStart(maxBase32Length, \"0\");\n};\n\nexport const str2uint = (str: string) => {\n return parseInt(str, 32); // Parse the string as base 32.\n};\n\n/**\n * Lex-reversed base-32 encoder for an unsigned integer in `[0, 2^bits)`.\n * Pads to `Math.ceil(bits/5)` chars so all values in the domain compare\n * lex against each other.\n *\n * **Order-reversal property:** for any pair of integers `a < b` (with\n * `a, b ∈ [0, 2^bits)`), `uint2strDesc(a, bits) > uint2strDesc(b, bits)`\n * lexicographically. Composed into an LSN of shape\n * `<base32-time>_<session>_<seq>` (where both `<base32-time>` and\n * `<seq>` use this encoder), a forward `Storage.list(prefix)`\n * returns log entries in reverse-causal order — newer entries first.\n *\n * This is the structural property the read path leans on:\n * `ListObjectsV2` is forward-only on S3, but the descending encoding\n * makes \"fetch the K newest entries\" a single bounded LIST with\n * `maxKeys=K` instead of a full-population LIST + in-memory reverse.\n *\n * Behaviourally verified across randomized populations in\n * `packages/protocol/src/lsn-reverse-list.test.ts`. Quantified\n * bytes-listed reduction is in\n * `docs/spec/attachments/lsn-reverse-walk-baseline.json`\n * (run `pnpm bench:lsn-reverse-walk` to reproduce). Spec rationale:\n * `docs/spec/sync-protocol.md` §\"LSNs, wall clocks, and downstream\n * consumers\".\n */\nexport const uint2strDesc = (num: number, bits: number): string => {\n const maxValue = Math.pow(2, bits) - 1;\n return uint2str(maxValue - num, bits);\n};\n\nexport const str2uintDesc = (str: string, bits: number): number => {\n const maxValue = Math.pow(2, bits) - 1;\n const num = parseInt(str, 32); // Convert base32 string to number\n return maxValue - num;\n};\n","import { TIMESTAMP_BIT_WIDTH } from \"./constants.ts\";\nimport { BaerlyError } from \"./errors.ts\";\nimport { uint2strDesc } from \"./types.ts\";\n\n/**\n * Encode an epoch-millis instant as a lexicographically-DEScending\n * base-32 key (newer sorts first). The load-bearing LSN ordering\n * primitive — see {@link uint2strDesc}.\n *\n * `epoch` is REQUIRED and validated. There is no default: an argless\n * call used to encode `0`, which descending-sorts as the most-ancient\n * instant and would silently invert ordering. A non-finite, negative,\n * or out-of-range `epoch` (e.g. a broken `Date.now()` returning `NaN`)\n * would corrupt the key silently rather than fail loud, so it throws\n * `Internal` instead — this is an invariant violation, not caller config\n * (the only legitimate argument is `Date.now()`).\n */\nexport const timestamp = (epoch: number): string => {\n if (!Number.isInteger(epoch) || epoch < 0 || epoch >= 2 ** TIMESTAMP_BIT_WIDTH) {\n throw new BaerlyError(\n \"Internal\",\n `timestamp(): epoch must be a non-negative integer < 2^${TIMESTAMP_BIT_WIDTH} (got ${epoch})`,\n );\n }\n return uint2strDesc(epoch, TIMESTAMP_BIT_WIDTH);\n};\n\n/**\n * Delay for `ms` milliseconds, with optional cancellation. If\n * `signal` aborts before the delay elapses, the returned promise\n * rejects with `signal.reason`. Used by `S3HttpStorage`'s retry\n * loop so shutdown can interrupt an in-flight backoff instead of\n * waiting for it to complete.\n */\nexport const delay = (ms: number, signal?: AbortSignal): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n const timer = setTimeout(resolve, ms);\n signal?.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n reject(signal.reason);\n },\n // Stryker disable next-line BooleanLiteral,ObjectLiteral: `{ once: true }` removes the\n // listener after the first fire. AbortController fires `abort` only once per signal, so\n // `once: false` / `{}` produce identical observable behaviour — the listener stays attached\n // to an already-fired signal, but calling reject on a settled Promise is a no-op. The\n // BooleanLiteral (once:false) and ObjectLiteral ({}) mutations are genuine equivalences.\n { once: true },\n );\n });\n"],"mappings":";;;;;;AAwCA,MAAa,aAAmB,OAAO,WAAW;;;;;;;;;;;;;;;;AAiBlD,MAAa,eAAqB;CAChC,MAAM,SAAS,KAAK,IAAI;CACxB,MAAM,uBAAO,IAAI,WAAW,EAAE;CAC9B,OAAO,gBAAgB,IAAI;CAG3B,KAAK,KAAM,KAAK,KAAM,KAAQ;CAG9B,KAAK,KAAM,KAAK,KAAM,KAAQ;CAC9B,MAAM,YAAY,OAAO,SAAS,EAAE,CAAC,CAAC,SAAS,IAAI,GAAG;CACtD,MAAM,IAAI,MAAM,KAAK,OAAO,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;CAC1E,OAAO,GAAG,UAAU,MAAM,GAAG,CAAC,EAAE,GAAG,UAAU,MAAM,GAAG,EAAE,EAAE,GAAG,EAAE,MAAM,GAAG,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,EAAE;AAC9G;;;;;;;;;;;AAYA,MAAa,YAAY,WAA2B,aAAa,QAAA,EAAuB;AAExF,MAAa,YAAY,KAAa,SAAiB;CACrD,MAAM,kBAAkB,KAAK,KAAK,OAAO,CAAC;CAE1C,OAD6B,IAAI,SAAS,EAChB,CAAC,CAAC,SAAS,iBAAiB,GAAG;AAC3D;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,gBAAgB,KAAa,SAAyB;CAEjE,OAAO,SADU,KAAK,IAAI,GAAG,IAAI,IAAI,IACV,KAAK,IAAI;AACtC;AAEA,MAAa,gBAAgB,KAAa,SAAyB;CAGjE,OAFiB,KAAK,IAAI,GAAG,IAAI,IAAI,IACzB,SAAS,KAAK,EACN;AACtB;;;;;;;;;;;;;;;;AC/GA,MAAa,aAAa,UAA0B;CAClD,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,KAAK,SAAS,KAAA,IACpD,MAAM,IAAI,YACR,YACA,iEAAqF,MAAM,EAC7F;CAEF,OAAO,aAAa,OAAA,EAA0B;AAChD;;;;;;;;AASA,MAAa,SAAS,IAAY,WAChC,IAAI,SAAe,SAAS,WAAW;CACrC,IAAI,QAAQ,SAAS;EACnB,OAAO,OAAO,MAAM;EACpB;CACF;CACA,MAAM,QAAQ,WAAW,SAAS,EAAE;CACpC,QAAQ,iBACN,eACM;EACJ,aAAa,KAAK;EAClB,OAAO,OAAO,MAAM;CACtB,GAMA,EAAE,MAAM,KAAK,CACf;AACF,CAAC"}
|
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
import { t as decodeJsonBytes } from "./bytes-BXdamO3L.js";
|
|
2
|
-
import { t as loadAppConfig } from "./config-
|
|
3
|
-
import { n as parseBucketUri, t as defineBaerlySubcommand } from "./subcommand-DZcHcsYp.js";
|
|
2
|
+
import { r as parseBucketUri, t as loadAppConfig } from "./config-1tv0-Yzm.js";
|
|
4
3
|
import { i as isJsonMode, o as BaerlyError, r as emitSuccess } from "./baerly.js";
|
|
5
|
-
|
|
6
|
-
const SAMPLE_SIZE = 120;
|
|
4
|
+
import { a as TENANT_ARG, i as JSON_ARG, s as defineBaerlySubcommand, t as APP_ARG } from "./subcommand-DoDA-K7d.js";
|
|
7
5
|
/** Build the canonical `current.json` key for one collection. */
|
|
8
6
|
const currentJsonKeyFor = (app, tenant, collection) => `app/${app}/tenant/${tenant}/manifests/${collection}/current.json`;
|
|
9
7
|
/** Derive the `collectionPrefix` (everything before `/current.json`). */
|
|
@@ -103,7 +101,7 @@ const readCommitTsBatched = async (storage, keys) => {
|
|
|
103
101
|
* root). Threaded through by `baerly inspect`.
|
|
104
102
|
*/
|
|
105
103
|
const estimateWritesPerMin = async (storage, app, tenant, collection, opts = {}) => {
|
|
106
|
-
const sampleSize = opts.sampleSize ??
|
|
104
|
+
const sampleSize = opts.sampleSize ?? 120;
|
|
107
105
|
const logPrefix = `${`${opts.keyPrefix ?? ""}${collectionPrefixOf(currentJsonKeyFor(app, tenant, collection))}`}/log/`;
|
|
108
106
|
let allKeys;
|
|
109
107
|
try {
|
|
@@ -251,22 +249,9 @@ const USAGE_ARGS = {
|
|
|
251
249
|
description: "Override `baerly.config.ts:target`. One of \"cloudflare\" | \"node\".",
|
|
252
250
|
valueHint: "target"
|
|
253
251
|
},
|
|
254
|
-
app:
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
description: "Application name segment (defaults to baerly.config.ts).",
|
|
258
|
-
valueHint: "app"
|
|
259
|
-
},
|
|
260
|
-
tenant: {
|
|
261
|
-
type: "string",
|
|
262
|
-
required: false,
|
|
263
|
-
description: "Tenant name segment (defaults to baerly.config.ts).",
|
|
264
|
-
valueHint: "tenant"
|
|
265
|
-
},
|
|
266
|
-
json: {
|
|
267
|
-
type: "boolean",
|
|
268
|
-
description: "Emit a structured JSON envelope to stdout (success) or stderr (error)"
|
|
269
|
-
}
|
|
252
|
+
app: APP_ARG,
|
|
253
|
+
tenant: TENANT_ARG,
|
|
254
|
+
json: JSON_ARG
|
|
270
255
|
};
|
|
271
256
|
const SEVERITY_GLYPH = {
|
|
272
257
|
ok: "✓",
|
|
@@ -336,4 +321,4 @@ bundle.run;
|
|
|
336
321
|
//#endregion
|
|
337
322
|
export { estimateWritesPerMin, usageCmd };
|
|
338
323
|
|
|
339
|
-
//# sourceMappingURL=usage-
|
|
324
|
+
//# sourceMappingURL=usage-DBV1eQHC.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"usage-DBV1eQHC.js","names":[],"sources":["../packages/cli/src/admin/usage.ts"],"sourcesContent":["/**\n * `baerly admin usage` — all-collection writes/min health check.\n *\n * Reads the most recent `SAMPLE_SIZE` log entries for every collection\n * under `app/<app>/tenant/<tenant>/manifests/`, compares the spread of\n * their embedded `commit_ts` timestamps against the M-size operating\n * ceiling (~30 writes/min/collection — see `M_SIZE_WRITES_PER_MIN_PER_COLLECTION`\n * below and `docs/about/thesis.md`), and prints one finding per\n * collection — `info` when well under the ceiling, `warning` when\n * approaching or exceeding it.\n *\n * The ~100 collections/tenant fan-out guideline is bench-grounded:\n * `admin usage` costs ≈ N × (1 LIST + up to 120 GETs per collection)\n * — strictly linear. See `docs/spec/attachments/collection-fanout-baseline.json`\n * (`pnpm bench:collection-fanout`). Neither the ~100 figure nor the\n * >10 GB/tenant storage line is a code constant here; both are cost\n * signals documented in `docs/about/cost-model.md`.\n *\n * Distinct from `baerly cost` (the per-table, $/month projection):\n * `cost` is a developer-facing trajectory for one table, `usage` is an\n * operator-facing M-size graduation health check across all\n * collections.\n *\n * The pure-storage half — {@link estimateWritesPerMin},\n * {@link discoverCollections}, {@link runUsageScan} — takes a\n * `Storage` handle from the caller and never reads `process.env`.\n * The CLI wrapper at the bottom of the file constructs that\n * `Storage` from `--bucket=<uri>` via `parseBucketUri`. The\n * Cloudflare target short-circuits with an info-level \"not yet\n * wired\" finding pending the follow-up work in\n * `docs/followups/agent-friendliness.md` entry 10.\n *\n * Why GET each entry instead of relying on list-time\n * `Last-Modified`: `MemoryStorage` (the test backend) intentionally\n * does NOT surface `lastModified` on `list()`, and the\n * cross-backend story stays uniform if we always read `commit_ts`\n * from the `LogEntry` body. Sample size is bounded (`SAMPLE_SIZE`\n * GETs per collection), so the cost is acceptable for an opt-in\n * operator command.\n *\n * @see docs/about/thesis.md — M-size ceiling rationale.\n * @see docs/spec/log-entry-shape.md — `LogEntry.commit_ts` contract.\n * @see packages/server/src/compactor.ts:224-225 — `collectionPrefix` /\n * `collectionName` derivation pattern reused here.\n */\n\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError, decodeJsonBytes, type LogEntry, type Storage } from \"@baerly/protocol\";\nimport { parseBucketUri } from \"../bucket-uri.ts\";\nimport { loadAppConfig } from \"../config.ts\";\nimport { emitSuccess, isJsonMode } from \"../output.ts\";\nimport { APP_ARG, defineBaerlySubcommand, JSON_ARG, TENANT_ARG } from \"../subcommand.ts\";\n\n/**\n * Verdict-shaped finding the scan emits. Mirrors the\n * `severity / check / message / fix?` shape that `baerly doctor` uses,\n * but doesn't depend on `doctor/cloudflare.ts` — `admin usage` runs\n * outside the doctor surface.\n */\nexport interface UsageFinding {\n readonly severity: \"ok\" | \"info\" | \"warning\" | \"error\";\n readonly check: string;\n readonly message: string;\n readonly fix?: string;\n}\n\n/**\n * M-size writes-per-minute-per-collection ceiling from\n * `docs/about/thesis.md`. Crossing this with sustained traffic\n * means operators should consider graduating the workload to a\n * graduated store via `baerly export --target=postgres|sqlite|d1`.\n */\nexport const M_SIZE_WRITES_PER_MIN_PER_COLLECTION = 30;\n\n/** Number of trailing log entries the estimator reads per collection. */\nexport const SAMPLE_SIZE = 120;\n\n/** Per-collection verdict surfaced by {@link estimateWritesPerMin}. */\nexport interface UsageVerdict {\n /** Collection name (matches `LogEntry.collection`). */\n readonly collection: string;\n /**\n * Writes per minute estimated over the sample window. `NaN` when\n * fewer than 2 entries were observed (no defensible rate).\n */\n readonly writesPerMin: number;\n /** Percent of {@link M_SIZE_WRITES_PER_MIN_PER_COLLECTION}; `NaN` propagates. */\n readonly percentOfCeiling: number;\n /**\n * Severity scaled by distance to ceiling:\n * - `< 50%` → `\"info\"`\n * - `50–99%` → `\"warning\"` (\"approaching ceiling\")\n * - `≥ 100%` → `\"warning\"` (\"exceeds ceiling — consider export\")\n *\n * Severity `warning` never bumps the doctor's exit code above 0\n * (operators can still deploy / continue while approaching the\n * ceiling).\n */\n readonly severity: \"info\" | \"warning\";\n /** Human-readable one-liner suitable for a {@link UsageFinding}. */\n readonly message: string;\n /** Empty when no remediation is meaningful (under 50%). */\n readonly fix: string;\n}\n\n/** Build the canonical `current.json` key for one collection. */\nexport const currentJsonKeyFor = (app: string, tenant: string, collection: string): string =>\n `app/${app}/tenant/${tenant}/manifests/${collection}/current.json`;\n\n/** Derive the `collectionPrefix` (everything before `/current.json`). */\nexport const collectionPrefixOf = (currentJsonKey: string): string =>\n currentJsonKey.slice(0, currentJsonKey.lastIndexOf(\"/\"));\n\n/**\n * List every log key under `${collectionPrefix}/log/` for one collection.\n * Returns the keys in **chronological order** (oldest seq first).\n *\n * The on-bucket key shape is `<collectionPrefix>/log/<seq>.json` where\n * `<seq>` is a base-10 integer minted by `Writer`. Lex-ascending\n * key order disagrees with numeric seq order past seq=9 (`log/10.json`\n * sorts before `log/2.json`), so we parse the trailing integer out of\n * each key and sort numerically.\n *\n * Caller is expected to slice the trailing N entries — the writes/min\n * estimator only needs the most recent sample.\n */\n// Parse the `<seq>` integer from a `<logPrefix>/<seq>.json` key. Returns\n// `NaN` when the basename isn't a finite integer (the caller filters\n// those out before sorting). Hoisted out of {@link listLogKeysSortedBySeq}\n// so a function instance isn't allocated per list entry.\nconst seqOfLogKey = (key: string): number => {\n const slash = key.lastIndexOf(\"/\");\n const dot = key.lastIndexOf(\".json\");\n if (slash === -1 || dot === -1 || dot <= slash) {\n return Number.NaN;\n }\n const seqStr = key.slice(slash + 1, dot);\n const n = Number.parseInt(seqStr, 10);\n return Number.isFinite(n) ? n : Number.NaN;\n};\n\nconst listLogKeysSortedBySeq = async (\n storage: Storage,\n logPrefix: string,\n): Promise<readonly string[]> => {\n const keys: string[] = [];\n for await (const entry of storage.list(logPrefix)) {\n keys.push(entry.key);\n }\n return keys\n .filter((k) => Number.isFinite(seqOfLogKey(k)))\n .toSorted((a, b) => seqOfLogKey(a) - seqOfLogKey(b));\n};\n\n/**\n * Fetch a `LogEntry` body at `key`, returning its `commit_ts` parsed\n * to epoch-ms. Returns `null` when the object is missing (a peer may\n * have GC'd it between list and get); throws `BaerlyError` on a\n * malformed body so the caller can downgrade the whole collection's\n * scan to an error-level finding.\n */\nconst readCommitTsMs = async (storage: Storage, key: string): Promise<number | null> => {\n const got = await storage.get(key);\n if (got === null) {\n return null;\n }\n let parsed: LogEntry;\n try {\n parsed = decodeJsonBytes<LogEntry>(got.body);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `usage scan: log entry at ${key} is not valid JSON`,\n error,\n );\n }\n if (typeof parsed.commit_ts !== \"string\") {\n throw new BaerlyError(\"InvalidResponse\", `usage scan: log entry at ${key} missing commit_ts`);\n }\n const ms = Date.parse(parsed.commit_ts);\n if (!Number.isFinite(ms)) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `usage scan: log entry at ${key} has unparseable commit_ts ${JSON.stringify(parsed.commit_ts)}`,\n );\n }\n return ms;\n};\n\n/**\n * Read each key with bounded concurrency. Mirrors the pattern in\n * `packages/server/src/log-walk.ts` — we cap parallelism to keep a\n * single doctor pass from blowing through the storage backend's\n * connection budget. Keeps a small constant rather than reaching for\n * `MAX_PARALLEL_LOG_READS` (8) so the doctor command is gentle by\n * default.\n */\nconst PARALLEL_READS = 8;\n\nconst readCommitTsBatched = async (\n storage: Storage,\n keys: readonly string[],\n): Promise<readonly (number | null)[]> => {\n const out: (number | null)[] = Array.from({ length: keys.length });\n for (let i = 0; i < keys.length; i += PARALLEL_READS) {\n const chunk = keys.slice(i, i + PARALLEL_READS);\n const results = await Promise.all(chunk.map((k) => readCommitTsMs(storage, k)));\n for (let j = 0; j < results.length; j++) {\n out[i + j] = results[j] ?? null;\n }\n }\n return out;\n};\n\n/**\n * Estimate writes/min for one collection.\n *\n * Reads the last `sampleSize` log entries (default `SAMPLE_SIZE`)\n * for `<app>/<tenant>/<collection>`, computes\n * `(observedEntries - 1) / ((maxTs - minTs) / 60_000)`\n * minutes, compares against {@link M_SIZE_WRITES_PER_MIN_PER_COLLECTION},\n * and returns a {@link UsageVerdict}.\n *\n * Edge cases:\n * - Fewer than 2 entries observable → `writesPerMin = NaN`,\n * severity `info`, no fix. Operators see \"not enough log\n * entries to estimate.\"\n * - All entries share the same `commit_ts` (e.g. a tight batch) →\n * the denominator is clamped to 1 second so the rate degrades\n * gracefully instead of dividing by zero.\n *\n * @throws BaerlyError code=\"NetworkError\" — wrapped storage failure\n * while listing. The caller (Node doctor backend) catches and\n * converts to a warning-severity finding so one bad collection\n * doesn't fail the whole scan.\n * @throws BaerlyError code=\"InvalidResponse\" — a sampled log entry\n * body is malformed; same caller treatment.\n * @param opts.keyPrefix - When the bucket has a non-empty key prefix\n * (e.g. `s3://my-bucket/some/prefix`), pass it here (ending in\n * `/`). Defaults to `\"\"`. Necessary for prefixed-bucket\n * correctness; ignored by `runUsageScan` (Node doctor scans the\n * root). Threaded through by `baerly inspect`.\n */\nexport const estimateWritesPerMin = async (\n storage: Storage,\n app: string,\n tenant: string,\n collection: string,\n opts: { readonly sampleSize?: number; readonly keyPrefix?: string } = {},\n): Promise<UsageVerdict> => {\n const sampleSize = opts.sampleSize ?? SAMPLE_SIZE;\n const keyPrefix = opts.keyPrefix ?? \"\";\n const collectionPrefix = `${keyPrefix}${collectionPrefixOf(currentJsonKeyFor(app, tenant, collection))}`;\n const logPrefix = `${collectionPrefix}/log/`;\n\n let allKeys: readonly string[];\n try {\n allKeys = await listLogKeysSortedBySeq(storage, logPrefix);\n } catch (error) {\n if (error instanceof BaerlyError) {\n throw error;\n }\n throw new BaerlyError(\n \"NetworkError\",\n `usage scan: list ${logPrefix} failed: ${(error as Error).message}`,\n error,\n );\n }\n const sample = allKeys.slice(Math.max(0, allKeys.length - sampleSize));\n if (sample.length < 2) {\n return {\n collection,\n writesPerMin: Number.NaN,\n percentOfCeiling: Number.NaN,\n severity: \"info\",\n message: `collection ${collection}: not enough log entries to estimate (saw ${sample.length}, need >= 2)`,\n fix: \"\",\n };\n }\n const commitTs = await readCommitTsBatched(storage, sample);\n const timestamps = commitTs.filter((v): v is number => v !== null);\n if (timestamps.length < 2) {\n return {\n collection,\n writesPerMin: Number.NaN,\n percentOfCeiling: Number.NaN,\n severity: \"info\",\n message: `collection ${collection}: not enough readable log entries to estimate (resolved ${timestamps.length}, need >= 2)`,\n fix: \"\",\n };\n }\n let minTs = timestamps[0]!;\n let maxTs = timestamps[0]!;\n for (const t of timestamps) {\n if (t < minTs) {\n minTs = t;\n }\n if (t > maxTs) {\n maxTs = t;\n }\n }\n // Guard the denominator: a tight batch may produce identical\n // commit_ts values; degrade to a one-second window so we never\n // divide by zero.\n const minutes = Math.max(1 / 60, (maxTs - minTs) / 60_000);\n const writesPerMin = (timestamps.length - 1) / minutes;\n const pct = (writesPerMin / M_SIZE_WRITES_PER_MIN_PER_COLLECTION) * 100;\n\n let severity: \"info\" | \"warning\" = \"info\";\n let message = `collection ${collection}: ${writesPerMin.toFixed(1)} writes/min (~${pct.toFixed(0)}% of M-size ceiling, sampled ${timestamps.length} entries)`;\n let fix = \"\";\n if (pct >= 100) {\n severity = \"warning\";\n message += \" — exceeds the M-size ceiling.\";\n fix = `consider graduating: \\`baerly export --target=postgres|sqlite|d1 --bucket=<bucket> --app=${app} --tenant=${tenant} --collection=${collection}\\``;\n } else if (pct >= 50) {\n severity = \"warning\";\n message += \" — approaching the M-size ceiling.\";\n fix = \"monitor; plan graduation via `baerly export --target=postgres|sqlite|d1`\";\n }\n return { collection, writesPerMin, percentOfCeiling: pct, severity, message, fix };\n};\n\n/**\n * Discover the set of collections under `<app>/<tenant>/manifests/`\n * by listing the bucket. Each collection is the immediate\n * subdirectory name (the segment after `manifests/` and before the\n * next `/`).\n *\n * Returns a deduped, lex-sorted list. An empty list means there are\n * no committed collections under this app/tenant yet — the caller\n * surfaces a single info finding rather than scanning per-collection.\n *\n * @throws BaerlyError code=\"NetworkError\" — wrapped list failure.\n */\nexport const discoverCollections = async (\n storage: Storage,\n app: string,\n tenant: string,\n): Promise<readonly string[]> => {\n const prefix = `app/${app}/tenant/${tenant}/manifests/`;\n const names = new Set<string>();\n try {\n for await (const entry of storage.list(prefix)) {\n const rest = entry.key.slice(prefix.length);\n const slash = rest.indexOf(\"/\");\n const name = slash === -1 ? rest : rest.slice(0, slash);\n if (name.length > 0) {\n names.add(name);\n }\n }\n } catch (error) {\n if (error instanceof BaerlyError) {\n throw error;\n }\n throw new BaerlyError(\n \"NetworkError\",\n `usage scan: list ${prefix} failed: ${(error as Error).message}`,\n error,\n );\n }\n return [...names].toSorted();\n};\n\n/**\n * Orchestrate the usage scan against a caller-supplied\n * {@link Storage}. The CLI wrapper handles bucket-URI construction;\n * this helper runs the shared discover → per-collection-estimate →\n * finding-push loop.\n *\n * Mutates `findings` in place. Returns when the scan completes\n * (success or per-collection failure all surface as findings). The\n * outer CLI exit code is driven by the rollup over all findings.\n *\n * Errors land as warnings (not errors) so one bad collection doesn't\n * abort the whole scan and so the operator stays deployable while a\n * single object is being investigated.\n */\nexport const runUsageScan = async (\n context: { readonly app: string; readonly tenant: string },\n storage: Storage,\n findings: UsageFinding[],\n): Promise<void> => {\n let collections: readonly string[];\n try {\n collections = await discoverCollections(storage, context.app, context.tenant);\n } catch (error) {\n findings.push({\n severity: \"warning\",\n check: \"usage-discover\",\n message: `could not enumerate collections under app/${context.app}/tenant/${context.tenant}/manifests/: ${error instanceof BaerlyError ? error.message : (error as Error).message}`,\n });\n return;\n }\n if (collections.length === 0) {\n findings.push({\n severity: \"info\",\n check: \"usage-empty\",\n message: `no collections found under app/${context.app}/tenant/${context.tenant}/manifests/; nothing to scan.`,\n });\n return;\n }\n for (const c of collections) {\n try {\n const verdict = await estimateWritesPerMin(storage, context.app, context.tenant, c);\n findings.push({\n severity: verdict.severity,\n check: `usage-${c}`,\n message: verdict.message,\n ...(verdict.fix !== \"\" && { fix: verdict.fix }),\n });\n } catch (error) {\n findings.push({\n severity: \"warning\",\n check: `usage-${c}`,\n message: `failed to estimate writes/min for ${c}: ${error instanceof BaerlyError ? error.message : (error as Error).message}`,\n });\n }\n }\n};\n\n// ---------------------------------------------------------------------------\n// CLI surface — `baerly admin usage`\n// ---------------------------------------------------------------------------\n\nconst USAGE_ARGS = {\n bucket: {\n type: \"string\",\n required: false,\n description:\n \"Bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>). Required for --target=node.\",\n valueHint: \"bucket-uri\",\n },\n target: {\n type: \"string\",\n required: false,\n description: 'Override `baerly.config.ts:target`. One of \"cloudflare\" | \"node\".',\n valueHint: \"target\",\n },\n app: APP_ARG,\n tenant: TENANT_ARG,\n json: JSON_ARG,\n} as const satisfies ArgsDef;\n\nconst SEVERITY_GLYPH: Record<UsageFinding[\"severity\"], string> = {\n ok: \"✓\",\n info: \"•\",\n warning: \"⚠\",\n error: \"✗\",\n};\n\nconst renderText = (target: string, findings: readonly UsageFinding[]): string => {\n const lines: string[] = [];\n lines.push(`baerly admin usage --target=${target}`);\n lines.push(\"\");\n for (const f of findings) {\n lines.push(` ${SEVERITY_GLYPH[f.severity]} ${f.message}`);\n if (f.fix !== undefined && f.fix !== \"\") {\n lines.push(` fix: ${f.fix}`);\n }\n }\n let warnings = 0;\n let errors = 0;\n for (const f of findings) {\n if (f.severity === \"warning\") {\n warnings++;\n } else if (f.severity === \"error\") {\n errors++;\n }\n }\n lines.push(\"\");\n lines.push(\n `Status: ${errors} error${errors === 1 ? \"\" : \"s\"}, ${warnings} warning${warnings === 1 ? \"\" : \"s\"}.`,\n );\n return lines.join(\"\\n\") + \"\\n\";\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"admin.usage\",\n meta: {\n description:\n \"All-collection writes/min health check; flags collections approaching the M-size ceiling.\",\n },\n args: USAGE_ARGS,\n handler: async (args, ctx) => {\n // Avoid loading the config when --target is explicit — the CLI\n // should still work outside an app directory if the operator\n // pins target + app + tenant on the flags.\n const target = args.target ?? (await loadAppConfig().then((c) => c.target));\n if (target !== \"cloudflare\" && target !== \"node\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin usage: unsupported --target ${JSON.stringify(target)} (one of \"cloudflare\" | \"node\")`,\n );\n }\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n\n const findings: UsageFinding[] = [];\n\n if (target === \"cloudflare\") {\n // The CLI runs in Node and can't reach a Workerd-side R2 binding\n // from `--bucket=<uri>`; full CF wiring is a follow-up — see\n // `docs/followups/agent-friendliness.md` entry 10.\n findings.push({\n severity: \"info\",\n check: \"usage.cloudflare\",\n message:\n \"baerly admin usage is not yet wired for --target=cloudflare. See docs/followups/agent-friendliness.md entry 10.\",\n });\n } else {\n if (args.bucket === undefined || args.bucket.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"baerly admin usage: --bucket=<uri> is required for --target=node\",\n );\n }\n const parsed = await parseBucketUri(args.bucket);\n await runUsageScan({ app, tenant }, parsed.storage, findings);\n }\n\n if (isJsonMode()) {\n emitSuccess({\n command: \"admin.usage\",\n status: \"ok\",\n target,\n findings: findings.map((f) => ({\n severity: f.severity,\n check: f.check,\n message: f.message,\n ...(f.fix !== undefined && f.fix !== \"\" && { fix: f.fix }),\n })),\n });\n } else {\n process.stdout.write(renderText(target, findings));\n }\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly admin usage`. */\nexport const usageCmd = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runUsage = bundle.run;\n"],"mappings":";;;;;AA0GA,MAAa,qBAAqB,KAAa,QAAgB,eAC7D,OAAO,IAAI,UAAU,OAAO,aAAa,WAAW;;AAGtD,MAAa,sBAAsB,mBACjC,eAAe,MAAM,GAAG,eAAe,YAAY,GAAG,CAAC;;;;;;;;;;;;;;AAmBzD,MAAM,eAAe,QAAwB;CAC3C,MAAM,QAAQ,IAAI,YAAY,GAAG;CACjC,MAAM,MAAM,IAAI,YAAY,OAAO;CACnC,IAAI,UAAU,MAAM,QAAQ,MAAM,OAAO,OACvC,OAAO;CAET,MAAM,SAAS,IAAI,MAAM,QAAQ,GAAG,GAAG;CACvC,MAAM,IAAI,OAAO,SAAS,QAAQ,EAAE;CACpC,OAAO,OAAO,SAAS,CAAC,IAAI,IAAI;AAClC;AAEA,MAAM,yBAAyB,OAC7B,SACA,cAC+B;CAC/B,MAAM,OAAiB,CAAC;CACxB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OAAO,MAAM,KAAK,IAAI,IAAI;AAC5B;AAEA,MAAM,SAAS,uBAAuB;CACpC,MAAM;CACN,MAAM,EACJ,aACE,4FACJ;CACA,MAAM;CACN,SAAS,OAAO,MAAM,QAAQ;EAI5B,MAAM,SAAS,KAAK,UAAW,MAAM,cAAc,CAAC,CAAC,MAAM,MAAM,EAAE,MAAM;EACzE,IAAI,WAAW,gBAAgB,WAAW,QACxC,MAAM,IAAI,YACR,iBACA,4CAA4C,KAAK,UAAU,MAAM,EAAE,gCACrE;EAEF,MAAM,EAAE,KAAK,WAAW,MAAM,IAAI,iBAAiB;GAAE,KAAK,KAAK;GAAK,QAAQ,KAAK;EAAO,CAAC;EAEzF,MAAM,WAA2B,CAAC;EAElC,IAAI,WAAW,cAIb,SAAS,KAAK;GACZ,UAAU;GACV,OAAO;GACP,SACE;EACJ,CAAC;OACI;GACL,IAAI,KAAK,WAAW,KAAA,KAAa,KAAK,OAAO,WAAW,GACtD,MAAM,IAAI,YACR,iBACA,kEACF;GAEF,MAAM,SAAS,MAAM,eAAe,KAAK,MAAM;GAC/C,MAAM,aAAa;IAAE;IAAK;GAAO,GAAG,OAAO,SAAS,QAAQ;EAC9D;EAEA,IAAI,WAAW,GACb,YAAY;GACV,SAAS;GACT,QAAQ;GACR;GACA,UAAU,SAAS,KAAK,OAAO;IAC7B,UAAU,EAAE;IACZ,OAAO,EAAE;IACT,SAAS,EAAE;IACX,GAAI,EAAE,QAAQ,KAAA,KAAa,EAAE,QAAQ,MAAM,EAAE,KAAK,EAAE,IAAI;GAC1D,EAAE;EACJ,CAAC;OAED,QAAQ,OAAO,MAAM,WAAW,QAAQ,QAAQ,CAAC;EAEnD,OAAO;CACT;AACF,CAAC;;AAGD,MAAa,WAAW,OAAO;AAOP,OAAO"}
|
|
@@ -1,54 +1,4 @@
|
|
|
1
1
|
import { o as BaerlyError } from "./baerly.js";
|
|
2
|
-
//#region ../protocol/src/query/_internals.ts
|
|
3
|
-
/** @internal Same primitive type for comparison purposes. */
|
|
4
|
-
const sameComparableType = (a, b) => typeof a === "string" && typeof b === "string" || typeof a === "number" && typeof b === "number";
|
|
5
|
-
/**
|
|
6
|
-
* @internal Returns negative / zero / positive for a<b / a==b / a>b.
|
|
7
|
-
*/
|
|
8
|
-
const compareScalar = (a, b) => {
|
|
9
|
-
if (typeof a === "number" && typeof b === "number") return a - b;
|
|
10
|
-
if (typeof a === "string" && typeof b === "string") {
|
|
11
|
-
if (a < b) return -1;
|
|
12
|
-
if (a > b) return 1;
|
|
13
|
-
return 0;
|
|
14
|
-
}
|
|
15
|
-
return 0;
|
|
16
|
-
};
|
|
17
|
-
/** @internal Render a predicate path for use in error messages. */
|
|
18
|
-
const formatPath = (path) => path.length === 0 ? "<root>" : path.map((p) => JSON.stringify(p)).join(".");
|
|
19
|
-
/**
|
|
20
|
-
* Recursive structural equality for `DocumentValue` values. Lifted to
|
|
21
|
-
* `export` so the filtered-index implication checker (in
|
|
22
|
-
* `@baerly/server`'s query planner) and other callers can reuse the
|
|
23
|
-
* same comparison rule the validator + merger already trust. Two
|
|
24
|
-
* values `a` and `b` are equal iff:
|
|
25
|
-
*
|
|
26
|
-
* - they are reference-equal (covers primitives and object identity);
|
|
27
|
-
* - or they are both non-`null` objects with the same key set, and
|
|
28
|
-
* every value pair is recursively equal.
|
|
29
|
-
*
|
|
30
|
-
* Arrays are out-of-band for `DocumentValue`; this function rejects
|
|
31
|
-
* them implicitly via the same key-set walk (an array reads as an
|
|
32
|
-
* object with numeric-string keys plus a `length` exposure that
|
|
33
|
-
* `Object.keys` happens to skip — defensive callers should still gate
|
|
34
|
-
* with `Array.isArray` first).
|
|
35
|
-
*/
|
|
36
|
-
const deepEqualDocumentValue = (a, b) => {
|
|
37
|
-
if (a === b) return true;
|
|
38
|
-
if (typeof a !== "object" || typeof b !== "object") return false;
|
|
39
|
-
const aKeys = Object.keys(a);
|
|
40
|
-
const bKeys = Object.keys(b);
|
|
41
|
-
if (aKeys.length !== bKeys.length) return false;
|
|
42
|
-
for (const key of aKeys) {
|
|
43
|
-
if (!(key in b)) return false;
|
|
44
|
-
const aSub = a[key];
|
|
45
|
-
const bSub = b[key];
|
|
46
|
-
if (aSub === void 0 || bSub === void 0) return false;
|
|
47
|
-
if (!deepEqualDocumentValue(aSub, bSub)) return false;
|
|
48
|
-
}
|
|
49
|
-
return true;
|
|
50
|
-
};
|
|
51
|
-
//#endregion
|
|
52
2
|
//#region ../protocol/src/query/matches.ts
|
|
53
3
|
/**
|
|
54
4
|
* Evaluate a validated wire-form predicate against a `JSONObject`
|
|
@@ -131,6 +81,56 @@ const compareLT = (actual, bound, inclusive) => {
|
|
|
131
81
|
return false;
|
|
132
82
|
};
|
|
133
83
|
//#endregion
|
|
84
|
+
//#region ../protocol/src/query/_internals.ts
|
|
85
|
+
/** @internal Same primitive type for comparison purposes. */
|
|
86
|
+
const sameComparableType = (a, b) => typeof a === "string" && typeof b === "string" || typeof a === "number" && typeof b === "number";
|
|
87
|
+
/**
|
|
88
|
+
* @internal Returns negative / zero / positive for a<b / a==b / a>b.
|
|
89
|
+
*/
|
|
90
|
+
const compareScalar = (a, b) => {
|
|
91
|
+
if (typeof a === "number" && typeof b === "number") return a - b;
|
|
92
|
+
if (typeof a === "string" && typeof b === "string") {
|
|
93
|
+
if (a < b) return -1;
|
|
94
|
+
if (a > b) return 1;
|
|
95
|
+
return 0;
|
|
96
|
+
}
|
|
97
|
+
return 0;
|
|
98
|
+
};
|
|
99
|
+
/** @internal Render a predicate path for use in error messages. */
|
|
100
|
+
const formatPath = (path) => path.length === 0 ? "<root>" : path.map((p) => JSON.stringify(p)).join(".");
|
|
101
|
+
/**
|
|
102
|
+
* Recursive structural equality for `DocumentValue` values. Lifted to
|
|
103
|
+
* `export` so the filtered-index implication checker (in
|
|
104
|
+
* `@baerly/server`'s query planner) and other callers can reuse the
|
|
105
|
+
* same comparison rule the validator + merger already trust. Two
|
|
106
|
+
* values `a` and `b` are equal iff:
|
|
107
|
+
*
|
|
108
|
+
* - they are reference-equal (covers primitives and object identity);
|
|
109
|
+
* - or they are both non-`null` objects with the same key set, and
|
|
110
|
+
* every value pair is recursively equal.
|
|
111
|
+
*
|
|
112
|
+
* Arrays are out-of-band for `DocumentValue`; this function rejects
|
|
113
|
+
* them implicitly via the same key-set walk (an array reads as an
|
|
114
|
+
* object with numeric-string keys plus a `length` exposure that
|
|
115
|
+
* `Object.keys` happens to skip — defensive callers should still gate
|
|
116
|
+
* with `Array.isArray` first).
|
|
117
|
+
*/
|
|
118
|
+
const deepEqualDocumentValue = (a, b) => {
|
|
119
|
+
if (a === b) return true;
|
|
120
|
+
if (typeof a !== "object" || typeof b !== "object") return false;
|
|
121
|
+
const aKeys = Object.keys(a);
|
|
122
|
+
const bKeys = Object.keys(b);
|
|
123
|
+
if (aKeys.length !== bKeys.length) return false;
|
|
124
|
+
for (const key of aKeys) {
|
|
125
|
+
if (!(key in b)) return false;
|
|
126
|
+
const aSub = a[key];
|
|
127
|
+
const bSub = b[key];
|
|
128
|
+
if (aSub === void 0 || bSub === void 0) return false;
|
|
129
|
+
if (!deepEqualDocumentValue(aSub, bSub)) return false;
|
|
130
|
+
}
|
|
131
|
+
return true;
|
|
132
|
+
};
|
|
133
|
+
//#endregion
|
|
134
134
|
//#region ../protocol/src/query/satisfiable.ts
|
|
135
135
|
/**
|
|
136
136
|
* Per-field satisfiability check for a {@link PredicateWire}. Groups
|
|
@@ -374,4 +374,4 @@ const validateRangeBound = (value, field, clauseIndex) => {
|
|
|
374
374
|
//#endregion
|
|
375
375
|
export { matchesWire as n, validateWire as t };
|
|
376
376
|
|
|
377
|
-
//# sourceMappingURL=validate-
|
|
377
|
+
//# sourceMappingURL=validate-DtljsCh1.js.map
|