Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/app/api/expansions/[id]/run/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { RunExpansionSchema, DirectionSchema } from "@/lib/validation";
import { getImageGenProvider } from "@/lib/image-gen";
import { getUserIdFromSession } from "@/lib/auth";
import { emitRoomEvent } from "@/lib/sse-emitter";
import { logger } from "@/lib/logger";
import type { Direction } from "@/types";

export async function POST(
Expand Down Expand Up @@ -123,7 +124,7 @@ export async function POST(
}),
]);
emitRoomEvent(expansion.roomId, "room_update");
console.error("Image generation failed:", err instanceof Error ? err.message : String(err));
logger.error("Image generation failed:", err);
return serverError("Image generation failed");
}
}
3 changes: 2 additions & 1 deletion src/app/api/rooms/[id]/generate-initial/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { notFound, unauthorized, forbidden, conflict } from "@/lib/errors";
import { getUserIdFromSession } from "@/lib/auth";
import { getImageGenProvider } from "@/lib/image-gen";
import { emitRoomEvent } from "@/lib/sse-emitter";
import { logger } from "@/lib/logger";
import type { PromptJson } from "@/types";

/** GENERATING 状態のまま放置を許容する最大時間(5分) */
Expand Down Expand Up @@ -80,7 +81,7 @@ export async function POST(

return NextResponse.json({ status: "DONE", imageUrl: result.imagePath });
} catch (error) {
console.error("Initial tile generation failed:", error instanceof Error ? error.message : String(error));
logger.error("Initial tile generation failed:", error);

// 失敗: status FAILED
await prisma.room.update({
Expand Down
5 changes: 3 additions & 2 deletions src/hooks/use-room.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useState, useEffect, useCallback, useRef } from "react";
import { logger } from "@/lib/logger";
import type { RoomDetail } from "@/types";

const FALLBACK_POLL_INTERVAL = 3_000;
Expand All @@ -21,7 +22,7 @@ export function useRoom(roomId: string) {
setError(errData.message || "Failed to fetch room");
}
} catch (err) {
console.error("Failed to fetch room:", err instanceof Error ? err.message : String(err));
logger.error("Failed to fetch room:", err);
setError("Network error");
} finally {
setLoading(false);
Expand Down Expand Up @@ -56,7 +57,7 @@ export function useRoom(roomId: string) {

eventSource.onerror = () => {
if (!pollTimer) {
console.warn("SSE connection lost, falling back to polling");
logger.warn("SSE connection lost, falling back to polling");
pollTimer = setInterval(fetchRoom, FALLBACK_POLL_INTERVAL);
}
};
Expand Down
3 changes: 2 additions & 1 deletion src/hooks/use-user.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useState, useEffect, useCallback } from "react";
import { logger } from "@/lib/logger";

export interface User {
id: string;
Expand All @@ -19,7 +20,7 @@ export function useUser() {
setUser(null);
}
} catch (error) {
console.error("Failed to fetch user:", error instanceof Error ? error.message : String(error));
logger.error("Failed to fetch user:", error);
setUser(null);
} finally {
setLoading(false);
Expand Down
22 changes: 6 additions & 16 deletions src/lib/auto-adopt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { createId } from "@paralleldrive/cuid2";
import { Prisma } from "@prisma/client";
import { prisma } from "./prisma";
import { emitRoomEvent } from "./sse-emitter";
import { logger } from "./logger";

// DONE 状態のまま放置された Expansion を自動決定するまでの時間 (ms)
// デフォルト 1 分。AUTO_ADOPT_AFTER_MS 環境変数で変更可能。
Expand Down Expand Up @@ -115,9 +116,9 @@ export async function autoAdoptStaleExpansions(roomId: string): Promise<void> {
} catch (err) {
// バッチ処理が失敗した場合(例: ユニーク制約違反)、
// 堅牢性のために従来の逐次処理にフォールバックする
console.warn(
logger.warn(
`[auto-adopt] Batched transaction failed, falling back to sequential:`,
err instanceof Error ? err.message : String(err)
err
);
await autoAdoptSequentialFallback(byCell, roomId);
}
Expand Down Expand Up @@ -218,22 +219,14 @@ async function autoAdoptSequentialFallback(
]);
changed = true;
} catch (err) {
console.warn(
`[auto-adopt] expansion ${pick.id} fallback failed:`,
err instanceof Error ? err.message : String(err)
);
logger.warn(`[auto-adopt] expansion ${pick.id} fallback failed:`, err);
// P2: リトライループ防止 — 失敗した全候補を REJECTED に更新
await prisma.expansion
.updateMany({
where: { id: { in: candidates.map((e) => e.id) }, status: "DONE" },
data: { status: "REJECTED" },
})
.catch((e2) =>
console.warn(
`[auto-adopt] fallback reject failed:`,
e2 instanceof Error ? e2.message : String(e2)
)
);
.catch((e2) => logger.warn(`[auto-adopt] fallback reject failed:`, e2));
}
} else {
// 全却下
Expand All @@ -253,10 +246,7 @@ async function autoAdoptSequentialFallback(
]);
changed = true;
} catch (err) {
console.warn(
`[auto-adopt] all-reject for cell failed:`,
err instanceof Error ? err.message : String(err)
);
logger.warn(`[auto-adopt] all-reject for cell failed:`, err);
}
}
}
Expand Down
24 changes: 24 additions & 0 deletions src/lib/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* Centralized logger.
* Error objects output stack trace (or message if unavailable) for debuggability,
* while preventing raw Error objects from being passed to console methods.
*/

const formatArg = (arg: unknown): unknown => {
if (arg instanceof Error) {
return arg.stack || arg.message;
}
return arg;
};
Comment on lines +7 to +12

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The current formatArg implementation only sanitizes top-level Error objects. If an Error object is nested within another object, it will be logged along with its stack trace, which could leak sensitive information. This doesn't fully meet the security goal of preventing accidental exposure of sensitive data.

To make the logger more robust, I suggest implementing a recursive sanitization function that traverses nested objects and arrays, sanitizes any Error instances it finds, and handles circular references.

const formatArg = (arg: unknown): unknown => {
  const sanitize = (value: unknown, seen: WeakSet<object>): unknown => {
    if (value instanceof Error) {
      return value.message;
    }

    if (typeof value !== "object" || value === null) {
      return value;
    }

    if (seen.has(value)) {
      return "[Circular]";
    }
    seen.add(value);

    if (Array.isArray(value)) {
      return value.map((item) => sanitize(item, seen));
    }

    const sanitizedObject: { [key: string]: unknown } = {};
    for (const key of Object.keys(value)) {
      sanitizedObject[key] = sanitize((value as Record<string, unknown>)[key], seen);
    }
    return sanitizedObject;
  };

  return sanitize(arg, new WeakSet());
};


export const logger = {
info: (...args: unknown[]) => {
console.info(...args.map(formatArg));
},
warn: (...args: unknown[]) => {
console.warn(...args.map(formatArg));
},
error: (...args: unknown[]) => {
console.error(...args.map(formatArg));
},
};
Loading