Compare commits

..
1 Commits
Author SHA1 Message Date
yukkop 92b2e579cc fix: matrix hardcode 2026-07-01 09:43:36 +00:00
3945 changed files with 45199 additions and 169005 deletions
@@ -1,41 +0,0 @@
---
# yamllint disable rule:line-length
name: check Nix download buffer
on: # yamllint disable-line rule:truthy
workflow_dispatch:
concurrency:
group: check-nix-download-buffer
cancel-in-progress: true
jobs:
check:
name: check Nix download buffer
runs-on: gross-nix-x86-perf
timeout-minutes: 20
env:
NIX_CONFIG: |
fallback = false
http2 = false
extra-substituters = https://cache.nixos.org https://cache.hectic-lab.com/hectic
trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= hectic:KMQsKow4SoA9K2vOJlOljmx7/Zpf91Yy+5qEtxDDCzA=
steps:
- name: Inspect Nix client
run: |
set -eu
nix --version
nix config show download-buffer-size
nix config show http2
nix config show fallback
nix config show substituters
- name: Ping Attic cache
run: |
set -eu
nix store ping --store https://cache.hectic-lab.com/hectic
- name: Download small cache path
run: |
set -eu
nix build --no-link --print-out-paths nixpkgs#hello
-86
View File
@@ -1,86 +0,0 @@
---
# yamllint disable rule:line-length
name: deploy hectic-lab
on: # yamllint disable-line rule:truthy
workflow_dispatch:
concurrency:
group: deploy-hectic-lab
cancel-in-progress: false
jobs:
deploy:
name: deploy hectic-lab with Attic cache
if: ${{ gitea.ref == 'refs/heads/master' }}
runs-on: nix
timeout-minutes: 435
env:
NIX_CONFIG: |
fallback = true
http2 = false
extra-substituters = https://cache.nixos.org https://cache.hectic-lab.com/hectic
trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= hectic:KMQsKow4SoA9K2vOJlOljmx7/Zpf91Yy+5qEtxDDCzA=
steps:
- name: Checkout dispatched revision
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
ref: ${{ gitea.sha }}
persist-credentials: false
- name: Show runner and cache configuration
run: |
set -eu
uname -a
nix --version
nix config show http2
nix config show fallback
nix config show download-buffer-size
nix config show substituters
- name: Configure SSH for hectic-lab
env:
HECTIC_LAB_SSH_PRIVATE_KEY: ${{ secrets.HECTIC_LAB_SSH_PRIVATE_KEY }}
HECTIC_LAB_SSH_KNOWN_HOSTS: ${{ secrets.HECTIC_LAB_SSH_KNOWN_HOSTS }}
run: |
set -eu
test -n "$HECTIC_LAB_SSH_PRIVATE_KEY"
test -n "$HECTIC_LAB_SSH_KNOWN_HOSTS"
ssh_home=$(mktemp -d)
trap 'rm -rf "$ssh_home"' EXIT
install -d -m 700 "$ssh_home/.ssh"
printf '%s\n' "$HECTIC_LAB_SSH_PRIVATE_KEY" > "$ssh_home/.ssh/id_ed25519"
printf '%s\n' "$HECTIC_LAB_SSH_KNOWN_HOSTS" > "$ssh_home/.ssh/known_hosts"
chmod 600 "$ssh_home/.ssh/id_ed25519" "$ssh_home/.ssh/known_hosts"
printf '%s\n' \
'Host hectic-lab' \
' HostName 128.140.75.58' \
' User root' \
" IdentityFile $ssh_home/.ssh/id_ed25519" \
' IdentitiesOnly yes' \
' StrictHostKeyChecking yes' \
" UserKnownHostsFile $ssh_home/.ssh/known_hosts" \
> "$ssh_home/.ssh/config"
chmod 600 "$ssh_home/.ssh/config"
printf '%s\n' "$ssh_home" > "$RUNNER_TEMP/hectic-lab-ssh-home"
- name: Deploy hectic-lab and save cache
env:
ATTIC_TOKEN: ${{ secrets.ATTIC_TOKEN }}
WITH_ATTIC_BUILD_TIMEOUT: "21600"
WITH_ATTIC_DRAIN_TIMEOUT: "3600"
WITH_ATTIC_UPLOAD_TIMEOUT: "600"
WITH_ATTIC_UPLOAD_RETRIES: "3"
WITH_ATTIC_BATCH_SIZE: "2"
run: |
set -eu
test -n "$ATTIC_TOKEN"
ssh_home=$(cat "$RUNNER_TEMP/hectic-lab-ssh-home")
trap 'rm -rf "$ssh_home"' EXIT
export HOME="$ssh_home"
export HECTIC_DEPLOY_SSH_CONFIG="$HOME/.ssh/config"
export NIX_SSHOPTS="-F $HOME/.ssh/config -o BatchMode=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$HOME/.ssh/known_hosts -o IdentitiesOnly=yes -i $HOME/.ssh/id_ed25519"
ssh -F "$HOME/.ssh/config" -o BatchMode=yes hectic-lab true
nix run --refresh '.#with-attic-cache' -- -- \
nix run --refresh '.#deploy' -- \
push -- --flake '.#hectic-lab|x86_64-linux' --target-host hectic-lab --use-remote-sudo
-113
View File
@@ -1,113 +0,0 @@
---
# yamllint disable rule:line-length
name: deploy neuro
on: # yamllint disable-line rule:truthy
workflow_dispatch:
inputs:
upload_cache:
description: Upload build outputs to Attic
required: false
type: boolean
default: true
runner_label:
description: Runner label for deploy job
required: false
type: choice
default: nix
options:
- nix
- gross-nix-x86-perf
- gross-nix-x86-highmem
concurrency:
group: deploy-neuro
cancel-in-progress: false
jobs:
deploy:
name: deploy neuro from performance node
if: ${{ gitea.ref == 'refs/heads/master' }}
runs-on: ${{ gitea.event.inputs.runner_label || 'nix' }}
timeout-minutes: 435
env:
NIX_CONFIG: |
fallback = true
http2 = false
extra-substituters = https://cache.nixos.org https://cache.hectic-lab.com/hectic
trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= hectic:KMQsKow4SoA9K2vOJlOljmx7/Zpf91Yy+5qEtxDDCzA=
steps:
- name: Checkout dispatched revision
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
ref: ${{ gitea.sha }}
persist-credentials: false
- name: Show runner and cache configuration
run: |
set -eu
uname -a
nix --version
nix config show http2
nix config show fallback
nix config show substituters
nix config show trusted-public-keys
- name: Deploy neuro
env:
ATTIC_TOKEN: ${{ secrets.ATTIC_TOKEN }}
UPLOAD_CACHE: ${{ inputs.upload_cache }}
WITH_ATTIC_BUILD_TIMEOUT: "21600"
WITH_ATTIC_DRAIN_TIMEOUT: "3600"
WITH_ATTIC_UPLOAD_TIMEOUT: "600"
WITH_ATTIC_BATCH_SIZE: "4"
NEURO_SSH_PRIVATE_KEY: ${{ secrets.NEURO_SSH_PRIVATE_KEY }}
NEURO_SSH_KNOWN_HOSTS: ${{ secrets.NEURO_SSH_KNOWN_HOSTS }}
run: |
set -eu
test -n "$NEURO_SSH_PRIVATE_KEY"
test -n "$NEURO_SSH_KNOWN_HOSTS"
ssh_home=$(mktemp -d)
trap 'rm -rf "$ssh_home"' EXIT
install -d -m 700 "$ssh_home/.ssh"
printf '%s\n' "$NEURO_SSH_PRIVATE_KEY" > "$ssh_home/.ssh/id_ed25519"
printf '%s\n' "$NEURO_SSH_KNOWN_HOSTS" > "$ssh_home/.ssh/known_hosts"
chmod 600 "$ssh_home/.ssh/id_ed25519" "$ssh_home/.ssh/known_hosts"
printf '%s\n' \
'Host neuro' \
' HostName 95.31.254.84' \
' User root' \
' Port 34457' \
" IdentityFile $ssh_home/.ssh/id_ed25519" \
' IdentitiesOnly yes' \
' StrictHostKeyChecking yes' \
" UserKnownHostsFile $ssh_home/.ssh/known_hosts" \
> "$ssh_home/.ssh/config"
chmod 600 "$ssh_home/.ssh/config"
export HOME="$ssh_home"
export HECTIC_DEPLOY_SSH_CONFIG="$HOME/.ssh/config"
export NIX_SSHOPTS="-F $HOME/.ssh/config -o BatchMode=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$HOME/.ssh/known_hosts -o IdentitiesOnly=yes -i $HOME/.ssh/id_ed25519"
ssh -F "$HOME/.ssh/config" -o BatchMode=yes -o ConnectTimeout=10 \
-o StrictHostKeyChecking=yes \
-o UserKnownHostsFile="$HOME/.ssh/known_hosts" \
-o IdentitiesOnly=yes \
-i "$HOME/.ssh/id_ed25519" \
neuro true
# Run deploy tool from checked-out Gitea revision; repository is not mirrored on GitHub.
case "$UPLOAD_CACHE" in
true)
nix run --refresh '.#with-attic-cache' -- -- \
nix run --refresh '.#deploy' -- \
push -- --flake '.#neuro|x86_64-linux' --target-host neuro
;;
false)
unset ATTIC_TOKEN
timeout --kill-after=60s 21600s \
nix run --refresh '.#deploy' -- \
push -- --flake '.#neuro|x86_64-linux' --target-host neuro
;;
*)
printf 'unsupported upload_cache value: %s\n' "$UPLOAD_CACHE" >&2
exit 64
;;
esac
+10 -11
View File
@@ -2,29 +2,28 @@ name: runner nix smoke
on:
workflow_dispatch:
push:
branches:
- master
paths:
- .gitea/workflows/runner-nix-smoke.yaml
- flake.lock
- flake.nix
- infra/gitea-runners/**
jobs:
smoke:
name: nix label and flake smoke
name: nix label smoke
runs-on: nix
env:
NIX_CONFIG: |
http2 = false
extra-substituters = https://cache.nixos.org https://cache.hectic-lab.com/hectic
extra-trusted-public-keys = hectic:KMQsKow4SoA9K2vOJlOljmx7/Zpf91Yy+5qEtxDDCzA=
steps:
- name: Checkout repository
uses: actions/checkout@v4.2.2
- name: Nix version and cache configuration
run: |
set -eu
nix --version
nix config show http2
nix config show substituters
nix config show trusted-public-keys
- name: Repository flake evaluation
run: |
set -eu
nix --option eval-cache false flake check --no-build --no-write-lock-file
nix flake check --no-build
@@ -2,6 +2,12 @@ name: runner ubuntu smoke
on:
workflow_dispatch:
push:
branches:
- master
paths:
- .gitea/workflows/runner-ubuntu-smoke.yaml
- infra/gitea-runners/**
jobs:
smoke:
+1 -15
View File
@@ -6,26 +6,12 @@ keys:
- &bfs-server age15yzgmsvl3ku2w863h6gw2vpmw37m9aruv6xrj4fue6n2jpm7pyuqk9xjmj
- &bfs-pol-server age1fpytf05sg9n6ywpwkmn09lhpfvgtud9h75h76jhxha475zpnasqq952rpu
- &bfs-new-server age17yx98qk9gzgcf2q6zhhp05p6mmtrkgz66dvyk9gqclypvlr8rersxjy5v7
- &neuro-server age1ak7heljpr0pjr4m0rcwxgn3sp0jjxw03lxyf33r8lcemqh2u2sgqx0aplq
- &neuro-server age15yzgmsvl3ku2w863h6gw2vpmw37m9aruv6xrj4fue6n2jpm7pyuqk9xjmj
- &games-server age15yzgmsvl3ku2w863h6gw2vpmw37m9aruv6xrj4fue6n2jpm7pyuqk9xjmj
- &hectic-lab-server age13h8twnwvgxn04l5ywtru89a6psw5d0uckr2eghxsjp88a5augvsstq5ard
- &umbriel-bfs age1jxntjca8q2vxvf2jaal4xyvm2ae6sh62fhv897694kuzawfrk5asj00zdt
creation_rules:
- path_regex: sus/neuro-project-zomboid.yaml$
key_groups:
- age:
- *yukkop
- *neuro-server
- age1ev53mzse6rg4ffwtcwtq4e93c7x7s4d0eyu89jrsahrke8r4yamsseu8h4
- path_regex: sus/neuro-minecraft.yaml$
key_groups:
- age:
- age1r25zdeqq8nac6dgca9en28r57ffyz9u9d8z5yc25gc8xqz747vaqmdtk0h
- age1ak7heljpr0pjr4m0rcwxgn3sp0jjxw03lxyf33r8lcemqh2u2sgqx0aplq
- age1ev53mzse6rg4ffwtcwtq4e93c7x7s4d0eyu89jrsahrke8r4yamsseu8h4
- path_regex: sus/home.xray.yaml$
key_groups:
- age:
-21
View File
@@ -1,21 +0,0 @@
{
flake,
self,
inputs,
system ? "aarch64-darwin",
...
}: let
name = builtins.baseNameOf ./.;
in inputs.nix-darwin.lib.darwinSystem {
inherit system;
specialArgs = { inherit flake self inputs; };
modules = [
inputs.home-manager.darwinModules.home-manager
{
networking.hostName = name;
nixpkgs.hostPlatform = system;
nixpkgs.overlays = [ self.overlays.default ];
}
./${name}.nix
];
}
-177
View File
@@ -1,177 +0,0 @@
{
flake,
pkgs,
lib,
...
}: let
name = "yukkop";
in {
system.primaryUser = name;
nix.settings.experimental-features = "nix-command flakes";
programs.zsh.enable = true;
services.openssh.enable = true;
users.users.${name} = {
home = "/Users/${name}";
openssh.authorizedKeys.keys = [
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIJf9ljuqny71bZJokebK4Ybfml0MFMCkApS+tbMdBudp u0_a472@localhost"
];
};
environment.systemPackages = with pkgs; [
aerospace
git
moreutils
neovim
tmux
];
launchd.user.agents.aerospace = {
serviceConfig = {
ProgramArguments = [
"${pkgs.aerospace}/Applications/AeroSpace.app/Contents/MacOS/AeroSpace"
];
RunAtLoad = true;
KeepAlive = true;
StandardOutPath = "/tmp/aerospace.out.log";
StandardErrorPath = "/tmp/aerospace.err.log";
};
};
home-manager.useGlobalPkgs = true;
home-manager.useUserPackages = true;
home-manager.backupFileExtension = "backup";
home-manager.sharedModules = [
(flake + "/home/module/program/tmux.nix")
];
home-manager.users.${name} = {
home.stateVersion = "25.11";
home.packages = with pkgs; [
iproute2mac
jujutsu
ripgrep
];
programs.git = {
enable = true;
lfs.enable = true;
settings = {
user.name = name;
user.email = "hectic.yukkop@gmail.com";
push.autoSetupRemote = true;
init.defaultBranch = "master";
};
};
programs.zsh = {
enable = true;
enableCompletion = true;
autosuggestion.enable = true;
syntaxHighlighting.enable = true;
history = {
size = 10000;
path = "$HOME/.zsh/.zsh_history";
};
shellAliases = {
drs = "darwin-rebuild switch --flake ~/pj/hearth#'yukkop|aarch64-darwin'";
nv = "nvim";
tmux = "tmux a";
};
initContent = ''
export PATH=/Users/yukkop/.opencode/bin:$PATH
'';
};
xdg.configFile."aerospace/aerospace.toml".text = ''
start-at-login = false
enable-normalization-flatten-containers = true
enable-normalization-opposite-orientation-for-nested-containers = true
default-root-container-layout = 'tiles'
default-root-container-orientation = 'auto'
accordion-padding = 30
on-focused-monitor-changed = ['move-mouse monitor-lazy-center']
automatically-unhide-macos-hidden-apps = false
[exec]
inherit-env-vars = true
[exec.env-vars]
PATH = '/run/current-system/sw/bin:/etc/profiles/per-user/yukkop/bin:/nix/var/nix/profiles/default/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:''${PATH}'
[gaps]
inner.horizontal = 8
inner.vertical = 8
outer.left = 8
outer.bottom = 8
outer.top = 8
outer.right = 8
[mode.main.binding]
alt-enter = 'exec-and-forget open -n /System/Applications/Utilities/Terminal.app'
alt-slash = 'layout tiles horizontal vertical'
alt-comma = 'layout accordion horizontal vertical'
alt-f = 'fullscreen'
alt-h = 'focus left'
alt-j = 'focus down'
alt-k = 'focus up'
alt-l = 'focus right'
alt-shift-h = 'move left'
alt-shift-j = 'move down'
alt-shift-k = 'move up'
alt-shift-l = 'move right'
alt-minus = 'resize smart -50'
alt-equal = 'resize smart +50'
alt-1 = 'workspace 1'
alt-2 = 'workspace 2'
alt-3 = 'workspace 3'
alt-4 = 'workspace 4'
alt-5 = 'workspace 5'
alt-6 = 'workspace 6'
alt-7 = 'workspace 7'
alt-8 = 'workspace 8'
alt-9 = 'workspace 9'
alt-shift-1 = 'move-node-to-workspace 1'
alt-shift-2 = 'move-node-to-workspace 2'
alt-shift-3 = 'move-node-to-workspace 3'
alt-shift-4 = 'move-node-to-workspace 4'
alt-shift-5 = 'move-node-to-workspace 5'
alt-shift-6 = 'move-node-to-workspace 6'
alt-shift-7 = 'move-node-to-workspace 7'
alt-shift-8 = 'move-node-to-workspace 8'
alt-shift-9 = 'move-node-to-workspace 9'
alt-tab = 'workspace-back-and-forth'
alt-shift-tab = 'move-workspace-to-monitor --wrap-around next'
alt-shift-semicolon = 'mode service'
[mode.service.binding]
esc = ['reload-config', 'mode main']
r = ['flatten-workspace-tree', 'mode main']
f = ['layout floating tiling', 'mode main']
b = ['balance-sizes', 'mode main']
backspace = ['close-all-windows-but-current', 'mode main']
alt-shift-h = ['join-with left', 'mode main']
alt-shift-j = ['join-with down', 'mode main']
alt-shift-k = ['join-with up', 'mode main']
alt-shift-l = ['join-with right', 'mode main']
'';
};
system.stateVersion = 6;
}
-1
View File
@@ -5,7 +5,6 @@
postgres-c = import ./postgres-c.nix { inherit self system pkgs; };
pure-c = import ./pure-c.nix { inherit self system pkgs; };
rust = import ./rust.nix { inherit self system pkgs; };
ratatui = import ./ratatui.nix { inherit self system pkgs; };
haskell = import ./haskell.nix { inherit self system pkgs; };
neuro = import ./neuro.nix { inherit self system pkgs; };
xmpp = import ./xmpp.nix { inherit self system pkgs; };
+9 -213
View File
@@ -5,217 +5,13 @@
exec ${pkgs.nix}/bin/nix run ${opentofuUnstable} -- "$@"
'';
packer = pkgs.stdenvNoCC.mkDerivation {
pname = "packer";
version = "1.16.0";
src = pkgs.fetchurl {
url = "https://releases.hashicorp.com/packer/1.16.0/packer_1.16.0_linux_amd64.zip";
hash = "sha256-XtzRSrWbU1BAxRLb7Nbsnvl2oACwc8Gdk+TEMclIWB4=";
};
nativeBuildInputs = [ pkgs.unzip ];
dontUnpack = true;
dontConfigure = true;
dontBuild = true;
installPhase = ''
install -d $out/bin
unzip -p $src packer > $out/bin/packer
chmod 755 $out/bin/packer
'';
};
buildMicroosSnapshots = pkgs.writeShellScriptBin "gitea-runners-build-microos-snapshots" ''
set -eu
: "''${HCLOUD_TOKEN:?HCLOUD_TOKEN is not set}"
architecture="''${1:-both}"
x86_location="''${GITEA_RUNNERS_X86_LOCATION:-nbg1}"
x86_server_type="''${GITEA_RUNNERS_X86_SERVER_TYPE:-cx23}"
case "$architecture" in
x86|arm|both) ;;
*)
printf 'usage: gitea-runners-build-microos-snapshots [x86|arm|both]\n' >&2
exit 2
;;
esac
workdir="$(mktemp -d)"
trap 'rm -rf "$workdir"' EXIT HUP INT TERM
ssh_private_key_file="$workdir/packer-ssh-key"
ssh-keygen -q -t ed25519 -N "" -f "$ssh_private_key_file"
: "''${GITEA_RUNNERS_IMAGE_SSH_PUBLIC_KEY_FILE:?GITEA_RUNNERS_IMAGE_SSH_PUBLIC_KEY_FILE is not set}"
image_public_key_file="$GITEA_RUNNERS_IMAGE_SSH_PUBLIC_KEY_FILE"
test -r "$image_public_key_file"
packer_public_key_b64="$(base64 -w0 "$ssh_private_key_file.pub")"
image_public_key_b64="$(base64 -w0 "$image_public_key_file")"
curl -fsSL \
https://raw.githubusercontent.com/kube-hetzner/terraform-hcloud-kube-hetzner/master/scripts/create.sh \
-o "$workdir/create.sh"
chmod +x "$workdir/create.sh"
(
cd "$workdir"
folder_name="runner-images" \
folder_path="$workdir" \
create_snapshots=none \
HCLOUD_TOKEN="$HCLOUD_TOKEN" \
"$workdir/create.sh"
)
packer_dir="$workdir/runner-images/packer"
"$packer_dir/scripts/install-verified-packer-plugin-hcloud.sh"
# Packer may try to remove its remote script after the image-writing reboot,
# while SSH is already unavailable. Keep that cleanup from aborting builds.
sed -i \
'/inline[[:space:]]*=[[:space:]]*\[local\.write_x86_image\]/a\ skip_clean = true' \
"$packer_dir/hcloud-microos-snapshots.pkr.hcl"
sed -i \
'/inline[[:space:]]*=[[:space:]]*\[local\.write_arm_image\]/a\ skip_clean = true' \
"$packer_dir/hcloud-microos-snapshots.pkr.hcl"
sed -i \
'/inline[[:space:]]*=[[:space:]]*\[local\.install_packages\]/a\ start_retry_timeout = "15m"' \
"$packer_dir/hcloud-microos-snapshots.pkr.hcl"
sed -i \
'/ssh_username[[:space:]]*=[[:space:]]*"root"/a\ temporary_key_pair_type = "ed25519"' \
"$packer_dir/hcloud-microos-snapshots.pkr.hcl"
awk \
-v ssh_private_key_file="$ssh_private_key_file" \
'/token[[:space:]]*=[[:space:]]*var[.]hcloud_token/ {
print
print " ssh_private_key_file = \"" ssh_private_key_file "\""
next
}
{ print }' \
"$packer_dir/hcloud-microos-snapshots.pkr.hcl" \
> "$packer_dir/hcloud-microos-snapshots.pkr.hcl.tmp"
mv "$packer_dir/hcloud-microos-snapshots.pkr.hcl.tmp" \
"$packer_dir/hcloud-microos-snapshots.pkr.hcl"
cat > "$workdir/image-key-injection.txt" <<'EOF'
partprobe /dev/sda || true
udevadm settle
root_device=""
for candidate in /dev/sda[0-9]*; do
if [ "$(blkid -s TYPE -o value "$candidate" 2>/dev/null || true)" = btrfs ]; then
root_device="$candidate"
break
fi
done
test -n "$root_device"
mount -o subvolid=5,rw "$root_device" /mnt
default_subvolume="$(btrfs subvolume get-default /mnt | awk 'NR == 1 { print $2 }')"
umount /mnt
mount -o subvolid="$default_subvolume",rw "$root_device" /mnt
btrfs property set -ts /mnt ro false || true
install -d -m 0755 /mnt/nix /mnt/var/lib/gcr-nix
install -d -m 0700 /mnt/root/.ssh
printf '%s' '__IMAGE_PUBLIC_KEY_B64__' | base64 -d > /mnt/root/.ssh/gcr_authorized_keys
printf '\n%s' '__PACKER_PUBLIC_KEY_B64__' | base64 -d >> /mnt/root/.ssh/gcr_authorized_keys
chmod 0600 /mnt/root/.ssh/gcr_authorized_keys
install -d -m 0755 /mnt/etc/ssh/sshd_config.d
printf '%s\n' 'PermitRootLogin prohibit-password' 'PubkeyAuthentication yes' 'AuthorizedKeysFile .ssh/authorized_keys .ssh/gcr_authorized_keys' > /mnt/etc/ssh/sshd_config.d/99-gcr-root.conf
chmod 0644 /mnt/etc/ssh/sshd_config.d/99-gcr-root.conf
sync
umount /mnt
EOF
sed -i "s|__PACKER_PUBLIC_KEY_B64__|$packer_public_key_b64|" \
"$workdir/image-key-injection.txt"
sed -i "s|__IMAGE_PUBLIC_KEY_B64__|$image_public_key_b64|" \
"$workdir/image-key-injection.txt"
awk -v inject_file="$workdir/image-key-injection.txt" \
'/rm -f \/root\/.ssh\/authorized_keys/ {
cleanup=1
}
cleanup && /sleep 1/ {
print
while ((getline line < inject_file) > 0) print line
close(inject_file)
cleanup=0
next
}
{ print }' \
"$packer_dir/hcloud-microos-snapshots.pkr.hcl" \
> "$packer_dir/hcloud-microos-snapshots.pkr.hcl.tmp"
mv "$packer_dir/hcloud-microos-snapshots.pkr.hcl.tmp" \
"$packer_dir/hcloud-microos-snapshots.pkr.hcl"
cat > "$workdir/cloud-init-cleanup.txt" <<'EOF'
cloud-init clean --logs --machine-id --seed --configs all || true
rm -rf /run/cloud-init/* /var/lib/cloud/*
EOF
awk -v cleanup_file="$workdir/cloud-init-cleanup.txt" \
'/# Cleanup some logs/ {
while ((getline line < cleanup_file) > 0) print "- [sh, -c, \"" line "\"]"
close(cleanup_file)
}
{ print }' \
"$packer_dir/hcloud-microos-snapshots.pkr.hcl" \
> "$packer_dir/hcloud-microos-snapshots.pkr.hcl.tmp"
mv "$packer_dir/hcloud-microos-snapshots.pkr.hcl.tmp" \
"$packer_dir/hcloud-microos-snapshots.pkr.hcl"
x86_base='https://download.opensuse.org/tumbleweed/appliances'
x86_file='openSUSE-MicroOS.x86_64-ContainerHost-OpenStack-Cloud.qcow2'
x86_url="$x86_base/$x86_file"
arm_base='https://download.opensuse.org/ports/aarch64/tumbleweed/appliances'
arm_file='openSUSE-MicroOS.aarch64-ContainerHost-OpenStack-Cloud.qcow2'
arm_url="$arm_base/$arm_file"
x86_sha="$(curl -fsSL "$x86_url.sha256" | awk '{print $1; exit}')"
arm_sha="$(curl -fsSL "$arm_url.sha256" | awk '{print $1; exit}')"
test -n "$x86_sha"
test -n "$arm_sha"
printf 'x86 digest: %s\n' "$x86_sha"
printf 'arm digest: %s\n' "$arm_sha"
(
cd "$packer_dir"
packer init hcloud-microos-snapshots.pkr.hcl
case "$architecture" in
x86)
packer build \
-only=hcloud.microos-x86-snapshot \
-var 'selinux_package_to_install=k3s' \
-var "x86_location=$x86_location" \
-var "x86_server_type=$x86_server_type" \
-var "opensuse_microos_x86_expected_sha256=$x86_sha" \
-var "opensuse_microos_arm_expected_sha256=$arm_sha" \
hcloud-microos-snapshots.pkr.hcl
;;
arm)
packer build \
-only=hcloud.microos-arm-snapshot \
-var 'selinux_package_to_install=k3s' \
-var "opensuse_microos_x86_expected_sha256=$x86_sha" \
-var "opensuse_microos_arm_expected_sha256=$arm_sha" \
hcloud-microos-snapshots.pkr.hcl
;;
both)
packer build \
-var 'selinux_package_to_install=k3s' \
-var "x86_location=$x86_location" \
-var "x86_server_type=$x86_server_type" \
-var "opensuse_microos_x86_expected_sha256=$x86_sha" \
-var "opensuse_microos_arm_expected_sha256=$arm_sha" \
hcloud-microos-snapshots.pkr.hcl
;;
esac
)
'';
giteaRunnersSetup = pkgs.writeShellScriptBin "gitea-runners-setup" /* sh */ ''
cat <<'EOF'
Gitea runners setup checklist
Tools available in this shell:
tofu, packer, gitea-runners-build-microos-snapshots [x86|arm|both], kubectl, kustomize,
kubeconform, sops, age, awscli2, hcloud,
tea, docker, skopeo, go-containerregistry, jq, yq-go, curl, git, openssh, nix
tofu, kubectl, kustomize, kubeconform, sops, age, awscli2, hcloud, tea,
docker, skopeo, go-containerregistry, jq, yq-go, curl, git, openssh, nix
Environment expected before real deploy/apply:
TF_VAR_hcloud_token
@@ -224,15 +20,18 @@ Environment expected before real deploy/apply:
S3 backend credentials and endpoint access
a matching SOPS age identity for sus/gitea-runners.yaml
kubectl access to the target cluster
a valid Hetzner Nix image ID in the controller host configuration
a concrete registry digest for the pushed Nix-capable runner image if enabling
the nix label
OpenTofu validation gate:
tofu version
tofu -chdir=infra/gitea-runners/opentofu validate
Nix image build/publish gate:
Nix image build/publish/digest gate:
nix build .#gitea-runner-nix-image
publish/import image, then set nixImageId / GCR_NIX_IMAGE_ID to its Hetzner ID
publish the archive, then pin the registry-reported digest in the runner label
mapping
nix:docker://gitea.hectic-lab.com/hectic-lab/gitea-runner-nix-image@sha256:<registry-digest>
SOPS token Secret creation gate:
kubectl apply -f infra/gitea-runners/k8s/namespace.yaml
@@ -269,7 +68,7 @@ Verification commands:
Main blockers and gates:
do not run tofu apply without all external inputs
do not apply the k8s overlay until the gitea-runner-token Secret exists
do not dispatch nix jobs until nixImageId / GCR_NIX_IMAGE_ID is valid
do not enable the nix label until the image has been published with a concrete digest
do not print, load, or require secrets on shell entry
EOF
'';
@@ -278,8 +77,6 @@ in pkgs.mkShell {
buildInputs = [
tofu
packer
buildMicroosSnapshots
giteaRunnersSetup
pkgs.nix
pkgs.kubectl
@@ -298,7 +95,6 @@ in pkgs.mkShell {
pkgs.curl
pkgs.git
pkgs.openssh
pkgs.unzip
];
shellHook = ''
-19
View File
@@ -1,19 +0,0 @@
{
self,
pkgs,
system
}: let
rustToolchain =
if builtins.pathExists ./rust-toolchain.toml
then pkgs.pkgsBuildHost.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml
else pkgs.pkgsBuildHost.rust-bin.stable."1.81.0".default;
in
self.devShells.${system}.default
// (pkgs.mkShell {
nativeBuildInputs = [
rustToolchain
pkgs.pkg-config
pkgs.gcc
pkgs.gnumake
];
})
-39
View File
@@ -1,42 +1,3 @@
# Documentation
- [Using the `hectic` Attic Cache](./attic-cache.md)
- [Minecraft incident log](./minecraft-incidents.md)
- [wowmine source versions and reset](./wowmine-reset.md)
- [Project Zomboid backups](./project-zomboid-backups.md)
- [Minecraft backups](./minecraft-backups.md)
- [Gitea Kanban CLI](./gitea-kanban-cli.md)
- [AFFiNE document typography](./affine-typography.md)
- [Native AFFiNE deployment and migration](./affine-native.md)
- [ChatGPT subscription connector for AFFiNE](./affine-chatgpt.md)
## Gitea runner labels
Common labels for controller-managed on-demand runners:
- `ubuntu-latest` — on-demand alias for `gross-x86`
- `nix` — on-demand Nix alias with 480-minute TTL
- `gross-x86` — x86 fallback chain `cx53` / `cx43` / `cx33`
- `gross-arm` — ARM fallback chain `cax41` / `cax31` / `cax21`
- `gross-x86-perf` — x86 performance chain `cx53` / `cpx62` / `cpx52`
- `gross-mixed-econ` — mixed chain `cx53` / `cax41` / `cx43`
- `gross-nix-x86` — `gross-x86` + Nix bootstrap
- `gross-nix-arm` — `gross-arm` + Nix bootstrap
- `gross-nix-x86-perf` — `gross-x86-perf` + Nix bootstrap
- `gross-nix-x86-highmem` — CCX53-only Nix runner, 480-minute TTL
- `gross-nix-mixed-econ` — `gross-mixed-econ` + Nix bootstrap
Region order for fallback: `nbg1`, then `fsn1`, then `hel1`.
The legacy Kubernetes persistent pool is disabled (`replicas: 0`) and has no
registered labels. All listed labels are handled by the VM controller. After a
successful job, a bootstrapped VM remains running and idle until its next hourly
lifetime boundary, capped by its original hard TTL. Before becoming generic
idle, its repository runner registration is disabled, deleted, and confirmed
absent. A queued job from any allowed repository may claim a VM with an exact
compatible server type, location, architecture, and image profile. The
controller rebuilds it from that clean image and registers a fresh runner
identity; reuse creates no second VM or budget reservation.
Operational details: `infra/gitea-runners/runbook.md` and
`package/gitea-runner-controller/decide.sh`.
-276
View File
@@ -1,276 +0,0 @@
# AFFiNE ChatGPT subscription connector
`affine-chatgpt` uses the official Sign in with ChatGPT preview flow. It does not
use browser cookies, another application's OAuth client, or an API-billing
fallback. Account eligibility and usage limits are controlled by OpenAI.
## Native service
The reusable NixOS module is `hectic.services.affine-chatgpt`. The hectic-lab
host enables it in `nixos/system/hectic-lab/affine-chatgpt.nix`.
- Unit: `affine-chatgpt.service`, running as `affine-chatgpt`.
- Listener: `127.0.0.1:3012`; no public port or Docker dependency.
- OAuth state: `/var/lib/affine-chatgpt/session`, mode `0700`.
- Credentials and stable gateway key: owner-only files, mode `0600`.
- Gateway key: `/var/lib/affine-chatgpt/gateway-key`.
Do not put credentials or key contents in Nix expressions, the Nix store,
environment variables, command arguments, logs, screenshots, or Git. The
service receives only the protected key's path. Keep the key stable: AFFiNE
stores its value as an encrypted workspace BYOK credential.
The service is deliberately not started when the OAuth credential file is
absent. Provision the state before starting it, using the service account's
ownership. Preserve the original private directory/file permissions.
## Authorize and move a session
On the computer running the user's regular browser:
```sh
nix run .#affine-chatgpt -- login
nix run .#affine-chatgpt -- status
nix run .#affine-chatgpt -- models
```
Open the printed OpenAI authorization URL in the normal browser, not a
temporary automation browser. Complete login, any passkey challenge, and app
consent. The loopback callback is `http://127.0.0.1:1455/auth/callback`; the
listener expires after 15 minutes unless `login --timeout` is specified.
For a self-hosted VM, securely transfer the complete credential record over
SSH. Create and persist a distinct VM host ID in `session/host.json`; do not
overwrite it with the laptop's host ID. Associate the imported credential's
`host_id` with that VM. Use the same issued client registration, not the
`dynamic_agent_client` registration entrypoint, for subsequent token exchanges.
After a successful remote model and inference test, remove the local active
credential record. Only the VM should rotate the imported refresh token.
Never copy a different application's credential record or session cookies.
Login and model-list success prove enrollment and catalog access, not working
inference. Require a streamed request ending with `response.completed` before
claiming that the subscription works.
## AFFiNE configuration
Configure these settings through AFFiNE's supported administrator API/UI, not
direct SQL or source-embedded secrets:
```json
{
"copilot.enabled": true,
"copilot.byok.enabled": true,
"copilot.byok.allowedProviders": ["openai"],
"copilot.byok.allowCustomEndpoint": true,
"copilot.byok.allowPrivateEndpoint": true
}
```
The native AFFiNE wrapper sets `DEPLOYMENT_TYPE=selfhosted`, required for custom
endpoints. The stable AFFiNE `private.key` must be preserved so stored BYOK
credentials remain decryptable.
Add a workspace BYOK provider:
- Provider: `openai`.
- Endpoint kind: `openai_compatible`.
- URL: `http://127.0.0.1:3012/v1`.
- Dialect: `responses`, not Chat Completions.
- Credential: the protected gateway key, not an OpenAI token.
- Model: a slug returned by the authorized account's catalog.
- Initial capabilities: text input/output and `tool_calling`, no attachments.
Persistent AFFiNE BYOK is workspace-wide. All authorized workspace members can
consume the connected account's limits and send document context/tool results
to OpenAI. User consent to shared access does not replace OpenAI's account and
subscription terms.
## Supported transport
The gateway authenticates requests before reading their bodies. It supports
`GET /v1/models` and `POST /v1/responses`, text history, function/custom tools,
and function-call results. AFFiNE executes tools; the gateway never executes
shell commands or document tools itself.
Upstream requests always use `store:false` and `stream:true`. Non-streaming
AFFiNE probes are assembled from completed SSE output items and the final
completion event. An explicitly non-SSE Content-Type is rejected; a missing
Content-Type is accepted only through the same strict SSE parser. Failed,
incomplete, malformed, or interrupted streams are not reported as successful.
Image generation, image/file/audio attachments, hosted MCP, Code Interpreter,
and persistent Responses conversation IDs are not supported. Do not declare
those capabilities in AFFiNE.
## Verification and development
```sh
nix build .#affine-chatgpt
nix build .#checks.x86_64-linux.affine-chatgpt-enrollment
nix build .#checks.x86_64-linux.affine-chatgpt-module
nix build .#checks.x86_64-linux.affine-model-picker
nix build .#affine-chatgpt.pythonEnv --out-link package/affine-chatgpt/.venv
pyright --project package/affine-chatgpt/pyrightconfig.json \
--pythonpath package/affine-chatgpt/.venv/bin/python3
```
Package checks use fake credentials and local HTTP fixtures only. Real smoke
tests should verify unauthenticated `401`, model filtering, text response,
function-call output, streamed completion, restart, and token refresh without
printing credentials. A successful direct gateway test is not proof that
AFFiNE's workspace provider and chat UI have been configured.
References:
- <https://developers.openai.com/siwc/token-sharing-open-source>
- <https://developers.openai.com/siwc/token-sharing-open-source/self-hosted-vms>
- <https://developers.openai.com/siwc/token-sharing-open-source/preview-limitations>
## hectic-lab deployment
The native service is active and the shared AFFiNE workspace has an enabled
`ChatGPT subscription` BYOK profile pointing at `http://127.0.0.1:3012/v1`.
The profile offers these account-catalog models, each with text input/output
and tool calling:
- `gpt-5.6-luna`
- `gpt-5.6-terra`
- `gpt-5.6-sol`
- `gpt-6-luna`
- `gpt-6-sol`
- `gpt-6-astra`
- `gpt-6.1-terra`
- `gpt-6.1-sol`
The existing first/default model remains `gpt-5.6-luna`. All eight models passed
AFFiNE's chat and tool-calling probes. A two-turn chat switched from
`gpt-5.6-luna` to `gpt-6.1-sol`; the second model recovered a random marker from
the first turn, confirming conversation history is retained across the switch.
The temporary test conversation was removed through AFFiNE's API. Model changes
use the existing workspace profile and do not replace its encrypted credential
or require another OAuth login. Reload an already-open client to refresh its
model catalog.
The pinned AFFiNE frontend originally exposed only managed route choices, which
are empty on self-hosted servers. `package/affine/byok-model-picker.patch` adds
workspace BYOK models to the existing Model menu and forwards the selected
profile/model separately from managed route IDs. Auto and managed selections
remain supported; retries retain the last request selection in memory.
BYOK discovery uses the existing owner/admin settings API. Owners and workspace
admins can choose these models in the patched selector; ordinary members retain
Auto and can use the shared default profile without gaining settings access.
No backend permission or Enterprise source code is changed.
The native module's optional `frontendPackage` mounts matching source-built
static assets read-only into the application service. Backend binaries and
migration units stay unchanged during this frontend-only rollout. Compatibility
checks require matching release and source revision. The host explicitly enables
this override; a standalone module with no override keeps its bundled frontend.
For a frontend-only rollout, build the static artifact and picker check, inspect
the host activation plan, then activate the host configuration normally:
```sh
nix build .#affine-frontend-static .#checks.x86_64-linux.affine-model-picker
nixos-rebuild switch --flake '.#hectic-lab|x86_64-linux'
```
Only `affine-native.service` should restart for a static-only change. Its
migration unit, dedicated PostgreSQL and Redis must keep their existing package
and restart triggers. Reload the client with a hard refresh after deployment to
discard cached frontend chunks.
### Verified picker rollout
The patched selector is deployed in NixOS generation
`1mvb1nb5xqhaj8xfskxi00lj39lmbpzl`. It binds frontend static package
`hrg3dkcacg5drizifiinjx481k6k33d5` over the unchanged native backend's static
directory. The activation restarted only AFFiNE; PostgreSQL, Redis and migration
unit process/state timestamps remained unchanged.
An authenticated headless browser verified all eight menu choices and selected
`gpt-6.1-sol`. The real selector returned the expected `profileId` and `modelId`
with no managed `routeTargetId`; the trigger displayed the selected model.
Open the AI input's Auto/current-model control, then its Model submenu. Use a
hard refresh (`Ctrl+F5`) if the old interface is still cached.
Account OAuth enrollment, remote catalog access, text generation, function
calls and streamed tool results were tested. AFFiNE's own provider probes and
chat SSE endpoint also passed, including automatic profile routing.
Only the server now owns the imported rotating session; the local active
credential copy was removed after remote verification. Images and attachments
remain unsupported and are not advertised by the profile.
## AFFiNE managed trial counter versus provider limits
`currentUser.copilot.quota { limit used }` describes AFFiNE's managed AI trial,
not the connected ChatGPT account's remaining usage. It must not be presented as
an OpenAI allowance or an invoice. BYOK execution is authorized independently
from quota-backed managed routes and records usage as `byok_server`.
The pinned release has a legacy accounting edge case: deleted sessions retain
`messageCost`, while the BYOK exemption query joins usage billing units to live
message rows. Removing test conversations can therefore leave a misleading
managed-trial cost after their BYOK message rows disappear. The observed `8/10`
was explained by eight such retained units; the connected provider's request
history was tagged BYOK, not AFFiNE-managed usage.
Do not fix this by resetting usage, promoting a plan, granting unlimited quota,
or weakening server enforcement. The raw quota and all provider/quota errors
remain unchanged. A self-hosted UI should instead identify AI as self-hosted
and explain that provider and server limits may apply, without a managed-trial
progress bar, Free badge or AFFiNE upgrade action. Cloud quota presentation
continues to use the original managed allowance.
ChatGPT subscription access is already paid for by the account owner; it is not
unlimited. OpenAI still enforces the account's model, usage-window and app-access
limits. This connector does not add an API-key billing fallback.
### Verified self-hosted usage rollout
On 2026-11-06, frontend static package
`3s22k6a5p9731xmlr6x33icilcsfkzv2-affine-frontend-static-0.27.4` was copied to
`hectic-lab` and mounted over the unchanged backend's static directory. This
was a bounded systemd override, **not** a NixOS generation switch: the active
and boot generation remain `6rb81fr95gngs99x1dvjw9vzzd7snkn5`. A whole-host
build was interrupted rather than activating unrelated package updates.
The root-owned persistent drop-in is
`/etc/systemd/system.control/affine-native.service.d/99-frontend-static-rollout.conf`.
It resets `BindReadOnlyPaths` and supplies only the new static bind. This
control directory is used because NixOS's `/etc/systemd/system` points into
the immutable store. GC roots `affine-frontend-static-rollout` and
`affine-frontend-static-rollback` under `/nix/var/nix/gcroots` retain the new
bundle and the previous `hrg3dkcacg5drizifiinjx481k6k33d5` bundle.
Only `affine-native.service` restarted. The migration unit's active timestamp,
PostgreSQL, Redis and ChatGPT gateway process IDs and active timestamps stayed
unchanged. The running application's mount namespace was checked against the
new package's `index.html`; HTTPS `/info` remained healthy. An authenticated
headless browser verified the sidebar and account settings on desktop and a
Pixel 5 viewport: neutral self-hosted text, no trial count, progress bar or
billing action, in both English and Russian. This stable release serves the
responsive web application to mobile browsers; upstream's separate mobile shell
is canary-only. The separate
mobile component is covered by the source-level rendering check.
A real BYOK text probe succeeded after deployment. AFFiNE's raw managed quota
remained `{ limit: 10, used: 8 }` before and after; no accounting records or
provider limits were altered. Existing browser sessions need a hard refresh.
The drop-in survives reboots and NixOS generation rollbacks, and masks future
declarative frontend changes until removed. During the next reviewed NixOS
switch containing the desired `frontendPackage`, remove this exact drop-in,
run `systemctl daemon-reload`, and restart only `affine-native.service` so the
declared bind takes effect. Remove the temporary GC roots only after checking
that the active generation retains the desired package and rollback retention
is no longer needed. Do not use a broad `systemctl revert` operation.
To roll back this bounded rollout while the original generation remains active,
remove that exact drop-in, daemon-reload and restart `affine-native.service`.
Its declared unit still binds the previous `hrg3dkcacg5drizifiinjx481k6k33d5`
bundle. Confirm health and the effective bind before removing any GC root.
-288
View File
@@ -1,288 +0,0 @@
# Native AFFiNE NixOS module
`hectic.services.affine` runs the source-built AFFiNE backend without Docker.
It is opt-in and uses distinct `affine-native` and `affine-native-migrate`
units, so enabling or importing the module does not alter an existing
`affine.service` or Compose deployment.
## Building and checking
The package targets `x86_64-linux` and pins AFFiNE 0.27.4. It builds the server,
Rust server-native binding, all three web/admin/mobile web bundles, and matching
Prisma 6.8.2 engines from source. Toolchains and dependency caches are fixed
inputs. No AFFiNE application binary or OCI image is used.
The backend license is marked unfree. For local development/testing, explicitly
allow evaluation without changing machine-wide Nixpkgs configuration:
```sh
NIXPKGS_ALLOW_UNFREE=1 nix build --impure .#affine --option post-build-hook ''
NIXPKGS_ALLOW_UNFREE=1 nix build --impure .#checks.x86_64-linux.affine-runtime --option post-build-hook ''
nix build .#checks.x86_64-linux.affine-module-basic --option post-build-hook ''
```
Do not publish server/native artifacts to a shared binary cache without checking
their redistribution terms. Allowing unfree evaluation does not grant production
or redistribution rights. The runtime check uses a fresh PostgreSQL 16 database,
pgvector, a non-superuser application role, and a private Redis instance. It tests
both migration passes, server startup, assets, administrator setup, authentication,
workspace creation, and disabled public signup.
## Runtime contract
The selected package must provide:
- `bin/affine-server`, the long-running backend;
- `bin/affine-migrate`, the full upstream predeploy sequence, including private
key setup, Prisma schema migrations, and AFFiNE data migrations.
Both units run as the static `affine-native` system user. systemd manages
`/var/lib/affine-native` with mode `0700`. `HOME` points there, so upstream uses
`/var/lib/affine-native/.affine/config` and
`/var/lib/affine-native/.affine/storage`.
The module writes an initial `config.json` only when none exists. It seeds the
external URL, server name, loopback listener, port, disabled public/OAuth
signup, and disabled copilot. Later admin-panel or manual edits are retained.
Use `settings` only to extend or override this initial seed.
## Isolated local example
This example deliberately creates a new database, Redis instance, state path,
and secret file. Do not point an initial native deployment at a production
AFFiNE database.
```nix
{ config, lib, pkgs, ... }:
{
nixpkgs.config.allowUnfreePredicate = package:
builtins.elem (lib.getName package) [ "affine" "affine-server-native" ];
services.postgresql = {
enable = true;
package = pkgs.postgresql_16;
ensureDatabases = [ "affine-native" ];
ensureUsers = [{
name = "affine-native";
ensureDBOwnership = true;
}];
extensions = ps: [ ps.pgvector ];
};
services.redis.servers.affine-native = {
enable = true;
port = 6388;
bind = "127.0.0.1";
};
# DATABASE_URL: postgresql://affine-native@localhost/affine-native?host=/run/postgresql
sops.secrets.affine-native-database-url = {};
sops.templates."affine-native.env" = {
owner = "affine-native";
group = "affine-native";
mode = "0400";
content = ''
DATABASE_URL=${config.sops.placeholder.affine-native-database-url}
'';
};
hectic.services.affine = {
enable = true;
environmentFile = config.sops.templates."affine-native.env".path;
externalUrl = "http://localhost:3011";
redisHost = "127.0.0.1";
redisPort = 6388;
};
# This example runs both dependencies locally, so order migration after them.
systemd.services.affine-native-migrate = {
after = [ "postgresql.service" "redis-affine-native.service" ];
requires = [ "postgresql.service" "redis-affine-native.service" ];
};
# pgvector is not a trusted extension; provision it as postgres, not the app role.
systemd.services.affine-native-database = {
requires = [ "postgresql.service" ];
after = [ "postgresql.service" ];
before = [ "affine-native-migrate.service" ];
requiredBy = [ "affine-native-migrate.service" ];
serviceConfig = {
Type = "oneshot";
User = "postgres";
RemainAfterExit = true;
};
script = ''
${pkgs.postgresql_16}/bin/psql --dbname=affine-native --set=ON_ERROR_STOP=1 \
--command='CREATE EXTENSION IF NOT EXISTS vector;'
'';
};
}
```
The module never creates PostgreSQL, pgvector, Redis, reverse-proxy, or
firewall configuration. `environmentFile` is required and is passed to systemd
at runtime; put `DATABASE_URL`, Redis credentials, and other secrets there,
never in Nix module values or the Nix store. Non-secret Redis host and port
options map to upstream `REDIS_SERVER_HOST` and `REDIS_SERVER_PORT`.
Default binding is `127.0.0.1:3011`. Perform initial administration through an
SSH tunnel, for example `ssh -L 3011:127.0.0.1:3011 host`, then browse to
`http://localhost:3011`. Add a reverse proxy separately only when remote access
is intended.
## Upgrades and rollback
`affine-native-migrate.service` is required by and ordered before
`affine-native.service`. Package or initial-seed changes restart the migration
unit before the app, and the package wrapper owns the complete upstream
predeploy procedure.
Database schema and AFFiNE data migrations are not reversed by switching to an
older NixOS generation. Back up the dedicated database and state directory
before upgrades. Production migration remains a separate, explicit operation.
AFFiNE backend source has its own license; review it before production use.
This module does not grant production authorization or alter upstream license
terms.
## hectic-lab host configuration
`nixos/system/hectic-lab/affine.nix` stages the reusable native module alongside
the original deployment. `hectic.affineDeployment.nativeActive` defaults to
`false`: the legacy Docker units and nginx port 3010 remain selected. The old
configuration is preserved in `affine-docker.nix` for staging and rollback.
Set `nativeActive = true` only after the final frozen-state restore and native
verification; this removes the legacy unit declarations and selects nginx port
3011. Source declarations alone are not evidence that production has migrated.
The host configuration intentionally uses isolated dependencies:
| Component | Unit | Endpoint/state |
| --- | --- | --- |
| AFFiNE | `affine-native.service` | `127.0.0.1:3011`, `/var/lib/affine-native` |
| Migration | `affine-native-migrate.service` | Same user, environment and state |
| PostgreSQL 16 | `affine-postgresql.service` | Unix socket `/run/affine-postgresql`, port 5433, `/var/lib/affine-postgresql` |
| Redis | `redis-affine.service` | `127.0.0.1:6388` |
| ChatGPT connector | `affine-chatgpt.service` | `127.0.0.1:3012`, separate protected state |
The database cluster does not listen on TCP and does not replace the host's
shared `postgresql.service`. It uses peer authentication, a non-superuser role
and database named `affine-native`, and pgvector `0.8.7` from the pinned
official release. PostgreSQL pre-creates `vector` and `pgcrypto` as its cluster
administrator. The cluster locale matches the existing Docker database's
`en_US.utf8`; do not silently substitute a different collation.
Both AFFiNE units are gated by `/var/lib/affine-native/environment`. Create that
file only after staging the correct database/config/storage. It must be
protected outside Git and the Nix store. Its required connection settings are:
```text
DATABASE_URL=postgresql://affine-native@localhost:5433/affine-native?host=/run/affine-postgresql
AFFINE_INDEXER_ENABLED=false
```
The database URL contains no password because the Unix socket uses peer auth.
The environment file may also carry secrets; treat the entire file as private.
## Docker-to-native migration procedure
1. Build the source package, exact pgvector version, native service units and
targeted checks before scheduling an outage. Inspect the activation plan;
do not restart the shared PostgreSQL cluster or unrelated Redis instances.
2. Inventory the running AFFiNE revision, database extensions/locale, workspace
and user counts, config/private key, storage file manifest and nginx route.
Never print secret values or document contents.
3. Make an owner-only custom-format PostgreSQL backup and config/storage
snapshot. Verify `pg_restore --list`, archive readability and checksums.
A listed archive is not a tested restore or an offsite backup.
4. Start only the dedicated PostgreSQL and Redis units. Restore a rehearsal
dump into their isolated database, preserving role ownership. Pre-created
extensions avoid giving the application superuser privileges. Use
`pg_restore --exit-on-error --no-owner --no-acl --no-comments
--role=affine-native`; investigate any error instead of ignoring it.
5. Copy the complete Docker config and storage to
`/var/lib/affine-native/.affine/{config,storage}`. Preserve `private.key`
byte-for-byte. Give the native account ownership and private permissions.
Update copied server/listen/port and Redis settings for native paths;
preserve authentication, external URL and all encryption material.
6. Run migration/startup against the rehearsal database and copied storage
only. Never point staging workers at the live Docker database/storage.
Verify `/info` reports `selfhosted` and compatibility `0.27.4`, then test
authenticated workspaces, representative documents and stored attachments.
7. Announce the write freeze. Stop all Docker AFFiNE application/worker writers
without deleting its PostgreSQL volume. Take a fresh final dump and final
config/storage snapshot after the freeze. Restore that final snapshot into
a clean native database; stop staging units before replacing state.
8. Start native migration and application units. Verify entity counts,
checksums, login, documents, attachments and readiness before switching
`hectic.affineDeployment.nativeActive` to `true` and nginx from port 3010 to
3011. Inspect the activation plan and test nginx configuration first.
9. Confirm the public HTTPS route, WebSockets/live editing and signup policy.
Confirm the cutover removed/disabled the old Docker `affine.service` and
`affine-frontend.service`. Retain their image/config/data and final snapshot;
do not delete old state as part of cutover.
10. Configure the [native ChatGPT connector](./affine-chatgpt.md) through AFFiNE's
administrator API/UI and verify an actual AFFiNE AI request, not only a
direct upstream probe.
Before native production writes, rollback can return nginx/application to the
frozen Docker state. After native writes begin, that state is stale: rollback
requires a new consistent export and compatible restore, not a proxy flip to
an old database. NixOS generation rollback alone does not restore application
data.
If SSH, package copying, extension build, rehearsal restore or verification is
blocked, leave the Docker production route intact. Do not create the runtime
environment marker or activate a half-prepared native application.
## Completed hectic-lab cutover: 2026-10-31
Production now explicitly sets `hectic.affineDeployment.nativeActive = true`.
The activated persistent NixOS generation is:
```text
/nix/store/6vp7qb6id8krb9l5ff1dkdi7nzxifhwd-nixos-system-hectic-lab-26.05.20261006.b253099
```
Final write-frozen backup:
```text
/var/backups/affine/native-cutover-20261031T231824Z
```
The backup directory is `0700`; database/config/storage archives are `0600`.
It includes the final database dump, verified archive listings, config and
storage snapshots, previous generation references, and matching before/after
data fingerprints. Keep it private. It is local recovery material, not an
offsite backup.
Cutover verification matched all rows/fingerprints in `users`, `workspaces`,
`workspace_members`, `workspace_pages`, `snapshots`, `updates`, and `blobs`:
5 users, 2 workspaces, 5 memberships, 44 pages, 53 snapshots, 0 pending update
rows, and 49 blob records. All 98 storage files (19,341,496 bytes) and the
original `private.key` were preserved. Rehearsal authenticated document bytes
and a 3,049,505-byte attachment matched the Docker source; final HTTPS login,
document reads, attachment retrieval and frontend assets passed.
The final `switch-to-configuration switch` completed successfully. The Docker
AFFiNE application/PostgreSQL/Redis containers are gone; their original
`/var/lib/affine` state remains retained. The host Docker daemon still serves
unrelated applications and was not removed.
The staging `test` activation encountered a pre-existing D-Bus reload timeout
(the journal also records it on 2026-10-10); the bus remained active and was
not restarted. The final cutover activation did not reload D-Bus and completed
successfully. Shared `postgresql.service` remained active throughout.
The native [ChatGPT connector](./affine-chatgpt.md) is enabled through the
workspace's persistent BYOK profile `ChatGPT subscription`. Text and function
probes were verified, and an actual AFFiNE SSE chat returned the expected
response with both explicit and automatic provider selection. Two authenticated
WebSocket connections joined the workspace and read identical document state
without writing documents.
After restarting both native AFFiNE and the connector, public login, document
and attachment reads, two-client WebSocket reads, and an automatic-routed AI
chat associated with an existing document passed again. Local validation also
passed 61 connector tests, Pyright with its Nix Python environment, and the
runtime, typography, native-module, production and connector Nix checks.
-75
View File
@@ -1,75 +0,0 @@
# AFFiNE document typography
The frontend source patch in `package/affine/gitea-document-typography.patch`
adopts Gitea README typography without replacing BlockSuite's document model.
At the default 16px body size, H1-H6 use 32, 24, 20, 16, 14 and 13.6px. Headings
use 1.25 line height, 24px/16px section spacing, and H1/H2 dividers. Body text
uses 1.5 line height and 16px paragraph spacing; nested lists remain compact.
Quotes and inline code retain native AFFiNE colors and formatting.
The scale and spacing are inspired by Gitea's MIT-licensed
[README markup stylesheet](https://github.com/go-gitea/gitea/blob/v1.27.3/web_src/css/markup/content.css).
This is an independently authored, scoped BlockSuite patch, not a wholesale
copy of that stylesheet; no vendored Gitea source files are changed.
The patch is limited to page mode. Canvas notes, embedded canvas previews and
database block trees retain their existing typography. Below 640px, page text
reflows to its viewport instead of following the intrinsic width of a wide
table. Tables and databases retain their native horizontal scrollers. The
existing sidebar toggle can be used to give the document the full phone width.
## Build and verify
```sh
nix build .#affine-frontend-static --option post-build-hook ''
NIXPKGS_ALLOW_UNFREE=1 nix build --impure .#checks.x86_64-linux.affine-typography --option post-build-hook ''
```
The browser check uses the real source-built frontend with an isolated backend
and anonymous, browser-local example documents. It covers light/dark desktop
and phone layouts, heading metrics, colored text/highlights, inline code,
editing, rich blocks, native canvas sizing and nested selector boundaries.
Screenshots and computed-size results are retained in the check output.
Fixture writes are restricted to the isolated loopback test server; the harness
does not accept a remote URL override.
The backend used by that check still requires explicit unfree evaluation.
## Current hectic-lab rollout
Since 2026-10-31, hectic-lab runs the source-built backend and patched frontend
together through `hectic.services.affine` and `affine-native.service`. Its
dedicated PostgreSQL, Redis and ChatGPT connector are native services as well.
There is no production AFFiNE container or `affine-frontend.service` mount.
See [native deployment and migration](./affine-native.md) for the cutover,
verification and backup record. The frontend patch remains part of the same
pinned AFFiNE source package; a read-only browser check after migration confirmed
the real document's H2 blocks retain the 24px scale.
## Historical Docker rollout
The following describes the earlier frontend-only rollout, retained for the
staging/rollback configuration. It is not the current production topology.
`affine-frontend-static` contains regular, copied web assets, including admin
and mobile directories and upstream license notices. It does not contain
symlinks into store paths that would be unavailable inside a container.
The existing Docker backend, database, Redis instance, image digests and data
paths remain unchanged. A companion `affine-frontend.service` applies a Compose
override mounting the source-built assets read-only at `/app/static`. It uses
`up --detach --no-deps --force-recreate affine`: only the application container
is reconciled. The main `affine.service` keeps its existing start/stop behavior.
Changing the frontend reloads the companion unit. Stopping/removing that unit
recreates the application from the base Compose configuration, restoring the
stock frontend. A restart of the parent stack reapplies the frontend afterward.
Database credentials and keys remain generated runtime state; no secret values
are embedded in the Nix store or repository by this frontend change.
Frontend and backend release versions must match; the NixOS configuration
asserts this before deployment.
Take a database/state backup before applying the first rollout, and verify that
PostgreSQL, Redis and migration container IDs remain unchanged. No database
upgrade or native-backend migration is part of this change. Application startup
may perform its usual background work; this is not a claim that the process
never writes to its database.
-93
View File
@@ -171,83 +171,6 @@ nix shell nixpkgs#attic-client -c attic cache info local:hectic
nix shell nixpkgs#attic-client -c attic login local https://cache.hectic-lab.com "<NEW_TOKEN>"
```
## Automatic uploads from trusted CI
The `deploy-neuro` workflow uses `with-attic-cache` around its deployment command:
```sh
# ATTIC_TOKEN must be supplied through a secret, not committed or printed.
nix run '.#with-attic-cache' -- -- nix build '.#my-package'
```
The wrapper installs a temporary Nix `post-build-hook`. Each successful local
build queues all output paths, including build-only dependencies and multiple
outputs. A separate worker uploads batches with `attic push --stdin --no-closure`
and two concurrent uploads. Pending outputs have registered garbage-collection
roots until uploaded. Substituted paths and the initial bootstrap of the wrapper
itself are not uploaded; this avoids copying the public NixOS cache into Attic.
The worker runs during the build and drains after success or failure. Uploads
have bounded retries; exhausted uploads fail an otherwise successful command.
If the build failed, its original exit status is preserved. Defaults are 30
minutes for the wrapped command, 10 minutes for the final drain, and three
120-second attempts per batch of up to 32 paths. These limits can be adjusted with
`WITH_ATTIC_BUILD_TIMEOUT`, `WITH_ATTIC_DRAIN_TIMEOUT`,
`WITH_ATTIC_UPLOAD_TIMEOUT`, `WITH_ATTIC_UPLOAD_RETRIES`, and
`WITH_ATTIC_BATCH_SIZE` (positive integer seconds/counts without leading zeros).
The heavier `deploy-neuro` workflow overrides these defaults: 6 hours for the
build/deploy command, batches of at most 8 paths, and 600 seconds per upload attempt. The
upload deadline covers the **whole batch**, not each individual path. Its final
drain is bounded at 1 hour; the 435-minute job budget leaves 15 minutes for setup
and cleanup. The `gross-nix-x86-perf` runner limit and Gitea's endless-task
watchdog are 8 hours. VM hard lifetime starts at allocation and has no controller
destruction grace. A prolonged cache outage can still exhaust the drain before
every queued path is uploaded.
The build timeout covers the entire wrapped command, not each derivation.
Completed outputs can be reused from the cache, but an interrupted CUDA/Magma
compilation does not produce a cacheable output or resume on the next ephemeral
runner. Exit code 124 with `interrupted by the user` can therefore mean the
wrapper deadline expired, not that someone manually cancelled the job.
The workflow also sets `fallback = true` in `NIX_CONFIG`, inherited by nested
Nix commands. If substitution fails, Nix can build the affected derivation from
source instead of aborting solely because the cache is unavailable. Caches and
signature checks remain enabled. Fallback cannot fix an unavailable upstream
source or a genuine compilation error, and rebuilding can consume more time.
Uploader logs report each attempt's batch size, whole-batch deadline and exit
status, distinguish deadline expiration from other failures, and list paths in
exhausted batches. The final summary counts queue records: acknowledged,
unconfirmed after exhausted attempts, pending and in flight. These are not
unique artifact counts: an unsuccessful batch may already have uploaded some
paths, and a successful retry can reuse those cached results.
This integration targets the root, single-user Nix environment on the ephemeral
runner. It refuses to replace an existing post-build hook. SIGINT/SIGTERM stop
the command and attempt a bounded drain; SIGKILL, VM destruction, or a hard
runner timeout cannot guarantee uploads. A failed upload remains a visible CI
failure, not a claim that the artifact was cached.
### CI credentials and rollout
- `ATTIC_TOKEN` is a Gitea repository secret for `hinterland/hearth`, passed only
to the deployment step. The workflow remains manual and restricted to `master`.
- The token grants pull/push only for `hectic`, without deletion or cache
administration. The current token expires **2027-09-09**; rotate it before then.
- The wrapper stores it in a private temporary `0600` file, references that file
from Attic configuration, and removes `ATTIC_TOKEN` from child environments.
Neither the hook nor `NIX_CONFIG` contains the token. Cleanup removes private
files after the worker stops.
- Never expose this credential to untrusted PR workflows or bake it into runner
images. A writer to this cache can publish artifacts trusted by its consumers.
- The `hectic` cache is public for reads. Build outputs must not contain secrets
or content that must remain private; the wrapper uploads every successful local
output, not just the final system.
- Workflow/package changes must be published to `master` before dispatched runs
use them. Creating the secret alone does not enable uploads in an existing run.
## Common issues
### `flake 'nixpkgs' does not provide attribute 'attic'`
@@ -276,22 +199,6 @@ Usually means:
- timeout/reverse proxy issue
- bad token permissions
On `hectic-lab`, the upload API has separate nginx locations for
`/_api/v1/upload-path` and `/next/_api/v1/upload-path`. Requests stream to Attic
without whole-body buffering, using HTTP/1.1 upstream and 600-second
`proxy_send_timeout` and `proxy_read_timeout` values. These are inactivity
timeouts, not an upload throughput guarantee. The CI wrapper still enforces its
own whole-batch deadline. The legacy `/previous/` endpoint stays read-only.
The host's Attic package also restricts its AWS SDK rustls connector to HTTP/1.1
after observed S3 `REFUSED_STREAM` failures. This is a reproducible, host-scoped
derived Cargo vendor tree; the pinned input tree and Cargo.lock are unchanged.
TLS certificate verification remains enabled. Nix clients now force HTTP/1.1 for
cache pulls because the cache endpoint has produced HTTP/2 framing errors; the
Attic upload client separately uses HTTP/1.1 upstream. The pinned crate path
makes upstream changes fail visibly during a future upgrade. This mitigates the
observed transport error, not every possible Hetzner S3 timeout.
### Cache pulls do not work
Check:
-141
View File
@@ -1,141 +0,0 @@
# Gitea Kanban CLI
`gitea-kanban` is the non-interactive interface for native Gitea Projects.
It shares its configuration, API client, models, permissions, and operations
with `gitea-kanban-tui`.
## Installation
The Nix package installs both binaries:
```sh
nix build .#gitea-kanban-tui
./result/bin/gitea-kanban --help
./result/bin/gitea-kanban-tui --help
```
For development:
```sh
cargo run --manifest-path package/gitea-kanban-tui/Cargo.toml \
--bin gitea-kanban -- --help
```
## Configuration
Configuration can be supplied with flags or environment variables. A project
selector is required, and exactly one selector must be supplied.
| Flag | Environment | Description |
| --- | --- | --- |
| `--url` | `GITEA_URL` | Gitea base URL |
| `--token-file PATH` | `GITEA_TOKEN_FILE` | File containing API token |
| — | `GITEA_TOKEN` | Token fallback when no token file is configured |
| `--project NAME` | `GITEA_PROJECT` | Exact, case-sensitive project name |
| `--project-id ID` | `GITEA_PROJECT_ID` | Project ID; useful for duplicate names |
| `OWNER` | `GITEA_OWNER` | Repository owner |
| `REPO` | `GITEA_REPO` | Repository name |
Precedence:
1. Command-line flags and positional arguments.
2. Token file from `--token-file` or `GITEA_TOKEN_FILE`.
3. `GITEA_TOKEN` when no token file is configured.
Token files must be regular files and must not be group- or world-readable on
Unix. Remote URLs must use HTTPS. Plain HTTP is accepted only for literal
loopback IP addresses (`127.0.0.1` or `::1`) during local development.
Example:
```sh
export GITEA_URL=https://gitea.example
export GITEA_TOKEN_FILE="$HOME/.config/gitea/token"
gitea-kanban --project Kanban owner repo board
```
## Commands
### `board`
Print selected project, columns, and issues:
```sh
gitea-kanban --project Kanban owner repo board
```
Output includes issue numbers and titles. Server-provided terminal control
characters are removed before output.
### `create`
Create an issue and assign it to selected project. The issue starts in the
project's default column.
```sh
gitea-kanban --project Kanban owner repo create \
--title "Fix deployment" \
--body "Investigate failed rollout"
```
### `edit`
Replace issue title and body. Issue must be assigned to selected project.
```sh
gitea-kanban --project Kanban owner repo edit 42 \
--title "Updated title" \
--body "Updated description"
```
### `move`
Move an issue to a project column. `ISSUE_ID` is the global Gitea issue ID,
not the repository issue number. `--sorting` is optional.
```sh
gitea-kanban --project Kanban owner repo move 123 --column-id 7
gitea-kanban --project Kanban owner repo move 123 --column-id 7 --sorting 2
```
### `comment`
Comments are managed on issues assigned to the selected project. Issue values
are repository issue numbers. Comment values are global Gitea comment IDs.
```sh
gitea-kanban --project Kanban owner repo comment list 42
gitea-kanban --project Kanban owner repo comment add 42 --body "Investigating"
gitea-kanban --project Kanban owner repo comment edit 42 9001 --body "Resolved"
gitea-kanban --project Kanban owner repo comment delete 42 9001 --yes
```
The CLI verifies that the issue belongs to the selected project and that the
comment belongs to that issue before editing or deleting it.
### `delete`
Delete an issue assigned to selected project. This is irreversible and requires
explicit confirmation with `--yes`:
```sh
gitea-kanban --project Kanban owner repo delete 42 --yes
```
Deletion also requires repository administrator permission in this Gitea fork.
## Permissions and server behavior
- The repository Projects unit must be enabled.
- Project operations require repository Projects write permission.
- Issue create/edit follows Gitea issue permissions.
- Delete requires repository administrator permission.
- Closed projects, archived repositories, disabled Projects units, foreign
project IDs, and issues outside selected project are rejected.
- API failures return a non-zero exit status. Authentication and HTTP status
guidance is shown without printing server response bodies or tokens.
## Related interface
Use `gitea-kanban-tui` for keyboard navigation over the same native Projects
API. Both binaries use the same configuration and server-side authorization.
-205
View File
@@ -1,205 +0,0 @@
# Minecraft backups
`services.minecraft-backups` adds scheduled S3 archives to the Minecraft module.
Neuro enables it for `vanilla`, `createAeronautics`, `wowMineMap`, and Horizon.
Enabled nix-minecraft servers are discovered automatically. Horizon is registered
explicitly because it runs a separate native engine.
Each server has a `minecraft-backup-<name>.timer`, scheduled every six hours
with up to ten minutes of jitter. S3 retains regular timestamped archives for
14 days under `minecraft/neuro/<name>/` in `backup-hectic-lab`.
Horizon also keeps its existing native backups.
Set `services.minecraft-backups.onCalendar` to change the schedule. Its default
is `"*-*-* 00/6:00:00"` (00:00, 06:00, 12:00, and 18:00 in the host timezone).
S3 retention is configured separately with `services.minecraft-backups.s3.retentionDays`.
## Shutdown warnings
wowMineMap broadcasts chat warnings five minutes before a backup stop, one
minute before it, and immediately before stopping. The countdown starts after
the maintenance lock is acquired and pending uploads have succeeded. It waits
240 seconds between the first two messages, then 60 seconds before the last.
The server remains playable during this interval.
`services.minecraft-backups.servers.<name>.announcementCommand` enables these
warnings. Its executable receives one plain-text message argument; wowMineMap
delivers it through its existing Minecraft console using `say`. Other servers
retain their previous behavior unless this option is set. Inactive servers
receive no warnings and incur no countdown. A failed announcement aborts that
backup before stopping or copying the server.
## Snapshot and local storage
A running server is shut down through its normal systemd stop command while
rsync copies its data to a private staging directory. A failed or forced
shutdown prevents the snapshot. The server starts again before compression
or upload. An already inactive server stays inactive.
An exit trap and the backup unit's `ExecStopPost` restore a server that the backup
stopped if copying fails or the backup is terminated. A `restart-needed` marker
persists until starting the server succeeds.
Staging and pending archives live in `/var/lib/minecraft-backups/<name>/`.
Staging remains for the next incremental copy. A completed archive is removed
locally only after a successful upload. Failed uploads leave it for the next
run, which retries pending archives before taking another snapshot.
Archives contain server data, including worlds and runtime lists such as
whitelists and operators. Regenerated mods, libraries, resources, caches,
logs, existing backups, and secret-bearing `server.properties` are excluded.
Reapply the matching Nix configuration when restoring.
S3 cleanup only deletes names matching that server's timestamped archive format.
Manual archives and other prefixes are preserved. Cleanup uses the same helper
as PZ: individual object deletions and explicit validation of S3 deletion errors.
## Clean shutdown verification, 2026-11-22
The deployed stop script sends Minecraft's `stop` command and waits until
the server exits. Minecraft 1.21.1 `MinecraftServer.stopServer` saves all
players, disconnects them, saves all levels with flushing enabled, closes
the levels, and releases world storage. The backup waits for systemd stop
to finish and requires `Result=success` before rsync starts.
The last inspected production shutdown logged `Saving players` followed by
`Saving worlds` at 17:02:56 UTC, then all chunks and dimensions saved at
17:02:57 UTC. Thus a normal backup copies the final stopped state rather
than combining a live inventory with an older frozen map. Process crashes,
power loss and save errors are separate failure cases; systemd success alone
does not certify that every mod or storage operation saved without error.
## wowMineMap live-backup investigation, 2026-11-16
Read-only inspection through `ssh neuro` confirmed that wowMineMap is running
Minecraft 1.21.1 / NeoForge 21.1.250 with Sable 2.0.5 and Distant Horizons 3.3.3.
Its data resides on ext4 at `/dev/nvme0n1p2`; there is no configured snapshot
backend for this mount.
The Java process has seven Distant Horizons SQLite databases open across the
dimensions, including their WAL and shared-memory files. The Azeroth main
database was about 2.2 GB with a separate nonempty WAL. Copying these files
independently is not a database snapshot.
One component was verified without stopping the game: Python's SQLite Backup
API copied `world/data/DistantHorizons.sqlite`, opened with `mode=ro`, into an
in-memory database. The copy reported journal mode `wal`, 1286 pages, six tables,
and `PRAGMA quick_check` returned `ok`. No backup file was written on neuro.
This verifies that database-copy mechanism, not a full-world restore.
Inspection with `javap` of the deployed Minecraft server and Sable jars found:
- `MinecraftServer.saveEverything` calls `PlayerList.saveAll` before applying
the chunk-saving flags.
- `PlayerList.remove(ServerPlayer)` calls `save(player)` during logout without
consulting the world's `noSave` flag.
- `MinecraftServer.saveAllChunks` also writes the main world metadata using
`LevelStorageAccess.saveDataTag` outside the per-level skip-save logic.
- Sable's `sable$saveSubLevels` injection runs before `ServerLevel.saveLevelData`,
inside the level's skip-save guard. That particular hook is not evidence that
Sable ignores `save-off`.
Consequently, `save-off` plus `save-all flush` does not make the entire server
directory immutable while players keep playing. A file copy can combine frozen
chunks with later player inventories or world metadata. SQLite snapshots alone
do not provide a common checkpoint for those different data stores.
No live mode with guarantees equivalent to an orderly stopped-server copy has
been established for this pack. The stop-based implementation has therefore
not been replaced or deployed. A full-world live restore test was not run,
because there is not yet a coordinated snapshot mechanism to test.
The next implementation step would be an in-process NeoForge checkpoint that
coordinates world, player, Sable, and SQLite persistence, followed by a restore
test on a disposable wowmine instance. Production was not stopped,
restarted, sent save commands, or deployed during this investigation; the
six-hour schedule and fourteen-day retention remain unchanged.
## Credentials and deployment
Before enabling the timers on neuro, provision a root-owned file with mode 0600:
```text
/var/lib/minecraft-backups/s3-credentials
```
Its contents use the systemd environment-file format:
```sh
AWS_ACCESS_KEY_ID=...
AWS_SECRET_ACCESS_KEY=...
```
The key must allow listing the bucket and uploading/deleting objects under
`minecraft/neuro/`. Keep the file outside the repository and `/nix/store`.
A missing file prevents the backup from starting, before it stops any server.
The committed configuration does not provision this secret. Apply the neuro
configuration after the file exists, then check:
```sh
systemctl list-timers 'minecraft-backup-*'
systemctl start minecraft-backup-vanilla.service
journalctl -u minecraft-backup-vanilla.service
```
## Restore
Stop that server's backup timer and game service. Download the chosen
`minecraft-<name>-<timestamp>.tar.zst` from its S3 prefix. Preserve the current
data directory separately before replacing anything.
Extract the archive into the server's data directory while the game is stopped.
Archives contain paths relative to that directory. Restore file ownership to the
game service's user (`minecraft` for Java servers, `horizon` for Horizon),
reapply the matching Nix configuration and runtime secrets, then start the game
and its backup timer.
## Isolated wowMineMap restore test
Neuro declares `wowMineMapRestore` as a separate, manually started Minecraft
instance. It reuses the production NeoForge package, pinned wowmine
modpack import, and shared modpack adjustments. It uses an 8 GB heap and reduced
view/simulation distances for the test. Its directory is
`/srv/minecraft/wowMineMapRestore`; its game socket is `127.0.0.1:25568`.
RCON, public firewall access, and scheduled backups of this copy are disabled.
It does not use the production source-map importer or reset service.
After deploying the neuro NixOS configuration normally, start the copy:
```sh
ssh neuro 'systemctl start minecraft-server-wowMineMapRestore.service'
ssh neuro 'journalctl -u minecraft-modpack-import-wowMineMapRestore -u minecraft-backup-restore-wowMineMapRestore -u minecraft-server-wowMineMapRestore -n 100 --no-pager'
ssh neuro 'tail -n 80 /srv/minecraft/wowMineMapRestore/logs/latest.log'
```
The first start installs the matching modpack, then downloads this exact object:
```text
s3://backup-hectic-lab/minecraft/neuro/wowMineMap/minecraft-wowMineMap-20261117T172531Z.tar.zst
```
The restore uses the existing root-only S3 credentials file. The key needs
`GetObject` access in addition to the backup permissions above. It checks the
compressed size (9,206,330,929 bytes), zstd integrity, archive paths, and the
configured world's `level.dat`. Backup data, including player and mod state,
overrides bootstrap configuration; regenerated mods remain installed.
It refuses to replace an existing world. A completion marker binds the
restored directory to this S3 object, and subsequent starts skip both bootstrap
and restoration so that restored configuration is preserved.
Connect using the matching wowmine client through an SSH tunnel:
```sh
ssh -N -L 25568:127.0.0.1:25568 neuro
```
Use `localhost:25568` in Minecraft. Confirm startup reaches `Done`, enter the
restored Azeroth dimension, and inspect known builds, player inventory, and mod
objects. A running systemd unit alone does not prove that the saved world
loaded correctly. These real-world checks remain to be performed after deploy.
Stop the test when finished:
```sh
ssh neuro 'systemctl stop minecraft-server-wowMineMapRestore.service'
```
-212
View File
@@ -1,212 +0,0 @@
# wowmine v16 Delight selection
Source: `minecraft/pack/wowmine-v16-delight-rules-r2.mrpack`.
SHA-256: `a7f474f1431719c6b11707fec05db8b571cb4d1b84d58c20962e771881b0109e`.
The survival successor removes Afterlife's Delight from both sides. See
[minecraft-survival-v16.md](minecraft-survival-v16.md) for the source pin,
backup, player-state checks and deployment evidence. The inventory below
records the original v16 selection.
The unbreakable netherite knife addon is required on both sides. Its upstream
client-side metadata is incorrect: a real connection failed registry sync without
the client JAR. The archive corrects that metadata; the JAR remains unmodified.
Minecraft remains 1.21.1; NeoForge remains 21.1.250. Existing base mods keep their versions.
Selection covers dedicated Farmer's Delight addons and integrations for installed base mods,
plus required libraries. Integrations requiring new large gameplay mods are excluded.
Modrinth version metadata and actual JAR dependencies were checked; every downloaded JAR
was verified against its published SHA-512. Native server boots and the actual Java packwiz
installer were used to reject incompatible combinations.
The pack removes FTB Ultimine, Create Ultimine, and their now-unused FTB Library.
Fresh clients hide the minimap. Updates preserve personal minimap, options and DH settings.
The separate `wowmine-rules` world datapack enables `mobGriefing` on load and reapplies
`xaerominimap:no_minimap` every second to everyone except Boss UUID
`1c189af5-2713-3fa6-bcc4-893dfadedfa4`. Boss can enable the minimap personally.
The same policy also applies `xaeroworldmap:no_world_map`, blocking the large
map on M for everyone except that UUID. Both restriction effects are cleared
from Boss. This server rule needs no new client archive.
DH cache identities remain `wos` / `wos-w1`.
The same server datapack filters
`cuttingdelight-dev:recipe/cutting/duplicate1.json` from lower-priority packs.
Cutting Delight 1.1.1 ships that recipe, which turns raw beef into cooked beef
on a cutting board with a knife. The normal Farmer's Delight beef-to-two-mince
recipe and both cutting-board conversion recipes remain available. No JAR is
modified, and this restriction needs no new client archive.
The remaining duplication and balance candidates, exact recipe IDs, audit
boundaries and runtime verification are recorded in
[minecraft-recipe-audit.md](minecraft-recipe-audit.md).
## Added artifacts
| Project | Version |
| --- | --- |
| `afterlifes-delight` | `1.1.2` |
| `algae-delight` | `0.2.1` |
| `arbitrary-delight` | `1.2.1` |
| `aures-farmers-structures` | `1.0.2` |
| `autochefs-delight` | `2.0.3+neoforge` |
| `bakersdelight` | `1.0.2` |
| `baldej-delights` | `0.2.0` |
| `barbeques-delight-forge` | `1.3.0` |
| `blockdonalds` | `0.3-1.21.1` |
| `bobo-lib` | `1.3.1-1.21.1` |
| `bountifulharvest` | `1.0.0` |
| `brewin-and-chewin` | `4.5.0+1.21.1-neoforge` |
| `caves-delights` | `1.3.1` |
| `chefs-delight` | `1.0.6-neoforge-1.21.1` |
| `choppers-delight` | `1.2.2` |
| `cocktails-delight` | `1.1.12` |
| `coffee-delight` | `1.4.1` |
| `cooksdelight` | `21.1.2` |
| `corn-delight` | `1.2.10-1.21.1` |
| `crabbers-delight` | `1.3.1` |
| `create-fd-dough` | `1.0.0` |
| `create-snickers` | `0.1.3` |
| `cuisine-delight` | `1.2.10` |
| `cultural-delights` | `0.19.8-1.21.1` |
| `cutt_promix` | `1.0-relase` |
| `cutting-delight` | `1.21.1-1.1.1` |
| `delight-lib` | `26.05.18-1.21-neoforge` |
| `delight-o-flight` | `1.21.1-1.4.3` |
| `delta-delight` | `1.3.926` |
| `display-delight` | `1.7.0` |
| `doris-delight` | `1.0.0` |
| `dough-slime-ball-recipe` | `1.0+mod` |
| `dungeons_delight` | `1.5.3` |
| `easters-delight` | `1.2.1` |
| `egg-delight` | `1.2` |
| `enders-delight` | `1.3.1` |
| `ends-delight` | `2.6.1+neoforge.1.21.1` |
| `even-more-delights` | `1.0.2` |
| `expanded-delight` | `0.1.4-neoforge` |
| `extradelight` | `2.7.2` |
| `farmers-cutting-everything` | `1.21.1-1.0.1` |
| `farmers-delight-contracts-feasts` | `1.0.3` |
| `farmers-delight-extended` | `1.21.1-0.2.2` |
| `farmers-delight-meal-mastery` | `1.1.2` |
| `farmers-delight-x-create-unbrekable-netherite-knife` | `3` |
| `farmers-knives` | `1.21.1-4.2.0` |
| `farmers-respite-unofficial-port` | `3.0.1` |
| `farmers-spell` | `1.0.7.1-1.21.1` |
| `fast-delights` | `0.3.1` |
| `fastfood-delight-unofficial` | `1.21.1-1.0.5` |
| `festive-delight` | `2.0.0` |
| `fizzy-delight` | `1.1` |
| `frights-delight` | `neoforge-1.21.1-1.4.8` |
| `fruits-delight` | `1.2.14` |
| `fungi-delight` | `1.3` |
| `hearth-and-harvest` | `1.4.3` |
| `immortalers-delight` | `1.21.1-neoforge-1.0.10` |
| `kazakh-delight` | `1.0.0` |
| `kitchen-projectiles` | `1.0.11+mc1.21.1+neoforge` |
| `korean-delight` | `1.0.0` |
| `kvass-delight` | `1.0.0` |
| `large-meals` | `1.21.1-1.0.1` |
| `legume-delight` | `1.21.1-1.4.0` |
| `luncheon-meat-s-delight` | `1.21.1-1.0.6` |
| `mangos-compat-delight` | `1.0.0` |
| `mexicans-delight` | `2.0.0` |
| `millet-delight` | `0.0.3-beta` |
| `mmlib` | `1.3.16-1.21.1` |
| `more-delight` | `26.05.20a-1.21-neoforge` |
| `my-nethers-delight` | `1.10.4.1` |
| `nearby-delight` | `1.6.0` |
| `new-years-delight-a-farmers-delight-add-on` | `nydelight-1.21.1-1.1.0` |
| `nomads-delight` | `1.0.2` |
| `oceans-delight` | `1.0.4` |
| `onion-onion` | `3.1.0` |
| `pantrywork` | `0.9.0+mc1.21.1` |
| `peruvians-delight` | `1.21.1-1.3.0` |
| `pizzadelight` | `1.21.1-2.0.2` |
| `provisioners-delight` | `0.9.31` |
| `ramadan-delight` | `1.7` |
| `rhubarb-delights` | `0.2` |
| `right-click-and-milk` | `1.0.3` |
| `roll-delight` | `1.3.0` |
| `runiclib` | `5.0.7` |
| `rustic-delight` | `1.7.1` |
| `seed-delight` | `1.0.1` |
| `slavic-delight` | `0.3.2` |
| `sniffers-sniffs-delights` | `neoforge-1.1+mc1.21` |
| `sodd-delight-a-farmers-delight-add-on` | `1.0.0` |
| `storage-delight` | `26.09.17-1.21-neoforge` |
| `sunflower-delight` | `1.0.2n` |
| `teyvats-delight` | `1.2.0` |
| `trailtales-delight` | `2.4` |
| `tweaks-delight` | `26.06.18-1.21-neoforge` |
| `ubes-delight` | `neoforge-1.21.1-0.4.15` |
| `valheim-delight` | `1.0.0` |
| `vanilla-delights` | `1.21.1-1.0.6` |
| `vintage-delight-kots` | `0.3.3` |
| `yafda` | `0.21` |
| `zena-desi-delight` | `1.21.1-0.2` |
## Rejected during runtime checks
These versions were not shipped. Existing base mods were not removed to accommodate them.
| Project | Observed reason |
| --- | --- |
| `bowling-bulb` | Native loader requires absent Nirvana and EMI; broken access transformer |
| `compat-delight` | References missing FD ShepherdsPieBlock class |
| `cooks-collection` | Native loader declares incompatibility with Cultural Delights |
| `create-slice-and-dice-growth-accelerator` | References absent old SprinkleBehaviour class; installed4.3.3 uses new behaviour API |
| `crockercorp-delight` | Requires absent Minestuck classes; dependency omitted by author |
| `custombrewrecipes` | Unused after Vietnam addon exclusion |
| `delightful-creators` | JDI captured crash in generated cooking_fallback/mooncake_delight/cooking/milk_tea_mooncake: empty Create sequence ingredients |
| `delightful-fares` | Requires absent Bountiful Fares classes |
| `dumplings-delight-rewrapped` | References missing celery_seeds, breaking global SereneSeasons autumn crop tag |
| `engineers-delight` | Recipes require absent Immersive Engineering serializer; no supported base installed |
| `farmers_attributes` | General farming attribute API; no selected addon requires it |
| `farmers-cutting-collection` | Unconditional recipes for absent BetterEnd/BetterNether/Biomes O Plenty/Regions Unexplored bases |
| `farmers-delight-kacchi` | Common setup loads client RenderType on dedicated server |
| `farmers-heater` | Requires absent Central Heater gameplay mod |
| `farmers-pizzeria` | Overrides Brewin and Chewin pizza recipe with zero-byte invalid JSON |
| `froot-trees` | Malformed core berry tag JSON |
| `gan_delight` | Invalid JSON in core steamed pork recipe |
| `gensokyo-delight-youkais-feasts` | Creates c:butter -> c:foods/butter cycle with ExtraDelight, breaking shared butter tag |
| `horizon-delight` | Brewin compat initializes BnC foods before effect registry, crashing registration |
| `hybrid-api` | Unused after Hybrid addon exclusion |
| `hybrid-delights` | Only integrates absent Hybrid Labs gameplay mods |
| `lodestonelib` | Unused after Miners Delight rejection; Veil shader link failure |
| `miners-delight` | Required Lodestone shaders fail to link with installed Veil renderer |
| `mooncake-delight` | Core mooncake and pepper_salt tags reference dozens of missing own items |
| `muffins-oven-api` | Same eager BlockEntityType mixin; only needed by rejected Thai addon |
| `muffins-thais-delight` | BlockEntityType mixin eagerly reads unbound Apotheosis registry holder |
| `oaks-delight` | Invalid JSON in core cleaver crafting recipes |
| `sauce-delight` | Create6.0.10 fluid result codec incompatible |
| `syals-delight` | Required tags reference absent UnusualFoodsDelight/ManorsBounty/LTC2/GTCEu items |
| `touhoupixelcanteen` | Loads ClientTooltipEvent on dedicated server |
| `vegan-delight` | Create6.0.10 integration fluid/item recipe codec incompatible |
| `vietnams-delight-reborn` | Native loader discourages combination with Coffee Delight |
| `wizardry-delight` | Real client title shows Sodium incompatibility: replaces unsupported terrain shaders |
Other exclusions include duplicate mod IDs, unsupported loader versions, and integrations
for absent bases such as Aether, Alex's Mobs, Aquaculture, Croptopia, Goety, Immersive
Engineering, Minestuck, and Twilight Forest. No dependency version validation was bypassed.
## Verification scope and upstream data warnings
Loader startup, real player login, registry synchronization, updater preservation,
and the minimap rule are tested. These checks do not certify every recipe or loot
rule supplied by the added projects.
The private runtime still reports nonfatal upstream data errors:
- Farmer's Knives emits recipes for knives from absent optional base mods.
- Farmer's Spell includes Create fluid recipes using the old `neoforge:fluid`
encoding and Botany Pots integration entries without that base mod.
- Dungeons Delight has several loot modifiers using the removed
`minecraft:random_chance_with_looting` condition; those modifiers are skipped.
- Even More Delights references `c:mushrooms` as an item in one cod recipe.
- Some addons emit unguarded optional recipes for Sawmill, Casualness Delight,
Vegan Delight, and Kaleidoscope Cookery when those mods are absent.
- Some recipe overrides use an unregistered `neoforge:never` condition.
The server and clients remain able to load and connect. These data errors were
not hidden or repaired by modifying third-party JARs. The original base pack also
reports unrelated Design n' Decor loot-table and class-selection function errors.
-154
View File
@@ -1,154 +0,0 @@
# Immersive Portals v17
Original v17 source: `wowmine-v17-immersive-portals.mrpack`, SHA-256
`f958597c4bed2da74d3e4c1d52b2773e2292fb9c3d1a4f42ccda76b9c620a9de`.
The published upstream artifact is UpperMoon0 Community Edition6.1.3.1,
SHA-256 `da2fa1d90eae031e34690a64c9cd75ed3b74d47325825f8f38c0419e1220bca2`.
The older official NeoForge6.0.7 targets Sodium classes absent from this pack.
The release adds exactly one JAR to both sides. Minecraft1.21.1,
NeoForge21.1.250, all old mod downloads and all override payloads remain
unchanged except client version metadata. Cloth Config15.0.140 already exists
on both sides. Expected counts are238client and230server JARs, including the
existing server-only World Policy and Sleep Time Skip.
## Routing and existing worlds
World Policy1.1.0 handles IP's own intrinsic portal generation rather than
relying only on vanilla `NetherPortalBlock.getPortalDestination`. Its mixin
rewrites the two forward generators and their source selection to
`crafting_azeroth:azeroth` and `wowmine:void`, with both ratios1. Reverse
generations inherit these keys and ratios. Normal/adaptive mode dispatch and
the built-in portal-helper generation remain in place.
The server selects normal Nether portal mode and disables the crouch-to-vanilla
shortcut. End portal mode remains vanilla, preserving the existing Azeroth
return policy. The old Nether, End, Outland, player data and map are retained.
No alternative worlds are enabled by this CE artifact.
Existing vanilla purple portal fields do not automatically become IP entities.
To reuse an old pair, extinguish both fields by briefly breaking/replacing one
frame block at each end, then reignite. IP can then match empty frames; an
occupied vanilla destination instead causes a warning and new-frame placement.
## Frameless spaces and rendering
The built-in Portal Wand item is `immersive_portals:portal_wand`. An operator
can obtain it with `/give @s immersive_portals:portal_wand` and configure
frameless openings. The existing void dimension can hold rooms linked through
these openings. Portal commands also include `create_scaled_box_view`.
The release does not grant commands, change player game modes, or add an
automatic personal-room survival recipe.
Sodium0.8.13, Iris1.8.14-beta.1, Distant Horizons3.3.3 and Pehkui3.8.3 remain
installed. DH deliberately cancels LOD rendering inside portal views; ordinary
nearby Minecraft geometry is used there. Main-view DH cache identities remain
`wos` and `wos-w1`. A software OpenGL test establishes rendering functionality,
not performance on a player's GPU.
## Release checks
The source builder verifies every old downloaded-file entry and override byte.
Actual Java packwiz fresh installation and v16 upgrade both installed238JARs,
verified the new mod, retained every old mod hash and preserved personal options,
DH settings and minimap configuration.
Native build/copy/dry-activation succeeded. Isolated real-client/server QA passed
24 checks on the exact tall Azeroth type: real player round trip, active cow and
arrow crossings, new-frame fire ignition, four intrinsic/adaptive routes, and
frameless views from two angles. NeoOrigins Tiny retained native scale0.5,
width0.3 and height0.9. Main inspected all four final screenshots, including
the unchanged published Bliss2.1.2 shader through Iris. DH remained active.
Software OpenGL establishes functionality; no GPU performance claim is made.
Evidence is retained under `/tmp/wowmine-immersive-qa`.
Native profile:
`/nix/store/814f6qg1alfj72h55wqgsqjnc4hndsw2-nixos-system-neuro-26.05.20261006.b253099`.
Original immutable public pack release:
`e969385695e6baa55961b6e45d5e69b24fc152de8a691df2a71af5c791d9e382`.
The client channel was switched after direct server checks passed. Installed
230JARs match the pinned source and two server-only additions; all228 unrelated
old JARs,20 player/stat/advancement records,7255 region files,23 datapack files
and access lists are preserved. Seed, spawn, world name and hardcore flag match
the cold copy. Sleep remains100%, eight selective Create types and DH identities
remain unchanged. No project commit is part of this change.
The aggregate NixOS activation returned4 because the unchanged
`ollama-model-loader.service` failed. Minecraft itself passed direct integrity,
RCON dimension/sleep and backup-timer checks. Ollama was not modified.
The deployment uses the shared backup lock and a verified cold recovery copy
on the workstation under
`/home/yukkop/.local/share/hearth-backups/wowmine-before-v17-20261123`.
An online rsync pre-seed avoids transferring the whole map during downtime.
After stopping the server, every copied file is checked against a fresh source
SHA-256 manifest before native activation. This retains neuro's10GiB reserve.
The verified recovery copy contains9376files. It must not be removed with
temporary QA runtimes. Sources, JSON receipts, logs and four inspected screenshots
remain under `/tmp/wowmine-immersive-qa`; disposable game runtimes are removed.
## Client culling hotfix
Client revision `v17-ip-culling-fix` preserves Sodium's original cave-culling
argument outside portal rendering. Upstream CE6.1.3.1 replaced it with `false`
even in the ordinary main view. The portal-specific branch remains unchanged:
```java
boolean doUseOcclusionCulling = PortalRendering.isRendering()
? PortalRendering.shouldEnableSodiumCaveCulling() : originalValue;
```
Only `MixinSodiumOcclusionCuller.class` changes in the upstream JAR. The complete
source diff, attribution and original license are retained inside the artifact.
Its SHA-256 is
`6a686c51e13cec7620964861c3bc6572019e5a08b7aadf3530b5cef56ff6fc1f`.
The mod and network protocol version remain6.1.3.1.
Source `wowmine-v17-ip-culling-fix.mrpack` has SHA-256
`ad9b753d59517483341a66cd1a5beca93310a938b99c4059bd97c1069df35d90`.
It retains the original server download and supplies the patched JAR only through
`client-overrides`. Existing server activation, worlds, routing, sleep, Create
rules and DH identities are unchanged. Client JAR count remains238.
The immutable client pack release is
`9ed30864f882c3fd5b17003f1638b59b1f865e90dd6b5b8798ceaa88449e8d92`.
A component probe failed on the original argument handling, passed with the fix,
and failed again after restoring the original. Actual NVIDIA RTX3050Ti captures
with Bliss, view distance18 and window2560x1369 measured17.23FPS before,
38.18FPS after, and33.52FPS in a repeat after restoring this fix. Rendered sections
fell from2077 to approximately1080. The player confirmed destination visibility
and a successful portal round trip on the restored fix.
These captures establish an improvement; they do not establish restoration of
the reported earlier60FPS. The repeat began shortly after world entry, and a
requested warmed capture was not supplied before the game closed. Remaining
frame cost has not been attributed to a particular IP hook. An additional
framebuffer-preparation experiment did not demonstrate benefit and is excluded.
Flywheel's shader-related backend warning also occurs without IP and does not
prove a new global backend regression.
The final local Java packwiz upgrade passed with the exact patched JAR,
all237 unrelated old mod hashes, and personal options, DH and minimap settings
preserved. All682 public managed payloads, archives, checksums and the download
page matched the staged release. Actual HTTPS fresh installation and the public
updater on the already-fixed client both passed with238JARs and exact old mod
hashes; the existing client's personal options, DH and minimap bytes remained
unchanged. The original-v17-to-hotfix transition was exercised locally with the
same payloads. These are delivery checks, not additional performance measurements.
Evidence and recovery copies are retained under `/tmp/wowmine-ip-fps`.
## Colorwheel client compatibility
The v18 client adds Colorwheel1.3.2 and Patcher1.0.5 while retaining the exact
culling-fixed IP JAR. The author-generated Bliss2.1.2 Clrwl variant was loaded
through Iris on the player's NVIDIA client. The player confirmed Create
geometry, shadows, portal views and a round trip. Source/bytecode inspection
found that Colorwheel's visualization-manager lookup respects IP's existing
vanilla-rendering gate in alternate, portal and clipped views; it does not
establish accelerated rendering inside those views.
The current measured profile is34.28FPS, within the earlier33–38FPS range.
No additional FPS gain is claimed. Release pins, selection instructions,
personal preset and updater evidence are recorded in
[minecraft-prism.md](minecraft-prism.md). Current evidence is retained under
`/tmp/wowmine-colorwheel`.
-104
View File
@@ -1,104 +0,0 @@
# Minecraft incident log
This file records only observed evidence, actions, and verification results.
An entity appearing in a stack trace is a trigger-path observation, not a
proven root cause.
Current player address: `wowmine.bfs.band` (no port). Addresses inside dated
incidents below record the endpoints used at the time.
## 2026-09-19 — wowmine crashes in Sable block-change handling
### Impact
- `minecraft-server-wowMineMap.service` terminates while a player is online.
- Public Minecraft endpoint is `store.hectic-lab.com:25568`.
- Server is intentionally stopped after the latest crash to prevent repeated
crash-save cycles while recovery is investigated.
### Observed evidence
All crash reports contain `sable@2.0.5` in
`LevelAccelerator.getBlockState`, followed by
`ArrayIndexOutOfBoundsException` where the requested section index exceeds
the world section array length of `24`.
| UTC timestamp | Crash report | Observed trigger path | Exception |
| --- | --- | --- | --- |
| 18:47:03 | `crash-2026-09-19_18.47.03-server.txt` | `EnderMan$EndermanTakeBlockGoal.tick` | index `38` / length `24` |
| 18:52:17 | `crash-2026-09-19_18.52.17-server.txt` | `GlowSquid.aiStep` → `RedStoneOreBlock.stepOn` | index `33` / length `24` |
| 19:14:46 | `crash-2026-09-19_19.14.46-server.txt` | `Skeleton.tick` → `RedStoneOreBlock.stepOn` | index `34` / length `24` |
Evidence locations on `neuro`:
```text
/srv/minecraft/wowMineMap/crash-reports/
/srv/minecraft/wowMineMap/logs/latest.log
```
### Actions performed
| UTC timestamp | Action | Result |
| --- | --- | --- |
| 17:51 | Archived current world before recovery | Archive checksum recorded |
| 18:08 | Set `randomTickSpeed=0` | Server started, but later crashed from an entity block change |
| 18:48 | Set `mobGriefing=false` | Prevented Enderman block pickup only; later crashes still occurred |
| 18:54 | Archived post-crash world | Archive checksum recorded |
| 19:00 | Moved Boss offline player NBT from `(3299.067, 142.630, 8613.742)` to `(3296, 500, 8608)` in `crafting_azeroth:azeroth` | Only `Pos` and `Dimension` changed; later crash still occurred |
| after 19:14 crash | Stopped `minecraft-server-wowMineMap.service` | Prevented further automatic crash/restart saves |
### Recovery artifacts
```text
/srv/minecraft/backups/wowMineMap-before-sable-recovery-20260919T175139Z.tar.zst
/srv/minecraft/backups/wowMineMap-after-sable-crashes-20260919T185445Z.tar.zst
/srv/minecraft/wowMineMap/world/playerdata/1c189af5-2713-3fa6-bcc4-893dfadedfa4.dat.before-relocation
```
### Conclusions supported by evidence
- Public proxy and reverse tunnel are not the failure point: server-list ping
succeeded before later in-world crashes.
- The failure is not limited to Endermen, random ticks, or one player
position.
- Sable's block-change callback is present in every captured crash.
### Not established
- Exact corrupt chunk, block, or mod data.
- Whether world data is corrupt, Sable itself is defective, or another mod is
supplying incompatible world state.
- Whether deleting any chunk, region, or Sable state would be safe.
### External research
No exact upstream match was found for Sable `2.0.5` on NeoForge `1.21.1` with
`LevelAccelerator.getBlockState` and a requested section index of `33`, `34`,
or `38` against a section array of length `24`.
Related but non-identical upstream reports:
- [Sable #776](https://github.com/ryanhcode/sable/issues/776) documents an
`ArrayIndexOutOfBoundsException` associated with unusual dimension height
bounds. This is relevant to section-coordinate handling, but is an older
version and different stack trace.
- [Sable #1087](https://github.com/ryanhcode/sable/issues/1087) documents a
`LevelAccelerator.getBlockState` recursion during block-shape processing.
The failure type differs.
- [Sable #820](https://github.com/ryanhcode/sable/issues/820) documents a
ticking-entity block-change crash. The reported downgrade to `1.1.3` helped
that distinct recursive-update failure; it is not evidence for this crash.
- [Sable #1223](https://github.com/ryanhcode/sable/issues/1223) documents a
different `ArrayIndexOutOfBoundsException` in voxel-neighborhood handling.
Its suggested Lithium setting only reduced crashes for some reporters and is
not a verified mitigation here.
Sable `2.0.4` and `2.0.5` release notes mention other block or contraption
crash fixes, but not this exception. No version upgrade or downgrade is
currently evidence-backed as a production fix.
### Next recovery step
Use a disposable full-world copy to test a supported Sable/physics integration
mitigation. Do not restart production, delete region files, or overwrite a
backup until that test gives reproducible evidence.
-37
View File
@@ -1,37 +0,0 @@
# Craftable Loot Chests recipes
`wowmine-rules/pack.mcmeta` filters recipe resources in the
`craftable_loot_chests` namespace with the unique `recipe/recipe_sealed_`
prefix. Installed version1.0.0 contains18matching files for coal, diamond,
food, gold, iron, lapis, netherite and village chests, including alternatives.
The original server loads16of those recipes; both coal recipes are already
unloaded. All18resource files are covered by the filter.
The mod stays installed. Item/block registrations, loot resources, existing
placed chests and inventory items are not removed.
Keep the path prefix narrow. Minecraft1.21.1 ResourceFilterSection tests
namespace and path independently across its block list. A broad `recipe/.*`
path in this shared pack would also filter recipes from other namespaces
already listed there. Validation must compare all other RecipeManager IDs,
not only check that this mod's recipes disappeared.
Verification uses separate cold starts of a matching disposable server and
compares RecipeManager IDs, item/block registrations, loot resources and a
chest saved before applying the filter. Native deployment likewise restarts
the server. A hot-reload trial failed on a separate duplicate
`mango_compat_delight:cutting/stripped_cinnamon_log` registration; this change
does not attempt to fix that mod's reload behavior.
Cold-start comparisons also exposed a generated Create Dragons Plus polishing
recipe occasionally missing. Its provider asynchronously saves resources into
an unsynchronized HashMap. QA uses `-Dmax.bg.threads=1` for both baseline and
filtered starts to keep the generated data stable while retaining the strict
all-other-recipe comparison. This JVM setting is test-only.
The final strict comparison passed: 21,528 recipes became21,512, with exactly
the16loaded Craftable Loot Chests recipes removed and no other recipe IDs
added or lost. All25registered mod items,16blocks and28loot resources remained
equal. A placed sealed diamond chest survived the filtered cold restart with
the same block state. Existing live rules were copied into the native snapshot
before adding the filter, preserving all six prior restrictions.
-99
View File
@@ -1,99 +0,0 @@
# wowmine live 3D map
The wowmine runtime rename was deployed on 2026-11-18. Renderer, space-guard
timer are active under their canonical names. Moving all
73,667 state entries preserved contents, inodes, ownership and modes; tile,
data and render-checkpoint files were retained. One renderer is active.
The public settings endpoint returns HTTP 200 with both map IDs. Initial
rendering continues; full coverage is not claimed. Evidence:
`/tmp/wowmine-rename/runtime-result.md` and `runtime-evidence/`.
The initial rollout below predates this rename; old evidence paths and
immutable store basenames remain historical.
The website links to `https://wowmine.bfs.band:8443/wowmine/map/` on neuro.
BlueMap 5.29 CLI reads the running server's saved world on neuro:
- `crafting_azeroth:azeroth`, displayed as **Азерот**.
- `crafting_azeroth:outland`, displayed as **Запределье**.
Only these dimensions are published. This is saved block geometry, not a
static illustration. Unsaved changes cannot appear until Minecraft writes
them. The standalone renderer does not publish live player locations.
Open **Menu → Maps** to switch dimensions. Drag to move, rotate the camera,
and use zoom controls to inspect terrain. Unrendered areas initially remain
empty; vertical walls can appear along incomplete coverage boundaries.
## Services and limits
`nixos/system/neuro/minecraft/bluemap.nix` defines
`wowmine-bluemap.service`. It uses Java 25, a pinned CLI JAR, two render
threads, a 3 GiB Java heap, 200% CPU quota, low CPU/I/O priority, and a 5 GiB
cgroup memory limit. Minecraft's server directory is mounted read-only in
the renderer's namespace. Its writable state lives exclusively under
`/var/lib/wowmine-bluemap`, with separate private data and public web roots.
The renderer watches region files, with a 60-second update cooldown and a
five-minute periodic region check. A full rescan is scheduled every 1440
minutes. These settings do not promise a fixed end-to-end delay during the
initial render or a large update backlog.
A separate timer checks free disk space each minute and stops only BlueMap
below 20 GiB free. Free space must be restored before manually starting
BlueMap again. Minecraft is not stopped by this guard.
`nixos/system/neuro/wowmine-web.nix` serves the map through local nginx.
The former hectic-lab SSH proxy is retired:
```text
HTTPS :8443 /wowmine/map/
→ neuro nginx :443
→ neuro 127.0.0.1:8100
```
No new public renderer port is opened. Nginx streams map events without proxy
buffering. Only GET/HEAD are permitted. The Minecraft endpoint remains
`wowmine.bfs.band:35565`.
## Initial rollout, November 18, 2026
Both maps were seeded with actual bounded renders around their starting
coordinates, then unrestricted initial rendering was started in the managed
service. The initial full render is **not complete**. Its early estimate was
several days; the estimate changes with terrain density and server load.
The presence of both map names does not establish full-world coverage.
Scoped runtime units were installed in `/etc/systemd/system.control` on both
hosts, with their store dependencies GC-rooted under
`/nix/var/nix/gcroots/worldofsosal-bluemap`. The Nix modules reproduce the
configuration on a future normal deployment. No system-wide activation or
Minecraft restart was performed for this rollout.
The existing deployed website, including its theme controls, was preserved.
Only two links and the map proxy locations were added. The scoped Nginx unit
points to `/nix/store/rj30dz9g052fa0044m6ran5wdfjlji8c-nginx.service/nginx.service`.
Map state is persistent and intentionally outside Git.
## Operations and verification
```sh
ssh neuro systemctl status wowmine-bluemap --no-pager
ssh neuro journalctl -u wowmine-bluemap -n 30 --no-pager
ssh neuro systemctl status wowmine-bluemap-space-guard.timer --no-pager
ssh neuro df -h /var/lib/wowmine-bluemap
ssh neuro du -sh /var/lib/wowmine-bluemap/web
curl -fsS https://wowmine.bfs.band:8443/wowmine/map/settings.json
```
Actual geometry for both dimensions was inspected in a WebGL browser at phone
and desktop sizes. Automatic updating was tested separately on a copied region:
after adding a gold-block section to that isolated copy, the continuously
running watcher regenerated mesh geometry within 6.142 seconds with a two-second
test cooldown. Vertex count changed from 136368 to 145584 and maximum vertex
height from 122 to 144. No manual rerender or process restart triggered it.
This demonstrates the mechanism, not production latency with its larger queue.
Rollout evidence and reproducible isolated test scripts are retained locally
under `/tmp/worldofsosal-bluemap/`; raw update evidence is
`update-artifacts.tar.gz`. These temporary artifacts are not needed to run
the persistent services.
-82
View File
@@ -1,82 +0,0 @@
# wowmine player visibility
Applied on neuro on November 22, 2026. Scope: hide overhead player names and
ordinary world-coordinate displays. Names in Tab, chat and Jade's targeted
entity tooltip remain available.
## Server rules
`wowmine-rules` sets `reducedDebugInfo=true` on load. This removes absolute
XYZ, block and chunk location lines from vanilla F3. Reduced F3 still shows
chunk-relative offsets; it does not remove every diagnostic value.
The datapack creates `wowmine_hidden` with `nametagVisibility=never`.
`player_visibility.mcfunction` assigns unteamed online players every tick,
including players joining later. There were no existing teams before rollout.
Existing team members are never moved. If administrators later introduce
custom teams, those teams need their own hidden-name setting.
Friendly fire stays enabled and friendly invisible players stay hidden.
The team has no custom prefix, suffix or color.
## Xaero profiles
The installed Xaero Minimap 26.4.2 renders coordinates independently of
`reducedDebugInfo`. Server profiles therefore also enforce:
- Minimap `coords`, `overworld_coords` and `chunk_coords` displays: false.
- World Map `display_coordinates`: false.
- Waypoint coordinate fields: hidden by default.
Source files live under
`nixos/system/neuro/minecraft/wowmine-server-config/xaero/`.
Minecraft's NixOS `preStart` copies them into its configuration directory.
The large `info_display_config` value has its own
`server_profiles/info_display_config/default.cfg.txt` file.
Both profiles enforce `ignore_enforcement_if_edit_permission=false`.
Other client HUD preferences remain local. Boss retains the existing minimap
and World Map access exception, with coordinate displays suppressed too.
These are display controls for the installed clients, not position secrecy.
Clients still receive positions to render the world. Xaero's waypoint editor
also offers a manual show/hide button for coordinate fields. No new client
archive or mod download is needed.
## Verification and operations
Native system:
`/nix/store/7rpz3mij1c049i8risqy1mxmaz6hpps1-nixos-system-neuro-26.05.20261006.b253099`.
Build, transfer, dry activation and native activation succeeded. Only Minecraft
was selected for restart. It reached readiness at 09:11:47 UTC with the same
18443 recipes.
Two actual matching clients were connected to an isolated server. A positive
control showed the other player's overhead name and absolute F3 coordinates.
Applying the real load function removed both. A separate normal HUD capture
showed the visible player without a name or coordinate HUD. Boss's large map
still opened without its coordinate readout. Reapplying the load function
worked with the existing team.
Screenshots under `/tmp/wowmine-visibility/`:
- `origin-human.png`: positive overhead-name control.
- `visible-control-f3.png`: absolute F3 coordinate control.
- `hidden-names-reduced-f3.png`: reduced F3 after policy application.
- `hidden-name-hud.png`: hidden overhead name and minimap coordinate HUD.
- `worldmap-no-coordinates.png`: Boss map access retained.
The live check reads persisted gamerules and scoreboard properties, checks
both server profiles and all three HUD display states, and compares previous
recipe/map rules against their snapshot. The modpack archive remains
`v16-survival-r1` with unchanged SHA-256
`a74f1b121d888247ce0fb8951d21a8c389eecd138f7b1e078430f27c6034261b`.
Previous settings and the old system reference are preserved in neuro's
private `/var/tmp/wowmine-visibility/`; the result is recorded in
`live-integrity.json` there. World identity and previous recipe/map rule files
are preserved. No player inventory, experience, class or game-mode records
were manually rewritten.
Gamerules and teams persist in world data. Reverting service files alone does
not undo those stored values. No project Git commit was created.
File diff suppressed because it is too large Load Diff
-338
View File
@@ -1,338 +0,0 @@
# wowmine recipe audit — 2026-11-21
## Scope and evidence
All 228 live server JAR SHA-256 hashes matched the v16 QA fixture. The audit
covered 18,868 packaged recipe declarations, including embedded JARs and optional
built-in datapacks. Vanilla recipes were also inspected to check conversion
costs. Live filesystem world datapacks contained no recipe JSONs.
These are static findings from recipe JSON, ingredient tags, and the installed
Farmer's Delight implementation. Duplication cycles below are arithmetic proofs
of the declared recipes, not live crafting trials. Runtime-generated recipes,
conditional loading, tag replacement, loot, custom machine behavior, and item
remainders limit completeness. Packaged declarations are not necessarily loaded
recipes. Ordinary raw foods such as sushi, tartare and ceviche, vanilla food
crafting, agriculture, and normal ore processing were not automatically called
exploits.
Fixture JAR names below are audit aliases. Production filenames differ, but
their hashes match. Recipe IDs identify the resources independently of names.
## Initial beef recipe removal
Only `cuttingdelight-dev:cutting/duplicate1` was disabled. Cutting Delight 1.1.1
ships it in `data/cuttingdelight-dev/recipe/cutting/duplicate1.json`:
- Input: one `minecraft:beef`; tool: `#c:tools/knife`.
- Output: one `minecraft:cooked_beef`; no heat.
- Existing `wowmine-rules/pack.mcmeta` now filters that exact resource from
lower-priority packs. No JAR or client release was changed.
- `farmersdelight:cutting/beef`, producing two `farmersdelight:minced_beef`,
and both cutting-board conversion recipes are outside the filter.
NixOS build, closure transfer and activation exited zero. Dry activation changed
only Minecraft. Native profile:
`/nix/store/bzn51xx459gwf7f8akgply0gdchabdmf-nixos-system-neuro-26.05.20261006.b253099`.
Server startup loaded **18,470 recipes**, down from **18,471**, and reached
`Done`. RCON returned `Unknown recipe: cuttingdelight-dev:cutting/duplicate1`.
Live metadata SHA-256 matched source:
`b0c73f88b0d52310ffb574e65637ac0e0a0df179b4cf2a55c8aebaac77f5f8ef`.
An earlier live `/reload` failed and retained old data. Its cause was a duplicate
`mango_compat_delight:cutting/stripped_cinnamon_log` registration in Mango's Compat
Delight. A normal NixOS Minecraft restart applied the filter successfully. The
Mango reload defect remains; it was not changed as part of this removal.
## Selected dismantling corrections
The first table's deterministic over-refunds are corrected through the same
server datapack, under their original `farmerscuttingeverything:cutting/` IDs:
| ID suffix | Corrected return |
| --- | --- |
| `iron_door` | One door -> two iron ingots; exact original material cost. |
| `iron_bars` | One bar -> three iron nuggets; 16 bars return 48 nuggets against a 54-nugget crafting cost. |
| `armor_stand` | One stand -> six sticks and one smooth stone slab; exact cost. |
| `bowl` | Four bowls -> three oak planks; shapeless crafting, exact cost. |
| `firework_rocket` | Three rockets -> one gunpowder; shapeless crafting, paper is lost. |
| `copper_grate`, `exposed_copper_grate`, `weathered_copper_grate`, `oxidized_copper_grate` | One grate -> two copper ingots; four return eight ingots against the cheapest nine-ingot stonecutting route. |
Single-item bowl and rocket cutting cannot express the required fractional
material returns without adding probabilities. Their batch crafting recipes
replace those cutting recipes instead.
The erroneous `honeycomb` self-duplication recipe is filtered; the existing
`honeycomb_block` recipe still returns four honeycombs from one block, exactly
matching its cost. No no-op honeycomb-to-itself recipe is added.
Fortune behavior and `spectral_arrow` are deferred and unchanged. Normal
manufacturing recipes, other audit findings and mod JARs are unchanged. The
tables below document the original audited recipes, not these corrected returns.
The corrected profile was built, copied and activated successfully:
`/nix/store/wk8ffl2jhwmdbpmp66pirvyxzcijl2yc-nixos-system-neuro-26.05.20261006.b253099`.
Only Minecraft was restarted. The server loaded 18,469 recipes and reached
`Done`; none of the nine overrides produced recipe-load errors. Live hashes
of all nine recipe files and `pack.mcmeta` matched the built source. Metadata
SHA-256 is `8b01b777bee79852582e9e6b05bfafb308772b7756856fdf82779b04e0cd5de7`.
Material-budget checks passed for every changed return. These checks verify
JSON, costs, deployment and loading; manual in-game dismantling was not run.
## Rotten flesh fermentation removal — 2026-11-22
The server datapack filters only
`vintagedelight:fermenting/leather_from_fermenting`, supplied by
`vintagedelight-kots-0.3.3.jar`. It converts four rotten flesh into one leather
in a Fermenting Jar, with a base processing time of 4000 ticks.
The exact filter uses namespace `^vintagedelight$` and resource path
`^recipe/fermenting/leather_from_fermenting\.json$`. The previous beef and
honeycomb filters remain intact. The other 196 Vintage Delight recipe
resources are outside this filter; the jar, station, other leather recipes
and client release are unchanged.
Native profile:
`/nix/store/gbzgzm80srgksaq9v3pkrxr7w5w37h0h-nixos-system-neuro-26.05.20261006.b253099`.
Build, copy, dry activation and switch exited zero; only Minecraft restarted.
It reached `Done` at 13:32:51 UTC. Live metadata matches source SHA-256
`be49e0f020988fef98a5d77e1bfe0accbed1446e4ae118417f9224ef854b283b`.
A standalone probe used the installed Minecraft 1.21.1
`MultiPackResourceManager`, the identical Vintage JAR and the before/after
datapacks. The positive control exposed 197 Vintage recipe resources; applying
the new filter exposed 196, excluding exactly the requested resource. The
remaining resource-ID sets were identical. Probe code:
`/tmp/wowmine-leather-filter/ResourceFilterProbe.java`.
The general startup count remained 18442 and was not used as proof of this
specific removal. No players were online for a brewing trial, and no recipe
book, inventory or player-state operations were performed. Activation held
the existing maintenance/backup lock and preserved the old metadata under
neuro's `/var/tmp/wowmine-leather-filter/`.
## Packed and blue ice cutting removal — 2026-11-22
The server datapack now filters all four audited ice-unpacking recipes:
- `farmerscuttingeverything:cutting/packed_ice`
- `farmerscuttingeverything:cutting/blue_ice`
- `extradelight:cutting/packed_ice_axe`
- `extradelight:cutting/blue_ice_axe`
The first pair uses a pickaxe; the second uses an axe. Each unpacked one
packed ice into nine ice, or one blue ice into nine packed ice. These
reverse recipes are disabled; machine freezing/washing recipes, snow
recipes and ordinary ice crafting are unchanged.
Both audited JARs match production SHA-256: Farmer's Cutting Everything
`3c8c9681bc4b7d9f2882d0df3dabdd44cb78c2c4930b4603c8436fbb383e86c4`,
Extra Delight `5a26dcd540efdba068894e27a3b4d5663e29e236aff948215f4919684bb3cffd`.
An installed Minecraft `MultiPackResourceManager` probe compared the
previous and new rules: 724 -> 722 Farmer's Cutting Everything recipe
resources and 2030 -> 2028 Extra Delight resources. Both positive controls
contained their two targets; each resulting resource set equals its
original set minus exactly those targets. Probe:
`/tmp/wowmine-ice-filter/IceFilterProbe.java`.
Native NixOS profile:
`/nix/store/dr2ng9cyag3qadr3lg420brnjfrdllpp-nixos-system-neuro-26.05.20261006.b253099`.
Build, closure copy, dry activation and switch exited zero. Activation held
the existing maintenance/backup lock and restarted Minecraft. Live metadata
SHA-256 matches source:
`0054e20934eb834823f8da0a0a50afca3c3bb55b8f34c7f1e7699d0a0674319c`.
All 14 rules-pack file paths remain; only `pack.mcmeta` changed. Previous
rules are saved at neuro `/var/tmp/wowmine-ice-filter/rules-before/`.
Backup timer is active. No mod/client release or player NBT was edited.
No manual in-game ice-cutting trial was performed.
The historical tables below still show the original recipes, including
already corrected or disabled entries; consult the removal sections above.
## One-string wool cutting — 2026-11-22
The server datapack filters `rusticdelight:wool`, whose cutting recipe uses
`#minecraft:wool` and shears to return two string. The exact resource filter
is namespace `^rusticdelight$`, path `^recipe/wool\.json$`.
All 16 Farmer's Cutting Everything color-specific wool recipes remain:
each returns exactly one string using shears. Rustic Delight's separate
carpet recipe, also returning one string, remains unchanged.
An installed Minecraft `MultiPackResourceManager` probe exposed 282 Rustic
Delight recipe resources before the filter and 281 afterward, excluding
exactly `recipe/wool.json` while retaining `recipe/wool_carpet.json`.
Farmer's Cutting Everything's 722 resources were identical before and after;
the probe parsed all 16 wool outputs and verified one string per recipe.
Production Rustic Delight SHA-256 matches the probe fixture:
`ad3d796132984a8d06184d7c9543d6f8b87df4dac33a5dd9b8f124e95afe6801`.
Probe: `/tmp/wowmine-wool-filter/WoolFilterProbe.java`.
Native NixOS profile:
`/nix/store/p03f64gvyg48jpwgck1kj24ssrf7qnwr-nixos-system-neuro-26.05.20261006.b253099`.
Build, copy, dry activation and switch exited zero. Activation held the
existing maintenance/backup lock and restarted Minecraft. All 14 rules-pack
file paths remain; only `pack.mcmeta` changed. Live/source metadata SHA-256:
`02d10042f637d43fba1c1e282a4bed68246a509a888d0ccc50a4d9448ee9498d`.
Prior rules are saved at neuro `/var/tmp/wowmine-wool-filter/rules-before/`;
backup timer is active. No mod/client release or player NBT was edited.
No manual in-game wool-cutting trial was performed.
Scope is the reported cutting-board conflict. Inspection also found
`create:milling/wool` (one string), `create:crushing/wool` (two string plus
a 50% third), and `minecraft:string` from Peruvian's Delight (four string).
Those machine/crafting routes are unchanged; broader scope was asked about
separately and had no answer when this change was applied.
## Direct duplication and mismatched conversion ratios
Unless noted, cutting IDs have prefix `farmerscuttingeverything:cutting/` and
come from `farmers-cutting-everything.jar`. Cutting consumes one ordinary tool
durability per operation; this cost does not correct the material ratios.
| Cutting ID suffix | Input and output | Loop or issue |
| --- | --- | --- |
| `honeycomb` | 1 honeycomb -> 4 honeycomb; knife | Direct self-duplication. |
| `iron_door` | 1 iron door -> 6 iron doors; pickaxe | Direct self-duplication; output really is doors. |
| `iron_bars` | 1 bar -> 5 iron nuggets; pickaxe | Vanilla `minecraft:iron_bars`: 6 ingots -> 16 bars. 54 nuggets become 80. |
| `armor_stand` | Stand -> 7 sticks + smooth stone slab; axe | Vanilla stand costs 6 sticks + same slab. Gain one stick. |
| `bowl` | Bowl -> oak plank; axe | Vanilla `minecraft:bowl`: 3 planks -> 4 bowls. 3 oak planks become 4. |
| `firework_rocket` | Rocket -> paper + guaranteed gunpowder + another gunpowder at 75%; knife | Vanilla `minecraft:firework_rocket_simple`: paper + gunpowder -> 3 rockets. At least triple both inputs. |
| `copper_grate` | Grate -> copper block; pickaxe | Vanilla `minecraft:copper_grate_from_copper_block_stonecutting`: block -> 4 grates. Fourfold copper. |
| `exposed_copper_grate` | Grate -> exposed copper block; pickaxe | Same cycle using `minecraft:exposed_copper_grate_from_exposed_copper_stonecutting`. |
| `weathered_copper_grate` | Grate -> weathered copper block; pickaxe | Same cycle using `minecraft:weathered_copper_grate_from_weathered_copper_stonecutting`. |
| `oxidized_copper_grate` | Grate -> oxidized copper block; pickaxe | Same cycle using `minecraft:oxidized_copper_grate_from_oxidized_copper_stonecutting`. |
| `spectral_arrow` | Arrow -> 2 glowstone dust + arrow at 95%; axe | Vanilla recipe: 4 dust + arrow -> 2 spectral arrows. Fortune I guarantees arrow recovery: retain dust, double arrows. |
Additional cross-mod cycles:
| Mod / exact IDs | Cycle |
| --- | --- |
| Ramadan Delight: `ramadandelight:stonecutting/mosaic_tiles` or `ramadandelight:mosaic_tiles`, then `ramadandelight:cutting/cutting/calcite_from_mosaic_tiles` | One calcite becomes one tile; one tile returns four calcite with a pickaxe. Fourfold gain. |
| Immortalers Delight: `immortalers_delight:sniffer_fur_half_tatami_mat`, then `immortalers_delight:sniffer_fur_full_tatami_mat2` | One full mat -> two half mats -> two full mats. No tool or machine required. |
| Ice conversions listed below | Ninefold gain per packing/unpacking tier. |
| DnDesires `dndesires:freezing/snow_block_from_snowball`, then Farmer's Cutting Everything `farmerscuttingeverything:cutting/snow_block` | One snowball -> one snow block -> four snowballs; shovel required for cutting. |
Every combination of a forward and reverse recipe in each following row
produces the indicated amplification:
| Tier | Forward: one item -> one compressed item | Reverse: one compressed item -> nine inputs |
| --- | --- | --- |
| Ice -> packed ice | `create:splashing/ice`; `dndesires:freezing/packed_ice_from_ice`; `create_dragons_plus:freezing/packed_ice_from_ice` | `farmerscuttingeverything:cutting/packed_ice` (pickaxe); `extradelight:cutting/packed_ice_axe` (axe) |
| Packed ice -> blue ice | `create_ultimate_factory:splashing_packed_ice`; `dndesires:freezing/blue_ice_from_packed_ice`; `create_dragons_plus:freezing/blue_ice_from_packed_ice` | `farmerscuttingeverything:cutting/blue_ice` (pickaxe); `extradelight:cutting/blue_ice_axe` (axe) |
Create, DnDesires and Create Dragons Plus require their processing machinery.
These are cross-mod ratio mismatches, not instantaneous crafting-only loops.
## Probabilistic salvage amplification
All cutting IDs here have prefix `farmerscuttingeverything:cutting/`.
Installed FD config sets `cuttingBoardFortuneBonus = 0.1`: Fortune adds
0.1 per level to result probability, with effective cap 100%. Probability
applies per output item. Expected values below use Fortune III.
| Suffix | Cost of crafting one batch | Expected recovered batch |
| --- | --- | --- |
| `activator_rail` | 6 iron + 2 sticks + redstone torch -> 6 rails | 6 iron, 3.9 sticks, 2.7 torches |
| `detector_rail` | 6 iron + stone pressure plate + redstone -> 6 rails | 6 iron, 2.7 plates, 2.7 redstone |
| `powered_rail` | 6 gold + stick + redstone -> 6 rails | 6 gold, 2.7 sticks, 2.7 redstone |
| `rail` | 6 iron + stick -> 16 rails | 8 iron, 16 sticks |
| `andesite` | Diorite + cobblestone -> 2 andesite | 1.6 diorite, 2 cobblestone |
| `coarse_dirt` | 2 dirt + 2 gravel -> 4 coarse dirt | 4 dirt, 3.2 gravel |
| `arrow` | Flint + stick + feather -> 4 arrows | 2.2 flint, 4 sticks, 2.2 feathers |
| `torch` | Coal + stick -> 4 torches | 2.2 coal, 4 sticks |
| `soul_torch` | Coal + stick + soul sand -> 4 torches | 2.2 coal, 4 sticks, 2.2 soul sand |
| `tripwire_hook` | Iron + stick + oak plank -> 2 hooks | 1.6 iron, 2 sticks, 2 oak planks |
| `fire_charge` | Gunpowder + blaze powder + coal -> 3 charges | 1.89 gunpowder, 1.89 blaze powder, 3 coal |
| `lead` | 4 string + slime ball -> 2 leads | 4 string, 1.6 slime balls |
| `scaffolding` | 6 bamboo + string -> 6 scaffolding | 6 bamboo, 2.52 string |
| `tinted_glass` | 4 amethyst shards + glass -> 2 tinted glass | 4 shards, 1.6 glass |
All counterpart crafting IDs are `minecraft:<suffix>`. Scaffolding also has
`mynethersdelight:crafting/scaffolding_alt`, whose bamboo/string alternatives
reach the same cycle. Pickaxe is required except shovel for coarse dirt, axe
for arrows/torches/soul torches/scaffolding, and knife for leads.
Even without Fortune, andesite, arrows, coarse dirt, torches, soul torches and
tripwire hooks return their consumed resources in expectation plus surplus
other material. Expected-value cycles can fail individual batches; they are
not guaranteed perpetual loops from a tiny starting stock.
## Strong resource conversions and balance choices
These are not all bugs. Some intentionally add resource-production routes.
| Source / recipe ID | Exact conversion and qualification |
| --- | --- |
| Farmer's Cutting Everything `farmerscuttingeverything:cutting/copper_bulb` | Vanilla crafting spends 3 copper blocks + blaze rod + redstone for 4 bulbs. Cutting returns 4 copper blocks, expected 1 redstone and 2 blaze powder without Fortune. Gains copper but spends fuel material and tool wear. |
| Same: `cutting/exposed_copper_bulb`, `cutting/weathered_copper_bulb`, `cutting/oxidized_copper_bulb` | Each aged bulb also returns the corresponding full copper block, redstone at 25%, blaze powder at 50%. |
| Same: `cutting/nether_gold_ore` | Nether gold ore + pickaxe -> 2 gold nuggets, another 4 nuggets at 75%, 2 gold ingots at 50%, netherrack at 25%; no smelting. |
| Same: `cutting/bell` | Bell + pickaxe -> stick + gold block. Strong trade/loot-to-gold conversion. |
| Same: `cutting/enchanted_golden_apple` | Enchanted golden apple + pickaxe -> apple + 8 gold blocks. Consumes valuable food. |
| Same: `cutting/trident` | Trident + pickaxe -> stick, 3 prismarine shards at 50%, heart of sea at 10%. |
| Same: `cutting/nether_star` | Nether star, using clock -> 3 wither-skeleton skulls. Consumes star and permits another Wither fight. |
| Same: `cutting/campfire` | Campfire + axe -> 3 sticks, guaranteed charcoal, 2 more charcoal at 50%, another at 25%. No heating operation. |
| DnDesires `dndesires:seething/magma_block_from_netherrack` + FCE `farmerscuttingeverything:cutting/magma_block` | One netherrack -> magma block -> 2 magma cream + two netherrack rolls at 75% each. Fortune III guarantees both: net gain one netherrack and two cream. Requires seething setup and pickaxe wear. |
| DnDesires `dndesires:seething/diamond_shard_from_coal_block` | Coal block -> diamond shard at 25%; 4 shards -> diamond via `dndesires:crafting/diamond_from_diamond_shard`. Expected 16 coal blocks per diamond; seething required. |
| DnDesires `dndesires:seething/diamond_shard_from_deepslate_coal_ore` | Deepslate coal ore -> diamond shard at 75%; expected 5 1/3 ore per diamond. |
| Create Ultimate Factory `create_ultimate_factory:crushing_netherite` | Nether-bricks block -> nether brick, another at 25%, netherite scrap at 0.5%; crushing time 350. Expected 200 consumed blocks per scrap. |
| Same: `create_ultimate_factory:crushing_blackstone` | Blackstone -> wither-skeleton skull at 1%, blackstone returned at 25%; condition requires absent `wstweaks`. |
| Same: `create_ultimate_factory:crushing_coral` | Coral-tag item -> heart of sea at 1%; crushing time 250. |
| Same: `create_ultimate_factory:compacting_coalblock` | 9 coal blocks + 100 mB lava -> diamond at 30%; heated compacting. Expected 270 coal per diamond. |
| Create New Age `create_new_age:sequenced_assembly/enchanted_golden_apple` | Apple + total 8 gold blocks + 8,000,000 energy -> enchanted golden apple. Not an apple-only recipe. |
| Apothic Enchanting `apothic_enchanting:infusion/echo_shard` | Echo shard -> 4 shards through advanced enchanting; Eterna 70, Quanta 50, Arcana 50 required. Intended gated infusion. |
| Same: `apothic_enchanting:infusion/carrot` | Carrot -> golden carrot through enchanting; Eterna 20, Quanta 10–30. |
| Iron's Spellbooks `irons_spellbooks:ancient_debris_from_pyrium` | Pyrium ingot -> 5 ancient debris. No cheap pyrium-producing recipe was established. |
DnDesires seething is not heatless crafting: its implementation requires
seething catalysts and the appropriate heated setup. Ordinary Create washing
of crushed metals is intended timed machinery processing and was not counted
as a cutting-board exploit.
## Food preparation without heat
These are the full food candidates found by the instant-processing checks.
They include possible mistakes and deliberate recipe abstractions; they are
not all equivalent to raw beef becoming a cooked steak.
| Source / recipe ID | Input -> output |
| --- | --- |
| Fast Delights `fastdelights:bacon_cheeseburger` | 2 buns + **raw FD bacon** + cooked beef patty + flaxen cheese wedge + sliced pickles -> bacon cheeseburger |
| Same: `fastdelights:chicken_bacon_cheeseburger` | 2 buns + **raw FD bacon** + chicken patty + cheese wedge + sliced pickles -> chicken bacon cheeseburger |
| Same: `fastdelights:crafting/bacon_cheeseburger_from_cheeseburger` | Cheeseburger + **raw FD bacon** -> bacon cheeseburger |
| Same: `fastdelights:crafting/chicken_n_cheeseburger_from_cheeseburger` | Chicken-and-cheese burger + **raw FD bacon** -> chicken bacon cheeseburger |
| Hearth and Harvest `hearthandharvest:meat_pizza` | 3 raw-meat-tag items + 3 cheese + 2 FD wheat dough + tomato sauce -> meat pizza |
| Same: `hearthandharvest:meat_pizza_from_cheese_pizza` | 3 raw-meat-tag items + cheese pizza -> meat pizza |
| Same: `hearthandharvest:pizza` | Raw meat + vegetable + mushroom + 3 cheese + 2 dough + tomato sauce -> pizza |
| Same: `hearthandharvest:pizza_from_cheese_pizza` | Raw meat + vegetable + mushroom + cheese pizza -> pizza |
| Slavic Delight `slavic_delight:crab_sticks` | Minced cod + red dye -> crab sticks |
| Roll Delight `roll_delight:nether_roll_recipe` | 2 raw porkchops + cooked nether wart -> 2 nether rolls |
| Valheim Delight `valheim_delight:fish_wrap_crafting` | Bread + safe-raw-fish-tag item + cabbage + onion -> fish wrap |
| Same: `valheim_delight:jerky_recipe` | Raw-meat-tag item + onion + honey bottle -> 3 jerky |
| Arbitrary Delight `arbitrarydelight:cutting/pepperonis` | FD minced beef + knife -> 2 pepperoni |
| Baldej Delights `baldejdelights:crafting/egg_barbecue` | Stick + 2 eggs -> egg barbecue |
Raw-meat and raw-fish tags admit multiple installed ingredients; these rows
represent each recipe with all its tag alternatives, not only beef or cod.
The four bacon recipes are especially plausible wrong-ingredient errors.
Pizzas bypass baking. Cured meat and raw-fish wraps may be intentional.
## Packaged examples and cases not established as usable
- `cutt_promix:ex`, in legacy `data/cutt_promix/recipes/ex.json`:
cabbage + knife -> 2 raw gold, plus 2 wheat seeds at 50%. It uses the old
plural directory, an unresolved knife tag and an obsolete result encoding.
No evidence established this as an active 1.21.1 recipe.
- YAFDA contributes optional raw empowered-meat/venison slices to the cooked-meat
tag. This could affect `farmersdelight:barbecue_stick` and
`vintagedelight:meat_pizza`, but availability of those optional meat items was
not established; relevant base mods are absent.
- `farmers_spell:cutting/mithril_scrap`: mithril cheese -> 4 mithril scraps.
Its source recipe already spends 4 scraps + foodgeist cheese, so this refunds
a paid material rather than generating mithril.
- Golden apple cutting refunds its normal eight gold ingots; golden carrot
cutting refunds its normal eight nuggets. These are not free-gold cycles.
- No definite zero-input recipe was found. Empty crafting declarations examined
were explicitly disabled or produced air. No cheap diamond/netherite/emerald
self-amplification or over-refunding diamond/netherite armor dismantling was
established by the checks.
-69
View File
@@ -1,69 +0,0 @@
# wowmine respawn and Overworld access
The server-only `wowmine-world-policy` mod is built from source by Nix and
installed by the Minecraft service's `preStart`. Clients need no additional
mod. It targets Minecraft 1.21.1 and NeoForge 21.1.250.
Valid beds keep their normal respawn behavior. Missing or destroyed beds
fall back to Azeroth at `3742.5 89 8891.5`, matching the existing first-join
spawn. Login records and player dimension transfers targeting the Overworld
also resolve to this Azeroth spawn. Nether portals returning from the Nether
resolve their destination in Azeroth, preserving portal coordinate scaling.
Other dimension destinations remain unchanged.
The Overworld stays registered because Minecraft requires it internally.
This policy prevents normal player entry; it does not delete world files or
unregister the engine dimension.
## Why the race could disappear after a destroyed bed
Production tests on November 22, 2026 confirmed that valid-bed deaths kept
Tiny's scale at 0.5. Destroying the bed caused vanilla fallback to the
Overworld and scale 1.0, despite the saved Tiny selection remaining intact.
Reconnecting restored the abilities.
The Overworld's shared spawn, at `3742 89 8891`, is above ocean water.
An isolated reproduction with the same 227 mod JARs traced the failure:
1. `PlayerList.respawn` constructs the replacement `ServerPlayer`.
2. Its constructor searches for a collision-free spawn over water.
3. NeoOrigins' fluid-collision hook queries `ActiveOriginService` before the
old player's origin attachment has been copied.
4. The resulting empty cache has data version 0. The copied, serialized
attachment also has version 0, so the cache remains valid even though the
origin selection changed from empty to populated.
5. The respawn grant sees no powers. Later cache rebuilding does not grant
the missing permanent attribute modifiers; login does.
The world policy selects Azeroth in `PlayerRespawnPositionEvent`, before
Minecraft constructs the replacement player. This avoids the ocean spawn
initialization path. It does not reset races or repeatedly rewrite player
attributes.
## Verification
Use a disposable matching server and real client, never production test
deaths or player-data edits. The regression fixture needs water beneath the
Overworld spawn; an ordinary flat-world spawn does not expose the cache bug.
Load the selected race from a saved player record rather than selecting it
again before each death.
Checks exercised during development:
- A real bed click saves the Azeroth point; death returns beside that bed.
- Death in the Nether with the bed chunk unloaded still returns to the bed.
- A destroyed bed without the policy reproduces Overworld fallback, an
unchanged Tiny selection, an empty power cache, and scale 1.0.
- Missing-bed fallback with the policy selects the Azeroth spawn.
- With the ocean fixture unchanged, two consecutive missing-bed deaths with
the policy retain Tiny's scale 0.5 and resolved powers. Disconnecting and
rejoining preserves the race, class, background, and Azeroth location.
- A saved Overworld login and an explicit Overworld teleport resolve to
Azeroth.
- A real Nether return portal resolves in Azeroth.
- Outland and End entry remain available; a real End exit portal and its
credits return to the selected Azeroth bed.
The production artifact is compiled against the pinned NeoForge server SDK.
Its class files were compared with the runtime-tested prototype. NixOS
activation must use the existing Minecraft maintenance/backup lock.
-65
View File
@@ -1,65 +0,0 @@
# wowmine sleep
The server installs Sleep Time Skip 1.1.0 for NeoForge 1.21.1 from a pinned
CurseForge artifact. Clients need no additional mod.
`wowmine-rules` sets `playersSleepingPercentage` to 100, so all players
counted by Minecraft's sleep rules must sleep. The normal bed and
monster-proximity checks remain.
Azeroth uses Minecraft's shared world clock through `DerivedLevelData`.
That wrapper reads the clock but ignores `setDayTime`, so ordinary sleep
could wake players without advancing the night. The server's world-policy
mod forwards Azeroth's time writes to the shared clock. Respawn and dimension
access behavior remain unchanged.
Sleep Time Skip measures the time change before players wake and queues
catch-up work in the dimension where they slept. Its defaults cover animal
aging, breeding cooldowns, chicken eggs, random block ticks, and selected
machines: furnaces, blast furnaces, smokers, brewing stands, campfires, and
hoppers. Furnaces use their actual tickers, inputs, and fuel.
Only active chunks receive catch-up. The declarative configuration explicitly
allows stationary Create millstones, saws, mechanical presses, depots, mixers,
basins, creative motors and basic shafts/cogwheels. This covers processing
through depots and unheated basin mixing, not universal Create simulation.
Moving contraptions, trains, loose-item physics, belt/funnel networks and
crushing wheels are outside this selected set. Existing machine speed, power,
recipe filters and inventory limits still apply; bulk cutting and pressing
remain disabled.
Simulation is budgeted across server ticks, so some results can appear
shortly after waking. The default cap is 24,000 simulated ticks per skip.
Runtime settings come from the NixOS-managed
`wowmine-server-config/sleeptimeskip-common.toml` and are installed at
`config/sleeptimeskip-common.toml`.
The default 10 ms budget per server tick and two-chunk immediate radius are
retained; the server does not globally accelerate entity AI or player combat.
Verification used a real client sleeping in Azeroth with the matching mod
set. Dawn advanced from 13,000 to 24,003 while only 107 ordinary server ticks
passed. A calf's age advanced by 11,003 ticks. A furnace smelted 55 iron
ingots from 64 ore, consuming seven coal; both dimensions reported identical
shared clocks. No production player was used as a test fixture.
Create integration uses real blocks, physical creative-motor power, the
installed recipe manager and actual inventories on a disposable matching
server. It invokes the public `SleepHook.markSkip(level, 11000)` entry used by
the wake hook and lets the normal simulation job run; it does not call machine
tickers or recipe application itself. The real-client bed/clock test above
covers that unchanged entry path. Vanilla-only and Create-enabled runs use
clean worlds and a 30-ordinary-tick observation window, with recipe choices
made explicit where addons offer multiple outputs.
With Create types enabled, all four fixtures completed after two ordinary
ticks: 64 cobblestone became 64 gravel, one andesite alloy became six shafts
on a depot, one iron ingot became one sheet on a depot, and a basin's andesite
plus iron nugget became one alloy. The vanilla furnace simultaneously produced
55 ingots using seven coal, and the calf aged by 11,002 ticks. With the same
inputs, speeds and filters but the vanilla-only list, 30 ordinary ticks
produced one gravel and no Create saw/press/mixer output.
The test copy once failed before world startup with a Pufferfish's Skills
`RewardRegistry.register` / `HashMap.compute` concurrent-modification error.
Its loader was serialized for QA (`fml.toml maxThreads=1`); that test-only
change is not part of the production configuration.
-96
View File
@@ -1,96 +0,0 @@
# wowmine v16 survival revision
Deployed on neuro on November 22, 2026 after approval to remove Afterlife's
Delight and restart Minecraft.
Subsequent overhead-name and coordinate-display rules are documented in
[minecraft-player-visibility.md](minecraft-player-visibility.md).
## Release
- Version: `v16-survival-r1`.
- Source: `minecraft/pack/wowmine-v16-survival-r1.mrpack`.
- Source SHA-256: `a74f1b121d888247ce0fb8951d21a8c389eecd138f7b1e078430f27c6034261b`.
- NixOS system: `/nix/store/l0x0bys8y8w6y88x3b9c8mh244h48b3k-nixos-system-neuro-26.05.20261006.b253099`.
- Public packwiz release: `037c3b3cefef2bdb57bc8c3bd73fe1ae71b63a024d175b262860a9cba30818a7`.
- Prism ZIP SHA-256: `cb7ff5ca7ffac63f54af36cfd448e2c7a790c959d413d0b0e775c344bef2358f`.
- Minecraft 1.21.1 and NeoForge 21.1.250 remain unchanged.
The source removes exactly `mods/afterlifes_delight-1.1.2.jar` from
`v16-delight-rules-r2`. Every other downloaded-file entry and override payload
remains identical, except client version metadata. There are 227 server JARs
and 237 client JARs. Other installed mod metadata declares no dependency on
Afterlife's Delight. Existing source archives and updater releases remain
available.
## Cause and player state
Installed Afterlife's Delight 1.1.2 bytecode confirms that
`GhostEvents.onConfirmedLivingDeath` records ordinary player deaths when
HardcoreLite is absent. Vanilla `hardcore=false` does not disable this
handler. Its configuration provides no global switch.
The mod persists `ghost_data` and `ghost_visual_state` under
`neoforge:attachments`, using the `afterlifes_delight` namespace. The optional
`ghost` field defaults to false. Its creative-flight attribute modifier is
transient. Resurrection through the mod's food calls `GhostManager`,
clearing ghost state and restoring flight and collision behavior.
After the approved cold stop, all five saved players already had no active
ghost state, pending resurrection food, gravity override or ghost-flight
modifier. Four players were in survival; the existing creative player kept
creative mode. No player NBT edits, inventory resets, teleports or game-mode
changes were needed. All 20 original player, statistics and advancement
records retained their exact SHA-256 values after activation.
Afterlife owns no corpse entity or corpse inventory. Its Sable and Gravestone
hooks restrict interaction; they do not own ordinary equipment. Corpses,
graves, other mod attachments and `.sable` data were not deleted.
Removing the mod also removes its 22 item IDs: pestles, ingredients, stews,
pie slices and pies, plus four placed pie block IDs. These removed items can
be discarded when inventories or containers load. The full original world
was backed up before activation.
## Backup and verification
Cold backup:
`/srv/minecraft/backups/wowMineMap-before-v16-survival-r1-20261122`.
Its private `sha256.json` covers 9331 files, each checked against the stopped
source. World, player data, mods, configuration, access records and importer
cache are included. The generated credential-bearing `server.properties`
was excluded; NixOS retains its declaration. Scheduled backups resumed after
server readiness and integrity checks.
Verified:
- Native NixOS build and closure transfer succeeded.
- Importer completed successfully; all 227 live JAR hashes match the pinned
archive. Only the Afterlife JAR was removed from the previous inventory.
- Minecraft reached `Done` and loaded 18443 recipes, 26 fewer than before.
- All 7235 original region files remain. World name, seed, spawn and
`hardcore=false` match the cold backup.
- All 13 `wowmine-rules` files match the backup, preserving recipe fixes and
Boss map restrictions. RCON reports `mobGriefing=true`.
- Distant Horizons identities remain `wos` and `wos-w1`.
- A disposable server without the mod booted and stopped successfully.
- Actual Java packwiz fresh and v16 upgrade runs installed 237 client JARs,
removed Afterlife and preserved personal options, DH and minimap settings.
- A separate v16 instance upgraded through the published HTTPS endpoint:
237 JARs, Afterlife removed and all three personal settings files preserved.
- RCON's selector for connected players with `ghost:1b` found no matches.
Evidence: neuro `/var/tmp/wowmine-survival/live-integrity.json`,
`cold-state.json`, `players-before.json` and `backup-complete.json`;
workstation `/tmp/wowmine-survival/`.
No graphical client session or in-game death/respawn trial was performed
for this revision. Removal of the owning JAR removes its death handlers;
saved player checks cover all five existing players.
NixOS activation returned status 4 because the pre-existing
`ollama-model-loader.service` could not complete TLS connections to its
registry. Its failures predate this activation. The Minecraft importer and
Minecraft service both report success. Existing upstream optional
recipe/loot warnings and the Mango's Compat `/reload` defect remain outside
this change; this deployment used a restart.
-36
View File
@@ -1,36 +0,0 @@
# Void portals
The rules datapack registers `wowmine:void`: an empty flat generator with no
layers, lakes, features or structures and the vanilla Overworld dimension type.
It has ordinary daylight, water and working beds. Its shared sleep clock is
forwarded to the same clock used by Azeroth.
World Policy1.0.2 routes Nether portals to this dimension and returns from it
to `crafting_azeroth:azeroth`. All three vanilla Nether-key reads inside
`NetherPortalBlock.getPortalDestination` are redirected: source detection,
destination selection and portal search mode. The existing Overworld-key
redirect to Azeroth remains.
`PortalIgnitionMixin` also permits the vanilla fire/portal checks in Azeroth
and the void. Without this, vanilla only ignites frames in Overworld/Nether;
testing a directly created portal would miss this boundary.
Coordinates use scale1:1. Vanilla portal search and construction remain in
charge, including their small obsidian support in an otherwise empty world.
Existing portals in Azeroth may be used. The old Nether remains registered
and its files are retained; End and Outland are not replaced.
This change requires a server restart for dimension registration and a server
policy update. No client mod update is required.
Isolated matching-server QA passed real portal-triggered cow travel from Azeroth
to the void and back, and both ServerPlayer destination APIs. The generated
portal had solid obsidian support and clear exits; its24non-air blocks did not
grow on reuse. A distant chunk was entirely air, used the void biome and had
no structures. The original Nether type remained registered. Actual client
crossing was not run.
The final run also ignited ordinary frames by vanilla fire placement in both
Azeroth and the void. This check failed on the artifact without the ignition
mixin, then passed with it; both real entity crossings and player destination
APIs still passed.
-120
View File
@@ -1,120 +0,0 @@
# Project Zomboid backups
`hectic.services."project-zomboid".backup` creates local backups without stopping
or pausing the server. The default schedule is every 30 minutes. Each run:
1. sends the local RCON `save` command and waits for the configured save grace
period;
2. rsyncs `Zomboid/Saves/Multiplayer/<serverName>` and non-secret server
settings (`SandboxVars`, spawn-points, and spawn-regions) from
`Zomboid/Server`, together with local `Zomboid/mods`, into a private staging
tree;
3. waits five seconds and repeats the rsync to narrow the live-write window;
4. publishes a timestamped `tar.zst` archive; and
5. uploads it to S3 when enabled, then applies local retention.
With `backup.retentionDays = 0`, local timestamped archives are removed after a
successful S3 upload (or after local creation when S3 is disabled). A failed
upload leaves the current archive locally and the next run retries that archive
before creating a new one. Restore archives named `pre-restore` are not managed
by this cleanup.
The service lock prevents overlapping runs. Missing save or server-config paths
skip the run through systemd `ConditionPathExists` checks.
## Consistency and secrets
This is a best-effort backup. It does not stop Project Zomboid and does not use
an atomic filesystem snapshot. The RCON save command flushes the world before
copying, and the second rsync narrows the remaining live-write window, but
neither makes the filesystem copy an atomic snapshot.
Archives do not include the generated server INI, `admin-password`,
host-generated password files, or the S3 credentials file. The server INI is
generated again during service startup; provision secret-backed values separately
after a restore.
## neuro
neuro runs the timer every 30 minutes and stores timestamped backups in
S3 for 14 days. It keeps no regular timestamped backup archives locally:
```text
/var/lib/project-zomboid/backups/archive/
```
The existing `project-zomboid-restore.sh` helper expects the fresh backup it
creates to remain in this directory for rollback. Therefore, with local
retention set to zero, do not use the helper until it is adapted for S3-only
retention; temporarily configure positive local retention for a restore.
Check it with:
```sh
systemctl list-timers project-zomboid-backup.timer
systemctl status project-zomboid-backup.service
journalctl -u project-zomboid-backup.service
```
RCON is enabled on localhost port `27015`; the firewall does not expose this
port. The password is generated at
`/var/lib/project-zomboid/rcon-password` with mode `0600`. The server also uses
`SaveWorldEveryMinutes=15` as a periodic persistence fallback.
## Optional S3 upload
S3 upload is disabled by default. Enabling it requires `bucket`, `endpoint`,
`region`, and an absolute runtime `credentialsFile` outside `/nix/store`. The
endpoint must use HTTPS. systemd reads the environment file without executing
it; this host keeps it owned by `project-zomboid` with mode `0400`:
```sh
AWS_ACCESS_KEY_ID=...
AWS_SECRET_ACCESS_KEY=...
```
Set `backup.s3.prefix` to choose the object-key prefix and
`backup.s3.remoteRetentionDays` to prune old archives from that prefix. Remote
deletion runs only after a successful upload and only matches this server's
archive name prefix. Configure bucket lifecycle expiration/versioning too when
available; it remains the stronger recovery and cleanup control.
## Restore
Restoring must be done while the server is stopped so it cannot modify files
during extraction:
On neuro, regular timestamped archives are retained only in S3. With
valid S3 credentials, download the chosen archive before restoring it:
```sh
aws s3 cp \
s3://backup-hectic-lab/project-zomboid/project-zomboid-servertest-<timestamp>.tar.zst \
/var/lib/project-zomboid/backups/archive/<archive>.tar.zst \
--endpoint-url https://hel1.your-objectstorage.com \
--region hel1
```
The versioned helper creates a fresh current-state backup, stops the timer and
server, validates archive paths, restores the save, and starts both services:
```sh
sudo ./docs/project-zomboid-restore.sh \
/var/lib/project-zomboid/backups/archive/<archive>.tar.zst
```
It writes a rollback archive named
`project-zomboid-<serverName>-pre-restore-<timestamp>.tar.zst` before changing
the save.
```sh
systemctl stop project-zomboid.service
tar --zstd --no-same-owner --no-same-permissions \
-xf /var/lib/project-zomboid/backups/archive/<archive>.tar.zst \
-C /var/lib/project-zomboid
chown -R project-zomboid:project-zomboid /var/lib/project-zomboid/Zomboid
systemctl start project-zomboid.service
```
Re-provision password files and secret-backed INI values before starting.
Verify the restored save and server name before allowing players to reconnect.
-92
View File
@@ -1,92 +0,0 @@
# Project Zomboid on neuro
The native NixOS service is `project-zomboid.service`. Its configuration lives
in `nixos/system/neuro/project-zomboid.nix`; the effective non-secret INI and
sandbox settings are captured in the adjacent JSON files. Runtime state lives
in `/var/lib/project-zomboid`, owned by UID 988 and GID 985.
Players connect to `95.31.254.84:36565`. The server uses UDP 36565 for
discovery and UDP 36566 for game traffic. Existing MikroTik rules forward
both ports unchanged to `192.168.88.10`. RCON TCP 27015 is not forwarded.
The port change was deployed through NixOS after a graceful save and shutdown.
External A2S_INFO on UDP 36565 succeeded; independent external probes reached
both 36565 and 36566. Minecraft, BlueMap and nginx retained their processes.
The migrated installation is Build 42.21.0, Steam build 25485538.
`updateOnStart = false` prevents an incidental SteamCMD upgrade. A deliberate
version upgrade must include a stopped-server backup and client compatibility
check before changing this setting.
The installed LuaDigitalWatchUI 1.0 and RC_RealisticColdMod 2.2.0 snapshots
are copied into `Zomboid/mods/LuaDigitalWatch` and
`Zomboid/mods/RealisticTemperature`. Their `common` and `42` directories remain
intact. Their mod IDs remain enabled; `WorkshopItems` is empty because the
game otherwise automatically replaces the temperature mod with a newer
published version on startup. Clients need matching mod files; automatic
Workshop provisioning is no longer advertised by this server. Preserve these
local copies during updates and restores.
The save remains `servertest`, with the original world identities, account
database, player database, vehicle database and passwords. S3 credentials are
provided by `sus/neuro-project-zomboid.yaml`. Never put runtime passwords or
decrypted SOPS contents in the Nix store.
Backups retain the existing bucket `backup-hectic-lab`, prefix
`project-zomboid`, half-hour schedule and 14-day remote retention.
Local mods are included. See [backup and restore instructions](project-zomboid-backups.md).
Migration recovery copies live under the private directory
`/var/backups/project-zomboid/migration-20261120` on neuro. The former neuro
installation must remain separate from the authoritative hectic-lab save.
Do not restore either copy over a running server.
## Cutover evidence, 2026-11-20
The old server was saved and gracefully stopped with no connected players.
The final offline rsync used content checksums. Independent SHA-256 inventories
matched for all 718,669 regular files (15,939,182,014 bytes), including file
paths, modes and symlink targets:
```text
11082cc5c3386ae591ffe8ce67d8dec57d1f2d53a66fe17fdbee54cc6df84167
```
All three account/player/vehicle databases passed SQLite `quick_check` and
matched byte-for-byte before startup. Counts were two network players, 1,009
vehicles and three whitelist records. Both local mod copies matched their
installed Workshop originals, and startup logs confirmed both loaded.
All 140 captured INI settings matched after the intentional Workshop and
announced-IP changes. All 191 sandbox settings, including nested mod settings,
also matched the original Lua values after startup.
Native NixOS activation on neuro succeeded. External A2S_INFO returned the
server on UDP 16261; independent probes also reached UDP 16262. Authenticated
local RCON succeeded, and external TCP 27015 was unreachable. A full game
client join was not tested.
The first native backup completed successfully and its S3 object was checked:
```text
project-zomboid/project-zomboid-servertest-20261120T123322Z.tar.zst
149420409 bytes
```
The local mod files were verified in backup staging. Regular local archive
retention remains zero after successful upload.
The hectic-lab service and backup timer are absent from the active system.
The original data remains in its private
`/var/backups/project-zomboid/retired-20261120` recovery directory.
Temporary migration masks were removed. The old host's existing D-Bus reload
timeout caused activation to return exit 4; the new system profile, Zomboid
removal, firewall changes and shared nginx/SSH were verified separately.
BlueMap and nginx kept their processes. Minecraft recorded a clean restart at
12:24:30 UTC, before Zomboid activation at 12:31:10 UTC; its cause was not
investigated. No kernel OOM event was found.
The `migration-20261120/cold` directory on neuro is an incomplete copy from an
interrupted transfer and must not be used for recovery. Use the verified
`hectic-lab` snapshot instead. Rolling back an entire old host configuration
can re-enable its former server; restore game data deliberately to one host.
-143
View File
@@ -1,143 +0,0 @@
#!/bin/sh
set -eu
SERVER_NAME=${SERVER_NAME:-servertest}
DATA_DIR=${DATA_DIR:-/var/lib/project-zomboid}
ARCHIVE=${1:-}
usage() {
printf '%s\n' "Usage: $0 /path/to/project-zomboid-${SERVER_NAME}-<timestamp>.tar.zst"
printf '%s\n' "Environment: SERVER_NAME, DATA_DIR"
}
if [ "$(id -u)" -ne 0 ]; then
printf '%s\n' 'Run as root.' >&2
exit 1
fi
if [ -z "$ARCHIVE" ]; then
usage >&2
exit 2
fi
if [ ! -r "$ARCHIVE" ]; then
printf 'Backup archive is not readable: %s\n' "$ARCHIVE" >&2
exit 1
fi
ARCHIVE_DIR="$DATA_DIR/backups/archive"
SAVE_DIR="$DATA_DIR/Zomboid/Saves/Multiplayer/$SERVER_NAME"
SERVER_DIR="$DATA_DIR/Zomboid/Server"
TMP_LIST=$(mktemp)
ROLLBACK_ARCHIVE=''
SERVER_STOPPED=0
RESTORE_SUCCEEDED=0
cleanup() {
rm -f "$TMP_LIST"
}
on_exit() {
status=$?
if [ "$status" -ne 0 ] && [ "$SERVER_STOPPED" -eq 1 ] \
&& [ "$RESTORE_SUCCEEDED" -eq 0 ] && [ -n "$ROLLBACK_ARCHIVE" ]; then
set +e
rm -rf "$SAVE_DIR"
rm -f \
"$SERVER_DIR/${SERVER_NAME}_SandboxVars.lua" \
"$SERVER_DIR/${SERVER_NAME}_spawnpoints.lua" \
"$SERVER_DIR/${SERVER_NAME}_spawnregions.lua"
tar --zstd --no-same-owner --no-same-permissions \
-xpf "$ROLLBACK_ARCHIVE" -C "$DATA_DIR"
chown -R project-zomboid:project-zomboid "$SAVE_DIR" "$SERVER_DIR"
systemctl start project-zomboid.service
systemctl start project-zomboid-backup.timer
printf '%s\n' "Restore failed; current state restored from $ROLLBACK_ARCHIVE" >&2
fi
cleanup
exit "$status"
}
trap on_exit EXIT
if ! tar --zstd -tf "$ARCHIVE" >"$TMP_LIST"; then
printf 'Archive integrity check failed: %s\n' "$ARCHIVE" >&2
exit 1
fi
while IFS= read -r member; do
case "$member" in
Zomboid/*) ;;
*)
printf 'Unsafe archive member: %s\n' "$member" >&2
exit 1
;;
esac
case "$member" in
/*|*../*)
printf 'Path traversal member: %s\n' "$member" >&2
exit 1
;;
esac
done <"$TMP_LIST"
if ! systemctl start project-zomboid-backup.service; then
printf '%s\n' 'Could not create fresh backup of current state.' >&2
exit 1
fi
CURRENT_ARCHIVE=$(find "$ARCHIVE_DIR" -maxdepth 1 -type f \
-name "project-zomboid-$SERVER_NAME-*.tar.zst" \
-printf '%T@ %p\n' | sort -nr | awk 'NR == 1 {sub(/^[^ ]* /, ""); print}')
if [ -z "$CURRENT_ARCHIVE" ]; then
printf '%s\n' 'Fresh current-state backup was not found.' >&2
exit 1
fi
stamp=$(date -u +%Y%m%dT%H%M%SZ)
ROLLBACK_ARCHIVE="$ARCHIVE_DIR/project-zomboid-$SERVER_NAME-pre-restore-$stamp.tar.zst"
cp --reflink=auto "$CURRENT_ARCHIVE" "$ROLLBACK_ARCHIVE" 2>/dev/null \
|| cp "$CURRENT_ARCHIVE" "$ROLLBACK_ARCHIVE"
chmod 0600 "$ROLLBACK_ARCHIVE"
chown project-zomboid:project-zomboid "$ROLLBACK_ARCHIVE"
systemctl stop project-zomboid-backup.timer
systemctl stop project-zomboid.service
SERVER_STOPPED=1
if [ "$(systemctl show project-zomboid --property=ActiveState --value)" != inactive ]; then
printf '%s\n' 'Project Zomboid did not stop; refusing to restore.' >&2
exit 1
fi
rm -rf "$SAVE_DIR"
rm -f \
"$SERVER_DIR/${SERVER_NAME}_SandboxVars.lua" \
"$SERVER_DIR/${SERVER_NAME}_spawnpoints.lua" \
"$SERVER_DIR/${SERVER_NAME}_spawnregions.lua"
tar --zstd --no-same-owner --no-same-permissions \
-xpf "$ARCHIVE" -C "$DATA_DIR"
chown -R project-zomboid:project-zomboid "$SAVE_DIR" "$SERVER_DIR"
systemctl start project-zomboid.service
started=0
for _ in $(seq 1 90); do
if [ "$(systemctl show project-zomboid --property=ActiveState --value)" = active ] \
&& [ "$(systemctl show project-zomboid --property=SubState --value)" = running ]; then
started=1
break
fi
sleep 2
done
if [ "$started" -ne 1 ]; then
printf 'Restore completed, but service did not become healthy. Rollback: %s\n' \
"$ROLLBACK_ARCHIVE" >&2
exit 1
fi
systemctl start project-zomboid-backup.timer
RESTORE_SUCCEEDED=1
printf 'Restore completed.\n'
printf 'Rollback archive: %s\n' "$ROLLBACK_ARCHIVE"
-114
View File
@@ -1,114 +0,0 @@
# wowmine v5 optimization compatibility
Historical release evidence below is unchanged. The source filename uses the
wowmine Storage Box naming contract; its hash identifies the verified v5 bytes,
not a newly verified upload of a renamed object.
Published on 2026-11-12 for Minecraft 1.21.1 / NeoForge 21.1.250.
Sodium 0.8.13, Create 6.0.10, Sable 2.0.5, and all existing mod versions
remain unchanged.
| Component | Version | Side |
| --- | --- | --- |
| ImmediatelyFast | 1.6.15+1.21.1 | Client |
| Entity Culling | 1.11.3 | Client |
| Create: Nowheel | 2.1.1+1.21.1neoforge | Client compatibility fix |
| FerriteCore | 7.0.3 | Both |
| ModernFix | 5.27.27+mc1.21.1 | Both |
| Lithium | 0.15.4+mc1.21.1 | Both |
More Culling is deferred: all 11 stable NeoForge artifacts advertised for
1.21.1 through 1.0.11 require Minecraft `[1.21,1.21.1)`, excluding 1.21.1.
No JAR metadata was patched or dependency check bypassed. Distant Horizons
and spark were not added.
Nowheel addresses Entity Culling hiding entities on Sable sublevels. The
conservative pairing is Entity Culling 1.11.3 with Nowheel 2.1.1, rather than
the newly released Entity Culling 1.12.0.
## Lithium compatibility
Common `config/lithium.properties` disables:
```properties
# Retained game-event dispatchers, issue 783.
mixin.world.game_events.dispatch=false
# Iron's Spellbooks multipart shields, issue 723.
mixin.entity.collisions.intersection=false
```
Client overrides retain both rules and additionally disable:
```properties
# Create Ponder fake-level collisions, issue 771.
mixin.entity.collisions.movement=false
# Create Ponder identification raycasts, issue 663.
mixin.world.raycast=false
```
Sable automatically disables Lithium's unpushable cramming, chunk access,
chunk ticking, and tick scheduler optimizations. Runtime confirmed four
automatic rules plus two manual server rules. Existing ModernFix configuration
is unchanged.
Two method-overwrite warnings are accepted overlap: ModernFix wins over Lithium
for biome temperature and sorted chunk-ticket removal. Temperature implementations
compute the same result; both ticket implementations retain linear compaction.
Disabling the skipped Lithium implementations would only remove warnings.
No warning suppression was added.
## Deployment and checks
Source: `minecraft/pack/wowmine-v5-optimizations.mrpack`.
SHA-256: `d3ec9d8725fbaaaa1e14ced3404a1fb904417ab45b1f632861d8e495e7846211`.
Parent v4: `4a197bc039d6684fa1e652e1242b15d87bd8758de895ea8c4f8455ce6a712df1`.
All previous archive entries and indexed mods are unchanged; only six JAR
entries and the two Lithium configuration files were added.
All prior Storage Box versions and web releases remain available. Fresh
production backups are under
`/srv/minecraft/backups/wowMineMap-before-optimizations-20261112T190256Z`,
with sibling `-mods` and `-config` copies. The working world was not reset.
The existing Azeroth spawn datapack and source-map pin were preserved.
An isolated server loaded, saved, restarted, and reloaded native Azeroth chunks.
Both comparisons passed: 81 chunks, 12,798 control blocks unchanged,
`yPos=-32`, 52-long heightmaps, and cobblestone below spawn unchanged.
The independent comparison after production deployment passed the same checks
against the fresh production backup. All 132 production JAR hashes matched the
new archive, with no extra JARs.
The actual client entered the isolated server, initialized all new mods, and
rendered Azeroth from multiple angles. A real packwiz v4-to-v5 transition also
passed, preserving modified options and selecting the client Lithium settings.
Public HTTPS checks verified the 598-entry index, checksums, source archive,
client settings, and Prism loader pin.
## Existing findings and test limits
Sodium Dynamic Lights 1.0.10 references older Sodium option/rendering classes
and declares a Sodium Options API dependency that conflicts with Reese's
current options. Client logs confirm missing old Sodium mixin targets. This
pre-existing mod was retained; no incompatible Options API was installed.
Full dynamic-lighting functionality is not certified by this update.
Older production logs already contain the same missing recipe/loot registry
entries from Design n' Decor, Artificers, and Craftable Loot Chests.
These were not changed as part of the optimization update.
Client smoke testing used llvmpipe software rendering on OpenGL 4.5. It is not
an FPS comparison; Sable's GPU-specific shaders and every moving-ship/passenger
scenario were not exhaustively tested.
## Primary references
- https://github.com/tr7zw/EntityCulling/issues/299
- https://modrinth.com/mod/create-nowheel/version/3NKOvEei
- https://raw.githubusercontent.com/FxMorin/MoreCulling/v1.0.11/gradle.properties
- https://github.com/FxMorin/MoreCulling/issues/481
- https://github.com/CaffeineMC/lithium/issues/783
- https://github.com/CaffeineMC/lithium/issues/723
- https://github.com/CaffeineMC/lithium/issues/771
- https://github.com/CaffeineMC/lithium/issues/663
- https://github.com/embeddedt/ModernFix/issues/274
- https://github.com/FlashyReese/reeses-sodium-options/issues/170
-204
View File
@@ -1,204 +0,0 @@
# wowmine source versions and reset
The rename target is a byte-identical source copy named
`wowmine-20261114T223938Z-winter-biomes.tar.gz`. Copy publication is planned,
not verified by this documentation change. Historical Storage Box source names
below use the wowmine prefix; recorded hashes and checks apply to the original
verified bytes and do not establish that renamed copies exist. Paths retaining
the old spelling below are explicitly historical rollout receipts or GC roots.
The source map is independent of the running world. Keep every source revision
as a separate archive in Storage Box under `minecraft/map/versions/`.
Never replace an existing version. The original `minecraft/map/wow mine map.rar`
remains the parent source.
Each new version has a UTC timestamp in its filename and a JSON sidecar recording
its SHA-256, parent archive and hash, spawn dimension and coordinates, and changes.
Upload to a temporary filename, verify the remote SHA-256, then rename to the
final version filename. Pin that path and hash in
`nixos/system/neuro/minecraft/wow-mine-map.nix`.
The current source bytes to be copied as
`wowmine-20261114T223938Z-winter-biomes.tar.gz` have
SHA-256 `d1afd169b16b7b50a57c47da46245e93285b46b6c833bfd08941d07d0341b208`
(6,423,189,189 bytes). Archive and JSON manifest were uploaded separately,
fully downloaded again, hash checked, and renamed to immutable Storage Box
paths on 2026-11-15 UTC. The manifest SHA-256 is
`4fd3caff074c1f2f30f55dd82a94fef6fd6918e06243094c4fd39457408facc0`.
The winter revision extends existing snowy plains, snowy taiga, and ice spikes
through the native height Y=-512..2031. The approved northern snowy `the_end`
component becomes snowy plains. Its exact contour contains 218,269 native
4x4 columns; existing winter areas contain 1,384,211 columns. Isolated snow
and ice decorations outside these masks remain unchanged. Together these
cover 1,602,480 columns in 104,637 chunks and 187 Azeroth region files.
The approved contour bundle SHA-256 is
`d15c85c563553c203fb32034f74421bda6a5b00209220ef4f9e780b5900760bd`.
The transformation checks all 1,019,177,280 target biome cells and every
unselected biome cell in each affected chunk. Original non-biome NBT bytes,
chunk membership, region timestamps, and untouched compressed chunk payloads
are preserved. Missing sections added within the native height contain only
air blocks. An independent verifier also checked every modified region header,
every untouched payload, and 512 selected chunks. A private server with the
production NeoForge 21.1.250, Java 21, and 133 mod JARs passed 117 biome predicates
and 216 original-block predicates at nine control points. Biome expectations
use Minecraft's seeded biome sampling, including neighboring quart cells.
On 2026-11-15 UTC the running world received a biome-only overlay, without a
reset or source extraction. Minecraft was stopped before copying the original
187 target region files and player/progress metadata to
`/srv/minecraft/backups/wowMineMap-before-winter-biomes-20261114T223938Z`.
This is a targeted backup, not a full-world snapshot. Separate output MCA files
passed the complete biome/non-biome checks and the independent 512-chunk check
before atomic replacement. All 3,361 other world files retained their SHA-256,
size, ownership, mode, inode, and modification time before server startup,
including entities, POI, playerdata, advancements, statistics, and level metadata.
The original live `SOURCE_VERSION.txt` remains unchanged; the separate overlay
receipt is `/var/tmp/worldofsosal-winter-biomes/live-application.json`.
The old Azeroth `data/DistantHorizons.sqlite` was moved intact into the backup's
`derived-dh/` directory (807,206,912 bytes, SHA-256
`d7c5174889f236bbbeca63be68cb7bd56f85cd96d83d5bd3730af7c089598a30`).
This derived terrain cache must be regenerated to avoid serving old biome LODs.
Other dimensions' caches were preserved. Old source versions and backups remain.
After startup at 00:23:37 UTC on 2026-11-15, the production server passed all
117 biome predicates and 216 block predicates against the pre-change live
baseline at nine control points. Both dimensions registered, temporary
force-load tickets were removed, and `save-all flush` succeeded. The Azeroth
DH database was recreated with the new cache identity. Only `levelKeyPrefix`
changed in the DH configuration; all other parsed TOML settings matched.
The v11 archive, all 133 mod JARs, JVM launcher and memory flags
(`-Xmx24G -Xms2G`), and view/simulation distances 32/32 were verified unchanged.
The public Minecraft status endpoint answered with the v11 MOTD.
No heightmap warnings appeared. All 304 distinct startup error messages matched
the previous 2026-11-13 launch: existing mod compatibility, registry, loot,
recipe, and function errors remain outside this biome change.
Verification reports reside in `/var/tmp/worldofsosal-winter-biomes/`:
`live-patch-report.json`, `live-independent.json`, `live-application.json`,
`live-runtime-report.json`, `live-config-application.json`, and
`live-final-report.json`. These separate offline byte-preservation evidence
from normal game writes after startup.
The parent is `wowmine-20261113T172314Z-outland.tar.gz`,
SHA-256 `bee81bb955099e85ed93ca7c258a9cc48ec1a26590bfe891c869a80ad0094def`
(6,579,158,241 bytes). This is a clean source revision, derived from the spawn
revision below, without gameplay state. It was activated on neuro on 2026-11-13:
the working world was reset through the updated import and reset units.
Previous source archives and existing backups were retained.
Outland is now `crafting_azeroth:outland`. The original source documentation
places its spawn at **-51210 100 7**, Shattrath at `-53787 77 1069`, and the
Hellfire Dark Portal at `-51153 119 7`. Positive X near `51200 116 0` is a
separate rotated Stormwind instance and remains in Azeroth.
All 147 region files west of X=-25600 were moved into Outland without changing
coordinates or MCA bytes: 96,403 chunks, 854,810,624 bytes. All 2,063,716 source
chunks remain accounted for. The new dimension reuses the native Azeroth height
type (`min_y=-512`, `height=2544`) and an empty flat generator. The Azeroth spawn
datapack remains enabled. Updated installation and teleport instructions and
`OUTLAND_SEPARATION.json` are included in the archive.
During the winter overlay the server used a revision-specific Distant Horizons
`server.levelKeyPrefix`, enforced by the modpack importer's `postStart`. This
historical long prefix was later shortened; see `minecraft-prism.md`. The archive
configuration omitted the key, so `postStart` inserted it under `[server]` rather
than only replacing an existing line. This gave clients a fresh terrain-cache
identity for each dimension. Obsolete client terrain
caches can be removed if old Azeroth LODs remain visible. No DH database is
included in the source archive. Ordinary server restarts preserve the working
world; only the explicit reset command imports the source again.
The isolated 2026-11-13 trial registered both dimensions on NeoForge 21.1.250.
All 1,440 sampled block states across seven control chunks matched before and
after a server restart, with `yPos=-32` and 52-long heightmaps. Controls include
Outland spawn, Hellfire, Shattrath, Azeroth spawn, the retained positive-X
instance, and both empty counterpart locations. The v11 client joined, visited
Outland and Shattrath, and returned to Azeroth; screenshots confirmed terrain.
Existing modpack recipe/function errors remain unrelated to this map revision.
After activation, the working server registered both dimensions and passed the
same seven-chunk, 1,440-block comparison with native height metadata. Temporary
force-load tickets were removed after verification. All 133 mod JARs, the v11
release, JVM launcher, and view/simulation distances of 32/32 remained unchanged.
The public Minecraft status endpoint responded successfully. The final restart
with the new DH cache identity began at 21:42:22 UTC on 2026-11-13.
The server now uses the native `crafting_azeroth_height` datapack
(`min_y=-512`, `height=2544`). The modpack importer's `postStart` removes
`dynamicheight-0.2.0+neoforge-1.21-1.21.1.jar` and
`sable_dynamicheight_compat-1.0.0.jar` after every import.
The original pack archive remains unchanged.
With the previous mod configuration, saved Azeroth height changed from
MinY=-512, MaxY=2016 to MinY=-64, MaxY=320 and loaded chunks were rewritten.
The native-height trial checks the 81 chunks around `3742 89 8891`, saves them,
restarts Minecraft, and compares control blocks and chunk height metadata.
The 2026-11-12 trial passed on the main server: 12,798 sampled blocks matched the
source both before and after restart, all 81 chunks retained `yPos=-32` and
52-long heightmaps, and the cobblestone at `3742 88 8891` remained present.
No heightmap-size warnings appeared after restart. Temporary force-load tickets
are removed after the trial. This verifies server loading and persistence;
client login with the changed mod set is a separate check.
The parent spawn revision is
`wowmine-20261112T093842Z-spawn-3742-89-8891.tar.gz`, with SHA-256
`da3f79e5593a5b7485ed371d65341cc1516c78a19a1fba71874ae8c1d90e624c`.
Its parent is retained as `versions/wowmine-original-bc80084d.rar`, with
SHA-256 `bc80084de10a06b0fc2cb1651c61936b9e2fd2288f3f0fe44c964d83a393aa30`.
The immutable spawn revision includes the historical namespace
`worldofsosal_spawn`, which initializes each new
character once at `3742 89 8891` in Azeroth and sets a personal respawn point.
Its maintained source is `nixos/system/neuro/minecraft/wowmine-spawn/`.
The spawn was re-enabled on 2026-11-12 after switching to native dimension height.
The working world was not reset or replaced: only the datapack, world spawn
metadata, and yukkop's personal respawn fields were changed. Player position,
inventory, and other player data were preserved. A full pre-change world copy is
kept at `/srv/minecraft/backups/wowMineMap-before-spawn-20261112T133407Z`.
After restart, the saved world spawn and personal respawn fields were verified
at `3742 89 8891`, with personal `SpawnDimension=crafting_azeroth:azeroth` and
forced respawn enabled. The spawn datapack was enabled in the running server.
Across 81 loaded chunks, all 12,798 control blocks matched the pre-change working
world; `yPos=-32`, 52-long heightmaps, and the cobblestone below spawn were
preserved. There were no heightmap-size warnings. The temporary force-load
tickets were removed after verification.
To discard all gameplay changes and return to the pinned source:
```sh
ssh neuro systemctl start minecraft-world-reset-wowMineMap.service
```
This command deletes the entire working world, including all dimensions,
inventories, player positions, advancements, and statistics. It first verifies
the cached source archive's SHA-256, stops the game and world importer, deletes
`/srv/minecraft/wowMineMap/world`, then starts the server. The existing importer
extracts the pinned archive before Minecraft starts.
Mods, server configuration, operator permissions, and source archives remain.
Ordinary server restarts preserve the working world; only the explicit reset
command discards it.
Check completion with:
```sh
ssh neuro systemctl status minecraft-world-reset-wowMineMap.service \
minecraft-world-import-wowMineMap.service minecraft-server-wowMineMap.service \
--no-pager
```
An inactive reset service with exit status 0 is expected after completion.
The cache must already contain the pinned archive. To switch source versions,
deploy the changed importer and cache the verified archive before resetting.
The initial deployment on neuro installs the generated import and reset units
under `/etc/systemd/system.control/`, with GC roots
`/nix/var/nix/gcroots/worldofsosal-world-{import,reset}-unit`. This avoids an
unrelated NixOS upgrade. These persistent units override ordinary NixOS units:
replace both links and GC roots when deploying another source revision, or
remove the overrides after a full NixOS activation includes the same revision.
The modpack importer also has an override under `/etc/systemd/system.control/`,
pinned by `/nix/var/nix/gcroots/worldofsosal-modpack-import-unit`. Update or remove
that override under the same rules when changing the modpack import configuration.
-128
View File
@@ -1,128 +0,0 @@
# wowmine
## 1. Purpose
A Russian-language Minecraft server landing page at `/wowmine/`. The existing
Prism publication at `/minecraft/wowmine/` remains the source of downloads
and updates. This page never publishes or changes a client pack or server world.
Primary action: download the auto-updating Prism instance.
Information priorities: the Azeroth/Outland world, how to install, how to connect.
Required content: Prism ZIP, server address, Minecraft 1.21.1, NeoForge 21.1.250,
Java 21, 8 GiB instance allocation, permission for the pre-launch updater,
preserved options.txt, managed configuration updates, relaunch after a loader
update, manual mrpack and checksums.
Left out: invented player counts, fake live status, reviews, prices, account
forms, tracking, external JavaScript, and changes to the existing pack publisher.
## 2. Direction
Minecraft's tangible game-menu language: square controls, inset highlights,
block geometry, earthy stone surfaces, warm sunlight and a grassy green action.
The hero is an original fictional voxel illustration, not a server screenshot.
Russo One gives the Cyrillic display a block-built silhouette; Golos Text keeps
instructions readable. No official Minecraft logo or character art is used.
The alternatives were a generic launcher dashboard and a parchment fantasy
page. Both obscure the requested Minecraft identity; neither is used.
Material exceptions to the general frontend defaults are deliberate: square
bevels and small hard shadows evoke Minecraft controls, not SaaS cards.
## 3. Tokens
Both light and dark palettes and the deployed theme switch are retained.
Dark: background `#141a15`, raised `#202921`, inset `#101610`,
text `#f4f3e7`, muted `#bec9b8`, line `#394638`.
Shared: grass `#a7d754`, grass hover `#b9e66c`, action ink `#17250d`,
focus `#e8b86c`;
hero ink `#fffdf0`, hero muted `#e5e9d7`.
Type: Russo One 400 for display/headings, Golos Text 400/600 for UI/body;
system monospace only for the server address and filenames.
Display: 36–84px; h2: 32–48px; h3: 24–28px; body: 16–18px; small: 14px.
Space: 4, 8, 12, 16, 24, 32, 48, 64, 80, 96px.
Container: 1200px maximum, 24px mobile and 48px desktop gutters.
Controls: minimum 48px tall, square corners; focus outline 3px with 4px offset.
Motion: 140ms ease-out for press/hover feedback; no ambient loops.
## 4. Layout
Layout: wowmine page - a world introduction followed by installation and help ->
main-with-rail (https://github.com/changeroa/StyleGallery/blob/main/patterns/split-sidebar/main-with-rail.md);
scroll owner: document; anti-patterns: no fixed-height scroll panels, no hidden
mobile content, no visual reordering that changes keyboard order.
Layout: installation - sequential setup actions ->
step-nav (https://github.com/changeroa/StyleGallery/blob/main/patterns/stacking/step-nav.md);
scroll owner: document; anti-patterns: no horizontal step scroller and no
same-size feature-card grid.
The hero uses one scenic image and readable text over a dark scrim.
Below it, theme-aware stone surfaces hold the server address and setup
instructions. Desktop has a narrow requirements rail; mobile stacks in DOM
order. Footer stays in normal flow. The whole page reflows down to 320px.
## 5. Components and states
- Brand: original block mark plus wowmine, linked to the page start.
- Navigation: in-page links; no account or fake menu.
- Primary download: `wowmine-Prism.zip`, suggested filename `wowmine.zip`; one
prominent button with hover/pressed/focus states.
- Copy-address row: address always visible; stable-size icon button; polite,
reserved feedback for success or clipboard denial. Address remains selectable.
- Setup list: three numbered instructions with real destinations and named
files; no interaction required to read the instructions.
- Requirements list: semantic description list, not performance claims.
- FAQ: native details/summary, visible keyboard focus and open-state icon.
- Theme: light and dark appearances, with the existing theme switch preserved.
## 6. Content and assets
Verified existing source: `docs/minecraft-prism.md`, the public active page,
and `script/build-prism-pack.py`. Stable links stay under
`/minecraft/wowmine/`; Prism ZIP is not a plain mrpack import.
Fonts are self-hosted Google Fonts releases under OFL, with notices beside them.
Hero art is generated specifically for this page; original generation is
retained in task evidence, and the shipped asset is a compressed WebP.
All other graphics are small SVG interface glyphs and an original favicon.
## 7. Accessibility and browser surfaces
Semantic landmarks, one h1, ordered h2/h3 headings, skip link, native FAQ,
visible focus, text selection, themed scrollbars, no color-only instructions.
Target: WCAG 2.2 AA contrast and reflow; touch controls 44px or larger.
Reduced motion disables smooth scrolling and transforms. The static document
works without JavaScript: downloads, setup, FAQ, and selectable IP remain usable.
Both light and dark appearances are checked on mobile and desktop; the component state harness is
the real page, exercised through browser interactions.
## 8. Evidence and accepted debt
Before captures: `/tmp/wowmine-qa/before-{desktop,mobile}.png`.
After captures and checks: `/tmp/wowmine-qa/`.
Publication is separate from local implementation and must be reported honestly.
No visual debt accepted yet.
Verified locally in Chromium: 1440px and 390px, both themes, installation
layout, native FAQ expansion, clipboard success and permission denial,
visible keyboard focus, and no horizontal overflow at 320px.
Captures: `after-{desktop,mobile}-{light,dark}.png`, `mobile-install.png`,
and `reflow-320.png` in the evidence directory.
HTTP preview serves the redirect, document, scripts, fonts and image; the three
existing public download/checksum URLs return 200.
Nix parsing and isolated route evaluation pass. Bun browser bundling and the
frontend draft guard pass. Full NixOS deployment was not run.
The frontend detect renderer cannot run on installed Bun 1.2.13 because
`Bun.WebView` is unavailable; browser checks above were run directly instead.
TypeScript and editor language servers are not installed; browser bundling
checks JavaScript syntax, not a full TypeScript analysis.
## 9. Gap ledger
| ID | Before | Required improvement | Proof |
| --- | --- | --- | --- |
| G1 | `/wowmine` returns 404 | Add a Nix-owned static route | Route evaluation and HTTP preview |
| G2 | Bare browser-default text | Minecraft identity and readable hierarchy | Desktop/mobile screenshots |
| G3 | Instructions lack structure | Ordered setup, requirements and FAQ | Browser landmarks and links |
| G4 | IP is plain text | Copy action with accessible feedback | Keyboard and clipboard states |
| G5 | No responsive/theme system | 320px reflow and both themes | Reflow/contrast probes |
Generated
+105 -169
View File
@@ -1,25 +1,5 @@
{
"nodes": {
"affine-rust-overlay": {
"inputs": {
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1792913333,
"narHash": "sha256-wjoZGhxH/Yr+OsFRpNyV9DpMGQIdNEjjAOinfzQvadk=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "fad80eb74614f7dc37c1c83df8caae64361eda22",
"type": "github"
},
"original": {
"owner": "oxalica",
"repo": "rust-overlay",
"type": "github"
}
},
"aquamarine": {
"inputs": {
"hyprutils": [
@@ -186,13 +166,13 @@
"locked": {
"lastModified": 1767039857,
"narHash": "sha256-vNpUSpF5Nuw8xvDLj2KCwwksIbjua2LZCqhV1LNRDns=",
"owner": "NixOS",
"owner": "edolstra",
"repo": "flake-compat",
"rev": "5edf11c44bc78a0d334f6334cdaf7d60d732daab",
"type": "github"
},
"original": {
"owner": "NixOS",
"owner": "edolstra",
"repo": "flake-compat",
"type": "github"
}
@@ -242,11 +222,11 @@
]
},
"locked": {
"lastModified": 1788450739,
"narHash": "sha256-glZLQlzIn1fXH6PazR2iUmTo7kzzyYSshrWhLS9TqCU=",
"lastModified": 1749398372,
"narHash": "sha256-tYBdgS56eXYaWVW3fsnPQ/nFlgWi/Z2Ymhyu21zVM98=",
"owner": "hercules-ci",
"repo": "flake-parts",
"rev": "31729ca8cbdb4fa927b34e5f4353e6a83f39e993",
"rev": "9305fe4e5c2a6fcf5ba6a3ff155720fbe4076569",
"type": "github"
},
"original": {
@@ -255,6 +235,24 @@
"type": "github"
}
},
"flake-utils": {
"inputs": {
"systems": "systems_4"
},
"locked": {
"lastModified": 1731533236,
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"git-hooks": {
"inputs": {
"flake-compat": [
@@ -268,11 +266,11 @@
]
},
"locked": {
"lastModified": 1778507602,
"narHash": "sha256-kTwur1wV+01SdqskVMSo6JMEpg71ps3HpbFY2GsflKs=",
"lastModified": 1775585728,
"narHash": "sha256-8Psjt+TWvE4thRKktJsXfR6PA/fWWsZ04DVaY6PUhr4=",
"owner": "cachix",
"repo": "git-hooks.nix",
"rev": "61ab0e80d9c7ab14c256b5b453d8b3fb0189ba0a",
"rev": "580633fa3fe5fc0379905986543fd7495481913d",
"type": "github"
},
"original": {
@@ -352,16 +350,16 @@
]
},
"locked": {
"lastModified": 1790996401,
"narHash": "sha256-f+kOxEmOUnQazVAmGg0i8hzwgd1kX/geY+k/Dpheye8=",
"lastModified": 1770260404,
"narHash": "sha256-3iVX1+7YUIt23hBx1WZsUllhbmP2EnXrV8tCRbLxHc8=",
"owner": "nix-community",
"repo": "home-manager",
"rev": "db7d5e2332710f5abb088f6b5de927d7f9511b35",
"rev": "0d782ee42c86b196acff08acfbf41bb7d13eed5b",
"type": "github"
},
"original": {
"owner": "nix-community",
"ref": "release-26.05",
"ref": "release-25.11",
"repo": "home-manager",
"type": "github"
}
@@ -627,28 +625,6 @@
"type": "github"
}
},
"iana-angl": {
"inputs": {
"nixpkgs": [
"nixpkgs"
],
"rust-overlay": "rust-overlay"
},
"locked": {
"lastModified": 1789498292,
"narHash": "sha256-bsrT7MWTXL+tpwDZmI5xWLPZZPYAzU1WjcGlNmqpePw=",
"ref": "refs/heads/master",
"rev": "2937d257d601b40de2437a51ebc3c7b61b40f679",
"revCount": 37,
"type": "git",
"url": "https://gitea.hectic-lab.com/yukkop/learning.git"
},
"original": {
"rev": "2937d257d601b40de2437a51ebc3c7b61b40f679",
"type": "git",
"url": "https://gitea.hectic-lab.com/yukkop/learning.git"
}
},
"impermanence": {
"locked": {
"lastModified": 1737831083,
@@ -664,6 +640,34 @@
"type": "github"
}
},
"ixx": {
"inputs": {
"flake-utils": [
"nixvim",
"nuschtosSearch",
"flake-utils"
],
"nixpkgs": [
"nixvim",
"nuschtosSearch",
"nixpkgs"
]
},
"locked": {
"lastModified": 1748294338,
"narHash": "sha256-FVO01jdmUNArzBS7NmaktLdGA5qA3lUMJ4B7a05Iynw=",
"owner": "NuschtOS",
"repo": "ixx",
"rev": "cc5f390f7caf265461d4aab37e98d2292ebbdb85",
"type": "github"
},
"original": {
"owner": "NuschtOS",
"ref": "v0.0.8",
"repo": "ixx",
"type": "github"
}
},
"mechabellum-replay-analysis": {
"inputs": {
"nixpkgs": [
@@ -684,27 +688,6 @@
"url": "ssh://git@github.com/LysmiMx/mechabellum-replay-analysis.git"
}
},
"nix-darwin": {
"inputs": {
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1783744694,
"narHash": "sha256-2cp6N3rrwnGYLTx9l6N+NI+kwrCWxvJUbj5WJhvB29A=",
"owner": "nix-darwin",
"repo": "nix-darwin",
"rev": "c3e90c89649b07d1a96e4b9dd6cd0d6e44b91a74",
"type": "github"
},
"original": {
"owner": "nix-darwin",
"ref": "nix-darwin-26.05",
"repo": "nix-darwin",
"type": "github"
}
},
"nix-minecraft": {
"inputs": {
"flake-compat": "flake-compat_3",
@@ -822,16 +805,16 @@
]
},
"locked": {
"lastModified": 1779650959,
"narHash": "sha256-dbO78C+xfY70Rg1YoMNgOSrYV85l1GmaS11auZeF9Sg=",
"lastModified": 1764075412,
"narHash": "sha256-d1+H7z21NsXgk9vL/9LAPUuiKrq9iqFxxqAWNNk1gY0=",
"owner": "simple-nixos-mailserver",
"repo": "nixos-mailserver",
"rev": "04094b9a1c120eb249e54b77963ae130f5b0d83d",
"rev": "8d35f004eeb47cfcfa5c4e1c8765f5c1bf64b9a0",
"type": "gitlab"
},
"original": {
"owner": "simple-nixos-mailserver",
"ref": "snm-26.05",
"ref": "snm-25.11",
"repo": "nixos-mailserver",
"type": "gitlab"
}
@@ -889,34 +872,18 @@
"type": "github"
}
},
"nixpkgs-gitea": {
"locked": {
"lastModified": 1790323409,
"narHash": "sha256-VVTPf+Hyd5ebpjBMHmrLMSBIeW6ls48Bqtosj7CNKLA=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "e94cb152ed51bd6e24eb4a41f1460252beb52cd2",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs_2": {
"locked": {
"lastModified": 1791254437,
"narHash": "sha256-qMSsgG+9tIdx282dMqGuJAUK3t6F36clM6efd0rXfes=",
"lastModified": 1779796641,
"narHash": "sha256-ZsIrKmhp4vbBXoXXmR/tBXA/UCsAQiJL9vsgZEduhVY=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "b25309931cfda5f0b8805f462a29897eeae50168",
"rev": "25f538306313eae3927264466c70d7001dcea1df",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-26.05",
"ref": "nixos-25.11",
"repo": "nixpkgs",
"type": "github"
}
@@ -927,44 +894,45 @@
"nixpkgs": [
"nixpkgs"
],
"systems": "systems_4"
"nuschtosSearch": "nuschtosSearch",
"systems": "systems_5"
},
"locked": {
"lastModified": 1789959143,
"narHash": "sha256-9oBHyJtUyunZL+6v0Ub8Y759cXcejQiTHpXtGcx5RLs=",
"lastModified": 1769049374,
"narHash": "sha256-h0Os2qqNyycDY1FyZgtbn28VF1ySP74/n0f+LDd8j+w=",
"owner": "nix-community",
"repo": "nixvim",
"rev": "4836e77b1798cd42e2de28593bec4c1788da08f5",
"rev": "b8f76bf5751835647538ef8784e4e6ee8deb8f95",
"type": "github"
},
"original": {
"owner": "nix-community",
"ref": "nixos-26.05",
"ref": "nixos-25.11",
"repo": "nixvim",
"type": "github"
}
},
"piu-piu": {
"nuschtosSearch": {
"inputs": {
"flake-utils": "flake-utils",
"ixx": "ixx",
"nixpkgs": [
"nixvim",
"nixpkgs"
],
"rust-overlay": "rust-overlay_2"
]
},
"locked": {
"lastModified": 1794607706,
"lfs": true,
"narHash": "sha256-uboAhaoXSrasdmnq1/fzag+2CNw7CfPO+KKQxCIRGU4=",
"ref": "refs/heads/main",
"rev": "1312bb414d97e04ca0b9ac062fb75c58a0455c00",
"revCount": 171,
"type": "git",
"url": "ssh://gitea@gitea.hectic-lab.com/liquiz/recompile.git"
"lastModified": 1749730855,
"narHash": "sha256-L3x2nSlFkXkM6tQPLJP3oCBMIsRifhIDPMQQdHO5xWo=",
"owner": "NuschtOS",
"repo": "search",
"rev": "8dfe5879dd009ff4742b668d9c699bc4b9761742",
"type": "github"
},
"original": {
"lfs": true,
"type": "git",
"url": "ssh://gitea@gitea.hectic-lab.com/liquiz/recompile.git"
"owner": "NuschtOS",
"repo": "search",
"type": "github"
}
},
"pre-commit-hooks": {
@@ -992,72 +960,25 @@
},
"root": {
"inputs": {
"affine-rust-overlay": "affine-rust-overlay",
"deploy-rs": "deploy-rs",
"disko": "disko",
"hectic-landing": "hectic-landing",
"home-manager": "home-manager",
"hyprland": "hyprland",
"iana-angl": "iana-angl",
"impermanence": "impermanence",
"mechabellum-replay-analysis": "mechabellum-replay-analysis",
"nix-darwin": "nix-darwin",
"nix-minecraft": "nix-minecraft",
"nixos-anywhere": "nixos-anywhere",
"nixos-hardware": "nixos-hardware",
"nixos-mailserver": "nixos-mailserver",
"nixos-wsl": "nixos-wsl",
"nixpkgs": "nixpkgs_2",
"nixpkgs-gitea": "nixpkgs-gitea",
"nixvim": "nixvim",
"piu-piu": "piu-piu",
"rust-overlay": "rust-overlay_3",
"rust-overlay": "rust-overlay",
"sops-nix": "sops-nix"
}
},
"rust-overlay": {
"inputs": {
"nixpkgs": [
"iana-angl",
"nixpkgs"
]
},
"locked": {
"lastModified": 1789457514,
"narHash": "sha256-Aggle++fTyAifBy+QBPxjM+obO5iepKW/8MDxQtgGvI=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "89e99bf0778a8f2cd18c9360c3f19c1ee47fc739",
"type": "github"
},
"original": {
"owner": "oxalica",
"repo": "rust-overlay",
"type": "github"
}
},
"rust-overlay_2": {
"inputs": {
"nixpkgs": [
"piu-piu",
"nixpkgs"
]
},
"locked": {
"lastModified": 1794476126,
"narHash": "sha256-KBjfmgZIUqBpjsemRKp4GvrCf8DlNsldkmxphh4X9oo=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "d1e30fd696e1151603aa8adaa8f6b8c604fe3eb0",
"type": "github"
},
"original": {
"owner": "oxalica",
"repo": "rust-overlay",
"type": "github"
}
},
"rust-overlay_3": {
"inputs": {
"nixpkgs": [
"nixpkgs"
@@ -1084,11 +1005,11 @@
]
},
"locked": {
"lastModified": 1791103873,
"narHash": "sha256-nFxM+pKoZ8LJAEnUXARyCaOAloWgaW9kZQOSjWzKcTE=",
"lastModified": 1764483358,
"narHash": "sha256-EyyvCzXoHrbL467YSsQBTWWg4sR96MH1sPpKoSOelB4=",
"owner": "Mic92",
"repo": "sops-nix",
"rev": "dcd241ba97088c22569d1573286e1b9daad340c0",
"rev": "5aca6ff67264321d47856a2ed183729271107c9c",
"type": "github"
},
"original": {
@@ -1157,6 +1078,21 @@
"type": "github"
}
},
"systems_5": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
},
"treefmt-nix": {
"inputs": {
"nixpkgs": [
+7 -30
View File
@@ -2,7 +2,6 @@
description = "yukkop's nix utilities";
nixConfig = {
http2 = false;
extra-substituters = [
"https://cache.nixos.org"
"https://cache.hectic-lab.com/hectic"
@@ -13,18 +12,13 @@
};
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-26.05";
nixpkgs-gitea.url = "github:NixOS/nixpkgs/nixos-unstable";
nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.11";
rust-overlay = {
url = "github:oxalica/rust-overlay";
inputs = {
nixpkgs.follows = "nixpkgs";
};
};
affine-rust-overlay = {
url = "github:oxalica/rust-overlay";
inputs.nixpkgs.follows = "nixpkgs";
};
deploy-rs = {
url = "github:serokell/deploy-rs";
inputs.nixpkgs.follows = "nixpkgs";
@@ -34,7 +28,7 @@
inputs.nixpkgs.follows = "nixpkgs";
};
nixvim = {
url = "github:nix-community/nixvim/nixos-26.05";
url = "github:nix-community/nixvim/nixos-25.11";
inputs.nixpkgs.follows = "nixpkgs";
};
disko = {
@@ -45,11 +39,7 @@
url = "github:nix-community/impermanence";
};
home-manager = {
url = "github:nix-community/home-manager/release-26.05";
inputs.nixpkgs.follows = "nixpkgs";
};
nix-darwin = {
url = "github:nix-darwin/nix-darwin/nix-darwin-26.05";
url = "github:nix-community/home-manager/release-25.11";
inputs.nixpkgs.follows = "nixpkgs";
};
nixos-wsl = {
@@ -68,7 +58,7 @@
inputs.nixpkgs.follows = "nixpkgs";
};
nixos-mailserver = {
url = "gitlab:simple-nixos-mailserver/nixos-mailserver/snm-26.05";
url = "gitlab:simple-nixos-mailserver/nixos-mailserver/snm-25.11";
inputs.nixpkgs.follows = "nixpkgs";
};
nix-minecraft.url = "github:Infinidoge/nix-minecraft";
@@ -78,28 +68,18 @@
url = "git+ssh://git@github.com/liquizz/hectic-landing.git";
inputs.nixpkgs.follows = "nixpkgs";
};
iana-angl = {
url = "git+https://gitea.hectic-lab.com/yukkop/learning.git?rev=2937d257d601b40de2437a51ebc3c7b61b40f679";
inputs.nixpkgs.follows = "nixpkgs";
};
mechabellum-replay-analysis = {
# NOTE(yukkop): private repo - SSH access required.
# Only evaluated when nixosConfigurations."hectic-lab|x86_64-linux" is built.
url = "git+ssh://git@github.com/LysmiMx/mechabellum-replay-analysis.git";
inputs.nixpkgs.follows = "nixpkgs";
};
piu-piu = {
# NOTE(yukkop): private repo - SSH access required.
# Set Port 22223 for gitea.hectic-lab.com in ~/.ssh/config.
# Keep the port out of the URL for Nix's LFS authentication.
url = "git+ssh://gitea@gitea.hectic-lab.com/liquiz/recompile.git?lfs=1";
inputs.nixpkgs.follows = "nixpkgs";
};
};
outputs = {
self,
nixpkgs,
rust-overlay,
...
}@inputs: let
flake = ./.;
@@ -112,13 +92,13 @@
legacyPackages = import ./legacy { inherit system pkgs self; };
pkgs = import nixpkgs {
inherit system;
overlays = [ (import inputs.rust-overlay) ];
overlays = [ (import rust-overlay) ];
};
in
baseOverlay // legacyPackages;
overlays = [ self.overlays.default ];
in self-lib.forAllSystemsWithPkgs ([(import inputs.rust-overlay)] ++ overlays) ({
in self-lib.forAllSystemsWithPkgs ([(import rust-overlay)] ++ overlays) ({
system,
pkgs,
}: {
@@ -143,8 +123,5 @@
"tenix|x86_64-linux" = import ./nixos/system/tenix { inherit flake self inputs; system = "x86_64-linux"; };
"hectic-lab|x86_64-linux" = import ./nixos/system/hectic-lab { inherit flake self inputs; system = "x86_64-linux"; };
};
darwinConfigurations = {
"yukkop|aarch64-darwin" = import ./darwin/system/yukkop { inherit flake self inputs; system = "aarch64-darwin"; };
};
};
}
-30
View File
@@ -1,30 +0,0 @@
{ pkgs, ... }: {
programs.tmux = {
enable = true;
plugins = with pkgs.tmuxPlugins; [ resurrect continuum ];
keyMode = "vi";
escapeTime = 500;
historyLimit = 50000;
newSession = true;
extraConfig = ''
# resurrect
set -g @resurrect-strategy-vim 'session'
set -g @resurrect-strategy-nvim 'session'
set -g @resurrect-capture-pane-contents 'on'
resurrect_dir="$HOME/.tmux/resurrect"
set -g @resurrect-dir $resurrect_dir
set -g @resurrect-hook-post-save-all 'target=$(readlink -f $resurrect_dir/last); sed "s| --cmd .*-vim-pack-dir||g; s|/etc/profiles/per-user/$USER/bin/||g; s|/home/$USER/.nix-profile/bin/||g" $target | sponge $target'
# continuum
set -g @continuum-restore 'on'
set -g @continuum-boot 'on'
set -g @continuum-save-interval '10'
bind-key -T copy-mode-vi v send-keys -X begin-selection
bind-key -T copy-mode-vi C-v send-keys -X rectangle-toggle
bind-key O select-pane -t :.-
'';
};
}
-2
View File
@@ -1,2 +0,0 @@
__pycache__/
*.py[cod]
-162
View File
@@ -1,162 +0,0 @@
# Attic repack migration helper
Local-only operator tool for safe resumable Attic cache repack/migration. Parent automation starts old/new services, supplies secrets, seeds spool, and runs this CLI.
## Deployment layout
### Operational state — 2026-09-10
The primary `/hectic` endpoint now serves `nix-cache-hectic-lab` through
`atticd-repacked`; the cutover was applied with NixOS `switch`. The original
bucket/database remain preserved and readable at `/previous/hectic`.
`/next/hectic` is an alias for the new backend. Existing public keys and CI
tokens remain valid, and the primary endpoint is writable again.
The migrated inventory contains 1343 paths and 1195 unique NAR hashes. The
independent inventory comparison and aggregate full-read receipts are recorded
in `/var/lib/attic-repack/verification-receipt.json`. Transient S3 504/read errors
required retries; this is data-integrity evidence, not a claim that Hetzner's
read availability is fixed.
All migration, verification, seeding, and watcher jobs have been stopped for
user-controlled load testing. Do not automatically restart bulk verification.
The transport-fix generation is
`/nix/store/mjx3gzrh03vq22j5nmrzwa56kfhdn702-nixos-system-hectic-lab-25.11.20260526.25f5383`
with the HTTP/1.1 S3 transport and upload-proxy timeout correction. Check
`/run/current-system` to confirm the active deployment.
The pinned rollback generation remains at
`/var/lib/attic-repack/rollback-system`; backups remain private under
`/var/lib/attic-repack/backups` and include the cache signing key.
- Original backend: `atticd`, port 8081, `/var/lib/atticd/server.db`, bucket
`cache-hectic-lab` in HEL1.
- During the write freeze and after cutover the original backend runs in
`api-server` mode, without its garbage collector, to preserve the comparison
dataset. Public write methods remain blocked by nginx.
- Repacked backend: `atticd-repacked`, port 8082,
`/var/lib/atticd-repacked/server.db`, bucket `nix-cache-hectic-lab` in HEL1.
- Both use the same `hectic` signing key and existing JWT verification secret;
clients do not need a new trusted public key or token.
- New chunk settings: threshold/minimum 1 MiB, average 2 MiB, maximum 4 MiB.
- `https://cache.hectic-lab.com/next/hectic` selects the new backend.
- `https://cache.hectic-lab.com/previous/hectic` selects the original backend;
nginx permits GET/HEAD only there.
- `repackedActive` in `nixos/system/hectic-lab/attic.nix` selects which backend
owns the original `/hectic` URL. Keep it false until all cutover gates pass.
## Cutover and rollback gates
1. Finish all migration partitions, then run an unfiltered migration/delta pass.
2. Confirm no CI writers remain. Set `migrationWriteFreeze = true` while
`repackedActive = false`, apply the small NixOS change, and briefly stop the
original Attic to drain/cancel any prior in-flight writes.
3. Take a SQLite backup with SQLite's backup API, not a raw live-file copy.
Keep backups and manifests under private `/var/lib/attic-repack`; the SQLite
backup includes the cache's private signing key.
4. Restart the original backend for reads only, refresh the complete inventory,
migrate any final delta, then run unfiltered `verify` across all 1343 old
paths. Its exit status must be zero with zero exhausted payload verification
failures; independently compare old/new store-path, NAR hash, size and
metadata inventories from the databases. `status` alone is not a cutover
certificate.
5. Pin the old/staging NixOS generation as a GC root, set `repackedActive = true`,
build, inspect dry activation, and switch. `/hectic` now reaches the new
backend; old data and `/previous/hectic` remain available.
6. Test public reads, signatures, and an authenticated upload at the original
URL. Do not remove the old bucket or database as part of this procedure.
Rollback reapplies the pinned staging generation. The new backend and its data
must remain preserved: paths first uploaded after cutover may exist only there.
When editing the flags manually, clear `migrationWriteFreeze` explicitly if
writes to the original backend are intended after rollback.
## Throughput comparison
Compare the same store-path hashes at `/next/hectic` and `/previous/hectic` with
the same request concurrency. For example, fetch
`https://cache.hectic-lab.com/next/hectic/nar/<store-path-hash>.nar` with
`curl --fail --location --output /dev/null --write-out 'bytes=%{size_download} seconds=%{time_total}\n'`.
Do not print effective redirect URLs: S3 redirects contain temporary signatures.
Compare wall time and error rate as well as bytes/second because compressed sizes
can differ after rechunking. Do not use a build with source fallback as a pure
cache throughput measurement. The two endpoints share the VPS and nginx, so run
the comparison sequentially or account for shared-resource contention.
## Spool/state convention
Default state dir: `/var/lib/attic-repack` (`0700`). Raw NAR spool path:
```text
/var/lib/attic-repack/raw/{sha256hex}.nar
```
Parent may seed this file directly. Tool always verifies SHA-256 and byte length before upload. Checkpoints live under `checkpoints/{store_path_hash}.json` and contain no keypair/token. Forced payload verification records a receipt with `payload_verified_at`, `payload_verify_attempts`, `payload_sha256`, and `payload_bytes` only after a complete successful read.
## Commands
```sh
attic-repack init \
--old-db file:/var/lib/atticd/server.db?mode=ro \
--old-url http://127.0.0.1:8081 \
--new-url http://127.0.0.1:8082 \
--host cache.hectic-lab.com \
--atticadm /run/current-system/sw/bin/atticadm \
--server-config /etc/atticd/server.toml
attic-repack inventory --state-dir /var/lib/attic-repack > inventory.json
attic-repack status --state-dir /var/lib/attic-repack
attic-repack migrate --state-dir /var/lib/attic-repack --workers 2 --limit 20
attic-repack verify --state-dir /var/lib/attic-repack --workers 2
```
`ATTIC_MIGRATION_TOKEN` may be set for manual/tests. Otherwise token is minted in memory with `atticadm make-token` for hectic pull/push/create-cache/configure-cache. Token/keypair are never printed.
## Inventory JSON
`inventory` writes `attic-repack-inventory-v1`:
```json
{
"format": "attic-repack-inventory-v1",
"cache": "hectic",
"spool_dir": "/var/lib/attic-repack/raw",
"raw_nar_filename": "{sha256hex}.nar",
"records": [
{"nar_hash":"sha256:...","nar_size":123,"store_path":"/nix/store/...","metadata_fingerprint":"..."}
]
}
```
Records also include upload metadata: `store_path_hash`, `references`, `system`, `deriver`, `sigs`, `ca`.
## Safety
- Checkpoints and `status` are progress information, not a final cutover proof.
After stopping old writers and taking a consistent snapshot, run an unfiltered
`verify` (no `--paths-file` or `--limit`) to reread every new NAR and reconcile
all paths, metadata, hashes, and sizes before switching the primary endpoint.
Do not skip files, change expected hashes, or relax server/client timeouts to
pass this gate.
- A local store path can differ from the historical cached NAR. Such a local
copy is rejected and recovered from the original S3 chunks instead.
- Old DB is opened readonly; old SQL NAR/chunk tables are never copied.
- Missing local raw NARs are reconstructed from old S3 chunkrefs with per-object retries and chunk/full hash checks.
- Upload uses Attic `PUT /_api/v1/upload-path` with JSON preamble plus raw uncompressed NAR.
- New cache verification compares immutable metadata against old rendered narinfo
and reads/decompresses one payload per verified path invocation. Payload reads
make up to three fresh attempts for transport HTTP 408/429/5xx and truncated
body/decompressor EOF failures only. Each attempt follows a new GET/redirect,
starts SHA-256 and byte counts from zero, closes failed readers, and fails
immediately on hash mismatch, full-size mismatch, oversized payload, missing
URL, unsupported compression, or HTTP 4xx other than 408/429.
- A receipt with retries proves the path was fully read and matched integrity; it
does not prove the storage provider is healthy. Treat retry events as provider
health signals separate from cutover correctness.
- Authenticated HTTP is refused unless URL host is loopback.
## Local build/test
```sh
nix build --option eval-cache false --impure --expr "let flake = builtins.getFlake \"git+file://$PWD\"; pkgs = import flake.inputs.nixpkgs { system = builtins.currentSystem; }; in pkgs.callPackage ./infra/attic-migration {}"
nix build --option eval-cache false --impure --expr "let flake = builtins.getFlake \"git+file://$PWD\"; pkgs = import flake.inputs.nixpkgs { system = builtins.currentSystem; }; p = pkgs.callPackage ./infra/attic-migration {}; in p.passthru.tests.unittest"
```
-48
View File
@@ -1,48 +0,0 @@
{ pkgs }:
let
source = pkgs.lib.cleanSourceWith {
src = ./.;
filter = path: type:
builtins.baseNameOf path != "__pycache__"
&& !(pkgs.lib.hasSuffix ".pyc" path);
};
pythonEnv = pkgs.python3.withPackages (ps: [
ps.requests
ps.boto3
ps.zstandard
]);
in
pkgs.stdenv.mkDerivation {
pname = "attic-repack";
version = "0.1.0";
src = source;
nativeBuildInputs = [ pkgs.makeWrapper ];
installPhase = ''
mkdir -p $out/bin $out/libexec/attic-repack
cp $src/repack.py $out/libexec/attic-repack/repack.py
chmod +x $out/libexec/attic-repack/repack.py
makeWrapper ${pythonEnv}/bin/python3 $out/bin/attic-repack \
--add-flags $out/libexec/attic-repack/repack.py \
--prefix PATH : ${pkgs.lib.makeBinPath [ pkgs.nix ]}
'';
doCheck = true;
checkPhase = ''
${pythonEnv}/bin/python3 -m unittest discover -s $src -p 'test_*.py'
'';
passthru = {
inherit pythonEnv;
tests.unittest = pkgs.runCommand "attic-repack-unittest" {
nativeBuildInputs = [ pythonEnv pkgs.nix ];
} ''
cp -r ${source} ./src
chmod -R u+w ./src
${pythonEnv}/bin/python3 -m unittest discover -s ./src -p 'test_*.py'
mkdir -p $out
'';
};
}
File diff suppressed because it is too large Load Diff
-562
View File
@@ -1,562 +0,0 @@
import argparse
import hashlib
import http.server
import io
import json
import os
import pathlib
import sqlite3
import tempfile
import threading
import time
import unittest
from unittest import mock
import repack
def sha(data):
return hashlib.sha256(data).hexdigest()
class FakeResponse:
def __init__(self, status_code=200, content=b"", json_data=None, raw=None, headers=None):
self.status_code = status_code
self.content = content
self._json = json_data
self.raw = raw or io.BytesIO(content)
self.headers = headers or {}
self.close_count = 0
def json(self):
return self._json
def close(self):
self.close_count += 1
class FakeSession:
def __init__(self):
self.calls = []
self.routes = {}
def request(self, method, url, **kwargs):
self.calls.append((method, url, kwargs))
key = (method, pathlib.PurePosixPath(url.split("?", 1)[0]).as_posix())
response = self.routes.get(key) or self.routes.get((method, url))
if callable(response):
return response(method, url, kwargs)
return response or FakeResponse(404)
class ThreadedHTTP:
def __init__(self, handler):
self.server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler)
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
@property
def url(self):
host, port = self.server.server_address[:2]
return f"http://{host}:{port}"
def __enter__(self):
self.thread.start()
return self
def __exit__(self, *_args):
self.server.shutdown()
self.thread.join(timeout=5)
self.server.server_close()
class RepackTests(unittest.TestCase):
def test_options_before_subcommand_are_preserved(self):
parser = repack.build_parser()
args = parser.parse_args(["--atticadm", "/safe/atticadm", "--server-config", "/safe/config", "--workers", "1", "init"])
self.assertEqual(args.atticadm, "/safe/atticadm")
self.assertEqual(args.server_config, "/safe/config")
self.assertEqual(args.workers, 1)
args = parser.parse_args(["--workers", "1", "migrate", "--workers", "2"])
self.assertEqual(args.workers, 2)
def test_inventory_reads_sqlite_reserved_references_column(self):
with tempfile.TemporaryDirectory() as td:
db = pathlib.Path(td) / "old.db"
con = sqlite3.connect(db)
con.executescript('''
CREATE TABLE cache(id INTEGER, name TEXT, deleted_at TEXT);
CREATE TABLE nar(id INTEGER, nar_hash TEXT, nar_size INTEGER, state TEXT);
CREATE TABLE object(cache_id INTEGER, nar_id INTEGER,
store_path_hash TEXT, store_path TEXT, "references" TEXT,
system TEXT, deriver TEXT, sigs TEXT, ca TEXT);
INSERT INTO cache VALUES(1, 'hectic', NULL);
''')
con.execute("INSERT INTO nar VALUES(1, ?, 7, 'V')", ("sha256:" + "a" * 64,))
con.execute("INSERT INTO object VALUES(1, 1, ?, ?, ?, NULL, NULL, ?, NULL)",
("b" * 32, "/nix/store/" + "b" * 32 + "-test", '["dependency"]', '[]'))
con.commit()
con.close()
rows = repack.InventoryDB(str(db), "hectic").records()
self.assertEqual(len(rows), 1)
self.assertEqual(rows[0]["references"], ["dependency"])
def test_metadata_import_keypair_capital(self):
with tempfile.TemporaryDirectory() as td:
db = pathlib.Path(td) / "old.db"
con = sqlite3.connect(db)
con.executescript("""
create table cache(id integer primary key,name text,keypair text,is_public integer,store_dir text,priority integer,upstream_cache_key_names text,retention_period integer,deleted_at text);
insert into cache values(1,'hectic','priv',1,'/nix/store',30,'["up"]',3600,null);
""")
con.close()
args = self.args(td, old_db=str(db))
mig = repack.Migrator(args)
old = mock.Mock()
old.get_cache_config.return_value = {"public_key": "pub"}
new = mock.Mock()
new.get_cache_config.side_effect = [None, {"public_key": "pub"}]
mig.old_client = old
mig.new_client = new
mig.init_cache()
body = new.create_cache.call_args.args[0]
self.assertEqual(body["keypair"], {"Keypair": "priv"})
new.patch_retention.assert_called_with({"Period": 3600})
def test_bad_hash_rejects_raw_spool(self):
with tempfile.TemporaryDirectory() as td:
args = self.args(td)
mig = repack.Migrator(args)
record = self.record(b"good")
raw = mig.state.raw_path(repack.nar_hash_hex(record["nar_hash"]))
raw.write_bytes(b"bad")
with self.assertRaises(repack.RepackError):
mig.ensure_raw_nar(record)
def test_local_mismatch_recovers_original_from_old_s3(self):
with tempfile.TemporaryDirectory() as td:
original = b"original cached NAR"
record = self.record(original)
local = pathlib.Path(td) / "different-local-copy"
local.write_bytes(b"different")
record["store_path"] = str(local)
mig = repack.Migrator(self.args(td))
def recover(_record, path):
path.write_bytes(original)
with mock.patch.object(mig, "dump_local_store_path", side_effect=repack.RepackError("nix dump-path NAR hash/size mismatch")), \
mock.patch.object(mig.s3, "assemble", side_effect=recover) as assemble:
result = mig.ensure_raw_nar(record)
self.assertEqual(result.read_bytes(), original)
assemble.assert_called_once()
def test_no_compile_subprocess_commands(self):
with tempfile.TemporaryDirectory() as td:
args = self.args(td)
mig = repack.Migrator(args)
data = b"nar"
record = self.record(data)
store = pathlib.Path(record["store_path"])
with mock.patch("subprocess.run") as run:
def fake_run(cmd, check, stdout, stderr, env):
self.assertEqual(cmd[:3], ["nix", "nar", "pack"])
self.assertNotIn("build", cmd)
self.assertNotIn(repack.TOKEN_ENV, env)
stdout.write(data)
return mock.Mock()
run.side_effect = fake_run
path = mig.state.raw_path(repack.nar_hash_hex(record["nar_hash"]))
mig.dump_local_store_path(record, path)
self.assertEqual(path.read_bytes(), data)
self.assertTrue(str(store).startswith("/nix/store/"))
def test_resumable_checkpoint(self):
with tempfile.TemporaryDirectory() as td:
state = repack.State(pathlib.Path(td))
record = self.record(b"abc")
state.set_checkpoint(record, "verified", 2)
cp = state.get_checkpoint(record)
self.assertEqual(cp["status"], "verified")
self.assertEqual(cp["tries"], 2)
self.assertEqual(cp["metadata_fingerprint"], repack.metadata_fingerprint(record))
def test_root_backend_upload_preamble(self):
data = b"abc"
record = self.record(data)
with tempfile.TemporaryDirectory() as td:
nar = pathlib.Path(td) / "x.nar"
nar.write_bytes(data)
client = repack.AtticClient("http://127.0.0.1:8082", "hectic", "cache.hectic-lab.com", repack.TokenProvider(None, None, "hectic"))
assert client.token_provider is not None
client.token_provider._token = "tok"
client.token_provider._expires = repack.now() + 3600
sess = FakeSession()
client._local.session = sess
def put(method, url, kwargs):
self.assertTrue(url.endswith("/_api/v1/upload-path"))
self.assertIn("X-Attic-Nar-Info-Preamble-Size", kwargs["headers"])
self.assertEqual(len(kwargs["data"]), int(kwargs["headers"]["Content-Length"]))
body = kwargs["data"].read()
pre = int(kwargs["headers"]["X-Attic-Nar-Info-Preamble-Size"])
meta = json.loads(body[:pre])
self.assertEqual(meta["store_path"], record["store_path"])
self.assertEqual(body[pre:], data)
return FakeResponse(200)
sess.routes[("PUT", "http://127.0.0.1:8082/_api/v1/upload-path")] = put
client.upload(record, nar)
def test_real_http_upload_has_content_length_no_chunked(self):
try:
repack.requests_module()
except ModuleNotFoundError:
self.skipTest("requests not installed outside Nix test env")
data = b"nar-bytes"
record = self.record(data)
seen = {}
class Handler(http.server.BaseHTTPRequestHandler):
def do_PUT(self):
seen["path"] = self.path
seen["host"] = self.headers.get("Host")
seen["te"] = self.headers.get("Transfer-Encoding")
length = int(self.headers["Content-Length"])
body = self.rfile.read(length)
pre = int(self.headers["X-Attic-Nar-Info-Preamble-Size"])
seen["meta"] = json.loads(body[:pre])
seen["nar"] = body[pre:]
self.send_response(200); self.end_headers()
def log_message(self, format, *args):
pass
with tempfile.TemporaryDirectory() as td, ThreadedHTTP(Handler) as srv:
nar = pathlib.Path(td) / "x.nar"
nar.write_bytes(data)
tp = repack.TokenProvider(None, None, "hectic")
tp._token = "tok"; tp._expires = repack.now() + 3600
repack.AtticClient(srv.url, "hectic", "cache.hectic-lab.com", tp).upload(record, nar)
self.assertEqual(seen["path"], "/_api/v1/upload-path")
self.assertEqual(seen["host"], "cache.hectic-lab.com")
self.assertIsNone(seen["te"])
self.assertEqual(seen["meta"]["store_path"], record["store_path"])
self.assertEqual(seen["nar"], data)
def test_payload_relative_url_and_redirect_strips_host(self):
try:
repack.requests_module()
except ModuleNotFoundError:
self.skipTest("requests not installed outside Nix test env")
data = b"nar"
seen = {}
class S3Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
seen["s3_path"] = self.path
seen["s3_host"] = self.headers.get("Host")
seen["s3_auth"] = self.headers.get("Authorization")
self.send_response(200); self.end_headers(); self.wfile.write(data)
def log_message(self, format, *args):
pass
with ThreadedHTTP(S3Handler) as s3:
class CacheHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
seen["cache_path"] = self.path
seen["cache_host"] = self.headers.get("Host")
seen["cache_auth"] = self.headers.get("Authorization")
self.send_response(302)
self.send_header("Location", s3.url + "/object")
self.end_headers()
def log_message(self, format, *args):
pass
with ThreadedHTTP(CacheHandler) as cache:
client = repack.AtticClient(cache.url, "hectic", "cache.hectic-lab.com", None)
client.verify_payload({"URL":"nar/x","Compression":"none"}, sha(data), len(data), cache.url + "/hectic/abcd.narinfo")
self.assertEqual(seen["cache_path"], "/hectic/nar/x")
self.assertEqual(seen["cache_host"], "cache.hectic-lab.com")
self.assertIsNone(seen["cache_auth"])
self.assertEqual(seen["s3_path"], "/object")
self.assertNotEqual(seen["s3_host"], "cache.hectic-lab.com")
self.assertIsNone(seen["s3_auth"])
def test_payload_retry_truncated_then_full_resets_hash(self):
data = b"complete NAR bytes"
client = repack.AtticClient("http://127.0.0.1:8082", "hectic", None, None)
sess = FakeSession(); client._local.session = sess
responses = [FakeResponse(200, content=data[:4]), FakeResponse(200, content=data)]
def get(_method, _url, _kwargs):
return responses.pop(0)
sess.routes[("GET", "http://127.0.0.1:8082/hectic/nar/x")] = get
with mock.patch("time.sleep") as sleep:
receipt = client.verify_payload({"URL": "nar/x", "Compression": "none"}, sha(data), len(data), "http://127.0.0.1:8082/hectic/abcd.narinfo", "/nix/store/abcd-name")
self.assertEqual(receipt, {"attempts": 2, "sha256": sha(data), "bytes": len(data)})
self.assertEqual(len(sess.calls), 2)
self.assertEqual(sleep.call_count, 1)
def test_payload_persistent_timeouts_fail_after_three(self):
client = repack.AtticClient("http://127.0.0.1:8082", "hectic", None, None)
sess = FakeSession(); client._local.session = sess
def timeout(_method, _url, _kwargs):
raise TimeoutError()
sess.routes[("GET", "http://127.0.0.1:8082/hectic/nar/x")] = timeout
with mock.patch("time.sleep") as sleep, self.assertRaises(TimeoutError):
client.verify_payload({"URL": "nar/x", "Compression": "none"}, sha(b"x"), 1, "http://127.0.0.1:8082/hectic/abcd.narinfo")
self.assertEqual(len(sess.calls), 3)
self.assertEqual(sleep.call_count, 2)
def test_payload_full_size_wrong_hash_fails_after_one(self):
client = repack.AtticClient("http://127.0.0.1:8082", "hectic", None, None)
sess = FakeSession(); client._local.session = sess
sess.routes[("GET", "http://127.0.0.1:8082/hectic/nar/x")] = FakeResponse(200, content=b"bad")
with self.assertRaises(repack.PayloadIntegrityError):
client.verify_payload({"URL": "nar/x", "Compression": "none"}, sha(b"nar"), 3, "http://127.0.0.1:8082/hectic/abcd.narinfo")
self.assertEqual(len(sess.calls), 1)
def test_payload_oversize_fails_after_one(self):
client = repack.AtticClient("http://127.0.0.1:8082", "hectic", None, None)
sess = FakeSession(); client._local.session = sess
sess.routes[("GET", "http://127.0.0.1:8082/hectic/nar/x")] = FakeResponse(200, content=b"toolong")
with self.assertRaises(repack.PayloadIntegrityError):
client.verify_payload({"URL": "nar/x", "Compression": "none"}, sha(b"too"), 3, "http://127.0.0.1:8082/hectic/abcd.narinfo")
self.assertEqual(len(sess.calls), 1)
def test_payload_http_403_no_retry_and_closes(self):
client = repack.AtticClient("http://127.0.0.1:8082", "hectic", None, None)
sess = FakeSession(); client._local.session = sess
resp = FakeResponse(403)
sess.routes[("GET", "http://127.0.0.1:8082/hectic/nar/x")] = resp
with self.assertRaises(repack.RepackError):
client.verify_payload({"URL": "nar/x", "Compression": "none"}, sha(b"x"), 1, "http://127.0.0.1:8082/hectic/abcd.narinfo")
self.assertEqual(len(sess.calls), 1)
self.assertEqual(resp.close_count, 1)
def test_auth_api_redirect_refused(self):
tp = repack.TokenProvider(None, None, "hectic")
tp._token = "tok"; tp._expires = repack.now() + 3600
client = repack.AtticClient("http://127.0.0.1:8082", "hectic", None, tp)
sess = FakeSession(); client._local.session = sess
sess.routes[("GET", "http://127.0.0.1:8082/_api/v1/cache-config/hectic")] = FakeResponse(302, headers={"Location":"http://evil/"})
with self.assertRaises(repack.RepackError):
client.get_cache_config()
def test_concatenated_zstd_correct(self):
try:
zstd = repack.zstd_module()
except ModuleNotFoundError:
self.skipTest("zstandard not installed outside Nix test env")
plain = b"a" * 100 + b"b" * 100
cctx = zstd.ZstdCompressor()
payload = cctx.compress(plain[:100]) + cctx.compress(plain[100:])
narinfo = {"URL": "nar/x.nar.zst", "Compression": "zstd"}
client = repack.AtticClient("http://127.0.0.1:8082", "hectic", None, None)
sess = FakeSession()
client._local.session = sess
sess.routes[("GET", "http://127.0.0.1:8082/hectic/nar/x.nar.zst")] = FakeResponse(200, raw=io.BytesIO(payload))
client.verify_payload(narinfo, sha(plain), len(plain), "http://127.0.0.1:8082/hectic/abcd.narinfo")
def test_perchunk_retry_cache(self):
try:
zstd = repack.zstd_module()
except ModuleNotFoundError:
self.skipTest("zstandard not installed outside Nix test env")
with tempfile.TemporaryDirectory() as td:
db = pathlib.Path(td) / "old.db"
plain = b"chunk"
comp = zstd.ZstdCompressor().compress(plain)
con = sqlite3.connect(db)
con.executescript("""
create table chunkref(nar_id integer,seq integer,chunk_id integer);
create table chunk(id integer primary key,state text,chunk_hash text,chunk_size integer,file_hash text,file_size integer,compression text,remote_file text);
""")
con.execute("insert into chunkref values(1,0,1)")
con.execute("insert into chunk values(1,'V',?,?,?,?,?,?)", (sha(plain), len(plain), sha(comp), len(comp), "zstd", json.dumps({"S3":{"region":"hel1","bucket":"cache-hectic-lab","key":"k"}})))
con.commit(); con.close()
state = repack.State(pathlib.Path(td) / "state")
asm = repack.OldS3Assembler(repack.InventoryDB(str(db), "hectic"), state, "https://example", "cache-hectic-lab", "hel1")
fake_client = mock.Mock()
fake_client.get_object.side_effect = [Exception("once"), {"Body": io.BytesIO(comp)}]
out = pathlib.Path(td) / "out.nar"
with mock.patch.object(asm, "client", return_value=fake_client):
asm.assemble({"nar_id": 1, "nar_hash": "sha256:" + sha(plain), "nar_size": len(plain)}, out)
self.assertEqual(out.read_bytes(), plain)
self.assertEqual(fake_client.get_object.call_count, 2)
fake_client.get_object.reset_mock()
self.assertEqual(asm._compressed_chunk(asm.db.chunk_rows(1)[0]), comp)
fake_client.get_object.assert_not_called()
def test_chunk_prefetch_is_bounded_and_preserves_order(self):
with tempfile.TemporaryDirectory() as td:
pieces = [f"chunk-{i}\n".encode() for i in range(12)]
rows = [{"seq": i, "compression": "none", "chunk_hash": sha(data), "chunk_size": len(data)}
for i, data in enumerate(pieces)]
db = mock.Mock()
db.chunk_rows.return_value = rows
asm = repack.OldS3Assembler(db, repack.State(pathlib.Path(td) / "state"), "https://example", "cache-hectic-lab", "hel1")
lock = threading.Lock()
active = 0
peak = 0
def fetch(row):
nonlocal active, peak
with lock:
active += 1
peak = max(peak, active)
time.sleep(0.04 if row["seq"] == 0 else 0.01)
with lock:
active -= 1
return pieces[row["seq"]]
whole = b"".join(pieces)
out = pathlib.Path(td) / "result.nar"
with mock.patch.object(asm, "_compressed_chunk", side_effect=fetch):
asm.assemble({"nar_id": 1, "nar_hash": "sha256:" + sha(whole), "nar_size": len(whole)}, out)
self.assertEqual(out.read_bytes(), whole)
self.assertGreater(peak, 1)
self.assertLessEqual(peak, 4)
def test_zstd_chunk_no_content_size_concat(self):
try:
zstd = repack.zstd_module()
except ModuleNotFoundError:
self.skipTest("zstandard not installed outside Nix test env")
cctx = zstd.ZstdCompressor(write_content_size=False)
payload = cctx.compress(b"aa") + cctx.compress(b"bb")
self.assertEqual(repack.decompress_chunk(payload, "zstd"), b"aabb")
def test_mismatch_new_key_fails(self):
with tempfile.TemporaryDirectory() as td:
db = pathlib.Path(td) / "old.db"
con = sqlite3.connect(db)
con.executescript("""
create table cache(id integer primary key,name text,keypair text,is_public integer,store_dir text,priority integer,upstream_cache_key_names text,retention_period text,deleted_at text);
insert into cache values(1,'hectic','priv',1,'/nix/store',30,'[]',null,null);
""")
con.close()
mig = repack.Migrator(self.args(td, old_db=str(db)))
mig.old_client = mock.Mock(); mig.old_client.get_cache_config.return_value = {"public_key":"old"}
mig.new_client = mock.Mock(); mig.new_client.get_cache_config.return_value = {"public_key":"new","is_public":True,"store_dir":"/nix/store","priority":30,"upstream_cache_key_names":[]}
with self.assertRaises(repack.RepackError):
mig.init_cache()
def test_init_requires_old_public_key(self):
with tempfile.TemporaryDirectory() as td:
db = pathlib.Path(td) / "old.db"
con = sqlite3.connect(db)
con.executescript("""
create table cache(id integer primary key,name text,keypair text,is_public integer,store_dir text,priority integer,upstream_cache_key_names text,retention_period text,deleted_at text);
insert into cache values(1,'hectic','priv',1,'/nix/store',30,'[]',null,null);
""")
con.close()
mig = repack.Migrator(self.args(td, old_db=str(db)))
mig.old_client = mock.Mock(); mig.old_client.get_cache_config.return_value = {}
mig.new_client = mock.Mock(); mig.new_client.get_cache_config.return_value = None
with self.assertRaises(repack.RepackError):
mig.init_cache()
def test_verify_readonly_no_put(self):
with tempfile.TemporaryDirectory() as td:
mig = repack.Migrator(self.args(td))
record = self.record(b"abc")
mig.selected_records = lambda: [record]
mig.new_client = mock.Mock()
mig.new_client.get_narinfo.return_value = {**repack.expected_narinfo(record), "URL": "nar/x", "Compression": "none"}
mig.new_client.verify_payload.return_value = {"attempts": 1, "sha256": sha(b"abc"), "bytes": 3}
mig.new_client.narinfo_url.return_value = "http://127.0.0.1:8082/hectic/abcd.narinfo"
mig.old_client = mock.Mock()
mig.old_client.get_narinfo.return_value = {**repack.expected_narinfo(record)}
mig.migrate(True)
mig.new_client.upload.assert_not_called()
mig.new_client.verify_payload.assert_called_once()
def test_payload_receipt_only_for_forced_successful_full_read(self):
with tempfile.TemporaryDirectory() as td:
mig = repack.Migrator(self.args(td))
record = self.record(b"abc")
mig.selected_records = lambda: [record]
narinfo = {**repack.expected_narinfo(record), "URL": "nar/x", "Compression": "none"}
old_info = {**repack.expected_narinfo(record)}
mig.old_client = mock.Mock(); mig.old_client.get_narinfo.return_value = old_info
mig.new_client = mock.Mock(); mig.new_client.get_narinfo.return_value = narinfo; mig.new_client.narinfo_url.return_value = "http://127.0.0.1/hectic/abcd.narinfo"
mig.new_client.verify_payload.return_value = {"attempts": 2, "sha256": sha(b"abc"), "bytes": 3}
self.assertEqual(mig.migrate(True), 0)
cp = mig.state.get_checkpoint(record)
self.assertEqual(cp["payload_verify_attempts"], 2)
self.assertEqual(cp["payload_sha256"], sha(b"abc"))
self.assertEqual(cp["payload_bytes"], 3)
self.assertTrue(cp["payload_verified_at"].endswith("Z"))
first_verified_at = cp["payload_verified_at"]
mig.new_client.verify_payload.reset_mock()
self.assertEqual(mig.migrate(False), 0)
cp = mig.state.get_checkpoint(record)
self.assertEqual(cp["payload_verified_at"], first_verified_at)
mig.new_client.verify_payload.assert_not_called()
mig.new_client.get_narinfo.return_value = narinfo
mig.new_client.verify_payload.side_effect = repack.PayloadIntegrityError("new NAR payload hash/size mismatch")
self.assertEqual(mig.migrate(True), 1)
cp = mig.state.get_checkpoint(record)
self.assertEqual(cp["status"], "failed")
self.assertNotIn("payload_verified_at", cp)
self.assertNotIn("payload_sha256", cp)
def test_key_redaction(self):
secret = "eyJhbGciOiPRIVATEKEYX-Amz-Signature=abc"
msg = repack.sanitized_error(RuntimeError("https://x/y?" + secret))
self.assertEqual(msg, "RuntimeError")
self.assertNotIn(secret, msg)
def test_old_new_narinfo_sig_compare_allows_db_sigs_empty(self):
with tempfile.TemporaryDirectory() as td:
mig = repack.Migrator(self.args(td))
record = self.record(b"abc")
record["sigs"] = []
old_info = {**repack.expected_narinfo(record), "Sig": ["hectic:sig"]}
new_info = dict(old_info)
mig.old_client = mock.Mock(); mig.old_client.get_narinfo.return_value = old_info
mig.new_client = mock.Mock(); mig.new_client.get_narinfo.return_value = new_info; mig.new_client.narinfo_url.return_value = "http://127.0.0.1/hectic/abcd.narinfo"
mig.new_client.verify_payload.return_value = None
self.assertTrue(mig.verify_record(record, False))
def test_migrate_record_missing_narinfo_raises(self):
with tempfile.TemporaryDirectory() as td:
mig = repack.Migrator(self.args(td))
record = self.record(b"abc")
raw = mig.state.raw_path(repack.nar_hash_hex(record["nar_hash"]))
raw.write_bytes(b"abc")
mig.new_client = mock.Mock(); mig.new_client.get_narinfo.return_value = None
with self.assertRaises(repack.RepackError):
mig.migrate_record(record)
def test_migrate_returns_failed_count(self):
with tempfile.TemporaryDirectory() as td:
mig = repack.Migrator(self.args(td))
mig.selected_records = lambda: [self.record(b"abc")]
mig.migrate_record = mock.Mock(side_effect=repack.RepackError("new narinfo missing"))
self.assertEqual(mig.migrate(False), 1)
def test_readonly_old_db_rejects_rw_and_missing(self):
with self.assertRaises(repack.RepackError):
repack.InventoryDB("file:/tmp/x.db?mode=rwc", "hectic")
with self.assertRaises(repack.RepackError):
repack.InventoryDB("/tmp/definitely-missing-attic.db", "hectic")
def test_verify_hash_size_fail_closed_unknown_hash(self):
with self.assertRaises(repack.RepackError):
repack.verify_hash_size(b"x", "sha1:abc", 1, "chunk")
def args(self, td, old_db=":memory:"):
return argparse.Namespace(old_db=old_db, state_dir=str(pathlib.Path(td) / "state"), old_url="http://127.0.0.1:8081", new_url="http://127.0.0.1:8082", host="cache.hectic-lab.com", cache="hectic", atticadm=None, server_config=None, nix="nix", old_storage_endpoint="https://hel1.your-objectstorage.com", old_bucket="cache-hectic-lab", old_region="hel1", workers=2, limit=None, paths_file=None)
def record(self, data):
h = sha(data)
return {"cache":"hectic","nar_id":1,"store_path_hash":"abcd","store_path":"/nix/store/abcd-name","references":["/nix/store/ref-ref"],"system":"x86_64-linux","deriver":None,"sigs":["cache:sig"],"ca":None,"nar_hash":"sha256:" + h,"nar_size":len(data)}
if __name__ == "__main__":
unittest.main()
+26 -14
View File
@@ -24,30 +24,43 @@ Preferred registry:
gitea.hectic-lab.com/hectic-lab/gitea-runner-nix-image
```
Publish the archive without adding secrets to the image layers. Controller-owned
zero-idle runners select this image through `nixImageId` / `GCR_NIX_IMAGE_ID`;
they do not use a Gitea label-to-container-image mapping:
Publish the archive without adding secrets to the image layers, then use the
registry-reported digest as the only final `nix` label image reference:
```text
nixImageId = "<Hetzner-image-id>";
nix:docker://gitea.hectic-lab.com/hectic-lab/gitea-runner-nix-image@sha256:<registry-digest>
```
The `2026-06-07` tag may be pushed as a human-readable companion tag. The
legacy Kubernetes rollback pool is currently disabled and has no labels.
If it is restored, its Nix-capable image must be configured separately and
digest-pinned before enabling a `nix` label.
The `2026-06-07` tag may be pushed as a human-readable companion tag, but the
runner label mapping must use the `@sha256:` reference above. Keep
`ubuntu-latest` on the `gitea/runner` default image unless a later runner
configuration task explicitly changes it. Only the `nix` label should select
this custom image.
Do not use a tag-only image for a restored Kubernetes rollback pool.
If the Gitea container registry is unavailable, select a private registry that
is reachable from the runner Kubernetes cluster and requires authentication that
can be provided through Kubernetes image-pull secrets. Record the selected
registry and replace the host in the same digest-pinned form:
```text
nix:docker://<private-registry>/<namespace>/gitea-runner-nix-image@sha256:<registry-digest>
```
Do not fall back to `latest` or a tag-only mapping.
## Task 7 publication status
Local build evidence is recorded in
`.sisyphus/evidence/task-7-image-digest.txt`. Kubernetes pull smoke is recorded in
`.sisyphus/evidence/task-7-image-digest.txt`. In this environment, Docker could
load and tag the image, but pushing to the preferred registry failed with
`unauthorized: reqPackageAccess`, so no registry digest was available to pin as a
concrete final mapping. Kubernetes pull smoke is recorded in
`.sisyphus/evidence/task-7-image-pull.txt` and is blocked here because `kubectl`
is not installed or not on `PATH`.
After importing the archive as a Hetzner image, record its image ID in the
controller host configuration before dispatching Nix jobs.
Once registry credentials are available, rerun the push, capture the
registry-reported digest, and replace `<registry-digest>` in the mapping above
before Task 6/9 consumes the label configuration.
## Image contents
@@ -58,8 +71,7 @@ top-level `flake.nix`:
```text
experimental-features = nix-command flakes
substituters = https://cache.nixos.org https://cache.hectic-lab.com/hectic
http2 = false
trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= hectic:KMQsKow4SoA9K2vOJlOljmx7/Zpf91Yy+5qEtxDDCzA=
trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gW4x6l1xP+GxgH0r7u+f6p1VFlr0= hectic:KMQsKow4SoA9K2vOJlOljmx7/Zpf91Yy+5qEtxDDCzA=
sandbox = false
```
+4 -2
View File
@@ -19,8 +19,10 @@ data:
insecure: false
fetch_timeout: 5s
fetch_interval: 2s
# Persistent pool is disabled; controller owns all runner labels.
labels: []
labels:
- ubuntu-latest
# The nix label is intentionally disabled until the runner image has a
# concrete registry-reported digest; see ../runbook.md before deploy.
cache:
enabled: true
+1 -2
View File
@@ -8,8 +8,7 @@ metadata:
app.kubernetes.io/part-of: gitea-actions
spec:
serviceName: gitea-runner
# Rollback-only pool. Keep manifest present, default replicas 0.
replicas: 0
replicas: 5
podManagementPolicy: Parallel
selector:
matchLabels:
+6 -12
View File
@@ -63,25 +63,19 @@ The default cluster is deliberately fixed-size:
- cluster name: `gitea-runners`
- Hetzner location: `fsn1`
- private network region: `eu-central`
- control plane: one `cpx22` node in pool `control-plane`
- workers: one `cpx22` node in pool `runner-workers`
- control plane: one `cpx21` node in pool `control-plane`
- workers: three `cpx31` nodes in pool `runner-workers`
- storage: Hetzner CSI enabled with expected StorageClass `hcloud-volumes`
- Longhorn: disabled
- autoscaling/KEDA: not enabled in this stack
The default baseline uses one `cpx22` worker to keep the idle bill low while
still supporting trusted internal jobs. To scale toward higher concurrency
later, keep autoscaling disabled and either raise `worker_count` or increase
`worker_server_type`, then run a fresh `tofu plan` and the Task 11 Kubernetes
pressure checks before applying.
The three default workers are sized for the initial five trusted privileged DinD
jobs. To scale toward ten jobs later, keep autoscaling disabled and either raise
`worker_count` to `5` or increase `worker_server_type`, then run a fresh
`tofu plan` and the Task 11 Kubernetes pressure checks before applying.
Required inputs must come from environment or secret injection, for example
`TF_VAR_hcloud_token`, `TF_VAR_ssh_public_key`, and `TF_VAR_ssh_private_key`.
Set `TF_VAR_firewall_ssh_source` and `TF_VAR_firewall_kube_api_source` explicitly
to trusted CIDR ranges before planning; the cluster must not expose SSH or port
6443 to `0.0.0.0/0`.
If the public key is already registered in Hetzner, set
`TF_VAR_hcloud_ssh_key_id` to reuse it instead of creating a duplicate key.
Do not commit `.tfvars` files. kube-hetzner v2.19.3 writes the generated
kubeconfig to `./<cluster_name>_kubeconfig.yaml` when `create_kubeconfig` is
enabled; this path is ignored as operational secret material.
+5 -16
View File
@@ -1,21 +1,10 @@
terraform {
backend "s3" {
bucket = "gitea-runner-hectic-lab"
key = "gitea-runners/kube-hetzner/terraform.tfstate"
region = "hel1"
endpoints = {
s3 = "https://hel1.your-objectstorage.com"
}
skip_credentials_validation = true
skip_metadata_api_check = true
skip_region_validation = true
skip_requesting_account_id = true
use_path_style = true
encrypt = false
skip_s3_checksum = true
use_lockfile = true
bucket = "gitea-runner-hectic-lab"
key = "gitea-runners/kube-hetzner/terraform.tfstate"
region = "fsn1"
encrypt = true
use_lockfile = true
}
}
@@ -1,39 +0,0 @@
"apiVersion": "kustomize.config.k8s.io/v1beta1"
"kind": "Kustomization"
"patches":
- "patch": |
apiVersion: apps/v1
kind: Deployment
metadata:
name: system-upgrade-controller
namespace: system-upgrade
spec:
template:
spec:
containers:
- name: system-upgrade-controller
volumeMounts:
- name: ca-certificates
mountPath: /var/lib/ca-certificates
volumes:
- name: ca-certificates
hostPath:
path: /var/lib/ca-certificates
type: Directory
"target":
"group": "apps"
"kind": "Deployment"
"name": "system-upgrade-controller"
"namespace": "system-upgrade"
"version": "v1"
- "path": "kured.yaml"
- "path": "ccm.yaml"
"resources":
- "https://github.com/kubereboot/kured/releases/download/1.23.0/kured-1.23.0-combined.yaml"
- "https://github.com/rancher/system-upgrade-controller/releases/download/v0.18.0/system-upgrade-controller.yaml"
- "https://github.com/rancher/system-upgrade-controller/releases/download/v0.18.0/crd.yaml"
- "https://github.com/hetznercloud/hcloud-cloud-controller-manager/releases/download/v1.35.0/ccm-networks.yaml"
- "hcloud-csi.yaml"
- "traefik_ingress.yaml"
- "flannel-rbac.yaml"
- "cert_manager.yaml"
-3
View File
@@ -47,9 +47,6 @@ module "kube_hetzner" {
load_balancer_location = var.hetzner_location
control_plane_nodepools = local.control_plane_nodepools
agent_nodepools = local.agent_nodepools
firewall_ssh_source = var.firewall_ssh_source
firewall_kube_api_source = var.firewall_kube_api_source
hcloud_ssh_key_id = var.hcloud_ssh_key_id
# Hetzner CSI is the required StorageClass provider for runner PVCs.
disable_hetzner_csi = false
+6 -22
View File
@@ -39,21 +39,21 @@ variable "network_region" {
}
variable "control_plane_server_type" {
description = "Default control-plane server type. cpx22 is small but leaves headroom for kube-system workloads."
description = "Default control-plane server type. cpx21 is small but leaves headroom for kube-system workloads."
type = string
default = "cpx22"
default = "cpx21"
}
variable "worker_server_type" {
description = "Default worker server type for the budget trusted DinD cluster. One cpx22 worker keeps the cluster baseline cheap; scale out later if rollback capacity requires it."
description = "Default worker server type for the initial trusted DinD runner pool. Three cpx31 workers provide enough headroom for five privileged jobs before Task 11 scaling validation."
type = string
default = "cpx22"
default = "cpx31"
}
variable "worker_count" {
description = "Fixed worker count. Default is a single cheap worker for low-cost baseline operation; increase later if concurrency requires it."
description = "Fixed worker count. Increase to 5 or choose a larger worker_server_type later to target 10 concurrent DinD jobs; do not enable autoscaling in this stack."
type = number
default = 1
default = 3
validation {
condition = var.worker_count >= 1
@@ -72,19 +72,3 @@ variable "base_domain" {
type = string
default = ""
}
variable "firewall_ssh_source" {
description = "CIDR ranges allowed to SSH to cluster nodes. Set explicitly; never expose SSH to the public internet."
type = list(string)
}
variable "firewall_kube_api_source" {
description = "CIDR ranges allowed to reach the Kubernetes API. Set explicitly; never expose port 6443 to the public internet."
type = list(string)
}
variable "hcloud_ssh_key_id" {
description = "Existing Hetzner SSH key ID. Set this when the public key is already registered in the project."
type = string
default = null
}
+35 -238
View File
@@ -2,13 +2,15 @@
## Scope
This directory is the repo-owned boundary for the Gitea Actions runner pool.
The controller is the active on-demand path; Kubernetes manifests and the
Nix-capable image are retained for manual rollback and maintenance.
This directory is the repo-owned boundary for the first Gitea Actions runner
pool. Task 1 only establishes the scaffold and immutable decision contract;
downstream tasks will add OpenTofu backend/provider files, Kubernetes manifests,
and a Nix-capable runner image under the existing subdirectories.
The target service is `https://gitea.hectic-lab.com` for the Gitea organization
`hectic-lab`. The pool is trusted-only. "Ephemeral" means each controller VM
and workflow job is disposable; the Kubernetes StatefulSet is rollback-only.
`hectic-lab`. The first pool is fixed-size and trusted-only. "Ephemeral" means
workflow job containers are ephemeral, while each runner pod keeps its runner
identity in per-pod `/data/.runner` storage backed by a StatefulSet PVC.
## Immutable decisions
@@ -25,21 +27,21 @@ and workflow job is disposable; the Kubernetes StatefulSet is rollback-only.
`/data`, including `/data/.runner`.
- Container builds run through privileged rootful DinD inside trusted runner
pods; host Docker socket mounting is not an implementation path.
- `ubuntu-latest` and `nix` are controller-managed on-demand aliases for
`gross-x86` and `gross-nix-x86`; the Kubernetes pool has no active labels.
- The active runner label is `ubuntu-latest`. The `nix` label is not live until
the Nix-capable image has been pushed and a concrete registry-reported digest
is added to the runner ConfigMap.
- First scope is trusted internal workflows only, with no untrusted fork or PR
workflow support.
- On-demand allocation is handled by the repo-owned controller; Kubernetes is
not an active autoscaling path.
- First scope has no autoscaling, no KEDA, and no dynamic runner controller.
## Lifecycle boundaries
- `infra/gitea-runners/opentofu/`: OpenTofu stack for the S3 backend
- `infra/gitea-runners/opentofu/`: downstream OpenTofu stack for the S3 backend
contract, Hetzner provider configuration, and kube-hetzner module wiring.
- `infra/gitea-runners/k8s/`: rollback-only namespace, ConfigMap, Secret mount,
- `infra/gitea-runners/k8s/`: downstream namespace, ConfigMap, Secret mount,
StatefulSet, PVC, DinD sidecar, cleanup, and operational manifest work.
- `infra/gitea-runners/image/`: notes and handoff for the optional Kubernetes
rollback image; active on-demand Nix image is selected by Hetzner image ID.
- `infra/gitea-runners/image/`: downstream notes or sources for the runner image
handoff; package or flake output changes are outside Task 1.
- `infra/gitea-runners/runbook.md`: this contract plus later operational
commands, rollback notes, and acceptance evidence references.
@@ -50,8 +52,8 @@ and workflow job is disposable; the Kubernetes StatefulSet is rollback-only.
instructions, or GitHub Actions ARC assumptions.
- Untrusted fork/PR workflows are out of first scope; privileged DinD is only
acceptable for trusted internal jobs.
- The persistent StatefulSet is rollback-only and defaults to zero replicas;
normal jobs use controller-managed on-demand VMs.
- Autoscaling/KEDA is out of first scope; start with a fixed-size StatefulSet
runner pool.
- No actual secrets are committed: no kubeconfig, runner token, Hetzner token,
S3 credentials, decrypted SOPS files, or SOPS age keys.
- OpenTofu must not manage plaintext Kubernetes Secrets containing the Gitea
@@ -246,7 +248,8 @@ These commands are executable only when the external inputs are available:
- S3 backend credentials and endpoint access
- a matching SOPS age identity for `sus/gitea-runners.yaml`
- `kubectl` access to the target cluster
- a valid `GCR_NIX_IMAGE_ID` for controller-managed Nix jobs
- a concrete digest for the pushed Nix-capable runner image, if enabling the
`nix` label
If any input is missing, stop before `tofu apply`. Do not guess values or reuse
stale kubeconfig files.
@@ -257,12 +260,15 @@ Before production Kubernetes apply or rollout, satisfy both manifest gates:
Kustomize overlay intentionally does not include a placeholder Secret, but
the StatefulSet still mounts `secretName: gitea-runner-token` as
`/runner-secrets/token` for `GITEA_RUNNER_REGISTRATION_TOKEN_FILE`.
2. Keep the persistent-pool ConfigMap labels empty. Runner labels belong to the
controller; Nix image readiness is governed by `GCR_NIX_IMAGE_ID`.
2. Keep the active ConfigMap on `ubuntu-latest` only unless the Nix-capable
image has been pushed successfully. Enable the `nix` label only by adding a
digest-pinned `docker://` mapping with the exact registry-reported sha256
digest from that push.
Use the same SOPS materialization pattern as token rotation before applying the
Kubernetes overlay. Applying the namespace alone is allowed so the Secret has a
target namespace; the full overlay remains gated on the Secret.
target namespace; the full overlay remains gated on the Secret and digest
decisions:
```sh
kubectl apply -f infra/gitea-runners/k8s/namespace.yaml
@@ -277,7 +283,8 @@ kubectl -n gitea-runners create secret generic gitea-runner-token \
```
Do not run `kubectl apply -k infra/gitea-runners/k8s` until the Secret command
above succeeds. The persistent pool ConfigMap must retain empty labels.
above succeeds. Do not claim or enable the `nix` runner label until the image
publication step has produced the concrete digest.
```sh
tofu -chdir=infra/gitea-runners/opentofu init
@@ -302,14 +309,14 @@ Expected status after deploy:
- `kubectl config current-context` names the runner cluster context.
- `kubectl get nodes -o wide` shows all expected Hetzner nodes Ready.
- `kubectl get sc` shows the Hetzner CSI storage class used by runner PVCs.
- `kubectl -n gitea-runners get statefulset gitea-runner` shows 0 desired and 0 ready replicas.
- `kubectl -n gitea-runners get pvc` shows no active runner PVCs; retained PVCs are rollback-only.
- The controller host reports healthy and owns runner registrations; no persistent runner claims `ubuntu-latest` or `nix`.
- `kubectl -n gitea-runners get statefulset gitea-runner` shows 5 desired and 5 ready replicas.
- `kubectl -n gitea-runners get pvc` shows 5 Bound PVCs.
- `kubectl -n gitea-runners logs statefulset/gitea-runner -c runner --tail=200` shows the runner daemon started and no token value.
## Legacy rollback pool scaling (manual only)
## Scale 5 to 10 to 5
Persistent-pool scaling is not part of normal operation. Use only after restoring
its labels and disabling the zero-idle controller as described in `Rollback`.
Scaling is a temporary capacity exercise, not the steady-state setting. Scale up,
wait for readiness, run the concurrent smoke jobs, then scale back down to 5.
```sh
kubectl -n gitea-runners scale statefulset/gitea-runner --replicas=10
@@ -317,7 +324,7 @@ kubectl -n gitea-runners rollout status statefulset/gitea-runner --timeout=10m
kubectl -n gitea-runners get pods -l app.kubernetes.io/name=gitea-runner -o wide
kubectl -n gitea-runners get pvc -l app.kubernetes.io/name=gitea-runner -o wide
# Run only workflows supported by restored persistent labels.
# Run the concurrent smoke workflows now.
kubectl -n gitea-runners scale statefulset/gitea-runner --replicas=5
kubectl -n gitea-runners rollout status statefulset/gitea-runner --timeout=10m
@@ -398,7 +405,7 @@ Do not run the delete command for a runner that still has an active
`gitea-runner-*` pod or retained `data-gitea-runner-*` PVC unless that PVC is
being intentionally reset for re-registration.
## Legacy Kubernetes application rollback
## Application rollback
Rollback the app layer only. Do not use this section to destroy the cluster.
@@ -494,213 +501,3 @@ Do not release unless the following evidence files exist and are readable:
If any evidence file is missing, stop and collect it before treating the runbook
as complete.
## Ephemeral VM runner cutover
This section governs replacing the legacy persistent K8s runner pool with the
ephemeral-VM controller (`package/gitea-runner-controller`) on this host.
The K8s pool above remains rollback-only until cutover is explicitly accepted.
### Operator gates (all three required before enable)
1. Secrets — add to `sus/gitea-runners.yaml` under
`gitea/hectic-lab/controller/*`:
```sh
sops sus/gitea-runners.yaml
# add keys:
# gitea:
# hectic-lab:
# controller:
# hcloud-token: <Hetzner API token, VM create/destroy scope>
# webhook-secret: <random 32+ bytes; also set as Gitea webhook secret>
# admin-token: <Gitea token with admin:runner scope for stale cleanup>
```
The org registration token key
`gitea/hectic-lab/org-runner-registration-token` already exists and is reused.
2. Base image — build the MicroOS snapshot and record its id:
```sh
nix develop .#gitea-runners -c gitea-runners-build-microos-snapshots x86
hcloud image list --selector '' -o json | jq '.[] | select(.type=="snapshot")'
```
3. DNS — A record `runners.hectic-lab.com -> 128.140.75.58` (ACME needs it).
### Enable
```sh
# nixos/system/hectic-lab/hectic-lab.nix: resolve the FIXME block
hectic.services.gitea-runner-controller = {
enable = true;
imageId = "<snapshot-id-from-gate-2>";
};
nixos-rebuild --target root@128.140.75.58 switch
systemctl status gitea-runner-controller.service gitea-runner-webhook.service
```
### Register the Gitea webhook
Org-level (preferred) or per-repo, on `https://gitea.hectic-lab.com`:
- URL: `https://runners.hectic-lab.com/`
- Method: `POST`, content type: JSON
- Secret: value of `gitea/hectic-lab/controller/webhook-secret`
- Trigger events: `Workflow jobs` only (`workflow_job`)
### Long CUDA/Magma deployment time budgets
The `deploy-neuro` workflow uses these nested limits:
| Layer | Limit |
| --- | --- |
| Wrapped build/deploy command | 6 hours (`WITH_ATTIC_BUILD_TIMEOUT=21600`) |
| Final cache drain | 1 hour (`WITH_ATTIC_DRAIN_TIMEOUT=3600`) |
| Workflow job | 435 minutes, including 15 minutes of setup/cleanup margin |
| `gross-nix-x86-perf` runner | 480 minutes |
| `gross-nix-x86-highmem` runner | 480 minutes |
| Gitea `actions.ENDLESS_TASK_TIMEOUT` | 8 hours |
| VM hard lifetime from allocation | 480 minutes; no destruction grace |
`ubuntu-latest` keeps a 180-minute limit; `nix` uses a 480-minute limit for
long-running Nix deployments. Deploy the controller and Gitea watchdog settings
before dispatching the longer workflow. Already
allocated VMs retain the TTL and runner configuration assigned when they were
created; updating the controller does not extend a running job.
`gross-nix-x86-highmem` is an explicit costly high-memory escape hatch backed
only by Hetzner CCX53 in `nbg1`, `fsn1`, or `hel1`; it may fall back by region
only, never to a lower-RAM server type. Current Hetzner public pricing for
Germany/Finland CCX53 is 0.8550 EUR/hour excluding IPv4, so one 480-minute
allocation reserves 6.84 EUR against the controller budget before VM creation.
These are maximum lifetimes. Unbootstrapped or profile-invalid VMs trigger
immediate teardown; failed jobs retain pre-destroy diagnostics. A healthy,
bootstrapped terminal VM may stay running until the next hourly boundary
measured from original VM creation, capped by its original hard TTL.
Each controller-managed registration is ephemeral: Gitea permits it to accept
exactly one task and revokes reuse credentials after assignment. Retention first
enters a durable retirement state. The controller disables the exact repository
runner registration, waits if a pre-upgrade non-ephemeral registration is still
assigned to an in-progress job, then deletes it and confirms its absence before
clearing repository, label, and runner ownership into generic idle. A
queued job from any allowed repository can atomically claim generic idle only
when persisted server type, location, architecture, and image match one of the
job label's candidates. The VM then remains unschedulable while Hetzner rebuilds
its root disk from that clean image. Controller verifies rebuild action and
server identity, current image/profile, and current IP before fetching a fresh
destination-repository token and bootstrapping a new runner name. Old runner
registration and filesystem are never reused.
Runner allocation and Gitea task assignment are separate identities. Bootstrap
installs and registers with the daemon stopped, resolves the exact repository
runner registration, persists its numeric `runner_id`, and only then starts the
daemon over the pinned SSH channel. Webhooks and unfiltered paginated polling
bind lifecycle by exact repository plus `runner_id`; terminal `runner_name` is
not authoritative because Gitea may already have deleted the ephemeral runner
row. If a runner consumes a different queued job, controller first persists a
`transfer_pending` intent, moves VM lifecycle to the actual job, and restores
the allocation-origin job as VM-less deferred work. Reconciliation replays this
ordered transfer before TTL, orphan, capacity, or deferred sweeps, and duplicate
crash-intermediate records count as one VM.
Pre-upgrade records without `runner_id` use exact live runner-name lookup once.
If registration is authoritatively absent and complete repository job polling
proves no job is active, VM moves to durable synthetic cleanup ownership while
origin is restored to deferred. Any malformed, ambiguous, repository-mismatched,
or unavailable identity data leaves state and VM untouched for later retry.
For every creation and reuse rebuild, the controller generates a unique SSH
host key, injects it through authenticated Hetzner `user_data`, and pins that
exact public key before sending a registration token. Shared image host keys
and trust-on-first-use are not used. Runner images must process cloud-init's
native `ssh_keys` with `ssh_deletekeys: true` and `ssh_genkeytypes: [ed25519]`
during create and rebuild. Before release, verify cloud-init completion and
agreement between generated, pinned, and live host-key fingerprints on the
target image. If host-key injection fails, bootstrap remains fail-closed.
Reuse preserves original Hetzner VM creation time, hard TTL, and budget charge;
it creates no server and makes no second reservation. Provider or registration
uncertainty remains in a non-schedulable durable state, and unrecoverable rebuild
uncertainty destroys the VM. Idle VMs are still billed: controller deletes them
at slot expiry and never relies on stopping a server to avoid charges. Allowed
repositories remain trusted-only and must not run untrusted fork or pull-request
code.
Active and idle VMs are deleted at profile hard TTL without grace. Idle reuse is
allowed only when at least one configured reconcile interval remains before both
slot expiry and hard TTL. Controller budget reservation still uses full label TTL
on initial creation, so a long-running label reserves more of existing monthly
budget. Do not raise that budget or disable timeout safeguards just to bypass a
refused allocation.
After changing any timeout, verify the complete chain rather than only
`timeout-minutes`; a shorter wrapper, runner, server watchdog, or VM TTL wins.
### Pre-flight verification (before first real job)
```sh
curl -fsS https://runners.hectic-lab.com/ -o /dev/null -w '%{http_code}\n' # any 4xx from handler = reachable
journalctl -u gitea-runner-webhook -n 20 --no-pager
hcloud server list -o json | jq '[.[] | select(.labels["gitea-runner-controller"]=="managed")] | length' # expect 0
```
Zero managed VMs is expected after retained billing slots expire. Immediately
after successful work, one managed VM per retained profile may remain until its
recorded hourly boundary.
### End-to-end acceptance (Task 9)
Trigger `.gitea/workflows/runner-nix-smoke.yaml` via workflow_dispatch, then:
```sh
watch_labels() { hcloud server list -o json | jq '[.[] | select(.labels["gitea-runner-controller"]=="managed") | {id,name,labels}]'; }
watch_labels # exactly one VM while queued/running
journalctl -f -u gitea-runner-controller # vm-created / vm-destroyed events
watch_labels # VM may remain until next hourly boundary
curl -fsS -H "Authorization: token $ADMIN" \
https://gitea.hectic-lab.com/api/v1/orgs/hectic-lab/actions/runners \
| jq '[.entries[] | select(.name | startswith("gcr-"))] | length' # may remain during retained slot
```
Failure paths to verify identically: duplicate delivery (send same webhook twice
via Gitea UI "Test delivery"), cancelled job, unknown-label job.
### Rollback
K8s rollback pool now defaults to deleted state:
- `infra/gitea-runners/k8s/statefulset.yaml` keeps `replicas: 0`
- old kube-hetzner nodes may be deleted to preserve zero idle cost
- PVCs and IaC remain for manual rollback only
Re-enable sequence:
```sh
# 1. edit nixos/system/hectic-lab/hectic-lab.nix and set
# services.gitea-runner-controller.enable = false, then rebuild:
nixos-rebuild --target root@128.140.75.58 switch
# 2. reprovision old kube-hetzner nodes when they were deleted:
tofu -chdir=infra/gitea-runners/opentofu apply
# 3. while controller is disabled, destroy every surviving managed VM and
# verify no gcr-* runner registration remains online:
hcloud server list -o json \
| jq -r '.[] | select(.labels["gitea-runner-controller"]=="managed") | .id' \
| xargs -r -n1 hcloud server delete
# 4. restore kubeconfig / cluster access, restore `ubuntu-latest` in the
# ConfigMap labels, then re-enable K8s runner pool. The legacy image does not
# provide `nix`; do not dispatch Nix workflows until a Nix-capable K8s image
# and label mapping are restored:
kubectl -n gitea-runners edit configmap/gitea-runner-config
kubectl -n gitea-runners scale statefulset/gitea-runner --replicas=5
kubectl -n gitea-runners rollout status statefulset/gitea-runner --timeout=10m
```
Any managed VM or `gcr-*` registration found after step 3 must be removed before
restoring persistent labels; otherwise both pools can claim the same job.
+2 -31
View File
@@ -26,41 +26,12 @@
"aarch64-darwin"
];
cudaUnfreeNames = [
"cuda_nvcc"
"cuda_cudart"
"cuda_cuobjdump"
"cuda_cupti"
"cuda_nvdisasm"
"cuda_cccl"
"cuda_nvml_dev"
"cuda_nvrtc"
"cuda_nvtx"
"cuda_profiler_api"
"libcusparse_lt"
"libcublas"
"libcufft"
"libcufile"
"libcurand"
"libcusolver"
"libnvjitlink"
"libcusparse"
"cudnn"
];
cudaUnfreePredicate = pkg:
builtins.elem (nixpkgs.lib.getName pkg) cudaUnfreeNames;
forSystemsWithPkgs = supportedSystems: pkgOverlays: f:
builtins.foldl' (
acc: system: let
pkgs = import nixpkgs {
inherit system;
overlays = pkgOverlays;
config.allowUnfreePredicate = pkg:
cudaUnfreePredicate pkg
|| builtins.elem (nixpkgs.lib.getName pkg) [ "vim-plugin-AnsiEsc" ];
};
systemOutputs = f {
system = system;
@@ -87,7 +58,7 @@
else {};
in {
# -- For all systems --
inherit dotEnv minorEnvironment parseEnv forAllSystemsWithPkgs forSystemsWithPkgs commonSystems AllSystems cudaUnfreeNames cudaUnfreePredicate;
inherit dotEnv minorEnvironment parseEnv forAllSystemsWithPkgs forSystemsWithPkgs commonSystems AllSystems;
forSystems = systems: nixpkgs.lib.genAttrs systems;
forAllSystems = nixpkgs.lib.genAttrs AllSystems;
@@ -128,7 +99,7 @@ in {
else throw (envErrorMessage varName);
# -- Cargo.toml --
cargoToml = manifest: (builtins.fromTOML (builtins.readFile manifest));
cargoToml = src: (builtins.fromTOML (builtins.readFile "${src}/Cargo.toml"));
# Consolidated SQL bundles for the `hectic` schema. Single source of truth
# for everything that creates objects in the `hectic` namespace, used by
-77
View File
@@ -1,77 +0,0 @@
{pkgs}:
pkgs.writeShellScript "s3-retention" ''
set -eu
if [ "$#" -ne 7 ]; then
echo "Usage: $0 bucket endpoint region prefix archivePrefix retentionDays workDir" >&2
exit 1
fi
bucket=$1
endpoint=$2
region=$3
prefix=$4
archive_prefix=$5
retention_days=$6
work_dir=$7
remote_prefix="''${prefix:+$prefix/}"
temp_dir="$(${pkgs.coreutils}/bin/mktemp -d "$work_dir/.s3-retention.XXXXXXXXXX")"
trap '${pkgs.coreutils}/bin/rm -rf "$temp_dir"' EXIT
remote_list="$temp_dir/objects.json"
remote_delete_dir="$temp_dir/delete"
${pkgs.awscli2}/bin/aws s3api list-objects-v2 \
--bucket "$bucket" \
--prefix "$remote_prefix" \
--endpoint-url "$endpoint" \
--region "$region" \
--output json > "$remote_list"
${pkgs.python3}/bin/python3 - "$remote_list" "$remote_delete_dir" \
"$(( $(${pkgs.coreutils}/bin/date +%s) - retention_days * 86400 ))" \
"$remote_prefix$archive_prefix" <<'PY'
import datetime
import json
import os
import re
import sys
objects_path, delete_dir, cutoff, key_prefix = sys.argv[1:]
cutoff = int(cutoff)
archive_pattern = re.compile(
re.escape(key_prefix) + r"\d{8}T\d{6}Z\.tar\.zst\Z"
)
with open(objects_path, encoding="utf-8") as stream:
objects = json.load(stream).get("Contents", [])
old_keys = []
for item in objects:
key = item.get("Key", "")
if not archive_pattern.fullmatch(key):
continue
modified = datetime.datetime.fromisoformat(
item["LastModified"].replace("Z", "+00:00")
)
if int(modified.timestamp()) < cutoff:
old_keys.append(key)
os.makedirs(delete_dir, exist_ok=True)
# The S3 endpoint disconnects when deleting multiple existing archives at once.
for number, key in enumerate(old_keys):
manifest_path = os.path.join(delete_dir, f"batch-{number:04d}.json")
with open(manifest_path, "w", encoding="utf-8") as stream:
json.dump({"Objects": [{"Key": key}], "Quiet": True}, stream)
PY
for remote_manifest in "$remote_delete_dir"/*.json; do
[ -f "$remote_manifest" ] || continue
${pkgs.awscli2}/bin/aws s3api delete-objects \
--bucket "$bucket" \
--delete "file://$remote_manifest" \
--endpoint-url "$endpoint" \
--region "$region" \
--query '{Errors: Errors}' \
--output json > "$temp_dir/result.json"
if ! ${pkgs.jq}/bin/jq -e '(.Errors // []) | length == 0' "$temp_dir/result.json" > /dev/null; then
${pkgs.coreutils}/bin/cat "$temp_dir/result.json" >&2
exit 1
fi
done
''
View File
View File
-195
View File
@@ -1,195 +0,0 @@
{ config, lib, pkgs, ... }:
let
cfg = config.services.minecraft-backups;
minecraft = config.services.minecraft-servers;
servers = lib.filterAttrs (_: server: server.enable) cfg.servers;
prune = import ../../../lib/s3-retention.nix { inherit pkgs; };
stateDir = name: "${cfg.stateDir}/${name}";
restore = name: server: pkgs.writeShellScript "minecraft-backup-resume-${name}" ''
set -eu
marker=${lib.escapeShellArg "${stateDir name}/restart-needed"}
if [ -e "$marker" ]; then
${pkgs.systemd}/bin/systemctl start ${lib.escapeShellArg server.service}
${pkgs.coreutils}/bin/rm -f "$marker"
fi
'';
backup = name: server: pkgs.writeShellScript "minecraft-backup-${name}" ''
set -eu
umask 077
state_dir=${lib.escapeShellArg (stateDir name)}
archive_dir="$state_dir/archive"
staging_dir="$state_dir/staging"
${pkgs.coreutils}/bin/install -d -m 0700 "$archive_dir" "$staging_dir"
exec 9>"$state_dir/lock"
${pkgs.util-linux}/bin/flock 9
: "''${AWS_ACCESS_KEY_ID:?AWS_ACCESS_KEY_ID is required}"
: "''${AWS_SECRET_ACCESS_KEY:?AWS_SECRET_ACCESS_KEY is required}"
upload() {
${pkgs.awscli2}/bin/aws s3 cp "$1" \
${lib.escapeShellArg "s3://${cfg.s3.bucket}/${cfg.s3.prefix}/${name}/"}"''${1##*/}" \
--endpoint-url ${lib.escapeShellArg cfg.s3.endpoint} \
--region ${lib.escapeShellArg cfg.s3.region} \
--cli-connect-timeout 30 --cli-read-timeout 300 --only-show-errors
${pkgs.coreutils}/bin/rm -f "$1"
}
# Retry a failed upload before creating another local archive.
for pending in "$archive_dir"/minecraft-${name}-????????T??????Z.tar.zst; do
[ -f "$pending" ] || continue
upload "$pending"
done
${restore name server}
trap '${restore name server}' EXIT
unit=${lib.escapeShellArg server.service}
if ${pkgs.systemd}/bin/systemctl is-active --quiet "$unit"; then
${lib.optionalString (server.announcementCommand != null) ''
${lib.escapeShellArg (toString server.announcementCommand)} \
"[Backup] Server will stop for backup in 5 minutes."
${pkgs.coreutils}/bin/sleep 240
${lib.escapeShellArg (toString server.announcementCommand)} \
"[Backup] Server will stop for backup in 1 minute."
${pkgs.coreutils}/bin/sleep 60
${lib.escapeShellArg (toString server.announcementCommand)} \
"[Backup] Server is stopping now to save a backup."
''}
${pkgs.coreutils}/bin/touch "$state_dir/restart-needed"
${pkgs.systemd}/bin/systemctl stop "$unit"
if [ "$(${pkgs.systemd}/bin/systemctl show "$unit" -p Result --value)" != success ]; then
echo "Minecraft did not stop cleanly; refusing to copy $unit" >&2
exit 1
fi
fi
${pkgs.rsync}/bin/rsync -a --checksum --delete --delete-excluded \
${lib.concatMapStringsSep " \\\n " (path: "--exclude=${lib.escapeShellArg "/${path}"}") server.exclude} \
${lib.escapeShellArg "${server.directory}/"} "$staging_dir/"
${restore name server}
trap - EXIT
timestamp="$(${pkgs.coreutils}/bin/date -u +%Y%m%dT%H%M%SZ)"
archive="$archive_dir/minecraft-${name}-$timestamp.tar.zst"
trap '${pkgs.coreutils}/bin/rm -f "$archive.tmp"' EXIT
${pkgs.gnutar}/bin/tar \
--use-compress-program=${lib.escapeShellArg "${pkgs.zstd}/bin/zstd -T2"} \
-C "$staging_dir" -cf "$archive.tmp" .
${pkgs.coreutils}/bin/mv "$archive.tmp" "$archive"
trap - EXIT
upload "$archive"
${prune} \
${lib.escapeShellArg cfg.s3.bucket} \
${lib.escapeShellArg cfg.s3.endpoint} \
${lib.escapeShellArg cfg.s3.region} \
${lib.escapeShellArg "${cfg.s3.prefix}/${name}"} \
${lib.escapeShellArg "minecraft-${name}-"} \
${toString cfg.s3.retentionDays} "$state_dir"
'';
in {
options.services.minecraft-backups = {
enable = lib.mkEnableOption "scheduled Minecraft archives in S3";
onCalendar = lib.mkOption {
type = lib.types.str;
default = "*-*-* 00/6:00:00";
description = "Backup schedule for each server.";
};
stateDir = lib.mkOption {
type = lib.types.str;
default = "/var/lib/minecraft-backups";
description = "Private staging trees and archives awaiting upload.";
};
s3 = {
bucket = lib.mkOption { type = lib.types.str; };
endpoint = lib.mkOption { type = lib.types.str; };
region = lib.mkOption { type = lib.types.str; };
prefix = lib.mkOption {
type = lib.types.str;
default = "minecraft/${config.networking.hostName}";
};
credentialsFile = lib.mkOption {
type = lib.types.str;
description = "Runtime environment file containing AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.";
};
retentionDays = lib.mkOption {
type = lib.types.ints.positive;
default = 14;
};
};
servers = lib.mkOption {
default = {};
description = "Enabled nix-minecraft servers are included automatically; additional engines can be declared here.";
type = lib.types.attrsOf (lib.types.submodule {
options = {
enable = lib.mkOption { type = lib.types.bool; default = true; };
service = lib.mkOption { type = lib.types.str; };
directory = lib.mkOption { type = lib.types.str; };
announcementCommand = lib.mkOption {
type = lib.types.nullOr lib.types.path;
default = null;
description = "Executable receiving one chat message argument. Enables warnings five minutes, one minute and immediately before stopping an active server.";
};
exclude = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [
"logs" "crash-reports" "backups" "cache" "libraries" "versions"
"mods" "resources" "*.jar" "server.properties"
];
description = "Root entries regenerated by deployment, logs, and secret-bearing server properties.";
};
};
});
};
};
config = lib.mkIf cfg.enable {
assertions = [
{
assertion = lib.hasPrefix "/" cfg.stateDir
&& !lib.hasPrefix "/nix/store/" cfg.stateDir;
message = "Minecraft backup stateDir must be an absolute runtime path.";
}
{
assertion = lib.hasPrefix "/" cfg.s3.credentialsFile
&& !lib.hasPrefix "/nix/store/" cfg.s3.credentialsFile;
message = "Minecraft S3 credentials must be a runtime file outside /nix/store.";
}
{
assertion = lib.hasPrefix "https://" cfg.s3.endpoint;
message = "Minecraft S3 endpoint must use HTTPS.";
}
] ++ lib.mapAttrsToList (name: server: {
assertion = builtins.match "[a-zA-Z0-9_-]+" name != null
&& lib.hasPrefix "/" server.directory
&& !(server.directory == cfg.stateDir || lib.hasPrefix "${server.directory}/" cfg.stateDir)
&& !(server.directory == cfg.stateDir || lib.hasPrefix "${cfg.stateDir}/" server.directory);
message = "Minecraft backup ${name} needs a safe name and a source directory separate from backup state.";
}) servers;
services.minecraft-backups.servers = lib.mapAttrs (name: _: {
service = lib.mkDefault "minecraft-server-${name}.service";
directory = lib.mkDefault "${minecraft.dataDir}/${name}";
}) (lib.filterAttrs (_: server: minecraft.enable && server.enable) minecraft.servers);
systemd.tmpfiles.rules = [ "d ${cfg.stateDir} 0700 root root - -" ]
++ lib.mapAttrsToList (name: _: "d ${stateDir name} 0700 root root - -") servers;
systemd.services = lib.mapAttrs' (name: server: lib.nameValuePair "minecraft-backup-${name}" {
description = "S3 backup of Minecraft ${name}";
wants = [ "network-online.target" ];
after = [ "network-online.target" ];
unitConfig.ConditionPathIsDirectory = server.directory;
serviceConfig = {
Type = "oneshot";
User = "root";
UMask = "0077";
EnvironmentFile = cfg.s3.credentialsFile;
ExecStart = backup name server;
# Also restore a stopped server when timeout/SIGKILL bypasses shell traps.
ExecStopPost = restore name server;
TimeoutStartSec = "2h";
};
}) servers;
systemd.timers = lib.mapAttrs' (name: _: lib.nameValuePair "minecraft-backup-${name}" {
wantedBy = [ "timers.target" ];
timerConfig = {
OnCalendar = cfg.onCalendar;
Persistent = true;
RandomizedDelaySec = "10min";
};
}) servers;
};
}
@@ -1,56 +0,0 @@
{ ... }:
{ config, lib, pkgs, ... }:
let
cfg = config.services.minecraft-public-relay;
in {
options.services.minecraft-public-relay = {
enable = lib.mkEnableOption "restricted SSH relay for Minecraft";
publicPort = lib.mkOption { type = lib.types.port; default = 25568; };
tunnelPort = lib.mkOption { type = lib.types.port; default = 25577; };
publicKey = lib.mkOption {
type = lib.types.str;
description = "Public SSH key of the Minecraft tunnel client";
};
};
config = lib.mkIf cfg.enable {
networking.firewall.allowedTCPPorts = [ cfg.publicPort ];
users.groups.mc-wow-relay = { };
users.users.mc-wow-relay = {
isSystemUser = true;
group = "mc-wow-relay";
openssh.authorizedKeys.keys = [
"restrict,port-forwarding,permitlisten=\"127.0.0.1:${toString cfg.tunnelPort}\" ${cfg.publicKey}"
];
};
services.openssh.extraConfig = ''
Match User mc-wow-relay
ClientAliveInterval 15
ClientAliveCountMax 3
AllowTcpForwarding remote
PermitListen 127.0.0.1:${toString cfg.tunnelPort}
AllowAgentForwarding no
X11Forwarding no
PermitTTY no
ForceCommand ${pkgs.coreutils}/bin/false
Match all
'';
systemd.sockets.minecraft-wow-proxy = {
description = "wowmine public Minecraft port";
wantedBy = [ "sockets.target" ];
listenStreams = [ "0.0.0.0:${toString cfg.publicPort}" ];
};
systemd.services.minecraft-wow-proxy = {
description = "Forward Minecraft to the neuro reverse tunnel";
requires = [ "minecraft-wow-proxy.socket" ];
after = [ "minecraft-wow-proxy.socket" ];
serviceConfig = {
ExecStart = "${pkgs.systemd}/lib/systemd/systemd-socket-proxyd 127.0.0.1:${toString cfg.tunnelPort}";
DynamicUser = true;
NoNewPrivileges = true;
ProtectSystem = "strict";
ProtectHome = true;
PrivateTmp = true;
};
};
};
}
-203
View File
@@ -1,203 +0,0 @@
{ config, lib, pkgs, ... }:
let
minecraft = config.services.minecraft-servers;
restores = lib.filterAttrs (_: restore: restore.enable) config.services.minecraft-backup-restores;
marker = ".minecraft-backup-restore-complete";
# Python's data filter resolves symlink chains against the extraction tree and
# rejects escaping links and special files. Also reject absolute/traversal
# names outright (data_filter alone strips leading slashes).
extract = pkgs.writeText "minecraft-restore-extract.py" ''
import pathlib
import sys
import tarfile
def safe_member(member: tarfile.TarInfo, destination: str) -> tarfile.TarInfo | None:
path = pathlib.PurePosixPath(member.name)
if path.is_absolute() or ".." in path.parts or path.parts == ("${marker}",):
raise tarfile.FilterError(f"Unsafe archive entry: {member.name}")
# nix-minecraft regenerates this as an absolute store symlink. Keep
# bootstrap's EULA rather than restoring a possibly obsolete store path.
if path.parts == ("eula.txt",):
return None
return tarfile.data_filter(member, destination)
with tarfile.open(sys.argv[1], mode="r:") as archive:
archive.extractall(sys.argv[2], filter=safe_member)
'';
fresh = pkgs.writeText "minecraft-restore-fresh.py" ''
import os
import pathlib
import sys
target = pathlib.Path(sys.argv[1])
level_name = sys.argv[2]
if os.path.lexists(target / level_name):
sys.exit(f"Refusing existing Minecraft level directory: {target / level_name}")
# Refuse even incomplete saves, including custom level-name directories
# and save signatures nested beneath mod-specific dimension paths.
for directory, directories, files in os.walk(target, followlinks=False):
for name in directories + files:
path = pathlib.Path(directory) / name
if (
name in {"level.dat", "level.dat_old", "session.lock", "region",
"entities", "poi", "playerdata", "advancements", "stats",
"dimensions", "DIM-1", "DIM1"}
or name.endswith((".mca", ".mcr"))
or (path.parent == target and (
name.startswith("world") or name == level_name
))
):
sys.exit(f"Refusing existing Minecraft world state: {path}")
'';
script = name: restore:
let
target = "${minecraft.dataDir}/${restore.serverName}";
levelName = toString (minecraft.servers.${restore.serverName}.serverProperties.level-name or "world");
identity = builtins.toJSON { inherit name; inherit (restore) bucket key endpoint; };
in pkgs.writeShellScript "minecraft-backup-restore-${name}" ''
set -euo pipefail
umask 077
target=${lib.escapeShellArg target}
${pkgs.coreutils}/bin/mkdir -p ${lib.escapeShellArg minecraft.dataDir}
exec 9>${lib.escapeShellArg "${minecraft.dataDir}/.minecraft-restore-${restore.serverName}.lock"}
${pkgs.util-linux}/bin/flock 9
if [ -L "$target" ]; then
echo "Refusing symlink restore target: $target" >&2
exit 1
fi
if [ -e "$target/${marker}" ] || [ -L "$target/${marker}" ]; then
if [ -f "$target/${marker}" ] && [ ! -L "$target/${marker}" ] &&
[ "$(${pkgs.coreutils}/bin/cat "$target/${marker}")" = ${lib.escapeShellArg identity} ]; then
exit 0
fi
echo "Restore marker does not match the configured S3 backup: $target/${marker}" >&2
exit 1
fi
${pkgs.python3}/bin/python ${fresh} "$target" ${lib.escapeShellArg levelName}
work="$(${pkgs.coreutils}/bin/mktemp -d ${lib.escapeShellArg "${minecraft.dataDir}/.minecraft-restore-${restore.serverName}.XXXXXX"})"
trap '${pkgs.coreutils}/bin/rm -rf -- "$work"' EXIT
trap 'exit 1' HUP INT TERM
${pkgs.coreutils}/bin/mkdir "$work/server"
if [ -e "$target" ]; then
test -d "$target"
${pkgs.coreutils}/bin/cp -a -- "$target/." "$work/server/"
fi
: "''${AWS_ACCESS_KEY_ID:?AWS_ACCESS_KEY_ID is required}"
: "''${AWS_SECRET_ACCESS_KEY:?AWS_SECRET_ACCESS_KEY is required}"
${pkgs.awscli2}/bin/aws s3 cp \
${lib.escapeShellArg "s3://${restore.bucket}/${restore.key}"} "$work/backup.tar.zst" \
--endpoint-url ${lib.escapeShellArg restore.endpoint} \
--region ${lib.escapeShellArg restore.region} \
--cli-connect-timeout 30 --cli-read-timeout 300 --only-show-errors
${lib.optionalString (restore.expectedSize != null) ''
test "$(${pkgs.coreutils}/bin/stat -c %s "$work/backup.tar.zst")" = ${toString restore.expectedSize}
''}
${pkgs.zstd}/bin/zstd --test --quiet "$work/backup.tar.zst"
${pkgs.zstd}/bin/zstd --decompress --stdout "$work/backup.tar.zst" > "$work/backup.tar"
${pkgs.python3}/bin/python ${extract} "$work/backup.tar" "$work/server"
# Require the configured save, not an unrelated nested level.dat that
# would let Minecraft silently generate a fresh world after this restore.
test -f "$work/server"/${lib.escapeShellArg "${levelName}/level.dat"}
printf '%s\n' ${lib.escapeShellArg identity} > "$work/server/${marker}"
${pkgs.coreutils}/bin/chown -hR minecraft:minecraft "$work/server"
# The marker moves with the tree in the same atomic operation. When a
# bootstrap exists, exchange leaves it in work/server for trap cleanup;
# an exchange failure leaves the original directory untouched.
if [ -e "$target" ]; then
${pkgs.coreutils}/bin/mv --exchange --no-copy -T "$work/server" "$target"
else
${pkgs.coreutils}/bin/mv --no-copy -T "$work/server" "$target"
fi
'';
in {
options.services.minecraft-backup-restores = lib.mkOption {
default = {};
description = "One-time full S3 backup restores, optionally after modpack bootstrap. The regenerated root eula.txt is retained from bootstrap.";
type = lib.types.attrsOf (lib.types.submodule ({ name, ... }: {
options = {
enable = lib.mkEnableOption "one-time Minecraft backup restore";
serverName = lib.mkOption { type = lib.types.str; default = name; };
completionMarker = lib.mkOption {
type = lib.types.str;
readOnly = true;
default = "${minecraft.dataDir}/${config.services.minecraft-backup-restores.${name}.serverName}/${marker}";
description = "Persistent marker path; bootstrap units should use ConditionPathExists=!<this path> to preserve restored configuration on subsequent boots.";
};
bucket = lib.mkOption { type = lib.types.str; };
key = lib.mkOption {
type = lib.types.str;
description = "Exact S3 object key ending in .tar.zst.";
};
endpoint = lib.mkOption { type = lib.types.str; };
region = lib.mkOption { type = lib.types.str; };
credentialsFile = lib.mkOption {
type = lib.types.str;
description = "Runtime EnvironmentFile outside /nix/store containing AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.";
};
expectedSize = lib.mkOption {
type = lib.types.nullOr lib.types.ints.positive;
default = null;
description = "Expected compressed object size in bytes.";
};
timeout = lib.mkOption { type = lib.types.str; default = "2h"; };
afterUnits = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [];
description = "Required units that finish before restore, e.g. modpack bootstrap. Backup files override bootstrap files; bootstrap-only mods remain.";
};
};
}));
};
config = lib.mkIf (restores != {}) {
assertions = [
{
assertion = lib.hasPrefix "/" minecraft.dataDir && !lib.hasPrefix "/nix/store/" minecraft.dataDir;
message = "Minecraft restores require an absolute runtime dataDir.";
}
{
assertion = lib.length (lib.unique (map (restore: restore.serverName) (lib.attrValues restores))) == lib.length (lib.attrNames restores);
message = "Minecraft restores must have unique server targets.";
}
] ++ lib.concatLists (lib.mapAttrsToList (name: restore: [
{
assertion = builtins.match "[a-zA-Z0-9_-]+" name != null
&& builtins.match "[a-zA-Z0-9_-]+" restore.serverName != null
&& minecraft.enable
&& (minecraft.servers.${restore.serverName}.enable or false);
message = "Minecraft restore ${name} must target an enabled Minecraft server and use safe names.";
}
{
assertion = lib.hasPrefix "/" restore.credentialsFile
&& !lib.hasPrefix "/nix/store/" restore.credentialsFile;
message = "Minecraft restore ${name} credentials must be a runtime file outside /nix/store.";
}
{
assertion = lib.hasPrefix "https://" restore.endpoint && lib.hasSuffix ".tar.zst" restore.key;
message = "Minecraft restore ${name} requires HTTPS and an exact .tar.zst object key.";
}
]) restores);
systemd.services = lib.mkMerge (lib.mapAttrsToList (name: restore: {
"minecraft-backup-restore-${name}" = {
description = "One-time full backup restore of Minecraft ${restore.serverName}";
wants = [ "network-online.target" ];
after = [ "network-online.target" ] ++ restore.afterUnits;
requires = restore.afterUnits;
before = [ "minecraft-server-${restore.serverName}.service" ];
serviceConfig = {
Type = "oneshot";
User = "root";
UMask = "0077";
EnvironmentFile = restore.credentialsFile;
ExecStart = script name restore;
TimeoutStartSec = restore.timeout;
};
};
"minecraft-server-${restore.serverName}" = {
requires = [ "minecraft-backup-restore-${name}.service" ];
after = [ "minecraft-backup-restore-${name}.service" ];
};
}) restores);
};
}
+1
View File
@@ -12,6 +12,7 @@
in {
imports = [
inputs.disko.nixosModules.default
inputs.nixos-mailserver.nixosModules.mailserver
];
options.hectic.archetype.base.enable = lib.mkEnableOption "Enable archetupe.dev";
@@ -132,11 +132,7 @@ in {
"${cfg.ipv6}::/64"
] ++ lib.optional (cfg.floatingIpv4 != null) "${cfg.floatingIpv4}/32";
routes = [
{
Gateway = "172.31.1.1";
GatewayOnLink = true;
PreferredSource = cfg.ipv4;
}
{ Gateway = "172.31.1.1"; GatewayOnLink = true; }
{ Gateway = "fe80::1"; }
];
};
-134
View File
@@ -1,134 +0,0 @@
{ ... }:
{
lib,
config,
...
}: let
cfg = config.hectic.hardware.njalla;
in {
options.hectic.hardware.njalla = {
enable = lib.mkEnableOption "Enable njalla hardware configurations";
ipv4 = lib.mkOption {
type = lib.types.strMatching "^([0-9]{1,3}\\.){3}[0-9]{1,3}$";
example = "185.193.126.103";
description = ''
Njalla IPv4 address assigned to the host.
'';
};
ipv4PrefixLength = lib.mkOption {
type = lib.types.int;
default = 24;
example = 24;
description = ''
Njalla IPv4 prefix length.
'';
};
ipv4Gateway = lib.mkOption {
type = lib.types.strMatching "^([0-9]{1,3}\\.){3}[0-9]{1,3}$";
default = "185.193.126.1";
example = "185.193.126.1";
description = ''
Njalla IPv4 gateway.
'';
};
ipv6 = lib.mkOption {
type = lib.types.strMatching "^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$";
example = "2a0a:3840:1337:126:0:b9c1:7e67:1337";
description = ''
Njalla IPv6 address assigned to the host.
'';
};
ipv6PrefixLength = lib.mkOption {
type = lib.types.int;
default = 64;
example = 64;
description = ''
Njalla IPv6 prefix length.
'';
};
ipv6Gateway = lib.mkOption {
type = lib.types.strMatching "^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$";
default = "2a0a:3840:1337:126::1";
example = "2a0a:3840:1337:126::1";
description = ''
Njalla IPv6 gateway.
'';
};
networkMatchConfigName = lib.mkOption {
type = lib.types.str;
default = "eth0";
example = "eth0";
description = ''
Njalla container network interface name.
'';
};
device = lib.mkOption {
type = lib.types.str;
default = "/dev/vda";
example = "/dev/disk/by-id/virtio-root";
description = ''
Njalla installation disk for disko/nixos-anywhere.
`/dev/vda` is the default block device visible on the inspected Njalla
host. Prefer a stable `/dev/disk/by-id/...` path when available.
'';
};
enableDisko = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Whether to provide a disko layout for nixos-anywhere installs.
'';
};
};
config = lib.mkIf cfg.enable (lib.mkMerge [
{
boot.isContainer = true;
networking.useDHCP = false;
networking.useNetworkd = true;
systemd.network.enable = true;
systemd.network.networks."30-wan" = {
matchConfig.Name = cfg.networkMatchConfigName;
networkConfig.DHCP = "no";
address = [
"${cfg.ipv4}/${toString cfg.ipv4PrefixLength}"
"${cfg.ipv6}/${toString cfg.ipv6PrefixLength}"
];
routes = [
{ Gateway = cfg.ipv4Gateway; }
{ Gateway = cfg.ipv6Gateway; }
];
};
networking.nameservers = [ "1.1.1.1" "8.8.8.8" ];
}
(lib.mkIf cfg.enableDisko {
boot.loader.grub.device = cfg.device;
disko.devices.disk.main = {
type = "disk";
device = cfg.device;
content = {
type = "gpt";
partitions = {
boot = {
size = "1M";
type = "EF02";
priority = 1;
};
root = {
size = "100%";
content = {
type = "filesystem";
format = "ext4";
mountpoint = "/";
};
};
};
};
};
})
]);
}
-1
View File
@@ -18,7 +18,6 @@ in {
config = lib.mkIf cfg.enable {
programs.nixvim = {
nixpkgs.source = inputs.nixpkgs;
enable = true;
extraPackages = with pkgs; [ gcc ];
+30 -1
View File
@@ -25,7 +25,36 @@ in {
programs.bash.shellAliases.tmux = "tmux a";
home-manager.sharedModules = [
(flake + "/home/module/program/tmux.nix")
{
programs.tmux = {
enable = true;
plugins = with pkgs.tmuxPlugins; [ resurrect continuum ];
keyMode = "vi";
escapeTime = 500;
historyLimit = 50000;
newSession = true;
extraConfig = ''
# resurrect
set -g @resurrect-strategy-vim 'session'
set -g @resurrect-strategy-nvim 'session'
set -g @resurrect-capture-pane-contents 'on'
resurrect_dir="$HOME/.tmux/resurrect"
set -g @resurrect-dir $resurrect_dir
set -g @resurrect-hook-post-save-all 'target=$(readlink -f $resurrect_dir/last); sed "s| --cmd .*-vim-pack-dir||g; s|/etc/profiles/per-user/$USER/bin/||g; s|/home/$USER/.nix-profile/bin/||g" $target | sponge $target'
# continuum
set -g @continuum-restore 'on'
set -g @continuum-boot 'on'
set -g @continuum-save-interval '10'
bind-key -T copy-mode-vi v send-keys -X begin-selection
bind-key -T copy-mode-vi C-v send-keys -X rectangle-toggle
bind-key O select-pane -t :.-
'';
};
}
];
home-manager.users.root.home.stateVersion = lib.mkDefault "25.05";
@@ -1,64 +0,0 @@
{ ... }:
{ config, lib, pkgs, ... }: let
cfg = config.hectic.services.affine-chatgpt;
stateDirectory = "/var/lib/affine-chatgpt";
in {
options.hectic.services.affine-chatgpt = {
enable = lib.mkEnableOption "native ChatGPT subscription gateway for AFFiNE";
package = lib.mkOption {
type = lib.types.package;
default = pkgs.hectic.affine-chatgpt;
description = "Package providing the affine-chatgpt executable.";
};
port = lib.mkOption {
type = lib.types.port;
default = 3012;
description = "Loopback-only gateway port.";
};
gatewayKeyFile = lib.mkOption {
type = lib.types.path;
default = "${stateDirectory}/gateway-key";
description = "Owner-only runtime bearer key readable by affine-chatgpt; never put its contents in Nix.";
};
};
config = lib.mkIf cfg.enable {
users.groups.affine-chatgpt = {};
users.users.affine-chatgpt = {
isSystemUser = true;
group = "affine-chatgpt";
home = stateDirectory;
};
systemd.services.affine-chatgpt = {
description = "Native ChatGPT subscription gateway for AFFiNE";
wantedBy = [ "multi-user.target" ];
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
unitConfig.ConditionPathExists = "${stateDirectory}/session/credentials.json";
preStart = ''
install -d -m 0700 ${stateDirectory}/session
'';
serviceConfig = {
Type = "simple";
User = "affine-chatgpt";
Group = "affine-chatgpt";
StateDirectory = "affine-chatgpt";
StateDirectoryMode = "0700";
ExecStart = "${cfg.package}/bin/affine-chatgpt --state-dir ${stateDirectory}/session serve --host 127.0.0.1 --port ${toString cfg.port} --gateway-key-file ${cfg.gatewayKeyFile}";
Restart = "on-failure";
RestartSec = "5s";
UMask = "0077";
NoNewPrivileges = true;
PrivateTmp = true;
ProtectHome = true;
ProtectSystem = "strict";
ReadWritePaths = [ stateDirectory ];
RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" ];
CapabilityBoundingSet = "";
LimitCORE = 0;
MemoryMax = "256M";
TasksMax = 64;
};
};
};
}
-215
View File
@@ -1,215 +0,0 @@
{
inputs,
flake,
...
}:
{
config,
lib,
pkgs,
...
}: let
cfg = config.hectic.services.affine;
stateDirectory = "/var/lib/affine-native";
configDirectory = "${stateDirectory}/.affine/config";
storageDirectory = "${stateDirectory}/.affine/storage";
initialConfig = pkgs.writeText "affine-native-config.json" (builtins.toJSON (
lib.recursiveUpdate {
server = {
externalUrl = cfg.externalUrl;
host = "localhost";
listenAddr = cfg.address;
name = cfg.serverName;
port = cfg.port;
};
auth = {
allowSignup = false;
allowSignupForOauth = false;
};
copilot.enabled = false;
} cfg.settings
));
prepareState = ''
install -d -m 0700 ${configDirectory} ${storageDirectory}
if [ ! -e ${configDirectory}/config.json ]; then
install -m 0600 ${initialConfig} ${configDirectory}/config.json
fi
'';
commonEnvironment = {
HOME = stateDirectory;
PORT = toString cfg.port;
AFFINE_SERVER_PORT = toString cfg.port;
LISTEN_ADDR = cfg.address;
REDIS_SERVER_HOST = cfg.redisHost;
REDIS_SERVER_PORT = toString cfg.redisPort;
};
commonServiceConfig = {
User = "affine-native";
Group = "affine-native";
StateDirectory = "affine-native";
StateDirectoryMode = "0700";
EnvironmentFile = cfg.environmentFile;
UMask = "0077";
NoNewPrivileges = true;
PrivateTmp = true;
ProtectHome = true;
ProtectSystem = "strict";
ReadWritePaths = [ stateDirectory ];
RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" ];
};
in {
options.hectic.services.affine = {
enable = lib.mkEnableOption "native AFFiNE server";
package = lib.mkOption {
type = lib.types.package;
default = pkgs.callPackage (flake + "/package/affine") {
inherit inputs;
system = pkgs.stdenv.hostPlatform.system;
nodejs = pkgs.nodejs_22;
# Baseline bundle intentionally excludes independently deployed picker patches.
frontendPatches = [ (flake + "/package/affine/gitea-document-typography.patch") ];
};
defaultText = lib.literalExpression "pkgs.callPackage ./package/affine { ...; }";
description = ''
AFFiNE package providing affine-server and affine-migrate. The default
source-built package is available only on x86_64-linux and has an unfree
backend license. Explicitly allow both "affine" and
"affine-server-native" through nixpkgs.config.allowUnfreePredicate, or
provide a package whose licensing policy you have configured separately.
'';
};
frontendPackage = lib.mkOption {
type = lib.types.nullOr lib.types.package;
default = null;
description = ''
Optional source-built AFFiNE web, admin, and mobile static assets to
bind over the native server's bundled frontend.
'';
};
environmentFile = lib.mkOption {
type = lib.types.path;
description = ''
Runtime environment file containing DATABASE_URL and any secret AFFiNE
or Redis variables. Keep this file outside the Nix store.
'';
};
address = lib.mkOption {
type = lib.types.str;
default = "127.0.0.1";
description = "Address on which AFFiNE listens.";
};
port = lib.mkOption {
type = lib.types.port;
default = 3011;
description = "Port on which AFFiNE listens.";
};
externalUrl = lib.mkOption {
type = lib.types.str;
default = "http://localhost:${toString cfg.port}";
description = "External URL written to the initial AFFiNE configuration.";
};
serverName = lib.mkOption {
type = lib.types.str;
default = "AFFiNE";
description = "Server name written to the initial AFFiNE configuration.";
};
redisHost = lib.mkOption {
type = lib.types.str;
default = "127.0.0.1";
description = "External Redis host exported as REDIS_SERVER_HOST.";
};
redisPort = lib.mkOption {
type = lib.types.port;
default = 6388;
description = "External Redis port exported as REDIS_SERVER_PORT.";
};
settings = lib.mkOption {
type = (pkgs.formats.json {}).type;
default = {};
description = ''
Extra values recursively merged into the initial AFFiNE config.json.
This seed is written only when config.json does not already exist.
'';
};
};
config = lib.mkIf cfg.enable {
assertions = [
{
assertion = pkgs.stdenv.hostPlatform.system == "x86_64-linux";
message = "hectic.services.affine currently supports only x86_64-linux.";
}
{
assertion = cfg.frontendPackage == null || (
cfg.package ? version &&
cfg.frontendPackage ? version &&
cfg.frontendPackage.version == cfg.package.version
);
message = "hectic.services.affine.frontendPackage version must match hectic.services.affine.package version.";
}
{
assertion = cfg.frontendPackage == null || (
cfg.package ? frontendStatic &&
cfg.package.frontendStatic ? revision &&
builtins.isString cfg.package.frontendStatic.revision &&
cfg.package.frontendStatic.revision != "" &&
cfg.frontendPackage ? revision &&
builtins.isString cfg.frontendPackage.revision &&
cfg.frontendPackage.revision != "" &&
cfg.frontendPackage.revision == cfg.package.frontendStatic.revision
);
message = "hectic.services.affine.frontendPackage revision must be a non-empty string matching package.frontendStatic.revision.";
}
];
users.groups.affine-native = {};
users.users.affine-native = {
isSystemUser = true;
group = "affine-native";
home = stateDirectory;
};
systemd.services.affine-native-migrate = {
description = "AFFiNE database and data migrations";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
environment = commonEnvironment;
preStart = prepareState;
restartTriggers = [ cfg.package initialConfig ];
serviceConfig = commonServiceConfig // {
Type = "oneshot";
ExecStart = "${cfg.package}/bin/affine-migrate";
RemainAfterExit = true;
};
};
systemd.services.affine-native = {
description = "Native AFFiNE server";
after = [ "network-online.target" "affine-native-migrate.service" ];
wants = [ "network-online.target" ];
requires = [ "affine-native-migrate.service" ];
wantedBy = [ "multi-user.target" ];
environment = commonEnvironment;
preStart = prepareState;
restartTriggers = [ cfg.package initialConfig ] ++ lib.optional (cfg.frontendPackage != null) cfg.frontendPackage;
serviceConfig = commonServiceConfig // {
Type = "simple";
ExecStart = "${cfg.package}/bin/affine-server";
Restart = "on-failure";
RestartSec = "5s";
BindReadOnlyPaths = lib.optional (cfg.frontendPackage != null)
"${cfg.frontendPackage}:${cfg.package}/share/affine/static";
};
};
};
}
-101
View File
@@ -1,101 +0,0 @@
{ ... }: {
lib,
config,
pkgs,
...
}: let
cfg = config.hectic.services.dify;
difySource = pkgs.fetchFromGitHub {
owner = "langgenius";
repo = "dify";
rev = "00e578606715a9da34488608edee8c68d4ef4893";
hash = "sha256-kLxMdmt1FtOl39C9SS7ZGY6C78e3hPiVI5Q3EdbkMPU=";
};
composeOverride = pkgs.writeText "dify-compose.override.yaml" ''
services:
nginx:
ports: !override
- "127.0.0.1:${toString cfg.port}:80"
plugin_daemon:
ports: !override
- "127.0.0.1:${toString cfg.pluginPort}:5003"
environment:
DB_USERNAME: ''${DB_USERNAME:-postgres}
DB_HOST: ''${DB_HOST:-db_postgres}
DB_PORT: ''${DB_PORT:-5432}
REDIS_HOST: ''${REDIS_HOST:-redis}
REDIS_PORT: ''${REDIS_PORT:-6379}
REDIS_DB: ''${REDIS_DB:-0}
'';
in {
options.hectic.services.dify = {
enable = lib.mkEnableOption "Dify self-hosted AI platform";
dataDir = lib.mkOption {
type = lib.types.path;
default = "/var/lib/dify";
description = "Persistent directory for Dify compose state and volumes.";
};
environmentFile = lib.mkOption {
type = lib.types.path;
description = ''
Environment file for Dify. Keep secrets here, including SECRET_KEY,
DB_PASSWORD, REDIS_PASSWORD, and plugin daemon credentials.
'';
};
port = lib.mkOption {
type = lib.types.port;
default = 80;
description = "Loopback HTTP port forwarded to Dify through SSH.";
};
pluginPort = lib.mkOption {
type = lib.types.port;
default = 5003;
description = "Loopback plugin daemon port forwarded through SSH when needed.";
};
composeProfiles = lib.mkOption {
type = lib.types.str;
default = "weaviate,postgresql,collaboration";
description = "Dify Docker Compose profiles to start.";
};
};
config = lib.mkIf cfg.enable {
virtualisation.docker.enable = true;
systemd.services.dify = {
description = "Dify Docker Compose stack";
wantedBy = [ "multi-user.target" ];
wants = [ "docker.service" ];
after = [ "docker.service" ];
requires = [ "docker.service" ];
restartIfChanged = true;
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
WorkingDirectory = cfg.dataDir;
ExecStartPre = pkgs.writeShellScript "dify-prepare" ''
set -eu
install -d -m 0750 ${lib.escapeShellArg cfg.dataDir}
cp -R ${difySource}/docker/. ${lib.escapeShellArg cfg.dataDir}/
install -m 0600 ${lib.escapeShellArg cfg.environmentFile} ${lib.escapeShellArg cfg.dataDir}/.env
'';
ExecStart = "${pkgs.docker-compose}/bin/docker-compose --project-directory ${cfg.dataDir} --file ${cfg.dataDir}/docker-compose.yaml --file ${composeOverride} --env-file ${cfg.dataDir}/.env up --detach";
ExecStop = "${pkgs.docker-compose}/bin/docker-compose --project-directory ${cfg.dataDir} --file ${cfg.dataDir}/docker-compose.yaml --file ${composeOverride} --env-file ${cfg.dataDir}/.env down";
};
environment = {
COMPOSE_PROFILES = cfg.composeProfiles;
};
};
systemd.tmpfiles.rules = [
"d ${cfg.dataDir} 0750 root root -"
];
};
}
+37 -58
View File
@@ -9,70 +9,49 @@
config,
...
}: let
cfg = config.hectic.services.element;
nonEmptyStr = lib.types.strMatching ".+";
generatedSettings = {
default_server_config = {
"m.homeserver".base_url = cfg.homeserverBaseUrl;
"m.homeserver".server_name = cfg.homeserverServerName;
"m.identity_server".base_url = "https://vector.im";
};
room_directory.servers = [ cfg.homeserverServerName ];
jitsi = lib.optionalAttrs (cfg.jitsiPreferredDomain != null) {
preferred_domain = cfg.jitsiPreferredDomain;
};
default_theme = "dark";
show_labs_settings = true;
};
legacyCfg = config.hectic.services.matrix;
hasClusterCfg = config.hectic ? generic && config.hectic.generic ? matrix-cluster;
clusterCfg = if hasClusterCfg then config.hectic.generic.matrix-cluster else null;
clusterSynapseEnabled =
if hasClusterCfg
then clusterCfg.enable
&& (if clusterCfg.overrideEnableSynapse != null then clusterCfg.overrideEnableSynapse else clusterCfg.role == "primary")
else false;
enabled = legacyCfg.enable || clusterSynapseEnabled;
matrixDomain = if legacyCfg.enable then legacyCfg.matrixDomain else if hasClusterCfg then clusterCfg.matrixDomain else "";
jitsiPreferredDomain =
if legacyCfg.enable && config.hectic.services.jitsi.enable
then config.hectic.services.jitsi.hostName
else if hasClusterCfg then clusterCfg.jitsi.preferredDomain else null;
in {
options.hectic.services.element = {
enable = lib.mkEnableOption "Element web client";
hostName = lib.mkOption {
type = nonEmptyStr;
description = "FQDN serving the Element web client.";
};
homeserverBaseUrl = lib.mkOption {
type = nonEmptyStr;
description = "Public Matrix homeserver base URL used by Element.";
};
homeserverServerName = lib.mkOption {
type = nonEmptyStr;
description = "Matrix server name presented by Element.";
};
jitsiPreferredDomain = lib.mkOption {
type = lib.types.nullOr nonEmptyStr;
default = null;
description = "Preferred Jitsi domain, or null to leave it unset.";
};
settings = lib.mkOption {
type = lib.types.attrsOf (pkgs.formats.json {}).type;
default = {};
description = ''
Extra Element config recursively merged over generated defaults.
Values here may override generated keys. Settings are PUBLIC in the
Nix store and served config.json; do not put secrets here.
'';
};
};
config = lib.mkIf cfg.enable {
services.nginx.enable = true;
services.nginx.virtualHosts.${cfg.hostName} = {
config = lib.mkIf enabled {
services.nginx.virtualHosts."element.${matrixDomain}" = {
enableACME = true;
forceSSL = true;
locations."= /config.${cfg.hostName}.json".return = "302 /config.json";
locations."= /config.element.${matrixDomain}.json".return = "302 /config.json";
root = pkgs.hectic.element-web.override {
conf = lib.recursiveUpdate generatedSettings cfg.settings;
conf = {
default_server_config = {
"m.homeserver".base_url = "https://${matrixDomain}";
"m.homeserver".server_name = matrixDomain;
"m.identity_server".base_url = "https://vector.im";
};
room_directory.servers = [
matrixDomain
];
hectic.videoMessages.enabled = true;
jitsi = lib.optionalAttrs (jitsiPreferredDomain != null) {
preferred_domain = jitsiPreferredDomain;
};
default_theme = "dark";
show_labs_settings = true;
};
};
};
};
@@ -1,267 +0,0 @@
{
inputs,
flake,
self,
}:
{
pkgs,
lib,
config,
...
}:
let
system = pkgs.stdenv.hostPlatform.system;
cfg = config.hectic.services.gitea-runner-controller;
secretPrefix = "gitea-runner-controller";
mkControllerSecret = name: {
name = "${secretPrefix}/${name}";
value = {
sopsFile = flake + "/sus/gitea-runners.yaml";
key = "gitea/hectic-lab/controller/${name}";
};
};
controllerSecrets = builtins.listToAttrs (map mkControllerSecret [
"hcloud-token"
"webhook-secret"
"admin-token"
"ssh-private-key"
]);
# Registration token is shared with the existing K8s/local runner setup.
registrationTokenPath = config.sops.secrets."gitea-runner/org-registration-token".path;
commonEnvironment =
[
"GCR_STATE_DIR=/var/lib/gitea-runner-controller"
"GCR_GITEA_URL=${cfg.giteaBaseUrl}"
"GCR_ALLOWED_REPOS=${lib.concatStringsSep "," cfg.allowedRepos}"
"GCR_CONCURRENCY_CAP=${toString cfg.concurrencyCap}"
"GCR_PER_REPO_CAP=${toString cfg.perRepoCap}"
"GCR_RECONCILE_INTERVAL_SEC=${toString cfg.reconcileIntervalSec}"
"GCR_BUDGET_EUR_MONTHLY=${cfg.budgetEurMonthly}"
"GCR_HETZNER_LOCATION=${cfg.hetznerLocation}"
"HCLOUD_TOKEN_FILE=${config.sops.secrets."${secretPrefix}/hcloud-token".path}"
"GITEA_WEBHOOK_SECRET_FILE=${config.sops.secrets."${secretPrefix}/webhook-secret".path}"
"GITEA_REGISTRATION_TOKEN_FILE=${registrationTokenPath}"
"GITEA_ADMIN_TOKEN_FILE=${config.sops.secrets."${secretPrefix}/admin-token".path}"
"GCR_SSH_PRIVKEY_FILE=${config.sops.secrets."${secretPrefix}/ssh-private-key".path}"
"GCR_HCLOUD_SSH_KEY_ID=${toString cfg.hcloudSshKeyId}"
"GCR_NIX_VERSION=${cfg.nixVersion}"
"GCR_NIX_TARBALL_SHA256=${cfg.nixTarballSha256}"
"GCR_ARM_NIX_TARBALL_SHA256=${cfg.armNixTarballSha256}"
"GCR_ACT_RUNNER_VERSION=${cfg.actRunnerVersion}"
"GCR_ACT_RUNNER_SHA256=${cfg.actRunnerSha256}"
]
++ lib.optional (cfg.debugSshPublicKey != null) "\"GCR_DEBUG_SSH_PUBKEY=${cfg.debugSshPublicKey}\""
++ lib.optionals (cfg.imageId != null) [ "GCR_IMAGE_ID=${cfg.imageId}" ]
++ lib.optionals (cfg.armImageId != null) [ "GCR_ARM_IMAGE_ID=${cfg.armImageId}" ]
++ lib.optionals (cfg.nixImageId != null) [ "GCR_NIX_IMAGE_ID=${cfg.nixImageId}" ]
++ lib.optionals (cfg.armNixImageId != null) [ "GCR_ARM_NIX_IMAGE_ID=${cfg.armNixImageId}" ];
in
{
options = {
hectic.services.gitea-runner-controller = {
enable = lib.mkEnableOption "gitea-runner-controller — ephemeral Hetzner VM runner controller";
listenAddr = lib.mkOption {
type = lib.types.str;
default = "127.0.0.1";
description = "Address the webhook listener binds to.";
};
listenPort = lib.mkOption {
type = lib.types.port;
default = 8787;
description = "Port the webhook listener binds to.";
};
webhookHost = lib.mkOption {
type = lib.types.str;
default = "runners.hectic-lab.com";
description = "Public vhost Gitea delivers webhooks to. Requires a DNS A record to this host.";
};
giteaBaseUrl = lib.mkOption {
type = lib.types.str;
default = "https://gitea.hectic-lab.com";
description = "Public Gitea URL runners register against.";
};
allowedRepos = lib.mkOption {
type = with lib.types; listOf str;
default = [ "hectic-lab/util.nix" ];
description = "Repos whose workflow_job events may trigger VM creation.";
};
concurrencyCap = lib.mkOption {
type = lib.types.int;
default = 2;
description = "Maximum simultaneously assigned runner VMs (global); retained idle VMs do not count.";
};
perRepoCap = lib.mkOption {
type = lib.types.int;
default = 1;
description = "Maximum concurrently assigned runner VMs per repo; retained idle VMs do not count.";
};
reconcileIntervalSec = lib.mkOption {
type = lib.types.int;
default = 60;
description = "Seconds between reconciliation ticks.";
};
budgetEurMonthly = lib.mkOption {
type = lib.types.str;
default = "15";
description = "Soft monthly EUR ceiling for estimated VM spend.";
};
hetznerLocation = lib.mkOption {
type = lib.types.str;
default = "nbg1";
description = "Hetzner location for ephemeral VMs.";
};
imageId = lib.mkOption {
type = with lib.types; nullOr str;
default = null;
example = "174108912";
description = ''
Hetzner image/snapshot id for ephemeral VMs (MicroOS base from
gitea-runners-build-microos-snapshots). Controller refuses VM
creation while null.
'';
};
armImageId = lib.mkOption {
type = with lib.types; nullOr str;
default = null;
example = "423979717";
description = ''
Hetzner ARM image/snapshot id for ephemeral VMs. Required for labels
whose fallback chain includes ARM server types.
'';
};
nixImageId = lib.mkOption {
type = with lib.types; nullOr str;
default = null;
example = "161547269";
description = "Hetzner Ubuntu image id used by Nix-capable x86 runners.";
};
armNixImageId = lib.mkOption {
type = with lib.types; nullOr str;
default = null;
example = "161547270";
description = "Hetzner Ubuntu image id used by Nix-capable ARM runners.";
};
actRunnerVersion = lib.mkOption {
type = lib.types.str;
default = "1.0.6";
description = "gitea-runner release version downloaded at VM bootstrap.";
};
actRunnerSha256 = lib.mkOption {
type = lib.types.str;
default = "d78ac11deed6580a2d88c1ef72c522aa7e2986d2d22b0d80edbee577b8f79b20";
description = "sha256 of the pinned gitea-runner linux-amd64 binary, verified at bootstrap.";
};
nixVersion = lib.mkOption {
type = lib.types.str;
default = "2.35.0";
description = "Nix release installed from the official static tarball at bootstrap.";
};
nixTarballSha256 = lib.mkOption {
type = lib.types.str;
default = "e828c574555f235f2ca47c4a1432f8a07905d5cf59f087e9581be56c238818db";
description = "sha256 of the pinned Nix x86_64-linux tarball, verified at bootstrap.";
};
armNixTarballSha256 = lib.mkOption {
type = lib.types.str;
default = "1916bd42cfd4a65d5642a4ca75be4fe55db0a67e5fa16e18808fb5b6d2365bf8";
description = "sha256 of the pinned Nix aarch64-linux tarball, verified at bootstrap.";
};
debugSshPublicKey = lib.mkOption {
type = with lib.types; nullOr str;
default = null;
description = ''
Injected into every ephemeral VM (project ssh-key "yukkop@nixos"
carries the matching public key; this value is informational and
used by gcr_bootstrap_script documentation).
'';
};
hcloudSshKeyId = lib.mkOption {
type = lib.types.nullOr lib.types.ints.positive;
default = null;
description = "Hetzner project SSH key ID injected into ephemeral VMs at creation.";
};
bootstrapSshPrivateKeyFile = lib.mkOption {
type = lib.types.path;
description = ''
Path (sops-rendered) to the SSH private key the controller uses to
push bootstrap into ephemeral VMs. Public half must be registered
as Hetzner project ssh-key "yukkop@nixos".
'';
};
};
};
config = lib.mkIf cfg.enable {
assertions = [
{
assertion = cfg.imageId != null;
message = "gitea-runner-controller: imageId must be set to a MicroOS snapshot id before enabling";
}
];
sops.secrets = controllerSecrets;
systemd.services.gitea-runner-controller = {
description = "Gitea ephemeral runner controller — reconcile loop";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
serviceConfig = {
Type = "simple";
ExecStart = "${self.packages.${system}.gitea-runner-controller}/bin/gitea-runner-controller";
Restart = "always";
RestartSec = "5s";
StateDirectory = "gitea-runner-controller";
NoNewPrivileges = true;
ProtectSystem = "strict";
ProtectHome = true;
PrivateTmp = true;
StandardOutput = "journal";
StandardError = "journal";
Environment = commonEnvironment;
};
};
systemd.services.gitea-runner-webhook = {
description = "Gitea ephemeral runner webhook receiver";
after = [
"network.target"
"gitea-runner-controller.service"
];
wantedBy = [ "multi-user.target" ];
partOf = [ "gitea-runner-controller.service" ];
serviceConfig = {
Type = "simple";
ExecStart = "${self.packages.${system}.gitea-runner-controller}/bin/gitea-runner-webhook";
Restart = "always";
RestartSec = "2s";
StateDirectory = "gitea-runner-controller";
NoNewPrivileges = true;
ProtectSystem = "strict";
ProtectHome = true;
PrivateTmp = true;
StandardOutput = "journal";
StandardError = "journal";
Environment = commonEnvironment ++ [
"GCR_LISTEN_ADDR=${cfg.listenAddr}"
"GCR_LISTEN_PORT=${toString cfg.listenPort}"
];
};
};
services.nginx.virtualHosts."${cfg.webhookHost}" = {
enableACME = true;
forceSSL = true;
locations."/" = {
extraConfig = ''
proxy_pass http://${cfg.listenAddr}:${toString cfg.listenPort};
proxy_read_timeout 30s;
'';
};
};
};
}
-168
View File
@@ -1,168 +0,0 @@
{ ... }:
{
lib,
config,
...
}:
let
cfg = config.hectic.services.immich;
in
{
options.hectic.services.immich = {
enable = lib.mkEnableOption "Immich self-hosted photo and video service";
domain = lib.mkOption {
type = lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9.-]*";
description = "Public hostname used to reach Immich.";
};
mediaLocation = lib.mkOption {
type = lib.types.path;
default = "/var/lib/immich";
description = ''
Local filesystem path used for Immich media. Upstream Immich does not
support S3 as its media backend; use a local disk or block volume here.
'';
};
maxUploadSize = lib.mkOption {
type = lib.types.strMatching "[1-9][0-9]*[KMG]?";
default = "10G";
description = "Maximum request body accepted by nginx in front of Immich.";
};
secretsFile = lib.mkOption {
type = lib.types.nullOr (lib.types.strMatching "/[^[:space:]]+");
default = null;
description = ''
SOPS-backed environment file passed to Immich. Use this for secrets
such as DB_PASSWORD; never put secret values in Nix configuration.
'';
};
machineLearning = {
enable = lib.mkOption {
type = lib.types.bool;
default = true;
description = "Whether to enable Immich machine-learning features.";
};
};
accelerationDevices = lib.mkOption {
type = lib.types.nullOr (lib.types.listOf lib.types.str);
default = [ ];
description = "Device paths exposed to Immich for hardware acceleration.";
};
storageBox = {
enable = lib.mkEnableOption "Hetzner Storage Box media storage";
host = lib.mkOption {
type = lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9.-]*";
default = "u666713-sub1.your-storagebox.de";
description = "Hetzner Storage Box SMB hostname.";
};
username = lib.mkOption {
type = lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9_-]*";
default = "u666713-sub1";
description = "Storage Box SMB username.";
};
share = lib.mkOption {
type = lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9_-]*";
default = "u666713-sub1";
description = "SMB share exported by Storage Box.";
};
subdirectory = lib.mkOption {
type = lib.types.nullOr (lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9_./-]*");
default = null;
description = "Directory within the SMB share used by Immich.";
};
credentialsFile = lib.mkOption {
type = lib.types.nullOr (lib.types.strMatching "/[^[:space:]]+");
default = null;
description = ''
Runtime file containing the SMB password. Keep this in a SOPS
secret, outside the Nix store.
'';
};
};
};
config = lib.mkIf cfg.enable {
assertions = [
{
assertion = cfg.secretsFile == null || !lib.hasPrefix "/nix/store/" cfg.secretsFile;
message = "hectic.services.immich.secretsFile must reference a runtime secret path, not /nix/store.";
}
{
assertion = !cfg.storageBox.enable || cfg.storageBox.credentialsFile != null;
message = "hectic.services.immich.storageBox.credentialsFile is required when Storage Box is enabled.";
}
{
assertion =
!cfg.storageBox.enable
|| cfg.storageBox.credentialsFile == null
|| !lib.hasPrefix "/nix/store/" cfg.storageBox.credentialsFile;
message = "hectic.services.immich.storageBox.credentialsFile must reference a runtime secret path, not /nix/store.";
}
];
services.immich = {
enable = true;
host = "127.0.0.1";
mediaLocation = cfg.mediaLocation;
secretsFile = cfg.secretsFile;
accelerationDevices = cfg.accelerationDevices;
machine-learning.enable = cfg.machineLearning.enable;
settings.server.externalDomain = "https://${cfg.domain}";
};
services.nginx = {
enable = true;
virtualHosts.${cfg.domain} = {
enableACME = true;
forceSSL = true;
extraConfig = lib.mkForce ''
client_max_body_size ${cfg.maxUploadSize};
'';
locations."/" = {
proxyPass = "http://127.0.0.1:${toString config.services.immich.port}";
proxyWebsockets = true;
extraConfig = ''
proxy_read_timeout 600s;
proxy_send_timeout 600s;
'';
};
};
};
fileSystems.${toString cfg.mediaLocation} = lib.mkIf cfg.storageBox.enable {
device = "//${cfg.storageBox.host}/${cfg.storageBox.share}";
fsType = "cifs";
options = [
"_netdev"
"nofail"
"x-systemd.mount-timeout=60s"
"vers=3.1.1"
"seal"
"cache=none"
"credentials=${cfg.storageBox.credentialsFile}"
"username=${cfg.storageBox.username}"
"uid=${config.services.immich.user}"
"gid=${config.services.immich.group}"
"file_mode=0660"
"dir_mode=0770"
] ++ lib.optional (cfg.storageBox.subdirectory != null)
"prefixpath=${cfg.storageBox.subdirectory}";
};
systemd.services.immich-server.unitConfig.RequiresMountsFor = lib.mkIf cfg.storageBox.enable [
cfg.mediaLocation
];
systemd.services.immich-server.serviceConfig.Restart = lib.mkForce "always";
};
}
@@ -1,7 +1,9 @@
{
inputs,
...
}: {
flake,
self,
}:
{
lib,
config,
...
@@ -13,10 +15,6 @@
value = input.${key};
}) (builtins.attrNames input));
in {
imports = [
inputs.nixos-mailserver.nixosModules.mailserver
];
options = {
services.mailserver.enable = lib.mkEnableOption "Mail server";
@@ -25,7 +23,7 @@ in {
description = "The domain name of the mail server";
};
services.mailserver.accounts = lib.mkOption {
services.mailserver.loginAccounts = lib.mkOption {
type = lib.types.attrsOf (lib.types.submodule {
options = {
hashedPassword = lib.mkOption {
@@ -53,9 +51,9 @@ in {
fqdn = "mail." + cfg.domain;
domains = [ cfg.domain ];
accounts = transformLoginAccounts cfg.domain cfg.accounts;
loginAccounts = transformLoginAccounts cfg.domain cfg.loginAccounts;
x509.useACMEHost = "mail." + cfg.domain;
certificateScheme = "acme-nginx";
};
services.postfix.settings.main = {
-356
View File
@@ -1,356 +0,0 @@
{ ... }:
{
pkgs,
lib,
config,
...
}: let
cfg = config.hectic.services.p4d;
boolString = value: if value then "1" else "0";
serviceUser = cfg.user;
serviceGroup = cfg.group;
packageExe = if cfg.package != null then "${cfg.package}/bin/p4d" else "/run/current-system/sw/bin/false";
clientExe = if cfg.clientPackage != null then "${cfg.clientPackage}/bin/p4" else "/run/current-system/sw/bin/false";
journalFile = "${cfg.journalDir}/journal";
logFile = "${cfg.dataDir}/logs/p4d.log";
sslPort = if cfg.ssl.enable then "ssl:${cfg.listenAddress}:${toString cfg.port}" else "${cfg.listenAddress}:${toString cfg.port}";
bootstrapPort = "${cfg.bootstrap.listenAddress}:${toString cfg.bootstrap.port}";
typemapLines = [
"binary+l //....uasset"
"binary+l //....umap"
"binary+l //....upk"
"binary+l //....udk"
"binary+l //....ubulk"
"binary+l //....uexp"
"binary+l //....utoc"
"binary+l //....ucas"
"binary+w //....exe"
"binary+w //....dll"
"binary+w //....lib"
"binary+w //....app"
"binary+w //....dylib"
"binary+w //....stub"
"binary+w //....ipa"
"binary+w //....pdb"
] ++ cfg.typemap.extraLines;
typemapSpec = pkgs.writeText "p4d-unreal-typemap.txt" (
lib.concatStringsSep "\n" ([ "Typemap:" ] ++ map (line: "\t${line}") typemapLines) + "\n"
);
mainArgs = [
"-r" cfg.dataDir
"-p" sslPort
"-J" journalFile
"-L" logFile
] ++ lib.optional (!cfg.caseSensitive) "-C1";
bootstrapArgs = [
"-r" cfg.dataDir
"-p" bootstrapPort
"-J" journalFile
"-L" "${cfg.dataDir}/logs/bootstrap.log"
] ++ lib.optional (!cfg.caseSensitive) "-C1";
initScript = ''
set -eu
export P4ROOT=${lib.escapeShellArg cfg.dataDir}
export P4JOURNAL=${lib.escapeShellArg journalFile}
export P4SSLDIR=${lib.escapeShellArg cfg.ssl.dir}
marker_file="$P4ROOT/.hectic-p4d-initialized"
typemap_target="$P4ROOT/unreal-engine.typemap"
server_id_file="$P4ROOT/server.id"
${pkgs.coreutils}/bin/install -d -m 0750 "$P4ROOT"
${pkgs.coreutils}/bin/install -d -m 0750 ${lib.escapeShellArg cfg.journalDir}
${pkgs.coreutils}/bin/install -d -m 0750 ${lib.escapeShellArg cfg.checkpointDir}
${pkgs.coreutils}/bin/install -d -m 0750 "$P4ROOT/logs"
${pkgs.coreutils}/bin/install -d -m 0700 ${lib.escapeShellArg cfg.ssl.dir}
if [ ! -f "$server_id_file" ]; then
umask 077
${pkgs.coreutils}/bin/printf '%s\n' ${lib.escapeShellArg cfg.serverId} > "$server_id_file"
fi
if [ "${boolString cfg.typemap.enable}" = "1" ]; then
${pkgs.coreutils}/bin/install -m 0640 ${lib.escapeShellArg typemapSpec} "$typemap_target"
fi
if [ "${boolString cfg.ssl.enable}" = "1" ] && {
[ ! -f "$P4SSLDIR/privatekey.txt" ] || [ ! -f "$P4SSLDIR/certificate.txt" ];
}; then
${packageExe} -r "$P4ROOT" -Gc
fi
if [ ! -f "$marker_file" ] && [ "${boolString cfg.unicode}" = "1" ] && [ ! -e "$P4ROOT/db.counters" ]; then
${packageExe} ${lib.escapeShellArgs ([ "-r" cfg.dataDir ] ++ lib.optional (!cfg.caseSensitive) "-C1" ++ [ "-xi" ])}
fi
if [ ! -f "$marker_file" ] && [ "${boolString cfg.bootstrap.enable}" = "1" ]; then
temp_pid_file="$P4ROOT/bootstrap.pid"
cleanup() {
if [ -f "$temp_pid_file" ]; then
pid=$(cat "$temp_pid_file")
kill "$pid" 2>/dev/null || true
wait "$pid" 2>/dev/null || true
rm -f "$temp_pid_file"
fi
}
trap cleanup EXIT INT TERM
${packageExe} ${lib.escapeShellArgs bootstrapArgs} &
pid=$!
${pkgs.coreutils}/bin/printf '%s\n' "$pid" > "$temp_pid_file"
ready=0
tries=0
while [ "$tries" -lt 30 ]; do
if ${clientExe} -p ${lib.escapeShellArg bootstrapPort} info >/dev/null 2>&1; then
ready=1
break
fi
tries=$((tries + 1))
sleep 1
done
if [ "$ready" -ne 1 ]; then
printf 'p4d bootstrap server failed to become ready on %s\n' ${lib.escapeShellArg bootstrapPort} >&2
exit 1
fi
${lib.optionalString (cfg.securityLevel != null) ''
${clientExe} -p ${lib.escapeShellArg bootstrapPort} configure set security=${toString cfg.securityLevel}
''}
if [ "${boolString cfg.typemap.enable}" = "1" ]; then
${clientExe} -p ${lib.escapeShellArg bootstrapPort} typemap -i < "$typemap_target"
fi
${clientExe} -p ${lib.escapeShellArg bootstrapPort} admin stop || true
wait "$pid" 2>/dev/null || true
rm -f "$temp_pid_file"
trap - EXIT INT TERM
fi
if [ ! -f "$marker_file" ]; then
: > "$marker_file"
fi
'';
in {
options.hectic.services.p4d = {
enable = lib.mkEnableOption "Perforce Helix Core p4d server";
package = lib.mkOption {
type = with lib.types; nullOr package;
default = null;
defaultText = lib.literalExpression "pkgs.p4d";
description = ''
Package providing the `p4d` executable. Left null by default because
nixpkgs marks Perforce packages unfree.
'';
};
clientPackage = lib.mkOption {
type = with lib.types; nullOr package;
default = null;
defaultText = lib.literalExpression "pkgs.p4";
description = ''
Package providing the `p4` client executable used for optional local
bootstrap tasks like typemap installation and security configuration.
'';
};
user = lib.mkOption {
type = lib.types.str;
default = "p4d";
description = "System user running the p4d service.";
};
group = lib.mkOption {
type = lib.types.str;
default = "p4d";
description = "System group running the p4d service.";
};
dataDir = lib.mkOption {
type = lib.types.str;
default = "/var/lib/p4d";
description = "Persistent P4ROOT directory for metadata and archives.";
};
journalDir = lib.mkOption {
type = lib.types.str;
default = "/var/lib/p4d/journal";
description = "Directory storing the live journal file.";
};
checkpointDir = lib.mkOption {
type = lib.types.str;
default = "/var/lib/p4d/checkpoints";
description = "Directory reserved for checkpoints and offline backups.";
};
listenAddress = lib.mkOption {
type = lib.types.str;
default = "0.0.0.0";
description = "Address p4d listens on for normal client traffic.";
};
port = lib.mkOption {
type = lib.types.port;
default = 1666;
description = "TCP port exposed by p4d.";
};
openFirewall = lib.mkOption {
type = lib.types.bool;
default = false;
description = "Whether to open the p4d TCP port in the firewall.";
};
serverId = lib.mkOption {
type = lib.types.str;
default = "master";
description = "Perforce server identifier written to P4ROOT/server.id.";
};
unicode = lib.mkOption {
type = lib.types.bool;
default = true;
description = "Initialize Unicode mode on first boot. Irreversible after init.";
};
caseSensitive = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Whether the server remains case-sensitive. Linux default stays true.
Set false only when tooling requires case-insensitive behavior.
'';
};
securityLevel = lib.mkOption {
type = with lib.types; nullOr (ints.between 0 5);
default = 4;
description = ''
Optional `p4 configure set security=<level>` value applied during local
bootstrap. Set null to skip automatic security tuning.
'';
};
ssl = {
enable = lib.mkOption {
type = lib.types.bool;
default = true;
description = "Whether p4d listens with SSL enabled.";
};
dir = lib.mkOption {
type = lib.types.str;
default = "/var/lib/p4d/ssl";
description = "Directory holding p4d SSL certificate and key material.";
};
};
bootstrap = {
enable = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Run one-time local bootstrap tasks on first start: optional security
level configuration and Unreal typemap installation.
'';
};
listenAddress = lib.mkOption {
type = lib.types.str;
default = "127.0.0.1";
description = "Loopback address used by the local temporary bootstrap server.";
};
port = lib.mkOption {
type = lib.types.port;
default = 1667;
description = "Loopback-only port used by the temporary bootstrap server.";
};
};
typemap = {
enable = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Generate the Unreal-focused typemap spec and optionally install it
during bootstrap.
'';
};
extraLines = lib.mkOption {
type = with lib.types; listOf str;
default = [ ];
description = "Extra lines appended to the generated Perforce typemap spec.";
};
};
};
config = lib.mkIf cfg.enable {
assertions = [
{
assertion = cfg.package != null;
message = "hectic.services.p4d.package must be set, for example pkgs.p4d.";
}
{
assertion = !cfg.bootstrap.enable || cfg.clientPackage != null;
message = "hectic.services.p4d.clientPackage must be set when bootstrap.enable is true.";
}
];
users.groups.${serviceGroup} = { };
users.users.${serviceUser} = {
isSystemUser = true;
group = serviceGroup;
home = cfg.dataDir;
createHome = true;
};
systemd.tmpfiles.rules = [
"d ${cfg.dataDir} 0750 ${serviceUser} ${serviceGroup} - -"
"d ${cfg.journalDir} 0750 ${serviceUser} ${serviceGroup} - -"
"d ${cfg.checkpointDir} 0750 ${serviceUser} ${serviceGroup} - -"
"d ${cfg.dataDir}/logs 0750 ${serviceUser} ${serviceGroup} - -"
"d ${cfg.ssl.dir} 0700 ${serviceUser} ${serviceGroup} - -"
];
systemd.services.p4d = {
description = "Perforce Helix Core p4d server";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
preStart = initScript;
serviceConfig = {
Type = "simple";
User = serviceUser;
Group = serviceGroup;
WorkingDirectory = cfg.dataDir;
Environment = lib.mkIf cfg.ssl.enable "P4SSLDIR=${cfg.ssl.dir}";
ExecStart = "${packageExe} ${lib.escapeShellArgs mainArgs}";
Restart = "on-failure";
RestartSec = "5s";
TimeoutStopSec = "30s";
KillSignal = "SIGTERM";
KillMode = "mixed";
UMask = "0077";
};
};
networking.firewall.allowedTCPPorts = lib.mkIf cfg.openFirewall [ cfg.port ];
};
}
@@ -1,576 +0,0 @@
{ ... }:
{
pkgs,
lib,
config,
...
}: let
cfg = config.hectic.services."project-zomboid";
serverProperties = cfg.serverProperties // {
DefaultPort = cfg.port;
UDPPort = cfg.udpPort;
WorkshopItems = lib.concatStringsSep ";" cfg.workshopItems;
Mods = lib.concatStringsSep ";" cfg.mods;
};
configLines = lib.mapAttrsToList (
name: value:
"${name}=${if builtins.isBool value then lib.boolToString value else toString value}"
) serverProperties;
sandboxValueType = lib.types.oneOf [
lib.types.bool
lib.types.int
lib.types.float
lib.types.str
(lib.types.attrsOf sandboxValueType)
];
luaValue = value:
if builtins.isBool value then
lib.boolToString value
else if builtins.isInt value || builtins.isFloat value then
toString value
else if builtins.isAttrs value then
"{ ${lib.concatStringsSep " " (lib.mapAttrsToList (name: child: "[${luaValue name}] = ${luaValue child},") value)} }"
else
"\"${lib.replaceStrings [ "\\" "\"" "\n" "\r" ] [ "\\\\" "\\\"" "\\n" "\\r" ] value}\"";
sandboxConfigLines = lib.mapAttrsToList (
name: value: "[${luaValue name}] = ${luaValue value},"
) cfg.sandboxProperties;
zomboidDir = "${cfg.dataDir}/Zomboid";
adminPasswordFile = "${cfg.dataDir}/admin-password";
rconPasswordFile = cfg.rcon.passwordFile;
backupCfg = cfg.backup;
s3CredentialsFile = if backupCfg.s3.credentialsFile == null then "" else backupCfg.s3.credentialsFile;
s3Bucket = if backupCfg.s3.bucket == null then "" else backupCfg.s3.bucket;
s3Endpoint = if backupCfg.s3.endpoint == null then "" else backupCfg.s3.endpoint;
s3Region = if backupCfg.s3.region == null then "" else backupCfg.s3.region;
timestampArchivePattern = "project-zomboid-${cfg.serverName}-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]T[0-9][0-9][0-9][0-9][0-9][0-9]Z.tar.zst";
saveDir = "${zomboidDir}/Saves/Multiplayer/${cfg.serverName}";
serverConfigDir = "${zomboidDir}/Server";
s3RetentionScript = import ../../../../lib/s3-retention.nix {inherit pkgs;};
backupScript = pkgs.writeShellScript "project-zomboid-backup" ''
set -eu
staging_dir=${lib.escapeShellArg backupCfg.stagingDir}
archive_dir=${lib.escapeShellArg backupCfg.archiveDir}
lock_file="$archive_dir/.backup.lock"
${pkgs.coreutils}/bin/install -d -m 0700 \
"$staging_dir/Zomboid/Saves/Multiplayer/${cfg.serverName}" \
"$staging_dir/Zomboid/Server" \
"$staging_dir/Zomboid/mods" \
"$archive_dir"
exec 9>"$lock_file"
if ! ${pkgs.util-linux}/bin/flock -n 9; then
${pkgs.coreutils}/bin/printf '%s\n' 'Project Zomboid backup already running; skipping.' >&2
exit 0
fi
${lib.optionalString backupCfg.s3.enable ''
if [ -z "''${AWS_ACCESS_KEY_ID:-}" ] || [ -z "''${AWS_SECRET_ACCESS_KEY:-}" ]; then
${pkgs.coreutils}/bin/printf '%s\n' \
'AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY missing from Project Zomboid S3 credentials file.' >&2
exit 1
fi
s3_bucket=${lib.escapeShellArg s3Bucket}
s3_prefix=${lib.escapeShellArg backupCfg.s3.prefix}
s3_upload() {
source=$1
key=$2
attempt=1
while [ "$attempt" -le 3 ]; do
if ${pkgs.awscli2}/bin/aws s3 cp "$source" "s3://$s3_bucket/$key" \
--endpoint-url ${lib.escapeShellArg s3Endpoint} \
--region ${lib.escapeShellArg s3Region} \
--cli-connect-timeout 30 \
--cli-read-timeout 300 \
--only-show-errors; then
return 0
fi
if [ "$attempt" -eq 3 ]; then
return 1
fi
${pkgs.coreutils}/bin/sleep 5
attempt=$((attempt + 1))
done
}
''}
${lib.optionalString (backupCfg.s3.enable && backupCfg.retentionDays == 0) ''
pending_list="$staging_dir/.pending-archives"
${pkgs.findutils}/bin/find "$archive_dir" -maxdepth 1 -type f \
-name ${lib.escapeShellArg timestampArchivePattern} \
-printf '%T@ %p\n' | ${pkgs.coreutils}/bin/sort -n > "$pending_list"
while IFS= read -r pending_line; do
pending_archive="''${pending_line#* }"
pending_name="''${pending_archive##*/}"
s3_upload "$pending_archive" "''${s3_prefix:+$s3_prefix/}$pending_name"
${pkgs.coreutils}/bin/rm -f "$pending_archive"
done < "$pending_list"
${pkgs.coreutils}/bin/rm -f "$pending_list"
''}
${lib.optionalString cfg.rcon.enable ''
rcon_password="$(${pkgs.coreutils}/bin/cat ${lib.escapeShellArg rconPasswordFile})"
if [ -z "$rcon_password" ]; then
${pkgs.coreutils}/bin/printf '%s\n' 'Project Zomboid RCON password file is empty.' >&2
exit 1
fi
${pkgs.rcon}/bin/rcon \
--host 127.0.0.1 \
--port ${toString cfg.rcon.port} \
--password "$rcon_password" \
save
${pkgs.coreutils}/bin/sleep ${toString backupCfg.saveWaitSeconds}
''}
sync_staging() {
${pkgs.rsync}/bin/rsync -a --delete \
${lib.escapeShellArg "${saveDir}/"} \
"$staging_dir/Zomboid/Saves/Multiplayer/${cfg.serverName}/"
${pkgs.rsync}/bin/rsync -a --delete \
${lib.escapeShellArg "${zomboidDir}/mods/"} \
"$staging_dir/Zomboid/mods/"
${pkgs.rsync}/bin/rsync -a --delete --delete-excluded \
--include=${lib.escapeShellArg "/${cfg.serverName}_SandboxVars.lua"} \
--include=${lib.escapeShellArg "/${cfg.serverName}_spawnpoints.lua"} \
--include=${lib.escapeShellArg "/${cfg.serverName}_spawnregions.lua"} \
--exclude='*' \
${lib.escapeShellArg "${serverConfigDir}/"} \
"$staging_dir/Zomboid/Server/"
}
# Second pass narrows, but cannot eliminate, live-save inconsistency.
sync_staging
${pkgs.coreutils}/bin/sleep 5
sync_staging
timestamp="$(${pkgs.coreutils}/bin/date -u +%Y%m%dT%H%M%SZ)"
archive_name="project-zomboid-${cfg.serverName}-$timestamp.tar.zst"
archive_tmp="$archive_dir/.$archive_name.tmp"
archive="$archive_dir/$archive_name"
trap '${pkgs.coreutils}/bin/rm -f "$archive_tmp"' EXIT
${pkgs.gnutar}/bin/tar \
--use-compress-program=${lib.escapeShellArg "${pkgs.zstd}/bin/zstd -T0"} \
-C "$staging_dir" -cf "$archive_tmp" Zomboid
${pkgs.coreutils}/bin/chmod 0600 "$archive_tmp"
${pkgs.coreutils}/bin/mv "$archive_tmp" "$archive"
trap - EXIT
${lib.optionalString backupCfg.s3.enable ''
s3_key="''${s3_prefix:+$s3_prefix/}$archive_name"
s3_upload "$archive" "$s3_key"
${lib.optionalString (backupCfg.retentionDays == 0) ''
${pkgs.coreutils}/bin/rm -f "$archive"
''}
${lib.optionalString (backupCfg.retentionDays != 0) ''
${pkgs.findutils}/bin/find "$archive_dir" -maxdepth 1 -type f \
-name ${lib.escapeShellArg timestampArchivePattern} \
-mmin +${toString (backupCfg.retentionDays * 1440)} -delete
''}
${s3RetentionScript} \
"$s3_bucket" \
${lib.escapeShellArg s3Endpoint} \
${lib.escapeShellArg s3Region} \
"$s3_prefix" \
${lib.escapeShellArg "project-zomboid-${cfg.serverName}-"} \
${toString backupCfg.s3.remoteRetentionDays} \
"$staging_dir"
''}
${lib.optionalString (!backupCfg.s3.enable) ''
if [ ${toString (if backupCfg.retentionDays == 0 then 0 else 1)} -eq 0 ]; then
${pkgs.findutils}/bin/find "$archive_dir" -maxdepth 1 -type f \
-name ${lib.escapeShellArg timestampArchivePattern} \
-delete
else
${pkgs.findutils}/bin/find "$archive_dir" -maxdepth 1 -type f \
-name ${lib.escapeShellArg timestampArchivePattern} \
-mmin +${toString (backupCfg.retentionDays * 1440)} -delete
fi
''}
'';
startScript = pkgs.writeShellScript "project-zomboid-start" ''
admin_password=$(${pkgs.coreutils}/bin/cat ${lib.escapeShellArg adminPasswordFile})
exec ${pkgs.steam-run}/bin/steam-run \
${lib.escapeShellArg "${cfg.installDir}/start-server.sh"} \
-servername ${lib.escapeShellArg cfg.serverName} \
-adminpassword "$admin_password"
'';
in {
options.hectic.services."project-zomboid" = {
enable = lib.mkEnableOption "Project Zomboid dedicated server";
serverName = lib.mkOption {
type = lib.types.strMatching "[A-Za-z0-9._-]+";
default = "servertest";
description = "Name used for Project Zomboid server and save files.";
};
dataDir = lib.mkOption {
type = lib.types.path;
default = "/var/lib/project-zomboid";
description = "Writable state directory for the server.";
};
installDir = lib.mkOption {
type = lib.types.path;
default = "/var/lib/project-zomboid/server";
description = "Directory where SteamCMD installs the dedicated server.";
};
port = lib.mkOption {
type = lib.types.port;
default = 16261;
description = "Project Zomboid UDP discovery port.";
};
udpPort = lib.mkOption {
type = lib.types.port;
default = 16262;
description = "Project Zomboid UDP game port.";
};
branch = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
description = "Steam beta branch, for example legacy41.";
};
updateOnStart = lib.mkOption {
type = lib.types.bool;
default = true;
description = "Update and validate the game through SteamCMD on startup; disable to use an existing installation.";
};
memory = lib.mkOption {
type = lib.types.strMatching "[0-9]+[mMgG]";
default = "3g";
description = "Maximum Java heap for the server, for example 3g.";
};
workshopItems = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = "Steam Workshop item IDs, downloaded and enabled by the server.";
};
mods = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = "Project Zomboid mod loading IDs from mod.info.";
};
serverProperties = lib.mkOption {
type = lib.types.attrsOf (
lib.types.oneOf [
lib.types.bool
lib.types.int
lib.types.str
]
);
default = { };
description = "Additional or overriding values for the server INI file.";
};
serverPropertiesFile = lib.mkOption {
type = lib.types.nullOr lib.types.path;
default = null;
description = "Runtime file with additional INI values, suitable for secrets.";
};
sandboxProperties = lib.mkOption {
type = lib.types.attrsOf sandboxValueType;
default = { };
description = "Values for the Project Zomboid SandboxVars.lua file.";
};
openFirewall = lib.mkOption {
type = lib.types.bool;
default = true;
description = "Open the Project Zomboid UDP ports in the firewall.";
};
rcon = {
enable = lib.mkEnableOption "local RCON for Project Zomboid automation";
port = lib.mkOption {
type = lib.types.port;
default = 27015;
description = "RCON TCP port; not opened in the firewall by this module.";
};
passwordFile = lib.mkOption {
type = lib.types.path;
default = "${cfg.dataDir}/rcon-password";
description = "Runtime file containing the generated RCON password.";
};
};
backup = {
enable = lib.mkEnableOption "no-stop Project Zomboid backups";
onCalendar = lib.mkOption {
type = lib.types.str;
default = "*:0/30";
description = "systemd calendar expression controlling backup frequency.";
};
stagingDir = lib.mkOption {
type = lib.types.path;
default = "${cfg.dataDir}/backups/staging";
description = "Local directory containing the two-pass rsync staging tree.";
};
archiveDir = lib.mkOption {
type = lib.types.path;
default = "${cfg.dataDir}/backups/archive";
description = "Local directory containing timestamped tar.zst archives.";
};
retentionDays = lib.mkOption {
type = lib.types.ints.between 0 3650;
default = 14;
description = "Delete local archives older than this many days; zero keeps no local archives.";
};
saveWaitSeconds = lib.mkOption {
type = lib.types.ints.positive;
default = 10;
description = "Seconds to wait after the RCON save command before rsync.";
};
s3 = {
enable = lib.mkEnableOption "uploading Project Zomboid backups to S3-compatible storage";
credentialsFile = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
description = ''
Runtime env file containing AWS_ACCESS_KEY_ID and
AWS_SECRET_ACCESS_KEY. Required when S3 upload is enabled.
'';
};
bucket = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
description = "S3 bucket receiving backup archives.";
};
endpoint = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
description = "S3-compatible endpoint URL.";
};
region = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
description = "S3 region passed to awscli2.";
};
prefix = lib.mkOption {
type = lib.types.str;
default = "project-zomboid";
description = "Optional object key prefix within the S3 bucket.";
};
remoteRetentionDays = lib.mkOption {
type = lib.types.ints.positive;
default = 14;
description = "Delete uploaded archives older than this many days.";
};
};
};
};
config = lib.mkIf cfg.enable {
assertions = [
{
assertion = !cfg.rcon.enable || (
lib.hasPrefix "/" cfg.rcon.passwordFile
&& !lib.hasPrefix "/nix/store/" cfg.rcon.passwordFile
);
message = "hectic.services.project-zomboid.rcon.passwordFile must be a runtime path outside /nix/store.";
}
{
assertion = !backupCfg.s3.enable || backupCfg.enable;
message = "hectic.services.project-zomboid.backup must be enabled before S3 upload.";
}
{
assertion = !backupCfg.s3.enable || backupCfg.s3.credentialsFile != null;
message = "hectic.services.project-zomboid.backup.s3.credentialsFile is required when S3 upload is enabled.";
}
{
assertion = !backupCfg.s3.enable || backupCfg.s3.bucket != null;
message = "hectic.services.project-zomboid.backup.s3.bucket is required when S3 upload is enabled.";
}
{
assertion = !backupCfg.s3.enable || backupCfg.s3.endpoint != null;
message = "hectic.services.project-zomboid.backup.s3.endpoint is required when S3 upload is enabled.";
}
{
assertion = !backupCfg.s3.enable || backupCfg.s3.region != null;
message = "hectic.services.project-zomboid.backup.s3.region is required when S3 upload is enabled.";
}
{
assertion =
!backupCfg.s3.enable
|| backupCfg.s3.credentialsFile == null
|| (
lib.hasPrefix "/" backupCfg.s3.credentialsFile
&& !lib.hasPrefix "/nix/store/" backupCfg.s3.credentialsFile
);
message = "hectic.services.project-zomboid.backup.s3.credentialsFile must be a runtime path outside /nix/store.";
}
{
assertion =
!backupCfg.s3.enable
|| backupCfg.s3.endpoint == null
|| lib.hasPrefix "https://" backupCfg.s3.endpoint;
message = "hectic.services.project-zomboid.backup.s3.endpoint must use HTTPS.";
}
];
users.groups.project-zomboid = { };
users.users.project-zomboid = {
isSystemUser = true;
group = "project-zomboid";
home = cfg.dataDir;
createHome = true;
};
systemd.tmpfiles.rules = [
"d ${cfg.dataDir} 0750 project-zomboid project-zomboid - -"
"d ${cfg.installDir} 0750 project-zomboid project-zomboid - -"
] ++ lib.optionals backupCfg.enable [
"d ${cfg.dataDir}/backups 0700 project-zomboid project-zomboid - -"
"Z ${cfg.dataDir}/backups 0700 project-zomboid project-zomboid - -"
"d ${backupCfg.stagingDir} 0700 project-zomboid project-zomboid - -"
"d ${backupCfg.archiveDir} 0700 project-zomboid project-zomboid - -"
];
systemd.services.project-zomboid = {
description = "Project Zomboid dedicated server";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
preStart = ''
${pkgs.coreutils}/bin/install -d -m 0750 \
${lib.escapeShellArg cfg.installDir}
if [ ! -s ${lib.escapeShellArg adminPasswordFile} ]; then
umask 077
${pkgs.openssl}/bin/openssl rand -base64 32 > ${lib.escapeShellArg adminPasswordFile}
fi
${lib.optionalString cfg.rcon.enable ''
if [ ! -s ${lib.escapeShellArg rconPasswordFile} ]; then
umask 077
${pkgs.openssl}/bin/openssl rand -hex 32 > ${lib.escapeShellArg rconPasswordFile}
else
rcon_password=$(${pkgs.coreutils}/bin/cat ${lib.escapeShellArg rconPasswordFile})
case "$rcon_password" in
*[!0123456789abcdefABCDEF]*)
umask 077
${pkgs.openssl}/bin/openssl rand -hex 32 > ${lib.escapeShellArg rconPasswordFile}
;;
esac
fi
${pkgs.coreutils}/bin/chown project-zomboid:project-zomboid ${lib.escapeShellArg rconPasswordFile}
${pkgs.coreutils}/bin/chmod 0600 ${lib.escapeShellArg rconPasswordFile}
''}
${if cfg.updateOnStart then ''
${pkgs.steamcmd}/bin/steamcmd \
+force_install_dir ${lib.escapeShellArg cfg.installDir} \
+login anonymous \
+app_update 380870 ${lib.optionalString (cfg.branch != null) "-beta ${lib.escapeShellArg cfg.branch}"} validate \
+quit
'' else ''
test -x ${lib.escapeShellArg "${cfg.installDir}/start-server.sh"}
test -s ${lib.escapeShellArg "${cfg.installDir}/ProjectZomboid64.json"}
''}
${pkgs.gnused}/bin/sed -i -E \
's/"-Xmx[0-9]+[mMgG]"/"-Xmx${cfg.memory}"/' \
${lib.escapeShellArg "${cfg.installDir}/ProjectZomboid64.json"}
${pkgs.coreutils}/bin/install -d -m 0750 \
${lib.escapeShellArg "${zomboidDir}/Server"}
{
${lib.concatMapStringsSep "\n " (line:
"${pkgs.coreutils}/bin/printf '%s\\n' ${lib.escapeShellArg line};"
) configLines}
${lib.optionalString (cfg.serverPropertiesFile != null)
"${pkgs.coreutils}/bin/cat ${lib.escapeShellArg cfg.serverPropertiesFile};"}
${lib.optionalString cfg.rcon.enable ''
${pkgs.coreutils}/bin/printf '%s\n' ${lib.escapeShellArg "RCONPort=${toString cfg.rcon.port}"};
${pkgs.coreutils}/bin/printf '%s' 'RCONPassword=';
${pkgs.coreutils}/bin/cat ${lib.escapeShellArg rconPasswordFile};
${pkgs.coreutils}/bin/printf '\n';
''}
} > ${lib.escapeShellArg "${zomboidDir}/Server/${cfg.serverName}.ini"}
${lib.optionalString (cfg.sandboxProperties != { }) ''
{
${pkgs.coreutils}/bin/printf '%s\n' 'SandboxVars = {';
${lib.concatMapStringsSep "\n " (line:
"${pkgs.coreutils}/bin/printf '%s\\n' ${lib.escapeShellArg line};"
) sandboxConfigLines}
${pkgs.coreutils}/bin/printf '%s\n' '};';
} > ${lib.escapeShellArg "${zomboidDir}/Server/${cfg.serverName}_SandboxVars.lua"}
''}
${lib.optionalString (cfg.sandboxProperties == { }) ''
${pkgs.coreutils}/bin/rm -f \
${lib.escapeShellArg "${zomboidDir}/Server/${cfg.serverName}_SandboxVars.lua"}
''}
'';
serviceConfig = {
User = "project-zomboid";
Group = "project-zomboid";
WorkingDirectory = cfg.dataDir;
Environment = [
"HOME=${cfg.dataDir}"
"SteamAppId=108600"
];
ExecStart = startScript;
Restart = "on-failure";
RestartSec = 5;
TimeoutStartSec = "15min";
TimeoutStopSec = 30;
UMask = "0077";
};
};
systemd.services.project-zomboid-backup = lib.mkIf backupCfg.enable {
description = "No-stop Project Zomboid backup";
after = [ "project-zomboid.service" ];
unitConfig.ConditionPathExists = [
saveDir
serverConfigDir
];
serviceConfig = {
Type = "oneshot";
User = "project-zomboid";
Group = "project-zomboid";
ExecStart = backupScript;
TimeoutStartSec = "30min";
UMask = "0077";
} // lib.optionalAttrs backupCfg.s3.enable {
EnvironmentFile = s3CredentialsFile;
};
};
systemd.timers.project-zomboid-backup = lib.mkIf backupCfg.enable {
description = "Run Project Zomboid backup";
wantedBy = [ "timers.target" ];
timerConfig = {
OnCalendar = backupCfg.onCalendar;
Persistent = true;
};
};
networking.firewall.allowedUDPPorts = lib.mkIf cfg.openFirewall [
cfg.port
cfg.udpPort
];
};
}
@@ -1,120 +0,0 @@
{
inputs,
flake,
self,
}:
{
config,
lib,
pkgs,
...
}: let
cfg = config.hectic.services.routine-server;
system = pkgs.stdenv.hostPlatform.system;
in {
options.hectic.services.routine-server = {
enable = lib.mkEnableOption "daily, weekly, and monthly routine server";
address = lib.mkOption {
type = lib.types.str;
default = "127.0.0.1";
description = "Address on which the routine server listens.";
};
port = lib.mkOption {
type = lib.types.port;
default = 8090;
description = "Port on which the routine server listens.";
};
generationDays = lib.mkOption {
type = lib.types.ints.unsigned;
default = 62;
description = "Number of future routine days to materialize.";
};
databaseName = lib.mkOption {
type = lib.types.str;
default = "routine-server";
description = "PostgreSQL database used by the routine server.";
};
databaseUser = lib.mkOption {
type = lib.types.str;
default = "routine-server";
description = "PostgreSQL and dynamic system user used by the routine server.";
};
databaseSocket = lib.mkOption {
type = lib.types.path;
default = "/run/postgresql";
description = "PostgreSQL Unix socket directory.";
};
timezone = lib.mkOption {
type = lib.types.str;
default = "UTC";
description = "Timezone used for dates and reminder times.";
};
environmentFile = lib.mkOption {
type = with lib.types; nullOr path;
default = null;
description = ''
Optional secret environment file. Supported variables:
ROUTINE_API_TOKEN=
ROUTINE_TELEGRAM_BOT_TOKEN=
ROUTINE_TELEGRAM_CHAT_ID=
'';
};
};
config = lib.mkIf cfg.enable {
services.postgresql = {
enable = true;
ensureDatabases = [ cfg.databaseName ];
ensureUsers = [
{
name = cfg.databaseUser;
ensureDBOwnership = true;
}
];
};
systemd.services.routine-server = {
description = "Personal routine task server";
after = [ "network-online.target" "postgresql.service" ];
wants = [ "network-online.target" ];
requires = [ "postgresql.service" ];
wantedBy = [ "multi-user.target" ];
environment = {
ROUTINE_BIND = "${cfg.address}:${toString cfg.port}";
ROUTINE_DATABASE_URL = "host=${cfg.databaseSocket} dbname=${cfg.databaseName} user=${cfg.databaseUser}";
ROUTINE_GENERATION_DAYS = toString cfg.generationDays;
TZ = cfg.timezone;
};
serviceConfig = lib.mkMerge [
{
Type = "simple";
ExecStart = "${self.packages.${system}.routine-server}/bin/routine-server";
Restart = "on-failure";
RestartSec = "5s";
DynamicUser = true;
User = cfg.databaseUser;
Group = cfg.databaseUser;
UMask = "0077";
NoNewPrivileges = true;
PrivateTmp = true;
ProtectHome = true;
ProtectSystem = "strict";
RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" ];
}
(lib.mkIf (cfg.environmentFile != null) {
EnvironmentFile = cfg.environmentFile;
})
];
};
};
}
@@ -1,153 +0,0 @@
{ ... }: {
pkgs,
lib,
config,
...
}: let
cfg = config.hectic.services.stable-video-diffusion;
in {
options.hectic.services.stable-video-diffusion = {
enable = lib.mkEnableOption "local Stable Video Diffusion HTTP API";
host = lib.mkOption {
type = lib.types.str;
default = "127.0.0.1";
description = "Address the Stable Video Diffusion API binds to.";
};
port = lib.mkOption {
type = lib.types.port;
default = 7861;
description = "Port the Stable Video Diffusion API binds to.";
};
package = lib.mkOption {
type = lib.types.package;
default = pkgs.hectic.stable-video-diffusion-api;
defaultText = lib.literalExpression "pkgs.hectic.stable-video-diffusion-api";
description = "Package providing the Stable Video Diffusion API executable.";
};
modelId = lib.mkOption {
type = lib.types.str;
default = "stabilityai/stable-video-diffusion-img2vid-xt";
description = "Model identifier loaded by the Stable Video Diffusion API.";
};
device = lib.mkOption {
type = with lib.types; nullOr (enum [ "cpu" "cuda" ]);
default = null;
description = ''
Torch device requested from the Stable Video Diffusion API. When null,
the package keeps its own auto-detection behavior.
'';
};
libraryPath = lib.mkOption {
type = with lib.types; listOf str;
default = [];
description = ''
Runtime library paths added to LD_LIBRARY_PATH. CUDA/NVIDIA deployments
should include /run/opengl-driver/lib so libcuda.so is visible to torch.
'';
};
stateDir = lib.mkOption {
type = lib.types.str;
default = "/var/lib/stable-video-diffusion-api";
description = "Persistent state directory for the Stable Video Diffusion API.";
};
cacheDir = lib.mkOption {
type = lib.types.str;
default = "/var/cache/stable-video-diffusion-api";
description = "Cache directory for downloaded model and runtime artifacts.";
};
outputDir = lib.mkOption {
type = lib.types.str;
default = "${cfg.stateDir}/outputs";
defaultText = lib.literalExpression ''"\${config.hectic.services.stable-video-diffusion.stateDir}/outputs"'';
description = "Directory where generated video outputs are written.";
};
environmentFile = lib.mkOption {
type = with lib.types; nullOr path;
default = null;
description = ''
Optional environment file for secrets or runtime overrides. Values from
the unit environment define SVD_API_HOST, SVD_API_PORT, SVD_MODEL_ID,
SVD_STATE_DIR, SVD_CACHE_DIR, SVD_OUTPUT_DIR, and optionally SVD_DEVICE
and LD_LIBRARY_PATH by default.
'';
};
openFirewall = lib.mkOption {
type = lib.types.bool;
default = false;
description = "Whether to open the API port in the firewall.";
};
};
config = lib.mkIf cfg.enable {
assertions = [
{
assertion = cfg.device != "cuda" || cfg.libraryPath != [];
message = "hectic.services.stable-video-diffusion.libraryPath must include the NVIDIA runtime library path when device is cuda.";
}
];
users.users.stable-video-diffusion = {
isSystemUser = true;
group = "stable-video-diffusion";
};
users.groups.stable-video-diffusion = {};
systemd.tmpfiles.rules = [
"d ${cfg.stateDir} 0750 stable-video-diffusion stable-video-diffusion -"
"d ${cfg.cacheDir} 0750 stable-video-diffusion stable-video-diffusion -"
"d ${cfg.outputDir} 0750 stable-video-diffusion stable-video-diffusion -"
];
systemd.services.stable-video-diffusion-api = {
description = "Stable Video Diffusion HTTP API";
after = [ "network.target" ];
wantedBy = [ "multi-user.target" ];
environment = {
SVD_API_HOST = cfg.host;
SVD_API_PORT = toString cfg.port;
SVD_MODEL_ID = cfg.modelId;
SVD_STATE_DIR = cfg.stateDir;
SVD_CACHE_DIR = cfg.cacheDir;
SVD_OUTPUT_DIR = cfg.outputDir;
}
// lib.optionalAttrs (cfg.device != null) {
SVD_DEVICE = cfg.device;
}
// lib.optionalAttrs (cfg.libraryPath != []) {
LD_LIBRARY_PATH = lib.concatStringsSep ":" cfg.libraryPath;
};
serviceConfig = lib.mkMerge [
{
Type = "simple";
User = "stable-video-diffusion";
Group = "stable-video-diffusion";
WorkingDirectory = cfg.stateDir;
ExecStart = lib.getExe' cfg.package "stable-video-diffusion-api";
Restart = "on-failure";
RestartSec = "5s";
TimeoutStopSec = "30s";
KillSignal = "SIGTERM";
KillMode = "mixed";
StandardOutput = "journal";
StandardError = "journal";
}
(lib.mkIf (cfg.environmentFile != null) {
EnvironmentFile = cfg.environmentFile;
})
];
};
networking.firewall.allowedTCPPorts = lib.mkIf cfg.openFirewall [ cfg.port ];
};
}
@@ -0,0 +1,230 @@
# Matrix Cluster Failover Runbook (`accord.tube`)
Primary: `hectic-lab` (NL, `128.140.75.58`)
Standby: `bfs.poland.xray` (PL, `91.198.166.181`)
Module: `hectic.generic.matrix-cluster` (`nixos/module/generic/matrix-cluster.nix`).
Shared secrets: `sus/matrix-cluster.yaml`.
All `psql` and `pg_ctl` invocations use PostgreSQL **17** at data dir
`/var/lib/postgresql/17`.
## Initial setup
### 1. Provision shared SOPS file (`sus/matrix-cluster.yaml`)
On a workstation with both yukkop and yukkop-alt age keys available:
```sh
sudo cat /var/lib/matrix-synapse/homeserver.signing.key # on NL (hectic-lab)
# Copy the single line value into the buffer for the next step.
sops sus/matrix-cluster.yaml
```
Populate the editor with:
```yaml
matrix:
signing-key: <paste verbatim signing-key line from NL>
postgres-replication-password: <openssl rand -base64 32>
object-storage:
credentials: |
ACCESS_KEY_ID=<verbatim copy from sus/hectic-lab.yaml>
SECRET_ACCESS_KEY=<verbatim copy from sus/hectic-lab.yaml>
porkbun-api-key: <PORKBUN_API_KEY>
porkbun-secret-api-key: <PORKBUN_SECRET_API_KEY>
```
Verify recipients:
```sh
sops updatekeys sus/matrix-cluster.yaml
sops -d sus/matrix-cluster.yaml | grep -E 'signing-key|porkbun-api-key|object-storage'
```
Expected: all five keys present, exit 0.
### 2. Deploy NL primary first
```sh
nixos-rebuild switch --flake .#'hectic-lab|x86_64-linux' --target-host root@128.140.75.58
```
Verify on NL:
```sh
sudo systemctl status matrix-synapse postgresql matrix-cluster-replication-password
sudo -u postgres psql -c "select rolname, rolreplication from pg_roles where rolname='replication';"
# Expected: replication | t
```
### 3. Seed PL replica with `pg_basebackup`
On PL:
```sh
sudo systemctl stop postgresql
sudo rm -rf /var/lib/postgresql/17
sudo -u postgres install -d -m 0700 /var/lib/postgresql/17
sudo -u postgres PGPASSWORD="$(sudo cat /run/secrets/matrix/postgres-replication-password)" \
pg_basebackup \
-h 128.140.75.58 \
-p 5432 \
-U replication \
-D /var/lib/postgresql/17 \
-Fp -Xs -P -R \
--no-password
```
`-R` writes `standby.signal` and an initial `primary_conninfo`. The
matrix-cluster module's `matrix-cluster-standby-bootstrap` service will
overwrite `primary_conninfo` to use a libpq passfile on next boot.
### 4. Deploy PL standby
```sh
nixos-rebuild switch --flake .#'bfs.poland.xray|x86_64-linux' --target-host root@91.198.166.181
sudo systemctl start postgresql
```
Verify streaming on NL:
```sh
sudo -u postgres psql -c 'select client_addr, state, sync_state from pg_stat_replication;'
# Expected: 91.198.166.181 | streaming | async
```
Verify standby on PL:
```sh
sudo -u postgres psql -c 'select pg_is_in_recovery();'
# Expected: t
sudo systemctl is-active matrix-synapse
# Expected: inactive (standby keeps Synapse off)
```
### 5. Remove duplicate S3 credentials from `sus/hectic-lab.yaml`
Only AFTER NL is confirmed healthy reading from the new shared file:
```sh
sops sus/hectic-lab.yaml
# Delete the matrix/object-storage/credentials block.
sudo nixos-rebuild switch --flake .#'hectic-lab|x86_64-linux'
```
## Normal operations
```sh
# NL: replication health
sudo -u postgres psql -c 'select * from pg_stat_replication;'
# Expected: 1 row, state=streaming, sync_state=async
# PL: replay status
sudo -u postgres psql -c 'select now() - pg_last_xact_replay_timestamp() as lag;'
# Both: cert renewal
sudo systemctl status acme-accord.tube.timer
sudo journalctl -u acme-accord.tube.service --since '24 hours ago'
# Synapse health (NL primary)
curl -sf https://accord.tube/_matrix/client/versions | head
```
## Planned failover (NL -> PL)
```sh
# 1. Drain NL: stop accepting writes.
sudo systemctl stop matrix-synapse
sudo systemctl stop postgresql # ensure no new WAL after this point
# 2. Promote PL replica.
sudo -u postgres pg_ctl -D /var/lib/postgresql/17 promote
# Wait until pg_is_in_recovery() returns f:
sudo -u postgres psql -c 'select pg_is_in_recovery();'
# 3. Make the role switch declarative before rebuilding.
# Edit the flake so rebuilds match the promoted database state:
# - nixos/system/bfs.poland.xray/bfs.poland.xray.nix:
# hectic.generic.matrix-cluster.role = "primary";
# hectic.generic.matrix-cluster.overrideEnableSynapse = true;
# hectic.generic.matrix-cluster.secretsFile = config.sops.secrets."matrix/secrets".path;
# - nixos/system/hectic-lab/hectic-lab.nix:
# hectic.generic.matrix-cluster.role = "standby";
# hectic.generic.matrix-cluster.overrideEnableSynapse = false;
# hectic.generic.matrix-cluster.replication.peerHost = "91.198.166.181";
# hectic.generic.matrix-cluster.replication.allowedSourceIPs = [ "128.140.75.58/32" ];
# (You will also need a matrix/secrets entry on PL - copy from NL via SOPS.)
sudo nixos-rebuild switch --flake .#'bfs.poland.xray|x86_64-linux'
sudo nixos-rebuild switch --flake .#'hectic-lab|x86_64-linux'
sudo systemctl status matrix-synapse
# 4. Swap DNS A record at Porkbun:
# accord.tube A 91.198.166.181 (was 128.140.75.58)
# TTL: set to 300 in advance of any planned failover.
# Porkbun UI: https://porkbun.com/account/domainsSpeedy -> accord.tube -> DNS -> edit A record.
# Or via API:
sudo curl -sX POST https://api.porkbun.com/api/json/v3/dns/editByNameType/accord.tube/A \
-H 'content-type: application/json' \
-d "$(jq -n --arg k "$PORKBUN_API_KEY" --arg s "$PORKBUN_SECRET_API_KEY" \
'{secretapikey:$s,apikey:$k,content:"91.198.166.181",ttl:"300"}')"
# 5. Federation smoke test.
curl -s 'https://federationtester.matrix.org/api/report?server_name=accord.tube' | jq .FederationOK
# Expected: true
```
Expected after the rebuilds:
- `bfs.poland.xray` evaluates and runs as `role = "primary"`.
- `hectic-lab` evaluates as `role = "standby"` with Synapse forced off.
- Future `nixos-rebuild` runs preserve the promoted topology instead of reapplying standby settings to PL.
## Failback (PL -> NL)
```sh
# 1. Stop NL postgres if still up; clear its data dir.
sudo systemctl stop postgresql matrix-synapse
sudo rm -rf /var/lib/postgresql/17
# 2. Re-seed NL from PL (now the live primary).
sudo -u postgres install -d -m 0700 /var/lib/postgresql/17
sudo -u postgres PGPASSWORD="$(sudo cat /run/secrets/matrix/postgres-replication-password)" \
pg_basebackup -h 91.198.166.181 -p 5432 -U replication \
-D /var/lib/postgresql/17 -Fp -Xs -P -R --no-password
# 3. Temporarily flip roles in the flake:
# - hectic-lab.nix: role = "standby"; peerHost = "91.198.166.181";
# - bfs.poland.xray.nix: role = "primary"; peerHost = "128.140.75.58";
# Rebuild both.
# 4. Once NL is streaming green, do the reverse failover dance:
sudo systemctl stop matrix-synapse # on PL
sudo -u postgres pg_ctl -D /var/lib/postgresql/17 promote # on NL
# Then revert the flake role assignments back to NL=primary / PL=standby and
# rebuild both hosts.
# 5. Swap DNS back at Porkbun (A -> 128.140.75.58).
```
## Disaster recovery (NL permanently lost)
```sh
# 1. Promote PL as the new permanent primary.
sudo -u postgres pg_ctl -D /var/lib/postgresql/17 promote
# 2. Edit nixos/system/bfs.poland.xray/bfs.poland.xray.nix:
# hectic.generic.matrix-cluster.role = "primary";
# hectic.generic.matrix-cluster.overrideEnableSynapse = lib.mkForce null;
# hectic.generic.matrix-cluster.replication.peerHost = "<new-standby-ip>";
# hectic.generic.matrix-cluster.replication.allowedSourceIPs = [ "<new-standby-ip>/32" ];
# 3. Provision a new host (any region with Porkbun-managed DNS) and import
# self.nixosModules.matrix-cluster with role = "standby" pointed at PL's IP.
# 4. Bootstrap the new standby via pg_basebackup from PL exactly as in
# "Initial setup" step 3, replacing 128.140.75.58 with PL's IP.
# 5. Update Porkbun A record to PL's IP permanently.
```
@@ -4,6 +4,7 @@
self,
}: {
lib,
pkgs,
modulesPath,
config,
...
@@ -15,7 +16,6 @@
matrixClusterSopsFile = flake + "/sus/matrix-cluster.yaml";
in {
imports = [
./minecraft-wow.nix
self.nixosModules.xray-system
self.nixosModules.matrix-cluster
self.nixosModules.matrix-cluster-users
@@ -65,14 +65,6 @@ in {
hostName = jitsiHost;
};
hectic.services.element = {
enable = true;
hostName = elementEntryDomain;
homeserverBaseUrl = "https://${polandEntryDomain}";
homeserverServerName = matrixHost;
jitsiPreferredDomain = jitsiHost;
};
# NOTE(yukkop): disk was provisioned outside disko, so the expected partition
# label does not exist. Pin root to the live filesystem UUID so stage 1 can
# mount `/` reliably.
@@ -178,6 +170,34 @@ in {
proxyPass = "http://127.0.0.1:8008";
};
};
virtualHosts.${elementEntryDomain} = {
enableACME = true;
forceSSL = true;
locations."= /config.${elementEntryDomain}.json".return = "302 /config.json";
root = pkgs.hectic.element-web.override {
conf = {
default_server_config = {
"m.homeserver".base_url = "https://${polandEntryDomain}";
"m.homeserver".server_name = matrixHost;
"m.identity_server".base_url = "https://vector.im";
};
jitsi = {
preferred_domain = jitsiHost;
};
hectic.videoMessages.enabled = true;
room_directory.servers = [ matrixHost ];
default_theme = "dark";
show_labs_settings = true;
};
};
};
};
sops.secrets."matrix/signing-key" = {
@@ -1,43 +0,0 @@
{ ... }:
{
imports = [ (import ../../module/generic/minecraft-public-relay.nix { }) ];
services.minecraft-public-relay = {
enable = true;
publicKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKNWWegOVTOF3EOmam32iP7sMybULMTxsXuC+cEGITQ8 minecraft-wow-relay";
};
systemd.tmpfiles.rules = [ "d /var/www/store/minecraft/wowmine 0755 root root -" ];
services.nginx.virtualHosts."store.bfs.band" = {
enableACME = true;
forceSSL = true;
root = "/var/www/store";
locations."= /".return = "302 /minecraft/wowmine/";
locations."= /minecraft".return = "302 /minecraft/wowmine/";
locations."= /minecraft/".return = "302 /minecraft/wowmine/";
locations."^~ /minecraft/world-of-sosal/".extraConfig = ''
rewrite ^/minecraft/world-of-sosal/WorldOfSosal-(.*)$ /minecraft/wowmine/wowmine-$1 permanent;
rewrite ^/minecraft/world-of-sosal/(.*)$ /minecraft/wowmine/$1 permanent;
'';
locations."/".extraConfig = ''
autoindex off;
add_header Cache-Control "no-cache";
try_files $uri $uri/ =404;
'';
};
# Keep old pack URLs working for already imported Prism instances.
services.nginx.virtualHosts."bfs.band".locations = {
"= /minecraft".return = "302 /minecraft/wowmine/";
"= /minecraft/".return = "302 /minecraft/wowmine/";
"^~ /minecraft/world-of-sosal/".extraConfig = ''
rewrite ^/minecraft/world-of-sosal/WorldOfSosal-(.*)$ /minecraft/wowmine/wowmine-$1 permanent;
rewrite ^/minecraft/world-of-sosal/(.*)$ /minecraft/wowmine/$1 permanent;
'';
"^~ /minecraft/" = {
root = "/var/www/store";
extraConfig = ''
autoindex off;
add_header Cache-Control "no-cache";
try_files $uri $uri/ =404;
'';
};
};
}
-7
View File
@@ -38,13 +38,6 @@
environment.systemPackages = (with pkgs; [ rsync git steamcmd hectic.AstroTuxLauncher ]);
hectic.services."project-zomboid" = {
enable = true;
serverName = "servertest";
workshopItems = [ ];
mods = [ ];
};
users.users.root.openssh.authorizedKeys.keys = [
''ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKAaObjLBslsdTlqEcYaS1TqX4x9aVJu75y27/8MFevO''
];
@@ -1,8 +0,0 @@
{ ... }: {
hectic.services.affine-chatgpt.enable = true;
systemd.services.affine-native = {
wants = [ "affine-chatgpt.service" ];
after = [ "affine-chatgpt.service" ];
};
}
-289
View File
@@ -1,289 +0,0 @@
{
domain,
...
}: {
pkgs,
lib,
...
}: let
affineDomain = "affine.${domain}";
stateDirectory = "/var/lib/affine";
environmentFile = "${stateDirectory}/.env";
bootstrapDirectory = "/var/lib/affine-bootstrap";
bootstrapPasswordFile = "${bootstrapDirectory}/password";
authFile = "${bootstrapDirectory}/htpasswd";
affineImage = "ghcr.io/toeverything/affine:0.27.4@sha256:c312116a134184947d98749c8a8e29f4e3bc97f4f2a51c9a3497f9baea2eec2b";
postgresImage = "pgvector/pgvector:pg16@sha256:a97d77306ff47cc1d8add4d000cec2207da2e110746318df3137ce53c337ca30";
redisImage = "redis:7-alpine@sha256:8be847644e195abc4c10c8d9936cfa45332eccc6b714fa7b186ff43f1f4d5579";
logging = {
driver = "json-file";
options = {
max-file = "3";
max-size = "10m";
};
};
commonEnvironment = {
AFFINE_INDEXER_ENABLED = "false";
DATABASE_URL = "postgresql://affine:\${DB_PASSWORD}@postgres:5432/affine";
REDIS_SERVER_HOST = "redis";
};
composeFile = (pkgs.formats.yaml {}).generate "affine-compose.yaml" {
services = {
affine = {
image = affineImage;
restart = "unless-stopped";
mem_limit = "2g";
inherit logging;
ports = [ "127.0.0.1:3010:3010" ];
volumes = [
"${stateDirectory}/data/storage:/root/.affine/storage"
"${stateDirectory}/data/config:/root/.affine/config"
];
environment = commonEnvironment;
depends_on = {
migration.condition = "service_completed_successfully";
postgres.condition = "service_healthy";
redis.condition = "service_healthy";
};
};
migration = {
image = affineImage;
command = [
"sh"
"-c"
"node ./scripts/self-host-predeploy.js"
];
mem_limit = "1g";
inherit logging;
volumes = [
"${stateDirectory}/data/storage:/root/.affine/storage"
"${stateDirectory}/data/config:/root/.affine/config"
];
environment = commonEnvironment;
depends_on = {
postgres.condition = "service_healthy";
redis.condition = "service_healthy";
};
};
postgres = {
image = postgresImage;
restart = "unless-stopped";
mem_limit = "512m";
inherit logging;
environment = {
POSTGRES_DB = "affine";
POSTGRES_PASSWORD = "\${POSTGRES_PASSWORD}";
POSTGRES_USER = "affine";
};
volumes = [ "${stateDirectory}/data/postgres:/var/lib/postgresql/data" ];
healthcheck = {
test = [ "CMD-SHELL" "pg_isready -U affine -d affine" ];
interval = "10s";
timeout = "5s";
retries = 5;
start_period = "10s";
};
};
redis = {
image = redisImage;
restart = "unless-stopped";
mem_limit = "128m";
inherit logging;
command = [
"redis-server"
"--save"
"60"
"1"
"--maxmemory"
"96mb"
"--maxmemory-policy"
"noeviction"
];
healthcheck = {
test = [ "CMD" "redis-cli" "ping" ];
interval = "10s";
timeout = "5s";
retries = 5;
};
};
};
};
configFile = pkgs.writeText "affine-config.json" (builtins.toJSON {
server = {
externalUrl = "https://${affineDomain}";
name = "Hectic AFFiNE";
};
copilot.enabled = false;
auth = {
allowSignup = false;
allowSignupForOauth = false;
newAccountShareActionDelay = 0;
};
});
compose = "${pkgs.docker-compose}/bin/docker-compose --project-name affine --env-file ${environmentFile} --file ${composeFile}";
frontendStatic = pkgs.hectic.affine-frontend-static;
frontendOverride = (pkgs.formats.yaml {}).generate "affine-frontend-compose.yaml" {
services.affine.volumes = [ "${frontendStatic}:/app/static:ro" ];
};
frontendCompose = "${compose} --file ${frontendOverride}";
in {
assertions = [
{
assertion = lib.hasPrefix "ghcr.io/toeverything/affine:${frontendStatic.version}@sha256:" affineImage;
message = "AFFiNE frontend assets and the deployed backend image must use the same release.";
}
{
assertion = frontendStatic.revision == "b4c8548c09da21b2898443559a5b846f0ccf5dd8";
message = "AFFiNE frontend source revision must match the pinned 0.27.4 backend.";
}
];
systemd.tmpfiles.rules = [
"d ${stateDirectory} 0750 root root -"
"d ${stateDirectory}/data 0750 root root -"
"d ${stateDirectory}/data/config 0750 root root -"
"d ${stateDirectory}/data/postgres 0750 999 999 -"
"d ${stateDirectory}/data/storage 0750 root root -"
"d ${bootstrapDirectory} 0750 root nginx -"
];
systemd.services.affine = {
description = "AFFiNE Docker Compose stack";
wantedBy = [ "multi-user.target" ];
wants = [ "network-online.target" ];
after = [
"docker.service"
"network-online.target"
"systemd-tmpfiles-setup.service"
];
requires = [
"docker.service"
"network-online.target"
];
restartIfChanged = true;
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
ExecStartPre = pkgs.writeShellScript "affine-prepare" ''
set -eu
umask 077
if [ ! -s ${environmentFile} ]; then
environment_tmp="$(${pkgs.coreutils}/bin/mktemp ${stateDirectory}/.env.XXXXXX)"
trap '${pkgs.coreutils}/bin/rm -f "$environment_tmp"' EXIT
password="$(${pkgs.openssl}/bin/openssl rand -hex 32)"
${pkgs.coreutils}/bin/printf 'DB_PASSWORD=%s\nPOSTGRES_PASSWORD=%s\n' "$password" "$password" > "$environment_tmp"
${pkgs.coreutils}/bin/chmod 0600 "$environment_tmp"
${pkgs.coreutils}/bin/chown root:root "$environment_tmp"
${pkgs.coreutils}/bin/mv "$environment_tmp" ${environmentFile}
trap - EXIT
fi
if [ ! -e ${stateDirectory}/data/config/config.json ]; then
${pkgs.coreutils}/bin/install -m 0644 ${configFile} ${stateDirectory}/data/config/config.json
fi
${pkgs.coreutils}/bin/chmod 0600 ${environmentFile}
${pkgs.coreutils}/bin/chown root:root ${environmentFile}
'';
ExecStart = "${compose} up --detach --wait";
ExecStop = "${compose} down";
TimeoutStartSec = "15min";
TimeoutStopSec = "5min";
};
};
# Reconcile only the application container; leave the database and migration job alone.
systemd.services.affine-frontend = {
description = "Source-built AFFiNE frontend assets";
wantedBy = [ "multi-user.target" ];
requires = [ "affine.service" ];
after = [ "affine.service" ];
partOf = [ "affine.service" ];
reloadIfChanged = true;
restartIfChanged = false;
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
ExecStart = "${frontendCompose} up --detach --no-deps --force-recreate affine";
ExecReload = "${frontendCompose} up --detach --no-deps --force-recreate affine";
ExecStop = "${compose} up --detach --no-deps --force-recreate affine";
TimeoutStartSec = "5min";
TimeoutStopSec = "5min";
};
};
systemd.services.affine-bootstrap = {
description = "Prepare AFFiNE pilot basic authentication";
requiredBy = [ "nginx.service" ];
before = [ "nginx.service" ];
after = [ "systemd-tmpfiles-setup.service" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
};
script = ''
set -eu
umask 077
if [ ! -s ${bootstrapPasswordFile} ]; then
password_tmp="$(${pkgs.coreutils}/bin/mktemp ${bootstrapDirectory}/.password.XXXXXX)"
trap '${pkgs.coreutils}/bin/rm -f "$password_tmp"' EXIT
${pkgs.openssl}/bin/openssl rand -hex 32 > "$password_tmp"
${pkgs.coreutils}/bin/chmod 0600 "$password_tmp"
${pkgs.coreutils}/bin/chown root:root "$password_tmp"
${pkgs.coreutils}/bin/mv "$password_tmp" ${bootstrapPasswordFile}
trap - EXIT
fi
if [ ! -s ${authFile} ]; then
auth_tmp="$(${pkgs.coreutils}/bin/mktemp ${bootstrapDirectory}/.htpasswd.XXXXXX)"
trap '${pkgs.coreutils}/bin/rm -f "$auth_tmp"' EXIT
hash="$(${pkgs.openssl}/bin/openssl passwd -6 -stdin < ${bootstrapPasswordFile})"
${pkgs.coreutils}/bin/printf 'affine:%s\n' "$hash" > "$auth_tmp"
${pkgs.coreutils}/bin/chmod 0640 "$auth_tmp"
${pkgs.coreutils}/bin/chown root:nginx "$auth_tmp"
${pkgs.coreutils}/bin/mv "$auth_tmp" ${authFile}
trap - EXIT
fi
${pkgs.coreutils}/bin/chmod 0600 ${bootstrapPasswordFile}
${pkgs.coreutils}/bin/chown root:root ${bootstrapPasswordFile}
${pkgs.coreutils}/bin/chmod 0640 ${authFile}
${pkgs.coreutils}/bin/chown root:nginx ${authFile}
'';
};
services.nginx.virtualHosts.${affineDomain} = {
enableACME = true;
forceSSL = true;
# Create this marker only after configuring the administrator and signup policy.
extraConfig = ''
client_max_body_size 100m;
set $affine_bootstrap_realm "AFFiNE setup";
if (-f ${bootstrapDirectory}/initialized) {
set $affine_bootstrap_realm off;
}
'';
locations."/" = {
proxyPass = "http://127.0.0.1:3010";
proxyWebsockets = true;
extraConfig = ''
auth_basic $affine_bootstrap_realm;
auth_basic_user_file ${authFile};
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
'';
};
};
}
-189
View File
@@ -1,189 +0,0 @@
{
domain,
...
}: args@{
config,
lib,
pkgs,
...
}: let
cfg = config.hectic.affineDeployment;
affineDomain = "affine.${domain}";
databaseName = "affine-native";
environmentFile = "/var/lib/affine-native/environment";
postgresqlDataDirectory = "/var/lib/affine-postgresql";
postgresqlSocketDirectory = "/run/affine-postgresql";
affinePgvector = pkgs.postgresql_16.pkgs.pgvector.overrideAttrs (_: {
version = "0.8.7";
# v0.8.7 resolves to release commit f37c13f68b57d2c3472b2214fbcff699d6d34876.
src = pkgs.fetchFromGitHub {
owner = "pgvector";
repo = "pgvector";
rev = "v0.8.7";
hash = "sha256-YYXz8zqiuqYWpJwImAhMry/QTLHKOP5MzuY0Of+aflc=";
};
});
affinePostgresql = pkgs.postgresql_16.withPackages (_: [ affinePgvector ]);
dockerConfig = (import ./affine-docker.nix { inherit domain; }) args;
in {
options.hectic.affineDeployment.nativeActive = lib.mkOption {
type = lib.types.bool;
default = false;
description = "Route production traffic to native AFFiNE and disable legacy Docker units.";
};
config = lib.mkMerge [
{
hectic.services.affine = {
enable = true;
frontendPackage = pkgs.hectic.affine-frontend-static;
externalUrl = "https://${affineDomain}";
serverName = "Hectic AFFiNE";
address = "127.0.0.1";
port = 3011;
redisHost = "127.0.0.1";
redisPort = 6388;
inherit environmentFile;
settings = {
copilot.enabled = false;
auth = {
allowSignup = false;
allowSignupForOauth = false;
newAccountShareActionDelay = 0;
};
};
};
users.groups.affine-postgres = {};
users.users.affine-postgres = {
isSystemUser = true;
group = "affine-postgres";
home = postgresqlDataDirectory;
};
systemd.services.affine-postgresql = {
description = "Isolated PostgreSQL cluster for AFFiNE";
wantedBy = [ "multi-user.target" ];
after = [ "local-fs.target" ];
unitConfig.RequiresMountsFor = postgresqlDataDirectory;
path = [ affinePostgresql ];
environment.POSTGRESQL_VERSION = affinePostgresql.version;
restartTriggers = [ affinePgvector ];
preStart = ''
if [ ! -s ${postgresqlDataDirectory}/PG_VERSION ]; then
initdb \
--pgdata=${postgresqlDataDirectory} \
--username=affine-postgres \
--encoding=UTF8 \
--locale=en_US.utf8 \
--auth-local=peer \
--auth-host=reject
fi
cat > ${postgresqlDataDirectory}/pg_hba.conf <<'EOF'
local all all peer
host all all 0.0.0.0/0 reject
host all all ::0/0 reject
EOF
'';
postStart = ''
ready=0
for attempt in $(seq 1 60); do
if pg_isready --host=${postgresqlSocketDirectory} --port=5433 --username=affine-postgres; then
ready=1
break
fi
sleep 1
done
if [ "$ready" -ne 1 ]; then
echo "AFFiNE PostgreSQL did not become ready" >&2
exit 1
fi
psql --host=${postgresqlSocketDirectory} --port=5433 --dbname=postgres \
--set=ON_ERROR_STOP=1 <<'SQL'
DO $role$
BEGIN
IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'affine-native') THEN
CREATE ROLE "affine-native" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE;
END IF;
END
$role$;
ALTER ROLE "affine-native" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE;
SELECT 'CREATE DATABASE "affine-native" OWNER "affine-native"'
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'affine-native')\gexec
ALTER DATABASE "affine-native" OWNER TO "affine-native";
SQL
psql --host=${postgresqlSocketDirectory} --port=5433 --dbname=${databaseName} \
--set=ON_ERROR_STOP=1 <<'SQL'
CREATE EXTENSION IF NOT EXISTS vector;
CREATE EXTENSION IF NOT EXISTS pgcrypto;
SQL
'';
serviceConfig = {
Type = "notify";
User = "affine-postgres";
Group = "affine-postgres";
StateDirectory = "affine-postgresql";
StateDirectoryMode = "0700";
RuntimeDirectory = "affine-postgresql";
RuntimeDirectoryMode = "0755";
ExecStart = "${affinePostgresql}/bin/postgres -D ${postgresqlDataDirectory} -k ${postgresqlSocketDirectory} -p 5433 -c \"listen_addresses=\"";
ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
KillSignal = "SIGINT";
TimeoutStopSec = "120s";
MemoryMax = "512M";
Restart = "on-failure";
RestartSec = "5s";
};
};
services.redis.servers.affine = {
enable = true;
bind = "127.0.0.1";
port = 6388;
settings = {
maxmemory = "96mb";
maxmemory-policy = "noeviction";
};
};
systemd.services.redis-affine.serviceConfig.MemoryMax = "128M";
# Live data restore is intentionally external. Main stages config, private.key,
# storage, and the database before creating this runtime environment file.
systemd.services.affine-native-migrate = {
after = [ "affine-postgresql.service" "redis-affine.service" ];
requires = [ "affine-postgresql.service" "redis-affine.service" ];
unitConfig.ConditionPathExists = environmentFile;
};
systemd.services.affine-native = {
unitConfig.ConditionPathExists = environmentFile;
serviceConfig.MemoryMax = "2G";
};
}
(lib.mkIf (!cfg.nativeActive) dockerConfig)
(lib.mkIf cfg.nativeActive {
services.nginx.virtualHosts.${affineDomain} = {
enableACME = true;
forceSSL = true;
extraConfig = ''
client_max_body_size 100m;
'';
locations."/" = {
proxyPass = "http://127.0.0.1:3011";
proxyWebsockets = true;
extraConfig = ''
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
'';
};
};
})
];
}
+2 -122
View File
@@ -3,51 +3,8 @@
...
}: {
config,
lib,
pkgs,
...
}: let
repackedActive = true;
migrationWriteFreeze = false;
uploadProxyConfig = ''
# Stream large NARs and tolerate S3 backpressure while Attic reads them.
proxy_http_version 1.1;
proxy_request_buffering off;
proxy_send_timeout 600s;
proxy_read_timeout 600s;
'';
repackedSettings = config.services.atticd.settings // {
listen = "127.0.0.1:8082";
allowed-hosts = [ "cache.${domain}" ];
api-endpoint = if repackedActive then "https://cache.${domain}/" else "https://cache.${domain}/next/";
substituter-endpoint = if repackedActive then "https://cache.${domain}/" else "https://cache.${domain}/next/";
database.url = "sqlite:///var/lib/atticd-repacked/server.db?mode=rwc";
storage = {
type = "s3";
bucket = "nix-cache-hectic-lab";
endpoint = "https://hel1.your-objectstorage.com";
region = "hel1";
};
chunking = {
nar-size-threshold = 1048576;
min-size = 1048576;
avg-size = 2097152;
max-size = 4194304;
};
compression.type = "zstd";
};
repackedConfigFile = pkgs.runCommand "checked-atticd-repacked.toml" {
configFile = (pkgs.formats.toml { }).generate "server-repacked.toml" repackedSettings;
} ''
export ATTIC_SERVER_TOKEN_RS256_SECRET_BASE64="$(${lib.getExe pkgs.openssl} genrsa -traditional 4096 | ${pkgs.coreutils}/bin/base64 -w0)"
export ATTIC_SERVER_DATABASE_URL="sqlite://:memory:"
${lib.getExe config.services.atticd.package} --mode check-config -f $configFile
cat <$configFile >$out
'';
in {
}: {
hectic.services.attic = {
enable = true;
hostName = "cache.${domain}";
@@ -60,48 +17,6 @@ in {
};
};
# Slow S3 chunk reads can exceed the SDK's default 20-second stall grace.
services.atticd.package = pkgs.attic-server.overrideAttrs (old: {
# Restrict the SDK TLS connector to HTTP/1.1 after S3 REFUSED_STREAM errors.
cargoDeps = pkgs.runCommand "attic-cargo-vendor-http1" { } ''
mkdir "$out"
cp -a --no-preserve=mode ${old.cargoDeps}/. "$out/"
crate="$out/source-registry-0/aws-smithy-http-client-1.0.6"
substituteInPlace "$crate/src/client/tls.rs" \
--replace-fail '.enable_http2()' ""
'';
postPatch = (old.postPatch or "") + ''
substituteInPlace server/src/storage/s3.rs \
--replace-fail 'let mut builder = S3ConfigBuilder::from(&shared_config);' \
'let mut builder = S3ConfigBuilder::from(&shared_config)
.stalled_stream_protection(
aws_sdk_s3::config::StalledStreamProtectionConfig::enabled()
.grace_period(Duration::from_secs(120))
.build(),
);'
'';
});
services.atticd.settings = lib.mkIf repackedActive {
api-endpoint = lib.mkForce "https://cache.${domain}/previous/";
substituter-endpoint = "https://cache.${domain}/previous/";
};
services.atticd.mode = if migrationWriteFreeze || repackedActive then "api-server" else "monolithic";
systemd.services.atticd-repacked = {
wantedBy = [ "multi-user.target" ];
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
serviceConfig = config.systemd.services.atticd.serviceConfig // {
ExecStart = "${lib.getExe config.services.atticd.package} -f ${repackedConfigFile} --mode monolithic";
EnvironmentFile = config.sops.secrets."atticd/environment".path;
StateDirectory = "atticd-repacked";
User = "atticd-repacked";
Group = "atticd-repacked";
};
};
services.nginx.virtualHosts."cache.${domain}" = {
enableACME = true;
forceSSL = true;
@@ -109,42 +24,7 @@ in {
client_max_body_size 0;
'';
locations."/" = {
proxyPass = if repackedActive then "http://127.0.0.1:8082" else "http://127.0.0.1:8081";
extraConfig = ''
# Allow quiet periods while Attic fetches NAR chunks from object storage.
proxy_read_timeout 300s;
'' + lib.optionalString (migrationWriteFreeze && !repackedActive) ''
# Quiesce the old writer during the final snapshot and verification.
limit_except GET {
deny all;
}
'';
};
locations."/next/" = {
proxyPass = "http://127.0.0.1:8082/";
extraConfig = ''
# Allow quiet periods while Attic fetches NAR chunks from object storage.
proxy_read_timeout 300s;
'';
};
locations."= /_api/v1/upload-path" = lib.mkIf (repackedActive || !migrationWriteFreeze) {
proxyPass = if repackedActive then "http://127.0.0.1:8082" else "http://127.0.0.1:8081";
extraConfig = uploadProxyConfig;
};
locations."= /next/_api/v1/upload-path" = {
proxyPass = "http://127.0.0.1:8082/_api/v1/upload-path";
extraConfig = uploadProxyConfig;
};
locations."/previous/" = {
proxyPass = "http://127.0.0.1:8081/";
extraConfig = ''
# Legacy backend is exposed for read-only migration checks.
limit_except GET {
deny all;
}
# Allow quiet periods while Attic fetches NAR chunks from object storage.
proxy_read_timeout 300s;
'';
proxyPass = "http://127.0.0.1:8081";
};
};
}
+1 -24
View File
@@ -11,30 +11,7 @@
in self.lib.nixpkgs-lib.nixosSystem {
pkgs = import inputs.nixpkgs {
inherit system;
overlays = [
self.overlays.default
(final: prev: {
python311 = prev.python311.overrideAttrs (old: {
passthru = old.passthru // {
doc = old.passthru.doc.overrideAttrs (oldDoc: {
patches = (oldDoc.patches or [ ]) ++ [
./python-docutils-0.22.patch
./python-sphinx9-glossary.patch
];
});
};
});
})
];
config.allowUnfreePredicate = pkg:
builtins.elem (inputs.nixpkgs.lib.getName pkg) [
"affine"
"affine-server-native"
"steamcmd"
"steam-unwrapped"
"p4d"
"p4"
];
overlays = [ self.overlays.default ];
};
modules = [
{ networking.hostName = name; }
@@ -1,75 +0,0 @@
{ pkgs, ... }:
let
port = 22222;
stateDir = "/var/lib/experimental-sshd";
configFile = pkgs.writeText "experimental-sshd_config" ''
Port 22222
ListenAddress 0.0.0.0
ListenAddress ::
HostKey ${stateDir}/ssh_host_ed25519_key
HostKey ${stateDir}/ssh_host_rsa_key
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
PermitRootLogin prohibit-password
UsePAM yes
AuthenticationMethods publickey
AuthorizedKeysFile %h/.ssh/authorized_keys /etc/ssh/authorized_keys.d/%u
LogLevel INFO
VersionAddendum none
HostKeyAlgorithms rsa-sha2-512,rsa-sha2-256,ssh-ed25519
KexAlgorithms curve25519-sha256,diffie-hellman-group14-sha256
Ciphers aes256-ctr,aes128-ctr
MACs hmac-sha2-512,hmac-sha2-256
'';
keygenScript = pkgs.writeShellScript "experimental-sshd-keygen" ''
set -eu
${pkgs.coreutils}/bin/mkdir -p -m 0700 ${stateDir}
if [ ! -f ${stateDir}/ssh_host_ed25519_key ]; then
${pkgs.openssh}/bin/ssh-keygen -t ed25519 -f ${stateDir}/ssh_host_ed25519_key -N ""
fi
if [ ! -f ${stateDir}/ssh_host_rsa_key ]; then
${pkgs.openssh}/bin/ssh-keygen -t rsa -b 4096 -f ${stateDir}/ssh_host_rsa_key -N ""
fi
'';
in
{
environment.etc."ssh/experimental-sshd_config".source = configFile;
networking.firewall.allowedTCPPorts = [ port ];
systemd.services.experimental-sshd-keygen = {
description = "Generate experimental SSH host keys";
wantedBy = [ "multi-user.target" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
StateDirectory = "experimental-sshd";
ExecStart = keygenScript;
};
};
systemd.services.experimental-sshd = {
description = "Experimental SSH daemon";
wantedBy = [ "multi-user.target" ];
wants = [ "experimental-sshd-keygen.service" ];
after = [ "network.target" "experimental-sshd-keygen.service" ];
serviceConfig = {
Type = "simple";
StateDirectory = "experimental-sshd";
RuntimeDirectory = "experimental-sshd";
ExecStart = "${pkgs.openssh}/bin/sshd -D -f /etc/ssh/experimental-sshd_config";
StandardError = "journal";
};
preStart = ''
${pkgs.openssh}/bin/sshd -t -f /etc/ssh/experimental-sshd_config
'';
};
}
+8 -155
View File
@@ -8,13 +8,14 @@
config,
pkgs,
lib,
modulesPath,
...
}:
with builtins;
with lib;
let
domain = "hectic-lab.com";
giteaSshPort = 22223;
sshPort = 22;
mailUserNames = [
"security"
"founders"
@@ -43,43 +44,24 @@ let
group = "ente";
};
};
giteaRunnerInstance = "hectic-lab-local";
giteaRunnerEscapedInstance = builtins.replaceStrings [ "-" ] [ "\\x2d" ] giteaRunnerInstance;
giteaRunnerService = "gitea-runner-${giteaRunnerEscapedInstance}";
giteaRunnerTokenEnvService = "${giteaRunnerService}-token-env";
giteaRunnerTokenEnv = "/run/gitea-runner-${giteaRunnerInstance}/token.env";
in {
imports = [
self.nixosModules.hectic
self.nixosModules.mailserver
self.nixosModules.matrix-cluster
inputs.sops-nix.nixosModules.sops
inputs.piu-piu.nixosModules.server
self.nixosModules."shadowsocks-rust" # NOTE(nrv): impl
self.nixosModules."shadowsocks" # NOTE(nrv): usage/instance
inputs.hectic-landing.nixosModules.hectic-landing
inputs.iana-angl.nixosModules.iana-angl
(import ./affine.nix { inherit domain; })
./affine-chatgpt.nix
(import ./attic.nix { inherit flake self inputs domain; })
(import ./containers.nix { inherit flake self inputs; })
./experimental-sshd.nix
./minecraft-wow-proxy.nix
(import ./ente.nix { inherit domain; })
(import ./immich.nix { inherit domain inputs; })
(import ./mechabellum.nix { inherit flake self inputs domain; })
(import ./whiteboard.nix { inherit domain; })
(import (./. + "/sentinèlla.nix") { inherit flake self inputs domain; })
];
services.piu-piu-server = {
enable = true;
bindAddress = "0.0.0.0";
};
services.hectic-landing = {
enable = true;
package = inputs.hectic-landing.packages.${pkgs.stdenv.hostPlatform.system}.hectic-landing;
@@ -88,18 +70,11 @@ in {
host = "127.0.0.1";
};
services.iana-angl = {
enable = true;
package = inputs.iana-angl.packages.${pkgs.stdenv.hostPlatform.system}.iana-angl;
domain = "lessons.${domain}";
};
# NOTE(yukkop): both nixos-mailserver and hectic-landing module set
# security.acme.defaults.email. Force the mailserver-aligned address.
security.acme.defaults.email = lib.mkForce "security@${domain}";
hectic = {
affineDeployment.nativeActive = true;
archetype.dev.enable = true;
hardware.hetzner-cloud = {
enable = true;
@@ -111,43 +86,6 @@ in {
services.matrix = {
enable = false;
};
services.p4d = {
enable = true;
package = pkgs.p4d;
clientPackage = pkgs.p4;
openFirewall = true;
bootstrap.enable = false;
};
services.gitea-runner-controller = {
# NOTE(yukkop): ephemeral Hetzner VM runners (1 VM = 1 job).
# Runbook: infra/gitea-runners/runbook.md "Ephemeral VM runner cutover".
enable = true;
budgetEurMonthly = "30";
imageId = "429747473"; # MicroOS x86 + persistent controller SSH key and writable Nix mount
armImageId = "423979717"; # OpenSUSE MicroOS ARM K3S 2026-08-24 snapshot
nixImageId = "161547269"; # Ubuntu 24.04 x86; Nix needs writable root
armNixImageId = "161547270"; # Ubuntu 24.04 ARM; Nix needs writable root
allowedRepos = [
"hinterland/*"
"yukkop/*"
"hectic-lab/*"
];
# FIXME(yukkop): debug key for bootstrap debugging; remove once E2E stable.
debugSshPublicKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIBSWIv80pyCMDQ6zH34P2qWizpOcO7X86BVhMGtbob9U gcr-controller@hectic-lab";
hcloudSshKeyId = 118512401;
};
services.routine-server = {
enable = true;
timezone = "Europe/Rome";
};
};
zramSwap = {
enable = true;
priority = 100;
algorithm = lib.mkDefault "zstd";
swapDevices = 1;
memoryPercent = lib.mkDefault 100;
};
# NOTE(yukkop): disk was provisioned by Hetzner rescue image, disko was never
@@ -163,12 +101,6 @@ in {
options = [ "umask=0077" ];
};
fileSystems."/nix" = lib.mkForce {
device = "/dev/disk/by-id/scsi-0HC_Volume_106777875";
fsType = "ext4";
neededForBoot = true;
};
programs.zsh.enable = true;
programs.zsh.interactiveShellInit = ''
setopt vi
@@ -192,12 +124,7 @@ in {
key = "init-postgresql";
};
"atticd/environment" = {};
"immich/storage-box" = {};
"wg-bfs/private-key" = {};
"gitea-runner/org-registration-token" = {
sopsFile = flake + "/sus/gitea-runners.yaml";
key = "gitea/hectic-lab/org-runner-registration-token";
};
"wg-bfs/private-key" = {};
} // builtins.listToAttrs (map mkEnteSecret [
"key-encryption"
"key-hash"
@@ -220,8 +147,6 @@ in {
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIE/EhBI6sJb2yHbTkqhZiCzUrsLE6t+CZe7RhS22z7w5 nrv@adamantia"
# github workflow
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKPEUArBxu7NUULT7Pi8ArtVxY1uVbIBSaeRKtqz1sz1"
# gitea workflow
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAogEr5boewtUrOeOqI96y/7FWR03vdbGW93Nj01tiIS gitea-actions-hectic-lab-deploy"
];
users.users.ds4d = { # NOTE(nrv): artishoque
@@ -238,12 +163,12 @@ in {
];
};
services.openssh.ports = [ giteaSshPort ];
services.openssh.ports = [ sshPort ];
services.mailserver = {
enable = true;
domain = domain;
accounts = builtins.listToAttrs (map mkMailLoginAccount mailUserNames);
loginAccounts = builtins.listToAttrs (map mkMailLoginAccount mailUserNames);
};
mailserver.stateVersion = 3;
@@ -260,7 +185,7 @@ in {
networking.firewall = {
allowedTCPPorts = [
giteaSshPort # gitea ssh
sshPort # ssh
80
443
3306 # mysql
@@ -268,7 +193,6 @@ in {
55228 # ss-bfs
];
allowedUDPPorts = [
config.services.piu-piu-server.port
51820 # wg-bfs
55228 # ss-bfs
];
@@ -284,40 +208,9 @@ in {
"d /var/www/store 0755 nginx nginx -"
];
systemd.services.${giteaRunnerTokenEnvService} = {
description = "Prepare local Gitea Actions runner token environment";
requiredBy = [ "${giteaRunnerService}.service" ];
before = [ "${giteaRunnerService}.service" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
RuntimeDirectory = "gitea-runner-${giteaRunnerInstance}";
RuntimeDirectoryMode = "0700";
};
script = ''
set -eu
umask 077
token_file=${config.sops.secrets."gitea-runner/org-registration-token".path}
env_file=${giteaRunnerTokenEnv}
printf 'TOKEN=' > "$env_file"
tr -d '\n' < "$token_file" >> "$env_file"
printf '\n' >> "$env_file"
'';
};
systemd.services.${giteaRunnerService} = {
after = [
"gitea.service"
"${giteaRunnerTokenEnvService}.service"
];
requires = [ "${giteaRunnerTokenEnvService}.service" ];
};
services.nginx = {
enable = true;
# NOTE(yukkop): virtualHosts.${domain} is owned by the hectic-landing module
virtualHosts."mail.${domain}".enableACME = true;
virtualHosts."store.${domain}" = {
enableACME = true;
forceSSL = true;
@@ -328,10 +221,6 @@ in {
'';
};
};
virtualHosts."lessons.${domain}" = {
enableACME = true;
forceSSL = true;
};
virtualHosts."snuff.${domain}" = {
enableACME = true;
forceSSL = true;
@@ -365,15 +254,10 @@ in {
virtualHosts."gitea.${domain}" = {
enableACME = true;
forceSSL = true;
# NOTE(yukkop): allow large git pushes over HTTPS.
extraConfig = "client_max_body_size 2g;";
locations."/" = {
extraConfig = ''
proxy_pass http://127.0.0.1:11011/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
'';
};
};
@@ -383,21 +267,12 @@ in {
gitea = {
enable = true;
package = pkgs.hectic.gitea-heatmap;
# Keep LFS storage limited to accounts provisioned by administrators.
settings.service.DISABLE_REGISTRATION = false;
settings.session.COOKIE_SECURE = true;
settings.actions.ENABLED = true;
# Long CUDA builds must not hit Gitea's default three-hour task watchdog.
settings.actions.ENDLESS_TASK_TIMEOUT = "8h";
settings.service.DISABLE_REGISTRATION = true;
settings.server = {
HTTP_ADDR = "127.0.0.1";
HTTP_PORT = 11011;
ROOT_URL = "https://gitea.${domain}/";
SSH_PORT = giteaSshPort;
SSH_PORT = sshPort;
SSH_DOMAIN = "hectic-lab.com";
LFS_MAX_FILE_SIZE = 2147483648;
};
lfs.enable = true;
database = {
createDatabase = true;
type = "postgres";
@@ -406,27 +281,5 @@ in {
name = "gitea";
};
};
gitea-actions-runner.instances.${giteaRunnerInstance} = {
enable = false;
name = giteaRunnerInstance;
url = "https://gitea.${domain}";
tokenFile = giteaRunnerTokenEnv;
labels = [
"nix:host"
"native:host"
];
hostPackages = with pkgs; [
bash
cacert
coreutils
curl
git
gnutar
gzip
nix
nodejs
xz
];
};
};
}
-21
View File
@@ -1,21 +0,0 @@
{ domain, inputs, ... }:
{
config,
pkgs,
...
}:
{
hectic.services.immich = {
enable = true;
domain = "immich.${domain}";
storageBox = {
enable = true;
credentialsFile = config.sops.secrets."immich/storage-box".path;
};
};
# Immich 3 is not available on nixos-26.05.
services.immich.package =
inputs.nixpkgs-gitea.legacyPackages.${pkgs.stdenv.hostPlatform.system}.immich;
}
@@ -1,8 +0,0 @@
{ ... }:
{
imports = [ (import ../../module/generic/minecraft-public-relay.nix { }) ];
services.minecraft-public-relay = {
enable = false;
publicKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKNWWegOVTOF3EOmam32iP7sMybULMTxsXuC+cEGITQ8 minecraft-wow-relay";
};
}
@@ -1,22 +0,0 @@
--- a/Doc/tools/extensions/pyspecific.py
+++ b/Doc/tools/extensions/pyspecific.py
@@ -48,11 +48,21 @@
SOURCE_URI = 'https://github.com/python/cpython/tree/3.11/%s'
# monkey-patch reST parser to disable alphabetic and roman enumerated lists
+def _disable_alphabetic_and_roman(text):
+ try:
+ # docutils >= 0.22
+ from docutils.parsers.rst.states import InvalidRomanNumeralError
+ raise InvalidRomanNumeralError(text)
+ except ImportError:
+ # docutils < 0.22
+ return None
+
+
from docutils.parsers.rst.states import Body
Body.enum.converters['loweralpha'] = \
Body.enum.converters['upperalpha'] = \
Body.enum.converters['lowerroman'] = \
- Body.enum.converters['upperroman'] = lambda x: None
+ Body.enum.converters['upperroman'] = _disable_alphabetic_and_roman
@@ -1,12 +0,0 @@
--- a/Doc/tools/extensions/glossary_search.py
+++ b/Doc/tools/extensions/glossary_search.py
@@ -33,7 +33,7 @@
rendered = app.builder.render_partial(definition)
terms[term] = {
'title': glossary_item[0].astext(),
- 'body': rendered['html_body']
+ 'body': rendered['fragment']
}
if hasattr(app.env, 'glossary_terms'):
@@ -1,18 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>wowmine</title>
</head>
<body>
<main>
<h1>wowmine</h1>
<p><a href="https://store.hectic-lab.com/minecraft/wowmine/">Install in Prism with automatic mod updates</a></p>
<p><a href="https://store.hectic-lab.com/minecraft/wowmine/latest.mrpack">Download latest pack</a></p>
<p><a href="prismlauncher://import?url=https%3A%2F%2Fstore.hectic-lab.com%2Fminecraft%2Fwowmine%2Flatest.mrpack">Import latest pack in Prism Launcher</a></p>
<p><a href="https://store.hectic-lab.com/minecraft/wowmine/SHA256SUMS">SHA-256 checksums</a></p>
<p>Updates are manual. Packs imported from arbitrary URLs do not update automatically.</p>
</main>
</body>
</html>
@@ -1,93 +0,0 @@
Copyright 2019 The Golos Text Project Authors (https://github.com/googlefonts/golos-text)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -1,93 +0,0 @@
Copyright (c) 2011-2012, Jovanny Lemonad (jovanny.ru), with Reserved Font Name "Russo"
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -1,6 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48">
<path fill="#a7d754" d="m24 2 22 11-22 11L2 13Z"/>
<path fill="#765239" d="m2 13 22 11v22L2 35Z"/>
<path fill="#513c30" d="m24 24 22-11v22L24 46Z"/>
<path fill="#76a637" d="m2 13 22 11v8l-8-4v-4l-6-3v5l-8-4Zm22 11 22-11v9l-7 3v-4l-7 4v5l-8 4Z"/>
</svg>

Before

Width:  |  Height:  |  Size: 322 B

@@ -1,217 +0,0 @@
@font-face {
font-family: "Golos Text";
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("./golos-regular.ttf") format("truetype");
}
@font-face {
font-family: "Golos Text";
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("./golos-semibold.ttf") format("truetype");
}
@font-face {
font-family: "Russo One";
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("./russo-one.ttf") format("truetype");
}
:root {
color-scheme: dark;
--bg: #141a15;
--surface: #202921;
--inset: #101610;
--ink: #f4f3e7;
--muted: #bec9b8;
--line: #394638;
--grass: #a7d754;
--grass-hover: #b9e66c;
--action-ink: #17250d;
--focus: #e8b86c;
--hero-ink: #fffdf0;
--hero-muted: #e5e9d7;
--body-font: "Golos Text", sans-serif;
--heading-font: "Russo One", sans-serif;
--space-1: 4px;
--space-2: 8px;
--space-3: 12px;
--space-4: 16px;
--space-6: 24px;
--space-8: 32px;
--space-12: 48px;
--space-16: 64px;
--space-20: 80px;
--space-24: 96px;
--ease: 140ms ease-out;
--gutter: clamp(24px, 4vw, 48px);
scroll-behavior: smooth;
scroll-padding-top: var(--space-8);
scrollbar-color: var(--line) var(--bg);
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--ink); font: 400 16px/1.65 var(--body-font); }
::selection { background: var(--grass); color: var(--action-ink); }
a { color: inherit; text-underline-offset: .22em; text-decoration-thickness: 1px; }
button, summary, a { -webkit-tap-highlight-color: transparent; }
button { font: inherit; cursor: pointer; }
button, a { touch-action: manipulation; }
:focus-visible { outline: 3px solid var(--focus); outline-offset: 4px; }
h1, h2, h3, p { margin: 0; }
h1, h2, h3 { font-family: var(--heading-font); font-weight: 400; line-height: 1.2; text-wrap: balance; }
h2 { font-size: clamp(32px, 3.4vw, 48px); letter-spacing: -.02em; }
h3 { font-size: clamp(24px, 2.1vw, 28px); }
code { font-family: ui-monospace, "Cascadia Code", monospace; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
.container { width: min(100% - var(--gutter) * 2, 1200px); margin-inline: auto; }
.section { padding-block: var(--space-24); }
.icon-sprite { position: absolute; inline-size: 0; block-size: 0; overflow: hidden; }
.icon, .world-icon { inline-size: 24px; block-size: 24px; flex: 0 0 auto; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: square; stroke-linejoin: miter; }
.skip-link { position: fixed; top: var(--space-4); left: var(--space-4); z-index: 3; padding: var(--space-3) var(--space-4); background: var(--grass); color: var(--action-ink); transform: translateY(-180%); }
.skip-link:focus { transform: translateY(0); }
.site-header { background: var(--bg); border-bottom: 1px solid var(--line); }
.header-inner { min-block-size: 88px; display: flex; align-items: center; gap: var(--space-8); }
.brand { display: inline-flex; align-items: center; gap: var(--space-3); text-decoration: none; }
.brand-block { inline-size: 36px; block-size: 40px; flex: 0 0 auto; }
.brand-name { font-family: var(--heading-font); font-size: 20px; letter-spacing: -.02em; line-height: 1.1; }
.brand-name span { display: block; font-size: 24px; }
.main-nav { display: flex; align-items: center; justify-content: center; gap: var(--space-8); margin-inline-start: auto; }
.main-nav a { display: flex; align-items: center; min-block-size: 48px; text-decoration: none; font-size: 14px; font-weight: 600; transition: color var(--ease); }
.main-nav a:hover { color: var(--muted); text-decoration: underline; }
.hero { --focus: #e8b86c; position: relative; isolation: isolate; overflow: hidden; color: var(--hero-ink); background: #101a10; }
.hero-scene { position: absolute; inset: 0; inline-size: 100%; block-size: 100%; object-fit: cover; object-position: center; z-index: -2; }
.hero::before { content: ""; position: absolute; inset: 0; z-index: -1; background: linear-gradient(90deg, rgb(9 20 10 / 88%), rgb(9 20 10 / 68%) 38%, rgb(9 20 10 / 9%) 78%), linear-gradient(0deg, rgb(9 20 10 / 48%), transparent 45%); }
.hero-inner { min-block-size: 640px; padding-block: var(--space-24) var(--space-24); display: flex; flex-direction: column; align-items: flex-start; justify-content: center; }
h1 { max-inline-size: 800px; font-size: clamp(36px, 5.3vw, 84px); line-height: 1.09; letter-spacing: -.02em; text-shadow: 0 4px 0 rgb(9 20 10 / 75%); }
h1 span { display: block; }
.hero-lead { max-inline-size: 51ch; margin-block-start: var(--space-6); color: var(--hero-muted); font-size: 18px; line-height: 1.75; text-wrap: pretty; }
.hero-actions { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-8); margin-block-start: var(--space-8); }
.button { display: inline-flex; justify-content: center; align-items: center; gap: var(--space-3); min-block-size: 56px; padding: var(--space-4) var(--space-6); border: 2px solid transparent; font-weight: 600; line-height: 1.3; text-decoration: none; transition: background var(--ease), transform var(--ease), box-shadow var(--ease); }
.button-primary { background: var(--grass); color: var(--action-ink); border-color: rgb(23 37 13 / 28%); box-shadow: inset 0 3px 0 rgb(255 255 255 / 26%), 0 5px 0 #506c26; }
.button-primary:hover { background: var(--grass-hover); transform: translateY(-2px); box-shadow: inset 0 3px 0 rgb(255 255 255 / 26%), 0 7px 0 #506c26; }
.button-primary:active { transform: translateY(4px); box-shadow: inset 0 3px 0 rgb(255 255 255 / 26%), 0 1px 0 #506c26; }
.hero-guide { display: inline-flex; align-items: center; gap: var(--space-3); min-block-size: 48px; text-decoration: none; font-weight: 600; }
.hero-guide:hover { text-decoration: underline; }
.hero-guide .icon { inline-size: 20px; }
.hero-note { margin-block-start: var(--space-6); color: var(--hero-muted); font-size: 14px; }
.hero-scroll { position: absolute; inset-block-end: var(--space-6); inset-inline-end: var(--gutter); display: flex; align-items: center; gap: var(--space-3); min-block-size: 44px; color: var(--hero-ink); text-decoration: none; font-size: 14px; }
.hero-scroll .icon { transform: rotate(90deg); inline-size: 18px; }
.hero-scroll:hover span { text-decoration: underline; }
.connection { background: var(--surface); border-bottom: 1px solid var(--line); }
.connection-inner { position: relative; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: var(--space-6); padding-block: var(--space-8) var(--space-12); }
.connection-label { display: flex; align-items: center; gap: var(--space-4); }
.signal-mark { inline-size: 12px; block-size: 12px; background: var(--muted); box-shadow: 6px -6px 0 var(--muted); margin-inline-end: var(--space-2); }
.connection-title { font-weight: 600; }
.connection-caption { color: var(--muted); font-size: 14px; }
.address-group { display: flex; align-items: center; gap: var(--space-6); min-inline-size: 0; }
#server-address { font-size: 17px; color: var(--ink); }
.button-copy { inline-size: 184px; min-block-size: 48px; padding: var(--space-3) var(--space-4); border: 1px solid var(--line); color: var(--ink); background: var(--inset); font-size: 14px; }
.button-copy:hover { background: var(--bg); }
.button-copy:active { transform: translateY(2px); }
.copied-icon { display: none; }
[data-copied="true"] .copy-icon { display: none; }
[data-copied="true"] .copied-icon { display: block; }
.copy-feedback { position: absolute; inset-inline-end: 0; inset-block-end: var(--space-3); max-inline-size: 100%; min-block-size: 23px; color: var(--muted); font-size: 14px; }
.world-layout { display: grid; grid-template-columns: 1.05fr 1fr; gap: var(--space-24); }
.section-intro > p { margin-block-start: var(--space-6); max-inline-size: 48ch; color: var(--muted); font-size: 18px; }
.world-list { display: grid; gap: var(--space-8); align-content: center; }
.world-entry { display: flex; gap: var(--space-6); }
.world-entry + .world-entry { padding-block-start: var(--space-8); border-top: 1px solid var(--line); }
.world-icon { inline-size: 32px; block-size: 32px; color: var(--muted); }
.world-entry p { margin-block-start: var(--space-3); color: var(--muted); max-inline-size: 48ch; }
.setup-section { background: var(--inset); }
.setup-layout { display: grid; grid-template-columns: minmax(0, 1.65fr) minmax(0, 1fr); gap: var(--space-24); margin-block-start: var(--space-12); }
.steps { list-style: none; margin: 0; padding: 0; display: grid; gap: var(--space-8); }
.steps li { display: flex; align-items: flex-start; gap: var(--space-6); }
.step-number { flex: 0 0 48px; display: grid; place-items: center; block-size: 48px; color: var(--muted); border: 1px solid var(--line); font-family: var(--heading-font); font-size: 20px; font-variant-numeric: tabular-nums; }
.steps h3 { font-size: 24px; }
.steps p { margin-block-start: var(--space-3); max-inline-size: 63ch; color: var(--muted); }
.steps a, .questions a { color: var(--ink); }
.steps a:hover, .questions a:hover { text-decoration-thickness: 2px; }
.requirements { align-self: start; padding: var(--space-8); background: var(--surface); }
.requirements dl { margin-block: var(--space-6); }
.requirements dl > div { display: flex; justify-content: space-between; flex-wrap: wrap; gap: var(--space-2) var(--space-4); padding-block: var(--space-3); border-bottom: 1px solid var(--line); font-size: 14px; }
.requirements dt { color: var(--muted); }
.requirements dd { margin: 0; font-weight: 600; font-variant-numeric: tabular-nums; }
.requirements > p { color: var(--muted); font-size: 14px; }
.help-layout { display: grid; grid-template-columns: 1fr 1.65fr; gap: var(--space-24); }
.questions details { border-bottom: 1px solid var(--line); }
.questions details:first-child { border-top: 1px solid var(--line); }
.questions summary { list-style: none; display: flex; align-items: center; justify-content: space-between; gap: var(--space-6); min-block-size: 80px; padding-block: var(--space-6); cursor: pointer; font-size: 18px; font-weight: 600; line-height: 1.5; }
.questions summary::-webkit-details-marker { display: none; }
.questions summary:hover { color: var(--muted); }
.questions summary .icon { transition: transform var(--ease); }
.questions details[open] summary .icon { transform: rotate(45deg); }
.questions details > p { max-inline-size: 65ch; padding-block-end: var(--space-6); padding-inline-end: var(--space-12); color: var(--muted); }
.site-footer { border-top: 1px solid var(--line); padding-block: var(--space-12); background: var(--inset); }
.footer-inner { display: flex; align-items: flex-start; justify-content: space-between; flex-wrap: wrap; gap: var(--space-8); }
.footer-brand { display: flex; flex-direction: column; min-block-size: 48px; text-decoration: none; font-family: var(--heading-font); font-size: 20px; }
.footer-brand span { margin-block-start: var(--space-2); color: var(--muted); font: 400 14px/1.65 var(--body-font); }
.footer-links { display: flex; flex-wrap: wrap; gap: var(--space-6); font-size: 14px; }
.footer-links a { display: flex; align-items: center; min-block-size: 48px; }
.footer-inner > p { flex-basis: 100%; color: var(--muted); font-size: 14px; }
@media (min-width: 1600px) {
.hero-inner { min-block-size: 720px; }
}
@media (max-width: 960px) {
.world-layout, .setup-layout, .help-layout { gap: var(--space-12); }
.world-layout { grid-template-columns: 1fr 1fr; }
.connection-label { flex-basis: 100%; }
.address-group { inline-size: 100%; justify-content: space-between; }
.copy-feedback { inset-inline-start: 0; }
}
@media (max-width: 700px) {
.header-inner { min-block-size: 80px; gap: var(--space-4); }
.brand-block { inline-size: 28px; block-size: 32px; }
.brand-name { font-size: 16px; }
.brand-name span { font-size: 19px; }
.main-nav { gap: 0; }
.main-nav a { font-size: 14px; }
.main-nav .nav-world, .main-nav .nav-help { display: none; }
.theme-toggle { inline-size: 44px; block-size: 44px; flex: 0 0 auto; }
.hero-inner { min-block-size: 620px; padding-block: var(--space-16) var(--space-24); }
.hero-scene { object-position: 61% center; }
.hero::before { background: linear-gradient(90deg, rgb(9 20 10 / 88%), rgb(9 20 10 / 60%)), linear-gradient(0deg, rgb(9 20 10 / 30%), transparent); }
h1 { font-size: clamp(34px, 7.7vw, 48px); }
.hero-lead { margin-block-start: var(--space-6); font-size: 16px; }
.hero-actions { gap: var(--space-4) var(--space-6); margin-block-start: var(--space-8); }
.button-primary { min-block-size: 56px; }
.hero-guide { font-size: 14px; }
.hero-note { font-size: 14px; }
.hero-scroll { inset-inline-start: var(--gutter); inset-inline-end: auto; font-size: 14px; }
.connection-inner { gap: var(--space-6); padding-block: var(--space-8) 52px; }
.address-group { gap: var(--space-3); }
#server-address { font-size: 14px; }
.button-copy { inline-size: 48px; flex: 0 0 48px; padding: var(--space-3); }
.button-copy span { position: absolute; inline-size: 1px; block-size: 1px; overflow: hidden; clip-path: inset(50%); }
.copy-feedback { font-size: 14px; line-height: 1.5; }
.section { padding-block: var(--space-16); }
.world-layout, .setup-layout, .help-layout { grid-template-columns: minmax(0, 1fr); gap: var(--space-12); }
.section-intro > p { font-size: 16px; }
.world-entry { gap: var(--space-4); }
.world-entry h3 { font-size: 26px; }
.world-icon { inline-size: 28px; block-size: 28px; }
.setup-layout { margin-block-start: var(--space-8); }
.steps li { gap: var(--space-4); }
.step-number { flex-basis: 40px; block-size: 40px; font-size: 18px; }
.steps h3 { font-size: 24px; }
.requirements { padding: var(--space-6); }
.questions summary { font-size: 16px; gap: var(--space-4); }
.questions details > p { padding-inline-end: 0; }
.footer-inner { gap: var(--space-6); }
.footer-links { gap: var(--space-6); }
}
@media (prefers-reduced-motion: reduce) {
:root { scroll-behavior: auto; }
*, *::before, *::after { transition: none !important; }
.button-primary:hover, .button-primary:active, .button-copy:active, .theme-toggle:active { transform: none; }
}
@@ -1,19 +0,0 @@
// @ts-check
document.querySelectorAll("[data-copy-address]").forEach((button) => {
button.addEventListener("click", async () => {
const address = document.getElementById("server-address");
const feedback = document.getElementById("copy-feedback");
if (!address || !feedback) return;
try {
await navigator.clipboard.writeText(address.innerText.trim());
button.setAttribute("data-copied", "true");
feedback.textContent = "Адрес скопирован. Увидимся в игре.";
} catch (error) {
if (!(error instanceof DOMException)) throw error;
button.removeAttribute("data-copied");
feedback.textContent = "Выдели адрес и скопируй его вручную.";
}
});
});

Some files were not shown because too many files have changed in this diff Show More