data

package
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 21 Imported by: 1 module, 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 data is initiative-api's data layer. Every collection that stores user data goes through Owned, which scopes each read and write by the caller's user ID (docs/coding- conventions.md, "Owner-Scoped Data Access") and pushes filter, sort, projection, and limit into the query ("Push Filtering, Sorting, and Counting to the Query Layer").

Index

Constants

View Source
const (
	MaxNameLen    = 200  // runes: roster, encounter, combatant and character names, theme_id
	MaxNotesLen   = 4000 // runes
	MaxCombatants = 200  // per encounter, removed ones included
	MaxCharacters = 200  // per roster
	MaxConditions = 20   // per combatant
	MaxMapEntries = 32   // health values and external refs per combatant or character
	MaxThemeIDLen = 64
)

Size bounds on stored text and collections. Every write path checks them in the data layer, so no route can store an unbounded document; a request over a bound is a typed 422 (ErrInvalid).

View Source
const (
	ChangePending  = "pending"
	ChangeApproved = "approved"
	ChangeRejected = "rejected"
	// ChangeApproving is an approval's claim: the request is taken but the encounter write has not
	// finished. Views show it as pending. It becomes approved when the write succeeds, goes back to
	// pending if the write fails, and can be resumed by a GM once the claim is older than
	// ClaimTimeout.
	ChangeApproving = "approving"
	// ChangeCancelled marks a pending request whose requester left the session or lost their
	// player role before it was decided.
	ChangeCancelled = "cancelled"
)

Change request statuses.

View Source
const (
	EventCreated           = "encounter.created"
	EventUpdated           = "encounter.updated"
	EventDeleted           = "encounter.deleted"
	EventReleased          = "encounter.released"
	EventStarted           = "encounter.started"
	EventEnded             = "encounter.ended"
	EventReset             = "encounter.reset"
	EventTurn              = "turn.advanced"
	EventCombatantAdded    = "combatant.added"
	EventCombatantUpdated  = "combatant.updated"
	EventCombatantRemoved  = "combatant.removed"
	EventCombatantRestored = "combatant.restored"
	EventControllers       = "controllers.updated"
)

Event types an encounter commit can produce. The default for a write whose caller named none is EventUpdated, which carries no ids, so an unannotated write is safe: subscribers refetch.

View Source
const (
	OriginUser        = "user"
	OriginIntegration = "integration"
	OriginSystem      = "system"
)

Origin kinds.

View Source
const (
	ReasonOwnerDenied      = "owner_denied"
	ReasonOwnerRoleRemoved = "owner_role_removed"
)

Revoke reasons the platform sets (PADR-0039).

View Source
const (
	CollectionRosters        = "rosters"
	CollectionEncounters     = "encounters"
	CollectionThemes         = "themes"
	CollectionGameSystems    = "game_systems"
	CollectionCredentials    = "integration_credentials"
	CollectionCredentialGate = "integration_credential_gate"
	// CollectionCredentialDeletions is the append-only audit of administrator deletions.
	CollectionCredentialDeletions = "integration_credential_deletions"
	CollectionSessions            = "sessions"
	CollectionSessionMembers      = "session_members"
	CollectionSessionInvites      = "session_invites"
	CollectionSessionRequests     = "session_requests"
	CollectionSessionBlocks       = "session_blocks"
	CollectionChangeRequests      = "change_requests"
)

Collection names.

View Source
const (
	KindPC        = "pc"
	KindAdversary = "adversary"
	KindObject    = "object"
)

Character kinds.

View Source
const (
	ScopeRead  = "read"
	ScopeWrite = "write"
)

Credential scopes.

View Source
const (
	OrderHighToLow     = "highToLow"
	OrderLowToHigh     = "lowToHigh"
	OrderPCVsAdversary = "pcVsAdversary"
	OrderPlayerManaged = "playerManaged"
)

Encounter orderings.

View Source
const (
	TieRandom       = "random"
	TieAlphabetical = "alphabetical"
	TieQuery        = "query"
)

Encounter tie breakers.

View Source
const (
	StatusDraft  = "draft"
	StatusActive = "active"
	StatusEnded  = "ended"
)

Encounter statuses.

View Source
const (
	HealthFull   = "full"
	HealthStatus = "status"
	HealthHidden = "hidden"
)

Health visibility values for a combatant.

View Source
const (
	FieldCounter = "counter"
	FieldPool    = "pool"
	FieldFlag    = "flag"
	FieldTrack   = "track"
)

Tracker field kinds.

View Source
const (
	NoticeTurnYours       = "turn.yours"
	NoticeTurnNext        = "turn.next"
	NoticeChangeSubmitted = "change_request.submitted"
	NoticeChangeApproved  = "change_request.approved"
	NoticeChangeRejected  = "change_request.rejected"
)

Notice types: the events addressed to particular users rather than to everyone watching an encounter (initiative-notifications).

View Source
const (
	DefaultLimit = 50
	MaxLimit     = 200
)

List bounds.

View Source
const (
	RoleGM       = "gm"
	RoleCoGM     = "co_gm"
	RolePlayer   = "player"
	RoleObserver = "observer"
)

Session roles.

View Source
const (
	RequestPending  = "pending"
	RequestApproved = "approved"
	RequestRejected = "rejected"
)

Join request states.

View Source
const ClaimTimeout = 60 * time.Second

ClaimTimeout is how long an approving claim is left alone before another approval may resume it.

View Source
const CollectionNotificationPrefs = "notification_preferences"

CollectionNotificationPrefs holds each user's muted notice types per session.

View Source
const CollectionOwnerEntitlements = "owner_entitlements"

CollectionOwnerEntitlements holds the last entitlement values read with each user's own bearer.

View Source
const CollectionStreamLeases = "stream_leases"

CollectionStreamLeases holds one row per open (or just dropped) event stream, so a user's concurrent streams can be counted across pods.

View Source
const CollectionStreamTickets = "stream_tickets"

CollectionStreamTickets holds the one-time tickets that open a WebSocket for a browser, which cannot send an Authorization header on an upgrade.

View Source
const DefaultSystemID = "none"

DefaultSystemID is "No System": the simple tracker every user can use, and the definition an encounter falls back to when its game system has no definition.

View Source
const MaxPendingChangeRequests = 50

MaxPendingChangeRequests bounds one player's open requests in a session, so a client cannot grow the collection without limit while the GM is away.

Variables

View Source
var (
	// ErrNotFound: no live record with that ID is visible to the caller (404).
	ErrNotFound = errors.New("data: not found")
	// ErrForbidden: the record exists but belongs to another owner (403). Reported only after the
	// owner-scoped write has already failed to match.
	ErrForbidden = errors.New("data: record belongs to another owner")
	// ErrNotMember is ErrForbidden for session data: the caller holds no role in the session.
	ErrNotMember = fmt.Errorf("%w: not a member of this session", ErrForbidden)
	// ErrRevisionConflict: the write carried a stale revision (409). The current record is
	// returned alongside it.
	ErrRevisionConflict = errors.New("data: revision conflict")
	// ErrConflict: a unique index rejected the write, for example a theme slot already in use (409).
	ErrConflict = errors.New("data: conflicts with an existing record")
	// ErrInactive: the record is over the owner's current limit and cannot be changed or used; it
	// stays readable and deletable (403).
	ErrInactive = errors.New("data: record is inactive")
	// ErrLocked: the record uses a game system its owner no longer holds the entitlement for. It
	// stays readable and deletable (403, typed entitlement error).
	ErrLocked = errors.New("data: record is locked by a missing entitlement")
	// ErrInvalid: the call itself is malformed (empty owner, reserved field, bad query) (400/422).
	ErrInvalid = errors.New("data: invalid argument")
)

Errors the API layer maps to HTTP statuses.

