den icon indicating copy to clipboard operation
den copied to clipboard

add finix class to den?

Open unazikx opened this issue 3 months ago • 1 comments

hi, how i can implement https://github.com/finix-community/finix class to den? it uses nixosConfigurations but use own instantinate inputs.finix.lib.finixSystem, how i can make this to use as well?

unazikx avatar Aug 27 '26 04:08 unazikx

Using a Third-Party NixOS-Style Builder (finix) with Den

Integrating third-party NixOS-style system builders—such as Finix—into a Den flake workspace requires understanding how Den manages module collection, builder invocation, and output attribute paths.

This tutorial provides a complete architectural guide and three practical integration patterns for wiring Finix hosts into a Den-managed fleet.


1. Overview & Finix Project Context

Finix is a minimal Linux distribution derived from NixOS base modules, designed for low-resource footprint or container environments. Key differences from standard NixOS include:

  • Init System: Uses finit (Fast Init) instead of systemd.
  • Device & Seat Management: Uses mdevd (instead of udev) and seatd (instead of logind).
  • Flake Entrypoint: Uses inputs.finix.lib.finixSystem { modules = [ ... ]; } to evaluate configurations instead of nixpkgs.lib.nixosSystem.

In Den, system configuration evaluation and flake output generation are managed through three decoupled concepts:

  1. Classes (den.classes.<name>): Named payload buckets (e.g. nixos, darwin, homeManager, droid, k8s-manifests, finix). When an aspect defines a top-level key matching a registered class name (e.g. finix = { ... };), Den collects those modules for target entities during policy resolution.
  2. Instantiate Thunks (instantiate = { modules, ... }: ...): A function that receives all Den-collected class modules for an entity and invokes the target builder (inputs.finix.lib.finixSystem).
  3. Flake Output Binding (intoAttr = [ "nixosConfigurations" host.name ]): An attribute path specification telling Den where on the output flake attribute set to place the evaluated system object.

2. Background: How Den Builds nixosConfigurations

For each host in den.hosts, Den resolves the host's active aspects into a list of collected class modules (for a nixos host, everything declared under the nixos class key, plus a default { nixpkgs.hostPlatform = lib.mkDefault host.system; } module), then invokes:

host.instantiate {
  modules = [
    host.mainModule
    { nixpkgs.hostPlatform = lib.mkDefault host.system; }
  ];
}

Den then places the resulting evaluation object at flake.${lib.concatStrings host.intoAttr}.

Core Class Defaults Table

By default, Den ships with pre-registered defaults in den/nix/lib/entities/host.nix:

host.class Default instantiate Builder Default intoAttr Output Path
nixos inputs.nixpkgs.lib.nixosSystem [ "nixosConfigurations" host.name ]
darwin inputs.darwin.lib.darwinSystem [ "darwinConfigurations" host.name ]
systemManager inputs.system-manager.lib.makeSystemConfig [ "systemConfigs" host.name ]

(See reference/output.mdx ["Build pipeline"] and reference/schema.mdx in the Den docs).

Key Observations for Finix Integration

  1. The Builder is Just a Function: From Den's perspective, inputs.nixpkgs.lib.nixosSystem and inputs.finix.lib.finixSystem have the same functional contract: take modules (plus builder-specific args such as pkgs, system, modulesPath, or specialArgs), and return an evaluated configuration attrset. Swapping builders is a plain option override.
  2. Output Placement is Data: intoAttr is a simple list of path segments on the flake. Placed outputs appear under nixosConfigurations or finixConfigurations automatically.
  3. ⚠️ Edge Case 1 — Evaluation Crash on Unknown Class: Default instantiate and intoAttr option implementations perform a lookup indexed by config.class (.{config.class}). If a host sets class = "finix" without supplying explicit overrides for instantiate and intoAttr, evaluation will crash with attribute 'finix' missing. Supplying explicit values via per-host options (Option A) or den.schema.host.imports (Option B) bypasses this lookup completely.
  4. ⚠️ Edge Case 2 — Class Bucket Isolation & Aspect Routing: Den collects the class bucket matching host.class. If existing aspects write module config under nixos = { ... }; and you declare class = "finix", those nixos blocks are ignored for that host by default. Remedy: register a route policy forwarding nixos class content into finix (shown in Option B). This makes Option A (keep class = "nixos", swap only the builder thunk) the lowest-friction starting point.
  5. Declaration Precedence & mkForce: Plain option declarations override mkOption defaults and mkDefault blocks (such as the channel-aware instantiate override in modules/den/schema/host.nix). lib.mkForce is only required when overriding another explicit plain assignment.

