Skip to content

Commit 1a67be4

Browse files
authored
Merge pull request #19 from upstash/DX-2969-blob-X-retry
DX-2969: retry blob credentials and delete while a new bucket provisions
2 parents 1eb6668 + e473cf7 commit 1a67be4

4 files changed

Lines changed: 267 additions & 14 deletions

File tree

‎src/commands/blob/credentials.ts‎

Lines changed: 60 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,35 @@ import { resolveAuth } from "../../auth.js";
33
import { HttpError, request } from "../../client.js";
44
import { printJSON } from "../../output.js";
55
import type { BlobBucket, BlobS3Credentials } from "../../types.js";
6+
import {
7+
isFreshlyCreated,
8+
PROVISIONING_MAX_RETRIES,
9+
PROVISIONING_RETRY_DELAY_MS,
10+
sleep,
11+
} from "./retry.js";
12+
import type { Sleep } from "./retry.js";
613

714
const BLOB_CREDENTIALS_URL = "https://blob.upstash.io/v1/credentials";
815
const RETRYABLE_STATUSES = new Set([429, 503]);
916
const DEFAULT_RETRY_DELAY_MS = 2000;
1017
const MAX_RETRY_DELAY_MS = 10000;
1118
const MAX_RETRIES = 3;
1219

13-
type Sleep = (ms: number) => Promise<void>;
20+
export interface FetchBlobCredentialsOptions {
21+
/**
22+
* How many times a 401 may be retried. A bucket that was created moments ago
23+
* can exist in the Developer API before the Blob worker has provisioned it,
24+
* and the worker answers 401 during that window.
25+
*/
26+
unauthorizedRetries?: number;
27+
}
1428

