Skip to content

Commit

Permalink
nix: add migrations passthru and run-migrations scipt
Browse files Browse the repository at this point in the history
  • Loading branch information
marijanp committed Sep 19, 2024
1 parent 0847283 commit 8047d24
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
23 changes: 22 additions & 1 deletion flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@
runtimeInputs = [
pkgs.tinyproxy
pkgs.simple-http-server
self'.packages.run-migrations
];
text =
let
Expand All @@ -109,9 +110,12 @@
};
in
''
database_file=$(mktemp database.XXXX)
run-migrations server/migrations "$database_file"
simple-http-server --index --port 8001 frontend &
PID_FRONTEND=$!
cargo run -- --listen-address 0.0.0.0:8002 &
cargo run -- --listen-address 0.0.0.0:8002 --database-url "sqlite://$database_file" &
PID_BACKEND=$!
tinyproxy -d -c ${proxyConfig} &
PID_PROXY=$!
Expand All @@ -125,9 +129,22 @@
trap cleanup SIGINT
wait $PID_FRONTEND $PID_BACKEND $PID_PROXY
rm -rf "$database_file"
'';
};

run-migrations = pkgs.writeShellApplication {
name = "run-migrations";
runtimeInputs = [ pkgs.sqlite ];
text = ''
>&2 echo "Applying migrations"
for migration_file in "$1"/*.sql; do
>&2 echo "Applying migration: $migration_file"
sqlite3 "$2" < "$migration_file"
done
'';
};

server-deps = craneLib.buildDepsOnly commonAttrs;

server-docs = craneLib.cargoDoc (
Expand All @@ -142,6 +159,10 @@
// {
cargoArtifacts = self'.packages.server-deps;
meta.mainProgram = "server";
passthru = {
migrations = ./server/migrations;
inherit (self'.packages) run-migrations;
};
}
);

Expand Down
15 changes: 15 additions & 0 deletions nixos/modules/server.nix
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ let
optionals
;
cfg = config.services.server;
stateDirectory = "/var/lib/server";
databasePath = "/var/lib/server/database.db";
in
{
options.services.server = {
Expand Down Expand Up @@ -37,6 +39,15 @@ in
'';
};

database_url = mkOption {
type = types.str;
default = "sqlite://${databasePath}";
example = "sqlite://${databasePath}";
description = ''
SQlite database to connect to.
'';
};

metrics = {
enable = lib.mkEnableOption "Prometheus metrics server";

Expand Down Expand Up @@ -75,6 +86,8 @@ in
[
"--listen-address"
"${cfg.address}:${toString cfg.port}"
"--database-url"
"sqlite://${databasePath}"
]
++ optionals cfg.metrics.enable [
"--metrics-listen-address"
Expand All @@ -92,9 +105,11 @@ in
RUST_LOG = cfg.logLevel;
};
serviceConfig = {
ExecStartPre = "${lib.getExe cfg.package.passthru.run-migrations} ${cfg.package.passthru.migrations} ${databasePath}";
ExecStart = "${lib.getExe cfg.package} ${args}";
Restart = "always";
DynamicUser = true;
StateDirectory = baseNameOf stateDirectory;
};
};
};
Expand Down

0 comments on commit 8047d24

Please sign in to comment.