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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"scripts": {
"build": "tsx scripts/build.ts",
"typecheck": "tsc --noEmit --project tsconfig.json",
"test": "npm run build && node dist/test/security-hardening.test.js && node dist/test/source-ssrf.test.js && node dist/test/browser-collector-ingest.test.js && node dist/test/slot-scheduler.test.js && node dist/test/daily-inventory-planner.test.js && node dist/test/refresh-queue-finalization.test.js && node dist/test/publish-summary.test.js && node dist/test/threads-refresh.test.js && node dist/test/linkedin-refresh.test.js && node dist/test/instagram-image-timeout.test.js && node dist/test/cost-control.test.js && node dist/test/recovery-scheduler.test.js && node dist/test/social-connector.test.js && node dist/test/meta-publication-boundary.test.js && node dist/test/cloudflare-health.test.js && node dist/test/exclusive-run-gate.test.js && node dist/test/runtime-scope.test.js && node dist/test/tenant-platform-policy.test.js",
"test": "npm run build && node dist/test/security-hardening.test.js && node dist/test/source-ssrf.test.js && node dist/test/browser-collector-ingest.test.js && node dist/test/slot-scheduler.test.js && node dist/test/daily-inventory-planner.test.js && node dist/test/refresh-queue-finalization.test.js && node dist/test/publish-summary.test.js && node dist/test/threads-refresh.test.js && node dist/test/linkedin-refresh.test.js && node dist/test/instagram-image-timeout.test.js && node dist/test/cost-control.test.js && node dist/test/recovery-scheduler.test.js && node dist/test/social-connector.test.js && node dist/test/meta-publication-boundary.test.js && node dist/test/cloudflare-health.test.js && node dist/test/exclusive-run-gate.test.js && node dist/test/runtime-scope.test.js && node dist/test/tenant-platform-policy.test.js && node dist/test/supabase-client-retry.test.js && node dist/test/worker-claims.test.js",
"smoke:dist": "node dist/src/cli.js status",
"ci": "npm run typecheck && npm test && npm run smoke:dist",
"dev": "tsx src/agent.ts",
Expand Down
54 changes: 44 additions & 10 deletions src/supabase-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@ export interface SupabaseMutationOptions {
returning?: boolean;
}

export interface SupabaseRpcOptions {
/**
* Allows network retries only when the RPC contract itself is idempotent for
* the exact request body. Ordinary database writes must leave this false.
*/
retrySafe?: boolean;
}

export class SupabaseRestError extends Error {
constructor(
message: string,
Expand Down Expand Up @@ -85,19 +93,25 @@ function describeCause(error: unknown): string | undefined {
return undefined;
}

async function fetchSupabase(url: string | URL, init: RequestInit, table: string, operation: string): Promise<Response> {
const maxAttempts = 3;
async function fetchSupabase(
url: string | URL,
init: RequestInit,
table: string,
operation: string,
maxAttempts: number
): Promise<Response> {
const attempts = Math.max(1, maxAttempts);
let lastError: unknown;

for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
for (let attempt = 1; attempt <= attempts; attempt += 1) {
try {
return await fetch(url, {
...init,
signal: AbortSignal.timeout(config.HTTP_TIMEOUT_MS),
});
} catch (error) {
lastError = error;
if (attempt < maxAttempts) {
if (attempt < attempts) {
await sleep(500 * attempt);
}
}
Expand All @@ -107,7 +121,7 @@ async function fetchSupabase(url: string | URL, init: RequestInit, table: string
const causeDetails = describeCause(lastError);
const suffix = causeDetails ? ` | cause: ${causeDetails}` : '';
throw new SupabaseNetworkError(
`Supabase ${operation} ${table} network request failed at ${endpoint} after ${maxAttempts} attempts${suffix}`,
`Supabase ${operation} ${table} network request failed at ${endpoint} after ${attempts} attempt${attempts === 1 ? '' : 's'}${suffix}`,
table,
operation,
endpoint,
Expand Down Expand Up @@ -166,7 +180,7 @@ export async function supabaseSelect<T>(

const response = await fetchSupabase(url, {
headers: serviceHeaders(),
}, table, 'select');
}, table, 'select', 3);
return parseResponse<T[]>(response, table);
}

Expand All @@ -183,7 +197,7 @@ export async function supabaseInsert<T>(
Prefer: returning ? 'return=representation' : 'return=minimal',
}),
body: JSON.stringify(body),
}, table, 'insert');
}, table, 'insert', 1);
return parseResponse<T[]>(response, table);
}

Expand All @@ -205,7 +219,7 @@ export async function supabaseUpsert<T>(
].join(','),
}),
body: JSON.stringify(body),
}, table, 'upsert');
}, table, 'upsert', 1);
return parseResponse<T[]>(response, table);
}

Expand All @@ -223,7 +237,7 @@ export async function supabaseUpdate<T>(
Prefer: options.returning ? 'return=representation' : 'return=minimal',
}),
body: JSON.stringify(body),
}, table, 'update');
}, table, 'update', 1);
return parseResponse<T[]>(response, table);
}

Expand All @@ -238,6 +252,26 @@ export async function supabaseDelete<T>(
headers: serviceHeaders({
Prefer: options.returning ? 'return=representation' : 'return=minimal',
}),
}, table, 'delete');
}, table, 'delete', 1);
return parseResponse<T[]>(response, table);
}

export async function supabaseRpc<T>(
functionName: string,
body: Record<string, unknown> = {},
options: SupabaseRpcOptions = {}
): Promise<T> {
if (!/^[a-z0-9_]+$/.test(functionName)) {
throw new Error(`Invalid Supabase RPC function name: ${functionName}`);
}

const url = `${baseUrl()}/rpc/${functionName}`;
const response = await fetchSupabase(url, {
method: 'POST',
headers: serviceHeaders({
'Content-Type': 'application/json',
}),
body: JSON.stringify(body),
}, `rpc/${functionName}`, 'rpc', options.retrySafe ? 3 : 1);
return parseResponse<T>(response, `rpc/${functionName}`);
}
Loading
Loading