Files
hearth/docs/affine-native.md
yukkop 50c4efc09b
runner nix smoke / nix label and flake smoke (push) Failing after 1m12s
gpt in affine
2026-11-01 11:21:28 +00:00

289 lines
14 KiB
Markdown

# Native AFFiNE NixOS module
`hectic.services.affine` runs the source-built AFFiNE backend without Docker.
It is opt-in and uses distinct `affine-native` and `affine-native-migrate`
units, so enabling or importing the module does not alter an existing
`affine.service` or Compose deployment.
## Building and checking
The package targets `x86_64-linux` and pins AFFiNE 0.27.4. It builds the server,
Rust server-native binding, all three web/admin/mobile web bundles, and matching
Prisma 6.8.2 engines from source. Toolchains and dependency caches are fixed
inputs. No AFFiNE application binary or OCI image is used.
The backend license is marked unfree. For local development/testing, explicitly
allow evaluation without changing machine-wide Nixpkgs configuration:
```sh
NIXPKGS_ALLOW_UNFREE=1 nix build --impure .#affine --option post-build-hook ''
NIXPKGS_ALLOW_UNFREE=1 nix build --impure .#checks.x86_64-linux.affine-runtime --option post-build-hook ''
nix build .#checks.x86_64-linux.affine-module-basic --option post-build-hook ''
```
Do not publish server/native artifacts to a shared binary cache without checking
their redistribution terms. Allowing unfree evaluation does not grant production
or redistribution rights. The runtime check uses a fresh PostgreSQL 16 database,
pgvector, a non-superuser application role, and a private Redis instance. It tests
both migration passes, server startup, assets, administrator setup, authentication,
workspace creation, and disabled public signup.
## Runtime contract
The selected package must provide:
- `bin/affine-server`, the long-running backend;
- `bin/affine-migrate`, the full upstream predeploy sequence, including private
key setup, Prisma schema migrations, and AFFiNE data migrations.
Both units run as the static `affine-native` system user. systemd manages
`/var/lib/affine-native` with mode `0700`. `HOME` points there, so upstream uses
`/var/lib/affine-native/.affine/config` and
`/var/lib/affine-native/.affine/storage`.
The module writes an initial `config.json` only when none exists. It seeds the
external URL, server name, loopback listener, port, disabled public/OAuth
signup, and disabled copilot. Later admin-panel or manual edits are retained.
Use `settings` only to extend or override this initial seed.
## Isolated local example
This example deliberately creates a new database, Redis instance, state path,
and secret file. Do not point an initial native deployment at a production
AFFiNE database.
```nix
{ config, lib, pkgs, ... }:
{
nixpkgs.config.allowUnfreePredicate = package:
builtins.elem (lib.getName package) [ "affine" "affine-server-native" ];
services.postgresql = {
enable = true;
package = pkgs.postgresql_16;
ensureDatabases = [ "affine-native" ];
ensureUsers = [{
name = "affine-native";
ensureDBOwnership = true;
}];
extensions = ps: [ ps.pgvector ];
};
services.redis.servers.affine-native = {
enable = true;
port = 6388;
bind = "127.0.0.1";
};
# DATABASE_URL: postgresql://affine-native@localhost/affine-native?host=/run/postgresql
sops.secrets.affine-native-database-url = {};
sops.templates."affine-native.env" = {
owner = "affine-native";
group = "affine-native";
mode = "0400";
content = ''
DATABASE_URL=${config.sops.placeholder.affine-native-database-url}
'';
};
hectic.services.affine = {
enable = true;
environmentFile = config.sops.templates."affine-native.env".path;
externalUrl = "http://localhost:3011";
redisHost = "127.0.0.1";
redisPort = 6388;
};
# This example runs both dependencies locally, so order migration after them.
systemd.services.affine-native-migrate = {
after = [ "postgresql.service" "redis-affine-native.service" ];
requires = [ "postgresql.service" "redis-affine-native.service" ];
};
# pgvector is not a trusted extension; provision it as postgres, not the app role.
systemd.services.affine-native-database = {
requires = [ "postgresql.service" ];
after = [ "postgresql.service" ];
before = [ "affine-native-migrate.service" ];
requiredBy = [ "affine-native-migrate.service" ];
serviceConfig = {
Type = "oneshot";
User = "postgres";
RemainAfterExit = true;
};
script = ''
${pkgs.postgresql_16}/bin/psql --dbname=affine-native --set=ON_ERROR_STOP=1 \
--command='CREATE EXTENSION IF NOT EXISTS vector;'
'';
};
}
```
The module never creates PostgreSQL, pgvector, Redis, reverse-proxy, or
firewall configuration. `environmentFile` is required and is passed to systemd
at runtime; put `DATABASE_URL`, Redis credentials, and other secrets there,
never in Nix module values or the Nix store. Non-secret Redis host and port
options map to upstream `REDIS_SERVER_HOST` and `REDIS_SERVER_PORT`.
Default binding is `127.0.0.1:3011`. Perform initial administration through an
SSH tunnel, for example `ssh -L 3011:127.0.0.1:3011 host`, then browse to
`http://localhost:3011`. Add a reverse proxy separately only when remote access
is intended.
## Upgrades and rollback
`affine-native-migrate.service` is required by and ordered before
`affine-native.service`. Package or initial-seed changes restart the migration
unit before the app, and the package wrapper owns the complete upstream
predeploy procedure.
Database schema and AFFiNE data migrations are not reversed by switching to an
older NixOS generation. Back up the dedicated database and state directory
before upgrades. Production migration remains a separate, explicit operation.
AFFiNE backend source has its own license; review it before production use.
This module does not grant production authorization or alter upstream license
terms.
## hectic-lab host configuration
`nixos/system/hectic-lab/affine.nix` stages the reusable native module alongside
the original deployment. `hectic.affineDeployment.nativeActive` defaults to
`false`: the legacy Docker units and nginx port 3010 remain selected. The old
configuration is preserved in `affine-docker.nix` for staging and rollback.
Set `nativeActive = true` only after the final frozen-state restore and native
verification; this removes the legacy unit declarations and selects nginx port
3011. Source declarations alone are not evidence that production has migrated.
The host configuration intentionally uses isolated dependencies:
| Component | Unit | Endpoint/state |
| --- | --- | --- |
| AFFiNE | `affine-native.service` | `127.0.0.1:3011`, `/var/lib/affine-native` |
| Migration | `affine-native-migrate.service` | Same user, environment and state |
| PostgreSQL 16 | `affine-postgresql.service` | Unix socket `/run/affine-postgresql`, port 5433, `/var/lib/affine-postgresql` |
| Redis | `redis-affine.service` | `127.0.0.1:6388` |
| ChatGPT connector | `affine-chatgpt.service` | `127.0.0.1:3012`, separate protected state |
The database cluster does not listen on TCP and does not replace the host's
shared `postgresql.service`. It uses peer authentication, a non-superuser role
and database named `affine-native`, and pgvector `0.8.7` from the pinned
official release. PostgreSQL pre-creates `vector` and `pgcrypto` as its cluster
administrator. The cluster locale matches the existing Docker database's
`en_US.utf8`; do not silently substitute a different collation.
Both AFFiNE units are gated by `/var/lib/affine-native/environment`. Create that
file only after staging the correct database/config/storage. It must be
protected outside Git and the Nix store. Its required connection settings are:
```text
DATABASE_URL=postgresql://affine-native@localhost:5433/affine-native?host=/run/affine-postgresql
AFFINE_INDEXER_ENABLED=false
```
The database URL contains no password because the Unix socket uses peer auth.
The environment file may also carry secrets; treat the entire file as private.
## Docker-to-native migration procedure
1. Build the source package, exact pgvector version, native service units and
targeted checks before scheduling an outage. Inspect the activation plan;
do not restart the shared PostgreSQL cluster or unrelated Redis instances.
2. Inventory the running AFFiNE revision, database extensions/locale, workspace
and user counts, config/private key, storage file manifest and nginx route.
Never print secret values or document contents.
3. Make an owner-only custom-format PostgreSQL backup and config/storage
snapshot. Verify `pg_restore --list`, archive readability and checksums.
A listed archive is not a tested restore or an offsite backup.
4. Start only the dedicated PostgreSQL and Redis units. Restore a rehearsal
dump into their isolated database, preserving role ownership. Pre-created
extensions avoid giving the application superuser privileges. Use
`pg_restore --exit-on-error --no-owner --no-acl --no-comments
--role=affine-native`; investigate any error instead of ignoring it.
5. Copy the complete Docker config and storage to
`/var/lib/affine-native/.affine/{config,storage}`. Preserve `private.key`
byte-for-byte. Give the native account ownership and private permissions.
Update copied server/listen/port and Redis settings for native paths;
preserve authentication, external URL and all encryption material.
6. Run migration/startup against the rehearsal database and copied storage
only. Never point staging workers at the live Docker database/storage.
Verify `/info` reports `selfhosted` and compatibility `0.27.4`, then test
authenticated workspaces, representative documents and stored attachments.
7. Announce the write freeze. Stop all Docker AFFiNE application/worker writers
without deleting its PostgreSQL volume. Take a fresh final dump and final
config/storage snapshot after the freeze. Restore that final snapshot into
a clean native database; stop staging units before replacing state.
8. Start native migration and application units. Verify entity counts,
checksums, login, documents, attachments and readiness before switching
`hectic.affineDeployment.nativeActive` to `true` and nginx from port 3010 to
3011. Inspect the activation plan and test nginx configuration first.
9. Confirm the public HTTPS route, WebSockets/live editing and signup policy.
Confirm the cutover removed/disabled the old Docker `affine.service` and
`affine-frontend.service`. Retain their image/config/data and final snapshot;
do not delete old state as part of cutover.
10. Configure the [native ChatGPT connector](./affine-chatgpt.md) through AFFiNE's
administrator API/UI and verify an actual AFFiNE AI request, not only a
direct upstream probe.
Before native production writes, rollback can return nginx/application to the
frozen Docker state. After native writes begin, that state is stale: rollback
requires a new consistent export and compatible restore, not a proxy flip to
an old database. NixOS generation rollback alone does not restore application
data.
If SSH, package copying, extension build, rehearsal restore or verification is
blocked, leave the Docker production route intact. Do not create the runtime
environment marker or activate a half-prepared native application.
## Completed hectic-lab cutover: 2026-10-31
Production now explicitly sets `hectic.affineDeployment.nativeActive = true`.
The activated persistent NixOS generation is:
```text
/nix/store/6vp7qb6id8krb9l5ff1dkdi7nzxifhwd-nixos-system-hectic-lab-26.05.20261006.b253099
```
Final write-frozen backup:
```text
/var/backups/affine/native-cutover-20261031T231824Z
```
The backup directory is `0700`; database/config/storage archives are `0600`.
It includes the final database dump, verified archive listings, config and
storage snapshots, previous generation references, and matching before/after
data fingerprints. Keep it private. It is local recovery material, not an
offsite backup.
Cutover verification matched all rows/fingerprints in `users`, `workspaces`,
`workspace_members`, `workspace_pages`, `snapshots`, `updates`, and `blobs`:
5 users, 2 workspaces, 5 memberships, 44 pages, 53 snapshots, 0 pending update
rows, and 49 blob records. All 98 storage files (19,341,496 bytes) and the
original `private.key` were preserved. Rehearsal authenticated document bytes
and a 3,049,505-byte attachment matched the Docker source; final HTTPS login,
document reads, attachment retrieval and frontend assets passed.
The final `switch-to-configuration switch` completed successfully. The Docker
AFFiNE application/PostgreSQL/Redis containers are gone; their original
`/var/lib/affine` state remains retained. The host Docker daemon still serves
unrelated applications and was not removed.
The staging `test` activation encountered a pre-existing D-Bus reload timeout
(the journal also records it on 2026-10-10); the bus remained active and was
not restarted. The final cutover activation did not reload D-Bus and completed
successfully. Shared `postgresql.service` remained active throughout.
The native [ChatGPT connector](./affine-chatgpt.md) is enabled through the
workspace's persistent BYOK profile `ChatGPT subscription`. Text and function
probes were verified, and an actual AFFiNE SSE chat returned the expected
response with both explicit and automatic provider selection. Two authenticated
WebSocket connections joined the workspace and read identical document state
without writing documents.
After restarting both native AFFiNE and the connector, public login, document
and attachment reads, two-client WebSocket reads, and an automatic-routed AI
chat associated with an existing document passed again. Local validation also
passed 61 connector tests, Pyright with its Nix Python environment, and the
runtime, typography, native-module, production and connector Nix checks.