An open-source, faster Devin alternative
TypeScript
Forward serverless-agents and @computer Worker logs to Sazabi (#981)
opencomputer-app[bot]b5c654cbf9c5
diff --git a/cloudflare-workers/log-tail/package.json b/cloudflare-workers/log-tail/package.jsonindex 15393eb2..0fa1d152 100644--- a/cloudflare-workers/log-tail/package.json+++ b/cloudflare-workers/log-tail/package.json@@ -2,7 +2,7 @@"name": "opencomputer-log-tail","version": "0.0.0","private": true,- "description": "Tail consumer that forwards Worker console output and exceptions to Axiom with credentials redacted.",+ "description": "Tail consumer that forwards Worker console output and exceptions to Axiom (and Sazabi over OTLP) with credentials redacted.","type": "module","engines": { "node": ">=22.6" },"scripts": {diff --git a/cloudflare-workers/log-tail/src/index.test.ts b/cloudflare-workers/log-tail/src/index.test.tsindex 574cec3c..2192e652 100644--- a/cloudflare-workers/log-tail/src/index.test.ts+++ b/cloudflare-workers/log-tail/src/index.test.ts@@ -206,3 +206,53 @@ test("promotes correlation keys from a JSON log line to fields", async () => {assert.equal(records[2]?.event, "x");assert.equal(records[2]?.service, "managed-agents");});++test("ships to Sazabi as OTLP protobuf without blocking Axiom on a Sazabi failure", async () => {+ const originalFetch = globalThis.fetch;+ const calls: Array<{ url: string; contentType: string | null }> = [];+ globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ calls.push({ url, contentType: new Headers(init?.headers).get("content-type") });+ return new Response(null, { status: url.startsWith("https://sazabi.test") ? 503 : 200 });+ }) as typeof fetch;++ let error: unknown;+ try {+ await worker.tail([{+ scriptName: "api-edge",+ outcome: "ok",+ logs: [{ timestamp: Date.now(), level: "info", message: ["hello"] }],+ exceptions: [],+ }], { ...env, SAZABI_OTLP_LOGS_URL: "https://sazabi.test/secret-key/v1/logs", SAZABI_SERVICES: "api-edge" }, {} as ExecutionContext);+ } catch (err) {+ error = err;+ } finally {+ globalThis.fetch = originalFetch;+ }++ assert.deepEqual(calls.map((c) => c.contentType).sort(), ["application/json", "application/x-protobuf"]);+ assert.match(String(error), /sazabi ingest failed status=503/);+ assert.equal(String(error).includes("secret-key"), false);+});++test("only allowlisted Workers go to Sazabi", async () => {+ const originalFetch = globalThis.fetch;+ const urls: string[] = [];+ globalThis.fetch = (async (input: RequestInfo | URL) => {+ urls.push(String(input));+ return new Response(null, { status: 200 });+ }) as typeof fetch;++ try {+ await worker.tail([{+ scriptName: "opencomputer-vmdo-prod",+ outcome: "ok",+ logs: [{ timestamp: Date.now(), level: "info", message: ["hello"] }],+ exceptions: [],+ }], { ...env, SAZABI_OTLP_LOGS_URL: "https://sazabi.test/v1/logs", SAZABI_SERVICES: "managed-agents, previews" }, {} as ExecutionContext);+ } finally {+ globalThis.fetch = originalFetch;+ }++ assert.deepEqual(urls, ["https://axiom.test/v1/datasets/edge/ingest"]);+});diff --git a/cloudflare-workers/log-tail/src/index.ts b/cloudflare-workers/log-tail/src/index.tsindex 33033b3f..b093804a 100644--- a/cloudflare-workers/log-tail/src/index.ts+++ b/cloudflare-workers/log-tail/src/index.ts@@ -1,5 +1,6 @@// Tail Worker — subscribes to console output and exception traces from-// other Workers in this account and POSTs them as JSON events to Axiom.+// other Workers in this account and POSTs them as JSON events to Axiom, and+// as OTLP logs to Sazabi for the Workers listed in SAZABI_SERVICES.//// Wire it up by adding to each producer Worker's wrangler.toml:// [[tail_consumers]]@@ -9,10 +10,18 @@// already emit (level, msg, service, ...) so the dataset stays one schema// regardless of producer.+import { encodeLogs } from "./otlp.ts";+interface Env {AXIOM_HOST: string;AXIOM_DATASET: string;AXIOM_TOKEN: string;+ // Sazabi OTLP logs intake (ends in /v1/logs). The URL is the credential,+ // so it's a Worker secret. Unset → Sazabi forwarding is off.+ SAZABI_OTLP_LOGS_URL?: string;+ // Comma-separated producer script names forwarded to Sazabi. Sazabi is+ // scoped to serverless agents and @computer, not every tailed Worker.+ SAZABI_SERVICES?: string;}interface TraceLog {@@ -208,23 +217,54 @@ export default {if (records.length === 0) return;- const url = `${env.AXIOM_HOST}/v1/datasets/${env.AXIOM_DATASET}/ingest`;- const resp = await fetch(url, {- method: "POST",- headers: {- Authorization: `Bearer ${env.AXIOM_TOKEN}`,- "Content-Type": "application/json",- },- body: JSON.stringify(records),- });- if (!resp.ok) {- const body = await resp.text().catch(() => "");- const message = `axiom ingest failed status=${resp.status} body=${body.slice(0, 200)}`;- console.error(message);+ // Axiom gets everything; Sazabi gets the allowlisted Workers. One sink+ // failing never stops the other.+ const sazabiServices = new Set((env.SAZABI_SERVICES ?? "").split(",").map((s) => s.trim()).filter(Boolean));+ const sazabiRecords = records.filter((r) => sazabiServices.has(String(r.service)));+ const results = await Promise.allSettled([+ sendToAxiom(records, env),+ env.SAZABI_OTLP_LOGS_URL && sazabiRecords.length > 0+ ? sendToSazabi(sazabiRecords, env.SAZABI_OTLP_LOGS_URL)+ : Promise.resolve(),+ ]);+ const failures = results+ .filter((r): r is PromiseRejectedResult => r.status === "rejected")+ .map((r) => (r.reason instanceof Error ? r.reason.message : String(r.reason)));+ if (failures.length > 0) {+ for (const message of failures) console.error(message);// The collector has Cloudflare Workers Logs enabled as an independent- // fallback. Throwing makes a broken durable sink an observable failed+ // fallback. Throwing makes a broken sink an observable failed// invocation instead of an apparently healthy, lossy success.- throw new Error(message);+ throw new Error(failures.join("; "));}},};++async function sendToAxiom(records: Record<string, unknown>[], env: Env): Promise<void> {+ const url = `${env.AXIOM_HOST}/v1/datasets/${env.AXIOM_DATASET}/ingest`;+ const resp = await fetch(url, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${env.AXIOM_TOKEN}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify(records),+ });+ if (!resp.ok) {+ const body = await resp.text().catch(() => "");+ throw new Error(`axiom ingest failed status=${resp.status} body=${body.slice(0, 200)}`);+ }+}++async function sendToSazabi(records: Record<string, unknown>[], url: string): Promise<void> {+ const resp = await fetch(url, {+ method: "POST",+ headers: { "Content-Type": "application/x-protobuf" },+ body: encodeLogs(records),+ });+ if (!resp.ok) {+ const body = await resp.text().catch(() => "");+ // Never echo the URL: it is the credential.+ throw new Error(`sazabi ingest failed status=${resp.status} body=${body.slice(0, 200)}`);+ }+}diff --git a/cloudflare-workers/log-tail/src/otlp.ts b/cloudflare-workers/log-tail/src/otlp.tsnew file mode 100644index 00000000..7595e690--- /dev/null+++ b/cloudflare-workers/log-tail/src/otlp.ts@@ -0,0 +1,139 @@+// Minimal OTLP/HTTP protobuf encoder for logs (ExportLogsServiceRequest),+// enough to ship our tail records to Sazabi. Hand-rolled because the+// generated protobuf libraries pull in code generation that Workers forbid,+// and the subset we need is a handful of fields:+//+// ExportLogsServiceRequest { repeated ResourceLogs resource_logs = 1; }+// ResourceLogs { Resource resource = 1; repeated ScopeLogs scope_logs = 2; }+// Resource { repeated KeyValue attributes = 1; }+// ScopeLogs { InstrumentationScope scope = 1; repeated LogRecord log_records = 2; }+// InstrumentationScope { string name = 1; }+// LogRecord { fixed64 time_unix_nano = 1; SeverityNumber severity_number = 2;+// string severity_text = 3; AnyValue body = 5;+// repeated KeyValue attributes = 6; }+// KeyValue { string key = 1; AnyValue value = 2; }+// AnyValue { string string_value = 1; bool bool_value = 2;+// int64 int_value = 3; double double_value = 4; }++const SEVERITY_NUMBER: Record<string, number> = { DEBUG: 5, INFO: 9, WARN: 13, ERROR: 17 };++// Envelope fields that describe the producer rather than the event; they+// become resource attributes so each Worker is one OTLP resource.+const RESOURCE_FIELDS = new Set(["service", "service_id", "cell_id", "region", "script_version"]);+// Fields already carried by the record's own protobuf fields.+const RECORD_FIELDS = new Set(["_time", "time", "level", "msg"]);++type Scalar = string | number | boolean;++class Writer {+ private chunks: number[] = [];++ varint(n: number | bigint): this {+ let v = BigInt(n);+ if (v < 0n) v += 1n << 64n;+ while (v > 0x7fn) {+ this.chunks.push(Number((v & 0x7fn) | 0x80n));+ v >>= 7n;+ }+ this.chunks.push(Number(v));+ return this;+ }++ tag(field: number, wireType: number): this {+ return this.varint((field << 3) | wireType);+ }++ bytes(field: number, data: Uint8Array): this {+ this.tag(field, 2).varint(data.length);+ for (const b of data) this.chunks.push(b);+ return this;+ }++ string(field: number, s: string): this {+ return this.bytes(field, new TextEncoder().encode(s));+ }++ message(field: number, w: Writer): this {+ return this.bytes(field, w.finish());+ }++ fixed64(field: number, n: bigint): this {+ this.tag(field, 1);+ for (let i = 0n; i < 8n; i++) this.chunks.push(Number((n >> (8n * i)) & 0xffn));+ return this;+ }++ double(field: number, n: number): this {+ this.tag(field, 1);+ const buf = new DataView(new ArrayBuffer(8));+ buf.setFloat64(0, n, true);+ for (let i = 0; i < 8; i++) this.chunks.push(buf.getUint8(i));+ return this;+ }++ finish(): Uint8Array {+ return Uint8Array.from(this.chunks);+ }+}++function anyValue(v: Scalar): Writer {+ const w = new Writer();+ if (typeof v === "string") w.string(1, v);+ else if (typeof v === "boolean") w.tag(2, 0).varint(v ? 1 : 0);+ else if (Number.isSafeInteger(v)) w.tag(3, 0).varint(v);+ else w.double(4, v);+ return w;+}++function keyValue(key: string, v: Scalar): Writer {+ return new Writer().string(1, key).message(2, anyValue(v));+}++function scalar(v: unknown): Scalar | undefined {+ if (v === undefined || v === null) return undefined;+ if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") return v;+ try { return JSON.stringify(v); } catch { return String(v); }+}++function logRecord(record: Record<string, unknown>): Writer {+ const w = new Writer();+ const ms = Date.parse(String(record._time ?? record.time ?? ""));+ w.fixed64(1, BigInt(Number.isNaN(ms) ? Date.now() : ms) * 1_000_000n);+ const level = String(record.level ?? "INFO");+ w.tag(2, 0).varint(SEVERITY_NUMBER[level] ?? 9);+ w.string(3, level);+ w.message(5, anyValue(String(record.msg ?? "")));+ for (const [key, value] of Object.entries(record)) {+ if (RECORD_FIELDS.has(key) || RESOURCE_FIELDS.has(key)) continue;+ const v = scalar(value);+ if (v !== undefined) w.message(6, keyValue(key, v));+ }+ return w;+}++// Encodes tail records (the same objects sent to Axiom) as one+// ExportLogsServiceRequest, one ResourceLogs per producing Worker.+export function encodeLogs(records: Record<string, unknown>[]): Uint8Array {+ const byResource = new Map<string, Record<string, unknown>[]>();+ for (const record of records) {+ const key = JSON.stringify([...RESOURCE_FIELDS].map((f) => record[f]));+ const group = byResource.get(key);+ if (group) group.push(record);+ else byResource.set(key, [record]);+ }++ const request = new Writer();+ for (const group of byResource.values()) {+ const first = group[0]!;+ const resource = new Writer();+ resource.message(1, keyValue("service.name", String(first.service ?? "unknown")));+ for (const field of RESOURCE_FIELDS) {+ const v = scalar(first[field]);+ if (v !== undefined) resource.message(1, keyValue(field, v));+ }+ const scope = new Writer().message(1, new Writer().string(1, "opencomputer-log-tail"));+ for (const record of group) scope.message(2, logRecord(record));+ request.message(1, new Writer().message(1, resource).message(2, scope));+ }+ return request.finish();+}