View Source
var (
	RosterSpec = Spec{
		Name:        CollectionRosters,
		Filterable:  []string{"name", "favorite"},
		Sortable:    []string{"name", "favorite", "created_at", "updated_at"},
		Projectable: []string{"name", "favorite", "characters", "revision", "owner_user_id", "created_at", "updated_at", "created_by", "updated_by"},
		Updatable:   []string{"name", "favorite", "characters"},
		Indexes: []store.IndexSpec{
			{Name: "owner_name", Keys: asc("owner_user_id", "name")},
			{Name: "owner_updated", Keys: bson.D{{Key: "owner_user_id", Value: 1}, {Key: "updated_at", Value: -1}}},
		},
	}

	// EncounterSpec: the launcher lists an owner's encounters by position, optionally by status.
	// Combat state (status, round, current_combatant_id, turn_queue, combatants) is not
	// updatable here: it changes only through the domain functions that apply the tracking rules.
	EncounterSpec = Spec{
		Name:          CollectionEncounters,
		Filterable:    []string{"name", "status", "game_system_id", "position"},
		Sortable:      []string{"name", "status", "position", "created_at", "updated_at"},
		Projectable:   []string{"name", "game_system_id", "ordering", "tie_breaker", "labels", "colorblind", "theme_id", "status", "round", "current_combatant_id", "turn_queue", "position", "combatants", "revision", "owner_user_id", "created_at", "updated_at", "created_by", "updated_by"},
		Updatable:     []string{"name", "game_system_id", "ordering", "tie_breaker", "labels", "colorblind", "theme_id", "position"},
		StateFields:   []string{"status", "round", "current_combatant_id", "turn_queue", "combatants", "ref_keys"},
		UnsetOnDelete: []string{"ref_keys"},
		Indexes: []store.IndexSpec{
			{Name: "session_position", Keys: asc("session_id", "position")},
			{Name: "owner_position", Keys: asc("owner_user_id", "position")},
			{Name: "owner_ref_keys", Keys: asc("owner_user_id", "ref_keys")},
			{Name: "owner_name", Keys: asc("owner_user_id", "name")},
			{Name: "owner_created_at", Keys: asc("owner_user_id", "created_at")},
			{Name: "owner_updated_at", Keys: bson.D{{Key: "owner_user_id", Value: 1}, {Key: "updated_at", Value: -1}}},
			{Name: "owner_status_updated", Keys: bson.D{{Key: "owner_user_id", Value: 1}, {Key: "status", Value: 1}, {Key: "updated_at", Value: -1}}},
		},
	}

	// ThemeSpec: slot numbers are unique per owner among live themes. Soft delete unsets slot, and
	// the partial filter ($exists: true is the supported form) leaves slot-less rows out.
	ThemeSpec = Spec{
		Name:                CollectionThemes,
		Filterable:          []string{"name", "slot"},
		Sortable:            []string{"name", "slot", "created_at", "updated_at"},
		Projectable:         []string{"name", "style", "slot", "main_color", "accent1_color", "accent2_color", "background1_color", "background2_color", "primary_font_name", "secondary_font_name", "background_image", "revision", "owner_user_id", "created_at", "updated_at"},
		Updatable:           []string{"name", "style", "main_color", "accent1_color", "accent2_color", "background1_color", "background2_color", "primary_font_name", "secondary_font_name", "background_image", "slot"},
		UnsetOnDelete:       []string{"slot"},
		ConflictOnDuplicate: true,
		Indexes: []store.IndexSpec{
			{Name: "owner_slot", Keys: asc("owner_user_id", "slot"), Unique: true,
				Partial: bson.D{{Key: "slot", Value: bson.D{{Key: "$exists", Value: true}}}}},
		},
	}

	// CredentialSpec: secret_hash is unique so a presented secret resolves to one credential.
	CredentialSpec = Spec{
		Name:        CollectionCredentials,
		Filterable:  []string{"label"},
		Sortable:    []string{"label", "created_at"},
		Updatable:   []string{"label"},
		Projectable: []string{"label", "scopes", "revoked_at", "last_used_at", "revision", "owner_user_id", "created_at", "updated_at"},
		Indexes: []store.IndexSpec{
			{Name: "owner_created", Keys: bson.D{{Key: "owner_user_id", Value: 1}, {Key: "created_at", Value: -1}}},
			{Name: "secret_hash", Keys: asc("secret_hash"), Unique: true},
		},
	}

	// SessionSpec: a session is owned by its GM, so owner-scoped create and soft delete apply to
	// the GM only. Reads by members go through Sessions.
	SessionSpec = Spec{
		Name:        CollectionSessions,
		Filterable:  []string{"name"},
		Sortable:    []string{"name", "created_at"},
		Projectable: []string{"name", "revision", "owner_user_id", "created_at", "updated_at", "created_by", "updated_by"},
		Updatable:   []string{"name", "allow_co_gm_create_encounter"},
		Indexes:     []store.IndexSpec{{Name: "owner_created", Keys: bson.D{{Key: "owner_user_id", Value: 1}, {Key: "created_at", Value: -1}}}},
	}

	// The membership collections are addressed by session_id, set from a record the caller was
	// already authorized for, never from request input alone.
	SessionMemberSpec = Spec{
		Name: CollectionSessionMembers, Sortable: []string{"created_at"},
		Indexes: []store.IndexSpec{
			{Name: "session_user", Keys: asc("session_id", "user_id"), Unique: true,
				Partial: bson.D{{Key: "live", Value: bson.D{{Key: "$exists", Value: true}}}}},
			{Name: "user", Keys: asc("user_id")},
		},
	}
	SessionInviteSpec = Spec{
		Name: CollectionSessionInvites, Sortable: []string{"created_at"},
		Indexes: []store.IndexSpec{
			{Name: "code_hash", Keys: asc("code_hash"), Unique: true},
			{Name: "session", Keys: asc("session_id")},
		},
	}
	SessionRequestSpec = Spec{
		Name: CollectionSessionRequests, Sortable: []string{"created_at"}, Filterable: []string{"status"},
		Indexes: []store.IndexSpec{{Name: "session_user", Keys: asc("session_id", "user_id"), Unique: true,
			Partial: bson.D{{Key: "live", Value: bson.D{{Key: "$exists", Value: true}}}}}},
	}
	SessionBlockSpec = Spec{
		Name: CollectionSessionBlocks, Sortable: []string{"created_at"},
		Indexes: []store.IndexSpec{{Name: "session_user", Keys: asc("session_id", "user_id"), Unique: true,
			Partial: bson.D{{Key: "live", Value: bson.D{{Key: "$exists", Value: true}}}}}},
	}

	// ChangeRequestSpec: a session encounter's player-submitted changes, listed oldest first and
	// filtered by status.
	ChangeRequestSpec = Spec{
		Name: CollectionChangeRequests, Sortable: []string{"created_at"}, Filterable: []string{"status", "combatant_id"},
		Indexes: []store.IndexSpec{
			{Name: "session_encounter_created", Keys: asc("session_id", "encounter_id", "created_at")},
			{Name: "session_requester_status", Keys: asc("session_id", "requested_by", "status")},
		},
	}

	// SystemSpec: aliases (including Foundry system IDs) are unique across systems.
	// SystemSpec has no Updatable fields: definitions change only through SystemRepo.Upsert.
	SystemSpec = Spec{
		Name:        CollectionGameSystems,
		Filterable:  []string{"family", "gated", "aliases", "name"},
		Sortable:    []string{"name", "family"},
		Projectable: []string{"name", "family", "aliases", "gated", "fields", "revision"},
		Indexes: []store.IndexSpec{
			{Name: "aliases", Keys: asc("aliases"), Unique: true},
			{Name: "family_name", Keys: asc("family", "name")},
		},
	}
)

Specs for each collection. Every owner-scoped index leads with owner_user_id, because every query filters by it.

View Source
var DeletionSpec = Spec{
	Name:     CollectionCredentialDeletions,
	Sortable: []string{"created_at"},
}

DeletionSpec pages the audit entries, newest first.

View Source
var ErrStreamLimit = errors.New("data: too many concurrent streams")

ErrStreamLimit means the user already holds the most concurrent streams allowed.

View Source
var ErrStreamUnavailable = errors.New("data: stream seats are unavailable")

ErrStreamUnavailable means the seat store could not be reached or written, so no seat could be granted. A new connect fails closed on it; streams already open stay up (see Renew).

Kinds lists the valid character and combatant kinds.

NoticeTypes lists every type a user can mute for a session.

View Source
var NotificationPrefSpec = Spec{
	Name:    CollectionNotificationPrefs,
	Indexes: []store.IndexSpec{{Name: "user_session", Keys: asc("user_id", "session_id"), Unique: true}},
}

NotificationPrefSpec: one document per user and session, addressed only by the caller's own id.

Functions

func CheckHealth

func CheckHealth(sys GameSystem, h map[string]int) error

CheckHealth validates h against sys's tracker definition: every key must be a defined field, a flag must be 0 or 1, and each value must be at least the field's Min and at most its Max (or, for MaxRef, the value of the referenced field in h when present). Keys are checked in sorted order so the reported field is stable.

func CheckMaps added in v0.6.0

func CheckMaps(what string, health map[string]int, refs map[string]string) error

CheckMaps bounds the health and external-ref maps of a combatant or character: at most MaxMapEntries entries each, and keys and values no longer than maxRefLen.

func CheckName added in v0.6.0

func CheckName(what, s string) error

CheckName requires a non-empty (after trimming) name of at most MaxNameLen runes.

func CheckText added in v0.6.0

func CheckText(what, s string, max int) error

CheckText requires s to be at most max runes. what names the field in the error.

func EnsureIndexes

func EnsureIndexes(ctx context.Context, db store.Database) error

EnsureIndexes creates every collection's indexes. Safe to run at each startup.

func RefKey

func RefKey(key, value string) string

RefKey is the fixed-shape lookup key for one external reference: the hex SHA-256 of the length-prefixed key and value. Lookups filter on this alone, so request text never becomes part of a query filter.

func ValidClientID added in v0.9.0

func ValidClientID(v string) bool

ValidClientID reports whether v may be recorded as an origin client id. A bad value is ignored, never rejected.

func ValidateEncounter

func ValidateEncounter(e *Encounter) error

ValidateEncounter checks a whole encounter document: ordering, tie breaker, and status come from their constants, and every turn_queue entry names one of the encounter's combatants.

func ValidateState

func ValidateState(st EncounterState) error

ValidateState checks status, a non-negative round, unique combatant IDs, and that the queue and the current combatant refer to combatants of this state.

func ValidateSystem

func ValidateSystem(sys GameSystem) error

ValidateSystem checks a definition is self-consistent: slug IDs and aliases, known field kinds, unique keys, bounds that make sense, and max references that resolve.

func WithGate added in v0.3.0

func WithGate(ctx context.Context, c RelationChecker, token string) context.Context

WithGate puts the checker and the caller's bearer token on ctx for Authorize. Per PADR-0037 the token is the caller's own; there is no service token.

func WithOp added in v0.9.0

func WithOp(ctx context.Context, eventType string, combatantIDs ...string) context.Context

WithOp names the event type the next encounter commit on ctx produces, and the combatants it changed. Domain entry points set it; a commit with none is EventUpdated with no ids.

func WithOrigin added in v0.9.0

func WithOrigin(ctx context.Context, o Origin) context.Context

WithOrigin records who is making the writes on ctx.

Types

type Block added in v0.2.0

type Block struct {
	ID        string    `bson:"_id" json:"-"`
	SessionID string    `bson:"session_id" json:"session_id"`
	UserID    string    `bson:"user_id" json:"user_id"`
	CreatedAt time.Time `bson:"created_at" json:"created_at"`
	CreatedBy string    `bson:"created_by" json:"created_by"`
	// Live is set while the record is not deleted, so unique indexes can ignore deleted ones.
	Live      bool       `bson:"live,omitempty" json:"-"`
	DeletedAt *time.Time `bson:"deleted_at,omitempty" json:"-"`
	DeletedBy *string    `bson:"deleted_by,omitempty" json:"-"`
}

Block keeps a user from rejoining a session.

type Change added in v0.9.0

type Change struct {
	Type  string
	After Encounter
	// Before is the document as it was just before the write, when the write path had it at the
	// revision the write was made against; nil when unknown. A subscriber's view is compared before
	// and after, so a change it cannot see produces no event for it.
	Before      *Encounter
	SessionID   string
	OwnerID     string
	CombatantID []string
	// GMOnly marks a change only GM-level viewers may hear of: a limit or entitlement flag (lock,
	// inactive) changed. It never reaches a player or observer, and never the bus.
	GMOnly bool
	Origin Origin
	At     time.Time
}

Change is one committed encounter write, handed to the Sink right after the commit. After is the stored document as the write left it, so a sink can render it for each subscriber without a read; SessionID is the session the encounter belonged to before the write (it differs from After.SessionID only for a release), so the audience of a release or delete is the session's. OwnerID is the encounter's owner after the write.

type ChangeRequest added in v0.7.0

type ChangeRequest struct {
	ID               string         `bson:"_id" json:"id"`
	SessionID        string         `bson:"session_id" json:"session_id"`
	EncounterID      string         `bson:"encounter_id" json:"encounter_id"`
	CombatantID      string         `bson:"combatant_id" json:"combatant_id"`
	RequestedBy      string         `bson:"requested_by" json:"requested_by"`
	Health           map[string]int `bson:"health,omitempty" json:"health,omitempty"`
	AddConditions    []Condition    `bson:"add_conditions,omitempty" json:"add_conditions,omitempty"`
	RemoveConditions []string       `bson:"remove_conditions,omitempty" json:"remove_conditions,omitempty"`
	Status           string         `bson:"status" json:"status"`
	// BaseRevision is the encounter revision the player saw when submitting.
	BaseRevision int64      `bson:"base_revision" json:"base_revision,omitempty"`
	CreatedAt    time.Time  `bson:"created_at" json:"created_at"`
	DecidedBy    string     `bson:"decided_by,omitempty" json:"decided_by,omitempty"`
	DecidedAt    *time.Time `bson:"decided_at,omitempty" json:"decided_at,omitempty"`
	// Reason is why a rejected request was rejected.
	Reason string `bson:"reason,omitempty" json:"reason,omitempty"`
	// ClaimedAt is when an approval took the request (status approving).
	ClaimedAt *time.Time `bson:"claimed_at,omitempty" json:"-"`
	// AppliedRevision is the encounter revision an approved request produced.
	AppliedRevision int64 `bson:"applied_revision,omitempty" json:"applied_revision,omitempty"`
}

