catgroup

package
v1.0.366 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 11 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package catgroup is the named category-group engine: bundles of URL categories (e.g. "AI", "Marketing", "Messaging") under a single name (e.g. "Prod Allowed") that policy rules reference instead of individual categories, enabling Zero Trust postures like: Auth Users → Prod Allowed → Allow, Deny Any Any. Extracted from package main's categorygroup.go per a recorded ADR-0002-style design (post-program extraction).

Performance: each group maintains a pre-computed catSet (map[string]bool) for O(1) membership checks on the proxy hot path. The set is rebuilt on every mutation (admin edit, UT1 sync, cluster sync) — never during request evaluation. All category names are normalized to lowercase.

Concurrency: RWMutex protects the authoritative store, and every writer republishes an immutable readView that the per-request matchers read with no lock at all (see readView). Write path (ReplaceAll) builds the new map outside the lock, then swaps the pointer under a brief Lock.

package main keeps: the `globalCategoryGroups` singleton, the API handlers, cluster sync, rollback, and — deliberately — the HOST-level match (`categoryGroupMatchesHost`): resolving a host to its category is the two-tier catStore+communityDB fusion that lives in main (same verdict as the urlcat extraction), so this engine exposes the pure MatchesCategory instead.

Index

Constants

This section is empty.

Variables

View Source
var ErrNameTaken = errors.New("name already in use")

ErrNameTaken marks a name-collision refusal (create against an existing name, or rename onto a name a DIFFERENT group owns). Handlers map it to a 409 — the server-authoritative refusal, checked under the store lock so a concurrent create/rename cannot slip past a handler-level pre-check.

View Source
var ErrPersist = errors.New("category groups: durable persistence failed")

ErrPersist marks a durable-persistence failure surfaced by MutateDurable AFTER the in-memory mutation was rolled back: nothing durable changed and the in-memory store was restored to the pre-mutation truth. Handlers map it to a 5xx — never a success.

Functions

This section is empty.

Types

type Group

type Group struct {
	ID         string   `json:"id"`
	Name       string   `json:"name"`
	Categories []string `json:"categories"`
	CreatedAt  string   `json:"created_at,omitempty"`
	UpdatedAt  string   `json:"updated_at,omitempty"`
	// contains filtered or unexported fields
}

Group is a named bundle of URL category names.

type Snapshot added in v1.0.218

type Snapshot struct {
	Groups  []Group
	Names   []string
	Version int64
}

Snapshot is one coherent read of the whole list contract: the groups, the derived name list, and the durable fence version, all describing the SAME store state (POST-2D-A COHERENT-READ CORRECTION DISCOVERED DURING 2D-B REVIEW).

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store manages persistent category groups with O(1) lookups.

func New

func New() *Store

New builds an empty store.

func (*Store) Add

func (s *Store) Add(name string, categories []string) (*Group, error)

Add creates a new category group. Returns error if name already exists.

func (*Store) ContainsCategory

func (s *Store) ContainsCategory(catName string) (groupName string, found bool)

ContainsCategory returns true if any group references the given category name. Used for referential integrity when deleting a base category.

func (*Store) Delete

func (s *Store) Delete(name string) error

Delete removes a group by name. Returns error if not found.

func (*Store) DeleteByID added in v1.0.86

func (s *Store) DeleteByID(id string) (string, error)

DeleteByID removes the group with the given stable ID. Returns the removed group's name (for audit/reference bookkeeping) or an error if not found.

func (*Store) GetByID added in v1.0.86

func (s *Store) GetByID(id string) *Group

GetByID returns a copy of the group with the given stable ID, or nil. ID addressing is rename-safe (the name key is mutable; the ID is not). O(1), lock-free, off the published view's byID index.

func (*Store) GetByName

func (s *Store) GetByName(name string) *Group

GetByName returns a group by name (case-insensitive). O(1), lock-free, off the published view. Returns nil if not found.

The returned pointer is safe to read concurrently, and now actually is: a published *Group is never mutated in place (readView), so the caller reads an immutable snapshot. Before the view, Update/UpdateByID/Rename edited the live value a previous caller still held, which made reading its catSet or Name a data race the comment here claimed was impossible.

func (*Store) List

func (s *Store) List() []Group

List returns a copy of all groups (safe for JSON serialization).

