TExcelTAD
Home › DevOps Capstone: Ship a Production Service › Mini Project: Ship It End to End

Mini Project: Ship It End to End

The capstone's final check: every artifact you built, in one workspace, verified by one script, then deployed for real on your machine. If verify-all.sh passes here and the deployment steps work on your laptop, you have finished the course, and you have the core of your portfolio piece.

Definition of done

# Requirement Checked by
1 linkly builds, is formatted and vetted, and passes unit and integration tests under the race detector make lint test integration
2 no reachable known vulnerabilities; no HIGH/CRITICAL dependency CVEs, misconfigurations or secrets in the repository make vuln scan
3 a static, version-stamped binary for the distroless image make build
4 the chart lints and renders valid Kubernetes, Gateway API and Prometheus Operator objects for staging and production helm lint, helm template, kubeconform -strict
5 the local platform's OpenTofu is formatted, valid and tested tofu fmt, tofu validate, tofu test
6 the SLO rules are valid and their unit tests pass promtool check rules, promtool test rules
7 it deploys through Argo CD on a kind or k3d cluster, a link can be created and followed through the Gateway, and the dashboard shows the traffic the deployment steps below (on your machine)
8 a bad release is rolled back with git revert, and everything is torn down Deploy, Roll Back & Tear Down

Verify everything

The session lays out the workspace exactly as your repositories are laid out (linkly/ with the app, chart and monitoring rules; linkly-infra/local/platform/), starts PostgreSQL and Redis, and runs a verify-all.sh that checks requirements 1 to 6, printing one line per check. It is long because it is the whole project; every file in it comes from an earlier lesson, unchanged.

bash · try it yourself
initdb -D pgdata -U linkly --auth=trust >/dev/null
mkdir -p pgrun
pg_ctl -D pgdata -o "-k /home/learner/pgrun -c listen_addresses=" -l pg.log start >/dev/null
createdb linkly
redis-server --port 6379 --bind 127.0.0.1 --daemonize yes --dir /home/learner
mkdir linkly && cd linkly
cat > main.go <<'EOF'
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/redis/go-redis/v9"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
	"go.opentelemetry.io/otel/propagation"
	"go.opentelemetry.io/otel/sdk/resource"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
)

// version is stamped at build time: go build -ldflags "-X main.version=1.4.0"
var version = "dev"

type config struct {
	Addr, DatabaseURL, RedisAddr, BaseURL, LogLevel, Traces string
	CacheTTL, ShutdownGrace                                 time.Duration
}

func env(key, def string) string {
	if v := os.Getenv(key); v != "" {
		return v
	}
	return def
}

// loadConfig reads the twelve-factor configuration from the environment.
func loadConfig() (config, error) {
	c := config{
		Addr:        env("LISTEN_ADDR", ":8080"),
		DatabaseURL: env("DATABASE_URL", ""),
		RedisAddr:   env("REDIS_ADDR", "localhost:6379"),
		BaseURL:     env("BASE_URL", "http://localhost:8080"),
		LogLevel:    env("LOG_LEVEL", "info"),
		Traces:      env("OTEL_TRACES_EXPORTER", "none"),
	}
	var err error
	if c.CacheTTL, err = time.ParseDuration(env("CACHE_TTL", "1h")); err != nil {
		return c, fmt.Errorf("CACHE_TTL: %w", err)
	}
	if c.ShutdownGrace, err = time.ParseDuration(env("SHUTDOWN_GRACE", "10s")); err != nil {
		return c, fmt.Errorf("SHUTDOWN_GRACE: %w", err)
	}
	if c.DatabaseURL == "" {
		return c, errors.New("DATABASE_URL is required")
	}
	return c, nil
}

func main() {
	cfg, err := loadConfig()
	var level slog.Level
	if err == nil {
		err = level.UnmarshalText([]byte(cfg.LogLevel))
	}
	log := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: level}))
	if err == nil {
		err = run(cfg, log)
	}
	if err != nil {
		log.Error("linkly stopped", "err", err)
		os.Exit(1)
	}
}

func run(cfg config, log *slog.Logger) error {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	shutdownTracing, err := setupTracing(cfg.Traces, os.Stderr)
	if err != nil {
		return err
	}
	defer shutdownTracing(context.Background())

	db, err := pgxpool.New(ctx, cfg.DatabaseURL)
	if err != nil {
		return fmt.Errorf("database: %w", err)
	}
	defer db.Close()
	if err := migrate(ctx, db); err != nil {
		return fmt.Errorf("migrate: %w", err)
	}
	redis.SetLogger(redisLogger{log})
	rdb := newRedis(cfg.RedisAddr)
	defer rdb.Close()

	app := newApp(pgStore{db}, rdb, cfg, log, prometheus.DefaultRegisterer, prometheus.DefaultGatherer)
	srv := &http.Server{Addr: cfg.Addr, Handler: app.Handler(), ReadHeaderTimeout: 5 * time.Second,
		ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second}
	errc := make(chan error, 1)
	go func() {
		log.Info("listening", "addr", cfg.Addr, "version", version)
		errc <- srv.ListenAndServe()
	}()
	select {
	case err := <-errc:
		return err
	case <-ctx.Done():
	}
	log.Info("shutting down", "grace", cfg.ShutdownGrace.String())
	app.draining.Store(true) // /readyz now answers 503
	sctx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownGrace)
	defer cancel()
	if err := srv.Shutdown(sctx); err != nil {
		return err
	}
	log.Info("stopped")
	return nil
}

// newRedis takes host:port or a redis:// or rediss:// (TLS) URL. The short timeouts keep
// the cache from slowing requests down when Redis is unwell.
func newRedis(addr string) *redis.Client {
	opt, err := redis.ParseURL(addr)
	if err != nil {
		opt = &redis.Options{Addr: addr}
	}
	opt.DialTimeout, opt.DialerRetries, opt.MaxRetries = time.Second, 1, 1
	opt.ReadTimeout, opt.WriteTimeout = 300*time.Millisecond, 300*time.Millisecond
	return redis.NewClient(opt)
}

// redisLogger sends go-redis's own messages to the JSON log instead of plain stderr.
type redisLogger struct{ log *slog.Logger }