ChangeRequest is a player's proposed change to one combatant's health values or conditions (initiative-player-access). It changes nothing until a GM or co-GM approves it. Health holds the values to set (merged into the combatant's health, like a combatant patch) and is absolute, so applying it twice is harmless. Conditions are a delta by name, applied to the combatant as it is when the request is applied: RemoveConditions drops conditions by name, AddConditions sets (adds, or replaces the rounds of) a condition by name. A condition added by the GM after the request was submitted therefore survives approval.

func (ChangeRequest) MarshalJSON added in v0.7.0

func (r ChangeRequest) MarshalJSON() ([]byte, error)

MarshalJSON shows an approving request as pending: the claim is an internal step of an approval, and until it completes the change has not been applied.

type ChangeRequests added in v0.7.0

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

ChangeRequests is the repository for change requests. Every function takes the Viewer or Decision that proves the caller's standing in the session (PADR-0035) and scopes by it.

func NewChangeRequests added in v0.7.0

func NewChangeRequests(db store.Database) *ChangeRequests

NewChangeRequests builds the repository on db.

func (*ChangeRequests) CancelPending added in v0.7.0

func (r *ChangeRequests) CancelPending(ctx context.Context, d Decision, userID string) error

CancelPending cancels userID's pending and approving requests in the session, for a member who left, was removed, or lost the player role. d grants can_edit, or can_view for one's own leave. The per-player cap bounds the loop.

func (*ChangeRequests) CancelSession added in v0.7.0

func (r *ChangeRequests) CancelSession(ctx context.Context, d Decision) error

CancelSession cancels every request still waiting (pending or approving) in the session, for a session that is being deleted. d must be the GM's. Idempotent; it fails rather than stop silently if more than maxCancelSweeps requests are waiting.

func (*ChangeRequests) Claim added in v0.7.0

func (r *ChangeRequests) Claim(ctx context.Context, d Decision, encounterID, id string) (ChangeRequest, error)

Claim takes a request for approval: pending becomes approving (claimed_at, decided_by), and an approving request whose claim is older than ClaimTimeout is taken over, so an approval that crashed can be resumed. A younger claim, and any decided request, is ErrConflict.

func (*ChangeRequests) Create added in v0.7.0

Create stores req as the viewer's pending request. Only a player Viewer may: an observer has no change requests, and a GM edits directly. The session, requester, status and time are set here.

func (*ChangeRequests) Finish added in v0.7.0

func (r *ChangeRequests) Finish(ctx context.Context, d Decision, encounterID, id string, revision int64) (ChangeRequest, error)

Finish records that the claimed approval's encounter write succeeded at revision: approving becomes approved. It only matches the claim d took; a request taken over since is ErrConflict (the change itself is idempotent, so the takeover's write does no harm).

func (*ChangeRequests) List added in v0.7.0

func (r *ChangeRequests) List(ctx context.Context, v Viewer, encounterID, status string, q Query) (Page[ChangeRequest], error)

List returns one page of the encounter's change requests, oldest first. A GM or co-GM sees all of them; a player only their own; an observer none.

func (*ChangeRequests) Load added in v0.7.0

func (r *ChangeRequests) Load(ctx context.Context, d Decision, encounterID, id string) (ChangeRequest, error)

Load reads one change request of the decision's session and encounter. d must grant can_edit.

func (*ChangeRequests) Reject added in v0.7.0

func (r *ChangeRequests) Reject(ctx context.Context, d Decision, encounterID, id, reason string) (ChangeRequest, error)

Reject settles a pending request as rejected with reason, in one compare-and-set on status, so it cannot win against an approval that has claimed the request. A request in any other state is ErrConflict.

func (*ChangeRequests) Unclaim added in v0.7.0

func (r *ChangeRequests) Unclaim(ctx context.Context, d Decision, encounterID, id string) error

Unclaim puts a request this decision claimed back to pending, for an approval whose encounter write failed.

type Character

type Character struct {
	ID           string            `bson:"id" json:"id"`
	Name         string            `bson:"name" json:"name"`
	Kind         string            `bson:"kind" json:"kind"`
	Notes        string            `bson:"notes" json:"notes"`
	Health       map[string]int    `bson:"health,omitempty" json:"health,omitempty"`
	ExternalRefs map[string]string `bson:"external_refs,omitempty" json:"external_refs,omitempty"`
}

Character is a reusable entry in a roster. Health holds default values keyed by the field keys of the game system's tracker definition.

type Combatant

type Combatant struct {
	ID                string            `bson:"id" json:"id"`
	Name              string            `bson:"name" json:"name"`
	Kind              string            `bson:"kind" json:"kind"`
	Initiative        *float64          `bson:"initiative,omitempty" json:"initiative,omitempty"`
	Health            map[string]int    `bson:"health,omitempty" json:"health,omitempty"`
	Conditions        []Condition       `bson:"conditions" json:"conditions"`
	Notes             string            `bson:"notes" json:"notes"`
	Removed           bool              `bson:"removed" json:"removed"`
	SourceCharacterID string            `bson:"source_character_id,omitempty" json:"source_character_id,omitempty"`
	ExternalRefs      map[string]string `bson:"external_refs,omitempty" json:"external_refs,omitempty"`
	// ControllerUserIDs are the session members who control this combatant (initiative-player-access).
	ControllerUserIDs []string `bson:"controller_user_ids,omitempty" json:"controller_user_ids,omitempty"`
	// Hidden keeps the combatant out of every non-GM view.
	Hidden bool `bson:"hidden,omitempty" json:"hidden,omitempty"`
	// HealthVisibility is how non-GM members see health: full, status, or hidden. Empty means
	// hidden, so a combatant is never exposed by omission.
	HealthVisibility string `bson:"health_visibility,omitempty" json:"health_visibility,omitempty"`
	// NotesShared lets non-GM members read Notes. Empty and false mean GM-only.
	NotesShared bool `bson:"notes_shared,omitempty" json:"notes_shared,omitempty"`
}

Combatant is an entry in an encounter, embedded in it. Initiative is nil until set. Health holds current values keyed by the field keys of the encounter's game system definition. Removed combatants stay in the document so they can be restored.

type Condition

type Condition struct {
	Name            string `bson:"name" json:"name"`
	RoundsRemaining *int   `bson:"rounds_remaining,omitempty" json:"rounds_remaining,omitempty"`
}

Condition is a named effect on a combatant. RoundsRemaining is nil for an open-ended condition.

type CredentialDeletion added in v0.2.0

type CredentialDeletion struct {
	CredentialID string    `bson:"_id" json:"credential_id"`
	OwnerUserID  string    `bson:"owner_user_id" json:"owner_user_id"`
	Label        string    `bson:"label" json:"label"`
	Scopes       []string  `bson:"scopes" json:"scopes"`
	Reason       string    `bson:"reason" json:"reason"`
	CreatedBy    string    `bson:"created_by" json:"deleted_by"`
	CreatedAt    time.Time `bson:"created_at" json:"deleted_at"`
}

CredentialDeletion is the append-only record of an administrator's permanent deletion of an integration credential. Its _id is the deleted credential's id, so a retried deletion cannot write a second entry. Nothing in the service updates or removes these (PADR-0027).

type Credentials

type Credentials struct {
	*Owned[IntegrationCredential, *IntegrationCredential]
	// contains filtered or unexported fields
}

Credentials is the repository for integration credentials: the owner-scoped operations come from Owned, plus the state changes (revoke, use) and the one lookup that is not owner-scoped.

func NewCredentials

func NewCredentials(db store.Database) *Credentials

NewCredentials builds the credential repository for db.

func (*Credentials) Authenticate

func (r *Credentials) Authenticate(ctx context.Context, secretHash string) (IntegrationCredential, error)

Authenticate resolves a presented secret's hash to its live, unrevoked credential and stamps last_used_at in the same write, so a revocation is seen by the very next request. This is the one lookup that is not owner-scoped: the secret is what identifies the owner. secretHash must be the hash the service computed, never a client-supplied value.

func (*Credentials) CountActive

func (r *Credentials) CountActive(ctx context.Context, owner string) (int64, error)

CountActive counts owner's credentials that can still authenticate.

func (*Credentials) DeletePermanently added in v0.2.0

func (r *Credentials) DeletePermanently(ctx context.Context, actor, id, reason string) (CredentialDeletion, error)

DeletePermanently removes any owner's credential and records who did it and why. The audit entry is written first, so a failure after it leaves the credential in place and a retry completes the deletion without a second entry. Returns the entry.

func (*Credentials) Deletions added in v0.2.0

func (r *Credentials) Deletions(ctx context.Context, owner string, q Query) (Page[CredentialDeletion], error)

Deletions returns one page of audit entries, newest first; a non-empty NextCursor means more. owner narrows it to one owner's deleted credentials.

func (*Credentials) GateClosed

func (r *Credentials) GateClosed(ctx context.Context) (bool, error)

GateClosed reports whether the persisted gate is closed. No document means open.

func (*Credentials) ItemStates

func (r *Credentials) ItemStates(ctx context.Context, owner string) ([]ItemState, error)

ItemStates lists owner's unrevoked credentials; a revoked one no longer counts toward the limit.

func (*Credentials) ListAll added in v0.2.0

ListAll returns one page of credentials across owners, newest first. Administrator use only: callers gate it on the admin role. Its filter has no request input; one owner's credentials go through the owner-scoped List instead.

func (*Credentials) ListOwned added in v0.2.0

func (r *Credentials) ListOwned(ctx context.Context, owner string, q Query) (Page[IntegrationCredential], error)

ListOwned is the owner-scoped List for an owner id taken from an administrator's request.

func (*Credentials) Live added in v0.2.0

func (r *Credentials) Live(ctx context.Context, id string) (bool, error)

Live reports whether the credential can still authenticate: present, unrevoked, not over the owner's limit. Open streams re-check it so a revoke or deletion ends them.

func (*Credentials) Revoke

func (r *Credentials) Revoke(ctx context.Context, owner, actor, id string) (IntegrationCredential, error)

Revoke ends owner's credential at once. Revoking an already revoked credential succeeds and returns it unchanged. Another owner's credential is ErrForbidden, an unknown one ErrNotFound.

func (*Credentials) RevokeAllByOwner

func (r *Credentials) RevokeAllByOwner(ctx context.Context, owner, reason string) (int, error)