3. Integration Patterns

Option A — Minimal: Per-Host instantiate Override (Start Here)

Since Finix is a NixOS-compatible base (it accepts standard NixOS modules in finixSystem), the simplest integration keeps class = "nixos" intact—allowing all existing nixos-class aspects and batteries to keep working—and swaps only the builder thunk on specific Finix hosts:

# modules/den.nix (or inside den.hosts)
{
  den.hosts.x86_64-linux.finix-box = {
    # class stays "nixos" (default), intoAttr stays [ "nixosConfigurations" "finix-box" ] (default).
    # Only the builder thunk is overridden:

    instantiate =
      { modules, ... }:
      inputs.finix.lib.finixSystem {
        inherit modules;
        # finixSystem builder arguments (adjust to finix's current flake API):
        pkgs = import inputs.nixpkgs {
          system = config.system;
          config.allowUnfree = true;
        };
        # finix's base modules path:
        modulesPath = inputs.finix.modulesPath;
        # Expose flake inputs to finix/NixOS modules:
        specialArgs = { inherit inputs; };
      };

    includes = [ den.aspects.base ];
  };
}

Result: .#nixosConfigurations.finix-box is evaluated using inputs.finix.lib.finixSystem instead of lib.nixosSystem, while consuming the standard nixos class modules collected from the host's aspects.

Technical Details & Variants:

  • Builder Arguments: pkgs, modulesPath, and specialArgs are owned by the builder. Den only supplies modules. Flake inputs are in scope wherever the module defining instantiate is evaluated.
  • hostPlatform Handling: Den automatically appends { nixpkgs.hostPlatform = lib.mkDefault host.system; } to modules for hosts without an explicit pkgs option. Since finixSystem evaluates standard NixOS options, this resolves seamlessly.
  • Fleet-Wide Variant: If every nixos-class host should evaluate through Finix, apply the override at the schema level instead of per-host:
    den.schema.host.imports = [
      (
        { config, ... }:
        lib.mkIf (config.class == "nixos") {
          instantiate = { modules, ... }: inputs.finix.lib.finixSystem { inherit modules; pkgs = import inputs.nixpkgs { system = config.system; }; specialArgs = { inherit inputs; }; };
        }
      )
    ];
    
  • Module Import Variant: If you only need Finix's base modules (e.g. shared modules) but standard nixosSystem output is acceptable, import those modules directly into your aspects without swapping the builder thunk.

Option B — Fleet-Wide: Custom finix OS Class

If you operate a fleet of Finix machines and want the builder and output namespace to be a first-class property of the host (class = "finix"), register the class and provide class-scoped instantiate/intoAttr defaults via a schema import.

This pattern mirrors the structure of the Nix-on-Droid battery in nix-on-droid.nix, which defines class = "droid" with inputs.nix-on-droid.lib.nixOnDroidConfiguration and intoAttr = [ "nixOnDroidConfigurations" config.name ].

Step 1: Define the Finix Battery (modules/den/batteries/finix.nix)

# modules/den/batteries/finix.nix
{
  den,
  lib,
  inputs,
  ...
}:
{
  # 1. Register 'finix' in Den's class registry so aspects can write under finix = { ... }
  den.classes.finix.description = "finix (finix-community) system modules";

  # 2. Class-scoped instantiation schema import.
  # lib.mkIf (config.class == "finix") leaves nixos/darwin hosts untouched.
  den.schema.host.imports = [
    (
      { config, ... }:
      lib.mkIf (config.class == "finix") {
        instantiate =
          { modules, ... }:
          inputs.finix.lib.finixSystem {
            inherit modules;
            pkgs = import inputs.nixpkgs {
              system = config.system;
              config.allowUnfree = true;
            };
            modulesPath = inputs.finix.modulesPath;
            specialArgs = { inherit inputs; };
          };

        # Direct output placement:
        intoAttr = [
          "nixosConfigurations" # Keep finix hosts under nixosConfigurations...
          config.name           # ...or use "finixConfigurations" for a distinct namespace
        ];
      }
    )
  ];

  # 3. Forward existing 'nixos' aspect blocks into 'finix' class for finix hosts
  den.policies.nixos-to-finix =
    { host, ... }:
    lib.optional (host.class == "finix") (
      den.lib.policy.route {
        fromClass = "nixos";
        intoClass = "finix";
        path = [ ]; # top-level merge
      }
    );

  # Register policy in global default scope so it fires in all scopes where host is bound
  den.default.includes = [ den.policies.nixos-to-finix ];
}