15-
function sleep(ms: number): Promise<void> {
16-
return new Promise((resolve) => setTimeout(resolve, ms));
29+
function unauthorizedMessage(retriesUsed: number): string {
30+
if (retriesUsed > 0) {
31+
const waited = Math.round((retriesUsed * PROVISIONING_RETRY_DELAY_MS) / 1000);
32+
return `Blob bucket token was rejected after waiting ${waited}s for the bucket to finish provisioning; retry in a minute or check the bucket in the console`;
33+
}
34+
return "Blob bucket token was rejected; if the bucket was created moments ago it may still be provisioning, wait a few seconds and retry";
1735
}
1836

1937
function parseErrorMessage(text: string, status: number): string {
@@ -86,8 +104,13 @@ function validateCredentials(data: unknown): BlobS3Credentials {
86104
export async function fetchBlobCredentials(
87105
token: string,
88106
pause: Sleep = sleep,
107+
options: FetchBlobCredentialsOptions = {},
89108
): Promise<BlobS3Credentials> {
90-
for (let attempt = 0; attempt <= MAX_RETRIES; attempt += 1) {
109+
const unauthorizedRetries = options.unauthorizedRetries ?? 0;
110+
let throttled = 0;
111+
let unauthorized = 0;
112+
113+
for (;;) {
91114
const response = await fetch(BLOB_CREDENTIALS_URL, {
92115
method: "POST",
93116
headers: {
@@ -108,34 +131,50 @@ export async function fetchBlobCredentials(
108131
}
109132

110133
if (response.status === 401) {
111-
throw new HttpError("Blob bucket token was rejected", response.status);
134+
if (unauthorized < unauthorizedRetries) {
135+
unauthorized += 1;
136+
await pause(PROVISIONING_RETRY_DELAY_MS);
137+
continue;
138+
}
139+
throw new HttpError(unauthorizedMessage(unauthorized), response.status);
112140
}
113141

114-
if (RETRYABLE_STATUSES.has(response.status) && attempt < MAX_RETRIES) {
142+
if (RETRYABLE_STATUSES.has(response.status) && throttled < MAX_RETRIES) {
143+
throttled += 1;
115144
await pause(getRetryDelayMs(response.headers.get("Retry-After")));
116145
continue;
117146
}
118147

119148
throw new HttpError(parseErrorMessage(text, response.status), response.status);
120149
}
150+
}
121151

122-
throw new Error("Blob credentials request failed after retries");
152+
interface BucketTokenSource {
153+
token: string;
154+
/** Retry 401s for buckets that may still be provisioning; 0 for ambient tokens. */
155+
unauthorizedRetries: number;
123156
}
124157

125-
function resolveBucketToken(flags: { bucketId?: string }, command: Command): Promise<string> {
158+
function resolveBucketToken(
159+
flags: { bucketId?: string },
160+
command: Command,
161+
): Promise<BucketTokenSource> {
126162
if (flags.bucketId) {
127163
const auth = resolveAuth(command);
128164
return request<BlobBucket>(auth, "GET", `/v2/blob/bucket/${flags.bucketId}`).then((bucket) => {
129165
if (typeof bucket.token === "string" && bucket.token.length > 0) {
130-
return bucket.token;
166+
return {
167+
token: bucket.token,
168+
unauthorizedRetries: isFreshlyCreated(bucket.creation_time) ? PROVISIONING_MAX_RETRIES : 0,
169+
};
131170
}
132171
throw new Error(`Blob bucket ${flags.bucketId} did not return a current token`);
133172
});
134173
}
135174

136175
const token = process.env.UPSTASH_BLOB_TOKEN;
137176
if (typeof token === "string" && token.length > 0) {
138-
return Promise.resolve(token);
177+
return Promise.resolve({ token, unauthorizedRetries: 0 });
139178
}
140179

141180
return Promise.reject(
@@ -152,9 +191,18 @@ export function registerBlobCredentials(blob: Command): void {
152191
"Get temporary S3 credentials for a Blob bucket; expiresAt is the credential expiry",
153192
)
154193
.option("--bucket-id <id>", "Blob bucket ID")
194+
.addHelpText(
195+
"after",
196+
`
197+
With --bucket-id, a bucket created in the last few minutes is polled for up
198+
to ~30s until provisioning finishes, so it is safe to run right after create.
199+
`,
200+
)
155201
.action(async (flags: { bucketId?: string }, command: Command) => {
156-
const token = await resolveBucketToken(flags, command);
157-
const credentials = await fetchBlobCredentials(token);
202+
const source = await resolveBucketToken(flags, command);
203+
const credentials = await fetchBlobCredentials(source.token, sleep, {
204+
unauthorizedRetries: source.unauthorizedRetries,
205+
});
158206
printJSON(credentials);
159207
});
160208
}

‎src/commands/blob/delete.ts‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,41 @@
11
import { Command } from "commander";
22
import { resolveAuth } from "../../auth.js";
3-
import { request } from "../../client.js";
3+
import { HttpError, request } from "../../client.js";
44
import { printJSON } from "../../output.js";
5+
import { sleep } from "./retry.js";
6+
import type { Sleep } from "./retry.js";
7+
import type { Auth } from "../../auth.js";
8+
9+
const SERVER_ERROR_RETRY_DELAY_MS = 3000;
10+
const SERVER_ERROR_MAX_RETRIES = 5;
11+
12+
/**
13+
* Deleting a bucket moments after creating it can fail with a 5xx while the
14+
* backend is still provisioning it. Retry briefly; a 404 after an earlier
15+
* attempt means that attempt actually went through.
16+
*/
17+
export async function deleteBlobBucket(
18+
auth: Auth,
19+
bucketId: string,
20+
pause: Sleep = sleep,
21+
): Promise<void> {
22+
let retries = 0;
23+
for (;;) {
24+
try {
25+
await request(auth, "DELETE", `/v2/blob/bucket/${bucketId}`);
26+
return;
27+
} catch (error) {
28+
if (!(error instanceof HttpError)) throw error;
29+
if (error.status === 404 && retries > 0) return;
30+
if (error.status >= 500 && retries < SERVER_ERROR_MAX_RETRIES) {
31+
retries += 1;
32+
await pause(SERVER_ERROR_RETRY_DELAY_MS);
33+
continue;
34+
}
35+
throw error;
36+
}
37+
}
38+
}
539

640
export function registerBlobDelete(blob: Command): void {
741
blob
@@ -15,7 +49,7 @@ export function registerBlobDelete(blob: Command): void {
1549
return;
1650
}
1751
const auth = resolveAuth(command);
18-
await request(auth, "DELETE", `/v2/blob/bucket/${flags.bucketId}`);
52+
await deleteBlobBucket(auth, flags.bucketId);
1953
printJSON({ deleted: true, bucket_id: flags.bucketId });
2054
});
2155
}

‎src/commands/blob/retry.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
export type Sleep = (ms: number) => Promise<void>;
2+
3+
export function sleep(ms: number): Promise<void> {
4+
return new Promise((resolve) => setTimeout(resolve, ms));
5+
}
6+
7+
/** Buckets younger than this may still be provisioning on the Blob worker. */
8+
export const PROVISIONING_WINDOW_SECONDS = 5 * 60;
9+
export const PROVISIONING_RETRY_DELAY_MS = 3000;
10+
export const PROVISIONING_MAX_RETRIES = 10;
11+
12+
export function isFreshlyCreated(creationTime: number | undefined, nowSeconds = Date.now() / 1000): boolean {
13+
if (typeof creationTime !== "number" || !Number.isFinite(creationTime)) return true;
14+
return nowSeconds - creationTime < PROVISIONING_WINDOW_SECONDS;
15+
}

‎tests/unit/blob.test.ts‎

Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
22
import { createBlobProgram, runCommand } from "../helpers/program.js";
33
import { fetchBlobCredentials } from "../../src/commands/blob/credentials.js";
4+
import { deleteBlobBucket } from "../../src/commands/blob/delete.js";
5+
import { isFreshlyCreated } from "../../src/commands/blob/retry.js";
46
import type { BlobBucket, BlobS3Credentials } from "../../src/types.js";
57

68
const originalEnv = { ...process.env };
@@ -317,6 +319,93 @@ describe("blob credentials command", () => {
317319
).rejects.toThrow(/rejected/);
318320
});
319321

322+
it("401 hint mentions provisioning when no retries were allowed", async () => {
323+
vi.spyOn(globalThis, "fetch").mockResolvedValue(
324+
new Response('{"error":"unauthorized"}', { status: 401 }),
325+
);
326+
327+
await expect(fetchBlobCredentials("token", async () => {})).rejects.toThrow(
328+
/still be provisioning/,
329+
);
330+
});
331+
332+
it("retries 401 while a fresh bucket is provisioning, then succeeds", async () => {
333+
const credentials = makeCredentials();
334+
const delays: number[] = [];
335+
vi.spyOn(globalThis, "fetch")
336+
.mockResolvedValueOnce(new Response('{"error":"unauthorized"}', { status: 401 }))
337+
.mockResolvedValueOnce(new Response('{"error":"unauthorized"}', { status: 401 }))
338+
.mockResolvedValueOnce(new Response(JSON.stringify(credentials), { status: 200 }));
339+
340+
const result = await fetchBlobCredentials(
341+
"bucket-token",
342+
async (ms) => {
343+
delays.push(ms);
344+
},
345+
{ unauthorizedRetries: 10 },
346+
);
347+
348+
expect(result).toEqual(credentials);
349+
expect(delays).toEqual([3000, 3000]);
350+
});
351+
352+
it("gives up on 401 after the provisioning retry budget and says how long it waited", async () => {
353+
const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async () =>
354+
new Response('{"error":"unauthorized"}', { status: 401 }),
355+
);
356+
357+
await expect(
358+
fetchBlobCredentials("bucket-token", async () => {}, { unauthorizedRetries: 2 }),
359+
).rejects.toThrow(/rejected after waiting 6s/);
360+
expect(fetchSpy).toHaveBeenCalledTimes(3);
361+
});
362+
363+
it("401 retries do not consume the throttle retry budget", async () => {
364+
const credentials = makeCredentials();
365+
vi.spyOn(globalThis, "fetch")
366+
.mockResolvedValueOnce(new Response("", { status: 401 }))
367+
.mockResolvedValueOnce(new Response("", { status: 503 }))
368+
.mockResolvedValueOnce(new Response("", { status: 401 }))
369+
.mockResolvedValueOnce(new Response("", { status: 503 }))
370+
.mockResolvedValueOnce(new Response("", { status: 503 }))
371+
.mockResolvedValueOnce(new Response(JSON.stringify(credentials), { status: 200 }));
372+
373+
const result = await fetchBlobCredentials("t", async () => {}, { unauthorizedRetries: 2 });
374+
expect(result).toEqual(credentials);
375+
});
376+
377+
it("by bucket id does not retry 401 for a bucket that is not freshly created", async () => {
378+
const bucket = makeBucket({ creation_time: 1 });
379+
const fetchSpy = vi
380+
.spyOn(globalThis, "fetch")
381+
.mockResolvedValueOnce(new Response(JSON.stringify(bucket), { status: 200 }))
382+
.mockResolvedValue(new Response('{"error":"unauthorized"}', { status: 401 }));
383+
384+
const program = await createBlobProgram();
385+
await expect(
386+
runCommand(program, ["blob", "credentials", "--bucket-id", "bucket_123"]),
387+
).rejects.toThrow(/rejected/);
388+
expect(fetchSpy).toHaveBeenCalledTimes(2);
389+
});
390+
391+
it("by bucket id polls 401 for a freshly created bucket", async () => {
392+
vi.useFakeTimers();
393+
const bucket = makeBucket({ creation_time: Math.floor(Date.now() / 1000) });
394+
const credentials = makeCredentials();
395+
const fetchSpy = vi
396+
.spyOn(globalThis, "fetch")
397+
.mockResolvedValueOnce(new Response(JSON.stringify(bucket), { status: 200 }))
398+
.mockResolvedValueOnce(new Response('{"error":"unauthorized"}', { status: 401 }))
399+
.mockResolvedValueOnce(new Response(JSON.stringify(credentials), { status: 200 }));
400+
401+
const program = await createBlobProgram();
402+
const pending = runCommand(program, ["blob", "credentials", "--bucket-id", "bucket_123"]);
403+
await vi.advanceTimersByTimeAsync(3000);
404+
405+
expect(await pending).toEqual(credentials);
406+
expect(fetchSpy).toHaveBeenCalledTimes(3);
407+
});
408+
320409
it("retries 429 and 503 with retry-after or fallback delays, then succeeds", async () => {
321410
const credentials = makeCredentials();
322411
const delays: number[] = [];
@@ -349,3 +438,70 @@ describe("blob credentials command", () => {
349438
expect(delays).toEqual([10000, 2000, 3000]);
350439
});
351440
});
441+
442+
describe("blob provisioning helpers", () => {
443+
it("treats missing or recent creation times as freshly created", () => {
444+
expect(isFreshlyCreated(undefined)).toBe(true);
445+
expect(isFreshlyCreated(1000, 1000 + 60)).toBe(true);
446+
expect(isFreshlyCreated(1000, 1000 + 5 * 60)).toBe(false);
447+
});
448+
});
449+
450+
describe("blob delete retries", () => {
451+
const auth = { email: "user@example.com", apiKey: "api-key" };
452+
453+
it("retries 5xx while the bucket is provisioning, then succeeds", async () => {
454+
const delays: number[] = [];
455+
const fetchSpy = vi
456+
.spyOn(globalThis, "fetch")
457+
.mockResolvedValueOnce(new Response('{"error":"internal"}', { status: 500 }))
458+
.mockResolvedValueOnce(new Response('"OK"', { status: 200 }));
459+
460+
await deleteBlobBucket(auth, "bucket_123", async (ms) => {
461+
delays.push(ms);
462+
});
463+
464+
expect(fetchSpy).toHaveBeenCalledTimes(2);
465+
expect(delays).toEqual([3000]);
466+
});
467+
468+
it("treats a 404 after a failed attempt as already deleted", async () => {
469+
vi.spyOn(globalThis, "fetch")
470+
.mockResolvedValueOnce(new Response('{"error":"internal"}', { status: 500 }))
471+
.mockResolvedValueOnce(new Response('{"error":"resource not found"}', { status: 404 }));
472+
473+
await expect(deleteBlobBucket(auth, "bucket_123", async () => {})).resolves.toBeUndefined();
474+
});
475+
476+
it("does not retry a first-attempt 404 or any 4xx", async () => {
477+
const fetchSpy = vi.spyOn(globalThis, "fetch")
478+
.mockResolvedValueOnce(new Response('{"error":"resource not found"}', { status: 404 }));
479+
await expect(deleteBlobBucket(auth, "bucket_123", async () => {})).rejects.toThrow(/not found/);
480+
expect(fetchSpy).toHaveBeenCalledTimes(1);
481+
482+
fetchSpy.mockResolvedValueOnce(new Response('{"error":"bad"}', { status: 400 }));
483+
await expect(deleteBlobBucket(auth, "bucket_123", async () => {})).rejects.toThrow(/bad/);
484+
expect(fetchSpy).toHaveBeenCalledTimes(2);
485+
});
486+
487+
it("gives up after the 5xx retry budget", async () => {
488+
const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async () =>
489+
new Response('{"error":"internal"}', { status: 500 }),
490+
);
491+
await expect(deleteBlobBucket(auth, "bucket_123", async () => {})).rejects.toThrow(/internal/);
492+
expect(fetchSpy).toHaveBeenCalledTimes(6);
493+
});
494+
495+
it("delete command surfaces the retried result", async () => {
496+
vi.useFakeTimers();
497+
vi.spyOn(globalThis, "fetch")
498+
.mockResolvedValueOnce(new Response('{"error":"internal"}', { status: 500 }))
499+
.mockResolvedValueOnce(new Response('"OK"', { status: 200 }));
500+
501+
const program = await createBlobProgram();
502+
const pending = runCommand(program, ["blob", "delete", "--bucket-id", "bucket_123"]);
503+
await vi.advanceTimersByTimeAsync(3000);
504+
505+
expect(await pending).toEqual({ deleted: true, bucket_id: "bucket_123" });
506+
});
507+
});

0 commit comments

Comments
 (0)