RevokeAllByOwner ends every active credential of owner, recording reason, and returns how many it ended. Each pass takes one credential, so a retry after a failure finishes the rest. This is the auth-event path, so it sets updated_by to the reason rather than a user.

func (*Credentials) SetGate

func (r *Credentials) SetGate(ctx context.Context, closed bool, actor string) error

SetGate persists the gate state so a restart cannot reopen it before a reconcile.

type Decision added in v0.3.0

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

Decision is a granted authorization for one user on one session (PADR-0035). Every session data function takes one and has no unchecked form: the only way to get a granted Decision is Authorize, which asks auth-api (OpenFGA) with the caller's own bearer token. The zero value grants nothing.

func Authorize added in v0.3.0

func Authorize(ctx context.Context, actor, sessionID, relation string) (Decision, error)

Authorize asks whether actor holds relation on the session. A malformed session id is ErrNotFound; a denial is ErrForbidden and carries no session data. When no decision can be obtained (no gate on ctx, auth-api or OpenFGA down) the error is relations.ErrUnavailable, or relations.ErrUnauthorized for a rejected token: session data fails closed.

func (Decision) Actor added in v0.3.0

func (d Decision) Actor() string

Actor returns the user the decision was made for.

func (Decision) SessionID added in v0.3.0

func (d Decision) SessionID() string

SessionID returns the session the decision covers.

type DeviceLimitError added in v0.15.0

type DeviceLimitError struct{ Limit int }

DeviceLimitError means one member already holds the most concurrent connections to a session.

func (*DeviceLimitError) Error added in v0.15.0

func (e *DeviceLimitError) Error() string

type Doc

type Doc[T any] interface {
	*T
	GetMeta() *Meta
}

Doc constrains P to a pointer to a document type that embeds Meta.

type Encounter

type Encounter struct {
	Meta         `bson:",inline"`
	Name         string `bson:"name" json:"name"`
	GameSystemID string `bson:"game_system_id" json:"game_system_id"`
	Ordering     string `bson:"ordering" json:"ordering"`
	TieBreaker   string `bson:"tie_breaker" json:"tie_breaker"`
	Labels       bool   `bson:"labels" json:"labels"`
	Colorblind   bool   `bson:"colorblind" json:"colorblind"`
	ThemeID      string `bson:"theme_id,omitempty" json:"theme_id,omitempty"`
	// SessionID is the session the encounter belongs to; empty is a private encounter of its owner.
	SessionID          string      `bson:"session_id,omitempty" json:"session_id,omitempty"`
	Status             string      `bson:"status" json:"status"`
	Round              int         `bson:"round" json:"round"`
	CurrentCombatantID string      `bson:"current_combatant_id,omitempty" json:"current_combatant_id,omitempty"`
	TurnQueue          []string    `bson:"turn_queue" json:"turn_queue"`
	Position           int         `bson:"position" json:"position"`
	Combatants         []Combatant `bson:"combatants" json:"combatants"`
	// RefKeys is derived from Combatants on every write (see RefKey); it only serves the
	// external_refs lookup and is never returned.
	RefKeys []string `bson:"ref_keys,omitempty" json:"-"`
}

Encounter is one revisioned document holding settings, live combat state, and its combatants (PADR-0033): no separate combat-state record, so every change is one atomic write. TurnQueue holds combatant IDs in turn order and is computed by the server. Position is the owner's launcher display order. Soft-deleted (PADR-0027: user-owned domain data).

An encounter with a SessionID is read by members only through the role-aware view builder (domain.EncounterView) with a data.Viewer from the PADR-0035 access path; the document itself is never serialized to a non-owner.

type EncounterState

type EncounterState struct {
	Status             string
	Round              int
	CurrentCombatantID string
	TurnQueue          []string
	Combatants         []Combatant
}

EncounterState is the live combat state of an encounter, written as one unit.

type Encounters

type Encounters struct {
	*Owned[Encounter, *Encounter]
	// contains filtered or unexported fields
}

Encounters is the owner-scoped encounter repository. It validates enumerated values and queue references before any write reaches the collection.

func NewEncounters

func NewEncounters(db store.Database) *Encounters

NewEncounters builds the encounter repository for db.

func (*Encounters) CountAll added in v0.8.0

func (r *Encounters) CountAll(ctx context.Context, owner string) (int64, error)

CountAll returns how many live encounters owner holds, private and in a session alike. Both count against the saved-encounters limit.

func (*Encounters) Create

func (r *Encounters) Create(ctx context.Context, ownerUserID, actingUserID string, e *Encounter) error

Create resets e's combat state to a fresh draft, validates it, then stores it as owner's new encounter. Callers cannot create an encounter that is already running.

func (*Encounters) FindByExternalRef

func (r *Encounters) FindByExternalRef(ctx context.Context, owner, key, value string) ([]RefMatch, error)

FindByExternalRef returns owner's live combatants in private encounters whose external_refs map key to value. The database matches on the derived RefKey; the stored values are then compared exactly, so a hash collision cannot return a wrong combatant.

func (*Encounters) ListForViewer added in v0.6.0

func (r *Encounters) ListForViewer(ctx context.Context, v Viewer, limit int64) ([]Encounter, error)

ListForViewer reads the viewer's session's encounters in display order, at most limit (the store default when zero).

func (*Encounters) ListOwnedViews added in v0.6.0

func (r *Encounters) ListOwnedViews(ctx context.Context, owner string, q Query) (Page[Encounter], Viewer, error)

ListOwnedViews returns one page of owner's private encounters (those with no session) and the viewer to render them with. Filtering on session_id happens in the query, so pages are full and the cursor is stable; session encounters are read through the session.

func (*Encounters) Load

func (r *Encounters) Load(ctx context.Context, owner, id string) (Encounter, error)

Load reads owner's encounter; a miss is classified 403 (another owner's) or 404 (absent).

func (*Encounters) LoadForViewer added in v0.6.0

func (r *Encounters) LoadForViewer(ctx context.Context, v Viewer, id string) (Encounter, error)

LoadForViewer reads one encounter of the viewer's session. A zero viewer, or an encounter in another session, is not found: the answer never distinguishes the two.

func (*Encounters) LoadOwnedView added in v0.6.0

func (r *Encounters) LoadOwnedView(ctx context.Context, owner, id string) (Encounter, Viewer, error)

LoadOwnedView reads the owner's private encounter with the viewer to render it with. An encounter that belongs to a session is not served this way: its owner reaches it through the session like any other GM (AuthorizeView), so a removed GM keeps no side door.

func (*Encounters) LockGated

func (r *Encounters) LockGated(ctx context.Context, owner string) (int, error)

LockGated locks owner's encounters that use a game system other than No System, and returns how many it locked. A locked encounter keeps all its data; only writes stop (spec initiative-game-systems, "Losing the entitlement locks gated-system items"). Each pass takes one encounter, so a retry after a failure finishes the rest.

func (*Encounters) OwnedViewer added in v0.6.0

func (r *Encounters) OwnedViewer(owner string, e Encounter) (Viewer, error)

OwnedViewer returns the viewer for rendering e, an encounter the caller has just read or written on the owner path. It refuses an encounter that is not the owner's or that belongs to a session, so an owner viewer is never issued for data the owner path may not show.

func (*Encounters) ReleaseSession added in v0.7.0

func (r *Encounters) ReleaseSession(ctx context.Context, d Decision) error

ReleaseSession turns every encounter of the session into a private encounter of its GM (the session's owner, d.actor, including encounters a co-GM created): session_id and every combatant's controller_user_ids are cleared, the revision advances, and owner_user_id becomes the GM (initiative-sessions, "Session deletion"). d must be the GM's. It reads a page at a time by _id until none is left, and an encounter that changed under it is re-read, so no encounter is skipped; running it again after a partial failure finishes the rest (a released encounter no longer matches). Position and ref_keys are kept. The GM's saved-encounter limit reconciles afterwards like any other count change.

func (*Encounters) RequireSystem added in v0.6.0

func (r *Encounters) RequireSystem(ctx context.Context, sysID string) error

RequireSystem rejects a game system that has no definition.

func (*Encounters) RetractNew added in v0.8.0

func (r *Encounters) RetractNew(ctx context.Context, d Decision, id string) error

RetractNew soft-deletes an encounter just created in the session, for a create that turned out to be over the owner's limit. d must grant can_edit; only a live encounter of that session matches. An encounter that is already gone (deleted by someone else since) is not live, so there is nothing to retract and that is not an error.

func (*Encounters) ScrubController added in v0.7.0

func (r *Encounters) ScrubController(ctx context.Context, d Decision, userID string) error

ScrubController removes userID from every combatant's controller_user_ids in the session's encounters. It keeps a user who left, was removed, blocked, or demoted from regaining control of a combatant by rejoining or being promoted, and keeps the GM's view free of stale ids. d grants can_edit, or can_view when the user is scrubbing their own leave. Only encounters that list the user are read, a page at a time by _id until none is left, so no encounter is skipped; if the session has more than maxScrubPages pages the scrub fails rather than stop silently. Each changed encounter is written under its revision (the revision advances, so clients re-read) and re-read up to maxScrubRetries times if it changed under the scrub. Idempotent.

func (*Encounters) SetSink added in v0.9.0

func (r *Encounters) SetSink(s Sink)

SetSink installs the sink for every encounter commit made through r. It is set once at startup; with none, commits emit nothing.

func (*Encounters) SetState

func (r *Encounters) SetState(ctx context.Context, ownerUserID, actingUserID, id string, expectedRevision int64, st EncounterState) (Encounter, error)

SetState validates st and writes it as the encounter's combat state with the revision check.

func (*Encounters) UnlockAll

func (r *Encounters) UnlockAll(ctx context.Context, owner string) (int, error)

UnlockAll restores owner's locked encounters exactly as they were.

func (*Encounters) Update

func (r *Encounters) Update(ctx context.Context, ownerUserID, actingUserID, id string, expectedRevision int64, set map[string]any) (Encounter, error)

Update validates the enumerated values in set, then applies it with the revision check. A change of game system also checks every combatant's health against the new system.

func (*Encounters) UpdateInSession added in v0.7.0

func (r *Encounters) UpdateInSession(ctx context.Context, d Decision, id string, expectedRevision int64, set map[string]any) (Encounter, error)

UpdateInSession writes set to the session's encounter id if its revision is still expectedRevision, bumping the revision and stamping updated_*. d must grant can_edit (a GM or co-GM); the match is one atomic write on {_id, session_id, revision}, so another session's encounter, a private one, and a stale revision all modify nothing. Failures are classified like Owned.Update: ErrNotFound, ErrLocked, ErrInactive, or ErrRevisionConflict (with the current record returned).

Only "combatants" may be set today: it is the field session edits (controller assignment, approved change requests) change. Each combatant is validated and ref_keys is recomputed.

func (*Encounters) ValidateCombatantChange added in v0.7.0

func (r *Encounters) ValidateCombatantChange(ctx context.Context, gameSystemID string, before, after Combatant) error

ValidateCombatantChange checks after, a combatant as it would be once an edit applies to before (the combatant as stored), against the rules a write enforces: its own fields, and the health keys the edit changed against the game system's definition (the default system when the encounter's has none). A stored value that a later definition change made invalid, in a key the edit does not touch, does not block the edit; an edit that leaves health alone checks none.

