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