|
| 1 | +import {onCall, HttpsError} from "firebase-functions/v2/https"; |
| 2 | +import {onTaskDispatched} from "firebase-functions/v2/tasks"; |
| 3 | +import {getFunctions} from "firebase-admin/functions"; |
| 4 | +import * as admin from "firebase-admin"; |
| 5 | +import * as logger from "firebase-functions/logger"; |
| 6 | + |
| 7 | +const LOCATION = "asia-northeast3"; |
| 8 | +const DELETE_DELAY_SECONDS = 5; |
| 9 | +const QUERY_BATCH_SIZE = 200; |
| 10 | + |
| 11 | +type TodoDeletionTaskData = { |
| 12 | + userId: string; |
| 13 | + todoId: string; |
| 14 | + createdAt?: FirebaseFirestore.Timestamp | Date | null; |
| 15 | +}; |
| 16 | + |
| 17 | +export const requestTodoDeletion = onCall({ |
| 18 | + cors: true, |
| 19 | + maxInstances: 10, |
| 20 | + region: LOCATION, |
| 21 | + }, |
| 22 | + async (request) => { |
| 23 | + const userId = request.auth?.uid; |
| 24 | + const todoId = typeof request.data?.todoId === "string" ? request.data.todoId.trim() : ""; |
| 25 | + |
| 26 | + if (!userId) { |
| 27 | + throw new HttpsError("unauthenticated", "인증된 사용자가 아닙니다."); |
| 28 | + } |
| 29 | + |
| 30 | + if (!todoId) { |
| 31 | + throw new HttpsError("invalid-argument", "todoId가 필요합니다."); |
| 32 | + } |
| 33 | + |
| 34 | + const todoRef = admin.firestore().doc(`users/${userId}/todoLists/${todoId}`); |
| 35 | + const todoSnapshot = await todoRef.get(); |
| 36 | + |
| 37 | + if (!todoSnapshot.exists) { |
| 38 | + throw new HttpsError("not-found", "Todo를 찾을 수 없습니다."); |
| 39 | + } |
| 40 | + |
| 41 | + const taskRef = admin.firestore().collection("todoDeletionTasks").doc(); |
| 42 | + const taskData = { |
| 43 | + userId, |
| 44 | + todoId, |
| 45 | + createdAt: admin.firestore.FieldValue.serverTimestamp() |
| 46 | + }; |
| 47 | + |
| 48 | + try { |
| 49 | + await taskRef.set(taskData); |
| 50 | + const todoRef = admin.firestore().doc(`users/${userId}/todoLists/${todoId}`); |
| 51 | + await todoRef.set({ |
| 52 | + // deletingAt: 삭제 요청은 되었지만, 5초 유예 후 최종 삭제되기 전 상태를 의미한다. |
| 53 | + deletingAt: admin.firestore.FieldValue.serverTimestamp() |
| 54 | + }, {merge: true}); |
| 55 | + |
| 56 | + await updateNotificationsDeletingAt( |
| 57 | + userId, |
| 58 | + todoId, |
| 59 | + admin.firestore.FieldValue.serverTimestamp() |
| 60 | + ); |
| 61 | + |
| 62 | + const queue = getFunctions().taskQueue( |
| 63 | + `locations/${LOCATION}/functions/completeTodoDeletion` |
| 64 | + ); |
| 65 | + await queue.enqueue( |
| 66 | + {taskId: taskRef.id}, |
| 67 | + {scheduleDelaySeconds: DELETE_DELAY_SECONDS} |
| 68 | + ); |
| 69 | + } catch (error) { |
| 70 | + try { |
| 71 | + await taskRef.delete(); |
| 72 | + } catch (cleanupError) { |
| 73 | + logger.warn("todoDeletionTasks 정리 실패", { |
| 74 | + userId, |
| 75 | + todoId, |
| 76 | + taskId: taskRef.id, |
| 77 | + error: normalizeError(cleanupError) |
| 78 | + }); |
| 79 | + } |
| 80 | + |
| 81 | + const todoRef = admin.firestore().doc(`users/${userId}/todoLists/${todoId}`); |
| 82 | + const todoSnapshotForCleanup = await todoRef.get(); |
| 83 | + |
| 84 | + if (todoSnapshotForCleanup.exists) { |
| 85 | + await todoRef.update({ |
| 86 | + deletingAt: admin.firestore.FieldValue.delete() |
| 87 | + }); |
| 88 | + } |
| 89 | + |
| 90 | + await updateNotificationsDeletingAt( |
| 91 | + userId, |
| 92 | + todoId, |
| 93 | + admin.firestore.FieldValue.delete() |
| 94 | + ); |
| 95 | + logger.error("todo 삭제 요청 실패", { |
| 96 | + userId, |
| 97 | + todoId, |
| 98 | + error: normalizeError(error) |
| 99 | + }); |
| 100 | + throw new HttpsError("internal", "Todo 삭제 요청에 실패했습니다."); |
| 101 | + } |
| 102 | + |
| 103 | + return {success: true}; |
| 104 | + } |
| 105 | +); |
| 106 | + |
| 107 | +export const completeTodoDeletion = onTaskDispatched({ |
| 108 | + region: LOCATION, |
| 109 | + retryConfig: {maxAttempts: 3, minBackoffSeconds: 5}, |
| 110 | + rateLimits: {maxDispatchesPerSecond: 200}, |
| 111 | + }, |
| 112 | + async (request) => { |
| 113 | + const taskId = typeof request.data?.taskId === "string" ? request.data.taskId.trim() : ""; |
| 114 | + if (!taskId) { |
| 115 | + logger.warn("유효하지 않은 todo 삭제 payload", request.data); |
| 116 | + return; |
| 117 | + } |
| 118 | + |
| 119 | + const taskRef = admin.firestore().collection("todoDeletionTasks").doc(taskId); |
| 120 | + const taskSnapshot = await taskRef.get(); |
| 121 | + if (!taskSnapshot.exists) { return; } |
| 122 | + |
| 123 | + const taskData = taskSnapshot.data() as TodoDeletionTaskData | undefined; |
| 124 | + const userId = typeof taskData?.userId === "string" ? taskData.userId : ""; |
| 125 | + const todoId = typeof taskData?.todoId === "string" ? taskData.todoId : ""; |
| 126 | + if (!userId || !todoId) { |
| 127 | + logger.warn("todoDeletionTasks 문서 형식이 올바르지 않습니다.", {taskId}); |
| 128 | + return; |
| 129 | + } |
| 130 | + |
| 131 | + const todoRef = admin.firestore().doc(`users/${userId}/todoLists/${todoId}`); |
| 132 | + |
| 133 | + try { |
| 134 | + const todoSnapshot = await todoRef.get(); |
| 135 | + const deletingAt = todoSnapshot.data()?.deletingAt; |
| 136 | + |
| 137 | + if (!todoSnapshot.exists || !deletingAt) { |
| 138 | + await taskRef.delete(); |
| 139 | + return; |
| 140 | + } |
| 141 | + |
| 142 | + await todoRef.delete(); |
| 143 | + await taskRef.delete(); |
| 144 | + } catch (error) { |
| 145 | + logger.error("todo 최종 삭제 실패", { |
| 146 | + userId, |
| 147 | + todoId, |
| 148 | + taskId, |
| 149 | + error: normalizeError(error) |
| 150 | + }); |
| 151 | + throw error; |
| 152 | + } |
| 153 | + } |
| 154 | +); |
| 155 | + |
| 156 | +async function updateNotificationsDeletingAt( |
| 157 | + userId: string, |
| 158 | + todoId: string, |
| 159 | + fieldValue: FirebaseFirestore.FieldValue |
| 160 | +): Promise<void> { |
| 161 | + while (true) { |
| 162 | + const snapshot = await admin.firestore() |
| 163 | + .collection(`users/${userId}/notifications`) |
| 164 | + .where("todoId", "==", todoId) |
| 165 | + .limit(QUERY_BATCH_SIZE) |
| 166 | + .get(); |
| 167 | + |
| 168 | + if (snapshot.empty) { return; } |
| 169 | + |
| 170 | + const batch = admin.firestore().batch(); |
| 171 | + snapshot.docs.forEach((document) => { |
| 172 | + batch.update(document.ref, { |
| 173 | + deletingAt: fieldValue |
| 174 | + }); |
| 175 | + }); |
| 176 | + await batch.commit(); |
| 177 | + |
| 178 | + if (snapshot.size < QUERY_BATCH_SIZE) { return; } |
| 179 | + } |
| 180 | +} |
| 181 | + |
| 182 | +function normalizeError(error: unknown): Record<string, unknown> { |
| 183 | + const normalized = error as {code?: unknown; message?: unknown; stack?: unknown}; |
| 184 | + return { |
| 185 | + code: normalized?.code ?? null, |
| 186 | + message: normalized?.message ?? String(error), |
| 187 | + stack: normalized?.stack ?? null |
| 188 | + }; |
| 189 | +} |
0 commit comments