Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions web/app/components-resolve.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { readdirSync, readFileSync, statSync } from 'node:fs'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'

// Vue renders an unknown component tag as nothing, and neither lint nor typecheck notices. This test compares every
// PascalCase tag in the app templates with the components Nuxt registered (.nuxt/components.d.ts, written by
// `nuxt prepare`, which runs on install).
const APP_DIR = join(__dirname)
const BUILT_IN = new Set(['NuxtLayout', 'NuxtPage', 'NuxtLink', 'ClientOnly', 'Teleport', 'Transition', 'TransitionGroup', 'KeepAlive'])

function vueFiles(dir: string): string[] {
return readdirSync(dir).flatMap((name) => {
const path = join(dir, name)
if (statSync(path).isDirectory()) return vueFiles(path)
return path.endsWith('.vue') ? [path] : []
})
}

describe('component tags', () => {
it('only uses components that Nuxt registered', () => {
const declared = readFileSync(join(APP_DIR, '..', '.nuxt', 'components.d.ts'), 'utf8')
const known = new Set([...declared.matchAll(/^export const ([A-Za-z0-9]+)/gm)].map(m => m[1]))
const unknown = vueFiles(APP_DIR).flatMap((file) => {
const template = readFileSync(file, 'utf8').split('<script')[0] ?? ''
return [...new Set([...template.matchAll(/<([A-Z][A-Za-z0-9]+)/g)].map(m => m[1]!))]
.filter(tag => !known.has(tag) && !BUILT_IN.has(tag))
.map(tag => `${file.slice(APP_DIR.length + 1)}: <${tag}>`)
})
expect(unknown, 'unresolved component tags').toEqual([])
})
})
10 changes: 6 additions & 4 deletions web/app/components/AppProblem.vue
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
</template>

<script setup lang="ts">
import { ApiError, NetworkError } from '~/lib/problem'
import { ApiError, NetworkError, toClientError } from '~/lib/problem'

/**
* Shows an error from the API. RFC 9457 problems show their title, detail and field errors; a network failure gets
Expand All @@ -19,14 +19,16 @@ import { ApiError, NetworkError } from '~/lib/problem'
const props = defineProps<{ error?: Error | null }>()
const { t } = useI18n()

const apiError = computed(() => (props.error instanceof ApiError ? props.error : null))
// Errors from useAsyncData arrive wrapped as Nuxt errors (and from the SSR payload as plain data), so rebuild first.
const normalized = computed(() => (props.error ? toClientError(props.error) : null))
const apiError = computed(() => (normalized.value instanceof ApiError ? normalized.value : null))
const title = computed(() => {
if (props.error instanceof NetworkError) return t('common.problem.network')
if (normalized.value instanceof NetworkError) return t('common.problem.network')
if (apiError.value) return `${apiError.value.status} ${apiError.value.problem.title}`
return t('common.problem.unexpected')
})
const detail = computed(() => {
if (props.error instanceof NetworkError) return t('common.problem.networkHint')
if (normalized.value instanceof NetworkError) return t('common.problem.networkHint')
if (apiError.value) return apiError.value.problem.detail ?? ''
return props.error?.message ?? ''
})
Expand Down
7 changes: 4 additions & 3 deletions web/app/components/pools/PoolSpecView.vue
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
<template>
<section :aria-labelledby="headingId" class="rounded-md bg-surface-container-low p-4 shadow-elevation-1">
<h2 :id="headingId" class="mb-4 text-title-large text-on-surface">{{ $t('pools.spec.heading') }}</h2>
<div class="grid gap-6 md:grid-cols-2">
<!-- One section per row: the card is half the page wide, two columns squeezed the values to a letter. -->
<div class="grid gap-6">
<div v-for="section in sections" :key="section.key" data-test="spec-section">
<h3 class="mb-2 text-title-small text-on-surface-variant">{{ $t(`pools.spec.sections.${section.key}`) }}</h3>
<dl class="grid grid-cols-[minmax(0,auto)_minmax(0,1fr)] gap-x-4 gap-y-1 text-body-medium">
<dl class="grid grid-cols-[minmax(6rem,11rem)_minmax(0,1fr)] gap-x-4 gap-y-1 text-body-medium">
<template v-for="row in section.rows" :key="row.key">
<dt class="text-on-surface-variant">{{ $t(`pools.spec.${row.key}`) }}</dt>
<dd class="min-w-0 break-words" :class="{ 'italic text-on-surface-variant': row.value === null }">
<dd class="min-w-0 [overflow-wrap:anywhere]" :class="{ 'italic text-on-surface-variant': row.value === null }">
{{ row.value ?? $t('pools.spec.none') }}
</dd>
</template>
Expand Down
3 changes: 2 additions & 1 deletion web/app/composables/useGrusEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ let retryTimer: ReturnType<typeof setTimeout> | undefined
export function useGrusEvents() {
const feed = useState<FeedState>('grus.events', () => ({ status: 'idle', recent: [] }))

if (import.meta.client) connect(feed)
// Opened after hydration: connecting during setup would change the status text before the server HTML is hydrated.
if (import.meta.client) onNuxtReady(() => connect(feed))

function subscribe(register: () => () => void): () => void {
const off = register()
Expand Down
8 changes: 5 additions & 3 deletions web/app/lib/grus.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { components } from '~/types/grus-api'
import { toClientError } from './problem'
import { toClientError, toTransportError } from './problem'

export type Pool = components['schemas']['Pool']
export type PoolSpec = components['schemas']['PoolSpec']
Expand Down Expand Up @@ -46,15 +46,17 @@ export function bffUrl(path: string, query?: Record<string, string | undefined>)
}

/**
* Browser requester: $fetch against the BFF; every failure is normalised to ApiError or NetworkError.
* Browser requester: $fetch against the BFF. Failures are thrown as Nuxt errors whose data carries the ApiError or
* NetworkError; `toClientError` rebuilds the original from them.
* Area clients in app/lib/api/ build on it the same way createGrusClient does.
*/
export const browserRequest: Requester = async (url, options) => {
try {
return await $fetch(url, { method: options.method, body: options.body as BodyInit | undefined })
}
catch (err) {
throw toClientError(err)
// Raised through createError so Nuxt keeps status and problem on the server render instead of masking them.
throw createError(toTransportError(toClientError(err)))
}
}

