Files
shared/media-webui/src/lib/features/ServantWorkspace.svelte
T

184 lines
7.9 KiB
Svelte
Raw Normal View History

<script lang="ts">
import { Database, FileClock, FolderOpen, HardDrive, Server, ShieldAlert } from '@lucide/svelte'
import { onMount } from 'svelte'
import { get } from '$lib/api'
import SectionTitle from '$lib/components/SectionTitle.svelte'
import Card from '$lib/components/ui/card.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import Metric from '$lib/components/ui/metric.svelte'
import EmptyState from '$lib/components/EmptyState.svelte'
type Json = Record<string, unknown>
type FileRow = { rel?: string; name?: string; path?: string; mtime?: number; size?: number; type?: string }
let { panel = 'overview' }: { panel?: string } = $props()
let stats = $state<Json>({})
let mounts = $state<Json>({})
let bandwidth = $state<Json>({})
let files = $state<FileRow[]>([])
let loading = $state(true)
let error = $state('')
let lastUpdated = $state('')
const value = (source: Json, ...keys: string[]) => {
for (const key of keys) if (source[key] !== undefined && source[key] !== null) return String(source[key])
return '0'
}
function formatBytes(input: unknown) {
const bytes = Number(input)
if (!Number.isFinite(bytes) || bytes <= 0) return '0 B'
const units = ['B', 'KB', 'MB', 'GB', 'TB']
const index = Math.min(units.length - 1, Math.floor(Math.log(bytes) / Math.log(1024)))
return `${(bytes / 1024 ** index).toFixed(index === 0 ? 0 : 1)} ${units[index]}`
}
// Each of these is independent data from a different (sometimes filesystem-touching, e.g.
// /api/stats walking every configured mount) backend call - fetched in parallel via
// allSettled (not sequential awaits, and not Promise.all) so a slow or failed one (an
// unreachable network mount, say) can neither hold up the others - /api/mounts is a pure
// settings read and should never wait behind /api/stats's filesystem walk - nor blank them
// out. Whatever succeeds still updates lastUpdated and its own section; only what actually
// failed reports an error.
async function load() {
loading = true
const failures: string[] = []
const [statsResult, mountsResult, filesResult] = await Promise.allSettled([
get<Json>('/api/stats'),
get<Json>('/api/mounts'),
get<Json>('/api/files/recent?limit=24'),
])
if (statsResult.status === 'fulfilled') {
stats = (statsResult.value.stats as Json) || {}
bandwidth = (statsResult.value.bandwidth as Json) || {}
} else {
failures.push(statsResult.reason instanceof Error ? statsResult.reason.message : 'stats unavailable')
}
if (mountsResult.status === 'fulfilled') {
mounts = (mountsResult.value.mappings as Json) || mountsResult.value
} else {
failures.push(mountsResult.reason instanceof Error ? mountsResult.reason.message : 'mounts unavailable')
}
if (filesResult.status === 'fulfilled') {
const rows = filesResult.value.files || filesResult.value.items || filesResult.value.rows
files = Array.isArray(rows) ? (rows as FileRow[]) : []
} else {
files = []
}
error = failures.join(' / ')
lastUpdated = new Date().toLocaleTimeString()
loading = false
}
onMount(() => {
void load()
const timer = window.setInterval(() => void load(), 15_000)
return () => window.clearInterval(timer)
})
</script>
<div class="space-y-4">
{#if error}<div
class="flex items-center gap-2 rounded-md border border-warning/30 bg-warning/10 px-4 py-3 text-sm text-warning"
>
<ShieldAlert class="size-4" />{error}
</div>{/if}
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<Metric
label="Requests"
value={value(stats, 'requests', 'totalRequests')}
detail="Tracked requests"
tone="primary"
/><Metric
label="Active mounts"
value={value(mounts, 'count', 'total', 'active')}
detail="Configured sources"
/><Metric
label="Bytes out"
value={formatBytes(bandwidth.bytesOut || bandwidth.egress)}
detail="Current tracker window"
tone="success"
/><Metric label="Updated" value={lastUpdated || '--'} detail={loading ? 'Refreshing' : 'Live snapshot'} />
</div>
{#if panel === 'files'}
<Card class="space-y-5"
><SectionTitle
title="Recent files"
description="The file feed is available when the browser has the required servant access."
/>{#if files.length === 0}<EmptyState
title="No recent file activity"
message="Recent files are protected by the internal service policy or no files have arrived yet."
/>{:else}<div class="divide-y divide-border">
{#each files as file, index (String(file.rel || file.path || index))}<div
class="flex items-center gap-3 py-3"
>
<div class="rounded-md border border-border bg-bg p-2"><FileClock class="size-4 text-primary" /></div>
<div class="min-w-0 flex-1">
<p class="truncate text-sm font-medium text-fg">{file.name || file.rel || file.path || 'Media file'}</p>
<p class="mt-1 truncate text-xs text-muted-fg">
{file.type || 'media'}{file.mtime ? ` - ${new Date(Number(file.mtime)).toLocaleString()}` : ''}
</p>
</div>
<span class="shrink-0 text-xs text-muted-fg">{formatBytes(file.size)}</span>
</div>{/each}
</div>{/if}</Card
>
{:else}
<div class="grid gap-4 lg:grid-cols-[minmax(0,1.25fr)_minmax(280px,.75fr)]">
<Card class="space-y-5"
><SectionTitle
title="Mount health"
description="Mount mappings are read from MediaConfig and used by the delivery layer."
/>{#if Object.keys(mounts).length === 0}<EmptyState
title="No mount mappings"
message="Connect MediaConfig and reload the mount configuration to see storage sources."
/>{:else}<div class="space-y-3">
{#each Object.entries(mounts) as [name, mapping] (name)}<div
class="flex items-center justify-between gap-3 rounded-md border border-border bg-bg p-3"
>
<div class="flex min-w-0 items-center gap-3">
<HardDrive class="size-4 shrink-0 text-primary" />
<div class="min-w-0">
<p class="truncate text-sm font-medium text-fg">{name}</p>
<p class="truncate text-xs text-muted-fg">
{typeof mapping === 'string' ? mapping : JSON.stringify(mapping)}
</p>
</div>
</div>
<Badge tone="success">Mapped</Badge>
</div>{/each}
</div>{/if}</Card
><Card class="space-y-5"
><SectionTitle title="Delivery signals" description="Useful at a glance when troubleshooting clients." />
<div class="space-y-3">
<div class="flex items-center gap-3 rounded-md border border-border bg-bg p-3">
<Server class="size-4 text-success" />
<div>
<p class="text-sm font-medium text-fg">Service online</p>
<p class="text-xs text-muted-fg">Health probes and file delivery share this process.</p>
</div>
</div>
<div class="flex items-center gap-3 rounded-md border border-border bg-bg p-3">
<Database class="size-4 text-primary" />
<div>
<p class="text-sm font-medium text-fg">Database tracked</p>
<p class="text-xs text-muted-fg">Last refresh: {lastUpdated || '--'}</p>
</div>
</div>
<div class="flex items-center gap-3 rounded-md border border-border bg-bg p-3">
<FolderOpen class="size-4 text-warning" />
<div>
<p class="text-sm font-medium text-fg">Recent entries</p>
<p class="text-xs text-muted-fg">{files.length || 'No'} visible in this session</p>
</div>
</div>
</div></Card
>
</div>
{/if}
</div>