func (*Encounters) Write

func (r *Encounters) Write(ctx context.Context, ownerUserID, actingUserID, id string, expectedRevision int64, settings map[string]any, st EncounterState) (Encounter, error)

Write validates settings (Updatable fields) and st (structure, and combatant health against the encounter's game system), then writes both in one atomic write with the revision check. Use it when a setting change, such as the ordering, comes with recomputed state.

type Filter

type Filter struct {
	Field  string
	Op     Op
	Values []any
}

Filter restricts a list to records whose Field matches. eq takes one value, in takes up to maxInValues, contains takes one non-empty string and matches case-insensitively as a literal.

type GameSystem

type GameSystem struct {
	ID               string         `bson:"_id" json:"id"`
	Name             string         `bson:"name" json:"name"`
	Family           string         `bson:"family" json:"family"`
	Aliases          []string       `bson:"aliases" json:"aliases"`
	Gated            bool           `bson:"gated" json:"gated"`
	Fields           []TrackerField `bson:"fields" json:"fields"`
	DefinitionHash   string         `bson:"definition_hash" json:"-"`
	Revision         int64          `bson:"revision" json:"revision"`
	models.Auditable `bson:",inline"`
}

GameSystem is API data, shared by all users (no owner). It is written only by the seed loader, as the system actor. ID is a stable slug. DefinitionHash lets the loader skip unchanged definitions.

type HealthError

type HealthError struct {
	Field  string
	Reason string
	// Unknown is set when the game system defines no such field, as opposed to a value out of bounds.
	Unknown bool
}

HealthError reports the health field that failed validation. It wraps ErrInvalid.

func (*HealthError) Error

func (e *HealthError) Error() string

func (*HealthError) Unwrap

func (e *HealthError) Unwrap() error

Unwrap lets errors.Is match ErrInvalid.

type IntegrationCredential

type IntegrationCredential struct {
	Meta       `bson:",inline"`
	Label      string     `bson:"label" json:"label"`
	Scopes     []string   `bson:"scopes" json:"scopes"`
	SecretHash string     `bson:"secret_hash" json:"-"`
	LastUsedAt *time.Time `bson:"last_used_at,omitempty" json:"last_used_at,omitempty"`
	RevokedAt  *time.Time `bson:"revoked_at,omitempty" json:"revoked_at,omitempty"`
	// RevokeReason is set when the platform, not the owner, ended the credential (PADR-0039).
	RevokeReason string `bson:"revoke_reason,omitempty" json:"revoke_reason,omitempty"`
}

IntegrationCredential authenticates an external integration as its owner. Only the hash of the secret is stored; it never appears in a response. Revocation is a state change, not a delete.

type Invite added in v0.2.0

type Invite struct {
	ID        string     `bson:"_id" json:"id"`
	SessionID string     `bson:"session_id" json:"session_id"`
	CodeHash  string     `bson:"code_hash" json:"-"`
	ExpiresAt time.Time  `bson:"expires_at" json:"expires_at"`
	RevokedAt *time.Time `bson:"revoked_at,omitempty" json:"revoked_at,omitempty"`
	RevokedBy string     `bson:"revoked_by,omitempty" json:"revoked_by,omitempty"`
	CreatedAt time.Time  `bson:"created_at" json:"created_at"`
	CreatedBy string     `bson:"created_by" json:"created_by"`
	// Live is set while the record is not deleted, so unique indexes can ignore deleted ones.
	Live      bool       `bson:"live,omitempty" json:"-"`
	DeletedAt *time.Time `bson:"deleted_at,omitempty" json:"-"`
	DeletedBy *string    `bson:"deleted_by,omitempty" json:"-"`
}

Invite is a join code. Only its hash is stored, so the code is shown once, at creation.

type ItemState

type ItemState struct {
	ID        string
	CreatedAt time.Time
	KeepRank  int
	Inactive  bool
}

ItemState is what limit enforcement needs to know about one stored item.

type JoinRequest added in v0.2.0

type JoinRequest struct {
	ID        string     `bson:"_id" json:"id"`
	SessionID string     `bson:"session_id" json:"session_id"`
	UserID    string     `bson:"user_id" json:"user_id"`
	Status    string     `bson:"status" json:"status"`
	Role      string     `bson:"role,omitempty" json:"role,omitempty"`
	Reason    string     `bson:"reason,omitempty" json:"reason,omitempty"`
	DecidedBy string     `bson:"decided_by,omitempty" json:"decided_by,omitempty"`
	DecidedAt *time.Time `bson:"decided_at,omitempty" json:"decided_at,omitempty"`
	CreatedAt time.Time  `bson:"created_at" json:"created_at"`
	// Live is set while the record is not deleted, so unique indexes can ignore deleted ones.
	Live      bool       `bson:"live,omitempty" json:"-"`
	DeletedAt *time.Time `bson:"deleted_at,omitempty" json:"-"`
	DeletedBy *string    `bson:"deleted_by,omitempty" json:"-"`
}

JoinRequest is a user's pending, approved, or rejected request to join.

type JoinState added in v0.3.0

type JoinState struct {
	Exists, Active, Blocked, Member bool
}

JoinState is what a presented invite lets its holder learn: whether the session still exists and whether they are blocked or already a member. It carries no session data.

type JoinTicket added in v0.3.0

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

JoinTicket is an invite the data layer has resolved and validated (known, live, not revoked, not expired) for one user. It is the gate for joining (initiative-sessions, "Join by code") and can only come from ResolveInvite, so the join calls cannot be aimed at an arbitrary session. The zero value is refused.

type LimitItems added in v0.3.0

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

LimitItems is the part of the owner-scoped repository the limit reconciler needs: which sessions an owner has and which are inactive. It reads no session content.

func (LimitItems) ItemStates added in v0.3.0

func (l LimitItems) ItemStates(ctx context.Context, owner string) ([]ItemState, error)

ItemStates lists owner's sessions with their activity state.

func (LimitItems) SetInactive added in v0.3.0

func (l LimitItems) SetInactive(ctx context.Context, owner, id string, inactive bool) error

SetInactive sets or clears a session's inactive mark.

func (LimitItems) SetKeepRanks added in v0.3.0

func (l LimitItems) SetKeepRanks(ctx context.Context, owner string, ids []string) error

SetKeepRanks records the owner's keep order.

type Member added in v0.2.0

type Member struct {
	ID        string    `bson:"_id" json:"-"`
	SessionID string    `bson:"session_id" json:"session_id"`
	UserID    string    `bson:"user_id" json:"user_id"`
	Role      string    `bson:"role" json:"role"`
	CreatedAt time.Time `bson:"created_at" json:"joined_at"`
	CreatedBy string    `bson:"created_by" json:"-"`
	// Live is set while the record is not deleted, so unique indexes can ignore deleted ones.
	Live      bool       `bson:"live,omitempty" json:"-"`
	DeletedAt *time.Time `bson:"deleted_at,omitempty" json:"-"`
	DeletedBy *string    `bson:"deleted_by,omitempty" json:"-"`
}

Member is one user's place in a session. This collection is the source of truth for who holds which role (initiative-session-authorization).

type Meta

type Meta struct {
	ID          string `bson:"_id" json:"id"`
	OwnerUserID string `bson:"owner_user_id" json:"owner_user_id"`
	// Revision starts at 1 and advances on every update; writes compare-and-set on it.
	Revision int64 `bson:"revision" json:"revision"`
	// InactiveAt is set while the record is over the owner's limit: readable and deletable, not
	// usable. KeepRank is the owner's choice order (1 first); zero means no choice was made.
	InactiveAt *time.Time `bson:"inactive_at,omitempty" json:"inactive_at,omitempty"`
	KeepRank   int        `bson:"keep_rank,omitempty" json:"-"`
	// LockedAt is set while the record uses a gated game system its owner is not entitled to.
	LockedAt         *time.Time `bson:"locked_at,omitempty" json:"locked_at,omitempty"`
	models.Auditable `bson:",inline"`
}

Meta is embedded (inline) in every owner-scoped document: identity, owner, revision, and the platform audit fields (PADR-0001).

func (*Meta) GetMeta

func (m *Meta) GetMeta() *Meta

GetMeta lets generic code reach the embedded Meta through the document pointer.

type Notice added in v0.13.0

type Notice struct {
	Type        string
	SessionID   string
	EncounterID string
	Users       []string
	Data        map[string]any
	At          time.Time
}

Notice is one event addressed to Users within a session. Data carries only what any addressee may see: ids and names the addressee already controls or manages, never a revision, view tag, or GM-only field.

type NotificationPrefs added in v0.13.0

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

NotificationPrefs stores which notice types a user has turned off for a session. Every read and write is filtered by the owning user's id (docs/coding-conventions.md, owner-scoped data access); there is no function that reaches another user's preferences. Whether the user belongs to the session is the caller's check.

A document is never deleted: it is at most one short list per session a user has joined, a deleted session is only soft-deleted (PADR-0027), and keeping the list means a member who is removed and later rejoins keeps their mutes. The event path only reads it for current members.

func NewNotificationPrefs added in v0.13.0

func NewNotificationPrefs(db store.Database) *NotificationPrefs

NewNotificationPrefs builds the repository on db.

func (*NotificationPrefs) Muted added in v0.13.0

func (r *NotificationPrefs) Muted(ctx context.Context, ownerUserID, sessionID string) ([]string, error)

Muted returns the notice types ownerUserID has turned off for sessionID; none when nothing is stored.

func (*NotificationPrefs) SetMuted added in v0.13.0

func (r *NotificationPrefs) SetMuted(ctx context.Context, ownerUserID, sessionID string, muted []string) ([]string, error)

SetMuted replaces ownerUserID's muted types for sessionID in one atomic upsert. Unknown types are rejected; duplicates collapse.

type Notifier added in v0.13.0

type Notifier interface {
	Notify(ctx context.Context, n Notice)
}

Notifier receives addressed events. Notify must not block.

type Op

type Op string

Op is a filter operator. Clients choose from this closed set; a client string never becomes an operator key or a live regular expression (PADR-0030).

const (
	OpEq       Op = "eq"
	OpIn       Op = "in"
	OpContains Op = "contains"
)

Filter operators.

type Origin added in v0.9.0

type Origin struct {
	Kind     string // user, integration, or system
	ClientID string
	ActorID  string
}

Origin says who made a change, so a client can recognise the echo of its own write. The actor is the originating user (never serialized); ClientID is the opaque value the client sent in X-Initiative-Client-Id, already validated.

type Outcome

type Outcome string

Outcome is what Upsert did with a definition.

const (
	Created   Outcome = "created"
	Updated   Outcome = "updated"
	Unchanged Outcome = "unchanged"
)

Upsert outcomes.

type Owned

type Owned[T any, P Doc[T]] struct {
	// contains filtered or unexported fields
}

Owned is the owner-scoped repository for one collection of user-owned documents. Every method requires the owner's user ID and folds it, plus the soft-delete filter, into the query itself. There is deliberately no method that reads or writes by ID alone.

func NewOwned

func NewOwned[T any, P Doc[T]](db store.Database, spec Spec) *Owned[T, P]

NewOwned builds the repository for spec's collection in db.

func (*Owned[T, P]) Count

func (r *Owned[T, P]) Count(ctx context.Context, ownerUserID string, filters []Filter) (int64, error)

Count returns how many of owner's live records match filters, counted by the database. For encounters that is the private ones only: an encounter in a session counts against the session's limits, not the owner's saved-encounter limit.

func (*Owned[T, P]) Create

func (r *Owned[T, P]) Create(ctx context.Context, ownerUserID, actingUserID string, doc P) error

Create stores doc as owner's new record: it assigns the ID, owner, revision 1, and the audit stamp (created_by and updated_by are actor). Any ID or owner already on doc is overwritten.

func (*Owned[T, P]) Get

func (r *Owned[T, P]) Get(ctx context.Context, ownerUserID, id string) (T, error)

Get returns owner's live record. Another owner's record is indistinguishable from a missing one on reads.

func (*Owned[T, P]) ItemStates

func (r *Owned[T, P]) ItemStates(ctx context.Context, owner string) ([]ItemState, error)

ItemStates lists owner's live items oldest first, for deciding which stay active.

func (*Owned[T, P]) List

func (r *Owned[T, P]) List(ctx context.Context, ownerUserID string, q Query) (Page[T], error)

List returns one page of owner's live records.

func (*Owned[T, P]) Missing

func (r *Owned[T, P]) Missing(ctx context.Context, owner, id string) error

Missing explains why owner's scoped read of id found nothing: ErrNotFound when no live record exists, ErrForbidden when it belongs to another owner. Call it only after a scoped read or write has already failed; it never grants access. It returns nil if the record is visible to owner.

func (*Owned[T, P]) SetInactive

func (r *Owned[T, P]) SetInactive(ctx context.Context, owner, id string, inactive bool) error

SetInactive marks owner's item inactive or active. It changes neither the revision nor the audit stamp: the owner did not edit the item.

func (*Owned[T, P]) SetKeepRanks

func (r *Owned[T, P]) SetKeepRanks(ctx context.Context, owner string, ids []string) error

SetKeepRanks records the owner's choice: ids get ranks 1..n in order, every other item loses its rank. Items already in that state are not written.

func (*Owned[T, P]) SoftDelete

func (r *Owned[T, P]) SoftDelete(ctx context.Context, ownerUserID, actingUserID, id string, expectedRevision int64) error

SoftDelete tombstones owner's record if its revision is still expectedRevision (deleted_at/ deleted_by, plus the spec's UnsetOnDelete fields), per PADR-0027 for user-owned domain data. Failures are classified like Update's, including ErrRevisionConflict.

