From 464c93e8f44ceaba5327496f8f885c0e618d1661 Mon Sep 17 00:00:00 2001 From: Hermenix Date: Mon, 28 Sep 2026 05:20:16 +0000 Subject: [PATCH] module: wire up the headless session and the frame server Implements the `config` side of the module surface in docs/CONTRACT.md: - `hhstream` user/group, and one private runtime directory shared by both units (RuntimeDirectory= with Preserve=yes, so the Wayland socket survives a restart of either side). - A rendered hyprland.conf (nix/hyprland-conf.nix): one `monitor =` line per `outputs` entry plus `extraConfig` verbatim, with the logo/splash, config autoreload, DPMS, cursor, animations, shadows and the update/donation and guiutils/XDG checks switched off -- none of them mean anything in a session with no seat, no input device and no user. Validated with `Hyprland --verify-config`. - `hyprland-headless.service`: Hyprland as the service user, Type=notify (it sends READY=1), Restart=always, and deliberately no WAYLAND_DISPLAY or DISPLAY in the environment so the compositor cannot pick a nested backend and falls back to headless. - `hyprland-headless-stream.service`: hhstream-server as the same user, After=/BindsTo= the compositor, Restart=always, with --socket/--fps/ --format/--capture-command on the command line. `outputs.*.scale` used `lib.types.positive`, which does not exist in nixpkgs and made the whole `outputs` option unreadable; it is now `lib.types.numbers.positive`. `package` gets its documented default (the flake's own build) via mkDefault on the config side, so the declared option surface is otherwise untouched. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_015pS3JxTJZBufyBKwimwBxy --- nix/hyprland-conf.nix | 94 ++++++++++++++++ nix/module.nix | 241 +++++++++++++++++++++++++++++++++++++++--- 2 files changed, 318 insertions(+), 17 deletions(-) create mode 100644 nix/hyprland-conf.nix diff --git a/nix/hyprland-conf.nix b/nix/hyprland-conf.nix new file mode 100644 index 0000000..f74fb48 --- /dev/null +++ b/nix/hyprland-conf.nix @@ -0,0 +1,94 @@ +# The hyprland.conf for a session nobody sits in front of. +# +# Split out of module.nix so the rendering is readable on its own (and diffable +# when an output list changes). Returns the file *text*; the caller puts it in +# the store. +{ + lib, + outputs, + extraConfig, +}: let + # `monitor = , x@, auto, ` -- "auto" + # lets the compositor lay the virtual outputs out left to right. + monitorLine = o: "monitor = ${o.name}, ${toString o.width}x${toString o.height}@${toString o.refresh}, auto, ${toString o.scale}"; +in '' + # Generated by services.hyprland-headless-stream. Do not edit. + # + # There is no seat, no libinput device, no cursor and no human here: the only + # consumer of this session is the frame server. Everything below either + # creates the virtual outputs or switches off something that assumes a user. + + ${lib.concatMapStringsSep "\n" monitorLine outputs} + + misc { + # Nothing should draw itself over the captured output. + disable_hyprland_logo = true + disable_splash_rendering = true + force_default_wallpaper = 0 + background_color = 0x000000 + + # The config lives in the store and never changes under us; watching it + # would only cost inotify watches on a read-only path. + disable_autoreload = true + + # A virtual output has no variable refresh rate to negotiate. + vrr = 0 + + # DPMS on a virtual output is meaningless, and there is no key or pointer + # event coming to wake it back up. + key_press_enables_dpms = false + mouse_move_enables_dpms = false + + # Both of these check for a desktop that is not here: the Qt helper + # dialogs, and the XDG portal environment. + disable_hyprland_guiutils_check = true + disable_xdg_env_checks = true + } + + debug { + # Capture wants a steady frame rate. With variable frame rate the + # compositor only renders on damage, so an idle session would starve the + # stream. + vfr = false + + # The session is a systemd unit: its log belongs in the journal, not in a + # file under a runtime directory nobody will look in. + enable_stdout_logs = true + colored_stdout_logs = false + } + + cursor { + # No hardware planes, no cursor theme on disk, nobody to warp. + invisible = true + no_hardware_cursors = true + enable_hyprcursor = false + no_warps = true + hide_on_key_press = false + inactive_timeout = 0 + } + + input { + # No pointer will ever exist; do not let focus depend on one. + follow_mouse = 0 + } + + # Frames cost capture bandwidth and CPU, and no one is watching the easing. + animations { + enabled = false + } + + decoration { + blur { + enabled = false + } + shadow { + enabled = false + } + } + + # Nothing here may reach the network or nag a user who is not there. + ecosystem { + no_update_news = true + no_donation_nag = true + } + ${lib.optionalString (extraConfig != "") "\n${extraConfig}"}'' diff --git a/nix/module.nix b/nix/module.nix index fde036c..ffb6296 100644 --- a/nix/module.nix +++ b/nix/module.nix @@ -1,10 +1,104 @@ -{ lib, config, pkgs, ... }: - -# Interface only: every option in docs/CONTRACT.md is declared here so tests and -# consumers can be written against a stable surface. The systemd wiring is the -# next piece of work (see docs/CONTRACT.md -> "Services"). +{ + lib, + config, + pkgs, + ... +}: +# The option surface below is the interface described in docs/CONTRACT.md +# ("NixOS module surface"); the `config` block wires it to the two services +# named there. let cfg = config.services.hyprland-headless-stream; + + # One private runtime directory, shared by both units: it holds the Wayland + # socket of the session and, by default, the published frame socket too. + # `RuntimeDirectoryPreserve` keeps it (and the Wayland socket) alive across a + # restart of either unit. + runtimeDirName = "hyprland-headless-stream"; + runtimeDir = "/run/${runtimeDirName}"; + + socketDir = builtins.dirOf cfg.socketPath; + + # Hyprland refuses `--socket` unless it is paired with `--wayland-fd` (that + # pair is the socket-handover path), so the name is not ours to choose: the + # compositor calls wl_display_add_socket_auto, which takes the first free + # `wayland-N` starting at 0. The runtime directory is private to this + # session, so that is always `wayland-0`. + waylandDisplay = "wayland-0"; + + hyprlandConf = pkgs.writeText "hyprland.conf" (import ./hyprland-conf.nix { + inherit lib; + inherit (cfg) outputs extraConfig; + }); + + # `BindsTo=` already stops the frame server when the compositor goes away, + # but the compositor is only *ready* once its Wayland socket is bound. The + # compositor unit is `Type=notify`, so this is a second line of defence for + # compositor builds that do not sd_notify. + waitForSession = pkgs.writeShellScript "hhstream-wait-for-session" '' + socket="$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY" + for _ in $(${lib.getExe' pkgs.coreutils "seq"} 1 300); do + if [ -S "$socket" ]; then + exit 0 + fi + ${lib.getExe' pkgs.coreutils "sleep"} 0.1 + done + echo "no Wayland socket at $socket after 30s; is the compositor up?" >&2 + exit 1 + ''; + + serverArgs = + [ + "--socket" + cfg.socketPath + "--fps" + (toString cfg.frameRate) + "--format" + cfg.format + ] + # One occurrence per argv word. The capture command is a list whose words + # start with `-` (`grim -t png -`), and repeating the flag is the only + # shape that survives that without inventing a quoting convention. + # `hhstream.server.build_parser()` is still a stub, so this is the one + # place the module guesses at the server's CLI rather than reading it. + ++ lib.concatMap (word: ["--capture-command" word]) cfg.captureCommand; + + # Shared by both units: a private session, no parent display to nest in. + sessionEnvironment = { + XDG_RUNTIME_DIR = runtimeDir; + HOME = runtimeDir; + XDG_SESSION_TYPE = "wayland"; + }; + + commonServiceConfig = { + User = cfg.user; + Group = cfg.group; + + RuntimeDirectory = runtimeDirName; + RuntimeDirectoryMode = "0750"; + RuntimeDirectoryPreserve = "yes"; + WorkingDirectory = runtimeDir; + + # docs/CONTRACT.md: the socket is owned by the service user, mode 0660. + UMask = "0007"; + + Restart = "always"; + RestartSec = 2; + + # A GPU render node is the one piece of hardware a headless session still + # needs; everything else is virtual. + SupplementaryGroups = ["video" "render"]; + + NoNewPrivileges = true; + PrivateTmp = true; + ProtectHome = true; + ProtectSystem = "strict"; + ProtectControlGroups = true; + ProtectKernelTunables = true; + ProtectKernelModules = true; + RestrictSUIDSGID = true; + ReadWritePaths = lib.optional (socketDir != runtimeDir) socketDir; + }; in { options.services.hyprland-headless-stream = { enable = lib.mkEnableOption "a headless Hyprland session streamed to a Unix socket"; @@ -34,7 +128,7 @@ in { }; format = lib.mkOption { - type = lib.types.enum [ "png" "jpeg" ]; + type = lib.types.enum ["png" "jpeg"]; default = "png"; description = "Frame encoding."; }; @@ -42,14 +136,37 @@ in { outputs = lib.mkOption { type = lib.types.listOf (lib.types.submodule { options = { - name = lib.mkOption { type = lib.types.str; }; - width = lib.mkOption { type = lib.types.ints.positive; default = 1280; }; - height = lib.mkOption { type = lib.types.ints.positive; default = 720; }; - refresh = lib.mkOption { type = lib.types.ints.positive; default = 30; }; - scale = lib.mkOption { type = lib.types.positive; default = 1.0; }; + name = lib.mkOption {type = lib.types.str;}; + width = lib.mkOption { + type = lib.types.ints.positive; + default = 1280; + }; + height = lib.mkOption { + type = lib.types.ints.positive; + default = 720; + }; + refresh = lib.mkOption { + type = lib.types.ints.positive; + default = 30; + }; + # Was `lib.types.positive`, which does not exist in nixpkgs and made + # `outputs` unreadable; `numbers.positive` is the int-or-float type + # that name meant. + scale = lib.mkOption { + type = lib.types.numbers.positive; + default = 1.0; + }; }; }); - default = [ { name = "HEADLESS-1"; width = 1280; height = 720; refresh = 30; scale = 1.0; } ]; + default = [ + { + name = "HEADLESS-1"; + width = 1280; + height = 720; + refresh = 30; + scale = 1.0; + } + ]; description = "Virtual monitors the compositor should create."; }; @@ -73,19 +190,109 @@ in { captureCommand = lib.mkOption { type = lib.types.listOf lib.types.str; - default = [ "grim" "-t" "png" "-" ]; + default = ["grim" "-t" "png" "-"]; description = "Command that writes one frame to stdout; overridable for tests."; }; }; config = lib.mkIf cfg.enable { - # TODO(module): user/group, runtime dir, hyprland.conf rendering, the two - # systemd units named in docs/CONTRACT.md. assertions = [ { - assertion = cfg.outputs != [ ]; + assertion = cfg.outputs != []; message = "services.hyprland-headless-stream.outputs must not be empty."; } + { + assertion = lib.hasPrefix "/" cfg.socketPath; + message = "services.hyprland-headless-stream.socketPath must be an absolute path."; + } ]; + + # The flake's own build, as docs/CONTRACT.md says; `mkDefault` so a + # consumer (or the test harness) can still point this at its own package. + services.hyprland-headless-stream.package = + lib.mkDefault (pkgs.callPackage ./package.nix {}); + + users.users.${cfg.user} = { + isSystemUser = true; + group = cfg.group; + description = "Headless Hyprland stream session"; + }; + users.groups.${cfg.group} = {}; + + # Only needed when the socket was moved out of the runtime directory that + # `RuntimeDirectory=` already creates for us. + systemd.tmpfiles.settings = lib.mkIf (socketDir != runtimeDir) { + "10-hyprland-headless-stream".${socketDir}.d = { + user = cfg.user; + group = cfg.group; + mode = "0750"; + }; + }; + + systemd.services.hyprland-headless = { + description = "Headless Hyprland session"; + documentation = ["file://${hyprlandConf}"]; + wantedBy = ["multi-user.target"]; + + # No WAYLAND_DISPLAY and no DISPLAY here on purpose: with either set the + # compositor would pick its nested backend and try to connect to a parent + # session. With no seat and no DRM device it falls back to headless, + # which is exactly what the virtual outputs in hyprland.conf want. + environment = + sessionEnvironment + // { + # We are a system service: there is no user bus and no user manager to + # import the session environment into. + HYPRLAND_NO_SD_VARS = "1"; + HYPRLAND_NO_CRASHREPORTER = "1"; + # Ignored by aquamarine-era Hyprland, honoured by wlroots-era builds + # someone may pin in `hyprlandPackage`. + WLR_BACKENDS = "headless"; + WLR_LIBINPUT_NO_DEVICES = "1"; + WLR_RENDERER_ALLOW_SOFTWARE = "1"; + }; + + serviceConfig = + commonServiceConfig + // { + # Hyprland sends READY=1 once the session is up, so the frame server's + # `After=` is an ordering on readiness, not just on fork. + Type = "notify"; + NotifyAccess = "all"; + TimeoutStartSec = 60; + ExecStart = lib.escapeShellArgs [ + (lib.getExe cfg.hyprlandPackage) + "--config" + "${hyprlandConf}" + ]; + }; + }; + + systemd.services.hyprland-headless-stream = { + description = "Frame server for the headless Hyprland session"; + wantedBy = ["multi-user.target"]; + after = ["hyprland-headless.service"]; + bindsTo = ["hyprland-headless.service"]; + + # `captureCommand` defaults to an unqualified `grim`. + path = [pkgs.grim]; + + environment = + sessionEnvironment + // { + WAYLAND_DISPLAY = waylandDisplay; + PYTHONUNBUFFERED = "1"; + }; + + serviceConfig = + commonServiceConfig + // { + Type = "simple"; + ExecStartPre = "${waitForSession}"; + ExecStart = lib.escapeShellArgs ( + [(lib.getExe' cfg.package "hhstream-server")] ++ serverArgs + ); + }; + }; }; -} \ No newline at end of file +}