-
Notifications
You must be signed in to change notification settings - Fork 174
Enable client logs like server logs in sandbox #187
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| import { NextRequest, NextResponse } from 'next/server' | ||
| import { z } from 'zod' | ||
| import { db } from '@/lib/db/client' | ||
| import * as schema from '@/lib/db/schema' | ||
| import { eq, and, isNull } from 'drizzle-orm' | ||
| import { getServerSession } from '@/lib/session/get-server-session' | ||
| import { redactSensitiveInfo } from '@/lib/utils/logging' | ||
|
|
||
| const { tasks, logEntrySchema } = schema | ||
|
|
||
| // Schema for the request body | ||
| const clientLogsSchema = z.object({ | ||
| logs: z.array(logEntrySchema), | ||
| }) | ||
|
|
||
| /** | ||
| * POST /api/tasks/[taskId]/client-logs | ||
| * Append client-side logs to the task's log database | ||
| */ | ||
| export async function POST(request: NextRequest, { params }: { params: Promise<{ taskId: string }> }) { | ||
| try { | ||
| const session = await getServerSession() | ||
| if (!session?.user?.id) { | ||
| return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) | ||
| } | ||
|
|
||
| const { taskId } = await params | ||
|
|
||
| // Parse the request body | ||
| const body = await request.json() | ||
| const { logs } = clientLogsSchema.parse(body) | ||
|
|
||
| if (!logs || logs.length === 0) { | ||
| return NextResponse.json({ error: 'No logs provided' }, { status: 400 }) | ||
| } | ||
|
|
||
| // Get the task and verify ownership (exclude soft-deleted) | ||
| const [task] = await db | ||
| .select() | ||
| .from(tasks) | ||
| .where(and(eq(tasks.id, taskId), eq(tasks.userId, session.user.id), isNull(tasks.deletedAt))) | ||
| .limit(1) | ||
|
|
||
| if (!task) { | ||
| return NextResponse.json({ error: 'Task not found' }, { status: 404 }) | ||
| } | ||
|
|
||
| // Redact sensitive information from all log messages | ||
| const sanitizedLogs = logs.map((log) => ({ | ||
| ...log, | ||
| message: redactSensitiveInfo(log.message), | ||
| timestamp: log.timestamp || new Date(), | ||
| })) | ||
|
|
||
| // Append the client logs to the existing logs | ||
| const existingLogs = task.logs || [] | ||
| const updatedLogs = [...existingLogs, ...sanitizedLogs] | ||
|
|
||
| await db.update(tasks).set({ logs: updatedLogs, updatedAt: new Date() }).where(eq(tasks.id, taskId)) | ||
|
|
||
| return NextResponse.json({ success: true }) | ||
| } catch (error) { | ||
| console.error('Error appending client logs:', error) | ||
| return NextResponse.json({ error: 'Failed to append client logs' }, { status: 500 }) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| import { useEffect, useRef, useCallback } from 'react' | ||
| import { createClientLogger, ClientLogger } from '@/lib/utils/client-logger' | ||
|
|
||
| /** | ||
| * Hook that creates a client logger for a task and provides helper methods | ||
| * The logger automatically batches and sends logs to the server | ||
| */ | ||
| export function useClientLogger(taskId: string | null | undefined) { | ||
| const loggerRef = useRef<ClientLogger | null>(null) | ||
|
|
||
| // Create logger when taskId is available | ||
| useEffect(() => { | ||
| if (taskId && !loggerRef.current) { | ||
| loggerRef.current = createClientLogger(taskId) | ||
| } | ||
|
|
||
| // Cleanup: flush any pending logs when component unmounts | ||
| return () => { | ||
| if (loggerRef.current) { | ||
| loggerRef.current.flush() | ||
| } | ||
| } | ||
| }, [taskId]) | ||
|
|
||
| // Helper methods that safely call the logger | ||
| const info = useCallback( | ||
| (message: string) => { | ||
| if (loggerRef.current) { | ||
| loggerRef.current.info(message) | ||
| } | ||
| }, | ||
| [loggerRef], | ||
| ) | ||
|
|
||
| const command = useCallback( | ||
| (message: string) => { | ||
| if (loggerRef.current) { | ||
| loggerRef.current.command(message) | ||
| } | ||
| }, | ||
| [loggerRef], | ||
| ) | ||
|
|
||
| const error = useCallback( | ||
| (message: string) => { | ||
| if (loggerRef.current) { | ||
| loggerRef.current.error(message) | ||
| } | ||
| }, | ||
| [loggerRef], | ||
| ) | ||
|
|
||
| const success = useCallback( | ||
| (message: string) => { | ||
| if (loggerRef.current) { | ||
| loggerRef.current.success(message) | ||
| } | ||
| }, | ||
| [loggerRef], | ||
| ) | ||
|
|
||
| const flush = useCallback(() => { | ||
| if (loggerRef.current) { | ||
| loggerRef.current.flush() | ||
| } | ||
| }, [loggerRef]) | ||
|
|
||
| return { | ||
| info, | ||
| command, | ||
| error, | ||
| success, | ||
| flush, | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| /** | ||
| * Client-side logger that sends logs to the server for storage | ||
| * All logs are prefixed with [CLIENT] and stored in the task's log database | ||
| */ | ||
|
|
||
| import { LogEntry } from '@/lib/db/schema' | ||
|
|
||
| export class ClientLogger { | ||
| private taskId: string | ||
| private batchQueue: LogEntry[] = [] | ||
| private batchTimeout: NodeJS.Timeout | null = null | ||
| private readonly BATCH_DELAY = 500 // ms | ||
| private readonly MAX_BATCH_SIZE = 10 | ||
|
|
||
| constructor(taskId: string) { | ||
| this.taskId = taskId | ||
| } | ||
|
|
||
| /** | ||
| * Send logs to the server | ||
| */ | ||
| private async sendToServer(logs: LogEntry[]): Promise<void> { | ||
| try { | ||
| const response = await fetch(`/api/tasks/${this.taskId}/client-logs`, { | ||
| method: 'POST', | ||
| headers: { | ||
| 'Content-Type': 'application/json', | ||
| }, | ||
| body: JSON.stringify({ logs }), | ||
| }) | ||
|
|
||
| if (!response.ok) { | ||
| console.error('Failed to send client logs to server') | ||
| } | ||
| } catch (error) { | ||
| console.error('Error sending client logs:', error) | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Flush the batch queue immediately | ||
| */ | ||
| private flushBatch(): void { | ||
| if (this.batchTimeout) { | ||
| clearTimeout(this.batchTimeout) | ||
| this.batchTimeout = null | ||
| } | ||
|
|
||
| if (this.batchQueue.length > 0) { | ||
| const logsToSend = [...this.batchQueue] | ||
| this.batchQueue = [] | ||
| this.sendToServer(logsToSend) | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Add a log entry to the batch queue | ||
| */ | ||
| private enqueue(type: LogEntry['type'], message: string): void { | ||
| const logEntry: LogEntry = { | ||
| type, | ||
| message: `[CLIENT] ${message}`, | ||
| timestamp: new Date(), | ||
| } | ||
|
|
||
| this.batchQueue.push(logEntry) | ||
|
|
||
| // Flush immediately if batch size reached | ||
| if (this.batchQueue.length >= this.MAX_BATCH_SIZE) { | ||
| this.flushBatch() | ||
| return | ||
| } | ||
|
|
||
| // Otherwise, schedule a batch flush | ||
| if (this.batchTimeout) { | ||
| clearTimeout(this.batchTimeout) | ||
| } | ||
|
|
||
| this.batchTimeout = setTimeout(() => { | ||
| this.flushBatch() | ||
| }, this.BATCH_DELAY) | ||
| } | ||
|
|
||
| /** | ||
| * Log an info message | ||
| */ | ||
| info(message: string): void { | ||
| this.enqueue('info', message) | ||
| console.log(`[CLIENT] ${message}`) | ||
| } | ||
|
|
||
| /** | ||
| * Log a command | ||
| */ | ||
| command(message: string): void { | ||
| this.enqueue('command', message) | ||
| console.log(`[CLIENT] $ ${message}`) | ||
| } | ||
|
|
||
| /** | ||
| * Log an error message | ||
| */ | ||
| error(message: string): void { | ||
| this.enqueue('error', message) | ||
| console.error(`[CLIENT] ${message}`) | ||
| } | ||
|
|
||
| /** | ||
| * Log a success message | ||
| */ | ||
| success(message: string): void { | ||
| this.enqueue('success', message) | ||
| console.log(`[CLIENT] ✓ ${message}`) | ||
| } | ||
|
|
||
| /** | ||
| * Flush any pending logs immediately | ||
| */ | ||
| flush(): void { | ||
| this.flushBatch() | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Create a client logger instance for a specific task | ||
| */ | ||
| export function createClientLogger(taskId: string): ClientLogger { | ||
| return new ClientLogger(taskId) | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The hook returns a new object literal on every render, causing the object reference to change even though the contained functions are memoized. This will cause the
clientLoggerdependency intask-page-client.tsxto change on every render, leading to the "Task page loaded in browser" log being recorded multiple times instead of just once.View Details
📝 Patch Details
Analysis
Object reference changes on every render causes repeated logging in task-page-client
What fails:
useClientLogger()returns a new object literal on every render, causing theclientLoggerdependency intask-page-client.tsxto change reference every render, which triggers the useEffect to run repeatedly instead of once.How to reproduce:
This causes the "Task page loaded in browser" message to be logged to the server multiple times when the page loads, instead of just once as intended.
Expected behavior: Per React's useEffect dependency documentation, dependency arrays use reference equality. React's official guidance states that when an object needs to remain stable between renders to prevent Effects from firing excessively, it should be wrapped in useMemo.
Fix: Wrap the returned object in
useMemoto maintain referential equality across renders when the contained callback functions haven't changed:useMemoto importsuseMemoand dependencies[info, command, error, success, flush]loggerRef, the memoized object maintains identity across renders