@volter/twin-upstash 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.
Files changed (162) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +202 -0
  3. package/api/src/fetch.ts +54 -0
  4. package/api/src/generated/surface.gen.json +1 -0
  5. package/api/src/generated/ui.gen.json +1 -0
  6. package/api/src/index.ts +19 -0
  7. package/api/src/key-gate.ts +30 -0
  8. package/api/src/manifest.ts +103 -0
  9. package/api/src/screens/developer-api.tsx +106 -0
  10. package/api/src/screens/qstash.tsx +99 -0
  11. package/api/src/screens/session.tsx +125 -0
  12. package/api/src/screens/teams.tsx +114 -0
  13. package/api/src/semantics/backups.ts +90 -0
  14. package/api/src/semantics/index.ts +191 -0
  15. package/api/src/semantics/shared.ts +42 -0
  16. package/api/src/semantics/teams.ts +108 -0
  17. package/api/src/semantics/time.ts +40 -0
  18. package/dist/api/src/fetch.d.ts +15 -0
  19. package/dist/api/src/fetch.js +44 -0
  20. package/dist/api/src/fetch.ts +54 -0
  21. package/dist/api/src/generated/surface.gen.json +1 -0
  22. package/dist/api/src/generated/ui.gen.json +1 -0
  23. package/dist/api/src/index.ts +19 -0
  24. package/dist/api/src/key-gate.d.ts +3 -0
  25. package/dist/api/src/key-gate.js +30 -0
  26. package/dist/api/src/key-gate.ts +30 -0
  27. package/dist/api/src/manifest.d.ts +2 -0
  28. package/dist/api/src/manifest.js +81 -0
  29. package/dist/api/src/manifest.ts +103 -0
  30. package/dist/api/src/screens/developer-api.d.ts +3 -0
  31. package/dist/api/src/screens/developer-api.js +101 -0
  32. package/dist/api/src/screens/developer-api.tsx +106 -0
  33. package/dist/api/src/screens/qstash.d.ts +3 -0
  34. package/dist/api/src/screens/qstash.js +92 -0
  35. package/dist/api/src/screens/qstash.tsx +99 -0
  36. package/dist/api/src/screens/session.d.ts +9 -0
  37. package/dist/api/src/screens/session.js +118 -0
  38. package/dist/api/src/screens/session.tsx +125 -0
  39. package/dist/api/src/screens/teams.d.ts +3 -0
  40. package/dist/api/src/screens/teams.js +99 -0
  41. package/dist/api/src/screens/teams.tsx +114 -0
  42. package/dist/api/src/semantics/backups.d.ts +7 -0
  43. package/dist/api/src/semantics/backups.js +75 -0
  44. package/dist/api/src/semantics/backups.ts +90 -0
  45. package/dist/api/src/semantics/index.d.ts +10 -0
  46. package/dist/api/src/semantics/index.js +191 -0
  47. package/dist/api/src/semantics/index.ts +191 -0
  48. package/dist/api/src/semantics/shared.d.ts +21 -0
  49. package/dist/api/src/semantics/shared.js +34 -0
  50. package/dist/api/src/semantics/shared.ts +42 -0
  51. package/dist/api/src/semantics/teams.d.ts +13 -0
  52. package/dist/api/src/semantics/teams.js +100 -0
  53. package/dist/api/src/semantics/teams.ts +108 -0
  54. package/dist/api/src/semantics/time.d.ts +2 -0
  55. package/dist/api/src/semantics/time.js +34 -0
  56. package/dist/api/src/semantics/time.ts +40 -0
  57. package/dist/qstash/src/doors.d.ts +6 -0
  58. package/dist/qstash/src/doors.js +33 -0
  59. package/dist/qstash/src/doors.ts +51 -0
  60. package/dist/qstash/src/egress.d.ts +7 -0
  61. package/dist/qstash/src/egress.js +66 -0
  62. package/dist/qstash/src/egress.ts +58 -0
  63. package/dist/qstash/src/fetch.d.ts +7 -0
  64. package/dist/qstash/src/fetch.js +48 -0
  65. package/dist/qstash/src/fetch.ts +46 -0
  66. package/dist/qstash/src/generated/surface.gen.json +1 -0
  67. package/dist/qstash/src/generated/ui.gen.json +1 -0
  68. package/dist/qstash/src/index.ts +35 -0
  69. package/dist/qstash/src/manifest.d.ts +10 -0
  70. package/dist/qstash/src/manifest.js +105 -0
  71. package/dist/qstash/src/manifest.ts +134 -0
  72. package/dist/qstash/src/semantics/account.d.ts +29 -0
  73. package/dist/qstash/src/semantics/account.js +91 -0
  74. package/dist/qstash/src/semantics/account.ts +98 -0
  75. package/dist/qstash/src/semantics/delivery.d.ts +17 -0
  76. package/dist/qstash/src/semantics/delivery.js +274 -0
  77. package/dist/qstash/src/semantics/delivery.ts +264 -0
  78. package/dist/qstash/src/semantics/dlq.d.ts +4 -0
  79. package/dist/qstash/src/semantics/dlq.js +51 -0
  80. package/dist/qstash/src/semantics/dlq.ts +61 -0
  81. package/dist/qstash/src/semantics/index.d.ts +2 -0
  82. package/dist/qstash/src/semantics/index.js +10 -0
  83. package/dist/qstash/src/semantics/index.ts +13 -0
  84. package/dist/qstash/src/semantics/keys.d.ts +2 -0
  85. package/dist/qstash/src/semantics/keys.js +9 -0
  86. package/dist/qstash/src/semantics/keys.ts +14 -0
  87. package/dist/qstash/src/semantics/messages.d.ts +74 -0
  88. package/dist/qstash/src/semantics/messages.js +233 -0
  89. package/dist/qstash/src/semantics/messages.ts +249 -0
  90. package/dist/qstash/src/semantics/queues.d.ts +2 -0
  91. package/dist/qstash/src/semantics/queues.js +60 -0
  92. package/dist/qstash/src/semantics/queues.ts +66 -0
  93. package/dist/qstash/src/semantics/schedules.d.ts +19 -0
  94. package/dist/qstash/src/semantics/schedules.js +125 -0
  95. package/dist/qstash/src/semantics/schedules.ts +132 -0
  96. package/dist/qstash/src/semantics/shared.d.ts +45 -0
  97. package/dist/qstash/src/semantics/shared.js +115 -0
  98. package/dist/qstash/src/semantics/shared.ts +121 -0
  99. package/dist/qstash/src/semantics/urlgroups.d.ts +2 -0
  100. package/dist/qstash/src/semantics/urlgroups.js +58 -0
  101. package/dist/qstash/src/semantics/urlgroups.ts +69 -0
  102. package/dist/qstash/src/semantics/workflows.d.ts +44 -0
  103. package/dist/qstash/src/semantics/workflows.js +379 -0
  104. package/dist/qstash/src/semantics/workflows.ts +401 -0
  105. package/dist/qstash/src/signing.d.ts +4 -0
  106. package/dist/qstash/src/signing.js +16 -0
  107. package/dist/qstash/src/signing.ts +19 -0
  108. package/dist/src/cli.d.ts +2 -0
  109. package/dist/src/cli.js +35 -0
  110. package/dist/src/generated/surface.gen.json +1 -0
  111. package/dist/src/index.d.ts +18 -0
  112. package/dist/src/index.js +124 -0
  113. package/dist/src/manifest.d.ts +14 -0
  114. package/dist/src/manifest.js +8 -0
  115. package/dist/src/upstash-budget.d.ts +85 -0
  116. package/dist/src/upstash-budget.js +440 -0
  117. package/dist/src/upstash-capabilities.d.ts +4 -0
  118. package/dist/src/upstash-capabilities.js +1286 -0
  119. package/dist/src/upstash-conformance.d.ts +7 -0
  120. package/dist/src/upstash-conformance.js +119 -0
  121. package/dist/src/upstash-connector.d.ts +115 -0
  122. package/dist/src/upstash-connector.js +309 -0
  123. package/dist/src/upstash-lua.d.ts +140 -0
  124. package/dist/src/upstash-lua.js +1229 -0
  125. package/dist/src/upstash-server.d.ts +29 -0
  126. package/dist/src/upstash-server.js +81 -0
  127. package/dist/src/upstash-store.d.ts +114 -0
  128. package/dist/src/upstash-store.js +1663 -0
  129. package/dist/src/upstash-twin.d.ts +73 -0
  130. package/dist/src/upstash-twin.js +437 -0
  131. package/package.json +59 -0
  132. package/qstash/src/doors.ts +51 -0
  133. package/qstash/src/egress.ts +58 -0
  134. package/qstash/src/fetch.ts +46 -0
  135. package/qstash/src/generated/surface.gen.json +1 -0
  136. package/qstash/src/generated/ui.gen.json +1 -0
  137. package/qstash/src/index.ts +35 -0
  138. package/qstash/src/manifest.ts +134 -0
  139. package/qstash/src/semantics/account.ts +98 -0
  140. package/qstash/src/semantics/delivery.ts +264 -0
  141. package/qstash/src/semantics/dlq.ts +61 -0
  142. package/qstash/src/semantics/index.ts +13 -0
  143. package/qstash/src/semantics/keys.ts +14 -0
  144. package/qstash/src/semantics/messages.ts +249 -0
  145. package/qstash/src/semantics/queues.ts +66 -0
  146. package/qstash/src/semantics/schedules.ts +132 -0
  147. package/qstash/src/semantics/shared.ts +121 -0
  148. package/qstash/src/semantics/urlgroups.ts +69 -0
  149. package/qstash/src/semantics/workflows.ts +401 -0
  150. package/qstash/src/signing.ts +19 -0
  151. package/src/cli.ts +36 -0
  152. package/src/generated/surface.gen.json +1 -0
  153. package/src/index.ts +203 -0
  154. package/src/manifest.ts +26 -0
  155. package/src/upstash-budget.ts +486 -0
  156. package/src/upstash-capabilities.ts +1418 -0
  157. package/src/upstash-conformance.ts +131 -0
  158. package/src/upstash-connector.ts +340 -0
  159. package/src/upstash-lua.ts +1120 -0
  160. package/src/upstash-server.ts +103 -0
  161. package/src/upstash-store.ts +1437 -0
  162. package/src/upstash-twin.ts +465 -0
