import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useState } from 'react'
import type { BaoClient } from '../../api/bao'
import { listLeases, lookupLease, renewLease, revokeLease, revokePrefix } from '../../api/engines/leases'
import { ListState } from '../shared/ListState'
import { useConfirm } from '../shared/useConfirm'
const when = (iso: string | null) => (iso ? new Date(iso).toLocaleString() : 'never')
function LeaseRow({ client, id, name, onChanged }: { client: BaoClient; id: string; name: string; onChanged: () => void }) {
const confirm = useConfirm()
const [open, setOpen] = useState(false)
const info = useQuery({ queryKey: ['lease', id], queryFn: () => lookupLease(client, id), enabled: open, retry: false })
const renew = useMutation({
mutationFn: () => renewLease(client, id),
onSuccess: () => info.refetch(),
})
const revoke = useMutation({ mutationFn: () => revokeLease(client, id), onSuccess: onChanged })
return (
{name}
{open && info.isPending && Loading…
}
{open && info.error && {info.error.message}
}
{open && info.data && (
- Issued
- {when(info.data.issueTime)}
- Expires
- {when(info.data.expireTime)}
- Remaining
- {info.data.ttl}s
{info.data.lastRenewal && (
<>
- Last renewed
- {when(info.data.lastRenewal)}
>
)}
{info.data.renewable && (
-
)}
)}
{renew.error && {renew.error.message}
}
{revoke.error && {revoke.error.message}
}
)
}
/** Browse and revoke the leases issued by a dynamic engine mount. */
export function LeasesPanel({ client, mount }: { client: BaoClient; mount: string }) {
const qc = useQueryClient()
const confirm = useConfirm()
const [prefix, setPrefix] = useState(mount)
const key = ['leases', mount, prefix]
const entries = useQuery({ queryKey: key, queryFn: () => listLeases(client, prefix), retry: false })
const refresh = () => qc.invalidateQueries({ queryKey: ['leases', mount] })
const revokeAll = useMutation({
mutationFn: () => revokePrefix(client, prefix),
onSuccess: refresh,
})
const crumbs = prefix.slice(mount.length).split('/').filter(Boolean)
const atRoot = prefix === mount
return (
{!!entries.data?.length && (
{entries.data.map((e) =>
e.isFolder ? (
-
) : (
),
)}
)}
{!atRoot && (
)}
{revokeAll.error && {revokeAll.error.message}
}
)
}