Step 2: Declare Hosts and Aspects (modules/den.nix)

# modules/den.nix
{
  imports = [ ./den/batteries/finix.nix ];

  den.hosts.x86_64-linux = {
    finix-1 = { class = "finix"; users.alice = { }; };
    finix-2 = { class = "finix"; };
    plain-nixos = { }; # untouched, still lib.nixosSystem -> nixosConfigurations
  };

  # Aspects can now target 'finix' explicitly or rely on policy.route from 'nixos'
  den.aspects.base = {
    finix = { config, pkgs, ... }: {
      services.finit.enable = true;
    };
  };
}

Technical Notes on Class Selection & Home Manager:

  • Aspect Compatibility: Built-in batteries emitting ${host.class}.... (hostname, users, home-manager bridges) emit finix.... on Finix hosts. Since finixSystem evaluates NixOS modules, these options evaluate natively.
  • Inert Option Shims: If a Finix base module lacks an option emitted by a global battery, use the option shim technique shown in nix-on-droid.nix.
  • Home Manager Bridge: If a Finix host requires Home Manager and inputs.home-manager has no finixModules attribute, use Den's den.lib.home-env.makeHomeEnv bridge (see the droidHome block in nix-on-droid.nix) to forward collected homeManager class payload.

Option C — Custom Non-OS Class Feeding Third-Party Tools

If you want aspects to declare structured content that a third-party tool assembles into something other than a host system (such as Kubernetes manifests via Nixidy, infrastructure via Terranix, or custom disk/OCI images), use den.lib.policy.instantiate with a custom class.

This pattern is documented in reference/policies.mdx (policy.instantiate spec) and demonstrated in tutorials/terranix-demo.mdx.

3-Step Walkthrough:

  1. Register a Custom Class:

    den.classes.k8s-manifests.description = "Kubernetes manifests collected for nixidy";
    

    (Note: For non-module structured payload such as lists of CRDs, manifests, or environment variables, register a companion quirk via den.quirks.* instead. See guides/quirks.mdx and nixidy.nix).

  2. Write Aspects Emitting Payload:

    den.aspects.monitoring = {
      k8s-manifests = { charts, ... }: {
        charts = [ { chart = charts.grafana.grafana; name = "grafana"; } ];
      };
    };
    
  3. Instantiate via Policy & Builder:

    den.policies.cluster-to-nixidy =
      { cluster, system, ... }:
      [
        (den.lib.policy.instantiate {
          name = cluster.name;
          class = "k8s-manifests"; # Bucket to collect
          instantiate =
            { modules, ... }:
            inputs.nixidy.lib.mkEnv {
              inherit modules; # Den-collected class modules
            };
          intoAttr = [ "nixidyEnvs" system cluster.name ]; # Flake output path
        })
      ];
    

    (Working reference: cluster-to-nixidy policy in clusters.nix).

    Per-Host Image Artifact Variant: To generate custom per-host Finix disk or OCI images alongside host system configs:

    den.policies.host-to-finix-image =
      { host, ... }:
      [
        (den.lib.policy.instantiate {
          name = host.name;
          class = "nixos";
          instantiate =
            { modules, ... }:
            <image-builder> { inherit modules; };
          intoAttr = [ "finixImages" host.system host.name ];
        })
      ];
    

    Per-entity isolation is automatic: policy.instantiate collects only from the target entity's scope subtree, guaranteeing host A's modules never leak into host B's artifact.


4. Decision Guide

Requirement / Goal Pattern Explanation
One or a few hosts build through finixSystem instead of nixosSystem Option A (Per-host override) Simplest path. Keeps class = "nixos" and intoAttr = [ "nixosConfigurations" ... ].
Every nixos host should build through finixSystem fleet-wide Option A Variant (Schema-scoped override) Overrides default instantiate for config.class == "nixos" fleet-wide.
A fleet of Finix hosts where builder and namespace are host properties Option B (class = "finix" + schema import) Explicit class separation. Pairs with den.policies.nixos-to-finix to reuse nixos aspects.
Assemble Finix/NixOS aspects into non-OS artifacts (disk images, OCI images, K8s manifests) Option C (Custom den.classes.* + policy.instantiate) Collects class modules across entities and feeds third-party builder functions (e.g. Nixidy, Terranix).

