1{ config, lib, ... }:
2
3let
4 cfg = config.nix.gc;
5in
6
7{
8
9 ###### interface
10
11 options = {
12
13 nix.gc = {
14
15 automatic = lib.mkOption {
16 default = false;
17 type = lib.types.bool;
18 description = "Automatically run the garbage collector at a specific time.";
19 };
20
21 dates = lib.mkOption {
22 type = with lib.types; either singleLineStr (listOf str);
23 apply = lib.toList;
24 default = [ "03:15" ];
25 example = "weekly";
26 description = ''
27 How often or when garbage collection is performed. For most desktop and server systems
28 a sufficient garbage collection is once a week.
29
30 This value must be a calendar event in the format specified by
31 {manpage}`systemd.time(7)`.
32 '';
33 };
34
35 randomizedDelaySec = lib.mkOption {
36 default = "0";
37 type = lib.types.singleLineStr;
38 example = "45min";
39 description = ''
40 Add a randomized delay before each garbage collection.
41 The delay will be chosen between zero and this value.
42 This value must be a time span in the format specified by
43 {manpage}`systemd.time(7)`
44 '';
45 };
46
47 persistent = lib.mkOption {
48 default = true;
49 type = lib.types.bool;
50 example = false;
51 description = ''
52 Takes a boolean argument. If true, the time when the service
53 unit was last triggered is stored on disk. When the timer is
54 activated, the service unit is triggered immediately if it
55 would have been triggered at least once during the time when
56 the timer was inactive. Such triggering is nonetheless
57 subject to the delay imposed by RandomizedDelaySec=. This is
58 useful to catch up on missed runs of the service when the
59 system was powered down.
60 '';
61 };
62
63 options = lib.mkOption {
64 default = "";
65 example = "--max-freed $((64 * 1024**3))";
66 type = lib.types.singleLineStr;
67 description = ''
68 Options given to [`nix-collect-garbage`](https://nixos.org/manual/nix/stable/command-ref/nix-collect-garbage) when the garbage collector is run automatically.
69 '';
70 };
71
72 };
73
74 };
75
76 ###### implementation
77
78 config = {
79 assertions = [
80 {
81 assertion = cfg.automatic -> config.nix.enable;
82 message = ''nix.gc.automatic requires nix.enable'';
83 }
84 ];
85
86 systemd.services.nix-gc = lib.mkIf config.nix.enable {
87 description = "Nix Garbage Collector";
88 script = "exec ${config.nix.package.out}/bin/nix-collect-garbage ${cfg.options}";
89 serviceConfig.Type = "oneshot";
90 startAt = lib.optionals cfg.automatic cfg.dates;
91 # do not start and delay when switching
92 restartIfChanged = false;
93 };
94
95 systemd.timers.nix-gc = lib.mkIf cfg.automatic {
96 timerConfig = {
97 RandomizedDelaySec = cfg.randomizedDelaySec;
98 Persistent = cfg.persistent;
99 };
100 };
101
102 };
103
104}