func (*Store) Load

func (s *Store) Load(path string) error

Load reads groups from a JSON file and pre-computes catSets.

func (*Store) MatchesCategory

func (s *Store) MatchesCategory(groupName, category string) bool

MatchesCategory reports whether the named group contains the given (already-resolved) category. This is the engine half of the hot-path group match: package main's categoryGroupMatchesHost resolves host → category through its two-tier fusion, then calls this O(1) check. Unknown group = no match (fail-closed); empty category never matches.

Lock-free, off the published view, so the name fallback no longer writes s.mu's cache line once per category-group rule per request. An earlier shape resolved the group through a locked GetByName and then read g.catSet with no lock held, racing Update / UpdateByID, which REASSIGNED the field of the live group under the write lock (the race detector reported that exact pair: proxy traffic evaluating an un-migrated category-group rule concurrent with an admin edit of that group). That race is now retired by ownership rather than by locking: a group reachable from a published view is never mutated in place, because every writer installs a copy-on-write replacement.

func (*Store) MatchesCategoryByID added in v1.0.96

func (s *Store) MatchesCategoryByID(id, category string) (matched, resolved bool)

MatchesCategoryByID is MatchesCategory keyed by the group's stable ID (references-by-id S2 hot-path match). resolved=true iff a group with that id EXISTS; matched is whether that group contains the (already-resolved) category. The ID is AUTHORITATIVE: a resolved group returns its own membership result so the caller does NOT fall back to a possibly-stale denormalized name (which could match a DIFFERENT group). Empty id / not found ⇒ resolved=false so the caller may fall back to the name.

Lock-free and O(1): one atomic view load, one byID probe, one catSet probe. It is called once per category-group rule inside the policy scan, so both properties matter — the byID index retired the O(groups) scan, and the published view retires the per-call s.mu.RLock. See readView for the measured figures.

func (*Store) MutateDurable added in v1.0.218

func (s *Store) MutateDurable(ifVersion *int64, fn func() error) error