func (*Owned[T, P]) Update

func (r *Owned[T, P]) Update(ctx context.Context, ownerUserID, actingUserID, id string, expectedRevision int64, set map[string]any) (T, error)

Update sets fields on owner's record if its revision is still expectedRevision, bumping the revision and stamping updated_*. The match is one atomic write on {_id, owner, live, revision}, so a stale revision or another owner's record modifies nothing. When nothing matched, the cause is classified afterwards: ErrNotFound, ErrForbidden, or ErrRevisionConflict (with the current record returned).

Update applies set as given and checks nothing about its values. Size and name bounds on a roster's characters live in the domain layer (domain.Rosters), so a caller that reaches this method directly bypasses them; go through the domain.

type OwnerEntitlement added in v0.6.0

type OwnerEntitlement struct {
	Key    string    `bson:"key"`
	Type   string    `bson:"type"`
	Limit  int       `bson:"limit"`
	Flag   bool      `bson:"flag"`
	ReadAt time.Time `bson:"read_at"`
}

OwnerEntitlement is one recorded key: a limit or a flag, and when it was read.

type OwnerEntitlements added in v0.6.0

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

OwnerEntitlements records a user's entitlement values so a request that cannot read them (an integration credential carries no user bearer, PADR-0034/0037) can still enforce the owner's limits. The record is written only by first-party requests that just read the values with the user's own token, and read back for that same user: one document per user, addressed by the caller's own ID, never by a client-supplied record ID.

func NewOwnerEntitlements added in v0.6.0

func NewOwnerEntitlements(db store.Database, maxAge time.Duration) *OwnerEntitlements

NewOwnerEntitlements builds the repository on db. A recorded value older than maxAge is no longer fresh (see Fresh).

func (*OwnerEntitlements) Fresh added in v0.6.0

Fresh reports whether e was read no longer than the configured max age ago.

func (*OwnerEntitlements) Get added in v0.6.0

func (r *OwnerEntitlements) Get(ctx context.Context, userID, key string) (OwnerEntitlement, error)

Get returns the recorded value of key for userID, or ErrNotFound when the user has no record or the record lacks that key. It does not judge age; see Fresh.

func (*OwnerEntitlements) Record added in v0.6.0

func (r *OwnerEntitlements) Record(ctx context.Context, userID string, entries ...OwnerEntitlement) error

Record upserts each entry under its own field (entries.<key>) with a single atomic write, so concurrent recorders of different keys never revert one another.

type Page

type Page[T any] struct {
	Items      []T
	NextCursor string
}

Page is one page of results; NextCursor is empty on the last page.

type Query

type Query struct {
	Filters []Filter
	Sort    []SortKey
	Fields  []string
	Limit   int
	Cursor  string
}

Query is the query-layer shape of a list call: everything here is applied by the database. Limit 0 means DefaultLimit; larger than MaxLimit is clamped. Fields is an optional projection (empty returns whole documents). Cursor is the opaque NextCursor of the previous page.

type RefMatch

type RefMatch struct {
	EncounterID string    `json:"encounter_id"`
	Combatant   Combatant `json:"combatant"`
}

RefMatch is a combatant whose external_refs hold a looked-up pair, with its encounter's ID.

type RelationChecker added in v0.3.0

type RelationChecker interface {
	Check(ctx context.Context, user, token, object, relation string) (bool, error)
}

RelationChecker answers whether the holder of token has relation on object. *relations.Client implements it.

type Roster

type Roster struct {
	Meta       `bson:",inline"`
	Name       string      `bson:"name" json:"name"`
	Favorite   bool        `bson:"favorite" json:"favorite"`
	Characters []Character `bson:"characters" json:"characters"`
}

Roster is a reusable cast. Characters are embedded: a roster is one document and one write. Soft-deleted (PADR-0027: user-owned domain data).

type Session added in v0.2.0

type Session struct {
	Meta `bson:",inline"`
	Name string `bson:"name" json:"name"`
	// OwnerLimits holds the owner's entitled values for the session-related keys as last read with
	// the owner's own token, and OwnerLimitsAt when. Members' checks use these because a member's
	// token cannot read the owner's entitlements (initiative-entitlement-gating).
	OwnerLimits   map[string]int `bson:"owner_limits,omitempty" json:"-"`
	OwnerLimitsAt *time.Time     `bson:"owner_limits_at,omitempty" json:"-"`
	// OwnerFlags holds the owner's entitled flags (the game-systems flag) as read at OwnerLimitsAt,
	// for the same reason as OwnerLimits. Never client-writable.
	OwnerFlags map[string]bool `bson:"owner_flags,omitempty" json:"-"`
	// AllowCoGMCreateEncounter lets a co-GM create encounters in the session. Only the GM changes
	// it. It is never serialized from here: SessionView shows it to the GM and co-GMs only.
	AllowCoGMCreateEncounter bool `bson:"allow_co_gm_create_encounter" json:"-"`
}

Session is a named group owned by one GM (the owner).

type Sessions added in v0.2.0

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

Sessions is the repository for sessions and their membership records. The session document is owner-scoped (its owner is the GM); membership records are looked up by session, and the domain layer decides from them who may do what.

The owner-scoped repository is not embedded: its Get, Update, List and the rest would be session reads and writes with no Decision (PADR-0035). Only Open, Count, SoftDelete and Limits expose it.

func NewSessions added in v0.2.0

func NewSessions(db store.Database) *Sessions

NewSessions builds the repository on db.

func (*Sessions) AddBlock added in v0.2.0

func (r *Sessions) AddBlock(ctx context.Context, d Decision, userID string) error

AddBlock keeps userID out of the session; blocking twice is harmless.

func (*Sessions) AddInvite added in v0.2.0

func (r *Sessions) AddInvite(ctx context.Context, d Decision, codeHash string, expires time.Time) (Invite, error)

AddInvite stores an invite for the session.

func (*Sessions) AddMember added in v0.2.0

func (r *Sessions) AddMember(ctx context.Context, d Decision, userID, role string) (Member, error)

AddMember records userID in the session with role. An existing member is ErrConflict.

func (*Sessions) AuthorizeView added in v0.6.0

func (r *Sessions) AuthorizeView(ctx context.Context, actor, sessionID string) (Viewer, error)

AuthorizeView returns the Viewer for actor on the session. OpenFGA decides membership (can_view, PADR-0035) and the actor's live member record names the role; the role's own relation is then checked too, and the two must agree or the answer is ErrForbidden and the zero Viewer. A caller who is not a member, or whose record and tuples disagree (for example during a role change), learns nothing else. When no answer can be obtained the error is relations.ErrUnavailable or relations.ErrUnauthorized, so session data fails closed.

func (*Sessions) Blocked added in v0.2.0

func (r *Sessions) Blocked(ctx context.Context, d Decision, userID string) (bool, error)

Blocked reports whether userID is blocked from the session.

func (*Sessions) Blocks added in v0.2.0

func (r *Sessions) Blocks(ctx context.Context, d Decision, q Query) (Page[Block], error)

Blocks lists the session's blocked users.

func (*Sessions) Count added in v0.3.0

func (r *Sessions) Count(ctx context.Context, owner string) (int64, error)

Count returns how many sessions owner has, including inactive ones.

func (*Sessions) CountMembers added in v0.9.0

func (r *Sessions) CountMembers(ctx context.Context, d Decision) (int64, error)

CountMembers returns how many live members the session has besides its GM: co-GMs, players and observers, the ones the member limit counts.

func (*Sessions) Decide added in v0.2.0

func (r *Sessions) Decide(ctx context.Context, d Decision, requestID, status, role, reason string) (JoinRequest, error)

Decide settles a pending request as approved (with role) or rejected (with reason). A request already settled is ErrConflict.

func (*Sessions) DropRequest added in v0.2.0

