Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 58 additions & 11 deletions src/gateways/api-gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import type {
} from '../types/domain/live.types.js';
import type { TeamSettings } from '../types/domain/team-settings.types.js';
import { components, paths } from '../types/generated/schema.types.js';
import type { SignedUpload } from './supabase-gateway.js';
import { expandHome } from '../utils/paths.js';
import { assertCompleteZip, IncompleteZipError } from '../utils/zip-integrity.js';

Expand Down Expand Up @@ -145,6 +146,15 @@ export interface ResultsPollCache {
etag?: string;
}

/**
* An upload-URL response. `signedUpload` comes only from an API that supports
* direct uploads, and only when the request asked for it; without it the
* client uploads to `tempPath`.
*/
type UploadUrlResponse = components['schemas']['IGetBinaryUploadUrlResponse'] & {
signedUpload?: SignedUpload;
};

export const ApiGateway = {
/**
* Enhances generic "fetch failed" errors with more specific diagnostic information
Expand Down Expand Up @@ -642,19 +652,25 @@ export const ApiGateway = {
*/
shaPlain?: string;
supabaseSuccess: boolean;
/**
* True when `path` is the final path a signed token uploaded to. The API
* then checks the object is there and skips its copy.
*/
useTus?: boolean;
}) {
const { baseUrl, auth, id, metadata, path, sha, shaPlain, supabaseSuccess, backblazeSuccess, bytes } = config;
const { baseUrl, auth, id, metadata, path, sha, shaPlain, supabaseSuccess, backblazeSuccess, bytes, useTus } = config;
try {
const res = await fetch(`${baseUrl}/uploads/finaliseUpload`, {
body: JSON.stringify({
backblazeSuccess,
bytes,
id,
metadata,
path, // This is tempPath for TUS uploads
path, // tempPath, or the signed final path when useTus is set
...(sha ? { sha } : {}),
...(shaPlain ? { shaPlain } : {}),
supabaseSuccess,
...(useTus ? { useTus } : {}),
}),
headers: {
'content-type': 'application/json',
Expand Down Expand Up @@ -686,7 +702,9 @@ export const ApiGateway = {
) {
try {
const res = await fetch(`${baseUrl}/uploads/getBinaryUploadUrl`, {
body: JSON.stringify({ platform, fileSize }),
// signedUpload: ask for a token to upload straight to the final
// path. An API without direct uploads ignores the field.
body: JSON.stringify({ platform, fileSize, signedUpload: true }),
headers: {
'content-type': 'application/json',
...auth.headers,
Expand All @@ -697,9 +715,7 @@ export const ApiGateway = {
await this.handleApiError(res, 'Failed to get upload URL');
}

return await parseJsonResponse<
paths['/uploads/getBinaryUploadUrl']['post']['responses']['201']['content']['application/json']
>(res, 'Failed to get upload URL');
return await parseJsonResponse<UploadUrlResponse>(res, 'Failed to get upload URL');
} catch (error) {
if (error instanceof TypeError && error.message === 'fetch failed') {
throw this.enhanceFetchError(error, `${baseUrl}/uploads/getBinaryUploadUrl`);
Expand Down Expand Up @@ -1007,7 +1023,7 @@ export const ApiGateway = {
) {
try {
const res = await fetch(`${baseUrl}/uploads/getFlowUploadUrl`, {
body: JSON.stringify({ fileSize, useTus: true }),
body: JSON.stringify({ fileSize, signedUpload: true, useTus: true }),
headers: {
'content-type': 'application/json',
...auth.headers,
Expand All @@ -1018,10 +1034,8 @@ export const ApiGateway = {
await this.handleApiError(res, 'Failed to get flow upload URL');
}

// Same response shape as getBinaryUploadUrl: { id, tempPath, finalPath, path, b2?, token? }.
return await parseJsonResponse<
components['schemas']['IGetBinaryUploadUrlResponse']
>(res, 'Failed to get flow upload URL');
// Same response shape as getBinaryUploadUrl.
return await parseJsonResponse<UploadUrlResponse>(res, 'Failed to get flow upload URL');
} catch (error) {
if (error instanceof TypeError && error.message === 'fetch failed') {
throw this.enhanceFetchError(error, `${baseUrl}/uploads/getFlowUploadUrl`);
Expand All @@ -1031,6 +1045,39 @@ export const ApiGateway = {
}
},

/**
* A fresh signed upload token for a path an upload-URL response gave us,
* so an upload whose token expired can carry on. The API refuses a path
* outside the caller's org and an upload that is already finalised.
*/
async refreshUploadToken(baseUrl: string, auth: AuthContext, path: string): Promise<SignedUpload> {
try {
const res = await fetch(`${baseUrl}/uploads/refreshUploadToken`, {
body: JSON.stringify({ path }),
headers: {
'content-type': 'application/json',
...auth.headers,
},
method: 'POST',
});
if (!res.ok) {
await this.handleApiError(res, 'Failed to refresh upload token');
}

const { signedUpload } = await parseJsonResponse<{ signedUpload: SignedUpload }>(
res,
'Failed to refresh upload token',
);
return signedUpload;
} catch (error) {
if (error instanceof TypeError && error.message === 'fetch failed') {
throw this.enhanceFetchError(error, `${baseUrl}/uploads/refreshUploadToken`);
}

throw error;
}
},

/**
* Submits a flow test that references an already-uploaded zip (JSON body, no
* multipart). The response is identical to the legacy `POST /uploads/flow`.
Expand Down
185 changes: 157 additions & 28 deletions src/gateways/supabase-gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,33 +14,131 @@ export interface ResumableUploadSource {
size: number;
}

/**
* A signed upload for one storage path, from the API's upload-URL response.
* The token is sent as `x-signature` on every TUS request; it writes only
* `path` and never overwrites an existing object.
*/
export interface SignedUpload {
expiresInSeconds: number;
path: string;
token: string;
}

/** Refresh this long before the token says it expires. */
const REFRESH_MARGIN_MS = 10 * 60 * 1000;
/** Fresh tokens one upload may ask for before it gives up. */
const MAX_TOKEN_REFRESHES = 5;
const RETRY_DELAYS = [0, 3000, 5000, 10_000, 20_000];

/**
* Whether a TUS error response says the upload token was refused, which a
* fresh token for the same path fixes. Storage answers an expired or bad
* signature with a 4xx whose body names the JWT or signature.
*/
export function isSignatureError(status: number, body: string): boolean {
return [400, 401, 403].includes(status) && /jwt|signature|expired/i.test(body);
}

/** tus's own rule: retry anything but a 4xx, except 409 and 423. */
function defaultShouldRetry(status: number): boolean {
return !(status >= 400 && status < 500) || status === 409 || status === 423;
}

export class SupabaseGateway {
/**
* Upload to Supabase using resumable uploads (TUS protocol)
* Uploads to staging location (uploads/{id}/) using the publishable key
* File is later moved to final location by API after finalization
* @param env - Environment (dev or prod)
* @param path - Staging storage path (uploads/{id}/file.ext)
* @param source - Upload source descriptor; the file is streamed from disk
* @param debug - Enable debug logging
* @param onProgress - Optional callback for upload progress (bytesUploaded, bytesTotal)
* @returns Promise that resolves when upload completes
* Upload straight to the final storage path with a signed token, through
* `/storage/v1/upload/resumable/sign`. No storage key of the client's own
* is needed: the token is the permission.
*
* The token lasts a couple of hours and storage checks it on every
* request, so a long or resumed upload can outlive it. Before each request
* the token is refreshed when it is close to expiry, and a request refused
* for its signature is retried with a fresh one. Either way it is the same
* path, so the same TUS upload carries on.
*
* @param refreshToken - Asks the API for a fresh token for `signed.path`
* @param options.storageUrl - Test seam; defaults to the environment's URL
*/
static async uploadResumable(
static async uploadResumableSigned(
env: DcdEnvName,
path: string,
signed: SignedUpload,
source: ResumableUploadSource,
refreshToken: (path: string) => Promise<SignedUpload>,
debug = false,
onProgress?: (bytesUploaded: number, bytesTotal: number) => void,
options: { retryDelays?: number[]; storageUrl?: string } = {},
): Promise<void> {
// Prod's Supabase URL is our own custom domain, so customers' networks
// only need to reach devicecloud.dev, not supabase.co.
const storageUrl = ENVIRONMENTS[env].supabase.url;
const storageUrl = options.storageUrl ?? ENVIRONMENTS[env].supabase.url;
const supabaseKey = await getSupabaseKey(env);

let { token } = signed;
let expiresAt = Date.now() + signed.expiresInSeconds * 1000;
let stale = false;
let refreshes = 0;
let pending: Promise<void> | undefined;

const margin = Math.min(REFRESH_MARGIN_MS, (signed.expiresInSeconds * 1000) / 2);
const refresh = (): Promise<void> => {
pending ??= (async () => {
refreshes += 1;
if (debug) console.log(`[DEBUG] Refreshing the upload token for ${signed.path}`);
const fresh = await refreshToken(signed.path);
token = fresh.token;
expiresAt = Date.now() + fresh.expiresInSeconds * 1000;
stale = false;
})().finally(() => {
pending = undefined;
});
return pending;
};

await this.runTusUpload({
debug,
endpoint: `${storageUrl}/storage/v1/upload/resumable/sign`,
// The gateway in front of Storage routes on the key; the token is the
// permission, and the upload is checked against it, not the key.
headers: supabaseKeyHeaders(supabaseKey),
async onBeforeRequest(req) {
if (stale || Date.now() >= expiresAt - margin) {
await refresh();
}

req.setHeader('x-signature', token);
},
onShouldRetry(err) {
const status = err.originalResponse?.getStatus() ?? 0;
const body = err.originalResponse?.getBody() ?? '';
if (isSignatureError(status, body)) {
if (refreshes >= MAX_TOKEN_REFRESHES) return false;
stale = true;
return true;
}

return defaultShouldRetry(status);
},
path: signed.path,
retryDelays: options.retryDelays ?? RETRY_DELAYS,
source,
});
}

/** One TUS upload of `source` to `path` in the organizations bucket. */
private static runTusUpload(config: {
debug: boolean;
endpoint: string;
headers: Record<string, string>;
onBeforeRequest?: (req: tus.HttpRequest) => Promise<void> | void;
onProgress?: (bytesUploaded: number, bytesTotal: number) => void;
onShouldRetry?: (err: tus.DetailedError) => boolean;
path: string;
retryDelays: number[];
source: ResumableUploadSource;
}): Promise<void> {
const { debug, endpoint, headers, onBeforeRequest, onProgress, onShouldRetry, path, retryDelays, source } = config;

if (debug) {
console.log(`[DEBUG] Resumable upload starting...`);
console.log(`[DEBUG] Storage URL: ${storageUrl}`);
console.log(`[DEBUG] Endpoint: ${endpoint}`);
console.log(`[DEBUG] Upload path: ${path}`);
console.log(`[DEBUG] File name: ${source.name}`);
console.log(`[DEBUG] File size: ${(source.size / 1024 / 1024).toFixed(2)} MB`);
Expand All @@ -56,18 +154,11 @@ export class SupabaseGateway {
// Bun's node:http can't send tus's create request; see FetchHttpStack.
...tusHttpStackOptions(),

// TUS endpoint for Supabase Storage
endpoint: `${storageUrl}/storage/v1/upload/resumable`,

// Retry configuration - will retry 5 times with increasing delays
retryDelays: [0, 3000, 5000, 10_000, 20_000],

// Authentication and headers
// Publishable key for staging uploads to uploads/* folder
headers: {
...supabaseKeyHeaders(supabaseKey),
'x-upsert': 'true', // Allow overwriting existing files
},
endpoint,
retryDelays,
headers,
...(onBeforeRequest ? { onBeforeRequest } : {}),
...(onShouldRetry ? { onShouldRetry } : {}),

// Upload metadata
metadata: {
Expand Down Expand Up @@ -134,4 +225,42 @@ export class SupabaseGateway {
upload.start();
});
}

/**
* Upload to Supabase using resumable uploads (TUS protocol)
* Uploads to staging location (uploads/{id}/) using the publishable key
* File is later moved to final location by API after finalization
* @param env - Environment (dev or prod)
* @param path - Staging storage path (uploads/{id}/file.ext)
* @param source - Upload source descriptor; the file is streamed from disk
* @param debug - Enable debug logging
* @param onProgress - Optional callback for upload progress (bytesUploaded, bytesTotal)
* @returns Promise that resolves when upload completes
*/
static async uploadResumable(
env: DcdEnvName,
path: string,
source: ResumableUploadSource,
debug = false,
onProgress?: (bytesUploaded: number, bytesTotal: number) => void,
): Promise<void> {
// Prod's Supabase URL is our own custom domain, so customers' networks
// only need to reach devicecloud.dev, not supabase.co.
const storageUrl = ENVIRONMENTS[env].supabase.url;
const supabaseKey = await getSupabaseKey(env);

return this.runTusUpload({
debug,
endpoint: `${storageUrl}/storage/v1/upload/resumable`,
// Publishable key for staging uploads to uploads/* folder
headers: {
...supabaseKeyHeaders(supabaseKey),
'x-upsert': 'true', // Allow overwriting existing files
},
onProgress,
path,
retryDelays: RETRY_DELAYS,
source,
});
}
}
Loading
Loading