initial commit

This commit is contained in:
TakuyaYagam1 committed 2026-10-05 14:23:31 +03:00
commit 88c14b627e
224 files changed
+17204

No files matched your search

+33
View File
@@ -0,0 +1,33 @@
.git
.github
.idea
.vscode
.DS_Store
Thumbs.db
.env
.env.*
# Local tools and caches
**/.venv
**/.venv-*
**/.cache
**/__pycache__
**/.pytest_cache
**/.mypy_cache
**/.ruff_cache
**/node_modules
# Build, test, and profiling output
bin/
dist/
tmp/
coverage/
**/*.exe
**/*.test
**/*.out
**/*.prof
**/*.cover
**/*.pprof
**/coverage.*
**/*.log
**/*.py[cod]
+14
View File
@@ -0,0 +1,14 @@
/.venv-quality/
/bin/
/dist/
/tmp/
/.cache/
# Go build and test output
*.exe
*.test
*.out
*.prof
*.cover
*.pprof
coverage.*
+140
View File
@@ -0,0 +1,140 @@
version: "2"
run:
timeout: 5m
tests: true
linters:
default: standard
enable:
- asasalint
- asciicheck
- bidichk
- bodyclose
- contextcheck
- copyloopvar
- durationcheck
- embeddedstructfieldcheck
- errname
- errorlint
- exhaustive
- exptostd
- fatcontext
- gocheckcompilerdirectives
- gochecknoinits
- gochecksumtype
- gocritic
- gocyclo
- gosec
- goprintffuncname
- inamedparam
- iotamixing
- loggercheck
- makezero
- mirror
- misspell
- musttag
- nakedret
- nilerr
- nilnesserr
- noctx
- nolintlint
- prealloc
- predeclared
- reassign
- revive
- rowserrcheck
- sloglint
- sqlclosecheck
- tagalign
- testableexamples
- testifylint
- thelper
- unconvert
- unparam
- unqueryvet
- wastedassign
- whitespace
- zerologlint
settings:
gocyclo:
min-complexity: 15
govet:
enable-all: true
disable:
- fieldalignment
- shadow
revive:
rules:
- name: blank-imports
- name: context-as-argument
- name: context-keys-type
- name: error-return
- name: error-strings
- name: error-naming
- name: var-declaration
- name: range
- name: receiver-naming
- name: time-naming
- name: indent-error-flow
- name: errorf
- name: empty-block
- name: superfluous-else
- name: unused-parameter
- name: unreachable-code
- name: redefines-builtin-id
nolintlint:
allow-unused: false
require-explanation: true
require-specific: true
gosec:
excludes:
- G104
staticcheck:
checks:
- all
testifylint:
enable-all: true
disable:
- go-require
exclusions:
generated: strict
paths:
- internal/adapter/primary/http/api/
- internal/adapter/secondary/ml/api/
- internal/adapter/secondary/postgres/sqlc/
- internal/bootstrap/wire_gen\.go$
- (^|/)mocks/
presets:
- comments
- common-false-positives
rules:
- path: _test\.go
linters:
- gocyclo
- gosec
- errcheck
- dupl
- path: _test\.go
text: net/http/httptest\.NewRequest must not be called
linters:
- noctx
formatters:
enable:
- gofmt
- goimports
exclusions:
generated: strict
paths:
- internal/adapter/primary/http/api/
- internal/adapter/secondary/ml/api/
- internal/adapter/secondary/postgres/sqlc/
- internal/bootstrap/wire_gen\.go$
- (^|/)mocks/
issues:
max-issues-per-linter: 0
max-same-issues: 0
+7
View File
@@ -0,0 +1,7 @@
[sqlfluff]
dialect = postgres
templater = raw
rules = AL04,AL05,AL08,AL10,AM01,AM04,AM07,AM08,AM09,CV02,CV05,CV06,CV12,PG01,PG02,RF01,RF07,ST03,ST08,ST10,ST11,ST12
large_file_skip_byte_limit = 0
large_file_skip_fail = true
max_parse_nodes = 500000
+16
View File
@@ -0,0 +1,16 @@
FROM golang:1.26.8-alpine AS build
WORKDIR /src/backend
COPY go.mod go.sum ./
RUN go mod download
COPY . ./
RUN CGO_ENABLED=0 GOOS=linux go build -buildvcs=false -trimpath -ldflags="-s -w" -o /out/app ./cmd/app
FROM gcr.io/distroless/static-debian12:nonroot
WORKDIR /
COPY --from=build /out/app /app
EXPOSE 8080 9090
USER nonroot:nonroot
ENTRYPOINT ["/app"]
+160
View File
@@ -0,0 +1,160 @@
SHELL := /usr/bin/env bash
.DEFAULT_GOAL := help
GO ?= go
GO_TOOL := $(GO) tool
API_DIR := $(abspath ../api)
ROOT_DIR := $(abspath ..)
API_PREPARED ?= 0
QUALITY_REQUIREMENTS ?= scripts/requirements-quality.txt
QUALITY_VENV ?= $(CURDIR)/.venv-quality
QUALITY_PYTHON ?= $(QUALITY_VENV)/bin/python
QUALITY_STAMP := $(QUALITY_VENV)/.deps.stamp
BOOTSTRAP_PYTHON ?= python3
##@ Build and run
.PHONY: build
build: ## Build the application binary
@mkdir -p bin
$(GO) build -buildvcs=false -trimpath -o bin/app ./cmd/app
.PHONY: run
run: ## Run the application with the current environment
$(GO) run ./cmd/app
.PHONY: deps install install-tools
deps: ## Download pinned Go module dependencies
$(GO) mod download
install install-tools: deps ## Install module-pinned Go tools without global changes
@$(GO) version
@$(GO_TOOL) ogen --version
@$(GO_TOOL) sqlc version
@$(GO_TOOL) golangci-lint version
.PHONY: tidy
tidy: ## Tidy application and tool dependencies
$(GO) mod tidy
.PHONY: clean
clean: ## Remove local build and test artifacts
rm -rf bin coverage.out coverage.html
##@ Code generation
.PHONY: generate gen
generate gen: ## Regenerate API, SQL, and dependency-injection code in dependency order
@if [ "$(API_PREPARED)" != "1" ]; then $(MAKE) -C "$(API_DIR)" bundle; fi
$(MAKE) --no-print-directory gen-openapi API_PREPARED=1
$(MAKE) --no-print-directory gen-ml API_PREPARED=1
$(MAKE) --no-print-directory gen-sqlc
$(MAKE) --no-print-directory gen-wire
$(MAKE) --no-print-directory mocks
.PHONY: gen-openapi
gen-openapi: ## Generate the public Ogen server adapter
@if [ "$(API_PREPARED)" != "1" ]; then $(MAKE) -C "$(API_DIR)" bundle; fi
$(GO_TOOL) ogen -config codegen/ogen.yml --target internal/adapter/primary/http/api --package api --clean ../api/core/openapi.bundle.yml
.PHONY: gen-ml
gen-ml: ## Generate the internal ML service client
@if [ "$(API_PREPARED)" != "1" ]; then $(MAKE) -C "$(API_DIR)" bundle; fi
$(GO_TOOL) ogen -config codegen/ogen-ml.yml --target internal/adapter/secondary/ml/api --package api --clean ../api/ml/openapi.bundle.yml
.PHONY: gen-sqlc
gen-sqlc: ## Generate PostgreSQL health query code
$(GO_TOOL) sqlc generate -f codegen/sqlc.yml
.PHONY: gen-wire
gen-wire: ## Generate the compile-time dependency graph
$(GO_TOOL) wire ./internal/bootstrap/...
.PHONY: mocks
mocks: ## Generate configured mocks when interfaces are selected
@if grep -Eq '^[[:space:]]*packages:[[:space:]]*\{\}[[:space:]]*(#.*)?$$' codegen/mockery.yml; then \
echo 'mockery: no interfaces selected in codegen/mockery.yml'; \
else \
$(GO_TOOL) mockery --config codegen/mockery.yml; \
fi
.PHONY: check-ogen-compat
check-ogen-compat: ## Verify OpenAPI 3.2 nullable values, validation, and additionalOperations
@set -euo pipefail; mkdir -p bin; temporary_dir=$$(mktemp -d "$(CURDIR)/bin/ogen-compat.XXXXXX"); trap 'rm -rf "$$temporary_dir"' EXIT; \
$(GO_TOOL) ogen -config codegen/ogen-compat.yml --target "$$temporary_dir" --package compat --clean ../api/testdata/openapi-3.2.0.yml; \
cp testdata/ogen_compat_test.go "$$temporary_dir/ogen_compat_test.go"; \
$(GO) test "./$${temporary_dir#$(CURDIR)/}"
.PHONY: check-generated
check-generated: ## Check tracked generated output against generator inputs
python3 "$(ROOT_DIR)/scripts/check-generated.py"
##@ Format, lint, and test
.PHONY: fmt
fmt: ## Format Go sources
$(GO_TOOL) golangci-lint fmt ./...
.PHONY: fmt-check
fmt-check: ## Check Go formatting without modifying files
@unformatted=$$(gofmt -l $$(find . -name '*.go' -type f)); \
if [ -n "$$unformatted" ]; then printf '%s\n' "$$unformatted"; exit 1; fi
@formatter_diff=$$($(GO_TOOL) golangci-lint fmt --diff ./...); \
if [ -n "$$formatter_diff" ]; then printf '%s\n' "$$formatter_diff"; exit 1; fi
.PHONY: lint lint-go lint-sql lint-fix
lint: ## Run Go and SQL linters
$(MAKE) --no-print-directory lint-go
$(MAKE) --no-print-directory lint-sql
lint-go: ## Run golangci-lint on all backend packages
$(GO_TOOL) golangci-lint run ./...
lint-sql: $(QUALITY_STAMP) ## Lint migrations and sqlc queries
$(QUALITY_PYTHON) -m sqlfluff lint --config .sqlfluff db/migrations db/queries
lint-fix: $(QUALITY_STAMP) ## Apply safe Go lint fixes and SQL formatting to queries only
$(GO_TOOL) golangci-lint run --fix ./...
$(QUALITY_PYTHON) -m sqlfluff fix --config .sqlfluff db/queries
$(QUALITY_STAMP): $(QUALITY_REQUIREMENTS)
$(BOOTSTRAP_PYTHON) -m venv "$(QUALITY_VENV)"
"$(QUALITY_PYTHON)" -m pip install --disable-pip-version-check -r "$(QUALITY_REQUIREMENTS)"
@touch "$(QUALITY_STAMP)"
.PHONY: install-quality-python-deps
install-quality-python-deps: $(QUALITY_STAMP) ## Install pinned SQL quality tools locally
.PHONY: test test-fast test-race test-int test-int-compile
test: ## Run backend unit tests with the race detector
$(GO) test -race -count=1 ./...
test-fast: ## Run backend unit tests without race instrumentation
$(GO) test ./...
test-race: test ## Alias for the race-enabled unit suite
test-int: ## Run PostgreSQL integration tests with Testcontainers
$(GO) test -tags=integration -count=1 ./integration_test/...
test-int-compile: ## Compile PostgreSQL integration tests without starting containers
$(GO) test -tags=integration -run '^$$' ./integration_test/...
.PHONY: verify check
check: ## Run local formatting, build, unit, and lint checks in order
$(MAKE) --no-print-directory fmt-check
$(MAKE) --no-print-directory build
$(MAKE) --no-print-directory test-fast
$(MAKE) --no-print-directory lint
verify: ## Run code, test, tooling, and generated-drift checks in order
$(MAKE) --no-print-directory generate
$(MAKE) --no-print-directory check
$(MAKE) --no-print-directory check-ogen-compat
$(MAKE) --no-print-directory check-generated
##@ Help
.PHONY: help
help: ## Show available targets
@awk 'BEGIN{FS=":.*##"; printf "\nUsage:\n make -C backend <target>\n"} /^[a-zA-Z0-9_-]+:.*##/ {printf " %-22s %s\n", $$1, $$2} /^##@/ {printf "\n%s\n", substr($$0, 5)}' $(MAKEFILE_LIST)
+15
View File
@@ -0,0 +1,15 @@
package main
import (
"fmt"
"os"
"lincodex/backend/internal/bootstrap"
)
func main() {
if err := bootstrap.Run(); err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
+2
View File
@@ -0,0 +1,2 @@
# Add real consumer-owned interfaces when they need generated test doubles.
packages: {}
+5
View File
@@ -0,0 +1,5 @@
generator:
features:
disable:
- paths/client
- webhooks/client
+5
View File
@@ -0,0 +1,5 @@
generator:
features:
disable:
- paths/server
- webhooks/server
+5
View File
@@ -0,0 +1,5 @@
generator:
features:
disable:
- paths/client
- webhooks/client
+11
View File
@@ -0,0 +1,11 @@
version: "2"
sql:
- engine: postgresql
schema: ../db/migrations
queries: ../db/queries
gen:
go:
package: sqlc
out: ../internal/adapter/secondary/postgres/sqlc
sql_package: pgx/v5
emit_interface: true
+99
View File
@@ -0,0 +1,99 @@
package config
import (
"fmt"
"net"
"os"
"strconv"
"strings"
"time"
)
type Config struct {
HTTPAddr string
MetricsAddr string
DatabaseURL string
LogLevel string
ReadinessTimeout time.Duration
ShutdownTimeout time.Duration
}
type LookupEnv func(string) (string, bool)
func Load() (Config, error) {
return LoadFromEnv(os.LookupEnv)
}
func LoadFromEnv(lookup LookupEnv) (Config, error) {
config := Config{
HTTPAddr: valueOrDefault(lookup, "HTTP_ADDR", ":8080"),
MetricsAddr: valueOrDefault(lookup, "METRICS_ADDR", ":9090"),
DatabaseURL: strings.TrimSpace(valueOrDefault(lookup, "DATABASE_URL", "")),
LogLevel: strings.ToLower(strings.TrimSpace(valueOrDefault(lookup, "LOG_LEVEL", "info"))),
ReadinessTimeout: time.Second,
ShutdownTimeout: 10 * time.Second,
}
if value, ok := lookup("READINESS_TIMEOUT"); ok {
duration, err := time.ParseDuration(value)
if err != nil {
return Config{}, fmt.Errorf("parse READINESS_TIMEOUT: %w", err)
}
config.ReadinessTimeout = duration
}
if value, ok := lookup("SHUTDOWN_TIMEOUT"); ok {
duration, err := time.ParseDuration(value)
if err != nil {
return Config{}, fmt.Errorf("parse SHUTDOWN_TIMEOUT: %w", err)
}
config.ShutdownTimeout = duration
}
if err := config.Validate(); err != nil {
return Config{}, err
}
return config, nil
}
func (config Config) Validate() error {
if err := validateAddress("HTTP_ADDR", config.HTTPAddr); err != nil {
return err
}
if err := validateAddress("METRICS_ADDR", config.MetricsAddr); err != nil {
return err
}
if config.ReadinessTimeout <= 0 {
return fmt.Errorf("READINESS_TIMEOUT must be positive")
}
if config.ShutdownTimeout <= 0 {
return fmt.Errorf("SHUTDOWN_TIMEOUT must be positive")
}
switch config.LogLevel {
case "debug", "info", "warn", "error":
default:
return fmt.Errorf("LOG_LEVEL must be one of debug, info, warn, or error")
}
return nil
}
func valueOrDefault(lookup LookupEnv, key, fallback string) string {
if value, ok := lookup(key); ok {
return value
}
return fallback
}
func validateAddress(name, address string) error {
if address == "" {
return fmt.Errorf("%s must not be empty", name)
}
_, port, err := net.SplitHostPort(address)
if err != nil {
return fmt.Errorf("%s must be a host:port address: %w", name, err)
}
number, err := strconv.Atoi(port)
if err != nil || number < 0 || number > 65535 {
return fmt.Errorf("%s port must be between 0 and 65535", name)
}
return nil
}
+81
View File
@@ -0,0 +1,81 @@
package config
import (
"strings"
"testing"
"time"
)
func TestLoadFromEnvUsesOperationalDefaults(t *testing.T) {
config, err := LoadFromEnv(func(string) (string, bool) { return "", false })
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
if config.HTTPAddr != ":8080" || config.MetricsAddr != ":9090" {
t.Fatalf("unexpected listener defaults: HTTP=%q metrics=%q", config.HTTPAddr, config.MetricsAddr)
}
if config.ReadinessTimeout != time.Second || config.ShutdownTimeout != 10*time.Second {
t.Fatalf("unexpected timeout defaults: readiness=%s shutdown=%s", config.ReadinessTimeout, config.ShutdownTimeout)
}
if config.DatabaseURL != "" {
t.Fatalf("DatabaseURL = %q, want empty", config.DatabaseURL)
}
if config.LogLevel != "info" {
t.Fatalf("LogLevel = %q, want info", config.LogLevel)
}
}
func TestLoadFromEnvReadsAddressesAndTimeouts(t *testing.T) {
values := map[string]string{
"HTTP_ADDR": "127.0.0.1:18080",
"METRICS_ADDR": "127.0.0.1:19090",
"DATABASE_URL": " postgres://app:secret@db/app ",
"LOG_LEVEL": " DEBUG ",
"READINESS_TIMEOUT": "2s",
"SHUTDOWN_TIMEOUT": "15s",
}
config, err := LoadFromEnv(func(key string) (string, bool) {
value, ok := values[key]
return value, ok
})
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
if config.HTTPAddr != values["HTTP_ADDR"] || config.MetricsAddr != values["METRICS_ADDR"] {
t.Fatalf("unexpected listener values: %+v", config)
}
if config.DatabaseURL != "postgres://app:secret@db/app" {
t.Fatalf("DatabaseURL was not trimmed: %q", config.DatabaseURL)
}
if config.LogLevel != "debug" {
t.Fatalf("LogLevel was not normalized: %q", config.LogLevel)
}
if config.ReadinessTimeout != 2*time.Second || config.ShutdownTimeout != 15*time.Second {
t.Fatalf("unexpected timeout values: readiness=%s shutdown=%s", config.ReadinessTimeout, config.ShutdownTimeout)
}
}
func TestLoadFromEnvRejectsInvalidSettings(t *testing.T) {
tests := []struct {
name string
values map[string]string
want string
}{
{name: "invalid HTTP address", values: map[string]string{"HTTP_ADDR": "bad"}, want: "HTTP_ADDR"},
{name: "invalid metrics port", values: map[string]string{"METRICS_ADDR": ":70000"}, want: "METRICS_ADDR"},
{name: "invalid readiness timeout", values: map[string]string{"READINESS_TIMEOUT": "soon"}, want: "READINESS_TIMEOUT"},
{name: "zero shutdown timeout", values: map[string]string{"SHUTDOWN_TIMEOUT": "0s"}, want: "SHUTDOWN_TIMEOUT"},
{name: "invalid log level", values: map[string]string{"LOG_LEVEL": "trace"}, want: "LOG_LEVEL"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
_, err := LoadFromEnv(func(key string) (string, bool) {
value, ok := test.values[key]
return value, ok
})
if err == nil || !strings.Contains(err.Error(), test.want) {
t.Fatalf("LoadFromEnv() error = %v, want an error mentioning %q", err, test.want)
}
})
}
}
+1
View File
@@ -0,0 +1 @@
+2
View File
@@ -0,0 +1,2 @@
-- name: Ping :one
SELECT 1::int4 AS alive;
+400
View File
@@ -0,0 +1,400 @@
module lincodex/backend
go 1.26.8
require (
github.com/felixge/httpsnoop v1.1.0
github.com/go-chi/chi/v5 v5.3.2
github.com/go-faster/errors v0.8.0
github.com/go-faster/jx v1.2.0
github.com/goforj/wire v1.2.0
github.com/jackc/pgx/v5 v5.11.0
github.com/ogen-go/ogen v1.24.0
github.com/prometheus/client_golang v1.24.1
github.com/testcontainers/testcontainers-go v0.44.0
github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0
github.com/wahrwelt-kit/go-httpkit v0.7.0
github.com/wahrwelt-kit/go-logkit v0.6.0
go.opentelemetry.io/otel v1.47.0
go.opentelemetry.io/otel/metric v1.47.0
go.opentelemetry.io/otel/trace v1.47.0
)
require (
4d63.com/gocheckcompilerdirectives v1.4.0 // indirect
4d63.com/gochecknoglobals v0.2.2 // indirect
cel.dev/expr v0.25.2 // indirect
charm.land/lipgloss/v2 v2.0.6 // indirect
cloud.google.com/go v0.123.0 // indirect
codeberg.org/chavacava/garif v0.2.1 // indirect
codeberg.org/polyfloyd/go-errorlint v1.9.0 // indirect
dario.cat/mergo v1.0.2 // indirect
dev.gaijin.team/go/exhaustruct/v4 v4.0.0 // indirect
dev.gaijin.team/go/exhaustruct/v5 v5.2.0 // indirect
dev.gaijin.team/go/golib v0.8.1 // indirect
filippo.io/edwards25519 v1.2.0 // indirect
github.com/4meepo/tagalign v1.4.4 // indirect
github.com/Abirdcfly/dupword v0.1.8 // indirect
github.com/AdminBenni/iota-mixing v1.0.0 // indirect
github.com/AlwxSin/noinlineerr v1.0.6 // indirect
github.com/Antonboom/errname v1.1.2 // indirect
github.com/Antonboom/nilnil v1.1.2 // indirect
github.com/Antonboom/testifylint v1.6.4 // indirect
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.1 // indirect
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1 // indirect
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect
github.com/AzureAD/microsoft-authentication-library-for-go v1.9.0 // indirect
github.com/BurntSushi/toml v1.6.0 // indirect
github.com/ClickHouse/ch-go v0.74.0 // indirect
github.com/ClickHouse/clickhouse-go-linter v1.2.1 // indirect
github.com/ClickHouse/clickhouse-go/v2 v2.48.0 // indirect
github.com/Djarvur/go-err113 v0.1.1 // indirect
github.com/Masterminds/semver/v3 v3.5.0 // indirect
github.com/Microsoft/go-winio v0.6.2 // indirect
github.com/MirrexOne/unqueryvet v1.5.4 // indirect
github.com/OpenPeeDeeP/depguard/v2 v2.2.1 // indirect
github.com/TwiN/go-color v1.4.1 // indirect
github.com/alecthomas/chroma/v2 v2.27.0 // indirect
github.com/alecthomas/go-check-sumtype v0.5.1-0.20260828200218-ae6904d28606 // indirect
github.com/alexkohler/nakedret/v2 v2.0.6 // indirect
github.com/alexkohler/prealloc v1.1.0 // indirect
github.com/alfatraining/structtag v1.0.0 // indirect
github.com/alingse/asasalint v0.0.11 // indirect
github.com/alingse/nilnesserr v0.2.0 // indirect
github.com/andybalholm/brotli v1.2.3 // indirect
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
github.com/ashanbrown/forbidigo/v2 v2.3.1 // indirect
github.com/ashanbrown/makezero/v2 v2.2.1 // indirect
github.com/bahlo/generic-list-go v0.2.0 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bkielbasa/cyclop v1.2.3 // indirect
github.com/blizzy78/varnamelen v0.8.0 // indirect
github.com/bombsimon/wsl/v4 v4.7.0 // indirect
github.com/bombsimon/wsl/v5 v5.9.0 // indirect
github.com/breml/bidichk v0.3.3 // indirect
github.com/breml/errchkjson v0.4.1 // indirect
github.com/brunoga/deep v1.3.1 // indirect
github.com/buger/jsonparser v1.6.1 // indirect
github.com/butuzov/ireturn v0.4.1 // indirect
github.com/butuzov/mirror v1.3.3 // indirect
github.com/catenacyber/perfsprint v0.10.1 // indirect
github.com/ccojocar/zxcvbn-go v1.0.4 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/charithe/durationcheck v0.0.11 // indirect
github.com/charmbracelet/colorprofile v0.4.3 // indirect
github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 // indirect
github.com/charmbracelet/x/ansi v0.11.8 // indirect
github.com/charmbracelet/x/term v0.2.2 // indirect
github.com/charmbracelet/x/termios v0.1.1 // indirect
github.com/charmbracelet/x/windows v0.2.2 // indirect
github.com/ckaznocha/intrange v0.3.1 // indirect
github.com/clipperhouse/displaywidth v0.11.0 // indirect
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
github.com/coder/websocket v1.8.15 // indirect
github.com/containerd/errdefs v1.0.0 // indirect
github.com/containerd/errdefs/pkg v0.3.0 // indirect
github.com/containerd/log v0.1.0 // indirect
github.com/containerd/platforms v0.2.1 // indirect
github.com/coreos/go-semver v0.3.1 // indirect
github.com/cpuguy83/dockercfg v0.3.2 // indirect
github.com/cubicdaiya/gonp v1.0.4 // indirect
github.com/curioswitch/go-reassign v0.3.0 // indirect
github.com/daixiang0/gci v0.13.7 // indirect
github.com/dave/dst v0.27.3 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/denis-tingaikin/go-header v0.5.0 // indirect
github.com/distribution/reference v0.6.0 // indirect
github.com/dlclark/regexp2 v1.12.0 // indirect
github.com/dlclark/regexp2/v2 v2.2.1 // indirect
github.com/docker/go-connections v0.8.1 // indirect
github.com/docker/go-units v0.5.0 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/ebitengine/purego v0.10.2 // indirect
github.com/elastic/go-sysinfo v1.15.5 // indirect
github.com/elastic/go-windows v1.0.2 // indirect
github.com/ettle/strcase v0.2.0 // indirect
github.com/fatih/color v1.19.0 // indirect
github.com/fatih/structs v1.1.0 // indirect
github.com/fatih/structtag v1.2.0 // indirect
github.com/firefart/nonamedreturns v1.0.8 // indirect
github.com/fsnotify/fsnotify v1.10.1 // indirect
github.com/fzipp/gocyclo v0.6.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
github.com/getkin/kin-openapi v0.149.0 // indirect
github.com/ghodss/yaml v1.0.0 // indirect
github.com/ghostiam/protogetter v1.0.1 // indirect
github.com/go-critic/go-critic v0.15.0 // indirect
github.com/go-faster/city v1.0.1 // indirect
github.com/go-faster/yaml v0.4.6 // indirect
github.com/go-logr/logr v1.4.4 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/go-openapi/jsonpointer v1.0.1 // indirect
github.com/go-playground/locales v0.14.2 // indirect
github.com/go-playground/universal-translator v0.18.2 // indirect
github.com/go-playground/validator/v10 v10.30.5 // indirect
github.com/go-sql-driver/mysql v1.10.0 // indirect
github.com/go-toolsmith/astcast v1.1.0 // indirect
github.com/go-toolsmith/astcopy v1.1.0 // indirect
github.com/go-toolsmith/astequal v1.2.0 // indirect
github.com/go-toolsmith/astfmt v1.1.0 // indirect
github.com/go-toolsmith/astp v1.1.0 // indirect
github.com/go-toolsmith/strparse v1.1.0 // indirect
github.com/go-toolsmith/typep v1.1.0 // indirect
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
github.com/go-xmlfmt/xmlfmt v1.1.3 // indirect
github.com/gobwas/glob v0.2.3 // indirect
github.com/godoc-lint/godoc-lint v0.11.4 // indirect
github.com/gofrs/flock v0.13.1 // indirect
github.com/golang-jwt/jwt/v4 v4.5.2 // indirect
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // indirect
github.com/golang-sql/sqlexp v0.1.0 // indirect
github.com/golangci/asciicheck v0.5.0 // indirect
github.com/golangci/canonicalheader v0.0.0-20260827115959-a25c71c521f6 // indirect
github.com/golangci/dupl v0.0.0-20260401084720-c99c5cf5c202 // indirect
github.com/golangci/go-printf-func-name v0.1.1 // indirect
github.com/golangci/gofmt v0.0.0-20260820135601-e84e05053792 // indirect
github.com/golangci/golangci-lint/v2 v2.14.0 // indirect
github.com/golangci/golines v0.15.0 // indirect
github.com/golangci/misspell v0.8.0 // indirect
github.com/golangci/plugin-module-register v0.1.2 // indirect
github.com/golangci/revgrep v0.8.0 // indirect
github.com/golangci/rowserrcheck v0.0.0-20260419091836-c5f79b8a11ba // indirect
github.com/golangci/swaggoswag v0.0.0-20250504205917-77f2aca3143e // indirect
github.com/golangci/unconvert v0.0.0-20250410112200-a129a6e6413e // indirect
github.com/google/cel-go v0.28.0 // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/subcommands v1.2.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/gordonklaus/ineffassign v0.2.0 // indirect
github.com/gostaticanalysis/analysisutil v0.7.1 // indirect
github.com/gostaticanalysis/comment v1.5.0 // indirect
github.com/gostaticanalysis/forcetypeassert v0.2.0 // indirect
github.com/gostaticanalysis/nilerr v0.1.2 // indirect
github.com/hashicorp/go-immutable-radix/v2 v2.1.0 // indirect
github.com/hashicorp/go-version v1.9.0 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/hexops/gotextdiff v1.0.3 // indirect
github.com/huandu/xstrings v1.5.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/invopop/jsonschema v0.14.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/jedib0t/go-pretty/v6 v6.7.8 // indirect
github.com/jgautheron/goconst v1.11.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jjti/go-spancheck v0.6.5 // indirect
github.com/joho/godotenv v1.5.1 // indirect
github.com/jonboulle/clockwork v0.5.0 // indirect
github.com/julz/importas v0.2.0 // indirect
github.com/karamaru-alpha/copyloopvar v1.2.2 // indirect
github.com/kisielk/errcheck v1.20.0 // indirect
github.com/kkHAIKE/contextcheck v1.1.6 // indirect
github.com/klauspost/compress v1.19.2 // indirect
github.com/knadh/koanf/maps v0.1.2 // indirect
github.com/knadh/koanf/parsers/yaml v1.1.0 // indirect
github.com/knadh/koanf/providers/env v1.1.0 // indirect
github.com/knadh/koanf/providers/file v1.2.1 // indirect
github.com/knadh/koanf/providers/posflag v1.0.1 // indirect
github.com/knadh/koanf/providers/structs v1.0.0 // indirect
github.com/knadh/koanf/v2 v2.3.2 // indirect
github.com/kulti/thelper v0.7.1 // indirect
github.com/kunwardeep/paralleltest v1.0.15 // indirect
github.com/kylelemons/godebug v1.1.0 // indirect
github.com/ldez/exptostd v0.4.5 // indirect
github.com/ldez/gomoddirectives v0.10.0 // indirect
github.com/ldez/grignotin v0.10.1 // indirect
github.com/ldez/structtags v0.6.1 // indirect
github.com/ldez/tagliatelle v0.8.0 // indirect
github.com/ldez/usetesting v0.5.0 // indirect
github.com/leodido/go-urn v1.5.0 // indirect
github.com/leonklingele/grouper v1.1.2 // indirect
github.com/lucasb-eyer/go-colorful v1.4.1 // indirect
github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e // indirect
github.com/macabu/inamedparam v0.2.0 // indirect
github.com/magiconair/properties v1.8.10 // indirect
github.com/manuelarte/embeddedstructfieldcheck v0.4.0 // indirect
github.com/manuelarte/funcorder v0.6.0 // indirect
github.com/maratori/testableexamples v1.0.1 // indirect
github.com/maratori/testpackage v1.1.2 // indirect
github.com/matoous/godox v1.1.0 // indirect
github.com/mattn/go-colorable v0.1.15 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/mattn/go-runewidth v0.0.24 // indirect
github.com/mfridman/interpolate v0.0.2 // indirect
github.com/mfridman/xflag v0.1.0 // indirect
github.com/mgechev/revive v1.17.0 // indirect
github.com/microsoft/go-mssqldb v1.11.0 // indirect
github.com/mitchellh/copystructure v1.2.0 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/moby/docker-image-spec v1.3.1 // indirect
github.com/moby/go-archive v0.2.0 // indirect
github.com/moby/moby/api v1.55.0 // indirect
github.com/moby/moby/client v0.5.1 // indirect
github.com/moby/patternmatcher v0.6.1 // indirect
github.com/moby/sys/sequential v0.7.0 // indirect
github.com/moby/sys/user v0.4.0 // indirect
github.com/moby/sys/userns v0.1.0 // indirect
github.com/moby/term v0.5.2 // indirect
github.com/moricho/tparallel v0.3.2 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/nakabonne/nestif v0.3.1 // indirect
github.com/ncruces/go-sqlite3 v0.32.0 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/ncruces/julianday v1.0.0 // indirect
github.com/nishanths/exhaustive v0.13.0 // indirect
github.com/nishanths/predeclared v0.2.2 // indirect
github.com/nunnatsa/ginkgolinter v0.24.0 // indirect
github.com/oasdiff/oasdiff v1.33.0 // indirect
github.com/oasdiff/yaml v0.1.1 // indirect
github.com/oasdiff/yaml3 v0.0.14 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.1 // indirect
github.com/paulmach/orb v0.13.0 // indirect
github.com/pb33f/ordered-map/v2 v2.3.1 // indirect
github.com/pelletier/go-toml/v2 v2.4.3 // indirect
github.com/pganalyze/pg_query_go/v6 v6.2.2 // indirect
github.com/pierrec/lz4/v4 v4.1.29 // indirect
github.com/pingcap/errors v0.11.5-0.20250523034308-74f78ae071ee // indirect
github.com/pingcap/failpoint v0.0.0-20240528011301-b51a646c7c86 // indirect
github.com/pingcap/log v1.1.0 // indirect
github.com/pingcap/tidb/pkg/parser v0.0.0-20260418072757-ce92298d1124 // indirect
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
github.com/pressly/goose/v3 v3.28.0 // indirect
github.com/prometheus/client_model v0.6.3 // indirect
github.com/prometheus/common v0.72.0 // indirect
github.com/prometheus/procfs v0.22.0 // indirect
github.com/quasilyte/go-ruleguard v0.4.5 // indirect
github.com/quasilyte/go-ruleguard/dsl v0.3.23 // indirect
github.com/quasilyte/gogrep v0.5.0 // indirect
github.com/quasilyte/regex/syntax v0.0.0-20210819130434-b3f0c404a727 // indirect
github.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567 // indirect
github.com/raeperd/recvcheck v0.3.1 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/riza-io/grpc-go v0.2.0 // indirect
github.com/rogpeppe/go-internal v1.16.0 // indirect
github.com/rs/zerolog v1.35.1 // indirect
github.com/ryancurrah/gomodguard v1.4.1 // indirect
github.com/ryancurrah/gomodguard/v2 v2.1.3 // indirect
github.com/ryanrolds/sqlclosecheck v0.6.0 // indirect
github.com/sagikazarmark/locafero v0.12.0 // indirect
github.com/sanposhiho/wastedassign/v2 v2.1.0 // indirect
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect
github.com/sashamelentyev/interfacebloat v1.1.0 // indirect
github.com/sashamelentyev/usestdlibvars v1.29.0 // indirect
github.com/securego/gosec/v2 v2.29.0 // indirect
github.com/segmentio/asm v1.2.1 // indirect
github.com/sethvargo/go-retry v0.4.0 // indirect
github.com/shirou/gopsutil/v4 v4.26.8 // indirect
github.com/shopspring/decimal v1.4.0 // indirect
github.com/sirupsen/logrus v1.10.2 // indirect
github.com/sivchari/containedctx v1.0.3 // indirect
github.com/sonatard/noctx v0.5.1 // indirect
github.com/sourcegraph/go-diff v0.9.0 // indirect
github.com/spf13/afero v1.15.0 // indirect
github.com/spf13/cast v1.10.0 // indirect
github.com/spf13/cobra v1.10.2 // indirect
github.com/spf13/pflag v1.0.10 // indirect
github.com/spf13/viper v1.21.0 // indirect
github.com/sqlc-dev/doubleclick v1.0.0 // indirect
github.com/sqlc-dev/sqlc v1.31.1 // indirect
github.com/ssgreg/nlreturn/v2 v2.2.1 // indirect
github.com/stbenjam/no-sprintf-host-port v0.3.1 // indirect
github.com/stretchr/objx v0.5.3 // indirect
github.com/stretchr/testify v1.12.1 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/tetafro/godot v1.5.6 // indirect
github.com/tetratelabs/wazero v1.11.0 // indirect
github.com/tidwall/gjson v1.19.0 // indirect
github.com/tidwall/match v1.2.0 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
github.com/tidwall/sjson v1.2.5 // indirect
github.com/timakin/bodyclose v0.0.0-20260723120731-857993a2939c // indirect
github.com/timonwong/loggercheck v0.12.0 // indirect
github.com/tklauser/go-sysconf v0.4.0 // indirect
github.com/tklauser/numcpus v0.12.0 // indirect
github.com/tomarrell/wrapcheck/v2 v2.12.0 // indirect
github.com/tommy-muehle/go-mnd/v2 v2.5.1 // indirect
github.com/tursodatabase/libsql-client-go v0.0.0-20260528064733-9d5d30a29a60 // indirect
github.com/ultraware/funlen v0.2.0 // indirect
github.com/ultraware/whitespace v0.2.0 // indirect
github.com/uudashr/gocognit v1.2.1 // indirect
github.com/uudashr/iface v1.5.1 // indirect
github.com/vektra/mockery/v3 v3.8.0 // indirect
github.com/vertica/vertica-sql-go v1.3.8 // indirect
github.com/wI2L/jsondiff v0.7.1 // indirect
github.com/wasilibs/go-pgquery v0.0.0-20250409022910-10ac41983c07 // indirect
github.com/wasilibs/wazero-helpers v0.0.0-20240620070341-3dff1577cd52 // indirect
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
github.com/xen0n/gosmopolitan v1.3.0 // indirect
github.com/xo/terminfo v1.0.0 // indirect
github.com/yagipy/maintidx v1.0.0 // indirect
github.com/yargevad/filepathx v1.0.0 // indirect
github.com/ydb-platform/ydb-go-genproto v0.0.0-20260810123728-f0c151ab31b9 // indirect
github.com/ydb-platform/ydb-go-sdk/v3 v3.151.1 // indirect
github.com/yeya24/promlinter v0.3.0 // indirect
github.com/ykadowak/zerologlint v0.1.5 // indirect
github.com/yuin/goldmark v1.8.6 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
github.com/ziutek/mymysql v1.5.4 // indirect
gitlab.com/bosi/decorder v0.4.2 // indirect
go-simpler.org/musttag v0.14.0 // indirect
go-simpler.org/sloglint v0.12.0 // indirect
go.augendre.info/arangolint v0.4.0 // indirect
go.augendre.info/fatcontext v0.10.1 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 // indirect
go.opentelemetry.io/otel/log v1.47.0 // indirect
go.uber.org/atomic v1.11.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.28.0 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
go.yaml.in/yaml/v4 v4.0.0-rc.6 // indirect
golang.org/x/crypto v0.57.0 // indirect
golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba // indirect
golang.org/x/exp/typeparams v0.0.0-20260811152304-ee035b5b010f // indirect
golang.org/x/mod v0.41.0 // indirect
golang.org/x/net v0.59.0 // indirect
golang.org/x/sync v0.23.0 // indirect
golang.org/x/sys v0.48.0 // indirect
golang.org/x/term v0.46.0 // indirect
golang.org/x/text v0.42.0 // indirect
golang.org/x/tools v0.50.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260831171406-18b4a7587f8a // indirect
google.golang.org/grpc v1.83.2 // indirect
google.golang.org/protobuf v1.36.12 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
honnef.co/go/tools v0.8.1 // indirect
howett.net/plist v1.0.1 // indirect
modernc.org/libc v1.75.6 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.12.1 // indirect
modernc.org/sqlite v1.57.0 // indirect
mvdan.cc/gofumpt v0.12.0 // indirect
mvdan.cc/unparam v0.0.0-20260823230713-2fa3d841b0c8 // indirect
)
tool (
github.com/goforj/wire/cmd/wire
github.com/golangci/golangci-lint/v2/cmd/golangci-lint
github.com/oasdiff/oasdiff
github.com/ogen-go/ogen/cmd/ogen
github.com/pressly/goose/v3/cmd/goose
github.com/sqlc-dev/sqlc/cmd/sqlc
github.com/vektra/mockery/v3
)
+1098
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,50 @@
//go:build integration
package integration_test
import (
"context"
"testing"
"time"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/postgres"
"lincodex/backend/config"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
)
func TestPostgresHealthQueryAgainstContainer(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
defer cancel()
container, err := postgres.Run(ctx, "postgres:alpine",
postgres.WithDatabase("health"),
postgres.WithUsername("health"),
postgres.WithPassword("health"),
postgres.BasicWaitStrategies(),
)
if err != nil {
t.Fatalf("start PostgreSQL container: %v", err)
}
t.Cleanup(func() {
if err := testcontainers.TerminateContainer(container); err != nil {
t.Errorf("terminate PostgreSQL container: %v", err)
}
})
databaseURL, err := container.ConnectionString(ctx, "sslmode=disable")
if err != nil {
t.Fatalf("get PostgreSQL connection string: %v", err)
}
checker, closePool, err := postgresadapter.NewHealthChecker(ctx, config.Config{DatabaseURL: databaseURL})
if err != nil {
t.Fatalf("create PostgreSQL health checker: %v", err)
}
defer closePool()
checkContext, checkCancel := context.WithTimeout(ctx, 5*time.Second)
defer checkCancel()
if err := checker.Check(checkContext); err != nil {
t.Fatalf("PostgreSQL health query failed: %v", err)
}
}
@@ -0,0 +1,251 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"net/http"
"strings"
"github.com/ogen-go/ogen/middleware"
"github.com/ogen-go/ogen/ogenerrors"
"github.com/ogen-go/ogen/otelogen"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
)
var (
// Allocate option closure once.
serverSpanKind = trace.WithSpanKind(trace.SpanKindServer)
)
type (
optionFunc[C any] func(*C)
otelOptionFunc func(*otelConfig)
)
type otelConfig struct {
TracerProvider trace.TracerProvider
Tracer trace.Tracer
MeterProvider metric.MeterProvider
Meter metric.Meter
Attributes []attribute.KeyValue
}
func (cfg *otelConfig) initOTEL() {
if cfg.TracerProvider == nil {
cfg.TracerProvider = otel.GetTracerProvider()
}
if cfg.MeterProvider == nil {
cfg.MeterProvider = otel.GetMeterProvider()
}
cfg.Tracer = cfg.TracerProvider.Tracer(otelogen.Name,
trace.WithInstrumentationVersion(otelogen.SemVersion()),
)
cfg.Meter = cfg.MeterProvider.Meter(otelogen.Name,
metric.WithInstrumentationVersion(otelogen.SemVersion()),
)
}
// ErrorHandler is error handler.
type ErrorHandler = ogenerrors.ErrorHandler
type serverConfig struct {
otelConfig
NotFound http.HandlerFunc
MethodNotAllowed func(w http.ResponseWriter, r *http.Request, allowed string)
ErrorHandler ErrorHandler
Prefix string
Middleware Middleware
MaxMultipartMemory int64
}
// ServerOption is server config option.
type ServerOption interface {
applyServer(*serverConfig)
}
var _ ServerOption = (optionFunc[serverConfig])(nil)
func (o optionFunc[C]) applyServer(c *C) {
o(c)
}
var _ ServerOption = (otelOptionFunc)(nil)
func (o otelOptionFunc) applyServer(c *serverConfig) {
o(&c.otelConfig)
}
func newServerConfig(opts ...ServerOption) serverConfig {
cfg := serverConfig{
NotFound: http.NotFound,
MethodNotAllowed: nil,
ErrorHandler: ogenerrors.DefaultErrorHandler,
Middleware: nil,
MaxMultipartMemory: 32 << 20, // 32 MB
}
for _, opt := range opts {
opt.applyServer(&cfg)
}
cfg.initOTEL()
return cfg
}
type baseServer struct {
cfg serverConfig
requests metric.Int64Counter
errors metric.Int64Counter
duration metric.Float64Histogram
}
func (s baseServer) notFound(w http.ResponseWriter, r *http.Request) {
s.cfg.NotFound(w, r)
}
type notAllowedParams struct {
allowedMethods string
allowedHeaders map[string]string
acceptPost string
acceptPatch string
}
func (s baseServer) notAllowed(w http.ResponseWriter, r *http.Request, params notAllowedParams) {
h := w.Header()
isOptions := r.Method == "OPTIONS"
if isOptions {
h.Set("Access-Control-Allow-Methods", params.allowedMethods)
if params.allowedHeaders != nil {
m := r.Header.Get("Access-Control-Request-Method")
if m != "" {
allowedHeaders, ok := params.allowedHeaders[strings.ToUpper(m)]
if ok {
h.Set("Access-Control-Allow-Headers", allowedHeaders)
}
}
}
if params.acceptPost != "" {
h.Set("Accept-Post", params.acceptPost)
}
if params.acceptPatch != "" {
h.Set("Accept-Patch", params.acceptPatch)
}
}
if s.cfg.MethodNotAllowed != nil {
s.cfg.MethodNotAllowed(w, r, params.allowedMethods)
return
}
status := http.StatusNoContent
if !isOptions {
h.Set("Allow", params.allowedMethods)
status = http.StatusMethodNotAllowed
}
w.WriteHeader(status)
}
func (cfg serverConfig) baseServer() (s baseServer, err error) {
s = baseServer{cfg: cfg}
if s.requests, err = otelogen.ServerRequestCountCounter(s.cfg.Meter); err != nil {
return s, err
}
if s.errors, err = otelogen.ServerErrorsCountCounter(s.cfg.Meter); err != nil {
return s, err
}
if s.duration, err = otelogen.ServerDurationHistogram(s.cfg.Meter); err != nil {
return s, err
}
return s, nil
}
// Option is config option.
type Option interface {
ServerOption
}
// WithTracerProvider specifies a tracer provider to use for creating a tracer.
//
// If none is specified, the global provider is used.
func WithTracerProvider(provider trace.TracerProvider) Option {
return otelOptionFunc(func(cfg *otelConfig) {
if provider != nil {
cfg.TracerProvider = provider
}
})
}
// WithMeterProvider specifies a meter provider to use for creating a meter.
//
// If none is specified, the otel.GetMeterProvider() is used.
func WithMeterProvider(provider metric.MeterProvider) Option {
return otelOptionFunc(func(cfg *otelConfig) {
if provider != nil {
cfg.MeterProvider = provider
}
})
}
// WithAttributes specifies default otel attributes.
func WithAttributes(attributes ...attribute.KeyValue) Option {
return otelOptionFunc(func(cfg *otelConfig) {
cfg.Attributes = attributes
})
}
// WithNotFound specifies Not Found handler to use.
func WithNotFound(notFound http.HandlerFunc) ServerOption {
return optionFunc[serverConfig](func(cfg *serverConfig) {
if notFound != nil {
cfg.NotFound = notFound
}
})
}
// WithMethodNotAllowed specifies Method Not Allowed handler to use.
func WithMethodNotAllowed(methodNotAllowed func(w http.ResponseWriter, r *http.Request, allowed string)) ServerOption {
return optionFunc[serverConfig](func(cfg *serverConfig) {
if methodNotAllowed != nil {
cfg.MethodNotAllowed = methodNotAllowed
}
})
}
// WithErrorHandler specifies error handler to use.
func WithErrorHandler(h ErrorHandler) ServerOption {
return optionFunc[serverConfig](func(cfg *serverConfig) {
if h != nil {
cfg.ErrorHandler = h
}
})
}
// WithPathPrefix specifies server path prefix.
func WithPathPrefix(prefix string) ServerOption {
return optionFunc[serverConfig](func(cfg *serverConfig) {
cfg.Prefix = prefix
})
}
// WithMiddleware specifies middlewares to use.
func WithMiddleware(m ...Middleware) ServerOption {
return optionFunc[serverConfig](func(cfg *serverConfig) {
switch len(m) {
case 0:
cfg.Middleware = nil
case 1:
cfg.Middleware = m[0]
default:
cfg.Middleware = middleware.ChainMiddlewares(m...)
}
})
}
// WithMaxMultipartMemory specifies limit of memory for storing file parts.
// File parts which can't be stored in memory will be stored on disk in temporary files.
func WithMaxMultipartMemory(max int64) ServerOption {
return optionFunc[serverConfig](func(cfg *serverConfig) {
if max > 0 {
cfg.MaxMultipartMemory = max
}
})
}
@@ -0,0 +1,157 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"context"
"net/http"
"time"
"github.com/go-faster/errors"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/middleware"
"github.com/ogen-go/ogen/otelogen"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
semconv "go.opentelemetry.io/otel/semconv/v1.39.0"
"go.opentelemetry.io/otel/trace"
)
type codeRecorder struct {
http.ResponseWriter
status int
}
func (c *codeRecorder) WriteHeader(status int) {
c.status = status
c.ResponseWriter.WriteHeader(status)
}
func (c *codeRecorder) Unwrap() http.ResponseWriter {
return c.ResponseWriter
}
// handleGetHealthzRequest handles GetHealthz operation.
//
// Check whether the API process is responding.
//
// GET /api/v1/healthz
func (s *Server) handleGetHealthzRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("GetHealthz"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/api/v1/healthz"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), GetHealthzOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
)
var rawBody []byte
var response *HealthResponse
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: GetHealthzOperation,
OperationSummary: "Check whether the API process is responding.",
OperationID: "GetHealthz",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{},
Raw: r,
}
type (
Request = struct{}
Params = struct{}
Response = *HealthResponse
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
nil,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.GetHealthz(ctx)
return response, err
},
)
} else {
response, err = s.h.GetHealthz(ctx)
}
if err != nil {
defer recordError("Internal", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeGetHealthzResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
@@ -0,0 +1,144 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"math/bits"
"strconv"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"github.com/ogen-go/ogen/validate"
)
// Encode implements json.Marshaler.
func (s *HealthResponse) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *HealthResponse) encodeFields(e *jx.Encoder) {
{
e.FieldStart("status")
s.Status.Encode(e)
}
}
var jsonFieldsNameOfHealthResponse = [1]string{
0: "status",
}
// Decode decodes HealthResponse from json.
func (s *HealthResponse) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode HealthResponse to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "status":
requiredBitSet[0] |= 1 << 0
if err := func() error {
if err := s.Status.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"status\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode HealthResponse")
}
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [1]uint8{
0b00000001,
} {
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
// Mask only required fields and check equality to mask using XOR.
//
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
// Bits of fields which would be set are actually bits of missed fields.
missed := bits.OnesCount8(result)
for bitN := 0; bitN < missed; bitN++ {
bitIdx := bits.TrailingZeros8(result)
fieldIdx := i*8 + bitIdx
var name string
if fieldIdx < len(jsonFieldsNameOfHealthResponse) {
name = jsonFieldsNameOfHealthResponse[fieldIdx]
} else {
name = strconv.Itoa(fieldIdx)
}
failures = append(failures, validate.FieldError{
Name: name,
Error: validate.ErrFieldRequired,
})
// Reset bit.
result &^= 1 << bitIdx
}
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *HealthResponse) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *HealthResponse) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes HealthResponseStatus as json.
func (s HealthResponseStatus) Encode(e *jx.Encoder) {
e.Str(string(s))
}
// Decode decodes HealthResponseStatus from json.
func (s *HealthResponseStatus) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode HealthResponseStatus to nil")
}
v, err := d.StrBytes()
if err != nil {
return err
}
// Try to use constant string.
switch HealthResponseStatus(v) {
case HealthResponseStatusOk:
*s = HealthResponseStatusOk
default:
*s = HealthResponseStatus(v)
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s HealthResponseStatus) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *HealthResponseStatus) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
@@ -0,0 +1,42 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"context"
"go.opentelemetry.io/otel/attribute"
)
// Labeler is used to allow adding custom attributes to the server request metrics.
type Labeler struct {
attrs []attribute.KeyValue
}
// Add attributes to the Labeler.
func (l *Labeler) Add(attrs ...attribute.KeyValue) {
l.attrs = append(l.attrs, attrs...)
}
// AttributeSet returns the attributes added to the Labeler as an attribute.Set.
func (l *Labeler) AttributeSet() attribute.Set {
return attribute.NewSet(l.attrs...)
}
type labelerContextKey struct{}
// LabelerFromContext retrieves the Labeler from the provided context, if present.
//
// If no Labeler was found in the provided context a new, empty Labeler is returned and the second
// return value is false. In this case it is safe to use the Labeler but any attributes added to
// it will not be used.
func LabelerFromContext(ctx context.Context) (*Labeler, bool) {
if l, ok := ctx.Value(labelerContextKey{}).(*Labeler); ok {
return l, true
}
return &Labeler{}, false
}
func contextWithLabeler(ctx context.Context, l *Labeler) context.Context {
return context.WithValue(ctx, labelerContextKey{}, l)
}
@@ -0,0 +1,10 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"github.com/ogen-go/ogen/middleware"
)
// Middleware is middleware type.
type Middleware = middleware.Middleware
@@ -0,0 +1,10 @@
// Code generated by ogen, DO NOT EDIT.
package api
// OperationName is the ogen operation name
type OperationName = string
const (
GetHealthzOperation OperationName = "GetHealthz"
)
@@ -0,0 +1,3 @@
// Code generated by ogen, DO NOT EDIT.
package api
@@ -0,0 +1,24 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"net/http"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"go.opentelemetry.io/otel/trace"
)
func encodeGetHealthzResponse(response *HealthResponse, w http.ResponseWriter, span trace.Span) error {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(200)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
}
@@ -0,0 +1,190 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"net/http"
"net/url"
"strings"
"github.com/ogen-go/ogen/uri"
)
func (s *Server) cutPrefix(path string) (string, bool) {
prefix := s.cfg.Prefix
if prefix == "" {
return path, true
}
if !strings.HasPrefix(path, prefix) {
// Prefix doesn't match.
return "", false
}
// Cut prefix from the path.
return strings.TrimPrefix(path, prefix), true
}
// ServeHTTP serves http request as defined by OpenAPI v3 specification,
// calling handler that matches the path or returning not found error.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
elem := r.URL.Path
elemIsEscaped := false
if rawPath := r.URL.RawPath; rawPath != "" {
if normalized, ok := uri.NormalizeEscapedPath(rawPath); ok {
elem = normalized
elemIsEscaped = strings.ContainsRune(elem, '%')
}
}
elem, ok := s.cutPrefix(elem)
if !ok || len(elem) == 0 {
s.notFound(w, r)
return
}
// Static code generated router with unwrapped path search.
switch {
default:
if len(elem) == 0 {
break
}
switch elem[0] {
case '/': // Prefix: "/api/v1/healthz"
if l := len("/api/v1/healthz"); len(elem) >= l && elem[0:l] == "/api/v1/healthz" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleGetHealthzRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET",
allowedHeaders: nil,
acceptPost: "",
acceptPatch: "",
})
}
return
}
}
}
s.notFound(w, r)
}
// Route is route object.
type Route struct {
name string
summary string
operationID string
operationGroup string
pathPattern string
count int
args [0]string
}
// Name returns ogen operation name.
//
// It is guaranteed to be unique and not empty.
func (r Route) Name() string {
return r.name
}
// Summary returns OpenAPI summary.
func (r Route) Summary() string {
return r.summary
}
// OperationID returns OpenAPI operationId.
func (r Route) OperationID() string {
return r.operationID
}
// OperationGroup returns the x-ogen-operation-group value.
func (r Route) OperationGroup() string {
return r.operationGroup
}
// PathPattern returns OpenAPI path.
func (r Route) PathPattern() string {
return r.pathPattern
}
// Args returns parsed arguments.
func (r Route) Args() []string {
return r.args[:r.count]
}
// FindRoute finds Route for given method and path.
//
// Note: this method does not unescape path or handle reserved characters in path properly. Use FindPath instead.
func (s *Server) FindRoute(method, path string) (Route, bool) {
return s.FindPath(method, &url.URL{Path: path})
}
// FindPath finds Route for given method and URL.
func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
var (
elem = u.Path
args = r.args
)
if rawPath := u.RawPath; rawPath != "" {
if normalized, ok := uri.NormalizeEscapedPath(rawPath); ok {
elem = normalized
}
defer func() {
for i, arg := range r.args[:r.count] {
if unescaped, err := url.PathUnescape(arg); err == nil {
r.args[i] = unescaped
}
}
}()
}
elem, ok := s.cutPrefix(elem)
if !ok {
return r, false
}
// Static code generated router with unwrapped path search.
switch {
default:
if len(elem) == 0 {
break
}
switch elem[0] {
case '/': // Prefix: "/api/v1/healthz"
if l := len("/api/v1/healthz"); len(elem) >= l && elem[0:l] == "/api/v1/healthz" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "GET":
r.name = GetHealthzOperation
r.summary = "Check whether the API process is responding."
r.operationID = "GetHealthz"
r.operationGroup = ""
r.pathPattern = "/api/v1/healthz"
r.args = args
r.count = 0
return r, true
default:
return
}
}
}
}
return r, false
}
@@ -0,0 +1,56 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"github.com/go-faster/errors"
)
// Ref: #/components/schemas/HealthResponse
type HealthResponse struct {
Status HealthResponseStatus `json:"status"`
}
// GetStatus returns the value of Status.
func (s *HealthResponse) GetStatus() HealthResponseStatus {
return s.Status
}
// SetStatus sets the value of Status.
func (s *HealthResponse) SetStatus(val HealthResponseStatus) {
s.Status = val
}
type HealthResponseStatus string
const (
HealthResponseStatusOk HealthResponseStatus = "ok"
)
// AllValues returns all HealthResponseStatus values.
func (HealthResponseStatus) AllValues() []HealthResponseStatus {
return []HealthResponseStatus{
HealthResponseStatusOk,
}
}
// MarshalText implements encoding.TextMarshaler.
func (s HealthResponseStatus) MarshalText() ([]byte, error) {
switch s {
case HealthResponseStatusOk:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *HealthResponseStatus) UnmarshalText(data []byte) error {
switch HealthResponseStatus(data) {
case HealthResponseStatusOk:
*s = HealthResponseStatusOk
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
}
@@ -0,0 +1,36 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"context"
)
// Handler handles operations described by OpenAPI v3 specification.
type Handler interface {
// GetHealthz implements GetHealthz operation.
//
// Check whether the API process is responding.
//
// GET /api/v1/healthz
GetHealthz(ctx context.Context) (*HealthResponse, error)
}
// Server implements http server based on OpenAPI v3 specification and
// calls Handler to handle requests.
type Server struct {
h Handler
baseServer
}
// NewServer creates new Server.
func NewServer(h Handler, opts ...ServerOption) (*Server, error) {
s, err := newServerConfig(opts...).baseServer()
if err != nil {
return nil, err
}
return &Server{
h: h,
baseServer: s,
}, nil
}
@@ -0,0 +1,23 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"context"
ht "github.com/ogen-go/ogen/http"
)
// UnimplementedHandler is no-op Handler which returns http.ErrNotImplemented.
type UnimplementedHandler struct{}
var _ Handler = UnimplementedHandler{}
// GetHealthz implements GetHealthz operation.
//
// Check whether the API process is responding.
//
// GET /api/v1/healthz
func (UnimplementedHandler) GetHealthz(ctx context.Context) (r *HealthResponse, _ error) {
return r, ht.ErrNotImplemented
}
@@ -0,0 +1,40 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"github.com/go-faster/errors"
"github.com/ogen-go/ogen/validate"
)
func (s *HealthResponse) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.Status.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "status",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s HealthResponseStatus) Validate() error {
switch s {
case "ok":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
@@ -0,0 +1,23 @@
package middleware
import (
"net/http"
"time"
"github.com/felixge/httpsnoop"
"github.com/go-chi/chi/v5"
)
type RequestMetrics interface {
ObserveRequest(method, route string, status int, duration time.Duration)
}
func CollectMetrics(metrics RequestMetrics) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
captured := httpsnoop.CaptureMetrics(next, w, r)
route := chi.RouteContext(r.Context()).RoutePattern()
metrics.ObserveRequest(r.Method, route, captured.Code, captured.Duration)
})
}
}
@@ -0,0 +1,30 @@
package httpadapter
import (
"log/slog"
"net/http"
"github.com/go-chi/chi/v5"
kitmiddleware "github.com/wahrwelt-kit/go-httpkit/httputil/middleware"
apiadapter "lincodex/backend/internal/adapter/primary/http/api"
httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
)
func NewRouter(health *v1.HealthHandler, collector httpmiddleware.RequestMetrics, logger *slog.Logger) (http.Handler, error) {
apiServer, err := apiadapter.NewServer(health)
if err != nil {
return nil, err
}
router := chi.NewRouter()
router.Use(kitmiddleware.RequestID())
router.Use(kitmiddleware.Recoverer(logger))
router.Use(kitmiddleware.Logger(logger, nil, kitmiddleware.WithSkipPaths("/healthz", "/readyz")))
router.Use(httpmiddleware.CollectMetrics(collector))
router.Get("/healthz", health.Healthz)
router.Get("/readyz", health.Readyz)
router.Handle("/api/v1/*", apiServer)
return router, nil
}
@@ -0,0 +1,82 @@
package httpadapter
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
"time"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
metrics "lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/usecase/health"
)
type readinessFunc func(context.Context) error
func (check readinessFunc) Check(ctx context.Context) error {
return check(ctx)
}
func TestOperationalHealthRoutes(t *testing.T) {
for _, test := range []struct {
name string
check readinessFunc
path string
statusCode int
bodyStatus string
}{
{name: "live", check: func(context.Context) error { return nil }, path: "/healthz", statusCode: http.StatusOK, bodyStatus: "ok"},
{name: "ready", check: func(context.Context) error { return nil }, path: "/readyz", statusCode: http.StatusOK, bodyStatus: "ready"},
{name: "not ready", check: func(context.Context) error { return context.DeadlineExceeded }, path: "/readyz", statusCode: http.StatusServiceUnavailable, bodyStatus: "not_ready"},
} {
t.Run(test.name, func(t *testing.T) {
router := newTestRouter(t, test.check)
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, test.path, nil))
if response.Code != test.statusCode {
t.Fatalf("status code = %d, want %d", response.Code, test.statusCode)
}
var body struct {
Status string `json:"status"`
}
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil {
t.Fatalf("decode response: %v", err)
}
if body.Status != test.bodyStatus {
t.Fatalf("status = %q, want %q", body.Status, test.bodyStatus)
}
})
}
}
func TestPublicHealthRouteUsesGeneratedOgenHandler(t *testing.T) {
router := newTestRouter(t, func(context.Context) error { return context.DeadlineExceeded })
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil))
if response.Code != http.StatusOK {
t.Fatalf("status code = %d, want %d: %s", response.Code, http.StatusOK, response.Body.String())
}
var body struct {
Status string `json:"status"`
}
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil {
t.Fatalf("decode response: %v", err)
}
if body.Status != "ok" {
t.Fatalf("status = %q, want %q", body.Status, "ok")
}
}
func newTestRouter(t *testing.T, checker readinessFunc) http.Handler {
t.Helper()
readiness := health.NewReadiness(checker)
healthHandler := v1.NewHealthHandler(readiness, time.Second)
router, err := NewRouter(healthHandler, metrics.New(), slog.New(slog.DiscardHandler))
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
return router
}
@@ -0,0 +1,46 @@
package v1
import (
"context"
"encoding/json"
"net/http"
"time"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/port/inbound"
)
type HealthHandler struct {
readiness inbound.Readiness
readinessTimeout time.Duration
}
func NewHealthHandler(readiness inbound.Readiness, readinessTimeout time.Duration) *HealthHandler {
return &HealthHandler{readiness: readiness, readinessTimeout: readinessTimeout}
}
func (handler *HealthHandler) GetHealthz(context.Context) (*api.HealthResponse, error) {
return &api.HealthResponse{Status: api.HealthResponseStatusOk}, nil
}
func (handler *HealthHandler) Healthz(w http.ResponseWriter, _ *http.Request) {
writeStatus(w, http.StatusOK, "ok")
}
func (handler *HealthHandler) Readyz(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), handler.readinessTimeout)
defer cancel()
if err := handler.readiness.Check(ctx); err != nil {
writeStatus(w, http.StatusServiceUnavailable, "not_ready")
return
}
writeStatus(w, http.StatusOK, "ready")
}
func writeStatus(w http.ResponseWriter, status int, value string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(struct {
Status string `json:"status"`
}{Status: value})
}
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,144 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"net/http"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/otelogen"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
)
var (
// Allocate option closure once.
clientSpanKind = trace.WithSpanKind(trace.SpanKindClient)
)
type (
optionFunc[C any] func(*C)
otelOptionFunc func(*otelConfig)
)
type otelConfig struct {
TracerProvider trace.TracerProvider
Tracer trace.Tracer
MeterProvider metric.MeterProvider
Meter metric.Meter
Attributes []attribute.KeyValue
}
func (cfg *otelConfig) initOTEL() {
if cfg.TracerProvider == nil {
cfg.TracerProvider = otel.GetTracerProvider()
}
if cfg.MeterProvider == nil {
cfg.MeterProvider = otel.GetMeterProvider()
}
cfg.Tracer = cfg.TracerProvider.Tracer(otelogen.Name,
trace.WithInstrumentationVersion(otelogen.SemVersion()),
)
cfg.Meter = cfg.MeterProvider.Meter(otelogen.Name,
metric.WithInstrumentationVersion(otelogen.SemVersion()),
)
}
type clientConfig struct {
otelConfig
Client ht.Client
}
// ClientOption is client config option.
type ClientOption interface {
applyClient(*clientConfig)
}
var _ ClientOption = (optionFunc[clientConfig])(nil)
func (o optionFunc[C]) applyClient(c *C) {
o(c)
}
var _ ClientOption = (otelOptionFunc)(nil)
func (o otelOptionFunc) applyClient(c *clientConfig) {
o(&c.otelConfig)
}
func newClientConfig(opts ...ClientOption) clientConfig {
cfg := clientConfig{
Client: http.DefaultClient,
}
for _, opt := range opts {
opt.applyClient(&cfg)
}
cfg.initOTEL()
return cfg
}
type baseClient struct {
cfg clientConfig
requests metric.Int64Counter
errors metric.Int64Counter
duration metric.Float64Histogram
}
func (cfg clientConfig) baseClient() (c baseClient, err error) {
c = baseClient{cfg: cfg}
if c.requests, err = otelogen.ClientRequestCountCounter(c.cfg.Meter); err != nil {
return c, err
}
if c.errors, err = otelogen.ClientErrorsCountCounter(c.cfg.Meter); err != nil {
return c, err
}
if c.duration, err = otelogen.ClientDurationHistogram(c.cfg.Meter); err != nil {
return c, err
}
return c, nil
}
// Option is config option.
type Option interface {
ClientOption
}
// WithTracerProvider specifies a tracer provider to use for creating a tracer.
//
// If none is specified, the global provider is used.
func WithTracerProvider(provider trace.TracerProvider) Option {
return otelOptionFunc(func(cfg *otelConfig) {
if provider != nil {
cfg.TracerProvider = provider
}
})
}
// WithMeterProvider specifies a meter provider to use for creating a meter.
//
// If none is specified, the otel.GetMeterProvider() is used.
func WithMeterProvider(provider metric.MeterProvider) Option {
return otelOptionFunc(func(cfg *otelConfig) {
if provider != nil {
cfg.MeterProvider = provider
}
})
}
// WithAttributes specifies default otel attributes.
func WithAttributes(attributes ...attribute.KeyValue) Option {
return otelOptionFunc(func(cfg *otelConfig) {
cfg.Attributes = attributes
})
}
// WithClient specifies http client to use.
func WithClient(client ht.Client) ClientOption {
return optionFunc[clientConfig](func(cfg *clientConfig) {
if client != nil {
cfg.Client = client
}
})
}
@@ -0,0 +1,241 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"context"
"io"
"net/url"
"strings"
"time"
"github.com/go-faster/errors"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/otelogen"
"github.com/ogen-go/ogen/uri"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
semconv "go.opentelemetry.io/otel/semconv/v1.39.0"
"go.opentelemetry.io/otel/trace"
)
func trimTrailingSlashes(u *url.URL) {
u.Path = strings.TrimRight(u.Path, "/")
u.RawPath = strings.TrimRight(u.RawPath, "/")
}
// Invoker invokes operations described by OpenAPI v3 specification.
type Invoker interface {
// GetMLHealthz invokes GetMLHealthz operation.
//
// Check whether the ML process is responding.
//
// GET /healthz
GetMLHealthz(ctx context.Context) (*MLHealthResponse, error)
// GetMLReadyz invokes GetMLReadyz operation.
//
// Check whether an inference runtime is available.
//
// GET /readyz
GetMLReadyz(ctx context.Context) (GetMLReadyzRes, error)
}
// Client implements OAS client.
type Client struct {
serverURL *url.URL
baseClient
}
// NewClient initializes new Client defined by OAS.
func NewClient(serverURL string, opts ...ClientOption) (*Client, error) {
u, err := url.Parse(serverURL)
if err != nil {
return nil, err
}
trimTrailingSlashes(u)
c, err := newClientConfig(opts...).baseClient()
if err != nil {
return nil, err
}
return &Client{
serverURL: u,
baseClient: c,
}, nil
}
type serverURLKey struct{}
// WithServerURL sets context key to override server URL.
func WithServerURL(ctx context.Context, u *url.URL) context.Context {
return context.WithValue(ctx, serverURLKey{}, u)
}
func (c *Client) requestURL(ctx context.Context) *url.URL {
u, ok := ctx.Value(serverURLKey{}).(*url.URL)
if !ok {
return c.serverURL
}
return u
}
// GetMLHealthz invokes GetMLHealthz operation.
//
// Check whether the ML process is responding.
//
// GET /healthz
func (c *Client) GetMLHealthz(ctx context.Context) (*MLHealthResponse, error) {
res, err := c.sendGetMLHealthz(ctx)
return res, err
}
func (c *Client) sendGetMLHealthz(ctx context.Context) (res *MLHealthResponse, err error) {
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("GetMLHealthz"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.URLTemplateKey.String("/healthz"),
}
otelAttrs = append(otelAttrs, c.cfg.Attributes...)
// Run stopwatch.
startTime := time.Now()
defer func() {
// Use floating point division here for higher precision (instead of Millisecond method).
elapsedDuration := time.Since(startTime)
c.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), metric.WithAttributes(otelAttrs...))
}()
// Increment request counter.
c.requests.Add(ctx, 1, metric.WithAttributes(otelAttrs...))
// Start a span for this request.
ctx, span := c.cfg.Tracer.Start(ctx, GetMLHealthzOperation,
trace.WithAttributes(otelAttrs...),
clientSpanKind,
)
// Track stage for error reporting.
var stage string
defer func() {
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, stage)
c.errors.Add(ctx, 1, metric.WithAttributes(otelAttrs...))
}
span.End()
}()
stage = "BuildURL"
u := uri.Clone(c.requestURL(ctx))
var pathParts [1]string
pathParts[0] = "/healthz"
uri.AddPathParts(u, pathParts[:]...)
stage = "EncodeRequest"
r, err := ht.NewRequest(ctx, "GET", u)
if err != nil {
return res, errors.Wrap(err, "create request")
}
stage = "SendRequest"
resp, err := c.cfg.Client.Do(r)
if err != nil {
return res, errors.Wrap(err, "do request")
}
body := resp.Body
defer func() {
// Drain the body to EOF before closing, so the underlying
// connection can be reused by the Transport regardless of the
// response status code. See https://github.com/ogen-go/ogen/issues/1670.
_, _ = io.Copy(io.Discard, body)
_ = body.Close()
}()
stage = "DecodeResponse"
result, err := decodeGetMLHealthzResponse(resp)
if err != nil {
return res, errors.Wrap(err, "decode response")
}
return result, nil
}
// GetMLReadyz invokes GetMLReadyz operation.
//
// Check whether an inference runtime is available.
//
// GET /readyz
func (c *Client) GetMLReadyz(ctx context.Context) (GetMLReadyzRes, error) {
res, err := c.sendGetMLReadyz(ctx)
return res, err
}
func (c *Client) sendGetMLReadyz(ctx context.Context) (res GetMLReadyzRes, err error) {
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("GetMLReadyz"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.URLTemplateKey.String("/readyz"),
}
otelAttrs = append(otelAttrs, c.cfg.Attributes...)
// Run stopwatch.
startTime := time.Now()
defer func() {
// Use floating point division here for higher precision (instead of Millisecond method).
elapsedDuration := time.Since(startTime)
c.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), metric.WithAttributes(otelAttrs...))
}()
// Increment request counter.
c.requests.Add(ctx, 1, metric.WithAttributes(otelAttrs...))
// Start a span for this request.
ctx, span := c.cfg.Tracer.Start(ctx, GetMLReadyzOperation,
trace.WithAttributes(otelAttrs...),
clientSpanKind,
)
// Track stage for error reporting.
var stage string
defer func() {
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, stage)
c.errors.Add(ctx, 1, metric.WithAttributes(otelAttrs...))
}
span.End()
}()
stage = "BuildURL"
u := uri.Clone(c.requestURL(ctx))
var pathParts [1]string
pathParts[0] = "/readyz"
uri.AddPathParts(u, pathParts[:]...)
stage = "EncodeRequest"
r, err := ht.NewRequest(ctx, "GET", u)
if err != nil {
return res, errors.Wrap(err, "create request")
}
stage = "SendRequest"
resp, err := c.cfg.Client.Do(r)
if err != nil {
return res, errors.Wrap(err, "do request")
}
body := resp.Body
defer func() {
// Drain the body to EOF before closing, so the underlying
// connection can be reused by the Transport regardless of the
// response status code. See https://github.com/ogen-go/ogen/issues/1670.
_, _ = io.Copy(io.Discard, body)
_ = body.Close()
}()
stage = "DecodeResponse"
result, err := decodeGetMLReadyzResponse(resp)
if err != nil {
return res, errors.Wrap(err, "decode response")
}
return result, nil
}
@@ -0,0 +1,6 @@
// Code generated by ogen, DO NOT EDIT.
package api
type GetMLReadyzRes interface {
getMLReadyzRes()
}
@@ -0,0 +1,354 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"math/bits"
"strconv"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"github.com/ogen-go/ogen/validate"
)
// Encode encodes GetMLReadyzOK as json.
func (s *GetMLReadyzOK) Encode(e *jx.Encoder) {
unwrapped := (*MLReadinessResponse)(s)
unwrapped.Encode(e)
}
// Decode decodes GetMLReadyzOK from json.
func (s *GetMLReadyzOK) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode GetMLReadyzOK to nil")
}
var unwrapped MLReadinessResponse
if err := func() error {
if err := unwrapped.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "alias")
}
*s = GetMLReadyzOK(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *GetMLReadyzOK) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *GetMLReadyzOK) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes GetMLReadyzServiceUnavailable as json.
func (s *GetMLReadyzServiceUnavailable) Encode(e *jx.Encoder) {
unwrapped := (*MLReadinessResponse)(s)
unwrapped.Encode(e)
}
// Decode decodes GetMLReadyzServiceUnavailable from json.
func (s *GetMLReadyzServiceUnavailable) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode GetMLReadyzServiceUnavailable to nil")
}
var unwrapped MLReadinessResponse
if err := func() error {
if err := unwrapped.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "alias")
}
*s = GetMLReadyzServiceUnavailable(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *GetMLReadyzServiceUnavailable) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *GetMLReadyzServiceUnavailable) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *MLHealthResponse) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *MLHealthResponse) encodeFields(e *jx.Encoder) {
{
e.FieldStart("status")
s.Status.Encode(e)
}
}
var jsonFieldsNameOfMLHealthResponse = [1]string{
0: "status",
}
// Decode decodes MLHealthResponse from json.
func (s *MLHealthResponse) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode MLHealthResponse to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "status":
requiredBitSet[0] |= 1 << 0
if err := func() error {
if err := s.Status.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"status\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode MLHealthResponse")
}
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [1]uint8{
0b00000001,
} {
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
// Mask only required fields and check equality to mask using XOR.
//
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
// Bits of fields which would be set are actually bits of missed fields.
missed := bits.OnesCount8(result)
for bitN := 0; bitN < missed; bitN++ {
bitIdx := bits.TrailingZeros8(result)
fieldIdx := i*8 + bitIdx
var name string
if fieldIdx < len(jsonFieldsNameOfMLHealthResponse) {
name = jsonFieldsNameOfMLHealthResponse[fieldIdx]
} else {
name = strconv.Itoa(fieldIdx)
}
failures = append(failures, validate.FieldError{
Name: name,
Error: validate.ErrFieldRequired,
})
// Reset bit.
result &^= 1 << bitIdx
}
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *MLHealthResponse) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *MLHealthResponse) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes MLHealthResponseStatus as json.
func (s MLHealthResponseStatus) Encode(e *jx.Encoder) {
e.Str(string(s))
}
// Decode decodes MLHealthResponseStatus from json.
func (s *MLHealthResponseStatus) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode MLHealthResponseStatus to nil")
}
v, err := d.StrBytes()
if err != nil {
return err
}
// Try to use constant string.
switch MLHealthResponseStatus(v) {
case MLHealthResponseStatusOk:
*s = MLHealthResponseStatusOk
default:
*s = MLHealthResponseStatus(v)
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s MLHealthResponseStatus) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *MLHealthResponseStatus) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *MLReadinessResponse) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *MLReadinessResponse) encodeFields(e *jx.Encoder) {
{
e.FieldStart("status")
s.Status.Encode(e)
}
}
var jsonFieldsNameOfMLReadinessResponse = [1]string{
0: "status",
}
// Decode decodes MLReadinessResponse from json.
func (s *MLReadinessResponse) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode MLReadinessResponse to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "status":
requiredBitSet[0] |= 1 << 0
if err := func() error {
if err := s.Status.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"status\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode MLReadinessResponse")
}
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [1]uint8{
0b00000001,
} {
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
// Mask only required fields and check equality to mask using XOR.
//
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
// Bits of fields which would be set are actually bits of missed fields.
missed := bits.OnesCount8(result)
for bitN := 0; bitN < missed; bitN++ {
bitIdx := bits.TrailingZeros8(result)
fieldIdx := i*8 + bitIdx
var name string
if fieldIdx < len(jsonFieldsNameOfMLReadinessResponse) {
name = jsonFieldsNameOfMLReadinessResponse[fieldIdx]
} else {
name = strconv.Itoa(fieldIdx)
}
failures = append(failures, validate.FieldError{
Name: name,
Error: validate.ErrFieldRequired,
})
// Reset bit.
result &^= 1 << bitIdx
}
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *MLReadinessResponse) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *MLReadinessResponse) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes MLReadinessResponseStatus as json.
func (s MLReadinessResponseStatus) Encode(e *jx.Encoder) {
e.Str(string(s))
}
// Decode decodes MLReadinessResponseStatus from json.
func (s *MLReadinessResponseStatus) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode MLReadinessResponseStatus to nil")
}
v, err := d.StrBytes()
if err != nil {
return err
}
// Try to use constant string.
switch MLReadinessResponseStatus(v) {
case MLReadinessResponseStatusReady:
*s = MLReadinessResponseStatusReady
case MLReadinessResponseStatusNotReady:
*s = MLReadinessResponseStatusNotReady
default:
*s = MLReadinessResponseStatus(v)
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s MLReadinessResponseStatus) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *MLReadinessResponseStatus) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
@@ -0,0 +1,11 @@
// Code generated by ogen, DO NOT EDIT.
package api
// OperationName is the ogen operation name
type OperationName = string
const (
GetMLHealthzOperation OperationName = "GetMLHealthz"
GetMLReadyzOperation OperationName = "GetMLReadyz"
)
@@ -0,0 +1,3 @@
// Code generated by ogen, DO NOT EDIT.
package api
@@ -0,0 +1,158 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"io"
"mime"
"net/http"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"github.com/ogen-go/ogen/ogenerrors"
"github.com/ogen-go/ogen/validate"
)
func decodeGetMLHealthzResponse(resp *http.Response) (res *MLHealthResponse, _ error) {
switch resp.StatusCode {
case 200:
// Code 200.
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return res, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
buf, err := io.ReadAll(resp.Body)
if err != nil {
return res, err
}
d := jx.DecodeBytes(buf)
var response MLHealthResponse
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return res, err
}
// Validate response.
if err := func() error {
if err := response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return res, errors.Wrap(err, "validate")
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
}
return res, validate.UnexpectedStatusCodeWithResponse(resp)
}
func decodeGetMLReadyzResponse(resp *http.Response) (res GetMLReadyzRes, _ error) {
switch resp.StatusCode {
case 200:
// Code 200.
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return res, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
buf, err := io.ReadAll(resp.Body)
if err != nil {
return res, err
}
d := jx.DecodeBytes(buf)
var response GetMLReadyzOK
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return res, err
}
// Validate response.
if err := func() error {
if err := response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return res, errors.Wrap(err, "validate")
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
case 503:
// Code 503.
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return res, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
buf, err := io.ReadAll(resp.Body)
if err != nil {
return res, err
}
d := jx.DecodeBytes(buf)
var response GetMLReadyzServiceUnavailable
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return res, err
}
// Validate response.
if err := func() error {
if err := response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return res, errors.Wrap(err, "validate")
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
}
return res, validate.UnexpectedStatusCodeWithResponse(resp)
}
@@ -0,0 +1,120 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"github.com/go-faster/errors"
)
type GetMLReadyzOK MLReadinessResponse
func (*GetMLReadyzOK) getMLReadyzRes() {}
type GetMLReadyzServiceUnavailable MLReadinessResponse
func (*GetMLReadyzServiceUnavailable) getMLReadyzRes() {}
// Ref: #/components/schemas/MLHealthResponse
type MLHealthResponse struct {
Status MLHealthResponseStatus `json:"status"`
}
// GetStatus returns the value of Status.
func (s *MLHealthResponse) GetStatus() MLHealthResponseStatus {
return s.Status
}
// SetStatus sets the value of Status.
func (s *MLHealthResponse) SetStatus(val MLHealthResponseStatus) {
s.Status = val
}
type MLHealthResponseStatus string
const (
MLHealthResponseStatusOk MLHealthResponseStatus = "ok"
)
// AllValues returns all MLHealthResponseStatus values.
func (MLHealthResponseStatus) AllValues() []MLHealthResponseStatus {
return []MLHealthResponseStatus{
MLHealthResponseStatusOk,
}
}
// MarshalText implements encoding.TextMarshaler.
func (s MLHealthResponseStatus) MarshalText() ([]byte, error) {
switch s {
case MLHealthResponseStatusOk:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *MLHealthResponseStatus) UnmarshalText(data []byte) error {
switch MLHealthResponseStatus(data) {
case MLHealthResponseStatusOk:
*s = MLHealthResponseStatusOk
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
}
// Ref: #/components/schemas/MLReadinessResponse
type MLReadinessResponse struct {
Status MLReadinessResponseStatus `json:"status"`
}
// GetStatus returns the value of Status.
func (s *MLReadinessResponse) GetStatus() MLReadinessResponseStatus {
return s.Status
}
// SetStatus sets the value of Status.
func (s *MLReadinessResponse) SetStatus(val MLReadinessResponseStatus) {
s.Status = val
}
type MLReadinessResponseStatus string
const (
MLReadinessResponseStatusReady MLReadinessResponseStatus = "ready"
MLReadinessResponseStatusNotReady MLReadinessResponseStatus = "not_ready"
)
// AllValues returns all MLReadinessResponseStatus values.
func (MLReadinessResponseStatus) AllValues() []MLReadinessResponseStatus {
return []MLReadinessResponseStatus{
MLReadinessResponseStatusReady,
MLReadinessResponseStatusNotReady,
}
}
// MarshalText implements encoding.TextMarshaler.
func (s MLReadinessResponseStatus) MarshalText() ([]byte, error) {
switch s {
case MLReadinessResponseStatusReady:
return []byte(s), nil
case MLReadinessResponseStatusNotReady:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *MLReadinessResponseStatus) UnmarshalText(data []byte) error {
switch MLReadinessResponseStatus(data) {
case MLReadinessResponseStatusReady:
*s = MLReadinessResponseStatusReady
return nil
case MLReadinessResponseStatusNotReady:
*s = MLReadinessResponseStatusNotReady
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
}
@@ -0,0 +1,90 @@
// Code generated by ogen, DO NOT EDIT.
package api
import (
"github.com/go-faster/errors"
"github.com/ogen-go/ogen/validate"
)
func (s *GetMLReadyzOK) Validate() error {
alias := (*MLReadinessResponse)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *GetMLReadyzServiceUnavailable) Validate() error {
alias := (*MLReadinessResponse)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *MLHealthResponse) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.Status.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "status",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s MLHealthResponseStatus) Validate() error {
switch s {
case "ok":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s *MLReadinessResponse) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.Status.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "status",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s MLReadinessResponseStatus) Validate() error {
switch s {
case "ready":
return nil
case "not_ready":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
Whitespace-only changes.
@@ -0,0 +1,44 @@
package postgres
import (
"context"
"fmt"
"github.com/jackc/pgx/v5/pgxpool"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/port/outbound"
)
type HealthChecker struct {
pool *pgxpool.Pool
queries *sqlc.Queries
}
func NewHealthChecker(ctx context.Context, config config.Config) (*HealthChecker, func(), error) {
if config.DatabaseURL == "" {
return &HealthChecker{}, func() {}, nil
}
poolConfig, err := pgxpool.ParseConfig(config.DatabaseURL)
if err != nil {
return nil, nil, fmt.Errorf("parse DATABASE_URL: %w", err)
}
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
if err != nil {
return nil, nil, fmt.Errorf("create PostgreSQL pool: %w", err)
}
return &HealthChecker{pool: pool, queries: sqlc.New(pool)}, pool.Close, nil
}
func (checker *HealthChecker) Check(ctx context.Context) error {
if checker.pool == nil || checker.queries == nil {
return outbound.ErrNotReady
}
if _, err := checker.queries.Ping(ctx); err != nil {
return fmt.Errorf("PostgreSQL health query: %w", err)
}
return nil
}
@@ -0,0 +1,22 @@
package postgres
import (
"context"
"errors"
"testing"
"lincodex/backend/config"
"lincodex/backend/internal/port/outbound"
)
func TestHealthCheckerWithoutDatabaseIsNotReady(t *testing.T) {
checker, closePool, err := NewHealthChecker(context.Background(), config.Config{})
if err != nil {
t.Fatalf("NewHealthChecker() error = %v", err)
}
closePool()
if err := checker.Check(context.Background()); !errors.Is(err, outbound.ErrNotReady) {
t.Fatalf("Check() error = %v, want ErrNotReady", err)
}
}
@@ -0,0 +1,32 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
package sqlc
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
type DBTX interface {
Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
Query(context.Context, string, ...interface{}) (pgx.Rows, error)
QueryRow(context.Context, string, ...interface{}) pgx.Row
}
func New(db DBTX) *Queries {
return &Queries{db: db}
}
type Queries struct {
db DBTX
}
func (q *Queries) WithTx(tx pgx.Tx) *Queries {
return &Queries{
db: tx,
}
}
@@ -0,0 +1,21 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: health.sql
package sqlc
import (
"context"
)
const ping = `-- name: Ping :one
SELECT 1::int4 AS alive
`
func (q *Queries) Ping(ctx context.Context) (int32, error) {
row := q.db.QueryRow(ctx, ping)
var alive int32
err := row.Scan(&alive)
return alive, err
}
@@ -0,0 +1,5 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
package sqlc
@@ -0,0 +1,15 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
package sqlc
import (
"context"
)
type Querier interface {
Ping(ctx context.Context) (int32, error)
}
var _ Querier = (*Queries)(nil)
@@ -0,0 +1,49 @@
package prometheus
import (
"net/http"
"strconv"
"time"
client "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
type Metrics struct {
registry *client.Registry
requests *client.CounterVec
latency *client.HistogramVec
}
func New() *Metrics {
registry := client.NewRegistry()
requests := client.NewCounterVec(client.CounterOpts{
Name: "lincodex_http_requests_total",
Help: "Total number of HTTP requests served by the API.",
}, []string{"method", "route", "status"})
latency := client.NewHistogramVec(client.HistogramOpts{
Name: "lincodex_http_request_duration_seconds",
Help: "HTTP request duration in seconds.",
Buckets: client.DefBuckets,
}, []string{"method", "route"})
registry.MustRegister(collectors.NewGoCollector(), collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}), requests, latency)
return &Metrics{registry: registry, requests: requests, latency: latency}
}
func (metrics *Metrics) ObserveRequest(method, route string, status int, duration time.Duration) {
if route == "" {
route = "unmatched"
}
switch method {
case http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete, http.MethodHead, http.MethodOptions:
default:
method = "OTHER"
}
metrics.requests.WithLabelValues(method, route, strconv.Itoa(status)).Inc()
metrics.latency.WithLabelValues(method, route).Observe(duration.Seconds())
}
func (metrics *Metrics) Handler() http.Handler {
return promhttp.HandlerFor(metrics.registry, promhttp.HandlerOpts{})
}
@@ -0,0 +1,23 @@
package prometheus
import (
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestMetricsHandlerExposesBoundedRequestLabels(t *testing.T) {
metrics := New()
metrics.ObserveRequest("CUSTOM", "", 599, 25*time.Millisecond)
response := httptest.NewRecorder()
metrics.Handler().ServeHTTP(response, httptest.NewRequest("GET", "/metrics", nil))
body := response.Body.String()
if !strings.Contains(body, `lincodex_http_requests_total{method="OTHER",route="unmatched",status="599"} 1`) {
t.Fatalf("metrics output is missing bounded request labels:\n%s", body)
}
if !strings.Contains(body, `lincodex_http_request_duration_seconds_bucket{method="OTHER",route="unmatched",le="0.05"} 1`) {
t.Fatalf("metrics output is missing request duration:\n%s", body)
}
}
Whitespace-only changes.
+158
View File
@@ -0,0 +1,158 @@
package bootstrap
import (
"context"
"errors"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/wahrwelt-kit/go-logkit"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/prometheus"
)
type Application struct {
config config.Config
apiHandler http.Handler
metrics *prometheus.Metrics
logger *slog.Logger
}
func NewApplication(config config.Config, apiHandler http.Handler, metrics *prometheus.Metrics, logger *slog.Logger) *Application {
return &Application{config: config, apiHandler: apiHandler, metrics: metrics, logger: logger}
}
func Run() (runErr error) {
settings, err := config.Load()
if err != nil {
return fmt.Errorf("load configuration: %w", err)
}
log, err := logkit.New(
logkit.WithLevel(logLevel(settings.LogLevel)),
logkit.WithServiceName("lincodex-backend"),
)
if err != nil {
return fmt.Errorf("create logger: %w", err)
}
defer func() {
runErr = errors.Join(runErr, log.Close())
}()
logger := slog.New(logkit.SlogHandler(log))
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if err := run(ctx, settings, logger); err != nil {
logger.ErrorContext(ctx, "application stopped", slog.Any("error", err))
return err
}
logger.Info("application stopped")
return nil
}
func run(ctx context.Context, config config.Config, logger *slog.Logger) error {
if err := config.Validate(); err != nil {
return fmt.Errorf("validate configuration: %w", err)
}
application, cleanup, err := initialize(ctx, config, logger)
if err != nil {
return fmt.Errorf("initialize application: %w", err)
}
defer cleanup()
return application.run(ctx)
}
func logLevel(value string) logkit.Level {
switch value {
case "debug":
return logkit.DebugLevel
case "warn":
return logkit.WarnLevel
case "error":
return logkit.ErrorLevel
default:
return logkit.InfoLevel
}
}
func (application *Application) run(ctx context.Context) error {
var listenerConfig net.ListenConfig
apiListener, err := listenerConfig.Listen(ctx, "tcp", application.config.HTTPAddr)
if err != nil {
return fmt.Errorf("listen on HTTP_ADDR: %w", err)
}
metricsListener, err := listenerConfig.Listen(ctx, "tcp", application.config.MetricsAddr)
if err != nil {
_ = apiListener.Close()
return fmt.Errorf("listen on METRICS_ADDR: %w", err)
}
application.logger.Info("servers started",
slog.String("http_addr", application.config.HTTPAddr),
slog.String("metrics_addr", application.config.MetricsAddr),
)
apiServer := &http.Server{
Handler: application.apiHandler,
ReadHeaderTimeout: 5 * time.Second,
IdleTimeout: 60 * time.Second,
}
metricsServer := &http.Server{
Handler: application.metrics.Handler(),
ReadHeaderTimeout: 5 * time.Second,
IdleTimeout: 60 * time.Second,
}
err = serveServers(ctx, apiListener, apiServer, metricsListener, metricsServer, application.config.ShutdownTimeout)
application.logger.Info("servers stopped")
return err
}
func serveServers(ctx context.Context, apiListener net.Listener, apiServer *http.Server, metricsListener net.Listener, metricsServer *http.Server, shutdownTimeout time.Duration) error {
type serveResult struct {
name string
err error
}
results := make(chan serveResult, 2)
go func() { results <- serveResult{name: "API", err: apiServer.Serve(apiListener)} }()
go func() { results <- serveResult{name: "metrics", err: metricsServer.Serve(metricsListener)} }()
serving := 2
var runErr error
select {
case <-ctx.Done():
case result := <-results:
serving--
if result.err != nil && !errors.Is(result.err, http.ErrServerClosed) {
runErr = fmt.Errorf("%s server stopped: %w", result.name, result.err)
}
}
shutdownContext, cancel := context.WithTimeout(context.WithoutCancel(ctx), shutdownTimeout)
defer cancel()
var shutdownErr error
for _, server := range []*http.Server{apiServer, metricsServer} {
if err := server.Shutdown(shutdownContext); err != nil {
shutdownErr = errors.Join(shutdownErr, err)
if closeErr := server.Close(); closeErr != nil {
shutdownErr = errors.Join(shutdownErr, closeErr)
}
}
}
for serving > 0 {
result := <-results
serving--
if result.err != nil && !errors.Is(result.err, http.ErrServerClosed) {
runErr = errors.Join(runErr, fmt.Errorf("%s server stopped: %w", result.name, result.err))
}
}
if shutdownErr != nil {
return errors.Join(runErr, fmt.Errorf("shut down servers: %w", shutdownErr))
}
return runErr
}
+65
View File
@@ -0,0 +1,65 @@
package bootstrap
import (
"context"
"net"
"net/http"
"strings"
"testing"
"time"
)
func TestServeServersGracefullyStopsOnCancellation(t *testing.T) {
apiListener := listenForTest(t)
metricsListener := listenForTest(t)
ctx, cancel := context.WithCancel(context.Background())
cancel()
err := serveServers(
ctx,
apiListener,
&http.Server{Handler: http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})},
metricsListener,
&http.Server{Handler: http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})},
time.Second,
)
if err != nil {
t.Fatalf("serveServers() error = %v", err)
}
}
func TestServeServersStopsBothListenersWhenOneFails(t *testing.T) {
apiListener := listenForTest(t)
if err := apiListener.Close(); err != nil {
t.Fatalf("close API listener: %v", err)
}
metricsListener := listenForTest(t)
metricsAddress := metricsListener.Addr().String()
err := serveServers(
context.Background(),
apiListener,
&http.Server{Handler: http.NotFoundHandler()},
metricsListener,
&http.Server{Handler: http.NotFoundHandler()},
time.Second,
)
if err == nil || !strings.Contains(err.Error(), "API server stopped") {
t.Fatalf("serveServers() error = %v, want API server failure", err)
}
dialContext, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
if _, err := (&net.Dialer{}).DialContext(dialContext, "tcp", metricsAddress); err == nil {
t.Fatal("metrics listener is still accepting connections after API server failure")
}
}
func listenForTest(t *testing.T) net.Listener {
t.Helper()
listener, err := (&net.ListenConfig{}).Listen(context.Background(), "tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
t.Cleanup(func() { _ = listener.Close() })
return listener
}
+41
View File
@@ -0,0 +1,41 @@
//go:build wireinject
package bootstrap
import (
"context"
"log/slog"
"github.com/goforj/wire"
"lincodex/backend/config"
httpadapter "lincodex/backend/internal/adapter/primary/http"
httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/postgres"
metrics "lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/health"
)
func initialize(ctx context.Context, config config.Config, logger *slog.Logger) (*Application, func(), error) {
wire.Build(
wire.NewSet(
postgres.NewHealthChecker,
wire.Bind(new(outbound.ReadinessChecker), new(*postgres.HealthChecker)),
wire.Bind(new(inbound.Readiness), new(*health.Readiness)),
wire.Bind(new(httpmiddleware.RequestMetrics), new(*metrics.Metrics)),
health.NewReadiness,
metrics.New,
newHealthHandler,
httpadapter.NewRouter,
NewApplication,
),
)
return nil, nil, nil
}
func newHealthHandler(readiness inbound.Readiness, config config.Config) *v1.HealthHandler {
return v1.NewHealthHandler(readiness, config.ReadinessTimeout)
}
+46
View File
@@ -0,0 +1,46 @@
// Code generated by Wire. DO NOT EDIT.
//go:generate go run -mod=mod github.com/goforj/wire/cmd/wire
//go:build !wireinject
// +build !wireinject
package bootstrap
import (
"context"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/primary/http"
"lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/usecase/health"
"log/slog"
)
// Injectors from wire.go:
func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger) (*Application, func(), error) {
healthChecker, cleanup, err := postgres.NewHealthChecker(ctx, config2)
if err != nil {
return nil, nil, err
}
readiness := health.NewReadiness(healthChecker)
healthHandler := newHealthHandler(readiness, config2)
metrics := prometheus.New()
handler, err := httpadapter.NewRouter(healthHandler, metrics, logger)
if err != nil {
cleanup()
return nil, nil, err
}
application := NewApplication(config2, handler, metrics, logger)
return application, func() {
cleanup()
}, nil
}
// wire.go:
func newHealthHandler(readiness inbound.Readiness, config2 config.Config) *v1.HealthHandler {
return v1.NewHealthHandler(readiness, config2.ReadinessTimeout)
}
View File
Whitespace-only changes.
@@ -0,0 +1,7 @@
package inbound
import "context"
type Readiness interface {
Check(ctx context.Context) error
}
@@ -0,0 +1,12 @@
package outbound
import (
"context"
"errors"
)
var ErrNotReady = errors.New("service is not ready")
type ReadinessChecker interface {
Check(ctx context.Context) error
}
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,23 @@
package health
import (
"context"
"fmt"
"lincodex/backend/internal/port/outbound"
)
type Readiness struct {
checker outbound.ReadinessChecker
}
func NewReadiness(checker outbound.ReadinessChecker) *Readiness {
return &Readiness{checker: checker}
}
func (readiness *Readiness) Check(ctx context.Context) error {
if err := readiness.checker.Check(ctx); err != nil {
return fmt.Errorf("readiness check failed: %w", err)
}
return nil
}
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
View File
Whitespace-only changes.
Whitespace-only changes.
View File
Whitespace-only changes.
View File
Whitespace-only changes.
+2
View File
@@ -0,0 +1,2 @@
PyYAML==6.0.3
sqlfluff==4.3.0
+53
View File
@@ -0,0 +1,53 @@
package compat
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)
type compatibilityHandler struct{}
func (compatibilityHandler) GetProbe(context.Context, GetProbeParams) (*NullablePayload, error) {
return &NullablePayload{}, nil
}
func (compatibilityHandler) PurgeProbe(context.Context) error {
return nil
}
func TestGeneratedServerRejectsInvalidInput(t *testing.T) {
server, err := NewServer(compatibilityHandler{})
if err != nil {
t.Fatalf("NewServer() error = %v", err)
}
response := httptest.NewRecorder()
server.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/probe?state=invalid", nil))
if response.Code != http.StatusBadRequest {
t.Fatalf("status code = %d, want %d", response.Code, http.StatusBadRequest)
}
}
func TestNullableTypeArrayPreservesNull(t *testing.T) {
var payload NullablePayload
if err := json.Unmarshal([]byte(`{"value":null}`), &payload); err != nil {
t.Fatalf("decode nullable payload: %v", err)
}
if !payload.Value.IsNull() {
t.Fatal("nullable value was not represented as null")
}
}
func TestAdditionalOperationIsRouted(t *testing.T) {
server, err := NewServer(compatibilityHandler{})
if err != nil {
t.Fatalf("NewServer() error = %v", err)
}
response := httptest.NewRecorder()
server.ServeHTTP(response, httptest.NewRequest("PURGE", "/probe", nil))
if response.Code != http.StatusNoContent {
t.Fatalf("status code = %d, want %d", response.Code, http.StatusNoContent)
}
}