Composition Note: Options A and B compose seamlessly with Option C. A host can evaluate finixSystem for its root system while using custom classes for extra build artifacts.


5. Checklist & Gotchas

  • pkgs Handling: Den's instantiate thunk convention is pkgs-less. The thunk imports or builds pkgs internally. Do not introduce a host-wide pkgs option, as it alters spec ? pkgs detection across all hosts (see NOTE on pkgs in nix-on-droid.nix).
  • finit, Not systemd: Finix replaces systemd with finit. Aspect modules emitting systemd.services.* or systemd.tmpfiles will fail unless guarded:
    guard = { options, ... }: options ? services.finit;
    
  • specialArgs: inputs is in scope wherever instantiate is defined. Passing specialArgs = { inherit inputs; }; is standard for forwarding flake inputs to modules.
  • Output Naming: Den auto-disambiguates output collision paths. Setting intoAttr = [ "nixosConfigurations" config.name ] places Finix configurations alongside NixOS configurations.
  • Skipping Output Placement (intoAttr = [ ]): Setting intoAttr = [ ] suppresses output binding (useful for child configs consumed by parent builders).
  • Class vs. Quirk: Use classes when payload aspects emit NixOS/Finix modules. Use quirks (den.quirks.*) when payload aspects emit raw structured data.

6. End-to-End Minimal Example

Below is a complete, minimal flake wiring Den + Finix matching Den's official templates/minimal shape (flake.nix shell using import-tree + modules/den.nix importing inputs.den.flakeModule):

# flake.nix — exact shell from Den's templates/minimal
{
  description = "Minimal Den flake with a finix host";

  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
    import-tree.url = "github:vic/import-tree";
    den.url = "github:denful/den";
    finix.url = "github:finix-community/finix";
  };

  outputs =
    inputs:
    (inputs.nixpkgs.lib.evalModules {
      modules = [ (inputs.import-tree ./modules) ];
      specialArgs = { inherit inputs; };
    }).config.flake;
}
# modules/den.nix
{
  den,
  lib,
  inputs,
  ...
}:
{
  imports = [ inputs.den.flakeModule ];

  den.classes.finix.description = "finix system configuration";

  den.schema.host.imports = [
    (
      { config, ... }:
      lib.mkIf (config.class == "finix") {
        instantiate =
          { modules, ... }:
          inputs.finix.lib.finixSystem {
            inherit modules;
            pkgs = import inputs.nixpkgs { system = config.system; };
            modulesPath = inputs.finix.modulesPath;
            specialArgs = { inherit inputs; };
          };
        intoAttr = [
          "nixosConfigurations"
          config.name
        ];
      }
    )
  ];

  den.aspects.base = {
    finix =
      { config, pkgs, ... }:
      {
        networking.hostName = "slab";
      };
  };

  den.hosts.x86_64-linux.slab = {
    class = "finix";
    includes = [ den.aspects.base ];
  };
}

Verification Commands

# Evaluate the generated Finix configuration
nix eval .#nixosConfigurations.slab.config.networking.hostName

# Build the system toplevel derivation
nix build .#nixosConfigurations.slab.config.system.build.toplevel

7. Further Reading & References

Den Documentation Surface (in Den Repository docs/src/content/docs/)

  • reference/output.mdx — Build pipeline, custom instantiation, custom output paths, den.systems
  • reference/policies.mdx — policy.instantiate, policy.route, policy.provide specs
  • guides/custom-classes.mdx — Declaring custom classes, forwardTo/parentPath class fields, worked examples
  • guides/quirks.mdx — Non-module payload channels
  • reference/schema.mdx — Host/Home option reference (class, instantiate, intoAttr)
  • tutorials/terranix-demo.mdx — Complete third-party tool integration example (Terranix)
  • templates/minimal — Minimal flake shape to copy from

Working References (sini/nix-config at Commit 01c9391efbdc)

  1. modules/den/batteries/nix-on-droid.nix — Custom OS class (class = "droid") + custom builder + custom output + Home Manager bridge.
  2. modules/den/schema/host.nix — Fleet-level host schema with channel-aware mkDefault instantiate/home-manager.module.
  3. modules/den/batteries/nixidy.nix — Custom class + quirk registration, flake-level outputs derived from Den pipeline output.
  4. modules/den/policies/clusters.nix — policy.instantiate with a third-party builder (mkEnv) per cluster/system.

sini avatar Aug 27 '26 20:08 sini