From 56bcfcb934b39f1e61c775794932e80aeada8331 Mon Sep 17 00:00:00 2001 From: opficdev <162981733+opficdev@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:14:43 +0900 Subject: [PATCH 1/7] =?UTF-8?q?feat:=20=EA=B0=9C=EB=B0=9C=20=EB=AA=A9?= =?UTF-8?q?=ED=91=9C=20=EC=99=84=EB=A3=8C=20API=EC=99=80=20=EC=84=9C?= =?UTF-8?q?=EB=B2=84=20transaction=20=EC=99=84=EB=A3=8C=20=ED=8C=90?= =?UTF-8?q?=EC=A0=95=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- nestjs-api/src/app.module.test.ts | 10 + nestjs-api/src/app.module.ts | 2 + .../development-goals.controller.ts | 74 ++++++ .../development-goals.module.test.ts | 46 ++++ .../development-goals.module.ts | 14 ++ .../development-goals.repository.test.ts | 209 ++++++++++++++++ .../development-goals.repository.ts | 123 +++++++++ .../development-goals.service.test.ts | 236 ++++++++++++++++++ .../development-goals.service.ts | 146 +++++++++++ nestjs-api/test/development-goals.e2e.test.ts | 172 +++++++++++++ 10 files changed, 1032 insertions(+) create mode 100644 nestjs-api/src/development-goals/development-goals.controller.ts create mode 100644 nestjs-api/src/development-goals/development-goals.module.test.ts create mode 100644 nestjs-api/src/development-goals/development-goals.module.ts create mode 100644 nestjs-api/src/development-goals/development-goals.repository.test.ts create mode 100644 nestjs-api/src/development-goals/development-goals.repository.ts create mode 100644 nestjs-api/src/development-goals/development-goals.service.test.ts create mode 100644 nestjs-api/src/development-goals/development-goals.service.ts create mode 100644 nestjs-api/test/development-goals.e2e.test.ts diff --git a/nestjs-api/src/app.module.test.ts b/nestjs-api/src/app.module.test.ts index 031d59e..2cec620 100644 --- a/nestjs-api/src/app.module.test.ts +++ b/nestjs-api/src/app.module.test.ts @@ -17,6 +17,7 @@ import { AppleAuthenticationModule } from './apple/apple-authentication.module'; import { FirebaseAuthGuard } from './auth/firebase-auth.guard'; import { ApiExceptionFilter } from './common/api-exception.filter'; import { AppModule } from './app.module'; +import { DevelopmentGoalsModule } from './development-goals/development-goals.module'; import { GOOGLE_AUTHENTICATION_CONFIGURATION_TOKEN } from './google/google-authentication.configuration'; import { GitHubAuthenticationModule } from './github/github-authentication.module'; import { GoogleAuthenticationModule } from './google/google-authentication.module'; @@ -97,6 +98,15 @@ describe(AppModule.name, () => { expect(imports).toContain(TodosModule); }); + it('DevelopmentGoalsModule을 애플리케이션에 연결한다', () => { + const imports = Reflect.getMetadata( + MODULE_METADATA.IMPORTS, + AppModule, + ) as unknown[]; + + expect(imports).toContain(DevelopmentGoalsModule); + }); + it('AppleAuthenticationModule을 애플리케이션에 연결한다', () => { const imports = Reflect.getMetadata( MODULE_METADATA.IMPORTS, diff --git a/nestjs-api/src/app.module.ts b/nestjs-api/src/app.module.ts index c3a3fef..907011a 100644 --- a/nestjs-api/src/app.module.ts +++ b/nestjs-api/src/app.module.ts @@ -4,6 +4,7 @@ import { APP_FILTER, APP_GUARD } from '@nestjs/core'; import { AppleAuthenticationModule } from './apple/apple-authentication.module'; import { FirebaseAuthGuard } from './auth/firebase-auth.guard'; import { ApiExceptionFilter } from './common/api-exception.filter'; +import { DevelopmentGoalsModule } from './development-goals/development-goals.module'; import { FirebaseModule } from './firebase/firebase.module'; import { GitHubAuthenticationModule } from './github/github-authentication.module'; import { GoogleAuthenticationModule } from './google/google-authentication.module'; @@ -14,6 +15,7 @@ import { TodosModule } from './todos/todos.module'; @Module({ imports: [ AppleAuthenticationModule, + DevelopmentGoalsModule, FirebaseModule, GitHubAuthenticationModule, GoogleAuthenticationModule, diff --git a/nestjs-api/src/development-goals/development-goals.controller.ts b/nestjs-api/src/development-goals/development-goals.controller.ts new file mode 100644 index 0000000..205ee54 --- /dev/null +++ b/nestjs-api/src/development-goals/development-goals.controller.ts @@ -0,0 +1,74 @@ +import { + Controller, + HttpCode, + HttpStatus, + Param, + Post, + Req, +} from '@nestjs/common'; + +import { type FirebaseAuthenticatedRequest } from '../auth/firebase-authenticated-request'; +import { ApiException } from '../common/api.exception'; +import { DevelopmentGoalsService } from './development-goals.service'; + +/** 개발 목표 완료 요청의 성공 응답 */ +export interface DevelopmentGoalCompletionResponse { + /** 완료한 개발 목표 ID */ + goalId: string; + /** 완료 후 개발 목표 상태 */ + status: 'completed'; +} + +/** 개발 목표 완료 요청의 HTTP 경계 */ +@Controller('goals') +export class DevelopmentGoalsController { + /** 개발 목표 완료 업무 규칙을 제공하는 의존성 주입 */ + constructor(private readonly service: DevelopmentGoalsService) {} + + /** 인증된 사용자의 개발 목표 완료 요청 처리 */ + @Post(':goalId/complete') + @HttpCode(HttpStatus.OK) + async complete( + @Req() request: FirebaseAuthenticatedRequest, + @Param('goalId') goalId: string, + ): Promise { + const validGoalId = requiredGoalId(goalId); + await this.service.complete(requiredUid(request), validGoalId); + + return { goalId: validGoalId, status: 'completed' }; + } +} + +/** 인증 Guard가 확인한 사용자 식별자 */ +function requiredUid(request: FirebaseAuthenticatedRequest): string { + if (!request.uid) { + throw new ApiException( + HttpStatus.UNAUTHORIZED, + 'unauthenticated', + '인증된 사용자가 아닙니다.', + ); + } + + return request.uid; +} + +/** 앞뒤 공백을 제거하고 경로 구분자를 거부한 개발 목표 식별자 */ +function requiredGoalId(goalId: string): string { + const trimmedGoalId = goalId.trim(); + if (!trimmedGoalId) { + throw new ApiException( + HttpStatus.BAD_REQUEST, + 'invalid-argument', + 'goalId가 필요합니다.', + ); + } + if (trimmedGoalId.includes('/')) { + throw new ApiException( + HttpStatus.BAD_REQUEST, + 'invalid-argument', + 'goalId에 경로 구분자를 포함할 수 없습니다.', + ); + } + + return trimmedGoalId; +} diff --git a/nestjs-api/src/development-goals/development-goals.module.test.ts b/nestjs-api/src/development-goals/development-goals.module.test.ts new file mode 100644 index 0000000..0a17690 --- /dev/null +++ b/nestjs-api/src/development-goals/development-goals.module.test.ts @@ -0,0 +1,46 @@ +import { type Provider } from '@nestjs/common'; +import { MODULE_METADATA } from '@nestjs/common/constants'; + +import { FirebaseModule } from '../firebase/firebase.module'; +import { DevelopmentGoalsController } from './development-goals.controller'; +import { DevelopmentGoalsModule } from './development-goals.module'; +import { DevelopmentGoalsRepository } from './development-goals.repository'; +import { DevelopmentGoalsService } from './development-goals.service'; + +jest.mock('firebase-admin/app', () => ({ + applicationDefault: jest.fn(), + getApps: jest.fn(), + initializeApp: jest.fn(), +})); +jest.mock('firebase-admin/auth', () => ({ + getAuth: jest.fn(), +})); +jest.mock('firebase-admin/firestore', () => ({ + getFirestore: jest.fn(), +})); + +describe(DevelopmentGoalsModule.name, () => { + it('FirebaseModule과 개발 목표 controller, provider를 구성한다', () => { + const imports = Reflect.getMetadata( + MODULE_METADATA.IMPORTS, + DevelopmentGoalsModule, + ) as unknown[]; + const controllers = Reflect.getMetadata( + MODULE_METADATA.CONTROLLERS, + DevelopmentGoalsModule, + ) as unknown[]; + const providers = Reflect.getMetadata( + MODULE_METADATA.PROVIDERS, + DevelopmentGoalsModule, + ) as Provider[]; + + expect(imports).toContain(FirebaseModule); + expect(controllers).toContain(DevelopmentGoalsController); + expect(providers).toEqual( + expect.arrayContaining([ + DevelopmentGoalsRepository, + DevelopmentGoalsService, + ]), + ); + }); +}); diff --git a/nestjs-api/src/development-goals/development-goals.module.ts b/nestjs-api/src/development-goals/development-goals.module.ts new file mode 100644 index 0000000..ed3c0e8 --- /dev/null +++ b/nestjs-api/src/development-goals/development-goals.module.ts @@ -0,0 +1,14 @@ +import { Module } from '@nestjs/common'; + +import { FirebaseModule } from '../firebase/firebase.module'; +import { DevelopmentGoalsController } from './development-goals.controller'; +import { DevelopmentGoalsRepository } from './development-goals.repository'; +import { DevelopmentGoalsService } from './development-goals.service'; + +/** 개발 목표 완료 판정과 Firestore transaction의 의존성 경계 */ +@Module({ + imports: [FirebaseModule], + controllers: [DevelopmentGoalsController], + providers: [DevelopmentGoalsRepository, DevelopmentGoalsService], +}) +export class DevelopmentGoalsModule {} diff --git a/nestjs-api/src/development-goals/development-goals.repository.test.ts b/nestjs-api/src/development-goals/development-goals.repository.test.ts new file mode 100644 index 0000000..254cfb9 --- /dev/null +++ b/nestjs-api/src/development-goals/development-goals.repository.test.ts @@ -0,0 +1,209 @@ +import { + FieldValue, + type Firestore, + Timestamp, +} from 'firebase-admin/firestore'; + +import { DevelopmentGoalsRepository } from './development-goals.repository'; + +describe(DevelopmentGoalsRepository.name, () => { + const uid = 'user-1'; + const goalId = 'goal-1'; + const recordsReference = { + path: 'users/user-1/developmentGoals/goal-1/records', + }; + const goalReference = { + path: 'users/user-1/developmentGoals/goal-1', + collection: jest.fn(), + }; + const transactionGet = jest.fn(); + const update = jest.fn(); + const doc = jest.fn(); + const runTransaction = jest.fn(); + const repository = new DevelopmentGoalsRepository({ + doc, + runTransaction, + } as unknown as Firestore); + + beforeEach(() => { + jest.resetAllMocks(); + doc.mockReturnValue(goalReference); + goalReference.collection.mockReturnValue(recordsReference); + runTransaction.mockImplementation( + ( + callback: (transaction: { + get: typeof transactionGet; + update: typeof update; + }) => Promise, + ) => callback({ get: transactionGet, update }), + ); + }); + + // status 값을 가진 개발 목표 snapshot + function goalSnapshot(status: unknown): { + exists: true; + get: (field: string) => unknown; + } { + return { + exists: true, + get: (field: string) => (field === 'status' ? status : undefined), + }; + } + + // 필드 값을 가진 개발 기록 snapshot + function recordSnapshot( + id: string, + data: Record, + ): { + id: string; + ref: { path: string }; + get: (field: string) => unknown; + } { + return { + id, + ref: { path: `${recordsReference.path}/${id}` }, + get: (field: string) => data[field], + }; + } + + it('목표가 없으면 개발 기록을 읽지 않고 missing을 반환한다', async () => { + transactionGet.mockResolvedValueOnce({ exists: false }); + const rejectionFrom = jest.fn(); + + await expect( + repository.completeGoal(uid, goalId, rejectionFrom), + ).resolves.toBe('missing'); + + expect(doc).toHaveBeenCalledWith('users/user-1/developmentGoals/goal-1'); + expect(transactionGet).toHaveBeenCalledTimes(1); + expect(rejectionFrom).not.toHaveBeenCalled(); + expect(update).not.toHaveBeenCalled(); + }); + + it.each([ + { status: 'completed', expected: 'already-completed' }, + { status: 'archived', expected: 'archived' }, + ])( + '$status 목표는 개발 기록을 읽지 않고 $expected를 반환한다', + async ({ status, expected }) => { + transactionGet.mockResolvedValueOnce(goalSnapshot(status)); + const rejectionFrom = jest.fn(); + + await expect( + repository.completeGoal(uid, goalId, rejectionFrom), + ).resolves.toBe(expected); + + expect(transactionGet).toHaveBeenCalledTimes(1); + expect(rejectionFrom).not.toHaveBeenCalled(); + expect(update).not.toHaveBeenCalled(); + }, + ); + + it.each([undefined, 'unknown'])( + '알 수 없는 목표 status %s를 오류로 처리한다', + async (status) => { + transactionGet.mockResolvedValueOnce(goalSnapshot(status)); + + await expect( + repository.completeGoal(uid, goalId, jest.fn()), + ).rejects.toThrow(`개발 목표 status 값 오류: ${String(status)}`); + expect(update).not.toHaveBeenCalled(); + }, + ); + + it('같은 transaction에서 읽은 개발 기록 상태로 판정한다', async () => { + const createdAt = new Timestamp(1, 0); + transactionGet + .mockResolvedValueOnce(goalSnapshot('inProgress')) + .mockResolvedValueOnce({ + docs: [ + recordSnapshot('record-1', { + createdAt, + currentVersionId: 'version-1', + currentVersionNumber: 1, + }), + recordSnapshot('record-2', { + createdAt, + draft: { title: 'draft' }, + }), + ], + }); + const rejectionFrom = jest.fn().mockReturnValue('has-draft'); + + await expect( + repository.completeGoal(uid, goalId, rejectionFrom), + ).resolves.toBe('has-draft'); + + expect(transactionGet).toHaveBeenNthCalledWith(1, goalReference); + expect(goalReference.collection).toHaveBeenCalledWith('records'); + expect(transactionGet).toHaveBeenNthCalledWith(2, recordsReference); + expect(rejectionFrom).toHaveBeenCalledWith([ + { + id: 'record-1', + createdAt, + hasCurrentVersion: true, + hasDraft: false, + }, + { + id: 'record-2', + createdAt, + hasCurrentVersion: false, + hasDraft: true, + }, + ]); + expect(update).not.toHaveBeenCalled(); + }); + + it('완료 조건을 충족하면 목표 상태와 완료 시각을 기록한다', async () => { + transactionGet + .mockResolvedValueOnce(goalSnapshot('inProgress')) + .mockResolvedValueOnce({ + docs: [ + recordSnapshot('record-1', { + createdAt: new Timestamp(1, 0), + currentVersionId: 'version-1', + currentVersionNumber: 1, + draft: null, + }), + ], + }); + + await expect( + repository.completeGoal(uid, goalId, () => undefined), + ).resolves.toBe('completed'); + + expect(update).toHaveBeenCalledWith(goalReference, { + status: 'completed', + completedAt: FieldValue.serverTimestamp(), + updatedAt: FieldValue.serverTimestamp(), + }); + }); + + it.each([ + { + field: 'createdAt 누락', + data: { currentVersionId: 'version-1', currentVersionNumber: 1 }, + }, + { + field: 'currentVersionNumber 누락', + data: { createdAt: new Timestamp(1, 0), currentVersionId: 'version-1' }, + }, + { + field: 'currentVersionId 누락', + data: { createdAt: new Timestamp(1, 0), currentVersionNumber: 1 }, + }, + ])('$field 개발 기록을 오류로 처리한다', async ({ data }) => { + transactionGet + .mockResolvedValueOnce(goalSnapshot('inProgress')) + .mockResolvedValueOnce({ docs: [recordSnapshot('record-1', data)] }); + const rejectionFrom = jest.fn(); + + await expect( + repository.completeGoal(uid, goalId, rejectionFrom), + ).rejects.toThrow( + '개발 기록 문서 값 오류: users/user-1/developmentGoals/goal-1/records/record-1', + ); + expect(rejectionFrom).not.toHaveBeenCalled(); + expect(update).not.toHaveBeenCalled(); + }); +}); diff --git a/nestjs-api/src/development-goals/development-goals.repository.ts b/nestjs-api/src/development-goals/development-goals.repository.ts new file mode 100644 index 0000000..7534281 --- /dev/null +++ b/nestjs-api/src/development-goals/development-goals.repository.ts @@ -0,0 +1,123 @@ +import { Inject, Injectable } from '@nestjs/common'; +import { + type DocumentReference, + FieldValue, + type Firestore, + type QueryDocumentSnapshot, + Timestamp, +} from 'firebase-admin/firestore'; + +import { FIREBASE_FIRESTORE_TOKEN } from '../firebase/firebase.tokens'; + +/** 완료 판정에 사용하는 개발 기록 상태 */ +export interface DevelopmentGoalCompletionRecord { + /** 개발 기록 문서 ID */ + id: string; + /** 개발 기록 생성 시각 */ + createdAt: Timestamp; + /** 현재 확정 버전 존재 여부 */ + hasCurrentVersion: boolean; + /** 확정되지 않은 초안 존재 여부 */ + hasDraft: boolean; +} + +/** 완료 조건을 충족하지 못한 사유 */ +export type DevelopmentGoalCompletionRejection = + 'requires-record' | 'needs-version' | 'has-draft'; + +/** 개발 목표 완료 transaction의 결과 */ +export type DevelopmentGoalCompletionOutcome = + | 'missing' + | 'completed' + | 'already-completed' + | 'archived' + | DevelopmentGoalCompletionRejection; + +/** 개발 목표와 개발 기록의 Firestore 완료 처리 */ +@Injectable() +export class DevelopmentGoalsRepository { + /** Firestore 저장소 의존성 주입 */ + constructor( + @Inject(FIREBASE_FIRESTORE_TOKEN) private readonly firestore: Firestore, + ) {} + + /** 목표와 하위 개발 기록을 같은 transaction에서 읽고 판정 결과에 따라 완료 상태 기록 */ + // prettier-ignore + async completeGoal( + uid: string, + goalId: string, + rejectionFrom: ( + records: DevelopmentGoalCompletionRecord[], + ) => DevelopmentGoalCompletionRejection | undefined, + ): Promise { + const goal = this.goalDocument(uid, goalId); + + return this.firestore.runTransaction(async (transaction) => { + const goalSnapshot = await transaction.get(goal); + if (!goalSnapshot.exists) { + return 'missing'; + } + + const status: unknown = goalSnapshot.get('status'); + if (status === 'completed') { + return 'already-completed'; + } + if (status === 'archived') { + return 'archived'; + } + if (status !== 'inProgress') { + throw new Error(`개발 목표 status 값 오류: ${String(status)}`); + } + + const recordsSnapshot = await transaction.get(goal.collection('records')); + const rejection = rejectionFrom( + recordsSnapshot.docs.map(completionRecord), + ); + if (rejection) { + return rejection; + } + + transaction.update(goal, { + status: 'completed', + completedAt: FieldValue.serverTimestamp(), + updatedAt: FieldValue.serverTimestamp(), + }); + return 'completed'; + }); + } + + /** 검증된 사용자 UID 범위의 개발 목표 문서 참조 */ + // prettier-ignore + private goalDocument( + uid: string, + goalId: string, + ): DocumentReference { + return this.firestore.doc(`users/${uid}/developmentGoals/${goalId}`); + } +} + +/** 개발 기록 문서를 완료 판정 입력으로 변환 */ +function completionRecord( + document: QueryDocumentSnapshot, +): DevelopmentGoalCompletionRecord { + const createdAt: unknown = document.get('createdAt'); + const currentVersionId: unknown = document.get('currentVersionId'); + const currentVersionNumber: unknown = document.get('currentVersionNumber'); + const draft: unknown = document.get('draft'); + const hasCurrentVersionId = typeof currentVersionId === 'string'; + const hasCurrentVersionNumber = typeof currentVersionNumber === 'number'; + + if ( + !(createdAt instanceof Timestamp) || + hasCurrentVersionId !== hasCurrentVersionNumber + ) { + throw new Error(`개발 기록 문서 값 오류: ${document.ref.path}`); + } + + return { + id: document.id, + createdAt, + hasCurrentVersion: hasCurrentVersionId, + hasDraft: typeof draft === 'object' && draft !== null, + }; +} diff --git a/nestjs-api/src/development-goals/development-goals.service.test.ts b/nestjs-api/src/development-goals/development-goals.service.test.ts new file mode 100644 index 0000000..eeb951e --- /dev/null +++ b/nestjs-api/src/development-goals/development-goals.service.test.ts @@ -0,0 +1,236 @@ +import { HttpStatus, Logger } from '@nestjs/common'; +import { Timestamp } from 'firebase-admin/firestore'; + +import { + type DevelopmentGoalCompletionOutcome, + type DevelopmentGoalCompletionRecord, + type DevelopmentGoalCompletionRejection, + DevelopmentGoalsRepository, +} from './development-goals.repository'; +import { DevelopmentGoalsService } from './development-goals.service'; + +type RejectionFrom = ( + records: DevelopmentGoalCompletionRecord[], +) => DevelopmentGoalCompletionRejection | undefined; + +describe(DevelopmentGoalsService.name, () => { + const uid = 'user-1'; + const goalId = 'goal-1'; + + afterEach(() => { + jest.restoreAllMocks(); + }); + + // 전달된 개발 기록으로 판정 함수를 실행하는 Repository + function judgingRepository(records: DevelopmentGoalCompletionRecord[]): { + repository: DevelopmentGoalsRepository; + completeGoal: jest.Mock; + } { + const completeGoal = jest + .fn() + .mockImplementation( + (_uid: string, _goalId: string, rejectionFrom: RejectionFrom) => + Promise.resolve( + rejectionFrom(records) ?? 'completed', + ), + ); + + return { + repository: { completeGoal } as unknown as DevelopmentGoalsRepository, + completeGoal, + }; + } + + // 완료 판정 입력으로 쓰는 개발 기록 + function record( + id: string, + seconds: number, + state: Partial< + Pick + > = {}, + ): DevelopmentGoalCompletionRecord { + return { + id, + createdAt: new Timestamp(seconds, 0), + hasCurrentVersion: state.hasCurrentVersion ?? true, + hasDraft: state.hasDraft ?? false, + }; + } + + it('검증된 UID와 목표 ID로 완료 조건을 충족한 목표를 완료한다', async () => { + const { repository, completeGoal } = judgingRepository([ + record('record-1', 1), + record('record-2', 2), + ]); + const service = new DevelopmentGoalsService(repository); + + await expect(service.complete(uid, goalId)).resolves.toBeUndefined(); + + expect(completeGoal).toHaveBeenCalledWith( + uid, + goalId, + expect.any(Function), + ); + }); + + it('이미 완료된 목표의 재요청을 성공으로 처리한다', async () => { + const completeGoal = jest.fn().mockResolvedValue('already-completed'); + const service = new DevelopmentGoalsService({ + completeGoal, + } as unknown as DevelopmentGoalsRepository); + + await expect(service.complete(uid, goalId)).resolves.toBeUndefined(); + }); + + it('개발 기록이 없으면 완료를 거부한다', async () => { + const { repository } = judgingRepository([]); + const service = new DevelopmentGoalsService(repository); + + await expect(service.complete(uid, goalId)).rejects.toMatchObject({ + status: HttpStatus.CONFLICT, + response: { + code: 'development-goal-completion-requires-record', + message: '개발 기록이 없는 개발 목표는 완료할 수 없습니다.', + }, + }); + }); + + it('생성 시각 기준 마지막 개발 기록에 확정 버전이 없으면 완료를 거부한다', async () => { + const { repository } = judgingRepository([ + record('record-2', 2, { hasCurrentVersion: false, hasDraft: true }), + record('record-1', 1), + ]); + const service = new DevelopmentGoalsService(repository); + + await expect(service.complete(uid, goalId)).rejects.toMatchObject({ + status: HttpStatus.CONFLICT, + response: { + code: 'development-goal-completion-needs-version', + message: '마지막 개발 기록에 확정 버전이 필요합니다.', + }, + }); + }); + + it('생성 시각이 같으면 문서 ID 순서로 마지막 개발 기록을 정한다', async () => { + const { repository } = judgingRepository([ + record('record-b', 1, { hasCurrentVersion: false, hasDraft: true }), + record('record-a', 1), + ]); + const service = new DevelopmentGoalsService(repository); + + await expect(service.complete(uid, goalId)).rejects.toMatchObject({ + response: { code: 'development-goal-completion-needs-version' }, + }); + }); + + it('나노초 단위로 늦은 개발 기록을 마지막 개발 기록으로 정한다', async () => { + const { repository } = judgingRepository([ + { + ...record('record-a', 1, { hasCurrentVersion: false, hasDraft: true }), + createdAt: new Timestamp(1, 2), + }, + { ...record('record-b', 1), createdAt: new Timestamp(1, 1) }, + ]); + const service = new DevelopmentGoalsService(repository); + + await expect(service.complete(uid, goalId)).rejects.toMatchObject({ + response: { code: 'development-goal-completion-needs-version' }, + }); + }); + + it('초안이 남은 개발 기록이 있으면 완료를 거부한다', async () => { + const { repository } = judgingRepository([ + record('record-1', 1, { hasDraft: true }), + record('record-2', 2), + ]); + const service = new DevelopmentGoalsService(repository); + + await expect(service.complete(uid, goalId)).rejects.toMatchObject({ + status: HttpStatus.CONFLICT, + response: { + code: 'development-goal-completion-has-draft', + message: '확정되지 않은 초안이 있는 개발 목표는 완료할 수 없습니다.', + }, + }); + }); + + it('개발 목표가 없으면 not-found로 거부한다', async () => { + const completeGoal = jest.fn().mockResolvedValue('missing'); + const service = new DevelopmentGoalsService({ + completeGoal, + } as unknown as DevelopmentGoalsRepository); + + await expect(service.complete(uid, goalId)).rejects.toMatchObject({ + status: HttpStatus.NOT_FOUND, + response: { + code: 'not-found', + message: '개발 목표를 찾을 수 없습니다.', + }, + }); + }); + + it('보관된 개발 목표의 완료를 거부한다', async () => { + const completeGoal = jest.fn().mockResolvedValue('archived'); + const service = new DevelopmentGoalsService({ + completeGoal, + } as unknown as DevelopmentGoalsRepository); + + await expect(service.complete(uid, goalId)).rejects.toMatchObject({ + status: HttpStatus.CONFLICT, + response: { + code: 'development-goal-not-in-progress', + message: '진행 중인 개발 목표만 완료할 수 있습니다.', + }, + }); + }); + + it.each([10, 409])( + '동시 변경으로 transaction 재시도를 소진한 오류 code %s를 aborted로 반환한다', + async (code) => { + const completeGoal = jest + .fn() + .mockRejectedValue(Object.assign(new Error('aborted'), { code })); + const loggerError = jest + .spyOn(Logger.prototype, 'error') + .mockImplementation(); + const service = new DevelopmentGoalsService({ + completeGoal, + } as unknown as DevelopmentGoalsRepository); + + await expect(service.complete(uid, goalId)).rejects.toMatchObject({ + status: HttpStatus.CONFLICT, + response: { + code: 'aborted', + message: '동시 변경으로 개발 목표를 완료하지 못했습니다.', + }, + }); + expect(loggerError).not.toHaveBeenCalled(); + }, + ); + + it('그 밖의 Firestore 오류를 기록하고 internal로 반환한다', async () => { + const error = new Error('Firestore 오류'); + const completeGoal = jest.fn().mockRejectedValue(error); + const loggerError = jest + .spyOn(Logger.prototype, 'error') + .mockImplementation(); + const service = new DevelopmentGoalsService({ + completeGoal, + } as unknown as DevelopmentGoalsRepository); + + await expect(service.complete(uid, goalId)).rejects.toMatchObject({ + status: HttpStatus.INTERNAL_SERVER_ERROR, + response: { + code: 'internal', + message: '개발 목표 완료에 실패했습니다.', + }, + }); + expect(loggerError).toHaveBeenCalledWith({ + message: '개발 목표 완료 실패', + errorMessage: 'Firestore 오류', + errorStack: error.stack, + uid, + goalId, + }); + }); +}); diff --git a/nestjs-api/src/development-goals/development-goals.service.ts b/nestjs-api/src/development-goals/development-goals.service.ts new file mode 100644 index 0000000..e48aa78 --- /dev/null +++ b/nestjs-api/src/development-goals/development-goals.service.ts @@ -0,0 +1,146 @@ +// prettier-ignore +import { + HttpStatus, + Injectable, + Logger, +} from '@nestjs/common'; + +import { ApiException } from '../common/api.exception'; +import { + type DevelopmentGoalCompletionOutcome, + type DevelopmentGoalCompletionRecord, + type DevelopmentGoalCompletionRejection, + DevelopmentGoalsRepository, +} from './development-goals.repository'; + +// 동시 변경으로 transaction 재시도를 소진했을 때의 Firestore 오류 code +const transactionContentionCodes: unknown[] = [10, 409]; + +/** 개발 목표 완료 조건 판정과 결과 응답 변환 */ +@Injectable() +export class DevelopmentGoalsService { + /** 개발 목표 완료 실패 원인을 기록하는 로그 기능 */ + private readonly logger = new Logger(DevelopmentGoalsService.name); + + /** 개발 목표 저장 동작을 제공하는 의존성 주입 */ + constructor(private readonly repository: DevelopmentGoalsRepository) {} + + /** 완료 조건을 충족한 진행 중 개발 목표의 완료 전환 */ + // prettier-ignore + async complete( + uid: string, + goalId: string, + ): Promise { + let outcome: DevelopmentGoalCompletionOutcome; + try { + outcome = await this.repository.completeGoal( + uid, + goalId, + completionRejection, + ); + } catch (error) { + if (isTransactionContention(error)) { + throw new ApiException( + HttpStatus.CONFLICT, + 'aborted', + '동시 변경으로 개발 목표를 완료하지 못했습니다.', + ); + } + + this.logger.error({ + message: '개발 목표 완료 실패', + errorMessage: error instanceof Error ? error.message : '알 수 없는 오류', + errorStack: error instanceof Error ? error.stack : undefined, + uid, + goalId, + }); + throw new ApiException( + HttpStatus.INTERNAL_SERVER_ERROR, + 'internal', + '개발 목표 완료에 실패했습니다.', + ); + } + + switch (outcome) { + case 'completed': + case 'already-completed': + return; + case 'missing': + throw new ApiException( + HttpStatus.NOT_FOUND, + 'not-found', + '개발 목표를 찾을 수 없습니다.', + ); + case 'archived': + throw new ApiException( + HttpStatus.CONFLICT, + 'development-goal-not-in-progress', + '진행 중인 개발 목표만 완료할 수 있습니다.', + ); + case 'requires-record': + throw new ApiException( + HttpStatus.CONFLICT, + 'development-goal-completion-requires-record', + '개발 기록이 없는 개발 목표는 완료할 수 없습니다.', + ); + case 'needs-version': + throw new ApiException( + HttpStatus.CONFLICT, + 'development-goal-completion-needs-version', + '마지막 개발 기록에 확정 버전이 필요합니다.', + ); + case 'has-draft': + throw new ApiException( + HttpStatus.CONFLICT, + 'development-goal-completion-has-draft', + '확정되지 않은 초안이 있는 개발 목표는 완료할 수 없습니다.', + ); + } + } +} + +/** 개발 기록 상태로 판정한 완료 거부 사유 */ +function completionRejection( + records: DevelopmentGoalCompletionRecord[], +): DevelopmentGoalCompletionRejection | undefined { + if (records.length === 0) { + return 'requires-record'; + } + + const lastRecord = records.reduce((last, record) => + isCreatedBefore(last, record) ? record : last, + ); + if (!lastRecord.hasCurrentVersion) { + return 'needs-version'; + } + if (records.some((record) => record.hasDraft)) { + return 'has-draft'; + } + + return undefined; +} + +/** 생성 시각과 문서 ID 순서상 앞선 개발 기록 여부 */ +function isCreatedBefore( + lhs: DevelopmentGoalCompletionRecord, + rhs: DevelopmentGoalCompletionRecord, +): boolean { + if (lhs.createdAt.seconds !== rhs.createdAt.seconds) { + return lhs.createdAt.seconds < rhs.createdAt.seconds; + } + if (lhs.createdAt.nanoseconds !== rhs.createdAt.nanoseconds) { + return lhs.createdAt.nanoseconds < rhs.createdAt.nanoseconds; + } + + return lhs.id < rhs.id; +} + +/** 동시 변경으로 transaction 재시도를 소진한 오류 여부 */ +function isTransactionContention(error: unknown): boolean { + return ( + typeof error === 'object' && + error !== null && + 'code' in error && + transactionContentionCodes.includes(error.code) + ); +} diff --git a/nestjs-api/test/development-goals.e2e.test.ts b/nestjs-api/test/development-goals.e2e.test.ts new file mode 100644 index 0000000..70ffbf6 --- /dev/null +++ b/nestjs-api/test/development-goals.e2e.test.ts @@ -0,0 +1,172 @@ +import { HttpStatus, type INestApplication } from '@nestjs/common'; +import { Test } from '@nestjs/testing'; +import { type Server } from 'node:http'; +import request from 'supertest'; + +import { configureApplication } from '../src/app.config'; +import { AppModule } from '../src/app.module'; +import { ApiException } from '../src/common/api.exception'; +import { DevelopmentGoalsService } from '../src/development-goals/development-goals.service'; +import { + FIREBASE_APP_TOKEN, + FIREBASE_AUTH_TOKEN, + FIREBASE_FIRESTORE_TOKEN, +} from '../src/firebase/firebase.tokens'; + +jest.mock('firebase-admin/app', () => ({ + applicationDefault: jest.fn(), + getApps: jest.fn(), + initializeApp: jest.fn(), +})); +jest.mock('firebase-admin/auth', () => ({ + getAuth: jest.fn(), +})); +jest.mock('firebase-admin/firestore', () => ({ + FieldPath: { documentId: jest.fn() }, + FieldValue: { + delete: jest.fn(), + serverTimestamp: jest.fn(), + }, + getFirestore: jest.fn(), +})); + +describe('개발 목표 완료 API', () => { + const uid = 'user-1'; + const token = 'Firebase-ID-Token'; + const verifyIdToken = jest.fn(); + const complete = jest.fn(); + let app: INestApplication; + + beforeAll(async () => { + const module = await Test.createTestingModule({ + imports: [AppModule], + }) + .overrideProvider(FIREBASE_APP_TOKEN) + .useValue({}) + .overrideProvider(FIREBASE_AUTH_TOKEN) + .useValue({ verifyIdToken }) + .overrideProvider(FIREBASE_FIRESTORE_TOKEN) + .useValue({}) + .overrideProvider(DevelopmentGoalsService) + .useValue({ complete }) + .compile(); + + app = module.createNestApplication(); + configureApplication(app); + await app.init(); + }); + + beforeEach(() => { + verifyIdToken.mockReset().mockResolvedValue({ uid }); + complete.mockReset().mockResolvedValue(undefined); + }); + + afterAll(async () => { + await app.close(); + }); + + it('검증된 UID와 공백을 제거한 목표 ID로 목표를 완료한다', async () => { + const server = app.getHttpServer() as Server; + + await request(server) + .post('/api/goals/%20goal-1%20/complete') + .set('Authorization', `Bearer ${token}`) + .expect(HttpStatus.OK) + .expect({ goalId: 'goal-1', status: 'completed' }); + + expect(verifyIdToken).toHaveBeenCalledWith(token); + expect(complete).toHaveBeenCalledWith(uid, 'goal-1'); + }); + + it('공백인 목표 ID를 invalid-argument로 거부한다', async () => { + const server = app.getHttpServer() as Server; + + await request(server) + .post('/api/goals/%20/complete') + .set('Authorization', `Bearer ${token}`) + .expect(HttpStatus.BAD_REQUEST) + .expect({ code: 'invalid-argument', message: 'goalId가 필요합니다.' }); + + expect(complete).not.toHaveBeenCalled(); + }); + + it('경로 구분자를 포함한 목표 ID를 invalid-argument로 거부한다', async () => { + const server = app.getHttpServer() as Server; + + await request(server) + .post('/api/goals/goal-1%2Frecords%2Frecord-1/complete') + .set('Authorization', `Bearer ${token}`) + .expect(HttpStatus.BAD_REQUEST) + .expect({ + code: 'invalid-argument', + message: 'goalId에 경로 구분자를 포함할 수 없습니다.', + }); + + expect(complete).not.toHaveBeenCalled(); + }); + + it('인증 token이 없으면 unauthenticated로 거부한다', async () => { + const server = app.getHttpServer() as Server; + + await request(server) + .post('/api/goals/goal-1/complete') + .expect(HttpStatus.UNAUTHORIZED) + .expect({ + code: 'unauthenticated', + message: '인증 토큰이 필요합니다.', + }); + + expect(complete).not.toHaveBeenCalled(); + }); + + it('Firebase Auth 오류를 401 응답으로 보존한다', async () => { + const server = app.getHttpServer() as Server; + verifyIdToken.mockRejectedValue({ + code: 'auth/id-token-expired', + message: 'Firebase ID token has expired.', + }); + + await request(server) + .post('/api/goals/goal-1/complete') + .set('Authorization', `Bearer ${token}`) + .expect(HttpStatus.UNAUTHORIZED) + .expect({ + code: 'auth/id-token-expired', + message: 'Firebase ID token has expired.', + }); + + expect(complete).not.toHaveBeenCalled(); + }); + + it.each([ + { + status: HttpStatus.NOT_FOUND, + code: 'not-found', + message: '개발 목표를 찾을 수 없습니다.', + }, + { + status: HttpStatus.CONFLICT, + code: 'development-goal-completion-has-draft', + message: '확정되지 않은 초안이 있는 개발 목표는 완료할 수 없습니다.', + }, + { + status: HttpStatus.CONFLICT, + code: 'aborted', + message: '동시 변경으로 개발 목표를 완료하지 못했습니다.', + }, + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + code: 'internal', + message: '개발 목표 완료에 실패했습니다.', + }, + ])('Service의 $code 오류를 반환한다', async ({ status, code, message }) => { + const server = app.getHttpServer() as Server; + complete.mockRejectedValue(new ApiException(status, code, message)); + + await request(server) + .post('/api/goals/goal-1/complete') + .set('Authorization', `Bearer ${token}`) + .expect(status) + .expect({ code, message }); + }); +}); From 55725f9a76b2b389af7a166a3e5b1d1ea1709ba9 Mon Sep 17 00:00:00 2001 From: opficdev <162981733+opficdev@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:15:44 +0900 Subject: [PATCH 2/7] =?UTF-8?q?test:=20=EA=B0=9C=EB=B0=9C=20=EB=AA=A9?= =?UTF-8?q?=ED=91=9C=20=EC=99=84=EB=A3=8C=20transaction=EC=9D=98=20Firesto?= =?UTF-8?q?re=20emulator=20=EA=B2=80=EC=82=AC=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 3 + nestjs-api/package.json | 3 +- .../test/development-goals.emulator.test.ts | 162 ++++++++++++++++++ nestjs-api/test/jest-emulator.json | 9 + 4 files changed, 176 insertions(+), 1 deletion(-) create mode 100644 nestjs-api/test/development-goals.emulator.test.ts create mode 100644 nestjs-api/test/jest-emulator.json diff --git a/README.md b/README.md index 8e814a7..f72e012 100644 --- a/README.md +++ b/README.md @@ -138,9 +138,12 @@ npm run lint npm run build npm test -- --runInBand npm run test:e2e -- --runInBand +npm run test:emulator npm run docker:build ``` +`npm run test:emulator`는 `firebase.test.json`의 Firestore emulator를 `demo-devlog` project로 띄워 개발 목표 완료 transaction을 확인합니다. Firebase CLI와 Java가 필요합니다. + `functions/node_modules`, `functions/lib`, `nestjs-api/node_modules`, `nestjs-api/dist`는 로컬 생성물입니다. Git에는 포함하지 않습니다. ## CI diff --git a/nestjs-api/package.json b/nestjs-api/package.json index eec1623..e23e77c 100644 --- a/nestjs-api/package.json +++ b/nestjs-api/package.json @@ -16,7 +16,8 @@ "test": "jest", "test:watch": "jest --watch", "test:cov": "jest --coverage", - "test:e2e": "jest --config ./test/jest-e2e.json" + "test:e2e": "jest --config ./test/jest-e2e.json", + "test:emulator": "firebase emulators:exec --config ../firebase.test.json --project demo-devlog --only firestore \"jest --config ./test/jest-emulator.json --runInBand\"" }, "engines": { "node": "22.x" diff --git a/nestjs-api/test/development-goals.emulator.test.ts b/nestjs-api/test/development-goals.emulator.test.ts new file mode 100644 index 0000000..1c960f4 --- /dev/null +++ b/nestjs-api/test/development-goals.emulator.test.ts @@ -0,0 +1,162 @@ +import { HttpStatus } from '@nestjs/common'; +import { type App, deleteApp, initializeApp } from 'firebase-admin/app'; +import { + type DocumentReference, + type Firestore, + getFirestore, + Timestamp, +} from 'firebase-admin/firestore'; + +import { DevelopmentGoalsRepository } from '../src/development-goals/development-goals.repository'; +import { DevelopmentGoalsService } from '../src/development-goals/development-goals.service'; + +describe('개발 목표 완료 Firestore transaction', () => { + const uid = 'owner'; + let app: App; + let firestore: Firestore; + let service: DevelopmentGoalsService; + + beforeAll(() => { + if (!process.env.FIRESTORE_EMULATOR_HOST) { + throw new Error('FIRESTORE_EMULATOR_HOST가 필요합니다.'); + } + + app = initializeApp({ projectId: 'demo-devlog' }, 'development-goals'); + firestore = getFirestore(app); + service = new DevelopmentGoalsService( + new DevelopmentGoalsRepository(firestore), + ); + }); + + afterAll(async () => { + await deleteApp(app); + }); + + // 진행 중 개발 목표와 개발 기록 저장 + async function seedGoal( + goalId: string, + records: Record>, + ): Promise { + const goal = firestore.doc(`users/${uid}/developmentGoals/${goalId}`); + await goal.set({ + title: 'goal', + markdownDescription: '', + status: 'inProgress', + createdAt: Timestamp.fromMillis(0), + updatedAt: Timestamp.fromMillis(0), + }); + for (const [recordId, data] of Object.entries(records)) { + await goal.collection('records').doc(recordId).set(data); + } + + return goal; + } + + // 확정 버전만 가진 개발 기록 데이터 + function confirmedRecord(millis: number): Record { + return { + createdAt: Timestamp.fromMillis(millis), + currentVersionId: 'version-1', + currentVersionNumber: 1, + }; + } + + // 개발 기록에 저장하는 초안 데이터 + function draftData(): Record { + return { + title: 'draft', + markdownContent: 'content', + updatedAt: Timestamp.now(), + }; + } + + it('완료 조건을 충족한 목표의 상태와 완료 시각을 기록한다', async () => { + const goal = await seedGoal('goal-completed', { + 'record-1': confirmedRecord(1), + 'record-2': confirmedRecord(2), + }); + + await expect( + service.complete(uid, 'goal-completed'), + ).resolves.toBeUndefined(); + + const snapshot = await goal.get(); + expect(snapshot.get('status')).toBe('completed'); + expect(snapshot.get('completedAt')).toBeInstanceOf(Timestamp); + expect(snapshot.get('updatedAt')).not.toEqual(Timestamp.fromMillis(0)); + }); + + it('초안이 남은 개발 기록이 있으면 목표 문서를 바꾸지 않는다', async () => { + const goal = await seedGoal('goal-draft', { + 'record-1': { ...confirmedRecord(1), draft: draftData() }, + 'record-2': confirmedRecord(2), + }); + const before = await goal.get(); + + await expect(service.complete(uid, 'goal-draft')).rejects.toMatchObject({ + status: HttpStatus.CONFLICT, + response: { code: 'development-goal-completion-has-draft' }, + }); + + const after = await goal.get(); + expect(after.updateTime).toEqual(before.updateTime); + expect(after.get('status')).toBe('inProgress'); + }); + + it('다른 사용자의 같은 목표 ID는 찾지 않는다', async () => { + await seedGoal('goal-owner', { 'record-1': confirmedRecord(1) }); + + await expect(service.complete('other', 'goal-owner')).rejects.toMatchObject( + { + status: HttpStatus.NOT_FOUND, + response: { code: 'not-found' }, + }, + ); + }); + + it('같은 목표의 동시 완료 요청은 모두 성공하고 완료 시각을 한 번만 기록한다', async () => { + const goal = await seedGoal('goal-concurrent', { + 'record-1': confirmedRecord(1), + }); + + await expect( + Promise.all([ + service.complete(uid, 'goal-concurrent'), + service.complete(uid, 'goal-concurrent'), + ]), + ).resolves.toEqual([undefined, undefined]); + + const completed = await goal.get(); + expect(completed.get('status')).toBe('completed'); + + await expect( + service.complete(uid, 'goal-concurrent'), + ).resolves.toBeUndefined(); + const repeated = await goal.get(); + expect(repeated.updateTime).toEqual(completed.updateTime); + }); + + it('완료 요청과 초안 저장이 동시에 일어나도 판정 결과와 목표 상태가 일치한다', async () => { + const goal = await seedGoal('goal-race', { + 'record-1': confirmedRecord(1), + }); + const record = goal.collection('records').doc('record-1'); + + const [completion, draftSave] = await Promise.allSettled([ + service.complete(uid, 'goal-race'), + record.update({ draft: draftData() }), + ]); + + expect(draftSave.status).toBe('fulfilled'); + const snapshot = await goal.get(); + if (completion.status === 'fulfilled') { + expect(snapshot.get('status')).toBe('completed'); + } else { + expect(completion.reason).toMatchObject({ + status: HttpStatus.CONFLICT, + response: { code: 'development-goal-completion-has-draft' }, + }); + expect(snapshot.get('status')).toBe('inProgress'); + } + }); +}); diff --git a/nestjs-api/test/jest-emulator.json b/nestjs-api/test/jest-emulator.json new file mode 100644 index 0000000..8fd8997 --- /dev/null +++ b/nestjs-api/test/jest-emulator.json @@ -0,0 +1,9 @@ +{ + "moduleFileExtensions": ["js", "json", "ts"], + "rootDir": ".", + "testEnvironment": "node", + "testRegex": "\\.emulator\\.test\\.ts$", + "transform": { + "^.+\\.(t|j)s$": "ts-jest" + } +} From 487115e59cb3c8967e29774a403e3f1822c08efa Mon Sep 17 00:00:00 2001 From: opficdev <162981733+opficdev@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:15:53 +0900 Subject: [PATCH 3/7] =?UTF-8?q?ci:=20=EA=B0=9C=EB=B0=9C=20=EB=AA=A9?= =?UTF-8?q?=ED=91=9C=20=EC=99=84=EB=A3=8C=20transaction=20emulator=20?= =?UTF-8?q?=EA=B2=80=EC=82=AC=EB=A5=BC=20CI=20nestjs-api=20job=EC=97=90=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ci.yml | 16 ++++++++++++++++ README.md | 3 +++ 2 files changed, 19 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 249e0db..887abbb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -174,6 +174,22 @@ jobs: set -o pipefail npm run test:e2e -- --runInBand 2>&1 | tee -a nestjs-api.log + - name: Setup Java + uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: 21 + + - name: Install Firebase CLI + run: npm install --global firebase-tools@15.24.0 + + - name: Test Firestore transaction + shell: bash + working-directory: nestjs-api + run: | + set -o pipefail + npm run test:emulator 2>&1 | tee -a nestjs-api.log + - name: Build Docker image shell: bash working-directory: nestjs-api diff --git a/README.md b/README.md index f72e012..ca75cff 100644 --- a/README.md +++ b/README.md @@ -171,11 +171,14 @@ npm run lint npm run build npm test -- --runInBand npm run test:e2e -- --runInBand +npm run test:emulator npm run docker:build cd .. git diff --check ``` +`nestjs-api` job은 `npm run test:emulator` 실행 전에 Java 21과 버전을 고정한 Firebase CLI를 설치합니다. + Docker 이미지는 검증을 위해 build만 수행하며 실행하거나 게시하지 않습니다. `report` job은 Functions와 NestJS API 결과를 함께 확인하고 실패 원인을 Pull Request 댓글로 남깁니다. 현재 CI는 검증만 담당합니다. Cloud Run 배포와 Docker 이미지 게시 자동화는 [이슈 #65](https://github.com/opficdev/DevLog_Firebase/issues/65)에서 별도로 다룹니다. From 6702cf673166d2a09489e0264ab064f47db68dc0 Mon Sep 17 00:00:00 2001 From: opficdev <162981733+opficdev@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:16:35 +0900 Subject: [PATCH 4/7] =?UTF-8?q?feat:=20=ED=81=B4=EB=9D=BC=EC=9D=B4?= =?UTF-8?q?=EC=96=B8=ED=8A=B8=EC=9D=98=20=EA=B0=9C=EB=B0=9C=20=EB=AA=A9?= =?UTF-8?q?=ED=91=9C=20completed=20=EC=A7=81=EC=A0=91=20=EC=A0=80=EC=9E=A5?= =?UTF-8?q?=EC=9D=84=20=EC=B0=A8=EB=8B=A8=ED=95=98=EB=8A=94=20Firestore=20?= =?UTF-8?q?=EA=B7=9C=EC=B9=99=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- firestore.rules | 3 ++- .../test/firestore-rules.emulator.test.js | 19 +++++++++++++++++++ functions/test/firestore-rules.test.js | 1 + 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/firestore.rules b/firestore.rules index b446b16..2e9423e 100644 --- a/firestore.rules +++ b/firestore.rules @@ -26,7 +26,8 @@ service cloud.firestore { match /developmentGoals/{goalId} { allow read: if request.auth != null && request.auth.uid == userId; allow create, update: if request.auth != null && request.auth.uid == userId && - userDataWriteAllowed(userId); + userDataWriteAllowed(userId) && + request.resource.data.get('status', null) != 'completed'; // 개발 기록의 생성과 초안, 현재 확정 버전 참조 갱신 match /records/{recordId} { diff --git a/functions/test/firestore-rules.emulator.test.js b/functions/test/firestore-rules.emulator.test.js index ad4af72..5b65669 100644 --- a/functions/test/firestore-rules.emulator.test.js +++ b/functions/test/firestore-rules.emulator.test.js @@ -36,6 +36,7 @@ let testEnvironment; try { await assertOwnerCreatesAndTransitionsGoal(); + await assertClientCannotCompleteGoal(); await assertOwnerCreatesRecordAndSavesDraft(); await assertOwnerConfirmsDraftWithNewVersion(); await assertOwnerReadsVersions(); @@ -68,6 +69,24 @@ async function assertOwnerCreatesAndTransitionsGoal() { await assertSucceeds(getDoc(doc(db, goalPath))); } +// 서버만 목표를 완료하도록 클라이언트의 completed 저장 거부 검증 +async function assertClientCannotCompleteGoal() { + await testEnvironment.clearFirestore(); + const db = ownerFirestore(); + + await assertFails(setDoc(doc(db, goalPath), { ...goalData(), status: "completed" })); + await assertSucceeds(setDoc(doc(db, goalPath), goalData())); + await assertFails(updateDoc(doc(db, goalPath), { status: "completed", completedAt: new Date() })); + + await seed({ [goalPath]: { ...goalData(), status: "completed", completedAt: new Date() } }); + await assertFails(updateDoc(doc(db, goalPath), { title: "changed" })); + await assertSucceeds(updateDoc(doc(db, goalPath), { + status: "inProgress", + completedAt: deleteField(), + updatedAt: new Date() + })); +} + // 소유자의 기록 생성과 초안 저장 허용 검증 async function assertOwnerCreatesRecordAndSavesDraft() { await testEnvironment.clearFirestore(); diff --git a/functions/test/firestore-rules.test.js b/functions/test/firestore-rules.test.js index 0c275f6..cecd5d2 100644 --- a/functions/test/firestore-rules.test.js +++ b/functions/test/firestore-rules.test.js @@ -20,6 +20,7 @@ assert.ok(rules.includes("match /{collectionId}/{document=**} {")); assert.ok(rules.includes("collectionId != 'developmentGoals'")); assert.ok(!rules.includes("match /{document=**} {")); assert.ok(rules.includes("match /developmentGoals/{goalId} {")); +assert.ok(rules.includes("request.resource.data.get('status', null) != 'completed'")); assert.ok(rules.includes("match /records/{recordId} {")); const versionBlock = rules.match(/match \/versions\/\{versionId\} \{[\s\S]*?\n\s*\}/)[0]; From 66732562ab254a7f014867f83a9f4e420d66bc31 Mon Sep 17 00:00:00 2001 From: opficdev <162981733+opficdev@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:16:47 +0900 Subject: [PATCH 5/7] =?UTF-8?q?feat:=20Staging=20Hosting=EC=97=90=20?= =?UTF-8?q?=EA=B0=9C=EB=B0=9C=20=EB=AA=A9=ED=91=9C=20API=EC=9D=98=20Cloud?= =?UTF-8?q?=20Run=20rewrite=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- firebase.json | 7 +++++++ functions/test/firebase-hosting.test.js | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/firebase.json b/firebase.json index 454478c..bd3666a 100644 --- a/firebase.json +++ b/firebase.json @@ -65,6 +65,13 @@ "region": "asia-northeast3" } }, + { + "source": "/api/goals/**", + "run": { + "serviceId": "api-v2", + "region": "asia-northeast3" + } + }, { "source": "/api/**", "function": { diff --git a/functions/test/firebase-hosting.test.js b/functions/test/firebase-hosting.test.js index feeedaa..e1db6d5 100644 --- a/functions/test/firebase-hosting.test.js +++ b/functions/test/firebase-hosting.test.js @@ -44,6 +44,13 @@ assert.deepStrictEqual(staging.rewrites, [ region: "asia-northeast3" } }, + { + source: "/api/goals/**", + run: { + serviceId: "api-v2", + region: "asia-northeast3" + } + }, { source: "/api/**", function: { From 1c20619af12282d6de6285bdb38a4f286f7164de Mon Sep 17 00:00:00 2001 From: opficdev <162981733+opficdev@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:18:00 +0900 Subject: [PATCH 6/7] =?UTF-8?q?docs:=20=EA=B0=9C=EB=B0=9C=20=EB=AA=A9?= =?UTF-8?q?=ED=91=9C=20API=EC=9D=98=20Staging=20=EB=9D=BC=EC=9A=B0?= =?UTF-8?q?=ED=8C=85=20=EA=B2=80=EC=A6=9D=EA=B3=BC=20Firestore=20rules=20?= =?UTF-8?q?=EB=B0=B0=ED=8F=AC=20=EC=A0=88=EC=B0=A8=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 8 ++-- docs/cloud-run-staging.md | 14 +++++- docs/firebase-hosting-staging.md | 50 ++++++++++++-------- docs/firestore-rules-staging.md | 79 ++++++++++++++++++++++++++++++++ 4 files changed, 127 insertions(+), 24 deletions(-) create mode 100644 docs/firestore-rules-staging.md diff --git a/README.md b/README.md index ca75cff..47cfb94 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ DevLog의 Firebase Cloud Functions와 Firestore index 설정을 관리하는 저 ```mermaid flowchart LR Client["API Client"] --> Hosting["Firebase Hosting"] - Hosting -->|"/api/todos/**
/api/push-notifications/**
/api/auth/google/**
/api/auth/apple/**
/api/auth/github/**"| CloudRun["Cloud Run
api-v2"] + Hosting -->|"/api/todos/**
/api/push-notifications/**
/api/auth/google/**
/api/auth/apple/**
/api/auth/github/**
/api/goals/**"| CloudRun["Cloud Run
api-v2"] Hosting -->|"나머지 /api/**"| Functions["Cloud Functions
api"] CloudRun --> Auth["Firebase Auth"] Functions --> Auth @@ -28,17 +28,17 @@ flowchart LR | 실행 구성 | 소스 | 책임 | | --- | --- | --- | | Firebase Hosting | `firebase.json` | 공개 요청 진입점과 경로별 rewrite 순서 관리 | -| Cloud Run `api-v2` | `nestjs-api` | Todo, PushNotification 요청의 Firebase ID Token 검증과 삭제, Google·Apple·GitHub 인증 관리 | +| Cloud Run `api-v2` | `nestjs-api` | Todo, PushNotification 요청의 Firebase ID Token 검증과 삭제, 개발 목표 완료 판정, Google·Apple·GitHub 인증 관리 | | Cloud Functions `api` | `functions` | Staging의 나머지 `/api/**` 요청에 대한 `404` 응답 경계 유지 | | Cloud Functions 개별 함수 | `functions` | trigger, Scheduler, Cloud Tasks, FCM 처리 | | Firebase Auth | — | 인증이 필요한 경로에 전달된 Bearer token 검증 | | Firestore | — | 검증된 사용자 UID 범위의 공통 데이터 저장 | -Staging Hosting에서는 `/api/todos/**`, `/api/push-notifications/**`, `/api/auth/google/**`, `/api/auth/apple/**`, `/api/auth/github/**`를 Cloud Run `api-v2`가 우선 처리합니다. 나머지 `/api/**`는 Functions `api`가 `404` 응답 경계를 유지합니다. +Staging Hosting에서는 `/api/todos/**`, `/api/push-notifications/**`, `/api/auth/google/**`, `/api/auth/apple/**`, `/api/auth/github/**`, `/api/goals/**`를 Cloud Run `api-v2`가 우선 처리합니다. 나머지 `/api/**`는 Functions `api`가 `404` 응답 경계를 유지합니다. 기존 Functions를 한 번에 교체하지 않고 요청 계약을 유지하면서 경로 단위로 NestJS API에 이전하는 구조입니다. 최종적으로 Cloud Functions `api`가 담당하는 HTTP API 전체를 Cloud Run 기반 `api-v2`로 이전하는 것을 목표로 합니다. -Cloud Run 배포와 직접 호출 검증은 [`docs/cloud-run-staging.md`](docs/cloud-run-staging.md), Firebase Hosting 분기 배포와 복구는 [`docs/firebase-hosting-staging.md`](docs/firebase-hosting-staging.md)에서 관리합니다. +Cloud Run 배포와 직접 호출 검증은 [`docs/cloud-run-staging.md`](docs/cloud-run-staging.md), Firebase Hosting 분기 배포와 복구는 [`docs/firebase-hosting-staging.md`](docs/firebase-hosting-staging.md), Firestore rules 배포와 복구는 [`docs/firestore-rules-staging.md`](docs/firestore-rules-staging.md)에서 관리합니다. ## Crashlytics 오류 분석과 자동 수정 diff --git a/docs/cloud-run-staging.md b/docs/cloud-run-staging.md index 68b203a..3828822 100644 --- a/docs/cloud-run-staging.md +++ b/docs/cloud-run-staging.md @@ -266,6 +266,14 @@ curl -i -X DELETE \ "${SERVICE_URL}/api/push-notifications/${PUSH_NOTIFICATION_ID}/deletion-request" \ <<<"Authorization: Bearer ${FIREBASE_ID_TOKEN}" +curl -i -X POST \ + "${SERVICE_URL}/api/goals/route-check/complete" + +curl -i -X POST \ + -H @- \ + "${SERVICE_URL}/api/goals/route-check/complete" \ + <<<"Authorization: Bearer ${FIREBASE_ID_TOKEN}" + unset FIREBASE_ID_TOKEN TODO_ID PUSH_NOTIFICATION_ID SERVICE_URL ``` @@ -287,9 +295,11 @@ unset FIREBASE_ID_TOKEN TODO_ID PUSH_NOTIFICATION_ID SERVICE_URL 14. Token이 없는 Todo `POST`: `401` 15. Token이 있는 Todo `POST`와 `DELETE`: 각각 `200`, `{"success":true}` 16. Token이 있는 PushNotification `POST`와 `DELETE`: 각각 `200`, `{"success":true}` -17. 각 `DELETE` 뒤 Todo와 연결 알림 및 PushNotification의 삭제 상태 복구 +17. Token이 없는 개발 목표 완료 `POST`: `401`, `unauthenticated` +18. Token이 있는 존재하지 않는 개발 목표 완료 `POST`: `404`, `not-found` +19. 각 `DELETE` 뒤 Todo와 연결 알림 및 PushNotification의 삭제 상태 복구 -유효한 Firebase ID Token과 일회용 인증 값이 필요한 Google custom token, account-link, account-link 해제, access-token 폐기와 Apple challenge, custom token, account-link, account-link 해제, access-token 갱신·폐기 및 refresh-token 성공 경로, GitHub 로그인·계정 연결·연결 해제·grant 폐기 성공 경로는 Staging 앱에서 별도로 확인합니다. Token과 인증 코드는 로그와 shell history에 남기지 않습니다. +유효한 Firebase ID Token과 일회용 인증 값이 필요한 Google custom token, account-link, account-link 해제, access-token 폐기와 Apple challenge, custom token, account-link, account-link 해제, access-token 갱신·폐기 및 refresh-token 성공 경로, GitHub 로그인·계정 연결·연결 해제·grant 폐기 성공 경로, 개발 목표 완료의 성공과 완료 조건 거부 경로는 Staging 앱에서 별도로 확인합니다. Token과 인증 코드는 로그와 shell history에 남기지 않습니다. 오류 로그가 한 항목의 `jsonPayload`로 수집되는지 확인합니다. diff --git a/docs/firebase-hosting-staging.md b/docs/firebase-hosting-staging.md index 2a8e8ad..a04719d 100644 --- a/docs/firebase-hosting-staging.md +++ b/docs/firebase-hosting-staging.md @@ -10,6 +10,7 @@ - Google 인증 경로: `/api/auth/google/**` - Apple 인증 경로: `/api/auth/apple/**` - GitHub 인증 경로: `/api/auth/github/**` +- 개발 목표 경로: `/api/goals/**` - 제외: `devlog-auth-prod`, Functions 배포, Firestore rules와 index, Cloud Run 배포와 revision 변경 이 문서는 Staging Hosting 단독 배포와 검증 및 복구 절차를 기록합니다. @@ -45,7 +46,9 @@ gcloud run services describe api-v2 \ 14. Token이 없는 Todo `POST`: `401` 15. Token이 있는 Todo `POST`와 `DELETE`: 각각 `200`, `{"success":true}` 16. Token이 있는 PushNotification `POST`와 `DELETE`: 각각 `200`, `{"success":true}` -17. 각 `DELETE` 뒤 Todo와 연결 알림 및 PushNotification의 삭제 상태 복구 +17. Token이 없는 개발 목표 완료 `POST`: `401`, `unauthenticated` +18. Token이 있는 존재하지 않는 개발 목표 완료 `POST`: `404`, `not-found` +19. 각 `DELETE` 뒤 Todo와 연결 알림 및 PushNotification의 삭제 상태 복구 하나라도 확인되지 않으면 Hosting 라우팅을 배포하지 않습니다. @@ -67,7 +70,8 @@ cd .. 3. `/api/auth/google/**` → Cloud Run `api-v2` 4. `/api/auth/apple/**` → Cloud Run `api-v2` 5. `/api/auth/github/**` → Cloud Run `api-v2` -6. `/api/**` → Functions `api` +6. `/api/goals/**` → Cloud Run `api-v2` +7. `/api/**` → Functions `api` Cloud Run rewrite에는 `pinTag`가 없어야 합니다. `devlog-auth-prod` 블록은 변경하지 않습니다. @@ -133,6 +137,14 @@ curl -i -X DELETE \ "${HOSTING_URL}/api/push-notifications/${PUSH_NOTIFICATION_ID}/deletion-request" \ <<<"Authorization: Bearer ${FIREBASE_ID_TOKEN}" +curl -i -X POST \ + "${HOSTING_URL}/api/goals/route-check/complete" + +curl -i -X POST \ + -H @- \ + "${HOSTING_URL}/api/goals/route-check/complete" \ + <<<"Authorization: Bearer ${FIREBASE_ID_TOKEN}" + curl -i -X POST \ "${HOSTING_URL}/api/auth/apple/challenges" @@ -209,20 +221,22 @@ unset FIREBASE_ID_TOKEN TODO_ID PUSH_NOTIFICATION_ID HOSTING_URL 3. Token이 있는 Todo `DELETE`: `200`, `{"success":true}` 4. Token이 없는 PushNotification `POST`: Cloud Run `api-v2`의 `401` 5. Token이 있는 PushNotification `POST`와 `DELETE`: 각각 `200`, `{"success":true}` -6. `/api/auth/apple/challenges` `POST`: Cloud Run `api-v2`의 `200`, `challengeId`, `hashedNonce`, `expiresAt` 필드가 존재 -7. `/api/auth/apple/custom-token` `POST`: Cloud Run `api-v2`의 `400`, `invalid-argument` -8. body가 빈 Google custom token `POST`: Cloud Run `api-v2`의 `400`, `invalid-argument` -9. 잘못된 `serverAuthCode`를 전달한 Google custom token `POST`: Cloud Run `api-v2`의 `401`, `invalid-google-proof` -10. Token이 없는 Google account-link와 access-token `DELETE`: Cloud Run `api-v2`의 `401` -11. Token이 없는 Apple account-link `PUT`/`DELETE`, access-token `POST`/`DELETE`, refresh-token `POST`: Cloud Run `api-v2`의 `401` -12. body가 빈 GitHub 로그인 session `POST`: Cloud Run `api-v2`의 `400`, `invalid-argument` -13. query가 빈 GitHub callback `GET`: Cloud Run `api-v2`의 `302`, `devlog://oauth-callback?error=oauth-failed` -14. body가 빈 GitHub custom token `POST`: Cloud Run `api-v2`의 `400`, `invalid-argument` -15. Token이 없는 GitHub 계정 연결 session `POST`: Cloud Run `api-v2`의 `401`, `unauthenticated` -16. Token이 없는 GitHub account-link `PUT`: Cloud Run `api-v2`의 `401`, `unauthenticated` -17. Token이 없는 GitHub account-link `DELETE`: Cloud Run `api-v2`의 `401`, `unauthenticated` -18. Token이 없는 GitHub access-token `DELETE`: Cloud Run `api-v2`의 `401`, `unauthenticated` -19. 각 `DELETE` 뒤 Todo와 연결 알림 및 PushNotification의 삭제 상태 복구 +6. Token이 없는 개발 목표 완료 `POST`: Cloud Run `api-v2`의 `401`, `unauthenticated` +7. Token이 있는 존재하지 않는 개발 목표 완료 `POST`: Cloud Run `api-v2`의 `404`, `not-found` +8. `/api/auth/apple/challenges` `POST`: Cloud Run `api-v2`의 `200`, `challengeId`, `hashedNonce`, `expiresAt` 필드가 존재 +9. `/api/auth/apple/custom-token` `POST`: Cloud Run `api-v2`의 `400`, `invalid-argument` +10. body가 빈 Google custom token `POST`: Cloud Run `api-v2`의 `400`, `invalid-argument` +11. 잘못된 `serverAuthCode`를 전달한 Google custom token `POST`: Cloud Run `api-v2`의 `401`, `invalid-google-proof` +12. Token이 없는 Google account-link와 access-token `DELETE`: Cloud Run `api-v2`의 `401` +13. Token이 없는 Apple account-link `PUT`/`DELETE`, access-token `POST`/`DELETE`, refresh-token `POST`: Cloud Run `api-v2`의 `401` +14. body가 빈 GitHub 로그인 session `POST`: Cloud Run `api-v2`의 `400`, `invalid-argument` +15. query가 빈 GitHub callback `GET`: Cloud Run `api-v2`의 `302`, `devlog://oauth-callback?error=oauth-failed` +16. body가 빈 GitHub custom token `POST`: Cloud Run `api-v2`의 `400`, `invalid-argument` +17. Token이 없는 GitHub 계정 연결 session `POST`: Cloud Run `api-v2`의 `401`, `unauthenticated` +18. Token이 없는 GitHub account-link `PUT`: Cloud Run `api-v2`의 `401`, `unauthenticated` +19. Token이 없는 GitHub account-link `DELETE`: Cloud Run `api-v2`의 `401`, `unauthenticated` +20. Token이 없는 GitHub access-token `DELETE`: Cloud Run `api-v2`의 `401`, `unauthenticated` +21. 각 `DELETE` 뒤 Todo와 연결 알림 및 PushNotification의 삭제 상태 복구 유효한 일회용 인증 값이 필요한 Apple challenge, custom token, account-link, account-link 해제, access-token 갱신·폐기 및 refresh-token 성공 경로와 GitHub 로그인·계정 연결·연결 해제·grant 폐기 성공 경로는 Staging 앱에서 확인합니다. 성공 응답과 최신 `api-v2` revision 로그를 함께 확인하며 Token과 인증 코드는 로그와 shell history에 남기지 않습니다. @@ -249,12 +263,12 @@ firebase functions:log \ unset LATEST_REVISION ``` -Todo, PushNotification과 Google·Apple·GitHub 인증 요청은 최신 `api-v2` revision에서 확인되어야 합니다. 알려지지 않은 나머지 `/api/**` 요청은 Functions `api`의 `404` 응답으로 확인되어야 합니다. +Todo, PushNotification, 개발 목표와 Google·Apple·GitHub 인증 요청은 최신 `api-v2` revision에서 확인되어야 합니다. 알려지지 않은 나머지 `/api/**` 요청은 Functions `api`의 `404` 응답으로 확인되어야 합니다. ## `api-v2` revision 복구 Hosting 전환 이후 `api-v2` 요청 검증이 실패하면 [`cloud-run-staging.md`](./cloud-run-staging.md#revision-복구)에 따라 이전 정상 revision으로 트래픽을 되돌립니다. 첫 revision이라 이전 정상 revision이 없으면 수정본을 배포합니다. `firebase.json`과 Hosting rewrite는 변경하지 않습니다. -복구 뒤 앞 절의 Hosting 요청을 다시 실행하고 Todo, PushNotification과 Google·Apple·GitHub 인증 요청이 선택한 `api-v2` revision에 기록되는지 확인합니다. 알려지지 않은 나머지 `/api/**` 요청은 Functions `api`의 `404` 응답과 로그로 확인합니다. +복구 뒤 앞 절의 Hosting 요청을 다시 실행하고 Todo, PushNotification, 개발 목표와 Google·Apple·GitHub 인증 요청이 선택한 `api-v2` revision에 기록되는지 확인합니다. 알려지지 않은 나머지 `/api/**` 요청은 Functions `api`의 `404` 응답과 로그로 확인합니다. 복구 과정에서는 Functions, Firestore, Secret과 Production 자원을 삭제하거나 변경하지 않습니다. 원인을 수정한 뒤에는 `api-v2` 직접 호출 검증 전체를 다시 통과하고 이 문서의 정상 전환 절차를 처음부터 수행합니다. diff --git a/docs/firestore-rules-staging.md b/docs/firestore-rules-staging.md new file mode 100644 index 0000000..a08a5c5 --- /dev/null +++ b/docs/firestore-rules-staging.md @@ -0,0 +1,79 @@ +# Staging Firestore rules 배포 + +## 범위 + +- Firebase project: `devlog-staging` +- database: `(default)` +- 규칙 파일: `firestore.rules` +- 포함 규칙: 클라이언트의 개발 목표 `completed` 저장 차단, 개발 기록 확정 버전의 갱신과 삭제 차단, 개발 목표와 개발 기록의 삭제 차단 +- 제외: Production project, Firestore index, Functions, Hosting, Cloud Run 배포 + +이 문서는 `firestore.rules`의 Staging 단독 배포와 확인 및 복구 절차를 기록합니다. 규칙 배포는 `firestore.rules` 전체를 한 번에 교체하므로 아직 Staging에 배포하지 않은 이전 규칙 변경도 함께 반영됩니다. + +## 선행 조건 + +개발 목표 완료는 이 규칙 배포 뒤 서버 API로만 가능합니다. 다음 항목이 모두 확인된 뒤에 배포합니다. + +1. [Cloud Run Staging 수동 배포 절차](./cloud-run-staging.md)의 직접 호출 검증에서 개발 목표 완료 `POST`가 `401`과 `404`로 응답 +2. [Staging Firebase Hosting API 라우팅](./firebase-hosting-staging.md)의 배포 후 요청 검증에서 `/api/goals/**`가 Cloud Run `api-v2`로 전달 +3. Staging 앱 빌드가 개발 목표 완료를 서버 API로 요청하고 `completed`를 Firestore에 직접 저장하지 않음 + +하나라도 확인되지 않으면 규칙을 배포하지 않습니다. + +## 설정 확인 + +규칙 구조 시험과 Firestore emulator 허용·거부 시험을 실행합니다. + +```bash +cd functions +npm run build +npm run test:run +npm run test:rules +cd .. +``` + +`firebase.json`의 `firestore` 설정이 `(default)` database와 `firestore.rules`를 가리키는지 확인합니다. + +```bash +git diff -- firestore.rules firebase.json +``` + +배포 전에 Firebase Console의 Staging Firestore 규칙 화면에서 현재 게시된 규칙 버전과 게시 시각을 기록합니다. 복구할 때 이 버전을 다시 게시합니다. + +## Staging 규칙 배포 + +현재 로그인 상태와 대상 project를 확인합니다. 명령 출력에 계정 정보가 포함될 수 있으므로 저장소에 기록하지 않습니다. + +```bash +firebase login:list +firebase projects:list +``` + +`devlog-staging`의 Firestore rules만 배포합니다. + +```bash +firebase deploy \ + --project devlog-staging \ + --only firestore:rules \ + --non-interactive +``` + +Firestore index, Functions, Hosting, Cloud Run은 이 명령의 배포 대상이 아닙니다. + +## 배포 후 확인 + +Staging 앱에서 다음 흐름을 확인합니다. + +1. 개발 목표 생성과 `보관`, `진행 중` 전환 성공 +2. 개발 기록 생성, 초안 저장, 확정 버전 생성 성공 +3. 완료 조건을 충족한 개발 목표의 완료가 서버 API로 성공하고 완료 시각이 표시됨 +4. 완료한 개발 목표의 `진행 중` 복귀 성공 +5. Todo, 알림, 설정 등 기존 사용자 데이터의 읽기와 쓰기 정상 + +클라이언트의 `completed` 직접 저장과 확정 버전 변경 거부는 `npm run test:rules`의 emulator 시험으로 확인합니다. + +## 복구 + +배포 후 확인이 실패하면 Firebase Console의 Staging Firestore 규칙 기록에서 배포 전에 기록한 버전을 다시 게시합니다. 복구 뒤 Staging 앱에서 기존 기능이 정상인지 다시 확인합니다. + +복구 과정에서는 Firestore 데이터, index, Functions, Hosting, Cloud Run과 Production 자원을 변경하지 않습니다. 원인을 수정한 뒤에는 이 문서의 절차를 처음부터 수행합니다. From 9f8e35c9b0aee8112da71214f56e3ff11577c8f6 Mon Sep 17 00:00:00 2001 From: opficdev <162981733+opficdev@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:57:25 +0900 Subject: [PATCH 7/7] =?UTF-8?q?docs:=20Firestore=20rules=EC=9D=98=20Produc?= =?UTF-8?q?tion=20=EB=B0=B0=ED=8F=AC=20=EC=84=A0=ED=96=89=20=EC=A1=B0?= =?UTF-8?q?=EA=B1=B4=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/firestore-rules-staging.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/firestore-rules-staging.md b/docs/firestore-rules-staging.md index a08a5c5..fda2f75 100644 --- a/docs/firestore-rules-staging.md +++ b/docs/firestore-rules-staging.md @@ -20,6 +20,8 @@ 하나라도 확인되지 않으면 규칙을 배포하지 않습니다. +`firestore.rules`는 Staging과 Production이 함께 사용하는 파일입니다. Production에 규칙을 배포할 때도 Production `api-v2`의 개발 목표 완료 API, Production Hosting의 `/api/goals/**` 경로, 서버 API로 완료를 요청하는 앱 배포가 먼저 확인되어야 합니다. 그 전에 배포하면 Production 사용자는 개발 목표를 완료할 수 없습니다. + ## 설정 확인 규칙 구조 시험과 Firestore emulator 허용·거부 시험을 실행합니다.