func (r redisLogger) Printf(ctx context.Context, format string, v ...any) {
	r.log.WarnContext(ctx, fmt.Sprintf(format, v...), "component", "go-redis")
}

// setupTracing installs the OpenTelemetry SDK; "console" writes spans as JSON to w.
func setupTracing(exporter string, w io.Writer) (func(context.Context) error, error) {
	res := resource.NewSchemaless(semconv.ServiceName("linkly"), semconv.ServiceVersion(version))
	opts := []sdktrace.TracerProviderOption{sdktrace.WithResource(res)}
	switch exporter {
	case "none":
	case "console":
		exp, err := stdouttrace.New(stdouttrace.WithWriter(w))
		if err != nil {
			return nil, err
		}
		opts = append(opts, sdktrace.WithSyncer(exp))
	default:
		return nil, fmt.Errorf("OTEL_TRACES_EXPORTER=%q: this build supports none and console", exporter)
	}
	tp := sdktrace.NewTracerProvider(opts...)
	otel.SetTracerProvider(tp)
	otel.SetTextMapPropagator(propagation.TraceContext{})
	return tp.Shutdown, nil
}
EOF
cat > app.go <<'EOF'
package main

import (
	"context"
	"crypto/rand"
	"encoding/json"
	"errors"
	"log/slog"
	"net/http"
	"net/url"
	"regexp"
	"runtime"
	"strconv"
	"strings"
	"sync/atomic"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/redis/go-redis/v9"
	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
	"go.opentelemetry.io/otel/attribute"
	semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
	"go.opentelemetry.io/otel/trace"
)

type App struct {
	store    Store
	cache    *redis.Client
	ttl      time.Duration
	baseURL  string
	log      *slog.Logger
	newCode  func() string
	draining atomic.Bool
	metrics  http.Handler

	requests  *prometheus.CounterVec
	duration  *prometheus.HistogramVec
	cacheReqs *prometheus.CounterVec
	created   prometheus.Counter
}

func newApp(store Store, cache *redis.Client, cfg config, log *slog.Logger,
	reg prometheus.Registerer, g prometheus.Gatherer) *App {
	f := promauto.With(reg)
	a := &App{store: store, cache: cache, ttl: cfg.CacheTTL, baseURL: cfg.BaseURL, log: log,
		newCode: randomCode, metrics: promhttp.HandlerFor(g, promhttp.HandlerOpts{}),
		requests: f.NewCounterVec(prometheus.CounterOpts{Name: "http_requests_total",
			Help: "HTTP requests by route and status code."}, []string{"route", "code"}),
		duration: f.NewHistogramVec(prometheus.HistogramOpts{Name: "http_request_duration_seconds",
			Help:    "Time to handle a request, by route.",
			Buckets: []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5}}, []string{"route"}),
		cacheReqs: f.NewCounterVec(prometheus.CounterOpts{Name: "linkly_cache_requests_total",
			Help: "Redis lookups for redirects, by result (hit, miss, error)."}, []string{"result"}),
		created: f.NewCounter(prometheus.CounterOpts{Name: "linkly_links_created_total",
			Help: "Short links created."}),
	}
	f.NewGaugeVec(prometheus.GaugeOpts{Name: "linkly_build_info", Help: "Always 1; labels describe the build."},
		[]string{"version", "goversion"}).WithLabelValues(version, runtime.Version()).Set(1)
	return a
}

func (a *App) Handler() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("POST /links", a.createLink)
	mux.HandleFunc("GET /{code}", a.redirect)
	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("ok\n")) })
	mux.HandleFunc("GET /readyz", a.readyz)
	mux.Handle("GET /metrics", a.metrics)
	notProbe := func(r *http.Request) bool { return !quiet(r.URL.Path) }
	return otelhttp.NewHandler(a.observe(mux), "linkly", otelhttp.WithFilter(notProbe))
}

func quiet(route string) bool {
	return route == "/healthz" || route == "/readyz" || route == "/metrics"
}

// observe records metrics, names the trace span and logs every request, all by route template.
func (a *App) observe(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
		next.ServeHTTP(rec, r)
		route := "unmatched" // r.Pattern is "GET /{code}" once the mux has matched, "" otherwise
		if _, p, ok := strings.Cut(r.Pattern, " "); ok {
			route = p
		}
		a.requests.WithLabelValues(route, strconv.Itoa(rec.status)).Inc()
		a.duration.WithLabelValues(route).Observe(time.Since(start).Seconds())
		span := trace.SpanFromContext(r.Context())
		span.SetName(r.Method + " " + route)
		span.SetAttributes(semconv.HTTPRoute(route))
		level := slog.LevelInfo
		if quiet(route) {
			level = slog.LevelDebug
		} else if rec.status >= 500 {
			level = slog.LevelError
		}
		a.log.LogAttrs(r.Context(), level, "request", slog.String("method", r.Method),
			slog.String("route", route), slog.Int("status", rec.status),
			slog.String("trace_id", span.SpanContext().TraceID().String()))
	})
}

type statusRecorder struct {
	http.ResponseWriter
	status int
}

func (s *statusRecorder) WriteHeader(code int) { s.status = code; s.ResponseWriter.WriteHeader(code) }

