The server closed idle keep-alive connections after 60 s while orca-proxy keeps upstream connections pooled for up to 90 s. A request sent on a connection the server was just closing failed with "connection closed before message completed" and the proxy answered 502: 76 times on tenant-registry-prod /healthz between 2026-10-09 and 2026-10-12, without restarts. IdleTimeout is now 120 s, above the proxy's pool timeout. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
209 lines
7.7 KiB
Go
209 lines
7.7 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/mail"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/storage"
|
|
"log/slog"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
"time"
|
|
|
|
"git.breakpilot.com/platform/tenant-registry/internal/authn"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/config"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/erp"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/licence"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/llmkeys"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/product"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/server"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
|
"git.breakpilot.com/platform/tenant-registry/migrations"
|
|
)
|
|
|
|
func main() {
|
|
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
|
|
slog.SetDefault(logger)
|
|
|
|
cfg, err := config.Load()
|
|
if err != nil {
|
|
slog.Error("config load failed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
bootCtx, cancelBoot := context.WithTimeout(context.Background(), 15*time.Second)
|
|
defer cancelBoot()
|
|
|
|
var s store.Store
|
|
if cfg.DatabaseURL == "" {
|
|
slog.Warn("DATABASE_URL not set — running with in-memory store (dev only)")
|
|
s = store.NewMemory()
|
|
} else {
|
|
if os.Getenv("MIGRATE_ON_START") == "true" {
|
|
if err := migrations.Up(bootCtx, cfg.DatabaseURL); err != nil {
|
|
slog.Error("MIGRATE_ON_START failed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
pg, err := store.NewPostgres(bootCtx, cfg.DatabaseURL)
|
|
if err != nil {
|
|
slog.Error("postgres connect failed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
s = pg
|
|
}
|
|
defer s.Close()
|
|
|
|
var kc keycloak.Adapter
|
|
if cfg.KeycloakAdminURL != "" && cfg.KeycloakClientID != "" {
|
|
kc = keycloak.NewHTTPAdapter(keycloak.HTTPConfig{
|
|
BaseURL: cfg.KeycloakAdminURL,
|
|
Realm: cfg.KeycloakRealm,
|
|
ClientID: cfg.KeycloakClientID,
|
|
ClientSecret: cfg.KeycloakClientSecret,
|
|
Timeout: cfg.KeycloakTimeout,
|
|
|
|
InviteClientID: cfg.InviteClientID,
|
|
InviteRedirectURI: cfg.InviteRedirectURI,
|
|
})
|
|
slog.Info("keycloak adapter configured",
|
|
"url", cfg.KeycloakAdminURL, "realm", cfg.KeycloakRealm, "client_id", cfg.KeycloakClientID)
|
|
} else {
|
|
slog.Warn("KEYCLOAK_ADMIN_URL not set — using mock adapter (dev only; no real KC writes)")
|
|
kc = keycloak.NewMock()
|
|
}
|
|
|
|
var av *authn.Verifier
|
|
if cfg.AuthEnabled {
|
|
av, err = authn.New(bootCtx, cfg.KeycloakIssuer, cfg.AuthAudience)
|
|
if err != nil {
|
|
// Fail closed: never start an "authenticated" server that
|
|
// cannot actually verify tokens.
|
|
slog.Error("AUTH_CONFIG_INCOMPLETE — AUTH_ENABLED=true but verifier init failed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
slog.Info("api auth enabled", "issuer", cfg.KeycloakIssuer, "audience", cfg.AuthAudience)
|
|
} else {
|
|
slog.Warn("AUTH_ENABLED=false — API is unauthenticated (dev only)")
|
|
}
|
|
|
|
// Downstream product provisioning. Wired only when PRODUCT_API_URL is set;
|
|
// otherwise a no-op so an unconfigured deployment still creates tenants.
|
|
// The product's gate is not yet enforcing, so no token is attached today —
|
|
// AuthHeaderFunc is the seam for when it is.
|
|
var pv product.Provisioner = product.NoopProvisioner{}
|
|
if cfg.ProductAPIURL != "" {
|
|
pv = product.NewHTTPProvisioner(cfg.ProductAPIURL, cfg.ProductAPIPath, nil, cfg.ProductTimeout)
|
|
slog.Info("product provisioner configured", "url", cfg.ProductAPIURL, "path", cfg.ProductAPIPath)
|
|
} else {
|
|
slog.Warn("PRODUCT_API_URL not set — product tenant provisioning disabled (anchors may diverge)")
|
|
}
|
|
|
|
authz := server.ParseAuthzRules(cfg.AuthzRules)
|
|
server.LogAuthz(logger, authz)
|
|
|
|
// ERP link (M-MIG-7). Staging: erpnext-mock-stage; prod: erp.breakpilot.com.
|
|
erpClient := erp.New(erp.Config{BaseURL: cfg.ErpBaseURL, APIKey: cfg.ErpAPIKey, APISecret: cfg.ErpAPISecret, LeadDoctype: cfg.ErpLeadDoctype})
|
|
if erpClient.Enabled() {
|
|
slog.Info("erp client configured", "url", cfg.ErpBaseURL, "lead_doctype", cfg.ErpLeadDoctype)
|
|
} else {
|
|
slog.Warn("ERP_BASE_URL not set — ERP outbox idle, reconcile runs ladder steps only")
|
|
}
|
|
if cfg.ErpWebhookSecret == "" {
|
|
slog.Warn("ERP_WEBHOOK_SECRET not set — POST /v1/internal/erp/webhook is disabled")
|
|
}
|
|
signer, err := licence.NewSigner(cfg.LicenceSigningKey, cfg.LicenceIssuer)
|
|
if err != nil {
|
|
slog.Error("licence signer init failed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
if signer.Ephemeral {
|
|
slog.Warn("LICENCE_SIGNING_KEY not set — ephemeral licence key (dev only; licences die with the process)", "kid", signer.KID())
|
|
} else {
|
|
slog.Info("licence signer configured", "kid", signer.KID(), "issuer", signer.Issuer())
|
|
}
|
|
|
|
// LiteLLM virtual keys for Werkpilot licences (D6).
|
|
llmKeys := llmkeys.New(llmkeys.Config{BaseURL: cfg.LiteLLMBaseURL, MasterKey: cfg.LiteLLMMasterKey, Models: cfg.LiteLLMModels,
|
|
BudgetTrial: cfg.LiteLLMBudgetTrial, BudgetDefault: cfg.LiteLLMBudgetDefault})
|
|
if llmKeys.Enabled() {
|
|
slog.Info("litellm key provisioning configured", "url", llmKeys.BaseURL(), "models", llmKeys.Models(),
|
|
"budget_trial_usd", llmKeys.Budget(true), "budget_default_usd", llmKeys.Budget(false), "budget_duration", llmKeys.BudgetDuration())
|
|
} else {
|
|
slog.Warn("LITELLM_MASTER_KEY not set — Werkpilot licences are issued without a LiteLLM key")
|
|
}
|
|
|
|
var objects storage.Objects
|
|
docCfg := storage.Config{Endpoint: cfg.DocumentsS3Endpoint, Region: cfg.DocumentsS3Region, Bucket: cfg.DocumentsS3Bucket,
|
|
AccessKey: cfg.DocumentsS3AccessKey, SecretKey: cfg.DocumentsS3SecretKey}
|
|
if docCfg.Configured() {
|
|
sctx, scancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
s3, serr := storage.NewS3(sctx, docCfg)
|
|
scancel()
|
|
if serr != nil {
|
|
// Documents are one feature; the registry keeps serving everything else.
|
|
logger.Error("document storage unavailable; document routes answer 503", "err", serr)
|
|
} else {
|
|
objects = s3
|
|
logger.Info("document storage ready", "bucket", docCfg.Bucket)
|
|
}
|
|
} else {
|
|
logger.Warn("DOCUMENTS_S3_* not set; document routes answer 503")
|
|
}
|
|
var mailer mail.Sender
|
|
if mc := (mail.Config{Host: cfg.SMTPHost, Port: cfg.SMTPPort, User: cfg.SMTPUser, Password: cfg.SMTPPassword, From: cfg.MailFrom, FromName: cfg.MailFromName}); mc.Configured() {
|
|
mailer = &mail.SMTP{Cfg: mc}
|
|
}
|
|
app := &server.Server{Cfg: cfg, Log: logger, Store: s, Keycloak: kc, Auth: av, Authz: authz, Product: pv, ERP: erpClient, Licences: signer, LLMKeys: llmKeys, Objects: objects, Mail: mailer}
|
|
handler := server.NewRouter(app)
|
|
srv := &http.Server{
|
|
Addr: cfg.Addr,
|
|
Handler: handler,
|
|
ReadTimeout: 10 * time.Second,
|
|
WriteTimeout: 30 * time.Second,
|
|
// Above orca-proxy's upstream pool idle timeout (90 s): with a shorter
|
|
// value the proxy reuses connections the server is closing and answers
|
|
// 502 "connection closed before message completed".
|
|
IdleTimeout: 120 * time.Second,
|
|
}
|
|
|
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
|
defer stop()
|
|
|
|
go app.RunOutbox(ctx, cfg.ErpOutboxInterval)
|
|
go app.RunReconcile(ctx, cfg.ErpReconcileEvery)
|
|
go app.RunMail(ctx, 20*time.Second)
|
|
|
|
go func() {
|
|
slog.Info("tenant-registry listening", "addr", cfg.Addr, "env", cfg.Env, "store", storeKind(s))
|
|
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
slog.Error("server crashed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
}()
|
|
|
|
<-ctx.Done()
|
|
slog.Info("shutdown requested")
|
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
|
defer cancel()
|
|
if err := srv.Shutdown(shutdownCtx); err != nil {
|
|
slog.Error("shutdown failed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
slog.Info("bye")
|
|
}
|
|
|
|
func storeKind(s store.Store) string {
|
|
switch s.(type) {
|
|
case *store.Memory:
|
|
return "memory"
|
|
case *store.Postgres:
|
|
return "postgres"
|
|
default:
|
|
return "unknown"
|
|
}
|
|
}
|