Expand Down
39 changes: 38 additions & 1 deletion web/app/lib/problem.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { ApiError, NetworkError, problemFromBody, toClientError } from './problem'
import { ApiError, NetworkError, problemFromBody, toClientError, toTransportError } from './problem'

describe('problemFromBody', () => {
it('keeps the RFC 9457 fields of a problem document', () => {
Expand Down Expand Up @@ -54,3 +54,40 @@ describe('toClientError', () => {
expect(toClientError(known)).toBe(known)
})
})

describe('toTransportError', () => {
it('carries status, title and problem of an ApiError', () => {
const problem = { type: 'about:blank', title: 'Conflict', status: 409, detail: 'Pool is busy' }
expect(toTransportError(new ApiError(problem))).toEqual({
status: 409,
statusText: 'Conflict',
message: 'Pool is busy',
data: { problem },
})
})

it('marks a NetworkError as a bad gateway with network data', () => {
const transported = toTransportError(new NetworkError())
expect(transported.status).toBe(502)
expect(transported.data).toEqual({ network: true })
})
})

describe('toClientError with transported data', () => {
it('rebuilds the ApiError from the data of a wrapped error', () => {
const problem = { type: 'about:blank', title: 'Not Found', status: 404, detail: 'No pool lobby' }
const wrapped = Object.assign(new Error('wrapped'), { data: { problem } })
const err = toClientError(wrapped)
expect(err).toBeInstanceOf(ApiError)
expect((err as ApiError).problem.detail).toBe('No pool lobby')
})

it('rebuilds a NetworkError from network data', () => {
expect(toClientError({ data: { network: true } })).toBeInstanceOf(NetworkError)
})

it('ignores data that is not a transported problem', () => {
const thrown = { data: { problem: 'text' }, response: { status: 500, statusText: 'Server Error', _data: {} } }
expect((toClientError(thrown) as ApiError).status).toBe(500)
})
})
44 changes: 40 additions & 4 deletions web/app/lib/problem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,18 @@ export function problemFromBody(status: number, statusText: string, body: unknow
}

/**
* Normalises whatever a failed $fetch call threw. A thrown error with a response is an API answer; without one the
* request never completed (network down, BFF unreachable).
* Normalises whatever a failed request threw. A thrown error with a response is an API answer; an error that already
* carries the transport data of {@link toTransportError} (for example restored from the SSR payload) is rebuilt from
* it; without either the request never completed (network down, BFF unreachable).
*/
export function toClientError(err: unknown): Error {
export function toClientError(err: unknown): ApiError | NetworkError {
if (err instanceof ApiError || err instanceof NetworkError) return err
if (typeof err === 'object' && err !== null && 'response' in err) {
if (typeof err !== 'object' || err === null) return new NetworkError()
const data = (err as { data?: unknown }).data
if (isTransportData(data)) {
return 'problem' in data ? new ApiError(data.problem) : new NetworkError()
}
if ('response' in err) {
const response = (err as { response?: { status?: unknown, statusText?: unknown, _data?: unknown } }).response
if (response && typeof response.status === 'number') {
return problemFromBody(
Expand All @@ -70,3 +76,33 @@ export function toClientError(err: unknown): Error {
}
return new NetworkError()
}

/** What travels in the `data` of a Nuxt error so the client can rebuild the original ApiError or NetworkError. */
export type TransportData = { problem: ProblemDetails } | { network: true }

/** Input for Nuxt's createError: status and text for the error page, the original error as data. */
export interface TransportError {
status: number
statusText: string
message: string
data: TransportData
}

/**
* Turns a client error into createError input. Nuxt masks every server-side error that was not raised with an HTTP
* status as "500 Internal Server Error" and drops its data, so API problems must travel this way to survive SSR.
*/
export function toTransportError(err: ApiError | NetworkError): TransportError {
if (err instanceof ApiError) {
return { status: err.status, statusText: err.problem.title, message: err.message, data: { problem: err.problem } }
}
return { status: 502, statusText: 'Bad Gateway', message: err.message, data: { network: true } }
}

function isTransportData(value: unknown): value is TransportData {
if (typeof value !== 'object' || value === null) return false
if ('network' in value) return (value as { network: unknown }).network === true
if (!('problem' in value)) return false
const problem = (value as { problem: unknown }).problem
return typeof problem === 'object' && problem !== null && typeof (problem as { status?: unknown }).status === 'number'
}
9 changes: 5 additions & 4 deletions web/app/pages/instances/[id].vue
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,12 @@

<div v-if="instance" class="grid gap-4 lg:grid-cols-2">
<M3Card variant="elevated" :title="$t('instances.detail.details')" class="lg:col-span-2">
<dl class="grid grid-cols-1 gap-x-6 gap-y-2 text-body-medium sm:grid-cols-2 xl:grid-cols-3">
<template v-for="row in fields" :key="row.label">
<dt class="text-on-surface-variant">{{ row.label }}</dt>
<dl class="grid grid-cols-1 gap-x-6 gap-y-3 text-body-medium sm:grid-cols-2 xl:grid-cols-3">
<!-- One group per field, so label and value stay together in every column count. -->
<div v-for="row in fields" :key="row.label">
<dt class="text-label-medium text-on-surface-variant">{{ row.label }}</dt>
<dd class="break-all" :class="row.mono ? 'font-mono text-body-small' : ''">{{ row.value }}</dd>
</template>
</div>
</dl>
<div class="mt-4 flex flex-wrap items-center gap-3">
<StatusChip :state="instance.state" />
Expand Down
2 changes: 1 addition & 1 deletion web/app/pages/pools/[pool].vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<template>
<div>
<div class="mb-2">
<IconButton icon="mdi-arrow-left" :label="$t('pools.back')" to="/pools" />
<M3IconButton icon="mdi-arrow-left" :label="$t('pools.back')" to="/pools" />
</div>

<template v-if="pool">
Expand Down
7 changes: 7 additions & 0 deletions web/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ export default defineNuxtConfig({
devtools: { enabled: false },
telemetry: false,

// Area components keep their own names (PoolTable, not PoolsPoolTable); m3/ keeps its M3 prefix.
components: [
{ path: '~/components/pools', pathPrefix: false },
{ path: '~/components/templates', pathPrefix: false },
'~/components',
],

modules: [
'@nuxt/eslint',
'@nuxtjs/i18n',
Expand Down