diff --git a/deploy/docker/docker-compose.yml b/deploy/docker/docker-compose.yml index 12052b7b..46666e3e 100644 --- a/deploy/docker/docker-compose.yml +++ b/deploy/docker/docker-compose.yml @@ -24,10 +24,14 @@ services: TITANO_DB_NAME: titano TITANO_DB_USER: titano TITANO_DB_PASSWORD: ${TITANO_DB_PASSWORD:?set TITANO_DB_PASSWORD in .env} - # auto (self-signed), pem or proxy; behind a proxy, set TITANO_TRUSTED_PROXIES to its address or network (for a - # proxy container on this network, the network's subnet; only loopback is trusted otherwise) + # auto (self-signed), pem or proxy. Behind a proxy, set TITANO_TRUSTED_PROXIES to the proxy's own address (only + # loopback is trusted otherwise). Give a proxy container a fixed one (ipv4_address, on a network with an ipam + # subnet that this service joins too) and let it reach Titano on that network, not through a published port. + # Never list a subnet or the network's gateway (.1): Docker relays connections to the published ports (IPv6 + # clients, the host) from the gateway, and each of them could then choose its client address. For a proxy on the + # host itself, run this service with network_mode: host; the proxy then reaches Titano over loopback. TITANO_TLS_MODE: auto - # TITANO_TRUSTED_PROXIES: "172.18.0.0/16" + # TITANO_TRUSTED_PROXIES: "172.30.0.10" # TITANO_PUBLIC_HTTPS_PORT: "8443" TITANO_SERVER_NAME: Titano Server # Trace, Debug, Information, Warning or Error diff --git a/deploy/releases-repo/README.md b/deploy/releases-repo/README.md index f6df9bf8..4f3ff4aa 100644 --- a/deploy/releases-repo/README.md +++ b/deploy/releases-repo/README.md @@ -91,9 +91,14 @@ admin panel shows under Settings so you can compare them. and set `TITANO_DB_HOST: 127.0.0.1`. - Behind a reverse proxy (`TITANO_TLS_MODE=proxy`), only the proxies listed in `TITANO_TRUSTED_PROXIES` may set `X-Forwarded-*` headers. By default that is loopback only: other machines on your network reach the HTTP port - directly, so they must not choose the address the sign-in limit and the audit log see. List your proxy's address, - or the subnet of the Docker network it shares with Titano (for example `172.18.0.0/16`). The admin panel shows *Not - via proxy* when a page did not come through a trusted proxy over HTTPS. + directly, so they must not choose the address the sign-in limit and the audit log see. List your proxy's own + address. Give a proxy container a fixed IP on a user-defined Docker network it shares with Titano (`ipv4_address` in + compose, *Fixed IP address* on Unraid), for example `172.30.0.10`, and let it reach Titano on that network rather + than through a published port. Never list a subnet, the network's gateway (`.1`) or Docker's default bridge + (`172.17.0.0/16`): Docker relays connections to published ports from the gateway (IPv6 clients, the host itself), + and on the default bridge every other container would count as your proxy too. For a proxy running on the Docker + host itself, run Titano with `network_mode: host`: the proxy then reaches it over loopback. The admin panel shows + *Not via proxy* when a page did not come through a trusted proxy over HTTPS. ## Titano Server on Unraid @@ -116,13 +121,18 @@ Choose the *Server* component in the setup, or unpack `Titano-Server-win-x64- prefer auto - + Titano Server Information 99 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index cfdc756a..75869f2d 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -46,7 +46,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S | `Model` | Domain entities and enums (§5) shared by Data, Server and clients | | `Packaging` | TPK1 installer payload writer/reader, staged install transaction | | `Diagnostics` | `Log`, file sink, synthetic sequences, `SecretScrubber`, `DiagnosticsArchive` (scrubbed diagnostics zip) | -| `Localization`, `IO`, `Hashing`, `Branding` | `Loc`/plural rules, `AtomicFile`, `StartupCommand` (sign-in entries of the programs, removed by the uninstaller), CRC-32/SHA helpers, brand mark geometry | +| `Localization`, `IO`, `Hashing`, `Branding` | `Loc`/plural rules, `AtomicFile`, `StartupCommand` (sign-in entries of the programs, moved or removed by setup), CRC-32/SHA helpers, brand mark geometry | ### 2.2 Titano.Data @@ -86,7 +86,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S | `Server/Api`, `Server/Events` | Endpoint groups (`XxxEndpoints.Map`), API errors, the WebSocket `EventHub` | | `Server/Security` | Accounts, password hashing, tokens, session cookies, login guard, access rules, audit log | | `Server/Storage`, `Server/Jobs` | Archive and processing modules, uploads, render store; `JobEngineHost`, render node service, monitor and availability | -| `Server/Hosting`, `Server/Admin/web` | `ServerHost`, certificates, discovery beacon, embedded static files, Windows service; the admin panel (ES modules, one per page) | +| `Server/Hosting`, `Server/Admin/web` | `ServerHost`, certificates, discovery beacon, embedded static files, Windows service (start and stop failures in the Application event log); the admin panel (ES modules, one per page) | ### 2.5 Hosts @@ -95,7 +95,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S | Titano (desktop) | `App/Infrastructure/AppServices` | SQLite index in `%LOCALAPPDATA%\Titano` (or `.\data` when portable); `ArchiveService` with WIC first, then managed decoders; `ProcessingService` with Media Foundation, then managed encoders; one `JobEngine` with the handlers of both; thumbnails; `ServerSession`; `SyncHost` while signed in (sync engine and agent, upload and download handlers, metered hold, editors of server sequences); the render node while opted in and signed in; update check and download (`About/UpdateCheck`, `About/UpdateDownload`, `About/UpdateFlow`: the setup, or the portable zip for a portable copy, verified against `SHA256SUMS`, resumable, cancellable, failing after 60 s without data); diagnostics bundle; daily index backups and the restore staged in Settings › Advanced (`DatabaseBackups`) | | Titano Server | `Server/Hosting/ServerHost.Build` | Options from `server.json` + `TITANO_*`; PostgreSQL (or SQLite on Windows); `ArchiveModule` then `ProcessingModule` register job handler providers; `JobEngineHost` (renders only managed formats and MP4 jobs no render node can take, BRIEF §14.7); `RenderNodeService`/`RenderNodeMonitor`; `UploadService`; `EventHub` (WebSocket); embedded admin panel; LAN discovery beacon; Windows service host; daily backups of an SQLite index (`DatabaseBackupService`) | | Titano Uploader | `Uploader/App.xaml.cs` | `TitanoClient`, persisted queue, watch folders; no database | -| Titano Setup | `Setup/Program` | TPK1 payload extraction, registry, shortcuts, file types named in setup's language, silent mode, uninstaller; only what starts a program its log or payload lists is changed: Windows services of those programs stopped once the programs have closed, started again (also after a failure) or deleted through the Service Control Manager (an elevated `/SERVICES … /NAMES` step when needed), sign-in entries of those programs removed, shared shortcuts handed to the product that keeps the program; the Server only for all users inside Program Files; "Remove my data" limited to the programs no other installed product uses | +| Titano Setup | `Setup/Program` | TPK1 payload extraction, registry, shortcuts, file types named in setup's language, silent mode, uninstaller; only what starts a program its log or payload lists is changed: Windows services of those programs stopped once the programs have closed, started again (also after a failure) or deleted through the Service Control Manager (an elevated `/SERVICES … /NAMES` step when needed), sign-in entries of those programs moved to the program an upgrade renamed or removed, shared shortcuts handed to the product that keeps the program; the Server only for all users inside Program Files; "Remove my data" limited to the programs no other installed product uses | ### 2.6 Job kinds and their handlers diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 0b14ae86..58763ebd 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -257,7 +257,7 @@ One line per decision: date · decision · alternative · reason. | 2026-10-12 | Maintenance vacuums the SQLite index only when at least 10 % of it is free pages; the dry run reports the reclaimable size. | Vacuum on every run | Rewriting a large index for a few pages holds every writer for nothing. | | 2026-10-12 | Settings › Formats Install opens the Microsoft Store page of the missing extension (ms-windows-store:), falling back to its web page. | Download or bundle codecs | No external processes except OS dialogs (BRIEF §8.6); the Store is the OS route for HEIF/HEVC/RAW extensions. | | 2026-10-12 | Settings › Archive rows show and edit the open archive's archive.json and also seed the archives this PC creates later. The rescan interval is a PC setting. | Keep separate 'defaults for new archives' rows | One set of rows matches Settings.html; the archive is the source of truth (BRIEF §7). | -| 2026-10-12 | TLS mode proxy honours `X-Forwarded-For/Proto/Host` only from `TITANO_TRUSTED_PROXIES` (new variable, also in `server.json`: IP addresses or CIDR networks), by default loopback only. The admin panel shows a *Not via proxy* chip (Dashboard, Settings) when a page did not come through a trusted proxy over HTTPS, and a cookie sign-in refused for that reason answers `proxy_untrusted`, naming the variable. | Trust every peer (as before), or default to loopback plus the RFC 1918 and ULA networks | BRIEF §14.2 keys the 5/min sign-in limit and the audit address on the client IP. Home-network clients reach the HTTP port directly from private addresses (Docker's port publishing keeps them), so trusting private networks let exactly them choose their own address. A proxy in another container is listed by its address or subnet. | +| 2026-10-12 | (Partly superseded by the deployment guidance row below: a proxy is listed by its own fixed address, never a Docker subnet or gateway; Docker's port publishing relays IPv6 clients and the host's own connections from the gateway.) TLS mode proxy honours `X-Forwarded-For/Proto/Host` only from `TITANO_TRUSTED_PROXIES` (new variable, also in `server.json`: IP addresses or CIDR networks), by default loopback only. The admin panel shows a *Not via proxy* chip (Dashboard, Settings) when a page did not come through a trusted proxy over HTTPS, and a cookie sign-in refused for that reason answers `proxy_untrusted`, naming the variable. | Trust every peer (as before), or default to loopback plus the RFC 1918 and ULA networks | BRIEF §14.2 keys the 5/min sign-in limit and the audit address on the client IP. Home-network clients reach the HTTP port directly from private addresses (Docker's port publishing keeps them), so trusting private networks let exactly them choose their own address. A proxy in another container is listed by its own fixed address. | | 2026-10-12 | `TITANO_PUBLIC_HTTP_PORT` and `TITANO_PUBLIC_HTTPS_PORT` (optional, 1–65535) name the host ports a container's ports are published on. The admin panel's HTTP→HTTPS redirect and the LAN beacon use them, otherwise the bound ports. LAN discovery from a container needs host networking (documented, with PostgreSQL then published on loopback). | Drop the redirect, or always advertise the bound ports | The Unraid template lets users remap ports (8443 is often taken), and the redirect and beacon otherwise named the container's internal port. | | 2026-10-12 | Windows data folder: a protected DACL (SYSTEM, Administrators, the server's account; nothing inherited), re-applied at start. The folder and everything in it must be owned by those accounts and contain no symbolic link or junction, checked before the ACL is touched; otherwise the server refuses to start and names the entry. `server.json` is read only after its owner is checked on the open handle. Secrets (`initial-admin-password.txt`, `tls/server.pfx`) are deleted and created anew with an explicit private DACL; elsewhere they get mode 0600. On Windows this replaces the 'owner-only file' wording of the 2026-10-02 sign-in row. | Reset foreign owners to Administrators, or keep %ProgramData%'s inherited ACL | A folder or file another user created keeps its owner's WRITE_DAC whatever the DACL says, and its contents (`server.json`, `titano.db`, `server.pfx`) are theirs, so resetting the owner would launder them. A link would carry the ACL rewrite and the server's writes elsewhere. | | 2026-10-12 | `--install-service` registers the LocalSystem service only from a program folder (and, under `dotnet`, a host folder) inside `%ProgramFiles%` or `%ProgramFiles(x86)%`, where no ACL entry gives change rights to an account other than SYSTEM, Administrators, TrustedInstaller or the registering administrator. Otherwise it exits 1 with a localized reason. | Register from anywhere, or only warn | A SYSTEM service runs whatever sits at its image path. A per-user install or a zip unpacked elsewhere would hand SYSTEM to any program of that user (CWE-732). | @@ -286,7 +286,7 @@ One line per decision: date · decision · alternative · reason. | 2026-10-12 | A click on a Windows notification restores the window. It runs the toast's action only when the toast opts in (`Toast.RunsFromNotification`: card detected → Import, interrupted import → Resume, job finished → Open, navigation to Import or Jobs) and it is the only notification shown since the tray icon appeared | Run every toast's action; track which balloon was clicked | People click a notification to bring the window back, so a Cancel, Undo or Retry there would act before they read why; NIN_BALLOONUSERCLICK does not say which of several notifications was clicked. | | 2026-10-12 | Toasts also become Windows notifications while no Titano window is active, not only while the window is minimised or hidden; Settings › General › Notifications turns them off | Only when minimised, as BRIEF §12.1 words it | A window behind another program is as unseen as a minimised one; card prompts (§12.4) and job endings would expire unseen after 8 s. | | 2026-10-12 | Settings › General › Startup writes the HKCU Run value `Titano` = `"" --minimized`. The window starts minimised, and its first restore brings back the saved maximised state. The value counts as on only when it starts this executable; it is rewritten only when an update renamed the program in this copy's folder, and only the copy it starts removes it. Portable copies hide the row and write nothing to the registry | Scheduled task; one value per copy; rewrite the value at every start | The Run key is what Task Manager's Startup tab shows and turns off (as for the Uploader). One value cannot serve two copies, and a copy that merely starts must not take it over. Portable mode keeps everything under `.\data` (BRIEF §6.2). | -| 2026-10-12 | The uninstaller removes the client's and the Uploader's HKCU Run values when their command starts a program in the folder it removes (`StartupCommand` in Titano.Core is shared by the programs and Setup) | Leave them; remove them whatever they start | Windows would otherwise keep a sign-in entry that points at a deleted exe; another copy's entry is not this uninstaller's to remove. | +| 2026-10-12 | (Superseded by the sign-in entry cleanup row below: a value is removed only when it starts a program the install log lists.) The uninstaller removes the client's and the Uploader's HKCU Run values when their command starts a program in the folder it removes (`StartupCommand` in Titano.Core is shared by the programs and Setup) | Leave them; remove them whatever they start | Windows would otherwise keep a sign-in entry that points at a deleted exe; another copy's entry is not this uninstaller's to remove. | | 2026-10-12 | The editor's 1:1 view moves from Ctrl+1 to Ctrl+Shift+1 (tooltip key `Tooltips.Editor.Preview.OneToOne`). Ctrl+1…6 (number row and keypad) and Ctrl+, open the rail's sections and do nothing behind the first-run dialog | Change the rail's shortcuts instead | The rail tooltips already listed Ctrl+1…6 (BRIEF §12.1 "standard shortcuts, listed in tooltips"); section shortcuts must work everywhere, the 1:1 view only inside the editor. | | 2026-10-12 | Rail badges: Jobs counts running or paused jobs plus failures not yet seen on the Jobs screen (which also turn the idle taskbar button red). Server counts sync conflicts. Library counts the sequences of this PC flagged with warnings (the Warnings filter), recounted after analyses. Archive counts the index health lines that need attention, set when the Archive screen reads its figures | Badge running jobs only; read the archive figures at start for the Archive badge | BRIEF §12.1 asks for "badge counts (warnings, running jobs)", and DESIGN §4 defines the badge as the count of things needing attention. The Archive figures are a heavy read that the screen already does when it opens. | | 2026-10-12 | The taskbar button uses WPF's `Window.TaskbarItemInfo`, bound to the shell: the job bar's progress, an indeterminate bar while the total is unknown, and red while a failure waits unseen | `Titano.Core.Windows/Shell/TaskbarProgress` | WPF already wraps ITaskbarList3 for its windows, and a binding needs no window-handle plumbing. | @@ -325,7 +325,7 @@ One line per decision: date · decision · alternative · reason. | 2026-10-12 | Setup asks programs to close before touching any service. On install it stops the running services, then installs, then prunes services whose program is gone and starts exactly the ones it stopped, whatever their start type. On uninstall it deletes the services only once the programs have closed, just before the files go. Any failure after a stop starts those services again. | Stop or delete services first; start every automatic service after an upgrade | A program refusing to close left the Server stopped, or its service already deleted, and a failed upgrade left it down until reboot. An administrator's deliberately stopped service, or a running demand-start one, keeps its state. | | 2026-10-12 | User data ownership in %LOCALAPPDATA%\Titano: entries starting with `uploader` (also inside `logs`) are the Uploader's, everything else the desktop app's. 'Remove my data' offers only the data of the uninstalled product's components that no other registered Titano product (same Publisher) has. A product whose folder or log cannot be read now counts as using all of it. | Delete the whole folder; hide the option whenever another product is registered | The products share the folder. An offline drive or damaged log must not make a still-installed product's index or upload queue look orphaned. A stale entry only hides the option, which is the safe direction. | | 2026-10-12 | A shortcut that starts an existing program elsewhere is not created or retargeted, but it is logged. When the product it starts is uninstalled (or an upgrade drops it), the shortcut is pointed at the same program of another installation of the same scope whose log lists it, and only deleted when there is none. | Each product overwrites and deletes the shared 'Titano Uploader' shortcuts; distinct names per product | Both products ship the Uploader under the same shortcut name. The program that stays installed keeps its Start menu and desktop shortcuts, and neither uninstall touches the other's. | -| 2026-10-12 | Sign-in entry cleanup: SetupRegistry.DeleteStartupEntries removes the client's ('Titano') and the Uploader's ('Titano Uploader') Run values, named by Core/IO/StartupCommand (shared with fix/shell-notify), only when they start a program the install log lists. This happens on uninstall and on an upgrade that drops that program. When merging with fix/shell-notify, keep this branch's DeleteStartupEntries and its call. | Every Run value under the folder (first version); the folder-scoped variant of fix/shell-notify | One implementation after the merge. Nothing outside Titano's own value names and installed programs is touched, so a portable copy in a subfolder keeps its entry. | +| 2026-10-12 | Sign-in entry cleanup: SetupRegistry.DeleteStartupEntries removes the client's ('Titano') and the Uploader's ('Titano Uploader') Run values, named by Core/IO/StartupCommand, only when they start a program the install log lists. This happens on uninstall, and on an upgrade that drops the program's component; an upgrade that renames the program moves the entry instead (see the sign-in entry move row below). | Every Run value under the folder (first version); the folder-scoped variant of fix/shell-notify | Nothing outside Titano's own value names and installed programs is touched, so a portable copy in a subfolder keeps its entry. | | 2026-10-12 | 'Maintenance release.' is written whenever no section or breaking entry was written, also under a title. | Test the output length | release.yml always passes a title, so the old check never fired (BRIEF §19.3). | | 2026-10-12 | A frame read from its proxy (an original this host cannot decode) records no decode tier: thumbnails drawn from the proxy, and renders or analyses that read it, leave the original's tier and flags as they are. | Record the proxy's tier | The tier describes the original on this host (BRIEF §8.2); a proxy that decodes says nothing about it, and its Undecodable flag must stay so renders keep reading the proxy. | | 2026-10-12 | *Reset all* also turns *Start with Windows* off; importing a settings file leaves it alone. | Keep the sign-in entry on reset | The entry belongs to this copy and lives in the registry, not in the settings file; its default is off, and a settings file from another PC says nothing about this copy. | diff --git a/docs/STATUS.md b/docs/STATUS.md index 786ae121..3bb856be 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -10,7 +10,7 @@ Phase plan: docs/BRIEF.md §22. Windows behaviour is verified on CI (`windows-la | 3 Library and Archive manager | Done: Library (virtualised grid and list, timeline with year bands, filters, saved views, quick actions, mass bar, *Delete…* into the archive's trash with a dry run, typed confirmation and Undo, cards for server-only sequences), Archive manager (tree, health, statistics charts, maintenance with *Trash…* and restore, verify, duplicates, orphans, adopt, mass rename and move with dry runs), Jobs, Settings, Welcome, Server and About. Gate measured on 500,000 photos: Library open 259 ms on SQLite and 181 ms on PostgreSQL on a new connection pool (warm OS cache; budget 1 s); every filter, search, sort and next page ≤ 6.4 ms (budget 200 ms). | | 4 Card import | Done: device detection, card pool and camera profiles, plan with sessions (merge and split), hash-verified copy, post-actions (verified delete, format behind a typed confirmation, eject), auto-import, Archive, Folder and Server destinations. Gate: import from a simulated card folder end to end in tests; delete and format refuse any photo the import did not verify; screenshots on `ci-screenshots`. | | 5 Analysis advisor | Done: light and deep analysis, reports and section charts, recommendations with localised reasons, sequence presets, Auto/manual controls and Optimise in the editor. Gate: golden recommendations for synthetic sequences; every reason key exists in `en` and `it` (`i18n check`); deep analysis streams with checkpoints and resumes after a restart. | -| 6 Engine, encoding, editor | Done: render pipeline, MP4/AVI/GIF/APNG/image sequences, Media Foundation H.264/HEVC/AV1 with managed fallbacks; the sequence editor (Frames, Exposure, Camera, Motion and Export tabs, preview tools, section charts, curve editor, undo/redo, batch export) for local and server sequences. Gate: self-test suite green; the in-house inspector validates the containers the tests write; the encoder in use is logged. Playback: MediaPlayer opens the Media Foundation output and a source reader decodes its first frame (Windows tests); every `--capture` screen is pixel-diffed against `tests/visual/baselines` (`screenshots diff`). | +| 6 Engine, encoding, editor | Done: render pipeline, MP4/AVI/GIF/APNG/image sequences, Media Foundation H.264/HEVC/AV1 with managed fallbacks; the sequence editor (Frames, Exposure, Camera, Motion and Export tabs, preview tools, section charts, curve editor, undo/redo, batch export) for local and server sequences. Gate: self-test suite green; the in-house inspector validates the containers the tests write; the encoder in use is logged. Playback: MediaPlayer opens the Media Foundation output and a source reader decodes its first frame (Windows tests). The pixel diff of every `--capture` screen against `tests/visual/baselines` (`screenshots diff`, BRIEF §20.2) is wired into CI but not armed: no baseline is committed yet, so the step compares nothing and only warns until the first baselines are accepted from `ci-screenshots` (Next steps). | | 7 Server, sync, uploader | Done: server (API, auth, uploads, jobs, render nodes, events, admin panel with light and dark themes, Windows service), Uploader, client sync (sync table, conflicts with *Save both*, proxies kept offline, metered pause), server sequences edited with proxies and rendered where the originals are, this PC as a render node. Gate covered in-process: a sequence uploaded from one PC downloads identically on another, interrupted uploads and downloads resume, server events update a PC, renders run on a node and on the server's managed fallback, jobs resume after a restart, sign-ins and administrative actions are audited. The run with two real PCs and the Uploader against the Docker server is part of the release test. | | 8 Release readiness | Release pipeline end to end (installers, portable and server zips, SHA256SUMS, release notes, optional signing, multi-arch GHCR image, public releases repository content), update check with verified download, scrubbed diagnostics bundles (desktop and server), performance gates, 38 cultures (`en`, `it` and 36 machine translations with glossaries and independent reviews), RTL pass (`ar`, `he`: mirrored windows, left-to-right islands for media, charts, numbers and paths; any right-to-left culture added later follows), accessibility pass (names, live regions, keyboard paths for charts and the curve editor). CI installs the packed installers silently on a clean `windows-latest` runner, runs the installed programs, upgrades in place and uninstalls (files, Add/Remove Programs, shortcuts, file type, user data kept, exit codes). Pending: a tagged pre-release published from CI, the interactive install on a real PC, Unraid template validation on a real server. | | 9 Monetization | Not started: requires explicit approval (§22). | @@ -18,7 +18,8 @@ Phase plan: docs/BRIEF.md §22. Windows behaviour is verified on CI (`windows-la ## Verification (2026-10-12) A full audit against the brief, `CLAUDE.md`, the UI kit, the tests and the Docker and client setups confirmed 71 -defects with independent verifiers; all are fixed (rows dated 2026-10-12 in DECISIONS and CHANGELOG). The Docker +defects with independent verifiers; all are fixed (rows dated 2026-10-12 in DECISIONS and CHANGELOG), except that the +new screenshot diff (BRIEF §20.2 visual regression) gates nothing until its first baselines are committed. The Docker image was built and run with PostgreSQL 17, a fresh archive folder and remapped ports; the client installers are installed, run, upgraded and removed on `windows-latest` by the `installer` CI job. @@ -52,8 +53,12 @@ src/Titano.App/bin/Release/net10.0-windows/Titano.exe --capture out/screenshots ## Next steps (Phase 8 gate) -1. Create the public repository (`/titano-releases`), add the `RELEASES_TOKEN` secret, push a `v0.x.y-rc.1` +1. Arm the screenshot diff: from the `ci-screenshots` commit of the first green `windows-latest` run at the current + HEAD, run `dotnet run --project src/Titano.Tools -- screenshots accept ` and commit the PNGs to + `tests/visual/baselines` (its README says how). From then on a visual change, or a screen without a baseline, + fails CI. +2. Create the public repository (`/titano-releases`), add the `RELEASES_TOKEN` secret, push a `v0.x.y-rc.1` tag and check the release, the public repository content and the GHCR image (set it public once). -2. On Windows: install, upgrade over the previous version, uninstall (with and without user data), silent mode. -3. Unraid: add the template repository, install with the official PostgreSQL template, reach the WebUI. -4. Native-speaker review of the machine translations where users report wording (`i18n export` per language). +3. On Windows: install, upgrade over the previous version, uninstall (with and without user data), silent mode. +4. Unraid: add the template repository, install with the official PostgreSQL template, reach the WebUI. +5. Native-speaker review of the machine translations where users report wording (`i18n export` per language). diff --git a/src/Titano.Core/IO/StartupCommand.cs b/src/Titano.Core/IO/StartupCommand.cs index 6e023874..4e0652ac 100644 --- a/src/Titano.Core/IO/StartupCommand.cs +++ b/src/Titano.Core/IO/StartupCommand.cs @@ -3,7 +3,8 @@ namespace Titano.Core.IO; /// /// The sign-in entries of Titano's programs: HKCU\Software\Microsoft\Windows\CurrentVersion\Run values whose /// command starts one executable with one option ("C:\…\Titano.exe" --minimized). Shared by the programs that -/// write them and the uninstaller that removes them; the paths are Windows paths, compared ignoring case. +/// write them and setup, which moves or removes them with the programs it installed; the paths are Windows paths, +/// compared ignoring case. /// public static class StartupCommand { @@ -39,13 +40,18 @@ public static class StartupCommand public static bool Starts(string? command, string? executable) => executable is { Length: > 0 } && string.Equals(Executable(command), executable, StringComparison.OrdinalIgnoreCase); - /// The program starts lies in or one of its folders. - public static bool StartsFrom(string? command, string directory) + /// + /// made to start with the same options (setup moves an entry + /// to the program an update renamed); null when names no program. + /// + public static string? Retarget(string? command, string executable) { - ArgumentNullException.ThrowIfNull(directory); - var folder = directory.TrimEnd('\\', '/'); - return Executable(command) is { } exe && folder.Length > 0 && exe.Length > folder.Length + 1 - && exe.StartsWith(folder, StringComparison.OrdinalIgnoreCase) && exe[folder.Length] is '\\' or '/'; + ArgumentNullException.ThrowIfNull(executable); + if (Executable(command) is null) return null; + var text = command!.Trim(); + var end = text[0] == '"' ? text.IndexOf('"', 1) + 1 : text.IndexOf(' ', StringComparison.Ordinal); + var options = end < 0 ? string.Empty : text[end..].Trim(); + return options.Length == 0 ? $"\"{executable}\"" : Format(executable, options); } /// The folder of the program starts; null when it names none. diff --git a/src/Titano.Server/Configuration/ServerOptions.cs b/src/Titano.Server/Configuration/ServerOptions.cs index f971f122..1ac0a6ec 100644 --- a/src/Titano.Server/Configuration/ServerOptions.cs +++ b/src/Titano.Server/Configuration/ServerOptions.cs @@ -234,7 +234,7 @@ public sealed class ServerOptions } catch (FormatException ex) { - throw new InvalidOperationException($"TITANO_TRUSTED_PROXIES must list IP addresses or networks such as 172.16.0.0/12: {ex.Message}", ex); + throw new InvalidOperationException($"TITANO_TRUSTED_PROXIES must list IP addresses (such as 172.30.0.10) or networks in CIDR form: {ex.Message}", ex); } if (ChunkSizeBytes is < 64 * 1024 or > 64 * 1024 * 1024) throw new InvalidOperationException("The chunk size must be between 64 KiB and 64 MiB."); diff --git a/src/Titano.Server/Hosting/Windows/ServiceEventLog.cs b/src/Titano.Server/Hosting/Windows/ServiceEventLog.cs new file mode 100644 index 00000000..2981696c --- /dev/null +++ b/src/Titano.Server/Hosting/Windows/ServiceEventLog.cs @@ -0,0 +1,58 @@ +using System.Runtime.Versioning; +using static Titano.Server.Hosting.Windows.ServiceNative; + +namespace Titano.Server.Hosting.Windows; + +/// +/// Errors of the Windows service in the Application event log (source TitanoServer). A service has no console, +/// and a start-up failure comes before the server's log file exists (the data folder that holds it may be the very +/// thing refused), so Event Viewer is where an operator finds why the service stopped. The source is not registered +/// with a message file: Event Viewer says it found no description for the event, then shows the text whole. +/// +internal static unsafe class ServiceEventLog +{ + public const uint StartFailed = 1; + public const uint StopFailed = 2; + + /// ReportEvent takes at most 31,839 characters per string. + public const int MaxLength = 31_839; + + /// + /// The event text: and the reason the server gave (the entry to check, for a refused data + /// folder), then the exception for a bug report; cut to . + /// + public static string Describe(string what, Exception exception) + { + var text = $"{what} {exception.Message}{Environment.NewLine}{Environment.NewLine}{exception}"; + if (text.Length <= MaxLength) return text; + var cut = MaxLength - 1; + // Never half a surrogate pair. + if (char.IsHighSurrogate(text[cut - 1])) cut--; + return string.Concat(text.AsSpan(0, cut), "…"); + } + + /// Writes an error event; false when the event log could not be written (the console still gets it). + [SupportedOSPlatform("windows")] + public static bool Error(uint eventId, string text) => Error(WindowsServiceHost.ServiceName, eventId, text); + + /// as (tests write as their own source). + [SupportedOSPlatform("windows")] + internal static bool Error(string sourceName, uint eventId, string text) + { + var source = RegisterEventSourceW(null, sourceName); + if (source == 0) return false; + try + { + fixed (char* chars = text.Length <= MaxLength ? text : text[..MaxLength]) + { + var strings = stackalloc char*[1]; + strings[0] = chars; + return ReportEventW(source, EventLogErrorType, 0, eventId, 0, 1, 0, strings, null); + } + } + finally + { + DeregisterEventSource(source); + } + } +} diff --git a/src/Titano.Server/Hosting/Windows/ServiceNative.cs b/src/Titano.Server/Hosting/Windows/ServiceNative.cs index 1b89fd1e..c4e642d3 100644 --- a/src/Titano.Server/Hosting/Windows/ServiceNative.cs +++ b/src/Titano.Server/Hosting/Windows/ServiceNative.cs @@ -3,7 +3,7 @@ using System.Runtime.Versioning; namespace Titano.Server.Hosting.Windows; -/// Service Control Manager functions of advapi32 (no Windows-only package needed). +/// Service Control Manager and event log functions of advapi32 (no Windows-only package needed). [SupportedOSPlatform("windows")] internal static unsafe partial class ServiceNative { @@ -29,6 +29,8 @@ internal static unsafe partial class ServiceNative public const uint ErrorCallNotImplemented = 120; public const uint ErrorExceptionInService = 1064; + public const ushort EventLogErrorType = 0x1; + [StructLayout(LayoutKind.Sequential)] public struct ServiceStatus { @@ -90,4 +92,16 @@ internal static unsafe partial class ServiceNative [LibraryImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static partial bool CloseServiceHandle(nint handle); + + [LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + public static partial nint RegisterEventSourceW(string? uncServerName, string sourceName); + + [LibraryImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool ReportEventW(nint eventLog, ushort type, ushort category, uint eventId, nint userSid, ushort stringCount, uint dataSize, + char** strings, void* rawData); + + [LibraryImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool DeregisterEventSource(nint eventLog); } diff --git a/src/Titano.Server/Hosting/Windows/WindowsServiceHost.cs b/src/Titano.Server/Hosting/Windows/WindowsServiceHost.cs index d08a87e7..b0824520 100644 --- a/src/Titano.Server/Hosting/Windows/WindowsServiceHost.cs +++ b/src/Titano.Server/Hosting/Windows/WindowsServiceHost.cs @@ -9,7 +9,8 @@ namespace Titano.Server.Hosting.Windows; /// /// Runs the server as a Windows service with the SCM API directly (StartServiceCtrlDispatcherW, /// RegisterServiceCtrlHandlerExW, SetServiceStatus). Stop and shutdown requests stop the web host gracefully: running -/// jobs keep their checkpoints and resume at the next start. +/// jobs keep their checkpoints and resume at the next start. A failure to start or stop goes to the Application event +/// log (), since a service has no console. /// [SupportedOSPlatform("windows")] public static class WindowsServiceHost @@ -56,7 +57,9 @@ public static class WindowsServiceHost } catch (Exception ex) { + // A refused data folder or server.json says which entry to check; the SCM itself records only error 1064. Console.Error.WriteLine(ex); + ServiceEventLog.Error(ServiceEventLog.StartFailed, ServiceEventLog.Describe("Titano Server did not start:", ex)); Report(Status.Stopped(ErrorExceptionInService)); } } @@ -96,6 +99,7 @@ public static class WindowsServiceHost catch (Exception ex) { Console.Error.WriteLine(ex); + ServiceEventLog.Error(ServiceEventLog.StopFailed, ServiceEventLog.Describe("Titano Server did not stop cleanly:", ex)); exitCode = ErrorExceptionInService; } Report(Status.Stopped(exitCode)); diff --git a/src/Titano.Setup/Engine/InstallEngine.cs b/src/Titano.Setup/Engine/InstallEngine.cs index ca050ccc..92a8cf52 100644 --- a/src/Titano.Setup/Engine/InstallEngine.cs +++ b/src/Titano.Setup/Engine/InstallEngine.cs @@ -2,6 +2,7 @@ using System.Globalization; using System.IO; using System.Reflection; using Titano.Core.Diagnostics; +using Titano.Core.IO; using Titano.Core.Localization; using Titano.Core.Packaging; using Titano.Setup.Cli; @@ -24,6 +25,10 @@ internal sealed class InstallEngine(PayloadReader payload) { private const double ExtractShare = 0.9; + /// Each sign-in entry and the component (as pack-installer names it) whose program it starts. + private static readonly (string Value, string Component)[] StartupComponents = + [(StartupCommand.ClientValue, "Titano"), (StartupCommand.UploaderValue, "Uploader")]; + public PayloadManifest Manifest => payload.Manifest; /// Bytes the selected components occupy once installed, uninstaller included. @@ -141,10 +146,28 @@ internal sealed class InstallEngine(PayloadReader payload) } /// - /// Removes what the previous version installed and this one no longer does (files, the sign-in entries of those - /// programs, shortcuts, file types). + /// The program each sign-in entry ('s value names) starts once + /// are installed in : the shortcut target of the entry's + /// component, for the components among them that have one. /// - private static void RemoveLeftovers(string directory, InstallLog previous, InstallLog current) + internal static IReadOnlyDictionary StartupPrograms(PayloadManifest manifest, string directory, IEnumerable components) + { + var selected = new HashSet(components, StringComparer.OrdinalIgnoreCase); + var programs = new Dictionary(StringComparer.Ordinal); + foreach (var (value, component) in StartupComponents) + { + if (!selected.Contains(component)) continue; + if (manifest.Shortcuts.FirstOrDefault(s => s.Component.Equals(component, StringComparison.OrdinalIgnoreCase)) is { } shortcut) + programs[value] = PayloadPath.Resolve(directory, shortcut.Target); + } + return programs; + } + + /// + /// Removes what the previous version installed and this one no longer does (files, shortcuts, file types). The + /// sign-in entries of the removed programs move to the program that replaces them, or go with a dropped component. + /// + private void RemoveLeftovers(string directory, InstallLog previous, InstallLog current) { var obsolete = previous.Files.Where(PayloadPath.IsValid).Except(current.Files, PayloadPath.Comparer).ToList(); if (obsolete.Count > 0) @@ -152,12 +175,14 @@ internal sealed class InstallEngine(PayloadReader payload) InstalledFiles.Remove(directory, obsolete); try { - // A dropped Uploader no longer starts at sign-in. - SetupRegistry.DeleteStartupEntries(CommandProgram.FullPaths(directory, obsolete)); + // A renamed program keeps starting at sign-in (without its entry, the new program has nothing to + // follow); a dropped Uploader no longer does. + var programs = StartupPrograms(Manifest, directory, current.Components).Where(p => File.Exists(p.Value)).ToDictionary(StringComparer.Ordinal); + SetupRegistry.MoveStartupEntries(CommandProgram.FullPaths(directory, obsolete), programs); } catch (Exception ex) when (ex is System.Security.SecurityException or UnauthorizedAccessException or IOException) { - Log.Warning("setup", "Sign-in entries not removed", ex); + Log.Warning("setup", "Sign-in entries not updated", ex); } } var links = previous.Shortcuts.Except(current.Shortcuts, StringComparer.OrdinalIgnoreCase).ToList(); diff --git a/src/Titano.Setup/Engine/SetupRegistry.cs b/src/Titano.Setup/Engine/SetupRegistry.cs index 9d1f161d..e1800d36 100644 --- a/src/Titano.Setup/Engine/SetupRegistry.cs +++ b/src/Titano.Setup/Engine/SetupRegistry.cs @@ -28,6 +28,9 @@ internal static partial class SetupRegistry private const string UninstallRoot = @"Software\Microsoft\Windows\CurrentVersion\Uninstall\"; private const string ClassesRoot = @"Software\Classes\"; + /// No replacement program: every matching sign-in entry is removed. + private static readonly IReadOnlyDictionary NoPrograms = new Dictionary(); + private static RegistryKey Hive(InstallScope scope) => scope == InstallScope.AllUsers ? Registry.LocalMachine : Registry.CurrentUser; /// The installation registered under whose folder still exists, current user first. @@ -101,24 +104,47 @@ internal static partial class SetupRegistry /// themselves) that start one of ( of the files an /// installation lists); another copy's entries, and other programs' values, stay. /// - public static void DeleteStartupEntries(IReadOnlySet programs) - { - using var run = Registry.CurrentUser.OpenSubKey(StartupCommand.RunKey, writable: true); - if (run is not null) DeleteStartupEntries(run, programs); - } + public static void DeleteStartupEntries(IReadOnlySet programs) => MoveStartupEntries(programs, NoPrograms); /// in ; returns the names removed. - public static IReadOnlyList DeleteStartupEntries(RegistryKey run, IReadOnlySet programs) + public static IReadOnlyList DeleteStartupEntries(RegistryKey run, IReadOnlySet programs) => MoveStartupEntries(run, programs, NoPrograms); + + /// + /// After an upgrade: a sign-in entry of the client or the Uploader that starts one of + /// (programs the previous version installed and this one does not) starts the program + /// gives for its value name instead, with the same options, when this version installs one (an update renamed or + /// moved it, and the program would find no entry to follow); otherwise it is removed (the component was dropped). + /// + public static void MoveStartupEntries(IReadOnlySet dropped, IReadOnlyDictionary programs) { - var removed = new List(); + using var run = Registry.CurrentUser.OpenSubKey(StartupCommand.RunKey, writable: true); + if (run is not null) MoveStartupEntries(run, dropped, programs); + } + + /// + /// in + /// ; returns the names moved or removed. + /// + public static IReadOnlyList MoveStartupEntries(RegistryKey run, IReadOnlySet dropped, IReadOnlyDictionary programs) + { + var changed = new List(); foreach (var name in (ReadOnlySpan)[StartupCommand.ClientValue, StartupCommand.UploaderValue]) { - if (!CommandProgram.IsAmong(StartupCommand.Executable(run.GetValue(name) as string), programs)) continue; - run.DeleteValue(name, throwOnMissingValue: false); - removed.Add(name); - Titano.Core.Diagnostics.Log.Info("setup", $"Sign-in entry '{name}' removed"); + var command = run.GetValue(name) as string; + if (!CommandProgram.IsAmong(StartupCommand.Executable(command), dropped)) continue; + if (programs.TryGetValue(name, out var program) && StartupCommand.Retarget(command, program) is { } moved) + { + run.SetValue(name, moved, RegistryValueKind.String); + Titano.Core.Diagnostics.Log.Info("setup", $"Sign-in entry '{name}' now starts '{program}'"); + } + else + { + run.DeleteValue(name, throwOnMissingValue: false); + Titano.Core.Diagnostics.Log.Info("setup", $"Sign-in entry '{name}' removed"); + } + changed.Add(name); } - return removed; + return changed; } /// Registers to open with "program" "%1" under . diff --git a/tests/Titano.App.Tests/Archive/ArchiveLanguageTests.cs b/tests/Titano.App.Tests/Archive/ArchiveLanguageTests.cs index 2fbbce94..932f2b92 100644 --- a/tests/Titano.App.Tests/Archive/ArchiveLanguageTests.cs +++ b/tests/Titano.App.Tests/Archive/ArchiveLanguageTests.cs @@ -51,7 +51,7 @@ public sealed class ArchiveLanguageTests { Loc.SetCulture(CultureInfo.GetCultureInfo("he")); Assert.Equal(Loc.L("Tooltips.Archive.YearRowRtl", "2026" + Loc.Separator + year.Detail), year.RowToolTip, "the arrow keys of a mirrored tree"); - Assert.Contains("‏", year.RowToolTip, "right-to-left marks keep the year and its figures apart"); + Assert.Contains("\u200F", year.RowToolTip, "right-to-left marks keep the year and its figures apart"); } finally { diff --git a/tests/Titano.App.Tests/Setup/SetupEngineTests.cs b/tests/Titano.App.Tests/Setup/SetupEngineTests.cs index a51a54cf..385ed7ef 100644 --- a/tests/Titano.App.Tests/Setup/SetupEngineTests.cs +++ b/tests/Titano.App.Tests/Setup/SetupEngineTests.cs @@ -178,6 +178,46 @@ public sealed class SetupEngineTests(TestContext context) } } + [Test] + [WindowsOnly] + public void AnUpgradeMovesTheSignInEntryOfARenamedProgramAndRemovesThatOfADroppedOne() + { + var folder = Path.Combine(context.CreateTempDirectory("upgrade"), "Apps"); + var keyPath = TestsKey + @"\" + Guid.NewGuid().ToString("N"); + // This version ships the client as Titano.exe (the previous one as Titano.old.exe), and the user left out the Uploader. + var manifest = Manifest(); + manifest.Components.Add(new PayloadComponent { Id = "Uploader", DisplayName = "Titano Uploader", DefaultSelected = true }); + manifest.Shortcuts.Add(new PayloadShortcut { Component = "Titano", Name = "Titano", Target = "Titano.exe", StartMenu = true }); + manifest.Shortcuts.Add(new PayloadShortcut { Component = "Uploader", Name = "Titano Uploader", Target = "Titano.Uploader.exe", StartMenu = true }); + var programs = InstallEngine.StartupPrograms(manifest, folder, ["Titano", "Server"]); + Assert.SequenceEqual(["Titano"], programs.Keys); + Assert.Equal(Path.Combine(folder, "Titano.exe"), programs["Titano"]); + try + { + using (var run = Registry.CurrentUser.CreateSubKey(keyPath, writable: true)) + { + run.SetValue("Titano", $"\"{Path.Combine(folder, "Titano.old.exe")}\" --minimized"); + run.SetValue("Titano Uploader", $"\"{Path.Combine(folder, "Titano.Uploader.exe")}\" --tray"); + run.SetValue("Other", $"\"{Path.Combine(folder, "Other.exe")}\" --background"); + + var dropped = CommandProgram.FullPaths(folder, ["Titano.old.exe", "Titano.Uploader.exe", "Other.exe"]); + Assert.SequenceEqual(["Titano", "Titano Uploader"], SetupRegistry.MoveStartupEntries(run, dropped, programs)); + // The new client finds its entry on, with its option; the Uploader no longer starts; other values stay. + Assert.Equal($"\"{Path.Combine(folder, "Titano.exe")}\" --minimized", run.GetValue("Titano")); + Assert.SequenceEqual(["Other", "Titano"], run.GetValueNames().Order(StringComparer.Ordinal)); + // An entry that starts another copy is not this upgrade's to move. + var other = $"\"{Path.Combine(folder + " 2", "Titano.old.exe")}\" --minimized"; + run.SetValue("Titano", other); + Assert.Empty(SetupRegistry.MoveStartupEntries(run, dropped, programs)); + Assert.Equal(other, run.GetValue("Titano")); + } + } + finally + { + DeleteTestKey(keyPath); + } + } + [Test] [WindowsOnly] public void AShortcutTellsWhichProgramItStarts() diff --git a/tests/Titano.Core.Tests/Foundation/StartupCommandTests.cs b/tests/Titano.Core.Tests/Foundation/StartupCommandTests.cs index 6a24ece3..a2908d1b 100644 --- a/tests/Titano.Core.Tests/Foundation/StartupCommandTests.cs +++ b/tests/Titano.Core.Tests/Foundation/StartupCommandTests.cs @@ -3,7 +3,7 @@ using Titano.Testing; namespace Titano.Core.Tests.Foundation; -/// The sign-in entries of the client and the Uploader: which copy they start, and which folder the uninstaller may clean. +/// The sign-in entries of the client and the Uploader: which copy they start, and how setup moves them to a renamed program. public sealed class StartupCommandTests { private const string Installed = @"C:\Users\ada\AppData\Local\Programs\Titano\Titano.exe"; @@ -40,19 +40,22 @@ public sealed class StartupCommandTests } [Test] - public void TheUninstallerRemovesOnlyTheEntriesOfItsFolder() + public void SetupMovesAnEntryToTheRenamedProgramWithItsOption() { - var client = StartupCommand.Format(Installed, "--minimized"); - var uploader = StartupCommand.Format(@"C:\Users\ada\AppData\Local\Programs\Titano\Uploader\Titano.Uploader.exe", "--tray"); - const string folder = @"C:\Users\ada\AppData\Local\Programs\Titano"; - Assert.True(StartupCommand.StartsFrom(client, folder)); - Assert.True(StartupCommand.StartsFrom(client, folder + @"\")); - Assert.True(StartupCommand.StartsFrom(uploader, folder.ToLowerInvariant())); - // A sibling folder that shares the name's start, another drive, or nothing at all stay. - Assert.False(StartupCommand.StartsFrom(StartupCommand.Format(@"C:\Users\ada\AppData\Local\Programs\Titano2\Titano.exe", "--minimized"), folder)); - Assert.False(StartupCommand.StartsFrom(StartupCommand.Format(@"E:\Titano\Titano.exe", "--minimized"), folder)); - Assert.False(StartupCommand.StartsFrom(StartupCommand.Format(folder, "--minimized"), folder)); - Assert.False(StartupCommand.StartsFrom(null, folder)); - Assert.False(StartupCommand.StartsFrom(client, @"\")); + // Setup matches an entry by the program it starts (one its install log lists, never any program under the + // folder) and, when an update renamed that program, points the entry at the new one. + const string renamed = @"C:\Users\ada\AppData\Local\Programs\Titano\Titano.old.exe"; + var moved = StartupCommand.Retarget(StartupCommand.Format(renamed, "--minimized"), Installed); + Assert.Equal(StartupCommand.Format(Installed, "--minimized"), moved); + Assert.True(StartupCommand.Starts(moved, Installed)); + // Written by hand or by an older tool: unquoted, without an option, or with more than one. + Assert.Equal(StartupCommand.Format(Installed, "--tray"), StartupCommand.Retarget(@" D:\Titano\Titano.Uploader.exe --tray ", Installed)); + Assert.Equal("\"" + Installed + "\"", StartupCommand.Retarget(@"D:\Titano\Titano.exe", Installed)); + Assert.Equal("\"" + Installed + "\"", StartupCommand.Retarget("\"" + renamed + "\"", Installed)); + Assert.Equal(StartupCommand.Format(Installed, "--minimized --verbose"), StartupCommand.Retarget("\"" + renamed + "\" --minimized --verbose", Installed)); + // Nothing to move. + Assert.Null(StartupCommand.Retarget(null, Installed)); + Assert.Null(StartupCommand.Retarget(" ", Installed)); + Assert.Null(StartupCommand.Retarget("\"unterminated --minimized", Installed)); } } diff --git a/tests/Titano.Server.Tests/Hosting/WindowsServiceTests.cs b/tests/Titano.Server.Tests/Hosting/WindowsServiceTests.cs index 2d624ec0..70317aeb 100644 --- a/tests/Titano.Server.Tests/Hosting/WindowsServiceTests.cs +++ b/tests/Titano.Server.Tests/Hosting/WindowsServiceTests.cs @@ -1,3 +1,4 @@ +using System.Diagnostics.Eventing.Reader; using System.Security.AccessControl; using System.Security.Principal; using Titano.Server.Hosting; @@ -41,6 +42,54 @@ public sealed class WindowsServiceTests(TestContext context) Assert.Equal(1064u, new ServiceStatusTracker().Stopped(1064).ExitCode); } + [Test] + public void AServiceFailureLeadsWithTheReasonTheServerGave() + { + var refused = new InvalidOperationException(@"C:\ProgramData\Titano Server belongs to PC\ada, not to SYSTEM, Administrators or the account Titano Server runs as."); + var text = ServiceEventLog.Describe("Titano Server did not start:", refused); + Assert.True(text.StartsWith(@"Titano Server did not start: C:\ProgramData\Titano Server belongs to PC\ada", StringComparison.Ordinal), text); + Assert.Contains("System.InvalidOperationException", text); + + // ReportEvent refuses a longer string: the text is cut, never between the halves of a surrogate pair. + var cut = ServiceEventLog.Describe("x", new InvalidOperationException(new string('a', ServiceEventLog.MaxLength))); + Assert.Equal(ServiceEventLog.MaxLength, cut.Length); + Assert.True(cut.EndsWith("a\u2026", StringComparison.Ordinal), cut[^5..]); + var pair = ServiceEventLog.Describe("x", new InvalidOperationException(new string('a', ServiceEventLog.MaxLength - 4) + "\uD83D\uDE00" + new string('b', 99))); + Assert.Equal(ServiceEventLog.MaxLength - 1, pair.Length); + Assert.True(pair.EndsWith("a\u2026", StringComparison.Ordinal), pair[^5..]); + } + + [Test] + [WindowsOnly] + public void AServiceFailureReachesTheApplicationEventLog() + { + if (!OperatingSystem.IsWindows()) return; + // Written as a source of its own, so a test run never looks like a failed service in Event Viewer. + const string source = "Titano.Server.Tests"; + var marker = source + " " + Guid.NewGuid().ToString("N"); + Assert.True(ServiceEventLog.Error(source, ServiceEventLog.StartFailed, marker), "the Application log takes the event"); + var filter = $"*[System[Provider[@Name='{source}'] and EventID={ServiceEventLog.StartFailed}]]"; + var query = new EventLogQuery("Application", PathType.LogName, filter) { ReverseDirection = true }; + for (var attempt = 0; attempt < 50; attempt++) + { + using (var reader = new EventLogReader(query)) + { + for (var read = 0; read < 100 && reader.ReadEvent() is { } record; read++) + { + using (record) + { + // The event's one string, which Event Viewer shows whole. + if (record.Properties.Count != 1 || record.Properties[0].Value as string != marker) continue; + Assert.Equal((byte?)2, record.Level, "an error"); + return; + } + } + } + Thread.Sleep(100); + } + Assert.Fail($"No {source} event carries '{marker}'."); + } + [Test] [WindowsOnly] public void TheServiceIsRegisteredOnlyFromInsideProgramFiles()