SPB Git

Repository Public

svc.go 3.9 KB 121 lines go

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Command Center (MCC)8 * File             : services/internal/svc/svc.go9 * Module           : services10 * Repository       : https://git.spboucher.ai/maclustr-command-center11 * Project Website  : https://clustr.spboucher.ai12 * Created          : 2026-11-1813 * Last Modified    : 2026-11-1814 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Package svc holds process plumbing shared by the service binaries:43// structured logging, signal handling, graceful HTTP shutdown, heartbeats.44package svc4546import (47	"context"48	"errors"49	"log/slog"50	"net"51	"net/http"52	"os"53	"os/signal"54	"syscall"55	"time"5657	"github.com/google/uuid"58	"github.com/jackc/pgx/v5/pgxpool"59)6061// Init configures JSON logging and returns a context cancelled by SIGINT/SIGTERM.62func Init(service string) (context.Context, context.CancelFunc) {63	slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo})).With("service", service))64	return signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)65}6667// ServeHTTP runs srv until ctx is cancelled, then drains connections.68func ServeHTTP(ctx context.Context, srv *http.Server, ln net.Listener) error {69	errc := make(chan error, 1)70	go func() { errc <- srv.Serve(ln) }()71	select {72	case err := <-errc:73		return err74	case <-ctx.Done():75	}76	sctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)77	defer cancel()78	if err := srv.Shutdown(sctx); err != nil {79		srv.Close()80	}81	if err := <-errc; err != nil && !errors.Is(err, http.ErrServerClosed) {82		return err83	}84	return nil85}8687// Heartbeat records liveness of a backend service every 10 s until ctx ends.88// detail is called on each beat and may return nil.89func Heartbeat(ctx context.Context, pool *pgxpool.Pool, service, version string, detail func() map[string]any) {90	instance := uuid.NewString()91	started := time.Now().UTC()92	beat := func() {93		d := map[string]any{}94		if detail != nil {95			if v := detail(); v != nil {96				d = v97			}98		}99		c, cancel := context.WithTimeout(ctx, 5*time.Second)100		defer cancel()101		if _, err := pool.Exec(c, `insert into service_heartbeats(service, instance, version, started_at, beat_at, detail)102			values ($1,$2,$3,$4,now(),$5)103			on conflict (service) do update set instance=excluded.instance, version=excluded.version,104				started_at=excluded.started_at, beat_at=excluded.beat_at, detail=excluded.detail`,105			service, instance, version, started, d); err != nil && ctx.Err() == nil {106			slog.Warn("heartbeat failed", "err", err)107		}108	}109	beat()110	t := time.NewTicker(10 * time.Second)111	defer t.Stop()112	for {113		select {114		case <-ctx.Done():115			return116		case <-t.C:117			beat()118		}119	}120}121
Files main
Menu

Theme