diff --git a/collector/main.go b/collector/main.go index afafd09df..bbf9b8abc 100644 --- a/collector/main.go +++ b/collector/main.go @@ -82,6 +82,11 @@ type containerInfo struct { } type containerStats struct { + // Read/Preread timestamps and NumProcs are used for the Windows CPU formula, + // which has no system_cpu_usage to divide by (#1574). + Read string `json:"read"` + Preread string `json:"preread"` + NumProcs uint32 `json:"num_procs"` CPUStats struct { CPUUsage struct { TotalUsage uint64 `json:"total_usage"` @@ -97,13 +102,76 @@ type containerStats struct { } `json:"precpu_stats"` MemoryStats struct { Usage uint64 `json:"usage"` - Stats struct { + // Windows reports memory as privateworkingset (already cache-free) instead + // of usage; a nil pointer means the payload is a Unix one (#1574). + PrivateWorkingSet *uint64 `json:"privateworkingset"` + Stats struct { InactiveFile uint64 `json:"inactive_file"` TotalInactiveFile uint64 `json:"total_inactive_file"` } `json:"stats"` } `json:"memory_stats"` } +// calcCPUPercent mirrors src/lib/server/stats-calc-core.ts. Unix uses the +// cpu-vs-system delta ratio; Windows has no system_cpu_usage, so it uses the +// wall-clock formula (num_procs * elapsed) - detected by privateworkingset (#1574). +func calcCPUPercent(s *containerStats) float64 { + // Compare BEFORE subtracting: uint64 underflow (precpu > cpu on a first sample + // or a counter reset) would wrap to a huge positive and slip past a >0 guard, + // producing an absurd CPU%. A non-increasing counter means no usage -> 0. + cur := s.CPUStats.CPUUsage.TotalUsage + prev := s.PrecpuStats.CPUUsage.TotalUsage + if cur <= prev { + return 0 + } + cpuDelta := float64(cur - prev) + + if s.MemoryStats.PrivateWorkingSet != nil { + read, errR := time.Parse(time.RFC3339Nano, s.Read) + preread, errP := time.Parse(time.RFC3339Nano, s.Preread) + if errR != nil || errP != nil { + return 0 + } + // possIntervals = num_procs * elapsed-MILLISECONDS; cpu% = cpuDelta / (possIntervals*100). + // Matches the Docker CLI / Portainer Windows formula and the TS core. + elapsedMs := float64(read.Sub(preread).Milliseconds()) + possIntervals := float64(s.NumProcs) * elapsedMs + if possIntervals > 0 { + return cpuDelta / (possIntervals * 100) + } + return 0 + } + + curSys := s.CPUStats.SystemCPUUsage + prevSys := s.PrecpuStats.SystemCPUUsage + if curSys <= prevSys { + return 0 + } + sysDelta := float64(curSys - prevSys) + cpuCount := s.CPUStats.OnlineCPUs + if cpuCount == 0 { + cpuCount = 1 + } + return (cpuDelta / sysDelta) * float64(cpuCount) * 100 +} + +// calcMemUsage mirrors the TS core: Windows uses privateworkingset (cache-free), +// Unix subtracts inactive-file cache from usage. +func calcMemUsage(s *containerStats) uint64 { + if s.MemoryStats.PrivateWorkingSet != nil { + return *s.MemoryStats.PrivateWorkingSet + } + memUsage := s.MemoryStats.Usage + memCache := s.MemoryStats.Stats.InactiveFile + if memCache == 0 { + memCache = s.MemoryStats.Stats.TotalInactiveFile + } + if memCache > 0 && memCache < memUsage { + return memUsage - memCache + } + return memUsage +} + type dockerInfo struct { MemTotal int64 `json:"MemTotal"` NCPU int `json:"NCPU"` @@ -496,27 +564,8 @@ func (m *manager) collectMetrics(env *environment) { return } - cpuDelta := float64(stats.CPUStats.CPUUsage.TotalUsage - stats.PrecpuStats.CPUUsage.TotalUsage) - sysDelta := float64(stats.CPUStats.SystemCPUUsage - stats.PrecpuStats.SystemCPUUsage) - cpuCount := stats.CPUStats.OnlineCPUs - if cpuCount == 0 { - cpuCount = 1 - } - - var cpuPct float64 - if sysDelta > 0 && cpuDelta > 0 { - cpuPct = (cpuDelta / sysDelta) * float64(cpuCount) * 100 - } - - memUsage := stats.MemoryStats.Usage - memCache := stats.MemoryStats.Stats.InactiveFile - if memCache == 0 { - memCache = stats.MemoryStats.Stats.TotalInactiveFile - } - actualMem := memUsage - if memCache > 0 && memCache < memUsage { - actualMem = memUsage - memCache - } + cpuPct := calcCPUPercent(&stats) + actualMem := calcMemUsage(&stats) results[idx] = statsResult{cpu: cpuPct, mem: actualMem} }(i, c.ID) diff --git a/collector/main_test.go b/collector/main_test.go new file mode 100644 index 000000000..c82a411b2 --- /dev/null +++ b/collector/main_test.go @@ -0,0 +1,109 @@ +package main + +import ( + "encoding/json" + "math" + "testing" +) + +// mustStats decodes a JSON stats payload into containerStats for the tests. +func mustStats(t *testing.T, jsonStr string) *containerStats { + t.Helper() + var s containerStats + if err := json.Unmarshal([]byte(jsonStr), &s); err != nil { + t.Fatalf("decode: %v", err) + } + return &s +} + +const unixPayload = `{ + "read": "2026-09-15T10:00:01Z", + "preread": "2026-09-15T10:00:00Z", + "cpu_stats": {"cpu_usage": {"total_usage": 2000000000}, "system_cpu_usage": 20000000000, "online_cpus": 4}, + "precpu_stats": {"cpu_usage": {"total_usage": 1000000000}, "system_cpu_usage": 18000000000}, + "memory_stats": {"usage": 209715200, "stats": {"inactive_file": 52428800}} +}` + +// Windows: no system_cpu_usage, privateworkingset present, 1000ms elapsed, 2 procs. +const windowsPayload = `{ + "read": "2026-09-15T10:00:01.0000000Z", + "preread": "2026-09-15T10:00:00.0000000Z", + "num_procs": 2, + "cpu_stats": {"cpu_usage": {"total_usage": 500000000}}, + "precpu_stats": {"cpu_usage": {"total_usage": 400000000}}, + "memory_stats": {"privateworkingset": 134217728} +}` + +func closeTo(a, b float64) bool { return math.Abs(a-b) < 1e-6 } + +func TestCalcCPUPercentUnix(t *testing.T) { + // cpuDelta=1e9, sysDelta=2e9, cpuCount=4 -> 0.5*4*100 = 200 + got := calcCPUPercent(mustStats(t, unixPayload)) + if !closeTo(got, 200) { + t.Fatalf("unix cpu: got %v want 200", got) + } +} + +func TestCalcCPUPercentWindows(t *testing.T) { + // cpuDelta=1e8, elapsed=1000ms, num_procs=2 -> possIntervals=2000 + // cpu = cpuDelta / (possIntervals*100) = 1e8/(2000*100) = 500. Matches the TS core. + got := calcCPUPercent(mustStats(t, windowsPayload)) + want := 1e8 / (2 * 1000 * 100) + if !closeTo(got, want) { + t.Fatalf("windows cpu: got %v want %v", got, want) + } + if !closeTo(got, 500) { + t.Fatalf("windows cpu: got %v want 500", got) + } + if got <= 0 { + t.Fatalf("windows cpu must be > 0 (proves the Windows branch ran, not the Unix 0)") + } +} + +func TestCalcCPUPercentWindowsZeroElapsed(t *testing.T) { + s := mustStats(t, windowsPayload) + s.Preread = s.Read // no elapsed time + if got := calcCPUPercent(s); got != 0 { + t.Fatalf("zero elapsed must be 0, got %v", got) + } +} + +func TestCalcMemUsageUnix(t *testing.T) { + // 200MiB usage - 50MiB cache = 150MiB + got := calcMemUsage(mustStats(t, unixPayload)) + if got != 150*1024*1024 { + t.Fatalf("unix mem: got %d want %d", got, 150*1024*1024) + } +} + +func TestCalcMemUsageWindows(t *testing.T) { + // privateworkingset used directly, no cache subtraction + got := calcMemUsage(mustStats(t, windowsPayload)) + if got != 128*1024*1024 { + t.Fatalf("windows mem: got %d want %d", got, 128*1024*1024) + } + if got == 0 { + t.Fatalf("windows mem must not be 0 (the #1574 symptom)") + } +} + +func TestCalcCPUPercentCounterReset(t *testing.T) { + // precpu > cpu (counter reset / first sample). uint64 subtraction would wrap to a + // huge positive; the fix must return 0, not garbage. Both Unix and Windows branches. + unixReset := mustStats(t, `{"cpu_stats":{"cpu_usage":{"total_usage":1000},"system_cpu_usage":5000,"online_cpus":2},"precpu_stats":{"cpu_usage":{"total_usage":2000},"system_cpu_usage":4000},"memory_stats":{"usage":1000}}`) + if got := calcCPUPercent(unixReset); got != 0 { + t.Fatalf("unix counter reset must be 0 (no uint64 underflow garbage), got %v", got) + } + winReset := mustStats(t, `{"read":"2026-09-15T10:00:01Z","preread":"2026-09-15T10:00:00Z","num_procs":2,"cpu_stats":{"cpu_usage":{"total_usage":1000}},"precpu_stats":{"cpu_usage":{"total_usage":2000}},"memory_stats":{"privateworkingset":1000}}`) + if got := calcCPUPercent(winReset); got != 0 { + t.Fatalf("windows counter reset must be 0, got %v", got) + } +} + +func TestCalcCPUPercentSystemCounterReset(t *testing.T) { + // cpu increases but SYSTEM counter went backwards -> sysDelta underflow guard. + s := mustStats(t, `{"cpu_stats":{"cpu_usage":{"total_usage":2000},"system_cpu_usage":4000,"online_cpus":2},"precpu_stats":{"cpu_usage":{"total_usage":1000},"system_cpu_usage":5000},"memory_stats":{"usage":1000}}`) + if got := calcCPUPercent(s); got != 0 { + t.Fatalf("system counter reset must be 0, got %v", got) + } +} diff --git a/drizzle-pg/0016_add_tags.sql b/drizzle-pg/0016_add_tags.sql new file mode 100644 index 000000000..11a5a668f --- /dev/null +++ b/drizzle-pg/0016_add_tags.sql @@ -0,0 +1,31 @@ +CREATE TABLE "container_tags" ( + "id" serial PRIMARY KEY NOT NULL, + "container_name" text NOT NULL, + "environment_id" integer, + "tag_id" integer NOT NULL, + "created_at" timestamp DEFAULT now(), + CONSTRAINT "container_tags_container_name_environment_id_tag_id_unique" UNIQUE("container_name","environment_id","tag_id") +); +--> statement-breakpoint +CREATE TABLE "stack_tags" ( + "id" serial PRIMARY KEY NOT NULL, + "stack_name" text NOT NULL, + "environment_id" integer, + "tag_id" integer NOT NULL, + "created_at" timestamp DEFAULT now(), + CONSTRAINT "stack_tags_stack_name_environment_id_tag_id_unique" UNIQUE("stack_name","environment_id","tag_id") +); +--> statement-breakpoint +CREATE TABLE "tags" ( + "id" serial PRIMARY KEY NOT NULL, + "name" text NOT NULL, + "color" text DEFAULT 'slate' NOT NULL, + "icon" text, + "created_at" timestamp DEFAULT now() +); +--> statement-breakpoint +CREATE UNIQUE INDEX "tags_name_unique" ON "tags" (lower("name"));--> statement-breakpoint +ALTER TABLE "container_tags" ADD CONSTRAINT "container_tags_environment_id_environments_id_fk" FOREIGN KEY ("environment_id") REFERENCES "public"."environments"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "container_tags" ADD CONSTRAINT "container_tags_tag_id_tags_id_fk" FOREIGN KEY ("tag_id") REFERENCES "public"."tags"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "stack_tags" ADD CONSTRAINT "stack_tags_environment_id_environments_id_fk" FOREIGN KEY ("environment_id") REFERENCES "public"."environments"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "stack_tags" ADD CONSTRAINT "stack_tags_tag_id_tags_id_fk" FOREIGN KEY ("tag_id") REFERENCES "public"."tags"("id") ON DELETE cascade ON UPDATE no action; \ No newline at end of file diff --git a/drizzle-pg/meta/0016_snapshot.json b/drizzle-pg/meta/0016_snapshot.json new file mode 100644 index 000000000..0bfb46288 --- /dev/null +++ b/drizzle-pg/meta/0016_snapshot.json @@ -0,0 +1,3817 @@ +{ + "id": "1be6c489-8ecf-4a22-b2d3-d4b871238b2e", + "prevId": "7b17f0e4-3123-4178-a85a-93c6ea6a46d5", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.api_tokens": { + "name": "api_tokens", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_prefix": { + "name": "token_prefix", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_used": { + "name": "last_used", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": { + "api_tokens_user_id_idx": { + "name": "api_tokens_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "api_tokens_token_prefix_idx": { + "name": "api_tokens_token_prefix_idx", + "columns": [ + { + "expression": "token_prefix", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "api_tokens_user_id_users_id_fk": { + "name": "api_tokens_user_id_users_id_fk", + "tableFrom": "api_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "api_tokens_token_hash_unique": { + "name": "api_tokens_token_hash_unique", + "nullsNotDistinct": false, + "columns": [ + "token_hash" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.audit_logs": { + "name": "audit_logs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "username": { + "name": "username", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "entity_name": { + "name": "entity_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "details": { + "name": "details", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": { + "audit_logs_user_id_idx": { + "name": "audit_logs_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "audit_logs_created_at_idx": { + "name": "audit_logs_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "audit_logs_user_id_users_id_fk": { + "name": "audit_logs_user_id_users_id_fk", + "tableFrom": "audit_logs", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "audit_logs_environment_id_environments_id_fk": { + "name": "audit_logs_environment_id_environments_id_fk", + "tableFrom": "audit_logs", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.auth_settings": { + "name": "auth_settings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "auth_enabled": { + "name": "auth_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "default_provider": { + "name": "default_provider", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'local'" + }, + "session_timeout": { + "name": "session_timeout", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 86400 + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.auto_update_settings": { + "name": "auto_update_settings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "container_name": { + "name": "container_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "schedule_type": { + "name": "schedule_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'daily'" + }, + "cron_expression": { + "name": "cron_expression", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "vulnerability_criteria": { + "name": "vulnerability_criteria", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'never'" + }, + "last_checked": { + "name": "last_checked", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_updated": { + "name": "last_updated", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "auto_update_settings_environment_id_environments_id_fk": { + "name": "auto_update_settings_environment_id_environments_id_fk", + "tableFrom": "auto_update_settings", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "auto_update_settings_environment_id_container_name_unique": { + "name": "auto_update_settings_environment_id_container_name_unique", + "nullsNotDistinct": false, + "columns": [ + "environment_id", + "container_name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.backup_configs": { + "name": "backup_configs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'container'" + }, + "target_name": { + "name": "target_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "destination_id": { + "name": "destination_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": true + }, + "all_volumes": { + "name": "all_volumes", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": true + }, + "selected_volumes": { + "name": "selected_volumes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stop_before_backup": { + "name": "stop_before_backup", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "schedule": { + "name": "schedule", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "retention": { + "name": "retention", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "options": { + "name": "options", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tags": { + "name": "tags", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_backup_at": { + "name": "last_backup_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_backup_status": { + "name": "last_backup_status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "backup_configs_environment_id_environments_id_fk": { + "name": "backup_configs_environment_id_environments_id_fk", + "tableFrom": "backup_configs", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "backup_configs_destination_id_backup_destinations_id_fk": { + "name": "backup_configs_destination_id_backup_destinations_id_fk", + "tableFrom": "backup_configs", + "tableTo": "backup_destinations", + "columnsFrom": [ + "destination_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.backup_destinations": { + "name": "backup_destinations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "repository": { + "name": "repository", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "env_vars": { + "name": "env_vars", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "flags": { + "name": "flags", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "host_path": { + "name": "host_path", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cacert": { + "name": "cacert", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tls_client_cert": { + "name": "tls_client_cert", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "policies": { + "name": "policies", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_test_at": { + "name": "last_test_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_test_status": { + "name": "last_test_status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_test_error": { + "name": "last_test_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "backup_destinations_name_unique": { + "name": "backup_destinations_name_unique", + "nullsNotDistinct": false, + "columns": [ + "name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.config_sets": { + "name": "config_sets", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "env_vars": { + "name": "env_vars", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "labels": { + "name": "labels", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ports": { + "name": "ports", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "volumes": { + "name": "volumes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "network_mode": { + "name": "network_mode", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'bridge'" + }, + "restart_policy": { + "name": "restart_policy", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'no'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "config_sets_name_unique": { + "name": "config_sets_name_unique", + "nullsNotDistinct": false, + "columns": [ + "name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.container_events": { + "name": "container_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "container_id": { + "name": "container_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "container_name": { + "name": "container_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_attributes": { + "name": "actor_attributes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "timestamp": { + "name": "timestamp", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": { + "container_events_env_timestamp_idx": { + "name": "container_events_env_timestamp_idx", + "columns": [ + { + "expression": "environment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "timestamp", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "container_events_environment_id_environments_id_fk": { + "name": "container_events_environment_id_environments_id_fk", + "tableFrom": "container_events", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.container_icon_overrides": { + "name": "container_icon_overrides", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "container_name": { + "name": "container_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "container_icon_overrides_environment_id_environments_id_fk": { + "name": "container_icon_overrides_environment_id_environments_id_fk", + "tableFrom": "container_icon_overrides", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "container_icon_overrides_container_name_environment_id_unique": { + "name": "container_icon_overrides_container_name_environment_id_unique", + "nullsNotDistinct": false, + "columns": [ + "container_name", + "environment_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.container_tags": { + "name": "container_tags", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "container_name": { + "name": "container_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "tag_id": { + "name": "tag_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "container_tags_environment_id_environments_id_fk": { + "name": "container_tags_environment_id_environments_id_fk", + "tableFrom": "container_tags", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "container_tags_tag_id_tags_id_fk": { + "name": "container_tags_tag_id_tags_id_fk", + "tableFrom": "container_tags", + "tableTo": "tags", + "columnsFrom": [ + "tag_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "container_tags_container_name_environment_id_tag_id_unique": { + "name": "container_tags_container_name_environment_id_tag_id_unique", + "nullsNotDistinct": false, + "columns": [ + "container_name", + "environment_id", + "tag_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.environment_notifications": { + "name": "environment_notifications", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "notification_id": { + "name": "notification_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": true + }, + "event_types": { + "name": "event_types", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "environment_notifications_environment_id_environments_id_fk": { + "name": "environment_notifications_environment_id_environments_id_fk", + "tableFrom": "environment_notifications", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "environment_notifications_notification_id_notification_settings_id_fk": { + "name": "environment_notifications_notification_id_notification_settings_id_fk", + "tableFrom": "environment_notifications", + "tableTo": "notification_settings", + "columnsFrom": [ + "notification_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "environment_notifications_environment_id_notification_id_unique": { + "name": "environment_notifications_environment_id_notification_id_unique", + "nullsNotDistinct": false, + "columns": [ + "environment_id", + "notification_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.environments": { + "name": "environments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "port": { + "name": "port", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 2375 + }, + "protocol": { + "name": "protocol", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'http'" + }, + "tls_ca": { + "name": "tls_ca", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tls_cert": { + "name": "tls_cert", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tls_key": { + "name": "tls_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tls_skip_verify": { + "name": "tls_skip_verify", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'globe'" + }, + "collect_activity": { + "name": "collect_activity", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": true + }, + "collect_metrics": { + "name": "collect_metrics", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": true + }, + "highlight_changes": { + "name": "highlight_changes", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": true + }, + "labels": { + "name": "labels", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "connection_type": { + "name": "connection_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'socket'" + }, + "socket_path": { + "name": "socket_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'/var/run/docker.sock'" + }, + "hawser_token": { + "name": "hawser_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "hawser_last_seen": { + "name": "hawser_last_seen", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "hawser_agent_id": { + "name": "hawser_agent_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "hawser_agent_name": { + "name": "hawser_agent_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "hawser_version": { + "name": "hawser_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "hawser_capabilities": { + "name": "hawser_capabilities", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "environments_name_unique": { + "name": "environments_name_unique", + "nullsNotDistinct": false, + "columns": [ + "name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.git_credentials": { + "name": "git_credentials", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "auth_type": { + "name": "auth_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'none'" + }, + "username": { + "name": "username", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ssh_private_key": { + "name": "ssh_private_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ssh_passphrase": { + "name": "ssh_passphrase", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "git_credentials_name_unique": { + "name": "git_credentials_name_unique", + "nullsNotDistinct": false, + "columns": [ + "name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.git_repositories": { + "name": "git_repositories", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'main'" + }, + "credential_id": { + "name": "credential_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "compose_path": { + "name": "compose_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'docker-compose.yml'" + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "auto_update": { + "name": "auto_update", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "auto_update_schedule": { + "name": "auto_update_schedule", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'daily'" + }, + "auto_update_cron": { + "name": "auto_update_cron", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'0 3 * * *'" + }, + "webhook_enabled": { + "name": "webhook_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "webhook_secret": { + "name": "webhook_secret", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_sync": { + "name": "last_sync", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_commit": { + "name": "last_commit", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sync_status": { + "name": "sync_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'pending'" + }, + "sync_error": { + "name": "sync_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "git_repositories_credential_id_git_credentials_id_fk": { + "name": "git_repositories_credential_id_git_credentials_id_fk", + "tableFrom": "git_repositories", + "tableTo": "git_credentials", + "columnsFrom": [ + "credential_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "git_repositories_name_unique": { + "name": "git_repositories_name_unique", + "nullsNotDistinct": false, + "columns": [ + "name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.git_stacks": { + "name": "git_stacks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "stack_name": { + "name": "stack_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "repository_id": { + "name": "repository_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "compose_path": { + "name": "compose_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'docker-compose.yml'" + }, + "env_file_path": { + "name": "env_file_path", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "auto_update": { + "name": "auto_update", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "auto_update_schedule": { + "name": "auto_update_schedule", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'daily'" + }, + "auto_update_cron": { + "name": "auto_update_cron", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'0 3 * * *'" + }, + "webhook_enabled": { + "name": "webhook_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "webhook_secret": { + "name": "webhook_secret", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "context_dir": { + "name": "context_dir", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "build_on_deploy": { + "name": "build_on_deploy", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "no_build_cache": { + "name": "no_build_cache", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "repull_images": { + "name": "repull_images", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "force_redeploy": { + "name": "force_redeploy", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "last_sync": { + "name": "last_sync", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "last_commit": { + "name": "last_commit", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sync_status": { + "name": "sync_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'pending'" + }, + "sync_error": { + "name": "sync_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "synced_files": { + "name": "synced_files", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "git_stacks_environment_id_environments_id_fk": { + "name": "git_stacks_environment_id_environments_id_fk", + "tableFrom": "git_stacks", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "git_stacks_repository_id_git_repositories_id_fk": { + "name": "git_stacks_repository_id_git_repositories_id_fk", + "tableFrom": "git_stacks", + "tableTo": "git_repositories", + "columnsFrom": [ + "repository_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "git_stacks_stack_name_environment_id_unique": { + "name": "git_stacks_stack_name_environment_id_unique", + "nullsNotDistinct": false, + "columns": [ + "stack_name", + "environment_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.hawser_tokens": { + "name": "hawser_tokens", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_prefix": { + "name": "token_prefix", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": true + }, + "last_used": { + "name": "last_used", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "hawser_tokens_environment_id_environments_id_fk": { + "name": "hawser_tokens_environment_id_environments_id_fk", + "tableFrom": "hawser_tokens", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "hawser_tokens_token_unique": { + "name": "hawser_tokens_token_unique", + "nullsNotDistinct": false, + "columns": [ + "token" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.host_metrics": { + "name": "host_metrics", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "cpu_percent": { + "name": "cpu_percent", + "type": "double precision", + "primaryKey": false, + "notNull": true + }, + "memory_percent": { + "name": "memory_percent", + "type": "double precision", + "primaryKey": false, + "notNull": true + }, + "memory_used": { + "name": "memory_used", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "memory_total": { + "name": "memory_total", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "timestamp": { + "name": "timestamp", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": { + "host_metrics_env_timestamp_idx": { + "name": "host_metrics_env_timestamp_idx", + "columns": [ + { + "expression": "environment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "timestamp", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "host_metrics_environment_id_environments_id_fk": { + "name": "host_metrics_environment_id_environments_id_fk", + "tableFrom": "host_metrics", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.ldap_config": { + "name": "ldap_config", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "server_url": { + "name": "server_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bind_dn": { + "name": "bind_dn", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "bind_password": { + "name": "bind_password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "base_dn": { + "name": "base_dn", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_filter": { + "name": "user_filter", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'(uid={{username}})'" + }, + "username_attribute": { + "name": "username_attribute", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'uid'" + }, + "email_attribute": { + "name": "email_attribute", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'mail'" + }, + "display_name_attribute": { + "name": "display_name_attribute", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'cn'" + }, + "group_base_dn": { + "name": "group_base_dn", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "group_filter": { + "name": "group_filter", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "admin_group": { + "name": "admin_group", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "role_mappings": { + "name": "role_mappings", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tls_enabled": { + "name": "tls_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "tls_ca": { + "name": "tls_ca", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.notification_settings": { + "name": "notification_settings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": true + }, + "config": { + "name": "config", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "event_types": { + "name": "event_types", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oidc_config": { + "name": "oidc_config", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "issuer_url": { + "name": "issuer_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_secret": { + "name": "client_secret", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scopes": { + "name": "scopes", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'openid profile email'" + }, + "username_claim": { + "name": "username_claim", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'preferred_username'" + }, + "email_claim": { + "name": "email_claim", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'email'" + }, + "display_name_claim": { + "name": "display_name_claim", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'name'" + }, + "admin_claim": { + "name": "admin_claim", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "admin_value": { + "name": "admin_value", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "role_mappings_claim": { + "name": "role_mappings_claim", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'groups'" + }, + "role_mappings": { + "name": "role_mappings", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.pending_container_updates": { + "name": "pending_container_updates", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "container_id": { + "name": "container_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "container_name": { + "name": "container_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "current_image": { + "name": "current_image", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "has_image_update": { + "name": "has_image_update", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "newer_version": { + "name": "newer_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "checked_at": { + "name": "checked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "pending_container_updates_environment_id_environments_id_fk": { + "name": "pending_container_updates_environment_id_environments_id_fk", + "tableFrom": "pending_container_updates", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "pending_container_updates_environment_id_container_id_unique": { + "name": "pending_container_updates_environment_id_container_id_unique", + "nullsNotDistinct": false, + "columns": [ + "environment_id", + "container_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.registries": { + "name": "registries", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "username": { + "name": "username", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_default": { + "name": "is_default", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "registries_name_unique": { + "name": "registries_name_unique", + "nullsNotDistinct": false, + "columns": [ + "name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.roles": { + "name": "roles", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_system": { + "name": "is_system", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "permissions": { + "name": "permissions", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "environment_ids": { + "name": "environment_ids", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "roles_name_unique": { + "name": "roles_name_unique", + "nullsNotDistinct": false, + "columns": [ + "name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.schedule_executions": { + "name": "schedule_executions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "schedule_type": { + "name": "schedule_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "schedule_id": { + "name": "schedule_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "entity_name": { + "name": "entity_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "triggered_by": { + "name": "triggered_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "triggered_at": { + "name": "triggered_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "duration": { + "name": "duration", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "details": { + "name": "details", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "logs": { + "name": "logs", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": { + "schedule_executions_type_id_idx": { + "name": "schedule_executions_type_id_idx", + "columns": [ + { + "expression": "schedule_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "schedule_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "schedule_executions_entity_env_idx": { + "name": "schedule_executions_entity_env_idx", + "columns": [ + { + "expression": "entity_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "environment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "schedule_executions_environment_id_environments_id_fk": { + "name": "schedule_executions_environment_id_environments_id_fk", + "tableFrom": "schedule_executions", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.secret_providers": { + "name": "secret_providers", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "config": { + "name": "config", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "secret_providers_name_unique": { + "name": "secret_providers_name_unique", + "nullsNotDistinct": false, + "columns": [ + "name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sessions": { + "name": "sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": { + "sessions_user_id_idx": { + "name": "sessions_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sessions_expires_at_idx": { + "name": "sessions_expires_at_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "sessions_user_id_users_id_fk": { + "name": "sessions_user_id_users_id_fk", + "tableFrom": "sessions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.settings": { + "name": "settings", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.stack_environment_variables": { + "name": "stack_environment_variables", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "stack_name": { + "name": "stack_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "is_secret": { + "name": "is_secret", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "stack_environment_variables_environment_id_environments_id_fk": { + "name": "stack_environment_variables_environment_id_environments_id_fk", + "tableFrom": "stack_environment_variables", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "stack_environment_variables_stack_name_environment_id_key_unique": { + "name": "stack_environment_variables_stack_name_environment_id_key_unique", + "nullsNotDistinct": false, + "columns": [ + "stack_name", + "environment_id", + "key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.stack_events": { + "name": "stack_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "stack_name": { + "name": "stack_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "timestamp": { + "name": "timestamp", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "metadata": { + "name": "metadata", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "stack_events_environment_id_environments_id_fk": { + "name": "stack_events_environment_id_environments_id_fk", + "tableFrom": "stack_events", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.stack_sources": { + "name": "stack_sources", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "stack_name": { + "name": "stack_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "source_type": { + "name": "source_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'internal'" + }, + "git_repository_id": { + "name": "git_repository_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "git_stack_id": { + "name": "git_stack_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "compose_path": { + "name": "compose_path", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "env_path": { + "name": "env_path", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "secret_provider_id": { + "name": "secret_provider_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "injected_secret_keys": { + "name": "injected_secret_keys", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "stack_sources_environment_id_environments_id_fk": { + "name": "stack_sources_environment_id_environments_id_fk", + "tableFrom": "stack_sources", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "stack_sources_git_repository_id_git_repositories_id_fk": { + "name": "stack_sources_git_repository_id_git_repositories_id_fk", + "tableFrom": "stack_sources", + "tableTo": "git_repositories", + "columnsFrom": [ + "git_repository_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "stack_sources_git_stack_id_git_stacks_id_fk": { + "name": "stack_sources_git_stack_id_git_stacks_id_fk", + "tableFrom": "stack_sources", + "tableTo": "git_stacks", + "columnsFrom": [ + "git_stack_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "stack_sources_secret_provider_id_secret_providers_id_fk": { + "name": "stack_sources_secret_provider_id_secret_providers_id_fk", + "tableFrom": "stack_sources", + "tableTo": "secret_providers", + "columnsFrom": [ + "secret_provider_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "stack_sources_stack_name_environment_id_unique": { + "name": "stack_sources_stack_name_environment_id_unique", + "nullsNotDistinct": false, + "columns": [ + "stack_name", + "environment_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.stack_tags": { + "name": "stack_tags", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "stack_name": { + "name": "stack_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "tag_id": { + "name": "tag_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "stack_tags_environment_id_environments_id_fk": { + "name": "stack_tags_environment_id_environments_id_fk", + "tableFrom": "stack_tags", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "stack_tags_tag_id_tags_id_fk": { + "name": "stack_tags_tag_id_tags_id_fk", + "tableFrom": "stack_tags", + "tableTo": "tags", + "columnsFrom": [ + "tag_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "stack_tags_stack_name_environment_id_tag_id_unique": { + "name": "stack_tags_stack_name_environment_id_tag_id_unique", + "nullsNotDistinct": false, + "columns": [ + "stack_name", + "environment_id", + "tag_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tags": { + "name": "tags", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'slate'" + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "tags_name_unique": { + "name": "tags_name_unique", + "nullsNotDistinct": false, + "columns": [ + "name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.template_sources": { + "name": "template_sources", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "source_id": { + "name": "source_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": true + }, + "builtin": { + "name": "builtin", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "template_sources_source_id_unique": { + "name": "template_sources_source_id_unique", + "nullsNotDistinct": false, + "columns": [ + "source_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_preferences": { + "name": "user_preferences", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "user_preferences_user_id_users_id_fk": { + "name": "user_preferences_user_id_users_id_fk", + "tableFrom": "user_preferences", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_preferences_environment_id_environments_id_fk": { + "name": "user_preferences_environment_id_environments_id_fk", + "tableFrom": "user_preferences", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "user_preferences_user_id_environment_id_key_unique": { + "name": "user_preferences_user_id_environment_id_key_unique", + "nullsNotDistinct": false, + "columns": [ + "user_id", + "environment_id", + "key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_roles": { + "name": "user_roles", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "user_roles_user_id_users_id_fk": { + "name": "user_roles_user_id_users_id_fk", + "tableFrom": "user_roles", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_roles_role_id_roles_id_fk": { + "name": "user_roles_role_id_roles_id_fk", + "tableFrom": "user_roles", + "tableTo": "roles", + "columnsFrom": [ + "role_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_roles_environment_id_environments_id_fk": { + "name": "user_roles_environment_id_environments_id_fk", + "tableFrom": "user_roles", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "user_roles_user_id_role_id_environment_id_unique": { + "name": "user_roles_user_id_role_id_environment_id_unique", + "nullsNotDistinct": false, + "columns": [ + "user_id", + "role_id", + "environment_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "username": { + "name": "username", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "avatar": { + "name": "avatar", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "auth_provider": { + "name": "auth_provider", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'local'" + }, + "mfa_enabled": { + "name": "mfa_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "mfa_secret": { + "name": "mfa_secret", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": true + }, + "last_login": { + "name": "last_login", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_username_unique": { + "name": "users_username_unique", + "nullsNotDistinct": false, + "columns": [ + "username" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.vulnerability_scans": { + "name": "vulnerability_scans", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "image_id": { + "name": "image_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "image_name": { + "name": "image_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scanner": { + "name": "scanner", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scanned_at": { + "name": "scanned_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "scan_duration": { + "name": "scan_duration", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "critical_count": { + "name": "critical_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "high_count": { + "name": "high_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "medium_count": { + "name": "medium_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "low_count": { + "name": "low_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "negligible_count": { + "name": "negligible_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "unknown_count": { + "name": "unknown_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "vulnerabilities": { + "name": "vulnerabilities", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": { + "vulnerability_scans_env_image_idx": { + "name": "vulnerability_scans_env_image_idx", + "columns": [ + { + "expression": "environment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "image_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "vulnerability_scans_environment_id_environments_id_fk": { + "name": "vulnerability_scans_environment_id_environments_id_fk", + "tableFrom": "vulnerability_scans", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle-pg/meta/_journal.json b/drizzle-pg/meta/_journal.json index 15869d271..535ead793 100644 --- a/drizzle-pg/meta/_journal.json +++ b/drizzle-pg/meta/_journal.json @@ -113,6 +113,13 @@ "when": 1788099526949, "tag": "0015_deploy_run_index", "breakpoints": true + }, + { + "idx": 16, + "version": "7", + "when": 1789748940854, + "tag": "0016_add_tags", + "breakpoints": true } ] } \ No newline at end of file diff --git a/drizzle/0016_add_tags.sql b/drizzle/0016_add_tags.sql new file mode 100644 index 000000000..6342bacfd --- /dev/null +++ b/drizzle/0016_add_tags.sql @@ -0,0 +1,31 @@ +CREATE TABLE `container_tags` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `container_name` text NOT NULL, + `environment_id` integer, + `tag_id` integer NOT NULL, + `created_at` text DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (`environment_id`) REFERENCES `environments`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`tag_id`) REFERENCES `tags`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE UNIQUE INDEX `container_tags_container_name_environment_id_tag_id_unique` ON `container_tags` (`container_name`,`environment_id`,`tag_id`);--> statement-breakpoint +CREATE TABLE `stack_tags` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `stack_name` text NOT NULL, + `environment_id` integer, + `tag_id` integer NOT NULL, + `created_at` text DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (`environment_id`) REFERENCES `environments`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`tag_id`) REFERENCES `tags`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE UNIQUE INDEX `stack_tags_stack_name_environment_id_tag_id_unique` ON `stack_tags` (`stack_name`,`environment_id`,`tag_id`);--> statement-breakpoint +CREATE TABLE `tags` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `name` text NOT NULL, + `color` text DEFAULT 'slate' NOT NULL, + `icon` text, + `created_at` text DEFAULT CURRENT_TIMESTAMP +); +--> statement-breakpoint +CREATE UNIQUE INDEX `tags_name_unique` ON `tags` (`name` COLLATE NOCASE); \ No newline at end of file diff --git a/drizzle/meta/0016_snapshot.json b/drizzle/meta/0016_snapshot.json new file mode 100644 index 000000000..663ddf414 --- /dev/null +++ b/drizzle/meta/0016_snapshot.json @@ -0,0 +1,3976 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "730cf06b-a48f-46c9-8c0e-41a1433264fb", + "prevId": "015e998b-f154-417d-9122-eef38fca253c", + "tables": { + "api_tokens": { + "name": "api_tokens", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token_prefix": { + "name": "token_prefix", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_used": { + "name": "last_used", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "api_tokens_token_hash_unique": { + "name": "api_tokens_token_hash_unique", + "columns": [ + "token_hash" + ], + "isUnique": true + }, + "api_tokens_user_id_idx": { + "name": "api_tokens_user_id_idx", + "columns": [ + "user_id" + ], + "isUnique": false + }, + "api_tokens_token_prefix_idx": { + "name": "api_tokens_token_prefix_idx", + "columns": [ + "token_prefix" + ], + "isUnique": false + } + }, + "foreignKeys": { + "api_tokens_user_id_users_id_fk": { + "name": "api_tokens_user_id_users_id_fk", + "tableFrom": "api_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "audit_logs": { + "name": "audit_logs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "username": { + "name": "username", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "entity_name": { + "name": "entity_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "details": { + "name": "details", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "audit_logs_user_id_idx": { + "name": "audit_logs_user_id_idx", + "columns": [ + "user_id" + ], + "isUnique": false + }, + "audit_logs_created_at_idx": { + "name": "audit_logs_created_at_idx", + "columns": [ + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "audit_logs_user_id_users_id_fk": { + "name": "audit_logs_user_id_users_id_fk", + "tableFrom": "audit_logs", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "audit_logs_environment_id_environments_id_fk": { + "name": "audit_logs_environment_id_environments_id_fk", + "tableFrom": "audit_logs", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "auth_settings": { + "name": "auth_settings", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "auth_enabled": { + "name": "auth_enabled", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "default_provider": { + "name": "default_provider", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'local'" + }, + "session_timeout": { + "name": "session_timeout", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": 86400 + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "auto_update_settings": { + "name": "auto_update_settings", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "container_name": { + "name": "container_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "schedule_type": { + "name": "schedule_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'daily'" + }, + "cron_expression": { + "name": "cron_expression", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "vulnerability_criteria": { + "name": "vulnerability_criteria", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'never'" + }, + "last_checked": { + "name": "last_checked", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_updated": { + "name": "last_updated", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "auto_update_settings_environment_id_container_name_unique": { + "name": "auto_update_settings_environment_id_container_name_unique", + "columns": [ + "environment_id", + "container_name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "auto_update_settings_environment_id_environments_id_fk": { + "name": "auto_update_settings_environment_id_environments_id_fk", + "tableFrom": "auto_update_settings", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "backup_configs": { + "name": "backup_configs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'container'" + }, + "target_name": { + "name": "target_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "destination_id": { + "name": "destination_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": true + }, + "all_volumes": { + "name": "all_volumes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": true + }, + "selected_volumes": { + "name": "selected_volumes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stop_before_backup": { + "name": "stop_before_backup", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "schedule": { + "name": "schedule", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "retention": { + "name": "retention", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "options": { + "name": "options", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tags": { + "name": "tags", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_backup_at": { + "name": "last_backup_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_backup_status": { + "name": "last_backup_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": {}, + "foreignKeys": { + "backup_configs_environment_id_environments_id_fk": { + "name": "backup_configs_environment_id_environments_id_fk", + "tableFrom": "backup_configs", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "backup_configs_destination_id_backup_destinations_id_fk": { + "name": "backup_configs_destination_id_backup_destinations_id_fk", + "tableFrom": "backup_configs", + "tableTo": "backup_destinations", + "columnsFrom": [ + "destination_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "backup_destinations": { + "name": "backup_destinations", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "repository": { + "name": "repository", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "env_vars": { + "name": "env_vars", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "flags": { + "name": "flags", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host_path": { + "name": "host_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cacert": { + "name": "cacert", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tls_client_cert": { + "name": "tls_client_cert", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "policies": { + "name": "policies", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_test_at": { + "name": "last_test_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_test_status": { + "name": "last_test_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_test_error": { + "name": "last_test_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "backup_destinations_name_unique": { + "name": "backup_destinations_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "config_sets": { + "name": "config_sets", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "env_vars": { + "name": "env_vars", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "labels": { + "name": "labels", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ports": { + "name": "ports", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "volumes": { + "name": "volumes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "network_mode": { + "name": "network_mode", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'bridge'" + }, + "restart_policy": { + "name": "restart_policy", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'no'" + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "config_sets_name_unique": { + "name": "config_sets_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "container_events": { + "name": "container_events", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "container_id": { + "name": "container_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "container_name": { + "name": "container_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "actor_attributes": { + "name": "actor_attributes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "timestamp": { + "name": "timestamp", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "container_events_env_timestamp_idx": { + "name": "container_events_env_timestamp_idx", + "columns": [ + "environment_id", + "timestamp" + ], + "isUnique": false + } + }, + "foreignKeys": { + "container_events_environment_id_environments_id_fk": { + "name": "container_events_environment_id_environments_id_fk", + "tableFrom": "container_events", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "container_icon_overrides": { + "name": "container_icon_overrides", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "container_name": { + "name": "container_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "container_icon_overrides_container_name_environment_id_unique": { + "name": "container_icon_overrides_container_name_environment_id_unique", + "columns": [ + "container_name", + "environment_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "container_icon_overrides_environment_id_environments_id_fk": { + "name": "container_icon_overrides_environment_id_environments_id_fk", + "tableFrom": "container_icon_overrides", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "container_tags": { + "name": "container_tags", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "container_name": { + "name": "container_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tag_id": { + "name": "tag_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "container_tags_container_name_environment_id_tag_id_unique": { + "name": "container_tags_container_name_environment_id_tag_id_unique", + "columns": [ + "container_name", + "environment_id", + "tag_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "container_tags_environment_id_environments_id_fk": { + "name": "container_tags_environment_id_environments_id_fk", + "tableFrom": "container_tags", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "container_tags_tag_id_tags_id_fk": { + "name": "container_tags_tag_id_tags_id_fk", + "tableFrom": "container_tags", + "tableTo": "tags", + "columnsFrom": [ + "tag_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "environment_notifications": { + "name": "environment_notifications", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "notification_id": { + "name": "notification_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": true + }, + "event_types": { + "name": "event_types", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "environment_notifications_environment_id_notification_id_unique": { + "name": "environment_notifications_environment_id_notification_id_unique", + "columns": [ + "environment_id", + "notification_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "environment_notifications_environment_id_environments_id_fk": { + "name": "environment_notifications_environment_id_environments_id_fk", + "tableFrom": "environment_notifications", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "environment_notifications_notification_id_notification_settings_id_fk": { + "name": "environment_notifications_notification_id_notification_settings_id_fk", + "tableFrom": "environment_notifications", + "tableTo": "notification_settings", + "columnsFrom": [ + "notification_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "environments": { + "name": "environments", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "port": { + "name": "port", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": 2375 + }, + "protocol": { + "name": "protocol", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'http'" + }, + "tls_ca": { + "name": "tls_ca", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tls_cert": { + "name": "tls_cert", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tls_key": { + "name": "tls_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tls_skip_verify": { + "name": "tls_skip_verify", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'globe'" + }, + "collect_activity": { + "name": "collect_activity", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": true + }, + "collect_metrics": { + "name": "collect_metrics", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": true + }, + "highlight_changes": { + "name": "highlight_changes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": true + }, + "labels": { + "name": "labels", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "connection_type": { + "name": "connection_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'socket'" + }, + "socket_path": { + "name": "socket_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'/var/run/docker.sock'" + }, + "hawser_token": { + "name": "hawser_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hawser_last_seen": { + "name": "hawser_last_seen", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hawser_agent_id": { + "name": "hawser_agent_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hawser_agent_name": { + "name": "hawser_agent_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hawser_version": { + "name": "hawser_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hawser_capabilities": { + "name": "hawser_capabilities", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "environments_name_unique": { + "name": "environments_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "git_credentials": { + "name": "git_credentials", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth_type": { + "name": "auth_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'none'" + }, + "username": { + "name": "username", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ssh_private_key": { + "name": "ssh_private_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ssh_passphrase": { + "name": "ssh_passphrase", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "git_credentials_name_unique": { + "name": "git_credentials_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "git_repositories": { + "name": "git_repositories", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'main'" + }, + "credential_id": { + "name": "credential_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "compose_path": { + "name": "compose_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'docker-compose.yml'" + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "auto_update": { + "name": "auto_update", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "auto_update_schedule": { + "name": "auto_update_schedule", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'daily'" + }, + "auto_update_cron": { + "name": "auto_update_cron", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'0 3 * * *'" + }, + "webhook_enabled": { + "name": "webhook_enabled", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "webhook_secret": { + "name": "webhook_secret", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_sync": { + "name": "last_sync", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_commit": { + "name": "last_commit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sync_status": { + "name": "sync_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'pending'" + }, + "sync_error": { + "name": "sync_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "git_repositories_name_unique": { + "name": "git_repositories_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "git_repositories_credential_id_git_credentials_id_fk": { + "name": "git_repositories_credential_id_git_credentials_id_fk", + "tableFrom": "git_repositories", + "tableTo": "git_credentials", + "columnsFrom": [ + "credential_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "git_stacks": { + "name": "git_stacks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "stack_name": { + "name": "stack_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "repository_id": { + "name": "repository_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "compose_path": { + "name": "compose_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'docker-compose.yml'" + }, + "env_file_path": { + "name": "env_file_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "auto_update": { + "name": "auto_update", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "auto_update_schedule": { + "name": "auto_update_schedule", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'daily'" + }, + "auto_update_cron": { + "name": "auto_update_cron", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'0 3 * * *'" + }, + "webhook_enabled": { + "name": "webhook_enabled", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "webhook_secret": { + "name": "webhook_secret", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "context_dir": { + "name": "context_dir", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "build_on_deploy": { + "name": "build_on_deploy", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "no_build_cache": { + "name": "no_build_cache", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "repull_images": { + "name": "repull_images", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "force_redeploy": { + "name": "force_redeploy", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "last_sync": { + "name": "last_sync", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_commit": { + "name": "last_commit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sync_status": { + "name": "sync_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'pending'" + }, + "sync_error": { + "name": "sync_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "synced_files": { + "name": "synced_files", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "git_stacks_stack_name_environment_id_unique": { + "name": "git_stacks_stack_name_environment_id_unique", + "columns": [ + "stack_name", + "environment_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "git_stacks_environment_id_environments_id_fk": { + "name": "git_stacks_environment_id_environments_id_fk", + "tableFrom": "git_stacks", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "git_stacks_repository_id_git_repositories_id_fk": { + "name": "git_stacks_repository_id_git_repositories_id_fk", + "tableFrom": "git_stacks", + "tableTo": "git_repositories", + "columnsFrom": [ + "repository_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "hawser_tokens": { + "name": "hawser_tokens", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token_prefix": { + "name": "token_prefix", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "is_active": { + "name": "is_active", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": true + }, + "last_used": { + "name": "last_used", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "expires_at": { + "name": "expires_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "hawser_tokens_token_unique": { + "name": "hawser_tokens_token_unique", + "columns": [ + "token" + ], + "isUnique": true + } + }, + "foreignKeys": { + "hawser_tokens_environment_id_environments_id_fk": { + "name": "hawser_tokens_environment_id_environments_id_fk", + "tableFrom": "hawser_tokens", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "host_metrics": { + "name": "host_metrics", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cpu_percent": { + "name": "cpu_percent", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "memory_percent": { + "name": "memory_percent", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "memory_used": { + "name": "memory_used", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "memory_total": { + "name": "memory_total", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "timestamp": { + "name": "timestamp", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "host_metrics_env_timestamp_idx": { + "name": "host_metrics_env_timestamp_idx", + "columns": [ + "environment_id", + "timestamp" + ], + "isUnique": false + } + }, + "foreignKeys": { + "host_metrics_environment_id_environments_id_fk": { + "name": "host_metrics_environment_id_environments_id_fk", + "tableFrom": "host_metrics", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "ldap_config": { + "name": "ldap_config", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "server_url": { + "name": "server_url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bind_dn": { + "name": "bind_dn", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "bind_password": { + "name": "bind_password", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "base_dn": { + "name": "base_dn", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_filter": { + "name": "user_filter", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'(uid={{username}})'" + }, + "username_attribute": { + "name": "username_attribute", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'uid'" + }, + "email_attribute": { + "name": "email_attribute", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'mail'" + }, + "display_name_attribute": { + "name": "display_name_attribute", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'cn'" + }, + "group_base_dn": { + "name": "group_base_dn", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "group_filter": { + "name": "group_filter", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "admin_group": { + "name": "admin_group", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "role_mappings": { + "name": "role_mappings", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tls_enabled": { + "name": "tls_enabled", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "tls_ca": { + "name": "tls_ca", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "notification_settings": { + "name": "notification_settings", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": true + }, + "config": { + "name": "config", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "event_types": { + "name": "event_types", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oidc_config": { + "name": "oidc_config", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "issuer_url": { + "name": "issuer_url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_secret": { + "name": "client_secret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scopes": { + "name": "scopes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'openid profile email'" + }, + "username_claim": { + "name": "username_claim", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'preferred_username'" + }, + "email_claim": { + "name": "email_claim", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'email'" + }, + "display_name_claim": { + "name": "display_name_claim", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'name'" + }, + "admin_claim": { + "name": "admin_claim", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "admin_value": { + "name": "admin_value", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "role_mappings_claim": { + "name": "role_mappings_claim", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'groups'" + }, + "role_mappings": { + "name": "role_mappings", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "pending_container_updates": { + "name": "pending_container_updates", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "container_id": { + "name": "container_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "container_name": { + "name": "container_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "current_image": { + "name": "current_image", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "has_image_update": { + "name": "has_image_update", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "newer_version": { + "name": "newer_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checked_at": { + "name": "checked_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "pending_container_updates_environment_id_container_id_unique": { + "name": "pending_container_updates_environment_id_container_id_unique", + "columns": [ + "environment_id", + "container_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "pending_container_updates_environment_id_environments_id_fk": { + "name": "pending_container_updates_environment_id_environments_id_fk", + "tableFrom": "pending_container_updates", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "registries": { + "name": "registries", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "username": { + "name": "username", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "is_default": { + "name": "is_default", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "registries_name_unique": { + "name": "registries_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "roles": { + "name": "roles", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "is_system": { + "name": "is_system", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "permissions": { + "name": "permissions", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "environment_ids": { + "name": "environment_ids", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "roles_name_unique": { + "name": "roles_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "schedule_executions": { + "name": "schedule_executions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "schedule_type": { + "name": "schedule_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "schedule_id": { + "name": "schedule_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "entity_name": { + "name": "entity_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "triggered_by": { + "name": "triggered_by", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "triggered_at": { + "name": "triggered_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "completed_at": { + "name": "completed_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "duration": { + "name": "duration", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "details": { + "name": "details", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "logs": { + "name": "logs", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "schedule_executions_type_id_idx": { + "name": "schedule_executions_type_id_idx", + "columns": [ + "schedule_type", + "schedule_id" + ], + "isUnique": false + }, + "schedule_executions_entity_env_idx": { + "name": "schedule_executions_entity_env_idx", + "columns": [ + "entity_name", + "environment_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "schedule_executions_environment_id_environments_id_fk": { + "name": "schedule_executions_environment_id_environments_id_fk", + "tableFrom": "schedule_executions", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "secret_providers": { + "name": "secret_providers", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "config": { + "name": "config", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "secret_providers_name_unique": { + "name": "secret_providers_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sessions": { + "name": "sessions", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "sessions_user_id_idx": { + "name": "sessions_user_id_idx", + "columns": [ + "user_id" + ], + "isUnique": false + }, + "sessions_expires_at_idx": { + "name": "sessions_expires_at_idx", + "columns": [ + "expires_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "sessions_user_id_users_id_fk": { + "name": "sessions_user_id_users_id_fk", + "tableFrom": "sessions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "stack_environment_variables": { + "name": "stack_environment_variables", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "stack_name": { + "name": "stack_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "is_secret": { + "name": "is_secret", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "stack_environment_variables_stack_name_environment_id_key_unique": { + "name": "stack_environment_variables_stack_name_environment_id_key_unique", + "columns": [ + "stack_name", + "environment_id", + "key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "stack_environment_variables_environment_id_environments_id_fk": { + "name": "stack_environment_variables_environment_id_environments_id_fk", + "tableFrom": "stack_environment_variables", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "stack_events": { + "name": "stack_events", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stack_name": { + "name": "stack_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "timestamp": { + "name": "timestamp", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "metadata": { + "name": "metadata", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "stack_events_environment_id_environments_id_fk": { + "name": "stack_events_environment_id_environments_id_fk", + "tableFrom": "stack_events", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "stack_sources": { + "name": "stack_sources", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "stack_name": { + "name": "stack_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source_type": { + "name": "source_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'internal'" + }, + "git_repository_id": { + "name": "git_repository_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "git_stack_id": { + "name": "git_stack_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "compose_path": { + "name": "compose_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "env_path": { + "name": "env_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "secret_provider_id": { + "name": "secret_provider_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "injected_secret_keys": { + "name": "injected_secret_keys", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "stack_sources_stack_name_environment_id_unique": { + "name": "stack_sources_stack_name_environment_id_unique", + "columns": [ + "stack_name", + "environment_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "stack_sources_environment_id_environments_id_fk": { + "name": "stack_sources_environment_id_environments_id_fk", + "tableFrom": "stack_sources", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "stack_sources_git_repository_id_git_repositories_id_fk": { + "name": "stack_sources_git_repository_id_git_repositories_id_fk", + "tableFrom": "stack_sources", + "tableTo": "git_repositories", + "columnsFrom": [ + "git_repository_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "stack_sources_git_stack_id_git_stacks_id_fk": { + "name": "stack_sources_git_stack_id_git_stacks_id_fk", + "tableFrom": "stack_sources", + "tableTo": "git_stacks", + "columnsFrom": [ + "git_stack_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "stack_sources_secret_provider_id_secret_providers_id_fk": { + "name": "stack_sources_secret_provider_id_secret_providers_id_fk", + "tableFrom": "stack_sources", + "tableTo": "secret_providers", + "columnsFrom": [ + "secret_provider_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "stack_tags": { + "name": "stack_tags", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "stack_name": { + "name": "stack_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tag_id": { + "name": "tag_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "stack_tags_stack_name_environment_id_tag_id_unique": { + "name": "stack_tags_stack_name_environment_id_tag_id_unique", + "columns": [ + "stack_name", + "environment_id", + "tag_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "stack_tags_environment_id_environments_id_fk": { + "name": "stack_tags_environment_id_environments_id_fk", + "tableFrom": "stack_tags", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "stack_tags_tag_id_tags_id_fk": { + "name": "stack_tags_tag_id_tags_id_fk", + "tableFrom": "stack_tags", + "tableTo": "tags", + "columnsFrom": [ + "tag_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tags": { + "name": "tags", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'slate'" + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "tags_name_unique": { + "name": "tags_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "template_sources": { + "name": "template_sources", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "source_id": { + "name": "source_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": true + }, + "builtin": { + "name": "builtin", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "template_sources_source_id_unique": { + "name": "template_sources_source_id_unique", + "columns": [ + "source_id" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "user_preferences": { + "name": "user_preferences", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "user_preferences_user_id_environment_id_key_unique": { + "name": "user_preferences_user_id_environment_id_key_unique", + "columns": [ + "user_id", + "environment_id", + "key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "user_preferences_user_id_users_id_fk": { + "name": "user_preferences_user_id_users_id_fk", + "tableFrom": "user_preferences", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_preferences_environment_id_environments_id_fk": { + "name": "user_preferences_environment_id_environments_id_fk", + "tableFrom": "user_preferences", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "user_roles": { + "name": "user_roles", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role_id": { + "name": "role_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "user_roles_user_id_role_id_environment_id_unique": { + "name": "user_roles_user_id_role_id_environment_id_unique", + "columns": [ + "user_id", + "role_id", + "environment_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "user_roles_user_id_users_id_fk": { + "name": "user_roles_user_id_users_id_fk", + "tableFrom": "user_roles", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_roles_role_id_roles_id_fk": { + "name": "user_roles_role_id_roles_id_fk", + "tableFrom": "user_roles", + "tableTo": "roles", + "columnsFrom": [ + "role_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_roles_environment_id_environments_id_fk": { + "name": "user_roles_environment_id_environments_id_fk", + "tableFrom": "user_roles", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "username": { + "name": "username", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "avatar": { + "name": "avatar", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "auth_provider": { + "name": "auth_provider", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'local'" + }, + "mfa_enabled": { + "name": "mfa_enabled", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": false + }, + "mfa_secret": { + "name": "mfa_secret", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "is_active": { + "name": "is_active", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": true + }, + "last_login": { + "name": "last_login", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "users_username_unique": { + "name": "users_username_unique", + "columns": [ + "username" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "vulnerability_scans": { + "name": "vulnerability_scans", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "environment_id": { + "name": "environment_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image_id": { + "name": "image_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "image_name": { + "name": "image_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scanner": { + "name": "scanner", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scanned_at": { + "name": "scanned_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scan_duration": { + "name": "scan_duration", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "critical_count": { + "name": "critical_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": 0 + }, + "high_count": { + "name": "high_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": 0 + }, + "medium_count": { + "name": "medium_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": 0 + }, + "low_count": { + "name": "low_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": 0 + }, + "negligible_count": { + "name": "negligible_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": 0 + }, + "unknown_count": { + "name": "unknown_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": 0 + }, + "vulnerabilities": { + "name": "vulnerabilities", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "CURRENT_TIMESTAMP" + } + }, + "indexes": { + "vulnerability_scans_env_image_idx": { + "name": "vulnerability_scans_env_image_idx", + "columns": [ + "environment_id", + "image_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "vulnerability_scans_environment_id_environments_id_fk": { + "name": "vulnerability_scans_environment_id_environments_id_fk", + "tableFrom": "vulnerability_scans", + "tableTo": "environments", + "columnsFrom": [ + "environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 44367adb7..efb919e4c 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -113,6 +113,13 @@ "when": 1788099517358, "tag": "0015_deploy_run_index", "breakpoints": true + }, + { + "idx": 16, + "version": "6", + "when": 1789748940121, + "tag": "0016_add_tags", + "breakpoints": true } ] } \ No newline at end of file diff --git a/package.json b/package.json index a779d30b6..eb5d62b13 100644 --- a/package.json +++ b/package.json @@ -41,6 +41,7 @@ "@lezer/highlight": "1.2.3", "@lucide/lab": "0.1.2", "@replit/codemirror-indentation-markers": "6.5.3", + "@uiw/codemirror-themes-all": "4.25.11", "ansi_up": "6.0.6", "argon2": "0.41.1", "better-sqlite3": "11.7.0", diff --git a/src/lib/components/CodeEditor.svelte b/src/lib/components/CodeEditor.svelte index e7c2ee487..f4a68da44 100644 --- a/src/lib/components/CodeEditor.svelte +++ b/src/lib/components/CodeEditor.svelte @@ -11,6 +11,8 @@ import { oneDarkHighlightStyle } from '@codemirror/theme-one-dark'; import { indentationMarkers } from '@replit/codemirror-indentation-markers'; import { themeStore } from '$lib/stores/theme'; + import { getEditorThemeExtension } from '$lib/utils/editor-theme-extensions'; + import { gutterBackgroundFor } from '$lib/utils/gutter-contrast'; import { get } from 'svelte/store'; import { shell } from '@codemirror/legacy-modes/mode/shell'; import { dockerFile } from '@codemirror/legacy-modes/mode/dockerfile'; @@ -233,9 +235,11 @@ onLintClick?: (line: number) => void; /** 1-based inclusive line ranges highlighted as freshly-added (green), e.g. a merged-in service. */ addedLineMarkers?: { line: number; endLine: number }[]; + /** Force a specific editor color theme id, ignoring the user's stored preference (live preview). */ + editorThemeOverride?: string; } - let { value = '', language = 'yaml', readonly = false, theme = 'dark', onchange, class: className = '', variableMarkers: variableMarkersProp = [], lintMarkers: lintMarkersProp = [], onLintClick, addedLineMarkers: addedLineMarkersProp = [] }: Props = $props(); + let { value = '', language = 'yaml', readonly = false, theme = 'dark', onchange, class: className = '', variableMarkers: variableMarkersProp = [], lintMarkers: lintMarkersProp = [], onLintClick, addedLineMarkers: addedLineMarkersProp = [], editorThemeOverride }: Props = $props(); // Keep markers reactive - destructured props with defaults lose reactivity const variableMarkers = $derived(variableMarkersProp); @@ -759,9 +763,9 @@ padding: '8px 0' }, '.cm-gutters': { - backgroundColor: '#1a1a1a', + backgroundColor: '#212121', color: '#858585', - border: 'none', + borderRight: '1px solid #333333', fontFamily: 'var(--font-editor, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace)', fontSize: '13px' }, @@ -801,14 +805,14 @@ padding: '8px 0' }, '.cm-gutters': { - backgroundColor: '#fafafa', + backgroundColor: '#f1f1f1', color: '#a1a1aa', - border: 'none', + borderRight: '1px solid #e0e0e0', fontFamily: 'var(--font-editor, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace)', fontSize: '13px' }, '.cm-activeLineGutter': { - backgroundColor: '#f4f4f5' + backgroundColor: '#e8e8e8' }, '.cm-activeLine': { backgroundColor: '#f4f4f5' @@ -837,13 +841,51 @@ // Track last applied markers to avoid redundant updates let lastAppliedMarkersJson = ''; + // Give the gutter a background derived from the (rendered) code background so line + // numbers stay visibly separated on any @uiw theme (#1309). Reads the real applied + // colour, so it works without knowing the theme's palette. + function applyGutterContrast() { + if (!view) return; + const gutters = view.dom.querySelector('.cm-gutters') as HTMLElement | null; + if (!gutters) return; + // The theme background can sit on .cm-content, the editor root, or the scroller; + // take the first that resolves to a real rgb() (skip transparent). + let gutterBg: string | null = null; + for (const sel of ['.cm-content', '.cm-scroller', '.cm-editor']) { + const el = (sel === '.cm-editor' ? view.dom : view.dom.querySelector(sel)) as HTMLElement | null; + if (!el) continue; + gutterBg = gutterBackgroundFor(getComputedStyle(el).backgroundColor); + if (gutterBg) break; + } + if (gutterBg) gutters.style.backgroundColor = gutterBg; + } + function createEditor() { if (!container || view || initialized) return; initialized = true; - const themeExtensions = theme === 'dark' - ? [dockhandDark, syntaxHighlighting(oneDarkHighlightStyle)] - : [dockhandLight, syntaxHighlighting(defaultHighlightStyle)]; + // Editor color theme (#1309): 'default' keeps the built-in theme that follows + // the app's dark/light toggle; any other id applies a @uiw theme extension + // (self-contained - it brings its own background/gutter/syntax colors). + const editorThemeId = editorThemeOverride ?? get(themeStore).editorTheme; + const pickedExtension = getEditorThemeExtension(editorThemeId); + // @uiw themes don't set a font, and most give the gutter the same background as the + // code so line numbers blend in (#1309). Force the user's editor font and a firmer + // border here; the distinct gutter BACKGROUND is derived from the rendered code + // background after mount (applyGutterContrast) so it stays visible on any theme. + const editorThemeTweaks = EditorView.theme({ + '.cm-content, .cm-gutters': { + fontFamily: 'var(--font-editor, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace)' + }, + '.cm-gutters': { + borderRight: '1px solid rgba(128, 128, 128, 0.5)' + } + }); + const themeExtensions = pickedExtension + ? [pickedExtension, editorThemeTweaks] + : theme === 'dark' + ? [dockhandDark, syntaxHighlighting(oneDarkHighlightStyle)] + : [dockhandLight, syntaxHighlighting(defaultHighlightStyle)]; // Build autocompletion config - add Docker Compose completions for YAML // Note: activateOnTyping can interfere with key repeat, so we disable it @@ -942,6 +984,11 @@ dispatchTransactions }); + // Derive a visibly distinct gutter background from the theme's rendered code + // background (#1309). Only for @uiw themes; the built-in dockhand themes set their + // own gutter colour. Runs after mount so getComputedStyle sees the applied theme. + if (pickedExtension) applyGutterContrast(); + // Push initial variable markers if provided. Lint markers need no initial // dispatch: currentLintField/gutter are created from lintMarkers, and the reactive // $effect below fires once on mount - dispatching here too would double it. @@ -1074,17 +1121,23 @@ let prevLanguage = $state(language); let prevTheme = $state(theme); let prevIndentGuides = $state($themeStore.editorIndentGuides); + let prevEditorTheme = $state(editorThemeOverride ?? $themeStore.editorTheme); + let prevEditorFont = $state($themeStore.editorFont); - // Recreate editor if language, theme, or the indent-guides preference changes + // Recreate editor if language, theme, indent-guides, the color theme, or the editor font changes $effect(() => { const currentLanguage = language; const currentTheme = theme; const currentIndentGuides = $themeStore.editorIndentGuides; + const currentEditorTheme = editorThemeOverride ?? $themeStore.editorTheme; + const currentEditorFont = $themeStore.editorFont; - if (view && (currentLanguage !== prevLanguage || currentTheme !== prevTheme || currentIndentGuides !== prevIndentGuides)) { + if (view && (currentLanguage !== prevLanguage || currentTheme !== prevTheme || currentIndentGuides !== prevIndentGuides || currentEditorTheme !== prevEditorTheme || currentEditorFont !== prevEditorFont)) { prevLanguage = currentLanguage; prevTheme = currentTheme; prevIndentGuides = currentIndentGuides; + prevEditorTheme = currentEditorTheme; + prevEditorFont = currentEditorFont; const currentContent = view.state.doc.toString(); destroyEditor(); value = currentContent; // Preserve content diff --git a/src/lib/components/CommandPalette.svelte b/src/lib/components/CommandPalette.svelte index 58a51f941..4e422af77 100644 --- a/src/lib/components/CommandPalette.svelte +++ b/src/lib/components/CommandPalette.svelte @@ -1,7 +1,7 @@ - - - - No results found. - - {#each filteredItems as item (item.href)} - handleSelect(item.href)} - > - - {item.name} - - {/each} - - {#if $licenseStore.isEnterprise && $authStore.authEnabled} - - - handleSelect('/audit')} - > - - Audit log - - - {/if} - - - {#each lightThemes as theme (theme.id)} - handleLightThemeSelect(theme.id)} - > - -
-
- {theme.name} -
- {#if $themeStore.lightTheme === theme.id} - - {/if} -
- {/each} -
- - - {#each darkThemes as theme (theme.id)} - handleDarkThemeSelect(theme.id)} - > - -
-
- {theme.name} -
- {#if $themeStore.darkTheme === theme.id} - - {/if} -
- {/each} -
- - - {#each fonts as font (font.id)} - handleFontSelect(font.id)} - > - - {font.name} - {#if $themeStore.font === font.id} - - {/if} - - {/each} - - {#if environments.length > 0} - - - {#each environments as env (env.id)} - handleEnvSelect(env)} - > - - {env.name} - {#if $currentEnvironment?.id === env.id} - + + + Command palette + Search for pages, themes, environments, stacks and containers + +
+ + = 0 ? `palette-row-${activeRow}` : undefined} + class="h-11 w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground" + /> +
+ + {#if rows.length === 0} +
No results found.
+ {:else} +
(scrollTop = e.currentTarget.scrollTop)} + class="max-h-[min(60vh,400px)] overflow-y-auto" + > +
+ {#each visible as { row, index } (index)} + {#if row.type === 'header'} +
+ {row.group} +
+ {:else} + {@const item = row.item} + {@const meta = built.meta.get(item.id)} + {@const isActive = index === activeRow} + + +
{ activeRow = index; meta?.run(); }} + onmousemove={() => (activeRow = index)} + class="absolute left-0 right-0 flex cursor-pointer items-center gap-2 px-3 text-sm {isActive ? 'bg-accent text-accent-foreground' : ''}" + style="top: {offsets[index]}px; height: {ITEM_H}px;" + > + {#if meta?.container} + {@const c = meta.container} + +
+ {item.label} + + + {c.envName} - {c.image} + +
+ {#if isActive} +
+ {#if c.state === 'running'} + + + + + {:else} + + {/if} +
+ {/if} + {:else if meta?.stack} + {@const s = meta.stack} + +
+ {item.label} + + + {s.envName} + +
+ {:else if meta?.env} + + {item.label} + {#if item.active} + + {/if} + {:else} + {@const Icon = meta?.icon ?? Box} + + {#if meta?.preview} + + {/if} + {item.label} + {#if item.active} + + {/if} + {/if} +
{/if} - - {/each} - - {/if} - {#if containers.length > 0} - - - {#each containers as container (container.id)} - handleContainerAction(container.id, 'logs')} - > - -
- {container.name} - {container.envName} • {container.image} -
-
- {#if container.state === 'running'} - - - - - {:else} - - {/if} -
-
- {/each} -
+ {/each} +
+
{/if} -
-
+ + diff --git a/src/lib/components/ContainerTagsSection.svelte b/src/lib/components/ContainerTagsSection.svelte new file mode 100644 index 000000000..4c287cf26 --- /dev/null +++ b/src/lib/components/ContainerTagsSection.svelte @@ -0,0 +1,66 @@ + + +
+ apply(assigned.filter((id) => id !== t.id))} /> + + {#if assignedTags.length === 0} + {emptyHint} + {/if} +
diff --git a/src/lib/components/EditorThemeSelector.svelte b/src/lib/components/EditorThemeSelector.svelte new file mode 100644 index 000000000..9c64c43a2 --- /dev/null +++ b/src/lib/components/EditorThemeSelector.svelte @@ -0,0 +1,173 @@ + + +
+
+ + +
+ + +
+
+ + + {#if awaitingGlobal} +
+ {:else} + + + {currentFontName} + + + {#each monospaceFonts as font} + + {font.name} + + {/each} + + + {/if} +
+ +
+ + {#if awaitingGlobal} +
+ {:else} + + + {currentLabel} + + + Default (follows app theme) + + Dark + {#each darkThemes as t} + {t.label} + {/each} + + + Light + {#each lightThemes as t} + {t.label} + {/each} + + + + {/if} +
+
+ + +
+ +
+

Applies to all code editors (compose files, env, config). Follows this theme regardless of the light/dark app setting.

+
diff --git a/src/lib/components/StackTagsSection.svelte b/src/lib/components/StackTagsSection.svelte new file mode 100644 index 000000000..c808c7082 --- /dev/null +++ b/src/lib/components/StackTagsSection.svelte @@ -0,0 +1,63 @@ + + +
+ apply(assigned.filter((id) => id !== t.id))} /> + +
diff --git a/src/lib/components/TagChips.svelte b/src/lib/components/TagChips.svelte new file mode 100644 index 000000000..4d4426246 --- /dev/null +++ b/src/lib/components/TagChips.svelte @@ -0,0 +1,37 @@ + + +{#if tags.length} +
+ {#each tags as tag (tag.id)} + {@const hex = tagHex(tag.color)} + + {#if tag.icon} + + {:else} + + {/if} + {tag.name} + {#if onRemove} + + {/if} + + {/each} +
+{/if} diff --git a/src/lib/components/TagEditPopover.svelte b/src/lib/components/TagEditPopover.svelte new file mode 100644 index 000000000..a62a20f10 --- /dev/null +++ b/src/lib/components/TagEditPopover.svelte @@ -0,0 +1,141 @@ + + + + + {#snippet child({ props })} + + {/snippet} + + + { if (e.key === 'Enter' && canCreate) create(); }} /> + + {#if canCreate} + {@const hex = tagHex(newColor)} +
+
Create new tag
+ +
+ + {#if newIcon}{:else}{/if} + {normalizeTag(query)} + +
+
+ {#each TAG_COLORS as c} + + {/each} +
+ +
+ +
+ + {#each iconResults as ic (ic)} + + {/each} +
+
+ +
+ {/if} + +
+ {#if filtered.length === 0 && !canCreate} +
No tags
+ {/if} + {#each filtered as tag (tag.id)} + {@const isSel = selected.includes(tag.id)} + + {/each} +
+
+
diff --git a/src/lib/components/TagFilter.svelte b/src/lib/components/TagFilter.svelte new file mode 100644 index 000000000..1b6ac68ec --- /dev/null +++ b/src/lib/components/TagFilter.svelte @@ -0,0 +1,103 @@ + + + + + {#snippet child({ props })} + + {/snippet} + + + {#if groupBy !== undefined} +
+ + Group by tag + +
+ {#if showBands !== undefined && groupBy} + +
+ + Group colors + +
+ {/if} + {/if} + {#if showTags !== undefined} +
+ + Show tags + +
+ {/if} + {#if groupBy !== undefined || showTags !== undefined} +
+ {/if} + {#if tags.length === 0} +
No tags yet
+ {:else} + +
+ Match + (mode = m as TagFilterMode)} /> +
+
+ {#each tags as tag (tag.id)} + {@const isSel = selected.includes(tag.id)} + + {/each} +
+ {#if selected.length > 0} + + {/if} + {/if} +
+
diff --git a/src/lib/components/TagIconPicker.svelte b/src/lib/components/TagIconPicker.svelte new file mode 100644 index 000000000..1d6d978ae --- /dev/null +++ b/src/lib/components/TagIconPicker.svelte @@ -0,0 +1,63 @@ + + + + + {#snippet child({ props })} + + {/snippet} + + + +
+ + {#each results as ic (ic)} + + {/each} +
+
+
diff --git a/src/lib/components/TagLucideIcon.svelte b/src/lib/components/TagLucideIcon.svelte new file mode 100644 index 000000000..e1ee51c9d --- /dev/null +++ b/src/lib/components/TagLucideIcon.svelte @@ -0,0 +1,13 @@ + + + diff --git a/src/lib/components/ThemeSelector.svelte b/src/lib/components/ThemeSelector.svelte index e97f382f4..e776b2789 100644 --- a/src/lib/components/ThemeSelector.svelte +++ b/src/lib/components/ThemeSelector.svelte @@ -1,6 +1,6 @@
@@ -367,28 +357,5 @@
- -
-
- - -
- - - {#each monospaceFonts as font} - {#if font.id === selectedEditorFont} - {font.name} - {/if} - {/each} - - - {#each monospaceFonts as font} - - {font.name} - - {/each} - - -
{/if} diff --git a/src/lib/components/data-grid/DataGrid.svelte b/src/lib/components/data-grid/DataGrid.svelte index 93468dbbd..67891ee83 100644 --- a/src/lib/components/data-grid/DataGrid.svelte +++ b/src/lib/components/data-grid/DataGrid.svelte @@ -11,6 +11,7 @@ import type { GridId, ColumnConfig, ColumnPreference } from '$lib/types'; import type { DataGridSortState, DataGridRowState } from './types'; import { setDataGridContext } from './context'; + import { groupData, type GroupDescriptor, type DataGridGroup } from './grouping-core'; // Props interface Props { @@ -59,6 +60,18 @@ // Selection filter - return false to make an item non-selectable selectableFilter?: (item: T) => boolean; + // Visual grouping (standard, non-virtual mode only; OFF by default). + // When `groupBy` is set, rows are partitioned into collapsible sections with + // a coloured header. When it is undefined the render path is byte-for-byte + // the ungrouped grid. + groupBy?: (item: T) => GroupDescriptor | null; + collapsedGroups?: Set; + ungroupedLabel?: string; + /** Draw the coloured left accent band spanning each group (default true). */ + showGroupBands?: boolean; + /** Optional custom header content (e.g. tag chips/icons) rendered inside the group pill. */ + groupHeaderLabel?: Snippet<[DataGridGroup]>; + // Expandable rows expandable?: boolean; expandedKeys?: Set; @@ -101,6 +114,11 @@ windowTotal, onWindowShift, onVisibleRangeChange, + groupBy, + collapsedGroups = $bindable(new Set()), + ungroupedLabel = 'Untagged', + showGroupBands = true, + groupHeaderLabel, onRowClick, highlightedKey, rowClass, @@ -456,6 +474,28 @@ return cachedVisibleData; }); + // Grouping (standard mode only). Empty when `groupBy` is not supplied, so the + // ungrouped body is chosen and nothing here runs. + const groups = $derived.by[]>(() => + groupBy ? groupData(data, groupBy, ungroupedLabel) : [] + ); + function toggleGroup(key: string) { + const collapsed = collapsedGroups.has(key); + const next = new Set(collapsedGroups); + if (collapsed) next.delete(key); else next.add(key); + collapsedGroups = next; + } + // Global, stable row index across all groups (for getRowState cache validity). + const groupIndexMap = $derived.by(() => { + const m = new Map(); + let i = 0; + for (const g of groups) for (const item of g.items) m.set(item, i++); + return m; + }); + function groupRowIndex(item: T): number { + return groupIndexMap.get(item) ?? 0; + } + // Windowed rows for the absolute range [startIndex, endIndex): each position is // the loaded row or undefined (→ a loading placeholder row). const windowedVisible = $derived.by<(T | undefined)[]>(() => { @@ -974,10 +1014,57 @@ {/snippet} + +{#snippet groupedBody()} + {@const totalCols = fixedStartCols.length + orderedColumns.length + fixedEndCols.length} + + {#each groups as group (group.key)} + {@const collapsed = collapsedGroups.has(group.key)} + {@const hex = group.color} + {@const band = !showGroupBands ? 'transparent' : (hex ?? 'var(--color-muted-foreground)')} + + + + + + + {#if !collapsed} + {#each group.items as item (item[keyField])} + {@render dataRow(item, getRowState(item, groupRowIndex(item)))} + {/each} + {/if} + + {/each} +{/snippet} + {#snippet tableContent()} {@render tableHeader()} - {@render tableBody()} + {#if groupBy} + {@render groupedBody()} + {:else} + {@render tableBody()} + {/if}
{/snippet} @@ -1027,3 +1114,12 @@ {@render tableContent()} {/if} + + diff --git a/src/lib/components/data-grid/grouping-core.ts b/src/lib/components/data-grid/grouping-core.ts new file mode 100644 index 000000000..4564dae8d --- /dev/null +++ b/src/lib/components/data-grid/grouping-core.ts @@ -0,0 +1,70 @@ +// Pure grouping logic for the DataGrid. Kept import-light + unit-tested so the +// grid component stays glue. A row's group descriptor is supplied by the caller +// (e.g. containers group by their tag combination); this module only partitions +// and orders, it does not know about tags. + +/** What `groupBy(item)` returns for one row. `null` = ungrouped (the trailing group). */ +export interface GroupDescriptor { + /** Stable identity of the group (rows with the same key share a group). */ + key: string; + /** Human label shown in the header. */ + label: string; + /** Optional accent colour (hex) for the header + left band. */ + color?: string | null; + /** Optional icon names shown in the header (e.g. one per tag in the combo). */ + icons?: (string | null)[]; + /** + * Sort weight for ordering groups against each other. Lower comes first. + * Ungrouped rows use +Infinity so they always trail. Defaults to 0. + */ + order?: number; +} + +export interface DataGridGroup { + key: string; + label: string; + color: string | null; + icons: (string | null)[]; + items: T[]; +} + +/** Sentinel key for the "no group" bucket (rows whose groupBy returned null). */ +export const UNGROUPED_KEY = '__ungrouped__'; + +/** + * Partition `data` into ordered groups. Row order WITHIN a group is preserved + * (the caller pre-sorts `data`), so grouping composes with column sorting. + * Group order: by `order` weight, then first-appearance, so it is stable and + * independent of object identity. The ungrouped bucket always trails. + */ +export function groupData( + data: T[], + groupBy: (item: T) => GroupDescriptor | null, + ungroupedLabel = 'Untagged' +): DataGridGroup[] { + const groups = new Map & { order: number; seq: number }>(); + let seq = 0; + + for (const item of data) { + const desc = groupBy(item); + const key = desc ? desc.key : UNGROUPED_KEY; + let g = groups.get(key); + if (!g) { + g = { + key, + label: desc ? desc.label : ungroupedLabel, + color: desc?.color ?? null, + icons: desc?.icons ?? [], + items: [], + order: desc ? (desc.order ?? 0) : Number.POSITIVE_INFINITY, + seq: seq++ + }; + groups.set(key, g); + } + g.items.push(item); + } + + return [...groups.values()] + .sort((a, b) => a.order - b.order || a.seq - b.seq) + .map(({ order: _order, seq: _seq, ...g }) => g); +} diff --git a/src/lib/components/ui/search-input/index.ts b/src/lib/components/ui/search-input/index.ts new file mode 100644 index 000000000..2cb00c927 --- /dev/null +++ b/src/lib/components/ui/search-input/index.ts @@ -0,0 +1,3 @@ +import SearchInput from './search-input.svelte'; + +export { SearchInput, SearchInput as Root }; diff --git a/src/lib/components/ui/search-input/search-input.svelte b/src/lib/components/ui/search-input/search-input.svelte new file mode 100644 index 000000000..b9457ab7c --- /dev/null +++ b/src/lib/components/ui/search-input/search-input.svelte @@ -0,0 +1,55 @@ + + +
+ + { + if (e.key === 'Escape' && value) { + e.preventDefault(); + value = ''; + } + onkeydown?.(e); + }} + class={cn('pl-8', value ? 'pr-8' : '', className)} + {...rest} + /> + {#if value} + + {/if} +
diff --git a/src/lib/data/changelog.json b/src/lib/data/changelog.json index 31359abe1..c54175b3a 100644 --- a/src/lib/data/changelog.json +++ b/src/lib/data/changelog.json @@ -1,4 +1,31 @@ [ + { + "version": "1.0.49", + "date": "", + "comingSoon": true, + "changes": [ + { "type": "feature", "text": "tag containers and stacks, then filter and group the grid by tag (#781, #870)" }, + { "type": "fix", "text": "don't report a newer version tag that resolves to the image you already run (#1572)" }, + { "type": "fix", "text": "fix vulnerability scans failing on the containerd image store (#1569, #1350)" }, + { "type": "fix", "text": "show CPU and memory for containers on Windows Docker hosts (#1574)" }, + { "type": "fix", "text": "don't send container died/killed notifications for a container being updated (#68)" }, + { "type": "fix", "text": "stop, start, restart and remove stacks that use secret providers, e.g. stop-during-backup (#1579)" }, + { "type": "fix", "text": "check for image updates on a plain-HTTP registry (#1580)" }, + { "type": "fix", "text": "send you to the login page when your session expires (#1577)" }, + { "type": "fix", "text": "skip hidden folders like .snapshots when scanning for stacks to adopt (#1251)" }, + { "type": "fix", "text": "updating a Podman container managed by a systemd Quadlet unit now works (#1529, #1559)" }, + { "type": "fix", "text": "option to skip bind mounts when scheduling backups for a whole environment (#1570)" }, + { "type": "fix", "text": "git stack env vars stay visible in the editor after saving (#1112)" }, + { "type": "feature", "text": "search and filter containers by label (#1372)" }, + { "type": "feature", "text": "editor themes: select from 40 themes with live preview (#1309)" }, + { "type": "feature", "text": "command palette searches stacks and containers across all hosts (#670)" }, + { "type": "feature", "text": "clear a search field with the X button in it (#1321)" }, + { "type": "fix", "text": "clearing a container's command now reverts it to the image default (#1489)" }, + { "type": "feature", "text": "one-shot container exec API returning stdout, stderr and exit code (#1380)" }, + { "type": "feature", "text": "set and change file ownership in the container file browser (#224)" } + ], + "imageTag": "fnsys/dockhand:v1.0.49" + }, { "version": "1.0.48", "date": "2026-09-14", diff --git a/src/lib/data/dependencies.json b/src/lib/data/dependencies.json index 1dbbce906..d0dd0296c 100644 --- a/src/lib/data/dependencies.json +++ b/src/lib/data/dependencies.json @@ -383,6 +383,228 @@ "license": "MIT", "repository": "https://github.com/typescript-eslint/typescript-eslint" }, + { + "name": "@uiw/codemirror-theme-abcdef", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-abyss", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-androidstudio", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-andromeda", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-atomone", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-aura", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-basic", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-bbedit", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-bespin", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-console", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-copilot", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-darcula", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-dracula", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-duotone", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-eclipse", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-github", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-gruvbox-dark", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-kimbie", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-material", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-monokai", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-monokai-dimmed", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-noctis-lilac", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-nord", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-okaidia", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-quietlight", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-red", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-solarized", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-sublime", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-tokyo-night", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-tokyo-night-day", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-tokyo-night-storm", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-tomorrow-night-blue", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-vscode", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-white", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-theme-xcode", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-themes", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, + { + "name": "@uiw/codemirror-themes-all", + "version": "4.25.11", + "license": "MIT", + "repository": "https://github.com/uiwjs/react-codemirror" + }, { "name": "abort-controller", "version": "3.0.0", diff --git a/src/lib/env-merge.ts b/src/lib/env-merge.ts new file mode 100644 index 000000000..222e59ed0 --- /dev/null +++ b/src/lib/env-merge.ts @@ -0,0 +1,58 @@ +// Merge a git stack's repo .env vars with its DB override vars for display in the +// editor. The save path stores only overrides (vars that differ from the repo .env, +// plus secrets), so a reopened editor would otherwise show only the changed vars - the +// untouched repo vars vanish even though the deploy still applies them. +// +// Precedence mirrors deploy (stacks.ts: repo .env first, .env.dockhand + secrets on +// top): file value is the base, a DB non-secret var overrides its key, a DB secret +// (masked '***') always wins over any same-named file key. + +import type { EnvVar } from '$lib/components/StackEnvVarsEditor.svelte'; + +export type { EnvVar }; + +// The load-bearing git-sync predicate: an editor var is stored to the DB only when it +// differs from the repo .env value, is new (no file entry), or is a secret. Everything +// file-equal and non-secret is dropped so the DB stays override-only. Shared by the +// modal's save filter, the re-populate preserve step, and the merge round-trip test so +// the invariant has one definition. +export function isGitStackOverride(v: EnvVar, fileVars: Record): boolean { + if (!v.key.trim()) return false; + const fileValue = fileVars[v.key]; + return fileValue === undefined || v.value !== fileValue || v.isSecret; +} + +export function mergeGitStackEnvVars( + fileVars: Record, + dbVars: EnvVar[] +): EnvVar[] { + const dbByKey = new Map(); + for (const v of dbVars) { + const key = v.key.trim(); + if (key) dbByKey.set(key, v); + } + + const merged: EnvVar[] = []; + const seen = new Set(); + + // File vars form the base, in file order. A DB var with the same key overrides it. + for (const [key, value] of Object.entries(fileVars)) { + const override = dbByKey.get(key); + if (override) { + merged.push({ key, value: override.value, isSecret: override.isSecret }); + } else { + merged.push({ key, value, isSecret: false }); + } + seen.add(key); + } + + // DB-only vars (user overrides / secrets with no file counterpart) keep their order. + for (const v of dbVars) { + const key = v.key.trim(); + if (!key || seen.has(key)) continue; + merged.push({ key, value: v.value, isSecret: v.isSecret }); + seen.add(key); + } + + return merged; +} diff --git a/src/lib/openapi.generated.json b/src/lib/openapi.generated.json index ae4621899..134146e4d 100644 --- a/src/lib/openapi.generated.json +++ b/src/lib/openapi.generated.json @@ -38,6 +38,9 @@ { "name": "container-icons" }, + { + "name": "container-tags" + }, { "name": "containers" }, @@ -131,12 +134,18 @@ { "name": "settings" }, + { + "name": "stack-tags" + }, { "name": "stacks" }, { "name": "system" }, + { + "name": "tags" + }, { "name": "templates" }, @@ -6375,6 +6384,206 @@ ] } }, + "/api/container-tags": { + "get": { + "operationId": "get_api_container-tags", + "tags": [ + "container-tags" + ], + "summary": "List all container tag assignments for an environment as a name -> tagIds map", + "parameters": [ + { + "name": "env", + "in": "query", + "required": false, + "schema": { + "type": "integer" + }, + "description": "Environment id" + } + ], + "responses": { + "200": { + "description": "A JSON object mapping container name to its array of tag ids" + }, + "403": { + "description": "Permission denied (needs containers:view)" + } + }, + "security": [ + { + "cookieAuth": [] + }, + { + "bearerAuth": [] + } + ], + "description": "Returns every container that has tags assigned in the given environment, so the containers list can render and filter by tag in one request instead of one lookup per row." + } + }, + "/api/container-tags/{name}": { + "get": { + "operationId": "get_api_container-tags_name", + "tags": [ + "container-tags" + ], + "summary": "Get the tag ids assigned to one container (by name)", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Container name" + }, + { + "name": "env", + "in": "query", + "required": false, + "schema": { + "type": "integer" + }, + "description": "Environment id" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "tagIds": { + "type": "array", + "items": { + "type": "integer" + } + } + }, + "required": [ + "tagIds" + ] + }, + "example": { + "tagIds": [ + 3, + 7 + ] + } + } + } + }, + "403": { + "description": "Permission denied (needs containers:view)" + } + }, + "security": [ + { + "cookieAuth": [] + }, + { + "bearerAuth": [] + } + ] + }, + "put": { + "operationId": "put_api_container-tags_name", + "tags": [ + "container-tags" + ], + "summary": "Replace the tag ids assigned to one container (by name)", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Container name" + }, + { + "name": "env", + "in": "query", + "required": false, + "schema": { + "type": "integer" + }, + "description": "Environment id" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "tagIds": { + "type": "array", + "items": { + "type": "integer" + } + } + }, + "required": [ + "tagIds" + ] + }, + "example": { + "tagIds": [ + 3, + 7 + ] + } + } + } + }, + "403": { + "description": "Permission denied (needs containers:edit)" + } + }, + "security": [ + { + "cookieAuth": [] + }, + { + "bearerAuth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "tagIds": { + "type": "array", + "items": { + "type": "integer" + } + } + }, + "required": [ + "tagIds" + ] + }, + "example": { + "tagIds": [ + 3, + 7 + ] + } + } + } + } + } + }, "/api/containers": { "get": { "operationId": "get_api_containers", @@ -6646,11 +6855,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" } ], "responses": { @@ -6695,11 +6904,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" }, { "name": "force", @@ -6773,11 +6982,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" } ], "responses": { @@ -6848,11 +7057,11 @@ { "name": "envId", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" } ], "responses": { @@ -6941,13 +7150,13 @@ } } }, - "/api/containers/{id}/files": { - "get": { - "operationId": "get_api_containers_id_files", + "/api/containers/{id}/exec/run": { + "post": { + "operationId": "post_api_containers_id_exec_run", "tags": [ "containers" ], - "summary": "List the contents of a directory inside a container's filesystem", + "summary": "Run a finite command in a container and wait for the result, returning stdout, stderr and the exit code (a non-interactive alternative to the terminal exec endpoint). Intended for short commands - the request is bounded by a ~30s ceiling on remote (Hawser/TCP) environments; use the interactive terminal for long-running work.", "parameters": [ { "name": "id", @@ -6959,45 +7168,58 @@ "description": "Container ID or name (from GET /api/containers)" }, { - "name": "env", + "name": "envId", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" - }, - { - "name": "path", - "in": "query", - "required": false, - "schema": { - "type": "string" - }, - "description": "Absolute directory path inside the container (default \"/\")" - }, - { - "name": "simpleLs", - "in": "query", - "required": false, - "schema": { - "type": "boolean" - }, - "description": "Use a lightweight `ls` listing instead of a full stat of each entry" + "description": "The target environment ID the container lives in (from GET /api/environments)" } ], "responses": { "200": { - "description": "Directory listing (entries with name, type, size and permission metadata)" + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "stdout": { + "type": "string" + }, + "stderr": { + "type": "string" + }, + "exitCode": { + "type": "integer" + } + }, + "required": [ + "stdout", + "stderr", + "exitCode" + ] + }, + "example": { + "stdout": "string", + "stderr": "string", + "exitCode": 0 + } + } + } }, - "403": { - "description": "Permission denied (needs containers:exec)" + "400": { + "description": "Missing or invalid cmd (must be a non-empty array of strings)" }, - "404": { - "description": "Container not found" + "401": { + "description": "Not authenticated" + }, + "403": { + "description": "Permission denied" }, "500": { - "description": "Failed to list the directory" + "description": "Failed to run the command" } }, "security": [ @@ -7007,16 +7229,51 @@ { "bearerAuth": [] } - ] - } - }, - "/api/containers/{id}/files/chmod": { - "post": { - "operationId": "post_api_containers_id_files_chmod", - "tags": [ - "containers" ], - "summary": "Change the mode (permissions) of a file or directory inside a container (requires the 'exec' permission)", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "cmd": { + "type": "array", + "items": { + "type": "string" + } + }, + "user": { + "type": "string" + }, + "workingDir": { + "type": "string" + } + }, + "required": [ + "cmd" + ] + }, + "example": { + "cmd": [ + "sh", + "-c", + "echo hi && exit 3" + ], + "workingDir": "/app" + } + } + } + } + } + }, + "/api/containers/{id}/files": { + "get": { + "operationId": "get_api_containers_id_files", + "tags": [ + "containers" + ], + "summary": "List the contents of a directory inside a container's filesystem", "parameters": [ { "name": "id", @@ -7030,11 +7287,80 @@ { "name": "env", "in": "query", + "required": true, + "schema": { + "type": "integer" + }, + "description": "The target environment ID the container lives in (from GET /api/environments)" + }, + { + "name": "path", + "in": "query", + "required": false, + "schema": { + "type": "string" + }, + "description": "Absolute directory path inside the container (default \"/\")" + }, + { + "name": "simpleLs", + "in": "query", "required": false, + "schema": { + "type": "boolean" + }, + "description": "Use a lightweight `ls` listing instead of a full stat of each entry" + } + ], + "responses": { + "200": { + "description": "Directory listing (entries with name, type, size and permission metadata)" + }, + "403": { + "description": "Permission denied (needs containers:exec)" + }, + "404": { + "description": "Container not found" + }, + "500": { + "description": "Failed to list the directory" + } + }, + "security": [ + { + "cookieAuth": [] + }, + { + "bearerAuth": [] + } + ] + } + }, + "/api/containers/{id}/files/chmod": { + "post": { + "operationId": "post_api_containers_id_files_chmod", + "tags": [ + "containers" + ], + "summary": "Change the mode (permissions) of a file or directory inside a container (requires the 'exec' permission)", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Container ID or name (from GET /api/containers)" + }, + { + "name": "env", + "in": "query", + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" } ], "responses": { @@ -7127,6 +7453,123 @@ } } }, + "/api/containers/{id}/files/chown": { + "post": { + "operationId": "post_api_containers_id_files_chown", + "tags": [ + "containers" + ], + "summary": "Change the owner (and optional group) of a file or directory inside a container (requires the 'exec' permission)", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Container ID or name (from GET /api/containers)" + }, + { + "name": "env", + "in": "query", + "required": true, + "schema": { + "type": "integer" + }, + "description": "The target environment ID the container lives in (from GET /api/environments)" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "path": { + "type": "string" + }, + "owner": { + "type": "string" + }, + "recursive": { + "type": "boolean" + } + }, + "required": [ + "success", + "path", + "owner", + "recursive" + ] + }, + "example": { + "success": true, + "path": "/app/data", + "owner": "1000:1000", + "recursive": true + } + } + } + }, + "400": { + "description": "Path or owner missing, an invalid owner spec, or the container is not running" + }, + "403": { + "description": "Permission denied, read-only file system, or operation not permitted" + }, + "404": { + "description": "Path not found" + }, + "500": { + "description": "Failed to change ownership" + } + }, + "security": [ + { + "cookieAuth": [] + }, + { + "bearerAuth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "path": { + "type": "string" + }, + "owner": { + "type": "string" + }, + "recursive": { + "type": "boolean" + } + }, + "required": [ + "path", + "owner" + ] + }, + "example": { + "path": "/app/data", + "owner": "1000:1000", + "recursive": true + } + } + } + } + } + }, "/api/containers/{id}/files/content": { "get": { "operationId": "get_api_containers_id_files_content", @@ -7147,11 +7590,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" }, { "name": "path", @@ -7234,11 +7677,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" }, { "name": "path", @@ -7347,11 +7790,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" } ], "responses": { @@ -7370,6 +7813,9 @@ }, "type": { "type": "string" + }, + "owner": { + "type": "string" } }, "required": [ @@ -7381,7 +7827,8 @@ "example": { "success": true, "path": "/app/data", - "type": "directory" + "type": "directory", + "owner": "1000:1000" } } } @@ -7422,6 +7869,9 @@ }, "type": { "type": "string" + }, + "owner": { + "type": "string" } }, "required": [ @@ -7431,7 +7881,8 @@ }, "example": { "path": "/app/data", - "type": "directory" + "type": "directory", + "owner": "1000:1000" } } } @@ -7458,11 +7909,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" }, { "name": "path", @@ -7544,11 +7995,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" }, { "name": "path", @@ -7616,11 +8067,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" } ], "responses": { @@ -7727,11 +8178,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" }, { "name": "path", @@ -7810,18 +8261,11 @@ "schema": { "type": "object", "properties": { - "files": { - "type": "array", - "items": { - "type": "string", - "format": "binary" - }, - "description": "One or more files to write into the target directory" + "owner": { + "type": "string", + "description": "Optional owner (\"user\", \"user:group\", \"uid\" or \"uid:gid\") to chown the uploaded files to; defaults to the container's configured user" } - }, - "required": [ - "files" - ] + } } } } @@ -7848,11 +8292,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" } ], "responses": { @@ -7896,11 +8340,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" }, { "name": "tail", @@ -7989,11 +8433,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" }, { "name": "tail", @@ -8062,11 +8506,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" } ], "responses": { @@ -8128,11 +8572,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" } ], "responses": { @@ -8221,11 +8665,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" } ], "responses": { @@ -8290,11 +8734,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" } ], "responses": { @@ -8398,11 +8842,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" } ], "responses": { @@ -8467,11 +8911,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" } ], "responses": { @@ -8586,11 +9030,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" } ], "responses": { @@ -8655,11 +9099,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" } ], "responses": { @@ -8747,11 +9191,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" } ], "responses": { @@ -8813,11 +9257,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" } ], "responses": { @@ -9094,11 +9538,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" }, { "name": "versions", @@ -9207,11 +9651,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" } ], "responses": { @@ -9354,11 +9798,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" } ], "responses": { @@ -9424,11 +9868,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" } ], "responses": { @@ -9517,11 +9961,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" } ], "responses": { @@ -9725,11 +10169,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" } ], "responses": { @@ -9764,11 +10208,11 @@ { "name": "env", "in": "query", - "required": false, + "required": true, "schema": { "type": "integer" }, - "description": "The target environment ID (omit for the local/default Docker host) (from GET /api/environments)" + "description": "The target environment ID the container lives in (from GET /api/environments)" }, { "name": "debug", @@ -12579,6 +13023,9 @@ }, "memoryLimitSupported": { "type": "boolean" + }, + "showMemoryWarning": { + "type": "boolean" } } }, @@ -12598,7 +13045,8 @@ "containers": 0, "images": 0, "name": "string", - "memoryLimitSupported": true + "memoryLimitSupported": true, + "showMemoryWarning": true }, "hawser": {} } @@ -20201,7 +20649,7 @@ "description": "Successful response" }, "400": { - "description": "A supplied field has the wrong type (e.g. editorIndentGuides not a boolean)" + "description": "A supplied field has the wrong type or an invalid value (e.g. editorIndentGuides not a boolean, or an unknown editorTheme)" }, "401": { "description": "Not authenticated" @@ -20257,6 +20705,9 @@ }, "editorIndentGuides": { "type": "boolean" + }, + "editorTheme": { + "type": "string" } } }, @@ -20271,7 +20722,8 @@ "animateIcons": true, "coloredActionButtons": true, "actionIconSize": "string", - "editorIndentGuides": true + "editorIndentGuides": true, + "editorTheme": "string" } } } @@ -23813,6 +24265,9 @@ "editorIndentGuides": { "type": "boolean" }, + "inlineTagEditing": { + "type": "boolean" + }, "coloredActionButtons": { "type": "boolean" }, @@ -23882,6 +24337,9 @@ "editorFont": { "type": "string" }, + "editorTheme": { + "type": "string" + }, "eventCleanupCron": { "type": "string" }, @@ -23980,6 +24438,7 @@ "example": { "animateIcons": true, "editorIndentGuides": true, + "inlineTagEditing": true, "coloredActionButtons": true, "lightTheme": "string", "darkTheme": "string", @@ -24004,6 +24463,7 @@ "deployLogReconcileEnabled": true, "downloadFormat": "string", "editorFont": "string", + "editorTheme": "string", "eventCleanupCron": "string", "eventCleanupEnabled": true, "eventCollectionMode": "string", @@ -24667,6 +25127,43 @@ "security": [] } }, + "/api/stack-tags": { + "get": { + "operationId": "get_api_stack-tags", + "tags": [ + "stack-tags" + ], + "summary": "List all stack tag assignments for an environment as a name -> tagIds map", + "parameters": [ + { + "name": "env", + "in": "query", + "required": false, + "schema": { + "type": "integer" + }, + "description": "Environment id" + } + ], + "responses": { + "200": { + "description": "A JSON object mapping stack name to its array of tag ids" + }, + "403": { + "description": "Permission denied (needs stacks:view)" + } + }, + "security": [ + { + "cookieAuth": [] + }, + { + "bearerAuth": [] + } + ], + "description": "Returns every stack that has tags assigned in the given environment, so the stacks list can render and filter by tag in one request." + } + }, "/api/stacks": { "get": { "operationId": "get_api_stacks", @@ -26836,6 +27333,166 @@ ] } }, + "/api/stacks/{name}/tags": { + "get": { + "operationId": "get_api_stacks_name_tags", + "tags": [ + "stacks" + ], + "summary": "Get the tag ids assigned to one stack (by name)", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Stack name" + }, + { + "name": "env", + "in": "query", + "required": false, + "schema": { + "type": "integer" + }, + "description": "Environment id" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "tagIds": { + "type": "array", + "items": { + "type": "integer" + } + } + }, + "required": [ + "tagIds" + ] + }, + "example": { + "tagIds": [ + 3 + ] + } + } + } + }, + "403": { + "description": "Permission denied (needs stacks:view)" + } + }, + "security": [ + { + "cookieAuth": [] + }, + { + "bearerAuth": [] + } + ] + }, + "put": { + "operationId": "put_api_stacks_name_tags", + "tags": [ + "stacks" + ], + "summary": "Replace the tag ids assigned to one stack (by name)", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Stack name" + }, + { + "name": "env", + "in": "query", + "required": false, + "schema": { + "type": "integer" + }, + "description": "Environment id" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "tagIds": { + "type": "array", + "items": { + "type": "integer" + } + } + }, + "required": [ + "tagIds" + ] + }, + "example": { + "tagIds": [ + 3 + ] + } + } + } + }, + "403": { + "description": "Permission denied (needs stacks:edit)" + } + }, + "security": [ + { + "cookieAuth": [] + }, + { + "bearerAuth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "tagIds": { + "type": "array", + "items": { + "type": "integer" + } + } + }, + "required": [ + "tagIds" + ] + }, + "example": { + "tagIds": [ + 3 + ] + } + } + } + } + } + }, "/api/stacks/{name}/validate": { "post": { "operationId": "post_api_stacks_name_validate", @@ -28011,6 +28668,303 @@ ] } }, + "/api/tags": { + "get": { + "operationId": "get_api_tags", + "tags": [ + "tags" + ], + "summary": "List the global tag catalog (name + colour)", + "parameters": [], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "tags": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "color": { + "type": "string" + } + }, + "required": [ + "id", + "name", + "color" + ] + } + } + }, + "required": [ + "tags" + ] + }, + "example": { + "tags": [ + { + "id": 3, + "name": "auth", + "color": "green" + } + ] + } + } + } + }, + "403": { + "description": "Permission denied (needs containers:view)" + } + }, + "security": [ + { + "cookieAuth": [] + }, + { + "bearerAuth": [] + } + ] + }, + "post": { + "operationId": "post_api_tags", + "tags": [ + "tags" + ], + "summary": "Create a tag (or return the existing one with the same name) in the global catalog", + "parameters": [], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "color": { + "type": "string" + }, + "icon": { + "type": "string" + } + }, + "required": [ + "id", + "name", + "color" + ] + }, + "example": { + "id": 3, + "name": "auth", + "color": "green", + "icon": "shield" + } + } + } + }, + "400": { + "description": "Missing or invalid tag name" + }, + "403": { + "description": "Permission denied (admin only)" + } + }, + "security": [ + { + "cookieAuth": [] + }, + { + "bearerAuth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "color": { + "type": "string" + }, + "icon": { + "type": "string" + } + }, + "required": [ + "name" + ] + }, + "example": { + "name": "auth", + "color": "green", + "icon": "shield" + } + } + } + } + } + }, + "/api/tags/{id}": { + "put": { + "operationId": "put_api_tags_id", + "tags": [ + "tags" + ], + "summary": "Update a global catalog tag's name and/or colour", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + }, + "description": "Tag id" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + } + }, + "required": [ + "success" + ] + }, + "example": { + "success": true + } + } + } + }, + "400": { + "description": "Invalid tag id or name" + }, + "403": { + "description": "Permission denied (admin only)" + }, + "409": { + "description": "A tag with that name already exists" + } + }, + "security": [ + { + "cookieAuth": [] + }, + { + "bearerAuth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "color": { + "type": "string" + }, + "icon": { + "type": "string" + } + } + }, + "example": { + "color": "blue", + "icon": "cloud" + } + } + } + } + }, + "delete": { + "operationId": "delete_api_tags_id", + "tags": [ + "tags" + ], + "summary": "Delete a catalog tag (removes it from every container and stack)", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + }, + "description": "Tag id" + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + } + }, + "required": [ + "success" + ] + }, + "example": { + "success": true + } + } + } + }, + "400": { + "description": "Invalid tag id" + }, + "403": { + "description": "Permission denied (admin only)" + } + }, + "security": [ + { + "cookieAuth": [] + }, + { + "bearerAuth": [] + } + ] + } + }, "/api/templates": { "get": { "operationId": "get_api_templates", diff --git a/src/lib/server/backups/validate.ts b/src/lib/server/backups/validate.ts index e8f2956b7..ef6a5a13b 100644 --- a/src/lib/server/backups/validate.ts +++ b/src/lib/server/backups/validate.ts @@ -66,7 +66,11 @@ export function validateBackupConfig(input: BackupConfigInput): ValidationResult } if (input.allVolumes === false) { const sel = input.selectedVolumes; - if (!Array.isArray(sel) || sel.length === 0) { + // An empty selection would back up no volumes. That is fine for a STACK - its + // compose/.env files are always captured, so the snapshot is a valid config-only + // backup (restorable via redeploy). For a CONTAINER there are no such files, so an + // empty selection really would back up nothing and stays an error. + if (!Array.isArray(sel) || (sel.length === 0 && input.type !== 'stack')) { issues.push({ field: 'selectedVolumes', message: 'select at least one volume, or enable "all volumes"' }); } } diff --git a/src/lib/server/chown-spec-core.ts b/src/lib/server/chown-spec-core.ts new file mode 100644 index 000000000..5e3b1d1c4 --- /dev/null +++ b/src/lib/server/chown-spec-core.ts @@ -0,0 +1,36 @@ +/** + * Validate a chown owner spec (`user`, `user:group`, `uid`, `uid:gid`) before it + * reaches `docker exec chown`. Pure so it is unit-testable and shared by the + * create/upload/chown paths. Rejects anything that isn't a plain user/group + * token, so nothing shell-special or path-like can be injected into the argv. + */ + +// A single user or group token: a numeric id, or a name (letters, digits, and the +// usual account punctuation `_ - .`, starting with a letter/digit/underscore). +const TOKEN = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/; + +export interface ChownSpec { + /** The exact `owner[:group]` string to pass to chown. */ + value: string; +} + +/** + * Parse and validate an owner spec. Returns { value } on success, or { error }. + * Accepts "user", "user:group", "uid", "uid:gid"; a bare token means owner only. + */ +export function parseChownSpec(input: string | null | undefined): ChownSpec | { error: string } { + if (input == null) return { error: 'Owner is required' }; + const raw = String(input).trim(); + if (!raw) return { error: 'Owner is required' }; + if (raw.length > 128) return { error: 'Owner is too long' }; + + const parts = raw.split(':'); + if (parts.length > 2) return { error: 'Owner must be "user" or "user:group"' }; + + const [owner, group] = parts; + if (!TOKEN.test(owner)) return { error: `Invalid user "${owner}"` }; + if (group !== undefined && !TOKEN.test(group)) return { error: `Invalid group "${group}"` }; + + // Normalise: bare owner stays owner-only (chown leaves the group untouched). + return { value: group !== undefined ? `${owner}:${group}` : owner }; +} diff --git a/src/lib/server/db.ts b/src/lib/server/db.ts index a382a11b3..7cee5b847 100644 --- a/src/lib/server/db.ts +++ b/src/lib/server/db.ts @@ -6,6 +6,7 @@ */ import type { SecretProviderConfig, SecretProviderType } from './secretproviders/shared'; +import { normalizeColor, type Tag, type TagColor } from '$lib/utils/tags-core'; import { mergeProviderConfigForWrite } from './secretproviders/shared'; import { db, @@ -44,6 +45,9 @@ import { secretProviders, stackSources, containerIconOverrides, + tags, + containerTags, + stackTags, vulnerabilityScans, auditLogs, containerEvents, @@ -552,8 +556,9 @@ export async function getUserThemePreferences(userId: number): Promise<{ coloredActionButtons: boolean; actionIconSize: string; editorIndentGuides: boolean; + editorTheme: string; }> { - const [lightTheme, darkTheme, font, fontSize, gridFontSize, terminalFont, editorFont, animateIcons, coloredActionButtons, actionIconSize, editorIndentGuides] = await Promise.all([ + const [lightTheme, darkTheme, font, fontSize, gridFontSize, terminalFont, editorFont, animateIcons, coloredActionButtons, actionIconSize, editorIndentGuides, editorTheme] = await Promise.all([ getUserSetting(userId, 'light_theme'), getUserSetting(userId, 'dark_theme'), getUserSetting(userId, 'font'), @@ -564,7 +569,8 @@ export async function getUserThemePreferences(userId: number): Promise<{ getUserSetting(userId, 'animate_icons'), getUserSetting(userId, 'colored_action_buttons'), getUserSetting(userId, 'action_icon_size'), - getUserSetting(userId, 'editor_indent_guides') + getUserSetting(userId, 'editor_indent_guides'), + getUserSetting(userId, 'editor_theme') ]); return { lightTheme: lightTheme || 'default', @@ -580,13 +586,14 @@ export async function getUserThemePreferences(userId: number): Promise<{ coloredActionButtons: coloredActionButtons === 'true', actionIconSize: actionIconSize || 'normal', // Default OFF — only true when explicitly stored (#1410) - editorIndentGuides: editorIndentGuides === 'true' + editorIndentGuides: editorIndentGuides === 'true', + editorTheme: editorTheme || 'default' }; } export async function setUserThemePreferences( userId: number, - prefs: { lightTheme?: string; darkTheme?: string; font?: string; fontSize?: string; gridFontSize?: string; terminalFont?: string; editorFont?: string; animateIcons?: boolean; coloredActionButtons?: boolean; actionIconSize?: string; editorIndentGuides?: boolean } + prefs: { lightTheme?: string; darkTheme?: string; font?: string; fontSize?: string; gridFontSize?: string; terminalFont?: string; editorFont?: string; animateIcons?: boolean; coloredActionButtons?: boolean; actionIconSize?: string; editorIndentGuides?: boolean; editorTheme?: string } ): Promise { const updates: Promise[] = []; if (prefs.lightTheme !== undefined) { @@ -622,6 +629,9 @@ export async function setUserThemePreferences( if (prefs.editorIndentGuides !== undefined) { updates.push(setUserSetting(userId, 'editor_indent_guides', prefs.editorIndentGuides ? 'true' : 'false')); } + if (prefs.editorTheme !== undefined) { + updates.push(setUserSetting(userId, 'editor_theme', prefs.editorTheme)); + } await Promise.all(updates); } @@ -3274,6 +3284,115 @@ export async function deleteContainerIconOverride(containerName: string, environ .where(and(eq(containerIconOverrides.containerName, containerName), containerEnvClause(environmentId))); } +// ============================================================================= +// TAGS (user-defined organizational tags) +// GLOBAL tag catalog (name + colour, unique on name) plus per-env assignment rows +// keyed by container/stack name. Distinct from Docker labels. +// ============================================================================= + +function envClause(col: any, environmentId: number | null) { + return environmentId !== null ? eq(col, environmentId) : isNull(col); +} + +function toTag(r: { id: number; name: string; color: string; icon: string | null }): Tag { + return { id: r.id, name: r.name, color: normalizeColor(r.color), icon: r.icon ?? null }; +} + +/** The whole tag catalog (global - not env-scoped). */ +export async function getTags(): Promise { + const rows = await db.select().from(tags).orderBy(tags.name); + return rows.map(toTag); +} + +/** + * Get an existing catalog tag by name, or create it. Matching is case-INSENSITIVE + * (so "Prod" and "prod" are the same tag), consistent with the rename collision + * check and the UI dedup. Done in JS over the (small, curated) catalog rather than + * a LOWER() query so it stays dialect-portable across SQLite and Postgres. + */ +export async function getOrCreateTag(name: string, color: TagColor, icon?: string | null): Promise { + const lower = name.toLowerCase(); + const findExisting = async () => + (await db.select().from(tags)).find((t) => t.name.toLowerCase() === lower); + const existing = await findExisting(); + if (existing) return toTag(existing); + // A concurrent same-name create races here; the case-insensitive unique index + // (COLLATE NOCASE / lower(name), see migration 0016) makes the loser's insert + // throw even for a case variant. Swallow it and re-select the winner so + // getOrCreateTag stays idempotent instead of surfacing a 500. + try { + await db.insert(tags).values({ name, color, icon: icon ?? null }); + } catch { + /* unique violation - the winner is found by the re-select below */ + } + return toTag((await findExisting())!); +} + +/** Update a catalog tag's name/colour/icon. `icon: null` clears it. */ +export async function updateTag(tagId: number, patch: { name?: string; color?: TagColor; icon?: string | null }): Promise { + const set: Record = {}; + if (patch.name !== undefined) set.name = patch.name; + if (patch.color !== undefined) set.color = patch.color; + if (patch.icon !== undefined) set.icon = patch.icon; + if (Object.keys(set).length === 0) return; + await db.update(tags).set(set).where(eq(tags.id, tagId)); +} + +/** Delete a catalog tag (assignments in every environment cascade away). */ +export async function deleteTag(tagId: number): Promise { + await db.delete(tags).where(eq(tags.id, tagId)); +} + +/** Tag ids assigned to one container. */ +export async function getContainerTagIds(containerName: string, environmentId: number | null): Promise { + const rows = await db.select().from(containerTags) + .where(and(eq(containerTags.containerName, containerName), envClause(containerTags.environmentId, environmentId))); + return rows.map((r) => r.tagId); +} + +/** All container assignments in an environment as a name -> tagId[] map (no N+1). */ +export async function getContainerTagsMap(environmentId: number | null): Promise> { + const rows = await db.select().from(containerTags).where(envClause(containerTags.environmentId, environmentId)); + const map: Record = {}; + for (const r of rows) (map[r.containerName] ??= []).push(r.tagId); + return map; +} + +/** Replace a container's tag assignments. */ +export async function setContainerTagIds(containerName: string, environmentId: number | null, tagIds: number[]): Promise { + await db.delete(containerTags) + .where(and(eq(containerTags.containerName, containerName), envClause(containerTags.environmentId, environmentId))); + const ids = [...new Set(tagIds)]; + if (ids.length) { + await db.insert(containerTags).values(ids.map((tagId) => ({ containerName, environmentId, tagId }))); + } +} + +/** Tag ids assigned to one stack. */ +export async function getStackTagIds(stackName: string, environmentId: number | null): Promise { + const rows = await db.select().from(stackTags) + .where(and(eq(stackTags.stackName, stackName), envClause(stackTags.environmentId, environmentId))); + return rows.map((r) => r.tagId); +} + +/** All stack assignments in an environment as a name -> tagId[] map. */ +export async function getStackTagsMap(environmentId: number | null): Promise> { + const rows = await db.select().from(stackTags).where(envClause(stackTags.environmentId, environmentId)); + const map: Record = {}; + for (const r of rows) (map[r.stackName] ??= []).push(r.tagId); + return map; +} + +/** Replace a stack's tag assignments. */ +export async function setStackTagIds(stackName: string, environmentId: number | null, tagIds: number[]): Promise { + await db.delete(stackTags) + .where(and(eq(stackTags.stackName, stackName), envClause(stackTags.environmentId, environmentId))); + const ids = [...new Set(tagIds)]; + if (ids.length) { + await db.insert(stackTags).values(ids.map((tagId) => ({ stackName, environmentId, tagId }))); + } +} + // ============================================================================= // VULNERABILITY SCAN RESULTS // ============================================================================= diff --git a/src/lib/server/db/drizzle.ts b/src/lib/server/db/drizzle.ts index 2e04126d9..a0cc6285e 100644 --- a/src/lib/server/db/drizzle.ts +++ b/src/lib/server/db/drizzle.ts @@ -926,6 +926,9 @@ export const gitStacks = schemaProxy.gitStacks; export const secretProviders = schemaProxy.secretProviders; export const stackSources = schemaProxy.stackSources; export const containerIconOverrides = schemaProxy.containerIconOverrides; +export const tags = schemaProxy.tags; +export const containerTags = schemaProxy.containerTags; +export const stackTags = schemaProxy.stackTags; export const vulnerabilityScans = schemaProxy.vulnerabilityScans; export const auditLogs = schemaProxy.auditLogs; export const containerEvents = schemaProxy.containerEvents; diff --git a/src/lib/server/db/schema/index.ts b/src/lib/server/db/schema/index.ts index 7337abaf9..7d77a0e66 100644 --- a/src/lib/server/db/schema/index.ts +++ b/src/lib/server/db/schema/index.ts @@ -383,6 +383,44 @@ export const containerIconOverrides = sqliteTable('container_icon_overrides', { containerIconEnvUnique: unique().on(table.containerName, table.environmentId) })); +// User-defined organizational tags for containers and stacks. +// Distinct from Docker labels. The catalog below is GLOBAL (one 'prod'/'infra'/etc +// across the whole instance, unique on name). Assignments (container_tags/stack_tags) +// ARE env-scoped and keyed by the container/stack NAME (stable across recreation), so +// which containers/stacks carry a tag is decided per environment. +export const tags = sqliteTable('tags', { + id: integer('id').primaryKey({ autoIncrement: true }), + name: text('name').notNull(), + color: text('color').notNull().default('slate'), // one of the fixed palette (tags-core.ts) + icon: text('icon'), // optional lucide icon name; null = default tag icon + createdAt: text('created_at').default(sql`CURRENT_TIMESTAMP`) +}, (table) => ({ + // Unique on name. The migration makes the index case-INSENSITIVE (COLLATE NOCASE + // on sqlite, lower(name) on pg) so "Prod" and "prod" are the same tag even under + // a concurrent create; drizzle's DSL can't express that, so it lives in 0016. + tagNameUnique: unique().on(table.name) +})); + +export const containerTags = sqliteTable('container_tags', { + id: integer('id').primaryKey({ autoIncrement: true }), + containerName: text('container_name').notNull(), + environmentId: integer('environment_id').references(() => environments.id, { onDelete: 'cascade' }), + tagId: integer('tag_id').notNull().references(() => tags.id, { onDelete: 'cascade' }), + createdAt: text('created_at').default(sql`CURRENT_TIMESTAMP`) +}, (table) => ({ + containerTagUnique: unique().on(table.containerName, table.environmentId, table.tagId) +})); + +export const stackTags = sqliteTable('stack_tags', { + id: integer('id').primaryKey({ autoIncrement: true }), + stackName: text('stack_name').notNull(), + environmentId: integer('environment_id').references(() => environments.id, { onDelete: 'cascade' }), + tagId: integer('tag_id').notNull().references(() => tags.id, { onDelete: 'cascade' }), + createdAt: text('created_at').default(sql`CURRENT_TIMESTAMP`) +}, (table) => ({ + stackTagUnique: unique().on(table.stackName, table.environmentId, table.tagId) +})); + export const stackEnvironmentVariables = sqliteTable('stack_environment_variables', { id: integer('id').primaryKey({ autoIncrement: true }), stackName: text('stack_name').notNull(), diff --git a/src/lib/server/db/schema/pg-schema.ts b/src/lib/server/db/schema/pg-schema.ts index 021301bd0..3d626d9e8 100644 --- a/src/lib/server/db/schema/pg-schema.ts +++ b/src/lib/server/db/schema/pg-schema.ts @@ -385,6 +385,41 @@ export const containerIconOverrides = pgTable('container_icon_overrides', { containerIconEnvUnique: unique().on(table.containerName, table.environmentId) })); +// User-defined organizational tags for containers and stacks. Distinct +// from Docker labels. GLOBAL tag catalog (unique on name, not env-scoped); assignment +// rows (container_tags/stack_tags) are keyed by name and stay env-scoped. +export const tags = pgTable('tags', { + id: serial('id').primaryKey(), + name: text('name').notNull(), + color: text('color').notNull().default('slate'), + icon: text('icon'), + createdAt: timestamp('created_at', { mode: 'string' }).defaultNow() +}, (table) => ({ + // Case-INSENSITIVE unique on name (lower(name) in the migration) so "Prod" and + // "prod" collide; drizzle's DSL can't express that, so it lives in 0016. + tagNameUnique: unique().on(table.name) +})); + +export const containerTags = pgTable('container_tags', { + id: serial('id').primaryKey(), + containerName: text('container_name').notNull(), + environmentId: integer('environment_id').references(() => environments.id, { onDelete: 'cascade' }), + tagId: integer('tag_id').notNull().references(() => tags.id, { onDelete: 'cascade' }), + createdAt: timestamp('created_at', { mode: 'string' }).defaultNow() +}, (table) => ({ + containerTagUnique: unique().on(table.containerName, table.environmentId, table.tagId) +})); + +export const stackTags = pgTable('stack_tags', { + id: serial('id').primaryKey(), + stackName: text('stack_name').notNull(), + environmentId: integer('environment_id').references(() => environments.id, { onDelete: 'cascade' }), + tagId: integer('tag_id').notNull().references(() => tags.id, { onDelete: 'cascade' }), + createdAt: timestamp('created_at', { mode: 'string' }).defaultNow() +}, (table) => ({ + stackTagUnique: unique().on(table.stackName, table.environmentId, table.tagId) +})); + export const stackEnvironmentVariables = pgTable('stack_environment_variables', { id: serial('id').primaryKey(), stackName: text('stack_name').notNull(), diff --git a/src/lib/server/docker-demux-core.ts b/src/lib/server/docker-demux-core.ts new file mode 100644 index 000000000..e39a39541 --- /dev/null +++ b/src/lib/server/docker-demux-core.ts @@ -0,0 +1,46 @@ +/** + * Pure demultiplexer for a Docker non-TTY exec/attach byte stream. + * + * Each frame is an 8-byte header (stream type in byte 0: 1=stdout, 2=stderr; + * 32-bit big-endian payload size in bytes 4-7) followed by the payload. With + * `separateStreams` the stdout and stderr payloads are returned apart; otherwise + * they are concatenated (stdout first). No imports / no I/O so it is unit-testable. + */ +export function demuxDockerStream( + buffer: Buffer, + options?: { separateStreams?: boolean } +): string | { stdout: string; stderr: string } { + const stdout: string[] = []; + const stderr: string[] = []; + let offset = 0; + + while (offset < buffer.length) { + if (offset + 8 > buffer.length) break; + + const streamType = buffer.readUInt8(offset); + const frameSize = buffer.readUInt32BE(offset + 4); + + if (frameSize === 0 || frameSize > buffer.length - offset - 8) { + // Invalid frame, return raw content with control chars stripped + const raw = buffer.toString('utf-8').replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, ''); + return options?.separateStreams ? { stdout: raw, stderr: '' } : raw; + } + + const payload = buffer.slice(offset + 8, offset + 8 + frameSize).toString('utf-8'); + + if (streamType === 1) { + stdout.push(payload); + } else if (streamType === 2) { + stderr.push(payload); + } else { + stdout.push(payload); // Default to stdout for unknown types + } + + offset += 8 + frameSize; + } + + if (options?.separateStreams) { + return { stdout: stdout.join(''), stderr: stderr.join('') }; + } + return [...stdout, ...stderr].join(''); +} diff --git a/src/lib/server/docker.ts b/src/lib/server/docker.ts index 773244e24..c1daddecd 100644 --- a/src/lib/server/docker.ts +++ b/src/lib/server/docker.ts @@ -16,19 +16,23 @@ import { createHash } from 'node:crypto'; import { pumpWebStreamToWritable } from './stream-pump'; import { toWebReadableStream } from './node-readable-stream'; import { buildImagePruneFilters } from './image-prune-core'; +import { demuxDockerStream } from './docker-demux-core'; import { computeRequestTimeoutMs } from './backups/request-timeout'; import { helperWaitDeadline, helperExitFromState } from './helper-wait-core'; import type { Environment } from './db'; import { getSetting } from './db'; import { getAdditionalVolumeBinds, dedupeVolumesForRecreate } from './mount-dedupe'; import { resolveNanoCpusConflict, resolvePodmanUsernsMode } from './hostconfig-recreate'; +import { expectedEvents, EXPECTED_EVENT_TTL_MS } from './expected-events-core'; +import { decideRespawnOutcome, isExactNameMatch } from './systemd-recreate-core'; // Import-light image parsing shared with the semver layer; re-exported below for callers. import { parseImageReference } from './registry/image-ref'; export { parseImageReference } from './registry/image-ref'; import { rebaseEnvOntoImage, rebaseLabelsOntoImage, rebaseCommand, describeEnvRebase, describeLabelRebase, type ImageEnvLabels } from './container-env-merge'; import { encodeRegistryAuth, fetchRegistryToken, isSafeRegistryHost } from './registry-auth'; +import { resolveRegistryScheme, type StoredRegistryScheme } from './registry-scheme-core'; import { classifyManifest, type ArtifactKind } from './semver/manifest-artifact'; -import { isSystemContainer, classifyEmptyDigestImage, localDigestIsIndexChild } from './scheduler/tasks/update-utils'; +import { isSystemContainer, classifyEmptyDigestImage, localDigestIsIndexChild, indexChildDigests } from './scheduler/tasks/update-utils'; import { deepDiff } from '../utils/diff.js'; import { getInstanceId } from './backups/identity'; import { isOwnedBackupHelper } from './backups/reap-core'; @@ -205,46 +209,6 @@ function detectDockerSocket(): string { const socketPath = detectDockerSocket(); -/** - * Demultiplex Docker stream output (strip 8-byte headers) - * Docker streams have: 1 byte type, 3 bytes padding, 4 bytes size BE, then payload - */ -function demuxDockerStream(buffer: Buffer, options?: { separateStreams?: boolean }): string | { stdout: string; stderr: string } { - const stdout: string[] = []; - const stderr: string[] = []; - let offset = 0; - - while (offset < buffer.length) { - if (offset + 8 > buffer.length) break; - - const streamType = buffer.readUInt8(offset); - const frameSize = buffer.readUInt32BE(offset + 4); - - if (frameSize === 0 || frameSize > buffer.length - offset - 8) { - // Invalid frame, return raw content with control chars stripped - const raw = buffer.toString('utf-8').replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, ''); - return options?.separateStreams ? { stdout: raw, stderr: '' } : raw; - } - - const payload = buffer.slice(offset + 8, offset + 8 + frameSize).toString('utf-8'); - - if (streamType === 1) { - stdout.push(payload); - } else if (streamType === 2) { - stderr.push(payload); - } else { - stdout.push(payload); // Default to stdout for unknown types - } - - offset += 8 + frameSize; - } - - if (options?.separateStreams) { - return { stdout: stdout.join(''), stderr: stderr.join('') }; - } - return [...stdout, ...stderr].join(''); -} - /** * Process Docker stream frames incrementally from a buffer * Returns processed frames and remaining buffer @@ -1884,6 +1848,100 @@ export async function createContainer(options: CreateContainerOptions, envId?: n return { id: result.Id, start: () => startContainer(result.Id, envId) }; } +/** + * Recreate a Podman Quadlet / systemd-managed container by handing the lifecycle to + * systemd instead of doing our own stop/rename/create/start. + * + * The unit's ExecStop removes the container and its Restart= policy respawns it from + * `podman run --replace` on the CURRENT tag (the image already pulled), so a single stop + * is the whole recreate. We then poll for the respawned container to come back under the + * same name, RUNNING, with a new id, and return that id. If it never reaches running + * (no Restart= policy, or a crash-loop on the new image), throw an actionable error + * rather than the misleading rename failure - and never report a broken update as success. + */ +async function recreateSystemdManagedContainer( + opts: { name: string; oldContainerId: string; wasRunning: boolean; unit: string }, + envId: number | null | undefined, + log?: (msg: string) => void +): Promise<{ Id: string }> { + const { name, oldContainerId, wasRunning, unit } = opts; + log?.(`Managed by systemd unit ${unit} - handing the recreate to systemd (Quadlet)`); + + // A stopped Quadlet container does not exist: the unit's ExecStop (podman rm -f) + // already removed it and the unit is inactive. We have only the Podman API (no + // systemctl), so we cannot bring the unit up - a stop would be a no-op and we would + // wait out the timeout for nothing. Fail fast with something the user can act on. + if (!wasRunning) { + throw new Error( + `Cannot update ${name}: it is managed by the systemd unit ${unit} and is not ` + + `running. Start the unit (systemctl start ${unit}) so it comes up on the ` + + `newly pulled image.` + ); + } + + // Stopping is what triggers the unit's ExecStop (podman rm) + Restart respawn. The + // stop/kill/die events are an expected part of the update, not a crash. + expectedEvents.markExpected(oldContainerId, Date.now(), EXPECTED_EVENT_TTL_MS); + log?.('Stopping container (systemd will recreate it on the new image)...'); + try { + await stopContainer(oldContainerId, envId); + } catch { + // A Quadlet stop can race the unit's own teardown; the container may already be + // gone. Not fatal - we verify the respawn below. + } + + // Poll for the unit to bring the container back under the same name, RUNNING, with a + // new id. A container that reappears but never reaches running (crash-loop on a broken + // new image) is a FAILURE on timeout, not a success. + try { + const deadline = Date.now() + SYSTEMD_RESPAWN_TIMEOUT_MS; + for (;;) { + await sleep(SYSTEMD_RESPAWN_POLL_MS); + const found = await findRunningContainerByName(name, envId).catch(() => null); + const outcome = decideRespawnOutcome(found, oldContainerId, Date.now() >= deadline); + if (!outcome.done) continue; + if (outcome.ok) { + log?.(`systemd recreated ${name} (new container ${outcome.id.slice(0, 12)})`); + return { Id: outcome.id }; + } + throw new Error( + `systemd unit ${unit} did not bring ${name} back to a running state after the ` + + `update. The image was pulled; check the unit (a Restart= policy is required, ` + + `and verify the container is not failing to start on the new image).` + ); + } + } finally { + // Clear the suppression on every exit path so a genuine later crash still alarms. + expectedEvents.clear(oldContainerId); + } +} + +/** Find a container by exact name via the daemon's name filter. Returns id + state, or null. */ +async function findRunningContainerByName( + name: string, + envId?: number | null +): Promise<{ Id: string; State: string } | null> { + const filters = JSON.stringify({ name: [`^/?${name}$`] }); + const res = await dockerFetch( + `/containers/json?all=true&filters=${encodeURIComponent(filters)}`, + {}, + envId + ); + if (!res.ok) { + await res.text(); + return null; + } + const list = (await res.json()) as Array<{ Id: string; Names: string[]; State: string }>; + // The name filter is a regex-contains on Podman/Docker; keep only an EXACT name match. + const match = list.find((c) => isExactNameMatch(c.Names, name)); + return match ? { Id: match.Id, State: match.State } : null; +} + +// Generous window: systemd honours RestartSec, and a heavy image can take a while to +// become running even though it is already pulled. +const SYSTEMD_RESPAWN_TIMEOUT_MS = 90_000; +const SYSTEMD_RESPAWN_POLL_MS = 500; +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); /** * Recreate a container using full Config/HostConfig passthrough from inspect data. @@ -1922,6 +1980,23 @@ export async function recreateContainerFromInspect( const oldContainerId = inspectData.Id; const wasRunning = inspectData.State?.Running; + // Podman Quadlet / systemd-managed container: the unit owns the lifecycle. Its + // ExecStop is `podman rm -f`, so the moment we stop the container systemd DELETES it + // and (Restart= policy) respawns a fresh one from the unit's `podman run --replace`, + // which reads the CURRENT tag - i.e. the image we just pulled. Our own + // stop/rename/create/start therefore cannot work: the rename step hits the + // already-removed id ("Failed to rename old container"), and creating our own + // container would collide with systemd's respawn. So hand the recreate to systemd: + // stop, then wait for the unit to bring the container back on the new image. + const systemdUnit = config.Labels?.['PODMAN_SYSTEMD_UNIT']; + if (systemdUnit) { + return await recreateSystemdManagedContainer( + { name, oldContainerId, wasRunning, unit: systemdUnit }, + envId, + log + ); + } + // Detect shared/special network modes where network manipulation must be skipped const networkMode = hostConfig.NetworkMode || ''; const isSharedNetwork = networkMode.startsWith('container:') || @@ -1936,6 +2011,9 @@ export async function recreateContainerFromInspect( // 1. Stop the container if (wasRunning) { log?.('Stopping container...'); + // The stop/kill/die events this triggers are an EXPECTED part of the update, + // not a crash - mark the id so the event handler skips their notifications (#68). + expectedEvents.markExpected(oldContainerId, Date.now(), EXPECTED_EVENT_TTL_MS); await stopContainer(oldContainerId, envId); } @@ -1997,6 +2075,10 @@ export async function recreateContainerFromInspect( if (wasRunning) { await startContainer(oldContainerId, envId).catch(() => {}); } + // The old container is alive again under its real name; its stop/kill were + // no longer "expected" once we chose to keep it, so a later genuine crash + // must alarm - drop the suppression mark (#68). + expectedEvents.clear(oldContainerId); } catch { log?.('Rollback failed'); } @@ -3108,6 +3190,25 @@ export async function findRegistryCredentials(registryHost: string): Promise<{ u } } +/** + * Resolve http vs https for a registry host from the stored registries, so the + * challenge/token request honours a plain-HTTP registry (#1580). Defaults to https. + */ +async function getRegistrySchemeForHost(registryHost: string): Promise<'http' | 'https'> { + try { + const { getRegistries } = await import('./db.js'); + const registries = await getRegistries(); + const stored: StoredRegistryScheme[] = registries.map((reg) => { + const parsed = parseRegistryUrl(reg.url); + return { host: parsed.host, protocol: parsed.protocol, isHub: DOCKER_HUB_HOSTS.has(parsed.host) }; + }); + const requested = parseRegistryUrl(registryHost); + return resolveRegistryScheme(requested.host, stored, DOCKER_HUB_HOSTS.has(requested.host)); + } catch { + return 'https'; + } +} + /** * Get bearer token from registry using challenge-response flow. * This follows the Docker Registry v2 authentication spec: @@ -3122,7 +3223,10 @@ async function getRegistryBearerToken(registry: string, repo: string): Promise = { 'User-Agent': 'Dockhand/1.0', @@ -3695,10 +3802,11 @@ export async function getTagArtifactKind( registry: string, repo: string, tag: string -): Promise<{ kind: ArtifactKind; digest: string | null }> { +): Promise<{ kind: ArtifactKind; digest: string | null; childDigests?: string[] }> { try { if (!isSafeRegistryHost(registry).ok) return { kind: 'image', digest: null }; const token = await getRegistryBearerToken(registry, repo); + const scheme = await getRegistrySchemeForHost(registry); const headers: Record = { 'User-Agent': 'Dockhand/1.0', 'Accept': [ @@ -3710,7 +3818,7 @@ export async function getTagArtifactKind( }; if (token) headers['Authorization'] = token; - const res = await fetch(`https://${registry}/v2/${repo}/manifests/${tag}`, { + const res = await fetch(`${scheme}://${registry}/v2/${repo}/manifests/${tag}`, { method: 'GET', headers, signal: AbortSignal.timeout(8000) @@ -3724,9 +3832,11 @@ export async function getTagArtifactKind( const body = (await res.json().catch(() => null)) as | { mediaType?: string; config?: { mediaType?: string }; manifests?: unknown[] } | null; - return { kind: classifyManifest(body, topMediaType), digest }; + // Per-arch child digests of a multi-arch index, so a same-image check can match + // a host that recorded the child digest in RepoDigests instead of the index (#1367). + return { kind: classifyManifest(body, topMediaType), digest, childDigests: indexChildDigests(body) }; } catch { - return { kind: 'image', digest: null }; + return { kind: 'image', digest: null, childDigests: [] }; } } @@ -3752,6 +3862,7 @@ async function localDigestMatchesRegistryChild( const { registry, repo, tag } = parseImageReference(imageName); if (!isSafeRegistryHost(registry).ok) return false; const token = await getRegistryBearerToken(registry, repo); + const scheme = await getRegistrySchemeForHost(registry); const headers: Record = { 'User-Agent': 'Dockhand/1.0', 'Accept': [ @@ -3761,7 +3872,7 @@ async function localDigestMatchesRegistryChild( }; if (token) headers['Authorization'] = token; - const response = await fetch(`https://${registry}/v2/${repo}/manifests/${tag}`, { + const response = await fetch(`${scheme}://${registry}/v2/${repo}/manifests/${tag}`, { method: 'GET', headers, signal: AbortSignal.timeout(8000) @@ -3785,6 +3896,9 @@ export interface ImageUpdateCheckResult { isLocalImage?: boolean; /** Error message if check failed */ error?: string; + /** The running image's RepoDigests (sha256:...), for the semver check to suppress + * a newer-version tag that resolves to the same digest already installed (#1572). */ + localDigests?: string[]; } /** @@ -3866,17 +3980,20 @@ export async function checkImageUpdateAvailable( const registryDigest = await getRegistryManifestDigest(imageName); if (!registryDigest) { - // Registry unreachable or image not found - can't determine update status + // Registry unreachable or image not found - can't determine update status. + // Still return localDigests: the semver check may run on the API path + // regardless of this error and needs them to suppress a same-digest tag. return { hasUpdate: false, currentDigest: currentRepoDigests[0], + localDigests, error: 'Could not query registry' }; } // Check if registry digest matches ANY of the local digests if (localDigests.includes(registryDigest)) { - return { hasUpdate: false, currentDigest: currentRepoDigests[0] }; + return { hasUpdate: false, currentDigest: currentRepoDigests[0], localDigests }; } // The HEAD digest (always the manifest-list/index digest) didn't match. Before @@ -3884,13 +4001,14 @@ export async function checkImageUpdateAvailable( // child digest won't equal the index digest even when the image is current // (#1367). Best-effort GET of the index; on any failure hasUpdate stays true. if (await localDigestMatchesRegistryChild(imageName, localDigests)) { - return { hasUpdate: false, currentDigest: currentRepoDigests[0] }; + return { hasUpdate: false, currentDigest: currentRepoDigests[0], localDigests }; } return { hasUpdate: true, currentDigest: currentRepoDigests[0], - registryDigest + registryDigest, + localDigests }; } catch (e: any) { return { hasUpdate: false, error: e.message }; @@ -4832,6 +4950,59 @@ export async function execInContainer( return output; } +/** + * One-shot exec that returns the result instead of throwing on a non-zero exit - + * argv in, { stdout, stderr, exitCode } out. Separate from execInContainer, whose + * throw-on-failure contract many internal callers rely on. + */ +export async function runExecInContainer( + containerId: string, + cmd: string[], + envId?: number | null, + options?: { user?: string | null; workingDir?: string | null } +): Promise<{ stdout: string; stderr: string; exitCode: number }> { + const execBody: any = { + Cmd: cmd, + AttachStdout: true, + AttachStderr: true, + Tty: false + }; + if (options?.user) execBody.User = options.user; + if (options?.workingDir) execBody.WorkingDir = options.workingDir; + + const execCreate = await dockerJsonRequest<{ Id: string }>( + `/containers/${containerId}/exec`, + { method: 'POST', body: JSON.stringify(execBody) }, + envId + ); + + const response = await dockerFetch( + `/exec/${execCreate.Id}/start`, + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ Detach: false, Tty: false }) + }, + envId + ); + + if (!response.ok) await throwDockerError(response); + + const buffer = Buffer.from(await response.arrayBuffer()); + const { stdout, stderr } = demuxDockerStream(buffer, { separateStreams: true }) as { + stdout: string; + stderr: string; + }; + + const execInfo = await dockerJsonRequest<{ ExitCode: number | null }>( + `/exec/${execCreate.Id}/json`, + {}, + envId + ); + + return { stdout, stderr, exitCode: execInfo.ExitCode ?? 0 }; +} + // Get Docker events as a stream (for SSE) // For streaming mode: call with just filters // For polling mode: call with since and until to get a finite window of events @@ -5390,7 +5561,7 @@ async function streamEdgeStderr( } // Extract stdout from a buffer, with raw fallback if frame parsing returns nothing. -// Mirrors demuxDockerStream's fallback (line ~202-205) for non-multiplexed Docker output. +// Mirrors demuxDockerStream's invalid-frame fallback in docker-demux-core.ts for non-multiplexed Docker output. function extractStdoutFromBuffer(buffer: Buffer): string { const result = processStreamFrames(buffer, undefined, undefined); @@ -6049,11 +6220,28 @@ export async function chmodContainerPath( throw new Error('Invalid chmod mode'); } - // Build command - const cmd = recursive ? ['chmod', '-R', mode, safePath] : ['chmod', mode, safePath]; + // Build command. `--` stops chmod reading a path that begins with `-` as an option. + const cmd = recursive ? ['chmod', '-R', mode, '--', safePath] : ['chmod', mode, '--', safePath]; await execInContainer(containerId, cmd, envId); } +/** + * chown a path in a container. `owner` must already be validated + * (parseChownSpec) - a `user`, `user:group`, `uid` or `uid:gid` token. + */ +export async function chownContainerPath( + containerId: string, + path: string, + owner: string, + recursive: boolean = false, + envId?: number | null +): Promise { + const safePath = path.replace(/[;&|`$(){}[\]<>'"\\]/g, ''); + // `--` stops chown reading a path that begins with `-` as an option. + const cmd = recursive ? ['chown', '-R', owner, '--', safePath] : ['chown', owner, '--', safePath]; + await execInContainer(containerId, cmd, envId, 'root'); +} + // Volume browsing and export helpers const VOLUME_HELPER_IMAGE = 'busybox:latest'; diff --git a/src/lib/server/expected-events-core.ts b/src/lib/server/expected-events-core.ts new file mode 100644 index 000000000..3ebec3f67 --- /dev/null +++ b/src/lib/server/expected-events-core.ts @@ -0,0 +1,75 @@ +/** + * Suppresses the die/kill/stop notifications that an auto-update deliberately + * causes. When Dockhand recreates a container to update its image, it stops the + * old container - Docker then emits kill/die/stop events that are EXPECTED, not a + * crash, but they used to notify the user as "Container died" (#68). + * + * A container id is marked "expected" for a short window before the update stops + * it; the event handler checks this and skips the notification for the noisy + * lifecycle actions only. A genuine crash AFTER the window still alarms. Pure, + * in-memory, unit-tested - no timers, expiry is checked lazily against `now`. + */ + +/** Actions an auto-update legitimately triggers, whose notification is noise. */ +const SUPPRESSED_ACTIONS = new Set(['die', 'kill', 'stop']); + +export class ExpectedEventsTracker { + // containerId -> expiry epoch-ms. Kept small: entries are dropped on check. + private readonly expiry = new Map(); + + /** Mark a container's imminent stop/kill as expected for `ttlMs` from `now`. */ + markExpected(containerId: string, now: number, ttlMs: number): void { + if (!containerId) return; + this.expiry.set(containerId, now + ttlMs); + } + + /** + * True when this action for this container should NOT notify: it is a + * die/kill/stop for a container marked expected and still within its window. + * A non-suppressed action (start, oom, health) always returns false, so those + * still notify even mid-update. Expired/unknown ids return false. + */ + shouldSuppress(containerId: string, action: string, now: number): boolean { + // Opportunistically drop everything already past its window so happy-path + // entries (whose id never emits another event to lazily expire them) can't + // accumulate for the process lifetime. Cheap: the map holds at most a handful + // of in-flight updates at once. + this.prune(now); + if (!SUPPRESSED_ACTIONS.has(action)) return false; + const exp = this.expiry.get(containerId); + if (exp === undefined) return false; + // A single update legitimately emits die AND kill AND stop for the same id, so + // do NOT delete on a suppressed hit (that would let the 2nd/3rd through); the + // prune above reclaims the entry once its window passes. + return now <= exp; + } + + /** Clear a container's mark, e.g. when an update rolls back and restarts it so a + * later genuine crash of that restored container is NOT wrongly suppressed. */ + clear(containerId: string): void { + this.expiry.delete(containerId); + } + + /** Drop all entries whose window has passed (called opportunistically). */ + prune(now: number): void { + for (const [id, exp] of this.expiry) { + if (now > exp) this.expiry.delete(id); + } + } + + /** Test/introspection helper. */ + size(): number { + return this.expiry.size; + } +} + +/** How long after marking a container its expected stop/kill stays suppressed. */ +export const EXPECTED_EVENT_TTL_MS = 30_000; + +/** + * Process-wide shared tracker. docker.ts marks a container before an auto-update + * stops it; subprocess-manager.ts checks it before notifying. Kept in this + * import-light module so neither of those (which don't import each other) creates + * a cycle - same pattern as token-cache.ts. + */ +export const expectedEvents = new ExpectedEventsTracker(); diff --git a/src/lib/server/registry-scheme-core.ts b/src/lib/server/registry-scheme-core.ts new file mode 100644 index 000000000..659186ec0 --- /dev/null +++ b/src/lib/server/registry-scheme-core.ts @@ -0,0 +1,35 @@ +// Resolve which URL scheme (http vs https) a registry host was CONFIGURED with, so the +// bearer-token / challenge request honours a plain-HTTP registry instead of always using +// HTTPS (#1580). The browse/catalog path already honours the stored scheme; this brings +// the update-check token path in line. Pure so it is unit-testable without the DB. + +export interface StoredRegistryScheme { + /** bare host[:port], no scheme, no path (e.g. "10.10.10.10:3000") */ + host: string; + /** 'http' | 'https' as stored */ + protocol: string; + /** true if this stored entry is a Docker Hub variant */ + isHub: boolean; +} + +/** + * Given the requested registry host and the schemes of the configured registries, + * return 'http' or 'https' to use for that host. A configured entry whose host matches + * wins; a Docker Hub request matches any stored Hub entry. Falls back to 'https' when + * nothing matches (the safe default, and what registries on the public internet use). + */ +export function resolveRegistryScheme( + requestedHost: string, + stored: StoredRegistryScheme[], + requestedIsHub: boolean +): 'http' | 'https' { + for (const s of stored) { + if (s.host === requestedHost) return s.protocol === 'http' ? 'http' : 'https'; + } + if (requestedIsHub) { + for (const s of stored) { + if (s.isHub) return s.protocol === 'http' ? 'http' : 'https'; + } + } + return 'https'; +} diff --git a/src/lib/server/scanner-registry-core.ts b/src/lib/server/scanner-registry-core.ts new file mode 100644 index 000000000..f6cfdfa4c --- /dev/null +++ b/src/lib/server/scanner-registry-core.ts @@ -0,0 +1,111 @@ +/** + * Pure helpers for the registry-scan fallback (no docker/db imports, unit-tested). + * + * On a containerd/OCI image store, `docker save` can silently emit a tar whose + * index references layer blobs that are not in the archive, so grype/trivy fail + * with "blob not found in tar". The fix is to re-scan straight from the registry + * (grype `registry:`, trivy without the daemon socket), which bypasses the + * broken daemon export. These helpers classify that failure and shape the + * registry-mode command + auth env. + */ + +export type ScannerType = 'grype' | 'trivy'; + +/** + * True when a scanner's output/error is the containerd daemon-export blob bug, + * i.e. the daemon handed the scanner an incomplete tar. Matched by the stable + * substrings both scanners print (grype via stereoscope, trivy via its analyzer). + * Deliberately narrow: it must NOT match an auth/network failure, so the fallback + * only fires for the export bug. + */ +export function isDaemonExportFailure(output: string | null | undefined): boolean { + if (!output) return false; + const s = output.toLowerCase(); + return ( + s.includes('unable to provide image from tarball') || // grype/stereoscope + (s.includes('unable to get uncompressed layer') && s.includes('failed to analyze layer')) || // trivy + (s.includes('does not exist') && s.includes('blobs/sha256/')) // "file blobs/sha256/... does not exist" + ); +} + +/** + * Rewrite a daemon-mode scanner command into a registry-mode one for the same image. + * grype needs the source prefix `registry:`; trivy scans the registry ref + * as-is once the docker socket is absent, so only the image token needs to be the + * plain ref (it already is). The image token is identified by exact match against + * `image` (parseCliArgs substitutes {image} with the ref verbatim). + */ +export function toRegistryScanCmd(scannerType: ScannerType, cmd: string[], image: string): string[] { + return cmd.map((tok) => { + if (tok !== image) return tok; + return scannerType === 'grype' ? `registry:${image}` : image; + }); +} + +/** + * Registry credentials as scanner env vars. grype reads GRYPE_REGISTRY_AUTH_*; + * trivy reads TRIVY_USERNAME/TRIVY_PASSWORD. `authority` is the registry host so + * grype scopes the credential to it. Returns [] when creds is null (public image, + * anonymous access - same as before this fix). + */ +export function registryAuthEnv( + scannerType: ScannerType, + creds: { username: string; password: string } | null, + authority?: string, +): string[] { + if (!creds) return []; + if (scannerType === 'grype') { + const env = [ + `GRYPE_REGISTRY_AUTH_USERNAME=${creds.username}`, + `GRYPE_REGISTRY_AUTH_PASSWORD=${creds.password}`, + ]; + if (authority) env.push(`GRYPE_REGISTRY_AUTH_AUTHORITY=${authority}`); + return env; + } + return [ + `TRIVY_USERNAME=${creds.username}`, + `TRIVY_PASSWORD=${creds.password}`, + ]; +} + +/** + * Per-environment memory of "this daemon's image store loses blobs on export, so + * skip the daemon path and scan straight from the registry". Keyed by the scan's + * environment (envId, or the 'local' sentinel). Sticky for the process lifetime: + * once a blob-export failure is seen for an env, every later scan on that env goes + * registry-first, avoiding the ~15-50s wasted on a doomed `docker save`. Reset on + * Dockhand restart so a fixed store returns to the fast daemon path automatically. + * In-memory only - no DB, no migration. + */ +export class RegistryFallbackMemory { + private readonly envs = new Set(); + private key(envId: number | null | undefined): string { + return envId == null ? 'local' : String(envId); + } + /** True if this env is known-broken and should scan registry-first. */ + prefersRegistry(envId: number | null | undefined): boolean { + return this.envs.has(this.key(envId)); + } + /** Record that this env's daemon export is broken (blob-loss seen). */ + markBroken(envId: number | null | undefined): void { + this.envs.add(this.key(envId)); + } + /** Test/reset hook. */ + clear(): void { + this.envs.clear(); + } +} + +/** + * The registry host (authority) of an image ref, or null for an implicit-Docker-Hub + * ref (no host component). Used to scope grype's registry auth. A host is the first + * path segment only when it contains a '.' or ':' (or is 'localhost') - the Docker + * ref grammar for distinguishing a registry from a Docker Hub org. + */ +export function imageRegistryAuthority(image: string): string | null { + const firstSlash = image.indexOf('/'); + if (firstSlash === -1) return null; // e.g. "alpine:latest" -> Docker Hub + const head = image.slice(0, firstSlash); + if (head === 'localhost' || head.includes('.') || head.includes(':')) return head; + return null; // e.g. "library/alpine" -> Docker Hub org, not a registry host +} diff --git a/src/lib/server/scanner.ts b/src/lib/server/scanner.ts index 56364e8ec..027a7e616 100644 --- a/src/lib/server/scanner.ts +++ b/src/lib/server/scanner.ts @@ -12,8 +12,17 @@ import { runContainerWithStreaming, inspectImage, checkImageUpdateAvailable, - getNegotiatedApiVersion + getNegotiatedApiVersion, + findRegistryCredentials, + parseImageReference } from './docker'; +import { + isDaemonExportFailure, + toRegistryScanCmd, + registryAuthEnv, + imageRegistryAuthority, + RegistryFallbackMemory +} from './scanner-registry-core'; import { getEnvironment, getEnvSetting, getSetting } from './db'; import { sendEventNotification } from './notifications'; import { detectRemoteSocketPath } from './scanner-socket-detect'; @@ -118,6 +127,11 @@ async function withScannerLock(scannerType: string, fn: () => Promise): Pr // Key: "{scannerType}:{imageName}", Value: Promise that resolves to the scan result const inProgressScans = new Map>(); +// Per-env memory of a broken daemon image store (blob-loss on `docker save`), so +// later scans on that env go registry-first instead of retrying the doomed daemon +// export every time. Process-lifetime only; resets on restart (#1569/#1350). +const registryFallback = new RegistryFallbackMemory(); + /** Scanner queue depth — for the metrics endpoint. `inProgress` = distinct * image scans running/deduped; `locked` = scanner types holding the serial lock. */ export function getScannerStats(): { inProgress: number; locked: number } { @@ -664,7 +678,10 @@ async function runScannerContainer( } } -// Internal implementation of scanner container run +// Internal implementation of scanner container run. Handles the daemon-export +// blob bug (#1569/#1350): if this env is already known-broken, go registry-first; +// otherwise try the daemon path and, on a blob-export failure, remember the env +// and retry straight from the registry. async function runScannerContainerImpl( scannerImage: string, scannerType: 'grype' | 'trivy', @@ -673,10 +690,31 @@ async function runScannerContainerImpl( envId?: number, onOutput?: (line: string) => void ): Promise { - // Serialize scans of the same type to avoid DB lock conflicts and re-downloads - return withScannerLock(scannerType, () => - runScannerContainerCore(scannerImage, scannerType, imageName, cmd, envId, onOutput) - ); + const run = (registryMode: boolean) => + // Serialize scans of the same type to avoid DB lock conflicts and re-downloads + withScannerLock(scannerType, () => + runScannerContainerCore(scannerImage, scannerType, imageName, cmd, envId, onOutput, registryMode) + ); + + // This env's store already lost blobs on a prior scan -> skip the doomed daemon + // export and scan the registry directly. + if (registryFallback.prefersRegistry(envId)) { + console.log(`[Scanner] ${scannerType}: env ${envId ?? 'local'} known to break daemon export - scanning registry directly`); + return run(true); + } + + try { + return await run(false); + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + if (!isDaemonExportFailure(msg)) throw error; + // The daemon handed the scanner an incomplete tar (containerd/OCI store blob + // loss). Remember this env and retry from the registry. + console.warn(`[Scanner] ${scannerType}: daemon export produced an incomplete image for ${imageName}; retrying from the registry`); + onOutput?.(`Daemon image export was incomplete; retrying scan from the registry...`); + registryFallback.markBroken(envId); + return run(true); + } } async function runScannerContainerCore( @@ -685,9 +723,10 @@ async function runScannerContainerCore( imageName: string, cmd: string[], envId?: number, - onOutput?: (line: string) => void + onOutput?: (line: string) => void, + registryMode?: boolean ): Promise { - console.log(`[Scanner] Starting ${scannerType} scan for image: ${imageName}, envId: ${envId ?? 'local'}`); + console.log(`[Scanner] Starting ${scannerType} scan for image: ${imageName}, envId: ${envId ?? 'local'}${registryMode ? ' (registry mode)' : ''}`); // Always use the base cache path — serial lock prevents concurrent conflicts const basePath = scannerType === 'grype' ? '/cache/grype' : '/cache/trivy'; @@ -776,15 +815,33 @@ async function runScannerContainerCore( console.log(`[Scanner] Standard mode - using volume: ${volumeName}`); } - // Build binds — only include socket mount when using socket mode + // Build binds — only include socket mount when using socket mode. + // In registry mode the scanner pulls straight from the registry, so the daemon + // socket is deliberately NOT mounted (that is the whole point - it bypasses the + // broken `docker save`). const binds: string[] = []; - if (hostSocketPath) { + if (hostSocketPath && !registryMode) { binds.push(`${hostSocketPath}:/var/run/docker.sock:ro`); } binds.push(cacheBind); console.log(`[Scanner] Container bind mounts: ${JSON.stringify(binds)}`); + // Registry mode: rewrite the command to scan the registry ref (grype needs a + // `registry:` source prefix; trivy scans the ref once no socket is present) and + // attach credentials for the image's registry from the configured registries. + // The scanner now reads from the registry instead of the local daemon, so it + // needs outbound reachability to the registry. On a hawser env the scanner runs + // on the remote host with default networking; if that registry is internal-only + // and was previously reachable only via the daemon, the registry scan can't reach + // it. Surface that so a split-network user knows why. + if (registryMode) { + cmd = toRegistryScanCmd(scannerType, cmd, imageName); + if (isHawser) { + console.warn(`[Scanner] Registry-mode fallback on a remote (hawser) env - the scanner container must be able to reach the registry from the remote host's default network.`); + } + } + // Environment variables to ensure scanners use the correct cache path const envVars = scannerType === 'grype' ? [`GRYPE_DB_CACHE_DIR=${dbPath}`] @@ -812,11 +869,31 @@ async function runScannerContainerCore( } } - // In TCP mode, pass DOCKER_HOST so scanner connects to Docker via TCP - if (scannerDockerHost) { + // In TCP mode, pass DOCKER_HOST so scanner connects to Docker via TCP. + // Not in registry mode - there is no daemon connection to make. + if (scannerDockerHost && !registryMode) { envVars.push(`DOCKER_HOST=${scannerDockerHost}`); } + // Registry mode: attach credentials for the image's registry so a private + // image (e.g. a self-hosted ZOT) authenticates. Public images match nothing + // and scan anonymously, exactly as before this fix. + if (registryMode) { + // findRegistryCredentials matches on the registry HOST, not the full ref, so + // resolve the registry the same way image pulls do (parseImageReference), not + // by passing the tagged image name (which never matches a stored org path). + const registry = parseImageReference(imageName).registry; + const authority = imageRegistryAuthority(imageName); + const creds = await findRegistryCredentials(registry); + const authEnv = registryAuthEnv(scannerType, creds, authority ?? undefined); + if (authEnv.length > 0) { + envVars.push(...authEnv); + console.log(`[Scanner] Registry mode - using stored credentials for ${registry}`); + } else { + console.log(`[Scanner] Registry mode - no stored credentials for ${registry}, anonymous`); + } + } + // Apply user-configured overrides on top of auto-detection (#1219). // Empty user settings → resolver returns the auto-detected values unchanged. const userScannerSettings = await getGlobalScannerDefaults(); diff --git a/src/lib/server/scheduler/tasks/env-update-check.ts b/src/lib/server/scheduler/tasks/env-update-check.ts index 05da2c4e4..f8f79fb04 100644 --- a/src/lib/server/scheduler/tasks/env-update-check.ts +++ b/src/lib/server/scheduler/tasks/env-update-check.ts @@ -228,7 +228,7 @@ export async function runEnvUpdateCheckJob( // A `dockhand.version.pattern` label lets a container teach the check // how to read its own non-standard tags (CalVer+hash, etc.). const versionPattern = getVersionPatternOverride(inspectData.Config?.Labels); - const newer = await checkNewerVersion(imageName, { ...semverOptions, versionPattern }, getTagArtifactKind).catch(() => null); + const newer = await checkNewerVersion(imageName, { ...semverOptions, versionPattern }, getTagArtifactKind, result.localDigests ?? []).catch(() => null); if (newer) { semverByContainer.set(container.id, newer); await log(` NEWER VERSION: ${newer.tag} (${newer.bump})`); diff --git a/src/lib/server/semver/check.ts b/src/lib/server/semver/check.ts index ecc0f76af..7a5bbf2e0 100644 --- a/src/lib/server/semver/check.ts +++ b/src/lib/server/semver/check.ts @@ -6,7 +6,7 @@ import { parseImageReference } from '../registry/image-ref'; import { parseTag } from './tag-parser'; import { listVersionTags } from './tag-source'; -import { findNewerVersionTag, findNewerImageTag, type FindNewerOptions, type NewerVersion } from './find-newer'; +import { findNewerVersionTag, findNewerImageTag, isRedundantNewerVersion, type FindNewerOptions, type NewerVersion } from './find-newer'; import type { ArtifactKind } from './manifest-artifact'; /** Probe a single tag's artifact kind + manifest digest. Injected so check.ts stays unit-testable. */ @@ -14,7 +14,7 @@ export type TagKindProbe = ( registry: string, repo: string, tag: string -) => Promise<{ kind: ArtifactKind; digest: string | null }>; +) => Promise<{ kind: ArtifactKind; digest: string | null; childDigests?: string[] }>; /** * Returns the newer-version suggestion for `imageRef`, or null when the current @@ -30,7 +30,8 @@ export type TagKindProbe = ( export async function checkNewerVersion( imageRef: string, options: FindNewerOptions = {}, - probeTagKind?: TagKindProbe + probeTagKind?: TagKindProbe, + currentImageDigests: readonly (string | null | undefined)[] = [] ): Promise { const { registry, repo, tag } = parseImageReference(imageRef); @@ -48,7 +49,12 @@ export async function checkNewerVersion( tags, async (candidate) => { try { - const { kind, digest } = await probeTagKind(registry, repo, candidate); + const { kind, digest, childDigests } = await probeTagKind(registry, repo, candidate); + // A more specific tag (12.3.3) that resolves to the SAME image the + // running container already has is not a real update - and nothing higher + // exists, so stop rather than drop to a lower patch (#1572). Matches the + // index digest or a per-arch child digest (RepoDigests can hold either). + if (isRedundantNewerVersion(digest, currentImageDigests, childDigests)) return { ok: false, redundant: true }; return { ok: kind === 'image', digest }; } catch { return { ok: true }; // fail-open: never hide a real update on a probe error. diff --git a/src/lib/server/semver/find-newer.ts b/src/lib/server/semver/find-newer.ts index d8bc671b5..b4986f5c1 100644 --- a/src/lib/server/semver/find-newer.ts +++ b/src/lib/server/semver/find-newer.ts @@ -44,6 +44,29 @@ export interface NewerVersion { digest?: string; } +/** + * A newer-version suggestion is REDUNDANT when the candidate tag resolves to the + * same image the running container already has - i.e. a more specific tag + * (`12.3.3`) pointing at the exact image a broader pinned tag (`12.3`) already + * runs. Reporting it is a false-positive update (#1572). + * + * Matches in BOTH digest shapes, because a `docker pull` may record either the + * multi-arch INDEX digest or just the PER-ARCH CHILD digest in RepoDigests (#1367): + * the running image's digests are compared against the candidate's index digest AND + * its per-arch child digests. Returns false when there is nothing to compare (no + * candidate digest / no local digests) so a real update is never hidden. + */ +export function isRedundantNewerVersion( + candidateDigest: string | null | undefined, + currentImageDigests: readonly (string | null | undefined)[], + candidateChildDigests: readonly (string | null | undefined)[] = [] +): boolean { + const local = new Set(currentImageDigests.filter((d): d is string => !!d)); + if (local.size === 0) return false; + if (candidateDigest && local.has(candidateDigest)) return true; + return candidateChildDigests.some((d) => !!d && local.has(d)); +} + /** Which segment first differs decides the bump: [0]=major, [1]=minor, else patch. */ export function classifyBump(current: ParsedTag, candidate: ParsedTag): VersionBump { if ((candidate.parts[0] ?? 0) !== (current.parts[0] ?? 0)) return 'major'; @@ -141,7 +164,7 @@ export function findNewerVersionTag( export async function findNewerImageTag( currentTag: string, allTags: string[], - probe: (tag: string) => Promise<{ ok: boolean; digest?: string | null }>, + probe: (tag: string) => Promise<{ ok: boolean; digest?: string | null; redundant?: boolean }>, options: FindNewerOptions = {}, maxSkips = 5 ): Promise { @@ -150,8 +173,12 @@ export async function findNewerImageTag( const pool = excluded.size ? allTags.filter((t) => !excluded.has(t)) : allTags; const newer = findNewerVersionTag(currentTag, pool, options); if (!newer) return null; - const { ok, digest } = await probe(newer.tag); + const { ok, digest, redundant } = await probe(newer.tag); if (ok) return digest ? { ...newer, digest } : newer; + // The highest newer tag resolves to the image already running (a more specific + // tag of the same digest, e.g. 12.3 running 12.3.3). There is nothing newer, and + // dropping to a LOWER patch would be a downgrade - stop, don't search below it. + if (redundant) return null; excluded.add(newer.tag); } return null; diff --git a/src/lib/server/stack-scanner.ts b/src/lib/server/stack-scanner.ts index 4e78e882b..cd9272f90 100644 --- a/src/lib/server/stack-scanner.ts +++ b/src/lib/server/stack-scanner.ts @@ -11,12 +11,11 @@ import yaml from 'js-yaml'; import { getExternalStackPaths, getStackSources, upsertStackSource, type StackSourceType } from './db'; import { DockerConnectionError } from './docker'; import { normalizeStackName } from '$lib/utils/stack-name'; +import { shouldSkipScanDir } from '$lib/utils/scan-skip'; // Compose file patterns to detect (in order of priority - prefer new style first) const COMPOSE_PATTERNS = ['compose.yaml', 'compose.yml', 'docker-compose.yml', 'docker-compose.yaml']; -// Directories to skip during scanning -const SKIP_DIRECTORIES = ['.git', 'node_modules', '.docker', '__pycache__', '.venv', 'venv']; // Maximum recursion depth to prevent runaway scanning const MAX_DEPTH = 5; @@ -149,8 +148,8 @@ async function scanPath(basePath: string): Promise<{ stacks: DiscoveredStack[]; const entryPath = join(currentPath, entry.name); if (entry.isDirectory()) { - // Skip excluded directories - if (SKIP_DIRECTORIES.includes(entry.name)) continue; + // Skip excluded and hidden (dot) directories (#1251). + if (shouldSkipScanDir(entry.name)) continue; // Skip if we already found a compose file here if (foundStackDirs.has(entryPath)) continue; diff --git a/src/lib/server/stacks.ts b/src/lib/server/stacks.ts index 3906965a7..24800f157 100644 --- a/src/lib/server/stacks.ts +++ b/src/lib/server/stacks.ts @@ -2521,9 +2521,11 @@ export async function startStack( const containers = await getStackContainers(stackName, envId); const operation = containers.length > 0 ? 'start' : 'up'; - if (operation === 'up') { - await applyProviderSecretsToComposeResult(result, stackName, envId, `[Stack:${stackName}]`); - } + // Resolve secret-provider values for BOTH operations: `docker compose start` + // parses and interpolates the compose file too, so a stack with required + // provider secrets (${VAR:?required}) fails to start without them - e.g. the + // post-backup restart of a stopped stack (#1579). + await applyProviderSecretsToComposeResult(result, stackName, envId, `[Stack:${stackName}]`); const startResult = await executeComposeCommand( operation, @@ -2561,6 +2563,11 @@ export async function stopStack( // sourceType is plumbed through from requireComposeFile to avoid a redundant DB lookup. const isGitStack = result.sourceType === 'git'; + // `docker compose stop` interpolates the compose file too, so a stack with required + // provider secrets (${VAR:?required}) fails to stop without them - e.g. the + // stop-during-backup path (#1579). + await applyProviderSecretsToComposeResult(result, stackName, envId, `[Stack:${stackName}]`); + const composeResult = await executeComposeCommand( 'stop', { stackName, envId, workingDir: result.stackDir, composePath: result.composePath, envPath: result.envPath, useOverrideFile: isGitStack, stackFiles: await lifecycleStackFiles(result.stackDir) }, @@ -2613,10 +2620,14 @@ export async function restartStack( let composeResult: StackOperationResult; + // Resolve secret-provider values up front: every restart mode ends in a compose + // command (up/start/restart) that interpolates the compose file, so a stack with + // required provider secrets (${VAR:?required}) fails without them (#1579). + await applyProviderSecretsToComposeResult(result, stackName, envId, `[Stack:${stackName}]`); + if (mode === 'recreate') { // Stop first, then bring up with --force-recreate to ensure new container IDs await executeComposeCommand('stop', opts, result.content!, result.nonSecretVars, result.secretVars, onLine); - await applyProviderSecretsToComposeResult(result, stackName, envId, `[Stack:${stackName}]`); composeResult = await executeComposeCommand('up', { ...opts, forceRecreate: true }, result.content!, result.nonSecretVars, result.secretVars, onLine); } else if (mode === 'ordered') { // Stop everything, then start in depends_on order (compose start honors the @@ -2654,6 +2665,11 @@ export async function downStack( // sourceType is plumbed through from requireComposeFile to avoid a redundant DB lookup. const isGitStack = result.sourceType === 'git'; + // `docker compose down` interpolates the compose file too, so a stack with required + // provider secrets (${VAR:?required}) fails to come down without them (#1579). + // bestEffort: an unreachable provider must not block tearing a stack down. + await applyProviderSecretsToComposeResult(result, stackName, envId, `[Stack:${stackName}]`, true); + const composeResult = await executeComposeCommand( 'down', { stackName, envId, removeVolumes, workingDir: result.stackDir, composePath: result.composePath, envPath: result.envPath, useOverrideFile: isGitStack, stackFiles: await lifecycleStackFiles(result.stackDir) }, @@ -2754,8 +2770,22 @@ export async function removeStack( // If compose file exists, run docker compose down first if (composeResult.success) { - const envVars = await getNonSecretEnvVarsAsRecord(stackName, envId); - const secretVars = await getSecretEnvVarsAsRecord(stackName, envId); + // `docker compose down` interpolates the compose file, so a stack with + // required provider secrets (${VAR:?required}) needs them resolved to come + // down (#1579). bestEffort: an unreachable provider must not block removal. + // suggestedEnvPath covers custom-path stacks whose stored envPath is null but + // have a real sibling .env (the selector/refs may live only there). + const resolved = await resolveProviderVarsBestEffort( + stackName, + envId, + await getNonSecretEnvVarsAsRecord(stackName, envId), + await getSecretEnvVarsAsRecord(stackName, envId), + composeResult.envPath ?? composeResult.suggestedEnvPath, + `[Stack:${stackName}]`, + true + ); + const envVars = resolved.nonSecretVars; + const secretVars = resolved.secretVars; // Stack removal cleanup (#1162): the agent deletes ONLY what Dockhand // explicitly lists. The list is the local staging dir contents — exactly @@ -3733,6 +3763,49 @@ async function resolveProviderEnvVars( return { dbNonSecretVars, secretVars, injectedProviderKeys: injectedProviderKeys() }; } +/** + * Resolve the bound provider's secrets over a raw (nonSecretVars, secretVars) pair. + * Returns the merged vars. bestEffort=true (tear-down paths) logs and returns the + * inputs unchanged if the provider is unreachable, so a down/remove is never blocked + * by a dead provider. The single source of truth both the compose-result helper and + * removeStack use, so envPath derivation cannot drift between them. + */ +async function resolveProviderVarsBestEffort( + stackName: string, + envId: number | null | undefined, + nonSecretVars: Record, + secretVars: Record, + envPath: string | null | undefined, + logPrefix: string, + bestEffort = false +): Promise<{ nonSecretVars: Record; secretVars: Record }> { + let envFileContent: string | undefined; + if (envPath && existsSync(envPath)) { + try { + envFileContent = readFileSync(envPath, 'utf-8'); + } catch (err) { + console.warn(`${logPrefix} Failed to read .env at ${envPath}:`, err); + } + } + + try { + const source = await getStackSource(stackName, envId ?? undefined); + const resolved = await resolveProviderEnvVars( + { ...nonSecretVars }, + { ...secretVars }, + logPrefix, + source?.secretProviderId, + envFileContent, + { stackName, envId: envId ?? undefined } + ); + return { nonSecretVars: resolved.dbNonSecretVars, secretVars: resolved.secretVars }; + } catch (err) { + if (!bestEffort) throw err; + console.warn(`${logPrefix} Provider secret resolution failed, proceeding without provider secrets:`, err); + return { nonSecretVars, secretVars }; + } +} + /** * Resolve the bound provider's secrets for a compose result produced by * requireComposeFile(). Mutates result.secretVars / result.nonSecretVars in @@ -3743,30 +3816,19 @@ async function applyProviderSecretsToComposeResult( result: RequireComposeResult, stackName: string, envId: number | null | undefined, - logPrefix: string + logPrefix: string, + // Tear-down paths (down/remove) pass bestEffort: a provider that is unreachable + // must not block bringing a stack down, so a resolve error is logged and the + // compose command proceeds with whatever vars are on disk/DB. + bestEffort = false ): Promise { if (!result.success || !result.secretVars || !result.nonSecretVars) return; - let envFileContent: string | undefined; - if (result.envPath && existsSync(result.envPath)) { - try { - envFileContent = readFileSync(result.envPath, 'utf-8'); - } catch (err) { - console.warn(`${logPrefix} Failed to read .env at ${result.envPath}:`, err); - } - } - - const source = await getStackSource(stackName, envId ?? undefined); - const { dbNonSecretVars, secretVars } = await resolveProviderEnvVars( - { ...result.nonSecretVars }, - { ...result.secretVars }, - logPrefix, - source?.secretProviderId, - envFileContent, - { stackName, envId: envId ?? undefined } + const resolved = await resolveProviderVarsBestEffort( + stackName, envId, result.nonSecretVars, result.secretVars, result.envPath, logPrefix, bestEffort ); - result.nonSecretVars = dbNonSecretVars; - result.secretVars = secretVars; + result.nonSecretVars = resolved.nonSecretVars; + result.secretVars = resolved.secretVars; } // ============================================================================= diff --git a/src/lib/server/stats-calc-core.ts b/src/lib/server/stats-calc-core.ts new file mode 100644 index 000000000..0073f9296 --- /dev/null +++ b/src/lib/server/stats-calc-core.ts @@ -0,0 +1,146 @@ +/** + * Pure Docker-stats math, shared by every container-stats endpoint so the CPU / + * memory / IO calculation lives in ONE place (it used to be copy-pasted across the + * per-container, container-list and dashboard stream routes). No imports, unit-tested. + * + * Windows vs Unix: the Docker stats payload differs by daemon OS. Unix reports + * `cpu_stats.system_cpu_usage` and `memory_stats.usage`; Windows reports neither - + * it carries `memory_stats.privateworkingset` and needs a wall-clock CPU formula + * (num_procs * elapsed). Detected per-payload by the presence of `privateworkingset` + * (matches how the Docker CLI / Portainer distinguish them). Without this, a Windows + * container shows 0% CPU and 0 B memory (#1574). + */ + +/** The subset of a Docker `/containers/{id}/stats` payload this module reads. */ +export interface DockerStatsPayload { + read?: string; + preread?: string; + num_procs?: number; + cpu_stats?: { + cpu_usage?: { total_usage?: number; percpu_usage?: number[] }; + system_cpu_usage?: number; + online_cpus?: number; + }; + precpu_stats?: { + cpu_usage?: { total_usage?: number }; + system_cpu_usage?: number; + }; + memory_stats?: { + usage?: number; + limit?: number; + privateworkingset?: number; + stats?: { inactive_file?: number; total_inactive_file?: number }; + }; + networks?: Record; + blkio_stats?: { io_service_bytes_recursive?: Array<{ op?: string; value?: number }> }; + // Windows daemons report block I/O here instead of blkio_stats. + storage_stats?: { read_size_bytes?: number; write_size_bytes?: number }; +} + +/** True when the payload came from a Windows daemon (has `privateworkingset`). */ +export function isWindowsStats(stats: DockerStatsPayload | null | undefined): boolean { + return stats?.memory_stats?.privateworkingset !== undefined; +} + +/** + * Container CPU usage as a percentage. Unix uses the cpu-vs-system delta ratio; + * Windows uses (cpu delta) / (num_procs * elapsed-ns), since it has no + * system_cpu_usage. Returns 0 when the deltas are non-positive (first sample, idle). + */ +export function calculateCpuPercent(stats: DockerStatsPayload | null | undefined): number { + if (!stats) return 0; + const cur = stats.cpu_stats?.cpu_usage?.total_usage ?? 0; + const prev = stats.precpu_stats?.cpu_usage?.total_usage ?? 0; + const cpuDelta = cur - prev; + + if (isWindowsStats(stats)) { + // Wall-clock formula (matches Docker CLI / Portainer for Windows containers): + // possIntervals = num_procs * elapsed-milliseconds; cpu% = cpuDelta / (possIntervals * 100). + // read/preread are RFC3339 timestamps. No system_cpu_usage exists on Windows. + const readMs = stats.read ? new Date(stats.read).getTime() : NaN; + const prereadMs = stats.preread ? new Date(stats.preread).getTime() : NaN; + const possIntervals = (stats.num_procs ?? 0) * (readMs - prereadMs); + if (Number.isFinite(possIntervals) && possIntervals > 0 && cpuDelta > 0) { + return cpuDelta / (possIntervals * 100); + } + return 0; + } + + const systemDelta = (stats.cpu_stats?.system_cpu_usage ?? 0) - (stats.precpu_stats?.system_cpu_usage ?? 0); + const cpuCount = stats.cpu_stats?.online_cpus || stats.cpu_stats?.cpu_usage?.percpu_usage?.length || 1; + if (systemDelta > 0 && cpuDelta > 0) { + return (cpuDelta / systemDelta) * cpuCount * 100; + } + return 0; +} + +/** + * Memory usage the way the Docker CLI shows it. Unix subtracts file cache + * (inactive_file / total_inactive_file) from the raw usage; Windows reports the + * already-cache-free `privateworkingset` and has no cache to subtract. + * Returns { usage: shown value, raw: pre-subtraction, cache }. + */ +export function calculateMemoryUsage( + memoryStats: DockerStatsPayload['memory_stats'] | null | undefined +): { usage: number; raw: number; cache: number } { + if (memoryStats?.privateworkingset !== undefined) { + const raw = memoryStats.privateworkingset || 0; + return { usage: raw, raw, cache: 0 }; + } + const raw = memoryStats?.usage || 0; + const stats = memoryStats?.stats || {}; + // cgroup v2 uses 'inactive_file', cgroup v1 uses 'total_inactive_file' + const cache = stats.inactive_file ?? stats.total_inactive_file ?? 0; + const usage = (cache > 0 && cache < raw) ? raw - cache : raw; + return { usage, raw, cache }; +} + +/** Sum rx/tx bytes across all container network interfaces. */ +export function calculateNetworkIO(stats: DockerStatsPayload | null | undefined): { rx: number; tx: number } { + let rx = 0; + let tx = 0; + if (stats?.networks) { + for (const iface of Object.values(stats.networks)) { + rx += iface.rx_bytes || 0; + tx += iface.tx_bytes || 0; + } + } + return { rx, tx }; +} + +/** + * Read/write bytes. Unix sums blkio_stats.io_service_bytes_recursive (lower- or + * upper-case op); Windows leaves that empty and reports the totals in storage_stats. + */ +export function calculateBlockIO(stats: DockerStatsPayload | null | undefined): { read: number; write: number } { + let read = 0; + let write = 0; + const ioStats = stats?.blkio_stats?.io_service_bytes_recursive; + if (Array.isArray(ioStats)) { + for (const entry of ioStats) { + const op = entry.op; + if (op === 'read' || op === 'Read') read += entry.value || 0; + else if (op === 'write' || op === 'Write') write += entry.value || 0; + } + } + if (read === 0 && write === 0 && stats?.storage_stats) { + read = stats.storage_stats.read_size_bytes || 0; + write = stats.storage_stats.write_size_bytes || 0; + } + return { read, write }; +} + +/** + * Memory limit denominator, or 0 when there is none to show. A Windows daemon does + * not report a usable `memory_stats.limit` (0/absent unless the container was started + * with an explicit --memory cap), so 0 is returned there and the UI shows "unlimited" + * instead of a bogus 1-byte limit. + */ +export function calculateMemoryLimit(stats: DockerStatsPayload | null | undefined): number { + const limit = stats?.memory_stats?.limit || 0; + if (isWindowsStats(stats)) { + // A Windows limit is only meaningful when a real cap was set; otherwise 0. + return limit > 1 ? limit : 0; + } + return limit; +} diff --git a/src/lib/server/subprocess-manager.ts b/src/lib/server/subprocess-manager.ts index dfe44c656..3ba34a233 100644 --- a/src/lib/server/subprocess-manager.ts +++ b/src/lib/server/subprocess-manager.ts @@ -25,6 +25,7 @@ import { } from './db'; import { sendEnvironmentNotification, sendEventNotification } from './notifications'; import { isNotifyDisabledByLabel } from './container-labels'; +import { expectedEvents } from './expected-events-core'; import { rssBeforeOp, rssAfterOp } from './rss-tracker'; import { pushMetric } from './metrics-store'; @@ -322,8 +323,10 @@ async function handleContainerEvent(msg: GoMessage): Promise { // Sub-category: notification const notifBefore = rssBeforeOp(); - // Check dockhand.notify label — Docker includes container labels in event Actor.Attributes - if (!isNotifyDisabledByLabel(event.Actor?.Attributes)) { + // Check dockhand.notify label — Docker includes container labels in event Actor.Attributes. + // Also skip die/kill/stop that an in-progress update deliberately caused (#68). + const suppressExpected = expectedEvents.shouldSuppress(containerId, action, Date.now()); + if (!suppressExpected && !isNotifyDisabledByLabel(event.Actor?.Attributes)) { const actionLabel = action.startsWith('health_status') ? action.includes('unhealthy') ? 'Unhealthy' : 'Healthy' : action.charAt(0).toUpperCase() + action.slice(1); diff --git a/src/lib/server/systemd-recreate-core.ts b/src/lib/server/systemd-recreate-core.ts new file mode 100644 index 000000000..c9591792c --- /dev/null +++ b/src/lib/server/systemd-recreate-core.ts @@ -0,0 +1,58 @@ +// Pure decision helpers for recreating a Podman Quadlet / systemd-managed container. +// Import-light (no docker/db) so the respawn-detection logic is unit-testable without a +// live Podman socket. + +export interface FoundContainer { + Id: string; + State: string; +} + +/** + * Classify what a name-lookup found while polling for the unit to respawn the container + * after a stop. `oldId` is the container we stopped. + * - 'respawned-running': a NEW id, running -> the recreate succeeded (fresh container + * from the unit's `podman run --replace` on the new image). + * - 'respawned-not-running': a NEW id, not yet/no longer running (created/exited/ + * restarting) -> respawned but not healthy; keep polling, and on timeout this is a + * FAILURE (a crash-loop on the new image must not be reported as success). + * - 'old-still-there': the id we stopped is still the one under this name -> keep polling. + * - 'gone': nothing under this name yet -> keep polling. + */ +export function classifyRespawn( + found: FoundContainer | null, + oldId: string +): 'respawned-running' | 'respawned-not-running' | 'old-still-there' | 'gone' { + if (!found) return 'gone'; + if (found.Id === oldId) return 'old-still-there'; + return found.State === 'running' ? 'respawned-running' : 'respawned-not-running'; +} + +/** Exact-name match filter for a container-list `name` filter (Podman/Docker treat it as regex-contains). */ +export function isExactNameMatch(names: string[] | undefined, name: string): boolean { + return (names || []).some((n) => n.replace(/^\//, '') === name); +} + +export type RespawnOutcome = + | { done: true; ok: true; id: string } // a new container is running -> success + | { done: false } // keep polling + | { done: true; ok: false }; // deadline reached without a running new container + +/** + * Decide, from one poll observation, whether to finish or keep polling. Pure so the + * timeout/success/failure branches are unit-testable without a live socket. + * + * A running new-id container is an immediate success. Otherwise we keep polling until the + * deadline; once reached, we only succeed if the CURRENT observation is a running new-id + * container - a container that merely appeared but never reached running (crash-loop on a + * broken new image) is a FAILURE, never a false success. + */ +export function decideRespawnOutcome( + found: FoundContainer | null, + oldId: string, + deadlineReached: boolean +): RespawnOutcome { + const state = classifyRespawn(found, oldId); + if (state === 'respawned-running') return { done: true, ok: true, id: found!.Id }; + if (!deadlineReached) return { done: false }; + return { done: true, ok: false }; +} diff --git a/src/lib/stores/environment.ts b/src/lib/stores/environment.ts index 4f30bb27f..333a51194 100644 --- a/src/lib/stores/environment.ts +++ b/src/lib/stores/environment.ts @@ -18,6 +18,7 @@ export interface Environment { connectionType?: 'socket' | 'direct' | 'hawser-standard' | 'hawser-edge'; publicIp?: string | null; timezone?: string; + highlightChanges?: boolean; } const STORAGE_KEY = 'dockhand:environment'; diff --git a/src/lib/stores/settings.ts b/src/lib/stores/settings.ts index 1173f86d5..d7bb2fafc 100644 --- a/src/lib/stores/settings.ts +++ b/src/lib/stores/settings.ts @@ -23,6 +23,7 @@ export interface AppSettings { confirmDestructive: boolean; showStoppedContainers: boolean; highlightUpdates: boolean; + inlineTagEditing: boolean; showGitCommitHash: boolean; timeFormat: TimeFormat; dateFormat: DateFormat; @@ -71,6 +72,7 @@ const DEFAULT_SETTINGS: AppSettings = { confirmDestructive: true, showStoppedContainers: true, highlightUpdates: true, + inlineTagEditing: false, showGitCommitHash: false, timeFormat: '24h', dateFormat: 'DD.MM.YYYY', @@ -164,6 +166,7 @@ function createSettingsStore() { confirmDestructive: settings.confirmDestructive ?? DEFAULT_SETTINGS.confirmDestructive, showStoppedContainers: settings.showStoppedContainers ?? DEFAULT_SETTINGS.showStoppedContainers, highlightUpdates: settings.highlightUpdates ?? DEFAULT_SETTINGS.highlightUpdates, + inlineTagEditing: settings.inlineTagEditing ?? DEFAULT_SETTINGS.inlineTagEditing, showGitCommitHash: settings.showGitCommitHash ?? DEFAULT_SETTINGS.showGitCommitHash, timeFormat: settings.timeFormat ?? DEFAULT_SETTINGS.timeFormat, dateFormat: settings.dateFormat ?? DEFAULT_SETTINGS.dateFormat, @@ -227,6 +230,7 @@ function createSettingsStore() { confirmDestructive: updatedSettings.confirmDestructive ?? DEFAULT_SETTINGS.confirmDestructive, showStoppedContainers: updatedSettings.showStoppedContainers ?? DEFAULT_SETTINGS.showStoppedContainers, highlightUpdates: updatedSettings.highlightUpdates ?? DEFAULT_SETTINGS.highlightUpdates, + inlineTagEditing: updatedSettings.inlineTagEditing ?? DEFAULT_SETTINGS.inlineTagEditing, showGitCommitHash: updatedSettings.showGitCommitHash ?? DEFAULT_SETTINGS.showGitCommitHash, timeFormat: updatedSettings.timeFormat ?? DEFAULT_SETTINGS.timeFormat, dateFormat: updatedSettings.dateFormat ?? DEFAULT_SETTINGS.dateFormat, @@ -321,6 +325,13 @@ function createSettingsStore() { return newSettings; }); }, + setInlineTagEditing: (value: boolean) => { + update((current) => { + const newSettings = { ...current, inlineTagEditing: value }; + saveSettings({ inlineTagEditing: value }); + return newSettings; + }); + }, setUseSelfhstIcons: (value: boolean) => { update((current) => { const newSettings = { ...current, useSelfhstIcons: value }; diff --git a/src/lib/stores/theme.ts b/src/lib/stores/theme.ts index 84fec0daa..70db49089 100644 --- a/src/lib/stores/theme.ts +++ b/src/lib/stores/theme.ts @@ -36,6 +36,7 @@ export interface ThemePreferences { coloredActionButtons: boolean; actionIconSize: ActionIconSize; editorIndentGuides: boolean; + editorTheme: string; } const STORAGE_KEY = 'dockhand-theme'; @@ -51,7 +52,8 @@ const defaultPrefs: ThemePreferences = { animateIcons: true, coloredActionButtons: false, actionIconSize: 'normal', - editorIndentGuides: false + editorIndentGuides: false, + editorTheme: 'default' }; // Font size scale mapping @@ -130,7 +132,8 @@ function createThemeStore() { coloredActionButtons: !!(data.coloredActionButtons ?? data.colored_action_buttons ?? false), actionIconSize: (data.actionIconSize || data.action_icon_size || 'normal') as ActionIconSize, // Default OFF (#1410) - editorIndentGuides: !!(data.editorIndentGuides ?? data.editor_indent_guides ?? false) + editorIndentGuides: !!(data.editorIndentGuides ?? data.editor_indent_guides ?? false), + editorTheme: data.editorTheme || data.editor_theme || 'default' }; set(prefs); saveToStorage(prefs); diff --git a/src/lib/utils/container-search-core.ts b/src/lib/utils/container-search-core.ts new file mode 100644 index 000000000..b5daab333 --- /dev/null +++ b/src/lib/utils/container-search-core.ts @@ -0,0 +1,67 @@ +/** + * Pure container search matching, so the containers-page filter is unit-testable. + * + * A plain query matches the name, image, any label key OR value, and (kept for + * back-compat) the compose project. A `label:` prefix does a Docker-style label + * filter: `label:heal` matches a container that HAS a `heal` label (any value); + * `label:heal=true` matches only when the value is `true` too. Mirrors + * `docker ps --filter "label=heal"` / `label=heal=true` (#1372). + */ + +export interface SearchableContainer { + name: string; + image: string; + labels?: Record; +} + +/** A `label:key` / `label:key=value` token, parsed once per query. */ +function parseLabelToken(query: string): { key: string; value: string | null } | null { + const m = /^label:(.+)$/i.exec(query.trim()); + if (!m) return null; + const rest = m[1]; + const eq = rest.indexOf('='); + if (eq === -1) return { key: rest.trim().toLowerCase(), value: null }; + return { + key: rest.slice(0, eq).trim().toLowerCase(), + value: rest.slice(eq + 1).trim().toLowerCase(), + }; +} + +/** True if the container has a label whose key matches `key` (and value matches + * `value` when given). Keys and values are compared case-insensitively. */ +function matchesLabelFilter( + labels: Record | undefined, + key: string, + value: string | null, +): boolean { + if (!labels) return false; + for (const [k, v] of Object.entries(labels)) { + if (k.toLowerCase() !== key) continue; + if (value === null) return true; + if ((v ?? '').toLowerCase() === value) return true; + } + return false; +} + +/** + * Does a container match the search query? Empty query matches everything. + * A `label:` query is a targeted label filter; any other query is a free-text + * substring match over name, image, every label key/value, and the compose project. + */ +export function containerMatchesSearch(c: SearchableContainer, rawQuery: string): boolean { + const q = rawQuery.trim(); + if (!q) return true; + + const labelToken = parseLabelToken(q); + if (labelToken) return matchesLabelFilter(c.labels, labelToken.key, labelToken.value); + + const query = q.toLowerCase(); + if (c.name.toLowerCase().includes(query)) return true; + if (c.image.toLowerCase().includes(query)) return true; + if (c.labels) { + for (const [k, v] of Object.entries(c.labels)) { + if (k.toLowerCase().includes(query) || (v ?? '').toLowerCase().includes(query)) return true; + } + } + return false; +} diff --git a/src/lib/utils/editor-theme-extensions.ts b/src/lib/utils/editor-theme-extensions.ts new file mode 100644 index 000000000..01a6c91b4 --- /dev/null +++ b/src/lib/utils/editor-theme-extensions.ts @@ -0,0 +1,61 @@ +import type { Extension } from '@codemirror/state'; +import * as uiw from '@uiw/codemirror-themes-all'; + +// id -> CM6 theme Extension (#1309). Heavy (pulls the whole @uiw theme package), so this +// module is imported ONLY client-side (CodeEditor / EditorThemeSelector). 'default' maps +// to null - CodeEditor then uses its built-in dark/light theme that follows the app toggle. +// Keys must match the ids in editor-themes.ts. +const EXTENSIONS: Record = { + dracula: uiw.dracula, + 'vscode-dark': uiw.vscodeDark, + 'github-dark': uiw.githubDark, + monokai: uiw.monokai, + 'monokai-dimmed': uiw.monokaiDimmed, + nord: uiw.nord, + 'tokyo-night': uiw.tokyoNight, + 'tokyo-night-storm': uiw.tokyoNightStorm, + 'solarized-dark': uiw.solarizedDark, + 'gruvbox-dark': uiw.gruvboxDark, + 'material-dark': uiw.materialDark, + 'atom-one': uiw.atomone, + androidstudio: uiw.androidstudio, + andromeda: uiw.andromeda, + aura: uiw.aura, + abcdef: uiw.abcdef, + abyss: uiw.abyss, + bespin: uiw.bespin, + copilot: uiw.copilot, + darcula: uiw.darcula, + 'duotone-dark': uiw.duotoneDark, + kimbie: uiw.kimbie, + okaidia: uiw.okaidia, + red: uiw.red, + sublime: uiw.sublime, + 'console-dark': uiw.consoleDark, + 'tomorrow-night-blue': uiw.tomorrowNightBlue, + 'white-dark': uiw.whiteDark, + 'xcode-dark': uiw.xcodeDark, + material: uiw.material, + 'basic-dark': uiw.basicDark, + + 'github-light': uiw.githubLight, + 'vscode-light': uiw.vscodeLight, + 'solarized-light': uiw.solarizedLight, + 'gruvbox-light': uiw.gruvboxLight, + 'material-light': uiw.materialLight, + 'duotone-light': uiw.duotoneLight, + eclipse: uiw.eclipse, + bbedit: uiw.bbedit, + 'noctis-lilac': uiw.noctisLilac, + quietlight: uiw.quietlight, + 'tokyo-night-day': uiw.tokyoNightDay, + 'xcode-light': uiw.xcodeLight, + 'console-light': uiw.consoleLight, + 'white-light': uiw.whiteLight +}; + +// Returns the CM6 theme extension for an id, or null for 'default'/unknown (built-in theme). +export function getEditorThemeExtension(id: string | undefined | null): Extension | null { + if (!id || id === 'default') return null; + return EXTENSIONS[id] ?? null; +} diff --git a/src/lib/utils/editor-themes.ts b/src/lib/utils/editor-themes.ts new file mode 100644 index 000000000..31b1f9c32 --- /dev/null +++ b/src/lib/utils/editor-themes.ts @@ -0,0 +1,76 @@ +// CodeMirror editor color themes (#1309) - LIGHT metadata only (no @uiw import). +// The heavy id->Extension mapping lives in editor-theme-extensions.ts and is imported +// only client-side (CodeEditor / EditorThemeSelector). Server routes import this module +// to validate an id string, so it must stay free of any CodeMirror weight. + +export interface EditorThemeMeta { + id: string; + label: string; + dark: boolean; +} + +// Built-in first, then dark, then light. Ids are persisted (per-user/global) - keep stable. +export const EDITOR_THEMES: EditorThemeMeta[] = [ + { id: 'default', label: 'Default (follows app theme)', dark: true }, + + // Dark + { id: 'dracula', label: 'Dracula', dark: true }, + { id: 'vscode-dark', label: 'VS Code Dark', dark: true }, + { id: 'github-dark', label: 'GitHub Dark', dark: true }, + { id: 'monokai', label: 'Monokai', dark: true }, + { id: 'monokai-dimmed', label: 'Monokai Dimmed', dark: true }, + { id: 'nord', label: 'Nord', dark: true }, + { id: 'tokyo-night', label: 'Tokyo Night', dark: true }, + { id: 'tokyo-night-storm', label: 'Tokyo Night Storm', dark: true }, + { id: 'solarized-dark', label: 'Solarized Dark', dark: true }, + { id: 'gruvbox-dark', label: 'Gruvbox Dark', dark: true }, + { id: 'material-dark', label: 'Material Dark', dark: true }, + { id: 'atom-one', label: 'Atom One', dark: true }, + { id: 'androidstudio', label: 'Android Studio', dark: true }, + { id: 'andromeda', label: 'Andromeda', dark: true }, + { id: 'aura', label: 'Aura', dark: true }, + { id: 'abcdef', label: 'abcdef', dark: true }, + { id: 'abyss', label: 'Abyss', dark: true }, + { id: 'bespin', label: 'Bespin', dark: true }, + { id: 'copilot', label: 'Copilot', dark: true }, + { id: 'darcula', label: 'Darcula', dark: true }, + { id: 'duotone-dark', label: 'Duotone Dark', dark: true }, + { id: 'kimbie', label: 'Kimbie', dark: true }, + { id: 'okaidia', label: 'Okaidia', dark: true }, + { id: 'red', label: 'Red', dark: true }, + { id: 'sublime', label: 'Sublime', dark: true }, + { id: 'console-dark', label: 'Console Dark', dark: true }, + { id: 'tomorrow-night-blue', label: 'Tomorrow Night Blue', dark: true }, + { id: 'white-dark', label: 'White Dark', dark: true }, + { id: 'xcode-dark', label: 'Xcode Dark', dark: true }, + { id: 'material', label: 'Material', dark: true }, + { id: 'basic-dark', label: 'Basic Dark', dark: true }, + + // Light + { id: 'github-light', label: 'GitHub Light', dark: false }, + { id: 'vscode-light', label: 'VS Code Light', dark: false }, + { id: 'solarized-light', label: 'Solarized Light', dark: false }, + { id: 'gruvbox-light', label: 'Gruvbox Light', dark: false }, + { id: 'material-light', label: 'Material Light', dark: false }, + { id: 'duotone-light', label: 'Duotone Light', dark: false }, + { id: 'eclipse', label: 'Eclipse', dark: false }, + { id: 'bbedit', label: 'BBEdit', dark: false }, + { id: 'noctis-lilac', label: 'Noctis Lilac', dark: false }, + { id: 'quietlight', label: 'Quiet Light', dark: false }, + { id: 'tokyo-night-day', label: 'Tokyo Night Day', dark: false }, + { id: 'xcode-light', label: 'Xcode Light', dark: false }, + { id: 'console-light', label: 'Console Light', dark: false }, + { id: 'white-light', label: 'White Light', dark: false } +]; + +export const EDITOR_THEME_IDS: string[] = EDITOR_THEMES.map((t) => t.id); +const ID_SET = new Set(EDITOR_THEME_IDS); +const META_BY_ID = new Map(EDITOR_THEMES.map((t) => [t.id, t])); + +export function getEditorThemeMeta(id: string | undefined | null): EditorThemeMeta { + return META_BY_ID.get(id ?? 'default') ?? EDITOR_THEMES[0]; +} + +export function isValidEditorThemeId(id: unknown): id is string { + return typeof id === 'string' && ID_SET.has(id); +} diff --git a/src/lib/utils/gutter-contrast.ts b/src/lib/utils/gutter-contrast.ts new file mode 100644 index 000000000..763369928 --- /dev/null +++ b/src/lib/utils/gutter-contrast.ts @@ -0,0 +1,41 @@ +// Compute a gutter background that stays visibly distinct from the editor's own +// background on ANY theme (#1309). @uiw themes give the gutter the same colour as the +// code, so line numbers blend in. Rather than guess per theme, the caller reads the +// rendered background and this derives a contrasting tint from it. + +export interface Rgb { + r: number; + g: number; + b: number; +} + +// Parse "rgb(r, g, b)" / "rgba(r, g, b, a)" (the form getComputedStyle returns). +// Returns null for anything else (e.g. "transparent", named colours, empty). +export function parseRgb(color: string | null | undefined): Rgb | null { + if (!color) return null; + const m = color.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i); + if (!m) return null; + return { r: Number(m[1]), g: Number(m[2]), b: Number(m[3]) }; +} + +// Perceived luminance 0..255 (Rec. 601 weights). +export function luminance({ r, g, b }: Rgb): number { + return 0.299 * r + 0.587 * g + 0.114 * b; +} + +function clamp(n: number): number { + return Math.max(0, Math.min(255, Math.round(n))); +} + +// A gutter background derived from the code background: lighten a dark background, +// darken a light one, by a fixed step so the shift is always visible. Returns an +// rgb() string, or null if the input can't be parsed (caller keeps its fallback). +export function gutterBackgroundFor(codeBg: string | null | undefined, step = 24): string | null { + const rgb = parseRgb(codeBg); + if (!rgb) return null; + const dir = luminance(rgb) < 128 ? 1 : -1; // dark bg -> lighten, light bg -> darken + const r = clamp(rgb.r + dir * step); + const g = clamp(rgb.g + dir * step); + const b = clamp(rgb.b + dir * step); + return `rgb(${r}, ${g}, ${b})`; +} diff --git a/src/lib/utils/icons.ts b/src/lib/utils/icons.ts index a06f82296..4c99f8521 100644 --- a/src/lib/utils/icons.ts +++ b/src/lib/utils/icons.ts @@ -9,7 +9,11 @@ import { Anchor, Ship, Plane, Rocket, Car, Bike, TrainFront, Bus, Truck, Activity, BarChart3, ChartLine, ChartPie, TrendingUp, Gauge, Timer, Mail, MessageSquare, Phone, Video, Camera, Music, Headphones, Volume2, - MapPin, Map, Compass, Navigation, Flag, Bookmark, Target + MapPin, Map, Compass, Navigation, Flag, Bookmark, Target, + Apple, Asterisk, Beer, BellRing, Book, CircleDot, CloudRain, CloudUpload, Dot, Droplet, + File, Filter, Fish, Flashlight, Flower2, GraduationCap, Highlighter, Layers3, + LayoutDashboard, LayoutGrid, ListMusic, MemoryStick, MessageCircle, Music2, PenTool, Play, + QrCode, Reply, Search, Share2, ShoppingBag, SlidersHorizontal, ToggleLeft, UserCog, UtensilsCrossed } from 'lucide-svelte'; import type { ComponentType } from 'svelte'; @@ -36,7 +40,28 @@ const iconMap: Record = { 'mail': Mail, 'message-square': MessageSquare, 'phone': Phone, 'video': Video, 'camera': Camera, 'music': Music, 'headphones': Headphones, 'volume-2': Volume2, 'map-pin': MapPin, 'map': Map, 'compass': Compass, 'navigation': Navigation, - 'flag': Flag, 'bookmark': Bookmark, 'target': Target + 'flag': Flag, 'bookmark': Bookmark, 'target': Target, + 'folder': Folder, 'file': File, 'file-text': FileText, 'files': Files, 'image': ImageIcon, + 'film': Film, 'play': Play, 'music-2': Music2, 'list-music': ListMusic, 'podcast': Podcast, + 'gamepad': Gamepad2, 'dices': Dices, 'puzzle': Puzzle, 'trophy': Trophy, 'medal': Medal, 'ticket': Ticket, + 'cloud-download': CloudDownload, 'cloud-upload': CloudUpload, 'download': Download, 'upload': Upload, + 'share': Share2, 'rss': Rss, 'link': Link, + 'users': Users, 'user': User, 'user-cog': UserCog, 'contact': Contact, 'bot': Bot, 'brain': BrainCircuit, + 'bell': Bell, 'bell-ring': BellRing, 'calendar': Calendar, 'clock': Clock, 'alarm-clock': AlarmClock, 'hourglass': Hourglass, + 'shopping-cart': ShoppingCart, 'shopping-bag': ShoppingBag, 'credit-card': CreditCard, 'wallet': Wallet, + 'dollar-sign': DollarSign, 'receipt': Receipt, 'banknote': Banknote, + 'coffee': Coffee, 'pizza': Pizza, 'utensils': UtensilsCrossed, 'beer': Beer, 'wine': Wine, 'apple': Apple, + 'leaf': Leaf, 'tree': TreePine, 'flower': Flower2, 'bug': Bug, 'cat': Cat, 'dog': Dog, 'fish': Fish, 'bird': Bird, + 'palette': Palette, 'brush': Brush, 'pen-tool': PenTool, 'grid': Grid3x3, 'layout-grid': LayoutGrid, 'dashboard': LayoutDashboard, + 'memory-stick': MemoryStick, 'usb': Usb, 'plug': Plug, 'battery': Battery, 'power': Power, 'bluetooth': Bluetooth, + 'layers-3': Layers3, 'workflow': Workflow, 'boxes': Boxes, 'component': Component, 'blocks': Blocks, + 'thermometer': Thermometer, 'droplet': Droplet, 'wind': Wind, 'umbrella': Umbrella, 'cloud-rain': CloudRain, + 'lightbulb': Lightbulb, 'flashlight': Flashlight, 'fingerprint': Fingerprint, 'scan-line': ScanLine, + 'qr-code': QrCode, 'webhook': Webhook, + 'book': Book, 'book-open': BookOpen, 'graduation-cap': GraduationCap, 'newspaper': Newspaper, + 'feather': Feather, 'pencil': Pencil, 'highlighter': Highlighter, + 'inbox': Inbox, 'send': Send, 'reply': Reply, 'at-sign': AtSign, 'hash': Hash, 'message-circle': MessageCircle, 'megaphone': Megaphone, + 'filter': Filter, 'search': Search, 'sliders': SlidersHorizontal, 'toggle': ToggleLeft, 'circle-dot': CircleDot, 'dot': Dot, 'asterisk': Asterisk }; export function getIconComponent(iconName: string): ComponentType { diff --git a/src/lib/utils/memory-support.ts b/src/lib/utils/memory-support.ts index 1e92ad148..95f93400e 100644 --- a/src/lib/utils/memory-support.ts +++ b/src/lib/utils/memory-support.ts @@ -20,10 +20,14 @@ export interface MemorySupportInfo { * `SwapLimit` are booleans; a missing/undefined field is treated as SUPPORTED (no * warning) so an older daemon or a partial info payload never produces a false alarm. */ -export function memorySupportFromInfo(info: { MemoryLimit?: boolean; SwapLimit?: boolean } | null | undefined): MemorySupportInfo { +export function memorySupportFromInfo(info: { MemoryLimit?: boolean; SwapLimit?: boolean; OSType?: string } | null | undefined): MemorySupportInfo { const memoryLimitSupported = info?.MemoryLimit !== false; const swapLimitSupported = info?.SwapLimit !== false; - return { warn: !memoryLimitSupported, memoryLimitSupported, swapLimitSupported }; + // cgroup memory accounting is a Linux concept. A Windows daemon reports + // MemoryLimit:false but reports per-container memory fine (via privateworkingset), + // so the "enable cgroup accounting" warning is wrong there - never warn (#1574). + const warn = !memoryLimitSupported && info?.OSType !== 'windows'; + return { warn, memoryLimitSupported, swapLimitSupported }; } /** Link to the manual section explaining how to enable cgroup memory accounting. */ diff --git a/src/lib/utils/mounts.ts b/src/lib/utils/mounts.ts index 118ee75a5..6a517f297 100644 --- a/src/lib/utils/mounts.ts +++ b/src/lib/utils/mounts.ts @@ -163,6 +163,50 @@ export interface BackupItem { volumes: VolumeInfo[]; } +/** + * The restic keys of an item's NAMED volumes only - bind mounts (and unbackupable + * host/socket binds) dropped. Used by the env batch-setup "skip bind mounts" toggle to + * build a selection that captures app data (named volumes) while skipping large host + * bind sources like media libraries or ISOs. + */ +export function namedVolumeKeys(item: { volumes: VolumeInfo[] }): string[] { + return item.volumes + .filter((v) => v.mountType === 'volume' && !v.unbackupable) + .map((v) => v.key); +} + +/** What the env batch setup should do with one item when "skip bind mounts" is on. */ +export type BatchSkipDecision = + | { action: 'skip' } // nothing worth backing up (a bind-only container) + | { action: 'all' } // volumes unknown (a down stack) - don't narrow, capture everything + | { action: 'named'; selectedVolumes: string[] }; // narrow to this item's named volumes + +/** + * Decide how one batch item is scheduled under "skip bind mounts". Pure so the + * type-dependent branching is unit-testable. + * + * The mount list is empty in two very different cases: a bind-only target (binds present, + * zero named) vs a DOWN stack whose containers aren't listed (nothing known at all). We + * must not freeze an empty named-selection for a down stack - that would permanently + * capture only its compose/.env even after it comes up, silently missing its real + * volumes. So: no mounts known at all -> 'all' (safe: capture everything once it's up); + * some mounts but none named -> 'named' with [] for a stack (stack files still captured), + * or 'skip' for a container (nothing to back up). + */ +export function batchSkipDecision(item: { + type: 'stack' | 'container'; + volumes: VolumeInfo[]; +}): BatchSkipDecision { + const named = namedVolumeKeys(item); + if (named.length > 0) return { action: 'named', selectedVolumes: named }; + // Zero named volumes. Distinguish "unknown" (no mounts listed at all) from + // "genuinely only bind mounts". + if (item.volumes.length === 0) return { action: 'all' }; + // Some mounts, all bind: a stack still captures its compose/.env (config-only); + // a container has nothing to back up. + return item.type === 'stack' ? { action: 'named', selectedVolumes: [] } : { action: 'skip' }; +} + function containerName(c: RawContainer): string { return c.name || c.Names?.[0]?.replace(/^\//, '') || ''; } diff --git a/src/lib/utils/palette-data.ts b/src/lib/utils/palette-data.ts new file mode 100644 index 000000000..2725278a2 --- /dev/null +++ b/src/lib/utils/palette-data.ts @@ -0,0 +1,73 @@ +// Pure row mappers for the command palette. The /api/containers and /api/stacks +// endpoints are per-environment and return camelCase rows; the palette stamps the +// env identity (from the loop) onto each row. Extracted (like palette-filter) so the +// exact field mapping that once regressed to Docker PascalCase is unit-testable. + +export interface PaletteEnv { + id: number; + name: string; + icon?: string; +} + +export interface ContainerRow { + id: string; + name: string; + state: string; + image: string; + envId: number; + envName: string; + envIcon: string; +} + +export interface StackRow { + id: string; + name: string; + icon?: string | null; + envId: number; + envName: string; + envIcon: string; +} + +/** Map one env's /api/containers rows (camelCase {id,name,state,image}) to palette rows. */ +export function mapContainerRows(list: unknown, env: PaletteEnv): ContainerRow[] { + if (!Array.isArray(list)) return []; + return list.map((c: any) => ({ + id: c.id, + name: c.name, + state: c.state, + image: c.image, + envId: env.id, + envName: env.name, + envIcon: env.icon || 'globe' + })); +} + +/** Map one env's /api/stacks rows to palette rows (id namespaced by env). */ +export function mapStackRows(list: unknown, env: PaletteEnv): StackRow[] { + if (!Array.isArray(list)) return []; + return list.map((s: any) => ({ + id: `${env.id}:${s.name}`, + name: s.name, + icon: s.icon ?? null, + envId: env.id, + envName: env.name, + envIcon: env.icon || 'globe' + })); +} + +/** + * Flatten per-group arrays by taking one from each group in turn + * (g0[0], g1[0], ..., g0[1], g1[1], ...). The palette caps its empty view, so + * interleaving per environment surfaces variety instead of filling the cap with + * one environment's rows (and their copies when environments share a daemon). + */ +export function roundRobin(groups: T[][]): T[] { + const out: T[] = []; + const max = Math.max(0, ...groups.map((g) => g.length)); + for (let i = 0; i < max; i++) { + for (const g of groups) { + if (i < g.length) out.push(g[i]); + } + } + return out; +} diff --git a/src/lib/utils/palette-filter.ts b/src/lib/utils/palette-filter.ts new file mode 100644 index 000000000..245e4a99d --- /dev/null +++ b/src/lib/utils/palette-filter.ts @@ -0,0 +1,94 @@ +// Pure filter + rank for the command palette. Import-light (no Svelte) so it is +// unit-testable. The palette holds hundreds of items (nav, themes, fonts, editor themes, +// environments, containers, stacks); this ranks matches cheaply (substring, no fuzzy lib) +// and keeps results grouped so the list stays readable. + +export interface PaletteItem { + /** Stable key (also the aria row id). */ + id: string; + /** Group heading, e.g. 'Navigation' | 'Light theme' | 'Containers' | 'Stacks'. */ + group: string; + /** Display text, matched with highest priority. */ + label: string; + /** Pre-lowercased extra haystack (keywords + image + envName + aliases). */ + keywords: string; + /** Drives a current-selection checkmark (theme/font/env). */ + active?: boolean; +} + +/** Per-group cap applied when the query is empty, so the default view stays small. */ +export type DefaultCaps = Record; + +function escapeRegExp(s: string): string { + return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +/** The word-boundary matcher for a query: `q` starts a word (^, space, -, _, /). */ +export function wordBoundaryRegex(q: string): RegExp { + return new RegExp(`(^|[\\s\\-_/])${escapeRegExp(q)}`); +} + +/** + * Match/rank tier for one item against a query. Lower number = better match; -1 = no + * match. Ordering: label-prefix < label-word-boundary < label-substring < keyword-substring. + * `wb` is the pre-compiled word-boundary regex for `q` (compiled ONCE per query by the + * caller, not per item - a fresh RegExp per item would be a perf killer at hundreds of + * items). When omitted (test convenience) it is compiled here. + */ +export function rankItem(item: PaletteItem, q: string, wb: RegExp = wordBoundaryRegex(q)): number { + if (!q) return 0; + const label = item.label.toLowerCase(); + if (label.startsWith(q)) return 0; + if (wb.test(label)) return 1; + if (label.includes(q)) return 2; + if (item.keywords.includes(q)) return 3; + return -1; +} + +/** + * Filter + rank the palette. Results stay grouped (a group's items never interleave with + * another group's), ordered by (group order, match tier, original index) so the sort is + * stable within a tier. An empty/whitespace query returns a CAPPED default set per group + * (via `defaultCaps`, default cap = Infinity for groups not listed) so the initial view + * doesn't mount every item. + */ +export function filterPalette( + items: PaletteItem[], + rawQuery: string, + opts: { defaultCaps?: DefaultCaps } = {} +): PaletteItem[] { + const q = rawQuery.trim().toLowerCase(); + + // group order = first appearance in the source list, so groups render in a stable order. + const groupOrder = new Map(); + for (const it of items) if (!groupOrder.has(it.group)) groupOrder.set(it.group, groupOrder.size); + + if (!q) { + const caps = opts.defaultCaps ?? {}; + const perGroup = new Map(); + const out: Array<{ item: PaletteItem; tier: number; i: number; g: number }> = []; + items.forEach((item, i) => { + const used = perGroup.get(item.group) ?? 0; + const cap = caps[item.group] ?? Infinity; + if (used >= cap) return; + perGroup.set(item.group, used + 1); + out.push({ item, tier: 0, i, g: groupOrder.get(item.group)! }); + }); + return sortGrouped(out); + } + + const wb = wordBoundaryRegex(q); // compile ONCE per query, not per item + const scored: Array<{ item: PaletteItem; tier: number; i: number; g: number }> = []; + items.forEach((item, i) => { + const tier = rankItem(item, q, wb); + if (tier >= 0) scored.push({ item, tier, i, g: groupOrder.get(item.group)! }); + }); + return sortGrouped(scored); +} + +function sortGrouped( + scored: Array<{ item: PaletteItem; tier: number; i: number; g: number }> +): PaletteItem[] { + scored.sort((a, b) => a.g - b.g || a.tier - b.tier || a.i - b.i); + return scored.map((s) => s.item); +} diff --git a/src/lib/utils/palette-virtual.ts b/src/lib/utils/palette-virtual.ts new file mode 100644 index 000000000..b9ee17a2d --- /dev/null +++ b/src/lib/utils/palette-virtual.ts @@ -0,0 +1,46 @@ +// Pure fixed-height virtualization math for the command palette list. Rows have one of two +// heights (item vs group header); a prefix-sum offsets array + binary search gives the +// visible window in O(log n). Import-light so it's unit-testable without the DOM. + +/** Cumulative top offset of each row plus a final total. `heights[i]` is row i's height. */ +export function buildOffsets(heights: number[]): number[] { + const o = new Array(heights.length + 1); + o[0] = 0; + for (let i = 0; i < heights.length; i++) o[i + 1] = o[i] + heights[i]; + return o; +} + +/** + * Index of the last row whose top offset is <= y. Binary search into `offsets` (length + * rows+1). Clamps: y below 0 -> 0; y past the end -> the last row. Returns 0 for an empty + * list. + */ +export function rowAtOffset(offsets: number[], y: number): number { + const rows = offsets.length - 1; + if (rows <= 0) return 0; + let lo = 0, hi = rows - 1, ans = 0; + while (lo <= hi) { + const mid = (lo + hi) >> 1; + if (offsets[mid] <= y) { + ans = mid; + lo = mid + 1; + } else { + hi = mid - 1; + } + } + return ans; +} + +/** The [start, end) row window to render for a viewport, padded by `buffer` rows. */ +export function visibleRange( + offsets: number[], + scrollTop: number, + viewportH: number, + buffer: number +): { start: number; end: number } { + const rows = offsets.length - 1; + if (rows <= 0) return { start: 0, end: 0 }; + const start = Math.max(0, rowAtOffset(offsets, scrollTop) - buffer); + const end = Math.min(rows, rowAtOffset(offsets, scrollTop + viewportH) + buffer + 1); + return { start, end }; +} diff --git a/src/lib/utils/scan-skip.ts b/src/lib/utils/scan-skip.ts new file mode 100644 index 000000000..466685890 --- /dev/null +++ b/src/lib/utils/scan-skip.ts @@ -0,0 +1,12 @@ +// Whether the stack-adoption scan should skip a directory (#1251). Pure + import-light so +// it's unit-testable without pulling in the scanner's db/docker deps. + +// Known noise directories that never hold an adoptable stack. +export const SKIP_DIRECTORIES = ['.git', 'node_modules', '.docker', '__pycache__', '.venv', 'venv']; + +// Skip a known noise dir, or any hidden (dot-prefixed) dir. Dotfolders like btrfs +// `.snapshots` otherwise surface one duplicate stack per snapshot; a stack directory is +// never legitimately dot-prefixed. +export function shouldSkipScanDir(name: string): boolean { + return SKIP_DIRECTORIES.includes(name) || name.startsWith('.'); +} diff --git a/src/lib/utils/selfhst-match.ts b/src/lib/utils/selfhst-match.ts index 70ff3be6d..62f15fd9e 100644 --- a/src/lib/utils/selfhst-match.ts +++ b/src/lib/utils/selfhst-match.ts @@ -41,22 +41,50 @@ export function imageBasename(image: string): string { return s; } +/** Drop separators so `thelounge` can match the reference `the-lounge`. */ +function stripSeparators(s: string): string { + return s.replace(/[-_]/g, ''); +} + /** - * Resolve an already-normalized base name to a known selfh.st Reference: alias table, - * then exact match. No fuzzy substring guessing (that mis-badges - e.g. `redis-exporter` - * should not become `redis`). Returns null when there is no confident match. + * A base is matched to a reference by: alias table, exact match, then a + * separator-insensitive match (image basenames drop the hyphens the selfh.st + * Reference keeps, e.g. `thelounge` -> `the-lounge`, `homeassistant` -> `home-assistant`). + * The separator match is equality-after-normalization, NOT a substring/fuzzy guess, so it + * never mis-badges (`redisexporter` has no reference and stays unmatched); the real + * manifest has zero refs that collapse to the same separator-stripped key, so the map is + * unambiguous. `separatorless` is prebuilt from knownRefs so the lookup stays O(1). */ -function resolveBase(base: string, knownRefs: Set): string | null { +function resolveBase( + base: string, + knownRefs: Set, + separatorless: Map +): string | null { if (!base) return null; const alias = IMAGE_ALIASES[base]; if (alias && knownRefs.has(alias)) return alias; if (knownRefs.has(base)) return base; + const stripped = stripSeparators(base); + if (!stripped) return null; // an all-separator base ("---") must not match a "" key + const collapsed = separatorless.get(stripped); + if (collapsed) return collapsed; return null; } +/** Build the separator-stripped -> reference lookup for a manifest's reference set. */ +function buildSeparatorlessMap(knownRefs: Set): Map { + const map = new Map(); + for (const ref of knownRefs) map.set(stripSeparators(ref), ref); + return map; +} + /** Match a Docker image reference to a selfh.st Reference (by its basename). */ -export function matchSelfhstRef(image: string, knownRefs: Set): string | null { - return resolveBase(imageBasename(image), knownRefs); +export function matchSelfhstRef( + image: string, + knownRefs: Set, + separatorless: Map = buildSeparatorlessMap(knownRefs) +): string | null { + return resolveBase(imageBasename(image), knownRefs, separatorless); } /** @@ -79,8 +107,12 @@ export function containerNameBase(name: string): string { * then exact name == reference. No fuzzy guessing - a generic name like `web` or `app` * that isn't a known reference stays unmatched. */ -export function matchSelfhstByName(name: string, knownRefs: Set): string | null { - return resolveBase(containerNameBase(name), knownRefs); +export function matchSelfhstByName( + name: string, + knownRefs: Set, + separatorless: Map = buildSeparatorlessMap(knownRefs) +): string | null { + return resolveBase(containerNameBase(name), knownRefs, separatorless); } /** @@ -93,10 +125,13 @@ export function createSelfhstMatcher( knownRefs: Set ): (image: string, name?: string) => string | null { const cache = new Map(); + const separatorless = buildSeparatorlessMap(knownRefs); return (image: string, name = '') => { const key = `${image} ${name}`; if (cache.has(key)) return cache.get(key)!; - const ref = matchSelfhstRef(image, knownRefs) ?? matchSelfhstByName(name, knownRefs); + const ref = + matchSelfhstRef(image, knownRefs, separatorless) ?? + matchSelfhstByName(name, knownRefs, separatorless); cache.set(key, ref); return ref; }; diff --git a/src/lib/utils/session-expiry.ts b/src/lib/utils/session-expiry.ts new file mode 100644 index 000000000..204f62245 --- /dev/null +++ b/src/lib/utils/session-expiry.ts @@ -0,0 +1,25 @@ +// Decide whether a fetch response should trigger a session-expiry re-check (#1577). +// Pure so the path/status logic in +layout.svelte's fetch interceptor is unit-testable. +// A true result means "this looks like it could be an expired session" - the caller then +// confirms with the server before actually redirecting, so a proxied upstream-auth 401 +// (e.g. bad registry credentials on /api/registry/image) is not treated as expiry until +// the session check says the user is really logged out. + +export function extractPath(input: RequestInfo | URL, origin: string): string | null { + try { + const url = + typeof input === 'string' ? input : input instanceof Request ? input.url : String(input); + return new URL(url, origin).pathname; + } catch { + return null; + } +} + +// Only a 401 on an /api/* path that is NOT one of the auth endpoints (session/login/logout, +// which legitimately 401 during normal auth flow) is a session-expiry candidate. +export function isSessionExpiryCandidate(status: number, path: string | null): boolean { + if (status !== 401 || !path) return false; + if (!path.startsWith('/api/')) return false; + if (path.startsWith('/api/auth/')) return false; + return true; +} diff --git a/src/lib/utils/tags-core.ts b/src/lib/utils/tags-core.ts new file mode 100644 index 000000000..9ccda36bc --- /dev/null +++ b/src/lib/utils/tags-core.ts @@ -0,0 +1,124 @@ +/** + * Pure helpers for user-defined container/stack tags. Distinct from + * Docker labels - these are Dockhand's own organizational tags. No I/O so they are + * unit-testable and shared by the API and the UI. + */ + +/** Max length of a single tag. */ +export const MAX_TAG_LENGTH = 32; + +// A curated, vibrant tag palette: distinct, well-spaced hues (no near-duplicate +// grays or shades). Rendered via inline styles, so it needs no Tailwind class per +// colour. The stored value is the KEY; the UI looks up the hex here. +export const TAG_HEX: Record = { + slate: '#64748b', + graphite: '#334155', + ruby: '#e11d48', + red: '#ef4444', + coral: '#fb7185', + orange: '#f97316', + amber: '#f59e0b', + gold: '#eab308', + lime: '#84cc16', + green: '#22c55e', + emerald: '#10b981', + forest: '#15803d', + teal: '#14b8a6', + cyan: '#06b6d4', + sky: '#0ea5e9', + blue: '#3b82f6', + indigo: '#6366f1', + royal: '#4338ca', + violet: '#8b5cf6', + purple: '#a855f7', + grape: '#7e22ce', + fuchsia: '#d946ef', + magenta: '#c026d3', + pink: '#ec4899' +}; + +/** All palette colour keys, in display order. */ +export const TAG_COLORS = Object.keys(TAG_HEX); +export type TagColor = string; +export const DEFAULT_TAG_COLOR: TagColor = 'slate'; + +/** Coerce an arbitrary colour value to a palette colour, defaulting to slate. */ +export function normalizeColor(raw: unknown): TagColor { + return typeof raw === 'string' && raw in TAG_HEX ? raw : DEFAULT_TAG_COLOR; +} + +/** The hex for a colour key (falls back to the default). */ +export function tagHex(color: string): string { + return TAG_HEX[color] ?? TAG_HEX[DEFAULT_TAG_COLOR]; +} + +/** A tag as stored/returned: catalog id, name, colour, and an optional lucide icon. */ +export interface Tag { + id: number; + name: string; + color: TagColor; + icon?: string | null; +} + +// A tag is a short human label: letters, digits, spaces, and `_ - . /` (so +// "home cloud", "web/proxy", "v2.0" all work). No control chars or other punctuation. +const TAG_CHARS = /^[A-Za-z0-9 _.\-/]+$/; + +/** + * Normalise a single tag: trim and collapse internal whitespace. Returns null if it + * is empty or otherwise invalid (too long, illegal characters). + */ +export function normalizeTag(raw: unknown): string | null { + if (typeof raw !== 'string') return null; + const t = raw.trim().replace(/\s+/g, ' '); + if (!t) return null; + if (t.length > MAX_TAG_LENGTH) return null; + if (!TAG_CHARS.test(t)) return null; + return t; +} + +export type TagFilterMode = 'all' | 'any'; + +/** + * True if an item's tags satisfy the filter. `mode` 'all' requires every selected + * tag id (AND); 'any' requires at least one (OR). An empty filter matches everything; + * a non-empty filter never matches an untagged item. + */ +export function matchesTagFilter( + itemTagIds: number[] | undefined, + filterTagIds: number[], + mode: TagFilterMode = 'all' +): boolean { + if (!filterTagIds.length) return true; + if (!itemTagIds || !itemTagIds.length) return false; + const have = new Set(itemTagIds); + return mode === 'any' + ? filterTagIds.some((id) => have.has(id)) + : filterTagIds.every((id) => have.has(id)); +} + +/** + * Build a DataGrid group descriptor for an item's unique tag COMBINATION (used by + * the containers/stacks "group by tag" mode). Returns null for an untagged item so + * it falls into the trailing "Untagged" bucket. The combination key is the sorted + * tag ids joined with '+', so a container tagged prod+infra forms its own group, + * distinct from just prod. Order weight puts fewer-tag groups first, tie-broken by + * first tag id, so ordering is stable. + */ +export function tagGroupDescriptor(tags: Tag[]): { + key: string; + label: string; + color: string; + icons: (string | null)[]; + order: number; +} | null { + if (!tags.length) return null; + const sorted = tags.slice().sort((a, b) => a.id - b.id); + return { + key: sorted.map((t) => t.id).join('+'), + label: sorted.map((t) => t.name).join(' + '), + color: tagHex(sorted[0].color), + icons: sorted.map((t) => t.icon ?? null), + order: sorted.length * 1e6 + sorted[0].id + }; +} diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte index a507fca30..fb5056fed 100644 --- a/src/routes/+layout.svelte +++ b/src/routes/+layout.svelte @@ -2,7 +2,9 @@ import '../app.css'; import { onMount } from 'svelte'; import { browser } from '$app/environment'; + import { goto } from '$app/navigation'; import { page } from '$app/stores'; + import { toast } from 'svelte-sonner'; import { Toaster } from '$lib/components/ui/sonner'; import AppSidebar from '$lib/components/app-sidebar.svelte'; import ThemeToggle from '$lib/components/theme-toggle.svelte'; @@ -14,7 +16,9 @@ import { connectSSE, disconnectSSE } from '$lib/stores/events'; import { currentEnvironment, environments } from '$lib/stores/environment'; import { licenseStore, daysUntilExpiry } from '$lib/stores/license'; + import { get } from 'svelte/store'; import { authStore } from '$lib/stores/auth'; + import { extractPath, isSessionExpiryCandidate } from '$lib/utils/session-expiry'; import { themeStore, applyTheme } from '$lib/stores/theme'; import { gridPreferencesStore } from '$lib/stores/grid-preferences'; import { appSettings } from '$lib/stores/settings'; @@ -87,7 +91,44 @@ // Check auth status authStore.check(); + // Redirect to the login page when the session expires mid-use (#1577): once auth is + // enabled, a stale session makes every /api/* call return 401, but the UI otherwise + // keeps showing the last page. Intercept fetch to catch that centrally, so we don't + // have to touch every call site. A 401 is only treated as expiry after re-checking + // the session with the server, so a proxied upstream-auth 401 (e.g. bad registry + // credentials on /api/registry/image) doesn't wrongly log the user out. + const originalFetch = window.fetch; + let checkingExpiry = false; // dedupe concurrent 401s while the session re-check is in flight + window.fetch = async (...args) => { + const response = await originalFetch(...args); + try { + const path = extractPath(args[0], window.location.origin); + if ( + isSessionExpiryCandidate(response.status, path) && + get(authStore).authEnabled && + !checkingExpiry && + window.location.pathname !== '/login' + ) { + checkingExpiry = true; + try { + await authStore.check(); // confirm with the server whether the session is actually gone + const auth = get(authStore); + if (auth.authEnabled && !auth.authenticated && window.location.pathname !== '/login') { + toast.error('Your session has expired. Please sign in again.'); + goto('/login'); + } + } finally { + checkingExpiry = false; + } + } + } catch { + // URL parsing / check failures are non-fatal; never break the original response. + } + return response; + }; + return () => { + window.fetch = originalFetch; disconnectSSE(); }; }); diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index 63e04aea4..7857458b4 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -5,7 +5,7 @@ + + + +
+
+ +
+ Tags + + Organize containers and stacks with your own tags. Tags are shared across all environments; which containers and stacks carry a tag is set per environment. + {#if !canEdit} Only an administrator can create or edit tags.{/if} + +
+
+
+
+ + {#if canEdit} + +
+ { if (e.key === 'Enter') create(); }} /> + + + {#snippet child({ props })} + + {/snippet} + + +
+ {#each TAG_COLORS as c} + + {/each} +
+
+
+ (newIcon = i)} /> + +
+ {/if} + + {#if loading} +

Loading...

+ {:else if tags.length === 0} +
No tags yet
+ {:else} +
+ {#each tags as tag (tag.id)} +
+ {#if editId === tag.id} + { if (e.key === 'Enter') saveEdit(tag); if (e.key === 'Escape') editId = null; }} /> + + {:else} + {@const hex = tagHex(tag.color)} + + {#if tag.icon}{:else}{/if} + {tag.name} + + {#if canEdit} + + colorPopoverId = o ? tag.id : null}> + + {#snippet child({ props })} + + {/snippet} + + +
+ {#each TAG_COLORS as c} + + {/each} +
+
+
+ + setIcon(tag, i)} /> + + remove(tag)} + > + {#snippet children({ open })} + + {/snippet} + + {/if} + {/if} +
+ {/each} +
+ {/if} +
+
diff --git a/src/routes/stacks/+page.svelte b/src/routes/stacks/+page.svelte index 940e17988..3f036b2c5 100644 --- a/src/routes/stacks/+page.svelte +++ b/src/routes/stacks/+page.svelte @@ -4,17 +4,17 @@