@gusto/baerly-storage 0.1.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/README.md +97 -0
- package/dist/API.md +850 -0
- package/dist/app-config-Cb5dO2s9.d.ts +480 -0
- package/dist/app-config.d.ts +2 -0
- package/dist/app-config.js +8 -0
- package/dist/app-config.js.map +1 -0
- package/dist/auth.d.ts +237 -0
- package/dist/auth.js +1335 -0
- package/dist/auth.js.map +1 -0
- package/dist/baerly.js +761 -0
- package/dist/baerly.js.map +1 -0
- package/dist/bucket-uri-BrDEYvzy.js +4922 -0
- package/dist/bucket-uri-BrDEYvzy.js.map +1 -0
- package/dist/chunk-EAsCxrDo.js +14 -0
- package/dist/client-BLf3Ae5s.d.ts +233 -0
- package/dist/client-react.d.ts +131 -0
- package/dist/client-react.js +559 -0
- package/dist/client-react.js.map +1 -0
- package/dist/client.d.ts +4 -0
- package/dist/client.js +160 -0
- package/dist/client.js.map +1 -0
- package/dist/cloudflare-CINJPKCW.js +911 -0
- package/dist/cloudflare-CINJPKCW.js.map +1 -0
- package/dist/cloudflare.d.ts +211 -0
- package/dist/cloudflare.js +445 -0
- package/dist/cloudflare.js.map +1 -0
- package/dist/config-Bsg8wgwo.js +198 -0
- package/dist/config-Bsg8wgwo.js.map +1 -0
- package/dist/context-Oj7ffwD-.js +187 -0
- package/dist/context-Oj7ffwD-.js.map +1 -0
- package/dist/cost-B1WiZxlf.js +203 -0
- package/dist/cost-B1WiZxlf.js.map +1 -0
- package/dist/current-json-BkatBzF7.js +252 -0
- package/dist/current-json-BkatBzF7.js.map +1 -0
- package/dist/db-D62JguBc.d.ts +336 -0
- package/dist/deploy-BB-wqbhf.js +83 -0
- package/dist/deploy-BB-wqbhf.js.map +1 -0
- package/dist/dev-banner-CWHIk8tH.d.ts +26 -0
- package/dist/dev-vite.d.ts +146 -0
- package/dist/dev-vite.js +223 -0
- package/dist/dev-vite.js.map +1 -0
- package/dist/dev.d.ts +3 -0
- package/dist/dev.js +2 -0
- package/dist/doctor-B8h9GCN9.js +331 -0
- package/dist/doctor-B8h9GCN9.js.map +1 -0
- package/dist/dump-BHo_sIMZ.js +116 -0
- package/dist/dump-BHo_sIMZ.js.map +1 -0
- package/dist/errors-DOdL95kK.js +58 -0
- package/dist/errors-DOdL95kK.js.map +1 -0
- package/dist/export-Dz2PZKSR.js +423 -0
- package/dist/export-Dz2PZKSR.js.map +1 -0
- package/dist/fsck-DEz9lyCy.js +293 -0
- package/dist/fsck-DEz9lyCy.js.map +1 -0
- package/dist/http-CjUO1Bec.js +1756 -0
- package/dist/http-CjUO1Bec.js.map +1 -0
- package/dist/http.d.ts +1619 -0
- package/dist/http.js +2 -0
- package/dist/index-BGC-ENnj.d.ts +1065 -0
- package/dist/index-BYv0hb8M.d.ts +1457 -0
- package/dist/index-BquQkhJi.d.ts +112 -0
- package/dist/index-COsQ-Mlz.d.ts +146 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/indexes-BXn7a06a.js +297 -0
- package/dist/indexes-BXn7a06a.js.map +1 -0
- package/dist/indexes-DwOXkn1Y.d.ts +22 -0
- package/dist/inspect-x02aFWnh.js +149 -0
- package/dist/inspect-x02aFWnh.js.map +1 -0
- package/dist/log-walk-DIru96UT.js +260 -0
- package/dist/log-walk-DIru96UT.js.map +1 -0
- package/dist/maintenance-Bn6ul9aV.js +758 -0
- package/dist/maintenance-Bn6ul9aV.js.map +1 -0
- package/dist/maintenance.d.ts +323 -0
- package/dist/maintenance.js +2 -0
- package/dist/node.d.ts +422 -0
- package/dist/node.js +2 -0
- package/dist/normalize-XWY25_sG.js +133 -0
- package/dist/normalize-XWY25_sG.js.map +1 -0
- package/dist/observability-2IDYRuZK.js +2333 -0
- package/dist/observability-2IDYRuZK.js.map +1 -0
- package/dist/observability.d.ts +3 -0
- package/dist/observability.js +3 -0
- package/dist/plan-Cs17VqjU.js +224 -0
- package/dist/plan-Cs17VqjU.js.map +1 -0
- package/dist/query-DcSbFLJt.js +1880 -0
- package/dist/query-DcSbFLJt.js.map +1 -0
- package/dist/rebuild-index-C5gTXryd.js +119 -0
- package/dist/rebuild-index-C5gTXryd.js.map +1 -0
- package/dist/rebuild-index-DwXM0WfA.js +104 -0
- package/dist/rebuild-index-DwXM0WfA.js.map +1 -0
- package/dist/request-BEF_OvMh.js +72 -0
- package/dist/request-BEF_OvMh.js.map +1 -0
- package/dist/restore-CbKVMMpm.js +847 -0
- package/dist/restore-CbKVMMpm.js.map +1 -0
- package/dist/shared-secret-BJdSwpgw.js +71 -0
- package/dist/shared-secret-BJdSwpgw.js.map +1 -0
- package/dist/snapshot-D7C4_FSl.js +71 -0
- package/dist/snapshot-D7C4_FSl.js.map +1 -0
- package/dist/snapshot-z_N9hpTe.js +917 -0
- package/dist/snapshot-z_N9hpTe.js.map +1 -0
- package/dist/src-Chafbw8r.js +522 -0
- package/dist/src-Chafbw8r.js.map +1 -0
- package/dist/src-DyET_VPP.js +6199 -0
- package/dist/src-DyET_VPP.js.map +1 -0
- package/dist/src-n0Te1r98.js +352 -0
- package/dist/src-n0Te1r98.js.map +1 -0
- package/dist/subcommand-BWs6K7zb.js +110 -0
- package/dist/subcommand-BWs6K7zb.js.map +1 -0
- package/dist/usage-RVUQMLop.js +339 -0
- package/dist/usage-RVUQMLop.js.map +1 -0
- package/dist/validate-DhH1lO8I.js +377 -0
- package/dist/validate-DhH1lO8I.js.map +1 -0
- package/dist/wire-izfGZDvr.js +7 -0
- package/dist/wire-izfGZDvr.js.map +1 -0
- package/package.json +189 -0
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { o as BaerlyError } from "./baerly.js";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { resolve } from "node:path";
|
|
4
|
+
import { existsSync } from "node:fs";
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
6
|
+
//#region ../protocol/src/constants.ts
|
|
7
|
+
/**
|
|
8
|
+
* Backoff (in milliseconds) inserted between LIST attempts when S3
|
|
9
|
+
* returns 429 (rate-limited).
|
|
10
|
+
*/
|
|
11
|
+
const RATE_LIMIT_BACKOFF_MILLIS = 1e3;
|
|
12
|
+
/**
|
|
13
|
+
* MIME type written for `current.json` PUTs. S3 round-trips this on
|
|
14
|
+
* subsequent GETs; useful for diagnostics when staring at a bucket
|
|
15
|
+
* via the AWS console.
|
|
16
|
+
*
|
|
17
|
+
* @see packages/protocol/src/coordination/current-json.ts
|
|
18
|
+
*/
|
|
19
|
+
const CURRENT_JSON_CONTENT_TYPE = "application/json";
|
|
20
|
+
/**
|
|
21
|
+
* Canonical auth posture identifiers consumed by `BaerlyAppConfig.auth`,
|
|
22
|
+
* the adapter resolution path (`packages/adapter-cloudflare/src/worker.ts`,
|
|
23
|
+
* `packages/adapter-node/src/baerly-node.ts`), and `baerly doctor`.
|
|
24
|
+
*
|
|
25
|
+
* - `"none"` — no header check; pin every request to `config.tenant`.
|
|
26
|
+
* For local dev, intranet, CLI tools — contexts where the network
|
|
27
|
+
* seam itself is the trust boundary.
|
|
28
|
+
* - `"shared-secret"` — bearer-token check; reads `SHARED_SECRET` from
|
|
29
|
+
* the runtime env and pins every request to `config.tenant`.
|
|
30
|
+
*
|
|
31
|
+
* Custom verifiers (`cloudflareAccess`, `bearerJwt`, SigV4, …) bypass
|
|
32
|
+
* this enum — pass a `Verifier` to the adapter factory's `verifier:`
|
|
33
|
+
* option instead.
|
|
34
|
+
*/
|
|
35
|
+
const AUTH_CONFIG_VALUES = ["none", "shared-secret"];
|
|
36
|
+
/**
|
|
37
|
+
* Locked error wording for `auth: "shared-secret"` + missing env var.
|
|
38
|
+
* Same pinning rationale as {@link NO_AUTH_CONFIGURED_MESSAGE}.
|
|
39
|
+
*/
|
|
40
|
+
const SHARED_SECRET_MISSING_MESSAGE = "baerly: auth=\"shared-secret\" but SHARED_SECRET env is empty/unset. Cloudflare: `wrangler secret put SHARED_SECRET`, or add to .dev.vars for local dev. Node: set in process env.";
|
|
41
|
+
//#endregion
|
|
42
|
+
//#region src/config.ts
|
|
43
|
+
/**
|
|
44
|
+
* `baerly.config.ts` loader for `baerly deploy` / `baerly doctor`.
|
|
45
|
+
*
|
|
46
|
+
* Mirrors the shape of `BaerlyAppConfig` from `@gusto/baerly-storage/config`
|
|
47
|
+
* but lives in `@baerly/cli` so the validator/loader doesn't depend on
|
|
48
|
+
* the rolldown'd umbrella bundle. The scaffolder emits the config file;
|
|
49
|
+
* the CLI reads it. Both sides agree on the wire shape (informally —
|
|
50
|
+
* the duplication is small and intentional).
|
|
51
|
+
*
|
|
52
|
+
* Resolution order:
|
|
53
|
+
* 1. `<cwd>/baerly.config.ts`
|
|
54
|
+
* 2. `<cwd>/baerly.config.js`
|
|
55
|
+
* 3. `<cwd>/baerly.config.mjs`
|
|
56
|
+
* 4. `<cwd>/baerly.config.json`
|
|
57
|
+
*
|
|
58
|
+
* The `.ts` form requires the user to have a TS-aware Node entry
|
|
59
|
+
* point (`tsx`, `--experimental-strip-types`, or a build step that
|
|
60
|
+
* produced the `.js` alongside). If `import()` throws on the `.ts`
|
|
61
|
+
* file, we re-wrap as `InvalidConfig` with a hint pointing at the
|
|
62
|
+
* `.js` / `.json` fallbacks.
|
|
63
|
+
*/
|
|
64
|
+
const CONFIG_BASENAMES = [
|
|
65
|
+
"baerly.config.ts",
|
|
66
|
+
"baerly.config.js",
|
|
67
|
+
"baerly.config.mjs",
|
|
68
|
+
"baerly.config.json"
|
|
69
|
+
];
|
|
70
|
+
/**
|
|
71
|
+
* Locate the first `baerly.config.*` file under `cwd`. Returns the
|
|
72
|
+
* absolute path or `null` if none exists.
|
|
73
|
+
*
|
|
74
|
+
* Exported so the collection-aware loader (and future consumers) can
|
|
75
|
+
* reuse the same resolution order without re-implementing it.
|
|
76
|
+
*/
|
|
77
|
+
const locateConfig = (cwd) => {
|
|
78
|
+
for (const base of CONFIG_BASENAMES) {
|
|
79
|
+
const abs = resolve(cwd, base);
|
|
80
|
+
if (existsSync(abs)) return abs;
|
|
81
|
+
}
|
|
82
|
+
return null;
|
|
83
|
+
};
|
|
84
|
+
/**
|
|
85
|
+
* Load `baerly.config.{ts,js,mjs,json}` from `cwd` (defaults to
|
|
86
|
+
* `process.cwd()`). Validates the required fields and the
|
|
87
|
+
* locked-shape optionals; returns an `AppConfig` decorated with the
|
|
88
|
+
* `repoRoot` it was loaded from.
|
|
89
|
+
*
|
|
90
|
+
* @throws BaerlyError code="InvalidConfig" — file missing, default
|
|
91
|
+
* export missing, or any field has the wrong shape / type.
|
|
92
|
+
*/
|
|
93
|
+
const loadAppConfig = async (cwd = process.cwd()) => {
|
|
94
|
+
const cfgPath = locateConfig(cwd);
|
|
95
|
+
if (cfgPath === null) throw new BaerlyError("InvalidConfig", `baerly: no baerly.config.{ts,js,mjs,json} at ${cwd}. Are you in a baerly app directory?`);
|
|
96
|
+
let raw;
|
|
97
|
+
if (cfgPath.endsWith(".json")) {
|
|
98
|
+
let text;
|
|
99
|
+
try {
|
|
100
|
+
text = await readFile(cfgPath, "utf8");
|
|
101
|
+
} catch (error) {
|
|
102
|
+
throw new BaerlyError("InvalidConfig", `baerly: failed to read ${cfgPath}: ${error.message}`, error);
|
|
103
|
+
}
|
|
104
|
+
try {
|
|
105
|
+
raw = JSON.parse(text);
|
|
106
|
+
} catch (error) {
|
|
107
|
+
throw new BaerlyError("InvalidConfig", `baerly: failed to parse ${cfgPath}: ${error.message}`, error);
|
|
108
|
+
}
|
|
109
|
+
} else {
|
|
110
|
+
let mod;
|
|
111
|
+
try {
|
|
112
|
+
mod = await import(pathToFileURL(cfgPath).href);
|
|
113
|
+
} catch (error) {
|
|
114
|
+
const hint = cfgPath.endsWith(".ts") ? " (Node cannot import .ts directly without a TS loader — point at the compiled .js or use a .json config)" : "";
|
|
115
|
+
throw new BaerlyError("InvalidConfig", `baerly: failed to load ${cfgPath}: ${error.message}${hint}`, error);
|
|
116
|
+
}
|
|
117
|
+
raw = mod.default;
|
|
118
|
+
}
|
|
119
|
+
if (raw === void 0 || typeof raw !== "object" || raw === null) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath} must default-export a BaerlyAppConfig object`);
|
|
120
|
+
const obj = raw;
|
|
121
|
+
const app = obj["app"];
|
|
122
|
+
const tenant = obj["tenant"];
|
|
123
|
+
const target = obj["target"];
|
|
124
|
+
if (typeof app !== "string" || app.length === 0) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`app\` must be a non-empty string`);
|
|
125
|
+
if (typeof tenant !== "string" || tenant.length === 0) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`tenant\` must be a non-empty string`);
|
|
126
|
+
if (target !== "cloudflare" && target !== "node") throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`target\` must be "cloudflare" or "node" (got ${JSON.stringify(target)})`);
|
|
127
|
+
const authRaw = obj["auth"];
|
|
128
|
+
if (typeof authRaw !== "string" || !AUTH_CONFIG_VALUES.includes(authRaw)) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`auth\` is required and must be one of ${JSON.stringify(AUTH_CONFIG_VALUES)} (got ${JSON.stringify(authRaw)})`);
|
|
129
|
+
const auth = authRaw;
|
|
130
|
+
const domainRaw = obj["domain"];
|
|
131
|
+
if (domainRaw !== void 0 && typeof domainRaw !== "string") throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`domain\` must be a string when set`);
|
|
132
|
+
const secretsRaw = obj["requiredSecrets"];
|
|
133
|
+
let requiredSecrets;
|
|
134
|
+
if (secretsRaw !== void 0) {
|
|
135
|
+
if (!Array.isArray(secretsRaw) || !secretsRaw.every((s) => typeof s === "string")) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`requiredSecrets\` must be an array of strings`);
|
|
136
|
+
requiredSecrets = secretsRaw;
|
|
137
|
+
}
|
|
138
|
+
const cfaRaw = obj["cloudflareAccess"];
|
|
139
|
+
let cloudflareAccess;
|
|
140
|
+
if (cfaRaw !== void 0) {
|
|
141
|
+
if (typeof cfaRaw !== "object" || cfaRaw === null) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`cloudflareAccess\` must be an object when set`);
|
|
142
|
+
const cfa = cfaRaw;
|
|
143
|
+
const td = cfa["teamDomain"];
|
|
144
|
+
const aud = cfa["audienceTag"];
|
|
145
|
+
if (typeof td !== "string" || td.length === 0) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`cloudflareAccess.teamDomain\` must be a non-empty string`);
|
|
146
|
+
if (typeof aud !== "string" || aud.length === 0) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`cloudflareAccess.audienceTag\` must be a non-empty string`);
|
|
147
|
+
cloudflareAccess = {
|
|
148
|
+
teamDomain: td,
|
|
149
|
+
audienceTag: aud
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
return {
|
|
153
|
+
app,
|
|
154
|
+
tenant,
|
|
155
|
+
target,
|
|
156
|
+
auth,
|
|
157
|
+
...domainRaw !== void 0 && { domain: domainRaw },
|
|
158
|
+
...requiredSecrets !== void 0 && { requiredSecrets },
|
|
159
|
+
...cloudflareAccess !== void 0 && { cloudflareAccess },
|
|
160
|
+
repoRoot: cwd
|
|
161
|
+
};
|
|
162
|
+
};
|
|
163
|
+
/**
|
|
164
|
+
* Load the declared `IndexDefinition[]` for a single collection from a
|
|
165
|
+
* `baerly.config.{js,mjs,json}`. Used by `baerly inspect` (key-count
|
|
166
|
+
* probes) and `baerly admin rebuild-index` (resolving the `on` field).
|
|
167
|
+
*
|
|
168
|
+
* `.ts` configs are rejected — Node can't `import` them without a TS
|
|
169
|
+
* loader; point at the compiled `.js` output instead.
|
|
170
|
+
*
|
|
171
|
+
* `commandName` is woven into thrown error messages so the operator
|
|
172
|
+
* sees the calling command name in the prefix.
|
|
173
|
+
*
|
|
174
|
+
* @throws BaerlyError code="InvalidConfig" — `.ts` extension, JSON
|
|
175
|
+
* parse error, missing default export, or missing
|
|
176
|
+
* `collections[collection]`.
|
|
177
|
+
*/
|
|
178
|
+
const loadCollectionIndexes = async (configPath, collection, commandName) => {
|
|
179
|
+
if (configPath.endsWith(".ts")) throw new BaerlyError("InvalidConfig", `${commandName}: --config must point at compiled JS / JSON (got .ts: ${JSON.stringify(configPath)})`);
|
|
180
|
+
let cfg;
|
|
181
|
+
if (configPath.endsWith(".json")) {
|
|
182
|
+
const text = await readFile(configPath, "utf8");
|
|
183
|
+
try {
|
|
184
|
+
cfg = JSON.parse(text);
|
|
185
|
+
} catch (error) {
|
|
186
|
+
throw new BaerlyError("InvalidConfig", `${commandName}: --config JSON parse error in ${JSON.stringify(configPath)}: ${error.message}`);
|
|
187
|
+
}
|
|
188
|
+
} else {
|
|
189
|
+
const mod = await import(pathToFileURL(configPath.startsWith("file://") ? fileURLToPath(configPath) : resolve(configPath)).href);
|
|
190
|
+
if (mod.default === void 0) throw new BaerlyError("InvalidConfig", `${commandName}: --config ${JSON.stringify(configPath)} has no default export`);
|
|
191
|
+
cfg = mod.default;
|
|
192
|
+
}
|
|
193
|
+
return cfg.collections?.[collection]?.indexes ?? [];
|
|
194
|
+
};
|
|
195
|
+
//#endregion
|
|
196
|
+
export { SHARED_SECRET_MISSING_MESSAGE as a, RATE_LIMIT_BACKOFF_MILLIS as i, loadCollectionIndexes as n, CURRENT_JSON_CONTENT_TYPE as r, loadAppConfig as t };
|
|
197
|
+
|
|
198
|
+
//# sourceMappingURL=config-Bsg8wgwo.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config-Bsg8wgwo.js","names":[],"sources":["../packages/protocol/src/constants.ts","../packages/cli/src/config.ts"],"sourcesContent":["/**\n * Half-window (in milliseconds) within which a `LogEntry`'s embedded\n * `commit_ts` must agree with wall-clock time for downstream consumers\n * to accept the entry as causally ordered. Bound on tolerated\n * client/server clock skew across the protocol.\n *\n * 5 s is the protocol's tolerance for client/server clock skew.\n * Tightening this can cause spurious rejections on machines that\n * haven't synced NTP; loosening it widens the window during which\n * causal ordering can be disturbed by skew.\n *\n * @see docs/spec/sync-protocol.md\n * @see packages/protocol/src/storage/types.ts (`Storage` JSDoc)\n */\nexport const LAG_WINDOW_MILLIS: number = 5000;\n\n/**\n * Bit width of the base-32 timestamp prefix encoded into every\n * {@link LogEntry.lsn} (`<base32-time>_<session>_<seq>`, minted in\n * `Writer.commit`). 42 bits gives ~139 years of millisecond\n * precision, which is enough for the protocol's lifetime.\n *\n * Changing this is a protocol-breaking change — it would re-shape\n * every emitted LSN.\n *\n * @see packages/protocol/src/time.ts (`timestamp`)\n * @see packages/server/src/writer.ts (`Writer.commit`)\n * @see docs/spec/sync-protocol.md\n */\nexport const TIMESTAMP_BIT_WIDTH: number = 42;\n\n/**\n * Length of the random-prefix `session` segment embedded in every\n * {@link LogEntry.lsn} (`<base32-time>_<session>_<seq>`). 6 hex chars\n * from `crypto.randomUUID()` give 16⁶ ≈ 1.7 × 10⁷ distinct sessions;\n * birthday-collision rate at N=100 is ~3 × 10⁻⁴, comfortably below\n * the 1 % bound asserted in `tests/regressions.test.ts`. Collisions\n * within a single commit's writer set are also disambiguated by the\n * trailing `<seq>` counter.\n *\n * @see packages/server/src/writer.ts (`Writer.commit` —\n * `session = uuid().slice(0, SESSION_ID_LENGTH)`)\n */\nexport const SESSION_ID_LENGTH: number = 6;\n\n/**\n * Maximum attempts `S3HttpStorage.list` will make per page when the\n * server replies 429 (rate-limited). After this many in a row, it\n * gives up with `NetworkError`. Separate from the inner transient-\n * failure budget so a single hot page can't burn the whole retry\n * allowance.\n */\nexport const LIST_OBJECT_MAX_RETRIES: number = 10;\n\n/**\n * Backoff (in milliseconds) inserted between LIST attempts when S3\n * returns 429 (rate-limited).\n */\nexport const RATE_LIMIT_BACKOFF_MILLIS: number = 1000;\n\n/**\n * Upper clamp on a server-provided `Retry-After` hint, in seconds.\n * RFC 7231 §7.1.3 allows arbitrary delta-seconds or HTTP-dates, but a\n * client that blindly honours a multi-hour hint hands a misbehaving\n * proxy a denial-of-service primitive. 60s covers any plausible S3-\n * compatible throttle while keeping the worst-case bounded.\n *\n * @see packages/protocol/src/storage/s3-http.ts (`parseRetryAfter`)\n */\nexport const RETRY_AFTER_MAX_SECONDS: number = 60;\n\n/**\n * Default retry budget for `S3HttpStorage.retry` (the wrapper around\n * each of the four `Storage` methods). Bounded so that permanent\n * failures (CORS misconfig, NXDOMAIN, persistent 5xx) surface to\n * callers as rejected promises instead of retrying forever and\n * leaving `Writer.commit()` permanently pending.\n *\n * 8 attempts at the existing 100ms→×1.5→10s schedule covers ~30s of\n * transient turbulence, which is enough to ride out a leader election\n * or a brief network blip without papering over a real outage.\n */\nexport const S3_REQUEST_MAX_RETRIES: number = 8;\n\n/**\n * Maximum concurrent log-entry GETs issued by a single `walkLogRange`\n * call. Bounds Class-B fan-out per read and per CAS attempt — without\n * a bound, a reader on a collection whose compactor has fallen behind\n * fans out one GET per live-tail entry (typically 50-100 on the free-\n * tier profile), and a contended writer multiplies that by the CAS\n * retry budget ({@link S3_REQUEST_MAX_RETRIES}).\n *\n * 16 keeps the worst-case under retry to `16 * 8 = 128` concurrent\n * GETs — comfortably under the Workers subrequest cap (50 concurrent\n * / 1000 total) and leaving headroom for the writer's content / index\n * / log / CAS PUTs sharing the same isolate.\n *\n * @see packages/server/src/log-walk.ts (`walkLogRange`)\n */\nexport const MAX_PARALLEL_LOG_READS: number = 16;\n\n/**\n * Current major version of the `current.json` control-object schema.\n * Readers MUST reject unknown versions with\n * `BaerlyError{code:\"InvalidResponse\"}` rather than try to coerce.\n *\n * Bump only on a breaking change to `CurrentJson` field semantics.\n * Adding a new optional field is NOT breaking; renaming or removing\n * a field IS breaking.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n */\nexport const CURRENT_JSON_SCHEMA_VERSION = 1 as const;\n\n/**\n * MIME type written for `current.json` PUTs. S3 round-trips this on\n * subsequent GETs; useful for diagnostics when staring at a bucket\n * via the AWS console.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n */\nexport const CURRENT_JSON_CONTENT_TYPE: string = \"application/json\";\n\n/**\n * Current major version of the `gc/pending.json` control-object\n * schema. Readers MUST reject unknown versions with\n * `BaerlyError{code:\"InvalidResponse\"}` rather than try to coerce.\n *\n * Bump only on a breaking change to `GcPending` field semantics.\n * Adding a new optional field is NOT breaking; renaming or removing\n * a field IS breaking.\n *\n * @see packages/protocol/src/coordination/gc-pending.ts\n */\nexport const GC_PENDING_SCHEMA_VERSION = 1 as const;\n\n/**\n * MIME type written for `gc/pending.json` PUTs.\n *\n * @see packages/protocol/src/coordination/gc-pending.ts\n */\nexport const GC_PENDING_CONTENT_TYPE: string = \"application/json\";\n\n/**\n * Default grace period between \"marking\" a key for GC and \"sweeping\"\n * (deleting) it. 7 days, chosen to span the worst plausible writer-\n * retry window (a paused-process writer that resumes hours later\n * should still find its idempotency anchor on the bucket). The\n * `runGc()` function accepts an override for tests.\n *\n * Why 7 days specifically:\n * - **1 day is too aggressive for batch workloads.** Worker isolate\n * scheduling pauses, cross-region replication lag, and\n * {@link RATE_LIMIT_BACKOFF_MILLIS} retry cascades can plausibly\n * exceed an hour under pathological conditions.\n * - **30 days is conservative beyond the worst plausible pause.**\n * Doubles `gc/pending.json` size at steady state and slows\n * visibility into \"did GC actually run?\" by 4×.\n * - **7 days spans the realistic upper bound** — long-running batch\n * jobs, multi-region propagation delays, queue backlogs, and\n * downstream outages the writer is retrying through. The protocol\n * is unaffected by the choice of value within the [hours, weeks]\n * range; this constant is the operator-tunable knob.\n *\n * Production code MUST NOT call `runGc` with `graceMillis` below the\n * default outside maintenance windows — going below the longest\n * plausible writer-retry latency risks deleting an anchor a writer\n * is about to find on retry. Test code that sets `graceMillis: 0` is\n * exercising the sweep path deliberately, not modelling production.\n *\n * @see packages/server/src/gc.ts\n */\nexport const GC_GRACE_PERIOD_MILLIS: number = 7 * 24 * 60 * 60 * 1000;\n\n/**\n * Cap on candidates kept in `gc/pending.json` to bound the size of\n * the file. The compactor marks at most this many candidates per\n * pass; subsequent passes pick up the rest. Larger collections will\n * lag GC by one pass per `GC_MAX_PENDING_CANDIDATES` orphans, which\n * is acceptable.\n *\n * @see packages/server/src/gc.ts\n */\nexport const GC_MAX_PENDING_CANDIDATES: number = 1000;\n\n/**\n * Placeholder for `CurrentJson.snapshot === null` in the\n * `_meta.manifest_pointer` cursor emitted on read responses. The\n * wire format is `\"<snapshot>@<next_seq>\"`, and `null` snapshots\n * serialise as this literal so the cursor is never empty and stays\n * byte-stable when destructured by operators.\n *\n * @see packages/server/src/contract.ts (HttpOkMeta)\n */\nexport const MANIFEST_POINTER_EMPTY_SNAPSHOT: string = \"none\";\n\n/**\n * Keys that must never propagate through {@link merge}: assigning to\n * them on a plain object pollutes the prototype chain. The literal\n * `{ __proto__: ... }` syntax is a prototype-setter (not an own key)\n * and bypasses `Object.keys`, but `JSON.parse('{\"__proto__\":...}')`\n * produces a real own property — which is exactly how a malicious\n * HTTP PATCH body would arrive on the wire.\n *\n * Lifted to a constant so every iteration path that touches a\n * caller-supplied object can re-use the same defence without\n * duplicating the keyword list.\n *\n * @see packages/protocol/src/json.ts (merge)\n * @see docs/spec/json-merge-patch.md\n */\nexport const FORBIDDEN_MERGE_KEYS: ReadonlySet<string> = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\n/**\n * Architecturally-enforced ceiling: storage ops per logical write.\n *\n * Three Class A ops: PUT content, PUT log entry, CAS-advance\n * `current.json`. The cost-model page derives the free-tier write\n * budget from this multiplier; the phase-5 end-to-end test asserts it\n * at CI time. Changing this constant is a cost-model-breaking change.\n *\n * @see docs/about/cost-model.md §\"Cost ceiling\"\n * @see tests/integration/phase5-end-to-end.test.ts\n */\nexport const STORAGE_OPS_PER_LOGICAL_WRITE: number = 3;\n\n/**\n * Canonical auth posture identifiers consumed by `BaerlyAppConfig.auth`,\n * the adapter resolution path (`packages/adapter-cloudflare/src/worker.ts`,\n * `packages/adapter-node/src/baerly-node.ts`), and `baerly doctor`.\n *\n * - `\"none\"` — no header check; pin every request to `config.tenant`.\n * For local dev, intranet, CLI tools — contexts where the network\n * seam itself is the trust boundary.\n * - `\"shared-secret\"` — bearer-token check; reads `SHARED_SECRET` from\n * the runtime env and pins every request to `config.tenant`.\n *\n * Custom verifiers (`cloudflareAccess`, `bearerJwt`, SigV4, …) bypass\n * this enum — pass a `Verifier` to the adapter factory's `verifier:`\n * option instead.\n */\nexport const AUTH_CONFIG_VALUES = [\"none\", \"shared-secret\"] as const;\n\n/**\n * Locked error wording for the \"no auth configured\" failure mode. The\n * adapter throws this when neither `config.auth` nor `verifier:`\n * resolves a real `Verifier`. Pinned via a regression test so future\n * refactors do not drift the operator-facing wording.\n *\n * Consumed by:\n * - `packages/adapter-cloudflare/src/worker.ts` (first-fetch throw)\n * - `packages/adapter-node/src/server.ts` (first-fetch throw)\n * - `packages/cli/src/doctor/cloudflare.ts` (FAIL finding mirrors it)\n */\nexport const NO_AUTH_CONFIGURED_MESSAGE: string =\n 'baerly: no auth configured. Set `auth` in baerly.config.ts (\"none\", \"shared-secret\") or pass `verifier` on the adapter factory.';\n\n/**\n * Locked error wording for `auth: \"shared-secret\"` + missing env var.\n * Same pinning rationale as {@link NO_AUTH_CONFIGURED_MESSAGE}.\n */\nexport const SHARED_SECRET_MISSING_MESSAGE: string =\n 'baerly: auth=\"shared-secret\" but SHARED_SECRET env is empty/unset. Cloudflare: `wrangler secret put SHARED_SECRET`, or add to .dev.vars for local dev. Node: set in process env.';\n","/**\n * `baerly.config.ts` loader for `baerly deploy` / `baerly doctor`.\n *\n * Mirrors the shape of `BaerlyAppConfig` from `@gusto/baerly-storage/config`\n * but lives in `@baerly/cli` so the validator/loader doesn't depend on\n * the rolldown'd umbrella bundle. The scaffolder emits the config file;\n * the CLI reads it. Both sides agree on the wire shape (informally —\n * the duplication is small and intentional).\n *\n * Resolution order:\n * 1. `<cwd>/baerly.config.ts`\n * 2. `<cwd>/baerly.config.js`\n * 3. `<cwd>/baerly.config.mjs`\n * 4. `<cwd>/baerly.config.json`\n *\n * The `.ts` form requires the user to have a TS-aware Node entry\n * point (`tsx`, `--experimental-strip-types`, or a build step that\n * produced the `.js` alongside). If `import()` throws on the `.ts`\n * file, we re-wrap as `InvalidConfig` with a hint pointing at the\n * `.js` / `.json` fallbacks.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport {\n AUTH_CONFIG_VALUES,\n type AuthConfig,\n type BaerlyConfig,\n BaerlyError,\n type IndexDefinition,\n} from \"@baerly/protocol\";\n\nexport interface AppConfig {\n readonly app: string;\n readonly tenant: string;\n readonly target: \"cloudflare\" | \"node\";\n /**\n * Required. See `AuthConfig` for the per-value semantics. The loader\n * throws `BaerlyError(\"InvalidConfig\", ...)` when `auth` is missing or\n * not a member of `AUTH_CONFIG_VALUES`.\n */\n readonly auth: AuthConfig;\n readonly domain?: string;\n readonly requiredSecrets?: readonly string[];\n readonly cloudflareAccess?: {\n readonly teamDomain: string;\n readonly audienceTag: string;\n };\n /** Absolute path to the repo root that contained the config. */\n readonly repoRoot: string;\n}\n\nconst CONFIG_BASENAMES: readonly string[] = [\n \"baerly.config.ts\",\n \"baerly.config.js\",\n \"baerly.config.mjs\",\n \"baerly.config.json\",\n];\n\n/**\n * Locate the first `baerly.config.*` file under `cwd`. Returns the\n * absolute path or `null` if none exists.\n *\n * Exported so the collection-aware loader (and future consumers) can\n * reuse the same resolution order without re-implementing it.\n */\nexport const locateConfig = (cwd: string): string | null => {\n for (const base of CONFIG_BASENAMES) {\n const abs = resolve(cwd, base);\n if (existsSync(abs)) {\n return abs;\n }\n }\n return null;\n};\n\n/**\n * Load `baerly.config.{ts,js,mjs,json}` from `cwd` (defaults to\n * `process.cwd()`). Validates the required fields and the\n * locked-shape optionals; returns an `AppConfig` decorated with the\n * `repoRoot` it was loaded from.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — file missing, default\n * export missing, or any field has the wrong shape / type.\n */\nexport const loadAppConfig = async (cwd: string = process.cwd()): Promise<AppConfig> => {\n const cfgPath = locateConfig(cwd);\n if (cfgPath === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: no baerly.config.{ts,js,mjs,json} at ${cwd}. Are you in a baerly app directory?`,\n );\n }\n\n let raw: unknown;\n if (cfgPath.endsWith(\".json\")) {\n let text: string;\n try {\n text = await readFile(cfgPath, \"utf8\");\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: failed to read ${cfgPath}: ${(error as Error).message}`,\n error,\n );\n }\n try {\n raw = JSON.parse(text) as unknown;\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: failed to parse ${cfgPath}: ${(error as Error).message}`,\n error,\n );\n }\n } else {\n let mod: { default?: unknown };\n try {\n mod = (await import(pathToFileURL(cfgPath).href)) as { default?: unknown };\n } catch (error) {\n const hint = cfgPath.endsWith(\".ts\")\n ? \" (Node cannot import .ts directly without a TS loader — point at the compiled .js or use a .json config)\"\n : \"\";\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: failed to load ${cfgPath}: ${(error as Error).message}${hint}`,\n error,\n );\n }\n raw = mod.default;\n }\n\n if (raw === undefined || typeof raw !== \"object\" || raw === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath} must default-export a BaerlyAppConfig object`,\n );\n }\n\n const obj = raw as Record<string, unknown>;\n const app = obj[\"app\"];\n const tenant = obj[\"tenant\"];\n const target = obj[\"target\"];\n if (typeof app !== \"string\" || app.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`app\\` must be a non-empty string`,\n );\n }\n if (typeof tenant !== \"string\" || tenant.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`tenant\\` must be a non-empty string`,\n );\n }\n if (target !== \"cloudflare\" && target !== \"node\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`target\\` must be \"cloudflare\" or \"node\" (got ${JSON.stringify(target)})`,\n );\n }\n\n // `auth` is a required typed posture as of the graduated-auth\n // redesign. The widening cast to `readonly string[]` is needed\n // because `.includes` on a tuple narrows its parameter to the\n // tuple's element type; widening locally is the standard idiom.\n const authRaw = obj[\"auth\"];\n if (typeof authRaw !== \"string\" || !(AUTH_CONFIG_VALUES as readonly string[]).includes(authRaw)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`auth\\` is required and must be one of ${JSON.stringify(AUTH_CONFIG_VALUES)} (got ${JSON.stringify(authRaw)})`,\n );\n }\n const auth = authRaw as AuthConfig;\n\n const domainRaw = obj[\"domain\"];\n if (domainRaw !== undefined && typeof domainRaw !== \"string\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`domain\\` must be a string when set`,\n );\n }\n\n const secretsRaw = obj[\"requiredSecrets\"];\n let requiredSecrets: readonly string[] | undefined;\n if (secretsRaw !== undefined) {\n if (!Array.isArray(secretsRaw) || !secretsRaw.every((s) => typeof s === \"string\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`requiredSecrets\\` must be an array of strings`,\n );\n }\n requiredSecrets = secretsRaw as readonly string[];\n }\n\n const cfaRaw = obj[\"cloudflareAccess\"];\n let cloudflareAccess: AppConfig[\"cloudflareAccess\"];\n if (cfaRaw !== undefined) {\n if (typeof cfaRaw !== \"object\" || cfaRaw === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`cloudflareAccess\\` must be an object when set`,\n );\n }\n const cfa = cfaRaw as Record<string, unknown>;\n const td = cfa[\"teamDomain\"];\n const aud = cfa[\"audienceTag\"];\n if (typeof td !== \"string\" || td.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`cloudflareAccess.teamDomain\\` must be a non-empty string`,\n );\n }\n if (typeof aud !== \"string\" || aud.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`cloudflareAccess.audienceTag\\` must be a non-empty string`,\n );\n }\n cloudflareAccess = { teamDomain: td, audienceTag: aud };\n }\n\n return {\n app,\n tenant,\n target,\n auth,\n ...(domainRaw !== undefined && { domain: domainRaw }),\n ...(requiredSecrets !== undefined && { requiredSecrets }),\n ...(cloudflareAccess !== undefined && { cloudflareAccess }),\n repoRoot: cwd,\n };\n};\n\n/**\n * Lightweight per-collection index reflection. Mirrors the shape the\n * runtime `BaerlyConfig` carries, but only the fields the doctor needs.\n *\n * `indexes` is an empty array when the collection declared none.\n */\nexport interface LoadedCollection {\n readonly name: string;\n readonly indexes: readonly IndexDefinition[];\n}\n\n/**\n * Load `baerly.config.{ts,js,mjs,json}` AND return the parsed\n * `collections[*]` shape alongside the narrow {@link AppConfig}. Lets\n * the doctor reflect on declared indexes without forcing every consumer\n * to widen `AppConfig`. Returns `undefined` for `collections` when the\n * config doesn't declare any (the doctor downgrades the drift check to\n * a no-op `info` finding in that case).\n *\n * Re-uses {@link loadAppConfig}'s parse/validate path, so the\n * `AppConfig` invariants are still enforced.\n */\nexport const loadAppConfigWithCollections = async (\n cwd: string = process.cwd(),\n): Promise<{\n readonly config: AppConfig;\n readonly collections: readonly LoadedCollection[] | undefined;\n}> => {\n const config = await loadAppConfig(cwd);\n const cfgPath = locateConfig(cwd);\n if (cfgPath === null) {\n return { config, collections: undefined };\n }\n\n // Re-parse the raw default-export to pluck `collections[*]`. We\n // don't validate the inner shape here — at the doctor surface,\n // anything that isn't an object is reported as \"no filtered\n // indexes\" rather than throwing, so a partially-typed config\n // doesn't fail the whole check.\n let raw: unknown;\n if (cfgPath.endsWith(\".json\")) {\n let text: string;\n try {\n text = await readFile(cfgPath, \"utf8\");\n } catch {\n return { config, collections: undefined };\n }\n try {\n raw = JSON.parse(text);\n } catch {\n return { config, collections: undefined };\n }\n } else {\n try {\n const mod = (await import(pathToFileURL(cfgPath).href)) as { default?: unknown };\n raw = mod.default;\n } catch {\n // Node can't `import` a .ts file without a TS loader. The\n // narrow `loadAppConfig` already surfaced the InvalidConfig if\n // that path was unreadable; here we silently downgrade to\n // \"no collections\" rather than re-throw.\n return { config, collections: undefined };\n }\n }\n\n if (raw === undefined || raw === null || typeof raw !== \"object\") {\n return { config, collections: undefined };\n }\n const colsRaw = (raw as { collections?: unknown }).collections;\n if (colsRaw === undefined || colsRaw === null || typeof colsRaw !== \"object\") {\n return { config, collections: undefined };\n }\n\n const out: LoadedCollection[] = [];\n for (const [name, decl] of Object.entries(colsRaw as Record<string, unknown>)) {\n if (decl === null || typeof decl !== \"object\") {\n continue;\n }\n const indexes = (decl as { indexes?: unknown }).indexes;\n if (!Array.isArray(indexes)) {\n out.push({ name, indexes: [] });\n continue;\n }\n // Pass-through cast: the runtime IndexDefinition validation\n // lives in `@baerly/server`; the doctor only reads `name`, `on`,\n // and `predicate`, so a partial shape still gives an actionable\n // finding rather than a SchemaError throw at config-load time.\n out.push({ name, indexes: indexes as readonly IndexDefinition[] });\n }\n return { config, collections: out };\n};\n\n/**\n * Load the declared `IndexDefinition[]` for a single collection from a\n * `baerly.config.{js,mjs,json}`. Used by `baerly inspect` (key-count\n * probes) and `baerly admin rebuild-index` (resolving the `on` field).\n *\n * `.ts` configs are rejected — Node can't `import` them without a TS\n * loader; point at the compiled `.js` output instead.\n *\n * `commandName` is woven into thrown error messages so the operator\n * sees the calling command name in the prefix.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — `.ts` extension, JSON\n * parse error, missing default export, or missing\n * `collections[collection]`.\n */\nexport const loadCollectionIndexes = async (\n configPath: string,\n collection: string,\n commandName: string,\n): Promise<readonly IndexDefinition[]> => {\n if (configPath.endsWith(\".ts\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${commandName}: --config must point at compiled JS / JSON (got .ts: ${JSON.stringify(configPath)})`,\n );\n }\n let cfg: BaerlyConfig;\n if (configPath.endsWith(\".json\")) {\n const text = await readFile(configPath, \"utf8\");\n try {\n cfg = JSON.parse(text) as BaerlyConfig;\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${commandName}: --config JSON parse error in ${JSON.stringify(configPath)}: ${(error as Error).message}`,\n );\n }\n } else {\n const abs = configPath.startsWith(\"file://\") ? fileURLToPath(configPath) : resolve(configPath);\n const mod = (await import(pathToFileURL(abs).href)) as { default?: BaerlyConfig };\n if (mod.default === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${commandName}: --config ${JSON.stringify(configPath)} has no default export`,\n );\n }\n cfg = mod.default;\n }\n return cfg.collections?.[collection]?.indexes ?? [];\n};\n"],"mappings":"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"}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
//#region packages/protocol/src/metrics.ts
|
|
3
|
+
/**
|
|
4
|
+
* No-op recorder. Safe default when no operator sink is wired —
|
|
5
|
+
* emission sites that read `getCurrentContext()?.recorder` fall
|
|
6
|
+
* back to this outside an active `runWithContext` scope.
|
|
7
|
+
*/
|
|
8
|
+
const noopMetricsRecorder = {
|
|
9
|
+
counter: () => {},
|
|
10
|
+
gauge: () => {},
|
|
11
|
+
histogram: () => {}
|
|
12
|
+
};
|
|
13
|
+
//#endregion
|
|
14
|
+
//#region packages/server/src/observability/recorder.ts
|
|
15
|
+
/**
|
|
16
|
+
* Implementation. Allocations:
|
|
17
|
+
*
|
|
18
|
+
* - Three arrays at construction time, grown on each emission.
|
|
19
|
+
* - On `summarize()` we materialize one extra `Map` per metric-
|
|
20
|
+
* family (counter / gauge / histogram) plus a copy of each
|
|
21
|
+
* histogram's values for sorting.
|
|
22
|
+
*
|
|
23
|
+
* CPU-ms budget on Workers is tight; we deliberately defer all of
|
|
24
|
+
* that to flush time.
|
|
25
|
+
*/
|
|
26
|
+
var RequestScopedMetricsRecorder = class {
|
|
27
|
+
#counters = [];
|
|
28
|
+
#gauges = [];
|
|
29
|
+
#histograms = [];
|
|
30
|
+
counter(name, value, labels = {}) {
|
|
31
|
+
this.#counters.push({
|
|
32
|
+
name,
|
|
33
|
+
value,
|
|
34
|
+
labels
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
gauge(name, value, labels = {}) {
|
|
38
|
+
this.#gauges.push({
|
|
39
|
+
name,
|
|
40
|
+
value,
|
|
41
|
+
labels
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
histogram(name, value, labels = {}) {
|
|
45
|
+
this.#histograms.push({
|
|
46
|
+
name,
|
|
47
|
+
value,
|
|
48
|
+
labels
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Read-only view of every observation seen so far. Intended for
|
|
53
|
+
* tests + structured debugging; the canonical-line flusher uses
|
|
54
|
+
* {@link summarize} instead.
|
|
55
|
+
*
|
|
56
|
+
* @internal Not part of the published observability surface; tests
|
|
57
|
+
* import via relative path. Production reads via {@link summarize}.
|
|
58
|
+
*/
|
|
59
|
+
snapshot() {
|
|
60
|
+
return {
|
|
61
|
+
counters: this.#counters.slice(),
|
|
62
|
+
gauges: this.#gauges.slice(),
|
|
63
|
+
histograms: this.#histograms.slice()
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Flat aggregation, keyed by metric name with suffixes baked in:
|
|
68
|
+
*
|
|
69
|
+
* - Counter `db.foo.bar` → `db.foo.bar_total` (sum of all observations)
|
|
70
|
+
* - Gauge `db.foo.bar` → `db.foo.bar` (last value seen)
|
|
71
|
+
* - Histogram `db.foo.bar` → `db.foo.bar_count` (number of observations)
|
|
72
|
+
* + `db.foo.bar_sum` (sum of values)
|
|
73
|
+
*
|
|
74
|
+
* Histogram aggregation is a single pass in insertion order — no
|
|
75
|
+
* sort. Returns numbers only — labels are NOT collapsed into keys;
|
|
76
|
+
* if a metric is emitted with different label sets, its
|
|
77
|
+
* observations are aggregated together by `name` alone. The
|
|
78
|
+
* canonical line is per-request anyway; per-label fan-out belongs
|
|
79
|
+
* to the operator's long-term recorder.
|
|
80
|
+
*/
|
|
81
|
+
summarize() {
|
|
82
|
+
const out = {};
|
|
83
|
+
for (const row of this.#counters) {
|
|
84
|
+
const key = row.name.endsWith("_total") ? row.name : `${row.name}_total`;
|
|
85
|
+
out[key] = (out[key] ?? 0) + row.value;
|
|
86
|
+
}
|
|
87
|
+
for (const row of this.#gauges) out[row.name] = row.value;
|
|
88
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
89
|
+
for (const row of this.#histograms) {
|
|
90
|
+
let agg = buckets.get(row.name);
|
|
91
|
+
if (agg === void 0) {
|
|
92
|
+
agg = {
|
|
93
|
+
count: 0,
|
|
94
|
+
sum: 0
|
|
95
|
+
};
|
|
96
|
+
buckets.set(row.name, agg);
|
|
97
|
+
}
|
|
98
|
+
agg.count += 1;
|
|
99
|
+
agg.sum += row.value;
|
|
100
|
+
}
|
|
101
|
+
for (const [name, { count, sum }] of buckets) {
|
|
102
|
+
out[`${name}_count`] = count;
|
|
103
|
+
out[`${name}_sum`] = sum;
|
|
104
|
+
}
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
//#endregion
|
|
109
|
+
//#region packages/server/src/observability/context.ts
|
|
110
|
+
/**
|
|
111
|
+
* Per-request observability context.
|
|
112
|
+
*
|
|
113
|
+
* One `ObservabilityContext` is created at the entry of each unit-of-
|
|
114
|
+
* work (HTTP request, maintenance tick, GC sweep, rebuild run) and
|
|
115
|
+
* carried through the call tree via {@link runWithContext} /
|
|
116
|
+
* {@link getCurrentContext}, which delegates to a single module-level
|
|
117
|
+
* `AsyncLocalStorage` instance.
|
|
118
|
+
*
|
|
119
|
+
* The context is intentionally tiny: an externally-set
|
|
120
|
+
* {@link request_id}, a high-resolution `started_at`, and a mutable
|
|
121
|
+
* {@link fields} bag used to accumulate canonical-line attributes
|
|
122
|
+
* during the unit's lifecycle.
|
|
123
|
+
*
|
|
124
|
+
* The context shape is `readonly` everywhere it can be — only the
|
|
125
|
+
* contents of `fields` are intended to mutate during a request. The
|
|
126
|
+
* {@link fields} map itself is not `readonly` because callers (the
|
|
127
|
+
* canonical-line emitter, middleware, the collection API once Dispatch
|
|
128
|
+
* 3+ wires it up) need to set entries.
|
|
129
|
+
*
|
|
130
|
+
* The context carries no sampling state — every unit-of-work emits
|
|
131
|
+
* one canonical line unconditionally; there is nothing to gate.
|
|
132
|
+
*
|
|
133
|
+
* ## Time source
|
|
134
|
+
*
|
|
135
|
+
* `started_at` uses `performance.now()` so durations can be
|
|
136
|
+
* computed without worrying about wall-clock skew (NTP step,
|
|
137
|
+
* leap-second smearing). `performance.now()` is part of both Node
|
|
138
|
+
* 18+ and the Workers Runtime; we don't fall back to `Date.now()`.
|
|
139
|
+
*
|
|
140
|
+
* @example
|
|
141
|
+
* ```ts
|
|
142
|
+
* const ctx = createObservabilityContext({});
|
|
143
|
+
* await runWithContext(ctx, async () => {
|
|
144
|
+
* const inner = getCurrentContext();
|
|
145
|
+
* inner?.fields.set("collection", "tickets");
|
|
146
|
+
* await doWork();
|
|
147
|
+
* });
|
|
148
|
+
* ```
|
|
149
|
+
*/
|
|
150
|
+
/**
|
|
151
|
+
* Factory for {@link ObservabilityContext}. We use a factory rather
|
|
152
|
+
* than a class so consumers can structural-type the result and so
|
|
153
|
+
* the `AsyncLocalStorage` slot type stays a plain interface — no
|
|
154
|
+
* surprises around `instanceof` across realms (Workers vs Node).
|
|
155
|
+
*/
|
|
156
|
+
const createObservabilityContext = (init = {}) => ({
|
|
157
|
+
request_id: init.request_id ?? crypto.randomUUID(),
|
|
158
|
+
started_at: performance.now(),
|
|
159
|
+
fields: /* @__PURE__ */ new Map(),
|
|
160
|
+
recorder: init.recorder ?? new RequestScopedMetricsRecorder()
|
|
161
|
+
});
|
|
162
|
+
/**
|
|
163
|
+
* Module-level slot. One instance per process — the Workers
|
|
164
|
+
* Runtime's `nodejs_compat` flag wires `node:async_hooks` to a
|
|
165
|
+
* per-request scope, so cross-request bleed is impossible there.
|
|
166
|
+
*/
|
|
167
|
+
const als = new AsyncLocalStorage();
|
|
168
|
+
/**
|
|
169
|
+
* Run `fn` with `ctx` active as the current observability context.
|
|
170
|
+
* Inside `fn` (and any `await`-chained continuation rooted in `fn`),
|
|
171
|
+
* {@link getCurrentContext} returns `ctx`. Outside, it returns the
|
|
172
|
+
* previously-active context (or `undefined`).
|
|
173
|
+
*
|
|
174
|
+
* `runWithContext` is async-safe via `AsyncLocalStorage`; it propagates
|
|
175
|
+
* through `await`, `Promise.all`, `setTimeout`, and `queueMicrotask`.
|
|
176
|
+
*
|
|
177
|
+
* Returns `fn`'s return value verbatim — including its promise
|
|
178
|
+
* identity, so callers can `await` or chain off it without extra
|
|
179
|
+
* indirection.
|
|
180
|
+
*/
|
|
181
|
+
const runWithContext = (ctx, fn) => als.run(ctx, fn);
|
|
182
|
+
/** Returns the currently-active context, or `undefined` outside one. */
|
|
183
|
+
const getCurrentContext = () => als.getStore();
|
|
184
|
+
//#endregion
|
|
185
|
+
export { noopMetricsRecorder as i, getCurrentContext as n, runWithContext as r, createObservabilityContext as t };
|
|
186
|
+
|
|
187
|
+
//# sourceMappingURL=context-Oj7ffwD-.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-Oj7ffwD-.js","names":["#counters","#gauges","#histograms"],"sources":["../packages/protocol/src/metrics.ts","../packages/server/src/observability/recorder.ts","../packages/server/src/observability/context.ts"],"sourcesContent":["/**\n * `MetricsRecorder` — internal emission contract for the six\n * load-bearing kernel metrics. Writer / compactor / GC emit through\n * an instance of this interface; in production the instance is the\n * per-request `RequestScopedMetricsRecorder` on the active\n * `ObservabilityContext`, and emissions flow onto the canonical line\n * via `summarize()`. Tests use a local `InMemoryMetricsRecorder` and\n * wrap their workload in `runWithContext` to attach it.\n *\n * Operators do not wire a custom sink against this interface — the\n * operator's view of kernel emissions is the canonical line on\n * stdout (one JSON object per HTTP request).\n *\n * **Naming convention** matches the load-bearing metrics:\n * - `db.write.class_a_ops_per_logical_write` — histogram (p99 alert at 5).\n * Includes one Class A op per index PUT + index DELETE emitted\n * in the commit's fence. Idle-reader cost is unchanged.\n * - `db.r2.put.412_total` — counter (CAS conflict / If-Match-or-None-Match loss)\n * - `db.r2.put.429_total` — counter (R2 prefix-partition rate-limit)\n * - `db.write.index_ops_per_logical_write` — histogram.\n * `K (PUT) + L (DELETE)` per commit. Per-collection label.\n * - `db.manifest.lag_window_depth` — gauge (alert at >100)\n * - `db.gc.entries_swept_per_second` — gauge (livelock indicator when <writes/s)\n * - `db.orphan.candidate_count` — gauge (`gc/pending.json` depth)\n * - `db.compact.entries_folded` — histogram (entries folded per run)\n * - `db.gc.swept_total` — counter (labelled by reason)\n *\n * Names follow `db.<subsystem>.<metric>`, dot-separated, all-lowercase\n * snake_case segments. Labels are flat\n * `Readonly<Record<string, string>>` — no numbers, no nested objects.\n *\n * Metric emissions never throw on the hot path; the default\n * `noopMetricsRecorder` cannot throw.\n */\nexport interface MetricsRecorder {\n /** Monotonically-incrementing event count. */\n counter(name: string, value: number, labels?: Readonly<Record<string, string>>): void;\n /** Point-in-time value. */\n gauge(name: string, value: number, labels?: Readonly<Record<string, string>>): void;\n /** Distribution sample. */\n histogram(name: string, value: number, labels?: Readonly<Record<string, string>>): void;\n}\n\n/**\n * No-op recorder. Safe default when no operator sink is wired —\n * emission sites that read `getCurrentContext()?.recorder` fall\n * back to this outside an active `runWithContext` scope.\n */\nexport const noopMetricsRecorder: MetricsRecorder = {\n counter: (): void => {},\n gauge: (): void => {},\n histogram: (): void => {},\n};\n","/**\n * Per-request `MetricsRecorder` whose primary product is the\n * canonical-line attribute set.\n *\n * `RequestScopedMetricsRecorder` is a deliberately tiny extension to\n * the {@link MetricsRecorder} interface that adds two readers\n * (`snapshot()` for tests / debug, `summarize()` for the canonical\n * log line). Every method just appends a row to a flat array — no\n * sorting, no JSON, no aggregation on the hot path. The work happens\n * once at end-of-request inside `summarize()`.\n *\n * The shape mirrors {@link InMemoryMetricsRecorder} from\n * `../_internal/in-memory-metrics.ts` but adds the per-request product. We do\n * NOT extend that class — composition over inheritance, and the\n * observability layer wants `summarize()` to be the only side-channel.\n */\n\nimport type { MetricsRecorder } from \"@baerly/protocol\";\n\n/** One observation row, kept in insertion order. */\nexport interface ObservationRow {\n readonly name: string;\n readonly value: number;\n readonly labels: Readonly<Record<string, string>>;\n}\n\n/** Result of {@link RequestScopedMetricsRecorder.snapshot}. */\nexport interface MetricsSnapshot {\n readonly counters: readonly ObservationRow[];\n readonly gauges: readonly ObservationRow[];\n readonly histograms: readonly ObservationRow[];\n}\n\n/** Flat per-metric aggregation as consumed by the canonical line. */\nexport type MetricsSummary = Record<string, number>;\n\n/**\n * Implementation. Allocations:\n *\n * - Three arrays at construction time, grown on each emission.\n * - On `summarize()` we materialize one extra `Map` per metric-\n * family (counter / gauge / histogram) plus a copy of each\n * histogram's values for sorting.\n *\n * CPU-ms budget on Workers is tight; we deliberately defer all of\n * that to flush time.\n */\nexport class RequestScopedMetricsRecorder implements MetricsRecorder {\n readonly #counters: ObservationRow[] = [];\n readonly #gauges: ObservationRow[] = [];\n readonly #histograms: ObservationRow[] = [];\n\n counter(name: string, value: number, labels: Readonly<Record<string, string>> = {}): void {\n this.#counters.push({ name, value, labels });\n }\n gauge(name: string, value: number, labels: Readonly<Record<string, string>> = {}): void {\n this.#gauges.push({ name, value, labels });\n }\n histogram(name: string, value: number, labels: Readonly<Record<string, string>> = {}): void {\n this.#histograms.push({ name, value, labels });\n }\n\n /**\n * Read-only view of every observation seen so far. Intended for\n * tests + structured debugging; the canonical-line flusher uses\n * {@link summarize} instead.\n *\n * @internal Not part of the published observability surface; tests\n * import via relative path. Production reads via {@link summarize}.\n */\n snapshot(): MetricsSnapshot {\n return {\n counters: this.#counters.slice(),\n gauges: this.#gauges.slice(),\n histograms: this.#histograms.slice(),\n };\n }\n\n /**\n * Flat aggregation, keyed by metric name with suffixes baked in:\n *\n * - Counter `db.foo.bar` → `db.foo.bar_total` (sum of all observations)\n * - Gauge `db.foo.bar` → `db.foo.bar` (last value seen)\n * - Histogram `db.foo.bar` → `db.foo.bar_count` (number of observations)\n * + `db.foo.bar_sum` (sum of values)\n *\n * Histogram aggregation is a single pass in insertion order — no\n * sort. Returns numbers only — labels are NOT collapsed into keys;\n * if a metric is emitted with different label sets, its\n * observations are aggregated together by `name` alone. The\n * canonical line is per-request anyway; per-label fan-out belongs\n * to the operator's long-term recorder.\n */\n summarize(): MetricsSummary {\n const out: MetricsSummary = {};\n\n // Counters: sum.\n for (const row of this.#counters) {\n // Counter convention: prefer the emitter's name verbatim. If the\n // emitter already namespaced its counter with `_total` (Prometheus\n // convention — see packages/server/src/observability/storage.ts),\n // do not double-append. Otherwise append for canonical-line\n // consumers that key off the `_total` suffix.\n const key = row.name.endsWith(\"_total\") ? row.name : `${row.name}_total`;\n out[key] = (out[key] ?? 0) + row.value;\n }\n\n // Gauges: last write wins per name (observations are in\n // insertion order; iterate forward and overwrite).\n for (const row of this.#gauges) {\n out[row.name] = row.value;\n }\n\n // Histograms: bucket-by-name, then emit `_count` + `_sum`.\n const buckets = new Map<string, { count: number; sum: number }>();\n for (const row of this.#histograms) {\n let agg = buckets.get(row.name);\n if (agg === undefined) {\n agg = { count: 0, sum: 0 };\n buckets.set(row.name, agg);\n }\n agg.count += 1;\n agg.sum += row.value;\n }\n for (const [name, { count, sum }] of buckets) {\n out[`${name}_count`] = count;\n out[`${name}_sum`] = sum;\n }\n\n return out;\n }\n}\n","/**\n * Per-request observability context.\n *\n * One `ObservabilityContext` is created at the entry of each unit-of-\n * work (HTTP request, maintenance tick, GC sweep, rebuild run) and\n * carried through the call tree via {@link runWithContext} /\n * {@link getCurrentContext}, which delegates to a single module-level\n * `AsyncLocalStorage` instance.\n *\n * The context is intentionally tiny: an externally-set\n * {@link request_id}, a high-resolution `started_at`, and a mutable\n * {@link fields} bag used to accumulate canonical-line attributes\n * during the unit's lifecycle.\n *\n * The context shape is `readonly` everywhere it can be — only the\n * contents of `fields` are intended to mutate during a request. The\n * {@link fields} map itself is not `readonly` because callers (the\n * canonical-line emitter, middleware, the collection API once Dispatch\n * 3+ wires it up) need to set entries.\n *\n * The context carries no sampling state — every unit-of-work emits\n * one canonical line unconditionally; there is nothing to gate.\n *\n * ## Time source\n *\n * `started_at` uses `performance.now()` so durations can be\n * computed without worrying about wall-clock skew (NTP step,\n * leap-second smearing). `performance.now()` is part of both Node\n * 18+ and the Workers Runtime; we don't fall back to `Date.now()`.\n *\n * @example\n * ```ts\n * const ctx = createObservabilityContext({});\n * await runWithContext(ctx, async () => {\n * const inner = getCurrentContext();\n * inner?.fields.set(\"collection\", \"tickets\");\n * await doWork();\n * });\n * ```\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { RequestScopedMetricsRecorder } from \"./recorder.ts\";\n\n/** Read-mostly per-request observability state. */\nexport interface ObservabilityContext {\n /** Externally-correlatable request identifier (UUID-ish). */\n readonly request_id: string;\n /** Monotonic `performance.now()` reading captured at construction. */\n readonly started_at: number;\n /**\n * Mutable bag for canonical-line attributes. Callers `obs.fields.set(\"k\", v)`;\n * the canonical-line flusher spreads this onto the emitted properties at\n * end-of-request.\n */\n readonly fields: Map<string, unknown>;\n /**\n * Per-request metrics bag. Lives on the context so adapters can\n * reach it from inside the `Db`'s `MetricsRecorder` callback via\n * `getCurrentContext()?.recorder` — no parallel `AsyncLocalStorage`\n * lookup. The canonical-line flusher reads its `summarize()` at\n * end-of-request and spreads the result onto the emitted line.\n */\n readonly recorder: RequestScopedMetricsRecorder;\n}\n\n/**\n * Optional construction inputs. All fields are optional so callers in\n * unit-of-work entry middleware (HTTP router, maintenance scheduler)\n * can pass only what they have. Defaults:\n *\n * - `request_id`: a fresh `crypto.randomUUID()`. Pass an externally-\n * supplied id (`X-Request-Id` header, scheduler-supplied tag) to\n * propagate correlation downstream.\n * - `recorder`: a fresh {@link RequestScopedMetricsRecorder}. Tests can\n * pass an externally-constructed recorder to assert on its\n * `snapshot()` after the unit-of-work completes; production callers\n * should accept the default.\n */\nexport interface ObservabilityContextInit {\n readonly request_id?: string;\n readonly recorder?: RequestScopedMetricsRecorder;\n}\n\n/**\n * Factory for {@link ObservabilityContext}. We use a factory rather\n * than a class so consumers can structural-type the result and so\n * the `AsyncLocalStorage` slot type stays a plain interface — no\n * surprises around `instanceof` across realms (Workers vs Node).\n */\nexport const createObservabilityContext = (\n init: ObservabilityContextInit = {},\n): ObservabilityContext => ({\n request_id: init.request_id ?? crypto.randomUUID(),\n started_at: performance.now(),\n fields: new Map(),\n recorder: init.recorder ?? new RequestScopedMetricsRecorder(),\n});\n\n/**\n * Module-level slot. One instance per process — the Workers\n * Runtime's `nodejs_compat` flag wires `node:async_hooks` to a\n * per-request scope, so cross-request bleed is impossible there.\n */\nconst als = new AsyncLocalStorage<ObservabilityContext>();\n\n/**\n * Run `fn` with `ctx` active as the current observability context.\n * Inside `fn` (and any `await`-chained continuation rooted in `fn`),\n * {@link getCurrentContext} returns `ctx`. Outside, it returns the\n * previously-active context (or `undefined`).\n *\n * `runWithContext` is async-safe via `AsyncLocalStorage`; it propagates\n * through `await`, `Promise.all`, `setTimeout`, and `queueMicrotask`.\n *\n * Returns `fn`'s return value verbatim — including its promise\n * identity, so callers can `await` or chain off it without extra\n * indirection.\n */\nexport const runWithContext = <T>(\n ctx: ObservabilityContext,\n fn: () => T | Promise<T>,\n): T | Promise<T> => als.run(ctx, fn);\n\n/** Returns the currently-active context, or `undefined` outside one. */\nexport const getCurrentContext = (): ObservabilityContext | undefined => als.getStore();\n"],"mappings":";;;;;;;AAgDA,MAAa,sBAAuC;CAClD,eAAqB,CAAC;CACtB,aAAmB,CAAC;CACpB,iBAAuB,CAAC;AAC1B;;;;;;;;;;;;;;ACLA,IAAa,+BAAb,MAAqE;CACnE,YAAuC,CAAC;CACxC,UAAqC,CAAC;CACtC,cAAyC,CAAC;CAE1C,QAAQ,MAAc,OAAe,SAA2C,CAAC,GAAS;EACxF,KAAKA,UAAU,KAAK;GAAE;GAAM;GAAO;EAAO,CAAC;CAC7C;CACA,MAAM,MAAc,OAAe,SAA2C,CAAC,GAAS;EACtF,KAAKC,QAAQ,KAAK;GAAE;GAAM;GAAO;EAAO,CAAC;CAC3C;CACA,UAAU,MAAc,OAAe,SAA2C,CAAC,GAAS;EAC1F,KAAKC,YAAY,KAAK;GAAE;GAAM;GAAO;EAAO,CAAC;CAC/C;;;;;;;;;CAUA,WAA4B;EAC1B,OAAO;GACL,UAAU,KAAKF,UAAU,MAAM;GAC/B,QAAQ,KAAKC,QAAQ,MAAM;GAC3B,YAAY,KAAKC,YAAY,MAAM;EACrC;CACF;;;;;;;;;;;;;;;;CAiBA,YAA4B;EAC1B,MAAM,MAAsB,CAAC;EAG7B,KAAK,MAAM,OAAO,KAAKF,WAAW;GAMhC,MAAM,MAAM,IAAI,KAAK,SAAS,QAAQ,IAAI,IAAI,OAAO,GAAG,IAAI,KAAK;GACjE,IAAI,QAAQ,IAAI,QAAQ,KAAK,IAAI;EACnC;EAIA,KAAK,MAAM,OAAO,KAAKC,SACrB,IAAI,IAAI,QAAQ,IAAI;EAItB,MAAM,0BAAU,IAAI,IAA4C;EAChE,KAAK,MAAM,OAAO,KAAKC,aAAa;GAClC,IAAI,MAAM,QAAQ,IAAI,IAAI,IAAI;GAC9B,IAAI,QAAQ,KAAA,GAAW;IACrB,MAAM;KAAE,OAAO;KAAG,KAAK;IAAE;IACzB,QAAQ,IAAI,IAAI,MAAM,GAAG;GAC3B;GACA,IAAI,SAAS;GACb,IAAI,OAAO,IAAI;EACjB;EACA,KAAK,MAAM,CAAC,MAAM,EAAE,OAAO,UAAU,SAAS;GAC5C,IAAI,GAAG,KAAK,WAAW;GACvB,IAAI,GAAG,KAAK,SAAS;EACvB;EAEA,OAAO;CACT;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACzCA,MAAa,8BACX,OAAiC,CAAC,OACR;CAC1B,YAAY,KAAK,cAAc,OAAO,WAAW;CACjD,YAAY,YAAY,IAAI;CAC5B,wBAAQ,IAAI,IAAI;CAChB,UAAU,KAAK,YAAY,IAAI,6BAA6B;AAC9D;;;;;;AAOA,MAAM,MAAM,IAAI,kBAAwC;;;;;;;;;;;;;;AAexD,MAAa,kBACX,KACA,OACmB,IAAI,IAAI,KAAK,EAAE;;AAGpC,MAAa,0BAA4D,IAAI,SAAS"}
|