Swadhin Biswas feat(api): add runner, analytics, packages, and security services · 3/6/2026
28f7954
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
/**
* Notifications API - List, read, archive notifications
*/
import { type APIRoute } from 'astro';
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { eq, desc, and, or, isNull } from 'drizzle-orm';
import { getDatabase , schema } from "@/db";
import { notifications } from '@/db/schema';
import { getUserFromRequest } from '@/lib/auth';
import { success, unauthorized, serverError } from '@/lib/api';
import { scoreNotificationPriority } from '@/lib/notification-priority';
import {
channelEnabled,
computePersonalizationBoost,
getRoutingDecision,
type NotificationRouteChannel,
} from "@/lib/notification-routing";
const BLOCKING_NOTIFICATION_TYPES = [
"ci_failed",
"review_request",
"security_alert",
"merge_conflict",
"merge_blocked",
];
const BLOCKING_NOTIFICATION_REASONS = [
"ci_failed",
"review_requested",
"security_alert",
"merge_conflict",
"merge_blocked",
];
export const GET: APIRoute = async ({ request, url }) => {
try {
const tokenPayload = await getUserFromRequest(request);
if (!tokenPayload) {
return unauthorized();
}
const db = getDatabase() as NodePgDatabase<typeof schema>;
const filter = url.searchParams.get('filter') || 'unread';
const prioritize = url.searchParams.get("prioritize") === "true";
const personalize = url.searchParams.get("personalize") === "true";
const rawChannel = url.searchParams.get("channel");
const allowedChannels: NotificationRouteChannel[] = ["in_app", "email", "slack", "browser_push"];
const channelFilter = rawChannel && allowedChannels.includes(rawChannel as NotificationRouteChannel)
? (rawChannel as NotificationRouteChannel)
: null;
let conditions = [eq(notifications.userId, tokenPayload.userId)];
if (filter === 'unread') {
conditions.push(eq(notifications.isRead, false));
conditions.push(eq(notifications.isArchived, false));
} else if (filter === 'read') {
conditions.push(eq(notifications.isRead, true));
conditions.push(eq(notifications.isArchived, false));
} else if (filter === 'archived') {
conditions.push(eq(notifications.isArchived, true));
} else if (filter === 'blocking') {
conditions.push(eq(notifications.isArchived, false));
conditions.push(
or(
...BLOCKING_NOTIFICATION_TYPES.map((type) => eq(notifications.type, type)),
...BLOCKING_NOTIFICATION_REASONS.map((reason) => eq(notifications.reason, reason))
)!
);
} else {
// all - just exclude archived
conditions.push(eq(notifications.isArchived, false));
}
const notifs = (await db.query.notifications.findMany({
where: and(...conditions),
orderBy: [desc(notifications.createdAt)],
limit: 100,
with: {
actor: {
columns: { id: true, username: true, displayName: true, avatarUrl: true }
},
repository: {
columns: { id: true, name: true, slug: true }
},
},
})) || [];
const prefs = db.query.notificationPreferences
? await db.query.notificationPreferences.findMany({
where: and(
eq(schema.notificationPreferences.userId, tokenPayload.userId),
isNull(schema.notificationPreferences.repositoryId)
),
})
: [];
const recentHistory = (await db.query.notifications.findMany({
where: and(
eq(notifications.userId, tokenPayload.userId),
eq(notifications.isArchived, false)
),
orderBy: [desc(notifications.createdAt)],
limit: 500,
columns: { type: true, isRead: true },
})) || [];
const readByType: Record<string, number> = {};
const unreadByType: Record<string, number> = {};
let totalRead = 0;
let totalHistory = 0;
for (const item of recentHistory) {
const type = item.type || "unknown";
totalHistory++;
if (item.isRead) {
totalRead++;
readByType[type] = (readByType[type] || 0) + 1;
} else {
unreadByType[type] = (unreadByType[type] || 0) + 1;
}
}
const baselineReadRatio = totalHistory > 0 ? totalRead / totalHistory : 0.5;
const notificationsWithPriority = notifs.map((notification) => {
const scored = scoreNotificationPriority(notification);
const routing = getRoutingDecision(notification.type, prefs as any);
const personalizationBoost = personalize
? computePersonalizationBoost({
eventType: notification.type,
readByType,
unreadByType,
baselineReadRatio,
})
: 0;
const priorityScore = Math.max(0, scored.score + personalizationBoost);
return {
...notification,
priority: scored.priority,
priorityScore,
isBlocking: scored.isBlocking,
personalizationBoost,
routeChannels: routing.channels,
primaryRouteChannel: routing.primaryChannel,
};
});
const routedNotifications = channelFilter
? notificationsWithPriority.filter((item) =>
channelEnabled(channelFilter, {
channels: item.routeChannels,
primaryChannel: item.primaryRouteChannel,
})
)
: notificationsWithPriority;
if (prioritize) {
routedNotifications.sort((a, b) => {
if (b.priorityScore !== a.priorityScore) return b.priorityScore - a.priorityScore;
return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
});
}
// Get unread count
const unreadNotifs = (await db.query.notifications.findMany({
where: and(
eq(notifications.userId, tokenPayload.userId),
eq(notifications.isRead, false),
eq(notifications.isArchived, false)
),
})) || [];
return success({
notifications: routedNotifications,
unreadCount: unreadNotifs.length,
routing: {
channelFilter: channelFilter || null,
personalized: personalize,
},
});
} catch (e) {
console.error('Error fetching notifications:', e);
return serverError('Failed to fetch notifications');
}
};