Files
mtusi2026lab6/scripts/lib/openobserve-account-http.ts

49 lines
2.5 KiB
TypeScript

export type AccountResponse = { status: number; chunks: AsyncIterable<Uint8Array> };
export type AccountRequest = { captureId: string; path: string; method: string; body?: unknown; auth: string };
export type AccountCapture = { captureId: string; raw: Uint8Array; status: number | null; outcome: string; complete: boolean };
export type AccountHTTPPorts = {
request(input: AccountRequest): Promise<AccountResponse>;
capture(input: AccountCapture): Promise<void>;
};
export class AccountHTTPError extends Error {
constructor(readonly stage: string, readonly captureFailed = false) {
super('Account HTTP outcome: ' + stage + (captureFailed ? '; private capture failed' : ''));
}
}
export function createAccountHTTP(ports: AccountHTTPPorts, maxBytes: number) {
if (!ports?.request || !ports?.capture || !Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 1_048_576) throw new Error('Invalid account HTTP ports or bound');
return async (input: AccountRequest) => {
const chunks: Uint8Array[] = [];
let size = 0, status: number | null = null, stage = 'network_uncertain';
const joined = () => {
const raw = new Uint8Array(size);
let offset = 0;
for (const chunk of chunks) { raw.set(chunk, offset); offset += chunk.length; }
return raw;
};
try {
const response = await ports.request(input);
status = response.status;
stage = 'body_uncertain';
for await (const chunk of response.chunks) {
const available = Math.min(chunk.length, maxBytes - size);
if (available > 0) { chunks.push(chunk.slice(0, available)); size += available; }
if (available < chunk.length) { stage = 'size_exceeded'; throw new AccountHTTPError(stage); }
}
} catch {
let captureFailed = false;
try { await ports.capture({ captureId: input.captureId, raw: joined(), status, outcome: stage, complete: false }); }
catch { captureFailed = true; }
// No retry: the remote POST may already have created the account.
throw new AccountHTTPError(stage, captureFailed);
}
const raw = joined();
try { await ports.capture({ captureId: input.captureId, raw, status, outcome: 'response_complete', complete: true }); }
catch { throw new AccountHTTPError('capture_failed', true); }
let body: unknown;
try { body = size ? JSON.parse(new TextDecoder().decode(raw)) : null; }
catch { throw new AccountHTTPError('invalid_json'); }
return { status: status!, body: body as any };
};
}