"""nsite: publish this node's static site and watch the gateway.
`publish` is the only command that moves bytes: it walks a directory,
PUTs each file to the node's own Blossom face (signed with the node key,
over loopback, so the face's auth switch does not matter), then asks the
daemon to sign and publish the manifest from the resulting hashes. The
control socket never carries file bodies.
"""
from __future__ import annotations
import argparse
from typing import Any, Mapping, Optional, TypedDict
from fleetmesh_node import keystore
from fleetmesh_node.config.parameter import Parameter
from fleetmesh_node.planes.services.nsite.client import upload_site_blobs, walk_site_files
from fleetmesh_node.planes.services.nsite.compartment import DomainBinding, NsiteGateway, NsiteState, PublishResult
from .adapter import CommandDispatcher
from .base import _ask, _live, _status_file, add_command, emit, fail
[docs]class DomainsResponse(TypedDict, total=False):
domains: list[DomainBinding]
def _face_http(a: argparse.Namespace) -> str:
st = _live(a, 'status') or _status_file(a.dir) or {}
url = st.get('face') or ''
if not url.startswith(('ws://', 'wss://')):
fail('the node is not running or its face is unknown (status has no face url)')
return 'http' + url[2:]
def _show_status(r: NsiteState) -> None:
print('nsite gateway:')
print(' manifests cached: %d' % r.get('manifests_cached', 0))
print(' domains verified: %d' % r.get('domains_verified', 0))
print(' bytes cached: %d' % r.get('cached_bytes', 0))
def _fmt_binding(b: Optional[DomainBinding]) -> str:
if not b:
return '(none)'
return '%-32s %-10s %s%s' % (b.get('domain'), b.get('status'), b.get('site_key') or '-',
(' - ' + (b.get('why') or '')) if b.get('why') else '')
def _show_domains(r: DomainsResponse | Mapping[str, Any]) -> None:
rows = r.get('domains') or []
if not rows:
print('no custom-domain bindings yet')
return
for b in rows:
print(_fmt_binding(b))
def _show_published(r: PublishResult) -> None:
print('published %d files, %d bytes' % (int(r.get('files', 0)), int(r.get('bytes', 0))))
print(' manifest %s (kind %s)' % (r.get('manifest'), r.get('kind')))
print(' version %s' % r.get('aggregate'))
if r.get('snapshot'):
print(' snapshot %s' % r['snapshot'])
for h in r.get('hosts') or []:
print(' https://%s/' % h)
if r.get('snapshot_label'):
print(' (snapshot label %s)' % r['snapshot_label'])
for p in r.get('published_to') or []:
print(' relays: %s %s' % ('ok' if p.get('ok') else 'FAILED', p.get('why') or ''))
[docs]def cmd_publish(a: argparse.Namespace) -> int:
if not a.path:
fail('publish requires --path <directory>')
try:
files = walk_site_files(a.path)
except ValueError as e:
fail(str(e))
if '/index.html' not in {p for p, _ in files}:
print('warning: no /index.html at the root; browsers asking for / get the 404 page')
ks = keystore.Keystore.load(a.dir)
face = _face_http(a)
def progress(rel: str, h: str, size: int) -> None:
if not getattr(a, 'json', False):
print(' %-40s %s %7d' % (rel, h[:12], size))
paths, total = upload_site_blobs(files, face, ks.node_sk, progress=progress)
res = _ask(
a.dir,
'nsite.publish',
paths=paths,
site=a.site,
snapshot=bool(a.snapshot),
domains=a.domain_claim or [],
servers=a.server or [],
title=a.title,
timeout=60,
)
res['files'] = len(paths)
res['bytes'] = total
return emit(a, res, _show_published)
# Build declarative dispatcher from NsiteGateway.COMMANDS
_cmd_map = {c.key: c for c in NsiteGateway.COMMANDS}
dispatcher = CommandDispatcher('nsite', default_action='status')
dispatcher.add_command('status', _cmd_map['sites'], human=_show_status, timeout=10)
dispatcher.add_command('domains', _cmd_map['domains'], human=_show_domains, timeout=10)
dispatcher.add_command('verify', _cmd_map['verify'], human=lambda r, a: print(_fmt_binding(r.get('binding'))), timeout=30)
dispatcher.add_command(
'forget',
_cmd_map['forget'],
human=lambda r, a: print('forgot %s' % a.domain if r.get('dropped') else 'no binding for %s' % a.domain),
timeout=30,
)
dispatcher.add_custom(
'publish',
handler=cmd_publish,
parameters=(
Parameter(key='path', name='path', description='publish: directory to publish', type=str, default=''),
Parameter(key='site', name='site', description='publish: named-site id (d tag, 1-13 of [a-z0-9-]); default is the root site', type=str, default=''),
Parameter(key='snapshot', name='snapshot', description='publish: also publish an immutable kind-5128 snapshot', type=bool, default=False),
Parameter(key='domain_claim', name='domain_claim', description='publish: claim a custom domain in the manifest (repeatable)', type=list, default=list, cli_name='--domain-claim'),
Parameter(key='server', name='server', description='publish: extra Blossom server URL the blobs are mirrored on (repeatable)', type=list, default=list, cli_name='--server'),
Parameter(key='title', name='title', description='publish: site title tag', type=str, default=''),
),
)
[docs]def cmd_nsite(a: argparse.Namespace) -> int:
return dispatcher.dispatch(a)
[docs]class NsiteCommandProvider:
"""Registers the nsite (NIP-5A static site) commands."""
[docs] @classmethod
def register(cls, sub: argparse._SubParsersAction) -> None:
p = add_command(sub, 'nsite', cmd_nsite, 'host static sites (NIP-5A): publish this node\'s site, manage custom domains', js=True, experimental=True)
dispatcher.register_arguments(p, action_choices=('status', 'domains', 'verify', 'forget', 'publish'))