-
- Parsimony
-
+
+
+ Parsimony
+
+
+ Queue
+
+
diff --git a/admin/src/lib/api.test.ts b/admin/src/lib/api.test.ts
index 28cfc5f..c8622e6 100644
--- a/admin/src/lib/api.test.ts
+++ b/admin/src/lib/api.test.ts
@@ -149,4 +149,14 @@ describe('endpoints', () => {
['GET', '/api/v1/archive/9'],
])
})
+
+ it('reads the queue and discards a delivery', async () => {
+ mockFetch(respond(204))
+ await api.queue.discard(4)
+ await api.queue.get().catch(() => undefined)
+ expect(calls.map((c) => [c.init.method, c.url])).toEqual([
+ ['DELETE', '/api/v1/queue/4'],
+ ['GET', '/api/v1/queue'],
+ ])
+ })
})
diff --git a/admin/src/lib/api.ts b/admin/src/lib/api.ts
index 1686a7a..23666fb 100644
--- a/admin/src/lib/api.ts
+++ b/admin/src/lib/api.ts
@@ -47,6 +47,22 @@ export interface ArchivePage {
messages: Message[]
}
+export interface QueueItem {
+ id: number
+ recipient: string
+ attempts: number
+ last_error: string
+ next_attempt: string
+ created_at: string
+}
+
+export interface Queue {
+ pending: number
+ retrying: number
+ oldest: string | null
+ items: QueueItem[]
+}
+
export class ApiError extends Error {
readonly status: number
constructor(status: number, message: string) {
@@ -130,6 +146,10 @@ export const api = {
approve: (id: number) => request
('POST', `/held/${id}/approve`),
discard: (id: number) => request('DELETE', `/held/${id}`),
},
+ queue: {
+ get: () => request('GET', '/queue'),
+ discard: (id: number) => request('DELETE', `/queue/${id}`),
+ },
archive: {
list: (listId: number, p: { q?: string; limit?: number; offset?: number } = {}) => {
const qs = new URLSearchParams()
diff --git a/admin/src/pages/QueuePage.test.tsx b/admin/src/pages/QueuePage.test.tsx
new file mode 100644
index 0000000..4c65104
--- /dev/null
+++ b/admin/src/pages/QueuePage.test.tsx
@@ -0,0 +1,113 @@
+import { act, screen, waitFor, within } from '@testing-library/react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import type { QueueItem } from '@/lib/api'
+import { installFakeApi, newState } from '@/test/fakeApi'
+import { renderApp } from '@/test/render'
+
+const item = (id: number, over: Partial = {}): QueueItem => ({
+ id,
+ recipient: `user${id}@example.com`,
+ attempts: 0,
+ last_error: '',
+ next_attempt: '2030-01-02T03:04:05Z',
+ created_at: '2030-01-01T00:00:00Z',
+ ...over,
+})
+
+async function setup(items: QueueItem[]) {
+ const state = installFakeApi(newState({ queue: items }))
+ const ctx = renderApp('/queue', { token: 'good' })
+ await screen.findByRole('heading', { name: /outbound queue/i })
+ return { ...ctx, state }
+}
+
+afterEach(() => vi.useRealTimers())
+
+describe('queue page', () => {
+ it('is reachable from the header', async () => {
+ installFakeApi(newState())
+ const { user } = renderApp('/', { token: 'good' })
+ await user.click(await screen.findByRole('link', { name: /^queue$/i }))
+ expect(await screen.findByRole('heading', { name: /outbound queue/i })).toBeInTheDocument()
+ })
+
+ it('says when the queue is empty', async () => {
+ await setup([])
+ expect(await screen.findByText(/the queue is empty/i)).toBeInTheDocument()
+ expect(screen.getByText('Pending').nextElementSibling).toHaveTextContent('0')
+ })
+
+ it('shows totals and each delivery, failing ones with their error', async () => {
+ await setup([
+ item(1),
+ item(2, { attempts: 3, last_error: 'connection refused', next_attempt: '2030-01-02T05:00:00Z' }),
+ ])
+ const failing = (await screen.findByText('user2@example.com')).closest('tr')!
+ expect(within(failing).getByText('3')).toBeInTheDocument()
+ expect(within(failing).getByText('connection refused')).toBeInTheDocument()
+ expect(within(failing).getByText('2030-01-02 05:00 UTC')).toBeInTheDocument()
+ const fresh = screen.getByText('user1@example.com').closest('tr')!
+ expect(within(fresh).getByText('—')).toBeInTheDocument()
+
+ expect(screen.getByText('Pending').nextElementSibling).toHaveTextContent('2')
+ expect(screen.getByText('Retrying').nextElementSibling).toHaveTextContent('1')
+ expect(screen.getByText('Oldest').nextElementSibling).toHaveTextContent('2030-01-01 00:00 UTC')
+ })
+
+ it('refreshes on demand', async () => {
+ const { user, state } = await setup([item(1)])
+ await screen.findByText('user1@example.com')
+ state.queue = []
+ await user.click(screen.getByRole('button', { name: /refresh/i }))
+ expect(await screen.findByText(/the queue is empty/i)).toBeInTheDocument()
+ })
+
+ it('refreshes by itself every few seconds', async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true }) // before the page starts its polling timer
+ const { state } = await setup([item(1)])
+ await screen.findByText('user1@example.com')
+ state.queue = []
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(6000)
+ })
+ expect(await screen.findByText(/the queue is empty/i)).toBeInTheDocument()
+ })
+
+ it('shows a loading error', async () => {
+ installFakeApi(newState({ fail: { 'GET /queue': { status: 500, error: 'database is locked' } } }))
+ renderApp('/queue', { token: 'good' })
+ expect(await screen.findByRole('alert')).toHaveTextContent('database is locked')
+ })
+
+ describe('discarding', () => {
+ async function open() {
+ const ctx = await setup([item(1), item(2)])
+ await ctx.user.click(within((await screen.findByText('user1@example.com')).closest('tr')!).getByRole('button', { name: /discard/i }))
+ return { ...ctx, dialog: await screen.findByRole('alertdialog') }
+ }
+
+ it('confirms first, naming the recipient; cancel keeps it', async () => {
+ const { user, state, dialog } = await open()
+ expect(dialog).toHaveTextContent('user1@example.com')
+ await user.click(within(dialog).getByRole('button', { name: /cancel/i }))
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+ expect(state.queue).toHaveLength(2)
+ })
+
+ it('discards the delivery', async () => {
+ const { user, state, dialog } = await open()
+ await user.click(within(dialog).getByRole('button', { name: /^discard$/i }))
+ await waitFor(() => expect(screen.queryByText('user1@example.com')).not.toBeInTheDocument())
+ expect(state.queue.map((i) => i.id)).toEqual([2])
+ expect(screen.getByText('user2@example.com')).toBeInTheDocument()
+ })
+
+ it('shows a server error inside the dialog', async () => {
+ const { user, state, dialog } = await open()
+ state.fail['DELETE /queue/1'] = { status: 500, error: 'locked' }
+ await user.click(within(dialog).getByRole('button', { name: /^discard$/i }))
+ expect(await within(dialog).findByRole('alert')).toHaveTextContent('locked')
+ expect(state.queue).toHaveLength(2)
+ })
+ })
+})
diff --git a/admin/src/pages/QueuePage.tsx b/admin/src/pages/QueuePage.tsx
new file mode 100644
index 0000000..b5d6967
--- /dev/null
+++ b/admin/src/pages/QueuePage.tsx
@@ -0,0 +1,141 @@
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { useState } from 'react'
+import { toast } from 'sonner'
+import {
+ AlertDialog,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from '@/components/ui/alert-dialog'
+import { Button } from '@/components/ui/button'
+import { Card, CardContent } from '@/components/ui/card'
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
+import { api, type QueueItem } from '@/lib/api'
+import { formatDate } from '@/lib/format'
+
+/** How often the page reloads by itself. */
+export const REFRESH_MS = 5000
+
+export function QueuePage() {
+ const queue = useQuery({ queryKey: ['queue'], queryFn: api.queue.get, refetchInterval: REFRESH_MS })
+ const [discarding, setDiscarding] = useState(null)
+ const q = queue.data
+
+ return (
+
+
+
Outbound queue
+
+
+
+ {queue.isPending &&
Loading…
}
+ {queue.isError &&
{queue.error.message}
}
+
+ {q && (
+ <>
+
+
+
+
+
+ {q.items.length === 0 ? (
+
The queue is empty. Mail is sent as soon as it is accepted.
+ ) : (
+
+
+
+ Recipient
+ Attempts
+ Last error
+ Next attempt
+ Actions
+
+
+
+ {q.items.map((i) => (
+
+ {i.recipient}
+ {i.attempts}
+ {i.last_error || '—'}
+ {formatDate(i.next_attempt)}
+
+
+
+
+ ))}
+
+
+ )}
+ {q.pending > q.items.length && (
+
Showing {q.items.length} of {q.pending} deliveries.
+ )}
+ >
+ )}
+
setDiscarding(null)} />
+
+ )
+}
+
+function Stat({ label, value }: { label: string; value: string }) {
+ return (
+
+
+ {label}
+ {value}
+
+
+ )
+}
+
+function DiscardDialog({ item, onClose }: { item: QueueItem | null; onClose: () => void }) {
+ const queryClient = useQueryClient()
+ const [error, setError] = useState(null)
+ const discard = useMutation({
+ mutationFn: (i: QueueItem) => api.queue.discard(i.id),
+ onSuccess: async () => {
+ await queryClient.invalidateQueries({ queryKey: ['queue'] })
+ toast.success('Delivery discarded')
+ onClose()
+ },
+ onError: (e: Error) => setError(e.message),
+ })
+
+ return (
+ {
+ if (!open) {
+ setError(null)
+ onClose()
+ }
+ }}
+ >
+
+
+ Discard this delivery?
+
+ The message for {item?.recipient} will not be sent. Other recipients are not affected.
+
+
+ {error && (
+
+ {error}
+
+ )}
+
+ Cancel
+
+
+
+
+ )
+}
diff --git a/admin/src/test/fakeApi.ts b/admin/src/test/fakeApi.ts
index 7fdd8f8..820e9ac 100644
--- a/admin/src/test/fakeApi.ts
+++ b/admin/src/test/fakeApi.ts
@@ -1,6 +1,6 @@
// An in-memory stand-in for the Parsimony API, used by component tests.
import { vi } from 'vitest'
-import type { Held, List, Member, Message } from '@/lib/api'
+import type { Held, List, Member, Message, QueueItem } from '@/lib/api'
export interface FakeState {
token: string
@@ -8,6 +8,7 @@ export interface FakeState {
members: Record
held: Record
archive: Record
+ queue: QueueItem[]
nextId: number
/** Every request seen, as "METHOD /path". */
calls: string[]
@@ -16,7 +17,7 @@ export interface FakeState {
}
export function newState(overrides: Partial = {}): FakeState {
- return { token: 'good', lists: [], members: {}, held: {}, archive: {}, nextId: 100, calls: [], fail: {}, ...overrides }
+ return { token: 'good', lists: [], members: {}, held: {}, archive: {}, queue: [], nextId: 100, calls: [], fail: {}, ...overrides }
}
export function aList(over: Partial = {}): List {
@@ -62,6 +63,18 @@ export function installFakeApi(state: FakeState) {
const body = init.body ? JSON.parse(init.body as string) : {}
let m: RegExpMatchArray | null
+ if (path === '/queue' && method === 'GET') {
+ const items = [...state.queue].sort((a, b) => b.attempts - a.attempts)
+ const retrying = state.queue.filter((i) => i.attempts > 0).length
+ const oldest = state.queue.map((i) => i.created_at).sort()[0] ?? null
+ return json(200, { pending: state.queue.length, retrying, oldest, items })
+ }
+ if ((m = path.match(/^\/queue\/(\d+)$/)) && method === 'DELETE') {
+ const id = Number(m[1])
+ if (!state.queue.some((i) => i.id === id)) return err(404, 'not found')
+ state.queue = state.queue.filter((i) => i.id !== id)
+ return json(204)
+ }
if (path === '/lists' && method === 'GET') return json(200, state.lists)
if (path === '/lists' && method === 'POST') {
if (state.lists.some((l) => l.name === body.name && l.domain === body.domain)) return err(409, 'already exists')
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index e5d16b8..52395a0 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -35,6 +35,15 @@ components:
date: {type: string, format: date-time}
size: {type: integer}
body: {type: string, description: Only when reading a single message}
+ QueueItem:
+ type: object
+ properties:
+ id: {type: integer}
+ recipient: {type: string}
+ attempts: {type: integer, description: Failed attempts so far}
+ last_error: {type: string}
+ next_attempt: {type: string, format: date-time}
+ created_at: {type: string, format: date-time}
Member:
type: object
properties:
@@ -243,3 +252,26 @@ paths:
responses:
'204': {description: Deleted}
'404': {$ref: '#/components/responses/Error'}
+ /queue:
+ get:
+ summary: Outbound queue totals and up to 100 deliveries (failing ones first)
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ pending: {type: integer}
+ retrying: {type: integer, description: Deliveries that failed at least once}
+ oldest: {type: string, format: date-time, nullable: true}
+ items: {type: array, items: {$ref: '#/components/schemas/QueueItem'}}
+ /queue/{id}:
+ parameters:
+ - {name: id, in: path, required: true, schema: {type: integer}}
+ delete:
+ summary: Discard a queued delivery
+ responses:
+ '204': {description: Discarded}
+ '404': {$ref: '#/components/responses/Error'}