Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f532e50516 | |||
| bc64a1d894 | |||
| ba2b6eebbb | |||
| f40894b108 | |||
| a4ea80dcc2 | |||
| a4491babed | |||
| e1d61534bb | |||
| ad09569f2e | |||
| 35a86f5eb9 | |||
| 424d2c6600 | |||
| 7e1cbdde9e | |||
| 448631c78e | |||
| f3b2722568 | |||
| b9fc83217d | |||
| c9b1f2a334 |
@@ -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
|
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
|
disable-model-invocation: true
|
||||||
---
|
---
|
||||||
|
|
||||||
# Implement tickets
|
# Implement tickets
|
||||||
|
|
||||||
You are the **orchestrator**. You dispatch, land results, and talk to the
|
You are the **orchestrator**. You write briefs, dispatch, land results, and talk
|
||||||
tracker. You do not write the implementation — every line of ticket code is
|
to the tracker. You do not write the implementation — every line of ticket code
|
||||||
written by a `ticket-implementer` subagent in its own git worktree. Reach for the
|
is written by a `ticket-implementer` subagent in its own git worktree. Reach for
|
||||||
editor yourself only for a merge conflict resolution.
|
the editor yourself only for a merge conflict resolution.
|
||||||
|
|
||||||
Ticket source and tracker conventions: `docs/agents/issue-tracker.md`. `tea` usage: skill `gitea`.
|
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 user's argument is the selector: issue numbers, a label, a parent issue, or
|
||||||
the base branch, the waves, the contracts, and each ticket's brief path and
|
nothing. With nothing, take the open issues labelled `ready-for-agent`.
|
||||||
status. Run the earliest wave that is not landed.
|
|
||||||
|
|
||||||
The briefs are the requirements and they are already approved: read each one you
|
Fetch each with `tea issue <n> --comments`, and read the **whole** body —
|
||||||
are about to dispatch, but do not rewrite it, and do not fetch the tickets from
|
acceptance criteria and the `Blocked by` line are what the rest of this skill
|
||||||
the tracker to second-guess it. A brief that is wrong or thin is a `plan-tickets`
|
runs on. A ticket whose blockers are still open is out of this batch unless a
|
||||||
problem — say so and stop, rather than patching it here.
|
blocker is also in it.
|
||||||
|
|
||||||
No plan file, or no briefs for the next wave: run `plan-tickets` first. That
|
## 2. Plan the batch
|
||||||
skill owns wave membership, contracts, and every brief.
|
|
||||||
|
|
||||||
## 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:
|
Per ticket, before dispatch:
|
||||||
|
|
||||||
```bash
|
```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
|
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
|
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
|
Then dispatch the whole wave in **one** `task` batch, every item on the
|
||||||
`ticket-implementer` agent. Each dispatch names: the absolute brief path, the
|
`ticket-implementer` agent. Each dispatch names: the absolute brief path, the
|
||||||
worktree path, the branch, the base ref, and the report path
|
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
|
`.scratch/<batch-slug>/t<n>-report.md`.
|
||||||
file.
|
|
||||||
|
|
||||||
## 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
|
The wave is landed when every ticket in it is closed, reverted, or handed back
|
||||||
to the user. Per returned ticket:
|
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.
|
owns the contract, as a re-dispatch with the collision described.
|
||||||
|
|
||||||
Then `tea comment <n> "<the report summary>"`, `tea issue close <n>`, and
|
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
|
`git worktree remove ../ticket-<n>`. Keep the report file.
|
||||||
`landed` or `handed back` in the plan 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
|
## 6. Close the batch
|
||||||
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.
|
|
||||||
|
|
||||||
Last wave landed: run the full suite once on the merged base, and report a line
|
Run the full suite once on the merged base, and report: a line per ticket with
|
||||||
per ticket with its status, commits, and open concerns, plus anything still
|
its status, commits, and open concerns, plus anything still assigned or open on
|
||||||
assigned or open on the tracker. A red suite after every ticket went green is an
|
the tracker. A red suite after every ticket went green is an interaction bug —
|
||||||
interaction bug — diagnose it, name the two tickets, and fix it or hand it back
|
diagnose it, name the two tickets, and fix it or hand it back with both named.
|
||||||
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
|
# The guild whose membership gates sign-in (Developer Mode -> right-click the
|
||||||
# server -> Copy Server ID).
|
# server -> Copy Server ID).
|
||||||
DISCORD_GUILD_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.
|
# Exact callback URL, e.g. https://bookmark.example.com/auth/discord/callback.
|
||||||
# Discord matches it verbatim, so it must equal the registered redirect.
|
# Discord matches it verbatim, so it must equal the registered redirect.
|
||||||
DISCORD_REDIRECT_URI=
|
DISCORD_REDIRECT_URI=
|
||||||
# Optional: a role snowflake members must hold on top of guild membership.
|
# Optional: a role snowflake members must hold on top of guild membership.
|
||||||
# Empty (the default) means membership alone suffices.
|
# Empty (the default) means membership alone suffices.
|
||||||
# DISCORD_REQUIRED_ROLE=
|
# DISCORD_REQUIRED_ROLE=
|
||||||
|
|
||||||
# Subdomain Traefik routes to the browser UI (required by the prod override).
|
# Subdomain Traefik routes to the browser UI (required by the prod override).
|
||||||
# Left commented on purpose: an example value here would be a silent
|
# 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
|
# 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
|
# 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.
|
# stranger's address, and "no browser" is a safe, self-announcing state.
|
||||||
# BROWSER_WS_URL=ws://100.x.y.z:9222
|
# 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
|
# 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
|
# 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
|
# 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
|
## Order of work
|
||||||
|
|
||||||
1. Read the brief file. It is the only statement of requirements you get — use
|
1. Read the brief file. It is the single source of requirements — use its exact
|
||||||
its exact values verbatim, and read nothing from the tracker. The
|
values verbatim.
|
||||||
orchestrator has already read the ticket, its comments and its parent spec,
|
2. Read the ticket and the issue it refers to, as the brief's **Read first**
|
||||||
and folded every live decision into the brief; the threads themselves also
|
section names them: `tea issue <n> --comments` for each. The ticket's
|
||||||
hold reversed and rejected ones you cannot tell apart from here.
|
comments and its parent carry the intent and the decisions behind the brief.
|
||||||
2. Read `AGENTS.md` in the worktree, plus the nested `AGENTS.md` for the area
|
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
|
you touch. Its invariants bind you: security rules, design system, comment
|
||||||
policy.
|
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.
|
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.
|
run the `tdd` skill and follow its red → green loop.
|
||||||
Follow the patterns already in the codebase; improve what you touch,
|
Follow the patterns already in the codebase; improve what you touch,
|
||||||
restructure nothing outside the ticket.
|
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.
|
once at the end. Test output must be pristine.
|
||||||
6. Commit to your branch. Reference the ticket number in the subject.
|
7. Commit to your branch. Reference the ticket number in the subject.
|
||||||
7. Review (below), fix, re-verify, commit the fixes.
|
8. Review (below), fix, re-verify, commit the fixes.
|
||||||
8. Write the report file, then return the status contract.
|
9. Write the report file, then return the status contract.
|
||||||
|
|
||||||
## Review
|
## Review
|
||||||
|
|
||||||
After your first green commit, run the **`code-review`** skill over
|
After your first green commit, run the **`code-review`** skill over
|
||||||
`<base ref>...HEAD` in the worktree, with two changes to how it dispatches:
|
`<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
|
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
|
Standards axis, both in one batch, and give the Spec axis your brief file plus
|
||||||
spec plus the ticket number from the brief's title, telling it to read the
|
the ticket body as the spec.
|
||||||
ticket itself (`tea issue <n> --comments`). The tracker check belongs in that
|
|
||||||
read-only context, not in yours.
|
|
||||||
|
|
||||||
Fix every Critical and Important finding, then re-run the tests that cover the
|
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
|
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).
|
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):
|
Live CDP proof (needs that browser and network, skipped otherwise):
|
||||||
`SMOKE_BROWSER_WS_URL=ws://<ip>:<port> go test -run 'TestSmokeKagane|TestSmokeComix' ./internal/latest`
|
`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
|
— fetches a real kagane and comix cover and chapter list. A red run means the challenge is
|
||||||
|
|||||||
+3
-15
@@ -95,7 +95,7 @@ _Avoid_: run, cycle, tick, batch, poll history
|
|||||||
**Forced Poll**:
|
**Forced Poll**:
|
||||||
A Poll the owner asks for by hand instead of waiting for the Series's turn. It jumps its
|
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
|
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
|
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
|
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.
|
next pass rather than at the moment of asking.
|
||||||
@@ -149,22 +149,10 @@ accent is permitted to signal.
|
|||||||
_Avoid_: unread, update available
|
_Avoid_: unread, update available
|
||||||
|
|
||||||
**Lifecycle bucket**:
|
**Lifecycle bucket**:
|
||||||
Which of the two states a Bookmark sits in — reading or archived. A Bookmark is in exactly
|
Which of three mutually exclusive states a Bookmark sits in — reading, archived, or
|
||||||
one. Orthogonal to being a favourite. Finished is not a bucket: it is a fact about the
|
finished. A Bookmark is in exactly one. Orthogonal to being a favourite.
|
||||||
Series (see `series.finished_at`), owned by the owner and stamped once, and every Bookmark
|
|
||||||
on a finished Series is archived.
|
|
||||||
_Avoid_: state, status (as a domain word), list
|
_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**:
|
**Favourite**:
|
||||||
A reader's manual pin on a Bookmark. Orthogonal to the Lifecycle bucket, and never a
|
A reader's manual pin on a Bookmark. Orthogonal to the Lifecycle bucket, and never a
|
||||||
reason to reorder the list.
|
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
|
DISCORD_REDIRECT_URI=https://bookmark.violetcrown.my.id/auth/discord/callback
|
||||||
# Optional: only members holding this role may sign in.
|
# Optional: only members holding this role may sign in.
|
||||||
# DISCORD_REQUIRED_ROLE=<role snowflake>
|
# 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
|
The guild id is in Discord's client with Developer Mode on: right-click the
|
||||||
|
|||||||
+5
-5
@@ -8,7 +8,7 @@ web
|
|||||||
|
|
||||||
## Users
|
## 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.
|
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
|
## Capabilities and Constraints
|
||||||
|
|
||||||
- Two libraries (manga, novels) with lifecycle tabs: All / Updated / Favourites / Archived. Search-filter by title (client-side, `filter.js`).
|
- 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, remove — each move out of the list confirm-gated.
|
- 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.
|
- "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.
|
- 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.
|
- 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.
|
- 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.
|
- 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.
|
- 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.
|
- 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.
|
- 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.
|
- 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
|
## 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_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_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_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_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_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. |
|
| `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
|
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
|
does not touch read progress, and reading an archived series leaves it
|
||||||
archived.
|
archived.
|
||||||
- **Finished**: the owner marks a Series finished from its detail page; the
|
- **Finished**: series you have completed live in a **Finished** tab in the web
|
||||||
backend stops polling it, and every Reader sees a read-only label. It is a
|
UI only. It is set there and nowhere else — the API rejects the value — and
|
||||||
fact about the Series, not a Reader's bucket: old `Finished` bookmarks were
|
finished series are hidden from every userscript tab and are no longer polled
|
||||||
folded into Archived in the cutover, so there is no Finished tab.
|
for new chapters.
|
||||||
- Bookmarks made on Asura appear when the panel is opened on Demonic, and vice
|
- Bookmarks made on Asura appear when the panel is opened on Demonic, and vice
|
||||||
versa — the backend is the shared store.
|
versa — the backend is the shared store.
|
||||||
|
|
||||||
|
|||||||
+5
-18
@@ -159,15 +159,6 @@ failures. The flag decays and they probe again.
|
|||||||
- Browser Lanes wake Chrome only when 5+ Series are due or one has waited 15m,
|
- 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.
|
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`
|
### Covers — `Store.OnSeriesCreated`, `latest.Acquirer`, `latest.CoverBytesFetcher`, `Store.SetSeriesCover`
|
||||||
|
|
||||||
Acquired once when the first Bookmark of a Series is created, then served from
|
Acquired once when the first Bookmark of a Series is created, then served from
|
||||||
@@ -209,16 +200,12 @@ stored** and clients must adopt that response rather than their own payload.
|
|||||||
|
|
||||||
### Lifecycle buckets — `status` on each bookmark
|
### Lifecycle buckets — `status` on each bookmark
|
||||||
|
|
||||||
`reading` | `archived`, orthogonal to `favorite`. Archived rows appear only
|
`reading` | `archived` | `finished`, orthogonal to `favorite`. Archived and
|
||||||
in their own tab, never in All, Updated, Favourites or the recent strip. The
|
finished appear only in their own tab, never in All, Updated, Favourites or the
|
||||||
poller keeps checking archived series; a finished Series (issue #157) is a
|
recent strip. The poller keeps checking archived series and skips finished ones.
|
||||||
`series.finished_at` fact the Lane gate reads, with every bookmark on it
|
|
||||||
archived.
|
|
||||||
|
|
||||||
- `PUT /bookmarks/{key}` accepts only the two values; anything else —
|
- `finished` is settable only from the web UI; `PUT /bookmarks/{key}` rejects
|
||||||
`finished` included — is a plain 400, and the web UI's own status control
|
it with 400.
|
||||||
validates the same way. The 0016 migration is the only writer of the flag
|
|
||||||
today; the undo is writing 0.
|
|
||||||
- **An empty incoming status means "keep the stored one"**, and it is resolved
|
- **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:
|
on the `VALUES` side of `Store.Upsert`, not in the conflict clause:
|
||||||
`excluded.*` is the post-evaluation row, so a default applied there would
|
`excluded.*` is the post-evaluation row, so a default applied there would
|
||||||
|
|||||||
+1
-48
@@ -2,7 +2,6 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"database/sql"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -299,7 +298,7 @@ func TestFlatWireFieldSet(t *testing.T) {
|
|||||||
"series_url": true, "cover": true, "last_chapter": true,
|
"series_url": true, "cover": true, "last_chapter": true,
|
||||||
"last_chapter_num": true, "last_chapter_url": true, "favorite": true,
|
"last_chapter_num": true, "last_chapter_url": true, "favorite": true,
|
||||||
"latest_chapter": true, "latest_chapter_num": true, "updated_at": 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 {
|
checkFlat := func(t *testing.T, payload []byte) map[string]json.RawMessage {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
@@ -363,52 +362,6 @@ func TestFlatWireFieldSet(t *testing.T) {
|
|||||||
checkFlat(t, body2)
|
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
|
// 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
|
// 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.
|
// values could otherwise land on a shared row — while progress still lands.
|
||||||
|
|||||||
@@ -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.
|
// An empty status is "no opinion" and Upsert keeps the stored bucket.
|
||||||
// Anything else outside the two lifecycle buckets is a client bug, not
|
// Finishing a series is a web-UI decision, so the JSON API refuses it
|
||||||
// something to silently coerce — finished included, which is no longer a
|
// rather than trusting every client to leave it alone.
|
||||||
// bucket at all (issue #157).
|
|
||||||
switch b.Status {
|
switch b.Status {
|
||||||
case "", store.StatusReading, store.StatusArchived:
|
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:
|
default:
|
||||||
http.Error(w, "invalid status", http.StatusBadRequest)
|
http.Error(w, "invalid status", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -145,10 +145,6 @@ func (f *TLSCoverFetcher) Fetch(ctx context.Context, sourceURL string) ([]byte,
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "", fmt.Errorf("build cover request: %w", err)
|
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)
|
resp, err := f.client.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "", fmt.Errorf("fetch cover: %w", err)
|
return nil, "", fmt.Errorf("fetch cover: %w", err)
|
||||||
|
|||||||
@@ -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
|
// 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
|
// what the Site actually answers with; the bytes are stored under the real
|
||||||
// name so one image cannot land under two spellings.
|
// 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))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -46,9 +46,6 @@ type Poller struct {
|
|||||||
// CoverBytesFetch is optional; it handles plain-TLS sources through the
|
// CoverBytesFetch is optional; it handles plain-TLS sources through the
|
||||||
// same failure-isolated prefetch path.
|
// same failure-isolated prefetch path.
|
||||||
CoverBytesFetch CoverBytesFetcher
|
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
|
Now func() time.Time // injected so tests can freeze it
|
||||||
// eligibleCount reports how many of a Site's Series are eligible for
|
// eligibleCount reports how many of a Site's Series are eligible for
|
||||||
// polling, defaulting to Store.EligibleSeriesCount. Injected so tests can
|
// polling, defaulting to Store.EligibleSeriesCount. Injected so tests can
|
||||||
@@ -276,9 +273,7 @@ const (
|
|||||||
// (issue #141). The classification the read already makes is counted, never a
|
// (issue #141). The classification the read already makes is counted, never a
|
||||||
// second taxonomy: refused is the Site holding a challenge, unreachable the
|
// second taxonomy: refused is the Site holding a challenge, unreachable the
|
||||||
// browser interrupting, noChapter a 200 with real HTML but no chapter links,
|
// 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
|
// unfetchable the host pin or a missing fetcher, and errors everything else.
|
||||||
// the 403 refusal — the Site answered with a client status — and errors
|
|
||||||
// everything else.
|
|
||||||
type readOutcome int
|
type readOutcome int
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -288,33 +283,14 @@ const (
|
|||||||
outcomeNoChapter
|
outcomeNoChapter
|
||||||
outcomeUnfetchable
|
outcomeUnfetchable
|
||||||
outcomeError
|
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
|
// outcomeCounts are the five named outcome counts of one pass. A success
|
||||||
// count is derived, never stored: checked minus the five named failures,
|
// count is derived, never stored: checked minus the four, with unreachable
|
||||||
// with unreachable excluded because the sidecar-loss path returns before the
|
// excluded because the sidecar-loss path returns before the checked counter
|
||||||
// checked counter increments (issue #141).
|
// increments (issue #141).
|
||||||
type outcomeCounts struct {
|
type outcomeCounts struct {
|
||||||
refused, unreachable, noChapter, unfetchable, errors, notFound int
|
refused, unreachable, noChapter, unfetchable, errors int
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *outcomeCounts) add(o readOutcome) {
|
func (c *outcomeCounts) add(o readOutcome) {
|
||||||
@@ -327,8 +303,6 @@ func (c *outcomeCounts) add(o readOutcome) {
|
|||||||
c.noChapter++
|
c.noChapter++
|
||||||
case outcomeUnfetchable:
|
case outcomeUnfetchable:
|
||||||
c.unfetchable++
|
c.unfetchable++
|
||||||
case outcomeNotFound:
|
|
||||||
c.notFound++
|
|
||||||
case outcomeError:
|
case outcomeError:
|
||||||
c.errors++
|
c.errors++
|
||||||
}
|
}
|
||||||
@@ -360,7 +334,7 @@ func (p *Poller) runLanePass(ctx context.Context, name string, paced bool) time.
|
|||||||
// carries the previous pass's forward inside recordPass.
|
// carries the previous pass's forward inside recordPass.
|
||||||
fig := passFigures{}
|
fig := passFigures{}
|
||||||
rec := passRecord{site: name, ranAt: now.UnixMilli()}
|
rec := passRecord{site: name, ranAt: now.UnixMilli()}
|
||||||
defer func() { p.recordPass(ctx, rec, fig) }()
|
defer func() { p.recordPass(rec, fig) }()
|
||||||
|
|
||||||
// One Lane row read at the top of a pass, serving two gates (issue #139).
|
// 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
|
// Both stamps outlive our process, so the gates read the durable row
|
||||||
@@ -477,7 +451,6 @@ func (p *Poller) runLanePass(ctx context.Context, name string, paced bool) time.
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
outcome := p.checkOne(ctx, sr)
|
outcome := p.checkOne(ctx, sr)
|
||||||
p.recordFailure(sr, outcome)
|
|
||||||
if outcome == outcomeUnreachable {
|
if outcome == outcomeUnreachable {
|
||||||
// The mid-loop browser loss writes an empty skip on purpose: the
|
// The mid-loop browser loss writes an empty skip on purpose: the
|
||||||
// pass returns before the checked counter increments, so its row
|
// pass returns before the checked counter increments, so its row
|
||||||
@@ -530,9 +503,8 @@ type passFigures struct {
|
|||||||
// pass's due, gap, clamped and checked forward rather than stating zeroes it
|
// 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
|
// did not measure; the skip column says why it declined, so the zeroes that
|
||||||
// remain (due-query, no-fetcher) read as explanations rather than
|
// remain (due-query, no-fetcher) read as explanations rather than
|
||||||
// measurements. Once the row is durable, the owner-notice judgement runs
|
// measurements.
|
||||||
// beside it (issue #171).
|
func (p *Poller) recordPass(rec passRecord, fig passFigures) {
|
||||||
func (p *Poller) recordPass(ctx context.Context, rec passRecord, fig passFigures) {
|
|
||||||
row := store.LanePass{
|
row := store.LanePass{
|
||||||
Site: rec.site,
|
Site: rec.site,
|
||||||
RanAt: rec.ranAt,
|
RanAt: rec.ranAt,
|
||||||
@@ -545,7 +517,6 @@ func (p *Poller) recordPass(ctx context.Context, rec passRecord, fig passFigures
|
|||||||
Unreachable: rec.counts.unreachable,
|
Unreachable: rec.counts.unreachable,
|
||||||
NoChapter: rec.counts.noChapter,
|
NoChapter: rec.counts.noChapter,
|
||||||
Unfetchable: rec.counts.unfetchable,
|
Unfetchable: rec.counts.unfetchable,
|
||||||
NotFound: rec.counts.notFound,
|
|
||||||
Errors: rec.counts.errors,
|
Errors: rec.counts.errors,
|
||||||
}
|
}
|
||||||
if row.GapMS == 0 {
|
if row.GapMS == 0 {
|
||||||
@@ -561,111 +532,7 @@ func (p *Poller) recordPass(ctx context.Context, rec passRecord, fig passFigures
|
|||||||
}
|
}
|
||||||
if err := p.Store.RecordLanePass(row, rec.ranAt-lanePassRetention.Milliseconds()); err != nil {
|
if err := p.Store.RecordLanePass(row, rec.ranAt-lanePassRetention.Milliseconds()); err != nil {
|
||||||
log.Printf("latest poll %s: record lane pass: %v", rec.site, err)
|
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
|
// countEligible routes the eligible count through the test seam when one is
|
||||||
@@ -740,35 +607,13 @@ func maxSeriesWait(due []store.Series, now time.Time, rest time.Duration) time.D
|
|||||||
}
|
}
|
||||||
return oldest
|
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":
|
// 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
|
// 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
|
// 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,
|
// 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
|
// a chapter-less page, an unfetchable address or a transport error without
|
||||||
// error without re-deriving the taxonomy.
|
// re-deriving the taxonomy.
|
||||||
func (p *Poller) checkOne(ctx context.Context, sr store.Series) (outcome readOutcome) {
|
func (p *Poller) checkOne(ctx context.Context, sr store.Series) (outcome readOutcome) {
|
||||||
defer func() {
|
defer func() {
|
||||||
if r := recover(); r != nil {
|
if r := recover(); r != nil {
|
||||||
@@ -812,9 +657,6 @@ func (p *Poller) checkOne(ctx context.Context, sr store.Series) (outcome readOut
|
|||||||
if errors.Is(err, errBrowserInterrupted) {
|
if errors.Is(err, errBrowserInterrupted) {
|
||||||
return outcomeUnreachable
|
return outcomeUnreachable
|
||||||
}
|
}
|
||||||
if errors.Is(err, errNotFound) {
|
|
||||||
return outcomeNotFound
|
|
||||||
}
|
|
||||||
return outcomeError
|
return outcomeError
|
||||||
}
|
}
|
||||||
// A legacy cover source is healed independently of the page read.
|
// A legacy cover source is healed independently of the page read.
|
||||||
@@ -827,25 +669,6 @@ func (p *Poller) checkOne(ctx context.Context, sr store.Series) (outcome readOut
|
|||||||
} else {
|
} else {
|
||||||
p.fillBlankCover(ctx, sr, facts.Cover)
|
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 {
|
if !facts.HasLatest {
|
||||||
// Most likely a challenge page or a layout change. Either way the row is
|
// 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.
|
// already stamped, so this waits out a rest instead of hot-looping.
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -6,19 +6,15 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
)
|
)
|
||||||
|
|
||||||
// seriesRead carries the facts the poll and the acquirer both extract from a
|
// seriesRead carries the two facts the poll and the acquirer both extract
|
||||||
// series page. Persistence, stamps and scheduling stay with the callers, so
|
// from a series page. Persistence, stamps and scheduling stay with the
|
||||||
// the policies that keep the two flows distinct (stamp order, rests) are not
|
// callers, so the policies that keep the two flows distinct (stamp order,
|
||||||
// swallowed by the module.
|
// rests) are not swallowed by the module.
|
||||||
type seriesRead struct {
|
type seriesRead struct {
|
||||||
Latest latestChapter
|
Latest latestChapter
|
||||||
HasLatest bool
|
HasLatest bool
|
||||||
Cover string
|
Cover string
|
||||||
HasCover bool
|
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
|
// 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.
|
// log uses it to tell a markup change from a body the size cap cut short.
|
||||||
BodyLen int
|
BodyLen int
|
||||||
@@ -29,18 +25,15 @@ type seriesRead struct {
|
|||||||
// errChallengeHeld (browser.go) is the outcome of a Site that answered with
|
// errChallengeHeld (browser.go) is the outcome of a Site that answered with
|
||||||
// its interstitial — status 403 (cf-mitigated) or a challenge page body — and
|
// 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).
|
// 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 (
|
var (
|
||||||
errNotFetchable = errors.New("series url not fetchable")
|
errNotFetchable = errors.New("series url not fetchable")
|
||||||
errNoFetcher = errors.New("no fetcher for site")
|
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
|
// 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
|
// 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
|
// Latest Chapter and the Cover address. It persists nothing and stamps
|
||||||
// persists nothing and stamps nothing.
|
// nothing.
|
||||||
//
|
//
|
||||||
// series_url arrives in a client-supplied PUT body (PUT /bookmarks/{key}
|
// 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
|
// accepts any string), so the gate is not an optimisation against burning a
|
||||||
@@ -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)
|
return seriesRead{}, fmt.Errorf("%w: fetch %s: status %d", errChallengeHeld, seriesURL, status)
|
||||||
}
|
}
|
||||||
if status != 200 {
|
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)
|
return seriesRead{}, fmt.Errorf("fetch %s: status %d", seriesURL, status)
|
||||||
}
|
}
|
||||||
if isInterstitial(body) {
|
if isInterstitial(body) {
|
||||||
@@ -79,12 +69,5 @@ func readSeriesPage(ctx context.Context, site, seriesURL string, browser, tls Fe
|
|||||||
}
|
}
|
||||||
latest, hasLatest := latestChapterFrom(site, seriesURL, body)
|
latest, hasLatest := latestChapterFrom(site, seriesURL, body)
|
||||||
cover, hasCover := coverFrom(site, seriesURL, body)
|
cover, hasCover := coverFrom(site, seriesURL, body)
|
||||||
return seriesRead{
|
return seriesRead{Latest: latest, HasLatest: hasLatest, Cover: cover, HasCover: hasCover, BodyLen: len(body)}, nil
|
||||||
Latest: latest,
|
|
||||||
HasLatest: hasLatest,
|
|
||||||
Cover: cover,
|
|
||||||
HasCover: hasCover,
|
|
||||||
SiteCompleted: siteCompletedFrom(site, seriesURL, body),
|
|
||||||
BodyLen: len(body),
|
|
||||||
}, nil
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,10 +22,10 @@ type latestChapter struct {
|
|||||||
|
|
||||||
// site answers the fixed questions every series-page read asks of its Site
|
// 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
|
// (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
|
// Chapter and the Cover address in a body, and — for a Site behind a
|
||||||
// completed, and — for a Site behind a JavaScript challenge — how to read its
|
// JavaScript challenge — how to read its payload from a cleared tab. One
|
||||||
// payload from a cleared tab. One entry describes everything about one Site,
|
// entry describes everything about one Site, and nowhere else gets to compare
|
||||||
// and nowhere else gets to compare the site string.
|
// the site string.
|
||||||
type site struct {
|
type site struct {
|
||||||
// Host is the exact hostname a series_url for this Site must carry.
|
// Host is the exact hostname a series_url for this Site must carry.
|
||||||
Host string
|
Host string
|
||||||
@@ -33,10 +33,6 @@ type site struct {
|
|||||||
LatestChapter func(seriesURL, body string) (latestChapter, bool)
|
LatestChapter func(seriesURL, body string) (latestChapter, bool)
|
||||||
// Cover finds the Cover address in a fetched body.
|
// Cover finds the Cover address in a fetched body.
|
||||||
Cover func(seriesURL, body string) (string, bool)
|
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 is how long a Series of this Site rests between Polls.
|
||||||
Rest time.Duration
|
Rest time.Duration
|
||||||
// Gap is the Lane's strictest pace: at least one second must pass between
|
// Gap is the Lane's strictest pace: at least one second must pass between
|
||||||
@@ -303,65 +299,43 @@ func kaganeCoverURL(body string) string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// comixDetailQuery returns the ["manga","detail","<id>"] query entry of
|
func comixCoverURL(seriesURL, body string) string {
|
||||||
// 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 {
|
|
||||||
id, ok := comixSeriesID(seriesURL)
|
id, ok := comixSeriesID(seriesURL)
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil
|
return ""
|
||||||
}
|
}
|
||||||
data := comixInitialDataRe.FindStringSubmatch(body)
|
data := comixInitialDataRe.FindStringSubmatch(body)
|
||||||
if data == nil {
|
if data == nil {
|
||||||
return nil
|
return ""
|
||||||
}
|
}
|
||||||
var state struct {
|
var state struct {
|
||||||
Queries map[string]json.RawMessage `json:"queries"`
|
Queries map[string]json.RawMessage `json:"queries"`
|
||||||
}
|
}
|
||||||
if err := json.Unmarshal([]byte(data[1]), &state); err != nil {
|
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 ""
|
return ""
|
||||||
}
|
}
|
||||||
var entry struct {
|
raw := state.Queries[`["manga","detail","`+id+`"]`]
|
||||||
|
if len(raw) == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
var detail struct {
|
||||||
Poster struct {
|
Poster struct {
|
||||||
Medium string `json:"medium"`
|
Medium string `json:"medium"`
|
||||||
} `json:"poster"`
|
} `json:"poster"`
|
||||||
}
|
}
|
||||||
if err := json.Unmarshal(detail, &entry); err != nil {
|
if err := json.Unmarshal(raw, &detail); err != nil {
|
||||||
return ""
|
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.
|
// lightnovelworld.
|
||||||
func ogImageCover(_, body string) (string, bool) {
|
func ogImageCover(_, body string) (string, bool) {
|
||||||
cover := metaContent(body, "property", "og:image")
|
cover := metaContent(body, "property", "og:image")
|
||||||
return cover, cover != ""
|
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) {
|
func novelfullCoverEntry(_, body string) (string, bool) {
|
||||||
cover := metaContent(body, "name", "image")
|
cover := metaContent(body, "name", "image")
|
||||||
return cover, cover != ""
|
return cover, cover != ""
|
||||||
@@ -386,87 +360,6 @@ func coverFrom(site, seriesURL, body string) (string, bool) {
|
|||||||
return "", false
|
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
|
// metaContent returns the content of the first <meta> whose attrName is
|
||||||
// attrValue. It keeps scanning after an empty match so a later published cover
|
// attrValue. It keeps scanning after an empty match so a later published cover
|
||||||
// is not hidden by an empty tag.
|
// is not hidden by an empty tag.
|
||||||
@@ -555,8 +448,7 @@ var sites = map[string]site{
|
|||||||
"asura": {
|
"asura": {
|
||||||
Host: "asurascans.com",
|
Host: "asurascans.com",
|
||||||
LatestChapter: asuraLatestChapter,
|
LatestChapter: asuraLatestChapter,
|
||||||
Cover: asuraCover,
|
Cover: ogImageCover,
|
||||||
Completed: asuraCompleted,
|
|
||||||
Rest: defaultRest,
|
Rest: defaultRest,
|
||||||
Gap: defaultGap,
|
Gap: defaultGap,
|
||||||
},
|
},
|
||||||
@@ -564,7 +456,6 @@ var sites = map[string]site{
|
|||||||
Host: "demonicscans.org",
|
Host: "demonicscans.org",
|
||||||
LatestChapter: demonicLatestChapter,
|
LatestChapter: demonicLatestChapter,
|
||||||
Cover: ogImageCover,
|
Cover: ogImageCover,
|
||||||
Completed: demonicCompleted,
|
|
||||||
Rest: defaultRest,
|
Rest: defaultRest,
|
||||||
Gap: defaultGap,
|
Gap: defaultGap,
|
||||||
},
|
},
|
||||||
@@ -572,7 +463,6 @@ var sites = map[string]site{
|
|||||||
Host: "comix.to",
|
Host: "comix.to",
|
||||||
LatestChapter: comixLatestChapter,
|
LatestChapter: comixLatestChapter,
|
||||||
Cover: comixCoverEntry,
|
Cover: comixCoverEntry,
|
||||||
Completed: comixCompleted,
|
|
||||||
Rest: defaultRest,
|
Rest: defaultRest,
|
||||||
Gap: defaultGap,
|
Gap: defaultGap,
|
||||||
Browser: &browserRead{
|
Browser: &browserRead{
|
||||||
@@ -589,7 +479,6 @@ var sites = map[string]site{
|
|||||||
Host: "kagane.to",
|
Host: "kagane.to",
|
||||||
LatestChapter: kaganeLatestChapter,
|
LatestChapter: kaganeLatestChapter,
|
||||||
Cover: kaganeCoverEntry,
|
Cover: kaganeCoverEntry,
|
||||||
Completed: kaganeCompleted,
|
|
||||||
Rest: defaultRest,
|
Rest: defaultRest,
|
||||||
Gap: defaultGap,
|
Gap: defaultGap,
|
||||||
Browser: &browserRead{
|
Browser: &browserRead{
|
||||||
@@ -604,7 +493,6 @@ var sites = map[string]site{
|
|||||||
Host: "novelfull.com",
|
Host: "novelfull.com",
|
||||||
LatestChapter: novelfullLatestChapter,
|
LatestChapter: novelfullLatestChapter,
|
||||||
Cover: novelfullCoverEntry,
|
Cover: novelfullCoverEntry,
|
||||||
Completed: novelfullCompleted,
|
|
||||||
Rest: defaultRest,
|
Rest: defaultRest,
|
||||||
Gap: defaultGap,
|
Gap: defaultGap,
|
||||||
Browser: &browserRead{
|
Browser: &browserRead{
|
||||||
@@ -619,7 +507,6 @@ var sites = map[string]site{
|
|||||||
Host: "lightnovelworld.net",
|
Host: "lightnovelworld.net",
|
||||||
LatestChapter: lnwLatestChapter,
|
LatestChapter: lnwLatestChapter,
|
||||||
Cover: ogImageCover,
|
Cover: ogImageCover,
|
||||||
Completed: lnwCompleted,
|
|
||||||
Rest: defaultRest,
|
Rest: defaultRest,
|
||||||
Gap: defaultGap,
|
Gap: defaultGap,
|
||||||
},
|
},
|
||||||
@@ -637,12 +524,6 @@ func SiteNames() []string {
|
|||||||
return 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
|
// browserBackedSites is derived from the registry: the Sites whose pages are
|
||||||
// read through the browser sidecar. Sorted so callers that range it (the
|
// read through the browser sidecar. Sorted so callers that range it (the
|
||||||
// browser fetcher's dispatch) see a stable order instead of map-iteration
|
// browser fetcher's dispatch) see a stable order instead of map-iteration
|
||||||
|
|||||||
@@ -188,109 +188,9 @@ const lnwSeriesFixture = `
|
|||||||
</div>
|
</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
|
// Trimmed from https://asurascans.com/comics/chronicles-of-the-demon-faction-f886a8af
|
||||||
// fetched 2026-08-22 by a curl probe.
|
// (redirected to ...-00dcbf97) on 2026-08-10.
|
||||||
const asuraOngoingFixture = `
|
const asuraCoverFixture = `<meta property="og:image" content="https://cdn.asurascans.com/asura-images/covers/chronicles-of-the-demon-faction.d4dcb8.webp">`
|
||||||
"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>`
|
|
||||||
|
|
||||||
// Trimmed from https://demonicscans.org/manga/Catastrophic-Necromancer on 2026-08-10.
|
// Trimmed from https://demonicscans.org/manga/Catastrophic-Necromancer on 2026-08-10.
|
||||||
// The source publishes the raw space in this URL.
|
// The source publishes the raw space in this URL.
|
||||||
@@ -323,7 +223,7 @@ func TestCoverFrom(t *testing.T) {
|
|||||||
wantCover string
|
wantCover string
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
name: "asura reads coverUrl prop, not og social card",
|
name: "asura uses published metadata URL",
|
||||||
site: "asura", body: asuraCoverFixture, wantOK: true,
|
site: "asura", body: asuraCoverFixture, wantOK: true,
|
||||||
wantCover: "https://cdn.asurascans.com/asura-images/covers/chronicles-of-the-demon-faction.d4dcb8.webp",
|
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",
|
name: "later metadata cover survives empty match",
|
||||||
site: "demonic",
|
site: "asura",
|
||||||
body: `<meta property="og:image" content="">` + demonicCoverFixture,
|
body: `<meta property="og:image" content="">` + asuraCoverFixture,
|
||||||
wantOK: true,
|
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",
|
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)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -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)
|
fmt.Println("pgtest:", err)
|
||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
// -v: the postgres image declares a VOLUME, so an explicit rm without it
|
defer exec.Command("docker", "rm", "-f", id).Run()
|
||||||
// leaves the anonymous data volume behind on every test run.
|
|
||||||
defer exec.Command("docker", "rm", "-f", "-v", id).Run()
|
|
||||||
|
|
||||||
adminURL = url
|
adminURL = url
|
||||||
return m.Run()
|
return m.Run()
|
||||||
@@ -87,7 +85,7 @@ func start() (id, url string, err error) {
|
|||||||
|
|
||||||
port, err := exec.Command("docker", "port", id, "5432/tcp").Output()
|
port, err := exec.Command("docker", "port", id, "5432/tcp").Output()
|
||||||
if err != nil {
|
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)
|
return "", "", fmt.Errorf("docker port: %w", err)
|
||||||
}
|
}
|
||||||
// "0.0.0.0:32768" (and possibly a second, IPv6 line); the port is all we want.
|
// "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:])
|
first[strings.LastIndex(first, ":")+1:])
|
||||||
|
|
||||||
if err := waitReady(url); err != nil {
|
if err := waitReady(url); err != nil {
|
||||||
exec.Command("docker", "rm", "-f", "-v", id).Run()
|
exec.Command("docker", "rm", "-f", id).Run()
|
||||||
return "", "", err
|
return "", "", err
|
||||||
}
|
}
|
||||||
return id, url, nil
|
return id, url, nil
|
||||||
|
|||||||
@@ -7,14 +7,10 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Series filter names (issue #140): the seven repair filters are ordered
|
// Series filter names (issue #140), ordered permanent-then-fixable — the
|
||||||
// permanent-then-fixable — the repairs nothing will ever undo first, the
|
// repairs nothing will ever undo first, the ones a Poll can make right after.
|
||||||
// ones a Poll can make right after. SeriesFilterFinished and
|
// A name is the repair a row needs, not the SQL that finds it; the values are
|
||||||
// SeriesFilterSiteCompleted are not part of that ordering: a finished
|
// the wire form the Series list URL carries (#142). "all" is the absent and
|
||||||
// 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.
|
// unknown case: every Series.
|
||||||
const (
|
const (
|
||||||
SeriesFilterAll = "all"
|
SeriesFilterAll = "all"
|
||||||
@@ -25,22 +21,17 @@ const (
|
|||||||
SeriesFilterStale = "stale"
|
SeriesFilterStale = "stale"
|
||||||
SeriesFilterNoCover = "no_cover"
|
SeriesFilterNoCover = "no_cover"
|
||||||
SeriesFilterReaderReport = "reader_report"
|
SeriesFilterReaderReport = "reader_report"
|
||||||
SeriesFilterFinished = "finished"
|
|
||||||
SeriesFilterSiteCompleted = "site_completed"
|
|
||||||
SeriesFilterFailing = "failing"
|
|
||||||
SeriesFilterUnverified = "unverified"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// SeriesFilter is one named filter predicate over the whole library. Site
|
// SeriesFilter is one named hygiene predicate over the whole library. Site
|
||||||
// and Kind narrow the row read; Name picks the predicate; Cutoff is the
|
// and Kind narrow the row read; Name picks the predicate; Cutoff is the
|
||||||
// staleness boundary the age-based filters — "stale" and the failing pair —
|
// staleness boundary the "stale" filter compares against, supplied by the
|
||||||
// compare against, supplied by the caller's clock — the store has no clock;
|
// caller's clock — the store has no clock; Page is 1-based.
|
||||||
// Page is 1-based.
|
|
||||||
type SeriesFilter struct {
|
type SeriesFilter struct {
|
||||||
Site string // "" = every Site
|
Site string // "" = every Site
|
||||||
Kind string // "" = both library buckets' series
|
Kind string // "" = both library buckets' series
|
||||||
Name string // one of the SeriesFilter* constants; "" = SeriesFilterAll
|
Name string // one of the SeriesFilter* constants; "" = SeriesFilterAll
|
||||||
Cutoff int64 // unix ms; the age-based filters read it, the store never does
|
Cutoff int64 // unix ms; "stale" reads it, the store never does
|
||||||
Page int // 1-based page of the row read; default 1
|
Page int // 1-based page of the row read; default 1
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -51,7 +42,7 @@ type SeriesFilter struct {
|
|||||||
// and only the anonymous boolean in raisedByReaderAnswer crosses 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,
|
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.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_corrected_at`
|
||||||
|
|
||||||
// raisedByReaderAnswer answers "did a Reader's report set this number" without
|
// raisedByReaderAnswer answers "did a Reader's report set this number" without
|
||||||
// naming which Reader. Kept apart from adminSeriesColumns so the column list —
|
// naming which Reader. Kept apart from adminSeriesColumns so the column list —
|
||||||
@@ -60,12 +51,6 @@ const adminSeriesColumns = `s.site, s.series_id, s.title, s.series_url, s.cover_
|
|||||||
// Reader behind them.
|
// Reader behind them.
|
||||||
const raisedByReaderAnswer = `(s.latest_raised_by IS NOT NULL) AS raised_by_reader`
|
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
|
// 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.
|
// ORDER BY is what makes this a stable page boundary — see SeriesPage.
|
||||||
const seriesPageSize = 50
|
const seriesPageSize = 50
|
||||||
@@ -95,19 +80,7 @@ type AdminSeries struct {
|
|||||||
LatestCorrectedAt int64
|
LatestCorrectedAt int64
|
||||||
ReaderCount int
|
ReaderCount int
|
||||||
RaisedByReader bool // a Reader's report set LatestChapterNum
|
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
|
// SeriesPage is one page of the owner's filtered Series list plus the count
|
||||||
@@ -140,28 +113,10 @@ func (a AdminSeries) Key() string { return a.Site + ":" + a.SeriesID }
|
|||||||
// The WHERE set is: no URL (an empty URL only — the host-failing-the-fetch-
|
// 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
|
// 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
|
// a later repair), never-read-a-chapter and never-checked as disjoint halves
|
||||||
// (non-zero versus zero check stamp), stale, no cover, finished (the
|
// (non-zero versus zero check stamp), stale, no cover, and Reader-report.
|
||||||
// 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
|
// 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.
|
// 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
|
// 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
|
// 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
|
// checked Series is already counted on its own "waiting"/never-checked
|
||||||
@@ -178,26 +133,16 @@ func adminFilter(f SeriesFilter) (where, having string, args []any, err error) {
|
|||||||
case SeriesFilterNoURL:
|
case SeriesFilterNoURL:
|
||||||
clauses = append(clauses, `s.series_url = ''`)
|
clauses = append(clauses, `s.series_url = ''`)
|
||||||
case SeriesFilterNoChapter:
|
case SeriesFilterNoChapter:
|
||||||
clauses = append(clauses, `s.latest_checked_at <> 0 AND s.latest_chapter_num IS NULL AND s.finished_at = 0`)
|
clauses = append(clauses, `s.latest_checked_at <> 0 AND s.latest_chapter_num IS NULL`)
|
||||||
case SeriesFilterNeverChecked:
|
case SeriesFilterNeverChecked:
|
||||||
clauses = append(clauses, `s.latest_checked_at = 0 AND s.finished_at = 0`)
|
clauses = append(clauses, `s.latest_checked_at = 0`)
|
||||||
case SeriesFilterStale:
|
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`)
|
clauses = append(clauses, `s.latest_checked_at > 0 AND s.latest_checked_at < $`+strconv.Itoa(len(args)+1))
|
||||||
args = append(args, f.Cutoff)
|
args = append(args, f.Cutoff)
|
||||||
case SeriesFilterNoCover:
|
case SeriesFilterNoCover:
|
||||||
clauses = append(clauses, `s.cover_address = '' AND s.finished_at = 0`)
|
clauses = append(clauses, `s.cover_address = ''`)
|
||||||
case SeriesFilterReaderReport:
|
case SeriesFilterReaderReport:
|
||||||
clauses = append(clauses, `s.latest_raised_by IS NOT NULL`)
|
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:
|
case SeriesFilterNoReaders:
|
||||||
having = `HAVING COUNT(b.reader_id) = 0`
|
having = `HAVING COUNT(b.reader_id) = 0`
|
||||||
default:
|
default:
|
||||||
@@ -212,9 +157,9 @@ func adminFilter(f SeriesFilter) (where, having string, args []any, err error) {
|
|||||||
// SeriesPage returns one page of the Series matching the filter, least
|
// SeriesPage returns one page of the Series matching the filter, least
|
||||||
// recently checked first. The LEFT JOIN to Bookmarks is what surfaces the
|
// 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
|
// 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
|
// as the Lane's join does. ReaderCount is a plain count of every Bookmark on
|
||||||
// finished is a Series flag, so this plain ReaderCount agrees with the Lane
|
// the Series, which knowingly disagrees with the two Lane queries for as long
|
||||||
// queries (issue #157).
|
// as the finished lifecycle bucket exists (#140).
|
||||||
//
|
//
|
||||||
// The tie-break is mandatory, not decorative: every unpollable Series shares a
|
// 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
|
// zero check stamp, so ordering on that column alone gives no stable page
|
||||||
@@ -243,18 +188,15 @@ func (s *Store) SeriesPage(f SeriesFilter) (SeriesPage, error) {
|
|||||||
base := len(args)
|
base := len(args)
|
||||||
args = append(args, seriesPageSize, seriesPageSize*(f.Page-1))
|
args = append(args, seriesPageSize, seriesPageSize*(f.Page-1))
|
||||||
rows, err := s.db.Query(`
|
rows, err := s.db.Query(`
|
||||||
SELECT `+adminSeriesColumns+`, `+raisedByReaderAnswer+`, `+failureAnswer+`,
|
SELECT `+adminSeriesColumns+`, `+raisedByReaderAnswer+`,
|
||||||
COUNT(b.reader_id) AS reader_count,
|
COUNT(b.reader_id) AS reader_count,
|
||||||
COUNT(*) OVER () AS filtered_total
|
COUNT(*) OVER () AS filtered_total
|
||||||
FROM series s
|
FROM series s
|
||||||
LEFT JOIN bookmarks b ON b.site = s.site AND b.series_id = s.series_id
|
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+`
|
`+where+`
|
||||||
GROUP BY s.site, s.series_id, s.title, s.series_url, s.cover_address,
|
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.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.force_poll_at, s.latest_corrected_at, s.latest_raised_by
|
||||||
s.latest_raised_by,
|
|
||||||
f.outcome, f.failing_since
|
|
||||||
`+having+`
|
`+having+`
|
||||||
ORDER BY s.latest_checked_at, s.site, s.series_id
|
ORDER BY s.latest_checked_at, s.site, s.series_id
|
||||||
LIMIT $`+strconv.Itoa(base+1)+` OFFSET $`+strconv.Itoa(base+2), args...)
|
LIMIT $`+strconv.Itoa(base+1)+` OFFSET $`+strconv.Itoa(base+2), args...)
|
||||||
@@ -293,7 +235,6 @@ func (s *Store) SeriesShapes(f SeriesFilter) ([]SiteSeriesShape, error) {
|
|||||||
SELECT s.site, s.kind
|
SELECT s.site, s.kind
|
||||||
FROM series s
|
FROM series s
|
||||||
LEFT JOIN bookmarks b ON b.site = s.site AND b.series_id = s.series_id
|
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+`
|
`+where+`
|
||||||
GROUP BY s.site, s.series_id, s.kind
|
GROUP BY s.site, s.series_id, s.kind
|
||||||
`+having+`
|
`+having+`
|
||||||
@@ -316,11 +257,11 @@ func (s *Store) SeriesShapes(f SeriesFilter) ([]SiteSeriesShape, error) {
|
|||||||
return out, rows.Err()
|
return out, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
// scanAdminSeries reads one row in adminSeriesColumns + raisedByReaderAnswer +
|
// scanAdminSeries reads one row in adminSeriesColumns + raisedByReaderAnswer
|
||||||
// failureAnswer order, plus the query's reader_count and filtered_total
|
// order, plus the query's reader_count and filtered_total columns, and returns
|
||||||
// columns, and returns the window total alongside the row. latest_chapter_num
|
// the window total alongside the row. latest_chapter_num is NULL until first
|
||||||
// is NULL until first captured — the "never read a chapter" state. The
|
// captured — the "never read a chapter" state. The Sighting-raiser column is
|
||||||
// Sighting-raiser column is never among the scanned columns.
|
// never among the scanned columns.
|
||||||
func scanAdminSeries(scan func(...any) error) (AdminSeries, int, error) {
|
func scanAdminSeries(scan func(...any) error) (AdminSeries, int, error) {
|
||||||
var (
|
var (
|
||||||
a AdminSeries
|
a AdminSeries
|
||||||
@@ -330,8 +271,8 @@ func scanAdminSeries(scan func(...any) error) (AdminSeries, int, error) {
|
|||||||
if err := scan(
|
if err := scan(
|
||||||
&a.Site, &a.SeriesID, &a.Title, &a.SeriesURL, &a.CoverAddress,
|
&a.Site, &a.SeriesID, &a.Title, &a.SeriesURL, &a.CoverAddress,
|
||||||
&a.Kind, &a.LatestChapter, &latestChapterNum, &a.LatestCheckedAt,
|
&a.Kind, &a.LatestChapter, &latestChapterNum, &a.LatestCheckedAt,
|
||||||
&a.ForcePollAt, &a.LatestCorrectedAt, &a.FinishedAt, &a.SiteCompletedAt,
|
&a.ForcePollAt, &a.LatestCorrectedAt,
|
||||||
&a.RaisedByReader, &a.FailureOutcome, &a.FailingSince, &a.ReaderCount, &total,
|
&a.RaisedByReader, &a.ReaderCount, &total,
|
||||||
); err != nil {
|
); err != nil {
|
||||||
return AdminSeries{}, 0, err
|
return AdminSeries{}, 0, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,7 +20,6 @@ type seriesSeed struct {
|
|||||||
latestNum *float64
|
latestNum *float64
|
||||||
bookmarks int // readers that hold it; 0 = orphan
|
bookmarks int // readers that hold it; 0 = orphan
|
||||||
raisedBy bool // a Reader's report is attributed as the raiser
|
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
|
// seedAdminSeries inserts one series row and its bookmarks (owner first, then
|
||||||
@@ -40,10 +39,10 @@ func seedAdminSeries(t *testing.T, s *Store, seed seriesSeed) {
|
|||||||
}
|
}
|
||||||
if _, err := s.db.Exec(`
|
if _, err := s.db.Exec(`
|
||||||
INSERT INTO series (site, series_id, title, kind, series_url, cover_address,
|
INSERT INTO series (site, series_id, title, kind, series_url, cover_address,
|
||||||
latest_checked_at, latest_chapter, latest_chapter_num, site_completed_at)
|
latest_checked_at, latest_chapter, latest_chapter_num)
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
|
||||||
site, seriesID, "Title of "+seed.key, seed.kind, seed.url, seed.cover,
|
site, seriesID, "Title of "+seed.key, seed.kind, seed.url, seed.cover,
|
||||||
seed.checkedAt, latestChapter, seed.latestNum, seed.siteCompletedAt); err != nil {
|
seed.checkedAt, latestChapter, seed.latestNum); err != nil {
|
||||||
t.Fatalf("seed series %q: %v", seed.key, err)
|
t.Fatalf("seed series %q: %v", seed.key, err)
|
||||||
}
|
}
|
||||||
for i := range seed.bookmarks {
|
for i := range seed.bookmarks {
|
||||||
@@ -129,85 +128,6 @@ func TestAdminSeriesFilters(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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:
|
// "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
|
// 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.
|
// mix that should satisfy both, no row may be counted twice.
|
||||||
@@ -474,263 +394,3 @@ func TestAdminSeriesCarriesForcePollAt(t *testing.T) {
|
|||||||
t.Fatalf("row = %+v, want ForcePollAt 5000", page.Rows)
|
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,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)
|
|
||||||
);
|
|
||||||
+45
-254
@@ -47,16 +47,13 @@ type Bookmark struct {
|
|||||||
LatestChapter string `json:"latest_chapter"`
|
LatestChapter string `json:"latest_chapter"`
|
||||||
LatestChapterNum *float64 `json:"latest_chapter_num"` // nil until first captured
|
LatestChapterNum *float64 `json:"latest_chapter_num"` // nil until first captured
|
||||||
UpdatedAt int64 `json:"updated_at"` // unix ms; see Upsert
|
UpdatedAt int64 `json:"updated_at"` // unix ms; see Upsert
|
||||||
// Status is the lifecycle bucket: reading or archived.
|
// Status is the lifecycle bucket: reading, archived, or finished.
|
||||||
// Archived series stay polled for new chapters.
|
// Archived series stay polled for new chapters; finished ones do not.
|
||||||
// Empty on the way in means "no opinion" — see Upsert.
|
// Empty on the way in means "no opinion" — see Upsert.
|
||||||
Status string `json:"status"`
|
Status string `json:"status"`
|
||||||
// Kind is the library bucket: manga or novel. Empty on the way in means
|
// Kind is the library bucket: manga or novel. Empty on the way in means
|
||||||
// "no opinion" — see Upsert.
|
// "no opinion" — see Upsert.
|
||||||
Kind string `json:"kind"`
|
Kind string `json:"kind"`
|
||||||
// Finished is the owner's retirement of the Series, derived: the flag is a
|
|
||||||
// Series fact and a client cannot write it — see Upsert.
|
|
||||||
Finished bool `json:"finished"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Series is one distinct work, shared by every bookmark that tracks it. It is
|
// Series is one distinct work, shared by every bookmark that tracks it. It is
|
||||||
@@ -84,10 +81,6 @@ type Series struct {
|
|||||||
LatestChapter string
|
LatestChapter string
|
||||||
LatestChapterNum *float64 // nil until first captured
|
LatestChapterNum *float64 // nil until first captured
|
||||||
LatestCheckedAt int64 // unix ms; see MarkLatestChecked
|
LatestCheckedAt int64 // unix ms; see MarkLatestChecked
|
||||||
// SiteCompletedAt is when the last successful Poll read saw the Site's
|
|
||||||
// own completed value, zero meaning it did not (issue #168). A poller
|
|
||||||
// fact, not reading progress: Upsert never touches it.
|
|
||||||
SiteCompletedAt int64
|
|
||||||
// LatestRaisedBy is the Reader whose Sighting last raised LatestChapter,
|
// LatestRaisedBy is the Reader whose Sighting last raised LatestChapter,
|
||||||
// and nil when the stored value is a Poll's own finding. It is what lets a
|
// and nil when the stored value is a Poll's own finding. It is what lets a
|
||||||
// Poll that contradicts the value downwards name a Reader instead of
|
// Poll that contradicts the value downwards name a Reader instead of
|
||||||
@@ -114,7 +107,7 @@ type LanePass struct {
|
|||||||
GapMS int64
|
GapMS int64
|
||||||
Clamped bool
|
Clamped bool
|
||||||
Refused, Unreachable, NoChapter int
|
Refused, Unreachable, NoChapter int
|
||||||
Unfetchable, Errors, NotFound int
|
Unfetchable, Errors int
|
||||||
PausedUntil, RefuseUntil int64
|
PausedUntil, RefuseUntil int64
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -123,7 +116,7 @@ type LanePass struct {
|
|||||||
type SiteOutcomes struct {
|
type SiteOutcomes struct {
|
||||||
Site string
|
Site string
|
||||||
Refused, Unreachable, NoChapter int
|
Refused, Unreachable, NoChapter int
|
||||||
Unfetchable, Errors, NotFound int
|
Unfetchable, Errors int
|
||||||
}
|
}
|
||||||
|
|
||||||
// LanePause is one persisted Lane pause stamp.
|
// LanePause is one persisted Lane pause stamp.
|
||||||
@@ -221,11 +214,10 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Lifecycle buckets. A bookmark is in exactly one; favorite is orthogonal.
|
// Lifecycle buckets. A bookmark is in exactly one; favorite is orthogonal.
|
||||||
// Finished is not a bucket: it is a fact about the Series (series.finished_at),
|
|
||||||
// never about a Reader's bookmark.
|
|
||||||
const (
|
const (
|
||||||
StatusReading = "reading"
|
StatusReading = "reading"
|
||||||
StatusArchived = "archived"
|
StatusArchived = "archived"
|
||||||
|
StatusFinished = "finished"
|
||||||
)
|
)
|
||||||
|
|
||||||
//go:embed migrations/*.sql
|
//go:embed migrations/*.sql
|
||||||
@@ -237,18 +229,16 @@ var migrations embed.FS
|
|||||||
// order, so the flat Bookmark reads back whole despite the split (ADR-0004).
|
// order, so the flat Bookmark reads back whole despite the split (ADR-0004).
|
||||||
const bookmarkColumns = `b.site, b.series_id, s.title, s.series_url, s.cover_address,
|
const bookmarkColumns = `b.site, b.series_id, s.title, s.series_url, s.cover_address,
|
||||||
b.last_chapter, b.last_chapter_num, b.last_chapter_url,
|
b.last_chapter, b.last_chapter_num, b.last_chapter_url,
|
||||||
b.favorite, s.latest_chapter, s.latest_chapter_num, b.updated_at, b.status, s.kind,
|
b.favorite, s.latest_chapter, s.latest_chapter_num, b.updated_at, b.status, s.kind`
|
||||||
s.finished_at > 0`
|
|
||||||
|
|
||||||
// seriesColumns is the series row in scanSeries order, used by the poller's
|
// seriesColumns is the series row in scanSeries order, used by the poller's
|
||||||
// due query. latest_checked_at lives only on series — see MarkLatestChecked
|
// due query. latest_checked_at lives only on series — see MarkLatestChecked
|
||||||
// for why it stays off every client-visible write.
|
// for why it stays off every client-visible write.
|
||||||
const seriesColumns = `s.site, s.series_id, s.title, s.series_url, s.cover, s.cover_address,
|
const seriesColumns = `s.site, s.series_id, s.title, s.series_url, s.cover, s.cover_address,
|
||||||
s.kind, s.latest_chapter, s.latest_chapter_num, s.latest_checked_at, s.latest_raised_by,
|
s.kind, s.latest_chapter, s.latest_chapter_num, s.latest_checked_at, s.latest_raised_by`
|
||||||
s.site_completed_at`
|
|
||||||
|
|
||||||
const lanePassColumns = `p.site, p.ran_at, p.skip, p.due, p.checked, p.gap_ms, p.clamped,
|
const lanePassColumns = `p.site, p.ran_at, p.skip, p.due, p.checked, p.gap_ms, p.clamped,
|
||||||
p.refused, p.unreachable, p.no_chapter, p.unfetchable, p.errors, p.not_found,
|
p.refused, p.unreachable, p.no_chapter, p.unfetchable, p.errors,
|
||||||
COALESCE(l.paused_until, 0), COALESCE(l.refuse_until, 0)`
|
COALESCE(l.paused_until, 0), COALESCE(l.refuse_until, 0)`
|
||||||
|
|
||||||
// Owner is the person running the service: the first Reader, seeded at startup
|
// Owner is the person running the service: the first Reader, seeded at startup
|
||||||
@@ -618,7 +608,6 @@ func (s *Store) scanBookmark(scan func(...any) error) (Bookmark, error) {
|
|||||||
&b.Site, &b.SeriesID, &b.Title, &b.SeriesURL, &coverAddress,
|
&b.Site, &b.SeriesID, &b.Title, &b.SeriesURL, &coverAddress,
|
||||||
&b.LastChapter, &b.LastChapterNum, &b.LastChapterURL,
|
&b.LastChapter, &b.LastChapterNum, &b.LastChapterURL,
|
||||||
&b.Favorite, &b.LatestChapter, &latestChapterNum, &b.UpdatedAt, &b.Status, &b.Kind,
|
&b.Favorite, &b.LatestChapter, &latestChapterNum, &b.UpdatedAt, &b.Status, &b.Kind,
|
||||||
&b.Finished,
|
|
||||||
); err != nil {
|
); err != nil {
|
||||||
return Bookmark{}, err
|
return Bookmark{}, err
|
||||||
}
|
}
|
||||||
@@ -630,9 +619,9 @@ func (s *Store) scanBookmark(scan func(...any) error) (Bookmark, error) {
|
|||||||
// bookmark is keyed (reader_id, site, series_id) (issue #22).
|
// bookmark is keyed (reader_id, site, series_id) (issue #22).
|
||||||
b.Key = b.Site + ":" + b.SeriesID
|
b.Key = b.Site + ":" + b.SeriesID
|
||||||
// An unrecognised bucket (a hand-edited row) would leave the row in no list
|
// An unrecognised bucket (a hand-edited row) would leave the row in no list
|
||||||
// at all, so anything outside the two known buckets reads as the default
|
// at all, so anything outside the three known buckets reads as the default
|
||||||
// rather than being passed through.
|
// rather than being passed through.
|
||||||
if b.Status != StatusReading && b.Status != StatusArchived {
|
if b.Status != StatusReading && b.Status != StatusArchived && b.Status != StatusFinished {
|
||||||
b.Status = StatusReading
|
b.Status = StatusReading
|
||||||
}
|
}
|
||||||
return b, nil
|
return b, nil
|
||||||
@@ -651,7 +640,7 @@ func scanSeries(scan func(...any) error) (Series, error) {
|
|||||||
if err := scan(
|
if err := scan(
|
||||||
&sr.Site, &sr.SeriesID, &sr.Title, &sr.SeriesURL, &sr.Cover, &sr.CoverAddress,
|
&sr.Site, &sr.SeriesID, &sr.Title, &sr.SeriesURL, &sr.Cover, &sr.CoverAddress,
|
||||||
&sr.Kind, &sr.LatestChapter, &latestChapterNum, &sr.LatestCheckedAt, &latestRaisedBy,
|
&sr.Kind, &sr.LatestChapter, &latestChapterNum, &sr.LatestCheckedAt, &latestRaisedBy,
|
||||||
&sr.SiteCompletedAt, &sr.Forced, &sr.readerCount,
|
&sr.Forced, &sr.readerCount,
|
||||||
); err != nil {
|
); err != nil {
|
||||||
return Series{}, err
|
return Series{}, err
|
||||||
}
|
}
|
||||||
@@ -668,7 +657,7 @@ func scanLanePass(scan func(...any) error) (LanePass, error) {
|
|||||||
var p LanePass
|
var p LanePass
|
||||||
if err := scan(
|
if err := scan(
|
||||||
&p.Site, &p.RanAt, &p.Skip, &p.Due, &p.Checked, &p.GapMS, &p.Clamped,
|
&p.Site, &p.RanAt, &p.Skip, &p.Due, &p.Checked, &p.GapMS, &p.Clamped,
|
||||||
&p.Refused, &p.Unreachable, &p.NoChapter, &p.Unfetchable, &p.Errors, &p.NotFound,
|
&p.Refused, &p.Unreachable, &p.NoChapter, &p.Unfetchable, &p.Errors,
|
||||||
&p.PausedUntil, &p.RefuseUntil,
|
&p.PausedUntil, &p.RefuseUntil,
|
||||||
); err != nil {
|
); err != nil {
|
||||||
return LanePass{}, err
|
return LanePass{}, err
|
||||||
@@ -1136,10 +1125,10 @@ func (s *Store) RecordLanePass(p LanePass, retainBefore int64) error {
|
|||||||
if _, err := tx.Exec(`
|
if _, err := tx.Exec(`
|
||||||
INSERT INTO poll_passes
|
INSERT INTO poll_passes
|
||||||
(site, ran_at, skip, due, checked, gap_ms, clamped,
|
(site, ran_at, skip, due, checked, gap_ms, clamped,
|
||||||
refused, unreachable, no_chapter, unfetchable, errors, not_found)
|
refused, unreachable, no_chapter, unfetchable, errors)
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)`,
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,
|
||||||
p.Site, p.RanAt, p.Skip, p.Due, p.Checked, p.GapMS, p.Clamped,
|
p.Site, p.RanAt, p.Skip, p.Due, p.Checked, p.GapMS, p.Clamped,
|
||||||
p.Refused, p.Unreachable, p.NoChapter, p.Unfetchable, p.Errors, p.NotFound); err != nil {
|
p.Refused, p.Unreachable, p.NoChapter, p.Unfetchable, p.Errors); err != nil {
|
||||||
return fmt.Errorf("insert lane pass %s at %d: %w", p.Site, p.RanAt, err)
|
return fmt.Errorf("insert lane pass %s at %d: %w", p.Site, p.RanAt, err)
|
||||||
}
|
}
|
||||||
if _, err := tx.Exec(`DELETE FROM poll_passes WHERE ran_at < $1`, retainBefore); err != nil {
|
if _, err := tx.Exec(`DELETE FROM poll_passes WHERE ran_at < $1`, retainBefore); err != nil {
|
||||||
@@ -1176,7 +1165,7 @@ func (s *Store) LatestLanePasses() ([]LanePass, error) {
|
|||||||
FROM (
|
FROM (
|
||||||
SELECT DISTINCT ON (site)
|
SELECT DISTINCT ON (site)
|
||||||
site, ran_at, skip, due, checked, gap_ms, clamped,
|
site, ran_at, skip, due, checked, gap_ms, clamped,
|
||||||
refused, unreachable, no_chapter, unfetchable, errors, not_found
|
refused, unreachable, no_chapter, unfetchable, errors
|
||||||
FROM poll_passes
|
FROM poll_passes
|
||||||
ORDER BY site, ran_at DESC
|
ORDER BY site, ran_at DESC
|
||||||
) p
|
) p
|
||||||
@@ -1203,7 +1192,7 @@ func (s *Store) LatestLanePasses() ([]LanePass, error) {
|
|||||||
func (s *Store) LanePassOutcomes(since int64) ([]SiteOutcomes, error) {
|
func (s *Store) LanePassOutcomes(since int64) ([]SiteOutcomes, error) {
|
||||||
rows, err := s.db.Query(`
|
rows, err := s.db.Query(`
|
||||||
SELECT site, SUM(refused), SUM(unreachable), SUM(no_chapter),
|
SELECT site, SUM(refused), SUM(unreachable), SUM(no_chapter),
|
||||||
SUM(unfetchable), SUM(errors), SUM(not_found)
|
SUM(unfetchable), SUM(errors)
|
||||||
FROM poll_passes
|
FROM poll_passes
|
||||||
WHERE ran_at >= $1
|
WHERE ran_at >= $1
|
||||||
GROUP BY site
|
GROUP BY site
|
||||||
@@ -1218,7 +1207,7 @@ func (s *Store) LanePassOutcomes(since int64) ([]SiteOutcomes, error) {
|
|||||||
var outcomes SiteOutcomes
|
var outcomes SiteOutcomes
|
||||||
if err := rows.Scan(
|
if err := rows.Scan(
|
||||||
&outcomes.Site, &outcomes.Refused, &outcomes.Unreachable,
|
&outcomes.Site, &outcomes.Refused, &outcomes.Unreachable,
|
||||||
&outcomes.NoChapter, &outcomes.Unfetchable, &outcomes.Errors, &outcomes.NotFound,
|
&outcomes.NoChapter, &outcomes.Unfetchable, &outcomes.Errors,
|
||||||
); err != nil {
|
); err != nil {
|
||||||
return nil, fmt.Errorf("scan lane pass outcomes: %w", err)
|
return nil, fmt.Errorf("scan lane pass outcomes: %w", err)
|
||||||
}
|
}
|
||||||
@@ -1227,101 +1216,6 @@ func (s *Store) LanePassOutcomes(since int64) ([]SiteOutcomes, error) {
|
|||||||
return out, rows.Err()
|
return out, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
// RefusingSince reports, per Site, when that Site's current unbroken run of
|
|
||||||
// refusing passes began: a pass refuses when the Lane gate returned early
|
|
||||||
// (skip = 'refusing') or the pass loop counted refusals (refused > 0), so a
|
|
||||||
// Site parked in refusal backoff keeps its run unbroken. A Site whose
|
|
||||||
// latest pass did not refuse is absent. The run is bounded by the pass
|
|
||||||
// log's retention — a run older than the log answers with the oldest row
|
|
||||||
// present — and nothing after now counts: the cutoff is the caller's clock.
|
|
||||||
func (s *Store) RefusingSince(now int64) (map[string]int64, error) {
|
|
||||||
rows, err := s.db.Query(`
|
|
||||||
SELECT site, MIN(ran_at)
|
|
||||||
FROM poll_passes p
|
|
||||||
WHERE ran_at <= $1
|
|
||||||
AND (refused > 0 OR skip = 'refusing')
|
|
||||||
AND ran_at > COALESCE((
|
|
||||||
SELECT MAX(q.ran_at) FROM poll_passes q
|
|
||||||
WHERE q.site = p.site AND q.ran_at <= $1
|
|
||||||
AND NOT (q.refused > 0 OR q.skip = 'refusing')
|
|
||||||
), 0)
|
|
||||||
GROUP BY site`, now)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("query refusing since: %w", err)
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
out := map[string]int64{}
|
|
||||||
for rows.Next() {
|
|
||||||
var site string
|
|
||||||
var since int64
|
|
||||||
if err := rows.Scan(&site, &since); err != nil {
|
|
||||||
return nil, fmt.Errorf("scan refusing since: %w", err)
|
|
||||||
}
|
|
||||||
out[site] = since
|
|
||||||
}
|
|
||||||
return out, rows.Err()
|
|
||||||
}
|
|
||||||
|
|
||||||
// SidecarOK reports, per Site in sites, the unix ms of that Site's most
|
|
||||||
// recent pass that actually reached the sidecar: the pass ran its loop
|
|
||||||
// (skip = '') and no Series read lost Chrome (unreachable = 0) — a
|
|
||||||
// challenge answer still reached the sidecar, a lost sidecar did not. A
|
|
||||||
// Site with no such pass is absent: an asleep Lane never reached it, so it
|
|
||||||
// is absent too and cannot age into a sidecar-down alarm by itself.
|
|
||||||
func (s *Store) SidecarOK(sites []string) (map[string]int64, error) {
|
|
||||||
rows, err := s.db.Query(`
|
|
||||||
SELECT DISTINCT ON (site) site, ran_at
|
|
||||||
FROM poll_passes
|
|
||||||
WHERE site = ANY($1) AND skip = '' AND unreachable = 0
|
|
||||||
ORDER BY site, ran_at DESC`, sites)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("query sidecar ok: %w", err)
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
out := map[string]int64{}
|
|
||||||
for rows.Next() {
|
|
||||||
var site string
|
|
||||||
var ranAt int64
|
|
||||||
if err := rows.Scan(&site, &ranAt); err != nil {
|
|
||||||
return nil, fmt.Errorf("scan sidecar ok: %w", err)
|
|
||||||
}
|
|
||||||
out[site] = ranAt
|
|
||||||
}
|
|
||||||
return out, rows.Err()
|
|
||||||
}
|
|
||||||
|
|
||||||
// NoChapterShare reports, per Site, the share of that Site's Series holding
|
|
||||||
// a no-chapter failure row older than cutoff: old rows over the Site's
|
|
||||||
// whole Series count, so a four-Series Site and a 200-Series Site are
|
|
||||||
// judged on the same scale. A Site with no Series has no share and is
|
|
||||||
// absent.
|
|
||||||
func (s *Store) NoChapterShare(cutoff int64) (map[string]float64, error) {
|
|
||||||
rows, err := s.db.Query(`
|
|
||||||
SELECT s.site,
|
|
||||||
(COUNT(*) FILTER (WHERE f.outcome = 'no_chapter' AND f.failing_since < $1))::float8
|
|
||||||
/ (COUNT(*)::float8)
|
|
||||||
FROM series s
|
|
||||||
LEFT JOIN poll_failures f ON f.site = s.site AND f.series_id = s.series_id
|
|
||||||
GROUP BY s.site
|
|
||||||
ORDER BY s.site`, cutoff)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("query no-chapter share: %w", err)
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
out := map[string]float64{}
|
|
||||||
for rows.Next() {
|
|
||||||
var site string
|
|
||||||
var share float64
|
|
||||||
if err := rows.Scan(&site, &share); err != nil {
|
|
||||||
return nil, fmt.Errorf("scan no-chapter share: %w", err)
|
|
||||||
}
|
|
||||||
out[site] = share
|
|
||||||
}
|
|
||||||
return out, rows.Err()
|
|
||||||
}
|
|
||||||
// SetLaneRefusal persists a Site's refusal backoff stamp without touching its
|
// SetLaneRefusal persists a Site's refusal backoff stamp without touching its
|
||||||
// pause. until is supplied by the caller's clock.
|
// pause. until is supplied by the caller's clock.
|
||||||
func (s *Store) SetLaneRefusal(site string, until int64) error {
|
func (s *Store) SetLaneRefusal(site string, until int64) error {
|
||||||
@@ -1398,72 +1292,6 @@ func (s *Store) LaneGates(site string) (pausedUntil, refuseUntil int64, err erro
|
|||||||
return pausedUntil, refuseUntil, nil
|
return pausedUntil, refuseUntil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// RecordSeriesFailure upserts one Series' failure row: the outcome word is
|
|
||||||
// updated when it changes, failing_since is never overwritten, and an
|
|
||||||
// unchanged word writes nothing. One statement, so the identical-word no-op
|
|
||||||
// and the keep-the-stamp rule are the same guarantee: the SET arm fires only
|
|
||||||
// when the word differs, and failing_since is simply absent from it
|
|
||||||
// (ADR-0016).
|
|
||||||
func (s *Store) RecordSeriesFailure(site, seriesID, outcome string, now int64) error {
|
|
||||||
if _, err := s.db.Exec(`
|
|
||||||
INSERT INTO poll_failures (site, series_id, outcome, failing_since) VALUES ($1, $2, $3, $4)
|
|
||||||
ON CONFLICT (site, series_id) DO UPDATE SET outcome = EXCLUDED.outcome
|
|
||||||
WHERE poll_failures.outcome <> EXCLUDED.outcome`, site, seriesID, outcome, now); err != nil {
|
|
||||||
return fmt.Errorf("record series failure %s:%s: %w", site, seriesID, err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ClearSeriesFailure deletes one Series' failure row. A row that is not there
|
|
||||||
// is not an error.
|
|
||||||
func (s *Store) ClearSeriesFailure(site, seriesID string) error {
|
|
||||||
if _, err := s.db.Exec(
|
|
||||||
`DELETE FROM poll_failures WHERE site = $1 AND series_id = $2`, site, seriesID); err != nil {
|
|
||||||
return fmt.Errorf("clear series failure %s:%s: %w", site, seriesID, err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// NoticeSent reports whether the owner has already been told about this
|
|
||||||
// episode (issue #171). The row's presence is the whole state, so a missing
|
|
||||||
// row reads false without error.
|
|
||||||
func (s *Store) NoticeSent(condition, site string) (bool, error) {
|
|
||||||
var at int64
|
|
||||||
err := s.db.QueryRow(
|
|
||||||
`SELECT notified_at FROM owner_notices WHERE condition = $1 AND site = $2`,
|
|
||||||
condition, site).Scan(&at)
|
|
||||||
if errors.Is(err, sql.ErrNoRows) {
|
|
||||||
return false, nil
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return false, fmt.Errorf("notice sent %s/%s: %w", condition, site, err)
|
|
||||||
}
|
|
||||||
return true, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// MarkNoticeSent records that the owner was told. Called only after a
|
|
||||||
// successful send. Re-marking the same episode just moves the stamp: the row
|
|
||||||
// is a lock against a second message, not a log.
|
|
||||||
func (s *Store) MarkNoticeSent(condition, site string, at int64) error {
|
|
||||||
if _, err := s.db.Exec(`
|
|
||||||
INSERT INTO owner_notices (condition, site, notified_at) VALUES ($1, $2, $3)
|
|
||||||
ON CONFLICT (condition, site) DO UPDATE SET notified_at = EXCLUDED.notified_at`,
|
|
||||||
condition, site, at); err != nil {
|
|
||||||
return fmt.Errorf("mark notice sent %s/%s: %w", condition, site, err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ClearNotice forgets an episode, so the condition's next occurrence sends
|
|
||||||
// again. A row that is not there is not an error.
|
|
||||||
func (s *Store) ClearNotice(condition, site string) error {
|
|
||||||
if _, err := s.db.Exec(
|
|
||||||
`DELETE FROM owner_notices WHERE condition = $1 AND site = $2`, condition, site); err != nil {
|
|
||||||
return fmt.Errorf("clear notice %s/%s: %w", condition, site, err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DueForLatestCheck returns one Site's series whose server-side
|
// DueForLatestCheck returns one Site's series whose server-side
|
||||||
// latest-chapter check has aged past cutoffMs, ordered by how many bookmarks
|
// latest-chapter check has aged past cutoffMs, ordered by how many bookmarks
|
||||||
// reference them (descending) then least-recently-checked first. One Site per
|
// reference them (descending) then least-recently-checked first. One Site per
|
||||||
@@ -1474,12 +1302,10 @@ func (s *Store) ClearNotice(condition, site string) error {
|
|||||||
//
|
//
|
||||||
// A forced Series (force_poll_at newer than latest_checked_at, issue #146)
|
// A forced Series (force_poll_at newer than latest_checked_at, issue #146)
|
||||||
// overrides exactly three gates: the rest cutoff, the Sighting-deferral
|
// overrides exactly three gates: the rest cutoff, the Sighting-deferral
|
||||||
// clause and a finished Series. It never overrides an empty series_url or the
|
// clause and the finished-only bucket. It never overrides an empty
|
||||||
// Bookmarks join — nothing to fetch, and no consumer for the result — so
|
// series_url or the Bookmarks join — nothing to fetch, and no consumer for
|
||||||
// those stay unconditional, and it never clears the finish: nothing here
|
// the result — so those stay unconditional. Forced rows sort to the front of
|
||||||
// writes finished_at, and pending force clears itself when the pass stamps
|
// the queue; the reader-count-then-age ordering among the rest is ADR-0003.
|
||||||
// the check timestamp. Forced rows sort to the front of the queue; the
|
|
||||||
// reader-count-then-age ordering among the rest is ADR-0003.
|
|
||||||
//
|
//
|
||||||
// The reader_count ordering is the point of the split (ADR-0003): a series
|
// The reader_count ordering is the point of the split (ADR-0003): a series
|
||||||
// shared by several readers is fetched once per due cycle, and the popular
|
// shared by several readers is fetched once per due cycle, and the popular
|
||||||
@@ -1487,15 +1313,14 @@ func (s *Store) ClearNotice(condition, site string) error {
|
|||||||
// reader count, oldest-first keeps the poll fair when the backlog outgrows
|
// reader count, oldest-first keeps the poll fair when the backlog outgrows
|
||||||
// throughput: the most neglected series is always next, so a large collection
|
// throughput: the most neglected series is always next, so a large collection
|
||||||
// refreshes uniformly slower rather than leaving a tail that never refreshes
|
// refreshes uniformly slower rather than leaving a tail that never refreshes
|
||||||
// at all. The userscript sorts its own queue the same way.
|
// at all. The userscript sorts its own queue the same way (L453).
|
||||||
//
|
//
|
||||||
// Series with no series_url are skipped — there is nothing to fetch, which is
|
// Series with no series_url are skipped — there is nothing to fetch, which is
|
||||||
// the same filter the userscript applies before refreshing. A finished Series is
|
// the same filter the userscript applies at L452. Series whose only bookmarks
|
||||||
// skipped unless forced: nothing more is coming, so fetching it only burns
|
// are finished are skipped too: nothing more is coming, so fetching them only
|
||||||
// requests (issue #157). Archived bookmarks still count — knowing what a
|
// burns requests. Archived bookmarks still count — knowing what a shelved
|
||||||
// shelved series is up to is the whole reason for archiving instead of
|
// series is up to is the whole reason for archiving instead of deleting.
|
||||||
// deleting. A series with no bookmarks at all never appears: the join
|
// A series with no bookmarks at all never appears: the join excludes it.
|
||||||
// excludes it.
|
|
||||||
//
|
//
|
||||||
// ceilingMs is the Sighting deferral ceiling (issue #103): a Series whose last
|
// ceilingMs is the Sighting deferral ceiling (issue #103): a Series whose last
|
||||||
// real Poll is older than it appears however recently it was sighted. That is
|
// real Poll is older than it appears however recently it was sighted. That is
|
||||||
@@ -1504,10 +1329,10 @@ func (s *Store) ClearNotice(condition, site string) error {
|
|||||||
// decided here, from two facts the query already computes, so a Lane gains no
|
// decided here, from two facts the query already computes, so a Lane gains no
|
||||||
// query per round: a Sighting younger than cutoffMs holds the Series back, but
|
// query per round: a Sighting younger than cutoffMs holds the Series back, but
|
||||||
// only while COUNT(*) is 1. A Series a second Reader bookmarks is Polled on
|
// only while COUNT(*) is 1. A Series a second Reader bookmarks is Polled on
|
||||||
// the schedule, so a wrong value the guild can see is corrected by a check
|
// schedule, so a wrong value the whole guild can see is corrected by a check
|
||||||
// that was never postponed; on a solitary Series the only person a wrong
|
// that was never postponed; on a solitary Series the only person a wrong value
|
||||||
// value reaches is the Reader who reported it. Whether the reporting Reader
|
// reaches is the Reader who reported it. Whether the reporting Reader is
|
||||||
// is allowed to defer at all was settled when the Sighting was recorded — see
|
// allowed to defer at all was settled when the Sighting was recorded — see
|
||||||
// RecordSighting.
|
// RecordSighting.
|
||||||
func (s *Store) DueForLatestCheck(site string, cutoffMs, ceilingMs int64) ([]Series, error) {
|
func (s *Store) DueForLatestCheck(site string, cutoffMs, ceilingMs int64) ([]Series, error) {
|
||||||
rows, err := s.db.Query(`SELECT `+seriesColumns+`,
|
rows, err := s.db.Query(`SELECT `+seriesColumns+`,
|
||||||
@@ -1519,11 +1344,12 @@ func (s *Store) DueForLatestCheck(site string, cutoffMs, ceilingMs int64) ([]Ser
|
|||||||
AND s.series_url <> ''
|
AND s.series_url <> ''
|
||||||
AND (s.latest_checked_at <= $2::bigint
|
AND (s.latest_checked_at <= $2::bigint
|
||||||
OR s.force_poll_at > s.latest_checked_at)
|
OR s.force_poll_at > s.latest_checked_at)
|
||||||
AND (s.finished_at = 0 OR s.force_poll_at > s.latest_checked_at)
|
|
||||||
GROUP BY s.site, s.series_id, s.title, s.series_url, s.cover,
|
GROUP BY s.site, s.series_id, s.title, s.series_url, s.cover,
|
||||||
s.kind, s.latest_chapter, s.latest_chapter_num, s.latest_checked_at,
|
s.kind, s.latest_chapter, s.latest_chapter_num, s.latest_checked_at,
|
||||||
s.site_completed_at, s.force_poll_at, s.finished_at
|
s.force_poll_at
|
||||||
HAVING (COUNT(*) > 1
|
HAVING (COUNT(*) FILTER (WHERE b.status <> 'finished') > 0
|
||||||
|
OR s.force_poll_at > s.latest_checked_at)
|
||||||
|
AND (COUNT(*) > 1
|
||||||
OR s.latest_sighted_at <= $2::bigint
|
OR s.latest_sighted_at <= $2::bigint
|
||||||
OR s.latest_checked_at <= $3::bigint
|
OR s.latest_checked_at <= $3::bigint
|
||||||
OR s.force_poll_at > s.latest_checked_at)
|
OR s.force_poll_at > s.latest_checked_at)
|
||||||
@@ -1545,18 +1371,14 @@ func (s *Store) DueForLatestCheck(site string, cutoffMs, ceilingMs int64) ([]Ser
|
|||||||
return out, rows.Err()
|
return out, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
// EligibleSeriesCount returns how many of a Site's Series are not finished —
|
// EligibleSeriesCount returns how many of a Site's Series still have at least
|
||||||
// the flag, never a Reader vote. It is the denominator of the Lane's pace
|
// one bookmark outside the finished bucket. It is the denominator of the
|
||||||
// (issue #100): the effective gap is the smaller of the registry gap and one
|
// Lane's pace (issue #100): the effective gap is the smaller of the registry
|
||||||
// hour divided by this count, so Series that will never be Polled do not make
|
// gap and one hour divided by this count, so Series that will never be Polled
|
||||||
// the Lane faster than it needs to be, and counting every eligible Series
|
// do not make the Lane faster than it needs to be, and counting every eligible
|
||||||
// rather than only those currently due keeps the pace steady — the single
|
// Series rather than only those currently due keeps the pace steady — the
|
||||||
// worst moment to be fastest is startup, when everything is due at once.
|
// single worst moment to be fastest is startup, when everything is due at
|
||||||
//
|
// once.
|
||||||
// The deliberate asymmetry with DueForLatestCheck's WHERE: a forced Series
|
|
||||||
// is due but never admitted here, because a forced pass must not speed up
|
|
||||||
// every other fetch on the Site — one impassioned press is not a reason to
|
|
||||||
// hammer the Site (issue #157).
|
|
||||||
func (s *Store) EligibleSeriesCount(site string) (int, error) {
|
func (s *Store) EligibleSeriesCount(site string) (int, error) {
|
||||||
var n int
|
var n int
|
||||||
err := s.db.QueryRow(`SELECT COUNT(*) FROM (
|
err := s.db.QueryRow(`SELECT COUNT(*) FROM (
|
||||||
@@ -1564,8 +1386,8 @@ func (s *Store) EligibleSeriesCount(site string) (int, error) {
|
|||||||
FROM series s
|
FROM series s
|
||||||
JOIN bookmarks b ON b.site = s.site AND b.series_id = s.series_id
|
JOIN bookmarks b ON b.site = s.site AND b.series_id = s.series_id
|
||||||
WHERE s.site = $1
|
WHERE s.site = $1
|
||||||
AND s.finished_at = 0
|
|
||||||
GROUP BY s.site, s.series_id
|
GROUP BY s.site, s.series_id
|
||||||
|
HAVING COUNT(*) FILTER (WHERE b.status <> 'finished') > 0
|
||||||
) e`, site).Scan(&n)
|
) e`, site).Scan(&n)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, fmt.Errorf("count eligible series %s: %w", site, err)
|
return 0, fmt.Errorf("count eligible series %s: %w", site, err)
|
||||||
@@ -1611,21 +1433,6 @@ func (s *Store) ForceSeriesPoll(site, seriesID string, at int64) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetSeriesFinished stamps or clears the owner's finish. at is unix ms to
|
|
||||||
// finish, zero to un-finish. A finished Series drops out of the Lane's reads
|
|
||||||
// (issue #157), and nothing else writes this column: it is the only writer
|
|
||||||
// outside migration 0016, so a machine write can never retire a Series
|
|
||||||
// silently. Touching a missing series is not an error: the row may have been
|
|
||||||
// orphaned, and the caller's read decides what exists.
|
|
||||||
func (s *Store) SetSeriesFinished(site, seriesID string, at int64) error {
|
|
||||||
if _, err := s.db.Exec(
|
|
||||||
`UPDATE series SET finished_at = $1 WHERE site = $2 AND series_id = $3`,
|
|
||||||
at, site, seriesID); err != nil {
|
|
||||||
return fmt.Errorf("set series finished %s:%s: %w", site, seriesID, err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// LatestCheckedAt reads the column MarkLatestChecked writes. It exists for
|
// LatestCheckedAt reads the column MarkLatestChecked writes. It exists for
|
||||||
// tests outside this package (the poller's own tests assert on rest
|
// tests outside this package (the poller's own tests assert on rest
|
||||||
// bookkeeping) — see MarkLatestChecked for why the field stays off the
|
// bookkeeping) — see MarkLatestChecked for why the field stays off the
|
||||||
@@ -1657,22 +1464,6 @@ func (s *Store) SetLatestChapter(site, seriesID, label string, num float64) erro
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetSiteCompletedAt stores when the last successful read saw the Site's
|
|
||||||
// completed value, zero meaning it did not. Series-level, like the Latest
|
|
||||||
// Chapter: it is a fact about the work, not about one Reader's bookmark, and
|
|
||||||
// the bookmark's updated_at is never touched — this is not reading progress
|
|
||||||
// and must not reorder any Reader's list, the same rule SetLatestChapter's
|
|
||||||
// comment states. Touching a missing series is not an error: the row may
|
|
||||||
// have been orphaned, and the caller's read decides what exists.
|
|
||||||
func (s *Store) SetSiteCompletedAt(site, seriesID string, at int64) error {
|
|
||||||
if _, err := s.db.Exec(
|
|
||||||
`UPDATE series SET site_completed_at = $1 WHERE site = $2 AND series_id = $3`,
|
|
||||||
at, site, seriesID); err != nil {
|
|
||||||
return fmt.Errorf("set site completed %s:%s: %w", site, seriesID, err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetSeriesURL stores the owner's repair for a Series' source address
|
// SetSeriesURL stores the owner's repair for a Series' source address
|
||||||
// (issue #151): the one write that lifts the write-once rule documented on
|
// (issue #151): the one write that lifts the write-once rule documented on
|
||||||
// Series.SeriesURL. It is a store, not a verification — the caller has
|
// Series.SeriesURL. It is a store, not a verification — the caller has
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import (
|
|||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"errors"
|
"errors"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
"fmt"
|
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strconv"
|
"strconv"
|
||||||
@@ -280,27 +279,6 @@ func seedForCheck(t *testing.T, s *Store, key, seriesURL string, checkedAt int64
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// seedFinished inserts a bookmark (and with it its series) and stamps the
|
|
||||||
// series finished — the series-level fact the due gate reads (issue #157).
|
|
||||||
func seedFinished(t *testing.T, s *Store, key, seriesURL string) {
|
|
||||||
t.Helper()
|
|
||||||
site, seriesID, ok := strings.Cut(key, ":")
|
|
||||||
if !ok {
|
|
||||||
t.Fatalf("key %q: no ':' separator", key)
|
|
||||||
}
|
|
||||||
if _, err := s.Upsert(s.OwnerID(), Bookmark{
|
|
||||||
Key: key, Site: site, SeriesID: seriesID, SeriesURL: seriesURL,
|
|
||||||
UpdatedAt: 1000,
|
|
||||||
}); err != nil {
|
|
||||||
t.Fatalf("seed %q: %v", key, err)
|
|
||||||
}
|
|
||||||
if _, err := s.db.Exec(
|
|
||||||
`UPDATE series SET finished_at = 1000 WHERE site = $1 AND series_id = $2`,
|
|
||||||
site, seriesID); err != nil {
|
|
||||||
t.Fatalf("seed finish %q: %v", key, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// noCeiling is a Sighting deferral ceiling no Series can reach, for the tests
|
// noCeiling is a Sighting deferral ceiling no Series can reach, for the tests
|
||||||
// that predate the ceiling and are about rest, ordering or buckets instead.
|
// that predate the ceiling and are about rest, ordering or buckets instead.
|
||||||
const noCeiling = int64(-1)
|
const noCeiling = int64(-1)
|
||||||
@@ -508,15 +486,24 @@ func TestUpsertStatusChangeKeepsUpdatedAt(t *testing.T) {
|
|||||||
t.Fatalf("UpdatedAt = %d, want it frozen at %d", stored.UpdatedAt, first.UpdatedAt)
|
t.Fatalf("UpdatedAt = %d, want it frozen at %d", stored.UpdatedAt, first.UpdatedAt)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Archiving is the reason to keep polling — the point is to come back to a
|
// Archiving is the reason to keep polling — the point is to come back to a
|
||||||
// series that has moved on. A finished series has nothing left to publish,
|
// series that has moved on. A finished series has nothing left to publish.
|
||||||
// whichever Reader marked it (issue #157).
|
|
||||||
func TestDueForLatestCheckSkipsFinishedKeepsArchived(t *testing.T) {
|
func TestDueForLatestCheckSkipsFinishedKeepsArchived(t *testing.T) {
|
||||||
store := newTestStore(t)
|
store := newTestStore(t)
|
||||||
for _, key := range []string{"asura:reading", "asura:archived"} {
|
for _, tc := range []struct{ key, status string }{
|
||||||
seedForCheck(t, store, key, "https://asurascans.com/comics/"+key, 0)
|
{"asura:reading", StatusReading},
|
||||||
|
{"asura:archived", StatusArchived},
|
||||||
|
{"asura:finished", StatusFinished},
|
||||||
|
} {
|
||||||
|
if _, err := store.Upsert(store.OwnerID(), Bookmark{
|
||||||
|
Key: tc.key, Site: "asura", SeriesID: strings.TrimPrefix(tc.key, "asura:"),
|
||||||
|
SeriesURL: "https://asurascans.com/comics/" + tc.key,
|
||||||
|
Status: tc.status, UpdatedAt: time.Now().UnixMilli(),
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("seed %s: %v", tc.key, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
seedFinished(t, store, "asura:finished", "https://asurascans.com/comics/asura:finished")
|
|
||||||
|
|
||||||
due, err := store.DueForLatestCheck("asura", time.Now().UnixMilli(), noCeiling)
|
due, err := store.DueForLatestCheck("asura", time.Now().UnixMilli(), noCeiling)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -535,26 +522,27 @@ func TestDueForLatestCheckSkipsFinishedKeepsArchived(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The gap's denominator counts every Series the Lane will ever Poll: a
|
// The gap's denominator counts every Series the Lane will ever Poll: a
|
||||||
// finished Series must not make the Lane faster than it needs to be, another
|
// finished Series must not make the Lane faster than it needs to be, and
|
||||||
// Site's Series must not leak into this Site's count, and a forced Series is
|
// another Site's Series must not leak into this Site's count.
|
||||||
// not admitted either — it is due once, not a reason to tighten the pace for
|
|
||||||
// every other fetch on the Site (issue #157).
|
|
||||||
func TestEligibleSeriesCount(t *testing.T) {
|
func TestEligibleSeriesCount(t *testing.T) {
|
||||||
store := newTestStore(t)
|
store := newTestStore(t)
|
||||||
seedForCheck(t, store, "asura:reading", "https://asurascans.com/comics/reading", 0)
|
seedForCheck(t, store, "asura:reading", "https://asurascans.com/comics/reading", 0)
|
||||||
seedForCheck(t, store, "asura:archived", "https://asurascans.com/comics/archived", 0)
|
seedForCheck(t, store, "asura:archived", "https://asurascans.com/comics/archived", 0)
|
||||||
seedFinished(t, store, "asura:finished", "https://asurascans.com/comics/asura:finished")
|
if _, err := store.Upsert(store.OwnerID(), Bookmark{
|
||||||
seedForCheck(t, store, "demonic:z", "https://demonicscans.org/manga/z", 0)
|
Key: "asura:finished", Site: "asura", SeriesID: "finished",
|
||||||
if err := store.ForceSeriesPoll("asura", "archived", 5000); err != nil {
|
SeriesURL: "https://asurascans.com/comics/finished",
|
||||||
t.Fatalf("ForceSeriesPoll: %v", err)
|
Status: StatusFinished, UpdatedAt: 1000,
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("seed finished: %v", err)
|
||||||
}
|
}
|
||||||
|
seedForCheck(t, store, "demonic:z", "https://demonicscans.org/manga/z", 0)
|
||||||
|
|
||||||
n, err := store.EligibleSeriesCount("asura")
|
n, err := store.EligibleSeriesCount("asura")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("EligibleSeriesCount: %v", err)
|
t.Fatalf("EligibleSeriesCount: %v", err)
|
||||||
}
|
}
|
||||||
if n != 2 {
|
if n != 2 {
|
||||||
t.Fatalf("eligible = %d, want 2 (finished and forced excluded, demonic excluded)", n)
|
t.Fatalf("eligible = %d, want 2 (finished excluded, demonic excluded)", n)
|
||||||
}
|
}
|
||||||
n, err = store.EligibleSeriesCount("demonic")
|
n, err = store.EligibleSeriesCount("demonic")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -767,133 +755,6 @@ func TestMigration0008DropsLegacyCoverRows(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 0016's three statements are order-dependent: the finished_at seed must see
|
|
||||||
// the pre-flip 'finished' buckets, and the flip must come after it. A seed
|
|
||||||
// that ran after the flip would read bookmarks that no longer say
|
|
||||||
// 'finished', declare nothing finished, and silently resume polling series
|
|
||||||
// somebody marked done. This seeds a pre-0016 database the way every
|
|
||||||
// deployment looked — finished a bookmark bucket, no finished_at column —
|
|
||||||
// runs the migration, and asserts on what it preserved.
|
|
||||||
func TestMigration0016SeedsFinishedAtBeforeFlippingBucket(t *testing.T) {
|
|
||||||
url := pgtest.URL(t)
|
|
||||||
db, err := sql.Open("pgx", url)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("open: %v", err)
|
|
||||||
}
|
|
||||||
defer db.Close()
|
|
||||||
|
|
||||||
if err := migrate(db, 15); err != nil {
|
|
||||||
t.Fatalf("migrate to 0015: %v", err)
|
|
||||||
}
|
|
||||||
if err := seedOwner(db, testOwner); err != nil {
|
|
||||||
t.Fatalf("seed owner: %v", err)
|
|
||||||
}
|
|
||||||
// A second reader, so "mixed" can carry two bookmarks on one series.
|
|
||||||
if _, err := db.Exec(
|
|
||||||
`INSERT INTO readers (discord_id, token_sha256) VALUES ('second', '\x01'::bytea)`); err != nil {
|
|
||||||
t.Fatalf("seed second reader: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
owner := func() int64 {
|
|
||||||
t.Helper()
|
|
||||||
var id int64
|
|
||||||
if err := db.QueryRow(
|
|
||||||
`SELECT id FROM readers WHERE discord_id = $1`, testOwner.DiscordID).Scan(&id); err != nil {
|
|
||||||
t.Fatalf("owner id: %v", err)
|
|
||||||
}
|
|
||||||
return id
|
|
||||||
}()
|
|
||||||
seedBookmark := func(readerID int64, site, seriesID, status string) {
|
|
||||||
t.Helper()
|
|
||||||
// The bookmark FK demands the series row; Upsert would create it on
|
|
||||||
// the fly, raw SQL has to spell it out.
|
|
||||||
if _, err := db.Exec(
|
|
||||||
`INSERT INTO series (site, series_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
|
|
||||||
site, seriesID); err != nil {
|
|
||||||
t.Fatalf("seed series %s:%s: %v", site, seriesID, err)
|
|
||||||
}
|
|
||||||
if _, err := db.Exec(
|
|
||||||
`INSERT INTO bookmarks (reader_id, site, series_id, status, updated_at)
|
|
||||||
VALUES ($1, $2, $3, $4, 1000)`, readerID, site, seriesID, status); err != nil {
|
|
||||||
t.Fatalf("seed %s:%s/%s: %v", site, seriesID, status, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// done: the one-bookmark series every finished series looked like.
|
|
||||||
seedBookmark(owner, "asura", "done", "finished")
|
|
||||||
// shared: every reader finished — the multi-reader equivalent.
|
|
||||||
seedBookmark(owner, "asura", "shared", "finished")
|
|
||||||
// mixed: a second reader still reading keeps the series alive.
|
|
||||||
seedBookmark(owner, "asura", "mixed", "finished")
|
|
||||||
seedBookmark(owner+1, "asura", "mixed", "archived")
|
|
||||||
// live: nobody finished it.
|
|
||||||
seedBookmark(owner, "asura", "live", "reading")
|
|
||||||
// orphan: no bookmarks at all, nothing to decide from.
|
|
||||||
if _, err := db.Exec(
|
|
||||||
`INSERT INTO series (site, series_id) VALUES ('asura', 'orphan')`); err != nil {
|
|
||||||
t.Fatalf("seed orphan: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := migrate(db, 0); err != nil {
|
|
||||||
t.Fatalf("migrate 0016: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
finishedAt := func(site, seriesID string) int64 {
|
|
||||||
t.Helper()
|
|
||||||
var at int64
|
|
||||||
if err := db.QueryRow(
|
|
||||||
`SELECT finished_at FROM series WHERE site = $1 AND series_id = $2`,
|
|
||||||
site, seriesID).Scan(&at); err != nil {
|
|
||||||
t.Fatalf("finished_at %s:%s: %v", site, seriesID, err)
|
|
||||||
}
|
|
||||||
return at
|
|
||||||
}
|
|
||||||
status := func(readerID int64, site, seriesID string) string {
|
|
||||||
t.Helper()
|
|
||||||
var s string
|
|
||||||
if err := db.QueryRow(
|
|
||||||
`SELECT status FROM bookmarks WHERE reader_id = $1
|
|
||||||
AND site = $2 AND series_id = $3`, readerID, site, seriesID).Scan(&s); err != nil {
|
|
||||||
t.Fatalf("status %s:%s: %v", site, seriesID, err)
|
|
||||||
}
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
|
|
||||||
// The seed ran before the flip: had the flip gone first, done's bookmarks
|
|
||||||
// would read archived and nothing would be stamped. The stamp is a real
|
|
||||||
// timestamp, not a sentinel.
|
|
||||||
before := time.Now().Add(-time.Minute).UnixMilli()
|
|
||||||
after := time.Now().Add(time.Minute).UnixMilli()
|
|
||||||
for _, sr := range []struct{ site, seriesID string }{
|
|
||||||
{"asura", "done"}, {"asura", "shared"},
|
|
||||||
} {
|
|
||||||
if at := finishedAt(sr.site, sr.seriesID); at < before || at > after {
|
|
||||||
t.Fatalf("%s:%s finished_at = %d, want now-ish", sr.site, sr.seriesID, at)
|
|
||||||
}
|
|
||||||
// The flip followed the seed: every finished bookmark is archived.
|
|
||||||
if s := status(owner, sr.site, sr.seriesID); s != StatusArchived {
|
|
||||||
t.Fatalf("%s:%s status = %q, want archived after the flip", sr.site, sr.seriesID, s)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// The seed ignores a series any bookmark keeps alive.
|
|
||||||
if at := finishedAt("asura", "mixed"); at != 0 {
|
|
||||||
t.Fatalf("mixed finished_at = %d, want 0", at)
|
|
||||||
}
|
|
||||||
// The flip is a bucket rewrite, not a series-wide one: the finished
|
|
||||||
// bookmark becomes archived and the sibling rows keep their buckets.
|
|
||||||
if s := status(owner, "asura", "mixed"); s != StatusArchived {
|
|
||||||
t.Fatalf("mixed finished bookmark = %q, want archived", s)
|
|
||||||
}
|
|
||||||
if s := status(owner+1, "asura", "mixed"); s != StatusArchived {
|
|
||||||
t.Fatalf("mixed archived bookmark = %q, want untouched archived", s)
|
|
||||||
}
|
|
||||||
if s := status(owner, "asura", "live"); s != StatusReading {
|
|
||||||
t.Fatalf("live status = %q, want untouched reading", s)
|
|
||||||
}
|
|
||||||
if at := finishedAt("asura", "orphan"); at != 0 {
|
|
||||||
t.Fatalf("orphan finished_at = %d, want 0", at)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// readSeries reads the series row directly, for asserting on what Upsert
|
// readSeries reads the series row directly, for asserting on what Upsert
|
||||||
// actually stored rather than what the joined Bookmark reports.
|
// actually stored rather than what the joined Bookmark reports.
|
||||||
func readSeries(t *testing.T, s *Store, site, seriesID string) Series {
|
func readSeries(t *testing.T, s *Store, site, seriesID string) Series {
|
||||||
@@ -935,37 +796,6 @@ func TestUpsertCreatesSeriesFromClient(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The wire's finished flag is derived, never stored: the Upsert's explicit
|
|
||||||
// column list does not name finished_at — the same omission that protects
|
|
||||||
// cover — so a client echoing a cached flag, true or false, cannot change the
|
|
||||||
// Series' retired state (issues #157, #160).
|
|
||||||
func TestUpsertCannotWriteSeriesFinished(t *testing.T) {
|
|
||||||
store := newTestStore(t)
|
|
||||||
seedFinished(t, store, "asura:done", "https://asurascans.com/comics/asura:done")
|
|
||||||
|
|
||||||
for _, sent := range []bool{true, false} {
|
|
||||||
stored, err := store.Upsert(store.OwnerID(), Bookmark{
|
|
||||||
Key: "asura:done", Site: "asura", SeriesID: "done",
|
|
||||||
Finished: sent, UpdatedAt: 2000,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Upsert(Finished: %v): %v", sent, err)
|
|
||||||
}
|
|
||||||
if !stored.Finished {
|
|
||||||
t.Fatalf("stored.Finished = false after echoing %v, want true", sent)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var finishedAt int64
|
|
||||||
if err := store.db.QueryRow(
|
|
||||||
`SELECT finished_at FROM series WHERE site = $1 AND series_id = $2`,
|
|
||||||
"asura", "done").Scan(&finishedAt); err != nil {
|
|
||||||
t.Fatalf("read finished_at: %v", err)
|
|
||||||
}
|
|
||||||
if finishedAt != 1000 {
|
|
||||||
t.Fatalf("series.finished_at = %v, want the seeded 1000 untouched", finishedAt)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The hook is what starts creation-time acquisition, so it must fire exactly
|
// The hook is what starts creation-time acquisition, so it must fire exactly
|
||||||
// once per Series — on the PUT that created it, and on no later one, whichever
|
// once per Series — on the PUT that created it, and on no later one, whichever
|
||||||
// Reader sends it.
|
// Reader sends it.
|
||||||
@@ -1979,12 +1809,19 @@ func TestDueForLatestCheckForcedOverridesSightingDeferral(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The finished flag excludes a series; a forced request overrides it — the
|
// The finished-only bucket excludes a series whose only bookmarks are
|
||||||
// owner asked, so the Lane looks.
|
// finished; a forced request overrides it — the owner asked, so the Lane
|
||||||
func TestDueForLatestCheckForcedOverridesFinishedFlag(t *testing.T) {
|
// looks.
|
||||||
|
func TestDueForLatestCheckForcedOverridesFinishedBucket(t *testing.T) {
|
||||||
s := newTestStore(t)
|
s := newTestStore(t)
|
||||||
seedForCheck(t, s, "asura:reading", "https://asurascans.com/comics/reading", 0)
|
seedForCheck(t, s, "asura:reading", "https://asurascans.com/comics/reading", 0)
|
||||||
seedFinished(t, s, "asura:finished", "https://asurascans.com/comics/asura:finished")
|
if _, err := s.Upsert(s.OwnerID(), Bookmark{
|
||||||
|
Key: "asura:finished", Site: "asura", SeriesID: "finished",
|
||||||
|
SeriesURL: "https://asurascans.com/comics/finished",
|
||||||
|
Status: StatusFinished, UpdatedAt: 1000,
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("seed finished: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
due, err := s.DueForLatestCheck("asura", 1000, noCeiling)
|
due, err := s.DueForLatestCheck("asura", 1000, noCeiling)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -2612,288 +2449,3 @@ func TestRemoveSeriesMissingKeyIsCleanNoOp(t *testing.T) {
|
|||||||
t.Fatalf("RemoveSeries on a missing key = %v, want nil", err)
|
t.Fatalf("RemoveSeries on a missing key = %v, want nil", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// The failure row's existence is the failure state (ADR-0016):
|
|
||||||
// RecordSeriesFailure upserts the outcome word, keeps the original
|
|
||||||
// failing_since through a word change, and an unchanged word writes nothing
|
|
||||||
// at all — a broken Series costs the same as a healthy one every hour.
|
|
||||||
func TestRecordSeriesFailureUpsertKeepsFailingSince(t *testing.T) {
|
|
||||||
s := newTestStore(t)
|
|
||||||
seedForCheck(t, s, "asura:solo", "https://asurascans.com/comics/solo", 0)
|
|
||||||
|
|
||||||
if err := s.RecordSeriesFailure("asura", "solo", "not_found", 1000); err != nil {
|
|
||||||
t.Fatalf("record: %v", err)
|
|
||||||
}
|
|
||||||
word, since, found := failureRow(t, s, "asura", "solo")
|
|
||||||
if !found || word != "not_found" || since != 1000 {
|
|
||||||
t.Fatalf("row after create = (%q, %d, %v), want (not_found, 1000, true)", word, since, found)
|
|
||||||
}
|
|
||||||
|
|
||||||
// A changed word updates the outcome and never touches failing_since.
|
|
||||||
if err := s.RecordSeriesFailure("asura", "solo", "errors", 2000); err != nil {
|
|
||||||
t.Fatalf("record changed word: %v", err)
|
|
||||||
}
|
|
||||||
word, since, found = failureRow(t, s, "asura", "solo")
|
|
||||||
if !found || word != "errors" || since != 1000 {
|
|
||||||
t.Fatalf("row after word change = (%q, %d, %v), want (errors, 1000, true)", word, since, found)
|
|
||||||
}
|
|
||||||
|
|
||||||
// An identical word writes nothing: the stamp survives a later now.
|
|
||||||
if err := s.RecordSeriesFailure("asura", "solo", "errors", 3000); err != nil {
|
|
||||||
t.Fatalf("record identical word: %v", err)
|
|
||||||
}
|
|
||||||
word, since, found = failureRow(t, s, "asura", "solo")
|
|
||||||
if !found || word != "errors" || since != 1000 {
|
|
||||||
t.Fatalf("row after identical word = (%q, %d, %v), want the earlier (errors, 1000, true)", word, since, found)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ClearSeriesFailure deletes the row, and a row that is not there is not an
|
|
||||||
// error — the poller clears on every successful read, so most clears find
|
|
||||||
// nothing.
|
|
||||||
func TestClearSeriesFailure(t *testing.T) {
|
|
||||||
s := newTestStore(t)
|
|
||||||
seedForCheck(t, s, "asura:solo", "https://asurascans.com/comics/solo", 0)
|
|
||||||
|
|
||||||
if err := s.ClearSeriesFailure("asura", "solo"); err != nil {
|
|
||||||
t.Fatalf("clear a missing row: %v, want nil", err)
|
|
||||||
}
|
|
||||||
if err := s.RecordSeriesFailure("asura", "solo", "not_found", 1000); err != nil {
|
|
||||||
t.Fatalf("record: %v", err)
|
|
||||||
}
|
|
||||||
if err := s.ClearSeriesFailure("asura", "solo"); err != nil {
|
|
||||||
t.Fatalf("clear: %v", err)
|
|
||||||
}
|
|
||||||
if _, _, found := failureRow(t, s, "asura", "solo"); found {
|
|
||||||
t.Fatal("row after clear: still present")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deleting a Series takes its failure row with it (the composite FK's
|
|
||||||
// cascade), so orphan removal stays a single statement.
|
|
||||||
func TestRemoveSeriesCascadesToFailureRow(t *testing.T) {
|
|
||||||
s := newTestStore(t)
|
|
||||||
seedForCheck(t, s, "asura:solo", "https://asurascans.com/comics/solo", 0)
|
|
||||||
if err := s.RecordSeriesFailure("asura", "solo", "not_found", 1000); err != nil {
|
|
||||||
t.Fatalf("record: %v", err)
|
|
||||||
}
|
|
||||||
if err := s.Delete(s.OwnerID(), "asura:solo"); err != nil {
|
|
||||||
t.Fatalf("delete bookmark: %v", err)
|
|
||||||
}
|
|
||||||
if err := s.RemoveSeries("asura", "solo"); err != nil {
|
|
||||||
t.Fatalf("RemoveSeries: %v", err)
|
|
||||||
}
|
|
||||||
if _, _, found := failureRow(t, s, "asura", "solo"); found {
|
|
||||||
t.Fatal("failure row after series delete: still present (no cascade)")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// failureRow reads one Series' failure row as stored.
|
|
||||||
func failureRow(t *testing.T, s *Store, site, seriesID string) (word string, since int64, found bool) {
|
|
||||||
t.Helper()
|
|
||||||
err := s.db.QueryRow(
|
|
||||||
`SELECT outcome, failing_since FROM poll_failures WHERE site = $1 AND series_id = $2`,
|
|
||||||
site, seriesID).Scan(&word, &since)
|
|
||||||
if errors.Is(err, sql.ErrNoRows) {
|
|
||||||
return "", 0, false
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("read failure row %s:%s: %v", site, seriesID, err)
|
|
||||||
}
|
|
||||||
return word, since, true
|
|
||||||
}
|
|
||||||
|
|
||||||
// Owner notices are one row per episode: the row's presence is the whole
|
|
||||||
// state. MarkNoticeSent stamps it, NoticeSent reads it, and ClearNotice
|
|
||||||
// forgets it — including a row that was never there, which is not an error.
|
|
||||||
func TestOwnerNoticeRows(t *testing.T) {
|
|
||||||
s := newTestStore(t)
|
|
||||||
|
|
||||||
if sent, err := s.NoticeSent("stall", "comix"); err != nil || sent {
|
|
||||||
t.Fatalf("NoticeSent on a fresh table = %v, %v; want false, nil", sent, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := s.MarkNoticeSent("stall", "comix", 4242); err != nil {
|
|
||||||
t.Fatalf("MarkNoticeSent: %v", err)
|
|
||||||
}
|
|
||||||
if sent, err := s.NoticeSent("stall", "comix"); err != nil || !sent {
|
|
||||||
t.Fatalf("NoticeSent after mark = %v, %v; want true, nil", sent, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Re-marking the same episode just moves the stamp: the row is a lock,
|
|
||||||
// not a log. A different site is its own episode — the key is
|
|
||||||
// (condition, site).
|
|
||||||
if err := s.MarkNoticeSent("stall", "comix", 4343); err != nil {
|
|
||||||
t.Fatalf("re-mark: %v", err)
|
|
||||||
}
|
|
||||||
if sent, err := s.NoticeSent("stall", "kagane"); err != nil || sent {
|
|
||||||
t.Fatalf("NoticeSent on another site = %v, %v; want false, nil", sent, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := s.ClearNotice("stall", "comix"); err != nil {
|
|
||||||
t.Fatalf("ClearNotice: %v", err)
|
|
||||||
}
|
|
||||||
if sent, err := s.NoticeSent("stall", "comix"); err != nil || sent {
|
|
||||||
t.Fatalf("NoticeSent after clear = %v, %v; want false, nil", sent, err)
|
|
||||||
}
|
|
||||||
if err := s.ClearNotice("stall", "comix"); err != nil {
|
|
||||||
t.Fatalf("ClearNotice on a missing row: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// RefusingSince reads one Site's current unbroken run of refusing passes
|
|
||||||
// (issue #172). A refusing pass is one the Lane gate returned early from
|
|
||||||
// (skip 'refusing') or one whose loop counted refusals (refused > 0) — the
|
|
||||||
// two shapes a persistently-challenged Site alternates between, so the run
|
|
||||||
// must not break when the gate row follows the refusal row. A Site whose
|
|
||||||
// latest pass did not refuse is absent, nothing after the caller's clock
|
|
||||||
// counts, and a run older than the log answers with the oldest row present.
|
|
||||||
func TestRefusingSince(t *testing.T) {
|
|
||||||
s := newTestStore(t)
|
|
||||||
seed := func(site string, ranAt int64, skip string, refused int) {
|
|
||||||
t.Helper()
|
|
||||||
if err := s.RecordLanePass(LanePass{Site: site, RanAt: ranAt, Skip: skip, Refused: refused}, -1); err != nil {
|
|
||||||
t.Fatalf("RecordLanePass(%s/%d): %v", site, ranAt, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// asura: a refusing run broken by a healthy pass, then resumed; the
|
|
||||||
// current run began at the pass after the break.
|
|
||||||
seed("asura", 100, "", 2)
|
|
||||||
seed("asura", 200, "", 0)
|
|
||||||
seed("asura", 300, "refusing", 0)
|
|
||||||
seed("asura", 400, "", 2)
|
|
||||||
// demonic: the latest pass is healthy — no run, absent.
|
|
||||||
seed("demonic", 100, "", 2)
|
|
||||||
seed("demonic", 200, "", 0)
|
|
||||||
// novelfull: a healthy pass after now must not break the run — the run
|
|
||||||
// is judged as of the caller's clock.
|
|
||||||
seed("novelfull", 100, "", 2)
|
|
||||||
seed("novelfull", 600, "", 0)
|
|
||||||
// comix: an unbroken run reaches back to the oldest row present.
|
|
||||||
seed("comix", 100, "", 2)
|
|
||||||
seed("comix", 200, "refusing", 0)
|
|
||||||
|
|
||||||
got, err := s.RefusingSince(450)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("RefusingSince: %v", err)
|
|
||||||
}
|
|
||||||
want := map[string]int64{"asura": 300, "novelfull": 100, "comix": 100}
|
|
||||||
if len(got) != len(want) {
|
|
||||||
t.Fatalf("RefusingSince = %v, want %v", got, want)
|
|
||||||
}
|
|
||||||
for site, since := range want {
|
|
||||||
if got[site] != since {
|
|
||||||
t.Fatalf("RefusingSince[%s] = %d, want %d (got %v)", site, got[site], since, got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if _, ok := got["demonic"]; ok {
|
|
||||||
t.Fatalf("RefusingSince names demonic, whose latest pass did not refuse: %v", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// SidecarOK reads, per Site, the most recent pass that actually reached the
|
|
||||||
// sidecar (issue #172): the pass ran its loop (skip '') and no read lost
|
|
||||||
// Chrome (unreachable 0). A challenge answer still reached the sidecar, a
|
|
||||||
// lost sidecar and every skip value did not, and a Site with no qualifying
|
|
||||||
// pass — an asleep Lane included — is absent.
|
|
||||||
func TestSidecarOK(t *testing.T) {
|
|
||||||
s := newTestStore(t)
|
|
||||||
seed := func(site string, ranAt int64, skip string, unreachable int) {
|
|
||||||
t.Helper()
|
|
||||||
if err := s.RecordLanePass(LanePass{Site: site, RanAt: ranAt, Skip: skip, Unreachable: unreachable}, -1); err != nil {
|
|
||||||
t.Fatalf("RecordLanePass(%s/%d): %v", site, ranAt, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// comix: only the skip='' unreachable=0 pass reached the sidecar; the
|
|
||||||
// mid-loop browser-loss row (skip '', unreachable > 0) and the skip
|
|
||||||
// values never did.
|
|
||||||
seed("comix", 100, "", 1)
|
|
||||||
seed("comix", 200, "sidecar-down", 0)
|
|
||||||
seed("comix", 300, "", 0)
|
|
||||||
seed("comix", 400, "refusing", 0)
|
|
||||||
// kagane: two passes reached the sidecar; the newest wins.
|
|
||||||
seed("kagane", 150, "", 0)
|
|
||||||
seed("kagane", 250, "", 0)
|
|
||||||
// novelfull: an asleep Lane never reached it.
|
|
||||||
seed("novelfull", 120, "asleep", 0)
|
|
||||||
|
|
||||||
got, err := s.SidecarOK([]string{"comix", "kagane", "novelfull", "lightnovelworld"})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("SidecarOK: %v", err)
|
|
||||||
}
|
|
||||||
want := map[string]int64{"comix": 300, "kagane": 250}
|
|
||||||
if len(got) != len(want) {
|
|
||||||
t.Fatalf("SidecarOK = %v, want %v", got, want)
|
|
||||||
}
|
|
||||||
for site, ranAt := range want {
|
|
||||||
if got[site] != ranAt {
|
|
||||||
t.Fatalf("SidecarOK[%s] = %d, want %d (got %v)", site, got[site], ranAt, got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, site := range []string{"novelfull", "lightnovelworld"} {
|
|
||||||
if _, ok := got[site]; ok {
|
|
||||||
t.Fatalf("SidecarOK names %s, which never reached the sidecar: %v", site, got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// NoChapterShare reads, per Site, the share of its Series holding a
|
|
||||||
// no-chapter failure row older than the cutoff (issue #172): old rows over
|
|
||||||
// the Site's whole Series count, so a four-Series Site and a 200-Series
|
|
||||||
// Site are judged on the same scale. A fresh no-chapter row and a row of
|
|
||||||
// any other outcome do not count.
|
|
||||||
func TestNoChapterShare(t *testing.T) {
|
|
||||||
s := newTestStore(t)
|
|
||||||
for i := 1; i <= 4; i++ {
|
|
||||||
seedForCheck(t, s, fmt.Sprintf("asura:a%d", i), fmt.Sprintf("https://asurascans.com/comics/a%d", i), 0)
|
|
||||||
}
|
|
||||||
seedForCheck(t, s, "comix:c1", "https://comix.to/title/c1", 0)
|
|
||||||
seedForCheck(t, s, "comix:c2", "https://comix.to/title/c2", 0)
|
|
||||||
seedForCheck(t, s, "demonic:d1", "https://demonicscans.org/series/d1", 0)
|
|
||||||
for i := 1; i <= 200; i++ {
|
|
||||||
seedForCheck(t, s, fmt.Sprintf("novelfull:n%d", i), fmt.Sprintf("https://novelfull.com/n%d.html", i), 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
const cutoff = 1000
|
|
||||||
oldNoChapter := func(site, seriesID string) {
|
|
||||||
t.Helper()
|
|
||||||
if err := s.RecordSeriesFailure(site, seriesID, "no_chapter", 100); err != nil {
|
|
||||||
t.Fatalf("seed no-chapter failure %s:%s: %v", site, seriesID, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// asura: three of four hold an old no-chapter row; the fourth's
|
|
||||||
// no-chapter row is fresh — it is not old, so it does not count.
|
|
||||||
oldNoChapter("asura", "a1")
|
|
||||||
oldNoChapter("asura", "a2")
|
|
||||||
oldNoChapter("asura", "a3")
|
|
||||||
if err := s.RecordSeriesFailure("asura", "a4", "no_chapter", 2000); err != nil {
|
|
||||||
t.Fatalf("seed fresh no-chapter failure: %v", err)
|
|
||||||
}
|
|
||||||
// comix: an old no-chapter row and an old errors row — the errors row
|
|
||||||
// is not a no-chapter row, so the share is 1/2, the exact boundary.
|
|
||||||
oldNoChapter("comix", "c1")
|
|
||||||
if err := s.RecordSeriesFailure("comix", "c2", "errors", 100); err != nil {
|
|
||||||
t.Fatalf("seed errors failure: %v", err)
|
|
||||||
}
|
|
||||||
// demonic and novelfull: one old no-chapter row each, against sites of
|
|
||||||
// one and two hundred Series.
|
|
||||||
oldNoChapter("demonic", "d1")
|
|
||||||
oldNoChapter("novelfull", "n1")
|
|
||||||
|
|
||||||
got, err := s.NoChapterShare(cutoff)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("NoChapterShare: %v", err)
|
|
||||||
}
|
|
||||||
checks := []struct {
|
|
||||||
site string
|
|
||||||
want float64
|
|
||||||
}{
|
|
||||||
{"asura", 3.0 / 4.0},
|
|
||||||
{"comix", 1.0 / 2.0},
|
|
||||||
{"demonic", 1.0 / 1.0},
|
|
||||||
{"novelfull", 1.0 / 200.0},
|
|
||||||
}
|
|
||||||
for _, c := range checks {
|
|
||||||
if got[c.site] != c.want {
|
|
||||||
t.Fatalf("NoChapterShare[%s] = %v, want %v", c.site, got[c.site], c.want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -4,16 +4,14 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
"bookmarkmanager/backend/internal/latest"
|
|
||||||
"bookmarkmanager/backend/internal/store"
|
"bookmarkmanager/backend/internal/store"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ownerWindow is the staleness boundary the Series list's "not checked in
|
// ownerWindow is the staleness boundary the Series list's "not checked in
|
||||||
// 12h" filter compares against. It reads latest.OwnerWindow — the one place
|
// 12h" filter compares against. Declared once; later admin tickets read it.
|
||||||
// the class-level twelve hours lives, shared with the owner-notice
|
const ownerWindow = 12 * time.Hour
|
||||||
// conditions (issue #171).
|
|
||||||
const ownerWindow = latest.OwnerWindow
|
|
||||||
|
|
||||||
// adminView is the shared shell data for an administrative page and the roster
|
// adminView is the shared shell data for an administrative page and the roster
|
||||||
// fragment returned after a Reader action.
|
// fragment returned after a Reader action.
|
||||||
@@ -49,8 +47,6 @@ func (h *Handler) adminRoutes() []adminRoute {
|
|||||||
{"GET /admin/series", h.adminSeries},
|
{"GET /admin/series", h.adminSeries},
|
||||||
{"GET /admin/series/{key}", h.adminSeriesDetail},
|
{"GET /admin/series/{key}", h.adminSeriesDetail},
|
||||||
{"POST /admin/series/{key}/poll", h.adminSeriesPoll},
|
{"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}/latest", h.adminSeriesCorrectLatest},
|
||||||
{"POST /admin/series/{key}/series-url", h.adminSeriesSetURL},
|
{"POST /admin/series/{key}/series-url", h.adminSeriesSetURL},
|
||||||
{"POST /admin/series/{key}/remove", h.adminSeriesRemove},
|
{"POST /admin/series/{key}/remove", h.adminSeriesRemove},
|
||||||
|
|||||||
@@ -56,10 +56,6 @@ type laneRow struct {
|
|||||||
// offer Resume from the moment the owner presses Pause, with no pass
|
// offer Resume from the moment the owner presses Pause, with no pass
|
||||||
// having run to record it (issue #147).
|
// having run to record it (issue #147).
|
||||||
Paused bool
|
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.
|
// chip is one named outcome count over the owner's window.
|
||||||
@@ -227,7 +223,6 @@ func buildLaneRow(p store.LanePass, o store.SiteOutcomes, now time.Time) laneRow
|
|||||||
if p.GapMS > 0 {
|
if p.GapMS > 0 {
|
||||||
row.Gap = (time.Duration(p.GapMS) * time.Millisecond).Truncate(time.Second).String()
|
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.Chips = outcomeChips(o)
|
||||||
row.HasChips = len(row.Chips) > 0
|
row.HasChips = len(row.Chips) > 0
|
||||||
row.StatePhrase, row.StateGood, row.Attention = laneState(p, now)
|
row.StatePhrase, row.StateGood, row.Attention = laneState(p, now)
|
||||||
@@ -237,24 +232,17 @@ func buildLaneRow(p store.LanePass, o store.SiteOutcomes, now time.Time) laneRow
|
|||||||
|
|
||||||
// outcomeChips lists a Site's nonzero window sums in the taxonomy's fixed
|
// 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
|
// 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
|
// written by the template, not drawn as a confident zero count.
|
||||||
// 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 {
|
func outcomeChips(o store.SiteOutcomes) []chip {
|
||||||
fixed := []struct {
|
fixed := []struct {
|
||||||
name string
|
name string
|
||||||
count int
|
count int
|
||||||
}{
|
}{
|
||||||
{outcomeWord("refused"), o.Refused},
|
{"refused", o.Refused},
|
||||||
{outcomeWord("unreachable"), o.Unreachable},
|
{"unreachable", o.Unreachable},
|
||||||
{outcomeWord("no_chapter"), o.NoChapter},
|
{"no chapter", o.NoChapter},
|
||||||
{outcomeWord("unfetchable"), o.Unfetchable},
|
{"unfetchable", o.Unfetchable},
|
||||||
{outcomeWord("not_found"), o.NotFound},
|
{"errors", o.Errors},
|
||||||
{outcomeWord("errors"), o.Errors},
|
|
||||||
}
|
}
|
||||||
var out []chip
|
var out []chip
|
||||||
for _, f := range fixed {
|
for _, f := range fixed {
|
||||||
|
|||||||
@@ -2,10 +2,8 @@ package web
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"bookmarkmanager/backend/internal/latest"
|
|
||||||
"bookmarkmanager/backend/internal/store"
|
"bookmarkmanager/backend/internal/store"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -25,9 +23,8 @@ type overviewView struct {
|
|||||||
// as stale + never_checked: a never-checked Series is already counted on
|
// as stale + never_checked: a never-checked Series is already counted on
|
||||||
// its own filter, and the verdict wants the inclusive number.
|
// its own filter, and the verdict wants the inclusive number.
|
||||||
Unchecked int
|
Unchecked int
|
||||||
// Hygiene is the problem filters in the Series list's own render order
|
// Hygiene is the seven problem filters in the Series list's own render
|
||||||
// plus the informational tail — finished, then site completed — riding
|
// order; Library is the library split plus the roster. Every figure is a
|
||||||
// last; Library is the library split plus the roster. Every figure is a
|
|
||||||
// door into the list that counts it, except a zero.
|
// door into the list that counts it, except a zero.
|
||||||
Hygiene []fig
|
Hygiene []fig
|
||||||
Library []fig
|
Library []fig
|
||||||
@@ -62,13 +59,10 @@ type siteRow struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// overviewView assembles the landing page from the store's read model: one
|
// overviewView assembles the landing page from the store's read model: one
|
||||||
// SeriesShapes pass per filter summed in Go (the shipped surface offers ten
|
// SeriesShapes pass per filter summed in Go (the shipped surface offers eight
|
||||||
// grouped passes, not a stats query — #140), the pass log's latest pass per
|
// 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
|
// Site, and the roster. A failure in any read is a 500 with a logged reason,
|
||||||
// is a 500 with a logged reason, never a page of silent zeroes. The three
|
// never a page of silent zeroes.
|
||||||
// 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) {
|
func (h *Handler) overviewView() (overviewView, error) {
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
cutoff := now.Add(-ownerWindow).UnixMilli()
|
cutoff := now.Add(-ownerWindow).UnixMilli()
|
||||||
@@ -97,36 +91,10 @@ func (h *Handler) overviewView() (overviewView, error) {
|
|||||||
|
|
||||||
view := overviewView{Waiting: waiting(passes)}
|
view := overviewView{Waiting: waiting(passes)}
|
||||||
view.Unchecked = totals[store.SeriesFilterStale] + totals[store.SeriesFilterNeverChecked]
|
view.Unchecked = totals[store.SeriesFilterStale] + totals[store.SeriesFilterNeverChecked]
|
||||||
var refusingSince map[string]int64
|
view.Verdict, view.HasCounts = overviewVerdict(passes, now)
|
||||||
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
|
// The seven problem filters, in seriesFilterOrder's permanent-then-fixable
|
||||||
// in permanent-then-fixable order, then the informational tail — finished
|
// order; the All filter's count belongs to the Library block, not to a
|
||||||
// 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" figure.
|
||||||
hygiene := make([]fig, 0, len(seriesFilterOrder)-1)
|
hygiene := make([]fig, 0, len(seriesFilterOrder)-1)
|
||||||
for _, name := range seriesFilterOrder[1:] {
|
for _, name := range seriesFilterOrder[1:] {
|
||||||
@@ -166,14 +134,11 @@ func (h *Handler) overviewView() (overviewView, error) {
|
|||||||
row := siteRow{
|
row := siteRow{
|
||||||
Site: sh.Site,
|
Site: sh.Site,
|
||||||
SiteHref: seriesListHref("", sh.Site, "", 0),
|
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{
|
Figs: []fig{
|
||||||
door("series", sh.Total, seriesListHref("", sh.Site, "", 0)),
|
door("", sh.Total, seriesListHref("", sh.Site, "", 0)),
|
||||||
door("no cover", siteCounts[store.SeriesFilterNoCover][sh.Site], seriesListHref(store.SeriesFilterNoCover, sh.Site, "", 0)),
|
door("", 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("", siteCounts[store.SeriesFilterNeverChecked][sh.Site], seriesListHref(store.SeriesFilterNeverChecked, sh.Site, "", 0)),
|
||||||
door("stale", siteCounts[store.SeriesFilterStale][sh.Site], seriesListHref(store.SeriesFilterStale, sh.Site, "", 0)),
|
door("", siteCounts[store.SeriesFilterStale][sh.Site], seriesListHref(store.SeriesFilterStale, sh.Site, "", 0)),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
if p, ok := passBySite[sh.Site]; ok {
|
if p, ok := passBySite[sh.Site]; ok {
|
||||||
@@ -197,26 +162,28 @@ func door(label string, count int, href string) fig {
|
|||||||
return fig{Label: label, Href: href, Count: count}
|
return fig{Label: label, Href: href, Count: count}
|
||||||
}
|
}
|
||||||
|
|
||||||
// overviewVerdict decides the landing page's one line: no passes at all is
|
// overviewVerdict decides the landing page's one line from the latest pass
|
||||||
// "no Lane has reported yet" — never confident zeroes; otherwise the count of
|
// per Site: no passes at all is "no Lane has reported yet" — never confident
|
||||||
// faults from the shared FaultsFrom judgement, so the page and the push
|
// zeroes; otherwise the count of Lanes whose last pass needs the owner, or
|
||||||
// cannot disagree. Zero faults is "all lanes healthy". A sidecar-down fault
|
// "all lanes healthy". The count comes from the same laneState judgement the
|
||||||
// carries Site == "" and is still one fault. The Lanes page's per-row
|
// Lanes page colours on, so the two pages cannot disagree on what a fault is.
|
||||||
// laneState is a different question (is this Lane's last pass healthy) from
|
func overviewVerdict(passes []store.LanePass, now time.Time) (phrase string, counts bool) {
|
||||||
// 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 {
|
if len(passes) == 0 {
|
||||||
return "no Lane has reported yet", false
|
return "no Lane has reported yet", false
|
||||||
}
|
}
|
||||||
n := len(faults)
|
attention := 0
|
||||||
if n == 0 {
|
for _, p := range passes {
|
||||||
|
if _, _, attn := laneState(p, now); attn {
|
||||||
|
attention++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if attention == 0 {
|
||||||
return "all lanes healthy", true
|
return "all lanes healthy", true
|
||||||
}
|
}
|
||||||
if n == 1 {
|
if attention == 1 {
|
||||||
return "1 lane needs a look", true
|
return "1 lane needs a look", true
|
||||||
}
|
}
|
||||||
return fmt.Sprintf("%d lanes need a look", n), true
|
return fmt.Sprintf("%d lanes need a look", attention), true
|
||||||
}
|
}
|
||||||
|
|
||||||
// waiting sums Due over the latest pass per Site: how many Series the Lanes
|
// waiting sums Due over the latest pass per Site: how many Series the Lanes
|
||||||
|
|||||||
@@ -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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -20,10 +20,10 @@ import (
|
|||||||
// the wrong page. The store does not export it (#140).
|
// the wrong page. The store does not export it (#140).
|
||||||
const seriesPageSize = 50
|
const seriesPageSize = 50
|
||||||
|
|
||||||
// seriesFilterLabels names every Series filter for the list select, keyed by
|
// seriesFilterLabels names every hygiene filter for the Series list select,
|
||||||
// the wire constant the URL carries. The render order is seriesFilterOrder;
|
// keyed by the wire constant the URL carries. The render order is
|
||||||
// the labels are read by later admin tickets too, so the map and the
|
// seriesFilterOrder; the labels are read by later admin tickets too, so the
|
||||||
// constants cannot drift apart.
|
// map and the constants cannot drift apart.
|
||||||
var seriesFilterLabels = map[string]string{
|
var seriesFilterLabels = map[string]string{
|
||||||
store.SeriesFilterAll: "All series",
|
store.SeriesFilterAll: "All series",
|
||||||
store.SeriesFilterNoURL: "No series URL",
|
store.SeriesFilterNoURL: "No series URL",
|
||||||
@@ -33,17 +33,10 @@ var seriesFilterLabels = map[string]string{
|
|||||||
store.SeriesFilterStale: "Not checked in 12h",
|
store.SeriesFilterStale: "Not checked in 12h",
|
||||||
store.SeriesFilterNoCover: "No cover",
|
store.SeriesFilterNoCover: "No cover",
|
||||||
store.SeriesFilterReaderReport: "Latest from a Reader",
|
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
|
// seriesFilterOrder is the select's render order: All first, then the
|
||||||
// permanent repairs, then the fixable ones (issue #140). Finished and the
|
// permanent repairs, then the fixable ones (issue #140).
|
||||||
// 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{
|
var seriesFilterOrder = []string{
|
||||||
store.SeriesFilterAll,
|
store.SeriesFilterAll,
|
||||||
store.SeriesFilterNoURL,
|
store.SeriesFilterNoURL,
|
||||||
@@ -53,10 +46,6 @@ var seriesFilterOrder = []string{
|
|||||||
store.SeriesFilterStale,
|
store.SeriesFilterStale,
|
||||||
store.SeriesFilterNoCover,
|
store.SeriesFilterNoCover,
|
||||||
store.SeriesFilterReaderReport,
|
store.SeriesFilterReaderReport,
|
||||||
store.SeriesFilterFailing,
|
|
||||||
store.SeriesFilterUnverified,
|
|
||||||
store.SeriesFilterFinished,
|
|
||||||
store.SeriesFilterSiteCompleted,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// seriesListView is the Series list page's data. The template renders strings
|
// seriesListView is the Series list page's data. The template renders strings
|
||||||
@@ -121,16 +110,6 @@ type seriesRowView struct {
|
|||||||
// raced answer: the row stays and says a fresh Bookmark caught the press.
|
// raced answer: the row stays and says a fresh Bookmark caught the press.
|
||||||
CanRemove bool
|
CanRemove bool
|
||||||
RemovalRefused 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,
|
// adminSeries renders the filterable, bookmarkable Series list: filter, Site,
|
||||||
@@ -203,96 +182,6 @@ func (h *Handler) adminSeriesPoll(w http.ResponseWriter, r *http.Request) {
|
|||||||
h.render(w, http.StatusOK, "series-row", seriesRow(a, band, time.Now()))
|
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
|
// adminSeriesCorrectLatest is the Latest Chapter correction: the owner types
|
||||||
// one number and the Series' Latest Chapter becomes it, stamped as a
|
// one number and the Series' Latest Chapter becomes it, stamped as a
|
||||||
// Correction. The number must be a finite float greater than zero — a
|
// Correction. The number must be a finite float greater than zero — a
|
||||||
@@ -313,8 +202,8 @@ func (h *Handler) adminSeriesCorrectLatest(w http.ResponseWriter, r *http.Reques
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
num, err := strconv.ParseFloat(r.PostFormValue("chapter"), 64)
|
num, err := strconv.ParseFloat(r.PostFormValue("chapter"), 64)
|
||||||
if err != nil || math.IsNaN(num) || math.IsInf(num, 0) || num <= 0 || num > maxChapterNum {
|
if err != nil || math.IsNaN(num) || math.IsInf(num, 0) || num <= 0 {
|
||||||
http.Error(w, "chapter must be a finite number between 0 and 10000", http.StatusBadRequest)
|
http.Error(w, "chapter must be a finite number greater than zero", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if _, found, err := h.adminSeriesByKey(site, seriesID); err != nil {
|
if _, found, err := h.adminSeriesByKey(site, seriesID); err != nil {
|
||||||
@@ -505,13 +394,10 @@ func (h *Handler) adminSeriesRemove(w http.ResponseWriter, r *http.Request) {
|
|||||||
band = 1
|
band = 1
|
||||||
}
|
}
|
||||||
h.render(w, http.StatusOK, "series-row", seriesRow(a, band, time.Now()))
|
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 {
|
if head, err := h.seriesListHeadView(r); err != nil {
|
||||||
log.Printf("series remove %s: %v", site+":"+seriesID, err)
|
log.Printf("series remove %s: %v", site+":"+seriesID, err)
|
||||||
} else if err := h.tmpl.ExecuteTemplate(w, "series-list-head", head); err != nil {
|
} else {
|
||||||
log.Printf("series remove %s: render series-list-head oob: %v", site+":"+seriesID, err)
|
h.render(w, http.StatusOK, "series-list-head", head)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -630,9 +516,9 @@ func (h *Handler) seriesListView(r *http.Request) (seriesListView, error) {
|
|||||||
return view, nil
|
return view, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// seriesFilterOptions renders every filter with its library-wide count, one
|
// seriesFilterOptions renders every hygiene filter with its library-wide
|
||||||
// SeriesShapes pass per filter summed in Go — the shipped surface offers nine
|
// count, one SeriesShapes pass per filter summed in Go — the shipped surface
|
||||||
// grouped passes, not a single stats query (#140). The counts
|
// offers eight grouped passes, not a single stats query (#140). The counts
|
||||||
// are library-wide because the select sits next to the Site narrowing and
|
// 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
|
// must not shift as the owner narrows the list itself. Cutoff travels with
|
||||||
// the stale filter, or its count would always be zero.
|
// the stale filter, or its count would always be zero.
|
||||||
@@ -686,7 +572,6 @@ func seriesRow(a store.AdminSeries, i int, now time.Time) seriesRowView {
|
|||||||
CanRemove: a.ReaderCount == 0,
|
CanRemove: a.ReaderCount == 0,
|
||||||
Pending: pending,
|
Pending: pending,
|
||||||
Requested: requested,
|
Requested: requested,
|
||||||
Finished: a.FinishedAt > 0,
|
|
||||||
}
|
}
|
||||||
if a.LatestChapterNum != nil {
|
if a.LatestChapterNum != nil {
|
||||||
row.Ch = strconv.FormatFloat(*a.LatestChapterNum, 'f', -1, 64)
|
row.Ch = strconv.FormatFloat(*a.LatestChapterNum, 'f', -1, 64)
|
||||||
@@ -694,9 +579,6 @@ func seriesRow(a store.AdminSeries, i int, now time.Time) seriesRowView {
|
|||||||
row.Ch = "—"
|
row.Ch = "—"
|
||||||
}
|
}
|
||||||
row.Age = checkedAge(now, a.LatestCheckedAt)
|
row.Age = checkedAge(now, a.LatestCheckedAt)
|
||||||
if a.FailureOutcome != "" {
|
|
||||||
row.Failure = outcomeWord(a.FailureOutcome) + " · " + checkedAge(now, a.FailingSince)
|
|
||||||
}
|
|
||||||
notes := seriesNotes(a, now)
|
notes := seriesNotes(a, now)
|
||||||
if n := len(notes); n > 2 {
|
if n := len(notes); n > 2 {
|
||||||
row.Notes, row.More = notes[:2], n-2
|
row.Notes, row.More = notes[:2], n-2
|
||||||
@@ -707,20 +589,6 @@ func seriesRow(a store.AdminSeries, i int, now time.Time) seriesRowView {
|
|||||||
return row
|
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
|
// seriesNotes are a row's hygiene chips in the design's order: no URL, no
|
||||||
// cover, orphan, stale, reader sighting.
|
// cover, orphan, stale, reader sighting.
|
||||||
func seriesNotes(a store.AdminSeries, now time.Time) []string {
|
func seriesNotes(a store.AdminSeries, now time.Time) []string {
|
||||||
|
|||||||
@@ -56,23 +56,6 @@ type seriesDetailView struct {
|
|||||||
// Series no Reader holds can be removed, so the owner is never offered a
|
// Series no Reader holds can be removed, so the owner is never offered a
|
||||||
// button the database will always refuse.
|
// button the database will always refuse.
|
||||||
CanRemove bool
|
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
|
// adminSeriesDetail renders one Series' page, keyed by the composite
|
||||||
@@ -158,19 +141,6 @@ func (h *Handler) seriesDetailView(a store.AdminSeries) seriesDetailView {
|
|||||||
v.Checked = since(time.Now(), time.UnixMilli(a.LatestCheckedAt))
|
v.Checked = since(time.Now(), time.UnixMilli(a.LatestCheckedAt))
|
||||||
}
|
}
|
||||||
v.Corrected = correctedAge(time.Now(), a.LatestCorrectedAt)
|
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
|
// Provenance: the actor class behind the current number, evaluated in the
|
||||||
// order the classes outrank one another — the owner's stamp, which a
|
// order the classes outrank one another — the owner's stamp, which a
|
||||||
@@ -201,13 +171,3 @@ func correctedAge(now time.Time, at int64) string {
|
|||||||
}
|
}
|
||||||
return "corrected " + since(now, time.UnixMilli(at))
|
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,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
|
ClientID string
|
||||||
ClientSecret string
|
ClientSecret string
|
||||||
GuildID 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
|
// RequiredRole, when non-empty, is a role ID a member must hold on top of
|
||||||
// guild membership. Empty by default: membership alone suffices.
|
// guild membership. Empty by default: membership alone suffices.
|
||||||
RequiredRole string
|
RequiredRole string
|
||||||
@@ -178,21 +173,16 @@ func (h *Handler) discordCallback(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
// The refusal is the same for a non-member and a member without the
|
// 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
|
// required role, and it names neither the guild nor its id: an outsider
|
||||||
// community so a stranger knows which Discord to ask about; otherwise it
|
// cannot tell whether the guild exists, let alone which one gates.
|
||||||
// degrades to a generic community label and still gives the next step. It
|
|
||||||
// never names the numeric guild id, which would not be actionable.
|
|
||||||
//
|
//
|
||||||
// It also returns before EnsureReader, so a refused sign-in leaves no
|
// It also returns before EnsureReader, so a refused sign-in leaves no
|
||||||
// Reader row behind — the gate is the only thing standing between guild
|
// Reader row behind — the gate is the only thing standing between guild
|
||||||
// membership and a library.
|
// membership and a library.
|
||||||
if !isMember || (h.discord.RequiredRole != "" && !slices.Contains(member.Roles, h.discord.RequiredRole)) {
|
if !isMember || (h.discord.RequiredRole != "" && !slices.Contains(member.Roles, h.discord.RequiredRole)) {
|
||||||
h.limiter.Fail(ip, time.Now())
|
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."
|
h.renderLogin(w, http.StatusForbidden,
|
||||||
if h.discord.GuildName != "" {
|
"This Discord account is not a member of this community.")
|
||||||
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)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,12 @@
|
|||||||
--measure-wide: 1080px;
|
--measure-wide: 1080px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: light) {
|
||||||
|
:root {
|
||||||
|
--measure-wide: 1080px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.admin-sheet {
|
.admin-sheet {
|
||||||
max-width: var(--measure-wide);
|
max-width: var(--measure-wide);
|
||||||
}
|
}
|
||||||
@@ -48,18 +54,12 @@
|
|||||||
|
|
||||||
.navrow a:hover {
|
.navrow a:hover {
|
||||||
color: var(--paper-dim);
|
color: var(--paper-dim);
|
||||||
background: var(--hover);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.navrow a.active {
|
.navrow a.active {
|
||||||
color: var(--patina);
|
color: var(--paper);
|
||||||
border-bottom: 2px solid var(--patina);
|
border-bottom: 2px solid var(--paper);
|
||||||
margin-bottom: -1px;
|
margin-bottom: -1px;
|
||||||
background: var(--patina-wash);
|
|
||||||
padding-left: 6px;
|
|
||||||
padding-right: 6px;
|
|
||||||
margin-left: -6px;
|
|
||||||
margin-right: -6px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.admin-page {
|
.admin-page {
|
||||||
@@ -97,13 +97,15 @@
|
|||||||
border-bottom: none;
|
border-bottom: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.admin-sheet .readerlist {
|
.admin-sheet .readerlist,
|
||||||
|
.admin-sheet .lanelist {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 0;
|
padding: 0;
|
||||||
list-style: none;
|
list-style: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.admin-sheet .readerlist li {
|
.admin-sheet .readerlist li,
|
||||||
|
.admin-sheet .lanelist li {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
@@ -113,12 +115,12 @@
|
|||||||
border-top: 1px solid var(--rule);
|
border-top: 1px solid var(--rule);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
.admin-sheet .reader-actions {
|
.admin-sheet .reader-actions {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex: 0 0 auto;
|
flex: 0 0 auto;
|
||||||
gap: 28px;
|
gap: 18px;
|
||||||
align-items: center;
|
margin-left: auto;
|
||||||
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
.admin-sheet .reader-actions .ghost,
|
.admin-sheet .reader-actions .ghost,
|
||||||
@@ -132,11 +134,13 @@
|
|||||||
color: var(--danger);
|
color: var(--danger);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
.admin-sheet .readerlist form {
|
.admin-sheet .readerlist form {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.admin-sheet .lane-browser {
|
||||||
|
padding: 12px 0 0;
|
||||||
|
}
|
||||||
|
|
||||||
.admin-sheet .ghost.danger {
|
.admin-sheet .ghost.danger {
|
||||||
color: var(--danger);
|
color: var(--danger);
|
||||||
@@ -155,7 +159,9 @@
|
|||||||
|
|
||||||
.admin-sheet .reader-sessions,
|
.admin-sheet .reader-sessions,
|
||||||
.admin-sheet .reader-sightings,
|
.admin-sheet .reader-sightings,
|
||||||
.admin-sheet .reader-blocked {
|
.admin-sheet .reader-blocked,
|
||||||
|
.admin-sheet .lane-fact,
|
||||||
|
.admin-sheet .lane-mark {
|
||||||
font: 500 13px/1.4 var(--font-mono);
|
font: 500 13px/1.4 var(--font-mono);
|
||||||
letter-spacing: .06em;
|
letter-spacing: .06em;
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
@@ -165,14 +171,25 @@
|
|||||||
color: var(--paper-dim);
|
color: var(--paper-dim);
|
||||||
}
|
}
|
||||||
|
|
||||||
.admin-sheet .reader-sightings {
|
.admin-sheet .reader-sightings,
|
||||||
|
.admin-sheet .lane-fact {
|
||||||
color: var(--mute);
|
color: var(--mute);
|
||||||
}
|
}
|
||||||
|
|
||||||
.admin-sheet .reader-blocked {
|
.admin-sheet .reader-blocked,
|
||||||
|
.admin-sheet .lane-mark {
|
||||||
color: var(--patina);
|
color: var(--patina);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.admin-sheet .lane-site {
|
||||||
|
font: 400 19px/1.2 var(--font-display);
|
||||||
|
color: var(--paper-dim);
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-sheet .lanelist li.attention .lane-site {
|
||||||
|
color: var(--danger);
|
||||||
|
}
|
||||||
|
|
||||||
/* A single grid keeps row rules continuous; cell padding supplies gutters. */
|
/* A single grid keeps row rules continuous; cell padding supplies gutters. */
|
||||||
.admin-sheet .sechead {
|
.admin-sheet .sechead {
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -284,10 +301,9 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.admin-sheet .tbl .c-act .ghost + .ghost {
|
.admin-sheet .tbl .c-act .ghost + .ghost {
|
||||||
margin-left: 28px;
|
margin-left: 12px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
.admin-sheet .tbl .trow > .confirm-row {
|
.admin-sheet .tbl .trow > .confirm-row {
|
||||||
grid-column: 1 / -1;
|
grid-column: 1 / -1;
|
||||||
padding: 10px 12px;
|
padding: 10px 12px;
|
||||||
@@ -308,10 +324,6 @@
|
|||||||
gap: 16px;
|
gap: 16px;
|
||||||
padding: 11px 24px 11px 0;
|
padding: 11px 24px 11px 0;
|
||||||
}
|
}
|
||||||
.admin-sheet .stat + .stat {
|
|
||||||
border-left: 1px solid var(--rule);
|
|
||||||
padding-left: 24px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-sheet .stat .lbl {
|
.admin-sheet .stat .lbl {
|
||||||
font: 500 13px/1.3 var(--font-mono);
|
font: 500 13px/1.3 var(--font-mono);
|
||||||
@@ -333,53 +345,34 @@
|
|||||||
.admin-sheet .stat a.fig {
|
.admin-sheet .stat a.fig {
|
||||||
/* The hover rule below sets the border on :hover only, which shifts the
|
/* The hover rule below sets the border on :hover only, which shifts the
|
||||||
row a pixel on hover; the transparent baseline holds the layout. */
|
row a pixel on hover; the transparent baseline holds the layout. */
|
||||||
border-bottom: 1px solid color-mix(in oklch, var(--patina) 22%, transparent);
|
border-bottom: 1px solid transparent;
|
||||||
}
|
}
|
||||||
|
|
||||||
.admin-sheet .stat a.fig:hover {
|
.admin-sheet .stat a.fig:hover {
|
||||||
color: var(--patina);
|
color: var(--patina);
|
||||||
border-bottom: 1px solid var(--patina);
|
border-bottom: 1px solid var(--patina);
|
||||||
background: var(--patina-wash);
|
|
||||||
}
|
|
||||||
@media (max-width: 600px) {
|
|
||||||
.admin-sheet .stat + .stat {
|
|
||||||
border-left: none;
|
|
||||||
border-top: 1px solid var(--rule);
|
|
||||||
padding-left: 0;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.admin-sheet .mark,
|
.admin-sheet .mark,
|
||||||
.admin-sheet .mark-faint {
|
.admin-sheet .mark-faint {
|
||||||
font: 500 12px/1.2 var(--font-mono);
|
font: 500 13px/1 var(--font-mono);
|
||||||
letter-spacing: .06em;
|
letter-spacing: .06em;
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
padding: 2px 6px;
|
|
||||||
border-radius: 2px;
|
|
||||||
border: 1px solid transparent;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.admin-sheet .mark {
|
.admin-sheet .mark {
|
||||||
color: var(--patina);
|
color: var(--patina);
|
||||||
background: var(--patina-wash);
|
|
||||||
border-color: var(--patina-line);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.admin-sheet .mark-faint {
|
.admin-sheet .mark-faint {
|
||||||
color: var(--mute-2);
|
color: var(--mute-2);
|
||||||
background: transparent;
|
|
||||||
border-color: transparent;
|
|
||||||
padding-left: 0;
|
|
||||||
padding-right: 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.admin-sheet .mark.mark-strong {
|
.admin-sheet .mark.mark-strong {
|
||||||
font-size: 12px;
|
font-size: 13px;
|
||||||
letter-spacing: .12em;
|
letter-spacing: .14em;
|
||||||
color: var(--patina);
|
color: var(--patina);
|
||||||
background: var(--patina-wash);
|
|
||||||
border-color: var(--patina-line);
|
|
||||||
padding: 3px 7px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.admin-sheet .mark.mark-strong::before {
|
.admin-sheet .mark.mark-strong::before {
|
||||||
@@ -394,21 +387,9 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.admin-sheet .mark.bad {
|
.admin-sheet .mark.bad {
|
||||||
color: var(--slate);
|
color: var(--danger);
|
||||||
background: var(--slate-wash);
|
|
||||||
border-color: var(--slate);
|
|
||||||
font-weight: 600;
|
|
||||||
}
|
|
||||||
.admin-sheet .mark.bad::before {
|
|
||||||
content: "";
|
|
||||||
display: inline-block;
|
|
||||||
width: 7px;
|
|
||||||
height: 7px;
|
|
||||||
background: var(--slate);
|
|
||||||
margin-right: 8px;
|
|
||||||
vertical-align: .08em;
|
|
||||||
border-radius: 1px; /* square, not circle — distinguishes from .mark-strong patina dot */
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.admin-sheet .tbl.sites {
|
.admin-sheet .tbl.sites {
|
||||||
grid-template-columns: 170px repeat(4, 106px) minmax(180px, 1fr);
|
grid-template-columns: 170px repeat(4, 106px) minmax(180px, 1fr);
|
||||||
}
|
}
|
||||||
@@ -421,56 +402,18 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.admin-sheet .tbl.sites .c-state {
|
.admin-sheet .tbl.sites .c-state {
|
||||||
color: var(--mute-2);
|
|
||||||
white-space: nowrap;
|
|
||||||
padding: 2px 7px;
|
|
||||||
border-radius: 2px;
|
|
||||||
border: 1px solid transparent;
|
|
||||||
background: transparent;
|
|
||||||
justify-self: start;
|
|
||||||
align-self: center;
|
|
||||||
font: 500 11px/1 var(--font-mono);
|
|
||||||
letter-spacing: .08em;
|
|
||||||
text-transform: uppercase;
|
|
||||||
}
|
|
||||||
.admin-sheet .tbl.sites .c-state.ok {
|
|
||||||
color: var(--patina);
|
color: var(--patina);
|
||||||
background: var(--patina-wash);
|
white-space: nowrap;
|
||||||
border-color: var(--patina-line);
|
|
||||||
}
|
}
|
||||||
.admin-sheet .tbl.sites .c-state.bad {
|
|
||||||
color: var(--slate);
|
.admin-sheet .tbl.sites .c-state.bad,
|
||||||
background: var(--slate-wash);
|
.admin-sheet .tbl.lanes .c-skip .bad,
|
||||||
border-color: var(--slate);
|
.admin-sheet .tbl.lanes .trow.attention .c-site {
|
||||||
font-weight: 600;
|
color: var(--danger);
|
||||||
}
|
}
|
||||||
|
|
||||||
.admin-sheet .tbl.lanes .c-skip .ok {
|
.admin-sheet .tbl.lanes .c-skip .ok {
|
||||||
color: var(--patina);
|
color: var(--patina);
|
||||||
background: var(--patina-wash);
|
|
||||||
border: 1px solid var(--patina-line);
|
|
||||||
padding: 1px 5px;
|
|
||||||
border-radius: 2px;
|
|
||||||
}
|
|
||||||
.admin-sheet .tbl.lanes .trow.attention .c-site {
|
|
||||||
color: var(--patina);
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-sheet .tbl.lanes .c-skip .bad {
|
|
||||||
color: var(--slate);
|
|
||||||
background: var(--slate-wash);
|
|
||||||
border: 1px solid var(--slate);
|
|
||||||
padding: 1px 5px;
|
|
||||||
border-radius: 2px;
|
|
||||||
font-weight: 600;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-sheet .tbl.lanes .trow.attention {
|
|
||||||
background: var(--patina-wash);
|
|
||||||
box-shadow: inset 1px 0 0 var(--patina);
|
|
||||||
}
|
|
||||||
.admin-sheet .tbl.series .trow.attention {
|
|
||||||
background: var(--patina-wash);
|
|
||||||
box-shadow: inset 1px 0 0 var(--patina);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.admin-sheet .tbl.sites .thead > *:nth-child(n+2):nth-child(-n+5),
|
.admin-sheet .tbl.sites .thead > *:nth-child(n+2):nth-child(-n+5),
|
||||||
@@ -629,13 +572,8 @@
|
|||||||
.admin-sheet .segrow a.active {
|
.admin-sheet .segrow a.active {
|
||||||
border-bottom-color: var(--patina);
|
border-bottom-color: var(--patina);
|
||||||
color: var(--patina);
|
color: var(--patina);
|
||||||
background: var(--patina-wash);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.admin-sheet .segrow a:hover {
|
|
||||||
color: var(--paper-dim);
|
|
||||||
background: var(--hover);
|
|
||||||
}
|
|
||||||
.admin-sheet .listhead {
|
.admin-sheet .listhead {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: baseline;
|
align-items: baseline;
|
||||||
@@ -674,11 +612,10 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.admin-sheet .pager .pg.disabled {
|
.admin-sheet .pager .pg.disabled {
|
||||||
color: var(--mute);
|
color: var(--faint);
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
.admin-sheet .empty {
|
.admin-sheet .empty {
|
||||||
padding: 28px 0;
|
padding: 28px 0;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
@@ -716,43 +653,6 @@
|
|||||||
margin-left: auto;
|
margin-left: auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* The finish confirm is the one calm row on the admin sheet: a reversible
|
|
||||||
move wears the recessed ash, never the remove wash above, and its
|
|
||||||
affirmative takes the sheet's patina accent (issue #158). */
|
|
||||||
.admin-sheet .confirm-row.calm {
|
|
||||||
background: var(--ash);
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-sheet .confirm-row.calm span {
|
|
||||||
color: var(--paper-dim);
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-sheet .confirm-row.calm .go {
|
|
||||||
background: var(--patina);
|
|
||||||
color: var(--ink);
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-sheet .readerlist li .confirm-row {
|
|
||||||
width: 100%;
|
|
||||||
margin-top: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Busy: same muted hairline the reader library uses, never ember. */
|
|
||||||
.admin-sheet .trow.htmx-request,
|
|
||||||
.admin-sheet #readers.htmx-request,
|
|
||||||
.admin-sheet #lanes.htmx-request,
|
|
||||||
.admin-sheet #detail-meta.htmx-request,
|
|
||||||
.admin-sheet .dform.htmx-request {
|
|
||||||
opacity: .6;
|
|
||||||
pointer-events: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-sheet .ghost:focus-visible {
|
|
||||||
outline: 2px solid var(--patina);
|
|
||||||
outline-offset: 2px;
|
|
||||||
color: var(--paper);
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-sheet .tbl.series .row-msg {
|
.admin-sheet .tbl.series .row-msg {
|
||||||
grid-column: 1 / -1;
|
grid-column: 1 / -1;
|
||||||
margin-top: 6px;
|
margin-top: 6px;
|
||||||
@@ -761,6 +661,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.admin-sheet .detail-back {
|
.admin-sheet .detail-back {
|
||||||
|
display: inline-block;
|
||||||
margin: 18px 0 0;
|
margin: 18px 0 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -902,23 +803,6 @@
|
|||||||
margin-left: auto;
|
margin-left: auto;
|
||||||
text-align: right;
|
text-align: right;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* The thead is gone, so every cell that was only legible under a column
|
|
||||||
heading prints its own. The label is data, not decoration: without it
|
|
||||||
"12 40 6h" is three numbers in the same face with no way to tell which
|
|
||||||
is which. Set in the mono face at label size so the figure still leads
|
|
||||||
visually. */
|
|
||||||
.admin-sheet .tbl.lanes [data-label] {
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-sheet .tbl.lanes [data-label]::before {
|
|
||||||
content: attr(data-label) " ";
|
|
||||||
font-size: 11px;
|
|
||||||
letter-spacing: .1em;
|
|
||||||
text-transform: uppercase;
|
|
||||||
color: var(--mute-2);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 899px) {
|
@media (max-width: 899px) {
|
||||||
@@ -934,12 +818,7 @@
|
|||||||
.admin-sheet .tbl .trow {
|
.admin-sheet .tbl .trow {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
/* Cells no longer share a font size — a label-value pair is 11px over
|
gap: 2px 10px;
|
||||||
15px — so they hang off the baseline, not off the box top. */
|
|
||||||
align-items: baseline;
|
|
||||||
/* Wider than the mouse layout's column gutter: each cell now carries its
|
|
||||||
own label, so the eye needs the pair to read as one unit. */
|
|
||||||
gap: 2px 18px;
|
|
||||||
padding: 11px 0;
|
padding: 11px 0;
|
||||||
border-bottom: 1px solid var(--rule);
|
border-bottom: 1px solid var(--rule);
|
||||||
}
|
}
|
||||||
@@ -976,69 +855,4 @@
|
|||||||
.admin-sheet .tbl .c-act {
|
.admin-sheet .tbl .c-act {
|
||||||
margin-left: auto;
|
margin-left: auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* A cell is one label-value pair and must not break between them. */
|
|
||||||
.admin-sheet .tbl [data-label] {
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-sheet .tbl [data-label]::before {
|
|
||||||
content: attr(data-label) " ";
|
|
||||||
font-size: 11px;
|
|
||||||
letter-spacing: .1em;
|
|
||||||
text-transform: uppercase;
|
|
||||||
color: var(--mute-2);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ---- touch: the reader's library is sized for a thumb throughout, this
|
|
||||||
sheet was not — it is a data surface that grew on a mouse. Gated on the
|
|
||||||
input method rather than the width, because the phone is not the only
|
|
||||||
coarse pointer and a 1400px touch laptop has the same problem. Vertical
|
|
||||||
only: horizontal space is what this surface is short of. ---- */
|
|
||||||
@media (pointer: coarse) {
|
|
||||||
/* The figure is the door — the label beside it is not a link — so the row
|
|
||||||
gives up its own padding to the cell that has to be hit. */
|
|
||||||
.admin-sheet .stat {
|
|
||||||
padding: 0 24px 0 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* A one-digit count is 11px wide: the minimum is on the box, not the
|
|
||||||
glyph, or the door is a target the thumb has to aim at. */
|
|
||||||
.admin-sheet .stat .fig {
|
|
||||||
min-width: 44px;
|
|
||||||
padding: 14px 0 14px 20px;
|
|
||||||
text-align: right;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-sheet .tbl .c-title a,
|
|
||||||
.admin-sheet .tbl a.fig,
|
|
||||||
.admin-sheet .tbl a.c-site,
|
|
||||||
/* The collapsed lanes row sets padding on every direct cell, which is a
|
|
||||||
more specific selector than the line above — its own Site link has to be
|
|
||||||
named here or it keeps the mouse metric. */
|
|
||||||
.admin-sheet .tbl.lanes .trow > a.c-site {
|
|
||||||
display: inline-block;
|
|
||||||
min-width: 44px;
|
|
||||||
padding: 10px 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-sheet .pager {
|
|
||||||
gap: 20px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-sheet .pager .pg {
|
|
||||||
padding: 16px 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-sheet .segrow a {
|
|
||||||
padding: 15px 11px 16px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-sheet .fsel select,
|
|
||||||
.admin-sheet .pausebar select,
|
|
||||||
.admin-sheet .dform input {
|
|
||||||
padding-top: 11px;
|
|
||||||
padding-bottom: 12px;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
// Title search runs entirely in the browser: the full list is already in the
|
// Title search runs entirely in the browser: the full list is already in the
|
||||||
// DOM, so filtering it needs no request.
|
// DOM, so filtering it needs no request.
|
||||||
(function () {
|
(function () {
|
||||||
function applyFilter(e) {
|
function applyFilter() {
|
||||||
var box = document.getElementById("search");
|
var box = document.getElementById("search");
|
||||||
if (!box) return;
|
if (!box) return;
|
||||||
var query = box.value.trim();
|
var query = box.value.trim();
|
||||||
@@ -30,21 +30,6 @@
|
|||||||
none.hidden = !(needle !== "" && cards.length > 0 && visible === 0);
|
none.hidden = !(needle !== "" && cards.length > 0 && visible === 0);
|
||||||
if (!none.hidden) none.querySelector(".no-match-q").textContent = query;
|
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) {
|
document.addEventListener("input", function (e) {
|
||||||
@@ -62,54 +47,6 @@
|
|||||||
// htmx replaces the list on a tab switch, so re-apply to the new cards.
|
// htmx replaces the list on a tab switch, so re-apply to the new cards.
|
||||||
document.body.addEventListener("htmx:afterSwap", applyFilter);
|
document.body.addEventListener("htmx:afterSwap", applyFilter);
|
||||||
document.addEventListener("bmgr:refilter", 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) {
|
function setActiveTab(el) {
|
||||||
@@ -124,7 +61,7 @@ function setActiveTab(el) {
|
|||||||
document.dispatchEvent(new Event("bmgr:refilter"));
|
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
|
// 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
|
// that owns an open panel carries .open, which is how the strip shows which
|
||||||
// cell the panel belongs to.
|
// cell the panel belongs to.
|
||||||
@@ -160,10 +97,10 @@ function toggleChapterForm(key) {
|
|||||||
if (form && !form.hidden) form.querySelector("input").focus();
|
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.
|
// cell share it.
|
||||||
function toggleConfirmRow(key, kind) {
|
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);
|
var row = togglePanel(key, "confirm-" + kind + "-" + key, ".actions " + cls);
|
||||||
// Focus the answer rather than trusting aria-live on a container that merely
|
// Focus the answer rather than trusting aria-live on a container that merely
|
||||||
// unhides: it makes the announcement deterministic, keeps tab order inside
|
// 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;
|
if (e.key !== "Escape" || !e.target.closest) return;
|
||||||
var card = e.target.closest(".card");
|
var card = e.target.closest(".card");
|
||||||
var owner = card && card.querySelector(".actions .open");
|
var owner = card && card.querySelector(".actions .open");
|
||||||
if (owner) {
|
if (!owner) return;
|
||||||
closeCardPanels(card.id.replace(/^card-/, ""));
|
closeCardPanels(card.id.replace(/^card-/, ""));
|
||||||
owner.focus();
|
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
|
// 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
|
// 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.
|
// went wrong. Surface it inline instead of leaving the tap looking ignored.
|
||||||
(function () {
|
(function () {
|
||||||
function slotFor(elt) {
|
function showError(elt, message, linkHref, linkText) {
|
||||||
var card = elt.closest(".card");
|
var card = elt.closest(".card");
|
||||||
if (card) {
|
var slot = card && card.querySelector(".error-inline");
|
||||||
var s = card.querySelector(".error-inline");
|
if (!slot) return;
|
||||||
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");
|
|
||||||
slot.textContent = message;
|
slot.textContent = message;
|
||||||
if (linkHref) {
|
if (linkHref) {
|
||||||
var a = document.createElement("a");
|
var a = document.createElement("a");
|
||||||
@@ -271,10 +155,9 @@ document.addEventListener("keydown", function (e) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
document.body.addEventListener("htmx:beforeRequest", 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;
|
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
|
// 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) {
|
document.body.addEventListener("htmx:responseError", function (e) {
|
||||||
var slot = slotFor(e.detail.elt);
|
|
||||||
if (!slot) return;
|
|
||||||
var xhr = e.detail.xhr;
|
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) {
|
if (xhr.status === 401) {
|
||||||
show(slot, inCard(slot) ? "Session expired — nothing was saved." : "Session expired.",
|
showError(e.detail.elt, "Session expired — nothing was saved.", "/login", "Log in again");
|
||||||
"/login", "Log in again");
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (xhr.status === 400) {
|
if (xhr.status === 400) {
|
||||||
var reason = reasonFrom(xhr);
|
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;
|
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) {
|
document.body.addEventListener("htmx:sendError", function (e) {
|
||||||
var slot = slotFor(e.detail.elt);
|
showError(e.detail.elt, "No connection — try again.");
|
||||||
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.");
|
|
||||||
});
|
});
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -54,10 +54,10 @@
|
|||||||
|
|
||||||
--ink: #100f0e; /* page */
|
--ink: #100f0e; /* page */
|
||||||
--ash: #161413; /* recessed panel (chapter form) */
|
--ash: #161413; /* recessed panel (chapter form) */
|
||||||
--dim: #0d0c0b; /* archived rows sink */
|
--dim: #0d0c0b; /* archived / finished rows sink */
|
||||||
--rule: #221f1d; /* decorative hairlines — not interactive — hairline between sheets */
|
--rule: #221f1d; /* hairline between sheets */
|
||||||
--rule-soft: #1a1817; /* decorative hairlines — not interactive — measure edges */
|
--rule-soft: #1a1817; /* measure edges */
|
||||||
--field-line: #4a4540; /* ≈■ #4a4540 — interactive border, distinct from decorative --rule/--rule-soft */
|
--field-line: #2c2926;
|
||||||
--hover: #1a1816;
|
--hover: #1a1816;
|
||||||
|
|
||||||
--paper: #f2ece5; /* highest-contrast text, primary button */
|
--paper: #f2ece5; /* highest-contrast text, primary button */
|
||||||
@@ -70,8 +70,8 @@
|
|||||||
--faint: #3a3733; /* meta separators */
|
--faint: #3a3733; /* meta separators */
|
||||||
--faint-2: #57504b; /* cover monogram */
|
--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: #e0452c; /* the only heat */
|
||||||
--ember-wash: #1c0f0d; /* ■ #1c0f0d — verified against this wash for is-new card/Recent/Updated/libswitch */
|
--ember-wash: #1a1211; /* ember-tinted surface */
|
||||||
--ember-ink: #150907; /* text on solid ember */
|
--ember-ink: #150907; /* text on solid ember */
|
||||||
--ember-soft: #eda798; /* text on ember wash */
|
--ember-soft: #eda798; /* text on ember wash */
|
||||||
/* Destruction is hot but not ember: a duller oxblood, so a remove confirm is
|
/* Destruction is hot but not ember: a duller oxblood, so a remove confirm is
|
||||||
@@ -80,7 +80,6 @@
|
|||||||
--danger-wash: #211311;
|
--danger-wash: #211311;
|
||||||
--danger-ink: #150808;
|
--danger-ink: #150808;
|
||||||
--danger-soft: #e2aaa1;
|
--danger-soft: #e2aaa1;
|
||||||
--danger-line: #4a2e2b; /* resting hairline for Remove — muted danger, not alarm */
|
|
||||||
--brass: #b8912f; /* favourite — a second, cooler metal */
|
--brass: #b8912f; /* favourite — a second, cooler metal */
|
||||||
/* One accent per action, so a press says which lane it belongs to. All three
|
/* 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. */
|
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
|
blue. Neither ember (new chapter) nor danger (destruction) may say
|
||||||
"system unhealthy". */
|
"system unhealthy". */
|
||||||
--patina: #5fb3a6;
|
--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. */
|
/* Desktop cell borders for the two coloured action states. */
|
||||||
--play-hot-line: #3a1d18;
|
--play-hot-line: #3a1d18;
|
||||||
--fav-line: #332b14;
|
--fav-line: #332b14;
|
||||||
@@ -127,9 +116,6 @@
|
|||||||
desktop, so both live here rather than as magic numbers. */
|
desktop, so both live here rather than as magic numbers. */
|
||||||
--cover-w: 93px;
|
--cover-w: 93px;
|
||||||
--row-gap: 14px;
|
--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
|
/* Light mode: same rules, cooler paper. Hues are re-tuned, not reused — the
|
||||||
@@ -139,8 +125,8 @@
|
|||||||
--ink: #f7f4ef;
|
--ink: #f7f4ef;
|
||||||
--ash: #efeae3;
|
--ash: #efeae3;
|
||||||
--dim: #f1ede7;
|
--dim: #f1ede7;
|
||||||
--rule: #e0dad2; /* decorative hairlines — not interactive */
|
--rule: #e0dad2;
|
||||||
--rule-soft: #e8e3dc; /* decorative hairlines — not interactive */
|
--rule-soft: #e8e3dc;
|
||||||
--field-line: #d4cdc4;
|
--field-line: #d4cdc4;
|
||||||
--hover: #efeae3;
|
--hover: #efeae3;
|
||||||
|
|
||||||
@@ -152,42 +138,30 @@
|
|||||||
--faint: #c9c2ba;
|
--faint: #c9c2ba;
|
||||||
--faint-2: #a8a098;
|
--faint-2: #a8a098;
|
||||||
|
|
||||||
--ember: #c23a22; /* verified against --ember-wash, not --ink */
|
--ember: #c23a22;
|
||||||
--ember-wash: #fbeee9; /* verified against --ember-wash, not --ink — wash ground */
|
--ember-wash: #fbeee9;
|
||||||
--ember-ink: #fff;
|
--ember-ink: #fff;
|
||||||
--ember-soft: #7c2314; /* from #8d2c17 — crimson not brown, 4.9:1 on #fbeee9 */
|
--ember-soft: #8d2c17;
|
||||||
--danger: #97362a;
|
--danger: #97362a;
|
||||||
--danger-wash: #fbe9e5;
|
--danger-wash: #fbe9e5;
|
||||||
--danger-ink: #fff;
|
--danger-ink: #fff;
|
||||||
--danger-soft: #7c2c22;
|
--danger-soft: #7c2c22;
|
||||||
--danger-line: #d8b8b0; /* resting hairline for Remove — light counterpart to #4a2e2b */
|
|
||||||
--brass: #8a681c;
|
--brass: #8a681c;
|
||||||
--slate: #3f6689;
|
--slate: #3f6689;
|
||||||
--moss: #3d6c46;
|
--moss: #3d6c46;
|
||||||
--clay: #7c5533;
|
--clay: #7c5533;
|
||||||
--trash: #8c6558;
|
--trash: #8c6558;
|
||||||
--patina: #1f6f66;
|
--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;
|
--play-hot-line: #f0cfc6;
|
||||||
--fav-line: #e3d3a4;
|
--fav-line: #e3d3a4;
|
||||||
|
|
||||||
--asura: #4f6b80;
|
--asura: #4f6b80;
|
||||||
--demonic: #7a5c4a; /* from #8a6a55 — 5.1:1 on #f7f4ef, ~4.7:1 on #efeae3 */
|
--demonic: #8a6a55;
|
||||||
--comix: #5a6c4b; /* from #5f7250 — 5.2:1 on #f7f4ef, 4.77:1 on #efeae3 — was 4.38:1 on ash, fails AA */
|
--comix: #5f7250;
|
||||||
--kagane: #6f5f7d;
|
--kagane: #6f5f7d;
|
||||||
--novelfull: #6f5f3f; /* from #7d6f4f — same bar */
|
--novelfull: #7d6f4f;
|
||||||
--lightnovelworld: #3d6b5e; /* from #4f7d70 — lifts 3.90→4.8:1 on ash */
|
--lightnovelworld: #4f7d70;
|
||||||
|
|
||||||
--hatch: repeating-linear-gradient(135deg, #e6e0d8 0 5px, #efeae3 5px 10px);
|
--hatch: repeating-linear-gradient(135deg, #e6e0d8 0 5px, #efeae3 5px 10px);
|
||||||
--hatch-dim: repeating-linear-gradient(135deg, #ebe6de 0 5px, #f2eee8 5px 10px);
|
--hatch-dim: repeating-linear-gradient(135deg, #ebe6de 0 5px, #f2eee8 5px 10px);
|
||||||
@@ -204,11 +178,6 @@ body {
|
|||||||
display: flex;
|
display: flex;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
-webkit-text-size-adjust: 100%;
|
-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; }
|
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. */
|
/* Every hideable thing here is a flex container, and display beats hidden. */
|
||||||
[hidden] { display: none !important; }
|
[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
|
/* Ends flush with the right edge of the card (30% wide × 233% travel), so the
|
||||||
card itself never needs overflow: hidden to contain it. */
|
card itself never needs overflow: hidden to contain it. */
|
||||||
@@ -247,9 +203,6 @@ button { cursor: pointer; }
|
|||||||
width: 100%;
|
width: 100%;
|
||||||
max-width: var(--measure);
|
max-width: var(--measure);
|
||||||
min-height: 100vh;
|
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;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
border-left: 1px solid var(--rule-soft);
|
border-left: 1px solid var(--rule-soft);
|
||||||
@@ -295,15 +248,6 @@ button { cursor: pointer; }
|
|||||||
.ghost:hover { color: var(--paper); border-bottom-color: var(--paper); }
|
.ghost:hover { color: var(--paper); border-bottom-color: var(--paper); }
|
||||||
/* The label is 15px tall by design; the thumb gets 44 without moving it. */
|
/* The label is 15px tall by design; the thumb gets 44 without moving it. */
|
||||||
.ghost::after { content: ""; position: absolute; inset: -15px -12px; }
|
.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 ---- */
|
/* ---- userscript setup: collapsed by default, one hairline, no card ---- */
|
||||||
.setup {
|
.setup {
|
||||||
@@ -317,7 +261,7 @@ button { cursor: pointer; }
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
min-height: 44px;
|
min-height: 44px;
|
||||||
padding: 0;
|
padding: 0;
|
||||||
font: 500 11px/1 var(--font-mono);
|
font: 500 10px/1 var(--font-mono);
|
||||||
letter-spacing: .2em;
|
letter-spacing: .2em;
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
color: var(--mute-2);
|
color: var(--mute-2);
|
||||||
@@ -353,21 +297,7 @@ button { cursor: pointer; }
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/* Sticky: the buckets and the search box are how a large library is triaged,
|
.chrome { display: flex; flex-direction: column; }
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
.searchbar {
|
.searchbar {
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -378,9 +308,8 @@ button { cursor: pointer; }
|
|||||||
border-bottom: 1px solid var(--rule);
|
border-bottom: 1px solid var(--rule);
|
||||||
color: var(--mute-2);
|
color: var(--mute-2);
|
||||||
}
|
}
|
||||||
/* The bar carries a resting recolour on focus-within, and the input carries
|
/* The input drops its own outline, so the bar it sits in carries the focus
|
||||||
its own ring: the 1px border change alone is a weaker indicator than every
|
ring — same move the two other inputs make with their border. */
|
||||||
other control on the sheet gets, on the control most worth finding. */
|
|
||||||
.searchbar:focus-within { border-bottom-color: var(--paper); color: var(--paper); }
|
.searchbar:focus-within { border-bottom-color: var(--paper); color: var(--paper); }
|
||||||
.searchbar svg { width: 15px; height: 15px; flex: none; }
|
.searchbar svg { width: 15px; height: 15px; flex: none; }
|
||||||
.search {
|
.search {
|
||||||
@@ -391,8 +320,8 @@ button { cursor: pointer; }
|
|||||||
background: transparent;
|
background: transparent;
|
||||||
color: var(--paper);
|
color: var(--paper);
|
||||||
font: 400 15px var(--font-body);
|
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); }
|
.search::placeholder { color: var(--mute-2); }
|
||||||
|
|
||||||
/* Tabs are set in the display serif and underlined, not chipped. */
|
/* Tabs are set in the display serif and underlined, not chipped. */
|
||||||
@@ -404,9 +333,6 @@ button { cursor: pointer; }
|
|||||||
overflow-y: hidden;
|
overflow-y: hidden;
|
||||||
scrollbar-width: none;
|
scrollbar-width: none;
|
||||||
border-bottom: 1px solid var(--rule);
|
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::-webkit-scrollbar { display: none; }
|
||||||
.tabs a {
|
.tabs a {
|
||||||
@@ -422,25 +348,21 @@ button { cursor: pointer; }
|
|||||||
font: 400 17px var(--font-display);
|
font: 400 17px var(--font-display);
|
||||||
white-space: nowrap;
|
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 {
|
.tabs a.active {
|
||||||
color: var(--paper);
|
color: var(--paper);
|
||||||
border-bottom: 2px solid var(--paper);
|
border-bottom: 2px solid var(--paper);
|
||||||
margin-bottom: -1px;
|
margin-bottom: -1px;
|
||||||
background: var(--hover);
|
|
||||||
}
|
}
|
||||||
/* Updated is the one tab that carries heat. */
|
/* Updated is the one tab that carries heat. */
|
||||||
.tabs .tab-new { color: var(--ember); }
|
.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.active { border-bottom-color: var(--ember); }
|
||||||
.tabs .tab-new:hover { background: var(--ember-wash); color: var(--ember); }
|
|
||||||
.count {
|
.count {
|
||||||
font: 600 10px var(--font-mono);
|
font: 600 10px var(--font-mono);
|
||||||
letter-spacing: 0;
|
letter-spacing: 0;
|
||||||
padding: 2px 5px;
|
padding: 2px 5px;
|
||||||
border: 1px solid currentColor;
|
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
|
/* ---- 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
|
never has to be guessed at. Lean on a phone (28px, edge to edge), a step
|
||||||
@@ -464,18 +386,12 @@ button { cursor: pointer; }
|
|||||||
}
|
}
|
||||||
.keyrow .pair svg { width: 14px; height: 14px; flex: none; }
|
.keyrow .pair svg { width: 14px; height: 14px; flex: none; }
|
||||||
.keyrow .pair span {
|
.keyrow .pair span {
|
||||||
font: 500 11px/1 var(--font-mono);
|
font: 500 10px/1 var(--font-mono);
|
||||||
letter-spacing: .04em;
|
letter-spacing: .04em;
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
}
|
}
|
||||||
.keyrow .pair.brass svg { color: var(--brass); }
|
.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.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 ---- */
|
/* ---- continue reading ---- */
|
||||||
.recent {
|
.recent {
|
||||||
@@ -488,7 +404,7 @@ button { cursor: pointer; }
|
|||||||
.recent h2 {
|
.recent h2 {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 0 20px;
|
padding: 0 20px;
|
||||||
font: 500 11px/1 var(--font-mono);
|
font: 500 10px/1 var(--font-mono);
|
||||||
letter-spacing: .2em;
|
letter-spacing: .2em;
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
color: var(--mute-2);
|
color: var(--mute-2);
|
||||||
@@ -500,10 +416,6 @@ button { cursor: pointer; }
|
|||||||
overflow-y: hidden;
|
overflow-y: hidden;
|
||||||
scrollbar-width: none;
|
scrollbar-width: none;
|
||||||
padding: 0 20px 4px;
|
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-strip::-webkit-scrollbar { display: none; }
|
||||||
.recent-card {
|
.recent-card {
|
||||||
@@ -512,7 +424,6 @@ button { cursor: pointer; }
|
|||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 8px;
|
gap: 8px;
|
||||||
scroll-snap-align: start;
|
|
||||||
}
|
}
|
||||||
.recent-cover {
|
.recent-cover {
|
||||||
position: relative;
|
position: relative;
|
||||||
@@ -523,11 +434,6 @@ button { cursor: pointer; }
|
|||||||
place-items: center;
|
place-items: center;
|
||||||
overflow: hidden;
|
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-cover img { width: 100%; height: 100%; object-fit: cover; }
|
||||||
.recent-title {
|
.recent-title {
|
||||||
font: 400 16px/1.25 var(--font-display);
|
font: 400 16px/1.25 var(--font-display);
|
||||||
@@ -536,7 +442,6 @@ button { cursor: pointer; }
|
|||||||
-webkit-line-clamp: 2;
|
-webkit-line-clamp: 2;
|
||||||
-webkit-box-orient: vertical;
|
-webkit-box-orient: vertical;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
overflow-wrap: anywhere;
|
|
||||||
}
|
}
|
||||||
.recent-chapter {
|
.recent-chapter {
|
||||||
font: 500 11px/1 var(--font-mono);
|
font: 500 11px/1 var(--font-mono);
|
||||||
@@ -545,7 +450,6 @@ button { cursor: pointer; }
|
|||||||
}
|
}
|
||||||
.recent-card.is-new .recent-title { color: var(--paper-hot); }
|
.recent-card.is-new .recent-title { color: var(--paper-hot); }
|
||||||
.recent-card.is-new .recent-chapter { color: var(--ember); }
|
.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
|
/* The rule at the cover foot is the only cover ornament: ember for a new
|
||||||
chapter, brass for a favourite. */
|
chapter, brass for a favourite. */
|
||||||
@@ -577,11 +481,6 @@ button { cursor: pointer; }
|
|||||||
animation: sheetIn .18s ease-out;
|
animation: sheetIn .18s ease-out;
|
||||||
}
|
}
|
||||||
.card.is-dim { background: var(--dim); }
|
.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); }
|
.row { display: flex; flex-wrap: wrap; align-items: center; gap: var(--row-gap); }
|
||||||
|
|
||||||
@@ -595,12 +494,9 @@ button { cursor: pointer; }
|
|||||||
place-items: center;
|
place-items: center;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
.cover > img, .cover > .monogram { grid-area: 1 / 1; }
|
|
||||||
.cover img { width: 100%; height: 100%; object-fit: cover; }
|
.cover img { width: 100%; height: 100%; object-fit: cover; }
|
||||||
.cover .monogram { font-size: 32px; }
|
.cover .monogram { font-size: 32px; }
|
||||||
.is-dim .cover { background: var(--hatch-dim); }
|
.is-dim .cover { background: var(--hatch-dim); filter: grayscale(1); opacity: .85; }
|
||||||
.is-dim .cover img { filter: grayscale(1); opacity: .85; }
|
|
||||||
.is-dim .cover .monogram { color: var(--mute-2); }
|
|
||||||
|
|
||||||
.body {
|
.body {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
@@ -618,17 +514,6 @@ button { cursor: pointer; }
|
|||||||
min-width: 0;
|
min-width: 0;
|
||||||
font: 400 21px/1.2 var(--font-display);
|
font: 400 21px/1.2 var(--font-display);
|
||||||
color: var(--paper-dim);
|
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. */
|
/* Heat: crimson title over an ember hairline sized to the text, not the row. */
|
||||||
.is-new .title {
|
.is-new .title {
|
||||||
@@ -637,9 +522,6 @@ button { cursor: pointer; }
|
|||||||
color: var(--paper-hot);
|
color: var(--paper-hot);
|
||||||
border-bottom: 1px solid var(--ember);
|
border-bottom: 1px solid var(--ember);
|
||||||
padding-bottom: 3px;
|
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 .title { font-style: italic; color: var(--mute); }
|
||||||
.is-dim .fav-mark { color: var(--mute-2); }
|
.is-dim .fav-mark { color: var(--mute-2); }
|
||||||
@@ -668,7 +550,6 @@ button { cursor: pointer; }
|
|||||||
.new-chapter { color: var(--ember); }
|
.new-chapter { color: var(--ember); }
|
||||||
.state { display: flex; align-items: center; gap: 4px; color: var(--mute); }
|
.state { display: flex; align-items: center; gap: 4px; color: var(--mute); }
|
||||||
.state svg { width: 10px; height: 10px; }
|
.state svg { width: 10px; height: 10px; }
|
||||||
.state.finished { color: var(--moss); }
|
|
||||||
.is-dim .meta { color: var(--mute-2); }
|
.is-dim .meta { color: var(--mute-2); }
|
||||||
.is-dim .site-asura, .is-dim .site-demonic,
|
.is-dim .site-asura, .is-dim .site-demonic,
|
||||||
.is-dim .site-comix, .is-dim .site-kagane,
|
.is-dim .site-comix, .is-dim .site-kagane,
|
||||||
@@ -683,7 +564,7 @@ button { cursor: pointer; }
|
|||||||
}
|
}
|
||||||
.libswitch a {
|
.libswitch a {
|
||||||
padding: 7px 13px;
|
padding: 7px 13px;
|
||||||
font: 500 11px/1 var(--font-mono);
|
font: 500 10px/1 var(--font-mono);
|
||||||
letter-spacing: .12em;
|
letter-spacing: .12em;
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
color: var(--mute);
|
color: var(--mute);
|
||||||
@@ -731,39 +612,28 @@ button { cursor: pointer; }
|
|||||||
.actions > *:last-child { border-right: none; }
|
.actions > *:last-child { border-right: none; }
|
||||||
.actions svg { width: 17px; height: 17px; }
|
.actions svg { width: 17px; height: 17px; }
|
||||||
.actions > *:hover { color: var(--paper); }
|
.actions > *:hover { color: var(--paper); }
|
||||||
/* Per-action accent on hover and press: gold favourite, slate archive, clay
|
/* Per-action accent on hover and press: gold favourite, slate archive, moss
|
||||||
chapter. Remove keeps --danger, play keeps paper/ember. */
|
finished, 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:hover, .actions .fav:active, .actions .fav:focus-visible { color: var(--brass); }
|
||||||
.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); }
|
||||||
.actions .pencil:hover, .actions .pencil:active, .actions .pencil:focus-visible { color: var(--clay); background: var(--clay-wash); }
|
.actions .box:hover, .actions .box:active, .actions .box:focus-visible { color: var(--slate); }
|
||||||
.actions .pencil:focus-visible { outline: 2px solid var(--clay); outline-offset: -2px; }
|
.actions .finish:hover, .actions .finish:active, .actions .finish:focus-visible { color: var(--moss); }
|
||||||
.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; }
|
|
||||||
.actions .play { color: var(--paper); }
|
.actions .play { color: var(--paper); }
|
||||||
|
|
||||||
.is-new .actions .play { color: var(--ember); }
|
.is-new .actions .play { color: var(--ember); }
|
||||||
.actions .play:hover { background: var(--hover); }
|
.actions .play:hover { background: var(--hover); }
|
||||||
.is-new .actions .play:hover { background: var(--ember-wash); color: var(--ember); }
|
.actions .on { color: var(--brass); }
|
||||||
.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 .restore { color: var(--paper); }
|
.actions .restore { color: var(--paper); }
|
||||||
.actions .restore:hover, .actions .restore:active, .actions .restore:focus-visible { color: var(--slate); background: var(--slate-wash); }
|
.actions .remove { color: var(--trash); }
|
||||||
.actions .restore:focus-visible { outline: 2px solid var(--slate); outline-offset: -2px; }
|
.actions .remove:hover { color: var(--danger); }
|
||||||
.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 .open { background: var(--hover); color: var(--paper); }
|
.actions .open { background: var(--hover); color: var(--paper); }
|
||||||
/* Lifecycle cells already sit on --ash, which is what --hover resolves to, so
|
/* 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. */
|
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 { 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); }
|
.actions .remove.open { background: var(--danger-wash); color: var(--danger); }
|
||||||
.is-dim .actions > * { color: var(--mute-2); }
|
.is-dim .actions > * { color: var(--mute-2); }
|
||||||
.is-dim .actions > *:hover { background: transparent; color: var(--mute); }
|
|
||||||
|
|
||||||
/* Two clusters by consequence: navigate (play) | organize (favourite,
|
/* Three clusters by consequence: navigate (play) | organize (favourite,
|
||||||
chapter) | lifecycle (archive/restore, remove). The lifecycle cells
|
chapter) | lifecycle (archive/restore, finish, remove). The lifecycle cells
|
||||||
sit on a recessed ground so the thumb reads "this one moves the series"
|
sit on a recessed ground so the thumb reads "this one moves the series"
|
||||||
before it reads which icon it landed on. */
|
before it reads which icon it landed on. */
|
||||||
.actions > .lifecycle { background: var(--ash); }
|
.actions > .lifecycle { background: var(--ash); }
|
||||||
@@ -783,7 +653,7 @@ button { cursor: pointer; }
|
|||||||
}
|
}
|
||||||
.chapter-form .hint {
|
.chapter-form .hint {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
font: 500 11px/1 var(--font-mono);
|
font: 500 10px/1 var(--font-mono);
|
||||||
letter-spacing: .14em;
|
letter-spacing: .14em;
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
color: var(--mute-2);
|
color: var(--mute-2);
|
||||||
@@ -800,10 +670,9 @@ button { cursor: pointer; }
|
|||||||
font: 500 17px var(--font-mono);
|
font: 500 17px var(--font-mono);
|
||||||
outline: none;
|
outline: none;
|
||||||
}
|
}
|
||||||
/* Clay carries the chapter action -- paper flashes on a dimmed OLED and ember
|
/* Focus follows the .searchbar idiom — paper, not heat: a red border on a
|
||||||
reads as "invalid" on a valid number. */
|
valid number field reads as "invalid". */
|
||||||
.chapter-form input:focus { border-color: var(--clay); }
|
.chapter-form input:focus { border-color: var(--paper); }
|
||||||
.chapter-form input:focus-visible { border-color: var(--clay); outline: 2px solid var(--clay); outline-offset: 2px; }
|
|
||||||
.chapter-form input::-webkit-outer-spin-button,
|
.chapter-form input::-webkit-outer-spin-button,
|
||||||
.chapter-form input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
|
.chapter-form input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
|
||||||
.chapter-form button {
|
.chapter-form button {
|
||||||
@@ -814,7 +683,6 @@ button { cursor: pointer; }
|
|||||||
color: var(--ink);
|
color: var(--ink);
|
||||||
font: 400 17px var(--font-display);
|
font: 400 17px var(--font-display);
|
||||||
}
|
}
|
||||||
.chapter-form button:focus-visible { outline: 2px solid var(--clay); outline-offset: 2px; }
|
|
||||||
|
|
||||||
.confirm-row {
|
.confirm-row {
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -827,26 +695,24 @@ button { cursor: pointer; }
|
|||||||
}
|
}
|
||||||
/* The remove question names the series, so it has to be able to take the row
|
/* 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. */
|
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 div { display: flex; flex: none; gap: 12px; margin-left: auto; }
|
||||||
.confirm-row button {
|
.confirm-row button {
|
||||||
height: 46px;
|
height: 46px;
|
||||||
padding: 0 14px;
|
padding: 0 14px;
|
||||||
border: 1px solid var(--field-line);
|
border: 1px solid var(--field-line);
|
||||||
background: var(--ash);
|
background: transparent;
|
||||||
color: var(--paper-dim);
|
color: var(--mute);
|
||||||
font: 500 12px var(--font-body);
|
font: 500 12px var(--font-body);
|
||||||
}
|
}
|
||||||
.confirm-row button:hover { color: var(--paper); border-color: var(--paper); }
|
.confirm-row button:hover { 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 .danger-solid {
|
.confirm-row .danger-solid {
|
||||||
border: none;
|
border: none;
|
||||||
background: var(--danger);
|
background: var(--danger);
|
||||||
color: var(--danger-ink);
|
color: var(--danger-ink);
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
}
|
}
|
||||||
.confirm-row .danger-solid:focus-visible { outline-color: var(--danger); }
|
/* Archive and finish are reversible, so their confirm asks in grey — only the
|
||||||
/* Archive is reversible, so its confirm asks in grey — only the
|
|
||||||
irreversible remove gets the danger wash. */
|
irreversible remove gets the danger wash. */
|
||||||
.confirm-row.calm { background: var(--ash); }
|
.confirm-row.calm { background: var(--ash); }
|
||||||
.confirm-row.calm span { color: var(--paper-dim); }
|
.confirm-row.calm span { color: var(--paper-dim); }
|
||||||
@@ -856,31 +722,16 @@ button { cursor: pointer; }
|
|||||||
color: var(--ink);
|
color: var(--ink);
|
||||||
font-weight: 600;
|
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 {
|
.error-inline {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 9px;
|
gap: 9px;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 11px 13px;
|
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);
|
background: var(--ash);
|
||||||
border-left: 2px solid var(--patina);
|
border-left: 2px solid var(--mute);
|
||||||
border-bottom: 1px solid var(--rule);
|
|
||||||
font: 400 16px var(--font-display);
|
font: 400 16px var(--font-display);
|
||||||
color: var(--paper-dim);
|
color: var(--paper-dim);
|
||||||
}
|
}
|
||||||
@@ -890,22 +741,13 @@ button { cursor: pointer; }
|
|||||||
width: 5px;
|
width: 5px;
|
||||||
height: 5px;
|
height: 5px;
|
||||||
border-radius: 50%;
|
border-radius: 50%;
|
||||||
background: var(--danger);
|
background: var(--mute);
|
||||||
}
|
|
||||||
.notice::before {
|
|
||||||
content: "";
|
|
||||||
flex: none;
|
|
||||||
width: 5px;
|
|
||||||
height: 5px;
|
|
||||||
border-radius: 50%;
|
|
||||||
background: var(--patina);
|
|
||||||
animation: mutePulse 1.4s ease-in-out infinite;
|
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);
|
border-bottom: 1px solid var(--field-line);
|
||||||
color: var(--paper);
|
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
|
/* Busy: a grey hairline slides across the top of the sheet — deliberately not
|
||||||
ember, which on a list screen only ever means "new chapter". */
|
ember, which on a list screen only ever means "new chapter". */
|
||||||
@@ -920,22 +762,6 @@ button { cursor: pointer; }
|
|||||||
background: var(--mute);
|
background: var(--mute);
|
||||||
animation: barSlide 1.15s linear infinite;
|
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 ---- */
|
||||||
.empty {
|
.empty {
|
||||||
@@ -944,7 +770,7 @@ button { cursor: pointer; }
|
|||||||
gap: 7px;
|
gap: 7px;
|
||||||
padding: 40px 20px 48px;
|
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 {
|
.empty .clear-search {
|
||||||
align-self: flex-start;
|
align-self: flex-start;
|
||||||
margin-top: 4px;
|
margin-top: 4px;
|
||||||
@@ -968,26 +794,21 @@ button { cursor: pointer; }
|
|||||||
.login-card {
|
.login-card {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
max-width: 420px;
|
max-width: 420px;
|
||||||
min-height: calc(100vh / var(--zoom));
|
min-height: 100vh;
|
||||||
min-height: calc(100dvh / var(--zoom));
|
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
padding: 52px 28px 40px;
|
padding: 52px 28px 40px;
|
||||||
}
|
}
|
||||||
.login-card .eyebrow {
|
.login-card .eyebrow {
|
||||||
font: 500 11px/1 var(--font-mono);
|
font: 500 10px/1 var(--font-mono);
|
||||||
letter-spacing: .2em;
|
letter-spacing: .2em;
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
color: var(--mute-2);
|
color: var(--mute-2);
|
||||||
}
|
}
|
||||||
.login-card h1 {
|
.login-card h1 {
|
||||||
margin: 14px 0 0;
|
margin: 14px 0 0;
|
||||||
/* The wordmark is the widest unbreakable run in the app; at 44px it is
|
font: 400 44px/1 var(--font-display);
|
||||||
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);
|
|
||||||
letter-spacing: -.01em;
|
letter-spacing: -.01em;
|
||||||
color: var(--paper);
|
color: var(--paper);
|
||||||
}
|
}
|
||||||
@@ -1038,7 +859,7 @@ button { cursor: pointer; }
|
|||||||
keeps every proportion — hairlines, cover ratios, hit targets —
|
keeps every proportion — hairlines, cover ratios, hit targets —
|
||||||
intact. ---- */
|
intact. ---- */
|
||||||
@media (min-width: 1280px) {
|
@media (min-width: 1280px) {
|
||||||
:root { --zoom: 1.2; zoom: var(--zoom); }
|
:root { zoom: 1.2; }
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ---- desktop: same measure, actions fold up beside the row ---- */
|
/* ---- desktop: same measure, actions fold up beside the row ---- */
|
||||||
@@ -1058,7 +879,6 @@ button { cursor: pointer; }
|
|||||||
}
|
}
|
||||||
.tabs { order: 1; flex: none; gap: 20px; padding: 0; border-bottom: none; }
|
.tabs { order: 1; flex: none; gap: 20px; padding: 0; border-bottom: none; }
|
||||||
.tabs a { padding: 10px 0 14px; font-size: 18px; }
|
.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; }
|
.searchbar { order: 2; flex: 1; margin: 0; border-bottom: none; }
|
||||||
.recent h2, .recent-strip { padding-left: 32px; padding-right: 32px; }
|
.recent h2, .recent-strip { padding-left: 32px; padding-right: 32px; }
|
||||||
.keyrow {
|
.keyrow {
|
||||||
@@ -1070,7 +890,8 @@ button { cursor: pointer; }
|
|||||||
}
|
}
|
||||||
.keyrow .pair { flex-direction: row; gap: 7px; }
|
.keyrow .pair { flex-direction: row; gap: 7px; }
|
||||||
.keyrow .pair svg { width: 14px; height: 14px; }
|
.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-card, .recent-cover { width: var(--cover-w); }
|
||||||
.recent-cover { height: calc(var(--cover-w) * 4 / 3); }
|
.recent-cover { height: calc(var(--cover-w) * 4 / 3); }
|
||||||
.recent-title { font-size: 17px; }
|
.recent-title { font-size: 17px; }
|
||||||
@@ -1091,29 +912,17 @@ button { cursor: pointer; }
|
|||||||
than by the hairline the phone layout uses. */
|
than by the hairline the phone layout uses. */
|
||||||
.actions > .play + *,
|
.actions > .play + *,
|
||||||
.actions > *:not(.lifecycle) + .lifecycle { margin-left: 10px; box-shadow: none; }
|
.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); }
|
.is-new .actions .play { border-color: var(--play-hot-line); }
|
||||||
.actions .on { border-color: var(--fav-line); }
|
.actions .on { border-color: var(--fav-line); }
|
||||||
/* The cell border follows the icon on hover, so the accent reads as a state
|
/* The cell border follows the icon on hover, so the accent reads as a state
|
||||||
rather than a stray colour. */
|
rather than a stray colour. */
|
||||||
.actions .fav:hover, .actions .pencil:hover,
|
.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 {
|
.chapter-form, .confirm-row, .error-inline {
|
||||||
margin-left: calc(var(--cover-w) + var(--row-gap));
|
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) {
|
@media (prefers-reduced-motion: reduce) {
|
||||||
@@ -1121,7 +930,4 @@ button { cursor: pointer; }
|
|||||||
busy bar and error dot are both ::before. Their static form still reads:
|
busy bar and error dot are both ::before. Their static form still reads:
|
||||||
the bar stays drawn and .actions stays dimmed. */
|
the bar stays drawn and .actions stays dimmed. */
|
||||||
*, *::before, *::after { animation: none !important; transition: none !important; }
|
*, *::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; }
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,17 +7,12 @@
|
|||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||||
<meta name="color-scheme" content="dark light">
|
<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>
|
<title>BookmarkManager — Admin</title>
|
||||||
<link rel="icon" href="/static/logo.svg" type="image/svg+xml">
|
<link rel="icon" href="/static/logo.svg" type="image/svg+xml">
|
||||||
<link rel="stylesheet" href="/static/style.css">
|
<link rel="stylesheet" href="/static/style.css">
|
||||||
<link rel="stylesheet" href="/static/admin.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/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/htmx.min.js" defer></script>
|
||||||
<script src="/static/filter.js" defer></script>
|
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="sheet admin-sheet">
|
<div class="sheet admin-sheet">
|
||||||
@@ -38,14 +33,9 @@
|
|||||||
<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>
|
<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>
|
</nav>
|
||||||
|
|
||||||
{{/* 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">
|
<main class="page admin-page">
|
||||||
{{if eq .Page "lanes"}}
|
{{if eq .Page "lanes"}}
|
||||||
{{template "lanes" .Lanes}}
|
<div aria-live="polite">{{template "lanes" .Lanes}}</div>
|
||||||
{{else if eq .Page "readers"}}
|
{{else if eq .Page "readers"}}
|
||||||
{{template "readers" .}}
|
{{template "readers" .}}
|
||||||
{{else if eq .Page "series"}}
|
{{else if eq .Page "series"}}
|
||||||
|
|||||||
@@ -5,11 +5,6 @@
|
|||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||||
<meta name="color-scheme" content="dark light">
|
<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>
|
<title>BookmarkManager</title>
|
||||||
<link rel="icon" href="/static/logo.svg" type="image/svg+xml">
|
<link rel="icon" href="/static/logo.svg" type="image/svg+xml">
|
||||||
<link rel="stylesheet" href="/static/style.css">
|
<link rel="stylesheet" href="/static/style.css">
|
||||||
@@ -58,39 +53,38 @@
|
|||||||
<a href="{{.PageURL "all"}}" class="{{if eq .Tab "all"}}active{{end}}"
|
<a href="{{.PageURL "all"}}" class="{{if eq .Tab "all"}}active{{end}}"
|
||||||
{{if eq .Tab "all"}}aria-current="page"{{end}}
|
{{if eq .Tab "all"}}aria-current="page"{{end}}
|
||||||
hx-get="{{.ListURL "all"}}" hx-target="#list" hx-swap="innerHTML"
|
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
|
{{/* 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. */}}
|
that I have not read", the tab would only ever restate All. */}}
|
||||||
{{if eq .Lib "manga"}}
|
{{if eq .Lib "manga"}}
|
||||||
<a href="{{.PageURL "new"}}" class="tab-new {{if eq .Tab "new"}}active{{end}}"
|
<a href="{{.PageURL "new"}}" class="tab-new {{if eq .Tab "new"}}active{{end}}"
|
||||||
{{if eq .Tab "new"}}aria-current="page"{{end}}
|
{{if eq .Tab "new"}}aria-current="page"{{end}}
|
||||||
hx-get="{{.ListURL "new"}}" hx-target="#list" hx-swap="innerHTML"
|
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>
|
{{template "newcount" .}}</a>
|
||||||
{{end}}
|
{{end}}
|
||||||
<a href="{{.PageURL "fav"}}" class="{{if eq .Tab "fav"}}active{{end}}"
|
<a href="{{.PageURL "fav"}}" class="{{if eq .Tab "fav"}}active{{end}}"
|
||||||
{{if eq .Tab "fav"}}aria-current="page"{{end}}
|
{{if eq .Tab "fav"}}aria-current="page"{{end}}
|
||||||
hx-get="{{.ListURL "fav"}}" hx-target="#list" hx-swap="innerHTML"
|
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}}"
|
<a href="{{.PageURL "archived"}}" class="{{if eq .Tab "archived"}}active{{end}}"
|
||||||
{{if eq .Tab "archived"}}aria-current="page"{{end}}
|
{{if eq .Tab "archived"}}aria-current="page"{{end}}
|
||||||
hx-get="{{.ListURL "archived"}}" hx-target="#list" hx-swap="innerHTML"
|
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>
|
</nav>
|
||||||
</div>
|
</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 "setup" .}}
|
||||||
|
|
||||||
{{template "keyrow" .}}
|
{{template "keyrow" .}}
|
||||||
|
|
||||||
{{template "recent" .}}
|
{{template "recent" .}}
|
||||||
|
|
||||||
<main id="list" class="list" tabindex="-1">
|
<main id="list" class="list">
|
||||||
{{template "list" .}}
|
{{template "list" .}}
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,22 +1,16 @@
|
|||||||
{{define "card"}}
|
{{define "card"}}
|
||||||
{{/* One sheet per series. is-new turns the title crimson over an ember rule;
|
{{/* 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}}"
|
<article class="card{{if eq .Status "reading"}}{{if .HasNewChapter}} is-new{{end}}{{else}} is-dim{{end}}"
|
||||||
id="card-{{.Key}}" data-title="{{.Title}}">
|
id="card-{{.Key}}" data-title="{{.Title}}">
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<a class="cover" href="{{.ContinueURL}}" target="_blank" rel="noopener noreferrer"
|
<a class="cover" href="{{.ContinueURL}}" target="_blank" rel="noopener noreferrer"
|
||||||
tabindex="-1" aria-hidden="true">
|
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
|
{{/* aria-hidden on the cover link is not enough — Chromium still exposes
|
||||||
the letter because the link is programmatically focusable — so the
|
the letter because the link is programmatically focusable — so the
|
||||||
monogram carries its own, same as the recent strip's.
|
monogram carries its own, same as the recent strip's. */}}
|
||||||
|
{{else}}<span class="monogram" aria-hidden="true">{{.Initial}}</span>{{end}}
|
||||||
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>
|
|
||||||
{{if and (eq .Status "reading") .HasNewChapter}}<span class="foot-rule"></span>
|
{{if and (eq .Status "reading") .HasNewChapter}}<span class="foot-rule"></span>
|
||||||
{{else if .Favorite}}<span class="foot-rule brass"></span>{{end}}
|
{{else if .Favorite}}<span class="foot-rule brass"></span>{{end}}
|
||||||
</a>
|
</a>
|
||||||
@@ -38,10 +32,9 @@
|
|||||||
{{if eq .Status "archived"}}
|
{{if eq .Status "archived"}}
|
||||||
<span class="sep">/</span>
|
<span class="sep">/</span>
|
||||||
<span class="state">archived</span>
|
<span class="state">archived</span>
|
||||||
{{end}}
|
{{else if eq .Status "finished"}}
|
||||||
{{if .Finished}}
|
|
||||||
<span class="sep">/</span>
|
<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}}
|
{{end}}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -52,19 +45,18 @@
|
|||||||
</a>
|
</a>
|
||||||
<button class="fav{{if .Favorite}} on{{end}}"
|
<button class="fav{{if .Favorite}} on{{end}}"
|
||||||
title="{{if .Favorite}}Remove from favourites{{else}}Add to favourites{{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-label="Toggle favourite"
|
||||||
aria-pressed="{{if .Favorite}}true{{else}}false{{end}}"
|
|
||||||
hx-post="/ui/bookmarks/{{.Key}}/favorite"
|
hx-post="/ui/bookmarks/{{.Key}}/favorite"
|
||||||
hx-target="[id='card-{{.Key}}']" hx-swap="outerHTML"
|
hx-target="[id='card-{{.Key}}']" hx-swap="outerHTML"
|
||||||
hx-indicator="[id='card-{{.Key}}']" hx-disabled-elt="this">
|
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>
|
<svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-star{{if .Favorite}}-on{{end}}"/></svg>
|
||||||
</button>
|
</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}}')">
|
onclick="toggleChapterForm('{{.Key}}')">
|
||||||
<svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-pencil"/></svg>
|
<svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-pencil"/></svg>
|
||||||
</button>
|
</button>
|
||||||
{{/* Restore is a reversal, so it fires straight away; every move *out* of
|
{{/* 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"}}
|
{{if eq .Status "reading"}}
|
||||||
<button class="lifecycle box" title="Archive" aria-label="Archive"
|
<button class="lifecycle box" title="Archive" aria-label="Archive"
|
||||||
aria-expanded="false" aria-controls="confirm-archive-{{.Key}}"
|
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>
|
<svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-undo"/></svg>
|
||||||
</button>
|
</button>
|
||||||
{{end}}
|
{{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"
|
<button class="lifecycle remove" title="Remove" aria-label="Remove"
|
||||||
aria-expanded="false" aria-controls="confirm-remove-{{.Key}}"
|
aria-expanded="false" aria-controls="confirm-remove-{{.Key}}"
|
||||||
onclick="toggleConfirmRow('{{.Key}}', 'remove')">
|
onclick="toggleConfirmRow('{{.Key}}', 'remove')">
|
||||||
@@ -95,11 +94,8 @@
|
|||||||
label names the field and the latest sits after it as context. */}}
|
label names the field and the latest sits after it as context. */}}
|
||||||
<label class="hint" for="chapter-{{.Key}}">Chapter you're on</label>
|
<label class="hint" for="chapter-{{.Key}}">Chapter you're on</label>
|
||||||
<div class="field">
|
<div class="field">
|
||||||
{{/* max is a fat-finger guard, not a real ceiling — no series is near it.
|
{{/* 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
|
<input id="chapter-{{.Key}}" name="chapter" type="number" step="0.1" min="0" max="9999"
|
||||||
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"
|
|
||||||
value="{{.LastChapterNum}}" required>
|
value="{{.LastChapterNum}}" required>
|
||||||
<button type="submit">Save</button>
|
<button type="submit">Save</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -120,6 +116,18 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{{end}}
|
{{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>
|
<div class="confirm-row" id="confirm-remove-{{.Key}}" role="group" aria-live="polite" hidden>
|
||||||
<span>Remove “{{.Title}}”? Chapter progress is lost.</span>
|
<span>Remove “{{.Title}}”? Chapter progress is lost.</span>
|
||||||
<div>
|
<div>
|
||||||
|
|||||||
@@ -14,9 +14,8 @@
|
|||||||
<a class="recent-card {{if .HasNewChapter}}is-new{{end}}" href="{{.ContinueURL}}"
|
<a class="recent-card {{if .HasNewChapter}}is-new{{end}}" href="{{.ContinueURL}}"
|
||||||
target="_blank" rel="noopener noreferrer">
|
target="_blank" rel="noopener noreferrer">
|
||||||
<span class="recent-cover">
|
<span class="recent-cover">
|
||||||
{{/* Monogram always present under the image; see card.html. */}}
|
{{if .Cover}}<img src="{{.Cover}}" alt="" loading="lazy">
|
||||||
{{if .Cover}}<img src="{{.Cover}}" alt="" loading="lazy" onerror="this.remove()">{{end}}
|
{{else}}<span class="monogram" aria-hidden="true">{{.Initial}}</span>{{end}}
|
||||||
<span class="monogram" aria-hidden="true">{{.Initial}}</span>
|
|
||||||
{{if .HasNewChapter}}<span class="foot-rule"></span>
|
{{if .HasNewChapter}}<span class="foot-rule"></span>
|
||||||
{{else if .Favorite}}<span class="foot-rule brass"></span>{{end}}
|
{{else if .Favorite}}<span class="foot-rule brass"></span>{{end}}
|
||||||
</span>
|
</span>
|
||||||
@@ -30,16 +29,20 @@
|
|||||||
|
|
||||||
{{/* The action key. The icon strip on a card is unlabelled, so one permanent
|
{{/* 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
|
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"}}
|
{{define "keyrow"}}
|
||||||
<div class="keyrow" id="keyrow" aria-label="Action key"{{if .OOB}} hx-swap-oob="true"{{end}}>
|
<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"><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 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>
|
<span class="pair"><svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-pencil"/></svg><span>Chapter</span></span>
|
||||||
{{if eq .Tab "archived"}}
|
{{if or (eq .Tab "archived") (eq .Tab "finished")}}
|
||||||
<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-undo"/></svg><span>Restore</span></span>
|
||||||
{{else}}
|
{{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}}
|
{{end}}
|
||||||
<span class="pair trash"><svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-trash"/></svg><span>Delete</span></span>
|
<span class="pair trash"><svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-trash"/></svg><span>Delete</span></span>
|
||||||
</div>
|
</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-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-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-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-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-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>
|
<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>
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
this template only prints them. */}}
|
this template only prints them. */}}
|
||||||
{{define "lanes"}}
|
{{define "lanes"}}
|
||||||
<section class="lanes" id="lanes"
|
<section class="lanes" id="lanes"
|
||||||
hx-get="/ui/admin/lanes" hx-trigger="every 30s" hx-swap="outerHTML" hx-sync="this:replace">
|
hx-get="/ui/admin/lanes" hx-trigger="every 30s" hx-swap="outerHTML">
|
||||||
<div class="sechead">
|
<div class="sechead">
|
||||||
<h2 class="sec">Poll Lanes</h2>
|
<h2 class="sec">Poll Lanes</h2>
|
||||||
<p class="statusline">
|
<p class="statusline">
|
||||||
@@ -18,23 +18,20 @@
|
|||||||
{{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}}
|
{{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>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<p class="hint">Healthy idle (paused, browser asleep, nothing eligible) needs no action — attention needs the owner.</p>
|
|
||||||
{{if .Rows}}
|
{{if .Rows}}
|
||||||
<div class="tbl lanes">
|
<div class="tbl lanes">
|
||||||
<div class="thead">
|
<div class="thead">
|
||||||
<span>Site</span><span>Due</span><span>Checked</span><span>Gap</span>
|
<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>
|
<span>Last pass</span><span>Outcomes · state</span><span></span>
|
||||||
</div>
|
</div>
|
||||||
{{range .Rows}}
|
{{range .Rows}}
|
||||||
<div class="trow{{if .Attention}} attention{{end}}">
|
<div class="trow{{if .Attention}} attention{{end}}">
|
||||||
<a class="c-site" href="{{.FailingHref}}">{{.Site}}</a>
|
<span class="c-site">{{.Site}}</span>
|
||||||
{{/* data-label is the column word for the phone layout, which drops the
|
<span>{{.Due}}</span>
|
||||||
thead: three bare numbers in a row say nothing. */}}
|
<span>{{.Checked}}</span>
|
||||||
<span data-label="due">{{.Due}}</span>
|
<span>{{.Gap}}</span>
|
||||||
<span data-label="checked">{{.Checked}}</span>
|
|
||||||
<span data-label="gap">{{.Gap}}</span>
|
|
||||||
<span>ran {{.Ran}}</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>
|
<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}}">{{.StatePhrase}}</span>{{end}}</span>
|
||||||
{{/* The pause control lives in the one slot the design leaves for it:
|
{{/* 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
|
a running Lane offers the three durations and Pause; a paused Lane
|
||||||
offers Resume in the same place. Pause is not destruction — it
|
offers Resume in the same place. Pause is not destruction — it
|
||||||
@@ -42,11 +39,11 @@
|
|||||||
confirm row or the danger accent. The form wraps the select so the
|
confirm row or the danger accent. The form wraps the select so the
|
||||||
offered duration travels with the press. */}}
|
offered duration travels with the press. */}}
|
||||||
<span class="c-ctrl">{{if .Paused}}<span class="pausebar">
|
<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">
|
<form hx-post="/admin/lanes/{{.Site}}/resume" hx-target="#lanes" hx-swap="outerHTML">
|
||||||
<button type="submit" class="ghost">Resume</button>
|
<button type="submit" class="ghost">Resume</button>
|
||||||
</form>
|
</form>
|
||||||
</span>{{else}}<span class="pausebar">
|
</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">
|
<form hx-post="/admin/lanes/{{.Site}}/pause" hx-target="#lanes" hx-swap="outerHTML">
|
||||||
<select name="duration" aria-label="Pause duration">
|
<select name="duration" aria-label="Pause duration">
|
||||||
<option>1h</option><option selected>6h</option><option>24h</option>
|
<option>1h</option><option selected>6h</option><option>24h</option>
|
||||||
</select>
|
</select>
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
{{/* The client filter only hides cards, so without this the list area goes
|
{{/* 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
|
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. */}}
|
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>
|
<strong>No titles match “<span class="no-match-q"></span>”.</strong>
|
||||||
<button type="button" class="clear-search">Clear search</button>
|
<button type="button" class="clear-search">Clear search</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -14,6 +14,8 @@
|
|||||||
<div class="empty"><strong>Nothing new.</strong><p>Every series is caught up to its latest chapter.</p></div>
|
<div class="empty"><strong>Nothing new.</strong><p>Every series is caught up to its latest chapter.</p></div>
|
||||||
{{else if eq .Tab "archived"}}
|
{{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>
|
<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}}
|
{{else if .EmptyLibrary}}
|
||||||
{{/* Nothing in either library, so the links are the only thing this page can
|
{{/* Nothing in either library, so the links are the only thing this page can
|
||||||
usefully say. Both scripts: the two libraries are separate installs. */}}
|
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="icon" href="/static/logo.svg" type="image/svg+xml">
|
||||||
<link rel="stylesheet" href="/static/style.css">
|
<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/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>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<main class="login-card">
|
<main class="login-card">
|
||||||
@@ -26,7 +25,7 @@
|
|||||||
<p class="error" role="alert">{{.Error}}</p>
|
<p class="error" role="alert">{{.Error}}</p>
|
||||||
<button type="submit">Continue with Discord</button>
|
<button type="submit">Continue with Discord</button>
|
||||||
</form>
|
</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>
|
</main>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -4,13 +4,11 @@
|
|||||||
figures link, what a Lane's state means — is made in Go; this template
|
figures link, what a Lane's state means — is made in Go; this template
|
||||||
only prints. */}}
|
only prints. */}}
|
||||||
{{define "overview"}}
|
{{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>
|
<p class="verdict"><span class="attn">{{.Verdict}}</span> {{if .HasCounts}}<span class="counts">· <b>{{.Waiting}}</b> series waiting · <b>{{.Unchecked}}</b> unchecked over 12h</span>{{end}}</p>
|
||||||
<h2 class="sec">Hygiene</h2>
|
<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>
|
<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>
|
<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>
|
<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>
|
<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}}
|
<div class="tbl sites"><div class="thead"><span>Site</span><span>Series</span><span>No cover</span><span>Never chk</span><span>Stale</span><span>State</span></div>{{range .Sites}}<div class="trow"><a class="c-site site-{{.Site}}" href="{{.SiteHref}}">{{.Site}}</a>{{range .Figs}}{{if .Href}}<a class="fig" href="{{.Href}}">{{.Count}}</a>{{else}}<span class="fig zero">{{.Count}}</span>{{end}}{{end}}<span class="c-state{{if .StateGood}} ok{{end}}{{if .StateBad}} bad{{end}}">{{.State}}</span></div>{{end}}</div>
|
||||||
{{end}}
|
{{end}}
|
||||||
|
|||||||
@@ -13,10 +13,9 @@
|
|||||||
often a later Poll confirmed or contradicted what that Reader's browser
|
often a later Poll confirmed or contradicted what that Reader's browser
|
||||||
reported; enough contradictions stop their reports deferring a Poll, and
|
reported; enough contradictions stop their reports deferring a Poll, and
|
||||||
clearing the marks gives that back.</p>
|
clearing the marks gives that back.</p>
|
||||||
{{if .Readers}}
|
|
||||||
<ul class="readerlist">
|
<ul class="readerlist">
|
||||||
{{range .Readers}}
|
{{range .Readers}}
|
||||||
<li id="reader-{{.ID}}">
|
<li>
|
||||||
<span class="reader-id">{{.DiscordID}}</span>
|
<span class="reader-id">{{.DiscordID}}</span>
|
||||||
<span class="reader-sessions">{{.Sessions}} session{{if ne .Sessions 1}}s{{end}}</span>
|
<span class="reader-sessions">{{.Sessions}} session{{if ne .Sessions 1}}s{{end}}</span>
|
||||||
<span class="reader-sightings">{{.Agreements}} confirmed / {{.Disagreements}} contradicted</span>
|
<span class="reader-sightings">{{.Agreements}} confirmed / {{.Disagreements}} contradicted</span>
|
||||||
@@ -24,42 +23,26 @@
|
|||||||
numbers and a threshold. */}}
|
numbers and a threshold. */}}
|
||||||
{{if .Blocked}}<span class="reader-blocked">deferral blocked</span>{{end}}
|
{{if .Blocked}}<span class="reader-blocked">deferral blocked</span>{{end}}
|
||||||
<span class="reader-actions">
|
<span class="reader-actions">
|
||||||
{{/* Clearing restores a privilege, so its confirm wears the calm wash,
|
{{/* Clearing restores a privilege, so it is a plain ghost button —
|
||||||
not destruction. Revocation destroys sessions, so it wears danger.
|
the destruction accent belongs to revocation alone. It is offered
|
||||||
Both are confirm-gated — the opener never posts. */}}
|
on every row, including one reading zero: the remedy must be
|
||||||
<button type="button" class="ghost" aria-expanded="false" aria-controls="confirm-clear-{{.ID}}"
|
findable before the counters climb, not after. */}}
|
||||||
onclick="document.getElementById('confirm-clear-{{.ID}}').hidden = false; this.setAttribute('aria-expanded','true')">Clear marks</button>
|
<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)}}
|
{{if and .Sessions (ne .ID $.OwnerID)}}
|
||||||
<button type="button" class="ghost danger" aria-expanded="false" aria-controls="confirm-revoke-{{.ID}}"
|
<form hx-post="/readers/{{.ID}}/revoke" hx-target="#readers" hx-swap="outerHTML"
|
||||||
onclick="document.getElementById('confirm-revoke-{{.ID}}').hidden = false; this.setAttribute('aria-expanded','true')">Revoke sessions</button>
|
hx-confirm="Revoking signs this Reader out on every device immediately. Revoke?">
|
||||||
|
<button type="submit" class="ghost danger">Revoke sessions</button>
|
||||||
|
</form>
|
||||||
{{end}}
|
{{end}}
|
||||||
</span>
|
</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>
|
</li>
|
||||||
{{end}}
|
{{end}}
|
||||||
</ul>
|
</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>
|
</section>
|
||||||
{{end}}
|
{{end}}
|
||||||
|
|||||||
@@ -9,77 +9,34 @@
|
|||||||
<h1 class="detail-title">{{.Title}}</h1>
|
<h1 class="detail-title">{{.Title}}</h1>
|
||||||
<p class="detail-key">{{.Key}} · {{.Site}} · {{.Kind}}</p>
|
<p class="detail-key">{{.Key}} · {{.Site}} · {{.Kind}}</p>
|
||||||
{{if .Cover}}<div class="cover"><img src="{{.Cover}}" alt="" loading="lazy"></div>
|
{{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}}
|
{{else}}<div class="cover"></div>{{end}}
|
||||||
{{template "series-detail-meta" .}}
|
{{template "series-detail-meta" .}}
|
||||||
<div class="detail-grid">
|
<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">
|
<form class="dform" hx-post="/admin/series/{{.Key}}/latest" hx-target="#detail-meta" hx-swap="outerHTML">
|
||||||
<h3>Correct latest chapter</h3>
|
<h3>Correct latest chapter</h3>
|
||||||
|
<p class="hint">The next successful Poll overwrites this value.</p>
|
||||||
<div class="field">
|
<div class="field">
|
||||||
<label class="sr-only" for="chapter-{{.Key}}">Latest chapter number</label>
|
<input type="number" name="chapter" step="any" placeholder="{{.Chapter}}" required>
|
||||||
<input id="chapter-{{.Key}}" type="number" name="chapter" step="any" placeholder="{{.Chapter}}" required aria-describedby="hint-latest-{{.Key}}">
|
<button type="submit" class="ghost">Set</button>
|
||||||
<button type="submit" class="ghost">Save chapter</button>
|
|
||||||
</div>
|
</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>
|
||||||
<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">
|
<form class="dform" hx-post="/admin/series/{{.Key}}/series-url" hx-target="#detail-meta" hx-swap="outerHTML">
|
||||||
<h3>Repair series URL</h3>
|
<h3>Repair series URL</h3>
|
||||||
|
<p class="hint">The Poll fetches this address — storing is not verifying it. A Site-wide host change is a SQL migration, not two hundred forms.</p>
|
||||||
<div class="field">
|
<div class="field">
|
||||||
<label class="sr-only" for="url-{{.Key}}">Series page URL</label>
|
<input type="url" name="series_url" value="{{.URL}}" required>
|
||||||
<input id="url-{{.Key}}" type="url" name="series_url" value="{{.URL}}" required aria-describedby="hint-url-{{.Key}}">
|
<button type="submit" class="ghost">Set</button>
|
||||||
<button type="submit" class="ghost">Save URL</button>
|
|
||||||
</div>
|
</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>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
{{if .CanPoll}}
|
{{if .CanPoll}}
|
||||||
<div class="dform">
|
<div class="dform">
|
||||||
<div class="field"><button type="button" class="ghost"
|
<div class="field"><a class="ghost act" hx-post="/admin/series/{{.Key}}/poll" hx-target="#detail-meta" hx-swap="outerHTML" href="#">Check now</a></div>
|
||||||
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>
|
</div>
|
||||||
{{end}}
|
{{end}}
|
||||||
{{if .CanRemove}}
|
{{if .CanRemove}}
|
||||||
<div class="dform">
|
<div class="dform">
|
||||||
<div class="field"><button type="button" class="ghost danger"
|
<div class="field"><button class="ghost danger" hx-post="/admin/series/{{.Key}}/remove" hx-target="#detail-meta" hx-confirm="Removes this series and its stored cover. No Reader has it bookmarked; one re-bookmarking it recreates the row.">Remove</button></div>
|
||||||
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>
|
</div>
|
||||||
{{end}}
|
{{end}}
|
||||||
{{end}}
|
{{end}}
|
||||||
@@ -90,14 +47,13 @@
|
|||||||
the provenance line beside the number — describe the value they sit
|
the provenance line beside the number — describe the value they sit
|
||||||
next to. */}}
|
next to. */}}
|
||||||
{{define "series-detail-meta"}}
|
{{define "series-detail-meta"}}
|
||||||
<div class="detail-meta" id="detail-meta" aria-live="polite">
|
<div class="detail-meta" id="detail-meta">
|
||||||
<span>ch {{.Chapter}}</span>
|
<span>ch {{.Chapter}}</span>
|
||||||
{{if .Provenance}}<span>{{.Provenance}}</span>{{end}}
|
{{if .Provenance}}<span>{{.Provenance}}</span>{{end}}
|
||||||
<span>checked {{.Checked}}</span>
|
<span>checked {{.Checked}}</span>
|
||||||
<span>{{.Readers}} reader{{if ne .Readers 1}}s{{end}}</span>
|
<span>{{.Readers}} readers</span>
|
||||||
{{if .Corrected}}<span class="mark">{{.Corrected}}</span>{{end}}
|
{{if .Corrected}}<span class="mark">{{.Corrected}}</span>{{end}}
|
||||||
{{if .Pending}}<span class="mark">{{.Requested}}</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 .Unpollable}}<span class="mark">unpollable</span>{{end}}
|
||||||
{{if .NoCover}}<span class="mark">no cover</span>{{end}}
|
{{if .NoCover}}<span class="mark">no cover</span>{{end}}
|
||||||
{{if .Orphan}}<span class="mark">orphan</span>{{end}}
|
{{if .Orphan}}<span class="mark">orphan</span>{{end}}
|
||||||
|
|||||||
@@ -6,14 +6,13 @@
|
|||||||
{{define "series-list"}}
|
{{define "series-list"}}
|
||||||
<form class="filterbar" id="filterbar" method="get" action="/admin/series">
|
<form class="filterbar" id="filterbar" method="get" action="/admin/series">
|
||||||
<input type="hidden" name="kind" value="{{.Kind}}">
|
<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">
|
<label class="fsel"><span>Show</span><select name="filter" onchange="this.form.submit()">
|
||||||
{{range .Filters}}<option value="{{.Name}}"{{if .Selected}} selected{{end}}>{{.Label}} ({{.Count}})</option>{{end}}
|
{{range .Filters}}<option value="{{.Name}}"{{if .Selected}} selected{{end}}>{{.Label}} ({{.Count}})</option>{{end}}
|
||||||
</select></label>
|
</select></label>
|
||||||
<label class="fsel"><span>Site</span><select name="site" onchange="this.form.submit()" aria-label="Filter by site — changes apply immediately">
|
<label class="fsel"><span>Site</span><select name="site" onchange="this.form.submit()">
|
||||||
<option value=""{{if not .Site}} selected{{end}}>All sites</option>
|
<option value=""{{if not .Site}} selected{{end}}>All sites</option>
|
||||||
{{range .Sites}}<option value="{{.}}"{{if eq $.Site .}} selected{{end}}>{{.}}</option>{{end}}
|
{{range .Sites}}<option value="{{.}}"{{if eq $.Site .}} selected{{end}}>{{.}}</option>{{end}}
|
||||||
</select></label>
|
</select></label>
|
||||||
<noscript><button type="submit" class="ghost">Apply</button></noscript>
|
|
||||||
<span class="segrow">
|
<span class="segrow">
|
||||||
<a href="{{.KindBoth}}"{{if not .Kind}} class="active"{{end}}>both</a>
|
<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="{{.KindManga}}"{{if eq .Kind "manga"}} class="active"{{end}}>manga</a>
|
||||||
@@ -42,32 +41,15 @@
|
|||||||
no page to fetch and on an orphan, so the owner is never offered a button
|
no page to fetch and on an orphan, so the owner is never offered a button
|
||||||
that can never do anything. */}}
|
that can never do anything. */}}
|
||||||
{{define "series-row"}}
|
{{define "series-row"}}
|
||||||
<div class="trow{{if .Attention}} attention{{end}}{{if .Band}} band{{end}}" id="row-{{.Key}}">
|
<div class="trow{{if .Attention}} attention{{end}}{{if .Band}} band{{end}}">
|
||||||
<span class="c-title"><a href="/admin/series/{{.Key}}">{{.Title}}</a>{{if .Pending}}<span class="mark">{{.Requested}}</span>{{end}}</span>
|
<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>
|
<span class="c-site site-{{.Site}}">{{.Site}}</span>
|
||||||
{{/* data-label is the column word for the phone layout, which drops the
|
<span class="c-ch">{{.Ch}}</span>
|
||||||
thead: "1200.25 3d 4" says nothing without it. */}}
|
<span>{{.Age}}</span>
|
||||||
<span class="c-ch" data-label="ch">{{.Ch}}</span>
|
<span class="c-rd">{{.Readers}}</span>
|
||||||
<span data-label="checked">{{.Age}}</span>
|
<span class="c-note">{{range .Notes}}<span class="mark">{{.}}</span>{{end}}{{if .More}}<span class="mark mark-faint">+{{.More}}</span>{{end}}</span>
|
||||||
<span class="c-rd" data-label="readers">{{.Readers}}</span>
|
<span class="c-act">{{if .CanPoll}}<a class="ghost act" hx-post="/admin/series/{{.Key}}/poll" hx-target="closest .trow" hx-swap="outerHTML" hx-vals='{"band":{{if .Band}}1{{else}}0{{end}}}' href="#">Check now</a>{{end}}{{if .CanRemove}}<button class="ghost danger" 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-confirm="Removes this series and its stored cover. No Reader has it bookmarked; one re-bookmarking it recreates the row.">Remove</button>{{end}}</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 .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>
|
</div>
|
||||||
{{end}}
|
{{end}}
|
||||||
|
|
||||||
|
|||||||
+23
-69
@@ -3,7 +3,6 @@ package web
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"embed"
|
"embed"
|
||||||
"fmt"
|
|
||||||
"html/template"
|
"html/template"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
"log"
|
"log"
|
||||||
@@ -30,14 +29,6 @@ var staticFS embed.FS
|
|||||||
// RecentCount is how many series the "Continue reading" strip shows.
|
// RecentCount is how many series the "Continue reading" strip shows.
|
||||||
const RecentCount = 5
|
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/.
|
// 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
|
// It is a separate handler from api.Handler because the two speak different
|
||||||
// representations (HTML versus JSON) to different clients under different auth.
|
// representations (HTML versus JSON) to different clients under different auth.
|
||||||
@@ -119,7 +110,6 @@ func (v listView) ListURL(tab string) string {
|
|||||||
// loginView is what the login template receives.
|
// loginView is what the login template receives.
|
||||||
type loginView struct {
|
type loginView struct {
|
||||||
Error string
|
Error string
|
||||||
GuildName string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// New parses every template up front so a broken one kills the process at
|
// New parses every template up front so a broken one kills the process at
|
||||||
@@ -253,7 +243,7 @@ func (h *Handler) render(w http.ResponseWriter, status int, name string, data an
|
|||||||
func (h *Handler) index(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) index(w http.ResponseWriter, r *http.Request) {
|
||||||
readerID, ok := h.sessionReader(r)
|
readerID, ok := h.sessionReader(r)
|
||||||
if !ok {
|
if !ok {
|
||||||
h.render(w, http.StatusOK, "login", loginView{GuildName: h.discord.GuildName})
|
h.render(w, http.StatusOK, "login", loginView{})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
view, err := h.buildListView(readerID, libOf(r.URL.Query().Get("lib")), r.URL.Query().Get("tab"))
|
view, err := h.buildListView(readerID, libOf(r.URL.Query().Get("lib")), r.URL.Query().Get("tab"))
|
||||||
@@ -303,11 +293,10 @@ func libOf(q string) string {
|
|||||||
// buildListView loads one reader's list once and derives both the tab-filtered
|
// buildListView loads one reader's list once and derives both the tab-filtered
|
||||||
// items and the recent strip from it.
|
// items and the recent strip from it.
|
||||||
//
|
//
|
||||||
// Archived series appear in their own tab and nowhere else — not in All, not
|
// Archived and finished series appear in their own tab and nowhere else — not
|
||||||
// in Updated, not in Favourites, and not in the recent strip. An archived
|
// in All, not in Updated, not in Favourites, and not in the recent strip. An
|
||||||
// favourite therefore shows only under Archived: Favourites means "favourites
|
// archived favourite therefore shows only under Archived: Favourites means
|
||||||
// I am currently reading". There is no Finished tab: finished is a fact about
|
// "favourites I am currently reading".
|
||||||
// the Series, not a bookmark bucket (issue #157).
|
|
||||||
func (h *Handler) buildListView(readerID int64, lib, tab string) (listView, error) {
|
func (h *Handler) buildListView(readerID int64, lib, tab string) (listView, error) {
|
||||||
all, err := h.store.List(readerID) // already ordered updated_at DESC
|
all, err := h.store.List(readerID) // already ordered updated_at DESC
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -338,6 +327,8 @@ func (h *Handler) buildListView(readerID int64, lib, tab string) (listView, erro
|
|||||||
items = withNew
|
items = withNew
|
||||||
case "archived":
|
case "archived":
|
||||||
items = filterBookmarks(all, func(b store.Bookmark) bool { return b.Status == store.StatusArchived })
|
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:
|
default:
|
||||||
tab = "all"
|
tab = "all"
|
||||||
items = reading
|
items = reading
|
||||||
@@ -401,7 +392,7 @@ func currentLib(r *http.Request) string {
|
|||||||
// writeChromeOOB appends the regions that live outside #list — the recent
|
// 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
|
// 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.
|
// 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.
|
// Archive for Restore.
|
||||||
func (h *Handler) writeChromeOOB(w http.ResponseWriter, view listView) {
|
func (h *Handler) writeChromeOOB(w http.ResponseWriter, view listView) {
|
||||||
view.OOB = true
|
view.OOB = true
|
||||||
@@ -428,20 +419,12 @@ func (h *Handler) refreshChrome(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
h.writeChromeOOB(w, view)
|
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
|
// renderLogin renders the login page with an error message, for refused or
|
||||||
// failed sign-ins. Every message is author-written text — nothing Discord
|
// failed sign-ins. Every message is author-written text — nothing Discord
|
||||||
// supplied is ever interpolated into a page.
|
// supplied is ever interpolated into a page.
|
||||||
func (h *Handler) renderLogin(w http.ResponseWriter, status int, msg string) {
|
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
|
// logout revokes the session row and clears the cookie in one step: the next
|
||||||
@@ -506,19 +489,12 @@ func (h *Handler) uiFavorite(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
b.Favorite = !b.Favorite
|
b.Favorite = !b.Favorite
|
||||||
b.UpdatedAt = time.Now().UnixMilli()
|
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.saveAndRenderCard(w, r, b)
|
||||||
h.writeAnnounceOOB(w, msg)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// uiStatus moves a bookmark between the two lifecycle buckets. Finished is not
|
// uiStatus moves a bookmark between lifecycle buckets. This is the only place
|
||||||
// one of them: it is a fact about the Series, decided from the admin surface,
|
// a series can be marked finished — the JSON API refuses that value, so the
|
||||||
// so the web UI's per-bookmark control cannot set it (issue #157).
|
// userscript cannot set it even by accident.
|
||||||
//
|
//
|
||||||
// last_chapter_num is untouched, so Upsert keeps the stored updated_at and the
|
// last_chapter_num is untouched, so Upsert keeps the stored updated_at and the
|
||||||
// list does not reorder.
|
// list does not reorder.
|
||||||
@@ -532,21 +508,14 @@ func (h *Handler) uiStatus(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
switch s := r.PostFormValue("status"); s {
|
switch s := r.PostFormValue("status"); s {
|
||||||
case store.StatusReading, store.StatusArchived:
|
case store.StatusReading, store.StatusArchived, store.StatusFinished:
|
||||||
b.Status = s
|
b.Status = s
|
||||||
default:
|
default:
|
||||||
http.Error(w, "invalid status", http.StatusBadRequest)
|
http.Error(w, "invalid status", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
b.UpdatedAt = time.Now().UnixMilli()
|
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.saveAndRenderCard(w, r, b)
|
||||||
h.writeAnnounceOOB(w, msg)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// uiChapter forces the read chapter to a value the user typed.
|
// uiChapter forces the read chapter to a value the user typed.
|
||||||
@@ -571,8 +540,8 @@ func (h *Handler) uiChapter(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
raw := strings.TrimSpace(r.PostFormValue("chapter"))
|
raw := strings.TrimSpace(r.PostFormValue("chapter"))
|
||||||
num, err := strconv.ParseFloat(raw, 64)
|
num, err := strconv.ParseFloat(raw, 64)
|
||||||
if err != nil || num < 0 || num > maxChapterNum || math.IsNaN(num) || math.IsInf(num, 0) {
|
if err != nil || num < 0 || math.IsNaN(num) || math.IsInf(num, 0) {
|
||||||
http.Error(w, "chapter must be a non-negative number below 10000", http.StatusBadRequest)
|
http.Error(w, "chapter must be a non-negative number", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -582,42 +551,27 @@ func (h *Handler) uiChapter(w http.ResponseWriter, r *http.Request) {
|
|||||||
b.LastChapterNum = num
|
b.LastChapterNum = num
|
||||||
}
|
}
|
||||||
b.UpdatedAt = time.Now().UnixMilli()
|
b.UpdatedAt = time.Now().UnixMilli()
|
||||||
msg := fmt.Sprintf("Updated %s to chapter %s", b.Title, raw)
|
|
||||||
h.saveAndRenderCard(w, r, b)
|
h.saveAndRenderCard(w, r, b)
|
||||||
h.writeAnnounceOOB(w, msg)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// uiDelete removes the row and answers with an empty body, which htmx swaps in
|
// uiDelete removes the row and answers with an empty body, which htmx swaps in
|
||||||
// place of the card — removing it from the page.
|
// place of the card — removing it from the page.
|
||||||
func (h *Handler) uiDelete(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) uiDelete(w http.ResponseWriter, r *http.Request) {
|
||||||
b, ok := h.loadForMutation(w, r)
|
key := r.PathValue("key")
|
||||||
if !ok {
|
if key == "" {
|
||||||
|
http.Error(w, "missing key", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := h.store.Delete(readerOf(r), b.Key); err != nil {
|
if err := h.store.Delete(readerOf(r), key); err != nil {
|
||||||
log.Printf("ui delete %q: %v", b.Key, err)
|
log.Printf("ui delete %q: %v", key, err)
|
||||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
msg := fmt.Sprintf("Removed %s", b.Title)
|
// The empty body is what removes the card; the chrome still has to be told
|
||||||
h.writeAnnounceOOB(w, msg)
|
// the library got smaller.
|
||||||
h.writeNoticeOOB(w, msg)
|
h.refreshChrome(w, r)
|
||||||
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>`)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// installUserscript renders the bindmounted script with the acting Reader's
|
// installUserscript renders the bindmounted script with the acting Reader's
|
||||||
|
|||||||
+4
-29
@@ -14,7 +14,6 @@ import (
|
|||||||
"bookmarkmanager/backend/internal/api"
|
"bookmarkmanager/backend/internal/api"
|
||||||
"bookmarkmanager/backend/internal/httpmw"
|
"bookmarkmanager/backend/internal/httpmw"
|
||||||
"bookmarkmanager/backend/internal/latest"
|
"bookmarkmanager/backend/internal/latest"
|
||||||
"bookmarkmanager/backend/internal/notify"
|
|
||||||
"bookmarkmanager/backend/internal/store"
|
"bookmarkmanager/backend/internal/store"
|
||||||
"bookmarkmanager/backend/internal/token"
|
"bookmarkmanager/backend/internal/token"
|
||||||
"bookmarkmanager/backend/internal/userscript"
|
"bookmarkmanager/backend/internal/userscript"
|
||||||
@@ -60,12 +59,6 @@ type Config struct {
|
|||||||
// the Lanes page reports the fact and derives reachability from the pass
|
// the Lanes page reports the fact and derives reachability from the pass
|
||||||
// log rather than asking the poller (issue #145).
|
// log rather than asking the poller (issue #145).
|
||||||
BrowserWSURL string
|
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 configures the background latest-chapter fetcher.
|
||||||
LatestPoll LatestPoll
|
LatestPoll LatestPoll
|
||||||
}
|
}
|
||||||
@@ -121,14 +114,12 @@ func loadConfig() Config {
|
|||||||
UserscriptPath: envOr("USERSCRIPT_PATH", "/userscript/manga-bookmark.user.js"),
|
UserscriptPath: envOr("USERSCRIPT_PATH", "/userscript/manga-bookmark.user.js"),
|
||||||
NovelUserscriptPath: envOr("NOVEL_USERSCRIPT_PATH", "/userscript/novel-bookmark.user.js"),
|
NovelUserscriptPath: envOr("NOVEL_USERSCRIPT_PATH", "/userscript/novel-bookmark.user.js"),
|
||||||
BrowserWSURL: os.Getenv("BROWSER_WS_URL"),
|
BrowserWSURL: os.Getenv("BROWSER_WS_URL"),
|
||||||
DiscordWebhookURL: os.Getenv("DISCORD_WEBHOOK_URL"),
|
|
||||||
LatestPoll: loadLatestPoll(),
|
LatestPoll: loadLatestPoll(),
|
||||||
}
|
}
|
||||||
c.Discord = web.DiscordConfig{
|
c.Discord = web.DiscordConfig{
|
||||||
ClientID: os.Getenv("DISCORD_CLIENT_ID"),
|
ClientID: os.Getenv("DISCORD_CLIENT_ID"),
|
||||||
ClientSecret: os.Getenv("DISCORD_CLIENT_SECRET"),
|
ClientSecret: os.Getenv("DISCORD_CLIENT_SECRET"),
|
||||||
GuildID: os.Getenv("DISCORD_GUILD_ID"),
|
GuildID: os.Getenv("DISCORD_GUILD_ID"),
|
||||||
GuildName: os.Getenv("DISCORD_GUILD_NAME"),
|
|
||||||
RequiredRole: os.Getenv("DISCORD_REQUIRED_ROLE"),
|
RequiredRole: os.Getenv("DISCORD_REQUIRED_ROLE"),
|
||||||
APIBase: envOr("DISCORD_API_BASE", "https://discord.com/api/v10"),
|
APIBase: envOr("DISCORD_API_BASE", "https://discord.com/api/v10"),
|
||||||
RedirectURI: os.Getenv("DISCORD_REDIRECT_URI"),
|
RedirectURI: os.Getenv("DISCORD_REDIRECT_URI"),
|
||||||
@@ -297,22 +288,10 @@ func main() {
|
|||||||
}
|
}
|
||||||
s.OnSeriesCreated = acq.Acquire
|
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)")
|
|
||||||
}
|
|
||||||
// The poller's only connection to the web layer is the database now: it is
|
// 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
|
// started for its own sake, and the Lanes page reads the pass rows it
|
||||||
// records (issue #145).
|
// records (issue #145).
|
||||||
startLatestPoller(pollCtx, s, cfg.LatestPoll, browser, notifier)
|
startLatestPoller(pollCtx, s, cfg.LatestPoll, browser)
|
||||||
|
|
||||||
srv := &http.Server{
|
srv := &http.Server{
|
||||||
Addr: ":" + cfg.Port,
|
Addr: ":" + cfg.Port,
|
||||||
@@ -345,9 +324,7 @@ func main() {
|
|||||||
|
|
||||||
// newLatestPoller wires the fetcher seams into the poller. Pace is registry
|
// newLatestPoller wires the fetcher seams into the poller. Pace is registry
|
||||||
// property, not config (issue #100), so there are no knobs to pass through.
|
// 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
|
func newLatestPoller(s *store.Store, cfg LatestPoll, fetch, browser latest.Fetcher) *latest.Poller {
|
||||||
// silent off switch, not an error (issue #171).
|
|
||||||
func newLatestPoller(s *store.Store, cfg LatestPoll, fetch, browser latest.Fetcher, notifier latest.Notifier) *latest.Poller {
|
|
||||||
var covers latest.BrowserCoverFetcher
|
var covers latest.BrowserCoverFetcher
|
||||||
if f, ok := browser.(latest.BrowserCoverFetcher); ok {
|
if f, ok := browser.(latest.BrowserCoverFetcher); ok {
|
||||||
covers = f
|
covers = f
|
||||||
@@ -358,7 +335,6 @@ func newLatestPoller(s *store.Store, cfg LatestPoll, fetch, browser latest.Fetch
|
|||||||
BrowserFetch: browser,
|
BrowserFetch: browser,
|
||||||
CoverFetch: covers,
|
CoverFetch: covers,
|
||||||
CoverBytesFetch: latest.NewCoverFetcher(),
|
CoverBytesFetch: latest.NewCoverFetcher(),
|
||||||
Notify: notifier,
|
|
||||||
Now: time.Now,
|
Now: time.Now,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -369,8 +345,7 @@ func newLatestPoller(s *store.Store, cfg LatestPoll, fetch, browser latest.Fetch
|
|||||||
// tracking, which is exactly how it behaved before. It returns the running
|
// 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 —
|
// 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.
|
// 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) *latest.Poller {
|
||||||
func startLatestPoller(ctx context.Context, s *store.Store, cfg LatestPoll, browser latest.Fetcher, notifier latest.Notifier) *latest.Poller {
|
|
||||||
if !cfg.Enabled {
|
if !cfg.Enabled {
|
||||||
log.Println("latest-chapter poller: disabled by config")
|
log.Println("latest-chapter poller: disabled by config")
|
||||||
return nil
|
return nil
|
||||||
@@ -383,7 +358,7 @@ func startLatestPoller(ctx context.Context, s *store.Store, cfg LatestPoll, brow
|
|||||||
// Nil browser: sites behind a JavaScript challenge are simply not polled,
|
// Nil browser: sites behind a JavaScript challenge are simply not polled,
|
||||||
// and their latest_chapter comes from the userscript alone — which is how
|
// and their latest_chapter comes from the userscript alone — which is how
|
||||||
// the service behaved before the sidecar existed.
|
// the service behaved before the sidecar existed.
|
||||||
p := newLatestPoller(s, cfg, f, browser, notifier)
|
p := newLatestPoller(s, cfg, f, browser)
|
||||||
|
|
||||||
go p.Run(ctx)
|
go p.Run(ctx)
|
||||||
return p
|
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) {
|
func TestLoadLatestPollEnabledParsing(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
raw string
|
raw string
|
||||||
@@ -65,8 +51,7 @@ func TestLoadLatestPollEnabledParsing(t *testing.T) {
|
|||||||
// nothing here sizes a cooldown any more.
|
// nothing here sizes a cooldown any more.
|
||||||
func TestNewLatestPollerWiresFetchers(t *testing.T) {
|
func TestNewLatestPollerWiresFetchers(t *testing.T) {
|
||||||
tls := &latest.TLSFetcher{}
|
tls := &latest.TLSFetcher{}
|
||||||
notifier := &stubNotifier{}
|
p := newLatestPoller(nil, LatestPoll{Enabled: true}, tls, nil)
|
||||||
p := newLatestPoller(nil, LatestPoll{Enabled: true}, tls, nil, notifier)
|
|
||||||
if p.Fetch != tls {
|
if p.Fetch != tls {
|
||||||
t.Fatalf("Fetch not wired")
|
t.Fatalf("Fetch not wired")
|
||||||
}
|
}
|
||||||
@@ -82,15 +67,8 @@ func TestNewLatestPollerWiresFetchers(t *testing.T) {
|
|||||||
if p.Now == nil {
|
if p.Now == nil {
|
||||||
t.Fatalf("Now = nil, want the live clock")
|
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) {
|
func TestPutStatusValidation(t *testing.T) {
|
||||||
cases := []struct {
|
cases := []struct {
|
||||||
name string
|
name string
|
||||||
@@ -100,7 +78,7 @@ func TestPutStatusValidation(t *testing.T) {
|
|||||||
{"empty is no opinion", "", http.StatusOK},
|
{"empty is no opinion", "", http.StatusOK},
|
||||||
{"reading", "reading", http.StatusOK},
|
{"reading", "reading", http.StatusOK},
|
||||||
{"archived", "archived", 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},
|
{"garbage", "dropped", http.StatusBadRequest},
|
||||||
}
|
}
|
||||||
for _, tc := range cases {
|
for _, tc := range cases {
|
||||||
|
|||||||
+44
-800
File diff suppressed because it is too large
Load Diff
+2
-10
@@ -45,13 +45,11 @@ services:
|
|||||||
# in; distroless already carries tzdata, so the name just resolves.
|
# in; distroless already carries tzdata, so the name just resolves.
|
||||||
TZ: ${API_TZ:-Asia/Jakarta}
|
TZ: ${API_TZ:-Asia/Jakarta}
|
||||||
# Discord OAuth for the browser UI (ADR-0002). The first four are
|
# Discord OAuth for the browser UI (ADR-0002). The first four are
|
||||||
# required; DISCORD_REQUIRED_ROLE and DISCORD_GUILD_NAME are optional and
|
# required; DISCORD_REQUIRED_ROLE is optional and empty by default.
|
||||||
# empty by default. Guild membership is the whole gate: any member
|
# Guild membership is the whole gate: any member becomes a Reader.
|
||||||
# becomes a Reader.
|
|
||||||
DISCORD_CLIENT_ID: ${DISCORD_CLIENT_ID:?set DISCORD_CLIENT_ID in .env}
|
DISCORD_CLIENT_ID: ${DISCORD_CLIENT_ID:?set DISCORD_CLIENT_ID in .env}
|
||||||
DISCORD_CLIENT_SECRET: ${DISCORD_CLIENT_SECRET:?set DISCORD_CLIENT_SECRET in .env}
|
DISCORD_CLIENT_SECRET: ${DISCORD_CLIENT_SECRET:?set DISCORD_CLIENT_SECRET in .env}
|
||||||
DISCORD_GUILD_ID: ${DISCORD_GUILD_ID:?set DISCORD_GUILD_ID in .env}
|
DISCORD_GUILD_ID: ${DISCORD_GUILD_ID:?set DISCORD_GUILD_ID in .env}
|
||||||
DISCORD_GUILD_NAME: ${DISCORD_GUILD_NAME:-}
|
|
||||||
DISCORD_REQUIRED_ROLE: ${DISCORD_REQUIRED_ROLE:-}
|
DISCORD_REQUIRED_ROLE: ${DISCORD_REQUIRED_ROLE:-}
|
||||||
DISCORD_API_BASE: ${DISCORD_API_BASE:-https://discord.com/api/v10}
|
DISCORD_API_BASE: ${DISCORD_API_BASE:-https://discord.com/api/v10}
|
||||||
DISCORD_REDIRECT_URI: ${DISCORD_REDIRECT_URI:?set DISCORD_REDIRECT_URI in .env}
|
DISCORD_REDIRECT_URI: ${DISCORD_REDIRECT_URI:?set DISCORD_REDIRECT_URI in .env}
|
||||||
@@ -78,12 +76,6 @@ services:
|
|||||||
# independent of chromedp's own dial logic. The same trap that used to
|
# independent of chromedp's own dial logic. The same trap that used to
|
||||||
# force a pinned Docker IP now forbids the tailnet name.
|
# force a pinned Docker IP now forbids the tailnet name.
|
||||||
BROWSER_WS_URL: ${BROWSER_WS_URL:-}
|
BROWSER_WS_URL: ${BROWSER_WS_URL:-}
|
||||||
#
|
|
||||||
# Owner-notice webhook (issue #171). Empty default, never a
|
|
||||||
# required-guard: unset means the whole path is off, so a local stack
|
|
||||||
# runs exactly as it does today. An env var not listed here never
|
|
||||||
# reaches the container.
|
|
||||||
DISCORD_WEBHOOK_URL: ${DISCORD_WEBHOOK_URL:-}
|
|
||||||
depends_on:
|
depends_on:
|
||||||
# The migration runner is the first thing the binary does, so a Postgres
|
# The migration runner is the first thing the binary does, so a Postgres
|
||||||
# that is still initialising means a crash-loop until it is not.
|
# that is still initialising means a crash-loop until it is not.
|
||||||
|
|||||||
@@ -1,109 +0,0 @@
|
|||||||
# ADR-0015: Finished is a fact about the Series, not a bookmark bucket
|
|
||||||
|
|
||||||
Date: 2026-08-22
|
|
||||||
Status: accepted
|
|
||||||
|
|
||||||
## Decision
|
|
||||||
|
|
||||||
"Finished" moves from the per-Reader `bookmarks.status` bucket to a
|
|
||||||
Series-owned flag: `series.finished_at`, unix ms, zero while the Series is
|
|
||||||
still running. The Lane's gate reads the flag — a Series is polled only while
|
|
||||||
`finished_at = 0` — and `bookmarks.status` keeps exactly two values,
|
|
||||||
`reading` and `archived`.
|
|
||||||
|
|
||||||
The cutover is one-way, done by migration 0016 in three load-bearing
|
|
||||||
statements:
|
|
||||||
|
|
||||||
1. `ALTER TABLE series ADD COLUMN finished_at bigint NOT NULL DEFAULT 0`.
|
|
||||||
2. Seed it from the bookmarks: a Series is stamped finished when no bookmark
|
|
||||||
on it is outside the `finished` bucket. This mirrors the pre-cutover due
|
|
||||||
gate exactly — the old query skipped a Series only while
|
|
||||||
`COUNT(*) FILTER (WHERE status <> 'finished') = 0` — so no Series changes
|
|
||||||
polling state at the cutover.
|
|
||||||
3. Rewrite every `finished` bookmark to `archived`. The bucket is gone; the
|
|
||||||
seed ran first because it is the only statement that can still read it.
|
|
||||||
|
|
||||||
The JSON API rejects a `finished` status with the same plain 400 as any
|
|
||||||
unknown value, and the web UI no longer offers a Finished tab, a finish
|
|
||||||
button, or a finished state badge.
|
|
||||||
|
|
||||||
## Why a future reader will find this surprising
|
|
||||||
|
|
||||||
The bucket looked Reader-shaped but described a Series fact. A Series is
|
|
||||||
finished once, and every Reader reading it is then on a finished Series —
|
|
||||||
yet the bucket carried three copies of the answer, one per Reader, free to
|
|
||||||
disagree. The disagreement is not theoretical: a second Reader who merely
|
|
||||||
kept the Series (or never read it) kept it in `reading`, so the poll gate
|
|
||||||
kept fetching a Series the first Reader had closed out, forever. Worse, the
|
|
||||||
disagreement was never resolvable — nothing in the system could say "this
|
|
||||||
Series is finished" without rewriting every bookmark, which silently edits
|
|
||||||
another Reader's progress state.
|
|
||||||
|
|
||||||
The flag is also the only memory of the bucket after the flip. `finished`
|
|
||||||
bookmarks become `archived` because a two-value status needs no third
|
|
||||||
value, and an archived row must keep meaning "shelved, but the Series is
|
|
||||||
being watched" — which is what the row says. The migration's seed is what
|
|
||||||
keeps the legacy meaning: a Series every Reader finished is stamped, so the
|
|
||||||
Lane stops polling it just as it would have pre-cutover; a Series any
|
|
||||||
Reader still reads is left alone, exactly as the old gate left it. A
|
|
||||||
Series whose every Reader only shelved (archived) continues to be polled,
|
|
||||||
because an archived bookmark is *supposed* to be polled — the cutover
|
|
||||||
changes the answer, it does not invent it. And because the flag is a series
|
|
||||||
fact, the cutover also repairs the disagreement case: the moment one Reader
|
|
||||||
has the Series open, it reads as finished to everyone.
|
|
||||||
|
|
||||||
The migration is the only writer of the flag today; the undo is writing 0,
|
|
||||||
which returns the Series to the poll. An owner-facing "mark finished" write
|
|
||||||
is deliberately not part of this change — the gate is what this ticket
|
|
||||||
rewrites, and the write can land on top of it without touching anything
|
|
||||||
here.
|
|
||||||
|
|
||||||
The userscript merge ranks `archived > reading` now. `finished` is not a
|
|
||||||
value the wire can carry, so the merge cannot un-finish a row — it cannot
|
|
||||||
even name the state it is protecting.
|
|
||||||
|
|
||||||
## Considered options
|
|
||||||
|
|
||||||
**Keep the bucket and add the flag alongside it, both live.**
|
|
||||||
Rejected: two sources of truth for one fact, with the Lane forced to
|
|
||||||
resolve "any Reader finished?" on every due query and every Reader write
|
|
||||||
still able to resurrect a finished Series. The whole point of the change is
|
|
||||||
that the finished state survives Readers.
|
|
||||||
|
|
||||||
**Stamp a Series finished when every bookmark is finished *or* archived.**
|
|
||||||
Rejected: it flips polling state at the cutover. Shelved-only Series were
|
|
||||||
polled before; making them finished stops the checks the reader knowingly
|
|
||||||
asked to keep.
|
|
||||||
|
|
||||||
**Finish as "no bookmark is reading", leaving the buckets untouched.**
|
|
||||||
Rejected for the same reason plus one: `archived` is a Reader's own state
|
|
||||||
and the flip is what makes the flag the *only* source of finished. Keeping
|
|
||||||
the `finished` value in the table would force every status validation,
|
|
||||||
merge and UI branch to keep handling a value no write can produce.
|
|
||||||
|
|
||||||
## Consequences
|
|
||||||
|
|
||||||
- `bookmarks.status` is validated to `reading | archived`, empty meaning
|
|
||||||
"keep the stored value"; the API's 400 for `finished` is now the generic
|
|
||||||
invalid-status rejection rather than a special case, and the web UI's own
|
|
||||||
status control rejects it the same way.
|
|
||||||
- The Lane due query and the eligible count read `finished_at`; a Forced
|
|
||||||
Poll (issue #146) still overrides the flag — the owner asked, so the Lane
|
|
||||||
looks — and the pending force clears itself when the pass stamps the
|
|
||||||
check timestamp, never by touching `finished_at`.
|
|
||||||
- The web UI has no Finished tab; finished Series render in Archived with
|
|
||||||
their archived badge, dimmed like any shelved row.
|
|
||||||
- Migration 0016 stamps `finished_at` with the migration's own clock
|
|
||||||
(`now()` ms), which is also the undo: write 0 and the Series returns to
|
|
||||||
the poll.
|
|
||||||
|
|
||||||
## Cost of reversing
|
|
||||||
|
|
||||||
The finished buckets are destroyed by the flip; reversing means re-deriving
|
|
||||||
per-Reader finished state from a Series fact that now encodes the
|
|
||||||
majority-agreement snapshot plus whatever the owner reset since. The stamp
|
|
||||||
differentiates "finished at the cutover and untouched" from "finished
|
|
||||||
later", but not which Reader's choice each Series carried, and any Series
|
|
||||||
the owner has since restored is gone from the derivation entirely. The ADR
|
|
||||||
is a statement of intent to ship the one-way cutover and live with its
|
|
||||||
consequences; the per-Reader history is not kept anywhere in the schema.
|
|
||||||
@@ -1,147 +0,0 @@
|
|||||||
# ADR-0016: The failure row is the state
|
|
||||||
|
|
||||||
Date: 2026-08-22
|
|
||||||
Status: accepted
|
|
||||||
|
|
||||||
## Decision
|
|
||||||
|
|
||||||
A Series that used to work and has stopped is recorded in one table,
|
|
||||||
`poll_failures`, keyed by the same `(site, series_id)` composite the rest of
|
|
||||||
the system uses. One row per failing Series, carrying the outcome word and a
|
|
||||||
`failing_since` stamp. The row's **existence** is the failure state: there is
|
|
||||||
no success sentinel, no counter, no history, and nothing added to the Series
|
|
||||||
row. A correct read deletes the row, and a repeated identical failure writes
|
|
||||||
nothing — the stamp ages the run of failures, not the current word.
|
|
||||||
|
|
||||||
The write is one upsert, from the poll pass loop:
|
|
||||||
|
|
||||||
```sql
|
|
||||||
INSERT INTO poll_failures (site, series_id, outcome, failing_since)
|
|
||||||
VALUES ($1, $2, $3, $4)
|
|
||||||
ON CONFLICT (site, series_id) DO UPDATE SET outcome = EXCLUDED.outcome
|
|
||||||
WHERE poll_failures.outcome <> EXCLUDED.outcome
|
|
||||||
```
|
|
||||||
|
|
||||||
`failing_since` is simply absent from the `SET` arm, so it is never
|
|
||||||
overwritten, and the `WHERE` makes an unchanged word write nothing at all —
|
|
||||||
one statement, no read-then-write race. The clear is a plain `DELETE`; a row
|
|
||||||
that is not there is not an error, because the poller clears on every
|
|
||||||
successful read and most clears find nothing. The composite foreign key
|
|
||||||
cascades: deleting a Series takes its failure row, so orphan removal stays a
|
|
||||||
single statement.
|
|
||||||
|
|
||||||
## Why a future reader will find this surprising
|
|
||||||
|
|
||||||
The failure state lives in a table of its own, not on the Series row and not
|
|
||||||
in the pass log. A flag on `series` would be the familiar shape, and the
|
|
||||||
pass log already records outcomes per pass — why a third place?
|
|
||||||
|
|
||||||
Because the failure must outlive the pass that observed it and mean
|
|
||||||
something the pass row cannot say. The pass log is a per-Lane stream: it
|
|
||||||
records that a Site returned N `errors` and M `not_found` on a given run,
|
|
||||||
but "this exact Series has been failing for three months" is not a question
|
|
||||||
any single pass row answers — it is a question across rows, and the Lanes
|
|
||||||
page is a live view of the last 14 days, not a Series index. A Series-level
|
|
||||||
fact needs Series-level storage, and a flag on the Series row is the wrong
|
|
||||||
shape too: the failure is *transient by definition* (a correct read ends it)
|
|
||||||
and *repeatable* (the same Series can fail again next year), so the honest
|
|
||||||
record of "failing since" is a stamp that moves, not a column that flips.
|
|
||||||
A row that is created and deleted by the read's outcome is that stamp, and
|
|
||||||
nothing else: the moment a read succeeds the row is gone, so "is this Series
|
|
||||||
failing?" is answered by one indexed existence check — no success sentinel
|
|
||||||
to keep consistent with the failure, no counter to reset, no history to
|
|
||||||
prune. The state cannot drift out of step with the reads that maintain it,
|
|
||||||
because the reads *are* the maintenance.
|
|
||||||
|
|
||||||
The two no-write outcomes are the second surprise. `refused` (the Site is
|
|
||||||
holding a challenge) and `unreachable` (the browser sidecar was lost
|
|
||||||
mid-loop) issue **no statement at all** — neither an upsert nor a delete.
|
|
||||||
The direction matters, and both directions are wrong to touch:
|
|
||||||
|
|
||||||
- **Writing would condemn a whole library for one Site's bad day.** A
|
|
||||||
refusal is the Site's mood, not a fact about any particular Series: when
|
|
||||||
Cloudflare turns a zone's JS detection on, every Series on that Site reads
|
|
||||||
refused in the same pass. Writing those rows would stamp every Series in
|
|
||||||
the library as failing on the evidence of one Site's configuration, and
|
|
||||||
#166's worklist would present a Site-wide outage as thousands of broken
|
|
||||||
Series.
|
|
||||||
- **Deleting would claim a recovery nothing read.** A lost sidecar tells us
|
|
||||||
nothing about the page — the read never happened. Deleting the row would
|
|
||||||
report the Series healthy, and worse, it would reset `failing_since`: the
|
|
||||||
age that makes a three-month failure findable would start over on a
|
|
||||||
browser restart, erasing evidence no page read contradicted.
|
|
||||||
|
|
||||||
So a refusal or an unreachable pass leaves the table exactly as it found
|
|
||||||
it — the pass neither adds rows that would condemn nor deletes rows that
|
|
||||||
would claim recovery. The four outcomes that are real evidence about the
|
|
||||||
page (`not_found`, `no_chapter`, `unfetchable`, `errors`) write; the two
|
|
||||||
that are not write nothing; success deletes. There is no third case.
|
|
||||||
|
|
||||||
## Considered options
|
|
||||||
|
|
||||||
**A `failing_since` column on the Series row, alongside the failure word.**
|
|
||||||
Rejected: it is two more columns on a table every due query and every
|
|
||||||
bookmark join already touches, for a state that is transient and repeatable.
|
|
||||||
The column would need its own "clear on success" writer anyway — the same
|
|
||||||
maintenance the row has — while permanently widening the hottest table in
|
|
||||||
the system for a value that is usually absent. And the worklist's join
|
|
||||||
would have to distinguish "never failed" from "currently healthy", which
|
|
||||||
is exactly the sentinel problem the row avoids: an empty column means both.
|
|
||||||
|
|
||||||
**A counter or last-outcome timestamp instead of (or beside) the row.**
|
|
||||||
Rejected: nothing in the system consumes a failure *count* or a
|
|
||||||
last-outcome time — the worklist needs "failing and since when". A counter
|
|
||||||
invites "three failures = something" thresholds that the ticket explicitly
|
|
||||||
keeps out of scope, and a last-outcome timestamp conflates "the word
|
|
||||||
changed" with "the run restarted", which the age is deliberately defined
|
|
||||||
against. The stamp is the only number that means anything, and the row
|
|
||||||
carries exactly that.
|
|
||||||
|
|
||||||
**Write into `poll_passes` and derive the failure state from the pass
|
|
||||||
stream.**
|
|
||||||
Rejected: a pass row is per-Lane and per-run; deriving "this Series is
|
|
||||||
failing since" means scanning 14 days of outcome counts per Series and
|
|
||||||
guessing at continuity across retention boundaries. The pass log answers
|
|
||||||
"what did this Site's lane do recently"; the failure table answers "which
|
|
||||||
Series are broken right now". Two questions, two tables — the pass log is
|
|
||||||
already pruned on a fixed cutoff, which would silently reset every
|
|
||||||
failure's age the moment the evidence aged out.
|
|
||||||
|
|
||||||
**Refused/unreachable write nothing, but the delete happens anyway (or the
|
|
||||||
upsert happens, with no delete).**
|
|
||||||
Rejected in both directions, above: writing condemns a library for one
|
|
||||||
Site's mood; deleting claims a recovery nothing read and resets the age
|
|
||||||
that makes a long failure findable. The asymmetry is the point — the two
|
|
||||||
outcomes are evidence about the *environment*, never about a page.
|
|
||||||
|
|
||||||
## Consequences
|
|
||||||
|
|
||||||
- The poller writes from the pass loop, one call after `checkOne`, and
|
|
||||||
clears through the ordinary success path: a Forced Poll that reads the
|
|
||||||
page deletes the row with no forced branch of its own, and a Forced Poll
|
|
||||||
*request* — which only stamps the request — clears nothing.
|
|
||||||
- `poll_failures` is a poll-write table like `poll_lanes` and
|
|
||||||
`poll_passes`: the store's two methods live next to the Lane-pass
|
|
||||||
writers, and neither runs on a request path. A store failure is logged
|
|
||||||
and the poll continues — a failure row is best-effort, and no single bad
|
|
||||||
Series may stall a Lane.
|
|
||||||
- The due query does not join the table. A failing Series is polled at the
|
|
||||||
same pace as any other, because the moment the query started pacing by
|
|
||||||
failure state, the age would stop meaning what the worklist reads it as.
|
|
||||||
- Orphan removal stays a single statement: the composite foreign key's
|
|
||||||
`ON DELETE CASCADE` is what takes the failure row with the Series.
|
|
||||||
- The table starts empty at deploy, so nothing is findable for the first
|
|
||||||
twelve hours after deploy and a pre-existing breakage reads as new.
|
|
||||||
Accepted; the alternative is inventing history.
|
|
||||||
|
|
||||||
## Cost of reversing
|
|
||||||
|
|
||||||
The failure state is derived, not stored: a rollback drops the table and
|
|
||||||
every in-progress failure age with it, leaving the pass log's outcome
|
|
||||||
counts as the only trace — which is exactly the "log line nobody reads"
|
|
||||||
the ticket set out to replace. Recreating the table later starts the ages
|
|
||||||
over, so a reversal that is later reversed loses the evidence of the
|
|
||||||
intervening failures. The failure state itself, however, is the one thing
|
|
||||||
that is *not* lost by reversing: it is re-derived from the next pass, in
|
|
||||||
the same direction the original design derives it — the row is
|
|
||||||
recreated by the next failing read and deleted by the next good one.
|
|
||||||
+22
-56
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Source of truth: the Claude Design project **BookmarkManager Web UI**
|
Source of truth: the Claude Design project **BookmarkManager Web UI**
|
||||||
(`969ac210-fe02-4c01-ae1b-9a271dcc779a`, `index.html` + siblings
|
(`969ac210-fe02-4c01-ae1b-9a271dcc779a`, `index.html` + siblings
|
||||||
`archived.html`/`fav.html`/`new.html`/`login.html`/`mobile.html`,
|
`archived.html`/`fav.html`/`finished.html`/`new.html`/`login.html`/`mobile.html`,
|
||||||
`style.css`, `filter.js`). This file records the rules that got implemented so
|
`style.css`, `filter.js`). This file records the rules that got implemented so
|
||||||
a future agent can extend the UI without re-reading the design.
|
a future agent can extend the UI without re-reading the design.
|
||||||
|
|
||||||
@@ -48,7 +48,7 @@ Defined once in `backend/internal/web/static/style.css` `:root`, mirrored in the
|
|||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| `--ink` | `#100f0e` | `#f7f4ef` | page |
|
| `--ink` | `#100f0e` | `#f7f4ef` | page |
|
||||||
| `--ash` | `#161413` | `#efeae3` | recessed panel (chapter form) |
|
| `--ash` | `#161413` | `#efeae3` | recessed panel (chapter form) |
|
||||||
| `--dim` | `#0d0c0b` | `#f1ede7` | archived row background |
|
| `--dim` | `#0d0c0b` | `#f1ede7` | archived / finished row background |
|
||||||
| `--rule` | `#221f1d` | `#e0dad2` | hairline between sheets, button borders |
|
| `--rule` | `#221f1d` | `#e0dad2` | hairline between sheets, button borders |
|
||||||
| `--rule-soft` | `#1a1817` | `#e8e3dc` | the measure's own side edges |
|
| `--rule-soft` | `#1a1817` | `#e8e3dc` | the measure's own side edges |
|
||||||
| `--field-line` | `#2c2926` | `#d4cdc4` | input borders, ghost-button underline |
|
| `--field-line` | `#2c2926` | `#d4cdc4` | input borders, ghost-button underline |
|
||||||
@@ -70,7 +70,7 @@ Defined once in `backend/internal/web/static/style.css` `:root`, mirrored in the
|
|||||||
| `--danger-soft` | `#e2aaa1` | `#7c2c22` | text on danger wash |
|
| `--danger-soft` | `#e2aaa1` | `#7c2c22` | text on danger wash |
|
||||||
| `--brass` | `#b8912f` | `#8a681c` | favourite — a cooler second metal |
|
| `--brass` | `#b8912f` | `#8a681c` | favourite — a cooler second metal |
|
||||||
| `--slate` | `#7fa0c0` | `#3f6689` | archive accent |
|
| `--slate` | `#7fa0c0` | `#3f6689` | archive accent |
|
||||||
| `--moss` | `#7fae86` | `#3d6c46` | finished Series label |
|
| `--moss` | `#7fae86` | `#3d6c46` | finished accent |
|
||||||
| `--clay` | `#b5906f` | `#7c5533` | set-chapter accent |
|
| `--clay` | `#b5906f` | `#7c5533` | set-chapter accent |
|
||||||
| `--trash` | `#977671` | `#8c6558` | remove, at rest — icons need 3:1, not 4.5:1 |
|
| `--trash` | `#977671` | `#8c6558` | remove, at rest — icons need 3:1, not 4.5:1 |
|
||||||
| `--patina` | `#5fb3a6` | `#1f6f66` | admin page only — a Poll Lane needing attention, a Reader whose reports are blocked |
|
| `--patina` | `#5fb3a6` | `#1f6f66` | admin page only — a Poll Lane needing attention, a Reader whose reports are blocked |
|
||||||
@@ -128,11 +128,8 @@ Recurring specs (copy these rather than inventing sizes):
|
|||||||
- Tab: `400 17px display` (`18px` ≥720px), active gets `border-bottom: 2px` in
|
- Tab: `400 17px display` (`18px` ≥720px), active gets `border-bottom: 2px` in
|
||||||
`--paper` (`--ember` for Updated) plus `margin-bottom: -1px` so it lands on
|
`--paper` (`--ember` for Updated) plus `margin-bottom: -1px` so it lands on
|
||||||
the row's own hairline.
|
the row's own hairline.
|
||||||
- Meta / label / badge / action key: `500 11px mono`, `letter-spacing:
|
- Meta / label / badge / action key: `500 10–11px mono`, `letter-spacing:
|
||||||
.04em`–`.2em`, `text-transform: uppercase`. Eyebrows use the widest tracking.
|
.04em`–`.2em`, `text-transform: uppercase`. Eyebrows use the widest tracking.
|
||||||
**11px is the floor** — nothing in this UI sets mono below it. The brief names
|
|
||||||
night reading and glare as the usage scene, and a 10px small-caps label at
|
|
||||||
arm's length on a phone is where that scene stops being served.
|
|
||||||
- Empty-state heading: `400 20px display`; body `400 14px/1.6 sans`, `max-width: 44ch`.
|
- Empty-state heading: `400 20px display`; body `400 14px/1.6 sans`, `max-width: 44ch`.
|
||||||
- Primary button: `--paper` fill, `--ink` text, `400 17–19px display`, no border radius.
|
- Primary button: `--paper` fill, `--ink` text, `400 17–19px display`, no border radius.
|
||||||
- Ghost button: mono small-caps, transparent, `border-bottom: 1px --field-line`.
|
- Ghost button: mono small-caps, transparent, `border-bottom: 1px --field-line`.
|
||||||
@@ -143,20 +140,11 @@ Recurring specs (copy these rather than inventing sizes):
|
|||||||
.sheet
|
.sheet
|
||||||
.topbar .brand (mark + wordmark) + .ghost (log out)
|
.topbar .brand (mark + wordmark) + .ghost (log out)
|
||||||
.chrome .searchbar + nav.tabs (column on phone, row ≥720px via order:)
|
.chrome .searchbar + nav.tabs (column on phone, row ≥720px via order:)
|
||||||
sticky at top: 0, z-index 2, on an --ink ground
|
|
||||||
.keyrow one-line action key: Read / Fav / Chapter / Archive / Done / Delete
|
.keyrow one-line action key: Read / Fav / Chapter / Archive / Done / Delete
|
||||||
.recent h2 eyebrow + .recent-strip > a.recent-card
|
.recent h2 eyebrow + .recent-strip > a.recent-card
|
||||||
main#list article.card … | .empty
|
main#list article.card … | .empty
|
||||||
```
|
```
|
||||||
|
|
||||||
**Sticky chrome.** Search and the tab row are the two controls a 300-item
|
|
||||||
library needs mid-scroll, so `.chrome` alone sticks (`padding-top:
|
|
||||||
env(safe-area-inset-top)` for the notch cutout). Everything above it —
|
|
||||||
`.topbar`, `.keyrow`, `.recent` — scrolls away on purpose: another 150px of
|
|
||||||
permanent chrome on an 844px phone costs more than re-scrolling for an icon
|
|
||||||
reminder. If header height ever grows, unstick `.recent`/`.keyrow` further
|
|
||||||
rather than adding to the sticky region, and keep `.chrome` above the cards.
|
|
||||||
|
|
||||||
The owner's admin page (`admin.html`) is the same sheet with two sections in
|
The owner's admin page (`admin.html`) is the same sheet with two sections in
|
||||||
place of the list — `.lanes` (Poll Lane rows) and `.readers` (the roster) —
|
place of the list — `.lanes` (Poll Lane rows) and `.readers` (the roster) —
|
||||||
and no library switch: it belongs to neither library, so its topbar carries a
|
and no library switch: it belongs to neither library, so its topbar carries a
|
||||||
@@ -176,9 +164,9 @@ rather than scaling the artwork down.
|
|||||||
|
|
||||||
**Action key** (`.keyrow`): one permanent line under the tabs naming what
|
**Action key** (`.keyrow`): one permanent line under the tabs naming what
|
||||||
every icon in `.actions` does — Read / Fav / Chapter / Archive / Done /
|
every icon in `.actions` does — Read / Fav / Chapter / Archive / Done /
|
||||||
Delete — so the icon strip on a card is never a guess. The key follows the
|
Delete — so the icon strip on a card is never a guess. The key follows the tab,
|
||||||
tab, not the row: under Archived, Archive becomes Restore. On a phone each
|
not the row: Archive becomes Restore under Archived and Finished, and Finished
|
||||||
pair stacks icon-over-word
|
drops Done. On a phone each pair stacks icon-over-word
|
||||||
(`flex-direction: column`) so the word gets the full cell width; ≥720px it lays
|
(`flex-direction: column`) so the word gets the full cell width; ≥720px it lays
|
||||||
out icon-beside-word at the same wording. `.pair.brass` and `.pair.trash`
|
out icon-beside-word at the same wording. `.pair.brass` and `.pair.trash`
|
||||||
carry their icon's resting accent so the key itself teaches the colour
|
carry their icon's resting accent so the key itself teaches the colour
|
||||||
@@ -191,7 +179,7 @@ article.card[.is-new|.is-dim]#card-<key>[data-title]
|
|||||||
.row
|
.row
|
||||||
a.cover[tabindex="-1" aria-hidden] img | span.monogram, + span.foot-rule[.brass]
|
a.cover[tabindex="-1" aria-hidden] img | span.monogram, + span.foot-rule[.brass]
|
||||||
.body .title-line (h3.title + svg.fav-mark) , p.meta
|
.body .title-line (h3.title + svg.fav-mark) , p.meta
|
||||||
.actions play, favourite, chapter | lifecycle: archive/restore, remove
|
.actions play, favourite, chapter | lifecycle: archive/restore, finish, remove
|
||||||
form.chapter-form[hidden] .hint + .field(input + Save) + .hint (latest known)
|
form.chapter-form[hidden] .hint + .field(input + Save) + .hint (latest known)
|
||||||
.confirm-row[.calm][hidden] × one per lifecycle action, span + (go/danger-solid, Cancel)
|
.confirm-row[.calm][hidden] × one per lifecycle action, span + (go/danger-solid, Cancel)
|
||||||
p.error-inline[hidden]
|
p.error-inline[hidden]
|
||||||
@@ -200,7 +188,7 @@ article.card[.is-new|.is-dim]#card-<key>[data-title]
|
|||||||
Rules that are easy to break:
|
Rules that are easy to break:
|
||||||
|
|
||||||
- `.is-new` only when `Status == reading && HasNewChapter`; `.is-dim` for
|
- `.is-new` only when `Status == reading && HasNewChapter`; `.is-dim` for
|
||||||
`archived`. Both are set on the `<article>` — every heat and
|
`archived` and `finished`. Both are set on the `<article>` — every heat and
|
||||||
dim rule is a descendant selector off those two classes, so a new sub-element
|
dim rule is a descendant selector off those two classes, so a new sub-element
|
||||||
inherits the state for free.
|
inherits the state for free.
|
||||||
- `.actions` is `flex: 1 0 100%` inside `.row`, which is what makes it a
|
- `.actions` is `flex: 1 0 100%` inside `.row`, which is what makes it a
|
||||||
@@ -208,19 +196,19 @@ Rules that are easy to break:
|
|||||||
the row at ≥720px. Cells are 46px tall on phone (thumb target) and divided by
|
the row at ≥720px. Cells are 46px tall on phone (thumb target) and divided by
|
||||||
`border-right: 1px var(--rule)`, last child none.
|
`border-right: 1px var(--rule)`, last child none.
|
||||||
- Three clusters by consequence, in this order: navigate (`.play`) | organize
|
- Three clusters by consequence, in this order: navigate (`.play`) | organize
|
||||||
(`.fav`, `.pencil`) | lifecycle (`.box`/`.restore`, `.remove`,
|
(`.fav`, `.pencil`) | lifecycle (`.box`/`.restore`, `.finish`, `.remove`,
|
||||||
each carrying the `.lifecycle` class). Lifecycle cells sit on a recessed
|
each carrying the `.lifecycle` class). Lifecycle cells sit on a recessed
|
||||||
`--ash` ground so the thumb reads "this one moves the series" before it
|
`--ash` ground so the thumb reads "this one moves the series" before it
|
||||||
reads which icon it landed on; ≥720px they separate by a 10px gap instead of
|
reads which icon it landed on; ≥720px they separate by a 10px gap instead of
|
||||||
the phone's inset hairline.
|
the phone's inset hairline.
|
||||||
- Every lifecycle button that moves a series out of the list is
|
- Every lifecycle button that moves a series out of the list is
|
||||||
**confirm-gated**: it opens its own `.confirm-row` (`archive`,
|
**confirm-gated**: it opens its own `.confirm-row` (`archive`, `finish`,
|
||||||
`remove` — `toggleConfirmRow(key, kind)` in `filter.js`). Archive asks in
|
`remove` — `toggleConfirmRow(key, kind)` in `filter.js`). Archive and finish
|
||||||
`.calm` grey since it's reversible; remove alone gets the
|
ask in `.calm` grey since they're reversible; remove alone gets the
|
||||||
`--danger-wash` treatment and names the series in its question. Restore
|
`--danger-wash` treatment and names the series in its question. Restore
|
||||||
fires instantly — no confirm — because it's the reversal.
|
fires instantly — no confirm — because it's the reversal.
|
||||||
- Per-action hover/press accent: `.fav` → `--brass`, `.pencil` → `--clay`,
|
- Per-action hover/press accent: `.fav` → `--brass`, `.pencil` → `--clay`,
|
||||||
`.box` → `--slate`. `.play` stays paper/ember (ember
|
`.box` → `--slate`, `.finish` → `--moss`. `.play` stays paper/ember (ember
|
||||||
only when `.is-new`). `.remove` stays `--trash` at rest, `--danger` on
|
only when `.is-new`). `.remove` stays `--trash` at rest, `--danger` on
|
||||||
hover. Desktop cell borders follow the same accent on hover
|
hover. Desktop cell borders follow the same accent on hover
|
||||||
(`border-color: currentColor`); the two coloured *resting* states
|
(`border-color: currentColor`); the two coloured *resting* states
|
||||||
@@ -237,16 +225,9 @@ Rules that are easy to break:
|
|||||||
- `[hidden] { display: none !important; }` is load-bearing — every disclosure
|
- `[hidden] { display: none !important; }` is load-bearing — every disclosure
|
||||||
panel is a flex container, and `display` beats `hidden`.
|
panel is a flex container, and `display` beats `hidden`.
|
||||||
- Busy state is `.card.htmx-request::before`, a 1px grey bar sliding across the
|
- Busy state is `.card.htmx-request::before`, a 1px grey bar sliding across the
|
||||||
top hairline (`barSlide`), the action strip at `opacity: .5`, and past 2s the
|
top hairline (`barSlide`), plus the action strip at `opacity: .5`. Never a
|
||||||
word `Saving…` in `::after` (`busyWord`, §6). `filter.js` sets `aria-busy` on
|
spinner, and deliberately `--mute` not `--ember` — on a list screen ember
|
||||||
the card over the same window because htmx sets none, so the wait is not
|
means "new chapter" and nothing else, so a system state can't borrow it.
|
||||||
silent to a screen reader. Never a spinner, and deliberately `--mute` not
|
|
||||||
`--ember` — on a list screen ember means "new chapter" and nothing else, so a
|
|
||||||
system state can't borrow it.
|
|
||||||
- Titles clamp at 3 lines (`.recent-title` at 2 — there the title is a
|
|
||||||
reminder, in the list it is the identifier). `.is-new .title` needs
|
|
||||||
`width: fit-content`, or `-webkit-box` stretches the ember underline to the
|
|
||||||
full row and the rule stops being sized to the text.
|
|
||||||
- `.open` on the pencil / lifecycle cell marks which panel is showing;
|
- `.open` on the pencil / lifecycle cell marks which panel is showing;
|
||||||
`filter.js` `togglePanel()`/`toggleConfirmRow()` own that class alongside
|
`filter.js` `togglePanel()`/`toggleConfirmRow()` own that class alongside
|
||||||
`hidden`. An open lifecycle cell needs the next surface step up from
|
`hidden`. An open lifecycle cell needs the next surface step up from
|
||||||
@@ -270,7 +251,7 @@ is a 1px bar, not a rotating ring); toasts are `--ash` with a 2px left rule,
|
|||||||
|
|
||||||
## 6. Motion
|
## 6. Motion
|
||||||
|
|
||||||
Four animations, all ≤ 1.15s and all disabled under
|
Three animations, all ≤ 1.15s and all disabled under
|
||||||
`prefers-reduced-motion: reduce` (pseudo-elements need naming explicitly in
|
`prefers-reduced-motion: reduce` (pseudo-elements need naming explicitly in
|
||||||
that query — `*` does not match `::before`/`::after`, so the busy bar and
|
that query — `*` does not match `::before`/`::after`, so the busy bar and
|
||||||
error dot are listed by name and fall back to their static drawn form):
|
error dot are listed by name and fall back to their static drawn form):
|
||||||
@@ -278,29 +259,16 @@ error dot are listed by name and fall back to their static drawn form):
|
|||||||
- `sheetIn` — 180ms fade + 4px rise, on a row and on each disclosure panel.
|
- `sheetIn` — 180ms fade + 4px rise, on a row and on each disclosure panel.
|
||||||
- `barSlide` — the sliding hairline, for any busy state.
|
- `barSlide` — the sliding hairline, for any busy state.
|
||||||
- `mutePulse` — the 5px dot on `.error-inline`.
|
- `mutePulse` — the 5px dot on `.error-inline`.
|
||||||
- `busyWord` — `0s 2s forwards`, a delay rather than a motion: it reveals the
|
|
||||||
`Saving…` word only once a request has outlived a plausible response. The
|
|
||||||
reduced-motion block cancels the animation and so would pin it at
|
|
||||||
`opacity: 0`; that branch re-declares `opacity: 1` to show it from the start.
|
|
||||||
Any future state revealed this way needs the same two-line pair.
|
|
||||||
|
|
||||||
No transforms on hover, no scale, no easing curves beyond `ease-out`/`linear`.
|
No transforms on hover, no scale, no easing curves beyond `ease-out`/`linear`.
|
||||||
|
|
||||||
## 7. Accessibility floor (not negotiable)
|
## 7. Accessibility floor (not negotiable)
|
||||||
|
|
||||||
|
- Touch targets on the phone layout are 44–46px; the 44px desktop cells are
|
||||||
|
pointer-only (≥720px).
|
||||||
- Every icon-only control keeps `title` + `aria-label`; the SVG inside is
|
- Every icon-only control keeps `title` + `aria-label`; the SVG inside is
|
||||||
`aria-hidden`. Lifecycle buttons also carry `aria-expanded` +
|
`aria-hidden`. Lifecycle buttons also carry `aria-expanded` +
|
||||||
`aria-controls` pointing at their `.confirm-row`.
|
`aria-controls` pointing at their `.confirm-row`.
|
||||||
- **Every focusable control carries a visible ring**: `outline: 2px solid
|
|
||||||
var(--paper)` with `2px` offset on `:focus-visible`, since the UA default is
|
|
||||||
a bright blue tuned for neither branch of this palette. `.searchbar` recolours
|
|
||||||
its border on `:focus-within` as a resting cue, but that 1px change is not the
|
|
||||||
ring — the `.search` input declares its own. A new control that suppresses
|
|
||||||
`outline` must replace it, not drop it.
|
|
||||||
- Touch targets are 44–46px under `(pointer: coarse)` — including inline text
|
|
||||||
controls like `.libswitch a`, where padding plus an 11px line lands short of
|
|
||||||
44 and needs `min-height` + `place-items: center`. The 44px desktop cells are
|
|
||||||
pointer-only (≥720px).
|
|
||||||
- The cover link is `tabindex="-1" aria-hidden="true"` because the title link
|
- The cover link is `tabindex="-1" aria-hidden="true"` because the title link
|
||||||
and the play cell already reach the same URL — do not make it a third tab stop.
|
and the play cell already reach the same URL — do not make it a third tab stop.
|
||||||
- Tabs keep `role="tab"` / `role="tablist"`; the active one is marked by class,
|
- Tabs keep `role="tab"` / `role="tablist"`; the active one is marked by class,
|
||||||
@@ -318,15 +286,13 @@ No transforms on hover, no scale, no easing curves beyond `ease-out`/`linear`.
|
|||||||
never reuse `--ember` or `--danger` for anything but their one meaning.
|
never reuse `--ember` or `--danger` for anything but their one meaning.
|
||||||
3. If it is per-series, hang it off `.is-new` / `.is-dim` rather than adding a
|
3. If it is per-series, hang it off `.is-new` / `.is-dim` rather than adding a
|
||||||
third state class.
|
third state class.
|
||||||
4. If it removes a series from the current view (archive/remove-shaped),
|
4. If it removes a series from the current view (archive/finish/remove-shaped),
|
||||||
it is confirm-gated via its own `.confirm-row` — no exceptions, restore is
|
it is confirm-gated via its own `.confirm-row` — no exceptions, restore is
|
||||||
the only instant action because it's the one that's reversible by nature.
|
the only instant action because it's the one that's reversible by nature.
|
||||||
5. Icon → `templates/icons.html`; nothing inlines SVG paths. Brand mark stays
|
5. Icon → `templates/icons.html`; nothing inlines SVG paths. Brand mark stays
|
||||||
the one exception (`chrome.html`'s `mark` template), since it takes
|
the one exception (`chrome.html`'s `mark` template), since it takes
|
||||||
page-level custom properties the sprite can't carry per-instance.
|
page-level custom properties the sprite can't carry per-instance.
|
||||||
6. Phone first (44px targets under `(pointer: coarse)`, single column), then the
|
6. Phone first (44px targets, single column), then the ≥720px block.
|
||||||
≥720px block. Mono no smaller than 11px, and a `:focus-visible` ring on
|
|
||||||
anything focusable — both are §7 floors, not preferences.
|
|
||||||
7. Verify: `cd backend && go test ./...`, then run the binary and screenshot
|
7. Verify: `cd backend && go test ./...`, then run the binary and screenshot
|
||||||
both widths and both colour schemes (Playwright: `emulateMedia`,
|
both widths and both colour schemes (Playwright: `emulateMedia`,
|
||||||
`setViewportSize`; disable the browser cache — `/static/*` is served with
|
`setViewportSize`; disable the browser cache — `/static/*` is served with
|
||||||
|
|||||||
@@ -471,10 +471,9 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Only an explicit archive/restore has an opinion about the bucket. Every
|
// Only an explicit archive/restore has an opinion about the bucket. Every
|
||||||
// other write omits `status`, so the server keeps the stored one —
|
// other write omits `status`, so the server keeps the stored one — otherwise
|
||||||
// otherwise a cached value would resend a stale status (the API rejects
|
// a cached value would resend "finished" (which the API rejects with 400) or
|
||||||
// unknown values with 400) or silently un-archive a series archived on
|
// silently un-archive a series archived on another device.
|
||||||
// another device.
|
|
||||||
async function apiPut(key, obj, { sendStatus = false } = {}) {
|
async function apiPut(key, obj, { sendStatus = false } = {}) {
|
||||||
const body = Object.assign({}, obj);
|
const body = Object.assign({}, obj);
|
||||||
if (!sendStatus) delete body.status;
|
if (!sendStatus) delete body.status;
|
||||||
@@ -551,12 +550,6 @@
|
|||||||
return b.kind || "manga";
|
return b.kind || "manga";
|
||||||
}
|
}
|
||||||
|
|
||||||
// finished is a fact about the Series, decided from the owner's side and
|
|
||||||
// derived on the wire (issue #157); the panel only labels it.
|
|
||||||
function finishedLabel(b) {
|
|
||||||
return b && b.finished ? "Finished" : "";
|
|
||||||
}
|
|
||||||
|
|
||||||
// ============================================================
|
// ============================================================
|
||||||
// Retry queue
|
// Retry queue
|
||||||
//
|
//
|
||||||
@@ -895,8 +888,8 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Archive parks a series: it leaves All and Favourites but the server keeps
|
// Archive parks a series: it leaves All and Favourites but the server keeps
|
||||||
// polling it for new chapters. finished is not a bucket the script can
|
// polling it for new chapters. "finished" is deliberately not reachable from
|
||||||
// reach — it is a fact about the Series now (issue #157).
|
// here — the API rejects that value, it is a web-UI decision.
|
||||||
async function toggleArchive(key) {
|
async function toggleArchive(key) {
|
||||||
const existing = state.byKey[key];
|
const existing = state.byKey[key];
|
||||||
if (!existing) return;
|
if (!existing) return;
|
||||||
@@ -973,6 +966,7 @@
|
|||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const due = state.list
|
const due = state.list
|
||||||
.filter((b) => b.site === site && b.series_url)
|
.filter((b) => b.site === site && b.series_url)
|
||||||
|
.filter((b) => statusOf(b) !== "finished")
|
||||||
.filter((b) => now - (checked[b.key] || 0) >= LATEST_CHECK_THROTTLE_MS)
|
.filter((b) => now - (checked[b.key] || 0) >= LATEST_CHECK_THROTTLE_MS)
|
||||||
.sort((a, b) => (checked[a.key] || 0) - (checked[b.key] || 0))
|
.sort((a, b) => (checked[a.key] || 0) - (checked[b.key] || 0))
|
||||||
.slice(0, LATEST_CHECK_BATCH);
|
.slice(0, LATEST_CHECK_BATCH);
|
||||||
@@ -1341,8 +1335,8 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Tabs narrow what is drawn; state.list always holds every bookmark.
|
// Tabs narrow what is drawn; state.list always holds every bookmark.
|
||||||
// Archived rows are hidden from All and Favourites; a Series that is
|
// Archived rows are hidden from All and Favourites, and finished ones —
|
||||||
// finished is the web UI's business and arrives archived (issue #157).
|
// which only the web UI can set — are hidden from every tab.
|
||||||
for (const [id, tab] of [["tabAll", "all"], ["tabFav", "favorites"], ["tabArc", "archived"]]) {
|
for (const [id, tab] of [["tabAll", "all"], ["tabFav", "favorites"], ["tabArc", "archived"]]) {
|
||||||
root.getElementById(id).classList.toggle("active", activeTab === tab);
|
root.getElementById(id).classList.toggle("active", activeTab === tab);
|
||||||
}
|
}
|
||||||
@@ -1405,7 +1399,6 @@
|
|||||||
el("div", { class: "meta" }, [
|
el("div", { class: "meta" }, [
|
||||||
el("a", { class: "go-t t", href: cont, text: b.title || b.series_id }),
|
el("a", { class: "go-t t", href: cont, text: b.title || b.series_id }),
|
||||||
el("div", { class: "c" + (behind ? " behind" : ""), text: sub }),
|
el("div", { class: "c" + (behind ? " behind" : ""), text: sub }),
|
||||||
b.finished && el("span", { class: "finished", text: finishedLabel(b) }),
|
|
||||||
el("div", { class: "actions" }, [
|
el("div", { class: "actions" }, [
|
||||||
el("button", {
|
el("button", {
|
||||||
class: "btn small star" + (b.favorite ? " on" : ""),
|
class: "btn small star" + (b.favorite ? " on" : ""),
|
||||||
@@ -1676,7 +1669,7 @@
|
|||||||
--paper: #f2ece5; --paper-hot: #f0d3cb; --paper-dim: #ddd5cb;
|
--paper: #f2ece5; --paper-hot: #f0d3cb; --paper-dim: #ddd5cb;
|
||||||
--mute: #8d857c; --mute-2: #5a5450; --faint: #3a3733; --faint-2: #57504b;
|
--mute: #8d857c; --mute-2: #5a5450; --faint: #3a3733; --faint-2: #57504b;
|
||||||
--ember: #e0452c; --ember-wash: #1a1211; --ember-ink: #150907;
|
--ember: #e0452c; --ember-wash: #1a1211; --ember-ink: #150907;
|
||||||
--ember-soft: #eda798; --brass: #b8912f; --trash: #6b5450; --moss: #7fae86;
|
--ember-soft: #eda798; --brass: #b8912f; --trash: #6b5450;
|
||||||
--font-display: Georgia, "Times New Roman", serif;
|
--font-display: Georgia, "Times New Roman", serif;
|
||||||
--font-mono: ui-monospace, SFMono-Regular, Menlo, monospace;
|
--font-mono: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||||
--font-body: system-ui, -apple-system, sans-serif;
|
--font-body: system-ui, -apple-system, sans-serif;
|
||||||
@@ -1795,12 +1788,6 @@
|
|||||||
font: 400 17px/1.2 var(--font-display); color: var(--paper-dim);
|
font: 400 17px/1.2 var(--font-display); color: var(--paper-dim);
|
||||||
max-width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
|
max-width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
|
||||||
}
|
}
|
||||||
/* finished: a Series fact, not a state class (issue #157) — same meta
|
|
||||||
typography as .c, moss instead of mute. */
|
|
||||||
.finished {
|
|
||||||
margin: 0; color: var(--moss);
|
|
||||||
font: 500 10px/1.4 var(--font-mono); letter-spacing: .12em; text-transform: uppercase;
|
|
||||||
}
|
|
||||||
.item.hot .t { color: var(--paper-hot); border-bottom: 1px solid var(--ember); padding-bottom: 3px; }
|
.item.hot .t { color: var(--paper-hot); border-bottom: 1px solid var(--ember); padding-bottom: 3px; }
|
||||||
.item.dim .t { font-style: italic; color: var(--mute); }
|
.item.dim .t { font-style: italic; color: var(--mute); }
|
||||||
.c {
|
.c {
|
||||||
@@ -1851,7 +1838,7 @@
|
|||||||
// Exposes pure logic only — see userscript/test/logic.test.js.
|
// Exposes pure logic only — see userscript/test/logic.test.js.
|
||||||
// ============================================================
|
// ============================================================
|
||||||
if (typeof window === "undefined" && typeof module === "object" && module.exports) {
|
if (typeof window === "undefined" && typeof module === "object" && module.exports) {
|
||||||
module.exports = { stripBuildHash, comixSeriesId, asura, demonic, comix, kagane, anchorsFromHTML, statusOf, kindOf, finishedLabel };
|
module.exports = { stripBuildHash, comixSeriesId, asura, demonic, comix, kagane, anchorsFromHTML, statusOf, kindOf };
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
|||||||
@@ -268,9 +268,8 @@
|
|||||||
// Duplicate case (spec user story 2): one row must survive, and it is
|
// Duplicate case (spec user story 2): one row must survive, and it is
|
||||||
// the one already under the repaired key — with the stale row's
|
// the one already under the repaired key — with the stale row's
|
||||||
// progress carried across when it is ahead, favourite OR'd, and the
|
// progress carried across when it is ahead, favourite OR'd, and the
|
||||||
// stronger lifecycle bucket kept (archived > reading, so a merge can
|
// stronger lifecycle bucket kept (finished > archived > reading, so a
|
||||||
// never silently un-archive a row). finished is not a bucket the
|
// merge can never silently un-archive or un-finish a row).
|
||||||
// script can see (issue #157).
|
|
||||||
const merged = Object.assign({}, existing);
|
const merged = Object.assign({}, existing);
|
||||||
if (
|
if (
|
||||||
existing.last_chapter_num == null ||
|
existing.last_chapter_num == null ||
|
||||||
@@ -281,7 +280,7 @@
|
|||||||
merged.last_chapter_url = stale.last_chapter_url;
|
merged.last_chapter_url = stale.last_chapter_url;
|
||||||
}
|
}
|
||||||
merged.favorite = !!(existing.favorite || stale.favorite);
|
merged.favorite = !!(existing.favorite || stale.favorite);
|
||||||
const rank = (s) => ({ archived: 1, reading: 0 }[s || "reading"] || 0);
|
const rank = (s) => ({ finished: 2, archived: 1, reading: 0 }[s || "reading"] || 0);
|
||||||
merged.status = rank(stale.status) > rank(existing.status) ? stale.status : existing.status;
|
merged.status = rank(stale.status) > rank(existing.status) ? stale.status : existing.status;
|
||||||
merged.updated_at = Math.max(existing.updated_at || 0, stale.updated_at || 0);
|
merged.updated_at = Math.max(existing.updated_at || 0, stale.updated_at || 0);
|
||||||
listOut = list.filter((b) => b.key !== oldKey).map((b) => (b.key === newKey ? merged : b));
|
listOut = list.filter((b) => b.key !== oldKey).map((b) => (b.key === newKey ? merged : b));
|
||||||
@@ -406,10 +405,9 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Only an explicit archive/restore has an opinion about the bucket. Every
|
// Only an explicit archive/restore has an opinion about the bucket. Every
|
||||||
// other write omits `status`, so the server keeps the stored one —
|
// other write omits `status`, so the server keeps the stored one — otherwise
|
||||||
// otherwise a cached value would resend a stale status (the API rejects
|
// a cached value would resend "finished" (which the API rejects with 400) or
|
||||||
// unknown values with 400) or silently un-archive a series archived on
|
// silently un-archive a series archived on another device.
|
||||||
// another device.
|
|
||||||
async function apiPut(key, obj, { sendStatus = false } = {}) {
|
async function apiPut(key, obj, { sendStatus = false } = {}) {
|
||||||
const body = Object.assign({}, obj);
|
const body = Object.assign({}, obj);
|
||||||
if (!sendStatus) delete body.status;
|
if (!sendStatus) delete body.status;
|
||||||
@@ -486,12 +484,6 @@
|
|||||||
return b.kind || "manga";
|
return b.kind || "manga";
|
||||||
}
|
}
|
||||||
|
|
||||||
// finished is a fact about the Series, decided from the owner's side and
|
|
||||||
// derived on the wire (issue #157); the panel only labels it.
|
|
||||||
function finishedLabel(b) {
|
|
||||||
return b && b.finished ? "Finished" : "";
|
|
||||||
}
|
|
||||||
|
|
||||||
// ============================================================
|
// ============================================================
|
||||||
// Retry queue
|
// Retry queue
|
||||||
//
|
//
|
||||||
@@ -800,8 +792,8 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Archive parks a series: it leaves All and Favourites but the server keeps
|
// Archive parks a series: it leaves All and Favourites but the server keeps
|
||||||
// polling it for new chapters. finished is not a bucket the script can
|
// polling it for new chapters. "finished" is deliberately not reachable from
|
||||||
// reach — it is a fact about the Series now (issue #157).
|
// here — the API rejects that value, it is a web-UI decision.
|
||||||
async function toggleArchive(key) {
|
async function toggleArchive(key) {
|
||||||
const existing = state.byKey[key];
|
const existing = state.byKey[key];
|
||||||
if (!existing) return;
|
if (!existing) return;
|
||||||
@@ -886,6 +878,7 @@
|
|||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const due = state.list
|
const due = state.list
|
||||||
.filter((b) => b.site === site && b.series_url)
|
.filter((b) => b.site === site && b.series_url)
|
||||||
|
.filter((b) => statusOf(b) !== "finished")
|
||||||
.filter((b) => now - (checked[b.key] || 0) >= LATEST_CHECK_THROTTLE_MS)
|
.filter((b) => now - (checked[b.key] || 0) >= LATEST_CHECK_THROTTLE_MS)
|
||||||
.sort((a, b) => (checked[a.key] || 0) - (checked[b.key] || 0))
|
.sort((a, b) => (checked[a.key] || 0) - (checked[b.key] || 0))
|
||||||
.slice(0, LATEST_CHECK_BATCH);
|
.slice(0, LATEST_CHECK_BATCH);
|
||||||
@@ -1248,8 +1241,8 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Tabs narrow what is drawn; state.list always holds every bookmark.
|
// Tabs narrow what is drawn; state.list always holds every bookmark.
|
||||||
// Archived rows are hidden from All and Favourites; a Series that is
|
// Archived rows are hidden from All and Favourites, and finished ones —
|
||||||
// finished is the web UI's business and arrives archived (issue #157).
|
// which only the web UI can set — are hidden from every tab.
|
||||||
for (const [id, tab] of [["tabAll", "all"], ["tabFav", "favorites"], ["tabArc", "archived"]]) {
|
for (const [id, tab] of [["tabAll", "all"], ["tabFav", "favorites"], ["tabArc", "archived"]]) {
|
||||||
root.getElementById(id).classList.toggle("active", activeTab === tab);
|
root.getElementById(id).classList.toggle("active", activeTab === tab);
|
||||||
}
|
}
|
||||||
@@ -1312,7 +1305,6 @@
|
|||||||
el("div", { class: "meta" }, [
|
el("div", { class: "meta" }, [
|
||||||
el("a", { class: "go-t t", href: cont, text: b.title || b.series_id }),
|
el("a", { class: "go-t t", href: cont, text: b.title || b.series_id }),
|
||||||
el("div", { class: "c" + (behind ? " behind" : ""), text: sub }),
|
el("div", { class: "c" + (behind ? " behind" : ""), text: sub }),
|
||||||
b.finished && el("span", { class: "finished", text: finishedLabel(b) }),
|
|
||||||
el("div", { class: "actions" }, [
|
el("div", { class: "actions" }, [
|
||||||
el("button", {
|
el("button", {
|
||||||
class: "btn small star" + (b.favorite ? " on" : ""),
|
class: "btn small star" + (b.favorite ? " on" : ""),
|
||||||
@@ -1601,7 +1593,7 @@
|
|||||||
--paper: #f2ece5; --paper-hot: #f0d3cb; --paper-dim: #ddd5cb;
|
--paper: #f2ece5; --paper-hot: #f0d3cb; --paper-dim: #ddd5cb;
|
||||||
--mute: #8d857c; --mute-2: #5a5450; --faint: #3a3733; --faint-2: #57504b;
|
--mute: #8d857c; --mute-2: #5a5450; --faint: #3a3733; --faint-2: #57504b;
|
||||||
--ember: #e0452c; --ember-wash: #1a1211; --ember-ink: #150907;
|
--ember: #e0452c; --ember-wash: #1a1211; --ember-ink: #150907;
|
||||||
--ember-soft: #eda798; --brass: #b8912f; --trash: #6b5450; --moss: #7fae86;
|
--ember-soft: #eda798; --brass: #b8912f; --trash: #6b5450;
|
||||||
--font-display: Georgia, "Times New Roman", serif;
|
--font-display: Georgia, "Times New Roman", serif;
|
||||||
--font-mono: ui-monospace, SFMono-Regular, Menlo, monospace;
|
--font-mono: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||||
--font-body: system-ui, -apple-system, sans-serif;
|
--font-body: system-ui, -apple-system, sans-serif;
|
||||||
@@ -1727,12 +1719,6 @@
|
|||||||
font: 500 10px/1.4 var(--font-mono); letter-spacing: .12em; text-transform: uppercase;
|
font: 500 10px/1.4 var(--font-mono); letter-spacing: .12em; text-transform: uppercase;
|
||||||
}
|
}
|
||||||
.c.behind { color: var(--ember); }
|
.c.behind { color: var(--ember); }
|
||||||
/* finished: a Series fact, not a state class (issue #157) — same meta
|
|
||||||
typography as .c, moss instead of mute. */
|
|
||||||
.finished {
|
|
||||||
margin: 0; color: var(--moss);
|
|
||||||
font: 500 10px/1.4 var(--font-mono); letter-spacing: .12em; text-transform: uppercase;
|
|
||||||
}
|
|
||||||
.actions { display: flex; gap: 0; flex-wrap: wrap; margin-top: 2px; }
|
.actions { display: flex; gap: 0; flex-wrap: wrap; margin-top: 2px; }
|
||||||
.btn {
|
.btn {
|
||||||
background: none; color: var(--mute); border: 1px solid var(--rule);
|
background: none; color: var(--mute); border: 1px solid var(--rule);
|
||||||
@@ -1776,7 +1762,7 @@
|
|||||||
// Exposes pure logic only — see userscript/test/novel-logic.test.js.
|
// Exposes pure logic only — see userscript/test/novel-logic.test.js.
|
||||||
// ============================================================
|
// ============================================================
|
||||||
if (typeof window === "undefined" && typeof module === "object" && module.exports) {
|
if (typeof window === "undefined" && typeof module === "object" && module.exports) {
|
||||||
module.exports = { novelfull, lightnovelworld, anchorsFromHTML, statusOf, kindOf, maxChapter, escapeRe, computeLatestChapter, repairLnwStaleRow, finishedLabel };
|
module.exports = { novelfull, lightnovelworld, anchorsFromHTML, statusOf, kindOf, maxChapter, escapeRe, computeLatestChapter, repairLnwStaleRow };
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
|||||||
@@ -58,7 +58,6 @@ const {
|
|||||||
anchorsFromHTML,
|
anchorsFromHTML,
|
||||||
statusOf,
|
statusOf,
|
||||||
kindOf,
|
kindOf,
|
||||||
finishedLabel,
|
|
||||||
} = require("../manga-bookmark.user.js");
|
} = require("../manga-bookmark.user.js");
|
||||||
|
|
||||||
// detect() reads only these four properties off location.
|
// detect() reads only these four properties off location.
|
||||||
@@ -396,18 +395,7 @@ test("statusOf defaults a missing status to reading", () => {
|
|||||||
assert.equal(statusOf({}), "reading");
|
assert.equal(statusOf({}), "reading");
|
||||||
assert.equal(statusOf({ status: "" }), "reading");
|
assert.equal(statusOf({ status: "" }), "reading");
|
||||||
assert.equal(statusOf({ status: "archived" }), "archived");
|
assert.equal(statusOf({ status: "archived" }), "archived");
|
||||||
});
|
assert.equal(statusOf({ status: "finished" }), "finished");
|
||||||
|
|
||||||
// ============================================================
|
|
||||||
// finishedLabel — finished is a fact about the Series (issue #157), which is
|
|
||||||
// the server's business; the panel only names it. The label is text through
|
|
||||||
// the el() helper, never markup.
|
|
||||||
// ============================================================
|
|
||||||
|
|
||||||
test("finishedLabel names a finished series and nothing else", () => {
|
|
||||||
assert.equal(finishedLabel({ finished: true }), "Finished");
|
|
||||||
assert.equal(finishedLabel({ finished: false }), "");
|
|
||||||
assert.equal(finishedLabel({}), "");
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
|||||||
@@ -49,7 +49,6 @@ const {
|
|||||||
kindOf,
|
kindOf,
|
||||||
maxChapter,
|
maxChapter,
|
||||||
repairLnwStaleRow,
|
repairLnwStaleRow,
|
||||||
finishedLabel,
|
|
||||||
} = require("../novel-bookmark.user.js");
|
} = require("../novel-bookmark.user.js");
|
||||||
|
|
||||||
function loc(href) {
|
function loc(href) {
|
||||||
@@ -564,23 +563,6 @@ test("repairLnwStaleRow does not regress progress when the repaired-key row is a
|
|||||||
assert.equal(out.list[0].last_chapter_num, 100);
|
assert.equal(out.list[0].last_chapter_num, 100);
|
||||||
});
|
});
|
||||||
|
|
||||||
// ============================================================
|
|
||||||
// Merge rank — exactly two values: archived beats reading, and nothing else
|
|
||||||
// can ever win (issue #157 retired the finished bucket).
|
|
||||||
// ============================================================
|
|
||||||
|
|
||||||
test("repairLnwStaleRow merge keeps archived over reading and lets no third value win", () => {
|
|
||||||
const canonical = (over) => staleRow(Object.assign({ key: "lightnovelworld:immortality-simulator" }, over));
|
|
||||||
// archived beats reading whether it arrives as the stale row or the repaired one
|
|
||||||
let out = repairLnwStaleRow([canonical({ status: "archived" }), staleRow({ status: "reading" })], [], {}, lnwPage());
|
|
||||||
assert.equal(out.list[0].status, "archived");
|
|
||||||
out = repairLnwStaleRow([staleRow({ status: "archived" }), canonical({ status: "reading" })], [], {}, lnwPage());
|
|
||||||
assert.equal(out.list[0].status, "archived");
|
|
||||||
// "finished" is not a bucket anymore: a row carrying it reads as the
|
|
||||||
// default, so it can never win (issue #157).
|
|
||||||
out = repairLnwStaleRow([staleRow({ status: "finished" }), canonical({ status: "reading" })], [], {}, lnwPage());
|
|
||||||
assert.equal(out.list[0].status, "reading");
|
|
||||||
});
|
|
||||||
// ============================================================
|
// ============================================================
|
||||||
// kindOf
|
// kindOf
|
||||||
// ============================================================
|
// ============================================================
|
||||||
@@ -593,18 +575,6 @@ test("kindOf passes through novel", () => {
|
|||||||
assert.equal(kindOf({ kind: "novel" }), "novel");
|
assert.equal(kindOf({ kind: "novel" }), "novel");
|
||||||
});
|
});
|
||||||
|
|
||||||
// ============================================================
|
|
||||||
// finishedLabel — finished is a fact about the Series (issue #157), which is
|
|
||||||
// the server's business; the panel only names it. The label is text through
|
|
||||||
// the el() helper, never markup.
|
|
||||||
// ============================================================
|
|
||||||
|
|
||||||
test("finishedLabel names a finished series and nothing else", () => {
|
|
||||||
assert.equal(finishedLabel({ finished: true }), "Finished");
|
|
||||||
assert.equal(finishedLabel({ finished: false }), "");
|
|
||||||
assert.equal(finishedLabel({}), "");
|
|
||||||
});
|
|
||||||
|
|
||||||
// ============================================================
|
// ============================================================
|
||||||
// Source guard
|
// Source guard
|
||||||
//
|
//
|
||||||
|
|||||||
Reference in New Issue
Block a user