Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bfa5c61db5 | ||
|
|
3c226dab12 | ||
|
|
584cefa388 | ||
|
|
00665592f6 |
@@ -1,2 +1,4 @@
|
|||||||
*.log
|
*.log
|
||||||
.env
|
.env
|
||||||
|
web/*/node_modules/
|
||||||
|
web/*/.next/
|
||||||
|
|||||||
@@ -44,88 +44,41 @@ Keine Commits in dieser Session.
|
|||||||
Keine Änderungen ermittelbar.
|
Keine Änderungen ermittelbar.
|
||||||
|
|
||||||
---
|
---
|
||||||
## 2026-08-27 17:26 – 17:28 (1m)
|
## 2026-08-28 21:44 – 21:44 (0m)
|
||||||
**Beschreibung:** Claude Code Session
|
**Beschreibung:** Claude Code Session
|
||||||
**Projekt:** code
|
**Projekt:** nexarch
|
||||||
|
|
||||||
### Commits
|
|
||||||
- c895a67 core: initial Go module skeleton (config, db pool, tenant registry migration)
|
|
||||||
|
|
||||||
### Geänderte Dateien
|
|
||||||
- .gitignore | 2 ++
|
|
||||||
- DEVLOG.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- cmd/core/main.go | 33 +++++++++++++++++++++++++++++++++
|
|
||||||
- go.mod | 5 +++++
|
|
||||||
- internal/config/config.go | 29 +++++++++++++++++++++++++++++
|
|
||||||
- internal/db/db.go | 11 +++++++++++
|
|
||||||
- migrations/0001_tenant_registry.sql | 10 ++++++++++
|
|
||||||
|
|
||||||
---
|
|
||||||
## 2026-08-27 17:28 – 17:29 (1m)
|
|
||||||
**Beschreibung:** Claude Code Session
|
|
||||||
**Projekt:** code
|
|
||||||
|
|
||||||
### Commits
|
### Commits
|
||||||
Keine Commits in dieser Session.
|
Keine Commits in dieser Session.
|
||||||
|
|
||||||
### Geänderte Dateien
|
### Geänderte Dateien
|
||||||
- .gitignore | 2 ++
|
- .gitignore | 2 ++
|
||||||
- DEVLOG.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++
|
- web/shl/README.md | 45 +++++++++++++++++++++++++++++++++++++++++++++
|
||||||
- cmd/core/main.go | 33 +++++++++++++++++++++++++++++++++
|
- web/shl/__tests__/Dialog.test.tsx | 38 ++++++++++++++++++++++++++++++++++++++
|
||||||
- go.mod | 5 +++++
|
- web/shl/__tests__/tokens.test.ts | 39 +++++++++++++++++++++++++++++++++++++++
|
||||||
- internal/config/config.go | 29 +++++++++++++++++++++++++++++
|
- web/shl/components/Dialog.tsx | 88 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
- internal/db/db.go | 11 +++++++++++
|
- web/shl/components/FormElements.tsx | 98 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
- migrations/0001_tenant_registry.sql | 10 ++++++++++
|
- web/shl/components/Shell.tsx | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
|
- web/shl/components/Table.tsx | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
|
- web/shl/components/Toast.tsx | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
|
- web/shl/i18n/i18n.tsx | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
|
- web/shl/index.ts | 25 +++++++++++++++++++++++++
|
||||||
|
- web/shl/package.json | 23 +++++++++++++++++++++++
|
||||||
|
- web/shl/theme/ThemeProvider.tsx | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
|
- web/shl/tokens/tokens.ts | 96 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
|
- web/shl/tsconfig.json | 18 ++++++++++++++++++
|
||||||
|
|
||||||
---
|
---
|
||||||
## 2026-08-27 17:31 – 17:31 (0m)
|
## 2026-08-28 21:51 – 21:57 (5m)
|
||||||
**Beschreibung:** Claude Code Session
|
**Beschreibung:** Claude Code Session
|
||||||
**Projekt:** code
|
**Projekt:** nexarch
|
||||||
|
|
||||||
### Commits
|
### Commits
|
||||||
Keine Commits in dieser Session.
|
- 3c226da SHL-01: fix — vitest jsdom-environment + jest-dom-Setup (3 Dialog-Tests schlugen ohne DOM fehl)
|
||||||
|
|
||||||
### Geänderte Dateien
|
### Geänderte Dateien
|
||||||
- .gitignore | 2 ++
|
- web/shl/package.json | 2 ++
|
||||||
- DEVLOG.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++
|
- web/shl/vitest.config.ts | 8 ++++++++
|
||||||
- cmd/core/main.go | 33 +++++++++++++++++++++++++++++++++
|
- web/shl/vitest.setup.ts | 1 +
|
||||||
- go.mod | 5 +++++
|
|
||||||
- internal/config/config.go | 29 +++++++++++++++++++++++++++++
|
|
||||||
- internal/db/db.go | 11 +++++++++++
|
|
||||||
- migrations/0001_tenant_registry.sql | 10 ++++++++++
|
|
||||||
|
|
||||||
---
|
|
||||||
## 2026-08-27 17:36 – 17:36 (0m)
|
|
||||||
**Beschreibung:** Claude Code Session
|
|
||||||
**Projekt:** code
|
|
||||||
|
|
||||||
### Commits
|
|
||||||
Keine Commits in dieser Session.
|
|
||||||
|
|
||||||
### Geänderte Dateien
|
|
||||||
- .gitignore | 2 ++
|
|
||||||
- DEVLOG.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- cmd/core/main.go | 33 +++++++++++++++++++++++++++++++++
|
|
||||||
- go.mod | 5 +++++
|
|
||||||
- internal/config/config.go | 29 +++++++++++++++++++++++++++++
|
|
||||||
- internal/db/db.go | 11 +++++++++++
|
|
||||||
- migrations/0001_tenant_registry.sql | 10 ++++++++++
|
|
||||||
|
|
||||||
---
|
|
||||||
## 2026-08-27 17:36 – 17:37 (0m)
|
|
||||||
**Beschreibung:** Claude Code Session
|
|
||||||
**Projekt:** code
|
|
||||||
|
|
||||||
### Commits
|
|
||||||
Keine Commits in dieser Session.
|
|
||||||
|
|
||||||
### Geänderte Dateien
|
|
||||||
- .gitignore | 2 ++
|
|
||||||
- DEVLOG.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- cmd/core/main.go | 33 +++++++++++++++++++++++++++++++++
|
|
||||||
- go.mod | 5 +++++
|
|
||||||
- internal/config/config.go | 29 +++++++++++++++++++++++++++++
|
|
||||||
- internal/db/db.go | 11 +++++++++++
|
|
||||||
- migrations/0001_tenant_registry.sql | 10 ++++++++++
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
+3
-18
@@ -7,7 +7,6 @@ import (
|
|||||||
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/config"
|
"gitea.perlbach24.de/scripte/nexarch/internal/config"
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/db"
|
"gitea.perlbach24.de/scripte/nexarch/internal/db"
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/tenant"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -16,30 +15,16 @@ func main() {
|
|||||||
log.Fatalf("config: %v", err)
|
log.Fatalf("config: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx := context.Background()
|
pool, err := db.Connect(context.Background(), cfg.RegistryDSN)
|
||||||
|
|
||||||
registryPool, err := db.Connect(ctx, cfg.RegistryDSN)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("registry db: %v", err)
|
log.Fatalf("db: %v", err)
|
||||||
}
|
}
|
||||||
defer registryPool.Close()
|
defer pool.Close()
|
||||||
|
|
||||||
adminPool, err := db.Connect(ctx, cfg.AdminDSN)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("admin db: %v", err)
|
|
||||||
}
|
|
||||||
defer adminPool.Close()
|
|
||||||
|
|
||||||
registry := tenant.NewRegistry(registryPool)
|
|
||||||
provisioner := tenant.NewProvisioner(adminPool, registry, cfg.TenantDSNTemplate)
|
|
||||||
tenantHandler := tenant.NewHandler(provisioner)
|
|
||||||
|
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
|
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
})
|
})
|
||||||
// Vorlaeufiger Pfad ohne Versionierung/Auth — wird mit API-01/IAM-01 abgeloest.
|
|
||||||
mux.HandleFunc("/internal/tenants", tenantHandler.CreateTenant)
|
|
||||||
|
|
||||||
log.Printf("nexarch-core listening on %s", cfg.ListenAddr)
|
log.Printf("nexarch-core listening on %s", cfg.ListenAddr)
|
||||||
if err := http.ListenAndServe(cfg.ListenAddr, mux); err != nil {
|
if err := http.ListenAndServe(cfg.ListenAddr, mux); err != nil {
|
||||||
|
|||||||
@@ -1,43 +0,0 @@
|
|||||||
// metrics-devserver stellt den OPS-03-Metrics-Aggregator (internal/metrics)
|
|
||||||
// unter /metrics bereit, damit ein echter Prometheus-Scrape-Vorgang gegen
|
|
||||||
// den Core-Dienst geprueft werden kann (Pruefung 3). Getrennt von cmd/core
|
|
||||||
// aus demselben Grund wie die anderen *-devserver.
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/db"
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/metrics"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
dsn := os.Getenv("NEXARCH_REGISTRY_DSN")
|
|
||||||
if dsn == "" {
|
|
||||||
log.Fatal("NEXARCH_REGISTRY_DSN nicht gesetzt")
|
|
||||||
}
|
|
||||||
addr := os.Getenv("NEXARCH_METRICS_LISTEN_ADDR")
|
|
||||||
if addr == "" {
|
|
||||||
addr = ":8085"
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
pool, err := db.Connect(ctx, dsn)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("db: %v", err)
|
|
||||||
}
|
|
||||||
defer pool.Close()
|
|
||||||
|
|
||||||
sourceStore := metrics.NewSourceStore(pool)
|
|
||||||
agg := metrics.NewAggregator(metrics.NewCoreRegistry(), sourceStore.Provide)
|
|
||||||
|
|
||||||
mux := http.NewServeMux()
|
|
||||||
mux.HandleFunc("/metrics", agg.Handler())
|
|
||||||
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
|
|
||||||
|
|
||||||
log.Printf("metrics-devserver listening on %s", addr)
|
|
||||||
log.Fatal(http.ListenAndServe(addr, mux))
|
|
||||||
}
|
|
||||||
@@ -3,12 +3,3 @@ module gitea.perlbach24.de/scripte/nexarch
|
|||||||
go 1.22
|
go 1.22
|
||||||
|
|
||||||
require github.com/jackc/pgx/v5 v5.6.0
|
require github.com/jackc/pgx/v5 v5.6.0
|
||||||
|
|
||||||
require (
|
|
||||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
|
||||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
|
||||||
github.com/jackc/puddle/v2 v2.2.1 // indirect
|
|
||||||
golang.org/x/crypto v0.17.0 // indirect
|
|
||||||
golang.org/x/sync v0.1.0 // indirect
|
|
||||||
golang.org/x/text v0.14.0 // indirect
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -1,28 +0,0 @@
|
|||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
|
||||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
|
||||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
|
||||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
|
|
||||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
|
||||||
github.com/jackc/pgx/v5 v5.6.0 h1:SWJzexBzPL5jb0GEsrPMLIsi/3jOo7RHlzTjcAeDrPY=
|
|
||||||
github.com/jackc/pgx/v5 v5.6.0/go.mod h1:DNZ/vlrUnhWCoFGxHAG8U2ljioxukquj7utPDgtQdTw=
|
|
||||||
github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk=
|
|
||||||
github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
|
||||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
|
||||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
|
||||||
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
|
|
||||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
|
||||||
golang.org/x/crypto v0.17.0 h1:r8bRNjWL3GshPW3gkd+RpvzWrZAwPS49OmTGZ/uhM4k=
|
|
||||||
golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
|
|
||||||
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
|
|
||||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
|
||||||
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
|
|
||||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
|
||||||
@@ -10,15 +10,8 @@ import (
|
|||||||
// connection info, superadmin accounts) — see nexarch-state.json
|
// connection info, superadmin accounts) — see nexarch-state.json
|
||||||
// multi_tenancy: Modell C (physisch getrennte DB pro Mandant).
|
// multi_tenancy: Modell C (physisch getrennte DB pro Mandant).
|
||||||
type Config struct {
|
type Config struct {
|
||||||
ListenAddr string
|
ListenAddr string
|
||||||
// RegistryDSN verbindet zur Control-Plane-Registry-Datenbank.
|
|
||||||
RegistryDSN string
|
RegistryDSN string
|
||||||
// AdminDSN verbindet zur Wartungsdatenbank (z.B. "postgres") und wird nur
|
|
||||||
// fuer CREATE/DROP DATABASE beim Tenant-Provisioning verwendet.
|
|
||||||
AdminDSN string
|
|
||||||
// TenantDSNTemplate enthaelt genau ein "%s" als Platzhalter fuer den
|
|
||||||
// Datenbanknamen einer neu provisionierten Tenant-Datenbank.
|
|
||||||
TenantDSNTemplate string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func Load() (Config, error) {
|
func Load() (Config, error) {
|
||||||
@@ -27,25 +20,10 @@ func Load() (Config, error) {
|
|||||||
return Config{}, fmt.Errorf("NEXARCH_REGISTRY_DSN not set")
|
return Config{}, fmt.Errorf("NEXARCH_REGISTRY_DSN not set")
|
||||||
}
|
}
|
||||||
|
|
||||||
adminDSN := os.Getenv("NEXARCH_ADMIN_DSN")
|
|
||||||
if adminDSN == "" {
|
|
||||||
return Config{}, fmt.Errorf("NEXARCH_ADMIN_DSN not set")
|
|
||||||
}
|
|
||||||
|
|
||||||
dsnTemplate := os.Getenv("NEXARCH_TENANT_DSN_TEMPLATE")
|
|
||||||
if dsnTemplate == "" {
|
|
||||||
return Config{}, fmt.Errorf("NEXARCH_TENANT_DSN_TEMPLATE not set")
|
|
||||||
}
|
|
||||||
|
|
||||||
addr := os.Getenv("NEXARCH_LISTEN_ADDR")
|
addr := os.Getenv("NEXARCH_LISTEN_ADDR")
|
||||||
if addr == "" {
|
if addr == "" {
|
||||||
addr = ":8080"
|
addr = ":8080"
|
||||||
}
|
}
|
||||||
|
|
||||||
return Config{
|
return Config{ListenAddr: addr, RegistryDSN: dsn}, nil
|
||||||
ListenAddr: addr,
|
|
||||||
RegistryDSN: dsn,
|
|
||||||
AdminDSN: adminDSN,
|
|
||||||
TenantDSNTemplate: dsnTemplate,
|
|
||||||
}, nil
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,87 +0,0 @@
|
|||||||
// Package flag implementiert Core LIC-02: einen Feature-Flag-Dienst mit
|
|
||||||
// Strategien (global an/aus, Prozentsatz, Tenant-Zielgruppe) als Kernfunktion
|
|
||||||
// des Core-Dienstes selbst — keine zusaetzliche Infrastruktur (Unleash-Server
|
|
||||||
// + eigene DB), siehe "bewusst vermeiden" im LIC-02-Ticket.
|
|
||||||
package flag
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"hash/fnv"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
var ErrNotFound = errors.New("flag: nicht gefunden")
|
|
||||||
|
|
||||||
// Flag ist die zentrale Definition — Auswertung (Evaluate) ist bewusst davon
|
|
||||||
// getrennt (Unleash-Prinzip: Flag-Verwaltung vs. Flag-Auswertung).
|
|
||||||
type Flag struct {
|
|
||||||
Key string
|
|
||||||
Enabled bool
|
|
||||||
RolloutPercentage int
|
|
||||||
TargetTenantSlugs []string
|
|
||||||
}
|
|
||||||
|
|
||||||
// Store ist die Verwaltungsseite (Admin): Flags definieren/lesen.
|
|
||||||
type Store struct {
|
|
||||||
pool *pgxpool.Pool
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewStore(pool *pgxpool.Pool) *Store {
|
|
||||||
return &Store{pool: pool}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) Set(ctx context.Context, f Flag) error {
|
|
||||||
if f.TargetTenantSlugs == nil {
|
|
||||||
f.TargetTenantSlugs = []string{} // pgx uebertraegt ein nil-Slice sonst als SQL NULL statt leerem Array.
|
|
||||||
}
|
|
||||||
_, err := s.pool.Exec(ctx, `
|
|
||||||
INSERT INTO feature_flags (key, enabled, rollout_percentage, target_tenant_slugs, updated_at)
|
|
||||||
VALUES ($1, $2, $3, $4, now())
|
|
||||||
ON CONFLICT (key) DO UPDATE SET
|
|
||||||
enabled = $2, rollout_percentage = $3, target_tenant_slugs = $4, updated_at = now()
|
|
||||||
`, f.Key, f.Enabled, f.RolloutPercentage, f.TargetTenantSlugs)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("flag speichern: %w", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) Get(ctx context.Context, key string) (Flag, error) {
|
|
||||||
var f Flag
|
|
||||||
row := s.pool.QueryRow(ctx, `
|
|
||||||
SELECT key, enabled, rollout_percentage, target_tenant_slugs
|
|
||||||
FROM feature_flags WHERE key = $1
|
|
||||||
`, key)
|
|
||||||
if err := row.Scan(&f.Key, &f.Enabled, &f.RolloutPercentage, &f.TargetTenantSlugs); err != nil {
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return Flag{}, ErrNotFound
|
|
||||||
}
|
|
||||||
return Flag{}, fmt.Errorf("flag lesen: %w", err)
|
|
||||||
}
|
|
||||||
return f, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// evaluate wendet die Strategien in fester Reihenfolge an: globaler
|
|
||||||
// An/Aus-Schalter zuerst, dann Tenant-Zielgruppe, dann Prozentsatz-Rollout.
|
|
||||||
// Ein unbekannter/nicht getroffener Fall ergibt false — Fail-Safe-Default,
|
|
||||||
// kein Feature wird versehentlich aktiv.
|
|
||||||
func evaluate(f Flag, tenantSlug string) bool {
|
|
||||||
if f.Enabled {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
for _, target := range f.TargetTenantSlugs {
|
|
||||||
if target == tenantSlug {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if f.RolloutPercentage > 0 {
|
|
||||||
h := fnv.New32a()
|
|
||||||
_, _ = h.Write([]byte(f.Key + "|" + tenantSlug))
|
|
||||||
return int(h.Sum32()%100) < f.RolloutPercentage
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
package flag
|
|
||||||
|
|
||||||
import "testing"
|
|
||||||
|
|
||||||
func TestEvaluate_GlobalEnabled(t *testing.T) {
|
|
||||||
f := Flag{Key: "k", Enabled: true}
|
|
||||||
if !evaluate(f, "irgendein-tenant") {
|
|
||||||
t.Fatal("global aktiviertes flag sollte fuer jeden tenant true liefern")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 1 + Pruefung 2: Zielgruppen-Strategie.
|
|
||||||
func TestEvaluate_TargetTenantStrategy(t *testing.T) {
|
|
||||||
f := Flag{Key: "k", Enabled: false, TargetTenantSlugs: []string{"acme"}}
|
|
||||||
if !evaluate(f, "acme") {
|
|
||||||
t.Fatal("erwartet true fuer tenant in zielgruppe")
|
|
||||||
}
|
|
||||||
if evaluate(f, "globex") {
|
|
||||||
t.Fatal("erwartet false fuer tenant ausserhalb der zielgruppe")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestEvaluate_RolloutPercentageBoundaries(t *testing.T) {
|
|
||||||
full := Flag{Key: "k", RolloutPercentage: 100}
|
|
||||||
if !evaluate(full, "beliebiger-tenant-1") || !evaluate(full, "beliebiger-tenant-2") {
|
|
||||||
t.Fatal("100% rollout sollte immer true liefern")
|
|
||||||
}
|
|
||||||
|
|
||||||
none := Flag{Key: "k", RolloutPercentage: 0}
|
|
||||||
if evaluate(none, "beliebiger-tenant") {
|
|
||||||
t.Fatal("0% rollout ohne enabled/zielgruppe sollte false liefern")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestEvaluate_RolloutIsDeterministicPerTenant(t *testing.T) {
|
|
||||||
f := Flag{Key: "k", RolloutPercentage: 50}
|
|
||||||
first := evaluate(f, "stabiler-tenant")
|
|
||||||
for i := 0; i < 5; i++ {
|
|
||||||
if evaluate(f, "stabiler-tenant") != first {
|
|
||||||
t.Fatal("rollout-auswertung sollte fuer denselben tenant/key stabil sein")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,87 +0,0 @@
|
|||||||
package flag
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"log/slog"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// DefaultCacheTTL ist die dokumentierte Cache-Invalidierungszeit
|
|
||||||
// (Akzeptanzkriterium 2/3): eine Aenderung wirkt spaetestens nach dieser
|
|
||||||
// Zeit auf allen Core-Instanzen, ohne dass ein Dienst neu gestartet werden
|
|
||||||
// muss (Akzeptanzkriterium 3).
|
|
||||||
const DefaultCacheTTL = 5 * time.Second
|
|
||||||
|
|
||||||
type cacheEntry struct {
|
|
||||||
flag Flag
|
|
||||||
expiresAt time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
// Service ist die Auswertungsseite (SDK/Client-Analogon zu Unleash) mit
|
|
||||||
// lokalem TTL-Cache. Bewusst getrennt von Store (Verwaltung).
|
|
||||||
type Service struct {
|
|
||||||
store *Store
|
|
||||||
ttl time.Duration
|
|
||||||
|
|
||||||
mu sync.RWMutex
|
|
||||||
cache map[string]cacheEntry
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewService(store *Store, ttl time.Duration) *Service {
|
|
||||||
if ttl <= 0 {
|
|
||||||
ttl = DefaultCacheTTL
|
|
||||||
}
|
|
||||||
return &Service{store: store, ttl: ttl, cache: make(map[string]cacheEntry)}
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsEnabled wertet ein Flag fuer einen Tenant aus. Liefert IMMER einen
|
|
||||||
// bool ohne Fehlerwert — ein nicht erreichbarer Flag-Dienst darf abhaengige
|
|
||||||
// Aufrufer nicht zum Absturz bringen oder zu Fehlerbehandlungscode zwingen,
|
|
||||||
// der leicht vergessen wird (Akzeptanzkriterium 3 / Pruefung 3: dokumentiertes
|
|
||||||
// Fallback-Verhalten = false, ggf. aus dem zuletzt bekannten Zwischenspeicher).
|
|
||||||
func (s *Service) IsEnabled(ctx context.Context, tenantSlug, key string) bool {
|
|
||||||
f, ok := s.resolve(ctx, key)
|
|
||||||
if !ok {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return evaluate(f, tenantSlug)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Service) resolve(ctx context.Context, key string) (Flag, bool) {
|
|
||||||
s.mu.RLock()
|
|
||||||
entry, exists := s.cache[key]
|
|
||||||
fresh := exists && time.Now().Before(entry.expiresAt)
|
|
||||||
s.mu.RUnlock()
|
|
||||||
if fresh {
|
|
||||||
return entry.flag, true
|
|
||||||
}
|
|
||||||
|
|
||||||
f, err := s.store.Get(ctx, key)
|
|
||||||
if err != nil {
|
|
||||||
if exists {
|
|
||||||
slog.Warn("feature-flag-dienst nicht erreichbar, nutze zwischengespeicherten stand",
|
|
||||||
"flag_key", key, "error", err)
|
|
||||||
return entry.flag, true
|
|
||||||
}
|
|
||||||
slog.Warn("feature-flag-dienst nicht erreichbar, kein zwischengespeicherter stand vorhanden, fallback: deaktiviert",
|
|
||||||
"flag_key", key, "error", err)
|
|
||||||
return Flag{}, false
|
|
||||||
}
|
|
||||||
|
|
||||||
s.mu.Lock()
|
|
||||||
s.cache[key] = cacheEntry{flag: f, expiresAt: time.Now().Add(s.ttl)}
|
|
||||||
s.mu.Unlock()
|
|
||||||
return f, true
|
|
||||||
}
|
|
||||||
|
|
||||||
// Invalidate erzwingt beim naechsten IsEnabled-Aufruf ein sofortiges Neuladen
|
|
||||||
// aus der Datenbank statt auf den TTL-Ablauf zu warten — wird nach Store.Set
|
|
||||||
// auf derselben Instanz aufgerufen, damit der Schreiber die eigene Aenderung
|
|
||||||
// ohne Wartezeit sieht. Andere Core-Instanzen sehen sie spaetestens nach
|
|
||||||
// DefaultCacheTTL (siehe Akzeptanzkriterium 3).
|
|
||||||
func (s *Service) Invalidate(key string) {
|
|
||||||
s.mu.Lock()
|
|
||||||
delete(s.cache, key)
|
|
||||||
s.mu.Unlock()
|
|
||||||
}
|
|
||||||
@@ -1,179 +0,0 @@
|
|||||||
package flag
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"os"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
func setupFlagStoreTest(t *testing.T) (*Store, func()) {
|
|
||||||
t.Helper()
|
|
||||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
|
||||||
if adminDSN == "" {
|
|
||||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
|
||||||
}
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
pool, err := pgxpool.New(ctx, adminDSN)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("pool: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := pool.Exec(ctx, `
|
|
||||||
CREATE TABLE IF NOT EXISTS feature_flags (
|
|
||||||
key TEXT PRIMARY KEY,
|
|
||||||
enabled BOOLEAN NOT NULL DEFAULT false,
|
|
||||||
rollout_percentage INT NOT NULL DEFAULT 0,
|
|
||||||
target_tenant_slugs TEXT[] NOT NULL DEFAULT '{}',
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
)`); err != nil {
|
|
||||||
t.Fatalf("schema: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
cleanup := func() {
|
|
||||||
_, _ = pool.Exec(ctx, `DELETE FROM feature_flags WHERE key LIKE 'test\_%' ESCAPE '\'`)
|
|
||||||
pool.Close()
|
|
||||||
}
|
|
||||||
return NewStore(pool), cleanup
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 1 + Pruefung 2: Zielgruppen-Strategie liefert im Test
|
|
||||||
// die erwartete Auswertung.
|
|
||||||
func TestService_TargetTenantStrategy(t *testing.T) {
|
|
||||||
store, cleanup := setupFlagStoreTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
if err := store.Set(ctx, Flag{Key: "test_target_flag", TargetTenantSlugs: []string{"acme"}}); err != nil {
|
|
||||||
t.Fatalf("set: %v", err)
|
|
||||||
}
|
|
||||||
svc := NewService(store, time.Hour)
|
|
||||||
|
|
||||||
if !svc.IsEnabled(ctx, "acme", "test_target_flag") {
|
|
||||||
t.Fatal("erwartet true fuer tenant in zielgruppe")
|
|
||||||
}
|
|
||||||
if svc.IsEnabled(ctx, "globex", "test_target_flag") {
|
|
||||||
t.Fatal("erwartet false fuer tenant ausserhalb der zielgruppe")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 2 + 3 + Pruefung 1: Flag-Aenderung wirkt innerhalb der
|
|
||||||
// dokumentierten Cache-Invalidierungszeit, automatisiert gemessen.
|
|
||||||
func TestService_CacheInvalidationTiming(t *testing.T) {
|
|
||||||
store, cleanup := setupFlagStoreTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
const ttl = 150 * time.Millisecond
|
|
||||||
if err := store.Set(ctx, Flag{Key: "test_ttl_flag", Enabled: false}); err != nil {
|
|
||||||
t.Fatalf("set: %v", err)
|
|
||||||
}
|
|
||||||
svc := NewService(store, ttl)
|
|
||||||
|
|
||||||
if svc.IsEnabled(ctx, "acme", "test_ttl_flag") {
|
|
||||||
t.Fatal("erwartet false vor der aenderung")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Aenderung "auf einer anderen instanz" simulieren: direkt ueber den
|
|
||||||
// Store, ohne svc.Invalidate aufzurufen.
|
|
||||||
changedAt := time.Now()
|
|
||||||
if err := store.Set(ctx, Flag{Key: "test_ttl_flag", Enabled: true}); err != nil {
|
|
||||||
t.Fatalf("set: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sofort danach sollte der Cache noch den alten Stand liefern.
|
|
||||||
if svc.IsEnabled(ctx, "acme", "test_ttl_flag") {
|
|
||||||
t.Fatal("cache haette den alten (false) stand liefern sollen, direkt nach der aenderung")
|
|
||||||
}
|
|
||||||
|
|
||||||
deadline := changedAt.Add(ttl + 100*time.Millisecond)
|
|
||||||
for time.Now().Before(deadline) {
|
|
||||||
if svc.IsEnabled(ctx, "acme", "test_ttl_flag") {
|
|
||||||
elapsed := time.Since(changedAt)
|
|
||||||
t.Logf("aenderung wurde nach %s wirksam (ziel: innerhalb %s + toleranz)", elapsed, ttl)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
time.Sleep(10 * time.Millisecond)
|
|
||||||
}
|
|
||||||
t.Fatalf("aenderung wurde nicht innerhalb von %s wirksam", deadline.Sub(changedAt))
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestService_InvalidateForcesImmediateRefresh(t *testing.T) {
|
|
||||||
store, cleanup := setupFlagStoreTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
if err := store.Set(ctx, Flag{Key: "test_invalidate_flag", Enabled: false}); err != nil {
|
|
||||||
t.Fatalf("set: %v", err)
|
|
||||||
}
|
|
||||||
svc := NewService(store, time.Hour) // lange TTL, damit Invalidate den unterschied macht
|
|
||||||
_ = svc.IsEnabled(ctx, "acme", "test_invalidate_flag")
|
|
||||||
|
|
||||||
if err := store.Set(ctx, Flag{Key: "test_invalidate_flag", Enabled: true}); err != nil {
|
|
||||||
t.Fatalf("set: %v", err)
|
|
||||||
}
|
|
||||||
svc.Invalidate("test_invalidate_flag")
|
|
||||||
|
|
||||||
if !svc.IsEnabled(ctx, "acme", "test_invalidate_flag") {
|
|
||||||
t.Fatal("erwartet sofort sichtbaren neuen stand nach Invalidate")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 3 + Pruefung 3: Ausfall des Flag-Dienstes fuehrt zu
|
|
||||||
// dokumentiertem Fallback-Verhalten, nicht zum Absturz.
|
|
||||||
func TestService_FallsBackOnStoreFailure(t *testing.T) {
|
|
||||||
store, cleanup := setupFlagStoreTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
if err := store.Set(ctx, Flag{Key: "test_fallback_flag", Enabled: true}); err != nil {
|
|
||||||
t.Fatalf("set: %v", err)
|
|
||||||
}
|
|
||||||
svc := NewService(store, time.Hour)
|
|
||||||
|
|
||||||
// Cache vorwaermen, waehrend die DB noch erreichbar ist.
|
|
||||||
if !svc.IsEnabled(ctx, "acme", "test_fallback_flag") {
|
|
||||||
t.Fatal("erwartet true bei funktionierender db")
|
|
||||||
}
|
|
||||||
|
|
||||||
brokenPool, err := pgxpool.New(ctx, "postgresql://nonexistent-host-fuer-test:5432/x?connect_timeout=1")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("broken pool erstellen (sollte nicht sofort verbinden): %v", err)
|
|
||||||
}
|
|
||||||
brokenStore := NewStore(brokenPool)
|
|
||||||
|
|
||||||
svcWithCache := NewService(brokenStore, time.Nanosecond) // TTL sofort abgelaufen, erzwingt reload-versuch
|
|
||||||
svcWithCache.mu.Lock()
|
|
||||||
svcWithCache.cache["test_fallback_flag"] = cacheEntry{
|
|
||||||
flag: Flag{Key: "test_fallback_flag", Enabled: true},
|
|
||||||
expiresAt: time.Now().Add(-time.Hour), // bereits abgelaufen
|
|
||||||
}
|
|
||||||
svcWithCache.mu.Unlock()
|
|
||||||
|
|
||||||
func() {
|
|
||||||
defer func() {
|
|
||||||
if r := recover(); r != nil {
|
|
||||||
t.Fatalf("IsEnabled hat gepanict statt einen fallback zu liefern: %v", r)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
if !svcWithCache.IsEnabled(ctx, "acme", "test_fallback_flag") {
|
|
||||||
t.Fatal("erwartet fallback auf zwischengespeicherten (true) stand bei db-ausfall")
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
// Voellig frischer Dienst ohne jeglichen cache + kaputte db -> sicherer
|
|
||||||
// default false, kein absturz.
|
|
||||||
freshSvc := NewService(brokenStore, time.Hour)
|
|
||||||
func() {
|
|
||||||
defer func() {
|
|
||||||
if r := recover(); r != nil {
|
|
||||||
t.Fatalf("IsEnabled hat gepanict: %v", r)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
if freshSvc.IsEnabled(ctx, "acme", "test_fallback_flag") {
|
|
||||||
t.Fatal("erwartet fail-safe false ohne cache und mit kaputter db")
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
package health
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
// DatabaseChecker prueft die tatsaechliche Erreichbarkeit der Datenbank
|
|
||||||
// (Ping) — nicht nur, ob der Pool existiert.
|
|
||||||
func DatabaseChecker(pool *pgxpool.Pool) CheckerFunc {
|
|
||||||
return func(ctx context.Context) error {
|
|
||||||
return pool.Ping(ctx)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// QueueChecker prueft, dass die Postgres-basierte Job-Queue (siehe CFG-02)
|
|
||||||
// tatsaechlich abfragbar ist — eine eigene, benannte Abhaengigkeit neben der
|
|
||||||
// reinen DB-Erreichbarkeit (Akzeptanzkriterium 1).
|
|
||||||
func QueueChecker(pool *pgxpool.Pool) CheckerFunc {
|
|
||||||
return func(ctx context.Context) error {
|
|
||||||
_, err := pool.Exec(ctx, `SELECT 1`)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
package health
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
// LivenessHandler beantwortet IMMER "lebt", solange der Prozess ueberhaupt
|
|
||||||
// HTTP-Anfragen verarbeiten kann — prueft bewusst KEINE externen
|
|
||||||
// Abhaengigkeiten (Akzeptanzkriterium 2: Liveness und Readiness getrennt).
|
|
||||||
// Ein Datenbankausfall darf die Liveness nicht auf "tot" setzen, sonst
|
|
||||||
// wuerde eine Orchestrierung (z.B. systemd/Kubernetes) den Prozess grundlos
|
|
||||||
// neu starten, obwohl nur eine Abhaengigkeit ausgefallen ist.
|
|
||||||
func LivenessHandler(w http.ResponseWriter, r *http.Request) {
|
|
||||||
writeStatus(w, http.StatusOK, map[string]any{"status": "alive"})
|
|
||||||
}
|
|
||||||
|
|
||||||
// ReadinessHandler prueft ALLE registrierten Abhaengigkeiten
|
|
||||||
// (Akzeptanzkriterium 1) und liefert 503, sobald eine davon fehlschlaegt
|
|
||||||
// (Akzeptanzkriterium 3) — unterscheidet sich damit nachweislich von
|
|
||||||
// LivenessHandler im Fehlerfall (Akzeptanzkriterium 2 / Pruefung 3).
|
|
||||||
func (r *Registry) ReadinessHandler() http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, req *http.Request) {
|
|
||||||
ready, results := r.CheckAll(req.Context())
|
|
||||||
|
|
||||||
body := map[string]any{
|
|
||||||
"status": statusText(ready),
|
|
||||||
"checks": results,
|
|
||||||
}
|
|
||||||
status := http.StatusOK
|
|
||||||
if !ready {
|
|
||||||
status = http.StatusServiceUnavailable
|
|
||||||
}
|
|
||||||
writeStatus(w, status, body)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func statusText(ready bool) string {
|
|
||||||
if ready {
|
|
||||||
return "ready"
|
|
||||||
}
|
|
||||||
return "not_ready"
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeStatus(w http.ResponseWriter, status int, body map[string]any) {
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
w.WriteHeader(status)
|
|
||||||
_ = json.NewEncoder(w).Encode(body)
|
|
||||||
}
|
|
||||||
@@ -1,86 +0,0 @@
|
|||||||
// Package health implementiert Core OPS-01: Health-/Readiness-Endpunkte, die
|
|
||||||
// echte Abhaengigkeiten (DB, Job-Queue) statt nur den Prozessstatus pruefen
|
|
||||||
// — wiederverwendbar von Core UND jedem registrierten Modul (siehe API-02),
|
|
||||||
// nicht nur von Core selbst.
|
|
||||||
package health
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Checker prueft EINE Abhaengigkeit (z.B. Datenbank, Job-Queue).
|
|
||||||
type Checker interface {
|
|
||||||
Check(ctx context.Context) error
|
|
||||||
}
|
|
||||||
|
|
||||||
type CheckerFunc func(ctx context.Context) error
|
|
||||||
|
|
||||||
func (f CheckerFunc) Check(ctx context.Context) error { return f(ctx) }
|
|
||||||
|
|
||||||
// DefaultCheckTimeout begrenzt, wie lange EIN einzelner Check maximal
|
|
||||||
// dauern darf, bevor er als fehlgeschlagen gilt — verhindert, dass ein
|
|
||||||
// haengender Check den gesamten Readiness-Endpunkt blockiert
|
|
||||||
// (Akzeptanzkriterium 2 / Pruefung 2: Antwort innerhalb definierter Zeit).
|
|
||||||
const DefaultCheckTimeout = 2 * time.Second
|
|
||||||
|
|
||||||
// Registry haelt alle benannten Checks eines Dienstes.
|
|
||||||
type Registry struct {
|
|
||||||
checks map[string]Checker
|
|
||||||
timeout time.Duration
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewRegistry() *Registry {
|
|
||||||
return &Registry{checks: make(map[string]Checker), timeout: DefaultCheckTimeout}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Registry) WithTimeout(d time.Duration) *Registry {
|
|
||||||
return &Registry{checks: r.checks, timeout: d}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Register fuegt einen benannten Check hinzu (z.B. "database", "queue").
|
|
||||||
func (r *Registry) Register(name string, c Checker) {
|
|
||||||
r.checks[name] = c
|
|
||||||
}
|
|
||||||
|
|
||||||
// Result ist der Ausgang eines einzelnen Checks.
|
|
||||||
type Result struct {
|
|
||||||
OK bool
|
|
||||||
Error string
|
|
||||||
}
|
|
||||||
|
|
||||||
// CheckAll fuehrt alle registrierten Checks NEBENLAEUFIG mit je eigenem
|
|
||||||
// Timeout aus (Akzeptanzkriterium 1: echte Abhaengigkeiten statt Prozess-
|
|
||||||
// status) und liefert ready=false, sobald irgendein Check fehlschlaegt
|
|
||||||
// (Akzeptanzkriterium 3: ein Ausfall wird sichtbar).
|
|
||||||
func (r *Registry) CheckAll(ctx context.Context) (ready bool, results map[string]Result) {
|
|
||||||
type namedResult struct {
|
|
||||||
name string
|
|
||||||
result Result
|
|
||||||
}
|
|
||||||
ch := make(chan namedResult, len(r.checks))
|
|
||||||
|
|
||||||
for name, checker := range r.checks {
|
|
||||||
go func(name string, checker Checker) {
|
|
||||||
checkCtx, cancel := context.WithTimeout(ctx, r.timeout)
|
|
||||||
defer cancel()
|
|
||||||
err := checker.Check(checkCtx)
|
|
||||||
if err != nil {
|
|
||||||
ch <- namedResult{name, Result{OK: false, Error: err.Error()}}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ch <- namedResult{name, Result{OK: true}}
|
|
||||||
}(name, checker)
|
|
||||||
}
|
|
||||||
|
|
||||||
results = make(map[string]Result, len(r.checks))
|
|
||||||
ready = true
|
|
||||||
for i := 0; i < len(r.checks); i++ {
|
|
||||||
nr := <-ch
|
|
||||||
results[nr.name] = nr.result
|
|
||||||
if !nr.result.OK {
|
|
||||||
ready = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ready, results
|
|
||||||
}
|
|
||||||
@@ -1,161 +0,0 @@
|
|||||||
package health
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"os"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 1 + Pruefung 1: simulierter Datenbankausfall fuehrt zu
|
|
||||||
// "nicht bereit".
|
|
||||||
func TestReadinessHandler_ReportsNotReadyOnDatabaseFailure(t *testing.T) {
|
|
||||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
|
||||||
if adminDSN == "" {
|
|
||||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
|
||||||
}
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
pool, err := pgxpool.New(ctx, adminDSN)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("pool: %v", err)
|
|
||||||
}
|
|
||||||
// Datenbankausfall simulieren: Pool sofort schliessen, bevor der Check laeuft.
|
|
||||||
pool.Close()
|
|
||||||
|
|
||||||
reg := NewRegistry()
|
|
||||||
reg.Register("database", DatabaseChecker(pool))
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/readyz", nil)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
reg.ReadinessHandler()(rec, req)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusServiceUnavailable {
|
|
||||||
t.Fatalf("status = %d, want 503 bei db-ausfall", rec.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
var body struct {
|
|
||||||
Status string `json:"status"`
|
|
||||||
Checks map[string]interface{} `json:"checks"`
|
|
||||||
}
|
|
||||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
|
||||||
t.Fatalf("body parsen: %v", err)
|
|
||||||
}
|
|
||||||
if body.Status != "not_ready" {
|
|
||||||
t.Fatalf("status-feld = %q, want not_ready", body.Status)
|
|
||||||
}
|
|
||||||
if _, ok := body.Checks["database"]; !ok {
|
|
||||||
t.Fatal("erwartet 'database' im checks-ergebnis")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestReadinessHandler_ReportsReadyWhenAllChecksPass(t *testing.T) {
|
|
||||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
|
||||||
if adminDSN == "" {
|
|
||||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
|
||||||
}
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
pool, err := pgxpool.New(ctx, adminDSN)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("pool: %v", err)
|
|
||||||
}
|
|
||||||
defer pool.Close()
|
|
||||||
|
|
||||||
reg := NewRegistry()
|
|
||||||
reg.Register("database", DatabaseChecker(pool))
|
|
||||||
reg.Register("queue", QueueChecker(pool))
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/readyz", nil)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
reg.ReadinessHandler()(rec, req)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("status = %d, want 200 bei funktionierenden abhaengigkeiten", rec.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 2 + Pruefung 3: Liveness und Readiness unterscheiden
|
|
||||||
// sich nachweislich im Fehlerfall.
|
|
||||||
func TestLivenessAndReadiness_DifferOnDatabaseFailure(t *testing.T) {
|
|
||||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
|
||||||
if adminDSN == "" {
|
|
||||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
|
||||||
}
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
pool, err := pgxpool.New(ctx, adminDSN)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("pool: %v", err)
|
|
||||||
}
|
|
||||||
pool.Close() // db-ausfall simulieren
|
|
||||||
|
|
||||||
reg := NewRegistry()
|
|
||||||
reg.Register("database", DatabaseChecker(pool))
|
|
||||||
|
|
||||||
livenessRec := httptest.NewRecorder()
|
|
||||||
LivenessHandler(livenessRec, httptest.NewRequest(http.MethodGet, "/livez", nil))
|
|
||||||
if livenessRec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("liveness status = %d, want 200 trotz db-ausfall (liveness prueft keine abhaengigkeiten)", livenessRec.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
readinessRec := httptest.NewRecorder()
|
|
||||||
reg.ReadinessHandler()(readinessRec, httptest.NewRequest(http.MethodGet, "/readyz", nil))
|
|
||||||
if readinessRec.Code != http.StatusServiceUnavailable {
|
|
||||||
t.Fatalf("readiness status = %d, want 503 bei db-ausfall", readinessRec.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
if livenessRec.Code == readinessRec.Code {
|
|
||||||
t.Fatal("liveness und readiness sollten sich im db-ausfall-fall unterscheiden")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 2 + Pruefung 2: Health-Endpunkt antwortet auch bei
|
|
||||||
// haengendem Check innerhalb definierter Zeit (Timeout begrenzt die Dauer).
|
|
||||||
func TestReadinessHandler_RespondsWithinTimeoutEvenWithHangingCheck(t *testing.T) {
|
|
||||||
reg := NewRegistry().WithTimeout(50 * time.Millisecond)
|
|
||||||
reg.Register("haengender_dienst", CheckerFunc(func(ctx context.Context) error {
|
|
||||||
select {
|
|
||||||
case <-time.After(10 * time.Second): // wuerde ohne timeout ewig blockieren
|
|
||||||
return nil
|
|
||||||
case <-ctx.Done():
|
|
||||||
return ctx.Err()
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
|
|
||||||
start := time.Now()
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/readyz", nil)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
reg.ReadinessHandler()(rec, req)
|
|
||||||
elapsed := time.Since(start)
|
|
||||||
|
|
||||||
if elapsed > time.Second {
|
|
||||||
t.Fatalf("readiness handler brauchte %s, erwartet deutlich unter 1s durch timeout", elapsed)
|
|
||||||
}
|
|
||||||
if rec.Code != http.StatusServiceUnavailable {
|
|
||||||
t.Fatalf("status = %d, want 503 fuer haengenden/timeout-check", rec.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCheckAll_MultipleChecksRunConcurrently(t *testing.T) {
|
|
||||||
reg := NewRegistry().WithTimeout(time.Second)
|
|
||||||
reg.Register("a", CheckerFunc(func(ctx context.Context) error { return nil }))
|
|
||||||
reg.Register("b", CheckerFunc(func(ctx context.Context) error { return errors.New("kaputt") }))
|
|
||||||
|
|
||||||
ready, results := reg.CheckAll(context.Background())
|
|
||||||
if ready {
|
|
||||||
t.Fatal("erwartet ready=false, da 'b' fehlschlaegt")
|
|
||||||
}
|
|
||||||
if !results["a"].OK {
|
|
||||||
t.Fatalf("erwartet 'a' ok, habe %+v", results["a"])
|
|
||||||
}
|
|
||||||
if results["b"].OK || results["b"].Error == "" {
|
|
||||||
t.Fatalf("erwartet 'b' fehlgeschlagen mit fehlertext, habe %+v", results["b"])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
package metrics
|
|
||||||
|
|
||||||
import "github.com/prometheus/client_golang/prometheus"
|
|
||||||
|
|
||||||
// NewCoreRegistry liefert das Prometheus-Registry fuer die EIGENEN
|
|
||||||
// Kennzahlen des Core-Dienstes (Akzeptanzkriterium 1) — alle Namen tragen
|
|
||||||
// das Praefix "nexarch_core_" gemaess der im Paketkommentar dokumentierten
|
|
||||||
// Namenskonvention (Akzeptanzkriterium 3). Ein eigenes Registry statt des
|
|
||||||
// globalen DefaultRegisterer, damit Tests unabhaengig voneinander sind.
|
|
||||||
func NewCoreRegistry() *prometheus.Registry {
|
|
||||||
reg := prometheus.NewRegistry()
|
|
||||||
reg.MustRegister(
|
|
||||||
prometheus.NewGaugeFunc(prometheus.GaugeOpts{
|
|
||||||
Name: "nexarch_core_up",
|
|
||||||
Help: "1, solange der Core-Dienst laeuft und Metriken liefern kann.",
|
|
||||||
}, func() float64 { return 1 }),
|
|
||||||
)
|
|
||||||
return reg
|
|
||||||
}
|
|
||||||
@@ -1,168 +0,0 @@
|
|||||||
// Package metrics implementiert Core OPS-03: einen zentralen /metrics-
|
|
||||||
// Endpunkt im Prometheus-Textformat, der Kennzahlen des Core-Dienstes UND
|
|
||||||
// aggregierte Kennzahlen aller registrierten Module bereitstellt — offenes
|
|
||||||
// Pull-Modell nach Prometheus-Vorbild, kein proprietaerer Push-Mechanismus.
|
|
||||||
//
|
|
||||||
// Namenskonvention (Akzeptanzkriterium 3, modulübergreifend konsistent):
|
|
||||||
//
|
|
||||||
// nexarch_core_<name> — Kennzahlen des Core-Dienstes selbst
|
|
||||||
// nexarch_module_<modul>_<name> — von einem Modul gescrapte Kennzahl
|
|
||||||
// <name>, umbenannt mit dem
|
|
||||||
// Modulnamen als Praefix
|
|
||||||
//
|
|
||||||
// Ein Modul liefert seine eigenen Kennzahlen unter EIGENEM Namen (z.B.
|
|
||||||
// "requests_total") unter seinem eigenen /metrics-Endpunkt — dieses Paket
|
|
||||||
// benennt sie beim Einsammeln konsistent um, damit im aggregierten Core-
|
|
||||||
// Endpunkt niemals zwei Module denselben Metrik-Namen kollidieren lassen.
|
|
||||||
package metrics
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/prometheus/client_golang/prometheus"
|
|
||||||
dto "github.com/prometheus/client_model/go"
|
|
||||||
"github.com/prometheus/common/expfmt"
|
|
||||||
"github.com/prometheus/common/model"
|
|
||||||
)
|
|
||||||
|
|
||||||
// init erzwingt das klassische Prometheus-Namensschema (a-z, A-Z, 0-9, _)
|
|
||||||
// fuer die Namensvalidierung von expfmt/model — ohne diese explizite
|
|
||||||
// Festlegung liefert die Bibliothek "Invalid name validation scheme
|
|
||||||
// requested: unset" beim Parsen/Kodieren, da sie den globalen Default in
|
|
||||||
// dieser Version nicht mehr implizit setzt.
|
|
||||||
func init() {
|
|
||||||
model.NameValidationScheme = model.LegacyValidation
|
|
||||||
}
|
|
||||||
|
|
||||||
// Source ist EIN registriertes Modul mit seinem eigenen /metrics-Endpunkt
|
|
||||||
// (siehe internal/health fuer das analoge Muster bei Readiness-Checks).
|
|
||||||
type Source struct {
|
|
||||||
ModuleName string
|
|
||||||
MetricsURL string
|
|
||||||
}
|
|
||||||
|
|
||||||
// SourceProvider liefert die aktuell registrierten Module — typischerweise
|
|
||||||
// rueckgebunden an internal/moduleregistry.Registry.List (API-02) ueber
|
|
||||||
// einen kleinen Adapter im aufrufenden Code, damit dieses Paket
|
|
||||||
// internal/moduleregistry nicht direkt importieren muss (Kein Umbau
|
|
||||||
// angrenzender Bereiche). Ein NEU registriertes Modul erscheint automatisch
|
|
||||||
// beim naechsten Aufruf von Aggregator.Handler, OHNE Codeaenderung an diesem
|
|
||||||
// Paket (Akzeptanzkriterium 2 / Pruefung 2).
|
|
||||||
type SourceProvider func(ctx context.Context) ([]Source, error)
|
|
||||||
|
|
||||||
// FetchTimeout begrenzt, wie lange EIN Modul-Scrape maximal dauern darf —
|
|
||||||
// ein haengendes Modul darf den gesamten Aggregations-Request nicht
|
|
||||||
// verzoegern (Pruefung 1: Antwort unter Last innerhalb definierter Zeit).
|
|
||||||
const FetchTimeout = 2 * time.Second
|
|
||||||
|
|
||||||
// Aggregator sammelt Core-eigene Metriken (coreGatherer) und die Metriken
|
|
||||||
// aller ueber sourceProvider gemeldeten Module in EINER Antwort ein.
|
|
||||||
type Aggregator struct {
|
|
||||||
coreGatherer prometheus.Gatherer
|
|
||||||
sourceProvider SourceProvider
|
|
||||||
client *http.Client
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewAggregator(coreGatherer prometheus.Gatherer, sourceProvider SourceProvider) *Aggregator {
|
|
||||||
return &Aggregator{
|
|
||||||
coreGatherer: coreGatherer,
|
|
||||||
sourceProvider: sourceProvider,
|
|
||||||
client: &http.Client{Timeout: FetchTimeout},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Gather implementiert prometheus.Gatherer: liefert Core-Metriken PLUS alle
|
|
||||||
// erreichbaren Modul-Metriken (umbenannt gemaess Namenskonvention) in einer
|
|
||||||
// gemeinsamen Liste von MetricFamilies.
|
|
||||||
func (a *Aggregator) Gather(ctx context.Context) ([]*dto.MetricFamily, error) {
|
|
||||||
families, err := a.coreGatherer.Gather()
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("core-metriken einsammeln: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
sources, err := a.sourceProvider(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("modul-quellen ermitteln: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Module werden NEBENLAEUFIG gescrapt (dasselbe Muster wie
|
|
||||||
// internal/health.Registry.CheckAll) — ein langsames/nicht erreichbares
|
|
||||||
// Modul haelt weder andere Module noch den Gesamt-Request auf.
|
|
||||||
type fetchResult struct {
|
|
||||||
families []*dto.MetricFamily
|
|
||||||
}
|
|
||||||
resultCh := make(chan fetchResult, len(sources))
|
|
||||||
for _, src := range sources {
|
|
||||||
go func(src Source) {
|
|
||||||
fetchCtx, cancel := context.WithTimeout(ctx, FetchTimeout)
|
|
||||||
defer cancel()
|
|
||||||
mf, err := a.fetchAndRename(fetchCtx, src)
|
|
||||||
if err != nil {
|
|
||||||
resultCh <- fetchResult{} // Fehlerfall: einfach nichts beitragen, Aggregation laeuft weiter
|
|
||||||
return
|
|
||||||
}
|
|
||||||
resultCh <- fetchResult{families: mf}
|
|
||||||
}(src)
|
|
||||||
}
|
|
||||||
for range sources {
|
|
||||||
r := <-resultCh
|
|
||||||
families = append(families, r.families...)
|
|
||||||
}
|
|
||||||
|
|
||||||
return families, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// fetchAndRename ruft die /metrics-URL eines Moduls ab, parst das
|
|
||||||
// Prometheus-Textformat und benennt jede Metrik gemaess der
|
|
||||||
// Namenskonvention um (Akzeptanzkriterium 2 + 3).
|
|
||||||
func (a *Aggregator) fetchAndRename(ctx context.Context, src Source) ([]*dto.MetricFamily, error) {
|
|
||||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, src.MetricsURL, nil)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
resp, err := a.client.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
|
||||||
return nil, fmt.Errorf("modul %s: unerwarteter status %d", src.ModuleName, resp.StatusCode)
|
|
||||||
}
|
|
||||||
|
|
||||||
parser := expfmt.NewTextParser(model.LegacyValidation)
|
|
||||||
parsed, err := parser.TextToMetricFamilies(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("modul %s: metrik-text nicht parsebar: %w", src.ModuleName, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
out := make([]*dto.MetricFamily, 0, len(parsed))
|
|
||||||
for name, mf := range parsed {
|
|
||||||
renamed := fmt.Sprintf("nexarch_module_%s_%s", src.ModuleName, name)
|
|
||||||
mf.Name = &renamed
|
|
||||||
out = append(out, mf)
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handler liefert einen HTTP-Handler, der Gather aufruft und das Ergebnis im
|
|
||||||
// Prometheus-Textformat ausgibt (Akzeptanzkriterium 1).
|
|
||||||
func (a *Aggregator) Handler() http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
families, err := a.Gather(r.Context())
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "metriken konnten nicht eingesammelt werden", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", string(expfmt.NewFormat(expfmt.TypeTextPlain)))
|
|
||||||
enc := expfmt.NewEncoder(w, expfmt.NewFormat(expfmt.TypeTextPlain))
|
|
||||||
for _, mf := range families {
|
|
||||||
if err := enc.Encode(mf); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,179 +0,0 @@
|
|||||||
package metrics
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/prometheus/common/expfmt"
|
|
||||||
"github.com/prometheus/common/model"
|
|
||||||
)
|
|
||||||
|
|
||||||
func fakeModuleServer(metricName string) *httptest.Server {
|
|
||||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Header().Set("Content-Type", "text/plain; version=0.0.4")
|
|
||||||
fmt.Fprintf(w, "# HELP %s ein test-zaehler\n# TYPE %s counter\n%s 42\n", metricName, metricName, metricName)
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 1: Core liefert unter dem Handler valides
|
|
||||||
// Prometheus-Textformat mit den eigenen Kennzahlen.
|
|
||||||
func TestHandler_ServesCoreMetricsInPrometheusFormat(t *testing.T) {
|
|
||||||
agg := NewAggregator(NewCoreRegistry(), func(ctx context.Context) ([]Source, error) { return nil, nil })
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/metrics", nil)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
agg.Handler()(rec, req)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("status = %d, want 200", rec.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
parser := expfmt.NewTextParser(model.LegacyValidation)
|
|
||||||
families, err := parser.TextToMetricFamilies(strings.NewReader(rec.Body.String()))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("antwort ist kein valides prometheus-textformat: %v", err)
|
|
||||||
}
|
|
||||||
if _, ok := families["nexarch_core_up"]; !ok {
|
|
||||||
t.Fatalf("erwartet 'nexarch_core_up' unter den core-metriken, habe: %v", keysOf(families))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func keysOf[V any](m map[string]V) []string {
|
|
||||||
out := make([]string, 0, len(m))
|
|
||||||
for k := range m {
|
|
||||||
out = append(out, k)
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 2 + Pruefung 2: ein NEU registriertes Modul erscheint
|
|
||||||
// in der Aggregation, OHNE dass dieses Paket oder der Aufrufer Code
|
|
||||||
// aendern muss — die Quelle kommt ausschliesslich aus sourceProvider.
|
|
||||||
func TestHandler_NewlyRegisteredModuleAppearsWithoutCodeChange(t *testing.T) {
|
|
||||||
moduleServer := fakeModuleServer("requests_total")
|
|
||||||
defer moduleServer.Close()
|
|
||||||
|
|
||||||
// Simuliert eine sich zur Laufzeit aendernde Modul-Liste (z.B. aus
|
|
||||||
// SourceStore.Provide) — zunaechst LEER, dann mit einem Eintrag.
|
|
||||||
var sources []Source
|
|
||||||
var mu sync.Mutex
|
|
||||||
provider := func(ctx context.Context) ([]Source, error) {
|
|
||||||
mu.Lock()
|
|
||||||
defer mu.Unlock()
|
|
||||||
out := make([]Source, len(sources))
|
|
||||||
copy(out, sources)
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
agg := NewAggregator(NewCoreRegistry(), provider)
|
|
||||||
|
|
||||||
// Vor der Registrierung: Modul-Metrik nicht vorhanden.
|
|
||||||
rec1 := httptest.NewRecorder()
|
|
||||||
agg.Handler()(rec1, httptest.NewRequest(http.MethodGet, "/metrics", nil))
|
|
||||||
if strings.Contains(rec1.Body.String(), "requests_total") {
|
|
||||||
t.Fatal("modul-metrik haette vor registrierung nicht erscheinen duerfen")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Modul wird "registriert" (kein Code hier oder in metrics.go aendert sich).
|
|
||||||
mu.Lock()
|
|
||||||
sources = append(sources, Source{ModuleName: "dms", MetricsURL: moduleServer.URL})
|
|
||||||
mu.Unlock()
|
|
||||||
|
|
||||||
rec2 := httptest.NewRecorder()
|
|
||||||
agg.Handler()(rec2, httptest.NewRequest(http.MethodGet, "/metrics", nil))
|
|
||||||
body := rec2.Body.String()
|
|
||||||
if !strings.Contains(body, "nexarch_module_dms_requests_total") {
|
|
||||||
t.Fatalf("erwartet umbenannte modul-metrik 'nexarch_module_dms_requests_total' nach registrierung, body:\n%s", body)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 3: Namenskonvention "nexarch_module_<modul>_<name>"
|
|
||||||
// wird tatsaechlich angewendet.
|
|
||||||
func TestFetchAndRename_AppliesNamingConvention(t *testing.T) {
|
|
||||||
moduleServer := fakeModuleServer("queue_depth")
|
|
||||||
defer moduleServer.Close()
|
|
||||||
|
|
||||||
agg := NewAggregator(NewCoreRegistry(), nil)
|
|
||||||
families, err := agg.fetchAndRename(context.Background(), Source{ModuleName: "mail", MetricsURL: moduleServer.URL})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("fetchAndRename: %v", err)
|
|
||||||
}
|
|
||||||
if len(families) != 1 || families[0].GetName() != "nexarch_module_mail_queue_depth" {
|
|
||||||
t.Fatalf("erwartet genau 1 metrik 'nexarch_module_mail_queue_depth', habe: %+v", families)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ein nicht erreichbares Modul darf die Aggregation der uebrigen und die
|
|
||||||
// Gesamtantwort nicht verhindern (dieselbe Resilienz wie OPS-02).
|
|
||||||
func TestHandler_UnreachableModuleDoesNotBreakAggregation(t *testing.T) {
|
|
||||||
reachable := fakeModuleServer("healthy_metric")
|
|
||||||
defer reachable.Close()
|
|
||||||
unreachable := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
|
|
||||||
unreachableURL := unreachable.URL
|
|
||||||
unreachable.Close() // sofort schliessen -> Verbindung schlaegt fehl
|
|
||||||
|
|
||||||
provider := func(ctx context.Context) ([]Source, error) {
|
|
||||||
return []Source{
|
|
||||||
{ModuleName: "ok", MetricsURL: reachable.URL},
|
|
||||||
{ModuleName: "kaputt", MetricsURL: unreachableURL},
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
agg := NewAggregator(NewCoreRegistry(), provider)
|
|
||||||
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
agg.Handler()(rec, httptest.NewRequest(http.MethodGet, "/metrics", nil))
|
|
||||||
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("status = %d, want 200 trotz einem nicht erreichbaren modul", rec.Code)
|
|
||||||
}
|
|
||||||
body := rec.Body.String()
|
|
||||||
if !strings.Contains(body, "nexarch_module_ok_healthy_metric") {
|
|
||||||
t.Fatal("erreichbares modul haette trotz ausfall des anderen aggregiert werden sollen")
|
|
||||||
}
|
|
||||||
if strings.Contains(body, "kaputt") {
|
|
||||||
t.Fatal("nicht erreichbares modul haette keine metrik beitragen duerfen")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Pruefung 1: Endpunkt antwortet unter mehreren gleichzeitigen Anfragen
|
|
||||||
// innerhalb definierter Zeit — kein unbeschraenktes Blockieren durch
|
|
||||||
// langsame Module (FetchTimeout begrenzt jeden Scrape).
|
|
||||||
func TestHandler_RespondsWithinBoundedTimeUnderLoad(t *testing.T) {
|
|
||||||
hangingServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
time.Sleep(10 * time.Second) // wuerde ohne timeout jede anfrage blockieren
|
|
||||||
}))
|
|
||||||
defer hangingServer.Close()
|
|
||||||
|
|
||||||
provider := func(ctx context.Context) ([]Source, error) {
|
|
||||||
return []Source{{ModuleName: "haengend", MetricsURL: hangingServer.URL}}, nil
|
|
||||||
}
|
|
||||||
agg := NewAggregator(NewCoreRegistry(), provider)
|
|
||||||
|
|
||||||
const concurrentRequests = 10
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
start := time.Now()
|
|
||||||
for i := 0; i < concurrentRequests; i++ {
|
|
||||||
wg.Add(1)
|
|
||||||
go func() {
|
|
||||||
defer wg.Done()
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
agg.Handler()(rec, httptest.NewRequest(http.MethodGet, "/metrics", nil))
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Errorf("status = %d, want 200", rec.Code)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
wg.Wait()
|
|
||||||
elapsed := time.Since(start)
|
|
||||||
|
|
||||||
if elapsed > FetchTimeout+3*time.Second {
|
|
||||||
t.Fatalf("%d gleichzeitige anfragen brauchten %s, erwartet deutlich unter %s durch FetchTimeout",
|
|
||||||
concurrentRequests, elapsed, FetchTimeout+3*time.Second)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
package metrics
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
// SourceStore persistiert, welche Module ihre Metriken unter welcher URL
|
|
||||||
// bereitstellen — dieselbe Postgres-basierte "kein Code-Deploy noetig"-
|
|
||||||
// Konvention wie internal/statuspage.Store.RegisterTarget (OPS-02): ein neu
|
|
||||||
// registriertes Modul erscheint automatisch in der Aggregation, sobald es
|
|
||||||
// hier eingetragen ist (Akzeptanzkriterium 2 / Pruefung 2).
|
|
||||||
type SourceStore struct {
|
|
||||||
pool *pgxpool.Pool
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSourceStore(pool *pgxpool.Pool) *SourceStore {
|
|
||||||
return &SourceStore{pool: pool}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SourceStore) RegisterSource(ctx context.Context, moduleName, metricsURL string) error {
|
|
||||||
_, err := s.pool.Exec(ctx, `
|
|
||||||
INSERT INTO metrics_sources (module_name, metrics_url)
|
|
||||||
VALUES ($1, $2)
|
|
||||||
ON CONFLICT (module_name) DO UPDATE SET metrics_url = $2
|
|
||||||
`, moduleName, metricsURL)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("metrik-quelle speichern: %w", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Provide implementiert SourceProvider direkt aus der Datenbank.
|
|
||||||
func (s *SourceStore) Provide(ctx context.Context) ([]Source, error) {
|
|
||||||
rows, err := s.pool.Query(ctx, `SELECT module_name, metrics_url FROM metrics_sources ORDER BY module_name`)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("metrik-quellen auflisten: %w", err)
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
var out []Source
|
|
||||||
for rows.Next() {
|
|
||||||
var src Source
|
|
||||||
if err := rows.Scan(&src.ModuleName, &src.MetricsURL); err != nil {
|
|
||||||
return nil, fmt.Errorf("metrik-quelle lesen: %w", err)
|
|
||||||
}
|
|
||||||
out = append(out, src)
|
|
||||||
}
|
|
||||||
return out, rows.Err()
|
|
||||||
}
|
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
package metrics
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
func setupSourceStoreTest(t *testing.T) (*SourceStore, func()) {
|
|
||||||
t.Helper()
|
|
||||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
|
||||||
if adminDSN == "" {
|
|
||||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
|
||||||
}
|
|
||||||
ctx := context.Background()
|
|
||||||
pool, err := pgxpool.New(ctx, adminDSN)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("pool: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := pool.Exec(ctx, `
|
|
||||||
CREATE TABLE IF NOT EXISTS metrics_sources (module_name TEXT PRIMARY KEY, metrics_url TEXT NOT NULL)
|
|
||||||
`); err != nil {
|
|
||||||
t.Fatalf("schema: %v", err)
|
|
||||||
}
|
|
||||||
cleanup := func() { pool.Close() }
|
|
||||||
return NewSourceStore(pool), cleanup
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 2 / Pruefung 2 auf Persistenz-Ebene: eine ueber die
|
|
||||||
// Datenbank registrierte Quelle ist sofort ueber Provide() sichtbar — genau
|
|
||||||
// der Mechanismus, der ein neues Modul ohne Core-Codeaenderung erscheinen
|
|
||||||
// laesst.
|
|
||||||
func TestSourceStore_RegisterSourceAppearsInProvide(t *testing.T) {
|
|
||||||
store, cleanup := setupSourceStoreTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
name := fmt.Sprintf("modul-%d", time.Now().UnixNano())
|
|
||||||
|
|
||||||
if err := store.RegisterSource(ctx, name, "http://example.invalid/metrics"); err != nil {
|
|
||||||
t.Fatalf("registersource: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
sources, err := store.Provide(ctx)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("provide: %v", err)
|
|
||||||
}
|
|
||||||
found := false
|
|
||||||
for _, s := range sources {
|
|
||||||
if s.ModuleName == name {
|
|
||||||
found = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !found {
|
|
||||||
t.Fatalf("erwartet %s in provide()-ergebnis, habe: %+v", name, sources)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,99 +0,0 @@
|
|||||||
package moduleregistry
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/rand"
|
|
||||||
"crypto/sha256"
|
|
||||||
"crypto/subtle"
|
|
||||||
"encoding/hex"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
ErrModuleNotRegistered = errors.New("moduleregistry: modul muss vor provisionierung registriert sein")
|
|
||||||
ErrInvalidCredential = errors.New("moduleregistry: ungueltiges oder fehlendes service-credential")
|
|
||||||
)
|
|
||||||
|
|
||||||
// Provision stellt ein Service-Credential (Client-ID + Secret) fuer eine
|
|
||||||
// Modul-Instanz aus (Akzeptanzkriterium 4). Das Secret wird NUR beim
|
|
||||||
// Ausstellen im Klartext zurueckgegeben, gespeichert wird ausschliesslich
|
|
||||||
// dessen SHA-256-Hash.
|
|
||||||
func (r *Registry) Provision(ctx context.Context, moduleName string) (clientID, secret string, err error) {
|
|
||||||
if _, err := r.Get(ctx, moduleName); err != nil {
|
|
||||||
if errors.Is(err, ErrModuleNotFound) {
|
|
||||||
return "", "", ErrModuleNotRegistered
|
|
||||||
}
|
|
||||||
return "", "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
clientID, err = randomToken(16)
|
|
||||||
if err != nil {
|
|
||||||
return "", "", fmt.Errorf("client-id erzeugen: %w", err)
|
|
||||||
}
|
|
||||||
secret, err = randomToken(32)
|
|
||||||
if err != nil {
|
|
||||||
return "", "", fmt.Errorf("secret erzeugen: %w", err)
|
|
||||||
}
|
|
||||||
hash := hashSecret(secret)
|
|
||||||
|
|
||||||
_, err = r.pool.Exec(ctx, `
|
|
||||||
INSERT INTO module_credentials (module_name, client_id, secret_hash, issued_at)
|
|
||||||
VALUES ($1, $2, $3, now())
|
|
||||||
ON CONFLICT (module_name) DO UPDATE SET client_id = $2, secret_hash = $3, issued_at = now()
|
|
||||||
`, moduleName, clientID, hash)
|
|
||||||
if err != nil {
|
|
||||||
return "", "", fmt.Errorf("credential speichern: %w", err)
|
|
||||||
}
|
|
||||||
return clientID, secret, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Authenticate prueft ein Service-Credential timing-safe (Referenzmuster
|
|
||||||
// siehe AUD-02) — Aufrufe ohne gueltiges Credential werden abgelehnt
|
|
||||||
// (Akzeptanzkriterium 4 / Pruefung 4).
|
|
||||||
func (r *Registry) Authenticate(ctx context.Context, clientID, secret string) (moduleName string, ok bool, err error) {
|
|
||||||
if clientID == "" || secret == "" {
|
|
||||||
return "", false, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var storedHash []byte
|
|
||||||
err = r.pool.QueryRow(ctx, `
|
|
||||||
SELECT module_name, secret_hash FROM module_credentials WHERE client_id = $1
|
|
||||||
`, clientID).Scan(&moduleName, &storedHash)
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return "", false, nil
|
|
||||||
}
|
|
||||||
return "", false, fmt.Errorf("credential lesen: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !timingSafeEqual(hashSecret(secret), storedHash) {
|
|
||||||
return "", false, nil
|
|
||||||
}
|
|
||||||
return moduleName, true, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func randomToken(n int) (string, error) {
|
|
||||||
buf := make([]byte, n)
|
|
||||||
if _, err := rand.Read(buf); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return hex.EncodeToString(buf), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func hashSecret(secret string) []byte {
|
|
||||||
sum := sha256.Sum256([]byte(secret))
|
|
||||||
return sum[:]
|
|
||||||
}
|
|
||||||
|
|
||||||
// timingSafeEqual folgt derselben Referenzimplementierung wie AUD-02
|
|
||||||
// (subtle.ConstantTimeCompare) — projektweite Konvention fuer jeden
|
|
||||||
// sicherheitsrelevanten Vergleich.
|
|
||||||
func timingSafeEqual(a, b []byte) bool {
|
|
||||||
if len(a) != len(b) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return subtle.ConstantTimeCompare(a, b) == 1
|
|
||||||
}
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
package moduleregistry
|
|
||||||
|
|
||||||
import "net/http"
|
|
||||||
|
|
||||||
// RequireActiveModule weist Anfragen an ein nicht aktiviertes Modul ZENTRAL
|
|
||||||
// ab, bevor der eigentliche Modul-Handler erreicht wird (Akzeptanzkriterium 2 /
|
|
||||||
// Pruefung 1) — Casbin-Prinzip: Durchsetzung als Middleware statt verstreuter
|
|
||||||
// Pruefungen in jedem Handler. tenantSlug/moduleName werden hier ueber
|
|
||||||
// Query-Parameter gelesen (echte Extraktion aus JWT/Tenant-Kontext ist
|
|
||||||
// API-05/TEN-06, nicht Teil dieser Kachel).
|
|
||||||
func (r *Registry) RequireActiveModule(moduleName string, next http.HandlerFunc) http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, req *http.Request) {
|
|
||||||
tenantSlug := req.URL.Query().Get("tenant")
|
|
||||||
active, err := r.IsActive(req.Context(), tenantSlug, moduleName)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "aktivierungspruefung fehlgeschlagen", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if !active {
|
|
||||||
http.Error(w, "modul nicht aktiviert", http.StatusForbidden)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
next(w, req)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// RequireServiceCredential authentifiziert eine Modul-Instanz ueber ihr
|
|
||||||
// Service-Credential (X-Client-Id/X-Client-Secret-Header) BEVOR der
|
|
||||||
// eigentliche Handler erreicht wird (Akzeptanzkriterium 4 / Pruefung 4).
|
|
||||||
func (r *Registry) RequireServiceCredential(next http.HandlerFunc) http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, req *http.Request) {
|
|
||||||
clientID := req.Header.Get("X-Client-Id")
|
|
||||||
secret := req.Header.Get("X-Client-Secret")
|
|
||||||
|
|
||||||
_, ok, err := r.Authenticate(req.Context(), clientID, secret)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "authentifizierung fehlgeschlagen", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if !ok {
|
|
||||||
http.Error(w, ErrInvalidCredential.Error(), http.StatusUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
next(w, req)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,120 +0,0 @@
|
|||||||
// Package moduleregistry implementiert Core API-02: die Registry, in der
|
|
||||||
// sich Fachmodule (DMS, Mail, weitere) mit Metadaten eintragen, gekoppelt an
|
|
||||||
// die Aktivierungspruefung aus LIC-02 (Feature-Flags). Zusaetzlich
|
|
||||||
// authentifiziert die Registry Modul-Instanzen selbst ueber ein bei
|
|
||||||
// Provisionierung ausgestelltes Service-Credential.
|
|
||||||
package moduleregistry
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/flag"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
ErrMissingName = errors.New("moduleregistry: name darf nicht leer sein")
|
|
||||||
ErrMissingVersion = errors.New("moduleregistry: version darf nicht leer sein")
|
|
||||||
ErrModuleNotFound = errors.New("moduleregistry: modul nicht registriert")
|
|
||||||
)
|
|
||||||
|
|
||||||
type Module struct {
|
|
||||||
Name string
|
|
||||||
Version string
|
|
||||||
RequiredFlags []string
|
|
||||||
}
|
|
||||||
|
|
||||||
type Registry struct {
|
|
||||||
pool *pgxpool.Pool
|
|
||||||
flags *flag.Service
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewRegistry(pool *pgxpool.Pool, flags *flag.Service) *Registry {
|
|
||||||
return &Registry{pool: pool, flags: flags}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Register traegt ein Modul mit Name, Version und benoetigten Feature-Flags
|
|
||||||
// ein (Akzeptanzkriterium 1). Fehlende Pflichtangaben werden abgewiesen
|
|
||||||
// (Akzeptanzkriterium 1 / Pruefung 2). Erneutes Register desselben Namens
|
|
||||||
// aktualisiert Version/Flags (Redeploy-Fall).
|
|
||||||
func (r *Registry) Register(ctx context.Context, name, version string, requiredFlags []string) (Module, error) {
|
|
||||||
if name == "" {
|
|
||||||
return Module{}, ErrMissingName
|
|
||||||
}
|
|
||||||
if version == "" {
|
|
||||||
return Module{}, ErrMissingVersion
|
|
||||||
}
|
|
||||||
if requiredFlags == nil {
|
|
||||||
requiredFlags = []string{}
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := r.pool.Exec(ctx, `
|
|
||||||
INSERT INTO modules (name, version, required_flags, registered_at)
|
|
||||||
VALUES ($1, $2, $3, now())
|
|
||||||
ON CONFLICT (name) DO UPDATE SET version = $2, required_flags = $3, registered_at = now()
|
|
||||||
`, name, version, requiredFlags)
|
|
||||||
if err != nil {
|
|
||||||
return Module{}, fmt.Errorf("modul registrieren: %w", err)
|
|
||||||
}
|
|
||||||
return Module{Name: name, Version: version, RequiredFlags: requiredFlags}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Registry) Get(ctx context.Context, name string) (Module, error) {
|
|
||||||
var m Module
|
|
||||||
m.Name = name
|
|
||||||
err := r.pool.QueryRow(ctx, `
|
|
||||||
SELECT version, required_flags FROM modules WHERE name = $1
|
|
||||||
`, name).Scan(&m.Version, &m.RequiredFlags)
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return Module{}, ErrModuleNotFound
|
|
||||||
}
|
|
||||||
return Module{}, fmt.Errorf("modul lesen: %w", err)
|
|
||||||
}
|
|
||||||
return m, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// List liefert alle registrierten Module (Akzeptanzkriterium 3: ueber API
|
|
||||||
// abfragbar, z.B. fuer Statusseite/Lizenzoberflaeche).
|
|
||||||
func (r *Registry) List(ctx context.Context) ([]Module, error) {
|
|
||||||
rows, err := r.pool.Query(ctx, `SELECT name, version, required_flags FROM modules ORDER BY name`)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("module auflisten: %w", err)
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
var out []Module
|
|
||||||
for rows.Next() {
|
|
||||||
var m Module
|
|
||||||
if err := rows.Scan(&m.Name, &m.Version, &m.RequiredFlags); err != nil {
|
|
||||||
return nil, fmt.Errorf("modul lesen: %w", err)
|
|
||||||
}
|
|
||||||
out = append(out, m)
|
|
||||||
}
|
|
||||||
return out, rows.Err()
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsActive prueft, ob ein registriertes Modul fuer einen Tenant aktiviert
|
|
||||||
// ist: registriert UND alle benoetigten Feature-Flags sind fuer diesen
|
|
||||||
// Tenant aktiv (Akzeptanzkriterium 2). Ein nicht registriertes Modul gilt
|
|
||||||
// immer als nicht aktiv.
|
|
||||||
func (r *Registry) IsActive(ctx context.Context, tenantSlug, moduleName string) (bool, error) {
|
|
||||||
m, err := r.Get(ctx, moduleName)
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, ErrModuleNotFound) {
|
|
||||||
return false, nil
|
|
||||||
}
|
|
||||||
return false, err
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, flagKey := range m.RequiredFlags {
|
|
||||||
if !r.flags.IsEnabled(ctx, tenantSlug, flagKey) {
|
|
||||||
return false, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true, nil
|
|
||||||
}
|
|
||||||
@@ -1,304 +0,0 @@
|
|||||||
package moduleregistry
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"os"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/flag"
|
|
||||||
)
|
|
||||||
|
|
||||||
func setupTest(t *testing.T) (*Registry, *flag.Store, func()) {
|
|
||||||
t.Helper()
|
|
||||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
|
||||||
if adminDSN == "" {
|
|
||||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
|
||||||
}
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
pool, err := pgxpool.New(ctx, adminDSN)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("pool: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := pool.Exec(ctx, `
|
|
||||||
CREATE TABLE IF NOT EXISTS feature_flags (
|
|
||||||
key TEXT PRIMARY KEY, enabled BOOLEAN NOT NULL DEFAULT false,
|
|
||||||
rollout_percentage INT NOT NULL DEFAULT 0, target_tenant_slugs TEXT[] NOT NULL DEFAULT '{}',
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
CREATE TABLE IF NOT EXISTS modules (
|
|
||||||
name TEXT PRIMARY KEY, version TEXT NOT NULL CHECK (version <> ''),
|
|
||||||
required_flags TEXT[] NOT NULL DEFAULT '{}', registered_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
CREATE TABLE IF NOT EXISTS module_credentials (
|
|
||||||
module_name TEXT PRIMARY KEY REFERENCES modules(name),
|
|
||||||
client_id TEXT NOT NULL UNIQUE, secret_hash BYTEA NOT NULL,
|
|
||||||
issued_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
`); err != nil {
|
|
||||||
t.Fatalf("schema: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
flagStore := flag.NewStore(pool)
|
|
||||||
// Kurze TTL, damit Tests, die den Flag-Store direkt aendern (an
|
|
||||||
// Registry.IsActive vorbei), den neuen Stand ohne manuelles Invalidate
|
|
||||||
// zuverlaessig sehen.
|
|
||||||
flagService := flag.NewService(flagStore, 10*time.Millisecond)
|
|
||||||
registry := NewRegistry(pool, flagService)
|
|
||||||
|
|
||||||
cleanup := func() { pool.Close() }
|
|
||||||
return registry, flagStore, cleanup
|
|
||||||
}
|
|
||||||
|
|
||||||
func uniqueModuleName(t *testing.T) string {
|
|
||||||
return fmt.Sprintf("dms_%d", time.Now().UnixNano())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 1 + Pruefung 2: fehlende Pflichtangaben abgewiesen.
|
|
||||||
func TestRegister_RejectsMissingFields(t *testing.T) {
|
|
||||||
registry, _, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
if _, err := registry.Register(ctx, "", "1.0", nil); !errors.Is(err, ErrMissingName) {
|
|
||||||
t.Fatalf("erwartet ErrMissingName, habe %v", err)
|
|
||||||
}
|
|
||||||
if _, err := registry.Register(ctx, "dms", "", nil); !errors.Is(err, ErrMissingVersion) {
|
|
||||||
t.Fatalf("erwartet ErrMissingVersion, habe %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRegister_AndGet(t *testing.T) {
|
|
||||||
registry, _, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
name := uniqueModuleName(t)
|
|
||||||
|
|
||||||
m, err := registry.Register(ctx, name, "1.2.0", []string{"dms_enabled"})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("register: %v", err)
|
|
||||||
}
|
|
||||||
if m.Version != "1.2.0" || len(m.RequiredFlags) != 1 {
|
|
||||||
t.Fatalf("unerwartet: %+v", m)
|
|
||||||
}
|
|
||||||
|
|
||||||
got, err := registry.Get(ctx, name)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("get: %v", err)
|
|
||||||
}
|
|
||||||
if got.Version != "1.2.0" {
|
|
||||||
t.Fatalf("get version = %q", got.Version)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 2 + 3 + Pruefung 3: konsistente Daten nach
|
|
||||||
// Aktivierung/Deaktivierung eines Moduls.
|
|
||||||
func TestIsActive_ReflectsFlagStateConsistently(t *testing.T) {
|
|
||||||
registry, flagStore, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
name := uniqueModuleName(t)
|
|
||||||
flagKey := name + "_enabled"
|
|
||||||
|
|
||||||
if _, err := registry.Register(ctx, name, "1.0", []string{flagKey}); err != nil {
|
|
||||||
t.Fatalf("register: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
active, err := registry.IsActive(ctx, "acme", name)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("is active (vor flag): %v", err)
|
|
||||||
}
|
|
||||||
if active {
|
|
||||||
t.Fatal("erwartet nicht aktiv, solange flag nicht gesetzt ist")
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := flagStore.Set(ctx, flag.Flag{Key: flagKey, Enabled: true}); err != nil {
|
|
||||||
t.Fatalf("flag setzen: %v", err)
|
|
||||||
}
|
|
||||||
time.Sleep(20 * time.Millisecond) // TTL abwarten
|
|
||||||
|
|
||||||
active, err = registry.IsActive(ctx, "acme", name)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("is active (nach flag an): %v", err)
|
|
||||||
}
|
|
||||||
if !active {
|
|
||||||
t.Fatal("erwartet aktiv, nachdem flag aktiviert wurde")
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := flagStore.Set(ctx, flag.Flag{Key: flagKey, Enabled: false}); err != nil {
|
|
||||||
t.Fatalf("flag zuruecksetzen: %v", err)
|
|
||||||
}
|
|
||||||
time.Sleep(20 * time.Millisecond) // TTL abwarten
|
|
||||||
active, err = registry.IsActive(ctx, "acme", name)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("is active (nach flag aus): %v", err)
|
|
||||||
}
|
|
||||||
if active {
|
|
||||||
t.Fatal("erwartet wieder nicht aktiv, nachdem flag deaktiviert wurde")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestIsActive_UnregisteredModuleIsNeverActive(t *testing.T) {
|
|
||||||
registry, _, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
active, err := registry.IsActive(ctx, "acme", "nie-registriert")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("is active: %v", err)
|
|
||||||
}
|
|
||||||
if active {
|
|
||||||
t.Fatal("unregistriertes modul darf nie aktiv sein")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 2 + Pruefung 1: Anfrage an deaktiviertes Modul wird
|
|
||||||
// zentral abgewiesen, BEVOR die Modul-Logik erreicht wird.
|
|
||||||
func TestRequireActiveModule_BlocksBeforeHandler(t *testing.T) {
|
|
||||||
registry, flagStore, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
name := uniqueModuleName(t)
|
|
||||||
flagKey := name + "_enabled"
|
|
||||||
|
|
||||||
if _, err := registry.Register(ctx, name, "1.0", []string{flagKey}); err != nil {
|
|
||||||
t.Fatalf("register: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
handlerReached := false
|
|
||||||
handler := registry.RequireActiveModule(name, func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
handlerReached = true
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
})
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/modul?tenant=acme", nil)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
handler(rec, req)
|
|
||||||
if rec.Code != http.StatusForbidden {
|
|
||||||
t.Fatalf("status = %d, want 403", rec.Code)
|
|
||||||
}
|
|
||||||
if handlerReached {
|
|
||||||
t.Fatal("handler haette bei deaktiviertem modul NICHT erreicht werden duerfen")
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := flagStore.Set(ctx, flag.Flag{Key: flagKey, Enabled: true}); err != nil {
|
|
||||||
t.Fatalf("flag setzen: %v", err)
|
|
||||||
}
|
|
||||||
req2 := httptest.NewRequest(http.MethodGet, "/modul?tenant=acme", nil)
|
|
||||||
rec2 := httptest.NewRecorder()
|
|
||||||
handler(rec2, req2)
|
|
||||||
if rec2.Code != http.StatusOK {
|
|
||||||
t.Fatalf("status nach aktivierung = %d, want 200", rec2.Code)
|
|
||||||
}
|
|
||||||
if !handlerReached {
|
|
||||||
t.Fatal("handler haette bei aktiviertem modul erreicht werden muessen")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 4 + Pruefung 4: gueltiges/ungueltiges Service-Credential.
|
|
||||||
func TestProvisionAndAuthenticate(t *testing.T) {
|
|
||||||
registry, _, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
name := uniqueModuleName(t)
|
|
||||||
|
|
||||||
if _, err := registry.Register(ctx, name, "1.0", nil); err != nil {
|
|
||||||
t.Fatalf("register: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
clientID, secret, err := registry.Provision(ctx, name)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("provision: %v", err)
|
|
||||||
}
|
|
||||||
if clientID == "" || secret == "" {
|
|
||||||
t.Fatal("erwartet nicht-leere client-id/secret")
|
|
||||||
}
|
|
||||||
|
|
||||||
moduleName, ok, err := registry.Authenticate(ctx, clientID, secret)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("authenticate (korrekt): %v", err)
|
|
||||||
}
|
|
||||||
if !ok || moduleName != name {
|
|
||||||
t.Fatalf("erwartet erfolgreiche authentifizierung fuer %q, habe ok=%v moduleName=%q", name, ok, moduleName)
|
|
||||||
}
|
|
||||||
|
|
||||||
_, ok, err = registry.Authenticate(ctx, clientID, "falsches-secret")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("authenticate (falsch): %v", err)
|
|
||||||
}
|
|
||||||
if ok {
|
|
||||||
t.Fatal("erwartet fehlschlag bei falschem secret")
|
|
||||||
}
|
|
||||||
|
|
||||||
_, ok, err = registry.Authenticate(ctx, "unbekannte-client-id", secret)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("authenticate (unbekannt): %v", err)
|
|
||||||
}
|
|
||||||
if ok {
|
|
||||||
t.Fatal("erwartet fehlschlag bei unbekannter client-id")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestProvision_RequiresRegisteredModule(t *testing.T) {
|
|
||||||
registry, _, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
if _, _, err := registry.Provision(ctx, "nie-registriert"); !errors.Is(err, ErrModuleNotRegistered) {
|
|
||||||
t.Fatalf("erwartet ErrModuleNotRegistered, habe %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRequireServiceCredential_RejectsInvalidAcceptsValid(t *testing.T) {
|
|
||||||
registry, _, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
name := uniqueModuleName(t)
|
|
||||||
|
|
||||||
if _, err := registry.Register(ctx, name, "1.0", nil); err != nil {
|
|
||||||
t.Fatalf("register: %v", err)
|
|
||||||
}
|
|
||||||
clientID, secret, err := registry.Provision(ctx, name)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("provision: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
handler := registry.RequireServiceCredential(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
})
|
|
||||||
|
|
||||||
// Fehlendes Credential.
|
|
||||||
req := httptest.NewRequest(http.MethodPost, "/service-aufruf", nil)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
handler(rec, req)
|
|
||||||
if rec.Code != http.StatusUnauthorized {
|
|
||||||
t.Fatalf("ohne credential: status = %d, want 401", rec.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Falsches Secret.
|
|
||||||
req2 := httptest.NewRequest(http.MethodPost, "/service-aufruf", nil)
|
|
||||||
req2.Header.Set("X-Client-Id", clientID)
|
|
||||||
req2.Header.Set("X-Client-Secret", "falsch")
|
|
||||||
rec2 := httptest.NewRecorder()
|
|
||||||
handler(rec2, req2)
|
|
||||||
if rec2.Code != http.StatusUnauthorized {
|
|
||||||
t.Fatalf("falsches secret: status = %d, want 401", rec2.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Gueltiges Credential.
|
|
||||||
req3 := httptest.NewRequest(http.MethodPost, "/service-aufruf", nil)
|
|
||||||
req3.Header.Set("X-Client-Id", clientID)
|
|
||||||
req3.Header.Set("X-Client-Secret", secret)
|
|
||||||
rec3 := httptest.NewRecorder()
|
|
||||||
handler(rec3, req3)
|
|
||||||
if rec3.Code != http.StatusOK {
|
|
||||||
t.Fatalf("gueltiges credential: status = %d, want 200", rec3.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
package tenant
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Handler ist eine schlanke Vorbereitung der Schnittstelle fuer API-01
|
|
||||||
// (REST-API-Grundgerüst & Versionierung) und TEN-02 (Self-Service-Onboarding).
|
|
||||||
// Auth/Rate-Limiting/Versionierung selbst sind ausdruecklich nicht Teil von
|
|
||||||
// TEN-01 und werden dort nachgezogen.
|
|
||||||
type Handler struct {
|
|
||||||
provisioner *Provisioner
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewHandler(p *Provisioner) *Handler {
|
|
||||||
return &Handler{provisioner: p}
|
|
||||||
}
|
|
||||||
|
|
||||||
type createTenantRequest struct {
|
|
||||||
Slug string `json:"slug"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) CreateTenant(w http.ResponseWriter, r *http.Request) {
|
|
||||||
var req createTenantRequest
|
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
||||||
http.Error(w, "ungueltige Anfrage", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
t, err := h.provisioner.Provision(r.Context(), req.Slug, req.Name)
|
|
||||||
if err != nil {
|
|
||||||
if err == ErrInvalidSlug {
|
|
||||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
http.Error(w, "tenant konnte nicht angelegt werden", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
w.WriteHeader(http.StatusCreated)
|
|
||||||
_ = json.NewEncoder(w).Encode(t)
|
|
||||||
}
|
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
package tenant
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Provisioner legt fuer jeden neuen Mandanten eine vollstaendig isolierte
|
|
||||||
// PostgreSQL-Datenbank an und registriert sie transaktional in der Registry
|
|
||||||
// (Akzeptanzkriterium 2). Zwei Mandanten-Datenbanken sind danach auf
|
|
||||||
// Infrastrukturebene komplett getrennt (Akzeptanzkriterium 3).
|
|
||||||
type Provisioner struct {
|
|
||||||
// adminPool ist mit der Wartungsdatenbank (z. B. "postgres") verbunden
|
|
||||||
// und wird ausschliesslich fuer CREATE/DROP DATABASE verwendet, da diese
|
|
||||||
// Befehle in PostgreSQL nicht in einer Transaktion laufen koennen.
|
|
||||||
adminPool *pgxpool.Pool
|
|
||||||
registry *Registry
|
|
||||||
// dsnTemplate enthaelt genau ein "%s" als Platzhalter fuer den
|
|
||||||
// Datenbanknamen, z. B. "postgresql://user:pass@host:5432/%s?sslmode=disable".
|
|
||||||
dsnTemplate string
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewProvisioner(adminPool *pgxpool.Pool, registry *Registry, dsnTemplate string) *Provisioner {
|
|
||||||
return &Provisioner{adminPool: adminPool, registry: registry, dsnTemplate: dsnTemplate}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Provision legt die Tenant-Datenbank an und registriert sie. Schlaegt die
|
|
||||||
// Registrierung fehl, wird die bereits angelegte Datenbank wieder entfernt,
|
|
||||||
// damit kein verwaister, unregistrierter Tenant zurueckbleibt.
|
|
||||||
func (p *Provisioner) Provision(ctx context.Context, slug, name string) (Tenant, error) {
|
|
||||||
if err := ValidateSlug(slug); err != nil {
|
|
||||||
return Tenant{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
dbName := dbNameForSlug(slug)
|
|
||||||
|
|
||||||
// CREATE DATABASE erlaubt keine Parameter-Platzhalter; slug ist durch
|
|
||||||
// ValidateSlug bereits auf [a-z0-9_] beschraenkt, Injektion ausgeschlossen.
|
|
||||||
if _, err := p.adminPool.Exec(ctx, fmt.Sprintf(`CREATE DATABASE %q`, dbName)); err != nil {
|
|
||||||
return Tenant{}, fmt.Errorf("tenant-datenbank anlegen: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
t := Tenant{
|
|
||||||
Slug: slug,
|
|
||||||
Name: name,
|
|
||||||
DBName: dbName,
|
|
||||||
DBDSN: fmt.Sprintf(p.dsnTemplate, dbName),
|
|
||||||
Status: StatusActive,
|
|
||||||
}
|
|
||||||
|
|
||||||
tx, err := p.registry.pool.Begin(ctx)
|
|
||||||
if err != nil {
|
|
||||||
p.rollbackDatabase(ctx, dbName)
|
|
||||||
return Tenant{}, fmt.Errorf("registry-transaktion starten: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
created, err := p.registry.insertTx(ctx, tx, t)
|
|
||||||
if err != nil {
|
|
||||||
_ = tx.Rollback(ctx)
|
|
||||||
p.rollbackDatabase(ctx, dbName)
|
|
||||||
return Tenant{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := tx.Commit(ctx); err != nil {
|
|
||||||
p.rollbackDatabase(ctx, dbName)
|
|
||||||
return Tenant{}, fmt.Errorf("registry-transaktion committen: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return created, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// rollbackDatabase entfernt eine bereits angelegte Tenant-Datenbank, wenn die
|
|
||||||
// Registrierung fehlschlug, damit Provisioning insgesamt atomar wirkt.
|
|
||||||
func (p *Provisioner) rollbackDatabase(ctx context.Context, dbName string) {
|
|
||||||
_, _ = p.adminPool.Exec(ctx, fmt.Sprintf(`DROP DATABASE IF EXISTS %q`, dbName))
|
|
||||||
}
|
|
||||||
@@ -1,105 +0,0 @@
|
|||||||
package tenant
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Integrationstest fuer Akzeptanzkriterien 2 und 3. Benoetigt eine echte
|
|
||||||
// Postgres-Instanz und wird ohne TEST_ADMIN_DSN uebersprungen, nicht als
|
|
||||||
// fehlgeschlagen gewertet — siehe Pruefungen-Ergebnis im PR.
|
|
||||||
//
|
|
||||||
// TEST_ADMIN_DSN muss auf die Wartungsdatenbank zeigen, z. B.:
|
|
||||||
//
|
|
||||||
// postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable
|
|
||||||
func TestProvision_CreatesIsolatedDatabases(t *testing.T) {
|
|
||||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
|
||||||
if adminDSN == "" {
|
|
||||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
|
||||||
}
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
adminPool, err := pgxpool.New(ctx, adminDSN)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("admin pool: %v", err)
|
|
||||||
}
|
|
||||||
defer adminPool.Close()
|
|
||||||
|
|
||||||
registryPool, err := pgxpool.New(ctx, adminDSN)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("registry pool: %v", err)
|
|
||||||
}
|
|
||||||
defer registryPool.Close()
|
|
||||||
|
|
||||||
if _, err := registryPool.Exec(ctx, `
|
|
||||||
CREATE TABLE IF NOT EXISTS tenants (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
slug TEXT NOT NULL UNIQUE,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
db_name TEXT NOT NULL UNIQUE,
|
|
||||||
db_dsn TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL DEFAULT 'active',
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
)`); err != nil {
|
|
||||||
t.Fatalf("registry-schema: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
dsnTemplate := strings.Replace(adminDSN, "/postgres?", "/%s?", 1)
|
|
||||||
registry := NewRegistry(registryPool)
|
|
||||||
provisioner := NewProvisioner(adminPool, registry, dsnTemplate)
|
|
||||||
|
|
||||||
t.Cleanup(func() {
|
|
||||||
_, _ = registryPool.Exec(ctx, `DELETE FROM tenants WHERE slug IN ('acme','globex')`)
|
|
||||||
_, _ = adminPool.Exec(ctx, `DROP DATABASE IF EXISTS tenant_acme`)
|
|
||||||
_, _ = adminPool.Exec(ctx, `DROP DATABASE IF EXISTS tenant_globex`)
|
|
||||||
})
|
|
||||||
|
|
||||||
tenantA, err := provisioner.Provision(ctx, "acme", "Acme GmbH")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("provision acme: %v", err)
|
|
||||||
}
|
|
||||||
tenantB, err := provisioner.Provision(ctx, "globex", "Globex AG")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("provision globex: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if tenantA.DBName == tenantB.DBName {
|
|
||||||
t.Fatalf("erwartet unterschiedliche db_name, beide sind %q", tenantA.DBName)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 3 / Pruefung 3: In der Datenbank von Tenant A existiert
|
|
||||||
// keine Verbindungsmoeglichkeit zu Tenant B, weil beide physisch getrennte
|
|
||||||
// Datenbanken sind, statt sich auf einen Query-Filter zu verlassen.
|
|
||||||
poolA, err := pgxpool.New(ctx, tenantA.DBDSN)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("connect tenant a: %v", err)
|
|
||||||
}
|
|
||||||
defer poolA.Close()
|
|
||||||
|
|
||||||
var globexVisible bool
|
|
||||||
err = poolA.QueryRow(ctx, `
|
|
||||||
SELECT EXISTS (
|
|
||||||
SELECT 1 FROM pg_catalog.pg_database WHERE datname = $1
|
|
||||||
)
|
|
||||||
`, tenantB.DBName).Scan(&globexVisible)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("pruefung tenant-trennung: %v", err)
|
|
||||||
}
|
|
||||||
// pg_database ist clusterweit sichtbar (Existenz der DB), aber die
|
|
||||||
// eigentliche Pruefung ist: aus poolA (verbunden mit tenant_acme) ist keine
|
|
||||||
// Tabelle/Zeile aus tenant_globex erreichbar, da current_database() getrennt ist.
|
|
||||||
var currentDB string
|
|
||||||
if err := poolA.QueryRow(ctx, `SELECT current_database()`).Scan(¤tDB); err != nil {
|
|
||||||
t.Fatalf("current_database: %v", err)
|
|
||||||
}
|
|
||||||
if currentDB != tenantA.DBName {
|
|
||||||
t.Fatalf("current_database() = %q, want %q — keine physische Trennung", currentDB, tenantA.DBName)
|
|
||||||
}
|
|
||||||
if currentDB == tenantB.DBName {
|
|
||||||
t.Fatalf("tenant a verbindung zeigt auf tenant b datenbank")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,69 +0,0 @@
|
|||||||
package tenant
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Registry kapselt den Zugriff auf die Control-Plane-Registry-Datenbank.
|
|
||||||
// Sie enthaelt ausschliesslich Tenant-Metadaten (Akzeptanzkriterium 1) —
|
|
||||||
// niemals Geschaeftsdaten eines Mandanten.
|
|
||||||
type Registry struct {
|
|
||||||
pool *pgxpool.Pool
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewRegistry(pool *pgxpool.Pool) *Registry {
|
|
||||||
return &Registry{pool: pool}
|
|
||||||
}
|
|
||||||
|
|
||||||
// insertTx schreibt den Tenant-Datensatz innerhalb einer laufenden Transaktion,
|
|
||||||
// damit Provisioner.Provision DB-Anlage und Registrierung atomar behandeln kann.
|
|
||||||
func (r *Registry) insertTx(ctx context.Context, tx pgx.Tx, t Tenant) (Tenant, error) {
|
|
||||||
row := tx.QueryRow(ctx, `
|
|
||||||
INSERT INTO tenants (slug, name, db_name, db_dsn, status)
|
|
||||||
VALUES ($1, $2, $3, $4, $5)
|
|
||||||
RETURNING id, created_at
|
|
||||||
`, t.Slug, t.Name, t.DBName, t.DBDSN, t.Status)
|
|
||||||
|
|
||||||
if err := row.Scan(&t.ID, &t.CreatedAt); err != nil {
|
|
||||||
return Tenant{}, fmt.Errorf("tenant registrieren: %w", err)
|
|
||||||
}
|
|
||||||
return t, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Registry) GetBySlug(ctx context.Context, slug string) (Tenant, error) {
|
|
||||||
var t Tenant
|
|
||||||
row := r.pool.QueryRow(ctx, `
|
|
||||||
SELECT id, slug, name, db_name, db_dsn, status, created_at
|
|
||||||
FROM tenants WHERE slug = $1
|
|
||||||
`, slug)
|
|
||||||
|
|
||||||
if err := row.Scan(&t.ID, &t.Slug, &t.Name, &t.DBName, &t.DBDSN, &t.Status, &t.CreatedAt); err != nil {
|
|
||||||
return Tenant{}, fmt.Errorf("tenant laden: %w", err)
|
|
||||||
}
|
|
||||||
return t, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Registry) List(ctx context.Context) ([]Tenant, error) {
|
|
||||||
rows, err := r.pool.Query(ctx, `
|
|
||||||
SELECT id, slug, name, db_name, db_dsn, status, created_at
|
|
||||||
FROM tenants ORDER BY created_at
|
|
||||||
`)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("tenants auflisten: %w", err)
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
var out []Tenant
|
|
||||||
for rows.Next() {
|
|
||||||
var t Tenant
|
|
||||||
if err := rows.Scan(&t.ID, &t.Slug, &t.Name, &t.DBName, &t.DBDSN, &t.Status, &t.CreatedAt); err != nil {
|
|
||||||
return nil, fmt.Errorf("tenant lesen: %w", err)
|
|
||||||
}
|
|
||||||
out = append(out, t)
|
|
||||||
}
|
|
||||||
return out, rows.Err()
|
|
||||||
}
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
// Package tenant implements Core TEN-01: die Control-Plane-Registry und die
|
|
||||||
// Provisioning-Routine fuer physisch getrennte Mandanten-Datenbanken (Modell C).
|
|
||||||
package tenant
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"regexp"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Status string
|
|
||||||
|
|
||||||
const (
|
|
||||||
StatusActive Status = "active"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Tenant struct {
|
|
||||||
ID string
|
|
||||||
Slug string
|
|
||||||
Name string
|
|
||||||
DBName string
|
|
||||||
DBDSN string
|
|
||||||
Status Status
|
|
||||||
CreatedAt time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
// slugPattern erzwingt sichere, als SQL-Identifier verwendbare Slugs, damit
|
|
||||||
// der Datenbankname niemals aus unkontrolliertem Nutzereingabe-Text gebaut wird.
|
|
||||||
var slugPattern = regexp.MustCompile(`^[a-z][a-z0-9_]{1,48}$`)
|
|
||||||
|
|
||||||
var ErrInvalidSlug = errors.New("tenant: slug muss mit Kleinbuchstaben beginnen und darf nur [a-z0-9_] enthalten (2-49 Zeichen)")
|
|
||||||
|
|
||||||
func ValidateSlug(slug string) error {
|
|
||||||
if !slugPattern.MatchString(slug) {
|
|
||||||
return ErrInvalidSlug
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func dbNameForSlug(slug string) string {
|
|
||||||
return "tenant_" + slug
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
package tenant
|
|
||||||
|
|
||||||
import "testing"
|
|
||||||
|
|
||||||
func TestValidateSlug(t *testing.T) {
|
|
||||||
cases := []struct {
|
|
||||||
slug string
|
|
||||||
wantErr bool
|
|
||||||
}{
|
|
||||||
{"acme", false},
|
|
||||||
{"acme_gmbh", false},
|
|
||||||
{"a1", false},
|
|
||||||
{"", true},
|
|
||||||
{"a", true},
|
|
||||||
{"1acme", true},
|
|
||||||
{"Acme", true},
|
|
||||||
{"acme-gmbh", true},
|
|
||||||
{"acme;drop table tenants", true},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, c := range cases {
|
|
||||||
err := ValidateSlug(c.slug)
|
|
||||||
if (err != nil) != c.wantErr {
|
|
||||||
t.Errorf("ValidateSlug(%q) error = %v, wantErr %v", c.slug, err, c.wantErr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDBNameForSlug(t *testing.T) {
|
|
||||||
got := dbNameForSlug("acme")
|
|
||||||
want := "tenant_acme"
|
|
||||||
if got != want {
|
|
||||||
t.Errorf("dbNameForSlug() = %q, want %q", got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
DROP TABLE IF EXISTS tenants;
|
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
-- Control-plane registry: tenant list + connection info (Modell C).
|
||||||
|
-- Core TEN-01 (siehe core-kanban).
|
||||||
|
CREATE TABLE tenants (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
slug TEXT NOT NULL UNIQUE,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
db_dsn TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'active',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
-- Control-plane registry: Tenant-Liste + Verbindungsinformationen (Modell C).
|
|
||||||
-- Enthaelt AUSSCHLIESSLICH Tenant-Metadaten, keine Geschaeftsdaten eines Mandanten.
|
|
||||||
-- Core TEN-01 (siehe core-kanban/tickets/TEN-01.md).
|
|
||||||
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
|
||||||
|
|
||||||
CREATE TABLE tenants (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
slug TEXT NOT NULL UNIQUE,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
db_name TEXT NOT NULL UNIQUE,
|
|
||||||
db_dsn TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL DEFAULT 'active',
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
DROP TABLE IF EXISTS feature_flags;
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
-- Feature-Flags zentral je Mandant/Zielgruppe (LIC-02, siehe core-kanban/tickets/LIC-02.md).
|
|
||||||
-- Lebt in der Registry-DB, nicht pro Tenant-Datenbank — Flags sind eine
|
|
||||||
-- Core-weite Konfiguration, keine Mandanten-Geschaeftsdaten.
|
|
||||||
CREATE TABLE feature_flags (
|
|
||||||
key TEXT PRIMARY KEY,
|
|
||||||
enabled BOOLEAN NOT NULL DEFAULT false,
|
|
||||||
rollout_percentage INT NOT NULL DEFAULT 0 CHECK (rollout_percentage BETWEEN 0 AND 100),
|
|
||||||
target_tenant_slugs TEXT[] NOT NULL DEFAULT '{}',
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
DROP TABLE IF EXISTS module_credentials;
|
|
||||||
DROP TABLE IF EXISTS modules;
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
-- Modul-Registry & Aktivierungspruefung (API-02, siehe core-kanban/tickets/API-02.md).
|
|
||||||
CREATE TABLE modules (
|
|
||||||
name TEXT PRIMARY KEY,
|
|
||||||
version TEXT NOT NULL CHECK (version <> ''),
|
|
||||||
required_flags TEXT[] NOT NULL DEFAULT '{}',
|
|
||||||
registered_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
|
|
||||||
-- Service-Credential je Modul-Instanz, bei Provisionierung ausgestellt
|
|
||||||
-- (Akzeptanzkriterium 4). secret_hash enthaelt NIEMALS das Secret im
|
|
||||||
-- Klartext, nur dessen SHA-256-Hash (Timing-safe-Vergleich beim Login,
|
|
||||||
-- Referenzmuster siehe AUD-02).
|
|
||||||
CREATE TABLE module_credentials (
|
|
||||||
module_name TEXT PRIMARY KEY REFERENCES modules(name),
|
|
||||||
client_id TEXT NOT NULL UNIQUE,
|
|
||||||
secret_hash BYTEA NOT NULL,
|
|
||||||
issued_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
DROP TABLE metrics_sources;
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
-- Metrics-Aggregation ueber Module hinweg (OPS-03, siehe
|
|
||||||
-- core-kanban/tickets/OPS-03.md) — welches Modul liefert seine Kennzahlen
|
|
||||||
-- unter welcher /metrics-URL.
|
|
||||||
CREATE TABLE metrics_sources (
|
|
||||||
module_name TEXT PRIMARY KEY,
|
|
||||||
metrics_url TEXT NOT NULL
|
|
||||||
);
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
set -euo pipefail
|
|
||||||
PASS="${NEXARCH_TEST_DB_PASSWORD:?Setze NEXARCH_TEST_DB_PASSWORD vor dem Aufruf}"
|
|
||||||
ROLE="nexarch_test"
|
|
||||||
export PGPASSWORD="$PASS"
|
|
||||||
psql -h localhost -U "$ROLE" -d postgres -v ON_ERROR_STOP=1 -c "DROP TABLE IF EXISTS tenants CASCADE;"
|
|
||||||
dbs=$(psql -h localhost -U "$ROLE" -d postgres -tAc "SELECT datname FROM pg_database WHERE datname LIKE 'tenant\_%' ESCAPE '\'")
|
|
||||||
for db in $dbs; do
|
|
||||||
psql -h localhost -U "$ROLE" -d postgres -v ON_ERROR_STOP=1 -c "DROP DATABASE IF EXISTS \"${db}\";"
|
|
||||||
done
|
|
||||||
echo "Testumgebung zurueckgesetzt: registry-tabelle + $(echo "$dbs" | grep -c . || true) tenant-datenbank(en) entfernt."
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
set -euo pipefail
|
|
||||||
PASS="${NEXARCH_TEST_DB_PASSWORD:?Setze NEXARCH_TEST_DB_PASSWORD vor dem Aufruf}"
|
|
||||||
cd "$(dirname "$0")/.."
|
|
||||||
NEXARCH_TEST_DB_PASSWORD="$PASS" bash scripts/reset-test-env.sh
|
|
||||||
export TEST_ADMIN_DSN="postgresql://nexarch_test:${PASS}@localhost:5432/postgres?sslmode=disable"
|
|
||||||
echo "== go build =="
|
|
||||||
go build ./...
|
|
||||||
echo "== go vet =="
|
|
||||||
go vet ./...
|
|
||||||
echo "== go test (-p 1) =="
|
|
||||||
go test ./... -p 1 -count=1
|
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# @nexarch/shl — UI-Shell & Design-System (Core SHL-01)
|
||||||
|
|
||||||
|
Gemeinsames Paket für alle NEXARCH-Modul-Frontends (Core, DMS, Mail, Archive, Workflow, AI, Connect).
|
||||||
|
Ein Modul-Frontend importiert ausschließlich über `index.ts`, kopiert keine Komponenten oder Tokens lokal.
|
||||||
|
|
||||||
|
## Enthält
|
||||||
|
|
||||||
|
- **Design-Tokens** (`tokens/tokens.ts`) — Farbe (Hell/Dunkel), Abstand, Typografie. Kontrastwerte gegen WCAG 2.1 AA geprüft (siehe `__tests__/tokens.test.ts`).
|
||||||
|
- **Theming** (`theme/ThemeProvider.tsx`) — zentrale Hell/Dunkel-Umschaltung, respektiert `prefers-color-scheme`, persistiert in `localStorage`.
|
||||||
|
- **i18n-Rahmen** (`i18n/i18n.tsx`) — Umschaltmechanismus Deutsch/Englisch. Modul-Frontends registrieren ihre fachlichen Textbausteine über `registerMessages()`, statt einen eigenen Mechanismus zu bauen.
|
||||||
|
- **Basis-Komponenten** (`components/`) — `Shell` (Layout + Navigation), `Table`, `Dialog`, `TextField`/`SelectField`/`CheckboxField`, `Toast`. Alle mit WCAG-2.1-AA-Grundlage (Tastaturbedienung, ARIA-Attribute, Fokus-Management).
|
||||||
|
|
||||||
|
## Verwendung in einem Modul-Frontend
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { ThemeProvider, I18nProvider, ToastProvider, Shell } from "@nexarch/shl";
|
||||||
|
|
||||||
|
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||||
|
return (
|
||||||
|
<ThemeProvider>
|
||||||
|
<I18nProvider initialLocale="de">
|
||||||
|
<ToastProvider>
|
||||||
|
<Shell modules={[]} tenantLabel="Mandant XY">
|
||||||
|
{children}
|
||||||
|
</Shell>
|
||||||
|
</ToastProvider>
|
||||||
|
</I18nProvider>
|
||||||
|
</ThemeProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Bekannter offener Punkt
|
||||||
|
|
||||||
|
Die vier bereits gebauten Core-Frontends (`TEN-05`, `LIC-04`, `AUD-04`, `OPS-02`) sind vor diesem Paket entstanden und binden es noch nicht ein — Retrofit ist der nächste Schritt, siehe `nexarch-state.json`.
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
Ausführung auf dem Test-Host (nicht lokal, siehe Projekt-Testinfrastruktur):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
npm test
|
||||||
|
npm run typecheck
|
||||||
|
```
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
// Prüfung: Tastaturbedienung der Basis-Komponenten funktioniert (SHL-01 Prüfung 2).
|
||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import { fireEvent, render, screen } from "@testing-library/react";
|
||||||
|
import { Dialog } from "../components/Dialog";
|
||||||
|
import { I18nProvider } from "../i18n/i18n";
|
||||||
|
|
||||||
|
function renderDialog(onClose: () => void) {
|
||||||
|
return render(
|
||||||
|
<I18nProvider>
|
||||||
|
<Dialog open titleId="test-title" title="Test-Dialog" onClose={onClose}>
|
||||||
|
<button type="button">Erste Aktion</button>
|
||||||
|
<button type="button">Zweite Aktion</button>
|
||||||
|
</Dialog>
|
||||||
|
</I18nProvider>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("Dialog: Tastaturbedienung", () => {
|
||||||
|
it("schließt sich bei ESC", () => {
|
||||||
|
const onClose = vi.fn();
|
||||||
|
renderDialog(onClose);
|
||||||
|
fireEvent.keyDown(document, { key: "Escape" });
|
||||||
|
expect(onClose).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("setzt den Fokus beim Öffnen auf das erste fokussierbare Element", () => {
|
||||||
|
renderDialog(vi.fn());
|
||||||
|
const closeButton = screen.getByRole("button", { name: /schließen/i });
|
||||||
|
expect(document.activeElement).toBe(closeButton);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ist als modaler Dialog mit Titel-Referenz ausgezeichnet", () => {
|
||||||
|
renderDialog(vi.fn());
|
||||||
|
const dialog = screen.getByRole("dialog");
|
||||||
|
expect(dialog).toHaveAttribute("aria-modal", "true");
|
||||||
|
expect(dialog).toHaveAttribute("aria-labelledby", "test-title");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
// Prüfung: Kontrastwerte erfüllen mindestens AA (SHL-01 Prüfung 3 / Akzeptanzkriterium 4).
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { colorTokens } from "../tokens/tokens";
|
||||||
|
|
||||||
|
// WCAG-2.1-AA-Kontrastberechnung (relative Luminanz, sRGB) — keine externe Abhängigkeit nötig.
|
||||||
|
function relLuminance(hex: string): number {
|
||||||
|
const rgb = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255);
|
||||||
|
const [r, g, b] = rgb.map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));
|
||||||
|
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||||
|
}
|
||||||
|
|
||||||
|
function contrastRatio(a: string, b: string): number {
|
||||||
|
const l1 = relLuminance(a);
|
||||||
|
const l2 = relLuminance(b);
|
||||||
|
const [lighter, darker] = l1 > l2 ? [l1, l2] : [l2, l1];
|
||||||
|
return (lighter + 0.05) / (darker + 0.05);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("Design-Tokens: WCAG 2.1 AA Kontrast", () => {
|
||||||
|
for (const scheme of ["light", "dark"] as const) {
|
||||||
|
const c = colorTokens[scheme];
|
||||||
|
|
||||||
|
it(`${scheme}: textPrimary auf background erfüllt AA (>= 4.5:1)`, () => {
|
||||||
|
expect(contrastRatio(c.textPrimary, c.background)).toBeGreaterThanOrEqual(4.5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it(`${scheme}: textSecondary auf surface erfüllt AA (>= 4.5:1)`, () => {
|
||||||
|
expect(contrastRatio(c.textSecondary, c.surface)).toBeGreaterThanOrEqual(4.5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it(`${scheme}: accentContrast auf accent erfüllt AA (>= 4.5:1)`, () => {
|
||||||
|
expect(contrastRatio(c.accentContrast, c.accent)).toBeGreaterThanOrEqual(4.5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it(`${scheme}: dangerContrast auf danger erfüllt AA (>= 4.5:1)`, () => {
|
||||||
|
expect(contrastRatio(c.dangerContrast, c.danger)).toBeGreaterThanOrEqual(4.5);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
// Dialog-Basis-Komponente — SHL-01. WCAG 2.1 AA: Fokus-Falle, ESC schließt, Tastaturbedienung vollständig.
|
||||||
|
|
||||||
|
import { useEffect, useRef } from "react";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { useI18n } from "../i18n/i18n";
|
||||||
|
|
||||||
|
const FOCUSABLE_SELECTOR =
|
||||||
|
'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';
|
||||||
|
|
||||||
|
export interface DialogProps {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
titleId: string;
|
||||||
|
title: string;
|
||||||
|
children: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Dialog({ open, onClose, titleId, title, children }: DialogProps) {
|
||||||
|
const { t } = useI18n();
|
||||||
|
const dialogRef = useRef<HTMLDivElement>(null);
|
||||||
|
const previouslyFocused = useRef<HTMLElement | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
previouslyFocused.current = document.activeElement as HTMLElement | null;
|
||||||
|
|
||||||
|
const node = dialogRef.current;
|
||||||
|
const focusables = node?.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR);
|
||||||
|
focusables?.[0]?.focus();
|
||||||
|
|
||||||
|
function handleKeyDown(event: KeyboardEvent) {
|
||||||
|
if (event.key === "Escape") {
|
||||||
|
onClose();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (event.key !== "Tab" || !node) return;
|
||||||
|
|
||||||
|
const items = Array.from(node.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR));
|
||||||
|
if (items.length === 0) return;
|
||||||
|
const first = items[0];
|
||||||
|
const last = items[items.length - 1];
|
||||||
|
|
||||||
|
if (event.shiftKey && document.activeElement === first) {
|
||||||
|
event.preventDefault();
|
||||||
|
last.focus();
|
||||||
|
} else if (!event.shiftKey && document.activeElement === last) {
|
||||||
|
event.preventDefault();
|
||||||
|
first.focus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener("keydown", handleKeyDown);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener("keydown", handleKeyDown);
|
||||||
|
previouslyFocused.current?.focus();
|
||||||
|
};
|
||||||
|
}, [open, onClose]);
|
||||||
|
|
||||||
|
if (!open) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="shl-dialog-backdrop"
|
||||||
|
role="presentation"
|
||||||
|
onMouseDown={(event) => {
|
||||||
|
if (event.target === event.currentTarget) onClose();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
ref={dialogRef}
|
||||||
|
className="shl-dialog"
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-labelledby={titleId}
|
||||||
|
>
|
||||||
|
<div className="shl-dialog-header">
|
||||||
|
<h2 id={titleId}>{title}</h2>
|
||||||
|
<button type="button" onClick={onClose} aria-label={t("shl.dialog.close")}>
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="shl-dialog-body">{children}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
// Formularelemente-Basis-Komponenten — SHL-01. WCAG: jedes Feld hat verknüpftes <label>,
|
||||||
|
// Fehler werden per aria-describedby + aria-invalid angebunden, nicht nur farblich markiert.
|
||||||
|
|
||||||
|
import { useId } from "react";
|
||||||
|
import type { InputHTMLAttributes, ReactNode, SelectHTMLAttributes } from "react";
|
||||||
|
|
||||||
|
interface FieldWrapperProps {
|
||||||
|
label: string;
|
||||||
|
error?: string;
|
||||||
|
hint?: string;
|
||||||
|
children: (ids: { inputId: string; describedBy: string | undefined }) => ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldWrapper({ label, error, hint, children }: FieldWrapperProps) {
|
||||||
|
const inputId = useId();
|
||||||
|
const hintId = hint ? `${inputId}-hint` : undefined;
|
||||||
|
const errorId = error ? `${inputId}-error` : undefined;
|
||||||
|
const describedBy = [hintId, errorId].filter(Boolean).join(" ") || undefined;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="shl-field">
|
||||||
|
<label htmlFor={inputId}>{label}</label>
|
||||||
|
{children({ inputId, describedBy })}
|
||||||
|
{hint && (
|
||||||
|
<p id={hintId} className="shl-field-hint">
|
||||||
|
{hint}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{error && (
|
||||||
|
<p id={errorId} className="shl-field-error" role="alert">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TextFieldProps
|
||||||
|
extends Omit<InputHTMLAttributes<HTMLInputElement>, "id" | "aria-describedby"> {
|
||||||
|
label: string;
|
||||||
|
error?: string;
|
||||||
|
hint?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TextField({ label, error, hint, ...inputProps }: TextFieldProps) {
|
||||||
|
return (
|
||||||
|
<FieldWrapper label={label} error={error} hint={hint}>
|
||||||
|
{({ inputId, describedBy }) => (
|
||||||
|
<input
|
||||||
|
id={inputId}
|
||||||
|
aria-describedby={describedBy}
|
||||||
|
aria-invalid={error ? true : undefined}
|
||||||
|
{...inputProps}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</FieldWrapper>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SelectFieldProps
|
||||||
|
extends Omit<SelectHTMLAttributes<HTMLSelectElement>, "id" | "aria-describedby"> {
|
||||||
|
label: string;
|
||||||
|
error?: string;
|
||||||
|
hint?: string;
|
||||||
|
children: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SelectField({ label, error, hint, children, ...selectProps }: SelectFieldProps) {
|
||||||
|
return (
|
||||||
|
<FieldWrapper label={label} error={error} hint={hint}>
|
||||||
|
{({ inputId, describedBy }) => (
|
||||||
|
<select
|
||||||
|
id={inputId}
|
||||||
|
aria-describedby={describedBy}
|
||||||
|
aria-invalid={error ? true : undefined}
|
||||||
|
{...selectProps}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</select>
|
||||||
|
)}
|
||||||
|
</FieldWrapper>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CheckboxFieldProps
|
||||||
|
extends Omit<InputHTMLAttributes<HTMLInputElement>, "id" | "type"> {
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CheckboxField({ label, ...inputProps }: CheckboxFieldProps) {
|
||||||
|
const inputId = useId();
|
||||||
|
return (
|
||||||
|
<div className="shl-field shl-field-checkbox">
|
||||||
|
<input id={inputId} type="checkbox" {...inputProps} />
|
||||||
|
<label htmlFor={inputId}>{label}</label>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
// Layout-Shell mit Navigation — SHL-01 Akzeptanzkriterium 1.
|
||||||
|
// Globale Navigation zeigt nur Module, die Core für Tenant/Benutzer freigibt (Backend entscheidet, UI blendet nur aus).
|
||||||
|
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { useI18n } from "../i18n/i18n";
|
||||||
|
import { useTheme } from "../theme/ThemeProvider";
|
||||||
|
|
||||||
|
export interface ModuleLink {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
href: string;
|
||||||
|
active?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ShellProps {
|
||||||
|
modules: ModuleLink[];
|
||||||
|
tenantLabel: string;
|
||||||
|
children: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Shell({ modules, tenantLabel, children }: ShellProps) {
|
||||||
|
const { scheme, toggle } = useTheme();
|
||||||
|
const { t } = useI18n();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="shl-shell">
|
||||||
|
<a className="shl-skip-link" href="#shl-main-content">
|
||||||
|
{t("shl.shell.skipToContent", "Zum Inhalt springen")}
|
||||||
|
</a>
|
||||||
|
<header className="shl-shell-header">
|
||||||
|
<nav aria-label={t("shl.shell.moduleNav", "Modul-Navigation")}>
|
||||||
|
<ul>
|
||||||
|
{modules.map((mod) => (
|
||||||
|
<li key={mod.key}>
|
||||||
|
<a href={mod.href} aria-current={mod.active ? "page" : undefined}>
|
||||||
|
{mod.label}
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</nav>
|
||||||
|
<div className="shl-shell-context">
|
||||||
|
<span className="shl-tenant-context">{tenantLabel}</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={toggle}
|
||||||
|
aria-label={
|
||||||
|
scheme === "light" ? t("shl.theme.toggleToDark") : t("shl.theme.toggleToLight")
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{scheme === "light" ? "🌙" : "☀️"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<main id="shl-main-content" className="shl-shell-content" tabIndex={-1}>
|
||||||
|
{children}
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
// Table-Basis-Komponente — SHL-01. WCAG: semantische <table>, scope auf Kopfzellen, sortierbare Spalten per Tastatur.
|
||||||
|
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { useI18n } from "../i18n/i18n";
|
||||||
|
|
||||||
|
export interface TableColumn<Row> {
|
||||||
|
key: string;
|
||||||
|
header: string;
|
||||||
|
render: (row: Row) => ReactNode;
|
||||||
|
sortable?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TableProps<Row> {
|
||||||
|
columns: TableColumn<Row>[];
|
||||||
|
rows: Row[];
|
||||||
|
rowKey: (row: Row) => string;
|
||||||
|
sortKey?: string;
|
||||||
|
sortDirection?: "asc" | "desc";
|
||||||
|
onSort?: (key: string) => void;
|
||||||
|
caption?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Table<Row>({
|
||||||
|
columns,
|
||||||
|
rows,
|
||||||
|
rowKey,
|
||||||
|
sortKey,
|
||||||
|
sortDirection,
|
||||||
|
onSort,
|
||||||
|
caption,
|
||||||
|
}: TableProps<Row>) {
|
||||||
|
const { t } = useI18n();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<table className="shl-table">
|
||||||
|
{caption && <caption>{caption}</caption>}
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
{columns.map((column) => {
|
||||||
|
const isSorted = column.key === sortKey;
|
||||||
|
const ariaSort = column.sortable
|
||||||
|
? isSorted
|
||||||
|
? sortDirection === "asc"
|
||||||
|
? "ascending"
|
||||||
|
: "descending"
|
||||||
|
: "none"
|
||||||
|
: undefined;
|
||||||
|
return (
|
||||||
|
<th key={column.key} scope="col" aria-sort={ariaSort}>
|
||||||
|
{column.sortable ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onSort?.(column.key)}
|
||||||
|
className="shl-table-sort-button"
|
||||||
|
>
|
||||||
|
{column.header}
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
column.header
|
||||||
|
)}
|
||||||
|
</th>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{rows.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={columns.length}>{t("shl.table.noRows")}</td>
|
||||||
|
</tr>
|
||||||
|
) : (
|
||||||
|
rows.map((row) => (
|
||||||
|
<tr key={rowKey(row)}>
|
||||||
|
{columns.map((column) => (
|
||||||
|
<td key={column.key}>{column.render(row)}</td>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
// Toast-Basis-Komponente — SHL-01. WCAG: aria-live sorgt dafür, dass Screenreader Meldungen ansagen.
|
||||||
|
|
||||||
|
import { createContext, useCallback, useContext, useMemo, useState } from "react";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { useI18n } from "../i18n/i18n";
|
||||||
|
|
||||||
|
export type ToastVariant = "info" | "success" | "danger" | "warning";
|
||||||
|
|
||||||
|
export interface ToastMessage {
|
||||||
|
id: string;
|
||||||
|
text: string;
|
||||||
|
variant: ToastVariant;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ToastContextValue {
|
||||||
|
toasts: ToastMessage[];
|
||||||
|
push: (text: string, variant?: ToastVariant) => void;
|
||||||
|
dismiss: (id: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ToastContext = createContext<ToastContextValue | null>(null);
|
||||||
|
|
||||||
|
export function ToastProvider({ children }: { children: ReactNode }) {
|
||||||
|
const [toasts, setToasts] = useState<ToastMessage[]>([]);
|
||||||
|
const { t } = useI18n();
|
||||||
|
|
||||||
|
const dismiss = useCallback((id: string) => {
|
||||||
|
setToasts((current) => current.filter((toast) => toast.id !== id));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const push = useCallback((text: string, variant: ToastVariant = "info") => {
|
||||||
|
const id = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||||
|
setToasts((current) => [...current, { id, text, variant }]);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const value = useMemo(() => ({ toasts, push, dismiss }), [toasts, push, dismiss]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ToastContext.Provider value={value}>
|
||||||
|
{children}
|
||||||
|
<div className="shl-toast-region" role="status" aria-live="polite" aria-atomic="false">
|
||||||
|
{toasts.map((toast) => (
|
||||||
|
<div key={toast.id} className={`shl-toast shl-toast-${toast.variant}`}>
|
||||||
|
<span>{toast.text}</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => dismiss(toast.id)}
|
||||||
|
aria-label={t("shl.toast.dismiss")}
|
||||||
|
>
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</ToastContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useToast(): ToastContextValue {
|
||||||
|
const ctx = useContext(ToastContext);
|
||||||
|
if (!ctx) {
|
||||||
|
throw new Error("useToast muss innerhalb von <ToastProvider> aufgerufen werden");
|
||||||
|
}
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
// i18n-Rahmen (mind. Deutsch/Englisch) — SHL-01 Akzeptanzkriterium 5.
|
||||||
|
// Liefert nur den Umschaltmechanismus + Basis-Komponenten-Texte.
|
||||||
|
// Modul-Frontends liefern ihre eigenen fachlichen Textbausteine über registerMessages(),
|
||||||
|
// statt einen eigenen i18n-Mechanismus zu bauen (siehe UI-UX-KONZEPT.md Abschnitt 4).
|
||||||
|
|
||||||
|
import { createContext, useContext, useMemo, useState } from "react";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
|
||||||
|
export type Locale = "de" | "en";
|
||||||
|
|
||||||
|
type MessageDict = Record<string, string>;
|
||||||
|
type MessageBundle = Record<Locale, MessageDict>;
|
||||||
|
|
||||||
|
const baseMessages: MessageBundle = {
|
||||||
|
de: {
|
||||||
|
"shl.dialog.close": "Schließen",
|
||||||
|
"shl.toast.dismiss": "Meldung schließen",
|
||||||
|
"shl.table.noRows": "Keine Einträge vorhanden",
|
||||||
|
"shl.theme.toggleToLight": "Helles Erscheinungsbild",
|
||||||
|
"shl.theme.toggleToDark": "Dunkles Erscheinungsbild",
|
||||||
|
},
|
||||||
|
en: {
|
||||||
|
"shl.dialog.close": "Close",
|
||||||
|
"shl.toast.dismiss": "Dismiss message",
|
||||||
|
"shl.table.noRows": "No entries",
|
||||||
|
"shl.theme.toggleToLight": "Switch to light theme",
|
||||||
|
"shl.theme.toggleToDark": "Switch to dark theme",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// Registry, in die Modul-Frontends ihre eigenen Textbausteine einhängen.
|
||||||
|
const registry: MessageBundle = { de: { ...baseMessages.de }, en: { ...baseMessages.en } };
|
||||||
|
|
||||||
|
export function registerMessages(locale: Locale, messages: MessageDict): void {
|
||||||
|
registry[locale] = { ...registry[locale], ...messages };
|
||||||
|
}
|
||||||
|
|
||||||
|
interface I18nContextValue {
|
||||||
|
locale: Locale;
|
||||||
|
setLocale: (locale: Locale) => void;
|
||||||
|
t: (key: string, fallback?: string) => string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const I18nContext = createContext<I18nContextValue | null>(null);
|
||||||
|
|
||||||
|
export function I18nProvider({
|
||||||
|
initialLocale = "de",
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
initialLocale?: Locale;
|
||||||
|
children: ReactNode;
|
||||||
|
}) {
|
||||||
|
const [locale, setLocale] = useState<Locale>(initialLocale);
|
||||||
|
|
||||||
|
const value = useMemo<I18nContextValue>(
|
||||||
|
() => ({
|
||||||
|
locale,
|
||||||
|
setLocale,
|
||||||
|
t: (key: string, fallback?: string) => registry[locale][key] ?? fallback ?? key,
|
||||||
|
}),
|
||||||
|
[locale],
|
||||||
|
);
|
||||||
|
|
||||||
|
return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useI18n(): I18nContextValue {
|
||||||
|
const ctx = useContext(I18nContext);
|
||||||
|
if (!ctx) {
|
||||||
|
throw new Error("useI18n muss innerhalb von <I18nProvider> aufgerufen werden");
|
||||||
|
}
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
// Öffentliche Schnittstelle des Pakets @nexarch/shl — Modul-Frontends importieren ausschließlich hierüber,
|
||||||
|
// nicht aus internen Unterpfaden (SHL-01 Akzeptanzkriterium 2: dokumentiert, versioniert, importierbar statt kopiert).
|
||||||
|
|
||||||
|
export { colorTokens, spacing, breakpoints, typography, cssVariables } from "./tokens/tokens";
|
||||||
|
export type { ColorScheme, ColorTokens } from "./tokens/tokens";
|
||||||
|
|
||||||
|
export { ThemeProvider, useTheme, currentColors } from "./theme/ThemeProvider";
|
||||||
|
|
||||||
|
export { I18nProvider, useI18n, registerMessages } from "./i18n/i18n";
|
||||||
|
export type { Locale } from "./i18n/i18n";
|
||||||
|
|
||||||
|
export { Shell } from "./components/Shell";
|
||||||
|
export type { ShellProps, ModuleLink } from "./components/Shell";
|
||||||
|
|
||||||
|
export { Dialog } from "./components/Dialog";
|
||||||
|
export type { DialogProps } from "./components/Dialog";
|
||||||
|
|
||||||
|
export { Table } from "./components/Table";
|
||||||
|
export type { TableProps, TableColumn } from "./components/Table";
|
||||||
|
|
||||||
|
export { TextField, SelectField, CheckboxField } from "./components/FormElements";
|
||||||
|
export type { TextFieldProps, SelectFieldProps, CheckboxFieldProps } from "./components/FormElements";
|
||||||
|
|
||||||
|
export { ToastProvider, useToast } from "./components/Toast";
|
||||||
|
export type { ToastMessage, ToastVariant } from "./components/Toast";
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"name": "@nexarch/shl",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"description": "NEXARCH UI-Shell & Design-System (Core SHL-01) — gemeinsames Paket für alle Modul-Frontends.",
|
||||||
|
"main": "index.ts",
|
||||||
|
"types": "index.ts",
|
||||||
|
"scripts": {
|
||||||
|
"test": "vitest run",
|
||||||
|
"typecheck": "tsc --noEmit"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": "^18.3.1",
|
||||||
|
"react-dom": "^18.3.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@testing-library/jest-dom": "^6.4.8",
|
||||||
|
"@testing-library/react": "^16.0.0",
|
||||||
|
"@types/react": "18.3.3",
|
||||||
|
"@types/react-dom": "18.3.0",
|
||||||
|
"jsdom": "^24.1.1",
|
||||||
|
"typescript": "5.5.3",
|
||||||
|
"vitest": "^2.0.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
// Zentrales Theming (Hell/Dunkel) — SHL-01 Akzeptanzkriterium 6.
|
||||||
|
// Einzige Quelle für Hell/Dunkel-Werte; Modul-Frontends schalten nur um, bauen kein eigenes Theming.
|
||||||
|
|
||||||
|
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { colorTokens, cssVariables, type ColorScheme } from "../tokens/tokens";
|
||||||
|
|
||||||
|
const STORAGE_KEY = "nexarch-shl-theme";
|
||||||
|
|
||||||
|
interface ThemeContextValue {
|
||||||
|
scheme: ColorScheme;
|
||||||
|
setScheme: (scheme: ColorScheme) => void;
|
||||||
|
toggle: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ThemeContext = createContext<ThemeContextValue | null>(null);
|
||||||
|
|
||||||
|
function readStoredScheme(): ColorScheme | null {
|
||||||
|
if (typeof window === "undefined") return null;
|
||||||
|
try {
|
||||||
|
const stored = window.localStorage.getItem(STORAGE_KEY);
|
||||||
|
return stored === "light" || stored === "dark" ? stored : null;
|
||||||
|
} catch {
|
||||||
|
// localStorage kann in privaten Fenstern/eingeschränkten Kontexten fehlschlagen — kein Absturz, nur kein persistierter Zustand.
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function systemPrefersDark(): boolean {
|
||||||
|
if (typeof window === "undefined" || !window.matchMedia) return false;
|
||||||
|
return window.matchMedia("(prefers-color-scheme: dark)").matches;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||||
|
const [scheme, setSchemeState] = useState<ColorScheme>("light");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const stored = readStoredScheme();
|
||||||
|
setSchemeState(stored ?? (systemPrefersDark() ? "dark" : "light"));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const setScheme = useCallback((next: ColorScheme) => {
|
||||||
|
setSchemeState(next);
|
||||||
|
try {
|
||||||
|
window.localStorage.setItem(STORAGE_KEY, next);
|
||||||
|
} catch {
|
||||||
|
// Speichern optional — Umschaltung funktioniert auch ohne Persistenz.
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const toggle = useCallback(() => {
|
||||||
|
setScheme(scheme === "light" ? "dark" : "light");
|
||||||
|
}, [scheme, setScheme]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const vars = cssVariables(scheme);
|
||||||
|
const root = document.documentElement;
|
||||||
|
for (const [key, value] of Object.entries(vars)) {
|
||||||
|
root.style.setProperty(key, value);
|
||||||
|
}
|
||||||
|
root.dataset.shlTheme = scheme;
|
||||||
|
}, [scheme]);
|
||||||
|
|
||||||
|
const value = useMemo(() => ({ scheme, setScheme, toggle }), [scheme, setScheme, toggle]);
|
||||||
|
|
||||||
|
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useTheme(): ThemeContextValue {
|
||||||
|
const ctx = useContext(ThemeContext);
|
||||||
|
if (!ctx) {
|
||||||
|
throw new Error("useTheme muss innerhalb von <ThemeProvider> aufgerufen werden");
|
||||||
|
}
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function currentColors(scheme: ColorScheme) {
|
||||||
|
return colorTokens[scheme];
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
// Design-Tokens: einzige Quelle für Farbe, Abstand, Typografie im gesamten Frontend-Verbund.
|
||||||
|
// Modul-Frontends importieren diese Tokens, überschreiben sie nicht lokal (SHL-01 Akzeptanzkriterium 3).
|
||||||
|
// Kontrastwerte sind gegen WCAG 2.1 AA geprüft (Akzeptanzkriterium 1/4): mindestens 4.5:1 für Fließtext.
|
||||||
|
|
||||||
|
export type ColorScheme = "light" | "dark";
|
||||||
|
|
||||||
|
export interface ColorTokens {
|
||||||
|
background: string;
|
||||||
|
surface: string;
|
||||||
|
surfaceRaised: string;
|
||||||
|
border: string;
|
||||||
|
textPrimary: string;
|
||||||
|
textSecondary: string;
|
||||||
|
accent: string;
|
||||||
|
accentContrast: string;
|
||||||
|
danger: string;
|
||||||
|
dangerContrast: string;
|
||||||
|
success: string;
|
||||||
|
warning: string;
|
||||||
|
focusRing: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Kontrastwerte geprüft: textPrimary auf background/surface >= 7:1, textSecondary >= 4.5:1,
|
||||||
|
// accentContrast auf accent >= 4.5:1 (WCAG AA, siehe SHL-01 Prüfung 3).
|
||||||
|
export const colorTokens: Record<ColorScheme, ColorTokens> = {
|
||||||
|
light: {
|
||||||
|
background: "#FFFFFF",
|
||||||
|
surface: "#F5F6F8",
|
||||||
|
surfaceRaised: "#FFFFFF",
|
||||||
|
border: "#D7DBE0",
|
||||||
|
textPrimary: "#14181F",
|
||||||
|
textSecondary: "#4B5563",
|
||||||
|
accent: "#1D4ED8",
|
||||||
|
accentContrast: "#FFFFFF",
|
||||||
|
danger: "#B91C1C",
|
||||||
|
dangerContrast: "#FFFFFF",
|
||||||
|
success: "#15803D",
|
||||||
|
warning: "#B45309",
|
||||||
|
focusRing: "#1D4ED8",
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
background: "#0F1115",
|
||||||
|
surface: "#181B21",
|
||||||
|
surfaceRaised: "#20242C",
|
||||||
|
border: "#333944",
|
||||||
|
textPrimary: "#F2F4F7",
|
||||||
|
textSecondary: "#B4BAC4",
|
||||||
|
accent: "#5B8DEF",
|
||||||
|
accentContrast: "#0F1115",
|
||||||
|
danger: "#F87171",
|
||||||
|
dangerContrast: "#0F1115",
|
||||||
|
success: "#4ADE80",
|
||||||
|
warning: "#FBBF24",
|
||||||
|
focusRing: "#5B8DEF",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export const spacing = {
|
||||||
|
xs: "4px",
|
||||||
|
sm: "8px",
|
||||||
|
md: "16px",
|
||||||
|
lg: "24px",
|
||||||
|
xl: "32px",
|
||||||
|
xxl: "48px",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export const breakpoints = {
|
||||||
|
mobile: "0px",
|
||||||
|
tablet: "768px",
|
||||||
|
desktop: "1200px",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export const typography = {
|
||||||
|
fontFamily: "'Inter', 'Segoe UI', system-ui, sans-serif",
|
||||||
|
fontFamilyMono: "'JetBrains Mono', ui-monospace, monospace",
|
||||||
|
sizeSm: "13px",
|
||||||
|
sizeMd: "15px",
|
||||||
|
sizeLg: "18px",
|
||||||
|
sizeXl: "24px",
|
||||||
|
lineHeight: 1.5,
|
||||||
|
weightRegular: 400,
|
||||||
|
weightMedium: 500,
|
||||||
|
weightBold: 600,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export function cssVariables(scheme: ColorScheme): Record<string, string> {
|
||||||
|
const c = colorTokens[scheme];
|
||||||
|
const vars: Record<string, string> = {};
|
||||||
|
for (const [key, value] of Object.entries(c)) {
|
||||||
|
vars[`--shl-color-${key.replace(/([A-Z])/g, "-$1").toLowerCase()}`] = value;
|
||||||
|
}
|
||||||
|
for (const [key, value] of Object.entries(spacing)) {
|
||||||
|
vars[`--shl-spacing-${key}`] = value;
|
||||||
|
}
|
||||||
|
return vars;
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2020",
|
||||||
|
"lib": ["dom", "dom.iterable", "esnext"],
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"strict": true,
|
||||||
|
"declaration": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true
|
||||||
|
},
|
||||||
|
"include": ["**/*.ts", "**/*.tsx"],
|
||||||
|
"exclude": ["node_modules"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { defineConfig } from "vitest/config";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
environment: "jsdom",
|
||||||
|
setupFiles: ["./vitest.setup.ts"],
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import "@testing-library/jest-dom/vitest";
|
||||||
|
import { afterEach } from "vitest";
|
||||||
|
import { cleanup } from "@testing-library/react";
|
||||||
|
|
||||||
|
// Ohne explizites Cleanup bleiben zwischen den it()-Blöcken gerenderte Dialoge im DOM stehen
|
||||||
|
// (mehrere <html>/<body>-Bäume stapeln sich), wodurch getByRole() mehrere Treffer statt einen findet.
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user