Skip to content
Closed
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
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ OPENAI_API_KEY=
OPENAI_STT_MODEL=
# Optional. Defaults to gpt-5.4-mini.
OPENAI_EVALUATION_MODEL=
PROCESS_GRAMMAR_AUDIO_SECRET=
PROCESS_ANALYSIS_SECRET=
ENABLE_TEST_ANALYSIS_PAGE=
ALLOW_UNAUTHENTICATED_PROCESS_ANALYSIS=
Expand Down
12 changes: 11 additions & 1 deletion docs/operations/structured-logging.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Node 서버는 Pino JSON을 stdout으로 출력한다. 업무 서비스는 `Reco
TEST_LOGS=1 npm test -- observeOperation --runInBand
```

시작과 종료 이벤트는 같은 operationId를 가진다. 실패 이벤트에는 오류 전문을 넣지 않는다.
시작과 종료 이벤트는 같은 operationId를 가진다. 실패 이벤트에는 오류 전문을 넣지 않는다. 허용된 오류 코드·HTTP 상태·OpenAI request ID·검증 필드 경로만 `error`에 기록한다.
로그 수집 실패는 업무 결과를 변경하지 않는다. 로그는 감사 원장이나 DB 정합성의 근거가 아니다.
DB 상태와 실제 저장 횟수는 통합 테스트에서 별도로 검증해야 한다.

