diff --git a/src/components/deploy/NpanelMigrationDialog.tsx b/src/components/deploy/NpanelMigrationDialog.tsx index 06e449b0..d387178d 100644 --- a/src/components/deploy/NpanelMigrationDialog.tsx +++ b/src/components/deploy/NpanelMigrationDialog.tsx @@ -1,7 +1,7 @@ import { useState } from 'react'; import { useQueryClient } from '@tanstack/react-query'; import { useNostr } from '@nostrify/react'; -import { AlertCircle, Check, ExternalLink, Loader2, Rocket } from 'lucide-react'; +import { AlertCircle, Check, ExternalLink, Loader2, Rocket, Trash2 } from 'lucide-react'; import { Dialog, DialogContent, @@ -14,23 +14,25 @@ import { Alert, AlertDescription } from '@/components/ui/alert'; import { Button } from '@/components/ui/button'; import { Skeleton } from '@/components/ui/skeleton'; import { useCurrentUser } from '@/hooks/useCurrentUser'; -import { useNpanelClaims, type NpanelClaimPlan } from '@/hooks/useNpanelClaims'; +import { useNpanelClaims, type NpanelClaimPlan, type NpanelTakenSite } from '@/hooks/useNpanelClaims'; import type { NpanelProvider } from '@/contexts/DeploySettingsContext'; import { claimNpanelHostname } from '@/lib/deploy/npanelApi'; -import { NAMED_SITE_KIND, republishTags } from '@/lib/deploy/npanelMigration'; -import { cn } from '@/lib/utils'; - -/** How long a manifest is given to reach the relays. */ -const PUBLISH_TIMEOUT_MS = 10_000; +import { NAMED_SITE_KIND, republishTags, retitleTags } from '@/lib/deploy/npanelMigration'; +import { checkRelayCoverage, forwardMissing, host, publishToRelays } from '@/lib/deploy/publishToRelays'; /** Where a single name has got to. */ type RowStatus = | { kind: 'waiting' } | { kind: 'publishing' } | { kind: 'claiming' } - | { kind: 'done' } + | { kind: 'done'; partial?: string } | { kind: 'failed'; error: string }; +/** What the last coverage run found, as a sentence per relay. */ +interface CoverageReport { + lines: string[]; +} + interface NpanelMigrationDialogProps { open: boolean; onOpenChange: (open: boolean) => void; @@ -50,17 +52,30 @@ function describeStep(claim: NpanelClaimPlan): string { } } +/** "took 3 of 5 relays", where that is worth saying. */ +function coverageNote(accepted: string[], rejected: { url: string; reason: string }[]): string | undefined { + if (!rejected.length) return undefined; + const total = accepted.length + rejected.length; + return `${accepted.length} of ${total} relays took it — ${host(rejected[0].url)}: ${rejected[0].reason}`; +} + export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMigrationDialogProps) { const { user } = useCurrentUser(); const { nostr } = useNostr(); const queryClient = useQueryClient(); - const { data: claims, isLoading, error } = useNpanelClaims(open ? provider : undefined); + const { data, isLoading, error } = useNpanelClaims(open ? provider : undefined); const [statuses, setStatuses] = useState>({}); - const [running, setRunning] = useState(false); + const [running, setRunning] = useState(null); + const [coverage, setCoverage] = useState(null); + + const claims = data?.waiting ?? []; + const actionable = claims.filter((claim) => claim.step.kind !== 'blocked'); + const blocked = claims.filter((claim) => claim.step.kind === 'blocked'); + + const retitlable = (data?.taken ?? []).filter((site) => site.needsTitle && !site.stray); + const strays = (data?.taken ?? []).filter((site) => site.stray); - const actionable = (claims ?? []).filter((claim) => claim.step.kind !== 'blocked'); - const blocked = (claims ?? []).filter((claim) => claim.step.kind === 'blocked'); const done = Object.values(statuses).filter((status) => status.kind === 'done').length; const failed = Object.values(statuses).filter((status) => status.kind === 'failed').length; @@ -79,6 +94,7 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi if (!user || claim.step.kind === 'blocked') return; let address: string; + let note: string | undefined; if (claim.step.kind === 'republish') { setStatus(claim.hostname, { kind: 'publishing' }); @@ -87,12 +103,14 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi kind: NAMED_SITE_KIND, content: claim.step.manifest.content, created_at: Math.floor(Date.now() / 1000), - tags: republishTags(claim.step.manifest, claim.step.identifier, provider.relayUrls), + tags: republishTags(claim.step.manifest, claim.step.identifier, provider.relayUrls, { + title: claim.suggestedTitle, + description: claim.suggestedDescription, + }), }); - await nostr - .group(provider.relayUrls) - .event(event, { signal: AbortSignal.timeout(PUBLISH_TIMEOUT_MS) }); + const published = await publishToRelays(nostr, event, provider.relayUrls); + note = coverageNote(published.accepted, published.rejected); address = `${NAMED_SITE_KIND}:${user.pubkey}:${claim.step.identifier}`; } else { @@ -101,35 +119,141 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi setStatus(claim.hostname, { kind: 'claiming' }); await claimNpanelHostname(provider.dashboardHost, user.signer, claim.hostname, address); - setStatus(claim.hostname, { kind: 'done' }); + setStatus(claim.hostname, { kind: 'done', partial: note }); }; - const migrateAll = async () => { - setRunning(true); + /** Republish one already-claimed site under the name it chose for itself. */ + const retitle = async (site: NpanelTakenSite): Promise => { + if (!user) return; - // One at a time: a remote signer answers one request at a time anyway, and - // a failure halfway through should leave a list somebody can read rather - // than a hundred simultaneous errors. - for (const claim of actionable) { - if (statuses[claim.hostname]?.kind === 'done') continue; + setStatus(site.hostname, { kind: 'publishing' }); + + const event = await user.signer.signEvent({ + kind: site.event.kind, + content: site.event.content, + created_at: Math.floor(Date.now() / 1000), + tags: retitleTags(site.event, { + title: site.suggestedTitle, + description: site.suggestedDescription, + }), + }); + + const published = await publishToRelays(nostr, event, provider.relayUrls); + setStatus(site.hostname, { + kind: 'done', + partial: coverageNote(published.accepted, published.rejected), + }); + }; + + /** Ask a relay to forget a manifest that was published for an unusable name. */ + const removeStray = async (site: NpanelTakenSite): Promise => { + if (!user) return; + + setStatus(site.hostname, { kind: 'publishing' }); + + try { + const identifier = site.event.tags.find(([name]) => name === 'd')?.[1] ?? ''; + const deletion = await user.signer.signEvent({ + kind: 5, + content: 'Published for a hostname no certificate can cover.', + created_at: Math.floor(Date.now() / 1000), + tags: [ + ['e', site.event.id], + ['a', `${site.event.kind}:${user.pubkey}:${identifier}`], + ['k', String(site.event.kind)], + ], + }); + + await publishToRelays(nostr, deletion, provider.relayUrls); + setStatus(site.hostname, { kind: 'done' }); + } catch (err) { + setStatus(site.hostname, { + kind: 'failed', + error: err instanceof Error ? err.message : 'Failed', + }); + } + }; + + /** Run `action` over `rows`, one at a time, recording failures per row. */ + const runEach = async ( + rows: T[], + key: (row: T) => string, + action: (row: T) => Promise, + ): Promise => { + for (const row of rows) { + if (statuses[key(row)]?.kind === 'done') continue; try { - await migrate(claim); + await action(row); } catch (err) { - setStatus(claim.hostname, { + setStatus(key(row), { kind: 'failed', error: err instanceof Error ? err.message : 'Failed', }); } } + }; - setRunning(false); + const migrateAll = async () => { + setRunning('migrate'); + // One at a time: a remote signer answers one request at a time anyway, and + // a failure halfway through should leave a list somebody can read rather + // than a hundred simultaneous errors. + await runEach(actionable, (claim) => claim.hostname, migrate); + setRunning(null); // Whatever succeeded is no longer waiting, and whatever failed still is. queryClient.invalidateQueries({ queryKey: ['npanel-claims'] }); }; - const renderStatus = (claim: NpanelClaimPlan) => { - const status = statuses[claim.hostname] ?? { kind: 'waiting' as const }; + const fixTitles = async () => { + setRunning('titles'); + await runEach(retitlable, (site) => site.hostname, retitle); + setRunning(null); + queryClient.invalidateQueries({ queryKey: ['npanel-claims'] }); + }; + + /** + * Fill in the relays that are missing these manifests. + * + * Costs no signatures: the events go out exactly as they are, ids and + * signatures unchanged, so a relay that already has one says `duplicate:` + * and a relay that refused before says why. + */ + const fixCoverage = async () => { + const events = data?.events ?? []; + if (!events.length) return; + + setRunning('coverage'); + setCoverage(null); + + try { + const found = await checkRelayCoverage( + nostr, + provider.relayUrls, + events.map((event) => event.id), + ); + const result = await forwardMissing(nostr, found, events); + + const lines = found.map((relay) => { + const had = relay.present.size; + const sent = result.filled.get(relay.url) ?? 0; + const why = result.refused.get(relay.url); + + if (why) return `${host(relay.url)}: had ${had} of ${events.length}, refused the rest — ${why}`; + if (sent) return `${host(relay.url)}: had ${had} of ${events.length}, sent ${sent} more`; + return `${host(relay.url)}: has all ${events.length}`; + }); + + setCoverage({ lines }); + } catch (err) { + setCoverage({ lines: [err instanceof Error ? err.message : 'Could not check relay coverage.'] }); + } + + setRunning(null); + }; + + const renderStatus = (hostname: string, fallback: string) => { + const status = statuses[hostname] ?? { kind: 'waiting' as const }; switch (status.kind) { case 'publishing': @@ -146,24 +270,33 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi ); case 'done': return ( - - Yours - + + + {status.partial ? ( + {status.partial} + ) : ( + + Yours + + )} + ); case 'failed': return {status.error}; case 'waiting': - return {describeStep(claim)}; + return {fallback}; } }; + const busy = running !== null; + return ( - + Take back your sites @@ -173,7 +306,7 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi -
+
{isLoading && (
@@ -189,32 +322,118 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi )} - {claims && claims.length === 0 && ( + {data && !claims.length && !data.taken.length && (

Nothing is waiting for you here.

)} {actionable.length > 0 && ( -
- {actionable.map((claim) => ( -
-
-
{claim.hostname}
-
{renderStatus(claim)}
+
+

Waiting for you

+
+ {actionable.map((claim) => ( +
+
+
{claim.hostname}
+
{renderStatus(claim.hostname, describeStep(claim))}
+
+ + {claim.step.kind === 'republish' ? 'republish' : 'claim'} +
- - {claim.step.kind === 'republish' ? 'republish' : 'claim'} - + ))} +
+
+ )} + + {retitlable.length > 0 && ( +
+
+
+

Titled after their address

+

+ The archive could only call a site by its hostname. These say what they are + actually called, so the name they publish under can too. +

- ))} + +
+
+ {retitlable.map((site) => ( +
+
+
{site.hostname}
+
+ {renderStatus( + site.hostname, + site.suggestedTitle ? `Will be titled "${site.suggestedTitle}".` : 'The title will be removed.', + )} +
+
+
+ ))} +
+
+ )} + + {(data?.events.length ?? 0) > 0 && ( +
+
+
+

Relay coverage

+

+ A site is only as findable as the relays holding its manifest. This sends the + events you already published to the relays that do not have them — same events, + no signing. +

+
+ +
+ {coverage && ( +
+ {coverage.lines.map((line) => ( +

+ {line} +

+ ))} +
+ )} +
+ )} + + {strays.length > 0 && ( +
+

Published for a name that cannot load

+
+ {strays.map((site) => ( +
+
+
{site.hostname}
+
+ {renderStatus( + site.hostname, + `No certificate covers a name this deep under ${provider.domain}.`, + )} +
+
+ +
+ ))} +
)} @@ -236,17 +455,17 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi {failed > 0 - ? `${done} of ${actionable.length} done, ${failed} failed — run it again to retry.` + ? `${done} done, ${failed} failed — run it again to retry.` : done > 0 - ? `${done} of ${actionable.length} done. A republished site takes the gateway about a minute to pick up.` + ? `${done} done. A republished site takes the gateway about a minute to pick up.` : `${actionable.length} to migrate.`}
- -