Files
zag/README.md
T
Daniel SamsonandClaude Sonnet 5.5 f4e15aa32d
CI / test (push) Failing after 11s
Drop Windows support: clear build error, docs updated
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-17 14:48:57 +01:00

11 KiB

Zag Job Daemon (Cross-Platform)

Zag is the Zig port of barn, the Java job daemon. It keeps barn's CLI, JSON/XML output and job directory layout so clients can switch by changing the binary name, and fixes the places where barn's behaviour did not match its documentation (see Migration from barn).

A cross-platform (Linux and macOS) service for managing long-running jobs that involve downloading and uploading media via WebDAV, using FFmpeg to analyse and transcode video, with strong guarantees around durability, observability, and crash recovery.

This project is designed to run as a real OS service / daemon on:

  • macOS (launchd)
  • Linux (systemd)

Windows is not supported.

The daemon is not HTTP-bound. It runs independently in the background and exposes control via a local CLI / RPC interface.


Why This Exists

Running FFmpeg jobs over SSH or ad-hoc scripts quickly breaks down when you need:

  • Multiple concurrent jobs
  • Reliable handling of failures
  • Recovery after crashes or restarts
  • Cross-platform support
  • Programmatic job inspection and control

This project treats FFmpeg jobs as first-class managed units of work, not shell commands.

Why Zig

Barn needs a JVM on every host that runs it. Zag aims to keep the same behaviour as a single small, statically linked native binary, with no runtime to install, fast startup, a low idle memory footprint, and easy cross-compilation to every supported platform.


Core Goals

  • Run FFmpeg jobs reliably in the background
  • Survive SSH disconnects, restarts, and crashes
  • Explicitly model job state and failure reasons
  • Provide durable, inspectable job state
  • Work consistently on Linux and macOS
  • Avoid coupling to HTTP or web frameworks
  • Stay drop-in compatible with barn's CLI, JSON/XML output, and job directory layout

Installation

Linux / macOS

The installer downloads the latest release, installs the binary and registers a service (systemd on Linux, launchd on macOS):

curl -fsSL https://gitea.samson.media/samson-media/zag/raw/branch/main/install.sh | sh

ZAG_VERSION, ZAG_PREFIX and ZAG_NO_SERVICE=1 tune the install; see the header of install.sh.

Homebrew

brew tap samson-media/tap https://gitea.samson.media/samson-media/homebrew-tap
brew install zag
brew services start zag

Manual

Download zag-linux-x64, zag-linux-arm64, zag-macos-arm64 or zag-macos-x64 from the releases page, check it against SHA256SUMS, and put it on your PATH:

chmod +x zag-linux-x64 && sudo mv zag-linux-x64 /usr/local/bin/zag
zag --version

The binaries are static and need no runtime. Windows is not supported and there are no plans to add it.

Setting up the service

sudo zag service install     # system-wide (as root); without sudo it installs for your user
zag service start
zag service status

Once installed, zag service start|stop|restart go through systemd/launchd. Without installing, zag service start runs a detached daemon of its own.

Building

Requires Zig 0.16.0 or newer. Linux builds default to musl (a static binary).

zig build                          # build to zig-out/bin/zag
zig build test                     # unit tests
zig build e2e                      # end-to-end smoke test against the built binary
zig build -Doptimize=ReleaseSafe -Dstrip=true   # release build (~1 MB)

Cross-compile with -Dtarget, for example:

zig build -Doptimize=ReleaseSafe -Dtarget=aarch64-macos
zig build -Doptimize=ReleaseSafe -Dtarget=x86_64-windows
zig build -Doptimize=ReleaseSafe -Dtarget=aarch64-linux

Global options

Option Description
-o, --output {human|json|xml} Output format (default human)
--config <file> Configuration file to merge on top of the system and user files
--offline Run without the service: same code, in this process (zag run --offline executes the job and prints its final state)
--barn-dir <dir> Data directory, overriding storage.base_dir (also relocates the socket)

Zag command

This project creates a simple CLI commandlet with sub-commands.

  • zag service {start|stop|restart|reload|status|logs|install|uninstall} - manages the zag service
  • zag run {command} - starts job
  • zag status - gets the status of all jobs running
  • zag describe {jobId} - collects all the info from /tmp and display it
  • zag usage {jobId} - shows resource usage (CPU, memory, disk, GPU) for a job
  • zag kill {jobId} - kills a job
  • zag clean - performs clean up
  • zag config install - installs default configuration files
  • zag config show - shows effective configuration
  • zag config validate --file <path> - checks a configuration file
  • zag config init - writes a default user configuration file
  • zag autocompletion {--bash|--zsh} - prints a shell completion script

zag is just one binary for both the service and the client. The client uses IPC to communicate with the service.

Clients typically access zag over ssh:

  • fetch from webdav server: zag run --output=json curl -u username:password -o /tmp/zag/input/video.mp4 https://example.com/dav/remote-file.ext
  • analyse file with ffmpeg: zag run --output=json ffprobe -i /tmp/zag/input/video.mp4
  • get status of the jobs zag status --output=json