Expand Down Expand Up @@ -52,3 +52,13 @@ operationId로 개별 실행을 구분한다. 클라이언트는 `recording.star
`recording.reset`을 브라우저 콘솔에 JSON으로 출력한다. 녹음 시작 취소는 `canceled`로
기록한다. 브라우저 로그의 서버 전송 및 SigNoz 연결은 아직 구현하지 않았다.
음성, 전사 전문, 사용자 토큰, 서명 URL은 로그에 포함하지 않는다.

## 예문·음성 오류 추적

- 브라우저 POST 200은 Server Action의 전송 완료다. 업무 성공은 반환값의 `ok`로 판단한다.
- 화면의 **문의 번호**를 서버 JSON 로그의 `operationId`와 대조한다.
- `grammar.examples.generate` / `grammar.examples.direct-reading`: `stage`가 `note.load`, `profile.load`, `quota.check`, `ai.generate`, `ai.direct-reading`, `output.validate` 중 실패 위치를 나타낸다.
- `grammar.audio.status` / `grammar.audio.retry` / `grammar.audio.prepare`: RPC 오류와 worker 실행 요청 오류를 기록한다. worker는 Edge Function 로그의 `jobId`, `stage`로 추적한다.
- Supabase Logs에서 같은 시각의 API Gateway/PostgREST·Storage·Edge Function 로그를 선택한다. `PGRST202`는 RPC 조회 실패, `PGRST205`는 테이블 조회 실패 여부를 먼저 확인한다.
- `npm run dev 2>&1 | tee /tmp/echo-server.log`로 실행한 뒤 `rg '<문의 번호>' /tmp/echo-server.log`로 검색한다. 기존 실행 중인 서버는 종료한 후 이 명령으로 다시 실행한다.
- 원문·AI 응답 전문·토큰·Storage 경로는 로그나 오류 팝업에 넣지 않는다. 자동 상태 조회는 인라인 안내만, 수동 재조회 실패는 팝업과 문의 번호를 표시한다.
4 changes: 4 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,8 @@ export default tseslint.config(
},
},
eslintConfigPrettier,
{
files: ["src/shared/lib/logging/**/*.{ts,tsx}"],
rules: { "no-nested-ternary": "error" },
},
);
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,31 @@ export const GenerateFailure: Story = {
const canvas = within(canvasElement);

await userEvent.click(canvas.getByRole("button", { name: "문장 듣기" }));
await expect(canvas.getByRole("alert")).toHaveTextContent("음성 생성에 실패");
await expect(canvas.getByRole("alert")).toHaveTextContent("음성을 생성하지 못했습니다.");
await userEvent.click(canvas.getByRole("button", { name: "음성 다시 생성" }));
await expect(args.generate).toHaveBeenCalledTimes(2);
},
};

export const StoredReadFailure: Story = {
args: { input: { noteId: "note", sentenceId: "example", noteVersion: 1 } },
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
await userEvent.click(canvas.getByRole("button", { name: "문장 듣기" }));
await expect(canvas.getByRole("alert")).toHaveTextContent("준비된 음성을 불러오지 못했습니다");
await userEvent.click(canvas.getByRole("button", { name: "음성 다시 불러오기" }));
await expect(args.generate).toHaveBeenCalledTimes(2);
},
};

export const Loading: Story = {
args: {
input: { noteId: "note", sentenceId: "example", noteVersion: 1 },
generate: fn(() => new Promise(() => {})),
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await userEvent.click(canvas.getByRole("button", { name: "문장 듣기" }));
await expect(canvas.getByRole("button", { name: "음성 불러오는 중…" })).toBeDisabled();
},
};
4 changes: 3 additions & 1 deletion src/_storybook/features/grammar-exam/GrammarExam.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,9 @@ export const SaveFailure: Story = {

await userEvent.type(canvas.getByLabelText("영어로 작성해 주세요"), "My draft");
await userEvent.click(canvas.getByRole("button", { name: "임시 저장" }));
await expect(canvas.getByText("저장하지 못했습니다. 다시 시도해 주세요.")).toBeVisible();
await expect(
canvas.getByText("시험을 처리하지 못했습니다. 입력을 유지한 채 다시 시도해 주세요."),
).toBeVisible();
await expect(canvas.getByLabelText("영어로 작성해 주세요")).toHaveValue("My draft");
},
};
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import { QueryProvider } from "@/app/providers/QueryProvider";
import type { Meta, StoryObj } from "@storybook/nextjs-vite";
import { expect, fn, mocked, userEvent, waitFor, within } from "storybook/test";
import { GrammarAudioButton } from "@/features/grammar-audio";
import { ExampleAudioPreparation } from "@/features/grammar-example-generation/ui/ExampleAudioPreparation";
import type { AudioPreparationResult, ExampleAudioCommand } from "@/entities/grammar-audio";
import { ErrorPopupProvider, errorPopupManager } from "@/shared/lib/error-popup";
type Action = (input: ExampleAudioCommand) => Promise<AudioPreparationResult>;
const meta = {
decorators: [
(Story) => (
<QueryProvider>
<Story />
</QueryProvider>
),
],
title: "features/grammar-example-generation/ExampleAudioPreparation",
component: ExampleAudioPreparation,
args: {
noteId: "note",
sentenceId: "example",
read: fn<Action>(async () => ({
ok: true,
data: [{ sentenceId: "example", status: "queued" }],
})),
retry: fn<Action>(async () => ({
ok: true,
data: [{ sentenceId: "example", status: "queued" }],
})),
},
} satisfies Meta<typeof ExampleAudioPreparation>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Preparing: Story = {
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
await expect(canvas.getByRole("status")).toHaveTextContent("음성을 준비하고 있어요");
await expect(args.retry).not.toHaveBeenCalled();
},
};
export const SavedWithAudioFailure: Story = {
args: {
read: fn<Action>(async () => ({
ok: true,
data: [{ sentenceId: "example", status: "retryable" }],
})),
},
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
const retry = await canvas.findByRole("button", { name: "음성 준비 재시도" });
await expect(canvas.getByRole("status")).toHaveTextContent("예문은 저장됐어요");
await userEvent.tab();
await expect(retry).toHaveFocus();
await userEvent.keyboard("{Enter}");
await expect(args.retry).toHaveBeenCalledWith({ noteId: "note", sentenceIds: ["example"] });
},
};
export const Ready: Story = {
args: {
read: fn<Action>(async () => ({
ok: true,
data: [{ sentenceId: "example", status: "ready" }],
})),
children: <button>음성 재생</button>,
},
play: async ({ canvasElement, args }) => {
await expect(
await within(canvasElement).findByRole("button", { name: "음성 재생" }),
).toBeVisible();
await expect(args.retry).not.toHaveBeenCalled();
},
};

export const QuotaLimited: Story = {
args: {
read: fn<Action>(async () => ({
ok: true,
data: [{ sentenceId: "example", status: "retryable", code: "RATE_LIMITED" }],
})),
},
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
await expect(
await canvas.findByText("음성 생성 요청 한도에 도달했어요. 잠시 후 다시 시도해 주세요."),
).toBeVisible();
await expect(canvas.getByRole("button", { name: "음성 준비 재시도" })).toBeEnabled();
await expect(args.retry).not.toHaveBeenCalled();
},
};

export const StatusReadFailure: Story = {
args: {
read: fn<Action>(async () => ({ ok: false, code: "FAILED", operationId: "audio-read-test" })),
},
decorators: [
(Story) => (
<>
<Story />
<ErrorPopupProvider />
</>
),
],
beforeEach: () => {
errorPopupManager.close();
},
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
const body = within(canvasElement.ownerDocument.body);
const button = await canvas.findByRole("button", { name: "상태 다시 확인" });
await expect(body.queryByRole("alertdialog")).not.toBeInTheDocument();
let complete!: (value: AudioPreparationResult) => void;
mocked(args.read).mockImplementationOnce(
() =>
new Promise((resolve) => {
complete = resolve;
}),
);
await userEvent.click(button);
await expect(canvas.getByRole("button", { name: "확인 중…" })).toBeDisabled();
complete({ ok: false, code: "FAILED", operationId: "audio-read-test" });
const dialog = await body.findByRole("alertdialog");
await waitFor(() =>
expect(within(dialog).getByText("음성 상태를 확인하지 못했습니다")).toBeVisible(),
);
await expect(within(dialog).getByText(/문의 번호: audio-read-test/)).toBeVisible();
await userEvent.click(within(dialog).getByRole("button", { name: "확인" }));
await expect(await canvas.findByRole("button", { name: "상태 다시 확인" })).toBeEnabled();
await expect(args.retry).not.toHaveBeenCalled();
},
};

export const ReadyPlayer: Story = {
args: {
initial: { sentenceId: "example", status: "ready" },
read: fn<Action>(async () => ({
ok: true,
data: [{ sentenceId: "example", status: "ready" }],
})),
children: (
<GrammarAudioButton
input={{ noteId: "note", sentenceId: "example", noteVersion: 1 }}
generate={fn(async () => ({ ok: false as const, code: "GENERATION_FAILED" as const }))}
/>
),
},
};
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ const meta = {
save: fn<GrammarExampleManagerProps["save"]>(async () => ({
ok: true,
data: { ...note, version: 2 },
audioPreparation: [],
})),
onUpdated: fn(),
onBack: fn(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import type { Meta, StoryObj } from "@storybook/nextjs-vite";
import type { ComponentProps } from "react";

import { Button } from "@/shared/components/atomics/button/Button";

type NativeButtonProps = Extract<ComponentProps<typeof Button>, { asChild?: false }>;

const meta = {
title: "shared/components/atomics/button/Button",
component: Button,
Expand All @@ -25,11 +28,11 @@ const meta = {
</div>
),
],
} satisfies Meta<typeof Button>;
} satisfies Meta<NativeButtonProps>;

export default meta;

type Story = StoryObj<typeof meta>;
type Story = StoryObj<NativeButtonProps>;

export const Default: Story = {
args: {
Expand Down Expand Up @@ -124,3 +127,7 @@ export const AllSizes: Story = {
</div>
),
};

export const Loading: Story = {
args: { loading: true, children: "저장 중…" },
};
12 changes: 12 additions & 0 deletions src/_storybook/views/grammar-detail/GrammarDetail.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { QueryProvider } from "@/app/providers/QueryProvider";
import type { Meta, StoryObj } from "@storybook/nextjs-vite";
import { expect, fn, userEvent, within } from "storybook/test";
import { GrammarDetail } from "@/views/grammar-detail/ui/GrammarDetail";
Expand All @@ -9,6 +10,13 @@ import { GrammarExamplesSection } from "@/views/grammar-detail/ui/GrammarExample
const note = createEditorNote();

const meta = {
decorators: [
(Story) => (
<QueryProvider>
<Story />
</QueryProvider>
),
],
title: "views/grammar/NoteDetail",
component: GrammarDetail,
args: {
Expand Down Expand Up @@ -55,6 +63,10 @@ export const DirectReading: Story = {
note={{ ...note, examples: [createExampleCandidates()[0]] }}
manageButton={null}
generateAudio={fn()}
readAudioPreparation={async ({ sentenceIds }) => ({
ok: true,
data: sentenceIds.map((sentenceId) => ({ sentenceId, status: "ready" })),
})}
/>
),
},
Expand Down
Loading
Loading