package main import ( "context" "crypto/rand" "encoding/hex" "fmt" "log" "net" "net/http" "os" "os/signal" "path/filepath" "time" "git.k6n.net/mats/go-cart-actor/internal/customerauth" "git.k6n.net/mats/go-cart-actor/internal/ucp" "git.k6n.net/mats/go-cart-actor/pkg/actor" "git.k6n.net/mats/go-cart-actor/pkg/profile" "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" ) // authSecret returns the HMAC key for customer session cookies. It reads // CUSTOMER_AUTH_SECRET; when unset it generates an ephemeral random key and // warns that issued sessions will not survive a restart (fine for dev). func authSecret() []byte { if v := os.Getenv("CUSTOMER_AUTH_SECRET"); v != "" { return []byte(v) } b := make([]byte, 32) if _, err := rand.Read(b); err != nil { log.Fatalf("could not generate auth secret: %v", err) } log.Print("warning: CUSTOMER_AUTH_SECRET unset — using an ephemeral key; customer sessions will not survive a restart") return []byte(hex.EncodeToString(b)) } var podIp = os.Getenv("POD_IP") var name = os.Getenv("POD_NAME") // loadUCPProfileSigner loads the UCP ECDSA signing key from the path specified in // the UCP_SIGNING_KEY_PATH environment variable. Returns nil if unset or unreadable. func loadUCPProfileSigner() *ucp.SigningConfig { path := os.Getenv("UCP_SIGNING_KEY_PATH") if path == "" { return nil } pemData, err := os.ReadFile(path) if err != nil { log.Printf("ucp signing: cannot read key %s: %v", path, err) return nil } cfg, err := ucp.NewSigningConfigFromPEM(pemData, "k6n-ecdsa-2026") if err != nil { log.Printf("ucp signing: invalid key at %s: %v", path, err) return nil } return cfg } // getEnv returns the value of the environment variable named by key, or def if unset/empty. func getEnv(key, def string) string { if v := os.Getenv(key); v != "" { return v } return def } func main() { reg := profile.NewProfileMutationRegistry() profileDir := getEnv("PROFILE_DIR", "data/profiles") if err := os.MkdirAll(profileDir, 0755); err != nil { log.Printf("warning: could not create profile data directory %s: %v", profileDir, err) } diskStorage := actor.NewDiskStorage[profile.ProfileGrain](profileDir, reg) poolConfig := actor.GrainPoolConfig[profile.ProfileGrain]{ MutationRegistry: reg, Storage: diskStorage, Spawn: func(ctx context.Context, id uint64) (actor.Grain[profile.ProfileGrain], error) { ret := profile.NewProfileGrain(id, time.Now()) err := diskStorage.LoadEvents(ctx, id, ret) return ret, err }, // Destroy is an optional grain-eviction cleanup hook; profiles need none // (disk storage persists via its own loop), so it's left unset — purge() // skips a nil Destroy. TTL: 10 * time.Minute, PoolSize: 65535, Hostname: podIp, } pool, err := actor.NewSimpleGrainPool(poolConfig) if err != nil { log.Fatalf("Error creating profile pool: %v\n", err) } mux := http.NewServeMux() debugMux := http.NewServeMux() ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) defer stop() otelShutdown, err := setupOTelSDK(ctx) if err != nil { log.Fatalf("Unable to start otel %v", err) } // UCP Customer REST adapter customerUCP := ucp.CustomerHandler(pool) if signer := loadUCPProfileSigner(); signer != nil { customerUCP = ucp.WithSigning(customerUCP, signer) log.Print("ucp customer signing enabled") } // StripPrefix is required because the sub-mux (CustomerHandler) registers // routes like "GET /{id}" which expect a relative path; Go's ServeMux // passes the full request path without stripping the prefix. mux.Handle("/ucp/v1/customers/", http.StripPrefix("/ucp/v1/customers", customerUCP)) // Customer auth: password signup/login + session cookies + identity linking. credStore, err := customerauth.LoadCredentialStore(filepath.Join(profileDir, "credentials.json")) if err != nil { log.Fatalf("Error loading credential store: %v\n", err) } authHandler := customerauth.NewServer(credStore, pool, customerauth.NewSigner(authSecret()), 0).Handler() mux.Handle("/ucp/v1/auth/", http.StripPrefix("/ucp/v1/auth", authHandler)) mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { grainCount, capacity := pool.LocalUsage() if grainCount >= capacity { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte("grain pool at capacity")) return } if !pool.IsHealthy() { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte("pool not healthy")) return } w.WriteHeader(http.StatusOK) w.Write([]byte("ok")) }) mux.HandleFunc("/readyz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte("ok")) }) mux.HandleFunc("/livez", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte("ok")) }) mux.HandleFunc("/version", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte("1.0.0")) }) srv := &http.Server{ Addr: getEnv("PROFILE_ADDR", ":8080"), BaseContext: func(net.Listener) context.Context { return ctx }, ReadTimeout: 10 * time.Second, WriteTimeout: 20 * time.Second, Handler: otelhttp.NewHandler(mux, "/"), } defer func() { fmt.Println("Shutting down profile service") otelShutdown(context.Background()) diskStorage.Close() pool.Close() }() srvErr := make(chan error, 1) go func() { srvErr <- srv.ListenAndServe() }() log.Print("Profile server started at port 8080") go http.ListenAndServe(":8081", debugMux) select { case err = <-srvErr: log.Fatalf("Unable to start server: %v", err) case <-ctx.Done(): stop() } }