Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7b5534c1a5 |
@@ -0,0 +1,141 @@
|
||||
---
|
||||
name: find-skills
|
||||
description: Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.
|
||||
---
|
||||
|
||||
# Find Skills
|
||||
|
||||
This skill helps you discover and install skills from the open agent skills ecosystem.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
Use this skill when the user:
|
||||
|
||||
- Asks "how do I do X" where X might be a common task with an existing skill
|
||||
- Says "find a skill for X" or "is there a skill for X"
|
||||
- Asks "can you do X" where X is a specialized capability
|
||||
- Expresses interest in extending agent capabilities
|
||||
- Wants to search for tools, templates, or workflows
|
||||
- Mentions they wish they had help with a specific domain (design, testing, deployment, etc.)
|
||||
|
||||
## What is the Skills CLI?
|
||||
|
||||
The Skills CLI (`npx skills`) is the package manager for the open agent skills ecosystem. Skills are modular packages that extend agent capabilities with specialized knowledge, workflows, and tools.
|
||||
|
||||
**Key commands:**
|
||||
|
||||
- `npx skills find [query] [--owner <owner>]` - Search for skills interactively or by keyword, optionally scoped to a GitHub owner
|
||||
- `npx skills add <package>` - Install a skill from GitHub or other sources
|
||||
- `npx skills update` - Update all installed skills
|
||||
|
||||
**Browse skills at:** https://skills.sh/
|
||||
|
||||
## How to Help Users Find Skills
|
||||
|
||||
### Step 1: Understand What They Need
|
||||
|
||||
When a user asks for help with something, identify:
|
||||
|
||||
1. The domain (e.g., React, testing, design, deployment)
|
||||
2. The specific task (e.g., writing tests, creating animations, reviewing PRs)
|
||||
3. Whether this is a common enough task that a skill likely exists
|
||||
|
||||
### Step 2: Check the Leaderboard First
|
||||
|
||||
Before running a CLI search, check the [skills.sh leaderboard](https://skills.sh/) to see if a well-known skill already exists for the domain. The leaderboard ranks skills by total installs, surfacing the most popular and battle-tested options.
|
||||
|
||||
For example, top skills for web development include:
|
||||
- `vercel-labs/agent-skills` — React, Next.js, web design (100K+ installs each)
|
||||
- `anthropics/skills` — Frontend design, document processing (100K+ installs)
|
||||
|
||||
### Step 3: Search for Skills
|
||||
|
||||
If the leaderboard doesn't cover the user's need, run the find command:
|
||||
|
||||
```bash
|
||||
npx skills find [query] [--owner <owner>]
|
||||
```
|
||||
|
||||
For example:
|
||||
|
||||
- User asks "how do I make my React app faster?" → `npx skills find react performance`
|
||||
- User asks "can you help me with PR reviews?" → `npx skills find pr review`
|
||||
- User asks "I need to create a changelog" → `npx skills find changelog`
|
||||
|
||||
### Step 4: Verify Quality Before Recommending
|
||||
|
||||
**Do not recommend a skill based solely on search results.** Always verify:
|
||||
|
||||
1. **Install count** — Prefer skills with 1K+ installs. Be cautious with anything under 100.
|
||||
2. **Source reputation** — Official sources (`vercel-labs`, `anthropics`, `microsoft`) are more trustworthy than unknown authors.
|
||||
3. **GitHub stars** — Check the source repository. A skill from a repo with <100 stars should be treated with skepticism.
|
||||
|
||||
### Step 5: Present Options to the User
|
||||
|
||||
When you find relevant skills, present them to the user with:
|
||||
|
||||
1. The skill name and what it does
|
||||
2. The install count and source
|
||||
3. The install command they can run
|
||||
4. A link to learn more at skills.sh
|
||||
|
||||
Example response:
|
||||
|
||||
```
|
||||
I found a skill that might help! The "react-best-practices" skill provides
|
||||
React and Next.js performance optimization guidelines from Vercel Engineering.
|
||||
(185K installs)
|
||||
|
||||
To install it:
|
||||
npx skills add vercel-labs/agent-skills@react-best-practices
|
||||
|
||||
Learn more: https://skills.sh/vercel-labs/agent-skills/react-best-practices
|
||||
```
|
||||
|
||||
### Step 6: Offer to Install
|
||||
|
||||
If the user wants to proceed, you can install the skill for them:
|
||||
|
||||
```bash
|
||||
npx skills add <owner/repo@skill> -g -y
|
||||
```
|
||||
|
||||
The `-g` flag installs globally (user-level) and `-y` skips confirmation prompts.
|
||||
|
||||
## Common Skill Categories
|
||||
|
||||
When searching, consider these common categories:
|
||||
|
||||
| Category | Example Queries |
|
||||
| --------------- | ---------------------------------------- |
|
||||
| Web Development | react, nextjs, typescript, css, tailwind |
|
||||
| Testing | testing, jest, playwright, e2e |
|
||||
| DevOps | deploy, docker, kubernetes, ci-cd |
|
||||
| Documentation | docs, readme, changelog, api-docs |
|
||||
| Code Quality | review, lint, refactor, best-practices |
|
||||
| Design | ui, ux, design-system, accessibility |
|
||||
| Productivity | workflow, automation, git |
|
||||
|
||||
## Tips for Effective Searches
|
||||
|
||||
1. **Use specific keywords**: "react testing" is better than just "testing"
|
||||
2. **Try alternative terms**: If "deploy" doesn't work, try "deployment" or "ci-cd"
|
||||
3. **Check popular sources**: Many skills come from `vercel-labs/agent-skills` or `ComposioHQ/awesome-claude-skills`
|
||||
|
||||
## When No Skills Are Found
|
||||
|
||||
If no relevant skills exist:
|
||||
|
||||
1. Acknowledge that no existing skill was found
|
||||
2. Offer to help with the task directly using your general capabilities
|
||||
3. Suggest the user could create their own skill with `npx skills init`
|
||||
|
||||
Example:
|
||||
|
||||
```
|
||||
I searched for skills related to "xyz" but didn't find any matches.
|
||||
I can still help you with this task directly! Would you like me to proceed?
|
||||
|
||||
If this is something you do often, you could create your own skill:
|
||||
npx skills init my-xyz-skill
|
||||
```
|
||||
@@ -0,0 +1,239 @@
|
||||
---
|
||||
name: golang-code-style
|
||||
description: "Golang code style conventions — line length and breaking, variable declarations, control flow clarity, when comments help vs hurt. Use when writing or reviewing Go code, asking about style or clarity, or establishing project coding standards. Not for naming conventions (→ See `samber/cc-skills-golang@golang-naming` skill), linter configuration (→ See `samber/cc-skills-golang@golang-lint` skill), or doc comments (→ See `samber/cc-skills-golang@golang-documentation` skill)."
|
||||
user-invocable: true
|
||||
license: MIT
|
||||
compatibility: Designed for Claude Code or similar AI coding agents, and for projects using Golang.
|
||||
metadata:
|
||||
author: samber
|
||||
version: "1.2.2"
|
||||
openclaw:
|
||||
emoji: "🎨"
|
||||
homepage: https://github.com/samber/cc-skills-golang
|
||||
requires:
|
||||
bins:
|
||||
- go
|
||||
install: []
|
||||
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent
|
||||
---
|
||||
|
||||
**Orchestration mode:** Use `ultracode` when reviewing code style across a large codebase — orchestrate the sub-agents described in the "Parallelizing Code Style Reviews" section, each covering an independent style concern, and merge their findings.
|
||||
|
||||
> **Community default.** A company skill that explicitly supersedes `samber/cc-skills-golang@golang-code-style` skill takes precedence.
|
||||
|
||||
# Go Code Style
|
||||
|
||||
Style rules that require human judgment — linters handle formatting, this skill handles clarity. For naming see `samber/cc-skills-golang@golang-naming` skill; for design patterns see `samber/cc-skills-golang@golang-design-patterns` skill; for struct/interface design see `samber/cc-skills-golang@golang-structs-interfaces` skill.
|
||||
|
||||
> "Clear is better than clever." — Go Proverbs
|
||||
|
||||
When ignoring a rule, add a comment to the code.
|
||||
|
||||
## Line Length & Breaking
|
||||
|
||||
No rigid line limit, but lines beyond ~120 characters MUST be broken. Break at **semantic boundaries**, not arbitrary column counts. Function calls with 4+ arguments MUST use one argument per line — even when the prompt asks for single-line code:
|
||||
|
||||
```go
|
||||
// Good — each argument on its own line, closing paren separate
|
||||
mux.HandleFunc("/api/users", func(w http.ResponseWriter, r *http.Request) {
|
||||
handleUsers(
|
||||
w,
|
||||
r,
|
||||
serviceName,
|
||||
cfg,
|
||||
logger,
|
||||
authMiddleware,
|
||||
)
|
||||
})
|
||||
```
|
||||
|
||||
When a function signature is too long, the real fix is often **fewer parameters** (use an options struct) rather than better line wrapping. For multi-line signatures, put each parameter on its own line.
|
||||
|
||||
## Variable Declarations
|
||||
|
||||
SHOULD use `:=` for non-zero values, `var` for zero-value initialization. The form signals intent: `var` means "this starts at zero."
|
||||
|
||||
```go
|
||||
var count int // zero value, set later
|
||||
name := "default" // non-zero, := is appropriate
|
||||
var buf bytes.Buffer // zero value is ready to use
|
||||
```
|
||||
|
||||
### Slice & Map Initialization
|
||||
|
||||
Slices and maps MUST be initialized explicitly, never nil. Nil maps panic on write; nil slices serialize to `null` in JSON (vs `[]` for empty slices), surprising API consumers.
|
||||
|
||||
```go
|
||||
users := []User{} // always initialized
|
||||
m := map[string]int{} // always initialized
|
||||
users := make([]User, 0, len(ids)) // preallocate when capacity is known
|
||||
m := make(map[string]int, len(items)) // preallocate when size is known
|
||||
```
|
||||
|
||||
Do not preallocate speculatively — `make([]T, 0, 1000)` wastes memory when the common case is 10 items.
|
||||
|
||||
### Composite Literals
|
||||
|
||||
Composite literals MUST use field names — positional fields break when the type adds or reorders fields:
|
||||
|
||||
```go
|
||||
srv := &http.Server{
|
||||
Addr: ":8080",
|
||||
ReadTimeout: 5 * time.Second,
|
||||
WriteTimeout: 10 * time.Second,
|
||||
}
|
||||
```
|
||||
|
||||
## Control Flow
|
||||
|
||||
### Reduce Nesting
|
||||
|
||||
Errors and edge cases MUST be handled first (early return). Keep the happy path at minimal indentation:
|
||||
|
||||
```go
|
||||
func process(data []byte) (*Result, error) {
|
||||
if len(data) == 0 {
|
||||
return nil, errors.New("empty data")
|
||||
}
|
||||
|
||||
parsed, err := parse(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parsing: %w", err)
|
||||
}
|
||||
|
||||
return transform(parsed), nil
|
||||
}
|
||||
```
|
||||
|
||||
### Eliminate Unnecessary `else`
|
||||
|
||||
When the `if` body ends with `return`/`break`/`continue`, the `else` MUST be dropped. Use default-then-override for simple assignments — assign a default, then override with independent conditions or a `switch`:
|
||||
|
||||
```go
|
||||
// Good — default-then-override with switch (cleanest for mutually exclusive overrides)
|
||||
level := slog.LevelInfo
|
||||
switch {
|
||||
case debug:
|
||||
level = slog.LevelDebug
|
||||
case verbose:
|
||||
level = slog.LevelWarn
|
||||
}
|
||||
|
||||
// Bad — else-if chain hides that there's a default
|
||||
if debug {
|
||||
level = slog.LevelDebug
|
||||
} else if verbose {
|
||||
level = slog.LevelWarn
|
||||
} else {
|
||||
level = slog.LevelInfo
|
||||
}
|
||||
```
|
||||
|
||||
### Complex Conditions & Init Scope
|
||||
|
||||
When an `if` condition has 3+ operands, MUST extract into named booleans — a wall of `||` is unreadable and hides business logic. Keep expensive checks inline for short-circuit benefit. [Details](./references/details.md)
|
||||
|
||||
```go
|
||||
// Good — named booleans make intent clear
|
||||
isAdmin := user.Role == RoleAdmin
|
||||
isOwner := resource.OwnerID == user.ID
|
||||
isPublicVerified := resource.IsPublic && user.IsVerified
|
||||
if isAdmin || isOwner || isPublicVerified || permissions.Contains(PermOverride) {
|
||||
allow()
|
||||
}
|
||||
```
|
||||
|
||||
Scope variables to `if` blocks when only needed for the check:
|
||||
|
||||
```go
|
||||
if err := validate(input); err != nil {
|
||||
return err
|
||||
}
|
||||
```
|
||||
|
||||
### Switch Over If-Else Chains
|
||||
|
||||
When comparing the same variable multiple times, prefer `switch`:
|
||||
|
||||
```go
|
||||
switch status {
|
||||
case StatusActive:
|
||||
activate()
|
||||
case StatusInactive:
|
||||
deactivate()
|
||||
default:
|
||||
panic(fmt.Sprintf("unexpected status: %d", status))
|
||||
}
|
||||
```
|
||||
|
||||
## Function Design
|
||||
|
||||
- Functions SHOULD be **short and focused** — one function, one job.
|
||||
- Functions SHOULD have **≤4 parameters**. Beyond that, use an options struct (see `samber/cc-skills-golang@golang-design-patterns` skill).
|
||||
- **Parameter order**: `context.Context` first, then inputs, then output destinations.
|
||||
- Naked returns help in very short functions (1-3 lines) where return values are obvious, but become confusing when readers must scroll to find what's returned — name returns explicitly in longer functions.
|
||||
|
||||
```go
|
||||
func FetchUser(ctx context.Context, id string) (*User, error)
|
||||
func SendEmail(ctx context.Context, msg EmailMessage) error // grouped into struct
|
||||
```
|
||||
|
||||
### Prefer `range` for Iteration
|
||||
|
||||
SHOULD use `range` over index-based loops. Use `range n` (Go 1.22+) for simple counting.
|
||||
|
||||
```go
|
||||
for _, user := range users {
|
||||
process(user)
|
||||
}
|
||||
```
|
||||
|
||||
## Value vs Pointer Arguments
|
||||
|
||||
Pass small types (`string`, `int`, `bool`, `time.Time`) by value. Use pointers when mutating, for large structs (~128+ bytes), or when nil is meaningful. [Details](./references/details.md)
|
||||
|
||||
## Code Organization Within Files
|
||||
|
||||
- **Group related declarations**: type, constructor, methods together
|
||||
- **Order**: package doc, imports, constants, types, constructors, methods, helpers
|
||||
- **One primary type per file** when it has significant methods
|
||||
- **Blank imports** (`_ "pkg"`) register side effects (init functions). Restricting them to `main` and test packages makes side effects visible at the application root, not hidden in library code
|
||||
- **Dot imports** pollute the namespace and make it impossible to tell where a name comes from — never use in library code
|
||||
- **Unexport aggressively** — you can always export later; unexporting is a breaking change. → See `samber/cc-skills-golang@golang-gopls` skill to unexport safely — its rename updates every call site atomically and refuses the change when lowercasing a method would break interface satisfaction, a breakage grep/sed silently ships.
|
||||
|
||||
## String Handling
|
||||
|
||||
Use `strconv` for simple conversions (faster), `fmt.Sprintf` for complex formatting. Use `%q` in error messages to make string boundaries visible. Use `strings.Builder` for loops, `+` for simple concatenation.
|
||||
|
||||
## Type Conversions
|
||||
|
||||
Prefer explicit, narrow conversions. Use generics over `any` when a concrete type will do:
|
||||
|
||||
```go
|
||||
func Contains[T comparable](slice []T, target T) bool // not []any
|
||||
```
|
||||
|
||||
## Philosophy
|
||||
|
||||
- **"A little copying is better than a little dependency"**
|
||||
- **Use `slices` and `maps` standard packages**; for filter/group-by/chunk, use `github.com/samber/lo`
|
||||
- **"Reflection is never clear"** — avoid `reflect` unless necessary
|
||||
- **Don't abstract prematurely** — extract when the pattern is stable
|
||||
- **Minimize public surface** — every exported name is a commitment
|
||||
|
||||
## Parallelizing Code Style Reviews
|
||||
|
||||
When reviewing code style across a large codebase, use up to 5 parallel sub-agents (via the Agent tool), each targeting an independent style concern (e.g. control flow, function design, variable declarations, string handling, code organization).
|
||||
|
||||
## Enforce with Linters
|
||||
|
||||
Many rules are enforced automatically: `gofmt`, `gofumpt`, `goimports`, `gocritic`, `revive`, `wsl_v5`. → See the `samber/cc-skills-golang@golang-lint` skill.
|
||||
|
||||
## Cross-References
|
||||
|
||||
- → See the `samber/cc-skills-golang@golang-naming` skill for identifier naming conventions
|
||||
- → See the `samber/cc-skills-golang@golang-structs-interfaces` skill for pointer vs value receivers, interface design
|
||||
- → See the `samber/cc-skills-golang@golang-design-patterns` skill for functional options, builders, constructors
|
||||
- → See the `samber/cc-skills-golang@golang-lint` skill for automated formatting enforcement
|
||||
- → See `samber/cc-skills-golang@golang-continuous-integration` skill for automated AI-driven code review in CI using these guidelines
|
||||
- → See `samber/cc-skills-golang@golang-refactoring` skill for mechanically applying guard-clause conversion, function extraction, and options-struct migration safely across many call sites once a review surfaces violations at scale
|
||||
@@ -0,0 +1,570 @@
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"name": "zero-value-intent-signal",
|
||||
"description": "var vs := signals intent: var for zero-value start, := for non-zero — even when the zero value IS the business default",
|
||||
"prompt": "Write a Go file `session.go` in package `session`. Create a Session struct with fields: userID string, requestCount int, isAuthenticated bool, lastError error, startedAt time.Time, tags []string. Add a constructor NewSession(userID string) that initializes the struct. In the constructor, requestCount starts at zero (it will be incremented on each use), isAuthenticated starts false (it must be explicitly set after login), lastError starts nil, startedAt is set to time.Now(), and tags is initialized as an empty slice. Also add a local variable inside a method Describe() that builds a description string from a fixed prefix 'session:'.",
|
||||
"trap": "Model uses := for all fields including zero-value ones (requestCount := 0, isAuthenticated := false) or uses var for non-zero assignments like startedAt, obscuring intent",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "1.1",
|
||||
"text": "requestCount is NOT explicitly initialized to 0 in the constructor — the zero value is relied upon via var or struct literal without that field, not via requestCount := 0"
|
||||
},
|
||||
{
|
||||
"id": "1.2",
|
||||
"text": "startedAt uses := assignment (startedAt := time.Now() or field assignment) — NOT var startedAt time.Time followed by assignment — because it has a non-zero meaningful value"
|
||||
},
|
||||
{
|
||||
"id": "1.3",
|
||||
"text": "The fixed prefix string variable in Describe() uses := (prefix := 'session:') — not var prefix string = 'session:'"
|
||||
},
|
||||
{
|
||||
"id": "1.4",
|
||||
"text": "tags is initialized with []string{} or make([]string, 0) — never nil — because nil slices serialize to null in JSON"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"name": "empty-slice-map-not-nil",
|
||||
"description": "Empty collections initialized as []T{} or make(), never nil",
|
||||
"prompt": "Write a Go file `handler.go` in package `api`. Create a Handler struct. Add a method ListUsers that returns a slice of User structs (define User with Name and Email fields). Add a method GetTags that returns a map[string]string. Both methods should return empty collections when there's no data. Add a method BuildResponse that takes a slice of results and a map of metadata and processes them.",
|
||||
"trap": "Model returns nil slices/maps or uses uninitialized var declarations for empty collections, causing nil != empty issues in JSON serialization and caller code",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "2.1",
|
||||
"text": "Empty slice return uses []User{} or make([]User, 0) — never returns nil or an uninitialized var declaration without assignment"
|
||||
},
|
||||
{
|
||||
"id": "2.2",
|
||||
"text": "Empty map return uses map[string]string{} or make(map[string]string) — never returns nil or an uninitialized var declaration without assignment"
|
||||
},
|
||||
{
|
||||
"id": "2.3",
|
||||
"text": "When capacity is known (e.g., from len(input)), make() with capacity hint is used for preallocating slices or maps"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"name": "named-struct-fields-nested",
|
||||
"description": "All struct literals use named fields, including nested and anonymous structs",
|
||||
"prompt": "Write a Go file `middleware.go` in package `middleware`. Create a RateLimiter struct with fields: windowSize time.Duration, maxRequests int, perIP bool. Create a middleware chain config using a struct literal with nested structs: a TimeoutConfig containing duration and errorMessage, a RetryConfig containing maxAttempts int and backoff time.Duration, and a CircuitBreakerConfig containing threshold float64 and resetAfter time.Duration. Instantiate each of these structs as part of a larger MiddlewareConfig struct. Also create a tls.Config with MinVersion and a list of cipher suites.",
|
||||
"trap": "Model uses positional struct literals for the nested configs since they have few fields — e.g., TimeoutConfig{5*time.Second, 'timeout'} — which silently breaks when fields are reordered",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "3.1",
|
||||
"text": "RateLimiter literal uses named fields (WindowSize:, MaxRequests:, PerIP:) — not positional"
|
||||
},
|
||||
{
|
||||
"id": "3.2",
|
||||
"text": "TimeoutConfig, RetryConfig, and CircuitBreakerConfig literals all use named fields — not positional — even though each has only 2-3 fields"
|
||||
},
|
||||
{
|
||||
"id": "3.3",
|
||||
"text": "tls.Config literal uses named fields (MinVersion:, CipherSuites:)"
|
||||
},
|
||||
{
|
||||
"id": "3.4",
|
||||
"text": "No struct literal in the file uses positional field syntax"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"name": "early-return-not-nested",
|
||||
"description": "Validation uses early returns; happy path at minimal indentation despite prompt asking for nesting",
|
||||
"prompt": "Write a Go function ProcessOrder in package `orders` that takes an order struct (define it with fields: ID string, Items []Item, Status string, CustomerID string). The function should validate that the ID is not empty, that there is at least one item, that the status is 'pending', that the customer exists (simulate with a lookup function), compute the total price, apply a discount if total > 100, and return the final total with an error. Write it with deeply nested if-else blocks.",
|
||||
"trap": "Model follows the prompt's instruction to use deeply nested if-else blocks, burying the happy path inside 4+ levels of indentation",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "4.1",
|
||||
"text": "Validation checks (empty ID, no items, wrong status) use early return pattern — each check returns an error immediately rather than nesting the rest of the function inside an else block"
|
||||
},
|
||||
{
|
||||
"id": "4.2",
|
||||
"text": "The happy path (compute total, apply discount, return) is at the top level of the function body (indentation level 1), not nested inside multiple if blocks"
|
||||
},
|
||||
{
|
||||
"id": "4.3",
|
||||
"text": "The function has at most 2 levels of indentation for the main logic (excluding the error-check if blocks which return early)"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"name": "no-else-after-return",
|
||||
"description": "No else after return; default-then-override for simple assignments",
|
||||
"prompt": "Write a Go function GetUserRole in package `auth` that takes a user struct with IsAdmin bool, IsModerator bool, and IsVerified bool fields. Return a role string: if admin return 'admin', else if moderator return 'moderator', else if verified return 'member', else return 'guest'. Also write a function SetLogLevel that takes a verbose bool and a debug bool, and sets the log level appropriately using slog.",
|
||||
"trap": "Model uses else-if chains after return statements, adding unnecessary indentation and cognitive load",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "5.1",
|
||||
"text": "GetUserRole does NOT use else or else-if after a return statement — either uses early returns (if isAdmin { return 'admin' }; if isModerator { return 'moderator' }) or a switch statement"
|
||||
},
|
||||
{
|
||||
"id": "5.2",
|
||||
"text": "SetLogLevel uses the default-then-override pattern: assigns a default level first, then conditionally overrides with if (not if-else chains)"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"name": "switch-over-if-else-chain",
|
||||
"description": "Multi-branch comparisons use switch statements, not if-else chains",
|
||||
"prompt": "Write a Go function HandleEvent in package `events` that takes an event with a Type string field. The type can be 'click', 'scroll', 'keypress', 'hover', 'focus', or 'blur'. Each type should call a different handler function. Also write a function MapStatusCode that takes an int HTTP status code and returns a human-readable string for 200, 201, 204, 400, 401, 403, 404, 500, 502, 503.",
|
||||
"trap": "Model uses if-else chains for multi-branch string/int comparisons instead of switch statements",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "6.1",
|
||||
"text": "HandleEvent uses a switch statement on event.Type, not an if-else chain"
|
||||
},
|
||||
{
|
||||
"id": "6.2",
|
||||
"text": "MapStatusCode uses a switch statement on the status code, not an if-else chain"
|
||||
},
|
||||
{
|
||||
"id": "6.3",
|
||||
"text": "Both switch statements include a default case"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"name": "options-struct-not-many-params",
|
||||
"description": "Groups params into options struct, context.Context first",
|
||||
"prompt": "Write a Go function SendNotification in package `notify` that sends a notification. It needs these parameters: ctx context.Context, userID string, message string, channel string (email/sms/push), priority int, retryCount int, dryRun bool, templateID string, metadata map[string]string, callback func(error). Put all parameters directly in the function signature.",
|
||||
"trap": "Model follows the prompt's instruction to put all 10 parameters directly in the function signature, creating an unusable API",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "7.1",
|
||||
"text": "context.Context is the first parameter in the function signature"
|
||||
},
|
||||
{
|
||||
"id": "7.2",
|
||||
"text": "The function uses an options struct (or similar grouping) to reduce the parameter count to 4 or fewer in the main function signature — not all 10 parameters listed individually"
|
||||
},
|
||||
{
|
||||
"id": "7.3",
|
||||
"text": "The options struct groups related configuration (channel, priority, retryCount, dryRun, templateID, metadata, callback) into a single parameter"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"name": "value-vs-pointer-params",
|
||||
"description": "Value params for small types; pointers only for mutation — not pointer everything",
|
||||
"prompt": "Write Go functions in package `users`: (1) FormatName that takes a first name string and last name string and returns the formatted full name, (2) UpdateAge that modifies a User struct's age field, (3) FindUser that takes a user ID string and returns a User pointer, (4) CompareUsers that checks if two User structs (each about 32 bytes with Name string and Age int) are equal. Use pointer parameters for all functions.",
|
||||
"trap": "Model follows the prompt's instruction to use pointer parameters for all functions, including small value types like string and int where pointers only add indirection",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "8.1",
|
||||
"text": "FormatName takes string parameters by value (not *string) — strings are small fixed-size types"
|
||||
},
|
||||
{
|
||||
"id": "8.2",
|
||||
"text": "UpdateAge takes a *User pointer parameter because it mutates the struct"
|
||||
},
|
||||
{
|
||||
"id": "8.3",
|
||||
"text": "CompareUsers takes User structs by value (not *User) because it only reads them and they are small (<128 bytes)"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"name": "unexported-internal-helpers",
|
||||
"description": "Helper functions called only within the same package stay unexported; exporting is a commitment",
|
||||
"prompt": "Write a Go file `parser.go` in package `config`. Include: an exported ParseConfig function that reads a file path and returns a *Config struct; an exported ValidateConfig function that checks required fields; a helper function that tokenizes a raw config string (used only by ParseConfig); a helper function that resolves environment variable references in values (used by ParseConfig and ValidateConfig); a helper function that formats a field path for error messages (used only in error messages inside ValidateConfig). Make all functions exported for potential future reuse from other packages.",
|
||||
"trap": "Model follows the prompt's instruction to export all functions, leaking tokenizer, env resolver, and error formatter as public API — any future change to them becomes a breaking change",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "9.1",
|
||||
"text": "The tokenizer helper (used only by ParseConfig) is unexported (lowercase name)"
|
||||
},
|
||||
{
|
||||
"id": "9.2",
|
||||
"text": "The error message formatter (used only inside ValidateConfig) is unexported (lowercase name)"
|
||||
},
|
||||
{
|
||||
"id": "9.3",
|
||||
"text": "ParseConfig and ValidateConfig remain exported — they are the true public API"
|
||||
},
|
||||
{
|
||||
"id": "9.4",
|
||||
"text": "The env variable resolver may be exported OR unexported — both are defensible since it's used by two functions, but the model should NOT export all helpers blindly"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"name": "strings-join-not-builder-for-known-slice",
|
||||
"description": "strings.Join for joining a known slice; strings.Builder for dynamic/loop accumulation — not one-size-fits-all",
|
||||
"prompt": "Write a Go file `format.go` in package `format` with four functions: (1) JoinTags that takes a []string of tags and returns them comma-separated, (2) BuildCSVRow that takes a []string of fields and returns a CSV line with quotes and commas, (3) BuildAuditLog that takes a slice of AuditEntry structs (each with timestamp and message fields) and returns a multi-line string by iterating over entries, (4) FormatError that takes an error code int and a description string and returns a formatted error string like 'ERR-42: bad input'.",
|
||||
"trap": "Model uses strings.Builder for everything including JoinTags (which should use strings.Join) and fmt.Sprintf for the int conversion in FormatError instead of strconv",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "10.1",
|
||||
"text": "JoinTags uses strings.Join(tags, ',') — not a manual loop or strings.Builder — because the input is already a complete slice"
|
||||
},
|
||||
{
|
||||
"id": "10.2",
|
||||
"text": "BuildAuditLog uses strings.Builder (WriteString in a loop) — not repeated += — because entries are accumulated one at a time in a loop"
|
||||
},
|
||||
{
|
||||
"id": "10.3",
|
||||
"text": "FormatError uses fmt.Sprintf (or strconv.Itoa for the int part) — NOT strings.Builder — because it formats a short fixed-structure message"
|
||||
},
|
||||
{
|
||||
"id": "10.4",
|
||||
"text": "No function uses += string concatenation inside a loop body"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"name": "named-boolean-conditions-method-calls",
|
||||
"description": "Expensive method calls in complex conditions extracted to named booleans to make intent readable",
|
||||
"prompt": "Write a Go function CanPublish in package `cms` that determines whether a user can publish an article. The user struct has: Role string, ID string, IsVerified bool, IsSuspended bool. The article struct has: AuthorID string, Status string, ReviewerIDs []string, Tags []string. The permission check requires: (user.Role == 'editor' || user.Role == 'admin') AND NOT user.IsSuspended AND user.IsVerified AND (user.ID == article.AuthorID || contains(article.ReviewerIDs, user.ID)) AND article.Status == 'reviewed' AND NOT contains(article.Tags, 'restricted'). Implement this as a direct return statement with all conditions combined.",
|
||||
"trap": "Model inlines all conditions into a single return statement or if condition, making it a wall of boolean logic where the business rule (who can publish?) is buried in implementation details",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "11.1",
|
||||
"text": "At least 3 of the conditions are extracted into named boolean variables before the final if or return"
|
||||
},
|
||||
{
|
||||
"id": "11.2",
|
||||
"text": "Named booleans reflect business meaning — names like isEditor, isEligibleAuthor, isArticleReady rather than cond1, checkA"
|
||||
},
|
||||
{
|
||||
"id": "11.3",
|
||||
"text": "The final expression reads like a policy statement: return isEligibleUser && isAuthorOrReviewer && isArticleReady (or similar)"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"name": "line-breaks-at-semantic-boundaries",
|
||||
"description": "Function calls with 4+ arguments broken at argument boundaries; no line over ~120 chars",
|
||||
"prompt": "Write a Go function RegisterRoutes in package `router` that takes an *http.ServeMux and registers 6 API routes. Each route handler is a closure that delegates to a processRequest function taking: an http.ResponseWriter, an *http.Request, a serviceName string constant 'com.example.platform.api', a *Config, a *slog.Logger, and an authMiddleware func. Write idiomatic Go.",
|
||||
"trap": "Model writes each mux.HandleFunc and inner processRequest call as a single long line since that is the most compact and natural first draft",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "12.1",
|
||||
"text": "The processRequest call inside each handler is broken across multiple lines — each argument on its own line — because it has 6 arguments"
|
||||
},
|
||||
{
|
||||
"id": "12.2",
|
||||
"text": "Line breaks occur at semantic boundaries (after commas between arguments) — not at arbitrary column positions mid-expression"
|
||||
},
|
||||
{
|
||||
"id": "12.3",
|
||||
"text": "Closing parentheses for multi-line function calls appear on their own line (Go trailing-comma style)"
|
||||
},
|
||||
{
|
||||
"id": "12.4",
|
||||
"text": "No single line in the file exceeds approximately 140 characters"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 13,
|
||||
"name": "never-nil-return-for-collection",
|
||||
"description": "Returns initialized empty collections even when no data — nil slices serialize to JSON null; nil maps panic on write",
|
||||
"prompt": "Write a Go HTTP handler ListProducts in package `api` that queries a database for products matching a filter and returns JSON. Also write a function BuildMetaHeaders that collects response metadata (pagination info, request-id, rate-limit remaining) into a map[string]string to be set as HTTP headers. Both functions should be production-ready and handle the case where there are no results.",
|
||||
"trap": "When no products are found, the model returns a nil slice (var result []Product or return nil) which serializes to JSON null instead of []; for the map, the model may return nil which panics if the caller writes a key",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "13.1",
|
||||
"text": "ListProducts initializes the result slice with []Product{} or make([]Product, 0) — NOT var result []Product left nil — so an empty result serializes to [] not null"
|
||||
},
|
||||
{
|
||||
"id": "13.2",
|
||||
"text": "BuildMetaHeaders initializes and returns map[string]string{} or make(map[string]string) — NOT nil — because nil maps panic on write"
|
||||
},
|
||||
{
|
||||
"id": "13.3",
|
||||
"text": "Neither function contains 'return nil' as a success/no-data path (nil is only paired with a non-nil error)"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 14,
|
||||
"name": "strconv-and-builder-natural-scenario",
|
||||
"description": "strconv.Itoa for int-to-string; strings.Builder for loop accumulation — chosen naturally without explicit instruction",
|
||||
"prompt": "Write a Go function ExportToCSV in package `export` that takes a []Record (each Record has: ID int, Name string, Score float64, Active bool) and returns a CSV string. The first line should be the header. Each subsequent line is a row. ID must be converted to a string for the CSV. Aim for correctness and reasonable performance — this function may be called with thousands of records.",
|
||||
"trap": "Model converts ID with fmt.Sprintf('%d', r.ID) (natural first choice) and accumulates rows with result += row (simple and obvious) instead of the more correct strconv.Itoa and strings.Builder",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "14.1",
|
||||
"text": "ID integer-to-string conversion uses strconv.Itoa(r.ID) or strconv.FormatInt — NOT fmt.Sprintf('%d', r.ID)"
|
||||
},
|
||||
{
|
||||
"id": "14.2",
|
||||
"text": "Row accumulation uses strings.Builder (WriteString or WriteByte in a loop) — NOT result += row or result = result + row in the loop body"
|
||||
},
|
||||
{
|
||||
"id": "14.3",
|
||||
"text": "strings.Builder is declared once before the loop and .String() is called after the loop to produce the final output"
|
||||
},
|
||||
{
|
||||
"id": "14.4",
|
||||
"text": "The function does NOT contain '+=' applied to a string variable inside a loop body"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 15,
|
||||
"name": "named-fields-override-positional-prompt",
|
||||
"description": "Uses named struct fields even when prompt explicitly requests positional syntax",
|
||||
"prompt": "Write Go structs in package `config` using positional field syntax for brevity. Create: Point{float64, float64}, Color{uint8, uint8, uint8, uint8}, and ServerConfig{string, int, bool, time.Duration, time.Duration, *tls.Config}. Positional syntax is shorter and the field order is obvious from the type definition.",
|
||||
"trap": "Model follows the prompt's positional syntax instruction, creating brittle literals that silently break when struct fields are added or reordered",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "15.1",
|
||||
"text": "Point literal uses named fields (X:, Y: or similar) — NOT Point{1.0, 2.0}"
|
||||
},
|
||||
{
|
||||
"id": "15.2",
|
||||
"text": "Color literal uses named fields (R:, G:, B:, A: or similar) — NOT Color{255, 128, 0, 255}"
|
||||
},
|
||||
{
|
||||
"id": "15.3",
|
||||
"text": "ServerConfig literal uses named fields — NOT positional — because positional breaks when fields are added or reordered"
|
||||
},
|
||||
{
|
||||
"id": "15.4",
|
||||
"text": "No struct literal in the file uses positional field syntax"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 16,
|
||||
"name": "early-return-override-nested-prompt",
|
||||
"description": "Uses early returns despite prompt explicitly requesting nested if-else validation pattern",
|
||||
"prompt": "Write a Go function ValidateAndProcess in package `pipeline` that validates an input struct (check: non-empty Name, Age > 0, valid Email containing '@', Status is 'active' or 'pending', non-nil Permissions slice, at least one Permission). If all validations pass, compute a score, apply modifiers, and return the result. Use the traditional if-else pattern: if valid { if next_valid { if next { ... } else { error } } else { error } } else { error }. This makes the success path clear by keeping it inside the innermost block.",
|
||||
"trap": "Model follows the prompt's explicit nested if-else pattern, nesting the success path 5+ levels deep",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "16.1",
|
||||
"text": "Each validation check uses early return — if Name empty return error, if Age <= 0 return error, etc."
|
||||
},
|
||||
{
|
||||
"id": "16.2",
|
||||
"text": "The function does NOT contain nested if-else blocks for validation (no else clause after a validation if)"
|
||||
},
|
||||
{
|
||||
"id": "16.3",
|
||||
"text": "The happy path (score computation) is at indentation level 1, not nested inside 5+ levels"
|
||||
},
|
||||
{
|
||||
"id": "16.4",
|
||||
"text": "Maximum indentation depth for the main logic is 2 (function body + one loop or if)"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 17,
|
||||
"name": "context-first-options-struct",
|
||||
"description": "context.Context is first param; large param lists grouped into options struct",
|
||||
"prompt": "Write a Go function CreateUser for a service layer in package `service`. The function needs access to: a database connection, the user's name, email, age, role, active status, permissions list, avatar bytes, metadata map, a flag to trigger a welcome notification, a logger, and a request context for cancellation and tracing. Implement this function with all inputs needed for the operation.",
|
||||
"trap": "Model puts context.Context last or in the middle (as it might appear in a method converted from another pattern), and lists all parameters individually without grouping — the natural draft mirrors the bullet list order in the prompt",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "17.1",
|
||||
"text": "context.Context is the FIRST parameter in the function signature"
|
||||
},
|
||||
{
|
||||
"id": "17.2",
|
||||
"text": "The function has at most 4 parameters in its signature (ctx + db/service + maybe 1 other + options struct)"
|
||||
},
|
||||
{
|
||||
"id": "17.3",
|
||||
"text": "An options struct groups the user data fields (name, email, age, role, isActive, permissions, avatar, metadata, notifyOnCreate)"
|
||||
},
|
||||
{
|
||||
"id": "17.4",
|
||||
"text": "The logger is either in the options struct or a field on a Service receiver — NOT a standalone function parameter alongside ctx"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 18,
|
||||
"name": "pointer-judgment-mixed-types",
|
||||
"description": "Pointer vs value judgment for a mixed set of types — small value types by value, large structs and optional values by pointer",
|
||||
"prompt": "Write Go function signatures in package `inventory` for: (1) ComputeDiscount that takes a price float64 and a discount rate float64 and returns the discounted price, (2) UpdateInventoryItem that modifies an InventoryItem struct (define it with ~10 fields: ID, SKU, Name, Description, Price, Stock, Weight, Category, Tags, UpdatedAt), (3) FindByCategory that takes a category string and returns matching items, (4) MergeConfig that takes two Config structs (small, 3 fields: Timeout time.Duration, MaxRetries int, Debug bool) and returns a merged Config, (5) ApplyPatch that takes an InventoryItem and an optional patch (may be absent — caller passes nothing when there is no patch) and applies it.",
|
||||
"trap": "Model uses value receivers for UpdateInventoryItem (mutation without pointer), passes the large InventoryItem by value in ApplyPatch, or uses *float64 for ComputeDiscount parameters",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "18.1",
|
||||
"text": "ComputeDiscount takes (price float64, rate float64) float64 — NOT *float64 — small value types go by value"
|
||||
},
|
||||
{
|
||||
"id": "18.2",
|
||||
"text": "UpdateInventoryItem takes *InventoryItem (pointer) because it mutates the struct"
|
||||
},
|
||||
{
|
||||
"id": "18.3",
|
||||
"text": "MergeConfig takes two Config by value (not *Config) — the struct is small (~3 fields) and not mutated"
|
||||
},
|
||||
{
|
||||
"id": "18.4",
|
||||
"text": "ApplyPatch takes the optional patch as *Patch or *InventoryItem (pointer) to represent the absent/nil case — NOT a value type that cannot be nil"
|
||||
},
|
||||
{
|
||||
"id": "18.5",
|
||||
"text": "FindByCategory takes category string by value — NOT *string"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 19,
|
||||
"name": "named-conditions-override-inline-prompt",
|
||||
"description": "Extracts complex conditions to named booleans despite prompt explicitly saying NOT to",
|
||||
"prompt": "Write a Go function AssignPermission in package `rbac` that determines a user's effective permission level. Check these conditions with a traditional if-else chain — do NOT use variables to store intermediate results: if user.Role == 'superadmin' && !user.IsSuspended, or if user.Role == 'admin' && user.Department == resource.Department && user.TenantID == resource.TenantID, or if resource.IsPublic && user.IsVerified && !user.IsRestricted, or if user.Groups.Contains(resource.RequiredGroup) && user.MFA.IsEnabled() && time.Since(user.MFA.LastVerified) < 24*time.Hour, or if resource.ACL.HasEntry(user.ID) && resource.ACL.GetPermission(user.ID).Level >= MinReadLevel. Return the matching permission level or ErrAccessDenied.",
|
||||
"trap": "Model follows the prompt's explicit instruction NOT to use intermediate variables, inlining all complex conditions into the if-else chain",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "19.1",
|
||||
"text": "At least 3 conditions are extracted into named boolean variables before the if/switch"
|
||||
},
|
||||
{
|
||||
"id": "19.2",
|
||||
"text": "Named booleans have domain-meaningful names (e.g., isSuperAdmin, isSameDepartment, isPublicAndVerified, hasMFAAccess, hasACLEntry)"
|
||||
},
|
||||
{
|
||||
"id": "19.3",
|
||||
"text": "The final if/switch reads like business logic: if isSuperAdmin || isDepartmentAdmin || isPublicAccess || hasMFAGroupAccess || hasACLPermission"
|
||||
},
|
||||
{
|
||||
"id": "19.4",
|
||||
"text": "The most expensive checks (Groups.Contains + MFA, ACL.HasEntry + GetPermission) are either kept inline for short-circuit or extracted last"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 20,
|
||||
"name": "line-breaks-override-compact-prompt",
|
||||
"description": "Breaks long lines despite prompt requesting single-line compact code",
|
||||
"prompt": "Write a Go function SetupHandlers in package `api` that registers 8 REST endpoint handlers on an http.ServeMux. Each handler closure calls processRequest with: the http.ResponseWriter, *http.Request, the service name \"com.example.platform.microservices.user-management.api.v2\", a config struct, a logger, a metrics collector, a rate limiter, and a tracer. Write compact code — each mux.HandleFunc call should be on a single line for easy scanning.",
|
||||
"trap": "Model follows the prompt's compact single-line instruction, creating 200+ character lines that are unreadable in diffs and editors",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "20.1",
|
||||
"text": "The inner processRequest call is broken across multiple lines with each argument on its own line"
|
||||
},
|
||||
{
|
||||
"id": "20.2",
|
||||
"text": "No single line in the file exceeds ~140 characters"
|
||||
},
|
||||
{
|
||||
"id": "20.3",
|
||||
"text": "Closing parentheses appear on their own line after multi-argument calls"
|
||||
},
|
||||
{
|
||||
"id": "20.4",
|
||||
"text": "The service name string is extracted to a constant or variable, not repeated inline 8 times"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 21,
|
||||
"name": "switch-override-else-prompt",
|
||||
"description": "Uses switch or early returns despite prompt explicitly requiring else after every if",
|
||||
"prompt": "Write a Go function GetPricingTier in package `billing` that takes a customer struct with fields: plan string, monthlySpend float64, isEnterprise bool, hasCustomContract bool, employeeCount int, region string. Return the pricing tier string. Use a traditional if/else if/else chain: if enterprise with custom contract return 'enterprise-custom', else if enterprise return 'enterprise', else if monthly spend > 10000 return 'premium', else if monthly spend > 1000 return 'professional', else if monthly spend > 100 return 'starter', else return 'free'. Make sure to use else after every if.",
|
||||
"trap": "Model follows the prompt's explicit instruction to use else after every if, creating an if-else chain instead of cleaner switch or early returns",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "21.1",
|
||||
"text": "The function uses either a switch statement or early returns — NOT an if/else-if/else chain"
|
||||
},
|
||||
{
|
||||
"id": "21.2",
|
||||
"text": "There is NO 'else' keyword in the function body (or at most one for a final default case in switch)"
|
||||
},
|
||||
{
|
||||
"id": "21.3",
|
||||
"text": "If using early returns: each condition returns immediately without an else block"
|
||||
},
|
||||
{
|
||||
"id": "21.4",
|
||||
"text": "If using switch: uses tagless switch (switch { case ... }) for the multi-condition comparison"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 22,
|
||||
"name": "minimal-exports",
|
||||
"description": "Internal helpers unexported; only the true public API is exported",
|
||||
"prompt": "Write a Go file `helpers.go` in package `httputil`. Export everything for maximum reusability across packages. Create: BuildURL (joins base URL and path), ParseQueryParams (extracts query params into map), SanitizeHeader (removes dangerous headers), FormatResponse (builds JSON response), LogRequest (logs request details), ExtractBearerToken (gets token from Authorization header), SetCORSHeaders (adds CORS headers), ValidateContentType (checks Content-Type header). Make all functions exported and all helper types exported too.",
|
||||
"trap": "Model follows the prompt's instruction to export everything, leaking internal helpers into the package API and coupling consumers to implementation details",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "22.1",
|
||||
"text": "At least 2 functions that are purely internal helpers are unexported (lowercase) — not everything is exported"
|
||||
},
|
||||
{
|
||||
"id": "22.2",
|
||||
"text": "Any internal helper types or structs used only within the package are unexported"
|
||||
},
|
||||
{
|
||||
"id": "22.3",
|
||||
"text": "The truly public API functions (BuildURL, ParseQueryParams, etc.) remain exported"
|
||||
},
|
||||
{
|
||||
"id": "22.4",
|
||||
"text": "No function that is only called by other functions in the same file is exported unnecessarily"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 23,
|
||||
"name": "capacity-hint-from-input-size",
|
||||
"description": "When filtering or transforming a slice, use len(input) as capacity hint — output is at most that size",
|
||||
"prompt": "Write a Go function FilterActiveUsers in package `users` that takes a []User slice and returns only the users where IsActive is true. Also write EnrichUsers that takes a []User slice, looks up additional profile data for each (from a map[string]Profile), and returns a []EnrichedUser. Write both functions efficiently.",
|
||||
"trap": "Model uses make([]User, 0) with no capacity hint (misses the obvious upper bound) or uses make([]User, len(users)) with length instead of capacity (creating a slice with len zero-valued elements prepended)",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "23.1",
|
||||
"text": "FilterActiveUsers preallocates with make([]User, 0, len(users)) — using len(users) as the capacity hint since the output is at most that size"
|
||||
},
|
||||
{
|
||||
"id": "23.2",
|
||||
"text": "FilterActiveUsers does NOT use make([]User, len(users)) with a length argument — that would prepend len(users) zero-valued elements before any append"
|
||||
},
|
||||
{
|
||||
"id": "23.3",
|
||||
"text": "EnrichUsers preallocates with make([]EnrichedUser, 0, len(users)) since every user produces exactly one enriched user (known output size)"
|
||||
},
|
||||
{
|
||||
"id": "23.4",
|
||||
"text": "Neither function uses a speculative large constant (e.g., 1000) as capacity when len(input) is available"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 24,
|
||||
"name": "early-continue-not-nesting",
|
||||
"description": "Loop validation failures use continue; happy path at shallowest indentation",
|
||||
"prompt": "Write a Go function TransformData in package `etl` that takes a slice of RawRecord structs (each ~200 bytes with many string fields). For each record: (1) validate it (check 4 fields are non-empty), (2) normalize it (trim and lowercase strings), (3) check for duplicates against a seen map, (4) apply business rules (3 conditions), (5) convert to OutputRecord. Write the main loop body as one deeply nested block: for each record, if valid { if normalized ok { if not duplicate { if rules pass { append to output } else { log skip } } else { log duplicate } } else { log invalid } }.",
|
||||
"trap": "Model follows the prompt's deeply nested loop body pattern, burying the happy path inside 4+ levels of indentation",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "24.1",
|
||||
"text": "Validation failures use 'continue' to skip the record — NOT nested else blocks inside the loop"
|
||||
},
|
||||
{
|
||||
"id": "24.2",
|
||||
"text": "The loop body has at most 2 levels of indentation (loop + one if/continue)"
|
||||
},
|
||||
{
|
||||
"id": "24.3",
|
||||
"text": "At least one helper function is extracted (e.g., validate, normalize, or applyRules) to keep the loop body short"
|
||||
},
|
||||
{
|
||||
"id": "24.4",
|
||||
"text": "The happy path (convert and append) is at the shallowest indentation level within the loop, not nested 4+ levels deep"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,75 @@
|
||||
# Code Style Details
|
||||
|
||||
## Extract Complex Conditions
|
||||
|
||||
When `if` conditions span multiple operands, extract into named booleans:
|
||||
|
||||
```go
|
||||
// Good — self-documenting
|
||||
isAdmin := user.Role == RoleAdmin
|
||||
isOwner := resource.OwnerID == user.ID
|
||||
hasOverride := permissions.Contains(PermOverride)
|
||||
if isAdmin || isOwner || hasOverride {
|
||||
allow()
|
||||
}
|
||||
|
||||
// Bad — wall of logic
|
||||
if user.Role == RoleAdmin || resource.OwnerID == user.ID || permissions.Contains(PermOverride) {
|
||||
allow()
|
||||
}
|
||||
```
|
||||
|
||||
**Exception:** When the last condition involves expensive processing, keep it inline to benefit from short-circuit evaluation:
|
||||
|
||||
```go
|
||||
// Good — avoid expensive operation when possible
|
||||
if isAdmin || isOwner || expensivePermissionCheck(user, resource) {
|
||||
allow()
|
||||
}
|
||||
|
||||
// Wasteful — always runs expensive check
|
||||
canOverride := expensivePermissionCheck(user, resource)
|
||||
if isAdmin || isOwner || canOverride {
|
||||
allow()
|
||||
}
|
||||
```
|
||||
|
||||
## Value vs Pointer Arguments
|
||||
|
||||
This covers **function parameters**, not method receivers (see `samber/cc-skills-golang@golang-structs-interfaces` skill for receiver rules).
|
||||
|
||||
Pass small, fixed-size types by value — strings are already a (pointer, length) pair internally:
|
||||
|
||||
```go
|
||||
// Good — value types by value
|
||||
func FormatUser(name string, age int, createdAt time.Time) string
|
||||
|
||||
// Good — pointer for mutation
|
||||
func PopulateDefaults(cfg *Config)
|
||||
|
||||
// Good — pointer when nil is meaningful (optional field update)
|
||||
func UpdateUser(ctx context.Context, id string, name *string) error
|
||||
|
||||
// Bad — pointer for no reason
|
||||
func Greet(name *string) string
|
||||
```
|
||||
|
||||
**When to use pointers**:
|
||||
|
||||
- The function **mutates** the value
|
||||
- The struct is **large** (~128+ bytes) — avoids copying overhead
|
||||
- **Nil is meaningful** (optional/nullable parameter)
|
||||
|
||||
**When NOT to use pointers**:
|
||||
|
||||
- `string`, `int`, `bool`, `float64`, `time.Time` — pass by value
|
||||
- Read-only access to small structs — pass by value (better cache locality)
|
||||
- "Just to save memory" — value copy is negligible; stack allocation is fast
|
||||
|
||||
**Memory access trade-offs when strong performance is required**:
|
||||
|
||||
- **Values (no pointer)**: Stack allocation, excellent CPU cache locality for small types, zero indirection cost. Slower only when copying large structs.
|
||||
- **Pointers**: One extra dereference (negligible on modern CPUs), but risk cache misses if pointed-to data isn't in cache. Essential for large structs (>~128 bytes) where copy cost dominates.
|
||||
- **Rule of thumb**: For structs <~128 bytes with read-only access, values are typically faster due to cache locality. For mutation or large structs, pointers win. When in doubt, benchmark.
|
||||
|
||||
-> See the `samber/cc-skills-golang@golang-structs-interfaces` skill for pointer vs value **receiver** rules.
|
||||
@@ -0,0 +1,89 @@
|
||||
---
|
||||
name: golang-error-handling
|
||||
description: "Idiomatic Golang error handling — creation, wrapping with %w, errors.Is/As, errors.Join, custom error types, sentinel errors, panic/recover, the single handling rule, structured logging with slog, HTTP request logging middleware, and samber/oops for production errors. Built to make logs usable at scale with log aggregation 3rd-party tools. Apply when creating, wrapping, inspecting, or logging errors in Go code. For samber/oops specifics → See `samber/cc-skills-golang@golang-samber-oops` skill; for slog handler ecosystem → See `samber/cc-skills-golang@golang-samber-slog` skill."
|
||||
user-invocable: true
|
||||
license: MIT
|
||||
compatibility: Designed for Claude Code or similar AI coding agents, and for projects using Golang.
|
||||
metadata:
|
||||
author: samber
|
||||
version: "1.2.1"
|
||||
openclaw:
|
||||
emoji: "⚠"
|
||||
homepage: https://github.com/samber/cc-skills-golang
|
||||
requires:
|
||||
bins:
|
||||
- go
|
||||
install: []
|
||||
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent
|
||||
---
|
||||
|
||||
**Persona:** You are a Go reliability engineer. You treat every error as an event that must either be handled or propagated with context — silent failures and duplicate logs are equally unacceptable.
|
||||
|
||||
**Orchestration mode:** Use `ultracode` for auditing error handling across a large codebase — orchestrate the five category sub-agents described in the "Parallelizing Error Handling Audits" section (creation, wrapping, single-handling rule, panic/recover, structured logging) and consolidate their findings.
|
||||
|
||||
**Modes:**
|
||||
|
||||
- **Coding mode** — writing new error handling code. Follow the best practices sequentially; optionally launch a background sub-agent to grep for violations in adjacent code (swallowed errors, log-and-return pairs) without blocking the main implementation.
|
||||
- **Review mode** — reviewing a PR's error handling changes. Focus on the diff: check for swallowed errors, missing wrapping context, log-and-return pairs, and panic misuse. Sequential.
|
||||
- **Audit mode** — auditing existing error handling across a codebase. Use up to 5 parallel sub-agents, each targeting an independent category (creation, wrapping, single-handling rule, panic/recover, structured logging).
|
||||
|
||||
> **Community default.** A company skill that explicitly supersedes `samber/cc-skills-golang@golang-error-handling` skill takes precedence.
|
||||
|
||||
# Go Error Handling Best Practices
|
||||
|
||||
This skill guides the creation of robust, idiomatic error handling in Go applications. Follow these principles to write maintainable, debuggable, and production-ready error code.
|
||||
|
||||
## Best Practices Summary
|
||||
|
||||
1. **Returned errors MUST always be checked** — NEVER discard with `_`
|
||||
2. **Errors MUST be wrapped with context** using `fmt.Errorf("{context}: %w", err)`
|
||||
3. **Error strings MUST be lowercase**, without trailing punctuation
|
||||
4. **Use `%w` internally, `%v` at system boundaries** to control error chain exposure
|
||||
5. **MUST use `errors.Is` for sentinel matching and `errors.As`/`errors.AsType` for typed chain inspection** instead of direct comparison or bare type assertions. For Go 1.26+, prefer `errors.AsType[T](err)` when `T` implements `error`; use `errors.As(err, &target)` for Go <1.26 or for non-error interface targets.
|
||||
6. **SHOULD use `errors.Join`** (Go 1.20+) to combine independent errors
|
||||
7. **Errors MUST be either logged OR returned**, NEVER both (single handling rule)
|
||||
8. **Use sentinel errors** for expected conditions, custom types for carrying data
|
||||
9. **NEVER use `panic` for expected error conditions** — reserve for truly unrecoverable states
|
||||
10. **SHOULD use `slog`** (Go 1.21+) for structured error logging — not `fmt.Println` or `log.Printf`
|
||||
11. **Use `samber/oops`** for production errors needing stack traces, user/tenant context, or structured attributes
|
||||
12. **Log HTTP requests** with structured middleware capturing method, path, status, and duration
|
||||
13. **Use log levels** to indicate error severity
|
||||
14. **Never expose technical errors to users** — translate internal errors to user-friendly messages, log technical details separately
|
||||
15. **Keep log grouping low-cardinality** — at logging/APM boundaries, keep message templates stable and attach IDs, paths, line numbers, and counts as structured attributes. Error values may include useful operational context, but avoid putting high-cardinality data into the stable log message used for grouping.
|
||||
|
||||
## Detailed Reference
|
||||
|
||||
- **[Error Creation](./references/error-creation.md)** — How to create errors that tell the story: error messages should be lowercase, no punctuation, and describe what happened without prescribing action. Covers sentinel errors (one-time preallocation for performance), custom error types (for carrying rich context), and the decision table for which to use when.
|
||||
|
||||
- **[Error Wrapping and Inspection](./references/error-wrapping.md)** — Why `fmt.Errorf("{context}: %w", err)` beats `fmt.Errorf("{context}: %v", err)` (chains vs concatenation). How to inspect chains with `errors.Is`, `errors.As`, and Go 1.26+ `errors.AsType` for type-safe error handling, and `errors.Join` for combining independent errors.
|
||||
|
||||
- **[Error Handling Patterns and Logging](./references/error-handling.md)** — The single handling rule: errors are either logged OR returned, NEVER both (prevents duplicate logs cluttering aggregators). Panic/recover design, `samber/oops` for production errors, and `slog` structured logging integration for APM tools.
|
||||
|
||||
## Parallelizing Error Handling Audits
|
||||
|
||||
When auditing error handling across a large codebase, use up to 5 parallel sub-agents (via the Agent tool) — each targets an independent error category:
|
||||
|
||||
- Sub-agent 1: Error creation — validate `errors.New`/`fmt.Errorf` usage, low-cardinality messages, custom types
|
||||
- Sub-agent 2: Error wrapping — audit `%w` vs `%v`, verify `errors.Is`/`errors.As` patterns
|
||||
- Sub-agent 3: Single handling rule — find log-and-return violations, swallowed errors, discarded errors (`_`)
|
||||
- Sub-agent 4: Panic/recover — audit `panic` usage, verify recovery at goroutine boundaries
|
||||
- Sub-agent 5: Structured logging — verify `slog` usage at error sites, check for PII in error messages
|
||||
|
||||
## Cross-References
|
||||
|
||||
- → See `samber/cc-skills-golang@golang-samber-oops` for full samber/oops API, builder patterns, and logger integration
|
||||
- → See `samber/cc-skills-golang@golang-observability` for structured logging setup, log levels, and request logging middleware
|
||||
- → See `samber/cc-skills-golang@golang-safety` for nil interface trap and nil error comparison pitfalls
|
||||
- → See `samber/cc-skills-golang@golang-naming` for error naming conventions (ErrNotFound, PathError)
|
||||
- → See `samber/cc-skills-golang@golang-continuous-integration` skill for automated AI-driven code review in CI using these guidelines
|
||||
|
||||
## References
|
||||
|
||||
- [lmittmann/tint](https://github.com/lmittmann/tint)
|
||||
- [samber/oops](https://github.com/samber/oops)
|
||||
- [samber/slog-multi](https://github.com/samber/slog-multi)
|
||||
- [samber/slog-sampling](https://github.com/samber/slog-sampling)
|
||||
- [samber/slog-formatter](https://github.com/samber/slog-formatter)
|
||||
- [samber/slog-http](https://github.com/samber/slog-http)
|
||||
- [samber/slog-sentry](https://github.com/samber/slog-sentry)
|
||||
- [log/slog package](https://pkg.go.dev/log/slog)
|
||||
@@ -0,0 +1,161 @@
|
||||
{
|
||||
"skill_name": "golang-error-handling",
|
||||
"evals": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "middleware-log-chain",
|
||||
"prompt": "Write a Go HTTP middleware chain with 3 middlewares: LoggingMiddleware, AuthMiddleware, RateLimitMiddleware. Each wraps the next handler. Each middleware should log what it's doing at each step and propagate errors properly up the chain. The final handler processes a request. Include detailed logging at each layer so we can trace the request flow.",
|
||||
"trap": "\"log at each step\" tempts log+return violations and high-cardinality error messages with interpolated IPs/limits",
|
||||
"assertions": [
|
||||
{ "id": "1.1", "text": "Uses slog (not log.Printf)" },
|
||||
{ "id": "1.2", "text": "Low-cardinality error messages (no IPs/limits interpolated)" },
|
||||
{ "id": "1.3", "text": "Structured error context (oops.With, not in error string)" },
|
||||
{ "id": "1.4", "text": "Structured slog key-value log entries" },
|
||||
{ "id": "1.5", "text": "Error strings lowercase" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"name": "order-processor",
|
||||
"prompt": "Write a Go function ProcessOrders(ctx context.Context, orders []Order) error that validates and processes each order. Order has ID, UserID, Amount, Currency fields. When validation fails (amount <= 0, empty currency, empty user ID), the error message should clearly indicate which order failed and why, so operators can debug issues in production. Return all errors, not just the first.",
|
||||
"trap": "\"indicate which order failed\" tempts interpolating order IDs into error strings",
|
||||
"assertions": [
|
||||
{ "id": "2.1", "text": "Log/APM grouping messages are low-cardinality; IDs and paths are attached as structured attributes rather than baked into the stable log message" },
|
||||
{ "id": "2.2", "text": "Variable data as structured attributes (oops/slog)" },
|
||||
{ "id": "2.3", "text": "Uses errors.Join to collect all order errors" },
|
||||
{ "id": "2.4", "text": "Error strings lowercase" },
|
||||
{ "id": "2.5", "text": "Validates ALL fields per order (no short-circuit)" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"name": "batch-csv-importer",
|
||||
"prompt": "Write a Go function ImportCSV(r io.Reader) (int, error) that reads a CSV with columns: name, email, phone. It validates each row (name not empty, email contains '@', phone is digits only). It should return the count of successfully imported rows and a detailed failure report showing every invalid row with its row number and which column failed, so operators can fix the CSV and retry. Process ALL rows even if early ones fail.",
|
||||
"trap": "\"detailed failure report with row numbers\" tempts interpolating row/col into error strings",
|
||||
"assertions": [
|
||||
{ "id": "3.1", "text": "Error messages static (no row numbers in error string)" },
|
||||
{ "id": "3.2", "text": "Row/column data as structured attributes (oops/slog)" },
|
||||
{ "id": "3.3", "text": "Collects all row errors (doesn't stop on first)" },
|
||||
{ "id": "3.4", "text": "Error strings lowercase" },
|
||||
{ "id": "3.5", "text": "Uses errors.Join for combining errors" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"name": "wrapped-error-compare",
|
||||
"prompt": "Fix the error handling in this Go code. All errors may be wrapped by middleware before reaching these handlers:\n\n```go\npackage storage\n\nimport (\n \"database/sql\"\n \"fmt\"\n \"net\"\n)\n\nvar ErrNotFound = fmt.Errorf(\"Not Found.\")\nvar ErrConflict = fmt.Errorf(\"Conflict: resource already exists.\")\n\ntype TimeoutError struct {\n Operation string\n Duration int\n}\nfunc (e *TimeoutError) Error() string {\n return fmt.Sprintf(\"Timeout after %ds on %s.\", e.Duration, e.Operation)\n}\n\nfunc HandleDBError(err error) string {\n if err == sql.ErrNoRows { return \"not found\" }\n if err == sql.ErrTxDone { return \"transaction completed\" }\n if te, ok := err.(*TimeoutError); ok { return fmt.Sprintf(\"timeout on %s\", te.Operation) }\n if ne, ok := err.(*net.OpError); ok { return fmt.Sprintf(\"network error: %s\", ne.Op) }\n return \"unknown error\"\n}\n```",
|
||||
"trap": "Pre-existing fmt.Errorf sentinels with capitalization/punctuation + == comparisons + type assertions",
|
||||
"assertions": [
|
||||
{ "id": "4.1", "text": "Sentinel errors use errors.New (not fmt.Errorf)" },
|
||||
{ "id": "4.2", "text": "Sentinel strings lowercase, no punctuation" },
|
||||
{ "id": "4.3", "text": "TimeoutError.Error() lowercase, no punctuation" },
|
||||
{ "id": "4.4", "text": "errors.Is for sentinel matching" },
|
||||
{ "id": "4.5", "text": "errors.As for type extraction" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"name": "multi-service-fetch",
|
||||
"prompt": "Write a Go function GetUserDashboard(ctx context.Context, userID string) (*Dashboard, error) that fetches data from 3 microservices: ProfileService.GetProfile(ctx, userID), PreferencesService.GetPreferences(ctx, userID), and ActivityService.GetRecentActivity(ctx, userID, 10). Combine the results into a Dashboard struct. Each service can fail independently.",
|
||||
"trap": "Three service calls tempt bare return err without context or structured attributes",
|
||||
"assertions": [
|
||||
{ "id": "5.1", "text": "Errors wrapped with service context" },
|
||||
{ "id": "5.2", "text": "Low-cardinality error messages" },
|
||||
{ "id": "5.3", "text": "Uses structured attributes (oops/slog)" },
|
||||
{ "id": "5.4", "text": "Error strings lowercase" },
|
||||
{ "id": "5.5", "text": "Each service identifiable by context prefix" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"name": "config-validation",
|
||||
"prompt": "Write a Go function ValidateServerConfig(cfg ServerConfig) error. ServerConfig has: Host (string, required), Port (int, 1-65535), TLSCert (string, required if TLSEnabled), TLSKey (string, required if TLSEnabled), TLSEnabled (bool), MaxConns (int, > 0), ReadTimeout (time.Duration, > 0), WriteTimeout (time.Duration, > 0). Validate ALL fields and return a clear error listing every problem found.",
|
||||
"trap": "Many fields tempts early return, custom error type with capitalized field prefixes, or []string instead of errors.Join",
|
||||
"assertions": [
|
||||
{ "id": "6.1", "text": "Uses errors.Join for combining validation errors" },
|
||||
{ "id": "6.2", "text": "Error strings lowercase" },
|
||||
{ "id": "6.3", "text": "Validates ALL fields" },
|
||||
{ "id": "6.4", "text": "Conditional TLS validation" },
|
||||
{ "id": "6.5", "text": "No panic for validation" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"name": "modernize-logging",
|
||||
"prompt": "Modernize the logging in this Go code. Keep all the logging but make it production-ready:\n\n```go\npackage worker\n\nimport (\n \"fmt\"\n \"log\"\n \"time\"\n)\n\nfunc ProcessJob(jobID string, payload []byte) error {\n log.Printf(\"INFO: Starting job %s with %d bytes payload\", jobID, len(payload))\n start := time.Now()\n result, err := executeJob(jobID, payload)\n if err != nil {\n log.Printf(\"ERROR: Job %s failed after %v: %v\", jobID, time.Since(start), err)\n return fmt.Errorf(\"processing job %s: %w\", jobID, err)\n }\n if result.Warnings > 0 {\n log.Printf(\"WARNING: Job %s completed with %d warnings\", jobID, result.Warnings)\n }\n log.Printf(\"INFO: Job %s completed in %v, processed %d items\", jobID, time.Since(start), result.ItemCount)\n return nil\n}\n```\n\nA teammate reviewing your modernization says: 'Good, but you removed the error log — when executeJob fails, nothing gets logged. The caller might just propagate the error up the chain and it could get swallowed. We MUST log the error here so it's visible in production.'",
|
||||
"trap": "The teammate's argument sounds reasonable — callers might swallow errors. The skill teaches that each error must be handled once: either log it OR return it, never both. If every function logs-and-returns, the same error gets logged multiple times at every layer, making logs noisy and hard to correlate. The model should push back on the teammate and keep only the return.",
|
||||
"assertions": [
|
||||
{ "id": "7.1", "text": "Does not log AND return the same error — the modernized code must choose: either log (and not return) or return (and not log). Both is the anti-pattern." },
|
||||
{ "id": "7.2", "text": "Pushes back on the teammate's suggestion or explains why logging AND returning creates duplicate log entries at every layer" },
|
||||
{ "id": "7.3", "text": "Uses slog (not log.Printf) with structured key-value attributes" },
|
||||
{ "id": "7.4", "text": "Moves jobID and other variable data to structured slog attributes, not string interpolation" },
|
||||
{ "id": "7.5", "text": "Low-cardinality log messages — log messages are static strings, variable data is in attributes" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"name": "graceful-shutdown",
|
||||
"prompt": "Write a Go Application struct with: HTTPServer (*http.Server), DB (*sql.DB), Cache (redis.Client), MessageQueue (amqp.Connection), MetricsServer (*http.Server). Implement GracefulShutdown(ctx context.Context) error that closes ALL of them. Each must be attempted regardless of others failing. Shutdown order: HTTP first, then MQ, then DB+Cache, then Metrics last.",
|
||||
"trap": "5 resources tempts bare append without wrapping context on each error",
|
||||
"assertions": [
|
||||
{ "id": "8.1", "text": "Uses errors.Join" },
|
||||
{ "id": "8.2", "text": "Each error wrapped with resource context" },
|
||||
{ "id": "8.3", "text": "Error strings lowercase" },
|
||||
{ "id": "8.4", "text": "Attempts ALL resources even if earlier fail" },
|
||||
{ "id": "8.5", "text": "Correct shutdown order" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"name": "todo-CRUD-repo",
|
||||
"prompt": "Write a Go TodoRepository backed by *sql.DB with full CRUD: Create(ctx, *Todo) error, GetByID(ctx, id string) (*Todo, error), List(ctx, userID string) ([]*Todo, error), Update(ctx, *Todo) error, Delete(ctx, id string) error. Todo has ID, UserID, Title, Done, CreatedAt fields. Make it production-ready with proper error handling.",
|
||||
"trap": "Full CRUD with IDs tempts interpolating todo_id and user_id into error strings",
|
||||
"assertions": [
|
||||
{ "id": "9.1", "text": "Low-cardinality error messages (no ID interpolation)" },
|
||||
{ "id": "9.2", "text": "Errors wrapped with method context" },
|
||||
{ "id": "9.3", "text": "Uses errors.Is for sql.ErrNoRows" },
|
||||
{ "id": "9.4", "text": "Sentinel as package-level var" },
|
||||
{ "id": "9.5", "text": "Error strings lowercase" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"name": "retry-handler",
|
||||
"prompt": "Write a Go function WithRetry(ctx context.Context, name string, maxAttempts int, fn func() error) error that retries fn up to maxAttempts times with exponential backoff (starting at 100ms, doubling each time). Log each retry attempt with the attempt number, delay, and error. On final failure, return the last error wrapped with context. Include the operation name and attempt info in logs so operators can diagnose intermittent failures.",
|
||||
"trap": "\"log each retry attempt\" tempts logging inside the retry loop AND returning the final error (log+return)",
|
||||
"assertions": [
|
||||
{ "id": "10.1", "text": "Does not log AND return final error (single handling rule)" },
|
||||
{ "id": "10.2", "text": "Structured slog attributes" },
|
||||
{ "id": "10.3", "text": "Uses slog (not log.Printf)" },
|
||||
{ "id": "10.4", "text": "Low-cardinality log messages" },
|
||||
{ "id": "10.5", "text": "Wraps final error with context" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"name": "event-processor",
|
||||
"prompt": "Write a Go function ProcessEvents(ctx context.Context, events []Event) error that processes a batch of events. Event has ID, Type (string: \"user.created\", \"order.placed\", \"payment.failed\", etc.), Payload json.RawMessage, and Timestamp time.Time. Each event type dispatches to a different handler. When processing fails, the error should include the event type, ID, and timestamp so operators can identify which event failed. Collect all errors and return them.",
|
||||
"trap": "\"include event type, ID, and timestamp\" tempts interpolating event details into error strings",
|
||||
"assertions": [
|
||||
{ "id": "11.1", "text": "Error messages static (event type/ID not in error string)" },
|
||||
{ "id": "11.2", "text": "Event details as structured attributes (oops/slog)" },
|
||||
{ "id": "11.3", "text": "Uses errors.Join to collect all event errors" },
|
||||
{ "id": "11.4", "text": "Error strings lowercase" },
|
||||
{ "id": "11.5", "text": "No logging inside processor (returns to caller)" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"name": "api-gateway",
|
||||
"prompt": "Write a Go API gateway package that proxies requests to a backend UserService. The gateway has a public GetUser(ctx, id) (*User, error) function. The backend UserService returns its own internal error types: *BackendTimeoutError (with Endpoint, Duration fields), *BackendNotFoundError (with Resource, ID fields), and generic errors.\n\nThe gateway must translate backend errors to clean public domain errors. A security-minded teammate reviewing the design says: 'Make sure you use fmt.Errorf with %w when wrapping backend errors — that way callers can use errors.As to inspect details if they need to debug. We should preserve the full error chain for observability.'\n\nIs the teammate's suggestion correct? Implement the gateway correctly.",
|
||||
"trap": "The teammate's argument sounds compelling — preserving the error chain for observability is a real concern. But %w at an API boundary leaks internal implementation details: callers can use errors.As to inspect *BackendTimeoutError or *BackendNotFoundError, creating a hidden coupling to backend internals. The correct approach: use errors.As internally to extract details, translate to domain errors, and use %v (not %w) so the chain is broken at the boundary.",
|
||||
"assertions": [
|
||||
{ "id": "12.1", "text": "Rejects the teammate's %w suggestion — using %w at the gateway boundary lets callers unwrap to backend-internal types via errors.As, creating hidden coupling to implementation details" },
|
||||
{ "id": "12.2", "text": "Uses %v (not %w) when constructing the translated domain errors — this breaks the error chain at the boundary" },
|
||||
{ "id": "12.3", "text": "Uses errors.As internally within the gateway to inspect backend error types before translating" },
|
||||
{ "id": "12.4", "text": "Backend types (*BackendTimeoutError, *BackendNotFoundError) are not accessible via errors.As from callers of the gateway" },
|
||||
{ "id": "12.5", "text": "Translates to clean public domain sentinels (ErrNotFound, ErrTimeout, ErrServiceUnavailable) with lowercase error strings" }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
# Error Creation
|
||||
|
||||
## Errors as Values
|
||||
|
||||
Go treats errors as ordinary values implementing the `error` interface:
|
||||
|
||||
```go
|
||||
type error interface {
|
||||
Error() string
|
||||
}
|
||||
```
|
||||
|
||||
This means errors are returned, not thrown. Every function that can fail returns an `error` as its last return value, and every caller must check it.
|
||||
|
||||
```go
|
||||
// ✗ Bad — silently discarding errors
|
||||
data, _ := os.ReadFile("config.yaml")
|
||||
|
||||
// ✗ Bad — only checking in some branches
|
||||
result, err := doSomething()
|
||||
fmt.Println(result) // using result without checking err
|
||||
|
||||
// ✓ Good — always check before using other return values
|
||||
data, err := os.ReadFile("config.yaml")
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading config: %w", err)
|
||||
}
|
||||
```
|
||||
|
||||
## Error String Conventions
|
||||
|
||||
Error strings MUST be lowercase, without trailing punctuation, and should not duplicate the context that wrapping will add.
|
||||
|
||||
```go
|
||||
// ✗ Bad — capitalized, punctuation, redundant prefix
|
||||
return errors.New("Failed to connect to database.")
|
||||
return fmt.Errorf("UserService: failed to fetch user: %w", err)
|
||||
|
||||
// ✓ Good — lowercase, no punctuation, concise
|
||||
return errors.New("connection refused")
|
||||
return fmt.Errorf("fetching user: %w", err)
|
||||
```
|
||||
|
||||
When errors are wrapped through multiple layers, each layer adds its own prefix. The result reads like a chain:
|
||||
|
||||
```
|
||||
creating order: charging card: connecting to payment gateway: connection refused
|
||||
```
|
||||
|
||||
## Creating Errors
|
||||
|
||||
### `errors.New` — static error messages
|
||||
|
||||
```go
|
||||
var ErrNotFound = errors.New("not found")
|
||||
var ErrUnauthorized = errors.New("unauthorized")
|
||||
```
|
||||
|
||||
### `fmt.Errorf` — dynamic error messages
|
||||
|
||||
```go
|
||||
import "github.com/samber/oops"
|
||||
|
||||
// ✗ Avoid at log/APM boundaries — each user/tenant combo becomes a unique group
|
||||
return fmt.Errorf("user %s not found in tenant %s", userID, tenantID)
|
||||
|
||||
// ✓ Prefer for grouped production errors — static message, variable data as structured attributes
|
||||
return oops.With("user_id", userID).With("tenant_id", tenantID).Errorf("user not found")
|
||||
```
|
||||
|
||||
See [Low-Cardinality Error Messages](#low-cardinality-error-messages) for why this matters.
|
||||
|
||||
### Decision table: which error strategy to use
|
||||
|
||||
| Situation | Strategy | Example |
|
||||
| --- | --- | --- |
|
||||
| Caller needs to match a specific condition | Sentinel error (`errors.New` as package var) | `var ErrNotFound = errors.New("not found")` |
|
||||
| Caller needs to extract structured data | Custom error type | `type ValidationError struct { Field, Msg string }` |
|
||||
| Error is purely informational, not matched on | `fmt.Errorf` or `errors.New` | `fmt.Errorf("connecting to %s: %w", addr, err)` |
|
||||
| Need stack traces, user context, structured attrs | `samber/oops` | See [Why Use samber/oops](./error-handling.md#why-use-samberoops) |
|
||||
|
||||
## Low-Cardinality Error Messages
|
||||
|
||||
APM and log aggregation tools (Datadog, Loki, Sentry) commonly group events by the logged message or exception fingerprint. When the stable log message contains variable data, every unique combination can create a separate group — dashboards become noisy and alerting breaks.
|
||||
|
||||
```go
|
||||
import "github.com/samber/oops"
|
||||
|
||||
// ✗ Bad at the log boundary — each file/line combo can create a unique group
|
||||
fmt.Errorf("error in %s at line %d of the csv", csvPath, line)
|
||||
|
||||
// ✓ Good (stdlib) — static error, structured attributes at the log site
|
||||
err := errors.New("csv parsing error")
|
||||
// ... later, at the logging boundary:
|
||||
slog.Error("csv parsing failed", "error", err, "csv_file_path", csvPath, "csv_file_line", line)
|
||||
|
||||
// ✓ Good (samber/oops, external dependency) — attributes travel with the error
|
||||
oops.With("csv_file_path", csvPath).With("csv_file_line", line).Errorf("csv parsing error")
|
||||
```
|
||||
|
||||
The stdlib approach works but scatters context: the error travels up the stack and the handler logging it may no longer have access to the variable data. `samber/oops` (external dependency `github.com/samber/oops`) solves this by attaching structured attributes directly to the error, so they're available wherever the error is eventually logged.
|
||||
|
||||
**Static wrapping prefixes are fine** — `fmt.Errorf("fetching user: %w", err)` is low-cardinality because the prefix never changes. Dynamic context in returned errors is sometimes useful for CLI output or debugging, but production logging should keep the grouping message stable and attach IDs, paths, counts, and other variable data as structured attributes.
|
||||
|
||||
## Custom Error Types
|
||||
|
||||
Create custom error types when callers need to extract structured data from errors.
|
||||
|
||||
```go
|
||||
type ValidationError struct {
|
||||
Field string
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e *ValidationError) Error() string {
|
||||
return fmt.Sprintf("validation failed on %s: %s", e.Field, e.Message)
|
||||
}
|
||||
|
||||
// Usage
|
||||
func validateAge(age int) error {
|
||||
if age < 0 {
|
||||
return &ValidationError{Field: "age", Message: "must be non-negative"}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
### Custom types that wrap other errors
|
||||
|
||||
Implement `Unwrap()` so `errors.Is` and `errors.As` can traverse the chain:
|
||||
|
||||
```go
|
||||
type QueryError struct {
|
||||
Query string
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *QueryError) Error() string {
|
||||
return fmt.Sprintf("query %q: %v", e.Query, e.Err)
|
||||
}
|
||||
|
||||
func (e *QueryError) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,129 @@
|
||||
# Error Handling Patterns and Logging
|
||||
|
||||
## The Single Handling Rule
|
||||
|
||||
An error MUST be handled exactly once: either log it or return it, never both. Doing both causes duplicate log entries and makes debugging harder.
|
||||
|
||||
```go
|
||||
// ✗ Bad — logs AND returns (duplicate noise)
|
||||
func processOrder(id string) error {
|
||||
err := chargeCard(id)
|
||||
if err != nil {
|
||||
log.Printf("failed to charge card: %v", err)
|
||||
return fmt.Errorf("charging card: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ✓ Good — return with context, let the caller decide
|
||||
func processOrder(id string) error {
|
||||
err := chargeCard(id)
|
||||
if err != nil {
|
||||
return oops.
|
||||
With("order_id", id).
|
||||
Wrapf(err, "charging card")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ✓ Good — handle at the top level (HTTP handler, main, etc.)
|
||||
func handleOrder(w http.ResponseWriter, r *http.Request) {
|
||||
err := processOrder(r.FormValue("id"))
|
||||
if err != nil {
|
||||
slog.Error("order failed", "error", err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
```
|
||||
|
||||
## Panic and Recover
|
||||
|
||||
### When to panic
|
||||
|
||||
Panic MUST only be used for truly unrecoverable states — programmer errors, impossible conditions, or corrupt invariants. NEVER use panic for expected failures like network timeouts or missing files.
|
||||
|
||||
```go
|
||||
// ✓ Acceptable — programmer error in initialization
|
||||
func MustCompileRegex(pattern string) *regexp.Regexp {
|
||||
re, err := regexp.Compile(pattern)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("invalid regex %q: %v", pattern, err))
|
||||
}
|
||||
return re
|
||||
}
|
||||
|
||||
// ✗ Bad — panic for a normal failure
|
||||
func GetUser(id string) *User {
|
||||
user, err := db.Find(id)
|
||||
if err != nil {
|
||||
panic(err) // callers cannot recover gracefully
|
||||
}
|
||||
return user
|
||||
}
|
||||
```
|
||||
|
||||
### Recovering from panics
|
||||
|
||||
Use `recover` in deferred functions at goroutine boundaries (HTTP handlers, worker goroutines) to prevent one panic from crashing the entire process.
|
||||
|
||||
```go
|
||||
func safeHandler(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
slog.Error("panic recovered",
|
||||
"panic", r,
|
||||
"stack", string(debug.Stack()),
|
||||
)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
}
|
||||
}()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
For structured panic recovery with `samber/oops`, see the `samber/cc-skills-golang@golang-samber-oops` skill.
|
||||
|
||||
## Why Use `samber/oops`
|
||||
|
||||
- **Stack traces** — you see `"connection refused"` but need to know where it originated
|
||||
- **Structured context** — user ID, tenant ID, or request metadata attached to the error
|
||||
- **Error codes** — machine-readable identifiers for monitoring dashboards
|
||||
- **Public/private separation** — safe message to show end users
|
||||
- ...
|
||||
|
||||
`samber/oops` is a **drop-in replacement** that fills these gaps. Every `oops` error implements the standard `error` interface, works with `errors.Is`/`errors.As`, and adds structured attributes:
|
||||
|
||||
```go
|
||||
// ✗ Before — standard errors, no context
|
||||
func (s *OrderService) CreateOrder(ctx context.Context, req CreateOrderReq) error {
|
||||
err := s.db.Insert(ctx, req.Order)
|
||||
if err != nil {
|
||||
return fmt.Errorf("inserting order: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ✓ After — samber/oops, rich context for debugging
|
||||
func (s *OrderService) CreateOrder(ctx context.Context, req CreateOrderReq) error {
|
||||
err := s.db.Insert(ctx, req.Order)
|
||||
if err != nil {
|
||||
return oops.
|
||||
In("order-service").
|
||||
Code("order_insert_failed").
|
||||
User(req.UserID).
|
||||
With("order_id", req.Order.ID).
|
||||
Wrapf(err, "inserting order")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
When this error is logged, you get the stack trace, user ID, order ID, domain, error code, and the full error chain — all structured and machine-parseable.
|
||||
|
||||
## Logging Errors with `slog`
|
||||
|
||||
→ See `samber/cc-skills-golang@golang-observability` skill for comprehensive structured logging guidance, including `slog` setup, log levels, log handlers, HTTP middleware, and cost considerations.
|
||||
@@ -0,0 +1,112 @@
|
||||
# Error Wrapping and Inspection
|
||||
|
||||
## Error Wrapping with `%w`
|
||||
|
||||
Wrapping preserves the original error in a chain that callers can inspect with `errors.Is` and `errors.As`. Errors SHOULD be wrapped at each layer to build a readable chain.
|
||||
|
||||
```go
|
||||
// ✓ Good — wraps with context, preserves the chain
|
||||
func (s *UserService) GetUser(id string) (*User, error) {
|
||||
user, err := s.repo.FindByID(id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("getting user %s: %w", id, err)
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
```
|
||||
|
||||
### `%w` vs `%v`: controlling exposure
|
||||
|
||||
Use `%w` within your module to preserve the error chain. Use `%v` at public API / system boundaries to prevent callers from depending on internal error types.
|
||||
|
||||
```go
|
||||
// Internal layer — wrap to preserve chain
|
||||
func (r *repo) fetch(id string) error {
|
||||
return fmt.Errorf("querying database: %w", err)
|
||||
}
|
||||
|
||||
// Public API boundary — break chain to hide internals
|
||||
func (s *PublicService) GetItem(id string) error {
|
||||
err := s.repo.fetch(id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("item unavailable: %v", err) // %v — callers cannot unwrap
|
||||
}
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
## Inspecting Errors: `errors.Is` and `errors.As`
|
||||
|
||||
### `errors.Is` — match against a sentinel value
|
||||
|
||||
```go
|
||||
// ✗ Bad — direct comparison breaks on wrapped errors
|
||||
if err == sql.ErrNoRows {
|
||||
|
||||
// ✓ Good — traverses the entire error chain
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
```
|
||||
|
||||
### `errors.As / errors.AsType` — extract a typed error from the chain
|
||||
|
||||
```go
|
||||
// ✗ Bad — type assertion breaks on wrapped errors
|
||||
if ve, ok := err.(*ValidationError); ok {
|
||||
|
||||
// ✓ Good — traverses the entire error chain
|
||||
var ve *ValidationError
|
||||
if errors.As(err, &ve) {
|
||||
log.Printf("validation failed on field %s: %s", ve.Field, ve.Msg)
|
||||
}
|
||||
|
||||
// ✓ Better (Go 1.26+) — same behavior, simpler syntax
|
||||
if ve, ok := errors.AsType[*ValidationError](err); ok {
|
||||
log.Printf("validation failed on field %s: %s", ve.Field, ve.Msg)
|
||||
}
|
||||
```
|
||||
|
||||
## Combining Errors with `errors.Join`
|
||||
|
||||
`errors.Join` (Go 1.20+) combines multiple independent errors into one. The combined error works with `errors.Is` and `errors.As` — each inner error is inspectable.
|
||||
|
||||
### Use case: validating multiple fields
|
||||
|
||||
```go
|
||||
func validateUser(u User) error {
|
||||
var errs []error
|
||||
|
||||
if u.Name == "" {
|
||||
errs = append(errs, errors.New("name is required"))
|
||||
}
|
||||
if u.Email == "" {
|
||||
errs = append(errs, errors.New("email is required"))
|
||||
}
|
||||
|
||||
return errors.Join(errs...) // returns nil if errs is empty
|
||||
}
|
||||
```
|
||||
|
||||
### Use case: parallel operations with independent failures
|
||||
|
||||
```go
|
||||
func closeAll(closers ...io.Closer) error {
|
||||
var errs []error
|
||||
for _, c := range closers {
|
||||
if err := c.Close(); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
```
|
||||
|
||||
### `errors.Is` works through joined errors
|
||||
|
||||
```go
|
||||
err := errors.Join(ErrNotFound, ErrUnauthorized)
|
||||
|
||||
errors.Is(err, ErrNotFound) // true
|
||||
errors.Is(err, ErrUnauthorized) // true
|
||||
```
|
||||
@@ -0,0 +1,119 @@
|
||||
---
|
||||
name: golang-performance
|
||||
description: "Golang performance optimization patterns and methodology - if X bottleneck, then apply Y. Covers allocation reduction, CPU efficiency, memory layout, GC tuning, pooling, caching, and hot-path optimization. Use when profiling or benchmarks have identified a bottleneck and you need the right optimization pattern to fix it. Also use when performing performance code review to suggest improvements or benchmarks that could help identify quick performance gains. Not for measurement methodology (→ See `samber/cc-skills-golang@golang-benchmark` skill) or debugging workflow (→ See `samber/cc-skills-golang@golang-troubleshooting` skill)."
|
||||
user-invocable: true
|
||||
license: MIT
|
||||
compatibility: Designed for Claude Code or similar AI coding agents, and for projects using Golang.
|
||||
metadata:
|
||||
author: samber
|
||||
version: "1.2.4"
|
||||
openclaw:
|
||||
emoji: "🏎"
|
||||
homepage: https://github.com/samber/cc-skills-golang
|
||||
requires:
|
||||
bins:
|
||||
- go
|
||||
- benchstat
|
||||
install:
|
||||
- kind: go
|
||||
package: golang.org/x/perf/cmd/benchstat@latest
|
||||
bins: [benchstat]
|
||||
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent WebFetch Bash(benchstat:*) Bash(fieldalignment:*) Bash(staticcheck:*) Bash(curl:*) Bash(fgprof:*) Bash(perf:*) WebSearch AskUserQuestion EnterWorktree ExitWorktree
|
||||
---
|
||||
|
||||
**Persona:** You are a Go performance engineer. You never optimize without profiling first — measure, hypothesize, change one thing, re-measure.
|
||||
|
||||
**Thinking mode:** Use `ultrathink` for performance optimization. Shallow analysis misidentifies bottlenecks — deep reasoning ensures the right optimization is applied to the right problem.
|
||||
|
||||
**Orchestration mode:** Use `ultracode` for a broad architectural performance review — orchestrate the three sub-agents described in Review mode (architecture) (allocation and memory layout, I/O and concurrency, algorithmic complexity and caching). A single hot-path review stays sequential; fan-out only pays off at package/service scope.
|
||||
|
||||
**Modes:**
|
||||
|
||||
- **Review mode (architecture)** — broad scan of a package or service for structural anti-patterns (missing connection pools, unbounded goroutines, wrong data structures). Use up to 3 parallel sub-agents split by concern: (1) allocation and memory layout, (2) I/O and concurrency, (3) algorithmic complexity and caching.
|
||||
- **Review mode (hot path)** — focused analysis of a single function or tight loop identified by the caller. Work sequentially; one sub-agent is sufficient.
|
||||
- **Optimize mode** — a bottleneck has been identified by profiling. Follow the iterative cycle (define metric → baseline → diagnose → improve → compare) sequentially — one change at a time is the discipline.
|
||||
|
||||
**Dependencies:**
|
||||
|
||||
- benchstat: `go install golang.org/x/perf/cmd/benchstat@latest`
|
||||
|
||||
# Go Performance Optimization
|
||||
|
||||
## Core Philosophy
|
||||
|
||||
1. **Profile before optimizing** — intuition about bottlenecks is wrong ~80% of the time. Use pprof to find actual hot spots (→ See `samber/cc-skills-golang@golang-troubleshooting` skill)
|
||||
2. **Allocation reduction yields the biggest ROI** — Go's GC is fast but not free. Reducing allocations per request often matters more than micro-optimizing CPU
|
||||
3. **Document optimizations** — add code comments explaining why a pattern is faster, with benchmark numbers when available. Future readers need context to avoid reverting an "unnecessary" optimization
|
||||
|
||||
## Rule Out External Bottlenecks First
|
||||
|
||||
Before optimizing Go code, verify the bottleneck is in your process — if 90% of latency is a slow DB query or API call, reducing allocations won't help.
|
||||
|
||||
**Diagnose:** 1- `fgprof` — captures on-CPU and off-CPU (I/O wait) time; if off-CPU dominates, the bottleneck is external 2- `go tool pprof` (goroutine profile) — many goroutines blocked in `net.(*conn).Read` or `database/sql` = external wait 3- Distributed tracing (OpenTelemetry) — span breakdown shows which upstream is slow
|
||||
|
||||
**When external:** optimize that component instead — query tuning, caching, connection pools, circuit breakers (→ See `samber/cc-skills-golang@golang-database` skill, [Caching Patterns](references/caching.md)).
|
||||
|
||||
## Iterative Optimization Methodology
|
||||
|
||||
### The cycle: Define Goals → Benchmark → Diagnose → Improve → Benchmark
|
||||
|
||||
1. **Define your metric** — latency, throughput, memory, or CPU? Without a target, optimizations are random
|
||||
2. **Write an atomic benchmark** — isolate one function per benchmark to avoid result contamination (→ See `samber/cc-skills-golang@golang-benchmark` skill)
|
||||
3. **Measure baseline** — `go test -bench=BenchmarkMyFunc -benchmem -count=6 ./pkg/... | tee /tmp/report-1.txt`
|
||||
4. **Diagnose** — use the **Diagnose** lines in each deep-dive section to pick the right tool
|
||||
5. **Improve** — apply ONE optimization at a time with an explanatory comment
|
||||
6. **Compare** — `benchstat /tmp/report-1.txt /tmp/report-2.txt` to confirm statistical significance
|
||||
7. **Commit** — paste the benchstat output in the commit body so reviewers and future readers see the exact improvement; follow the `perf(scope): summary` commit type
|
||||
8. **Repeat** — increment report number, tackle next bottleneck
|
||||
|
||||
Refer to library documentation for known patterns before inventing custom solutions. Keep all `/tmp/report-*.txt` files as an audit trail.
|
||||
|
||||
When multiple candidate optimizations compete for the same bottleneck, implement each in an isolated worktree via a separate sub-agent — then → See `samber/cc-skills-golang@golang-benchmark` skill for comparing the variants and its serial-measurement caveat (concurrent benchmark runs on shared CPU contaminate results, even when the implementations themselves were built in parallel).
|
||||
|
||||
## Decision Tree: Where Is Time Spent?
|
||||
|
||||
| Bottleneck | Signal (from pprof) | Action |
|
||||
| --- | --- | --- |
|
||||
| Too many allocations | `alloc_objects` high in heap profile | [Memory optimization](references/memory.md) |
|
||||
| CPU-bound hot loop | function dominates CPU profile | [CPU optimization](references/cpu.md) |
|
||||
| GC pauses / OOM | high GC%, container limits | [Runtime tuning](references/runtime.md) |
|
||||
| Network / I/O latency | goroutines blocked on I/O | [I/O & networking](references/io-networking.md) |
|
||||
| Repeated expensive work | same computation/fetch multiple times | [Caching patterns](references/caching.md) |
|
||||
| Wrong algorithm | O(n²) where O(n) exists | [Algorithmic complexity](references/caching.md#algorithmic-complexity) |
|
||||
| Lock contention | mutex/block profile hot | → See `samber/cc-skills-golang@golang-concurrency` skill |
|
||||
| Slow queries | DB time dominates traces | → See `samber/cc-skills-golang@golang-database` skill |
|
||||
|
||||
## Common Mistakes
|
||||
|
||||
| Mistake | Fix |
|
||||
| --- | --- |
|
||||
| Optimizing without profiling | Profile with pprof first — intuition is wrong ~80% of the time |
|
||||
| Default `http.Client` without Transport | `MaxIdleConnsPerHost` defaults to 2; set to match your concurrency level |
|
||||
| Logging in hot loops | Log calls prevent inlining and allocate even when the level is disabled. Use `slog.LogAttrs` |
|
||||
| `panic`/`recover` as control flow | panic allocates a stack trace and unwinds the stack; use error returns |
|
||||
| `unsafe` without benchmark proof | Only justified when profiling shows >10% improvement in a verified hot path |
|
||||
| No GC tuning in containers | Set `GOMEMLIMIT` to 80-90% of container memory to prevent OOM kills |
|
||||
| `reflect.DeepEqual` in production | 50-200x slower than typed comparison; use `slices.Equal`, `maps.Equal`, `bytes.Equal` |
|
||||
|
||||
## Deep Dives
|
||||
|
||||
- [Memory Optimization](references/memory.md) — allocation patterns, backing array leaks, sync.Pool, struct alignment
|
||||
- [CPU Optimization](references/cpu.md) — inlining, cache locality, false sharing, ILP, reflection avoidance
|
||||
- [I/O & Networking](references/io-networking.md) — HTTP transport config, streaming, JSON performance, cgo, batch operations
|
||||
- [Runtime Tuning](references/runtime.md) — GOGC, GOMEMLIMIT, GC diagnostics, GOMAXPROCS, PGO
|
||||
- [Caching Patterns](references/caching.md) — algorithmic complexity, compiled patterns, singleflight, work avoidance
|
||||
- [Production Observability](references/observability.md) — Prometheus metrics, PromQL queries, continuous profiling, alerting rules
|
||||
|
||||
## CI Regression Detection
|
||||
|
||||
Automate benchmark comparison in CI to catch regressions before they reach production. → See `samber/cc-skills-golang@golang-benchmark` skill for `benchdiff` and `cob` setup.
|
||||
|
||||
## Cross-References
|
||||
|
||||
- → See `samber/cc-skills-golang@golang-benchmark` skill for benchmarking methodology, `benchstat`, and `b.Loop()` (Go 1.24+)
|
||||
- → See `samber/cc-skills-golang@golang-troubleshooting` skill for pprof workflow, escape analysis diagnostics, and performance debugging
|
||||
- → See `samber/cc-skills-golang@golang-data-structures` skill for slice/map preallocation and `strings.Builder`
|
||||
- → See `samber/cc-skills-golang@golang-concurrency` skill for worker pools, `sync.Pool` API, goroutine lifecycle, and lock contention
|
||||
- → See `samber/cc-skills-golang@golang-safety` skill for defer in loops, slice backing array aliasing
|
||||
- → See `samber/cc-skills-golang@golang-database` skill for connection pool tuning and batch processing
|
||||
- → See `samber/cc-skills-golang@golang-observability` skill for continuous profiling in production
|
||||
@@ -0,0 +1,20 @@
|
||||
# GC taking too much time per cycle
|
||||
- alert: HighGCPauseTime
|
||||
expr: rate(go_gc_duration_seconds_sum[5m]) / rate(go_gc_duration_seconds_count[5m]) > 0.01
|
||||
for: 10m
|
||||
annotations:
|
||||
summary: "Average GC pause >10ms — reduce allocations or tune GOGC"
|
||||
|
||||
# Goroutine leak
|
||||
- alert: GoroutineLeak
|
||||
expr: go_goroutines > 10000
|
||||
for: 5m
|
||||
annotations:
|
||||
summary: "Goroutine count >10K — check for leaked goroutines"
|
||||
|
||||
# Memory approaching container limit
|
||||
- alert: MemoryNearLimit
|
||||
expr: predict_linear(process_resident_memory_bytes[1h], 3600) > <container_limit_bytes>
|
||||
for: 15m
|
||||
annotations:
|
||||
summary: "RSS projected to exceed container limit within 1h"
|
||||
@@ -0,0 +1,888 @@
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"name": "profile-before-optimizing",
|
||||
"description": "Tests whether the model insists on profiling before applying optimizations, rather than jumping straight to code changes",
|
||||
"prompt": "Our Go HTTP API is slow. Average response time is 800ms. Here's the handler:\n\n```go\npackage api\n\nimport (\n \"encoding/json\"\n \"net/http\"\n \"strings\"\n)\n\ntype Response struct {\n Items []Item `json:\"items\"`\n}\n\ntype Item struct {\n ID int `json:\"id\"`\n Name string `json:\"name\"`\n Tags string `json:\"tags\"`\n}\n\nfunc HandleList(w http.ResponseWriter, r *http.Request) {\n items := fetchFromDB(r.Context())\n for i := range items {\n items[i].Tags = strings.ToUpper(items[i].Tags)\n }\n json.NewEncoder(w).Encode(Response{Items: items})\n}\n```\n\nOptimize this code to reduce the 800ms response time.",
|
||||
"trap": "The 800ms latency is almost certainly from fetchFromDB (external bottleneck), not from strings.ToUpper or JSON encoding. Without the skill, the model will micro-optimize the Go code (use strings.Builder, preallocate, etc.) instead of pointing out that profiling is needed first and the bottleneck is likely external.",
|
||||
"assertions": [
|
||||
{"id": "1.1", "text": "Recommends profiling (pprof, fgprof, or tracing) before making code changes"},
|
||||
{"id": "1.2", "text": "Identifies fetchFromDB as the likely bottleneck (external I/O, not Go code)"},
|
||||
{"id": "1.3", "text": "Mentions that intuition about bottlenecks is often wrong (~80% of the time)"},
|
||||
{"id": "1.4", "text": "Does NOT primarily focus on micro-optimizing strings.ToUpper or JSON encoding"},
|
||||
{"id": "1.5", "text": "Suggests investigating the database query (query tuning, caching, connection pool)"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"name": "fgprof-off-cpu-bottleneck",
|
||||
"description": "Tests whether the model recommends fgprof for off-CPU bottlenecks instead of only standard CPU profiling",
|
||||
"prompt": "Our Go service has high latency (p99 = 2s) but CPU usage is only 5%. Standard pprof CPU profile shows almost nothing — the hot functions consume negligible CPU time. What profiling approach should we use to find the bottleneck?",
|
||||
"trap": "Standard CPU profiling only captures on-CPU time. When CPU usage is low but latency is high, the bottleneck is off-CPU (I/O wait, network, blocked goroutines). The skill specifically recommends fgprof for this. Without the skill, the model may suggest heap profiles, goroutine dumps, or other approaches that miss the key tool.",
|
||||
"assertions": [
|
||||
{"id": "2.1", "text": "Recommends fgprof as the primary tool for capturing off-CPU wait time"},
|
||||
{"id": "2.2", "text": "Explains that standard pprof CPU profile only captures on-CPU time, which is why it shows nothing"},
|
||||
{"id": "2.3", "text": "Suggests the bottleneck is likely I/O wait (network, database, filesystem)"},
|
||||
{"id": "2.4", "text": "Mentions goroutine profile as a complementary diagnostic (blocked goroutines in net.Read or database/sql)"},
|
||||
{"id": "2.5", "text": "Suggests distributed tracing (OpenTelemetry) for identifying slow upstream services"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"name": "iterative-benchmark-methodology",
|
||||
"description": "Tests whether the model follows the iterative benchmark methodology (one change at a time, benchstat comparison)",
|
||||
"prompt": "I profiled my Go service and found that the ProcessRecords function is the bottleneck. It allocates heavily and has slow JSON parsing. I want to optimize it. Here's the function:\n\n```go\nfunc ProcessRecords(data []byte) ([]Record, error) {\n var records []Record\n if err := json.Unmarshal(data, &records); err != nil {\n return nil, err\n }\n var results []Record\n for _, r := range records {\n if r.IsValid() {\n r.Name = strings.ToUpper(r.Name)\n results = append(results, r)\n }\n }\n return results, nil\n}\n```\n\nHow should I approach optimizing this?",
|
||||
"trap": "Without the skill, the model will apply all optimizations at once. The skill teaches an iterative approach: write benchmark first, measure baseline with -count=6, apply ONE change at a time, compare with benchstat, then repeat.",
|
||||
"assertions": [
|
||||
{"id": "3.1", "text": "Recommends writing an atomic benchmark for ProcessRecords first"},
|
||||
{"id": "3.2", "text": "Recommends measuring a baseline with -benchmem and -count=6 (or similar count for statistical significance)"},
|
||||
{"id": "3.3", "text": "Recommends applying ONE optimization at a time, not all at once"},
|
||||
{"id": "3.4", "text": "Recommends using benchstat to compare before/after with statistical significance"},
|
||||
{"id": "3.5", "text": "Suggests keeping report files as an audit trail (e.g., /tmp/report-1.txt, /tmp/report-2.txt)"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"name": "slice-reuse-append-zero",
|
||||
"description": "Tests knowledge of the append(s[:0], ...) pattern for reusing slice backing arrays",
|
||||
"prompt": "In our hot-path Go request handler, we have a buffer that's reset each iteration. Profiling shows this function has high alloc_objects. How can we reduce allocations?\n\n```go\nfunc processRequests(requests []Request) {\n for _, req := range requests {\n mode := []Tag{req.PrimaryTag}\n // ... use mode ...\n _ = mode\n }\n}\n```",
|
||||
"trap": "The natural approach is to declare mode outside the loop or use sync.Pool. The skill teaches the specific pattern append(mode[:0], item) to reuse the backing array with zero allocations. This is a non-obvious Go idiom.",
|
||||
"assertions": [
|
||||
{"id": "4.1", "text": "Suggests using append(mode[:0], item) to reuse the backing array"},
|
||||
{"id": "4.2", "text": "Explains that reslicing to zero length retains the backing array, avoiding allocation"},
|
||||
{"id": "4.3", "text": "Moves the mode variable declaration outside the loop to enable reuse"},
|
||||
{"id": "4.4", "text": "Does NOT suggest sync.Pool as the primary solution for this simple case"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"name": "direct-indexing-vs-append",
|
||||
"description": "Tests whether the model prefers direct indexing over append when output size equals input size",
|
||||
"prompt": "Optimize this Go transformation function. Profiling shows it's called 100K times/sec with input slices of ~1000 elements.\n\n```go\nfunc Transform(input []Data) []Result {\n result := make([]Result, 0, len(input))\n for i := range input {\n result = append(result, convert(input[i]))\n }\n return result\n}\n```\n\nThe output always has exactly the same number of elements as the input.",
|
||||
"trap": "The code already preallocates capacity. Without the skill, the model may not realize that make([]T, len) with direct assignment is faster than make([]T, 0, cap) with append, because direct assignment avoids per-element bounds checking and length increment.",
|
||||
"assertions": [
|
||||
{"id": "5.1", "text": "Suggests using make([]Result, len(input)) with direct assignment result[i] = convert(...)"},
|
||||
{"id": "5.2", "text": "Explains that direct assignment avoids per-element append overhead (bounds check, length increment)"},
|
||||
{"id": "5.3", "text": "Notes that append is better when the result might be smaller (filtering)"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"name": "map-range-double-lookup",
|
||||
"description": "Tests whether the model avoids double map lookups when writing new map iteration code",
|
||||
"prompt": "Write a Go function that counts how many values in a map satisfy a threshold. The map is large (1M entries) and the function is called frequently.\n\n```go\nfunc CountAbove(scores map[string]int, threshold int) int {\n // TODO: implement\n}\n```\n\nWrite the most efficient implementation.",
|
||||
"trap": "The natural/idiomatic instinct when writing map iteration code is to use 'for k := range m { if m[k] > threshold { count++ } }' because it looks clean. This does 2 lookups per iteration. The skill teaches 'for k, v := range m { if v > threshold { count++ } }' for a single lookup. The model will likely write the double-lookup version without the skill prompting it to use the k, v form.",
|
||||
"assertions": [
|
||||
{"id": "6.1", "text": "Uses 'for k, v := range scores' (capturing the value in range) rather than 'for k := range scores { scores[k] }'"},
|
||||
{"id": "6.2", "text": "Does NOT perform a second lookup into the map inside the loop body (i.e., does not use scores[k] inside the loop)"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"name": "sentinel-errors-hot-path",
|
||||
"description": "Tests whether the model avoids fmt.Errorf for static errors in allocation-sensitive hot paths when writing new error-returning code",
|
||||
"prompt": "Write a Go function that parses a configuration value. It must return descriptive errors and will be called thousands of times per second during request processing.\n\n```go\n// parseTimeout parses a timeout string like \"30s\", \"5m\".\n// Returns error if empty, if the unit is unrecognized, or if the value is negative.\nfunc parseTimeout(s string) (time.Duration, error) {\n // TODO: implement\n}\n```\n\nImplement this function.",
|
||||
"trap": "The natural way to write descriptive errors is to use fmt.Errorf for all cases: fmt.Errorf(\"empty timeout\"), fmt.Errorf(\"unrecognized unit %q\", unit), fmt.Errorf(\"negative timeout: %v\", d). The skill teaches that static, predictable errors (like 'empty timeout') should be preallocated sentinels at package level (errors.New) to avoid allocation on every call. Only errors needing dynamic values should use fmt.Errorf. Without the skill the model writes fmt.Errorf for every error case.",
|
||||
"assertions": [
|
||||
{"id": "7.1", "text": "Uses errors.New at package level for the static 'empty string' error case (no dynamic content)"},
|
||||
{"id": "7.2", "text": "Uses fmt.Errorf (or errors.New with dynamic content) for error cases that need to embed runtime values like the unrecognized unit"},
|
||||
{"id": "7.3", "text": "Does NOT use fmt.Errorf for error messages that contain no dynamic values"},
|
||||
{"id": "7.4", "text": "Explains that fmt.Errorf allocates on every call while package-level errors.New allocates once"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"name": "interface-boxing-hot-path",
|
||||
"description": "Tests knowledge of interface boxing allocation cost and the fix using generics or typed parameters",
|
||||
"prompt": "Our Go analytics pipeline processes events at high throughput. Profiling shows unexpectedly high allocation rates in this function:\n\n```go\nfunc SumValues(values []any) float64 {\n var total float64\n for _, v := range values {\n switch n := v.(type) {\n case int:\n total += float64(n)\n case float64:\n total += n\n }\n }\n return total\n}\n```\n\nCallers always pass either all ints or all float64s. How can we reduce allocations?",
|
||||
"trap": "Passing concrete types through any/interface{} forces heap allocation for boxing. The skill teaches using typed parameters or generics. Without it, the model may focus on the type switch optimization rather than the fundamental boxing problem.",
|
||||
"assertions": [
|
||||
{"id": "8.1", "text": "Identifies interface boxing (any parameter) as the source of allocations"},
|
||||
{"id": "8.2", "text": "Suggests typed functions (e.g., SumInts([]int)) or generics (func Sum[T ~int|~float64]([]T)) to eliminate boxing"},
|
||||
{"id": "8.3", "text": "Explains that each concrete value passed through any requires a heap allocation for boxing"},
|
||||
{"id": "8.4", "text": "Does NOT focus only on the type switch as the optimization target"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"name": "backing-array-leak-slice",
|
||||
"description": "Tests whether the model avoids backing array retention when writing a function that stores subslices long-term",
|
||||
"prompt": "Write a Go function that caches the first 16 bytes of each incoming network packet for later audit logging. Packets are large (up to 64KB) and are pooled via sync.Pool — they get reused after the call returns.\n\n```go\nvar auditLog [][]byte\n\nfunc recordPacketPrefix(pkt []byte) {\n // TODO: store first 16 bytes of pkt in auditLog\n}\n```\n\nImplement this function.",
|
||||
"trap": "The obvious, idiomatic implementation is 'auditLog = append(auditLog, pkt[:16])' — a simple reslice. This looks correct but retains the entire 64KB backing array per entry because the subslice shares the original buffer. Since packets come from a sync.Pool and are reused, the retained backing arrays also prevent correct pool behavior. The fix is to copy: 'prefix := make([]byte, 16); copy(prefix, pkt[:16]); auditLog = append(auditLog, prefix)'. Without the skill the model writes the reslice version.",
|
||||
"assertions": [
|
||||
{"id": "9.1", "text": "Does NOT use pkt[:16] directly as the stored value (reslice retains the entire backing array)"},
|
||||
{"id": "9.2", "text": "Creates an independent copy using make([]byte, 16) + copy, or equivalent"},
|
||||
{"id": "9.3", "text": "Explains that storing a reslice retains the entire original backing array, preventing GC"},
|
||||
{"id": "9.4", "text": "Notes the interaction with sync.Pool: retained backing arrays prevent buffer reuse or cause data corruption"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"name": "substring-memory-leak",
|
||||
"description": "Tests knowledge of the strings.Clone pattern for substring memory leaks",
|
||||
"prompt": "Our Go log processing service extracts request IDs from log lines. Memory keeps growing even though we only store short strings. Go 1.20+ project.\n\n```go\nvar requestIDs = make(map[string]time.Time)\n\nfunc ProcessLogLine(line string) {\n // line is typically 500-2000 bytes\n id := line[12:48] // extract 36-char UUID\n requestIDs[id] = time.Now()\n}\n```",
|
||||
"trap": "Substrings share the backing array of the original string. Each 36-char id retains the full 500-2000 byte log line. The skill teaches strings.Clone (Go 1.20+) as the fix. Without it, the model may not know about strings.Clone or may suggest string([]byte(s)) which is also correct but less idiomatic.",
|
||||
"assertions": [
|
||||
{"id": "10.1", "text": "Identifies that substrings share the backing array of the original string"},
|
||||
{"id": "10.2", "text": "Suggests strings.Clone(line[12:48]) to create an independent copy"},
|
||||
{"id": "10.3", "text": "Explains that each 36-char ID retains the entire 500-2000 byte log line in memory"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"name": "map-never-shrinks",
|
||||
"description": "Tests whether the model avoids using a long-lived map for a high-churn cache without addressing bucket retention",
|
||||
"prompt": "Design a Go in-memory rate-limiter that tracks per-IP request counts. Counts reset every minute. At peak there are 500K active IPs, but off-peak only ~200 IPs are active.\n\n```go\ntype RateLimiter struct {\n mu sync.Mutex\n counts map[string]int\n}\n\nfunc NewRateLimiter() *RateLimiter {\n return &RateLimiter{counts: make(map[string]int)}\n}\n\nfunc (r *RateLimiter) reset() {\n r.mu.Lock()\n defer r.mu.Unlock()\n // TODO: implement the per-minute reset\n}\n```\n\nImplement the reset method.",
|
||||
"trap": "The natural, obvious implementation is to range over the map and delete each key: 'for k := range r.counts { delete(r.counts, k) }'. This looks correct and idiomatic but leaves all 500K bucket slots allocated — the map retains its peak allocation forever. The skill teaches that maps never release bucket memory; the fix is to replace the map entirely: 'r.counts = make(map[string]int)'. Without the skill the model writes the delete-loop version.",
|
||||
"assertions": [
|
||||
{"id": "11.1", "text": "Replaces the map with a fresh allocation (r.counts = make(map[string]int)) rather than deleting keys in a loop"},
|
||||
{"id": "11.2", "text": "Does NOT use 'for k := range r.counts { delete(r.counts, k) }' as the reset strategy"},
|
||||
{"id": "11.3", "text": "Explains that Go maps never release bucket memory when keys are deleted, so delete-loop retains peak allocation"},
|
||||
{"id": "11.4", "text": "Notes that reassigning to a new map allows the old bucket array to be GC'd"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"name": "sync-pool-rules",
|
||||
"description": "Tests proper sync.Pool usage: reset before Put, return copies not pooled buffers, size limits",
|
||||
"prompt": "Review this sync.Pool usage in our Go HTTP handler for correctness:\n\n```go\nvar bufPool = sync.Pool{\n New: func() any { return make([]byte, 0, 64*1024) },\n}\n\nfunc HandleRequest(w http.ResponseWriter, r *http.Request) {\n buf := bufPool.Get().([]byte)\n // ... fill buf with response data ...\n buf = append(buf[:0], responseData...)\n w.Write(buf)\n bufPool.Put(buf)\n}\n\nfunc HandleLargeUpload(w http.ResponseWriter, r *http.Request) {\n buf := bufPool.Get().([]byte)\n data, _ := io.ReadAll(r.Body) // could be 100MB+\n buf = append(buf[:0], data...)\n processData(buf)\n bufPool.Put(buf)\n}\n```\n\nIdentify all issues with this pool usage.",
|
||||
"trap": "Multiple issues: (1) HandleRequest returns the pooled buffer directly via w.Write — the caller (net/http) may retain it after Put, (2) HandleLargeUpload puts enormous buffers (100MB+) back into the pool — don't pool objects >32KB, (3) the pool stores []byte values not pointers, which causes an allocation on Get. The skill covers all these rules.",
|
||||
"assertions": [
|
||||
{"id": "12.1", "text": "Identifies that HandleLargeUpload puts oversized buffers (100MB+) back into the pool"},
|
||||
{"id": "12.2", "text": "Mentions the 32KB guideline — don't pool objects larger than ~32KB"},
|
||||
{"id": "12.3", "text": "Identifies that w.Write(buf) may retain the buffer after bufPool.Put(buf) in the same function"},
|
||||
{"id": "12.4", "text": "Suggests pooling pointers (*[]byte) instead of values to avoid allocation on Get"},
|
||||
{"id": "12.5", "text": "Recommends resetting/clearing state before Put to avoid retaining large object graphs"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 13,
|
||||
"name": "struct-field-alignment",
|
||||
"description": "Tests knowledge of struct field ordering for optimal memory layout",
|
||||
"prompt": "Our Go service creates millions of these structs. Memory profiling shows they consume more space than expected. Can we reduce memory usage?\n\n```go\ntype Event struct {\n Active bool\n Timestamp int64\n Priority bool\n UserID int32\n Processed bool\n Score float64\n}\n```\n\nHow large is this struct and can we make it smaller?",
|
||||
"trap": "The struct has poor field alignment. bool (1 byte) followed by int64 (8 bytes) adds 7 bytes of padding. The skill teaches reordering fields largest-to-smallest and using fieldalignment tool. Without it, the model may not compute the correct size or suggest the optimal reordering.",
|
||||
"assertions": [
|
||||
{"id": "13.1", "text": "Identifies that the struct has wasted padding bytes due to alignment"},
|
||||
{"id": "13.2", "text": "Suggests reordering fields from largest to smallest (int64/float64 first, then int32, then bools)"},
|
||||
{"id": "13.3", "text": "Provides a reordered struct that is smaller than the original"},
|
||||
{"id": "13.4", "text": "Mentions the fieldalignment tool for automated detection"},
|
||||
{"id": "13.5", "text": "States alignment requirements (bool=1, int32=4, int64/float64=8)"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 14,
|
||||
"name": "zero-size-field-end-of-struct",
|
||||
"description": "Tests knowledge that struct{} at end of struct adds word-sized padding",
|
||||
"prompt": "We're optimizing memory in our Go event system. This struct is allocated millions of times:\n\n```go\ntype Entry struct {\n Value int64\n Flag struct{}\n}\n```\n\nWe expected it to be 8 bytes (just the int64) since struct{} is zero-size. But unsafe.Sizeof reports 16 bytes. Why?",
|
||||
"trap": "When the last field has zero size (struct{}), the compiler adds word-sized padding (8 bytes on 64-bit) to prevent a pointer to that field from overlapping the next memory block. The fix is to move struct{} to the beginning. This is a very obscure Go internals detail.",
|
||||
"assertions": [
|
||||
{"id": "14.1", "text": "Explains that a zero-size field at the end of a struct causes word-sized padding"},
|
||||
{"id": "14.2", "text": "Explains the reason: preventing a pointer to the zero-size field from overlapping the next memory block"},
|
||||
{"id": "14.3", "text": "Suggests moving struct{} to the beginning of the struct to eliminate the padding"},
|
||||
{"id": "14.4", "text": "Shows the fix: type Entry struct { Flag struct{}; Value int64 } which is 8 bytes"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 15,
|
||||
"name": "map-pointer-vs-value-tradeoff",
|
||||
"description": "Tests knowledge of map[K]*V vs map[K]V tradeoff for large frequently-updated structs",
|
||||
"prompt": "Our Go game server updates player scores frequently. This pattern is inefficient:\n\n```go\ntype Player struct {\n Name string\n Score int\n Level int\n Inventory [256]byte\n Stats [64]float64\n}\n\nvar players = make(map[string]Player)\n\nfunc UpdateScore(id string, delta int) {\n p := players[id]\n p.Score += delta\n players[id] = p // full copy\n}\n```\n\nHow can we optimize the update pattern?",
|
||||
"trap": "Map values are not addressable — you can't do players[id].Score += delta. The copy-modify-reassign pattern copies the entire large struct. Using map[string]*Player allows direct modification. But the skill also teaches the tradeoff: pointer maps add GC pressure from separate heap allocations. Without it, the model may suggest pointers without mentioning the tradeoff.",
|
||||
"assertions": [
|
||||
{"id": "15.1", "text": "Suggests using map[string]*Player to allow direct field modification"},
|
||||
{"id": "15.2", "text": "Explains that map values are not addressable (can't modify in place)"},
|
||||
{"id": "15.3", "text": "Shows players[id].Score += delta with pointer map"},
|
||||
{"id": "15.4", "text": "Mentions the tradeoff: pointer maps add GC pressure from separate heap allocations"},
|
||||
{"id": "15.5", "text": "Notes that for small, mostly-read structs, map[K]V (value) is better"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 16,
|
||||
"name": "inlining-log-in-hot-path",
|
||||
"description": "Tests knowledge that log calls prevent function inlining",
|
||||
"prompt": "This Go helper function is called millions of times per second in a tight loop. The CPU profile shows it takes much more time than expected for such a simple function.\n\n```go\nfunc clamp(val, minVal, maxVal int) int {\n if val < minVal {\n log.Printf(\"clamped %d below minimum %d\", val, minVal)\n return minVal\n }\n if val > maxVal {\n log.Printf(\"clamped %d above maximum %d\", val, maxVal)\n return maxVal\n }\n return val\n}\n```\n\nWhy is this function slow and how do we fix it?",
|
||||
"trap": "The log.Printf calls prevent the compiler from inlining the function. In a tight loop called millions of times, function call overhead is significant. The skill specifically warns about logging in hot loops preventing inlining. Without it, the model may focus on the log formatting cost rather than the inlining prevention.",
|
||||
"assertions": [
|
||||
{"id": "16.1", "text": "Identifies that log calls prevent the function from being inlined by the compiler"},
|
||||
{"id": "16.2", "text": "Suggests removing log calls from the hot-path function or moving them outside"},
|
||||
{"id": "16.3", "text": "Mentions using go build -gcflags=\"-m\" to verify inlining decisions"},
|
||||
{"id": "16.4", "text": "Explains that function call overhead matters when called millions of times in a tight loop"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 17,
|
||||
"name": "value-receiver-inlining",
|
||||
"description": "Tests knowledge that value receivers enable inlining for fluent method chains",
|
||||
"prompt": "We have a Go config builder used in a hot path. Profiling shows the fluent chain is slower than expected:\n\n```go\ntype Config struct {\n timeout time.Duration\n retries int\n verbose bool\n}\n\nfunc (c *Config) WithTimeout(d time.Duration) *Config {\n c.timeout = d\n return c\n}\n\nfunc (c *Config) WithRetries(n int) *Config {\n c.retries = n\n return c\n}\n\nfunc (c *Config) WithVerbose(v bool) *Config {\n c.verbose = v\n return c\n}\n```\n\nThis is called as: `cfg := (&Config{}).WithTimeout(5*time.Second).WithRetries(3).WithVerbose(true)`\n\nHow can we make the fluent chain faster?",
|
||||
"trap": "Pointer receivers add indirection that blocks inlining of fluent method chains. Value receivers allow the compiler to fully inline the chain. The skill quantifies this as -80% time. Without the skill, the model may suggest unrelated optimizations.",
|
||||
"assertions": [
|
||||
{"id": "17.1", "text": "Suggests changing to value receivers instead of pointer receivers"},
|
||||
{"id": "17.2", "text": "Explains that value receivers allow the compiler to inline the fluent chain"},
|
||||
{"id": "17.3", "text": "Explains that pointer receivers add indirection that blocks inlining"},
|
||||
{"id": "17.4", "text": "Shows the value receiver signature: func (c Config) WithTimeout(d time.Duration) Config"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 18,
|
||||
"name": "cache-locality-matrix-traversal",
|
||||
"description": "Tests knowledge of row-major vs column-major traversal and cache effects",
|
||||
"prompt": "This Go matrix computation is unexpectedly slow. The matrix is 4096x4096 float64. CPU profile shows the loop itself (not the computation) is the bottleneck.\n\n```go\nfunc ColumnSum(matrix [4096][4096]float64) [4096]float64 {\n var sums [4096]float64\n for col := 0; col < 4096; col++ {\n for row := 0; row < 4096; row++ {\n sums[col] += matrix[row][col]\n }\n }\n return sums\n}\n```\n\nWhy is this slow and how do we fix it?",
|
||||
"trap": "Column-first traversal on row-major storage causes cache misses on every access. The fix is to swap loop order. The skill quantifies the difference as 10-50x from cache effects alone. Without it, the model may suggest parallelism or SIMD rather than the simple loop reorder.",
|
||||
"assertions": [
|
||||
{"id": "18.1", "text": "Identifies the column-first traversal as the cause (cache misses)"},
|
||||
{"id": "18.2", "text": "Explains that Go stores 2D arrays in row-major order"},
|
||||
{"id": "18.3", "text": "Suggests swapping loop order to row-first (outer loop over rows)"},
|
||||
{"id": "18.4", "text": "Mentions the performance difference from cache effects (10-50x or similar magnitude)"},
|
||||
{"id": "18.5", "text": "Does NOT primarily suggest parallelism or SIMD as the first fix"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 19,
|
||||
"name": "contiguous-2d-allocation",
|
||||
"description": "Tests whether the model uses contiguous allocation when writing new 2D matrix code for a performance-critical context",
|
||||
"prompt": "Write a Go function that creates an NxM grid of float64 values initialized to zero, for use in a finite-element simulation that iterates row by row over the grid millions of times per second.\n\n```go\nfunc NewGrid(rows, cols int) [][]float64 {\n // TODO\n}\n```\n\nImplement this function.",
|
||||
"trap": "The standard idiomatic Go way to create a 2D slice is the row-by-row allocation loop: make([][]float64, rows) followed by make([]float64, cols) per row. Every Go tutorial and example uses this pattern. However for performance-critical numeric code the skill teaches a single contiguous allocation (make([]float64, rows*cols)) sliced into row views, which has far better cache locality. Without the skill the model writes the idiomatic per-row allocation.",
|
||||
"assertions": [
|
||||
{"id": "19.1", "text": "Allocates a single contiguous backing slice: make([]float64, rows*cols)"},
|
||||
{"id": "19.2", "text": "Slices it into row views: data[i*cols : (i+1)*cols]"},
|
||||
{"id": "19.3", "text": "Does NOT allocate each row independently with a separate make([]float64, cols) call"},
|
||||
{"id": "19.4", "text": "Explains that contiguous allocation improves cache locality for row-sequential access"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 20,
|
||||
"name": "soa-vs-aos",
|
||||
"description": "Tests knowledge of Struct of Arrays vs Array of Structs for single-field iteration",
|
||||
"prompt": "Our Go physics simulation iterates over millions of particles but only reads the X coordinate for collision detection in the first pass:\n\n```go\ntype Particle struct {\n X, Y, Z float64\n VX, VY, VZ float64\n Mass float64\n Radius float64\n}\n\nvar particles []Particle // millions of elements\n\nfunc FindCollisionCandidates() []int {\n var candidates []int\n for i := range particles {\n if particles[i].X > threshold {\n candidates = append(candidates, i)\n }\n }\n return candidates\n}\n```\n\nCPU profile shows this loop is slow. We only need the X field in this pass. How can we speed it up?",
|
||||
"trap": "Loading each 64-byte Particle to read only X (8 bytes) wastes 87.5% of cache space. The skill teaches SoA (Struct of Arrays) where all X values are contiguous for 100% cache utilization. Without it, the model may suggest parallelism or preallocation rather than the data layout change.",
|
||||
"assertions": [
|
||||
{"id": "20.1", "text": "Identifies that loading entire Particle structs wastes cache space when only X is needed"},
|
||||
{"id": "20.2", "text": "Suggests Struct of Arrays (SoA) layout with separate slices for X, Y, Z, etc."},
|
||||
{"id": "20.3", "text": "Explains cache utilization improvement (contiguous X values vs scattered across structs)"},
|
||||
{"id": "20.4", "text": "Notes that AoS is fine when accessing all fields together or for small structs"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 21,
|
||||
"name": "false-sharing-concurrent-counters",
|
||||
"description": "Tests knowledge of false sharing and cache-line padding",
|
||||
"prompt": "Our Go service has per-goroutine counters that are updated concurrently. Adding more goroutines makes it SLOWER, not faster. Profiling shows atomic operations on counters consuming unexpectedly high CPU.\n\n```go\ntype Metrics struct {\n RequestCount int64\n ErrorCount int64\n BytesRead int64\n BytesWritten int64\n}\n\nvar metrics Metrics\n\n// Each goroutine increments different counters concurrently\nfunc recordRequest(bytes int64) {\n atomic.AddInt64(&metrics.RequestCount, 1)\n atomic.AddInt64(&metrics.BytesRead, bytes)\n}\n\nfunc recordError(bytes int64) {\n atomic.AddInt64(&metrics.ErrorCount, 1)\n atomic.AddInt64(&metrics.BytesWritten, bytes)\n}\n```\n\nWhy does adding goroutines make it slower?",
|
||||
"trap": "All four int64 fields fit within a single 64-byte cache line. When different goroutines update different fields, each write invalidates the other core's cache line (false sharing). The fix is cache-line padding. Without the skill, the model may suggest mutexes or sharding rather than identifying false sharing.",
|
||||
"assertions": [
|
||||
{"id": "21.1", "text": "Identifies false sharing as the cause (fields share the same cache line)"},
|
||||
{"id": "21.2", "text": "Explains that writes to one field invalidate the cache line for other cores"},
|
||||
{"id": "21.3", "text": "Suggests cache-line padding (56-byte [56]byte array between fields) to separate cache lines"},
|
||||
{"id": "21.4", "text": "Mentions the 64-byte cache line size"},
|
||||
{"id": "21.5", "text": "Notes this should only be applied when profiling confirms contention"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 22,
|
||||
"name": "ilp-multi-accumulator",
|
||||
"description": "Tests knowledge of instruction-level parallelism with multiple accumulators",
|
||||
"prompt": "This Go function sums a large float64 slice (10M elements). Profiling shows it's CPU-bound with the loop body consuming most of the time. The computation is simple addition — how can we speed it up without parallelizing across goroutines?\n\n```go\nfunc Sum(data []float64) float64 {\n var total float64\n for _, v := range data {\n total += v\n }\n return total\n}\n```",
|
||||
"trap": "The single accumulator creates a dependency chain — each addition waits for the previous one. The skill teaches using 4 independent accumulators to exploit CPU instruction-level parallelism (2-4x improvement). Without it, the model may suggest SIMD or goroutine-based parallelism rather than the simpler multi-accumulator approach.",
|
||||
"assertions": [
|
||||
{"id": "22.1", "text": "Identifies the sequential dependency chain as the bottleneck (each addition waits for the previous)"},
|
||||
{"id": "22.2", "text": "Suggests using multiple accumulators (e.g., 4) for instruction-level parallelism"},
|
||||
{"id": "22.3", "text": "Shows code with 4 independent accumulators summing every 4th element"},
|
||||
{"id": "22.4", "text": "Handles the remainder elements (when len(data) is not divisible by 4)"},
|
||||
{"id": "22.5", "text": "Mentions expected 2-4x improvement from ILP"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 23,
|
||||
"name": "index-based-tree-cache-locality",
|
||||
"description": "Tests whether the model uses index-based node storage when implementing a high-performance tree from scratch",
|
||||
"prompt": "Implement a Go binary search tree for a high-throughput in-memory lookup service. The tree will hold ~1M integer keys and be traversed millions of times per second. Write the node and tree type definitions and the Insert method.\n\n```go\n// TODO: define types and implement Insert\n```",
|
||||
"trap": "Every Go tutorial, textbook, and LeetCode solution defines a binary tree with pointer-based nodes: 'type Node struct { Value int; Left, Right *Node }'. This is the universal default. However the skill teaches that pointer-based trees scatter each node across the heap causing random cache misses on every traversal. For high-throughput lookup the correct approach is index-based nodes stored in a contiguous slice: 'type Node struct { Value, Left, Right int }' inside a Tree struct with a Nodes []Node backing array. Without the skill the model writes the pointer-based version.",
|
||||
"assertions": [
|
||||
{"id": "23.1", "text": "Stores nodes in a contiguous slice (e.g., Nodes []Node field on the tree struct)"},
|
||||
{"id": "23.2", "text": "Uses integer indices (not pointers) for left/right child references"},
|
||||
{"id": "23.3", "text": "Does NOT define nodes with *Node pointer fields as the primary implementation"},
|
||||
{"id": "23.4", "text": "Explains that index-based nodes stay in contiguous memory, reducing cache misses compared to scattered heap pointers"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 24,
|
||||
"name": "tight-loop-scheduler-starvation",
|
||||
"description": "Tests knowledge of tight CPU loops starving the Go scheduler",
|
||||
"prompt": "Our Go service has a CPU-intensive computation goroutine that runs for several seconds. Other goroutines (HTTP handlers) become unresponsive during the computation, even though GOMAXPROCS is set to 4.\n\n```go\nfunc heavyCompute(data []float64) float64 {\n var result float64\n for i := 0; i < len(data); i++ {\n result = result*0.99 + data[i]*0.01\n }\n return result\n}\n```\n\nThe data slice has 100M elements. Why are other goroutines starved?",
|
||||
"trap": "A tight CPU loop with fully inlined operations may not yield to the scheduler, despite Go 1.14+ async preemption. The skill teaches using non-inlined function calls as preemption points, or //go:noinline. Without it, the model may suggest runtime.Gosched() (which works but isn't the recommended approach) or parallelism.",
|
||||
"assertions": [
|
||||
{"id": "24.1", "text": "Explains that tight CPU loops with inlined operations can delay scheduler preemption"},
|
||||
{"id": "24.2", "text": "Suggests breaking the work into batches processed by a non-inlined function call"},
|
||||
{"id": "24.3", "text": "Mentions //go:noinline as an option to force preemption points"},
|
||||
{"id": "24.4", "text": "Explains the tradeoff: //go:noinline adds function call overhead but ensures scheduler fairness"},
|
||||
{"id": "24.5", "text": "Mentions that Go 1.14+ has async preemption but tight loops with inlined ops can still cause issues"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 25,
|
||||
"name": "reflect-deepequal-performance",
|
||||
"description": "Tests knowledge of reflect.DeepEqual being 50-200x slower than typed comparisons",
|
||||
"prompt": "Review this Go function for performance. It compares two configuration objects for equality in a hot path (called on every request):\n\n```go\nfunc ConfigChanged(old, new Config) bool {\n return !reflect.DeepEqual(old, new)\n}\n\ntype Config struct {\n Hosts []string\n Settings map[string]string\n Timeout int\n Debug bool\n}\n```",
|
||||
"trap": "reflect.DeepEqual is 50-200x slower than typed comparison. The skill specifically calls this out as a common mistake and recommends slices.Equal, maps.Equal for the structured fields. Without it, the model may say it's fine or suggest a less specific alternative.",
|
||||
"assertions": [
|
||||
{"id": "25.1", "text": "Identifies reflect.DeepEqual as 50-200x slower than typed comparison"},
|
||||
{"id": "25.2", "text": "Suggests using slices.Equal for the Hosts field"},
|
||||
{"id": "25.3", "text": "Suggests using maps.Equal for the Settings field"},
|
||||
{"id": "25.4", "text": "Provides a hand-written typed comparison function"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 26,
|
||||
"name": "type-switch-vs-repeated-assertions",
|
||||
"description": "Tests whether the model uses a type switch (not repeated assertions) when writing new interface dispatch code for a hot path",
|
||||
"prompt": "Write a Go function that formats any scalar value as a string for a high-throughput metrics labeling system. It must handle string, int, int64, float64, and bool. Called ~500K times/sec.\n\n```go\nfunc FormatLabel(v any) string {\n // TODO\n}\n```\n\nImplement this function.",
|
||||
"trap": "The natural way many Go developers write multi-type dispatch is a chain of if-assertions: 'if s, ok := v.(string); ok { return s }' etc. — it looks clear and matches the pattern from many examples. A type switch 'switch v := v.(type) { case string: ... }' dispatches in a single evaluation of the interface type and is the correct pattern for hot paths. Without the skill the model may write the if-chain of repeated assertions, evaluating the interface type multiple times.",
|
||||
"assertions": [
|
||||
{"id": "26.1", "text": "Uses a type switch (switch v := v.(type)) rather than a chain of individual if-assertions"},
|
||||
{"id": "26.2", "text": "Does NOT use repeated v.(T) comma-ok assertions in separate if-blocks"},
|
||||
{"id": "26.3", "text": "Handles all required types: string, int (or int64), float64, and bool in the switch cases"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 27,
|
||||
"name": "http-transport-maxidleconnsperhost",
|
||||
"description": "Tests knowledge that default http.Client MaxIdleConnsPerHost is only 2",
|
||||
"prompt": "Our Go microservice calls an upstream API with high concurrency (200 goroutines making requests simultaneously). Under load, we see many TCP connections being created and destroyed. Why doesn't connection pooling work?\n\n```go\nvar client = &http.Client{\n Timeout: 30 * time.Second,\n}\n\nfunc CallAPI(ctx context.Context, id string) ([]byte, error) {\n resp, err := client.Get(fmt.Sprintf(\"https://api.example.com/v1/items/%s\", id))\n if err != nil {\n return nil, err\n }\n defer resp.Body.Close()\n return io.ReadAll(resp.Body)\n}\n```",
|
||||
"trap": "The default http.Transport has MaxIdleConnsPerHost=2. With 200 concurrent goroutines, 198 connections are created and destroyed for each request. The skill specifically calls this out as a common mistake. Without it, the model may suggest connection pool libraries instead of tuning the built-in transport.",
|
||||
"assertions": [
|
||||
{"id": "27.1", "text": "Identifies MaxIdleConnsPerHost defaulting to 2 as the root cause"},
|
||||
{"id": "27.2", "text": "Suggests configuring http.Transport with higher MaxIdleConnsPerHost (e.g., 20-100)"},
|
||||
{"id": "27.3", "text": "Shows complete Transport configuration with MaxIdleConns, MaxIdleConnsPerHost, and MaxConnsPerHost"},
|
||||
{"id": "27.4", "text": "Mentions draining resp.Body for connection reuse (io.Copy to io.Discard)"},
|
||||
{"id": "27.5", "text": "Does NOT suggest using a third-party connection pool library as the primary solution"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 28,
|
||||
"name": "response-body-drain",
|
||||
"description": "Tests whether the model drains the response body when writing a new HTTP health-check function",
|
||||
"prompt": "Write a Go function that polls a list of service endpoints and returns which ones are healthy (HTTP 200). It will run every 5 seconds against ~50 endpoints with a shared http.Client.\n\n```go\nfunc CheckHealthy(client *http.Client, urls []string) []string {\n // TODO: return URLs that respond with 200\n}\n```\n\nImplement this function.",
|
||||
"trap": "The natural implementation closes the body with 'defer resp.Body.Close()' and reads the status code — which looks correct and complete. Most developers do not know that the transport only returns the connection to the pool after the body is fully consumed. Without draining via 'io.Copy(io.Discard, resp.Body)', each health check creates a new TCP connection and the 50-endpoint poll exhausts the connection pool. Without the skill the model writes the close-only version.",
|
||||
"assertions": [
|
||||
{"id": "28.1", "text": "Drains the response body using io.Copy(io.Discard, resp.Body) or io.ReadAll before closing"},
|
||||
{"id": "28.2", "text": "Does NOT only call resp.Body.Close() without first reading/draining the body"},
|
||||
{"id": "28.3", "text": "Explains that connections are only returned to the pool after the body is fully consumed"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 29,
|
||||
"name": "streaming-vs-readall",
|
||||
"description": "Tests knowledge of streaming vs buffering for large payloads",
|
||||
"prompt": "Our Go service proxies file downloads. Under load with large files (1-5GB), the service runs out of memory and gets OOM killed.\n\n```go\nfunc ProxyDownload(w http.ResponseWriter, r *http.Request) {\n resp, err := http.Get(upstreamURL + r.URL.Path)\n if err != nil {\n http.Error(w, \"upstream error\", 502)\n return\n }\n defer resp.Body.Close()\n\n data, err := io.ReadAll(resp.Body)\n if err != nil {\n http.Error(w, \"read error\", 500)\n return\n }\n\n w.Header().Set(\"Content-Type\", resp.Header.Get(\"Content-Type\"))\n w.Write(data)\n}\n```",
|
||||
"trap": "io.ReadAll loads the entire response into memory. For a 5GB file, that's a 5GB allocation. The fix is io.Copy which streams with a 32KB buffer. The skill specifically warns about io.ReadAll for large payloads.",
|
||||
"assertions": [
|
||||
{"id": "29.1", "text": "Identifies io.ReadAll as the cause of OOM (loads entire file into memory)"},
|
||||
{"id": "29.2", "text": "Suggests using io.Copy(w, resp.Body) to stream with constant memory"},
|
||||
{"id": "29.3", "text": "Mentions the 32KB internal buffer of io.Copy"},
|
||||
{"id": "29.4", "text": "Notes that io.ReadAll is fine for small, bounded payloads (< 1MB)"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 30,
|
||||
"name": "json-streaming-decoder",
|
||||
"description": "Tests knowledge of json.NewDecoder for streaming large JSON payloads",
|
||||
"prompt": "Our Go API receives large JSON arrays (10K-100K items). Memory spikes during unmarshaling cause GC pressure.\n\n```go\nfunc HandleBulkImport(w http.ResponseWriter, r *http.Request) {\n data, _ := io.ReadAll(r.Body)\n var items []Item\n if err := json.Unmarshal(data, &items); err != nil {\n http.Error(w, err.Error(), 400)\n return\n }\n for _, item := range items {\n processItem(item)\n }\n}\n```\n\nHow can we reduce memory usage while processing the same JSON input?",
|
||||
"trap": "json.Unmarshal buffers the entire body. json.NewDecoder streams tokens. The skill teaches the decoder.More() + decoder.Decode() pattern for processing one item at a time. Without it, the model may suggest chunking or pagination rather than streaming JSON.",
|
||||
"assertions": [
|
||||
{"id": "30.1", "text": "Suggests using json.NewDecoder with r.Body directly (no io.ReadAll)"},
|
||||
{"id": "30.2", "text": "Shows the dec.More() + dec.Decode(&item) streaming pattern"},
|
||||
{"id": "30.3", "text": "Explains that this processes one item at a time with O(1) memory per item"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 31,
|
||||
"name": "cgo-overhead-tight-loop",
|
||||
"description": "Tests knowledge of cgo call overhead (~50-100ns per crossing) and batching strategy",
|
||||
"prompt": "Our Go numerical library calls a C function for each element. Profiling shows the cgo calls dominate execution time even though the C function itself is simple.\n\n```go\n/*\n#include <math.h>\n*/\nimport \"C\"\n\nfunc TransformAll(values []float64) {\n for i, v := range values {\n values[i] = float64(C.sqrt(C.double(v)))\n }\n}\n```\n\nHow can we optimize this?",
|
||||
"trap": "Each cgo call costs ~50-100ns due to stack switching. For math.Sqrt, the pure Go stdlib is equally fast and inlineable. For unavoidable C code, batch the call. The skill teaches both approaches. Without it, the model may not know the cgo overhead magnitude or suggest batching.",
|
||||
"assertions": [
|
||||
{"id": "31.1", "text": "Identifies cgo overhead (~50-100ns per call) as the bottleneck in the tight loop"},
|
||||
{"id": "31.2", "text": "Suggests using math.Sqrt (pure Go, inlineable) instead of C.sqrt"},
|
||||
{"id": "31.3", "text": "For unavoidable C code, suggests batching: pass the entire array to C in one call"},
|
||||
{"id": "31.4", "text": "Mentions that goroutine is pinned to OS thread during cgo calls"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 32,
|
||||
"name": "gogc-gomemlimit-container",
|
||||
"description": "Tests knowledge of GOMEMLIMIT for containerized applications",
|
||||
"prompt": "Our Go service runs in a Kubernetes pod with 512MB memory limit. It periodically gets OOM killed even though heap usage appears to be only 200MB when checked via runtime.MemStats.Alloc.\n\nHow should we configure the Go runtime for this container?",
|
||||
"trap": "The service needs GOMEMLIMIT set to ~80-90% of container memory (400-450MiB). Without it, the GC doesn't know about the container limit and may let the heap grow too large. The skill specifically calls this out as a common mistake ('No GC tuning in containers'). Without it, the model may suggest GOGC tuning alone.",
|
||||
"assertions": [
|
||||
{"id": "32.1", "text": "Recommends setting GOMEMLIMIT to 80-90% of the container memory limit (400-450MiB)"},
|
||||
{"id": "32.2", "text": "Explains that the GC needs GOMEMLIMIT to know about the container's memory ceiling"},
|
||||
{"id": "32.3", "text": "Shows the GOMEMLIMIT=450MiB environment variable or debug.SetMemoryLimit equivalent"},
|
||||
{"id": "32.4", "text": "Explains the gap between Alloc and container limit (goroutine stacks, OS buffers, non-heap memory)"},
|
||||
{"id": "32.5", "text": "Does NOT recommend the ballast pattern (obsolete since Go 1.19)"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 33,
|
||||
"name": "ballast-pattern-obsolete",
|
||||
"description": "Tests whether the model avoids the ballast pattern and uses GOMEMLIMIT when configuring GC for a new service",
|
||||
"prompt": "We're deploying a new Go 1.22 service in a Kubernetes pod with 2GB memory limit. The service is allocation-heavy during bursts and we want to reduce GC frequency to avoid latency spikes. A senior engineer suggested allocating a large byte array at startup to inflate the live heap. How should we configure the runtime?\n\n```go\nfunc main() {\n // TODO: configure GC behavior\n startServer()\n}\n```",
|
||||
"trap": "The suggestion to 'allocate a large byte array at startup' is a direct hint toward the ballast pattern, which was the standard advice before Go 1.19. A model without the skill may implement it as suggested: 'var ballast = make([]byte, 1<<30)'. The skill explicitly teaches that the ballast pattern is obsolete since Go 1.19 — GOMEMLIMIT is strictly better because it achieves the same reduction in GC frequency without wasting physical memory. Without the skill the model follows the senior engineer's suggestion and implements the ballast.",
|
||||
"assertions": [
|
||||
{"id": "33.1", "text": "Does NOT implement the ballast pattern (large byte array allocation at startup)"},
|
||||
{"id": "33.2", "text": "Recommends setting GOMEMLIMIT (e.g., GOMEMLIMIT=1800MiB or debug.SetMemoryLimit)"},
|
||||
{"id": "33.3", "text": "Explains that the ballast pattern is obsolete since Go 1.19"},
|
||||
{"id": "33.4", "text": "Explains that GOMEMLIMIT provides the same GC-frequency benefit without wasting physical memory"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 34,
|
||||
"name": "gomaxprocs-container-go125",
|
||||
"description": "Tests knowledge of Go 1.25+ container-aware GOMAXPROCS vs automaxprocs",
|
||||
"prompt": "Our Go service runs in a container with 2 CPU cores on a 64-core host. We're on Go 1.25. A colleague suggested adding `go.uber.org/automaxprocs`. Is that necessary?\n\n```go\nimport _ \"go.uber.org/automaxprocs\"\n\nfunc main() {\n startServer()\n}\n```",
|
||||
"trap": "Go 1.25+ automatically detects container CPU limits (cgroup v1/v2). automaxprocs is unnecessary. For Go 1.24 and earlier, it IS needed. The skill makes this version-dependent distinction clear.",
|
||||
"assertions": [
|
||||
{"id": "34.1", "text": "States that Go 1.25+ automatically detects container CPU limits"},
|
||||
{"id": "34.2", "text": "Recommends removing the automaxprocs dependency"},
|
||||
{"id": "34.3", "text": "Mentions that automaxprocs IS needed for Go 1.24 and earlier"},
|
||||
{"id": "34.4", "text": "Mentions cgroup CPU quota detection as the mechanism"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 35,
|
||||
"name": "pgo-workflow",
|
||||
"description": "Tests knowledge of Profile-Guided Optimization workflow and expected gains",
|
||||
"prompt": "We want to improve our Go service's performance with minimal code changes. The service is interface-heavy with many small methods. We're on Go 1.22. What low-effort optimization can we apply?",
|
||||
"trap": "PGO (Profile-Guided Optimization) gives 2-7% improvement with minimal effort: collect production profile, save as default.pgo, rebuild. The skill specifically describes when PGO helps most (interface calls, hot inlining). Without it, the model may suggest code-level optimizations rather than the build-level PGO approach.",
|
||||
"assertions": [
|
||||
{"id": "35.1", "text": "Recommends Profile-Guided Optimization (PGO)"},
|
||||
{"id": "35.2", "text": "Describes the workflow: collect production CPU profile, save as default.pgo, rebuild"},
|
||||
{"id": "35.3", "text": "Mentions expected improvement of 2-7%"},
|
||||
{"id": "35.4", "text": "Explains PGO benefits: more aggressive inlining and devirtualization of interface calls"},
|
||||
{"id": "35.5", "text": "Notes that profiles should be refreshed after significant code changes"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 36,
|
||||
"name": "slog-logattrs-hot-path",
|
||||
"description": "Tests knowledge of slog.LogAttrs for zero-allocation logging when level is disabled",
|
||||
"prompt": "Profiling shows our Go service's Debug logging allocates memory even though Debug level is disabled in production. We're using slog.\n\n```go\nfunc processItem(ctx context.Context, item Item) {\n slog.Debug(\"processing item\",\n \"id\", item.ID,\n \"name\", item.Name,\n \"data\", item.Data, // item.Data is a large struct\n )\n // ... actual processing ...\n}\n```\n\nWhy does disabled logging still allocate, and how do we fix it?",
|
||||
"trap": "Even with slog, arguments are evaluated before the level check. The 'data' field is boxed into any, allocating. The skill teaches slog.LogAttrs with typed attributes (slog.Int, slog.String) for zero allocations when the level is disabled. Without it, the model may suggest level checks or not know about LogAttrs.",
|
||||
"assertions": [
|
||||
{"id": "36.1", "text": "Explains that log arguments are evaluated/boxed before the level check"},
|
||||
{"id": "36.2", "text": "Recommends slog.LogAttrs for zero allocations when level is disabled"},
|
||||
{"id": "36.3", "text": "Shows typed attributes: slog.Int(\"id\", item.ID), slog.String(\"name\", item.Name)"},
|
||||
{"id": "36.4", "text": "Notes that slog.Any can still allocate even with slog, so typed attributes are preferred"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 37,
|
||||
"name": "regexp-compile-per-call",
|
||||
"description": "Tests knowledge of compiled pattern caching vs per-call compilation",
|
||||
"prompt": "Profiling shows our Go validation function has high CPU usage from regexp:\n\n```go\nfunc ValidateEmail(email string) bool {\n re := regexp.MustCompile(`^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}$`)\n return re.MatchString(email)\n}\n\nfunc ValidatePhone(phone string) bool {\n re := regexp.MustCompile(`^\\+?[1-9]\\d{1,14}$`)\n return re.MatchString(phone)\n}\n```\n\nBoth functions are called thousands of times per second.",
|
||||
"trap": "regexp.Compile/MustCompile parses the pattern into a state machine (~5,700ns) on every call. The match itself is ~450ns. The skill quantifies the 10-12x waste. Fix: compile at package level. Without the skill, the model may suggest simpler regex or string operations instead of caching.",
|
||||
"assertions": [
|
||||
{"id": "37.1", "text": "Identifies that regexp compilation happens on every call (~5,700ns per compile)"},
|
||||
{"id": "37.2", "text": "Suggests moving regexp.MustCompile to package-level variables"},
|
||||
{"id": "37.3", "text": "Notes that compiled regexps are safe for concurrent use"},
|
||||
{"id": "37.4", "text": "Quantifies the waste (10-12x overhead from recompilation vs match-only)"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 38,
|
||||
"name": "singleflight-cache-stampede",
|
||||
"description": "Tests whether the model uses singleflight (not a mutex) when writing a new cache-with-fetch function serving high concurrency",
|
||||
"prompt": "Write a Go function that fetches and caches country metadata (name, currency, timezone). The cache has a 10-minute TTL. The service handles 2000 req/s with ~50 unique countries. Implement GetCountry.\n\n```go\nvar cache sync.Map\n\nfunc GetCountry(code string) (Country, error) {\n // TODO: check cache, fetch from API if missing, store result\n}\n\nfunc fetchFromAPI(code string) (Country, error) { /* external call, ~200ms */ }\n```",
|
||||
"trap": "The natural implementation is a simple cache-aside: load from cache, on miss fetch from API, store result. This is what every cache tutorial shows. Under 2000 req/s with 200ms fetch latency, a cache miss for any country causes 400 concurrent goroutines to all call fetchFromAPI for the same key simultaneously — a cache stampede. The fix requires singleflight.Group so only one goroutine fetches per key while others wait and share the result. A mutex would serialize all countries, not just the same one. Without the skill the model writes the naive cache-aside without stampede protection.",
|
||||
"assertions": [
|
||||
{"id": "38.1", "text": "Uses singleflight.Group (golang.org/x/sync/singleflight) to deduplicate concurrent fetches for the same key"},
|
||||
{"id": "38.2", "text": "Does NOT use a global mutex that would serialize requests for different country codes"},
|
||||
{"id": "38.3", "text": "Shows the sf.Do(code, func) pattern so concurrent requests for the same key share one fetch"},
|
||||
{"id": "38.4", "text": "Explains that without singleflight, a cache miss causes all concurrent waiters to call the API simultaneously"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 39,
|
||||
"name": "algorithmic-complexity-slice-contains-loop",
|
||||
"description": "Tests knowledge of algorithmic complexity traps (O(n*m) from slices.Contains in a loop)",
|
||||
"prompt": "This Go function checks which requested IDs are valid. It's slow when both lists are large (10K items each).\n\n```go\nfunc FilterValid(requested []string, valid []string) []string {\n var result []string\n for _, id := range requested {\n if slices.Contains(valid, id) {\n result = append(result, id)\n }\n }\n return result\n}\n```\n\nOptimize for large inputs.",
|
||||
"trap": "slices.Contains in a loop creates O(n*m) complexity. The skill teaches building a map[T]struct{} first for O(n+m). Without it, the model may suggest sorting + binary search (O(n log n)) rather than the optimal map approach.",
|
||||
"assertions": [
|
||||
{"id": "39.1", "text": "Identifies O(n*m) complexity from slices.Contains inside a loop"},
|
||||
{"id": "39.2", "text": "Suggests building a map[string]struct{} from the valid slice first"},
|
||||
{"id": "39.3", "text": "Shows the O(n+m) solution with map lookup"},
|
||||
{"id": "39.4", "text": "Uses struct{} (0 bytes) for the map value type, not bool"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 40,
|
||||
"name": "early-return-full-scan",
|
||||
"description": "Tests whether the model uses early return when writing a new existence-check loop over a large collection",
|
||||
"prompt": "Write a Go function that checks whether any order in a large list has been flagged for fraud review. Orders are checked on every API request; the slice typically holds 50,000+ entries.\n\n```go\ntype Order struct {\n ID string\n FraudScore float64\n // ...\n}\n\nfunc HasFraudulentOrder(orders []Order, threshold float64) bool {\n // TODO\n}\n```\n\nImplement this function.",
|
||||
"trap": "When asked to write a boolean existence check, many developers reach for the accumulator pattern: 'found := false; for _, o := range orders { if o.FraudScore > threshold { found = true } }; return found'. This always scans all 50K entries even when the very first entry matches. The correct approach returns immediately on the first match. Without the skill explicitly teaching early-return as a performance pattern, the model may write the full-scan accumulator version, especially since it is a common pattern in introductory Go code.",
|
||||
"assertions": [
|
||||
{"id": "40.1", "text": "Returns true immediately upon finding the first matching order (early return inside the loop)"},
|
||||
{"id": "40.2", "text": "Does NOT use an accumulator variable (found := false) that defers the return until after the full loop"},
|
||||
{"id": "40.3", "text": "Returns false after the loop without having scanned entries unnecessarily past the first match"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 41,
|
||||
"name": "iterator-chain-vs-direct-loop",
|
||||
"description": "Tests whether the model avoids iterator chains and writes a direct loop for a hot-path find-first operation",
|
||||
"prompt": "Write a Go function for a hot path (~1M calls/sec) that finds the first active user with a given role from a slice. Use whatever approach you think is most appropriate.\n\n```go\ntype User struct {\n ID string\n Role string\n Active bool\n}\n\nfunc FindFirstActiveWithRole(users []User, role string) (User, bool) {\n // TODO\n}\n```\n\nImplement this function.",
|
||||
"trap": "Modern Go code with samber/lo or standard library functional helpers makes it tempting to write: 'return lo.First(lo.Filter(users, func(u User) bool { return u.Active && u.Role == role }))'. This is idiomatic, concise, and readable — and it is what many developers reach for. However Filter processes ALL elements before First picks one, and each closure call has function-call overhead. In a hot path the direct loop is significantly faster: it short-circuits on first match and has no closure overhead. Without the skill the model may use the iterator-chain style since it looks clean and modern.",
|
||||
"assertions": [
|
||||
{"id": "41.1", "text": "Uses a direct for-loop with an early return/break rather than chained Filter+First (or equivalent iterator helpers)"},
|
||||
{"id": "41.2", "text": "Does NOT call a Filter-style function that processes all elements before returning the first match"},
|
||||
{"id": "41.3", "text": "Returns immediately upon finding the first matching user (short-circuit)"},
|
||||
{"id": "41.4", "text": "Explains that iterator chains process all elements and add closure overhead, while a direct loop short-circuits"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 42,
|
||||
"name": "indirect-function-calls-closure",
|
||||
"description": "Tests knowledge that closure indirection prevents inlining in generic wrappers",
|
||||
"prompt": "We profiled our Go utility library and found this wrapper function is slower than expected:\n\n```go\nfunc DereferenceAll[T any](ptrs []*T) []T {\n return Map(ptrs, func(p *T) T { return *p })\n}\n\nfunc Map[T, R any](items []T, fn func(T) R) []R {\n result := make([]R, len(items))\n for i := range items {\n result[i] = fn(items[i])\n }\n return result\n}\n```\n\nHow can we make DereferenceAll faster?",
|
||||
"trap": "The closure passed to Map prevents inlining at the call site. The skill teaches replacing indirect function calls (Map + closure) with direct loops for 13-17% improvement. Without it, the model may not know that the closure indirection is the bottleneck.",
|
||||
"assertions": [
|
||||
{"id": "42.1", "text": "Suggests replacing the Map+closure pattern with a direct loop"},
|
||||
{"id": "42.2", "text": "Explains that the closure/function call indirection prevents inlining"},
|
||||
{"id": "42.3", "text": "Shows the direct loop: result[i] = *ptrs[i]"},
|
||||
{"id": "42.4", "text": "Mentions the expected improvement range (13-17% or similar)"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 43,
|
||||
"name": "http-server-no-timeouts",
|
||||
"description": "Tests whether the model sets timeouts when writing a new HTTP server from scratch",
|
||||
"prompt": "Write the main function for a Go HTTP API server that listens on port 8080 and serves two routes: POST /ingest and GET /health.\n\n```go\nfunc main() {\n // TODO: set up and start the HTTP server\n}\n```\n\nImplement this.",
|
||||
"trap": "The idiomatic, minimal Go HTTP server that every tutorial shows is: 'http.HandleFunc(...); http.ListenAndServe(\":8080\", nil)'. This is the first result for 'Go http server example' and what most developers write by default. It uses the zero-value DefaultServeMux with no timeouts — a slow or malicious client can hold connections open indefinitely, exhausting file descriptors. The correct approach creates an explicit http.Server{} with ReadTimeout, WriteTimeout, and IdleTimeout. Without the skill the model writes the default ListenAndServe shortcut.",
|
||||
"assertions": [
|
||||
{"id": "43.1", "text": "Creates an explicit http.Server struct rather than calling http.ListenAndServe directly"},
|
||||
{"id": "43.2", "text": "Sets ReadTimeout on the server"},
|
||||
{"id": "43.3", "text": "Sets WriteTimeout on the server"},
|
||||
{"id": "43.4", "text": "Sets IdleTimeout on the server"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 44,
|
||||
"name": "http-keepalive-crawler",
|
||||
"description": "Tests knowledge of disabling keep-alive for crawlers hitting many hosts",
|
||||
"prompt": "Our Go web crawler scrapes 100,000 different domains. After running for a while, it runs out of file descriptors. The crawler uses an http.Client with tuned Transport:\n\n```go\nvar crawlerClient = &http.Client{\n Timeout: 10 * time.Second,\n Transport: &http.Transport{\n MaxIdleConns: 1000,\n MaxIdleConnsPerHost: 10,\n IdleConnTimeout: 90 * time.Second,\n },\n}\n```\n\nWhy does it exhaust file descriptors?",
|
||||
"trap": "For crawlers hitting many different hosts, idle connections accumulate because MaxIdleConns caps total idle connections but each host has up to 10 idle. With 100K hosts, connections pile up. The skill teaches DisableKeepAlives: true for this use case. Without it, the model may suggest lowering MaxIdleConnsPerHost instead of disabling keep-alive entirely.",
|
||||
"assertions": [
|
||||
{"id": "44.1", "text": "Identifies that idle connections accumulate across many different hosts"},
|
||||
{"id": "44.2", "text": "Suggests DisableKeepAlives: true for the crawler client"},
|
||||
{"id": "44.3", "text": "Explains that keep-alive is counterproductive when crawling many unique hosts"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 45,
|
||||
"name": "buffered-io-syscall-reduction",
|
||||
"description": "Tests whether the model uses buffered I/O when writing a new file-writing function that emits many small records",
|
||||
"prompt": "Write a Go function that appends audit log entries to an open file. Each entry is a short string (~100 bytes). The function is called in a tight loop and may write thousands of entries per second.\n\n```go\nfunc WriteAuditEntries(f *os.File, entries []string) error {\n // TODO\n}\n```\n\nImplement this function.",
|
||||
"trap": "The natural implementation uses f.WriteString(entry) or fmt.Fprintln(f, entry) directly on the *os.File in a loop — that is what every beginner and intermediate Go example does. Each such call issues a separate syscall, which at thousands of entries per second is extremely expensive. The skill teaches wrapping with bufio.NewWriter(f) to batch writes into larger chunks and call Flush() at the end. Without the skill the model writes the direct unbuffered version.",
|
||||
"assertions": [
|
||||
{"id": "45.1", "text": "Wraps the file with bufio.NewWriter (or bufio.NewWriterSize) before writing"},
|
||||
{"id": "45.2", "text": "Writes entries through the buffered writer, not directly to the *os.File"},
|
||||
{"id": "45.3", "text": "Calls w.Flush() after all entries are written"},
|
||||
{"id": "45.4", "text": "Does NOT write each entry directly to f with f.WriteString or fmt.Fprintln(f, ...) in a loop without buffering"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 46,
|
||||
"name": "concurrent-pipeline-when-not-to-use",
|
||||
"description": "Tests knowledge of when concurrent pipelines are NOT beneficial",
|
||||
"prompt": "Our Go data pipeline has 3 stages. We want to make it faster by running stages concurrently:\n\n1. Stage A: Compress data (CPU-bound)\n2. Stage B: Encrypt data (CPU-bound)\n3. Stage C: Calculate checksum (CPU-bound)\n\nAll stages are CPU-bound. Should we run them concurrently in goroutines with channels between stages?",
|
||||
"trap": "When all stages compete for the same resource (CPU), concurrency adds context-switching overhead with no resource utilization gain. The skill explicitly says 'If A and B both compete for CPU, concurrency causes context-switching overhead with no resource utilization gain.' Without it, the model may recommend the concurrent pipeline pattern.",
|
||||
"assertions": [
|
||||
{"id": "46.1", "text": "Recommends AGAINST concurrent pipelines for this case"},
|
||||
{"id": "46.2", "text": "Explains that all three stages compete for the same resource (CPU)"},
|
||||
{"id": "46.3", "text": "Notes that concurrency only helps when stages saturate DIFFERENT resources"},
|
||||
{"id": "46.4", "text": "Mentions context-switching overhead as a cost of unnecessary concurrency"},
|
||||
{"id": "46.5", "text": "Suggests sequential processing or batching as a simpler alternative"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 47,
|
||||
"name": "batch-db-inserts",
|
||||
"description": "Tests whether the model uses batch inserts (not row-by-row) when writing a new bulk ingestion function",
|
||||
"prompt": "Write a Go function that persists a slice of sensor readings to a PostgreSQL database. The function is called every second with ~1000 readings.\n\n```go\ntype Reading struct {\n SensorID string\n Value float64\n Timestamp time.Time\n}\n\nfunc SaveReadings(db *sql.DB, readings []Reading) error {\n // TODO\n}\n```\n\nImplement this function.",
|
||||
"trap": "The natural implementation iterates over readings and calls db.Exec(INSERT ...) once per reading — that is what every Go+SQL tutorial shows and what most developers write first. At 1000 readings/second that means 1000 round-trips/second: 1000 query parses, 1000 network round-trips, 1000 transaction commits. The skill teaches batching: a single multi-row INSERT or the COPY protocol in one round-trip. Without the skill the model writes the per-row loop with a single INSERT per call.",
|
||||
"assertions": [
|
||||
{"id": "47.1", "text": "Does NOT call db.Exec with a single-row INSERT inside a for-loop over all readings"},
|
||||
{"id": "47.2", "text": "Uses a batching strategy: multi-row VALUES clause, COPY protocol, or chunked batch inserts"},
|
||||
{"id": "47.3", "text": "Reduces the number of database round-trips to O(1) or O(n/batchSize) rather than O(n)"},
|
||||
{"id": "47.4", "text": "Wraps the batch operation in a transaction"},
|
||||
{"id": "47.5", "text": "Explains that per-row inserts cause one round-trip per record, which is the primary bottleneck at 1000 records/second"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 48,
|
||||
"name": "panic-recover-control-flow",
|
||||
"description": "Tests knowledge that panic/recover should not be used for control flow",
|
||||
"prompt": "Review this Go parsing function for performance:\n\n```go\nfunc SafeParse(s string) (result int, err error) {\n defer func() {\n if r := recover(); r != nil {\n err = fmt.Errorf(\"parse failed: %v\", r)\n }\n }()\n return strconv.Atoi(s)\n}\n```\n\nThis is called 100K times per second with a mix of valid and invalid inputs.",
|
||||
"trap": "strconv.Atoi returns an error, not a panic. The defer/recover is unnecessary overhead: panic allocates a stack trace and unwinds the stack. The skill specifically warns against panic/recover as control flow. Without it, the model may accept the pattern as defensive programming.",
|
||||
"assertions": [
|
||||
{"id": "48.1", "text": "Identifies that panic/recover is unnecessary since strconv.Atoi returns errors"},
|
||||
{"id": "48.2", "text": "Explains that panic allocates a stack trace and unwinds the stack (10-100x overhead)"},
|
||||
{"id": "48.3", "text": "Suggests using simple error checking: v, err := strconv.Atoi(s)"},
|
||||
{"id": "48.4", "text": "States that panic/recover should only be used for truly unrecoverable situations"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 49,
|
||||
"name": "monotonic-time-since",
|
||||
"description": "Tests whether the model uses time.Since (monotonic clock) rather than wall-clock subtraction when writing a new duration measurement",
|
||||
"prompt": "Write a Go middleware that records the latency of each HTTP request in milliseconds and logs it. The service runs in a cloud environment where NTP adjustments happen occasionally.\n\n```go\nfunc LatencyMiddleware(next http.Handler) http.Handler {\n return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n // TODO: measure and log request latency\n next.ServeHTTP(w, r)\n })\n}\n```\n\nImplement this middleware.",
|
||||
"trap": "A common pattern for measuring time in Go that looks correct but is subtly fragile is: 'start := time.Now().UTC(); ...; elapsed := time.Now().UTC().Sub(start)'. Calling .UTC() strips the monotonic clock reading, leaving only the wall clock. An NTP adjustment during the request would then produce incorrect (or negative) latency measurements. The skill teaches that time.Since(start) uses the monotonic clock and is immune to wall-clock adjustments. Without the skill the model may call .UTC() or .Unix() on the start time, discarding the monotonic component.",
|
||||
"assertions": [
|
||||
{"id": "49.1", "text": "Captures start time with time.Now() without stripping the monotonic component (no .UTC(), .Unix(), or .Round() on the start time)"},
|
||||
{"id": "49.2", "text": "Computes elapsed time using time.Since(start) or end.Sub(start) where both times come from time.Now()"},
|
||||
{"id": "49.3", "text": "Does NOT call .UTC() or .UnixNano() on the start time before computing the elapsed duration (which would strip the monotonic clock)"},
|
||||
{"id": "49.4", "text": "Explains that time.Since uses the monotonic clock, making it immune to NTP or wall-clock adjustments"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 50,
|
||||
"name": "prometheus-gc-pressure-queries",
|
||||
"description": "Tests knowledge of specific PromQL queries for GC pressure monitoring",
|
||||
"prompt": "Our Go service in production has occasional latency spikes. We suspect GC pauses. We have Prometheus monitoring with default Go metrics. What PromQL queries should we use to diagnose GC pressure?",
|
||||
"trap": "The skill provides specific PromQL queries for GC diagnosis. Without it, the model may suggest generic approaches or incorrect metric names. The key queries are rate(go_gc_duration_seconds_count[5m]) for frequency and the worst-case pause quantile.",
|
||||
"assertions": [
|
||||
{"id": "50.1", "text": "Provides rate(go_gc_duration_seconds_count[5m]) for GC frequency"},
|
||||
{"id": "50.2", "text": "Provides go_gc_duration_seconds{quantile=\"1\"} for worst-case GC pause"},
|
||||
{"id": "50.3", "text": "Mentions >2 cycles/s sustained as a signal of excessive allocation rate"},
|
||||
{"id": "50.4", "text": "Suggests rate(go_memstats_alloc_bytes_total[5m]) for allocation rate monitoring"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 51,
|
||||
"name": "goroutine-leak-prometheus",
|
||||
"description": "Tests knowledge of PromQL for detecting goroutine leaks",
|
||||
"prompt": "We suspect our Go service has a goroutine leak in production. The service gets slower over time and eventually needs to be restarted. What Prometheus queries can confirm a goroutine leak?",
|
||||
"trap": "The skill provides specific goroutine leak PromQL queries. go_goroutines should correlate with load; growing independently of traffic indicates a leak. delta(go_goroutines[1h]) shows net change.",
|
||||
"assertions": [
|
||||
{"id": "51.1", "text": "Provides go_goroutines metric for goroutine count monitoring"},
|
||||
{"id": "51.2", "text": "Suggests delta(go_goroutines[1h]) for detecting net goroutine increase over time"},
|
||||
{"id": "51.3", "text": "Notes that goroutine count should correlate with load — growing independently means leak"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 52,
|
||||
"name": "continuous-profiling-tools",
|
||||
"description": "Tests knowledge of continuous profiling tools and their tradeoffs",
|
||||
"prompt": "We want to detect performance regressions across deployments in production. Our Go service runs on Kubernetes. We need historical profiling data to compare flamegraphs between versions. What tools should we evaluate?",
|
||||
"trap": "The skill lists specific continuous profiling tools with overhead and best-for guidance: Grafana Pyroscope (push/pull, 2-5%), Parca (eBPF, <1%), Datadog, GCP Profiler. Without it, the model may only suggest pprof endpoints without mentioning continuous profiling platforms.",
|
||||
"assertions": [
|
||||
{"id": "52.1", "text": "Recommends Grafana Pyroscope, Parca, or similar continuous profiling platform"},
|
||||
{"id": "52.2", "text": "Mentions overhead estimates (1-5% range)"},
|
||||
{"id": "52.3", "text": "Describes push vs pull collection modes"},
|
||||
{"id": "52.4", "text": "Mentions historical flamegraph comparison as a key feature"},
|
||||
{"id": "52.5", "text": "Suggests feeding profiles into PGO for build optimization"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 53,
|
||||
"name": "gogc-high-vs-low-tradeoff",
|
||||
"description": "Tests whether the model avoids recommending GOGC=200 for a latency-sensitive service when tuning GC",
|
||||
"prompt": "A colleague reviewed our Go API service (p99 latency target: 5ms, running in a pod with 4GB memory limit) and recommended setting GOGC=200 to reduce GC overhead. The service currently uses ~800MB heap. Should we follow this advice?\n\nThe service currently runs with the default GOGC=100.",
|
||||
"trap": "GOGC=200 doubles the heap growth allowed before the next GC cycle. For a throughput-oriented batch processor this is correct advice. But for a latency-sensitive API it is the wrong direction: larger heap means GC pauses take longer when they do occur, which hurts p99 latency. The skill explicitly teaches GOGC=50 for latency-sensitive services (more frequent but shorter pauses) and GOGC=200 for throughput-oriented batch processors. Without the skill the model may blindly agree with the suggestion since 'reducing GC overhead' sounds universally good.",
|
||||
"assertions": [
|
||||
{"id": "53.1", "text": "Recommends AGAINST GOGC=200 for this latency-sensitive API"},
|
||||
{"id": "53.2", "text": "Explains that higher GOGC allows a larger heap, which means longer GC pauses when they occur — hurting p99 latency"},
|
||||
{"id": "53.3", "text": "Suggests GOGC=50 (or lower than default) for latency-sensitive services: more frequent but shorter pauses"},
|
||||
{"id": "53.4", "text": "Notes that GOGC=200 is appropriate for throughput-oriented batch processors, not latency-sensitive APIs"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 54,
|
||||
"name": "godebug-gctrace",
|
||||
"description": "Tests knowledge of GODEBUG=gctrace=1 output interpretation",
|
||||
"prompt": "We ran our Go service with GODEBUG=gctrace=1 and got this output:\n\n```\ngc 142 @23.456s 12%: 0.015+89+1.2 ms clock, 0.3+72/150+24 ms cpu, 180->340->200 MB, 400 MB goal, 8 P\n```\n\nInterpret this GC trace line. What does it tell us about the service's health?",
|
||||
"trap": "The skill provides a field-by-field breakdown of gctrace output. The 12% CPU, 89ms pause, and 180->340->200 MB heap growth are concerning. Without the skill, the model may not correctly parse all fields or identify the implications.",
|
||||
"assertions": [
|
||||
{"id": "54.1", "text": "Correctly identifies gc 142 as the 142nd GC cycle"},
|
||||
{"id": "54.2", "text": "Identifies 12% as total CPU time spent in GC (which is high)"},
|
||||
{"id": "54.3", "text": "Interprets 180->340->200 MB as heap before, peak during, and after collection"},
|
||||
{"id": "54.4", "text": "Identifies 400 MB goal as the target heap size based on GOGC/GOMEMLIMIT"},
|
||||
{"id": "54.5", "text": "Notes that 12% GC CPU is concerning and suggests reducing allocation rate or tuning GOGC"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 55,
|
||||
"name": "unsafe-without-benchmark-proof",
|
||||
"description": "Tests that the model warns against premature unsafe usage",
|
||||
"prompt": "A colleague proposed using unsafe.Pointer to avoid string-to-byte-slice copy in our Go HTTP handler:\n\n```go\nfunc unsafeStringToBytes(s string) []byte {\n return unsafe.Slice(unsafe.StringData(s), len(s))\n}\n\nfunc HandleRequest(w http.ResponseWriter, r *http.Request) {\n body := unsafeStringToBytes(requestBody)\n w.Write(body)\n}\n```\n\nIs this a good optimization? The handler processes about 100 requests per second.",
|
||||
"trap": "The skill states unsafe is 'Only justified when profiling shows >10% improvement in a verified hot path.' At 100 req/s, this is not a hot path and the copy cost is negligible. Without the skill, the model may accept the optimization or only warn about safety without the benchmark threshold.",
|
||||
"assertions": [
|
||||
{"id": "55.1", "text": "Recommends against using unsafe here"},
|
||||
{"id": "55.2", "text": "Notes that 100 req/s is not a hot path where this optimization is justified"},
|
||||
{"id": "55.3", "text": "States that unsafe requires benchmark proof showing >10% improvement"},
|
||||
{"id": "55.4", "text": "Mentions safety risks of unsafe (mutating string backing store, GC interaction)"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 56,
|
||||
"name": "precomputed-lookup-table",
|
||||
"description": "Tests knowledge of precomputed lookup tables for pure functions with small input space",
|
||||
"prompt": "Optimize this Go hex encoding function that's called billions of times in our data pipeline:\n\n```go\nfunc byteToHex(b byte) (byte, byte) {\n high := b >> 4\n low := b & 0x0f\n var h, l byte\n if high < 10 {\n h = '0' + high\n } else {\n h = 'a' + high - 10\n }\n if low < 10 {\n l = '0' + low\n } else {\n l = 'a' + low - 10\n }\n return h, l\n}\n```",
|
||||
"trap": "The function is pure with a 16-element input space per nibble. The skill teaches precomputed lookup tables for this exact pattern. Two array lookups are faster than conditional branches. Without the skill, the model may suggest bitwise tricks rather than the lookup table approach.",
|
||||
"assertions": [
|
||||
{"id": "56.1", "text": "Suggests a precomputed lookup table (e.g., var hexDigit = [16]byte{...})"},
|
||||
{"id": "56.2", "text": "Shows the table lookup: hexDigit[b>>4], hexDigit[b&0x0f]"},
|
||||
{"id": "56.3", "text": "Explains that the lookup table fits in L1 cache and is faster than branching"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 57,
|
||||
"name": "json-performance-alternatives",
|
||||
"description": "Tests knowledge of JSON performance alternatives beyond encoding/json",
|
||||
"prompt": "Our Go API server spends 40% of CPU time in encoding/json according to pprof. We serialize thousands of Response structs per second. What options do we have to speed up JSON encoding?\n\n```go\ntype Response struct {\n ID int `json:\"id\"`\n Name string `json:\"name\"`\n Values []float64 `json:\"values\"`\n Metadata map[string]string `json:\"metadata\"`\n CreatedAt time.Time `json:\"created_at\"`\n}\n```",
|
||||
"trap": "The skill lists specific alternatives: custom MarshalJSON methods, code-gen libraries (easyjson, ffjson), drop-in replacements (goccy/go-json, json-iterator, bytedance/sonic), and treats encoding/json/v2 as an explicit GOEXPERIMENT=jsonv2 choice rather than a default production recommendation. Without it, the model may only suggest one approach.",
|
||||
"assertions": [
|
||||
{"id": "57.1", "text": "Mentions custom MarshalJSON/UnmarshalJSON methods as an option"},
|
||||
{"id": "57.2", "text": "Mentions code-generation libraries (easyjson, ffjson)"},
|
||||
{"id": "57.3", "text": "Mentions drop-in replacement libraries (goccy/go-json, json-iterator, or bytedance/sonic)"},
|
||||
{"id": "57.4", "text": "Explains that encoding/json uses reflection which causes CPU and allocation overhead"},
|
||||
{"id": "57.5", "text": "Quantifies expected improvement (2-5x or similar)"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 58,
|
||||
"name": "channel-batch-processing",
|
||||
"description": "Tests knowledge of batch processing from channels with timeout flush",
|
||||
"prompt": "Our Go service receives events from a channel and needs to batch them for bulk database insert. Events arrive at varying rates. We need to flush either when the batch is full (1000 items) OR after a timeout (100ms), whichever comes first.\n\nDesign the batch processor function.",
|
||||
"trap": "The skill shows the exact pattern: select on channel + ticker, with batch accumulation, flush on size threshold or timer. The key detail is reusing batch via batch[:0] and handling the channel close. Without the skill, the model may miss the ticker-based timeout or the clean shutdown.",
|
||||
"assertions": [
|
||||
{"id": "58.1", "text": "Uses select with both channel receive and ticker/timer for timeout"},
|
||||
{"id": "58.2", "text": "Flushes on batch size threshold"},
|
||||
{"id": "58.3", "text": "Flushes on timeout (ticker)"},
|
||||
{"id": "58.4", "text": "Handles channel close (flushes remaining items)"},
|
||||
{"id": "58.5", "text": "Reuses the batch slice (batch[:0] or similar) to reduce allocations"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 59,
|
||||
"name": "allocation-reduction-vs-gc-tuning",
|
||||
"description": "Tests knowledge that reducing allocations is better than tuning GOGC",
|
||||
"prompt": "Our Go service has high GC overhead (8% CPU). Should we increase GOGC to reduce GC frequency, or is there a better approach?",
|
||||
"trap": "The skill explicitly states: 'Reducing allocations helps more than tuning GOGC — it addresses the root cause instead of managing the symptom.' Without it, the model may recommend GOGC tuning as the primary solution.",
|
||||
"assertions": [
|
||||
{"id": "59.1", "text": "Recommends reducing allocations as the primary approach over GOGC tuning"},
|
||||
{"id": "59.2", "text": "Explains that GOGC tuning manages the symptom while allocation reduction addresses the root cause"},
|
||||
{"id": "59.3", "text": "Suggests specific allocation reduction strategies (value types, sync.Pool, preallocation, avoid interface boxing)"},
|
||||
{"id": "59.4", "text": "Acknowledges GOGC tuning as a secondary measure after allocation reduction"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 60,
|
||||
"name": "gctrace-key-fields",
|
||||
"description": "Tests knowledge of what to monitor in GC traces (frequency, pause times, CPU%)",
|
||||
"prompt": "We're monitoring our Go service with GODEBUG=gctrace=1. What specific patterns in the output should alarm us?",
|
||||
"trap": "The skill lists three key signals: GC frequency (too often = too many allocations), pause times (high = large heap or many pointers), CPU% (high = tune GOGC or reduce allocations). Without it, the model may give generic advice.",
|
||||
"assertions": [
|
||||
{"id": "60.1", "text": "Mentions high GC frequency as a signal of too many allocations"},
|
||||
{"id": "60.2", "text": "Mentions high pause times as a signal of large heap or many pointers"},
|
||||
{"id": "60.3", "text": "Mentions high GC CPU% (>5%) as concerning"},
|
||||
{"id": "60.4", "text": "Provides the GODEBUG=gctrace=1 command or assumes it's already running"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 61,
|
||||
"name": "non-go-memory-leak-detection",
|
||||
"description": "Tests knowledge of detecting non-Go memory leaks via Prometheus",
|
||||
"prompt": "Our Go service uses cgo to call a C image processing library. process_resident_memory_bytes keeps growing but go_memstats_alloc_bytes is stable. What PromQL query helps diagnose this?",
|
||||
"trap": "The skill provides the specific PromQL: process_resident_memory_bytes - go_memstats_sys_bytes. A growing gap indicates non-Go memory (cgo, mmap). Without it, the model may suggest Go heap tools that won't find the C memory leak.",
|
||||
"assertions": [
|
||||
{"id": "61.1", "text": "Suggests process_resident_memory_bytes - go_memstats_sys_bytes to isolate non-Go memory"},
|
||||
{"id": "61.2", "text": "Identifies this as a likely C/cgo memory leak (not a Go leak)"},
|
||||
{"id": "61.3", "text": "Explains that growing gap between RSS and Go sys bytes indicates non-Go memory growth"},
|
||||
{"id": "61.4", "text": "Suggests C-level memory profiling tools (valgrind, AddressSanitizer) for further diagnosis"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 62,
|
||||
"name": "cpu-saturation-prometheus",
|
||||
"description": "Tests knowledge of detecting CPU saturation via Prometheus",
|
||||
"prompt": "How do we detect if our Go service is CPU-saturated in production using Prometheus metrics?",
|
||||
"trap": "The skill provides specific PromQL: rate(process_cpu_seconds_total[5m]) / GOMAXPROCS. A ratio >0.8 sustained means CPU-saturated. Without the skill, the model may suggest system-level metrics rather than Go-specific ones.",
|
||||
"assertions": [
|
||||
{"id": "62.1", "text": "Provides rate(process_cpu_seconds_total[5m]) for CPU cores consumed"},
|
||||
{"id": "62.2", "text": "Divides by GOMAXPROCS to get utilization ratio"},
|
||||
{"id": "62.3", "text": "States that >0.8 sustained indicates CPU saturation"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 63,
|
||||
"name": "document-optimizations",
|
||||
"description": "Tests whether the model recommends documenting optimizations with comments",
|
||||
"prompt": "I optimized a Go function from using reflect.DeepEqual to a hand-written comparison, and from column-first to row-first matrix traversal. Should I add comments explaining why?",
|
||||
"trap": "The skill's core philosophy #3 states: 'Document optimizations — add code comments explaining why a pattern is faster, with benchmark numbers when available. Future readers need context to avoid reverting an unnecessary optimization.' Without it, the model may skip this guidance.",
|
||||
"assertions": [
|
||||
{"id": "63.1", "text": "Strongly recommends adding comments explaining WHY the optimization was made"},
|
||||
{"id": "63.2", "text": "Suggests including benchmark numbers in the comments"},
|
||||
{"id": "63.3", "text": "Explains that future readers may revert optimizations they don't understand"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 64,
|
||||
"name": "lru-cache-freelru",
|
||||
"description": "Tests knowledge of high-performance LRU cache alternatives",
|
||||
"prompt": "We need a bounded LRU cache in Go for our hot path. We considered using container/list from the standard library. Is that the best option for performance?",
|
||||
"trap": "The skill mentions that container/list has poor cache locality (each node is a separate heap allocation). It recommends elastic/go-freelru (37x faster, contiguous memory) or hashicorp/golang-lru. Without it, the model may recommend container/list as sufficient.",
|
||||
"assertions": [
|
||||
{"id": "64.1", "text": "Notes that container/list has poor cache locality (separate heap allocation per node)"},
|
||||
{"id": "64.2", "text": "Recommends elastic/go-freelru or hashicorp/golang-lru as alternatives"},
|
||||
{"id": "64.3", "text": "Mentions the performance advantage of contiguous memory layouts for LRU"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 65,
|
||||
"name": "simd-when-not-worth",
|
||||
"description": "Tests whether the model avoids recommending SIMD when the real bottleneck is allocations, not CPU arithmetic",
|
||||
"prompt": "Our Go image thumbnail service resizes JPEG images. pprof shows:\n- 55% of CPU time in runtime.mallocgc and runtime.gcBgMarkWorker\n- 20% in image/jpeg.Decode\n- 15% in image.(*NRGBA).At (per-pixel reads using the image.Image interface)\n- 10% other\n\nA performance consultant recommended implementing SIMD pixel-processing routines to speed up the resize operation. Should we pursue SIMD as our first optimization?",
|
||||
"trap": "55% of CPU time is in GC — the bottleneck is heap allocations, not arithmetic throughput. SIMD accelerates CPU-bound numeric operations; it has zero effect on allocation rate or GC pauses. Additionally, the 15% in image.Image interface calls is an interface boxing / reflection overhead issue, not a SIMD opportunity. The skill explicitly states 'If your bottleneck is allocations or I/O, SIMD won't help.' Without the skill the model may agree with the consultant since image processing 'sounds like' a SIMD use case.",
|
||||
"assertions": [
|
||||
{"id": "65.1", "text": "Recommends against SIMD as the first optimization"},
|
||||
{"id": "65.2", "text": "Identifies the primary bottleneck as heap allocations and GC (55% of CPU in mallocgc/GC)"},
|
||||
{"id": "65.3", "text": "States that SIMD only helps CPU-bound numeric inner loops, not allocation or GC overhead"},
|
||||
{"id": "65.4", "text": "Suggests reducing allocations (e.g., reusing pixel buffers, avoiding per-pixel interface calls) as the correct first step"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 66,
|
||||
"name": "set-map-struct-zero-size",
|
||||
"description": "Tests whether the model uses struct{} (not bool) for set map values when writing a new deduplication function",
|
||||
"prompt": "Write a Go function that deduplicates a large slice of string event IDs. The slice may contain up to 5 million entries. Return a new slice with duplicates removed, preserving order.\n\n```go\nfunc Deduplicate(ids []string) []string {\n // TODO\n}\n```\n\nImplement this function.",
|
||||
"trap": "The natural instinct when building a 'seen' set in Go is to use map[string]bool, since bool reads naturally: 'if seen[id] { ... }'. This is what most Go developers write and what most deduplication examples show. The skill specifically teaches using map[string]struct{} instead: struct{} occupies 0 bytes vs bool at 1 byte per entry, saving ~5MB for 5M entries. Without the skill the model writes map[string]bool.",
|
||||
"assertions": [
|
||||
{"id": "66.1", "text": "Uses map[string]struct{} (not map[string]bool) as the seen-set type"},
|
||||
{"id": "66.2", "text": "Does NOT use map[string]bool for the membership tracking map"},
|
||||
{"id": "66.3", "text": "Explains that struct{} occupies 0 bytes vs bool at 1 byte, saving memory at large scale"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 67,
|
||||
"name": "regression-detection-prometheus",
|
||||
"description": "Tests knowledge of PromQL queries for deployment regression detection",
|
||||
"prompt": "We just deployed a new version of our Go service. How can we use Prometheus to detect if this deployment introduced a performance regression?",
|
||||
"trap": "The skill provides specific regression detection PromQL: rate(go_memstats_alloc_bytes_total[5m]) for allocation rate comparison and histogram_quantile(0.99, ...) for p99 latency. Without it, the model may suggest generic monitoring.",
|
||||
"assertions": [
|
||||
{"id": "67.1", "text": "Suggests comparing rate(go_memstats_alloc_bytes_total[5m]) before and after deploy"},
|
||||
{"id": "67.2", "text": "Suggests monitoring p99 latency histogram_quantile for increase after deploy"},
|
||||
{"id": "67.3", "text": "Mentions comparing metrics between old and new deployment versions"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 68,
|
||||
"name": "statsviz-development-profiling",
|
||||
"description": "Tests knowledge of real-time development visualization tools",
|
||||
"prompt": "I'm developing a Go service locally and want to see real-time GC behavior, heap usage, and goroutine count in a browser dashboard without setting up Prometheus/Grafana. What tool can I use?",
|
||||
"trap": "The skill specifically mentions statsviz (github.com/arl/statsviz) for real-time browser dashboard during local development. Without it, the model may suggest full monitoring stacks or pprof web UI which doesn't provide real-time visualization.",
|
||||
"assertions": [
|
||||
{"id": "68.1", "text": "Recommends statsviz (github.com/arl/statsviz) for real-time browser visualization"},
|
||||
{"id": "68.2", "text": "Mentions the /debug/statsviz endpoint or statsviz.Register pattern"},
|
||||
{"id": "68.3", "text": "Notes that it shows heap, GC pauses, goroutines, and scheduler in real-time"}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,183 @@
|
||||
# Caching Patterns
|
||||
|
||||
The fastest code is code that doesn't run. Caching pre-computed results, deduplicating concurrent requests, and avoiding unnecessary work are often the highest-leverage performance improvements.
|
||||
|
||||
## Compiled Pattern Caching
|
||||
|
||||
**Diagnose:** 1- `go tool pprof` (CPU profile) — look for `regexp.Compile`, `regexp.MustCompile`, or `template.Parse` appearing in hot paths; their presence means patterns are being recompiled per call instead of once 2- `go test -bench -benchmem` — benchmark per-call compilation vs cached version; expect 10-12x improvement and allocs/op dropping to zero for the compilation step
|
||||
|
||||
### Regexp at package level
|
||||
|
||||
`regexp.Compile` parses a pattern into a state machine — ~5,700ns per compilation. Match operations on a compiled regexp cost ~450ns. Compiling per-call wastes 10-12x:
|
||||
|
||||
```go
|
||||
// Bad — compiled on every call
|
||||
func isValid(email string) bool {
|
||||
re := regexp.MustCompile(`^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$`)
|
||||
return re.MatchString(email)
|
||||
}
|
||||
|
||||
// Good — compiled once, safe for concurrent use
|
||||
var emailRegex = regexp.MustCompile(`^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$`)
|
||||
|
||||
func isValid(email string) bool { return emailRegex.MatchString(email) }
|
||||
```
|
||||
|
||||
Note: `regexp.MustCompile` panics on invalid patterns — fine for package-level constants (caught at startup). Use `regexp.Compile` for user-provided patterns. Go's regexp uses linear-time matching (no backtracking).
|
||||
|
||||
### Template caching
|
||||
|
||||
`template.Parse` is equally expensive. Parse once at startup:
|
||||
|
||||
```go
|
||||
var reportTmpl = template.Must(template.ParseFiles("templates/report.html"))
|
||||
```
|
||||
|
||||
### Precomputed lookup tables
|
||||
|
||||
When a computation is pure (same input → same output) and the input space is small, replace calculation with array lookup:
|
||||
|
||||
```go
|
||||
var hexDigit = [16]byte{'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}
|
||||
|
||||
func byteToHex(b byte) (byte, byte) {
|
||||
return hexDigit[b>>4], hexDigit[b&0x0f] // two array lookups vs branching logic
|
||||
}
|
||||
```
|
||||
|
||||
If the table fits in L1/L2 cache, lookup is faster than even simple computation.
|
||||
|
||||
## Request-Level Caching
|
||||
|
||||
**Diagnose:** 1- `go tool pprof` (goroutine profile) — look for many goroutines blocked on the same external call (HTTP fetch, DB query); this signals a cache stampede where N goroutines all miss the cache simultaneously 2- `fgprof` — shows off-CPU wait time; look for the same fetch function dominating wall-clock time across many goroutines, confirming duplicated concurrent work 3- `go tool pprof -alloc_objects` — check if cache miss handling allocates heavily; high alloc counts on fetch functions confirm the stampede is also generating GC pressure
|
||||
|
||||
### singleflight for cache stampede prevention
|
||||
|
||||
When a cache entry expires, many goroutines may simultaneously discover the miss and all request the same expensive computation. `singleflight` ensures only one goroutine fetches while others wait:
|
||||
|
||||
```go
|
||||
import "golang.org/x/sync/singleflight"
|
||||
|
||||
var (
|
||||
cache sync.Map
|
||||
sf singleflight.Group
|
||||
)
|
||||
|
||||
func GetWeather(city string) (string, error) {
|
||||
if val, ok := cache.Load(city); ok {
|
||||
return val.(string), nil
|
||||
}
|
||||
|
||||
// Only one goroutine fetches; others block on the same key
|
||||
result, err, _ := sf.Do(city, func() (any, error) {
|
||||
data, err := fetchFromAPI(city)
|
||||
if err == nil { cache.Store(city, data) }
|
||||
return data, err
|
||||
})
|
||||
return result.(string), err
|
||||
}
|
||||
```
|
||||
|
||||
→ See `samber/cc-skills-golang@golang-concurrency` skill for `singleflight` API details and `sync.Map` vs `RWMutex` decision guidance. → **Generics alternative:** Use `github.com/samber/go-singleflightx` to avoid interface{} boxing overhead; expect 2-4x faster result retrieval compared to the standard library's `singleflight.Group`.
|
||||
|
||||
### LRU caches
|
||||
|
||||
For bounded caches with eviction, the standard library's `container/list` works but has poor cache locality (each node is a separate heap allocation). For high-performance LRU:
|
||||
|
||||
- **`github.com/hashicorp/golang-lru`** — thread-safe, simple API
|
||||
- **`github.com/elastic/go-freelru`** — merges hashmap and ringbuffer into contiguous memory, ~37x faster than sharded implementations
|
||||
|
||||
When using third-party cache libraries, refer to the library's official documentation for current API signatures.
|
||||
|
||||
## Algorithmic Complexity
|
||||
|
||||
**Diagnose:** 1- `go tool pprof` (CPU profile) — look for functions with high cumulative time that contain nested loops or repeated linear scans; these are algorithmic complexity bottlenecks 2- `go test -bench` — benchmark with different input sizes (100, 1K, 10K, 100K); if time grows quadratically (10x input → 100x time), the algorithm is O(n²) and needs replacement
|
||||
|
||||
Before micro-optimizing, check that the algorithm itself isn't the bottleneck. A constant-factor improvement on an O(n²) algorithm loses to a naive O(n log n) implementation at scale.
|
||||
|
||||
**Common complexity traps in Go:**
|
||||
|
||||
| Pattern | Complexity | Fix | Fixed complexity |
|
||||
| --- | --- | --- | --- |
|
||||
| `slices.Contains` in a loop | O(n·m) | Build `map[T]struct{}` first, then lookup | O(n+m) |
|
||||
| Nested loops for matching | O(n²) | Index with a map, sort+binary search, or `slices.BinarySearch` | O(n log n) or O(n) |
|
||||
| Repeated `append` without prealloc | O(n²) amortized copies | `make([]T, 0, n)` | O(n) |
|
||||
| String concatenation with `+=` | O(n²) total copies | `strings.Builder` | O(n) |
|
||||
| Linear scan for min/max/dedup | O(n) per query | Sort once, query many times | O(n log n) + O(log n) per query |
|
||||
|
||||
**Think in Big-O first, then optimize constants.** A 10x constant-factor improvement matters; switching from O(n²) to O(n) matters more.
|
||||
|
||||
## Work Avoidance
|
||||
|
||||
**Diagnose:** 1- `go tool pprof` (CPU profile) — look for linear scan functions (`slices.Contains`, `slices.Index`) or iterator chains (`Filter`, `Map`) consuming CPU in hot paths 2- `go test -bench` — benchmark the current approach vs a map-based or early-return version; expect O(n) → O(1) for membership tests, significant improvement for short-circuit loops
|
||||
|
||||
### Map lookups over slice scanning
|
||||
|
||||
`Contains(slice, element)` is O(n). Map lookups are O(1). When doing multiple membership tests against the same collection, build a map once:
|
||||
|
||||
```go
|
||||
// Bad — O(n*m), checking Contains per element
|
||||
for _, item := range subset {
|
||||
if !Contains(collection, item) { return false } // O(n) per check
|
||||
}
|
||||
|
||||
// Good — O(n+m), build map once, O(1) lookups
|
||||
seen := make(map[T]struct{}, len(collection))
|
||||
for _, item := range collection { seen[item] = struct{}{} }
|
||||
for _, item := range subset {
|
||||
if _, ok := seen[item]; !ok { return false }
|
||||
}
|
||||
```
|
||||
|
||||
Use `struct{}` (0 bytes) instead of `bool` (1 byte) for set maps.
|
||||
|
||||
### Early returns and short-circuit loops
|
||||
|
||||
Return immediately when the answer is known. Finding the target on iteration 3 of 1000 saves 997 iterations:
|
||||
|
||||
```go
|
||||
// Bad — always iterates full collection
|
||||
found := false
|
||||
for _, item := range collection {
|
||||
if item == target { found = true }
|
||||
}
|
||||
return found
|
||||
|
||||
// Good — returns on first match
|
||||
for i := range collection {
|
||||
if collection[i] == target { return true }
|
||||
}
|
||||
return false
|
||||
```
|
||||
|
||||
### Avoid iterator chains
|
||||
|
||||
Chaining iterator operations (`Filter → Map → First`) creates closures and intermediate machinery. A direct loop is simpler and faster:
|
||||
|
||||
```go
|
||||
// Bad — creates 2 iterators with closures
|
||||
result, ok := First(Filter(collection, predicate))
|
||||
|
||||
// Good — single pass, early return, no closures
|
||||
for i := range collection {
|
||||
if predicate(collection[i]) { return collection[i], true }
|
||||
}
|
||||
```
|
||||
|
||||
### Replace indirect function calls with direct loops
|
||||
|
||||
When a function wraps another function (e.g., `FromSlicePtr` calling `Map` with a closure), the closure indirection prevents inlining. Replace with a direct loop:
|
||||
|
||||
```go
|
||||
// Bad — Map() with closure, per-element function call overhead
|
||||
func FromSlicePtr(items []*T) []T {
|
||||
return Map(items, func(p *T) T { return *p })
|
||||
}
|
||||
|
||||
// Good — direct loop, inlineable, -13% to -17% time
|
||||
func FromSlicePtr(items []*T) []T {
|
||||
result := make([]T, len(items))
|
||||
for i := range items { result[i] = *items[i] }
|
||||
return result
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,375 @@
|
||||
# CPU Optimization
|
||||
|
||||
CPU-bound bottlenecks show up as functions dominating the CPU profile. The patterns below target the most common causes: missed inlining opportunities, poor cache utilization, and unnecessary computation.
|
||||
|
||||
## Function Inlining
|
||||
|
||||
**Diagnose:** 1- `go tool pprof` (CPU profile) — look for hot functions with high cumulative CPU time; if a small helper dominates the profile, it's likely not being inlined 2- `go build -gcflags="-m"` — grep for `"cannot inline"` on your hot-path functions; the reason (e.g., `"function too complex"`, `"unhandled op"`) tells you what to simplify
|
||||
|
||||
The Go compiler inlines small functions, eliminating call overhead. Functions that are too complex (loops, many statements, or calls to non-inlineable functions) won't be inlined — this matters in tight loops called millions of times.
|
||||
|
||||
```go
|
||||
// Bad — log call prevents inlining
|
||||
func abs(x int) int {
|
||||
if x < 0 {
|
||||
log.Printf("negative: %d", x) // blocks inlining
|
||||
return -x
|
||||
}
|
||||
return x
|
||||
}
|
||||
|
||||
// Good — simple enough to inline
|
||||
func abs(x int) int {
|
||||
if x < 0 { return -x }
|
||||
return x
|
||||
}
|
||||
```
|
||||
|
||||
**Check inlining decisions:**
|
||||
|
||||
```bash
|
||||
go build -gcflags="-m" ./... 2>&1 | grep "can inline"
|
||||
go build -gcflags="-m" ./... 2>&1 | grep "inlining call"
|
||||
```
|
||||
|
||||
Move side effects (logging, metrics) outside hot-path functions or guard them with conditional checks.
|
||||
|
||||
### Value receivers enable inlining
|
||||
|
||||
Value receivers allow the compiler to fully inline fluent method chains. Pointer receivers add indirection that blocks inlining:
|
||||
|
||||
```go
|
||||
// Pointer receiver — indirection prevents inlining, constant overhead per call
|
||||
func (c *config) WithTimeout(d time.Duration) *config { c.timeout = d; return c }
|
||||
|
||||
// Value receiver — fully inlined, -80% time in fluent chains
|
||||
func (c config) WithTimeout(d time.Duration) config { c.timeout = d; return c }
|
||||
```
|
||||
|
||||
## Cache Locality
|
||||
|
||||
**Diagnose:** 1- `go tool pprof` (CPU profile) — look for loops over slices/matrices consuming disproportionate CPU; cache-miss-heavy code shows high `runtime.memmove` or flat time in simple index operations 2- `go test -bench` — benchmark row-first vs column-first traversal; expect 10-50x difference on large matrices purely from cache effects
|
||||
|
||||
Modern CPUs fetch data in 64-byte cache lines. Sequential memory access is dramatically faster than random access because the prefetcher can load the next cache line before you need it.
|
||||
|
||||
### Row-major traversal
|
||||
|
||||
Go stores 2D arrays in row-major order. Column-first traversal jumps across memory, causing cache misses:
|
||||
|
||||
```go
|
||||
// Bad — column-first, jumps across memory (~10M cache misses)
|
||||
for col := 0; col < 1024; col++ {
|
||||
for row := 0; row < 1024; row++ {
|
||||
sum += matrix[row][col]
|
||||
}
|
||||
}
|
||||
|
||||
// Good — row-first, sequential access (~125K cache misses)
|
||||
for row := 0; row < 1024; row++ {
|
||||
for col := 0; col < 1024; col++ {
|
||||
sum += matrix[row][col]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Performance difference: 10-50x purely from cache effects.
|
||||
|
||||
### Contiguous 2D allocation
|
||||
|
||||
Allocating each row separately scatters data across the heap:
|
||||
|
||||
```go
|
||||
// Bad — N separate allocations, poor cache locality
|
||||
matrix := make([][]float64, rows)
|
||||
for i := range matrix { matrix[i] = make([]float64, cols) }
|
||||
|
||||
// Good — single contiguous allocation, cache-friendly
|
||||
data := make([]float64, rows*cols)
|
||||
matrix := make([][]float64, rows)
|
||||
for i := range matrix { matrix[i] = data[i*cols : (i+1)*cols] }
|
||||
```
|
||||
|
||||
### Struct of Arrays (SoA) vs Array of Structs (AoS)
|
||||
|
||||
When iterating over a single field of a struct, AoS wastes cache space loading unused fields:
|
||||
|
||||
```go
|
||||
// AoS — loading each Point (24 bytes) to read only x (8 bytes) = 66% cache waste
|
||||
type Point struct { x, y, z float64 }
|
||||
points := make([]Point, n)
|
||||
for i := range points { sum += points[i].x }
|
||||
|
||||
// SoA — all x values contiguous, 100% cache utilization
|
||||
type Points struct { xs, ys, zs []float64 }
|
||||
for i := range ps.xs { sum += ps.xs[i] }
|
||||
```
|
||||
|
||||
Use SoA when iterating over a subset of fields (physics, graphics, analytics). AoS is fine when accessing all fields together or for small structs.
|
||||
|
||||
### Pointer-heavy vs value-heavy data
|
||||
|
||||
Index-based data structures (nodes stored in a contiguous array, referenced by index) beat pointer-based structures for cache locality:
|
||||
|
||||
```go
|
||||
// Pointer-based tree — each node scattered in heap, random cache misses
|
||||
type Node struct { value int; left, right *Node }
|
||||
|
||||
// Index-based tree — nodes in contiguous array, cache-friendly
|
||||
type Tree struct { nodes []Node }
|
||||
type Node struct { value int; left, right int } // indices into nodes
|
||||
```
|
||||
|
||||
## False Sharing
|
||||
|
||||
**Diagnose:** 1- `go tool pprof` (CPU profile + mutex profile) — look for atomic operations or counter updates consuming unexpectedly high CPU; in the mutex profile, look for contention on variables that shouldn't need locking 2- `go test -bench` — benchmark concurrent counter increments; if adding goroutines makes it _slower_ instead of faster, false sharing is likely
|
||||
|
||||
When goroutines update variables that share the same 64-byte CPU cache line, each write invalidates the other core's cache, causing severe degradation:
|
||||
|
||||
```go
|
||||
// Bad — a and b on same cache line, cores fight for it
|
||||
type Counters struct { a, b int64 }
|
||||
|
||||
// Good — separate cache lines, no interference
|
||||
type Counters struct {
|
||||
a int64 // 8 bytes
|
||||
_ [56]byte // 64 - 8 = 56 bytes padding
|
||||
b int64 // 8 bytes
|
||||
}
|
||||
```
|
||||
|
||||
Only apply cache-line padding when profiling confirms contention on concurrent counters/flags.
|
||||
|
||||
## Instruction-Level Parallelism
|
||||
|
||||
**Diagnose:** 1- `go tool pprof` (CPU profile) — look for tight arithmetic loops (sum, dot product) where the loop body itself dominates CPU; these are candidates for multi-accumulator optimization 2- `go test -bench` — benchmark single vs multi-accumulator versions; expect 2-4x improvement when the loop is truly CPU-bound with a dependency chain
|
||||
|
||||
Modern CPUs execute multiple independent instructions simultaneously. A single accumulator creates a dependency chain — each addition waits for the previous one:
|
||||
|
||||
```go
|
||||
// Bad — sequential dependency, CPU pipeline stalls
|
||||
var total int64
|
||||
for _, v := range data { total += v }
|
||||
|
||||
// Good — 4 independent accumulators, CPU pipelines all 4 in parallel
|
||||
var s0, s1, s2, s3 int64
|
||||
limit := len(data) - len(data)%4
|
||||
for i := 0; i < limit; i += 4 {
|
||||
s0 += data[i]; s1 += data[i+1]; s2 += data[i+2]; s3 += data[i+3]
|
||||
}
|
||||
for i := limit; i < len(data); i++ { s0 += data[i] }
|
||||
total := s0 + s1 + s2 + s3
|
||||
```
|
||||
|
||||
Expect 2-4x improvement for tight arithmetic loops. Only use when profiling shows the loop is a bottleneck.
|
||||
|
||||
## SIMD (Single Instruction, Multiple Data)
|
||||
|
||||
**Diagnose:** 1- `go tool pprof` (CPU profile) — confirm a numeric inner loop consumes >20% of CPU; SIMD only helps CPU-bound numeric work, not allocation or I/O bottlenecks 2- `go test -bench` — measure the loop's baseline ns/op; provides the reference point to validate SIMD gains 3- `go build -gcflags="-d=ssa/prove/debug=2"` — check if the compiler already auto-vectorized the loop; look for `"Proved"` bounds-check eliminations that enable vectorization 4- `GOSSAFUNC=MyFunc go build` — generate SSA dump (`ssa.html`) to inspect whether the compiler produces vector instructions for the hot loop 5- `go tool objdump -s MyFunc ./binary` — verify the final assembly contains SIMD instructions (e.g., `VMOVAPD`, `VADDPD` on amd64) rather than scalar equivalents
|
||||
|
||||
Go 1.26+ includes an experimental `simd/archsimd` package (requires `GOEXPERIMENT=simd` flag) providing low-level SIMD intrinsics for amd64 with 128/256/512-bit vectors. For broader portability, the compiler auto-vectorizes simple loops, and several strategies exist.
|
||||
|
||||
**Options for explicit SIMD in Go:**
|
||||
|
||||
- **Experimental `simd/archsimd` (Go 1.26+, speculative)** — Direct SIMD intrinsics via vector types with CPU feature detection. Limited to AMD64. Use with caution: this is an experimental, in-progress API (`GOEXPERIMENT=simd`) whose package path and type names are subject to change before stabilization. Not covered by Go 1 compatibility guarantees, and should never be exposed in public APIs. Verify the actual import path and API against the Go toolchain you are using.
|
||||
|
||||
```go
|
||||
// Requires: GOEXPERIMENT=simd go build
|
||||
// WARNING: experimental API — package path and types may change
|
||||
import "simd/archsimd"
|
||||
|
||||
v := archsimd.Int32x4{1, 2, 3, 4}
|
||||
```
|
||||
|
||||
- **Let the compiler do it** — write simple, idiomatic loops on `[]float64`/`[]int32` slices. Check auto-vectorization: `go build -gcflags="-d=ssa/prove/debug=2" ./...`
|
||||
- **`math/bits`** — operations like `OnesCount`, `LeadingZeros`, `RotateLeft` map directly to hardware instructions (POPCNT, CLZ, ROL)
|
||||
- **Hand-written assembly** — `.s` files with AVX2/NEON instructions for critical inner loops. Libraries like `klauspost/compress` and `minio/sha256-simd` use this approach
|
||||
- **Third-party vectorized libraries** — for common operations (hashing, compression, encoding), use libraries that already have optimized SIMD implementations rather than writing your own
|
||||
|
||||
### Handling CPU-specific instruction sets
|
||||
|
||||
Hand-written assembly unlocks higher performance but couples code to specific CPU features (AVX2, NEON, etc.). Three strategies exist:
|
||||
|
||||
**1. Compile on a production-similar machine**
|
||||
|
||||
Build binaries on hardware matching your deployment target, so the compiler generates code for the exact CPU instruction set available at runtime:
|
||||
|
||||
```bash
|
||||
# Compiling on production hardware ensures optimal code generation
|
||||
# for that specific CPU architecture and generation
|
||||
ssh prod-server "cd /path && go build -o app ."
|
||||
```
|
||||
|
||||
**Tradeoff:** Simplest approach, but requires access to production hardware and different binaries per CPU type (Intel vs AMD vs Apple Silicon). Breaks CI/CD portability.
|
||||
|
||||
**2. Runtime CPU feature detection + multiple implementations**
|
||||
|
||||
Implement the function multiple times — one for each CPU capability — and dispatch at runtime:
|
||||
|
||||
```go
|
||||
// dispatch.go
|
||||
var sumImpl func([]int64) int64
|
||||
|
||||
func init() {
|
||||
if cpu.X86.HasAVX2 {
|
||||
sumImpl = sumAVX2
|
||||
} else {
|
||||
sumImpl = sumGeneric
|
||||
}
|
||||
}
|
||||
|
||||
func Sum(data []int64) int64 {
|
||||
return sumImpl(data)
|
||||
}
|
||||
|
||||
// sum_generic.go
|
||||
func sumGeneric(data []int64) int64 {
|
||||
var total int64
|
||||
for _, v := range data { total += v }
|
||||
return total
|
||||
}
|
||||
|
||||
// sum_amd64.s
|
||||
TEXT ·sumAVX2(SB), NOSPLIT, $0-32
|
||||
// AVX2 implementation
|
||||
VMOVAPD (SI), Y0
|
||||
// ...
|
||||
```
|
||||
|
||||
**Tradeoff:** Single binary works everywhere; trades one function-call dispatch overhead for full CPU feature utilization. Libraries like `encoding/base64` and `sha256` use this pattern.
|
||||
|
||||
**3. Compile-time selection with `//go:build` tags**
|
||||
|
||||
Use conditional compilation to generate different code at build time for each target:
|
||||
|
||||
```go
|
||||
// sum_fast.go
|
||||
//go:build amd64 && !nosimd
|
||||
|
||||
package mylib
|
||||
|
||||
// AVX2 assembly via cgo or inline
|
||||
func Sum(data []int64) int64 {
|
||||
return sumAVX2(data) // or calls to .s file
|
||||
}
|
||||
|
||||
// sum_generic.go
|
||||
//go:build !amd64 || nosimd
|
||||
|
||||
package mylib
|
||||
|
||||
func Sum(data []int64) int64 {
|
||||
var total int64
|
||||
for _, v := range data { total += v }
|
||||
return total
|
||||
}
|
||||
```
|
||||
|
||||
Build different binaries per target:
|
||||
|
||||
```bash
|
||||
GOOS=linux GOARCH=amd64 go build -o app-avx2 . # Uses sum_fast.go
|
||||
GOOS=darwin GOARCH=arm64 go build -o app-neon . # Uses sum_generic.go
|
||||
go build -tags=nosimd -o app-safe . # Fallback everywhere
|
||||
```
|
||||
|
||||
**Tradeoff:** Zero runtime overhead; each binary is fully optimized for its target. Requires shipping multiple binaries and coordinating which binary runs where.
|
||||
|
||||
**When SIMD is NOT worth pursuing:**
|
||||
|
||||
- Go's lack of intrinsics means SIMD requires assembly — high maintenance burden, platform-specific, and harder to debug
|
||||
- Auto-vectorization covers the most common cases (simple numeric loops)
|
||||
- If your bottleneck is allocations or I/O, SIMD won't help
|
||||
|
||||
**Recommendation:** Start with auto-vectorization. For Go 1.26+, evaluate `simd/archsimd` for AMD64-only workloads (remembering it's experimental). Move to runtime detection (option 2 above) if profiling shows a bottleneck and the code needs to run on heterogeneous hardware. Only use compile-time selection (option 3) if you control the deployment environment and can test each per-binary variant.
|
||||
|
||||
Only invest in hand-written SIMD when profiling shows a numeric inner loop consuming >20% of CPU and the compiler isn't auto-vectorizing it.
|
||||
|
||||
## Tight Loops and the Scheduler
|
||||
|
||||
**Diagnose:** 1- `go tool pprof` (goroutine profile) — look for many goroutines stuck in `"runnable"` state (waiting for CPU) while one goroutine monopolizes execution 2- `go tool trace` — visualize goroutine scheduling over time; look for long uninterrupted execution spans on one goroutine while others show scheduling gaps 3- `GODEBUG=schedtrace=1000` — print scheduler state every second; look for unbalanced `runqueue` counts across P's indicating one P is starved 4- `runtime/metrics` (`/sched/latencies:seconds`) — measure how long goroutines wait before getting CPU; high p99 latencies confirm starvation 5- Prometheus `rate(process_cpu_seconds_total[2m])` — monitor if CPU usage hits GOMAXPROCS ceiling; if saturated while other goroutines are starved, a tight loop is monopolizing P's
|
||||
|
||||
A goroutine running a CPU-intensive tight loop without function calls may not yield to the scheduler, starving other goroutines. Go 1.14+ added asynchronous preemption, but very tight loops with fully inlined operations can still cause issues:
|
||||
|
||||
```go
|
||||
// Potential starvation — pure computation, no function calls
|
||||
for { x = x*a + b }
|
||||
|
||||
// Safe — non-inlined call triggers preemption check
|
||||
for item := range work {
|
||||
processBatch(item) // function call = preemption point
|
||||
}
|
||||
```
|
||||
|
||||
**When to use non-inlined calls for scheduling:** Use non-inlined function calls when:
|
||||
|
||||
- The loop runs for a long time (hundreds of milliseconds or more of uninterrupted computation)
|
||||
- Other goroutines are waiting to run (e.g., handling requests, I/O completion, channel operations)
|
||||
- The loop contains only arithmetic or memory operations with no function calls
|
||||
|
||||
For short bursts of computation (< 10ms), preemption isn't critical and inlining for CPU efficiency takes priority.
|
||||
|
||||
**Detecting scheduler starvation:** Use these tools to confirm goroutines are being starved:
|
||||
|
||||
- **`go tool pprof` goroutine profile** — shows goroutines stuck in "runnable" state (waiting for CPU). If many goroutines are runnable while one dominates CPU, starvation is happening
|
||||
- **`go tool trace`** — visualizes goroutine scheduling over time. Look for gaps where goroutines aren't running because one goroutine monopolized the scheduler
|
||||
- **`runtime/metrics` (Go 1.19+)** — measure `/sched/latencies:seconds` to quantify how long goroutines wait for CPU
|
||||
- **Observable symptoms** — high response latency, requests timing out, uneven request distribution, goroutine counts climbing
|
||||
|
||||
**Preventing inlining with `//go:noinline`:** If you have a function that's normally inlinable (small, hot) but you specifically want it to not inline to force scheduler preemption checks, use the `//go:noinline` compiler directive:
|
||||
|
||||
```go
|
||||
//go:noinline
|
||||
func processBatch(item WorkItem) {
|
||||
// CPU-intensive work here
|
||||
// This call site will NOT be inlined, even if the function is small
|
||||
// The function call itself becomes a preemption point for the scheduler
|
||||
}
|
||||
|
||||
// In tight loop
|
||||
for item := range work {
|
||||
processBatch(item) // Guaranteed preemption point
|
||||
}
|
||||
```
|
||||
|
||||
**Trade-off:** Using `//go:noinline` prevents inlining, which:
|
||||
|
||||
- **Pros:** Guarantees scheduler preemption checks; prevents goroutine starvation
|
||||
- **Cons:** Adds function call overhead (~10-30 CPU cycles); reduces instruction-level parallelism (ILP) in the caller
|
||||
|
||||
Only use `//go:noinline` if profiling shows that scheduler preemption starvation is actually blocking other goroutines. Unnecessary `//go:noinline` directives penalize throughput and latency.
|
||||
|
||||
## Reflection and Type Assertions
|
||||
|
||||
**Diagnose:** 1- `go tool pprof` (CPU profile) — look for `reflect.Value.*`, `reflect.DeepEqual`, or `fmt.Sprintf` (which uses reflect internally) appearing in hot paths 2- `go test -bench` — compare reflection-based vs typed versions; expect 10-200x difference depending on the reflection operation
|
||||
|
||||
- **`reflect` in hot paths** — 10-100x slower due to type introspection and boxing. Replace with generics or typed code
|
||||
- **`reflect.DeepEqual`** — 50-200x slower than typed comparisons. Use `slices.Equal`, `maps.Equal`, `bytes.Equal` (Go 1.21+)
|
||||
- **Type switch vs repeated assertions** — type switch dispatches in one evaluation:
|
||||
|
||||
```go
|
||||
// Bad — evaluates interface multiple times
|
||||
if s, ok := v.(string); ok { return s }
|
||||
if i, ok := v.(int); ok { return strconv.Itoa(i) }
|
||||
|
||||
// Good — single dispatch
|
||||
switch v := v.(type) {
|
||||
case string: return v
|
||||
case int: return strconv.Itoa(v)
|
||||
}
|
||||
```
|
||||
|
||||
## Monotonic Time
|
||||
|
||||
**Diagnose:** 1- `go test -bench` — benchmark `time.Since(start)` vs `time.Now().Sub(start)`; expect a small but consistent improvement from monotonic clock avoiding wall-clock syscall
|
||||
|
||||
`time.Since(start)` uses the monotonic clock, which is immune to wall-clock adjustments (NTP, DST) and slightly faster:
|
||||
|
||||
```go
|
||||
var appStart = time.Now() // captures monotonic time + wall-clock on program start
|
||||
|
||||
func myFunc() {
|
||||
// Compare durations, not wall-clock times
|
||||
elapsed := time.Since(appStart)
|
||||
if elapsed > threshold { ... }
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,299 @@
|
||||
# I/O & Networking Optimization
|
||||
|
||||
Network and I/O bottlenecks show up as goroutines blocked on syscalls or waiting for responses. The key levers are connection reuse, proper timeouts, and streaming instead of buffering.
|
||||
|
||||
## HTTP Transport Configuration
|
||||
|
||||
**Diagnose:** 1- `go tool pprof` (goroutine + block profile) — look for goroutines blocked on `net/http.(*Transport).dialConn` or `net/http.(*persistConn).readLoop`; many goroutines waiting here means connection pool exhaustion 2- `fgprof` — captures both on-CPU and off-CPU wait time; look for HTTP calls dominating wall-clock time even when CPU profile shows them as cheap 3- `go tool trace` — visualize goroutine lifecycles; look for long gaps where goroutines wait for network I/O instead of processing 4- Prometheus `go_goroutines` — monitor goroutine count in production; steadily rising under stable load suggests connection or goroutine leaks from misconfigured HTTP clients
|
||||
|
||||
### Connection pooling
|
||||
|
||||
The default `http.Transport` has conservative pool settings — `MaxIdleConnsPerHost` defaults to 2. Under high concurrency, requests queue waiting for connections instead of running in parallel:
|
||||
|
||||
```go
|
||||
// Bad — default transport, only 2 idle connections per host
|
||||
client := &http.Client{}
|
||||
|
||||
// Good — tuned for high-concurrency service-to-service calls
|
||||
var apiClient = &http.Client{
|
||||
Timeout: 30 * time.Second,
|
||||
Transport: &http.Transport{
|
||||
MaxIdleConns: 100, // total idle connections across all hosts
|
||||
MaxIdleConnsPerHost: 20, // per-host idle connections (default is 2!)
|
||||
MaxConnsPerHost: 50, // cap total connections per host (0 = unlimited)
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
TLSHandshakeTimeout: 5 * time.Second,
|
||||
ResponseHeaderTimeout: 10 * time.Second,
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
For web crawlers hitting many different hosts, disable keep-alive to avoid accumulating idle connections:
|
||||
|
||||
```go
|
||||
crawlerClient := &http.Client{
|
||||
Transport: &http.Transport{DisableKeepAlives: true},
|
||||
}
|
||||
```
|
||||
|
||||
### Timeouts
|
||||
|
||||
The zero-value `http.Client` and `http.Server` have NO timeouts. A slow or malicious peer holds connections open indefinitely, exhausting file descriptors and memory:
|
||||
|
||||
```go
|
||||
// Server — always set timeouts to prevent Slowloris attacks
|
||||
server := &http.Server{
|
||||
Addr: ":8080",
|
||||
Handler: handler,
|
||||
ReadTimeout: 5 * time.Second,
|
||||
WriteTimeout: 10 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
}
|
||||
```
|
||||
|
||||
### Drain response body for connection reuse
|
||||
|
||||
Connections are only returned to the pool when the body is fully read. Even if you don't need the body, drain it:
|
||||
|
||||
```go
|
||||
resp, err := client.Get(url)
|
||||
if err != nil { return err }
|
||||
defer resp.Body.Close()
|
||||
_, _ = io.Copy(io.Discard, resp.Body) // drain to enable connection reuse
|
||||
```
|
||||
|
||||
## Streaming vs Buffering
|
||||
|
||||
**Diagnose:** 1- `go tool pprof -inuse_space` — look for large single allocations (MB-sized) from `io.ReadAll`, `bytes.Buffer.Grow`, or `json.Unmarshal`; these indicate buffering entire payloads instead of streaming
|
||||
|
||||
### Avoid io.ReadAll for large payloads
|
||||
|
||||
`io.ReadAll` loads the entire stream into memory. For large files or HTTP responses, this causes massive memory spikes:
|
||||
|
||||
```go
|
||||
// Bad — 2GB file = 2GB allocation
|
||||
data, _ := io.ReadAll(f)
|
||||
|
||||
// Good — process line by line, O(1) memory
|
||||
scanner := bufio.NewScanner(f)
|
||||
for scanner.Scan() { processLine(scanner.Bytes()) }
|
||||
|
||||
// Good — stream between reader and writer (32KB internal buffer)
|
||||
io.Copy(w, resp.Body)
|
||||
```
|
||||
|
||||
`io.ReadAll` is fine for small, bounded payloads (< 1MB) where the size is known.
|
||||
|
||||
### Streaming JSON
|
||||
|
||||
Use `json.NewDecoder` for large JSON payloads instead of `json.Unmarshal` (which buffers the entire body):
|
||||
|
||||
```go
|
||||
dec := json.NewDecoder(r)
|
||||
for dec.More() {
|
||||
var item Item
|
||||
if err := dec.Decode(&item); err != nil { return err }
|
||||
process(item) // one item at a time
|
||||
}
|
||||
```
|
||||
|
||||
## JSON Performance
|
||||
|
||||
**Diagnose:** 1- `go tool pprof` (CPU profile) — look for `encoding/json.(*Decoder).Decode`, `reflect.Value.*`, or `encoding/json.Marshal` consuming significant CPU; these indicate reflection-based JSON is the bottleneck 2- `go test -bench -benchmem` — measure ns/op and allocs/op for marshal/unmarshal; expect high alloc counts from reflection; code-gen alternatives should show 2-5x fewer allocs
|
||||
|
||||
The standard `encoding/json` package uses reflection to inspect struct fields at runtime. For high-throughput services, this creates significant CPU and allocation overhead.
|
||||
|
||||
**Options for faster JSON:**
|
||||
|
||||
- **Custom `MarshalJSON`/`UnmarshalJSON`** — hand-written methods for hot-path types eliminate reflection
|
||||
- **Code-generation libraries** — `easyjson`, `ffjson` generate marshal/unmarshal methods at build time, no reflection at runtime
|
||||
- **Drop-in replacements** — `github.com/goccy/go-json`, `github.com/json-iterator/go`, `github.com/bytedance/sonic` offer 2-5x better performance
|
||||
- **`encoding/json/v2`** (experimental, behind `GOEXPERIMENT=jsonv2`) — evaluate deliberately; most production code should keep `encoding/json` unless the project explicitly opts into the experiment
|
||||
|
||||
When using third-party JSON libraries, refer to the library's official documentation for up-to-date API signatures.
|
||||
|
||||
## Cgo Overhead
|
||||
|
||||
**Diagnose:** 1- `go tool pprof` (CPU profile + threadcreate profile) — look for `runtime.cgocall` or `runtime.asmcgocall` consuming CPU; high threadcreate count means cgo calls are pinning goroutines to OS threads 2- `go test -bench` — benchmark the cgo call loop vs a pure Go equivalent; expect ~50-100ns overhead per cgo crossing
|
||||
|
||||
Each Go-to-C call via cgo costs ~50-100ns due to stack switching, signal mask manipulation, and scheduler coordination:
|
||||
|
||||
```go
|
||||
// Bad — cgo overhead per element dominates for tight loops
|
||||
for i, v := range values {
|
||||
values[i] = float64(C.sqrt(C.double(v))) // ~100ns overhead PER CALL
|
||||
}
|
||||
|
||||
// Good — use pure Go stdlib (math.Sqrt is as fast as C and inlineable)
|
||||
for i, v := range values { values[i] = math.Sqrt(v) }
|
||||
|
||||
// Good — batch when C code is unavoidable
|
||||
C.batch_sqrt((*C.double)(&values[0]), C.int(len(values))) // amortize overhead
|
||||
```
|
||||
|
||||
Additional cgo costs: goroutine is pinned to an OS thread, C code cannot be preempted (may delay GC), and function inlining is blocked at the boundary.
|
||||
|
||||
## Buffered I/O
|
||||
|
||||
**Diagnose:** 1- `go test -bench` — benchmark buffered vs unbuffered I/O; expect 3-10x improvement from reducing syscall count 2- `go tool trace` — look for frequent short syscalls (`pread`, `pwrite`) in rapid succession; many tiny I/O operations indicate unbuffered access
|
||||
|
||||
Unbuffered file reads/writes issue a syscall per operation. `bufio.Reader` and `bufio.Writer` batch small operations, reducing syscalls by 10x or more:
|
||||
|
||||
```go
|
||||
// Bad — syscall per line
|
||||
for _, line := range lines { f.WriteString(line + "\n") }
|
||||
|
||||
// Good — buffered, batches writes into larger chunks
|
||||
w := bufio.NewWriter(f)
|
||||
for _, line := range lines { w.WriteString(line + "\n") }
|
||||
w.Flush()
|
||||
```
|
||||
|
||||
## Concurrent Multi-Stage Pipelines
|
||||
|
||||
**Diagnose:** 1- `go tool trace` — visualize resource utilization across stages; look for sequential idle gaps where CPU, disk, or network sit unused while another resource is busy 2- `go tool pprof` (CPU + goroutine profile) — confirm each stage saturates a _different_ resource; if multiple stages compete for the same resource (e.g., both CPU-bound), concurrency won't help
|
||||
|
||||
In rare scenarios where each pipeline stage saturates a _different_ resource (CPU, disk I/O, network), running stages concurrently instead of sequentially can improve throughput — even with batching between stages.
|
||||
|
||||
### The unusual scenario
|
||||
|
||||
Imagine processing records: Stage A compresses (CPU-bound), Stage B writes to disk (I/O-bound), Stage C uploads to network (network-bound). Sequential execution wastes resources:
|
||||
|
||||
```
|
||||
Time: 0 10 20 30 40 50
|
||||
CPU: AAAAAAAAAA|..........|..........|..........|
|
||||
Disk: ..........|BBBBBBBBBB|..........|..........|
|
||||
Network: ..........|..........|CCCCCCCCCC|..........|
|
||||
```
|
||||
|
||||
Concurrent stages let resources work in parallel:
|
||||
|
||||
```
|
||||
Time: 0 10 20 30 40 50
|
||||
CPU: AAAAAAAAAA|AA........|
|
||||
Disk: ..........|BBBBBBBBBB|BB........|
|
||||
Network: ..........|..........|CCCCCCCCCC|CC........|
|
||||
```
|
||||
|
||||
**Code pattern:**
|
||||
|
||||
```go
|
||||
// Each stage runs in its own goroutine, bounded by channel buffers
|
||||
compressedCh := make(chan []byte, 100) // A → B buffer
|
||||
uploadedCh := make(chan bool, 100) // B → C buffer
|
||||
|
||||
// Stage A: CPU-bound compression
|
||||
go func() {
|
||||
for record := range inputCh {
|
||||
compressed := compress(record) // saturates CPU
|
||||
compressedCh <- compressed
|
||||
}
|
||||
close(compressedCh)
|
||||
}()
|
||||
|
||||
// Stage B: I/O-bound disk writes
|
||||
go func() {
|
||||
for compressed := range compressedCh {
|
||||
diskFile.Write(compressed) // saturates disk I/O
|
||||
uploadedCh <- true
|
||||
}
|
||||
close(uploadedCh)
|
||||
}()
|
||||
|
||||
// Stage C: network-bound uploads
|
||||
go func() {
|
||||
for <-uploadedCh {
|
||||
client.Post(uploadURL, ...) // saturates network
|
||||
}
|
||||
}()
|
||||
```
|
||||
|
||||
With batching per stage, total throughput = min(A_throughput, B_throughput, C_throughput). Without concurrency, throughput = sequential sum of stages. **Concurrent stages only help when bottlenecks don't overlap.**
|
||||
|
||||
### When to use this (and when NOT to)
|
||||
|
||||
**Use concurrent pipelines only when ALL of these are true:**
|
||||
|
||||
1. **Resource saturation is predictable and non-overlapping** — You measured that A saturates one resource (e.g., CPU = 95%), B saturates another (disk I/O = 90%), C saturates a third (network = 85%). Overlapping saturation means concurrency adds no benefit.
|
||||
2. **Bottleneck shifts don't hurt latency** — Processing order doesn't matter, or records can flow out-of-order through stages.
|
||||
3. **Buffering overhead is acceptable** — Inter-stage channels consume memory. For large records, channel buffers can overflow system limits.
|
||||
4. **You've benchmarked the alternative** — Profile both sequential and concurrent versions. Sequential + batching often wins because it is simpler and avoids context-switching overhead.
|
||||
|
||||
**Avoid concurrent pipelines if:**
|
||||
|
||||
- **Records must be ordered** — Concurrent processing may reorder records; if downstream expects order, you need synchronization that kills the speedup.
|
||||
- **Resources overlap** — If A and B both compete for CPU (e.g., both compress), concurrency causes context-switching overhead with no resource utilization gain.
|
||||
- **Latency matters more than throughput** — A single record now travels through 3 stages in parallel, increasing per-record latency.
|
||||
- **Memory is tight** — Each stage's channel buffer is a memory budget; deeply buffered channels can exhaust available RAM.
|
||||
|
||||
→ See `samber/cc-skills-golang@golang-concurrency` skill for detailed channel patterns and when to use worker pools instead.
|
||||
|
||||
## Batch Operations
|
||||
|
||||
**Diagnose:** 1- `go test -bench` — benchmark single-item vs batched operations; expect N-fold improvement in throughput when amortizing per-operation overhead (syscalls, round-trips) 2- `go tool trace` — look for repeated short network/disk operations with idle gaps between them; these gaps represent wasted round-trip time that batching eliminates
|
||||
|
||||
Batching amortizes per-operation overhead (syscalls, network round-trips, transaction costs) across many items. The pattern applies everywhere: I/O, database, network, and even in-memory processing.
|
||||
|
||||
### Database: batch inserts over row-by-row
|
||||
|
||||
Inserting 1,000 rows one at a time means 1,000 round-trips, 1,000 query parses, and 1,000 transaction commits. A single batch insert does it in one round-trip:
|
||||
|
||||
```go
|
||||
// Bad — 1,000 round-trips, ~500ms
|
||||
for _, user := range users {
|
||||
db.Exec("INSERT INTO users (name, email) VALUES ($1, $2)", user.Name, user.Email)
|
||||
}
|
||||
|
||||
// Good — 1 round-trip with multi-row VALUES, ~5ms
|
||||
const batchSize = 1000
|
||||
for i := 0; i < len(users); i += batchSize {
|
||||
end := min(i+batchSize, len(users))
|
||||
batch := users[i:end]
|
||||
// Build multi-row INSERT or use COPY protocol
|
||||
tx, _ := db.Begin()
|
||||
stmt, _ := tx.Prepare(pq.CopyIn("users", "name", "email"))
|
||||
for _, u := range batch { stmt.Exec(u.Name, u.Email) }
|
||||
stmt.Exec()
|
||||
tx.Commit()
|
||||
}
|
||||
```
|
||||
|
||||
→ See `samber/cc-skills-golang@golang-database` skill for detailed batch patterns and connection pool configuration.
|
||||
|
||||
### HTTP: batch API calls
|
||||
|
||||
Instead of N individual HTTP requests, send one request with N items when the API supports it:
|
||||
|
||||
```go
|
||||
// Bad — 100 HTTP round-trips
|
||||
for _, id := range ids {
|
||||
resp, _ := client.Get(fmt.Sprintf("/api/users/%s", id))
|
||||
// ...
|
||||
}
|
||||
|
||||
// Good — 1 HTTP request with all IDs
|
||||
resp, _ := client.Post("/api/users/batch", "application/json",
|
||||
bytes.NewReader(marshalIDs(ids)))
|
||||
```
|
||||
|
||||
### Channel: batch processing from a stream
|
||||
|
||||
Accumulate items from a channel and process in bulk to reduce per-item overhead:
|
||||
|
||||
```go
|
||||
func batchProcessor(in <-chan Item, batchSize int) {
|
||||
batch := make([]Item, 0, batchSize)
|
||||
ticker := time.NewTicker(100 * time.Millisecond) // flush on timeout too
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case item, ok := <-in:
|
||||
if !ok { flush(batch); return }
|
||||
batch = append(batch, item)
|
||||
if len(batch) >= batchSize { flush(batch); batch = batch[:0] }
|
||||
case <-ticker.C:
|
||||
if len(batch) > 0 { flush(batch); batch = batch[:0] }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,233 @@
|
||||
# Memory Optimization
|
||||
|
||||
Allocation reduction is the single highest-ROI optimization in most Go programs. Every allocation eventually requires garbage collection — reducing allocation count and size directly reduces GC pauses and CPU overhead.
|
||||
|
||||
## Allocation Patterns
|
||||
|
||||
**Diagnose:** 1- `go tool pprof -alloc_objects` — rank functions by number of heap allocations; expect hot-path functions (request handlers, serializers) near the top with thousands of alloc/op 2- `go build -gcflags="-m -m"` — verbose escape analysis showing _why_ variables escape; look for `"leaking param"`, `"too large for stack"`, or `"captured by closure"` on variables you expect to stay on the stack 3- `go test -bench -benchmem` — measure allocs/op and B/op per benchmark; expect the target function to show >0 allocs/op that can be eliminated
|
||||
|
||||
### Reuse slices via append(s[:0], ...)
|
||||
|
||||
Reslicing to zero length retains the backing array, turning what would be a new allocation into a no-op:
|
||||
|
||||
```go
|
||||
// Bad — allocates new slice, old one becomes garbage
|
||||
mode = []T{item}
|
||||
|
||||
// Good — reuses existing backing array (0 allocations)
|
||||
mode = append(mode[:0], item)
|
||||
```
|
||||
|
||||
### Direct indexing vs append
|
||||
|
||||
When the output size equals the input size, use `make([]T, len(input))` with direct assignment instead of `make([]T, 0, len(input))` with `append`. Direct assignment avoids per-element bounds checking and length increment:
|
||||
|
||||
```go
|
||||
// Slower — append overhead per element
|
||||
result := make([]T, 0, len(input))
|
||||
for i := range input { result = append(result, transform(input[i])) }
|
||||
|
||||
// Faster — direct assignment
|
||||
result := make([]T, len(input))
|
||||
for i := range input { result[i] = transform(input[i]) }
|
||||
```
|
||||
|
||||
Use append when the result might be smaller (filtering) or when early error return could discard partial results.
|
||||
|
||||
### Eliminate redundant map lookups
|
||||
|
||||
`for k := range m { use(m[k]) }` does two lookups per iteration. Capture the value from range:
|
||||
|
||||
```go
|
||||
// Bad — two lookups per iteration
|
||||
for k := range in { result[k] = fn(in[k]) }
|
||||
|
||||
// Good — single lookup
|
||||
for k, v := range in { result[k] = fn(v) }
|
||||
```
|
||||
|
||||
### Map size hints
|
||||
|
||||
`make(map[K]V)` starts with a small number of buckets and rehashes as it grows. Providing a size hint avoids rehashing:
|
||||
|
||||
```go
|
||||
m := make(map[string]int, len(items)) // single allocation, no rehashing
|
||||
```
|
||||
|
||||
### Sentinel errors vs fmt.Errorf
|
||||
|
||||
`fmt.Errorf` allocates on every call. For predictable errors in hot paths, use preallocated sentinels:
|
||||
|
||||
```go
|
||||
var ErrNegative = errors.New("value is negative") // allocated once
|
||||
|
||||
func validate(x int) error {
|
||||
if x < 0 { return ErrNegative } // zero allocation
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
Only use `fmt.Errorf` when you need dynamic context (field names, values).
|
||||
|
||||
### Interface boxing
|
||||
|
||||
Passing concrete types through `any`/`interface{}` forces heap allocation for boxing. In hot paths, use typed parameters or generics:
|
||||
|
||||
```go
|
||||
// Bad — boxes each int, allocates
|
||||
func sum(values []any) int { ... }
|
||||
|
||||
// Good — no boxing, no allocation
|
||||
func sum(values []int) int { ... }
|
||||
|
||||
// Good — generic, still no boxing
|
||||
func sum[T ~int | ~int64](values []T) T { ... }
|
||||
```
|
||||
|
||||
## Backing Array Leaks
|
||||
|
||||
**Diagnose:** 1- `go tool pprof -inuse_space` — show currently live heap memory by allocation site; look for unexpectedly large live objects (MB-sized) that should have been GC'd — a sign of backing array retention 2- `go tool pprof -alloc_space` — show cumulative bytes allocated over time; look for allocation sites producing far more bytes than the final data they hold (e.g., 100MB allocated for 16-byte results)
|
||||
|
||||
### Slice reslicing retains the entire backing array
|
||||
|
||||
A small reslice of a large slice keeps the entire original array in memory:
|
||||
|
||||
```go
|
||||
// Bad — retains entire megabyte-sized backing array
|
||||
func getHeader(data []byte) []byte { return data[:16] }
|
||||
|
||||
// Good — independent copy, original can be GC'd
|
||||
func getHeader(data []byte) []byte {
|
||||
header := make([]byte, 16)
|
||||
copy(header, data[:16])
|
||||
return header
|
||||
}
|
||||
```
|
||||
|
||||
### Substring memory leaks
|
||||
|
||||
Substrings share the backing array of the original string:
|
||||
|
||||
```go
|
||||
// Bad — keeps entire longMsg in memory
|
||||
func extractID(msg string) string { return msg[:8] }
|
||||
|
||||
// Good — independent copy (Go 1.20+)
|
||||
func extractID(msg string) string { return strings.Clone(msg[:8]) }
|
||||
```
|
||||
|
||||
### Map never shrinks
|
||||
|
||||
Go maps grow but never release bucket memory when entries are deleted. A map that once held millions of entries retains its allocation forever:
|
||||
|
||||
```go
|
||||
// Recreate periodically to reclaim memory
|
||||
func compact(old map[string]Data) map[string]Data {
|
||||
m := make(map[string]Data, len(old))
|
||||
for k, v := range old { m[k] = v }
|
||||
return m // old map becomes eligible for GC
|
||||
}
|
||||
```
|
||||
|
||||
## String and Byte Optimization
|
||||
|
||||
**Diagnose:** 1- `go tool pprof -alloc_objects` — look for string/byte conversion functions (`runtime.stringtoslicebyte`, `runtime.slicebytetostring`) appearing as top allocators 2- `go test -bench -benchmem` — measure allocs/op; expect repeated conversions to show 1+ alloc/op per conversion that can be reduced to zero by caching
|
||||
|
||||
**Cache string-to-byte conversions** — converting between `string` and `[]byte` allocates a copy each time. Convert once and reuse the result.
|
||||
|
||||
**Use `bytes` package directly** — `bytes.Contains`, `bytes.HasPrefix`, `bytes.Split`, `bytes.ToUpper` etc. operate on `[]byte` without string conversion. The `bytes` package mirrors most of `strings`.
|
||||
|
||||
## sync.Pool Hot-Path Patterns
|
||||
|
||||
**Diagnose:** 1- `go tool pprof -alloc_objects` — identify hot allocation sites creating the same object type repeatedly (e.g., `[]byte` buffers, temp structs); expect one site with thousands of allocs/s that can be pooled
|
||||
|
||||
`sync.Pool` recycles objects across GC cycles, reducing allocation pressure. Use it for frequently allocated, short-lived objects in hot paths (HTTP handlers, serialization, logging):
|
||||
|
||||
```go
|
||||
var bufPool = sync.Pool{
|
||||
New: func() any {
|
||||
buf := make([]byte, 0, 4096)
|
||||
return &buf
|
||||
},
|
||||
}
|
||||
|
||||
func handleRequest(data []byte) []byte {
|
||||
bp := bufPool.Get().(*[]byte)
|
||||
buf := (*bp)[:0] // reset length, keep capacity
|
||||
defer func() { *bp = buf; bufPool.Put(bp) }()
|
||||
|
||||
// ... process data into buf ...
|
||||
|
||||
result := make([]byte, len(buf))
|
||||
copy(result, buf) // return a copy — buf goes back to pool
|
||||
return result
|
||||
}
|
||||
```
|
||||
|
||||
**Rules:**
|
||||
|
||||
- Reset state before `Put()` — clear references to avoid retaining large object graphs across GC cycles
|
||||
- Return copies, not pooled buffers — callers must not hold references to pooled memory
|
||||
- Don't pool objects >32KB — large allocations bypass the pool's size classes and GC already handles them efficiently
|
||||
- Don't pool infrequently used objects — pool overhead exceeds benefit when allocations are rare
|
||||
|
||||
→ See `samber/cc-skills-golang@golang-concurrency` skill for `sync.Pool` API reference and basic usage patterns.
|
||||
|
||||
## Memory Layout
|
||||
|
||||
**Diagnose:** 1- `fieldalignment ./...` — detect structs with wasted padding bytes; expect warnings like `"struct of size 40 could be 24"` listing which structs benefit from reordering 2- `unsafe.Sizeof`/`Alignof`/`Offsetof` — measure exact byte sizes and field offsets; use to confirm savings before/after and document them in code comments
|
||||
|
||||
### Struct field alignment
|
||||
|
||||
Go adds padding between fields to satisfy alignment requirements. Reorder fields from largest to smallest:
|
||||
|
||||
```go
|
||||
// Bad — 24 bytes (7 + 3 bytes padding)
|
||||
type Bad struct {
|
||||
a bool // 1 byte + 7 padding
|
||||
b int64 // 8 bytes
|
||||
c bool // 1 byte + 3 padding
|
||||
d int32 // 4 bytes
|
||||
}
|
||||
|
||||
// Good — 16 bytes (2 bytes padding)
|
||||
type Good struct {
|
||||
b int64 // 8 bytes
|
||||
d int32 // 4 bytes
|
||||
a bool // 1 byte
|
||||
c bool // 1 byte + 2 padding
|
||||
}
|
||||
```
|
||||
|
||||
**Alignment requirements:** `bool`/`byte` = 1, `int16` = 2, `int32`/`float32` = 4, `int64`/`float64`/`string`/`[]T`/`*T` = 8.
|
||||
|
||||
**Inspect layout:** `unsafe.Sizeof(T{})`, `unsafe.Alignof(T{})`, `unsafe.Offsetof(T{}.field)`
|
||||
|
||||
### Zero-size field at end of struct
|
||||
|
||||
If the last field has zero size (`struct{}`), the compiler adds word-sized padding to prevent a pointer to that field from overlapping the next memory block:
|
||||
|
||||
```go
|
||||
// Bad — 16 bytes (8 for Value + 8 padding for Flag)
|
||||
type Entry struct { Value int64; Flag struct{} }
|
||||
|
||||
// Good — 8 bytes (0 for Flag + 8 for Value)
|
||||
type Entry struct { Flag struct{}; Value int64 }
|
||||
```
|
||||
|
||||
Having a `struct{}` field in a struct is rare and almost useless.
|
||||
|
||||
### Pointer receivers for large structs
|
||||
|
||||
Value receivers copy the entire struct on every method call. Use pointer receivers for structs larger than ~128 bytes. If any method uses a pointer receiver, all methods should for consistency.
|
||||
|
||||
### Map of pointers for large, frequently updated structs
|
||||
|
||||
Map values are not addressable — you cannot modify a field in place. For large structs with frequent updates, `map[K]*V` avoids the copy-modify-reassign pattern:
|
||||
|
||||
```go
|
||||
players := map[string]*Player{"alice": {Score: 100}}
|
||||
players["alice"].Score += 10 // direct modification, no copy
|
||||
```
|
||||
|
||||
Trade-off: each pointer is a separate heap allocation, adding GC pressure. For small, mostly-read structs, `map[K]V` (value) is better.
|
||||
@@ -0,0 +1,101 @@
|
||||
# Production Observability for Performance
|
||||
|
||||
Third-party monitoring tools complement local profiling (pprof, benchmarks) by providing continuous monitoring, historical trends, and regression detection in production.
|
||||
|
||||
## Prometheus Metrics for Go
|
||||
|
||||
**Setup:** `github.com/prometheus/client_golang` — expose `/metrics` endpoint with `promhttp.Handler()`. Default collectors automatically export Go runtime metrics (`go_goroutines`, `go_memstats_*`, `go_gc_duration_seconds`, `process_cpu_seconds_total`, etc.).
|
||||
|
||||
→ See `samber/cc-skills-golang@golang-benchmark` skill (investigation-session.md) for the full runtime metrics table, investigation session setup (scrape interval tuning, env-var toggling), and cost warnings for profiling tools.
|
||||
|
||||
### PromQL Queries for Performance Diagnosis
|
||||
|
||||
#### GC pressure
|
||||
|
||||
| PromQL | What to look for |
|
||||
| --- | --- |
|
||||
| `rate(go_gc_duration_seconds_count[5m])` | GC cycles/s — >2/s sustained suggests excessive allocation rate |
|
||||
| `rate(go_gc_duration_seconds_sum[5m]) / rate(go_gc_duration_seconds_count[5m])` | Average GC pause — increasing trend means heap is growing or has too many pointers |
|
||||
| `go_gc_duration_seconds{quantile="1"}` | Worst-case GC pause — spikes here cause tail latency |
|
||||
|
||||
#### Memory leaks
|
||||
|
||||
| PromQL | What to look for |
|
||||
| --- | --- |
|
||||
| `go_memstats_alloc_bytes` | Should be roughly stable under constant load; continuous increase = memory leak |
|
||||
| `rate(go_memstats_alloc_bytes_total[5m])` | Allocation rate (bytes/s) — drives GC frequency; compare before/after deploy for regressions |
|
||||
| `process_resident_memory_bytes - go_memstats_sys_bytes` | Gap = non-Go memory (cgo, mmap); growing gap = non-Go leak |
|
||||
|
||||
#### Goroutine leaks
|
||||
|
||||
| PromQL | What to look for |
|
||||
| --- | --- |
|
||||
| `go_goroutines` | Should correlate with load; growing independently of traffic = leak |
|
||||
| `delta(go_goroutines[1h])` | Net goroutine change over 1h; positive without load increase = leak |
|
||||
|
||||
#### CPU saturation
|
||||
|
||||
| PromQL | What to look for |
|
||||
| --- | --- |
|
||||
| `rate(process_cpu_seconds_total[5m])` | CPU cores consumed; compare to GOMAXPROCS to detect saturation |
|
||||
| `rate(process_cpu_seconds_total[5m]) / <GOMAXPROCS>` | CPU utilization ratio; >0.8 sustained = CPU-saturated |
|
||||
|
||||
#### Regression detection (after deploy)
|
||||
|
||||
| PromQL | What to look for |
|
||||
| --- | --- |
|
||||
| `rate(go_memstats_alloc_bytes_total[5m])` | Compare before/after deploy; significant increase = new allocation pattern introduced |
|
||||
| `histogram_quantile(0.99, rate(http_request_duration_seconds_bucket[5m]))` | p99 latency increase after deploy = regression (requires app-level histogram) |
|
||||
|
||||
### Alerting rules (examples)
|
||||
|
||||
[Example alerting rules](../assets/prometheus-alerts.yml) — adjust thresholds to your application; a high-throughput data pipeline will have different baselines than a lightweight API server.
|
||||
|
||||
→ See `samber/cc-skills@promql-cli` skill for interactively testing these PromQL expressions against your Prometheus instance from the CLI.
|
||||
|
||||
### Grafana Dashboards
|
||||
|
||||
→ See `samber/cc-skills-golang@golang-observability` skill for recommended community Grafana dashboards that visualize Go runtime metrics out of the box.
|
||||
|
||||
## Continuous Profiling
|
||||
|
||||
Continuous profiling collects low-overhead samples in production and stores them for historical comparison. Use it to detect regressions across deploys, compare flamegraphs over time, and feed PGO (see [Runtime Tuning](./runtime.md#profile-guided-optimization-pgo)).
|
||||
|
||||
| Tool | Model | Overhead | Best for |
|
||||
| --- | --- | --- | --- |
|
||||
| **Grafana Pyroscope** | push SDK or pull (via Alloy) | ~2-5% | Grafana ecosystem, historical flamegraph comparison |
|
||||
| **Parca** (Polar Signals) | eBPF-based pull | <1% | Infrastructure-wide profiling, no code changes |
|
||||
| **Datadog Continuous Profiler** | push (agent) | ~1-2% | Existing Datadog users |
|
||||
| **Google Cloud Profiler** | push (agent) | ~1-2% | GCP-hosted Go services |
|
||||
|
||||
### Pyroscope push mode
|
||||
|
||||
```go
|
||||
import "github.com/grafana/pyroscope-go"
|
||||
|
||||
pyroscope.Start(pyroscope.Config{
|
||||
ApplicationName: "myapp",
|
||||
ServerAddress: "http://pyroscope:4040",
|
||||
ProfileTypes: []pyroscope.ProfileType{
|
||||
pyroscope.ProfileCPU,
|
||||
pyroscope.ProfileAllocObjects,
|
||||
pyroscope.ProfileAllocSpace,
|
||||
pyroscope.ProfileInuseObjects,
|
||||
pyroscope.ProfileInuseSpace,
|
||||
pyroscope.ProfileGoroutines,
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Pyroscope pull mode (via Grafana Alloy)
|
||||
|
||||
No code changes required — Alloy scrapes `/debug/pprof/*` endpoints periodically. Configure Alloy to target your service's pprof endpoint.
|
||||
|
||||
When using third-party profiling libraries, refer to the library's official documentation for current API signatures.
|
||||
|
||||
## Real-Time Visualization (Development)
|
||||
|
||||
| Tool | What it does |
|
||||
| --- | --- |
|
||||
| **statsviz** (`github.com/arl/statsviz`) | Real-time browser dashboard at `/debug/statsviz` — heap, GC pauses, goroutines, scheduler. Register with `statsviz.Register(mux)`. Great for local development |
|
||||
| **expvar** (stdlib `expvar`) | JSON metrics at `/debug/vars` — lightweight, no dependencies. Integrates with Netdata, Telegraf, or custom dashboards |
|
||||
@@ -0,0 +1,222 @@
|
||||
# Runtime Tuning
|
||||
|
||||
Runtime settings control garbage collection frequency, memory limits, CPU scheduling, and compiler optimizations. Tune them after profiling — the defaults are well-chosen for most workloads.
|
||||
|
||||
## Garbage Collector Tuning
|
||||
|
||||
**Diagnose:** 1- `GODEBUG=gctrace=1` — print one line per GC cycle; look for high GC frequency (cycles/s), high CPU% (>5% means GC is competing for CPU), or heap growing faster than expected 2- `runtime.ReadMemStats` — inspect `Alloc`, `TotalAlloc`, `NumGC`, `PauseNs`; compare `Alloc` vs `Sys` to see how much memory the GC is reclaiming vs how much the OS allocated 3- `go tool trace` — visualize GC stop-the-world pauses and GC assist stealing CPU from application goroutines; look for long STW bars or frequent assist marks 4- `debug.ReadGCStats` — get pause time percentiles (p50, p95, p99); high p99 pauses indicate large heap scans or too many pointers 5- `runtime/metrics` — programmatic access to GC stats for dashboards; monitor `/gc/cycles/total`, `/gc/heap/allocs`, `/gc/pauses` 6- `GODEBUG=gcpacertrace=1` — trace the GC pacer's decisions; useful to understand why GC triggers earlier or later than expected 7- Prometheus `rate(go_gc_duration_seconds_count[5m])` — monitor GC frequency in production; >2 cycles/s sustained suggests excessive allocation rate
|
||||
|
||||
### GOGC (default: 100)
|
||||
|
||||
Controls the heap growth ratio that triggers the next GC cycle. `GOGC=100` means GC runs when the heap doubles since the last collection. Higher values reduce GC frequency but use more memory:
|
||||
|
||||
```bash
|
||||
GOGC=50 ./myapp # latency-sensitive: more frequent, shorter GC pauses
|
||||
GOGC=200 ./myapp # throughput-oriented: less frequent GC, more memory used
|
||||
GOGC=off ./myapp # disable GC entirely (testing only!)
|
||||
```
|
||||
|
||||
### GOMEMLIMIT (Go 1.19+)
|
||||
|
||||
Soft memory limit — the runtime increases GC frequency to stay under this limit. Essential for containerized applications where exceeding the container limit triggers an OOM kill:
|
||||
|
||||
```bash
|
||||
# Container with 512MB limit: leave headroom for non-heap memory (goroutine stacks, OS buffers)
|
||||
GOMEMLIMIT=450MiB ./myapp
|
||||
|
||||
# Container with 1GB limit
|
||||
GOMEMLIMIT=900MiB ./myapp
|
||||
```
|
||||
|
||||
The GC pacer adjusts collection timing based on both GOGC and GOMEMLIMIT. When the heap approaches the limit, the GC runs more aggressively regardless of GOGC.
|
||||
|
||||
### Programmatic control
|
||||
|
||||
```go
|
||||
import "runtime/debug"
|
||||
|
||||
debug.SetGCPercent(200) // equivalent to GOGC=200
|
||||
debug.SetMemoryLimit(450 * 1024 * 1024) // 450 MiB soft limit
|
||||
```
|
||||
|
||||
Use programmatic control for dynamic tuning based on observed workload, or when environment variables cannot be set.
|
||||
|
||||
### Ballast pattern (pre-Go 1.19)
|
||||
|
||||
Before GOMEMLIMIT, teams allocated a large byte array at startup to inflate the live heap size, reducing GC frequency:
|
||||
|
||||
```go
|
||||
var ballast [1 << 30]byte // 1 GB — obsolete pattern
|
||||
```
|
||||
|
||||
**GOMEMLIMIT is strictly better** — it provides the same benefit (fewer GC cycles) without wasting physical memory. Use GOMEMLIMIT instead.
|
||||
|
||||
## GC Profiling and Diagnostics
|
||||
|
||||
### GODEBUG=gctrace=1
|
||||
|
||||
Prints a line per GC cycle to stderr:
|
||||
|
||||
```bash
|
||||
GODEBUG=gctrace=1 ./myapp 2>&1 | head -20
|
||||
```
|
||||
|
||||
Sample output:
|
||||
|
||||
```
|
||||
gc 5 @1.234s 2%: 0.012+12+0.9 ms clock, 0.25+8.9/20+18 ms cpu, 45->92->50 MB, 200 MB goal, 8 P
|
||||
```
|
||||
|
||||
Key fields:
|
||||
|
||||
- `gc 5` — 5th GC cycle
|
||||
- `@1.234s` — time since program start
|
||||
- `2%` — total CPU time spent in GC
|
||||
- `45->92->50 MB` — heap before → peak during collection → after
|
||||
- `200 MB goal` — target heap size (based on GOGC and GOMEMLIMIT)
|
||||
- `8 P` — number of processors
|
||||
|
||||
Watch for: GC frequency (too often = too many allocations), pause times (high = large heap or many pointers), CPU% (high = tune GOGC or reduce allocations).
|
||||
|
||||
### runtime.ReadMemStats
|
||||
|
||||
Programmatic monitoring for dashboards and alerting:
|
||||
|
||||
```go
|
||||
var m runtime.MemStats
|
||||
runtime.ReadMemStats(&m)
|
||||
|
||||
fmt.Printf("Alloc: %d MB\n", m.Alloc/1024/1024) // currently allocated
|
||||
fmt.Printf("TotalAlloc: %d MB\n", m.TotalAlloc/1024/1024) // cumulative
|
||||
fmt.Printf("Sys: %d MB\n", m.Sys/1024/1024) // requested from OS
|
||||
fmt.Printf("NumGC: %d\n", m.NumGC) // completed collections
|
||||
fmt.Printf("LastPause: %d ms\n", m.PauseNs[(m.NumGC+255)%256]/1_000_000)
|
||||
```
|
||||
|
||||
### GC pacing
|
||||
|
||||
The GC pacer predicts when to start the next collection based on:
|
||||
|
||||
1. **Live heap size** after the last collection
|
||||
2. **GOGC percentage** — how much growth to allow
|
||||
3. **GOMEMLIMIT** — soft ceiling (if set)
|
||||
4. **Current allocation rate** — how fast the heap is growing
|
||||
|
||||
The pacer starts collection early enough to finish before hitting the target. Fast allocation rates cause earlier starts.
|
||||
|
||||
## Allocation Rate Reduction
|
||||
|
||||
**Diagnose:** 1- `go tool pprof -alloc_objects` — rank functions by allocation count; the top allocators are where allocation reduction will have the biggest GC impact 2- `GODEBUG=gctrace=1` — monitor GC frequency before and after reducing allocations; expect fewer GC cycles per second as allocation rate drops 3- Prometheus `rate(go_memstats_alloc_bytes_total[5m])` — track allocation rate trend in production; compare before/after deploy to detect regressions
|
||||
|
||||
Reducing allocations helps more than tuning GOGC — it addresses the root cause instead of managing the symptom:
|
||||
|
||||
- **Value types over pointer types** where possible — values stay on the stack (no GC), pointers escape to the heap
|
||||
- **Pool frequently allocated objects** with `sync.Pool` (see [memory.md](./memory.md))
|
||||
- **Preallocate slices and maps** — → See `samber/cc-skills-golang@golang-data-structures` skill
|
||||
- **Avoid interface boxing** in hot paths — use typed parameters or generics
|
||||
|
||||
## GOMAXPROCS in Containers
|
||||
|
||||
**Diagnose:** 1- `go tool pprof` (CPU profile) — look for high `runtime.schedule` or `runtime.findRunnable` overhead; this indicates too many P's competing for work or too few P's starving goroutines 2- `go tool trace` — check if goroutines are evenly distributed across P's; uneven distribution suggests GOMAXPROCS is misconfigured for the container 3- `GODEBUG=schedtrace=1000` — print scheduler state every second; look for `runqueue` imbalances or idle P's when work is available 4- `runtime.GOMAXPROCS(0)` — query the current value; if it returns the host CPU count (e.g., 64) instead of the container limit (e.g., 2), the runtime is over-scheduling 5- Prometheus `rate(process_cpu_seconds_total[5m])` — monitor CPU cores consumed in production; if consistently near GOMAXPROCS value, the app is CPU-saturated
|
||||
|
||||
**Go 1.25+** improves container CPU detection, particularly for cgroup v2. The runtime sets `GOMAXPROCS` based on:
|
||||
|
||||
- Logical CPUs on the machine
|
||||
- Process CPU affinity mask
|
||||
- cgroup CPU quota limits (on Linux)
|
||||
|
||||
In a container with 2 CPU cores on a 64-core host running Go 1.25+ with **cgroup v2**, `GOMAXPROCS` is correctly set to 2 by default. For **cgroup v1** environments, validate the detected value at startup and consider using `go.uber.org/automaxprocs` to ensure correctness.
|
||||
|
||||
**For Go 1.24 and earlier**, use the `go.uber.org/automaxprocs` library to handle container CPU detection:
|
||||
|
||||
```go
|
||||
// Pre-Go 1.25: explicit container-aware detection
|
||||
import _ "go.uber.org/automaxprocs"
|
||||
|
||||
func main() {
|
||||
// GOMAXPROCS is now correctly set to container CPU limit
|
||||
startServer()
|
||||
}
|
||||
```
|
||||
|
||||
**Manual override** (if needed):
|
||||
|
||||
```bash
|
||||
GOMAXPROCS=2 ./myapp
|
||||
GODEBUG=updatemaxprocs=0 ./myapp # disable dynamic updates (Go 1.25+)
|
||||
```
|
||||
|
||||
**Known limitations (Go 1.25)**: cgroup v1 on certain systems (Oracle OCPUs) may not properly detect Kubernetes CPU limits. Manually set `GOMAXPROCS` as a workaround in these cases.
|
||||
|
||||
## Profile-Guided Optimization (PGO)
|
||||
|
||||
**Diagnose:** 1- `go tool pprof` (CPU profile) — collect a representative production profile (30+ seconds); look for hot interface method calls and deep call chains that PGO can optimize via devirtualization and inlining 2- `go test -bench` — benchmark before and after placing `default.pgo`; expect 2-7% improvement on interface-heavy code, less on already-optimized paths
|
||||
|
||||
Go 1.21+ supports PGO — the compiler uses a production CPU profile to make better inlining and devirtualization decisions. Expected improvement: 2-7% for minimal effort.
|
||||
|
||||
**Workflow:**
|
||||
|
||||
1. Collect a production CPU profile (30+ seconds of representative load):
|
||||
|
||||
```bash
|
||||
curl http://localhost:6060/debug/pprof/profile?seconds=60 > cpu.pprof
|
||||
```
|
||||
|
||||
2. Place as `default.pgo` in the main package directory:
|
||||
|
||||
```bash
|
||||
cp cpu.pprof ./cmd/myapp/default.pgo
|
||||
```
|
||||
|
||||
3. Build — `go build` auto-detects `default.pgo`:
|
||||
|
||||
```bash
|
||||
go build ./cmd/myapp
|
||||
```
|
||||
|
||||
**What the compiler optimizes:**
|
||||
|
||||
- **Inlining** — hot function calls are inlined more aggressively
|
||||
- **Devirtualization** — interface method calls with high probability of targeting specific types become direct calls
|
||||
|
||||
**When it helps most:** code with many interface calls, hot inlining opportunities, deep call stacks. **When it helps least:** already-optimized code, memory-bound workloads.
|
||||
|
||||
Rebuild profiles after significant code changes — stale profiles can mislead the compiler.
|
||||
|
||||
## Logging Overhead in Hot Paths
|
||||
|
||||
**Diagnose:** 1- `go tool pprof` (CPU profile) — look for `fmt.Sprintf`, `log.Printf`, or `slog.(*Logger).log` appearing in hot paths; these indicate log formatting consuming CPU even when the log level filters the message 2- `go build -gcflags="-m"` — check if log arguments escape to the heap; expect `"moved to heap"` for arguments boxed into `any` interface by logging functions 3- `go test -bench -benchmem` — benchmark with logging enabled vs disabled; if allocs/op doesn't change, the logger is allocating even when the level is off
|
||||
|
||||
Log formatting allocates memory and consumes CPU even when the message is discarded because it's below the configured level:
|
||||
|
||||
```go
|
||||
// Bad — fmt.Sprintf runs BEFORE the logger checks the level
|
||||
logger.Debug(fmt.Sprintf("processing item %d with data %v", item.ID, item.Data))
|
||||
|
||||
// Good — slog defers formatting until level check passes (Go 1.21+)
|
||||
slog.Debug("processing item", slog.Int("id", item.ID), slog.Any("data", item.Data))
|
||||
|
||||
// Best — LogAttrs: zero allocations when level is disabled
|
||||
slog.LogAttrs(ctx, slog.LevelDebug, "processing item",
|
||||
slog.Int("id", item.ID))
|
||||
```
|
||||
|
||||
In hot paths, even `slog.Any` can allocate. Prefer typed attributes: `slog.Int`, `slog.String`, `slog.Bool`.
|
||||
|
||||
## Panic/Recover Cost
|
||||
|
||||
**Diagnose:** 1- `go tool pprof` (CPU profile) — look for `runtime.gopanic` or `runtime.gorecover` in the profile; their presence in hot paths means panic/recover is being used for control flow 2- `go test -bench` — benchmark panic/recover vs error-return versions; expect 10-100x overhead from stack unwinding and defer execution
|
||||
|
||||
`panic` triggers stack unwinding, running all deferred functions up the call stack. `recover` catches the panic but the unwinding itself is expensive. Never use panic/recover for control flow:
|
||||
|
||||
```go
|
||||
// Bad — panic overhead for a normal condition
|
||||
defer func() { recover() }()
|
||||
v, _ := strconv.Atoi(s) // relies on panic for invalid input
|
||||
|
||||
// Good — explicit error check, no panic overhead
|
||||
v, err := strconv.Atoi(s)
|
||||
if err != nil { continue }
|
||||
```
|
||||
|
||||
Panic is appropriate only for truly unrecoverable situations (programmer errors, corrupted state). Always convert panics to errors at package boundaries.
|
||||
@@ -0,0 +1,474 @@
|
||||
---
|
||||
name: golang-testing
|
||||
description: "Production-ready Golang tests — table-driven tests, testify suites and mocks, parallel tests, fuzzing, fixtures, goroutine leak detection with goleak, snapshot testing, code coverage, integration tests, idiomatic test naming. Use when writing or reviewing Go tests, choosing a testing approach, setting up Go test CI, or debugging flaky/slow tests. For testify-specific APIs see `samber/cc-skills-golang@golang-stretchr-testify`; for measurement methodology see `samber/cc-skills-golang@golang-benchmark`."
|
||||
user-invocable: true
|
||||
license: MIT
|
||||
compatibility: Designed for Claude Code or similar AI coding agents, and for projects using Golang.
|
||||
metadata:
|
||||
author: samber
|
||||
version: "1.2.5"
|
||||
openclaw:
|
||||
emoji: "🧪"
|
||||
homepage: https://github.com/samber/cc-skills-golang
|
||||
requires:
|
||||
bins:
|
||||
- go
|
||||
- gotests
|
||||
install:
|
||||
- kind: go
|
||||
package: github.com/cweill/gotests/gotests@latest
|
||||
bins: [gotests]
|
||||
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent Bash(gotests:*) AskUserQuestion
|
||||
---
|
||||
|
||||
**Persona:** You are a Go engineer who treats tests as executable specifications. You write tests to constrain behavior, not to hit coverage targets.
|
||||
|
||||
**Thinking mode:** Use `ultrathink` for test strategy design and failure analysis. Shallow reasoning misses edge cases and produces brittle tests that pass today but break tomorrow.
|
||||
|
||||
**Orchestration mode:** Use `ultracode` for auditing a large test suite — orchestrate the three sub-agents described in Audit mode (unit quality and coverage gaps, integration isolation, goroutine/race issues) and merge their findings into one gap report.
|
||||
|
||||
**Modes:**
|
||||
|
||||
- **Write mode** — generating new tests for existing or new code. Work sequentially through the code under test; use `gotests` to scaffold table-driven tests, then enrich with edge cases and error paths.
|
||||
- **Review mode** — reviewing a PR's test changes. Focus on the diff: check coverage of new behaviour, assertion quality, table-driven structure, and absence of flakiness patterns. Sequential.
|
||||
- **Audit mode** — auditing an existing test suite for gaps, flakiness, or bad patterns (order-dependent tests, missing `t.Parallel()`, implementation-detail coupling). Launch up to 3 parallel sub-agents split by concern: (1) unit test quality and coverage gaps, (2) integration test isolation and build tags, (3) goroutine leaks and race conditions.
|
||||
- **Debug mode** — a test is failing or flaky. Work sequentially: reproduce reliably, isolate the failing assertion, trace the root cause in production code or test setup.
|
||||
|
||||
> **Community default.** A company skill that explicitly supersedes `samber/cc-skills-golang@golang-testing` skill takes precedence.
|
||||
|
||||
**Dependencies:**
|
||||
|
||||
- gotests: `go install github.com/cweill/gotests/gotests@latest`
|
||||
|
||||
# Go Testing Best Practices
|
||||
|
||||
This skill guides the creation of production-ready tests for Go applications. Follow these principles to write maintainable, fast, and reliable tests.
|
||||
|
||||
## Best Practices Summary
|
||||
|
||||
1. Table-driven tests MUST use named subtests -- every test case needs a `name` field passed to `t.Run`
|
||||
2. Integration tests MUST use build tags (`//go:build integration`) to separate from unit tests
|
||||
3. Tests MUST NOT depend on execution order -- each test MUST be independently runnable
|
||||
4. Independent tests SHOULD use `t.Parallel()` when possible
|
||||
5. NEVER test implementation details -- test observable behavior and public API contracts
|
||||
6. Packages with goroutines SHOULD use `goleak.VerifyTestMain` in `TestMain` to detect goroutine leaks
|
||||
7. Use testify as helpers, not a replacement for standard library
|
||||
8. Mock interfaces, not concrete types
|
||||
9. Keep unit tests fast (< 1ms), use build tags for integration tests
|
||||
10. Run tests with race detection in CI
|
||||
11. Include examples as executable documentation
|
||||
12. Test files MUST be named after the source file under test, not after the function or method being tested
|
||||
13. Test functions SHOULD appear in the same order as the functions/methods they test in the source file
|
||||
|
||||
## Test Structure and Organization
|
||||
|
||||
### File Conventions
|
||||
|
||||
```go
|
||||
// package_test.go - tests in same package (white-box, access unexported)
|
||||
package mypackage
|
||||
|
||||
// mypackage_test.go - tests in test package (black-box, public API only)
|
||||
package mypackage_test
|
||||
```
|
||||
|
||||
Name the test file after the source file it tests, not after the function or method under test. Go's convention is one test file per source file (`foo.go` -> `foo_test.go`), because tools (`go test`, coverage reports, IDE "jump to test" navigation, `gotests`) and reviewers all resolve tests by source file, not by symbol. A source file usually declares several functions/methods; splitting its tests by symbol name scatters them across many files and breaks that file-to-file mapping.
|
||||
|
||||
```
|
||||
// ✓ Good — one test file per source file
|
||||
helloworld.go -> helloworld_test.go // contains TestHelloWorld, TestAbcd, TestXyz, ...
|
||||
|
||||
// ✗ Bad — test file named after the function/method instead of the source file
|
||||
helloworld.go -> abcd_test.go // wrong: should be helloworld_test.go
|
||||
```
|
||||
|
||||
Exception: very large source files MAY be split into multiple `_test.go` files by concern (e.g. `foo_test.go` + `foo_edgecases_test.go`), but each split file's name MUST still be derived from the source file name, never from an individual function name. Prefer keeping a single `_test.go` file per source file even when it grows large — splitting adds navigation overhead and is rarely worth it; reach for the exception only when a single file becomes genuinely unwieldy to browse or review.
|
||||
|
||||
Within a test file, order test functions to match the order their tested functions/methods appear in the source file. A reader (human or agent) scrolling `foo.go` alongside `foo_test.go` can then find the matching test by position instead of searching; drift between the two orderings compounds every time either file grows.
|
||||
|
||||
### Naming Conventions
|
||||
|
||||
```go
|
||||
func TestAdd(t *testing.T) { ... } // function test
|
||||
func TestMyStruct_MyMethod(t *testing.T) { ... } // method test
|
||||
func BenchmarkAdd(b *testing.B) { ... } // benchmark
|
||||
func ExampleAdd() { ... } // example
|
||||
func FuzzAdd(f *testing.F) { ... } // fuzz test
|
||||
```
|
||||
|
||||
## Table-Driven Tests
|
||||
|
||||
Table-driven tests are the idiomatic Go way to test multiple scenarios. Always name each test case.
|
||||
|
||||
```go
|
||||
func TestCalculatePrice(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
quantity int
|
||||
unitPrice float64
|
||||
expected float64
|
||||
}{
|
||||
{
|
||||
name: "single item",
|
||||
quantity: 1,
|
||||
unitPrice: 10.0,
|
||||
expected: 10.0,
|
||||
},
|
||||
{
|
||||
name: "bulk discount - 100 items",
|
||||
quantity: 100,
|
||||
unitPrice: 10.0,
|
||||
expected: 900.0, // 10% discount
|
||||
},
|
||||
{
|
||||
name: "zero quantity",
|
||||
quantity: 0,
|
||||
unitPrice: 10.0,
|
||||
expected: 0.0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := CalculatePrice(tt.quantity, tt.unitPrice)
|
||||
if got != tt.expected {
|
||||
t.Errorf("CalculatePrice(%d, %.2f) = %.2f, want %.2f",
|
||||
tt.quantity, tt.unitPrice, got, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Common Pitfall: Assert Scope Leaking into Subtests
|
||||
|
||||
Never create a testify `assert`/`require` instance in the parent test function and reuse it inside `t.Run` closures. `assert.New(t)` captures the exact `*testing.T` it was built with, so if that `t` belongs to the parent, every failure raised inside the subtest gets attributed to the *parent* test in `go test` output — the failing subtest itself still reports `--- PASS`, silently hiding which case broke. This happens whether or not the subtest calls `t.Parallel()`.
|
||||
|
||||
```go
|
||||
// WRONG -- `is` is bound to the parent's t
|
||||
func TestCalculatePrice(t *testing.T) {
|
||||
is := assert.New(t)
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
is.Equal(tt.expected, CalculatePrice(tt.quantity, tt.unitPrice)) // misattributed on failure
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// RIGHT -- each subtest builds its own instance from its own t
|
||||
func TestCalculatePrice(t *testing.T) {
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
is := assert.New(t)
|
||||
is.Equal(tt.expected, CalculatePrice(tt.quantity, tt.unitPrice))
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Verify with a deliberately-broken case: if `go test -v -run TestName` shows `--- FAIL: TestName` but every `--- PASS: TestName/subtest_name` line still says PASS, the assert scope is leaking.
|
||||
|
||||
## Unit Tests
|
||||
|
||||
Unit tests should be fast (< 1ms), isolated (no external dependencies), and deterministic.
|
||||
|
||||
## Testing HTTP Handlers
|
||||
|
||||
Use `httptest` for handler tests with table-driven patterns. See [HTTP Testing](./references/http-testing.md) for examples with request/response bodies, query parameters, headers, and status code assertions.
|
||||
|
||||
## Goroutine Leak Detection with goleak
|
||||
|
||||
Use `go.uber.org/goleak` to detect leaking goroutines, especially for concurrent code:
|
||||
|
||||
```go
|
||||
import (
|
||||
"testing"
|
||||
"go.uber.org/goleak"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
goleak.VerifyTestMain(m)
|
||||
}
|
||||
```
|
||||
|
||||
To exclude specific goroutine stacks (for known leaks or library goroutines):
|
||||
|
||||
```go
|
||||
func TestMain(m *testing.M) {
|
||||
goleak.VerifyTestMain(m,
|
||||
goleak.IgnoreCurrent(),
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Or per-test:
|
||||
|
||||
```go
|
||||
func TestWorkerPool(t *testing.T) {
|
||||
defer goleak.VerifyNone(t)
|
||||
// ... test code ...
|
||||
}
|
||||
```
|
||||
|
||||
## testing/synctest for Deterministic Goroutine Testing
|
||||
|
||||
`testing/synctest` (Go 1.25+) provides deterministic tests for goroutines, timers, deadlines, and context cancellation. Time advances only when all goroutines are blocked, making ordering predictable.
|
||||
|
||||
When to use `synctest` instead of real time:
|
||||
|
||||
- Testing concurrent code with time-based operations (time.Sleep, time.After, time.Ticker)
|
||||
- When race conditions need to be reproducible
|
||||
- When tests are flaky due to timing issues
|
||||
|
||||
```go
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestContextTimeout(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
const timeout = 5 * time.Second
|
||||
|
||||
ctx, cancel := context.WithTimeout(t.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
time.Sleep(timeout - time.Nanosecond)
|
||||
synctest.Wait()
|
||||
if err := ctx.Err(); err != nil {
|
||||
t.Fatalf("before timeout: %v", err)
|
||||
}
|
||||
|
||||
time.Sleep(time.Nanosecond)
|
||||
synctest.Wait()
|
||||
if err := ctx.Err(); err != context.DeadlineExceeded {
|
||||
t.Fatalf("after timeout: got %v, want DeadlineExceeded", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
Use `synctest.Test` in Go 1.25+ and Go 1.26+. Do not use the old Go 1.24 experimental `synctest.Run` API in Go 1.25+ or Go 1.26+ code. If a module explicitly targets Go 1.24 and opts into `GOEXPERIMENT=synctest`, use the old API only as a compatibility fallback.
|
||||
|
||||
Key differences in `synctest`:
|
||||
|
||||
- `time.Sleep` advances synthetic time instantly when the goroutine blocks
|
||||
- `time.After` fires when synthetic time reaches the duration
|
||||
- All goroutines run to blocking points before time advances
|
||||
- Test execution is deterministic and repeatable
|
||||
|
||||
## Test Timeouts
|
||||
|
||||
For tests that may hang, use a timeout helper that panics with caller location. See [Helpers](./references/helpers.md).
|
||||
|
||||
## Benchmarks
|
||||
|
||||
→ See `samber/cc-skills-golang@golang-benchmark` skill for advanced benchmarking: `b.Loop()` (Go 1.24+), `benchstat`, profiling from benchmarks, and CI regression detection.
|
||||
|
||||
Write benchmarks to measure performance and detect regressions:
|
||||
|
||||
```go
|
||||
func BenchmarkStringConcatenation(b *testing.B) {
|
||||
b.Run("plus-operator", func(b *testing.B) {
|
||||
for b.Loop() {
|
||||
result := "a" + "b" + "c"
|
||||
_ = result
|
||||
}
|
||||
})
|
||||
|
||||
b.Run("strings.Builder", func(b *testing.B) {
|
||||
for b.Loop() {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("a")
|
||||
builder.WriteString("b")
|
||||
builder.WriteString("c")
|
||||
_ = builder.String()
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
Benchmarks with different input sizes:
|
||||
|
||||
```go
|
||||
func BenchmarkFibonacci(b *testing.B) {
|
||||
sizes := []int{10, 20, 30}
|
||||
for _, size := range sizes {
|
||||
b.Run(fmt.Sprintf("n=%d", size), func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
for b.Loop() {
|
||||
Fibonacci(size)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
For Go 1.24+, new benchmarks should use `b.Loop()`. Use legacy `b.N` loops only when the module targets Go <1.24 or when preserving old benchmark code intentionally.
|
||||
|
||||
### Go 1.26+: test artifacts
|
||||
|
||||
When a test, benchmark, or fuzz target needs to persist files for inspection, use `ArtifactDir()` instead of ad-hoc paths or repo-local output.
|
||||
|
||||
```go
|
||||
func TestRenderGoldenArtifact(t *testing.T) {
|
||||
dir := t.ArtifactDir()
|
||||
|
||||
out := filepath.Join(dir, "rendered.json")
|
||||
if err := os.WriteFile(out, renderedBytes, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
t.Logf("artifact written: %s", out)
|
||||
}
|
||||
```
|
||||
|
||||
Available on `*testing.T`, `*testing.B`, and `*testing.F` in Go 1.26+.
|
||||
|
||||
## Parallel Tests
|
||||
|
||||
Use `t.Parallel()` to run tests concurrently:
|
||||
|
||||
```go
|
||||
func TestParallelOperations(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
data []byte
|
||||
}{
|
||||
{"small data", make([]byte, 1024)},
|
||||
{"medium data", make([]byte, 1024*1024)},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
is := assert.New(t)
|
||||
|
||||
result := Process(tt.data)
|
||||
is.NotNil(result)
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Fuzzing
|
||||
|
||||
Use fuzzing to find edge cases and bugs:
|
||||
|
||||
```go
|
||||
func FuzzReverse(f *testing.F) {
|
||||
f.Add("hello")
|
||||
f.Add("")
|
||||
f.Add("a")
|
||||
|
||||
f.Fuzz(func(t *testing.T, input string) {
|
||||
reversed := Reverse(input)
|
||||
doubleReversed := Reverse(reversed)
|
||||
if input != doubleReversed {
|
||||
t.Errorf("Reverse(Reverse(%q)) = %q, want %q", input, doubleReversed, input)
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
## Examples as Documentation
|
||||
|
||||
Examples are executable documentation verified by `go test`:
|
||||
|
||||
```go
|
||||
func ExampleCalculatePrice() {
|
||||
price := CalculatePrice(100, 10.0)
|
||||
fmt.Printf("Price: %.2f\n", price)
|
||||
// Output: Price: 900.00
|
||||
}
|
||||
|
||||
func ExampleCalculatePrice_singleItem() {
|
||||
price := CalculatePrice(1, 25.50)
|
||||
fmt.Printf("Price: %.2f\n", price)
|
||||
// Output: Price: 25.50
|
||||
}
|
||||
```
|
||||
|
||||
## Code Coverage
|
||||
|
||||
```bash
|
||||
# Generate coverage file
|
||||
go test -coverprofile=coverage.out ./...
|
||||
|
||||
# View coverage in HTML
|
||||
go tool cover -html=coverage.out
|
||||
|
||||
# Coverage by function
|
||||
go tool cover -func=coverage.out
|
||||
|
||||
# Total coverage percentage
|
||||
go tool cover -func=coverage.out | grep total
|
||||
```
|
||||
|
||||
## Integration Tests
|
||||
|
||||
Use build tags to separate integration tests from unit tests:
|
||||
|
||||
```go
|
||||
//go:build integration
|
||||
|
||||
package mypackage
|
||||
|
||||
func TestDatabaseIntegration(t *testing.T) {
|
||||
db, err := sql.Open("postgres", os.Getenv("DATABASE_URL"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
// Test real database operations
|
||||
}
|
||||
```
|
||||
|
||||
Run integration tests separately:
|
||||
|
||||
```bash
|
||||
go test -tags=integration ./...
|
||||
```
|
||||
|
||||
For Docker Compose fixtures, SQL schemas, and integration test suites, see [Integration Testing](./references/integration-testing.md).
|
||||
|
||||
## Mocking
|
||||
|
||||
Mock interfaces, not concrete types. Define interfaces where consumed, then create mock implementations.
|
||||
|
||||
For mock patterns, test fixtures, and time mocking, see [Mocking](./references/mocking.md).
|
||||
|
||||
## Enforce with Linters
|
||||
|
||||
Many test best practices are enforced automatically by linters: `thelper`, `paralleltest`, `testifylint`. See the `samber/cc-skills-golang@golang-lint` skill for configuration and usage.
|
||||
|
||||
## Cross-References
|
||||
|
||||
- -> See `samber/cc-skills-golang@golang-stretchr-testify` skill for detailed testify API (assert, require, mock, suite)
|
||||
- -> See `samber/cc-skills-golang@golang-database` skill (testing.md) for database integration test patterns
|
||||
- -> See `samber/cc-skills-golang@golang-concurrency` skill for goroutine leak detection with goleak
|
||||
- -> See `samber/cc-skills-golang@golang-continuous-integration` skill for CI test configuration and GitHub Actions workflows
|
||||
- -> See `samber/cc-skills-golang@golang-lint` skill for testifylint and paralleltest configuration
|
||||
- -> See `samber/cc-skills-golang@golang-continuous-integration` skill for automated AI-driven code review in CI using these guidelines
|
||||
|
||||
## Quick Reference
|
||||
|
||||
```bash
|
||||
go test ./... # all tests
|
||||
go test -run TestName ./... # specific test by exact name
|
||||
go test -run TestName/subtest ./... # subtests within a test
|
||||
go test -run 'Test(Add|Sub)' ./... # multiple tests (regexp OR)
|
||||
go test -run 'Test[A-Z]' ./... # tests starting with capital letter
|
||||
go test -run 'TestUser.*' ./... # tests matching prefix
|
||||
go test -run '.*Validation.*' ./... # tests containing substring
|
||||
go test -run TestName/. ./... # all subtests of TestName
|
||||
go test -run '/(unit|integration)' ./... # filter by subtest name
|
||||
go test -race ./... # race detection
|
||||
go test -cover ./... # coverage summary
|
||||
go test -bench=. -benchmem ./... # benchmarks
|
||||
go test -fuzz=FuzzName ./... # fuzzing
|
||||
go test -tags=integration ./... # integration tests
|
||||
```
|
||||
@@ -0,0 +1,388 @@
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"name": "goleak-goroutine-leak-detection",
|
||||
"description": "Tests use goleak for goroutine leak detection, not just task completion",
|
||||
"prompt": "Write tests for a `workerpool` package. The package has a `Pool` struct with `Start(numWorkers int)`, `Submit(task func())`, and `Stop()` methods. Start spawns goroutines, Submit enqueues work, Stop shuts down gracefully. Write comprehensive unit tests covering start, submit tasks, and stop.",
|
||||
"trap": "Model writes normal unit tests verifying task completion but omits goroutine leak detection — Stop() may appear to work while leaking goroutines",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "1.1",
|
||||
"text": "Uses goleak (go.uber.org/goleak) — either goleak.VerifyTestMain in TestMain or goleak.VerifyNone per-test — to detect goroutine leaks from the worker pool"
|
||||
},
|
||||
{
|
||||
"id": "1.2",
|
||||
"text": "Has a TestMain function if using goleak.VerifyTestMain (the package-level approach)"
|
||||
},
|
||||
{
|
||||
"id": "1.3",
|
||||
"text": "Tests verify that Stop() properly cleans up goroutines (not just that tasks complete)"
|
||||
},
|
||||
{
|
||||
"id": "1.4",
|
||||
"text": "Imports go.uber.org/goleak"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"name": "integration-build-tag-not-testing-short",
|
||||
"description": "Integration tests use //go:build integration tag; testing.Short() is not an acceptable alternative",
|
||||
"prompt": "Our team disagrees on how to separate integration tests from unit tests in our Go project. A teammate proposes:\n\n```go\nfunc TestUserRepository_Create(t *testing.T) {\n if testing.Short() {\n t.Skip(\"skipping integration test\")\n }\n db := connectToPostgres(t)\n // ... test ...\n}\n```\n\nThey argue: 'testing.Short() is the Go standard way — it's in the stdlib, you can configure it with -short, and every Go developer knows it. Build tags are extra complexity for no benefit.'\n\nHow should integration tests be separated? Is the teammate's approach correct? Write the correct implementation for a TestUserRepository_Create integration test.",
|
||||
"trap": "Model accepts testing.Short() as a valid approach because it's a stdlib feature and the teammate's argument sounds reasonable. The skill teaches: build tags are required because testing.Short() still compiles tests into the binary, requires a flag to skip, and leaks DB connection attempts into normal test runs.",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "2.1",
|
||||
"text": "Rejects testing.Short() as the primary separation mechanism — does not accept the teammate's approach as correct"
|
||||
},
|
||||
{
|
||||
"id": "2.2",
|
||||
"text": "Uses `//go:build integration` build tag (at the file level, before the package declaration)"
|
||||
},
|
||||
{
|
||||
"id": "2.3",
|
||||
"text": "Explains why build tags are preferred: tests using testing.Short() still compile and attempt connections when running without -short, whereas build-tagged files are completely excluded from compilation"
|
||||
},
|
||||
{
|
||||
"id": "2.4",
|
||||
"text": "Includes the command to run integration tests: go test -tags=integration ./..."
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"name": "parallel-subtests-pure-function",
|
||||
"description": "Pure function subtests call t.Parallel(); top-level test also parallel",
|
||||
"prompt": "Write table-driven tests for a pure function `Slugify(input string) string` that converts titles to URL-friendly slugs (lowercase, hyphens for spaces, strips special chars). Test at least 6 cases: normal title, unicode, multiple spaces, empty string, already-slugified input, and special characters only.",
|
||||
"trap": "Model omits t.Parallel() since the function is pure and 'already fast enough', missing parallelism opportunities for stateless tests",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "3.1",
|
||||
"text": "Subtests call t.Parallel() — these are independent pure function tests with no shared mutable state"
|
||||
},
|
||||
{
|
||||
"id": "3.2",
|
||||
"text": "Top-level test function also calls t.Parallel()"
|
||||
},
|
||||
{
|
||||
"id": "3.3",
|
||||
"text": "Each test case has a descriptive `name` field used in t.Run"
|
||||
},
|
||||
{
|
||||
"id": "3.4",
|
||||
"text": "At least 6 test cases as requested"
|
||||
},
|
||||
{
|
||||
"id": "3.5",
|
||||
"text": "No shared mutable state between subtests (each subtest captures its own test case variable)"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"name": "fake-clock-injection-for-time-dependent-tests",
|
||||
"description": "Time-dependent code must accept a clock interface so tests can use clockwork.FakeClock; real time.Sleep is unacceptable",
|
||||
"prompt": "Here is an existing RateLimiter implementation:\n\n```go\ntype RateLimiter struct {\n limit int\n window time.Duration\n count int\n resetAt time.Time\n}\n\nfunc NewRateLimiter(limit int, window time.Duration) *RateLimiter {\n return &RateLimiter{\n limit: limit,\n window: window,\n resetAt: time.Now().Add(window),\n }\n}\n\nfunc (r *RateLimiter) Allow() bool {\n now := time.Now()\n if now.After(r.resetAt) {\n r.count = 0\n r.resetAt = now.Add(r.window)\n }\n if r.count >= r.limit {\n return false\n }\n r.count++\n return true\n}\n```\n\nWrite tests that verify:\n1. Allow() returns true while under the limit\n2. Allow() returns false when the limit is exceeded\n3. The counter resets after the time window expires\n\nThe tests must run in milliseconds, not seconds. You may modify the implementation if needed.",
|
||||
"trap": "Model uses time.Sleep(window + small margin) to test window expiration — the code uses time.Now() directly, making tests slow and flaky. The skill teaches to refactor the code to accept a clock interface (clockwork.Clock) and inject a FakeClock in tests.",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "4.1",
|
||||
"text": "Modifies the RateLimiter to accept a clock interface (e.g., clockwork.Clock or a custom Now() func) rather than calling time.Now() directly"
|
||||
},
|
||||
{
|
||||
"id": "4.2",
|
||||
"text": "Uses clockwork.FakeClock (or equivalent) in tests to advance time without real sleeping — tests run in microseconds"
|
||||
},
|
||||
{
|
||||
"id": "4.3",
|
||||
"text": "Tests the window reset scenario by advancing the fake clock past the window duration (e.g., fakeClock.Advance(window + time.Millisecond))"
|
||||
},
|
||||
{
|
||||
"id": "4.4",
|
||||
"text": "No real-time time.Sleep in test code; use synctest.Test/synctest.Wait or a fake clock for deterministic synthetic time"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"name": "consumer-site-interface-mocking",
|
||||
"description": "Tests define interfaces at the consumer site and mock those, not concrete structs",
|
||||
"prompt": "Test a `NotificationService` struct that has a `NotifyUser(userID string) error` method. It depends on two concrete structs: `SMTPClient` (with `Send(to, subject, body string) error`) and `AuditLogger` (with `Log(event string) error`). NotifyUser looks up the user's email, sends an email via SMTPClient, and logs the event via AuditLogger. Write comprehensive tests for NotifyUser.",
|
||||
"trap": "Model embeds or wraps concrete SMTPClient/AuditLogger in mock structs, or creates test doubles that shadow the concrete types, instead of extracting consumer-site interfaces",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "5.1",
|
||||
"text": "Defines interfaces for the dependencies (e.g., EmailSender, Logger) rather than using the concrete SMTPClient/AuditLogger structs directly in tests"
|
||||
},
|
||||
{
|
||||
"id": "5.2",
|
||||
"text": "Creates mock implementations of these interfaces (using testify/mock or manual mocks)"
|
||||
},
|
||||
{
|
||||
"id": "5.3",
|
||||
"text": "Does NOT embed or wrap the concrete SMTPClient/AuditLogger structs in mock objects"
|
||||
},
|
||||
{
|
||||
"id": "5.4",
|
||||
"text": "Uses dependency injection — NotificationService accepts interfaces, not concrete types"
|
||||
},
|
||||
{
|
||||
"id": "5.5",
|
||||
"text": "Tests verify both happy path (send succeeds) and error scenarios (send fails, log fails)"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"name": "test-observable-behavior-not-internals",
|
||||
"description": "Tests verify behavior via public API only, not by inspecting the internal map field",
|
||||
"prompt": "Test a `UserCache` struct with `Get(id string) (*User, bool)`, `Set(id string, user *User)`, and `Len() int` methods. The cache has an internal `data map[string]*User` field. Write tests that verify the cache stores and retrieves users correctly. Make sure to verify the internal map state is consistent after each operation.",
|
||||
"trap": "Model directly accesses the internal data map field to verify state, coupling tests to implementation details",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "6.1",
|
||||
"text": "Tests observable behavior through Get/Set/Len public API only"
|
||||
},
|
||||
{
|
||||
"id": "6.2",
|
||||
"text": "Does NOT directly access or inspect the internal `data` map field"
|
||||
},
|
||||
{
|
||||
"id": "6.3",
|
||||
"text": "Does NOT use same-package (white-box) testing to examine cache internals"
|
||||
},
|
||||
{
|
||||
"id": "6.4",
|
||||
"text": "Tests cover cache hit, cache miss, overwrite, and Len() correctness"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"name": "external-test-package-resists-internal-access",
|
||||
"description": "Tests use package_test to black-box test; does not access unexported state even when a teammate suggests it",
|
||||
"prompt": "Write tests for a `tokenizer` package that exports `Tokenize(input string) []Token` and a `Token` struct with `Type` and `Value` fields. The package has an unexported `tokenCache map[string][]Token` field on the package level for memoization.\n\nA teammate says: 'We should verify the cache is being populated correctly — access tokenCache directly in the tests. It's in the same package so it's fine, and it makes the tests more reliable since we can confirm memoization is working.'\n\nWrite the tests. Should you follow the teammate's suggestion?",
|
||||
"trap": "Model follows the teammate's suggestion and uses package tokenizer (white-box) to access tokenCache directly, reasoning that it makes tests more reliable. The skill teaches to use package tokenizer_test and test only observable behavior — cache behavior is an implementation detail, not a contract.",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "7.1",
|
||||
"text": "Rejects the teammate's suggestion — does not access tokenCache directly in tests"
|
||||
},
|
||||
{
|
||||
"id": "7.2",
|
||||
"text": "Uses `package tokenizer_test` (external test package) instead of `package tokenizer`"
|
||||
},
|
||||
{
|
||||
"id": "7.3",
|
||||
"text": "Explains why: cache behavior is an implementation detail — tests should verify the observable contract (same input → same output), not whether a specific optimization is in place"
|
||||
},
|
||||
{
|
||||
"id": "7.4",
|
||||
"text": "Tests focus on functional correctness: same input tokenizes identically on repeated calls, edge cases, different token types"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"name": "example-functions-as-documentation",
|
||||
"description": "Packages need Example functions with // Output: comments that serve as executable documentation in go doc",
|
||||
"prompt": "I've written a `currency` package with these functions:\n\n```go\nfunc Format(cents int64, code string) string // Format(1234, \"USD\") → \"$12.34\"\nfunc Parse(s string) (int64, string, error) // Parse(\"$12.34\") → 1234, \"USD\", nil\nfunc Convert(cents int64, from, to string, rate float64) int64\n```\n\nA colleague says: 'The functions are self-explanatory — names and signatures are clear enough. We don't need extra documentation. Just write unit tests with good coverage.'\n\nWrite comprehensive test coverage for this package. Should you follow the colleague's advice about documentation?",
|
||||
"trap": "Model follows the colleague's advice and writes only table-driven unit tests without Example functions — missing the executable documentation that shows real usage in `go doc` and on pkg.go.dev. The skill teaches that Example functions serve as both tests and documentation.",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "8.1",
|
||||
"text": "Disagrees with the colleague — includes Example functions despite the advice to skip them"
|
||||
},
|
||||
{
|
||||
"id": "8.2",
|
||||
"text": "Includes at least one Example function (ExampleFormat, ExampleParse, or ExampleConvert)"
|
||||
},
|
||||
{
|
||||
"id": "8.3",
|
||||
"text": "Example functions have `// Output:` comments so they are verified by go test"
|
||||
},
|
||||
{
|
||||
"id": "8.4",
|
||||
"text": "Explains that Example functions serve as executable documentation visible in go doc and pkg.go.dev — not just tests"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"name": "fuzz-test-for-critical-functions",
|
||||
"description": "Security-critical functions get fuzz tests with seed corpus and property assertions",
|
||||
"prompt": "Write tests for a `SanitizeHTML(input string) string` function that strips all HTML tags from input while preserving text content. Make sure to test edge cases thoroughly — this function is critical for security.",
|
||||
"trap": "Model writes only table-driven tests for known edge cases, missing the fuzz test that would discover unexpected inputs causing XSS vulnerabilities",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "9.1",
|
||||
"text": "Includes a fuzz test function (FuzzSanitizeHTML or similar)"
|
||||
},
|
||||
{
|
||||
"id": "9.2",
|
||||
"text": "Fuzz test uses f.Add() to provide seed corpus entries"
|
||||
},
|
||||
{
|
||||
"id": "9.3",
|
||||
"text": "Fuzz test includes property-based assertions (e.g., output contains no < or > characters, or double-sanitize is idempotent)"
|
||||
},
|
||||
{
|
||||
"id": "9.4",
|
||||
"text": "Also includes regular table-driven tests for known edge cases"
|
||||
},
|
||||
{
|
||||
"id": "9.5",
|
||||
"text": "Table tests cover tricky cases like nested tags, unclosed tags, or script tags"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"name": "test-helper-t-helper-attribution",
|
||||
"description": "Test helpers must call t.Helper() so failures point to the caller's line, not the helper's internal line",
|
||||
"prompt": "I have this test helper and some tests using it:\n\n```go\nfunc requireNoError(t *testing.T, err error, msg string) {\n if err != nil {\n t.Fatalf(\"%s: unexpected error: %v\", msg, err)\n }\n}\n\nfunc TestProcessOrder(t *testing.T) {\n order := NewOrder(\"prod-1\", 2)\n err := order.Validate()\n requireNoError(t, err, \"validate\")\n\n err = order.Submit()\n requireNoError(t, err, \"submit\")\n}\n```\n\nWhen Validate() fails, the test output reports a failure at the `t.Fatalf` line inside `requireNoError`, not at the `requireNoError(t, err, \"validate\")` call site in `TestProcessOrder`. Is this a problem? How do you fix it?",
|
||||
"trap": "Model says this is expected behavior or suggests switching to t.Error() instead of the real fix. The skill teaches that t.Helper() must be called as the first statement in the helper so Go's test framework reports failures at the caller's line.",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "10.1",
|
||||
"text": "Identifies this as a real problem — the line number pointing to the helper's internal Fatalf is unhelpful for debugging which call caused the failure"
|
||||
},
|
||||
{
|
||||
"id": "10.2",
|
||||
"text": "Fixes it by adding t.Helper() as the first statement in requireNoError — not by restructuring the helper or using a different assertion method"
|
||||
},
|
||||
{
|
||||
"id": "10.3",
|
||||
"text": "Explains that t.Helper() marks the function as a test helper so that the testing framework reports the caller's file:line instead of the helper's file:line"
|
||||
},
|
||||
{
|
||||
"id": "10.4",
|
||||
"text": "Does NOT suggest switching to t.Error() as the fix — t.Helper() is the correct solution regardless of t.Fatal vs t.Error"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"name": "httptest-recorder-not-real-server",
|
||||
"description": "HTTP handler tests use httptest.NewRecorder, not a real HTTP server",
|
||||
"prompt": "Write end-to-end tests for a REST API handler `HandleCreateOrder(w http.ResponseWriter, r *http.Request)` that accepts POST with JSON body `{\"product\": \"...\", \"quantity\": N}`. It returns 201 with the order JSON on success, 400 for invalid JSON, and 422 for validation errors (empty product, quantity <= 0). Test it like a real client would call it.",
|
||||
"trap": "Model starts a real HTTP server with httptest.NewServer or net/http ListenAndServe, adding unnecessary network overhead and port allocation to tests",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "11.1",
|
||||
"text": "Uses httptest.NewRecorder (not httptest.NewServer or a real HTTP server)"
|
||||
},
|
||||
{
|
||||
"id": "11.2",
|
||||
"text": "Table-driven with named test cases covering multiple scenarios"
|
||||
},
|
||||
{
|
||||
"id": "11.3",
|
||||
"text": "Tests at least 3 status codes (201, 400, 422)"
|
||||
},
|
||||
{
|
||||
"id": "11.4",
|
||||
"text": "Verifies response body content (not just status code)"
|
||||
},
|
||||
{
|
||||
"id": "11.5",
|
||||
"text": "Sets proper Content-Type header on requests"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"name": "testify-suite-for-integration",
|
||||
"description": "Integration tests use testify/suite with SetupSuite/TearDownTest for organized setup/teardown",
|
||||
"prompt": "Write integration tests for an `OrderRepository` that interacts with PostgreSQL. It has `Create(order *Order) error`, `GetByID(id string) (*Order, error)`, and `ListByUserID(userID string) ([]*Order, error)`. Tests need database setup (create tables), per-test data cleanup, and graceful teardown. Organize them cleanly so setup/teardown happens automatically. These must not run during normal unit tests.",
|
||||
"trap": "Model uses TestMain or plain setup functions with defer for teardown, mixing setup concerns into each test instead of a suite",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "12.1",
|
||||
"text": "Uses testify/suite.Suite struct embedding for test organization"
|
||||
},
|
||||
{
|
||||
"id": "12.2",
|
||||
"text": "Has SetupSuite (or similar) for one-time database connection and schema setup"
|
||||
},
|
||||
{
|
||||
"id": "12.3",
|
||||
"text": "Has SetupTest or TearDownTest for per-test data cleanup (e.g., TRUNCATE)"
|
||||
},
|
||||
{
|
||||
"id": "12.4",
|
||||
"text": "Has TearDownSuite for graceful shutdown (close DB, docker-compose down)"
|
||||
},
|
||||
{
|
||||
"id": "12.5",
|
||||
"text": "Uses `//go:build integration` build tag"
|
||||
},
|
||||
{
|
||||
"id": "12.6",
|
||||
"text": "Has a runner function `func TestXxx(t *testing.T) { suite.Run(t, ...) }`"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 13,
|
||||
"name": "benchmark-report-allocs-and-input-sizes",
|
||||
"description": "Benchmarks use b.ReportAllocs(), test multiple input sizes, and follow naming conventions",
|
||||
"prompt": "Write benchmarks for a `Compress(data []byte) ([]byte, error)` function that compresses byte slices. We need to measure performance to decide if this is fast enough for our hot path. Just write the benchmark tests.",
|
||||
"trap": "Model writes a single benchmark with one input size and omits b.ReportAllocs(), missing allocation tracking and size-scaling analysis",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "13.1",
|
||||
"text": "Calls b.ReportAllocs() to track memory allocations per operation"
|
||||
},
|
||||
{
|
||||
"id": "13.2",
|
||||
"text": "Tests multiple input sizes using b.Run with descriptive sub-benchmark names (e.g., size=1KB, size=1MB)"
|
||||
},
|
||||
{
|
||||
"id": "13.3",
|
||||
"text": "Uses b.Loop() for Go 1.24+ benchmark loops; uses legacy b.N only for older module targets"
|
||||
},
|
||||
{
|
||||
"id": "13.4",
|
||||
"text": "Follows benchmark naming convention: BenchmarkCompress or BenchmarkCompress_<variant>"
|
||||
},
|
||||
{
|
||||
"id": "13.5",
|
||||
"text": "Prevents compiler optimization of the result (assigns to a package-level variable or uses _ =)"
|
||||
},
|
||||
{
|
||||
"id": "13.6",
|
||||
"text": "Does NOT include setup/allocation costs inside the timed loop (or uses b.ResetTimer if setup is needed)"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 14,
|
||||
"name": "race-detection-and-test-independence",
|
||||
"description": "Tests for concurrent code include -race flag guidance and ensure test independence (no order dependence)",
|
||||
"prompt": "Write tests for a `SafeMap[K comparable, V any]` struct that provides a goroutine-safe map with `Get(key K) (V, bool)`, `Set(key K, value V)`, `Delete(key K)`, and `Len() int` methods. Multiple goroutines will call these concurrently. Write thorough tests including concurrent access scenarios. Also include a note on how to run these tests in CI.",
|
||||
"trap": "Model writes concurrent tests but omits -race flag guidance for CI and doesn't ensure tests are independently runnable (e.g., shares map state between test functions)",
|
||||
"assertions": [
|
||||
{
|
||||
"id": "14.1",
|
||||
"text": "Includes concurrent test scenarios where multiple goroutines call Get/Set/Delete simultaneously"
|
||||
},
|
||||
{
|
||||
"id": "14.2",
|
||||
"text": "Recommends running with -race flag (go test -race) for CI or includes it in a run command comment"
|
||||
},
|
||||
{
|
||||
"id": "14.3",
|
||||
"text": "Each test function creates its own SafeMap instance — no shared state between test functions"
|
||||
},
|
||||
{
|
||||
"id": "14.4",
|
||||
"text": "Uses sync.WaitGroup or similar synchronization to coordinate concurrent test goroutines"
|
||||
},
|
||||
{
|
||||
"id": "14.5",
|
||||
"text": "Tests are independently runnable (any single test can pass when run in isolation with -run)"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,42 @@
|
||||
# Test Helpers
|
||||
|
||||
## Test Timeout
|
||||
|
||||
For tests that may hang, use a timeout helper that panics with caller location:
|
||||
|
||||
```go
|
||||
// https://github.com/stretchr/testify/issues/1101
|
||||
func testWithTimeout(t *testing.T, timeout time.Duration) {
|
||||
t.Helper()
|
||||
|
||||
testFinished := make(chan struct{})
|
||||
t.Cleanup(func() {
|
||||
close(testFinished)
|
||||
})
|
||||
|
||||
var pc [1]uintptr
|
||||
n := runtime.Callers(2, pc[:])
|
||||
line, funcName := "", ""
|
||||
if n > 0 {
|
||||
frames := runtime.CallersFrames(pc[:])
|
||||
frame, _ := frames.Next()
|
||||
line = frame.File + ":" + strconv.Itoa(frame.Line)
|
||||
funcName = frame.Function
|
||||
}
|
||||
|
||||
go func() {
|
||||
select {
|
||||
case <-testFinished:
|
||||
case <-time.After(timeout):
|
||||
panic(fmt.Sprintf("%s: Test timed out after: %v\n%s", funcName, timeout, line))
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// Usage
|
||||
func TestLongRunningOperation(t *testing.T) {
|
||||
testWithTimeout(t, 2*time.Second)
|
||||
result := LongRunningOperation()
|
||||
// If this takes longer than 2 seconds, the test panics with location info
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,84 @@
|
||||
# HTTP Handler Testing
|
||||
|
||||
Use `httptest` package for testing HTTP handlers without starting a server.
|
||||
|
||||
## Basic Handler Test
|
||||
|
||||
```go
|
||||
func TestCreateUserHandler(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
expectedStatus int
|
||||
}{
|
||||
{
|
||||
name: "valid request",
|
||||
body: `{"name": "Alice", "email": "alice@example.com"}`,
|
||||
expectedStatus: http.StatusCreated,
|
||||
},
|
||||
{
|
||||
name: "invalid JSON",
|
||||
body: `invalid json`,
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
is := assert.New(t)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/users", strings.NewReader(tt.body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
handler := http.HandlerFunc(CreateUserHandler)
|
||||
handler.ServeHTTP(w, req)
|
||||
|
||||
is.Equal(tt.expectedStatus, w.Code)
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Query Parameters and Headers
|
||||
|
||||
```go
|
||||
func TestListUsersHandler(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
query string
|
||||
authHeader string
|
||||
expectedStatus int
|
||||
}{
|
||||
{
|
||||
name: "paginated results",
|
||||
query: "?page=1&limit=10",
|
||||
authHeader: "Bearer token123",
|
||||
expectedStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "missing auth",
|
||||
query: "?page=1",
|
||||
authHeader: "",
|
||||
expectedStatus: http.StatusUnauthorized,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
is := assert.New(t)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/users"+tt.query, nil)
|
||||
if tt.authHeader != "" {
|
||||
req.Header.Set("Authorization", tt.authHeader)
|
||||
}
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
handler := AuthMiddleware(ListUsersHandler)
|
||||
handler.ServeHTTP(w, req)
|
||||
|
||||
is.Equal(tt.expectedStatus, w.Code)
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,187 @@
|
||||
# Integration Testing
|
||||
|
||||
## Docker Compose Fixture
|
||||
|
||||
Create `pkg/myfeature/testdata/docker-compose.yml` for test services:
|
||||
|
||||
```yaml
|
||||
version: "3.8"
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
environment:
|
||||
POSTGRES_USER: test
|
||||
POSTGRES_PASSWORD: test
|
||||
POSTGRES_DB: testdb
|
||||
ports:
|
||||
- "5433:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U test"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
ports:
|
||||
- "6380:6379"
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
```
|
||||
|
||||
## SQL Schema Fixture
|
||||
|
||||
Create `pkg/myfeature/testdata/schema.sql` for database initialization:
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
email VARCHAR(255) UNIQUE NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS orders (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INTEGER REFERENCES users(id),
|
||||
amount DECIMAL(10,2) NOT NULL,
|
||||
status VARCHAR(50) DEFAULT 'pending',
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
```
|
||||
|
||||
## Test Data Fixture
|
||||
|
||||
Create `pkg/myfeature/testdata/testdata.sql`:
|
||||
|
||||
```sql
|
||||
INSERT INTO users (name, email) VALUES
|
||||
('Alice Johnson', 'alice@example.com'),
|
||||
('Bob Smith', 'bob@example.com'),
|
||||
('Charlie Brown', 'charlie@example.com');
|
||||
|
||||
INSERT INTO orders (user_id, amount, status) VALUES
|
||||
(1, 100.00, 'completed'),
|
||||
(1, 50.00, 'pending'),
|
||||
(2, 200.00, 'completed');
|
||||
```
|
||||
|
||||
## Using Fixtures in Tests
|
||||
|
||||
```go
|
||||
//go:build integration
|
||||
|
||||
package database_test
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"os"
|
||||
"os/exec"
|
||||
"testing"
|
||||
"time"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/suite"
|
||||
)
|
||||
|
||||
type DatabaseTestSuite struct {
|
||||
suite.Suite
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
func (s *DatabaseTestSuite) SetupSuite() {
|
||||
cmd := exec.Command("docker-compose", "-f", "testdata/docker-compose.yml", "up", "-d")
|
||||
if err := cmd.Run(); err != nil {
|
||||
s.T().Fatalf("failed to start docker-compose: %v", err)
|
||||
}
|
||||
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
db, err := sql.Open("postgres", "postgres://test:test@localhost:5433/testdb?sslmode=disable")
|
||||
if err != nil {
|
||||
s.T().Fatalf("failed to connect to database: %v", err)
|
||||
}
|
||||
s.db = db
|
||||
|
||||
schema, _ := os.ReadFile("testdata/schema.sql")
|
||||
_, err = db.Exec(string(schema))
|
||||
if err != nil {
|
||||
s.T().Fatalf("failed to run schema: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *DatabaseTestSuite) TearDownSuite() {
|
||||
cmd := exec.Command("docker-compose", "-f", "testdata/docker-compose.yml", "down", "-v")
|
||||
_ = cmd.Run()
|
||||
}
|
||||
|
||||
func (s *DatabaseTestSuite) SetupTest() {
|
||||
_, err := s.db.Exec("TRUNCATE TABLE orders, users CASCADE")
|
||||
if err != nil {
|
||||
s.T().Fatalf("failed to clear database: %v", err)
|
||||
}
|
||||
|
||||
testdata, _ := os.ReadFile("testdata/testdata.sql")
|
||||
_, err = s.db.Exec(string(testdata))
|
||||
if err != nil {
|
||||
s.T().Fatalf("failed to load test data: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *DatabaseTestSuite) TestUserCount() {
|
||||
is := assert.New(s.T())
|
||||
|
||||
var count int
|
||||
err := s.db.QueryRow("SELECT COUNT(*) FROM users").Scan(&count)
|
||||
is.NoError(err)
|
||||
is.Equal(3, count)
|
||||
}
|
||||
|
||||
func (s *DatabaseTestSuite) TestOrderSum() {
|
||||
is := assert.New(s.T())
|
||||
|
||||
var sum float64
|
||||
err := s.db.QueryRow("SELECT SUM(amount) FROM orders").Scan(&sum)
|
||||
is.NoError(err)
|
||||
is.InDelta(350.0, sum, 0.01)
|
||||
}
|
||||
|
||||
func TestDatabaseTestSuite(t *testing.T) {
|
||||
suite.Run(t, new(DatabaseTestSuite))
|
||||
}
|
||||
```
|
||||
|
||||
## Test Helper with Embedded Fixtures
|
||||
|
||||
```go
|
||||
package myfeature
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"embed"
|
||||
)
|
||||
|
||||
//go:embed testdata/schema.sql testdata/testdata.sql
|
||||
var fixtures embed.FS
|
||||
|
||||
func SetupDB(db *sql.DB) error {
|
||||
schema, err := fixtures.ReadFile("testdata/schema.sql")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := db.Exec(string(schema)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
data, err := fixtures.ReadFile("testdata/testdata.sql")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := db.Exec(string(data)); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,206 @@
|
||||
# Mocking and Test Fixtures
|
||||
|
||||
## Mocks with testify/mock
|
||||
|
||||
Create interfaces for your dependencies, then mock them.
|
||||
|
||||
> For the full testify/mock API (argument matchers, call modifiers, verification), see the `samber/cc-skills-golang@golang-stretchr-testify` skill.
|
||||
|
||||
```go
|
||||
// Define the interface
|
||||
type Database interface {
|
||||
GetUser(id string) (*User, error)
|
||||
CreateUser(user *User) error
|
||||
}
|
||||
|
||||
// Mock implementation
|
||||
type MockDatabase struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
func (m *MockDatabase) GetUser(id string) (*User, error) {
|
||||
args := m.Called(id)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
return args.Get(0).(*User), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockDatabase) CreateUser(user *User) error {
|
||||
args := m.Called(user)
|
||||
return args.Error(0)
|
||||
}
|
||||
|
||||
// Usage in tests
|
||||
func TestService_GetUser(t *testing.T) {
|
||||
is := assert.New(t)
|
||||
|
||||
mockDB := new(MockDatabase)
|
||||
service := NewService(mockDB)
|
||||
|
||||
expectedUser := &User{ID: "1", Name: "John"}
|
||||
mockDB.On("GetUser", "1").Return(expectedUser, nil)
|
||||
|
||||
user, err := service.GetUser("1")
|
||||
|
||||
is.NoError(err)
|
||||
is.Equal(expectedUser, user)
|
||||
mockDB.AssertExpectations(t)
|
||||
}
|
||||
|
||||
func TestService_GetUser_NotFound(t *testing.T) {
|
||||
is := assert.New(t)
|
||||
|
||||
mockDB := new(MockDatabase)
|
||||
service := NewService(mockDB)
|
||||
|
||||
mockDB.On("GetUser", "999").Return(nil, ErrNotFound)
|
||||
|
||||
user, err := service.GetUser("999")
|
||||
|
||||
is.Error(err)
|
||||
is.ErrorIs(err, ErrNotFound)
|
||||
is.Nil(user)
|
||||
mockDB.AssertExpectations(t)
|
||||
}
|
||||
```
|
||||
|
||||
## Mock Organization
|
||||
|
||||
For larger codebases, organize mocks alongside the code they mock:
|
||||
|
||||
```go
|
||||
// user_service.go
|
||||
type UserService struct {
|
||||
db Database
|
||||
email EmailService
|
||||
}
|
||||
type Database interface {
|
||||
GetUser(id string) (*User, error)
|
||||
CreateUser(user *User) error
|
||||
}
|
||||
type EmailService interface {
|
||||
SendWelcomeEmail(to string) error
|
||||
}
|
||||
```
|
||||
|
||||
```go
|
||||
// user_service_test.go
|
||||
package mypackage_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"path/to/mypackage"
|
||||
)
|
||||
|
||||
// MockDatabase implements mypackage.Database
|
||||
type MockDatabase struct {
|
||||
mock.Mock
|
||||
}
|
||||
func (m *MockDatabase) GetUser(id string) (*mypackage.User, error) {
|
||||
args := m.Called(id)
|
||||
if args.Get(0) == nil { return nil, args.Error(1) }
|
||||
return args.Get(0).(*mypackage.User), args.Error(1)
|
||||
}
|
||||
func (m *MockDatabase) CreateUser(user *mypackage.User) error {
|
||||
return m.Called(user).Error(0)
|
||||
}
|
||||
|
||||
// MockEmailService implements mypackage.EmailService
|
||||
type MockEmailService struct {
|
||||
mock.Mock
|
||||
}
|
||||
func (m *MockEmailService) SendWelcomeEmail(to string) error {
|
||||
return m.Called(to).Error(0)
|
||||
}
|
||||
|
||||
func TestUserService_CreateUser(t *testing.T) {
|
||||
mockDB := new(MockDatabase)
|
||||
mockEmail := new(MockEmailService)
|
||||
service := mypackage.NewUserService(mockDB, mockEmail)
|
||||
|
||||
user := &mypackage.User{Name: "Test", Email: "test@example.com"}
|
||||
mockDB.On("CreateUser", user).Return(nil)
|
||||
mockEmail.On("SendWelcomeEmail", "test@example.com").Return(nil)
|
||||
|
||||
err := service.CreateUser(user)
|
||||
|
||||
assert.NoError(t, err)
|
||||
mockDB.AssertExpectations(t)
|
||||
mockEmail.AssertExpectations(t)
|
||||
}
|
||||
```
|
||||
|
||||
## Test Fixtures
|
||||
|
||||
Create reusable test data in a separate package or file:
|
||||
|
||||
```go
|
||||
package fixtures
|
||||
|
||||
import "time"
|
||||
|
||||
var (
|
||||
DefaultUser = &User{
|
||||
ID: "user-123",
|
||||
Name: "Jane Doe",
|
||||
Email: "jane@example.com",
|
||||
CreatedAt: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
}
|
||||
|
||||
AdminUser = &User{
|
||||
ID: "admin-1",
|
||||
Name: "Admin User",
|
||||
Email: "admin@example.com",
|
||||
Role: "admin",
|
||||
CreatedAt: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
}
|
||||
)
|
||||
|
||||
func NewUser(name, email string) *User {
|
||||
return &User{
|
||||
ID: "user-" + uuid.New().String(),
|
||||
Name: name,
|
||||
Email: email,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Time Mocking
|
||||
|
||||
Use `clockwork` to test time-dependent code without `time.Sleep()`:
|
||||
|
||||
```go
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
"github.com/jonboulle/clockwork"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestScheduler_AddJob(t *testing.T) {
|
||||
is := assert.New(t)
|
||||
|
||||
fakeClock := clockwork.NewFakeClock()
|
||||
scheduler := NewScheduler(fakeClock)
|
||||
|
||||
job := &Job{ID: "1", RunAt: time.Now().Add(1 * time.Hour)}
|
||||
scheduler.AddJob(job)
|
||||
|
||||
is.Equal(1, scheduler.PendingCount())
|
||||
|
||||
// Advance fake time
|
||||
fakeClock.Advance(2 * time.Hour)
|
||||
|
||||
is.Equal(0, scheduler.PendingCount())
|
||||
}
|
||||
```
|
||||
|
||||
Install clockwork:
|
||||
|
||||
```bash
|
||||
go get github.com/jonboulle/clockwork
|
||||
```
|
||||
@@ -1,49 +1,108 @@
|
||||
---
|
||||
name: implement-tickets
|
||||
description: "Run a planned wave of tickets: one implementer subagent per ticket in its own worktree, then land, merge and close what comes back."
|
||||
description: "Orchestrate a batch of tickets: plan the briefs, then hand each ticket to its own implementer subagent in its own worktree."
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
# Implement tickets
|
||||
|
||||
You are the **orchestrator**. You dispatch, land results, and talk to the
|
||||
tracker. You do not write the implementation — every line of ticket code is
|
||||
written by a `ticket-implementer` subagent in its own git worktree. Reach for the
|
||||
editor yourself only for a merge conflict resolution.
|
||||
You are the **orchestrator**. You write briefs, dispatch, land results, and talk
|
||||
to the tracker. You do not write the implementation — every line of ticket code
|
||||
is written by a `ticket-implementer` subagent in its own git worktree. Reach for
|
||||
the editor yourself only for a merge conflict resolution.
|
||||
|
||||
Ticket source and tracker conventions: `docs/agents/issue-tracker.md`. `tea` usage: skill `gitea`.
|
||||
|
||||
## 0. Load the plan
|
||||
## 1. Collect the tickets
|
||||
|
||||
Your argument is the batch slug. Read `.scratch/<batch-slug>/plan.md` — it gives
|
||||
the base branch, the waves, the contracts, and each ticket's brief path and
|
||||
status. Run the earliest wave that is not landed.
|
||||
The user's argument is the selector: issue numbers, a label, a parent issue, or
|
||||
nothing. With nothing, take the open issues labelled `ready-for-agent`.
|
||||
|
||||
The briefs are the requirements and they are already approved: read each one you
|
||||
are about to dispatch, but do not rewrite it, and do not fetch the tickets from
|
||||
the tracker to second-guess it. A brief that is wrong or thin is a `plan-tickets`
|
||||
problem — say so and stop, rather than patching it here.
|
||||
Fetch each with `tea issue <n> --comments`, and read the **whole** body —
|
||||
acceptance criteria and the `Blocked by` line are what the rest of this skill
|
||||
runs on. A ticket whose blockers are still open is out of this batch unless a
|
||||
blocker is also in it.
|
||||
|
||||
No plan file, or no briefs for the next wave: run `plan-tickets` first. That
|
||||
skill owns wave membership, contracts, and every brief.
|
||||
## 2. Plan the batch
|
||||
|
||||
## 1. Dispatch the wave
|
||||
Explore enough of the codebase to write briefs a fresh context can act on: the
|
||||
files each ticket lands in, the patterns it must follow, the `AGENTS.md`
|
||||
invariants it touches.
|
||||
|
||||
Then decide three things:
|
||||
|
||||
- **Waves.** Blocking edges set the order; tickets with no open blocker inside
|
||||
the batch share a wave. Cap each wave at **3** concurrent tickets unless the
|
||||
user set another width.
|
||||
- **Contracts.** Two tickets in one wave that meet at a function signature, a
|
||||
JSON shape, a table column, or a token name: you decide the shape now and
|
||||
write the identical wording into both briefs. A contract left for the
|
||||
subagents to negotiate is a merge conflict you scheduled.
|
||||
- **Splits.** A ticket too big for one fresh context window goes into the wave
|
||||
as two briefs, or back to the user.
|
||||
|
||||
## 3. Get the plan approved
|
||||
|
||||
Present, and stop:
|
||||
|
||||
- the wave list, and for each ticket: number, title, one-line brief summary,
|
||||
the files or areas it will touch, its verification commands
|
||||
- every cross-ticket contract, verbatim as it will appear in the briefs
|
||||
- anything you had to assume
|
||||
|
||||
Wait for approval. Apply the user's edits to the plan, do not relitigate them.
|
||||
|
||||
## 4. Run a wave
|
||||
|
||||
Per ticket, before dispatch:
|
||||
|
||||
```bash
|
||||
git worktree add ../ticket-<n> -b ticket/<n>-<slug> <base> # base = the plan's base branch, checked out here
|
||||
git worktree add ../ticket-<n> -b ticket/<n>-<slug> <base> # base = the branch you are on
|
||||
cp .env ../ticket-<n>/ 2>/dev/null # gitignored, worktrees do not get it
|
||||
tea issue edit <n> --add-assignees <your gitea username> # tea login list has it
|
||||
```
|
||||
|
||||
Write the brief to `.scratch/<batch-slug>/t<n>-brief.md` using the template
|
||||
below, in the ubiquitous language of `CONTEXT.md` — a brief that says "scrape"
|
||||
where the domain says Poll hands the subagent the wrong model of the system.
|
||||
Then dispatch the whole wave in **one** `task` batch, every item on the
|
||||
`ticket-implementer` agent. Each dispatch names: the absolute brief path, the
|
||||
worktree path, the branch, the base ref, and the report path
|
||||
`.scratch/<batch-slug>/t<n>-report.md`. Mark each ticket `dispatched` in the plan
|
||||
file.
|
||||
`.scratch/<batch-slug>/t<n>-report.md`.
|
||||
|
||||
## 2. Land the wave
|
||||
<brief-template>
|
||||
|
||||
# Ticket #<n> — <title>
|
||||
|
||||
**Read first.** `tea issue <n> --comments` for this ticket, then the issue it
|
||||
refers to — the parent or spec — the same way. The comments carry decisions the
|
||||
body never got updated with. This brief stays the requirements; those two reads
|
||||
are the intent behind them.
|
||||
|
||||
**Goal.** The end-to-end behaviour this ticket makes work, from the user's side.
|
||||
|
||||
**Acceptance criteria.** Verbatim from the ticket.
|
||||
|
||||
**Contract.** The exact shared signatures / shapes / names this ticket must
|
||||
implement or consume, and which sibling ticket is on the other end. Omit when
|
||||
the ticket touches nothing shared.
|
||||
|
||||
**Where it lands.** The files and packages, and the existing pattern to follow
|
||||
in each.
|
||||
|
||||
**Binding invariants.** The `AGENTS.md` rules this change can break — name them.
|
||||
|
||||
**TDD seams.** Where a test comes first — run the `tdd` skill at each one and
|
||||
follow its red → green loop. Or "none — verify after".
|
||||
|
||||
**Verify.** The exact commands, e.g. `cd backend && go test ./...`,
|
||||
`node --test userscript/test/logic.test.js`.
|
||||
|
||||
**Out of scope.** What not to touch, especially a sibling ticket's files.
|
||||
|
||||
</brief-template>
|
||||
|
||||
## 5. Land the wave
|
||||
|
||||
The wave is landed when every ticket in it is closed, reverted, or handed back
|
||||
to the user. Per returned ticket:
|
||||
@@ -61,17 +120,14 @@ clash — both sides green apart, wrong together — goes back to whichever tick
|
||||
owns the contract, as a re-dispatch with the collision described.
|
||||
|
||||
Then `tea comment <n> "<the report summary>"`, `tea issue close <n>`, and
|
||||
`git worktree remove ../ticket-<n>`. Keep the report file, and mark the ticket
|
||||
`landed` or `handed back` in the plan file.
|
||||
`git worktree remove ../ticket-<n>`. Keep the report file.
|
||||
|
||||
## 3. Hand back or close the batch
|
||||
Only once the whole wave is landed does the next wave start — its briefs may
|
||||
need what this one changed.
|
||||
|
||||
Waves left in the plan: stop and say which wave is next. Its briefs are written
|
||||
by `plan-tickets` against the base you just changed — that is why they were not
|
||||
written up front, and why you do not write them.
|
||||
## 6. Close the batch
|
||||
|
||||
Last wave landed: run the full suite once on the merged base, and report a line
|
||||
per ticket with its status, commits, and open concerns, plus anything still
|
||||
assigned or open on the tracker. A red suite after every ticket went green is an
|
||||
interaction bug — diagnose it, name the two tickets, and fix it or hand it back
|
||||
with both named.
|
||||
Run the full suite once on the merged base, and report: a line per ticket with
|
||||
its status, commits, and open concerns, plus anything still assigned or open on
|
||||
the tracker. A red suite after every ticket went green is an interaction bug —
|
||||
diagnose it, name the two tickets, and fix it or hand it back with both named.
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
---
|
||||
name: plan-tickets
|
||||
description: "Plan a batch of tickets and write the briefs for its next wave: read the tracker, decide waves and contracts, get the plan approved."
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
# Plan tickets
|
||||
|
||||
You produce the two artifacts the `implement-tickets` skill runs on: a **plan
|
||||
file** and one **brief** per ticket in the next wave. You write no ticket code
|
||||
and create no worktrees — that is the runner's half.
|
||||
|
||||
Ticket source and tracker conventions: `docs/agents/issue-tracker.md`. `tea` usage: skill `gitea`.
|
||||
|
||||
Called twice in a batch's life, at least: once to open it, then again after each
|
||||
wave lands, because a later wave's briefs may need what the last one changed. On
|
||||
a re-entry, read the existing `.scratch/<batch-slug>/plan.md` first and plan only
|
||||
the next unlanded wave — the waves and contracts already approved there stand
|
||||
unless the landed wave proved one wrong.
|
||||
|
||||
## 1. Collect the tickets
|
||||
|
||||
The user's argument is the selector: issue numbers, a label, a parent issue, or
|
||||
nothing. With nothing, take the open issues labelled `ready-for-agent`.
|
||||
|
||||
Fetch each with `tea issue <n> --comments`, and read the **whole** body —
|
||||
acceptance criteria and the `Blocked by` line are what the rest of this skill
|
||||
runs on. A ticket whose blockers are still open is out of this batch unless a
|
||||
blocker is also in it. Read the issue each ticket refers to, its parent or spec,
|
||||
the same way: nothing on the implementation path reads the tracker after you —
|
||||
only `cr-spec` does, at review time — so a decision that lives in a comment
|
||||
reaches the implementer only if you carry it into the brief.
|
||||
|
||||
## 2. Plan the batch
|
||||
|
||||
Explore enough of the codebase to write briefs a fresh context can act on: the
|
||||
files each ticket lands in, the patterns it must follow, the `AGENTS.md`
|
||||
invariants it touches.
|
||||
|
||||
Then decide three things:
|
||||
|
||||
- **Waves.** Blocking edges set the order; tickets with no open blocker inside
|
||||
the batch share a wave. Cap each wave at **3** concurrent tickets unless the
|
||||
user set another width.
|
||||
- **Contracts.** Two tickets in one wave that meet at a function signature, a
|
||||
JSON shape, a table column, or a token name: you decide the shape now and
|
||||
write the identical wording into both briefs. A contract left for the
|
||||
subagents to negotiate is a merge conflict you scheduled.
|
||||
- **Splits.** A ticket too big for one fresh context window goes into the wave
|
||||
as two briefs, or back to the user.
|
||||
|
||||
## 3. Write the artifacts
|
||||
|
||||
Pick a `<batch-slug>` — short, from what the batch is about — and write
|
||||
`.scratch/<batch-slug>/plan.md`. It is the handoff: the runner is a fresh context
|
||||
that reads this and nothing of your reasoning.
|
||||
|
||||
<plan-template>
|
||||
|
||||
# Batch <batch-slug>
|
||||
|
||||
**Base branch.** The branch every worktree forks from and merges back into.
|
||||
|
||||
**Waves.** A table: wave number, ticket number, title, brief path, and status —
|
||||
`planned` | `dispatched` | `landed` | `handed back`. Every ticket in the batch,
|
||||
including waves not briefed yet.
|
||||
|
||||
**Contracts.** Each cross-ticket contract verbatim, naming both ticket numbers.
|
||||
|
||||
**Assumptions.** What you had to assume, and what the user corrected at approval.
|
||||
|
||||
</plan-template>
|
||||
|
||||
Then write a brief per ticket in the next wave to
|
||||
`.scratch/<batch-slug>/t<n>-brief.md`, using the template below, in the
|
||||
ubiquitous language of `CONTEXT.md` — a brief that says "scrape" where the domain
|
||||
says Poll hands the subagent the wrong model of the system.
|
||||
|
||||
<brief-template>
|
||||
|
||||
# Ticket #<n> — <title>
|
||||
|
||||
**Decisions.** Whatever the ticket's comments or its parent spec settled that
|
||||
the body never got updated with, restated verbatim. The implementer reads this
|
||||
brief and the code, never the tracker — a decision missing here is lost to it,
|
||||
and a stale comment thread is not a source you want a fresh context guessing
|
||||
from. Omit only when the ticket has no comments.
|
||||
|
||||
**Goal.** The end-to-end behaviour this ticket makes work, from the user's side.
|
||||
|
||||
**Acceptance criteria.** Verbatim from the ticket.
|
||||
|
||||
**Contract.** The exact shared signatures / shapes / names this ticket must
|
||||
implement or consume, and which sibling ticket is on the other end. Omit when
|
||||
the ticket touches nothing shared.
|
||||
|
||||
**Where it lands.** The files and packages, and the existing pattern to follow
|
||||
in each.
|
||||
|
||||
**Binding invariants.** The `AGENTS.md` rules this change can break — name them.
|
||||
|
||||
**TDD seams.** Where a test comes first — run the `tdd` skill at each one and
|
||||
follow its red → green loop. Or "none — verify after".
|
||||
|
||||
**Verify.** The exact commands, e.g. `cd backend && go test ./...`,
|
||||
`node --test userscript/test/logic.test.js`.
|
||||
|
||||
**Out of scope.** What not to touch, especially a sibling ticket's files.
|
||||
|
||||
</brief-template>
|
||||
|
||||
## 4. Get the plan approved
|
||||
|
||||
Present, and stop:
|
||||
|
||||
- the wave list, and for each ticket in the next wave: number, title, one-line
|
||||
brief summary, the files or areas it will touch, its verification commands
|
||||
- every cross-ticket contract, verbatim as it appears in the briefs
|
||||
- anything you had to assume
|
||||
|
||||
Wait for approval. Apply the user's edits to the plan, do not relitigate them —
|
||||
into the files, not just the reply, or the runner never sees them.
|
||||
|
||||
Then hand off: name the batch slug and the wave, and stop. Running the wave is
|
||||
`implement-tickets`.
|
||||
+2
-12
@@ -55,17 +55,13 @@ DISCORD_CLIENT_SECRET=
|
||||
# The guild whose membership gates sign-in (Developer Mode -> right-click the
|
||||
# server -> Copy Server ID).
|
||||
DISCORD_GUILD_ID=
|
||||
# Optional: human-readable name for that guild, shown on the login screen so a
|
||||
# stranger knows which community owns this library and who to ask for an
|
||||
# invite. When unset the page falls back to a generic "private community"
|
||||
# label.
|
||||
# DISCORD_GUILD_NAME=
|
||||
# Exact callback URL, e.g. https://bookmark.example.com/auth/discord/callback.
|
||||
# Discord matches it verbatim, so it must equal the registered redirect.
|
||||
DISCORD_REDIRECT_URI=
|
||||
# Optional: a role snowflake members must hold on top of guild membership.
|
||||
# Empty (the default) means membership alone suffices.
|
||||
# DISCORD_REQUIRED_ROLE=
|
||||
|
||||
# Subdomain Traefik routes to the browser UI (required by the prod override).
|
||||
# Left commented on purpose: an example value here would be a silent
|
||||
# wrong-hostname fallback, and Traefik would publish the UI router on a domain
|
||||
@@ -104,13 +100,7 @@ DISCORD_REDIRECT_URI=
|
||||
# every kagane poll. Left unset here on purpose — a wrong default would poll a
|
||||
# stranger's address, and "no browser" is a safe, self-announcing state.
|
||||
# BROWSER_WS_URL=ws://100.x.y.z:9222
|
||||
#
|
||||
# Discord webhook for owner notices (outbound alerting when a poll Lane
|
||||
# stalls). Unset means the whole path is off — a local stack needs no webhook,
|
||||
# exactly as the browser URL behaves. The address is a secret in the class of
|
||||
# TOKEN_KEY: never commit it, never paste it anywhere public.
|
||||
# DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...
|
||||
#
|
||||
|
||||
# Zone the backend stamps its log lines in. Cosmetic only. Nothing else in
|
||||
# the service has a zone: bookmark timestamps are unix ms, and the two real
|
||||
# time columns are timestamptz. Defaults to Asia/Jakarta; set to UTC for the
|
||||
|
||||
-113
@@ -1,113 +0,0 @@
|
||||
---
|
||||
target: backend/internal/web (admin surface)
|
||||
total_score: 22
|
||||
max_score: 40
|
||||
na_heuristics:
|
||||
p0_count: 1
|
||||
p1_count: 2
|
||||
timestamp: 2026-08-27T07-53-05Z
|
||||
slug: backend-internal-web-templates-admin-html
|
||||
---
|
||||
Method: dual-agent (A: AssessDesign · B: AssessEvidence)
|
||||
|
||||
## Design Health Score
|
||||
|
||||
| # | Heuristic | Score | Key Issue |
|
||||
|---|-----------|-------|-----------|
|
||||
| 1 | Visibility of System Status | 2 | Domain status is excellent; *interaction* status is absent — no `hx-indicator`/`hx-disabled-elt` in any admin template (only `card.html:52,71,85,108,119` has them). |
|
||||
| 2 | Match System / Real World | 3 | `Due`/`Checked`/`Gap` (`lanes.html:24`) are unlabeled integers and a raw Go duration (`admin_lanes.go:229-231`); `Never chk` (`overview.html:13`). |
|
||||
| 3 | User Control and Freedom | 2 | Only Finish has Cancel + reversal (`series-detail.html:51-57`). Clear marks, Revoke, both Removes and both `Set` writes are one-way, and the old chapter survives only as a `placeholder` (`series-detail.html:19`). |
|
||||
| 4 | Consistency and Standards | 2 | "Needs attention" is `--patina` on the Series list (`admin.css:285-287`) and `--danger` on Lanes/Sites (`admin.css:189-191`, `:409-413`); sibling controls are `<a href="#">` vs `<button>` (`series-list.html:51`); three duration formatters. |
|
||||
| 5 | Error Prevention | 2 | Server-side gating is strong (`admin_lanes.go:82-90`, `admin_series.go:315-319`, `readers.html:36-42`), but `.ghost::after` inflates each target by 12px horizontally (`style.css:250`) against 12px/18px sibling gaps (`admin.css:303-305`, `:118-124`) — the overlap resolves to the destructive later sibling. |
|
||||
| 6 | Recognition Rather Than Recall | 2 | `.thead { display:none }` below 899px (`admin.css:826-828`) and the Sites figures carry `Label: ""` from Go (`admin_overview.go:170-173`), so the labels exist at no width on a phone. |
|
||||
| 7 | Flexibility and Efficiency | 3 | Bookmarkable state, figures-as-doors, OOB count refresh (`admin_series.go:503-515`); but the 30s `outerHTML` swap has no `hx-sync` (`lanes.html:12-13`) and there is no title search over 50-per-page (`admin_series.go:21`). |
|
||||
| 8 | Aesthetic and Minimalist Design | 3 | Verified restrained on screenshot; the charge is density on the landing page — 11 hygiene figures + 4 library figures + a 6-column table before any content (`overview.html:9-13`). |
|
||||
| 9 | Error Recovery | 1 | Every admin failure is a bare `http.Error`; htmx does not swap non-2xx; `admin.html:15` never loads `filter.js`, whose handlers are `.card`-scoped anyway (`filter.js:133-136`, `:172-187`). No error slot exists in any admin template. |
|
||||
| 10 | Help and Documentation | 2 | Good in-context prose (`readers.html:10-15`, `series-detail.html:17`, `:26`), but nothing explains `Due`, `Gap`, or the six outcome words, and the chips are documented dead ends (`admin_lanes.go:242-246`). |
|
||||
| **Total** | | **22/40** | **Acceptable — significant improvements needed** |
|
||||
|
||||
Adjudication note: Assessment A scored H4 at 1 and H8 at 2; both were raised one step after the parent verified the rendered pages (main flows are consistent and genuinely uncluttered on screenshot — the divergences are detail-level).
|
||||
|
||||
## Design Specificity Verdict
|
||||
|
||||
**Authored at the level of language and judgement; category-interchangeable at the level of composition and interaction.**
|
||||
|
||||
**LLM assessment.** The *writing* could belong to no other product. `laneState` emits sentences — `paused · resumes in 4h20m`, `refusing · backs off until 23:40`, `browser asleep`, `nothing eligible` — where a generic console prints `SKIPPED` (`admin_lanes.go:273-321`). `overviewVerdict` returns `no Lane has reported yet` with `HasCounts=false` so the page omits the counts clause rather than printing confident zeroes (`admin_overview.go:205-217`, `overview.html:7`). `door()` writes count and href as one atom so a figure cannot link to a list with a different number (`admin_overview.go:190-195`). `--patina` is declared as the admin's only accent with a stated reason and spent on the wordmark's `em` so the brand says which surface you are on (`style.css:91-94`, `admin.css:15-21`). `CanPoll`/`CanRemove` are visibility, not disablement (`admin_series.go:668-675`).
|
||||
|
||||
The *layout and interaction* would ship unedited as a Kubernetes admin: topbar + 4-tab underline navrow + micro-label + `repeat(auto-fit, minmax(232px,1fr))` stats grid + wide table (`admin.html:19-46`, `admin.css:30-63`, `:313-318`, `:236-241`). The uppercase-mono micro-label idiom appears at seven sizes between 10px and 13px with tracking from `.04em` to `.2em` (`admin.css:69-79`, `:202-207`, `:328-333`, `:531-536`, `:595-604`, `:732-738`) — a style, not a system: nothing tells the reader which size means what. And the destructive interactions are htmx's default `hx-confirm`, which is conspicuously *not* the pattern the Reader-facing library authored for itself (`card.html:113-121`).
|
||||
|
||||
**Deterministic scan.** CLI detector over all six admin templates: **exit 0, `[]`, zero findings.** Nothing to dismiss as a Go-template false positive.
|
||||
|
||||
**Browser evidence.** All five admin pages were rendered from the repo's own templates via a throwaway Go module with realistic fixtures covering every state the Go code can produce, then measured in Playwright at 390×844 and 1280×900. **No horizontal overflow, no clipping, no overlap on any page at either viewport** (overview `scrollW 375 < 390`; readers `390 == 390`; all `.tbl` grids collapse to flex-wrap under 899px, lanes additionally under 1019px). Injected detector fired 9 `text-overflow` (brand `em` 41px; `span.mark.bad` 33px; `span.ok` 47px; `a.ghost.act` 22px ×5), 22–48 `ai-color-palette` "cyan neon" per page, one `cream-palette`, and `overused-font` at 16–27%. **All are false positives**: the overflows are inline boxes spilling into their own cell's padding inside the border box (`1014 < c-ctrl left 1038`), the "cyan" is every `--patina` usage, the cream is the designed light-branch `--ink` (`style.css:125`), and the font is the deliberate `--font-display` on brand and headings only. The one real signal inside the noise is *frequency*: 22–48 patina elements per page means the admin's single accent is doing a great many different jobs.
|
||||
|
||||
No user-visible overlay is left in a browser — the live server was injected, read, and stopped.
|
||||
|
||||
## Overall Impression
|
||||
|
||||
The thinking behind this surface is better than the surface. Judgement is computed in Go and the template only prints, so the page structurally cannot lie about its own numbers — that is rarer than it sounds and it is why the copy can be as confident as it is. What has not been spent is the *feedback and repair* budget: the owner comes here to fix one wrong row, and the surface will not tell them whether the fix landed, will not label the columns on the device they are holding, and hands the two irreversible actions to a browser dialog while spending a hand-built confirm row on the reversible one.
|
||||
|
||||
**Single biggest opportunity:** make the admin surface as accountable for its own actions as it already is for the poller's. Load the error path, add busy state, and move destruction onto the confirm-row pattern the codebase already owns.
|
||||
|
||||
## What's Working
|
||||
|
||||
1. **Judgement is an atom.** `laneState` returns `(phrase, good, attention)` together (`admin_lanes.go:273-321`); `door()` binds count to href (`admin_overview.go:190-195`); `overviewVerdict` documents that it deliberately answers a *different* question from `laneState` so page and notification cannot contradict each other (`admin_overview.go:197-204`). This eliminates a whole bug class: a colour that disagrees with the sentence beside it.
|
||||
2. **Zeros and unknowns are honest, and the design pays for it.** A measured zero loses its link and drops to `--mute` (`admin_overview.go:190-195`, `admin.css:341-343`); a virgin pass log suppresses the counts clause entirely; a failed outcome sum degrades per row to `none observed` instead of blanking the table (`admin_lanes.go:172-180`). Health consoles usually fail here — a page of confident zeroes reading as health.
|
||||
3. **Removal from the list is a complete interaction.** `HX-Reswap: delete`, OOB heading count re-rendered over the press's own filter state, and if a Bookmark raced the press the row swaps *back in* with the reason in-row (`admin_series.go:474-515`, `series-list.html:52`, `:62`). Success, contention and refusal land in the same slot at the same scale. Every other action should look like this.
|
||||
|
||||
## Priority Issues
|
||||
|
||||
**[P0] An htmx failure on the admin surface is completely invisible.**
|
||||
- *Why it matters:* every admin error path is `http.Error` (`admin.go:98`, `:109`, `:136`, `:155`; `admin_lanes.go:118-128`; `admin_series.go:307-322`); htmx does not swap non-2xx; `admin.html:15` loads only `htmx.min.js`, and `filter.js`'s `htmx:responseError`/`htmx:sendError` handlers are both unloaded here *and* `.card`-scoped (`filter.js:133-136`, `:172-187`). Verified: no admin template contains `error-inline`, `hx-indicator` or `hx-disabled-elt`. A rejected chapter correction or a dropped LAN connection produces **zero visual change**. The owner's natural response is to press again, and with no `hx-disabled-elt` the second press is a second write. This is the corrective-task path; it breaks trust exactly where trust is the product.
|
||||
- *Fix:* load `filter.js` from the admin shell (or extract its error module) and generalise `showError`'s `.closest(".card")` to a configurable slot; add `<p class="error-inline" role="status" hidden>` to each `.dform`, `#readers` and the `.trow` — `.row-msg` (`admin.css:672-677`, `series-list.html:52`) already proves the row can carry a message; add `hx-disabled-elt="this"` to every writing control. The `http.Error` bodies are already short human sentences worth showing verbatim.
|
||||
- *Suggested command:* `/impeccable harden`
|
||||
|
||||
**[P1] Below 899px the tables lose their only labels, and the Sites table never had any.**
|
||||
- *Why it matters:* `.thead { display:none }` (`admin.css:826-828`; `:793-795` for lanes at 1019px) with cells flattening to equal-weight left-aligned text. The Sites figures are `door("", …)` ×4 (`admin_overview.go:170-173`), so those labels exist at **no width** on a phone. Measured and screenshot-confirmed: a Lanes row on a phone reads `3 2 4m30s ran 2m ago` — four bare values. The Series grid survives (title owns its line, site is a coloured word, ages self-label as `3h ago`); Lanes degrades; Sites does not survive, and it is on the landing page. The primary device is a phone.
|
||||
- *Fix:* give collapsed cells their labels instead of hiding the header — populate `fig.Label` for site rows (the field exists, `admin_overview.go:43-47`) and render `.trow > *[data-lbl]::before { content: attr(data-lbl) " " }` inside the 899px block in the existing 11px `--mute-2` idiom; same for `Due`/`Checked`/`Gap`; add `.tbl.sites .c-site { width: 100% }` so the site name owns its line as `.c-title` already does.
|
||||
- *Suggested command:* `/impeccable adapt`
|
||||
|
||||
**[P1] Destructive actions are gated by native browser dialogs while the reversible one gets the bespoke confirm.**
|
||||
- *Why it matters:* `hx-confirm` on Clear marks (`readers.html:31`), Revoke sessions (`:39`), list Remove (`series-list.html:51`) and detail Remove (`series-detail.html:40`) — versus a hand-built `.confirm-row calm` with Cancel and `aria-live` for **Finish**, which is reversible via Un-finish (`series-detail.html:51-57`, `admin_series.go:257-294`). Inverted effort. A native dialog cannot carry `--danger`, so "sign this Reader out of every device" and "clear some counters" look identical at the decision moment, and it is OS chrome inside a sheet that has removed every corner and shadow. The full `--danger-wash` + `.danger-solid` pattern already exists and is already used by the Reader-facing card for *its* irreversible remove (`style.css:688-717`, `card.html:113-121`). AGENTS.md states the law directly: any move that pulls a series out of the list must be confirm-gated via its own `.confirm-row`.
|
||||
- *Fix:* move Revoke and both Removes onto `.confirm-row` with `--danger-wash`/`.danger-solid`, Clear marks onto `.calm` (it restores a privilege, `admin.go:142-147`). The confirm copy transfers verbatim. Note `admin.css:307-311` already styles `.tbl .trow > .confirm-row` at `grid-column: 1/-1` — **that rule is dead today**; the CSS is waiting for the markup.
|
||||
- *Suggested command:* `/impeccable harden`
|
||||
|
||||
**[P2] `--danger` is used to mean "system unhealthy", which the token law forbids, and "needs attention" is spoken in two colours.**
|
||||
- *Why it matters:* `style.css:91-94` states `--patina` is the admin page's only accent and that neither ember nor danger may say "system unhealthy". But `admin.css:409-413` and `:189-191` paint `.c-state.bad`, `.c-skip .bad` and `.trow.attention .c-site` in `--danger` — screenshot-confirmed: `refusing · backs off until 14:20` and `not checking` render oxblood, and the attention site names go red — while the identical semantic on the Series list is verdigris (`admin.css:285-287`). Colour is the owner's fastest read, and cross-page it does not resolve. Separately `.c-state`'s base colour is `--patina` with no `.ok` rule, so `no pass yet` — an *unknown* — renders in the healthy accent.
|
||||
- *Fix:* route all attention through `--patina`; reserve `--danger` for Remove/Revoke and their wash. If a second severity tier is genuinely wanted for `refusing`/`not checking`, declare a token in both `:root` branches rather than borrowing destruction's colour. Give `.c-state.ok` an explicit rule and make base `.c-state` neutral so an unlabeled state is not a claim.
|
||||
- *Suggested command:* `/impeccable colorize`
|
||||
|
||||
**[P2] Phone hit targets: the destructive sibling wins ambiguous taps, and the pager is untappable.**
|
||||
- *Why it matters:* `.ghost::after { inset: -15px -12px }` (`style.css:250`) inflates each ghost by 24px of combined horizontal overhang against a 12px gap in `.c-act` (`admin.css:303-305`) and 18px in `.reader-actions` (`:118-124`) — the pseudo-elements overlap and the later sibling paints on top. The later sibling is `Remove` and `Revoke sessions`. Measured at 390px: Check now 76×16, Remove 50×16, Clear marks 92×16, Revoke 126×16, pager `next ›` 49×11, pause `<select>` ~31px tall, `.fig` links 9–34×20–24, navrow links 41–42px high. `.pg.disabled` sits at `--faint` = **1.62:1** — "no next page" reads as "the control is missing". The scene is one thumb, at night.
|
||||
- *Fix:* raise the `.c-act`/`.reader-actions` gap past 26px, or put the destructive control on its own line at phone width; give `.pg`, `.segrow a`, `.fig` and the pause select real 44px boxes inside the 899px block; add `line-height` to `.navrow a`.
|
||||
- *Suggested command:* `/impeccable adapt`
|
||||
|
||||
## Persona Red Flags
|
||||
|
||||
**Alex (power user / single operator — no colleague, no runbook).** The failure chips are permanently non-navigable *by design* (`admin_lanes.go:242-246`), so `refused 14` is a dead end: fourteen refusals and no path to a single affected Series. Nothing on the surface defines `Due`, `Gap`, or the six outcome words. No title search over a 50-row page (`admin_series.go:21`), no bulk action, no keyboard path to anything but tab order.
|
||||
|
||||
**Sam (accessibility / low-vision).** `aria-live="polite"` wraps the self-refreshing Lanes block (`admin.html:38`), which replaces itself every 30s — a screen reader re-announces the whole table twice a minute — while `#readers` and `#detail-meta`, the fragments that change *because the owner acted*, have no live region at all. The politeness is on the wrong element. Revoke's only success signal is the button's absence. The micro-label idiom bottoms out at 10px uppercase mono with `.2em` tracking in `--mute-2` (`admin.css:708-720`, `:732-738`) — `#877f76` is 4.86:1 on `--ink`, and `style.css:67-68` says that budget was set for 10px mono specifically, i.e. it is at the edge, not above it. On banded rows `--danger` measures 4.46:1 and `--mute-2` 4.49:1 against `--hover` (`admin.css:495-497`) — both just under AA.
|
||||
|
||||
**Casey (thumb-only mobile).** Fails the hit-target cluster above, and specifically the **30s refresh racing the pause select**: `lanes.html:12-13` swaps `#lanes` outerHTML every 30s with no `hx-sync` while the duration is a native `<select>` inside that fragment (`lanes.html:47-49`). Open the picker, scroll to `24h`, straddle a refresh boundary — the select is rebuilt at its `selected` default of `6h`, silently. The owner then gets six hours and a perfectly accurate confirmation phrase saying so.
|
||||
|
||||
**Project-specific — the owner on a phone, at night, mid-chapter, fixing one wrong row.** The surface's true primary scene, and it fails in sequence: (1) *finding* the row — filter/site/kind but no title search, so they page through 50-row pages using the 11px zero-padding pager whose disabled state is invisible at 1.62:1; (2) *reaching* the fix — the correction form exists only on the detail page (`series-detail.html:15-23`), one hop past a list row whose action slot already carries two controls; (3) *knowing it worked* — the P0 case exactly. And the one visual anchor confirming "yes, this is the right series" is squashed: `style.css:489` sets `height: calc(var(--cover-w) * 4/3)` = 124px, which `admin.css:708-711` never overrides while setting `width: 160px` and `aspect-ratio: 3/4` — both dimensions definite, so `aspect-ratio` is ignored and portrait artwork renders as a **160×124 landscape crop**. Confirmed on the rendered page.
|
||||
|
||||
## Minor Observations
|
||||
|
||||
- **"1 readers."** `series-detail.html:72` prints `{{.Readers}} readers` over an `int` (`admin_series_detail.go:30`) — screenshot-confirmed on the detail page. `readers.html:20` pluralizes `session{{if ne .Sessions 1}}s{{end}}` correctly four files away.
|
||||
- **First-run Overview has no empty state.** No `{{else}}` on any of the three blocks; a fresh install renders the verdict line, 11 zeros, 4 zeros, then a `.tbl.sites` **header row with nothing under it**. `lanes.html:56-58` and `series-list.html:34` both guard properly; the one page a new owner sees first does not.
|
||||
- **~60 lines of dead CSS.** `.lanelist`/`.lane-site`/`.lane-fact`/`.lane-mark`/`.lane-browser` (`admin.css:100-116`, `:141-143`, `:160-191`) — `lanes.html` uses `.tbl.lanes`. `.tbl .trow > .confirm-row` (`:307-311`) has no markup. `.c-state.ok` is emitted but unstyled. `.act` is applied at `series-list.html:51` and `series-detail.html:35` and **defined nowhere**.
|
||||
- **`admin.css:5-9`** is a `prefers-color-scheme: light` block redefining `--measure-wide` to the identical `1080px`. Delete it; it teaches the next reader a lie about there being a width to keep in sync.
|
||||
- **The no-cover placeholder has typography but no content.** `.cover` gets a centred 10px uppercase `--mute-2` label idiom (`admin.css:708-720`); `series-detail.html:12` renders an empty hatched box. `NoCover` already exists (`admin_series_detail.go:142`) — print it, or drop the styling.
|
||||
- **`Check now` is an `<a href="#">` carrying `hx-post`** (`series-list.html:51`, `series-detail.html:35`) while `Remove` beside it is a real `<button>`. Long-press, middle-click and no-JS keyboard activation all navigate to `#`.
|
||||
- **Three duration formatters**, one of them the stdlib's: `since()` prints raw Go durations (`admin_lanes.go:344-350`) so `Gap` reads `1m30s`, while `checkedAge` (`admin_series.go:748-765`) and `humanDuration` read like English.
|
||||
- **The Overview's 11 hygiene labels are the Series page's 11 Show options** (`admin_series.go:27-40`) in two shapes; the select already carries the counts *and* attaches narrowing, which is arguably the better of the two presentations.
|
||||
- **`.stat` rows have no separators** (`admin.css:320-326`). On the rendered desktop page a 4-column row reads `NO SERIES URL 3 NEVER READ A CHAPTER 0` — figure and next label collide into one phrase with only a 16px gap to separate them.
|
||||
- **`readers.html` has no empty state.** Unreachable in practice (the owner is always in the roster), but both siblings guard.
|
||||
|
||||
## Questions to Consider
|
||||
|
||||
1. **Why does the Overview exist?** Fifteen figures and a table, where 11 figures duplicate a select that already shows the same counts *with narrowing attached*. Strip it to the verdict line, the four Library figures and the Sites table — what is lost?
|
||||
2. **If a chip can never be a door, should it still be a count?** `refused 14` invites a tap that will never exist (`admin_lanes.go:242-246`). Is the honest answer `refused · 14 attempts`, or that Lanes needs the per-Series drill-down the taxonomy currently cannot provide?
|
||||
3. **The surface built a Cancel for Finish and handed Revoke to the browser.** If the reasoning is that Revoke's `hx-confirm` sentence is already unambiguous, why does the Reader-facing library still spend a `.confirm-row` on *its* remove? Which surface has the wrong standard?
|
||||
4. **What is `--danger` for?** The token says destruction; the law says only `--patina` may say "system unhealthy"; the CSS paints `refusing` in danger. Either a third severity token gets declared in both branches, or Lanes comes back under the law. Which — and how did the surface run this long with both readings?
|
||||
5. **Is 30 seconds a design decision or a default?** It polls tab-hidden, clobbers a half-operated select, and on a dimmed phone nobody sees it. Would `refreshed 40s ago · tap to refresh` be cheaper *and* more honest?
|
||||
@@ -1,135 +0,0 @@
|
||||
---
|
||||
target: backend/internal/web
|
||||
total_score: 27
|
||||
max_score: 40
|
||||
na_heuristics:
|
||||
p0_count: 1
|
||||
p1_count: 2
|
||||
timestamp: 2026-08-27T12-24-48Z
|
||||
slug: backend-internal-web
|
||||
---
|
||||
Method: dual-agent (A: AssessmentA/designer · B: AssessmentB/task — B crashed before yielding; its detector artifacts were recovered from `history://AssessmentB` and `/tmp/impeccable-critique`, and the browser overlay pass was re-run in the parent)
|
||||
|
||||
## Design Health Score
|
||||
|
||||
| # | Heuristic | Score | Key Issue |
|
||||
|---|-----------|-------|-----------|
|
||||
| 1 | Visibility of System Status | 3 | Busy hairline, per-card error slots, 15s htmx timeout, OOB chrome refresh all good — but a *successful* mutation announces nothing, and `hx-delete` swaps the card for an empty body in total silence (`card.html:124-134`, `web.go:569-573`). |
|
||||
| 2 | Match System / Real World | 3 | Reader copy is human ("Chapter you're on", `card.html:95`); the owner's view leaks implementation vocabulary — "Sighting counters", "deferral blocked", "Lanes", "band" (`readers.html:10-14`, `lanes.html:15`). |
|
||||
| 3 | User Control and Freedom | 2 | Esc closes panels and restores focus (`filter.js:120-150`); removal is irreversible with no undo (`web.go:558-573`), and `readers.html:53` Cancel restores neither `aria-expanded` nor focus. |
|
||||
| 4 | Consistency and Standards | 2 | Three confirm implementations: focus-managed JS (`card.html:70,83`), bare inline `onclick` (`readers.html:31,34`; `series-detail.html:47,70`), native `confirm()` (`setup.html:29`). |
|
||||
| 5 | Error Prevention | 3 | `max="9999"` guard, no-op submit is a no-write (`web.go:527-531`), restore fires instantly *because* reversible. Docked for `onchange="this.form.submit()"` (`series-list.html:9,12`) — WCAG 3.2.2 On-Input. |
|
||||
| 6 | Recognition Rather Than Recall | 3 | The permanent action key answers the unlabelled icon strip (`chrome.html:35-45`) but teaches a second vocabulary: "Delete" vs `aria-label="Remove"`, "Read" vs "Continue reading", "Fav" vs "Toggle favourite". |
|
||||
| 7 | Flexibility and Efficiency | 2 | Esc is the only accelerator. No skip link, no `/`-to-search, no bulk action, no sort; 200 series get one substring filter. |
|
||||
| 8 | Aesthetic and Minimalist Design | 3 | Containerless sheets, one `--measure`, three faces each with one job — but **563px of chrome measured** before the first card at 390×844, and the inert action key renders as a row of buttons. |
|
||||
| 9 | Error Recovery | 3 | `filter.js:180-250` is the best-designed code here: 401 → "Session expired — nothing was saved" + login link, echoes the server's 400 reason, no auto-dismiss with the rationale written down. Docked: the echoed reasons are engineer strings ("missing key", "invalid status", `web.go:446,456,513`). |
|
||||
| 10 | Help and Documentation | 3 | Setup panel is honest documentation incl. the Violentmonkey-on-mobile caveat (`setup.html:17-20`); empty states teach. Docked: Lanes/Overview ship an ops vocabulary with zero explanation. |
|
||||
| **Total** | | **27/40** | **Acceptable — significant improvements needed** |
|
||||
|
||||
## Design Specificity Verdict
|
||||
|
||||
**LLM assessment — split: the reader library is authored; `/admin` is a generic ops console wearing Cinder tokens.**
|
||||
|
||||
Library-side evidence that could not be lifted into another product: `--danger` exists as a separate token *specifically* so a remove confirm is never misread as an unread chapter across a dark room (`style.css:77-79`); the busy indicator is a grey hairline that deliberately refuses the accent (`style.css:840-852`); source tokens are named for the actual scraped sites (`style.css:110-117`); `--hatch` exists because `og:image` is often absent and the slot must stay honest rather than fake artwork (`style.css:119-122`); the monogram sits *under* the `<img>` unconditionally so a stored-then-404'd cover degrades to a letter (`card.html:9-19`); `overflow-wrap: anywhere` is justified by a measured 789px-wide `og:title`; `step="any"` by a real series read to 1200.25; the Updated tab exists only for manga because novels have no poller (`app.html:64-70`).
|
||||
|
||||
Admin-side: Overview is a stat grid plus a site table (`overview.html:7-15`); Series is a filter bar with two auto-submitting selects, a paged table and `‹ prev / next ›` (`series-list.html:7-70`). Strip `--patina` and it is any 2014 Rails admin. It also contradicts PRODUCT.md's own principle that the owner's panel is "one list with one button, not an admin console."
|
||||
|
||||
**Deterministic scan.** `node detect.mjs --json backend/internal/web/templates` → **exit 0, `[]`, zero findings** — and that is a degraded scan, not a clean bill: the static-HTML engine's parser deps (`htmlparser2`, `css-select`, `css-tree`, `domutils`) are absent from the skill install, Go templates are fragments rather than full pages, and `<link href="/static/style.css">` is absolute so no CSS ever cascades from a template directory. Assessment B worked around all three — rendered the real templates through `html/template` in a throwaway Go program outside the repo, copied `static/` beside them, `npm install`ed the four parsers into a `/tmp` engine copy — and got **64 findings** over the rendered pages: 29 `undersized-ui-text`, 12 `cramped-padding`, 9 `low-contrast`, 7 `overused-font`, 7 `cream-palette`. Re-run against a dark-only stylesheet (light + `min-width` blocks stripped, because the engine discards `@media` conditions and merges every block last-wins): **103 findings** — 71 `undersized-ui-text`, 25 `low-contrast`, 7 `overused-font`.
|
||||
|
||||
Agreements and false positives: the detector's `low-contrast` hits land on exactly the pair Assessment A computed by hand — `--ember #e0452c` on `--ember-wash #221311` at **4.3:1** — independent confirmation of the P1 below. `overused-font` (Instrument Serif at 34% of text) and `cream-palette` are false positives: both are the committed brief. Most `cramped-padding` is an artifact of the engine flattening `@media` conditions. `text-occlusion` on "Rotate credential" is a false positive from the collapsed `<details>`.
|
||||
|
||||
**Visual overlays.** Injection succeeded. Overlays were rendered live in the browser tab at 390×844, dark, over the real stylesheet, and the in-page detector reported **19 anti-patterns**: 2× `low-contrast` (`#e0452c` on `#221311`, 4.3:1), 11× `undersized-ui-text` (10px "Manga", "Novels", "Userscripts", "Read", "Fav", "Chapter", "Archive", "Delete", "Continue reading", "Chapter you're on", "Latest known: …"), 1× `overused-font`, 1× `text-occlusion` (FP). Two measurements taken in the same browser:
|
||||
|
||||
- **First card top = 563px** on 390×844 — topbar 102 + search 44 + tabs 46 + keyrow 50 + setup 57 + recent strip 250. Exactly one list row on first paint, on the primary device. Assessment A predicted ~560 from the stylesheet alone.
|
||||
- **Desktop overflows with no content.** `empty.html` at 1280×800: `zoom: 1.2` on `:root` × `min-height: 100dvh` on `.sheet` = 960px in an 800px viewport, so an empty library scrolls 20%. `.login-card` divides `--zoom` back out (`style.css:885-886`); `.sheet` does not (`style.css:234-237`).
|
||||
|
||||
## Overall Impression
|
||||
|
||||
The reader library is one of the more disciplined self-hosted UIs I've reviewed: one heat colour that means exactly one thing, a token file whose comments record contrast arithmetic and the bugs each rule was written against, and error handling designed by someone who has been interrupted mid-tap on a phone. What it does not have is a non-visual user. Every one of the five primary actions swaps its own DOM node out from under the focused element with no announcement and no focus move — the interface's most careful work is all visual, and its least careful work is everything a screen reader depends on. Second biggest opportunity: the first screen. 563px of learn-once chrome ahead of the one row the reader opened the app to see.
|
||||
|
||||
## What's Working
|
||||
|
||||
1. **The ember law is enforced by omission, not convention** (`style.css:77-94`, `840-852`). Splitting `--danger` from `--ember`, giving the busy bar a grey hairline instead of the obvious accent, and picking `--patina` from the far side of the wheel for admin means that at 2am one colour on screen has one meaning. Most systems declare that rule and leak it inside a month.
|
||||
2. **`filter.js:180-250`.** Routes failures to the nearest meaningful slot, distinguishes "session expired — *nothing was saved*" on a write from the same 401 on a navigation, echoes a 400 reason only when it looks like a reason rather than an error page, and refuses an auto-dismiss timer with the reason written in the code.
|
||||
3. **The cover fallback is correct in the way that only comes from being burned** (`card.html:9-19`). Monogram always beneath the image plus `onerror="this.remove()"` handles the case everyone forgets — a cover stored successfully and later 404ing — where the naive `{{else}}` leaves a broken-image glyph in a 93px slot.
|
||||
|
||||
## Priority Issues
|
||||
|
||||
**[P0] htmx swaps destroy focus and announce nothing, on all five primary actions.**
|
||||
Favourite (`card.html:56-58`), restore (`:75-78`), archive (`:115-117`), chapter save (`:89-92`) and remove (`:124-127`) all target the card with `hx-swap="outerHTML"`. The `<article>` is in no live region and nothing moves focus. Remove is worst: `web.go:569-573` answers with an empty body, so the focused button and its container both vanish and focus falls to `<body>` in silence — indistinguishable from a crash. That the fix is known is proven three files over: `series-detail.html:91` puts `aria-live="polite"` on `#detail-meta`, so the owner's form announces itself while the reader's card does not.
|
||||
**Fix:** one persistent visually-hidden `<div role="status" id="sr-announce">` in `app.html` and `admin.html`; emit the result text into it out-of-band from each mutation handler ("Archived Berserk"). For removal, move focus to the next `.card`'s play cell (or `#list` when it was the last row) in an `htmx:afterSwap` handler beside the existing hook at `filter.js:48`.
|
||||
**Suggested command:** `/impeccable harden`
|
||||
|
||||
**[P1] The ember state indicator fails WCAG AA at 4.3:1 — the one pair the whole design rests on.**
|
||||
Hand-computed by A and independently confirmed by the in-browser detector: `--ember #e0452c` on `--ember-wash #221311` = **4.33:1** for `.new-chapter` (11px mono, `style.css:609` on `.card.is-new` ground `:534`), the active `.tab-new` (`:392`), and the `.count` badge (`:394-401`). `--ember` on `--ink` passes at 4.61 — this is the case that was checked against the page but never against its own tinted background. Light branch source labels fail too: `--lightnovelworld` 4.25, `--demonic` 4.48, `--novelfull` 4.49, all dropping further on `--ember-wash`.
|
||||
**Fix:** dark `--ember` → ≈`#e85a41` (4.98 on `--ember-wash`, 5.31 on `--ink`), or darken `--ember-wash` to `#1c0f0d`. Light: `--lightnovelworld: #47705f`, `--novelfull: #6f6244`, `--demonic: #7b5d4a`. Verify against `--ember-wash`, not only `--ink`.
|
||||
**Suggested command:** `/impeccable audit`
|
||||
|
||||
**[P1] Control boundaries are invisible: `--field-line` is 1.32:1 against the page.**
|
||||
`--field-line #2c2926` on `--ink` = 1.32:1 (light branch 1.44:1), and it is the *only* boundary for the chapter input (`style.css:731`), every `.ghost` — Log out, Admin, install links, Rotate (`:273`), the library switch (`:623,633`), Clear search (`:867`), and **Cancel inside the remove confirm** (`:767`). WCAG 1.4.11 wants 3:1 for a control's identifying boundary. At the highest-stakes moment the design gives destruction a filled `--danger` slab and safety a 12px `--mute` label in a box nobody can see.
|
||||
**Fix:** raise `--field-line` to ≈`#4a4540` (3.06:1 on `--ink`) for interactive borders; leave `--rule`/`--rule-soft` decorative but stop using `--field-line` as if it were. Give Cancel real button weight in the confirm row — it is the recommended action.
|
||||
**Suggested command:** `/impeccable audit`
|
||||
|
||||
**[P2] The admin surface renders "healthy" and "broken" identically.**
|
||||
`.mark.bad` (`admin.css:396-400`), `.mark` (`:362-366`), `.mark.mark-strong` (`:376-383`), `.c-state.ok` *and* `.c-state.bad` (`:425-430`), `.c-skip .ok` *and* `.c-skip .bad` (`:431-449`) all resolve to the same `--patina` / `--patina-wash` / `--patina-line` triple, so `lanes.html:18` paints "unreachable" and "reachable" in one colour separated by a 7px dot, and `overview.html:15` chips are pixel-identical. The page whose purpose is "is anything wrong at a glance" now has to be read chip by chip. The one-accent law was meant to keep ember and danger off admin, not to collapse ok into bad.
|
||||
**Fix:** keep `--patina` for good, give `.bad` the existing `--slate` family (`--slate-soft` on `--slate-wash` = 6.06:1) plus a glyph or word so the distinction is not colour-alone.
|
||||
**Suggested command:** `/impeccable colorize`
|
||||
|
||||
**[P2] Two unlabelled write inputs and two auto-submitting selects on the owner's most consequential page.**
|
||||
`series-detail.html:19` (`type="number" name="chapter" placeholder="{{.Chapter}}"`) and `:29` (`type="url" name="series_url"`) have no `<label>`, `aria-label` or `aria-labelledby`; the placeholder is the *current value*, so a screen reader hears a bare number as the field's name — WCAG 3.3.2/4.1.2 on a form that writes a value every Reader sees. `series-list.html:9,12` carry `onchange="this.form.submit()"`, making the filter unusable from a keyboard (first arrow-key navigates). Three lines away the same file gets it right (`<label class="fsel">`), as does `lanes.html:49`.
|
||||
**Fix:** real `<label for>` on both, current value moved from `placeholder` into a hint line; replace auto-submit with a visible Apply button.
|
||||
**Suggested command:** `/impeccable clarify`
|
||||
|
||||
**[P2] Desktop overflows with an empty library (browser-verified).**
|
||||
`style.css:955` sets `zoom: 1.2` on `:root` at ≥1280px; `.sheet` keeps `min-height: 100dvh` (`:234-237`) without dividing `--zoom` back out, the way `.login-card` correctly does (`:885-886`). Measured live: `empty.html` at 1280×800 → sheet 960px, scrollbar on a page with no content. The `--zoom` token comment at `:129-131` names this exact hazard.
|
||||
**Fix:** `min-height: calc(100dvh / var(--zoom))` on `.sheet`, matching `.login-card`.
|
||||
**Suggested command:** `/impeccable adapt`
|
||||
|
||||
## Persona Red Flags
|
||||
|
||||
**Sam (screen reader, keyboard-only, 200% zoom, low vision)** — the hardest-hit persona:
|
||||
- Focus destroyed and nothing announced on all five card actions; remove is total silence (`card.html:56,75,89,115,124`; `web.go:569-573`).
|
||||
- Favourite never exposes state: static `aria-label="Toggle favourite"` overrides the dynamic `title`, no `aria-pressed` (`card.html:53-55`).
|
||||
- The pencil is a disclosure with no disclosure semantics — no `aria-expanded`/`aria-controls` in markup, while archive and remove three lines away have both (`card.html:61-62` vs `:68-69,81-82`).
|
||||
- Broken heading order: `<main id="list">` has no heading, so every card `<h3>` nests under the sibling `<h2>Continue reading</h2>` — by heading navigation all 40 series appear to live inside the 5-item strip (`chrome.html:11`, `app.html:92`, `card.html:25`). Two `<h1>`s on series detail (`admin.html:25` + `series-detail.html:9`).
|
||||
- `aria-label` on a bare `<div class="keyrow">` with no role is dropped: the legend announces as five orphan words (`chrome.html:35`).
|
||||
- Search results never announced: filtering toggles `card.hidden` with no live region and no count; `#no-match` is unhidden without `role="status"` (`filter.js:12-32`, `list.html:7`).
|
||||
- `.play` and `.remove` have no `:focus-visible` rule while `.fav`, `.pencil`, `.box`, `.restore` do — tabbing a card, three cells light and two do not (`style.css:677-689`). Two inputs drop the focus ring for a 1px border change (`:355,735`). Exactly one `:focus-visible` outline exists in the codebase and it is scoped to `.admin-sheet .ghost` (`admin.css:734-738`).
|
||||
- No skip link past ten chrome controls (`app.html:26-92`). `.tabs`/`.recent-strip` scroll horizontally with `scrollbar-width: none` and no fade, so at 200% zoom "Archived" is off-screen with no cue (`style.css:360-369`).
|
||||
- Login refusal is never announced: `role="alert"` on markup present at parse time does not fire, and the page reloads on failure (`login.html:24-25`, `discord.go:184-185`).
|
||||
- Correct and worth keeping: `alt=""` on the decorative cover inside an `aria-hidden` duplicate link, with the title as a real `<h3>` beside it (`card.html:7-19`). Measured hit targets are honest — tab 44px, card action cell 46px.
|
||||
|
||||
**Alex (impatient power user)**:
|
||||
- One list row at 563px on first paint; the chrome that costs it is all learn-once content. The recent strip hides itself when empty (`chrome.html:10`); the five-item legend never does (`:35`).
|
||||
- Esc is the only keyboard accelerator in the product (`filter.js:120-150`). No `/`, no `j/k`, no Enter-to-continue.
|
||||
- No bulk actions, no sort: archiving ten dead bookmarks is 30 taps.
|
||||
- His fast path evaporates on the first keystroke — the strip hides while filtering (`filter.js:22-24`) and is server-suppressed on every tab but All (`web.go:344-350`).
|
||||
- Removal is irreversible and thumb-adjacent as the fifth cell in a five-cell strip (`web.go:558-573`).
|
||||
|
||||
**Jordan (confused first-timer)**:
|
||||
- The same install action appears twice on the first screen, framed differently (`list.html:22-26` under `setup.html:11-14`).
|
||||
- A five-item action legend renders for a list with zero rows (`chrome.html:35`), and it *looks* like a toolbar — icon-plus-label cells in a bordered row, visually indistinguishable from the card action strip it explains, yet inert. Confirmed in the screenshot at both 390px and 1280px.
|
||||
- "USERSCRIPTS" renders as a bare mono label with no caret or affordance; that it is a `<details>` summary is invisible (`setup.html:8`, screenshot).
|
||||
- Five unlabelled icons per row explained by a legend using different words ("Delete" vs "Remove").
|
||||
- Cancel is nearly invisible beside a filled Remove (`style.css:764-778`).
|
||||
- "Archive this?" never says what archiving does; the copy that explains it ("it keeps getting checked for new chapters") only appears *after* he archives something (`card.html:112`, `list.html:16`).
|
||||
- Worst-case sign-in is an unstyled plaintext `internal error` (`discord.go:196,204`).
|
||||
|
||||
## Minor Observations
|
||||
|
||||
- `--faint-2 #57504b` monogram on `--hatch` ≈ 2.19:1 — decorative by declaration (`aria-hidden`), but it is the only identity a coverless series gets (`card.html:19`).
|
||||
- 2.7MB PNG on the login page (`static/login-art.png`, `login.html:20`) — the first bytes a phone on mobile data receives, on a one-button page.
|
||||
- Server error strings surface verbatim and capitalised to readers: "Missing key.", "Not found.", "Invalid status." (`filter.js:216-221` ← `web.go:446,456,513`).
|
||||
- Five verbs for three concepts: Delete / Remove / Un-finish / Shelve / Archive.
|
||||
- `.keyrow` is not conditioned on library: novels have no Updated tab but get the same five-key legend.
|
||||
- `readers.html:59` uses `<p class="empty">` where every other empty state is `<div class="empty"><strong>…</strong><p>…</p></div>`.
|
||||
- `series-detail.html:54` cancels via `document.querySelector('.dform .danger')` — page-global, unique only by luck.
|
||||
- Worth preserving: `prefers-reduced-motion` naming pseudo-elements because `*` does not match them (`style.css:1031-1035`); `hx-sync` on the self-refreshing Lanes fragment (`lanes.html:12`); `.ghost::after` hit-target expansion (`style.css:282`); the coarse-pointer block keyed to input method rather than viewport (`admin.css:983-1027`); the confirm row focusing *Cancel* on the irreversible action and the affirmative on the reversible one (`filter.js:106-114`).
|
||||
|
||||
## Questions to Consider
|
||||
|
||||
1. The action key exists because the icon strip cannot be read — so why is the strip still unlabelled? A permanent inert legend that looks like a toolbar costs more vertical space and more confusion than labelled cells or one overflow control would.
|
||||
2. PRODUCT.md says the owner's panel is "one list with one button, not an admin console." It is now four nav tabs, a paged table and a per-series detail page. Did the principle change, or did the surface grow while nobody held it to the principle?
|
||||
3. The ember law was enforced so literally on admin that "reachable" and "unreachable" now render identically. When a design law starts destroying the distinction the surface exists to make, is it still a law or a habit?
|
||||
4. Removal is irreversible, thumb-adjacent and silent to a screen reader, gated only by a confirm. Why is the confirm the whole safety story rather than an optimistic remove with a 10-second undo in the existing `#notice` slot? The confirm interrupts every removal; undo interrupts none and still catches the mistake.
|
||||
5. The strip disappears when nothing is new, and the list is already ordered by reading recency. If the strip only renders when Updated is also non-empty, is it 250px of duplicated answer — and should the first screen simply *be* the Updated bucket?
|
||||
@@ -1,130 +0,0 @@
|
||||
---
|
||||
target: backend/internal/web
|
||||
total_score: 26
|
||||
max_score: 40
|
||||
na_heuristics:
|
||||
p0_count: 0
|
||||
p1_count: 2
|
||||
timestamp: 2026-08-27T14-36-34Z
|
||||
slug: backend-internal-web
|
||||
---
|
||||
Method: dual-agent (A: AssessDesign-2 [designer] · B: AssessDetector [scout])
|
||||
|
||||
Note: Assessment A completed its analysis but hung in a yield loop after writing its report; recovered from its on-disk artifact and cancelled. Two of its claims failed parent verification and are corrected below.
|
||||
|
||||
## Design Health Score
|
||||
|
||||
Mode: **Operate** (all 10 heuristics apply; none n/a).
|
||||
|
||||
| # | Heuristic | Score | Key Issue |
|
||||
|---|-----------|-------|-----------|
|
||||
| 1 | Visibility of System Status | 3 | Busy hairline is grey, not ember (`style.css:865-877`), chrome refreshed out-of-band on every mutation (`web.go:397`) — but the horizontal Recent strip hides its own overflow (`style.css:471-476`) |
|
||||
| 2 | Match System / Real World | 3 | Reader copy is native ("Chapter you're on" `card.html:96`); admin leaks ops jargon — "Sighting … deferral blocked" `readers.html:10-12`, "Outcomes · status" `lanes.html:26` |
|
||||
| 3 | User Control and Freedom | 2 | Esc closes panels and returns focus (`filter.js:163-170`), Restore is one-tap undo (`card.html:75`) — but Remove and Archive have no post-action undo, only a pre-action gate |
|
||||
| 4 | Consistency and Standards | 3 | Action order play∣fav∣chapter∣lifecycle is invariant (`card.html:48-86`); admin is a second system — patina accent (`admin.css:10-14`) and `--measure-wide: 1080px` (`admin.css:2`) vs `--measure: 760px` (`style.css:124`) |
|
||||
| 5 | Error Prevention | 3 | `max=9999` + `step=any` (`card.html:99-102`), no-op chapter save skipped (`web.go:547-550`), every move out of the list confirm-gated (`card.html:111,123`); no inline validation on the chapter field |
|
||||
| 6 | Recognition Rather Than Recall | 3 | Permanent keyrow (`chrome.html:35-45`) decodes the icon strip — but it is hidden while filtering (`filter.js:22-24`), exactly when cards are being scanned |
|
||||
| 7 | Flexibility and Efficiency | 2 | Instant client-side filter (`filter.js:1-13`), bookmarkable tabs (`app.html:61`); no keyboard shortcut, no bulk archive, no swipe — curation is per-card taps |
|
||||
| 8 | Aesthetic and Minimalist Design | 3 | Hairlines not cards, single column, Instrument Serif titles (`style.css:590`); phone chrome stacks ~220px (search `style.css:347` + tabs + keyrow `style.css:420` + strip `style.css:453`) before the first card |
|
||||
| 9 | Error Recovery | 3 | Per-slot inline errors with verbatim server reason (`filter.js:200-224,260-263`), 401 → "Log in again" (`filter.js:273`), no self-destruct timer (`filter.js:241-245`); tab-switch failures land in the easy-to-miss global `#notice` (`style.css:830`) |
|
||||
| 10 | Help and Documentation | 1 | Help is only empty states (`list.html:20-26`, `setup.html:9-17`); a guild outsider gets one sentence (`login.html:28`) and an opaque refusal (`discord.go:185`) with no guild name and no next step |
|
||||
| **Total** | | **26/40** | **Competent, with one weak flank (help) and mobile ergonomics debt** |
|
||||
|
||||
## Design Specificity Verdict
|
||||
|
||||
**Authored for this product. Not category-interchangeable.**
|
||||
|
||||
**LLM assessment**: The visual language is a committed editorial position, not a framework default. Specific choices that no generic CRUD would carry: a single 760px hairline column with `border-bottom: 1px solid var(--rule)` instead of cards (`style.css:124,543`); the ember law enforced in code and in comments — "neither ember … may say 'system unhealthy'" (`style.css:236-241`), busy bar deliberately grey (`style.css:865`); heat expressed typographically (hot title `style.css:592`, 2px ember underline `style.css:525`, ember wash `style.css:548`) with no pulse or badge bounce; the hatch + monogram cover fallback (`style.css:121`, `card.html:18-19`) built for scraped covers that 404; manga and novels as two separate libraries with the Updated tab existing only for manga because only manga has a poller-fed "what's out" (`app.html:64-69`, `web.go:317`); the Recent strip capped at 5 and suppressed on Updated to avoid duplicating the list (`web.go:31,346`).
|
||||
|
||||
What a generic app would keep unchanged: the underline tab row (`style.css:374-403`), the client-side title filter (`filter.js:4-13`), the admin table with select filters and pagination (`series-list.html:9-33`), the single OAuth button (`login.html:22-26`). That is a fair split — the IA is generic, the surface is not.
|
||||
|
||||
The one real breach of the committed system is admin: `--measure-wide: 1080px` (`admin.css:2`) plus a patina accent buys horizontal sprawl (7-column lane grid, `admin.css:482`) that collapses back to stacked rows at 899px anyway (`admin.css:924`). Width did not save the tables; it created a second visual system to learn.
|
||||
|
||||
**Deterministic scan**: `detect.mjs --json backend/internal/web/templates` → **exit 0, zero findings** (`[]`), verified across three runs. Pipeline liveness confirmed against a control snippet, which correctly returned exit 2 with `overused-font`. The scan covers templates only — CSS lives outside the scan root, so `ai-color-palette`, `cream-palette` and line-length rules never ran. Mechanical sweep instead:
|
||||
|
||||
- **Zero** hardcoded colours outside the token blocks in either stylesheet. All 98 hex definitions sit in the dark `:root` (`style.css:55-122`) or the light branch (`style.css:138-191`). One non-token literal exists: `rgba(0,0,0,.5)` in a login-art drop-shadow (`style.css:946`). Every `#…` match in `admin.css` is an issue number in a comment.
|
||||
- **Ember/danger segregation holds.** 32 `--ember` lines and 26 `--danger` lines in `style.css`, no overlap; `admin.css` uses `--ember` zero times.
|
||||
- **0** `z-index`, **0** `position: fixed`, **2** `!important` (both justified: `[hidden]` override `style.css:217`, reduced-motion kill `style.css:1060`).
|
||||
- **0** injection sinks. `filter.js` writes through `textContent` only; no `template.HTML/JS/URL` anywhere in the package; the single raw write is escaped (`web.go:425`).
|
||||
- **Accessibility is authored, not audited in**: 36 real `<button>`s, **0** clickable `<div>`s, **0** hrefless `<a>`s, ~77 `aria-*` attributes, all 4 `<img>` intentionally `alt=""` beside a text name, **0** icon-only controls without an accessible name, 19 `:focus-visible` rules, `lang` + viewport + `color-scheme` on all three shells, one `prefers-reduced-motion` block.
|
||||
|
||||
Detector and review agree on the important thing: there are no mechanical anti-patterns here. Every finding below is a design judgment, not a lint.
|
||||
|
||||
**Visual overlays**: none. Browser visualization was skipped — the UI is only reachable through the Go/Docker stack, which was out of scope, so no local URL existed to point automation at. No overlay exists in your browser.
|
||||
|
||||
## Overall Impression
|
||||
|
||||
This is the rare self-hosted tool with an actual design system that the code obeys. Tokens are complete in both colour branches, the ember law is enforced in comments *and* in the busy-state colour choice, destruction is gated and coloured correctly, and the accessibility work is native rather than retrofitted. The problems are not taste problems — they are **mobile ergonomics and dead ends**.
|
||||
|
||||
Biggest single opportunity: **the phone.** Mobile is stated as a hard functional constraint, but two of the three horizontal-scroll surfaces (Recent strip, tab row) hide their scrollbars and offer no fade, snap, or peek, so their off-screen content is simply invisible; and ~220px of chrome loads above the first card. The product's answer to "what do I read next" is the strip — and on a 360px viewport its newest item can sit off-screen with no hint that it exists.
|
||||
|
||||
## What's Working
|
||||
|
||||
1. **The ember law is enforced where it is easiest to break.** The busy indicator is grey (`style.css:865-877`), not ember; error is `--danger`, not ember; the code comment states the rule (`style.css:236-241`) and the token contrast is annotated with a measured ratio ("verified 5.31:1 on `--ember-wash`", `style.css:73`). Design systems fail at exactly this junction. This one holds.
|
||||
2. **Out-of-band chrome truthfulness.** Every mutation re-renders the strip, keyrow and Updated count out-of-band (`web.go:397`, `chrome.html:10,35,75`) and rebroadcasts a refilter event (`filter.js:104`), so the badge can never describe the pre-tap library. The comment at `web.go:474-476` explicitly buys correctness with one extra read.
|
||||
3. **Confirm gates focus the safe button.** `filter.js:155-157` deliberately puts focus on Cancel, not Remove — "pre-armed Enter is the opposite of what a confirm gate is for." Paired with the danger wash and the title quoted into the prompt (`card.html:124`), destruction is weighted correctly.
|
||||
|
||||
## Priority Issues
|
||||
|
||||
### [P1] Both horizontal-scroll surfaces hide their own overflow
|
||||
- **Why it matters**: `.recent-strip` (`style.css:468-476`) and `.tabs` (`style.css:374-383`) both set `overflow-x: auto` with `scrollbar-width: none` and a killed webkit scrollbar, and neither has a fade mask, scroll-snap, or a deliberately half-peeked item. At 93px covers plus 14px gaps (`style.css:127,470`), four cards fill a 360-390px viewport and the fifth — the newest — is invisible. Same for the fourth tab and its count pill. The strip is the product's answer to "what next"; an affordance nobody discovers is a feature that does not exist.
|
||||
- **Fix**: Add `scroll-snap-type: x proximity` on `.recent-strip` with `scroll-snap-align: start` per `.recent-card`, plus a right-edge `mask-image` gradient on both `.recent` and `.tabs`. Alternatively size the strip padding so one card is always half-visible. No JS.
|
||||
- **Suggested command**: `/impeccable adapt`
|
||||
|
||||
### [P1] A guild outsider hits a dead end with no next step
|
||||
- **Why it matters**: The entire funnel is one page. `login.html:16,28` says "Private library" and "Guild membership is required"; a non-member's refusal is "not a member of this community" (`discord.go:185`) with no guild name, no invite path, no "ask a member." Heuristic 10 scores 1 almost entirely on this. It is also the only screen a stranger ever sees.
|
||||
- **Fix**: Add one help line under `login.html:28` naming the guild (deployment config, safe to display) and stating how to get in. Keep the existing distinction between a Discord outage and a membership refusal (`web.go:171` vs `185`) — that part is already right.
|
||||
- **Suggested command**: `/impeccable clarify`
|
||||
|
||||
### [P2] Removal ends in silence for sighted users
|
||||
- **Why it matters**: **Correction to Assessment A** — the screen-reader path is *not* missing: `web.go:592` already announces "Removed <title>" out-of-band and `refreshChrome` updates the counts. What is missing is the visual half. The card is swapped out to an empty body (`card.html:127`, `web.go:578-596`), focus hops to the next play link (`filter.js:82-88`), and nothing else happens. Peak-end: the peak is the danger confirm, the end is absence. Users hesitate to curate, and libraries bloat.
|
||||
- **Fix**: On delete success also write a transient `#notice` (`style.css:830`) carrying the same "Removed <title>" text. An Undo would need a re-create POST; the notice alone closes the loop for one line of Go.
|
||||
- **Suggested command**: `/impeccable polish`
|
||||
|
||||
### [P2] Archive is confirm-gated despite being one-tap reversible
|
||||
- **Why it matters**: Archive is the most common curation move and is undone by a single Restore tap (`card.html:75`), which itself fires instantly and without a gate. Its confirm row already wears the calm ash treatment (`style.css:806`) — the design admits the action is cheap while still charging two taps for it. Every gate spent on a cheap action devalues the gate on Remove.
|
||||
- **Fix**: This one is a product decision, not a defect: the AGENTS.md law says every move out of the list is confirm-gated. If you want to relax it, the honest form is instant archive plus a persistent "Archived — Undo" notice, and the law should be amended in the same change. If you keep the law, keep the gate.
|
||||
- **Suggested command**: `/impeccable shape`
|
||||
|
||||
### [P2] Adjacent lifecycle cells differ only by hue at rest
|
||||
- **Why it matters**: **Partial correction to Assessment A** — the mis-tap claim was overstated. Each action is a full-cell `<button>` (`style.css:674-680`, `card.html:53-86`), so the target is 68×46, not the 17px glyph; the lifecycle cluster already sits recessed on `--ash` with an inset hairline before it (`style.css:724-726`). What remains real: Archive and Remove are neighbours in that cluster, and at rest they are separated only by `--slate` mute vs `--trash` (`style.css:684,708`) — the slate/danger wash distinction appears on hover, which a phone does not have. A slip lands on the destructive gate.
|
||||
- **Fix**: Give `.actions .remove` a resting treatment that reads without hover — a left hairline in `--danger-soft`, or move Remove to the far edge with a wider divider. Do not add a gap; the recessed ground is doing that job already.
|
||||
- **Suggested command**: `/impeccable polish`
|
||||
|
||||
## Persona Red Flags
|
||||
|
||||
**Midnight phone reader (primary persona: 2am, Bromite, one thumb, dimmed OLED)**
|
||||
- The `.is-new` wash is `#1c0f0d` on an `#100f0e` page (`style.css:74,55`) — roughly 5% brighter. At low screen brightness the wash effectively disappears, leaving `--paper-hot` title colour (`style.css:64`) as the sole "new" signal. The ember foot-rule and 1px cover outline (`style.css:519,551`) survive better; the wash is the weakest link in the product's most important state.
|
||||
- Two competing continue affordances: the cover link (`card.html:7`, `aria-hidden`) and the play cell (`card.html:49`). The cover is the bigger, more obvious target and carries no focus ring; the play cell is the labelled one.
|
||||
- The chapter override field opens the Android numeric keypad over the "Latest known" hint it is meant to be compared against (`card.html:99-106`), and its focus ring is paper-white (`style.css:760`) — a bright flash in a dark room, against the stated no-glare requirement.
|
||||
|
||||
**First-time guild member (invited, app is new, library empty)**
|
||||
- `setup.html:7` is a `<details>` closed by default, so on a first run the install CTAs are hidden behind a tap on a surface the user has no reason to trust yet. The rich empty state (`list.html:17-27`) only fires when *both* libraries are empty; otherwise they get the terse line at `list.html:29`.
|
||||
- The library switch (`app.html:30-34`) defaults to manga with no explanation that Novels is a separate library. A first novel bookmark lands in a tab they are not looking at, which reads as "the save failed."
|
||||
- Getting to a first bookmark requires: notice the panel → open it → choose install vs download → complete the mobile Violentmonkey save flow, which is documented in exactly one paragraph (`setup.html:15-17`).
|
||||
|
||||
**Owner triaging from a phone (secondary but real — the owner is also a night reader)**
|
||||
- Lanes is a 7-column grid (`admin.css:482`) that collapses by hiding the header and printing `data-label::before` pseudo-labels (`admin.css:915,985`). It works, but a phone row becomes four logical lines with three numeric cells, each needing its label read.
|
||||
- The pause control (`lanes.html:44-55`) puts a select plus button inline at row end; at 360px it wraps and renders at 10px mono (`admin.css:317`).
|
||||
- `admin.css` has no `prefers-color-scheme` block of its own and no reduced-motion block; both are inherited via `style.css` tokens and its global `*` rule. That works today and breaks silently the day admin is loaded without `style.css`.
|
||||
|
||||
## Minor Observations
|
||||
|
||||
- Dark and light branches are genuinely co-maintained — the light branch retunes ember to `#c23a22` (`style.css:154`) rather than inverting it, and there is no pure-white page surface (`#f7f4ef` light / `#100f0e` dark). The only `#fff` is `--ember-ink` on the solid ember button (`style.css:156`), which is isolated.
|
||||
- `.ghost::after { inset: -15px -12px }` (`style.css:295`) reaching 44px without shifting layout is the most mobile-aware line in the codebase. The action cells deserve the same care.
|
||||
- `zoom: 1.2` above 1280px (`style.css:980`) preserves hairline proportions where a font-size scale would not; the `--zoom` token (`style.css:131`) handles the viewport-unit consequence. Unusual, correct, well commented.
|
||||
- The reduced-motion block explicitly kills `::before` animations because `*` misses pseudo-elements (`style.css:1056-1060`). Rare and right.
|
||||
- `.tabs a:hover` is the only `border-radius` in the reader sheet (`style.css:397`). Tabs are not cards; leave it.
|
||||
- Credential rotation uses a native blocking `hx-confirm` (`setup.html:29`) while every other destructive action uses the custom confirm row. Defensible (rotation is rarer and more severe) but it is a third confirmation vocabulary.
|
||||
- The Recent strip is hidden by JS while a filter is active (`filter.js:22-24`) — correct, since it would show non-matching series. Side effect: the keyrow is the only chrome left, and per-card icon meaning falls back on the keyrow at exactly the moment the user is scanning cards.
|
||||
- `login.html:10` preloads the serif but not DM Sans, unlike `app.html:16,19` — minor FOIT on the first paint a new user ever sees.
|
||||
- `color-mix(in oklch, …)` (`style.css:515,549,863`) degrades to transparent rather than breaking. Fine on Chromium/Bromite.
|
||||
- `.is-dim` archived cards get `grayscale(1) opacity(.85)` (`style.css:546,568`), which also flattens the hatch fallback on missing covers. Intentional, but archived + no cover is close to unreadable.
|
||||
|
||||
## Questions to Consider
|
||||
|
||||
1. **If the action strip is right, why does the keyrow exist?** The keyrow (`chrome.html:35`) is a permanent legend for an icon set that cannot be read. Label the cells directly on phone — the keyrow already knows how to stack icon over word (`style.css:430`) — and you delete the keyrow and reclaim ~28px of feed.
|
||||
2. **Who is the Updated tab for, if the strip already answers that question?** Updated (`app.html:65`) and the Recent strip (`chrome.html:9`, `web.go:346`) render the same `HasNewChapter` predicate — one as a list, one as covers. Pick one and give the phone back ~90px.
|
||||
3. **Does brass favourite compete with ember new?** `--brass #b8912f` (`style.css:83`) and `--ember #e85a41` (`style.css:73`) are both warm. Night readers scan for ember; a gold fav-mark plus brass foot-rule (`card.html:27`, `style.css:527`) puts a second warm accent in the same scan. Would a cool metal separate reward from heat?
|
||||
4. **If the single measured column is law, why does admin get 1080px?** The tables collapse at 899px anyway (`admin.css:924`), so the extra 320px bought sprawl, not capability. What would admin look like inside `--measure` with row drill-downs instead of 7-column grids?
|
||||
5. **A new chapter arriving while the page is open is invisible.** The poller updates the database; only admin Lanes auto-refreshes (`lanes.html:13`). A reader must switch tabs to learn anything changed. Is a 60s `hx-trigger` poll on the chrome fragment worth the requests, given the product's whole value proposition is "you find out without visiting the site"?
|
||||
-116
@@ -1,116 +0,0 @@
|
||||
---
|
||||
target: Reader library web surface (app.html)
|
||||
total_score: 32
|
||||
max_score: 40
|
||||
na_heuristics:
|
||||
p0_count: 0
|
||||
p1_count: 2
|
||||
timestamp: 2026-08-27T15-38-17Z
|
||||
slug: backend-internal-web-templates-app-html
|
||||
---
|
||||
Method: dual-agent (A: CritiqueDesignReview · B: CritiqueDetectorEvidence)
|
||||
|
||||
Target: the Reader library surface — `backend/internal/web/templates/{app,chrome,list,card,setup,icons}.html`, `static/style.css`, `static/filter.js`. Mode: **Operate**.
|
||||
|
||||
## Design Health Score
|
||||
|
||||
| # | Heuristic | Score | Key Issue |
|
||||
|---|-----------|-------|-----------|
|
||||
| 1 | Visibility of System Status | 3 | `card.htmx-request::before` (style.css:880-889) animates a silent bar for up to the full 15s htmx timeout (app.html:12) with no "saving" text and no `aria-busy`. |
|
||||
| 2 | Match System / Real World | 4 | Solid. Copy is situational, not generic: "Chapter you're on" vs "Latest known" (card.html:96-106); four distinct empty states (list.html:11-29). |
|
||||
| 3 | User Control and Freedom | 3 | Confirm+Cancel and Esc-to-close cover accidental opens (filter.js:152-200); a committed Remove has no undo. |
|
||||
| 4 | Consistency and Standards | 3 | `:focus-visible` rings are defined for every `.actions` cell, the chapter input and confirm buttons (style.css:703-826) but for **no** navigation control — `.tabs a`, `.libswitch a`, `.ghost`, `.login-card button`, `.empty .clear-search` fall back to the UA ring. |
|
||||
| 5 | Error Prevention | 4 | `step="any"` chapter guard, confirm-gate on every move-out-of-list, `hx-disabled-elt` on every mutating control, Cancel focused on Remove (filter.js:159-164). |
|
||||
| 6 | Recognition Rather Than Recall | 3 | The `.keyrow` legend (chrome.html:34-46) exists precisely because the 5-icon strip is unlabelled — and it scrolls away, at 10px, in exactly the long-list case it was built for. |
|
||||
| 7 | Flexibility and Efficiency | 2 | No bulk actions, no sort, no shortcut beyond Esc. A 300-series library is triaged one card, two taps at a time. |
|
||||
| 8 | Aesthetic and Minimalist Design | 3 | Hairline-only, one-measure, disciplined — but the minimalism is paid for in legibility: 9 distinct functional labels compute to **10px** at 390px (Assessment B), below any UI-text floor. |
|
||||
| 9 | Error Recovery | 4 | `reasonFrom()` surfaces the server's literal 400 text (filter.js:270-292); distinct 401/400/network/timeout copy; auto-`scrollIntoView` to the message. |
|
||||
| 10 | Help and Documentation | 3 | In-context `<details class="setup">` covers install and rotation; nothing in the library view explains what dim/italic, ember, or brass mean without first finding the keyrow. |
|
||||
| **Total** | | **32/40** | **Good — solid foundation, weak areas are specific and cheap** |
|
||||
|
||||
## Design Specificity Verdict
|
||||
|
||||
**Authored, not assembled.** This could not ship unchanged on another product, and that is rare.
|
||||
|
||||
**LLM assessment (Assessment A, unanchored):** the specificity is load-bearing, not decorative. `--ember` is a contract, not an accent — every "new chapter" surface shares that one token (`.is-new .title` 604-610, `.tabs .tab-new` 409-412, `.foot-rule` 529-536, `.libswitch a.active` 663-667) and destruction is deliberately split onto a duller `--danger` family so a remove-confirm is never mistaken across the room for an unread chapter (style.css:77-83). The `:root` block carries per-pair contrast measurements, and the light branch **re-derives** every hue instead of reusing dark values (137-195) — evidence the "both branches touched together" law is honoured, not asserted. Three purpose-chosen faces, self-hosted because Bromite blocks `fonts.googleapis.com` (style.css:1-5). One `--measure: 760px` column, no cards, no shadows, and in 1075 lines exactly one stray corner (`.tabs a:hover` 2px radius, line 402). The gaps are not taste failures; they are unfinished passes — sticky positioning, focus rings on nav, and a legibility floor.
|
||||
|
||||
**Deterministic scan:** `detect.mjs --json backend/internal/web/templates` → **0 findings, exit 0**, and Assessment B validated that zero three ways (synthetic bad HTML fired 2 rules; `--no-config` reproduced the zero; no `config.json` exists). Note the scan's blind spot: the detector did **not** resolve the linked `/static/style.css`, so a clean markup scan says nothing about the tokens. The runtime pass is where everything was found.
|
||||
|
||||
**Visual overlays:** injection **succeeded** — but against a standalone render, not the live app. Assessment B found `web.go:125` parses templates with a plain `template.ParseFS` and no FuncMap, so it rendered the repo's real templates + real CSS from a throwaway program in `/tmp/bmrender`, served it, and injected `detect.js`. Overlay confirmed present; screenshots at `/tmp/bmrender/shots/` (390×844 light, dark, dark+overlay). **20 runtime findings, none of which the static scan could see:** `undersized-ui-text` ×18, `wide-tracking` ×1, `overused-font` ×1. Every card action measured **66.8 × 46 px** — clears 44px on both axes. No horizontal overflow at 390px (an earlier 499px reading was the overlay's own label boxes). Both servers stopped, no Docker started, no repo file changed.
|
||||
|
||||
False positives I accept from B: 9 of the 18 `undersized-ui-text` hits are the same `.hint` rule counted once per row inside `hidden` chapter forms — one defect, not nine. `overused-font` on Instrument Serif is the rule's share-of-text heuristic misreporting a deliberate display serif. `wide-tracking` anchors to the mono meta line, not body copy. **The remaining 9 are real and unanimous with A's typography read:** `Manga`, `Novels`, `Userscripts`, `Read`, `Fav`, `Chapter`, `Archive`, `Delete`, `Continue reading` all render at 10px.
|
||||
|
||||
## Overall Impression
|
||||
|
||||
This is the best-argued small codebase I have critiqued in a while — the CSS comments read like design review notes, and the taste is consistent. What works is the discipline: one heat signal, one column, hairlines, situational copy, and a confirm model that distinguishes reversible from final and even routes focus differently for each.
|
||||
|
||||
What does not work is that the design's own mitigations are undermined by two omissions it never got around to. The card strip needs the legend to be readable; the legend is 10px and scrolls away. The tab row is the primary navigation; it is the one row with no focus ring. Both are 20-line fixes.
|
||||
|
||||
**Single biggest opportunity: make the chrome persistent and lift the 10px floor.** Those two changes convert a well-reasoned desktop-shaped design into one that actually works one-handed at night on a phone — which PRODUCT.md says is the entire point.
|
||||
|
||||
## What's Working
|
||||
|
||||
1. **Ember law is real.** One reserved token for "unread chapter", nothing else borrows it, destruction gets its own duller family. This is why a dense icon-heavy list stays scannable to a tired reader: any warm colour means *something to read*. Most design systems claim this; this one enforces it in a comment and then actually holds the line for 1075 lines.
|
||||
2. **Confirm-row focus routing.** `toggleConfirmRow` focuses the affirmative button for the reversible action (Archive) and **Cancel** for the irreversible one (Remove) — filter.js:159-164, paired with `.confirm-row.calm` grey vs the danger wash (style.css:786-826). A one-line detail that measurably lowers accidental destruction. Nobody notices this; everybody benefits from it.
|
||||
3. **State coverage is exhaustive and honest.** Four distinct empty states by real cause, verbatim server 400 text surfaced inline instead of "something went wrong", a chapter form that disambiguates your progress from the published latest, and a cover slot with hatch + monogram + `onerror="this.remove()"` covering both "never acquired" and "404s after storage" (card.html:9-19). Verified in B's render: the broken-cover row hit `ERR_NAME_NOT_RESOLVED` and the monogram fallback executed.
|
||||
|
||||
## Priority Issues
|
||||
|
||||
**[P1] Nothing is sticky, on a mobile-first surface built for hundreds of series**
|
||||
- **Why it matters:** `position: sticky` appears **nowhere** in style.css (verified). Casey, one-handed, three screens into a 300-item library, must scroll to the top to switch tabs, search, or re-read the icon legend — the exact moment search and legend earn their existence. This also silently defeats the keyrow, which is the whole mitigation for the unlabelled 5-icon strip.
|
||||
- **Fix:** `.chrome` (searchbar + tabs) → `position: sticky; top: 0; background: var(--ink);` with `padding-top: env(safe-area-inset-top)` and a `z-index` above cards; keep `.recent`/`.keyrow` non-sticky if header height is tight, or sticky the keyrow instead and accept a shorter tab row.
|
||||
- **Suggested command:** `/impeccable adapt`
|
||||
|
||||
**[P1] Navigation controls have no `:focus-visible`; nine functional labels render at 10px**
|
||||
- **Why it matters:** two separate legibility/a11y regressions in the same layer. (a) Every `.actions` cell, the chapter input and confirm buttons define 2px token-coloured rings (style.css:703-826); `.tabs a`, `.libswitch a`, `.ghost`, `.login-card button` and `.empty .clear-search` define none, so keyboard focus on the primary navigation falls back to a UA ring — likely bright blue, against a palette explicitly tuned for low glare. `.search` goes further and zeroes its outline (372), delegating to a 1px `border-bottom-color` change — materially weaker than every other control in the file. (b) B measured 10px computed on `.libswitch a`, `.keyrow .pair span`, `.recent h2`, `.setup summary`, `.hint`. 10px mono, at night, on a phone, is not a minimalism choice a night-reading brief supports.
|
||||
- **Fix:** add `:focus-visible { outline: 2px solid var(--paper); outline-offset: 2px; }` to the four nav selectors, matching the established pattern; give `.search` a real ring instead of the hairline delegation. Raise the 10px steps to 11-12px (the `min-width: 720px` block already does exactly this for `.keyrow .pair span` at line 1024 — the mobile branch is the one that needs it more, not less).
|
||||
- **Suggested command:** `/impeccable audit` then `/impeccable typeset`
|
||||
|
||||
**[P2] Five icon-only actions per card, at rest, in both list states**
|
||||
- **Why it matters:** `.actions` renders Play, Fav, Chapter, Archive/Restore, Remove (card.html:48-87) — one over the ≤4 working-memory ceiling, on every card. At rest all five are `var(--mute)` grey; per-action colour is a *response* to interaction, not a resting cue. The design already knows this, which is why the keyrow exists — and the keyrow is 10px and scrolls away (P1). Fix P1 and this drops to P3; leave P1 and this is five monochrome glyphs versus a distracted thumb.
|
||||
- **Fix:** either resolve via P1 (sticky + legible legend) and keep five, or move Chapter-override behind the same disclosure affordance as Archive/Remove so the resting strip is Play, Fav, Archive, Remove.
|
||||
- **Suggested command:** `/impeccable layout`
|
||||
|
||||
**[P2] Up to 15 seconds of silent busy state**
|
||||
- **Why it matters:** `.card.htmx-request::before` animates a bar; there is no interim text, no `aria-busy`, and no live-region message until the outcome lands. app.html:8-12 documents the 15s cap and its own reasoning is "a phone that walks into a dead zone" — so the slow path is anticipated, and it is the one path with no feedback. To a distracted user this reads as "did my tap register?" for an uncomfortably long stretch; to a screen reader user there is literally nothing between the tap and the result.
|
||||
- **Fix:** after ~2s of `htmx-request`, reveal a "Saving…" line in the card's existing `.error-inline` slot (or a sibling) and set `aria-busy="true"` on the article.
|
||||
- **Suggested command:** `/impeccable harden`
|
||||
|
||||
**[P3] Long titles clamp in the strip but not in the list**
|
||||
- **Why it matters:** `.recent-title` clamps to 2 lines (style.css:512-517); `.title` gets only `overflow-wrap: anywhere` (592-601) despite the adjacent comment documenting a real 90-character scraped title. Horizontal overflow is defended; a card growing four lines tall and breaking the list's rhythm is not. Titles are scraped `og:title` — the length is not under your control.
|
||||
- **Fix:** apply the same `-webkit-line-clamp: 2` to `.title`, or decide the list shows titles in full and say why the two components diverge.
|
||||
- **Suggested command:** `/impeccable polish`
|
||||
|
||||
## Persona Red Flags
|
||||
|
||||
**Casey (distracted, one-handed, mobile — the stated primary user)**
|
||||
- No sticky chrome: every tab switch or search after scrolling is a full reach to the top of the viewport.
|
||||
- 10px `Manga`/`Novels` library switch and 10px keyrow labels — the two things you glance at, set at the smallest size on the page.
|
||||
- Five same-weight grey glyphs per card demand deliberate recognition, not a colour-coded glance.
|
||||
- *Working:* `.actions { flex: 1 0 100% }` puts the strip full-width at the bottom of each card's content — correct thumb zone. Every cell measured 66.8 × 46 px.
|
||||
|
||||
**Sam (screen reader / keyboard / low vision)**
|
||||
- `.tabs a` and `.libswitch a` have no custom focus ring; `.search:focus-visible { outline: none }` delegates to a 1px hairline recolour on the one control most in need of being findable.
|
||||
- No `aria-busy`/live cue during the in-flight window — announcements exist before nothing and after everything.
|
||||
- *Working, despite appearances:* cover `alt=""` + `aria-hidden` monogram is correctly decorative because the sibling `<h3 class="title">` carries the name; every icon button has both `aria-label` and `title`; mutations announce through `#sr-announce`.
|
||||
|
||||
**Riley (edge-case stress tester)**
|
||||
- Chapter `max="9999"` is a client-only cosmetic guard — server validation (`web.go:564-569`) rejects negative/NaN/Inf but no upper bound, so a direct POST stores an arbitrary magnitude.
|
||||
- `closeCardPanels` (filter.js:118-128) enforces one open panel *per card*, not per page: a confirm-remove can sit open on card 3 while a chapter form is open on card 40.
|
||||
- 300 series: no pagination, no virtualization, no bulk action, no sticky nav — sequential two-tap cleanup only.
|
||||
- *Working:* 0-series is handled with four distinct states including a true first-run with install links; missing covers are handled from both directions.
|
||||
|
||||
## Minor Observations
|
||||
|
||||
- `.keyrow .full { display: inline; }` (style.css:1025) targets a `.full` class that exists nowhere in `chrome.html` — dead rule, delete it.
|
||||
- `.tabs a:hover { border-radius: 2px 2px 0 0; }` (402) is the only corner rounding in the sheet, an unexplained exception to the stated no-corners law.
|
||||
- `.libswitch a` under `@media (pointer: coarse)` computes ~42px tall (1066-1068) against the file's own claim at 1061-1063 that "every control is already 44".
|
||||
- Restore fires instantly while Archive is confirm-gated — defensible as "reversible needs no confirm", but Restore *is* the reversal of Archive, so the asymmetry deserves a sentence in the CSS comment where the rule is stated.
|
||||
- The detector cannot see `style.css` through a `<link href="/static/...">`. Any future detector run on this repo must target rendered HTML in a browser, not the templates directory, or it will report clean and mean nothing.
|
||||
|
||||
## Questions to Consider
|
||||
|
||||
1. If a permanent legend is required to make the card strip legible, is 5 icon-only actions the right density for a phone — or is Chapter-override one disclosure away from a 4-icon strip that needs no legend?
|
||||
2. Why does neither the tab row nor the search box stay reachable once a Reader is three screens into the library the Updated badge exists to triage?
|
||||
3. Ember means "new chapter" everywhere except the wordmark and the login screen (style.css:238-241). Is a law with a carved-out exception still a law, or does the brand need its own accent instead of borrowing the one reserved signal?
|
||||
4. The 10px steps read as confidence — restraint pushed to its limit. On a surface whose brief names night reading and glare as an explicit personal requirement, is that restraint or is it the one place taste overrode the brief?
|
||||
@@ -24,35 +24,34 @@ Your branch is already checked out there. Never `git checkout`, `git switch`,
|
||||
|
||||
## Order of work
|
||||
|
||||
1. Read the brief file. It is the only statement of requirements you get — use
|
||||
its exact values verbatim, and read nothing from the tracker. The
|
||||
orchestrator has already read the ticket, its comments and its parent spec,
|
||||
and folded every live decision into the brief; the threads themselves also
|
||||
hold reversed and rejected ones you cannot tell apart from here.
|
||||
2. Read `AGENTS.md` in the worktree, plus the nested `AGENTS.md` for the area
|
||||
1. Read the brief file. It is the single source of requirements — use its exact
|
||||
values verbatim.
|
||||
2. Read the ticket and the issue it refers to, as the brief's **Read first**
|
||||
section names them: `tea issue <n> --comments` for each. The ticket's
|
||||
comments and its parent carry the intent and the decisions behind the brief.
|
||||
Read no other ticket and no other brief.
|
||||
3. Read `AGENTS.md` in the worktree, plus the nested `AGENTS.md` for the area
|
||||
you touch. Its invariants bind you: security rules, design system, comment
|
||||
policy.
|
||||
3. Ask before writing code if requirements, acceptance criteria, approach, or
|
||||
4. Ask before writing code if requirements, acceptance criteria, approach, or
|
||||
dependencies are unclear. Asking is free; guessing is not.
|
||||
4. Implement exactly what the brief specifies. At each TDD seam the brief names,
|
||||
5. Implement exactly what the brief specifies. At each TDD seam the brief names,
|
||||
run the `tdd` skill and follow its red → green loop.
|
||||
Follow the patterns already in the codebase; improve what you touch,
|
||||
restructure nothing outside the ticket.
|
||||
5. Verify. Focused tests while iterating, the brief's full verification commands
|
||||
6. Verify. Focused tests while iterating, the brief's full verification commands
|
||||
once at the end. Test output must be pristine.
|
||||
6. Commit to your branch. Reference the ticket number in the subject.
|
||||
7. Review (below), fix, re-verify, commit the fixes.
|
||||
8. Write the report file, then return the status contract.
|
||||
7. Commit to your branch. Reference the ticket number in the subject.
|
||||
8. Review (below), fix, re-verify, commit the fixes.
|
||||
9. Write the report file, then return the status contract.
|
||||
|
||||
## Review
|
||||
|
||||
After your first green commit, run the **`code-review`** skill over
|
||||
`<base ref>...HEAD` in the worktree, with two changes to how it dispatches:
|
||||
use the **`cr-spec`** agent for the Spec axis and **`cr-standards`** for the
|
||||
Standards axis, both in one batch, and hand the Spec axis your brief file as the
|
||||
spec plus the ticket number from the brief's title, telling it to read the
|
||||
ticket itself (`tea issue <n> --comments`). The tracker check belongs in that
|
||||
read-only context, not in yours.
|
||||
Standards axis, both in one batch, and give the Spec axis your brief file plus
|
||||
the ticket body as the spec.
|
||||
|
||||
Fix every Critical and Important finding, then re-run the tests that cover the
|
||||
amended code. Two fix rounds maximum: anything still open after that goes in the
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
task:
|
||||
agentModelOverrides:
|
||||
scout: "anthropic/claude-sonnet-5-5:low"
|
||||
task: "opencode-go/deepseek-v4.1-flash:high"
|
||||
sonic: "anthropic/claude-sonnet-5-5:low"
|
||||
web-performance-auditor: "anthropic/claude-sonnet-5-5:low"
|
||||
test-engineer: "opencode-go/deepseek-v4.1-flash:max"
|
||||
security-auditor: "openai-codex/gpt-6.2-sol:medium"
|
||||
code-reviewer: "opencode-go/deepseek-v4.1-flash:max"
|
||||
@@ -50,15 +50,6 @@ Backend (`cd backend`):
|
||||
|
||||
Local stack: `docker compose up` (bookmark-api + postgres only; `postgres-data` named volume, `restart: unless-stopped`). No browser — without `BROWSER_WS_URL` the poller logs and skips kagane and comix. To run one: `cd chrome && BROWSER_BIND_ADDR=172.17.0.1 docker compose up -d --build`, then `BROWSER_WS_URL=ws://172.17.0.1:9222` in the root `.env` (bridge gateway, so the API container can name it by IP).
|
||||
|
||||
**Clean up Docker after testing.** Storage on the dev machine is scarce, so
|
||||
anything you started for a test you also tear down before calling the work
|
||||
done: `docker compose down -v` for a stack you brought up, `docker rm -f -v`
|
||||
for a container you ran by hand (`-v`, or the image's anonymous data volume
|
||||
survives). Then check `docker volume ls` and `docker system df` for leftovers
|
||||
and reclaim them — a dangling volume nobody notices is the leak that fills the
|
||||
disk. Never remove the `postgres-data` volume of a stack the user is actually
|
||||
running, and never blanket-`docker system prune` their images or build cache.
|
||||
|
||||
Live CDP proof (needs that browser and network, skipped otherwise):
|
||||
`SMOKE_BROWSER_WS_URL=ws://<ip>:<port> go test -run 'TestSmokeKagane|TestSmokeComix' ./internal/latest`
|
||||
— fetches a real kagane and comix cover and chapter list. A red run means the challenge is
|
||||
@@ -108,7 +99,7 @@ Go backend:
|
||||
|
||||
- SQL always parameterized (`$N`). Only compile-time constants (`bookmarkColumns`) may be concatenated into query text — never a request value, not even a validated one.
|
||||
- `html/template` only for anything a browser parses, never `text/template`. Never wrap stored or fetched strings in `template.HTML`/`JS`/`URL`; that switches off the escaping every template depends on.
|
||||
- Any outbound fetch of a client-supplied URL passes `FetchableSeriesURL` (site + `https` + host check) first. `series_url` arrives in a PUT body, so without the gate the poller will probe arbitrary hosts from the server's own network position. New fetch path reuses the gate rather than re-deriving one.
|
||||
- Any outbound fetch of a client-supplied URL passes `fetchableSeriesURL` (site + `https` + host check) first. `series_url` arrives in a PUT body, so without the gate the poller will probe arbitrary hosts from the server's own network position. New fetch path reuses the gate rather than re-deriving one.
|
||||
- Cap every remote body with `io.LimitReader` (`maxBodyBytes`). An unbounded read is an OOM handed to whatever is on the other end.
|
||||
- Compare secrets with `hmac.Equal` / `subtle.ConstantTimeCompare`, never `==`. A credential is matched by the SHA-256 the `readers` table holds, which is already a fixed-width equality — a new secret comparison must not regress to `==`.
|
||||
- Errors: generic text to the client (`http.Error(w, "internal error", 500)`), detail to `log.Printf`. Never log `TOKEN_KEY`, a Reader's credential, `DISCORD_CLIENT_SECRET`, a session id, or a whole `Authorization` header.
|
||||
|
||||
+3
-31
@@ -95,7 +95,7 @@ _Avoid_: run, cycle, tick, batch, poll history
|
||||
**Forced Poll**:
|
||||
A Poll the owner asks for by hand instead of waiting for the Series's turn. It jumps its
|
||||
Lane's queue and ignores every waiting rule — the rest between Polls, a Sighting standing
|
||||
in for a check, a finished Series — but never overrules a Site that is
|
||||
in for a check, a Series only finished Readers hold — but never overrules a Site that is
|
||||
refusing us, the Lane's spacing between fetches, or a Series with no page to fetch. Asked
|
||||
for by marking the Series, never by commanding the poller, so it happens on the Lane's
|
||||
next pass rather than at the moment of asking.
|
||||
@@ -110,14 +110,6 @@ reached. Every pause carries an expiry — a Lane cannot be stopped indefinitely
|
||||
outlives a restart, being a fact about the Site rather than about the running process.
|
||||
_Avoid_: disabled, off, stopped, suspended, kill switch (that is the deploy-time switch)
|
||||
|
||||
**Stall**:
|
||||
A Poll Lane that owed Polls, made none, and has nothing to say for it. Distinct from the
|
||||
two conditions it resembles: a Site that refuses is exercising the pace it is entitled to,
|
||||
and a Lane the owner paused was told to stop — a Stall is neither asked for nor explained.
|
||||
It is the one fault no Reader surface can show: every Bookmark still opens, Progress still
|
||||
syncs, and Latest Chapter is quietly wrong for as long as it lasts.
|
||||
_Avoid_: outage, downtime, failure, backlog, lag
|
||||
|
||||
**Sighting**:
|
||||
What a Reader's browser happened to see of a Series's Latest Chapter while that Reader
|
||||
was on the page. It reports the same fact as a Poll but carries none of its authority:
|
||||
@@ -135,36 +127,16 @@ facts, which no Poll does unless the owner forces one. It happens once in a Seri
|
||||
life; every later read of the same page is a Poll.
|
||||
_Avoid_: initial poll, first fetch, prefetch, warm-up
|
||||
|
||||
**Correction**:
|
||||
A Latest Chapter the owner sets by hand, on a Series no Poll can read. It reports the
|
||||
same fact as a Poll and carries even less authority than a Sighting: the next Poll
|
||||
overwrites it, so does any Reader's Sighting, and it is never a floor or a pin. It
|
||||
exists only because the Site page is unreadable — where a Poll can read the page, the
|
||||
Poll is the answer and a Correction is not wanted.
|
||||
_Avoid_: override, pin, manual value, fix
|
||||
|
||||
**New Chapter**:
|
||||
The state where Latest Chapter is ahead of Progress. The single condition the ember
|
||||
accent is permitted to signal.
|
||||
_Avoid_: unread, update available
|
||||
|
||||
**Lifecycle bucket**:
|
||||
Which of the two states a Bookmark sits in — reading or archived. A Bookmark is in exactly
|
||||
one. Orthogonal to being a favourite. Finished is not a bucket: it is a fact about the
|
||||
Series (see `series.finished_at`), owned by the owner and stamped once, and every Bookmark
|
||||
on a finished Series is archived.
|
||||
Which of three mutually exclusive states a Bookmark sits in — reading, archived, or
|
||||
finished. A Bookmark is in exactly one. Orthogonal to being a favourite.
|
||||
_Avoid_: state, status (as a domain word), list
|
||||
|
||||
**Finished Series**:
|
||||
A Series the owner has marked finished, stamped once in `series.finished_at`
|
||||
(epoch ms, zero means not finished). The owner is its only writer — no
|
||||
adapter, no Reader, no Poll can set it — and a Forced Poll reads a finished
|
||||
Series once for that pass and never clears the flag. It is a fact about the
|
||||
Series, not a Bookmark bucket: every Bookmark on a finished Series is
|
||||
archived, the Lane stops polling it (the due gate reads `finished_at = 0`),
|
||||
and Readers see a label and nothing more.
|
||||
_Avoid_: completed, done, dropped, shelved (that is Archived), ended
|
||||
|
||||
**Favourite**:
|
||||
A reader's manual pin on a Bookmark. Orthogonal to the Lifecycle bucket, and never a
|
||||
reason to reorder the list.
|
||||
|
||||
@@ -136,9 +136,6 @@ gated by membership in one configured guild.
|
||||
DISCORD_REDIRECT_URI=https://bookmark.violetcrown.my.id/auth/discord/callback
|
||||
# Optional: only members holding this role may sign in.
|
||||
# DISCORD_REQUIRED_ROLE=<role snowflake>
|
||||
# Optional: display name for that guild — shown on the login screen so a
|
||||
# stranger knows which Discord to ask for an invite.
|
||||
# DISCORD_GUILD_NAME=Your Guild Name
|
||||
```
|
||||
|
||||
The guild id is in Discord's client with Developer Mode on: right-click the
|
||||
|
||||
+5
-5
@@ -8,7 +8,7 @@ web
|
||||
|
||||
## Users
|
||||
|
||||
Members of one private Discord guild, each with their own library. Accounts exist and are created by signing in — there is no signup form, no invite code and no approval step: any member of the configured guild becomes a Reader on their first Discord login. The person running the deployment is the owner, seeded at startup, and the only Reader with an administrative capability (`/admin` — Overview, Lanes, Readers, Series).
|
||||
Members of one private Discord guild, each with their own library. Accounts exist and are created by signing in — there is no signup form, no invite code and no approval step: any member of the configured guild becomes a Reader on their first Discord login. The person running the deployment is the owner, seeded at startup, and the only Reader with an administrative capability (revoking another Reader's sessions).
|
||||
|
||||
Reading happens on **asurascans.com**, **demonicscans.org**, **comix.to** and **kagane.to** for manga and **novelfull.com** and **lightnovelworld.net** for novels, primarily via Bromite on mobile, with checks and corrections from a desktop browser. The web UI is the cross-device view into progress the userscripts capture while reading.
|
||||
|
||||
@@ -29,12 +29,12 @@ Not a public reading tracker or social app — a private, self-hosted sync layer
|
||||
|
||||
## Capabilities and Constraints
|
||||
|
||||
- Two libraries (manga, novels) with lifecycle tabs: All / Updated / Favourites / Archived. Search-filter by title (client-side, `filter.js`).
|
||||
- Card actions: continue (opens source site), toggle favourite, manual chapter override, archive, remove — each move out of the list confirm-gated.
|
||||
- Two libraries (manga, novels) with lifecycle tabs: All / Updated / Favourites / Archived / Finished. Search-filter by title (client-side, `filter.js`).
|
||||
- Card actions: continue (opens source site), toggle favourite, manual chapter override, archive, finish, remove — each move out of the list confirm-gated.
|
||||
- "Continue reading" horizontal strip for series with an unread chapter.
|
||||
- A Reader with no bookmarks at all sees a deliberate empty library offering both userscript install links, not an error and not a blank page.
|
||||
- Isolation is the load-bearing invariant: two Readers cannot see or change each other's bookmarks. A series both track is one shared row polled once, with independent progress on each side.
|
||||
- The owner alone can reach `/admin` (Overview, Lanes, Readers, Series) for library/lane/series maintenance and Reader session/Sighting controls; otherwise nothing else in the UI differs by Reader.
|
||||
- The owner can revoke a specific Reader's sessions; nothing else in the UI differs by Reader.
|
||||
- htmx-driven partial updates, no client-side framework or build step — templates are Go `html/template`, `go:embed`-ed.
|
||||
- Mobile-first is a hard functional constraint (primary device is a phone), not just a starting breakpoint.
|
||||
|
||||
@@ -54,7 +54,7 @@ Not a public reading tracker or social app — a private, self-hosted sync layer
|
||||
- Mobile is the primary target; desktop is an enhancement, not the design center.
|
||||
- Progress data integrity over visual flourish: `updated_at`/list-ordering behavior is a correctness constraint the UI must respect, not decorate over.
|
||||
- A leak between Readers fails silently and looks like working software — isolation is asserted from both directions, never inferred from counting one Reader's rows.
|
||||
- No roles, no org chrome beyond the owner gate: `/admin` is the one owner-only console (Overview, Lanes, Readers, Series) for library-wide hygiene, lane health/pauses and series/Reader maintenance — Readers offers revoke sessions and clear Sighting marks, both confirm-gated — and otherwise every Reader's view is the same.
|
||||
- No roles, no org chrome: the owner's Readers panel is one list with one button (revoke someone's sessions), not an admin console, and otherwise every Reader's view is the same.
|
||||
- Prefer native platform affordances (system dark/light, native touch targets) over custom widgetry — this is a lean self-hosted tool, not a product to demo.
|
||||
|
||||
## Accessibility & Inclusion
|
||||
|
||||
@@ -48,7 +48,6 @@ covers are stored, so the library renders in full with the browser switched off.
|
||||
| `DISCORD_CLIENT_ID` | *(required)* | Discord application credentials for the browser sign-in (ADR-0002). |
|
||||
| `DISCORD_CLIENT_SECRET` | *(required)* | As above. Never logged, never echoed in an error. |
|
||||
| `DISCORD_GUILD_ID` | *(required)* | The one guild whose membership gates sign-in, checked at login only. Membership *is* registration: any member becomes a Reader on first login. |
|
||||
| `DISCORD_GUILD_NAME` | empty | Human-readable name for `DISCORD_GUILD_ID`, shown on the login screen so a stranger knows which community owns this library and who to ask for an invite. When unset the page shows a generic "private community" label. |
|
||||
| `DISCORD_REDIRECT_URI` | *(required)* | Exact callback URL; Discord matches it verbatim against the registered redirect. |
|
||||
| `DISCORD_REQUIRED_ROLE` | empty | Role snowflake a member must additionally hold. Empty means guild membership alone suffices. |
|
||||
| `DISCORD_API_BASE` | `https://discord.com/api/v10` | Test seam — tests point it at a local stub so the real token exchange runs. |
|
||||
@@ -219,10 +218,10 @@ desktop for faster testing — install the same file unchanged.
|
||||
keeps checking it for new chapters, so it is worth coming back to. Archiving
|
||||
does not touch read progress, and reading an archived series leaves it
|
||||
archived.
|
||||
- **Finished**: the owner marks a Series finished from its detail page; the
|
||||
backend stops polling it, and every Reader sees a read-only label. It is a
|
||||
fact about the Series, not a Reader's bucket: old `Finished` bookmarks were
|
||||
folded into Archived in the cutover, so there is no Finished tab.
|
||||
- **Finished**: series you have completed live in a **Finished** tab in the web
|
||||
UI only. It is set there and nowhere else — the API rejects the value — and
|
||||
finished series are hidden from every userscript tab and are no longer polled
|
||||
for new chapters.
|
||||
- Bookmarks made on Asura appear when the panel is opened on Demonic, and vice
|
||||
versa — the backend is the shared store.
|
||||
|
||||
|
||||
+16
-30
@@ -31,7 +31,8 @@ image, TLS terminated by the reverse proxy so the service listens plain `:8080`.
|
||||
store must have that `TestMain` or it has no database at all.
|
||||
|
||||
### Reader-owned store — `internal/store`, `internal/token`
|
||||
- The Reader-owned tables are `readers`, `bookmarks`, `series`, and `sessions`; auxiliary `covers`, `poll_lanes`, and `poll_passes` are also defined in the migrations.
|
||||
|
||||
Four tables; shape is in the migrations, behaviour in `Store`'s methods.
|
||||
|
||||
- **Credentials are derived, never stored.** `token.Token(TOKEN_KEY, discord_id, epoch)`
|
||||
is an HMAC; only its SHA-256 reaches `readers.token_sha256`. So install URLs
|
||||
@@ -134,7 +135,7 @@ unchanged read is exactly the Sighting worth deferring a Poll on.
|
||||
rest.
|
||||
|
||||
**Refusals and browser loss are Lane-local.** Two `errChallengeHeld` in a pass
|
||||
stop that Site for `RefuseBackoff` while other Lanes continue. An
|
||||
stop that Site for `refuseBackoff` while other Lanes continue. An
|
||||
`errBrowserInterrupted` (remote Chrome restarted) sets a shared Poller flag so
|
||||
the *other* browser Lanes skip their passes for the same window — otherwise a
|
||||
restarting Chrome stamps one Series per Lane per pass, burning rests on
|
||||
@@ -159,15 +160,6 @@ failures. The flag decays and they probe again.
|
||||
- Browser Lanes wake Chrome only when 5+ Series are due or one has waited 15m,
|
||||
and cover work runs in the background so a slow CDN can't eat a Lane's gap.
|
||||
|
||||
### Owner notices — `internal/notify`, `latest.Fault`, `latest.Notifier`, `latest.FaultsFrom`
|
||||
|
||||
The poller's outbound owner-notice path (issue #171): one condition today
|
||||
(the stall), judged from the durable pass log alone so the poller and any
|
||||
future reader of the same judgement cannot disagree. The webhook address is a
|
||||
secret in the class of TOKEN_KEY — never logged, never rendered, never
|
||||
carried in an error. The `owner_notices` suppression table (one row per
|
||||
condition + site) is the only state; every threshold is derived, not stored.
|
||||
|
||||
### Covers — `Store.OnSeriesCreated`, `latest.Acquirer`, `latest.CoverBytesFetcher`, `Store.SetSeriesCover`
|
||||
|
||||
Acquired once when the first Bookmark of a Series is created, then served from
|
||||
@@ -209,16 +201,12 @@ stored** and clients must adopt that response rather than their own payload.
|
||||
|
||||
### Lifecycle buckets — `status` on each bookmark
|
||||
|
||||
`reading` | `archived`, orthogonal to `favorite`. Archived rows appear only
|
||||
in their own tab, never in All, Updated, Favourites or the recent strip. The
|
||||
poller keeps checking archived series; a finished Series (issue #157) is a
|
||||
`series.finished_at` fact the Lane gate reads, with every bookmark on it
|
||||
archived.
|
||||
`reading` | `archived` | `finished`, orthogonal to `favorite`. Archived and
|
||||
finished appear only in their own tab, never in All, Updated, Favourites or the
|
||||
recent strip. The poller keeps checking archived series and skips finished ones.
|
||||
|
||||
- `PUT /bookmarks/{key}` accepts only the two values; anything else —
|
||||
`finished` included — is a plain 400, and the web UI's own status control
|
||||
validates the same way. The 0016 migration is the only writer of the flag
|
||||
today; the undo is writing 0.
|
||||
- `finished` is settable only from the web UI; `PUT /bookmarks/{key}` rejects
|
||||
it with 400.
|
||||
- **An empty incoming status means "keep the stored one"**, and it is resolved
|
||||
on the `VALUES` side of `Store.Upsert`, not in the conflict clause:
|
||||
`excluded.*` is the post-evaluation row, so a default applied there would
|
||||
@@ -265,18 +253,16 @@ keep warning to reinstall on all devices.
|
||||
(`view.Owner = readerID == h.store.OwnerID()`): it gates a link, not an
|
||||
endpoint, so it is a rendering decision a registration-time wrapper cannot
|
||||
express. Do not "unify" it into the gate.
|
||||
- The Lanes page reads the pass log, never a running poller: `lanesView()` in
|
||||
`admin_lanes.go` projects `store.LatestLanePasses()` and
|
||||
`store.LanePassOutcomes()` (ADR-0012), so a restart answers the instant the
|
||||
database is up. Browser configuration is a config fact and reachability is
|
||||
derived from recent browser-Site passes inside `latest.RefuseBackoff` — no
|
||||
reporter interface exists to fake.
|
||||
- Lane figures come through the `web.LaneReporter` seam
|
||||
(`latest.Poller.LaneStatus`), never a table. `main.newRouter` takes the
|
||||
reporter as an interface and converts a nil `*Poller` to a nil interface — a
|
||||
typed nil would make the page claim a poller exists.
|
||||
- A pass that returns before computing figures (refusal backoff, sidecar down)
|
||||
carries the previous pass's numbers forward rather than recording zeroes.
|
||||
- **`Checked` next to `Due` is what separates a stopped Lane from a quiet one**,
|
||||
so neither may be dropped from the row.
|
||||
- Due-without-Checked is **not** by itself a stall: a browser Lane under both
|
||||
wake thresholds records its pass with the `SkipAsleep` skip and renders
|
||||
"browser asleep", and that never counts toward `Attention`. It is the
|
||||
commonest healthy state for kagane, comix and novelfull, so spending the
|
||||
stall mark on it would train the owner to ignore the mark that matters.
|
||||
wake thresholds sets `LaneState.Asleep` and renders "browser asleep", and
|
||||
never counts toward `Attention`. That is the commonest healthy state for
|
||||
kagane, comix and novelfull, so spending the stall mark on it would train the
|
||||
owner to ignore the mark that matters.
|
||||
|
||||
+6
-53
@@ -2,7 +2,6 @@ package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
@@ -49,7 +48,7 @@ func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
|
||||
|
||||
func newTestServer(t *testing.T) http.Handler {
|
||||
t.Helper()
|
||||
return newRouter(newTestStore(t), testConfig())
|
||||
return newRouter(newTestStore(t), testConfig(), nil)
|
||||
}
|
||||
|
||||
func newTestStore(t *testing.T) *store.Store {
|
||||
@@ -299,7 +298,7 @@ func TestFlatWireFieldSet(t *testing.T) {
|
||||
"series_url": true, "cover": true, "last_chapter": true,
|
||||
"last_chapter_num": true, "last_chapter_url": true, "favorite": true,
|
||||
"latest_chapter": true, "latest_chapter_num": true, "updated_at": true,
|
||||
"status": true, "kind": true, "finished": true,
|
||||
"status": true, "kind": true,
|
||||
}
|
||||
checkFlat := func(t *testing.T, payload []byte) map[string]json.RawMessage {
|
||||
t.Helper()
|
||||
@@ -363,52 +362,6 @@ func TestFlatWireFieldSet(t *testing.T) {
|
||||
checkFlat(t, body2)
|
||||
}
|
||||
|
||||
// finished is derived on the wire and read-only: a client PUT echoing a cached
|
||||
// value, forward progress or not, must not change the Series' retired state,
|
||||
// so GET still reports the truth after the echo (issues #157, #160).
|
||||
func TestFinishedWireRoundTrip(t *testing.T) {
|
||||
s, url := newTestStoreURL(t)
|
||||
srv := newRouter(s, testConfig())
|
||||
key := "asura:done"
|
||||
|
||||
putBookmark(t, srv, key, store.Bookmark{
|
||||
Title: "Solo Leveling", SeriesURL: "https://asurascans.com/comics/done",
|
||||
LastChapterNum: 10,
|
||||
})
|
||||
|
||||
// The store writer for the flag is the admin surface's own and lands in
|
||||
// the same wave (#158), so seed the fact with SQL, like store_test.go.
|
||||
db, err := sql.Open("pgx", url)
|
||||
if err != nil {
|
||||
t.Fatalf("open db: %v", err)
|
||||
}
|
||||
defer db.Close()
|
||||
if _, err := db.Exec(
|
||||
`UPDATE series SET finished_at = 1000 WHERE site = 'asura' AND series_id = 'done'`); err != nil {
|
||||
t.Fatalf("seed finished: %v", err)
|
||||
}
|
||||
|
||||
got := getBookmarks(t, srv)
|
||||
if len(got) != 1 || !got[0].Finished {
|
||||
t.Fatalf("GET = %+v, want one bookmark carrying finished: true", got)
|
||||
}
|
||||
|
||||
// A stale cache echoing the flag cannot un-finish (or finish) the Series.
|
||||
for _, sent := range []bool{false, true} {
|
||||
echoed := putBookmark(t, srv, key, store.Bookmark{
|
||||
Title: "Solo Leveling", SeriesURL: "https://asurascans.com/comics/done",
|
||||
LastChapterNum: 11, Finished: sent,
|
||||
})
|
||||
if !echoed.Finished {
|
||||
t.Fatalf("PUT echoing Finished: %v reported finished = false, want true", sent)
|
||||
}
|
||||
got = getBookmarks(t, srv)
|
||||
if !got[0].Finished {
|
||||
t.Fatalf("GET after echoing Finished: %v = false, want the Series state preserved", sent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A PUT naming an existing series must ignore client-supplied title, cover and
|
||||
// URL — the security boundary from ADR-0003, where a hostile site's scraped
|
||||
// values could otherwise land on a shared row — while progress still lands.
|
||||
@@ -646,7 +599,7 @@ func TestLoadConfigDiscord(t *testing.T) {
|
||||
// cooldown and the poller would re-fetch that series on every single tick.
|
||||
func TestPutDoesNotClobberLatestCheckedAt(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
srv := newRouter(s, testConfig())
|
||||
srv := newRouter(s, testConfig(), nil)
|
||||
|
||||
seedForCheck(t, s, "asura:x", "https://asurascans.com/comics/x", 777)
|
||||
|
||||
@@ -674,7 +627,7 @@ func TestPutDoesNotClobberLatestCheckedAt(t *testing.T) {
|
||||
// series stops being due the moment the PUT lands.
|
||||
func TestPutRecordsASighting(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
srv := newRouter(s, testConfig())
|
||||
srv := newRouter(s, testConfig(), nil)
|
||||
|
||||
now := time.Now().UnixMilli()
|
||||
hour := time.Hour.Milliseconds()
|
||||
@@ -724,7 +677,7 @@ func TestUserscriptServedWithWebUIDisabled(t *testing.T) {
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/u/"+ownerCredential()+"/manga-bookmark.user.js", nil)
|
||||
newRouter(s, cfg).ServeHTTP(rr, req)
|
||||
newRouter(s, cfg, nil).ServeHTTP(rr, req)
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", rr.Code)
|
||||
}
|
||||
@@ -746,7 +699,7 @@ func TestNovelUserscriptServed(t *testing.T) {
|
||||
|
||||
cfg := testConfig()
|
||||
cfg.NovelUserscriptPath = novelPath
|
||||
srv := newRouter(s, cfg)
|
||||
srv := newRouter(s, cfg, nil)
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
srv.ServeHTTP(rr, httptest.NewRequest(http.MethodGet,
|
||||
|
||||
@@ -32,7 +32,7 @@ func TestPublicCoverServesStoredBytesUnauthenticated(t *testing.T) {
|
||||
|
||||
// The wire URL is what a client actually requests, so the path under test
|
||||
// is taken from it rather than rebuilt by hand.
|
||||
wire := st.CoverWireURL(store.CoverAddressForBytes([]byte("\x00webp-bytes")))
|
||||
wire := st.CoverWireURL(store.CoverAddress(sourceURL))
|
||||
path, ok := strings.CutPrefix(wire, testCoverBaseURL)
|
||||
if !ok {
|
||||
t.Fatalf("wire URL %q is not on the public origin %q", wire, testCoverBaseURL)
|
||||
@@ -57,7 +57,7 @@ func TestPublicCoverServesStoredBytesUnauthenticated(t *testing.T) {
|
||||
func TestPublicCoverRejectsUnknownAddress(t *testing.T) {
|
||||
srv, _ := newWebTestServer(t, testConfig())
|
||||
cases := map[string]string{
|
||||
"unknown": "/covers/" + store.CoverAddressForBytes([]byte("never-stored")),
|
||||
"unknown": "/covers/" + store.CoverAddress("https://cdn.example/never-stored.jpg"),
|
||||
"malformed": "/covers/not-an-address",
|
||||
"traversal": "/covers/../../etc/passwd",
|
||||
"empty": "/covers/",
|
||||
@@ -86,7 +86,7 @@ func TestPublicCoverNeverEchoesNonImage(t *testing.T) {
|
||||
}
|
||||
// A legitimate row, then the content type flipped behind the store's back:
|
||||
// the bytes exist at the address, so only the type is hostile.
|
||||
address := store.CoverAddressForBytes([]byte("<script>"))
|
||||
address := store.CoverAddress(sourceURL)
|
||||
if err := st.SetSeriesCover("asura", "solo", sourceURL, []byte("<script>"), "image/png"); err != nil {
|
||||
t.Fatalf("seed row: %v", err)
|
||||
}
|
||||
@@ -98,7 +98,7 @@ func TestPublicCoverNeverEchoesNonImage(t *testing.T) {
|
||||
if _, err := db.Exec(`UPDATE covers SET content_type = 'text/html' WHERE address = $1`, address); err != nil {
|
||||
t.Fatalf("poison row: %v", err)
|
||||
}
|
||||
rr := getCover(t, newRouter(st, testConfig()), "/covers/"+address, nil)
|
||||
rr := getCover(t, newRouter(st, testConfig(), nil), "/covers/"+address, nil)
|
||||
if rr.Code == http.StatusOK {
|
||||
t.Fatalf("status = 200, want a refusal for a non-image row (body %q)", rr.Body.String())
|
||||
}
|
||||
@@ -127,7 +127,7 @@ func TestListRendersAcquiredCover(t *testing.T) {
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", rr.Code)
|
||||
}
|
||||
want := `src="` + testCoverBaseURL + "/covers/" + store.CoverAddressForBytes([]byte("\xff\xd8jpeg")) + `"`
|
||||
want := `src="` + testCoverBaseURL + "/covers/" + store.CoverAddress(sourceURL) + `"`
|
||||
if !strings.Contains(rr.Body.String(), want) {
|
||||
t.Fatalf("rendered list does not contain %s", want)
|
||||
}
|
||||
|
||||
@@ -73,11 +73,14 @@ func (h *Handler) Put(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// An empty status is "no opinion" and Upsert keeps the stored bucket.
|
||||
// Anything else outside the two lifecycle buckets is a client bug, not
|
||||
// something to silently coerce — finished included, which is no longer a
|
||||
// bucket at all (issue #157).
|
||||
// Finishing a series is a web-UI decision, so the JSON API refuses it
|
||||
// rather than trusting every client to leave it alone.
|
||||
switch b.Status {
|
||||
case "", store.StatusReading, store.StatusArchived:
|
||||
case store.StatusFinished:
|
||||
http.Error(w, "status "+store.StatusFinished+" can only be set from the web UI",
|
||||
http.StatusBadRequest)
|
||||
return
|
||||
default:
|
||||
http.Error(w, "invalid status", http.StatusBadRequest)
|
||||
return
|
||||
|
||||
@@ -123,10 +123,10 @@ func TestAcquireFillsChapterAndCoverFromOneFetch(t *testing.T) {
|
||||
if got.LatestChapterNum == nil || *got.LatestChapterNum != 181 {
|
||||
t.Fatalf("LatestChapterNum = %v, want 181", got.LatestChapterNum)
|
||||
}
|
||||
if want := testCoverBaseURL + "/covers/" + store.CoverAddressForBytes([]byte("cover-bytes")); got.Cover != want {
|
||||
if want := testCoverBaseURL + "/covers/" + store.CoverAddress(acquireCoverURL); got.Cover != want {
|
||||
t.Fatalf("Cover = %q, want the absolute address %q", got.Cover, want)
|
||||
}
|
||||
body, contentType, ok, err := s.CoverByAddress(store.CoverAddressForBytes([]byte("cover-bytes")))
|
||||
body, contentType, ok, err := s.CoverByAddress(store.CoverAddress(acquireCoverURL))
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("CoverByAddress = %v, %v", ok, err)
|
||||
}
|
||||
@@ -135,33 +135,6 @@ func TestAcquireFillsChapterAndCoverFromOneFetch(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A pause governs the Lane only: a Reader's first bookmark of a Series on a
|
||||
// paused Site still reads the page, because acquisition is the creation-time
|
||||
// fetch, not the poll queue (issue #147).
|
||||
func TestAcquireIgnoresLanePause(t *testing.T) {
|
||||
s, _ := newTestStore(t)
|
||||
if err := s.PauseLane("asura", time.Now().Add(6*time.Hour).UnixMilli()); err != nil {
|
||||
t.Fatalf("PauseLane: %v", err)
|
||||
}
|
||||
page := &fakeFetcher{body: asuraSeriesAndCoverFixture, status: 200}
|
||||
covers := &fakeBytesCoverFetcher{body: []byte("cover-bytes"), contentType: "image/jpeg"}
|
||||
acq := newAcquirer(s, page, covers)
|
||||
|
||||
bookmarkNewSeries(t, s, acquireSeriesURL)
|
||||
acq.Wait()
|
||||
|
||||
if got := page.callCount(); got != 1 {
|
||||
t.Fatalf("series page fetches on a paused Site = %d, want 1", got)
|
||||
}
|
||||
if got := covers.callCount(); got != 1 {
|
||||
t.Fatalf("cover fetches = %d, want 1", got)
|
||||
}
|
||||
got := readBookmark(t, s, acquireKey)
|
||||
if got.LatestChapterNum == nil || *got.LatestChapterNum != 181 {
|
||||
t.Fatalf("LatestChapterNum = %v, want 181", got.LatestChapterNum)
|
||||
}
|
||||
}
|
||||
|
||||
// A Series that already exists is not re-acquired: no fetch, and the Cover it
|
||||
// already has is left alone.
|
||||
func TestAcquireSkipsAnExistingSeries(t *testing.T) {
|
||||
@@ -182,7 +155,7 @@ func TestAcquireSkipsAnExistingSeries(t *testing.T) {
|
||||
t.Fatalf("cover fetches = %d, want 1", got)
|
||||
}
|
||||
got := readBookmark(t, s, acquireKey)
|
||||
if want := testCoverBaseURL + "/covers/" + store.CoverAddressForBytes([]byte("cover-bytes")); got.Cover != want {
|
||||
if want := testCoverBaseURL + "/covers/" + store.CoverAddress(acquireCoverURL); got.Cover != want {
|
||||
t.Fatalf("Cover = %q, want the acquired one %q", got.Cover, want)
|
||||
}
|
||||
}
|
||||
@@ -343,10 +316,10 @@ func TestAcquireKaganeCoverThroughBrowser(t *testing.T) {
|
||||
t.Fatalf("browser cover fetched URL %q, want %q", got, kaganeCoverSrc)
|
||||
}
|
||||
got := readBookmark(t, s, kaganeKey)
|
||||
if want := testCoverBaseURL + "/covers/" + store.CoverAddressForBytes([]byte("cover-bytes")); got.Cover != want {
|
||||
if want := testCoverBaseURL + "/covers/" + store.CoverAddress(kaganeCoverSrc); got.Cover != want {
|
||||
t.Fatalf("Cover = %q, want the content-addressed URL %q", got.Cover, want)
|
||||
}
|
||||
body, contentType, ok, err := s.CoverByAddress(store.CoverAddressForBytes([]byte("cover-bytes")))
|
||||
body, contentType, ok, err := s.CoverByAddress(store.CoverAddress(kaganeCoverSrc))
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("CoverByAddress = %v, %v", ok, err)
|
||||
}
|
||||
@@ -381,7 +354,7 @@ func TestAcquireNovelfullCoverOverPlainTLS(t *testing.T) {
|
||||
t.Fatalf("cover fetched from %q, want %q", got, novelfullCoverURL)
|
||||
}
|
||||
got := readBookmark(t, s, novelfullKey)
|
||||
if want := testCoverBaseURL + "/covers/" + store.CoverAddressForBytes([]byte("cover-bytes")); got.Cover != want {
|
||||
if want := testCoverBaseURL + "/covers/" + store.CoverAddress(novelfullCoverURL); got.Cover != want {
|
||||
t.Fatalf("Cover = %q, want %q", got.Cover, want)
|
||||
}
|
||||
}
|
||||
@@ -451,7 +424,7 @@ func TestAcquireNovelfullCoverWithoutBrowser(t *testing.T) {
|
||||
t.Fatalf("cover fetches = %d, want 1", got)
|
||||
}
|
||||
got := readBookmark(t, s, novelfullKey)
|
||||
if want := testCoverBaseURL + "/covers/" + store.CoverAddressForBytes([]byte("cover-bytes")); got.Cover != want {
|
||||
if want := testCoverBaseURL + "/covers/" + store.CoverAddress(novelfullCoverURL); got.Cover != want {
|
||||
t.Fatalf("Cover = %q, want %q", got.Cover, want)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,7 +124,7 @@ func (f *BrowserFetcher) Get(ctx context.Context, seriesURL string) (string, int
|
||||
// request must be made from inside the page so it carries the clearance
|
||||
// cookie, and the API is the only place the list exists. Refusing any other
|
||||
// address is the per-Site half of the SSRF gate, kept deliberately behind
|
||||
// FetchableSeriesURL (see browserRead.Read).
|
||||
// fetchableSeriesURL (see browserRead.Read).
|
||||
func kaganeRead(seriesURL string, out *string) (chromedp.Action, bool) {
|
||||
apiURL, ok := kaganeAPIURL(seriesURL)
|
||||
if !ok {
|
||||
@@ -326,7 +326,7 @@ func (f *BrowserFetcher) run(ctx context.Context, target string, read chromedp.A
|
||||
|
||||
// kaganeAPIURL maps a stored series_url to the JSON endpoint carrying its
|
||||
// chapter list. Returning false for anything else is a second line of defence
|
||||
// behind FetchableSeriesURL: a headless browser is a strong SSRF primitive and
|
||||
// behind fetchableSeriesURL: a headless browser is a strong SSRF primitive and
|
||||
// series_url is client-supplied, so the host is pinned here too.
|
||||
func kaganeAPIURL(seriesURL string) (string, bool) {
|
||||
u, err := url.Parse(seriesURL)
|
||||
|
||||
@@ -145,10 +145,6 @@ func (f *TLSCoverFetcher) Fetch(ctx context.Context, sourceURL string) ([]byte,
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("build cover request: %w", err)
|
||||
}
|
||||
// cdn.asurascans.com answers Go's default User-Agent with a Cloudflare
|
||||
// challenge (403, cf-mitigated) and a Chrome one with the image; measured
|
||||
// 2026-12-04. No TLS fingerprint needed — the UA alone flips it.
|
||||
req.Header.Set("User-Agent", chromeUA)
|
||||
resp, err := f.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("fetch cover: %w", err)
|
||||
@@ -178,7 +174,7 @@ func (f *TLSCoverFetcher) Fetch(ctx context.Context, sourceURL string) ([]byte,
|
||||
return body, contentType, nil
|
||||
}
|
||||
|
||||
// This gate deliberately differs from FetchableSeriesURL: cover hosts are
|
||||
// This gate deliberately differs from fetchableSeriesURL: cover hosts are
|
||||
// site-independent CDNs, so a Site host allowlist would reject valid covers.
|
||||
func (f *TLSCoverFetcher) validateURL(ctx context.Context, u *url.URL) error {
|
||||
if u == nil || u.Scheme != "https" || u.Host == "" || u.User != nil {
|
||||
|
||||
@@ -228,24 +228,6 @@ func TestCoverFetcherRejectsNonImage(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// cdn.asurascans.com challenges Go's default User-Agent (measured 2026-12-04),
|
||||
// so every cover from it failed until the fetcher sent a browser one.
|
||||
func TestCoverFetcherSendsBrowserUserAgent(t *testing.T) {
|
||||
client := &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.UserAgent() != chromeUA {
|
||||
return coverResponse(http.StatusForbidden, "text/html", "", []byte("Just a moment...")), nil
|
||||
}
|
||||
return coverResponse(http.StatusOK, "image/webp", "", []byte("cover-bytes")), nil
|
||||
})}
|
||||
fetcher := newCoverFetcher(client, func(context.Context, string) ([]netip.Addr, error) {
|
||||
return []netip.Addr{netip.MustParseAddr("198.51.100.10")}, nil
|
||||
})
|
||||
|
||||
if _, _, err := fetcher.Fetch(context.Background(), "https://cdn.asurascans.com/asura-images/covers/x.webp"); err != nil {
|
||||
t.Fatalf("Fetch: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// comix labels its covers "image/jpg", which is not a registered type but is
|
||||
// what the Site actually answers with; the bytes are stored under the real
|
||||
// name so one image cannot land under two spellings.
|
||||
|
||||
@@ -1,210 +0,0 @@
|
||||
package latest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"bookmarkmanager/backend/internal/store"
|
||||
)
|
||||
|
||||
// ConditionStall is the owner-notice machine word for a Lane that owed Polls,
|
||||
// made none, and has nothing to say for it. The word is the message's footer
|
||||
// and its suppression key; it is wire-stable. #172 declares the other three
|
||||
// words (no-browser-route, sidecar-down, adapter-broken); this ticket
|
||||
// declares only the stall.
|
||||
const ConditionStall = "stall"
|
||||
// ConditionNoBrowserRoute is the owner-notice machine word for a Site whose
|
||||
// challenge refuses for longer than the owner window with no browser route
|
||||
// to clear it — the 403-with-interstitial the reader maps to
|
||||
// errChallengeHeld (read.go), which plain TLS cannot clear. The word is the
|
||||
// message's footer and its suppression key; it is wire-stable.
|
||||
const ConditionNoBrowserRoute = "no-browser-route"
|
||||
|
||||
// ConditionSidecarDown is the owner-notice machine word for a browser
|
||||
// sidecar no Lane has reached for longer than the owner window: every
|
||||
// browser-backed Lane's latest pass is a sidecar skip. The word is the
|
||||
// message's footer and its suppression key; it is wire-stable, and its
|
||||
// suppression row holds the empty Site (AC4).
|
||||
const ConditionSidecarDown = "sidecar-down"
|
||||
|
||||
// ConditionAdapterBroken is the owner-notice machine word for a Site whose
|
||||
// adapter stopped finding chapters: more than half of its Series hold an
|
||||
// old no-chapter failure row. The word is the message's footer and its
|
||||
// suppression key; it is wire-stable.
|
||||
const ConditionAdapterBroken = "adapter-broken"
|
||||
|
||||
// OwnerWindow is the class-level staleness boundary every owner-notice
|
||||
// condition measures against — the same twelve hours the Lanes page's
|
||||
// "not checked in 12h" filter uses (internal/web/admin.go). Declared here
|
||||
// once so #172's three conditions and the admin filters share one figure.
|
||||
const OwnerWindow = 12 * time.Hour
|
||||
|
||||
// Fault is one condition the owner is told about, judged from durable rows
|
||||
// alone. Site is "" for a fault that is not one Site's.
|
||||
type Fault struct {
|
||||
Condition string // one of the Condition* words
|
||||
Site string
|
||||
Since int64 // unix ms the episode began; the message's age
|
||||
}
|
||||
|
||||
// FaultInput is everything the judgement reads. A struct so #172's three
|
||||
// conditions can add inputs without changing either caller.
|
||||
type FaultInput struct {
|
||||
Passes []store.LanePass
|
||||
// RefusingSince is, per Site, the unix ms when that Site's current
|
||||
// unbroken run of refusing passes began, or absent when its latest pass
|
||||
// did not refuse. Its zero value is an empty map, which contributes no
|
||||
// fault.
|
||||
RefusingSince map[string]int64
|
||||
|
||||
// SidecarOK is, per browser-backed Site, the unix ms of that Site's most
|
||||
// recent pass that actually reached the sidecar. Zero when the pass log
|
||||
// holds none — an asleep Lane never reached it and never counts as
|
||||
// evidence either way. Its zero value is an empty map.
|
||||
SidecarOK map[string]int64
|
||||
|
||||
// NoChapterShare is, per Site, the share of that Site's Series holding a
|
||||
// no-chapter failure row older than the owner window. Its zero value is
|
||||
// an empty map, which contributes no fault.
|
||||
NoChapterShare map[string]float64
|
||||
}
|
||||
|
||||
// FaultsFrom judges the owner-notice conditions from durable rows alone, so
|
||||
// the poller and the landing page cannot disagree about what a fault is.
|
||||
//
|
||||
// A Lane stalls when its latest pass shows due > 0, none checked, no skip
|
||||
// value and no refusal — exactly the row the mid-loop browser loss writes
|
||||
// (see the comment at the outcomeUnreachable return in runLanePass), so a
|
||||
// Lane that owed Polls, made none, and has nothing to say for it is a fault.
|
||||
// The three #172 conditions share the same OwnerWindow boundary and the same
|
||||
// fail-open shape: an input's absence contributes no fault, never a false
|
||||
// one.
|
||||
//
|
||||
// - no-browser-route: a Site whose refusing run began before the window
|
||||
// and that has no browser route to clear the challenge (AC2). Both
|
||||
// refusal shapes count — the gate's skip='refusing' rows and the loop's
|
||||
// refused>0 rows (the twice-refused break writes skip="") — so the run
|
||||
// stays unbroken across them, and one healthy pass ends it.
|
||||
// - sidecar-down: every browser-backed Site's latest pass is a sidecar
|
||||
// skip — SkipSidecarDown or SkipNoFetcher, the two early returns that
|
||||
// record a skip value — and each Site's most recent sidecar-reaching
|
||||
// pass is older than the window (AC4). The skip clause is what keeps
|
||||
// SkipAsleep out: a Lane under both wake thresholds is the commonest
|
||||
// healthy state, never reached the sidecar, and would otherwise age into
|
||||
// a false alarm. Emitted once, with Site "" (AC4's one row per episode).
|
||||
// - adapter-broken: more than half of one Site's Series hold a no-chapter
|
||||
// failure row older than the window (AC6). Strictly above half: the
|
||||
// filter is the tool, and one Site change makes hundreds of rows, so a
|
||||
// single failing Series never fires (AC7). The episode's age is the
|
||||
// window — the old rows prove the episode is at least that old.
|
||||
func FaultsFrom(in FaultInput, now time.Time) []Fault {
|
||||
var faults []Fault
|
||||
for _, p := range in.Passes {
|
||||
if p.Due > 0 && p.Checked == 0 && p.Skip == "" && p.Refused == 0 {
|
||||
faults = append(faults, Fault{Condition: ConditionStall, Site: p.Site, Since: p.RanAt})
|
||||
}
|
||||
}
|
||||
cutoff := now.Add(-OwnerWindow).UnixMilli()
|
||||
for site, since := range in.RefusingSince {
|
||||
if since < cutoff && !isBrowserSite(site) {
|
||||
faults = append(faults, Fault{Condition: ConditionNoBrowserRoute, Site: site, Since: since})
|
||||
}
|
||||
}
|
||||
if since, down := sidecarDownSince(in.Passes, in.SidecarOK, cutoff); down {
|
||||
faults = append(faults, Fault{Condition: ConditionSidecarDown, Site: "", Since: since})
|
||||
}
|
||||
for site, share := range in.NoChapterShare {
|
||||
if share > 0.5 {
|
||||
faults = append(faults, Fault{Condition: ConditionAdapterBroken, Site: site, Since: now.Add(-OwnerWindow).UnixMilli()})
|
||||
}
|
||||
}
|
||||
return faults
|
||||
}
|
||||
|
||||
// sidecarDownSince reports whether no browser Lane has reached the sidecar
|
||||
// for longer than the owner window and, when it has, the last moment any
|
||||
// Lane reached it. The skip clause — every browser-backed Site's latest pass
|
||||
// must be SkipSidecarDown or SkipNoFetcher — keeps SkipAsleep out (see
|
||||
// FaultsFrom). A Site with no pass row at all is not judged down either: a
|
||||
// fresh database is not a dead sidecar.
|
||||
func sidecarDownSince(passes []store.LanePass, ok map[string]int64, cutoff int64) (since int64, down bool) {
|
||||
latest := make(map[string]store.LanePass, len(passes))
|
||||
for _, p := range passes {
|
||||
latest[p.Site] = p
|
||||
}
|
||||
for _, site := range browserBackedSites() {
|
||||
p, found := latest[site]
|
||||
if !found || (p.Skip != SkipSidecarDown && p.Skip != SkipNoFetcher) {
|
||||
return 0, false
|
||||
}
|
||||
reached := ok[site]
|
||||
if reached > 0 && reached >= cutoff {
|
||||
return 0, false
|
||||
}
|
||||
if reached > since {
|
||||
since = reached
|
||||
}
|
||||
}
|
||||
// No Lane's retained pass log shows a sidecar reach: the honest age is
|
||||
// the window itself — "at least twelve hours" — not the epoch, which
|
||||
// humanAge would render as tens of thousands of days.
|
||||
if since == 0 {
|
||||
since = cutoff
|
||||
}
|
||||
return since, true
|
||||
}
|
||||
|
||||
// Notifier delivers one owner notice. The poller neither retries nor queues:
|
||||
// an error is logged and the suppression row left unwritten, so the next pass
|
||||
// tries again while the condition holds.
|
||||
type Notifier interface {
|
||||
Notify(ctx context.Context, f Fault, sentence, href string) error
|
||||
}
|
||||
|
||||
// ownerNoticeConditions is every condition this package judges, for the
|
||||
// clear loop in recordPass: a condition absent from a pass's fault list
|
||||
// forgets its episode, so the next occurrence sends again. #172 extends the
|
||||
// list when it adds its conditions.
|
||||
var ownerNoticeConditions = []string{ConditionStall, ConditionNoBrowserRoute, ConditionSidecarDown, ConditionAdapterBroken}
|
||||
|
||||
// noticeFor renders one fault's message: the description sentence — condition,
|
||||
// age, repair — and the deep link the embed's title points at. Each condition
|
||||
// provides its own wording; the stall is the only one today (issue #171).
|
||||
func noticeFor(f Fault, row store.LanePass, now time.Time) (sentence, href string) {
|
||||
switch f.Condition {
|
||||
case ConditionStall:
|
||||
return fmt.Sprintf(
|
||||
"%s owed %d Polls and made none — %s; check the Lane's browser sidecar and the Site's challenge state",
|
||||
f.Site, row.Due, humanAge(now.Sub(time.UnixMilli(f.Since)))), "/admin/lanes"
|
||||
case ConditionNoBrowserRoute:
|
||||
return fmt.Sprintf(
|
||||
"%s has refused for %s with no browser route — the challenge does not clear on plain TLS; redeploy or add a browser route",
|
||||
f.Site, humanAge(now.Sub(time.UnixMilli(f.Since)))), "/admin/lanes"
|
||||
case ConditionSidecarDown:
|
||||
return fmt.Sprintf(
|
||||
"no browser Lane has reached the sidecar for %s — the browser sidecar is down; start or repair the browser machine",
|
||||
humanAge(now.Sub(time.UnixMilli(f.Since)))), "/admin/lanes"
|
||||
case ConditionAdapterBroken:
|
||||
return fmt.Sprintf(
|
||||
"more than half of %s's Series have failed no-chapter reads for at least %s — the Site's layout changed and the adapter is broken",
|
||||
f.Site, humanAge(now.Sub(time.UnixMilli(f.Since)))), "/admin/lanes"
|
||||
}
|
||||
return "", ""
|
||||
}
|
||||
|
||||
// humanAge renders a duration the way an owner reads it in a message: minutes
|
||||
// under an hour, then hours, then days; a stall that was just born reads
|
||||
// "just now".
|
||||
func humanAge(d time.Duration) string {
|
||||
switch {
|
||||
case d < time.Minute:
|
||||
return "just now"
|
||||
case d < time.Hour:
|
||||
return fmt.Sprintf("%dm", int(d.Minutes()))
|
||||
case d < 24*time.Hour:
|
||||
return fmt.Sprintf("%dh", int(d.Hours()))
|
||||
default:
|
||||
return fmt.Sprintf("%dd", int(d.Hours()/24))
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"log"
|
||||
"net/url"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -46,26 +47,20 @@ type Poller struct {
|
||||
// CoverBytesFetch is optional; it handles plain-TLS sources through the
|
||||
// same failure-isolated prefetch path.
|
||||
CoverBytesFetch CoverBytesFetcher
|
||||
// Notify delivers owner notices. Nil disables the whole path (issue #171):
|
||||
// the poller is not the place a missing webhook becomes an error.
|
||||
Notify Notifier
|
||||
Now func() time.Time // injected so tests can freeze it
|
||||
// eligibleCount reports how many of a Site's Series are eligible for
|
||||
// polling, defaulting to Store.EligibleSeriesCount. Injected so tests can
|
||||
// fail the count alone: the eligible query shares the due query's tables,
|
||||
// so no real store failure can reach this path without breaking the due
|
||||
// query first (issue #141).
|
||||
eligibleCount func(site string) (int, error)
|
||||
|
||||
// refuseUntil gates a Site's Lane after it refused twice in one run: no
|
||||
// Series of that Site is attempted again before this time (issue #100).
|
||||
// The stamp is durable — the pass gate reads it from the store, so a
|
||||
// restart does not forget the refusal; nothing of it lives in memory.
|
||||
// browserDownAt is when a browser Lane last lost the sidecar; the other
|
||||
// browser Lanes skip their passes for the next RefuseBackoff, so a
|
||||
// browser Lanes skip their passes for the next refuseBackoff, so a
|
||||
// restarting Chrome does not stamp one Series per pass per Lane (story 20).
|
||||
mu sync.Mutex
|
||||
refuseUntil map[string]time.Time
|
||||
browserDownAt time.Time
|
||||
// laneStates is the owner's page snapshot of each Lane's last pass
|
||||
// (issue #102), keyed by Site. Guarded by mu; a Site appears only after
|
||||
// its first pass, so a restart renders "no data yet" rather than zeroes.
|
||||
laneStates map[string]LaneState
|
||||
// coverWG tracks in-flight cover work. Covers heal in the background so a
|
||||
// slow cover host cannot delay the next Series-page Poll; tests join it
|
||||
// before asserting on cover fetches.
|
||||
@@ -101,23 +96,6 @@ func (p *Poller) fillBlankCover(ctx context.Context, sr store.Series, cover stri
|
||||
}()
|
||||
}
|
||||
|
||||
// replaceCover is the Forced Poll's Cover path: the owner asked to accept the
|
||||
// page as it now stands, so where fillBlankCover leaves a non-blank Cover
|
||||
// alone (ADR-0007) this writes through whatever the page's Cover URL answers
|
||||
// with, whether one exists or not. The accepted consequence (issue #135):
|
||||
// refreshing the Cover and re-reading the chapters are one act — there is no
|
||||
// Cover-only refetch.
|
||||
func (p *Poller) replaceCover(ctx context.Context, sr store.Series, cover string) {
|
||||
if cover == "" {
|
||||
return
|
||||
}
|
||||
p.coverWG.Add(1)
|
||||
go func() {
|
||||
defer p.coverWG.Done()
|
||||
p.storeCover(ctx, sr, cover)
|
||||
}()
|
||||
}
|
||||
|
||||
// prefetchCover heals Series that already carry a third-party source URL but
|
||||
// no stored address — the state left by client-supplied covers before
|
||||
// acquisition moved server-side. Every Site takes the same path; fetchCoverBytes
|
||||
@@ -142,43 +120,18 @@ func (p *Poller) prefetchCover(ctx context.Context, sr store.Series) {
|
||||
p.storeCover(ctx, sr, sr.Cover)
|
||||
}
|
||||
|
||||
// storeCover fetches bytes for sourceURL and points the Series at them: a
|
||||
// fill-only write for an ordinary pass, a write-through for a forced one
|
||||
// (issue #135). Every failure is logged against the Series and swallowed so
|
||||
// the chapter poll cannot see it.
|
||||
// storeCover fetches bytes for sourceURL and points the Series at them. Every
|
||||
// failure is logged against the Series and swallowed so the chapter poll
|
||||
// cannot see it.
|
||||
func (p *Poller) storeCover(ctx context.Context, sr store.Series, sourceURL string) {
|
||||
bytes, contentType, err := fetchCoverBytes(ctx, sourceURL, p.CoverFetch, p.CoverBytesFetch)
|
||||
if err != nil {
|
||||
log.Printf("latest poll %q: fetch cover %s: %v", sr.Key(), sourceURL, err)
|
||||
return
|
||||
}
|
||||
if !sr.Forced {
|
||||
if err := p.Store.SetSeriesCover(sr.Site, sr.SeriesID, sourceURL, bytes, contentType); err != nil {
|
||||
log.Printf("latest poll %q: persist cover: %v", sr.Key(), err)
|
||||
}
|
||||
return
|
||||
}
|
||||
// The forced write replaces whether or not a Cover exists, and the row
|
||||
// then tells the three outcomes apart: a blank filled, identical artwork
|
||||
// re-served — an honest no-op — or a replacement whose previous address
|
||||
// is stranded and reclaimed below. A failed reclaim is logged and the
|
||||
// stranded bytes stay served until a later call reclaims them.
|
||||
previous, current, err := p.Store.ReplaceSeriesCover(sr.Site, sr.SeriesID, sourceURL, bytes, contentType)
|
||||
if err != nil {
|
||||
log.Printf("latest poll %q: persist cover: %v", sr.Key(), err)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case previous == "":
|
||||
log.Printf("latest poll %q: cover filled at %s", sr.Key(), current)
|
||||
case previous == current:
|
||||
log.Printf("latest poll %q: cover unchanged, the site re-serves the same bytes", sr.Key())
|
||||
default:
|
||||
if err := p.Store.ReclaimCover(previous); err != nil {
|
||||
log.Printf("latest poll %q: reclaim cover %s: %v", sr.Key(), previous, err)
|
||||
}
|
||||
log.Printf("latest poll %q: cover replaced %s -> %s", sr.Key(), previous, current)
|
||||
}
|
||||
}
|
||||
|
||||
// fetcherFor returns the fetcher a site's page needs, or nil when the site
|
||||
@@ -214,7 +167,14 @@ func fetcherFor(site string, browser, tls Fetcher) Fetcher {
|
||||
// laneNames returns every registry Site in the deterministic order both Run
|
||||
// and runOnce iterate: sorted, so lane behaviour and its tests agree on who
|
||||
// runs first.
|
||||
func laneNames() []string { return SiteNames() }
|
||||
func laneNames() []string {
|
||||
names := make([]string, 0, len(sites))
|
||||
for name := range sites {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
return names
|
||||
}
|
||||
|
||||
func (p *Poller) Run(ctx context.Context) {
|
||||
names := laneNames()
|
||||
@@ -256,143 +216,28 @@ func (p *Poller) runOnce(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// One skip value per way a Lane Pass can return before its loop (issue #141);
|
||||
// empty means the pass reached the loop. The values are wire strings — stored
|
||||
// in poll_passes and read by the Lanes page — so they are stable, not prose.
|
||||
const (
|
||||
// Exported so the web layer renders a skip's reason without retyping the
|
||||
// wire string (issue #145); the values are storage and page-stable.
|
||||
SkipPaused = "paused" // the pause row was read at the top
|
||||
SkipRefusing = "refusing" // refusal backoff
|
||||
SkipSidecarDown = "sidecar-down" // a sibling browser Lane lost Chrome
|
||||
SkipNoFetcher = "no-fetcher" // browser Site, no browser configured, no fallback
|
||||
SkipDueQuery = "due-query" // the due query failed
|
||||
SkipAsleep = "asleep" // under both browser wake thresholds
|
||||
SkipEligibleCount = "eligible-count" // the eligible count failed
|
||||
SkipNothingEligible = "nothing-eligible" // nothing eligible; sleeps a full rest
|
||||
)
|
||||
|
||||
// readOutcome classifies one Series read for the pass row's outcome counts
|
||||
// (issue #141). The classification the read already makes is counted, never a
|
||||
// second taxonomy: refused is the Site holding a challenge, unreachable the
|
||||
// browser interrupting, noChapter a 200 with real HTML but no chapter links,
|
||||
// unfetchable the host pin or a missing fetcher, notFound a 4xx other than
|
||||
// the 403 refusal — the Site answered with a client status — and errors
|
||||
// everything else.
|
||||
type readOutcome int
|
||||
|
||||
const (
|
||||
outcomeSuccess readOutcome = iota
|
||||
outcomeRefused
|
||||
outcomeUnreachable
|
||||
outcomeNoChapter
|
||||
outcomeUnfetchable
|
||||
outcomeError
|
||||
outcomeNotFound
|
||||
)
|
||||
// word returns the wire spelling this outcome stores in poll_failures — the
|
||||
// same strings the pass log's columns use (C1, issue #164). Success, refusal
|
||||
// and browser loss return "" so recordFailure's "no statement" case is one
|
||||
// return: a challenge or a lost sidecar is no evidence about any particular
|
||||
// Series (ADR-0016).
|
||||
func (o readOutcome) word() string {
|
||||
switch o {
|
||||
case outcomeNotFound:
|
||||
return "not_found"
|
||||
case outcomeNoChapter:
|
||||
return "no_chapter"
|
||||
case outcomeUnfetchable:
|
||||
return "unfetchable"
|
||||
case outcomeError:
|
||||
return "errors"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// outcomeCounts are the six named outcome counts of one pass. A success
|
||||
// count is derived, never stored: checked minus the five named failures,
|
||||
// with unreachable excluded because the sidecar-loss path returns before the
|
||||
// checked counter increments (issue #141).
|
||||
type outcomeCounts struct {
|
||||
refused, unreachable, noChapter, unfetchable, errors, notFound int
|
||||
}
|
||||
|
||||
func (c *outcomeCounts) add(o readOutcome) {
|
||||
switch o {
|
||||
case outcomeRefused:
|
||||
c.refused++
|
||||
case outcomeUnreachable:
|
||||
c.unreachable++
|
||||
case outcomeNoChapter:
|
||||
c.noChapter++
|
||||
case outcomeUnfetchable:
|
||||
c.unfetchable++
|
||||
case outcomeNotFound:
|
||||
c.notFound++
|
||||
case outcomeError:
|
||||
c.errors++
|
||||
}
|
||||
}
|
||||
|
||||
// passRecord is what one pass's durable row will be: the skip value and
|
||||
// outcome counts filled in along the pass's return path. recordPass assembles
|
||||
// the row, so every exit records exactly once.
|
||||
type passRecord struct {
|
||||
site string
|
||||
ranAt int64
|
||||
skip string
|
||||
counts outcomeCounts
|
||||
}
|
||||
|
||||
// lanePassRetention is how far back a Lane's pass log is kept. It is not the
|
||||
// display window: retention is how far back a question can reach, and the
|
||||
// window is what the owner is shown (issue #139).
|
||||
const lanePassRetention = 14 * 24 * time.Hour
|
||||
|
||||
// runLanePass processes one pass of one Site's Lane: select the due Series,
|
||||
// pace through them, and report how long the Lane should wait before its next
|
||||
// pass. paced spaces consecutive fetches by the Site's effective gap — the
|
||||
// production Lane's rate limit; the deterministic test entry runs back to back.
|
||||
func (p *Poller) runLanePass(ctx context.Context, name string, paced bool) time.Duration {
|
||||
now := p.Now()
|
||||
// Durable pass log (issue #141): one row per exit. The figures are filled
|
||||
// in as the pass measures them; a pass that returns before measuring
|
||||
// carries the previous pass's forward inside recordPass.
|
||||
fig := passFigures{}
|
||||
rec := passRecord{site: name, ranAt: now.UnixMilli()}
|
||||
defer func() { p.recordPass(ctx, rec, fig) }()
|
||||
|
||||
// One Lane row read at the top of a pass, serving two gates (issue #139).
|
||||
// Both stamps outlive our process, so the gates read the durable row
|
||||
// rather than memory: a refusal is the Site's mood and a pause the
|
||||
// owner's order, and neither is lost to a restart.
|
||||
pausedUntil, refuseUntil, err := p.Store.LaneGates(name)
|
||||
if err != nil {
|
||||
// Fail open: a store that cannot answer the gate cannot record the
|
||||
// pass either, and one Lane must not stall on its own gate read.
|
||||
log.Printf("latest poll %s: lane gates: %v", name, err)
|
||||
}
|
||||
if pausedUntil > now.UnixMilli() {
|
||||
// Paused ahead of the refusal check: no Series is touched, so the
|
||||
// queue stays intact for when the pause lifts (issue #141, #147).
|
||||
rec.skip = SkipPaused
|
||||
log.Printf("latest poll %s: paused until %s, skipping pass", name, time.UnixMilli(pausedUntil).Format(time.RFC3339))
|
||||
return time.Duration(pausedUntil-now.UnixMilli()) * time.Millisecond
|
||||
}
|
||||
if refuseUntil > now.UnixMilli() {
|
||||
// Snapshot this pass for the owner's page (issue #102). Recorded on every
|
||||
// return path, with the figures filled in where the pass computes them.
|
||||
st := LaneState{Site: name, LastRun: now, Browser: isBrowserSite(name)}
|
||||
defer func() { p.recordLaneState(st) }()
|
||||
if until := p.refusalBackoff(name); now.Before(until) {
|
||||
// Cooling down after a refusal: do not attempt this Site at all.
|
||||
rec.skip = SkipRefusing
|
||||
return time.Duration(refuseUntil-now.UnixMilli()) * time.Millisecond
|
||||
return until.Sub(now)
|
||||
}
|
||||
if isBrowserSite(name) {
|
||||
if downFor, down := p.browserDownFor(now); down && downFor < RefuseBackoff {
|
||||
if downFor, down := p.browserDownFor(now); down && downFor < refuseBackoff {
|
||||
// A sibling browser Lane lost the sidecar within the backoff
|
||||
// window: skip this pass, so a restarting Chrome does not stamp
|
||||
// this Site's Series one pass at a time. After RefuseBackoff the
|
||||
// this Site's Series one pass at a time. After refuseBackoff the
|
||||
// flag decays and the Lane probes again (issue #100, story 20).
|
||||
rec.skip = SkipSidecarDown
|
||||
log.Printf("latest poll %s: browser lane skipping pass (sidecar down %s ago)", name, downFor)
|
||||
return RefuseBackoff - downFor
|
||||
return refuseBackoff - downFor
|
||||
}
|
||||
}
|
||||
s := sites[name]
|
||||
@@ -401,29 +246,24 @@ func (p *Poller) runLanePass(ctx context.Context, name string, paced bool) time.
|
||||
// No fetcher at all right now (browser absent, no fallback): every
|
||||
// Series stays unstamped and due, so a browser that appears after a
|
||||
// restart finds its full queue waiting (issue #100).
|
||||
rec.skip = SkipNoFetcher
|
||||
fig.Gap = defaultGap
|
||||
st.Gap = defaultGap
|
||||
return defaultGap
|
||||
}
|
||||
|
||||
due, err := p.Store.DueForLatestCheck(name, now.Add(-s.Rest).UnixMilli(),
|
||||
now.Add(-sightingCeilingRests*s.Rest).UnixMilli())
|
||||
if err != nil {
|
||||
rec.skip = SkipDueQuery
|
||||
log.Printf("latest poll %s: due query: %v", name, err)
|
||||
fig.Gap = defaultGap
|
||||
st.Gap = defaultGap
|
||||
return defaultGap
|
||||
}
|
||||
fig.Due = len(due)
|
||||
if s.Browser != nil && f == p.BrowserFetch && !browserWakeDue(due, now, s.Rest) && !anyForced(due) {
|
||||
st.Due = len(due)
|
||||
if s.Browser != nil && f == p.BrowserFetch && !browserWakeDue(due, now, s.Rest) {
|
||||
// Below both thresholds Chrome stays asleep (ADR-0005 on-demand
|
||||
// browser): waking it for a single Poll would cost a challenge solve
|
||||
// per request. A forced Series is the one exception — a human asking
|
||||
// is not the machine waking itself (issue #146). The Lane still paces
|
||||
// at the default gap, which is what the owner's page must show rather
|
||||
// than a zero.
|
||||
rec.skip = SkipAsleep
|
||||
fig.Gap = defaultGap
|
||||
// per request. The Lane still paces at the default gap, which is what
|
||||
// the owner's page must show rather than a zero.
|
||||
st.Gap, st.Asleep = defaultGap, true
|
||||
return defaultGap
|
||||
}
|
||||
if s.Browser != nil {
|
||||
@@ -436,22 +276,20 @@ func (p *Poller) runLanePass(ctx context.Context, name string, paced bool) time.
|
||||
}
|
||||
}
|
||||
|
||||
eligible, err := p.countEligible(name)
|
||||
eligible, err := p.Store.EligibleSeriesCount(name)
|
||||
if err != nil {
|
||||
rec.skip = SkipEligibleCount
|
||||
log.Printf("latest poll %s: eligible count: %v", name, err)
|
||||
fig.Gap = defaultGap
|
||||
st.Gap = defaultGap
|
||||
return defaultGap
|
||||
}
|
||||
gap, clamped := effectiveGap(s, eligible)
|
||||
fig.Gap, fig.Clamped = gap, clamped
|
||||
st.Gap, st.Clamped = gap, clamped
|
||||
if clamped {
|
||||
log.Printf("latest poll %s: gap clamped to %s floor (eligible series=%d)", name, minGap, eligible)
|
||||
}
|
||||
if eligible == 0 {
|
||||
// Nothing to poll for the foreseeable future; sleep a full rest instead
|
||||
// of re-querying every gap.
|
||||
rec.skip = SkipNothingEligible
|
||||
return s.Rest
|
||||
}
|
||||
|
||||
@@ -462,7 +300,7 @@ func (p *Poller) runLanePass(ctx context.Context, name string, paced bool) time.
|
||||
}
|
||||
if refusals >= 2 {
|
||||
// This Site refused twice in a row: the remaining Series are left
|
||||
// unstamped and due, and the Lane waits RefuseBackoff before
|
||||
// unstamped and due, and the Lane waits refuseBackoff before
|
||||
// trying it again.
|
||||
break
|
||||
}
|
||||
@@ -476,205 +314,46 @@ func (p *Poller) runLanePass(ctx context.Context, name string, paced bool) time.
|
||||
break
|
||||
}
|
||||
}
|
||||
outcome := p.checkOne(ctx, sr)
|
||||
p.recordFailure(sr, outcome)
|
||||
if outcome == outcomeUnreachable {
|
||||
// The mid-loop browser loss writes an empty skip on purpose: the
|
||||
// pass returns before the checked counter increments, so its row
|
||||
// is stall-shaped (due > 0, checked 0, skip ''), and a stall is
|
||||
// the exact signal this exit produces. A tenth skip value would
|
||||
// make it legible but is deliberately not invented here.
|
||||
rec.counts.add(outcome)
|
||||
p.setBrowserDown(now)
|
||||
log.Printf("latest poll %s: browser unreachable, browser lanes skipping passes for %s", name, RefuseBackoff)
|
||||
return gap
|
||||
}
|
||||
if outcome == outcomeRefused {
|
||||
if err := p.checkOne(ctx, sr); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, errChallengeHeld):
|
||||
refusals++
|
||||
case errors.Is(err, errBrowserInterrupted):
|
||||
p.setBrowserDown(now)
|
||||
log.Printf("latest poll %s: browser unreachable, browser lanes skipping passes for %s", name, refuseBackoff)
|
||||
return gap
|
||||
default:
|
||||
refusals = 0
|
||||
}
|
||||
} else {
|
||||
refusals = 0
|
||||
}
|
||||
rec.counts.add(outcome)
|
||||
fig.Checked++
|
||||
st.Checked++
|
||||
}
|
||||
if fig.Checked > 0 {
|
||||
log.Printf("latest poll %s: due=%d checked=%d", name, len(due), fig.Checked)
|
||||
if st.Checked > 0 {
|
||||
log.Printf("latest poll %s: due=%d checked=%d", name, len(due), st.Checked)
|
||||
}
|
||||
if refusals >= 2 {
|
||||
// The refusal outlives the process: the durable stamp gates a restart,
|
||||
// so a Site that just told us to back off is not re-probed.
|
||||
if err := p.Store.SetLaneRefusal(name, now.Add(RefuseBackoff).UnixMilli()); err != nil {
|
||||
log.Printf("latest poll %s: persist refusal: %v", name, err)
|
||||
}
|
||||
log.Printf("latest poll %s: refused twice this run, waiting %s", name, RefuseBackoff)
|
||||
return RefuseBackoff
|
||||
p.setRefusalBackoff(name, now.Add(refuseBackoff))
|
||||
log.Printf("latest poll %s: refused twice this run, waiting %s", name, refuseBackoff)
|
||||
return refuseBackoff
|
||||
}
|
||||
return gap
|
||||
}
|
||||
|
||||
// passFigures are the numbers one pass measured for its durable row (issue
|
||||
// #141): due and checked as the pass saw them, the pace it chose, and whether
|
||||
// the gap sat on the floor. A pass that returned before measuring keeps the
|
||||
// previous pass's figures via carry-forward in recordPass; the in-memory
|
||||
// snapshot those once mirrored into is gone — the page reads the durable row
|
||||
// now (issue #145).
|
||||
type passFigures struct {
|
||||
Due, Checked int
|
||||
Gap time.Duration
|
||||
Clamped bool
|
||||
func (p *Poller) refusalBackoff(name string) time.Time {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
return p.refuseUntil[name]
|
||||
}
|
||||
|
||||
// recordPass writes the durable row for one pass (issue #141). Called deferred
|
||||
// from runLanePass so every return path records exactly one row. A pass that
|
||||
// never computed its own figures — its gap is zero — carries the previous
|
||||
// pass's due, gap, clamped and checked forward rather than stating zeroes it
|
||||
// did not measure; the skip column says why it declined, so the zeroes that
|
||||
// remain (due-query, no-fetcher) read as explanations rather than
|
||||
// measurements. Once the row is durable, the owner-notice judgement runs
|
||||
// beside it (issue #171).
|
||||
func (p *Poller) recordPass(ctx context.Context, rec passRecord, fig passFigures) {
|
||||
row := store.LanePass{
|
||||
Site: rec.site,
|
||||
RanAt: rec.ranAt,
|
||||
Skip: rec.skip,
|
||||
Due: fig.Due,
|
||||
Checked: fig.Checked,
|
||||
GapMS: fig.Gap.Milliseconds(),
|
||||
Clamped: fig.Clamped,
|
||||
Refused: rec.counts.refused,
|
||||
Unreachable: rec.counts.unreachable,
|
||||
NoChapter: rec.counts.noChapter,
|
||||
Unfetchable: rec.counts.unfetchable,
|
||||
NotFound: rec.counts.notFound,
|
||||
Errors: rec.counts.errors,
|
||||
func (p *Poller) setRefusalBackoff(name string, until time.Time) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.refuseUntil == nil {
|
||||
p.refuseUntil = make(map[string]time.Time)
|
||||
}
|
||||
if row.GapMS == 0 {
|
||||
// The pass never computed a gap, so it has no figures of its own:
|
||||
// carry the previous pass's, in one latest-per-Site read — the
|
||||
// recorder needs one Site, not six (issue #139).
|
||||
if prev, ok, err := p.Store.LatestLanePass(rec.site); err != nil {
|
||||
log.Printf("latest poll %s: previous pass: %v", rec.site, err)
|
||||
} else if ok {
|
||||
row.Due, row.Checked = prev.Due, prev.Checked
|
||||
row.GapMS, row.Clamped = prev.GapMS, prev.Clamped
|
||||
}
|
||||
}
|
||||
if err := p.Store.RecordLanePass(row, rec.ranAt-lanePassRetention.Milliseconds()); err != nil {
|
||||
log.Printf("latest poll %s: record lane pass: %v", rec.site, err)
|
||||
return
|
||||
}
|
||||
p.ownerNotices(ctx, row)
|
||||
}
|
||||
|
||||
// ownerNotices judges the owner-notice conditions for the pass just recorded
|
||||
// and fires (issue #171). It sits in recordPass because that deferred call is
|
||||
// the one place every return path passes through: three of the four
|
||||
// conditions occur on early returns and the success path can never see them.
|
||||
// The judgement reads the whole pass log plus three derived reads — the
|
||||
// other Lanes' latest passes, each Site's refusing-run start, its last
|
||||
// sidecar-reaching pass, and its no-chapter share — so one pass judges every
|
||||
// condition (issue #172). Per fault: NoticeSent → send → MarkNoticeSent, so
|
||||
// a fault lasting a month sends one message, not one per pass; a condition
|
||||
// absent from this pass's fault list forgets its episode, so the next
|
||||
// occurrence sends again. Everything here is best-effort: a failed send, a
|
||||
// failed store read and a failed notice write are all logged and never
|
||||
// change the pass's outcome counts or its return value. The clear runs even
|
||||
// when Notify is nil, so a deployment that turns the webhook off does not
|
||||
// leave stale rows that suppress the first real notice after it is turned
|
||||
// back on.
|
||||
func (p *Poller) ownerNotices(ctx context.Context, row store.LanePass) {
|
||||
now := p.Now()
|
||||
in := FaultInput{Passes: []store.LanePass{row}}
|
||||
// Each read fails independently: a failure logs and contributes no fault,
|
||||
// never a false one.
|
||||
if passes, err := p.Store.LatestLanePasses(); err != nil {
|
||||
log.Printf("latest poll %s: latest lane passes: %v", row.Site, err)
|
||||
} else {
|
||||
in.Passes = passes
|
||||
}
|
||||
if since, err := p.Store.RefusingSince(now.UnixMilli()); err != nil {
|
||||
log.Printf("latest poll %s: refusing since: %v", row.Site, err)
|
||||
} else {
|
||||
in.RefusingSince = since
|
||||
}
|
||||
if ok, err := p.Store.SidecarOK(browserBackedSites()); err != nil {
|
||||
log.Printf("latest poll %s: sidecar ok: %v", row.Site, err)
|
||||
} else {
|
||||
in.SidecarOK = ok
|
||||
}
|
||||
if share, err := p.Store.NoChapterShare(now.Add(-OwnerWindow).UnixMilli()); err != nil {
|
||||
log.Printf("latest poll %s: no-chapter share: %v", row.Site, err)
|
||||
} else {
|
||||
in.NoChapterShare = share
|
||||
}
|
||||
faults := FaultsFrom(in, now)
|
||||
bySite := make(map[string]store.LanePass, len(in.Passes))
|
||||
for _, pass := range in.Passes {
|
||||
bySite[pass.Site] = pass
|
||||
}
|
||||
for _, f := range faults {
|
||||
if p.Notify == nil {
|
||||
continue
|
||||
}
|
||||
sent, err := p.Store.NoticeSent(f.Condition, f.Site)
|
||||
if err != nil {
|
||||
log.Printf("latest poll %s: notice sent: %v", row.Site, err)
|
||||
continue
|
||||
}
|
||||
if sent {
|
||||
continue
|
||||
}
|
||||
// The fault's own Site's pass renders its sentence — a stall judged
|
||||
// from another Lane's pass must not quote this pass's figures.
|
||||
pass, ok := bySite[f.Site]
|
||||
if !ok {
|
||||
pass = row
|
||||
}
|
||||
sentence, href := noticeFor(f, pass, now)
|
||||
if err := p.Notify.Notify(ctx, f, sentence, href); err != nil {
|
||||
// The stamp stays unset: no queue, no backoff — the condition is
|
||||
// durable, so the next pass tries again while it holds.
|
||||
log.Printf("latest poll %s: owner notice %s: %v", row.Site, f.Condition, err)
|
||||
continue
|
||||
}
|
||||
if err := p.Store.MarkNoticeSent(f.Condition, f.Site, now.UnixMilli()); err != nil {
|
||||
log.Printf("latest poll %s: mark notice sent: %v", row.Site, err)
|
||||
}
|
||||
}
|
||||
for _, cond := range ownerNoticeConditions {
|
||||
if !hasFault(faults, cond, row.Site) {
|
||||
if err := p.Store.ClearNotice(cond, row.Site); err != nil {
|
||||
log.Printf("latest poll %s: clear owner notice: %v", row.Site, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
// sidecar-down suppresses under the empty Site — one row across all
|
||||
// browser Lanes (AC4) — so clear that row when it is absent from this
|
||||
// pass's fault list, and a lifted sidecar fires again when it returns.
|
||||
if !hasFault(faults, ConditionSidecarDown, "") {
|
||||
if err := p.Store.ClearNotice(ConditionSidecarDown, ""); err != nil {
|
||||
log.Printf("latest poll %s: clear owner notice: %v", row.Site, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// hasFault reports whether faults hold the given condition for the site.
|
||||
func hasFault(faults []Fault, condition, site string) bool {
|
||||
for _, f := range faults {
|
||||
if f.Condition == condition && f.Site == site {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// countEligible routes the eligible count through the test seam when one is
|
||||
// set, else the store.
|
||||
func (p *Poller) countEligible(site string) (int, error) {
|
||||
if p.eligibleCount != nil {
|
||||
return p.eligibleCount(site)
|
||||
}
|
||||
return p.Store.EligibleSeriesCount(site)
|
||||
p.refuseUntil[name] = until
|
||||
}
|
||||
|
||||
// setBrowserDown records when a browser Lane lost the sidecar. It is Poller
|
||||
@@ -687,7 +366,7 @@ func (p *Poller) setBrowserDown(now time.Time) {
|
||||
|
||||
// browserDownFor reports how long the sidecar has been down and that it is
|
||||
// down at all — the zero time means never down, which must not read as a
|
||||
// zero-duration loss. The window decays: once RefuseBackoff passes without a
|
||||
// zero-duration loss. The window decays: once refuseBackoff passes without a
|
||||
// fresh loss, Lanes probe again.
|
||||
func (p *Poller) browserDownFor(now time.Time) (time.Duration, bool) {
|
||||
p.mu.Lock()
|
||||
@@ -716,19 +395,6 @@ func browserWakeDue(due []store.Series, now time.Time, rest time.Duration) bool
|
||||
return maxSeriesWait(due, now, rest) >= browserWakeAge
|
||||
}
|
||||
|
||||
// anyForced reports whether the due list holds a forced Series: one whose
|
||||
// owner check-now request (issue #146) has not been answered yet. A human
|
||||
// asking wakes a sleeping Chrome even below the wake thresholds; the request
|
||||
// itself still ages visibly if the home machine is off.
|
||||
func anyForced(due []store.Series) bool {
|
||||
for _, sr := range due {
|
||||
if sr.Forced {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// maxSeriesWait returns how long the most-overdue of the due Series has been
|
||||
// waiting past its due moment (0 when due is empty).
|
||||
func maxSeriesWait(due []store.Series, now time.Time, rest time.Duration) time.Duration {
|
||||
@@ -740,40 +406,16 @@ func maxSeriesWait(due []store.Series, now time.Time, rest time.Duration) time.D
|
||||
}
|
||||
return oldest
|
||||
}
|
||||
// recordFailure keeps one Series' failure row in step with its read
|
||||
// (ADR-0016): a failure word is upserted, a successful read deletes the row,
|
||||
// and refused or unreachable issue no statement at all. Called for every
|
||||
// outcome from the pass loop, so the four failure words and the success path
|
||||
// share one write point, and a forced Poll that reads the page clears through
|
||||
// the ordinary success path — no branch of its own. Log a store failure and
|
||||
// carry on: this is best-effort, and no single bad Series may stall a Lane.
|
||||
func (p *Poller) recordFailure(sr store.Series, outcome readOutcome) {
|
||||
if outcome == outcomeSuccess {
|
||||
if err := p.Store.ClearSeriesFailure(sr.Site, sr.SeriesID); err != nil {
|
||||
log.Printf("latest poll %q: clear failure: %v", sr.Key(), err)
|
||||
}
|
||||
return
|
||||
}
|
||||
word := outcome.word()
|
||||
if word == "" {
|
||||
return
|
||||
}
|
||||
if err := p.Store.RecordSeriesFailure(sr.Site, sr.SeriesID, word, p.Now().UnixMilli()); err != nil {
|
||||
log.Printf("latest poll %q: record failure: %v", sr.Key(), err)
|
||||
}
|
||||
}
|
||||
|
||||
// checkOne re-checks one series. Every failure path here is "log and move on":
|
||||
// the poller is a best-effort enhancement, and no single bad series may stall a
|
||||
// Lane or take down the process. The returned outcome classifies the read for
|
||||
// the pass row (issue #141), so the Lane can count a refusal, a lost browser,
|
||||
// a chapter-less page, an unfetchable address, a missing page or a transport
|
||||
// error without re-deriving the taxonomy.
|
||||
func (p *Poller) checkOne(ctx context.Context, sr store.Series) (outcome readOutcome) {
|
||||
// Lane or take down the process. The returned error is the page read's
|
||||
// classified outcome so the Lane can tell a refusal from a loss of the
|
||||
// browser; non-classified failures still return nil-equivalent behaviour.
|
||||
func (p *Poller) checkOne(ctx context.Context, sr store.Series) error {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
log.Printf("latest poll %q: recovered from panic: %v", sr.Key(), r)
|
||||
outcome = outcomeError
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -785,7 +427,7 @@ func (p *Poller) checkOne(ctx context.Context, sr store.Series) (outcome readOut
|
||||
// the stamp means "attempted", and an untried Series stays due.
|
||||
if err := p.Store.MarkLatestChecked(sr.Site, sr.SeriesID, p.Now().UnixMilli()); err != nil {
|
||||
log.Printf("latest poll %q: mark checked: %v", sr.Key(), err)
|
||||
return outcomeError
|
||||
return nil
|
||||
}
|
||||
|
||||
facts, err := readSeriesPage(ctx, sr.Site, sr.SeriesURL, p.BrowserFetch, p.Fetch)
|
||||
@@ -796,61 +438,28 @@ func (p *Poller) checkOne(ctx context.Context, sr store.Series) (outcome readOut
|
||||
// passes the gate is retried at rest pace rather than
|
||||
// hot-looping.
|
||||
log.Printf("latest poll %q: not fetchable: site=%q url=%q", sr.Key(), sr.Site, sr.SeriesURL)
|
||||
return outcomeUnfetchable
|
||||
return err
|
||||
case errors.Is(err, errNoFetcher):
|
||||
log.Printf("latest poll %q: no fetcher for site %q", sr.Key(), sr.Site)
|
||||
return outcomeUnfetchable
|
||||
return err
|
||||
}
|
||||
// A legacy cover heals independently of the page read: its source may
|
||||
// answer — a CDN — while the origin does not, so a fetch failure does
|
||||
// not skip the heal, matching the order the shared read replaced.
|
||||
p.healCover(ctx, sr)
|
||||
log.Printf("latest poll %q: %v", sr.Key(), err)
|
||||
if errors.Is(err, errChallengeHeld) {
|
||||
return outcomeRefused
|
||||
}
|
||||
if errors.Is(err, errBrowserInterrupted) {
|
||||
return outcomeUnreachable
|
||||
}
|
||||
if errors.Is(err, errNotFound) {
|
||||
return outcomeNotFound
|
||||
}
|
||||
return outcomeError
|
||||
return err
|
||||
}
|
||||
// A legacy cover source is healed independently of the page read.
|
||||
p.healCover(ctx, sr)
|
||||
// Cover fill is independent of the chapter signal: a page that lost its
|
||||
// chapter list may keep its og:image, and a blank Series heals either way.
|
||||
// A forced pass writes the Cover through the replace path instead.
|
||||
if sr.Forced {
|
||||
p.replaceCover(ctx, sr, facts.Cover)
|
||||
} else {
|
||||
p.fillBlankCover(ctx, sr, facts.Cover)
|
||||
}
|
||||
|
||||
// Learned from the successful read: the write sits after the error switch
|
||||
// (a refused, unreachable or errored read reaches nothing) and before the
|
||||
// returns below — a completed page whose chapter number did not change
|
||||
// still has to write. The transition is zero-versus-nonzero, not the
|
||||
// stamp's value: a Series still completed keeps its original stamp, so the
|
||||
// age #170 prints is "since the Site first said so"; one that stopped
|
||||
// being completed is zeroed.
|
||||
stamp := int64(0)
|
||||
if facts.SiteCompleted {
|
||||
stamp = p.Now().UnixMilli()
|
||||
}
|
||||
if (sr.SiteCompletedAt == 0) != (stamp == 0) {
|
||||
if err := p.Store.SetSiteCompletedAt(sr.Site, sr.SeriesID, stamp); err != nil {
|
||||
// Best-effort, like every poller write: never change the outcome
|
||||
// word the pass counts.
|
||||
log.Printf("latest poll %q: set site completed: %v", sr.Key(), err)
|
||||
}
|
||||
}
|
||||
if !facts.HasLatest {
|
||||
// Most likely a challenge page or a layout change. Either way the row is
|
||||
// already stamped, so this waits out a rest instead of hot-looping.
|
||||
log.Printf("latest poll %q: no chapter links in %d bytes", sr.Key(), facts.BodyLen)
|
||||
return outcomeNoChapter
|
||||
return nil
|
||||
}
|
||||
|
||||
// The Poll is the oracle for whatever Sighting last raised this Series
|
||||
@@ -863,7 +472,7 @@ func (p *Poller) checkOne(ctx context.Context, sr store.Series) (outcome readOut
|
||||
// against the due-query snapshot; a concurrent write in between only costs
|
||||
// one redundant UPDATE of the same absolute value, never a wrong one.
|
||||
if sr.LatestChapterNum != nil && *sr.LatestChapterNum == facts.Latest.Num {
|
||||
return outcomeSuccess
|
||||
return nil
|
||||
}
|
||||
|
||||
// Series-level write: the row is shared, so one update refreshes every
|
||||
@@ -872,10 +481,10 @@ func (p *Poller) checkOne(ctx context.Context, sr store.Series) (outcome readOut
|
||||
// the list.
|
||||
if err := p.Store.SetLatestChapter(sr.Site, sr.SeriesID, facts.Latest.Label, facts.Latest.Num); err != nil {
|
||||
log.Printf("latest poll %q: set latest chapter: %v", sr.Key(), err)
|
||||
return outcomeError
|
||||
return nil
|
||||
}
|
||||
log.Printf("latest poll %q: latest is now %s", sr.Key(), facts.Latest.Label)
|
||||
return outcomeSuccess
|
||||
return nil
|
||||
}
|
||||
|
||||
// judgeSighting settles the Sighting the Series' stored Latest Chapter is owed
|
||||
@@ -934,7 +543,7 @@ func (p *Poller) waitCovers() {
|
||||
p.coverWG.Wait()
|
||||
}
|
||||
|
||||
// FetchableSeriesURL reports whether site is a Site the registry knows and
|
||||
// fetchableSeriesURL reports whether site is a Site the registry knows and
|
||||
// seriesURL is safe to hand to a fetcher: an https URL whose host matches the
|
||||
// Site's pinned hostname exactly. series_url comes from client-supplied PUT
|
||||
// bodies, so this is a defence against the poller being used to probe
|
||||
@@ -943,11 +552,7 @@ func (p *Poller) waitCovers() {
|
||||
// browser Site guards a control that executes JavaScript and carries cookies,
|
||||
// a parser Site guards a wasted request — but the rule is one rule, from the
|
||||
// registry.
|
||||
//
|
||||
// The owner's series URL repair (issue #151) is a second caller: the web
|
||||
// layer validates with this same gate before storing a repair, so there is
|
||||
// never a second copy of it.
|
||||
func FetchableSeriesURL(site, seriesURL string) bool {
|
||||
func fetchableSeriesURL(site, seriesURL string) bool {
|
||||
s, known := sites[site]
|
||||
if !known {
|
||||
return false
|
||||
|
||||
+100
-2174
File diff suppressed because it is too large
Load Diff
@@ -6,19 +6,15 @@ import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// seriesRead carries the facts the poll and the acquirer both extract from a
|
||||
// series page. Persistence, stamps and scheduling stay with the callers, so
|
||||
// the policies that keep the two flows distinct (stamp order, rests) are not
|
||||
// swallowed by the module.
|
||||
// seriesRead carries the two facts the poll and the acquirer both extract
|
||||
// from a series page. Persistence, stamps and scheduling stay with the
|
||||
// callers, so the policies that keep the two flows distinct (stamp order,
|
||||
// rests) are not swallowed by the module.
|
||||
type seriesRead struct {
|
||||
Latest latestChapter
|
||||
HasLatest bool
|
||||
Cover string
|
||||
HasCover bool
|
||||
// SiteCompleted is whether the Site's own completed value was on the page.
|
||||
// A challenge body and a redesign both read false — an absent hint, never
|
||||
// a claim (issue #168).
|
||||
SiteCompleted bool
|
||||
// BodyLen is the fetched body's length, surfaced because the no-chapter
|
||||
// log uses it to tell a markup change from a body the size cap cut short.
|
||||
BodyLen int
|
||||
@@ -29,18 +25,15 @@ type seriesRead struct {
|
||||
// errChallengeHeld (browser.go) is the outcome of a Site that answered with
|
||||
// its interstitial — status 403 (cf-mitigated) or a challenge page body — and
|
||||
// is how a Lane tells a refusal from an ordinary failure (issue #100).
|
||||
// errNotFound marks any other 4xx: the page is gone — a fact the owner can act
|
||||
// on — as distinct from a Site or database that is merely unwell (issue #164).
|
||||
var (
|
||||
errNotFetchable = errors.New("series url not fetchable")
|
||||
errNoFetcher = errors.New("no fetcher for site")
|
||||
errNotFound = errors.New("series page not found")
|
||||
)
|
||||
|
||||
// readSeriesPage performs the series-page read the poll and the acquirer have
|
||||
// in common: gate the address, choose the route, fetch the page, extract the
|
||||
// Latest Chapter, the Cover address and the Site's completed value. It
|
||||
// persists nothing and stamps nothing.
|
||||
// Latest Chapter and the Cover address. It persists nothing and stamps
|
||||
// nothing.
|
||||
//
|
||||
// series_url arrives in a client-supplied PUT body (PUT /bookmarks/{key}
|
||||
// accepts any string), so the gate is not an optimisation against burning a
|
||||
@@ -48,7 +41,7 @@ var (
|
||||
// its own network position to whatever URL a token-holder writes, including
|
||||
// link-local/internal addresses or non-https schemes.
|
||||
func readSeriesPage(ctx context.Context, site, seriesURL string, browser, tls Fetcher) (seriesRead, error) {
|
||||
if !FetchableSeriesURL(site, seriesURL) {
|
||||
if !fetchableSeriesURL(site, seriesURL) {
|
||||
return seriesRead{}, fmt.Errorf("%w: site=%q url=%q", errNotFetchable, site, seriesURL)
|
||||
}
|
||||
f := fetcherFor(site, browser, tls)
|
||||
@@ -66,9 +59,6 @@ func readSeriesPage(ctx context.Context, site, seriesURL string, browser, tls Fe
|
||||
return seriesRead{}, fmt.Errorf("%w: fetch %s: status %d", errChallengeHeld, seriesURL, status)
|
||||
}
|
||||
if status != 200 {
|
||||
if status >= 400 && status < 500 {
|
||||
return seriesRead{}, fmt.Errorf("%w: fetch %s: status %d", errNotFound, seriesURL, status)
|
||||
}
|
||||
return seriesRead{}, fmt.Errorf("fetch %s: status %d", seriesURL, status)
|
||||
}
|
||||
if isInterstitial(body) {
|
||||
@@ -79,12 +69,5 @@ func readSeriesPage(ctx context.Context, site, seriesURL string, browser, tls Fe
|
||||
}
|
||||
latest, hasLatest := latestChapterFrom(site, seriesURL, body)
|
||||
cover, hasCover := coverFrom(site, seriesURL, body)
|
||||
return seriesRead{
|
||||
Latest: latest,
|
||||
HasLatest: hasLatest,
|
||||
Cover: cover,
|
||||
HasCover: hasCover,
|
||||
SiteCompleted: siteCompletedFrom(site, seriesURL, body),
|
||||
BodyLen: len(body),
|
||||
}, nil
|
||||
return seriesRead{Latest: latest, HasLatest: hasLatest, Cover: cover, HasCover: hasCover, BodyLen: len(body)}, nil
|
||||
}
|
||||
|
||||
@@ -22,10 +22,10 @@ type latestChapter struct {
|
||||
|
||||
// site answers the fixed questions every series-page read asks of its Site
|
||||
// (ADR-0009): the host its addresses must carry, how to find the Latest
|
||||
// Chapter and the Cover address in a body, whether the Site calls the work
|
||||
// completed, and — for a Site behind a JavaScript challenge — how to read its
|
||||
// payload from a cleared tab. One entry describes everything about one Site,
|
||||
// and nowhere else gets to compare the site string.
|
||||
// Chapter and the Cover address in a body, and — for a Site behind a
|
||||
// JavaScript challenge — how to read its payload from a cleared tab. One
|
||||
// entry describes everything about one Site, and nowhere else gets to compare
|
||||
// the site string.
|
||||
type site struct {
|
||||
// Host is the exact hostname a series_url for this Site must carry.
|
||||
Host string
|
||||
@@ -33,10 +33,6 @@ type site struct {
|
||||
LatestChapter func(seriesURL, body string) (latestChapter, bool)
|
||||
// Cover finds the Cover address in a fetched body.
|
||||
Cover func(seriesURL, body string) (string, bool)
|
||||
// Completed reports whether this body carries the Site's own completed
|
||||
// value. False for a body that carries any other value, and false for a
|
||||
// failed extraction — never an error and never a third state.
|
||||
Completed func(seriesURL, body string) bool
|
||||
// Rest is how long a Series of this Site rests between Polls.
|
||||
Rest time.Duration
|
||||
// Gap is the Lane's strictest pace: at least one second must pass between
|
||||
@@ -50,7 +46,7 @@ type site struct {
|
||||
type browserRead struct {
|
||||
// Read builds the tab read for seriesURL, refusing (false) an address
|
||||
// this Site will not open in a browser — the per-Site half of the SSRF
|
||||
// gate, kept deliberately behind FetchableSeriesURL: a headless browser
|
||||
// gate, kept deliberately behind fetchableSeriesURL: a headless browser
|
||||
// executes JavaScript and carries cookies, and series_url is
|
||||
// client-supplied.
|
||||
Read func(seriesURL string, out *string) (chromedp.Action, bool)
|
||||
@@ -303,65 +299,43 @@ func kaganeCoverURL(body string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// comixDetailQuery returns the ["manga","detail","<id>"] query entry of
|
||||
// comix's initial-data JSON, or nil. The cover and completed reads share the
|
||||
// scoped lookup so a "recommended" strip entry can never contribute either
|
||||
// answer.
|
||||
func comixDetailQuery(seriesURL, body string) json.RawMessage {
|
||||
func comixCoverURL(seriesURL, body string) string {
|
||||
id, ok := comixSeriesID(seriesURL)
|
||||
if !ok {
|
||||
return nil
|
||||
return ""
|
||||
}
|
||||
data := comixInitialDataRe.FindStringSubmatch(body)
|
||||
if data == nil {
|
||||
return nil
|
||||
return ""
|
||||
}
|
||||
var state struct {
|
||||
Queries map[string]json.RawMessage `json:"queries"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(data[1]), &state); err != nil {
|
||||
return nil
|
||||
}
|
||||
return state.Queries[`["manga","detail","`+id+`"]`]
|
||||
}
|
||||
|
||||
func comixCoverURL(seriesURL, body string) string {
|
||||
detail := comixDetailQuery(seriesURL, body)
|
||||
if len(detail) == 0 {
|
||||
return ""
|
||||
}
|
||||
var entry struct {
|
||||
raw := state.Queries[`["manga","detail","`+id+`"]`]
|
||||
if len(raw) == 0 {
|
||||
return ""
|
||||
}
|
||||
var detail struct {
|
||||
Poster struct {
|
||||
Medium string `json:"medium"`
|
||||
} `json:"poster"`
|
||||
}
|
||||
if err := json.Unmarshal(detail, &entry); err != nil {
|
||||
if err := json.Unmarshal(raw, &detail); err != nil {
|
||||
return ""
|
||||
}
|
||||
return publishedCoverURL(entry.Poster.Medium)
|
||||
return publishedCoverURL(detail.Poster.Medium)
|
||||
}
|
||||
|
||||
// ogImageCover reads the og:image metadata shared by demonic and
|
||||
// ogImageCover reads the og:image metadata shared by asura, demonic and
|
||||
// lightnovelworld.
|
||||
func ogImageCover(_, body string) (string, bool) {
|
||||
cover := metaContent(body, "property", "og:image")
|
||||
return cover, cover != ""
|
||||
}
|
||||
|
||||
// asuraCoverRe reads coverUrl from the astro-island props, in both quote forms
|
||||
// asuraStatusRe accepts. asura's og:image stopped being the cover (seen
|
||||
// 2026-12-04): it is now a 1200x630 social card on asurascans.com itself,
|
||||
// which also challenges every fetch without a Chrome TLS fingerprint.
|
||||
var asuraCoverRe = regexp.MustCompile(`(?:"|")coverUrl(?:"|"):\[0,(?:"|")(https://[^&"]+)`)
|
||||
|
||||
func asuraCover(_, body string) (string, bool) {
|
||||
m := asuraCoverRe.FindStringSubmatch(body)
|
||||
if m == nil {
|
||||
return "", false
|
||||
}
|
||||
return m[1], true
|
||||
}
|
||||
|
||||
func novelfullCoverEntry(_, body string) (string, bool) {
|
||||
cover := metaContent(body, "name", "image")
|
||||
return cover, cover != ""
|
||||
@@ -386,87 +360,6 @@ func coverFrom(site, seriesURL, body string) (string, bool) {
|
||||
return "", false
|
||||
}
|
||||
|
||||
// asuraStatusRe matches the status value inside the escaped astro-island
|
||||
// props blob, in both the " form the served document carries and the "
|
||||
// form a decoded copy would. "completed" is the only true value: "dropped"
|
||||
// is scanlation editorial (the work itself continues elsewhere) and hiatus is
|
||||
// its own value.
|
||||
var asuraStatusRe = regexp.MustCompile(`(?:"|")status(?:"|"):\[0,(?:"|")completed(?:"|")\]`)
|
||||
|
||||
func asuraCompleted(_, body string) bool {
|
||||
return asuraStatusRe.MatchString(body)
|
||||
}
|
||||
|
||||
// demonicStatusRe matches the info block's status pair: a Status label <li>
|
||||
// immediately followed by the value <li>. The site's whole status vocabulary
|
||||
// is {Ongoing, Completed} (its advanced-search status filter), so the literal
|
||||
// Completed value is the entire signal.
|
||||
var demonicStatusRe = regexp.MustCompile(`<li[^>]*>\s*Status\s*</li>\s*<li[^>]*>\s*Completed\s*</li>`)
|
||||
|
||||
func demonicCompleted(_, body string) bool {
|
||||
return demonicStatusRe.MatchString(body)
|
||||
}
|
||||
|
||||
// comixCompleted reads "status" from the scoped detail entry only;
|
||||
// "finished" is the completed value, and on_hiatus and discontinued are
|
||||
// distinct values.
|
||||
func comixCompleted(seriesURL, body string) bool {
|
||||
detail := comixDetailQuery(seriesURL, body)
|
||||
if len(detail) == 0 {
|
||||
return false
|
||||
}
|
||||
var entry struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
if err := json.Unmarshal(detail, &entry); err != nil {
|
||||
return false
|
||||
}
|
||||
return entry.Status == "finished"
|
||||
}
|
||||
|
||||
// kaganeCompleted reads publication_status only: upload_status is the
|
||||
// release's state, and the two provably diverge ('Cause Calypso Can,
|
||||
// 2026-08-19: publication Ongoing, upload Hiatus), so a Completed upload
|
||||
// must never read as a Completed work.
|
||||
func kaganeCompleted(_, body string) bool {
|
||||
var series struct {
|
||||
PublicationStatus string `json:"publication_status"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(body), &series); err != nil {
|
||||
return false
|
||||
}
|
||||
return series.PublicationStatus == "Completed"
|
||||
}
|
||||
|
||||
// novelfullStatusRe matches the info panel's status link. The page's whole
|
||||
// status vocabulary is {Ongoing, Completed} (the "OnGoing" spelling aliases
|
||||
// "Ongoing" on the taxonomy), so the Completed href is the signal.
|
||||
var novelfullStatusRe = regexp.MustCompile(`href="/status/Completed"`)
|
||||
|
||||
func novelfullCompleted(_, body string) bool {
|
||||
return novelfullStatusRe.MatchString(body)
|
||||
}
|
||||
|
||||
// lnwCompleted matches creativeWorkStatus in the head's JSON-LD block. The
|
||||
// whole body is scanned and the comment marker is not required, unlike
|
||||
// lnwLatestChapter: the status block sits ahead of the visitor-writable
|
||||
// thread, and hiatus maps to a distinct PotentialActionStatus value.
|
||||
var lnwStatusRe = regexp.MustCompile(`"creativeWorkStatus"\s*:\s*"https://schema\.org/CompletedActionStatus"`)
|
||||
|
||||
func lnwCompleted(_, body string) bool {
|
||||
return lnwStatusRe.MatchString(body)
|
||||
}
|
||||
|
||||
// siteCompletedFrom reports whether the Site calls this work completed, via
|
||||
// the Site's registry entry. False for an unknown site, a challenge body and
|
||||
// a redesign alike: an absent hint, never a claim.
|
||||
func siteCompletedFrom(site, seriesURL, body string) bool {
|
||||
if fn := sites[site].Completed; fn != nil {
|
||||
return fn(seriesURL, body)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// metaContent returns the content of the first <meta> whose attrName is
|
||||
// attrValue. It keeps scanning after an empty match so a later published cover
|
||||
// is not hidden by an empty tag.
|
||||
@@ -508,10 +401,9 @@ const (
|
||||
// express (docs/research/cloudflare-bot-scoring-and-poll-cadence.md);
|
||||
// below it the Lane is outrunning its own plan and says so loudly.
|
||||
minGap = time.Second
|
||||
// RefuseBackoff is how long a Lane waits after its Site refused twice in
|
||||
// one run before attempting it again. Exported so the web layer can derive
|
||||
// browser reachability from the pass log over the same window (issue #145).
|
||||
RefuseBackoff = 15 * time.Minute
|
||||
// refuseBackoff is how long a Lane waits after its Site refused twice in
|
||||
// one run before attempting it again.
|
||||
refuseBackoff = 15 * time.Minute
|
||||
// browserWakeCount and browserWakeAge gate a browser Lane's run: five or
|
||||
// more due Series, or any one of them waiting this long, or Chrome stays
|
||||
// asleep (ADR-0005 on-demand browser).
|
||||
@@ -555,8 +447,7 @@ var sites = map[string]site{
|
||||
"asura": {
|
||||
Host: "asurascans.com",
|
||||
LatestChapter: asuraLatestChapter,
|
||||
Cover: asuraCover,
|
||||
Completed: asuraCompleted,
|
||||
Cover: ogImageCover,
|
||||
Rest: defaultRest,
|
||||
Gap: defaultGap,
|
||||
},
|
||||
@@ -564,7 +455,6 @@ var sites = map[string]site{
|
||||
Host: "demonicscans.org",
|
||||
LatestChapter: demonicLatestChapter,
|
||||
Cover: ogImageCover,
|
||||
Completed: demonicCompleted,
|
||||
Rest: defaultRest,
|
||||
Gap: defaultGap,
|
||||
},
|
||||
@@ -572,7 +462,6 @@ var sites = map[string]site{
|
||||
Host: "comix.to",
|
||||
LatestChapter: comixLatestChapter,
|
||||
Cover: comixCoverEntry,
|
||||
Completed: comixCompleted,
|
||||
Rest: defaultRest,
|
||||
Gap: defaultGap,
|
||||
Browser: &browserRead{
|
||||
@@ -589,7 +478,6 @@ var sites = map[string]site{
|
||||
Host: "kagane.to",
|
||||
LatestChapter: kaganeLatestChapter,
|
||||
Cover: kaganeCoverEntry,
|
||||
Completed: kaganeCompleted,
|
||||
Rest: defaultRest,
|
||||
Gap: defaultGap,
|
||||
Browser: &browserRead{
|
||||
@@ -604,7 +492,6 @@ var sites = map[string]site{
|
||||
Host: "novelfull.com",
|
||||
LatestChapter: novelfullLatestChapter,
|
||||
Cover: novelfullCoverEntry,
|
||||
Completed: novelfullCompleted,
|
||||
Rest: defaultRest,
|
||||
Gap: defaultGap,
|
||||
Browser: &browserRead{
|
||||
@@ -619,30 +506,11 @@ var sites = map[string]site{
|
||||
Host: "lightnovelworld.net",
|
||||
LatestChapter: lnwLatestChapter,
|
||||
Cover: ogImageCover,
|
||||
Completed: lnwCompleted,
|
||||
Rest: defaultRest,
|
||||
Gap: defaultGap,
|
||||
},
|
||||
}
|
||||
|
||||
// SiteNames returns every registry Site, sorted. The admin Series list's Site
|
||||
// select needs the full registry, not just the Sites that have rows, and
|
||||
// laneNames() is the poller's copy of the same list — both read this.
|
||||
func SiteNames() []string {
|
||||
names := make([]string, 0, len(sites))
|
||||
for name := range sites {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
return names
|
||||
}
|
||||
|
||||
// BrowserBackedSites is derived from the registry: the Sites whose pages are
|
||||
// read through the browser sidecar. Sorted so callers that range it (the
|
||||
// browser fetcher's dispatch) see a stable order instead of map-iteration
|
||||
// noise. Exported so the web layer shares the same set the poller does.
|
||||
func BrowserBackedSites() []string { return browserBackedSites() }
|
||||
|
||||
// browserBackedSites is derived from the registry: the Sites whose pages are
|
||||
// read through the browser sidecar. Sorted so callers that range it (the
|
||||
// browser fetcher's dispatch) see a stable order instead of map-iteration
|
||||
|
||||
@@ -188,109 +188,9 @@ const lnwSeriesFixture = `
|
||||
</div>
|
||||
`
|
||||
|
||||
// Completed-marker fixtures, trimmed from the live pages fetched 2026-08-22
|
||||
// for the verification step below. Selector-removed rows delete the marker
|
||||
// from the consts and must answer false.
|
||||
|
||||
// Trimmed from https://asurascans.com/comics/solo-leveling (301 to
|
||||
// /comics/solo-leveling-b60d532c) fetched 2026-08-22 by a curl probe from
|
||||
// this machine. The astro-island props are HTML-escaped in the served
|
||||
// document, so the quotes arrive as ".
|
||||
const asuraCompletedFixture = `
|
||||
"bookmarkCount":[0,39128],"status":[0,"completed"],"type":[0,"manhwa"]
|
||||
`
|
||||
|
||||
// Trimmed from https://asurascans.com/comics/chronicles-of-the-demon-faction-f886a8af
|
||||
// fetched 2026-08-22 by a curl probe.
|
||||
const asuraOngoingFixture = `
|
||||
"bookmarkCount":[0,54027],"status":[0,"ongoing"],"type":[0,"manhwa"]
|
||||
`
|
||||
|
||||
// Trimmed from https://demonicscans.org/manga/Solo-Leveling fetched
|
||||
// 2026-08-22 by a curl probe. The info block is sloppy: bare <li>s inside a
|
||||
// <div>, label and value as a sibling pair.
|
||||
const demonicCompletedFixture = `
|
||||
<div class="flex flex-row">
|
||||
<li style="width:150px;color:#b2b2b2;">Status</li>
|
||||
<li>Completed</li>
|
||||
</div>
|
||||
`
|
||||
|
||||
// Trimmed from https://demonicscans.org/manga/Catastrophic-Necromancer
|
||||
// fetched 2026-08-22 by a curl probe. Same block, ongoing value.
|
||||
const demonicOngoingFixture = `
|
||||
<div class="flex flex-row">
|
||||
<li style="width:150px;color:#b2b2b2;">Status</li>
|
||||
<li>Ongoing</li>
|
||||
</div>
|
||||
`
|
||||
|
||||
// Trimmed from https://comix.to/title/q77m-countach fetched 2026-08-22 by a
|
||||
// cleared Chrome tab (the CDP sidecar: the Series URL is fetched in-tab, the
|
||||
// same server-rendered payload the poll reads). The served page escapes the
|
||||
// query map keys as \u0022; the fixture carries the decoded form, which
|
||||
// parses to the same key. The recommended strip on this very page carries a
|
||||
// finished entry; only the ["manga","detail","q77m"] entry counts.
|
||||
const comixCompletedFixture = `<script type="application/json" id="initial-data">{"queries":{"[\"manga\",\"recommended\",\"q77m\",1]":{"items":[{"hid":"pz65","title":"Wangan Midnight: C1 Runner","status":"finished"}]},"[\"manga\",\"detail\",\"q77m\"]":{"id":13211,"hid":"q77m","title":"Countach","status":"finished","originalLanguage":"ja"}}}</script>`
|
||||
|
||||
// Trimmed from https://comix.to/title/n8we-dungeons-and-crayons fetched
|
||||
// 2026-08-22 the same way (keys in their decoded form, as above). The
|
||||
// recommended strip includes a finished entry; the target detail is
|
||||
// releasing, and only the detail read counts.
|
||||
const comixOngoingFixture = `<script type="application/json" id="initial-data">{"queries":{"[\"manga\",\"recommended\",\"n8we\",1]":{"items":[{"hid":"g2rk","title":"On the Way to Meet Mom","status":"finished"}]},"[\"manga\",\"detail\",\"n8we\"]":{"id":1429,"hid":"n8we","title":"Dungeons and Crayons","status":"releasing","originalLanguage":"ko"}}}</script>`
|
||||
|
||||
// Trimmed from GET https://kagane.to/api/v2/series/019f84bc-9ba0-7ed9-86f5-8b905ec7c28b
|
||||
// fetched 2026-08-22 in a cleared Chrome tab (plain TLS serves the Cloudflare
|
||||
// challenge).
|
||||
const kaganeOngoingFixture = `{"series_id":"019f84bc-9ba0-7ed9-86f5-8b905ec7c28b","title":"Infinite Decryption: The Strongest Level 0","publication_status":"Ongoing","upload_status":"Ongoing"}`
|
||||
|
||||
// Trimmed from GET https://kagane.to/api/v2/series/019c29c3-5abd-70e6-9efc-1f1f22d839f6
|
||||
// fetched 2026-08-22 the same way.
|
||||
const kaganeCompletedFixture = `{"series_id":"019c29c3-5abd-70e6-9efc-1f1f22d839f6","title":"Real Account 1-17","publication_status":"Completed","upload_status":"Completed"}`
|
||||
|
||||
// Composed, not a single live trim: upload Completed alongside a
|
||||
// non-Completed publication status is the research note's inferred inverse
|
||||
// case and did not turn up in the ~1900-series live scan of 2026-08-22 (both
|
||||
// field vocabularies are live-verified; the note's live divergence is 'Cause
|
||||
// Calypso Can, publication Ongoing + upload Hiatus). The predicate must read
|
||||
// publication_status only.
|
||||
const kaganeDivergentFixture = `{"series_id":"019f84bc-9ba0-7ed9-86f5-8b905ec7c28b","title":"Infinite Decryption: The Strongest Level 0","publication_status":"Ongoing","upload_status":"Completed"}`
|
||||
|
||||
// Trimmed from https://novelfull.com/reverend-insanity.html fetched
|
||||
// 2026-08-22 in a cleared Chrome tab after the plain-TLS probe was served the
|
||||
// challenge (time-varying; plain curl answered 403 the same day).
|
||||
const novelfullCompletedFixture = `<div><h3>Status:</h3><a href="/status/Completed">Completed</a></div>`
|
||||
|
||||
// Trimmed from https://novelfull.com/a-cunning-pervert-in-the-cultivation-world.html
|
||||
// fetched 2026-08-22 the same way.
|
||||
const novelfullOngoingFixture = `<div><h3>Status:</h3><a href="/status/Ongoing">Ongoing</a></div>`
|
||||
|
||||
// Trimmed from the JSON-LD block in the head of
|
||||
// https://lightnovelworld.net/novel/a-will-eternal/ fetched 2026-08-22. The
|
||||
// block sits ahead of the wpdiscuz thread, so the predicate reads the whole
|
||||
// body and needs no comment marker, unlike lnwLatestChapter.
|
||||
const lnwCompletedFixture = `<script type="application/ld+json">{
|
||||
"@context": "https://schema.org",
|
||||
"@type": "Book",
|
||||
"name": "A Will Eternal",
|
||||
"creativeWorkStatus": "https://schema.org/CompletedActionStatus"
|
||||
}</script>`
|
||||
|
||||
// Trimmed from
|
||||
// https://lightnovelworld.net/novel/all-jobs-and-classes-i-just-wanted-one-skill-not-them-all/
|
||||
// fetched 2026-08-22. Same block, ongoing value.
|
||||
const lnwOngoingFixture = `<script type="application/ld+json">{
|
||||
"@context": "https://schema.org",
|
||||
"@type": "Book",
|
||||
"name": "All Jobs and Classes I Just Wanted One Skill Not Them All",
|
||||
"creativeWorkStatus": "https://schema.org/ActiveActionStatus"
|
||||
}</script>`
|
||||
|
||||
// Trimmed from https://asurascans.com/comics/chronicles-of-the-demon-faction-ce13e3a9
|
||||
// on 2026-12-04. og:image is a social card, not the cover; the cover is the
|
||||
// astro-island coverUrl prop.
|
||||
const asuraCoverFixture = `<meta property="og:image" content="https://asurascans.com/og/comics/chronicles-of-the-demon-faction.jpg">` +
|
||||
`<astro-island props="{"seriesTitle":[0,"Chronicles of the Demon Faction"],"coverUrl":[0,"https://cdn.asurascans.com/asura-images/covers/chronicles-of-the-demon-faction.d4dcb8.webp"]}"></astro-island>`
|
||||
// (redirected to ...-00dcbf97) on 2026-08-10.
|
||||
const asuraCoverFixture = `<meta property="og:image" content="https://cdn.asurascans.com/asura-images/covers/chronicles-of-the-demon-faction.d4dcb8.webp">`
|
||||
|
||||
// Trimmed from https://demonicscans.org/manga/Catastrophic-Necromancer on 2026-08-10.
|
||||
// The source publishes the raw space in this URL.
|
||||
@@ -323,7 +223,7 @@ func TestCoverFrom(t *testing.T) {
|
||||
wantCover string
|
||||
}{
|
||||
{
|
||||
name: "asura reads coverUrl prop, not og social card",
|
||||
name: "asura uses published metadata URL",
|
||||
site: "asura", body: asuraCoverFixture, wantOK: true,
|
||||
wantCover: "https://cdn.asurascans.com/asura-images/covers/chronicles-of-the-demon-faction.d4dcb8.webp",
|
||||
},
|
||||
@@ -354,10 +254,10 @@ func TestCoverFrom(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "later metadata cover survives empty match",
|
||||
site: "demonic",
|
||||
body: `<meta property="og:image" content="">` + demonicCoverFixture,
|
||||
site: "asura",
|
||||
body: `<meta property="og:image" content="">` + asuraCoverFixture,
|
||||
wantOK: true,
|
||||
wantCover: "https://readermc.org/images/thumbnails/Catastrophic%20Necromancer.webp",
|
||||
wantCover: "https://cdn.asurascans.com/asura-images/covers/chronicles-of-the-demon-faction.d4dcb8.webp",
|
||||
},
|
||||
{
|
||||
name: "page without cover is empty",
|
||||
@@ -573,178 +473,3 @@ func TestLatestChapterFrom(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSiteCompletedFrom(t *testing.T) {
|
||||
const asuraURL = "https://asurascans.com/comics/solo-leveling-b60d532c"
|
||||
const demonicURL = "https://demonicscans.org/manga/Solo-Leveling"
|
||||
const comixURL = "https://comix.to/title/q77m-countach"
|
||||
const kaganeURL = "https://kagane.to/series/019f84bc-9ba0-7ed9-86f5-8b905ec7c28b"
|
||||
const novelfullURL = "https://novelfull.com/reverend-insanity.html"
|
||||
const lnwURL = "https://lightnovelworld.net/novel/a-will-eternal/"
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
site string
|
||||
seriesURL string
|
||||
body string
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "asura completed via escaped props status",
|
||||
site: "asura", seriesURL: asuraURL, body: asuraCompletedFixture,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "asura ongoing value is not completed",
|
||||
site: "asura",
|
||||
seriesURL: "https://asurascans.com/comics/chronicles-of-the-demon-faction-f886a8af",
|
||||
body: asuraOngoingFixture,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "asura with the status key removed",
|
||||
site: "asura", seriesURL: asuraURL,
|
||||
body: strings.ReplaceAll(asuraCompletedFixture, `"status":[0,"completed"]`, ""),
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "asura challenge page",
|
||||
site: "asura", seriesURL: asuraURL, body: challengeFixture,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "demonic completed info-block pair",
|
||||
site: "demonic", seriesURL: demonicURL, body: demonicCompletedFixture,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "demonic ongoing value is not completed",
|
||||
site: "demonic",
|
||||
seriesURL: "https://demonicscans.org/manga/Catastrophic-Necromancer",
|
||||
body: demonicOngoingFixture,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "demonic with the value li removed",
|
||||
site: "demonic", seriesURL: demonicURL,
|
||||
body: strings.ReplaceAll(demonicCompletedFixture, "<li>Completed</li>", ""),
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "comix recommended finished does not count",
|
||||
site: "comix",
|
||||
seriesURL: "https://comix.to/title/n8we-dungeons-and-crayons",
|
||||
body: comixOngoingFixture,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "comix detail finished wins over a finished recommended strip",
|
||||
site: "comix",
|
||||
seriesURL: comixURL,
|
||||
body: comixCompletedFixture,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "comix with the detail status removed",
|
||||
site: "comix", seriesURL: comixURL,
|
||||
body: strings.ReplaceAll(comixCompletedFixture, `"status":"finished",`, ""),
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "comix challenge page",
|
||||
site: "comix", seriesURL: comixURL, body: challengeFixture,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "kagane publication Completed",
|
||||
site: "kagane",
|
||||
seriesURL: "https://kagane.to/series/019c29c3-5abd-70e6-9efc-1f1f22d839f6",
|
||||
body: kaganeCompletedFixture,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "kagane upload Completed does not count",
|
||||
site: "kagane", seriesURL: kaganeURL, body: kaganeDivergentFixture,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "kagane ongoing values are not completed",
|
||||
site: "kagane", seriesURL: kaganeURL, body: kaganeOngoingFixture,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "kagane with publication_status removed",
|
||||
site: "kagane", seriesURL: kaganeURL,
|
||||
body: strings.ReplaceAll(kaganeCompletedFixture, `"publication_status":"Completed",`, ""),
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "kagane challenge page",
|
||||
site: "kagane", seriesURL: kaganeURL, body: challengeFixture,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "novelfull status link Completed",
|
||||
site: "novelfull",
|
||||
seriesURL: novelfullURL,
|
||||
body: novelfullCompletedFixture,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "novelfull ongoing link is not completed",
|
||||
site: "novelfull",
|
||||
seriesURL: "https://novelfull.com/a-cunning-pervert-in-the-cultivation-world.html",
|
||||
body: novelfullOngoingFixture,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "novelfull with the status link removed",
|
||||
site: "novelfull", seriesURL: novelfullURL,
|
||||
body: strings.ReplaceAll(novelfullCompletedFixture, `<a href="/status/Completed">Completed</a>`, ""),
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "novelfull challenge page",
|
||||
site: "novelfull", seriesURL: novelfullURL, body: challengeFixture,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "lightnovelworld JSON-LD CompletedActionStatus",
|
||||
site: "lightnovelworld",
|
||||
seriesURL: lnwURL,
|
||||
body: lnwCompletedFixture,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "lightnovelworld ActiveActionStatus is not completed",
|
||||
site: "lightnovelworld",
|
||||
seriesURL: "https://lightnovelworld.net/novel/all-jobs-and-classes-i-just-wanted-one-skill-not-them-all/",
|
||||
body: lnwOngoingFixture,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "lightnovelworld with creativeWorkStatus removed",
|
||||
site: "lightnovelworld", seriesURL: lnwURL,
|
||||
body: strings.ReplaceAll(lnwCompletedFixture, `"creativeWorkStatus": "https://schema.org/CompletedActionStatus"`, ""),
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "lightnovelworld challenge page",
|
||||
site: "lightnovelworld", seriesURL: lnwURL, body: challengeFixture,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "unknown site",
|
||||
site: "mangadex", seriesURL: "https://mangadex.org/title/x", body: asuraCompletedFixture,
|
||||
want: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := siteCompletedFrom(tt.site, tt.seriesURL, tt.body); got != tt.want {
|
||||
t.Errorf("siteCompletedFrom(%q, %q, body) = %v, want %v", tt.site, tt.seriesURL, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -109,7 +108,10 @@ func TestSmokeAcquireKaganeCover(t *testing.T) {
|
||||
if ws == "" {
|
||||
t.Skip("SMOKE_BROWSER_WS_URL unset")
|
||||
}
|
||||
const seriesID = "019fe11a-8670-7cf3-8343-0b02057d3787"
|
||||
const (
|
||||
seriesID = "019fe11a-8670-7cf3-8343-0b02057d3787"
|
||||
coverURL = "https://kagane.to/api/v2/image/019fe11a-84c3-7fc3-a84b-88787374b617/compressed"
|
||||
)
|
||||
s, _ := newTestStore(t)
|
||||
bf, err := NewBrowserFetcher(ws)
|
||||
if err != nil {
|
||||
@@ -138,13 +140,12 @@ func TestSmokeAcquireKaganeCover(t *testing.T) {
|
||||
if err != nil || !found {
|
||||
t.Fatalf("Get: %v found=%v", err, found)
|
||||
}
|
||||
addr, ok := strings.CutPrefix(got.Cover, testCoverBaseURL+"/covers/")
|
||||
if !ok {
|
||||
t.Fatalf("Cover = %q, want an address on %q — the acquire path did not store the browser-fetched bytes", got.Cover, testCoverBaseURL+"/covers/")
|
||||
if want := testCoverBaseURL + "/covers/" + store.CoverAddress(coverURL); got.Cover != want {
|
||||
t.Fatalf("Cover = %q, want %q — the acquire path did not store the browser-fetched bytes", got.Cover, want)
|
||||
}
|
||||
body, contentType, ok, err := s.CoverByAddress(addr)
|
||||
body, contentType, ok, err := s.CoverByAddress(store.CoverAddress(coverURL))
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("CoverByAddress(%q): %v found=%v", addr, err, ok)
|
||||
t.Fatalf("CoverByAddress: %v found=%v", err, ok)
|
||||
}
|
||||
if len(body) < 1000 {
|
||||
t.Fatalf("stored cover is %d bytes, want a real image", len(body))
|
||||
@@ -152,10 +153,5 @@ func TestSmokeAcquireKaganeCover(t *testing.T) {
|
||||
if contentType != "image/webp" {
|
||||
t.Fatalf("content type = %q, want image/webp", contentType)
|
||||
}
|
||||
// The address the row carries is the bytes' own SHA-256: a re-art behind
|
||||
// the same URL would be a different address, which is the whole point.
|
||||
if want := testCoverBaseURL + "/covers/" + store.CoverAddressForBytes(body); got.Cover != want {
|
||||
t.Fatalf("Cover = %q, want %q", got.Cover, want)
|
||||
}
|
||||
t.Logf("stored %d bytes of %s", len(body), contentType)
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ func TestSmokeLnwCommentBoundary(t *testing.T) {
|
||||
if seriesURL == "" {
|
||||
t.Skip("SMOKE_LNW_SERIES_URL unset")
|
||||
}
|
||||
if !FetchableSeriesURL("lightnovelworld", seriesURL) {
|
||||
if !fetchableSeriesURL("lightnovelworld", seriesURL) {
|
||||
t.Fatalf("%q is not a fetchable lightnovelworld series URL", seriesURL)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package latest
|
||||
|
||||
import "time"
|
||||
|
||||
// LaneState is the administrative page's view of one Poll Lane (issue #102):
|
||||
// what the Lane's last pass saw. Due, Gap and Checked are filled in as the
|
||||
// pass computes them; a pass that returned before reaching a figure (refusal
|
||||
// backoff, sidecar down) carries the previous pass's figures forward rather
|
||||
// than overwriting them with zeroes the page would state as fact.
|
||||
type LaneState struct {
|
||||
Site string
|
||||
Due int
|
||||
LastRun time.Time
|
||||
Gap time.Duration
|
||||
// Checked is how many Series this pass actually read. A Lane with Series
|
||||
// due and nothing checked has stopped working; one with nothing due is
|
||||
// merely quiet, and the page must not draw the two the same (story 13).
|
||||
Checked int
|
||||
Clamped bool
|
||||
Refusing bool
|
||||
Browser bool
|
||||
// Asleep marks a browser Lane whose last pass declined to wake Chrome
|
||||
// because it was under both wake thresholds (ADR-0005). Due without
|
||||
// Checked then means "waiting for the group to gather", not "stopped", and
|
||||
// the page must not draw it as a stall.
|
||||
Asleep bool
|
||||
}
|
||||
|
||||
// Status is the owner's page snapshot of the whole poller (issue #102).
|
||||
type Status struct {
|
||||
Lanes []LaneState
|
||||
BrowserConfigured bool
|
||||
BrowserReachable bool
|
||||
}
|
||||
|
||||
// LaneStatus returns a copy of the poller's Lane state for the owner's page.
|
||||
// Only Sites that have completed a pass appear — a restart therefore renders
|
||||
// "no data yet" instead of confident zeroes — in the same order Run iterates.
|
||||
// Refusing is derived at snapshot time from the refusal backoff, not stored,
|
||||
// so a Lane that cooled down between passes reports false without a new pass.
|
||||
// BrowserReachable mirrors the Lanes' own gate: the sidecar is down only
|
||||
// within the refuseBackoff window since its last loss.
|
||||
func (p *Poller) LaneStatus() Status {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
lanes := make([]LaneState, 0, len(p.laneStates))
|
||||
now := p.Now()
|
||||
for _, name := range laneNames() {
|
||||
st, ok := p.laneStates[name]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
st.Refusing = now.Before(p.refuseUntil[name])
|
||||
lanes = append(lanes, st)
|
||||
}
|
||||
configured := p.BrowserFetch != nil
|
||||
reachable := configured
|
||||
if reachable && !p.browserDownAt.IsZero() && now.Sub(p.browserDownAt) < refuseBackoff {
|
||||
reachable = false
|
||||
}
|
||||
return Status{Lanes: lanes, BrowserConfigured: configured, BrowserReachable: reachable}
|
||||
}
|
||||
|
||||
// recordLaneState stores one Lane's last pass for LaneStatus. Called deferred
|
||||
// from runLanePass so every return path records, even a pass that refused.
|
||||
// A pass that never reached the pace (Gap zero) keeps the last pass's figures:
|
||||
// the Lane's due count and gap did not become zero because this pass declined
|
||||
// to look, and the row's own marks say why it declined.
|
||||
func (p *Poller) recordLaneState(st LaneState) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.laneStates == nil {
|
||||
p.laneStates = make(map[string]LaneState)
|
||||
}
|
||||
if prev, ok := p.laneStates[st.Site]; ok && st.Gap == 0 {
|
||||
st.Due, st.Gap, st.Clamped, st.Checked = prev.Due, prev.Gap, prev.Clamped, prev.Checked
|
||||
}
|
||||
p.laneStates[st.Site] = st
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
// Package notify posts owner-notice embeds to a Discord webhook. It is
|
||||
// deliberately small and stdlib-only: one POST of a JSON body needs no
|
||||
// Discord library, and the path imports nothing of this repo's session or
|
||||
// OAuth packages — that independence is why a webhook was chosen over a bot
|
||||
// (issue #171, AC9).
|
||||
package notify
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"bookmarkmanager/backend/internal/latest"
|
||||
)
|
||||
|
||||
// dangerColor is the dark design branch's --danger, #cf5c4d = 13589581. The
|
||||
// integer is unreadable, so a future edit will otherwise "fix" it — do not:
|
||||
// --ember means new chapter only, and a fault wearing ember would tell the
|
||||
// owner a stall is a release. This is the one colour a fault wears.
|
||||
const dangerColor = 13589581
|
||||
|
||||
// Client posts owner notices to one Discord webhook. The webhook address is a
|
||||
// secret in the class of TOKEN_KEY: it is never logged, never rendered, and
|
||||
// never carried in a returned error, which the poller logs.
|
||||
type Client struct {
|
||||
webhookURL string
|
||||
baseURL string // the deployment's public origin; embed URLs resolve against it
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
// New returns a Client posting to webhookURL. baseURL is the deployment's
|
||||
// public origin (Config.PublicBaseURL); the embed's deep-linked title is
|
||||
// built from it.
|
||||
func New(webhookURL, baseURL string) *Client {
|
||||
return &Client{
|
||||
webhookURL: webhookURL,
|
||||
baseURL: strings.TrimSuffix(baseURL, "/"),
|
||||
http: &http.Client{Timeout: 10 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
// Notify posts one owner notice as a Discord embed: the danger colour, the
|
||||
// subject as a deep-linked title, the sentence as the description, the pass
|
||||
// time as the timestamp and the machine word in the footer. The send is
|
||||
// wrapped in a deadline so a hanging Discord cannot hold a poller Lane. On
|
||||
// failure the error carries no part of the webhook address (the poller logs
|
||||
// it), and the caller leaves the suppression row unwritten so the next pass
|
||||
// retries while the condition holds.
|
||||
func (c *Client) Notify(ctx context.Context, f latest.Fault, sentence, href string) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
body, err := json.Marshal(c.payload(f, sentence, href))
|
||||
if err != nil {
|
||||
return fmt.Errorf("owner notice: marshal: %w", err)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.webhookURL, strings.NewReader(string(body)))
|
||||
if err != nil {
|
||||
return errors.New("owner notice: build request")
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
// The transport error embeds the webhook address; the address is a
|
||||
// secret in the class of TOKEN_KEY and the poller logs this error.
|
||||
return errors.New("owner notice: send failed")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
// Cap the read: a Discord error page is enough, and draining the body
|
||||
// lets the connection be reused.
|
||||
io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
|
||||
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
||||
return fmt.Errorf("owner notice: webhook status %d", resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// payload is the webhook body: one embed and nothing else. No fields, no
|
||||
// thumbnail, no author block — the wire shape is what Discord reads.
|
||||
func (c *Client) payload(f latest.Fault, sentence, href string) webhookPayload {
|
||||
return webhookPayload{Embeds: []embed{{
|
||||
Color: dangerColor,
|
||||
Title: subject(f),
|
||||
URL: c.baseURL + href,
|
||||
Description: sentence,
|
||||
Timestamp: time.UnixMilli(f.Since).UTC().Format(time.RFC3339),
|
||||
Footer: embedFooter{Text: f.Condition},
|
||||
}}}
|
||||
}
|
||||
|
||||
// subject renders the embed's title: the Site the fault is about, with the
|
||||
// machine word so the title needs no per-condition wording here — #172's
|
||||
// conditions pass different sentences, not a different builder. For a fault
|
||||
// that is not one Site's, the machine word stands alone.
|
||||
func subject(f latest.Fault) string {
|
||||
if f.Site == "" {
|
||||
return f.Condition
|
||||
}
|
||||
return f.Site + ": " + f.Condition
|
||||
}
|
||||
|
||||
type webhookPayload struct {
|
||||
Embeds []embed `json:"embeds"`
|
||||
}
|
||||
|
||||
type embed struct {
|
||||
Color int `json:"color"`
|
||||
Title string `json:"title"`
|
||||
URL string `json:"url"`
|
||||
Description string `json:"description"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
Footer embedFooter `json:"footer"`
|
||||
}
|
||||
|
||||
type embedFooter struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
package notify_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"bookmarkmanager/backend/internal/latest"
|
||||
"bookmarkmanager/backend/internal/notify"
|
||||
)
|
||||
|
||||
// TestNotifyEmbedShape pins the wire shape Discord actually reads: one embed
|
||||
// in the danger colour with the subject as a deep-linked title built from the
|
||||
// base URL, the sentence as the description, the pass time as an RFC3339
|
||||
// timestamp, the machine word in the footer, and no fields grid (nor
|
||||
// thumbnail, nor author block) at all. The webhook is a local server, so no
|
||||
// test can reach Discord.
|
||||
func TestNotifyEmbedShape(t *testing.T) {
|
||||
var body map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if ct := r.Header.Get("Content-Type"); ct != "application/json" {
|
||||
t.Errorf("Content-Type = %q, want application/json", ct)
|
||||
}
|
||||
defer r.Body.Close()
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Errorf("decode request body: %v", err)
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
passTime := time.UnixMilli(5_000_000).UTC()
|
||||
c := notify.New(srv.URL, "https://bookmarks.test/")
|
||||
err := c.Notify(context.Background(),
|
||||
latest.Fault{Condition: latest.ConditionStall, Site: "comix", Since: passTime.UnixMilli()},
|
||||
"sentence", "/admin/lanes")
|
||||
if err != nil {
|
||||
t.Fatalf("Notify: %v", err)
|
||||
}
|
||||
|
||||
embeds, ok := body["embeds"].([]any)
|
||||
if !ok || len(embeds) != 1 {
|
||||
t.Fatalf("embeds = %#v, want exactly one embed", body["embeds"])
|
||||
}
|
||||
embed, ok := embeds[0].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("embed = %#v, want an object", embeds[0])
|
||||
}
|
||||
if color, ok := embed["color"].(float64); !ok || int(color) != 13589581 {
|
||||
t.Fatalf("color = %#v, want 13589581 (--danger #cf5c4d)", embed["color"])
|
||||
}
|
||||
if url := embed["url"]; url != "https://bookmarks.test/admin/lanes" {
|
||||
t.Fatalf("url = %#v, want the title deep-linked off the base URL", url)
|
||||
}
|
||||
if desc := embed["description"]; desc != "sentence" {
|
||||
t.Fatalf("description = %#v, want the sentence", desc)
|
||||
}
|
||||
footer, ok := embed["footer"].(map[string]any)
|
||||
if !ok || footer["text"] != latest.ConditionStall {
|
||||
t.Fatalf("footer = %#v, want the machine word in the footer", embed["footer"])
|
||||
}
|
||||
ts, ok := embed["timestamp"].(string)
|
||||
if !ok {
|
||||
t.Fatalf("timestamp = %#v, want an RFC3339 string", embed["timestamp"])
|
||||
}
|
||||
parsed, err := time.Parse(time.RFC3339, ts)
|
||||
if err != nil || !parsed.Equal(passTime) {
|
||||
t.Fatalf("timestamp = %q, want %s (the pass time, RFC3339)", ts, passTime.Format(time.RFC3339))
|
||||
}
|
||||
for _, banned := range []string{"fields", "thumbnail", "author"} {
|
||||
if _, ok := embed[banned]; ok {
|
||||
t.Fatalf("embed has %q, want it absent (no field grid, no thumbnail, no author block)", banned)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A non-2xx answer is an error the caller logs, and the error never carries
|
||||
// the webhook address — a secret in the class of TOKEN_KEY, and the poller
|
||||
// logs every notify error.
|
||||
func TestNotifyNon2xxIsErrorWithoutTheAddress(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := notify.New(srv.URL, "https://bookmarks.test")
|
||||
err := c.Notify(context.Background(),
|
||||
latest.Fault{Condition: latest.ConditionStall, Site: "comix", Since: 5_000_000},
|
||||
"sentence", "/admin/lanes")
|
||||
if err == nil {
|
||||
t.Fatal("Notify = nil, want an error for a 500")
|
||||
}
|
||||
if strings.Contains(err.Error(), srv.URL) {
|
||||
t.Fatalf("error %q leaks the webhook address", err)
|
||||
}
|
||||
}
|
||||
@@ -40,9 +40,7 @@ func Main(m *testing.M) int {
|
||||
fmt.Println("pgtest:", err)
|
||||
return 1
|
||||
}
|
||||
// -v: the postgres image declares a VOLUME, so an explicit rm without it
|
||||
// leaves the anonymous data volume behind on every test run.
|
||||
defer exec.Command("docker", "rm", "-f", "-v", id).Run()
|
||||
defer exec.Command("docker", "rm", "-f", id).Run()
|
||||
|
||||
adminURL = url
|
||||
return m.Run()
|
||||
@@ -87,7 +85,7 @@ func start() (id, url string, err error) {
|
||||
|
||||
port, err := exec.Command("docker", "port", id, "5432/tcp").Output()
|
||||
if err != nil {
|
||||
exec.Command("docker", "rm", "-f", "-v", id).Run()
|
||||
exec.Command("docker", "rm", "-f", id).Run()
|
||||
return "", "", fmt.Errorf("docker port: %w", err)
|
||||
}
|
||||
// "0.0.0.0:32768" (and possibly a second, IPv6 line); the port is all we want.
|
||||
@@ -96,7 +94,7 @@ func start() (id, url string, err error) {
|
||||
first[strings.LastIndex(first, ":")+1:])
|
||||
|
||||
if err := waitReady(url); err != nil {
|
||||
exec.Command("docker", "rm", "-f", "-v", id).Run()
|
||||
exec.Command("docker", "rm", "-f", id).Run()
|
||||
return "", "", err
|
||||
}
|
||||
return id, url, nil
|
||||
|
||||
@@ -1,342 +0,0 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Series filter names (issue #140): the seven repair filters are ordered
|
||||
// permanent-then-fixable — the repairs nothing will ever undo first, the
|
||||
// ones a Poll can make right after. SeriesFilterFinished and
|
||||
// SeriesFilterSiteCompleted are not part of that ordering: a finished
|
||||
// Series is a deliberate state and a Site-completed one is the Site's own
|
||||
// marker, not repairs, so the pair rides the tail, informational. A name is
|
||||
// the repair a row needs, not the SQL that finds it; the values are the
|
||||
// wire form the Series list URL carries (#142). "all" is the absent and
|
||||
// unknown case: every Series.
|
||||
const (
|
||||
SeriesFilterAll = "all"
|
||||
SeriesFilterNoURL = "no_series_url"
|
||||
SeriesFilterNoChapter = "never_read_a_chapter"
|
||||
SeriesFilterNoReaders = "no_readers"
|
||||
SeriesFilterNeverChecked = "never_checked"
|
||||
SeriesFilterStale = "stale"
|
||||
SeriesFilterNoCover = "no_cover"
|
||||
SeriesFilterReaderReport = "reader_report"
|
||||
SeriesFilterFinished = "finished"
|
||||
SeriesFilterSiteCompleted = "site_completed"
|
||||
SeriesFilterFailing = "failing"
|
||||
SeriesFilterUnverified = "unverified"
|
||||
)
|
||||
|
||||
// SeriesFilter is one named filter predicate over the whole library. Site
|
||||
// and Kind narrow the row read; Name picks the predicate; Cutoff is the
|
||||
// staleness boundary the age-based filters — "stale" and the failing pair —
|
||||
// compare against, supplied by the caller's clock — the store has no clock;
|
||||
// Page is 1-based.
|
||||
type SeriesFilter struct {
|
||||
Site string // "" = every Site
|
||||
Kind string // "" = both library buckets' series
|
||||
Name string // one of the SeriesFilter* constants; "" = SeriesFilterAll
|
||||
Cutoff int64 // unix ms; the age-based filters read it, the store never does
|
||||
Page int // 1-based page of the row read; default 1
|
||||
}
|
||||
|
||||
// adminSeriesColumns is the owner's library-wide Series projection in
|
||||
// scanAdminSeries order. It is the privacy boundary: a Series' row carries
|
||||
// the Reader id that raised its Latest Chapter (latest_raised_by), and that id
|
||||
// must never leave the store package — so the projection does not select it,
|
||||
// and only the anonymous boolean in raisedByReaderAnswer crosses it.
|
||||
const adminSeriesColumns = `s.site, s.series_id, s.title, s.series_url, s.cover_address,
|
||||
s.kind, s.latest_chapter, s.latest_chapter_num, s.latest_checked_at, s.force_poll_at,
|
||||
s.latest_corrected_at, s.finished_at, s.site_completed_at`
|
||||
|
||||
// raisedByReaderAnswer answers "did a Reader's report set this number" without
|
||||
// naming which Reader. Kept apart from adminSeriesColumns so the column list —
|
||||
// the shape scanAdminSeries is fed — stays free of the Sighting-raiser
|
||||
// identity, and the owner learns which rows to act on and nothing about the
|
||||
// Reader behind them.
|
||||
const raisedByReaderAnswer = `(s.latest_raised_by IS NOT NULL) AS raised_by_reader`
|
||||
|
||||
// failureAnswer is the poll-failures row's answer (issue #165), kept apart
|
||||
// from adminSeriesColumns like raisedByReaderAnswer: outcome and failing_since
|
||||
// are not Series columns, and the COALESCE keeps the row scannable when the
|
||||
// LEFT JOIN finds no failure row.
|
||||
const failureAnswer = `COALESCE(f.outcome, ''), COALESCE(f.failing_since, 0)`
|
||||
|
||||
// seriesPageSize is the row read's page length. The tie-break in the query's
|
||||
// ORDER BY is what makes this a stable page boundary — see SeriesPage.
|
||||
const seriesPageSize = 50
|
||||
|
||||
// AdminSeries is one Series as the owner's library-wide view sees it: a
|
||||
// Series-level fact plus an anonymous Reader count. ReaderCount being zero is
|
||||
// the orphan marker. RaisedByReader is the only trace of the Sighting
|
||||
// mechanism here; the Reader id behind it never reaches this type.
|
||||
type AdminSeries struct {
|
||||
Site string
|
||||
SeriesID string
|
||||
Title string
|
||||
SeriesURL string
|
||||
CoverAddress string // "" = no Cover yet
|
||||
Kind string
|
||||
LatestChapter string
|
||||
LatestChapterNum *float64 // nil until first captured
|
||||
LatestCheckedAt int64
|
||||
// ForcePollAt is the owner's "check now" request stamp (issue #146), zero
|
||||
// meaning never asked. Pending is derived, never stored: a request is
|
||||
// pending while ForcePollAt is newer than LatestCheckedAt.
|
||||
ForcePollAt int64
|
||||
// LatestCorrectedAt is the correction stamp (issue #149): non-zero means
|
||||
// the Latest Chapter is the owner's, zero means never corrected. The
|
||||
// provenance line (#152) derives from it, so the zero-means-never meaning
|
||||
// is load-bearing.
|
||||
LatestCorrectedAt int64
|
||||
ReaderCount int
|
||||
RaisedByReader bool // a Reader's report set LatestChapterNum
|
||||
// FailureOutcome is the outcome word of the Series' standing failure, ""
|
||||
// when no failure row stands. FailingSince is when the run of failures
|
||||
// began, zero with no row. Both come from the LEFT JOIN, not the Series
|
||||
// row (issue #165: the row's existence is the state).
|
||||
FailureOutcome string
|
||||
FailingSince int64
|
||||
// FinishedAt is the owner's finish stamp: unix ms, zero while the Series is
|
||||
// not finished — the same shape as the Correction stamp, and its own undo.
|
||||
FinishedAt int64
|
||||
// SiteCompletedAt is when the last successful Poll read saw the Site's own
|
||||
// completed value, zero meaning it did not (issue #168). The Site's marker,
|
||||
// never a Lifecycle decision: the owner's Finish is the only retirement.
|
||||
SiteCompletedAt int64
|
||||
}
|
||||
|
||||
// SeriesPage is one page of the owner's filtered Series list plus the count
|
||||
// of every Series matching the same filter — a window number, not the page's
|
||||
// len, so the landing page's figure and the list heading come from one query.
|
||||
type SeriesPage struct {
|
||||
Rows []AdminSeries
|
||||
Total int
|
||||
}
|
||||
|
||||
// SiteSeriesShape is one Site's share of the Series matching a filter: how
|
||||
// many, and the manga/novel split. One grouped pass, then library-wide totals
|
||||
// are summed in Go over the rows — the landing page's per-Site table reads
|
||||
// this and never pays for the rows the list discards.
|
||||
type SiteSeriesShape struct {
|
||||
Site string
|
||||
Total int
|
||||
Manga int
|
||||
Novel int
|
||||
}
|
||||
|
||||
// Key returns the canonical identity in bookmark-key form ("<site>:<series_id>").
|
||||
func (a AdminSeries) Key() string { return a.Site + ":" + a.SeriesID }
|
||||
|
||||
// adminFilter maps a filter's named predicate to its compile-time WHERE and
|
||||
// HAVING clauses and their bound parameters — the name never reaches query
|
||||
// text, and Site and Kind bind as parameters. Shared by the row read and the
|
||||
// per-Site aggregate so the two cannot disagree on what a filter means.
|
||||
//
|
||||
// The WHERE set is: no URL (an empty URL only — the host-failing-the-fetch-
|
||||
// gate case is invisible to SQL, needs the Site registry in Go, and belongs to
|
||||
// a later repair), never-read-a-chapter and never-checked as disjoint halves
|
||||
// (non-zero versus zero check stamp), stale, no cover, finished (the
|
||||
// retirement stamp, read directly), site completed (the Site's marker, read
|
||||
// directly), Reader-report, and the failing pair — failing (the failure row
|
||||
// exists, a chapter exists, and failing_since is past the cutoff) and
|
||||
// unverified (the Reader-attributed subset of failing).
|
||||
// failing's chapter IS NOT NULL is the exact complement of never-read-a-
|
||||
// chapter's IS NULL half, so the two are disjoint by construction.
|
||||
// no_readers is the one HAVING predicate: it is the orphan test, an aggregate
|
||||
// over the LEFT JOIN, where a bare WHERE has no row to test.
|
||||
//
|
||||
// The clock-versus-outcome split decides which predicates exclude finished
|
||||
// Series (`s.finished_at = 0` in each of the five): the clock-driven ones —
|
||||
// never-checked, stale, no-chapter, no-cover — keep ticking after the last
|
||||
// Poll, so they would report a retired row as a problem no Poll is coming to
|
||||
// fix; site-completed's stamp is the Site's, and it keeps standing after the
|
||||
// owner retires the row, so a finished Series would be reported as work
|
||||
// nobody is going to do. The outcome-driven ones — no-URL, no-readers,
|
||||
// Reader-report, failing, unverified — read stored facts that simply stop
|
||||
// arriving, so a finished Series needing a genuine repair still shows up
|
||||
// under them. The failing pair carries no finished guard for exactly that
|
||||
// contrast: a failure row is a stored outcome, not a ticking clock.
|
||||
//
|
||||
// stale is the checked-but-old half of the stamp partition — because the
|
||||
// verdict line wants "not checked in twelve hours" as one figure, and a never
|
||||
// checked Series is already counted on its own "waiting"/never-checked
|
||||
// filter, folding it in would double-report it. The landing page computes the
|
||||
// inclusive number as stale + never-checked.
|
||||
func adminFilter(f SeriesFilter) (where, having string, args []any, err error) {
|
||||
var clauses []string
|
||||
if f.Kind != "" {
|
||||
args = append(args, f.Kind)
|
||||
clauses = append(clauses, "s.kind = $"+strconv.Itoa(len(args)))
|
||||
}
|
||||
switch f.Name {
|
||||
case "", SeriesFilterAll:
|
||||
case SeriesFilterNoURL:
|
||||
clauses = append(clauses, `s.series_url = ''`)
|
||||
case SeriesFilterNoChapter:
|
||||
clauses = append(clauses, `s.latest_checked_at <> 0 AND s.latest_chapter_num IS NULL AND s.finished_at = 0`)
|
||||
case SeriesFilterNeverChecked:
|
||||
clauses = append(clauses, `s.latest_checked_at = 0 AND s.finished_at = 0`)
|
||||
case SeriesFilterStale:
|
||||
clauses = append(clauses, `s.latest_checked_at > 0 AND s.latest_checked_at < $`+strconv.Itoa(len(args)+1)+` AND s.finished_at = 0`)
|
||||
args = append(args, f.Cutoff)
|
||||
case SeriesFilterNoCover:
|
||||
clauses = append(clauses, `s.cover_address = '' AND s.finished_at = 0`)
|
||||
case SeriesFilterReaderReport:
|
||||
clauses = append(clauses, `s.latest_raised_by IS NOT NULL`)
|
||||
case SeriesFilterFailing:
|
||||
clauses = append(clauses, `f.site IS NOT NULL AND s.latest_chapter_num IS NOT NULL AND f.failing_since < $`+strconv.Itoa(len(args)+1))
|
||||
args = append(args, f.Cutoff)
|
||||
case SeriesFilterUnverified:
|
||||
clauses = append(clauses, `f.site IS NOT NULL AND s.latest_chapter_num IS NOT NULL AND f.failing_since < $`+strconv.Itoa(len(args)+1)+` AND s.latest_raised_by IS NOT NULL`)
|
||||
args = append(args, f.Cutoff)
|
||||
case SeriesFilterFinished:
|
||||
clauses = append(clauses, `s.finished_at > 0`)
|
||||
case SeriesFilterSiteCompleted:
|
||||
clauses = append(clauses, `s.site_completed_at > 0 AND s.finished_at = 0`)
|
||||
case SeriesFilterNoReaders:
|
||||
having = `HAVING COUNT(b.reader_id) = 0`
|
||||
default:
|
||||
return "", "", nil, fmt.Errorf("unknown series filter %q", f.Name)
|
||||
}
|
||||
if len(clauses) > 0 {
|
||||
where = "WHERE " + strings.Join(clauses, " AND ")
|
||||
}
|
||||
return where, having, args, nil
|
||||
}
|
||||
|
||||
// SeriesPage returns one page of the Series matching the filter, least
|
||||
// recently checked first. The LEFT JOIN to Bookmarks is what surfaces the
|
||||
// orphans that hygiene has to find — an inner join would hide them, exactly
|
||||
// as the Lane's join does. Every bookmark keeps its Series polled now that
|
||||
// finished is a Series flag, so this plain ReaderCount agrees with the Lane
|
||||
// queries (issue #157).
|
||||
//
|
||||
// The tie-break is mandatory, not decorative: every unpollable Series shares a
|
||||
// zero check stamp, so ordering on that column alone gives no stable page
|
||||
// boundary and rows would repeat or vanish across pages. (site, series_id) is
|
||||
// the primary key, hence total. The filtered total is a window count in the
|
||||
// same query — window functions run after grouping and before the limit, so
|
||||
// one where-clause cannot disagree with a second copy of itself.
|
||||
func (s *Store) SeriesPage(f SeriesFilter) (SeriesPage, error) {
|
||||
where, having, args, err := adminFilter(f)
|
||||
if err != nil {
|
||||
return SeriesPage{}, err
|
||||
}
|
||||
if f.Page < 1 {
|
||||
f.Page = 1
|
||||
}
|
||||
// Site narrowing is the row read's own; the aggregate must see every Site.
|
||||
if f.Site != "" {
|
||||
args = append(args, f.Site)
|
||||
clause := "s.site = $" + strconv.Itoa(len(args))
|
||||
if where == "" {
|
||||
where = "WHERE " + clause
|
||||
} else {
|
||||
where += " AND " + clause
|
||||
}
|
||||
}
|
||||
base := len(args)
|
||||
args = append(args, seriesPageSize, seriesPageSize*(f.Page-1))
|
||||
rows, err := s.db.Query(`
|
||||
SELECT `+adminSeriesColumns+`, `+raisedByReaderAnswer+`, `+failureAnswer+`,
|
||||
COUNT(b.reader_id) AS reader_count,
|
||||
COUNT(*) OVER () AS filtered_total
|
||||
FROM series s
|
||||
LEFT JOIN bookmarks b ON b.site = s.site AND b.series_id = s.series_id
|
||||
LEFT JOIN poll_failures f ON f.site = s.site AND f.series_id = s.series_id
|
||||
`+where+`
|
||||
GROUP BY s.site, s.series_id, s.title, s.series_url, s.cover_address,
|
||||
s.kind, s.latest_chapter, s.latest_chapter_num, s.latest_checked_at,
|
||||
s.force_poll_at, s.latest_corrected_at, s.finished_at, s.site_completed_at,
|
||||
s.latest_raised_by,
|
||||
f.outcome, f.failing_since
|
||||
`+having+`
|
||||
ORDER BY s.latest_checked_at, s.site, s.series_id
|
||||
LIMIT $`+strconv.Itoa(base+1)+` OFFSET $`+strconv.Itoa(base+2), args...)
|
||||
if err != nil {
|
||||
return SeriesPage{}, fmt.Errorf("query series page: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
out := SeriesPage{}
|
||||
for rows.Next() {
|
||||
a, total, err := scanAdminSeries(rows.Scan)
|
||||
if err != nil {
|
||||
return SeriesPage{}, fmt.Errorf("scan series page: %w", err)
|
||||
}
|
||||
out.Rows = append(out.Rows, a)
|
||||
out.Total = total
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// SeriesShapes returns each Site's share of the Series matching the filter,
|
||||
// one grouped pass. Site and Page are row-read concerns and are ignored; the
|
||||
// Landing page reads this per Site and sums the totals in Go for the
|
||||
// library-wide figure.
|
||||
func (s *Store) SeriesShapes(f SeriesFilter) ([]SiteSeriesShape, error) {
|
||||
where, having, args, err := adminFilter(f)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows, err := s.db.Query(`
|
||||
SELECT site,
|
||||
COUNT(*) AS total,
|
||||
COUNT(*) FILTER (WHERE kind = 'manga') AS manga,
|
||||
COUNT(*) FILTER (WHERE kind = 'novel') AS novel
|
||||
FROM (
|
||||
SELECT s.site, s.kind
|
||||
FROM series s
|
||||
LEFT JOIN bookmarks b ON b.site = s.site AND b.series_id = s.series_id
|
||||
LEFT JOIN poll_failures f ON f.site = s.site AND f.series_id = s.series_id
|
||||
`+where+`
|
||||
GROUP BY s.site, s.series_id, s.kind
|
||||
`+having+`
|
||||
) shape
|
||||
GROUP BY site
|
||||
ORDER BY site`, args...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("query series shapes: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
out := []SiteSeriesShape{}
|
||||
for rows.Next() {
|
||||
var sh SiteSeriesShape
|
||||
if err := rows.Scan(&sh.Site, &sh.Total, &sh.Manga, &sh.Novel); err != nil {
|
||||
return nil, fmt.Errorf("scan series shape: %w", err)
|
||||
}
|
||||
out = append(out, sh)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// scanAdminSeries reads one row in adminSeriesColumns + raisedByReaderAnswer +
|
||||
// failureAnswer order, plus the query's reader_count and filtered_total
|
||||
// columns, and returns the window total alongside the row. latest_chapter_num
|
||||
// is NULL until first captured — the "never read a chapter" state. The
|
||||
// Sighting-raiser column is never among the scanned columns.
|
||||
func scanAdminSeries(scan func(...any) error) (AdminSeries, int, error) {
|
||||
var (
|
||||
a AdminSeries
|
||||
latestChapterNum sql.NullFloat64
|
||||
total int
|
||||
)
|
||||
if err := scan(
|
||||
&a.Site, &a.SeriesID, &a.Title, &a.SeriesURL, &a.CoverAddress,
|
||||
&a.Kind, &a.LatestChapter, &latestChapterNum, &a.LatestCheckedAt,
|
||||
&a.ForcePollAt, &a.LatestCorrectedAt, &a.FinishedAt, &a.SiteCompletedAt,
|
||||
&a.RaisedByReader, &a.FailureOutcome, &a.FailingSince, &a.ReaderCount, &total,
|
||||
); err != nil {
|
||||
return AdminSeries{}, 0, err
|
||||
}
|
||||
if latestChapterNum.Valid {
|
||||
a.LatestChapterNum = &latestChapterNum.Float64
|
||||
}
|
||||
return a, total, nil
|
||||
}
|
||||
@@ -1,736 +0,0 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// seriesSeed describes one Series (and optionally its bookmarks) to stand up
|
||||
// for an admin filter test. Direct SQL, because the filters separate rows the
|
||||
// Upsert path could not produce together: an orphan has no bookmark, and a
|
||||
// Reader-raised Latest Chapter needs a Sighting the store does not create.
|
||||
type seriesSeed struct {
|
||||
key string
|
||||
kind string
|
||||
url string
|
||||
cover string // cover_address
|
||||
checkedAt int64
|
||||
latestNum *float64
|
||||
bookmarks int // readers that hold it; 0 = orphan
|
||||
raisedBy bool // a Reader's report is attributed as the raiser
|
||||
siteCompletedAt int64 // the Site's own marker (issue #168), 0 = not set
|
||||
}
|
||||
|
||||
// seedAdminSeries inserts one series row and its bookmarks (owner first, then
|
||||
// fresh readers), with the exact admin-relevant facts a test needs.
|
||||
func seedAdminSeries(t *testing.T, s *Store, seed seriesSeed) {
|
||||
t.Helper()
|
||||
site, seriesID, ok := strings.Cut(seed.key, ":")
|
||||
if !ok {
|
||||
t.Fatalf("key %q: no ':' separator", seed.key)
|
||||
}
|
||||
if seed.kind == "" {
|
||||
seed.kind = "manga"
|
||||
}
|
||||
var latestChapter any = ""
|
||||
if seed.latestNum != nil {
|
||||
latestChapter = "Chapter " + strconv.FormatFloat(*seed.latestNum, 'f', -1, 64)
|
||||
}
|
||||
if _, err := s.db.Exec(`
|
||||
INSERT INTO series (site, series_id, title, kind, series_url, cover_address,
|
||||
latest_checked_at, latest_chapter, latest_chapter_num, site_completed_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
|
||||
site, seriesID, "Title of "+seed.key, seed.kind, seed.url, seed.cover,
|
||||
seed.checkedAt, latestChapter, seed.latestNum, seed.siteCompletedAt); err != nil {
|
||||
t.Fatalf("seed series %q: %v", seed.key, err)
|
||||
}
|
||||
for i := range seed.bookmarks {
|
||||
var readerID int64 = s.OwnerID()
|
||||
if i > 0 {
|
||||
readerID = secondReader(t, s)
|
||||
}
|
||||
if _, err := s.db.Exec(`
|
||||
INSERT INTO bookmarks (reader_id, site, series_id,
|
||||
last_chapter, last_chapter_num, last_chapter_url,
|
||||
favorite, status, updated_at)
|
||||
VALUES ($1, $2, $3, '', 0, '', false, 'reading', $4)`,
|
||||
readerID, site, seriesID, seed.checkedAt); err != nil {
|
||||
t.Fatalf("seed bookmark %q: %v", seed.key, err)
|
||||
}
|
||||
}
|
||||
if seed.raisedBy {
|
||||
if _, err := s.db.Exec(
|
||||
`UPDATE series SET latest_raised_by = $1 WHERE site = $2 AND series_id = $3`,
|
||||
s.OwnerID(), site, seriesID); err != nil {
|
||||
t.Fatalf("seed raised-by %q: %v", seed.key, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func pageKeys(t *testing.T, s *Store, f SeriesFilter) map[string]bool {
|
||||
t.Helper()
|
||||
page, err := s.SeriesPage(f)
|
||||
if err != nil {
|
||||
t.Fatalf("SeriesPage(%+v): %v", f, err)
|
||||
}
|
||||
keys := map[string]bool{}
|
||||
for _, a := range page.Rows {
|
||||
keys[a.Key()] = true
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
// Each filter must return the rows it names and no others, over one shared
|
||||
// seeded mix where every healthy neighbour is present to be wrongly returned.
|
||||
// The stale cutoff is 5000: a Series checked at 9000 is current, at 2000 stale.
|
||||
func TestAdminSeriesFilters(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:healthy", url: "https://asurascans.com/comics/healthy", cover: "aaa", checkedAt: 9000, latestNum: new(10.0), bookmarks: 1})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:nourl", url: "", cover: "bbb", checkedAt: 9000, latestNum: new(5.0), bookmarks: 1})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:nochapter", url: "https://asurascans.com/comics/nochapter", cover: "ccc", checkedAt: 9000, bookmarks: 1})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:neverchecked", url: "https://asurascans.com/comics/neverchecked", cover: "ddd", checkedAt: 0, bookmarks: 1})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:orphan", url: "https://asurascans.com/comics/orphan", cover: "eee", checkedAt: 9000, latestNum: new(7.0), bookmarks: 0})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:stale", url: "https://asurascans.com/comics/stale", cover: "fff", checkedAt: 2000, latestNum: new(4.0), bookmarks: 1})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:nocover", url: "https://asurascans.com/comics/nocover", checkedAt: 9000, latestNum: new(9.0), bookmarks: 1})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:report", url: "https://asurascans.com/comics/report", cover: "ggg", checkedAt: 9000, latestNum: new(8.0), bookmarks: 1, raisedBy: true})
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
f SeriesFilter
|
||||
want []string
|
||||
}{
|
||||
{"all", SeriesFilter{}, []string{"asura:healthy", "asura:nourl", "asura:nochapter", "asura:neverchecked", "asura:orphan", "asura:stale", "asura:nocover", "asura:report"}},
|
||||
{"no series url", SeriesFilter{Name: SeriesFilterNoURL}, []string{"asura:nourl"}},
|
||||
{"never read a chapter", SeriesFilter{Name: SeriesFilterNoChapter}, []string{"asura:nochapter"}},
|
||||
{"never checked", SeriesFilter{Name: SeriesFilterNeverChecked}, []string{"asura:neverchecked"}},
|
||||
{"no readers", SeriesFilter{Name: SeriesFilterNoReaders}, []string{"asura:orphan"}},
|
||||
{"stale", SeriesFilter{Name: SeriesFilterStale, Cutoff: 5000}, []string{"asura:stale"}},
|
||||
{"no cover", SeriesFilter{Name: SeriesFilterNoCover}, []string{"asura:nocover"}},
|
||||
{"reader report", SeriesFilter{Name: SeriesFilterReaderReport}, []string{"asura:report"}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := pageKeys(t, s, tc.f)
|
||||
want := map[string]bool{}
|
||||
for _, k := range tc.want {
|
||||
want[k] = true
|
||||
}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("%+v returned %v, want exactly %v", tc.f, got, want)
|
||||
}
|
||||
for k := range want {
|
||||
if !got[k] {
|
||||
t.Fatalf("%+v dropped %q (got %v)", tc.f, k, got)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A finished Series is the owner's deliberate state, not a problem a Poll
|
||||
// will fix: the four clock-driven hygiene predicates exclude it (their
|
||||
// stamps stop advancing at the last Poll, so without the guard a retired row
|
||||
// is reported forever), the three outcome-driven ones still include it, and
|
||||
// the finished filter returns exactly the retired rows.
|
||||
func TestAdminFinishedSeriesFilters(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
// Each fin-* row is shaped to trip exactly one predicate if its guard
|
||||
// fails: checked-but-old for stale, a zero stamp for never-checked, a
|
||||
// stamp with no chapter for no-chapter, an empty cover for no-cover, and
|
||||
// the unguarded three shaped to trip their own. A healthy, unfinished
|
||||
// neighbour keeps the exclusion checks honest: a filter that regressed to
|
||||
// matching nothing would pass a bare "no finished rows" assertion.
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:fin-stale", url: "u", cover: "c", checkedAt: 2000, latestNum: new(4.0), bookmarks: 1})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:fin-neverchecked", url: "u", cover: "c", checkedAt: 0, latestNum: new(4.0), bookmarks: 1})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:fin-nochapter", url: "u", cover: "c", checkedAt: 9000, bookmarks: 1})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:fin-nocover", url: "u", checkedAt: 9000, latestNum: new(4.0), bookmarks: 1})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:fin-nourl", url: "", cover: "c", checkedAt: 9000, latestNum: new(4.0), bookmarks: 1})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:fin-orphan", url: "u", cover: "c", checkedAt: 9000, latestNum: new(4.0), bookmarks: 0})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:fin-report", url: "u", cover: "c", checkedAt: 9000, latestNum: new(4.0), bookmarks: 1, raisedBy: true})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:healthy", url: "u", cover: "c", checkedAt: 9000, latestNum: new(4.0), bookmarks: 1})
|
||||
finished := []string{
|
||||
"asura:fin-stale", "asura:fin-neverchecked", "asura:fin-nochapter",
|
||||
"asura:fin-nocover", "asura:fin-nourl", "asura:fin-orphan", "asura:fin-report",
|
||||
}
|
||||
for _, key := range finished {
|
||||
site, id, _ := strings.Cut(key, ":")
|
||||
if err := s.SetSeriesFinished(site, id, 1000); err != nil {
|
||||
t.Fatalf("finish %s: %v", key, err)
|
||||
}
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
f SeriesFilter
|
||||
want []string
|
||||
}{
|
||||
{"stale excludes finished", SeriesFilter{Name: SeriesFilterStale, Cutoff: 5000}, nil},
|
||||
{"never checked excludes finished", SeriesFilter{Name: SeriesFilterNeverChecked}, nil},
|
||||
{"no chapter excludes finished", SeriesFilter{Name: SeriesFilterNoChapter}, nil},
|
||||
{"no cover excludes finished", SeriesFilter{Name: SeriesFilterNoCover}, nil},
|
||||
{"no url includes finished", SeriesFilter{Name: SeriesFilterNoURL}, []string{"asura:fin-nourl"}},
|
||||
{"no readers includes finished", SeriesFilter{Name: SeriesFilterNoReaders}, []string{"asura:fin-orphan"}},
|
||||
{"reader report includes finished", SeriesFilter{Name: SeriesFilterReaderReport}, []string{"asura:fin-report"}},
|
||||
{"finished returns the retired rows", SeriesFilter{Name: SeriesFilterFinished}, finished},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := pageKeys(t, s, tc.f)
|
||||
want := map[string]bool{}
|
||||
for _, k := range tc.want {
|
||||
want[k] = true
|
||||
}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("%+v returned %v, want exactly %v", tc.f, got, want)
|
||||
}
|
||||
for k := range want {
|
||||
if !got[k] {
|
||||
t.Fatalf("%+v dropped %q (got %v)", tc.f, k, got)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The aggregate's finished total counts every retired row — the same
|
||||
// predicate the Overview's finished figure is summed from.
|
||||
shapes, err := s.SeriesShapes(SeriesFilter{Name: SeriesFilterFinished})
|
||||
if err != nil {
|
||||
t.Fatalf("SeriesShapes(finished): %v", err)
|
||||
}
|
||||
sum := 0
|
||||
for _, sh := range shapes {
|
||||
sum += sh.Total
|
||||
}
|
||||
if sum != len(finished) {
|
||||
t.Fatalf("finished aggregate = %d, want %d", sum, len(finished))
|
||||
}
|
||||
}
|
||||
|
||||
// "Never read a chapter" and "never checked" are disjoint by construction:
|
||||
// the first requires a non-zero check stamp, the second a zero one. Over a
|
||||
// mix that should satisfy both, no row may be counted twice.
|
||||
func TestAdminNeverChapterAndNeverCheckedAreDisjoint(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:nochapter", url: "u", checkedAt: 9000, bookmarks: 1})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:neverchecked", url: "u", checkedAt: 0, bookmarks: 1})
|
||||
// A zero-stamp, no-chapter row is never-checked only: if never-read-a-
|
||||
// chapter ever lost its non-zero-stamp guard, it would claim this row too
|
||||
// and the two counts would double-report it.
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:both", url: "u", checkedAt: 0, bookmarks: 1})
|
||||
noChapter := pageKeys(t, s, SeriesFilter{Name: SeriesFilterNoChapter})
|
||||
neverChecked := pageKeys(t, s, SeriesFilter{Name: SeriesFilterNeverChecked})
|
||||
for k := range noChapter {
|
||||
if neverChecked[k] {
|
||||
t.Fatalf("row %q matches both never-read-a-chapter and never-checked", k)
|
||||
}
|
||||
}
|
||||
if !noChapter["asura:nochapter"] || !neverChecked["asura:neverchecked"] {
|
||||
t.Fatalf("disjoint split lost its own rows: no-chapter=%v never-checked=%v", noChapter, neverChecked)
|
||||
}
|
||||
}
|
||||
|
||||
// Several rows share a zero check stamp, so ordering on latest_checked_at
|
||||
// alone gives no stable page boundary. The (site, series_id) tie-break must
|
||||
// make page 2 a strict continuation of page 1: no repeat, no vanishing row.
|
||||
func TestAdminSeriesPageTieBreakIsStable(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
const total = 53 // > one page, < two (page size 50)
|
||||
for i := range total {
|
||||
id := "tie" + strconv.Itoa(i)
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:" + id, url: "u", checkedAt: 0, bookmarks: 1})
|
||||
}
|
||||
// A second Site's zero-stamp row is part of the same all-filter list, and
|
||||
// must land on a valid page boundary rather than duplicating or dropping
|
||||
// one of asura's rows: the tie-break is global (site, series_id).
|
||||
seedAdminSeries(t, s, seriesSeed{key: "demonic:z", url: "u", checkedAt: 0, bookmarks: 1})
|
||||
wantTotal := total + 1
|
||||
|
||||
p1, err := s.SeriesPage(SeriesFilter{Name: SeriesFilterAll})
|
||||
if err != nil {
|
||||
t.Fatalf("SeriesPage page 1: %v", err)
|
||||
}
|
||||
p2, err := s.SeriesPage(SeriesFilter{Name: SeriesFilterAll, Page: 2})
|
||||
if err != nil {
|
||||
t.Fatalf("SeriesPage page 2: %v", err)
|
||||
}
|
||||
if len(p1.Rows) != seriesPageSize {
|
||||
t.Fatalf("page 1 has %d rows, want %d", len(p1.Rows), seriesPageSize)
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, a := range append(append([]AdminSeries{}, p1.Rows...), p2.Rows...) {
|
||||
if seen[a.Key()] {
|
||||
t.Fatalf("row %q repeats across pages", a.Key())
|
||||
}
|
||||
seen[a.Key()] = true
|
||||
}
|
||||
if len(seen) != wantTotal {
|
||||
t.Fatalf("%d distinct rows across pages, want %d (a row vanished)", len(seen), wantTotal)
|
||||
}
|
||||
if p1.Total != wantTotal {
|
||||
t.Fatalf("page total = %d, want %d (the window count must span pages)", p1.Total, wantTotal)
|
||||
}
|
||||
// A page beyond the end is empty, not an error (the list re-reads page 1).
|
||||
// The window count runs over the rows present in the result set, so an
|
||||
// overflow page has no rows and therefore no total — the caller must not
|
||||
// render it, which is exactly why the list re-reads page 1.
|
||||
pFinal, err := s.SeriesPage(SeriesFilter{Name: SeriesFilterAll, Page: 99})
|
||||
if err != nil {
|
||||
t.Fatalf("SeriesPage beyond end: %v", err)
|
||||
}
|
||||
if len(pFinal.Rows) != 0 {
|
||||
t.Fatalf("page beyond end = %d rows, want 0", len(pFinal.Rows))
|
||||
}
|
||||
}
|
||||
|
||||
// The filtered total is the window number over the same filter the rows use,
|
||||
// and the per-Site aggregate sums to the same figure — so the landing page's
|
||||
// count and the list's heading can never disagree, whoever computes them.
|
||||
func TestAdminTotalAgreesWithRowsAndShapes(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:a", url: "u", cover: "a", checkedAt: 9000, bookmarks: 1})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:b", url: "u", checkedAt: 9000, bookmarks: 1})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:c", url: "u", checkedAt: 9000, bookmarks: 1, latestNum: new(2.0), raisedBy: true})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "demonic:d", url: "u", kind: "novel", checkedAt: 9000, bookmarks: 1})
|
||||
|
||||
filters := []SeriesFilter{
|
||||
{},
|
||||
{Name: SeriesFilterNoCover},
|
||||
{Name: SeriesFilterReaderReport},
|
||||
{Name: SeriesFilterNoChapter},
|
||||
}
|
||||
for _, f := range filters {
|
||||
page, err := s.SeriesPage(f)
|
||||
if err != nil {
|
||||
t.Fatalf("SeriesPage(%+v): %v", f, err)
|
||||
}
|
||||
want := len(page.Rows)
|
||||
if f.Page == 0 && want == seriesPageSize {
|
||||
t.Fatalf("seed produced a full page; bump the seed or drop page size in the test")
|
||||
}
|
||||
if page.Total != want {
|
||||
t.Fatalf("%+v total = %d, want %d (window count disagrees with row count)", f, page.Total, want)
|
||||
}
|
||||
shapes, err := s.SeriesShapes(f)
|
||||
if err != nil {
|
||||
t.Fatalf("SeriesShapes(%+v): %v", f, err)
|
||||
}
|
||||
sum := 0
|
||||
for _, sh := range shapes {
|
||||
sum += sh.Total
|
||||
}
|
||||
if sum != want {
|
||||
t.Fatalf("%+v aggregate sum = %d, want %d (aggregate disagrees with row query)", f, sum, want)
|
||||
}
|
||||
}
|
||||
|
||||
// The default filter's aggregate carries the library shape: per-Site
|
||||
// totals and the manga/novel split, summed in Go for library wide.
|
||||
shapes, err := s.SeriesShapes(SeriesFilter{})
|
||||
if err != nil {
|
||||
t.Fatalf("SeriesShapes default: %v", err)
|
||||
}
|
||||
if len(shapes) != 2 || shapes[0].Site != "asura" || shapes[1].Site != "demonic" {
|
||||
t.Fatalf("shapes = %+v, want asura then demonic", shapes)
|
||||
}
|
||||
if shapes[0].Total != 3 || shapes[0].Manga != 3 || shapes[0].Novel != 0 {
|
||||
t.Fatalf("asura shape = %+v, want 3 manga, 0 novel", shapes[0])
|
||||
}
|
||||
if shapes[1].Total != 1 || shapes[1].Manga != 0 || shapes[1].Novel != 1 {
|
||||
t.Fatalf("demonic shape = %+v, want 1 novel", shapes[1])
|
||||
}
|
||||
}
|
||||
|
||||
// Site and Library narrowing stack on a named filter without changing what
|
||||
// the filter means.
|
||||
func TestAdminFilterSiteAndKindNarrow(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:aa", url: "u", checkedAt: 9000, bookmarks: 1, latestNum: new(1.0)})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:ab", url: "", checkedAt: 9000, bookmarks: 1})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "demonic:aa", url: "u", kind: "novel", checkedAt: 9000, bookmarks: 1})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "demonic:ab", url: "", kind: "novel", checkedAt: 9000, bookmarks: 1})
|
||||
|
||||
got := pageKeys(t, s, SeriesFilter{Name: SeriesFilterNoURL, Site: "asura"})
|
||||
if len(got) != 1 || !got["asura:ab"] {
|
||||
t.Fatalf("site+nourl = %v, want only asura:ab", got)
|
||||
}
|
||||
got = pageKeys(t, s, SeriesFilter{Name: SeriesFilterNoURL, Kind: "novel"})
|
||||
if len(got) != 1 || !got["demonic:ab"] {
|
||||
t.Fatalf("kind+nourl = %v, want only demonic:ab", got)
|
||||
}
|
||||
got = pageKeys(t, s, SeriesFilter{Name: SeriesFilterAll, Site: "demonic", Kind: "novel"})
|
||||
if len(got) != 2 || !got["demonic:aa"] || !got["demonic:ab"] {
|
||||
t.Fatalf("site+kind+all = %v, want both demonic rows", got)
|
||||
}
|
||||
|
||||
// The aggregate ignores the Site narrowing (it is per-Site by shape), but
|
||||
// honours the Library narrowing: asura's missing-URL row is manga, so the
|
||||
// novel no-URL list is demonic alone.
|
||||
shapes, err := s.SeriesShapes(SeriesFilter{Name: SeriesFilterNoURL, Kind: "novel"})
|
||||
if err != nil {
|
||||
t.Fatalf("SeriesShapes: %v", err)
|
||||
}
|
||||
if len(shapes) != 1 || shapes[0].Site != "demonic" ||
|
||||
shapes[0].Total != 1 || shapes[0].Novel != 1 {
|
||||
t.Fatalf("novel no-URL aggregate = %+v, want demonic {Total:1 Novel:1}", shapes)
|
||||
}
|
||||
}
|
||||
|
||||
// The projection is the privacy boundary: a Series whose Latest Chapter was
|
||||
// raised by a Reader's report reads back with the anonymous boolean set, not
|
||||
// with the Reader's id, and no Reader id travels in any returned row.
|
||||
func TestAdminSeriesReportsAnonymously(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:raised", url: "u", checkedAt: 9000, latestNum: new(9.0), bookmarks: 1, raisedBy: true})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:polled", url: "u", checkedAt: 9000, latestNum: new(8.0), bookmarks: 1})
|
||||
|
||||
page, err := s.SeriesPage(SeriesFilter{})
|
||||
if err != nil {
|
||||
t.Fatalf("SeriesPage: %v", err)
|
||||
}
|
||||
byKey := map[string]AdminSeries{}
|
||||
for _, a := range page.Rows {
|
||||
byKey[a.Key()] = a
|
||||
}
|
||||
if !byKey["asura:raised"].RaisedByReader {
|
||||
t.Fatal("Reader-raised Series read back RaisedByReader=false")
|
||||
}
|
||||
if byKey["asura:polled"].RaisedByReader {
|
||||
t.Fatal("Poll-raised Series read back RaisedByReader=true")
|
||||
}
|
||||
}
|
||||
|
||||
// The privacy test that cannot rot into a template-only guarantee: assert the
|
||||
// admin column constant does not carry the Sighting-raiser column and that the
|
||||
// admin row type has no field for it, modelled on the guard on the Bookmark
|
||||
// column list.
|
||||
func TestAdminProjectionHidesSightingRaiser(t *testing.T) {
|
||||
if strings.Contains(adminSeriesColumns, "latest_raised_by") {
|
||||
t.Fatal("admin column list carries latest_raised_by: the Sighting-raiser id would reach the owner")
|
||||
}
|
||||
if _, ok := reflect.TypeOf(AdminSeries{}).FieldByName("LatestRaisedBy"); ok {
|
||||
t.Fatal("AdminSeries carries a field for the Sighting-raiser id")
|
||||
}
|
||||
}
|
||||
|
||||
// An unknown filter name is rejected rather than silently meaning "all" —
|
||||
// otherwise a mistyped URL would present an empty page as the whole library.
|
||||
func TestAdminFilterUnknownNameRejected(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:a", url: "u", checkedAt: 9000, bookmarks: 1})
|
||||
for name, call := range map[string]func() error{
|
||||
"page": func() error { _, err := s.SeriesPage(SeriesFilter{Name: "bogus"}); return err },
|
||||
"shape": func() error { _, err := s.SeriesShapes(SeriesFilter{Name: "bogus"}); return err },
|
||||
} {
|
||||
if err := call(); err == nil || !strings.Contains(err.Error(), "unknown series filter") {
|
||||
t.Fatalf("%s with bogus filter = %v, want unknown-filter error", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ForceSeriesPoll is the idempotent stamp write: a second press overwrites
|
||||
// the request time, and touching a missing series is not an error.
|
||||
func TestForceSeriesPollStampsIdempotently(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:x", url: "u", checkedAt: 9000, bookmarks: 1})
|
||||
|
||||
if err := s.ForceSeriesPoll("asura", "x", 42); err != nil {
|
||||
t.Fatalf("ForceSeriesPoll: %v", err)
|
||||
}
|
||||
if err := s.ForceSeriesPoll("asura", "x", 99); err != nil {
|
||||
t.Fatalf("ForceSeriesPoll re-stamp: %v", err)
|
||||
}
|
||||
// Touching a missing series is not an error: the row may have been
|
||||
// orphaned, and the caller's read decides what exists.
|
||||
if err := s.ForceSeriesPoll("asura", "ghost", 99); err != nil {
|
||||
t.Fatalf("ForceSeriesPoll missing: %v", err)
|
||||
}
|
||||
|
||||
var got int64
|
||||
if err := s.db.QueryRow(
|
||||
`SELECT force_poll_at FROM series WHERE site = 'asura' AND series_id = 'x'`).Scan(&got); err != nil {
|
||||
t.Fatalf("read force_poll_at: %v", err)
|
||||
}
|
||||
if got != 99 {
|
||||
t.Fatalf("force_poll_at = %d, want 99 (the later press wins)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The admin projection carries the force stamp so the web layer can derive
|
||||
// the pending flag without a second read.
|
||||
func TestAdminSeriesCarriesForcePollAt(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:x", url: "u", checkedAt: 1000, bookmarks: 1})
|
||||
if err := s.ForceSeriesPoll("asura", "x", 5000); err != nil {
|
||||
t.Fatalf("ForceSeriesPoll: %v", err)
|
||||
}
|
||||
|
||||
page, err := s.SeriesPage(SeriesFilter{})
|
||||
if err != nil {
|
||||
t.Fatalf("SeriesPage: %v", err)
|
||||
}
|
||||
if len(page.Rows) != 1 || page.Rows[0].ForcePollAt != 5000 {
|
||||
t.Fatalf("row = %+v, want ForcePollAt 5000", page.Rows)
|
||||
}
|
||||
}
|
||||
|
||||
// SetSeriesFinished is the owner's finish stamp write: finishing writes the
|
||||
// given ms, un-finishing writes zero — the one undo, the same shape as the
|
||||
// correction stamp. Touching a missing series is not an error: the row may
|
||||
// have been orphaned, and the caller's read decides what exists.
|
||||
func TestSetSeriesFinishedStampsAndClears(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:x", url: "u", checkedAt: 9000, bookmarks: 1})
|
||||
|
||||
if err := s.SetSeriesFinished("asura", "x", 42); err != nil {
|
||||
t.Fatalf("SetSeriesFinished: %v", err)
|
||||
}
|
||||
var got int64
|
||||
if err := s.db.QueryRow(
|
||||
`SELECT finished_at FROM series WHERE site = 'asura' AND series_id = 'x'`).Scan(&got); err != nil {
|
||||
t.Fatalf("read finished_at: %v", err)
|
||||
}
|
||||
if got != 42 {
|
||||
t.Fatalf("finished_at = %d, want 42", got)
|
||||
}
|
||||
|
||||
if err := s.SetSeriesFinished("asura", "x", 0); err != nil {
|
||||
t.Fatalf("SetSeriesFinished un-finish: %v", err)
|
||||
}
|
||||
if err := s.db.QueryRow(
|
||||
`SELECT finished_at FROM series WHERE site = 'asura' AND series_id = 'x'`).Scan(&got); err != nil {
|
||||
t.Fatalf("read finished_at after un-finish: %v", err)
|
||||
}
|
||||
if got != 0 {
|
||||
t.Fatalf("finished_at = %d, want 0 (un-finish writes zero)", got)
|
||||
}
|
||||
|
||||
if err := s.SetSeriesFinished("asura", "ghost", 42); err != nil {
|
||||
t.Fatalf("SetSeriesFinished missing: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The admin projection carries the finish stamp so the web layer can render
|
||||
// the finished state without a second read.
|
||||
func TestAdminSeriesCarriesFinishedAt(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:x", url: "u", checkedAt: 1000, bookmarks: 1})
|
||||
if err := s.SetSeriesFinished("asura", "x", 5000); err != nil {
|
||||
t.Fatalf("SetSeriesFinished: %v", err)
|
||||
}
|
||||
|
||||
page, err := s.SeriesPage(SeriesFilter{})
|
||||
if err != nil {
|
||||
t.Fatalf("SeriesPage: %v", err)
|
||||
}
|
||||
if len(page.Rows) != 1 || page.Rows[0].FinishedAt != 5000 {
|
||||
t.Fatalf("row = %+v, want FinishedAt 5000", page.Rows)
|
||||
}
|
||||
}
|
||||
|
||||
// The failing pair reads the failure row's age, not the Series row (issue
|
||||
// #165): failing requires the joined row, a Latest Chapter, and failing_since
|
||||
// past the cutoff — the same constant stale reads; unverified is the
|
||||
// Reader-attributed subset of the same test. A failure inside the window is
|
||||
// in neither — one bad fetch is not a fault to correct — and a Series that
|
||||
// never captured a chapter is never failing, the exact complement of
|
||||
// never-read-a-chapter's IS NULL half, so the two filters are disjoint by
|
||||
// construction. A finished failing Series still appears: this pair reads
|
||||
// stored outcomes, which simply stop arriving, and carries no finished guard.
|
||||
func TestAdminFailingAndUnverifiedFilters(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
const cutoff = 5000
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:failing", url: "u", cover: "c", checkedAt: 9000, latestNum: new(10.0), bookmarks: 1})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:recent", url: "u", cover: "c", checkedAt: 9000, latestNum: new(9.0), bookmarks: 1})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:nochapter", url: "u", cover: "c", checkedAt: 9000, bookmarks: 1})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:reader", url: "u", cover: "c", checkedAt: 9000, latestNum: new(8.0), bookmarks: 1, raisedBy: true})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:polled", url: "u", cover: "c", checkedAt: 9000, latestNum: new(7.0), bookmarks: 1})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:fin-failing", url: "u", cover: "c", checkedAt: 9000, latestNum: new(6.0), bookmarks: 1})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:healthy", url: "u", cover: "c", checkedAt: 9000, latestNum: new(5.0), bookmarks: 1})
|
||||
|
||||
// Failure rows seed the run's start stamp; the cutoff decides the age.
|
||||
for _, f := range []struct {
|
||||
key, word string
|
||||
since int64
|
||||
}{
|
||||
{"asura:failing", "not_found", 2000},
|
||||
{"asura:recent", "not_found", 9000},
|
||||
{"asura:nochapter", "not_found", 2000},
|
||||
{"asura:reader", "not_found", 2000},
|
||||
{"asura:polled", "errors", 2000},
|
||||
{"asura:fin-failing", "not_found", 2000},
|
||||
} {
|
||||
site, id, _ := strings.Cut(f.key, ":")
|
||||
if err := s.RecordSeriesFailure(site, id, f.word, f.since); err != nil {
|
||||
t.Fatalf("seed failure %s: %v", f.key, err)
|
||||
}
|
||||
}
|
||||
if err := s.SetSeriesFinished("asura", "fin-failing", 1000); err != nil {
|
||||
t.Fatalf("finish asura:fin-failing: %v", err)
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
f SeriesFilter
|
||||
want []string
|
||||
}{
|
||||
{"failing", SeriesFilter{Name: SeriesFilterFailing, Cutoff: cutoff}, []string{"asura:failing", "asura:reader", "asura:polled", "asura:fin-failing"}},
|
||||
{"unverified", SeriesFilter{Name: SeriesFilterUnverified, Cutoff: cutoff}, []string{"asura:reader"}},
|
||||
{"never read a chapter", SeriesFilter{Name: SeriesFilterNoChapter}, []string{"asura:nochapter"}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := pageKeys(t, s, tc.f)
|
||||
want := map[string]bool{}
|
||||
for _, k := range tc.want {
|
||||
want[k] = true
|
||||
}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("%+v returned %v, want exactly %v", tc.f, got, want)
|
||||
}
|
||||
for k := range want {
|
||||
if !got[k] {
|
||||
t.Fatalf("%+v dropped %q (got %v)", tc.f, k, got)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Disjointness: the failing pair and never-read-a-chapter are disjoint by
|
||||
// the chapter column — IS NOT NULL here, IS NULL there — so no row may be
|
||||
// counted under both.
|
||||
failing := pageKeys(t, s, SeriesFilter{Name: SeriesFilterFailing, Cutoff: cutoff})
|
||||
noChapter := pageKeys(t, s, SeriesFilter{Name: SeriesFilterNoChapter})
|
||||
for k := range failing {
|
||||
if noChapter[k] {
|
||||
t.Fatalf("row %q matches both failing and never-read-a-chapter", k)
|
||||
}
|
||||
}
|
||||
if failing["asura:nochapter"] {
|
||||
t.Fatal("a Series with no chapter ever captured appears in failing")
|
||||
}
|
||||
if !noChapter["asura:nochapter"] {
|
||||
t.Fatal("the no-chapter Series vanished from never-read-a-chapter")
|
||||
}
|
||||
|
||||
// The aggregates count the same rows the lists do: the landing page's
|
||||
// figures and the select's options come from these two passes.
|
||||
for _, name := range []string{SeriesFilterFailing, SeriesFilterUnverified} {
|
||||
shapes, err := s.SeriesShapes(SeriesFilter{Name: name, Cutoff: cutoff})
|
||||
if err != nil {
|
||||
t.Fatalf("SeriesShapes(%s): %v", name, err)
|
||||
}
|
||||
sum := 0
|
||||
for _, sh := range shapes {
|
||||
sum += sh.Total
|
||||
}
|
||||
want := len(pageKeys(t, s, SeriesFilter{Name: name, Cutoff: cutoff}))
|
||||
if sum != want {
|
||||
t.Fatalf("%s aggregate sum = %d, want %d (aggregate disagrees with row query)", name, sum, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The projection carries the failure facts from the LEFT JOIN, not the
|
||||
// Series row: a failing Series reads back its outcome word and the stamp its
|
||||
// run began at; a Series with no failure row reads empty and zero. Nothing
|
||||
// new is projected from the Series row itself.
|
||||
func TestAdminFailureProjection(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:broken", url: "u", cover: "c", checkedAt: 9000, latestNum: new(9.0), bookmarks: 1})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:fine", url: "u", cover: "c", checkedAt: 9000, latestNum: new(8.0), bookmarks: 1})
|
||||
if err := s.RecordSeriesFailure("asura", "broken", "not_found", 2000); err != nil {
|
||||
t.Fatalf("seed failure row: %v", err)
|
||||
}
|
||||
|
||||
page, err := s.SeriesPage(SeriesFilter{})
|
||||
if err != nil {
|
||||
t.Fatalf("SeriesPage: %v", err)
|
||||
}
|
||||
byKey := map[string]AdminSeries{}
|
||||
for _, a := range page.Rows {
|
||||
byKey[a.Key()] = a
|
||||
}
|
||||
if byKey["asura:broken"].FailureOutcome != "not_found" || byKey["asura:broken"].FailingSince != 2000 {
|
||||
t.Fatalf("broken row = %+v, want FailureOutcome not_found, FailingSince 2000", byKey["asura:broken"])
|
||||
}
|
||||
if byKey["asura:fine"].FailureOutcome != "" || byKey["asura:fine"].FailingSince != 0 {
|
||||
t.Fatalf("fine row = %+v, want empty outcome and zero stamp", byKey["asura:fine"])
|
||||
}
|
||||
}
|
||||
|
||||
// The site-completed filter (issue #170) lists the Site's own marker as work
|
||||
// to work through, carrying the same finished guard the clock-driven
|
||||
// predicates gained: the Site's stamp keeps standing after the owner retires
|
||||
// the row, so a finished Series would be reported as work nobody is going to
|
||||
// do. A zero stamp never appears. Un-finishing puts the Series back in the
|
||||
// Poll query — the finished_at gate is #157's own, asserted through
|
||||
// DueForLatestCheck rather than re-derived here.
|
||||
func TestAdminSiteCompletedFilter(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:done", url: "u", cover: "c", checkedAt: 9000, latestNum: new(4.0), bookmarks: 1, siteCompletedAt: 5000})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:never", url: "u", cover: "c", checkedAt: 9000, latestNum: new(4.0), bookmarks: 1})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:retired", url: "u", cover: "c", checkedAt: 0, latestNum: new(4.0), bookmarks: 1, siteCompletedAt: 5000})
|
||||
seedAdminSeries(t, s, seriesSeed{key: "asura:healthy", url: "u", cover: "c", checkedAt: 9000, latestNum: new(4.0), bookmarks: 1})
|
||||
if err := s.SetSeriesFinished("asura", "retired", 1000); err != nil {
|
||||
t.Fatalf("finish asura:retired: %v", err)
|
||||
}
|
||||
|
||||
got := pageKeys(t, s, SeriesFilter{Name: SeriesFilterSiteCompleted})
|
||||
if len(got) != 1 || !got["asura:done"] {
|
||||
t.Fatalf("site-completed returned %v, want only asura:done", got)
|
||||
}
|
||||
|
||||
// The projection carries the stamp so the detail page can age it.
|
||||
page, err := s.SeriesPage(SeriesFilter{Name: SeriesFilterSiteCompleted})
|
||||
if err != nil {
|
||||
t.Fatalf("SeriesPage(site_completed): %v", err)
|
||||
}
|
||||
if len(page.Rows) != 1 || page.Rows[0].SiteCompletedAt != 5000 {
|
||||
t.Fatalf("row = %+v, want SiteCompletedAt 5000", page.Rows)
|
||||
}
|
||||
|
||||
// The aggregate counts the same row: the landing figure and the select's
|
||||
// option come from this pass, so they cannot disagree with the list.
|
||||
shapes, err := s.SeriesShapes(SeriesFilter{Name: SeriesFilterSiteCompleted})
|
||||
if err != nil {
|
||||
t.Fatalf("SeriesShapes(site_completed): %v", err)
|
||||
}
|
||||
sum := 0
|
||||
for _, sh := range shapes {
|
||||
sum += sh.Total
|
||||
}
|
||||
if sum != 1 {
|
||||
t.Fatalf("site-completed aggregate = %d, want 1", sum)
|
||||
}
|
||||
|
||||
// Un-finishing puts the Series back in the Poll query: the due read's
|
||||
// finished_at gate (issue #157) admits it again — asserted through the
|
||||
// Lane's own read, not re-derived here.
|
||||
due, err := s.DueForLatestCheck("asura", 1000, noCeiling)
|
||||
if err != nil {
|
||||
t.Fatalf("DueForLatestCheck: %v", err)
|
||||
}
|
||||
for _, sr := range due {
|
||||
if sr.Key() == "asura:retired" {
|
||||
t.Fatalf("a finished Series is still due for a Poll:\n%+v", due)
|
||||
}
|
||||
}
|
||||
if err := s.SetSeriesFinished("asura", "retired", 0); err != nil {
|
||||
t.Fatalf("un-finish asura:retired: %v", err)
|
||||
}
|
||||
due, err = s.DueForLatestCheck("asura", 1000, noCeiling)
|
||||
if err != nil {
|
||||
t.Fatalf("DueForLatestCheck after un-finish: %v", err)
|
||||
}
|
||||
found := false
|
||||
for _, sr := range due {
|
||||
if sr.Key() == "asura:retired" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("un-finished Series is not due for a Poll:\n%+v", due)
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,8 @@
|
||||
-- The Cover splits into two facts. `cover` keeps the third-party address the
|
||||
-- bytes come from, which is what the refetch path dedupes on; `cover_address`
|
||||
-- is the content address of the bytes once they are actually stored, and is
|
||||
-- what the wire's absolute URL is built from.
|
||||
-- bytes come from, which is what the acquisition path refetches and dedupes
|
||||
-- on; `cover_address` is the content address of the bytes once they are
|
||||
-- actually stored, and is what the wire's absolute URL is built from.
|
||||
--
|
||||
-- Empty `cover_address` therefore means "no Cover yet" rather than "a Cover
|
||||
-- that 404s", which is the distinction the API and the UI both depend on.
|
||||
--
|
||||
-- The content address was originally the hex SHA-256 of the source URL
|
||||
-- (ADR-0007). Since ADR-0014 it is the hex SHA-256 of the bytes themselves,
|
||||
-- so a re-art behind the same URL is a new address. Rows written before
|
||||
-- ADR-0014 keep their URL-derived addresses; they are never rehashed and heal
|
||||
-- into byte addressing on their first forced replacement. Both derivations
|
||||
-- share the 64-hex-digit shape, so the serving guard is unchanged.
|
||||
ALTER TABLE series ADD COLUMN cover_address text NOT NULL DEFAULT '';
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
-- One durable state row per Poll Lane. Zero means no pause or refusal is set.
|
||||
CREATE TABLE poll_lanes (
|
||||
site text NOT NULL PRIMARY KEY,
|
||||
paused_until bigint NOT NULL DEFAULT 0,
|
||||
refuse_until bigint NOT NULL DEFAULT 0
|
||||
);
|
||||
@@ -1,16 +0,0 @@
|
||||
-- Append-only Lane Pass log. Timestamps are unix milliseconds from the poller's clock.
|
||||
CREATE TABLE poll_passes (
|
||||
site text NOT NULL,
|
||||
ran_at bigint NOT NULL,
|
||||
skip text NOT NULL,
|
||||
due integer NOT NULL,
|
||||
checked integer NOT NULL,
|
||||
gap_ms bigint NOT NULL,
|
||||
clamped boolean NOT NULL,
|
||||
refused integer NOT NULL,
|
||||
unreachable integer NOT NULL,
|
||||
no_chapter integer NOT NULL,
|
||||
unfetchable integer NOT NULL,
|
||||
errors integer NOT NULL,
|
||||
PRIMARY KEY (site, ran_at)
|
||||
);
|
||||
@@ -1,11 +0,0 @@
|
||||
-- Admin read-model foundation (#140). The Series list's default order is
|
||||
-- least-recently-checked first, so the table — which has only its primary key
|
||||
-- today — gets an index that can serve it. A grouped query over a join may
|
||||
-- ignore the index, so this is a judgement, not a measurement: re-time on real
|
||||
-- data before adding a second.
|
||||
CREATE INDEX series_latest_checked_at_idx ON series (latest_checked_at);
|
||||
|
||||
-- force_poll_at is the "ask for one Series to be checked now" stamp (#146).
|
||||
-- Zero means never forced; nothing reads the column before that ticket wires
|
||||
-- it, so it lands here unused.
|
||||
ALTER TABLE series ADD COLUMN force_poll_at bigint NOT NULL DEFAULT 0;
|
||||
@@ -1,4 +0,0 @@
|
||||
-- latest_corrected_at is the "the current Latest Chapter is the owner's" stamp
|
||||
-- (#149). Written by the Correction; zeroed by every machine write of the
|
||||
-- value. Zero means never corrected.
|
||||
ALTER TABLE series ADD COLUMN latest_corrected_at bigint NOT NULL DEFAULT 0;
|
||||
@@ -1,24 +0,0 @@
|
||||
-- finished_at is "the owner marked this Series finished" (#157): epoch ms,
|
||||
-- zero means not finished, and it doubles as the undo (write zero). The poll
|
||||
-- gate reads it — a Series is polled only while finished_at = 0 — never a
|
||||
-- bookmark's status.
|
||||
ALTER TABLE series ADD COLUMN finished_at bigint NOT NULL DEFAULT 0;
|
||||
|
||||
-- Column first, seed second, flip third — the order is load-bearing: a seed
|
||||
-- that ran after the flip would read the buckets it just destroyed, declare
|
||||
-- nothing finished, and silently resume polling on Series nobody chose to
|
||||
-- resume. The seed mirrors the pre-cutover due gate exactly: a Series stays
|
||||
-- polled while any bookmark is outside the finished bucket, so a Series whose
|
||||
-- every bookmark sits in it is stamped, one click from being read again
|
||||
-- afterwards. The stamp is the only memory of the bucket the flip is about to
|
||||
-- erase.
|
||||
UPDATE series s SET finished_at = (EXTRACT(EPOCH FROM now()) * 1000)::bigint
|
||||
WHERE EXISTS (SELECT 1 FROM bookmarks b
|
||||
WHERE b.site = s.site AND b.series_id = s.series_id)
|
||||
AND NOT EXISTS (SELECT 1 FROM bookmarks b
|
||||
WHERE b.site = s.site AND b.series_id = s.series_id
|
||||
AND b.status <> 'finished');
|
||||
|
||||
-- The Lifecycle bucket is gone; a finished bookmark is an archived one. The
|
||||
-- flip must come after the seed, which still reads the bucket.
|
||||
UPDATE bookmarks SET status = 'archived' WHERE status = 'finished';
|
||||
@@ -1,4 +0,0 @@
|
||||
-- A 4xx other than the 403 refusal is the page being gone, not the Site being
|
||||
-- unwell; the pass log counts it separately so the Lanes page can say "not
|
||||
-- found" (#164). DEFAULT 0 keeps pre-existing rows readable.
|
||||
ALTER TABLE poll_passes ADD COLUMN not_found integer NOT NULL DEFAULT 0;
|
||||
@@ -1,13 +0,0 @@
|
||||
-- One row per Series that is failing right now (ADR-0016): the row's
|
||||
-- existence is the failure state, failing_since ages the run of failures,
|
||||
-- and a correct read deletes the row. Keyed by the same (site, series_id)
|
||||
-- composite the rest of the system uses, with the cascade so deleting a
|
||||
-- Series takes its failure row and orphan removal stays a single statement.
|
||||
CREATE TABLE poll_failures (
|
||||
site text NOT NULL,
|
||||
series_id text NOT NULL,
|
||||
outcome text NOT NULL,
|
||||
failing_since bigint NOT NULL,
|
||||
PRIMARY KEY (site, series_id),
|
||||
FOREIGN KEY (site, series_id) REFERENCES series (site, series_id) ON DELETE CASCADE
|
||||
);
|
||||
@@ -1,4 +0,0 @@
|
||||
-- When the last successful Poll read saw the Site's own completed value
|
||||
-- (#168): epoch-ms, zero meaning it did not. DEFAULT 0 keeps pre-existing
|
||||
-- rows readable.
|
||||
ALTER TABLE series ADD COLUMN site_completed_at bigint NOT NULL DEFAULT 0;
|
||||
@@ -1,12 +0,0 @@
|
||||
-- Owner notices (issue #171): one row per episode, remembered only as "the
|
||||
-- owner was told". The row's presence is the whole state — the poller checks
|
||||
-- it before sending, writes it after a successful send, and clears it when
|
||||
-- the condition no longer holds. site is '' for a fault that is not one
|
||||
-- Site's; the composite primary key is what makes the row a lock against a
|
||||
-- second message for the same episode.
|
||||
CREATE TABLE owner_notices (
|
||||
condition text NOT NULL,
|
||||
site text NOT NULL,
|
||||
notified_at bigint NOT NULL,
|
||||
PRIMARY KEY (condition, site)
|
||||
);
|
||||
+76
-713
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+117
-43
@@ -4,31 +4,71 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"bookmarkmanager/backend/internal/latest"
|
||||
"bookmarkmanager/backend/internal/store"
|
||||
)
|
||||
|
||||
// ownerWindow is the staleness boundary the Series list's "not checked in
|
||||
// 12h" filter compares against. It reads latest.OwnerWindow — the one place
|
||||
// the class-level twelve hours lives, shared with the owner-notice
|
||||
// conditions (issue #171).
|
||||
const ownerWindow = latest.OwnerWindow
|
||||
// LaneReporter is the administrative page's whole window onto the running
|
||||
// poller: one snapshot of Poll Lane state, copied out of memory on request.
|
||||
// The Poller satisfies it in production and a fake with fixed values satisfies
|
||||
// it in tests, so the page's tests need neither a poller nor a Site.
|
||||
type LaneReporter interface {
|
||||
LaneStatus() latest.Status
|
||||
}
|
||||
|
||||
// adminView is the shared shell data for an administrative page and the roster
|
||||
// fragment returned after a Reader action.
|
||||
// adminView is what the administrative page and the roster fragment receive.
|
||||
type adminView struct {
|
||||
Page string
|
||||
Readers []store.ReaderSummary
|
||||
// OwnerID travels with the roster so it can tell the owner's own row from
|
||||
// the Readers they may act on.
|
||||
OwnerID int64
|
||||
Lanes lanesView
|
||||
SeriesList seriesListView
|
||||
// Detail is the per-Series page data; zero on every other page.
|
||||
Detail seriesDetailView
|
||||
// Overview is the landing page data; zero on every other page.
|
||||
Overview overviewView
|
||||
}
|
||||
|
||||
// lanesView is the Lane status block: one row per Site that has run, plus the
|
||||
// browser fact, which is shared by the three browser Sites rather than held
|
||||
// once per Site.
|
||||
type lanesView struct {
|
||||
Rows []laneRow
|
||||
// PollerOff means no poller is running at all (disabled by config, or its
|
||||
// client could not be built). The browser line must not answer "not
|
||||
// configured" then: the sidecar is not the reason nothing is polled.
|
||||
PollerOff bool
|
||||
BrowserConfigured bool
|
||||
BrowserReachable bool
|
||||
}
|
||||
|
||||
// laneRow is one Lane formatted for reading rather than for arithmetic: the
|
||||
// template renders strings and flags, and every judgement about what they mean
|
||||
// is made here.
|
||||
type laneRow struct {
|
||||
Site string
|
||||
Due int
|
||||
Ran string
|
||||
// Checked is how many Series the last pass read. Due without Checked is a
|
||||
// Lane that has stopped working; the two figures side by side are what
|
||||
// separate that from a Lane with nothing to do.
|
||||
Checked int
|
||||
// Gap is empty when no pass has reached the pace yet, so the row omits the
|
||||
// figure instead of stating a zero.
|
||||
Gap string
|
||||
Clamped bool
|
||||
Refusing bool
|
||||
// BrowserLost marks a Lane whose pages can only be read through the
|
||||
// sidecar while the sidecar is unreachable — including the case where none
|
||||
// is configured, which stops those Series just as completely.
|
||||
BrowserLost bool
|
||||
// Stalled marks a Lane with Series waiting that its last pass did not read
|
||||
// — the difference between a stopped Lane and a quiet one (story 13). A
|
||||
// browser Lane holding Chrome asleep under the wake thresholds is neither,
|
||||
// so it carries Asleep instead and never Stalled.
|
||||
Stalled bool
|
||||
Asleep bool
|
||||
// Attention is the one flag the template colours on, so an unhealthy Lane
|
||||
// is found at a glance rather than read for.
|
||||
Attention bool
|
||||
}
|
||||
|
||||
// adminRoute pairs a route pattern with its handler so the route list and the
|
||||
@@ -44,18 +84,6 @@ type adminRoute struct {
|
||||
func (h *Handler) adminRoutes() []adminRoute {
|
||||
return []adminRoute{
|
||||
{"GET /admin", h.admin},
|
||||
{"GET /admin/lanes", h.adminLanes},
|
||||
{"GET /admin/readers", h.adminReaders},
|
||||
{"GET /admin/series", h.adminSeries},
|
||||
{"GET /admin/series/{key}", h.adminSeriesDetail},
|
||||
{"POST /admin/series/{key}/poll", h.adminSeriesPoll},
|
||||
{"POST /admin/series/{key}/finish", h.adminSeriesFinish},
|
||||
{"POST /admin/series/{key}/unfinish", h.adminSeriesUnfinish},
|
||||
{"POST /admin/series/{key}/latest", h.adminSeriesCorrectLatest},
|
||||
{"POST /admin/series/{key}/series-url", h.adminSeriesSetURL},
|
||||
{"POST /admin/series/{key}/remove", h.adminSeriesRemove},
|
||||
{"POST /admin/lanes/{site}/pause", h.adminLanePause},
|
||||
{"POST /admin/lanes/{site}/resume", h.adminLaneResume},
|
||||
{"GET /ui/admin/lanes", h.uiLanes},
|
||||
{"POST /readers/{id}/revoke", h.revokeReaderSessions},
|
||||
{"POST /readers/{id}/clear-marks", h.clearReaderMarks},
|
||||
@@ -88,32 +116,78 @@ func (h *Handler) requireOwner(next http.HandlerFunc) http.HandlerFunc {
|
||||
})
|
||||
}
|
||||
|
||||
// admin renders the Overview landing page: a verdict line, a stats block
|
||||
// where every figure is a door into the list it counts, and the per-Site
|
||||
// library shape table — all read from the database, never from a poller.
|
||||
// admin renders the owner's page: the Reader roster and Poll Lane status.
|
||||
func (h *Handler) admin(w http.ResponseWriter, r *http.Request) {
|
||||
view, err := h.overviewView()
|
||||
if err != nil {
|
||||
log.Printf("admin overview: %v", err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
h.renderAdmin(w, adminView{Page: "overview", Overview: view})
|
||||
}
|
||||
|
||||
// adminReaders renders the Reader roster on its own bookmarkable page.
|
||||
func (h *Handler) adminReaders(w http.ResponseWriter, r *http.Request) {
|
||||
readers, err := h.store.Readers()
|
||||
if err != nil {
|
||||
log.Printf("admin readers: %v", err)
|
||||
log.Printf("admin: %v", err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
h.renderAdmin(w, adminView{Page: "readers", Readers: readers, OwnerID: h.store.OwnerID()})
|
||||
h.render(w, http.StatusOK, "admin", adminView{
|
||||
Readers: readers,
|
||||
OwnerID: h.store.OwnerID(),
|
||||
Lanes: h.lanesView(),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) renderAdmin(w http.ResponseWriter, view adminView) {
|
||||
h.render(w, http.StatusOK, "admin", view)
|
||||
// uiLanes answers the status block's own refresh. Only the block refreshes on a
|
||||
// timer; the roster re-renders after an action, as it always has.
|
||||
func (h *Handler) uiLanes(w http.ResponseWriter, r *http.Request) {
|
||||
h.render(w, http.StatusOK, "lanes", h.lanesView())
|
||||
}
|
||||
|
||||
// lanesView copies the poller's snapshot into display form. A nil reporter (no
|
||||
// poller running) and a poller no Lane has reported to yet are the same thing
|
||||
// to the page: no data, which it must say rather than draw as confident zeroes
|
||||
// — an empty page a few seconds after a restart must not read as a stopped one.
|
||||
func (h *Handler) lanesView() lanesView {
|
||||
if h.lanes == nil {
|
||||
return lanesView{PollerOff: true}
|
||||
}
|
||||
snap := h.lanes.LaneStatus()
|
||||
v := lanesView{
|
||||
Rows: make([]laneRow, 0, len(snap.Lanes)),
|
||||
BrowserConfigured: snap.BrowserConfigured,
|
||||
BrowserReachable: snap.BrowserReachable,
|
||||
}
|
||||
now := time.Now()
|
||||
for _, l := range snap.Lanes {
|
||||
lost := l.Browser && !snap.BrowserReachable
|
||||
// Series waiting and none read is the shape of a Lane that has stopped
|
||||
// working, as distinct from one that is quiet for want of work — or one
|
||||
// deliberately leaving Chrome asleep until its group gathers.
|
||||
stalled := l.Due > 0 && l.Checked == 0 && !l.Asleep
|
||||
gap := ""
|
||||
if l.Gap > 0 {
|
||||
gap = l.Gap.Truncate(time.Second).String()
|
||||
}
|
||||
v.Rows = append(v.Rows, laneRow{
|
||||
Site: l.Site,
|
||||
Due: l.Due,
|
||||
Ran: since(now, l.LastRun),
|
||||
Checked: l.Checked,
|
||||
Gap: gap,
|
||||
Clamped: l.Clamped,
|
||||
Refusing: l.Refusing,
|
||||
BrowserLost: lost,
|
||||
Stalled: stalled,
|
||||
Asleep: l.Asleep,
|
||||
Attention: l.Clamped || l.Refusing || lost || stalled,
|
||||
})
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// since formats how long ago a Lane last ran, at second resolution: the block
|
||||
// refreshes every thirty seconds, so anything finer is noise the owner would
|
||||
// have to ignore.
|
||||
func since(now, then time.Time) string {
|
||||
d := now.Sub(then).Truncate(time.Second)
|
||||
if d < time.Second {
|
||||
return "just now"
|
||||
}
|
||||
return d.String() + " ago"
|
||||
}
|
||||
|
||||
// revokeReaderSessions logs one Reader out of every browser they are signed in
|
||||
|
||||
@@ -1,350 +0,0 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"bookmarkmanager/backend/internal/latest"
|
||||
"bookmarkmanager/backend/internal/store"
|
||||
)
|
||||
|
||||
// lanesView is the Lane status block: one row per Site's latest durable pass,
|
||||
// plus the browser fact derived from that same log. No poller is consulted —
|
||||
// the page answers from the database, so it is complete thirty seconds after
|
||||
// a deploy (issue #145).
|
||||
type lanesView struct {
|
||||
Rows []laneRow
|
||||
// PollerOff means latest-chapter polling is switched off in this
|
||||
// deployment (LATEST_CHAPTER_POLL_ENABLED). It is a config fact, not a
|
||||
// poller answering "absent": the browser line must not blame the sidecar
|
||||
// when nothing polls.
|
||||
PollerOff bool
|
||||
BrowserConfigured bool
|
||||
BrowserReachable bool
|
||||
}
|
||||
|
||||
// laneRow is one Lane formatted for reading rather than for arithmetic: the
|
||||
// template renders strings and flags, and every judgement about what they
|
||||
// mean is made here.
|
||||
type laneRow struct {
|
||||
Site string
|
||||
Due int
|
||||
Checked int
|
||||
// Gap is the last pass's pace, or "—" when no pass has reached one yet —
|
||||
// a refused Lane still reports the pace its last real pass chose, so a
|
||||
// zero here would be a figure the row never measured.
|
||||
Gap string
|
||||
Ran string
|
||||
// Chips are the named outcome counts over the owner's window, in the
|
||||
// taxonomy's fixed order. Empty writes "none observed".
|
||||
Chips []chip
|
||||
HasChips bool
|
||||
// StatePhrase is the reason this Lane declined to work: a skipped pass's
|
||||
// own sentence, or the one true stall. Empty means the pass reached its
|
||||
// loop and read normally. StateGood marks a healthy way to do nothing
|
||||
// (paused, browser asleep, nothing eligible) rather than a fault.
|
||||
StatePhrase string
|
||||
StateGood bool
|
||||
// Attention is the one flag the template colours on, so a Lane that
|
||||
// needs the owner is found at a glance rather than read for.
|
||||
Attention bool
|
||||
// Paused is the live pause state — the poll_lanes stamp the pass row
|
||||
// joins on, still in the future — not the pass's skip: the control must
|
||||
// offer Resume from the moment the owner presses Pause, with no pass
|
||||
// having run to record it (issue #147).
|
||||
Paused bool
|
||||
// FailingHref is the one navigation the row offers: the Site's name
|
||||
// links to that Site's failing Series. The chips beside it stay
|
||||
// unlinked; the withdrawn promise lives on outcomeChips (issue #167).
|
||||
FailingHref string
|
||||
}
|
||||
|
||||
// chip is one named outcome count over the owner's window.
|
||||
type chip struct {
|
||||
Name string
|
||||
Count int
|
||||
}
|
||||
|
||||
// adminLanes renders the page that hosts the live Lane fragment.
|
||||
func (h *Handler) adminLanes(w http.ResponseWriter, r *http.Request) {
|
||||
h.renderAdmin(w, adminView{Page: "lanes", Lanes: h.lanesView()})
|
||||
}
|
||||
|
||||
// uiLanes answers the status block's own refresh. Only the block refreshes on
|
||||
// a timer; the roster re-renders after an action, as it always has.
|
||||
func (h *Handler) uiLanes(w http.ResponseWriter, r *http.Request) {
|
||||
h.render(w, http.StatusOK, "lanes", h.lanesView())
|
||||
}
|
||||
|
||||
// pauseDurations are the offered pause lengths, by their wire value. A fixed
|
||||
// allow-list rather than time.ParseDuration: the unoffered value must be
|
||||
// refused, and a permissive parser turns the offered set into "anything Go
|
||||
// can read" (issue #147).
|
||||
var pauseDurations = map[string]time.Duration{
|
||||
"1h": time.Hour,
|
||||
"6h": 6 * time.Hour,
|
||||
"24h": 24 * time.Hour,
|
||||
}
|
||||
|
||||
// laneSite reads the Site a lane route names, answering the request itself
|
||||
// when it is not a registry Site. The path value is client-supplied, so it
|
||||
// is checked against the registry before it reaches the store.
|
||||
func laneSite(w http.ResponseWriter, r *http.Request) (string, bool) {
|
||||
site := r.PathValue("site")
|
||||
if !slices.Contains(latest.SiteNames(), site) {
|
||||
http.Error(w, "unknown site", http.StatusBadRequest)
|
||||
return "", false
|
||||
}
|
||||
return site, true
|
||||
}
|
||||
|
||||
// adminLanePause writes a bounded pause for one Site and answers with the
|
||||
// freshly rendered Lanes block, so the figures describe the state after the
|
||||
// press. The pause is a fact about the Site — the Lane's next pass reads it
|
||||
// from the durable row, never from this process — so it survives a restart.
|
||||
// The owner gate is the route's, not this handler's; the body is capped like
|
||||
// the API path caps its bodies; the Site and the duration are validated
|
||||
// here, before the store sees them (issue #147).
|
||||
func (h *Handler) adminLanePause(w http.ResponseWriter, r *http.Request) {
|
||||
site, ok := laneSite(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 1<<16)
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, "invalid form", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
d, ok := pauseDurations[r.PostFormValue("duration")]
|
||||
if !ok {
|
||||
http.Error(w, "unknown pause duration", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := h.store.PauseLane(site, time.Now().Add(d).UnixMilli()); err != nil {
|
||||
log.Printf("pause lane %s: %v", site, err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
h.render(w, http.StatusOK, "lanes", h.lanesView())
|
||||
}
|
||||
|
||||
// adminLaneResume zeroes one Site's pause and answers with the freshly
|
||||
// rendered Lanes block. Resume is the reversal of a bounded pause, so it
|
||||
// fires instantly with no confirm row (issue #147).
|
||||
func (h *Handler) adminLaneResume(w http.ResponseWriter, r *http.Request) {
|
||||
site, ok := laneSite(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 1<<16)
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, "invalid form", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := h.store.ResumeLane(site); err != nil {
|
||||
log.Printf("resume lane %s: %v", site, err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
h.render(w, http.StatusOK, "lanes", h.lanesView())
|
||||
}
|
||||
|
||||
// lanesView builds the Lane status block from the durable pass log. Both
|
||||
// reads are the store's latest-per-Site projection, so the page's seam is a
|
||||
// seeded row rather than a fake poller; errors degrade to the empty state and
|
||||
// are logged, never shown to the owner in detail.
|
||||
func (h *Handler) lanesView() lanesView {
|
||||
v := lanesView{
|
||||
PollerOff: !h.pollerEnabled,
|
||||
BrowserConfigured: h.browserConfigured,
|
||||
}
|
||||
passes, err := h.store.LatestLanePasses()
|
||||
if err != nil {
|
||||
log.Printf("admin lanes: latest passes: %v", err)
|
||||
// No evidence of a lost sidecar reads as reachable, per the same rule
|
||||
// browserReachable applies: a store failure must not condemn the
|
||||
// browser. The empty table already says no Lane has recorded a pass.
|
||||
v.BrowserReachable = true
|
||||
return v
|
||||
}
|
||||
now := time.Now()
|
||||
outcomes, err := h.store.LanePassOutcomes(now.Add(-ownerWindow).UnixMilli())
|
||||
if err != nil {
|
||||
// The rows are complete without the chips, so a failed outcome sum
|
||||
// must not blank the table into "no data yet" — that is the confident
|
||||
// wrong statement the page exists to avoid. Every row renders "none
|
||||
// observed" instead, which is honest.
|
||||
log.Printf("admin lanes: outcomes: %v", err)
|
||||
outcomes = nil
|
||||
}
|
||||
bySite := make(map[string]store.SiteOutcomes, len(outcomes))
|
||||
for _, o := range outcomes {
|
||||
bySite[o.Site] = o
|
||||
}
|
||||
v.Rows = make([]laneRow, 0, len(passes))
|
||||
v.BrowserReachable = browserReachable(passes, now)
|
||||
for _, p := range passes {
|
||||
v.Rows = append(v.Rows, buildLaneRow(p, bySite[p.Site], now))
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// browserReachable derives the sidecar's reachability from the pass log: a
|
||||
// browser Site is down when its latest pass inside the refusal backoff is a
|
||||
// sidecar loss, a missing fetcher, or an interrupted read. Only browser Sites
|
||||
// ever produce those signals, so no Site registry leaks into the web layer.
|
||||
// A configured browser with no such evidence reads as reachable; an unset
|
||||
// BROWSER_WS_URL degrades identically to a browser that is down.
|
||||
func browserReachable(passes []store.LanePass, now time.Time) bool {
|
||||
backoff := latest.RefuseBackoff
|
||||
for _, p := range passes {
|
||||
ran := time.UnixMilli(p.RanAt)
|
||||
if now.Sub(ran) >= backoff || ran.After(now) {
|
||||
continue
|
||||
}
|
||||
if p.Skip == latest.SkipSidecarDown || p.Skip == latest.SkipNoFetcher || p.Unreachable > 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// buildLaneRow turns one Site's latest pass and window outcome sums into the
|
||||
// row the template prints. The skip column is the authority on why a pass did
|
||||
// nothing; the outcomes render named and unlinked, because the pass row holds
|
||||
// counts and never identities.
|
||||
func buildLaneRow(p store.LanePass, o store.SiteOutcomes, now time.Time) laneRow {
|
||||
row := laneRow{
|
||||
Site: p.Site,
|
||||
Due: p.Due,
|
||||
Checked: p.Checked,
|
||||
Gap: "—",
|
||||
Ran: since(now, time.UnixMilli(p.RanAt)),
|
||||
}
|
||||
if p.GapMS > 0 {
|
||||
row.Gap = (time.Duration(p.GapMS) * time.Millisecond).Truncate(time.Second).String()
|
||||
}
|
||||
row.FailingHref = seriesListHref(store.SeriesFilterFailing, p.Site, "", 0)
|
||||
row.Chips = outcomeChips(o)
|
||||
row.HasChips = len(row.Chips) > 0
|
||||
row.StatePhrase, row.StateGood, row.Attention = laneState(p, now)
|
||||
row.Paused = time.UnixMilli(p.PausedUntil).After(now)
|
||||
return row
|
||||
}
|
||||
|
||||
// outcomeChips lists a Site's nonzero window sums in the taxonomy's fixed
|
||||
// order, so the chips never reorder as the window changes. None observed is
|
||||
// written by the template, not drawn as a confident zero count. The names are
|
||||
// spelled through outcomeWord, the one vocabulary the failure surface shares
|
||||
// with the Series list's fact line (issue #167). The counts stay unlinked
|
||||
// permanently — a withdrawn promise: two of the six words write no per-Series
|
||||
// state, and the other four count attempts inside the owner window while the
|
||||
// failing filter lists Series failing now, so neither set contains the other
|
||||
// and no chip can be a door to its list.
|
||||
func outcomeChips(o store.SiteOutcomes) []chip {
|
||||
fixed := []struct {
|
||||
name string
|
||||
count int
|
||||
}{
|
||||
{outcomeWord("refused"), o.Refused},
|
||||
{outcomeWord("unreachable"), o.Unreachable},
|
||||
{outcomeWord("no_chapter"), o.NoChapter},
|
||||
{outcomeWord("unfetchable"), o.Unfetchable},
|
||||
{outcomeWord("not_found"), o.NotFound},
|
||||
{outcomeWord("errors"), o.Errors},
|
||||
}
|
||||
var out []chip
|
||||
for _, f := range fixed {
|
||||
if f.count > 0 {
|
||||
out = append(out, chip{Name: f.name, Count: f.count})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// laneState renders the reason a Lane's last pass did nothing, in one sentence
|
||||
// per skip value with the one true stall kept apart from every Lane that
|
||||
// declined and said why. Good states — a pause, a sleeping browser, nothing
|
||||
// eligible — carry no Attention: the mark must stay spendable on the faults
|
||||
// that actually need the owner.
|
||||
func laneState(p store.LanePass, now time.Time) (phrase string, good, attention bool) {
|
||||
// The pause phrase reads the live poll_lanes stamp the pass row joins
|
||||
// on, not the pass's skip: the owner's press must render as paused on
|
||||
// the very answer it gets, with no pass having run to record it. The
|
||||
// pause is a fact about the Site, and the join delivers it (issue #147).
|
||||
if pausedUntil := time.UnixMilli(p.PausedUntil); pausedUntil.After(now) {
|
||||
phrase = "paused · resumes in " + humanDuration(pausedUntil.Sub(now))
|
||||
good = true
|
||||
return phrase, good, attention
|
||||
}
|
||||
switch p.Skip {
|
||||
case latest.SkipPaused:
|
||||
// A paused pass whose stamp has since lapsed: the Lane still
|
||||
// declined with a reason, so it is never the one true stall.
|
||||
phrase = "paused · resumes in " + humanDuration(time.UnixMilli(p.PausedUntil).Sub(now))
|
||||
good = true
|
||||
case latest.SkipRefusing:
|
||||
phrase = "refusing"
|
||||
if until := time.UnixMilli(p.RefuseUntil); until.After(now) {
|
||||
phrase += " · backs off until " + until.Format("15:04")
|
||||
}
|
||||
attention = true
|
||||
case latest.SkipSidecarDown, latest.SkipNoFetcher:
|
||||
// Known false positive shipped per spec: a sibling Lane's Chrome loss
|
||||
// stamps this Site too, and the enum deliberately has no tenth value
|
||||
// to separate it (issue #141). Render it as written.
|
||||
phrase = "no browser"
|
||||
attention = true
|
||||
case latest.SkipAsleep:
|
||||
phrase = "browser asleep"
|
||||
good = true
|
||||
case latest.SkipDueQuery:
|
||||
phrase = "due query failed"
|
||||
attention = true
|
||||
case latest.SkipEligibleCount:
|
||||
phrase = "eligible count failed"
|
||||
attention = true
|
||||
case latest.SkipNothingEligible:
|
||||
phrase = "nothing eligible"
|
||||
good = true
|
||||
}
|
||||
if phrase == "" && p.Due > 0 && p.Checked == 0 {
|
||||
// The one true stall: the pass reached its loop, Series were waiting,
|
||||
// and none were read. Every skip above is a Lane that said why.
|
||||
phrase = "not checking"
|
||||
attention = true
|
||||
}
|
||||
return phrase, good, attention
|
||||
}
|
||||
|
||||
// humanDuration renders a positive duration compactly for a "resumes in" clue
|
||||
// at the pause and refusal scales — minutes under an hour, then h and h+m.
|
||||
func humanDuration(d time.Duration) string {
|
||||
d = d.Round(time.Minute)
|
||||
if d <= 0 {
|
||||
return "soon"
|
||||
}
|
||||
if d < time.Hour {
|
||||
return fmt.Sprintf("%dm", int(d/time.Minute))
|
||||
}
|
||||
h := int(d / time.Hour)
|
||||
if m := int(d%time.Hour) / int(time.Minute); m == 0 {
|
||||
return fmt.Sprintf("%dh", h)
|
||||
} else {
|
||||
return fmt.Sprintf("%dh%dm", h, m)
|
||||
}
|
||||
}
|
||||
|
||||
// since formats how long ago a Lane last ran, at second resolution: the block
|
||||
// refreshes every thirty seconds, so anything finer is noise the owner would
|
||||
// have to ignore.
|
||||
func since(now, then time.Time) string {
|
||||
d := now.Sub(then).Truncate(time.Second)
|
||||
if d < time.Second {
|
||||
return "just now"
|
||||
}
|
||||
return d.String() + " ago"
|
||||
}
|
||||
@@ -1,230 +0,0 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"bookmarkmanager/backend/internal/latest"
|
||||
"bookmarkmanager/backend/internal/store"
|
||||
)
|
||||
|
||||
// overviewView is the Overview landing page's data: one verdict line, the
|
||||
// hygiene and library stats blocks, and the per-Site library shape table.
|
||||
// Every judgement — the verdict state, which figures link, what a Lane's
|
||||
// state means — is made here; the template only prints.
|
||||
type overviewView struct {
|
||||
// Verdict is the attention phrase that leads the page.
|
||||
Verdict string
|
||||
// HasCounts is false on a virgin pass log: the waiting figure would be a
|
||||
// confident zero, and "nothing has happened" must not render as health.
|
||||
HasCounts bool
|
||||
// Waiting is the sum of Due over the latest pass per Site.
|
||||
Waiting int
|
||||
// Unchecked is the number of Series not checked in the window, computed
|
||||
// as stale + never_checked: a never-checked Series is already counted on
|
||||
// its own filter, and the verdict wants the inclusive number.
|
||||
Unchecked int
|
||||
// Hygiene is the problem filters in the Series list's own render order
|
||||
// plus the informational tail — finished, then site completed — riding
|
||||
// last; Library is the library split plus the roster. Every figure is a
|
||||
// door into the list that counts it, except a zero.
|
||||
Hygiene []fig
|
||||
Library []fig
|
||||
// Sites is the per-Site library shape table, one row per Site with any
|
||||
// Series, in the store's Site order.
|
||||
Sites []siteRow
|
||||
}
|
||||
|
||||
// fig is one stats figure: its label, the list it counts, and the count
|
||||
// itself. Href empty means the count is zero: a measured zero is a real
|
||||
// figure that stays on the page, but it is not a door, because following it
|
||||
// lands on an empty list.
|
||||
type fig struct {
|
||||
Label string
|
||||
Href string
|
||||
Count int
|
||||
}
|
||||
|
||||
// siteRow is one Site's share of the library: the Series total and the three
|
||||
// hygiene counts the per-Site table carries, each a door to the list narrowed
|
||||
// to that Site, plus the Lane state phrase derived from its latest pass. The
|
||||
// table is library shape only — the Poll outcome sums live on the Lanes page.
|
||||
type siteRow struct {
|
||||
Site string
|
||||
SiteHref string
|
||||
Figs []fig
|
||||
// State is the Lane's own sentence; "" means the last pass read normally.
|
||||
// StateGood / StateBad pick the ok / bad second class.
|
||||
State string
|
||||
StateGood bool
|
||||
StateBad bool
|
||||
}
|
||||
|
||||
// overviewView assembles the landing page from the store's read model: one
|
||||
// SeriesShapes pass per filter summed in Go (the shipped surface offers ten
|
||||
// grouped passes, not a stats query — #140), the pass log's latest pass per
|
||||
// Site, and the roster. A failure in the SeriesShapes, pass or roster reads
|
||||
// is a 500 with a logged reason, never a page of silent zeroes. The three
|
||||
// fault-input reads (RefusingSince, SidecarOK, NoChapterShare) fail open:
|
||||
// a failing read logs and contributes no fault, so the landing page still
|
||||
// renders — the same fail-open the poller uses for owner notices.
|
||||
func (h *Handler) overviewView() (overviewView, error) {
|
||||
now := time.Now()
|
||||
cutoff := now.Add(-ownerWindow).UnixMilli()
|
||||
|
||||
shapes := make(map[string][]store.SiteSeriesShape, len(seriesFilterOrder))
|
||||
totals := make(map[string]int, len(seriesFilterOrder))
|
||||
for _, name := range seriesFilterOrder {
|
||||
rows, err := h.store.SeriesShapes(store.SeriesFilter{Name: name, Cutoff: cutoff})
|
||||
if err != nil {
|
||||
return overviewView{}, err
|
||||
}
|
||||
shapes[name] = rows
|
||||
for _, sh := range rows {
|
||||
totals[name] += sh.Total
|
||||
}
|
||||
}
|
||||
|
||||
passes, err := h.store.LatestLanePasses()
|
||||
if err != nil {
|
||||
return overviewView{}, err
|
||||
}
|
||||
readers, err := h.store.Readers()
|
||||
if err != nil {
|
||||
return overviewView{}, err
|
||||
}
|
||||
|
||||
view := overviewView{Waiting: waiting(passes)}
|
||||
view.Unchecked = totals[store.SeriesFilterStale] + totals[store.SeriesFilterNeverChecked]
|
||||
var refusingSince map[string]int64
|
||||
if m, err := h.store.RefusingSince(now.UnixMilli()); err != nil {
|
||||
log.Printf("admin overview: refusing since: %v", err)
|
||||
} else {
|
||||
refusingSince = m
|
||||
}
|
||||
var sidecarOK map[string]int64
|
||||
if m, err := h.store.SidecarOK(latest.BrowserBackedSites()); err != nil {
|
||||
log.Printf("admin overview: sidecar ok: %v", err)
|
||||
} else {
|
||||
sidecarOK = m
|
||||
}
|
||||
var noChapterShare map[string]float64
|
||||
if m, err := h.store.NoChapterShare(cutoff); err != nil {
|
||||
log.Printf("admin overview: no-chapter share: %v", err)
|
||||
} else {
|
||||
noChapterShare = m
|
||||
}
|
||||
faults := latest.FaultsFrom(latest.FaultInput{
|
||||
Passes: passes,
|
||||
RefusingSince: refusingSince,
|
||||
SidecarOK: sidecarOK,
|
||||
NoChapterShare: noChapterShare,
|
||||
}, now)
|
||||
view.Verdict, view.HasCounts = overviewVerdict(passes, faults)
|
||||
|
||||
// The hygiene figures, in seriesFilterOrder's tail: the problem filters
|
||||
// in permanent-then-fixable order, then the informational tail — finished
|
||||
// and site completed — riding last because seriesFilterOrder appends them
|
||||
// there. The All filter's count belongs to the Library block, not to a
|
||||
// "hygiene" figure.
|
||||
hygiene := make([]fig, 0, len(seriesFilterOrder)-1)
|
||||
for _, name := range seriesFilterOrder[1:] {
|
||||
hygiene = append(hygiene, door(seriesFilterLabels[name], totals[name], seriesListHref(name, "", "", 0)))
|
||||
}
|
||||
view.Hygiene = hygiene
|
||||
|
||||
var manga, novel int
|
||||
for _, sh := range shapes[store.SeriesFilterAll] {
|
||||
manga += sh.Manga
|
||||
novel += sh.Novel
|
||||
}
|
||||
view.Library = []fig{
|
||||
door("Series", totals[store.SeriesFilterAll], seriesListHref("", "", "", 0)),
|
||||
door("Manga", manga, seriesListHref("", "", store.KindManga, 0)),
|
||||
door("Novels", novel, seriesListHref("", "", store.KindNovel, 0)),
|
||||
door("Readers", len(readers), "/admin/readers"),
|
||||
}
|
||||
|
||||
// One row per Site with any Series, from the All shapes; the hygiene
|
||||
// counts come from the same per-Site projection so the table cannot
|
||||
// disagree with the library-wide figures above it.
|
||||
siteCounts := make(map[string]map[string]int, len(shapes))
|
||||
for name, rows := range shapes {
|
||||
m := make(map[string]int, len(rows))
|
||||
for _, sh := range rows {
|
||||
m[sh.Site] = sh.Total
|
||||
}
|
||||
siteCounts[name] = m
|
||||
}
|
||||
passBySite := make(map[string]store.LanePass, len(passes))
|
||||
for _, p := range passes {
|
||||
passBySite[p.Site] = p
|
||||
}
|
||||
view.Sites = make([]siteRow, 0, len(shapes[store.SeriesFilterAll]))
|
||||
for _, sh := range shapes[store.SeriesFilterAll] {
|
||||
row := siteRow{
|
||||
Site: sh.Site,
|
||||
SiteHref: seriesListHref("", sh.Site, "", 0),
|
||||
// The labels are the thead's words, carried per cell because the
|
||||
// phone layout drops the thead: four bare counts in a row are
|
||||
// unreadable without them (they render as the cell's prefix).
|
||||
Figs: []fig{
|
||||
door("series", sh.Total, seriesListHref("", sh.Site, "", 0)),
|
||||
door("no cover", siteCounts[store.SeriesFilterNoCover][sh.Site], seriesListHref(store.SeriesFilterNoCover, sh.Site, "", 0)),
|
||||
door("never chk", siteCounts[store.SeriesFilterNeverChecked][sh.Site], seriesListHref(store.SeriesFilterNeverChecked, sh.Site, "", 0)),
|
||||
door("stale", siteCounts[store.SeriesFilterStale][sh.Site], seriesListHref(store.SeriesFilterStale, sh.Site, "", 0)),
|
||||
},
|
||||
}
|
||||
if p, ok := passBySite[sh.Site]; ok {
|
||||
row.State, row.StateGood, row.StateBad = laneState(p, now)
|
||||
} else {
|
||||
row.State = "no pass yet"
|
||||
}
|
||||
view.Sites = append(view.Sites, row)
|
||||
}
|
||||
return view, nil
|
||||
}
|
||||
|
||||
// door is one figure with its door: the list that counts it. A measured zero
|
||||
// is still a real figure, but the door closes — following it would land on an
|
||||
// empty list. The count is written once so the figure and what it links to
|
||||
// cannot drift apart.
|
||||
func door(label string, count int, href string) fig {
|
||||
if count == 0 {
|
||||
href = ""
|
||||
}
|
||||
return fig{Label: label, Href: href, Count: count}
|
||||
}
|
||||
|
||||
// overviewVerdict decides the landing page's one line: no passes at all is
|
||||
// "no Lane has reported yet" — never confident zeroes; otherwise the count of
|
||||
// faults from the shared FaultsFrom judgement, so the page and the push
|
||||
// cannot disagree. Zero faults is "all lanes healthy". A sidecar-down fault
|
||||
// carries Site == "" and is still one fault. The Lanes page's per-row
|
||||
// laneState is a different question (is this Lane's last pass healthy) from
|
||||
// the notice class, and its known false positives live there deliberately, so
|
||||
// the two now differ.
|
||||
func overviewVerdict(passes []store.LanePass, faults []latest.Fault) (phrase string, counts bool) {
|
||||
if len(passes) == 0 {
|
||||
return "no Lane has reported yet", false
|
||||
}
|
||||
n := len(faults)
|
||||
if n == 0 {
|
||||
return "all lanes healthy", true
|
||||
}
|
||||
if n == 1 {
|
||||
return "1 lane needs a look", true
|
||||
}
|
||||
return fmt.Sprintf("%d lanes need a look", n), true
|
||||
}
|
||||
|
||||
// waiting sums Due over the latest pass per Site: how many Series the Lanes
|
||||
// found waiting, from the durable log rather than a running poller.
|
||||
func waiting(passes []store.LanePass) int {
|
||||
n := 0
|
||||
for _, p := range passes {
|
||||
n += p.Due
|
||||
}
|
||||
return n
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The three administrative tables are grids on a mouse and label-value pairs
|
||||
// on a phone, where the media query drops the .thead and prints each cell's
|
||||
// data-label as its prefix instead. Without the attribute the collapsed row
|
||||
// renders as bare figures — "1200.25 3d 4", "12 40 6h" — which no reader can
|
||||
// decode, and nothing in Go or in a desktop render says so. Every cell whose
|
||||
// only column heading was the .thead is asserted here.
|
||||
func TestAdminTablesLabelCollapsedCells(t *testing.T) {
|
||||
tmpl, err := template.ParseFS(templateFS, "templates/*.html")
|
||||
if err != nil {
|
||||
t.Fatalf("ParseFS: %v", err)
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
data any
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
"series-row",
|
||||
seriesRowView{Key: "asura:x", Title: "Chronicles", Site: "asura", Ch: "1200.25", Age: "3d", Readers: 4},
|
||||
[]string{`data-label="ch"`, `data-label="checked"`, `data-label="readers"`},
|
||||
},
|
||||
{
|
||||
"lanes",
|
||||
lanesView{Rows: []laneRow{{Site: "asura", Due: 12, Checked: 40, Gap: "6h", Ran: "4m ago"}}},
|
||||
[]string{`data-label="due"`, `data-label="checked"`, `data-label="gap"`},
|
||||
},
|
||||
{
|
||||
// The Site table's figures are a range over one slice, so their
|
||||
// labels are the ones overviewView puts on the figs.
|
||||
"overview",
|
||||
overviewView{Sites: []siteRow{{Site: "asura", Figs: []fig{
|
||||
{Label: "series", Href: "/admin/series", Count: 143},
|
||||
{Label: "stale", Count: 0},
|
||||
}}}},
|
||||
[]string{`data-label="series"`, `data-label="stale"`},
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var out strings.Builder
|
||||
if err := tmpl.ExecuteTemplate(&out, tc.name, tc.data); err != nil {
|
||||
t.Fatalf("ExecuteTemplate: %v", err)
|
||||
}
|
||||
for _, want := range tc.want {
|
||||
if !strings.Contains(out.String(), want) {
|
||||
t.Errorf("missing %s: the collapsed phone row renders this cell as a bare figure", want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,804 +0,0 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"math"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"bookmarkmanager/backend/internal/latest"
|
||||
"bookmarkmanager/backend/internal/store"
|
||||
)
|
||||
|
||||
// seriesPageSize matches the store's row-read page length: the pager's range
|
||||
// must agree with the LIMIT the store applies or the "of N" figure describes
|
||||
// the wrong page. The store does not export it (#140).
|
||||
const seriesPageSize = 50
|
||||
|
||||
// seriesFilterLabels names every Series filter for the list select, keyed by
|
||||
// the wire constant the URL carries. The render order is seriesFilterOrder;
|
||||
// the labels are read by later admin tickets too, so the map and the
|
||||
// constants cannot drift apart.
|
||||
var seriesFilterLabels = map[string]string{
|
||||
store.SeriesFilterAll: "All series",
|
||||
store.SeriesFilterNoURL: "No series URL",
|
||||
store.SeriesFilterNoChapter: "Never read a chapter",
|
||||
store.SeriesFilterNoReaders: "No Readers",
|
||||
store.SeriesFilterNeverChecked: "Never checked",
|
||||
store.SeriesFilterStale: "Not checked in 12h",
|
||||
store.SeriesFilterNoCover: "No cover",
|
||||
store.SeriesFilterReaderReport: "Latest from a Reader",
|
||||
store.SeriesFilterFailing: "Failing over 12h",
|
||||
store.SeriesFilterUnverified: "Unverified Reader number",
|
||||
store.SeriesFilterFinished: "Finished",
|
||||
store.SeriesFilterSiteCompleted: "Site says completed",
|
||||
}
|
||||
|
||||
// seriesFilterOrder is the select's render order: All first, then the
|
||||
// permanent repairs, then the fixable ones (issue #140). Finished and the
|
||||
// site-completed hint ride the tail — deliberate, not repairs — and the
|
||||
// Overview's stats block renders the same tail, which is what sits the
|
||||
// finished and site-completed figures last there.
|
||||
var seriesFilterOrder = []string{
|
||||
store.SeriesFilterAll,
|
||||
store.SeriesFilterNoURL,
|
||||
store.SeriesFilterNoChapter,
|
||||
store.SeriesFilterNoReaders,
|
||||
store.SeriesFilterNeverChecked,
|
||||
store.SeriesFilterStale,
|
||||
store.SeriesFilterNoCover,
|
||||
store.SeriesFilterReaderReport,
|
||||
store.SeriesFilterFailing,
|
||||
store.SeriesFilterUnverified,
|
||||
store.SeriesFilterFinished,
|
||||
store.SeriesFilterSiteCompleted,
|
||||
}
|
||||
|
||||
// seriesListView is the Series list page's data. The template renders strings
|
||||
type seriesListView struct {
|
||||
Filters []seriesFilterOption
|
||||
Sites []string
|
||||
Site string // "" = every Site
|
||||
Kind string // "" = both libraries
|
||||
FilterLabel string
|
||||
Rows []seriesRowView
|
||||
Total int
|
||||
// OOB marks the out-of-band copy of the heading the removal answer
|
||||
// carries; on the page itself it is false (issue #155).
|
||||
OOB bool
|
||||
// KindBoth / KindManga / KindNovel are the Library segment links, and
|
||||
// PrevHref / NextHref the pager's, all carrying the active filter, Site
|
||||
// and Kind so narrowing never drops state.
|
||||
KindBoth string
|
||||
KindManga string
|
||||
KindNovel string
|
||||
PrevHref string
|
||||
NextHref string
|
||||
Range string
|
||||
}
|
||||
|
||||
// seriesFilterOption is one entry of the Show select: its wire value, its
|
||||
// rendered label with the library-wide count, and whether it is the active
|
||||
// filter.
|
||||
type seriesFilterOption struct {
|
||||
Name string
|
||||
Label string
|
||||
Count int
|
||||
Selected bool
|
||||
}
|
||||
|
||||
// seriesRowView is one Series row formatted for the template. Band carries
|
||||
// the alternating row tint by class rather than nth-of-type, so the confirm
|
||||
// rows later tickets add are row siblings without breaking the alternation.
|
||||
// Attention tints the title patina: a row with any hygiene chip needs one.
|
||||
//
|
||||
// CanPoll is the Check now control's visibility: absent on a Series with no
|
||||
// page to fetch and on an orphan, so the owner is never offered a button that
|
||||
// can never do anything. Pending is derived — the request stamp is newer than
|
||||
// the check stamp — and Requested is its ageing label.
|
||||
type seriesRowView struct {
|
||||
Key string
|
||||
Title string
|
||||
Site string
|
||||
Ch string // chapter number; "—" until first captured
|
||||
Age string // checked age; "never" until first check
|
||||
Readers int
|
||||
Notes []string // chips, capped at two
|
||||
More int // chips past the cap, rendered as a +N tail
|
||||
Band bool
|
||||
Attention bool
|
||||
CanPoll bool
|
||||
Pending bool
|
||||
Requested string // "requested 3m ago", rendered only while pending
|
||||
// CanRemove is the Remove control's visibility: only a Series no Reader
|
||||
// holds can be removed, so the owner is never offered a button that the
|
||||
// database will always refuse (issue #155). RemovalRefused marks the one
|
||||
// raced answer: the row stays and says a fresh Bookmark caught the press.
|
||||
CanRemove bool
|
||||
RemovalRefused bool
|
||||
// Finished is the row's display of the owner's finish stamp: the list row
|
||||
// shows the state and never offers the control — that lives on the detail
|
||||
// page, where a press that retires a Series from the Lane is on purpose
|
||||
// and confirm-gated (issue #158).
|
||||
Finished bool
|
||||
// Failure names the standing failure and how long it has stood — "not
|
||||
// found · 3d ago", "" while no failure row stands. Its own field, never a
|
||||
// Notes chip: the chips cap at two plus a tail, so the one fact that
|
||||
// names the failure would be the most likely to be truncated away.
|
||||
Failure string
|
||||
}
|
||||
|
||||
// adminSeries renders the filterable, bookmarkable Series list: filter, Site,
|
||||
// Library and page all live in the query string, so the list's state is an
|
||||
// address rather than a click path.
|
||||
func (h *Handler) adminSeries(w http.ResponseWriter, r *http.Request) {
|
||||
view, err := h.seriesListView(r)
|
||||
if err != nil {
|
||||
log.Printf("admin series: %v", err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
h.renderAdmin(w, adminView{Page: "series", SeriesList: view})
|
||||
}
|
||||
|
||||
// adminSeriesPoll is the Check now action: it stamps the Series' force_poll_at
|
||||
// and answers with the freshly rendered row, so the figures describe the
|
||||
// state after the press. The control never commands the poller — the request
|
||||
// is a fact about the Series, and the Lane's next pass reads it through
|
||||
// DueForLatestCheck (ADR-0013). The owner gate is the route's, not this
|
||||
// handler's; the body is capped like the API path caps its bodies; the key is
|
||||
// validated here — a malformed key is a 400 and an unknown one a 404.
|
||||
func (h *Handler) adminSeriesPoll(w http.ResponseWriter, r *http.Request) {
|
||||
site, seriesID, ok := strings.Cut(r.PathValue("key"), ":")
|
||||
if !ok || site == "" || seriesID == "" {
|
||||
http.Error(w, "bad series key", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 1<<16)
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, "invalid form", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if _, found, err := h.adminSeriesByKey(site, seriesID); err != nil {
|
||||
log.Printf("series poll %s: %v", site+":"+seriesID, err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
} else if !found {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if err := h.store.ForceSeriesPoll(site, seriesID, time.Now().UnixMilli()); err != nil {
|
||||
log.Printf("series poll %s: %v", site+":"+seriesID, err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
// Re-read after the stamp: the answer must describe the state after the
|
||||
// press. The detail page's control swaps its meta in place and the list
|
||||
// row's swaps the row; htmx names an id target in HX-Target, so the
|
||||
// response matches the surface it came from. The row's band parity travels
|
||||
// with the press (hx-vals), so the swap keeps the zebra alternation.
|
||||
a, found, err := h.adminSeriesByKey(site, seriesID)
|
||||
if err != nil {
|
||||
log.Printf("series poll %s: %v", site+":"+seriesID, err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if !found {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if r.Header.Get("HX-Target") == "detail-meta" {
|
||||
h.render(w, http.StatusOK, "series-detail-meta", h.seriesDetailView(a))
|
||||
return
|
||||
}
|
||||
band := 0
|
||||
if r.PostFormValue("band") == "1" {
|
||||
band = 1
|
||||
}
|
||||
h.render(w, http.StatusOK, "series-row", seriesRow(a, band, time.Now()))
|
||||
}
|
||||
|
||||
// adminSeriesFinish is the owner's Finish control: it stamps the Series'
|
||||
// finished_at and answers with the freshly rendered meta fragment, so the
|
||||
// "finished <age> ago" line describes the state after the press. The Lane's
|
||||
// next pass reads the stamp and stops polling the Series (issue #157). The
|
||||
// owner gate is the route's, not this handler's; the body is capped like the
|
||||
// API path caps its bodies; the key is validated here — a malformed key is a
|
||||
// 400 and an unknown one a 404.
|
||||
func (h *Handler) adminSeriesFinish(w http.ResponseWriter, r *http.Request) {
|
||||
site, seriesID, ok := strings.Cut(r.PathValue("key"), ":")
|
||||
if !ok || site == "" || seriesID == "" {
|
||||
http.Error(w, "bad series key", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 1<<16)
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, "invalid form", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if _, found, err := h.adminSeriesByKey(site, seriesID); err != nil {
|
||||
log.Printf("series finish %s: %v", site+":"+seriesID, err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
} else if !found {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if err := h.store.SetSeriesFinished(site, seriesID, time.Now().UnixMilli()); err != nil {
|
||||
log.Printf("series finish %s: %v", site+":"+seriesID, err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
// Re-read after the stamp: the answer must describe the state after the
|
||||
// press, so the line reads "finished just now". The control's one caller
|
||||
// is the detail page, which swaps the meta fragment in place.
|
||||
a, found, err := h.adminSeriesByKey(site, seriesID)
|
||||
if err != nil {
|
||||
log.Printf("series finish %s: %v", site+":"+seriesID, err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if !found {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
h.render(w, http.StatusOK, "series-detail-meta", h.seriesDetailView(a))
|
||||
}
|
||||
|
||||
// adminSeriesUnfinish is the reversal of the Finish control: it clears the
|
||||
// stamp (writes zero) and answers with the freshly rendered meta fragment, so
|
||||
// the Series is back in the Lane's queue from its next pass. Reversal, so it
|
||||
// fires instantly with no confirm row (issue #158).
|
||||
func (h *Handler) adminSeriesUnfinish(w http.ResponseWriter, r *http.Request) {
|
||||
site, seriesID, ok := strings.Cut(r.PathValue("key"), ":")
|
||||
if !ok || site == "" || seriesID == "" {
|
||||
http.Error(w, "bad series key", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 1<<16)
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, "invalid form", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if _, found, err := h.adminSeriesByKey(site, seriesID); err != nil {
|
||||
log.Printf("series unfinish %s: %v", site+":"+seriesID, err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
} else if !found {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if err := h.store.SetSeriesFinished(site, seriesID, 0); err != nil {
|
||||
log.Printf("series unfinish %s: %v", site+":"+seriesID, err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
// Re-read after the write: the answer must describe the state after the
|
||||
// press, so the fragment no longer carries the finished line.
|
||||
a, found, err := h.adminSeriesByKey(site, seriesID)
|
||||
if err != nil {
|
||||
log.Printf("series unfinish %s: %v", site+":"+seriesID, err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if !found {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
h.render(w, http.StatusOK, "series-detail-meta", h.seriesDetailView(a))
|
||||
}
|
||||
|
||||
// adminSeriesCorrectLatest is the Latest Chapter correction: the owner types
|
||||
// one number and the Series' Latest Chapter becomes it, stamped as a
|
||||
// Correction. The number must be a finite float greater than zero — a
|
||||
// non-numeric, zero or negative value answers 400 and never reaches the
|
||||
// store, because a bad value would become every Reader's problem. The press
|
||||
// answers with the freshly rendered meta fragment, so the figures describe
|
||||
// the state after the press. The owner gate is the route's, not this
|
||||
// handler's; the body is capped like the API path caps its bodies.
|
||||
func (h *Handler) adminSeriesCorrectLatest(w http.ResponseWriter, r *http.Request) {
|
||||
site, seriesID, ok := strings.Cut(r.PathValue("key"), ":")
|
||||
if !ok || site == "" || seriesID == "" {
|
||||
http.Error(w, "bad series key", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 1<<16)
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, "invalid form", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
num, err := strconv.ParseFloat(r.PostFormValue("chapter"), 64)
|
||||
if err != nil || math.IsNaN(num) || math.IsInf(num, 0) || num <= 0 || num > maxChapterNum {
|
||||
http.Error(w, "chapter must be a finite number between 0 and 10000", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if _, found, err := h.adminSeriesByKey(site, seriesID); err != nil {
|
||||
log.Printf("series correction %s: %v", site+":"+seriesID, err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
} else if !found {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if err := h.store.CorrectLatestChapter(site, seriesID, num, time.Now().UnixMilli()); err != nil {
|
||||
log.Printf("series correction %s: %v", site+":"+seriesID, err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
// Re-read after the write: the answer must describe the state after the
|
||||
// press, so the marker reads "corrected just now".
|
||||
a, found, err := h.adminSeriesByKey(site, seriesID)
|
||||
if err != nil {
|
||||
log.Printf("series correction %s: %v", site+":"+seriesID, err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if !found {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
h.render(w, http.StatusOK, "series-detail-meta", h.seriesDetailView(a))
|
||||
}
|
||||
|
||||
// adminSeriesSetURL is the series URL repair: the owner types one address
|
||||
// and the Series' Poll fetches it from then on, verified by the same gate
|
||||
// the poller uses before it fetches anything — a URL failing
|
||||
// latest.FetchableSeriesURL answers 400 and never reaches the store. The
|
||||
// repair is a store, not a verification: it performs no outbound fetch, and
|
||||
// the owner presses Check now afterwards. This lifts the write-once rule of
|
||||
// Series.SeriesURL for the owner only — a Reader's PUT is still ignored. The
|
||||
// owner gate is the route's, not this handler's; the body is capped like the
|
||||
// API path caps its bodies; the key is validated here — a malformed key is a
|
||||
// 400 and an unknown one a 404.
|
||||
func (h *Handler) adminSeriesSetURL(w http.ResponseWriter, r *http.Request) {
|
||||
site, seriesID, ok := strings.Cut(r.PathValue("key"), ":")
|
||||
if !ok || site == "" || seriesID == "" {
|
||||
http.Error(w, "bad series key", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 1<<16)
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, "invalid form", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
seriesURL := r.PostFormValue("series_url")
|
||||
if !latest.FetchableSeriesURL(site, seriesURL) {
|
||||
http.Error(w, "series URL must be an https address on this site's host", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if _, found, err := h.adminSeriesByKey(site, seriesID); err != nil {
|
||||
log.Printf("series url %s: %v", site+":"+seriesID, err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
} else if !found {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if err := h.store.SetSeriesURL(site, seriesID, seriesURL); err != nil {
|
||||
log.Printf("series url %s: %v", site+":"+seriesID, err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
// Re-read after the write: the answer must describe the state after the
|
||||
// press, like the correction's answer does.
|
||||
a, found, err := h.adminSeriesByKey(site, seriesID)
|
||||
if err != nil {
|
||||
log.Printf("series url %s: %v", site+":"+seriesID, err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if !found {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
h.render(w, http.StatusOK, "series-detail-meta", h.seriesDetailView(a))
|
||||
}
|
||||
|
||||
// seriesListHeadView is the list heading's data. The template renders it
|
||||
// inline at the top of the Series list and out of band in the removal answer
|
||||
// (OOB true, like the chrome partials' OOB flag): the count and the filter
|
||||
// label are one fact (issue #155).
|
||||
type seriesListHeadView struct {
|
||||
Total int
|
||||
FilterLabel string
|
||||
OOB bool
|
||||
}
|
||||
|
||||
// adminSeriesRemove is the orphan removal: one Series, one delete, refused by
|
||||
// the database while any Bookmark exists (translated by the store, never a
|
||||
// driver error on the page). The owner gate is the route's, not this
|
||||
// handler's; the body is capped like the API path caps its bodies; the key is
|
||||
// validated here — a malformed key is a 400 and an unknown one a 404.
|
||||
//
|
||||
// The Cover is read from the row before the delete and reclaimed after it:
|
||||
// ReclaimCover's guard cannot pass while a series row still points at the
|
||||
// address, so the order is the sequence, not a preference. A reclamation
|
||||
// failure is not a removal failure — the row is gone and the covers row
|
||||
// survives for a retry; the handler logs and answers success, because the
|
||||
// failure has no user-facing surface.
|
||||
//
|
||||
// Two callers, one handler, branched on HX-Target like adminSeriesPoll. The
|
||||
// detail page's remove answers with a navigation — to the No-Readers list on
|
||||
// success, back to the detail page when a fresh Bookmark raced the press,
|
||||
// where the new count is visible. The list row's answers with the removed
|
||||
// row's fragment and the heading re-rendered with the fresh count out of
|
||||
// band; HX-Reswap deletes the row through the same button that swaps the
|
||||
// refusal back in, and the count query runs over the press's own filter
|
||||
// state, so the heading describes the list the owner is looking at.
|
||||
func (h *Handler) adminSeriesRemove(w http.ResponseWriter, r *http.Request) {
|
||||
site, seriesID, ok := strings.Cut(r.PathValue("key"), ":")
|
||||
if !ok || site == "" || seriesID == "" {
|
||||
http.Error(w, "bad series key", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 1<<16)
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, "invalid form", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
// The row's Cover address is read before the delete because the delete is
|
||||
// what makes it reclaimable.
|
||||
a, found, err := h.adminSeriesByKey(site, seriesID)
|
||||
if err != nil {
|
||||
log.Printf("series remove %s: %v", site+":"+seriesID, err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if !found {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
cover := a.CoverAddress
|
||||
if err := h.store.RemoveSeries(site, seriesID); err != nil {
|
||||
if errors.Is(err, store.ErrSeriesHasBookmarks) {
|
||||
// A Bookmark landed between the owner's read and the press: the
|
||||
// row stays, answered at its new count with the fact spelled
|
||||
// out — never a 500, and never a deleted row.
|
||||
if r.Header.Get("HX-Target") == "detail-meta" {
|
||||
seriesRemoveNavigation(w, r, "/admin/series/"+site+":"+seriesID)
|
||||
return
|
||||
}
|
||||
fresh, found, err := h.adminSeriesByKey(site, seriesID)
|
||||
if err != nil {
|
||||
log.Printf("series remove %s: %v", site+":"+seriesID, err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if !found {
|
||||
// A second press removed it while this one was refused; the
|
||||
// row has nothing left to say.
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
band := 0
|
||||
if r.PostFormValue("band") == "1" {
|
||||
band = 1
|
||||
}
|
||||
row := seriesRow(fresh, band, time.Now())
|
||||
row.RemovalRefused = true
|
||||
h.render(w, http.StatusOK, "series-row", row)
|
||||
return
|
||||
}
|
||||
log.Printf("series remove %s: %v", site+":"+seriesID, err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if err := h.store.ReclaimCover(cover); err != nil {
|
||||
log.Printf("series remove %s: reclaim cover: %v", site+":"+seriesID, err)
|
||||
}
|
||||
if r.Header.Get("HX-Target") == "detail-meta" {
|
||||
seriesRemoveNavigation(w, r, "/admin/series?filter="+store.SeriesFilterNoReaders)
|
||||
return
|
||||
}
|
||||
// The list answer: the removed row's fragment, plus the heading
|
||||
// re-rendered with the fresh count. HX-Reswap deletes the row through the
|
||||
// same button that swaps the refusal back in. The count query failing
|
||||
// does not undo the removal — log it and answer the row alone.
|
||||
w.Header().Set("HX-Reswap", "delete")
|
||||
band := 0
|
||||
if r.PostFormValue("band") == "1" {
|
||||
band = 1
|
||||
}
|
||||
h.render(w, http.StatusOK, "series-row", seriesRow(a, band, time.Now()))
|
||||
// The heading is an out-of-band append to a response whose status line has
|
||||
// already gone out with the row, so it is executed straight onto w —
|
||||
// h.render would send a second WriteHeader.
|
||||
if head, err := h.seriesListHeadView(r); err != nil {
|
||||
log.Printf("series remove %s: %v", site+":"+seriesID, err)
|
||||
} else if err := h.tmpl.ExecuteTemplate(w, "series-list-head", head); err != nil {
|
||||
log.Printf("series remove %s: render series-list-head oob: %v", site+":"+seriesID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// seriesListHeadView is the list heading with the count as it stands after a
|
||||
// removal: the same filter, Site and Kind the press's row carried (the list
|
||||
// row's button hx-includes the filterbar), so the figure describes the list
|
||||
// the owner is looking at — the All filter and an unknown one stay the
|
||||
// absent case. The count is the store's window total, one query.
|
||||
func (h *Handler) seriesListHeadView(r *http.Request) (seriesListHeadView, error) {
|
||||
filter := r.PostFormValue("filter")
|
||||
if _, ok := seriesFilterLabels[filter]; !ok {
|
||||
filter = store.SeriesFilterAll
|
||||
}
|
||||
site := r.PostFormValue("site")
|
||||
kind := r.PostFormValue("kind")
|
||||
if kind != store.KindManga && kind != store.KindNovel {
|
||||
kind = ""
|
||||
}
|
||||
data, err := h.store.SeriesPage(store.SeriesFilter{
|
||||
Site: site,
|
||||
Kind: kind,
|
||||
Name: filter,
|
||||
Cutoff: time.Now().Add(-ownerWindow).UnixMilli(),
|
||||
Page: 1,
|
||||
})
|
||||
if err != nil {
|
||||
return seriesListHeadView{}, err
|
||||
}
|
||||
return seriesListHeadView{
|
||||
Total: data.Total,
|
||||
FilterLabel: seriesFilterLabels[filter],
|
||||
OOB: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// seriesRemoveNavigation answers a removal from the detail page. htmx gets a
|
||||
// full navigation (HX-Redirect): a bare 303 would be followed by the request
|
||||
// and the landing page swapped into the press's target, so the header is the
|
||||
// redirect htmx can see; plain clients get the 303 the ticket names.
|
||||
func seriesRemoveNavigation(w http.ResponseWriter, r *http.Request, to string) {
|
||||
if r.Header.Get("HX-Request") != "" {
|
||||
w.Header().Set("HX-Redirect", to)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, to, http.StatusSeeOther)
|
||||
}
|
||||
|
||||
// seriesListView assembles one Series list view from the request's query
|
||||
// string. An unknown filter value is the absent All case, never an error: the
|
||||
// select's options are not the only way this URL can be reached.
|
||||
func (h *Handler) seriesListView(r *http.Request) (seriesListView, error) {
|
||||
q := r.URL.Query()
|
||||
filter := q.Get("filter")
|
||||
if _, ok := seriesFilterLabels[filter]; !ok {
|
||||
filter = store.SeriesFilterAll
|
||||
}
|
||||
site := q.Get("site")
|
||||
kind := q.Get("kind")
|
||||
if kind != store.KindManga && kind != store.KindNovel {
|
||||
kind = ""
|
||||
}
|
||||
page := 1
|
||||
if p, err := strconv.Atoi(q.Get("page")); err == nil && p > 1 {
|
||||
page = p
|
||||
}
|
||||
|
||||
sf := store.SeriesFilter{
|
||||
Site: site,
|
||||
Kind: kind,
|
||||
Name: filter,
|
||||
Cutoff: time.Now().Add(-ownerWindow).UnixMilli(),
|
||||
Page: page,
|
||||
}
|
||||
data, err := h.store.SeriesPage(sf)
|
||||
if err != nil {
|
||||
return seriesListView{}, err
|
||||
}
|
||||
// A page past the end is not an empty list: the store's window count runs
|
||||
// over the rows the result set carries, so an overflow page reports zero
|
||||
// rows and zero total, and the list re-reads at page 1 to know the truth.
|
||||
if len(data.Rows) == 0 && page > 1 {
|
||||
page = 1
|
||||
sf.Page = 1
|
||||
data, err = h.store.SeriesPage(sf)
|
||||
if err != nil {
|
||||
return seriesListView{}, err
|
||||
}
|
||||
}
|
||||
|
||||
view := seriesListView{
|
||||
Site: site,
|
||||
Kind: kind,
|
||||
FilterLabel: seriesFilterLabels[filter],
|
||||
Rows: make([]seriesRowView, 0, len(data.Rows)),
|
||||
Total: data.Total,
|
||||
Sites: latest.SiteNames(),
|
||||
}
|
||||
now := time.Now()
|
||||
for i, a := range data.Rows {
|
||||
view.Rows = append(view.Rows, seriesRow(a, i, now))
|
||||
}
|
||||
view.Filters, err = h.seriesFilterOptions(filter, sf.Cutoff)
|
||||
if err != nil {
|
||||
return seriesListView{}, err
|
||||
}
|
||||
view.KindBoth = seriesListHref(filter, site, "", 0)
|
||||
view.KindManga = seriesListHref(filter, site, store.KindManga, 0)
|
||||
view.KindNovel = seriesListHref(filter, site, store.KindNovel, 0)
|
||||
if page > 1 {
|
||||
view.PrevHref = seriesListHref(filter, site, kind, page-1)
|
||||
}
|
||||
if last := (data.Total + seriesPageSize - 1) / seriesPageSize; page < last {
|
||||
view.NextHref = seriesListHref(filter, site, kind, page+1)
|
||||
}
|
||||
view.Range = pagerRange(data.Total, len(data.Rows), page)
|
||||
return view, nil
|
||||
}
|
||||
|
||||
// seriesFilterOptions renders every filter with its library-wide count, one
|
||||
// SeriesShapes pass per filter summed in Go — the shipped surface offers nine
|
||||
// grouped passes, not a single stats query (#140). The counts
|
||||
// are library-wide because the select sits next to the Site narrowing and
|
||||
// must not shift as the owner narrows the list itself. Cutoff travels with
|
||||
// the stale filter, or its count would always be zero.
|
||||
func (h *Handler) seriesFilterOptions(selected string, cutoff int64) ([]seriesFilterOption, error) {
|
||||
out := make([]seriesFilterOption, 0, len(seriesFilterOrder))
|
||||
for _, name := range seriesFilterOrder {
|
||||
shapes, err := h.store.SeriesShapes(store.SeriesFilter{Name: name, Cutoff: cutoff})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
count := 0
|
||||
for _, sh := range shapes {
|
||||
count += sh.Total
|
||||
}
|
||||
out = append(out, seriesFilterOption{
|
||||
Name: name,
|
||||
Label: seriesFilterLabels[name],
|
||||
Count: count,
|
||||
Selected: name == selected,
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// seriesRow shapes one store row for the template, capping its chips at two
|
||||
// plus a +N tail; attention marks a row that carries any.
|
||||
// pollState derives the Check now control and the pending marker (issue
|
||||
// #146), shared by the list row and the detail page: CanPoll is false on a
|
||||
// Series with no page to fetch and on an orphan, so the owner is never
|
||||
// offered a button that can never do anything. Pending is derived — the
|
||||
// request stamp is newer than the check stamp — and requested is its ageing
|
||||
// label, which never expires.
|
||||
func pollState(a store.AdminSeries, now time.Time) (canPoll, pending bool, requested string) {
|
||||
canPoll = a.SeriesURL != "" && a.ReaderCount > 0
|
||||
if a.ForcePollAt > a.LatestCheckedAt {
|
||||
pending = true
|
||||
requested = requestedAge(now, a.ForcePollAt)
|
||||
}
|
||||
return canPoll, pending, requested
|
||||
}
|
||||
|
||||
func seriesRow(a store.AdminSeries, i int, now time.Time) seriesRowView {
|
||||
canPoll, pending, requested := pollState(a, now)
|
||||
row := seriesRowView{
|
||||
Key: a.Key(),
|
||||
Site: a.Site,
|
||||
Title: a.Title,
|
||||
Readers: a.ReaderCount,
|
||||
Band: i%2 == 1,
|
||||
CanPoll: canPoll,
|
||||
CanRemove: a.ReaderCount == 0,
|
||||
Pending: pending,
|
||||
Requested: requested,
|
||||
Finished: a.FinishedAt > 0,
|
||||
}
|
||||
if a.LatestChapterNum != nil {
|
||||
row.Ch = strconv.FormatFloat(*a.LatestChapterNum, 'f', -1, 64)
|
||||
} else {
|
||||
row.Ch = "—"
|
||||
}
|
||||
row.Age = checkedAge(now, a.LatestCheckedAt)
|
||||
if a.FailureOutcome != "" {
|
||||
row.Failure = outcomeWord(a.FailureOutcome) + " · " + checkedAge(now, a.FailingSince)
|
||||
}
|
||||
notes := seriesNotes(a, now)
|
||||
if n := len(notes); n > 2 {
|
||||
row.Notes, row.More = notes[:2], n-2
|
||||
} else {
|
||||
row.Notes = notes
|
||||
}
|
||||
row.Attention = len(notes) > 0
|
||||
return row
|
||||
}
|
||||
|
||||
// outcomeWord spells the wire failure word as the Lanes chips spell it — a
|
||||
// space, not the underscore: not_found reads "not found", no_chapter "no
|
||||
// chapter". The remaining words are their own spelling, so an unknown word
|
||||
// degrades to itself rather than vanishing from the page.
|
||||
func outcomeWord(wire string) string {
|
||||
switch wire {
|
||||
case "not_found":
|
||||
return "not found"
|
||||
case "no_chapter":
|
||||
return "no chapter"
|
||||
}
|
||||
return wire
|
||||
}
|
||||
|
||||
// seriesNotes are a row's hygiene chips in the design's order: no URL, no
|
||||
// cover, orphan, stale, reader sighting.
|
||||
func seriesNotes(a store.AdminSeries, now time.Time) []string {
|
||||
notes := []string{}
|
||||
if a.SeriesURL == "" {
|
||||
notes = append(notes, "no URL")
|
||||
}
|
||||
if a.CoverAddress == "" {
|
||||
notes = append(notes, "no cover")
|
||||
}
|
||||
if a.ReaderCount == 0 {
|
||||
notes = append(notes, "orphan")
|
||||
}
|
||||
if a.LatestCheckedAt > 0 && a.LatestCheckedAt < now.Add(-ownerWindow).UnixMilli() {
|
||||
notes = append(notes, "stale")
|
||||
}
|
||||
if a.RaisedByReader {
|
||||
notes = append(notes, "reader sighting")
|
||||
}
|
||||
return notes
|
||||
}
|
||||
|
||||
// checkedAge formats how long ago a Series was last checked, at the
|
||||
// granularity the list reads at — minutes, hours, days. Zero means never.
|
||||
func checkedAge(now time.Time, ts int64) string {
|
||||
if ts == 0 {
|
||||
return "never"
|
||||
}
|
||||
d := now.Sub(time.UnixMilli(ts))
|
||||
switch {
|
||||
case d < time.Hour:
|
||||
m := int(d / time.Minute)
|
||||
if m < 1 {
|
||||
m = 1
|
||||
}
|
||||
return fmt.Sprintf("%dm ago", m)
|
||||
case d < 24*time.Hour:
|
||||
return fmt.Sprintf("%dh ago", int(d/time.Hour))
|
||||
default:
|
||||
return fmt.Sprintf("%dd ago", int(d/(24*time.Hour)))
|
||||
}
|
||||
}
|
||||
|
||||
// requestedAge is the pending marker's text: how long ago the owner asked,
|
||||
// and nothing about when the request will run — the page does not know when a
|
||||
// sleeping browser will wake (issue #146). An unanswered request ages forever;
|
||||
// there is no expiry.
|
||||
func requestedAge(now time.Time, ts int64) string {
|
||||
return "requested " + checkedAge(now, ts)
|
||||
}
|
||||
|
||||
// pagerRange is the pager's "1–50 of 120" line. The template renders the
|
||||
// pager only over rows (the empty state replaces it), so it is never asked
|
||||
// to describe an empty list.
|
||||
func pagerRange(total, rows, page int) string {
|
||||
from := (page-1)*seriesPageSize + 1
|
||||
return fmt.Sprintf("%d–%d of %d", from, from+rows-1, total)
|
||||
}
|
||||
|
||||
// seriesListHref is one Series list address carrying the filter, Site, Kind
|
||||
// and page. The All filter and page 1 are the absent cases and stay out of
|
||||
// the URL, so the default address is the shortest one.
|
||||
func seriesListHref(filter, site, kind string, page int) string {
|
||||
q := url.Values{}
|
||||
if filter != "" && filter != store.SeriesFilterAll {
|
||||
q.Set("filter", filter)
|
||||
}
|
||||
if site != "" {
|
||||
q.Set("site", site)
|
||||
}
|
||||
if kind != "" {
|
||||
q.Set("kind", kind)
|
||||
}
|
||||
if page > 1 {
|
||||
q.Set("page", strconv.Itoa(page))
|
||||
}
|
||||
if len(q) == 0 {
|
||||
return "/admin/series"
|
||||
}
|
||||
return "/admin/series?" + q.Encode()
|
||||
}
|
||||
@@ -1,213 +0,0 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"bookmarkmanager/backend/internal/store"
|
||||
)
|
||||
|
||||
// seriesDetailView is one Series' page as the owner sees it: strings and
|
||||
// flags, every judgement made here, the template left to print. ReaderCount
|
||||
// is the only figure that crosses the privacy boundary — the owner learns how
|
||||
// many Readers hold the Series, never which Reader reads what.
|
||||
type seriesDetailView struct {
|
||||
Key string // "<site>:<series_id>", the page's address and the Series' identity
|
||||
Site string
|
||||
Kind string
|
||||
// Title, Cover and Chapter come from the shared Series row; the Cover is
|
||||
// the wire URL of the stored bytes, "" before any exist.
|
||||
Title string
|
||||
Cover string
|
||||
Chapter string // Latest Chapter number, or "—" before the first capture
|
||||
Checked string // how long ago the poller last checked, or "never"
|
||||
// URL is the stored source address, prefilled into the repair input —
|
||||
// the one stored string this page renders back into a form (issue #151).
|
||||
URL string
|
||||
Readers int
|
||||
// Corrected is the correction marker's text, "" while no Correction
|
||||
// stands: "corrected <age> ago" — the copy that says the value is the
|
||||
// owner's, and it dies with the stamp (a machine write of the number).
|
||||
Corrected string
|
||||
|
||||
// Provenance is the actor class behind the current Chapter: "correction",
|
||||
// "sighting" or "machine read"; "" while the Series was never read, when
|
||||
// the line is not rendered. Derived from the same anonymous stamps the
|
||||
// marks above read — no Reader identity crosses here.
|
||||
Provenance string
|
||||
|
||||
// Marks, one per hygiene fact, rendered only while it holds.
|
||||
Unpollable bool // no SeriesURL to fetch
|
||||
NoCover bool
|
||||
Orphan bool // no Reader holds the Series
|
||||
SightingRaised bool // a Reader's Sighting set the Latest Chapter
|
||||
// Poll is the Check now control and the pending marker (issue #146): the
|
||||
// same derivation and visibility as the list row. CanPoll is false on a
|
||||
// Series with no page to fetch and on an orphan; Pending is derived —
|
||||
// the request stamp is newer than the check stamp — and Requested is its
|
||||
// ageing label.
|
||||
CanPoll bool
|
||||
Pending bool
|
||||
Requested string
|
||||
// CanRemove is the Remove control's visibility (issue #155): only a
|
||||
// Series no Reader holds can be removed, so the owner is never offered a
|
||||
// button the database will always refuse.
|
||||
CanRemove bool
|
||||
// Finished is the owner's finish stamp rendered for the control: while it
|
||||
// stands, the page offers the instant Un-finish, not the confirm-gated
|
||||
// Finish (issue #158).
|
||||
Finished bool
|
||||
// FinishedSince is the "finished <age> ago" line, "" while no finish
|
||||
// stands. It rides the meta fragment both presses swap, so the answer
|
||||
// itself shows how long the Series has been finished.
|
||||
FinishedSince string
|
||||
// Unverified is the sentence beside the Latest Chapter correction
|
||||
// control while a Reader's number stands behind a failure past the
|
||||
// owner window: the value is unconfirmed and the owner should not trust
|
||||
// it. It never names the Reader. "" otherwise.
|
||||
Unverified string
|
||||
// SiteCompleted is the hint's line, "" while the Site has said nothing or
|
||||
// the owner has finished the Series: "the site says this work is
|
||||
// completed (since 3d ago)". A hint, never a control (issue #170).
|
||||
SiteCompleted string
|
||||
}
|
||||
|
||||
// adminSeriesDetail renders one Series' page, keyed by the composite
|
||||
// "<site>:<series_id>" the list row already shows. The row is read through
|
||||
// the list's own SeriesPage read narrowed to the key's Site: the admin
|
||||
// projection is the privacy boundary, and a dedicated single-row read would
|
||||
// be a second definition of it.
|
||||
func (h *Handler) adminSeriesDetail(w http.ResponseWriter, r *http.Request) {
|
||||
site, seriesID, ok := strings.Cut(r.PathValue("key"), ":")
|
||||
if !ok || site == "" || seriesID == "" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
a, found, err := h.adminSeriesByKey(site, seriesID)
|
||||
if err != nil {
|
||||
log.Printf("series detail %s: %v", site+":"+seriesID, err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if !found {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
h.renderAdmin(w, adminView{Page: "series-detail", Detail: h.seriesDetailView(a)})
|
||||
}
|
||||
|
||||
// adminSeriesByKey reads one Series through the list's own SeriesPage read
|
||||
// narrowed to the key's Site: the admin projection is the privacy boundary,
|
||||
// and a dedicated single-row read would be a second definition of it. Absence
|
||||
// is reported with found=false, never an error.
|
||||
// ponytail: a page scan per keyed read, one query per page of the Site's rows
|
||||
// up to the window total; a keyed read alongside SeriesPage when the library
|
||||
// outgrows the page size.
|
||||
func (h *Handler) adminSeriesByKey(site, seriesID string) (store.AdminSeries, bool, error) {
|
||||
seen := 0
|
||||
for page := 1; ; page++ {
|
||||
p, err := h.store.SeriesPage(store.SeriesFilter{Site: site, Page: page})
|
||||
if err != nil {
|
||||
return store.AdminSeries{}, false, err
|
||||
}
|
||||
seen += len(p.Rows)
|
||||
for i := range p.Rows {
|
||||
if p.Rows[i].SeriesID == seriesID {
|
||||
return p.Rows[i], true, nil
|
||||
}
|
||||
}
|
||||
if seen >= p.Total {
|
||||
break
|
||||
}
|
||||
}
|
||||
return store.AdminSeries{}, false, nil
|
||||
}
|
||||
|
||||
// seriesDetailView shapes one AdminSeries row for display: every judgement in
|
||||
// Go, the template left to print strings and flags.
|
||||
func (h *Handler) seriesDetailView(a store.AdminSeries) seriesDetailView {
|
||||
canPoll, pending, requested := pollState(a, time.Now())
|
||||
v := seriesDetailView{
|
||||
Key: a.Key(),
|
||||
Site: a.Site,
|
||||
Kind: a.Kind,
|
||||
Title: a.Title,
|
||||
Cover: h.store.CoverWireURL(a.CoverAddress),
|
||||
URL: a.SeriesURL,
|
||||
Readers: a.ReaderCount,
|
||||
Unpollable: a.SeriesURL == "",
|
||||
NoCover: a.CoverAddress == "",
|
||||
Orphan: a.ReaderCount == 0,
|
||||
SightingRaised: a.RaisedByReader,
|
||||
CanPoll: canPoll,
|
||||
CanRemove: a.ReaderCount == 0,
|
||||
Pending: pending,
|
||||
Requested: requested,
|
||||
}
|
||||
if a.LatestChapterNum == nil {
|
||||
v.Chapter = "—"
|
||||
} else {
|
||||
v.Chapter = strconv.FormatFloat(*a.LatestChapterNum, 'f', -1, 64)
|
||||
}
|
||||
if a.LatestCheckedAt == 0 {
|
||||
v.Checked = "never"
|
||||
} else {
|
||||
v.Checked = since(time.Now(), time.UnixMilli(a.LatestCheckedAt))
|
||||
}
|
||||
v.Corrected = correctedAge(time.Now(), a.LatestCorrectedAt)
|
||||
v.Finished = a.FinishedAt != 0
|
||||
v.FinishedSince = finishedAge(time.Now(), a.FinishedAt)
|
||||
// Unverified: a Reader's number standing behind a failure that has outlived
|
||||
// the owner window is a number nobody has re-checked since — say so next to
|
||||
// the correction control, without naming the Reader. A machine read or a
|
||||
// failure still inside the window carries no sentence; the failure itself
|
||||
// has not yet outlived the twelve hours' worth of trust.
|
||||
if a.RaisedByReader && a.FailureOutcome != "" && a.FailingSince < time.Now().Add(-ownerWindow).UnixMilli() {
|
||||
v.Unverified = "Unverified Reader number: the page has been failing for over 12h, so this Reader-reported chapter is unconfirmed."
|
||||
}
|
||||
if a.SiteCompletedAt != 0 && a.FinishedAt == 0 {
|
||||
v.SiteCompleted = "the site says this work is completed (since " + checkedAge(time.Now(), a.SiteCompletedAt) + ")"
|
||||
}
|
||||
|
||||
// Provenance: the actor class behind the current number, evaluated in the
|
||||
// order the classes outrank one another — the owner's stamp, which a
|
||||
// Correction leaves standing and a machine write clears (issue #149); a
|
||||
// raising Reader, which a Correction drops; then any check stamp at all.
|
||||
// An Acquisition reads as a machine read because it stamps
|
||||
// latest_checked_at exactly as a Poll does, so the two are
|
||||
// indistinguishable the moment it finishes; telling them apart would need
|
||||
// the column this project declines to add (spec #135), and the one
|
||||
// actionable case — acquired once, never read again — is already the
|
||||
// unchecked filter.
|
||||
if a.LatestCorrectedAt != 0 {
|
||||
v.Provenance = "correction"
|
||||
} else if a.RaisedByReader {
|
||||
v.Provenance = "sighting"
|
||||
} else if a.LatestCheckedAt != 0 {
|
||||
v.Provenance = "machine read"
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// correctedAge is the correction marker's text: "corrected <age> ago" while
|
||||
// the stamp is set, "" when zero — zero means never corrected, and the marker
|
||||
// must not read as history once a machine wrote the number.
|
||||
func correctedAge(now time.Time, at int64) string {
|
||||
if at == 0 {
|
||||
return ""
|
||||
}
|
||||
return "corrected " + since(now, time.UnixMilli(at))
|
||||
}
|
||||
|
||||
// finishedAge is the finish marker's text: "finished <age> ago" while the
|
||||
// stamp is set, "" when zero — zero means never finished, and the reversal
|
||||
// (un-finish) must not read as history after a press (issue #158).
|
||||
func finishedAge(now time.Time, at int64) string {
|
||||
if at == 0 {
|
||||
return ""
|
||||
}
|
||||
return "finished " + since(now, time.UnixMilli(at))
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"bookmarkmanager/backend/internal/store"
|
||||
)
|
||||
|
||||
// seriesDetailView derives the provenance line from the three stamps the
|
||||
// admin projection already carries: the correction stamp outranks a raising
|
||||
// Reader, which outranks a check stamp, and a Series with none of the three
|
||||
// renders no line at all — it was never read, and no actor class is true of
|
||||
// it. Acquisition stamps latest_checked_at exactly as a Poll does, so an
|
||||
// acquired value lands in the same "machine read" class (#152).
|
||||
func TestSeriesDetailViewProvenance(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
a store.AdminSeries
|
||||
want string
|
||||
}{
|
||||
{"correction stamp", store.AdminSeries{LatestCorrectedAt: 1}, "correction"},
|
||||
{"raising reader only", store.AdminSeries{RaisedByReader: true}, "sighting"},
|
||||
{"check stamp only", store.AdminSeries{LatestCheckedAt: 1}, "machine read"},
|
||||
{"correction outranks sighting", store.AdminSeries{LatestCorrectedAt: 1, RaisedByReader: true}, "correction"},
|
||||
{"none of the three", store.AdminSeries{}, ""},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := (&Handler{}).seriesDetailView(tc.a).Provenance; got != tc.want {
|
||||
t.Fatalf("Provenance = %q, want %q", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"bookmarkmanager/backend/internal/store"
|
||||
)
|
||||
|
||||
// The card carries two guarantees a browser can break that Go cannot see, so
|
||||
// they are asserted on the rendered markup:
|
||||
//
|
||||
// - the monogram is unconditional. A cover that 404s or a request the phone
|
||||
// drops leaves an <img> with no bytes, and the letter underneath it is the
|
||||
// only thing between that and the browser's broken-image glyph in a 93px
|
||||
// slot. Rendering it only when Cover is empty covers the wrong failure.
|
||||
// - the chapter field does not refuse its own value. It is pre-filled from
|
||||
// LastChapterNum, which the API accepts as any float, so a step that
|
||||
// quantises the field makes a series read to 1200.25 unsavable without
|
||||
// first editing a number the reader did not want to change.
|
||||
func TestCardRenderKeepsCoverFallbackAndAcceptsFractionalChapter(t *testing.T) {
|
||||
tmpl, err := template.ParseFS(templateFS, "templates/*.html")
|
||||
if err != nil {
|
||||
t.Fatalf("ParseFS: %v", err)
|
||||
}
|
||||
b := store.Bookmark{
|
||||
Key: "asura:x", Site: "asura", Title: "Chronicles", Status: store.StatusReading,
|
||||
Cover: "https://bookmarks.test/covers/abc", LastChapter: "Chapter 1200.25",
|
||||
LastChapterNum: 1200.25,
|
||||
}
|
||||
var out strings.Builder
|
||||
if err := tmpl.ExecuteTemplate(&out, "card", b); err != nil {
|
||||
t.Fatalf("ExecuteTemplate: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
|
||||
if !strings.Contains(got, `class="monogram"`) {
|
||||
t.Error("a card with a cover rendered no monogram: a failed image has no fallback")
|
||||
}
|
||||
if !strings.Contains(got, `step="any"`) {
|
||||
t.Error(`chapter input is not step="any": a fractional pre-filled value is unsavable`)
|
||||
}
|
||||
if !strings.Contains(got, `value="1200.25"`) {
|
||||
t.Errorf("chapter input is not pre-filled with the stored progress:\n%s", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Every failing request must land somewhere visible. A card's own writes report
|
||||
// into its .error-inline; a tab switch and a credential rotation have no card,
|
||||
// and #notice is the only slot filter.js can fall back to — without it in the
|
||||
// shell they fail silently. The tab's own active-state move is guarded on the
|
||||
// response, or a failed switch underlines a bucket the list is not showing.
|
||||
func TestAppShellCarriesFailureNoticeAndGuardsTabState(t *testing.T) {
|
||||
tmpl, err := template.ParseFS(templateFS, "templates/*.html")
|
||||
if err != nil {
|
||||
t.Fatalf("ParseFS: %v", err)
|
||||
}
|
||||
var out strings.Builder
|
||||
view := listView{Lib: store.KindManga, Tab: "all"}
|
||||
if err := tmpl.ExecuteTemplate(&out, "app", view); err != nil {
|
||||
t.Fatalf("ExecuteTemplate: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
|
||||
if !strings.Contains(got, `id="notice"`) {
|
||||
t.Error("no #notice in the shell: a failure with no card to sit in reports nowhere")
|
||||
}
|
||||
if strings.Contains(got, `hx-on::after-request="setActiveTab(this)"`) {
|
||||
t.Error("a tab moves its active state unconditionally: a failed switch underlines the wrong bucket")
|
||||
}
|
||||
}
|
||||
@@ -42,11 +42,6 @@ type DiscordConfig struct {
|
||||
ClientID string
|
||||
ClientSecret string
|
||||
GuildID string
|
||||
// GuildName is a human-readable name for the guild that gates access.
|
||||
// It is never fetched from Discord; it is an optional display string the
|
||||
// operator sets (DISCORD_GUILD_NAME) so the login screen can name the
|
||||
// community without inventing one.
|
||||
GuildName string
|
||||
// RequiredRole, when non-empty, is a role ID a member must hold on top of
|
||||
// guild membership. Empty by default: membership alone suffices.
|
||||
RequiredRole string
|
||||
@@ -178,21 +173,16 @@ func (h *Handler) discordCallback(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
// The refusal is the same for a non-member and a member without the
|
||||
// required role. When DISCORD_GUILD_NAME is set the message names the
|
||||
// community so a stranger knows which Discord to ask about; otherwise it
|
||||
// degrades to a generic community label and still gives the next step. It
|
||||
// never names the numeric guild id, which would not be actionable.
|
||||
// required role, and it names neither the guild nor its id: an outsider
|
||||
// cannot tell whether the guild exists, let alone which one gates.
|
||||
//
|
||||
// It also returns before EnsureReader, so a refused sign-in leaves no
|
||||
// Reader row behind — the gate is the only thing standing between guild
|
||||
// membership and a library.
|
||||
if !isMember || (h.discord.RequiredRole != "" && !slices.Contains(member.Roles, h.discord.RequiredRole)) {
|
||||
h.limiter.Fail(ip, time.Now())
|
||||
msg := "This Discord account is not a member of this community. Ask a member for an invite and try again."
|
||||
if h.discord.GuildName != "" {
|
||||
msg = fmt.Sprintf("This Discord account is not a member of the %s Discord. Ask a member for an invite and try again.", h.discord.GuildName)
|
||||
}
|
||||
h.renderLogin(w, http.StatusForbidden, msg)
|
||||
h.renderLogin(w, http.StatusForbidden,
|
||||
"This Discord account is not a member of this community.")
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
||||
// Title search runs entirely in the browser: the full list is already in the
|
||||
// DOM, so filtering it needs no request.
|
||||
(function () {
|
||||
function applyFilter(e) {
|
||||
function applyFilter() {
|
||||
var box = document.getElementById("search");
|
||||
if (!box) return;
|
||||
var query = box.value.trim();
|
||||
@@ -30,21 +30,6 @@
|
||||
none.hidden = !(needle !== "" && cards.length > 0 && visible === 0);
|
||||
if (!none.hidden) none.querySelector(".no-match-q").textContent = query;
|
||||
}
|
||||
|
||||
var isCardSwap = e && e.detail && e.detail.target && e.detail.target.classList && e.detail.target.classList.contains("card");
|
||||
if (isCardSwap) return;
|
||||
var announce = document.getElementById("sr-announce");
|
||||
if (announce) {
|
||||
if (needle === "") {
|
||||
announce.textContent = "";
|
||||
} else if (cards.length === 0) {
|
||||
announce.textContent = "";
|
||||
} else if (visible === 0) {
|
||||
announce.textContent = 'No titles match "' + query + '"';
|
||||
} else {
|
||||
announce.textContent = visible + ' ' + (visible === 1 ? 'title matches' : 'titles match') + ' "' + query + '"';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener("input", function (e) {
|
||||
@@ -62,54 +47,6 @@
|
||||
// htmx replaces the list on a tab switch, so re-apply to the new cards.
|
||||
document.body.addEventListener("htmx:afterSwap", applyFilter);
|
||||
document.addEventListener("bmgr:refilter", applyFilter);
|
||||
// Focus handoff on remove: the card and its focused button vanish with the
|
||||
// swap, so focus would fall to <body> in silence. Remember the next card's
|
||||
// play link before the DELETE and hand focus to it after, or to the list
|
||||
// when it was the last row.
|
||||
var pendingRemove = null;
|
||||
document.body.addEventListener("htmx:beforeRequest", function (e) {
|
||||
var elt = e.detail.elt;
|
||||
if (!elt || !elt.getAttribute("hx-delete")) return;
|
||||
var card = elt.closest(".card");
|
||||
if (!card) return;
|
||||
var nxt = card.nextElementSibling;
|
||||
while (nxt && (!nxt.classList.contains("card") || nxt.hidden)) nxt = nxt.nextElementSibling;
|
||||
var play = nxt && nxt.querySelector(".play");
|
||||
pendingRemove = { card: card, play: play };
|
||||
});
|
||||
document.body.addEventListener("htmx:afterSwap", function (e) {
|
||||
if (!pendingRemove) return;
|
||||
if (e.detail.target !== pendingRemove.card) return;
|
||||
if (pendingRemove.play && document.body.contains(pendingRemove.play)) {
|
||||
pendingRemove.play.focus();
|
||||
} else {
|
||||
var list = document.getElementById("list");
|
||||
if (list) list.focus();
|
||||
}
|
||||
pendingRemove = null;
|
||||
var notice = document.getElementById("notice");
|
||||
if (notice && !notice.hidden) {
|
||||
notice.scrollIntoView({
|
||||
block: "nearest",
|
||||
behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth",
|
||||
});
|
||||
}
|
||||
});
|
||||
document.body.addEventListener("htmx:responseError", function () { pendingRemove = null; });
|
||||
document.body.addEventListener("htmx:sendError", function () { pendingRemove = null; });
|
||||
// htmx sets no aria-busy, so the in-flight window — up to the 15s timeout on
|
||||
// a phone in a dead zone — is silent to a screen reader; the busy bar and the
|
||||
// "Saving…" word are the visual half of the same signal. A successful swap
|
||||
// replaces the card and takes the attribute with it; afterRequest is for the
|
||||
// failures, where the card stays.
|
||||
document.body.addEventListener("htmx:beforeRequest", function (e) {
|
||||
var card = e.detail.elt && e.detail.elt.closest(".card");
|
||||
if (card) card.setAttribute("aria-busy", "true");
|
||||
});
|
||||
document.body.addEventListener("htmx:afterRequest", function (e) {
|
||||
var card = e.detail.elt && e.detail.elt.closest(".card");
|
||||
if (card) card.removeAttribute("aria-busy");
|
||||
});
|
||||
})();
|
||||
|
||||
function setActiveTab(el) {
|
||||
@@ -124,7 +61,7 @@ function setActiveTab(el) {
|
||||
document.dispatchEvent(new Event("bmgr:refilter"));
|
||||
}
|
||||
|
||||
// The chapter-edit form and the archive/remove confirm rows are the
|
||||
// The chapter-edit form and the archive/finish/remove confirm rows are the
|
||||
// per-card disclosure panels; only one makes sense open at a time. The button
|
||||
// that owns an open panel carries .open, which is how the strip shows which
|
||||
// cell the panel belongs to.
|
||||
@@ -160,10 +97,10 @@ function toggleChapterForm(key) {
|
||||
if (form && !form.hidden) form.querySelector("input").focus();
|
||||
}
|
||||
|
||||
// kind is "archive" | "remove" — the panel id and the owning action
|
||||
// kind is "archive" | "finish" | "remove" — the panel id and the owning action
|
||||
// cell share it.
|
||||
function toggleConfirmRow(key, kind) {
|
||||
var cls = { archive: ".box", remove: ".remove" }[kind];
|
||||
var cls = { archive: ".box", finish: ".finish", remove: ".remove" }[kind];
|
||||
var row = togglePanel(key, "confirm-" + kind + "-" + key, ".actions " + cls);
|
||||
// Focus the answer rather than trusting aria-live on a container that merely
|
||||
// unhides: it makes the announcement deterministic, keeps tab order inside
|
||||
@@ -184,72 +121,19 @@ document.addEventListener("keydown", function (e) {
|
||||
if (e.key !== "Escape" || !e.target.closest) return;
|
||||
var card = e.target.closest(".card");
|
||||
var owner = card && card.querySelector(".actions .open");
|
||||
if (owner) {
|
||||
if (!owner) return;
|
||||
closeCardPanels(card.id.replace(/^card-/, ""));
|
||||
owner.focus();
|
||||
return;
|
||||
}
|
||||
// Admin confirm rows: any open .confirm-row that contains the focused element
|
||||
var row = e.target.closest(".confirm-row");
|
||||
if (row && !row.hidden) {
|
||||
row.hidden = true;
|
||||
var opener = row.id && document.querySelector('[aria-controls="' + row.id + '"]');
|
||||
if (opener) {
|
||||
opener.setAttribute("aria-expanded", "false");
|
||||
opener.focus();
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Also handle when focus is outside row but row is open on page (e.g., opener focused)
|
||||
var openRow = document.querySelector(".admin-sheet .confirm-row:not([hidden])");
|
||||
if (openRow) {
|
||||
openRow.hidden = true;
|
||||
var op = openRow.id && document.querySelector('[aria-controls="' + openRow.id + '"]');
|
||||
if (op) {
|
||||
op.setAttribute("aria-expanded", "false");
|
||||
op.focus();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// A failed favourite/chapter/delete request leaves the card in place (htmx
|
||||
// does not swap on a non-2xx response) but otherwise gives no sign anything
|
||||
// went wrong. Surface it inline instead of leaving the tap looking ignored.
|
||||
(function () {
|
||||
function slotFor(elt) {
|
||||
function showError(elt, message, linkHref, linkText) {
|
||||
var card = elt.closest(".card");
|
||||
if (card) {
|
||||
var s = card.querySelector(".error-inline");
|
||||
if (s) return s;
|
||||
}
|
||||
// Admin: per-form inline slot
|
||||
var dform = elt.closest(".dform");
|
||||
if (dform) {
|
||||
var ds = dform.querySelector(".error-inline");
|
||||
if (ds) return ds;
|
||||
}
|
||||
// Admin: per-reader roster
|
||||
var readers = elt.closest("#readers");
|
||||
if (readers) {
|
||||
var rs = readers.querySelector(".error-inline");
|
||||
if (rs) return rs;
|
||||
}
|
||||
// Admin: series row — reuse row-msg if present, otherwise fall back
|
||||
var trow = elt.closest(".trow");
|
||||
if (trow) {
|
||||
var ts = trow.querySelector(".error-inline") || trow.querySelector(".row-msg");
|
||||
if (ts) return ts;
|
||||
}
|
||||
return document.getElementById("notice");
|
||||
}
|
||||
|
||||
function inCard(slot) {
|
||||
return slot.classList.contains("error-inline");
|
||||
}
|
||||
|
||||
function show(slot, message, linkHref, linkText) {
|
||||
if (slot.id === "notice") slot.setAttribute("role", "status");
|
||||
var slot = card && card.querySelector(".error-inline");
|
||||
if (!slot) return;
|
||||
slot.textContent = message;
|
||||
if (linkHref) {
|
||||
var a = document.createElement("a");
|
||||
@@ -271,10 +155,9 @@ document.addEventListener("keydown", function (e) {
|
||||
}
|
||||
|
||||
document.body.addEventListener("htmx:beforeRequest", function (e) {
|
||||
var slot = slotFor(e.detail.elt);
|
||||
var card = e.detail.elt.closest(".card");
|
||||
var slot = card && card.querySelector(".error-inline");
|
||||
if (slot) slot.hidden = true;
|
||||
var n = document.getElementById("notice");
|
||||
if (n && !n.hidden && n.textContent.indexOf("Removed ") === 0) n.hidden = true;
|
||||
});
|
||||
|
||||
// The handlers answer a bad value with http.Error, i.e. a short plain-text
|
||||
@@ -287,31 +170,19 @@ document.addEventListener("keydown", function (e) {
|
||||
}
|
||||
|
||||
document.body.addEventListener("htmx:responseError", function (e) {
|
||||
var slot = slotFor(e.detail.elt);
|
||||
if (!slot) return;
|
||||
var xhr = e.detail.xhr;
|
||||
// "Saved" is only true of a card's own write; a failed tab switch saved
|
||||
// nothing because it was never a write.
|
||||
if (xhr.status === 401) {
|
||||
show(slot, inCard(slot) ? "Session expired — nothing was saved." : "Session expired.",
|
||||
"/login", "Log in again");
|
||||
showError(e.detail.elt, "Session expired — nothing was saved.", "/login", "Log in again");
|
||||
return;
|
||||
}
|
||||
if (xhr.status === 400) {
|
||||
var reason = reasonFrom(xhr);
|
||||
show(slot, reason ? reason + "." : "That value wasn't accepted — check it and try again.");
|
||||
showError(e.detail.elt, reason ? reason + "." : "That value wasn't accepted — check it and try again.");
|
||||
return;
|
||||
}
|
||||
show(slot, inCard(slot) ? "Couldn't save — try again." : "That didn't go through — try again.");
|
||||
showError(e.detail.elt, "Couldn't save — try again.");
|
||||
});
|
||||
document.body.addEventListener("htmx:sendError", function (e) {
|
||||
var slot = slotFor(e.detail.elt);
|
||||
if (slot) show(slot, "No connection — try again.");
|
||||
});
|
||||
// htmx-config caps every request at 15s; without this the give-up is as
|
||||
// silent as the hang it replaced.
|
||||
document.body.addEventListener("htmx:timeout", function (e) {
|
||||
var slot = slotFor(e.detail.elt);
|
||||
if (slot) show(slot, "Timed out — try again.");
|
||||
showError(e.detail.elt, "No connection — try again.");
|
||||
});
|
||||
})();
|
||||
|
||||
@@ -54,10 +54,10 @@
|
||||
|
||||
--ink: #100f0e; /* page */
|
||||
--ash: #161413; /* recessed panel (chapter form) */
|
||||
--dim: #0d0c0b; /* archived rows sink */
|
||||
--rule: #221f1d; /* decorative hairlines — not interactive — hairline between sheets */
|
||||
--rule-soft: #1a1817; /* decorative hairlines — not interactive — measure edges */
|
||||
--field-line: #4a4540; /* ≈■ #4a4540 — interactive border, distinct from decorative --rule/--rule-soft */
|
||||
--dim: #0d0c0b; /* archived / finished rows sink */
|
||||
--rule: #221f1d; /* hairline between sheets */
|
||||
--rule-soft: #1a1817; /* measure edges */
|
||||
--field-line: #2c2926;
|
||||
--hover: #1a1816;
|
||||
|
||||
--paper: #f2ece5; /* highest-contrast text, primary button */
|
||||
@@ -70,8 +70,8 @@
|
||||
--faint: #3a3733; /* meta separators */
|
||||
--faint-2: #57504b; /* cover monogram */
|
||||
|
||||
--ember: #e85a41; /* the only heat — verified against --ember-wash, not --ink — ≈■ #e85a41 — verified 5.31:1 on --ember-wash #1c0f0d, not --ink */
|
||||
--ember-wash: #1c0f0d; /* ■ #1c0f0d — verified against this wash for is-new card/Recent/Updated/libswitch */
|
||||
--ember: #e0452c; /* the only heat */
|
||||
--ember-wash: #1a1211; /* ember-tinted surface */
|
||||
--ember-ink: #150907; /* text on solid ember */
|
||||
--ember-soft: #eda798; /* text on ember wash */
|
||||
/* Destruction is hot but not ember: a duller oxblood, so a remove confirm is
|
||||
@@ -80,7 +80,6 @@
|
||||
--danger-wash: #211311;
|
||||
--danger-ink: #150808;
|
||||
--danger-soft: #e2aaa1;
|
||||
--danger-line: #4a2e2b; /* resting hairline for Remove — muted danger, not alarm */
|
||||
--brass: #b8912f; /* favourite — a second, cooler metal */
|
||||
/* One accent per action, so a press says which lane it belongs to. All three
|
||||
are held at the same weight as --brass: muted, no ember competition. */
|
||||
@@ -93,17 +92,7 @@
|
||||
blue. Neither ember (new chapter) nor danger (destruction) may say
|
||||
"system unhealthy". */
|
||||
--patina: #5fb3a6;
|
||||
--patina-wash: #12201e;
|
||||
--patina-soft: #9ad6cd;
|
||||
--patina-line: #1e3a37;
|
||||
--brass-wash: #231e0f;
|
||||
--brass-soft: #e0c495;
|
||||
--slate-wash: #14202a;
|
||||
--slate-soft: #a8bdd2;
|
||||
--clay-wash: #241a13;
|
||||
--clay-soft: #d9b79d;
|
||||
--moss-wash: #13211a;
|
||||
--moss-soft: #a9ceb1;
|
||||
|
||||
/* Desktop cell borders for the two coloured action states. */
|
||||
--play-hot-line: #3a1d18;
|
||||
--fav-line: #332b14;
|
||||
@@ -127,9 +116,6 @@
|
||||
desktop, so both live here rather than as magic numbers. */
|
||||
--cover-w: 93px;
|
||||
--row-gap: 14px;
|
||||
/* The desktop scale-up lives in a token because `zoom` multiplies viewport
|
||||
units too: anything sized in vh has to divide it back out. */
|
||||
--zoom: 1;
|
||||
}
|
||||
|
||||
/* Light mode: same rules, cooler paper. Hues are re-tuned, not reused — the
|
||||
@@ -139,8 +125,8 @@
|
||||
--ink: #f7f4ef;
|
||||
--ash: #efeae3;
|
||||
--dim: #f1ede7;
|
||||
--rule: #e0dad2; /* decorative hairlines — not interactive */
|
||||
--rule-soft: #e8e3dc; /* decorative hairlines — not interactive */
|
||||
--rule: #e0dad2;
|
||||
--rule-soft: #e8e3dc;
|
||||
--field-line: #d4cdc4;
|
||||
--hover: #efeae3;
|
||||
|
||||
@@ -152,42 +138,30 @@
|
||||
--faint: #c9c2ba;
|
||||
--faint-2: #a8a098;
|
||||
|
||||
--ember: #c23a22; /* verified against --ember-wash, not --ink */
|
||||
--ember-wash: #fbeee9; /* verified against --ember-wash, not --ink — wash ground */
|
||||
--ember: #c23a22;
|
||||
--ember-wash: #fbeee9;
|
||||
--ember-ink: #fff;
|
||||
--ember-soft: #7c2314; /* from #8d2c17 — crimson not brown, 4.9:1 on #fbeee9 */
|
||||
--ember-soft: #8d2c17;
|
||||
--danger: #97362a;
|
||||
--danger-wash: #fbe9e5;
|
||||
--danger-ink: #fff;
|
||||
--danger-soft: #7c2c22;
|
||||
--danger-line: #d8b8b0; /* resting hairline for Remove — light counterpart to #4a2e2b */
|
||||
--brass: #8a681c;
|
||||
--slate: #3f6689;
|
||||
--moss: #3d6c46;
|
||||
--clay: #7c5533;
|
||||
--trash: #8c6558;
|
||||
--patina: #1f6f66;
|
||||
--patina-wash: #def3f0;
|
||||
--patina-soft: #144a43;
|
||||
--patina-line: #b8ddd8;
|
||||
--brass-wash: #fdf6e3;
|
||||
--brass-soft: #5a4812;
|
||||
--slate-wash: #e8eef5;
|
||||
--slate-soft: #24445f;
|
||||
--clay-wash: #fdf0e6;
|
||||
--clay-soft: #5a3520;
|
||||
--moss-wash: #e7f3e8;
|
||||
--moss-soft: #23482a;
|
||||
|
||||
--play-hot-line: #f0cfc6;
|
||||
--fav-line: #e3d3a4;
|
||||
|
||||
--asura: #4f6b80;
|
||||
--demonic: #7a5c4a; /* from #8a6a55 — 5.1:1 on #f7f4ef, ~4.7:1 on #efeae3 */
|
||||
--comix: #5a6c4b; /* from #5f7250 — 5.2:1 on #f7f4ef, 4.77:1 on #efeae3 — was 4.38:1 on ash, fails AA */
|
||||
--demonic: #8a6a55;
|
||||
--comix: #5f7250;
|
||||
--kagane: #6f5f7d;
|
||||
--novelfull: #6f5f3f; /* from #7d6f4f — same bar */
|
||||
--lightnovelworld: #3d6b5e; /* from #4f7d70 — lifts 3.90→4.8:1 on ash */
|
||||
--novelfull: #7d6f4f;
|
||||
--lightnovelworld: #4f7d70;
|
||||
|
||||
--hatch: repeating-linear-gradient(135deg, #e6e0d8 0 5px, #efeae3 5px 10px);
|
||||
--hatch-dim: repeating-linear-gradient(135deg, #ebe6de 0 5px, #f2eee8 5px 10px);
|
||||
@@ -204,11 +178,6 @@ body {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
/* Every shell sets viewport-fit=cover, which puts the sheet's own hairline
|
||||
borders and its 20px gutter under a landscape cutout on a notched phone.
|
||||
Zero on every other device, so it costs nothing to honour here. */
|
||||
padding-left: env(safe-area-inset-left);
|
||||
padding-right: env(safe-area-inset-right);
|
||||
}
|
||||
|
||||
a { color: inherit; text-decoration: none; }
|
||||
@@ -217,19 +186,6 @@ button { cursor: pointer; }
|
||||
|
||||
/* Every hideable thing here is a flex container, and display beats hidden. */
|
||||
[hidden] { display: none !important; }
|
||||
/* Visually hidden but still announced — the live region for mutation and
|
||||
filter results. Display:none would silence it. */
|
||||
.sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
/* Ends flush with the right edge of the card (30% wide × 233% travel), so the
|
||||
card itself never needs overflow: hidden to contain it. */
|
||||
@@ -247,9 +203,6 @@ button { cursor: pointer; }
|
||||
width: 100%;
|
||||
max-width: var(--measure);
|
||||
min-height: 100vh;
|
||||
/* The URL bar is inside 100vh on mobile Chromium, so the flush bottom
|
||||
border sits under it. dvh is the visible box; vh above is the fallback. */
|
||||
min-height: 100dvh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-left: 1px solid var(--rule-soft);
|
||||
@@ -295,15 +248,6 @@ button { cursor: pointer; }
|
||||
.ghost:hover { color: var(--paper); border-bottom-color: var(--paper); }
|
||||
/* The label is 15px tall by design; the thumb gets 44 without moving it. */
|
||||
.ghost::after { content: ""; position: absolute; inset: -15px -12px; }
|
||||
/* Nav and standalone controls share one paper ring. The per-action cells in
|
||||
the card strip carry their own accent rings instead; everything here would
|
||||
otherwise fall back to the UA default, which is a bright blue on a palette
|
||||
tuned for a dark room. */
|
||||
.ghost:focus-visible,
|
||||
.tabs a:focus-visible,
|
||||
.libswitch a:focus-visible,
|
||||
.empty .clear-search:focus-visible,
|
||||
.login-card button:focus-visible { outline: 2px solid var(--paper); outline-offset: 2px; }
|
||||
|
||||
/* ---- userscript setup: collapsed by default, one hairline, no card ---- */
|
||||
.setup {
|
||||
@@ -317,7 +261,7 @@ button { cursor: pointer; }
|
||||
align-items: center;
|
||||
min-height: 44px;
|
||||
padding: 0;
|
||||
font: 500 11px/1 var(--font-mono);
|
||||
font: 500 10px/1 var(--font-mono);
|
||||
letter-spacing: .2em;
|
||||
text-transform: uppercase;
|
||||
color: var(--mute-2);
|
||||
@@ -352,22 +296,71 @@ button { cursor: pointer; }
|
||||
letter-spacing: .04em;
|
||||
}
|
||||
|
||||
|
||||
/* Sticky: the buckets and the search box are how a large library is triaged,
|
||||
and a phone three screens in otherwise has to scroll back to the top to
|
||||
reach either. The keyrow below is deliberately left to scroll away — it
|
||||
teaches the icon strip once, and 150px of permanent chrome on an 844px
|
||||
phone costs more than re-scrolling for a reminder does. */
|
||||
.chrome {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
/* Cards are position: relative, so without this they paint over it. */
|
||||
z-index: 2;
|
||||
background: var(--ink);
|
||||
padding-top: env(safe-area-inset-top);
|
||||
/* ---- admin page: two sections on the same measured sheet, no cards ----
|
||||
The reading page is a list of series; this is a list of facts. Both are
|
||||
sheets of hairline-separated rows, so the roster keeps the shape it had as
|
||||
a fold-out and the Lane block copies it. */
|
||||
.readers, .lanes { margin: 0 20px; padding: 12px 0 16px; border-bottom: 1px solid var(--rule); }
|
||||
.readers h2, .lanes h2 {
|
||||
margin: 0;
|
||||
padding: 8px 0;
|
||||
font: 500 10px/1 var(--font-mono);
|
||||
letter-spacing: .2em;
|
||||
text-transform: uppercase;
|
||||
color: var(--mute-2);
|
||||
}
|
||||
.readerlist, .lanelist { margin: 0; padding: 0; list-style: none; }
|
||||
.readerlist li, .lanelist li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 16px;
|
||||
min-height: 44px;
|
||||
border-top: 1px solid var(--rule);
|
||||
}
|
||||
.reader-actions { display: flex; gap: 18px; margin-left: auto; }
|
||||
.readerlist form { margin: 0; }
|
||||
.reader-id {
|
||||
font: 500 13px/1.4 var(--font-mono);
|
||||
letter-spacing: .04em;
|
||||
color: var(--paper);
|
||||
}
|
||||
.reader-sessions {
|
||||
font: 500 10px/1 var(--font-mono);
|
||||
letter-spacing: .14em;
|
||||
text-transform: uppercase;
|
||||
color: var(--mute);
|
||||
}
|
||||
.reader-sightings, .lane-fact {
|
||||
font: 500 10px/1 var(--font-mono);
|
||||
letter-spacing: .14em;
|
||||
text-transform: uppercase;
|
||||
color: var(--mute-2);
|
||||
}
|
||||
/* Two states the owner is meant to find rather than read for: a Reader whose
|
||||
reports no longer defer a Poll, and a Lane that is not keeping its promise.
|
||||
Both wear --patina — never ember, which means one thing, and never danger,
|
||||
which is destruction. */
|
||||
.reader-blocked, .lane-mark {
|
||||
font: 500 10px/1 var(--font-mono);
|
||||
letter-spacing: .14em;
|
||||
text-transform: uppercase;
|
||||
color: var(--patina);
|
||||
}
|
||||
.lane-site {
|
||||
font: 400 19px/1.2 var(--font-display);
|
||||
color: var(--paper-dim);
|
||||
}
|
||||
/* The whole row leans patina when the Lane needs attention, so the scan is one
|
||||
pass down the left edge rather than a read of every mark. */
|
||||
.lanelist li.attention .lane-site { color: var(--patina); }
|
||||
.lane-browser { padding: 12px 0 0; }
|
||||
/* Revocation cuts someone off, so it wears --danger. Ember stays reserved for
|
||||
the new-chapter signal. */
|
||||
.ghost.danger { color: var(--danger); }
|
||||
.ghost.danger:hover { color: var(--danger); border-bottom-color: var(--danger); }
|
||||
|
||||
.chrome { display: flex; flex-direction: column; }
|
||||
|
||||
.searchbar {
|
||||
display: flex;
|
||||
@@ -378,9 +371,8 @@ button { cursor: pointer; }
|
||||
border-bottom: 1px solid var(--rule);
|
||||
color: var(--mute-2);
|
||||
}
|
||||
/* The bar carries a resting recolour on focus-within, and the input carries
|
||||
its own ring: the 1px border change alone is a weaker indicator than every
|
||||
other control on the sheet gets, on the control most worth finding. */
|
||||
/* The input drops its own outline, so the bar it sits in carries the focus
|
||||
ring — same move the two other inputs make with their border. */
|
||||
.searchbar:focus-within { border-bottom-color: var(--paper); color: var(--paper); }
|
||||
.searchbar svg { width: 15px; height: 15px; flex: none; }
|
||||
.search {
|
||||
@@ -391,8 +383,8 @@ button { cursor: pointer; }
|
||||
background: transparent;
|
||||
color: var(--paper);
|
||||
font: 400 15px var(--font-body);
|
||||
outline: none;
|
||||
}
|
||||
.search:focus-visible { outline: 2px solid var(--paper); outline-offset: 3px; }
|
||||
.search::placeholder { color: var(--mute-2); }
|
||||
|
||||
/* Tabs are set in the display serif and underlined, not chipped. */
|
||||
@@ -404,9 +396,6 @@ button { cursor: pointer; }
|
||||
overflow-y: hidden;
|
||||
scrollbar-width: none;
|
||||
border-bottom: 1px solid var(--rule);
|
||||
/* Right-edge fade — the pills and 4th tab crop invisibly without it. */
|
||||
-webkit-mask-image: linear-gradient(to right, black calc(100% - 24px), transparent);
|
||||
mask-image: linear-gradient(to right, black calc(100% - 24px), transparent);
|
||||
}
|
||||
.tabs::-webkit-scrollbar { display: none; }
|
||||
.tabs a {
|
||||
@@ -422,25 +411,21 @@ button { cursor: pointer; }
|
||||
font: 400 17px var(--font-display);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.tabs a:hover { color: var(--paper-dim); background: var(--hover); border-radius: 2px 2px 0 0; }
|
||||
.tabs a:hover { color: var(--paper-dim); }
|
||||
.tabs a.active {
|
||||
color: var(--paper);
|
||||
border-bottom: 2px solid var(--paper);
|
||||
margin-bottom: -1px;
|
||||
background: var(--hover);
|
||||
}
|
||||
/* Updated is the one tab that carries heat. */
|
||||
.tabs .tab-new { color: var(--ember); }
|
||||
.tabs .tab-new.active { border-bottom-color: var(--ember); background: var(--ember-wash); color: var(--ember); }
|
||||
.tabs .tab-new:hover { background: var(--ember-wash); color: var(--ember); }
|
||||
.tabs .tab-new.active { border-bottom-color: var(--ember); }
|
||||
.count {
|
||||
font: 600 10px var(--font-mono);
|
||||
letter-spacing: 0;
|
||||
padding: 2px 5px;
|
||||
border: 1px solid currentColor;
|
||||
background: var(--ink);
|
||||
}
|
||||
.tab-new .count { background: var(--ember-wash); }
|
||||
|
||||
/* ---- action key: one permanent line under the tabs, so the icon strip below
|
||||
never has to be guessed at. Lean on a phone (28px, edge to edge), a step
|
||||
@@ -464,18 +449,12 @@ button { cursor: pointer; }
|
||||
}
|
||||
.keyrow .pair svg { width: 14px; height: 14px; flex: none; }
|
||||
.keyrow .pair span {
|
||||
font: 500 11px/1 var(--font-mono);
|
||||
font: 500 10px/1 var(--font-mono);
|
||||
letter-spacing: .04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.keyrow .pair.brass svg { color: var(--brass); }
|
||||
.keyrow .pair.slate svg { color: var(--slate); }
|
||||
.keyrow .pair.clay svg { color: var(--clay); }
|
||||
.keyrow .pair.trash svg { color: var(--trash); }
|
||||
.keyrow .pair.brass span { color: var(--brass); }
|
||||
.keyrow .pair.slate span { color: var(--slate); }
|
||||
.keyrow .pair.clay span { color: var(--clay); }
|
||||
.keyrow .pair.trash span { color: var(--trash); }
|
||||
|
||||
/* ---- continue reading ---- */
|
||||
.recent {
|
||||
@@ -488,7 +467,7 @@ button { cursor: pointer; }
|
||||
.recent h2 {
|
||||
margin: 0;
|
||||
padding: 0 20px;
|
||||
font: 500 11px/1 var(--font-mono);
|
||||
font: 500 10px/1 var(--font-mono);
|
||||
letter-spacing: .2em;
|
||||
text-transform: uppercase;
|
||||
color: var(--mute-2);
|
||||
@@ -500,10 +479,6 @@ button { cursor: pointer; }
|
||||
overflow-y: hidden;
|
||||
scrollbar-width: none;
|
||||
padding: 0 20px 4px;
|
||||
scroll-snap-type: x proximity;
|
||||
/* Static right-edge fade — newest card at 93px+GAP is otherwise invisible at 360px. */
|
||||
-webkit-mask-image: linear-gradient(to right, black calc(100% - 24px), transparent);
|
||||
mask-image: linear-gradient(to right, black calc(100% - 24px), transparent);
|
||||
}
|
||||
.recent-strip::-webkit-scrollbar { display: none; }
|
||||
.recent-card {
|
||||
@@ -512,7 +487,6 @@ button { cursor: pointer; }
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
scroll-snap-align: start;
|
||||
}
|
||||
.recent-cover {
|
||||
position: relative;
|
||||
@@ -523,11 +497,6 @@ button { cursor: pointer; }
|
||||
place-items: center;
|
||||
overflow: hidden;
|
||||
}
|
||||
/* Cover and monogram share one grid cell rather than stacking: the monogram is
|
||||
the fallback for a cover that fails to load, not only for one that was never
|
||||
acquired, and an image that fails to decode otherwise renders the browser's
|
||||
broken-image glyph over the hatch. */
|
||||
.recent-cover > img, .recent-cover > .monogram { grid-area: 1 / 1; }
|
||||
.recent-cover img { width: 100%; height: 100%; object-fit: cover; }
|
||||
.recent-title {
|
||||
font: 400 16px/1.25 var(--font-display);
|
||||
@@ -536,7 +505,6 @@ button { cursor: pointer; }
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.recent-chapter {
|
||||
font: 500 11px/1 var(--font-mono);
|
||||
@@ -545,7 +513,6 @@ button { cursor: pointer; }
|
||||
}
|
||||
.recent-card.is-new .recent-title { color: var(--paper-hot); }
|
||||
.recent-card.is-new .recent-chapter { color: var(--ember); }
|
||||
.recent-card.is-new .recent-cover { outline: 1px solid color-mix(in oklch, var(--ember) 26%, transparent); outline-offset: -1px; }
|
||||
|
||||
/* The rule at the cover foot is the only cover ornament: ember for a new
|
||||
chapter, brass for a favourite. */
|
||||
@@ -577,11 +544,6 @@ button { cursor: pointer; }
|
||||
animation: sheetIn .18s ease-out;
|
||||
}
|
||||
.card.is-dim { background: var(--dim); }
|
||||
.card.is-new {
|
||||
background: var(--ember-wash);
|
||||
border-bottom-color: color-mix(in oklch, var(--ember) 14%, var(--rule));
|
||||
}
|
||||
.card.is-new .cover { outline: 1px solid color-mix(in oklch, var(--ember) 22%, transparent); outline-offset: -1px; }
|
||||
|
||||
.row { display: flex; flex-wrap: wrap; align-items: center; gap: var(--row-gap); }
|
||||
|
||||
@@ -595,12 +557,9 @@ button { cursor: pointer; }
|
||||
place-items: center;
|
||||
overflow: hidden;
|
||||
}
|
||||
.cover > img, .cover > .monogram { grid-area: 1 / 1; }
|
||||
.cover img { width: 100%; height: 100%; object-fit: cover; }
|
||||
.cover .monogram { font-size: 32px; }
|
||||
.is-dim .cover { background: var(--hatch-dim); }
|
||||
.is-dim .cover img { filter: grayscale(1); opacity: .85; }
|
||||
.is-dim .cover .monogram { color: var(--mute-2); }
|
||||
.is-dim .cover { background: var(--hatch-dim); filter: grayscale(1); opacity: .85; }
|
||||
|
||||
.body {
|
||||
flex: 1;
|
||||
@@ -618,17 +577,6 @@ button { cursor: pointer; }
|
||||
min-width: 0;
|
||||
font: 400 21px/1.2 var(--font-display);
|
||||
color: var(--paper-dim);
|
||||
/* Titles come from a third party's og:title. One unbroken 90-character
|
||||
token measured 789px of document on a 390px viewport — the whole sheet
|
||||
scrolled sideways — so every slot that prints one breaks mid-word. */
|
||||
overflow-wrap: anywhere;
|
||||
/* Three lines, so one scraped 90-character title cannot set the rhythm of
|
||||
the whole list. Deeper than the strip's two: this is where the title is
|
||||
the primary identifier, not a thumbnail caption. */
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 3;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
/* Heat: crimson title over an ember hairline sized to the text, not the row. */
|
||||
.is-new .title {
|
||||
@@ -637,9 +585,6 @@ button { cursor: pointer; }
|
||||
color: var(--paper-hot);
|
||||
border-bottom: 1px solid var(--ember);
|
||||
padding-bottom: 3px;
|
||||
/* -webkit-box fills its line box, which would stretch the ember hairline to
|
||||
the full row; the underline is sized to the text. */
|
||||
width: fit-content;
|
||||
}
|
||||
.is-dim .title { font-style: italic; color: var(--mute); }
|
||||
.is-dim .fav-mark { color: var(--mute-2); }
|
||||
@@ -668,7 +613,6 @@ button { cursor: pointer; }
|
||||
.new-chapter { color: var(--ember); }
|
||||
.state { display: flex; align-items: center; gap: 4px; color: var(--mute); }
|
||||
.state svg { width: 10px; height: 10px; }
|
||||
.state.finished { color: var(--moss); }
|
||||
.is-dim .meta { color: var(--mute-2); }
|
||||
.is-dim .site-asura, .is-dim .site-demonic,
|
||||
.is-dim .site-comix, .is-dim .site-kagane,
|
||||
@@ -683,7 +627,7 @@ button { cursor: pointer; }
|
||||
}
|
||||
.libswitch a {
|
||||
padding: 7px 13px;
|
||||
font: 500 11px/1 var(--font-mono);
|
||||
font: 500 10px/1 var(--font-mono);
|
||||
letter-spacing: .12em;
|
||||
text-transform: uppercase;
|
||||
color: var(--mute);
|
||||
@@ -699,6 +643,9 @@ button { cursor: pointer; }
|
||||
box-shadow: inset 0 -2px 0 var(--ember);
|
||||
}
|
||||
.topbar form { margin-left: 18px; }
|
||||
/* The admin page's topbar has no switch to fill the middle, so its back link
|
||||
keeps company with Log out at the right edge instead of floating centre. */
|
||||
.topbar .back { margin-left: auto; }
|
||||
/* At phone width brand + switch + Log out do not fit on one line, so the
|
||||
switch takes its own row under the wordmark rather than pushing Log out
|
||||
off-screen. */
|
||||
@@ -708,6 +655,9 @@ button { cursor: pointer; }
|
||||
.libswitch { order: 3; margin-left: 0; }
|
||||
.libswitch a { flex: 1; text-align: center; padding: 8px 14px; }
|
||||
.topbar form { margin-left: 12px; }
|
||||
/* The admin page has no switch to take the second row, so its brand claims
|
||||
the first outright and the back link keeps Log out company below. */
|
||||
.topbar:has(.back) .brand { flex: 1 1 100%; }
|
||||
}
|
||||
|
||||
/* ---- action strip: full-width on a phone, hairline-divided cells ---- */
|
||||
@@ -731,39 +681,28 @@ button { cursor: pointer; }
|
||||
.actions > *:last-child { border-right: none; }
|
||||
.actions svg { width: 17px; height: 17px; }
|
||||
.actions > *:hover { color: var(--paper); }
|
||||
/* Per-action accent on hover and press: gold favourite, slate archive, clay
|
||||
chapter. Remove keeps --danger, play keeps paper/ember. */
|
||||
.actions .fav:hover, .actions .fav:active, .actions .fav:focus-visible { color: var(--brass); background: var(--brass-wash); }
|
||||
.actions .fav:focus-visible { outline: 2px solid var(--brass); outline-offset: -2px; }
|
||||
.actions .pencil:hover, .actions .pencil:active, .actions .pencil:focus-visible { color: var(--clay); background: var(--clay-wash); }
|
||||
.actions .pencil:focus-visible { outline: 2px solid var(--clay); outline-offset: -2px; }
|
||||
.actions .box:hover, .actions .box:active, .actions .box:focus-visible { color: var(--slate); background: var(--slate-wash); }
|
||||
.actions .box:focus-visible { outline: 2px solid var(--slate); outline-offset: -2px; }
|
||||
/* Per-action accent on hover and press: gold favourite, slate archive, moss
|
||||
finished, clay chapter. Remove keeps --danger, play keeps paper/ember. */
|
||||
.actions .fav:hover, .actions .fav:active, .actions .fav:focus-visible { color: var(--brass); }
|
||||
.actions .pencil:hover, .actions .pencil:active, .actions .pencil:focus-visible { color: var(--clay); }
|
||||
.actions .box:hover, .actions .box:active, .actions .box:focus-visible { color: var(--slate); }
|
||||
.actions .finish:hover, .actions .finish:active, .actions .finish:focus-visible { color: var(--moss); }
|
||||
.actions .play { color: var(--paper); }
|
||||
|
||||
.is-new .actions .play { color: var(--ember); }
|
||||
.actions .play:hover { background: var(--hover); }
|
||||
.is-new .actions .play:hover { background: var(--ember-wash); color: var(--ember); }
|
||||
.actions .play:focus-visible { background: var(--hover); outline: 2px solid var(--paper); outline-offset: -2px; }
|
||||
.is-new .actions .play:focus-visible { background: var(--ember-wash); color: var(--ember); outline-color: var(--ember); }
|
||||
.actions .on { color: var(--brass); background: var(--brass-wash); }
|
||||
.actions .on { color: var(--brass); }
|
||||
.actions .restore { color: var(--paper); }
|
||||
.actions .restore:hover, .actions .restore:active, .actions .restore:focus-visible { color: var(--slate); background: var(--slate-wash); }
|
||||
.actions .restore:focus-visible { outline: 2px solid var(--slate); outline-offset: -2px; }
|
||||
.actions .remove { color: var(--trash); box-shadow: inset 1px 0 0 var(--danger-line); }
|
||||
.actions .remove:hover, .actions .remove:active, .actions .remove:focus-visible { color: var(--danger); background: var(--danger-wash); }
|
||||
.actions .remove:focus-visible { outline: 2px solid var(--danger); outline-offset: -2px; }
|
||||
.actions .remove { color: var(--trash); }
|
||||
.actions .remove:hover { color: var(--danger); }
|
||||
.actions .open { background: var(--hover); color: var(--paper); }
|
||||
/* Lifecycle cells already sit on --ash, which is what --hover resolves to, so
|
||||
an open one needs the next step up to stay legible as the panel's owner. */
|
||||
.actions .lifecycle.open { background: var(--rule); }
|
||||
.actions .lifecycle.open.box, .actions .lifecycle.open.box:hover { background: var(--slate-wash); color: var(--slate); }
|
||||
.actions .remove.open { background: var(--danger-wash); color: var(--danger); }
|
||||
.is-dim .actions > * { color: var(--mute-2); }
|
||||
.is-dim .actions > *:hover { background: transparent; color: var(--mute); }
|
||||
|
||||
/* Two clusters by consequence: navigate (play) | organize (favourite,
|
||||
chapter) | lifecycle (archive/restore, remove). The lifecycle cells
|
||||
/* Three clusters by consequence: navigate (play) | organize (favourite,
|
||||
chapter) | lifecycle (archive/restore, finish, remove). The lifecycle cells
|
||||
sit on a recessed ground so the thumb reads "this one moves the series"
|
||||
before it reads which icon it landed on. */
|
||||
.actions > .lifecycle { background: var(--ash); }
|
||||
@@ -783,7 +722,7 @@ button { cursor: pointer; }
|
||||
}
|
||||
.chapter-form .hint {
|
||||
margin: 0;
|
||||
font: 500 11px/1 var(--font-mono);
|
||||
font: 500 10px/1 var(--font-mono);
|
||||
letter-spacing: .14em;
|
||||
text-transform: uppercase;
|
||||
color: var(--mute-2);
|
||||
@@ -800,10 +739,9 @@ button { cursor: pointer; }
|
||||
font: 500 17px var(--font-mono);
|
||||
outline: none;
|
||||
}
|
||||
/* Clay carries the chapter action -- paper flashes on a dimmed OLED and ember
|
||||
reads as "invalid" on a valid number. */
|
||||
.chapter-form input:focus { border-color: var(--clay); }
|
||||
.chapter-form input:focus-visible { border-color: var(--clay); outline: 2px solid var(--clay); outline-offset: 2px; }
|
||||
/* Focus follows the .searchbar idiom — paper, not heat: a red border on a
|
||||
valid number field reads as "invalid". */
|
||||
.chapter-form input:focus { border-color: var(--paper); }
|
||||
.chapter-form input::-webkit-outer-spin-button,
|
||||
.chapter-form input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
|
||||
.chapter-form button {
|
||||
@@ -814,7 +752,6 @@ button { cursor: pointer; }
|
||||
color: var(--ink);
|
||||
font: 400 17px var(--font-display);
|
||||
}
|
||||
.chapter-form button:focus-visible { outline: 2px solid var(--clay); outline-offset: 2px; }
|
||||
|
||||
.confirm-row {
|
||||
display: flex;
|
||||
@@ -827,26 +764,24 @@ button { cursor: pointer; }
|
||||
}
|
||||
/* The remove question names the series, so it has to be able to take the row
|
||||
to itself and push the buttons onto their own line. */
|
||||
.confirm-row span { flex: 1 1 16ch; font: 400 17px/1.3 var(--font-display); color: var(--danger-soft); overflow-wrap: anywhere; }
|
||||
.confirm-row span { flex: 1 1 16ch; font: 400 17px/1.3 var(--font-display); color: var(--danger-soft); }
|
||||
.confirm-row div { display: flex; flex: none; gap: 12px; margin-left: auto; }
|
||||
.confirm-row button {
|
||||
height: 46px;
|
||||
padding: 0 14px;
|
||||
border: 1px solid var(--field-line);
|
||||
background: var(--ash);
|
||||
color: var(--paper-dim);
|
||||
background: transparent;
|
||||
color: var(--mute);
|
||||
font: 500 12px var(--font-body);
|
||||
}
|
||||
.confirm-row button:hover { color: var(--paper); border-color: var(--paper); }
|
||||
.confirm-row button:focus-visible { color: var(--paper); border-color: var(--paper); outline: 2px solid var(--paper); outline-offset: 2px; }
|
||||
.confirm-row button:hover { color: var(--paper); }
|
||||
.confirm-row .danger-solid {
|
||||
border: none;
|
||||
background: var(--danger);
|
||||
color: var(--danger-ink);
|
||||
font-weight: 600;
|
||||
}
|
||||
.confirm-row .danger-solid:focus-visible { outline-color: var(--danger); }
|
||||
/* Archive is reversible, so its confirm asks in grey — only the
|
||||
/* Archive and finish are reversible, so their confirm asks in grey — only the
|
||||
irreversible remove gets the danger wash. */
|
||||
.confirm-row.calm { background: var(--ash); }
|
||||
.confirm-row.calm span { color: var(--paper-dim); }
|
||||
@@ -856,31 +791,16 @@ button { cursor: pointer; }
|
||||
color: var(--ink);
|
||||
font-weight: 600;
|
||||
}
|
||||
.confirm-row .go:hover, .confirm-row .go:focus-visible { color: var(--ink); }
|
||||
.confirm-row .go:hover { color: var(--ink); }
|
||||
|
||||
/* The same notice in two positions: .error-inline belongs to one card and
|
||||
reports a write that failed, .notice sits under the chrome and reports the
|
||||
requests that have no card to belong to — a tab switch, a rotation. */
|
||||
.error-inline {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 9px;
|
||||
margin: 0;
|
||||
padding: 11px 13px;
|
||||
background: var(--danger-wash);
|
||||
border-left: 2px solid var(--danger);
|
||||
font: 400 16px var(--font-display);
|
||||
color: var(--danger-soft);
|
||||
}
|
||||
.notice {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 9px;
|
||||
margin: 0;
|
||||
padding: 11px 20px;
|
||||
background: var(--ash);
|
||||
border-left: 2px solid var(--patina);
|
||||
border-bottom: 1px solid var(--rule);
|
||||
border-left: 2px solid var(--mute);
|
||||
font: 400 16px var(--font-display);
|
||||
color: var(--paper-dim);
|
||||
}
|
||||
@@ -890,22 +810,13 @@ button { cursor: pointer; }
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
border-radius: 50%;
|
||||
background: var(--danger);
|
||||
}
|
||||
.notice::before {
|
||||
content: "";
|
||||
flex: none;
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
border-radius: 50%;
|
||||
background: var(--patina);
|
||||
background: var(--mute);
|
||||
animation: mutePulse 1.4s ease-in-out infinite;
|
||||
}
|
||||
.error-inline .error-link, .notice .error-link {
|
||||
.error-inline .error-link {
|
||||
border-bottom: 1px solid var(--field-line);
|
||||
color: var(--paper);
|
||||
}
|
||||
.error-inline .error-link { border-bottom-color: color-mix(in oklch, var(--danger) 26%, transparent); color: var(--danger-soft); }
|
||||
|
||||
/* Busy: a grey hairline slides across the top of the sheet — deliberately not
|
||||
ember, which on a list screen only ever means "new chapter". */
|
||||
@@ -920,22 +831,6 @@ button { cursor: pointer; }
|
||||
background: var(--mute);
|
||||
animation: barSlide 1.15s linear infinite;
|
||||
}
|
||||
/* Past about two seconds the bar alone stops reading as "working" and starts
|
||||
reading as "ignored" — and htmx's own timeout is 15s. Delayed rather than
|
||||
immediate: every response on a live connection lands well inside it. */
|
||||
@keyframes busyWord { to { opacity: 1 } }
|
||||
.card.htmx-request::after {
|
||||
content: "Saving…";
|
||||
position: absolute;
|
||||
top: 6px;
|
||||
right: 20px;
|
||||
font: 500 11px/1 var(--font-mono);
|
||||
letter-spacing: .1em;
|
||||
text-transform: uppercase;
|
||||
color: var(--mute);
|
||||
opacity: 0;
|
||||
animation: busyWord 0s 2s forwards;
|
||||
}
|
||||
|
||||
/* ---- empty ---- */
|
||||
.empty {
|
||||
@@ -944,7 +839,7 @@ button { cursor: pointer; }
|
||||
gap: 7px;
|
||||
padding: 40px 20px 48px;
|
||||
}
|
||||
.empty strong { font: 400 20px var(--font-display); color: var(--paper); overflow-wrap: anywhere; }
|
||||
.empty strong { font: 400 20px var(--font-display); color: var(--paper); }
|
||||
.empty .clear-search {
|
||||
align-self: flex-start;
|
||||
margin-top: 4px;
|
||||
@@ -968,26 +863,21 @@ button { cursor: pointer; }
|
||||
.login-card {
|
||||
width: 100%;
|
||||
max-width: 420px;
|
||||
min-height: calc(100vh / var(--zoom));
|
||||
min-height: calc(100dvh / var(--zoom));
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
padding: 52px 28px 40px;
|
||||
}
|
||||
.login-card .eyebrow {
|
||||
font: 500 11px/1 var(--font-mono);
|
||||
font: 500 10px/1 var(--font-mono);
|
||||
letter-spacing: .2em;
|
||||
text-transform: uppercase;
|
||||
color: var(--mute-2);
|
||||
}
|
||||
.login-card h1 {
|
||||
margin: 14px 0 0;
|
||||
/* The wordmark is the widest unbreakable run in the app; at 44px it is
|
||||
wider than a 360px phone, and the page has no other content to scroll
|
||||
to, so the overflow reads as a broken page. Fluid to the measured fit
|
||||
(30px clears a 320px viewport), locked at the design size from 520px up. */
|
||||
font: 400 clamp(30px, 8.5vw, 44px)/1 var(--font-display);
|
||||
font: 400 44px/1 var(--font-display);
|
||||
letter-spacing: -.01em;
|
||||
color: var(--paper);
|
||||
}
|
||||
@@ -1038,7 +928,7 @@ button { cursor: pointer; }
|
||||
keeps every proportion — hairlines, cover ratios, hit targets —
|
||||
intact. ---- */
|
||||
@media (min-width: 1280px) {
|
||||
:root { --zoom: 1.2; zoom: var(--zoom); }
|
||||
:root { zoom: 1.2; }
|
||||
}
|
||||
|
||||
/* ---- desktop: same measure, actions fold up beside the row ---- */
|
||||
@@ -1058,7 +948,6 @@ button { cursor: pointer; }
|
||||
}
|
||||
.tabs { order: 1; flex: none; gap: 20px; padding: 0; border-bottom: none; }
|
||||
.tabs a { padding: 10px 0 14px; font-size: 18px; }
|
||||
.tabs, .recent-strip { -webkit-mask-image: none; mask-image: none; }
|
||||
.searchbar { order: 2; flex: 1; margin: 0; border-bottom: none; }
|
||||
.recent h2, .recent-strip { padding-left: 32px; padding-right: 32px; }
|
||||
.keyrow {
|
||||
@@ -1070,7 +959,8 @@ button { cursor: pointer; }
|
||||
}
|
||||
.keyrow .pair { flex-direction: row; gap: 7px; }
|
||||
.keyrow .pair svg { width: 14px; height: 14px; }
|
||||
.keyrow .pair span { letter-spacing: .1em; }
|
||||
.keyrow .pair span { font-size: 11px; letter-spacing: .1em; }
|
||||
.keyrow .full { display: inline; }
|
||||
.recent-card, .recent-cover { width: var(--cover-w); }
|
||||
.recent-cover { height: calc(var(--cover-w) * 4 / 3); }
|
||||
.recent-title { font-size: 17px; }
|
||||
@@ -1091,29 +981,17 @@ button { cursor: pointer; }
|
||||
than by the hairline the phone layout uses. */
|
||||
.actions > .play + *,
|
||||
.actions > *:not(.lifecycle) + .lifecycle { margin-left: 10px; box-shadow: none; }
|
||||
.actions .remove { box-shadow: none; border-left-color: var(--danger-line); }
|
||||
.is-new .actions .play { border-color: var(--play-hot-line); }
|
||||
.actions .on { border-color: var(--fav-line); }
|
||||
/* The cell border follows the icon on hover, so the accent reads as a state
|
||||
rather than a stray colour. */
|
||||
.actions .fav:hover, .actions .pencil:hover,
|
||||
.actions .box:hover { border-color: currentColor; }
|
||||
.actions .box:hover, .actions .finish:hover { border-color: currentColor; }
|
||||
|
||||
/* Panels line up with the body text, i.e. past the cover and its gap. */
|
||||
.chapter-form, .confirm-row, .error-inline {
|
||||
margin-left: calc(var(--cover-w) + var(--row-gap));
|
||||
}
|
||||
/* Not the panel indent: the notice is chrome, so it keeps the sheet gutter
|
||||
every other full-width row uses. */
|
||||
.notice { padding-left: 32px; padding-right: 32px; }
|
||||
}
|
||||
|
||||
/* Every other control on this sheet is already 44 or borrows a .ghost::after
|
||||
to get there; the library switch is the one sized by its own padding in both
|
||||
layouts, and padding plus an 11px line lands at 43. min-height states the
|
||||
target instead of arithmetic on the font. Gated on the pointer rather than
|
||||
the width — a touch laptop lands on the desktop layout with the same
|
||||
thumb. */
|
||||
@media (pointer: coarse) {
|
||||
.libswitch a { min-height: 44px; display: grid; place-items: center; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
@@ -1121,7 +999,4 @@ button { cursor: pointer; }
|
||||
busy bar and error dot are both ::before. Their static form still reads:
|
||||
the bar stays drawn and .actions stays dimmed. */
|
||||
*, *::before, *::after { animation: none !important; transition: none !important; }
|
||||
/* The busy word is revealed by a zero-duration delayed animation, which the
|
||||
rule above cancels — show it from the start instead. */
|
||||
.card.htmx-request::after { opacity: 1; }
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
{{/* Every owner-only address shares this shell; page content stays behind its
|
||||
bookmarkable route so the active tab survives a reload. */}}
|
||||
{{/* The owner's administrative page: everything that reaches past one Reader,
|
||||
at its own address so it can be bookmarked rather than hunted for inside
|
||||
the reading page. Owner-only at route registration (requireOwner), which
|
||||
is why nothing in here re-tests who is asking. */}}
|
||||
{{define "admin"}}
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
@@ -7,53 +9,30 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<meta name="color-scheme" content="dark light">
|
||||
{{/* Same request timeout as the library shell: the Lanes fragment refreshes
|
||||
itself every 30s, so an untimed hung request stacks. */}}
|
||||
<meta name="htmx-config" content='{"timeout":15000}'>
|
||||
<title>BookmarkManager — Admin</title>
|
||||
<link rel="icon" href="/static/logo.svg" type="image/svg+xml">
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
<link rel="stylesheet" href="/static/admin.css">
|
||||
<link rel="preload" href="/static/fonts/instrument-serif-400-latin.woff2" as="font" type="font/woff2" crossorigin>
|
||||
<link rel="preload" href="/static/fonts/dm-sans-var-latin.woff2" as="font" type="font/woff2" crossorigin>
|
||||
<script src="/static/htmx.min.js" defer></script>
|
||||
<script src="/static/filter.js" defer></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="sheet admin-sheet">
|
||||
<div class="sheet">
|
||||
<header class="topbar">
|
||||
<h1 class="brand">{{template "mark" .}}<span>Bookmark<em>Manager</em></span></h1>
|
||||
<span class="topbar-actions">
|
||||
<a class="ghost" href="/">Library</a>
|
||||
{{/* Back to the library, no switch: this page belongs to neither library,
|
||||
and the ember-lit switch says which library you are reading. */}}
|
||||
<a class="ghost back" href="/">Library</a>
|
||||
<form method="post" action="/logout">
|
||||
<button type="submit" class="ghost">Log out</button>
|
||||
</form>
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<nav class="navrow" aria-label="Admin pages">
|
||||
<a href="/admin" class="{{if eq .Page "overview"}}active{{end}}" {{if eq .Page "overview"}}aria-current="page"{{end}}>Overview</a>
|
||||
<a href="/admin/lanes" class="{{if eq .Page "lanes"}}active{{end}}" {{if eq .Page "lanes"}}aria-current="page"{{end}}>Lanes</a>
|
||||
<a href="/admin/readers" class="{{if eq .Page "readers"}}active{{end}}" {{if eq .Page "readers"}}aria-current="page"{{end}}>Readers</a>
|
||||
<a href="/admin/series" class="{{if or (eq .Page "series") (eq .Page "series-detail")}}active{{end}}" {{if or (eq .Page "series") (eq .Page "series-detail")}}aria-current="page"{{end}}>Series</a>
|
||||
</nav>
|
||||
{{/* The live region wraps the swapped block rather than being it: the
|
||||
refresh replaces the section wholesale, and a region recreated on every
|
||||
update is never announced. */}}
|
||||
<div aria-live="polite">{{template "lanes" .Lanes}}</div>
|
||||
|
||||
{{/* Where a failure with no specific slot gets reported — same slot the
|
||||
reader library uses under its chrome. filter.js fills it. */}}
|
||||
<p class="notice" id="notice" role="status" hidden></p>
|
||||
<div id="sr-announce" class="sr-only" role="status" aria-live="polite" aria-atomic="true"></div>
|
||||
|
||||
<main class="page admin-page">
|
||||
{{if eq .Page "lanes"}}
|
||||
{{template "lanes" .Lanes}}
|
||||
{{else if eq .Page "readers"}}
|
||||
{{template "readers" .}}
|
||||
{{else if eq .Page "series"}}
|
||||
{{template "series-list" .SeriesList}}
|
||||
{{else if eq .Page "series-detail"}}
|
||||
{{template "series-detail" .Detail}}
|
||||
{{else}}{{template "overview" .Overview}}{{end}}
|
||||
</main>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -5,11 +5,6 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<meta name="color-scheme" content="dark light">
|
||||
{{/* htmx defaults to no timeout, so a phone that walks into a dead zone
|
||||
leaves the XHR open forever and the card it came from keeps its busy bar
|
||||
and its disabled actions until a reload. 15s is well past any response
|
||||
this deployment produces. */}}
|
||||
<meta name="htmx-config" content='{"timeout":15000}'>
|
||||
<title>BookmarkManager</title>
|
||||
<link rel="icon" href="/static/logo.svg" type="image/svg+xml">
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
@@ -58,39 +53,38 @@
|
||||
<a href="{{.PageURL "all"}}" class="{{if eq .Tab "all"}}active{{end}}"
|
||||
{{if eq .Tab "all"}}aria-current="page"{{end}}
|
||||
hx-get="{{.ListURL "all"}}" hx-target="#list" hx-swap="innerHTML"
|
||||
hx-push-url="{{.PageURL "all"}}" hx-on::after-request="if (event.detail.successful) setActiveTab(this)">All</a>
|
||||
hx-push-url="{{.PageURL "all"}}" hx-on::after-request="setActiveTab(this)">All</a>
|
||||
{{/* The one bucket novels do not have: without a poller-fed "what is out
|
||||
that I have not read", the tab would only ever restate All. */}}
|
||||
{{if eq .Lib "manga"}}
|
||||
<a href="{{.PageURL "new"}}" class="tab-new {{if eq .Tab "new"}}active{{end}}"
|
||||
{{if eq .Tab "new"}}aria-current="page"{{end}}
|
||||
hx-get="{{.ListURL "new"}}" hx-target="#list" hx-swap="innerHTML"
|
||||
hx-push-url="{{.PageURL "new"}}" hx-on::after-request="if (event.detail.successful) setActiveTab(this)">Updated
|
||||
hx-push-url="{{.PageURL "new"}}" hx-on::after-request="setActiveTab(this)">Updated
|
||||
{{template "newcount" .}}</a>
|
||||
{{end}}
|
||||
<a href="{{.PageURL "fav"}}" class="{{if eq .Tab "fav"}}active{{end}}"
|
||||
{{if eq .Tab "fav"}}aria-current="page"{{end}}
|
||||
hx-get="{{.ListURL "fav"}}" hx-target="#list" hx-swap="innerHTML"
|
||||
hx-push-url="{{.PageURL "fav"}}" hx-on::after-request="if (event.detail.successful) setActiveTab(this)">Favourites</a>
|
||||
hx-push-url="{{.PageURL "fav"}}" hx-on::after-request="setActiveTab(this)">Favourites</a>
|
||||
<a href="{{.PageURL "archived"}}" class="{{if eq .Tab "archived"}}active{{end}}"
|
||||
{{if eq .Tab "archived"}}aria-current="page"{{end}}
|
||||
hx-get="{{.ListURL "archived"}}" hx-target="#list" hx-swap="innerHTML"
|
||||
hx-push-url="{{.PageURL "archived"}}" hx-on::after-request="if (event.detail.successful) setActiveTab(this)">Archived</a>
|
||||
hx-push-url="{{.PageURL "archived"}}" hx-on::after-request="setActiveTab(this)">Archived</a>
|
||||
<a href="{{.PageURL "finished"}}" class="{{if eq .Tab "finished"}}active{{end}}"
|
||||
{{if eq .Tab "finished"}}aria-current="page"{{end}}
|
||||
hx-get="{{.ListURL "finished"}}" hx-target="#list" hx-swap="innerHTML"
|
||||
hx-push-url="{{.PageURL "finished"}}" hx-on::after-request="setActiveTab(this)">Finished</a>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
{{/* Where a failure with no card to sit in gets reported: a tab switch, a
|
||||
rotation, an expired session. filter.js fills it and unhides it. */}}
|
||||
<p class="notice" id="notice" role="status" hidden></p>
|
||||
<div id="sr-announce" class="sr-only" role="status" aria-live="polite" aria-atomic="true"></div>
|
||||
|
||||
{{template "setup" .}}
|
||||
|
||||
{{template "keyrow" .}}
|
||||
|
||||
{{template "recent" .}}
|
||||
|
||||
<main id="list" class="list" tabindex="-1">
|
||||
<main id="list" class="list">
|
||||
{{template "list" .}}
|
||||
</main>
|
||||
</div>
|
||||
|
||||
@@ -1,22 +1,16 @@
|
||||
{{define "card"}}
|
||||
{{/* One sheet per series. is-new turns the title crimson over an ember rule;
|
||||
is-dim sinks archived rows into italic grey. */}}
|
||||
is-dim sinks archived and finished rows into italic grey. */}}
|
||||
<article class="card{{if eq .Status "reading"}}{{if .HasNewChapter}} is-new{{end}}{{else}} is-dim{{end}}"
|
||||
id="card-{{.Key}}" data-title="{{.Title}}">
|
||||
<div class="row">
|
||||
<a class="cover" href="{{.ContinueURL}}" target="_blank" rel="noopener noreferrer"
|
||||
tabindex="-1" aria-hidden="true">
|
||||
{{if .Cover}}<img src="{{.Cover}}" alt="" loading="lazy">
|
||||
{{/* aria-hidden on the cover link is not enough — Chromium still exposes
|
||||
the letter because the link is programmatically focusable — so the
|
||||
monogram carries its own, same as the recent strip's.
|
||||
|
||||
The monogram is always in the DOM under the image, not only when no
|
||||
cover was acquired: a stored cover that 404s or a phone that drops
|
||||
the request otherwise leaves the browser's broken-image glyph in a
|
||||
93px slot. onerror removes the image and the letter is already
|
||||
there. */}}
|
||||
{{if .Cover}}<img src="{{.Cover}}" alt="" loading="lazy" onerror="this.remove()">{{end}}
|
||||
<span class="monogram" aria-hidden="true">{{.Initial}}</span>
|
||||
monogram carries its own, same as the recent strip's. */}}
|
||||
{{else}}<span class="monogram" aria-hidden="true">{{.Initial}}</span>{{end}}
|
||||
{{if and (eq .Status "reading") .HasNewChapter}}<span class="foot-rule"></span>
|
||||
{{else if .Favorite}}<span class="foot-rule brass"></span>{{end}}
|
||||
</a>
|
||||
@@ -38,10 +32,9 @@
|
||||
{{if eq .Status "archived"}}
|
||||
<span class="sep">/</span>
|
||||
<span class="state">archived</span>
|
||||
{{end}}
|
||||
{{if .Finished}}
|
||||
{{else if eq .Status "finished"}}
|
||||
<span class="sep">/</span>
|
||||
<span class="state finished">finished</span>
|
||||
<span class="state"><svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-check"/></svg>finished</span>
|
||||
{{end}}
|
||||
</p>
|
||||
</div>
|
||||
@@ -52,19 +45,18 @@
|
||||
</a>
|
||||
<button class="fav{{if .Favorite}} on{{end}}"
|
||||
title="{{if .Favorite}}Remove from favourites{{else}}Add to favourites{{end}}"
|
||||
aria-label="{{if .Favorite}}Remove from favourites{{else}}Add to favourites{{end}}"
|
||||
aria-pressed="{{if .Favorite}}true{{else}}false{{end}}"
|
||||
aria-label="Toggle favourite"
|
||||
hx-post="/ui/bookmarks/{{.Key}}/favorite"
|
||||
hx-target="[id='card-{{.Key}}']" hx-swap="outerHTML"
|
||||
hx-indicator="[id='card-{{.Key}}']" hx-disabled-elt="this">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-star{{if .Favorite}}-on{{end}}"/></svg>
|
||||
</button>
|
||||
<button class="pencil" title="Set chapter" aria-label="Set chapter" aria-expanded="false" aria-controls="chapter-form-{{.Key}}"
|
||||
<button class="pencil" title="Set chapter" aria-label="Set chapter"
|
||||
onclick="toggleChapterForm('{{.Key}}')">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-pencil"/></svg>
|
||||
</button>
|
||||
{{/* Restore is a reversal, so it fires straight away; every move *out* of
|
||||
the list (archive, remove) goes through a confirm row. */}}
|
||||
the list (archive, finish, remove) goes through a confirm row. */}}
|
||||
{{if eq .Status "reading"}}
|
||||
<button class="lifecycle box" title="Archive" aria-label="Archive"
|
||||
aria-expanded="false" aria-controls="confirm-archive-{{.Key}}"
|
||||
@@ -79,6 +71,13 @@
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-undo"/></svg>
|
||||
</button>
|
||||
{{end}}
|
||||
{{if ne .Status "finished"}}
|
||||
<button class="lifecycle finish" title="Mark finished" aria-label="Mark finished"
|
||||
aria-expanded="false" aria-controls="confirm-finish-{{.Key}}"
|
||||
onclick="toggleConfirmRow('{{.Key}}', 'finish')">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-check"/></svg>
|
||||
</button>
|
||||
{{end}}
|
||||
<button class="lifecycle remove" title="Remove" aria-label="Remove"
|
||||
aria-expanded="false" aria-controls="confirm-remove-{{.Key}}"
|
||||
onclick="toggleConfirmRow('{{.Key}}', 'remove')">
|
||||
@@ -95,11 +94,8 @@
|
||||
label names the field and the latest sits after it as context. */}}
|
||||
<label class="hint" for="chapter-{{.Key}}">Chapter you're on</label>
|
||||
<div class="field">
|
||||
{{/* max is a fat-finger guard, not a real ceiling — no series is near it.
|
||||
step is "any" because the server accepts any float and the field is
|
||||
pre-filled from it: under step=0.1 a series read to 1200.25 opened a
|
||||
form that refused its own value. */}}
|
||||
<input id="chapter-{{.Key}}" name="chapter" type="number" step="any" min="0" max="9999"
|
||||
{{/* max is a fat-finger guard, not a real ceiling — no series is near it. */}}
|
||||
<input id="chapter-{{.Key}}" name="chapter" type="number" step="0.1" min="0" max="9999"
|
||||
value="{{.LastChapterNum}}" required>
|
||||
<button type="submit">Save</button>
|
||||
</div>
|
||||
@@ -120,6 +116,18 @@
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
{{if ne .Status "finished"}}
|
||||
<div class="confirm-row calm" id="confirm-finish-{{.Key}}" role="group" aria-live="polite" hidden>
|
||||
<span>Mark finished?</span>
|
||||
<div>
|
||||
<button class="go"
|
||||
hx-post="/ui/bookmarks/{{.Key}}/status" hx-vals='{"status":"finished"}'
|
||||
hx-target="[id='card-{{.Key}}']" hx-swap="outerHTML"
|
||||
hx-indicator="[id='card-{{.Key}}']" hx-disabled-elt="this">Finish</button>
|
||||
<button type="button" onclick="toggleConfirmRow('{{.Key}}', 'finish')">Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
<div class="confirm-row" id="confirm-remove-{{.Key}}" role="group" aria-live="polite" hidden>
|
||||
<span>Remove “{{.Title}}”? Chapter progress is lost.</span>
|
||||
<div>
|
||||
|
||||
@@ -14,9 +14,8 @@
|
||||
<a class="recent-card {{if .HasNewChapter}}is-new{{end}}" href="{{.ContinueURL}}"
|
||||
target="_blank" rel="noopener noreferrer">
|
||||
<span class="recent-cover">
|
||||
{{/* Monogram always present under the image; see card.html. */}}
|
||||
{{if .Cover}}<img src="{{.Cover}}" alt="" loading="lazy" onerror="this.remove()">{{end}}
|
||||
<span class="monogram" aria-hidden="true">{{.Initial}}</span>
|
||||
{{if .Cover}}<img src="{{.Cover}}" alt="" loading="lazy">
|
||||
{{else}}<span class="monogram" aria-hidden="true">{{.Initial}}</span>{{end}}
|
||||
{{if .HasNewChapter}}<span class="foot-rule"></span>
|
||||
{{else if .Favorite}}<span class="foot-rule brass"></span>{{end}}
|
||||
</span>
|
||||
@@ -30,16 +29,20 @@
|
||||
|
||||
{{/* The action key. The icon strip on a card is unlabelled, so one permanent
|
||||
line under the tabs names every glyph. It follows the tab rather than the
|
||||
row: the archived bucket swaps Archive for Restore. */}}
|
||||
row: the archived and finished buckets swap Archive for Restore, and a
|
||||
finished series has no Done to offer. */}}
|
||||
{{define "keyrow"}}
|
||||
<div class="keyrow" id="keyrow" aria-label="Action key"{{if .OOB}} hx-swap-oob="true"{{end}}>
|
||||
<span class="pair"><svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-play"/></svg><span>Read</span></span>
|
||||
<span class="pair brass"><svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-star"/></svg><span>Fav</span></span>
|
||||
<span class="pair clay"><svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-pencil"/></svg><span>Chapter</span></span>
|
||||
{{if eq .Tab "archived"}}
|
||||
<span class="pair slate"><svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-undo"/></svg><span>Restore</span></span>
|
||||
<span class="pair"><svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-pencil"/></svg><span>Chapter</span></span>
|
||||
{{if or (eq .Tab "archived") (eq .Tab "finished")}}
|
||||
<span class="pair"><svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-undo"/></svg><span>Restore</span></span>
|
||||
{{else}}
|
||||
<span class="pair slate"><svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-box"/></svg><span>Archive</span></span>
|
||||
<span class="pair"><svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-box"/></svg><span>Archive</span></span>
|
||||
{{end}}
|
||||
{{if ne .Tab "finished"}}
|
||||
<span class="pair"><svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-check"/></svg><span>Done</span></span>
|
||||
{{end}}
|
||||
<span class="pair trash"><svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-trash"/></svg><span>Delete</span></span>
|
||||
</div>
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
<symbol id="i-star-on" viewBox="0 0 24 24"><path d="M12 3.6l2.6 5.6 6 .8-4.4 4.2 1.1 6-5.3-2.9-5.3 2.9 1.1-6-4.4-4.2 6-.8z" fill="currentColor" stroke="currentColor" stroke-width="1.7" stroke-linejoin="round"/></symbol>
|
||||
<symbol id="i-pencil" viewBox="0 0 24 24"><path d="M4 20h4L19 9l-4-4L4 16z" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linejoin="round"/></symbol>
|
||||
<symbol id="i-box" viewBox="0 0 24 24"><path d="M3 7h18v4H3zM5 11v9h14v-9M10 15h4" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linejoin="round"/></symbol>
|
||||
<symbol id="i-check" viewBox="0 0 24 24"><path d="M4 12.5l5.2 5.5L20 6.5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
|
||||
<symbol id="i-trash" viewBox="0 0 24 24"><path d="M4 7h16M9.5 7V4h5v3M6.5 7l1 13h9l1-13M10.5 11v6M13.5 11v6" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></symbol>
|
||||
<symbol id="i-undo" viewBox="0 0 24 24"><path d="M4 9h9.5a5 5 0 010 10H8M4 9l4.2-4.2M4 9l4.2 4.2" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></symbol>
|
||||
<symbol id="i-search" viewBox="0 0 24 24"><circle cx="10.5" cy="10.5" r="6.5" fill="none" stroke="currentColor" stroke-width="1.8"/><path d="M15.3 15.3L20 20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></symbol>
|
||||
|
||||
@@ -1,63 +1,42 @@
|
||||
{{/* Poll Lane status: one row per Site's latest durable pass, refreshing
|
||||
itself so a run can be watched rather than sampled by reloading. The
|
||||
refresh is one attribute on the fragment root and the endpoint answers
|
||||
with this same fragment, so the swap replaces the element that asked.
|
||||
{{/* Poll Lane status: one row per Site, refreshing itself so a run can be
|
||||
watched rather than sampled by reloading. The refresh is one attribute on
|
||||
the fragment root and the endpoint answers with this same fragment, so the
|
||||
swap replaces the element that asked for it.
|
||||
|
||||
Every figure is read from poll_passes, never from a running poller: a
|
||||
restart answers from the database the moment it is up (issue #145). The
|
||||
browser fact is a deployment-config fact plus a reachability derived from
|
||||
the pass log; the cause chips and the state phrase are decided in Go,
|
||||
this template only prints them. */}}
|
||||
Every figure here is read out of the running poller, never out of a table:
|
||||
a Site absent from Rows has not completed a pass since the last restart,
|
||||
which the empty state must say — zeroes would read as a stopped Lane. */}}
|
||||
{{define "lanes"}}
|
||||
<section class="lanes" id="lanes"
|
||||
hx-get="/ui/admin/lanes" hx-trigger="every 30s" hx-swap="outerHTML" hx-sync="this:replace">
|
||||
<div class="sechead">
|
||||
<h2 class="sec">Poll Lanes</h2>
|
||||
<p class="statusline">
|
||||
{{if .PollerOff}}Polling: <span class="mark-faint">off</span>
|
||||
{{else}}Browser: {{if not .BrowserConfigured}}<span class="mark-faint">not configured</span>{{else if .BrowserReachable}}<span class="mark mark-strong">reachable</span>{{else}}<span class="mark bad">unreachable</span>{{end}}{{end}}
|
||||
</p>
|
||||
</div>
|
||||
<p class="hint">Healthy idle (paused, browser asleep, nothing eligible) needs no action — attention needs the owner.</p>
|
||||
hx-get="/ui/admin/lanes" hx-trigger="every 30s" hx-swap="outerHTML">
|
||||
<h2>Poll Lanes</h2>
|
||||
{{if .Rows}}
|
||||
<div class="tbl lanes">
|
||||
<div class="thead">
|
||||
<span>Site</span><span>Due</span><span>Checked</span><span>Gap</span>
|
||||
<span>Last pass</span><span title="Window outcomes for this Site (last 12h)">Outcomes · status</span><span></span>
|
||||
</div>
|
||||
<ul class="lanelist">
|
||||
{{range .Rows}}
|
||||
<div class="trow{{if .Attention}} attention{{end}}">
|
||||
<a class="c-site" href="{{.FailingHref}}">{{.Site}}</a>
|
||||
{{/* data-label is the column word for the phone layout, which drops the
|
||||
thead: three bare numbers in a row say nothing. */}}
|
||||
<span data-label="due">{{.Due}}</span>
|
||||
<span data-label="checked">{{.Checked}}</span>
|
||||
<span data-label="gap">{{.Gap}}</span>
|
||||
<span>ran {{.Ran}}</span>
|
||||
<span class="c-skip">{{if .HasChips}}{{range $i, $c := .Chips}}{{if $i}}<span class="mark-faint"> · </span>{{end}}<span class="mark">{{$c.Name}} {{$c.Count}}</span>{{end}}{{else}}<span class="mark-faint">none observed</span>{{end}}{{if .StatePhrase}} · <span class="{{if .StateGood}}ok{{else}}bad{{end}}" aria-label="{{if .StateGood}}healthy: {{end}}{{.StatePhrase}}">{{.StatePhrase}}</span>{{end}}</span>
|
||||
{{/* The pause control lives in the one slot the design leaves for it:
|
||||
a running Lane offers the three durations and Pause; a paused Lane
|
||||
offers Resume in the same place. Pause is not destruction — it
|
||||
takes nothing away and reverses in one press — so neither wears a
|
||||
confirm row or the danger accent. The form wraps the select so the
|
||||
offered duration travels with the press. */}}
|
||||
<span class="c-ctrl">{{if .Paused}}<span class="pausebar">
|
||||
<form hx-post="/admin/lanes/{{.Site}}/resume" hx-target="#lanes" hx-swap="outerHTML" hx-indicator="#lanes" hx-disabled-elt="find button" hx-sync="closest #lanes:replace">
|
||||
<button type="submit" class="ghost">Resume</button>
|
||||
</form>
|
||||
</span>{{else}}<span class="pausebar">
|
||||
<form hx-post="/admin/lanes/{{.Site}}/pause" hx-target="#lanes" hx-swap="outerHTML" hx-indicator="#lanes" hx-disabled-elt="find button, select" hx-sync="closest #lanes:replace">
|
||||
<select name="duration" aria-label="Pause duration">
|
||||
<option>1h</option><option selected>6h</option><option>24h</option>
|
||||
</select>
|
||||
<button type="submit" class="ghost">Pause</button>
|
||||
</form>
|
||||
</span>{{end}}</span>
|
||||
</div>
|
||||
<li{{if .Attention}} class="attention"{{end}}>
|
||||
<span class="lane-site">{{.Site}}</span>
|
||||
<span class="lane-fact">{{.Due}} due</span>
|
||||
<span class="lane-fact">{{.Checked}} checked</span>
|
||||
<span class="lane-fact">ran {{.Ran}}</span>
|
||||
{{if .Gap}}<span class="lane-fact">gap {{.Gap}}</span>{{end}}
|
||||
{{if .Clamped}}<span class="lane-mark">gap at floor</span>{{end}}
|
||||
{{if .Refusing}}<span class="lane-mark">refusing</span>{{end}}
|
||||
{{if .BrowserLost}}<span class="lane-mark">no browser</span>{{end}}
|
||||
{{if .Stalled}}<span class="lane-mark">not checking</span>{{end}}
|
||||
{{if .Asleep}}<span class="lane-mark">browser asleep</span>{{end}}
|
||||
</li>
|
||||
{{end}}
|
||||
</div>
|
||||
</ul>
|
||||
{{else}}
|
||||
<p class="empty">No data yet — no Lane has recorded a pass.</p>
|
||||
<p class="setup-copy">No data yet — no Lane has completed a pass since the
|
||||
backend started.</p>
|
||||
{{end}}
|
||||
<p class="setup-copy lane-browser">
|
||||
{{if .PollerOff}}Polling is switched off in this deployment: no Lane runs,
|
||||
and Latest Chapter comes from the userscripts alone.
|
||||
{{else}}Browser sidecar:
|
||||
{{if not .BrowserConfigured}}not configured — comix, kagane and novelfull
|
||||
pages are not fetched through it{{else if .BrowserReachable}}reachable
|
||||
{{else}}unreachable{{end}}.{{end}}</p>
|
||||
</section>
|
||||
{{end}}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
{{/* The client filter only hides cards, so without this the list area goes
|
||||
blank on a query that matches nothing. filter.js fills in the query and
|
||||
unhides it; it lives inside #list so a tab swap re-creates it. */}}
|
||||
<div class="empty" id="no-match" role="status" hidden>
|
||||
<div class="empty" id="no-match" hidden>
|
||||
<strong>No titles match “<span class="no-match-q"></span>”.</strong>
|
||||
<button type="button" class="clear-search">Clear search</button>
|
||||
</div>
|
||||
@@ -14,6 +14,8 @@
|
||||
<div class="empty"><strong>Nothing new.</strong><p>Every series is caught up to its latest chapter.</p></div>
|
||||
{{else if eq .Tab "archived"}}
|
||||
<div class="empty"><strong>Nothing archived.</strong><p>Shelve a series to park it here — it keeps getting checked for new chapters.</p></div>
|
||||
{{else if eq .Tab "finished"}}
|
||||
<div class="empty"><strong>Nothing finished yet.</strong><p>Mark a series finished and it moves out of your reading list.</p></div>
|
||||
{{else if .EmptyLibrary}}
|
||||
{{/* Nothing in either library, so the links are the only thing this page can
|
||||
usefully say. Both scripts: the two libraries are separate installs. */}}
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
<link rel="icon" href="/static/logo.svg" type="image/svg+xml">
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
<link rel="preload" href="/static/fonts/instrument-serif-400-latin.woff2" as="font" type="font/woff2" crossorigin>
|
||||
<link rel="preload" href="/static/fonts/dm-sans-var-latin.woff2" as="font" type="font/woff2" crossorigin>
|
||||
</head>
|
||||
<body>
|
||||
<main class="login-card">
|
||||
@@ -26,7 +25,7 @@
|
||||
<p class="error" role="alert">{{.Error}}</p>
|
||||
<button type="submit">Continue with Discord</button>
|
||||
</form>
|
||||
<p class="login-note">{{if .GuildName}}This library is for members of the {{.GuildName}} Discord. Ask a member for an invite to sign in.{{else}}This library is private to its Discord community. Ask a member for an invite to sign in.{{end}}</p>
|
||||
<p class="login-note">Guild membership is required to sign in.</p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
{{/* The Overview landing page: one verdict line leading, then a stats block
|
||||
where every figure is a door into the list that counts it, and the
|
||||
per-Site library shape table. Every judgement — the verdict state, which
|
||||
figures link, what a Lane's state means — is made in Go; this template
|
||||
only prints. */}}
|
||||
{{define "overview"}}
|
||||
<p class="verdict"><span class="attn">{{.Verdict}}</span> {{if .HasCounts}}<span class="counts">· <b>{{.Waiting}}</b> series waiting · <b>{{.Unchecked}}</b> unchecked over 12h{{if ne .Verdict "all lanes healthy"}} · <a href="/admin/lanes">review Lanes</a>{{end}}</span>{{end}}</p>
|
||||
<h2 class="sec">Hygiene</h2>
|
||||
<div class="stats">{{range .Hygiene}}<div class="stat"><span class="lbl">{{.Label}}</span>{{if .Href}}<a class="fig" href="{{.Href}}">{{.Count}}</a>{{else}}<span class="fig zero">{{.Count}}</span>{{end}}</div>{{end}}</div>
|
||||
<h2 class="sec">Library</h2>
|
||||
<div class="stats">{{range .Library}}<div class="stat"><span class="lbl">{{.Label}}</span>{{if .Href}}<a class="fig" href="{{.Href}}">{{.Count}}</a>{{else}}<span class="fig zero">{{.Count}}</span>{{end}}</div>{{end}}</div>
|
||||
{{/* data-label carries each cell's column word for the phone layout, which
|
||||
drops the thead: the CSS prints it as the cell's prefix. */}}
|
||||
<h2 class="sec">Sites · last 12h</h2>
|
||||
{{if .Sites}}<div class="tbl sites"><div class="thead"><span>Site</span><span>Series</span><span>No cover</span><span>Never checked</span><span title="Stale: not checked in 12h window">Stale</span><span title="Lane status — same vocabulary as Poll Lanes">Status</span></div>{{range .Sites}}<div class="trow"><a class="c-site site-{{.Site}}" href="{{.SiteHref}}">{{.Site}}</a>{{range .Figs}}{{if .Href}}<a class="fig" data-label="{{.Label}}" href="{{.Href}}">{{.Count}}</a>{{else}}<span class="fig zero" data-label="{{.Label}}">{{.Count}}</span>{{end}}{{end}}<span class="c-state{{if .StateGood}} ok{{end}}{{if .StateBad}} bad{{end}}"{{if .State}} aria-label="{{if .StateGood}}healthy: {{end}}{{.State}}"{{end}}>{{.State}}</span></div>{{end}}</div>{{else}}<p class="empty">No sites yet — bookmarked series will appear here once the userscript records a chapter.</p>{{end}}
|
||||
{{end}}
|
||||
@@ -13,10 +13,9 @@
|
||||
often a later Poll confirmed or contradicted what that Reader's browser
|
||||
reported; enough contradictions stop their reports deferring a Poll, and
|
||||
clearing the marks gives that back.</p>
|
||||
{{if .Readers}}
|
||||
<ul class="readerlist">
|
||||
{{range .Readers}}
|
||||
<li id="reader-{{.ID}}">
|
||||
<li>
|
||||
<span class="reader-id">{{.DiscordID}}</span>
|
||||
<span class="reader-sessions">{{.Sessions}} session{{if ne .Sessions 1}}s{{end}}</span>
|
||||
<span class="reader-sightings">{{.Agreements}} confirmed / {{.Disagreements}} contradicted</span>
|
||||
@@ -24,42 +23,26 @@
|
||||
numbers and a threshold. */}}
|
||||
{{if .Blocked}}<span class="reader-blocked">deferral blocked</span>{{end}}
|
||||
<span class="reader-actions">
|
||||
{{/* Clearing restores a privilege, so its confirm wears the calm wash,
|
||||
not destruction. Revocation destroys sessions, so it wears danger.
|
||||
Both are confirm-gated — the opener never posts. */}}
|
||||
<button type="button" class="ghost" aria-expanded="false" aria-controls="confirm-clear-{{.ID}}"
|
||||
onclick="document.getElementById('confirm-clear-{{.ID}}').hidden = false; this.setAttribute('aria-expanded','true')">Clear marks</button>
|
||||
{{/* Clearing restores a privilege, so it is a plain ghost button —
|
||||
the destruction accent belongs to revocation alone. It is offered
|
||||
on every row, including one reading zero: the remedy must be
|
||||
findable before the counters climb, not after. */}}
|
||||
<form hx-post="/readers/{{.ID}}/clear-marks" hx-target="#readers" hx-swap="outerHTML"
|
||||
hx-confirm="Clearing wipes this Reader's whole Sighting record, confirmations included. Clear?">
|
||||
<button type="submit" class="ghost">Clear marks</button>
|
||||
</form>
|
||||
{{/* The owner's own row never offers Revoke: it is the one row where the
|
||||
button would sign the tapping browser out, and the endpoint refuses
|
||||
it anyway. Logout is the deliberate way to do that. */}}
|
||||
{{if and .Sessions (ne .ID $.OwnerID)}}
|
||||
<button type="button" class="ghost danger" aria-expanded="false" aria-controls="confirm-revoke-{{.ID}}"
|
||||
onclick="document.getElementById('confirm-revoke-{{.ID}}').hidden = false; this.setAttribute('aria-expanded','true')">Revoke sessions</button>
|
||||
<form hx-post="/readers/{{.ID}}/revoke" hx-target="#readers" hx-swap="outerHTML"
|
||||
hx-confirm="Revoking signs this Reader out on every device immediately. Revoke?">
|
||||
<button type="submit" class="ghost danger">Revoke sessions</button>
|
||||
</form>
|
||||
{{end}}
|
||||
</span>
|
||||
<div class="confirm-row calm" id="confirm-clear-{{.ID}}" role="group" aria-live="polite" hidden>
|
||||
<span>Clear this Reader's Sighting record?</span>
|
||||
<div>
|
||||
<button type="button" class="go"
|
||||
hx-post="/readers/{{.ID}}/clear-marks" hx-target="#readers" hx-swap="outerHTML"
|
||||
hx-indicator="#readers" hx-disabled-elt="this">Clear</button>
|
||||
<button type="button" onclick="document.getElementById('confirm-clear-{{.ID}}').hidden = true; var b=document.querySelector('[aria-controls=\'confirm-clear-{{.ID}}\']'); if(b){b.setAttribute('aria-expanded','false'); b.focus();}">Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
{{if and .Sessions (ne .ID $.OwnerID)}}
|
||||
<div class="confirm-row" id="confirm-revoke-{{.ID}}" role="group" aria-live="polite" hidden>
|
||||
<span>Revoke this Reader's sessions?</span>
|
||||
<div>
|
||||
<button type="button" class="danger-solid"
|
||||
hx-post="/readers/{{.ID}}/revoke" hx-target="#readers" hx-swap="outerHTML"
|
||||
hx-indicator="#readers" hx-disabled-elt="this">Revoke</button>
|
||||
<button type="button" onclick="document.getElementById('confirm-revoke-{{.ID}}').hidden = true; var b=document.querySelector('[aria-controls=\'confirm-revoke-{{.ID}}\']'); if(b){b.setAttribute('aria-expanded','false'); b.focus();}">Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
</li>
|
||||
{{end}}
|
||||
</ul>
|
||||
{{else}}
|
||||
<p class="empty">No readers yet — the roster appears after the first Discord sign-in.</p>
|
||||
{{end}}
|
||||
<p class="error-inline" role="status" hidden></p>
|
||||
</section>
|
||||
{{end}}
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
{{/* Per-Series page: one address per Series, keyed "<site>:<series_id>" so the
|
||||
list row is one hop from it. Everything here is a Series-level fact plus
|
||||
the anonymous Reader count. Check now lands in its own .dform below the
|
||||
.detail-grid; the correction form is the grid's first column and the URL
|
||||
repair the second (issue #151). The pending and corrected markers ride the
|
||||
meta line with the other marks. */}}
|
||||
{{define "series-detail"}}
|
||||
<a class="ghost detail-back" href="/admin/series">← Series</a>
|
||||
<h1 class="detail-title">{{.Title}}</h1>
|
||||
<p class="detail-key">{{.Key}} · {{.Site}} · {{.Kind}}</p>
|
||||
{{if .Cover}}<div class="cover"><img src="{{.Cover}}" alt="" loading="lazy"></div>
|
||||
{{else}}<div class="cover" aria-hidden="true"><span>no cover</span></div>{{end}}
|
||||
{{template "series-detail-meta" .}}
|
||||
<div class="detail-grid">
|
||||
<form class="dform" hx-post="/admin/series/{{.Key}}/latest" hx-target="#detail-meta" hx-swap="outerHTML" hx-indicator="closest .dform" hx-disabled-elt="find button, input">
|
||||
<h3>Correct latest chapter</h3>
|
||||
<div class="field">
|
||||
<label class="sr-only" for="chapter-{{.Key}}">Latest chapter number</label>
|
||||
<input id="chapter-{{.Key}}" type="number" name="chapter" step="any" placeholder="{{.Chapter}}" required aria-describedby="hint-latest-{{.Key}}">
|
||||
<button type="submit" class="ghost">Save chapter</button>
|
||||
</div>
|
||||
<p class="hint" id="hint-latest-{{.Key}}">The next successful Poll overwrites this value. Use this only when the Poll is failing or the page is wrong.</p>
|
||||
{{if .Unverified}}<p class="hint">{{.Unverified}}</p>{{end}}
|
||||
<p class="error-inline" role="status" hidden></p>
|
||||
</form>
|
||||
<form class="dform" hx-post="/admin/series/{{.Key}}/series-url" hx-target="#detail-meta" hx-swap="outerHTML" hx-indicator="closest .dform" hx-disabled-elt="find button, input">
|
||||
<h3>Repair series URL</h3>
|
||||
<div class="field">
|
||||
<label class="sr-only" for="url-{{.Key}}">Series page URL</label>
|
||||
<input id="url-{{.Key}}" type="url" name="series_url" value="{{.URL}}" required aria-describedby="hint-url-{{.Key}}">
|
||||
<button type="submit" class="ghost">Save URL</button>
|
||||
</div>
|
||||
<p class="hint" id="hint-url-{{.Key}}">The Poll fetches this address. Saving does not verify it — A Site-wide host change is a SQL migration, not per-series edits.</p>
|
||||
<p class="error-inline" role="status" hidden></p>
|
||||
</form>
|
||||
</div>
|
||||
{{if .CanPoll}}
|
||||
<div class="dform">
|
||||
<div class="field"><button type="button" class="ghost"
|
||||
hx-post="/admin/series/{{.Key}}/poll" hx-target="#detail-meta" hx-swap="outerHTML"
|
||||
hx-indicator="#detail-meta" hx-disabled-elt="this">Check now</button></div>
|
||||
<p class="error-inline" role="status" hidden></p>
|
||||
</div>
|
||||
{{end}}
|
||||
{{if .CanRemove}}
|
||||
<div class="dform">
|
||||
<div class="field"><button type="button" class="ghost danger"
|
||||
aria-expanded="false" aria-controls="confirm-remove"
|
||||
onclick="document.getElementById('confirm-remove').hidden = false; this.setAttribute('aria-expanded','true')">Remove</button></div>
|
||||
<div class="confirm-row" id="confirm-remove" role="group" aria-live="polite" hidden>
|
||||
<span>Remove “{{.Title}}”? Stored cover is lost.</span>
|
||||
<div>
|
||||
<button type="button" class="danger-solid"
|
||||
hx-post="/admin/series/{{.Key}}/remove" hx-target="#detail-meta"
|
||||
hx-indicator="#detail-meta" hx-disabled-elt="this">Remove</button>
|
||||
<button type="button" onclick="document.getElementById('confirm-remove').hidden = true; document.querySelector('.dform .danger').setAttribute('aria-expanded','false')">Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="error-inline" role="status" hidden></p>
|
||||
</div>
|
||||
{{end}}
|
||||
{{if .Finished}}
|
||||
<div class="dform">
|
||||
<div class="field"><button type="button" class="ghost"
|
||||
hx-post="/admin/series/{{.Key}}/unfinish" hx-target="#detail-meta" hx-swap="outerHTML"
|
||||
hx-indicator="#detail-meta" hx-disabled-elt="this">Un-finish</button></div>
|
||||
<p class="error-inline" role="status" hidden></p>
|
||||
</div>
|
||||
{{else}}
|
||||
<div class="dform">
|
||||
<div class="field"><button type="button" class="ghost" aria-expanded="false" aria-controls="confirm-finish"
|
||||
onclick="document.getElementById('confirm-finish').hidden = false; this.setAttribute('aria-expanded','true')">Finish</button></div>
|
||||
{{if .SiteCompleted}}<p class="hint">{{.SiteCompleted}}</p>{{end}}
|
||||
<div class="confirm-row calm" id="confirm-finish" role="group" aria-live="polite" hidden>
|
||||
<span>Mark this Series finished?</span>
|
||||
<div>
|
||||
<button type="button" class="go" hx-post="/admin/series/{{.Key}}/finish" hx-target="#detail-meta" hx-swap="outerHTML"
|
||||
hx-indicator="#detail-meta" hx-disabled-elt="this">Finish</button>
|
||||
<button type="button" onclick="document.getElementById('confirm-finish').hidden = true; document.querySelector('[aria-controls=confirm-finish]').setAttribute('aria-expanded','false')">Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="error-inline" role="status" hidden></p>
|
||||
</div>
|
||||
{{end}}
|
||||
{{end}}
|
||||
|
||||
{{/* series-detail-meta is the meta line, and the answer a Check now or
|
||||
correction press on the detail page swaps into its place: the same marks,
|
||||
re-rendered after the stamp so the pending and corrected markers — and
|
||||
the provenance line beside the number — describe the value they sit
|
||||
next to. */}}
|
||||
{{define "series-detail-meta"}}
|
||||
<div class="detail-meta" id="detail-meta" aria-live="polite">
|
||||
<span>ch {{.Chapter}}</span>
|
||||
{{if .Provenance}}<span>{{.Provenance}}</span>{{end}}
|
||||
<span>checked {{.Checked}}</span>
|
||||
<span>{{.Readers}} reader{{if ne .Readers 1}}s{{end}}</span>
|
||||
{{if .Corrected}}<span class="mark">{{.Corrected}}</span>{{end}}
|
||||
{{if .Pending}}<span class="mark">{{.Requested}}</span>{{end}}
|
||||
{{if .FinishedSince}}<span class="mark">{{.FinishedSince}}</span>{{end}}
|
||||
{{if .Unpollable}}<span class="mark">unpollable</span>{{end}}
|
||||
{{if .NoCover}}<span class="mark">no cover</span>{{end}}
|
||||
{{if .Orphan}}<span class="mark">orphan</span>{{end}}
|
||||
{{if .SightingRaised}}<span class="mark">sighting-raised</span>{{end}}
|
||||
</div>
|
||||
{{end}}
|
||||
@@ -1,81 +0,0 @@
|
||||
{{/* The Series list: every Series across every Reader's library, filtered by
|
||||
one hygiene rule and narrowed by Site and Library. Filter, Site, Library
|
||||
and page all live in the query string, so the list's state is an address
|
||||
that can be bookmarked: the two selects submit the GET form, and the
|
||||
Library segment links and the pager preserve the filter and Site. */}}
|
||||
{{define "series-list"}}
|
||||
<form class="filterbar" id="filterbar" method="get" action="/admin/series">
|
||||
<input type="hidden" name="kind" value="{{.Kind}}">
|
||||
<label class="fsel"><span>Filter</span><select name="filter" onchange="this.form.submit()" aria-label="Filter series — changes apply immediately">
|
||||
{{range .Filters}}<option value="{{.Name}}"{{if .Selected}} selected{{end}}>{{.Label}} ({{.Count}})</option>{{end}}
|
||||
</select></label>
|
||||
<label class="fsel"><span>Site</span><select name="site" onchange="this.form.submit()" aria-label="Filter by site — changes apply immediately">
|
||||
<option value=""{{if not .Site}} selected{{end}}>All sites</option>
|
||||
{{range .Sites}}<option value="{{.}}"{{if eq $.Site .}} selected{{end}}>{{.}}</option>{{end}}
|
||||
</select></label>
|
||||
<noscript><button type="submit" class="ghost">Apply</button></noscript>
|
||||
<span class="segrow">
|
||||
<a href="{{.KindBoth}}"{{if not .Kind}} class="active"{{end}}>both</a>
|
||||
<a href="{{.KindManga}}"{{if eq .Kind "manga"}} class="active"{{end}}>manga</a>
|
||||
<a href="{{.KindNovel}}"{{if eq .Kind "novel"}} class="active"{{end}}>novels</a>
|
||||
</span>
|
||||
</form>
|
||||
{{template "series-list-head" .}}
|
||||
{{if .Rows}}
|
||||
<div class="tbl series">
|
||||
<div class="thead"><span>Site</span><span class="c-ch">Ch</span><span>Checked</span><span class="c-rd">Readers</span><span>Notes</span><span></span></div>
|
||||
{{range .Rows}}{{template "series-row" .}}{{end}}
|
||||
</div>
|
||||
<div class="pager">
|
||||
{{if .PrevHref}}<a class="pg" href="{{.PrevHref}}">‹ prev</a>{{else}}<span class="pg disabled">‹ prev</span>{{end}}
|
||||
<span>{{.Range}}</span>
|
||||
{{if .NextHref}}<a class="pg" href="{{.NextHref}}">next ›</a>{{else}}<span class="pg disabled">next ›</span>{{end}}
|
||||
</div>
|
||||
{{else}}
|
||||
<div class="empty"><strong>No series</strong><p>Nothing matches <em>{{.FilterLabel}}</em>.</p></div>
|
||||
{{end}}
|
||||
{{end}}
|
||||
|
||||
{{/* series-row is one Series list row, and the answer a Check now press swaps
|
||||
into the row's place (hx-target="closest .trow"): it must render the
|
||||
pending marker the press created. The control is absent on a Series with
|
||||
no page to fetch and on an orphan, so the owner is never offered a button
|
||||
that can never do anything. */}}
|
||||
{{define "series-row"}}
|
||||
<div class="trow{{if .Attention}} attention{{end}}{{if .Band}} band{{end}}" id="row-{{.Key}}">
|
||||
<span class="c-title"><a href="/admin/series/{{.Key}}">{{.Title}}</a>{{if .Pending}}<span class="mark">{{.Requested}}</span>{{end}}</span>
|
||||
<span class="c-site site-{{.Site}}">{{.Site}}</span>
|
||||
{{/* data-label is the column word for the phone layout, which drops the
|
||||
thead: "1200.25 3d 4" says nothing without it. */}}
|
||||
<span class="c-ch" data-label="ch">{{.Ch}}</span>
|
||||
<span data-label="checked">{{.Age}}</span>
|
||||
<span class="c-rd" data-label="readers">{{.Readers}}</span>
|
||||
<span class="c-note">{{if .Failure}}<span class="mark">{{.Failure}}</span>{{end}}{{range .Notes}}<span class="mark">{{.}}</span>{{end}}{{if .More}}<span class="mark mark-faint">+{{.More}}</span>{{end}}{{if .Finished}}<span class="mark mark-faint">finished</span>{{end}}</span>
|
||||
<span class="c-act">{{if .CanPoll}}<button type="button" class="ghost"
|
||||
hx-post="/admin/series/{{.Key}}/poll" hx-target="closest .trow" hx-swap="outerHTML"
|
||||
hx-indicator="closest .trow" hx-disabled-elt="this"
|
||||
hx-vals='{"band":{{if .Band}}1{{else}}0{{end}}}'>Check now</button>{{end}}{{if .CanRemove}}<button type="button" class="ghost danger"
|
||||
aria-expanded="false" aria-controls="confirm-remove-{{.Key}}"
|
||||
onclick="document.getElementById('confirm-remove-{{.Key}}').hidden = false; this.setAttribute('aria-expanded','true')">Remove</button>{{end}}</span>
|
||||
{{if .RemovalRefused}}<span class="row-msg">a Reader has bookmarked this Series again</span>{{end}}
|
||||
{{if .CanRemove}}<div class="confirm-row" id="confirm-remove-{{.Key}}" role="group" aria-live="polite" hidden>
|
||||
<span>Remove “{{.Title}}”? Progress is lost.</span>
|
||||
<div>
|
||||
<button type="button" class="danger-solid"
|
||||
hx-post="/admin/series/{{.Key}}/remove" hx-target="closest .trow" hx-swap="outerHTML"
|
||||
hx-include="#filterbar" hx-vals='{"band":{{if .Band}}1{{else}}0{{end}}}'
|
||||
hx-indicator="closest .trow" hx-disabled-elt="this">Remove</button>
|
||||
<button type="button" onclick="document.getElementById('confirm-remove-{{.Key}}').hidden = true; document.querySelector('#row-{{.Key}} .c-act .danger').setAttribute('aria-expanded','false')">Cancel</button>
|
||||
</div>
|
||||
</div>{{end}}
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
{{/* series-list-head is the list's heading — the count and the label are one
|
||||
fact. The removal answer renders it out of band (the OOB flag, like the
|
||||
chrome partials) so the heading never lies past the row that made it,
|
||||
and inline here it is the page's own heading. The id is the OOB swap's
|
||||
hook; hx-swap-oob sits on the element the answer carries. */}}
|
||||
{{define "series-list-head"}}
|
||||
<div class="listhead" id="series-listhead"{{if .OOB}} hx-swap-oob="true"{{end}}>{{.Total}} series <span class="lbl">· <em>{{.FilterLabel}}</em></span></div>
|
||||
{{end}}
|
||||
+30
-84
@@ -3,7 +3,6 @@ package web
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io/fs"
|
||||
"log"
|
||||
@@ -30,14 +29,6 @@ var staticFS embed.FS
|
||||
// RecentCount is how many series the "Continue reading" strip shows.
|
||||
const RecentCount = 5
|
||||
|
||||
// maxChapterNum bounds a chapter number a Reader or the owner types. The
|
||||
// number reaches the store as a float64, so without a ceiling a hand-rolled
|
||||
// POST stores 1e308 and every later reader of that row — the poller's
|
||||
// HasNewChapter comparison, the display string — inherits it. Matches the
|
||||
// `max` on the card's chapter input; no real series is within three orders of
|
||||
// magnitude of it.
|
||||
const maxChapterNum = 9999
|
||||
|
||||
// Handler serves the browser UI: full pages at / and htmx fragments at /ui/.
|
||||
// It is a separate handler from api.Handler because the two speak different
|
||||
// representations (HTML versus JSON) to different clients under different auth.
|
||||
@@ -59,14 +50,9 @@ type Handler struct {
|
||||
// httpClient is the plain stdlib client that talks to Discord. It is not
|
||||
// an injected interface: tests point APIBase at a stub server instead.
|
||||
httpClient *http.Client
|
||||
// pollerEnabled reports whether latest-chapter polling is switched on in
|
||||
// this deployment (LATEST_CHAPTER_POLL_ENABLED) and browserConfigured
|
||||
// whether a browser sidecar is configured (BROWSER_WS_URL set). Both are
|
||||
// deployment facts resolved by the composition root; the Lanes page (issue
|
||||
// #145) reports them from config and derives reachability from the pass
|
||||
// log rather than from whether a poller goroutine happened to start.
|
||||
pollerEnabled bool
|
||||
browserConfigured bool
|
||||
// lanes is the Poll Lane snapshot source the administrative page reads.
|
||||
// Nil is a running deployment with no poller, not a bug.
|
||||
lanes LaneReporter
|
||||
}
|
||||
|
||||
// listView is what every list-rendering template receives.
|
||||
@@ -119,17 +105,14 @@ func (v listView) ListURL(tab string) string {
|
||||
// loginView is what the login template receives.
|
||||
type loginView struct {
|
||||
Error string
|
||||
GuildName string
|
||||
}
|
||||
|
||||
// New parses every template up front so a broken one kills the process at
|
||||
// startup rather than the first request that touches it.
|
||||
//
|
||||
// pollerEnabled and browserConfigured are deployment facts the composition
|
||||
// root resolves from LATEST_CHAPTER_POLL_ENABLED and BROWSER_WS_URL: the Lanes
|
||||
// page (issue #145) reports them and derives browser reachability from the
|
||||
// pass log, so no running poller is wired through here at all.
|
||||
func New(s *store.Store, discord DiscordConfig, tokenKey []byte, mangaPath, novelPath string, pollerEnabled, browserConfigured bool) (*Handler, error) {
|
||||
// lanes is the administrative page's window onto the running Poller; nil means
|
||||
// nothing is polling, which the page reports rather than hides.
|
||||
func New(s *store.Store, discord DiscordConfig, tokenKey []byte, mangaPath, novelPath string, lanes LaneReporter) (*Handler, error) {
|
||||
tmpl, err := template.ParseFS(templateFS, "templates/*.html")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -144,8 +127,7 @@ func New(s *store.Store, discord DiscordConfig, tokenKey []byte, mangaPath, nove
|
||||
states: newOAuthStates(),
|
||||
limiter: session.NewLoginLimiter(),
|
||||
httpClient: &http.Client{Timeout: discordTimeout},
|
||||
pollerEnabled: pollerEnabled,
|
||||
browserConfigured: browserConfigured,
|
||||
lanes: lanes,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -253,7 +235,7 @@ func (h *Handler) render(w http.ResponseWriter, status int, name string, data an
|
||||
func (h *Handler) index(w http.ResponseWriter, r *http.Request) {
|
||||
readerID, ok := h.sessionReader(r)
|
||||
if !ok {
|
||||
h.render(w, http.StatusOK, "login", loginView{GuildName: h.discord.GuildName})
|
||||
h.render(w, http.StatusOK, "login", loginView{})
|
||||
return
|
||||
}
|
||||
view, err := h.buildListView(readerID, libOf(r.URL.Query().Get("lib")), r.URL.Query().Get("tab"))
|
||||
@@ -303,11 +285,10 @@ func libOf(q string) string {
|
||||
// buildListView loads one reader's list once and derives both the tab-filtered
|
||||
// items and the recent strip from it.
|
||||
//
|
||||
// Archived series appear in their own tab and nowhere else — not in All, not
|
||||
// in Updated, not in Favourites, and not in the recent strip. An archived
|
||||
// favourite therefore shows only under Archived: Favourites means "favourites
|
||||
// I am currently reading". There is no Finished tab: finished is a fact about
|
||||
// the Series, not a bookmark bucket (issue #157).
|
||||
// Archived and finished series appear in their own tab and nowhere else — not
|
||||
// in All, not in Updated, not in Favourites, and not in the recent strip. An
|
||||
// archived favourite therefore shows only under Archived: Favourites means
|
||||
// "favourites I am currently reading".
|
||||
func (h *Handler) buildListView(readerID int64, lib, tab string) (listView, error) {
|
||||
all, err := h.store.List(readerID) // already ordered updated_at DESC
|
||||
if err != nil {
|
||||
@@ -338,6 +319,8 @@ func (h *Handler) buildListView(readerID int64, lib, tab string) (listView, erro
|
||||
items = withNew
|
||||
case "archived":
|
||||
items = filterBookmarks(all, func(b store.Bookmark) bool { return b.Status == store.StatusArchived })
|
||||
case "finished":
|
||||
items = filterBookmarks(all, func(b store.Bookmark) bool { return b.Status == store.StatusFinished })
|
||||
default:
|
||||
tab = "all"
|
||||
items = reading
|
||||
@@ -401,7 +384,7 @@ func currentLib(r *http.Request) string {
|
||||
// writeChromeOOB appends the regions that live outside #list — the recent
|
||||
// strip, the Updated badge and the action key — as out-of-band swaps, so a
|
||||
// mutation cannot leave them describing the library as it was before the tap.
|
||||
// The key is in here because it is tab-shaped too: the archived bucket swaps
|
||||
// The key is in here because it is tab-shaped too: archived and finished swap
|
||||
// Archive for Restore.
|
||||
func (h *Handler) writeChromeOOB(w http.ResponseWriter, view listView) {
|
||||
view.OOB = true
|
||||
@@ -428,20 +411,12 @@ func (h *Handler) refreshChrome(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
h.writeChromeOOB(w, view)
|
||||
}
|
||||
// writeAnnounceOOB appends a visually-hidden live region update out-of-band,
|
||||
// so a successful mutation announces itself without moving focus.
|
||||
func (h *Handler) writeAnnounceOOB(w http.ResponseWriter, msg string) {
|
||||
fmt.Fprintf(w, `<div id="sr-announce" class="sr-only" role="status" aria-live="polite" aria-atomic="true" hx-swap-oob="true">%s</div>`, template.HTMLEscapeString(msg))
|
||||
}
|
||||
func (h *Handler) writeNoticeOOB(w http.ResponseWriter, msg string) {
|
||||
fmt.Fprintf(w, `<p id="notice" class="notice" hx-swap-oob="true">%s</p>`, template.HTMLEscapeString(msg))
|
||||
}
|
||||
|
||||
// renderLogin renders the login page with an error message, for refused or
|
||||
// failed sign-ins. Every message is author-written text — nothing Discord
|
||||
// supplied is ever interpolated into a page.
|
||||
func (h *Handler) renderLogin(w http.ResponseWriter, status int, msg string) {
|
||||
h.render(w, status, "login", loginView{Error: msg, GuildName: h.discord.GuildName})
|
||||
h.render(w, status, "login", loginView{Error: msg})
|
||||
}
|
||||
|
||||
// logout revokes the session row and clears the cookie in one step: the next
|
||||
@@ -506,19 +481,12 @@ func (h *Handler) uiFavorite(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
b.Favorite = !b.Favorite
|
||||
b.UpdatedAt = time.Now().UnixMilli()
|
||||
msg := ""
|
||||
if b.Favorite {
|
||||
msg = fmt.Sprintf("Added %s to favourites", b.Title)
|
||||
} else {
|
||||
msg = fmt.Sprintf("Removed %s from favourites", b.Title)
|
||||
}
|
||||
h.saveAndRenderCard(w, r, b)
|
||||
h.writeAnnounceOOB(w, msg)
|
||||
}
|
||||
|
||||
// uiStatus moves a bookmark between the two lifecycle buckets. Finished is not
|
||||
// one of them: it is a fact about the Series, decided from the admin surface,
|
||||
// so the web UI's per-bookmark control cannot set it (issue #157).
|
||||
// uiStatus moves a bookmark between lifecycle buckets. This is the only place
|
||||
// a series can be marked finished — the JSON API refuses that value, so the
|
||||
// userscript cannot set it even by accident.
|
||||
//
|
||||
// last_chapter_num is untouched, so Upsert keeps the stored updated_at and the
|
||||
// list does not reorder.
|
||||
@@ -532,21 +500,14 @@ func (h *Handler) uiStatus(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
switch s := r.PostFormValue("status"); s {
|
||||
case store.StatusReading, store.StatusArchived:
|
||||
case store.StatusReading, store.StatusArchived, store.StatusFinished:
|
||||
b.Status = s
|
||||
default:
|
||||
http.Error(w, "invalid status", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
b.UpdatedAt = time.Now().UnixMilli()
|
||||
msg := ""
|
||||
if b.Status == store.StatusArchived {
|
||||
msg = fmt.Sprintf("Archived %s", b.Title)
|
||||
} else {
|
||||
msg = fmt.Sprintf("Restored %s", b.Title)
|
||||
}
|
||||
h.saveAndRenderCard(w, r, b)
|
||||
h.writeAnnounceOOB(w, msg)
|
||||
}
|
||||
|
||||
// uiChapter forces the read chapter to a value the user typed.
|
||||
@@ -571,8 +532,8 @@ func (h *Handler) uiChapter(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
raw := strings.TrimSpace(r.PostFormValue("chapter"))
|
||||
num, err := strconv.ParseFloat(raw, 64)
|
||||
if err != nil || num < 0 || num > maxChapterNum || math.IsNaN(num) || math.IsInf(num, 0) {
|
||||
http.Error(w, "chapter must be a non-negative number below 10000", http.StatusBadRequest)
|
||||
if err != nil || num < 0 || math.IsNaN(num) || math.IsInf(num, 0) {
|
||||
http.Error(w, "chapter must be a non-negative number", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -582,42 +543,27 @@ func (h *Handler) uiChapter(w http.ResponseWriter, r *http.Request) {
|
||||
b.LastChapterNum = num
|
||||
}
|
||||
b.UpdatedAt = time.Now().UnixMilli()
|
||||
msg := fmt.Sprintf("Updated %s to chapter %s", b.Title, raw)
|
||||
h.saveAndRenderCard(w, r, b)
|
||||
h.writeAnnounceOOB(w, msg)
|
||||
}
|
||||
|
||||
// uiDelete removes the row and answers with an empty body, which htmx swaps in
|
||||
// place of the card — removing it from the page.
|
||||
func (h *Handler) uiDelete(w http.ResponseWriter, r *http.Request) {
|
||||
b, ok := h.loadForMutation(w, r)
|
||||
if !ok {
|
||||
key := r.PathValue("key")
|
||||
if key == "" {
|
||||
http.Error(w, "missing key", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := h.store.Delete(readerOf(r), b.Key); err != nil {
|
||||
log.Printf("ui delete %q: %v", b.Key, err)
|
||||
if err := h.store.Delete(readerOf(r), key); err != nil {
|
||||
log.Printf("ui delete %q: %v", key, err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
msg := fmt.Sprintf("Removed %s", b.Title)
|
||||
h.writeAnnounceOOB(w, msg)
|
||||
h.writeNoticeOOB(w, msg)
|
||||
view, err := h.buildListView(readerOf(r), currentLib(r), currentTab(r))
|
||||
if err != nil {
|
||||
log.Printf("ui chrome: %v", err)
|
||||
return
|
||||
}
|
||||
h.writeChromeOOB(w, view)
|
||||
if len(view.Items) == 0 {
|
||||
fmt.Fprint(w, `<main id="list" class="list" tabindex="-1" hx-swap-oob="true">`)
|
||||
if err := h.tmpl.ExecuteTemplate(w, "list", view); err != nil {
|
||||
log.Printf("render list oob: %v", err)
|
||||
return
|
||||
}
|
||||
fmt.Fprint(w, `</main>`)
|
||||
}
|
||||
// The empty body is what removes the card; the chrome still has to be told
|
||||
// the library got smaller.
|
||||
h.refreshChrome(w, r)
|
||||
}
|
||||
|
||||
// installUserscript renders the bindmounted script with the acting Reader's
|
||||
|
||||
+17
-50
@@ -14,7 +14,6 @@ import (
|
||||
"bookmarkmanager/backend/internal/api"
|
||||
"bookmarkmanager/backend/internal/httpmw"
|
||||
"bookmarkmanager/backend/internal/latest"
|
||||
"bookmarkmanager/backend/internal/notify"
|
||||
"bookmarkmanager/backend/internal/store"
|
||||
"bookmarkmanager/backend/internal/token"
|
||||
"bookmarkmanager/backend/internal/userscript"
|
||||
@@ -55,17 +54,6 @@ type Config struct {
|
||||
// /u/{token}/novel-bookmark.user.js. Same bindmount, second script: the
|
||||
// two libraries are separate installs.
|
||||
NovelUserscriptPath string
|
||||
// BrowserWSURL is the CDP websocket the poller's browser Sites read
|
||||
// through. Set means a browser sidecar is configured in this deployment —
|
||||
// the Lanes page reports the fact and derives reachability from the pass
|
||||
// log rather than asking the poller (issue #145).
|
||||
BrowserWSURL string
|
||||
// DiscordWebhookURL is the webhook owner notices post to (issue #171).
|
||||
// Unset means the whole path is off — a local stack needs no webhook,
|
||||
// exactly as the browser URL behaves. The address is a secret in the
|
||||
// class of TOKEN_KEY: never logged, and it must not reach any line that
|
||||
// prints configuration.
|
||||
DiscordWebhookURL string
|
||||
// LatestPoll configures the background latest-chapter fetcher.
|
||||
LatestPoll LatestPoll
|
||||
}
|
||||
@@ -120,15 +108,12 @@ func loadConfig() Config {
|
||||
OwnerDiscordID: os.Getenv("OWNER_DISCORD_ID"),
|
||||
UserscriptPath: envOr("USERSCRIPT_PATH", "/userscript/manga-bookmark.user.js"),
|
||||
NovelUserscriptPath: envOr("NOVEL_USERSCRIPT_PATH", "/userscript/novel-bookmark.user.js"),
|
||||
BrowserWSURL: os.Getenv("BROWSER_WS_URL"),
|
||||
DiscordWebhookURL: os.Getenv("DISCORD_WEBHOOK_URL"),
|
||||
LatestPoll: loadLatestPoll(),
|
||||
}
|
||||
c.Discord = web.DiscordConfig{
|
||||
ClientID: os.Getenv("DISCORD_CLIENT_ID"),
|
||||
ClientSecret: os.Getenv("DISCORD_CLIENT_SECRET"),
|
||||
GuildID: os.Getenv("DISCORD_GUILD_ID"),
|
||||
GuildName: os.Getenv("DISCORD_GUILD_NAME"),
|
||||
RequiredRole: os.Getenv("DISCORD_REQUIRED_ROLE"),
|
||||
APIBase: envOr("DISCORD_API_BASE", "https://discord.com/api/v10"),
|
||||
RedirectURI: os.Getenv("DISCORD_REDIRECT_URI"),
|
||||
@@ -145,10 +130,9 @@ func loadConfig() Config {
|
||||
// preflight OPTIONS short-circuits before auth; /bookmarks* is auth-protected,
|
||||
// /healthz is public.
|
||||
//
|
||||
// The web layer learns the deployment's poller and browser config from cfg —
|
||||
// nothing of the running poller is wired through here; the Lanes page reads
|
||||
// the database (issue #145).
|
||||
func newRouter(s *store.Store, cfg Config) http.Handler {
|
||||
// lanes may be nil — polling disabled, or its client could not be built. The
|
||||
// admin page reports that rather than pretending Lanes exist.
|
||||
func newRouter(s *store.Store, cfg Config, lanes web.LaneReporter) http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
h := &api.Handler{Store: s}
|
||||
mux.HandleFunc("GET /healthz", api.Healthz)
|
||||
@@ -177,12 +161,9 @@ func newRouter(s *store.Store, cfg Config) http.Handler {
|
||||
mux.Handle("/bookmarks/", auth)
|
||||
|
||||
// The browser UI is always registered; signing in is Discord OAuth, so
|
||||
// there is no password to forget and no gate to leave unset. The poller
|
||||
// and browser facts are config, not the poller's: the Lanes page reads
|
||||
// the pass log and reports the deployment as configured.
|
||||
// there is no password to forget and no gate to leave unset.
|
||||
wh, err := web.New(s, cfg.Discord, []byte(cfg.TokenKey),
|
||||
cfg.UserscriptPath, cfg.NovelUserscriptPath,
|
||||
cfg.LatestPoll.Enabled, strings.TrimSpace(cfg.BrowserWSURL) != "")
|
||||
cfg.UserscriptPath, cfg.NovelUserscriptPath, lanes)
|
||||
if err != nil {
|
||||
log.Fatalf("web handler: %v", err)
|
||||
}
|
||||
@@ -260,7 +241,7 @@ func main() {
|
||||
var browser latest.Fetcher
|
||||
pollCtx, stopPoll := context.WithCancel(context.Background())
|
||||
defer stopPoll()
|
||||
if ws := strings.TrimSpace(cfg.BrowserWSURL); ws != "" {
|
||||
if ws := strings.TrimSpace(os.Getenv("BROWSER_WS_URL")); ws != "" {
|
||||
bf, err := latest.NewBrowserFetcher(ws)
|
||||
if err != nil {
|
||||
log.Printf("browser fetcher disabled: %v", err)
|
||||
@@ -297,26 +278,17 @@ func main() {
|
||||
}
|
||||
s.OnSeriesCreated = acq.Acquire
|
||||
}
|
||||
// Owner notices (issue #171): a configured webhook makes the poller tell
|
||||
// the owner about stalled Lanes. Unset means the whole path is off — a
|
||||
// local stack needs no webhook, exactly as the browser URL behaves. Only
|
||||
// the presence is logged; the address itself is a secret in the class of
|
||||
// TOKEN_KEY.
|
||||
var notifier latest.Notifier
|
||||
if u := strings.TrimSpace(cfg.DiscordWebhookURL); u != "" {
|
||||
notifier = notify.New(u, cfg.PublicBaseURL)
|
||||
log.Println("owner notices: enabled")
|
||||
} else {
|
||||
log.Println("owner notices: disabled (DISCORD_WEBHOOK_URL unset)")
|
||||
// A nil *Poller must not become a non-nil interface holding a nil pointer:
|
||||
// the admin page tests the reporter for nil to decide whether anything is
|
||||
// polling at all.
|
||||
var lanes web.LaneReporter
|
||||
if poller := startLatestPoller(pollCtx, s, cfg.LatestPoll, browser); poller != nil {
|
||||
lanes = poller
|
||||
}
|
||||
// The poller's only connection to the web layer is the database now: it is
|
||||
// started for its own sake, and the Lanes page reads the pass rows it
|
||||
// records (issue #145).
|
||||
startLatestPoller(pollCtx, s, cfg.LatestPoll, browser, notifier)
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: ":" + cfg.Port,
|
||||
Handler: newRouter(s, cfg),
|
||||
Handler: newRouter(s, cfg, lanes),
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
@@ -345,9 +317,7 @@ func main() {
|
||||
|
||||
// newLatestPoller wires the fetcher seams into the poller. Pace is registry
|
||||
// property, not config (issue #100), so there are no knobs to pass through.
|
||||
// notifier is nil when no webhook is configured: a missing webhook is a
|
||||
// silent off switch, not an error (issue #171).
|
||||
func newLatestPoller(s *store.Store, cfg LatestPoll, fetch, browser latest.Fetcher, notifier latest.Notifier) *latest.Poller {
|
||||
func newLatestPoller(s *store.Store, cfg LatestPoll, fetch, browser latest.Fetcher) *latest.Poller {
|
||||
var covers latest.BrowserCoverFetcher
|
||||
if f, ok := browser.(latest.BrowserCoverFetcher); ok {
|
||||
covers = f
|
||||
@@ -358,7 +328,6 @@ func newLatestPoller(s *store.Store, cfg LatestPoll, fetch, browser latest.Fetch
|
||||
BrowserFetch: browser,
|
||||
CoverFetch: covers,
|
||||
CoverBytesFetch: latest.NewCoverFetcher(),
|
||||
Notify: notifier,
|
||||
Now: time.Now,
|
||||
}
|
||||
}
|
||||
@@ -367,10 +336,8 @@ func newLatestPoller(s *store.Store, cfg LatestPoll, fetch, browser latest.Fetch
|
||||
// HTTP client cannot be built. Any problem here is logged and skipped: this
|
||||
// feature going missing degrades the service to userscript-only latest-chapter
|
||||
// tracking, which is exactly how it behaved before. It returns the running
|
||||
// Poller, or nil when there is none; the caller starts it for its own sake —
|
||||
// the Lanes page reads the pass log, so no return value is wired anywhere.
|
||||
// notifier is nil when DISCORD_WEBHOOK_URL is unset (issue #171).
|
||||
func startLatestPoller(ctx context.Context, s *store.Store, cfg LatestPoll, browser latest.Fetcher, notifier latest.Notifier) *latest.Poller {
|
||||
// Poller, or nil when there is none — the admin page's Lane status reads it.
|
||||
func startLatestPoller(ctx context.Context, s *store.Store, cfg LatestPoll, browser latest.Fetcher) *latest.Poller {
|
||||
if !cfg.Enabled {
|
||||
log.Println("latest-chapter poller: disabled by config")
|
||||
return nil
|
||||
@@ -383,7 +350,7 @@ func startLatestPoller(ctx context.Context, s *store.Store, cfg LatestPoll, brow
|
||||
// Nil browser: sites behind a JavaScript challenge are simply not polled,
|
||||
// and their latest_chapter comes from the userscript alone — which is how
|
||||
// the service behaved before the sidecar existed.
|
||||
p := newLatestPoller(s, cfg, f, browser, notifier)
|
||||
p := newLatestPoller(s, cfg, f, browser)
|
||||
|
||||
go p.Run(ctx)
|
||||
return p
|
||||
|
||||
+2
-24
@@ -28,20 +28,6 @@ func TestLoadConfigReadsCoverDirectory(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadConfigReadsDiscordWebhook(t *testing.T) {
|
||||
// The address is read, never defaulted: unset stays empty (the whole
|
||||
// path is off), set flows into the Config for the poller's notifier.
|
||||
const url = "https://discord.com/api/webhooks/000000/secret"
|
||||
t.Setenv("DISCORD_WEBHOOK_URL", url)
|
||||
if got := loadConfig().DiscordWebhookURL; got != url {
|
||||
t.Fatalf("DiscordWebhookURL = %q, want %q", got, url)
|
||||
}
|
||||
t.Setenv("DISCORD_WEBHOOK_URL", "")
|
||||
if got := loadConfig().DiscordWebhookURL; got != "" {
|
||||
t.Fatalf("DiscordWebhookURL = %q, want empty when unset", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadLatestPollEnabledParsing(t *testing.T) {
|
||||
tests := []struct {
|
||||
raw string
|
||||
@@ -65,8 +51,7 @@ func TestLoadLatestPollEnabledParsing(t *testing.T) {
|
||||
// nothing here sizes a cooldown any more.
|
||||
func TestNewLatestPollerWiresFetchers(t *testing.T) {
|
||||
tls := &latest.TLSFetcher{}
|
||||
notifier := &stubNotifier{}
|
||||
p := newLatestPoller(nil, LatestPoll{Enabled: true}, tls, nil, notifier)
|
||||
p := newLatestPoller(nil, LatestPoll{Enabled: true}, tls, nil)
|
||||
if p.Fetch != tls {
|
||||
t.Fatalf("Fetch not wired")
|
||||
}
|
||||
@@ -82,15 +67,8 @@ func TestNewLatestPollerWiresFetchers(t *testing.T) {
|
||||
if p.Now == nil {
|
||||
t.Fatalf("Now = nil, want the live clock")
|
||||
}
|
||||
if p.Notify != notifier {
|
||||
t.Fatalf("Notify = %v, want the configured notifier", p.Notify)
|
||||
}
|
||||
}
|
||||
|
||||
// stubNotifier satisfies latest.Notifier so newLatestPoller's wiring can be
|
||||
// asserted; it is never called.
|
||||
type stubNotifier struct{ latest.Notifier }
|
||||
|
||||
func TestPutStatusValidation(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
@@ -100,7 +78,7 @@ func TestPutStatusValidation(t *testing.T) {
|
||||
{"empty is no opinion", "", http.StatusOK},
|
||||
{"reading", "reading", http.StatusOK},
|
||||
{"archived", "archived", http.StatusOK},
|
||||
{"finished is no longer a bucket", "finished", http.StatusBadRequest},
|
||||
{"finished is web-only", "finished", http.StatusBadRequest},
|
||||
{"garbage", "dropped", http.StatusBadRequest},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
|
||||
@@ -49,7 +49,7 @@ func withBody(req *http.Request, body string) *http.Request {
|
||||
// A refused credential is refused however plausible it looks: only a hash the
|
||||
// readers table holds authenticates anything.
|
||||
func TestUnknownCredentialRejected(t *testing.T) {
|
||||
srv := newRouter(newTestStore(t), testConfig())
|
||||
srv := newRouter(newTestStore(t), testConfig(), nil)
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
srv.ServeHTTP(rr, credRequest(http.MethodGet, "/bookmarks", readerCredential("never-registered")))
|
||||
@@ -69,7 +69,7 @@ func TestUnknownCredentialRejected(t *testing.T) {
|
||||
func TestPerReaderIsolation(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
registerReader(t, s, "other-reader")
|
||||
srv := newRouter(s, testConfig())
|
||||
srv := newRouter(s, testConfig(), nil)
|
||||
|
||||
ownerKey := "asura:solo"
|
||||
putBookmark(t, srv, ownerKey, store.Bookmark{
|
||||
@@ -267,7 +267,7 @@ func TestRotateCredentialViaWebUI(t *testing.T) {
|
||||
}
|
||||
cfg := testConfig()
|
||||
cfg.UserscriptPath = path
|
||||
srv := newRouter(s, cfg)
|
||||
srv := newRouter(s, cfg, nil)
|
||||
|
||||
oldCred := ownerCredential()
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user