func (r *Sessions) DropRequest(ctx context.Context, d Decision, userID string) error

DropRequest removes userID's request, if any.

func (*Sessions) DropSession added in v0.2.0

func (r *Sessions) DropSession(ctx context.Context, d Decision) error

DropSession soft-deletes every membership record of the session: members, invites, requests, and blocks. The session document itself is soft-deleted by SoftDelete.

func (*Sessions) ForJoin added in v0.3.0

func (r *Sessions) ForJoin(ctx context.Context, t JoinTicket) (JoinState, error)

ForJoin reads the join state for the ticket holder. The ticket is the gate (initiative-sessions, "Join by code"), and the pending request created from it grants nothing.

func (*Sessions) Invites added in v0.2.0

func (r *Sessions) Invites(ctx context.Context, d Decision, q Query) (Page[Invite], error)

Invites lists the session's invites, oldest first.

func (*Sessions) IsMember added in v0.13.0

func (r *Sessions) IsMember(ctx context.Context, userID, sessionID string) (bool, error)

IsMember reports whether userID is a live member of the live session sessionID. It is the per-delivery check behind the user-level stream, which spans sessions and so is not evicted when one membership ends.

func (*Sessions) Limits added in v0.3.0

func (r *Sessions) Limits() LimitItems

Limits returns the limit reconciler's view of the sessions.

func (*Sessions) Live added in v0.2.0

func (r *Sessions) Live(ctx context.Context, d Decision) (Session, error)

Live returns the session if it exists and is not deleted.

func (*Sessions) LookupSessions added in v0.3.0

func (r *Sessions) LookupSessions(ctx context.Context, ids []string) (map[string]bool, error)

LookupSessions maps each of ids that has a session record to whether it is soft-deleted; an ID with no record is absent. It reads no session content. Reconciler only: it decides which minted session IDs never became sessions (PADR-0040).

func (*Sessions) ManagerIDs added in v0.13.0

func (r *Sessions) ManagerIDs(ctx context.Context, sessionID string) ([]string, error)

ManagerIDs returns the user ids of the session's live GM and co-GMs: the audience of a change request. It is an addressing lookup for the event path, not a read on behalf of a user, and returns ids only.

func (*Sessions) Member added in v0.2.0

func (r *Sessions) Member(ctx context.Context, d Decision, userID string) (Member, error)

Member returns userID's membership, or ErrNotFound.

func (*Sessions) Members added in v0.2.0

func (r *Sessions) Members(ctx context.Context, d Decision, q Query) (Page[Member], error)

Members lists the session's members, oldest first.

func (*Sessions) Open added in v0.3.0

func (r *Sessions) Open(ctx context.Context, actor, id string, s *Session) error

Open creates the session owned by actor with the ID auth-api minted for them and records actor as its GM. Creating is not a session read: it is gated by the sessions_per_gm entitlement, which the caller checks first, and by the mint that put the GM tuple on id.

func (*Sessions) PendingUser added in v0.7.0

func (r *Sessions) PendingUser(ctx context.Context, d Decision, requestID string) (string, error)

PendingUser returns the user who made the still-pending request requestID, so work that must precede the decision (scrubbing stale combatant controls) can run before the request settles. A request that is not pending is ErrNotFound: a retried approval of a member who already has controls must not be scrubbed.

func (*Sessions) RecordOwnerLimits added in v0.2.0

func (r *Sessions) RecordOwnerLimits(ctx context.Context, d Decision, limits map[string]int, flags map[string]bool) error

RecordOwnerLimits stores the owner's current entitled values on the session. It changes neither the revision nor the audit stamp: nobody edited the session. Only the owner may: the write is owner-scoped to the decision's actor.

func (*Sessions) RemoveBlock added in v0.2.0

func (r *Sessions) RemoveBlock(ctx context.Context, d Decision, userID string) error

RemoveBlock lifts a block.

func (*Sessions) RemoveGMLess added in v0.4.0

func (r *Sessions) RemoveGMLess(ctx context.Context, sessionID string) error

RemoveGMLess soft-deletes a live session that has no live GM record, and every membership record of it, as the system. Such a session is left by a creation whose GM record could not be stored and whose removal also failed (Open); nobody can delete it, and it counts toward the owner's sessions_per_gm. It refuses (ErrConflict) a session that does have a GM or is younger than gmLessMinAge, so a lookup that raced a creation cannot remove a real session. Reconciler only.

func (*Sessions) RemoveMember added in v0.2.0

func (r *Sessions) RemoveMember(ctx context.Context, d Decision, userID string) error

RemoveMember ends a membership (soft delete).

func (*Sessions) RequestJoin added in v0.2.0

func (r *Sessions) RequestJoin(ctx context.Context, t JoinTicket) (JoinRequest, error)

RequestJoin records a pending request from the ticket holder for the ticket's session. An earlier settled request becomes pending again (the caller has checked the user is not a member, so an approved one means the approval never finished); an existing pending one is returned unchanged.

func (*Sessions) Requests added in v0.2.0

func (r *Sessions) Requests(ctx context.Context, d Decision, status string, q Query) (Page[JoinRequest], error)

Requests lists the session's requests, optionally only those with status.

func (*Sessions) ResolveInvite added in v0.3.0

func (r *Sessions) ResolveInvite(ctx context.Context, actor, codeHash string, now time.Time) (JoinTicket, error)

ResolveInvite turns a presented code's hash into a ticket for actor, judging expiry at now. An unknown, deleted, revoked, or expired invite is ErrNotFound, whatever the reason.

func (*Sessions) ResumeDeletion added in v0.7.0

func (r *Sessions) ResumeDeletion(ctx context.Context, actor, sessionID string) (Decision, error)

ResumeDeletion returns the Decision to finish deleting a session this user already deleted: the session document is soft-deleted and owned by actor, who deleted it. A deleted session has no OpenFGA tuples left to ask (and its record is gone from Live), so Mongo is the proof here, and the Decision is the GM's; it only exists so that cleanup steps interrupted after the soft delete can be run again. Anyone else, or a session that is not deleted, is ErrNotFound.

func (*Sessions) RevokeInvite added in v0.2.0

func (r *Sessions) RevokeInvite(ctx context.Context, d Decision, inviteID string) (Invite, error)

RevokeInvite ends an invite; revoking twice is harmless.

func (*Sessions) ScanMembers added in v0.2.0

func (r *Sessions) ScanMembers(ctx context.Context, q Query) (Page[Member], error)

ScanMembers pages through every membership record, live and soft-deleted, across all sessions. It exists for the OpenFGA reconciler (PADR-0035, PADR-0038), which has no acting user and must also see deleted records so it can remove their tuples. It is not reachable from a request.

func (*Sessions) SeatInfo added in v0.15.0

func (r *Sessions) SeatInfo(ctx context.Context, userID, sessionID string) (Session, Member, error)

SeatInfo returns the live session and userID's live member record in it, for the connect-time limit: the same checks as TicketView without its level rule. Every refusal is ErrNotMember.

func (*Sessions) SessionIDsOf added in v0.2.0

func (r *Sessions) SessionIDsOf(ctx context.Context, userID string, q Query) (Page[Member], error)

SessionIDsOf lists the sessions userID belongs to. It is keyed by the caller's own membership records and returns no session data; the caller authorizes each session before reading it.

func (*Sessions) SessionMembers added in v0.3.0

func (r *Sessions) SessionMembers(ctx context.Context, sessionID string) ([]Member, error)

SessionMembers returns every membership record of one session, live and soft-deleted, read fresh. Reconciler only: it has no acting user (PADR-0035, PADR-0038).

func (*Sessions) SessionsWithGM added in v0.4.0

func (r *Sessions) SessionsWithGM(ctx context.Context, ids []string) (map[string]bool, error)

SessionsWithGM returns the IDs among ids that have a live GM member record. Reconciler only.

func (*Sessions) SetRole added in v0.2.0

func (r *Sessions) SetRole(ctx context.Context, d Decision, userID, role string) (Member, error)

SetRole changes a member's role.

func (*Sessions) SoftDelete added in v0.3.0

func (r *Sessions) SoftDelete(ctx context.Context, d Decision, expectedRevision int64) error

SoftDelete deletes the session at expectedRevision. Only the GM may.

func (*Sessions) TicketView added in v0.10.0

func (r *Sessions) TicketView(ctx context.Context, userID, sessionID string, minted ViewLevel) (Viewer, error)

TicketView returns the Viewer a redeemed ticket opens: the user's live member record decides, not the ticket. OpenFGA was asked when the ticket was minted and is not asked again (a redeem carries no bearer to ask with), so the live record is the check: the session must exist, the user must still be a member, and their role's level must not exceed minted (a member promoted since gets a new ticket). A lower level is served at the lower level. Every refusal is ErrNotMember.

func (*Sessions) Update added in v0.8.0

func (r *Sessions) Update(ctx context.Context, d Decision, expectedRevision int64, set map[string]any) (Session, error)

Update changes the session's settings at expectedRevision and returns it. Only the GM may.

type Sink added in v0.9.0

type Sink interface {
	Emit(ctx context.Context, c Change)
}

Sink receives every committed encounter change after the write has succeeded. Emit must not block. Changes made by concurrent writers can reach the sink out of commit order, so clients order what they receive by the revision (GM and co-GM) or the view_tag (everyone else) in each event, not by arrival.

type SortKey

type SortKey struct {
	Field string
	Desc  bool
}

SortKey orders a list. _id is always appended as the final tie-break so paging is stable.

type Spec

type Spec struct {
	Name        string
	Filterable  []string
	Sortable    []string
	Projectable []string
	// Updatable lists the fields Owned.Update may set. State changes with their own rules
	// (credential revocation, last use, scopes, secret) are not here; they get dedicated functions.
	Updatable []string
	// StateFields lists the fields only Encounters.SetState may set: results of domain rules.
	StateFields   []string
	UnsetOnDelete []string
	// ConflictOnDuplicate maps a unique-index rejection to ErrConflict. Set it only where the
	// collection's one unique index is a user-facing constraint (theme slot); elsewhere the raw
	// store.ErrDuplicate is returned so it is not mislabeled.
	ConflictOnDuplicate bool
	Indexes             []store.IndexSpec
}

Spec declares one collection: its name, the fields a client may filter, sort, and project by (allow-lists; anything else is rejected, PADR-0030), fields to unset on soft delete, and its indexes.

func AllSpecs

func AllSpecs() []Spec

AllSpecs lists every collection the service owns.

type StreamLease added in v0.10.0

type StreamLease struct {
	ID        string    `bson:"_id"`
	Bucket    string    `bson:"bucket"`
	UserID    string    `bson:"user_id"`
	SessionID string    `bson:"session_id,omitempty"`
	ClientID  string    `bson:"client_id,omitempty"`
	Pod       string    `bson:"pod"`
	Until     time.Time `bson:"until"`
	Dropped   bool      `bson:"dropped,omitempty"`
	// Counted marks a session seat that counts toward the session's member limit: every member
	// but the GM. Every session seat, the GM's too, counts toward the member's device limit.
	Counted bool `bson:"counted,omitempty"`
	// Pending marks a session seat whose connect has not passed its checks yet. A pending seat
	// counts toward every limit but never shields its member from the member limit, so two first
	// connects of one new member racing each other are both refused.
	Pending bool `bson:"pending,omitempty"`
}

