@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 265 lines 8.43 KB
Raw
1 import * as workers from "@distilled.cloud/cloudflare/workers";
2 import type { LogLine, LogsInput } from "alchemy/Provider";
3 import { profileCommandHint } from "alchemy/Util/interactive";
4 import type * as Cause from "effect/Cause";
5 import * as Effect from "effect/Effect";
6 import * as Queue from "effect/Queue";
7 import * as Schedule from "effect/Schedule";
8 import * as Socket from "effect/socket/Socket";
9 import * as Stream from "effect/Stream";
10
11 const DEFAULT_LOOKBACK_MS = 1 * 60 * 60 * 1000;
12
13 export interface TelemetryFilter {
14 key: string;
15 operation:
16 | "eq"
17 | "neq"
18 | "includes"
19 | "not_includes"
20 | "starts_with"
21 | "gt"
22 | "gte"
23 | "lt"
24 | "lte"
25 | "in"
26 | "not_in";
27 type: "string" | "number" | "boolean";
28 value?: string | number | boolean;
29 }
30
31 interface TailEventMessage {
32 eventTimestamp?: number;
33 wallTime: number;
34 cpuTime: number;
35 truncated: boolean;
36 outcome: string;
37 scriptName: string;
38 exceptions: {
39 name: string;
40 message: string;
41 stack: string;
42 timestamp: string;
43 }[];
44 logs: {
45 message: string[];
46 level: string;
47 timestamp: string;
48 }[];
49 event:
50 | {
51 request: { method: string; url: string };
52 response?: { status: number };
53 }
54 | null
55 | undefined;
56 }
57
58 const parseEvents = (response: workers.QueryObservabilityTelemetryResponse): LogLine[] => {
59 const lines: LogLine[] = [];
60 if (response.events?.events) {
61 for (const event of response.events.events) {
62 const ts = new Date(event.timestamp);
63 const meta = event.metadata;
64 const msg =
65 meta.message ??
66 (meta.level === "error" ? `error: ${meta.error ?? "unknown"}` : `${meta.level ?? "log"}`);
67 lines.push({ timestamp: ts, message: msg });
68 }
69 }
70 return lines;
71 };
72
73 export const CloudflareLogs = Effect.gen(function* () {
74 const queryTelemetry = yield* workers.queryObservabilityTelemetry;
75 const createScriptTail = yield* workers.createScriptTail;
76 const deleteScriptTail = yield* workers.deleteScriptTail;
77
78 /**
79 * The telemetry query needs the `workers_observability:read` OAuth scope.
80 * A token minted by an older login (before the scope joined the
81 * defaults) keeps its original grants forever, so the query fails with a
82 * bare `Unauthorized`/`Forbidden` even though a fresh login would work —
83 * explain the fix instead of surfacing the raw tag.
84 */
85 const explainMissingObservabilityScope = <A, R>(
86 effect: Effect.Effect<A, workers.QueryObservabilityTelemetryError, R>,
87 ): Effect.Effect<A, workers.QueryObservabilityTelemetryError, R> =>
88 effect.pipe(
89 Effect.catchTag("Unauthorized", () =>
90 Effect.gen(function* () {
91 const command = yield* profileCommandHint(
92 "alchemy profile edit --reconfigure Cloudflare",
93 );
94 return yield* Effect.die(
95 new Error(
96 "Cloudflare rejected the observability telemetry query (Unauthorized). " +
97 'Your stored credentials are likely missing the "workers_observability:read" scope — ' +
98 "OAuth tokens keep the scopes they were minted with, so tokens minted by " +
99 `an older login won't have it. Run \`${command}\` to mint a token with ` +
100 "the current default scopes, or use an API token that grants Workers Observability read access.",
101 ),
102 );
103 }),
104 ),
105 );
106
107 const queryLogs = (opts: { accountId: string; filters: TelemetryFilter[]; options: LogsInput }) =>
108 Effect.gen(function* () {
109 const now = Date.now();
110 const limit = opts.options.limit ?? 100;
111
112 if (opts.options.since) {
113 const response = yield* explainMissingObservabilityScope(
114 queryTelemetry({
115 accountId: opts.accountId,
116 queryId: "events",
117 view: "events",
118 timeframe: { from: opts.options.since.getTime(), to: now },
119 limit,
120 parameters: {
121 filters: opts.filters,
122 // orderBy: { value: "timestamp", order: "desc" },
123 },
124 }),
125 );
126 return parseEvents(response);
127 }
128
129 const response = yield* explainMissingObservabilityScope(
130 queryTelemetry({
131 accountId: opts.accountId,
132 queryId: "events",
133 view: "events",
134 timeframe: { from: now - DEFAULT_LOOKBACK_MS, to: now },
135 limit,
136 parameters: {
137 filters: opts.filters,
138 },
139 }),
140 );
141
142 return parseEvents(response);
143 });
144
145 /**
146 * Open a real-time Workers tail session against `scriptName` and
147 * surface its messages as a {@link LogLine} stream. The websocket is
148 * automatically reconnected (with `Stream.repeat`) when Cloudflare
149 * closes it after its idle window.
150 */
151 const tailScript = (opts: { accountId: string; scriptName: string }) => {
152 const runTailSession = Effect.gen(function* () {
153 const { id: tailId, url } = yield* createScriptTail({
154 scriptName: opts.scriptName,
155 accountId: opts.accountId,
156 filters: [],
157 });
158
159 const socket = yield* Socket.makeWebSocket(url, {
160 protocols: ["trace-v1"],
161 });
162
163 const queue = yield* Queue.make<LogLine, Cause.Done>();
164
165 const decoder = new TextDecoder();
166 const offerTailMessage = (raw: Uint8Array) => {
167 const data: TailEventMessage = JSON.parse(decoder.decode(raw));
168 const eventTs = new Date(data.eventTimestamp ?? Date.now());
169
170 if (data.event && "request" in data.event) {
171 const reqEvent = data.event;
172 const pathname = (() => {
173 try {
174 return new URL(reqEvent.request.url).pathname;
175 } catch {
176 return reqEvent.request.url;
177 }
178 })();
179 const status = reqEvent.response?.status ?? 500;
180 Queue.offerUnsafe(queue, {
181 timestamp: eventTs,
182 message: `${reqEvent.request.method} ${pathname} > ${status} (cpu: ${Math.round(data.cpuTime)}ms, wall: ${Math.round(data.wallTime)}ms)`,
183 });
184 }
185
186 for (const log of data.logs) {
187 const msg = log.message.join(" ");
188 Queue.offerUnsafe(queue, {
189 timestamp: new Date(log.timestamp),
190 message: log.level === "log" ? msg : `${log.level}: ${msg}`,
191 });
192 }
193
194 for (const exception of data.exceptions) {
195 Queue.offerUnsafe(queue, {
196 timestamp: new Date(exception.timestamp),
197 message: `${exception.name} ${exception.message}\n${exception.stack}`,
198 });
199 }
200 };
201
202 yield* Socket.toStream(socket).pipe(
203 Stream.runForEach((raw) => Effect.sync(() => offerTailMessage(raw))),
204 Effect.catchIf(
205 (error) =>
206 Socket.isSocketError(error) &&
207 error.reason._tag === "SocketCloseError" &&
208 (error.reason.code === 1000 || error.reason.code === 1006),
209 () => Effect.void,
210 ),
211 Effect.ensuring(
212 Effect.all([
213 deleteScriptTail({
214 scriptName: opts.scriptName,
215 id: tailId,
216 accountId: opts.accountId,
217 }).pipe(Effect.ignore),
218 Queue.end(queue),
219 ]),
220 ),
221 Effect.scoped,
222 Effect.ignore,
223 Effect.forkChild(),
224 );
225
226 return Stream.fromQueue(queue);
227 });
228
229 return Stream.unwrap(runTailSession).pipe(Stream.repeat(Schedule.spaced("1 second")));
230 };
231
232 const tailStream = (opts: { accountId: string; filters: TelemetryFilter[] }) => {
233 const poll = (since: number): Stream.Stream<LogLine, any> =>
234 Stream.unwrap(
235 Effect.gen(function* () {
236 yield* Effect.sleep("2 seconds");
237 const now = Date.now();
238
239 const response = yield* explainMissingObservabilityScope(
240 queryTelemetry({
241 accountId: opts.accountId,
242 queryId: "events",
243 view: "events",
244 timeframe: { from: since, to: now },
245 limit: 100,
246 parameters: {
247 filters: opts.filters,
248 orderBy: { value: "timestamp", order: "asc" },
249 },
250 }),
251 );
252
253 const lines = parseEvents(response);
254 const nextSince =
255 lines.length > 0 ? Math.max(...lines.map((l) => l.timestamp.getTime())) + 1 : since;
256
257 return Stream.concat(Stream.fromIterable(lines), poll(nextSince));
258 }),
259 );
260
261 return poll(Date.now());
262 };
263
264 return { queryLogs, tailScript, tailStream };
265 });