Documentation
¶
Overview ¶
Package urlcat is the admin-managed URL-category engine: named categories with lowercase host-set indexing for O(labels) membership checks during policy evaluation, JSON file persistence, and the built-in + embedded-SaaS default seed list. Extracted from package main's policy.go per ADR-0002 (policy.go decomposition Phase A).
package main keeps the surfaces: the `catStore` singleton, the TWO-TIER category resolution (matchCategory / lookupHostCategory compose this store with the community BadgerDB feed), the API handlers, cluster sync, and config-version rollback — all through aliases.
Index ¶
- Constants
- Variables
- func DefaultBusinessCategoryNames() []string
- func ValidateEntries(entries []Entry) error
- type Category
- type Entry
- type RevisionConflictError
- type Store
- func (s *Store) AddHost(category, host string) error
- func (s *Store) AddHostDurable(expectedRev *string, category, host string) error
- func (s *Store) All() []Entry
- func (s *Store) BuiltInFlag(name string) (builtIn, found bool)
- func (s *Store) BuiltInHostCategories() map[string]string
- func (s *Store) BuiltInHostMemberships() map[string][]string
- func (s *Store) ContentFingerprint() string
- func (s *Store) CreateDurable(expectedRev *string, name string, hosts []string) error
- func (s *Store) Delete(name string) error
- func (s *Store) DeleteDurable(expectedRev *string, name string) error
- func (s *Store) GetByName(name string) *Entry
- func (s *Store) Load(path string) error
- func (s *Store) LookupHost(host string) (category, matchedBy string, ok bool)
- func (s *Store) LookupHostAdmin(host string) (category, matchedBy string, ok bool)
- func (s *Store) MatchesHost(cat Category, host string) bool
- func (s *Store) MatchesHostAdmin(cat Category, host string) bool
- func (s *Store) MatchesHostAdminNorm(cat Category, normHost string) bool
- func (s *Store) MatchesHostNorm(cat Category, normHost string) bool
- func (s *Store) Path() string
- func (s *Store) RemoveHost(category, host string) error
- func (s *Store) RemoveHostDurable(expectedRev *string, category, host string) error
- func (s *Store) ReplaceAll(cats []Entry)
- func (s *Store) ReplaceAllChecked(cats []Entry) error
- func (s *Store) ReplaceHostsDurable(expectedRev *string, name string, hosts []string) error
- func (s *Store) Revision() uint64
- func (s *Store) Save()
- func (s *Store) SaveErr() error
- func (s *Store) Set(name string, hosts []string, builtIn bool) error
- func (s *Store) SetPathForTest(path string)
- func (s *Store) SnapshotWithRevision() (entries []Entry, revision string)
Constants ¶
const MaxHostsPerCategory = 10000
MaxHostsPerCategory is the post-mutation size bound for ONE category, enforced at the store boundary (2D-B §11) so no write path — POST, PUT, single-host AddHost, or a future caller — can grow a category past it.
Variables ¶
var ErrNameExists = errors.New("category name already exists")
ErrNameExists is the strict-create refusal: the v2 "Create category" path must never silently update an existing category (2D-B §10).
var ErrPersist = errors.New("url category persistence failed")
ErrPersist marks a durable-mutation failure: the mutation was rolled back and nothing changed, in memory or on disk (2D-B.0a, the 2D-A doctrine).
var ErrTooManyHosts = fmt.Errorf("category cannot contain more than %d hosts", MaxHostsPerCategory)
ErrTooManyHosts is the MaxHostsPerCategory bound refusal.
Functions ¶
func DefaultBusinessCategoryNames ¶ added in v1.0.208
func DefaultBusinessCategoryNames() []string
DefaultBusinessCategoryNames returns the sorted names of the embedded SaaS BUSINESS category seed list ONLY (default_categories.json) — deliberately excluding the hardcoded non-business built-ins (Social Media, Malicious, News, Streaming, Gambling, Adult). This is the fail-closed seed for the policy-learning recommendable-category allowlist (ADR-0025 M4): a category must be on this list (or a future governed surface's) before the learning engine may propose an Allow rule for it.
func ValidateEntries ¶ added in v1.0.218
ValidateEntries is the CANONICAL full-set bulk validation seam (2D-B final correction, Blocker C): every category in a bulk candidate must satisfy the same MaxHostsPerCategory bound the admin write paths enforce (raw len, the exact check setMem/addHostMem/CreateDurable/ReplaceHostsDurable apply). Every RUNTIME bulk installer — cluster snapshot apply, config import, config-version rollback — must judge its whole candidate through this (or ReplaceAllChecked) BEFORE installing anything: an over-cap category rejects the WHOLE candidate, never truncated, never partially applied. Startup Load is the one deliberate exemption (legacy compatibility: a pre-cap on-disk file keeps loading; no runtime path may re-create what it grandfathers).
Types ¶
type Entry ¶
type Entry struct {
Name string `json:"name"`
Hosts []string `json:"hosts"`
BuiltIn bool `json:"builtIn"` // seeded from built-in defaults; editable by admin
}
Entry is one named URL category with its list of host patterns.
func DefaultEntries ¶
func DefaultEntries() []*Entry
DefaultEntries returns the built-in hardcoded categories merged with the embedded SaaS category seed list.
type RevisionConflictError ¶ added in v1.0.218
type RevisionConflictError struct {
Current string // the store's current ContentFingerprint
Asserted string // the revision the caller asserted
}
RevisionConflictError reports a failed optimistic-revision fence: the client asserted the semantic taxonomy revision (ContentFingerprint) it loaded, and the store's current revision differs. Mirrors the 2D-A VersionConflictError shape so handlers render the same structured 409. The fingerprint is ABA-blind by design (an A→B→A round trip restores the same identity) — accepted for this fence per the 2D-B §7 decision: equality means the CURRENT semantic taxonomy is equivalent to what the operator loaded, which is exactly what the fence protects.
func (*RevisionConflictError) Error ¶ added in v1.0.218
func (e *RevisionConflictError) Error() string
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store manages URL categories with thread-safe, file-backed persistence. index maps lowercase(category-name) → set of lowercase host strings for O(1) host membership checks during policy evaluation. adminIndex is the same, restricted to admin-created (BuiltIn=false) categories — the signed-feed F3b-4 cutover consults it so the SaaS taxonomy (BuiltIn=true) is served by the atomic effective view instead of double-served from here.
func (*Store) AddHost ¶
AddHost appends a host to the named category (no-op if already present). LEGACY wrapper: mutation + best-effort persistence per call — the SaaS legacy feed merge calls it once per merged host, so the memory mutation must stay the incremental-index fold (addHostToIndexes), never a wholesale rebuild.
func (*Store) AddHostDurable ¶ added in v1.0.218
AddHostDurable is the fenced v2 single-host add. Enforces the post-mutation MaxHostsPerCategory bound (the legacy AddHost could grow past the cap).
func (*Store) BuiltInFlag ¶ added in v1.0.218
BuiltInFlag reports whether the named category (case-insensitive) exists and carries the BuiltIn flag. Cheap read accessor — no host copying.
func (*Store) BuiltInHostCategories ¶ added in v1.0.180
BuiltInHostCategories returns a normalized host→category map over the BuiltIn=true entries (the embedded/seeded SaaS taxonomy + rule-vocabulary built-ins). It is the initial effective-view baseline for the signed feed: building it from the live store — not the compiled DefaultEntries — preserves any admin host-additions to built-in categories and any legacy-merged SaaS hosts already persisted. Empty-host entries (e.g. UT1 name-seeds) contribute nothing.
A host that appears under SEVERAL built-in categories (the shipped taxonomy has such hosts — e.g. linkedin.com is both "Social Media" and "HR & Recruiting") collapses to ONE category here, because the map shape admits only one. FIRST entry wins, matching the entry-order precedence LookupHost applies when it scans s.entries top-down — so the collapsed value is the same category the pre-effective-view classification path returned. (It used to be LAST-wins, which silently changed which category a multi-category host classified as once the effective view went on the policy path.)
This map is a CLASSIFICATION view ("what is this host?") and is lossy by construction. Never answer a MEMBERSHIP question ("is this host in category C?") from it — use BuiltInHostMemberships, which keeps every category.
func (*Store) BuiltInHostMemberships ¶ added in v1.0.207
BuiltInHostMemberships returns a normalized host→categories map over the BuiltIn=true entries, keeping EVERY category a host belongs to rather than collapsing to one. Per-host category lists are in s.entries order (so index 0 is the classification winner BuiltInHostCategories reports) and deduplicated.
It is the membership source for the signed-feed effective view: MatchesHost answers "is host in category C?" across the full many-to-many taxonomy, and an effective view built from the collapsed single-category map cannot answer that question without losing a category — which drops a policy rule keyed on the losing category (a fail-open). Empty-host entries contribute nothing.
func (*Store) ContentFingerprint ¶ added in v1.0.208
ContentFingerprint returns a deterministic semantic identity of the taxonomy: equal iff the RESOLUTION-RELEVANT content is equal, stable across restart/reload of identical persisted state (unlike a process-local revision counter). Consumed by the policy-learning category epoch (ADR-0025 §6, epoch scheme v2).
Covered (exactly the state that can change a Lookup*/Matches* result):
- the ENTRY SEQUENCE ORDER (QB-2.1: LookupHost/LookupHostAdmin scan s.entries in order and return the FIRST match, so order is resolution-relevant whenever category patterns overlap; entries are framed in sequence, never sorted — a reorder that cannot change any resolution (no overlaps) still changes the identity, an accepted CONSERVATIVE false-stale: safer than missing a real semantic change),
- every entry's Name in ORIGINAL case (the resolvers return it verbatim, and downstream consumers key on it),
- the BuiltIn flag (it decides admin-tier membership: LookupHostAdmin / MatchesHostAdmin see only BuiltIn=false entries),
- the entry's host patterns, lowercased RAW — the trailing dot is KEPT (v3, Codex round 26): the host→category resolver (LookupHost, the path Learning consumes) compares strings.ToLower(pattern) with NO trailing- dot trim while the incoming host IS trimmed, so a "example.com." spelling is a DEAD pattern there and switching a live pattern to it is resolution-relevant — the fingerprint must move. (The category→hosts matcher MatchesHost trims, so for it this is a conservative false-stale — the accepted direction. The two matchers have disagreed on this spelling since before the reverse index existed; the fingerprint mirrors the resolver Learning actually uses.) De-duplicated and sorted — WITHIN-entry host order stays canonical because it can only affect the matchedBy display string, and Learning consumes the resolved category, never matchedBy.
Excluded by contract: process-local counters, timestamps, mutation history, map iteration order, host pattern CASE and exact-duplicate patterns (matchedBy display only), empty patterns, and display-only or metrics state. Framing is length-prefixed under fingerprintDomain, so field boundaries are unambiguous.
The value is memoized on the semantic-mutation revision: in steady state a read is two atomic loads, and the hash is recomputed at most once per mutation BATCH by the first reader that needs it (single-flighted through fpMu). Computation happens under the READ lock, so it never stalls the request path's category lookups; a zero-value store (pre-Load window) answers on demand and caches at revision 0.
Freshness is exact, not best-effort: every semantic mutation advances s.rev inside the writer's critical section, so a reader that can observe new content necessarily observes the advanced revision, misses the memo, and recomputes. A cached entry can therefore never describe superseded content (s.rev is monotonic, so a revision names exactly one content state). That is load-bearing beyond performance — the policy-learning category epoch pins this value, and a fingerprint that failed to move after a taxonomy edit would leave recommendations reported FRESH against a taxonomy their evidence was never observed under.
func (*Store) CreateDurable ¶ added in v1.0.218
CreateDurable is the fenced v2 "create category" primitive — STRICT create (2D-B §10): an existing case-insensitive name is refused with ErrNameExists, never silently updated. Enforces MaxHostsPerCategory.
func (*Store) Delete ¶
Delete removes a category by name. Returns an error if not found. LEGACY wrapper: mutation + best-effort persistence.
func (*Store) DeleteDurable ¶ added in v1.0.218
DeleteDurable is the fenced v2 "delete category" primitive.
func (*Store) GetByName ¶
GetByName finds a category by name (case-insensitive). Returns the live entry pointer (callers treat it as read-only outside the store's lock — pre-extraction contract preserved).
func (*Store) Load ¶
Load reads categories from a JSON file. If the file does not exist the built-in defaults are seeded and written to disk.
func (*Store) LookupHost ¶
LookupHost resolves a hostname to its category (exact + suffix match), returning the original-case category name and the pattern that matched. matchedBy is the admin's configured pattern verbatim, not a normalized form (admin URL-lookup API contract) — hence the index resolves back through s.entries rather than answering from a lowercase key.
func (*Store) LookupHostAdmin ¶ added in v1.0.180
LookupHostAdmin is LookupHost restricted to admin-created (BuiltIn=false) categories (the admin layer of the F3b-4 source-aware resolution). Same exact-or-subdomain grammar as LookupHost.
func (*Store) MatchesHost ¶
MatchesHost checks whether host belongs to the named URL category. Uses the pre-built index for O(labels) lookup instead of O(N×M) iteration.
It is the NORMALIZING wrapper over MatchesHostNorm: host is canonicalized here and the membership decision is made there. Callers that already hold hostutil.NormalizeHost(host) — the per-request policy scan does, see MatchesHostNorm — should call that directly and skip this.
func (*Store) MatchesHostAdmin ¶ added in v1.0.180
MatchesHostAdmin is MatchesHost restricted to admin-created (BuiltIn=false) categories. The signed-feed F3b-4 policy path consults this so the built-in / embedded SaaS taxonomy is served exclusively by the atomic effective view and never double-served (or served stale) from this store after a signed activation supersedes it. Same normalization + exact-then-suffix semantics as MatchesHost, and LOCK-FREE on the same contract.
func (*Store) MatchesHostAdminNorm ¶ added in v1.0.265
MatchesHostAdminNorm is MatchesHostAdmin over an already-normalized host — the admin-tier twin of MatchesHostNorm, and the entry point the policy scan uses when the signed-feed effective view is armed. See MatchesHostNorm for why the normalization is hoisted to the caller. LOCK-FREE, as MatchesHostNorm.
func (*Store) MatchesHostNorm ¶ added in v1.0.265
MatchesHostNorm is MatchesHost over a host the CALLER has already run through hostutil.NormalizeHost. It is the per-rule entry point for the policy hot path. LOCK-FREE: it probes the published forwardView, never s.mu.
Why it exists: package main's hostCatScratch.matchesCategory (policy_hostcat.go) calls a membership matcher once per category-scoped access rule per proxied request, and MatchesHost re-canonicalized the SAME destination on every one of those calls. Normalization is a pure function of the host, so it is request-invariant — the same class of value as the normalized host, the parsed client IP and the one clock read that Evaluate already hoists out of its rule scan, and the most expensive of them: measured at 45.97 ns against MatchesHost's 105.8 ns total, i.e. 43% of the probe was re-deriving a value the scan already had (that measurement predates forwardView; the RLock it then included was ~10 ns of it).
The hoist needs NO idempotence assumption about NormalizeHost, which is what makes it a pure cost change: the value matched against is hostutil.NormalizeHost(host) either way — the same function applied to the same input — so only WHERE it is computed moves. Equivalence is pinned against this file's own wrapper by urlcat_matcheshost_norm_test.go (named shapes + randomized sweep + FuzzMatchesHostNorm), so a future change to either body that breaks the identity fails the build.
func (*Store) RemoveHost ¶
RemoveHost deletes a host from the named category. LEGACY wrapper: mutation + best-effort persistence.
func (*Store) RemoveHostDurable ¶ added in v1.0.218
RemoveHostDurable is the fenced v2 single-host remove.
func (*Store) ReplaceAll ¶
ReplaceAll atomically replaces all categories. Holds mutMu so a bulk install orders against the v2 revision fence and the publication/commit boundary (2D-B §12); memory-only — the callers' separate Save() reacquires the domain and publishes the current committed state.
UNCHECKED: it does not enforce MaxHostsPerCategory, for exactly one caller class — startup Load's legacy-compatibility installs (and tests). Every RUNTIME bulk path (cluster snapshot apply, config import, rollback) must go through ReplaceAllChecked / ValidateEntries instead (Blocker C).
func (*Store) ReplaceAllChecked ¶ added in v1.0.218
ReplaceAllChecked validates the whole candidate through ValidateEntries and installs it only when every category passes — the checked bulk installer runtime callers must use. On error NOTHING changes (whole-candidate reject; the store keeps serving its current taxonomy).
func (*Store) ReplaceHostsDurable ¶ added in v1.0.218
ReplaceHostsDurable is the fenced v2 "replace category hosts" primitive. The category must exist; its BuiltIn flag is preserved INSIDE the transaction (the legacy handler's read-then-write of the flag had a window). Enforces MaxHostsPerCategory (the legacy PUT lacked the cap — 2D-B §11 closes the contract at the store boundary).
func (*Store) Revision ¶ added in v1.0.208
Revision returns the process-local semantic-mutation counter. Monotonic within a process; resets on restart — a fence key, not an identity.
func (*Store) Save ¶
func (s *Store) Save()
Save atomically persists categories to disk. Best-effort legacy wrapper (errors discarded — the pre-2D-B contract); the fenced v2 durable primitives use the error-returning path and roll back on failure.
func (*Store) SaveErr ¶ added in v1.0.218
SaveErr is the PUBLIC error-returning persistence entry. It acquires mutMu FIRST (the 2D-A commit-boundary doctrine), so a standalone save orders against the whole mutation domain and can never observe — let alone publish — an in-flight durable mutation's memory. The durable primitives already hold mutMu and call saveErrLocked directly; mutMu is not reentrant, so an internal SaveErr call from inside the mutation domain would deadlock and must never be added.
func (*Store) Set ¶
Set creates or replaces the host list for a named category. LEGACY upsert wrapper (pre-2D-B contract preserved for old callers): mutation + best-effort persistence, errors discarded. The fenced v2 path uses CreateDurable (strict create) / ReplaceHostsDurable instead.
func (*Store) SetPathForTest ¶
SetPathForTest points persistence at path without loading (Load on a missing file would seed the defaults; tests often want an EMPTY store that saves to a temp location).
func (*Store) SnapshotWithRevision ¶ added in v1.0.218
SnapshotWithRevision returns a copy of all category entries TOGETHER WITH the semantic ContentFingerprint of exactly those entries, captured under one hold of the read lock (2D-B final coherency correction, Blocker A). All() followed by ContentFingerprint() is two independent reads — a writer landing between them hands the caller superseded rows paired with the successor's revision, and a client editing from that pair passes the fence against content it never saw. This is the ONLY read the v2 state contract may use.
COMMITTED-SNAPSHOT rule (transactional-read correction): the snapshot also acquires mutMu FIRST, so a management read can never observe an IN-FLIGHT durable transaction — mutateDurable mutates memory inside fn (releasing mu) before the durable publication, and a persist failure rolls the memory back, so a snapshot taken in that window would describe taxonomy that was never durably acknowledged, never recomposed into the effective view, and may vanish on rollback. A management GET describes committed/current management truth, not intermediate mutation memory; it waits for the open transaction to reach success or rollback. This is a COLD admin read — the hot-path lookups (LookupHost/MatchesHost/ContentFingerprint) never touch mutMu.
Lock order is the store's established order: mutMu → fpMu → mu. fpMu is held so the memo single-flight stays intact (a valid memo is reused; a computed pair is published for the next reader), and the entries copy happens under the SAME mu.RLock as the rev/fingerprint capture, so no writer's critical section can land between the rows and the revision that names them.