feat(admin): outbound queue page
- Add queue totals, delivery table with errors and next attempt - Refresh on demand and every 5 seconds - Add confirmed discard of a stuck delivery - Link the page from the header
This commit is contained in:
parent
98bbcf6b68
commit
f3c75dc97d
7 changed files with 341 additions and 5 deletions
|
|
@ -8,6 +8,7 @@ import { ArchiveTab } from '@/tabs/ArchiveTab'
|
|||
import { HeldTab } from '@/tabs/HeldTab'
|
||||
import { MembersTab } from '@/tabs/MembersTab'
|
||||
import { SettingsTab } from '@/tabs/SettingsTab'
|
||||
import { QueuePage } from '@/pages/QueuePage'
|
||||
import { Toaster } from '@/components/ui/sonner'
|
||||
|
||||
/** Routes only: providers (query client, router, auth) are set up by the caller. */
|
||||
|
|
@ -18,6 +19,7 @@ export function App() {
|
|||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route element={<Shell />}>
|
||||
<Route index element={<ListsPage />} />
|
||||
<Route path="queue" element={<QueuePage />} />
|
||||
<Route path="lists/:id" element={<ListPage />}>
|
||||
<Route index element={<SettingsTab />} />
|
||||
<Route path="members" element={<MembersTab />} />
|
||||
|
|
|
|||
|
|
@ -11,9 +11,14 @@ export function Shell() {
|
|||
<div className="min-h-screen">
|
||||
<header className="border-b">
|
||||
<div className="mx-auto flex max-w-5xl items-center justify-between p-4">
|
||||
<Link to="/" className="text-lg font-semibold">
|
||||
Parsimony
|
||||
</Link>
|
||||
<div className="flex items-center gap-6">
|
||||
<Link to="/" className="text-lg font-semibold">
|
||||
Parsimony
|
||||
</Link>
|
||||
<Link to="/queue" className="text-sm text-muted-foreground hover:text-foreground">
|
||||
Queue
|
||||
</Link>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={logout}>
|
||||
Sign out
|
||||
</Button>
|
||||
|
|
|
|||
|
|
@ -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'],
|
||||
])
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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<void>('POST', `/held/${id}/approve`),
|
||||
discard: (id: number) => request<void>('DELETE', `/held/${id}`),
|
||||
},
|
||||
queue: {
|
||||
get: () => request<Queue>('GET', '/queue'),
|
||||
discard: (id: number) => request<void>('DELETE', `/queue/${id}`),
|
||||
},
|
||||
archive: {
|
||||
list: (listId: number, p: { q?: string; limit?: number; offset?: number } = {}) => {
|
||||
const qs = new URLSearchParams()
|
||||
|
|
|
|||
113
admin/src/pages/QueuePage.test.tsx
Normal file
113
admin/src/pages/QueuePage.test.tsx
Normal file
|
|
@ -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> = {}): 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)
|
||||
})
|
||||
})
|
||||
})
|
||||
141
admin/src/pages/QueuePage.tsx
Normal file
141
admin/src/pages/QueuePage.tsx
Normal file
|
|
@ -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<QueueItem | null>(null)
|
||||
const q = queue.data
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-semibold">Outbound queue</h1>
|
||||
<Button variant="outline" onClick={() => queue.refetch()} disabled={queue.isFetching}>
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{queue.isPending && <p className="text-muted-foreground">Loading…</p>}
|
||||
{queue.isError && <p role="alert" className="text-destructive">{queue.error.message}</p>}
|
||||
|
||||
{q && (
|
||||
<>
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<Stat label="Pending" value={String(q.pending)} />
|
||||
<Stat label="Retrying" value={String(q.retrying)} />
|
||||
<Stat label="Oldest" value={q.oldest ? formatDate(q.oldest) : '—'} />
|
||||
</div>
|
||||
{q.items.length === 0 ? (
|
||||
<p className="text-muted-foreground">The queue is empty. Mail is sent as soon as it is accepted.</p>
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Recipient</TableHead>
|
||||
<TableHead>Attempts</TableHead>
|
||||
<TableHead>Last error</TableHead>
|
||||
<TableHead>Next attempt</TableHead>
|
||||
<TableHead className="text-right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{q.items.map((i) => (
|
||||
<TableRow key={i.id}>
|
||||
<TableCell className="font-medium">{i.recipient}</TableCell>
|
||||
<TableCell>{i.attempts}</TableCell>
|
||||
<TableCell>{i.last_error || '—'}</TableCell>
|
||||
<TableCell>{formatDate(i.next_attempt)}</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<Button size="sm" variant="outline" onClick={() => setDiscarding(i)}>
|
||||
Discard
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
{q.pending > q.items.length && (
|
||||
<p className="text-sm text-muted-foreground">Showing {q.items.length} of {q.pending} deliveries.</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<DiscardDialog item={discarding} onClose={() => setDiscarding(null)} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Stat({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<Card size="sm">
|
||||
<CardContent>
|
||||
<div className="text-sm text-muted-foreground">{label}</div>
|
||||
<div className="text-xl font-semibold">{value}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
function DiscardDialog({ item, onClose }: { item: QueueItem | null; onClose: () => void }) {
|
||||
const queryClient = useQueryClient()
|
||||
const [error, setError] = useState<string | null>(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 (
|
||||
<AlertDialog
|
||||
open={item !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setError(null)
|
||||
onClose()
|
||||
}
|
||||
}}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Discard this delivery?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
The message for {item?.recipient} will not be sent. Other recipients are not affected.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
{error && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<Button variant="destructive" disabled={discard.isPending} onClick={() => item && discard.mutate(item)}>
|
||||
Discard
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)
|
||||
}
|
||||
|
|
@ -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<number, Member[]>
|
||||
held: Record<number, Held[]>
|
||||
archive: Record<number, Message[]>
|
||||
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> = {}): 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> = {}): 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')
|
||||
|
|
|
|||
Loading…
Reference in a new issue