Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AcpNativeLogging.ts

129 lines4.4 KB

1import type { ProviderDriverKind, ThreadId } from "@t3tools/contracts";
2import { causeErrorTag, errorTag } from "@t3tools/shared/observability";
3import * as Cause from "effect/Cause";
4import * as Crypto from "effect/Crypto";
5import * as DateTime from "effect/DateTime";
6import * as Effect from "effect/Effect";
7import type * as EffectAcpProtocol from "effect-acp/protocol";
8​
9import type { EventNdjsonLogger } from "../Layers/EventNdjsonLogger.ts";
10import type * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
11​
12function structuralMethod(value: string): string {
13 return value.length <= 128 && /^[A-Za-z][A-Za-z0-9._:/-]*$/.test(value) ? value : "unknown";
15​
16function summarizePayload(payload: unknown): Readonly<Record<string, unknown>> {
17 if (payload === null) return { valueType: "null" };
18 if (typeof payload === "string") {
19 return { valueType: "string", byteLength: new TextEncoder().encode(payload).byteLength };
20 }
21 if (payload instanceof Uint8Array) {
22 return { valueType: "bytes", byteLength: payload.byteLength };
23 }
24 if (Array.isArray(payload)) {
25 return { valueType: "array", itemCount: payload.length };
26 }
27 if (typeof payload !== "object") {
28 return { valueType: typeof payload };
29 }
30​
31 try {
32 const record = payload as Record<string, unknown>;
33 return {
34 valueType: "object",
35 fieldCount: Object.keys(record).length,
36 ...(typeof record._tag === "string" ? { messageTag: errorTag(record) } : {}),
37 ...(typeof record.tag === "string" ? { method: structuralMethod(record.tag) } : {}),
38 };
39 } catch {
40 return { valueType: "object" };
41 }
43​
44function formatRequestLogPayload(event: AcpSessionRuntime.AcpSessionRequestLogEvent) {
45 return {
46 method: structuralMethod(event.method),
47 status: event.status,
48 request: summarizePayload(event.payload),
49 ...(event.result !== undefined ? { result: summarizePayload(event.result) } : {}),
50 ...(event.cause !== undefined
51 ? {
52 errorTag: causeErrorTag(event.cause),
53 reasonCount: event.cause.reasons.length,
54 }
55 : {}),
56 };
58​
59function formatProtocolLogPayload(event: EffectAcpProtocol.AcpProtocolLogEvent) {
60 return {
61 direction: event.direction,
62 stage: event.stage,
63 payload: summarizePayload(event.payload),
64 };
66​
67export const makeAcpNativeLoggerFactory = Effect.fn("makeAcpNativeLoggerFactory")(function* () {
68 const crypto = yield* Crypto.Crypto;
69 return (input: {
70 readonly nativeEventLogger: EventNdjsonLogger | undefined;
71 readonly provider: ProviderDriverKind;
72 readonly threadId: ThreadId;
73 }): Pick<AcpSessionRuntime.AcpSessionRuntimeOptions, "requestLogger" | "protocolLogging"> => {
74 const writeNativeAcpLog = (logInput: {
75 readonly kind: "request" | "protocol";
76 readonly payload: unknown;
77 }) =>
78 Effect.gen(function* () {
79 if (!input.nativeEventLogger) return;
80 const observedAt = DateTime.formatIso(yield* DateTime.now);
81 yield* input.nativeEventLogger.write(
82 {
83 observedAt,
84 event: {
85 id: yield* crypto.randomUUIDv4,
86 kind: logInput.kind,
87 provider: input.provider,
88 createdAt: observedAt,
89 threadId: input.threadId,
90 payload: logInput.payload,
91 },
92 },
93 input.threadId,
94 );
95 }).pipe(
96 Effect.catchCause((cause) =>
97 Cause.hasInterrupts(cause)
98 ? Effect.interrupt
99 : Effect.logWarning("Failed to write native ACP event log.", {
100 errorTag: causeErrorTag(cause),
101 reasonCount: cause.reasons.length,
102 provider: input.provider,
103 threadId: input.threadId,
104 }),
105 ),
106 );
107​
108 return {
109 requestLogger: (event: AcpSessionRuntime.AcpSessionRequestLogEvent) =>
110 writeNativeAcpLog({
111 kind: "request",
112 payload: formatRequestLogPayload(event),
113 }),
114 ...(input.nativeEventLogger
115 ? {
116 protocolLogging: {
117 logIncoming: true,
118 logOutgoing: true,
119 logger: (event: EffectAcpProtocol.AcpProtocolLogEvent) =>
120 writeNativeAcpLog({
121 kind: "protocol",
122 payload: formatProtocolLogPayload(event),
123 }),
124 } satisfies NonNullable<AcpSessionRuntime.AcpSessionRuntimeOptions["protocolLogging"]>,
125 }
126 : {}),
127 };
128 };
129});