|
16 | 16 | * under the LICENSE. |
17 | 17 | */ |
18 | 18 |
|
| 19 | +// Command server is the entry point for the tenant-service. |
| 20 | +// |
| 21 | +// Environment variables: |
| 22 | +// |
| 23 | +// PORT HTTP listen port (default: 8083) |
| 24 | +// DATABASE_URL PostgreSQL connection string (required) |
| 25 | +// LOG_LEVEL debug | info | warn | error (default: info) |
| 26 | +// LOG_FORMAT json | text (default: json) |
19 | 27 | package main |
20 | 28 |
|
21 | 29 | import ( |
22 | | - "encoding/json" |
23 | | - "log" |
| 30 | + "context" |
| 31 | + "errors" |
| 32 | + "log/slog" |
24 | 33 | "net/http" |
| 34 | + "os" |
| 35 | + "os/signal" |
| 36 | + "syscall" |
| 37 | + "time" |
| 38 | + |
| 39 | + "github.com/jackc/pgx/v5/pgxpool" |
25 | 40 |
|
26 | 41 | "github.com/SoftLaneIT/serviceforge/packages/go-common/config" |
| 42 | + "github.com/SoftLaneIT/serviceforge/packages/go-common/logger" |
| 43 | + "github.com/SoftLaneIT/serviceforge/packages/go-common/tenant" |
| 44 | + "github.com/SoftLaneIT/serviceforge/services/tenant-service/internal/handler" |
| 45 | + "github.com/SoftLaneIT/serviceforge/services/tenant-service/internal/repository" |
27 | 46 | ) |
28 | 47 |
|
29 | | -type createTenantRequest struct { |
30 | | - Name string `json:"name"` |
31 | | - Slug string `json:"slug"` |
32 | | - PlanID string `json:"planId"` |
33 | | -} |
34 | | - |
35 | 48 | func main() { |
| 49 | + // ── logger ──────────────────────────────────────────────────────────────── |
| 50 | + log := logger.NewFromEnv("tenant-service") |
| 51 | + |
| 52 | + // ── database ────────────────────────────────────────────────────────────── |
| 53 | + dsn := config.GetEnv("DATABASE_URL", |
| 54 | + "postgres://serviceforge:serviceforge@localhost:5432/serviceforge?sslmode=disable") |
| 55 | + |
| 56 | + pool := mustConnectPool(log, dsn) |
| 57 | + defer pool.Close() |
| 58 | + |
| 59 | + // ── repository + handler ────────────────────────────────────────────────── |
| 60 | + repo := repository.NewPostgres(pool) |
| 61 | + h := handler.New(repo, log) |
| 62 | + |
| 63 | + // ── HTTP server ─────────────────────────────────────────────────────────── |
36 | 64 | mux := http.NewServeMux() |
37 | | - mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { |
38 | | - respondJSON(w, http.StatusOK, map[string]any{"service": "tenant-service", "status": "ok"}) |
39 | | - }) |
40 | | - mux.HandleFunc("/v1/tenants", func(w http.ResponseWriter, r *http.Request) { |
41 | | - switch r.Method { |
42 | | - case http.MethodPost: |
43 | | - var req createTenantRequest |
44 | | - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { |
45 | | - http.Error(w, "invalid payload", http.StatusBadRequest) |
46 | | - return |
47 | | - } |
48 | | - respondJSON(w, http.StatusCreated, map[string]any{ |
49 | | - "id": "tenant_001", |
50 | | - "name": req.Name, |
51 | | - "slug": req.Slug, |
52 | | - "planId": req.PlanID, |
53 | | - }) |
54 | | - default: |
55 | | - http.Error(w, "method not allowed", http.StatusMethodNotAllowed) |
56 | | - } |
57 | | - }) |
| 65 | + h.RegisterRoutes(mux) |
| 66 | + |
| 67 | + // Middleware chain (outermost first): |
| 68 | + // tenant.Middleware → injects tenant_id from X-Tenant-ID header |
| 69 | + // logger.HTTPMiddleware → structured request logging with tenant_id + trace_id |
| 70 | + httpHandler := tenant.Middleware(logger.HTTPMiddleware(log)(mux)) |
58 | 71 |
|
59 | 72 | port := config.GetEnv("PORT", "8083") |
60 | | - log.Printf("tenant-service listening on :%s", port) |
61 | | - if err := http.ListenAndServe(":"+port, mux); err != nil { |
62 | | - log.Fatal(err) |
| 73 | + srv := &http.Server{ |
| 74 | + Addr: ":" + port, |
| 75 | + Handler: httpHandler, |
| 76 | + ReadTimeout: 10 * time.Second, |
| 77 | + WriteTimeout: 30 * time.Second, |
| 78 | + IdleTimeout: 120 * time.Second, |
| 79 | + } |
| 80 | + |
| 81 | + // ── graceful shutdown ───────────────────────────────────────────────────── |
| 82 | + // Start the HTTP server in a goroutine so the main goroutine can block on |
| 83 | + // the signal channel. |
| 84 | + serverErr := make(chan error, 1) |
| 85 | + go func() { |
| 86 | + log.Info("tenant-service starting", slog.String("port", port)) |
| 87 | + if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) { |
| 88 | + serverErr <- err |
| 89 | + } |
| 90 | + }() |
| 91 | + |
| 92 | + quit := make(chan os.Signal, 1) |
| 93 | + signal.Notify(quit, syscall.SIGTERM, syscall.SIGINT) |
| 94 | + |
| 95 | + select { |
| 96 | + case sig := <-quit: |
| 97 | + log.Info("shutdown signal received", slog.String("signal", sig.String())) |
| 98 | + case err := <-serverErr: |
| 99 | + log.Error("server error", slog.Any("error", err)) |
| 100 | + os.Exit(1) |
| 101 | + } |
| 102 | + |
| 103 | + // Allow up to 30 s for in-flight requests to complete. |
| 104 | + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| 105 | + defer cancel() |
| 106 | + |
| 107 | + if err := srv.Shutdown(ctx); err != nil { |
| 108 | + log.Error("forced shutdown", slog.Any("error", err)) |
63 | 109 | } |
| 110 | + log.Info("tenant-service stopped") |
64 | 111 | } |
65 | 112 |
|
66 | | -func respondJSON(w http.ResponseWriter, status int, payload any) { |
67 | | - w.Header().Set("Content-Type", "application/json") |
68 | | - w.WriteHeader(status) |
69 | | - _ = json.NewEncoder(w).Encode(payload) |
| 113 | +// mustConnectPool attempts to connect to PostgreSQL with exponential back-off |
| 114 | +// retries. It calls os.Exit(1) if the database is unreachable after all |
| 115 | +// attempts, because a tenant-service without a database is not useful. |
| 116 | +func mustConnectPool(log *slog.Logger, dsn string) *pgxpool.Pool { |
| 117 | + const maxAttempts = 5 |
| 118 | + |
| 119 | + cfg, err := pgxpool.ParseConfig(dsn) |
| 120 | + if err != nil { |
| 121 | + log.Error("invalid DATABASE_URL", slog.Any("error", err)) |
| 122 | + os.Exit(1) |
| 123 | + } |
| 124 | + |
| 125 | + // Reasonable pool limits for a Phase 1 single-replica deployment. |
| 126 | + cfg.MaxConns = 10 |
| 127 | + cfg.MinConns = 2 |
| 128 | + cfg.MaxConnLifetime = 1 * time.Hour |
| 129 | + cfg.MaxConnIdleTime = 5 * time.Minute |
| 130 | + |
| 131 | + ctx := context.Background() |
| 132 | + var pool *pgxpool.Pool |
| 133 | + |
| 134 | + for attempt := range maxAttempts { |
| 135 | + pool, err = pgxpool.NewWithConfig(ctx, cfg) |
| 136 | + if err == nil { |
| 137 | + if pingErr := pool.Ping(ctx); pingErr == nil { |
| 138 | + log.Info("database connected", slog.Int("attempt", attempt+1)) |
| 139 | + return pool |
| 140 | + } else { |
| 141 | + pool.Close() |
| 142 | + err = pingErr |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + wait := time.Duration(1<<attempt) * time.Second // 1, 2, 4, 8, 16 s |
| 147 | + log.Warn("database not ready, retrying", |
| 148 | + slog.Int("attempt", attempt+1), |
| 149 | + slog.Int("maxAttempts", maxAttempts), |
| 150 | + slog.Duration("retryIn", wait), |
| 151 | + slog.Any("error", err), |
| 152 | + ) |
| 153 | + time.Sleep(wait) |
| 154 | + } |
| 155 | + |
| 156 | + log.Error("could not connect to database after retries", slog.Any("error", err)) |
| 157 | + os.Exit(1) |
| 158 | + return nil // unreachable — satisfies the compiler |
70 | 159 | } |
0 commit comments