chord: Optional gRPC session recording system to improve observability (#5999)
chord: Optional gRPC session recording system to improve observability
This commit is contained in:
1 parent
d69fb10cfd
commit
291287c8e4
9 files changed
+483
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"claude-dev": patch
|
||||
---
|
||||
|
||||
Adding a grpc recording class with its builder
|
||||
Vendored
+36
@@ -120,6 +120,42 @@
|
||||
},
|
||||
"console": "integratedTerminal",
|
||||
"internalConsoleOptions": "neverOpen"
|
||||
},
|
||||
{
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"name": "Debug Current Test File",
|
||||
"skipFiles": [
|
||||
"<node_internals>/**"
|
||||
],
|
||||
"sourceMaps": true,
|
||||
"resolveSourceMapLocations": [
|
||||
"${workspaceFolder}/**",
|
||||
"!**/node_modules/**"
|
||||
],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"runtimeExecutable": "npx",
|
||||
"runtimeArgs": [
|
||||
"mocha"
|
||||
],
|
||||
"args": [
|
||||
"--require",
|
||||
"ts-node/register",
|
||||
"--require",
|
||||
"source-map-support/register",
|
||||
"--require",
|
||||
"./src/test/requires.ts",
|
||||
"--exit",
|
||||
"${file}"
|
||||
],
|
||||
"env": {
|
||||
"TS_NODE_PROJECT": "./tsconfig.unit-test.json",
|
||||
"NODE_ENV": "test",
|
||||
"IS_DEV": "true",
|
||||
"CLINE_ENVIRONMENT": "local"
|
||||
},
|
||||
"console": "integratedTerminal",
|
||||
"internalConsoleOptions": "openOnSessionStart"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { GrpcRecorder, GrpcRecorderNoops, IRecorder } from "@/core/controller/grpc-recorder/grpc-recorder"
|
||||
import { LogFileHandler, LogFileHandlerNoops } from "@/core/controller/grpc-recorder/log-file-handler"
|
||||
|
||||
/**
|
||||
* A builder class for constructing a gRPC recorder instance.
|
||||
*
|
||||
* This class follows the Builder pattern, allowing consumers
|
||||
* to configure logging behavior and control whether recording
|
||||
* is enabled or disabled before creating a final `IRecorder`.
|
||||
*/
|
||||
export class GrpcRecorderBuilder {
|
||||
private fileHandler: LogFileHandler | null = null
|
||||
private enabled: boolean = true
|
||||
|
||||
public withLogFileHandler(handler: LogFileHandler): this {
|
||||
this.fileHandler = handler
|
||||
return this
|
||||
}
|
||||
|
||||
public enableIf(condition: boolean): this {
|
||||
this.enabled = condition
|
||||
return this
|
||||
}
|
||||
|
||||
public build(): IRecorder {
|
||||
if (!this.enabled) {
|
||||
return new GrpcRecorderNoops()
|
||||
}
|
||||
|
||||
const handler = this.fileHandler ?? new LogFileHandlerNoops()
|
||||
return new GrpcRecorder(handler)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { GrpcRecorder, IRecorder } from "@core/controller/grpc-recorder/grpc-recorder"
|
||||
import { expect } from "chai"
|
||||
import { ExtensionMessage } from "@/shared/ExtensionMessage"
|
||||
import { GrpcRequest } from "@/shared/WebviewMessage"
|
||||
|
||||
describe("grpc-recorder", () => {
|
||||
let recorder: IRecorder
|
||||
|
||||
before(async () => {
|
||||
recorder = GrpcRecorder.builder().enableIf(true).build()
|
||||
})
|
||||
|
||||
describe("GrpcRecorder", () => {
|
||||
it("matches multiple request, response and stats", async () => {
|
||||
interface UseCase {
|
||||
request: GrpcRequest
|
||||
response: ExtensionMessage["grpc_response"]
|
||||
expectedStatus: string
|
||||
}
|
||||
const requestResponseUseCases: UseCase[] = [
|
||||
{
|
||||
request: {
|
||||
service: "the-service",
|
||||
method: "the-method",
|
||||
message: "the-message",
|
||||
request_id: "request-id-1",
|
||||
is_streaming: false,
|
||||
},
|
||||
response: {
|
||||
request_id: "request-id-1",
|
||||
message: "the-message-response",
|
||||
error: "",
|
||||
},
|
||||
expectedStatus: "completed",
|
||||
},
|
||||
{
|
||||
request: {
|
||||
service: "streaming-service",
|
||||
method: "stream-method",
|
||||
message: { data: "streaming-data", count: 42 },
|
||||
request_id: "request-id-2",
|
||||
is_streaming: true,
|
||||
},
|
||||
response: {
|
||||
request_id: "request-id-2",
|
||||
message: { streamData: "chunk-1" },
|
||||
error: "",
|
||||
is_streaming: true,
|
||||
sequence_number: 1,
|
||||
},
|
||||
expectedStatus: "completed",
|
||||
},
|
||||
{
|
||||
request: {
|
||||
service: "another-service",
|
||||
method: "another-method",
|
||||
message: { complex: { nested: "object", array: [1, 2, 3] } },
|
||||
request_id: "request-id-3",
|
||||
is_streaming: false,
|
||||
},
|
||||
response: {
|
||||
request_id: "request-id-3",
|
||||
message: "",
|
||||
error: "Something went wrong",
|
||||
},
|
||||
expectedStatus: "error",
|
||||
},
|
||||
]
|
||||
|
||||
const initialExpectedStatus = "pending"
|
||||
|
||||
requestResponseUseCases.forEach((us: UseCase, index: number) => {
|
||||
recorder.recordRequest(us.request)
|
||||
|
||||
let sessionLog = recorder.getSessionLog()
|
||||
expect(sessionLog.entries).length(index + 1)
|
||||
|
||||
expect(sessionLog.entries[index]).to.include({
|
||||
service: us.request.service,
|
||||
method: us.request.method,
|
||||
isStreaming: us.request.is_streaming,
|
||||
requestId: us.request.request_id,
|
||||
status: initialExpectedStatus,
|
||||
})
|
||||
|
||||
if (us.response) {
|
||||
recorder.recordResponse(us.request.request_id, us.response)
|
||||
}
|
||||
sessionLog = recorder.getSessionLog()
|
||||
|
||||
expect(sessionLog.entries[index].status).equal(us.expectedStatus)
|
||||
expect(sessionLog.entries[index].response).to.deep.include({
|
||||
error: us.response?.error,
|
||||
})
|
||||
})
|
||||
|
||||
const sessionLog = recorder.getSessionLog()
|
||||
expect(sessionLog.stats).to.include({
|
||||
totalRequests: 3,
|
||||
pendingRequests: 0,
|
||||
completedRequests: 2,
|
||||
errorRequests: 1,
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,179 @@
|
||||
import { GrpcResponse } from "@shared/ExtensionMessage"
|
||||
import { GrpcRequest } from "@shared/WebviewMessage"
|
||||
import { GrpcRecorderBuilder } from "@/core/controller/grpc-recorder/grpc-recorder.builder"
|
||||
import { ILogFileHandler } from "@/core/controller/grpc-recorder/log-file-handler"
|
||||
import { GrpcLogEntry, GrpcSessionLog, SessionStats } from "@/core/controller/grpc-recorder/types"
|
||||
|
||||
export class GrpcRecorderNoops implements IRecorder {
|
||||
recordRequest(_request: GrpcRequest): void {}
|
||||
recordResponse(_requestId: string, _response: GrpcResponse): void {}
|
||||
recordError(_requestId: string, _error: string): void {}
|
||||
getSessionLog(): GrpcSessionLog {
|
||||
return {
|
||||
startTime: "",
|
||||
entries: [],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface IRecorder {
|
||||
recordRequest(request: GrpcRequest): void
|
||||
recordResponse(requestId: string, response: GrpcResponse): void
|
||||
recordError(requestId: string, error: string): void
|
||||
getSessionLog(): GrpcSessionLog
|
||||
}
|
||||
|
||||
/**
|
||||
* Default implementation of a gRPC recorder.
|
||||
*
|
||||
* Responsibilities:
|
||||
* - Records requests, responses, and errors.
|
||||
* - Tracks request/response lifecycle, including duration and status.
|
||||
* - Maintains a session log of all recorded entries.
|
||||
* - Persists logs asynchronously through a file handler.
|
||||
*/
|
||||
export class GrpcRecorder implements IRecorder {
|
||||
private sessionLog: GrpcSessionLog
|
||||
private pendingRequests: Map<string, { entry: GrpcLogEntry; startTime: number }> = new Map()
|
||||
|
||||
constructor(private fileHandler: ILogFileHandler) {
|
||||
this.sessionLog = {
|
||||
startTime: new Date().toISOString(),
|
||||
entries: [],
|
||||
}
|
||||
|
||||
this.fileHandler.initialize(this.sessionLog).catch((error) => {
|
||||
console.error("Failed to initialize gRPC log file:", error)
|
||||
})
|
||||
}
|
||||
|
||||
public static builder(): GrpcRecorderBuilder {
|
||||
return new GrpcRecorderBuilder()
|
||||
}
|
||||
|
||||
/**
|
||||
* Records a gRPC request.
|
||||
*
|
||||
* - Stores the request as a "pending" log entry.
|
||||
* - Tracks the request start time for later duration calculation.
|
||||
* - Persists the log asynchronously.
|
||||
*
|
||||
* @param request - The incoming gRPC request.
|
||||
*/
|
||||
public recordRequest(request: GrpcRequest): void {
|
||||
const entry: GrpcLogEntry = {
|
||||
requestId: request.request_id,
|
||||
service: request.service,
|
||||
method: request.method,
|
||||
isStreaming: request.is_streaming || false,
|
||||
request: {
|
||||
message: request.message,
|
||||
},
|
||||
status: "pending",
|
||||
}
|
||||
|
||||
this.pendingRequests.set(request.request_id, {
|
||||
entry,
|
||||
startTime: Date.now(),
|
||||
})
|
||||
|
||||
this.sessionLog.entries.push(entry)
|
||||
this.flushLogAsync()
|
||||
}
|
||||
|
||||
public getSessionLog(): GrpcSessionLog {
|
||||
return this.sessionLog
|
||||
}
|
||||
|
||||
/**
|
||||
* Records a gRPC response for a given request.
|
||||
*
|
||||
* - Looks up the pending request entry.
|
||||
* - Updates the entry with response data, status, and duration.
|
||||
* - Removes the request from pending if it's not streaming.
|
||||
* - Recomputes session stats.
|
||||
* - Persists the log asynchronously.
|
||||
*
|
||||
* @param requestId - The ID of the request being responded to.
|
||||
* @param response - The corresponding gRPC response.
|
||||
*/
|
||||
public recordResponse(requestId: string, response: GrpcResponse): void {
|
||||
const pendingRequest = this.pendingRequests.get(requestId)
|
||||
if (!pendingRequest) {
|
||||
console.warn(`No pending request found for response with ID: ${requestId}`)
|
||||
return
|
||||
}
|
||||
|
||||
const { entry, startTime } = pendingRequest
|
||||
|
||||
entry.response = {
|
||||
message: response?.message ? response.message : undefined,
|
||||
error: response?.error,
|
||||
isStreaming: response?.is_streaming,
|
||||
sequenceNumber: response?.sequence_number,
|
||||
}
|
||||
|
||||
entry.duration = Date.now() - startTime
|
||||
entry.status = response?.error ? "error" : "completed"
|
||||
|
||||
if (!response?.is_streaming) {
|
||||
this.pendingRequests.delete(requestId)
|
||||
}
|
||||
|
||||
this.sessionLog.stats = this.getStats()
|
||||
|
||||
this.flushLogAsync()
|
||||
}
|
||||
|
||||
/**
|
||||
* Records an error for a given request.
|
||||
*
|
||||
* - Marks the request as failed.
|
||||
* - Records the error message and request duration.
|
||||
* - Removes it from the pending requests.
|
||||
* - Persists the log asynchronously.
|
||||
*
|
||||
* @param requestId - The ID of the request that errored.
|
||||
* @param error - Error message.
|
||||
*/
|
||||
public recordError(requestId: string, error: string): void {
|
||||
const pendingRequest = this.pendingRequests.get(requestId)
|
||||
if (!pendingRequest) {
|
||||
console.warn(`No pending request found for error with ID: ${requestId}`)
|
||||
return
|
||||
}
|
||||
|
||||
const { entry, startTime } = pendingRequest
|
||||
|
||||
entry.response = {
|
||||
error: error,
|
||||
}
|
||||
entry.duration = Date.now() - startTime
|
||||
entry.status = "error"
|
||||
|
||||
this.pendingRequests.delete(requestId)
|
||||
this.flushLogAsync()
|
||||
}
|
||||
|
||||
private flushLogAsync(): void {
|
||||
setImmediate(() => {
|
||||
this.fileHandler.write(this.sessionLog).catch((error) => {
|
||||
console.error("Failed to flush gRPC log:", error)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
public getStats(): SessionStats {
|
||||
const totalRequests = this.sessionLog.entries.length
|
||||
const pendingRequests = this.sessionLog.entries.filter((e) => e.status === "pending").length
|
||||
const completedRequests = this.sessionLog.entries.filter((e) => e.status === "completed").length
|
||||
const errorRequests = this.sessionLog.entries.filter((e) => e.status === "error").length
|
||||
|
||||
return {
|
||||
totalRequests,
|
||||
pendingRequests,
|
||||
completedRequests,
|
||||
errorRequests,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { expect } from "chai"
|
||||
import { before, describe, it } from "mocha"
|
||||
import { LogFileHandler } from "@/core/controller/grpc-recorder/log-file-handler"
|
||||
|
||||
describe("log-file-handler", () => {
|
||||
let logHandler: LogFileHandler
|
||||
|
||||
before(async () => {
|
||||
logHandler = new LogFileHandler()
|
||||
expect(logHandler.getFilePath()).not.empty
|
||||
})
|
||||
|
||||
describe("LogFileHandler", () => {
|
||||
it("returns file name with timestamp when env var not set", () => {
|
||||
const result = logHandler.getFileName()
|
||||
expect(result).to.contains("grpc_recorded_session")
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,57 @@
|
||||
import { writeFile } from "@utils/fs"
|
||||
import fs from "fs/promises"
|
||||
import * as path from "path"
|
||||
import { GrpcSessionLog } from "@/core/controller/grpc-recorder/types"
|
||||
|
||||
const LOG_FILE_PREFIX = "grpc_recorded_session"
|
||||
|
||||
export class LogFileHandlerNoops implements ILogFileHandler {
|
||||
async initialize(_initialData: GrpcSessionLog): Promise<void> {}
|
||||
async write(_sessionLog: GrpcSessionLog): Promise<void> {}
|
||||
}
|
||||
|
||||
export interface ILogFileHandler {
|
||||
initialize(initialData: GrpcSessionLog): Promise<void>
|
||||
write(sessionLog: GrpcSessionLog): Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* Default implementation of `ILogFileHandler` that persists logs to disk.
|
||||
*
|
||||
* - Creates a log file inside the workspace `tests/specs` folder.
|
||||
* - Uses a timestamped filename by default, unless overridden by an env var.
|
||||
* - Saves logs in JSON format.
|
||||
*/
|
||||
export class LogFileHandler implements ILogFileHandler {
|
||||
private logFilePath: string
|
||||
|
||||
constructor() {
|
||||
const fileName = this.getFileName()
|
||||
const workspaceFolder = process.env.DEV_WORKSPACE_FOLDER ?? process.cwd()
|
||||
const folderPath = path.join(workspaceFolder, "tests", "specs")
|
||||
this.logFilePath = path.join(folderPath, fileName)
|
||||
}
|
||||
|
||||
public getFilePath(): string {
|
||||
return this.logFilePath
|
||||
}
|
||||
|
||||
public getFileName(): string {
|
||||
const envFileName = path.basename(process.env.GRPC_RECORDER_FILE_NAME || "").replace(/[^a-zA-Z0-9-_]/g, "_")
|
||||
if (envFileName && envFileName.trim().length > 0) {
|
||||
return `${LOG_FILE_PREFIX}_${envFileName}.json`
|
||||
}
|
||||
|
||||
const timestamp = new Date().toISOString().replace(/[:.]/g, "-")
|
||||
return `${LOG_FILE_PREFIX}_${timestamp}.json`
|
||||
}
|
||||
|
||||
public async initialize(initialData: GrpcSessionLog): Promise<void> {
|
||||
await fs.mkdir(path.dirname(this.logFilePath), { recursive: true })
|
||||
await writeFile(this.logFilePath, JSON.stringify(initialData, null, 2), "utf8")
|
||||
}
|
||||
|
||||
public async write(sessionLog: GrpcSessionLog): Promise<void> {
|
||||
await writeFile(this.logFilePath, JSON.stringify(sessionLog, null, 2), "utf8")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
export interface GrpcLogEntry {
|
||||
requestId: string
|
||||
service: string
|
||||
method: string
|
||||
isStreaming: boolean
|
||||
request: {
|
||||
message: any
|
||||
}
|
||||
response?: {
|
||||
message?: any
|
||||
error?: string
|
||||
isStreaming?: boolean
|
||||
sequenceNumber?: number
|
||||
}
|
||||
duration?: number
|
||||
status: "pending" | "completed" | "error"
|
||||
}
|
||||
|
||||
export interface SessionStats {
|
||||
totalRequests: number
|
||||
pendingRequests: number
|
||||
completedRequests: number
|
||||
errorRequests: number
|
||||
}
|
||||
|
||||
export interface GrpcSessionLog {
|
||||
startTime: string
|
||||
stats?: SessionStats
|
||||
entries: GrpcLogEntry[]
|
||||
}
|
||||
@@ -35,6 +35,22 @@ export class E2ETestHelper {
|
||||
return label ? path.join(testDir, label) : testDir
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a filename for gRPC recorder logs based on test information
|
||||
* @param testTitle The title of the test
|
||||
* @param projectName The name of the test project (optional)
|
||||
* @returns A sanitized filename suitable for gRPC recorder logs
|
||||
*/
|
||||
public static generateTestFileName(testTitle: string, projectName?: string): string {
|
||||
// Create a base name from the test title
|
||||
const baseName = E2ETestHelper.escapeToPath(testTitle)
|
||||
|
||||
// Add project name if provided and different from default
|
||||
const projectSuffix = projectName && projectName !== "e2e tests" ? `_${E2ETestHelper.escapeToPath(projectName)}` : ""
|
||||
|
||||
return `${baseName}${projectSuffix}`
|
||||
}
|
||||
|
||||
public static async waitUntil(predicate: () => boolean | Promise<boolean>, maxDelay = 5000): Promise<void> {
|
||||
let delay = 10
|
||||
const start = Date.now()
|
||||
@@ -220,6 +236,8 @@ export const e2e = test
|
||||
TEMP_PROFILE: "true",
|
||||
E2E_TEST: "true",
|
||||
CLINE_ENVIRONMENT: "local",
|
||||
GRPC_RECORDER_FILE_NAME: E2ETestHelper.generateTestFileName(testInfo.title, testInfo.project.name),
|
||||
// GRPC_RECORDER_ENABLED: "true",
|
||||
// IS_DEV: "true",
|
||||
// DEV_WORKSPACE_FOLDER: E2ETestHelper.CODEBASE_ROOT_DIR,
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user