notifkit 0.1.14 → 0.1.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dashboard/dist/assets/index-C-DJYu0_.css +1 -0
- package/dashboard/dist/assets/index-CzFZcEon.js +318 -0
- package/dashboard/dist/index.html +2 -2
- package/dist/{bootstrap-m107TukN.mjs → bootstrap-BMDRPjgp.mjs} +1 -1
- package/dist/{bulk-xAd_biYV.mjs → bulk-CJ5QXiPa.mjs} +1 -1
- package/dist/index.d.mts +71 -27
- package/dist/index.mjs +2 -2
- package/dist/{main-CWIBUEc7.mjs → main-6_bXQBDH.mjs} +21 -41
- package/dist/{main-WkxXwP5q.mjs → main-8nP3qmCT.mjs} +29 -49
- package/dist/{main-HT5c6jyf.mjs → main-B82bsFoy.mjs} +183 -334
- package/dist/{main-C87TSAqM.mjs → main-CpaHF1Zw.mjs} +13 -15
- package/dist/{main-DRHL2bst.mjs → main-DULD8-th.mjs} +8 -6
- package/dist/{main-D_62f9fH.mjs → main-ZW5RaiOK.mjs} +77 -64
- package/dist/{main-5kVwbbnW.mjs → main-g1KEcXXp.mjs} +676 -582
- package/dist/{main-C0MjK1Au.mjs → main-mGIT8jv4.mjs} +4 -4
- package/dist/schedule-or-dispatch-Cd7GLfc3.mjs +52 -0
- package/dist/{src-DYqdD694.mjs → src-BE_EUpZ6.mjs} +93 -93
- package/package.json +1 -1
- package/scripts/create-admin.mjs +0 -0
- package/scripts/create-project.mjs +6 -2
- package/scripts/migrate.mjs +0 -0
- package/scripts/notifkit.mjs +0 -0
- package/src/client.ts +3 -3
- package/src/config/index.ts +1 -0
- package/src/contracts/common.ts +2 -0
- package/src/contracts/envelope.ts +1 -1
- package/src/contracts/events/notification-created.ts +2 -0
- package/src/contracts/events/notification-delivered.ts +1 -1
- package/src/contracts/events/notification-failed.ts +1 -1
- package/src/contracts/events/notification-requested.ts +3 -2
- package/src/contracts/helpers.ts +1 -2
- package/src/contracts/index.ts +1 -0
- package/src/contracts/registry.ts +1 -0
- package/src/contracts/sdk.ts +8 -37
- package/src/db/schema.ts +8 -13
- package/src/idempotency/index.ts +6 -8
- package/src/metrics/index.ts +2 -0
- package/src/rate-limiter/api-rate-limiter.ts +208 -0
- package/src/rate-limiter/index.ts +3 -411
- package/src/rate-limiter/project-settings-cache.ts +99 -0
- package/src/rate-limiter/user-throttle.ts +100 -0
- package/src/redis/index.ts +10 -3
- package/src/repositories/admin-user.ts +83 -0
- package/src/repositories/contact.ts +359 -0
- package/src/repositories/index.ts +9 -1416
- package/src/repositories/preference.ts +35 -0
- package/src/repositories/project.ts +110 -0
- package/src/repositories/segment.ts +16 -0
- package/src/repositories/template.ts +72 -0
- package/src/repositories/types.ts +49 -0
- package/src/repositories/user.ts +644 -0
- package/src/repositories/workflow.ts +64 -0
- package/src/services/ai/main.ts +29 -71
- package/src/services/api/admin-static.ts +4 -1
- package/src/services/api/handlers/auth.ts +109 -0
- package/src/services/api/handlers/campaigns.ts +191 -0
- package/src/services/api/handlers/events.ts +99 -0
- package/src/services/api/handlers/notifications.ts +356 -0
- package/src/services/api/handlers/projects.ts +116 -0
- package/src/services/api/handlers/shared.ts +262 -0
- package/src/services/api/handlers/suppressions.ts +95 -0
- package/src/services/api/handlers/system.ts +314 -0
- package/src/services/api/handlers/templates.ts +97 -0
- package/src/services/api/handlers/unsubscribe.ts +215 -0
- package/src/services/api/handlers/users.ts +262 -0
- package/src/services/api/handlers/workflows.ts +150 -0
- package/src/services/api/handlers.ts +25 -2190
- package/src/services/api/health.ts +133 -0
- package/src/services/api/http.ts +12 -0
- package/src/services/api/main.ts +32 -322
- package/src/services/api/router.ts +1 -1
- package/src/services/api/webhooks.ts +172 -0
- package/src/services/delivery/main.ts +256 -498
- package/src/services/engine/main.ts +31 -235
- package/src/services/engine/quiet-hours.ts +151 -0
- package/src/services/engine/schedule-or-dispatch.ts +104 -0
- package/src/services/enricher/main.ts +9 -21
- package/src/services/events/main.ts +2 -2
- package/src/services/scheduler/main.ts +16 -25
- package/src/services/workflow/duration.ts +24 -0
- package/src/services/workflow/main.ts +6 -164
- package/src/services/workflow/timers.ts +157 -0
- package/src/shared/events.ts +3 -2
- package/src/templates/render.ts +1 -0
- package/src/workers/index.ts +7 -4
- package/src/workflows/sdk.ts +1 -0
- package/dashboard/README.md +0 -29
- package/dashboard/dist/assets/index-ggpJKZqZ.js +0 -315
- package/dashboard/dist/assets/index-s-SXGIwv.css +0 -1
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
3
|
+
import {
|
|
4
|
+
NotifyRequestSchema,
|
|
5
|
+
type NotificationRequestedPayload,
|
|
6
|
+
type NotificationTarget,
|
|
7
|
+
buildStreamEvent,
|
|
8
|
+
} from "@/contracts/index.js";
|
|
9
|
+
import { readJsonBody, sendJson, sendValidationError } from "../http.js";
|
|
10
|
+
import type { RouteContext } from "../router.js";
|
|
11
|
+
import { globalEmitter, getPriorityBucket } from "@/shared/index.js";
|
|
12
|
+
import { metrics } from "@/metrics/index.js";
|
|
13
|
+
import { eq, desc, and, sql, like, or, inArray } from "drizzle-orm";
|
|
14
|
+
import { messageLogs, scheduledPayloads } from "@/db/schema.js";
|
|
15
|
+
import {
|
|
16
|
+
type Deps,
|
|
17
|
+
type InlineUserLike,
|
|
18
|
+
persistUsers,
|
|
19
|
+
encodeLogCursor,
|
|
20
|
+
decodeLogCursor,
|
|
21
|
+
contains,
|
|
22
|
+
getQueryParam,
|
|
23
|
+
parseLimit,
|
|
24
|
+
} from "./shared.js";
|
|
25
|
+
|
|
26
|
+
export function createNotificationsHandlers(deps: Deps) {
|
|
27
|
+
const { logger } = deps;
|
|
28
|
+
|
|
29
|
+
async function notify(
|
|
30
|
+
req: IncomingMessage,
|
|
31
|
+
res: ServerResponse,
|
|
32
|
+
ctx: RouteContext,
|
|
33
|
+
): Promise<void> {
|
|
34
|
+
const rawBody = await readJsonBody(req);
|
|
35
|
+
const parsed = NotifyRequestSchema.safeParse(rawBody);
|
|
36
|
+
|
|
37
|
+
if (!parsed.success) return sendValidationError(res, parsed.error);
|
|
38
|
+
const body = parsed.data;
|
|
39
|
+
|
|
40
|
+
// Resolve the (unresolved) target. Inline users are synced first.
|
|
41
|
+
let targets: NotificationTarget[] = [];
|
|
42
|
+
const inlineUsersToSync: InlineUserLike[] = [];
|
|
43
|
+
if (body.user !== undefined) {
|
|
44
|
+
const users = Array.isArray(body.user) ? body.user : [body.user];
|
|
45
|
+
for (const u of users) {
|
|
46
|
+
if (typeof u === "string") {
|
|
47
|
+
targets.push({ type: "user", userId: u });
|
|
48
|
+
} else {
|
|
49
|
+
inlineUsersToSync.push(u);
|
|
50
|
+
targets.push({ type: "user", userId: u.id });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
if (inlineUsersToSync.length > 0) {
|
|
55
|
+
try {
|
|
56
|
+
await persistUsers(deps, inlineUsersToSync, ctx.projectId!);
|
|
57
|
+
} catch (err) {
|
|
58
|
+
deps.logger.error({ err }, "inline user bulk sync failed");
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
} else if (body.segment !== undefined) {
|
|
62
|
+
targets.push({ type: "segment", segment: body.segment });
|
|
63
|
+
} else {
|
|
64
|
+
targets.push({ type: "topic", topic: body.topic! });
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const baseNotificationId = (req.headers["x-idempotency-key"] as string) || randomUUID();
|
|
68
|
+
|
|
69
|
+
const priority = body.priority ?? "normal";
|
|
70
|
+
const p = getPriorityBucket(priority);
|
|
71
|
+
const producer = deps.producers[p] ?? deps.producers.normal!;
|
|
72
|
+
|
|
73
|
+
const messageIds: string[] = [];
|
|
74
|
+
let lastNotificationId = "";
|
|
75
|
+
|
|
76
|
+
const CHUNK_SIZE = 1000;
|
|
77
|
+
for (let chunkStart = 0; chunkStart < targets.length; chunkStart += CHUNK_SIZE) {
|
|
78
|
+
const chunk = targets.slice(chunkStart, chunkStart + CHUNK_SIZE);
|
|
79
|
+
|
|
80
|
+
const events = chunk.map((target, idx) => {
|
|
81
|
+
const i = chunkStart + idx;
|
|
82
|
+
const notificationId =
|
|
83
|
+
targets.length > 1 ? `${baseNotificationId}-${i}` : baseNotificationId;
|
|
84
|
+
lastNotificationId = notificationId;
|
|
85
|
+
|
|
86
|
+
const payload: NotificationRequestedPayload = {
|
|
87
|
+
projectId: ctx.projectId!,
|
|
88
|
+
target,
|
|
89
|
+
templateId: body.template,
|
|
90
|
+
priority,
|
|
91
|
+
channels: body.channels,
|
|
92
|
+
data: body.data ?? {},
|
|
93
|
+
aiPrompts: body.aiPrompts,
|
|
94
|
+
fallback: body.fallback ?? false,
|
|
95
|
+
scheduledAt: body.sendAt,
|
|
96
|
+
// Only a caller's own key: the enricher keeps those for the full
|
|
97
|
+
// 24-hour window, and dedupes everything else on the event id.
|
|
98
|
+
...(req.headers["x-idempotency-key"] ? { idempotencyKey: notificationId } : {}),
|
|
99
|
+
campaignId: body.campaign,
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
return buildStreamEvent(
|
|
103
|
+
"notification.requested",
|
|
104
|
+
payload as Record<string, unknown>,
|
|
105
|
+
"api",
|
|
106
|
+
notificationId,
|
|
107
|
+
);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
const { messageIds: chunkMessageIds } = await producer.publishBatch(events);
|
|
111
|
+
messageIds.push(...chunkMessageIds);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
logger.debug({ count: targets.length, priority: p }, "notification requested");
|
|
115
|
+
metrics.messagesPublished.inc({ channel: "api", priority: p }, targets.length);
|
|
116
|
+
|
|
117
|
+
if (targets.length === 1) {
|
|
118
|
+
sendJson(res, 202, {
|
|
119
|
+
messageId: messageIds[0],
|
|
120
|
+
notificationId: lastNotificationId,
|
|
121
|
+
target: targets[0],
|
|
122
|
+
...(body.campaign ? { campaign: body.campaign } : {}),
|
|
123
|
+
});
|
|
124
|
+
} else {
|
|
125
|
+
sendJson(res, 202, {
|
|
126
|
+
messageIds,
|
|
127
|
+
notificationIdsBase: baseNotificationId,
|
|
128
|
+
batchSize: targets.length,
|
|
129
|
+
...(body.campaign ? { campaign: body.campaign } : {}),
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function cancelNotification(
|
|
135
|
+
req: IncomingMessage,
|
|
136
|
+
res: ServerResponse,
|
|
137
|
+
ctx: RouteContext,
|
|
138
|
+
): Promise<void> {
|
|
139
|
+
const { taskId } = ctx.params;
|
|
140
|
+
if (!taskId) return sendJson(res, 400, { error: "missing_task_id" });
|
|
141
|
+
|
|
142
|
+
const rows = await deps.db
|
|
143
|
+
.select({ payload: scheduledPayloads.payload })
|
|
144
|
+
.from(scheduledPayloads)
|
|
145
|
+
.where(eq(scheduledPayloads.taskId, taskId))
|
|
146
|
+
.limit(1);
|
|
147
|
+
|
|
148
|
+
if (rows.length === 0) {
|
|
149
|
+
return sendJson(res, 404, {
|
|
150
|
+
error: "not_found",
|
|
151
|
+
message: "Task not found or already processed",
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const payload = rows[0]!.payload as any;
|
|
156
|
+
if (payload.projectId !== ctx.projectId) {
|
|
157
|
+
return sendJson(res, 404, {
|
|
158
|
+
error: "not_found",
|
|
159
|
+
message: "Task not found or already processed",
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const deletedRows = await deps.db
|
|
164
|
+
.delete(scheduledPayloads)
|
|
165
|
+
.where(eq(scheduledPayloads.taskId, taskId))
|
|
166
|
+
.returning({ taskId: scheduledPayloads.taskId });
|
|
167
|
+
|
|
168
|
+
if (deletedRows.length > 0) {
|
|
169
|
+
globalEmitter.emit("notification:canceled", { projectId: ctx.projectId, taskId });
|
|
170
|
+
sendJson(res, 200, { success: true });
|
|
171
|
+
} else {
|
|
172
|
+
sendJson(res, 404, { error: "not_found", message: "Task not found or already processed" });
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async function getNotificationLogs(
|
|
177
|
+
req: IncomingMessage,
|
|
178
|
+
res: ServerResponse,
|
|
179
|
+
ctx: RouteContext,
|
|
180
|
+
): Promise<void> {
|
|
181
|
+
const limit = parseLimit(ctx, 50);
|
|
182
|
+
const cursor = ctx.query.get("cursor");
|
|
183
|
+
|
|
184
|
+
const templateId = getQueryParam(ctx, "templateId");
|
|
185
|
+
const workflowInstanceId = getQueryParam(ctx, "workflowInstanceId");
|
|
186
|
+
const channel = getQueryParam(ctx, "channel");
|
|
187
|
+
const status = getQueryParam(ctx, "status");
|
|
188
|
+
const taskId = getQueryParam(ctx, "taskId");
|
|
189
|
+
const campaign = getQueryParam(ctx, "campaign") || getQueryParam(ctx, "campaignId");
|
|
190
|
+
const search = getQueryParam(ctx, "search");
|
|
191
|
+
|
|
192
|
+
const conditions = [eq(messageLogs.projectId, ctx.projectId!)];
|
|
193
|
+
if (templateId) conditions.push(eq(messageLogs.templateId, templateId));
|
|
194
|
+
if (workflowInstanceId) conditions.push(eq(messageLogs.workflowInstanceId, workflowInstanceId));
|
|
195
|
+
if (channel) conditions.push(eq(messageLogs.channel, channel as any));
|
|
196
|
+
if (status) conditions.push(eq(messageLogs.status, status as any));
|
|
197
|
+
if (taskId) conditions.push(eq(messageLogs.taskId, taskId));
|
|
198
|
+
if (campaign) conditions.push(eq(messageLogs.campaignId, campaign));
|
|
199
|
+
if (search) {
|
|
200
|
+
conditions.push(
|
|
201
|
+
or(
|
|
202
|
+
like(messageLogs.taskId, contains(search)),
|
|
203
|
+
like(messageLogs.templateId, contains(search)),
|
|
204
|
+
like(messageLogs.providerMessageId, contains(search)),
|
|
205
|
+
like(messageLogs.campaignId, contains(search)),
|
|
206
|
+
)!,
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// One entry per task, newest activity first. Rows are scanned in
|
|
211
|
+
// (timestamp, id) order — a batch of deliveries shares one timestamp, so
|
|
212
|
+
// the timestamp alone cannot mark a place — and a task is listed at its
|
|
213
|
+
// newest row. The cursor is that row for the first task of the next page,
|
|
214
|
+
// and any task with a row newer than the cursor was listed on an earlier
|
|
215
|
+
// page. Paging on a millisecond timestamp over `limit * 2` rows skipped
|
|
216
|
+
// tasks that shared a timestamp and dropped any that did not fit the slice.
|
|
217
|
+
const start = decodeLogCursor(cursor);
|
|
218
|
+
const tsText = sql<string>`${messageLogs.timestamp}::text`;
|
|
219
|
+
const position = (ts: string, id: string) => sql`(${ts}::timestamptz, ${id}::uuid)`;
|
|
220
|
+
const rowKey = sql`(${messageLogs.timestamp}, ${messageLogs.id})`;
|
|
221
|
+
|
|
222
|
+
const order: string[] = [];
|
|
223
|
+
const rowsByTask = new Map<string, (typeof messageLogs.$inferSelect)[]>();
|
|
224
|
+
let nextCursor: string | null = null;
|
|
225
|
+
let scanFrom = start;
|
|
226
|
+
let inclusive = true;
|
|
227
|
+
const batchSize = Math.max(limit * 4, 50);
|
|
228
|
+
|
|
229
|
+
for (let round = 0; round < 50 && nextCursor === null; round++) {
|
|
230
|
+
const batch = await deps.db
|
|
231
|
+
.select({ row: messageLogs, ts: tsText })
|
|
232
|
+
.from(messageLogs)
|
|
233
|
+
.where(
|
|
234
|
+
and(
|
|
235
|
+
...conditions,
|
|
236
|
+
scanFrom
|
|
237
|
+
? sql`${rowKey} ${inclusive ? sql`<=` : sql`<`} ${position(scanFrom.ts, scanFrom.id)}`
|
|
238
|
+
: undefined,
|
|
239
|
+
),
|
|
240
|
+
)
|
|
241
|
+
.orderBy(desc(messageLogs.timestamp), desc(messageLogs.id))
|
|
242
|
+
.limit(batchSize);
|
|
243
|
+
|
|
244
|
+
const fresh = [...new Set(batch.map((b) => b.row.taskId))].filter((t) => !rowsByTask.has(t));
|
|
245
|
+
const listedEarlier = new Set<string>();
|
|
246
|
+
if (start && fresh.length > 0) {
|
|
247
|
+
const newer = await deps.db
|
|
248
|
+
.selectDistinct({ taskId: messageLogs.taskId })
|
|
249
|
+
.from(messageLogs)
|
|
250
|
+
.where(
|
|
251
|
+
and(
|
|
252
|
+
...conditions,
|
|
253
|
+
inArray(messageLogs.taskId, fresh),
|
|
254
|
+
sql`${rowKey} > ${position(start.ts, start.id)}`,
|
|
255
|
+
),
|
|
256
|
+
);
|
|
257
|
+
for (const r of newer) listedEarlier.add(r.taskId);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
for (const { row, ts } of batch) {
|
|
261
|
+
if (listedEarlier.has(row.taskId)) continue;
|
|
262
|
+
let rows = rowsByTask.get(row.taskId);
|
|
263
|
+
if (!rows) {
|
|
264
|
+
if (order.length === limit) {
|
|
265
|
+
nextCursor = encodeLogCursor(ts, row.id);
|
|
266
|
+
break;
|
|
267
|
+
}
|
|
268
|
+
rows = [];
|
|
269
|
+
order.push(row.taskId);
|
|
270
|
+
rowsByTask.set(row.taskId, rows);
|
|
271
|
+
}
|
|
272
|
+
rows.push(row);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
if (batch.length < batchSize) break;
|
|
276
|
+
const last = batch[batch.length - 1]!;
|
|
277
|
+
scanFrom = { ts: last.ts, id: last.row.id };
|
|
278
|
+
inclusive = false;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// The latest outcome, rather than the dispatch that preceded it.
|
|
282
|
+
const deduplicatedLogs = order.map((taskId) => {
|
|
283
|
+
const rows = rowsByTask.get(taskId)!;
|
|
284
|
+
return rows.find((r) => r.status !== "dispatched") ?? rows[0]!;
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
sendJson(res, 200, { logs: deduplicatedLogs, nextCursor });
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
async function getNotificationStatus(
|
|
291
|
+
req: IncomingMessage,
|
|
292
|
+
res: ServerResponse,
|
|
293
|
+
ctx: RouteContext,
|
|
294
|
+
): Promise<void> {
|
|
295
|
+
const { taskId } = ctx.params;
|
|
296
|
+
if (!taskId) return sendJson(res, 400, { error: "missing_task_id" });
|
|
297
|
+
|
|
298
|
+
const logs = await deps.db
|
|
299
|
+
.select()
|
|
300
|
+
.from(messageLogs)
|
|
301
|
+
.where(and(eq(messageLogs.taskId, taskId), eq(messageLogs.projectId, ctx.projectId!)))
|
|
302
|
+
.orderBy(desc(messageLogs.timestamp));
|
|
303
|
+
|
|
304
|
+
if (logs.length === 0) {
|
|
305
|
+
// It might still be pending in Redis or scheduled
|
|
306
|
+
return sendJson(res, 404, {
|
|
307
|
+
error: "not_found",
|
|
308
|
+
message: "Task not found or not processed yet",
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// Newest first, so `status` is the latest known state rather than whichever
|
|
313
|
+
// row Postgres happened to return first.
|
|
314
|
+
sendJson(res, 200, { status: logs[0]?.status, logs });
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
async function getScheduledMessages(
|
|
318
|
+
_req: IncomingMessage,
|
|
319
|
+
res: ServerResponse,
|
|
320
|
+
ctx: RouteContext,
|
|
321
|
+
): Promise<void> {
|
|
322
|
+
const limit = parseLimit(ctx, 50);
|
|
323
|
+
const cursor = getQueryParam(ctx, "cursor");
|
|
324
|
+
const channel = getQueryParam(ctx, "channel");
|
|
325
|
+
|
|
326
|
+
const conditions = [sql`(payload->>'projectId') = ${ctx.projectId!}`];
|
|
327
|
+
if (cursor) {
|
|
328
|
+
conditions.push(sql`task_id > ${cursor}`);
|
|
329
|
+
}
|
|
330
|
+
if (channel) {
|
|
331
|
+
conditions.push(sql`(payload->>'channel') = ${channel}`);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const rows = await deps.db
|
|
335
|
+
.select()
|
|
336
|
+
.from(scheduledPayloads)
|
|
337
|
+
.where(and(...conditions))
|
|
338
|
+
.orderBy(scheduledPayloads.taskId)
|
|
339
|
+
.limit(limit + 1);
|
|
340
|
+
|
|
341
|
+
const hasNext = rows.length > limit;
|
|
342
|
+
const scheduled = hasNext ? rows.slice(0, limit) : rows;
|
|
343
|
+
const nextCursor =
|
|
344
|
+
hasNext && scheduled.length > 0 ? scheduled[scheduled.length - 1]!.taskId : null;
|
|
345
|
+
|
|
346
|
+
sendJson(res, 200, { scheduled, nextCursor });
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
return {
|
|
350
|
+
notify,
|
|
351
|
+
cancelNotification,
|
|
352
|
+
getNotificationLogs,
|
|
353
|
+
getNotificationStatus,
|
|
354
|
+
getScheduledMessages,
|
|
355
|
+
};
|
|
356
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { randomBytes, createHash } from "node:crypto";
|
|
2
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
3
|
+
import { PUBSUB_CHANNELS, UpdateProjectSchema } from "@/contracts/index.js";
|
|
4
|
+
import { readJsonBody, sendJson, sendNoContent, sendValidationError } from "../http.js";
|
|
5
|
+
import type { RouteContext } from "../router.js";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { type Deps, isUuid } from "./shared.js";
|
|
8
|
+
|
|
9
|
+
export function createProjectsHandlers(deps: Deps) {
|
|
10
|
+
const { logger } = deps;
|
|
11
|
+
|
|
12
|
+
async function listProjects(
|
|
13
|
+
req: IncomingMessage,
|
|
14
|
+
res: ServerResponse,
|
|
15
|
+
_ctx: RouteContext,
|
|
16
|
+
): Promise<void> {
|
|
17
|
+
const projects = await deps.projectRepo.list();
|
|
18
|
+
sendJson(res, 200, { projects });
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function deleteProject(
|
|
22
|
+
req: IncomingMessage,
|
|
23
|
+
res: ServerResponse,
|
|
24
|
+
ctx: RouteContext,
|
|
25
|
+
): Promise<void> {
|
|
26
|
+
const id = ctx.params.id!;
|
|
27
|
+
const deleted = isUuid(id) && (await deps.projectRepo.delete(id));
|
|
28
|
+
if (!deleted) return sendJson(res, 404, { error: "project_not_found" });
|
|
29
|
+
|
|
30
|
+
sendNoContent(res);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function updateProject(
|
|
34
|
+
req: IncomingMessage,
|
|
35
|
+
res: ServerResponse,
|
|
36
|
+
ctx: RouteContext,
|
|
37
|
+
): Promise<void> {
|
|
38
|
+
const id = ctx.params.id!;
|
|
39
|
+
const parsed = UpdateProjectSchema.safeParse(await readJsonBody(req));
|
|
40
|
+
|
|
41
|
+
if (!parsed.success) return sendValidationError(res, parsed.error);
|
|
42
|
+
|
|
43
|
+
const updated = isUuid(id) && (await deps.projectRepo.updateSettings(id, parsed.data));
|
|
44
|
+
if (!updated) return sendJson(res, 404, { error: "project_not_found" });
|
|
45
|
+
|
|
46
|
+
// Drop the engine's cached throttle overrides so the change applies to the
|
|
47
|
+
// next notification instead of waiting out the cache TTL.
|
|
48
|
+
await deps.redis.native.publish(PUBSUB_CHANNELS.PROJECT_INVALIDATED, id);
|
|
49
|
+
|
|
50
|
+
// rateLimitRpm is read through the API's auth cache, which is keyed by token
|
|
51
|
+
// hash rather than project — dropping the whole cache is the only way to
|
|
52
|
+
// pick up a new limit promptly. Project updates are rare admin operations.
|
|
53
|
+
if (parsed.data.rateLimitRpm !== undefined) {
|
|
54
|
+
await deps.redis.native.publish(PUBSUB_CHANNELS.API_KEY_INVALIDATED, "*");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
logger.info({ projectId: id }, "project settings updated");
|
|
58
|
+
sendJson(res, 200, { id });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function createProjectKey(
|
|
62
|
+
req: IncomingMessage,
|
|
63
|
+
res: ServerResponse,
|
|
64
|
+
ctx: RouteContext,
|
|
65
|
+
): Promise<void> {
|
|
66
|
+
const id = ctx.params.id!;
|
|
67
|
+
const parsed = z
|
|
68
|
+
.object({ role: z.enum(["admin", "read_only"]).default("admin") })
|
|
69
|
+
.safeParse(await readJsonBody(req));
|
|
70
|
+
const role = parsed.success ? parsed.data.role : "admin";
|
|
71
|
+
|
|
72
|
+
// A key for a project that does not exist would fail the foreign key.
|
|
73
|
+
if (!isUuid(id) || !(await deps.projectRepo.findThrottleSettings(id))) {
|
|
74
|
+
return sendJson(res, 404, { error: "project_not_found" });
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const apiKey = `nk_live_${randomBytes(32).toString("hex")}`;
|
|
78
|
+
const apiKeyHash = createHash("sha256").update(apiKey).digest("hex");
|
|
79
|
+
|
|
80
|
+
const key = await deps.projectRepo.createApiKey(id, apiKeyHash, role);
|
|
81
|
+
sendJson(res, 201, { id: key.id, apiKey, role });
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function listProjectKeys(
|
|
85
|
+
req: IncomingMessage,
|
|
86
|
+
res: ServerResponse,
|
|
87
|
+
ctx: RouteContext,
|
|
88
|
+
): Promise<void> {
|
|
89
|
+
const id = ctx.params.id!;
|
|
90
|
+
if (!isUuid(id)) return sendJson(res, 404, { error: "project_not_found" });
|
|
91
|
+
const keys = await deps.projectRepo.listApiKeys(id);
|
|
92
|
+
sendJson(res, 200, { keys });
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function deleteProjectKey(
|
|
96
|
+
req: IncomingMessage,
|
|
97
|
+
res: ServerResponse,
|
|
98
|
+
ctx: RouteContext,
|
|
99
|
+
): Promise<void> {
|
|
100
|
+
const { id, keyId } = ctx.params;
|
|
101
|
+
const deleted = isUuid(id) && isUuid(keyId) && (await deps.projectRepo.deleteApiKey(id, keyId));
|
|
102
|
+
if (!deleted) return sendJson(res, 404, { error: "key_not_found" });
|
|
103
|
+
|
|
104
|
+
await deps.redis.native.publish(PUBSUB_CHANNELS.API_KEY_INVALIDATED, "*");
|
|
105
|
+
sendNoContent(res);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
return {
|
|
109
|
+
listProjects,
|
|
110
|
+
deleteProject,
|
|
111
|
+
updateProject,
|
|
112
|
+
createProjectKey,
|
|
113
|
+
listProjectKeys,
|
|
114
|
+
deleteProjectKey,
|
|
115
|
+
};
|
|
116
|
+
}
|