eggup-service
Manager-neutral service-registration, ownership, state, and lifecycle-snapshot model plus reusable Unix manager mechanics (systemd, launchd, user crontab) and a native Windows SCM adapter.
ServiceId/ServiceSpecidentify desired registrations with exact executable, arguments, and config evidence.Ownership::{Absent, Owned, Foreign, Unknown}iseggup_core::Ownership: the service crate re-exports the canonical type rather than defining its own, so the two crates denote one type and no conversion exists.Ownership::Ownedis never inferred — it is returned only by a caller-proven ownership check. Destructive manager operations are authorized only forOwned;ForeignandUnknownfail closed.CronOwnershipis a public type alias of the same canonical type.LifecycleState::{Stopped, Running, Transitioning, Unknown}is distinct from application health (HealthState::{Healthy, Degraded, Unknown}).LifecycleSnapshotpreserves pre-update intent (was_running,was_registered) so orchestration can restore "was running" versus "was registered but stopped". Stopped services remain stopped by default.ServiceManagertrait plusTestDoubleManagerfor deterministic tests;HealthProbeseam is consumer-supplied and never mutates manager state.WindowsScmManageruses the safewindows-serviceSCM wrapper on Windows and a Windows command-line parser for exact executable/argument ownership. Service key name alone never authorizes a mutation; ambiguous registrations areUnknownand foreign registrations are denied.WindowsScmInstallsupplies caller-owned display/start/error settings. Creation never starts the service. Optional caller-supplied service or load-order-group dependencies are supported. Refresh preserves service type, unspecified dependencies, account, load-order group, and tag fields outside the adapter's ownership. Account selection is create-time only; custom passwords, descriptions, and recovery actions are not supported by this generic adapter.- Windows start/stop/restart polling shares one monotonic deadline per transition. Uninstall reports incomplete while SCM still exposes a marked-for-delete entry and completes only after confirmed absence. Access denial returns bounded remediation and never starts an elevation flow.
- The native Windows SCM adapter returns typed errors on every path. The
SCM's "the service does not exist" (
1060) and "the service is marked for deletion" (1072) codes keep their exact meanings —Absent,MarkedForDelete, and the "the service disappeared before the operation" conflict — and every other SCM code becomes aServiceError::Managerthat still carries the raw OS code. No SCM condition panics, and no new error variant or taxonomy was added: the codes are surfaced through the existingServiceError::Manager/ServiceError::Conflictconstructors and the existingManagerFailureKindset. - The native Windows SCM backend is exercised against the real Service
Control Manager by a Windows-only fixture (
tests/windows_scm_live.rs): it registers a disposable service through the crate's public API and drives install → inspect → ownership → start → stop → uninstall, asserting thewindows-servicemapping layer explicitly. It removes its own registrations on every exit path, never touches a pre-existing service, waits only under explicit deadlines, and skips with a recorded reason when the runner lacks the administrator rights a real registration needs. windows-serviceis a Windows-target dependency.windows-argsis the small cross-platform parser dependency used for the same ownership tests on Unix.- Bounded
TransitionResultwith conflict diagnostics; no automatic privilege elevation; no updater/release/network policy. - Crate-produced service errors and manager stderr excerpts share one
declared ceiling,
MAX_DIAGNOSTIC_BYTES(512 bytes), truncated only at UTF-8 character boundaries. ServiceError::Manageris a struct variant: it carries a machine-readableManagerFailureKind(Spawn | Timeout | Permission | NotFound | Protocol | LocalFilesystem), the bounded diagnostic detail, and the platform OS code when the platform supplied a structured one. The kind — not the text — is the carrier of meaning:ServiceError::manager_kind()andServiceError::manager_os_code()are the programmatic discriminators, and no adapter or helper classifies a failure by substring-matching its own error text. The classification is decided by two pure mapping functions (ManagerFailureKind::from_spawn_error,ManagerFailureKind::from_scm_os_code), so it is assertable on every lane without a real privilege failure, a real spawn, or a wall-clock sleep.- Every adapter creates exactly one
OperationDeadlineper public operation and threads it through every manager invocation that operation makes. No invocation is granted a fresh full budget: the single initial clamp happens at deadline construction and each call receives the remaining budget.start/stop/restartuse the caller-suppliedtimeout;install/uninstall/inspectuse the descriptor'stransition_timeoutfor the whole operation. - Cron has one ownership rule, stated once and used by
inspect,install, anduninstallalike: ownership is decided only bycron_classify, i.e. exact content identity of the managed block body.inspectlists the crontab exactly once, and the pre-write re-listing before a destructive write is retained. An executable-containment gate applies before any listing or mutation: the caller's managed block body must containspec.executable(), otherwise every cron operation refuses withServiceError::InvalidInput. commit_with_lifecycleandcommit_with_dispositionare two orchestrators over one commit-and-rollback engine (commit_engine). The transition, rollback-quiesce, panic-safe-inspect, panic-safe-restore, deadline, and detail-truncation mechanics have a single implementation, and both orchestrators reach it. A desired lifecycle state outside{Running, Stopped}is a typed, bounded failure, never a panic.- The two behavioural inputs that used to differ between the former engine
copies are named, separately testable policy inputs on
CommitEnginePolicy:PostTransitionVerification::Verify(default) re-inspects the manager and validates the observed ownership and state after every transition — a manager's owncompletedflag is a self-report, not evidence;TrustManagerReportis the explicitly selected non-default input.OwnershipLossTolerance::Deny(default) makes an ownership that is no longerOwneda typed failure;TolerateAlreadyStoppedis the explicitly selected non-default input. The selected policy is observable in the returned receipt'sengine_policyfield.
commit_with_lifecyclecomposes an already validatedeggup_coretransaction with owned-service quiescence, successful-update restoration, a bounded caller-ownedPostInstallCheck, and Core'sKeepInstalled/RollBackpolicy. It requires an existingOwnedregistration inRunningorStoppedstate; it never installs or refreshes the registration.commit_with_disposition(M006) generalizes orchestration with a product-neutralUpdateRuntimeDisposition::{ManagedRunning, ManagedStopped, DirectRunning, Stopped, ForeignPreserved}. Artifact commit authority and manager mutation authority are separate facts:ForeignPreservedperforms zero manager mutation,DirectRunninguses only the caller-ownedDirectRuntimeControlseam (exact instance/config, bounded deadlines, no health-protocol content), andStoppedfabricates no restart. Pureplan_unix/plan_windowsplanners reproduce the reference decision matrix without native managers. The disposition observed after preparation is revalidated immediately before mutation; owned-to-foreign/unknown or direct-identity changes fail before destructive action with zero further mutation.- With
RestoreIntent::Preserve, a stopped service stays stopped after success.RestoreIntentonly controls the successful new generation; after a successful artifact rollback, orchestration restores the pre-update running/stopped state. If Core reportsRecoveryRequired, it does not automatically start the service against uncertain artifacts. - The post-install check receives the remaining shared deadline and must
finish within it. Existing
HealthProbehas no timeout contract and alone does not meet this bound. Application health semantics remain caller-owned. - M003 hardening: each start/stop/restart validates one monotonic caller deadline shared by ownership queries, manager commands, and state polling. Zero transition timeouts are rejected; expiry is returned as an incomplete transition or a manager timeout.
- Production
SystemExecutorresolvessystemctl,launchctl, andcrontabonly from fixed absolute platform paths, never ambientPATH. It clears the child environment; only user-scoped systemd retainsDBUS_SESSION_BUS_ADDRESS,XDG_RUNTIME_DIR, andSYSTEMD_BUS_ADDRESSwhen present. ManagerCommandOutputis the bounded output of one manager command invocation. The formerCommandOutputspelling survives as a type alias to it, so existingCommandExecutorimplementations written against either spelling still satisfy the trait. The alias is deliberately not deprecated; its disposition is settled at the intentional 0.2/1.0 API boundary.- systemd/launchd config ownership is proven by one exact config path occurrence
in canonical argv. Missing identity is
Foreign; repeated/ambiguous identity isUnknown. - M002 Unix adapters (
SystemdManager,LaunchdManager,CronManager) implementServiceManageron top of the M001 contract:- shared bounded command runner (literal argv, no shell, null/controlled
stdin, bounded output, deadline with kill/reap, injectable
FakeExecutorfor tests); the bounded execution itself is delegated toeggup_core::run_bounded, while this crate's own pre-flight — the allowlisted absolute program path, the cleared environment, the bounded stdin payload, and the timeout range — stays in front of that call and is unchanged; - systemd: explicit
--system/--userscope, narrowExecStartparsing (ambiguous/specifier shapes yieldUnknown), atomic definition writes, explicitenable/daemon-reloadonly, boundedstart/stop/restartwith state confirmation, nosudo; a recognized exact-ownedfailedunit is stopped only after ownership revalidation and proof that its manager job, main/control processes, and cgroup work are gone; - launchd: explicit
gui/<uid>vssystemtargets (never guessed), structuredProgramArgumentsparsing (malformed yieldsUnknown), label-only never proves ownership, boundedbootstrap/bootout/kickstart/stop, foreign labels fail closed; - cron: managed
# BEGIN/# END <marker>block (caller-owned marker + exact block), purecron_merge/cron_removepreserving unrelated bytes, idempotent install, owned-only removal, no redundantcrontab -writes, re-read before destructive writes to expose races, explicit "no start/stop semantics" errors, one listing perinspect, one ownership rule, and the executable-containment gate on the destructive paths; atomic_write_definition(same-dir exclusive temp, owner-safe mode,fsync, no-replace vs overwrite authority, owned-temp-only cleanup, never creates privileged parents);inspect_hostfacts vscandidate_managerspolicy (Linux systemd or cron; macOS launchd or cron; detection failure distinct from absent).
- shared bounded command runner (literal argv, no shell, null/controlled
stdin, bounded output, deadline with kill/reap, injectable
- Ownership for systemd/launchd uses exact executable plus critical args and reconciles optional config identity against those exact args. Consumer unit/plist bodies, usernames, paths, hardening text, health checks, and CLI messages stay consumer-owned. No consumer is migrated here.
- The crate's public API surface is guarded locally. Every public item is
bound to an explicit type in
tests/public_api_surface.rs, so a removed item or a changed signature is a compilation error in the crate's own test gate. The committed snapshottests/public-api-surface.txtis the reviewable artifact: it is maintained by hand, and a change to it, or to the guard, is a deliberate, separately reviewed edit. The guard adds no dependency and changes no public API.