From ef79fbe5add01e22b75e6453fa8af423bede49d4 Mon Sep 17 00:00:00 2001 From: Vitali Date: Sun, 26 Jul 2026 13:27:16 +0000 Subject: [PATCH] Persist the printer token on connect (survive unclean restarts) The token obtained from the printer was only written to the known-hosts file by the shutdown defer in main(), which runs only on a graceful exit. On an unclean exit (SIGKILL, container restart, OOM, power loss) a freshly authorized token was therefore lost, forcing another touchscreen authorization on the next start. Additionally, the IP-only fallback printer (-host without discovery) was created without an ID, and LocalStorage.Add skips ID-less printers, so its token was never persisted even on a clean exit. Fix: - Add an OnPrinterUpdate hook, invoked right after a successful connect, which main() wires to ls.Add(printer) + ls.Save() -- persisting the (refreshed) token immediately instead of only at shutdown. - Give the IP-only fallback printer an ID (its host) so ls.Add persists it. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_018zWUoJhzouLTnkrpZE7rkJ --- connector.go | 10 ++++++++++ main.go | 15 +++++++++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/connector.go b/connector.go index 311a458..cb8fbfb 100644 --- a/connector.go +++ b/connector.go @@ -18,6 +18,10 @@ var ( errFileTooLarge = errors.New("File is too large.") ) +// OnPrinterUpdate, if set, is called after a successful connect so the caller +// can persist the printer's (refreshed) token to disk. Set by main(). +var OnPrinterUpdate func(*Printer) + type Payload struct { File io.Reader Name string @@ -126,6 +130,12 @@ func (c *connector) Upload(printer *Printer, payload *Payload) error { } defer h.Disconnect() + // Persist the (possibly refreshed) token so it survives restarts, + // including an unclean exit that skips the shutdown defer. + if OnPrinterUpdate != nil { + OnPrinterUpdate(printer) + } + if payload.Size > FILE_SIZE_MAX { return errFileTooLarge } diff --git a/main.go b/main.go index 9278fe0..30b4ef0 100644 --- a/main.go +++ b/main.go @@ -83,6 +83,16 @@ func main() { var printer *Printer ls := NewLocalStorage(KnownHosts) + // Persist the token to known hosts as soon as it is (re)obtained on connect, + // so it survives restarts even on an unclean exit (the shutdown defer below + // only runs on a graceful exit). + OnPrinterUpdate = func(p *Printer) { + if p == nil { + return + } + ls.Add(p) + _ = ls.Save() + } defer func() { if printer != nil { // update printer's token @@ -140,8 +150,9 @@ func main() { printer = printers[0] } } else { - // directly to printer using ip/hostname - printer = &Printer{IP: Host} + // directly to printer using ip/hostname; keep an ID so the token gets + // persisted (ls.Add skips ID-less printers) + printer = &Printer{IP: Host, ID: Host} } }