zag's output defaults to a human-readable format, but also supports xml or json via the --output={json|xml} cli option.

Managing the service

There needs to be a zag service in order to run jobs (unless you use --offline). You manage the service using the zag service sub command.

  • zag service status - check the status of the service. up/down, process id etc.
  • zag service start - starts zag service process
  • zag service stop - stops/kills the zag service
  • zag service restart - restarts the zag service
  • zag service reload - reloads the configuration and soft restarts the zag service

Adding jobs

zag run --output=json --tag=downloading <cmd> takes in a command to run, starts a new process/thread, outputs the status of that job:

Field Description
job_id the id of the job
state queued, running, succeeded, failed, canceled
load_level HIGH, MEDIUM, or LOW (auto-detected or manual)
tag user defined string
created_at Job creation timestamp
started_at Execution start timestamp
finished_at Execution end timestamp
exit_code '-' if still running, 0 or symbolic error code
error Human-readable failure reason
pid OS process ID (best-effort)
heartbeat Last liveness update
retryCount Current retry attempt (0 if never retried)
retryAt Timestamp for next retry attempt (null if not retrying)

Users can tag jobs for the purpose of filtering using the --tag=string CLI option.

Jobs are automatically assigned a load level based on the command being run (see Load Levels). You can override this with --load-level={high|medium|low}.

Developers can use the --offline command line option to test how the service behaves (e.g., creating tmp files). This runs the same code as the service but without having to run the service.

Get status of jobs

zag status gets the status of all jobs found in /tmp.

ID            STATE      LOAD    TAG  CREATED              EXIT  PID       RETRIES  NEXT RETRY
job-6d368040  succeeded  medium  -    2026-01-22 01:48:46  0     17486     -        -

Total: 1 job (1 succeeded)

Get details of a job

zag describe {jobId} - collects all the info from /tmp and display it

Stop a job

zag kill {jobId} - kills a job process

Clean up jobs

zag clean - removes completed jobs and cleans up old jobs (older than max_age config) from /tmp


Load Levels

Zag supports per-level job limits to allow concurrent execution of different types of jobs. For example, you can run multiple downloads while transcoding without overwhelming the system.

Load Level Types

Level Default Max Use Case
HIGH 2 CPU/GPU intensive (transcoding, encoding)
MEDIUM 8 General purpose commands
LOW 32 Network/IO intensive (downloads, uploads)

Auto-Classification

Jobs are automatically classified based on whitelist files in /etc/zag/:

  • high.load - ffmpeg, ffprobe, handbrake, x264, x265, etc.
  • medium.load - general commands (default if not matched)
  • low.load - curl, wget, rclone, rsync, aria2c, etc.

Manual Override

# Run ffmpeg as LOW load (bypass normal HIGH classification)
zag run --load-level=low -- ffmpeg -i input.mp4 output.mp4

# Run curl as HIGH load (override normal LOW classification)
zag run --load-level=high -- curl -O https://example.com/file.zip

Migration from barn

Area Barn Zag
Language Java 21 (GraalVM native image) Zig, static binary of about 1 MB
Binary barn zag
Data dir /tmp/barn /tmp/zag
Config /etc/barn/barn.conf, ~/.config/barn/barn.conf /etc/zag/zag.conf, ~/.config/zag/zag.conf
Environment overrides BARN_<SECTION>_<KEY> ZAG_<SECTION>_<KEY> (ZAG_LOAD_LEVELS_MAX_HIGH_JOBS works)
Socket <base>/barn.sock <base>/zag.sock (mode 0600)

The CLI surface, --output={json|xml} formats, job states, load levels and the on-disk job layout match barn. Where barn's code disagreed with its own documentation, zag follows the documentation:

  • zag clean behaves the same offline and through the service: with none of --all, --older-than or --job-id it removes nothing.
  • kill ends the job as canceled without racing the runner, and also cancels queued jobs.
  • A failed job is actually retried (--max-retries, --retry-delay, retry_on_exit_codes, exponential backoff with jitter); barn only retried jobs orphaned by a crash.
  • --timeout and default_timeout_seconds are enforced (symbolic exit code timeout).
  • service reload re-reads the configuration (also on SIGHUP) instead of doing nothing.
  • heartbeat_interval_seconds is honoured, and storage.base_dir / service.ipc_socket are used consistently by the daemon and the CLI.
  • Jobs run in their own process group, so kill and service stop --force take down the whole process tree. Job directories are created and deleted atomically.
  • Without config install, the built-in .load lists still classify ffmpeg as HIGH and curl as LOW.
  • config show calls the load-limit section load_levels, matching the config file.

Not implemented: Windows (dropped on purpose), max_disk_usage_gb, preserve_work_dir, auto-update.

Project Layout

See AGENTS.md for the module map. In short: src/cli*.zig is the command line, src/service.zig the daemon core, src/scheduler.zig / src/runner.zig run jobs, src/repository.zig persists them, src/ipc.zig is the socket protocol.