MutateDurable runs ONE admin mutation with the OPTIONAL expected-version fence AND the durable persist evaluated in the same serialized critical section (the 2B.0a/2B.0b contract transposed to the object store):

  • ifVersion == nil: no fence — the mutation proceeds (still serialized, still durable-or-nothing). Legacy name-addressed callers land here.
  • ifVersion != nil: compared against the store generation BEFORE fn runs; a mismatch returns *VersionConflictError and the mutation never runs.
  • fn applies the in-memory mutation through the normal store methods; its error is returned verbatim (validation/not-found → the handler's 4xx).
  • On fn success the generation bumps and SaveErr persists content + epoch as ONE atomic envelope. A pre-replacement persist failure restores the pre-mutation in-memory state (objects AND generation) and returns the failure wrapped in ErrPersist — confirmed 2xx therefore means restart-durable, epoch included.
  • ErrReplacedNotSynced follows the repository's landed-content doctrine (the renamed file already carries the new objects; rolling memory back would contradict the visible file and a restart would activate the "failed" state anyway): proceed as success with a warning. Because the envelope is one write, the landed content CARRIES the new epoch — a restart can never re-expose the pre-mutation token.

Bulk install writers (ReplaceAll) hold the SAME mutMu, so nothing can alter the fenced domain between the version comparison and the mutation.

func (*Store) Names

func (s *Store) Names() []string

Names returns all group names (for UI dropdowns).

func (*Store) Path

func (s *Store) Path() string

Path reports the persistence path ("" = persistence disabled).

func (*Store) Rename added in v1.0.96

func (s *Store) Rename(id, newName string) (oldName string, err error)

Rename changes the display name of the group with the given stable ID, re-keying the name map and the order slice (references-by-id S2: rules link by ID, so the rename is safe — the caller cascades the denormalized name onto referencing rules). Validates the new name is non-empty and not already taken by a DIFFERENT group. Returns the OLD name (for audit + the caller's cascade). A case-only change updates the display name in place without a collision check.

func (*Store) ReplaceAll

func (s *Store) ReplaceAll(groups []Group)

ReplaceAll atomically replaces all groups (used by cluster config sync, config import, and config-version rollback). Builds catSets outside the store lock for zero contention.

SERIALIZATION (2D-A fence correction, Blocker B): ReplaceAll holds the SAME mutMu as MutateDurable, so a bulk install can never interleave between a client's ifVersion comparison and its protected mutation — the two writer classes observe exactly one serial order, and the fence generation cannot alias across them.

func (*Store) Revision added in v1.0.208

func (s *Store) Revision() uint64

Revision returns the process-local mutation counter. Monotonic within a process; resets on restart — a memo key, not an identity.

Served from the published view, so the counter a caller reads and the contents it can observe are the SAME generation (see readView).

func (*Store) Save

func (s *Store) Save()

Save persists the current groups to disk (atomic write). Best-effort legacy wrapper for old non-critical callers; the hardened v2 mutation path (MutateDurable) uses the error-returning SaveErr and rolls back on failure.

func (*Store) SaveErr added in v1.0.218

func (s *Store) SaveErr() error

SaveErr is the error-returning persistence core (2D-A durable-or-nothing): callers that must know whether the durable write landed use it directly. Content and the fence epoch are ONE envelope in ONE atomic write, so they can never diverge durably — including under ErrReplacedNotSynced, where the landed replacement carries the new epoch with the new content. The retired legacy sidecar is removed once the envelope has landed (it would otherwise carry a stale epoch a future downgrade-then-upgrade could resurrect).

SaveErr is the PUBLIC entry: it acquires mutMu FIRST (2D-A commit-boundary correction), so a standalone save orders against the whole mutation domain and can never observe — let alone publish — the memory state of an in-flight MutateDurable transaction: fn's uncommitted content paired with the not-yet-advanced epoch. Without this, a caller-side Save (the production ReplaceAll+Save bulk shape) racing an admin mutation could persist uncommitted-new-content + old-epoch; if that mutation then failed its own publication and rolled back, the failed, unacknowledged mutation stayed on disk. MutateDurable already holds mutMu and calls saveErrLocked directly — mutMu is not reentrant, so an internal SaveErr call from inside the mutation path would deadlock and must never be added.

func (*Store) SetPathForTest

func (s *Store) SetPathForTest(path string)

SetPathForTest points persistence at path without loading.

func (*Store) SnapshotView added in v1.0.218

func (s *Store) SnapshotView() Snapshot

SnapshotView captures groups + names + version under ONE hold of the read lock. List()/Names()/Version() assembled by a caller are three independent reads — a writer landing between any two hands the client rows from one state paired with the fence version of another, and an edit from that pair passes the ifVersion fence against content the client never saw. Handlers serving the fenced list contract must use this, never the trio.

COMMITTED-SNAPSHOT rule (transactional-read correction): SnapshotView also acquires mutMu FIRST. MutateDurable's fn mutates the store under mu and RELEASES mu before the version bump and the durable publication, and a persist failure rolls everything back to the pre-mutation state at the SAME version — so a snapshot taken inside that window returns mutated rows paired with the UNBUMPED version, and after the rollback a client edit derived from those phantom rows PASSES the ifVersion fence against the restored tree. Holding mutMu makes the snapshot wait until the open transaction reaches success or rollback; it then describes committed truth only. Cold admin read — hot-path accessors never touch mutMu. Lock order: mutMu → mu (the store's established order).

func (*Store) Update

func (s *Store) Update(name string, categories []string) error

Update replaces the categories in an existing group. Returns error if not found.

func (*Store) UpdateByID added in v1.0.86

func (s *Store) UpdateByID(id string, categories []string) error

UpdateByID replaces the categories of the group with the given stable ID. Rename-safe counterpart to Update — the edit lands on the intended group even if its name changed. Returns error if no group carries the id.

func (*Store) Version added in v1.0.218

func (s *Store) Version() int64

Version returns the durable per-store mutation generation (the ifVersion fence value clients echo back on mutations).

type VersionConflictError added in v1.0.218

type VersionConflictError struct {
	Current  int64 // the store generation at the locked moment of the check
	Asserted int64 // the caller's ?ifVersion= assertion
}

VersionConflictError is the optimistic-concurrency failure returned by MutateDurable when the caller's asserted store generation no longer matches: another admin mutated the store since the caller loaded it. The mutation never ran. Mirrors package main's policyVersionConflictError contract.

func (*VersionConflictError) Error added in v1.0.218

func (e *VersionConflictError) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL