Open History to see the last commit
1/**
2 * Changes feed (PLAN.md task 4.5) — the polling-friendly alternative to
3 * webhooks. Cursor-paginated, newest first; the cursor is an opaque
4 * (createdAt, id) keyset token, so pages stay stable while new changes land.
5 */
6import { and, desc, eq, gte, lt, or } from 'drizzle-orm'
7import type { SQL } from 'drizzle-orm'
8
9import type { Db } from '#/db/index.ts'
10import { halGet } from '#/server/hal.ts'
11import type { HalLink } from '#/server/hal.ts'
12import { changes } from '#/db/schema.ts'
13import type { ChangeType } from '#/db/schema.ts'
14
15export interface ChangesQuery {
16 since?: number
17 provider?: string
18 type?: ChangeType
19 cursor?: string
20 limit?: number
21}
22
23export const MAX_CHANGES_LIMIT = 200
24const DEFAULT_LIMIT = 50
25
26interface Cursor {
27 createdAt: number
28 id: string
29}
30
31export function encodeCursor(cursor: Cursor): string {
32 return btoa(`${String(cursor.createdAt)}:${cursor.id}`)
33}
34
35export function decodeCursor(token: string): Cursor | null {
36 try {
37 const [createdAt, ...idParts] = atob(token).split(':')
38 const time = Number(createdAt)
39 const id = idParts.join(':')
40 if (!Number.isInteger(time) || id === '') return null
41 return { createdAt: time, id }
42 } catch {
43 return null
44 }
45}
46
47export type ListChangesOutcome =
48 | {
49 ok: true
50 result: {
51 count: number
52 changes: Array<typeof changes.$inferSelect>
53 nextCursor: string | null
54 _links: { self: HalLink; next?: HalLink }
55 }
56 }
57 | { ok: false; status: number; code: string; message: string }
58
59export async function listChanges(
60 db: Db,
61 query: ChangesQuery,
62): Promise<ListChangesOutcome> {
63 const limit = Math.min(
64 Math.max(query.limit ?? DEFAULT_LIMIT, 1),
65 MAX_CHANGES_LIMIT,
66 )
67
68 const conditions: Array<SQL> = []
69 if (query.since !== undefined) {
70 conditions.push(gte(changes.createdAt, query.since))
71 }
72 if (query.provider) conditions.push(eq(changes.providerId, query.provider))
73 if (query.type) conditions.push(eq(changes.type, query.type))
74
75 if (query.cursor !== undefined) {
76 const cursor = decodeCursor(query.cursor)
77 if (!cursor) {
78 return {
79 ok: false,
80 status: 400,
81 code: 'invalid_cursor',
82 message:
83 'Invalid cursor. Use the nextCursor value from a previous response.',
84 }
85 }
86 const keyset = or(
87 lt(changes.createdAt, cursor.createdAt),
88 and(eq(changes.createdAt, cursor.createdAt), lt(changes.id, cursor.id)),
89 )
90 if (keyset) conditions.push(keyset)
91 }
92
93 // Fetch one extra row to know whether another page exists.
94 const rows = await db
95 .select()
96 .from(changes)
97 .where(conditions.length > 0 ? and(...conditions) : undefined)
98 .orderBy(desc(changes.createdAt), desc(changes.id))
99 .limit(limit + 1)
100
101 const page = rows.slice(0, limit)
102 const last = page[page.length - 1]
103 const nextCursor =
104 rows.length > limit && last
105 ? encodeCursor({ createdAt: last.createdAt, id: last.id })
106 : null
107
108 const params = new URLSearchParams()
109 if (query.since !== undefined) params.set('since', String(query.since))
110 if (query.provider) params.set('provider', query.provider)
111 if (query.type) params.set('type', query.type)
112 const baseParams = params.toString()
113 const self = `/v1/changes${baseParams ? `?${baseParams}` : ''}`
114
115 return {
116 ok: true,
117 result: {
118 count: page.length,
119 changes: page,
120 nextCursor,
121 _links: {
122 self: halGet(self),
123 ...(nextCursor
124 ? {
125 next: halGet(
126 `/v1/changes?${baseParams ? `${baseParams}&` : ''}cursor=${encodeURIComponent(nextCursor)}`,
127 ),
128 }
129 : {}),
130 },
131 },
132 }
133}