var codeRE = regexp.MustCompile(`^[A-Za-z0-9_-]{3,32}

  
    
    
    Mini Project: Ship It End to End - DevOps Capstone: Ship a Production Service · ExcelTAD
    
    
    
    
    
    
    
    
    
    
    
    
    
    
  
  
    )

const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"

// randomCode returns 7 random characters from a 64-letter alphabet (b&63 has no modulo bias).
// They come from crypto/rand, so codes can't be predicted.
func randomCode() string {
	b := make([]byte, 7)
	if _, err := rand.Read(b); err != nil {
		panic(err) // the OS random source failed: nothing sensible is left to do
	}
	for i := range b {
		b[i] = alphabet[b[i]&63]
	}
	return string(b)
}

func validateURL(raw string) error {
	if len(raw) > 2048 {
		return errors.New("url is longer than 2048 bytes")
	}
	u, err := url.Parse(raw)
	if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
		return errors.New("url must be an absolute http or https URL")
	}
	return nil
}

func (a *App) createLink(w http.ResponseWriter, r *http.Request) {
	var req struct{ URL, Code string }
	if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&req); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": `body must be JSON like {"url": "https://..."}`})
		return
	}
	if err := validateURL(req.URL); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
		return
	}
	if req.Code != "" && !codeRE.MatchString(req.Code) {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "code must be 3-32 of A-Z a-z 0-9 _ -"})
		return
	}
	code := req.Code
	for attempt := 1; ; attempt++ {
		if req.Code == "" {
			code = a.newCode()
		}
		err := a.store.Create(r.Context(), code, req.URL)
		if err == nil {
			break
		}
		if errors.Is(err, ErrExists) && req.Code == "" && attempt < 3 {
			continue // a random code collided: draw again
		}
		if errors.Is(err, ErrExists) {
			writeJSON(w, http.StatusConflict, map[string]string{"error": "code already taken"})
			return
		}
		a.fail(w, r, err)
		return
	}
	a.created.Inc()
	writeJSON(w, http.StatusCreated, map[string]string{"code": code, "short_url": a.baseURL + "/" + code, "url": req.URL})
}

// redirect reads through the cache: Redis first, PostgreSQL on a miss (or when Redis is down).
func (a *App) redirect(w http.ResponseWriter, r *http.Request) {
	code, ctx := r.PathValue("code"), r.Context()
	if !codeRE.MatchString(code) {
		http.NotFound(w, r)
		return
	}
	key := "link:" + code
	target, err := a.cache.Get(ctx, key).Result()
	result := "hit"
	if errors.Is(err, redis.Nil) {
		result = "miss"
	} else if err != nil {
		result = "error"
		a.log.WarnContext(ctx, "cache read failed", "err", err)
	}
	a.cacheReqs.WithLabelValues(result).Inc()
	trace.SpanFromContext(ctx).SetAttributes(attribute.String("linkly.cache", result))
	if result != "hit" {
		if target, err = a.store.Get(ctx, code); errors.Is(err, ErrNotFound) {
			http.NotFound(w, r)
			return
		} else if err != nil {
			a.fail(w, r, err)
			return
		}
		if err := a.cache.Set(ctx, key, target, a.ttl).Err(); err != nil {
			a.log.WarnContext(ctx, "cache write failed", "err", err)
		}
	}
	http.Redirect(w, r, target, http.StatusFound)
}

// readyz fails only on the database: without Redis, linkly is slower but still correct.
func (a *App) readyz(w http.ResponseWriter, r *http.Request) {
	if a.draining.Load() {
		writeJSON(w, http.StatusServiceUnavailable, map[string]string{"status": "draining"})
		return
	}
	ctx, cancel := context.WithTimeout(r.Context(), time.Second)
	defer cancel()
	res, code := map[string]string{"status": "ready", "database": "up", "cache": "up"}, http.StatusOK
	if err := a.store.Ping(ctx); err != nil {
		a.log.WarnContext(ctx, "readiness: database", "err", err)
		res["status"], res["database"], code = "unavailable", "down", http.StatusServiceUnavailable
	}
	if err := a.cache.Ping(ctx).Err(); err != nil {
		a.log.WarnContext(ctx, "readiness: cache", "err", err)
		res["cache"] = "down"
	}
	writeJSON(w, code, res)
}

func (a *App) fail(w http.ResponseWriter, r *http.Request, err error) {
	a.log.ErrorContext(r.Context(), "request failed", "err", err)
	writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})
}

func writeJSON(w http.ResponseWriter, code int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)
	json.NewEncoder(w).Encode(v)
}
EOF
cat > store.go <<'EOF'
package main

import (
	"context"
	"errors"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgconn"
	"github.com/jackc/pgx/v5/pgxpool"
)

var (
	ErrNotFound = errors.New("link not found")
	ErrExists   = errors.New("code already exists")
)

// Store is where links live; pgStore in production, an in-memory fake in unit tests.
type Store interface {
	Create(ctx context.Context, code, url string) error
	Get(ctx context.Context, code string) (string, error)
	Ping(ctx context.Context) error
}

const schema = `CREATE TABLE IF NOT EXISTS links (
  code       text PRIMARY KEY,
  url        text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now())`

func migrate(ctx context.Context, db *pgxpool.Pool) error {
	_, err := db.Exec(ctx, schema)
	return err
}

type pgStore struct{ db *pgxpool.Pool }

func (s pgStore) Create(ctx context.Context, code, url string) error {
	_, err := s.db.Exec(ctx, `INSERT INTO links (code, url) VALUES ($1, $2)`, code, url)
	var pgErr *pgconn.PgError
	if errors.As(err, &pgErr) && pgErr.Code == "23505" { // unique_violation
		return ErrExists
	}
	return err
}

func (s pgStore) Get(ctx context.Context, code string) (string, error) {
	var url string
	err := s.db.QueryRow(ctx, `SELECT url FROM links WHERE code = $1`, code).Scan(&url)
	if errors.Is(err, pgx.ErrNoRows) {
		return "", ErrNotFound
	}
	return url, err
}

func (s pgStore) Ping(ctx context.Context) error { return s.db.Ping(ctx) }
EOF
cat > app_test.go <<'EOF'
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/alicebob/miniredis/v2"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/testutil"
	"github.com/redis/go-redis/v9"
)

// memStore is the in-memory fake Store for unit tests.
type memStore struct {
	mu    sync.Mutex
	links map[string]string
	down  bool
}

func (m *memStore) Create(_ context.Context, code, url string) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	if _, ok := m.links[code]; ok {
		return ErrExists
	}
	m.links[code] = url
	return nil
}

func (m *memStore) Get(_ context.Context, code string) (string, error) {
	m.mu.Lock()
	defer m.mu.Unlock()
	if url, ok := m.links[code]; ok {
		return url, nil
	}
	return "", ErrNotFound
}

func (m *memStore) Ping(context.Context) error {
	if m.down {
		return errors.New("connection refused")
	}
	return nil
}

func newTestApp(t *testing.T) (*App, *memStore, *miniredis.Miniredis, *prometheus.Registry) {
	mr := miniredis.RunT(t)
	store := &memStore{links: map[string]string{}}
	reg := prometheus.NewRegistry()
	log := slog.New(slog.NewJSONHandler(io.Discard, nil))
	redis.SetLogger(redisLogger{log})
	cfg := config{BaseURL: "https://lnk.test", CacheTTL: time.Hour}
	a := newApp(store, newRedis(mr.Addr()), cfg, log, reg, reg)
	n := 0
	a.newCode = func() string { n++; return fmt.Sprintf("code%03d", n) }
	return a, store, mr, reg
}

func do(h http.Handler, method, path, body string) *httptest.ResponseRecorder {
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, httptest.NewRequest(method, path, strings.NewReader(body)))
	return rec
}

func TestCreateAndRedirect(t *testing.T) {
	a, _, mr, _ := newTestApp(t)
	h := a.Handler()
	rec := do(h, "POST", "/links", `{"url": "https://go.dev/doc/"}`)
	want := `{"code":"code001","short_url":"https://lnk.test/code001","url":"https://go.dev/doc/"}` + "\n"
	if rec.Code != http.StatusCreated || rec.Body.String() != want {
		t.Fatalf("POST /links = %d %s", rec.Code, rec.Body)
	}
	for i := 0; i < 2; i++ { // the first redirect misses the cache, the second hits it
		rec = do(h, "GET", "/code001", "")
		if rec.Code != http.StatusFound || rec.Header().Get("Location") != "https://go.dev/doc/" {
			t.Fatalf("GET /code001 = %d %q", rec.Code, rec.Header().Get("Location"))
		}
	}
	for result, want := range map[string]float64{"miss": 1, "hit": 1} {
		if got := testutil.ToFloat64(a.cacheReqs.WithLabelValues(result)); got != want {
			t.Errorf("cache %s = %v, want %v", result, got, want)
		}
	}
	if ttl := mr.TTL("link:code001"); ttl != time.Hour {
		t.Errorf("cache TTL = %v, want 1h", ttl)
	}
}

func TestBadRequests(t *testing.T) {
	a, _, _, _ := newTestApp(t)
	h := a.Handler()
	do(h, "POST", "/links", `{"url": "https://example.com", "code": "docs"}`)
	for _, tc := range []struct {
		method, path, body string
		want               int
	}{
		{"POST", "/links", `not json`, 400},
		{"POST", "/links", `{"url": "ftp://example.com/file"}`, 400},
		{"POST", "/links", `{"url": "/relative/path"}`, 400},
		{"POST", "/links", `{"url": "https://example.com", "code": "a b"}`, 400},
		{"POST", "/links", `{"url": "https://example.org", "code": "docs"}`, 409},
		{"GET", "/nope", "", 404},
		{"GET", "/x", "", 404}, // too short to be a code: rejected before any lookup
		{"DELETE", "/links", "", 405},
	} {
		if rec := do(h, tc.method, tc.path, tc.body); rec.Code != tc.want {
			t.Errorf("%s %s %s = %d, want %d", tc.method, tc.path, tc.body, rec.Code, tc.want)
		}
	}
}

func TestRedisDownFallsBackToDatabase(t *testing.T) {
	a, store, mr, _ := newTestApp(t)
	h := a.Handler()
	store.links["docs"] = "https://go.dev/doc/"
	mr.Close()
	if rec := do(h, "GET", "/docs", ""); rec.Code != http.StatusFound {
		t.Fatalf("redirect without Redis = %d, want 302", rec.Code)
	}
	if got := testutil.ToFloat64(a.cacheReqs.WithLabelValues("error")); got != 1 {
		t.Errorf("cache errors = %v, want 1", got)
	}
	if rec := do(h, "GET", "/readyz", ""); rec.Code != http.StatusOK {
		t.Errorf("readyz without Redis = %d, want 200 (the cache is optional)", rec.Code)
	}
}

func TestReadiness(t *testing.T) {
	a, store, _, _ := newTestApp(t)
	h := a.Handler()
	store.down = true
	if rec := do(h, "GET", "/readyz", ""); rec.Code != http.StatusServiceUnavailable {
		t.Errorf("readyz without the database = %d, want 503", rec.Code)
	}
	store.down = false
	a.draining.Store(true)
	if rec := do(h, "GET", "/readyz", ""); rec.Code != http.StatusServiceUnavailable {
		t.Errorf("readyz while draining = %d, want 503", rec.Code)
	}
}

func TestMetricsUseRouteTemplates(t *testing.T) {
	a, store, _, reg := newTestApp(t)
	h := a.Handler()
	store.links["abc"] = "https://example.com"
	do(h, "GET", "/abc", "")
	do(h, "GET", "/zzz", "")
	do(h, "GET", "/a/b/c", "")
	want := `
# HELP http_requests_total HTTP requests by route and status code.
# TYPE http_requests_total counter
http_requests_total{code="302",route="/{code}"} 1
http_requests_total{code="404",route="/{code}"} 1
http_requests_total{code="404",route="unmatched"} 1
`
	if err := testutil.GatherAndCompare(reg, strings.NewReader(want), "http_requests_total"); err != nil {
		t.Error(err)
	}
}
EOF
cat > integration_test.go <<'EOF'
//go:build integration

package main

import (
	"context"
	"io"
	"log/slog"
	"os"
	"testing"
	"time"

	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/prometheus/client_golang/prometheus"
)

// Run with real servers: DATABASE_URL=... REDIS_ADDR=... go test -tags integration ./...
func TestWithPostgresAndRedis(t *testing.T) {
	dsn, addr := os.Getenv("DATABASE_URL"), os.Getenv("REDIS_ADDR")
	if dsn == "" || addr == "" {
		t.Skip("DATABASE_URL and REDIS_ADDR are not set")
	}
	ctx := context.Background()
	db, err := pgxpool.New(ctx, dsn)
	if err != nil {
		t.Fatal(err)
	}
	defer db.Close()
	if err := migrate(ctx, db); err != nil {
		t.Fatal(err)
	}
	db.Exec(ctx, `DELETE FROM links WHERE code LIKE 'it-%'`)
	rdb := newRedis(addr)
	defer rdb.Close()
	rdb.Del(ctx, "link:it-docs")

	reg := prometheus.NewRegistry()
	cfg := config{BaseURL: "https://lnk.test", CacheTTL: time.Minute}
	h := newApp(pgStore{db}, rdb, cfg, slog.New(slog.NewJSONHandler(io.Discard, nil)), reg, reg).Handler()

	if rec := do(h, "POST", "/links", `{"url": "https://go.dev/doc/", "code": "it-docs"}`); rec.Code != 201 {
		t.Fatalf("create = %d %s", rec.Code, rec.Body)
	}
	if rec := do(h, "POST", "/links", `{"url": "https://example.com", "code": "it-docs"}`); rec.Code != 409 {
		t.Errorf("duplicate = %d, want 409 from the primary key", rec.Code)
	}
	if rec := do(h, "GET", "/it-docs", ""); rec.Code != 302 {
		t.Fatalf("redirect = %d", rec.Code)
	}
	if ttl := rdb.TTL(ctx, "link:it-docs").Val(); ttl <= 0 || ttl > time.Minute {
		t.Errorf("cached TTL = %v", ttl)
	}
	if rec := do(h, "GET", "/readyz", ""); rec.Code != 200 {
		t.Errorf("readyz = %d %s", rec.Code, rec.Body)
	}
}
EOF
cat > Makefile <<'MK'
VERSION ?= $(shell git describe --tags --always --dirty)
LDFLAGS := -s -w -X main.version=$(VERSION)

.PHONY: ci lint test integration vuln build scan

ci: lint test integration vuln build scan

lint:
	@test -z "$(gofmt -l .)" || { echo "gofmt needed:"; gofmt -l .; exit 1; }
	go vet ./...

test:
	go test -race ./...

integration:
	go test -race -tags integration -run WithPostgres ./...

vuln:
	govulncheck ./...

build:
	CGO_ENABLED=0 go build -trimpath -ldflags "$(LDFLAGS)" -o dist/linkly .
	@echo "built dist/linkly $(VERSION)"

scan:
	trivy fs -q --scanners vuln,secret,misconfig --severity HIGH,CRITICAL --exit-code 1 .
MK
cat > Dockerfile <<'X'
# syntax=docker/dockerfile:1
FROM golang:1.27.3 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY *.go ./
ARG VERSION=dev
RUN CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X main.version=${VERSION}" -o /out/linkly .

FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/linkly /linkly
USER nonroot:nonroot
EXPOSE 8080
ENTRYPOINT ["/linkly"]
X
printf '# Kubernetes uses the chart probes; distroless has no shell for a HEALTHCHECK.\nDS-0026\n' > .trivyignore
printf '/dist/\n' > .gitignore
mkdir -p chart/linkly/templates && cd chart/linkly
cat > Chart.yaml <<'YAML'
apiVersion: v2
name: linkly
description: linkly, a link shortener (Go, PostgreSQL, Redis)
type: application
version: 0.0.0-dev
appVersion: "0.0.0-dev"
kubeVersion: ">= 1.30.0-0"
YAML
cat > values.yaml <<'YAML'
replicaCount: 2
image:
  repository: ghcr.io/acme/linkly
  tag: ""          # defaults to appVersion
  digest: ""       # sha256:...; wins over the tag when set
config:
  logLevel: info
  baseUrl: https://lnk.example.com
  redisAddr: linkly-redis:6379
  cacheTTL: 1h
database:
  existingSecret: linkly-db   # created outside the chart (CloudNativePG, External Secrets)
  secretKey: url
service:
  port: 80
httpRoute:
  enabled: true
  parentRefs: [{name: public, namespace: gateway-system}]
  hostnames: [lnk.example.com]
autoscaling:
  enabled: false
  minReplicas: 2
  maxReplicas: 10
  targetCPUUtilizationPercentage: 70
podDisruptionBudget:
  enabled: true
  maxUnavailable: 1
serviceMonitor:
  enabled: false
  interval: 30s
networkPolicy:
  enabled: true
  ingressNamespaces: [gateway-system, monitoring]
terminationGracePeriodSeconds: 30
preStopSleepSeconds: 5
resources:
  requests: {cpu: 100m, memory: 64Mi}
  limits: {memory: 128Mi}
YAML
cat > templates/_helpers.tpl <<'YAML'
{{- define "linkly.fullname" -}}
{{- if contains .Chart.Name .Release.Name }}{{ .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}{{ printf "%s-%s" .Release.Name .Chart.Name | trunc 63 | trimSuffix "-" }}{{ end }}
{{- end }}
{{- define "linkly.selectorLabels" -}}
app.kubernetes.io/name: {{ .Chart.Name }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
{{- define "linkly.labels" -}}
{{ include "linkly.selectorLabels" . }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
helm.sh/chart: {{ printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" }}
{{- end }}
{{- define "linkly.image" -}}
{{- if .Values.image.digest }}{{ .Values.image.repository }}@{{ .Values.image.digest }}
{{- else }}{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}{{ end }}
{{- end }}
YAML
cat > templates/configmap.yaml <<'YAML'
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
data:
  LISTEN_ADDR: ":8080"
  LOG_LEVEL: {{ .Values.config.logLevel | quote }}
  BASE_URL: {{ .Values.config.baseUrl | quote }}
  REDIS_ADDR: {{ .Values.config.redisAddr | quote }}
  CACHE_TTL: {{ .Values.config.cacheTTL | quote }}
  SHUTDOWN_GRACE: "{{ sub (sub .Values.terminationGracePeriodSeconds .Values.preStopSleepSeconds) 5 }}s"
YAML
cat > templates/deployment.yaml <<'YAML'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  {{- if not .Values.autoscaling.enabled }}
  replicas: {{ .Values.replicaCount }}
  {{- end }}
  revisionHistoryLimit: 5
  strategy: {rollingUpdate: {maxSurge: 25%, maxUnavailable: 0}}
  selector:
    matchLabels: {{- include "linkly.selectorLabels" . | nindent 6 }}
  template:
    metadata:
      labels: {{- include "linkly.selectorLabels" . | nindent 8 }}
      annotations:
        checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum | trunc 16 }}
    spec:
      automountServiceAccountToken: false
      terminationGracePeriodSeconds: {{ .Values.terminationGracePeriodSeconds }}
      securityContext: {runAsNonRoot: true, runAsUser: 65532, runAsGroup: 65532, seccompProfile: {type: RuntimeDefault}}
      topologySpreadConstraints:
        - maxSkew: 1
          topologyKey: kubernetes.io/hostname
          whenUnsatisfiable: ScheduleAnyway
          labelSelector:
            matchLabels: {{- include "linkly.selectorLabels" . | nindent 14 }}
      containers:
        - name: linkly
          image: {{ include "linkly.image" . | quote }}
          ports: [{name: http, containerPort: 8080}]
          envFrom: [{configMapRef: {name: {{ include "linkly.fullname" . }}}}]
          env:
            - name: DATABASE_URL
              valueFrom: {secretKeyRef: {name: {{ .Values.database.existingSecret }}, key: {{ .Values.database.secretKey }}}}
          readinessProbe: {httpGet: {path: /readyz, port: http}, periodSeconds: 5, failureThreshold: 2}
          livenessProbe: {httpGet: {path: /healthz, port: http}, periodSeconds: 10, failureThreshold: 3}
          lifecycle:
            preStop: {sleep: {seconds: {{ .Values.preStopSleepSeconds }}}}
          resources: {{- toYaml .Values.resources | nindent 12 }}
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities: {drop: [ALL]}
YAML
cat > templates/service.yaml <<'YAML'
apiVersion: v1
kind: Service
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  selector: {{- include "linkly.selectorLabels" . | nindent 4 }}
  ports: [{name: http, port: {{ .Values.service.port }}, targetPort: http}]
YAML
cat > templates/httproute.yaml <<'YAML'
{{- if .Values.httpRoute.enabled }}
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  parentRefs: {{- toYaml .Values.httpRoute.parentRefs | nindent 4 }}
  hostnames: {{- toYaml .Values.httpRoute.hostnames | nindent 4 }}
  rules:
    - matches: [{path: {type: PathPrefix, value: /}}]
      backendRefs: [{name: {{ include "linkly.fullname" . }}, port: {{ .Values.service.port }}}]
{{- end }}
YAML
cat > templates/hpa.yaml <<'YAML'
{{- if .Values.autoscaling.enabled }}
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  scaleTargetRef: {apiVersion: apps/v1, kind: Deployment, name: {{ include "linkly.fullname" . }}}
  minReplicas: {{ .Values.autoscaling.minReplicas }}
  maxReplicas: {{ .Values.autoscaling.maxReplicas }}
  metrics:
    - type: Resource
      resource: {name: cpu, target: {type: Utilization, averageUtilization: {{ .Values.autoscaling.targetCPUUtilizationPercentage }}}}
{{- end }}
YAML
cat > templates/pdb.yaml <<'YAML'
{{- if .Values.podDisruptionBudget.enabled }}
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  maxUnavailable: {{ .Values.podDisruptionBudget.maxUnavailable }}
  selector:
    matchLabels: {{- include "linkly.selectorLabels" . | nindent 6 }}
{{- end }}
YAML
cat > templates/networkpolicy.yaml <<'YAML'
{{- if .Values.networkPolicy.enabled }}
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  podSelector:
    matchLabels: {{- include "linkly.selectorLabels" . | nindent 6 }}
  policyTypes: [Ingress]
  ingress:
    - from:
        {{- range .Values.networkPolicy.ingressNamespaces }}
        - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: {{ . }}}}
        {{- end }}
      ports: [{port: http}]
{{- end }}
YAML
cat > templates/servicemonitor.yaml <<'YAML'
{{- if .Values.serviceMonitor.enabled }}
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  selector:
    matchLabels: {{- include "linkly.selectorLabels" . | nindent 6 }}
  endpoints:
    - port: http
      path: /metrics
      interval: {{ .Values.serviceMonitor.interval }}
{{- end }}
YAML
cd ../..
mkdir -p monitoring && cd monitoring
cat > linkly-rules.yml <<'YAML'
groups:
  - name: linkly-recording
    rules:
      - record: job:http_requests:rate5m
        expr: sum by (job) (rate(http_requests_total{job="linkly"}[5m]))
      - record: job:slo_errors_per_request:ratio_rate5m
        expr: |
          sum by (job) (rate(http_requests_total{job="linkly",code=~"5.."}[5m]))
            / sum by (job) (rate(http_requests_total{job="linkly"}[5m]))
      - record: job:slo_errors_per_request:ratio_rate1h
        expr: |
          sum by (job) (rate(http_requests_total{job="linkly",code=~"5.."}[1h]))
            / sum by (job) (rate(http_requests_total{job="linkly"}[1h]))
      - record: job_route:http_request_duration_seconds:p99_5m
        expr: |
          histogram_quantile(0.99,
            sum by (job, route, le) (rate(http_request_duration_seconds_bucket{job="linkly"}[5m])))
      - record: job:linkly_cache_hits:ratio_rate5m
        expr: |
          sum by (job) (rate(linkly_cache_requests_total{job="linkly",result="hit"}[5m]))
            / sum by (job) (rate(linkly_cache_requests_total{job="linkly"}[5m]))
  - name: linkly-alerts
    rules:
      - alert: LinklyErrorBudgetBurn
        expr: |
          job:slo_errors_per_request:ratio_rate1h > (14.4 * 0.001)
          and job:slo_errors_per_request:ratio_rate5m > (14.4 * 0.001)
        labels: {severity: page}
        annotations:
          summary: "linkly is burning its 99.9% availability budget 14x too fast"
          runbook_url: https://github.com/acme/linkly/blob/main/docs/runbook.md#error-budget-burn
      - alert: LinklySlowRedirects
        expr: job_route:http_request_duration_seconds:p99_5m{route="/{code}"} > 0.25
        for: 10m
        labels: {severity: ticket}
        annotations:
          summary: "p99 redirect latency is {{ $value | humanizeDuration }}"
      - alert: LinklyCacheDegraded
        expr: sum by (job) (rate(linkly_cache_requests_total{job="linkly",result="error"}[5m])) > 0
        for: 5m
        labels: {severity: ticket}
        annotations:
          summary: "Redis errors: redirects are served from PostgreSQL"
YAML
cat > linkly-rules.test.yml <<'YAML'
rule_files: [linkly-rules.yml]
evaluation_interval: 1m
tests:
  - name: a burst of 5xx pages, a single error does not
    interval: 1m
    input_series:
      - series: 'http_requests_total{job="linkly",route="/{code}",code="302"}'
        values: '0+600x90'
      - series: 'http_requests_total{job="linkly",route="/{code}",code="500"}'
        values: '0x60 1 1 1 1 1 1 1 1 1 1 61+60x20'
    promql_expr_test:
      - expr: job:http_requests:rate5m
        eval_time: 30m
        exp_samples: [{labels: 'job:http_requests:rate5m{job="linkly"}', value: 10}]
    alert_rule_test:
      - eval_time: 70m
        alertname: LinklyErrorBudgetBurn
        exp_alerts: []
      - eval_time: 85m
        alertname: LinklyErrorBudgetBurn
        exp_alerts:
          - exp_labels: {job: linkly, severity: page}
            exp_annotations:
              summary: "linkly is burning its 99.9% availability budget 14x too fast"
              runbook_url: https://github.com/acme/linkly/blob/main/docs/runbook.md#error-budget-burn
  - name: Redis down for a while
    interval: 1m
    input_series:
      - series: 'linkly_cache_requests_total{job="linkly",result="hit"}'
        values: '0+540x30'
      - series: 'linkly_cache_requests_total{job="linkly",result="error"}'
        values: '0x10 0+300x20'
    promql_expr_test:
      - expr: job:linkly_cache_hits:ratio_rate5m
        eval_time: 25m
        exp_samples: [{labels: 'job:linkly_cache_hits:ratio_rate5m{job="linkly"}', value: 0.64285714285714285}]
    alert_rule_test:
      - eval_time: 14m
        alertname: LinklyCacheDegraded
        exp_alerts: []
      - eval_time: 18m
        alertname: LinklyCacheDegraded
        exp_alerts:
          - exp_labels: {job: linkly, severity: ticket}
            exp_annotations: {summary: "Redis errors: redirects are served from PostgreSQL"}
YAML
cd ../..
mkdir -p linkly-infra/local/platform/tests && cd linkly-infra/local/platform
cat > main.tf <<'X'
terraform {
  required_version = ">= 1.10"
  required_providers {
    helm       = { source = "hashicorp/helm", version = "~> 3.0" }
    kubernetes = { source = "hashicorp/kubernetes", version = "~> 3.0" }
  }
}

variable "kube_context" {
  type    = string
  default = "kind-linkly"
}

variable "environments" {
  type    = set(string)
  default = ["staging", "production"]
}

variable "addons" {
  description = "Platform add-ons, each pinned to an exact chart version."
  type = map(object({
    repository = string
    chart      = string
    version    = string
    namespace  = string
    values     = optional(any, {})
  }))
  validation {
    condition     = alltrue([for a in values(var.addons) : can(regex("^v?[0-9]+\\.[0-9]+\\.[0-9]+
quot;, a.version))]) error_message = "Pin every chart to an exact version (x.y.z), never a range or \"latest\"." } } provider "kubernetes" { config_path = "~/.kube/config" config_context = var.kube_context } provider "helm" { kubernetes = { config_path = "~/.kube/config" config_context = var.kube_context } } resource "helm_release" "addon" { for_each = var.addons name = each.key repository = each.value.repository chart = each.value.chart version = each.value.version namespace = each.value.namespace create_namespace = true values = [yamlencode(each.value.values)] wait = true timeout = 600 } resource "kubernetes_namespace_v1" "app" { for_each = var.environments metadata { name = "linkly-${each.key}" labels = { "app.kubernetes.io/part-of" = "linkly", env = each.key } } } # Redis per environment. It is a cache: one replica, no persistence, bounded memory. resource "kubernetes_deployment_v1" "redis" { for_each = var.environments metadata { name = "linkly-redis" namespace = kubernetes_namespace_v1.app[each.key].metadata[0].name } spec { replicas = 1 selector { match_labels = { app = "linkly-redis" } } template { metadata { labels = { app = "linkly-redis" } } spec { container { name = "redis" image = "redis:7.4" args = ["--save", "", "--appendonly", "no", "--maxmemory", "64mb", "--maxmemory-policy", "allkeys-lru"] port { container_port = 6379 } resources { requests = { cpu = "50m", memory = "80Mi" } limits = { memory = "96Mi" } } } } } } } resource "kubernetes_service_v1" "redis" { for_each = var.environments metadata { name = "linkly-redis" namespace = kubernetes_namespace_v1.app[each.key].metadata[0].name } spec { selector = { app = "linkly-redis" } port { port = 6379 target_port = 6379 } } } output "redis_addr" { value = { for env in var.environments : env => "linkly-redis.linkly-${env}.svc:6379" } } X cat > tests/platform.tftest.hcl <<'X' mock_provider "helm" {} mock_provider "kubernetes" {} variables { addons = { cnpg = { repository = "https://cloudnative-pg.github.io/charts", chart = "cloudnative-pg", version = "1.0.0", namespace = "cnpg-system" } monitoring = { repository = "https://prometheus-community.github.io/helm-charts", chart = "kube-prometheus-stack" version = "1.0.0", namespace = "monitoring" values = { prometheus = { prometheusSpec = { serviceMonitorSelectorNilUsesHelmValues = false } } } } } } run "plans_the_platform" { command = plan assert { condition = length(helm_release.addon) == 2 && helm_release.addon["cnpg"].namespace == "cnpg-system" error_message = "expected the two add-ons from the variables" } assert { condition = length(kubernetes_deployment_v1.redis) == 2 error_message = "expected one Redis per environment" } assert { condition = output.redis_addr["production"] == "linkly-redis.linkly-production.svc:6379" error_message = "unexpected Redis address" } } run "rejects_unpinned_charts" { command = plan variables { addons = { argocd = { repository = "https://argoproj.github.io/argo-helm", chart = "argo-cd", version = "latest", namespace = "argocd" } } } expect_failures = [var.addons] } X cd ../../.. cat > verify-all.sh <<'X' #!/usr/bin/env bash # verify-all.sh: requirements 1-6 of the capstone, one line per check set -uo pipefail failed=0 check() { local name=$1; shift if out=$("$@" 2>&1); then echo "PASS $name"; else echo "FAIL $name"; echo "$out" | tail -5 | sed 's/^/ /'; failed=1; fi } cd linkly check "1 lint (gofmt, go vet)" make -s lint check "1 unit tests (race)" make -s test check "1 integration tests (race)" make -s integration check "2 govulncheck" make -s vuln check "2 trivy: CVEs, misconfig, secrets" make -s scan check "3 static build" make -s build check "3 binary is static" sh -c 'file -b dist/linkly | grep -q "statically linked"' check "4 helm lint" helm lint chart/linkly --strict --quiet for env in staging production; do extra=""; [ $env = production ] && extra="--set autoscaling.enabled=true --set serviceMonitor.enabled=true" check "4 $env renders and validates" sh -c "helm template linkly chart/linkly -n linkly-$env $extra | kubeconform -strict -summary" done cd ../linkly-infra/local/platform check "5 tofu fmt" tofu fmt -check -recursive check "5 tofu init (provider mirror)" tofu init -backend=false check "5 tofu validate" tofu validate check "5 tofu test (mocked providers)" tofu test cd ../../../linkly check "6 promtool check rules" promtool check rules monitoring/linkly-rules.yml check "6 promtool test rules" promtool test rules monitoring/linkly-rules.test.yml exit $failed X chmod +x verify-all.sh cd linkly && go mod init github.com/acme/linkly >/dev/null 2>&1 && go mod tidy 2>/dev/null git init -q && git add . && git commit -qm "linkly 1.4.0" && git tag v1.4.0 && cd .. export DATABASE_URL="postgres:///linkly?host=/home/learner/pgrun" REDIS_ADDR=127.0.0.1:6379 ./verify-all.sh; echo "verify-all exit code: $?" env -u DATABASE_URL ./linkly/dist/linkly | jq -r '"release binary without DATABASE_URL: " + .msg + " (" + .err + ")"' tree --noreport -L 2 -I 'pgdata|pgrun|data|dist|*.log' linkly linkly-infra
PASS  1 lint (gofmt, go vet)
PASS  1 unit tests (race)
PASS  1 integration tests (race)
PASS  2 govulncheck
PASS  2 trivy: CVEs, misconfig, secrets
PASS  3 static build
PASS  3 binary is static
PASS  4 helm lint
PASS  4 staging renders and validates
PASS  4 production renders and validates
PASS  5 tofu fmt
PASS  5 tofu init (provider mirror)
PASS  5 tofu validate
PASS  5 tofu test (mocked providers)
PASS  6 promtool check rules
PASS  6 promtool test rules
verify-all exit code: 0
release binary without DATABASE_URL: linkly stopped (DATABASE_URL is required)
linkly
├── Dockerfile
├── Makefile
├── app.go
├── app_test.go
├── chart
│   └── linkly
├── go.mod
├── go.sum
├── integration_test.go
├── main.go
├── monitoring
│   ├── linkly-rules.test.yml
│   └── linkly-rules.yml
└── store.go
linkly-infra
└── local
    └── platform

Every requirement the sandbox can check passes, on a tagged commit, so make build stamped v1.4.0. The last check ran the static release binary without DATABASE_URL: it refused to start with a clear message, as designed. Put verify-all.sh (or its steps) into CI and the repository proves its own state on every pull request.

Deploy it (on your machine)

With Docker, kind, kubectl, Helm, OpenTofu and the Argo CD CLI installed, follow these steps in order; each one refers to the lesson with the details.

  1. Cluster and platform: apply linkly-infra/local/cluster and local/platform with your pinned chart versions (Local Track).
  2. Registry and image: build with --build-arg VERSION=$(git describe --tags), push to the local registry or kind load it (A Distroless Image, CI Against a Local Registry).
  3. Chart: helm package with the tag's version and push it to the local OCI registry.
  4. Deploy repository: point linkly-deploy's Applications and values at the local registries; commit; kubectl apply -n argocd -f argocd/root.yaml (GitOps Delivery).
  5. Smoke test: create a link and follow it through the Gateway with curl; check /readyz through a port-forward (Deploy, Roll Back & Tear Down).
  6. Observe: open Grafana (kubectl -n monitoring port-forward svc/monitoring-grafana 3000:80), import or provision the linkly dashboard, generate traffic (hey -n 2000 -c 20 …/<code>) and watch request rate, latency and the cache hit ratio move (SLO Alerts & Dashboards).
  7. Break it on purpose: scale Redis to zero (kubectl -n linkly-staging scale deploy/linkly-redis --replicas=0): redirects keep working, the cache panel shows errors, and LinklyCacheDegraded fires after five minutes. Scale it back.
  8. Release and roll back: tag v1.5.0 with a deliberate bug (say, /{code} returning 500 for one code), promote it, watch the burn-rate alert, revert the promotion commit, watch the recovery.
  9. Tear down and check nothing is left.

Record steps 5 to 8 on video: that two-minute recording is the most convincing part of the portfolio piece (Publishing It).

Grading yourself

Level You have
Done requirements 1 to 8 met on the local track
Strong plus: images signed and verified at admission; the migration Job (Exercise 6); rate limiting; a postmortem written for your step-8 incident
Outstanding plus: the cloud track applied and destroyed with a cost note in the README; multi-window burn-rate alerts with tests; a load test showing how many requests per second one pod handles and how the HPA responds

Extensions

  1. Canary releases. Replace the Deployment with an Argo Rollouts Rollout that shifts traffic through the Gateway API plugin and analyses the error ratio from Prometheus before promoting (Progressive Delivery).
  2. Preview environments. An Argo CD ApplicationSet with the pull-request generator deploys every PR of linkly into its own namespace and deletes it on merge.
  3. Policy as code in CI. Run Kyverno or Conftest against the rendered chart in verify-all.sh (no latest tags, resources required, runAsNonRoot) instead of relying on Trivy's defaults (Secrets & Policy).
  4. Cost visibility. Install OpenCost on the cloud track and add a cost-per-namespace panel to the dashboard.

Test yourself

What is the value of a single verify-all.sh that checks the app, chart, infrastructure and rules?

  1. It replaces the CI workflow's security settings
  2. One command proves the whole repository's state, locally and in CI, before anything reaches a cluster
  3. It deploys to production
  4. It makes builds faster

In deployment step 7, Redis is scaled to zero. What should you observe?

  1. linkly pods restart
  2. Redirects fail with 503
  3. Redirects keep working from PostgreSQL, cache errors appear on the dashboard, and the cache ticket alert fires after five minutes
  4. Argo CD scales Redis back immediately