diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..11287d5 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,40 @@ +# Build, lint and test the module. +name: ci + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + check: + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/setup-go@0aaccfd150d50ccaeb58ebd88d36e91967a5f35b # v5 + with: + go-version-file: go.mod + - name: Build and test + run: | + set -euo pipefail + go build ./... && go vet ./... && go test -race ./... + + lint: + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/setup-go@0aaccfd150d50ccaeb58ebd88d36e91967a5f35b # v5 + with: + go-version-file: go.mod + - uses: golangci/golangci-lint-action@9fae48acfc02a90574d7c304a1758ef9895495fa # v7 + with: + version: v2.11.3 diff --git a/.github/workflows/pr-title.yml b/.github/workflows/pr-title.yml new file mode 100644 index 0000000..51f72c9 --- /dev/null +++ b/.github/workflows/pr-title.yml @@ -0,0 +1,23 @@ +name: PR Title + +# Conventional-commit titles feed the release-please changelog and version. + +on: + pull_request: + branches: [main] + types: [opened, edited, synchronize, reopened] + +concurrency: + group: pr-title-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + pr-title: + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + pull-requests: read + steps: + - uses: amannn/action-semantic-pull-request@48f256284bd46cdaab1048c3721360e808335d50 # v6 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml new file mode 100644 index 0000000..d0f2e9c --- /dev/null +++ b/.github/workflows/release-please.yml @@ -0,0 +1,23 @@ +name: Release Please + +# Versioning only: a release is the changelog plus the `vX.Y.Z` tag that +# consumers pin in their go.mod. + +on: + push: + branches: [main] + +permissions: + contents: write + pull-requests: write + +jobs: + release-please: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: googleapis/release-please-action@v4 + with: + token: ${{ secrets.GITHUB_TOKEN }} + config-file: release-please-config.json + manifest-file: .release-please-manifest.json diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..4908c15 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,519 @@ +# Lint standards for this module: the platform repo's config (the api's golden +# config based on github.com/maratori/golangci-lint-config, with wrapcheck +# enabled and no new-from-merge-base filter), so the whole module stays clean. +# This file is licensed under the terms of the MIT license https://opensource.org/license/mit +# Copyright (c) 2021-2025 Marat Reimers + +## Golden config for golangci-lint v2.11.3 +# +# This is the best config for golangci-lint based on my experience and opinion. +# It is very strict, but not extremely strict. +# Feel free to adapt it to suit your needs. +# If this config helps you, please consider keeping a link to this repo (see the next comment). + +# Based on https://github.com/maratori/golangci-lint-config + +version: "2" + +issues: + # Maximum count of issues with the same text. + # Set to 0 to disable. + # Default: 3 + max-same-issues: 50 + + +formatters: + enable: + - goimports # checks if the code and import statements are formatted according to the 'goimports' command + - golines # checks if code is formatted, and fixes long lines + - gci # checks if code and import statements are formatted, with additional rules + - gofmt # checks if the code is formatted according to 'gofmt' command + - gofumpt # enforces a stricter format than 'gofmt', while being backwards compatible + + # All settings can be found here https://github.com/golangci/golangci-lint/blob/HEAD/.golangci.reference.yml + settings: + goimports: + # A list of prefixes, which, if set, checks import paths + # with the given prefixes are grouped after 3rd-party packages. + # Default: [] + local-prefixes: + - github.com/MetsaApp/platform-kit + + gci: + sections: + - standard + - default + - prefix(github.com/MetsaApp/platform-kit) + + golines: + # Target maximum line length. + # Default: 100 + max-len: 120 + +linters: + enable: + - asasalint # checks for pass []any as any in variadic func(...any) + - asciicheck # checks that your code does not contain non-ASCII identifiers + - bidichk # checks for dangerous unicode character sequences + - bodyclose # checks whether HTTP response body is closed successfully + - canonicalheader # checks whether net/http.Header uses canonical header + - copyloopvar # detects places where loop variables are copied (Go 1.22+) + - cyclop # checks function and package cyclomatic complexity + - depguard # checks if package imports are in a list of acceptable packages + - dupl # tool for code clone detection + - durationcheck # checks for two durations multiplied together + - embeddedstructfieldcheck # checks embedded types in structs + - errcheck # checking for unchecked errors, these unchecked errors can be critical bugs in some cases + - errname # checks that sentinel errors are prefixed with the Err and error types are suffixed with the Error + - errorlint # finds code that will cause problems with the error wrapping scheme introduced in Go 1.13 + - wrapcheck # checks that errors returned from external packages are wrapped + - exhaustive # checks exhaustiveness of enum switch statements + - exptostd # detects functions from golang.org/x/exp/ that can be replaced by std functions + - fatcontext # detects nested contexts in loops + - forbidigo # forbids identifiers + - funcorder # checks the order of functions, methods, and constructors + - funlen # tool for detection of long functions + - gocheckcompilerdirectives # validates go compiler directive comments (//go:) + - gochecknoglobals # checks that no global variables exist + - gochecknoinits # checks that no init functions are present in Go code + - gochecksumtype # checks exhaustiveness on Go "sum types" + - gocognit # computes and checks the cognitive complexity of functions + - goconst # finds repeated strings that could be replaced by a constant + - gocritic # provides diagnostics that check for bugs, performance and style issues + - gocyclo # computes and checks the cyclomatic complexity of functions + - godoclint # checks Golang's documentation practice + - godot # checks if comments end in a period + - gomoddirectives # manages the use of 'replace', 'retract', and 'excludes' directives in go.mod + - goprintffuncname # checks that printf-like functions are named with f at the end + - gosec # inspects source code for security problems + - govet # reports suspicious constructs, such as Printf calls whose arguments do not align with the format string + - iface # checks the incorrect use of interfaces, helping developers avoid interface pollution + - ineffassign # detects when assignments to existing variables are not used + - intrange # finds places where for loops could make use of an integer range + - iotamixing # checks if iotas are being used in const blocks with other non-iota declarations + - loggercheck # checks key value pairs for common logger libraries (kitlog,klog,logr,zap) + - makezero # finds slice declarations with non-zero initial length + - mirror # reports wrong mirror patterns of bytes/strings usage + - mnd # detects magic numbers + - modernize # suggests simplifications to Go code, using modern language and library features + - musttag # enforces field tags in (un)marshaled structs + - nakedret # finds naked returns in functions greater than a specified function length + - nestif # reports deeply nested if statements + - nilerr # finds the code that returns nil even if it checks that the error is not nil + - nilnesserr # reports that it checks for err != nil, but it returns a different nil value error (powered by nilness and nilerr) + - nilnil # checks that there is no simultaneous return of nil error and an invalid value + - noctx # finds sending http request without context.Context + - nolintlint # reports ill-formed or insufficient nolint directives + - nonamedreturns # reports all named returns + - nosprintfhostport # checks for misuse of Sprintf to construct a host with port in a URL + - perfsprint # checks that fmt.Sprintf can be replaced with a faster alternative + - predeclared # finds code that shadows one of Go's predeclared identifiers + - promlinter # checks Prometheus metrics naming via promlint + - protogetter # reports direct reads from proto message fields when getters should be used + - reassign # checks that package variables are not reassigned + - recvcheck # checks for receiver type consistency + - revive # fast, configurable, extensible, flexible, and beautiful linter for Go, drop-in replacement of golint + - rowserrcheck # checks whether Err of rows is checked successfully + - sloglint # ensure consistent code style when using log/slog + - spancheck # checks for mistakes with OpenTelemetry/Census spans + - sqlclosecheck # checks that sql.Rows and sql.Stmt are closed + - staticcheck # is a go vet on steroids, applying a ton of static analysis checks + - testableexamples # checks if examples are testable (have an expected output) + - testifylint # checks usage of github.com/stretchr/testify + - testpackage # makes you use a separate _test package + - tparallel # detects inappropriate usage of t.Parallel() method in your Go test codes + - unconvert # removes unnecessary type conversions + - unparam # reports unused function parameters + - unqueryvet # detects SELECT * in SQL queries and SQL builders, encouraging explicit column selection + - unused # checks for unused constants, variables, functions and types + - usestdlibvars # detects the possibility to use variables/constants from the Go standard library + - usetesting # reports uses of functions with replacement inside the testing package + - wastedassign # finds wasted assignment statements + - whitespace # detects leading and trailing whitespace + + ## you may want to enable + #- arangolint # opinionated best practices for arangodb client + #- decorder # checks declaration order and count of types, constants, variables and functions + #- exhaustruct # [highly recommend to enable] checks if all structure fields are initialized + #- ginkgolinter # [if you use ginkgo/gomega] enforces standards of using ginkgo and gomega + #- godox # detects usage of FIXME, TODO and other keywords inside comments + #- goheader # checks is file header matches to pattern + #- inamedparam # [great idea, but too strict, need to ignore a lot of cases by default] reports interfaces with unnamed method parameters + #- interfacebloat # checks the number of methods inside an interface + #- ireturn # accept interfaces, return concrete types + #- noinlineerr # disallows inline error handling `if err := ...; err != nil {` + #- prealloc # [premature optimization, but can be used in some cases] finds slice declarations that could potentially be preallocated + #- tagalign # checks that struct tags are well aligned + #- varnamelen # [great idea, but too many false positives] checks that the length of a variable's name matches its scope + #- zerologlint # detects the wrong usage of zerolog that a user forgets to dispatch zerolog.Event + + ## disabled + #- containedctx # detects struct contained context.Context field + #- contextcheck # [too many false positives] checks the function whether use a non-inherited context + #- dogsled # checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) + #- dupword # [useless without config] checks for duplicate words in the source code + #- err113 # [too strict] checks the errors handling expressions + #- errchkjson # [don't see profit + I'm against of omitting errors like in the first example https://github.com/breml/errchkjson] checks types passed to the json encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted + #- forcetypeassert # [replaced by errcheck] finds forced type assertions + #- gomodguard # [use more powerful depguard] allow and block lists linter for direct Go module dependencies + #- gosmopolitan # reports certain i18n/l10n anti-patterns in your Go codebase + #- grouper # analyzes expression groups + #- importas # enforces consistent import aliases + #- lll # [replaced by golines] reports long lines + #- maintidx # measures the maintainability index of each function + #- misspell # [useless] finds commonly misspelled English words in comments + #- nlreturn # [too strict and mostly code is not more readable] checks for a new line before return and branch statements to increase code clarity + #- paralleltest # [too many false positives] detects missing usage of t.Parallel() method in your Go test + #- tagliatelle # checks the struct tags + #- thelper # detects golang test helpers without t.Helper() call and checks the consistency of test helpers + #- wsl # [too strict and mostly code is not more readable] whitespace linter forces you to use empty lines + #- wsl_v5 # [too strict and mostly code is not more readable] add or remove empty lines + + # All settings can be found here https://github.com/golangci/golangci-lint/blob/HEAD/.golangci.reference.yml + settings: + cyclop: + # The maximal code complexity to report. + # Default: 10 + max-complexity: 30 + # The maximal average package complexity. + # If it's higher than 0.0 (float) the check is enabled. + # Disabled because generated templ code inflates the average. + # Default: 0.0 + package-average: 0.0 + + depguard: + # Rules to apply. + # + # Variables: + # - File Variables + # Use an exclamation mark `!` to negate a variable. + # Example: `!$test` matches any file that is not a go test file. + # + # `$all` - matches all go files + # `$test` - matches all go test files + # + # - Package Variables + # + # `$gostd` - matches all of go's standard library (Pulled from `GOROOT`) + # + # Default (applies if no custom rules are defined): Only allow $gostd in all files. + rules: + "deprecated": + # List of file globs that will match this list of settings to compare against. + # By default, if a path is relative, it is relative to the directory where the golangci-lint command is executed. + # The placeholder '${base-path}' is substituted with a path relative to the mode defined with `run.relative-path-mode`. + # The placeholder '${config-path}' is substituted with a path relative to the configuration file. + # Default: $all + files: + - "$all" + # List of packages that are not allowed. + # Entries can be a variable (starting with $), a string prefix, or an exact match (if ending with $). + # Default: [] + deny: + - pkg: github.com/golang/protobuf + desc: Use google.golang.org/protobuf instead, see https://developers.google.com/protocol-buffers/docs/reference/go/faq#modules + - pkg: github.com/satori/go.uuid + desc: Use github.com/google/uuid instead, satori's package is not maintained + - pkg: github.com/gofrs/uuid$ + desc: Use github.com/gofrs/uuid/v5 or later, it was not a go module before v5 + "non-test files": + files: + - "!$test" + deny: + - pkg: math/rand$ + desc: Use math/rand/v2 instead, see https://go.dev/blog/randv2 + "non-main files": + files: + - "!**/main.go" + deny: + - pkg: log$ + desc: Use log/slog instead, see https://go.dev/blog/slog + + embeddedstructfieldcheck: + # Checks that sync.Mutex and sync.RWMutex are not used as embedded fields. + # Default: false + forbid-mutex: true + + errcheck: + # Report about not checking of errors in type assertions: `a := b.(MyStruct)`. + # Such cases aren't reported by default. + # Default: false + check-type-assertions: true + + exhaustive: + # Program elements to check for exhaustiveness. + # Default: [ switch ] + check: + - switch + - map + + exhaustruct: + # List of regular expressions to match type names that should be excluded from processing. + # Anonymous structs can be matched by '' alias. + # Has precedence over `include`. + # Each regular expression must match the full type name, including package path. + # For example, to match type `net/http.Cookie` regular expression should be `.*/http\.Cookie`, + # but not `http\.Cookie`. + # Default: [] + exclude: + # std libs + - ^net/http.Client$ + - ^net/http.Cookie$ + - ^net/http.Request$ + - ^net/http.Response$ + - ^net/http.Server$ + - ^net/http.Transport$ + - ^net/url.URL$ + - ^os/exec.Cmd$ + - ^reflect.StructField$ + # public libs + - ^github.com/Shopify/sarama.Config$ + - ^github.com/Shopify/sarama.ProducerMessage$ + - ^github.com/mitchellh/mapstructure.DecoderConfig$ + - ^github.com/prometheus/client_golang/.+Opts$ + - ^github.com/spf13/cobra.Command$ + - ^github.com/spf13/cobra.CompletionOptions$ + - ^github.com/stretchr/testify/mock.Mock$ + - ^github.com/testcontainers/testcontainers-go.+Request$ + - ^github.com/testcontainers/testcontainers-go.FromDockerfile$ + - ^golang.org/x/tools/go/analysis.Analyzer$ + - ^google.golang.org/protobuf/.+Options$ + - ^gopkg.in/yaml.v3.Node$ + # Allows empty structures in return statements. + # Default: false + allow-empty-returns: true + + funcorder: + # Checks if the exported methods of a structure are placed before the non-exported ones. + # Default: true + struct-method: false + + funlen: + # Checks the number of lines in a function. + # If lower than 0, disable the check. + # Default: 60 + lines: 100 + # Checks the number of statements in a function. + # If lower than 0, disable the check. + # Default: 40 + statements: 50 + + gomoddirectives: + replace-local: false + + gochecksumtype: + # Presence of `default` case in switch statements satisfies exhaustiveness, if all members are not listed. + # Default: true + default-signifies-exhaustive: false + + gocognit: + # Minimal code complexity to report. + # Default: 30 (but we recommend 10-20) + min-complexity: 20 + + gocritic: + # Settings passed to gocritic. + # The settings key is the name of a supported gocritic checker. + # The list of supported checkers can be found at https://go-critic.com/overview. + settings: + captLocal: + # Whether to restrict checker to params only. + # Default: true + paramsOnly: false + underef: + # Whether to skip (*x).method() calls where x is a pointer receiver. + # Default: true + skipRecvDeref: false + + godoclint: + # List of rules to enable in addition to the default set. + # Default: empty + enable: + # Assert no unused link in godocs. + # https://github.com/godoc-lint/godoc-lint?tab=readme-ov-file#no-unused-link + - no-unused-link + # Require proper doc links to standard library declarations where applicable. + # https://github.com/godoc-lint/godoc-lint?tab=readme-ov-file#require-stdlib-doclink + - require-stdlib-doclink + + govet: + # Enable all analyzers. + # Default: false + enable-all: true + # Disable analyzers by name. + # Run `GL_DEBUG=govet golangci-lint run --enable=govet` to see default, all available analyzers, and enabled analyzers. + # Default: [] + disable: + - fieldalignment # too strict + # Settings per analyzer. + settings: + shadow: + # Whether to be strict about shadowing; can be noisy. + # Default: false + strict: true + + inamedparam: + # Skips check for interface methods with only a single parameter. + # Default: false + skip-single-param: true + + mnd: + # List of function patterns to exclude from analysis. + # Values always ignored: `time.Date`, + # `strconv.FormatInt`, `strconv.FormatUint`, `strconv.FormatFloat`, + # `strconv.ParseInt`, `strconv.ParseUint`, `strconv.ParseFloat`. + # Default: [] + ignored-functions: + - args.Error + - flag.Arg + - flag.Duration.* + - flag.Float.* + - flag.Int.* + - flag.Uint.* + - os.Chmod + - os.Mkdir.* + - os.OpenFile + - os.WriteFile + - prometheus.ExponentialBuckets.* + - prometheus.LinearBuckets + + wrapcheck: + # The defaults, plus the gateway client's handling outcomes: Retry + # and Drop are error constructors like errors.New, and returning + # one from a handler is the point, not an unwrapped foreign error. + ignore-sigs: + - .Errorf( + - errors.New( + - errors.Unwrap( + - errors.Join( + - .Wrap( + - .Wrapf( + - .WithMessage( + - .WithMessagef( + - .WithStack( + + nakedret: + # Make an issue if func has more lines of code than this setting, and it has naked returns. + # Default: 30 + max-func-lines: 0 + + nolintlint: + # Exclude following linters from requiring an explanation. + # Default: [] + allow-no-explanation: [funlen, gocognit, golines] + # Enable to require an explanation of nonzero length after each nolint directive. + # Default: false + require-explanation: true + # Enable to require nolint directives to mention the specific linter being suppressed. + # Default: false + require-specific: true + + perfsprint: + # Optimizes into strings concatenation. + # Default: true + strconcat: false + + reassign: + # Patterns for global variable names that are checked for reassignment. + # See https://github.com/curioswitch/go-reassign#usage + # Default: ["EOF", "Err.*"] + patterns: + - ".*" + + rowserrcheck: + # database/sql is always checked. + # Default: [] + packages: + - github.com/jmoiron/sqlx + + sloglint: + # Enforce not using global loggers. + # Values: + # - "": disabled + # - "all": report all global loggers + # - "default": report only the default slog logger + # https://github.com/go-simpler/sloglint?tab=readme-ov-file#no-global + # Default: "" + no-global: all + # Enforce using methods that accept a context. + # Values: + # - "": disabled + # - "all": report all contextless calls + # - "scope": report only if a context exists in the scope of the outermost function + # https://github.com/go-simpler/sloglint?tab=readme-ov-file#context-only + # Default: "" + context: scope + + staticcheck: + # SAxxxx checks in https://staticcheck.dev/docs/configuration/options/#checks + # Example (to disable some checks): [ "all", "-SA1000", "-SA1001"] + # Default: ["all", "-ST1000", "-ST1003", "-ST1016", "-ST1020", "-ST1021", "-ST1022"] + checks: + - all + # Incorrect or missing package comment. + # https://staticcheck.dev/docs/checks/#ST1000 + - -ST1000 + # Use consistent method receiver names. + # https://staticcheck.dev/docs/checks/#ST1016 + - -ST1016 + # Omit embedded fields from selector expression. + # https://staticcheck.dev/docs/checks/#QF1008 + - -QF1008 + + usetesting: + # Enable/disable `os.TempDir()` detections. + # Default: false + os-temp-dir: true + + exclusions: + # Auto-detect generated files via the standard `Code generated … + # DO NOT EDIT` header and skip linting them. Covers oapi-codegen + # (.gen.go), sqlc (dbmodels/*), and templ (*_templ.go) without + # needing a path rule per tool. `lax` matches the conventional + # marker comment; `strict` also requires the marker on the first + # line, which sqlc + templ don't quite satisfy. + generated: lax + + # Predefined exclusion rules. + # Default: [] + presets: + - std-error-handling + - common-false-positives + # Excluding configuration per-path, per-linter, per-text and per-source. + rules: + - source: "TODO" + linters: [godot] + - source: "// @\\w+" + linters: [godot] + - text: "should have a package comment" + linters: [revive] + - text: 'exported \S+ \S+ should have comment( \(or a comment on this block\))? or be unexported' + linters: [revive] + - text: 'package comment should be of the form ".+"' + source: "// ?(nolint|TODO)" + linters: [revive] + - text: 'comment on exported \S+ \S+ should be of the form ".+"' + source: "// ?(nolint|TODO)" + linters: [revive, staticcheck] + - text: "avoid package names that conflict with Go standard library" + linters: [revive] + - path: '_test\.go' + linters: + - bodyclose + - dupl + - errcheck + - funlen + - goconst + - gosec + - noctx + - wrapcheck + # godoclint's pkg-doc rule reports the canonical hand-written doc + # as "more than one godoc" whenever a generated sibling + # (oapi-codegen `*.gen.go`, templ `*_templ.go`) carries its own + # leading comment that godoclint mistakes for a package doc. + # The exclusions.generated: lax filter handles per-file warnings + # but not these cross-file "duplicate" complaints. Suppress at + # the call site instead, the canonical docs live in `doc.go`. + - path: 'doc\.go' + linters: + - godoclint diff --git a/.release-please-manifest.json b/.release-please-manifest.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/.release-please-manifest.json @@ -0,0 +1 @@ +{} diff --git a/README.md b/README.md index 944ecf9..0c87d12 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,81 @@ # platform-kit -Shared Go module for services on the platform. +Shared Go module for services on the platform. The `runtime` package +implements the runtime contract once, so a service's `main` is: load the +runtime, register readiness checks, serve. + +```go +ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) +defer stop() + +rt, err := runtime.New(ctx) // config, logger, tracing, metrics +if err != nil { ... } +rt.Ready("database", pool.Ping) // /readyz is 503 while this fails +err = rt.Serve(ctx, handler) // until ctx is done, then drain and flush +``` + +``` +go get github.com/MetsaApp/platform-kit +``` + +## The contract + +| Port | Serves | +|---|---| +| 8080 | the handler passed to `Serve`; a nil handler serves nothing, for a worker | +| 8081 | `/healthz` (the process is up) and `/readyz` (every registered check passes) | +| 9464 | `/metrics`: OTel instruments and `client_golang` collectors on the default registry | + +The ports are fixed. `/healthz` never runs the readiness checks, because a +restart does not fix a dependency. `/readyz` also answers 503 once the +process has begun to stop. + +| Variable | `rt.Config` | | +|---|---|---| +| `ENVIRONMENT` | `Environment` | default `local` | +| `LOG_LEVEL` | `LogLevel` | default `info` | +| `OTEL_SERVICE_NAME` | `ServiceName` | required; the name in traces, metrics and logs | +| `SERVICE_IDENTITY` | `ServiceIdentity` | `/` | +| `DATABASE_URL` | `DatabaseURL` | | +| `NATS_URL` | `NATSURL` | | +| `NATS_TOKEN_FILE` | `NATSTokenFile` | rotates hourly: read it on every connect | +| `REDIS_URL` | `RedisURL` | | + +The connection settings are empty unless the service's definition enables +them; a service checks the ones it needs. The other `OTEL_*` variables +(endpoint, sampler, resource attributes) are read by the OTel SDK. Traces are +exported over OTLP gRPC only when `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` or +`OTEL_EXPORTER_OTLP_ENDPOINT` is set. + +These names are the contract's and carry no prefix. Anything else is +namespaced: a service prefixes its own settings with its name (`LIVE_...`, +`BILLING_...`) and parses them itself, and any variable this module adds +beyond the contract starts with `PLATFORM_KIT_`. + +Logs are JSON on stderr with `service`, `environment` and, when logged with a +`*Context` method inside a span, `trace_id` and `span_id`. Use `rt.Logger`; +the module never sets the global logger. + +## Example + +`example/` is a complete service: + +``` +OTEL_SERVICE_NAME=example go run ./example +curl localhost:8080/ +curl -i localhost:8081/readyz # 503 for two seconds, then 200 +curl localhost:9464/metrics +``` + +## Working here + +``` +go build ./... && go vet ./... && go test -race ./... +go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.11.3 run +``` + +The tests run a small service as a child process on the real ports, so 8080, +8081 and 9464 must be free. + +Releases are cut by release-please from conventional commit titles; only +`feat:` and `fix:` produce one. diff --git a/example/main.go b/example/main.go new file mode 100644 index 0000000..4b4217a --- /dev/null +++ b/example/main.go @@ -0,0 +1,60 @@ +// Command example is the smallest service on the runtime contract: load the +// runtime, register a readiness check, serve on 8080. +// +// OTEL_SERVICE_NAME=example go run ./example +package main + +import ( + "context" + "errors" + "fmt" + "net/http" + "os" + "os/signal" + "sync/atomic" + "syscall" + "time" + + "github.com/MetsaApp/platform-kit/runtime" +) + +// warmup stands in for a dependency that takes a moment to come up. +const warmup = 2 * time.Second + +func main() { + if err := run(); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +func run() error { + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + + rt, err := runtime.New(ctx) + if err != nil { + return fmt.Errorf("start runtime: %w", err) + } + + // A real service registers its database ping or NATS connection here. + var warm atomic.Bool + time.AfterFunc(warmup, func() { warm.Store(true) }) + rt.Ready("warmup", func(context.Context) error { + if !warm.Load() { + return errors.New("still warming up") + } + return nil + }) + + mux := http.NewServeMux() + mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { + rt.Logger.InfoContext(r.Context(), "hello") + _, _ = fmt.Fprintf(w, "hello from %s\n", rt.Config.ServiceName) + }) + + if err = rt.Serve(ctx, mux); err != nil { + return fmt.Errorf("serve: %w", err) + } + return nil +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..6fdf0a2 --- /dev/null +++ b/go.mod @@ -0,0 +1,46 @@ +module github.com/MetsaApp/platform-kit + +go 1.26.0 + +require ( + github.com/caarlos0/env/v11 v11.4.1 + github.com/prometheus/client_golang v1.23.2 + github.com/stretchr/testify v1.11.1 + go.opentelemetry.io/contrib/instrumentation/runtime v0.68.0 + go.opentelemetry.io/otel v1.44.0 + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.44.0 + go.opentelemetry.io/otel/exporters/prometheus v0.66.0 + go.opentelemetry.io/otel/sdk v1.44.0 + go.opentelemetry.io/otel/sdk/metric v1.44.0 + go.opentelemetry.io/otel/trace v1.44.0 + go.opentelemetry.io/proto/otlp v1.10.0 + google.golang.org/grpc v1.81.1 +) + +require ( + github.com/beorn7/perks v1.0.1 // indirect + github.com/cenkalti/backoff/v5 v5.0.3 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/go-logr/logr v1.4.3 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/prometheus/client_model v0.6.2 // indirect + github.com/prometheus/common v0.67.5 // indirect + github.com/prometheus/otlptranslator v1.0.0 // indirect + github.com/prometheus/procfs v0.20.1 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 // indirect + go.opentelemetry.io/otel/metric v1.44.0 // indirect + go.yaml.in/yaml/v2 v2.4.4 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/sys v0.45.0 // indirect + golang.org/x/text v0.37.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect + google.golang.org/protobuf v1.36.11 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..da002b1 --- /dev/null +++ b/go.sum @@ -0,0 +1,98 @@ +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/caarlos0/env/v11 v11.4.1 h1:fYwH0sWEsBSMPG7t4e/PEfTFzrWrpjyygXyUnWiSwEw= +github.com/caarlos0/env/v11 v11.4.1/go.mod h1:qupehSf/Y0TUTsxKywqRt/vJjN5nz6vauiYEUUr8P4U= +github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= +github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs= +github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= +github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o= +github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg= +github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= +github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= +github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4= +github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw= +github.com/prometheus/otlptranslator v1.0.0 h1:s0LJW/iN9dkIH+EnhiD3BlkkP5QVIUVEoIwkU+A6qos= +github.com/prometheus/otlptranslator v1.0.0/go.mod h1:vRYWnXvI6aWGpsdY/mOT/cbeVRBlPWtBNDb7kGR3uKM= +github.com/prometheus/procfs v0.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc= +github.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo= +github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= +github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/contrib/instrumentation/runtime v0.68.0 h1:jhVIQEprwUTV+KfzzliLidclhoTOoHTgdz96kAyR8mU= +go.opentelemetry.io/contrib/instrumentation/runtime v0.68.0/go.mod h1:4HsdbLUbernaTnA8CNaNE+1g026SciXb3juRYe3l8EY= +go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU= +go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 h1:4YsVu3B8+3qtWYYrsUYgn0OG78pN0rnNPRGX4SbokQI= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0/go.mod h1:+wnlSn0mD1ADVMe3v9Z/WIaiz6q6gL2J/ejaAmdmv80= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.44.0 h1:qazEJlUOQzhCpzQpFETGby7EdqjI1wsd0W+6Gg1SCTU= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.44.0/go.mod h1:fOD2Yefuxixkx3ahVNf0O/PERb6r4OlbxfATVnYvzCo= +go.opentelemetry.io/otel/exporters/prometheus v0.66.0 h1:vkrK8PAznv2NKt2r+kdu252ccGzkEqLc2aSXbQIALYQ= +go.opentelemetry.io/otel/exporters/prometheus v0.66.0/go.mod h1:V/UB6D3vMF/UBOL5igAsAYnk1nG/bzYYTzvsB16cy7o= +go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc= +go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo= +go.opentelemetry.io/otel/metric/x v0.66.0 h1:YkCrx1zLOChi9ZcZ6euupOcsgzbVlec7D/xoEU1+cTA= +go.opentelemetry.io/otel/metric/x v0.66.0/go.mod h1:d1+BDj9t96do0/1LoU1ayfCv79ZgNE41qbhBvnMOBZk= +go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58= +go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0= +go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI= +go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA= +go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk= +go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE= +go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g= +go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= +go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY= +golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= +gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= +google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa h1:Kjn0N0tCrDgiAFW+lGO4JZ3ck44CehvJQMAwj9QF0G8= +google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:q4lMZS6kskjT5HvCPrnnypcDPVJqT/f4nfxmkE7gryY= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/grpc v1.81.1 h1:VnnIIZ88UzOOKLukQi+ImGz8O1Wdp8nAGGnvOfEIWQQ= +google.golang.org/grpc v1.81.1/go.mod h1:xGH9GfzOyMTGIOXBJmXt+BX/V0kcdQbdcuwQ/zNw42I= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/release-please-config.json b/release-please-config.json new file mode 100644 index 0000000..3be862c --- /dev/null +++ b/release-please-config.json @@ -0,0 +1,10 @@ +{ + "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json", + "bump-minor-pre-major": true, + "packages": { + ".": { + "release-type": "go", + "initial-version": "0.1.0" + } + } +} diff --git a/runtime/config.go b/runtime/config.go new file mode 100644 index 0000000..f722c7b --- /dev/null +++ b/runtime/config.go @@ -0,0 +1,47 @@ +package runtime + +import ( + "fmt" + "log/slog" + + "github.com/caarlos0/env/v11" +) + +// The contract's ports. They are the same for every service, so the chart, +// the network policy and the scrape config never ask a service for them. +const ( + // HTTPPort serves the service's traffic. + HTTPPort = 8080 + // ProbePort serves /healthz and /readyz. + ProbePort = 8081 + // MetricsPort serves /metrics. + MetricsPort = 9464 +) + +// Config is the contract's configuration, read from the names the +// metsa-service chart injects. The connection settings are empty when the +// service's definition does not enable them; a service checks the ones it +// needs. The remaining OTEL_* variables are read by the OTel SDK itself. +type Config struct { + Environment string `env:"ENVIRONMENT" envDefault:"local"` + LogLevel slog.Level `env:"LOG_LEVEL" envDefault:"info"` + // ServiceName names the service in traces, metrics and logs. It is never + // set in code, so telemetry matches the deployment. + ServiceName string `env:"OTEL_SERVICE_NAME,required,notEmpty"` + // ServiceIdentity is /, the NATS user. + ServiceIdentity string `env:"SERVICE_IDENTITY"` + DatabaseURL string `env:"DATABASE_URL"` + NATSURL string `env:"NATS_URL"` + // NATSTokenFile holds a projected token that rotates hourly: read it on + // every connect, never once at start. + NATSTokenFile string `env:"NATS_TOKEN_FILE"` + RedisURL string `env:"REDIS_URL"` +} + +func loadConfig() (Config, error) { + cfg, err := env.ParseAs[Config]() + if err != nil { + return Config{}, fmt.Errorf("load runtime config: %w", err) + } + return cfg, nil +} diff --git a/runtime/logging.go b/runtime/logging.go new file mode 100644 index 0000000..940d7af --- /dev/null +++ b/runtime/logging.go @@ -0,0 +1,46 @@ +package runtime + +import ( + "context" + "io" + "log/slog" + + "go.opentelemetry.io/otel/trace" +) + +// newLogger returns the process logger: JSON in every environment (the log +// pipeline parses one shape), with service and environment as base +// attributes and trace_id/span_id injected from the active span on every +// *Context call. +func newLogger(w io.Writer, cfg Config) *slog.Logger { + inner := slog.NewJSONHandler(w, &slog.HandlerOptions{Level: cfg.LogLevel}) + return slog.New(&traceHandler{inner: inner}). + With("service", cfg.ServiceName, "environment", cfg.Environment) +} + +type traceHandler struct { + inner slog.Handler +} + +func (h *traceHandler) Enabled(ctx context.Context, level slog.Level) bool { + return h.inner.Enabled(ctx, level) +} + +func (h *traceHandler) Handle(ctx context.Context, r slog.Record) error { + sc := trace.SpanFromContext(ctx).SpanContext() + if sc.HasTraceID() { + r.AddAttrs( + slog.String("trace_id", sc.TraceID().String()), + slog.String("span_id", sc.SpanID().String()), + ) + } + return h.inner.Handle(ctx, r) //nolint:wrapcheck // slog.Handler contract. +} + +func (h *traceHandler) WithAttrs(attrs []slog.Attr) slog.Handler { + return &traceHandler{inner: h.inner.WithAttrs(attrs)} +} + +func (h *traceHandler) WithGroup(name string) slog.Handler { + return &traceHandler{inner: h.inner.WithGroup(name)} +} diff --git a/runtime/probes.go b/runtime/probes.go new file mode 100644 index 0000000..374c2a2 --- /dev/null +++ b/runtime/probes.go @@ -0,0 +1,68 @@ +package runtime + +import ( + "context" + "net/http" + "strings" + "time" +) + +// readyCheckTimeout bounds one readiness check, so a hung dependency reads +// as not ready instead of hanging the probe. +const readyCheckTimeout = 2 * time.Second + +type readyCheck struct { + name string + check func(context.Context) error +} + +// Ready registers a readiness check, such as a database ping or the NATS +// connection state. /readyz answers 503 while any registered check returns +// an error. Liveness never runs them: a restart does not fix a dependency. +func (r *Runtime) Ready(name string, check func(context.Context) error) { + r.mu.Lock() + defer r.mu.Unlock() + r.checks = append(r.checks, readyCheck{name: name, check: check}) +} + +func (r *Runtime) probeHandler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte("ok\n")) + }) + mux.HandleFunc("GET /readyz", r.readyz) + return mux +} + +func (r *Runtime) readyz(w http.ResponseWriter, req *http.Request) { + failing := r.failingChecks(req.Context()) + if len(failing) > 0 { + http.Error(w, "not ready: "+strings.Join(failing, ", "), http.StatusServiceUnavailable) + return + } + _, _ = w.Write([]byte("ok\n")) +} + +func (r *Runtime) failingChecks(ctx context.Context) []string { + // Not ready once shutdown has begun, so the endpoints drop the pod + // while in-flight requests drain. + if r.stopping.Load() { + return []string{"shutting down"} + } + + r.mu.Lock() + checks := append([]readyCheck(nil), r.checks...) + r.mu.Unlock() + + var failing []string + for _, c := range checks { + checkCtx, cancel := context.WithTimeout(ctx, readyCheckTimeout) + err := c.check(checkCtx) + cancel() + if err != nil { + failing = append(failing, c.name) + r.Logger.WarnContext(ctx, "readiness check failed", "check", c.name, "error", err.Error()) + } + } + return failing +} diff --git a/runtime/runtime.go b/runtime/runtime.go new file mode 100644 index 0000000..eb55a00 --- /dev/null +++ b/runtime/runtime.go @@ -0,0 +1,142 @@ +// Package runtime implements the platform's runtime contract once: the +// configuration names the metsa-service chart injects, a probe listener on +// 8081, a metrics listener on 9464, OTel tracing named from configuration +// and JSON logging. A service's main loads the runtime, registers its +// readiness checks and serves on 8080. +package runtime + +import ( + "context" + "errors" + "fmt" + "log/slog" + "net" + "net/http" + "os" + "strconv" + "sync" + "sync/atomic" + "time" + + "github.com/prometheus/client_golang/prometheus/promhttp" +) + +const ( + readHeaderTimeout = 10 * time.Second + // drainTimeout is how long in-flight requests get after the context is + // done; it must stay under the pod's termination grace period. + drainTimeout = 10 * time.Second + flushTimeout = 5 * time.Second +) + +// Runtime is one service process on the contract. +type Runtime struct { + // Config is the contract's configuration as loaded by New. + Config Config + // Logger is the process logger. Pass it on; there is no global logger. + Logger *slog.Logger + + flushTelemetry func(context.Context) error + mu sync.Mutex + checks []readyCheck + stopping atomic.Bool +} + +// New loads the configuration, builds the logger and sets up tracing and +// metrics. It fails when a required name is missing, so a misconfigured pod +// never starts serving. +func New(ctx context.Context) (*Runtime, error) { + cfg, err := loadConfig() + if err != nil { + return nil, err + } + logger := newLogger(os.Stderr, cfg) + flush, err := initTelemetry(ctx, logger) + if err != nil { + return nil, err + } + return &Runtime{Config: cfg, Logger: logger, flushTelemetry: flush}, nil +} + +// Serve listens on the contract's ports until ctx is done or a listener +// fails: handler on 8080, the probes on 8081 and the metrics on 9464. A nil +// handler serves no traffic port, for a worker that only consumes. On the +// way out it drains in-flight requests and flushes telemetry. It returns nil +// after a clean stop. +// +// handler is served as given; tracing its routes (otelhttp, otelecho) is the +// service's choice. +func (r *Runtime) Serve(ctx context.Context, handler http.Handler) error { + metrics := http.NewServeMux() + metrics.Handle("GET /metrics", promhttp.Handler()) + + // Drained in this order: traffic first, while the probe listener still + // answers "not ready". + var servers []*http.Server + if handler != nil { + servers = append(servers, newServer(HTTPPort, handler)) + } + servers = append(servers, newServer(MetricsPort, metrics), newServer(ProbePort, r.probeHandler())) + + listeners, err := listenAll(ctx, servers) + if err != nil { + return err + } + serveErrs := make(chan error, len(servers)) + for i, srv := range servers { + go func() { serveErrs <- srv.Serve(listeners[i]) }() + } + r.Logger.InfoContext(ctx, "serving", "traffic", handler != nil) + + var serveErr error + select { + case <-ctx.Done(): + case serveErr = <-serveErrs: + } + r.stopping.Store(true) + r.Logger.InfoContext(ctx, "stopping") + + // ctx is already done on the normal path; the drain needs its own time. + stopCtx := context.WithoutCancel(ctx) + errs := []error{serveErr} + drainCtx, cancelDrain := context.WithTimeout(stopCtx, drainTimeout) + defer cancelDrain() + for _, srv := range servers { + if shutdownErr := srv.Shutdown(drainCtx); shutdownErr != nil { + errs = append(errs, fmt.Errorf("shut down %s: %w", srv.Addr, shutdownErr)) + } + } + flushCtx, cancelFlush := context.WithTimeout(stopCtx, flushTimeout) + defer cancelFlush() + if flushErr := r.flushTelemetry(flushCtx); flushErr != nil { + errs = append(errs, fmt.Errorf("flush telemetry: %w", flushErr)) + } + return errors.Join(errs...) +} + +func newServer(port int, handler http.Handler) *http.Server { + // No WriteTimeout: a service may stream (SSE) on the traffic port. + return &http.Server{ + Addr: ":" + strconv.Itoa(port), + Handler: handler, + ReadHeaderTimeout: readHeaderTimeout, + } +} + +// listenAll binds every server's address up front, so a taken port fails +// Serve instead of being logged from a goroutine. +func listenAll(ctx context.Context, servers []*http.Server) ([]net.Listener, error) { + listeners := make([]net.Listener, 0, len(servers)) + for _, srv := range servers { + var lc net.ListenConfig + ln, err := lc.Listen(ctx, "tcp", srv.Addr) + if err != nil { + for _, open := range listeners { + _ = open.Close() + } + return nil, fmt.Errorf("listen on %s: %w", srv.Addr, err) + } + listeners = append(listeners, ln) + } + return listeners, nil +} diff --git a/runtime/runtime_test.go b/runtime/runtime_test.go new file mode 100644 index 0000000..59aa818 --- /dev/null +++ b/runtime/runtime_test.go @@ -0,0 +1,380 @@ +package runtime_test + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "os" + "os/exec" + "os/signal" + "path/filepath" + "strconv" + "strings" + "sync" + "syscall" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.opentelemetry.io/otel" + coltracepb "go.opentelemetry.io/proto/otlp/collector/trace/v1" + "google.golang.org/grpc" + + "github.com/MetsaApp/platform-kit/runtime" +) + +// The runtime owns process-wide state (the contract's ports, the OTel +// globals, stderr), so every test drives it the way a pod does: as a +// process. The test binary re-executes itself as a small service when +// childEnv is set. +const ( + childEnv = "PLATFORM_KIT_TEST_CHILD" + // workerEnv makes the child serve no traffic port. + workerEnv = "PLATFORM_KIT_TEST_WORKER" + // unreadyFileEnv names a file; the child's readiness check fails while + // it exists. + unreadyFileEnv = "PLATFORM_KIT_TEST_UNREADY_FILE" +) + +func TestMain(m *testing.M) { + if os.Getenv(childEnv) != "" { + os.Exit(childMain()) + } + os.Exit(m.Run()) +} + +// childMain is a service's main as the package intends it. +func childMain() int { + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM) + defer stop() + + rt, err := runtime.New(ctx) + if err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } + rt.Ready("dependency", func(context.Context) error { + if _, statErr := os.Stat(os.Getenv(unreadyFileEnv)); statErr == nil { + return errors.New("dependency down") + } + return nil + }) + + var handler http.Handler + if os.Getenv(workerEnv) == "" { + mux := http.NewServeMux() + mux.HandleFunc("GET /config", func(w http.ResponseWriter, _ *http.Request) { + _ = json.NewEncoder(w).Encode(rt.Config) //nolint:musttag // Test-only dump; Config is not a wire type. + }) + mux.HandleFunc("GET /work", func(_ http.ResponseWriter, r *http.Request) { + spanCtx, span := otel.Tracer("child").Start(r.Context(), "work") + defer span.End() + rt.Logger.InfoContext(spanCtx, "working") + rt.Logger.WarnContext(spanCtx, "careful") + }) + handler = mux + } + + if err = rt.Serve(ctx, handler); err != nil { + fmt.Fprintln(os.Stderr, err) + return 1 + } + return 0 +} + +func TestServesTheContractPorts(t *testing.T) { + startChild(t, nil) + + status, body := get(t, runtime.ProbePort, "/healthz") + assert.Equal(t, http.StatusOK, status) + assert.Equal(t, "ok\n", body) + + status, _ = get(t, runtime.ProbePort, "/readyz") + assert.Equal(t, http.StatusOK, status) + + status, body = get(t, runtime.MetricsPort, "/metrics") + assert.Equal(t, http.StatusOK, status) + assert.Contains(t, body, `service_name="kit-test"`, "OTel metrics carry the configured service name") + assert.Contains(t, body, "go_goroutines", "client_golang collectors are scraped on the same port") + + status, _ = get(t, runtime.HTTPPort, "/config") + assert.Equal(t, http.StatusOK, status) + + // Probes and metrics are never routed: they are not on the traffic port. + for _, path := range []string{"/healthz", "/readyz", "/metrics"} { + status, _ = get(t, runtime.HTTPPort, path) + assert.Equal(t, http.StatusNotFound, status, path) + } + assert.Equal(t, 8080, runtime.HTTPPort) + assert.Equal(t, 8081, runtime.ProbePort) + assert.Equal(t, 9464, runtime.MetricsPort) +} + +func TestReadinessFollowsRegisteredChecks(t *testing.T) { + unready := filepath.Join(t.TempDir(), "unready") + require.NoError(t, os.WriteFile(unready, nil, 0o600)) + startChild(t, map[string]string{unreadyFileEnv: unready}) + + status, body := get(t, runtime.ProbePort, "/readyz") + assert.Equal(t, http.StatusServiceUnavailable, status) + assert.Contains(t, body, "dependency") + + // Liveness only reflects the process: restarting would not fix it. + status, _ = get(t, runtime.ProbePort, "/healthz") + assert.Equal(t, http.StatusOK, status) + + require.NoError(t, os.Remove(unready)) + status, _ = get(t, runtime.ProbePort, "/readyz") + assert.Equal(t, http.StatusOK, status) +} + +func TestConfigReadsTheContractNames(t *testing.T) { + startChild(t, map[string]string{ + "ENVIRONMENT": "preview", + "LOG_LEVEL": "warn", + "SERVICE_IDENTITY": "metsa-preview/kit-test", + "DATABASE_URL": "postgres://db/app?sslmode=require", + "NATS_URL": "nats://nats.nats.svc.cluster.local:4222", + "NATS_TOKEN_FILE": "/var/run/secrets/nats/token", + "REDIS_URL": "redis://dragonfly.dragonfly.svc:6379/3", + }) + + _, body := get(t, runtime.HTTPPort, "/config") + assert.JSONEq(t, `{ + "Environment": "preview", + "LogLevel": "WARN", + "ServiceName": "kit-test", + "ServiceIdentity": "metsa-preview/kit-test", + "DatabaseURL": "postgres://db/app?sslmode=require", + "NATSURL": "nats://nats.nats.svc.cluster.local:4222", + "NATSTokenFile": "/var/run/secrets/nats/token", + "RedisURL": "redis://dragonfly.dragonfly.svc:6379/3" + }`, body) +} + +func TestNewFailsWithoutAServiceName(t *testing.T) { + t.Setenv("OTEL_SERVICE_NAME", "") + + _, err := runtime.New(t.Context()) + + require.ErrorContains(t, err, "OTEL_SERVICE_NAME") +} + +func TestTraceServiceNameComesFromConfig(t *testing.T) { + collector := startCollector(t) + child := startChild(t, map[string]string{ + "OTEL_SERVICE_NAME": "named-by-config", + "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT": "http://" + collector.addr, + }) + + get(t, runtime.HTTPPort, "/work") + child.stop(t) // A clean stop flushes the batch. + + assert.Equal(t, []string{"named-by-config"}, collector.serviceNames()) +} + +func TestLogsAreJSONWithTraceIDs(t *testing.T) { + collector := startCollector(t) + child := startChild(t, map[string]string{ + "ENVIRONMENT": "preview", + "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT": "http://" + collector.addr, + }) + + get(t, runtime.HTTPPort, "/work") + child.stop(t) + + line := child.logLine(t, "working") + assert.Equal(t, "INFO", line["level"]) + assert.Equal(t, "kit-test", line["service"]) + assert.Equal(t, "preview", line["environment"]) + assert.Len(t, line["trace_id"], 32) + assert.Len(t, line["span_id"], 16) +} + +func TestLogLevelComesFromConfig(t *testing.T) { + child := startChild(t, map[string]string{"LOG_LEVEL": "warn"}) + + get(t, runtime.HTTPPort, "/work") + child.stop(t) + + assert.NotNil(t, child.logLine(t, "careful")) + assert.NotContains(t, child.stderr.String(), `"msg":"working"`) +} + +func TestWorkerServesNoTrafficPort(t *testing.T) { + startChild(t, map[string]string{workerEnv: "1"}) + + status, _ := get(t, runtime.ProbePort, "/readyz") + assert.Equal(t, http.StatusOK, status) + + var dialer net.Dialer + conn, err := dialer.DialContext(t.Context(), "tcp", "127.0.0.1:"+strconv.Itoa(runtime.HTTPPort)) + if err == nil { + _ = conn.Close() + } + require.Error(t, err) +} + +func TestNotReadyWhileDraining(t *testing.T) { + child := startChild(t, nil) + + // A request still in flight holds the drain open. + var dialer net.Dialer + conn, err := dialer.DialContext(t.Context(), "tcp", "127.0.0.1:"+strconv.Itoa(runtime.HTTPPort)) + require.NoError(t, err) + _, err = conn.Write([]byte("GET /config HTTP/1.1\r\nHost: x\r\n")) + require.NoError(t, err) + + require.NoError(t, child.cmd.Process.Signal(syscall.SIGTERM)) + assert.Eventually(t, func() bool { + status, _, getErr := tryGet(t.Context(), runtime.ProbePort, "/readyz") + return getErr == nil && status == http.StatusServiceUnavailable + }, 5*time.Second, 20*time.Millisecond) + + require.NoError(t, conn.Close()) + child.stop(t) +} + +type child struct { + cmd *exec.Cmd + stderr *syncBuffer + once sync.Once +} + +// startChild runs the test binary as a service with the chart's minimal +// environment plus env, and waits until its probe listener answers. +func startChild(t *testing.T, env map[string]string) *child { + t.Helper() + + // t.Context is cancelled before cleanups run, which would kill the child + // ahead of its clean stop. + cmd := exec.CommandContext(context.WithoutCancel(t.Context()), os.Args[0]) + c := &child{cmd: cmd, stderr: &syncBuffer{}} + c.cmd.Env = append(os.Environ(), childEnv+"=1", "OTEL_SERVICE_NAME=kit-test") + for k, v := range env { + c.cmd.Env = append(c.cmd.Env, k+"="+v) + } + c.cmd.Stderr = c.stderr + require.NoError(t, c.cmd.Start()) + t.Cleanup(func() { c.stop(t) }) + + require.Eventually(t, func() bool { + status, _, err := tryGet(t.Context(), runtime.ProbePort, "/healthz") + return err == nil && status == http.StatusOK + }, 10*time.Second, 20*time.Millisecond, "child did not start: %s", c.stderr) + return c +} + +// stop sends SIGTERM, as the kubelet does, and requires a clean exit. +func (c *child) stop(t *testing.T) { + t.Helper() + c.once.Do(func() { + require.NoError(t, c.cmd.Process.Signal(syscall.SIGTERM)) + require.NoError(t, c.cmd.Wait(), "child stderr: %s", c.stderr) + }) +} + +func (c *child) logLine(t *testing.T, msg string) map[string]any { + t.Helper() + for raw := range strings.SplitSeq(c.stderr.String(), "\n") { + var line map[string]any + if json.Unmarshal([]byte(raw), &line) == nil && line["msg"] == msg { + return line + } + } + require.Failf(t, "log line not found", "msg %q in: %s", msg, c.stderr) + return nil +} + +func get(t *testing.T, port int, path string) (int, string) { + t.Helper() + status, body, err := tryGet(t.Context(), port, path) + require.NoError(t, err) + return status, body +} + +func tryGet(ctx context.Context, port int, path string) (int, string, error) { + url := "http://127.0.0.1:" + strconv.Itoa(port) + path + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return 0, "", err + } + // No keep-alive: an idle connection would outlive the child it reached. + req.Close = true + resp, err := http.DefaultClient.Do(req) + if err != nil { + return 0, "", err + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + return resp.StatusCode, string(body), err +} + +// collector is an in-process OTLP gRPC trace receiver. +type collector struct { + coltracepb.UnimplementedTraceServiceServer + + addr string + mu sync.Mutex + names []string +} + +func startCollector(t *testing.T) *collector { + t.Helper() + var lc net.ListenConfig + ln, err := lc.Listen(t.Context(), "tcp", "127.0.0.1:0") + require.NoError(t, err) + + c := &collector{addr: ln.Addr().String()} + srv := grpc.NewServer() + coltracepb.RegisterTraceServiceServer(srv, c) + go func() { _ = srv.Serve(ln) }() + t.Cleanup(srv.Stop) + return c +} + +func (c *collector) Export( + _ context.Context, req *coltracepb.ExportTraceServiceRequest, +) (*coltracepb.ExportTraceServiceResponse, error) { + c.mu.Lock() + defer c.mu.Unlock() + for _, rs := range req.GetResourceSpans() { + for _, attr := range rs.GetResource().GetAttributes() { + if attr.GetKey() == "service.name" { + c.names = append(c.names, attr.GetValue().GetStringValue()) + } + } + } + return &coltracepb.ExportTraceServiceResponse{}, nil +} + +func (c *collector) serviceNames() []string { + c.mu.Lock() + defer c.mu.Unlock() + return append([]string(nil), c.names...) +} + +// syncBuffer is a [bytes.Buffer] the child's stderr copier and the test can +// share. +type syncBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *syncBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *syncBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} diff --git a/runtime/telemetry.go b/runtime/telemetry.go new file mode 100644 index 0000000..6feaa72 --- /dev/null +++ b/runtime/telemetry.go @@ -0,0 +1,121 @@ +package runtime + +import ( + "context" + "errors" + "fmt" + "log/slog" + "os" + "time" + + otelruntime "go.opentelemetry.io/contrib/instrumentation/runtime" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc" + otelprom "go.opentelemetry.io/otel/exporters/prometheus" + "go.opentelemetry.io/otel/propagation" + sdkmetric "go.opentelemetry.io/otel/sdk/metric" + "go.opentelemetry.io/otel/sdk/resource" + sdktrace "go.opentelemetry.io/otel/sdk/trace" +) + +// runtimeMemStatsInterval throttles the runtime collector; at 30s it is a +// no-op against the scrape interval and is kept for clarity. +const runtimeMemStatsInterval = 30 * time.Second + +// initTelemetry configures the global tracer and meter providers and returns +// a func that flushes what was built. Traces ship over OTLP gRPC to whatever +// OTEL_EXPORTER_OTLP[_TRACES]_ENDPOINT points at; with no endpoint the +// exporter is not built at all, so local runs dial nothing. Metrics are read +// by the Prometheus exporter and served by the metrics listener. +func initTelemetry(ctx context.Context, logger *slog.Logger) (func(context.Context) error, error) { + // SDK errors (export failures) are logged at WARN so a collector outage + // is visible in the log stream. + otel.SetErrorHandler(otel.ErrorHandlerFunc(func(err error) { + logger.WarnContext(context.Background(), "otel sdk error", "error", err.Error()) + })) + + // service.name and deployment.environment come from OTEL_SERVICE_NAME + // and OTEL_RESOURCE_ATTRIBUTES: nothing about the deployment is named + // in code. + res, err := resource.New(ctx, resource.WithFromEnv(), resource.WithHost()) + if err != nil { + return nil, fmt.Errorf("build telemetry resource: %w", err) + } + + // Always set, even without an exporter: instrumented clients and + // servers still forward W3C traceparent so downstream hops keep one + // trace. + otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator( + propagation.TraceContext{}, + propagation.Baggage{}, + )) + + var shutdowns []func(context.Context) error + + if tracesConfigured() { + // No explicit transport security or sampler: the endpoint's scheme + // and OTEL_TRACES_SAMPLER / _ARG decide. + traceExporter, traceErr := otlptracegrpc.New(ctx) + if traceErr != nil { + return nil, fmt.Errorf("build OTLP trace exporter: %w", traceErr) + } + tp := sdktrace.NewTracerProvider( + sdktrace.WithResource(res), + sdktrace.WithBatcher(traceExporter), + ) + otel.SetTracerProvider(tp) + shutdowns = append(shutdowns, tp.Shutdown) + } + + // The exporter registers on the default Prometheus registry, so OTel + // instruments and plain client_golang collectors are scraped together. + promExporter, promErr := otelprom.New() + if promErr != nil { + return nil, errors.Join(fmt.Errorf("build prometheus exporter: %w", promErr), joinShutdowns(shutdowns)(ctx)) + } + mp := sdkmetric.NewMeterProvider( + sdkmetric.WithResource(res), + sdkmetric.WithReader(promExporter), + // Keep only the RED latency histogram from the HTTP server + // instrumentation; the two body size histograms triple the + // per-route series for nothing. + sdkmetric.WithView(sdkmetric.NewView( + sdkmetric.Instrument{Name: "http.server.request.body.size"}, + sdkmetric.Stream{Aggregation: sdkmetric.AggregationDrop{}}, + )), + sdkmetric.WithView(sdkmetric.NewView( + sdkmetric.Instrument{Name: "http.server.response.body.size"}, + sdkmetric.Stream{Aggregation: sdkmetric.AggregationDrop{}}, + )), + ) + otel.SetMeterProvider(mp) + shutdowns = append(shutdowns, mp.Shutdown) + + if runtimeErr := otelruntime.Start( + otelruntime.WithMinimumReadMemStatsInterval(runtimeMemStatsInterval), + ); runtimeErr != nil { + return nil, errors.Join( + fmt.Errorf("start runtime instrumentation: %w", runtimeErr), + joinShutdowns(shutdowns)(ctx), + ) + } + + return joinShutdowns(shutdowns), nil +} + +// tracesConfigured reports whether OTLP trace export has a destination, per +// the standard env precedence: the per-signal var, then the shared one. +func tracesConfigured() bool { + return os.Getenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT") != "" || + os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT") != "" +} + +func joinShutdowns(fns []func(context.Context) error) func(context.Context) error { + return func(ctx context.Context) error { + errs := make([]error, 0, len(fns)) + for _, fn := range fns { + errs = append(errs, fn(ctx)) + } + return errors.Join(errs...) + } +}