StreamLease is one stream's seat. Until is when the seat lapses unless renewed: a pod that crashes leaves seats that expire on their own, and a dropped client keeps its seat for a grace period so a reconnect does not need a free one. Bucket is what the cap counts: "user:<id>" for a user's stream, "cred:<id>" for an integration credential's, so a runaway credential cannot lock its owner out of their own stream. Every pod stamps Until from its own clock and the pods compare them, so the cluster's clocks must agree to within a few seconds (a skew moves a seat's lapse by that much). Pod and SessionID are not read yet; the per-session member count (7.12b) will.

type StreamLeases added in v0.10.0

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

StreamLeases is the lease store.

func NewStreamLeases added in v0.10.0

func NewStreamLeases(db store.Database) *StreamLeases

NewStreamLeases returns the lease store on db.

func (*StreamLeases) Acquire added in v0.10.0

func (r *StreamLeases) Acquire(ctx context.Context, l StreamLease, ttl time.Duration, max int) error

Acquire gives l a seat valid for ttl, or ErrStreamLimit when its bucket already holds max, or ErrStreamUnavailable when the store fails. Two acquisitions can both pass the count, so the seat is recounted after the insert and given back if the bucket is over: both may then be refused, but neither is kept over the limit. A dropped seat of the same client is taken over once the new one is in, not before, so a refused reconnect keeps its old seat. ponytail: concurrent connects at the limit can all be refused; a retry succeeds.

func (*StreamLeases) AcquireSession added in v0.15.0

func (r *StreamLeases) AcquireSession(ctx context.Context, l StreamLease, ttl time.Duration, members, devices int) error

AcquireSession gives l a seat in a session's bucket. A member's connections share one member seat, so the session holds at most members distinct counted members (a dropped client's seat counts until its grace ends), and one member holds at most devices live connections, the GM included. A new connection of a member who already holds a seat adds no member, so it is refused only by the device limit, even when the member limit has fallen below the members connected. Over the device limit is *DeviceLimitError, over the member limit ErrStreamLimit, a store failure ErrStreamUnavailable. Like Acquire, the seat is inserted, recounted and given back when over, so two racing first connects of different members can both be refused but neither is kept over.

func (*StreamLeases) Release added in v0.10.0

func (r *StreamLeases) Release(ctx context.Context, l StreamLease, grace time.Duration, keep bool) error

Release ends the seat. With keep, a client that has an id keeps it for grace so its reconnect does not need a free seat; every other end (evicted, over its age, revoked, never opened) frees it at once.

func (*StreamLeases) Renew added in v0.10.0

func (r *StreamLeases) Renew(ctx context.Context, l StreamLease, ttl time.Duration) error

ponytail: Renew can bring back a seat that lapsed (after more than the lease TTL of failed renewals) without recounting, so a bucket may sit one over its cap until that stream ends; a recount here would close a healthy stream on a store blip. Renew pushes the seat's end to ttl from now. If the row is gone (its TTL ran out while renewals were failing) it is put back, so a healthy stream does not lose its seat. A renewal that fails leaves the stream up; its seat lapses after the lease TTL if renewals keep failing.

func (*StreamLeases) SetClock added in v0.10.0

func (r *StreamLeases) SetClock(now func() time.Time)

SetClock replaces the clock seats are aged by (tests).

type StreamTicket added in v0.10.0

type StreamTicket struct {
	ID          string    `bson:"_id"` // hex SHA-256 of the ticket
	UserID      string    `bson:"user_id"`
	SessionID   string    `bson:"session_id,omitempty"` // empty: the user's private encounters
	EncounterID string    `bson:"encounter_id,omitempty"`
	Level       ViewLevel `bson:"level"` // what the user could see when the ticket was minted
	ClientID    string    `bson:"client_id,omitempty"`
	// UserLevel marks a ticket for the user-level stream: addressed events across every session
	// the user belongs to, no encounter state. It carries no session or encounter.
	UserLevel bool      `bson:"user_level,omitempty"`
	At        time.Time `bson:"at"`
}

StreamTicket is what a minted ticket stands for. Only the SHA-256 of the ticket is stored, as the row id, so a database read does not yield a usable ticket. Nothing here is trusted beyond who asked, for what, and at what level: access is re-read when the ticket is redeemed.

type StreamTickets added in v0.10.0

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

StreamTickets is the ticket store.

func NewStreamTickets added in v0.10.0

func NewStreamTickets(db store.Database) *StreamTickets

NewStreamTickets returns the ticket store on db.

func (*StreamTickets) Mint added in v0.10.0

Mint stores t (its ID already the hash of the ticket handed to the caller).

func (*StreamTickets) Peek added in v0.10.0

func (r *StreamTickets) Peek(ctx context.Context, id string, maxAge time.Duration) (StreamTicket, error)

Peek reads the ticket without spending it, so a connect that will be refused for a limit leaves it redeemable. Redeem is still what makes it single-use.

func (*StreamTickets) Redeem added in v0.10.0

func (r *StreamTickets) Redeem(ctx context.Context, id string, maxAge time.Duration) (StreamTicket, error)

Redeem spends the ticket whose hash is id: it finds the row, then deletes it by _id and requires that the delete removed one row. Two redeems can both find the row, but only one delete removes it (the other reports ErrNotFound, which store.DeleteOne raises on a deleted count of zero), so a ticket opens one stream even when two pods are asked at once. A ticket older than maxAge, unknown, or already spent is ErrNotFound.

func (*StreamTickets) SetClock added in v0.10.0

func (r *StreamTickets) SetClock(now func() time.Time)

SetClock replaces the clock the ticket ages are read from (tests).

type SystemRepo

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

SystemRepo reads and seeds game-system definitions. They are shared reference data with no owner, so there is no owner scoping; the only writer is the seed loader, as the system actor.

func NewSystemRepo

func NewSystemRepo(db store.Database) *SystemRepo

NewSystemRepo builds the repository for the game_systems collection in db.

func (*SystemRepo) Get

func (s *SystemRepo) Get(ctx context.Context, idOrAlias string) (GameSystem, error)

Get returns the system whose ID or alias equals idOrAlias.

func (*SystemRepo) GetOrDefault

func (s *SystemRepo) GetOrDefault(ctx context.Context, idOrAlias string) (GameSystem, error)

GetOrDefault returns the system for idOrAlias, or the default system when none is defined for it.

func (*SystemRepo) List

func (s *SystemRepo) List(ctx context.Context, q Query) (Page[GameSystem], error)

List returns one page of every system, gated or not. It is for the loader and tools; an API caller's list goes through ListAvailable.

func (*SystemRepo) ListAvailable added in v0.6.0

func (s *SystemRepo) ListAvailable(ctx context.Context, q Query, entitled bool) (Page[GameSystem], error)

ListAvailable returns one page of the systems a caller may use: every system when entitled, otherwise only the ungated ones (No System). The restriction is part of the query itself and is ANDed with the client's filters, so a filter can never widen it.

func (*SystemRepo) Upsert

func (s *SystemRepo) Upsert(ctx context.Context, sys GameSystem) (Outcome, error)

Upsert creates or updates sys by ID. A definition identical to the stored one (same content hash) is left untouched, so re-seeding keeps IDs, revisions, and audit fields stable.

type Theme

type Theme struct {
	Meta              `bson:",inline"`
	Name              string `bson:"name" json:"name"`
	Style             string `bson:"style" json:"style"`
	MainColor         string `bson:"main_color" json:"main_color"`
	Accent1Color      string `bson:"accent1_color" json:"accent1_color"`
	Accent2Color      string `bson:"accent2_color" json:"accent2_color"`
	Background1Color  string `bson:"background1_color" json:"background1_color"`
	Background2Color  string `bson:"background2_color" json:"background2_color"`
	PrimaryFontName   string `bson:"primary_font_name" json:"primary_font_name"`
	SecondaryFontName string `bson:"secondary_font_name" json:"secondary_font_name"`
	BackgroundImage   string `bson:"background_image,omitempty" json:"background_image,omitempty"`
	Slot              *int   `bson:"slot,omitempty" json:"slot,omitempty"`
}

Theme is a user's custom theme. Slot is the numbered editable slot it occupies; soft delete unsets it so the slot is free again (see ThemeSpec).

type TrackerField

type TrackerField struct {
	Key    string `bson:"key" json:"key"`
	Label  string `bson:"label" json:"label"`
	Kind   string `bson:"kind" json:"kind"`
	Def    int    `bson:"default" json:"default"`
	Min    *int   `bson:"min,omitempty" json:"min,omitempty"`
	Max    *int   `bson:"max,omitempty" json:"max,omitempty"`
	MaxRef string `bson:"max_ref,omitempty" json:"max_ref,omitempty"`
}

TrackerField is one health value in a game system's tracker definition. Max is a literal bound; MaxRef names another field in the same definition whose current value is the bound. At most one of the two is set.

type ViewLevel added in v0.6.0

type ViewLevel int

ViewLevel is the least a Viewer may see, weakest first. The zero value sees nothing.

const (
	ViewNone ViewLevel = iota
	ViewObserver
	ViewPlayer
	ViewGM // gm, co_gm, or the owner of a private encounter
)

View levels: Observer and Player both get the non-GM view; only the Player controls combatants.

type Viewer added in v0.6.0

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

Viewer is the proof of how a caller may see one encounter. Every encounter view is built from a Viewer and nothing else, so the view builder never recomputes membership (PADR-0035). The only ways to get a granted Viewer are AuthorizeView (a session member, asked of OpenFGA with the caller's own bearer) and an owner-scoped load of a private encounter. The zero value grants nothing.

func BusViewer added in v0.9.0

func BusViewer(sessionID string) Viewer

BusViewer is the viewer the platform-bus form of an event is rendered for: observer level, no actor, bound to the session of the encounter being rendered ("" for a private encounter). It grants no read: nothing can load an encounter with it, it only lets the view builder decide what an unprivileged consumer may be told about a document already in memory.

func OwnerViewer added in v0.10.0

func OwnerViewer(owner string) (Viewer, error)

OwnerViewer is the viewer for owner's own private encounters.

func (Viewer) Actor added in v0.6.0

func (v Viewer) Actor() string

Actor returns the user the viewer is.

func (Viewer) Level added in v0.6.0

func (v Viewer) Level() ViewLevel

Level returns what the viewer may see.

func (Viewer) SessionID added in v0.6.0

func (v Viewer) SessionID() string

SessionID returns the session the viewer covers; empty for the owner of a private encounter.

Jump to

Keyboard shortcuts

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