@@ -0,0 +1,486 @@
1
+ // UPSTASH REDIS'S CLIENT-SIDE RATE BUDGET — the pack's DECLARATION (the numbers) plus
2
+ // `guardUpstashRedisClient`, the choke point every live Upstash Redis call goes through. The
3
+ // MECHANISM — the durable token-keyed ledger, the rolling window, reserve-under-lock, the
4
+ // `Retry-After`/429 cooldown, fail-CLOSED on a corrupt ledger — lives ONCE in the vendor-agnostic
5
+ // kernel (`@volter/world-core` → `rateBudget.ts`). Read that module's header for the full rationale AND
6
+ // for the honest list of what the guard does NOT guarantee (an injected clock or ledger path still
7
+ // defeats it — it guards carelessness, not malice). This module is modeled on notion-budget.ts, the
8
+ // reference injected-client decorator.
9
+ //
10
+ // ── WHY UPSTASH REDIS NEEDS ONE, AND WHY THE OBVIOUS NUMBER IS THE WRONG ONE ───────────────────
11
+ // Upstash publishes a real scalar, and it is enormous. Its billing page's "All plans and limits"
12
+ // table (upstash.com/docs/redis/overall/billing) gives **10,000 commands/sec** on Free, Pay-As-You-Go
13
+ // and every Fixed plan up to 50 GB (16,000 on the two largest). Taken at face value that would
14
+ // license 600,000 calls a minute, which is not a guard — it is the absence of one.
15
+ //
16
+ // The number that actually binds a connector loop is the QUOTA, not the rate:
17
+ // • Free tier: **500,000 commands per month** (same table). That is ~11.6 commands/minute
18
+ // sustained. At the vendor's own 10,000/sec ceiling a runaway loop exhausts a month of free
19
+ // quota in FIFTY SECONDS.
20
+ // • Pay-As-You-Go bills **per command**, and the docs are explicit that "one command is one
21
+ // billable request" and that "each command inside a pipeline or transaction is still billed
22
+ // individually" — so a 500-key pull is 500 billable commands, not one.
23
+ // So the risk this budget exists to bound is SPEND and QUOTA EXHAUSTION, not throttling. Upstash
24
+ // does document throttle errors (`ERR max daily request limit exceeded`, `ERR max requests limit
25
+ // exceeded`) but publishes NO figure for either, and the grounding pass could not trigger them, so
26
+ // their HTTP status is UNVERIFIED and nothing here claims otherwise.
27
+ //
28
+ // ── HOW THE CEILING WAS CHOSEN ────────────────────────────────────────────────────────────────
29
+ // 600 weighted units / 60s at the default weight of 2 = **300 commands per minute**. That is:
30
+ // • 2,000x TIGHTER than the documented 10,000/sec rate limit — so it can never be the thing that
31
+ // trips the vendor's own limiter, and it is not "more permissive than a documented limit";
32
+ // • loose enough that a legitimate pull of a few hundred named keys completes in one window
33
+ // instead of degenerating into a cascade of refusals;
34
+ // • tight enough that exhausting the free tier's whole monthly quota would take ~28 hours of
35
+ // continuous looping rather than under a minute.
36
+ // It IS more permissive than the kernel's austere `DEFAULT_RATE_BUDGET` (60 units/60s), and the
37
+ // justification is the published table above — a documented limit three orders of magnitude higher,
38
+ // against a per-command API where a single logical "pull one hash" is several commands. Without
39
+ // that headroom the fallback would refuse an ordinary twenty-key pull.
40
+ //
41
+ // ── WHAT THIS DOES NOT DO: PACE ───────────────────────────────────────────────────────────────
42
+ // It bounds the 60s AVERAGE; it does NOT bound the instantaneous rate. The window has no spacing,
43
+ // so a tight `await` loop can legitimately fire the whole allowance in a fraction of a second. In
44
+ // that shape a vendor 429 can arrive BEFORE this ceiling does, and the backstop is then the
45
+ // COOLDOWN: the guard reads the back-off off the thrown error (or the response's exhaustion
46
+ // headers) and refuses every later call without touching the vendor. So the honest claim is
47
+ // "bounds the 60s average, and converts the vendor's first 429 into a hard stop" — never "refuses
48
+ // before the vendor ever 429s". Pacing is the CALLER's job; this module REFUSES, it never sleeps
49
+ // (see the kernel header: it is deliberately not a scheduler).
50
+ //
51
+ // ── HOW THE WEIGHTS WERE CHOSEN (and what is a judgement call) ────────────────────────────────
52
+ // `scan` costs 8, four times everything else. Documented half: `SCAN` is the one call here whose
53
+ // cost is unbounded in the SIZE OF THE CUSTOMER'S KEYSPACE rather than in what the caller asked
54
+ // for — Upstash's own docs warn against enumerating a production database — and each page is a
55
+ // separate billable command. Judgement half: `pullUpstashRedisScan` is the only entrypoint that
56
+ // loops without the caller naming what it wants, so it is the one most likely to be pointed at a
57
+ // real database by accident. Quadrupling its price is what makes the ceiling bite on a keyspace
58
+ // walk long before it bites on a named-key pull.
59
+ import {
60
+ declareRateBudget,
61
+ rateBudgetPath,
62
+ rateBudgetWeight,
63
+ RateBudget,
64
+ RateBudgetError,
65
+ type RateBudgetDeclaration,
66
+ type RateBudgetOptions,
67
+ type RateBudgetReservation,
68
+ type RateBudgetSnapshot,
69
+ } from '@volter/world-core';
70
+ import type { UpstashRedisLikeClient } from './upstash-connector.ts';
71
+
72
+ const VENDOR = 'upstash';
73
+
74
+ /** Rolling window, in ms. Spend older than this is pruned. */
75
+ export const UPSTASH_BUDGET_WINDOW_MS = 60_000;
76
+
77
+ /** Weighted units allowed inside one window. See the header for where this number comes from. */
78
+ export const UPSTASH_BUDGET_CEILING = 600;
79
+
80
+ /** Seconds. A `Retry-After` above this means the credential is throttled hard — fail loudly. */
81
+ export const UPSTASH_BUDGET_MAX_RETRY_AFTER_S = 300;
82
+
83
+ /** Per-call cost, keyed by the client method the guard is about to invoke. See the header. */
84
+ export const UPSTASH_CALL_WEIGHTS = {
85
+ /** `scan` — a keyspace WALK, whose cost scales with the customer's database, not the request. */
86
+ scan: 8,
87
+ /** Every other modeled call (get/type/ttl/hgetall/smembers/lrange/zrange, and anything unclassified). */
88
+ other: 2,
89
+ } as const;
90
+
91
+ /**
92
+ * The client methods this pack PRICES BY NAME, as dotted paths into the injected client.
93
+ *
94
+ * Two kinds of entry: (a) every method this connector actually calls, and (b) an endpoint the
95
+ * VENDOR documents in a distinct tier which a consumer can reach through the guarded client even
96
+ * though this connector never calls it (see the weights section of the header). Used to build the
97
+ * guarded surface — and, in the pack's own suite, the counting fake.
98
+ *
99
+ * NOT a closed list, and not a claim about the injected client's shape. A path the real client does
100
+ * not have is SKIPPED (this connector's members are optional; inventing one would turn "observe
101
+ * nothing" into "call something that isn't there"), and a method absent from this list is still
102
+ * PRICED at `defaultWeight` when a caller reaches for it — an unmodeled endpoint must never be
103
+ * free, and dropping one would be worse than free because it would be invisible.
104
+ */
105
+ export const UPSTASH_BUDGETED_METHODS = [
106
+ "get",
107
+ "type",
108
+ "ttl",
109
+ "hgetall",
110
+ "smembers",
111
+ "lrange",
112
+ "zrange",
113
+ "scan",
114
+ ] as const;
115
+
116
+ /** THE PACK'S DECLARATION — pure data, the only Upstash-specific thing in the whole budget. */
117
+ export const UPSTASH_RATE_BUDGET: RateBudgetDeclaration = {
118
+ windowMs: UPSTASH_BUDGET_WINDOW_MS,
119
+ ceiling: UPSTASH_BUDGET_CEILING,
120
+ defaultWeight: UPSTASH_CALL_WEIGHTS.other,
121
+ maxRetryAfterSeconds: UPSTASH_BUDGET_MAX_RETRY_AFTER_S,
122
+ // Ordered: the kernel prices FIRST-MATCH-WINS, so the most expensive tier is listed first.
123
+ rules: [
124
+ { match: "(^|\\.)scan$", weight: UPSTASH_CALL_WEIGHTS.scan },
125
+ ],
126
+ reason:
127
+ "Upstash PUBLISHES a scalar and it is enormous: the \"All plans and limits\" table at " +
128
+ "upstash.com/docs/redis/overall/billing gives 10,000 commands/sec on Free, Pay-As-You-Go and every Fixed " +
129
+ "plan up to 50 GB (16,000 on the two largest). Taking that at face value would license 600,000 calls a " +
130
+ "minute, which is not a guard. The limit that actually binds a connector loop is the QUOTA: the free tier " +
131
+ "allows 500,000 commands per MONTH (~11.6/min sustained) and Pay-As-You-Go bills per command, with the docs " +
132
+ "explicit that \"one command is one billable request\" and that each command inside a pipeline or " +
133
+ "transaction is billed individually. So this ceiling (600 units / 60s at weight 2 = 300 commands/min) is " +
134
+ "chosen against SPEND, not throttling: 2,000x tighter than the documented 10,000/sec so it can never be " +
135
+ "what trips the vendor's own limiter, loose enough for a few-hundred-key pull to finish in one window, and " +
136
+ "tight enough that burning the whole free monthly quota would take ~28 hours of looping instead of 50 " +
137
+ "seconds. It is more permissive than the kernel fallback (60 units/60s) and the published table three " +
138
+ "orders of magnitude higher is the justification. scan costs 8 because its cost scales with the CUSTOMER'S " +
139
+ "keyspace rather than the request, and it is the one entrypoint that loops without the caller naming what " +
140
+ "it wants. Upstash also documents throttle errors (ERR max daily request limit exceeded, ERR max requests " +
141
+ "limit exceeded) but publishes NO figure for either and the grounding pass could not trigger them, so their " +
142
+ "status and thresholds are UNVERIFIED and nothing here claims a number for them.",
143
+ };
144
+
145
+ // Declared at module load, so merely importing this module (which `upstash-connector.ts` does) is
146
+ // enough to arm the real ceiling. A budget constructed BEFORE this runs falls back to the kernel's
147
+ // DEFAULT_RATE_BUDGET — which is tighter in call COUNT but prices every call at 2, so for a vendor
148
+ // with an expensive endpoint the fallback is CHEAPER there, not safer. `RateBudget` reads its policy
149
+ // LIVE precisely so this declaration takes effect the moment it lands, and constructing through the
150
+ // subclass below (whose module IS this one) makes the ordering a non-issue in practice.
151
+ declareRateBudget(VENDOR, UPSTASH_RATE_BUDGET);
152
+
153
+ /** Price one Upstash Redis call by its client method name (e.g. `get`, `scan`). */
154
+ export function upstashCallWeight(method: string): number {
155
+ return rateBudgetWeight(VENDOR, method);
156
+ }
157
+
158
+ /** Where UpstashRedis's ledger lives. Token-keyed and cwd-independent by default (the vendor limits per
159
+ * credential, so a cwd-scoped ledger would hand the same credential a fresh allowance in every
160
+ * checkout, worktree and CI matrix leg); pass `root` to opt into world-scoped accounting. */
161
+ export function upstashBudgetPath(opts: { root?: string; token?: string } | string = {}): string {
162
+ const o = typeof opts === 'string' ? { root: opts } : opts;
163
+ // VENDOR spread LAST: a loosely-typed `{ vendor: 'other', … }` slipping through (TypeScript's
164
+ // excess-property check only catches object literals) must not redirect this pack's ledger to
165
+ // another vendor's file.
166
+ return rateBudgetPath({ ...o, vendor: VENDOR });
167
+ }
168
+
169
+ /** Construction options for UpstashRedis's budget. The vendor is fixed; everything else may only TIGHTEN. */
170
+ export type UpstashRedisBudgetOptions = Omit<RateBudgetOptions, 'vendor'>;
171
+
172
+ /**
173
+ * UpstashRedis's budget — the shared kernel guard bound to this vendor's declaration. A real subclass,
174
+ * not an alias, so `budget instanceof UpstashRedisBudget` means "a budget that accounts against this
175
+ * vendor's ledger under this vendor's ceiling": another vendor's `RateBudget` (with its own,
176
+ * possibly larger, ceiling) is NOT assignable where one of these is required.
177
+ */
178
+ export class UpstashRedisBudget extends RateBudget {
179
+ constructor(opts: UpstashRedisBudgetOptions = {}) {
180
+ super({ ...opts, vendor: VENDOR });
181
+ }
182
+ }
183
+
184
+ export type { RateBudgetErrorKind as UpstashRedisBudgetErrorKind } from '@volter/world-core';
185
+ export { RateBudgetError as UpstashRedisBudgetError } from '@volter/world-core';
186
+ export type UpstashRedisBudgetReservation = RateBudgetReservation;
187
+ export type UpstashRedisBudgetSnapshot = RateBudgetSnapshot;
188
+
189
+ /** What every budgeted connector entrypoint accepts. There is deliberately no option that turns the
190
+ * guard OFF — only ones that say WHICH ledger and clock to account against. */
191
+ export type UpstashRedisBudgetedOptions = {
192
+ /** An existing budget to share across calls. Omit and one is constructed. Cannot be null. */
193
+ budget?: UpstashRedisBudget;
194
+ /** Construction options for the default budget (ledger path, clock). Cannot loosen it. */
195
+ budgetOptions?: UpstashRedisBudgetOptions;
196
+ };
197
+
198
+ /** Pull the budget wiring out of a caller's opts bag, so an entrypoint can forward it verbatim. */
199
+ export function upstashBudgetOf(opts: UpstashRedisBudgetedOptions): UpstashRedisBudgetedOptions {
200
+ return {
201
+ ...(opts.budget !== undefined ? { budget: opts.budget } : {}),
202
+ ...(opts.budgetOptions !== undefined ? { budgetOptions: opts.budgetOptions } : {}),
203
+ };
204
+ }
205
+
206
+ // ── the choke point ─────────────────────────────────────────────────────────────────────────
207
+
208
+ /**
209
+ * Marks a client this module has already wrapped, so guarding twice cannot charge twice.
210
+ *
211
+ * A MODULE-PRIVATE `Symbol()`, deliberately not `Symbol.for()`: a global-registry symbol is
212
+ * reachable BY NAME, so any caller could stamp `client[Symbol.for(…)] = anything` on a RAW client and
213
+ * the guard would hand it straight back UNGUARDED — a one-line bypass of the whole budget. With a
214
+ * private symbol the only way to be branded is to have been wrapped by this function. The cost is
215
+ * that two copies of this module in one dependency tree would each wrap (double-charging a call);
216
+ * that is the SAFE direction, and over-charging is the tradeoff this module takes everywhere else.
217
+ */
218
+ const GUARDED: unique symbol = Symbol('@volter/twin-upstash.budget.guarded');
219
+
220
+ type Guarded = { [GUARDED]?: unknown };
221
+
222
+ /** Is this client already behind a budget? Returns the budget it is behind, if so. */
223
+ export function upstashClientBudget(client: unknown): RateBudget | undefined {
224
+ const mark = (client as Guarded | null)?.[GUARDED];
225
+ // Belt and braces: only a REAL budget counts as "already guarded". A non-RateBudget value here
226
+ // could only come from a forged brand, and the answer to a forgery is to wrap anyway.
227
+ return mark instanceof RateBudget ? mark : undefined;
228
+ }
229
+
230
+ /** Charge a call keyed by `method`, invoke it, settle. Returns whatever the call returned. */
231
+ type Charge = (method: string, invoke: (...args: unknown[]) => unknown) => (...args: unknown[]) => unknown;
232
+
233
+ /**
234
+ * Wrap an INJECTED UpstashRedis client so EVERY call it makes is charged against the shared budget
235
+ * BEFORE the request goes out. This pack's connector never constructs the transport itself (the
236
+ * consumer injects a client that satisfies `UpstashRedisLikeClient` structurally), so the guard is a
237
+ * DECORATOR rather than a factory — which is exactly why every connector entrypoint applies it
238
+ * UNCONDITIONALLY instead of trusting the caller to have done it.
239
+ *
240
+ * IDEMPOTENT: wrapping an already-guarded client returns it unchanged, so a caller who forgot is
241
+ * protected and a caller who wrapped deliberately is not double-charged.
242
+ *
243
+ * A method that THROWS is still inspected: an SDK typically RAISES on a 429 rather than returning
244
+ * it, and that error's back-off is exactly the signal that must become a persisted cooldown. Losing
245
+ * it would leave the ledger cheerfully spending into a throttled credential. The original error is
246
+ * always re-raised afterwards — the budget never swallows a vendor failure — EXCEPT when the
247
+ * back-off is beyond the cap, where the budget's own louder "stop calling" error takes precedence.
248
+ */
249
+ export function guardUpstashRedisClient(client: UpstashRedisLikeClient, opts: UpstashRedisBudgetedOptions = {}): UpstashRedisLikeClient {
250
+ // There is no value a caller can pass to end up with an UNGUARDED client. `null`/`undefined` (or
251
+ // omitting it) build the default budget; anything that is not a REAL `UpstashRedisBudget` is refused
252
+ // loudly rather than trusted — a duck-typed stand-in with a no-op `checkBudget` would otherwise be
253
+ // the one clean way around the guard. Validated BEFORE the already-guarded early return, so
254
+ // `guardUpstashRedisClient(alreadyGuarded, { budget: impostor })` is refused too rather than silently
255
+ // ignoring the impostor.
256
+ if (opts.budget !== undefined && opts.budget !== null && !(opts.budget instanceof UpstashRedisBudget)) {
257
+ throw new Error('guardUpstashRedisClient: `budget` must be a UpstashRedisBudget — refusing to guard a UpstashRedis client with an unverified rate guard');
258
+ }
259
+ if (upstashClientBudget(client)) return client;
260
+ const budget = opts.budget instanceof UpstashRedisBudget
261
+ ? opts.budget
262
+ : new UpstashRedisBudget({
263
+ // The default ledger is keyed by a hash of the credential — the vendor limits per credential,
264
+ // so a cwd-scoped ledger would hand it a fresh allowance per worktree/CI leg.
265
+ //
266
+ // HONESTLY: this pack does NOT hold the credential — the consumer's injected client does — so
267
+ // `UPSTASH_REDIS_REST_TOKEN` is a BEST-EFFORT stand-in for it, not the real thing. If that env var names a
268
+ // different account than the injected client, spend is booked against the wrong ledger; if it
269
+ // is unset, every unattributed UpstashRedis credential on the machine shares one (over-tight,
270
+ // which is the safe direction). A caller who knows the credential should say so:
271
+ // `budgetOptions: { token }` overrides this, and does so deliberately last in the spread.
272
+ ...(process.env.UPSTASH_REDIS_REST_TOKEN !== undefined ? { token: process.env.UPSTASH_REDIS_REST_TOKEN } : {}),
273
+ ...(opts.budgetOptions ?? {}),
274
+ });
275
+
276
+ /** Settle a reservation from whatever the call produced. May THROW (a back-off past the cap). */
277
+ const settle = (weight: number, reservation: RateBudgetReservation, v: unknown): void => {
278
+ const status = responseStatus(v);
279
+ const headers = responseHeaders(v);
280
+ if (status !== undefined || headers !== undefined) budget.recordCall(weight, headers, { status, reservation });
281
+ else budget.recordCall(weight, undefined, { reservation });
282
+ };
283
+
284
+ /**
285
+ * Settle once the call RESOLVED: the vendor has answered. recordCall arms any cooldown before
286
+ * it throws (a back-off beyond the cap), so that refusal is swallowed and the answer kept — a
287
+ * write the vendor accepted is never reported failed and performed again on retry. A resolved
288
+ * answer that carries a non-2xx status still lets the louder refusal win.
289
+ */
290
+ const settleAnswered = (weight: number, reservation: RateBudgetReservation, v: unknown): void => {
291
+ try {
292
+ settle(weight, reservation, v);
293
+ } catch (e) {
294
+ const status = responseStatus(v);
295
+ if (!(e instanceof RateBudgetError) || (status !== undefined && (status < 200 || status >= 300))) throw e;
296
+ }
297
+ };
298
+
299
+ /**
300
+ * Charge, call, settle — for a MODELED method, whose interface declares it `async`. Refusing
301
+ * REJECTS rather than throwing synchronously, so `client.x().catch(…)` behaves exactly as it does
302
+ * on an unguarded client. `checkBudget` RESERVES under lock, so nothing after its line runs when
303
+ * the budget refuses: the request is never made.
304
+ */
305
+ const chargeAsync = (method: string, invoke: (...args: unknown[]) => unknown) =>
306
+ async (...args: unknown[]): Promise<unknown> => {
307
+ const weight = budget.weightFor(method);
308
+ const reservation = budget.checkBudget(weight);
309
+ try {
310
+ const res = await invoke(...args);
311
+ settleAnswered(weight, reservation, res);
312
+ return res;
313
+ } catch (e) {
314
+ settle(weight, reservation, e); // may throw its own louder refusal, which wins
315
+ throw e;
316
+ }
317
+ };
318
+
319
+ /**
320
+ * Charge, call, settle — for an UNMODELED member reached through the passthrough Proxy, where the
321
+ * shape is unknown.
322
+ *
323
+ * Deliberately NOT `async`. Some vendor SDKs (twilio-shaped ones) build requests through
324
+ * SYNCHRONOUS chained accessors — `client.a.b('sid').c.create()` — where the intermediate calls
325
+ * return a resource context, not a promise. An `async` wrapper would turn every one of those into
326
+ * a `Promise` and `.c` would come back `undefined`: the guard would BREAK the client instead of
327
+ * guarding it. So a non-thenable return is treated as an accessor — still charged (we cannot know
328
+ * before calling, and over-charging is the safe direction) and wrapped, so the eventual async leaf
329
+ * is charged too rather than escaping the budget. The cost of the sync shape is that a REFUSAL on
330
+ * this path throws synchronously instead of rejecting; that is the honest signal for an accessor,
331
+ * and the modeled surface above (every method this connector actually calls) does not have it.
332
+ */
333
+ const charge: Charge = (method, invoke) => (...args) => {
334
+ const weight = budget.weightFor(method);
335
+ const reservation = budget.checkBudget(weight);
336
+ let out: unknown;
337
+ try {
338
+ out = invoke(...args);
339
+ } catch (e) {
340
+ settle(weight, reservation, e); // may throw its own louder refusal, which wins
341
+ throw e;
342
+ }
343
+ if (!isThenable(out)) {
344
+ settle(weight, reservation, undefined);
345
+ return out !== null && (typeof out === 'object' || typeof out === 'function')
346
+ ? proxyThrough({}, out as object, method, charge)
347
+ : out;
348
+ }
349
+ return out.then(
350
+ (res) => { settleAnswered(weight, reservation, res); return res; },
351
+ (e: unknown) => { settle(weight, reservation, e); throw e; },
352
+ );
353
+ };
354
+
355
+ // Build the charged surface from UPSTASH_BUDGETED_METHODS (see its docstring for why an absent path is
356
+ // SKIPPED rather than stubbed).
357
+ const guarded: Record<string, unknown> & Guarded = {};
358
+ for (const path of UPSTASH_BUDGETED_METHODS) {
359
+ const segs = path.split('.');
360
+ const leaf = segs[segs.length - 1]!;
361
+ let owner: Record<string, unknown> | undefined = client as unknown as Record<string, unknown>;
362
+ for (const seg of segs.slice(0, -1)) owner = owner?.[seg] as Record<string, unknown> | undefined;
363
+ if (typeof owner?.[leaf] !== 'function') continue;
364
+ const realOwner = owner;
365
+ let node: Record<string, unknown> = guarded;
366
+ for (const seg of segs.slice(0, -1)) node = (node[seg] ??= {}) as Record<string, unknown>;
367
+ // The method is resolved at CALL time, not here, so a client whose method is swapped later is
368
+ // still charged for whatever it actually runs.
369
+ node[leaf] = chargeAsync(path, (...args) => (realOwner[leaf] as (...a: unknown[]) => unknown).apply(realOwner, args));
370
+ }
371
+ Object.defineProperty(guarded, GUARDED, { value: budget, enumerable: false });
372
+
373
+ // The surface above is what this connector calls. A real client has MORE — and a consumer who
374
+ // needs any of it must not be forced to keep the RAW client alongside, because every call through
375
+ // that would be unbudgeted. So the guarded object is a Proxy: known members come from the map
376
+ // above, anything else is taken from the real client and PRICED at `defaultWeight`.
377
+ return proxyThrough(guarded, client as object, '', charge) as UpstashRedisLikeClient;
378
+ }
379
+
380
+ /**
381
+ * Members JavaScript itself asks for. Wrapping any of these turns the object into something that
382
+ * looks thenable / mis-reports its own identity, which breaks `await`, `instanceof` and logging —
383
+ * so they always come from the target untouched, never priced.
384
+ */
385
+ const NEVER_WRAP = new Set(['then', 'catch', 'finally', 'constructor', 'prototype', 'toJSON', 'toString', 'valueOf', 'inspect']);
386
+
387
+ /** Does this look like a promise? (Only a thenable gets the settle-on-resolution treatment.) */
388
+ function isThenable(v: unknown): v is Promise<unknown> {
389
+ return v !== null && (typeof v === 'object' || typeof v === 'function') && typeof (v as { then?: unknown }).then === 'function';
390
+ }
391
+
392
+ /**
393
+ * Symbols that name an ITERATION PROTOCOL. Reaching for one of these on a vendor object is how a
394
+ * paginator is driven (`for await (const page of client.things.list())`), i.e. it is the doorway to
395
+ * an unbounded sequence of REQUESTS — exactly what this budget exists to bound — so they are charged
396
+ * and their result is kept behind the proxy. Every other symbol (`Symbol.toStringTag`,
397
+ * `nodejs.util.inspect.custom`, …) is metadata rather than a request and passes through untouched.
398
+ */
399
+ const ITERATOR_SYMBOLS = new Set<symbol>([Symbol.asyncIterator, Symbol.iterator]);
400
+
401
+ /**
402
+ * Serve `known` where it has the member; otherwise price a passthrough to `real`. Applied
403
+ * recursively, so a namespace member this pack never modeled is charged at `defaultWeight` rather
404
+ * than coming back `undefined`.
405
+ *
406
+ * CALLABLE NAMESPACES (§9 finding): a member can be BOTH a function and a namespace — twilio's
407
+ * `client.messages` is called as `client.messages(sid)` to get one message's context AND read as
408
+ * `client.messages.list()`. An earlier version returned the modeled node as a plain object whenever
409
+ * this pack modeled any child of it, which silently DROPPED the call signature and every unmodeled
410
+ * sibling — the module's own docstring calls a dropped member "worse than free, because it is
411
+ * invisible", and that is what it was doing. So when `real` is callable the proxy target is a
412
+ * function and an `apply` trap charges the call, while `known` stays the source of modeled members.
413
+ */
414
+ function proxyThrough(known: object, real: object, prefix: string, charge: Charge, owner?: object): object {
415
+ const callable = typeof real === 'function';
416
+ // The target must itself be callable for the `apply` trap to exist at all. `known` stays the
417
+ // source of modeled members, read explicitly below rather than through the target.
418
+ const target: object = callable ? function proxied() { /* every call goes through the trap */ } : known;
419
+ return new Proxy(target, {
420
+ apply(_t, _thisArg, args: unknown[]) {
421
+ // Calling the namespace is itself a request-builder hop: charge it, and keep the result
422
+ // behind the proxy (charge() re-proxies a non-thenable) so the eventual leaf is charged too.
423
+ // `owner` is the object the function was read from — dropping it would silently break every
424
+ // method that relies on `this`.
425
+ return charge(prefix || 'call', (...a) => (real as (...x: unknown[]) => unknown).apply(owner, a))(...args);
426
+ },
427
+ get(_t, prop, receiver) {
428
+ if (typeof prop === 'symbol') {
429
+ const ownSym = Reflect.get(known, prop, receiver);
430
+ if (ownSym !== undefined) return ownSym; // the GUARDED brand, and anything we model
431
+ const fromSym = (real as Record<symbol, unknown> | null)?.[prop];
432
+ if (ITERATOR_SYMBOLS.has(prop) && typeof fromSym === 'function') {
433
+ return charge(`${prefix}[${prop.description ?? 'iterator'}]`, (...args) => (fromSym as (...a: unknown[]) => unknown).apply(real, args));
434
+ }
435
+ return fromSym;
436
+ }
437
+ const name = String(prop);
438
+ if (NEVER_WRAP.has(name)) return Reflect.get(known, prop, receiver);
439
+ const key = prefix ? `${prefix}.${name}` : name;
440
+ const own = Reflect.get(known, prop, receiver);
441
+ const from = (real as Record<string, unknown> | null)?.[name];
442
+ // A member we model: the charged wrapper (a function) or a namespace we must keep descending
443
+ // into, so an unmodeled sibling is still priced rather than dropped.
444
+ if (typeof own === 'function') return own;
445
+ if (own && typeof own === 'object') {
446
+ // `from` may be an object OR a CALLABLE namespace — both keep descending, which is what
447
+ // preserves `client.messages(sid)` alongside the modeled `client.messages.list()`.
448
+ return from && (typeof from === 'object' || typeof from === 'function')
449
+ ? proxyThrough(own, from, key, charge, real)
450
+ : own;
451
+ }
452
+ if (own !== undefined) return own;
453
+ // A member only the real client has. Functions go through proxyThrough too, so one that also
454
+ // carries members (a callable namespace) keeps both its call signature and its siblings.
455
+ if (typeof from === 'function') return proxyThrough({}, from, key, charge, real);
456
+ if (from && typeof from === 'object') return proxyThrough({}, from, key, charge, real);
457
+ return from;
458
+ },
459
+ has(_t, prop) {
460
+ return Reflect.has(known, prop) || (real !== null && Reflect.has(real, prop));
461
+ },
462
+ });
463
+ }
464
+
465
+ /** The HTTP status a value carries, if it looks like one (an SDK error, or a raw response). */
466
+ function responseStatus(v: unknown): number | undefined {
467
+ const s = (v as { status?: unknown } | null)?.status;
468
+ return typeof s === 'number' && Number.isFinite(s) ? s : undefined;
469
+ }
470
+
471
+ /**
472
+ * Response/error headers as a plain lower-cased record, or `undefined` when there are none. Accepts
473
+ * a `Headers` instance, a `Map`, or a plain object — an SDK's error type changes shape across
474
+ * versions and none of the three is worth depending on.
475
+ */
476
+ function responseHeaders(v: unknown): Record<string, string> | undefined {
477
+ const h = (v as { headers?: unknown } | null)?.headers;
478
+ if (!h || typeof h !== 'object') return undefined;
479
+ const out: Record<string, string> = {};
480
+ if (typeof (h as Headers).forEach === 'function') {
481
+ (h as Headers).forEach((value: string, key: string) => { out[String(key).toLowerCase()] = String(value); });
482
+ } else {
483
+ for (const [k, value] of Object.entries(h as Record<string, unknown>)) out[k.toLowerCase()] = String(value);
484
+ }
485
+ return Object.keys(out).length > 0 ? out : undefined;
486
+ }