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