diff --git a/.apm/commands/architecture-review.md b/.apm/commands/architecture-review.md new file mode 100644 index 0000000..7e37754 --- /dev/null +++ b/.apm/commands/architecture-review.md @@ -0,0 +1,75 @@ +--- +description: "Comprehensive architecture review: generate a ranked findings document, then address findings systematically one commit at a time" +argument-hint: "[review|address [round]]" +allowed-tools: ["Bash", "Glob", "Grep", "Read", "Write", "Edit", "Task"] +--- + +# Architecture Review Workflow + +Generate a comprehensive architecture review document, or systematically address findings from a prior review. + +**Arguments:** "$ARGUMENTS" + +--- + +## Phase 1: Generate Review (`architecture-review review`) + +Perform a comprehensive architecture and engineering review of the current codebase and write the output to `claude-review-architecture.md`. + +### Review Dimensions + +Analyse the codebase across these dimensions: + +- **Inconsistencies** — mismatched patterns, duplicate logic, divergent conventions +- **Correctness** — bugs, race conditions, error handling gaps, incorrect assumptions +- **Maintainability** — coupling, cohesion, complexity, testability +- **Modern practices** — alignment with current language idioms and community standards +- **Architecture** — apply hexagonal architecture thinking to identify areas of high coupling and candidates for restructuring + +### Output Format + +Write findings to `claude-review-architecture.md`: + +1. Executive summary +2. Findings list, each with: + - Title and affected file(s) + - Dimension(s) it falls under + - Description and recommended fix + - Priority rating (High / Medium / Low) across all dimensions +3. Ranked priority table (highest-impact findings first) + +--- + +## Phase 2: Address Findings (`architecture-review address [round]`) + +Systematically work through findings in `claude-review-architecture.md`, one commit per finding. + +**Round** (optional): limits work to a labelled subset of findings (e.g. `Round-2`). Defaults to all unresolved findings. + +### Workflow per Finding + +1. **Plan** — read the finding and identify the minimal correct fix +2. **Baseline complexity** — record cognitive complexity before touching the file: + ```bash + gocognit + ``` +3. **Fix** — implement the change; if the correct fix lives in an upstream `github.com/dioad` repository, create a GitHub issue instead: + ```bash + gh issue create --repo github.com/dioad/ --title "..." --body "..." + ``` +4. **Verify** — run the repository's pre-completion checks before committing (e.g. `make verify`) +5. **Post-fix complexity** — record cognitive complexity after the fix: + ```bash + gocognit + ``` +6. **Commit** — one conventional commit per finding: + ``` + fix: + ``` +7. **Update document** — record outcome, commit SHA, and complexity delta in `claude-review-architecture.md` + +### Constraints + +- Keep complexity the same or lower after each fix — do not let it increase +- Do not batch multiple unrelated findings into one commit +- Do not skip the pre-completion checks step diff --git a/.apm/instructions/git-workflow.instructions.md b/.apm/instructions/git-workflow.instructions.md new file mode 100644 index 0000000..3edf725 --- /dev/null +++ b/.apm/instructions/git-workflow.instructions.md @@ -0,0 +1,19 @@ +--- +description: 'Git workflow rules for this repository' +applyTo: "**" +--- + +# Git workflow instructions + +When performing Git operations in this repository, follow these rules: + +1. Never push to remote repositories (`git push` is not allowed). +2. Do not use `git add -A` (or `git add .`). Stage files explicitly by path. +3. Only stage files you directly modified for the requested task. +4. Use Conventional Commits for commit messages (for example: `fix: ...`, `feat: ...`, `chore: ...`). + +Recommended safety practices: + +1. Do not create commits unless the user explicitly asks for a commit. +2. Do not amend commits unless explicitly requested. +3. Before committing, inspect staged changes with `git diff --cached` to confirm scope is correct. diff --git a/.apm/instructions/go-graph.instructions.md b/.apm/instructions/go-graph.instructions.md new file mode 100644 index 0000000..b85cd80 --- /dev/null +++ b/.apm/instructions/go-graph.instructions.md @@ -0,0 +1,230 @@ +--- +description: 'AST-aware Go repository navigation via gograph — use for symbol lookup and call-tree analysis instead of grep/find in *.go codebases' +applyTo: '**/*.go' +--- + +gograph: AST-aware Repository Navigation Tool for AI Agents + +Use gograph whenever you need to find a symbol or analyse call trees in a Go +(*.go) codebase. Before answering architecture, dependency, or "where is X?" +questions about this repository, read `.gograph/GRAPH_REPORT.md` first — use +it as the repo map before searching raw files. Use `gograph query` and +`gograph callers` for symbol lookup. + +━━━ READ FIRST ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +This repository contains an llm-wiki/ directory with curated context pages. +Read them BEFORE writing any code or running any analysis: + + llm-wiki/README.md → index of all wiki pages + llm-wiki/project.md → project identity, non-goals, correctness model + llm-wiki/rules.md → binding rules (git, build, testing, architecture) + llm-wiki/agent-contract.md → session lifecycle and tool selection contract + +If generated pages are missing: gograph build . --precise && gograph wiki + +━━━ PREREQUISITE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +ALL query commands read from .gograph/graph.json. If it does not exist, every +query fails. Build it once before anything else: + + gograph build . fast, tolerates broken code — use during development + gograph build . --precise type-checked CHA — use before refactors (needs compilable code) + +After build: graph.json + Markdown reports are written to .gograph/. +The .gograph/ ignore entry is appended to the Git repository root .gitignore +when available; outside Git, the build target .gitignore is used. +If no Go files are found after ignore filtering, build exits before writing artifacts. + gograph stats → counts (packages/files/symbols/calls/routes/SQL/tests) + gograph stale → lists source files newer than graph.json (shows newest source time/file) + +Rebuild whenever source files change. The graph does NOT auto-update. + +━━━ COMMON WORKFLOWS ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + Start of any session → summary (top hotspots + worst instability + highest complexity + orphan/god-obj counts in ONE call) + Onboard to unfamiliar repo → hotspot, skeleton, focus + Find where X is defined → query then source to read body + Understand a symbol (raw) → context (callers+callees+source+tests in one call) + Understand all changed syms → context --uncommitted (all contexts bundled — use after plan --uncommitted) + Understand a symbol (deep) → explain (role, complexity, SQL, env, routes, interfaces) + Before editing any symbol → plan (callers, tests, SQL/env/route risk) + After editing, before commit → review --uncommitted then build . --precise + Before a package refactor → dependents (every consumer of this package) + Full blast radius of change → impact or impact --uncommitted or impact --since + PR / branch scope review → changes --git main + HTTP endpoint deep-dive → endpoint (route + call chain + SQL + env) + Error root-cause trace → errorflow + Dead code sweep → orphans + Test coverage gaps (codebase) → untested (callers but zero test edges — one sweep, sorted by risk) + External symbol signature → doc (stdlib/third-party — no graph required) + API breaking-change check → api --since + CI enforcement → gate, check --since + +━━━ WHEN TO USE WHAT ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +FINDING THINGS — three different scopes: + query broad: searches symbol names, file paths, package names, import paths, call sites + node exact: AST metadata for one named symbol (kind, file, line, signature, doc) + source body: extracts the actual source code block — use instead of reading the file + +CALL GRAPH — two different depths: + callers/callees [--depth N] bounded: 1 hop (default) up to 10 — use for focused exploration + impact unbounded: full BFS to ALL transitive callers — can be large on hotspots + can be a short name ("Validate" — fuzzy substring match), a standard Go package-qualified + name ("graph.Graph" or "graph.Graph.Build" — standard dot-notation), or a fully-qualified + ID ("pkg/path::(*Service).Validate" — exact match, no same-name conflation). Use + the dot or FQ form to disambiguate overloads/duplicates. Requires --precise build for + full effect. Works for callers, callees, impact, and path (both endpoints). + +SYMBOL UNDERSTANDING — two different outputs: + context structured data: node + source + callers + callees + tests — fast, token-efficient + explain narrative: role classification, prod vs test split, complexity, SQL, env, routes, interfaces + → use context when you need lists to act on; use explain when you need to understand purpose + +PACKAGE RELATIONS — three different questions: + deps what does this package import? (outgoing) + dependents what imports this package? (incoming) — essential before refactoring a package + imports which files import this specific import path? — for tracing one external dependency + +STRUCT / TYPE — five different angles: + fields what fields does this struct have? + embeds which structs embed this struct? + constructors which functions return this struct? (New*, factory functions) + literals where is this struct initialized as Foo{...}? (run before adding a required field) + implementers which structs satisfy this interface? + interfaces which interfaces does this struct satisfy? (inverse of implementers) + usages where is this type used? (param/return types, struct fields, iface methods) + → use before changing any interface or type — shows the full blast radius + +PACKAGE vs SYMBOL scope: + focus everything in a package: files, all symbols, internal calls, imports + public exported symbols only: the package's API surface + context one symbol only: deep slice of a single function/struct/interface + +ERRORS — two different questions: + errors where are all errors defined and returned in the codebase? + errorflow how does this specific error reach the HTTP layer? (definition → return sites → entry point) + +━━━ OUTPUT FORMAT ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +All search/navigation commands support four output modes: + + (default) [kind] Name — detail (file:line) — one result per line + --json {"ok":true,"cmd":"...","query":"...","count":N,"data":[...]} + --files-only flat deduplicated list of file paths — use for checklists + --mermaid visual dependency/call diagrams in Mermaid format + (supported by deps, dependents, coupling, callers, callees, path, impact, endpoint) + +Use --json when piping output to another tool or when you need structured data. +Use --files-only when you only need to know which files are involved. + +━━━ STATIC ANALYSIS LIMITATIONS ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +Know these before trusting results: + + Interface dispatch callers/callees may miss calls through interface variables unless + 'build . --precise' was used (enables type-checked CHA call graph) + errorflow heuristic AST traversal — NOT SSA/data-flow. Useful for navigation, + not proof. Confidence rating (HIGH/MEDIUM) is a heuristic estimate. + endpoint route patterns only resolve flat string literals. Gin/Echo/Chi + Group() prefixes are lost at AST level — always search by handler + symbol name, not route string. + impact / skeleton can produce very large output on hotspot symbols or large repos. + Use callers --depth N for bounded traversal instead of impact. + All results reflect the state of graph.json at last build. Run 'gograph stale' + to confirm the index is current before structural analysis. + Subdirectory safe all query commands auto-discover the project root (walks up to + the nearest .gograph/ directory). No need to cd back to the repo + root before running plan, review, or any other query. + +━━━ COMMANDS ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +AGENT WORKFLOW RULES (CRITICAL): +1. BEFORE editing: run 'gograph plan ' — callers, tests, SQL/env/route risk in one call +2. AFTER editing: run 'gograph build . --precise' then 'gograph review --uncommitted' + +INDEXING: +build . [--precise] : parse AST, write graph.json + GRAPH_REPORT.md to .gograph/ + Skips .git, vendor, testdata, .claude, .cursor, .agents, and + any directories listed in .gitignore (via git check-ignore). +stale : list source files newer than graph.json (shows newest source time/file) +stats : schema version, build time, symbol/call/route counts + +QUERY COMMANDS: +boundaries [--config] : verify package architecture constraints using boundaries.json +boundaries --create : auto-generate a baseline boundaries.json from the current repo +callees [--no-tests] [--depth N]: what fn calls (depth=1 direct; --depth 2+ expands N hops, max 10) +callers [--no-tests] [--depth N]: who calls fn (depth=1 direct; --depth 2+ expands N hops, max 10) +complexity [sym] : cyclomatic complexity estimate per function (highest first) +concurrency [str] : goroutines/channels/mutexes +coupling [pkg] : fan-in, fan-out, and instability per package +diagram [--group-by package|module|service|file] [--max-depth N] [--include-stdlib] + : Mermaid architecture diagram of package dependency graph +embeds : structs embedding this struct +envs [str] : os.Getenv/viper reads +errors [--no-tests] : custom errors/panics +fields : fields/types of struct +focus : all files, symbols, calls, imports for one package +godobj : god-object struct candidates (--methods N --fields N --calls N --top N) +impact : full transitive blast radius — WARNING: can be large on hotspot symbols +impact --uncommitted : blast radius of all uncommitted changes +impact --since : blast radius of all symbols changed since a git ref (e.g. main, HEAD~5) +implementers [--test-only] : structs implementing iface (--test-only = test/mock files only) +imports : files importing a specific import path +interfaces : interfaces satisfied by this struct (inverse of implementers) +node : AST metadata for one symbol (kind, file, line, signature, doc) +orphans : symbols unreachable from any entry point via BFS (main, routes, exports) +path : shortest call chain between two symbols (BFS) +public : exported symbols only +query : broad search — symbols, files, packages, imports, call sites +routes : all HTTP REST routes. Annotates unresolvable handlers. +source : exact source code — USE THIS instead of reading files +sql : raw SQL queries mapped to their functions +tests : test functions exercising this symbol + +TOKEN SAVERS (COMPOSED COMMANDS — each replaces 3-8 separate calls): +api --since : breaking API/contract changes since a git reference +arity [--min 5] : functions with too many arguments +changes : symbols modified/new/deleted since last build +changes --git : symbols in files changed since a git ref (e.g. main, HEAD~5, v1.4.50) +constructors : factory functions returning this struct +literals : composite literal sites Foo{...} — run before adding/removing a required field +usages : where a type appears in signatures and fields (param/return/field/iface method) +returnusage : how each caller uses the return value of fn (discarded/assigned/returned/passed) +risk : risk evaluation — blast radius, complexity, tests, SQL/env (0-100 score + verdict) +risk --uncommitted : risk evaluation for all uncommitted changes +context [--limit N]: node+source+callers+callees+tests — raw structured data +context --uncommitted : context for ALL uncommitted symbols in one call (replaces 5-8 sequential context calls) + NOTE: every context response now includes 'role' (architectural classification) +dependents : packages that import this package (run before any package refactor) +deps [--transitive]: import dependency tree (add --transitive for full BFS closure) +endpoint : route + handler + full call chain + SQL + env reads + INPUT: handler symbol name (always works) or flat route string (flat routers only) +errorflow [--no-tests]: error definition → return sites → likely HTTP entry point path +explain : narrative summary — role, complexity, SQL, env, routes, interfaces, tests + (use explain for understanding; use context for raw data to act on) +fixtures : test helper structs and functions in test files +globals : package-level vars, consts, and functions mutating them +hotspot [--top N] : functions ranked by incoming call count — study these first +mocks : alias for 'implementers --test-only' (kept for compatibility) +mutate : functions that mutate a specific struct field — covers direct assignments, ++/+= (--precise only), and indirect mutations via method calls (atomic.*/sync.Map/sync.Mutex/channels/user wrappers; --precise only). Indirect rows show via=. +plan : change plan — callers, tests, SQL/env/route risk, public API impact +plan --with-context : plan + full context for every inspect_first symbol (saves N follow-up context calls) +plan --uncommitted : change plan for all currently uncommitted modified symbols +review : post-edit review — test coverage, complexity, risk profile +review --uncommitted : post-edit review for all uncommitted changes +risk : change risk profile — blast radius, complexity, test coverage, SQL/env dependencies +risk --uncommitted : change risk profile for all uncommitted changes +schema : structs mapped to a DB table via struct tags +skeleton : full repository API signatures with bodies stripped — WARNING: large on big repos +trace : alias for errorflow (kept for compatibility) +doc : "go doc " — signature + doc comment for any stdlib or third-party symbol. + No graph required. Examples: doc fmt.Errorf doc net/http.HandleFunc doc io.Reader + doc github.com/jackc/pgx/v5.Conn.QueryRow +httpcalls [term] : all outbound HTTP client calls via net/http (Get, Post, PostForm, Head). + Filter by method or URL substring. +untested [--pkg ] [--top N] : production functions with callers but zero test edges — coverage gaps + sorted by caller count (highest risk first). Replaces N 'tests ' calls. +check [--since ref] : static policy checks (boundaries, api_drift, test requirements) +gate : CI/CD enforcement against .gograph.yml thresholds +snapshot : architectural metric snapshots (save, diff, list, drop) +mcp [path] : start MCP server over stdio +gograph session : start/end audit sessions (create [word], end, audit, cleanup) + NOTE: MCP tool calls (gograph_plan, gograph_review) are + now correctly recorded in session audit counters. +add-claude-plugin : install MCP plugin + CLAUDE.md rules + PreToolUse hook +hook-guard : PreToolUse hook — blocks grep on Go symbols, redirects to gograph diff --git a/.apm/instructions/go-testing.instructions.md b/.apm/instructions/go-testing.instructions.md new file mode 100644 index 0000000..659551f --- /dev/null +++ b/.apm/instructions/go-testing.instructions.md @@ -0,0 +1,83 @@ +--- +description: 'Cross-project Go testing instructions: testify assertions, executable examples, and Test Desiderata 2.0' +applyTo: '**/*.go' +--- + +# Go Testing Instructions + +## Assertions: Use testify + +Use `github.com/stretchr/testify` for all test assertions. Do not use bare `t.Error`, `t.Fatal`, or manual comparisons when testify covers the case. + +- Use `github.com/stretchr/testify/assert` for non-fatal assertions (test continues after failure). +- Use `github.com/stretchr/testify/require` for fatal assertions (test stops immediately on failure). Prefer `require` for setup and preconditions. +- Use `github.com/stretchr/testify/mock` for mock objects when interface substitution is needed. + +```go +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestFoo(t *testing.T) { + result, err := Foo() + require.NoError(t, err) + assert.Equal(t, "expected", result) +} +``` + +Prefer specific assertions over generic ones (`assert.Equal` over `assert.True(t, a == b)`), as they produce clearer failure messages. + +## Executable Examples + +All Go code examples must be executable and written using the `func Example...` convention from the `testing` package. Place example functions in `*_test.go` files. + +- Name examples `ExampleFunctionName`, `ExampleType_MethodName`, or `ExamplePackage` following Go conventions. +- Include an `// Output:` comment so `go test` verifies the output automatically. +- Keep examples self-contained and minimal — they serve as documentation. + +```go +func ExampleGreet() { + fmt.Println(Greet("world")) + // Output: + // hello, world +} +``` + +Do not write example code in comments, README snippets, or prose without a corresponding runnable `func Example...` counterpart in a `_test.go` file. + +## Test Desiderata 2.0 + +Write tests that satisfy the properties from [Test Desiderata 2.0](https://coding-is-like-cooking.info/2025/12/test-desiderata-2-0/). These are grouped by the outcome they support. + +### Predict Success in Production + +- **Sensitive to Behaviour** — tests must detect functional regressions. Test observable outputs and side effects, not internal implementation details. +- **Sensitive to Execution Qualities** — where relevant, cover non-functional concerns such as latency bounds, concurrency safety (`-race`), and resource cleanup. + +### Fast Feedback + +- **Minimal Data** — use the smallest dataset that exercises the behaviour. Avoid large fixtures when a single representative value will do. +- **Run in Any Order** — tests must be fully independent. Never rely on global state left by another test; use `t.Cleanup` or reset state explicitly. +- **Run in Parallel** — call `t.Parallel()` in tests that are safe to run concurrently. Design tests to be parallelisable by default. + +### Low Total Cost of Ownership + +- **Automated** — every test must run via `go test ./...` with no manual steps. +- **Deterministic** — tests must produce the same result on every run. Eliminate time dependencies, random seeds, and environment-specific assumptions. +- **Diagnosable** — a failing test must clearly communicate what went wrong. Use testify's descriptive messages and `t.Run` subtests with meaningful names so failures are easy to locate and understand. +- **Easy to Read** — test code is documentation. Prefer readability over brevity. Use table-driven tests and `t.Run` to express intent clearly. +- **Easy to Update** — write tests against the public API and observable behaviour, not private functions or implementation internals, so refactoring does not require rewriting tests. +- **Easy to Write** — reduce friction: shared helpers go in `testdata` or helper functions marked with `t.Helper()`. Reuse setup with `t.Cleanup` rather than duplicating teardown. +- **Insensitive to Code Structure** — tests must not break when the code is refactored without changing behaviour. Avoid testing private functions directly. + +### Support Ongoing Code Design Change + +- **Composable** — structure tests so subtests and helpers can be combined without duplication. +- **Documents Intent** — test names and assertions should describe what the code is supposed to do, not how it does it. A reader should understand expected behaviour from the test alone. +- **Durable** — write tests that remain valid as the product evolves. Avoid asserting on incidental details that are likely to change. +- **Necessary** — every test must guide a development decision or prevent a real regression. Delete tests that duplicate coverage without adding signal. +- **Organized** — place test files alongside the code they test. Use `_test.go` suffix. One test file per source file is a reasonable default. +- **Positive Design Pressure** — if a piece of code is hard to test, treat that as a design signal. Refactor toward testable, decoupled interfaces rather than reaching for mocks of concrete types. \ No newline at end of file diff --git a/.apm/instructions/project-checks.instructions.md b/.apm/instructions/project-checks.instructions.md new file mode 100644 index 0000000..dc81008 --- /dev/null +++ b/.apm/instructions/project-checks.instructions.md @@ -0,0 +1,45 @@ +--- +description: 'Required pre-completion checks and project-specific guidelines for connect' +applyTo: "**" +--- + +# Pre-completion Checks + +Before a task is marked as complete, run: + +```bash +make verify +``` + +This automates: `go generate ./...`, `go build .`, `go vet ./...`, `go test -race ./...`, and `shellcheck -o all` on shell scripts. All steps must pass. + +# PR Review Workflow + +## Finding the PR for the Current Branch + +```bash +gh pr view --json number --jq .number +gh pr view +``` + +## Workflow for Addressing Review Comments + +1. Fetch unresolved comments for the current branch's PR +2. Analyze each comment +3. Make code changes to address the issues +4. One commit per comment or related group of issues +5. Run `make verify` +6. Push when all checks pass + +## Commit Message Format for Review Fixes + +``` +fix: address PR {PR_NUMBER} review comments on {topic} + +This commit addresses {N} unresolved review comments: + +1. {Comment title} (line {X} of {file}.go) + - {Description of fix} + +Co-Authored-By: Claude Sonnet 4.6 +``` diff --git a/.apm/instructions/zerolog.instructions.md b/.apm/instructions/zerolog.instructions.md new file mode 100644 index 0000000..a483d63 --- /dev/null +++ b/.apm/instructions/zerolog.instructions.md @@ -0,0 +1,356 @@ +--- +description: 'Structured logging conventions using zerolog across HTTP handlers, middleware, and library code' +applyTo: '**/*.go' +--- + +# Structured Logging with zerolog + +All logging uses `github.com/rs/zerolog`. Follow these conventions consistently across every package and codebase. + +## Core Rule: Request-Scoped vs Construction-Time Loggers + +The choice of where a logger lives determines how log events are correlated: + +| Context | Pattern | Reason | +|---------|---------|--------| +| `net/http` handler or middleware | `zerolog.Ctx(r.Context())` | Carries request-scoped fields (request ID, auth info) through the full handler chain | +| Long-lived struct with fixed enrichment | `zerolog.Logger` field on the struct | Carries construction-time labels (component name, validator label) that never change | +| Program startup / `main()` | `log.Logger` (package-level) | No request context exists; acceptable at the outermost layer only | + +Never store a `zerolog.Logger` on a struct that handles `net/http` requests just to avoid writing `zerolog.Ctx(r.Context())`. The stored logger will not carry dynamic request fields, and those fields will be silently absent from every log event. + +## Application Startup: DefaultContextLogger and Root Context Injection + +At the application entry point (`Exec` / `main`), do two things after configuring `log.Logger`: + +1. **Set `zerolog.DefaultContextLogger`** to the enriched logger so that `zerolog.Ctx` works correctly on *any* context — including shutdown contexts derived from `context.Background()`. +2. **Inject the same logger into the root context** so all child contexts inherit the enrichment automatically. + +Both must use the **same enriched logger**. Splitting them — setting `DefaultContextLogger` to the raw `log.Logger` while injecting an enriched version into `ctx` — means fallback-context paths (e.g. shutdown, periodic cleanup) log without the service label. + +```go +// Correct — single enriched logger for both mechanisms +serviceLogger := log.Logger.With().Str("service", "my-service").Logger() +zerolog.DefaultContextLogger = &serviceLogger +ctx = serviceLogger.WithContext(ctx) + +// Wrong — DefaultContextLogger lacks the service field +log.Logger = ... // configured by CLI +zerolog.DefaultContextLogger = &log.Logger // no service field +ctx = log.Logger.With().Str("service", "x").Logger().WithContext(ctx) // enriched ctx only +``` + +With `DefaultContextLogger` set, `zerolog.Ctx(ctx)` is safe to use everywhere: it returns the configured logger even for contexts that have no embedded logger, making `log.*` calls unnecessary outside of program initialisation. + +## Component Context Enrichment + +When creating a long-lived sub-context for a component (manager, worker pool, background bridge), enrich it with a `component` label immediately after creating the derived context. All goroutines spawned from that context automatically emit log events with the label. + +```go +func NewManager(ctx context.Context, ...) *Manager { + managerCtx, cancel := context.WithCancel(ctx) + + // Enrich before storing — all goroutines inherit component=webhook. + componentLogger := zerolog.Ctx(managerCtx).With().Str("component", "webhook").Logger() + managerCtx = componentLogger.WithContext(managerCtx) + + m := &Manager{ctx: managerCtx, cancel: cancel} + m.startWorkers(managerCtx) // workers get component label for free + ... +} +``` + +`context.WithCancel` (and `WithTimeout`, `WithDeadline`) preserve the value bag, so the embedded logger is inherited by all derived contexts automatically. + +## Context Consistency Within a Function + +When a function has both guard/early-return paths and a long-running goroutine, build the logger from the **same context** used by the goroutine. Building the logger from the caller's context for the guard checks and from a different context for the goroutine produces log events with inconsistent field sets — making them unrelatable in log aggregation. + +```go +// Wrong — logger built from caller ctx (request-scoped, has request_id); +// goroutine logger built from m.ctx (component-scoped, has component=webhook). +// The two paths emit structurally different log events. +func (m *Manager) DeliverHistoricalEvents(ctx context.Context, ...) { + logger := zerolog.Ctx(ctx).With().Str("subscription_id", sub.ID).Logger() + if store == nil { + logger.Warn()... // has request_id, lacks component=webhook + return + } + deliveryCtx := m.ctx + go func() { + logger := zerolog.Ctx(deliveryCtx).With().Str("subscription_id", sub.ID).Logger() + logger.Debug()... // has component=webhook, lacks request_id + }() +} + +// Correct — resolve the authoritative context first, build one logger from it, +// share it between guard checks and the goroutine. +func (m *Manager) DeliverHistoricalEvents(ctx context.Context, ...) { + deliveryCtx := m.ctx // resolve authoritative context first + logger := zerolog.Ctx(deliveryCtx).With().Str("subscription_id", sub.ID).Logger() + if store == nil { + logger.Warn()... // same fields as goroutine + return + } + go func() { + // logger captured from enclosing scope — no re-derivation needed. + logger.Debug()... + }() +} +``` + +The general rule: **if a goroutine runs under a different context than the caller, resolve that context before building the logger** so all log events for the operation carry a consistent field set. + +## HTTP Response Writers and Background Write Goroutines + +When spawning a goroutine to handle HTTP response writes (e.g. SSE, chunked streaming), pass `req.Context()` as the logging context — not the server or broker context. Write errors are per-stream, per-request events; they should carry the same `request_id`, `principal`, and other request-scoped fields as every other log line for that stream. + +```go +// Wrong — broker context loses request_id and principal in write errors +writer := m.startWriter(serverCtx, w, streamID) + +// Correct — request context preserves full per-request enrichment +writer := m.startWriter(req.Context(), w, streamID) +``` + +## Service Layer Functions + +Service layer functions (business logic, managers, services) that accept `context.Context` and are called from HTTP handlers — directly or transitively — must use `zerolog.Ctx(ctx)` to emit logs. This ensures that request-scoped fields injected by middleware (request ID, trace ID, principal) are present in service layer log output. + +```go +// Correct — request-scoped fields flow through the call stack +func (s *EventService) PublishEventsToTopic(ctx context.Context, topic string, events []event.Event) error { + zerolog.Ctx(ctx).Info().Str("topic", topic).Msg("publishing events") + ... +} + +// Correct — audit log in a service method called from an HTTP handler +func (m *Manager) CreateSubscription(ctx context.Context, ...) (*Subscription, error) { + ... + zerolog.Ctx(ctx).Info(). + Str("subscription_id", subscription.ID). + Str("action", "subscription_created"). + Msg("Audit: subscription created") + return subscription, nil +} + +// Wrong — global logger loses all request-scoped fields +func (m *Manager) CreateSubscription(ctx context.Context, ...) (*Subscription, error) { + ... + log.Info().Str("subscription_id", subscription.ID).Msg("Audit: subscription created") // missing request ID, trace, etc. + return subscription, nil +} +``` + +**Background goroutines and lifecycle methods:** Functions that run outside the HTTP request lifetime (worker goroutines, shutdown handlers, pubsub bridge routines, periodic cleanup) use `zerolog.Ctx(ctx)` just like any other code. Their context is a process/manager context that carries component-level enrichment (e.g. `component=webhook`) but not request-scoped fields — which is correct, since those fields have no meaning outside a request. + +With `zerolog.DefaultContextLogger` set at startup (see "Application Startup" section), `zerolog.Ctx(ctx)` is always safe to call even if the context has no embedded logger; the fallback returns the configured application logger. The global `log.*` package is therefore only needed before the application context is initialised (i.e. in `main` / `init`). + +```go +// Correct — background worker uses context logger; inherits component=webhook +// from the manager's enriched context. +func (m *Manager) worker(ctx context.Context, id int) { + logger := zerolog.Ctx(ctx).With().Int("worker_id", id).Logger() + logger.Debug().Msg("Starting webhook worker") + for { + select { + case job := <-m.eventQueue: + m.processJob(ctx, job) + case <-ctx.Done(): + logger.Debug().Msg("Stopping webhook worker") + return + } + } +} + +// Correct — lifecycle method uses context logger; DefaultContextLogger provides +// the configured logger when ctx is a fresh shutdown context. +func (m *Manager) Shutdown(ctx context.Context) error { + zerolog.Ctx(ctx).Info().Msg("Shutting down webhook manager") + ... +} +``` + +## HTTP Handlers + +Always obtain the logger from the request context: + +```go +// Correct +func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + log := zerolog.Ctx(r.Context()) + log.Error().Err(err).Msg("token exchange failed") +} + +// Correct — inline for single use +zerolog.Ctx(r.Context()).Error().Err(err).Msg("failed to generate state") + +// Wrong — stored logger misses request-scoped fields +type Handler struct { + logger zerolog.Logger // do not do this for HTTP handlers +} +``` + +`zerolog.Ctx` returns a no-op logger when no logger is in the context — it is always safe to call without a nil check. + +For handlers that call the logger more than once, assign a short-lived local: + +```go +log := zerolog.Ctx(r.Context()) +if code == "" { + log.Error().Msg("missing code in callback") + http.Error(w, "missing code", http.StatusBadRequest) + return +} +if state == "" { + log.Error().Msg("missing state in callback") + http.Error(w, "missing state", http.StatusBadRequest) + return +} +``` + +## Middleware: Enrich the Context Logger with UpdateContext + +Middleware that authenticates, enriches, or categorises a request should add structured fields to the context logger using `UpdateContext`. Fields added this way are present in all subsequent log events for the request — including deferred access log entries written after the handler returns. + +```go +// Add a field unconditionally when auth succeeds +zerolog.Ctx(r.Context()).UpdateContext(func(c zerolog.Context) zerolog.Context { + return c.Str("auth_source", "oidc_session") +}) + +// Add a field conditionally (e.g. only when a token was refreshed) +if refreshed { + zerolog.Ctx(r.Context()).UpdateContext(func(c zerolog.Context) zerolog.Context { + return c.Bool("token_refreshed", true) + }) +} + +// Pass the enriched context to the next handler +next.ServeHTTP(w, r.WithContext(ctx)) +``` + +`UpdateContext` mutates the logger stored in the context in-place. There is no need to create a new context or reassign `r` solely for the logger update; the mutation is visible to all code that subsequently calls `zerolog.Ctx` on the same context. + +### Do Not Pass Loggers as Function Arguments to HTTP Handlers + +Middleware and handlers should not accept a `zerolog.Logger` parameter for per-request logging. Use `zerolog.Ctx(r.Context())` inside the handler body. Passing a logger as an argument bypasses context-scoped enrichment. + +```go +// Wrong +func NewHandler(validator Validator, cookieName string, logger zerolog.Logger) *Handler + +// Correct +func NewHandler(validator Validator, cookieName string) *Handler +``` + +## Field Naming: Always snake_case + +All log field names must use `snake_case`. This applies to both `Str`/`Bool`/`Int` calls in handlers and to fields added by `UpdateContext`. + +```go +// Correct +log.Str("auth_source", "oidc_session") +log.Bool("token_refreshed", true) +log.Str("request_id", id) +log.Int("jwt_validators", count) + +// Wrong — mixed naming breaks query consistency in log aggregation tools +log.Str("authSource", "oidc_session") // camelCase +log.Bool("TokenRefreshed", true) // PascalCase +log.Str("request-id", id) // kebab-case +``` + +### Standard Field Names + +Use these names consistently across all codebases: + +| Field | Type | Set by | Meaning | +|-------|------|--------|---------| +| `service` | `string` | Application entry point (`Exec`) | Process-wide label identifying the service (e.g. `eventbroker`). Set once via `DefaultContextLogger` and root context injection so every log event carries it. | +| `component` | `string` | Component constructor (e.g. `NewManager`) | Subsystem label injected into a long-lived sub-context (e.g. `webhook`, `sse`, `cors`). Inherited by all goroutines spawned from that context. | +| `request_id` | `string` | Request-ID middleware | Unique ID per HTTP request | +| `auth_source` | `string` | Auth middleware | Which auth mechanism validated the request (`oidc_session`, `jwt`, `basic`, `github`, `hmac`) | +| `token_refreshed` | `bool` | OIDC session middleware | Set to `true` when a token was silently refreshed during the request | + +## Log Messages + +- Use sentence case; start messages with a capital letter +- Keep messages lowercase — they are machine-readable strings, not prose +- Never end a message with punctuation +- Do not interpolate dynamic values into the message string; put them in typed fields + +```go +// Correct +log.Error().Err(err).Msg("failed to refresh token") +log.Error().Err(err).Str("cookie", name).Msg("missing or invalid state cookie") + +// Wrong +log.Error().Msgf("failed to refresh token: %v", err) // swallows structured err field +log.Error().Msg("Failed to refresh token.") // capital + punctuation +``` + +## Construction-Time Loggers + +Validators, debuggers, and other long-lived components that carry a fixed label (e.g. the name of the OIDC issuer being validated) may hold a `zerolog.Logger` as a struct field. This is correct because the enrichment is set once at construction, not per-request. + +```go +type ValidatorDebugger struct { + inner TokenValidator + logger zerolog.Logger // acceptable: enriched once with a fixed label +} + +func NewValidatorDebugger(v TokenValidator, opts ...Option) *ValidatorDebugger { + d := &ValidatorDebugger{inner: v, logger: zerolog.Nop()} + for _, opt := range opts { + opt(d) + } + return d +} + +func WithLogger(l zerolog.Logger) Option { + return func(d *ValidatorDebugger) { d.logger = l } +} +``` + +The key distinction: if the log enrichment is the same for every call (e.g. `label:"flyio"`), a stored logger is appropriate. If the enrichment depends on the in-flight request (e.g. `request_id`, `auth_source`), use `zerolog.Ctx`. + +## Testing + +Use `zerolog.Nop()` for construction-time loggers in tests: + +```go +d := NewValidatorDebugger(validator, WithLogger(zerolog.Nop())) +``` + +For handlers and middleware under test, inject a logger into the request context: + +```go +logger := zerolog.New(os.Stderr) +ctx := logger.WithContext(context.Background()) +req = req.WithContext(ctx) +``` + +Or use `zerolog.Nop()` to suppress output in unit tests where log content is not being asserted: + +```go +ctx := zerolog.Nop().WithContext(context.Background()) +req = req.WithContext(ctx) +``` + +## Summary of Anti-Patterns + +| Anti-pattern | Correct alternative | +|---|---| +| `logger zerolog.Logger` field on an HTTP handler struct | `zerolog.Ctx(r.Context())` in the handler body | +| Passing `zerolog.Logger` as an argument to handler constructors | Remove the parameter; read from context at call time | +| Using `log.Logger` (package-level) inside a handler or service function that accepts `context.Context` | `zerolog.Ctx(ctx)` — preserves request-scoped fields across the call stack | +| Setting `zerolog.DefaultContextLogger` to the raw `log.Logger` while injecting an enriched logger into `ctx` | Use the same enriched logger for both — split enrichment means fallback-context paths (shutdown, cleanup) log without the service label | +| Building the logger from the caller's request context in a function whose goroutine runs under a different (component) context | Resolve the authoritative context first, then build one logger from it and share it across guard checks and the goroutine | +| Passing the server/broker context to an HTTP response-writer goroutine | Pass `req.Context()` — write errors are per-request events and should carry request-scoped fields | +| Not enriching a component's sub-context with a `component` label before spawning workers | Call `zerolog.Ctx(ctx).With().Str("component", "name").Logger().WithContext(ctx)` immediately after `context.WithCancel` | +| `ctx.Done()` drop in a queue `select` with no metric or log | Record the drop identically to the capacity-full branch (metric increment + observer call + warn log) | +| camelCase or PascalCase field names | `snake_case` field names | +| `log.Msgf(...)` with `%v` for errors | `.Err(err).Msg(...)` to preserve structured error fields | +| Logging an error and then returning it | Choose one: log it here, or return it and let the caller log it | +| `UpdateContext` fields added after calling `next.ServeHTTP` | Add `UpdateContext` fields before calling `next.ServeHTTP` so they are present in the handler and in deferred access logs | diff --git a/.apm/skills/architecture-review/SKILL.md b/.apm/skills/architecture-review/SKILL.md new file mode 100644 index 0000000..f47d0d5 --- /dev/null +++ b/.apm/skills/architecture-review/SKILL.md @@ -0,0 +1,168 @@ +--- +name: architecture-review +description: > + Activate when the user asks for a comprehensive architecture review of the + codebase, or wants to systematically address findings from a prior review. + Generates a ranked findings document (claude-review-architecture.md) or + works through existing findings one commit at a time. +--- + +# Architecture Review + +A two-phase skill for reviewing and improving codebase architecture. Phase 1 +generates a ranked findings document; Phase 2 addresses findings +systematically, one commit at a time. + +## When to activate + +- User asks for an "architecture review" or "code review" +- User asks to "review the codebase" or "find architectural issues" +- User asks to "address findings" from a prior architecture review +- User references `claude-review-architecture.md` +- User says "architecture-review review" or "architecture-review address" + +## Determine the phase + +Examine the user's request to determine which phase to run: + +- **Phase 1** — the user wants a new review generated. Keywords: "review", + "analyse", "generate findings", "what's wrong with", "architecture-review review". +- **Phase 2** — the user wants to act on existing findings. Keywords: "address", + "fix findings", "work through", "architecture-review address". + +If unclear, ask: "Do you want to generate a new architecture review, or address +findings from an existing one?" + +--- + +## Phase 1: Generate Review + +Perform a comprehensive architecture and engineering review of the current +codebase and write the output to `claude-review-architecture.md`. + +### Review dimensions + +Analyse the codebase across these five dimensions: + +- **Inconsistencies** -- mismatched patterns, duplicate logic, divergent + conventions across packages or files +- **Correctness** -- bugs, race conditions, error handling gaps, incorrect + assumptions +- **Maintainability** -- coupling, cohesion, complexity, testability +- **Modern practices** -- alignment with current language idioms and community + standards +- **Architecture** -- apply hexagonal architecture thinking to identify areas + of high coupling and candidates for restructuring + +### Execution steps + +1. Read the project's entry points, core packages, and test files to build a + mental model of the system. +2. Analyse each dimension in turn. For each finding, record: + - Which file(s) are affected + - Which dimension(s) it falls under + - A clear description of the problem + - A concrete recommended fix + - A priority rating: **High**, **Medium**, or **Low** +3. Write all findings to `claude-review-architecture.md` using the output + format below. +4. After writing, report the total finding count and top three High-priority + items to the user. + +### Output format + +Write `claude-review-architecture.md` with this structure: + +``` +# Architecture Review + +## Executive Summary +<2-4 sentences: overall health, most critical theme, recommended focus> + +## Findings + +### +- **File(s):** +- **Dimension(s):** +- **Priority:** High | Medium | Low +- **Description:** +- **Recommended fix:** + +... (repeat for each finding) + +## Priority Table + +| Priority | Title | File(s) | +|----------|-------|---------| +| High | ... | ... | +| Medium | ... | ... | +| Low | ... | ... | +``` + +--- + +## Phase 2: Address Findings + +Work through findings in `claude-review-architecture.md` one at a time. Each +finding gets exactly one conventional commit. + +### Scope + +If the user specifies a round label (e.g. "Round-2"), process only findings +tagged with that label. Otherwise process all unresolved findings in priority +order (High first). + +### Per-finding workflow + +For each finding: + +1. **Plan** -- read the finding and identify the minimal correct fix. + +2. **Baseline complexity** -- before touching any file, record its cognitive + complexity: + ```bash + gocognit + ``` + +3. **Fix** -- implement the change. + - If the correct fix belongs in an upstream `github.com/dioad` repository, + create a GitHub issue instead of a local change: + ```bash + gh issue create --repo github.com/dioad/ --title "..." --body "..." + ``` + +4. **Verify** -- run all pre-completion checks before committing: + ```bash + go fix ./... + go fmt ./... + go vet ./... + go test -race ./... + go build . + ``` + Do not proceed to the commit step if any check fails. + +5. **Post-fix complexity** -- record cognitive complexity after the fix: + ```bash + gocognit + ``` + The complexity score must stay the same or decrease. If it increases, + rethink the approach. + +6. **Commit** -- one conventional commit per finding: + ``` + fix: + ``` + +7. **Update document** -- in `claude-review-architecture.md`, mark the finding + resolved and record the commit SHA and complexity delta: + ``` + - **Status:** Resolved in + - **Complexity delta:** -> + ``` + +### Constraints + +- Do not batch multiple unrelated findings into a single commit. +- Do not skip the pre-completion checks step. +- Do not let complexity increase after a fix. +- Do not push to remote; committing locally is sufficient. diff --git a/.gitignore b/.gitignore index 71f4713..0f24725 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,9 @@ temp/ # OS files .DS_Store Thumbs.db + +.gograph/ + + +# APM dependencies +apm_modules/ diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..aa6c643 --- /dev/null +++ b/Makefile @@ -0,0 +1,18 @@ + + +default: verify + +build: + go build . + +lint: + go fmt ./... + go fix ./... + golangci-lint run ./... + gosec ./... + go vet ./... + +test: + go test -race ./... + +verify: lint test build diff --git a/apm.yml b/apm.yml new file mode 100644 index 0000000..02a6194 --- /dev/null +++ b/apm.yml @@ -0,0 +1,14 @@ +name: cli +version: 1.0.0 +description: APM project for cli +author: Pat Downey +# Which agent platforms to deploy to. +# Resolution order: --target flag > this field > auto-detect from filesystem. +# Accepted values: copilot, claude, cursor, opencode, codex, gemini, windsurf, all +targets: +- claude +dependencies: + apm: [] + mcp: [] +includes: auto +scripts: {} diff --git a/claude-review-architecture.md b/claude-review-architecture.md new file mode 100644 index 0000000..c03d4d2 --- /dev/null +++ b/claude-review-architecture.md @@ -0,0 +1,232 @@ +# Architecture Review + +## Executive Summary + +This is a small (4-package, ~110-symbol) library wrapping Cobra + Viper + zerolog for +building CLI applications. The code is clean, well-commented, and reasonably tested, but +one real correctness bug ships silently (`FatalError` never fires), and the recurring +architectural theme is **coupling to process-global singletons** — the global `viper` +package, the global `zerolog/log.Logger`, and an advertised-but-inert config-watcher +goroutine — which together undermine composability, testability, and the "hot-reload" +and "structured logging" features the package claims to provide. Fixing `FatalError` is +the priority; the singleton coupling is a design decision worth revisiting deliberately +rather than patching piecemeal. + +## Findings + +### `FatalError` never logs or exits — the event is built but never finalized + +- **File(s):** `logging/logging.go:149-151` +- **Dimension(s):** Correctness +- **Priority:** High +- **Description:** `FatalError` is implemented as: + ```go + func FatalError(err error) { + log.Fatal().Err(err) + } + ``` + zerolog's own documentation states an `Event` is "finalized by the `Msg` or `Msgf` + method" — until one of those (or `Send`) is called, the event is never written, and + critically, zerolog's `os.Exit(1)` side effect for `Fatal()` only fires from that same + finalization path. Without `.Msg("")`/`.Send()`, `FatalError(err)` is a complete no-op: + it neither logs the error nor terminates the process, despite its name and its exported + contract. `gograph query FatalError` confirms this function has no production callers + today, but it is an exported API surface that any consumer of this library may already + be relying on (or will rely on) to terminate on unrecoverable errors — silently doing + nothing is the worst failure mode for a function named `FatalError`. Notably, the + existing test (`logging/logging_test.go:182`, `TestFatalError`) documents that it + "can't easily test FatalError as it calls log.Fatal which exits" — the test author's + own assumption confirms the bug went unnoticed because it looks correct at a glance. +- **Recommended fix:** Add `.Msg(err.Error())` (or `.Send()`) to finalize the event: + ```go + func FatalError(err error) { + log.Fatal().Err(err).Msg(err.Error()) + } + ``` + Then add a real test using `os.Exit` interception (e.g. via a subprocess test with + `exec.Command` re-invoking the test binary, the standard Go pattern for testing + functions that call `os.Exit`), replacing the current placebo test. +- **Status:** Resolved in `a7e66d6` +- **Complexity delta:** 0 -> 0 (no branching added; `logging.go`'s other functions + unaffected. New subprocess test verified to fail against the pre-fix code.) + +### `InitConfig` advertises "hot-reloading" but never re-applies reloaded config, and leaks a watcher goroutine per call + +- **File(s):** `config.go:130-219` (`InitConfig`, `WithoutWatchConfig`) +- **Dimension(s):** Correctness, Architecture +- **Priority:** Medium-High +- **Description:** `InitConfig`'s doc comment promises "Configuration hot-reloading via + Viper watchers," and `options.watchConfig` gates a call to `v.WatchConfig()`. However, + `v.WatchConfig()` only updates Viper's *internal* key-value store when the file + changes — `gograph query OnConfigChange` returns no results anywhere in the repo, so + no `v.OnConfigChange(func(fsnotify.Event){...})` callback is ever registered to + re-`Unmarshal` the change into the caller's `cfg`/`CommonConfig` structs. The net + effect: the advertised "hot-reload" feature changes nothing the caller can observe. + Compounding this, `InitConfig` does not return the `*viper.Viper` instance it + constructs, so even a future caller wanting to add their own `OnConfigChange` handler + has no handle to do so, and the `WatchConfig`-spawned fsnotify watcher goroutine (one + per `InitConfig` call) can never be stopped — each call to `InitConfig` with the + default options leaks one background goroutine for the lifetime of the process. +- **Recommended fix:** Either (a) implement the feature properly — register + `v.OnConfigChange` to re-run `UnmarshalConfig(v, cfg)` (and reconfigure logging if + `c.Logging` changed) on file-change events, and return the `*viper.Viper` (or a small + wrapper with a `Stop()`/`Close()`) so callers can manage the watcher's lifecycle; or + (b) if hot-reload isn't actually a supported feature, remove `v.WatchConfig()` and the + `WithoutWatchConfig` option entirely and correct the doc comment. Leaving the + half-built version in place is the worst of both — it reads as a feature but silently + isn't one. +- **Status:** Resolved in `a059e26`. Option (a) was rejected during implementation + design review: registering `v.OnConfigChange` to re-`Unmarshal` into the caller's + `cfg` writes that struct from the fsnotify goroutine while the caller/`execFunc` reads + it from the main goroutine — an unsynchronized read/write the project's own + `go test -race` gate would (correctly) flag. Safe delivery needs the caller to + participate (mutex, atomic snapshot, getter), which is an API change and therefore out + of scope for a non-breaking fix. Went with a variant of option (b): removed the + `v.WatchConfig()` call from `InitConfig` (the exported `WithoutWatchConfig` option is + kept, now documented as a deprecated no-op, since removing an exported symbol would be + a breaking change) and corrected `InitConfig`'s doc comment. Added + `TestInitConfigDoesNotLeakWatcherGoroutine`, verified to fail against the pre-fix code + (32 live goroutines vs. an expected ≤4 after 10 calls) and pass after. +- **Complexity delta:** `InitConfig`: 15 -> 13 (one branch removed); all other + functions in `config.go` unchanged. + +### Two parallel, inconsistent config-initialization paths: global Viper singleton vs. per-call instance + +- **File(s):** `config.go:37-93` (`InitViperConfig`, `InitViperConfigWithFlagSet`) vs. `config.go:138-219` (`InitConfig`) +- **Dimension(s):** Inconsistencies, Architecture, Maintainability +- **Priority:** Medium +- **Description:** The package ships two independent config-loading implementations + with different behavior and different coupling models: + - `InitViperConfig` / `InitViperConfigWithFlagSet` operate entirely on the **global** + `viper` package-level singleton (`gograph query "viper."` shows every one of + `viper.BindPFlags`, `viper.SetConfigName`, `viper.AddConfigPath`, `viper.AutomaticEnv`, + etc. called only from `InitViperConfigWithFlagSet`). Any process that calls this + twice (e.g. two subcommands, or a test suite) mutates shared global state; the + package's own test (`initconfig_test.go:177-178`) documents this explicitly: *"Note: + InitViperConfigWithFlagSet uses the global Viper instance. These tests must not run + in parallel to avoid interference."* — a direct violation of this project's own + testing standard ("Run in Parallel: tests must be fully independent"). + - `InitConfig` instead constructs a local `viper.New()` per call and is fully + parallel-safe and composable — the design the library should be standardizing on. + - The two paths also disagree on environment variable key replacement: + `InitViperConfigWithFlagSet` replaces only `-` (`strings.NewReplacer("-", "_")`, + `config.go:77`), while `InitConfig` replaces both `-` and `.` + (`strings.NewReplacer("-", "_", ".", "_")`, `config.go:152`) — so a nested config key + like `log.level` maps to `LOG_LEVEL` under one path and is left unmapped under the + other. + - **Compounding this, the package's own doc comments contradict each other on + precedence.** `doc.go:53-61` states the merge order (highest to lowest, "last wins") + as: file at `/etc/...` → file at `$HOME/.config/...` → CLI flags → env vars → + `--config` file. `InitViperConfig`'s doc comment (`config.go:44-49`) states the + opposite ordering — flags highest, then `--config` file, then env vars, then + standard-location files lowest. Both cannot be correct, and neither matches Viper's + actual fixed precedence order (explicit `Set` > flag > env > config file > default), + so a consumer reading either doc comment will form a wrong mental model of which + source wins. +- **Recommended fix:** Deprecate `InitViperConfig`/`InitViperConfigWithFlagSet` in favor + of `InitConfig`'s local-instance pattern (or refactor them to build a local + `viper.New()` too), unify the env-key replacer behavior between the two paths, and + rewrite `doc.go`'s and `InitViperConfig`'s precedence descriptions to match Viper's + actual documented precedence — verify against the real behavior with a table test + rather than prose. +- **Status:** Resolved in `5bf716a`. Kept both deprecated functions as-is behaviorally + (no change to the global-singleton mechanics or the env-key replacer difference — + deprecated code shouldn't get further behavior changes, only documentation pointing + callers away from it) and added standard `// Deprecated:` godoc lines to both, + referencing `InitConfig`. Rewrote `doc.go`'s "Configuration Loading Order" section and + `InitViperConfig`'s doc comment to state the same, correct precedence order (verified + against Viper's official docs via Context7): command-line flags > environment + variables > config file > defaults. +- **Complexity delta:** No change (doc-comment-only edit); `InitViperConfigWithFlagSet` + remains at 6, `InitViperConfig` remains untracked by gocognit (below its reporting + threshold, unaffected). + +### `Context()`/`SetOrgName`/`SetAppName` establish a context-propagation pattern, but the configured logger is never attached to it + +- **File(s):** `config.go:391-438` (`Context`, `SetOrgName`, `SetAppName`), `logging/logging.go:119-146` (`ConfigureLogOutput`) +- **Dimension(s):** Architecture, Maintainability +- **Priority:** Medium +- **Description:** The library provides a clean, hexagonal-style context-propagation + convention for org/app metadata (`cli.Context`, `cli.SetOrgName`, `cli.SetAppName`, + consumed later by `CobraRunE` via `OrgNameFromContext`/`AppNameFromContext`), and + `CobraRunE`'s `execFunc` signature is `func(context.Context, *T) error` — signaling + that downstream application code is expected to work through `context.Context`. But + `ConfigureCmdLogger`/`ConfigureLogOutput` only ever mutate the global + `github.com/rs/zerolog/log.Logger` — there is no equivalent `SetLogger`/context + injection to make the configured logger retrievable via `zerolog.Ctx(ctx)` from within + `execFunc`. Every consumer is therefore forced to depend on the global `log.Logger` + inside their command bodies even though the library already hands them a + `context.Context` built for exactly this kind of propagation. This is a missed + opportunity in the library's own abstraction, not a bug — but it means the "structured + logging" feature this package advertises doesn't compose with the "context management" + feature it also advertises. +- **Recommended fix:** After `ConfigureLogOutput` builds `log.Logger`, also inject it + into the context passed to `execFunc` (e.g. have `CobraRunE` call + `log.Logger.WithContext(cmd.Context())` before invoking `execFunc`, and consider + setting `zerolog.DefaultContextLogger = &log.Logger` at the same point) so command + bodies can use `zerolog.Ctx(ctx)` instead of the global logger. +- **Status:** Resolved in `e8217e3`. `CobraRunE` now does + `ctx := log.Logger.WithContext(cmd.Context())` and passes that to `execFunc`. Did + **not** also set `zerolog.DefaultContextLogger` — per this repo's own zerolog + conventions, that's set once at the entry point (`main`/`Exec`), not inside a + per-command `RunE` that can run repeatedly. Purely additive; no signature changes. + Added `TestCobraRunEInjectsLoggerIntoContext`, verified to fail (reports + `zerolog.Disabled`) against the pre-fix code. +- **Complexity delta:** `CobraRunE`: 7 -> 7 (no new branching, straight-line context + wrap). + +### Inconsistent test assertion style: raw `t.Error`/`t.Fatalf` alongside testify in the same package + +- **File(s):** `logging/logging_test.go` (entirely raw), `config_test.go` (`TestIsDocker`, `TestValidateName`, `TestDefaultUserConfigPath`, etc. — raw), vs. `integration_test.go`, `initconfig_test.go`, `commandparts_test.go` (consistently testify) +- **Dimension(s):** Inconsistencies, Modern Practices +- **Priority:** Low-Medium +- **Description:** The project's own testing standard mandates testify (`assert`/ + `require`) for all assertions, and `logging/example_test.go`, `logging/logfile_test.go`, + `integration_test.go`, and `initconfig_test.go` all follow it. But `logging/logging_test.go` + uses raw `if x != y { t.Errorf(...) }` throughout (e.g. lines 23-37, 84-90, 102-137, + 192-221), and `config_test.go` mixes both styles in the same file (`TestIsDocker`, + `TestValidateName` at lines 25-101 are raw; `TestContextWithNilBase`, + `TestUnmarshalConfig` at lines 238-249, 395-416 use testify). This makes failure + messages inconsistent in quality (raw `t.Errorf` calls here don't produce the + richer diffs testify provides) and signals the standard isn't enforced uniformly. +- **Recommended fix:** Convert the remaining raw assertions in `logging/logging_test.go` + and the older parts of `config_test.go` to `assert`/`require`, consistent with the rest + of the suite. Low risk, mechanical change — a good candidate for a single follow-up + commit per file. +- **Status:** Resolved in `e89380d`. Converted all raw `t.Error`/`t.Errorf`/`t.Fatalf` + checks in both files to `assert`/`require`. No behavior change; a couple of + incidental simplifications fell out naturally (e.g. `TestIsDocker`'s redundant + double-check of the same condition collapsed to one skip-guard plus one assertion). +- **Complexity delta:** Every touched function decreased or stayed the same; none + increased. Notably `TestConfigureLogLevel`: 6 -> 4, `TestDefaultConfigPath`: 5 -> 1, + `TestValidateName`: 4 -> 1 (via a branch-free `assert.Equal(t, tt.wantErr, err != nil)` + instead of an if/else, after an initial if/else draft measured 4 -> 5 and was + reworked). + +### Minor: redundant `log.Logger` construction in `ConfigureLogOutput` + +- **File(s):** `logging/logging.go:119-146` +- **Dimension(s):** Maintainability +- **Priority:** Low +- **Description:** `log.Logger` is constructed twice — once at line 129 to guarantee a + writable logger exists while resolving file output, and again unconditionally at line + 141 with whatever `logOutput` ended up being. This is intentional per the inline + comment ("Setup logging to stdout by default so we have somewhere to log any errors + configuring logging") and not a bug, but it's easy to misread as duplicated/dead code + during future edits. +- **Recommended fix:** Optional — a one-line comment above line 141 clarifying "this + replaces the temporary stdout logger above once file output (if any) is resolved" + would remove the ambiguity for future readers. Not worth a structural change. +- **Status:** Resolved in `03cb631`. Added the clarifying comment; no logic change. +- **Complexity delta:** `ConfigureLogOutput`: 5 -> 5 (comment-only). + +## Priority Table + +| Priority | Title | File(s) | +|----------|-------|---------| +| High | `FatalError` never logs or exits | `logging/logging.go` | +| Medium-High | `InitConfig` hot-reload is inert and leaks a watcher goroutine | `config.go` | +| Medium | Two parallel, inconsistent config-init paths (global vs. local Viper) | `config.go`, `doc.go` | +| Medium | Context propagation pattern doesn't extend to the configured logger | `config.go`, `logging/logging.go` | +| Low-Medium | Inconsistent test assertion style (raw vs. testify) | `logging/logging_test.go`, `config_test.go` | +| Low | Redundant `log.Logger` construction (intentional, under-commented) | `logging/logging.go` | diff --git a/config.go b/config.go index cb8a716..90d515d 100644 --- a/config.go +++ b/config.go @@ -11,6 +11,7 @@ import ( "github.com/go-viper/mapstructure/v2" "github.com/mitchellh/go-homedir" + "github.com/rs/zerolog/log" "github.com/spf13/cobra" "github.com/spf13/pflag" "github.com/spf13/viper" @@ -42,11 +43,16 @@ func commandParts(cmd *cobra.Command) []string { // - Support environment variables with the given appName prefix // - Unmarshal configuration into the provided cfg struct // -// Configuration sources are merged with this precedence (highest to lowest): -// 1. Command-line flags -// 2. Explicit config file (--config flag) -// 3. Environment variables (prefixed with appName) -// 4. Config files in standard locations +// Configuration sources are merged with Viper's standard precedence (highest to +// lowest): explicit overrides, command-line flags, environment variables +// (prefixed with appName), config files, then defaults. +// +// Deprecated: use InitConfig instead. InitViperConfig and +// InitViperConfigWithFlagSet operate on Viper's global package-level singleton, +// so concurrent or repeated calls within the same process (including parallel +// tests) mutate shared state. InitConfig instead constructs a local Viper +// instance per call and is safe to use from parallel tests or multiple +// commands in the same process. func InitViperConfig(orgName, appName string, cfg any) error { pflag.Parse() return InitViperConfigWithFlagSet(orgName, appName, cfg, pflag.CommandLine) @@ -57,6 +63,12 @@ func InitViperConfig(orgName, appName string, cfg any) error { // Similar to InitViperConfig but allows specifying a custom pflag.FlagSet // instead of using the global command line flags. Useful for embedding // configuration initialization in library code or tests. +// +// Deprecated: use InitConfig instead, for the same reason as InitViperConfig — +// this function reads and mutates Viper's global singleton. Note also that its +// environment variable key replacer only maps "-" to "_", whereas InitConfig's +// also maps "." to "_"; the two functions are not behaviourally interchangeable +// for keys containing dots. func InitViperConfigWithFlagSet(orgName, appName string, cfg any, parsedFlagSet *pflag.FlagSet) error { err := viper.BindPFlags(parsedFlagSet) if err != nil { @@ -117,10 +129,14 @@ func WithoutLogging() InitConfigOption { } } -// WithoutWatchConfig disables automatic configuration hot-reloading during InitConfig. +// WithoutWatchConfig is a no-op, retained for backward compatibility. // -// By default, InitConfig calls WatchConfig when a config file is found, which -// starts a background goroutine. Use this option in tests to prevent that. +// Deprecated: InitConfig no longer starts a background config-file watcher. +// The previous implementation started an fsnotify goroutine via Viper's +// WatchConfig but never re-applied changes into the caller's config struct, +// and doing so safely would require synchronized access to that struct (a +// breaking API change). The goroutine was therefore removed rather than +// left running with no observable effect. func WithoutWatchConfig() InitConfigOption { return func(o *initConfigOptions) { o.watchConfig = false @@ -134,7 +150,6 @@ func WithoutWatchConfig() InitConfigOption { // - Flag binding from the Cobra command // - Environment variable overrides // - Automatic logging configuration (disable with WithoutLogging) -// - Configuration hot-reloading via Viper watchers (disable with WithoutWatchConfig) func InitConfig(orgName, appName string, cmd *cobra.Command, cfg any, opts ...InitConfigOption) (*CommonConfig, error) { options := defaultInitConfigOptions() for _, o := range opts { @@ -195,10 +210,6 @@ func InitConfig(orgName, appName string, cmd *cobra.Command, cfg any, opts ...In } } - if err == nil && options.watchConfig { - v.WatchConfig() - } - var c CommonConfig err = UnmarshalConfig(v, &c) @@ -464,6 +475,11 @@ func CobraRunE[T any](execFunc func(context.Context, *T) error, opt ...CobraOpt[ return err } - return execFunc(cmd.Context(), &cfg) + // Attach the logger InitConfig just configured to the context so + // execFunc can retrieve it via zerolog.Ctx(ctx) instead of depending + // on the global logger directly. + ctx := log.Logger.WithContext(cmd.Context()) + + return execFunc(ctx, &cfg) } } diff --git a/config_test.go b/config_test.go index 6722e2d..bc04bf3 100644 --- a/config_test.go +++ b/config_test.go @@ -14,6 +14,7 @@ import ( "github.com/spf13/pflag" "github.com/spf13/viper" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/dioad/cli" ) @@ -29,9 +30,7 @@ func TestIsDocker(t *testing.T) { if cli.IsDocker() { t.Skip("running inside Docker; skipping non-Docker assertion") } - if cli.IsDocker() { - t.Error("IsDocker() = true, want false when /.dockerenv is absent") - } + assert.False(t, cli.IsDocker(), "IsDocker() should return false when /.dockerenv is absent") } func TestValidateName(t *testing.T) { @@ -94,9 +93,7 @@ func TestValidateName(t *testing.T) { for _, tt := range tests { t.Run(tt.label, func(t *testing.T) { err := cli.ValidateName(tt.name) - if (err != nil) != tt.wantErr { - t.Errorf("validateName() error = %v, wantErr %v", err, tt.wantErr) - } + assert.Equal(t, tt.wantErr, err != nil, "ValidateName(%q) error = %v", tt.name, err) }) } } @@ -107,24 +104,17 @@ func TestDefaultUserConfigPath(t *testing.T) { appName := "testapp" filePath, err := cli.DefaultUserConfigPath(orgName, appName) - if err != nil { - t.Fatalf("DefaultUserConfigPath() error = %v", err) - } + require.NoError(t, err) t.Cleanup(func() { _ = os.RemoveAll(filepath.Dir(filePath)) }) - if filePath == "" { - t.Error("DefaultUserConfigPath() returned empty path") - } + assert.NotEmpty(t, filePath, "DefaultUserConfigPath() returned empty path") // Verify directory was created - if _, err := os.Stat(filePath); err != nil { - t.Fatalf("DefaultUserConfigPath() created path not found: %v", err) - } + _, err = os.Stat(filePath) + require.NoError(t, err, "DefaultUserConfigPath() created path not found") // Verify path contains org and app names - if !strings.Contains(filePath, orgName) { - t.Errorf("DefaultUserConfigPath() path doesn't contain orgName: %s", filePath) - } + assert.Contains(t, filePath, orgName) } // TestDefaultConfigPath returns the correct path based on environment. @@ -133,21 +123,15 @@ func TestDefaultConfigPath(t *testing.T) { appName := "testapp" filePath, err := cli.DefaultConfigPath(orgName, appName) - if err != nil { - t.Fatalf("DefaultConfigPath() error = %v", err) - } + require.NoError(t, err) t.Cleanup(func() { _ = os.RemoveAll(filepath.Dir(filePath)) }) - if filePath == "" { - t.Error("DefaultConfigPath() returned empty path") - } + assert.NotEmpty(t, filePath, "DefaultConfigPath() returned empty path") - // Verify path is valid - if _, err := os.Stat(filePath); err != nil { - if !os.IsNotExist(err) { - t.Fatalf("DefaultConfigPath() stat error: %v", err) - } - // Path may not exist yet, that's OK + // Verify path is valid; it may not exist yet, that's OK. + _, err = os.Stat(filePath) + if err != nil { + require.True(t, os.IsNotExist(err), "DefaultConfigPath() stat error: %v", err) } } @@ -157,14 +141,10 @@ func TestDefaultPersistencePath(t *testing.T) { appName := "testapp" filePath, err := cli.DefaultPersistencePath(orgName, appName) - if err != nil { - t.Fatalf("DefaultPersistencePath() error = %v", err) - } + require.NoError(t, err) t.Cleanup(func() { _ = os.RemoveAll(filepath.Dir(filePath)) }) - if filePath == "" { - t.Error("DefaultPersistencePath() returned empty path") - } + assert.NotEmpty(t, filePath, "DefaultPersistencePath() returned empty path") } // TestDefaultConfigFile returns the correct file path. @@ -174,19 +154,14 @@ func TestDefaultConfigFile(t *testing.T) { baseName := "config" filePath, err := cli.DefaultConfigFile(orgName, appName, baseName) - if err != nil { - t.Fatalf("DefaultConfigFile() error = %v", err) - } + require.NoError(t, err) t.Cleanup(func() { _ = os.RemoveAll(filepath.Dir(filePath)) }) - if filePath == "" { - t.Error("DefaultConfigFile() returned empty path") - } + assert.NotEmpty(t, filePath, "DefaultConfigFile() returned empty path") // Verify the file path ends with the expected name - if !strings.HasSuffix(filePath, "config.yaml") { - t.Errorf("DefaultConfigFile() path doesn't end with 'config.yaml': %s", filePath) - } + assert.True(t, strings.HasSuffix(filePath, "config.yaml"), + "DefaultConfigFile() path doesn't end with 'config.yaml': %s", filePath) } // TestDefaultPersistenceFile returns the correct file path. @@ -196,18 +171,12 @@ func TestDefaultPersistenceFile(t *testing.T) { baseName := "state" filePath, err := cli.DefaultPersistenceFile(orgName, appName, baseName) - if err != nil { - t.Fatalf("DefaultPersistenceFile() error = %v", err) - } + require.NoError(t, err) t.Cleanup(func() { _ = os.RemoveAll(filepath.Dir(filePath)) }) - if filePath == "" { - t.Error("DefaultPersistenceFile() returned empty path") - } - - if !strings.HasSuffix(filePath, "state.yaml") { - t.Errorf("DefaultPersistenceFile() path doesn't end with 'state.yaml': %s", filePath) - } + assert.NotEmpty(t, filePath, "DefaultPersistenceFile() returned empty path") + assert.True(t, strings.HasSuffix(filePath, "state.yaml"), + "DefaultPersistenceFile() path doesn't end with 'state.yaml': %s", filePath) } // TestContext creates and retrieves context values. @@ -236,7 +205,7 @@ func TestContext(t *testing.T) { // TestContextWithNilBase creates context with nil base context. func TestContextWithNilBase(t *testing.T) { - ctx := cli.Context(nil) // lint:ignore SA1012 specifically testing behaviour is nil is passed + ctx := cli.Context(nil) //nolint:staticcheck // specifically testing behaviour when nil is passed assert.NotNil(t, ctx) // Verify context is usable @@ -252,32 +221,22 @@ func TestContextWithNilBase(t *testing.T) { func TestSetOrgName(t *testing.T) { orgName := "myorg" opt := cli.SetOrgName(orgName) - - if opt == nil { - t.Error("SetOrgName() returned nil") - } + require.NotNil(t, opt, "SetOrgName() returned nil") // Apply to context ctx := opt(context.Background()) - if ctx == nil { - t.Error("SetOrgName() returned nil context") - } + assert.NotNil(t, ctx, "SetOrgName() returned nil context") } // TestSetAppName sets app name in context. func TestSetAppName(t *testing.T) { appName := "myapp" opt := cli.SetAppName(appName) - - if opt == nil { - t.Error("SetAppName() returned nil") - } + require.NotNil(t, opt, "SetAppName() returned nil") // Apply to context ctx := opt(context.Background()) - if ctx == nil { - t.Error("SetAppName() returned nil context") - } + assert.NotNil(t, ctx, "SetAppName() returned nil context") } // TestNewCommand creates a command with type-safe config. @@ -303,17 +262,9 @@ func TestNewCommand(t *testing.T) { cfg, ) - if cmd == nil { - t.Fatal("NewCommand() returned nil command") - } - - if cmd.Use != "test" { - t.Errorf("NewCommand() use = %s, want test", cmd.Use) - } - - if cmd.RunE == nil { - t.Error("NewCommand() RunE not set") - } + require.NotNil(t, cmd, "NewCommand() returned nil command") + assert.Equal(t, "test", cmd.Use) + assert.NotNil(t, cmd.RunE, "NewCommand() RunE not set") } // TestNewCommandWithConfigFlag creates command with config flag option. @@ -335,19 +286,12 @@ func TestNewCommandWithConfigFlag(t *testing.T) { cli.WithConfigFlag("config.yaml"), ) - if cmd == nil { - t.Fatal("NewCommand() returned nil") - } + require.NotNil(t, cmd, "NewCommand() returned nil") // Verify config flag was added configFlag := cmd.Flag("config") - if configFlag == nil { - t.Fatal("NewCommand() did not add config flag") - } - - if configFlag.Shorthand != "c" { - t.Errorf("config flag shorthand = %s, want c", configFlag.Shorthand) - } + require.NotNil(t, configFlag, "NewCommand() did not add config flag") + assert.Equal(t, "c", configFlag.Shorthand) } // TestWithConfigFlag option sets config flag correctly. @@ -358,13 +302,8 @@ func TestWithConfigFlag(t *testing.T) { opt(cmd) configFlag := cmd.Flag("config") - if configFlag == nil { - t.Fatal("WithConfigFlag() did not add config flag") - } - - if configFlag.DefValue != "my-config.yaml" { - t.Errorf("config flag default = %s, want my-config.yaml", configFlag.DefValue) - } + require.NotNil(t, configFlag, "WithConfigFlag() did not add config flag") + assert.Equal(t, "my-config.yaml", configFlag.DefValue) } func TestUnmarshalConfig(t *testing.T) { diff --git a/doc.go b/doc.go index 4350a78..7f79a33 100644 --- a/doc.go +++ b/doc.go @@ -52,13 +52,15 @@ // // # Configuration Loading Order // -// Configurations are loaded and merged in this order (last wins): -// -// 1. Config file at /etc/{org}/{app}/config.yaml -// 2. Config file at $HOME/.config/{org}/{app}/config.yaml -// 3. Command-line flags -// 4. Environment variables with prefix {APPNAME}_ -// 5. Config file specified by --config flag +// InitConfig searches for a config file at /etc/{org}/{app}/... or +// $HOME/.config/{org}/{app}/..., unless --config points at an explicit file. +// Whichever file is found (if any) is merged with flags and environment +// variables using Viper's standard precedence (highest to lowest): +// +// 1. Command-line flags +// 2. Environment variables with prefix {APPNAME}_ +// 3. Config file (explicit --config file, or the first standard location found) +// 4. Defaults // // # Context Management // diff --git a/example_test.go b/example_test.go index 21c2338..5490bf0 100644 --- a/example_test.go +++ b/example_test.go @@ -4,8 +4,9 @@ import ( "context" "fmt" - "github.com/dioad/cli" "github.com/spf13/cobra" + + "github.com/dioad/cli" ) // ExampleNewCommand demonstrates creating a type-safe command with configuration. diff --git a/initconfig_test.go b/initconfig_test.go index 43e3335..8c98ce3 100644 --- a/initconfig_test.go +++ b/initconfig_test.go @@ -5,6 +5,7 @@ package cli_test import ( "os" "path/filepath" + "runtime" "testing" "github.com/spf13/cobra" @@ -46,7 +47,8 @@ func newTestCmd(t *testing.T, configFile string) *cobra.Command { // - t.TempDir() for filesystem isolation // - t.Setenv() for environment variable isolation // - WithoutLogging() to avoid global zerolog state changes -// - WithoutWatchConfig() to prevent background goroutines +// - WithoutWatchConfig() for backward-compatible option parity (it is now a +// no-op; InitConfig no longer starts a background watcher goroutine) func TestInitConfig(t *testing.T) { type testConfig struct { Name string `mapstructure:"name"` @@ -162,7 +164,7 @@ func TestInitConfig(t *testing.T) { // Act _, err := cli.InitConfig(tt.orgName, tt.appName, cmd, &cfg, cli.WithoutLogging(), // keep global zerolog state unchanged - cli.WithoutWatchConfig(), // prevent background goroutines + cli.WithoutWatchConfig(), // no-op, kept for option parity ) // Assert @@ -171,6 +173,30 @@ func TestInitConfig(t *testing.T) { } } +// TestInitConfigDoesNotLeakWatcherGoroutine verifies that InitConfig no +// longer starts a background fsnotify watcher goroutine per call (the +// watcher was removed because it had no safe way to propagate reloaded +// config into the caller's struct — see WithoutWatchConfig's doc comment). +func TestInitConfigDoesNotLeakWatcherGoroutine(t *testing.T) { + type testConfig struct { + Name string `mapstructure:"name"` + } + + before := runtime.NumGoroutine() + + for range 10 { + cmd := newTestCmd(t, writeYAML(t, "name: x\n")) + var cfg testConfig + _, err := cli.InitConfig("testorg", "testapp", cmd, &cfg, cli.WithoutLogging()) + require.NoError(t, err) + } + + runtime.Gosched() + after := runtime.NumGoroutine() + assert.LessOrEqual(t, after, before+2, + "InitConfig should not start a background watcher goroutine per call") +} + // TestInitViperConfigWithFlagSet verifies that a custom pflag.FlagSet is // correctly bound and unmarshalled into the target struct. // diff --git a/integration_test.go b/integration_test.go index 9e2e987..438dd6b 100644 --- a/integration_test.go +++ b/integration_test.go @@ -4,6 +4,7 @@ import ( "context" "testing" + "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/spf13/pflag" "github.com/stretchr/testify/assert" @@ -164,6 +165,34 @@ func TestContextPropagation(t *testing.T) { "app name should be retrievable from the command context") } +// TestCobraRunEInjectsLoggerIntoContext verifies that CobraRunE attaches the +// logger configured by InitConfig to the context passed to execFunc, so +// execFunc can retrieve it via zerolog.Ctx(ctx) instead of the global logger. +func TestCobraRunEInjectsLoggerIntoContext(t *testing.T) { + type Config struct{} + var level zerolog.Level + + cmd := cli.NewCommand( + &cobra.Command{Use: "test", SilenceUsage: true}, + func(ctx context.Context, c *Config) error { + level = zerolog.Ctx(ctx).GetLevel() + return nil + }, + &Config{}, + ) + + ctx := cli.Context( + context.Background(), + cli.SetOrgName("testorg"), + cli.SetAppName("testapp"), + ) + + cmd.SetArgs([]string{}) + require.NoError(t, cmd.ExecuteContext(ctx)) + assert.NotEqual(t, zerolog.Disabled, level, + "zerolog.Ctx(ctx) inside execFunc should return the configured logger, not the no-op logger") +} + // TestEnvironmentIntegration verifies that environment variables are // correctly read and applied by InitViperConfigWithFlagSet. func TestEnvironmentIntegration(t *testing.T) { diff --git a/logging/example_test.go b/logging/example_test.go index f218b75..8820f3d 100644 --- a/logging/example_test.go +++ b/logging/example_test.go @@ -3,8 +3,9 @@ package logging_test import ( "fmt" - "github.com/dioad/cli/logging" "github.com/rs/zerolog" + + "github.com/dioad/cli/logging" ) // ExampleConfig demonstrates creating a logging configuration. diff --git a/logging/logging.go b/logging/logging.go index 1091231..204a3bf 100644 --- a/logging/logging.go +++ b/logging/logging.go @@ -138,6 +138,8 @@ func ConfigureLogOutput(c Config) { logOutput = fileOutput } } + // Replaces the temporary stdout logger constructed above once file + // output (if any) has been resolved; not a duplicate of that call. log.Logger = zerolog.New(logOutput).With().Timestamp().Logger() // Configure default logger @@ -147,5 +149,5 @@ func ConfigureLogOutput(c Config) { // FatalError logs an error with fatal level and exits the program. func FatalError(err error) { - log.Fatal().Err(err) + log.Fatal().Err(err).Msg(err.Error()) } diff --git a/logging/logging_test.go b/logging/logging_test.go index 7162a6f..20070b0 100644 --- a/logging/logging_test.go +++ b/logging/logging_test.go @@ -1,10 +1,17 @@ package logging_test import ( + "bytes" + "errors" + "os" + "os/exec" "testing" - "github.com/dioad/cli/logging" "github.com/rs/zerolog" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dioad/cli/logging" ) // TestConfig verifies the logging configuration struct. @@ -19,21 +26,10 @@ func TestConfig(t *testing.T) { Compress: true, } - if cfg.Level != "debug" { - t.Errorf("Config.Level = %s, want debug", cfg.Level) - } - - if cfg.File != "test.log" { - t.Errorf("Config.File = %s, want test.log", cfg.File) - } - - if cfg.MaxSize != 100 { - t.Errorf("Config.MaxSize = %d, want 100", cfg.MaxSize) - } - - if cfg.MaxBackups != 3 { - t.Errorf("Config.MaxBackups = %d, want 3", cfg.MaxBackups) - } + assert.Equal(t, "debug", cfg.Level) + assert.Equal(t, "test.log", cfg.File) + assert.Equal(t, 100, cfg.MaxSize) + assert.Equal(t, 3, cfg.MaxBackups) } // TestConfigureLogLevel sets and verifies log level. @@ -78,14 +74,13 @@ func TestConfigureLogLevel(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - defer func() { - if r := recover(); r != nil && tt.expectedNoPanic { - t.Errorf("ConfigureLogLevel(%s) panicked: %v", tt.level, r) - } - }() - - logging.ConfigureLogLevel(tt.level, tt.defaultLevel) - // If we get here, no panic occurred + assertFunc := assert.NotPanics + if !tt.expectedNoPanic { + assertFunc = assert.Panics + } + assertFunc(t, func() { + logging.ConfigureLogLevel(tt.level, tt.defaultLevel) + }) }) } } @@ -97,16 +92,11 @@ func TestWithDefaultLogLevel(t *testing.T) { } opt := logging.WithDefaultLogLevel(zerolog.DebugLevel) - - if opt == nil { - t.Error("WithDefaultLogLevel() returned nil") - } + require.NotNil(t, opt, "WithDefaultLogLevel() returned nil") opt(&cfg) - if cfg.Level != "debug" { - t.Errorf("WithDefaultLogLevel() set level to %s, want debug", cfg.Level) - } + assert.Equal(t, "debug", cfg.Level) } // TestWithDefaultLogLevelDoesNotOverride preserves existing level. @@ -118,9 +108,7 @@ func TestWithDefaultLogLevelDoesNotOverride(t *testing.T) { opt := logging.WithDefaultLogLevel(zerolog.DebugLevel) opt(&cfg) - if cfg.Level != "error" { - t.Errorf("WithDefaultLogLevel() override existing level to %s, want error", cfg.Level) - } + assert.Equal(t, "error", cfg.Level, "WithDefaultLogLevel() should not override an existing level") } // TestWithDefaultLogLevelFixesInvalid replaces invalid level with default. @@ -132,9 +120,7 @@ func TestWithDefaultLogLevelFixesInvalid(t *testing.T) { opt := logging.WithDefaultLogLevel(zerolog.DebugLevel) opt(&cfg) - if cfg.Level != "debug" { - t.Errorf("WithDefaultLogLevel() fixed invalid level to %s, want debug", cfg.Level) - } + assert.Equal(t, "debug", cfg.Level, "WithDefaultLogLevel() should replace an invalid level with the default") } // TestConfigureCmdLogger applies configuration without panic. @@ -177,28 +163,43 @@ func TestConfigureLogOutput(t *testing.T) { logging.ConfigureLogOutput(cfg) } -// TestFatalError doesn't panic during unit test (it would exit). -func TestFatalError(t *testing.T) { - // We can't easily test FatalError as it calls log.Fatal which exits. - // This is a documentation test showing the function exists. - // In practice, this would only be used when the application needs to exit. +// TestFatalErrorExits verifies FatalError logs the error and exits the +// process with a non-zero status. Since FatalError calls log.Fatal (which +// calls os.Exit), it is exercised in a subprocess rather than in-process. +func TestFatalErrorExits(t *testing.T) { + if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" { + return + } + + cmd := exec.Command(os.Args[0], "-test.run=TestHelperProcessFatalError") + cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1") + var stderr bytes.Buffer + cmd.Stderr = &stderr + err := cmd.Run() + + var exitErr *exec.ExitError + require.ErrorAs(t, err, &exitErr, "FatalError should cause the process to exit non-zero") + assert.False(t, exitErr.Success(), "process should exit with a non-zero status") + assert.Contains(t, stderr.String(), "boom", + "stderr should contain the fatal error message") +} + +// TestHelperProcessFatalError is not a real test; it is invoked as a +// subprocess by TestFatalErrorExits to exercise FatalError's os.Exit path. +func TestHelperProcessFatalError(t *testing.T) { + if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" { + return + } + logging.FatalError(errors.New("boom")) } // TestEmptyConfig uses default values. func TestEmptyConfig(t *testing.T) { cfg := logging.Config{} - if cfg.Level != "" { - t.Errorf("empty Config.Level = %s, want empty", cfg.Level) - } - - if cfg.File != "" { - t.Errorf("empty Config.File = %s, want empty", cfg.File) - } - - if cfg.MaxSize != 0 { - t.Errorf("empty Config.MaxSize = %d, want 0", cfg.MaxSize) - } + assert.Empty(t, cfg.Level) + assert.Empty(t, cfg.File) + assert.Zero(t, cfg.MaxSize) } // TestConfigIsConsistent verifies configuration can be created and used. @@ -211,13 +212,8 @@ func TestConfigIsConsistent(t *testing.T) { cfg2 := cfg1 - if cfg1.Level != cfg2.Level { - t.Error("Config copy doesn't maintain Level") - } - - if cfg1.MaxSize != cfg2.MaxSize { - t.Error("Config copy doesn't maintain MaxSize") - } + assert.Equal(t, cfg1.Level, cfg2.Level, "Config copy should maintain Level") + assert.Equal(t, cfg1.MaxSize, cfg2.MaxSize, "Config copy should maintain MaxSize") } // BenchmarkConfigureLogLevel measures log level configuration time. diff --git a/metadata/metadata.go b/metadata/metadata.go index e54f437..cf78e64 100644 --- a/metadata/metadata.go +++ b/metadata/metadata.go @@ -72,8 +72,8 @@ as a JSON object.`, return enc.Encode(details) } - fmt.Fprintf(cmd.OutOrStdout(), "%s %s %s\n", orgName, appName, info.Version) - return nil + _, err := fmt.Fprintf(cmd.OutOrStdout(), "%s %s %s\n", orgName, appName, info.Version) + return err }, }