package libraryfreeze import ( "context" "encoding/json" "net" "net/http" "os" "path/filepath" "strings" "testing" "time" ) type projectFixture struct { appID string frontID string appRunning bool appHealthy bool signals []string services []string } func newProjectFixture(t *testing.T) (*projectFixture, string) { t.Helper() f := &projectFixture{ appID: strings.Repeat("a", 64), frontID: strings.Repeat("b", 64), appRunning: true, appHealthy: true, services: []string{"app", "frontend"}, } // A short path: unix socket addresses are length-limited and t.TempDir() // embeds the (long) test name. root, err := os.MkdirTemp(os.TempDir(), "kgp-") if err != nil { t.Fatal(err) } t.Cleanup(func() { os.RemoveAll(root) }) socket := filepath.Join(root, "engine.sock") listener, err := net.Listen("unix", socket) if err != nil { t.Fatal(err) } labels := func(service string) map[string]string { return map[string]string{composeProjectLabel: "weknora", composeServiceLabel: service} } server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { case r.Method == "GET" && strings.HasSuffix(r.URL.Path, "/containers/json"): if !strings.Contains(r.URL.Query().Get("filters"), "weknora") { t.Error("missing project filter") } items := []map[string]any{} for _, service := range f.services { id := f.appID if service == "frontend" { id = f.frontID } items = append(items, map[string]any{"Id": id, "Labels": labels(service)}) } _ = json.NewEncoder(w).Encode(items) case r.Method == "GET" && strings.HasSuffix(r.URL.Path, "/json"): id := strings.TrimPrefix(strings.TrimSuffix(r.URL.Path, "/json"), "/containers/") service := "app" if id == f.frontID { service = "frontend" } status := "exited" health := any(nil) if id == f.appID && f.appRunning { status = "running" if f.appHealthy { health = map[string]string{"Status": "healthy"} } else { health = map[string]string{"Status": "starting"} } } _ = json.NewEncoder(w).Encode(map[string]any{"Id": id, "Config": map[string]any{"Labels": labels(service)}, "State": map[string]any{"Running": id == f.appID && f.appRunning, "Status": status, "Health": health}}) case r.Method == "POST" && strings.HasSuffix(r.URL.Path, "/kill"): if r.URL.Query().Get("signal") != "SIGTERM" { t.Error("unsafe stop signal") } if !strings.Contains(r.URL.Path, f.appID) { t.Error("stopped an undeclared container") } f.signals = append(f.signals, "stop") f.appRunning = false w.WriteHeader(204) case r.Method == "POST" && strings.HasSuffix(r.URL.Path, "/start"): f.signals = append(f.signals, "start") f.appRunning = true w.WriteHeader(204) default: w.WriteHeader(404) } })} go server.Serve(listener) t.Cleanup(func() { server.Close() }) return f, socket } func TestProjectControllerStopsOnlyDeclaredWritersByPinnedIdentity(t *testing.T) { fixture, socket := newProjectFixture(t) control, err := NewProjectController(socket, "weknora", []string{"app"}, map[string]string{"frontend": "serves the UI only; never writes knowledge"}, time.Second) if err != nil { t.Fatal(err) } defer control.Close() items, err := control.Inventory(context.Background()) if err != nil { t.Fatal(err) } if len(items) != 1 || items[0].ID != fixture.appID || !items[0].Running || !items[0].Healthy { t.Fatalf("unexpected writer inventory %+v", items) } if err = control.Stop(context.Background(), fixture.appID); err != nil { t.Fatal(err) } if fixture.appRunning { t.Fatal("writer still running after stop") } if err = control.Start(context.Background(), fixture.appID); err != nil { t.Fatal(err) } if len(fixture.signals) != 2 || fixture.signals[0] != "stop" || fixture.signals[1] != "start" { t.Fatalf("unexpected signal order %v", fixture.signals) } } func TestProjectControllerRefusesUndeclaredSibling(t *testing.T) { fixture, socket := newProjectFixture(t) control, err := NewProjectController(socket, "weknora", []string{"app"}, map[string]string{}, time.Second) if err != nil { t.Fatal(err) } defer control.Close() if _, err = control.Inventory(context.Background()); err == nil { t.Fatal("undeclared sibling service was accepted") } if len(fixture.signals) != 0 { t.Fatal("refused inventory still signalled a container") } } func TestProjectControllerRefusesReplacedContainerIdentity(t *testing.T) { fixture, socket := newProjectFixture(t) control, err := NewProjectController(socket, "weknora", []string{"app"}, map[string]string{"frontend": "serves the UI only; never writes knowledge"}, time.Second) if err != nil { t.Fatal(err) } defer control.Close() if _, err = control.Inventory(context.Background()); err != nil { t.Fatal(err) } // A recreated container keeps the service name but is a different instance: // stopping it would hit a container the maintenance window never declared. fixture.appID = strings.Repeat("c", 64) if _, err = control.Inventory(context.Background()); err == nil { t.Fatal("recreated writer identity was accepted") } } func TestProjectControllerWaitsForHealthOnStart(t *testing.T) { fixture, socket := newProjectFixture(t) control, err := NewProjectController(socket, "weknora", []string{"app"}, map[string]string{"frontend": "serves the UI only; never writes knowledge"}, time.Second) if err != nil { t.Fatal(err) } defer control.Close() if _, err = control.Inventory(context.Background()); err != nil { t.Fatal(err) } fixture.appRunning = false fixture.appHealthy = false ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) defer cancel() if err = control.Start(ctx, fixture.appID); err == nil { t.Fatal("start succeeded without health") } }