Repository navigation
Expand file tree
/
Copy pathstackApiV3.ts
More file actions
498 lines (426 loc) · 15.1 KB
/
Copy pathstackApiV3.ts
File metadata and controls
498 lines (426 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
import {
ApiTransportError,
type FetchLike,
type ThrottleNotice,
readJsonResponse,
} from "./httpClient";
import {
assertSafePaginationPage,
DEFAULT_PAGINATION_SAFETY_LIMIT,
} from "./paginationSafety";
type WaitFn = (seconds: number) => Promise<void>;
type NowFn = () => number;
interface StackApiV3ClientOptions {
apiV3Url: string;
token: string;
fetchFn?: FetchLike;
onThrottle?: (notice: ThrottleNotice) => void | Promise<void>;
waitFn?: WaitFn;
nowFn?: NowFn;
paginationSafetyLimit?: number;
maxRetryWaitSeconds?: number;
maxCumulativeRetryWaitSeconds?: number;
maxBackoffNoticeSeconds?: number;
retryPutRequests?: boolean;
}
interface ValidatedStackApiV3Page<T> {
items: T[];
totalPages: number | null;
}
export interface StackApiV3UserSummary {
id: number;
email?: string | null;
name?: string;
}
export interface StackApiV3UserGroup {
id: number;
name: string;
description?: string | null;
users?: StackApiV3UserSummary[];
}
interface CreateUserGroupInput {
name: string;
description?: string;
userIds: number[];
}
interface PagingOptions {
maxPages?: number;
}
export interface StackApiPagedResult<T> {
items: T[];
pageCount: number;
reachedMaxPages: boolean;
hasMore: boolean;
}
export interface StackApiV3Page<T> {
items: T[];
page: number;
totalPages: number | null;
hasMore: boolean;
}
const API_V3_USER_AGENT =
"StackAPIUtilities/0.1 (+https://github.com/EstoesMoises/StackAPIUtilities)";
const BURST_LOW_WATERMARK = 5;
const TOKEN_BUCKET_LOW_WATERMARK = 30;
const MAX_IDEMPOTENT_RETRIES = 3;
const FALLBACK_RETRY_SECONDS = 2;
export const MAX_STACK_API_V3_BACKOFF_NOTICE_SECONDS = 86_400;
const waitSeconds: WaitFn = (seconds) =>
new Promise((resolve) => setTimeout(resolve, seconds * 1_000));
function shouldFetchNextPage({
page,
totalPages,
maxPages,
lastPageItemCount,
}: {
page: number;
totalPages: number | null;
maxPages: number;
lastPageItemCount: number;
}) {
if (page > maxPages) return false;
return totalPages === null ? lastPageItemCount > 0 : page <= totalPages;
}
export class StackApiV3Client {
private readonly apiV3Url: string;
private readonly token: string;
private readonly fetchFn: FetchLike;
private readonly onThrottle?: (notice: ThrottleNotice) => void | Promise<void>;
private readonly waitFn: WaitFn;
private readonly nowFn: NowFn;
private readonly paginationSafetyLimit: number;
private readonly maxRetryWaitSeconds: number;
private readonly maxCumulativeRetryWaitSeconds: number;
private readonly maxBackoffNoticeSeconds: number;
private readonly retryPutRequests: boolean;
constructor(options: StackApiV3ClientOptions) {
this.apiV3Url = options.apiV3Url.replace(/\/+$/, "");
this.token = options.token;
this.fetchFn = options.fetchFn ?? ((input, init) => globalThis.fetch(input, init));
this.onThrottle = options.onThrottle;
this.waitFn = options.waitFn ?? waitSeconds;
this.nowFn = options.nowFn ?? (() => Date.now());
this.paginationSafetyLimit = options.paginationSafetyLimit ?? DEFAULT_PAGINATION_SAFETY_LIMIT;
if (!areValidRetryBudgets(options)) {
throw new TypeError("Stack API v3 retry budgets must be non-negative safe integers.");
}
this.maxRetryWaitSeconds = options.maxRetryWaitSeconds ?? Number.POSITIVE_INFINITY;
this.maxCumulativeRetryWaitSeconds =
options.maxCumulativeRetryWaitSeconds ?? Number.POSITIVE_INFINITY;
this.maxBackoffNoticeSeconds = options.maxBackoffNoticeSeconds ?? Number.POSITIVE_INFINITY;
this.retryPutRequests = options.retryPutRequests ?? true;
}
async getPagedItems<T = unknown>(
path: string,
query: Record<string, string> = {},
options: PagingOptions = {},
): Promise<T[]> {
return (await this.getPagedResult<T>(path, query, options)).items;
}
async getPagedResult<T = unknown>(
path: string,
query: Record<string, string> = {},
options: PagingOptions = {},
): Promise<StackApiPagedResult<T>> {
const items: T[] = [];
let page = 1;
let totalPages: number | null = null;
let pageCount = 0;
let lastPageItemCount = 0;
const maxPages = options.maxPages ?? Number.POSITIVE_INFINITY;
do {
assertSafePaginationPage("Stack API v3", path, page, this.paginationSafetyLimit);
const url = this.buildUrl(path, { ...query, page: String(page) });
const response = await this.readResponse(url);
const body: ValidatedStackApiV3Page<T> = validateStackApiV3Page<T>(
await readJsonResponse<unknown>(response, "Stack API v3"),
path,
page,
totalPages,
);
const pageItems = body.items;
items.push(...pageItems);
lastPageItemCount = pageItems.length;
totalPages = body.totalPages;
pageCount += 1;
page += 1;
} while (shouldFetchNextPage({ page, totalPages, maxPages, lastPageItemCount }));
const hasMore = totalPages === null
? pageCount >= maxPages && lastPageItemCount > 0
: pageCount < totalPages;
return {
items,
pageCount,
reachedMaxPages: pageCount >= maxPages && hasMore,
hasMore,
};
}
async getPage<T = unknown>(
path: string,
query: Record<string, string> = {},
page: number,
): Promise<StackApiV3Page<T>> {
if (!Number.isSafeInteger(page) || page < 1) {
throw new Error("Stack API v3 page must be a positive safe integer.");
}
assertSafePaginationPage("Stack API v3", path, page, this.paginationSafetyLimit);
const response = await this.readResponse(this.buildUrl(path, { ...query, page: String(page) }));
const body = validateStackApiV3Page<T>(
await readJsonResponse<unknown>(response, "Stack API v3"),
path,
page,
null,
);
return {
items: body.items,
page,
totalPages: body.totalPages,
hasMore: body.totalPages === null ? body.items.length > 0 : page < body.totalPages,
};
}
async getJson<T = unknown>(path: string): Promise<T> {
const response = await this.readResponse(this.buildUrl(path, {}));
return readJsonResponse<T>(response, "Stack API v3");
}
async putJson<T = unknown>(path: string, body: unknown): Promise<T> {
const url = this.buildUrl(path, {});
const init: RequestInit = {
method: "PUT",
headers: this.createJsonHeaders(),
body: JSON.stringify(body),
};
const response = this.retryPutRequests
? await this.readResponse(url, init)
: await this.fetchOnce(url, init);
if (!this.retryPutRequests && isRetryableStatus(response.status) && this.onThrottle) {
await this.onThrottle({
kind: "backoff",
seconds: Math.min(
getRetryDelaySeconds(response.headers, this.nowFn()),
this.maxBackoffNoticeSeconds,
),
});
} else if (!this.retryPutRequests && response.ok) {
await this.notifyThrottle(response.headers);
}
return readJsonResponse<T>(response, "Stack API v3");
}
async getUserByEmail(email: string): Promise<StackApiV3UserSummary | null> {
const response = await this.readResponse(
this.buildUrl(`/users/by-email/${encodeURIComponent(email)}`, {}),
);
if (response.status === 404) {
return null;
}
return readJsonResponse<StackApiV3UserSummary>(response, "Stack API v3");
}
async getUserGroups(): Promise<StackApiV3UserGroup[]> {
return this.getPagedItems<StackApiV3UserGroup>("/user-groups", { pageSize: "100" });
}
async createUserGroup(input: CreateUserGroupInput): Promise<StackApiV3UserGroup> {
return this.writeJson<StackApiV3UserGroup>("/user-groups", "POST", input);
}
async addUserGroupMembers(userGroupId: number, userIds: number[]): Promise<StackApiV3UserGroup> {
return this.writeJson<StackApiV3UserGroup>(`/user-groups/${userGroupId}/members`, "POST", userIds);
}
async removeUserGroupMember(userGroupId: number, userId: number): Promise<void> {
const response = await this.fetchOnce(this.buildUrl(`/user-groups/${userGroupId}/members/${userId}`, {}), {
method: "DELETE",
headers: this.createJsonHeaders(),
});
if (!response.ok) {
await readJsonResponse<unknown>(response, "Stack API v3");
}
}
private buildUrl(path: string, query: Record<string, string>): URL {
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
const url = new URL(`${this.apiV3Url}${normalizedPath}`);
for (const [key, value] of Object.entries(query)) {
url.searchParams.set(key, value);
}
return url;
}
private async writeJson<T>(path: string, method: "POST", body: unknown): Promise<T> {
const response = await this.fetchOnce(this.buildUrl(path, {}), {
method,
headers: this.createJsonHeaders(),
body: JSON.stringify(body),
});
return readJsonResponse<T>(response, "Stack API v3");
}
private createJsonHeaders(): HeadersInit {
return {
Authorization: `Bearer ${this.token}`,
"Content-Type": "application/json",
"User-Agent": API_V3_USER_AGENT,
};
}
private async fetchOnce(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
try {
return await this.fetchFn(input, init);
} catch (error) {
if (error instanceof TypeError) throw new ApiTransportError("Stack API v3");
throw error;
}
}
private async readResponse(url: URL, init?: RequestInit): Promise<Response> {
let cumulativeWaitSeconds = 0;
for (let retryCount = 0; ; retryCount += 1) {
let response: Response;
try {
response = await this.fetchFn(url, init ?? { headers: this.createJsonHeaders() });
} catch (error) {
if (!(error instanceof TypeError)) throw error;
if (
retryCount >= MAX_IDEMPOTENT_RETRIES ||
!this.canWaitForRetry(FALLBACK_RETRY_SECONDS, cumulativeWaitSeconds)
) {
throw new ApiTransportError("Stack API v3");
}
await this.waitFn(FALLBACK_RETRY_SECONDS);
cumulativeWaitSeconds += FALLBACK_RETRY_SECONDS;
continue;
}
if (!isRetryableStatus(response.status)) {
if (response.ok) {
await this.notifyThrottle(response.headers);
}
return response;
}
if (retryCount >= MAX_IDEMPOTENT_RETRIES) {
return response;
}
const seconds = getRetryDelaySeconds(response.headers, this.nowFn());
if (response.status === 429 && this.onThrottle) {
await this.onThrottle({
kind: "backoff",
seconds: Math.min(seconds, this.maxBackoffNoticeSeconds),
});
}
if (!this.canWaitForRetry(seconds, cumulativeWaitSeconds)) {
return response;
}
await this.waitFn(seconds);
cumulativeWaitSeconds += seconds;
}
}
private canWaitForRetry(seconds: number, cumulativeWaitSeconds: number): boolean {
return (
seconds <= this.maxRetryWaitSeconds &&
seconds <= this.maxCumulativeRetryWaitSeconds - cumulativeWaitSeconds
);
}
private async notifyThrottle(headers: Headers): Promise<void> {
if (!this.onThrottle) {
return;
}
const burstCallsLeft = parseIntegerHeader(headers, "x-burst-throttle-calls-left");
const burstSecondsUntilFull = parseIntegerHeader(headers, "x-burst-throttle-seconds-until-full");
if (
burstCallsLeft !== null &&
burstSecondsUntilFull !== null &&
burstCallsLeft < BURST_LOW_WATERMARK &&
burstSecondsUntilFull > 0
) {
await this.onThrottle({ kind: "burst", seconds: burstSecondsUntilFull, remaining: burstCallsLeft });
}
const callsLeft = parseIntegerHeader(headers, "x-token-bucket-calls-left");
const secondsUntilRefill = parseIntegerHeader(headers, "x-token-bucket-seconds-until-next-refill");
if (
callsLeft !== null &&
secondsUntilRefill !== null &&
callsLeft <= TOKEN_BUCKET_LOW_WATERMARK &&
secondsUntilRefill > 0
) {
await this.onThrottle({ kind: "token-bucket", seconds: secondsUntilRefill, remaining: callsLeft });
}
}
}
function isRetryableStatus(status: number): boolean {
return status === 429 || status === 502 || status === 503 || status === 504;
}
function areValidRetryBudgets(options: StackApiV3ClientOptions): boolean {
return [
options.maxRetryWaitSeconds,
options.maxCumulativeRetryWaitSeconds,
options.maxBackoffNoticeSeconds,
].every((value) => value === undefined || (Number.isSafeInteger(value) && value >= 0));
}
export function validateStackApiV3Page<T>(
value: unknown,
path: string,
page: number,
knownTotalPages: number | null,
): ValidatedStackApiV3Page<T> {
if (!isRecord(value) || !hasOwn(value, "items") || !Array.isArray(value.items)) {
throw invalidPaginationEnvelope(path, page);
}
let suppliedTotalPages: number | null = null;
if (hasOwn(value, "totalPages")) {
const rawTotalPages = value.totalPages;
if (
typeof rawTotalPages !== "number" ||
!Number.isFinite(rawTotalPages) ||
!Number.isInteger(rawTotalPages) ||
rawTotalPages < 0
) {
throw invalidPaginationEnvelope(path, page);
}
suppliedTotalPages = rawTotalPages;
}
if (
knownTotalPages !== null &&
suppliedTotalPages !== null &&
suppliedTotalPages !== knownTotalPages
) {
throw invalidPaginationEnvelope(path, page);
}
const totalPages: number | null = suppliedTotalPages ?? knownTotalPages;
if (value.items.length > 0 && totalPages !== null && page > totalPages) {
throw invalidPaginationEnvelope(path, page);
}
return { items: value.items as T[], totalPages };
}
function invalidPaginationEnvelope(path: string, page: number): Error {
return new Error(
`Stack API v3 returned an invalid pagination envelope for ${path} page ${page}. No complete result was produced.`,
);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function hasOwn(value: object, key: PropertyKey): boolean {
return Object.prototype.hasOwnProperty.call(value, key);
}
function getRetryDelaySeconds(headers: Headers, nowMs: number): number {
const durations = [
parseRetryAfter(headers.get("Retry-After"), nowMs),
parseNonNegativeInteger(headers.get("x-burst-throttle-seconds-until-full")),
parseNonNegativeInteger(headers.get("x-token-bucket-seconds-until-next-refill")),
].filter((duration): duration is number => duration !== null);
return durations.length > 0 ? Math.max(...durations) : FALLBACK_RETRY_SECONDS;
}
function parseRetryAfter(value: string | null, nowMs: number): number | null {
const seconds = parseNonNegativeInteger(value);
if (seconds !== null) {
return seconds;
}
if (value === null) {
return null;
}
const retryDateMs = Date.parse(value);
if (Number.isNaN(retryDateMs)) {
return null;
}
return Math.max(0, Math.ceil((retryDateMs - nowMs) / 1_000));
}
function parseIntegerHeader(headers: Headers, name: string): number | null {
return parseNonNegativeInteger(headers.get(name));
}
function parseNonNegativeInteger(value: string | null): number | null {
if (value === null || !/^\d+$/.test(value.trim())) {
return null;
}
const parsed = Number(value);
return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : null;
}