@bedrock-rbx/ocale 0.3.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -1
- package/dist/badges.d.mts +1 -1
- package/dist/badges.mjs +3 -3
- package/dist/{polling-Bs0GDvEa.d.mts → capacity-admission-BvnJjY0S.d.mts} +53 -14
- package/dist/capacity-admission-BvnJjY0S.d.mts.map +1 -0
- package/dist/developer-products.d.mts +1 -1
- package/dist/developer-products.mjs +4 -4
- package/dist/game-passes.d.mts +1 -1
- package/dist/game-passes.mjs +4 -4
- package/dist/index.d.mts +217 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +70 -5
- package/dist/index.mjs.map +1 -0
- package/dist/luau-execution.d.mts +39 -5
- package/dist/luau-execution.d.mts.map +1 -1
- package/dist/luau-execution.mjs +8 -13
- package/dist/luau-execution.mjs.map +1 -1
- package/dist/{rate-limit-Df55K34f.mjs → network-error-DR9FX5hb.mjs} +81 -36
- package/dist/network-error-DR9FX5hb.mjs.map +1 -0
- package/dist/places.d.mts +4 -4
- package/dist/places.d.mts.map +1 -1
- package/dist/places.mjs +8 -13
- package/dist/places.mjs.map +1 -1
- package/dist/{poll-timeout-DpEY-gAc.mjs → poll-timeout-3PXLsabj.mjs} +2 -2
- package/dist/{poll-timeout-DpEY-gAc.mjs.map → poll-timeout-3PXLsabj.mjs.map} +1 -1
- package/dist/{polling-helpers-BjFXyaOm.mjs → polling-helpers-CFuSt2O5.mjs} +349 -67
- package/dist/polling-helpers-CFuSt2O5.mjs.map +1 -0
- package/dist/{price-information-Brs8ebsh.mjs → price-information-D8BxwgTS.mjs} +2 -2
- package/dist/{price-information-Brs8ebsh.mjs.map → price-information-D8BxwgTS.mjs.map} +1 -1
- package/dist/resource-client--yYybltk.mjs +899 -0
- package/dist/resource-client--yYybltk.mjs.map +1 -0
- package/dist/resource-client-BivRq3JZ.d.mts +164 -0
- package/dist/resource-client-BivRq3JZ.d.mts.map +1 -0
- package/dist/retry-Cc4LcXYZ.mjs +1456 -0
- package/dist/retry-Cc4LcXYZ.mjs.map +1 -0
- package/dist/{retry-CdpA3z4A.d.mts → retry-DXEklFrt.d.mts} +51 -16
- package/dist/{retry-CdpA3z4A.d.mts.map → retry-DXEklFrt.d.mts.map} +1 -1
- package/dist/storage.d.mts +2 -157
- package/dist/storage.d.mts.map +1 -1
- package/dist/storage.mjs +3 -3
- package/dist/testing.d.mts +9 -17
- package/dist/testing.d.mts.map +1 -1
- package/dist/testing.mjs +1 -1
- package/dist/{types-mhEalVsR.d.mts → types-C3Egi37J.d.mts} +86 -10
- package/dist/types-C3Egi37J.d.mts.map +1 -0
- package/dist/universes.d.mts +1 -1
- package/dist/universes.mjs +4 -4
- package/dist/{validation-Cg2lBhpQ.mjs → validation-B_Zs1So2.mjs} +2 -2
- package/dist/{validation-Cg2lBhpQ.mjs.map → validation-B_Zs1So2.mjs.map} +1 -1
- package/package.json +1 -1
- package/dist/polling-Bs0GDvEa.d.mts.map +0 -1
- package/dist/polling-helpers-BjFXyaOm.mjs.map +0 -1
- package/dist/rate-limit-Df55K34f.mjs.map +0 -1
- package/dist/resource-client-DtfDWglY.mjs +0 -1177
- package/dist/resource-client-DtfDWglY.mjs.map +0 -1
- package/dist/retry-DM2-tlR8.mjs +0 -458
- package/dist/retry-DM2-tlR8.mjs.map +0 -1
- package/dist/types-mhEalVsR.d.mts.map +0 -1
|
@@ -0,0 +1,899 @@
|
|
|
1
|
+
import { a as ApiError, n as RateLimitError, o as requestContextOf, r as hasServerRetryGuidance } from "./network-error-DR9FX5hb.mjs";
|
|
2
|
+
import { _ as ABORTED, b as RequestAbortedError, c as defaultRetryDelay, f as RetryDelayExceededError, g as isUploadRequest, h as createFetchHttpClient, l as mergeConfig, m as PermissionError, p as RequestDeadlineExceededError, r as IDEMPOTENT_METHOD_DEFAULTS, s as computeRetryWaitMs, u as shouldRetry, v as raceWithAbortAsync, x as parseRateLimitHeaders, y as requestAbortedError } from "./retry-Cc4LcXYZ.mjs";
|
|
3
|
+
import { setTimeout } from "node:timers/promises";
|
|
4
|
+
//#region src/internal/utils/is-date-time-string.ts
|
|
5
|
+
/**
|
|
6
|
+
* Narrows `value` to a string that parses to a real {@link Date} via the
|
|
7
|
+
* `Date(string)` constructor. Used by resource parsers to gate
|
|
8
|
+
* `format: date-time` wire fields before handing them to `new Date(...)`,
|
|
9
|
+
* which silently produces an `Invalid Date` for invalid input.
|
|
10
|
+
*
|
|
11
|
+
* @param value - The unknown wire value to validate.
|
|
12
|
+
* @returns `true` when `value` is a string and `new Date(value).getTime()`
|
|
13
|
+
* is not `NaN`.
|
|
14
|
+
*/
|
|
15
|
+
function isDateTimeString(value) {
|
|
16
|
+
if (typeof value !== "string") return false;
|
|
17
|
+
const parsed = new Date(value);
|
|
18
|
+
return !Number.isNaN(parsed.getTime());
|
|
19
|
+
}
|
|
20
|
+
//#endregion
|
|
21
|
+
//#region src/internal/utils/is-record.ts
|
|
22
|
+
/**
|
|
23
|
+
* Narrows `value` to a plain JSON-style record. Excludes arrays, class
|
|
24
|
+
* instances, primitives, and `null`/`undefined`. Used by resource
|
|
25
|
+
* parsers to gate property access on wire bodies whose shape isn't
|
|
26
|
+
* known at compile time.
|
|
27
|
+
*
|
|
28
|
+
* @param value - The unknown value to narrow.
|
|
29
|
+
* @returns `true` when `value` is a plain `[object Object]`.
|
|
30
|
+
*/
|
|
31
|
+
function isRecord(value) {
|
|
32
|
+
return Object.prototype.toString.call(value) === "[object Object]";
|
|
33
|
+
}
|
|
34
|
+
//#endregion
|
|
35
|
+
//#region src/internal/utils/to-json-details.ts
|
|
36
|
+
/**
|
|
37
|
+
* Narrows an untyped response body to the `JSONValue` accepted by
|
|
38
|
+
* `ApiError.details`. `HttpResponse.body` is `unknown` because a transport may
|
|
39
|
+
* hand back anything, but only a JSON graph is safe to retain on an error for
|
|
40
|
+
* diagnostics. Anything else — functions, symbols, bigints, class instances,
|
|
41
|
+
* or a cyclic graph — is dropped rather than asserted through.
|
|
42
|
+
*
|
|
43
|
+
* @param value - The parsed response body, or `undefined` for an empty body.
|
|
44
|
+
* @returns The value as a `JSONValue`, or `undefined` when it is absent or not
|
|
45
|
+
* JSON-representable.
|
|
46
|
+
*/
|
|
47
|
+
function toJsonDetails(value) {
|
|
48
|
+
return asJsonValue(value, /* @__PURE__ */ new Set());
|
|
49
|
+
}
|
|
50
|
+
function asJsonValue(value, seen) {
|
|
51
|
+
if (value === null) return null;
|
|
52
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
|
|
53
|
+
if (Array.isArray(value)) return asJsonArray(value, seen);
|
|
54
|
+
if (isRecord(value)) return asJsonObject(value, seen);
|
|
55
|
+
}
|
|
56
|
+
function asJsonArray(value, seen) {
|
|
57
|
+
if (seen.has(value)) return;
|
|
58
|
+
seen.add(value);
|
|
59
|
+
const items = [];
|
|
60
|
+
for (const item of value) {
|
|
61
|
+
const converted = asJsonValue(item, seen);
|
|
62
|
+
if (converted === void 0) return;
|
|
63
|
+
items.push(converted);
|
|
64
|
+
}
|
|
65
|
+
seen.delete(value);
|
|
66
|
+
return items;
|
|
67
|
+
}
|
|
68
|
+
function asJsonObject(value, seen) {
|
|
69
|
+
if (seen.has(value)) return;
|
|
70
|
+
seen.add(value);
|
|
71
|
+
const entries = [];
|
|
72
|
+
for (const [key, item] of Object.entries(value)) {
|
|
73
|
+
const converted = asJsonValue(item, seen);
|
|
74
|
+
if (converted === void 0) return;
|
|
75
|
+
entries.push([key, converted]);
|
|
76
|
+
}
|
|
77
|
+
seen.delete(value);
|
|
78
|
+
return Object.fromEntries(entries);
|
|
79
|
+
}
|
|
80
|
+
//#endregion
|
|
81
|
+
//#region src/internal/http/admission-wait.ts
|
|
82
|
+
/**
|
|
83
|
+
* Performs one SDK-managed wait and emits a balanced request-scoped lifecycle.
|
|
84
|
+
* Observer failures are deliberately ignored: observation cannot become part
|
|
85
|
+
* of admission control.
|
|
86
|
+
*
|
|
87
|
+
* @template T - Value produced by the observed wait.
|
|
88
|
+
* @param options - Wait metadata, observer, and the wait operation itself.
|
|
89
|
+
* @returns The value produced by the wait.
|
|
90
|
+
*/
|
|
91
|
+
async function observeAdmissionWaitAsync({ durationMs, observer, reason, waitAsync }) {
|
|
92
|
+
const details = {
|
|
93
|
+
...durationMs === void 0 ? {} : { durationMs },
|
|
94
|
+
reason
|
|
95
|
+
};
|
|
96
|
+
notify(observer, {
|
|
97
|
+
...details,
|
|
98
|
+
phase: "started"
|
|
99
|
+
});
|
|
100
|
+
try {
|
|
101
|
+
return await waitAsync();
|
|
102
|
+
} finally {
|
|
103
|
+
notify(observer, {
|
|
104
|
+
...details,
|
|
105
|
+
phase: "ended"
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
function notify(observer, event) {
|
|
110
|
+
try {
|
|
111
|
+
const notification = observer?.(event);
|
|
112
|
+
if (notification !== void 0) Promise.resolve(notification).catch(Boolean);
|
|
113
|
+
} catch {}
|
|
114
|
+
}
|
|
115
|
+
//#endregion
|
|
116
|
+
//#region src/internal/http/budget-tracker.ts
|
|
117
|
+
const MS_PER_SECOND = 1e3;
|
|
118
|
+
/**
|
|
119
|
+
* Tracks the live rate-limit budget for a single scope. Primed by `observe`
|
|
120
|
+
* from response headers and drawn down by `reserve` as requests leave, so
|
|
121
|
+
* `waitMs` can pace requests across the window.
|
|
122
|
+
*
|
|
123
|
+
* Pacing has two regimes. While budget remains, requests are spread evenly over
|
|
124
|
+
* the time left in the window (`timeLeft / remaining`), so a burst does not
|
|
125
|
+
* spend the whole window's budget up front and then stall. Once the budget is
|
|
126
|
+
* spent, requests hold until the window resets. Budget and reset time move
|
|
127
|
+
* together as one window, so the tracker is either unprimed or fully primed,
|
|
128
|
+
* never half-known.
|
|
129
|
+
*/
|
|
130
|
+
var BudgetTracker = class {
|
|
131
|
+
/** Time (ms) the most recent request was allowed out, for spacing. */
|
|
132
|
+
#lastAllowedAt = void 0;
|
|
133
|
+
#window = void 0;
|
|
134
|
+
/**
|
|
135
|
+
* Folds a fresh server reading in, replacing any prior window. The latest
|
|
136
|
+
* reading wins: observe time is monotonic, so the most recently resolved
|
|
137
|
+
* response is the best current estimate. The spacing reference is left
|
|
138
|
+
* untouched so a window refresh does not reset pacing mid-stream.
|
|
139
|
+
*
|
|
140
|
+
* @param sample - Parsed `remaining`/`resetSeconds` from a response.
|
|
141
|
+
* @param now - The current time in ms.
|
|
142
|
+
*/
|
|
143
|
+
observe(sample, now) {
|
|
144
|
+
this.#window = {
|
|
145
|
+
predictedRemaining: sample.remaining,
|
|
146
|
+
resetAt: now + sample.resetSeconds * MS_PER_SECOND
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Accounts for one request leaving at `now`: records the spacing reference
|
|
151
|
+
* and decrements the prediction. A no-op on the prediction while unprimed.
|
|
152
|
+
*
|
|
153
|
+
* @param now - The time the request was allowed out, in ms.
|
|
154
|
+
*/
|
|
155
|
+
reserve(now) {
|
|
156
|
+
this.#lastAllowedAt = now;
|
|
157
|
+
if (this.#window !== void 0) this.#window = {
|
|
158
|
+
...this.#window,
|
|
159
|
+
predictedRemaining: this.#window.predictedRemaining - 1
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Milliseconds to wait before the next request is allowed.
|
|
164
|
+
*
|
|
165
|
+
* @param now - The current time in ms.
|
|
166
|
+
* @returns `0` when a request may go now (unprimed, or the first paced send);
|
|
167
|
+
* the time until reset when the budget is spent; otherwise the time until
|
|
168
|
+
* this request's evenly-spaced slot.
|
|
169
|
+
*/
|
|
170
|
+
waitMs(now) {
|
|
171
|
+
if (this.#window === void 0) return 0;
|
|
172
|
+
const { predictedRemaining, resetAt } = this.#window;
|
|
173
|
+
if (predictedRemaining <= 0) return Math.max(0, resetAt - now);
|
|
174
|
+
if (this.#lastAllowedAt === void 0) return 0;
|
|
175
|
+
const interval = (resetAt - now) / predictedRemaining;
|
|
176
|
+
return Math.max(0, this.#lastAllowedAt + interval - now);
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
//#endregion
|
|
180
|
+
//#region src/internal/http/request-deadline.ts
|
|
181
|
+
const DEADLINE_ELAPSED = Symbol("request deadline elapsed");
|
|
182
|
+
const MAX_ABORT_TIMEOUT_MS = 2147483647;
|
|
183
|
+
/**
|
|
184
|
+
* Resolves one signal that spans the whole logical request.
|
|
185
|
+
*
|
|
186
|
+
* @param deadlineMs - Absolute deadline, as Unix epoch milliseconds.
|
|
187
|
+
* @param callerSignal - Optional caller cancellation signal.
|
|
188
|
+
* @returns Signals that span and classify the logical request.
|
|
189
|
+
*/
|
|
190
|
+
function requestLifecycle(deadlineMs, callerSignal) {
|
|
191
|
+
if (deadlineMs === void 0) return {
|
|
192
|
+
deadlineMs,
|
|
193
|
+
deadlineSignal: void 0,
|
|
194
|
+
signal: callerSignal
|
|
195
|
+
};
|
|
196
|
+
const deadlineSignal = deadlineTimeout(deadlineMs);
|
|
197
|
+
return {
|
|
198
|
+
deadlineMs,
|
|
199
|
+
deadlineSignal,
|
|
200
|
+
signal: callerSignal === void 0 ? deadlineSignal : AbortSignal.any([callerSignal, deadlineSignal])
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Returns a typed failure when the deadline signal ended the request.
|
|
205
|
+
*
|
|
206
|
+
* @param lifecycle - Signals and timestamp for the logical request.
|
|
207
|
+
* @returns A deadline failure, or `undefined` when another signal won.
|
|
208
|
+
*/
|
|
209
|
+
function elapsedDeadlineFailure({ deadlineMs, deadlineSignal, signal }) {
|
|
210
|
+
if (deadlineMs === void 0 || deadlineSignal?.aborted !== true || !Object.is(signal?.reason, deadlineSignal.reason)) return;
|
|
211
|
+
return new RequestDeadlineExceededError("Request deadline elapsed", {
|
|
212
|
+
deadlineMs,
|
|
213
|
+
remainingMs: 0
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Reclassifies an internal abort when the request deadline supplied its signal.
|
|
218
|
+
*
|
|
219
|
+
* @param error - Error returned by the request pipeline.
|
|
220
|
+
* @param lifecycle - Signals and timestamp for the logical request.
|
|
221
|
+
* @returns A deadline failure, or `undefined` for other failures.
|
|
222
|
+
*/
|
|
223
|
+
function deadlineFailureFromError(error, lifecycle) {
|
|
224
|
+
return error instanceof RequestAbortedError ? elapsedDeadlineFailure(lifecycle) : void 0;
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Refuses a known admission wait that cannot fit before the deadline.
|
|
228
|
+
*
|
|
229
|
+
* @param inputs - Deadline, wait duration, reason, and optional cause.
|
|
230
|
+
* @returns A typed refusal, or `undefined` when the wait fits.
|
|
231
|
+
*/
|
|
232
|
+
function waitDeadlineFailure({ cause, deadlineMs, waitMs, waitReason }) {
|
|
233
|
+
if (deadlineMs === void 0) return;
|
|
234
|
+
const now = Date.now();
|
|
235
|
+
const remainingMs = Math.max(0, deadlineMs - now);
|
|
236
|
+
if (now < deadlineMs && waitMs <= remainingMs) return;
|
|
237
|
+
const options = {
|
|
238
|
+
cause,
|
|
239
|
+
deadlineMs,
|
|
240
|
+
remainingMs,
|
|
241
|
+
waitMs,
|
|
242
|
+
waitReason
|
|
243
|
+
};
|
|
244
|
+
return new RequestDeadlineExceededError(waitMessage(waitMs, remainingMs), options);
|
|
245
|
+
}
|
|
246
|
+
function armDeadlineTimeout(controller, deadlineMs) {
|
|
247
|
+
const remainingMs = deadlineMs - Date.now();
|
|
248
|
+
if (remainingMs <= 0) {
|
|
249
|
+
controller.abort(DEADLINE_ELAPSED);
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
AbortSignal.timeout(Math.min(Math.ceil(remainingMs), MAX_ABORT_TIMEOUT_MS)).addEventListener("abort", () => {
|
|
253
|
+
armDeadlineTimeout(controller, deadlineMs);
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
function deadlineTimeout(deadlineMs) {
|
|
257
|
+
const controller = new AbortController();
|
|
258
|
+
if (Number.isFinite(deadlineMs)) armDeadlineTimeout(controller, deadlineMs);
|
|
259
|
+
else controller.abort(DEADLINE_ELAPSED);
|
|
260
|
+
return controller.signal;
|
|
261
|
+
}
|
|
262
|
+
function waitMessage(waitMs, remainingMs) {
|
|
263
|
+
return `Admission wait would take ${waitMs / 1e3}s; ${remainingMs / 1e3}s remain before the request deadline`;
|
|
264
|
+
}
|
|
265
|
+
//#endregion
|
|
266
|
+
//#region src/internal/http/budget-gate.ts
|
|
267
|
+
const REPORTED_BUDGET_REASON = "reported-budget";
|
|
268
|
+
/**
|
|
269
|
+
* Header-primed rate-limit gate shared across a client. Holds one
|
|
270
|
+
* {@link BudgetTracker} per {@link BudgetScope}. Before each request the caller
|
|
271
|
+
* gates on the request's scope (sleeping if that budget is spent), and after
|
|
272
|
+
* each response folds the parsed sample back in, so a later call on the same
|
|
273
|
+
* scope can head off a 429 the static per-operation token bucket cannot
|
|
274
|
+
* foresee.
|
|
275
|
+
*
|
|
276
|
+
* Gating is serialized per scope through a promise chain so concurrent
|
|
277
|
+
* requests on one scope cannot read the same budget and reserve the same slot;
|
|
278
|
+
* each waits for the prior gate's reserve before computing its own.
|
|
279
|
+
*/
|
|
280
|
+
var BudgetGate = class {
|
|
281
|
+
#chains = /* @__PURE__ */ new Map();
|
|
282
|
+
#pendingGates = /* @__PURE__ */ new Map();
|
|
283
|
+
#sleep;
|
|
284
|
+
#trackers = /* @__PURE__ */ new Map();
|
|
285
|
+
/**
|
|
286
|
+
* Creates a gate bound to an injectable sleep.
|
|
287
|
+
*
|
|
288
|
+
* @param sleep - Injectable sleep (tests pass a fake clock).
|
|
289
|
+
*/
|
|
290
|
+
constructor(sleep) {
|
|
291
|
+
this.#sleep = sleep;
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Holds until the scope's budget permits a send, then reserves one slot.
|
|
295
|
+
* Runs after the prior gate on the same scope settles, whether it resolved
|
|
296
|
+
* or rejected, so one failed attempt cannot poison later gates on the
|
|
297
|
+
* scope.
|
|
298
|
+
*
|
|
299
|
+
* @param scope - The API key and operation to gate on.
|
|
300
|
+
* @param context - Request-local observer and cancellation signal.
|
|
301
|
+
* @rejects {@link RequestAbortedError} when the caller cancels while waiting.
|
|
302
|
+
*/
|
|
303
|
+
async gateAsync(scope, { deadlineMs, observer, signal } = {}) {
|
|
304
|
+
const key = scopeKey(scope);
|
|
305
|
+
const pendingGates = this.#pendingGates.get(key) ?? 0;
|
|
306
|
+
const waitsForEarlierGate = pendingGates > 0;
|
|
307
|
+
this.#pendingGates.set(key, pendingGates + 1);
|
|
308
|
+
const completed = (this.#chains.get(key) ?? Promise.resolve()).catch(ignoreRejection$1).then(async () => {
|
|
309
|
+
return this.#gateOnce(key, {
|
|
310
|
+
deadlineMs,
|
|
311
|
+
observer: waitsForEarlierGate ? void 0 : observer,
|
|
312
|
+
signal
|
|
313
|
+
});
|
|
314
|
+
}).finally(() => {
|
|
315
|
+
const remainingGates = (this.#pendingGates.get(key) ?? 1) - 1;
|
|
316
|
+
this.#pendingGates.set(key, remainingGates);
|
|
317
|
+
});
|
|
318
|
+
this.#chains.set(key, completed.catch(ignoreRejection$1));
|
|
319
|
+
if (waitsForEarlierGate) await observeAdmissionWaitAsync({
|
|
320
|
+
observer,
|
|
321
|
+
reason: REPORTED_BUDGET_REASON,
|
|
322
|
+
waitAsync: async () => waitForGateAsync(completed, signal)
|
|
323
|
+
});
|
|
324
|
+
else await waitForGateAsync(completed, signal);
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Folds a response's parsed budget back onto the scope. A `undefined`
|
|
328
|
+
* sample (headers absent or non-numeric) is ignored, leaving the scope on
|
|
329
|
+
* static pacing.
|
|
330
|
+
*
|
|
331
|
+
* @param scope - The same scope passed to {@link gateAsync}.
|
|
332
|
+
* @param sample - Parsed sample, or `undefined` when none was reported.
|
|
333
|
+
*/
|
|
334
|
+
observe(scope, sample) {
|
|
335
|
+
if (sample === void 0) return;
|
|
336
|
+
this.#tracker(scopeKey(scope)).observe(sample, Date.now());
|
|
337
|
+
}
|
|
338
|
+
async #gateOnce(key, { deadlineMs, observer, signal }) {
|
|
339
|
+
if (signal?.aborted === true) throw requestAbortedError(signal);
|
|
340
|
+
const tracker = this.#tracker(key);
|
|
341
|
+
const waitMs = tracker.waitMs(Date.now());
|
|
342
|
+
if (waitMs > 0) await this.#waitAsync(waitMs, {
|
|
343
|
+
deadlineMs,
|
|
344
|
+
observer,
|
|
345
|
+
signal
|
|
346
|
+
});
|
|
347
|
+
tracker.reserve(Date.now());
|
|
348
|
+
}
|
|
349
|
+
#tracker(key) {
|
|
350
|
+
const existing = this.#trackers.get(key);
|
|
351
|
+
if (existing !== void 0) return existing;
|
|
352
|
+
const tracker = new BudgetTracker();
|
|
353
|
+
this.#trackers.set(key, tracker);
|
|
354
|
+
return tracker;
|
|
355
|
+
}
|
|
356
|
+
async #waitAsync(waitMs, { deadlineMs, observer, signal }) {
|
|
357
|
+
const refusal = waitDeadlineFailure({
|
|
358
|
+
deadlineMs,
|
|
359
|
+
waitMs,
|
|
360
|
+
waitReason: REPORTED_BUDGET_REASON
|
|
361
|
+
});
|
|
362
|
+
if (refusal !== void 0) throw refusal;
|
|
363
|
+
await observeAdmissionWaitAsync({
|
|
364
|
+
durationMs: waitMs,
|
|
365
|
+
observer,
|
|
366
|
+
reason: REPORTED_BUDGET_REASON,
|
|
367
|
+
waitAsync: async () => {
|
|
368
|
+
if (await raceWithAbortAsync(async () => this.#sleep(waitMs, signal), signal) === ABORTED) throw requestAbortedError(signal);
|
|
369
|
+
}
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
};
|
|
373
|
+
function ignoreRejection$1() {}
|
|
374
|
+
async function waitForGateAsync(gate, signal) {
|
|
375
|
+
if (await raceWithAbortAsync(async () => gate, signal) === ABORTED) throw requestAbortedError(signal);
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Composes the map key one budget window is tracked under.
|
|
379
|
+
*
|
|
380
|
+
* @param scope - The API key and operation naming the window.
|
|
381
|
+
* @returns The key for the tracker and chain maps.
|
|
382
|
+
*/
|
|
383
|
+
function scopeKey({ apiKey, operationKey }) {
|
|
384
|
+
return `${apiKey}::${operationKey}`;
|
|
385
|
+
}
|
|
386
|
+
//#endregion
|
|
387
|
+
//#region src/internal/http/execute.ts
|
|
388
|
+
/**
|
|
389
|
+
* Retry-aware orchestration loop. Coordinates a single logical request,
|
|
390
|
+
* looping over `options.send` until it succeeds, the error is non-retryable,
|
|
391
|
+
* or `options.config.maxRetries` is exhausted. Fires observability hooks
|
|
392
|
+
* at each transition. Domain- and queue-agnostic: `send` may be any
|
|
393
|
+
* callback, including one wrapped by a rate-limit queue.
|
|
394
|
+
*
|
|
395
|
+
* @param request - The immutable request to send.
|
|
396
|
+
* @param options - The transport callback, resolved config, hooks, and sleep.
|
|
397
|
+
* @returns The first success, or the final error after retries are exhausted.
|
|
398
|
+
*/
|
|
399
|
+
async function executeWithRetryAsync(request, options) {
|
|
400
|
+
const { admissionWaitObserver, config, deadlineMs, hooks, signal, sleep } = options;
|
|
401
|
+
if (signal?.aborted === true) return abortedResult(signal);
|
|
402
|
+
let result = await attemptAsync(request, options);
|
|
403
|
+
for (let retry = 0; retry < config.maxRetries; retry++) {
|
|
404
|
+
if (result.success || !shouldRetry(result.err, config)) return result;
|
|
405
|
+
const { err } = result;
|
|
406
|
+
const waitMs = computeRetryWaitMs(err, {
|
|
407
|
+
attempt: retry,
|
|
408
|
+
retryDelay: config.retryDelay
|
|
409
|
+
});
|
|
410
|
+
const refusal = retryRefusal({
|
|
411
|
+
cause: err,
|
|
412
|
+
deadlineMs,
|
|
413
|
+
retryAfterMs: waitMs
|
|
414
|
+
});
|
|
415
|
+
if (refusal !== void 0) return {
|
|
416
|
+
err: refusal,
|
|
417
|
+
success: false
|
|
418
|
+
};
|
|
419
|
+
announceRetry({
|
|
420
|
+
attempt: retry + 1,
|
|
421
|
+
error: err,
|
|
422
|
+
hooks,
|
|
423
|
+
waitMs
|
|
424
|
+
});
|
|
425
|
+
if (await observeAdmissionWaitAsync({
|
|
426
|
+
durationMs: waitMs,
|
|
427
|
+
observer: admissionWaitObserver,
|
|
428
|
+
reason: "retry-delay",
|
|
429
|
+
waitAsync: async () => raceWithAbortAsync(async () => sleep(waitMs, signal), signal)
|
|
430
|
+
}) === ABORTED) return abortedResult(signal);
|
|
431
|
+
result = await attemptAsync(request, options);
|
|
432
|
+
}
|
|
433
|
+
return result;
|
|
434
|
+
}
|
|
435
|
+
function announceRetry({ attempt, error, hooks, waitMs }) {
|
|
436
|
+
hooks.onRetry?.(attempt, error);
|
|
437
|
+
hooks.onRateLimit?.(waitMs);
|
|
438
|
+
}
|
|
439
|
+
function retryRefusal({ cause, deadlineMs, retryAfterMs }) {
|
|
440
|
+
if (deadlineMs === void 0) return;
|
|
441
|
+
const refusal = waitDeadlineFailure({
|
|
442
|
+
cause,
|
|
443
|
+
deadlineMs,
|
|
444
|
+
waitMs: retryAfterMs,
|
|
445
|
+
waitReason: "retry-delay"
|
|
446
|
+
});
|
|
447
|
+
if (refusal === void 0) return;
|
|
448
|
+
const { remainingMs } = refusal;
|
|
449
|
+
return new RetryDelayExceededError(`Retry delay would wait ${retryAfterMs / 1e3}s; ${remainingMs / 1e3}s remain before the request deadline`, {
|
|
450
|
+
cause,
|
|
451
|
+
deadlineMs,
|
|
452
|
+
remainingMs,
|
|
453
|
+
retryAfterMs
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
function abortedResult(signal) {
|
|
457
|
+
return {
|
|
458
|
+
err: requestAbortedError(signal),
|
|
459
|
+
success: false
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
async function attemptAsync(request, { hooks, send, signal }) {
|
|
463
|
+
hooks.onRequest?.(request);
|
|
464
|
+
const attempt = await raceWithAbortAsync(async () => send(request), signal);
|
|
465
|
+
return attempt === ABORTED ? abortedResult(signal) : attempt;
|
|
466
|
+
}
|
|
467
|
+
//#endregion
|
|
468
|
+
//#region src/internal/http/rate-limit-observation.ts
|
|
469
|
+
/**
|
|
470
|
+
* Extracts a {@link RateLimitSample} from a transport result so the budget gate
|
|
471
|
+
* can be fed from every attempt. A 2xx carries the budget in its headers. A 429
|
|
472
|
+
* only primes the gate when it reports zero remaining and valid guidance. This
|
|
473
|
+
* is a conservative scheduling condition, not a semantic classification of the
|
|
474
|
+
* 429. Any other error yields `undefined`.
|
|
475
|
+
*
|
|
476
|
+
* @param result - The classified transport result for one attempt.
|
|
477
|
+
* @returns The parsed sample, or `undefined` when none was reported.
|
|
478
|
+
*/
|
|
479
|
+
function rateLimitSampleFromResult(result) {
|
|
480
|
+
if (result.success) return parseRateLimitHeaders(result.data.headers);
|
|
481
|
+
const { err } = result;
|
|
482
|
+
if (err instanceof RateLimitError && err.remaining === 0 && hasServerRetryGuidance(err)) return {
|
|
483
|
+
remaining: err.remaining,
|
|
484
|
+
resetSeconds: err.retryAfterSeconds
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
//#endregion
|
|
488
|
+
//#region src/internal/http/rate-limit-queue.ts
|
|
489
|
+
const OPERATION_QUEUE_REASON = "operation-queue";
|
|
490
|
+
/**
|
|
491
|
+
* Token-bucket rate limiter for a single `(apiKey, operation)` pair. Every
|
|
492
|
+
* call to `acquire` consumes one token; when the bucket is empty the call
|
|
493
|
+
* waits until a token regenerates before invoking the task. Tokens refill at
|
|
494
|
+
* `maxPerSecond` per second, up to the operation's `burstCapacity`.
|
|
495
|
+
*
|
|
496
|
+
* Implemented as a leaky bucket tracking drain debt in ms. `#lastCheck`
|
|
497
|
+
* advances by `waitMs` after every sleep so the algorithm stays correct
|
|
498
|
+
* whether or not the injected sleep moves `Date.now()` forward. `#bucketLevel`
|
|
499
|
+
* and `#maxBucketLevel` are both ms of drain debt, so the ceiling is the burst
|
|
500
|
+
* expressed in that unit: `burstCapacity` refill intervals. Deriving it any
|
|
501
|
+
* other way (notably `maxPerSecond * intervalMs`, whose units cancel to a
|
|
502
|
+
* constant 1000) starves every operation slower than one request per second.
|
|
503
|
+
*/
|
|
504
|
+
var RateLimitQueue = class {
|
|
505
|
+
#hooks;
|
|
506
|
+
#intervalMs;
|
|
507
|
+
#maxBucketLevel;
|
|
508
|
+
#sleep;
|
|
509
|
+
#bucketLevel = 0;
|
|
510
|
+
#chain = Promise.resolve();
|
|
511
|
+
#lastCheck = Date.now();
|
|
512
|
+
#pendingAcquisitions = 0;
|
|
513
|
+
/**
|
|
514
|
+
* Creates a rate-limit queue bound to a single operation.
|
|
515
|
+
*
|
|
516
|
+
* @param limit - The operation key and its per-second request ceiling.
|
|
517
|
+
* @param hooks - Observability callbacks; `onRateLimit` fires when the
|
|
518
|
+
* bucket is empty and a sleep is about to start.
|
|
519
|
+
* @param sleep - Injectable sleep (tests pass a fake).
|
|
520
|
+
*/
|
|
521
|
+
constructor(limit, hooks, sleep) {
|
|
522
|
+
this.#intervalMs = 1e3 / limit.maxPerSecond;
|
|
523
|
+
const burstCapacity = limit.burstCapacity ?? Math.max(1, limit.maxPerSecond);
|
|
524
|
+
this.#maxBucketLevel = burstCapacity * this.#intervalMs;
|
|
525
|
+
this.#hooks = hooks;
|
|
526
|
+
this.#sleep = sleep;
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* Waits for a token — sleeping and firing `hooks.onRateLimit` if the
|
|
530
|
+
* bucket is empty — then executes `task`. Concurrent callers are
|
|
531
|
+
* serialized at token acquisition; tasks themselves run independently
|
|
532
|
+
* once their token is secured.
|
|
533
|
+
*
|
|
534
|
+
* @param task - The request to run once a token is available.
|
|
535
|
+
* @param context - Request-local observer and cancellation signal.
|
|
536
|
+
* @returns The value produced by `task`.
|
|
537
|
+
* @rejects {@link RequestAbortedError} when the caller cancels while queued.
|
|
538
|
+
*/
|
|
539
|
+
async acquireAsync(task, { deadlineMs, observer, signal } = {}) {
|
|
540
|
+
const waitsForEarlierAcquisition = this.#pendingAcquisitions > 0;
|
|
541
|
+
this.#pendingAcquisitions++;
|
|
542
|
+
const waitForTokenAsync = async () => {
|
|
543
|
+
return this.#waitForToken({
|
|
544
|
+
deadlineMs,
|
|
545
|
+
observer: waitsForEarlierAcquisition ? void 0 : observer,
|
|
546
|
+
signal
|
|
547
|
+
});
|
|
548
|
+
};
|
|
549
|
+
const completed = this.#chain.catch(ignoreRejection).then(waitForTokenAsync).finally(() => {
|
|
550
|
+
this.#pendingAcquisitions--;
|
|
551
|
+
});
|
|
552
|
+
this.#chain = completed.catch(ignoreRejection);
|
|
553
|
+
if (waitsForEarlierAcquisition) await observeAdmissionWaitAsync({
|
|
554
|
+
observer,
|
|
555
|
+
reason: OPERATION_QUEUE_REASON,
|
|
556
|
+
waitAsync: async () => waitForTurnAsync(completed, signal)
|
|
557
|
+
});
|
|
558
|
+
else await waitForTurnAsync(completed, signal);
|
|
559
|
+
return task();
|
|
560
|
+
}
|
|
561
|
+
async #waitAsync({ deadlineMs, now, observer, signal, waitMs }) {
|
|
562
|
+
const refusal = waitDeadlineFailure({
|
|
563
|
+
deadlineMs,
|
|
564
|
+
waitMs,
|
|
565
|
+
waitReason: OPERATION_QUEUE_REASON
|
|
566
|
+
});
|
|
567
|
+
if (refusal !== void 0) throw refusal;
|
|
568
|
+
this.#hooks.onRateLimit?.(waitMs);
|
|
569
|
+
await observeAdmissionWaitAsync({
|
|
570
|
+
durationMs: waitMs,
|
|
571
|
+
observer,
|
|
572
|
+
reason: OPERATION_QUEUE_REASON,
|
|
573
|
+
waitAsync: async () => {
|
|
574
|
+
if (await raceWithAbortAsync(async () => this.#sleep(waitMs, signal), signal) === ABORTED) throw requestAbortedError(signal);
|
|
575
|
+
}
|
|
576
|
+
});
|
|
577
|
+
this.#bucketLevel = this.#maxBucketLevel;
|
|
578
|
+
this.#lastCheck = now + waitMs;
|
|
579
|
+
}
|
|
580
|
+
async #waitForToken({ deadlineMs, observer, signal }) {
|
|
581
|
+
if (signal?.aborted === true) throw requestAbortedError(signal);
|
|
582
|
+
const now = Math.max(Date.now(), this.#lastCheck);
|
|
583
|
+
const drained = Math.max(0, this.#bucketLevel - (now - this.#lastCheck));
|
|
584
|
+
this.#lastCheck = now;
|
|
585
|
+
if (drained + this.#intervalMs <= this.#maxBucketLevel) {
|
|
586
|
+
this.#bucketLevel = drained + this.#intervalMs;
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
const waitMs = drained + this.#intervalMs - this.#maxBucketLevel;
|
|
590
|
+
await this.#waitAsync({
|
|
591
|
+
deadlineMs,
|
|
592
|
+
now,
|
|
593
|
+
observer,
|
|
594
|
+
signal,
|
|
595
|
+
waitMs
|
|
596
|
+
});
|
|
597
|
+
}
|
|
598
|
+
};
|
|
599
|
+
function ignoreRejection() {}
|
|
600
|
+
async function waitForTurnAsync(turn, signal) {
|
|
601
|
+
if (await raceWithAbortAsync(async () => turn, signal) === ABORTED) throw requestAbortedError(signal);
|
|
602
|
+
}
|
|
603
|
+
//#endregion
|
|
604
|
+
//#region src/internal/utils/sleep.ts
|
|
605
|
+
/**
|
|
606
|
+
* Timer-backed production sleep that releases its timer on cancellation.
|
|
607
|
+
*
|
|
608
|
+
* @param ms - Duration to wait in milliseconds.
|
|
609
|
+
* @param signal - Optional caller cancellation signal.
|
|
610
|
+
*/
|
|
611
|
+
async function defaultSleepAsync(ms, signal) {
|
|
612
|
+
await setTimeout(ms, void 0, { signal });
|
|
613
|
+
}
|
|
614
|
+
//#endregion
|
|
615
|
+
//#region src/internal/http/resolve-dependencies.ts
|
|
616
|
+
/**
|
|
617
|
+
* Resolves the concrete HTTP client and sleep implementation a resource
|
|
618
|
+
* client should use. Falls back to the fetch-backed HTTP client and the
|
|
619
|
+
* default `setTimeout`-based sleep when the caller omits the test seams.
|
|
620
|
+
*
|
|
621
|
+
* Extracted so resource client constructors can keep their dependency
|
|
622
|
+
* resolution logic in a single, unit-testable place; this makes the
|
|
623
|
+
* default branches easy to cover without stubbing globals like `fetch`.
|
|
624
|
+
*
|
|
625
|
+
* @param options - Optional {@link HttpClient} and {@link SleepFunc} test seams.
|
|
626
|
+
* @returns A {@link ResolvedDependencies} with defaults applied.
|
|
627
|
+
*/
|
|
628
|
+
function resolveDependencies(options) {
|
|
629
|
+
return {
|
|
630
|
+
httpClient: options.httpClient ?? createFetchHttpClient(),
|
|
631
|
+
sleep: options.sleep ?? defaultSleepAsync
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
//#endregion
|
|
635
|
+
//#region src/internal/resource-client.ts
|
|
636
|
+
/**
|
|
637
|
+
* Wraps an infallible request build as a {@link Result}-returning
|
|
638
|
+
* `buildRequest` callback compatible with {@link ResourceMethodSpec}.
|
|
639
|
+
* Use from a resource client whose builder cannot fail; resource clients
|
|
640
|
+
* with local validation should construct the {@link Result} directly.
|
|
641
|
+
*
|
|
642
|
+
* @param request - The pre-built {@link HttpRequest}.
|
|
643
|
+
* @returns A success Result wrapping the request.
|
|
644
|
+
*/
|
|
645
|
+
function okRequest(request) {
|
|
646
|
+
return {
|
|
647
|
+
data: request,
|
|
648
|
+
success: true
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
/**
|
|
652
|
+
* A {@link ResourceMethodSpec.parse} implementation for endpoints that return
|
|
653
|
+
* no business payload on success (such as `DELETE` and reorder operations).
|
|
654
|
+
* Surfaces `undefined` data and never inspects the response body.
|
|
655
|
+
*
|
|
656
|
+
* @returns A success Result with `undefined` data.
|
|
657
|
+
*/
|
|
658
|
+
function parseEmptyResponse() {
|
|
659
|
+
return {
|
|
660
|
+
data: void 0,
|
|
661
|
+
success: true
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
const CLIENT_DEFAULTS = Object.freeze({
|
|
665
|
+
baseUrl: "https://apis.roblox.com",
|
|
666
|
+
maxRetries: 3,
|
|
667
|
+
retryableStatuses: IDEMPOTENT_METHOD_DEFAULTS.retryableStatuses,
|
|
668
|
+
retryableTransportCodes: IDEMPOTENT_METHOD_DEFAULTS.retryableTransportCodes,
|
|
669
|
+
retryDelay: defaultRetryDelay,
|
|
670
|
+
timeout: 3e4
|
|
671
|
+
});
|
|
672
|
+
/**
|
|
673
|
+
* Internal orchestrator shared by every Open Cloud resource client. Holds
|
|
674
|
+
* the frozen client config, observability hooks, injected HTTP client and
|
|
675
|
+
* sleep, and the per-effective-key rate-limit queue registry. Resource
|
|
676
|
+
* classes compose one instance and dispatch every public method through
|
|
677
|
+
* {@link ResourceClient.executeAsync} with a per-method {@link ResourceMethodSpec}.
|
|
678
|
+
* Not exported from any package subpath; reachable only via sibling
|
|
679
|
+
* `src/resources/**` modules in this package.
|
|
680
|
+
*/
|
|
681
|
+
var ResourceClient = class {
|
|
682
|
+
#budgets;
|
|
683
|
+
#config;
|
|
684
|
+
#hooks;
|
|
685
|
+
#httpClient;
|
|
686
|
+
#queues = /* @__PURE__ */ new Map();
|
|
687
|
+
#sleep;
|
|
688
|
+
/**
|
|
689
|
+
* Creates a new {@link ResourceClient}. Resolves the injected HTTP
|
|
690
|
+
* client and sleep (defaulting to fetch + `setTimeout`) and freezes the
|
|
691
|
+
* merged client config so subsequent calls cannot mutate it.
|
|
692
|
+
*
|
|
693
|
+
* @param options - Client-level configuration including the API key
|
|
694
|
+
* and optional construction-time test seams.
|
|
695
|
+
*/
|
|
696
|
+
constructor({ apiKey, hooks, httpClient, sleep, ...overrides }) {
|
|
697
|
+
const resolved = resolveDependencies({
|
|
698
|
+
httpClient,
|
|
699
|
+
sleep
|
|
700
|
+
});
|
|
701
|
+
this.#httpClient = resolved.httpClient;
|
|
702
|
+
this.#sleep = resolved.sleep;
|
|
703
|
+
this.#budgets = new BudgetGate(this.#sleep);
|
|
704
|
+
this.#hooks = hooks ?? {};
|
|
705
|
+
this.#config = Object.freeze({
|
|
706
|
+
...CLIENT_DEFAULTS,
|
|
707
|
+
apiKey,
|
|
708
|
+
...overrides
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
/**
|
|
712
|
+
* Dispatches a single resource-method call. Merges the frozen client
|
|
713
|
+
* config with the method's `methodDefaults` and the caller's optional
|
|
714
|
+
* per-request `options`, routes through the effective-apiKey rate-limit
|
|
715
|
+
* queue, runs the retry loop, and finally parses the response with the
|
|
716
|
+
* spec's parser.
|
|
717
|
+
*
|
|
718
|
+
* @param call - The per-method spec, resource-specific parameters, and
|
|
719
|
+
* optional per-request overrides.
|
|
720
|
+
* @returns The parsed success payload or the {@link OpenCloudError} that
|
|
721
|
+
* caused the request to fail. Never throws.
|
|
722
|
+
* @rejects An unexpected collaborator failure unrelated to caller cancellation.
|
|
723
|
+
*/
|
|
724
|
+
async executeAsync({ options, parameters, refineError, spec }) {
|
|
725
|
+
const start = startRequest(options);
|
|
726
|
+
if (!start.success) return start;
|
|
727
|
+
const { admission, lifecycle, requestOptions } = start.data;
|
|
728
|
+
const merged = mergeConfig(this.#config, {
|
|
729
|
+
methodDefaults: spec.methodDefaults,
|
|
730
|
+
methodKind: spec.methodKind,
|
|
731
|
+
requestOptions
|
|
732
|
+
});
|
|
733
|
+
const requestResult = spec.buildRequest(parameters);
|
|
734
|
+
if (!requestResult.success) return requestResult;
|
|
735
|
+
const request = requestResult.data;
|
|
736
|
+
const { signal } = admission;
|
|
737
|
+
const requestConfig = buildRequestConfig({
|
|
738
|
+
merged,
|
|
739
|
+
options,
|
|
740
|
+
request,
|
|
741
|
+
signal
|
|
742
|
+
});
|
|
743
|
+
return finishRequest({
|
|
744
|
+
httpResult: await this.#dispatchAsync({
|
|
745
|
+
admission,
|
|
746
|
+
merged,
|
|
747
|
+
operationLimit: spec.operationLimit,
|
|
748
|
+
refineError,
|
|
749
|
+
request,
|
|
750
|
+
requestConfig
|
|
751
|
+
}),
|
|
752
|
+
lifecycle,
|
|
753
|
+
spec
|
|
754
|
+
});
|
|
755
|
+
}
|
|
756
|
+
/**
|
|
757
|
+
* Returns the sleep function used by this client instance.
|
|
758
|
+
*
|
|
759
|
+
* @returns The sleep function injected at construction time.
|
|
760
|
+
*/
|
|
761
|
+
get sleep() {
|
|
762
|
+
return this.#sleep;
|
|
763
|
+
}
|
|
764
|
+
async #dispatchAsync({ admission, merged, operationLimit, refineError, request, requestConfig }) {
|
|
765
|
+
const queue = this.#getQueue(merged.apiKey, operationLimit);
|
|
766
|
+
try {
|
|
767
|
+
return await queue.acquireAsync(async () => {
|
|
768
|
+
return executeWithRetryAsync(request, {
|
|
769
|
+
admissionWaitObserver: admission.observer,
|
|
770
|
+
config: merged,
|
|
771
|
+
deadlineMs: admission.deadlineMs,
|
|
772
|
+
hooks: this.#hooks,
|
|
773
|
+
send: this.#gatedSend({
|
|
774
|
+
admission,
|
|
775
|
+
refineError,
|
|
776
|
+
requestConfig,
|
|
777
|
+
scope: {
|
|
778
|
+
apiKey: merged.apiKey,
|
|
779
|
+
operationKey: operationLimit.operationKey
|
|
780
|
+
}
|
|
781
|
+
}),
|
|
782
|
+
signal: admission.signal,
|
|
783
|
+
sleep: this.#sleep
|
|
784
|
+
});
|
|
785
|
+
}, admission);
|
|
786
|
+
} catch (err) {
|
|
787
|
+
return dispatchFailure(err);
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
/**
|
|
791
|
+
* Builds the transport callback for one logical call, wrapping the HTTP
|
|
792
|
+
* client with the budget gate: each attempt waits on the scope's budget
|
|
793
|
+
* before sending, then folds the response's reported budget back in so the
|
|
794
|
+
* next attempt (or a later call on the same scope) can head off a 429.
|
|
795
|
+
*
|
|
796
|
+
* @param inputs - Budget scope, transport config, observer, and caller signal.
|
|
797
|
+
* @returns A send callback for {@link executeWithRetryAsync}.
|
|
798
|
+
*/
|
|
799
|
+
#gatedSend({ admission, refineError, requestConfig, scope }) {
|
|
800
|
+
return async (toSend) => {
|
|
801
|
+
await this.#budgets.gateAsync(scope, admission);
|
|
802
|
+
const transportResult = await this.#httpClient.request(toSend, requestConfig);
|
|
803
|
+
const sendResult = refineError === void 0 || transportResult.success ? transportResult : {
|
|
804
|
+
err: refineError(transportResult.err),
|
|
805
|
+
success: false
|
|
806
|
+
};
|
|
807
|
+
this.#budgets.observe(scope, rateLimitSampleFromResult(transportResult));
|
|
808
|
+
return sendResult;
|
|
809
|
+
};
|
|
810
|
+
}
|
|
811
|
+
#getQueue(apiKey, limit) {
|
|
812
|
+
const key = `${apiKey}::${limit.operationKey}`;
|
|
813
|
+
const existing = this.#queues.get(key);
|
|
814
|
+
if (existing !== void 0) return existing;
|
|
815
|
+
const queue = new RateLimitQueue(limit, this.#hooks, this.#sleep);
|
|
816
|
+
this.#queues.set(key, queue);
|
|
817
|
+
return queue;
|
|
818
|
+
}
|
|
819
|
+
};
|
|
820
|
+
function startRequest(options) {
|
|
821
|
+
const callerSignal = options?.signal;
|
|
822
|
+
if (callerSignal?.aborted === true) return {
|
|
823
|
+
err: requestAbortedError(callerSignal),
|
|
824
|
+
success: false
|
|
825
|
+
};
|
|
826
|
+
const lifecycle = requestLifecycle(options?.deadlineMs, callerSignal);
|
|
827
|
+
const deadlineFailure = elapsedDeadlineFailure(lifecycle);
|
|
828
|
+
if (deadlineFailure !== void 0) return {
|
|
829
|
+
err: deadlineFailure,
|
|
830
|
+
success: false
|
|
831
|
+
};
|
|
832
|
+
const { deadlineMs, onAdmissionWait, signal: _signal, ...requestOptions } = options ?? {};
|
|
833
|
+
return {
|
|
834
|
+
data: {
|
|
835
|
+
admission: {
|
|
836
|
+
deadlineMs,
|
|
837
|
+
observer: onAdmissionWait,
|
|
838
|
+
signal: lifecycle.signal
|
|
839
|
+
},
|
|
840
|
+
lifecycle,
|
|
841
|
+
requestOptions
|
|
842
|
+
},
|
|
843
|
+
success: true
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
function dispatchFailure(err) {
|
|
847
|
+
if (err instanceof RequestAbortedError || err instanceof RequestDeadlineExceededError) return {
|
|
848
|
+
err,
|
|
849
|
+
success: false
|
|
850
|
+
};
|
|
851
|
+
throw err;
|
|
852
|
+
}
|
|
853
|
+
/**
|
|
854
|
+
* Resolves the per-request {@link RequestConfig}. Upload requests
|
|
855
|
+
* ({@link isUploadRequest}) carry no default timeout: a multi-megabyte place
|
|
856
|
+
* file over a slow link is bandwidth-bound, so a transport-attempt timeout only
|
|
857
|
+
* fires spuriously. An explicit `options.timeout` still applies to any
|
|
858
|
+
* request; every non-upload request keeps the merged default.
|
|
859
|
+
*
|
|
860
|
+
* @param inputs - The merged config, the built request, and per-request overrides.
|
|
861
|
+
* @returns The config to hand to the transport, with `timeout` omitted when
|
|
862
|
+
* no transport-attempt timeout should apply.
|
|
863
|
+
*/
|
|
864
|
+
function buildRequestConfig({ merged, options, request, signal }) {
|
|
865
|
+
const shouldOmitDefaultTimeout = options?.timeout === void 0 && isUploadRequest(request);
|
|
866
|
+
return {
|
|
867
|
+
apiKey: merged.apiKey,
|
|
868
|
+
baseUrl: merged.baseUrl,
|
|
869
|
+
...signal === void 0 ? {} : { signal },
|
|
870
|
+
...shouldOmitDefaultTimeout ? {} : { timeout: merged.timeout }
|
|
871
|
+
};
|
|
872
|
+
}
|
|
873
|
+
function enrichPermissionError(err, spec) {
|
|
874
|
+
if (spec.requiredScopes === void 0) return err;
|
|
875
|
+
if (err instanceof PermissionError) return err;
|
|
876
|
+
if (!(err instanceof ApiError)) return err;
|
|
877
|
+
if (err.statusCode !== 401 && err.statusCode !== 403) return err;
|
|
878
|
+
if (err.gatewaySummary !== void 0) return err;
|
|
879
|
+
return new PermissionError(err.message, {
|
|
880
|
+
...requestContextOf(err),
|
|
881
|
+
cause: err.cause,
|
|
882
|
+
code: err.code,
|
|
883
|
+
details: err.details,
|
|
884
|
+
operationKey: spec.operationLimit.operationKey,
|
|
885
|
+
requiredScopes: spec.requiredScopes,
|
|
886
|
+
statusCode: err.statusCode
|
|
887
|
+
});
|
|
888
|
+
}
|
|
889
|
+
function finishRequest({ httpResult, lifecycle, spec }) {
|
|
890
|
+
if (httpResult.success) return spec.parse(httpResult.data);
|
|
891
|
+
return {
|
|
892
|
+
err: deadlineFailureFromError(httpResult.err, lifecycle) ?? enrichPermissionError(httpResult.err, spec),
|
|
893
|
+
success: false
|
|
894
|
+
};
|
|
895
|
+
}
|
|
896
|
+
//#endregion
|
|
897
|
+
export { observeAdmissionWaitAsync as a, isDateTimeString as c, waitDeadlineFailure as i, okRequest as n, toJsonDetails as o, parseEmptyResponse as r, isRecord as s, ResourceClient as t };
|
|
898
|
+
|
|
899
|
+
//# sourceMappingURL=resource-client--yYybltk.mjs.map
|