@volter/twin-polar 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/LICENSE +202 -0
- package/README.md +36 -0
- package/package.json +43 -0
- package/src/cli.ts +25 -0
- package/src/index.ts +70 -0
- package/src/polar-budget.ts +443 -0
- package/src/polar-capabilities.ts +413 -0
- package/src/polar-conformance.ts +33 -0
- package/src/polar-connector.ts +155 -0
- package/src/polar-server.ts +33 -0
- package/src/polar-twin.ts +828 -0
|
@@ -0,0 +1,443 @@
|
|
|
1
|
+
// Polar's CLIENT-SIDE RATE BUDGET — the pack's DECLARATION (the numbers) plus `guardPolarClient`,
|
|
2
|
+
// the choke point every live Polar call goes through. The MECHANISM — the durable token-keyed
|
|
3
|
+
// ledger, the rolling window, reserve-under-lock, the `Retry-After`/429 cooldown, fail-CLOSED on a
|
|
4
|
+
// corrupt ledger — lives ONCE in the vendor-agnostic kernel (`@volter/twin` → `rateBudget.ts`).
|
|
5
|
+
// Read that module's header for the full rationale AND for the honest list of what the guard does
|
|
6
|
+
// NOT guarantee (an injected clock or ledger path still defeats it — it guards carelessness, not
|
|
7
|
+
// malice). This module is modeled on notion-budget.ts, the reference injected-client decorator.
|
|
8
|
+
//
|
|
9
|
+
// ── WHY POLAR NEEDS ONE ─────────────────────────────────────────────────────────────
|
|
10
|
+
// Polar publishes its limits cleanly and is the only vendor in this batch that documents a
|
|
11
|
+
// `Retry-After` header (polar.sh/docs/api-reference/introduction): "500 requests per minute" in
|
|
12
|
+
// production and "100 requests per minute" in sandbox, in both cases per organization/customer or
|
|
13
|
+
// OAuth2 client, plus a separate "3 requests per second" budget for the unauthenticated license-key
|
|
14
|
+
// validation/activation/deactivation endpoints. Its 429 "includes a Retry-After header indicating how
|
|
15
|
+
// long you should wait" — which is exactly the signal the kernel's cooldown is built to consume, so
|
|
16
|
+
// on this vendor the guard's second line of defence is genuinely armed rather than inferred.
|
|
17
|
+
//
|
|
18
|
+
// ── HOW THE CEILING WAS CHOSEN ──────────────────────────────────────────────────────────────
|
|
19
|
+
// THIS PACK IS DELIBERATELY MORE PERMISSIVE THAN THE KERNEL FALLBACK, and the documented limits are
|
|
20
|
+
// why. The ceiling is derived from the SANDBOX figure, not production: 100 requests/minute is the
|
|
21
|
+
// tighter of the two published numbers, and a twin consumer is at least as likely to be pointed at
|
|
22
|
+
// sandbox as at production, so budgeting against 500/min would be the wrong default. 60 weighted
|
|
23
|
+
// units / 60s at weight 1 admits 60 calls/minute — 60% of the documented sandbox limit and 12% of
|
|
24
|
+
// production, against the fallback's 30/min. A pull of all four domains is 4 calls, so this leaves a
|
|
25
|
+
// pull-heavy caller real headroom while still stopping a loop well inside the vendor's own limit.
|
|
26
|
+
//
|
|
27
|
+
// ── WHAT THIS DOES NOT DO: PACE ─────────────────────────────────────────────────────────────
|
|
28
|
+
// It bounds the 60s AVERAGE; it does NOT bound the instantaneous rate. The window has no
|
|
29
|
+
// spacing, so a tight `await` loop can legitimately fire the whole allowance in a fraction of a
|
|
30
|
+
// second. In that shape the vendor's own 429 can arrive BEFORE this ceiling does, and the backstop
|
|
31
|
+
// is then the COOLDOWN: the guard reads the back-off off the thrown error (or the response's
|
|
32
|
+
// exhaustion headers) and refuses every later call without touching the vendor. So the honest claim
|
|
33
|
+
// is "bounds the 60s average, and converts the vendor's first 429 into a hard stop" — never
|
|
34
|
+
// "refuses before the vendor ever 429s". Pacing is the CALLER's job; this module REFUSES, it never
|
|
35
|
+
// sleeps (see the kernel header: it is deliberately not a scheduler). A tighter window would not
|
|
36
|
+
// close the gap, it would only turn every legitimate multi-page pull into a cascade of refusals.
|
|
37
|
+
//
|
|
38
|
+
// ── HOW THE WEIGHTS WERE CHOSEN (and what is a judgement call) ──────────────────────────────
|
|
39
|
+
// FLAT: every call costs 1. Polar meters ONE per-minute budget across the authenticated API — its
|
|
40
|
+
// docs give a single figure per environment rather than a per-endpoint table — so pricing one list
|
|
41
|
+
// above another would be invention. The one genuinely separate budget Polar publishes (3 requests/
|
|
42
|
+
// second for the unauthenticated license-key endpoints) is not part of this connector's surface and
|
|
43
|
+
// is per-second rather than per-minute, so it is recorded here rather than modeled as a rule. An
|
|
44
|
+
// unmodeled method reached through the guarded client is charged the same 1, never free.
|
|
45
|
+
import {
|
|
46
|
+
declareRateBudget,
|
|
47
|
+
rateBudgetPath,
|
|
48
|
+
rateBudgetWeight,
|
|
49
|
+
RateBudget,
|
|
50
|
+
type RateBudgetDeclaration,
|
|
51
|
+
type RateBudgetOptions,
|
|
52
|
+
type RateBudgetReservation,
|
|
53
|
+
type RateBudgetSnapshot,
|
|
54
|
+
} from '@volter/twin';
|
|
55
|
+
import type { PolarLikeClient } from './polar-connector.ts';
|
|
56
|
+
|
|
57
|
+
const VENDOR = 'polar';
|
|
58
|
+
|
|
59
|
+
/** Rolling window, in ms. Spend older than this is pruned. */
|
|
60
|
+
export const POLAR_BUDGET_WINDOW_MS = 60_000;
|
|
61
|
+
|
|
62
|
+
/** Weighted units allowed inside one window. See the header for where this number comes from. */
|
|
63
|
+
export const POLAR_BUDGET_CEILING = 60;
|
|
64
|
+
|
|
65
|
+
/** Seconds. A `Retry-After` above this means the credential is throttled hard — fail loudly. */
|
|
66
|
+
export const POLAR_BUDGET_MAX_RETRY_AFTER_S = 300;
|
|
67
|
+
|
|
68
|
+
/** Per-call cost, keyed by the client method the guard is about to invoke. See the header. */
|
|
69
|
+
export const POLAR_CALL_WEIGHTS = {
|
|
70
|
+
/** Every modeled call. Polar meters one per-minute budget across the API. */
|
|
71
|
+
other: 1,
|
|
72
|
+
} as const;
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The client methods this pack PRICES BY NAME, as dotted paths into the injected client.
|
|
76
|
+
*
|
|
77
|
+
* Two kinds of entry: (a) every method this connector actually calls, and (b) an endpoint the
|
|
78
|
+
* VENDOR documents in a distinct tier which a consumer can reach through the guarded client even
|
|
79
|
+
* though this connector never calls it (see the weights section of the header). Used to build the
|
|
80
|
+
* guarded surface — and, in the pack's own suite, the counting fake.
|
|
81
|
+
*
|
|
82
|
+
* NOT a closed list, and not a claim about the injected client's shape. A path the real client does
|
|
83
|
+
* not have is SKIPPED (this connector's members are optional; inventing one would turn "observe
|
|
84
|
+
* nothing" into "call something that isn't there"), and a method absent from this list is still
|
|
85
|
+
* PRICED at `defaultWeight` when a caller reaches for it — an unmodeled endpoint must never be
|
|
86
|
+
* free, and dropping one would be worse than free because it would be invisible.
|
|
87
|
+
*/
|
|
88
|
+
export const POLAR_BUDGETED_METHODS = [
|
|
89
|
+
'customers.list',
|
|
90
|
+
'customers.create',
|
|
91
|
+
'products.list',
|
|
92
|
+
'products.create',
|
|
93
|
+
'subscriptions.list',
|
|
94
|
+
'orders.list',
|
|
95
|
+
] as const;
|
|
96
|
+
|
|
97
|
+
/** THE PACK'S DECLARATION — pure data, the only Polar-specific thing in the whole budget. */
|
|
98
|
+
export const POLAR_RATE_BUDGET: RateBudgetDeclaration = {
|
|
99
|
+
windowMs: POLAR_BUDGET_WINDOW_MS,
|
|
100
|
+
ceiling: POLAR_BUDGET_CEILING,
|
|
101
|
+
defaultWeight: POLAR_CALL_WEIGHTS.other,
|
|
102
|
+
maxRetryAfterSeconds: POLAR_BUDGET_MAX_RETRY_AFTER_S,
|
|
103
|
+
// Ordered: the kernel prices FIRST-MATCH-WINS, so the tightest tier is listed first.
|
|
104
|
+
rules: [],
|
|
105
|
+
reason:
|
|
106
|
+
"Polar publishes \"500 requests per minute\" in production and \"100 requests per minute\" in sandbox, per " +
|
|
107
|
+
"organization/customer or OAuth2 client, plus a separate 3 requests/second budget for the unauthenticated " +
|
|
108
|
+
"license-key endpoints; its 429 explicitly \"includes a Retry-After header\". THIS DECLARATION IS MORE " +
|
|
109
|
+
"PERMISSIVE THAN the kernel's DEFAULT_RATE_BUDGET (30 calls/min) and the documented limits are why: 60 " +
|
|
110
|
+
"units / 60s at weight 1 admits 60 calls/min, derived from the tighter SANDBOX figure (60% of 100/min, 12% " +
|
|
111
|
+
"of production's 500/min) because a twin consumer is at least as likely to be pointed at sandbox. Weights " +
|
|
112
|
+
"are flat because Polar meters one per-minute budget across the authenticated API rather than publishing a " +
|
|
113
|
+
"per-endpoint table; the separate 3/s license-key budget is not in this connector's surface. Polar is the " +
|
|
114
|
+
"one vendor in this batch that documents Retry-After, so the cooldown path is armed by the vendor itself.",
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
// Declared at module load, so merely importing this module (which `polar-connector.ts` does) is
|
|
118
|
+
// enough to arm the real ceiling. A budget constructed BEFORE this runs falls back to the kernel's
|
|
119
|
+
// DEFAULT_RATE_BUDGET — which is tighter in call COUNT but prices every call at 2, so for a vendor
|
|
120
|
+
// with an expensive endpoint the fallback is CHEAPER there, not safer. `RateBudget` reads its policy
|
|
121
|
+
// LIVE precisely so this declaration takes effect the moment it lands, and constructing through the
|
|
122
|
+
// subclass below (whose module IS this one) makes the ordering a non-issue in practice.
|
|
123
|
+
declareRateBudget(VENDOR, POLAR_RATE_BUDGET);
|
|
124
|
+
|
|
125
|
+
/** Price one Polar call by its client method key (a dotted path, e.g. `customers.list`). */
|
|
126
|
+
export function polarCallWeight(method: string): number {
|
|
127
|
+
return rateBudgetWeight(VENDOR, method);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Where Polar's ledger lives. Token-keyed and cwd-independent by default (the vendor limits per
|
|
131
|
+
* credential, so a cwd-scoped ledger would hand the same credential a fresh allowance in every
|
|
132
|
+
* checkout, worktree and CI matrix leg); pass `root` to opt into world-scoped accounting. */
|
|
133
|
+
export function polarBudgetPath(opts: { root?: string; token?: string } | string = {}): string {
|
|
134
|
+
const o = typeof opts === 'string' ? { root: opts } : opts;
|
|
135
|
+
// VENDOR spread LAST: a loosely-typed `{ vendor: 'other', … }` slipping through (TypeScript's
|
|
136
|
+
// excess-property check only catches object literals) must not redirect this pack's ledger to
|
|
137
|
+
// another vendor's file.
|
|
138
|
+
return rateBudgetPath({ ...o, vendor: VENDOR });
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Construction options for Polar's budget. The vendor is fixed; everything else may only TIGHTEN. */
|
|
142
|
+
export type PolarBudgetOptions = Omit<RateBudgetOptions, 'vendor'>;
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Polar's budget — the shared kernel guard bound to this vendor's declaration. A real subclass,
|
|
146
|
+
* not an alias, so `budget instanceof PolarBudget` means "a budget that accounts against this
|
|
147
|
+
* vendor's ledger under this vendor's ceiling": another vendor's `RateBudget` (with its own,
|
|
148
|
+
* possibly larger, ceiling) is NOT assignable where one of these is required.
|
|
149
|
+
*/
|
|
150
|
+
export class PolarBudget extends RateBudget {
|
|
151
|
+
constructor(opts: PolarBudgetOptions = {}) {
|
|
152
|
+
super({ ...opts, vendor: VENDOR });
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export type { RateBudgetErrorKind as PolarBudgetErrorKind } from '@volter/twin';
|
|
157
|
+
export { RateBudgetError as PolarBudgetError } from '@volter/twin';
|
|
158
|
+
export type PolarBudgetReservation = RateBudgetReservation;
|
|
159
|
+
export type PolarBudgetSnapshot = RateBudgetSnapshot;
|
|
160
|
+
|
|
161
|
+
/** What every budgeted connector entrypoint accepts. There is deliberately no option that turns the
|
|
162
|
+
* guard OFF — only ones that say WHICH ledger and clock to account against. */
|
|
163
|
+
export type PolarBudgetedOptions = {
|
|
164
|
+
/** An existing budget to share across calls. Omit and one is constructed. Cannot be null. */
|
|
165
|
+
budget?: PolarBudget;
|
|
166
|
+
/** Construction options for the default budget (ledger path, clock). Cannot loosen it. */
|
|
167
|
+
budgetOptions?: PolarBudgetOptions;
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
/** Pull the budget wiring out of a caller's opts bag, so an entrypoint can forward it verbatim. */
|
|
171
|
+
export function polarBudgetOf(opts: PolarBudgetedOptions): PolarBudgetedOptions {
|
|
172
|
+
return {
|
|
173
|
+
...(opts.budget !== undefined ? { budget: opts.budget } : {}),
|
|
174
|
+
...(opts.budgetOptions !== undefined ? { budgetOptions: opts.budgetOptions } : {}),
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// ── the choke point ─────────────────────────────────────────────────────────────────────────
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Marks a client this module has already wrapped, so guarding twice cannot charge twice.
|
|
182
|
+
*
|
|
183
|
+
* A MODULE-PRIVATE `Symbol()`, deliberately not `Symbol.for()`: a global-registry symbol is
|
|
184
|
+
* reachable BY NAME, so any caller could stamp `client[Symbol.for(…)] = anything` on a RAW client and
|
|
185
|
+
* the guard would hand it straight back UNGUARDED — a one-line bypass of the whole budget. With a
|
|
186
|
+
* private symbol the only way to be branded is to have been wrapped by this function. The cost is
|
|
187
|
+
* that two copies of this module in one dependency tree would each wrap (double-charging a call);
|
|
188
|
+
* that is the SAFE direction, and over-charging is the tradeoff this module takes everywhere else.
|
|
189
|
+
*/
|
|
190
|
+
const GUARDED: unique symbol = Symbol('@volter/twin-polar.budget.guarded');
|
|
191
|
+
|
|
192
|
+
type Guarded = { [GUARDED]?: unknown };
|
|
193
|
+
|
|
194
|
+
/** Is this client already behind a budget? Returns the budget it is behind, if so. */
|
|
195
|
+
export function polarClientBudget(client: unknown): RateBudget | undefined {
|
|
196
|
+
const mark = (client as Guarded | null)?.[GUARDED];
|
|
197
|
+
// Belt and braces: only a REAL budget counts as "already guarded". A non-RateBudget value here
|
|
198
|
+
// could only come from a forged brand, and the answer to a forgery is to wrap anyway.
|
|
199
|
+
return mark instanceof RateBudget ? mark : undefined;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Charge a call keyed by `method`, invoke it, settle. Returns whatever the call returned. */
|
|
203
|
+
type Charge = (method: string, invoke: (...args: unknown[]) => unknown) => (...args: unknown[]) => unknown;
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Wrap an INJECTED Polar client so EVERY call it makes is charged against the shared budget
|
|
207
|
+
* BEFORE the request goes out. This pack's connector never constructs the transport itself (the
|
|
208
|
+
* consumer injects a client that satisfies `PolarLikeClient` structurally), so the guard is a
|
|
209
|
+
* DECORATOR rather than a factory — which is exactly why every connector entrypoint applies it
|
|
210
|
+
* UNCONDITIONALLY instead of trusting the caller to have done it.
|
|
211
|
+
*
|
|
212
|
+
* IDEMPOTENT: wrapping an already-guarded client returns it unchanged, so a caller who forgot is
|
|
213
|
+
* protected and a caller who wrapped deliberately is not double-charged.
|
|
214
|
+
*
|
|
215
|
+
* A method that THROWS is still inspected: an SDK typically RAISES on a 429 rather than returning
|
|
216
|
+
* it, and that error's back-off is exactly the signal that must become a persisted cooldown. Losing
|
|
217
|
+
* it would leave the ledger cheerfully spending into a throttled credential. The original error is
|
|
218
|
+
* always re-raised afterwards — the budget never swallows a vendor failure — EXCEPT when the
|
|
219
|
+
* back-off is beyond the cap, where the budget's own louder "stop calling" error takes precedence.
|
|
220
|
+
*/
|
|
221
|
+
export function guardPolarClient(client: PolarLikeClient, opts: PolarBudgetedOptions = {}): PolarLikeClient {
|
|
222
|
+
// There is no value a caller can pass to end up with an UNGUARDED client. `null`/`undefined` (or
|
|
223
|
+
// omitting it) build the default budget; anything that is not a REAL `PolarBudget` is refused
|
|
224
|
+
// loudly rather than trusted — a duck-typed stand-in with a no-op `checkBudget` would otherwise be
|
|
225
|
+
// the one clean way around the guard. Validated BEFORE the already-guarded early return, so
|
|
226
|
+
// `guardPolarClient(alreadyGuarded, { budget: impostor })` is refused too rather than silently
|
|
227
|
+
// ignoring the impostor.
|
|
228
|
+
if (opts.budget !== undefined && opts.budget !== null && !(opts.budget instanceof PolarBudget)) {
|
|
229
|
+
throw new Error('guardPolarClient: `budget` must be a PolarBudget — refusing to guard a Polar client with an unverified rate guard');
|
|
230
|
+
}
|
|
231
|
+
if (polarClientBudget(client)) return client;
|
|
232
|
+
const budget = opts.budget instanceof PolarBudget
|
|
233
|
+
? opts.budget
|
|
234
|
+
: new PolarBudget({
|
|
235
|
+
// The default ledger is keyed by a hash of the credential — the vendor limits per credential,
|
|
236
|
+
// so a cwd-scoped ledger would hand it a fresh allowance per worktree/CI leg.
|
|
237
|
+
//
|
|
238
|
+
// HONESTLY: this pack does NOT hold the credential — the consumer's injected client does — so
|
|
239
|
+
// `POLAR_ACCESS_TOKEN` is a BEST-EFFORT stand-in for it, not the real thing. If that env var names a
|
|
240
|
+
// different account than the injected client, spend is booked against the wrong ledger; if it
|
|
241
|
+
// is unset, every unattributed Polar credential on the machine shares one (over-tight,
|
|
242
|
+
// which is the safe direction). A caller who knows the credential should say so:
|
|
243
|
+
// `budgetOptions: { token }` overrides this, and does so deliberately last in the spread.
|
|
244
|
+
...(process.env.POLAR_ACCESS_TOKEN !== undefined ? { token: process.env.POLAR_ACCESS_TOKEN } : {}),
|
|
245
|
+
...(opts.budgetOptions ?? {}),
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
/** Settle a reservation from whatever the call produced. May THROW (a back-off past the cap). */
|
|
249
|
+
const settle = (weight: number, reservation: RateBudgetReservation, v: unknown): void => {
|
|
250
|
+
const status = responseStatus(v);
|
|
251
|
+
const headers = responseHeaders(v);
|
|
252
|
+
if (status !== undefined || headers !== undefined) budget.recordCall(weight, headers, { status, reservation });
|
|
253
|
+
else budget.recordCall(weight, undefined, { reservation });
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Charge, call, settle — for a MODELED method, whose interface declares it `async`. Refusing
|
|
258
|
+
* REJECTS rather than throwing synchronously, so `client.x().catch(…)` behaves exactly as it does
|
|
259
|
+
* on an unguarded client. `checkBudget` RESERVES under lock, so nothing after its line runs when
|
|
260
|
+
* the budget refuses: the request is never made.
|
|
261
|
+
*/
|
|
262
|
+
const chargeAsync = (method: string, invoke: (...args: unknown[]) => unknown) =>
|
|
263
|
+
async (...args: unknown[]): Promise<unknown> => {
|
|
264
|
+
const weight = budget.weightFor(method);
|
|
265
|
+
const reservation = budget.checkBudget(weight);
|
|
266
|
+
try {
|
|
267
|
+
const res = await invoke(...args);
|
|
268
|
+
settle(weight, reservation, res);
|
|
269
|
+
return res;
|
|
270
|
+
} catch (e) {
|
|
271
|
+
settle(weight, reservation, e); // may throw its own louder refusal, which wins
|
|
272
|
+
throw e;
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Charge, call, settle — for an UNMODELED member reached through the passthrough Proxy, where the
|
|
278
|
+
* shape is unknown.
|
|
279
|
+
*
|
|
280
|
+
* Deliberately NOT `async`. Some vendor SDKs (twilio-shaped ones) build requests through
|
|
281
|
+
* SYNCHRONOUS chained accessors — `client.a.b('sid').c.create()` — where the intermediate calls
|
|
282
|
+
* return a resource context, not a promise. An `async` wrapper would turn every one of those into
|
|
283
|
+
* a `Promise` and `.c` would come back `undefined`: the guard would BREAK the client instead of
|
|
284
|
+
* guarding it. So a non-thenable return is treated as an accessor — still charged (we cannot know
|
|
285
|
+
* before calling, and over-charging is the safe direction) and wrapped, so the eventual async leaf
|
|
286
|
+
* is charged too rather than escaping the budget. The cost of the sync shape is that a REFUSAL on
|
|
287
|
+
* this path throws synchronously instead of rejecting; that is the honest signal for an accessor,
|
|
288
|
+
* and the modeled surface above (every method this connector actually calls) does not have it.
|
|
289
|
+
*/
|
|
290
|
+
const charge: Charge = (method, invoke) => (...args) => {
|
|
291
|
+
const weight = budget.weightFor(method);
|
|
292
|
+
const reservation = budget.checkBudget(weight);
|
|
293
|
+
let out: unknown;
|
|
294
|
+
try {
|
|
295
|
+
out = invoke(...args);
|
|
296
|
+
} catch (e) {
|
|
297
|
+
settle(weight, reservation, e); // may throw its own louder refusal, which wins
|
|
298
|
+
throw e;
|
|
299
|
+
}
|
|
300
|
+
if (!isThenable(out)) {
|
|
301
|
+
settle(weight, reservation, undefined);
|
|
302
|
+
return out !== null && (typeof out === 'object' || typeof out === 'function')
|
|
303
|
+
? proxyThrough({}, out as object, method, charge)
|
|
304
|
+
: out;
|
|
305
|
+
}
|
|
306
|
+
return out.then(
|
|
307
|
+
(res) => { settle(weight, reservation, res); return res; },
|
|
308
|
+
(e: unknown) => { settle(weight, reservation, e); throw e; },
|
|
309
|
+
);
|
|
310
|
+
};
|
|
311
|
+
|
|
312
|
+
// Build the charged surface from POLAR_BUDGETED_METHODS (see its docstring for why an absent path is
|
|
313
|
+
// SKIPPED rather than stubbed).
|
|
314
|
+
const guarded: Record<string, unknown> & Guarded = {};
|
|
315
|
+
for (const path of POLAR_BUDGETED_METHODS) {
|
|
316
|
+
const segs = path.split('.');
|
|
317
|
+
const leaf = segs[segs.length - 1]!;
|
|
318
|
+
let owner: Record<string, unknown> | undefined = client as unknown as Record<string, unknown>;
|
|
319
|
+
for (const seg of segs.slice(0, -1)) owner = owner?.[seg] as Record<string, unknown> | undefined;
|
|
320
|
+
if (typeof owner?.[leaf] !== 'function') continue;
|
|
321
|
+
const realOwner = owner;
|
|
322
|
+
let node: Record<string, unknown> = guarded;
|
|
323
|
+
for (const seg of segs.slice(0, -1)) node = (node[seg] ??= {}) as Record<string, unknown>;
|
|
324
|
+
// The method is resolved at CALL time, not here, so a client whose method is swapped later is
|
|
325
|
+
// still charged for whatever it actually runs.
|
|
326
|
+
node[leaf] = chargeAsync(path, (...args) => (realOwner[leaf] as (...a: unknown[]) => unknown).apply(realOwner, args));
|
|
327
|
+
}
|
|
328
|
+
Object.defineProperty(guarded, GUARDED, { value: budget, enumerable: false });
|
|
329
|
+
|
|
330
|
+
// The surface above is what this connector calls. A real client has MORE — and a consumer who
|
|
331
|
+
// needs any of it must not be forced to keep the RAW client alongside, because every call through
|
|
332
|
+
// that would be unbudgeted. So the guarded object is a Proxy: known members come from the map
|
|
333
|
+
// above, anything else is taken from the real client and PRICED at `defaultWeight`.
|
|
334
|
+
return proxyThrough(guarded, client as object, '', charge) as PolarLikeClient;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* Members JavaScript itself asks for. Wrapping any of these turns the object into something that
|
|
339
|
+
* looks thenable / mis-reports its own identity, which breaks `await`, `instanceof` and logging —
|
|
340
|
+
* so they always come from the target untouched, never priced.
|
|
341
|
+
*/
|
|
342
|
+
const NEVER_WRAP = new Set(['then', 'catch', 'finally', 'constructor', 'prototype', 'toJSON', 'toString', 'valueOf', 'inspect']);
|
|
343
|
+
|
|
344
|
+
/** Does this look like a promise? (Only a thenable gets the settle-on-resolution treatment.) */
|
|
345
|
+
function isThenable(v: unknown): v is Promise<unknown> {
|
|
346
|
+
return v !== null && (typeof v === 'object' || typeof v === 'function') && typeof (v as { then?: unknown }).then === 'function';
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* Symbols that name an ITERATION PROTOCOL. Reaching for one of these on a vendor object is how a
|
|
351
|
+
* paginator is driven (`for await (const page of client.things.list())`), i.e. it is the doorway to
|
|
352
|
+
* an unbounded sequence of REQUESTS — exactly what this budget exists to bound — so they are charged
|
|
353
|
+
* and their result is kept behind the proxy. Every other symbol (`Symbol.toStringTag`,
|
|
354
|
+
* `nodejs.util.inspect.custom`, …) is metadata rather than a request and passes through untouched.
|
|
355
|
+
*/
|
|
356
|
+
const ITERATOR_SYMBOLS = new Set<symbol>([Symbol.asyncIterator, Symbol.iterator]);
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* Serve `known` where it has the member; otherwise price a passthrough to `real`. Applied
|
|
360
|
+
* recursively, so a namespace member this pack never modeled is charged at `defaultWeight` rather
|
|
361
|
+
* than coming back `undefined`.
|
|
362
|
+
*
|
|
363
|
+
* CALLABLE NAMESPACES (§9 finding): a member can be BOTH a function and a namespace — twilio's
|
|
364
|
+
* `client.messages` is called as `client.messages(sid)` to get one message's context AND read as
|
|
365
|
+
* `client.messages.list()`. An earlier version returned the modeled node as a plain object whenever
|
|
366
|
+
* this pack modeled any child of it, which silently DROPPED the call signature and every unmodeled
|
|
367
|
+
* sibling — the module's own docstring calls a dropped member "worse than free, because it is
|
|
368
|
+
* invisible", and that is what it was doing. So when `real` is callable the proxy target is a
|
|
369
|
+
* function and an `apply` trap charges the call, while `known` stays the source of modeled members.
|
|
370
|
+
*/
|
|
371
|
+
function proxyThrough(known: object, real: object, prefix: string, charge: Charge, owner?: object): object {
|
|
372
|
+
const callable = typeof real === 'function';
|
|
373
|
+
// The target must itself be callable for the `apply` trap to exist at all. `known` stays the
|
|
374
|
+
// source of modeled members, read explicitly below rather than through the target.
|
|
375
|
+
const target: object = callable ? function proxied() { /* every call goes through the trap */ } : known;
|
|
376
|
+
return new Proxy(target, {
|
|
377
|
+
apply(_t, _thisArg, args: unknown[]) {
|
|
378
|
+
// Calling the namespace is itself a request-builder hop: charge it, and keep the result
|
|
379
|
+
// behind the proxy (charge() re-proxies a non-thenable) so the eventual leaf is charged too.
|
|
380
|
+
// `owner` is the object the function was read from — dropping it would silently break every
|
|
381
|
+
// method that relies on `this`.
|
|
382
|
+
return charge(prefix || 'call', (...a) => (real as (...x: unknown[]) => unknown).apply(owner, a))(...args);
|
|
383
|
+
},
|
|
384
|
+
get(_t, prop, receiver) {
|
|
385
|
+
if (typeof prop === 'symbol') {
|
|
386
|
+
const ownSym = Reflect.get(known, prop, receiver);
|
|
387
|
+
if (ownSym !== undefined) return ownSym; // the GUARDED brand, and anything we model
|
|
388
|
+
const fromSym = (real as Record<symbol, unknown> | null)?.[prop];
|
|
389
|
+
if (ITERATOR_SYMBOLS.has(prop) && typeof fromSym === 'function') {
|
|
390
|
+
return charge(`${prefix}[${prop.description ?? 'iterator'}]`, (...args) => (fromSym as (...a: unknown[]) => unknown).apply(real, args));
|
|
391
|
+
}
|
|
392
|
+
return fromSym;
|
|
393
|
+
}
|
|
394
|
+
const name = String(prop);
|
|
395
|
+
if (NEVER_WRAP.has(name)) return Reflect.get(known, prop, receiver);
|
|
396
|
+
const key = prefix ? `${prefix}.${name}` : name;
|
|
397
|
+
const own = Reflect.get(known, prop, receiver);
|
|
398
|
+
const from = (real as Record<string, unknown> | null)?.[name];
|
|
399
|
+
// A member we model: the charged wrapper (a function) or a namespace we must keep descending
|
|
400
|
+
// into, so an unmodeled sibling is still priced rather than dropped.
|
|
401
|
+
if (typeof own === 'function') return own;
|
|
402
|
+
if (own && typeof own === 'object') {
|
|
403
|
+
// `from` may be an object OR a CALLABLE namespace — both keep descending, which is what
|
|
404
|
+
// preserves `client.messages(sid)` alongside the modeled `client.messages.list()`.
|
|
405
|
+
return from && (typeof from === 'object' || typeof from === 'function')
|
|
406
|
+
? proxyThrough(own, from, key, charge, real)
|
|
407
|
+
: own;
|
|
408
|
+
}
|
|
409
|
+
if (own !== undefined) return own;
|
|
410
|
+
// A member only the real client has. Functions go through proxyThrough too, so one that also
|
|
411
|
+
// carries members (a callable namespace) keeps both its call signature and its siblings.
|
|
412
|
+
if (typeof from === 'function') return proxyThrough({}, from, key, charge, real);
|
|
413
|
+
if (from && typeof from === 'object') return proxyThrough({}, from, key, charge, real);
|
|
414
|
+
return from;
|
|
415
|
+
},
|
|
416
|
+
has(_t, prop) {
|
|
417
|
+
return Reflect.has(known, prop) || (real !== null && Reflect.has(real, prop));
|
|
418
|
+
},
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** The HTTP status a value carries, if it looks like one (an SDK error, or a raw response). */
|
|
423
|
+
function responseStatus(v: unknown): number | undefined {
|
|
424
|
+
const s = (v as { status?: unknown } | null)?.status;
|
|
425
|
+
return typeof s === 'number' && Number.isFinite(s) ? s : undefined;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/**
|
|
429
|
+
* Response/error headers as a plain lower-cased record, or `undefined` when there are none. Accepts
|
|
430
|
+
* a `Headers` instance, a `Map`, or a plain object — an SDK's error type changes shape across
|
|
431
|
+
* versions and none of the three is worth depending on.
|
|
432
|
+
*/
|
|
433
|
+
function responseHeaders(v: unknown): Record<string, string> | undefined {
|
|
434
|
+
const h = (v as { headers?: unknown } | null)?.headers;
|
|
435
|
+
if (!h || typeof h !== 'object') return undefined;
|
|
436
|
+
const out: Record<string, string> = {};
|
|
437
|
+
if (typeof (h as Headers).forEach === 'function') {
|
|
438
|
+
(h as Headers).forEach((value: string, key: string) => { out[String(key).toLowerCase()] = String(value); });
|
|
439
|
+
} else {
|
|
440
|
+
for (const [k, value] of Object.entries(h as Record<string, unknown>)) out[k.toLowerCase()] = String(value);
|
|
441
|
+
}
|
|
442
|
+
return Object.keys(out).length > 0 ? out : undefined;
|
|
443
|
+
}
|