polite-crawler 0.7.4 → 0.7.6
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 +1 -1
- package/build/api.d.mts +2 -1
- package/build/api.mjs +132 -228
- package/build/api.mjs.map +1 -1
- package/build/{cli-daemon-DLq2mL2u.mjs → cli-daemon-CLI_AKI9.mjs} +2 -2
- package/build/{cli-daemon-DLq2mL2u.mjs.map → cli-daemon-CLI_AKI9.mjs.map} +1 -1
- package/build/{cli-recipes-Bpxtn038.mjs → cli-recipes-DzJiJH_X.mjs} +2 -2
- package/build/{cli-recipes-Bpxtn038.mjs.map → cli-recipes-DzJiJH_X.mjs.map} +1 -1
- package/build/cli.mjs +7 -7
- package/build/{daemon-gic2K75W.mjs → daemon-KF6CrGNK.mjs} +3 -3
- package/build/{daemon-gic2K75W.mjs.map → daemon-KF6CrGNK.mjs.map} +1 -1
- package/build/{diff-BRqaThsF.mjs → diff-D3abBl9u.mjs} +2 -2
- package/build/{diff-BRqaThsF.mjs.map → diff-D3abBl9u.mjs.map} +1 -1
- package/build/{extract-CI3T_zCs.mjs → extract-BVyy_jCx.mjs} +2 -2
- package/build/{extract-CI3T_zCs.mjs.map → extract-BVyy_jCx.mjs.map} +1 -1
- package/build/index.d.mts +32 -2
- package/build/index.mjs +11 -11
- package/build/{open-BJjZ87iB.mjs → open-VReqHK-q.mjs} +6 -6
- package/build/{open-BJjZ87iB.mjs.map → open-VReqHK-q.mjs.map} +1 -1
- package/build/politeness.d.mts +2 -2
- package/build/politeness.mjs.map +1 -1
- package/build/{recipe-BAUadZKl.mjs → recipe-BYneEKBR.mjs} +3 -3
- package/build/{recipe-BAUadZKl.mjs.map → recipe-BYneEKBR.mjs.map} +1 -1
- package/build/{recipe-product-CSQEzSiR.mjs → recipe-product-m-pL3J9O.mjs} +41 -20
- package/build/recipe-product-m-pL3J9O.mjs.map +1 -0
- package/build/{runtime-DgktarsN.mjs → runtime-Dk73mHMw.mjs} +2 -2
- package/build/{runtime-DgktarsN.mjs.map → runtime-Dk73mHMw.mjs.map} +1 -1
- package/build/{version-C6Xx2HGj.mjs → version-BfBpCoXu.mjs} +2 -2
- package/build/{version-C6Xx2HGj.mjs.map → version-BfBpCoXu.mjs.map} +1 -1
- package/build/{wacz-BJVmPMY2.mjs → wacz-BQY4wyWy.mjs} +3 -3
- package/build/{wacz-BJVmPMY2.mjs.map → wacz-BQY4wyWy.mjs.map} +1 -1
- package/build/{warc-DMBvXJA3.mjs → warc-ynGyYcab.mjs} +2 -2
- package/build/{warc-DMBvXJA3.mjs.map → warc-ynGyYcab.mjs.map} +1 -1
- package/package.json +4 -3
- package/build/recipe-product-CSQEzSiR.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -293,7 +293,7 @@ The engine of the time travel, the diff and the watch list is `versionAtTime`, `
|
|
|
293
293
|
|
|
294
294
|
The engine of hybrid search is `createHybridSearch`, `HybridSearchOptions`, `VectorStore`, `VECTORS_SCHEMA` and the types of the vector store. It also includes `chunkText`, `chunkTokensOf`, `estimateTokens`, `CHUNK_LIMITS`, `fuseRanks`, `unitVector`, `isLoopback`, `FeatureExtractor`, `TransformersModule`, the optional method `ReadingIndex.digests` and `DocIndex.digests`. The file `vectors.sqlite` is a projection, as the index is: it is not part of the stable store.
|
|
295
295
|
|
|
296
|
-
The engine of the recipes is `registerRecipe`, `rankHoursLinks`, `namesVenue`, `locationMatches`, `pickProduct`, `pickVariant`, `readAmount`, `VENUE_LIMITS`, `PRODUCT_LIMITS`, `RECIPE_LIMITS` and the `steps` of `VenueRead` and `ProductRead`. The words that rank a link or a label are the engine too, so a version can improve them.
|
|
296
|
+
The engine of the recipes is `registerRecipe`, `rankHoursLinks`, `chooseVenueReadings`, `namesVenue`, `locationMatches`, `pickProduct`, `pickVariant`, `readAmount`, `VENUE_LIMITS`, `PRODUCT_LIMITS`, `RECIPE_LIMITS` and the `steps` of `VenueRead` and `ProductRead`. The words that rank a link or a label are the engine too, so a version can improve them.
|
|
297
297
|
|
|
298
298
|
The engine of the archived fallback and of the signatures is `archiveExtractor`, `archivedDocId`, and the `fallback` and `archiveDespiteRobots` of `PageOptions`. It also includes `range`, `signalLines` and `originalHeaderPrefix` of `FetchRequest`, `ai_input` of `ExtractedDoc`, `sign` of `RenderOptions` and `signer` of `CrawlerOptions`.
|
|
299
299
|
|
package/build/api.d.mts
CHANGED
|
@@ -290,7 +290,8 @@ interface QuotaGateOptions {
|
|
|
290
290
|
/**
|
|
291
291
|
* This function makes the gate of one key.
|
|
292
292
|
*
|
|
293
|
-
* @throws ApiError when the quota
|
|
293
|
+
* @throws ApiError when the quota, its window or `maxBlockMs` is not valid. The message gives each
|
|
294
|
+
* problem.
|
|
294
295
|
* @beta
|
|
295
296
|
*/
|
|
296
297
|
export declare function quotaGate(quota: Quota, options: QuotaGateOptions): QuotaGate;
|
package/build/api.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { classify, parseRetryAfter } from "./classify.mjs";
|
|
2
2
|
import { policyFor, restAfter, validatorsToSend } from "./politeness.mjs";
|
|
3
3
|
import { i as freshUntil, n as reactToOutcome, t as outcomeResult } from "./reaction-Cqeo5kNs.mjs";
|
|
4
|
-
import {
|
|
4
|
+
import { keyedQuota, quotaProblems, takeQuotas } from "@mark1russell7/service/limiter";
|
|
5
5
|
// src/api-error.ts
|
|
6
6
|
/**
|
|
7
7
|
* The error of `polite-crawler/api`. It is in a module of its own, so `api.ts` and `quota.ts` import
|
|
@@ -33,19 +33,6 @@ const NAMES = /* @__PURE__ */ new Set(["ApiError", "QuotaError"]);
|
|
|
33
33
|
const isApiError = (value) => value instanceof ApiError || value instanceof Error && NAMES.has(value.name);
|
|
34
34
|
// src/quota.ts
|
|
35
35
|
/**
|
|
36
|
-
* The quotas of API keys. A quota gives a key at most `limit` units in each window: a calendar day
|
|
37
|
-
* or month in a time zone, or a rolling window. The gate counts each call before it starts, and it
|
|
38
|
-
* refuses a call over the quota before the provider does. `withQuota` puts a gate on any async
|
|
39
|
-
* function: a `fetch`, a transport or a different client.
|
|
40
|
-
*
|
|
41
|
-
* The count is not lower than the count of the provider. A rolling window puts each call in a time
|
|
42
|
-
* bucket, and a bucket counts until all of it is out of the window. The answer of the provider can
|
|
43
|
-
* make the count larger, but not smaller.
|
|
44
|
-
*
|
|
45
|
-
* The civil time of a calendar window comes from `@mark1russell7/algebra/clock`. The module imports
|
|
46
|
-
* no Node.js module, so a browser can use it. Each export is beta.
|
|
47
|
-
*/
|
|
48
|
-
/**
|
|
49
36
|
* The refusal of a call over its quota. The gate refused the call before the call started.
|
|
50
37
|
*
|
|
51
38
|
* @beta
|
|
@@ -72,227 +59,113 @@ var QuotaError = class extends ApiError {
|
|
|
72
59
|
* @beta
|
|
73
60
|
*/
|
|
74
61
|
const isQuotaError = (value) => value instanceof QuotaError || value instanceof Error && value.name === "QuotaError" && typeof value.key === "string" && Number.isFinite(value.resetAt);
|
|
75
|
-
const MAX_BUCKETS = 1e3;
|
|
76
62
|
const DEFAULT_BUCKETS = 60;
|
|
77
|
-
const HOUR_MS = 36e5;
|
|
78
63
|
/** The largest time of a `Date`, in milliseconds from the epoch. */
|
|
79
64
|
const MAX_TIME = 864e13;
|
|
80
65
|
const iso = (t) => new Date(t).toISOString();
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
if (
|
|
85
|
-
const { year, month, day, hour, minute, second } = local;
|
|
86
|
-
return Date.UTC(year, month - 1, day, hour, minute, second);
|
|
66
|
+
const isTime = (value) => typeof value === "number" && Number.isFinite(value) && Math.abs(value) <= MAX_TIME;
|
|
67
|
+
/** This function refuses a cost that is not a finite number of 0 or more. */
|
|
68
|
+
const checkCost = (cost, of) => {
|
|
69
|
+
if (!Number.isFinite(cost) || cost < 0) throw new ApiError(`The cost of ${of} is not a number of 0 or more: ${String(cost)}.`);
|
|
87
70
|
};
|
|
88
71
|
/**
|
|
89
|
-
* This function gives the
|
|
90
|
-
*
|
|
91
|
-
* of the change: the end of the gap.
|
|
72
|
+
* This function gives the spec of the limiter for a quota. Without `maxBlockMs`, a block ends at the
|
|
73
|
+
* latest when the bucket of its reading stops counting: one window.
|
|
92
74
|
*/
|
|
93
|
-
const
|
|
94
|
-
const
|
|
95
|
-
if (first !== void 0) return first;
|
|
96
|
-
const change = (offsetChanges(wall - 15 * HOUR_MS, wall + 13 * HOUR_MS, timeZone) ?? []).find((at) => wallOf(at - 1, timeZone) < wall && wallOf(at, timeZone) >= wall);
|
|
97
|
-
if (change === void 0) throw new ApiError(`The clock of ${timeZone} does not show or jump over ${iso(wall)}.`);
|
|
98
|
-
return change;
|
|
99
|
-
};
|
|
100
|
-
/** This function gives the calendar window of the time `t`: its start, and the start of the next window. */
|
|
101
|
-
const calendarOf = (unit, timeZone, hour, t) => {
|
|
102
|
-
const wall = new Date(wallOf(t, timeZone));
|
|
103
|
-
const year = wall.getUTCFullYear();
|
|
104
|
-
const month = wall.getUTCMonth();
|
|
105
|
-
const day = wall.getUTCDate();
|
|
106
|
-
const startOf = (back) => firstAt(unit === "day" ? Date.UTC(year, month, day - back, hour) : Date.UTC(year, month - back, 1, hour), timeZone);
|
|
107
|
-
const start = startOf(0);
|
|
108
|
-
return start <= t ? [start, startOf(-1)] : [startOf(1), start];
|
|
109
|
-
};
|
|
110
|
-
const spanOf = (window) => {
|
|
111
|
-
if (window.kind === "rolling") {
|
|
112
|
-
const buckets = window.buckets ?? DEFAULT_BUCKETS;
|
|
113
|
-
if (!Number.isFinite(window.ms) || window.ms <= 0) throw new ApiError(`The rolling window is not a positive number: ${String(window.ms)}.`);
|
|
114
|
-
if (!Number.isInteger(buckets) || buckets < 1 || buckets > MAX_BUCKETS) throw new ApiError(`The count of buckets is not a whole number from 1 to ${String(MAX_BUCKETS)}: ${String(buckets)}.`);
|
|
115
|
-
const { ms } = window;
|
|
116
|
-
const size = Math.ceil(ms / buckets);
|
|
117
|
-
return {
|
|
118
|
-
bucket: (t) => {
|
|
119
|
-
const start = Math.floor(t / size) * size;
|
|
120
|
-
return [start, start + size];
|
|
121
|
-
},
|
|
122
|
-
counting: (t) => (start) => start + size + ms > t,
|
|
123
|
-
freeAt: (start) => start + size + ms
|
|
124
|
-
};
|
|
125
|
-
}
|
|
126
|
-
const hour = window.hour ?? 0;
|
|
127
|
-
if (!Number.isInteger(hour) || hour < 0 || hour > 23) throw new ApiError(`The hour of the window is not a whole number from 0 to 23: ${String(hour)}.`);
|
|
128
|
-
if (localTime(0, window.timeZone) === void 0) throw new ApiError(`The time zone of the window is not an IANA time zone: ${window.timeZone}.`);
|
|
129
|
-
const { unit, timeZone } = window;
|
|
75
|
+
const specOf = (quota, maxBlockMs) => {
|
|
76
|
+
const { window } = quota;
|
|
130
77
|
return {
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
78
|
+
limit: {
|
|
79
|
+
value: quota.limit,
|
|
80
|
+
unit: "count"
|
|
81
|
+
},
|
|
82
|
+
reserve: {
|
|
83
|
+
value: quota.reserve ?? 0,
|
|
84
|
+
unit: "count"
|
|
135
85
|
},
|
|
136
|
-
|
|
86
|
+
window: window.kind === "rolling" ? {
|
|
87
|
+
kind: "rolling",
|
|
88
|
+
span: {
|
|
89
|
+
value: window.ms,
|
|
90
|
+
unit: "ms"
|
|
91
|
+
},
|
|
92
|
+
buckets: {
|
|
93
|
+
value: window.buckets ?? DEFAULT_BUCKETS,
|
|
94
|
+
unit: "count"
|
|
95
|
+
}
|
|
96
|
+
} : {
|
|
97
|
+
kind: "calendar",
|
|
98
|
+
unit: window.unit,
|
|
99
|
+
zone: window.timeZone,
|
|
100
|
+
start: {
|
|
101
|
+
value: window.hour ?? 0,
|
|
102
|
+
unit: "h"
|
|
103
|
+
}
|
|
104
|
+
},
|
|
105
|
+
maxBlock: maxBlockMs === void 0 ? "window" : {
|
|
106
|
+
value: maxBlockMs,
|
|
107
|
+
unit: "ms"
|
|
108
|
+
}
|
|
137
109
|
};
|
|
138
110
|
};
|
|
139
|
-
const isTime = (value) => typeof value === "number" && Number.isFinite(value) && Math.abs(value) <= MAX_TIME;
|
|
140
111
|
/**
|
|
141
|
-
* This function gives
|
|
142
|
-
*
|
|
143
|
-
* record lets it.
|
|
112
|
+
* This function gives a store of the limiter over a store of this package. The two stores keep one
|
|
113
|
+
* form of record, so a record of an earlier version stays valid.
|
|
144
114
|
*/
|
|
145
|
-
const
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
return {
|
|
157
|
-
spent: items,
|
|
158
|
-
...isTime(blockedUntil) ? { blockedUntil } : {},
|
|
159
|
-
...isTime(readAt) ? { readAt } : {}
|
|
160
|
-
};
|
|
161
|
-
};
|
|
162
|
-
/** This function removes the buckets that do not count at the time `t`, and an ended refusal. */
|
|
163
|
-
const prune = (span, record, t) => {
|
|
164
|
-
const counts = span.counting(t);
|
|
165
|
-
const spent = (record?.spent ?? []).filter(([start]) => counts(start));
|
|
166
|
-
const blockedUntil = record?.blockedUntil;
|
|
167
|
-
const readAt = record?.readAt;
|
|
168
|
-
return {
|
|
169
|
-
spent,
|
|
170
|
-
...blockedUntil !== void 0 && blockedUntil > t ? { blockedUntil } : {},
|
|
171
|
-
...readAt === void 0 ? {} : { readAt }
|
|
172
|
-
};
|
|
173
|
-
};
|
|
174
|
-
const usedOf = (record) => record.spent.reduce((sum, [, units]) => sum + units, 0);
|
|
175
|
-
/** This function adds units to the bucket of the time `t`. */
|
|
176
|
-
const add = (span, record, t, units) => {
|
|
177
|
-
const [start] = span.bucket(t);
|
|
178
|
-
const spent = record.spent.map(([at, count]) => at === start ? [at, count + units] : [at, count]);
|
|
179
|
-
if (!spent.some(([at]) => at === start)) spent.push([start, units]);
|
|
180
|
-
spent.sort((a, b) => a[0] - b[0]);
|
|
181
|
-
return {
|
|
182
|
-
...record,
|
|
183
|
-
spent
|
|
184
|
-
};
|
|
185
|
-
};
|
|
186
|
-
/** This function gives the time when `need` units of the oldest buckets stop counting. */
|
|
187
|
-
const freeTime = (span, record, need) => {
|
|
188
|
-
let freed = 0;
|
|
189
|
-
for (const [start, units] of record.spent) {
|
|
190
|
-
freed += units;
|
|
191
|
-
if (freed >= need) return span.freeAt(start);
|
|
115
|
+
const limiterStore = (store) => ({
|
|
116
|
+
sync: true,
|
|
117
|
+
change(quota, key, step) {
|
|
118
|
+
let result;
|
|
119
|
+
store.changeQuota(quota, key, (stored) => {
|
|
120
|
+
const next = step(stored);
|
|
121
|
+
result = { value: next.result };
|
|
122
|
+
return next.record;
|
|
123
|
+
});
|
|
124
|
+
if (result === void 0) throw new ApiError(`The store did not change the record of the quota ${quota} of ${key}.`);
|
|
125
|
+
return result.value;
|
|
192
126
|
}
|
|
193
|
-
};
|
|
127
|
+
});
|
|
194
128
|
/**
|
|
195
129
|
* This function makes the gate of one key.
|
|
196
130
|
*
|
|
197
|
-
* @throws ApiError when the quota
|
|
131
|
+
* @throws ApiError when the quota, its window or `maxBlockMs` is not valid. The message gives each
|
|
132
|
+
* problem.
|
|
198
133
|
* @beta
|
|
199
134
|
*/
|
|
200
135
|
function quotaGate(quota, options) {
|
|
201
|
-
const span = spanOf(quota.window);
|
|
202
136
|
const { limit, name } = quota;
|
|
203
137
|
const reserve = quota.reserve ?? 0;
|
|
204
|
-
if (!Number.isFinite(limit) || limit <= 0) throw new ApiError(`The limit of the quota ${name} is not a positive number: ${String(limit)}.`);
|
|
205
|
-
if (!Number.isFinite(reserve) || reserve < 0 || reserve >= limit) throw new ApiError(`The reserve of the quota ${name} is not from 0 to less than the limit: ${String(reserve)}.`);
|
|
206
138
|
const { key, maxBlockMs } = options;
|
|
207
|
-
|
|
208
|
-
const
|
|
209
|
-
|
|
210
|
-
const
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
};
|
|
222
|
-
};
|
|
223
|
-
const bounded = (record, t) => {
|
|
224
|
-
const { blockedUntil } = record;
|
|
225
|
-
const bound = blockBound(t);
|
|
226
|
-
return blockedUntil !== void 0 && blockedUntil > bound ? {
|
|
227
|
-
...record,
|
|
228
|
-
blockedUntil: bound
|
|
229
|
-
} : record;
|
|
139
|
+
const spec = specOf(quota, maxBlockMs);
|
|
140
|
+
const problems = quotaProblems(name, spec);
|
|
141
|
+
if (problems.length > 0) throw new ApiError(`The quota ${name} is not valid: ${problems.join("; ")}.`);
|
|
142
|
+
const limiter = keyedQuota(name, spec, limiterStore(options.store ?? memoryQuotaStore()), {
|
|
143
|
+
time: "wall",
|
|
144
|
+
now: options.now ?? Date.now
|
|
145
|
+
});
|
|
146
|
+
/** This function gives the error of a refused call. */
|
|
147
|
+
const refusal = (verdict, cost) => {
|
|
148
|
+
if (verdict.cause === "capacity") return new ApiError(`A call of ${String(cost)} units is more than the quota ${name} gives in one window: ${String(verdict.capacity)}.`);
|
|
149
|
+
const { resetAt, state } = verdict;
|
|
150
|
+
const { blockedUntil } = state;
|
|
151
|
+
if (verdict.cause === "provider" && blockedUntil !== void 0) return new QuotaError(`The provider refused the quota ${name} of ${key} until ${iso(blockedUntil)}.` + (resetAt > blockedUntil ? ` The window has the units of the call at ${iso(resetAt)}.` : ""), key, resetAt);
|
|
152
|
+
return new QuotaError(`The quota ${name} of ${key} refused a call of ${String(cost)} units: ${String(state.used)} of ${String(limit)} are used, and ${String(reserve)} stay in reserve. It gives units again at ${iso(resetAt)}.`, key, resetAt);
|
|
230
153
|
};
|
|
231
|
-
const change = (step) => {
|
|
232
|
-
const t = now();
|
|
233
|
-
const record = store.changeQuota(name, key, (stored) => bounded(step(bounded(prune(span, recordOf(stored), t), t), t), t));
|
|
234
|
-
return stateOf(prune(span, recordOf(record), t), t);
|
|
235
|
-
};
|
|
236
|
-
const state = () => change((record) => record);
|
|
237
154
|
return {
|
|
238
155
|
quota,
|
|
239
156
|
key,
|
|
240
157
|
take(cost = 1) {
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
if (
|
|
244
|
-
|
|
245
|
-
const taken = change((record, t) => {
|
|
246
|
-
const used = usedOf(record);
|
|
247
|
-
const free = used + cost > allowed ? freeTime(span, record, used + cost - allowed) ?? span.bucket(t)[1] : void 0;
|
|
248
|
-
const { blockedUntil } = record;
|
|
249
|
-
if (blockedUntil !== void 0) {
|
|
250
|
-
const resetAt = Math.max(blockedUntil, free ?? blockedUntil);
|
|
251
|
-
refused = new QuotaError(`The provider refused the quota ${name} of ${key} until ${iso(blockedUntil)}.` + (resetAt > blockedUntil ? ` The window has the units of the call at ${iso(resetAt)}.` : ""), key, resetAt);
|
|
252
|
-
return record;
|
|
253
|
-
}
|
|
254
|
-
if (free !== void 0) {
|
|
255
|
-
refused = new QuotaError(`The quota ${name} of ${key} refused a call of ${String(cost)} units: ${String(used)} of ${String(limit)} are used, and ${String(reserve)} stay in reserve. It gives units again at ${iso(free)}.`, key, free);
|
|
256
|
-
return record;
|
|
257
|
-
}
|
|
258
|
-
return add(span, record, t, cost);
|
|
259
|
-
});
|
|
260
|
-
if (refused !== void 0) throw refused;
|
|
261
|
-
return taken;
|
|
158
|
+
checkCost(cost, "a call");
|
|
159
|
+
const verdict = limiter.take(key, cost);
|
|
160
|
+
if (!verdict.allowed) throw refusal(verdict, cost);
|
|
161
|
+
return verdict.state;
|
|
262
162
|
},
|
|
263
|
-
note(reading)
|
|
264
|
-
|
|
265
|
-
let next = record;
|
|
266
|
-
const { remaining, resetAt } = reading;
|
|
267
|
-
if (remaining !== void 0 && Number.isFinite(remaining) && remaining >= 0) {
|
|
268
|
-
const more = limit - remaining - usedOf(next);
|
|
269
|
-
if (more > 0) next = add(span, next, t, more);
|
|
270
|
-
next = {
|
|
271
|
-
...next,
|
|
272
|
-
readAt: Math.max(next.readAt ?? t, t)
|
|
273
|
-
};
|
|
274
|
-
}
|
|
275
|
-
if ((remaining === void 0 || remaining <= 0) && resetAt !== void 0 && Number.isFinite(resetAt) && resetAt > t) next = {
|
|
276
|
-
...next,
|
|
277
|
-
blockedUntil: Math.max(next.blockedUntil ?? 0, resetAt)
|
|
278
|
-
};
|
|
279
|
-
return next;
|
|
280
|
-
});
|
|
281
|
-
},
|
|
282
|
-
state,
|
|
163
|
+
note: (reading) => limiter.note(key, reading),
|
|
164
|
+
state: () => limiter.state(key),
|
|
283
165
|
giveBack(cost, at) {
|
|
284
|
-
|
|
166
|
+
checkCost(cost, "a give-back");
|
|
285
167
|
if (!isTime(at)) throw new ApiError(`The time of a give-back is not a time: ${String(at)}.`);
|
|
286
|
-
|
|
287
|
-
return change((record) => {
|
|
288
|
-
if (record.readAt !== void 0 && record.readAt >= at) return record;
|
|
289
|
-
const [start] = span.bucket(at);
|
|
290
|
-
const spent = record.spent.flatMap(([from, units]) => from !== start ? [[from, units]] : units > cost ? [[from, units - cost]] : []);
|
|
291
|
-
return {
|
|
292
|
-
...record,
|
|
293
|
-
spent
|
|
294
|
-
};
|
|
295
|
-
});
|
|
168
|
+
return limiter.giveBack(key, cost, at);
|
|
296
169
|
}
|
|
297
170
|
};
|
|
298
171
|
}
|
|
@@ -338,35 +211,66 @@ const report = (onError, error) => {
|
|
|
338
211
|
onError?.(error);
|
|
339
212
|
} catch {}
|
|
340
213
|
};
|
|
341
|
-
/** This function gives
|
|
342
|
-
const
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
214
|
+
/** This function gives a state of a gate in the form of the limiter. A state with no time gets the time NaN. */
|
|
215
|
+
const limiterState = (state) => ({
|
|
216
|
+
...state,
|
|
217
|
+
at: state.at ?? NaN
|
|
218
|
+
});
|
|
219
|
+
/**
|
|
220
|
+
* This function gives a gate of a list as a part of `takeQuotas`. The part keeps the `QuotaError` of
|
|
221
|
+
* its refusal in `refusals`, because the caller gets that error. A `QuotaError` has no state, so a
|
|
222
|
+
* refused part reads the state of its gate. A give-back of units with no time fails, and `onError`
|
|
223
|
+
* gets its error.
|
|
224
|
+
*/
|
|
225
|
+
const partOf = (gate, units, index, refusals) => ({
|
|
226
|
+
key: gate.key,
|
|
227
|
+
units,
|
|
228
|
+
quota: {
|
|
229
|
+
sync: true,
|
|
230
|
+
take: (_key, cost = 1) => {
|
|
231
|
+
try {
|
|
232
|
+
return {
|
|
233
|
+
allowed: true,
|
|
234
|
+
state: limiterState(gate.take(cost))
|
|
235
|
+
};
|
|
236
|
+
} catch (error) {
|
|
237
|
+
if (!isQuotaError(error)) throw error;
|
|
238
|
+
refusals.set(index, error);
|
|
239
|
+
const state = limiterState(gate.state());
|
|
240
|
+
const wait = Number.isNaN(state.at) ? 0 : Math.max(0, error.resetAt - state.at);
|
|
241
|
+
return {
|
|
242
|
+
allowed: false,
|
|
243
|
+
cause: state.blockedUntil === void 0 ? "limit" : "provider",
|
|
244
|
+
resetAt: error.resetAt,
|
|
245
|
+
retryAfter: {
|
|
246
|
+
value: wait,
|
|
247
|
+
unit: "ms"
|
|
248
|
+
},
|
|
249
|
+
state
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
},
|
|
253
|
+
giveBack: (_key, cost, at) => {
|
|
254
|
+
if (Number.isNaN(at)) throw new ApiError(`The gate of the quota ${gate.quota.name} of ${gate.key} gave no time for its units, so it cannot give them back.`);
|
|
255
|
+
return limiterState(gate.giveBack?.(cost, at) ?? gate.state());
|
|
256
|
+
}
|
|
348
257
|
}
|
|
349
|
-
};
|
|
258
|
+
});
|
|
350
259
|
/**
|
|
351
|
-
* This function counts `cost` units in each gate, or in none.
|
|
352
|
-
*
|
|
353
|
-
* `QuotaError` has the latest
|
|
260
|
+
* This function counts `cost` units in each gate, or in none. One gate gives its refusal as it is. A
|
|
261
|
+
* list takes with `takeQuotas`: when a gate refuses, the gates that counted give back the units,
|
|
262
|
+
* because the call did not start. The next gates still answer, so the `QuotaError` has the latest
|
|
263
|
+
* time of a reset.
|
|
354
264
|
*/
|
|
355
265
|
const takeAll = (gates, cost, onError) => {
|
|
356
|
-
const
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
taken.push([gate, gate.take(cost).at]);
|
|
361
|
-
} catch (error) {
|
|
362
|
-
if (!isQuotaError(error) || gates.length === 1) throw error;
|
|
363
|
-
if (refusal === void 0 || error.resetAt > refusal.resetAt) refusal = error;
|
|
364
|
-
}
|
|
365
|
-
if (refusal !== void 0) throw refusal;
|
|
366
|
-
} catch (error) {
|
|
367
|
-
giveBackAll(taken, cost, onError);
|
|
368
|
-
throw error;
|
|
266
|
+
const [only] = gates;
|
|
267
|
+
if (gates.length === 1 && only !== void 0) {
|
|
268
|
+
only.take(cost);
|
|
269
|
+
return;
|
|
369
270
|
}
|
|
271
|
+
const refusals = /* @__PURE__ */ new Map();
|
|
272
|
+
const verdict = takeQuotas(gates.map((gate, index) => partOf(gate, cost, index, refusals)), { onGiveBackError: (error) => report(onError, error) });
|
|
273
|
+
if (!verdict.allowed) throw refusals.get(verdict.index) ?? new ApiError("A gate of the list refused the call, but it gave no QuotaError.");
|
|
370
274
|
};
|
|
371
275
|
/**
|
|
372
276
|
* This function puts a gate, or a list of gates, on an async function, and keeps the type of the
|