@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
package/dist/API.md
CHANGED
|
@@ -17,18 +17,31 @@ directory remain the source of truth (the bundler chunks them across
|
|
|
17
17
|
noisy to read flat — read this first, drop into the `.d.ts` chunks
|
|
18
18
|
only for exact signatures).
|
|
19
19
|
|
|
20
|
+
The public surface is intentionally small and **closed**: the absence
|
|
21
|
+
of a method is a design choice, not an undocumented gap. Every
|
|
22
|
+
unsupported operation is a compile error — the type system enforces the
|
|
23
|
+
vocabulary rather than surfacing a runtime "not implemented", so an agent
|
|
24
|
+
reaches the correct call zero-shot without inventing ceremony the kernel
|
|
25
|
+
doesn't support. The predicate operator set is the concrete example
|
|
26
|
+
(see [Predicates](#predicates)).
|
|
27
|
+
|
|
20
28
|
## Imports cheat sheet
|
|
21
29
|
|
|
22
30
|
```ts
|
|
23
31
|
// Server kernel
|
|
24
32
|
import {
|
|
25
33
|
Db,
|
|
26
|
-
MemoryStorage,
|
|
27
|
-
type Collection,
|
|
34
|
+
MemoryStorage, // in-memory `Storage`; canonical for tests
|
|
35
|
+
type Collection,
|
|
36
|
+
type Query,
|
|
37
|
+
type Predicate, // equality-object `.where(...)` form
|
|
38
|
+
type PredicateArg, // `.where(...)` arg: object or builder callback
|
|
28
39
|
type DocumentData,
|
|
29
|
-
type RowOf,
|
|
30
|
-
|
|
31
|
-
|
|
40
|
+
type RowOf,
|
|
41
|
+
type CollectionNames, // row-shape inference from a bound config
|
|
42
|
+
BaerlyError,
|
|
43
|
+
type BaerlyErrorCode,
|
|
44
|
+
defineConfig, // narrower; root barrel
|
|
32
45
|
} from "@gusto/baerly-storage";
|
|
33
46
|
|
|
34
47
|
// Scaffold-aware config (`app`, `tenant`, `target`, `domain`, …)
|
|
@@ -43,18 +56,27 @@ import { createRouter, mapError } from "@gusto/baerly-storage/http";
|
|
|
43
56
|
// Browser / Node client (HTTP)
|
|
44
57
|
import {
|
|
45
58
|
createBaerlyClient,
|
|
46
|
-
type BaerlyClient,
|
|
47
|
-
type
|
|
59
|
+
type BaerlyClient,
|
|
60
|
+
type ClientCollection,
|
|
61
|
+
type ClientQuery,
|
|
62
|
+
type TerminalOptions,
|
|
63
|
+
type Fetcher,
|
|
64
|
+
type Predicate,
|
|
65
|
+
type PredicateArg,
|
|
48
66
|
} from "@gusto/baerly-storage/client";
|
|
49
67
|
|
|
50
68
|
// Auth verifiers
|
|
51
|
-
import {
|
|
52
|
-
sharedSecret, cloudflareAccess, bearerJwt,
|
|
53
|
-
} from "@gusto/baerly-storage/auth";
|
|
69
|
+
import { sharedSecret, cloudflareAccess, bearerJwt } from "@gusto/baerly-storage/auth";
|
|
54
70
|
|
|
55
71
|
// Adapters
|
|
56
72
|
import { baerlyWorker, r2BindingStorage } from "@gusto/baerly-storage/cloudflare";
|
|
57
|
-
import {
|
|
73
|
+
import {
|
|
74
|
+
baerlyNode,
|
|
75
|
+
s3Storage,
|
|
76
|
+
r2Storage,
|
|
77
|
+
minioStorage,
|
|
78
|
+
gcsStorage,
|
|
79
|
+
} from "@gusto/baerly-storage/node";
|
|
58
80
|
|
|
59
81
|
// Dev helpers (Vite, local-fs storage)
|
|
60
82
|
import { baerlyDevAuth, loadDevVars } from "@gusto/baerly-storage/dev/vite";
|
|
@@ -63,6 +85,8 @@ import { LocalFsStorage } from "@gusto/baerly-storage/dev";
|
|
|
63
85
|
|
|
64
86
|
## `Db.create({ storage, app, tenant, config? })`
|
|
65
87
|
|
|
88
|
+
*When NOT to use: in a browser/SPA — use `createBaerlyClient` (HTTP) instead; `Db` is the in-process server surface.*
|
|
89
|
+
|
|
66
90
|
One `Db` per `(app, tenant)` request. The constructor is private —
|
|
67
91
|
always go through `Db.create`. Collections are auto-provisioned on first
|
|
68
92
|
write (no `ensureCollection` step).
|
|
@@ -72,11 +96,11 @@ import { Db, MemoryStorage } from "@gusto/baerly-storage";
|
|
|
72
96
|
import config from "./baerly.config";
|
|
73
97
|
|
|
74
98
|
const db = Db.create({
|
|
75
|
-
storage: new MemoryStorage(),
|
|
99
|
+
storage: new MemoryStorage(), // or `s3Storage(...)`, `r2BindingStorage(env.BUCKET)`, …
|
|
76
100
|
app: "tickets",
|
|
77
101
|
tenant: "acme-co",
|
|
78
|
-
config,
|
|
79
|
-
|
|
102
|
+
config, // ← optional. Wires schemas + indexes
|
|
103
|
+
// AND narrows `db.collection(name)` types.
|
|
80
104
|
});
|
|
81
105
|
|
|
82
106
|
await db.collection("tickets").insert({ title: "first ticket", status: "open" });
|
|
@@ -88,7 +112,7 @@ backs an independent in-process bucket — two `Db` instances built
|
|
|
88
112
|
against two `new MemoryStorage()`s see two empty, isolated stores.
|
|
89
113
|
This is what makes it the canonical test fixture: one fresh instance
|
|
90
114
|
per test gives a hermetic bucket without `beforeEach` cleanup. Pass
|
|
91
|
-
the
|
|
115
|
+
the _same_ `MemoryStorage` instance to multiple `Db` constructors
|
|
92
116
|
when you want two writers contending on one bucket.
|
|
93
117
|
|
|
94
118
|
Full `Db.create` config:
|
|
@@ -112,7 +136,9 @@ import type { Db } from "@gusto/baerly-storage";
|
|
|
112
136
|
import type config from "./baerly.config";
|
|
113
137
|
|
|
114
138
|
let cached: Db<typeof config> | undefined;
|
|
115
|
-
export function setDbForTesting(db: Db<typeof config>) {
|
|
139
|
+
export function setDbForTesting(db: Db<typeof config>) {
|
|
140
|
+
cached = db;
|
|
141
|
+
}
|
|
116
142
|
```
|
|
117
143
|
|
|
118
144
|
The narrowed `Db<typeof config>` carries the same `collection(name)`
|
|
@@ -121,6 +147,8 @@ overloads as the inferred return; `Db` (no parameter) widens to
|
|
|
121
147
|
|
|
122
148
|
## `db.collection(name)` → `Collection<T>`
|
|
123
149
|
|
|
150
|
+
*When NOT to use: from the browser — call collection verbs over HTTP via `createBaerlyClient`.*
|
|
151
|
+
|
|
124
152
|
`Collection<T>` carries the common-case verbs directly (collection-level
|
|
125
153
|
reads plus by-primary-key mutations). Modifiers (`where`, `order`,
|
|
126
154
|
`limit`) return a `Query<T>` for bulk-by-predicate work. Terminals fire
|
|
@@ -135,7 +163,7 @@ interface Collection<T extends DocumentData = DocumentData> {
|
|
|
135
163
|
count(): Promise<number>;
|
|
136
164
|
get(id: string): Promise<T | undefined>;
|
|
137
165
|
// Modifiers — return Query<T>.
|
|
138
|
-
where(predicate: PredicateArg<T>): Query<T>;
|
|
166
|
+
where(predicate: PredicateArg<T>): Query<T>; // PredicateArg = Predicate<T> | (q => PredicateBuilder<T>)
|
|
139
167
|
order(spec: OrderSpec<T>): Query<T>;
|
|
140
168
|
limit(n: number): Query<T>;
|
|
141
169
|
// Writes — by primary key.
|
|
@@ -162,7 +190,8 @@ interface Query<T> extends /* Collection<T>'s modifiers */ {
|
|
|
162
190
|
`replace` is by-id only — `Collection<T>.replace(id, doc)` throws
|
|
163
191
|
`NotFound` on missing id. There is no predicate-form `.replace(doc)`
|
|
164
192
|
on `Query<T>`: a strict-cardinality-1 verb is redundant ceremony to
|
|
165
|
-
the by-id form (
|
|
193
|
+
the by-id form (the public surface is additive-only locked, so a second
|
|
194
|
+
type-valid path to one capability is redundancy).
|
|
166
195
|
|
|
167
196
|
### Predicates
|
|
168
197
|
|
|
@@ -189,11 +218,15 @@ paths (`author._id`) on referenced documents are still allowed.
|
|
|
189
218
|
```ts
|
|
190
219
|
db.collection("tickets").where({ status: "open" }).all();
|
|
191
220
|
db.collection("tickets").where({ "assignee.team": "platform" }).all();
|
|
192
|
-
db.collection("tickets")
|
|
193
|
-
|
|
221
|
+
db.collection("tickets")
|
|
222
|
+
.where((q) => q.gte("count", 1).lt("count", 10))
|
|
223
|
+
.all();
|
|
224
|
+
db.collection("tickets")
|
|
225
|
+
.where((q) => q.in("status", ["open", "pending"]))
|
|
226
|
+
.all();
|
|
194
227
|
db.collection("tickets")
|
|
195
228
|
.where({ status: "open" })
|
|
196
|
-
.where(q => q.gte("priority", 5))
|
|
229
|
+
.where((q) => q.gte("priority", 5))
|
|
197
230
|
.all();
|
|
198
231
|
```
|
|
199
232
|
|
|
@@ -204,10 +237,12 @@ db.collection("tickets")
|
|
|
204
237
|
```ts
|
|
205
238
|
interface PredicateClause {
|
|
206
239
|
readonly op: "eq" | "gt" | "gte" | "lt" | "lte" | "in";
|
|
207
|
-
readonly field: string;
|
|
208
|
-
readonly value: DocumentValue | ReadonlyArray<DocumentValue>;
|
|
240
|
+
readonly field: string; // top-level or dotted path
|
|
241
|
+
readonly value: DocumentValue | ReadonlyArray<DocumentValue>; // array iff op === "in"
|
|
242
|
+
}
|
|
243
|
+
interface PredicateWire {
|
|
244
|
+
readonly clauses: ReadonlyArray<PredicateClause>;
|
|
209
245
|
}
|
|
210
|
-
interface PredicateWire { readonly clauses: ReadonlyArray<PredicateClause>; }
|
|
211
246
|
```
|
|
212
247
|
|
|
213
248
|
Example: `.where({ status: "open" })` → `{"clauses":[{"op":"eq","field":"status","value":"open"}]}`.
|
|
@@ -227,7 +262,9 @@ await db.collection("tickets").update("01HQ...", { status: "closed" });
|
|
|
227
262
|
// → { modified: 1 } (JSON-merge-patch RFC 7386; `null` deletes a field)
|
|
228
263
|
|
|
229
264
|
await db.collection("tickets").replace("01HQ...", {
|
|
230
|
-
_id: "01HQ...",
|
|
265
|
+
_id: "01HQ...",
|
|
266
|
+
status: "open",
|
|
267
|
+
title: "rewrite",
|
|
231
268
|
});
|
|
232
269
|
// → void (whole-document overwrite)
|
|
233
270
|
|
|
@@ -235,7 +272,8 @@ await db.collection("tickets").delete("01HQ...");
|
|
|
235
272
|
// → { deleted: 1 } (or `{ deleted: 0 }` if the id is unknown)
|
|
236
273
|
|
|
237
274
|
// Bulk-by-predicate (Query<T>):
|
|
238
|
-
await db
|
|
275
|
+
await db
|
|
276
|
+
.collection("tickets")
|
|
239
277
|
.where({ status: "open" })
|
|
240
278
|
.update({ status: "closed", closed_at: new Date().toISOString() });
|
|
241
279
|
// → { modified: N }
|
|
@@ -280,7 +318,10 @@ Two ways to get a typed row:
|
|
|
280
318
|
the construction site for a narrower row shape:
|
|
281
319
|
```ts
|
|
282
320
|
import type { Collection, DocumentData } from "@gusto/baerly-storage";
|
|
283
|
-
interface Bookmark extends DocumentData {
|
|
321
|
+
interface Bookmark extends DocumentData {
|
|
322
|
+
_id: string;
|
|
323
|
+
url: string;
|
|
324
|
+
}
|
|
284
325
|
const bookmarks = db.collection("bookmarks") as Collection<Bookmark>;
|
|
285
326
|
await bookmarks.all();
|
|
286
327
|
```
|
|
@@ -298,23 +339,23 @@ try {
|
|
|
298
339
|
await db.collection("tickets").insert({ title: "hi" });
|
|
299
340
|
} catch (err) {
|
|
300
341
|
if (err instanceof BaerlyError && err.code === "Conflict") {
|
|
301
|
-
// CAS
|
|
342
|
+
// Check err.retriable: CAS conflicts can retry; duplicate _id cannot.
|
|
302
343
|
}
|
|
303
344
|
}
|
|
304
345
|
```
|
|
305
346
|
|
|
306
|
-
| `code` | HTTP | When
|
|
307
|
-
| ------------------------ | ---- |
|
|
308
|
-
| `InvalidConfig` | 400 | Caller config/input is invalid (bad bucket, malformed predicate, …)
|
|
309
|
-
| `NetworkError` | 502 | Transport (S3 5xx, retries exhausted)
|
|
310
|
-
| `AccessDenied` | 403 | S3 403 or bucket policy denied
|
|
311
|
-
| `InvalidResponse` | 502 | Server returned unparseable body
|
|
312
|
-
| `Internal` | 500 | Invariant violation — file a bug
|
|
313
|
-
| `SchemaError` |
|
|
314
|
-
| `Conflict` | 409 | CAS retry budget exhausted, or `insert` `_id` collision
|
|
315
|
-
| `Unauthorized` | 401 | Verifier returned no identity
|
|
316
|
-
| `NotFound` | 404 | Row by id not found
|
|
317
|
-
| `PayloadTooLarge` | 413 | Body > 1 MiB cap
|
|
347
|
+
| `code` | HTTP | When |
|
|
348
|
+
| ------------------------ | ---- | ---------------------------------------------------------------------- |
|
|
349
|
+
| `InvalidConfig` | 400 | Caller config/input is invalid (bad bucket, malformed predicate, …) |
|
|
350
|
+
| `NetworkError` | 502 | Transport (S3 5xx, retries exhausted) |
|
|
351
|
+
| `AccessDenied` | 403 | S3 403 or bucket policy denied |
|
|
352
|
+
| `InvalidResponse` | 502 | Server returned unparseable body |
|
|
353
|
+
| `Internal` | 500 | Invariant violation — file a bug |
|
|
354
|
+
| `SchemaError` | 400 | JSON shape invalid or bound schema rejected the doc |
|
|
355
|
+
| `Conflict` | 409 | CAS retry budget exhausted, or `insert` `_id` collision |
|
|
356
|
+
| `Unauthorized` | 401 | Verifier returned no identity |
|
|
357
|
+
| `NotFound` | 404 | Row by id not found |
|
|
358
|
+
| `PayloadTooLarge` | 413 | Body > 1 MiB cap |
|
|
318
359
|
| `UnsatisfiablePredicate` | 400 | Predicate is well-formed but contradicts itself (empty `in` set, etc.) |
|
|
319
360
|
|
|
320
361
|
### Mapping errors to HTTP yourself
|
|
@@ -345,10 +386,16 @@ app.post("/notes", async (c) => {
|
|
|
345
386
|
});
|
|
346
387
|
```
|
|
347
388
|
|
|
348
|
-
`mapError` accepts any thrown value
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
389
|
+
`mapError` accepts any thrown value. Caller-facing errors such as
|
|
390
|
+
`SchemaError`, `NotFound`, `PayloadTooLarge`, predicate `InvalidConfig`,
|
|
391
|
+
and non-retriable caller `Conflict`s keep their actionable message.
|
|
392
|
+
Storage/server diagnostics such as `Internal`, `NetworkError`,
|
|
393
|
+
`InvalidResponse`, storage `AccessDenied`, storage `InvalidConfig`, and
|
|
394
|
+
retriable CAS/storage `Conflict`s keep their code/status/retriable shape
|
|
395
|
+
but use a generic wire message; the full thrown error is logged via the
|
|
396
|
+
observability channel. Non-`BaerlyError` throws fall through to
|
|
397
|
+
`500 Internal` with the message redacted. The HTTP status / envelope shape
|
|
398
|
+
is locked.
|
|
352
399
|
|
|
353
400
|
## `defineConfig({ app, tenant, target, collections })`
|
|
354
401
|
|
|
@@ -361,7 +408,7 @@ import { defineConfig } from "@gusto/baerly-storage/config";
|
|
|
361
408
|
import { z } from "zod";
|
|
362
409
|
|
|
363
410
|
const TicketSchema = z.object({
|
|
364
|
-
_id: z.string(),
|
|
411
|
+
_id: z.string(), // required — see callout below
|
|
365
412
|
status: z.enum(["open", "closed"]),
|
|
366
413
|
title: z.string().min(1),
|
|
367
414
|
tags: z.array(z.string()).optional(),
|
|
@@ -373,8 +420,8 @@ export default defineConfig({
|
|
|
373
420
|
target: "cloudflare",
|
|
374
421
|
collections: {
|
|
375
422
|
tickets: {
|
|
376
|
-
schema: TicketSchema,
|
|
377
|
-
indexes: [{ name: "by_status", on: "status" }],
|
|
423
|
+
schema: TicketSchema, // StandardSchema v1
|
|
424
|
+
indexes: [{ name: "by_status", on: "status" }], // single-field equality
|
|
378
425
|
},
|
|
379
426
|
},
|
|
380
427
|
});
|
|
@@ -384,7 +431,9 @@ Schemas: any [StandardSchema v1](https://standardschema.dev) validator
|
|
|
384
431
|
(Zod 3.24+, Valibot 0.36+, ArkType 2.0+). Validation runs on the
|
|
385
432
|
post-image: `update` and `replace` see the full doc, not just the
|
|
386
433
|
patch. Failures → `BaerlyError{code:"SchemaError", issues:[…]}`,
|
|
387
|
-
mapped to HTTP
|
|
434
|
+
mapped to HTTP 400. Validation is write-path only — reads, export, and
|
|
435
|
+
replay never re-validate, so a schema change never retroactively rejects
|
|
436
|
+
existing rows.
|
|
388
437
|
|
|
389
438
|
**Author `_id` as required, not `.optional()`.** The validator runs
|
|
390
439
|
on the post-image — by the time it fires, the server has already
|
|
@@ -396,7 +445,7 @@ still accepts a doc without `_id` (the public signature is
|
|
|
396
445
|
required does not break the "omit and let the server mint it" path.
|
|
397
446
|
The win is on the read side: `db.collection("tickets").all()` is
|
|
398
447
|
typed `Ticket[]` with `_id: string` (required), so route handlers
|
|
399
|
-
and response schemas don't need a parallel "_id-required" row type.
|
|
448
|
+
and response schemas don't need a parallel "\_id-required" row type.
|
|
400
449
|
|
|
401
450
|
`_id` is server-minted (UUIDv7, sorts by mint time) — there is no
|
|
402
451
|
exported id generator, and minting one client-side is unsupported.
|
|
@@ -411,12 +460,14 @@ preserved).
|
|
|
411
460
|
|
|
412
461
|
## `createBaerlyClient` (browser / Node HTTP client)
|
|
413
462
|
|
|
463
|
+
*When NOT to use: server-side in the same process as `Db` — call `Db`/`Collection` directly; the client is for out-of-process / browser callers.*
|
|
464
|
+
|
|
414
465
|
```ts
|
|
415
|
-
import type config from "./baerly.config";
|
|
466
|
+
import type config from "./baerly.config"; // type-only — server adapter stays out of the SPA bundle
|
|
416
467
|
const client = createBaerlyClient<typeof config>({
|
|
417
|
-
baseUrl: "",
|
|
418
|
-
headers: { Authorization: "Bearer …" },
|
|
419
|
-
fetch: customFetcher,
|
|
468
|
+
baseUrl: "", // same-origin
|
|
469
|
+
headers: { Authorization: "Bearer …" }, // wrap `fetch` for per-call refresh
|
|
470
|
+
fetch: customFetcher, // optional Fetcher middleware
|
|
420
471
|
});
|
|
421
472
|
|
|
422
473
|
await client.collection("tickets").where({ status: "open" }).all();
|
|
@@ -427,7 +478,7 @@ trailing `TerminalOptions`:
|
|
|
427
478
|
|
|
428
479
|
```ts
|
|
429
480
|
interface TerminalOptions {
|
|
430
|
-
signal?: AbortSignal;
|
|
481
|
+
signal?: AbortSignal; // cancels this specific request
|
|
431
482
|
}
|
|
432
483
|
|
|
433
484
|
await client.collection("tickets").all({ signal: ac.signal });
|
|
@@ -453,12 +504,12 @@ interface SinceResponse {
|
|
|
453
504
|
}
|
|
454
505
|
|
|
455
506
|
interface LogEntry {
|
|
456
|
-
readonly lsn: string;
|
|
457
|
-
readonly commit_ts: string;
|
|
507
|
+
readonly lsn: string; // opaque cursor; lex-asc, monotonic
|
|
508
|
+
readonly commit_ts: string; // ISO-8601 ms
|
|
458
509
|
readonly op: "I" | "U" | "D";
|
|
459
510
|
readonly collection: string;
|
|
460
|
-
readonly doc_id: string;
|
|
461
|
-
readonly after?: DocumentData;
|
|
511
|
+
readonly doc_id: string; // I/U/D only
|
|
512
|
+
readonly after?: DocumentData; // I/U — post-image (Debezium's `after`)
|
|
462
513
|
readonly session: string;
|
|
463
514
|
readonly seq: number;
|
|
464
515
|
// `before` / `key_old` / `origin` are optional; see `LogEntry` JSDoc.
|
|
@@ -466,7 +517,7 @@ interface LogEntry {
|
|
|
466
517
|
```
|
|
467
518
|
|
|
468
519
|
**Cursor priming.** First call: pass `cursor=` (empty string). The
|
|
469
|
-
server's fast path returns immediately
|
|
520
|
+
server's fast path returns immediately _iff_ the log already has
|
|
470
521
|
entries for this collection — you get `events: [...]` and the
|
|
471
522
|
last entry's `lsn` as `next_cursor`. **If the collection is empty,
|
|
472
523
|
the first call blocks for the full long-poll budget (~25 s) before
|
|
@@ -498,10 +549,12 @@ shrink `sinceTimeoutMs` in production code paths — it multiplies the
|
|
|
498
549
|
R2 class-A op count per idle long-poll connection.
|
|
499
550
|
|
|
500
551
|
React applications use `@gusto/baerly-storage/client/react` (see next
|
|
501
|
-
section) instead of poking `/v1/since` by hand
|
|
502
|
-
subscribers in other UI frameworks
|
|
503
|
-
|
|
504
|
-
|
|
552
|
+
section) instead of poking `/v1/since` by hand. Hand-rolled
|
|
553
|
+
subscribers in other UI frameworks `fetch` this endpoint directly:
|
|
554
|
+
loop, `fetch`-ing with `cursor=` (empty) first, then threading the
|
|
555
|
+
returned `next_cursor` back as `cursor` on each subsequent call (the
|
|
556
|
+
cursor is opaque — treat it as a string). The wire shape above is the
|
|
557
|
+
public contract; there is no exported cursor-tailing helper.
|
|
505
558
|
|
|
506
559
|
## React: `createBaerlyReact`
|
|
507
560
|
|
|
@@ -523,8 +576,7 @@ import { createBaerlyReact } from "@gusto/baerly-storage/client/react";
|
|
|
523
576
|
import config from "../../baerly.config.ts";
|
|
524
577
|
|
|
525
578
|
export const client = createBaerlyClient({ baseUrl: "", config });
|
|
526
|
-
export const { BaerlyProvider, useQuery, useMutation } =
|
|
527
|
-
createBaerlyReact<typeof config>();
|
|
579
|
+
export const { BaerlyProvider, useQuery, useMutation } = createBaerlyReact<typeof config>();
|
|
528
580
|
```
|
|
529
581
|
|
|
530
582
|
```tsx
|
|
@@ -534,7 +586,7 @@ import { BaerlyProvider, client, useMutation, useQuery } from "./client.ts";
|
|
|
534
586
|
// 1. Wrap your app once.
|
|
535
587
|
<BaerlyProvider client={client}>
|
|
536
588
|
<App />
|
|
537
|
-
</BaerlyProvider
|
|
589
|
+
</BaerlyProvider>;
|
|
538
590
|
|
|
539
591
|
// 2. useQuery(cb, deps) — the callback receives the bound client and
|
|
540
592
|
// returns a ClientCollection / ClientQuery chain. Re-runs on deps
|
|
@@ -548,9 +600,7 @@ const result = useQuery((c) => c.collection("notes").all(), []);
|
|
|
548
600
|
// 3. useQuery.skip — short-circuit to status: "skipped", no
|
|
549
601
|
// subscription. Use for conditional or dependent reads.
|
|
550
602
|
const filtered = useQuery(
|
|
551
|
-
(c) => filter === "all"
|
|
552
|
-
? useQuery.skip
|
|
553
|
-
: c.collection("notes").where({ status: filter }).all(),
|
|
603
|
+
(c) => (filter === "all" ? useQuery.skip : c.collection("notes").where({ status: filter }).all()),
|
|
554
604
|
[filter],
|
|
555
605
|
);
|
|
556
606
|
|
|
@@ -572,12 +622,12 @@ await mutate((c) => c.collection("notes").insert({ body }));
|
|
|
572
622
|
The JS SDK is the canonical path. Reach for `curl` only when
|
|
573
623
|
debugging. Mutation bodies are wrapped:
|
|
574
624
|
|
|
575
|
-
| Route
|
|
576
|
-
|
|
|
577
|
-
| `POST /v1/c/:collection`
|
|
578
|
-
| `PATCH /v1/c/:collection/:id`
|
|
579
|
-
| `PUT /v1/c/:collection/:id`
|
|
580
|
-
| `DELETE /v1/c/:collection/:id`
|
|
625
|
+
| Route | Body | Response |
|
|
626
|
+
| ------------------------------ | ----------------- | ---------------- |
|
|
627
|
+
| `POST /v1/c/:collection` | `{"doc":{...}}` | `201 {_id}` |
|
|
628
|
+
| `PATCH /v1/c/:collection/:id` | `{"patch":{...}}` | `200 {modified}` |
|
|
629
|
+
| `PUT /v1/c/:collection/:id` | `{"doc":{...}}` | `200 {modified}` |
|
|
630
|
+
| `DELETE /v1/c/:collection/:id` | — | `204` |
|
|
581
631
|
|
|
582
632
|
Reads (`GET /v1/c/:collection[/:id]`, `GET /v1/count?collection=…`,
|
|
583
633
|
`GET /v1/since?collection=…&cursor=…`) take no body and return
|
|
@@ -596,16 +646,26 @@ If your probe path is fixed to something else (a k8s readiness path,
|
|
|
596
646
|
say), put a custom route in front of the kernel (see "Recipe — custom
|
|
597
647
|
routes in front of `baerlyNode`" below).
|
|
598
648
|
|
|
649
|
+
### Machine contract (`GET /v1/spec`)
|
|
650
|
+
|
|
651
|
+
`baerlyWorker` and `baerlyNode` both mount an anonymous
|
|
652
|
+
`GET /v1/spec` → the machine-readable contract IR (error codes +
|
|
653
|
+
HTTP status, predicate operators, method/route tables) — the same
|
|
654
|
+
data shipped as `dist/baerly.spec.json`. It runs the verifier
|
|
655
|
+
tolerantly: an unauthenticated probe gets the static contract (no
|
|
656
|
+
401), and a request that the verifier accepts additionally gets a
|
|
657
|
+
`collections` array of declared collection + index names.
|
|
658
|
+
|
|
599
659
|
### Read modifiers (query params)
|
|
600
660
|
|
|
601
661
|
`GET /v1/c/:collection` accepts three JSON-encoded query params; all are
|
|
602
662
|
optional and compose:
|
|
603
663
|
|
|
604
|
-
| Param
|
|
605
|
-
|
|
|
606
|
-
| `?where=`
|
|
607
|
-
| `?order=`
|
|
608
|
-
| `?limit=`
|
|
664
|
+
| Param | Encodes | Wire example |
|
|
665
|
+
| --------- | ----------------------------------------- | ----------------------------------------- |
|
|
666
|
+
| `?where=` | `PredicateWire` (see "Wire format" above) | `?where=%7B%22clauses%22%3A%5B%5D%7D` |
|
|
667
|
+
| `?order=` | `{ [field]: "asc" \| "desc" }` | `?order=%7B%22sent_at%22%3A%22desc%22%7D` |
|
|
668
|
+
| `?limit=` | bare integer (no JSON wrapper) | `?limit=50` |
|
|
609
669
|
|
|
610
670
|
`?order=` and `?where=` are JSON, **not** Rails-style `field:asc` —
|
|
611
671
|
the kernel `JSON.parse`s them and returns `400 SchemaError` on a flat
|
|
@@ -616,6 +676,8 @@ client.
|
|
|
616
676
|
|
|
617
677
|
## Adapter factories
|
|
618
678
|
|
|
679
|
+
*On Cloudflare Workers use `r2BindingStorage(env.BUCKET)` (the R2 binding), NOT the S3-credentials factory — credential-based factories assume `fetch` + Node TLS, not the Workers runtime.*
|
|
680
|
+
|
|
619
681
|
```ts
|
|
620
682
|
// Cloudflare Worker entry
|
|
621
683
|
import { baerlyWorker } from "@gusto/baerly-storage/cloudflare";
|
|
@@ -624,8 +686,18 @@ export default baerlyWorker((env) => ({
|
|
|
624
686
|
// scheduled?: (controller, env, ctx) => … // opt-in cron handler
|
|
625
687
|
}));
|
|
626
688
|
|
|
627
|
-
// Node listener entry (any host that runs `node server.js`)
|
|
628
|
-
|
|
689
|
+
// Node listener entry (any host that runs `node server.js`).
|
|
690
|
+
// resolveStorageFromEnv() is the safe default selector: R2_ACCOUNT_ID → R2,
|
|
691
|
+
// BUCKET → S3, else local-fs (dev only). It REFUSES to start in a detected
|
|
692
|
+
// deployment with no bucket — never a silent in-memory/local-fs fallback,
|
|
693
|
+
// which is how hand-rolled selectors ship data loss to production.
|
|
694
|
+
// (assertStorageReachable(storage) adds an opt-in boot-time CAS probe.)
|
|
695
|
+
import { baerlyNode, resolveStorageFromEnv } from "@gusto/baerly-storage/node";
|
|
696
|
+
const { storage, label } = resolveStorageFromEnv();
|
|
697
|
+
baerlyNode({ storage, webRoot: "dist/client" }).listen(PORT); // webRoot optional
|
|
698
|
+
|
|
699
|
+
// Or select the store yourself (custom endpoint, MinIO, GCS, …):
|
|
700
|
+
import { s3Storage } from "@gusto/baerly-storage/node";
|
|
629
701
|
baerlyNode({
|
|
630
702
|
storage: s3Storage({ bucket: "…", credentials: { … } }),
|
|
631
703
|
verifier: bearerJwt({ jwks, issuer, audience }),
|
|
@@ -664,7 +736,9 @@ export default defineConfig({
|
|
|
664
736
|
tenant: "main",
|
|
665
737
|
target: "cloudflare",
|
|
666
738
|
auth: "none", // dev only — production swaps to "shared-secret" or a custom Verifier
|
|
667
|
-
collections: {
|
|
739
|
+
collections: {
|
|
740
|
+
/* … */
|
|
741
|
+
},
|
|
668
742
|
});
|
|
669
743
|
|
|
670
744
|
// src/server/index.ts
|
|
@@ -673,16 +747,10 @@ import config from "../../baerly.config.ts";
|
|
|
673
747
|
export default baerlyWorker(() => ({ config }));
|
|
674
748
|
```
|
|
675
749
|
|
|
676
|
-
|
|
677
750
|
`s3Storage` / `r2Storage` / `minioStorage` / `gcsStorage` from
|
|
678
751
|
`@gusto/baerly-storage/node` are re-exports of one factory family — same
|
|
679
752
|
shape (bucket + credentials), all hide `aws4fetch` / `@xmldom/xmldom`
|
|
680
|
-
behind the package boundary.
|
|
681
|
-
`r2BindingStorage` from `@gusto/baerly-storage/cloudflare`**: that one takes
|
|
682
|
-
the platform-bound `R2Bucket` directly (`r2BindingStorage(env.BUCKET)`)
|
|
683
|
-
and is the only storage factory a Worker should reach for — the
|
|
684
|
-
credential-based factories assume `fetch` + Node TLS, not the Workers
|
|
685
|
-
runtime.
|
|
753
|
+
behind the package boundary.
|
|
686
754
|
|
|
687
755
|
### Verifier presets
|
|
688
756
|
|
|
@@ -692,11 +760,11 @@ returns `VerifierResult | null` (null = 401 unauth; thrown
|
|
|
692
760
|
`BaerlyError` = 500 operator fault — the dispatcher splits the
|
|
693
761
|
codes deliberately so on-call paging targets operator faults only).
|
|
694
762
|
|
|
695
|
-
| Preset | Identity source
|
|
696
|
-
| ------------------ |
|
|
697
|
-
| `sharedSecret` | `Authorization: Bearer <secret>` with constant-time compare
|
|
698
|
-
| `bearerJwt` | JWT over JWKS, `iss` + `aud` + `alg` allowlist
|
|
699
|
-
| `cloudflareAccess` | `Cf-Access-Jwt-Assertion` header (thin shim over `bearerJwt`)
|
|
763
|
+
| Preset | Identity source | Tenant derivation |
|
|
764
|
+
| ------------------ | ------------------------------------------------------------- | --------------------------------------------------------------------------------- |
|
|
765
|
+
| `sharedSecret` | `Authorization: Bearer <secret>` with constant-time compare | `tenantPrefix:` option (single-tenant only) |
|
|
766
|
+
| `bearerJwt` | JWT over JWKS, `iss` + `aud` + `alg` allowlist | Configurable `tenantClaim` (default `"tenant"`) or fixed `tenantPrefix:` override |
|
|
767
|
+
| `cloudflareAccess` | `Cf-Access-Jwt-Assertion` header (thin shim over `bearerJwt`) | Same as `bearerJwt` |
|
|
700
768
|
|
|
701
769
|
```ts
|
|
702
770
|
import { sharedSecret, bearerJwt, cloudflareAccess } from "@gusto/baerly-storage/auth";
|
|
@@ -711,8 +779,9 @@ Signature, audience, and expiry checks are still enforced; only
|
|
|
711
779
|
tenant derivation is replaced.
|
|
712
780
|
|
|
713
781
|
**Why a function and not a class?** The source repo's
|
|
714
|
-
`docs/
|
|
715
|
-
|
|
782
|
+
`docs/guide/auth.md` records the properties the shape upholds and the
|
|
783
|
+
rejected alternatives (class hierarchy, middleware chain, closed enum,
|
|
784
|
+
kernel-side composition).
|
|
716
785
|
|
|
717
786
|
## Observability
|
|
718
787
|
|
|
@@ -744,20 +813,20 @@ options.
|
|
|
744
813
|
|
|
745
814
|
### Field reference
|
|
746
815
|
|
|
747
|
-
| Field
|
|
748
|
-
|
|
|
749
|
-
| `request_id`
|
|
750
|
-
| `method` / `path` / `status`
|
|
751
|
-
| `cache_status`
|
|
752
|
-
| `duration_ms`
|
|
753
|
-
| `outcome`
|
|
754
|
-
| `db.storage.class_a_ops_total`
|
|
755
|
-
| `db.storage.class_b_ops_total`
|
|
756
|
-
| `db.storage.<op>.calls_total`
|
|
757
|
-
| `db.storage.<op>.duration_ms_sum` / `_count
|
|
758
|
-
| `db.write.class_a_ops_per_logical_write_*`
|
|
759
|
-
| `db.r2.put.412_total` / `429_total`
|
|
760
|
-
| `error.code` / `error.message` / `error.stack` | Failure-path only. `error.code` is `BaerlyErrorCode`.
|
|
816
|
+
| Field | Meaning |
|
|
817
|
+
| ---------------------------------------------- | ------------------------------------------------------------------------------------ |
|
|
818
|
+
| `request_id` | Correlation key. Set from `X-Request-Id` if provided, else minted fresh. |
|
|
819
|
+
| `method` / `path` / `status` | HTTP request line + response code. |
|
|
820
|
+
| `cache_status` | `"hit" \| "miss" \| "bypass"` — Cloudflare adapter only. Node adapter omits. |
|
|
821
|
+
| `duration_ms` | `performance.now()` delta, monotonic wall-clock. |
|
|
822
|
+
| `outcome` | `"read"` (GET <400), `"committed"` (non-GET <400), `"conflict"` (409), or `"error"`. |
|
|
823
|
+
| `db.storage.class_a_ops_total` | PUT + DELETE + LIST count. S3-pricing Class A — cost-dominant. |
|
|
824
|
+
| `db.storage.class_b_ops_total` | GET count. S3-pricing Class B. |
|
|
825
|
+
| `db.storage.<op>.calls_total` | Per-op breakdown for `get` / `put` / `delete` / `list`. |
|
|
826
|
+
| `db.storage.<op>.duration_ms_sum` / `_count` | Per-call duration histogram. |
|
|
827
|
+
| `db.write.class_a_ops_per_logical_write_*` | Writer's per-`commit()` Class-A-op count. |
|
|
828
|
+
| `db.r2.put.412_total` / `429_total` | CAS conflicts (412) and storage rate-limit hits (429). |
|
|
829
|
+
| `error.code` / `error.message` / `error.stack` | Failure-path only. `error.code` is `BaerlyErrorCode`. |
|
|
761
830
|
|
|
762
831
|
Class-A / Class-B totals are the load-bearing fields — the cost
|
|
763
832
|
model puts a per-request ceiling on Class-A ops and the canonical
|
|
@@ -765,12 +834,12 @@ line is how you verify a deployed service stays under it.
|
|
|
765
834
|
|
|
766
835
|
### Log levels
|
|
767
836
|
|
|
768
|
-
| Level | What lands
|
|
769
|
-
| ------- |
|
|
770
|
-
| `error` | `status >= 500` or an exception was thrown.
|
|
771
|
-
| `warn` | Adds 4xx canonical lines and explicit `warn` records.
|
|
772
|
-
| `info` | Default. Adds 2xx canonical lines and lifecycle events.
|
|
773
|
-
| `debug` | Adds per-storage-op events. **High volume**; off in production.
|
|
837
|
+
| Level | What lands |
|
|
838
|
+
| ------- | --------------------------------------------------------------- |
|
|
839
|
+
| `error` | `status >= 500` or an exception was thrown. |
|
|
840
|
+
| `warn` | Adds 4xx canonical lines and explicit `warn` records. |
|
|
841
|
+
| `info` | Default. Adds 2xx canonical lines and lifecycle events. |
|
|
842
|
+
| `debug` | Adds per-storage-op events. **High volume**; off in production. |
|
|
774
843
|
|
|
775
844
|
Set `LOG_LEVEL` env var or the typed `observability.level` factory
|
|
776
845
|
option. Sink wiring (Workers Analytics Engine, OTel, Datadog) lives
|
|
@@ -848,13 +917,14 @@ export default {
|
|
|
848
917
|
|
|
849
918
|
The client reads via the normal `GET /v1/c/messages` route and tails
|
|
850
919
|
via `GET /v1/since?collection=messages&cursor=…` — both still served by
|
|
851
|
-
`inner`. Only writes go through `/api/messages`.
|
|
920
|
+
`inner`. Only writes go through `/api/messages`. Reads stay uncapped and
|
|
921
|
+
tenant-wide — scope and clamp them in your route too (see RECIPES.md).
|
|
852
922
|
|
|
853
923
|
**Known limitations of this recipe.** The custom-route `Db.create` is
|
|
854
924
|
a second instance — it doesn't share `baerlyWorker`'s
|
|
855
925
|
`observableStorage(...)` wrapping (so custom-route writes don't land
|
|
856
926
|
in the canonical-line storage counters) or the read-cache invalidation
|
|
857
|
-
helper. For
|
|
927
|
+
helper. For small chat-shaped apps this is acceptable; the
|
|
858
928
|
observability gap is being tracked as a follow-up. If you also need
|
|
859
929
|
PATCH/PUT/DELETE on the same collection, repeat steps (1) and (2) for
|
|
860
930
|
each verb.
|
|
@@ -885,15 +955,13 @@ const inner = baerlyNode({
|
|
|
885
955
|
serve({
|
|
886
956
|
port: Number(process.env["PORT"] ?? 8080),
|
|
887
957
|
fetch: (req) =>
|
|
888
|
-
new URL(req.url).pathname === "/health-check"
|
|
889
|
-
? Response.json({ ok: true })
|
|
890
|
-
: inner.fetch(req),
|
|
958
|
+
new URL(req.url).pathname === "/health-check" ? Response.json({ ok: true }) : inner.fetch(req),
|
|
891
959
|
});
|
|
892
960
|
```
|
|
893
961
|
|
|
894
962
|
The handle's `fetch` is the documented embedding seam (it's also what
|
|
895
963
|
the Vite dev middleware and tests consume) — there's no separate
|
|
896
|
-
`createApp` to reach for. If you don't need a
|
|
964
|
+
`createApp` to reach for. If you don't need a _custom_ probe path,
|
|
897
965
|
skip all of this and point your platform at the built-in
|
|
898
966
|
`GET /v1/healthz` (see above).
|
|
899
967
|
|
|
@@ -924,7 +992,12 @@ the network. Three recipes cover the common cases.
|
|
|
924
992
|
```ts
|
|
925
993
|
import { createBaerlyClient, type Fetcher } from "@gusto/baerly-storage/client";
|
|
926
994
|
|
|
927
|
-
const withHooks =
|
|
995
|
+
const withHooks =
|
|
996
|
+
(
|
|
997
|
+
next: Fetcher,
|
|
998
|
+
onSuccess: (req: Request, res: Response) => void,
|
|
999
|
+
onError: (req: Request, err: unknown) => void,
|
|
1000
|
+
): Fetcher =>
|
|
928
1001
|
async (req) => {
|
|
929
1002
|
try {
|
|
930
1003
|
const res = await next(req);
|
|
@@ -938,7 +1011,8 @@ const withHooks = (next: Fetcher, onSuccess: (req: Request, res: Response) => vo
|
|
|
938
1011
|
|
|
939
1012
|
const client = createBaerlyClient({
|
|
940
1013
|
baseUrl: "https://api.example.com",
|
|
941
|
-
fetch: withHooks(
|
|
1014
|
+
fetch: withHooks(
|
|
1015
|
+
globalThis.fetch,
|
|
942
1016
|
(req, res) => log.info({ url: req.url, status: res.status }),
|
|
943
1017
|
(req, err) => log.error({ url: req.url, err }),
|
|
944
1018
|
),
|
|
@@ -952,7 +1026,8 @@ const client = createBaerlyClient({
|
|
|
952
1026
|
### Retry on transient failures (GET only)
|
|
953
1027
|
|
|
954
1028
|
```ts
|
|
955
|
-
const withRetry =
|
|
1029
|
+
const withRetry =
|
|
1030
|
+
(next: Fetcher, max = 3, baseMs = 100): Fetcher =>
|
|
956
1031
|
async (req) => {
|
|
957
1032
|
for (let i = 0; i < max - 1; i++) {
|
|
958
1033
|
const res = await next(req.clone());
|
|
@@ -973,7 +1048,8 @@ one-shot stream.
|
|
|
973
1048
|
### Refresh credentials on 401
|
|
974
1049
|
|
|
975
1050
|
```ts
|
|
976
|
-
const withAuthRefresh =
|
|
1051
|
+
const withAuthRefresh =
|
|
1052
|
+
(next: Fetcher, refresh: () => Promise<string>): Fetcher =>
|
|
977
1053
|
async (req) => {
|
|
978
1054
|
const res = await next(req.clone());
|
|
979
1055
|
if (res.status !== 401) return res;
|
|
@@ -1008,23 +1084,21 @@ once. Pick by what you want to observe.
|
|
|
1008
1084
|
|
|
1009
1085
|
## Anti-patterns
|
|
1010
1086
|
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
- Don't put `SHARED_SECRET` in the SPA bundle
|
|
1016
|
-
server-to-server-only; the dev path uses `baerlyDevAuth` to inject
|
|
1017
|
-
it server-side, the prod path uses CF Access (CF target) or
|
|
1018
|
-
`bearerJwt` (Node target).
|
|
1019
|
-
- Don't mutate `VerifierResult.tenantPrefix` between the verifier
|
|
1020
|
-
and `Db.create`. The dispatcher pins the tenant from the
|
|
1021
|
-
verifier's return value.
|
|
1087
|
+
A few that compile but are wrong (full list, keyed by the exact error
|
|
1088
|
+
string you see: `cat node_modules/@gusto/baerly-storage/dist/RECIPES.md`):
|
|
1089
|
+
|
|
1090
|
+
- Don't widen branded types (`UUID`, `ContentVersionId`) with `as string`.
|
|
1091
|
+
- Don't put `SHARED_SECRET` in the SPA bundle — it's server-to-server only.
|
|
1022
1092
|
|
|
1023
1093
|
## Where to look next
|
|
1024
1094
|
|
|
1095
|
+
- **A call you expected doesn't type-check?** The public surface is
|
|
1096
|
+
additive-only locked, but the rare breaking change carries an
|
|
1097
|
+
old→new migration in `dist/CHANGELOG.md` (`cat dist/CHANGELOG.md`). The
|
|
1098
|
+
`.d.ts` types are canonical; the changelog is the recovery path.
|
|
1025
1099
|
- Per-symbol JSDoc: read the `.d.ts` chunks in this directory
|
|
1026
1100
|
(`db-*.d.ts`, `index-*.d.ts`, `client-*.d.ts`, …) — the bundler
|
|
1027
1101
|
splits them; `cat dist/*.d.ts` gives the union.
|
|
1028
1102
|
- Theoretical foundations + cost model: the repository's `docs/`
|
|
1029
1103
|
tree (`docs/about/`, `docs/spec/`).
|
|
1030
|
-
-
|
|
1104
|
+
- Common mistakes & recipes: `cat node_modules/@gusto/baerly-storage/dist/RECIPES.md`; deeper guides in the repo's `docs/guide/`.
|