modules/port-magic: full module rework

This commit is contained in:
Max Headroom 2022-06-18 01:57:06 +02:00
parent 6a07e436c6
commit 911f7269ac
2 changed files with 81 additions and 50 deletions

View file

@ -1,56 +1,11 @@
{ config, lib, ... }: { config, lib, ... }:
with builtins;
with lib; with lib;
let {
cfg = config.reservedPorts; options.links = mkOption {
type = types.attrsOf (types.submodule ./link.nix);
portNames = config.reservePortsFor; description = "Port Magic links.";
portHash = flip pipe [
(hashString "md5")
(substring 0 7)
(hash: (fromTOML "v=0x${hash}").v)
(flip mod cfg.amount)
(add cfg.start)
];
ports = genAttrs portNames portHash;
portsEnd = cfg.start + cfg.amount;
in {
options = {
reservedPorts = {
amount = mkOption {
type = types.int;
default = 10000;
description = "Amount of ports to reserve at most.";
};
start = mkOption {
type = types.int;
default = 30000;
description = "Starting point for reserved ports.";
};
};
reservePortsFor = mkOption {
type = types.listOf types.str;
default = [];
description = "List of application names for which to automatically reserve ports.";
};
ports = mkOption {
type = types.attrsOf (types.ints.between cfg.start portsEnd);
default = {}; default = {};
description = "Named network ports.";
};
portsStr = mkOption {
readOnly = true;
type = types.attrsOf types.str;
description = "Named network ports, as strings.";
};
};
config = lib.mkIf (config.reservePortsFor != []) {
inherit ports;
portsStr = mapAttrs (_: toString) ports;
}; };
} }

View file

@ -0,0 +1,76 @@
{ config, lib, name, ... }:
with builtins;
with lib;
let
cfg = config;
portHash = flip pipe [
(hashString "md5")
(substring 0 7)
(hash: (fromTOML "v=0x${hash}").v)
(flip mod cfg.reservedPorts.amount)
(add cfg.reservedPorts.start)
];
in
{
options = {
ipv4 = mkOption {
type = types.str;
default = "127.0.0.1";
description = "The IPv4 address.";
};
hostname = mkOption {
type = types.str;
description = "The hostname.";
};
port = mkOption {
type = types.int;
description = "The TCP or UDP port.";
};
portStr = mkOption {
type = types.str;
description = "The TCP or UDP port, as a string.";
};
reservedPorts = {
amount = mkOption {
type = types.int;
default = 10000;
description = "Amount of ports to reserve at most.";
};
start = mkOption {
type = types.int;
default = 30000;
description = "Starting point for reserved ports.";
};
};
protocol = mkOption {
type = types.str;
description = "The protocol in URL scheme name format.";
};
path = mkOption {
type = types.nullOr types.path;
default = null;
description = "The resource path.";
};
url = mkOption {
type = types.str;
description = "The URL.";
};
tuple = mkOption {
type = types.str;
description = "The hostname:port tuple.";
};
};
config = mkIf true {
hostname = mkDefault cfg.ipv4;
port = mkDefault (portHash name);
portStr = toString cfg.port;
tuple = "${cfg.hostname}:${cfg.portStr}";
url = "${cfg.protocol}://${cfg.hostname}:${cfg.portStr}${if cfg.path == null then "" else cfg.path}";
};
}