Compare commits

...
Author SHA1 Message Date
james.maes be752fbb74 feat(esb): ESB_OVERVIEW widget for the ESB app
Lists providers, destinations with publishers, and triggers from GET /esb/overview.

Part of QRun-IO/qqq#739
2026-09-26 01:30:28 -05:00
james.maes 8b3b8b9b3f feat(esb): process developer view
The dev route resolves process slugs and shows process metadata with its ESB section.

Part of QRun-IO/qqq#739
2026-09-26 01:30:27 -05:00
james.maes 4fdff640ba feat(esb): management actions and message browsing
Trigger and queue actions show only with permission and broker support; purge and delete ask for confirmation.

Part of QRun-IO/qqq#739
2026-09-26 01:30:26 -05:00
james.maes 270c5c84fc feat(esb): API client for process, overview, browsing and actions
Adds the process, overview, messages and dead-letter endpoints and runs operate processes through the process API.

Part of QRun-IO/qqq#739
2026-09-26 01:30:25 -05:00
19 changed files with 2784 additions and 139 deletions

No files matched your search

@@ -14,7 +14,7 @@
* limitations under the License.
*/
// Tests for the table Developer view's ESB section wiring
// Tests for the Developer view's slug resolution and ESB section wiring
import React from 'react'
import { render, screen, waitFor } from '@testing-library/react'
@@ -126,4 +126,24 @@ describe('TableDeveloperViewPage ESB section', () => {
).not.toBeInTheDocument()
expect(toast.error).not.toHaveBeenCalled()
})
it('shows the process Developer view with its ESB section for a process slug', async () => {
params.slug = 'fulfillOrder'
renderPage()
expect(
await screen.findByRole('heading', { name: 'Process Developer View: fulfillOrder' })
).toBeInTheDocument()
expect(
await screen.findByRole('heading', { name: 'Enterprise Service Bus' })
).toBeInTheDocument()
expect(screen.getByRole('table', { name: 'Triggers' })).toBeInTheDocument()
expect(screen.queryByText('Fields')).not.toBeInTheDocument()
})
it('keeps the table Developer view for a table slug', async () => {
renderPage()
expect(
await screen.findByRole('heading', { name: 'Table Developer View: order' })
).toBeInTheDocument()
})
})
+97 -37
View File
@@ -15,8 +15,9 @@
*/
/**
* @file TableDeveloperView page — shows raw table metadata as formatted JSON for debugging field definitions and permissions,
* and the table's ESB publications and subscribers when it has any.
* @file Developer view page — resolves the slug to a table or a process. For a table it shows raw
* table metadata as formatted JSON for debugging field definitions and permissions; for a process,
* its metadata summary and JSON; for either, its ESB publications and triggers when it has any.
*/
'use client'
@@ -27,70 +28,93 @@ import { Code, ChevronDown, ChevronUp } from 'lucide-react'
import { useRouteParams } from '@/lib/hooks/use-route-params'
import { useQContext } from '@/lib/context/q-context'
import { useMetaData, useProcessMetaData } from '@/lib/hooks/use-metadata'
import { loadTableMetaData } from '@/lib/api/metadata'
import { getEsbForTable } from '@/lib/api/esb'
import { getEsbForProcess, getEsbForTable } from '@/lib/api/esb'
import { queryKeys } from '@/lib/query-client'
import { EsbSection } from '@/components/esb/EsbSection'
import { ProcessDeveloperView } from '@/components/esb/ProcessDeveloperView'
/**
* Renders the Developer view for the table or process named by the slug. A slug naming both
* resolves to the table, as it does on the slug page; a slug naming neither (or instance metadata
* that fails to load) falls through to the table view, which reports the load failure.
*
* @returns A spinner while instance metadata loads, then `<ProcessDeveloperPage>` for a process
* slug or `<TableDeveloperView>` otherwise.
*/
export default function DeveloperViewPage() {
const params = useRouteParams<{ slug: string }>()
const { setPageHeader } = useQContext()
const slug = params.slug
const { data: metaData, isError: metaDataError } = useMetaData()
useEffect(() => {
setPageHeader(`Developer View: ${slug}`)
}, [slug, setPageHeader])
if (!metaData && !metaDataError) return <LoadingSpinner />
const isProcess = Boolean(metaData && !metaData.tables?.[slug] && metaData.processes?.[slug])
return isProcess ? <ProcessDeveloperPage processName={slug} /> : <TableDeveloperView tableName={slug} />
}
/**
* Loads a process's metadata and ESB data and renders its Developer view.
*
* @param props - Component props.
* @param props.processName - The process to show.
* @returns A spinner while metadata loads, a destructive error panel on failure, then the
* `<ProcessDeveloperView>` (without an ESB section on 403, 404, or a backend without the ESB module).
*/
function ProcessDeveloperPage({ processName }: { processName: string }) {
const { data, error } = useProcessMetaData(processName)
const { data: esb } = useQuery({
queryKey: queryKeys.esbProcess(processName),
queryFn: () => getEsbForProcess(processName),
})
if (error) return <LoadError error={error} />
if (!data) return <LoadingSpinner />
return <ProcessDeveloperView process={data} esb={esb ?? null} />
}
/**
* Renders a developer debug view for a QQQ table, showing summary statistics
* and the full table metadata as a collapsible JSON block.
*
* @returns A composed page that assembles:
* @param props - Component props.
* @param props.tableName - The table to show.
* @returns A composed view that assembles:
* - A 4-column stats grid (`<MetaStat>` cards: field count, section count, permissions, primary key)
* - An `<EsbSection>` with the table's ESB publications and subscribers, omitted when the
* table has none to show (403, 404, or a backend without the ESB module)
* - A collapsible `<JsonBlock>` panel rendering the full table metadata as formatted JSON
* - A loading spinner while metadata is fetching, and a destructive error panel on failure
*/
export default function TableDeveloperViewPage() {
const params = useRouteParams<{ slug: string }>()
const { setPageHeader } = useQContext()
const slug = params.slug
useEffect(() => {
setPageHeader(`Developer View: ${slug}`)
}, [slug, setPageHeader])
function TableDeveloperView({ tableName }: { tableName: string }) {
const { data, isLoading, error } = useQuery({
queryKey: queryKeys.tableMetadata(slug),
queryFn: () => loadTableMetaData(slug),
queryKey: queryKeys.tableMetadata(tableName),
queryFn: () => loadTableMetaData(tableName),
staleTime: 1000 * 60 * 5,
})
const { data: esb } = useQuery({
queryKey: queryKeys.esbTable(slug),
queryFn: () => getEsbForTable(slug),
queryKey: queryKeys.esbTable(tableName),
queryFn: () => getEsbForTable(tableName),
})
return (
<div className="space-y-6" data-qqq-id={`table-dev-${slug}`}>
<div className="space-y-6" data-qqq-id={`table-dev-${tableName}`}>
<div className="flex items-center gap-3">
<Code className="h-6 w-6 text-muted-foreground" aria-hidden="true" />
<h2 className="text-2xl font-semibold text-foreground">
Table Developer View: <span className="font-mono text-primary">{slug}</span>
Table Developer View: <span className="font-mono text-primary">{tableName}</span>
</h2>
</div>
{isLoading && (
<div
className="flex items-center justify-center py-12"
role="status"
aria-live="polite"
aria-busy="true"
>
<div className="h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent" />
</div>
)}
{isLoading && <LoadingSpinner />}
{error && (
<div
className="rounded-xl border border-destructive/30 bg-destructive/10 p-4 text-sm text-destructive"
role="alert"
>
Failed to load metadata: {error instanceof Error ? error.message : 'Unknown error'}
</div>
)}
{error && <LoadError error={error} />}
{data && (
<div className="space-y-4">
@@ -121,6 +145,42 @@ export default function TableDeveloperViewPage() {
)
}
/**
* A centered spinner announced as busy.
*
* @returns The loading indicator.
*/
function LoadingSpinner() {
return (
<div
className="flex items-center justify-center py-12"
role="status"
aria-live="polite"
aria-busy="true"
>
<div className="h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent" />
</div>
)
}
/**
* A destructive panel reporting a metadata load failure.
*
* @param props - Component props.
* @param props.error - The load error.
* @returns The error panel.
*/
function LoadError({ error }: { error: unknown }) {
return (
<div
className="rounded-xl border border-destructive/30 bg-destructive/10 p-4 text-sm text-destructive"
role="alert"
>
Failed to load metadata: {error instanceof Error ? error.message : 'Unknown error'}
</div>
)
}
/**
* Renders a single labeled statistic card.
*
+233
View File
@@ -0,0 +1,233 @@
/*
* Copyright 2026 QRun.IO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Tests for the ESB management actions
import React from 'react'
import { render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { toast } from 'sonner'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { EsbCapabilities, EsbPermissions } from '@/types'
import { processInit } from '@/lib/api/processes'
import { orderEsb } from '@/mocks/fixtures/esb'
import { EsbQueueActions, EsbTriggerActions, destinationQueue, type EsbQueueRef } from './EsbActions'
vi.mock('@/lib/api/processes', () => ({ processInit: vi.fn() }))
vi.mock('sonner', async (importOriginal) => ({
...(await importOriginal<typeof import('sonner')>()),
toast: { error: vi.fn(), success: vi.fn(), info: vi.fn(), warning: vi.fn(), dismiss: vi.fn() },
}))
const [fulfillTrigger, cancelTrigger] = orderEsb.subscribers
const orderFulfillment = orderEsb.publications[1].destination
const NONE: EsbPermissions = { canOperate: false, canDelete: false }
const ALL: EsbPermissions = { canOperate: true, canDelete: true }
const NO_CAPABILITIES: EsbCapabilities = {
browse: false,
pauseQueue: false,
purge: false,
deleteSelected: false,
deleteOlderThan: false,
move: false,
}
/**
* Renders a component inside a fresh query client.
*
* @param ui - The element to render.
*/
function renderWithClient(ui: React.ReactElement): void {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
render(<QueryClientProvider client={client}>{ui}</QueryClientProvider>)
}
/**
* The broker queue behind the `orderFulfillment` destination.
*
* @returns Its queue reference.
*/
function fulfillmentQueue(): EsbQueueRef {
const queue = destinationQueue(orderFulfillment)
if (!queue) throw new Error('orderFulfillment is a queue')
return queue
}
describe('EsbActions', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(processInit).mockResolvedValue({
type: 'COMPLETE',
processUUID: 'uuid',
values: { count: 1, message: 'Done.' },
})
})
it('shows no actions without esbOperate or esbDelete', () => {
renderWithClient(
<>
<EsbTriggerActions trigger={fulfillTrigger} permissions={NONE} />
<EsbQueueActions queue={fulfillmentQueue()} permissions={NONE} />
</>
)
expect(screen.queryAllByRole('button')).toHaveLength(0)
})
it('shows no queue actions the broker does not support', () => {
renderWithClient(
<EsbQueueActions
queue={{ ...fulfillmentQueue(), capabilities: NO_CAPABILITIES }}
permissions={ALL}
/>
)
expect(screen.queryAllByRole('button')).toHaveLength(0)
})
it('needs esbOperate for pausing a queue and esbDelete for purging and deleting', () => {
const { unmount } = render(
<QueryClientProvider client={new QueryClient()}>
<EsbQueueActions queue={fulfillmentQueue()} permissions={{ canOperate: true, canDelete: false }} />
</QueryClientProvider>
)
expect(screen.getByRole('button', { name: 'Pause queue orderFulfillment' })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Purge orderFulfillment' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Delete older messages in orderFulfillment' })).not.toBeInTheDocument()
unmount()
renderWithClient(
<EsbQueueActions queue={fulfillmentQueue()} permissions={{ canOperate: false, canDelete: true }} />
)
expect(screen.queryByRole('button', { name: 'Pause queue orderFulfillment' })).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Purge orderFulfillment' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Delete older messages in orderFulfillment' })).toBeInTheDocument()
})
it('offers resume instead of pause for a paused queue', () => {
renderWithClient(
<EsbQueueActions queue={{ ...fulfillmentQueue(), paused: true }} permissions={ALL} />
)
expect(screen.getByRole('button', { name: 'Resume queue orderFulfillment' })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Pause queue orderFulfillment' })).not.toBeInTheDocument()
})
it('offers pause for a running trigger and resume for a paused one', () => {
renderWithClient(
<>
<EsbTriggerActions trigger={fulfillTrigger} permissions={ALL} />
<EsbTriggerActions trigger={cancelTrigger} permissions={ALL} />
</>
)
expect(screen.getByRole('button', { name: 'Pause Fulfill Order' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Resume Cancel Order' })).toBeInTheDocument()
expect(screen.getAllByRole('button', { name: /^Restart/ })).toHaveLength(2)
})
it('pauses a trigger with esbPauseTrigger', async () => {
const user = userEvent.setup()
renderWithClient(<EsbTriggerActions trigger={fulfillTrigger} permissions={ALL} />)
await user.click(screen.getByRole('button', { name: 'Pause Fulfill Order' }))
await waitFor(() =>
expect(processInit).toHaveBeenCalledWith('esbPauseTrigger', {
values: { triggerName: 'fulfillOrder.orderFulfillment' },
})
)
await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Done.'))
})
it('replays all dead letters with esbReplayDeadLetters', async () => {
const user = userEvent.setup()
renderWithClient(<EsbTriggerActions trigger={fulfillTrigger} permissions={ALL} />)
await user.click(screen.getByRole('button', { name: 'Replay dead letters for Fulfill Order' }))
await waitFor(() =>
expect(processInit).toHaveBeenCalledWith('esbReplayDeadLetters', {
values: { triggerName: 'fulfillOrder.orderFulfillment', all: true },
})
)
})
it('does not purge until the dialog naming the queue and message count is confirmed', async () => {
const user = userEvent.setup()
renderWithClient(<EsbQueueActions queue={fulfillmentQueue()} permissions={ALL} />)
await user.click(screen.getByRole('button', { name: 'Purge orderFulfillment' }))
let dialog = await screen.findByRole('alertdialog')
expect(dialog).toHaveTextContent('orderFulfillment')
expect(dialog).toHaveTextContent('7 messages')
expect(processInit).not.toHaveBeenCalled()
await user.click(within(dialog).getByRole('button', { name: 'Cancel' }))
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
expect(processInit).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: 'Purge orderFulfillment' }))
dialog = await screen.findByRole('alertdialog')
await user.click(within(dialog).getByRole('button', { name: 'Purge queue' }))
await waitFor(() =>
expect(processInit).toHaveBeenCalledWith('esbPurgeQueue', {
values: { providerName: 'artemis', brokerQueueName: 'orderFulfillment' },
})
)
})
it('deletes messages older than the chosen time after confirmation', async () => {
const user = userEvent.setup()
renderWithClient(<EsbQueueActions queue={fulfillmentQueue()} permissions={ALL} />)
await user.click(screen.getByRole('button', { name: 'Delete older messages in orderFulfillment' }))
const dialog = await screen.findByRole('alertdialog')
expect(dialog).toHaveTextContent('orderFulfillment')
expect(dialog).toHaveTextContent('7 messages')
const confirm = within(dialog).getByRole('button', { name: 'Delete messages' })
expect(confirm).toBeDisabled()
await user.type(within(dialog).getByLabelText('Older than'), '2026-09-25T10:00')
await user.click(confirm)
await waitFor(() =>
expect(processInit).toHaveBeenCalledWith('esbDeleteMessages', {
values: {
providerName: 'artemis',
brokerQueueName: 'orderFulfillment',
olderThan: new Date('2026-09-25T10:00').toISOString(),
},
})
)
})
it('pauses a broker queue with esbPauseQueue', async () => {
const user = userEvent.setup()
renderWithClient(<EsbQueueActions queue={fulfillmentQueue()} permissions={ALL} />)
await user.click(screen.getByRole('button', { name: 'Pause queue orderFulfillment' }))
await waitFor(() =>
expect(processInit).toHaveBeenCalledWith('esbPauseQueue', {
values: { providerName: 'artemis', brokerQueueName: 'orderFulfillment' },
})
)
})
it('shows the process error when an action fails', async () => {
vi.mocked(processInit).mockResolvedValue({ type: 'ERROR', error: 'Broker unavailable' })
const user = userEvent.setup()
renderWithClient(<EsbTriggerActions trigger={fulfillTrigger} permissions={ALL} />)
await user.click(screen.getByRole('button', { name: 'Restart Fulfill Order' }))
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Broker unavailable'))
})
it('treats a topic as having no broker queue', () => {
expect(destinationQueue(orderEsb.publications[0].destination)).toBeNull()
})
})
+658
View File
@@ -0,0 +1,658 @@
/*
* Copyright 2026 QRun.IO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file EsbActions — management actions for ESB triggers and broker queues, run as the backend's
* ESB operate processes. Each action shows only when the user holds its permission and, for broker
* queues, when the broker adapter supports it. Purge and delete ask for confirmation first.
*/
'use client'
import React, { useId, useState } from 'react'
import * as AlertDialogPrimitive from '@radix-ui/react-alert-dialog'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import type { EsbCapabilities, EsbDestination, EsbPermissions, EsbTrigger } from '@/types'
import { runEsbAction } from '@/lib/api/esb'
import { HANDLES_OWN_ERRORS, queryKeys } from '@/lib/query-client'
import { cn } from '@/lib/utils/cn'
/** A queue on the broker that management actions address. */
export interface EsbQueueRef {
/** ESB provider the queue lives on. */
providerName: string
/** Broker-side queue name. */
brokerQueueName: string
/** What the provider's broker adapter supports. */
capabilities: EsbCapabilities
/** Messages in the queue, or `null` when the broker cannot report it. */
messageCount: number | null
/** Whether delivery is paused, or `null` when unknown; pause and resume show only when known. */
paused: boolean | null
}
/** Values an operate process takes. */
type EsbActionValues = Record<string, string | boolean>
/**
* The broker queue behind a destination.
*
* @param destination - A queue or topic.
* @returns The queue, or `null` for a topic (its subscriptions are the queues).
*/
export function destinationQueue(destination: EsbDestination): EsbQueueRef | null {
if (destination.type !== 'QUEUE') return null
return {
providerName: destination.provider,
brokerQueueName: destination.brokerName,
capabilities: destination.capabilities,
messageCount: destination.queueInfo?.messageCount ?? null,
paused: destination.queueInfo?.paused ?? null,
}
}
/**
* A trigger's dead-letter queue, which lives on the same provider as its destination.
*
* @param trigger - The trigger.
* @returns Its dead-letter queue.
*/
export function deadLetterQueue(trigger: EsbTrigger): EsbQueueRef {
return {
providerName: trigger.destination.provider,
brokerQueueName: trigger.deadLetter.brokerName,
capabilities: trigger.destination.capabilities,
messageCount: trigger.deadLetter.messageCount,
paused: null,
}
}
/**
* Counts messages in words.
*
* @param count - Number of messages.
* @param adjective - Optional word before "message", e.g. `selected`.
* @returns For example `7 messages` or `1 selected message`.
*/
export function messageCountText(count: number, adjective?: string): string {
return [count, adjective, count === 1 ? 'message' : 'messages'].filter(Boolean).join(' ')
}
/**
* Runs ESB operate processes, reporting the outcome in a toast and refreshing every ESB query.
*
* @param onDone - Called after an action succeeds.
* @returns The mutation; call `mutate({ processName, values })`.
*/
export function useEsbAction(onDone?: () => void) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: ({ processName, values }: { processName: string; values: EsbActionValues }) =>
runEsbAction(processName, values),
meta: HANDLES_OWN_ERRORS,
onSuccess: (result) => {
toast.success(result.message)
void queryClient.invalidateQueries({ queryKey: queryKeys.esb() })
onDone?.()
},
onError: (error) => {
toast.error(error instanceof Error ? error.message : 'The action failed.')
},
})
}
/**
* Pause or resume, restart, and replay-dead-letter buttons for a trigger. These act on QQQ's own
* consumers on every node, so they need `esbOperate` but no broker management API.
*
* @param props - Component props.
* @param props.trigger - The trigger.
* @param props.permissions - The current user's ESB permissions.
* @returns The buttons, or `null` without `esbOperate`.
*/
export function EsbTriggerActions({
trigger,
permissions,
}: {
trigger: EsbTrigger
permissions: EsbPermissions
}) {
if (!permissions.canOperate) return null
return <TriggerButtons trigger={trigger} />
}
/**
* The trigger buttons, once the user is known to hold `esbOperate`.
*
* @param props - Component props.
* @param props.trigger - The trigger.
* @returns A group of buttons.
*/
function TriggerButtons({ trigger }: { trigger: EsbTrigger }) {
const action = useEsbAction()
const run = (processName: string, values: EsbActionValues = {}) =>
action.mutate({ processName, values: { triggerName: trigger.name, ...values } })
const paused = trigger.state === 'PAUSED'
const id = trigger.name
return (
<div className="flex flex-wrap gap-1" role="group" aria-label={`Actions for ${trigger.processLabel}`}>
{paused ? (
<ActionButton
label="Resume"
ariaLabel={`Resume ${trigger.processLabel}`}
qqqId={`button-esb-resume-trigger-${id}`}
disabled={action.isPending}
onClick={() => run('esbResumeTrigger')}
/>
) : (
<ActionButton
label="Pause"
ariaLabel={`Pause ${trigger.processLabel}`}
qqqId={`button-esb-pause-trigger-${id}`}
disabled={action.isPending}
onClick={() => run('esbPauseTrigger')}
/>
)}
<ActionButton
label="Restart"
ariaLabel={`Restart ${trigger.processLabel}`}
qqqId={`button-esb-restart-trigger-${id}`}
disabled={action.isPending}
onClick={() => run('esbRestartTrigger')}
/>
{trigger.deadLetter.messageCount !== 0 && (
<ActionButton
label="Replay dead letters"
ariaLabel={`Replay dead letters for ${trigger.processLabel}`}
qqqId={`button-esb-replay-dead-letters-${id}`}
disabled={action.isPending}
onClick={() => run('esbReplayDeadLetters', { all: true })}
/>
)}
</div>
)
}
/**
* Pause or resume, purge, and delete-older-than buttons for a broker queue. Pause and resume need
* `esbOperate`; purge and delete need `esbDelete`; each also needs the broker to support it.
*
* @param props - Component props.
* @param props.queue - The broker queue.
* @param props.permissions - The current user's ESB permissions.
* @returns The buttons, or `null` when none is available.
*/
export function EsbQueueActions({
queue,
permissions,
}: {
queue: EsbQueueRef
permissions: EsbPermissions
}) {
const canPause = permissions.canOperate && queue.capabilities.pauseQueue && queue.paused !== null
const canPurge = permissions.canDelete && queue.capabilities.purge
const canDeleteOlder = permissions.canDelete && queue.capabilities.deleteOlderThan
if (!canPause && !canPurge && !canDeleteOlder) return null
return (
<QueueButtons
queue={queue}
canPause={canPause}
canPurge={canPurge}
canDeleteOlder={canDeleteOlder}
/>
)
}
/**
* The queue buttons and their confirmation dialogs.
*
* @param props - Component props.
* @param props.queue - The broker queue.
* @param props.canPause - Whether to offer pause or resume.
* @param props.canPurge - Whether to offer purge.
* @param props.canDeleteOlder - Whether to offer deleting messages older than a time.
* @returns A group of buttons.
*/
function QueueButtons({
queue,
canPause,
canPurge,
canDeleteOlder,
}: {
queue: EsbQueueRef
canPause: boolean
canPurge: boolean
canDeleteOlder: boolean
}) {
const [dialog, setDialog] = useState<'purge' | 'deleteOlder' | null>(null)
const [olderThan, setOlderThan] = useState('')
const olderThanId = useId()
const close = () => {
setDialog(null)
setOlderThan('')
}
const action = useEsbAction(close)
const target = { providerName: queue.providerName, brokerQueueName: queue.brokerQueueName }
const name = queue.brokerQueueName
const inQueue =
queue.messageCount === null ? '' : ` (${messageCountText(queue.messageCount)} in the queue)`
const cutoff = olderThan ? new Date(olderThan) : null
const cutoffValid = cutoff !== null && !Number.isNaN(cutoff.getTime())
return (
<div className="flex flex-wrap gap-1" role="group" aria-label={`Actions for queue ${name}`}>
{canPause && (
<ActionButton
label={queue.paused ? 'Resume queue' : 'Pause queue'}
ariaLabel={`${queue.paused ? 'Resume' : 'Pause'} queue ${name}`}
qqqId={`button-esb-${queue.paused ? 'resume' : 'pause'}-queue-${name}`}
disabled={action.isPending}
onClick={() =>
action.mutate({
processName: queue.paused ? 'esbResumeQueue' : 'esbPauseQueue',
values: target,
})
}
/>
)}
{canPurge && (
<ActionButton
label="Purge"
ariaLabel={`Purge ${name}`}
qqqId={`button-esb-purge-${name}`}
destructive
disabled={action.isPending}
onClick={() => setDialog('purge')}
/>
)}
{canDeleteOlder && (
<ActionButton
label="Delete older"
ariaLabel={`Delete older messages in ${name}`}
qqqId={`button-esb-delete-older-${name}`}
destructive
disabled={action.isPending}
onClick={() => setDialog('deleteOlder')}
/>
)}
<EsbConfirmDialog
open={dialog === 'purge'}
title="Purge queue"
confirmLabel="Purge queue"
pending={action.isPending}
onCancel={close}
onConfirm={() => action.mutate({ processName: 'esbPurgeQueue', values: target })}
>
{queue.messageCount === null
? `Delete every message in queue ${name} on ${queue.providerName}?`
: `Delete all ${messageCountText(queue.messageCount)} in queue ${name} on ${queue.providerName}?`}{' '}
This cannot be undone.
</EsbConfirmDialog>
<EsbConfirmDialog
open={dialog === 'deleteOlder'}
title="Delete older messages"
confirmLabel="Delete messages"
pending={action.isPending}
confirmDisabled={!cutoffValid}
onCancel={close}
onConfirm={() => {
if (!cutoffValid) return
action.mutate({
processName: 'esbDeleteMessages',
values: { ...target, olderThan: cutoff.toISOString() },
})
}}
body={
<div className="mt-4 space-y-1">
<label htmlFor={olderThanId} className="text-sm font-medium text-foreground">
Older than
</label>
<input
id={olderThanId}
type="datetime-local"
value={olderThan}
onChange={(event) => setOlderThan(event.target.value)}
aria-required="true"
className="block w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-ring"
data-qqq-id={`input-esb-older-than-${name}`}
/>
</div>
}
>
Delete the messages older than the chosen time from queue {name} on {queue.providerName}
{inQueue}? This cannot be undone.
</EsbConfirmDialog>
</div>
)
}
/**
* Replay, move and delete buttons for messages selected in a browsed queue. Replay needs
* `esbOperate` and a trigger (dead letters only); move needs `esbOperate`; delete needs
* `esbDelete`; move and delete also need the broker to support them.
*
* @param props - Component props.
* @param props.queue - The broker queue the messages are in.
* @param props.permissions - The current user's ESB permissions.
* @param props.messageIds - The selected messages.
* @param props.replayTriggerName - For dead letters, the trigger whose process replays them.
* @param props.onDone - Called after an action succeeds, e.g. to clear the selection.
* @returns The buttons, or `null` when none is available.
*/
export function EsbSelectionActions({
queue,
permissions,
messageIds,
replayTriggerName,
onDone,
}: {
queue: EsbQueueRef
permissions: EsbPermissions
messageIds: string[]
replayTriggerName?: string
onDone?: () => void
}) {
const available = selectionActions(queue, permissions, replayTriggerName)
if (!available.replay && !available.move && !available.delete) return null
return (
<SelectionButtons
queue={queue}
messageIds={messageIds}
replayTriggerName={replayTriggerName}
available={available}
onDone={onDone}
/>
)
}
/**
* Which actions on selected messages the user may take.
*
* @param queue - The broker queue the messages are in.
* @param permissions - The current user's ESB permissions.
* @param replayTriggerName - For dead letters, the trigger whose process replays them.
* @returns A flag per action.
*/
export function selectionActions(
queue: EsbQueueRef,
permissions: EsbPermissions,
replayTriggerName?: string
): { replay: boolean; move: boolean; delete: boolean } {
return {
replay: permissions.canOperate && Boolean(replayTriggerName),
move: permissions.canOperate && queue.capabilities.move,
delete: permissions.canDelete && queue.capabilities.deleteSelected,
}
}
/**
* The selection buttons and their dialogs.
*
* @param props - Component props.
* @param props.queue - The broker queue the messages are in.
* @param props.messageIds - The selected messages.
* @param props.replayTriggerName - For dead letters, the trigger whose process replays them.
* @param props.available - Which actions to offer.
* @param props.onDone - Called after an action succeeds.
* @returns A group of buttons.
*/
function SelectionButtons({
queue,
messageIds,
replayTriggerName,
available,
onDone,
}: {
queue: EsbQueueRef
messageIds: string[]
replayTriggerName?: string
available: { replay: boolean; move: boolean; delete: boolean }
onDone?: () => void
}) {
const [dialog, setDialog] = useState<'move' | 'delete' | null>(null)
const [toQueue, setToQueue] = useState('')
const toQueueId = useId()
const close = () => {
setDialog(null)
setToQueue('')
}
const action = useEsbAction(() => {
close()
onDone?.()
})
const name = queue.brokerQueueName
const ids = messageIds.join(',')
const selected = messageCountText(messageIds.length, 'selected')
const target = { providerName: queue.providerName, brokerQueueName: name, messageIds: ids }
const none = messageIds.length === 0 || action.isPending
return (
<div className="flex flex-wrap gap-1" role="group" aria-label="Actions for selected messages">
{available.replay && replayTriggerName && (
<ActionButton
label="Replay selected"
qqqId={`button-esb-replay-selected-${name}`}
disabled={none}
onClick={() =>
action.mutate({
processName: 'esbReplayDeadLetters',
values: { triggerName: replayTriggerName, messageIds: ids },
})
}
/>
)}
{available.move && (
<ActionButton
label="Move selected"
qqqId={`button-esb-move-selected-${name}`}
disabled={none}
onClick={() => setDialog('move')}
/>
)}
{available.delete && (
<ActionButton
label="Delete selected"
qqqId={`button-esb-delete-selected-${name}`}
destructive
disabled={none}
onClick={() => setDialog('delete')}
/>
)}
<EsbConfirmDialog
open={dialog === 'move'}
title="Move messages"
confirmLabel="Move messages"
destructive={false}
pending={action.isPending}
confirmDisabled={!toQueue.trim()}
onCancel={close}
onConfirm={() =>
action.mutate({
processName: 'esbMoveMessages',
values: { ...target, toBrokerQueueName: toQueue.trim() },
})
}
body={
<div className="mt-4 space-y-1">
<label htmlFor={toQueueId} className="text-sm font-medium text-foreground">
Target queue
</label>
<input
id={toQueueId}
type="text"
value={toQueue}
onChange={(event) => setToQueue(event.target.value)}
aria-required="true"
className="block w-full rounded-md border border-input bg-background px-3 py-2 font-mono text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-ring"
data-qqq-id={`input-esb-move-target-${name}`}
/>
</div>
}
>
Move {selected} from queue {name} on {queue.providerName} to another queue on the same
broker.
</EsbConfirmDialog>
<EsbConfirmDialog
open={dialog === 'delete'}
title="Delete messages"
confirmLabel="Delete messages"
pending={action.isPending}
onCancel={close}
onConfirm={() => action.mutate({ processName: 'esbDeleteMessages', values: target })}
>
Delete {selected} from queue {name} on {queue.providerName}? This cannot be undone.
</EsbConfirmDialog>
</div>
)
}
/**
* A small outlined action button.
*
* @param props - Component props.
* @param props.label - Visible text.
* @param props.ariaLabel - Accessible name when the visible text needs context; it starts with `label`.
* @param props.qqqId - `data-qqq-id` value.
* @param props.destructive - Whether to style it as destructive.
* @param props.disabled - Whether it is disabled.
* @param props.onClick - Click handler.
* @returns The button.
*/
function ActionButton({
label,
ariaLabel,
qqqId,
destructive = false,
disabled = false,
onClick,
}: {
label: string
ariaLabel?: string
qqqId: string
destructive?: boolean
disabled?: boolean
onClick: () => void
}) {
return (
<button
type="button"
onClick={onClick}
disabled={disabled}
aria-label={ariaLabel}
data-qqq-id={qqqId}
className={cn(
'inline-flex items-center rounded-md border px-2 py-1 text-xs font-medium transition-colors',
'focus:outline-none focus:ring-2 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50',
destructive
? 'border-destructive/40 text-destructive hover:bg-destructive/10'
: 'border-input bg-background text-foreground hover:bg-accent'
)}
>
{label}
</button>
)
}
/**
* A confirmation dialog: nothing runs until the confirm button is pressed.
*
* @param props - Component props.
* @param props.open - Whether the dialog is shown.
* @param props.title - Heading, also the dialog's accessible name.
* @param props.children - The question, naming what the action affects.
* @param props.body - Optional inputs shown under the question.
* @param props.confirmLabel - Text of the confirm button.
* @param props.destructive - Whether to style the confirm button as destructive (default true).
* @param props.confirmDisabled - Whether the confirm button is disabled, e.g. until an input is valid.
* @param props.pending - Whether the action is running.
* @param props.onConfirm - Runs the action.
* @param props.onCancel - Closes the dialog without running anything.
* @returns The dialog.
*/
export function EsbConfirmDialog({
open,
title,
children,
body,
confirmLabel,
destructive = true,
confirmDisabled = false,
pending,
onConfirm,
onCancel,
}: {
open: boolean
title: string
children: React.ReactNode
body?: React.ReactNode
confirmLabel: string
destructive?: boolean
confirmDisabled?: boolean
pending: boolean
onConfirm: () => void
onCancel: () => void
}) {
return (
<AlertDialogPrimitive.Root open={open} onOpenChange={(isOpen) => { if (!isOpen) onCancel() }}>
<AlertDialogPrimitive.Portal>
<AlertDialogPrimitive.Overlay className="fixed inset-0 z-50 bg-black/50" />
<AlertDialogPrimitive.Content
data-qqq-id="esb-confirm-dialog"
className="fixed left-1/2 top-1/2 z-50 w-full max-w-md -translate-x-1/2 -translate-y-1/2 rounded-xl border border-border bg-background shadow-lg focus:outline-none"
>
<div className="p-6">
<AlertDialogPrimitive.Title className="text-lg font-semibold text-foreground">
{title}
</AlertDialogPrimitive.Title>
<AlertDialogPrimitive.Description className="mt-2 text-sm text-muted-foreground">
{children}
</AlertDialogPrimitive.Description>
{body}
</div>
<div className="flex items-center justify-end gap-3 rounded-b-xl bg-muted px-6 py-4">
<AlertDialogPrimitive.Cancel
data-qqq-id="button-esb-confirm-cancel"
className="inline-flex items-center rounded-md border border-input bg-background px-4 py-2 text-sm font-medium text-foreground hover:bg-accent focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
>
Cancel
</AlertDialogPrimitive.Cancel>
<button
type="button"
onClick={onConfirm}
disabled={confirmDisabled || pending}
data-qqq-id="button-esb-confirm"
className={cn(
'inline-flex items-center rounded-md px-4 py-2 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
destructive
? 'bg-destructive text-destructive-foreground hover:bg-destructive/90 focus:ring-destructive'
: 'bg-primary text-primary-foreground hover:bg-primary/90 focus:ring-ring'
)}
>
{confirmLabel}
</button>
</div>
</AlertDialogPrimitive.Content>
</AlertDialogPrimitive.Portal>
</AlertDialogPrimitive.Root>
)
}
+218
View File
@@ -0,0 +1,218 @@
/*
* Copyright 2026 QRun.IO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Tests for browsing ESB messages and acting on selected ones
import React from 'react'
import { render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { http, HttpResponse } from 'msw'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { EsbPermissions } from '@/types'
import { processInit } from '@/lib/api/processes'
import { orderEsb, orderFulfillmentMessages } from '@/mocks/fixtures/esb'
import { server } from '@/mocks/node'
import { deadLetterQueue, destinationQueue, type EsbQueueRef } from './EsbActions'
import { EsbBrowseButton, EsbMessageList, type EsbMessageSource } from './EsbMessageList'
vi.mock('@/lib/api/processes', () => ({ processInit: vi.fn() }))
const fulfillTrigger = orderEsb.subscribers[0]
const ALL: EsbPermissions = { canOperate: true, canDelete: true }
const NONE: EsbPermissions = { canOperate: false, canDelete: false }
const QUEUE_SOURCE: EsbMessageSource = { kind: 'destination', name: 'orderFulfillment' }
const DEAD_LETTER_SOURCE: EsbMessageSource = {
kind: 'deadLetters',
triggerName: 'fulfillOrder.orderFulfillment',
}
/**
* The broker queue behind the `orderFulfillment` destination.
*
* @returns Its queue reference.
*/
function fulfillmentQueue(): EsbQueueRef {
const queue = destinationQueue(orderEsb.publications[1].destination)
if (!queue) throw new Error('orderFulfillment is a queue')
return queue
}
/**
* Renders a component inside a fresh query client.
*
* @param ui - The element to render.
*/
function renderWithClient(ui: React.ReactElement): void {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
render(<QueryClientProvider client={client}>{ui}</QueryClientProvider>)
}
describe('EsbMessageList', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(processInit).mockResolvedValue({
type: 'COMPLETE',
processUUID: 'uuid',
values: { count: 1, message: 'Done.' },
})
})
it('lists a queue\'s messages with their event type and subject', async () => {
renderWithClient(
<EsbMessageList source={QUEUE_SOURCE} queue={fulfillmentQueue()} permissions={NONE} />
)
const table = await screen.findByRole('table', { name: 'Messages' })
const rows = within(table).getAllByRole('row').slice(1)
expect(rows).toHaveLength(2)
expect(rows[0]).toHaveTextContent('ID:msg-1')
expect(rows[0]).toHaveTextContent('qqq.table.order.INSERT')
expect(rows[0]).toHaveTextContent('1001')
expect(rows[1]).toHaveTextContent('ID:msg-2')
})
it('shows a dead letter\'s error and raw body when it is not a CloudEvent', async () => {
renderWithClient(
<EsbMessageList
source={DEAD_LETTER_SOURCE}
queue={deadLetterQueue(fulfillTrigger)}
permissions={NONE}
/>
)
const table = await screen.findByRole('table', { name: 'Messages' })
expect(table).toHaveTextContent('unparseable message')
expect(table).toHaveTextContent('Not a CloudEvent')
expect(table).toHaveTextContent('not json')
})
it('pages forward while the backend has more messages', async () => {
const offsets: string[] = []
server.use(
http.get('/qqq/v1/esb/messages/orderFulfillment', ({ request }) => {
const offset = new URL(request.url).searchParams.get('offset') ?? ''
offsets.push(offset)
return HttpResponse.json(
offset === '0' ? orderFulfillmentMessages : { messages: [], hasMore: false }
)
})
)
const user = userEvent.setup()
renderWithClient(
<EsbMessageList source={QUEUE_SOURCE} queue={fulfillmentQueue()} permissions={NONE} />
)
await screen.findByRole('table', { name: 'Messages' })
expect(screen.getByRole('button', { name: 'Previous page' })).toBeDisabled()
await user.click(screen.getByRole('button', { name: 'Next page' }))
await screen.findByText('No messages.')
expect(offsets).toEqual(['0', '50'])
expect(screen.getByRole('button', { name: 'Next page' })).toBeDisabled()
})
it('offers no selection without permission', async () => {
renderWithClient(
<EsbMessageList source={QUEUE_SOURCE} queue={fulfillmentQueue()} permissions={NONE} />
)
await screen.findByRole('table', { name: 'Messages' })
expect(screen.queryByRole('checkbox')).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /selected/ })).not.toBeInTheDocument()
})
it('deletes the selected messages after a confirmation naming the queue and count', async () => {
const user = userEvent.setup()
renderWithClient(
<EsbMessageList source={QUEUE_SOURCE} queue={fulfillmentQueue()} permissions={ALL} />
)
await user.click(await screen.findByRole('checkbox', { name: 'Select ID:msg-1' }))
await user.click(screen.getByRole('checkbox', { name: 'Select ID:msg-2' }))
await user.click(screen.getByRole('button', { name: 'Delete selected' }))
const dialog = await screen.findByRole('alertdialog')
expect(dialog).toHaveTextContent('2 selected messages')
expect(dialog).toHaveTextContent('orderFulfillment')
expect(processInit).not.toHaveBeenCalled()
await user.click(within(dialog).getByRole('button', { name: 'Delete messages' }))
await waitFor(() =>
expect(processInit).toHaveBeenCalledWith('esbDeleteMessages', {
values: {
providerName: 'artemis',
brokerQueueName: 'orderFulfillment',
messageIds: 'ID:msg-1,ID:msg-2',
},
})
)
})
it('moves the selected messages to the named queue', async () => {
const user = userEvent.setup()
renderWithClient(
<EsbMessageList source={QUEUE_SOURCE} queue={fulfillmentQueue()} permissions={ALL} />
)
await user.click(await screen.findByRole('checkbox', { name: 'Select ID:msg-2' }))
await user.click(screen.getByRole('button', { name: 'Move selected' }))
const dialog = await screen.findByRole('alertdialog')
const confirm = within(dialog).getByRole('button', { name: 'Move messages' })
expect(confirm).toBeDisabled()
await user.type(within(dialog).getByLabelText('Target queue'), 'orderFulfillment.hold')
await user.click(confirm)
await waitFor(() =>
expect(processInit).toHaveBeenCalledWith('esbMoveMessages', {
values: {
providerName: 'artemis',
brokerQueueName: 'orderFulfillment',
messageIds: 'ID:msg-2',
toBrokerQueueName: 'orderFulfillment.hold',
},
})
)
})
it('replays the selected dead letters through the trigger', async () => {
const user = userEvent.setup()
renderWithClient(
<EsbMessageList
source={DEAD_LETTER_SOURCE}
queue={deadLetterQueue(fulfillTrigger)}
permissions={{ canOperate: true, canDelete: false }}
/>
)
await user.click(await screen.findByRole('checkbox', { name: 'Select ID:dlq-1' }))
expect(screen.queryByRole('button', { name: 'Delete selected' })).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Replay selected' }))
await waitFor(() =>
expect(processInit).toHaveBeenCalledWith('esbReplayDeadLetters', {
values: { triggerName: 'fulfillOrder.orderFulfillment', messageIds: 'ID:dlq-1' },
})
)
})
it('opens the list in a dialog from the browse button', async () => {
const user = userEvent.setup()
renderWithClient(
<EsbBrowseButton
label="Browse"
title="Messages in orderFulfillment"
source={QUEUE_SOURCE}
queue={fulfillmentQueue()}
permissions={NONE}
/>
)
expect(screen.queryByRole('table', { name: 'Messages' })).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Browse' }))
const dialog = await screen.findByRole('dialog', { name: 'Messages in orderFulfillment' })
expect(await within(dialog).findByRole('table', { name: 'Messages' })).toBeInTheDocument()
})
})
+329
View File
@@ -0,0 +1,329 @@
/*
* Copyright 2026 QRun.IO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file EsbMessageList — pages through the messages waiting on a queue or in a trigger's
* dead-letter queue, with replay, move and delete for selected messages when permitted, and
* purge and delete-older-than for the dead-letter queue itself.
*/
'use client'
import React, { useState } from 'react'
import * as DialogPrimitive from '@radix-ui/react-dialog'
import { useQuery } from '@tanstack/react-query'
import { X } from 'lucide-react'
import type { EsbMessage, EsbPermissions } from '@/types'
import { ESB_PAGE_SIZE, getEsbDeadLetters, getEsbMessages } from '@/lib/api/esb'
import { HANDLES_OWN_ERRORS, queryKeys } from '@/lib/query-client'
import { formatDateTime } from '@/lib/utils/datetime-utils'
import {
EsbQueueActions,
EsbSelectionActions,
selectionActions,
type EsbQueueRef,
} from './EsbActions'
/** What to browse: the queue behind a destination, or a trigger's dead letters. */
export type EsbMessageSource =
| { kind: 'destination'; name: string }
| { kind: 'deadLetters'; triggerName: string }
/** Props for {@link EsbMessageList}. */
interface EsbMessageListProps {
source: EsbMessageSource
/** The broker queue holding the messages, for actions on selected ones. */
queue: EsbQueueRef
permissions: EsbPermissions
}
/**
* Lists one page of browsed messages at a time: id, time, delivery count, CloudEvent type and
* subject (or the raw body when it is not a CloudEvent), and the `qqqError` a dead letter carries.
* Each row can be selected when an action on selected messages is available. Dead letters also
* get the queue actions, since their queue is shown nowhere else.
*
* @param props - See {@link EsbMessageListProps}.
* @returns The action bars, the message table with previous and next buttons, or a loading,
* error or empty state.
*/
export function EsbMessageList({ source, queue, permissions }: EsbMessageListProps) {
const [offset, setOffset] = useState(0)
const [selected, setSelected] = useState<string[]>([])
const name = source.kind === 'destination' ? source.name : source.triggerName
const replayTriggerName = source.kind === 'deadLetters' ? source.triggerName : undefined
const available = selectionActions(queue, permissions, replayTriggerName)
const selectable = available.replay || available.move || available.delete
const { data, isLoading, error } = useQuery({
queryKey: queryKeys.esbMessages(source.kind, name, offset),
queryFn: () =>
source.kind === 'destination'
? getEsbMessages(source.name, offset)
: getEsbDeadLetters(source.triggerName, offset),
meta: HANDLES_OWN_ERRORS,
})
const goTo = (nextOffset: number) => {
setOffset(Math.max(0, nextOffset))
setSelected([])
}
const toggle = (messageId: string) =>
setSelected((current) =>
current.includes(messageId) ? current.filter((id) => id !== messageId) : [...current, messageId]
)
return (
<div className="space-y-3" data-qqq-id={`esb-message-list-${name}`}>
{source.kind === 'deadLetters' && <EsbQueueActions queue={queue} permissions={permissions} />}
{selectable && (
<EsbSelectionActions
queue={queue}
permissions={permissions}
messageIds={selected}
replayTriggerName={replayTriggerName}
onDone={() => setSelected([])}
/>
)}
{isLoading && (
<p className="text-sm text-muted-foreground" role="status">
Loading messages…
</p>
)}
{error && (
<p className="text-sm text-destructive" role="alert">
Failed to load messages: {error instanceof Error ? error.message : 'Unknown error'}
</p>
)}
{data && data.messages.length === 0 && (
<p className="text-sm text-muted-foreground">No messages.</p>
)}
{data && data.messages.length > 0 && (
<div className="overflow-x-auto">
<table className="w-full text-sm" aria-label="Messages">
<thead>
<tr className="border-b border-border text-left">
{selectable && (
<th scope="col" className="px-2 py-1.5">
<span className="sr-only">Select</span>
</th>
)}
{['Message', 'Time', 'Deliveries', 'Event'].map((column) => (
<th
key={column}
scope="col"
className="whitespace-nowrap px-2 py-1.5 font-medium text-muted-foreground"
>
{column}
</th>
))}
</tr>
</thead>
<tbody>
{data.messages.map((message) => (
<MessageRow
key={message.messageId}
message={message}
selectable={selectable}
selected={selected.includes(message.messageId)}
onToggle={() => toggle(message.messageId)}
/>
))}
</tbody>
</table>
</div>
)}
<div className="flex items-center justify-end gap-2">
<PageButton
label="Previous page"
disabled={offset === 0}
onClick={() => goTo(offset - ESB_PAGE_SIZE)}
>
Previous
</PageButton>
<PageButton
label="Next page"
disabled={!data?.hasMore}
onClick={() => goTo(offset + ESB_PAGE_SIZE)}
>
Next
</PageButton>
</div>
</div>
)
}
/**
* One browsed message as a table row.
*
* @param props - Component props.
* @param props.message - The message.
* @param props.selectable - Whether to show a selection checkbox.
* @param props.selected - Whether it is selected.
* @param props.onToggle - Toggles its selection.
* @returns The row.
*/
function MessageRow({
message,
selectable,
selected,
onToggle,
}: {
message: EsbMessage
selectable: boolean
selected: boolean
onToggle: () => void
}) {
const error = message.properties.qqqError
return (
<tr
className="border-b border-border/50 align-top last:border-0"
data-qqq-id={`esb-message-${message.messageId}`}
>
{selectable && (
<td className="px-2 py-2">
<input
type="checkbox"
checked={selected}
onChange={onToggle}
aria-label={`Select ${message.messageId}`}
className="h-4 w-4 rounded border-input focus:ring-2 focus:ring-ring"
data-qqq-id={`checkbox-esb-message-${message.messageId}`}
/>
</td>
)}
<td className="px-2 py-2 font-mono text-xs text-foreground">{message.messageId}</td>
<td className="whitespace-nowrap px-2 py-2 text-foreground">
{formatDateTime(message.timestamp) ?? message.timestamp}
</td>
<td className="px-2 py-2 tabular-nums text-foreground">{message.deliveryCount}</td>
<td className="space-y-1 px-2 py-2">
{message.event ? (
<p className="text-foreground">
<span className="font-mono text-xs">{message.event.type}</span>
{message.event.subject && (
<span className="text-muted-foreground"> · {message.event.subject}</span>
)}
</p>
) : (
<p className="text-muted-foreground">Not a CloudEvent</p>
)}
{error != null && <p className="break-words text-destructive">{String(error)}</p>}
<details>
<summary className="cursor-pointer text-xs text-primary focus:outline-none focus:ring-2 focus:ring-ring">
Body
</summary>
<pre className="mt-1 max-h-60 overflow-auto whitespace-pre-wrap break-all rounded bg-muted p-2 text-xs text-foreground">
{message.rawBody}
</pre>
</details>
</td>
</tr>
)
}
/**
* A pager button.
*
* @param props - Component props.
* @param props.label - Accessible name.
* @param props.disabled - Whether it is disabled.
* @param props.onClick - Click handler.
* @param props.children - Visible text.
* @returns The button.
*/
function PageButton({
label,
disabled,
onClick,
children,
}: {
label: string
disabled: boolean
onClick: () => void
children: React.ReactNode
}) {
return (
<button
type="button"
aria-label={label}
disabled={disabled}
onClick={onClick}
data-qqq-id={`button-esb-messages-${label.toLowerCase().replace(' ', '-')}`}
className="inline-flex items-center rounded-md border border-input bg-background px-3 py-1 text-xs font-medium text-foreground hover:bg-accent focus:outline-none focus:ring-2 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
>
{children}
</button>
)
}
/** Props for {@link EsbBrowseButton}. */
interface EsbBrowseButtonProps extends EsbMessageListProps {
/** Visible button text. */
label: string
/** Accessible name when the visible text needs context; it starts with `label`. */
ariaLabel?: string
/** Dialog heading. */
title: string
}
/**
* A button that opens an {@link EsbMessageList} in a dialog. The list, and its requests, exist
* only while the dialog is open.
*
* @param props - See {@link EsbBrowseButtonProps}.
* @returns The button and its dialog.
*/
export function EsbBrowseButton({ label, ariaLabel, title, ...listProps }: EsbBrowseButtonProps) {
const name =
listProps.source.kind === 'destination' ? listProps.source.name : listProps.source.triggerName
return (
<DialogPrimitive.Root>
<DialogPrimitive.Trigger
aria-label={ariaLabel}
data-qqq-id={`button-esb-browse-${listProps.source.kind}-${name}`}
className="inline-flex items-center rounded-md border border-input bg-background px-2 py-1 text-xs font-medium text-foreground hover:bg-accent focus:outline-none focus:ring-2 focus:ring-ring"
>
{label}
</DialogPrimitive.Trigger>
<DialogPrimitive.Portal>
<DialogPrimitive.Overlay className="fixed inset-0 z-50 bg-black/50" />
<DialogPrimitive.Content
aria-describedby={undefined}
data-qqq-id={`esb-browse-dialog-${name}`}
className="fixed left-1/2 top-1/2 z-50 max-h-[85vh] w-[calc(100%-2rem)] max-w-4xl -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-xl border border-border bg-background p-6 shadow-lg focus:outline-none"
>
<div className="mb-4 flex items-start justify-between gap-4">
<DialogPrimitive.Title className="text-lg font-semibold text-foreground">
{title}
</DialogPrimitive.Title>
<DialogPrimitive.Close
aria-label="Close"
data-qqq-id="button-esb-browse-close"
className="rounded-md p-1 text-muted-foreground hover:bg-accent focus:outline-none focus:ring-2 focus:ring-ring"
>
<X className="h-4 w-4" aria-hidden="true" />
</DialogPrimitive.Close>
</div>
<EsbMessageList {...listProps} />
</DialogPrimitive.Content>
</DialogPrimitive.Portal>
</DialogPrimitive.Root>
)
}
+45 -1
View File
@@ -18,10 +18,11 @@
import React from 'react'
import { act, render, screen, within } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { axe } from 'jest-axe'
import { describe, expect, it } from 'vitest'
import { orderEsb } from '@/mocks/fixtures/esb'
import { fulfillOrderEsb, orderEsb } from '@/mocks/fixtures/esb'
import { EsbSection } from './EsbSection'
/**
@@ -123,6 +124,49 @@ describe('EsbSection', () => {
).toBeInTheDocument()
})
it('offers browsing a queue and a trigger\'s dead letters to anyone who sees them', () => {
render(<EsbSection data={orderEsb} />)
const [topic, queue] = bodyRows('Publications')
expect(within(topic).queryByRole('button')).not.toBeInTheDocument()
expect(within(queue).getByRole('button', { name: 'Browse orderFulfillment' })).toBeInTheDocument()
expect(within(queue).queryByRole('button', { name: /^Purge/ })).not.toBeInTheDocument()
const [fulfill] = bodyRows('Subscribers')
expect(
within(fulfill).getByRole('button', { name: 'Browse dead letters for Fulfill Order' })
).toBeInTheDocument()
expect(within(fulfill).queryByRole('button', { name: /^Pause/ })).not.toBeInTheDocument()
})
it('shows management actions when the user may operate and delete', () => {
render(
<QueryClientProvider client={new QueryClient()}>
<EsbSection data={{ ...orderEsb, permissions: { canOperate: true, canDelete: true } }} />
</QueryClientProvider>
)
const [topic, queue] = bodyRows('Publications')
expect(within(topic).queryByRole('button')).not.toBeInTheDocument()
expect(within(queue).getByRole('button', { name: 'Purge orderFulfillment' })).toBeInTheDocument()
expect(
within(queue).getByRole('button', { name: 'Pause queue orderFulfillment' })
).toBeInTheDocument()
const [fulfill, cancel] = bodyRows('Subscribers')
expect(within(fulfill).getByRole('button', { name: 'Pause Fulfill Order' })).toBeInTheDocument()
expect(within(cancel).getByRole('button', { name: 'Resume Cancel Order' })).toBeInTheDocument()
})
it('renders a process\'s publications and the triggers that start it', () => {
render(<EsbSection data={fulfillOrderEsb} />)
expect(bodyRows('Publications')).toHaveLength(1)
expect(bodyRows('Triggers')).toHaveLength(1)
expect(screen.queryByRole('table', { name: 'Subscribers' })).not.toBeInTheDocument()
})
it('says so when a process has no publications or triggers', () => {
render(<EsbSection data={{ ...fulfillOrderEsb, publications: [], triggers: [] }} />)
expect(screen.getByText('This process does not publish to any destination.')).toBeInTheDocument()
expect(screen.getByText('No destinations trigger this process.')).toBeInTheDocument()
})
it('has no accessibility violations', async () => {
const { container } = render(<EsbSection data={orderEsb} />)
// next/link updates its prefetch state while axe runs; act() flushes it.
+78 -19
View File
@@ -15,44 +15,60 @@
*/
/**
* @file EsbSection — the ESB part of a table's Developer view: the destinations the table
* publishes to and the processes those destinations trigger, with per-node counters.
* @file EsbSection — the ESB part of a table's or process's Developer view: the destinations it
* publishes to and the triggers on them, with per-node counters and management actions.
*/
import React, { useId } from 'react'
import { Network } from 'lucide-react'
import type { EsbDestinationType, EsbTableResponse } from '@/types'
import type {
EsbDestination,
EsbDestinationType,
EsbPermissions,
EsbProcessResponse,
EsbTableResponse,
} from '@/types'
import { EsbQueueActions, destinationQueue } from './EsbActions'
import { EsbCounters } from './EsbCounters'
import { EsbBrowseButton } from './EsbMessageList'
import { EsbTriggerRow } from './EsbTriggerRow'
/** Label for each destination type. */
const DESTINATION_TYPES: Record<EsbDestinationType, string> = { QUEUE: 'Queue', TOPIC: 'Topic' }
export const DESTINATION_TYPES: Record<EsbDestinationType, string> = { QUEUE: 'Queue', TOPIC: 'Topic' }
/** Column headings of a trigger table, matching {@link EsbTriggerRow}. */
export const TRIGGER_COLUMNS = ['Process', 'Destination', 'State', 'Counters', 'Dead letters', 'Actions']
/** Props for {@link EsbSection}. */
interface EsbSectionProps {
/** The table's ESB data, or `null` when the table has none or the user may not see it. */
data: EsbTableResponse | null
/** The table's or process's ESB data, or `null` when it has none or the user may not see it. */
data: EsbTableResponse | EsbProcessResponse | null
}
/**
* Renders a table's ESB publications and subscribers, or nothing when `data` is `null`.
* Renders a table's or process's ESB publications and triggers, or nothing when `data` is `null`.
*
* @param props - Component props.
* @param props.data - Response of `GET /esb/table/{table}`, or `null`.
* @param props.data - Response of `GET /esb/table/{table}` or `GET /esb/process/{process}`, or `null`.
* @returns A section with a Publications table (destination, type, events, counters, queue
* depth) and a Subscribers table (process, destination, state, counters, dead letters),
* each replaced by a sentence when empty; or `null`.
* depth, actions) and a Subscribers table for a table or a Triggers table for a process
* (process, destination, state, counters, dead letters, actions), each replaced by a
* sentence when empty; or `null`.
*/
export function EsbSection({ data }: EsbSectionProps) {
const headingId = useId()
if (!data) return null
const isTable = 'table' in data
const owner = isTable ? data.table : data.process
const triggers = isTable ? data.subscribers : data.triggers
return (
<section
aria-labelledby={headingId}
className="space-y-4 rounded-xl border border-border bg-card p-4"
data-qqq-id={`esb-section-${data.table}`}
data-qqq-id={`esb-section-${owner}`}
>
<div className="flex items-center gap-2">
<Network className="h-5 w-5 text-muted-foreground" aria-hidden="true" />
@@ -63,8 +79,8 @@ export function EsbSection({ data }: EsbSectionProps) {
<EsbList
title="Publications"
columns={['Destination', 'Type', 'Events', 'Counters', 'Queue depth']}
empty="This table does not publish to any destination."
columns={['Destination', 'Type', 'Events', 'Counters', 'Queue depth', 'Actions']}
empty={`This ${isTable ? 'table' : 'process'} does not publish to any destination.`}
>
{data.publications.map(({ destination, events }) => (
<tr
@@ -83,23 +99,66 @@ export function EsbSection({ data }: EsbSectionProps) {
<td className="px-2 py-2 tabular-nums text-foreground">
{destination.queueInfo ? destination.queueInfo.messageCount : '—'}
</td>
<td className="px-2 py-2">
<EsbDestinationActions destination={destination} permissions={data.permissions} />
</td>
</tr>
))}
</EsbList>
<EsbList
title="Subscribers"
columns={['Process', 'Destination', 'State', 'Counters', 'Dead letters']}
empty="No processes you can access are triggered by these destinations."
title={isTable ? 'Subscribers' : 'Triggers'}
columns={TRIGGER_COLUMNS}
empty={
isTable
? 'No processes you can access are triggered by these destinations.'
: 'No destinations trigger this process.'
}
>
{data.subscribers.map((trigger) => (
<EsbTriggerRow key={trigger.name} trigger={trigger} />
{triggers.map((trigger) => (
<EsbTriggerRow key={trigger.name} trigger={trigger} permissions={data.permissions} />
))}
</EsbList>
</section>
)
}
/**
* Browsing and management actions for the queue behind a destination. A topic has none: its
* messages wait in each trigger's subscription, not on the topic.
*
* @param props - Component props.
* @param props.destination - The destination.
* @param props.permissions - The current user's ESB permissions.
* @returns A browse button when the broker supports browsing, and the permitted queue actions;
* or `null` for a topic.
*/
export function EsbDestinationActions({
destination,
permissions,
}: {
destination: EsbDestination
permissions: EsbPermissions
}) {
const queue = destinationQueue(destination)
if (!queue) return null
return (
<div className="space-y-1">
{queue.capabilities.browse && (
<EsbBrowseButton
label="Browse"
ariaLabel={`Browse ${destination.name}`}
title={`Messages in ${destination.name}`}
source={{ kind: 'destination', name: destination.name }}
queue={queue}
permissions={permissions}
/>
)}
<EsbQueueActions queue={queue} permissions={permissions} />
</div>
)
}
/**
* A titled table of ESB rows, or a sentence when there are none.
*
@@ -110,7 +169,7 @@ export function EsbSection({ data }: EsbSectionProps) {
* @param props.children - The table rows.
* @returns The heading followed by the table or the empty sentence.
*/
function EsbList({
export function EsbList({
title,
columns,
empty,
+30 -7
View File
@@ -15,16 +15,19 @@
*/
/**
* @file EsbTriggerRow — one table row for a process triggered by an ESB destination.
* @file EsbTriggerRow — one table row for a process triggered by an ESB destination, with its
* management actions.
*/
import React from 'react'
import Link from 'next/link'
import type { EsbTrigger, EsbTriggerMode, EsbTriggerState } from '@/types'
import type { EsbPermissions, EsbTrigger, EsbTriggerMode, EsbTriggerState } from '@/types'
import { CHIP_COLOR_CLASSES, type ChipColor } from '@/lib/utils/adornment-utils'
import { cn } from '@/lib/utils/cn'
import { EsbTriggerActions, deadLetterQueue } from './EsbActions'
import { EsbCounters } from './EsbCounters'
import { EsbBrowseButton } from './EsbMessageList'
/** Label and chip color for each trigger state. */
const STATES: Record<EsbTriggerState, { label: string; color: ChipColor }> = {
@@ -38,15 +41,24 @@ const STATES: Record<EsbTriggerState, { label: string; color: ChipColor }> = {
const MODES: Record<EsbTriggerMode, string> = { SINGLE: 'Single', BATCH: 'Batch' }
/**
* Renders a trigger as a row of five cells: the process (linked, with its mode, concurrency
* and attempts), the destination it consumes, its state, its counters, and the number of
* messages in its dead-letter queue (`—` when the broker cannot report it).
* Renders a trigger as a row of six cells: the process (linked, with its mode, concurrency
* and attempts), the destination it consumes, its state, its counters, the number of
* messages in its dead-letter queue (`—` when the broker cannot report it), and its actions:
* pause or resume, restart and replay when permitted, and browsing its dead letters.
*
* @param props - Component props.
* @param props.trigger - The trigger to show.
* @returns A `<tr>` for a table with Process, Destination, State, Counters and Dead letters columns.
* @param props.permissions - The current user's ESB permissions.
* @returns A `<tr>` for a table with Process, Destination, State, Counters, Dead letters and
* Actions columns.
*/
export function EsbTriggerRow({ trigger }: { trigger: EsbTrigger }) {
export function EsbTriggerRow({
trigger,
permissions,
}: {
trigger: EsbTrigger
permissions: EsbPermissions
}) {
const state = STATES[trigger.state] ?? { label: trigger.state, color: 'default' }
const attempts = `${trigger.maxAttempts} ${trigger.maxAttempts === 1 ? 'attempt' : 'attempts'}`
@@ -83,6 +95,17 @@ export function EsbTriggerRow({ trigger }: { trigger: EsbTrigger }) {
<td className="px-2 py-2 tabular-nums text-foreground">
{trigger.deadLetter.messageCount ?? '—'}
</td>
<td className="space-y-1 px-2 py-2">
<EsbTriggerActions trigger={trigger} permissions={permissions} />
<EsbBrowseButton
label="Browse dead letters"
ariaLabel={`Browse dead letters for ${trigger.processLabel}`}
title={`Dead letters for ${trigger.processLabel}`}
source={{ kind: 'deadLetters', triggerName: trigger.name }}
queue={deadLetterQueue(trigger)}
permissions={permissions}
/>
</td>
</tr>
)
}
@@ -0,0 +1,104 @@
/*
* Copyright 2026 QRun.IO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Tests for the process Developer view
import React from 'react'
import { act, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { axe } from 'jest-axe'
import { describe, expect, it } from 'vitest'
import { fulfillOrderEsb } from '@/mocks/fixtures/esb'
import { qInstance } from '@/mocks/fixtures/q-instance'
import type { EsbProcessResponse } from '@/types'
import { ProcessDeveloperView } from './ProcessDeveloperView'
const fulfillOrder = qInstance.processes.fulfillOrder
/**
* Renders the view inside a query client.
*
* @param esb - The process's ESB data.
* @returns The render container.
*/
function renderView(esb: EsbProcessResponse | null): HTMLElement {
const { container } = render(
<QueryClientProvider client={new QueryClient()}>
<ProcessDeveloperView process={fulfillOrder} esb={esb} />
</QueryClientProvider>
)
return container
}
/**
* Reads the value shown for a summary statistic.
*
* @param label - The statistic's label.
* @returns Its displayed value.
*/
function stat(label: string): string | null | undefined {
return screen.getByText(label, { selector: 'dt' }).nextElementSibling?.textContent
}
describe('ProcessDeveloperView', () => {
it('summarizes the process metadata', () => {
renderView(null)
expect(
screen.getByRole('heading', { name: 'Process Developer View: fulfillOrder' })
).toBeInTheDocument()
expect(stat('Label')).toBe('Fulfill Order')
expect(stat('Steps')).toBe('2')
expect(stat('Table')).toBe('order')
expect(stat('Access')).toBe('Allowed')
})
it('shows the full metadata as JSON on demand', async () => {
const user = userEvent.setup()
renderView(null)
expect(screen.queryByText(/"trackingNumber"/)).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Full Process Metadata' }))
expect(screen.getByText(/"trackingNumber"/)).toBeInTheDocument()
})
it('shows the process\'s ESB publications and triggers', () => {
renderView(fulfillOrderEsb)
expect(screen.getByRole('heading', { name: 'Enterprise Service Bus' })).toBeInTheDocument()
const publications = screen.getByRole('table', { name: 'Publications' })
expect(within(publications).getByText('fulfillmentResults')).toBeInTheDocument()
expect(publications).toHaveTextContent('COMPLETED, FAILED')
const triggers = screen.getByRole('table', { name: 'Triggers' })
expect(within(triggers).getAllByRole('row')).toHaveLength(2)
expect(triggers).toHaveTextContent('orderFulfillment')
})
it('omits the ESB section when the process has none', () => {
renderView(null)
expect(
screen.queryByRole('heading', { name: 'Enterprise Service Bus' })
).not.toBeInTheDocument()
})
it('has no accessibility violations', async () => {
const container = renderView(fulfillOrderEsb)
let results: Awaited<ReturnType<typeof axe>> | undefined
await act(async () => {
results = await axe(container)
})
expect(results).toHaveNoViolations()
})
})
+105
View File
@@ -0,0 +1,105 @@
/*
* Copyright 2026 QRun.IO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file ProcessDeveloperView — a process's Developer view: a metadata summary, the process's ESB
* publications and triggers, and its full metadata as JSON.
*/
'use client'
import React, { useState } from 'react'
import { ChevronDown, ChevronUp, Code } from 'lucide-react'
import type { EsbProcessResponse, QProcessMetaData } from '@/types'
import { EsbSection } from './EsbSection'
/** Props for {@link ProcessDeveloperView}. */
interface ProcessDeveloperViewProps {
/** The process's metadata. */
process: QProcessMetaData
/** The process's ESB data, or `null` when it has none or the user may not see it. */
esb: EsbProcessResponse | null
}
/**
* Renders a process's Developer view.
*
* @param props - See {@link ProcessDeveloperViewProps}.
* @returns A heading, a summary (label, step count, table, access), the `<EsbSection>` when
* `esb` is not `null`, and a collapsible block with the full metadata as JSON.
*/
export function ProcessDeveloperView({ process, esb }: ProcessDeveloperViewProps) {
const [jsonOpen, setJsonOpen] = useState(false)
const stats: Array<[string, string]> = [
['Label', process.label],
['Steps', String((process.frontendSteps ?? []).length)],
['Table', process.tableName || '—'],
['Access', process.hasPermission === false ? 'Denied' : 'Allowed'],
]
return (
<div className="space-y-6" data-qqq-id={`process-dev-${process.name}`}>
<div className="flex items-center gap-3">
<Code className="h-6 w-6 text-muted-foreground" aria-hidden="true" />
<h2 className="text-2xl font-semibold text-foreground">
Process Developer View: <span className="font-mono text-primary">{process.name}</span>
</h2>
</div>
<div className="space-y-4">
<dl className="grid grid-cols-2 gap-4 sm:grid-cols-4">
{stats.map(([label, value]) => (
<div key={label} className="rounded-xl border border-border bg-card p-4">
<dt className="text-xs font-medium text-muted-foreground">{label}</dt>
<dd className="mt-1 text-lg font-semibold text-foreground">{value}</dd>
</div>
))}
</dl>
<EsbSection data={esb} />
<div className="overflow-hidden rounded-xl border border-border">
<button
type="button"
onClick={() => setJsonOpen((open) => !open)}
className="flex w-full items-center justify-between bg-muted px-4 py-3 text-sm font-medium text-foreground hover:bg-accent focus:outline-none focus:ring-2 focus:ring-inset focus:ring-ring"
aria-expanded={jsonOpen}
data-qqq-id="button-json-block-toggle"
>
<span className="flex items-center gap-2">
<Code className="h-4 w-4" aria-hidden="true" />
Full Process Metadata
</span>
{jsonOpen ? (
<ChevronUp className="h-4 w-4" aria-hidden="true" />
) : (
<ChevronDown className="h-4 w-4" aria-hidden="true" />
)}
</button>
{jsonOpen && (
<pre
className="overflow-x-auto bg-gray-900 p-4 text-xs text-green-300"
data-qqq-id="json-output"
>
{JSON.stringify(process, null, 2)}
</pre>
)}
</div>
</div>
</div>
)
}
@@ -0,0 +1,135 @@
/*
* Copyright 2026 QRun.IO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Tests for the ESB app's overview widget
import React from 'react'
import { act, render, screen, within } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { axe } from 'jest-axe'
import { http, HttpResponse } from 'msw'
import { describe, expect, it } from 'vitest'
import type { QWidgetMetaData } from '@/types'
import { esbOverview } from '@/mocks/fixtures/esb'
import { server } from '@/mocks/node'
import { EsbOverviewWidget } from './EsbOverviewWidget'
import { WidgetRenderer } from './WidgetRenderer'
const widgetMetaData = { name: 'esbOverview', label: 'ESB', type: 'ESB_OVERVIEW' } as QWidgetMetaData
/**
* Renders an element inside a fresh query client.
*
* @param ui - The element to render.
* @returns The render container.
*/
function renderWithClient(ui: React.ReactElement): HTMLElement {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
return render(<QueryClientProvider client={client}>{ui}</QueryClientProvider>).container
}
/**
* Returns the body rows of the table with the given accessible name.
*
* @param name - The table's accessible name.
* @returns Its rows, excluding the header row.
*/
function bodyRows(name: string): HTMLElement[] {
return within(screen.getByRole('table', { name })).getAllByRole('row').slice(1)
}
describe('EsbOverviewWidget', () => {
it('lists providers with their connection and management state', async () => {
renderWithClient(<EsbOverviewWidget widgetMetaData={widgetMetaData} />)
await screen.findByRole('table', { name: 'Providers' })
const [artemis, rabbit] = bodyRows('Providers')
expect(artemis).toHaveTextContent('artemis')
expect(artemis).toHaveTextContent('ActiveMQ Artemis')
expect(artemis).toHaveTextContent('Connected')
expect(artemis).toHaveTextContent('Enabled')
expect(rabbit).toHaveTextContent('RabbitMQ')
expect(rabbit).toHaveTextContent('Disconnected')
expect(rabbit).toHaveTextContent('Not configured')
})
it('lists destinations with their publishers and queue depth', async () => {
renderWithClient(<EsbOverviewWidget widgetMetaData={widgetMetaData} />)
await screen.findByRole('table', { name: 'Destinations' })
const [events, fulfillment, results] = bodyRows('Destinations')
expect(bodyRows('Destinations')).toHaveLength(3)
expect(events).toHaveTextContent('orderEvents')
expect(events).toHaveTextContent('Topic')
expect(within(events).getByRole('link', { name: 'order' })).toHaveAttribute('href', '/app/order')
expect(events).toHaveTextContent('INSERT, UPDATE, DELETE')
expect(fulfillment).toHaveTextContent('Queue')
expect(within(fulfillment).getAllByRole('cell')[3]).toHaveTextContent(/^7$/)
expect(within(results).getByRole('link', { name: 'fulfillOrder' })).toHaveAttribute(
'href',
'/app/fulfillOrder'
)
})
it('lists every trigger with its management actions', async () => {
renderWithClient(<EsbOverviewWidget widgetMetaData={widgetMetaData} />)
await screen.findByRole('table', { name: 'Triggers' })
const [cancel, fulfill] = bodyRows('Triggers')
expect(bodyRows('Triggers')).toHaveLength(2)
expect(within(cancel).getByRole('link', { name: 'Cancel Order' })).toBeInTheDocument()
expect(within(cancel).getByRole('button', { name: 'Resume Cancel Order' })).toBeInTheDocument()
expect(within(fulfill).getByRole('button', { name: 'Pause Fulfill Order' })).toBeInTheDocument()
const fulfillment = bodyRows('Destinations')[1]
expect(
within(fulfillment).getByRole('button', { name: 'Purge orderFulfillment' })
).toBeInTheDocument()
})
it('hides management actions without permission', async () => {
server.use(
http.get('/qqq/v1/esb/overview', () =>
HttpResponse.json({ ...esbOverview, permissions: { canOperate: false, canDelete: false } })
)
)
renderWithClient(<EsbOverviewWidget widgetMetaData={widgetMetaData} />)
await screen.findByRole('table', { name: 'Triggers' })
expect(screen.queryByRole('button', { name: /^(Pause|Resume|Restart|Purge)/ })).not.toBeInTheDocument()
})
it('says so when the ESB status is not available', async () => {
server.use(
http.get('/qqq/v1/esb/overview', () =>
HttpResponse.json({ error: 'Permission denied.' }, { status: 403 })
)
)
renderWithClient(<EsbOverviewWidget widgetMetaData={widgetMetaData} />)
expect(await screen.findByText('ESB status is not available.')).toBeInTheDocument()
})
it('is rendered for the ESB_OVERVIEW widget type', async () => {
renderWithClient(<WidgetRenderer widgetMetaData={widgetMetaData} data={{ type: 'ESB_OVERVIEW' }} />)
expect(await screen.findByRole('table', { name: 'Destinations' })).toBeInTheDocument()
})
it('has no accessibility violations', async () => {
const container = renderWithClient(<EsbOverviewWidget widgetMetaData={widgetMetaData} />)
await screen.findByRole('table', { name: 'Triggers' })
let results: Awaited<ReturnType<typeof axe>> | undefined
await act(async () => {
results = await axe(container)
})
expect(results).toHaveNoViolations()
})
})
@@ -0,0 +1,199 @@
/*
* Copyright 2026 QRun.IO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file EsbOverviewWidget — the ESB app's `ESB_OVERVIEW` widget: every provider, destination,
* publisher and trigger from `GET /esb/overview`, with per-node counters and management actions.
*/
'use client'
import React from 'react'
import Link from 'next/link'
import { useQuery } from '@tanstack/react-query'
import type { EsbOverviewDestination, EsbPermissions, EsbProviderType, QWidgetMetaData } from '@/types'
import { getEsbOverview } from '@/lib/api/esb'
import { HANDLES_OWN_ERRORS, queryKeys } from '@/lib/query-client'
import { CHIP_COLOR_CLASSES } from '@/lib/utils/adornment-utils'
import { cn } from '@/lib/utils/cn'
import { EsbCounters } from '@/components/esb/EsbCounters'
import {
DESTINATION_TYPES,
EsbDestinationActions,
EsbList,
TRIGGER_COLUMNS,
} from '@/components/esb/EsbSection'
import { EsbTriggerRow } from '@/components/esb/EsbTriggerRow'
/** Label for each provider type. */
const PROVIDER_TYPES: Record<EsbProviderType, string> = {
ACTIVEMQ_ARTEMIS: 'ActiveMQ Artemis',
RABBITMQ: 'RabbitMQ',
}
/**
* Renders the ESB overview. The widget's own payload carries nothing it needs: the data comes
* from the permission-checked overview endpoint, so management actions refresh it.
*
* @param props - Component props.
* @param props.widgetMetaData - The widget's metadata, for `data-qqq-id` scoping.
* @returns Providers, Destinations and Triggers tables; or a loading, error or unavailable state.
*/
export function EsbOverviewWidget({ widgetMetaData }: { widgetMetaData: QWidgetMetaData }) {
const { data, isLoading, error } = useQuery({
queryKey: queryKeys.esbOverview(),
queryFn: getEsbOverview,
meta: HANDLES_OWN_ERRORS,
})
if (isLoading) {
return (
<p className="text-sm text-muted-foreground" role="status">
Loading ESB status…
</p>
)
}
if (error) {
return (
<p className="text-sm text-destructive" role="alert">
Failed to load ESB status: {error instanceof Error ? error.message : 'Unknown error'}
</p>
)
}
if (!data) return <p className="text-sm text-muted-foreground">ESB status is not available.</p>
const triggers = data.destinations.flatMap((destination) => destination.triggers)
return (
<div className="space-y-6" data-qqq-id={`widget-esb-overview-${widgetMetaData.name}`}>
<EsbList
title="Providers"
columns={['Provider', 'Type', 'Connection', 'Management API']}
empty="No ESB providers are configured."
>
{data.providers.map((provider) => (
<tr
key={provider.name}
className="border-b border-border/50 align-top last:border-0"
data-qqq-id={`esb-provider-${provider.name}`}
>
<td className="px-2 py-2 font-mono text-xs text-foreground">{provider.name}</td>
<td className="px-2 py-2 text-foreground">
{PROVIDER_TYPES[provider.type] ?? provider.type}
</td>
<td className="px-2 py-2">
<span
className={cn(
'inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium',
CHIP_COLOR_CLASSES[provider.connected ? 'success' : 'error']
)}
>
{provider.connected ? 'Connected' : 'Disconnected'}
</span>
</td>
<td className="px-2 py-2 text-foreground">
{provider.managementEnabled ? 'Enabled' : 'Not configured'}
</td>
</tr>
))}
</EsbList>
<EsbList
title="Destinations"
columns={['Destination', 'Type', 'Publishers', 'Queue depth', 'Counters', 'Actions']}
empty="No destinations are configured."
>
{data.destinations.map((destination) => (
<DestinationRow
key={destination.name}
destination={destination}
permissions={data.permissions}
/>
))}
</EsbList>
<EsbList title="Triggers" columns={TRIGGER_COLUMNS} empty="No triggers on processes you can access.">
{triggers.map((trigger) => (
<EsbTriggerRow key={trigger.name} trigger={trigger} permissions={data.permissions} />
))}
</EsbList>
</div>
)
}
/**
* One destination with its provider, the tables and processes publishing to it, queue depth,
* counters and actions.
*
* @param props - Component props.
* @param props.destination - The destination.
* @param props.permissions - The current user's ESB permissions.
* @returns The row.
*/
function DestinationRow({
destination,
permissions,
}: {
destination: EsbOverviewDestination
permissions: EsbPermissions
}) {
return (
<tr
className="border-b border-border/50 align-top last:border-0"
data-qqq-id={`esb-destination-${destination.name}`}
>
<td className="px-2 py-2">
<p className="font-mono text-xs text-foreground">{destination.name}</p>
<p className="text-xs text-muted-foreground">on {destination.provider}</p>
</td>
<td className="px-2 py-2 text-foreground">
{DESTINATION_TYPES[destination.type] ?? destination.type}
</td>
<td className="px-2 py-2">
{destination.publishers.length === 0 ? (
<span className="text-muted-foreground">—</span>
) : (
<ul className="space-y-1">
{destination.publishers.map((publisher) => (
<li key={`${publisher.kind}-${publisher.name}`} className="text-foreground">
<span className="text-xs text-muted-foreground">
{publisher.kind === 'TABLE' ? 'Table' : 'Process'}{' '}
</span>
<Link
href={`/app/${encodeURIComponent(publisher.name)}`}
className="font-medium text-primary underline-offset-2 hover:underline focus:outline-none focus:ring-2 focus:ring-ring"
>
{publisher.name}
</Link>
<span className="text-xs text-muted-foreground">: {publisher.events.join(', ')}</span>
</li>
))}
</ul>
)}
</td>
<td className="px-2 py-2 tabular-nums text-foreground">
{destination.queueInfo ? destination.queueInfo.messageCount : '—'}
</td>
<td className="px-2 py-2">
<EsbCounters counters={destination.counters} kind="publish" />
</td>
<td className="px-2 py-2">
<EsbDestinationActions destination={destination} permissions={permissions} />
</td>
</tr>
)
}
+4 -1
View File
@@ -25,7 +25,7 @@
* pieChart, quickSightChart, statistics, stackedBarChart, stepper, table, usaMap,
* process, parentWidget, composite, childRecordList, customComponent, cronUI,
* dynamicForm, dataBagViewer, pivotTableSetup, filterAndColumnsSetup, rowBuilder,
* scriptViewer — plus the demo shapes (recordGrid, quickLinks, processSummary,
* scriptViewer, and the ESB module's ESB_OVERVIEW — plus the demo shapes (recordGrid, quickLinks, processSummary,
* block, parent) used by the mocked development API.
*
* Chart components are loaded lazily so Recharts is split out of the initial bundle.
@@ -72,6 +72,7 @@ import { FilterAndColumnsSetupWidget } from './FilterAndColumnsSetupWidget'
import { PivotTableSetupWidget } from './PivotTableSetupWidget'
import { RowBuilderWidget } from './RowBuilderWidget'
import { ScriptViewerWidget } from './ScriptViewerWidget'
import { EsbOverviewWidget } from './EsbOverviewWidget'
const QqqChartWidget = lazy(() => import('./QqqChartWidget').then((m) => ({ default: m.QqqChartWidget })))
const BarChartWidget = lazy(() => import('./BarChartWidget').then((m) => ({ default: m.BarChartWidget })))
@@ -204,6 +205,8 @@ export function WidgetRenderer({ widgetMetaData, data, recordContext, actionCall
return <RowBuilderWidget {...common} data={data} />
case 'scriptViewer':
return <ScriptViewerWidget {...common} data={data} />
case 'ESB_OVERVIEW':
return <EsbOverviewWidget widgetMetaData={widgetMetaData} />
case 'recordGrid':
return <RecordGridWidget data={data as unknown as RecordGridWidgetPayload} widgetName={name} />
case 'quickLinks':
+166 -3
View File
@@ -17,11 +17,27 @@
// Tests for the ESB API client
import { http, HttpResponse } from 'msw'
import { describe, expect, it } from 'vitest'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { orderEsb } from '@/mocks/fixtures/esb'
import {
esbOverview,
fulfillOrderDeadLetters,
fulfillOrderEsb,
orderEsb,
orderFulfillmentMessages,
} from '@/mocks/fixtures/esb'
import { server } from '@/mocks/node'
import { getEsbForTable } from './esb'
import { processInit } from './processes'
import {
getEsbDeadLetters,
getEsbForProcess,
getEsbForTable,
getEsbMessages,
getEsbOverview,
runEsbAction,
} from './esb'
vi.mock('./processes', () => ({ processInit: vi.fn() }))
describe('getEsbForTable', () => {
it('returns the table ESB section from GET /qqq/v1/esb/table/{table}', async () => {
@@ -88,3 +104,150 @@ describe('getEsbForTable', () => {
await expect(getEsbForTable('order')).resolves.toBeNull()
})
})
describe('getEsbForProcess', () => {
it('returns the process ESB section from GET /qqq/v1/esb/process/{process}', async () => {
let path = ''
server.use(
http.get('/qqq/v1/esb/process/:process', ({ request }) => {
path = new URL(request.url).pathname
return HttpResponse.json(fulfillOrderEsb)
})
)
await expect(getEsbForProcess('fulfill order')).resolves.toEqual(fulfillOrderEsb)
expect(path).toBe('/qqq/v1/esb/process/fulfill%20order')
})
it.each([403, 404])('returns null on %i', async (status) => {
server.use(
http.get('/qqq/v1/esb/process/fulfillOrder', () =>
HttpResponse.json({ error: 'Permission denied.' }, { status })
)
)
await expect(getEsbForProcess('fulfillOrder')).resolves.toBeNull()
})
it('returns null for a body without publications and triggers', async () => {
server.use(
http.get('/qqq/v1/esb/process/fulfillOrder', () =>
HttpResponse.html('<!doctype html><html><body>SPA</body></html>')
)
)
await expect(getEsbForProcess('fulfillOrder')).resolves.toBeNull()
})
})
describe('getEsbOverview', () => {
it('returns the overview from GET /qqq/v1/esb/overview', async () => {
await expect(getEsbOverview()).resolves.toEqual(esbOverview)
})
it.each([403, 404])('returns null on %i', async (status) => {
server.use(
http.get('/qqq/v1/esb/overview', () =>
HttpResponse.json({ error: 'Permission denied.' }, { status })
)
)
await expect(getEsbOverview()).resolves.toBeNull()
})
it('returns null for a body without providers and destinations', async () => {
server.use(http.get('/qqq/v1/esb/overview', () => HttpResponse.json({ error: 'unexpected' })))
await expect(getEsbOverview()).resolves.toBeNull()
})
})
describe('getEsbMessages and getEsbDeadLetters', () => {
it('browse a destination with offset and limit', async () => {
let url = new URL('http://localhost')
server.use(
http.get('/qqq/v1/esb/messages/:destination', ({ request }) => {
url = new URL(request.url)
return HttpResponse.json(orderFulfillmentMessages)
})
)
await expect(getEsbMessages('orderFulfillment', 50, 25)).resolves.toEqual(orderFulfillmentMessages)
expect(url.pathname).toBe('/qqq/v1/esb/messages/orderFulfillment')
expect(url.searchParams.get('offset')).toBe('50')
expect(url.searchParams.get('limit')).toBe('25')
})
it('browse a trigger\'s dead letters, 50 at a time from the start by default', async () => {
let url = new URL('http://localhost')
server.use(
http.get('/qqq/v1/esb/deadLetters/:trigger', ({ request }) => {
url = new URL(request.url)
return HttpResponse.json(fulfillOrderDeadLetters)
})
)
await expect(getEsbDeadLetters('fulfillOrder.orderFulfillment')).resolves.toEqual(
fulfillOrderDeadLetters
)
expect(url.pathname).toBe('/qqq/v1/esb/deadLetters/fulfillOrder.orderFulfillment')
expect(url.searchParams.get('offset')).toBe('0')
expect(url.searchParams.get('limit')).toBe('50')
})
it('rejects a body that is not a message page', async () => {
server.use(http.get('/qqq/v1/esb/messages/orderFulfillment', () => HttpResponse.json({})))
await expect(getEsbMessages('orderFulfillment')).rejects.toThrow('Invalid ESB message page')
})
it('rethrows request failures', async () => {
server.use(
http.get('/qqq/v1/esb/deadLetters/fulfillOrder.orderFulfillment', () =>
HttpResponse.json({ error: 'Permission denied.' }, { status: 403 })
)
)
await expect(getEsbDeadLetters('fulfillOrder.orderFulfillment')).rejects.toThrow()
})
})
describe('runEsbAction', () => {
beforeEach(() => {
vi.mocked(processInit).mockReset()
})
it('runs the operate process with the values and returns its count and message', async () => {
vi.mocked(processInit).mockResolvedValue({
type: 'COMPLETE',
processUUID: 'uuid',
values: { count: 7, message: 'Purged 7 messages.' },
})
await expect(
runEsbAction('esbPurgeQueue', { providerName: 'artemis', brokerQueueName: 'orderFulfillment' })
).resolves.toEqual({ count: 7, message: 'Purged 7 messages.' })
expect(processInit).toHaveBeenCalledWith('esbPurgeQueue', {
values: { providerName: 'artemis', brokerQueueName: 'orderFulfillment' },
})
})
it('reads a count sent as text', async () => {
vi.mocked(processInit).mockResolvedValue({
type: 'COMPLETE',
processUUID: 'uuid',
values: { count: '2', message: 'Deleted 2 messages.' },
})
await expect(runEsbAction('esbDeleteMessages', {})).resolves.toEqual({
count: 2,
message: 'Deleted 2 messages.',
})
})
it('rejects with the user-facing error when the process fails', async () => {
vi.mocked(processInit).mockResolvedValue({
type: 'ERROR',
error: 'Error message: boom',
userFacingError: 'The broker refused the purge.',
})
await expect(runEsbAction('esbPurgeQueue', {})).rejects.toThrow('The broker refused the purge.')
})
it('says the action is still running when it continues as a job', async () => {
vi.mocked(processInit).mockResolvedValue({ type: 'JOB_STARTED', processUUID: 'uuid', jobUUID: 'job' })
await expect(runEsbAction('esbRestartTrigger', {})).resolves.toEqual({
count: null,
message: 'The action is still running.',
})
})
})
+140 -9
View File
@@ -18,9 +18,25 @@
* @file ESB API — permission-checked `/qqq/v1/esb` endpoints served by the `qqq-esb` module.
*/
import type { EsbTableResponse } from '@/types'
import type {
EsbMessagePage,
EsbOverviewResponse,
EsbProcessResponse,
EsbTableResponse,
} from '@/types'
import { getErrorStatusCode } from '@/lib/utils/error-utils'
import apiClient from './client'
import { processInit } from './processes'
/** Messages per page when browsing, the backend's default. */
export const ESB_PAGE_SIZE = 50
/** Output of an ESB operate process (`esbPauseTrigger`, `esbPurgeQueue`, ...). */
export interface EsbActionResult {
/** Messages or consumers affected, or `null` when the process did not report it. */
count: number | null
message: string
}
/**
* Loads a table's ESB publications and subscribing triggers from `GET /esb/table/{table}`.
@@ -35,25 +51,140 @@ import apiClient from './client'
* @throws The request error for any other failure.
*/
export async function getEsbForTable(tableName: string): Promise<EsbTableResponse | null> {
let data: unknown
const data = await getOrNull(`/esb/table/${encodeURIComponent(tableName)}`)
return hasArrays<EsbTableResponse>(data, 'publications', 'subscribers') ? data : null
}
/**
* Loads a process's ESB publications and the triggers that start it from
* `GET /esb/process/{process}`. As with {@link getEsbForTable}, 403, 404 and a non-ESB body
* all mean there is nothing to show.
*
* @param processName - Backend process name.
* @returns The process's ESB section, or `null` on 403, on 404, or when a 2xx body is not an ESB process object.
* @throws The request error for any other failure.
*/
export async function getEsbForProcess(processName: string): Promise<EsbProcessResponse | null> {
const data = await getOrNull(`/esb/process/${encodeURIComponent(processName)}`)
return hasArrays<EsbProcessResponse>(data, 'publications', 'triggers') ? data : null
}
/**
* Loads every provider, destination, publisher and trigger from `GET /esb/overview`.
*
* @returns The overview, or `null` on 403, on 404, or when a 2xx body is not an ESB overview.
* @throws The request error for any other failure.
*/
export async function getEsbOverview(): Promise<EsbOverviewResponse | null> {
const data = await getOrNull('/esb/overview')
return hasArrays<EsbOverviewResponse>(data, 'providers', 'destinations') ? data : null
}
/**
* Browses one page of the messages waiting on a destination's queue via
* `GET /esb/messages/{destination}`.
*
* @param destinationName - QQQ destination name.
* @param offset - Messages to skip.
* @param limit - Messages to return.
* @returns The page of messages.
* @throws The request error, or an error when the body is not a message page.
*/
export async function getEsbMessages(
destinationName: string,
offset = 0,
limit = ESB_PAGE_SIZE
): Promise<EsbMessagePage> {
return getMessagePage(`/esb/messages/${encodeURIComponent(destinationName)}`, offset, limit)
}
/**
* Browses one page of a trigger's dead letters via `GET /esb/deadLetters/{trigger}`.
*
* @param triggerName - Trigger name (`<processName>.<destinationName>`).
* @param offset - Messages to skip.
* @param limit - Messages to return.
* @returns The page of dead letters.
* @throws The request error, or an error when the body is not a message page.
*/
export async function getEsbDeadLetters(
triggerName: string,
offset = 0,
limit = ESB_PAGE_SIZE
): Promise<EsbMessagePage> {
return getMessagePage(`/esb/deadLetters/${encodeURIComponent(triggerName)}`, offset, limit)
}
/**
* Runs an ESB operate process through the standard process API and reads its output values.
*
* @param processName - The operate process, e.g. `esbPurgeQueue`.
* @param values - Its input values, e.g. `providerName` and `brokerQueueName`.
* @returns The process's `count` and `message`; a generic message while it continues as a job.
* @throws An error with the process's user-facing message when it fails or is refused.
*/
export async function runEsbAction(
processName: string,
values: Record<string, string | boolean>
): Promise<EsbActionResult> {
const response = await processInit(processName, { values })
if (response.type === 'ERROR') {
throw new Error(response.userFacingError ?? response.error)
}
if (response.type !== 'COMPLETE') {
return { count: null, message: 'The action is still running.' }
}
const count = Number(response.values.count)
const message = response.values.message
return {
count: response.values.count == null || Number.isNaN(count) ? null : count,
message: typeof message === 'string' && message ? message : 'Done.',
}
}
/**
* GETs an ESB resource, treating 403 and 404 as "nothing to show".
*
* @param path - Path under the API base URL.
* @returns The parsed body, or `null` on 403 or 404.
* @throws The request error for any other failure.
*/
async function getOrNull(path: string): Promise<unknown> {
try {
data = await apiClient.get<unknown>(`/esb/table/${encodeURIComponent(tableName)}`)
return await apiClient.get<unknown>(path)
} catch (error) {
const status = getErrorStatusCode(error)
if (status === 403 || status === 404) return null
throw error
}
return isEsbTableResponse(data) ? data : null
}
/**
* Whether a response body has the shape of an ESB table response.
* GETs one page of browsed messages.
*
* @param path - Path under the API base URL.
* @param offset - Messages to skip.
* @param limit - Messages to return.
* @returns The page.
* @throws The request error, or an error when the body is not a message page.
*/
async function getMessagePage(path: string, offset: number, limit: number): Promise<EsbMessagePage> {
const data = await apiClient.get<unknown>(path, { params: { offset, limit } })
if (!hasArrays<EsbMessagePage>(data, 'messages')) {
throw new Error('Invalid ESB message page')
}
return data
}
/**
* Whether a response body is an object whose named properties are all arrays.
*
* @param data - The parsed response body.
* @returns True for an object with `publications` and `subscribers` arrays.
* @param keys - Properties that must be arrays.
* @returns True when `data` is a non-array object with an array at every key.
*/
function isEsbTableResponse(data: unknown): data is EsbTableResponse {
function hasArrays<T extends object>(data: unknown, ...keys: Array<keyof T & string>): data is T {
if (!data || typeof data !== 'object' || Array.isArray(data)) return false
const body = data as Partial<Record<keyof EsbTableResponse, unknown>>
return Array.isArray(body.publications) && Array.isArray(body.subscribers)
const body = data as Record<string, unknown>
return keys.every((key) => Array.isArray(body[key]))
}
+23
View File
@@ -350,6 +350,29 @@ export const queryKeys = {
* @returns The table ESB query key tuple.
*/
esbTable: (tableName: string) => [...queryKeys.esb(), 'table', tableName] as const,
/**
* Key for a process's ESB publications and triggers.
*
* @param processName - Backend process name.
* @returns The process ESB query key tuple.
*/
esbProcess: (processName: string) => [...queryKeys.esb(), 'process', processName] as const,
/**
* Key for the ESB overview of every provider, destination and trigger.
*
* @returns The overview query key tuple.
*/
esbOverview: () => [...queryKeys.esb(), 'overview'] as const,
/**
* Key for one page of messages browsed from a destination's queue or a trigger's dead letters.
*
* @param kind - `destination` or `deadLetters`.
* @param name - The destination or trigger name.
* @param offset - Messages skipped before the page.
* @returns The message page query key tuple.
*/
esbMessages: (kind: 'destination' | 'deadLetters', name: string, offset: number) =>
[...queryKeys.esb(), 'messages', kind, name, offset] as const,
// Search
/**
+148 -46
View File
@@ -15,11 +15,22 @@
*/
/**
* @file ESB fixture data — `GET /qqq/v1/esb/table/order` for the demo `order` table: a topic
* without broker management data, a managed queue, and one trigger on each.
* @file ESB fixture data for the demo `order` table: a topic without broker management data,
* a managed queue, one trigger on each, and the `fulfillOrder` process that the queue triggers.
* Covers `GET /qqq/v1/esb/table/order`, `/process/fulfillOrder`, `/overview`,
* `/messages/orderFulfillment` and `/deadLetters/fulfillOrder.orderFulfillment`.
*/
import type { EsbCapabilities, EsbCounter, EsbDestination, EsbTableResponse } from '@/types'
import type {
EsbCapabilities,
EsbCounter,
EsbDestination,
EsbMessagePage,
EsbOverviewResponse,
EsbProcessResponse,
EsbTableResponse,
EsbTrigger,
} from '@/types'
/**
* Builds a counter snapshot with every count at zero.
@@ -74,54 +85,145 @@ const orderFulfillment: EsbDestination = {
capabilities: artemisCapabilities,
}
const fulfillOrderTrigger: EsbTrigger = {
name: 'fulfillOrder.orderFulfillment',
processName: 'fulfillOrder',
processLabel: 'Fulfill Order',
destination: orderFulfillment,
mode: 'SINGLE',
concurrency: 2,
maxAttempts: 3,
state: 'RUNNING',
counters: counter({
consumed: 33,
succeeded: 30,
failed: 3,
retried: 4,
deadLettered: 1,
inFlight: 1,
lastActivity: '2026-09-25T11:58:31Z',
avgMs: 120,
maxMs: 950,
lastError: 'Warehouse API timed out',
}),
deadLetter: { brokerName: 'orderFulfillment.dlq', messageCount: 1 },
}
const cancelOrderTrigger: EsbTrigger = {
name: 'cancelOrder.orderEvents',
processName: 'cancelOrder',
processLabel: 'Cancel Order',
destination: orderEvents,
mode: 'BATCH',
concurrency: 1,
maxAttempts: 5,
state: 'PAUSED',
counters: counter({
consumed: 12,
succeeded: 12,
lastActivity: '2026-09-25T10:15:00Z',
avgMs: 45,
maxMs: 80,
}),
deadLetter: { brokerName: 'orderEvents.cancelOrder.orderEvents.dlq', messageCount: null },
}
const fulfillmentResults: EsbDestination = {
name: 'fulfillmentResults',
type: 'TOPIC',
provider: 'artemis',
brokerName: 'fulfillmentResults',
counters: counter({ published: 30, lastActivity: '2026-09-25T11:58:32Z' }),
queueInfo: null,
capabilities: artemisCapabilities,
}
export const orderEsb: EsbTableResponse = {
table: 'order',
publications: [
{ destination: orderEvents, events: ['INSERT', 'UPDATE', 'DELETE'] },
{ destination: orderFulfillment, events: ['INSERT'] },
],
subscribers: [
{
name: 'fulfillOrder.orderFulfillment',
processName: 'fulfillOrder',
processLabel: 'Fulfill Order',
destination: orderFulfillment,
mode: 'SINGLE',
concurrency: 2,
maxAttempts: 3,
state: 'RUNNING',
counters: counter({
consumed: 33,
succeeded: 30,
failed: 3,
retried: 4,
deadLettered: 1,
inFlight: 1,
lastActivity: '2026-09-25T11:58:31Z',
avgMs: 120,
maxMs: 950,
lastError: 'Warehouse API timed out',
}),
deadLetter: { brokerName: 'orderFulfillment.dlq', messageCount: 1 },
},
{
name: 'cancelOrder.orderEvents',
processName: 'cancelOrder',
processLabel: 'Cancel Order',
destination: orderEvents,
mode: 'BATCH',
concurrency: 1,
maxAttempts: 5,
state: 'PAUSED',
counters: counter({
consumed: 12,
succeeded: 12,
lastActivity: '2026-09-25T10:15:00Z',
avgMs: 45,
maxMs: 80,
}),
deadLetter: { brokerName: 'orderEvents.cancelOrder.orderEvents.dlq', messageCount: null },
},
],
subscribers: [fulfillOrderTrigger, cancelOrderTrigger],
permissions: { canOperate: false, canDelete: false },
}
export const fulfillOrderEsb: EsbProcessResponse = {
process: 'fulfillOrder',
publications: [{ destination: fulfillmentResults, events: ['COMPLETED', 'FAILED'] }],
triggers: [fulfillOrderTrigger],
permissions: { canOperate: false, canDelete: false },
}
export const esbOverview: EsbOverviewResponse = {
providers: [
{ name: 'artemis', type: 'ACTIVEMQ_ARTEMIS', connected: true, managementEnabled: true },
{ name: 'rabbit', type: 'RABBITMQ', connected: false, managementEnabled: false },
],
destinations: [
{
...orderEvents,
publishers: [{ kind: 'TABLE', name: 'order', events: ['INSERT', 'UPDATE', 'DELETE'] }],
triggers: [cancelOrderTrigger],
},
{
...orderFulfillment,
publishers: [{ kind: 'TABLE', name: 'order', events: ['INSERT'] }],
triggers: [fulfillOrderTrigger],
},
{
...fulfillmentResults,
publishers: [{ kind: 'PROCESS', name: 'fulfillOrder', events: ['COMPLETED', 'FAILED'] }],
triggers: [],
},
],
permissions: { canOperate: true, canDelete: true },
}
export const orderFulfillmentMessages: EsbMessagePage = {
messages: [
{
messageId: 'ID:msg-1',
timestamp: '2026-09-25T11:58:00Z',
deliveryCount: 0,
event: {
specversion: '1.0',
id: 'evt-1',
source: 'qqq/table/order',
type: 'qqq.table.order.INSERT',
subject: '1001',
},
rawBody: '{"specversion":"1.0","id":"evt-1","type":"qqq.table.order.INSERT","subject":"1001"}',
properties: {},
},
{
messageId: 'ID:msg-2',
timestamp: '2026-09-25T11:58:10Z',
deliveryCount: 1,
event: {
specversion: '1.0',
id: 'evt-2',
source: 'qqq/table/order',
type: 'qqq.table.order.INSERT',
subject: '1002',
},
rawBody: '{"specversion":"1.0","id":"evt-2","type":"qqq.table.order.INSERT","subject":"1002"}',
properties: {},
},
],
hasMore: true,
}
export const fulfillOrderDeadLetters: EsbMessagePage = {
messages: [
{
messageId: 'ID:dlq-1',
timestamp: '2026-09-25T11:40:00Z',
deliveryCount: 3,
event: null,
rawBody: 'not json',
properties: { qqqError: 'unparseable message', qqqFailedTrigger: 'fulfillOrder.orderFulfillment' },
},
],
hasMore: false,
}
+51 -15
View File
@@ -15,12 +15,19 @@
*/
/**
* @file MSW handlers for the ESB endpoints (`GET /qqq/v1/esb/table/:tableName`).
* @file MSW handlers for the ESB endpoints (`GET /qqq/v1/esb/table/:tableName`,
* `/process/:processName`, `/overview`, `/messages/:destination` and `/deadLetters/:trigger`).
*/
import { http, HttpResponse } from 'msw'
import type { EsbTableResponse } from '@/types'
import { orderEsb } from '../fixtures/esb'
import type { EsbMessagePage, EsbProcessResponse, EsbTableResponse } from '@/types'
import {
esbOverview,
fulfillOrderDeadLetters,
fulfillOrderEsb,
orderEsb,
orderFulfillmentMessages,
} from '../fixtures/esb'
const BASE = '/qqq/v1'
@@ -28,17 +35,46 @@ const esbTables: Record<string, EsbTableResponse> = {
order: orderEsb,
}
const esbProcesses: Record<string, EsbProcessResponse> = {
fulfillOrder: fulfillOrderEsb,
}
const esbMessages: Record<string, EsbMessagePage> = {
orderFulfillment: orderFulfillmentMessages,
}
const esbDeadLetters: Record<string, EsbMessagePage> = {
'fulfillOrder.orderFulfillment': fulfillOrderDeadLetters,
}
/**
* Answers with the entry for `name`, or a 404 as the backend does for objects without ESB metadata.
*
* @param entries - Fixture responses by name.
* @param name - The requested name.
* @param kind - What `name` names, for the error message.
* @returns The fixture as JSON, or a 404 response.
*/
function esbResponse<T extends object>(entries: Record<string, T>, name: string, kind: string) {
const data = entries[name]
if (!data) {
return HttpResponse.json({ error: `${kind} '${name}' has no ESB metadata` }, { status: 404 })
}
return HttpResponse.json(data)
}
export const esbHandlers = [
// GET /esb/table/:tableName — 404 for tables without ESB metadata, as the backend answers
http.get(`${BASE}/esb/table/:tableName`, ({ params }) => {
const { tableName } = params as { tableName: string }
const data = esbTables[tableName]
if (!data) {
return HttpResponse.json(
{ error: `Table '${tableName}' has no ESB metadata` },
{ status: 404 }
)
}
return HttpResponse.json(data)
}),
http.get(`${BASE}/esb/table/:tableName`, ({ params }) =>
esbResponse(esbTables, String(params.tableName), 'Table')
),
http.get(`${BASE}/esb/process/:processName`, ({ params }) =>
esbResponse(esbProcesses, String(params.processName), 'Process')
),
http.get(`${BASE}/esb/overview`, () => HttpResponse.json(esbOverview)),
http.get(`${BASE}/esb/messages/:destination`, ({ params }) =>
esbResponse(esbMessages, String(params.destination), 'Destination')
),
http.get(`${BASE}/esb/deadLetters/:trigger`, ({ params }) =>
esbResponse(esbDeadLetters, String(params.trigger), 'Trigger')
),
]