diff --git a/api/project-tickets.test.ts b/api/project-tickets.test.ts index 5a532fc..b1b7785 100644 --- a/api/project-tickets.test.ts +++ b/api/project-tickets.test.ts @@ -5,10 +5,13 @@ import { createGithubProvider } from './github-provider.ts' import { createJiraProvider } from './jira-provider.ts' import { filterTickets, + getProjectTicket, listProjectTickets, + toTicketDetailRow, toTicketRow, } from './project-tickets.ts' import { + type Comment, groupIntoTickets, type Person, type ProjectScope, @@ -214,3 +217,130 @@ describe('toTicketRow', () => { assertEquals('discussion' in row, false) }) }) + +const threadProvider = ( + id: Provider['id'], + items: WorkItem[], + thread: (item: WorkItem) => Comment[], +) => { + const asked: string[] = [] + const provider: Provider = { + id, + list: () => Promise.resolve(items), + comments: (item) => { + asked.push(item.externalId) + return Promise.resolve(thread(item)) + }, + } + return { provider, asked } +} + +describe('getProjectTicket', () => { + const jiraSide = threadProvider( + 'jira', + [jira('TNT-1'), jira('TNT-2')], + (item) => [ + { + source: 'jira', + author: 'ada@example.com', + body: `description of ${item.externalId}`, + createdAt: 100, + }, + { + source: 'jira', + author: 'ada@example.com', + body: 'jira comment', + createdAt: 400, + }, + ], + ) + const githubSide = threadProvider( + 'github', + [pr('TNT-1 Fix it'), pr('TNT-1 Follow-up', { externalId: 'gh-2' })], + (item) => [ + { + source: 'github', + author: 'grace', + body: `review on ${item.externalId}`, + createdAt: item.externalId === 'gh-2' ? 300 : 200, + }, + { source: 'github', author: 'stranger', body: 'undated' }, + ], + ) + const load = (key: string) => + getProjectTicket( + { jiraProjectKey: 'TNT' }, + key, + [jiraSide.provider, githubSide.provider], + () => Promise.resolve(directory), + ) + + it('merges the comments of every linked item, oldest first', async () => { + jiraSide.asked.length = 0 + githubSide.asked.length = 0 + const ticket = await load('TNT1') + + assertEquals(ticket?.key, 'TNT1') + assertEquals(jiraSide.asked, ['jira-TNT-1']) + assertEquals(githubSide.asked.sort(), ['gh-2', 'gh-TNT-1 Fix it']) + assertEquals(ticket?.discussion.map((comment) => comment.body), [ + 'description of jira-TNT-1', + 'review on gh-TNT-1 Fix it', + 'review on gh-2', + 'jira comment', + 'undated', + 'undated', + ]) + }) + + it('resolves comment authors against the team directory', async () => { + const ticket = await load('TNT1') + const authors = ticket?.discussion.map((comment) => comment.author?.id) + assertEquals(authors, ['p1', 'p2', 'p2', 'p1', undefined, undefined]) + }) + + it('finds a ticket from any key notation', async () => { + assertEquals((await load('tnt-2'))?.key, 'TNT2') + }) + + it('finds an unkeyed ticket by its exact key', async () => { + const side = threadProvider('github', [pr('Bump deps')], () => []) + const ticket = await getProjectTicket( + {}, + 'github:gh-Bump deps', + [side.provider], + () => Promise.resolve([]), + ) + assertEquals(ticket?.title, 'Bump deps') + assertEquals(ticket?.discussion, []) + }) + + it('returns undefined for an unknown key', async () => { + assertEquals(await load('TNT-999'), undefined) + assertEquals(await load('nonsense'), undefined) + }) +}) + +describe('toTicketDetailRow', () => { + it('only exposes resolved authors, never the raw source identity', async () => { + const side = threadProvider('jira', [jira('TNT-1')], () => [ + { source: 'jira', author: 'ada@example.com', body: 'hi', createdAt: 1 }, + { source: 'jira', author: 'nobody@example.com', body: 'yo' }, + ]) + const ticket = await getProjectTicket( + {}, + 'TNT-1', + [side.provider], + () => Promise.resolve(directory), + ) + + const row = toTicketDetailRow(ticket!) + + assertEquals(row.discussion.map((comment) => comment.author), [ + { id: 'p1', name: 'Ada Lovelace' }, + undefined, + ]) + assertEquals(JSON.stringify(row).includes('@example.com'), false) + assertEquals(row.items.every((item) => !('raw' in item)), true) + }) +}) diff --git a/api/project-tickets.ts b/api/project-tickets.ts index b67c9d9..a83f3f3 100644 --- a/api/project-tickets.ts +++ b/api/project-tickets.ts @@ -1,12 +1,17 @@ import { discordProvider } from './discord-provider.ts' import { githubProvider } from './github-provider.ts' import { jiraProvider } from './jira-provider.ts' +import { withListCache } from './provider-cache.ts' import { buildTeamDirectory } from './team-directory.ts' import { + type Comment, groupIntoTickets, + normalizeKey, type Person, + type PersonRef, type ProjectScope, type Provider, + resolvePerson, type Source, type Ticket, type TicketStatus, @@ -21,11 +26,13 @@ export type TicketFilters = { search?: string | null } +// list() goes through the cache, so neither the list nor the detail endpoint +// hits the STORE on every request; comments() are only fetched on open const ticketProviders: Provider[] = [ jiraProvider, githubProvider, discordProvider, -] +].map((provider) => withListCache(provider)) const ticketUpdatedAt = (ticket: Ticket): number => Math.max(0, ...ticket.items.map((item) => item.updatedAt ?? 0)) @@ -35,17 +42,85 @@ const ticketUpdatedAt = (ticket: Ticket): number => const byLatestActivity = (a: Ticket, b: Ticket): number => ticketUpdatedAt(b) - ticketUpdatedAt(a) || a.key.localeCompare(b.key) +const loadTickets = async ( + scope: ProjectScope, + providers: Provider[], + loadDirectory: () => Promise, +) => { + const [directory, ...results] = await Promise.all([ + loadDirectory(), + ...providers.map((provider) => provider.list(scope)), + ]) + return { directory, tickets: groupIntoTickets(results.flat(), directory) } +} + // each provider returns [] by itself when its scope field is missing export const listProjectTickets = async ( scope: ProjectScope, providers: Provider[] = ticketProviders, loadDirectory: () => Promise = buildTeamDirectory, ): Promise => { - const [directory, ...results] = await Promise.all([ - loadDirectory(), - ...providers.map((provider) => provider.list(scope)), - ]) - return groupIntoTickets(results.flat(), directory).sort(byLatestActivity) + const { tickets } = await loadTickets(scope, providers, loadDirectory) + return tickets.sort(byLatestActivity) +} + +// comments without a date go last, ties keep the provider order +const byCreatedAt = (a: Comment, b: Comment): number => { + if (a.createdAt === undefined) return b.createdAt === undefined ? 0 : 1 + if (b.createdAt === undefined) return -1 + return a.createdAt - b.createdAt +} + +// what a comment author is, per source (see each provider's toComment) +const authorRef = ({ source, author }: Comment): PersonRef | undefined => { + if (!author) return undefined + switch (source) { + case 'jira': + return { email: author } + case 'github': + return { login: author } + case 'discord': + return { discordId: author } + } +} + +export type TicketComment = Omit & { author?: Person } +export type TicketDetail = Omit & { + discussion: TicketComment[] +} + +// "tnt-393" finds TNT393, unkeyed tickets are found by their exact key +export const getProjectTicket = async ( + scope: ProjectScope, + key: string, + providers: Provider[] = ticketProviders, + loadDirectory: () => Promise = buildTeamDirectory, +): Promise => { + const { directory, tickets } = await loadTickets( + scope, + providers, + loadDirectory, + ) + const wanted = key.trim() + const normalized = normalizeKey(wanted) + const ticket = tickets.find((ticket) => ticket.key === wanted) ?? + (normalized + ? tickets.find((ticket) => ticket.key === normalized) + : undefined) + if (!ticket) return undefined + + const bySource = new Map(providers.map((provider) => [provider.id, provider])) + const threads = await Promise.all( + ticket.items.map((item) => + bySource.get(item.source)?.comments(item) ?? Promise.resolve([]) + ), + ) + const discussion = threads.flat().sort(byCreatedAt).map((comment) => { + const ref = authorRef(comment) + const author = ref ? resolvePerson(directory, ref) : undefined + return { ...comment, author } + }) + return { ...ticket, discussion } } const hasPerson = (persons: Person[], id: string): boolean => @@ -90,3 +165,15 @@ export const toTicketRow = (ticket: Ticket) => ({ assignees: ticket.assignees.map(toPersonRow), reviewers: ticket.reviewers.map(toPersonRow), }) + +// the author is only ever exposed as a resolved directory person +export const toTicketDetailRow = (ticket: TicketDetail) => ({ + ...toTicketRow({ ...ticket, discussion: [] }), + discussion: ticket.discussion.map((comment) => ({ + source: comment.source, + author: comment.author && toPersonRow(comment.author), + body: comment.body, + url: comment.url, + createdAt: comment.createdAt, + })), +}) diff --git a/api/provider-cache.test.ts b/api/provider-cache.test.ts new file mode 100644 index 0000000..1dd3c0e --- /dev/null +++ b/api/provider-cache.test.ts @@ -0,0 +1,182 @@ +import { assertEquals, assertRejects, assertStrictEquals } from '@std/assert' +import { describe, it } from '@std/testing/bdd' +import { type ListCacheOptions, withListCache } from './provider-cache.ts' +import type { ProjectScope, Provider, WorkItem } from './tickets.ts' + +const item = (externalId: string): WorkItem => ({ + source: 'jira', + externalId, + externalUrl: `https://example.atlassian.net/browse/${externalId}`, + title: externalId, +}) + +// a provider whose list() answers are queued by the test, one per call +const setup = (options: ListCacheOptions = {}) => { + let time = 0 + const calls: ProjectScope[] = [] + const answers: (() => Promise)[] = [] + const errors: unknown[] = [] + const provider: Provider = { + id: 'jira', + list: (scope) => { + calls.push(scope) + const answer = answers.shift() + return answer ? answer() : Promise.resolve([item(`call-${calls.length}`)]) + }, + comments: () => Promise.resolve([]), + } + const cached = withListCache(provider, { + ttl: 100, + idleTtl: 1000, + retryDelay: 50, + now: () => time, + onError: (error) => errors.push(error), + ...options, + }) + return { + cached, + calls, + errors, + answers, + tick: (ms: number) => (time += ms), + fail: (message: string) => + answers.push(() => Promise.reject(new Error(message))), + } +} + +const tnt = { jiraProjectKey: 'TNT' } +const ids = (items: WorkItem[]) => items.map((entry) => entry.externalId) +// let the background refresh settle +const flush = () => new Promise((resolve) => setTimeout(resolve, 0)) + +describe('withListCache', () => { + it('serves list() from cache within the ttl', async () => { + const { cached, calls, tick } = setup() + + const first = await cached.list(tnt) + tick(99) + const second = await cached.list(tnt) + + assertEquals(calls.length, 1) + assertStrictEquals(second, first) + }) + + it('keys the cache on the scope', async () => { + const { cached, calls } = setup() + + await cached.list(tnt) + await cached.list({ jiraProjectKey: 'DEV' }) + await cached.list({ jiraProjectKey: 'TNT' }) + + assertEquals(calls, [tnt, { jiraProjectKey: 'DEV' }]) + }) + + it('shares one STORE call between concurrent first loads', async () => { + const { cached, calls } = setup() + + const [a, b] = await Promise.all([cached.list(tnt), cached.list(tnt)]) + + assertEquals(calls.length, 1) + assertStrictEquals(a, b) + }) + + it('serves stale data right away and refreshes in the background', async () => { + const { cached, calls, tick } = setup() + + await cached.list(tnt) + tick(100) + assertEquals(ids(await cached.list(tnt)), ['call-1']) + assertEquals(calls.length, 2) + + await flush() + assertEquals(ids(await cached.list(tnt)), ['call-2']) + assertEquals(calls.length, 2) + }) + + it('starts a single refresh while one is already running', async () => { + const { cached, calls, tick } = setup() + + await cached.list(tnt) + tick(100) + await Promise.all([cached.list(tnt), cached.list(tnt), cached.list(tnt)]) + + assertEquals(calls.length, 2) + }) + + it('keeps serving stale data and logs when a refresh fails', async () => { + const { cached, calls, errors, tick, fail } = setup() + + await cached.list(tnt) + tick(100) + fail('store down') + assertEquals(ids(await cached.list(tnt)), ['call-1']) + await flush() + + assertEquals(ids(await cached.list(tnt)), ['call-1']) + assertEquals(errors.map((error) => (error as Error).message), [ + 'store down', + ]) + + // no retry storm: the next attempt waits retryDelay + tick(49) + await cached.list(tnt) + assertEquals(calls.length, 2) + tick(1) + await cached.list(tnt) + await flush() + assertEquals(calls.length, 3) + assertEquals(ids(await cached.list(tnt)), ['call-3']) + }) + + it('throws when the first load fails, and retries on the next call', async () => { + const { cached, calls, errors, fail } = setup() + + fail('store down') + await assertRejects(() => cached.list(tnt), Error, 'store down') + assertEquals(errors.length, 1) + + assertEquals(ids(await cached.list(tnt)), ['call-2']) + assertEquals(calls.length, 2) + }) + + it('drops the least recently read scope above maxEntries', async () => { + const { cached, calls } = setup({ maxEntries: 2 }) + const scope = (key: string) => ({ jiraProjectKey: key }) + + await cached.list(scope('A')) + await cached.list(scope('B')) + await cached.list(scope('A')) // B is now the least recently read + await cached.list(scope('C')) // evicts B + await cached.list(scope('A')) + await cached.list(scope('B')) + + assertEquals(calls.map((call) => call.jiraProjectKey), ['A', 'B', 'C', 'B']) + }) + + it('drops scopes nobody read within idleTtl', async () => { + const { cached, calls, tick } = setup({ ttl: 10_000 }) + + await cached.list(tnt) + tick(1001) + await cached.list({ jiraProjectKey: 'DEV' }) // sweeps the idle TNT entry + await cached.list(tnt) + + assertEquals(calls.map((call) => call.jiraProjectKey), [ + 'TNT', + 'DEV', + 'TNT', + ]) + }) + + it('passes comments() through untouched', async () => { + const comment = { source: 'jira' as const, body: 'hi' } + const cached = withListCache({ + id: 'jira', + list: () => Promise.resolve([]), + comments: () => Promise.resolve([comment]), + }) + + assertEquals(await cached.comments(item('TNT-1')), [comment]) + assertEquals(cached.id, 'jira') + }) +}) diff --git a/api/provider-cache.ts b/api/provider-cache.ts new file mode 100644 index 0000000..c787354 --- /dev/null +++ b/api/provider-cache.ts @@ -0,0 +1,124 @@ +import { log } from '/api/lib/logger.ts' +import type { ProjectScope, Provider, WorkItem } from './tickets.ts' + +export type ListCacheOptions = { + // how long a list() result is served without asking the STORE again + ttl?: number + // an entry nobody read for this long is dropped, stale or not + idleTtl?: number + // upper bound of cached scopes per provider, least recently read go first + maxEntries?: number + // how long to wait before retrying after a failed refresh + retryDelay?: number + now?: () => number + onError?: (error: unknown, context: Record) => void +} + +type Entry = { + items?: WorkItem[] + fetchedAt: number + lastReadAt: number + retryAt: number + pending?: Promise +} + +const SECOND = 1000 +const MINUTE = 60 * SECOND + +const logRefreshError: NonNullable = ( + error, + context, +) => log.error('provider-list-refresh-failed', { ...context, error }) + +// only the fields a provider scopes on, in a fixed order +const scopeKey = (scope: ProjectScope): string => + JSON.stringify([ + scope.repositoryUrl ?? null, + scope.jiraProjectKey ?? null, + scope.discordChannelId ?? null, + ]) + +// Stale-while-revalidate in front of provider.list(): +// - fresh (< ttl): served from memory, no STORE call +// - stale: served from memory right away, one refresh runs in the background +// - refresh failure: the stale list stays served, the error is logged and the +// next attempt waits `retryDelay` +// No timer refreshes anything by itself: a scope nobody asks for costs nothing +// and is dropped after `idleTtl`. Cached arrays are shared with callers, who +// must not mutate them. +export const withListCache = ( + provider: Provider, + { + ttl = MINUTE, + idleTtl = 15 * MINUTE, + maxEntries = 50, + retryDelay = 30 * SECOND, + now = Date.now, + onError = logRefreshError, + }: ListCacheOptions = {}, +): Provider => { + const entries = new Map() + + const evict = (time: number) => { + for (const [key, entry] of entries) { + if (time - entry.lastReadAt > idleTtl && !entry.pending) { + entries.delete(key) + } + } + // Map keeps insertion order and reads re-insert, so the first is the LRU + for (const key of entries.keys()) { + if (entries.size <= maxEntries) break + entries.delete(key) + } + } + + // single flight: every caller of the same scope shares one STORE call + const refresh = (key: string, entry: Entry, scope: ProjectScope) => { + entry.pending ??= provider.list(scope).then( + (items) => { + entry.items = items + entry.fetchedAt = now() + entry.pending = undefined + return items + }, + (error) => { + entry.retryAt = now() + retryDelay + entry.pending = undefined + onError(error, { provider: provider.id, scope: key }) + throw error + }, + ) + return entry.pending + } + + return { + id: provider.id, + comments: (item) => provider.comments(item), + list: (scope) => { + const time = now() + const key = scopeKey(scope) + const entry = entries.get(key) ?? + { fetchedAt: 0, lastReadAt: time, retryAt: 0 } + + entry.lastReadAt = time + entries.delete(key) + entries.set(key, entry) + evict(time) + + // nothing to fall back on yet: wait for the first load, and forget + // the entry if it fails so the next request tries again + if (!entry.items) { + return refresh(key, entry, scope).catch((error) => { + entries.get(key) === entry && !entry.items && entries.delete(key) + throw error + }) + } + + if (time - entry.fetchedAt >= ttl && time >= entry.retryAt) { + // already logged by refresh, the stale list is served meanwhile + refresh(key, entry, scope).catch(() => {}) + } + return Promise.resolve(entry.items) + }, + } +} diff --git a/api/routes.ts b/api/routes.ts index e2e83ba..ebfc1fb 100644 --- a/api/routes.ts +++ b/api/routes.ts @@ -46,7 +46,9 @@ import { analyzeQueryWithAI } from '/api/fix-query.ts' import { PERSON_LINK_PATH, type PersonLink } from './team-directory.ts' import { filterTickets, + getProjectTicket, listProjectTickets, + toTicketDetailRow, toTicketRow, } from './project-tickets.ts' @@ -148,6 +150,25 @@ const userInTeam = async (teamId: string, userId?: string) => { return !!matches } +const withProjectAccess = async ( + ctx: RequestContext & { session: User }, + projectId: string, + resource: string, +) => { + const project = ProjectsCollection.get(projectId) + if (!project) { + throw new respond.NotFoundError({ message: 'Project not found' }) + } + if (!project.isPublic && !ctx.session.isAdmin) { + if (!(await userInTeam(project.teamId, ctx.session.id))) { + throw new respond.ForbiddenError({ + message: `Access to project ${resource} denied`, + }) + } + } + return project +} + const withDeploymentTableAccess = async ( ctx: RequestContext & { session: User }, deployment: string, @@ -161,17 +182,7 @@ const withDeploymentTableAccess = async ( }) } - const project = ProjectsCollection.get(dep.projectId) - if (!project) { - throw new respond.NotFoundError({ message: 'Project not found' }) - } - if (!project.isPublic && !ctx.session.isAdmin) { - if (!(await userInTeam(project.teamId, ctx.session.id))) { - throw new respond.ForbiddenError({ - message: 'Access to project tables denied', - }) - } - } + await withProjectAccess(ctx, dep.projectId, 'tables') return dep } @@ -229,6 +240,29 @@ const ticketOutput = OBJ({ reviewers: ARR(ticketPersonOutput, 'The resolved reviewers'), }) +const ticketOutputFields = ticketOutput.properties +const ticketDetailOutput = OBJ({ + ...ticketOutputFields, + discussion: ARR( + OBJ({ + source: LIST(TICKET_SOURCES, 'The source system of the comment'), + author: optional(ticketPersonOutput), + body: STR('The comment text'), + url: optional(STR('The link to the comment in the source system')), + createdAt: optional(NUM('The comment creation date, in ms')), + }), + 'Every comment of every linked source, oldest first', + ), +}) + +const toTicketScope = ( + project: NonNullable>, +) => ({ + repositoryUrl: project.repositoryUrl ?? undefined, + jiraProjectKey: project.jiraProjectKey ?? undefined, + discordChannelId: project.discordChannelId ?? undefined, +}) + // GET params always arrive as strings, NUM would reject them const toCount = (value: string | null | undefined, fallback: number) => { if (value == null) return fallback @@ -535,29 +569,14 @@ const defs = { 'GET/api/project/tickets': route({ authorize: withUserSession, fn: async (ctx, { project: slug, limit, offset, ...filters }) => { - const project = ProjectsCollection.get(slug) - if (!project) { - throw new respond.NotFoundError({ message: 'Project not found' }) - } - if (!project.isPublic && !ctx.session.isAdmin) { - if (!(await userInTeam(project.teamId, ctx.session.id))) { - throw new respond.ForbiddenError({ - message: 'Access to project tickets denied', - }) - } - } - + const project = await withProjectAccess(ctx, slug, 'tickets') const start = toCount(offset, 0) const size = Math.min( toCount(limit, DEFAULT_TICKET_LIMIT), MAX_TICKET_LIMIT, ) const tickets = filterTickets( - await listProjectTickets({ - repositoryUrl: project.repositoryUrl ?? undefined, - jiraProjectKey: project.jiraProjectKey ?? undefined, - discordChannelId: project.discordChannelId ?? undefined, - }), + await listProjectTickets(toTicketScope(project)), filters, ) return { @@ -590,6 +609,24 @@ const defs = { description: 'List the tickets of a project, aggregated from Jira, GitHub and Discord, latest activity first', }), + 'GET/api/project/ticket': route({ + authorize: withUserSession, + fn: async (ctx, { project: slug, key }) => { + const project = await withProjectAccess(ctx, slug, 'tickets') + const ticket = await getProjectTicket(toTicketScope(project), key) + if (!ticket) { + throw new respond.NotFoundError({ message: 'Ticket not found' }) + } + return toTicketDetailRow(ticket) + }, + input: OBJ({ + project: STR('The slug of the project'), + key: STR('The ticket key, as returned by GET /api/project/tickets'), + }), + output: ticketDetailOutput, + description: + 'Get one ticket of a project with its discussion merged from all of its linked sources', + }), 'GET/api/deployment': route({ authorize: withUserSession, fn: async ({ session }, { url }) => { @@ -749,17 +786,7 @@ const defs = { message: 'Logging not enabled for deployment', }) } - const project = ProjectsCollection.get(deployment.projectId) - if (!project) { - throw new respond.NotFoundError({ message: 'Project not found' }) - } - if (!project.isPublic && !ctx.session.isAdmin) { - if (!(await userInTeam(project.teamId, ctx.session.id))) { - throw new respond.ForbiddenError({ - message: 'Access to project logs denied', - }) - } - } + await withProjectAccess(ctx, deployment.projectId, 'logs') return getLogs(deployment.url, params) },