Skip to content
refs
266 lines · 13.8 KBRaw
1import { now } from "./auth.ts";
2import type { Actor } from "./contract/actor.ts";
3import type { EventOf } from "./contract/events.ts";
4import type { Page } from "./contract/common.ts";
5import { LABEL_COLORS, MAX_LABEL_NAME_LENGTH, TASK_LIST_LIMIT } from "./contract/limits.ts";
6import type { Label, LabelColor, LabelWithUsage, TaskCounts, TaskDetail, TaskStatus, TaskSummary } from "./contract/views.ts";
7import { recordEvent, taskStream } from "./events.ts";
8import { renderMarkdown } from "./markdown.ts";
9
10export { bodyError, requiredBodyError, titleError } from "./text.ts";
11
12export interface TaskRecord {
13 id: number;
14 repo_id: string;
15 repo_name: string;
16 number: number;
17 title: string;
18 body: string;
19 status: TaskStatus;
20 author_id: string;
21 author: string;
22 assignee_id: string | null;
23 assignee: string | null;
24 created_at: number;
25 updated_at: number;
26 closed_at: number | null;
27}
28
29type ListRow = TaskRecord & { comments: number; labels_json: string };
30
31const SELECT_TASK =
32 "SELECT t.*, (SELECT slug FROM namespaces WHERE id = r.namespace_id) || '/' || r.name AS repo_name, a.name AS author, u.name AS assignee FROM tasks t JOIN repos r ON r.id = t.repo_id JOIN users a ON a.id = t.author_id LEFT JOIN users u ON u.id = t.assignee_id";
33
34const SELECT_LIST = SELECT_TASK.replace(
35 "SELECT t.*",
36 "SELECT t.*, (SELECT count(*) FROM events e WHERE e.stream = 'task:' || t.id AND e.kind = 'task.commented') AS comments, (SELECT json_group_array(json_object('id', l.id, 'name', l.name, 'color', l.color, 'description', l.description)) FROM task_labels tl JOIN labels l ON l.id = tl.label_id WHERE tl.task_id = t.id) AS labels_json",
37);
38
39const NEXT_NUMBER = "(SELECT coalesce(max(n), 0) + 1 FROM (SELECT number AS n FROM tasks WHERE repo_id = ?1 UNION ALL SELECT number FROM task_redirects WHERE repo_id = ?1))";
40
41function sortLabels(labels: Label[]): Label[] {
42 return labels.sort((a, b) => a.name.localeCompare(b.name));
43}
44
45export function toSummary(row: TaskRecord, labels: Label[], comments: number): TaskSummary {
46 return {
47 number: row.number,
48 repo: row.repo_name,
49 title: row.title,
50 status: row.status,
51 author: { id: row.author_id, name: row.author },
52 assignee: row.assignee_id ? { id: row.assignee_id, name: row.assignee ?? "Former member" } : null,
53 labels,
54 comments,
55 createdAt: row.created_at,
56 closedAt: row.closed_at,
57 };
58}
59
60export function toDetail(row: TaskRecord, labels: Label[], comments: number): TaskDetail {
61 return { ...toSummary(row, labels, comments), body: row.body, bodyHtml: row.body ? renderMarkdown(row.body) : null, updatedAt: row.updated_at };
62}
63
64export interface TaskFilter {
65 namespaceId: string;
66 status: TaskStatus;
67 repoId?: string;
68 label?: string;
69 assigneeId?: string;
70 cursor?: string;
71 limit?: number;
72}
73
74export async function listTasks(db: D1Database, filter: TaskFilter): Promise<{ page: Page<TaskSummary>; counts: TaskCounts }> {
75 const conditions: string[] = ["t.repo_id IN (SELECT id FROM repos WHERE namespace_id = ?)"];
76 const bindings: (string | number)[] = [filter.namespaceId];
77 if (filter.repoId) {
78 conditions.push("t.repo_id = ?");
79 bindings.push(filter.repoId);
80 }
81 if (filter.assigneeId) {
82 conditions.push("t.assignee_id = ?");
83 bindings.push(filter.assigneeId);
84 }
85 if (filter.label) {
86 conditions.push("EXISTS (SELECT 1 FROM task_labels tl JOIN labels l ON l.id = tl.label_id WHERE tl.task_id = t.id AND l.name = ?)");
87 bindings.push(filter.label);
88 }
89 const scope = conditions.map((condition) => ` AND ${condition}`).join("");
90 const limit = Math.min(Math.max(filter.limit ?? TASK_LIST_LIMIT, 1), TASK_LIST_LIMIT);
91 const cursor = Number(filter.cursor);
92 const after = Number.isInteger(cursor) && cursor > 0 ? ` AND t.id < ${cursor}` : "";
93
94 const [counts, rows] = await db.batch([
95 db.prepare(`SELECT status, count(*) AS total FROM tasks t WHERE 1 = 1${scope} GROUP BY status`).bind(...bindings),
96 db.prepare(`${SELECT_LIST} WHERE t.status = ?${scope}${after} ORDER BY t.id DESC LIMIT ${limit + 1}`).bind(filter.status, ...bindings),
97 ]);
98 const totals = Object.fromEntries((counts.results as { status: TaskStatus; total: number }[]).map((row) => [row.status, row.total]));
99 const found = rows.results as ListRow[];
100 const items = found.slice(0, limit).map(({ labels_json, comments, ...row }) => toSummary(row, sortLabels(JSON.parse(labels_json) as Label[]), comments));
101 const next = found.length > limit ? String(found[limit - 1].id) : null;
102 return { page: { items, next }, counts: { open: totals.open ?? 0, closed: totals.closed ?? 0 } };
103}
104
105/** Finds a task by repository and number, following the redirect left by a transfer. */
106export async function findTaskRecord(db: D1Database, repoId: string, number: number): Promise<TaskRecord | null> {
107 if (!Number.isInteger(number) || number < 1) return null;
108 const direct = await db.prepare(`${SELECT_TASK} WHERE t.repo_id = ? AND t.number = ?`).bind(repoId, number).first<TaskRecord>();
109 if (direct) return direct;
110 return db.prepare(`${SELECT_TASK} WHERE t.id = (SELECT task_id FROM task_redirects WHERE repo_id = ? AND number = ?)`).bind(repoId, number).first<TaskRecord>();
111}
112
113export async function taskExtras(db: D1Database, taskId: number): Promise<{ labels: Label[]; comments: number }> {
114 const [labels, comments] = await db.batch([
115 db.prepare("SELECT l.id, l.name, l.color, l.description FROM task_labels tl JOIN labels l ON l.id = tl.label_id WHERE tl.task_id = ? ORDER BY l.name COLLATE NOCASE").bind(taskId),
116 db.prepare("SELECT count(*) AS total FROM events WHERE stream = ? AND kind = 'task.commented'").bind(taskStream(taskId)),
117 ]);
118 return { labels: labels.results as Label[], comments: (comments.results[0] as { total: number }).total };
119}
120
121export async function memberName(db: D1Database, repoId: string, userId: string): Promise<string | null> {
122 return db
123 .prepare("SELECT u.name FROM users u JOIN memberships m ON m.user_id = u.id JOIN repos r ON r.namespace_id = m.namespace_id WHERE r.id = ? AND u.id = ?")
124 .bind(repoId, userId)
125 .first<string>("name");
126}
127
128export async function createTaskRecord(
129 db: D1Database,
130 actor: Actor,
131 input: { repoId: string; title: string; body: string; authorId: string; assigneeId: string | null; labelIds: readonly string[] },
132): Promise<{ id: number; number: number }> {
133 const at = now();
134 const [inserted] = await db.batch<{ id: number; number: number }>([
135 db
136 .prepare(`INSERT INTO tasks (repo_id, number, title, body, author_id, assignee_id, created_at, updated_at) VALUES (?1, ${NEXT_NUMBER}, ?2, ?3, ?4, ?5, ?6, ?6) RETURNING id, number`)
137 .bind(input.repoId, input.title, input.body, input.authorId, input.assigneeId, at),
138 recordEvent(db, actor, { newest: "task", repoId: input.repoId }, "task.opened", { title: input.title }, at),
139 ...input.labelIds.map((labelId) =>
140 db
141 .prepare("INSERT OR IGNORE INTO task_labels (task_id, label_id) SELECT (SELECT max(id) FROM tasks WHERE repo_id = ?3), l.id FROM labels l JOIN repos r ON r.namespace_id = l.namespace_id WHERE l.id = ?2 AND r.id = ?3")
142 .bind(null, labelId, input.repoId),
143 ),
144 ]);
145 return inserted.results[0];
146}
147
148function touch(db: D1Database, taskId: number, at: number): D1PreparedStatement {
149 return db.prepare("UPDATE tasks SET updated_at = ? WHERE id = ?").bind(at, taskId);
150}
151
152function statusChange(db: D1Database, actor: Actor, task: TaskRecord, status: TaskStatus, at: number): D1PreparedStatement[] {
153 return [
154 db.prepare("UPDATE tasks SET status = ?, closed_at = ?, updated_at = ? WHERE id = ?").bind(status, status === "closed" ? at : null, at, task.id),
155 recordEvent(db, actor, taskStream(task.id), status === "closed" ? "task.closed" : "task.reopened", {}, at),
156 ];
157}
158
159export async function addComment(db: D1Database, actor: Actor, task: TaskRecord, body: string, then?: TaskStatus): Promise<number> {
160 const at = now();
161 const [inserted] = await db.batch([
162 recordEvent(db, actor, taskStream(task.id), "task.commented", { body }, at),
163 touch(db, task.id, at),
164 ...(then && then !== task.status ? statusChange(db, actor, task, then, at) : []),
165 ]);
166 return inserted.meta.last_row_id;
167}
168
169export async function setStatus(db: D1Database, actor: Actor, task: TaskRecord, status: TaskStatus): Promise<void> {
170 if (status !== task.status) await db.batch(statusChange(db, actor, task, status, now()));
171}
172
173export async function rename(db: D1Database, actor: Actor, task: TaskRecord, title: string): Promise<void> {
174 if (title === task.title) return;
175 const at = now();
176 await db.batch([
177 db.prepare("UPDATE tasks SET title = ?, updated_at = ? WHERE id = ?").bind(title, at, task.id),
178 recordEvent(db, actor, taskStream(task.id), "task.renamed", { from: task.title, to: title }, at),
179 ]);
180}
181
182export async function describe(db: D1Database, task: TaskRecord, body: string): Promise<void> {
183 await db.prepare("UPDATE tasks SET body = ?, updated_at = ? WHERE id = ?").bind(body, now(), task.id).run();
184}
185
186export async function assign(db: D1Database, actor: Actor, task: TaskRecord, assignee: { id: string; name: string } | null): Promise<void> {
187 if ((assignee?.id ?? null) === task.assignee_id) return;
188 const at = now();
189 const previous = { id: task.assignee_id ?? "", name: task.assignee ?? "Former member" };
190 await db.batch([
191 db.prepare("UPDATE tasks SET assignee_id = ?, updated_at = ? WHERE id = ?").bind(assignee?.id ?? null, at, task.id),
192 assignee ? recordEvent(db, actor, taskStream(task.id), "task.assigned", { assignee }, at) : recordEvent(db, actor, taskStream(task.id), "task.unassigned", { assignee: previous }, at),
193 ]);
194}
195
196export async function recordHandOff(db: D1Database, actor: Actor, task: TaskRecord, handed: EventOf<"task.handed">["data"]): Promise<void> {
197 const at = now();
198 await db.batch([recordEvent(db, actor, taskStream(task.id), "task.handed", handed, at), touch(db, task.id, at)]);
199}
200
201/** Moves the task to another repository under that repository's next number, leaving a redirect at its old address. */
202export async function transfer(db: D1Database, actor: Actor, task: TaskRecord, target: { id: string; name: string }): Promise<{ repo: string; number: number }> {
203 const at = now();
204 await db.batch([
205 db.prepare("INSERT OR REPLACE INTO task_redirects (repo_id, number, task_id) VALUES (?, ?, ?)").bind(task.repo_id, task.number, task.id),
206 db.prepare(`UPDATE tasks SET repo_id = ?1, number = ${NEXT_NUMBER}, updated_at = ?2 WHERE id = ?3`).bind(target.id, at, task.id),
207 ]);
208 const number = (await db.prepare("SELECT number FROM tasks WHERE id = ?").bind(task.id).first<number>("number"))!;
209 await recordEvent(db, actor, taskStream(task.id), "task.transferred", { from: { repo: task.repo_name, number: task.number }, to: { repo: target.name, number } }, at).run();
210 return { repo: target.name, number };
211}
212
213export async function setLabels(db: D1Database, actor: Actor, task: TaskRecord, labelIds: readonly string[]): Promise<void> {
214 const { labels: current } = await taskExtras(db, task.id);
215 const known = new Map((
216 await db
217 .prepare("SELECT l.id, l.name, l.color FROM labels l JOIN repos r ON r.namespace_id = l.namespace_id WHERE r.id = ?")
218 .bind(task.repo_id)
219 .all<{ id: string; name: string; color: LabelColor }>()
220 ).results.map((label) => [label.id, label]));
221 const wanted = new Set(labelIds.filter((id) => known.has(id)));
222 const added = [...wanted].filter((id) => !current.some((label) => label.id === id));
223 const removed = current.filter((label) => !wanted.has(label.id));
224 if (!added.length && !removed.length) return;
225
226 const at = now();
227 await db.batch([
228 ...added.map((id) => db.prepare("INSERT OR IGNORE INTO task_labels (task_id, label_id) VALUES (?, ?)").bind(task.id, id)),
229 ...removed.map((label) => db.prepare("DELETE FROM task_labels WHERE task_id = ? AND label_id = ?").bind(task.id, label.id)),
230 ...added.map((id) => recordEvent(db, actor, taskStream(task.id), "task.labeled", { label: { name: known.get(id)!.name, color: known.get(id)!.color } }, at)),
231 ...removed.map((label) => recordEvent(db, actor, taskStream(task.id), "task.unlabeled", { label: { name: label.name, color: label.color } }, at)),
232 touch(db, task.id, at),
233 ]);
234}
235
236export async function editComment(db: D1Database, task: TaskRecord, commentId: number, authorId: string, body: string): Promise<boolean> {
237 const result = await db
238 .prepare("UPDATE events SET data = ?, edited_at = ? WHERE id = ? AND stream = ? AND kind = 'task.commented' AND actor_kind = 'human' AND actor_id = ?")
239 .bind(JSON.stringify({ body }), now(), commentId, taskStream(task.id), authorId)
240 .run();
241 return result.meta.changes > 0;
242}
243
244export async function deleteComment(db: D1Database, task: TaskRecord, commentId: number, actorId: string, canModerate: boolean): Promise<boolean> {
245 const result = await db
246 .prepare("DELETE FROM events WHERE id = ? AND stream = ? AND kind = 'task.commented' AND (coalesce(on_behalf_of, actor_id) = ? OR ? = 1)")
247 .bind(commentId, taskStream(task.id), actorId, canModerate ? 1 : 0)
248 .run();
249 return result.meta.changes > 0;
250}
251
252export async function listLabels(db: D1Database, namespaceId: string): Promise<LabelWithUsage[]> {
253 const { results } = await db
254 .prepare(
255 "SELECT l.id, l.name, l.color, l.description, (SELECT count(*) FROM task_labels tl JOIN tasks t ON t.id = tl.task_id WHERE tl.label_id = l.id AND t.status = 'open') AS openTasks FROM labels l WHERE l.namespace_id = ? ORDER BY l.name COLLATE NOCASE",
256 )
257 .bind(namespaceId)
258 .all<LabelWithUsage>();
259 return results;
260}
261
262export function labelError(input: { name: string; color: string; description: string }): string | undefined {
263 if (!input.name || input.name.length > MAX_LABEL_NAME_LENGTH) return `Label names must be 1–${MAX_LABEL_NAME_LENGTH} characters.`;
264 if (!LABEL_COLORS.includes(input.color as LabelColor)) return "Pick one of the label colors.";
265 if (input.description.length > 200) return "Label descriptions must be at most 200 characters.";
266}