1{ config, lib, ... }:
2
3let
4 cfg = config.nix.optimise;
5in
6
7{
8 options = {
9 nix.optimise = {
10 automatic = lib.mkOption {
11 default = false;
12 type = lib.types.bool;
13 description = "Automatically run the nix store optimiser at a specific time.";
14 };
15
16 dates = lib.mkOption {
17 default = [ "03:45" ];
18 apply = lib.toList;
19 type = with lib.types; either singleLineStr (listOf str);
20 description = ''
21 Specification (in the format described by
22 {manpage}`systemd.time(7)`) of the time at
23 which the optimiser will run.
24 '';
25 };
26
27 randomizedDelaySec = lib.mkOption {
28 default = "1800";
29 type = lib.types.singleLineStr;
30 example = "45min";
31 description = ''
32 Add a randomized delay before the optimizer will run.
33 The delay will be chosen between zero and this value.
34 This value must be a time span in the format specified by
35 {manpage}`systemd.time(7)`
36 '';
37 };
38
39 persistent = lib.mkOption {
40 default = true;
41 type = lib.types.bool;
42 example = false;
43 description = ''
44 Takes a boolean argument. If true, the time when the service
45 unit was last triggered is stored on disk. When the timer is
46 activated, the service unit is triggered immediately if it
47 would have been triggered at least once during the time when
48 the timer was inactive. Such triggering is nonetheless
49 subject to the delay imposed by RandomizedDelaySec=. This is
50 useful to catch up on missed runs of the service when the
51 system was powered down.
52 '';
53 };
54 };
55 };
56
57 config = {
58 assertions = [
59 {
60 assertion = cfg.automatic -> config.nix.enable;
61 message = ''nix.optimise.automatic requires nix.enable'';
62 }
63 ];
64
65 systemd = lib.mkIf config.nix.enable {
66 services.nix-optimise = {
67 description = "Nix Store Optimiser";
68 # No point this if the nix daemon (and thus the nix store) is outside
69 unitConfig.ConditionPathIsReadWrite = "/nix/var/nix/daemon-socket";
70 serviceConfig.ExecStart = "${config.nix.package}/bin/nix-store --optimise";
71 startAt = lib.optionals cfg.automatic cfg.dates;
72 # do not start and delay when switching
73 restartIfChanged = false;
74 };
75
76 timers.nix-optimise = lib.mkIf cfg.automatic {
77 timerConfig = {
78 RandomizedDelaySec = cfg.randomizedDelaySec;
79 Persistent = cfg.persistent;
80 };
81 };
82 };
83 };
84}