Add comprehensive project documentation

- docs/config.md: Configuration options, retry behavior, cleanup policies
- docs/development.md: Local dev setup, building from source
- docs/releasing.md: Version management, release process, AUR/Homebrew automation
- docs/ci-cd.md: GitHub Actions workflows for build, release, AUR, Homebrew
- docs/distribution.md: Package manager setup (WinGet, apt, AUR, Homebrew)
- docs/auto-update.md: Built-in barn update command
- docs/testing-automated.md: Test suite, running tests, CI integration
- docs/testing-manual.md: Step-by-step manual test procedures
- docs/jobs.md: Added retry-related state files
- README.md: Updated documentation links

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Daniel SamsonandClaude Opus 4.5 committed 2026-01-21 12:12:16 +00:00
1 parent 822086b39d
commit cf750b6eb5
10 files changed
+4403 -1

No files matched your search

+9 -1
View File
@@ -127,4 +127,12 @@ Developers can use the --offline command line option to test how the service beh
## Documentation
- [Barn Temporary Directory Layout](docs/jobs.md) describes how barn tracks jobs and storage
- [Barn Temporary Directory Layout](docs/jobs.md) describes how barn tracks jobs and storage
- [Barn Configuration](docs/config.md) describes configuration options, retry behavior, and cleanup policies
- [Development Guide](docs/development.md) covers local development setup and building from source
- [Releasing](docs/releasing.md) describes version management and the release process
- [CI/CD](docs/ci-cd.md) documents the GitHub Actions workflows for building and releasing
- [Distribution](docs/distribution.md) covers package manager setup (WinGet, apt, AUR, Homebrew)
- [Auto-Update](docs/auto-update.md) explains the built-in `barn update` command
- [Automated Testing](docs/testing-automated.md) covers the test suite, running tests, and CI integration
- [Manual Testing](docs/testing-manual.md) provides step-by-step manual test procedures
+434
View File
@@ -0,0 +1,434 @@
# Auto-Update
This document describes Barn's built-in self-update mechanism.
---
## Overview
Barn includes a `barn update` command that can check for and install new versions directly from GitHub Releases without requiring a package manager.
---
## Commands
### Check for Updates
```bash
barn update --check
```
Output:
```
Current version: 1.2.3
Latest version: 1.3.0
Update available: yes
Run 'barn update' to install the latest version.
```
### Install Latest Version
```bash
barn update
```
Output:
```
Current version: 1.2.3
Latest version: 1.3.0
Downloading barn-macos-arm64...
Verifying checksum...
Installing...
Restarting service...
Successfully updated to version 1.3.0
```
### Install Specific Version
```bash
barn update --version=1.2.0
```
### Force Update (Reinstall Current Version)
```bash
barn update --force
```
### JSON Output
```bash
barn update --check --output=json
```
```json
{
"current_version": "1.2.3",
"latest_version": "1.3.0",
"update_available": true,
"release_url": "https://github.com/samson-media/barn/releases/tag/v1.3.0"
}
```
---
## Update Flow
### 1. Query GitHub Releases API
Barn queries the GitHub Releases API to find the latest version:
```
GET https://api.github.com/repos/samson-media/barn/releases/latest
```
Response includes:
- Version tag
- Asset download URLs
- Checksums
### 2. Compare Versions
Versions are compared using semantic versioning:
```
1.3.0 > 1.2.3 → Update available
1.2.3 = 1.2.3 → Up to date
1.2.0 < 1.2.3 → Downgrade (requires --force)
```
### 3. Download Binary
The appropriate binary is downloaded based on OS and architecture:
| OS | Architecture | Asset |
|----|--------------|-------|
| Linux | x86_64 | `barn-linux-x64` |
| Linux | ARM64 | `barn-linux-arm64` |
| macOS | x86_64 | `barn-macos-x64` |
| macOS | ARM64 | `barn-macos-arm64` |
| Windows | x86_64 | `barn-windows-x64.exe` |
### 4. Verify Checksum
The SHA256 checksum is verified against `SHA256SUMS`:
```bash
# Downloaded automatically and verified
sha256sum -c SHA256SUMS
```
If verification fails, the update is aborted.
### 5. Replace Binary
The old binary is replaced with the new one.
### 6. Verify Installation
After replacement, Barn verifies the new binary works:
```bash
barn --version
```
---
## Platform-Specific Behavior
### Windows
Windows cannot replace a running executable. The update process:
1. Download new binary to temp location
2. Stop the Barn service
3. Rename current `barn.exe` to `barn.exe.old`
4. Move new binary to `barn.exe`
5. Start the Barn service
6. Delete `barn.exe.old` on next run
```
C:\Program Files\Barn\
barn.exe ← New version
barn.exe.old ← Previous version (deleted on next run)
```
### Linux / macOS
Direct replacement if permissions allow:
```bash
# Requires write permission to binary location
sudo barn update
```
If running without sudo and binary is in a protected location:
```
Error: Cannot update binary at /usr/local/bin/barn
Permission denied. Run with sudo or use your package manager.
```
### Package Manager Installations
If Barn detects it was installed via a package manager, it warns the user:
```
Warning: Barn appears to be installed via Homebrew.
Using 'barn update' may conflict with your package manager.
Recommended: Run 'brew upgrade barn' instead.
Continue anyway? [y/N]
```
Detection methods:
| Package Manager | Detection |
|-----------------|-----------|
| Homebrew | Binary in `/opt/homebrew/` or `/usr/local/Cellar/` |
| apt/dpkg | Binary in `/usr/bin/` with dpkg ownership |
| pacman | Binary in `/usr/bin/` with pacman ownership |
| WinGet | Registry entries present |
---
## Security
### HTTPS Only
All downloads use HTTPS. HTTP is never used.
### Checksum Verification
Every download is verified against the published SHA256 checksum:
```
SHA256SUMS content:
a1b2c3d4... barn-linux-x64
e5f6g7h8... barn-linux-arm64
...
```
If the checksum doesn't match, the update fails:
```
Error: Checksum verification failed
Expected: a1b2c3d4...
Got: xxxxxxxx...
The download may be corrupted or tampered with.
Update aborted.
```
### Signature Verification (Optional)
If GPG signatures are published, Barn can verify them:
```bash
barn update --verify-signature
```
This requires the Samson Media public key to be imported.
---
## Configuration
Update behavior can be configured in `barn.conf`:
```toml
[update]
# Disable update checks
enabled = true
# Check for updates automatically on service start
check_on_start = true
# Notify about updates without auto-installing
auto_install = false
# GitHub API endpoint (for enterprise GitHub)
github_api = "https://api.github.com"
# Proxy settings
proxy = ""
```
### Environment Variables
```bash
# Disable update functionality
BARN_UPDATE_ENABLED=false
# Use proxy for downloads
BARN_UPDATE_PROXY=http://proxy.example.com:8080
```
---
## Rollback
Barn keeps the previous version as a backup.
### Automatic Backup
During update, the previous binary is preserved:
| Platform | Backup Location |
|----------|-----------------|
| Linux/macOS | `/usr/local/bin/barn.backup` or alongside binary |
| Windows | `barn.exe.backup` |
### Manual Rollback
```bash
barn update --rollback
```
Or manually:
```bash
# Linux/macOS
sudo mv /usr/local/bin/barn.backup /usr/local/bin/barn
# Windows
move "C:\Program Files\Barn\barn.exe.backup" "C:\Program Files\Barn\barn.exe"
```
### Rollback Retention
Only the most recent previous version is kept. Older backups are deleted.
---
## Offline Mode
If network is unavailable:
```bash
barn update --check
```
```
Error: Cannot reach GitHub API
Check your network connection or proxy settings.
For offline installation, download the binary manually from:
https://github.com/samson-media/barn/releases
```
### Manual Offline Update
1. Download binary on another machine
2. Transfer to target machine
3. Replace binary manually:
```bash
chmod +x barn-linux-x64
sudo mv barn-linux-x64 /usr/local/bin/barn
```
---
## Update Notifications
When `check_on_start = true`, Barn checks for updates when the service starts and logs:
```
[INFO] Update available: 1.3.0 (current: 1.2.3)
[INFO] Run 'barn update' to install
```
This check is non-blocking and doesn't affect service startup.
---
## Troubleshooting
### Update Check Fails
```
Error: Failed to check for updates
GitHub API rate limit exceeded.
```
Solution: Wait an hour or authenticate with a GitHub token:
```bash
GITHUB_TOKEN=xxx barn update --check
```
### Permission Denied
```
Error: Cannot write to /usr/local/bin/barn
```
Solution: Run with elevated privileges:
```bash
sudo barn update
```
### Binary Corrupted After Update
```
Error: barn: cannot execute binary file
```
Solution: Roll back and report the issue:
```bash
sudo mv /usr/local/bin/barn.backup /usr/local/bin/barn
barn --version # Verify rollback worked
```
### Service Won't Start After Update
1. Check logs: `barn service logs`
2. Roll back: `barn update --rollback`
3. Start service: `barn service start`
---
## Implementation Details
### Version Detection
Barn determines its own version at compile time:
```kotlin
object Version {
const val CURRENT = "1.2.3" // Injected at build
val commit = System.getenv("BARN_COMMIT") ?: "unknown"
}
```
### API Endpoint
```
GET https://api.github.com/repos/samson-media/barn/releases/latest
Accept: application/vnd.github.v3+json
```
### Download with Progress
Downloads show progress for large binaries:
```
Downloading barn-linux-x64...
[████████████████████░░░░░░░░░░] 67% (12.3 MB / 18.4 MB)
```
---
## Next Steps
- [Releasing](releasing.md) - How versions are published
- [Distribution](distribution.md) - Package manager alternatives
+664
View File
@@ -0,0 +1,664 @@
# CI/CD
This document describes the GitHub Actions workflows for building and releasing Barn.
---
## Workflow Overview
| Workflow | Trigger | Purpose |
|----------|---------|---------|
| `build.yml` | Push, PR | Build and test on all platforms |
| `release.yml` | Tag push | Build, package, and publish release |
| `update-aur.yml` | Release published | Update AUR package |
| `update-homebrew.yml` | Release published | Update Homebrew formula |
---
## Build Workflow
File: `.github/workflows/build.yml`
```yaml
name: Build
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up GraalVM
uses: graalvm/setup-graalvm@v1
with:
java-version: '21'
distribution: 'graalvm-community'
cache: 'gradle'
- name: Run tests
run: ./gradlew test
- name: Upload test results
uses: actions/upload-artifact@v4
if: always()
with:
name: test-results
path: build/reports/tests/
build-native:
needs: test
strategy:
matrix:
include:
- os: ubuntu-latest
arch: x64
artifact: barn-linux-x64
- os: ubuntu-24.04-arm
arch: arm64
artifact: barn-linux-arm64
- os: macos-latest
arch: arm64
artifact: barn-macos-arm64
- os: macos-13
arch: x64
artifact: barn-macos-x64
- os: windows-latest
arch: x64
artifact: barn-windows-x64.exe
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- name: Set up GraalVM
uses: graalvm/setup-graalvm@v1
with:
java-version: '21'
distribution: 'graalvm-community'
cache: 'gradle'
- name: Build native image
run: ./gradlew nativeCompile
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: ${{ matrix.artifact }}
path: build/native/nativeCompile/barn*
```
---
## Release Workflow
File: `.github/workflows/release.yml`
```yaml
name: Release
on:
push:
tags:
- 'v*'
permissions:
contents: write
jobs:
build-native:
strategy:
matrix:
include:
- os: ubuntu-latest
arch: x64
artifact: barn-linux-x64
- os: ubuntu-24.04-arm
arch: arm64
artifact: barn-linux-arm64
- os: macos-latest
arch: arm64
artifact: barn-macos-arm64
- os: macos-13
arch: x64
artifact: barn-macos-x64
- os: windows-latest
arch: x64
artifact: barn-windows-x64
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- name: Set up GraalVM
uses: graalvm/setup-graalvm@v1
with:
java-version: '21'
distribution: 'graalvm-community'
cache: 'gradle'
- name: Build native image
run: ./gradlew nativeCompile
- name: Rename artifact (Unix)
if: runner.os != 'Windows'
run: mv build/native/nativeCompile/barn build/native/nativeCompile/${{ matrix.artifact }}
- name: Rename artifact (Windows)
if: runner.os == 'Windows'
run: mv build/native/nativeCompile/barn.exe build/native/nativeCompile/${{ matrix.artifact }}.exe
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: ${{ matrix.artifact }}
path: build/native/nativeCompile/${{ matrix.artifact }}*
build-deb:
needs: build-native
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Download Linux x64 binary
uses: actions/download-artifact@v4
with:
name: barn-linux-x64
path: packaging/deb/usr/bin/
- name: Build .deb package
run: |
chmod +x packaging/deb/usr/bin/barn-linux-x64
mv packaging/deb/usr/bin/barn-linux-x64 packaging/deb/usr/bin/barn
dpkg-deb --build packaging/deb barn-linux-x64.deb
- name: Upload .deb
uses: actions/upload-artifact@v4
with:
name: barn-linux-x64.deb
path: barn-linux-x64.deb
build-msi:
needs: build-native
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- name: Download Windows binary
uses: actions/download-artifact@v4
with:
name: barn-windows-x64
path: packaging/wix/
- name: Install WiX Toolset
run: dotnet tool install --global wix
- name: Build MSI
run: |
cd packaging/wix
wix build -o barn-windows-x64.msi barn.wxs
- name: Upload MSI
uses: actions/upload-artifact@v4
with:
name: barn-windows-x64.msi
path: packaging/wix/barn-windows-x64.msi
release:
needs: [build-native, build-deb, build-msi]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Download all artifacts
uses: actions/download-artifact@v4
with:
path: artifacts/
- name: Flatten artifacts
run: |
mkdir release
find artifacts -type f -exec mv {} release/ \;
- name: Generate checksums
run: |
cd release
sha256sum * > SHA256SUMS
- name: Extract changelog
id: changelog
run: |
VERSION=${GITHUB_REF#refs/tags/v}
sed -n "/## \[$VERSION\]/,/## \[/p" CHANGELOG.md | head -n -1 > release_notes.md
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
body_path: release_notes.md
files: release/*
```
---
## AUR Update Workflow
File: `.github/workflows/update-aur.yml`
This workflow automatically updates the AUR package when a new release is published.
```yaml
name: Update AUR
on:
release:
types: [published]
jobs:
update-aur:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Get release info
id: release
run: |
VERSION=${GITHUB_REF#refs/tags/v}
echo "version=$VERSION" >> $GITHUB_OUTPUT
# Get checksums from release
curl -sL "https://github.com/samson-media/barn/releases/download/v${VERSION}/SHA256SUMS" -o SHA256SUMS
X64_SHA=$(grep barn-linux-x64 SHA256SUMS | awk '{print $1}')
ARM64_SHA=$(grep barn-linux-arm64 SHA256SUMS | awk '{print $1}')
echo "x64_sha=$X64_SHA" >> $GITHUB_OUTPUT
echo "arm64_sha=$ARM64_SHA" >> $GITHUB_OUTPUT
- name: Update PKGBUILD
run: |
cat > PKGBUILD << 'EOF'
# Maintainer: Samson Media <support@samson-media.com>
pkgname=barn
pkgver=${{ steps.release.outputs.version }}
pkgrel=1
pkgdesc="Cross-platform job daemon for media processing"
arch=('x86_64' 'aarch64')
url="https://github.com/samson-media/barn"
license=('MIT')
depends=('glibc')
provides=('barn')
conflicts=('barn-git')
install=barn.install
source_x86_64=("${pkgname}-${pkgver}-x86_64::https://github.com/samson-media/barn/releases/download/v${pkgver}/barn-linux-x64")
source_aarch64=("${pkgname}-${pkgver}-aarch64::https://github.com/samson-media/barn/releases/download/v${pkgver}/barn-linux-arm64")
source=("barn.service" "barn.install")
sha256sums_x86_64=('${{ steps.release.outputs.x64_sha }}')
sha256sums_aarch64=('${{ steps.release.outputs.arm64_sha }}')
sha256sums=('SKIP' 'SKIP')
package() {
install -Dm755 "${srcdir}/${pkgname}-${pkgver}-${CARCH}" "${pkgdir}/usr/bin/barn"
install -Dm644 "${srcdir}/barn.service" "${pkgdir}/usr/lib/systemd/system/barn.service"
}
EOF
- name: Generate .SRCINFO
uses: hapakaien/archlinux-package-action@v2
with:
pkgbuild: PKGBUILD
flags: '--printsrcinfo > .SRCINFO'
- name: Publish to AUR
uses: KSXGitHub/github-actions-deploy-aur@v2
with:
pkgname: barn
pkgbuild: ./PKGBUILD
commit_username: 'Samson Media Bot'
commit_email: 'bot@samson-media.com'
ssh_private_key: ${{ secrets.AUR_SSH_KEY }}
commit_message: "Update to version ${{ steps.release.outputs.version }}"
assets: |
barn.service
barn.install
```
### AUR SSH Key Setup
To enable automated AUR publishing:
1. Generate an SSH key pair:
```bash
ssh-keygen -t ed25519 -C "barn-aur-deploy" -f barn-aur-key -N ""
```
2. Add the **public key** to your AUR account:
- Go to https://aur.archlinux.org/account/
- Add the contents of `barn-aur-key.pub` to SSH Keys
3. Add the **private key** to GitHub Secrets:
- Go to repository Settings > Secrets > Actions
- Create `AUR_SSH_KEY` with contents of `barn-aur-key`
### AUR Package Files
The workflow requires these files in the repository:
**File: `packaging/aur/barn.service`**
```ini
[Unit]
Description=Barn Job Daemon
After=network.target
[Service]
Type=simple
ExecStart=/usr/bin/barn service run
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
```
**File: `packaging/aur/barn.install`**
```bash
post_install() {
systemctl daemon-reload
echo ":: Run 'systemctl enable --now barn.service' to start Barn"
}
post_upgrade() {
systemctl daemon-reload
systemctl try-restart barn.service
}
pre_remove() {
systemctl stop barn.service || true
systemctl disable barn.service || true
}
post_remove() {
systemctl daemon-reload
}
```
### Manual AUR Update
If the automated workflow fails, update manually:
```bash
# Clone the AUR repo
git clone ssh://aur@aur.archlinux.org/barn.git aur-barn
cd aur-barn
# Update PKGBUILD version and checksums
# Edit pkgver, sha256sums_x86_64, sha256sums_aarch64
# Regenerate .SRCINFO
makepkg --printsrcinfo > .SRCINFO
# Commit and push
git add PKGBUILD .SRCINFO
git commit -m "Update to version X.Y.Z"
git push
```
---
## Homebrew Update Workflow
File: `.github/workflows/update-homebrew.yml`
```yaml
name: Update Homebrew
on:
release:
types: [published]
jobs:
update-homebrew:
runs-on: ubuntu-latest
steps:
- name: Get release info
id: release
run: |
VERSION=${GITHUB_REF#refs/tags/v}
echo "version=$VERSION" >> $GITHUB_OUTPUT
# Get checksums
curl -sL "https://github.com/samson-media/barn/releases/download/v${VERSION}/SHA256SUMS" -o SHA256SUMS
MACOS_ARM64_SHA=$(grep barn-macos-arm64 SHA256SUMS | awk '{print $1}')
MACOS_X64_SHA=$(grep barn-macos-x64 SHA256SUMS | awk '{print $1}')
echo "macos_arm64_sha=$MACOS_ARM64_SHA" >> $GITHUB_OUTPUT
echo "macos_x64_sha=$MACOS_X64_SHA" >> $GITHUB_OUTPUT
- name: Update Homebrew formula
uses: mislav/bump-homebrew-formula-action@v3
with:
formula-name: barn
formula-path: Formula/barn.rb
homebrew-tap: samson-media/homebrew-barn
base-branch: main
download-url: https://github.com/samson-media/barn/releases/download/v${{ steps.release.outputs.version }}/barn-macos-arm64
download-sha256: ${{ steps.release.outputs.macos_arm64_sha }}
env:
COMMITTER_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
```
---
## Build Matrix
| Runner | Architecture | Output |
|--------|--------------|--------|
| `ubuntu-latest` | x86_64 | `barn-linux-x64` |
| `ubuntu-24.04-arm` | ARM64 | `barn-linux-arm64` |
| `macos-latest` | ARM64 | `barn-macos-arm64` |
| `macos-13` | x86_64 | `barn-macos-x64` |
| `windows-latest` | x86_64 | `barn-windows-x64.exe` |
---
## GraalVM Setup
The `graalvm/setup-graalvm` action handles installation:
```yaml
- name: Set up GraalVM
uses: graalvm/setup-graalvm@v1
with:
java-version: '21'
distribution: 'graalvm-community'
cache: 'gradle'
```
Key options:
| Option | Value | Purpose |
|--------|-------|---------|
| `java-version` | `21` | JDK version |
| `distribution` | `graalvm-community` | GraalVM CE |
| `cache` | `gradle` | Cache Gradle dependencies |
---
## Caching Strategy
### Gradle Cache
The GraalVM action caches Gradle dependencies automatically when `cache: 'gradle'` is set.
### Manual Caching
For more control:
```yaml
- name: Cache Gradle packages
uses: actions/cache@v4
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
${{ runner.os }}-gradle-
```
### Native Image Cache
GraalVM native image builds can be cached:
```yaml
- name: Cache native image
uses: actions/cache@v4
with:
path: build/native
key: ${{ runner.os }}-native-${{ hashFiles('src/**', 'build.gradle.kts') }}
```
---
## Secrets Management
Required secrets in GitHub repository settings:
| Secret | Purpose |
|--------|---------|
| `SIGNING_KEY` | Code signing private key (optional) |
| `SIGNING_KEY_PASSWORD` | Signing key passphrase (optional) |
| `HOMEBREW_TAP_TOKEN` | Token for updating Homebrew tap |
| `AUR_SSH_KEY` | SSH key for AUR updates |
### Using Secrets
```yaml
- name: Sign binary
env:
SIGNING_KEY: ${{ secrets.SIGNING_KEY }}
SIGNING_KEY_PASSWORD: ${{ secrets.SIGNING_KEY_PASSWORD }}
run: ./scripts/sign.sh release/barn-linux-x64
```
---
## Artifact Upload
Artifacts are uploaded per platform and downloaded in the release job:
```yaml
# Upload in build job
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: barn-linux-x64
path: build/native/nativeCompile/barn
retention-days: 7
# Download in release job
- name: Download all artifacts
uses: actions/download-artifact@v4
with:
path: artifacts/
```
---
## Checksums
SHA256 checksums are generated for all release artifacts:
```yaml
- name: Generate checksums
run: |
cd release
sha256sum * > SHA256SUMS
```
The `SHA256SUMS` file is included in the release for verification.
---
## Triggering Workflows
### Build Workflow
Triggered automatically on:
- Push to `main`
- Pull request to `main`
### Release Workflow
Triggered by pushing a version tag:
```bash
git tag v1.2.3
git push origin v1.2.3
```
---
## Monitoring Workflows
View workflow runs at:
```
https://github.com/samson-media/barn/actions
```
### Status Badges
Add to README:
```markdown
![Build](https://github.com/samson-media/barn/actions/workflows/build.yml/badge.svg)
![Release](https://github.com/samson-media/barn/actions/workflows/release.yml/badge.svg)
```
---
## Troubleshooting
### Native Build Fails
Check GraalVM version compatibility:
```yaml
- name: Check GraalVM
run: |
java -version
native-image --version
```
### Artifact Not Found
Ensure artifact names match between upload and download steps.
### Release Already Exists
Delete the existing release via GitHub UI before re-running.
### Windows Long Paths
Enable long path support:
```yaml
- name: Enable long paths
run: git config --system core.longpaths true
```
---
## Next Steps
- [Releasing](releasing.md) - How to create releases
- [Distribution](distribution.md) - Package manager setup
+343
View File
@@ -0,0 +1,343 @@
# Barn Configuration
This document describes the configuration file format and options for the Barn job daemon.
---
## Configuration File Location
Barn looks for configuration in the following locations (in order):
| Platform | Path |
|----------|------|
| Linux | `/etc/barn/barn.conf` or `~/.config/barn/barn.conf` |
| macOS | `/etc/barn/barn.conf` or `~/Library/Application Support/barn/barn.conf` |
| Windows | `%PROGRAMDATA%\barn\barn.conf` or `%APPDATA%\barn\barn.conf` |
You can also specify a config file explicitly:
```bash
barn --config /path/to/barn.conf service start
```
---
## Configuration Format
Barn uses a simple key-value format (TOML-like):
```toml
[service]
log_level = "info"
max_concurrent_jobs = 4
heartbeat_interval_seconds = 5
ipc_socket = "/tmp/barn/barn.sock"
[jobs]
default_timeout_seconds = 3600
max_retries = 3
retry_delay_seconds = 30
retry_backoff_multiplier = 2.0
[cleanup]
enabled = true
max_age_hours = 72
cleanup_interval_minutes = 60
keep_failed_jobs = true
[storage]
base_dir = "/tmp/barn"
max_disk_usage_gb = 50
```
---
## Service Settings
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `log_level` | string | `"info"` | Logging verbosity: `debug`, `info`, `warn`, `error` |
| `max_concurrent_jobs` | integer | `4` | Maximum jobs running simultaneously |
| `heartbeat_interval_seconds` | integer | `5` | How often running jobs update their heartbeat |
| `ipc_socket` | string | platform-specific | Path to the IPC socket for CLI communication |
| `stale_heartbeat_threshold_seconds` | integer | `30` | Heartbeat age before a job is considered orphaned |
---
## Job Settings
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `default_timeout_seconds` | integer | `3600` | Maximum time a job can run before being killed |
| `max_retries` | integer | `3` | Number of retry attempts for failed jobs |
| `retry_delay_seconds` | integer | `30` | Initial delay before first retry |
| `retry_backoff_multiplier` | float | `2.0` | Multiplier applied to delay after each retry |
| `retry_on_exit_codes` | array | `[]` | Only retry on these exit codes (empty = retry all failures) |
---
## Retry Behavior
Barn implements **exponential backoff** for job retries.
### How Retries Work
1. When a job fails, Barn checks if retries are allowed
2. If `retry_count < max_retries`, the job is re-queued
3. The retry delay increases exponentially:
```
delay = retry_delay_seconds * (retry_backoff_multiplier ^ retry_count)
```
### Example Timeline
With default settings (`retry_delay_seconds=30`, `retry_backoff_multiplier=2.0`, `max_retries=3`):
| Attempt | Delay Before Retry |
|---------|-------------------|
| 1st retry | 30 seconds |
| 2nd retry | 60 seconds |
| 3rd retry | 120 seconds |
| (no more retries) | job marked `failed` |
### Retry State Tracking
Retry information is stored in the job directory:
```
/tmp/barn/jobs/<job-id>/
retry_count → current retry attempt (0, 1, 2, ...)
retry_at → timestamp for next retry attempt
retry_history → log of previous attempt exit codes and errors
```
### Per-Job Retry Override
You can override retry settings per job:
```bash
barn run --max-retries=5 --retry-delay=60 ffmpeg -i input.mp4 output.mp4
```
### Disabling Retries
To disable retries for a specific job:
```bash
barn run --max-retries=0 ffmpeg -i input.mp4 output.mp4
```
Or globally in config:
```toml
[jobs]
max_retries = 0
```
---
## Cleanup Settings
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `enabled` | boolean | `true` | Enable automatic cleanup |
| `max_age_hours` | integer | `72` | Remove jobs older than this |
| `cleanup_interval_minutes` | integer | `60` | How often the cleanup task runs |
| `keep_failed_jobs` | boolean | `true` | Preserve failed jobs for debugging |
| `keep_failed_jobs_hours` | integer | `168` | How long to keep failed jobs (1 week) |
---
## Cleanup Behavior
Barn provides both **automatic** and **manual** cleanup mechanisms.
### Automatic Cleanup
When `cleanup.enabled = true`, the daemon periodically:
1. Scans all jobs in `/tmp/barn/jobs/`
2. Identifies jobs eligible for removal based on:
- Job state (`succeeded`, `failed`, `canceled`)
- Age (based on `finished_at` timestamp)
- Configured retention policies
### What Gets Cleaned
| Job State | Cleanup Rule |
|-----------|--------------|
| `succeeded` | Removed after `max_age_hours` |
| `canceled` | Removed after `max_age_hours` |
| `failed` | Kept for `keep_failed_jobs_hours` if `keep_failed_jobs=true`, otherwise `max_age_hours` |
| `running` | Never automatically removed |
| `queued` | Never automatically removed |
### Manual Cleanup
Run cleanup immediately:
```bash
barn clean
```
With options:
```bash
# Remove all completed jobs regardless of age
barn clean --all
# Remove jobs older than 24 hours
barn clean --older-than=24h
# Dry run - show what would be removed
barn clean --dry-run
# Include failed jobs in cleanup
barn clean --include-failed
# Clean a specific job
barn clean --job-id=job-9f83c
```
### Cleanup Process
For each job being cleaned:
1. Acquire job lock (`/tmp/barn/locks/job-<job-id>.lock`)
2. Verify job is in terminal state
3. Remove job directory (`/tmp/barn/jobs/<job-id>/`)
4. Release and remove lock file
5. Log cleanup action to `/tmp/barn/logs/barn.log`
### Disk Space Protection
When `max_disk_usage_gb` is set, Barn will:
1. Calculate total disk usage of `/tmp/barn/`
2. If usage exceeds limit, trigger aggressive cleanup
3. Remove oldest completed jobs first (FIFO)
4. Log warnings if unable to free sufficient space
---
## Storage Settings
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `base_dir` | string | `/tmp/barn` | Root directory for all Barn data |
| `max_disk_usage_gb` | integer | `50` | Maximum disk space Barn can use |
| `preserve_work_dir` | boolean | `false` | Keep work/input and work/output after job completion |
---
## Environment Variable Overrides
Any config option can be overridden via environment variables:
```bash
BARN_SERVICE_LOG_LEVEL=debug
BARN_JOBS_MAX_RETRIES=5
BARN_CLEANUP_MAX_AGE_HOURS=24
```
Pattern: `BARN_<SECTION>_<KEY>` (uppercase, underscores)
---
## Example Configurations
### Development (Aggressive Cleanup)
```toml
[service]
log_level = "debug"
max_concurrent_jobs = 2
[jobs]
max_retries = 1
default_timeout_seconds = 300
[cleanup]
enabled = true
max_age_hours = 1
cleanup_interval_minutes = 5
keep_failed_jobs = false
```
### Production (Conservative)
```toml
[service]
log_level = "warn"
max_concurrent_jobs = 8
heartbeat_interval_seconds = 10
[jobs]
max_retries = 5
retry_delay_seconds = 60
default_timeout_seconds = 7200
[cleanup]
enabled = true
max_age_hours = 168
keep_failed_jobs = true
keep_failed_jobs_hours = 336
[storage]
max_disk_usage_gb = 200
```
### CI/CD (No Retries, Fast Cleanup)
```toml
[service]
max_concurrent_jobs = 1
[jobs]
max_retries = 0
default_timeout_seconds = 600
[cleanup]
enabled = true
max_age_hours = 1
keep_failed_jobs = false
```
---
## Reloading Configuration
To apply config changes without restarting:
```bash
barn service reload
```
This will:
1. Re-read the configuration file
2. Apply changes to cleanup and job settings immediately
3. New jobs will use updated settings
4. Running jobs are not affected
Settings that require a full restart:
- `ipc_socket`
- `base_dir`
---
## Validating Configuration
Check your config file for errors:
```bash
barn config validate
barn config validate --config /path/to/barn.conf
```
Show effective configuration (with defaults and overrides):
```bash
barn config show
```
+249
View File
@@ -0,0 +1,249 @@
# Development Guide
This document covers local development setup and building Barn from source.
---
## Prerequisites
| Requirement | Version | Notes |
|-------------|---------|-------|
| JDK | 21+ | Required for building |
| GraalVM CE | 21+ | Required for native image builds |
| Gradle | 8.x | Wrapper included in project |
| Git | Any recent | For version control |
### Installing GraalVM
**macOS (Homebrew):**
```bash
brew install --cask graalvm-jdk
```
**Linux:**
```bash
# Download from https://www.graalvm.org/downloads/
# Extract and set GRAALVM_HOME
export GRAALVM_HOME=/path/to/graalvm
export PATH=$GRAALVM_HOME/bin:$PATH
```
**Windows:**
Download from [GraalVM Downloads](https://www.graalvm.org/downloads/) and add to PATH.
---
## Project Structure
```
barn/
src/
main/
kotlin/ # Application source code
resources/ # Configuration and resource files
test/
kotlin/ # Unit and integration tests
build.gradle.kts # Build configuration
gradle.properties # Version and build properties
settings.gradle.kts # Project settings
docs/ # Documentation
```
---
## Building
### Build the JAR
```bash
./gradlew build
```
This compiles the source, runs tests, and produces a JAR in `build/libs/`.
### Run Tests
```bash
# Run all tests
./gradlew test
# Run specific test class
./gradlew test --tests "com.samsonmedia.barn.JobManagerTest"
# Run with verbose output
./gradlew test --info
```
### Build Native Image
Building a native executable requires GraalVM with Native Image support:
```bash
# Ensure GraalVM is active
java -version # Should show GraalVM
# Build native image
./gradlew nativeCompile
```
The native binary is output to `build/native/nativeCompile/barn`.
### Clean Build
```bash
./gradlew clean build
```
---
## Running Locally
### From JAR
```bash
java -jar build/libs/barn.jar --help
```
### From Native Binary
```bash
./build/native/nativeCompile/barn --help
```
### Development Mode
Use the `--offline` flag to test commands without running the service:
```bash
./gradlew run --args="run --offline echo hello"
```
---
## IDE Setup
### IntelliJ IDEA (Recommended)
1. Open IntelliJ IDEA
2. Select **File > Open**
3. Navigate to the `barn` directory and open it
4. IntelliJ will detect the Gradle project and import it
5. Wait for Gradle sync to complete
**Recommended plugins:**
- Kotlin
- Gradle
**Run configurations:**
- Create a Kotlin Application configuration
- Main class: `com.samsonmedia.barn.MainKt`
- Program arguments: `--help` (or any command)
### VS Code
1. Install the Kotlin and Gradle extensions
2. Open the `barn` folder
3. The Gradle extension will detect the project
---
## Common Tasks
### Format Code
```bash
./gradlew ktlintFormat
```
### Check Code Style
```bash
./gradlew ktlintCheck
```
### Generate Documentation
```bash
./gradlew dokkaHtml
```
Output is in `build/dokka/html/`.
### Dependency Updates
Check for outdated dependencies:
```bash
./gradlew dependencyUpdates
```
---
## Troubleshooting
### GraalVM Not Found
Ensure `GRAALVM_HOME` is set and GraalVM is on your PATH:
```bash
export GRAALVM_HOME=/path/to/graalvm
export PATH=$GRAALVM_HOME/bin:$PATH
```
### Native Image Build Fails
Common causes:
1. **Reflection configuration missing**: Add classes to `reflect-config.json`
2. **Resource not included**: Add to `resource-config.json`
3. **Insufficient memory**: Increase heap with `-J-Xmx8g`
```bash
./gradlew nativeCompile -Pnative.heap=8g
```
### Tests Fail on Windows
Ensure line endings are consistent:
```bash
git config core.autocrlf input
```
### Gradle Wrapper Issues
Regenerate the wrapper:
```bash
gradle wrapper --gradle-version 8.5
```
### Out of Memory During Build
Increase Gradle daemon memory in `gradle.properties`:
```properties
org.gradle.jvmargs=-Xmx4g
```
---
## Environment Variables
| Variable | Description |
|----------|-------------|
| `GRAALVM_HOME` | Path to GraalVM installation |
| `JAVA_HOME` | Path to JDK (can point to GraalVM) |
| `BARN_LOG_LEVEL` | Override log level during development |
---
## Next Steps
- [Releasing](releasing.md) - How to create releases
- [CI/CD](ci-cd.md) - Automated build and release workflows
+689
View File
@@ -0,0 +1,689 @@
# Distribution
This document describes package manager setup and installer creation for all supported platforms.
---
## Overview
| Platform | Package Format | Distribution Channel |
|----------|---------------|---------------------|
| Windows | MSI installer | WinGet |
| Linux (Debian/Ubuntu) | .deb | GitHub Releases, optional PPA |
| Linux (Arch) | PKGBUILD | AUR |
| macOS | Formula | Homebrew tap |
---
## Windows MSI
### WiX Toolset Setup
Barn uses [WiX Toolset v4](https://wixtoolset.org/) to create MSI installers.
Install WiX:
```powershell
dotnet tool install --global wix
```
### Package Structure
```
packaging/wix/
barn.wxs # WiX source file
license.rtf # License for installer
banner.png # Installer banner (optional)
dialog.png # Installer dialog background (optional)
```
### WiX Source File
File: `packaging/wix/barn.wxs`
```xml
<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://wixtoolset.org/schemas/v4/wxs">
<Package Name="Barn"
Version="!(bind.FileVersion.BarnExe)"
Manufacturer="Samson Media"
UpgradeCode="PUT-GUID-HERE"
Scope="perMachine">
<MajorUpgrade DowngradeErrorMessage="A newer version of Barn is already installed." />
<MediaTemplate EmbedCab="yes" />
<Feature Id="ProductFeature" Title="Barn" Level="1">
<ComponentGroupRef Id="ProductComponents" />
<ComponentGroupRef Id="ServiceComponents" />
</Feature>
<StandardDirectory Id="ProgramFiles64Folder">
<Directory Id="INSTALLFOLDER" Name="Barn">
<Component Id="BarnExe" Guid="PUT-GUID-HERE">
<File Id="BarnExe" Source="barn-windows-x64.exe" Name="barn.exe" KeyPath="yes" />
</Component>
<Component Id="PathEntry" Guid="PUT-GUID-HERE">
<Environment Id="PATH" Name="PATH" Value="[INSTALLFOLDER]"
Permanent="no" Part="last" Action="set" System="yes" />
</Component>
</Directory>
</StandardDirectory>
<ComponentGroup Id="ProductComponents">
<ComponentRef Id="BarnExe" />
<ComponentRef Id="PathEntry" />
</ComponentGroup>
<ComponentGroup Id="ServiceComponents">
<Component Id="BarnService" Directory="INSTALLFOLDER" Guid="PUT-GUID-HERE">
<ServiceInstall Id="BarnServiceInstall"
Type="ownProcess"
Name="BarnService"
DisplayName="Barn Job Daemon"
Description="Background service for managing media processing jobs"
Start="auto"
Account="LocalSystem"
ErrorControl="normal" />
<ServiceControl Id="StartBarnService"
Start="install"
Stop="both"
Remove="uninstall"
Name="BarnService"
Wait="yes" />
</Component>
</ComponentGroup>
</Package>
</Wix>
```
### Building the MSI
```powershell
cd packaging/wix
wix build -o barn-windows-x64.msi barn.wxs
```
### WinGet Submission
#### Manifest Structure
Create a manifest directory:
```
manifests/s/SamsonMedia/Barn/1.2.3/
SamsonMedia.Barn.yaml
SamsonMedia.Barn.installer.yaml
SamsonMedia.Barn.locale.en-US.yaml
```
#### Version Manifest
File: `SamsonMedia.Barn.yaml`
```yaml
PackageIdentifier: SamsonMedia.Barn
PackageVersion: 1.2.3
DefaultLocale: en-US
ManifestType: version
ManifestVersion: 1.6.0
```
#### Installer Manifest
File: `SamsonMedia.Barn.installer.yaml`
```yaml
PackageIdentifier: SamsonMedia.Barn
PackageVersion: 1.2.3
Platform:
- Windows.Desktop
MinimumOSVersion: 10.0.0.0
InstallerType: msi
Scope: machine
InstallModes:
- silent
- silentWithProgress
Installers:
- Architecture: x64
InstallerUrl: https://github.com/samson-media/barn/releases/download/v1.2.3/barn-windows-x64.msi
InstallerSha256: <SHA256_HASH>
ManifestType: installer
ManifestVersion: 1.6.0
```
#### Locale Manifest
File: `SamsonMedia.Barn.locale.en-US.yaml`
```yaml
PackageIdentifier: SamsonMedia.Barn
PackageVersion: 1.2.3
PackageLocale: en-US
Publisher: Samson Media
PackageName: Barn
PackageUrl: https://github.com/samson-media/barn
License: MIT
ShortDescription: Cross-platform job daemon for media processing
Description: A cross-platform service for managing long-running jobs involving media download, upload, and FFmpeg processing.
Tags:
- cli
- ffmpeg
- media
- daemon
- job-scheduler
ManifestType: defaultLocale
ManifestVersion: 1.6.0
```
#### Submitting to WinGet
1. Fork [microsoft/winget-pkgs](https://github.com/microsoft/winget-pkgs)
2. Create branch: `barn-1.2.3`
3. Add manifest files to `manifests/s/SamsonMedia/Barn/1.2.3/`
4. Validate: `winget validate manifests/s/SamsonMedia/Barn/1.2.3/`
5. Create pull request
---
## Linux .deb (apt)
### Package Structure
```
packaging/deb/
DEBIAN/
control
postinst
prerm
conffiles
usr/
bin/
barn
lib/
systemd/
system/
barn.service
etc/
barn/
barn.conf
```
### Control File
File: `packaging/deb/DEBIAN/control`
```
Package: barn
Version: 1.2.3
Section: utils
Priority: optional
Architecture: amd64
Maintainer: Samson Media <support@samson-media.com>
Description: Cross-platform job daemon for media processing
A cross-platform service for managing long-running jobs involving
media download, upload, and FFmpeg processing with strong guarantees
around durability, observability, and crash recovery.
Homepage: https://github.com/samson-media/barn
Depends: libc6 (>= 2.31)
```
### Post-Install Script
File: `packaging/deb/DEBIAN/postinst`
```bash
#!/bin/bash
set -e
# Reload systemd
systemctl daemon-reload
# Enable and start service
systemctl enable barn.service
systemctl start barn.service
echo "Barn installed successfully. Service is running."
echo "Run 'barn status' to check job status."
```
### Pre-Remove Script
File: `packaging/deb/DEBIAN/prerm`
```bash
#!/bin/bash
set -e
# Stop and disable service
systemctl stop barn.service || true
systemctl disable barn.service || true
echo "Barn service stopped."
```
### Systemd Service File
File: `packaging/deb/lib/systemd/system/barn.service`
```ini
[Unit]
Description=Barn Job Daemon
After=network.target
[Service]
Type=simple
ExecStart=/usr/bin/barn service run
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5
User=root
[Install]
WantedBy=multi-user.target
```
### Building the .deb
```bash
# Set permissions
chmod 755 packaging/deb/DEBIAN/postinst
chmod 755 packaging/deb/DEBIAN/prerm
chmod 755 packaging/deb/usr/bin/barn
# Build package
dpkg-deb --build packaging/deb barn-linux-x64.deb
# Verify
dpkg-deb --info barn-linux-x64.deb
```
### Installation
Users install directly from GitHub Releases:
```bash
# Download
wget https://github.com/samson-media/barn/releases/download/v1.2.3/barn-linux-x64.deb
# Install
sudo dpkg -i barn-linux-x64.deb
# Or with apt (handles dependencies)
sudo apt install ./barn-linux-x64.deb
```
### Optional: Launchpad PPA
For automatic updates via apt:
1. Create account at [Launchpad](https://launchpad.net/)
2. Create PPA: `ppa:samson-media/barn`
3. Upload source package with `dput`
4. Users add: `sudo add-apt-repository ppa:samson-media/barn`
---
## Linux PKGBUILD (pacman/AUR)
### PKGBUILD File
File: `packaging/aur/PKGBUILD`
```bash
# Maintainer: Samson Media <support@samson-media.com>
pkgname=barn
pkgver=1.2.3
pkgrel=1
pkgdesc="Cross-platform job daemon for media processing"
arch=('x86_64' 'aarch64')
url="https://github.com/samson-media/barn"
license=('MIT')
depends=('glibc')
provides=('barn')
conflicts=('barn-git')
source_x86_64=("${pkgname}-${pkgver}-x86_64::https://github.com/samson-media/barn/releases/download/v${pkgver}/barn-linux-x64")
source_aarch64=("${pkgname}-${pkgver}-aarch64::https://github.com/samson-media/barn/releases/download/v${pkgver}/barn-linux-arm64")
sha256sums_x86_64=('SKIP') # Replace with actual hash
sha256sums_aarch64=('SKIP') # Replace with actual hash
package() {
install -Dm755 "${srcdir}/${pkgname}-${pkgver}-${CARCH}" "${pkgdir}/usr/bin/barn"
install -Dm644 "${srcdir}/barn.service" "${pkgdir}/usr/lib/systemd/system/barn.service"
}
```
### Install Script
File: `packaging/aur/barn.install`
```bash
post_install() {
systemctl daemon-reload
echo ":: Run 'systemctl enable --now barn.service' to start Barn"
}
post_upgrade() {
systemctl daemon-reload
systemctl try-restart barn.service
}
pre_remove() {
systemctl stop barn.service || true
systemctl disable barn.service || true
}
post_remove() {
systemctl daemon-reload
}
```
### AUR Submission
1. Create account at [AUR](https://aur.archlinux.org/)
2. Add SSH key to account
3. Clone AUR package base:
```bash
git clone ssh://aur@aur.archlinux.org/barn.git
```
4. Add PKGBUILD and .SRCINFO:
```bash
makepkg --printsrcinfo > .SRCINFO
```
5. Commit and push:
```bash
git add PKGBUILD .SRCINFO barn.install
git commit -m "Update to version 1.2.3"
git push
```
### Updating AUR Package
AUR updates are **automated** via GitHub Actions. See [CI/CD](ci-cd.md#aur-update-workflow) for the workflow details.
If manual update is needed:
1. Update `pkgver` in PKGBUILD
2. Update SHA256 checksums
3. Regenerate .SRCINFO
4. Commit and push
```bash
# Clone the AUR repo
git clone ssh://aur@aur.archlinux.org/barn.git aur-barn
cd aur-barn
# Update version
sed -i "s/pkgver=.*/pkgver=1.2.4/" PKGBUILD
# Get new checksums from GitHub release
curl -sL https://github.com/samson-media/barn/releases/download/v1.2.4/SHA256SUMS
# Update checksums in PKGBUILD
# Edit sha256sums_x86_64 and sha256sums_aarch64
# Regenerate .SRCINFO
makepkg --printsrcinfo > .SRCINFO
# Commit and push
git add PKGBUILD .SRCINFO
git commit -m "Update to version 1.2.4"
git push
```
### Initial AUR Setup
Before the first release, create the AUR package:
1. **Create AUR Account**
- Register at https://aur.archlinux.org/register/
- Verify email and log in
2. **Add SSH Key**
```bash
ssh-keygen -t ed25519 -C "aur" -f ~/.ssh/aur
```
- Add public key at https://aur.archlinux.org/account/
- Configure SSH:
```
# ~/.ssh/config
Host aur.archlinux.org
IdentityFile ~/.ssh/aur
User aur
```
3. **Create Package Base**
```bash
git clone ssh://aur@aur.archlinux.org/barn.git
cd barn
# Directory will be empty for new packages
```
4. **Add Package Files**
```bash
# Copy PKGBUILD, barn.install, barn.service from packaging/aur/
cp /path/to/packaging/aur/* .
# Generate .SRCINFO
makepkg --printsrcinfo > .SRCINFO
# Initial commit
git add PKGBUILD .SRCINFO barn.install barn.service
git commit -m "Initial package submission"
git push
```
5. **Verify Package**
- Check https://aur.archlinux.org/packages/barn
- Test installation:
```bash
yay -S barn # or paru -S barn
```
### AUR Best Practices
- **Test locally** before pushing: `makepkg -si`
- **Bump pkgrel** for packaging changes (same upstream version)
- **Reset pkgrel to 1** when pkgver changes
- **Respond to comments** on AUR package page
- **Flag out-of-date** packages if automation fails
### barn-git Package (Optional)
For users who want the latest development version, consider maintaining a `-git` package:
File: `packaging/aur-git/PKGBUILD`
```bash
# Maintainer: Samson Media <support@samson-media.com>
pkgname=barn-git
pkgver=r123.abc1234
pkgrel=1
pkgdesc="Cross-platform job daemon for media processing (development version)"
arch=('x86_64' 'aarch64')
url="https://github.com/samson-media/barn"
license=('MIT')
depends=('glibc')
makedepends=('git' 'graalvm-jdk' 'gradle')
provides=('barn')
conflicts=('barn')
source=("git+https://github.com/samson-media/barn.git")
sha256sums=('SKIP')
pkgver() {
cd barn
printf "r%s.%s" "$(git rev-list --count HEAD)" "$(git rev-parse --short HEAD)"
}
build() {
cd barn
./gradlew nativeCompile
}
package() {
cd barn
install -Dm755 "build/native/nativeCompile/barn" "${pkgdir}/usr/bin/barn"
}
```
---
## macOS Homebrew
### Homebrew Tap Setup
Create a tap repository: `samson-media/homebrew-barn`
```bash
# Create repository structure
mkdir homebrew-barn
cd homebrew-barn
git init
mkdir Formula
```
### Formula File
File: `Formula/barn.rb`
```ruby
class Barn < Formula
desc "Cross-platform job daemon for media processing"
homepage "https://github.com/samson-media/barn"
version "1.2.3"
license "MIT"
on_macos do
on_arm do
url "https://github.com/samson-media/barn/releases/download/v1.2.3/barn-macos-arm64"
sha256 "SHA256_HASH_HERE"
def install
bin.install "barn-macos-arm64" => "barn"
end
end
on_intel do
url "https://github.com/samson-media/barn/releases/download/v1.2.3/barn-macos-x64"
sha256 "SHA256_HASH_HERE"
def install
bin.install "barn-macos-x64" => "barn"
end
end
end
service do
run [opt_bin/"barn", "service", "run"]
keep_alive true
log_path var/"log/barn.log"
error_log_path var/"log/barn.error.log"
end
test do
assert_match "barn", shell_output("#{bin}/barn --version")
end
end
```
### User Installation
```bash
# Add tap
brew tap samson-media/barn
# Install
brew install barn
# Start service
brew services start barn
```
### Formula vs Cask
Use **Formula** (not Cask) because:
- Barn is a CLI tool
- No GUI components
- Single binary installation
- Service integration via `brew services`
### Auto-Updating Formula
Create a GitHub Action to update the formula on release:
File: `.github/workflows/update-homebrew.yml`
```yaml
name: Update Homebrew
on:
release:
types: [published]
jobs:
update:
runs-on: ubuntu-latest
steps:
- name: Update Homebrew formula
uses: mislav/bump-homebrew-formula-action@v3
with:
formula-name: barn
homebrew-tap: samson-media/homebrew-barn
download-url: https://github.com/samson-media/barn/releases/download/${{ github.ref_name }}/barn-macos-arm64
env:
COMMITTER_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
```
---
## Direct Binary Downloads
For users who prefer manual installation:
### Download URLs
```
https://github.com/samson-media/barn/releases/download/v1.2.3/barn-linux-x64
https://github.com/samson-media/barn/releases/download/v1.2.3/barn-linux-arm64
https://github.com/samson-media/barn/releases/download/v1.2.3/barn-macos-x64
https://github.com/samson-media/barn/releases/download/v1.2.3/barn-macos-arm64
https://github.com/samson-media/barn/releases/download/v1.2.3/barn-windows-x64.exe
https://github.com/samson-media/barn/releases/download/v1.2.3/SHA256SUMS
```
### Manual Installation (Unix)
```bash
# Download
curl -LO https://github.com/samson-media/barn/releases/download/v1.2.3/barn-linux-x64
# Verify checksum
curl -LO https://github.com/samson-media/barn/releases/download/v1.2.3/SHA256SUMS
sha256sum -c SHA256SUMS --ignore-missing
# Install
chmod +x barn-linux-x64
sudo mv barn-linux-x64 /usr/local/bin/barn
# Verify
barn --version
```
---
## Release Checklist for Distribution
After publishing a GitHub Release:
1. **Windows**: Submit WinGet manifest PR
2. **Arch Linux**: Update AUR PKGBUILD
3. **Homebrew**: Formula auto-updates via workflow
4. **Debian**: .deb available on GitHub Releases
---
## Next Steps
- [Auto-Update](auto-update.md) - Built-in update mechanism
- [CI/CD](ci-cd.md) - Automated packaging workflows
+3
View File
@@ -128,6 +128,9 @@ Written once at job creation.
| `error` | Human-readable failure reason |
| `pid` | OS process ID (best-effort) |
| `heartbeat` | Last liveness update |
| `retry_count` | Current retry attempt (0, 1, 2, ...) |
| `retry_at` | Timestamp for next retry attempt |
| `retry_history` | Log of previous attempt exit codes and errors |
All values are stored as **plain text**.
+422
View File
@@ -0,0 +1,422 @@
# Releasing
This document describes how releases are versioned, tagged, and published.
---
## Versioning
Barn follows [Semantic Versioning](https://semver.org/):
```
MAJOR.MINOR.PATCH
```
| Component | When to Increment |
|-----------|-------------------|
| MAJOR | Breaking changes to CLI or config format |
| MINOR | New features, backward compatible |
| PATCH | Bug fixes, backward compatible |
### Pre-release Versions
For pre-release testing:
- Alpha: `1.2.0-alpha.1`
- Beta: `1.2.0-beta.1`
- Release candidate: `1.2.0-rc.1`
---
## Version Location
The version is defined in `gradle.properties`:
```properties
version=1.2.3
```
This version is embedded in the binary and available via `barn --version`.
---
## Changelog
Maintain `CHANGELOG.md` in the repository root using [Keep a Changelog](https://keepachangelog.com/) format:
```markdown
# Changelog
All notable changes to this project will be documented in this file.
## [Unreleased]
### Added
- New feature description
### Changed
- Modified behavior description
### Fixed
- Bug fix description
### Removed
- Removed feature description
## [1.2.3] - 2026-01-21
### Added
- Initial release features
[Unreleased]: https://github.com/samson-media/barn/compare/v1.2.3...HEAD
[1.2.3]: https://github.com/samson-media/barn/releases/tag/v1.2.3
```
### Changelog Categories
- **Added**: New features
- **Changed**: Changes in existing functionality
- **Deprecated**: Features that will be removed
- **Removed**: Features that were removed
- **Fixed**: Bug fixes
- **Security**: Security-related changes
---
## Release Checklist
### Prerequisites (First Release Only)
Before the first release, ensure the following are set up:
- [ ] **AUR SSH Key**: Generate and add to GitHub Secrets as `AUR_SSH_KEY` (see [CI/CD](ci-cd.md#aur-ssh-key-setup))
- [ ] **AUR Package**: Create initial package at https://aur.archlinux.org (see [Distribution](distribution.md#initial-aur-setup))
- [ ] **Homebrew Tap**: Create `samson-media/homebrew-barn` repository
- [ ] **Homebrew Token**: Add `HOMEBREW_TAP_TOKEN` to GitHub Secrets
- [ ] **Code Signing** (optional): Add `SIGNING_KEY` and `SIGNING_KEY_PASSWORD` to GitHub Secrets
### 1. Prepare the Release
Ensure all changes are merged to `main` and tests pass:
```bash
git checkout main
git pull origin main
./gradlew clean test
```
### 2. Update Version
Edit `gradle.properties`:
```properties
version=1.2.3
```
### 3. Update Changelog
Move items from `[Unreleased]` to the new version section:
```markdown
## [1.2.3] - 2026-01-21
### Added
- New feature X
- Support for Y
### Fixed
- Bug in Z
```
### 4. Commit the Release
```bash
git add gradle.properties CHANGELOG.md
git commit -m "Release v1.2.3"
```
### 5. Tag the Release
```bash
git tag v1.2.3
```
### 6. Push to Remote
```bash
git push origin main --tags
```
This triggers the release workflow in GitHub Actions.
---
## Automated Release Pipeline
When a tag is pushed, the following happens automatically:
```
git push --tags
│
▼
┌─────────────────────────────────────────────────────────┐
│ release.yml - Build & Publish │
│ ├── Build native binaries (Linux, macOS, Windows) │
│ ├── Build packages (.deb, .msi) │
│ ├── Generate SHA256SUMS │
│ └── Create GitHub Release with artifacts │
└─────────────────────────────────────────────────────────┘
│
▼ (on: release published)
┌─────────────────────────────────────────────────────────┐
│ update-aur.yml - Arch Linux │
│ ├── Fetch checksums from GitHub Release │
│ ├── Generate PKGBUILD with new version │
│ ├── Generate .SRCINFO │
│ └── Push to AUR via SSH │
└─────────────────────────────────────────────────────────┘
│
▼ (on: release published)
┌─────────────────────────────────────────────────────────┐
│ update-homebrew.yml - macOS │
│ ├── Fetch checksums from GitHub Release │
│ ├── Update formula with new version/SHA │
│ └── Push to homebrew-barn tap │
└─────────────────────────────────────────────────────────┘
```
### Manual Steps Required
| Package Manager | Automated | Manual Action Required |
|-----------------|-----------|------------------------|
| GitHub Releases | Yes | None |
| AUR (Arch Linux) | Yes | None (verify after) |
| Homebrew (macOS) | Yes | None (verify after) |
| WinGet (Windows) | No | Submit manifest PR |
| apt (Debian/Ubuntu) | Partial | .deb on GitHub, PPA requires manual upload |
---
## GitHub Release
The CI/CD pipeline automatically creates a GitHub Release when a tag is pushed. The release includes:
### Artifacts
| Artifact | Description |
|----------|-------------|
| `barn-linux-x64` | Linux x86_64 binary |
| `barn-linux-arm64` | Linux ARM64 binary |
| `barn-macos-x64` | macOS Intel binary |
| `barn-macos-arm64` | macOS Apple Silicon binary |
| `barn-windows-x64.exe` | Windows x86_64 binary |
| `barn-windows-x64.msi` | Windows installer |
| `barn-linux-x64.deb` | Debian/Ubuntu package |
| `SHA256SUMS` | Checksums for all artifacts |
### Release Notes
The release workflow extracts the changelog section for the released version and uses it as release notes.
---
## Hotfix Releases
For urgent fixes to a released version:
### 1. Create Hotfix Branch
```bash
git checkout -b hotfix/v1.2.4 v1.2.3
```
### 2. Apply Fix
Make the necessary changes and commit:
```bash
git commit -m "Fix critical bug in job scheduler"
```
### 3. Update Version and Changelog
```bash
# Edit gradle.properties: version=1.2.4
# Update CHANGELOG.md
git commit -m "Release v1.2.4"
```
### 4. Tag and Push
```bash
git tag v1.2.4
git push origin hotfix/v1.2.4 --tags
```
### 5. Merge Back to Main
```bash
git checkout main
git merge hotfix/v1.2.4
git push origin main
```
---
## Post-Release Tasks
After a release is published:
### 1. Verify GitHub Release
```bash
# Check release page
open https://github.com/samson-media/barn/releases/latest
# Verify all artifacts are present
curl -s https://api.github.com/repos/samson-media/barn/releases/latest | jq '.assets[].name'
# Expected artifacts:
# - barn-linux-x64
# - barn-linux-arm64
# - barn-macos-x64
# - barn-macos-arm64
# - barn-windows-x64.exe
# - barn-windows-x64.msi
# - barn-linux-x64.deb
# - SHA256SUMS
```
### 2. Verify Package Manager Updates
#### AUR (Arch Linux) - Automated
Check the GitHub Actions workflow status:
```bash
open https://github.com/samson-media/barn/actions/workflows/update-aur.yml
```
Verify the AUR package:
```bash
# Check AUR page shows new version
open https://aur.archlinux.org/packages/barn
# Test installation (on Arch Linux)
yay -Sy barn
barn --version
```
If the workflow failed, manually update:
```bash
git clone ssh://aur@aur.archlinux.org/barn.git aur-barn
cd aur-barn
# Update pkgver and checksums in PKGBUILD
makepkg --printsrcinfo > .SRCINFO
git add -A && git commit -m "Update to vX.Y.Z" && git push
```
#### Homebrew (macOS) - Automated
Check the GitHub Actions workflow status:
```bash
open https://github.com/samson-media/barn/actions/workflows/update-homebrew.yml
```
Verify the Homebrew formula:
```bash
# Update tap and check version
brew update
brew info samson-media/barn/barn
# Test installation (on macOS)
brew upgrade barn
barn --version
```
#### WinGet (Windows) - Manual
Submit a PR to winget-pkgs:
```bash
# Fork and clone microsoft/winget-pkgs
# Create manifests/s/SamsonMedia/Barn/X.Y.Z/
# Add version, installer, and locale manifests
# See Distribution docs for manifest format
```
Validate and submit:
```powershell
winget validate manifests/s/SamsonMedia/Barn/X.Y.Z/
# Create PR to microsoft/winget-pkgs
```
### 3. Announce Release
- Post to relevant channels (Discord, Twitter, blog, etc.)
- Update project website if applicable
### 4. Monitor for Issues
- Watch GitHub Issues for regression reports
- Monitor AUR comments: https://aur.archlinux.org/packages/barn
- Check Homebrew issues if any
### Troubleshooting Failed Updates
| Package Manager | Check Logs | Manual Fix |
|-----------------|------------|------------|
| AUR | Actions → update-aur.yml | See [Distribution](distribution.md#updating-aur-package) |
| Homebrew | Actions → update-homebrew.yml | See [Distribution](distribution.md#homebrew-tap-setup) |
| WinGet | N/A (manual) | See [Distribution](distribution.md#winget-submission) |
---
## Reverting a Release
If a critical issue is found after release:
### Option 1: Hotfix Release
Create a patch release with the fix (preferred).
### Option 2: Yank the Release
Mark the GitHub Release as a pre-release or delete it:
```bash
# Mark as pre-release via GitHub UI
# Or delete the release (artifacts remain)
```
Never delete tags that have been pushed publicly.
---
## Version Embedding
The version is embedded in the binary at build time. To verify:
```bash
barn --version
# Output: barn 1.2.3
```
The version is also available programmatically:
```bash
barn version --output=json
# Output: {"version": "1.2.3", "commit": "abc123", "built_at": "2026-01-21T10:00:00Z"}
```
---
## Next Steps
- [CI/CD](ci-cd.md) - Automated release workflow details
- [Distribution](distribution.md) - Package manager updates
+750
View File
@@ -0,0 +1,750 @@
# Automated Testing
This document describes the automated testing strategy, test structure, and how to run tests for Barn.
---
## Overview
| Test Type | Purpose | Location |
|-----------|---------|----------|
| Unit Tests | Test individual functions and classes | `src/test/kotlin/unit/` |
| Integration Tests | Test component interactions | `src/test/kotlin/integration/` |
| End-to-End Tests | Test full CLI workflows | `src/test/kotlin/e2e/` |
| Native Image Tests | Verify native binary behavior | `src/test/kotlin/native/` |
---
## Running Tests
### All Tests
```bash
./gradlew test
```
### Specific Test Types
```bash
# Unit tests only
./gradlew test --tests "com.samsonmedia.barn.unit.*"
# Integration tests only
./gradlew test --tests "com.samsonmedia.barn.integration.*"
# End-to-end tests only
./gradlew test --tests "com.samsonmedia.barn.e2e.*"
```
### Single Test Class
```bash
./gradlew test --tests "com.samsonmedia.barn.unit.JobManagerTest"
```
### Single Test Method
```bash
./gradlew test --tests "com.samsonmedia.barn.unit.JobManagerTest.shouldCreateJobDirectory"
```
### With Verbose Output
```bash
./gradlew test --info
```
### Continuous Testing (Watch Mode)
```bash
./gradlew test --continuous
```
---
## Test Structure
```
src/test/kotlin/
com/samsonmedia/barn/
unit/
JobManagerTest.kt
ConfigParserTest.kt
StateFileTest.kt
RetryPolicyTest.kt
CleanupServiceTest.kt
integration/
ServiceIntegrationTest.kt
IpcCommunicationTest.kt
FilesystemStateTest.kt
ProcessManagementTest.kt
e2e/
CliRunCommandTest.kt
CliStatusCommandTest.kt
CliServiceCommandTest.kt
CliCleanCommandTest.kt
native/
NativeBinaryTest.kt
NativeServiceTest.kt
fixtures/
TestFixtures.kt
MockProcessExecutor.kt
testutil/
TempDirectoryExtension.kt
ServiceTestExtension.kt
```
---
## Unit Tests
Unit tests verify individual components in isolation.
### Characteristics
- Fast execution (milliseconds)
- No filesystem or network access
- Dependencies are mocked
- Run on every commit
### Example: JobManagerTest
```kotlin
class JobManagerTest {
@Test
fun `should generate unique job IDs`() {
val manager = JobManager(MockFileSystem())
val job1 = manager.createJob(Command("echo hello"))
val job2 = manager.createJob(Command("echo world"))
assertNotEquals(job1.id, job2.id)
}
@Test
fun `should set initial state to queued`() {
val manager = JobManager(MockFileSystem())
val job = manager.createJob(Command("echo hello"))
assertEquals(JobState.QUEUED, job.state)
}
@Test
fun `should record creation timestamp`() {
val clock = MockClock(Instant.parse("2026-01-21T10:00:00Z"))
val manager = JobManager(MockFileSystem(), clock)
val job = manager.createJob(Command("echo hello"))
assertEquals("2026-01-21T10:00:00Z", job.createdAt)
}
}
```
### Example: RetryPolicyTest
```kotlin
class RetryPolicyTest {
@Test
fun `should calculate exponential backoff delay`() {
val policy = RetryPolicy(
maxRetries = 3,
initialDelay = Duration.ofSeconds(30),
backoffMultiplier = 2.0
)
assertEquals(Duration.ofSeconds(30), policy.delayFor(retryCount = 0))
assertEquals(Duration.ofSeconds(60), policy.delayFor(retryCount = 1))
assertEquals(Duration.ofSeconds(120), policy.delayFor(retryCount = 2))
}
@Test
fun `should not retry when max retries exceeded`() {
val policy = RetryPolicy(maxRetries = 3)
assertTrue(policy.shouldRetry(retryCount = 2))
assertFalse(policy.shouldRetry(retryCount = 3))
}
}
```
---
## Integration Tests
Integration tests verify component interactions with real filesystem operations.
### Characteristics
- Uses temporary directories
- Tests actual file I/O
- May spawn subprocesses
- Slower than unit tests (seconds)
### Example: FilesystemStateTest
```kotlin
@ExtendWith(TempDirectoryExtension::class)
class FilesystemStateTest {
@TempDir
lateinit var tempDir: Path
@Test
fun `should persist job state to filesystem`() {
val stateManager = FilesystemStateManager(tempDir)
val jobId = "job-12345"
stateManager.writeState(jobId, JobState.RUNNING)
val stateFile = tempDir.resolve("jobs/$jobId/state")
assertTrue(stateFile.exists())
assertEquals("running", stateFile.readText())
}
@Test
fun `should atomically update state files`() {
val stateManager = FilesystemStateManager(tempDir)
val jobId = "job-12345"
// Simulate concurrent updates
val threads = (1..10).map { i ->
thread {
stateManager.writeState(jobId, JobState.RUNNING)
}
}
threads.forEach { it.join() }
// File should be valid (not corrupted)
val state = stateManager.readState(jobId)
assertEquals(JobState.RUNNING, state)
}
}
```
### Example: ProcessManagementTest
```kotlin
@ExtendWith(TempDirectoryExtension::class)
class ProcessManagementTest {
@TempDir
lateinit var tempDir: Path
@Test
fun `should capture stdout to log file`() {
val executor = ProcessExecutor(tempDir)
val jobId = "job-12345"
val result = executor.run(jobId, Command("echo", "hello world"))
val stdout = tempDir.resolve("jobs/$jobId/logs/stdout.log")
assertEquals("hello world\n", stdout.readText())
}
@Test
fun `should record exit code`() {
val executor = ProcessExecutor(tempDir)
val jobId = "job-12345"
executor.run(jobId, Command("sh", "-c", "exit 42"))
val exitCode = tempDir.resolve("jobs/$jobId/exit_code")
assertEquals("42", exitCode.readText())
}
@Test
fun `should update heartbeat during execution`() {
val executor = ProcessExecutor(tempDir, heartbeatInterval = Duration.ofMillis(100))
val jobId = "job-12345"
executor.run(jobId, Command("sleep", "0.5"))
val heartbeat = tempDir.resolve("jobs/$jobId/heartbeat")
// Heartbeat should have been updated multiple times
assertTrue(heartbeat.exists())
}
}
```
---
## End-to-End Tests
E2E tests verify complete CLI workflows.
### Characteristics
- Tests the actual `barn` binary or JAR
- Simulates real user commands
- Validates output format (human, JSON, XML)
- Slowest tests (seconds to minutes)
### Example: CliRunCommandTest
```kotlin
@ExtendWith(ServiceTestExtension::class)
class CliRunCommandTest {
@Test
fun `should run command and return job ID`() {
val result = barn("run", "echo", "hello")
assertEquals(0, result.exitCode)
assertContains(result.stdout, "job-")
assertContains(result.stdout, "queued")
}
@Test
fun `should support JSON output`() {
val result = barn("run", "--output=json", "echo", "hello")
val json = Json.parseToJsonElement(result.stdout)
assertTrue(json.jsonObject.containsKey("job_id"))
assertEquals("queued", json.jsonObject["state"]?.jsonPrimitive?.content)
}
@Test
fun `should apply custom tag`() {
val result = barn("run", "--tag=download", "--output=json", "echo", "hello")
val json = Json.parseToJsonElement(result.stdout)
assertEquals("download", json.jsonObject["tag"]?.jsonPrimitive?.content)
}
@Test
fun `should work in offline mode without service`() {
val result = barn("run", "--offline", "echo", "hello")
assertEquals(0, result.exitCode)
assertContains(result.stdout, "job-")
}
private fun barn(vararg args: String): ProcessResult {
return ProcessBuilder("./build/libs/barn.jar", *args)
.redirectErrorStream(true)
.start()
.waitFor(30, TimeUnit.SECONDS)
}
}
```
### Example: CliStatusCommandTest
```kotlin
@ExtendWith(ServiceTestExtension::class)
class CliStatusCommandTest {
@Test
fun `should list all jobs`() {
// Create some jobs
barn("run", "--offline", "echo", "job1")
barn("run", "--offline", "echo", "job2")
val result = barn("status")
assertEquals(0, result.exitCode)
assertContains(result.stdout, "job-")
}
@Test
fun `should filter by tag`() {
barn("run", "--offline", "--tag=download", "echo", "job1")
barn("run", "--offline", "--tag=transcode", "echo", "job2")
val result = barn("status", "--tag=download", "--output=json")
val json = Json.parseToJsonElement(result.stdout)
val jobs = json.jsonObject["jobs"]?.jsonArray
assertEquals(1, jobs?.size)
}
@Test
fun `should show empty state gracefully`() {
val result = barn("status")
assertEquals(0, result.exitCode)
assertContains(result.stdout, "No jobs found")
}
}
```
---
## Native Image Tests
Tests that verify the GraalVM native binary works correctly.
### Characteristics
- Requires native image to be built first
- Tests startup time
- Verifies reflection configuration
- Platform-specific
### Running Native Tests
```bash
# Build native image first
./gradlew nativeCompile
# Run native-specific tests
./gradlew nativeTest
```
### Example: NativeBinaryTest
```kotlin
class NativeBinaryTest {
private val nativeBinary = Path.of("build/native/nativeCompile/barn")
@BeforeAll
fun checkBinaryExists() {
assumeTrue(nativeBinary.exists(), "Native binary not found. Run ./gradlew nativeCompile first.")
}
@Test
fun `should start within 100ms`() {
val start = System.currentTimeMillis()
val process = ProcessBuilder(nativeBinary.toString(), "--version")
.start()
process.waitFor(5, TimeUnit.SECONDS)
val elapsed = System.currentTimeMillis() - start
assertTrue(elapsed < 100, "Startup took ${elapsed}ms, expected < 100ms")
}
@Test
fun `should display version`() {
val result = runNative("--version")
assertEquals(0, result.exitCode)
assertMatches(Regex("barn \\d+\\.\\d+\\.\\d+"), result.stdout)
}
@Test
fun `should handle JSON serialization`() {
val result = runNative("status", "--output=json", "--offline")
assertEquals(0, result.exitCode)
// Verify JSON is valid (reflection config is correct)
assertDoesNotThrow { Json.parseToJsonElement(result.stdout) }
}
private fun runNative(vararg args: String): ProcessResult {
return ProcessBuilder(nativeBinary.toString(), *args)
.redirectErrorStream(true)
.start()
.let { process ->
process.waitFor(30, TimeUnit.SECONDS)
ProcessResult(
exitCode = process.exitValue(),
stdout = process.inputStream.bufferedReader().readText()
)
}
}
}
```
---
## Test Fixtures
### TestFixtures.kt
```kotlin
object TestFixtures {
fun createTestJob(
id: String = "job-${UUID.randomUUID().toString().take(5)}",
state: JobState = JobState.QUEUED,
tag: String? = null,
createdAt: Instant = Instant.now()
): Job {
return Job(
id = id,
state = state,
tag = tag,
createdAt = createdAt.toString(),
command = Command("echo", "test")
)
}
fun createTestConfig(
maxConcurrentJobs: Int = 4,
maxRetries: Int = 3,
cleanupMaxAgeHours: Int = 72
): Config {
return Config(
service = ServiceConfig(maxConcurrentJobs = maxConcurrentJobs),
jobs = JobsConfig(maxRetries = maxRetries),
cleanup = CleanupConfig(maxAgeHours = cleanupMaxAgeHours)
)
}
fun createJobDirectory(baseDir: Path, jobId: String, state: JobState = JobState.QUEUED): Path {
val jobDir = baseDir.resolve("jobs/$jobId")
jobDir.createDirectories()
jobDir.resolve("state").writeText(state.name.lowercase())
jobDir.resolve("created_at").writeText(Instant.now().toString())
return jobDir
}
}
```
### MockProcessExecutor.kt
```kotlin
class MockProcessExecutor : ProcessExecutor {
private val executions = mutableListOf<Execution>()
private val results = mutableMapOf<String, ProcessResult>()
fun whenCommand(pattern: String, result: ProcessResult) {
results[pattern] = result
}
override fun execute(command: Command): ProcessResult {
executions.add(Execution(command, Instant.now()))
val matchingResult = results.entries.find { (pattern, _) ->
command.toString().contains(pattern)
}?.value
return matchingResult ?: ProcessResult(exitCode = 0, stdout = "", stderr = "")
}
fun verifyExecuted(pattern: String) {
assertTrue(
executions.any { it.command.toString().contains(pattern) },
"Expected command matching '$pattern' to be executed"
)
}
data class Execution(val command: Command, val timestamp: Instant)
}
```
---
## Test Extensions
### TempDirectoryExtension
```kotlin
class TempDirectoryExtension : BeforeEachCallback, AfterEachCallback {
private val tempDirs = mutableMapOf<ExtensionContext, Path>()
override fun beforeEach(context: ExtensionContext) {
val tempDir = Files.createTempDirectory("barn-test-")
tempDirs[context] = tempDir
// Inject into test instance
context.testInstance.ifPresent { instance ->
instance.javaClass.declaredFields
.filter { it.isAnnotationPresent(TempDir::class.java) }
.forEach { field ->
field.isAccessible = true
field.set(instance, tempDir)
}
}
}
override fun afterEach(context: ExtensionContext) {
tempDirs.remove(context)?.let { dir ->
dir.toFile().deleteRecursively()
}
}
}
```
### ServiceTestExtension
```kotlin
class ServiceTestExtension : BeforeAllCallback, AfterAllCallback {
private var serviceProcess: Process? = null
override fun beforeAll(context: ExtensionContext) {
// Start barn service in test mode
serviceProcess = ProcessBuilder("./gradlew", "run", "--args=service start --test-mode")
.start()
// Wait for service to be ready
retry(maxAttempts = 10, delay = Duration.ofMillis(500)) {
val result = ProcessBuilder("./gradlew", "run", "--args=service status")
.start()
.waitFor(5, TimeUnit.SECONDS)
result == 0
}
}
override fun afterAll(context: ExtensionContext) {
serviceProcess?.destroyForcibly()
}
}
```
---
## CI Integration
### Test Reporting
Test results are published as artifacts in CI:
```yaml
- name: Run tests
run: ./gradlew test
- name: Upload test results
uses: actions/upload-artifact@v4
if: always()
with:
name: test-results
path: |
build/reports/tests/
build/test-results/
```
### Code Coverage
```bash
# Generate coverage report
./gradlew jacocoTestReport
# Check coverage thresholds
./gradlew jacocoTestCoverageVerification
```
Coverage thresholds in `build.gradle.kts`:
```kotlin
tasks.jacocoTestCoverageVerification {
violationRules {
rule {
limit {
minimum = "0.80".toBigDecimal() // 80% line coverage
}
}
}
}
```
### Test Matrix
Tests run on all supported platforms in CI:
| Platform | JVM Tests | Native Tests |
|----------|-----------|--------------|
| Linux x64 | Yes | Yes |
| Linux ARM64 | Yes | Yes |
| macOS x64 | Yes | Yes |
| macOS ARM64 | Yes | Yes |
| Windows x64 | Yes | Yes |
---
## Best Practices
### Naming Conventions
```kotlin
// Use backticks with descriptive names
@Test
fun `should create job directory when running command`() { }
@Test
fun `should fail gracefully when service unavailable`() { }
@Test
fun `should retry failed job up to max retries`() { }
```
### Test Organization
```kotlin
class JobManagerTest {
// Group related tests
@Nested
inner class `when creating jobs` {
@Test
fun `should generate unique ID`() { }
@Test
fun `should set initial state to queued`() { }
}
@Nested
inner class `when job fails` {
@Test
fun `should record exit code`() { }
@Test
fun `should schedule retry if policy allows`() { }
}
}
```
### Assertions
```kotlin
// Prefer specific assertions
assertEquals(JobState.RUNNING, job.state)
assertTrue(job.startedAt != null)
assertContains(output, "job-")
// Avoid generic assertions
assertTrue(job.state == JobState.RUNNING) // Less informative on failure
```
---
## Troubleshooting
### Tests Fail on Windows
Check line endings:
```bash
git config core.autocrlf input
```
### Flaky Tests
Use retry for inherently flaky operations:
```kotlin
@Test
@RetryingTest(3)
fun `should handle concurrent access`() { }
```
### Slow Tests
Tag slow tests and exclude from fast feedback loop:
```kotlin
@Tag("slow")
@Test
fun `should handle large file processing`() { }
```
```bash
# Run without slow tests
./gradlew test -PexcludeTags=slow
```
---
## Next Steps
- [Manual Testing](testing-manual.md) - Manual test procedures
- [Development Guide](development.md) - Setting up dev environment
+840
View File
@@ -0,0 +1,840 @@
# Manual Testing
This document provides step-by-step procedures for manually testing Barn functionality.
---
## Overview
Manual testing is essential for:
- Verifying user-facing behavior
- Testing platform-specific features
- Exploratory testing
- Release validation
---
## Test Environment Setup
### Prerequisites
1. Build the barn binary:
```bash
./gradlew nativeCompile
```
2. Add to PATH (optional):
```bash
export PATH=$PATH:$(pwd)/build/native/nativeCompile
```
3. Create a clean test directory:
```bash
rm -rf /tmp/barn
mkdir -p /tmp/barn
```
### Verify Installation
```bash
barn --version
# Expected: barn 1.x.x
barn --help
# Expected: Usage information
```
---
## Service Management Tests
### Test: Start Service
**Steps:**
1. Ensure service is not running:
```bash
barn service status
```
2. Start the service:
```bash
barn service start
```
3. Verify service is running:
```bash
barn service status
```
**Expected:**
- Status shows "running"
- Process ID is displayed
- No error messages
**Verify:**
```bash
# Check process exists
ps aux | grep barn
# Check IPC socket created (Unix)
ls -la /tmp/barn/barn.sock
# Check logs
cat /tmp/barn/logs/barn.log
```
---
### Test: Stop Service
**Steps:**
1. Ensure service is running
2. Stop the service:
```bash
barn service stop
```
3. Verify service stopped:
```bash
barn service status
```
**Expected:**
- Status shows "stopped" or "not running"
- Process no longer exists
---
### Test: Restart Service
**Steps:**
1. Start the service
2. Note the PID:
```bash
barn service status
```
3. Restart:
```bash
barn service restart
```
4. Verify new PID:
```bash
barn service status
```
**Expected:**
- Service restarts successfully
- New PID is different from old PID
---
### Test: Reload Configuration
**Steps:**
1. Start the service
2. Modify configuration:
```bash
echo "[cleanup]" >> /etc/barn/barn.conf
echo "max_age_hours = 24" >> /etc/barn/barn.conf
```
3. Reload:
```bash
barn service reload
```
4. Check logs for reload confirmation
**Expected:**
- Service continues running (same PID)
- Logs show "Configuration reloaded"
---
## Job Execution Tests
### Test: Run Simple Command
**Steps:**
1. Run a command:
```bash
barn run echo "hello world"
```
2. Note the job ID from output
3. Check job status:
```bash
barn status
```
**Expected:**
- Job ID is returned
- Status shows job as "succeeded"
- Exit code is 0
---
### Test: Run Command (JSON Output)
**Steps:**
```bash
barn run --output=json echo "hello world"
```
**Expected Output:**
```json
{
"job_id": "job-xxxxx",
"state": "queued",
"tag": null,
"created_at": "2026-01-21T10:00:00Z",
"exit_code": null
}
```
**Verify JSON is valid:**
```bash
barn run --output=json echo "hello" | jq .
```
---
### Test: Run Command with Tag
**Steps:**
```bash
barn run --tag=download curl -o /tmp/test.txt https://example.com
barn status --tag=download
```
**Expected:**
- Job is tagged with "download"
- Filtering by tag shows only matching jobs
---
### Test: Run Long-Running Command
**Steps:**
1. Start a long command:
```bash
barn run sleep 30
```
2. Immediately check status:
```bash
barn status
```
3. Verify heartbeat updates:
```bash
watch -n 1 'cat /tmp/barn/jobs/job-*/heartbeat'
```
**Expected:**
- Job shows as "running"
- Heartbeat timestamp updates every few seconds
---
### Test: Run Failing Command
**Steps:**
```bash
barn run --output=json sh -c "exit 1"
barn status
```
**Expected:**
- Job state is "failed"
- Exit code is 1
- Error file contains failure reason
**Verify files:**
```bash
cat /tmp/barn/jobs/job-*/exit_code
cat /tmp/barn/jobs/job-*/error
```
---
### Test: Run Command in Offline Mode
**Steps:**
1. Stop service if running:
```bash
barn service stop
```
2. Run with offline flag:
```bash
barn run --offline echo "offline test"
```
**Expected:**
- Command executes without service
- Job files created in /tmp/barn/jobs/
---
## Job Inspection Tests
### Test: Describe Job
**Steps:**
1. Run a command and note job ID
2. Get job details:
```bash
barn describe job-xxxxx
```
**Expected Output:**
```
Job ID: job-xxxxx
State: succeeded
Tag: -
Created: 2026-01-21T10:00:00Z
Started: 2026-01-21T10:00:01Z
Finished: 2026-01-21T10:00:02Z
Exit Code: 0
PID: 12345
Command:
echo hello world
Logs:
stdout: /tmp/barn/jobs/job-xxxxx/logs/stdout.log
stderr: /tmp/barn/jobs/job-xxxxx/logs/stderr.log
```
---
### Test: Describe Job (JSON)
**Steps:**
```bash
barn describe --output=json job-xxxxx
```
**Expected:**
- Valid JSON with all job fields
- Includes manifest, state, timestamps, logs
---
### Test: View Job Logs
**Steps:**
1. Run a command that produces output:
```bash
barn run sh -c "echo stdout; echo stderr >&2"
```
2. View logs:
```bash
cat /tmp/barn/jobs/job-xxxxx/logs/stdout.log
cat /tmp/barn/jobs/job-xxxxx/logs/stderr.log
```
**Expected:**
- stdout.log contains "stdout"
- stderr.log contains "stderr"
---
## Job Control Tests
### Test: Kill Running Job
**Steps:**
1. Start a long-running job:
```bash
barn run sleep 300
```
2. Note the job ID
3. Kill the job:
```bash
barn kill job-xxxxx
```
4. Verify:
```bash
barn describe job-xxxxx
```
**Expected:**
- Job state is "canceled"
- Process is terminated
- finished_at is recorded
---
### Test: Kill Non-Existent Job
**Steps:**
```bash
barn kill job-nonexistent
```
**Expected:**
- Error message: "Job not found: job-nonexistent"
- Exit code is non-zero
---
## Cleanup Tests
### Test: Clean Completed Jobs
**Steps:**
1. Run several jobs:
```bash
for i in 1 2 3; do barn run --offline echo "test $i"; done
```
2. Verify jobs exist:
```bash
ls /tmp/barn/jobs/
barn status
```
3. Clean up:
```bash
barn clean
```
4. Verify cleaned:
```bash
ls /tmp/barn/jobs/
barn status
```
**Expected:**
- Completed jobs are removed
- Job directories deleted
---
### Test: Clean with Dry Run
**Steps:**
```bash
barn clean --dry-run
```
**Expected:**
- Shows what would be deleted
- No actual deletion occurs
- Job directories still exist
---
### Test: Clean Jobs Older Than
**Steps:**
1. Create jobs with old timestamps (manual file manipulation):
```bash
# Create a job dir with old timestamp
mkdir -p /tmp/barn/jobs/job-old
echo "succeeded" > /tmp/barn/jobs/job-old/state
touch -d "2 days ago" /tmp/barn/jobs/job-old/finished_at
```
2. Clean with age filter:
```bash
barn clean --older-than=24h
```
**Expected:**
- Old jobs are removed
- Recent jobs are kept
---
### Test: Clean Including Failed Jobs
**Steps:**
1. Create a failed job:
```bash
barn run --offline sh -c "exit 1"
```
2. Default clean (should keep failed):
```bash
barn clean
barn status
```
3. Clean with include-failed:
```bash
barn clean --include-failed
barn status
```
**Expected:**
- Default clean preserves failed jobs
- --include-failed removes them
---
## Retry Behavior Tests
### Test: Automatic Retry on Failure
**Setup:**
Configure retries in barn.conf:
```toml
[jobs]
max_retries = 3
retry_delay_seconds = 5
```
**Steps:**
1. Create a script that fails twice then succeeds:
```bash
cat > /tmp/flaky.sh << 'EOF'
#!/bin/bash
COUNT_FILE="/tmp/flaky_count"
COUNT=$(cat $COUNT_FILE 2>/dev/null || echo 0)
COUNT=$((COUNT + 1))
echo $COUNT > $COUNT_FILE
if [ $COUNT -lt 3 ]; then
echo "Attempt $COUNT - failing"
exit 1
fi
echo "Attempt $COUNT - success"
exit 0
EOF
chmod +x /tmp/flaky.sh
rm -f /tmp/flaky_count
```
2. Run the flaky command:
```bash
barn run /tmp/flaky.sh
```
3. Wait for retries and check status:
```bash
watch barn status
```
**Expected:**
- Job retries automatically
- Eventually succeeds on 3rd attempt
- retry_count file shows retry history
---
### Test: Max Retries Exceeded
**Steps:**
1. Run a command that always fails:
```bash
barn run sh -c "exit 1"
```
2. Wait for all retries to exhaust
3. Check final status:
```bash
barn describe job-xxxxx
```
**Expected:**
- Job state is "failed"
- retry_count equals max_retries
- No more retry attempts
---
## Output Format Tests
### Test: Human-Readable Output (Default)
**Steps:**
```bash
barn status
```
**Expected:**
- Formatted table or list
- Human-readable timestamps
- Clear column headers
---
### Test: JSON Output
**Steps:**
```bash
barn status --output=json | jq .
```
**Expected:**
- Valid JSON
- Array of job objects
- ISO 8601 timestamps
---
### Test: XML Output
**Steps:**
```bash
barn status --output=xml | xmllint --format -
```
**Expected:**
- Valid XML
- Proper element structure
- XML declaration present
---
## Platform-Specific Tests
### Linux (systemd)
**Test: Service Integration**
```bash
# After installing .deb
sudo systemctl status barn
sudo systemctl start barn
sudo systemctl stop barn
sudo journalctl -u barn
```
### macOS (launchd)
**Test: Service Integration**
```bash
# After brew install
brew services list
brew services start barn
brew services stop barn
cat /usr/local/var/log/barn.log
```
### Windows (Service)
**Test: Service Integration**
```powershell
# After MSI install
Get-Service BarnService
Start-Service BarnService
Stop-Service BarnService
Get-EventLog -LogName Application -Source Barn
```
---
## Crash Recovery Tests
### Test: Service Crash Recovery
**Steps:**
1. Start service and create a long-running job:
```bash
barn service start
barn run sleep 300
```
2. Force-kill the service:
```bash
pkill -9 -f "barn service"
```
3. Restart service:
```bash
barn service start
```
4. Check orphaned job status:
```bash
barn status
```
**Expected:**
- Orphaned job detected
- State changed to "failed"
- exit_code set to "orphaned_process"
---
### Test: System Reboot Recovery
**Steps:**
1. Create a running job
2. Reboot the system
3. After reboot, start service and check status
**Expected:**
- Previous running jobs marked as failed/orphaned
- Service recovers cleanly
---
## Concurrent Access Tests
### Test: Multiple Simultaneous Jobs
**Steps:**
```bash
# Run 10 jobs in parallel
for i in $(seq 1 10); do
barn run --tag=batch sleep 5 &
done
wait
# Check status
barn status --tag=batch
```
**Expected:**
- All jobs execute (respecting max_concurrent_jobs)
- No file corruption
- All jobs complete successfully
---
### Test: Multiple CLI Clients
**Steps:**
1. Open two terminals
2. In terminal 1:
```bash
watch -n 0.5 barn status
```
3. In terminal 2:
```bash
for i in $(seq 1 20); do barn run echo $i; sleep 0.5; done
```
**Expected:**
- Status updates in real-time
- No IPC errors
- All jobs visible
---
## Update Tests
### Test: Check for Updates
**Steps:**
```bash
barn update --check
```
**Expected:**
- Shows current version
- Shows latest available version
- Indicates if update available
---
### Test: Perform Update
**Steps:**
```bash
sudo barn update
```
**Expected:**
- Downloads new binary
- Verifies checksum
- Replaces binary
- Restarts service if running
---
### Test: Rollback Update
**Steps:**
```bash
sudo barn update --rollback
barn --version
```
**Expected:**
- Previous version restored
- Service continues working
---
## Error Handling Tests
### Test: Invalid Command
**Steps:**
```bash
barn invalidcommand
```
**Expected:**
- Error message with suggestion
- Non-zero exit code
---
### Test: Missing Arguments
**Steps:**
```bash
barn run
```
**Expected:**
- Error: "Missing command to run"
- Usage hint displayed
---
### Test: Permission Denied
**Steps:**
```bash
# As non-root user
barn run --offline touch /root/test.txt
```
**Expected:**
- Job runs and fails
- Error captured in job's error file
- Exit code is non-zero
---
## Test Checklist
Use this checklist before each release:
### Basic Functionality
- [ ] `barn --version` shows correct version
- [ ] `barn --help` displays usage
- [ ] `barn service start/stop/status` works
- [ ] `barn run <cmd>` executes commands
- [ ] `barn status` lists jobs
- [ ] `barn describe <id>` shows job details
- [ ] `barn kill <id>` terminates jobs
- [ ] `barn clean` removes old jobs
### Output Formats
- [ ] Human-readable output is formatted correctly
- [ ] JSON output is valid
- [ ] XML output is valid
### Platform-Specific
- [ ] Linux: systemd integration works
- [ ] macOS: launchd integration works
- [ ] Windows: Service Control Manager works
### Error Handling
- [ ] Invalid commands show helpful errors
- [ ] Missing service shows clear message
- [ ] Permission errors are handled gracefully
### Recovery
- [ ] Service recovers from crash
- [ ] Orphaned jobs are detected
- [ ] State files are not corrupted
---
## Reporting Issues
When reporting bugs found during manual testing:
1. **Environment**: OS, version, architecture
2. **Steps to reproduce**: Exact commands run
3. **Expected behavior**: What should happen
4. **Actual behavior**: What actually happened
5. **Logs**: Relevant output and log files
6. **Screenshots**: If applicable
Submit issues at: https://github.com/samson-media/barn/issues
---
## Next Steps
- [Automated Testing](testing-automated.md) - Automated test suite
- [Development Guide](development.md) - Development setup