// Command initiative-api serves the Initiative! API.
package main
import (
"context"
"errors"
"log"
"log/slog"
"net/http"
"os"
"os/signal"
"sync/atomic"
"syscall"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/gomodule/redigo/redis"
"github.com/joho/godotenv"
"github.com/sweetrpg/api-core.go/ratelimit"
"github.com/sweetrpg/api-core.go/tracing"
"github.com/sweetrpg/api-core.go/util"
"github.com/sweetrpg/authz-client.go/authz"
"github.com/sweetrpg/common.go/logging"
"github.com/sweetrpg/initiative-api/config"
"github.com/sweetrpg/initiative-api/constants"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/domain"
"github.com/sweetrpg/initiative-api/entitlements"
"github.com/sweetrpg/initiative-api/events"
"github.com/sweetrpg/initiative-api/events/stream"
"github.com/sweetrpg/initiative-api/relations"
"github.com/sweetrpg/initiative-api/server"
"github.com/sweetrpg/initiative-api/startup"
"github.com/sweetrpg/initiative-api/store"
"github.com/sweetrpg/mongodb.go/database"
"go.mongodb.org/mongo-driver/bson/primitive"
)
func main() {
_ = godotenv.Load(".env")
cfg, err := config.FromEnv()
if err != nil {
log.Fatalf("invalid configuration:\n%v", err)
}
// common.go/logging reads LOG_LEVEL itself; pass the validated, defaulted value.
_ = os.Setenv(constants.LOG_LEVEL, cfg.LogLevel)
logging.Init()
tracing.SetupTracing(constants.ServiceName)
defer tracing.TeardownTracing()
// Reads the MongoDB connection settings from the environment; waits out a brief resolver or
// network failure instead of crashing the pod.
retry := startup.DefaultPolicy()
if err := startup.ConnectDatabase(retry); err != nil {
log.Fatalf("database: %v", err)
}
defer database.TeardownDatabase()
db := store.MongoDatabase{DB: database.Db}
fanout := db.Collection(stream.FanoutCollection)
if err := startup.Do("create indexes", startup.IndexPolicy(retry), func() error { // a conflicting index never resolves by waiting
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := data.EnsureIndexes(ctx, db); err != nil {
return err
}
return fanout.EnsureIndexes(ctx, stream.FanoutIndexes)
}); err != nil {
log.Fatalf("indexes: %v", err)
}
themes, err := domain.NewThemes(db)
if err != nil {
log.Fatalf("themes: %v", err)
}
creds := domain.NewCredentials(db)
pool := util.RedisPool() // non-nil: config requires REDIS_HOST
rosters, encounters, sessions := domain.NewRosters(db), domain.NewEncounters(db), domain.NewSessions(db)
// Fail-open: the hub publishes from its own queue and drops an event it cannot send.
var pub *events.Publisher
if natsURL := os.Getenv("NATS_URL"); natsURL != "" {
var err error
if pub, err = events.NewPublisher(natsURL); err != nil {
log.Fatalf("event publisher: %v", err)
}
defer pub.Close() // deferred before hub.Close, so it runs after the queue that feeds it stops
}
hub := stream.New(encounters)
defer hub.Close()
if pub != nil {
hub.AttachBus(pub, 1024)
}
encounters.SetSink(hub)
sessions.SetSink(hub)
sessions.SetEvictor(hub)
host, _ := os.Hostname()
pod := host + "-" + primitive.NewObjectID().Hex() // unique per process: a pod never mistakes another's rows for its own
relay := hub.AttachRelay(fanout, pod, 1024)
relay.Run(context.Background())
defer relay.Stop()
// Credentials stay off (503) until the auth-event consumer is bound and caught up, so a deny
// published while the service was down is applied before any secret authenticates (PADR-0039).
// The consumer starts after the hub, the bus and the relay exist, so an event it applies first (a
// deny) already finds the hub to evict from and nothing is acked into a void. It starts in the
// background, so the rest of the API does not wait on NATS; if NATS
// stays unreachable past CREDENTIAL_EVENTS_MAX_DISCONNECT the gate closes again.
if natsURL := os.Getenv("NATS_URL"); natsURL == "" {
logging.Logger.Warn("NATS_URL is not set; integration credentials are disabled")
} else {
var live atomic.Pointer[events.Consumer]
consumerCtx, stopConsumer := context.WithCancel(context.Background())
go runConsumer(consumerCtx, creds, hub, natsURL, os.Getenv("NATS_DURABLE_NAME"), cfg.CredentialEventsMaxDisconnect, retry, &live)
defer func() {
stopConsumer() // first, so runConsumer does not rebuild what Stop closes
if c := live.Load(); c != nil {
c.Stop()
}
}()
}
rosters.SetSink(hub)
sessions.OwnerRecordMaxAge = cfg.OwnerEntitlementsMaxAge
sessions.MaxMembers = cfg.SessionMembersMax
streams := domain.NewStreams(db, sessions, encounters)
prefs := domain.NewNotificationPrefs(db, sessions)
changeRequests := domain.NewChangeRequests(db, encounters, sessions)
changeRequests.Notifier = hub
hub.SetPreferences(prefs)
hub.SetManagers(sessions)
hub.SetMembers(sessions)
streams.TTL = cfg.StreamTicketTTL
ready := server.NewReadiness(5*time.Second, 2*time.Second, server.Check{Name: "database", Fn: func(ctx context.Context) error { return database.Db.Client().Ping(ctx, nil) }})
svc := server.Services{
Ready: ready,
Locks: encounters.Locks(),
Limits: domain.NewLimits(
domain.Kind{Name: "themes", Key: domain.KeyThemeSlots, Repo: themes.Items()},
domain.Kind{Name: "rosters", Key: domain.KeySavedRosters, Repo: rosters.Items()},
domain.Kind{Name: "encounters", Key: domain.KeySavedEncounters, Repo: encounters.Items()},
domain.Kind{Name: "sessions", Key: domain.KeySessionsPerGM, Repo: sessions.Items()},
domain.Kind{Name: "credentials", Key: domain.KeyIntegrationCredentials, Repo: creds.Items()},
),
Authz: authz.NewClient(cfg.AuthAPIURL, cfg.UsersAPIURL),
Entitlements: entitlements.New(cfg.EntitlementsAPIURL),
OwnerLimits: data.NewOwnerEntitlements(db, cfg.OwnerEntitlementsMaxAge),
Themes: themes,
Systems: data.NewSystemRepo(db),
Credentials: creds,
Rosters: rosters,
Encounters: encounters,
Sessions: sessions,
ChangeRequests: changeRequests,
NotificationPrefs: prefs,
Relations: relations.New(cfg.AuthAPIURL),
Hub: hub,
Streams: streams,
Leases: data.NewStreamLeases(db),
Stream: server.StreamOptions{
AllowedOrigins: cfg.StreamAllowedOrigins, MaxAge: cfg.StreamMaxAge, Heartbeat: cfg.StreamHeartbeat, RecheckInterval: cfg.StreamRecheckInterval,
ConcurrentMax: cfg.StreamConcurrentMax, CredentialMax: cfg.StreamCredentialMax, DevicesMax: cfg.SessionDevicesMax, MaxPerPod: cfg.StreamMaxPerPod, LeaseTTL: cfg.StreamLeaseTTL, Grace: cfg.StreamGrace, Pod: pod,
},
}
srv := &http.Server{Addr: cfg.BindAddress, Handler: newRouter(cfg, svc, pool), ReadHeaderTimeout: 10 * time.Second}
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
logging.Logger.Error("server failed", "error", err.Error())
os.Exit(1)
}
}()
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
<-stop
// http.Server.Shutdown does not wait for upgraded connections, so end the event streams first
// (each closes with 1001 and its client reconnects to another pod), give their close frames a
// moment to go out, then drain the ordinary requests.
hub.Shutdown()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
drain, drainCancel := context.WithTimeout(ctx, 3*time.Second)
hub.Drain(drain)
drainCancel()
if err := srv.Shutdown(ctx); err != nil {
logging.Logger.Error("shutdown failed", "error", err.Error())
}
}
func newRouter(cfg config.Config, svc server.Services, pool *redis.Pool) *gin.Engine {
httpLogger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
r := gin.New()
r.Use(server.Middleware(httpLogger, cfg.RequestTimeout)...)
if len(cfg.AllowedOrigins) > 0 {
r.Use(cors.New(cors.Config{
AllowOrigins: cfg.AllowedOrigins,
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization", constants.CorrelationHeader},
ExposeHeaders: []string{constants.CorrelationHeader},
AllowCredentials: true,
MaxAge: 12 * time.Hour,
}))
}
r.Use(server.RateLimit(pool, ratelimit.DefaultOptions(), svc.Credentials)...)
server.SetupHandlers(r, svc)
return r
}
// Pacing for runConsumer: the wait between attempts, and how long a consumer must live before a
// loss counts as new trouble rather than a flap.
const (
consumerFirstWait = 5 * time.Second
consumerMaxWait = 2 * time.Minute
consumerMinLife = time.Minute
)
// runConsumer keeps an auth-event consumer running until ctx ends: it starts one (retrying with a
// capped backoff, an error logged each round, so a NATS that is down at boot is picked up when it
// returns) and builds a new one if the connection is lost for good. Until a consumer has started and
// caught up, credentials stay closed (503) and the rest of the API serves.
func runConsumer(ctx context.Context, creds *domain.Credentials, evict events.Evictor, natsURL, durable string, maxDisconnect time.Duration, retry startup.Policy, live *atomic.Pointer[events.Consumer]) {
wait := consumerFirstWait
for ctx.Err() == nil {
var c *events.Consumer
err := startup.Do("start the auth-event consumer", retry, func() error {
c = events.New(creds, creds)
c.Evictor = evict
c.MaxDisconnect = maxDisconnect
return c.Start(ctx, natsURL, durable)
})
if err != nil {
logging.Logger.Error("the auth-event consumer did not start; integration credentials stay closed; retrying", "error", err.Error(), "retry_in", wait.String())
select {
case <-ctx.Done():
return
case <-time.After(wait):
}
wait = min(wait*2, consumerMaxWait)
continue
}
started := time.Now()
live.Store(c)
select {
case <-c.Dead():
logging.Logger.Error("the auth-event consumer lost its connection for good; starting a new one", "retry_in", wait.String())
c.Stop()
case <-ctx.Done():
return
}
if time.Since(started) >= consumerMinLife {
wait = consumerFirstWait // it ran long enough to count as healthy
}
select {
case <-ctx.Done():
return
case <-time.After(wait):
}
wait = min(wait*2, consumerMaxWait)
}
}
// Command reconciler runs one OpenFGA tuple reconciliation pass and exits (PADR-0035, PADR-0038).
// It authenticates to auth-api as an Auth0 machine-to-machine client and caches the token in Redis
// (PADR-0041). Exit codes: 1 pass failed, Auth0/Redis failed, or the database stayed unreachable after retries, 2 missing configuration, 3 auth-api
// rejected the token. Any non-zero exit shows on the CronJob and fires the alert.
package main
import (
"context"
"errors"
"log"
"net/url"
"os"
"time"
"github.com/sweetrpg/api-core.go/util"
"github.com/sweetrpg/common.go/logging"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/reconcile"
"github.com/sweetrpg/initiative-api/startup"
"github.com/sweetrpg/initiative-api/store"
"github.com/sweetrpg/mongodb.go/database"
)
func main() { os.Exit(run()) }
func run() int {
logging.Init()
tokens, authURL, ok := tokenSource()
if !ok {
return 2
}
if err := startup.ConnectDatabase(startup.DefaultPolicy()); err != nil {
logging.Logger.Error("cannot reach the database", "error", err.Error())
return 1
}
defer database.TeardownDatabase()
// Under the CronJob's activeDeadlineSeconds (270); the last minute is reserved for mint
// garbage collection (reconcile.Reconciler.GCReserve).
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute)
defer cancel()
sessions := data.NewSessions(store.MongoDatabase{DB: database.Db})
api := reconcile.NewAuthAPIWithSource(authURL, tokens)
r := reconcile.Reconciler{Members: sessions, Tuples: api, Mints: api, Sessions: sessions}
res, err := r.Run(ctx)
logging.Logger.Info("reconcile finished", "sessions", res.Sessions, "written", res.Written, "deleted", res.Deleted, "failed", res.Failed,
"mints_closed", res.MintsClosed, "mints_skipped", res.MintsSkipped)
switch {
case errors.Is(err, reconcile.ErrTokenRejected):
logging.Logger.Error("auth-api rejected the reconciler token (401, 403, or a rejection recorded in the last hour); check the initiative-reconciler role, deny entries, login_profiles mapping and audience (PADR-0041)")
return 3
case err != nil:
logging.Logger.Error("reconcile failed", "error", err.Error())
return 1
}
return 0
}
// settings is the reconciler's token configuration.
type settings struct {
authURL, clientID, clientSecret, tokenURL, audience string
}
// loadSettings reads and validates the environment. The token URL must be https so the client
// secret never crosses the network in clear text. The secret is read here and never logged.
func loadSettings(get func(string) string) (settings, error) {
s := settings{
authURL: get("AUTH_API_URL"), clientID: get("RECONCILER_CLIENT_ID"), clientSecret: get("RECONCILER_CLIENT_SECRET"),
tokenURL: get("RECONCILER_TOKEN_URL"), audience: get("RECONCILER_AUDIENCE"),
}
for _, f := range []struct{ name, value string }{
{"AUTH_API_URL", s.authURL}, {"RECONCILER_CLIENT_ID", s.clientID}, {"RECONCILER_CLIENT_SECRET", s.clientSecret},
{"RECONCILER_TOKEN_URL", s.tokenURL}, {"RECONCILER_AUDIENCE", s.audience}, {"REDIS_HOST", get("REDIS_HOST")},
} {
if f.value == "" {
return settings{}, errors.New(f.name + " is required")
}
}
if u, err := url.Parse(s.tokenURL); err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil {
return settings{}, errors.New("RECONCILER_TOKEN_URL must be an https URL without credentials")
}
return s, nil
}
// tokenSource builds the Auth0 client-credentials source from the environment.
func tokenSource() (src reconcile.TokenSource, authURL string, ok bool) {
s, err := loadSettings(os.Getenv)
if err != nil {
log.Print(err.Error())
return nil, "", false
}
pool := util.RedisPool()
if pool == nil {
log.Print("REDIS_HOST is required for the token cache")
return nil, "", false
}
return reconcile.NewClientCredentials(s.tokenURL, s.clientID, s.clientSecret, s.audience, pool), s.authURL, true
}
// Command seed applies the checked-in game-system definitions to the configured database. It is
// idempotent and safe to run at every deploy.
package main
import (
"context"
"log"
"time"
"github.com/sweetrpg/common.go/logging"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/seed"
"github.com/sweetrpg/initiative-api/store"
"github.com/sweetrpg/mongodb.go/database"
)
func main() {
logging.Init()
database.SetupDatabase() // reads the MongoDB connection settings from the environment
defer database.TeardownDatabase()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
db := store.MongoDatabase{DB: database.Db}
if err := data.EnsureIndexes(ctx, db); err != nil {
log.Fatalf("indexes: %v", err)
}
res, err := seed.Load(ctx, data.NewSystemRepo(db))
if err != nil {
log.Fatalf("seed: %v", err)
}
log.Printf("game systems seeded: created=%d updated=%d unchanged=%d", res.Created, res.Updated, res.Unchanged)
}
// Package config loads and validates the service configuration from the environment.
package config
import (
"errors"
"fmt"
"net"
"net/url"
"os"
"path"
"strconv"
"strings"
"time"
"github.com/sweetrpg/initiative-api/constants"
)
// Config is the validated runtime configuration.
type Config struct {
BindAddress string
Env string
Version string
LogLevel string
// OTLPEndpoint is the trace collector base URL; empty leaves the exporter default.
OTLPEndpoint string
// AllowedOrigins is the CORS allowlist; empty disables CORS (fail closed).
AllowedOrigins []string
// AuthAPIURL is auth-api's base URL. Bearer tokens are verified there via /authz/check
// (signature, expiry, iss, aud, roles); this service holds no signing keys or credentials.
AuthAPIURL string
// UsersAPIURL is users-api's base URL, used to resolve the verified caller to users._id.
UsersAPIURL string
// EntitlementsAPIURL is entitlements-api's base URL for gating checks.
EntitlementsAPIURL string
// RedisHost is the rate limiter's counter store; the limiter fails closed without it
// (PADR-0036), so it is required. Port and password are read by the Redis pool itself.
RedisHost string
// OwnerEntitlementsMaxAge is how long a recorded owner entitlement value stays usable for
// integration credentials, which cannot read it live. Past it the credential gets
// limits_not_synced until the owner opens the app.
OwnerEntitlementsMaxAge time.Duration
// SessionMembersMax is the maximum of a session's member limit: an entitled members_per_session
// above it has no effect (initiative-entitlement-gating, "Session member limit").
SessionMembersMax int
// SessionDevicesMax is the most connections one member may hold to a session stream, the GM
// included.
SessionDevicesMax int
// CredentialEventsMaxDisconnect is how long NATS may be unreachable before integration
// credentials fail closed (503); the rest of the API keeps serving.
CredentialEventsMaxDisconnect time.Duration
// StreamAllowedOrigins are the browser origins (host patterns) that may open an event stream; a
// request with no Origin header (a native client) is always allowed.
StreamAllowedOrigins []string
// StreamTicketTTL is how long a stream ticket can be redeemed; StreamMaxAge ends every stream
// after that long, so a revoked credential or a missed eviction cannot outlive it;
// StreamHeartbeat is the interval of the server's heartbeat frames.
StreamTicketTTL, StreamMaxAge, StreamHeartbeat time.Duration
// StreamRecheckInterval is how often an open stream re-checks membership and credentials; it
// never exceeds StreamHeartbeat.
StreamRecheckInterval time.Duration
// RequestTimeout bounds every request except the event stream's upgrade.
RequestTimeout time.Duration
// StreamConcurrentMax is the most event streams one user may hold open across all pods and
// StreamCredentialMax the most one integration credential may (its own count, not the owner's);
// StreamMaxPerPod caps one pod's connections. StreamLeaseTTL is how long a stream's seat lasts
// without a renewal (a crashed pod's seats lapse after it), and StreamGrace how long a dropped
// client keeps its seat so its reconnect does not need a free one.
StreamConcurrentMax, StreamCredentialMax, StreamMaxPerPod int
StreamLeaseTTL, StreamGrace time.Duration
}
// defaultOwnerEntitlementsMaxAge is seven days.
const defaultOwnerEntitlementsMaxAge = "168h"
var logLevels = map[string]bool{"DEBUG": true, "INFO": true, "WARN": true, "ERROR": true}
// Load reads the environment through lookup (os.LookupEnv in production) and returns every
// validation problem at once, so a misconfigured deploy reports all of them in one start attempt.
func Load(lookup func(string) (string, bool)) (Config, error) {
get := func(key, def string) string {
if v, ok := lookup(key); ok && strings.TrimSpace(v) != "" {
return strings.TrimSpace(v)
}
return def
}
c := Config{
BindAddress: get("BIND_ADDRESS", ":8000"),
Env: get("ENV", "dev"),
Version: get("VERSION", "v0.0.0"),
LogLevel: strings.ToUpper(get(constants.LOG_LEVEL, "WARN")),
OTLPEndpoint: get(constants.OTEL_EXPORTER_OTLP_ENDPOINT, ""),
AuthAPIURL: strings.TrimRight(get(constants.AUTH_API_URL, ""), "/"),
UsersAPIURL: strings.TrimRight(get(constants.USERS_API_URL, ""), "/"),
EntitlementsAPIURL: strings.TrimRight(get(constants.ENTITLEMENTS_API_URL, ""), "/"),
RedisHost: get("REDIS_HOST", ""),
}
if origins := get(constants.ALLOWED_ORIGINS, ""); origins != "" {
c.AllowedOrigins = strings.Split(origins, ",")
}
var errs []error
maxMembers := get(constants.SESSION_MEMBERS_MAX, strconv.Itoa(constants.DefaultSessionMembersMax))
if n, err := strconv.Atoi(maxMembers); err != nil || n < 1 {
errs = append(errs, fmt.Errorf("%s %q: must be a positive integer", constants.SESSION_MEMBERS_MAX, maxMembers))
} else {
c.SessionMembersMax = n
}
maxDevices := get(constants.SESSION_DEVICES_MAX, strconv.Itoa(constants.DefaultSessionDevicesMax))
if n, err := strconv.Atoi(maxDevices); err != nil || n < 1 {
errs = append(errs, fmt.Errorf("%s %q: must be a positive integer", constants.SESSION_DEVICES_MAX, maxDevices))
} else {
c.SessionDevicesMax = n
}
maxAge := get(constants.OWNER_ENTITLEMENTS_MAX_AGE, defaultOwnerEntitlementsMaxAge)
if d, err := time.ParseDuration(maxAge); err != nil || d <= 0 {
errs = append(errs, fmt.Errorf("%s %q: must be a positive duration such as 168h", constants.OWNER_ENTITLEMENTS_MAX_AGE, maxAge))
} else {
c.OwnerEntitlementsMaxAge = d
}
for _, d := range []struct {
key string
dst *time.Duration
def time.Duration
min, max time.Duration
}{
{constants.REQUEST_TIMEOUT, &c.RequestTimeout, constants.DefaultRequestTimeout, time.Second, time.Minute},
{constants.STREAM_TICKET_TTL, &c.StreamTicketTTL, constants.DefaultStreamTicketTTL, time.Second, constants.MaxStreamTicketTTL},
{constants.STREAM_MAX_AGE, &c.StreamMaxAge, constants.DefaultStreamMaxAge, time.Minute, 24 * time.Hour},
{constants.STREAM_HEARTBEAT, &c.StreamHeartbeat, constants.DefaultStreamHeartbeat, time.Second, time.Minute},
// How often a stream re-checks membership and credentials: with the check timeout it bounds
// how long a revocation can go unseen (see server.StreamOptions.RevocationBound).
{constants.STREAM_RECHECK_INTERVAL, &c.StreamRecheckInterval, constants.DefaultStreamRecheckInterval, time.Second, time.Minute},
} {
v := get(d.key, d.def.String())
if n, err := time.ParseDuration(v); err != nil || n < d.min || n > d.max {
errs = append(errs, fmt.Errorf("%s %q: must be a duration between %s and %s", d.key, v, d.min, d.max))
} else {
*d.dst = n
}
}
c.StreamRecheckInterval = min(c.StreamRecheckInterval, c.StreamHeartbeat) // a re-check slower than the heartbeat would not be the bound
for _, d := range []struct {
key string
dst *int
def int
min, max int
}{
{constants.STREAM_CONCURRENT_MAX, &c.StreamConcurrentMax, 10, 1, 100},
{constants.STREAM_CREDENTIAL_MAX, &c.StreamCredentialMax, 3, 1, 20},
{constants.STREAM_MAX_PER_POD, &c.StreamMaxPerPod, 1000, 1, 100000},
} {
v := get(d.key, strconv.Itoa(d.def))
if n, err := strconv.Atoi(v); err != nil || n < d.min || n > d.max {
errs = append(errs, fmt.Errorf("%s %q: must be an integer between %d and %d", d.key, v, d.min, d.max))
} else {
*d.dst = n
}
}
for _, d := range []struct {
key string
dst *time.Duration
def time.Duration
min, max time.Duration
}{
{constants.STREAM_LEASE_TTL, &c.StreamLeaseTTL, constants.DefaultStreamLeaseTTL, 2 * time.Second, 10 * time.Minute},
{constants.STREAM_GRACE, &c.StreamGrace, constants.DefaultStreamGrace, time.Second, 10 * time.Minute},
} {
v := get(d.key, d.def.String())
if n, err := time.ParseDuration(v); err != nil || n < d.min || n > d.max {
errs = append(errs, fmt.Errorf("%s %q: must be a duration between %s and %s", d.key, v, d.min, d.max))
} else {
*d.dst = n
}
}
// A seat is renewed on every heartbeat, so it must outlast at least one missed renewal.
if c.StreamHeartbeat > 0 && c.StreamLeaseTTL > 0 && c.StreamLeaseTTL < 2*c.StreamHeartbeat {
errs = append(errs, fmt.Errorf("%s %s: must be at least twice %s (%s)", constants.STREAM_LEASE_TTL, c.StreamLeaseTTL, constants.STREAM_HEARTBEAT, c.StreamHeartbeat))
}
if origins := get(constants.STREAM_ALLOWED_ORIGINS, ""); origins != "" {
for _, o := range strings.Split(origins, ",") {
if o = strings.TrimSpace(o); o == "*" {
errs = append(errs, fmt.Errorf("%s: wildcard origin is not allowed", constants.STREAM_ALLOWED_ORIGINS))
} else if matchesArbitraryHost(o) {
errs = append(errs, fmt.Errorf("%s %q: pattern would match any host", constants.STREAM_ALLOWED_ORIGINS, o))
} else if _, err := path.Match(o, ""); err != nil {
errs = append(errs, fmt.Errorf("%s %q: not a valid host pattern", constants.STREAM_ALLOWED_ORIGINS, o))
} else if o != "" {
c.StreamAllowedOrigins = append(c.StreamAllowedOrigins, o)
}
}
}
maxDisc := get(constants.CREDENTIAL_EVENTS_MAX_DISCONNECT, "10m")
if d, err := time.ParseDuration(maxDisc); err != nil || d < 30*time.Second || d > time.Hour {
errs = append(errs, fmt.Errorf("%s %q: must be a duration between 30s and 1h", constants.CREDENTIAL_EVENTS_MAX_DISCONNECT, maxDisc))
} else {
c.CredentialEventsMaxDisconnect = d
}
if _, _, err := net.SplitHostPort(c.BindAddress); err != nil {
errs = append(errs, fmt.Errorf("BIND_ADDRESS %q: %w", c.BindAddress, err))
}
if !logLevels[c.LogLevel] {
errs = append(errs, fmt.Errorf("%s %q: must be one of DEBUG, INFO, WARN, ERROR", constants.LOG_LEVEL, c.LogLevel))
}
errs = append(errs, checkURL(constants.OTEL_EXPORTER_OTLP_ENDPOINT, c.OTLPEndpoint, false)...)
errs = append(errs, checkURL(constants.AUTH_API_URL, c.AuthAPIURL, true)...)
errs = append(errs, checkURL(constants.USERS_API_URL, c.UsersAPIURL, true)...)
errs = append(errs, checkURL(constants.ENTITLEMENTS_API_URL, c.EntitlementsAPIURL, true)...)
if c.RedisHost == "" {
errs = append(errs, errors.New("REDIS_HOST: required"))
}
for _, o := range c.AllowedOrigins {
if strings.TrimSpace(o) == "*" {
errs = append(errs, fmt.Errorf("%s: wildcard origin is not allowed", constants.ALLOWED_ORIGINS))
}
}
return c, errors.Join(errs...)
}
// FromEnv is Load against the process environment.
func FromEnv() (Config, error) { return Load(os.LookupEnv) }
// checkURL validates an absolute http(s) URL; an empty value is an error only when required.
func checkURL(key, value string, required bool) []error {
if value == "" {
if required {
return []error{fmt.Errorf("%s: required", key)}
}
return nil
}
if u, err := url.Parse(value); err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return []error{fmt.Errorf("%s %q: must be an absolute http(s) URL", key, value)}
}
return nil
}
// matchesArbitraryHost reports whether pattern matches hosts it does not name (such as "**" or
// "*?*"), which would defeat the ban on a wildcard origin.
func matchesArbitraryHost(pattern string) bool {
for _, host := range []string{"a.b", "zz.example.test", "q"} {
if ok, _ := path.Match(pattern, host); ok {
return true
}
}
return false
}
package data
import (
"fmt"
"strings"
"unicode/utf8"
)
// 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).
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
)
// CheckText requires s to be at most max runes. what names the field in the error.
func CheckText(what, s string, max int) error {
if utf8.RuneCountInString(s) > max {
return fmt.Errorf("%w: %s is longer than %d characters", ErrInvalid, what, max)
}
return nil
}
// CheckName requires a non-empty (after trimming) name of at most MaxNameLen runes.
func CheckName(what, s string) error {
if strings.TrimSpace(s) == "" {
return fmt.Errorf("%w: %s is required", ErrInvalid, what)
}
return CheckText(what, s, MaxNameLen)
}
// 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 CheckMaps(what string, health map[string]int, refs map[string]string) error {
if len(health) > MaxMapEntries || len(refs) > MaxMapEntries {
return fmt.Errorf("%w: %s has more than %d health values or external references", ErrInvalid, what, MaxMapEntries)
}
for k := range health {
if err := CheckText(what+" health key", k, maxRefLen); err != nil {
return err
}
}
for k, v := range refs {
if err := CheckText(what+" external reference key", k, maxRefLen); err != nil {
return err
}
if err := CheckText(what+" external reference value", v, maxRefLen); err != nil {
return err
}
}
return nil
}
package data
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/sweetrpg/initiative-api/store"
"go.mongodb.org/mongo-driver/bson"
)
// Change request statuses.
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"
)
// ClaimTimeout is how long an approving claim is left alone before another approval may resume it.
const ClaimTimeout = 60 * time.Second
// MaxPendingChangeRequests bounds one player's open requests in a session, so a client cannot
// grow the collection without limit while the GM is away.
const MaxPendingChangeRequests = 50
// maxCancelSweeps bounds how many requests one session deletion cancels in a pass: far more
// members than a session may have (20 plus the GM) times each one's pending cap. A session over
// it fails the deletion, which a retry continues.
const maxCancelSweeps = 100 * MaxPendingChangeRequests
// 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.
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"`
}
// 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.
func (r ChangeRequest) MarshalJSON() ([]byte, error) {
type plain ChangeRequest
if r.Status == ChangeApproving {
r.Status, r.DecidedBy = ChangePending, ""
}
return json.Marshal(plain(r))
}
// 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.
type ChangeRequests struct {
c store.Collection
now func() time.Time
}
// NewChangeRequests builds the repository on db.
func NewChangeRequests(db store.Database) *ChangeRequests {
return &ChangeRequests{c: db.Collection(CollectionChangeRequests), now: func() time.Time { return time.Now().UTC() }}
}
// 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 (r *ChangeRequests) Create(ctx context.Context, v Viewer, req ChangeRequest) (ChangeRequest, error) {
if v.level != ViewPlayer || v.session == "" || checkUserID(v.actor) != nil {
return ChangeRequest{}, ErrForbidden
}
n, err := r.c.CountDocuments(ctx, bson.D{{Key: "session_id", Value: v.session}, {Key: "requested_by", Value: v.actor}, {Key: "status", Value: ChangePending}})
if err != nil {
return ChangeRequest{}, err
}
// Count-then-insert: concurrent submissions can overrun the cap by at most the number of
// requests in flight at once, which one player's connection count bounds.
if n >= MaxPendingChangeRequests {
return ChangeRequest{}, invalid("you have %d change requests waiting for the GM; wait for some to be decided", n)
}
req.ID, req.SessionID, req.RequestedBy = newID(), v.session, v.actor
req.Status, req.CreatedAt = ChangePending, r.now()
if err := r.c.InsertOne(ctx, req); err != nil {
return ChangeRequest{}, err
}
return req.forViewer(v), nil
}
// forViewer is the request as v may read it. Only GM-level viewers see the encounter revisions
// (base_revision, applied_revision); everyone else orders by view_tag and never reads a revision.
func (r ChangeRequest) forViewer(v Viewer) ChangeRequest {
if v.level != ViewGM {
r.BaseRevision, r.AppliedRevision = 0, 0
}
return r
}
// 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 (r *ChangeRequests) List(ctx context.Context, v Viewer, encounterID, status string, q Query) (Page[ChangeRequest], error) {
encounterID, ok := cleanID(encounterID)
if !ok {
return Page[ChangeRequest]{}, ErrNotFound
}
base := bson.D{{Key: "session_id", Value: v.session}, {Key: "encounter_id", Value: encounterID}}
switch v.level {
case ViewGM:
case ViewPlayer:
base = append(base, bson.E{Key: "requested_by", Value: v.actor})
default:
return Page[ChangeRequest]{}, ErrForbidden
}
if v.session == "" {
return Page[ChangeRequest]{}, ErrForbidden
}
q = byCreated(q)
switch status {
case "":
case ChangePending:
q.Filters = append(q.Filters, Filter{Field: "status", Op: OpIn, Values: []any{ChangePending, ChangeApproving}})
default:
q.Filters = append(q.Filters, Filter{Field: "status", Op: OpEq, Values: []any{status}})
}
page, err := runQuery[ChangeRequest](ctx, r.c, ChangeRequestSpec, base, q)
for i := range page.Items {
page.Items[i] = page.Items[i].forViewer(v)
}
return page, err
}
// Load reads one change request of the decision's session and encounter. d must grant can_edit.
func (r *ChangeRequests) Load(ctx context.Context, d Decision, encounterID, id string) (ChangeRequest, error) {
var req ChangeRequest
if err := d.require(relEdit); err != nil {
return req, err
}
id, ok := cleanID(id)
encounterID, eok := cleanID(encounterID)
if !ok || !eok {
return req, ErrNotFound
}
err := r.c.FindOne(ctx, bson.D{{Key: "_id", Value: id}, {Key: "session_id", Value: d.session}, {Key: "encounter_id", Value: encounterID}}, &req)
if errors.Is(err, store.ErrNotFound) {
return req, ErrNotFound
}
return req, err
}
// 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 (r *ChangeRequests) Reject(ctx context.Context, d Decision, encounterID, id, reason string) (ChangeRequest, error) {
return r.settle(ctx, d, encounterID, id, bson.E{Key: "status", Value: ChangePending},
bson.D{{Key: "status", Value: ChangeRejected}, {Key: "decided_by", Value: d.actor}, {Key: "decided_at", Value: r.now()}, {Key: "reason", Value: reason}})
}
// 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 (r *ChangeRequests) Claim(ctx context.Context, d Decision, encounterID, id string) (ChangeRequest, error) {
now := r.now()
open := bson.E{Key: "$or", Value: bson.A{
bson.D{{Key: "status", Value: ChangePending}},
bson.D{{Key: "status", Value: ChangeApproving}, {Key: "claimed_at", Value: bson.D{{Key: "$lte", Value: now.Add(-ClaimTimeout)}}}},
}}
return r.settle(ctx, d, encounterID, id, open,
bson.D{{Key: "status", Value: ChangeApproving}, {Key: "decided_by", Value: d.actor}, {Key: "claimed_at", Value: now}})
}
// 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 (r *ChangeRequests) Finish(ctx context.Context, d Decision, encounterID, id string, revision int64) (ChangeRequest, error) {
return r.settle(ctx, d, encounterID, id, bson.E{Key: "$and", Value: bson.A{
bson.D{{Key: "status", Value: ChangeApproving}}, bson.D{{Key: "decided_by", Value: d.actor}}}},
bson.D{{Key: "status", Value: ChangeApproved}, {Key: "decided_at", Value: r.now()}, {Key: "applied_revision", Value: revision}})
}
// Unclaim puts a request this decision claimed back to pending, for an approval whose encounter
// write failed.
func (r *ChangeRequests) Unclaim(ctx context.Context, d Decision, encounterID, id string) error {
if err := d.require(relEdit); err != nil {
return err
}
id, ok := cleanID(id)
encounterID, eok := cleanID(encounterID)
if !ok || !eok {
return ErrNotFound
}
var discard ChangeRequest
err := r.c.FindOneAndUpdate(ctx,
bson.D{{Key: "_id", Value: id}, {Key: "session_id", Value: d.session}, {Key: "encounter_id", Value: encounterID},
{Key: "status", Value: ChangeApproving}, {Key: "decided_by", Value: d.actor}},
bson.D{{Key: "$set", Value: bson.D{{Key: "status", Value: ChangePending}}},
{Key: "$unset", Value: bson.D{{Key: "decided_by", Value: ""}, {Key: "claimed_at", Value: ""}}}}, &discard)
if errors.Is(err, store.ErrNotFound) {
return ErrNotFound
}
return err
}
// settle applies set to the request if it is in the state open describes, in one atomic write. When
// nothing matched, a request that exists is ErrConflict and one that does not is ErrNotFound.
func (r *ChangeRequests) settle(ctx context.Context, d Decision, encounterID, id string, open bson.E, set bson.D) (ChangeRequest, error) {
var req ChangeRequest
if err := d.require(relEdit); err != nil {
return req, err
}
id, ok := cleanID(id)
encounterID, eok := cleanID(encounterID)
if !ok || !eok {
return req, ErrNotFound
}
filter := bson.D{{Key: "_id", Value: id}, {Key: "session_id", Value: d.session}, {Key: "encounter_id", Value: encounterID}}
err := r.c.FindOneAndUpdate(ctx, append(filter, open), bson.D{{Key: "$set", Value: set}}, &req)
if !errors.Is(err, store.ErrNotFound) {
return req, err
}
if ferr := r.c.FindOne(ctx, filter, &req); ferr == nil {
return req, ErrConflict
}
return req, ErrNotFound
}
// 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 (r *ChangeRequests) CancelSession(ctx context.Context, d Decision) error {
if err := d.require(relGM); err != nil {
return err
}
for range maxCancelSweeps {
var discard ChangeRequest
err := r.c.FindOneAndUpdate(ctx,
bson.D{{Key: "session_id", Value: d.session}, {Key: "status", Value: bson.D{{Key: "$in", Value: bson.A{ChangePending, ChangeApproving}}}}},
bson.D{{Key: "$set", Value: bson.D{{Key: "status", Value: ChangeCancelled}, {Key: "decided_by", Value: d.actor}, {Key: "decided_at", Value: r.now()}}}}, &discard)
if errors.Is(err, store.ErrNotFound) {
return nil
}
if err != nil {
return err
}
}
return fmt.Errorf("%w: more than %d change requests waiting in one session; retry delete", ErrInvalid, maxCancelSweeps)
}
// 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 (r *ChangeRequests) CancelPending(ctx context.Context, d Decision, userID string) error {
need := relEdit
if userID == d.actor {
need = relView
}
if err := pairOK(d, need, userID); err != nil {
return err
}
for range MaxPendingChangeRequests + 1 {
var discard ChangeRequest
err := r.c.FindOneAndUpdate(ctx,
bson.D{{Key: "session_id", Value: d.session}, {Key: "requested_by", Value: userID},
{Key: "status", Value: bson.D{{Key: "$in", Value: bson.A{ChangePending, ChangeApproving}}}}},
bson.D{{Key: "$set", Value: bson.D{{Key: "status", Value: ChangeCancelled}, {Key: "decided_by", Value: d.actor}, {Key: "decided_at", Value: r.now()}}}}, &discard)
if errors.Is(err, store.ErrNotFound) {
return nil
}
if err != nil {
return err
}
}
return nil
}
package data
import (
"context"
"log/slog"
"regexp"
"time"
)
// 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.
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"
)
// 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 Origin struct {
Kind string // user, integration, or system
ClientID string
ActorID string
}
// Origin kinds.
const (
OriginUser = "user"
OriginIntegration = "integration"
OriginSystem = "system"
)
var clientIDPattern = regexp.MustCompile(`^[A-Za-z0-9._-]{1,64}$`)
// ValidClientID reports whether v may be recorded as an origin client id. A bad value is ignored,
// never rejected.
func ValidClientID(v string) bool { return clientIDPattern.MatchString(v) }
type opKey struct{}
type originKey struct{}
type op struct {
typ string
ids []string
}
// 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 WithOp(ctx context.Context, eventType string, combatantIDs ...string) context.Context {
return context.WithValue(ctx, opKey{}, op{eventType, combatantIDs})
}
// WithOrigin records who is making the writes on ctx.
func WithOrigin(ctx context.Context, o Origin) context.Context {
return context.WithValue(ctx, originKey{}, o)
}
func opOf(ctx context.Context) op {
o, _ := ctx.Value(opKey{}).(op)
if o.typ == "" {
o.typ = EventUpdated
}
return o
}
func originOf(ctx context.Context) Origin {
o, _ := ctx.Value(originKey{}).(Origin)
if o.Kind == "" {
o.Kind = OriginSystem
}
return o
}
// 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 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
}
// 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 Sink interface {
Emit(ctx context.Context, c Change)
}
// SetSink installs the sink for every encounter commit made through r. It is set once at
// startup; with none, commits emit nothing.
func (r *Encounters) SetSink(s Sink) {
r.sink = s
r.commit = func(ctx context.Context, kind commitKind, before, after *Encounter) {
r.emitCommit(ctx, kind, before, *after)
}
}
type commitKind int
const (
commitCreate commitKind = iota
commitWrite
commitDelete
commitFlag
)
func (r *Encounters) emitCommit(ctx context.Context, kind commitKind, before *Encounter, after Encounter) {
if r.sink == nil {
return
}
c := Change{After: after, Before: before, SessionID: after.SessionID, OwnerID: after.OwnerUserID, Origin: originOf(ctx), At: r.now()}
switch kind {
case commitCreate:
c.Type = EventCreated
case commitDelete:
c.Type = EventDeleted
case commitFlag:
c.Type, c.GMOnly = EventUpdated, true
default:
o := opOf(ctx)
c.Type, c.CombatantID = o.typ, o.ids
}
r.deliver(ctx, c)
}
// deliver hands c to the sink. A sink that panics must never fail a write that already
// committed, so the panic is recovered and logged.
func (r *Encounters) deliver(ctx context.Context, c Change) {
defer func() {
if p := recover(); p != nil {
slog.ErrorContext(ctx, "an encounter event sink panicked", "encounter", c.After.ID, "type", c.Type, "panic", p)
}
}()
r.sink.Emit(ctx, c)
}
// emit sends a change the caller built itself (scrub, release, retract), for the cases the
// generic commit hook does not cover.
func (r *Encounters) emit(ctx context.Context, c Change) {
if r.sink == nil {
return
}
c.Origin, c.At = originOf(ctx), r.now()
r.deliver(ctx, c)
}
package data
import (
"context"
"errors"
"fmt"
"regexp"
"strings"
"time"
"github.com/sweetrpg/initiative-api/store"
"go.mongodb.org/mongo-driver/bson"
)
// 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 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"`
}
// ownerPattern is the shape of a user id (Auth0 subject or users-api id). An owner filter taken
// from a request must match it, so only a plain id can reach a query.
var ownerPattern = regexp.MustCompile(`^[A-Za-z0-9_.|:-]{1,128}$`)
func checkOwner(owner string) error {
if owner != "" && !ownerPattern.MatchString(owner) {
return invalid("owner is not a valid user id")
}
return nil
}
// 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 (r *Credentials) ListAll(ctx context.Context, q Query) (Page[IntegrationCredential], error) {
if len(q.Sort) == 0 {
q.Sort = []SortKey{{Field: "created_at", Desc: true}}
}
return runQuery[IntegrationCredential](ctx, r.c, r.spec, bson.D{{Key: "deleted_at", Value: nil}}, q)
}
// ListOwned is the owner-scoped List for an owner id taken from an administrator's request.
func (r *Credentials) ListOwned(ctx context.Context, owner string, q Query) (Page[IntegrationCredential], error) {
if err := checkOwner(owner); err != nil {
return Page[IntegrationCredential]{}, err
}
if len(q.Sort) == 0 {
q.Sort = []SortKey{{Field: "created_at", Desc: true}}
}
return r.List(ctx, owner, q)
}
// 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 (r *Credentials) Live(ctx context.Context, id string) (bool, error) {
id, ok := cleanID(id)
if !ok {
return false, nil
}
var c IntegrationCredential
filter := bson.D{{Key: "_id", Value: id}, {Key: "revoked_at", Value: nil}, {Key: "deleted_at", Value: nil}, {Key: "inactive_at", Value: nil}}
err := r.c.FindOne(ctx, filter, &c)
if errors.Is(err, store.ErrNotFound) {
return false, nil
}
return err == nil, err
}
// 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 (r *Credentials) DeletePermanently(ctx context.Context, actor, id, reason string) (CredentialDeletion, error) {
var out CredentialDeletion
if strings.TrimSpace(actor) == "" || strings.TrimSpace(reason) == "" {
return out, fmt.Errorf("%w: administrator and reason are required", ErrInvalid)
}
id, ok := cleanID(id)
if !ok {
return out, ErrNotFound
}
var c IntegrationCredential
err := r.c.FindOne(ctx, bson.D{{Key: "_id", Value: id}}, &c)
if errors.Is(err, store.ErrNotFound) {
return out, ErrNotFound
}
if err != nil {
return out, err
}
out = CredentialDeletion{
CredentialID: c.ID, OwnerUserID: c.OwnerUserID, Label: c.Label, Scopes: c.Scopes,
Reason: strings.TrimSpace(reason), CreatedBy: actor, CreatedAt: r.now(),
}
// A duplicate means an earlier attempt wrote the entry: return that stored row, so the
// response and log match what the audit collection holds.
if err := r.deletions.InsertOne(ctx, out); errors.Is(err, store.ErrDuplicate) {
if err := r.deletions.FindOne(ctx, bson.D{{Key: "_id", Value: id}}, &out); err != nil {
return CredentialDeletion{}, err
}
} else if err != nil {
return CredentialDeletion{}, err
}
if err := r.c.DeleteOne(ctx, bson.D{{Key: "_id", Value: id}}); err != nil && !errors.Is(err, store.ErrNotFound) {
return CredentialDeletion{}, err
}
return out, nil
}
// DeletionSpec pages the audit entries, newest first.
var DeletionSpec = Spec{
Name: CollectionCredentialDeletions,
Sortable: []string{"created_at"},
}
// 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 (r *Credentials) Deletions(ctx context.Context, owner string, q Query) (Page[CredentialDeletion], error) {
if err := checkOwner(owner); err != nil {
return Page[CredentialDeletion]{}, err
}
if len(q.Sort) == 0 {
q.Sort = []SortKey{{Field: "created_at", Desc: true}}
}
if owner == "" {
return runQuery[CredentialDeletion](ctx, r.deletions, DeletionSpec, bson.D{}, q)
}
return runQuery[CredentialDeletion](ctx, r.deletions, DeletionSpec, bson.D{{Key: "owner_user_id", Value: owner}}, q)
}
package data
import (
"context"
"errors"
"fmt"
"strings"
"github.com/sweetrpg/initiative-api/store"
"go.mongodb.org/mongo-driver/bson"
)
// 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.
type Credentials struct {
*Owned[IntegrationCredential, *IntegrationCredential]
gate, deletions store.Collection
}
// NewCredentials builds the credential repository for db.
func NewCredentials(db store.Database) *Credentials {
return &Credentials{NewOwned[IntegrationCredential](db, CredentialSpec), db.Collection(CollectionCredentialGate), db.Collection(CollectionCredentialDeletions)}
}
// activeScope is owner's credentials that are neither revoked nor deleted.
func activeScope(owner string) bson.D {
return append(scope(owner), bson.E{Key: "revoked_at", Value: nil})
}
// ItemStates lists owner's unrevoked credentials; a revoked one no longer counts toward the limit.
func (r *Credentials) ItemStates(ctx context.Context, owner string) ([]ItemState, error) {
if err := checkUserID(owner); err != nil {
return nil, err
}
return r.itemStates(ctx, activeScope(owner))
}
// CountActive counts owner's credentials that can still authenticate.
func (r *Credentials) CountActive(ctx context.Context, owner string) (int64, error) {
if err := checkUserID(owner); err != nil {
return 0, err
}
return r.c.CountDocuments(ctx, activeScope(owner))
}
// 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 (r *Credentials) Revoke(ctx context.Context, owner, actor, id string) (IntegrationCredential, error) {
var out IntegrationCredential
if err := requireOwnerActor(owner, actor); err != nil {
return out, err
}
id, ok := cleanID(id)
if !ok {
return out, ErrNotFound
}
now := r.now()
update := bson.D{
{Key: "$set", Value: bson.D{{Key: "revoked_at", Value: now}, {Key: "updated_at", Value: now}, {Key: "updated_by", Value: actor}}},
{Key: "$inc", Value: bson.D{{Key: "revision", Value: 1}}},
}
filter := append(scopeID(owner, id), bson.E{Key: "revoked_at", Value: nil})
err := r.c.FindOneAndUpdate(ctx, filter, update, &out)
if !errors.Is(err, store.ErrNotFound) {
return out, err
}
// Nothing matched: already revoked (fine), someone else's, or missing.
cur, gerr := r.Get(ctx, owner, id)
if gerr == nil {
return cur, nil
}
if errors.Is(gerr, ErrNotFound) {
_, cerr := r.classify(ctx, owner, id)
if cerr != nil && !errors.Is(cerr, ErrRevisionConflict) {
return out, cerr
}
}
return out, gerr
}
// 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 (r *Credentials) Authenticate(ctx context.Context, secretHash string) (IntegrationCredential, error) {
var out IntegrationCredential
if secretHash == "" {
return out, ErrNotFound
}
filter := bson.D{{Key: "secret_hash", Value: secretHash}, {Key: "revoked_at", Value: nil}, {Key: "deleted_at", Value: nil}, {Key: "inactive_at", Value: nil}}
update := bson.D{{Key: "$set", Value: bson.D{{Key: "last_used_at", Value: r.now()}}}}
err := r.c.FindOneAndUpdate(ctx, filter, update, &out)
if errors.Is(err, store.ErrNotFound) {
return out, ErrNotFound
}
return out, err
}
// Revoke reasons the platform sets (PADR-0039).
const (
ReasonOwnerDenied = "owner_denied"
ReasonOwnerRoleRemoved = "owner_role_removed"
)
// 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 (r *Credentials) RevokeAllByOwner(ctx context.Context, owner, reason string) (int, error) {
if strings.TrimSpace(owner) == "" || strings.TrimSpace(reason) == "" {
return 0, fmt.Errorf("%w: owner and reason are required", ErrInvalid)
}
n := 0
for {
now := r.now()
update := bson.D{
{Key: "$set", Value: bson.D{{Key: "revoked_at", Value: now}, {Key: "revoke_reason", Value: reason}, {Key: "updated_at", Value: now}, {Key: "updated_by", Value: reason}}},
{Key: "$inc", Value: bson.D{{Key: "revision", Value: 1}}},
}
var out IntegrationCredential
err := r.c.FindOneAndUpdate(ctx, activeScope(owner), update, &out)
if errors.Is(err, store.ErrNotFound) {
return n, nil
}
if err != nil {
return n, err
}
n++
}
}
const gateID = "gate"
// GateClosed reports whether the persisted gate is closed. No document means open.
func (r *Credentials) GateClosed(ctx context.Context) (bool, error) {
var doc struct {
Closed bool `bson:"closed"`
}
err := r.gate.FindOne(ctx, bson.D{{Key: "_id", Value: gateID}}, &doc)
if errors.Is(err, store.ErrNotFound) {
return false, nil
}
return doc.Closed, err
}
// SetGate persists the gate state so a restart cannot reopen it before a reconcile.
func (r *Credentials) SetGate(ctx context.Context, closed bool, actor string) error {
col := r.gate
filter := bson.D{{Key: "_id", Value: gateID}}
update := bson.D{{Key: "$set", Value: bson.D{{Key: "closed", Value: closed}, {Key: "updated_at", Value: r.now()}, {Key: "updated_by", Value: actor}}}}
var out bson.M
err := col.FindOneAndUpdate(ctx, filter, update, &out)
if !errors.Is(err, store.ErrNotFound) {
return err
}
err = col.InsertOne(ctx, bson.D{{Key: "_id", Value: gateID}, {Key: "closed", Value: closed}, {Key: "updated_at", Value: r.now()}, {Key: "updated_by", Value: actor}})
if errors.Is(err, store.ErrDuplicate) {
return col.FindOneAndUpdate(ctx, filter, update, &out)
}
return err
}
package data
import (
"context"
"github.com/sweetrpg/initiative-api/relations"
)
// 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.
type Decision struct {
actor, session, relation string
}
// Actor returns the user the decision was made for.
func (d Decision) Actor() string { return d.actor }
// SessionID returns the session the decision covers.
func (d Decision) SessionID() string { return d.session }
// Relations on a session, weakest first. The model (auth-api fga/model.fga) makes can_edit and
// can_approve the same set (gm or co_gm), gm a subset of that, and can_view everyone.
const (
relView = "can_view"
relEdit = "can_edit"
relApprove = "can_approve"
relGM = "gm"
)
var relationRank = map[string]int{relView: 1, relEdit: 2, relApprove: 2, relGM: 3}
// require refuses the zero Decision and any decision made for a weaker relation than min, so a
// can_view grant (any observer) cannot be spent on a write that needs can_edit.
func (d Decision) require(min string) error {
if d.actor == "" || d.session == "" || relationRank[d.relation] == 0 || relationRank[d.relation] < relationRank[min] {
return ErrForbidden
}
return nil
}
// RelationChecker answers whether the holder of token has relation on object.
// *relations.Client implements it.
type RelationChecker interface {
Check(ctx context.Context, user, token, object, relation string) (bool, error)
}
type gate struct {
checker RelationChecker
token string
}
type gateKey struct{}
// 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 WithGate(ctx context.Context, c RelationChecker, token string) context.Context {
return context.WithValue(ctx, gateKey{}, gate{c, token})
}
// 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 Authorize(ctx context.Context, actor, sessionID, relation string) (Decision, error) {
if err := checkUserID(actor); err != nil {
return Decision{}, err
}
id, ok := cleanID(sessionID)
if !ok {
return Decision{}, ErrNotFound
}
g, ok := ctx.Value(gateKey{}).(gate)
if !ok || g.checker == nil {
return Decision{}, relations.ErrUnavailable
}
allowed, err := g.checker.Check(ctx, actor, g.token, "session:"+id, relation)
if err != nil {
return Decision{}, err
}
if !allowed {
return Decision{}, ErrForbidden
}
return Decision{actor: actor, session: id, relation: relation}, nil
}
package data
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"maps"
"slices"
"strings"
"github.com/sweetrpg/initiative-api/store"
"go.mongodb.org/mongo-driver/bson"
)
var (
orderings = []string{OrderHighToLow, OrderLowToHigh, OrderPCVsAdversary, OrderPlayerManaged}
tieBreakers = []string{TieRandom, TieAlphabetical, TieQuery}
statuses = []string{StatusDraft, StatusActive, StatusEnded}
)
// Encounters is the owner-scoped encounter repository. It validates enumerated values and
// queue references before any write reaches the collection.
type Encounters struct {
*Owned[Encounter, *Encounter]
systems *SystemRepo
sink Sink
}
// NewEncounters builds the encounter repository for db.
func NewEncounters(db store.Database) *Encounters {
o := NewOwned[Encounter](db, EncounterSpec)
o.extra = bson.D{{Key: "session_id", Value: nil}}
o.exclude = func(e *Encounter) bool { return e.SessionID != "" }
return &Encounters{Owned: o, systems: NewSystemRepo(db)}
}
// 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 ValidateEncounter(e *Encounter) error {
if err := CheckText("encounter name", e.Name, MaxNameLen); err != nil { // required-ness is the domain's rule
return err
}
if err := CheckText("theme_id", e.ThemeID, MaxThemeIDLen); err != nil {
return err
}
if e.Position < 0 {
return fmt.Errorf("%w: position %d", ErrInvalid, e.Position)
}
if !slices.Contains(orderings, e.Ordering) {
return fmt.Errorf("%w: ordering %q", ErrInvalid, e.Ordering)
}
if !slices.Contains(tieBreakers, e.TieBreaker) {
return fmt.Errorf("%w: tie_breaker %q", ErrInvalid, e.TieBreaker)
}
return ValidateState(EncounterState{Status: e.Status, Round: e.Round,
CurrentCombatantID: e.CurrentCombatantID, TurnQueue: e.TurnQueue, Combatants: e.Combatants})
}
// EncounterState is the live combat state of an encounter, written as one unit.
type EncounterState struct {
Status string
Round int
CurrentCombatantID string
TurnQueue []string
Combatants []Combatant
}
// 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 ValidateState(st EncounterState) error {
if !slices.Contains(statuses, st.Status) {
return fmt.Errorf("%w: status %q", ErrInvalid, st.Status)
}
if st.Round < 0 {
return fmt.Errorf("%w: round %d", ErrInvalid, st.Round)
}
if len(st.Combatants) > MaxCombatants {
return fmt.Errorf("%w: an encounter holds at most %d combatants", ErrInvalid, MaxCombatants)
}
ids := make(map[string]bool, len(st.Combatants))
for _, c := range st.Combatants {
if err := validateCombatant(c); err != nil {
return err
}
if ids[c.ID] {
return fmt.Errorf("%w: duplicate combatant id %q", ErrInvalid, c.ID)
}
ids[c.ID] = true
}
if st.CurrentCombatantID != "" && !ids[st.CurrentCombatantID] {
return fmt.Errorf("%w: current combatant %q is not a combatant", ErrInvalid, st.CurrentCombatantID)
}
for _, id := range st.TurnQueue {
if !ids[id] {
return fmt.Errorf("%w: turn_queue entry %q is not a combatant", ErrInvalid, id)
}
}
return nil
}
func validateEncounterSet(set map[string]any) error {
if v, ok := set["name"]; ok {
s, isStr := v.(string)
if !isStr {
return fmt.Errorf("%w: name must be a string", ErrInvalid)
}
if err := CheckName("encounter name", s); err != nil {
return err
}
}
if v, ok := set["theme_id"]; ok {
s, isStr := v.(string)
if !isStr {
return fmt.Errorf("%w: theme_id must be a string", ErrInvalid)
}
if err := CheckText("theme_id", s, MaxThemeIDLen); err != nil {
return err
}
}
if v, ok := set["position"]; ok {
if n, isInt := v.(int); !isInt || n < 0 {
return fmt.Errorf("%w: position must be a non-negative integer", ErrInvalid)
}
}
if v, ok := set["game_system_id"]; ok {
if s, isStr := v.(string); !isStr || strings.TrimSpace(s) == "" {
return fmt.Errorf("%w: game_system_id must be a non-empty string", ErrInvalid)
}
}
if v, ok := set["ordering"]; ok {
if s, isStr := v.(string); !isStr || !slices.Contains(orderings, s) {
return fmt.Errorf("%w: ordering %v", ErrInvalid, v)
}
}
if v, ok := set["tie_breaker"]; ok {
if s, isStr := v.(string); !isStr || !slices.Contains(tieBreakers, s) {
return fmt.Errorf("%w: tie_breaker %v", ErrInvalid, v)
}
}
return nil
}
// 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 (r *Encounters) Create(ctx context.Context, ownerUserID, actingUserID string, e *Encounter) error {
e.Status, e.Round, e.CurrentCombatantID, e.TurnQueue = StatusDraft, 0, "", nil
if err := ValidateEncounter(e); err != nil {
return err
}
if err := r.checkHealth(ctx, e.GameSystemID, e.Combatants, nil); err != nil {
return err
}
e.RefKeys = refKeys(e.Combatants)
return r.Owned.Create(ctx, ownerUserID, actingUserID, e)
}
// CountAll returns how many live encounters owner holds, private and in a session alike. Both
// count against the saved-encounters limit.
func (r *Encounters) CountAll(ctx context.Context, owner string) (int64, error) {
if err := checkUserID(owner); err != nil {
return 0, err
}
return r.c.CountDocuments(ctx, scope(owner))
}
// 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 (r *Encounters) Update(ctx context.Context, ownerUserID, actingUserID, id string, expectedRevision int64, set map[string]any) (Encounter, error) {
if err := validateEncounterSet(set); err != nil {
return Encounter{}, err
}
if sysID, ok := set["game_system_id"].(string); ok {
if err := r.requireSystem(ctx, sysID); err != nil {
return Encounter{}, err
}
// Every combatant's health must fit the new system before the switch is stored.
cur, err := r.Load(ctx, ownerUserID, id)
if err != nil {
return Encounter{}, err
}
if err := r.checkHealth(ctx, sysID, cur.Combatants, nil); err != nil {
return Encounter{}, err
}
}
return r.Owned.Update(ctx, ownerUserID, actingUserID, id, expectedRevision, set)
}
func validateCombatant(c Combatant) error {
if strings.TrimSpace(c.Name) == "" {
return fmt.Errorf("%w: combatant %q has no name", ErrInvalid, c.ID)
}
if err := errors.Join(CheckText("combatant name", c.Name, MaxNameLen), CheckText("combatant notes", c.Notes, MaxNotesLen),
CheckMaps("combatant", c.Health, c.ExternalRefs)); err != nil {
return err
}
if len(c.Conditions) > MaxConditions || len(c.ControllerUserIDs) > MaxCombatants {
return fmt.Errorf("%w: combatant %q has too many conditions or controllers", ErrInvalid, c.ID)
}
if !slices.Contains(Kinds, c.Kind) {
return fmt.Errorf("%w: combatant %q kind %q", ErrInvalid, c.ID, c.Kind)
}
if !slices.Contains([]string{"", HealthFull, HealthStatus, HealthHidden}, c.HealthVisibility) {
return fmt.Errorf("%w: combatant %q health visibility %q", ErrInvalid, c.ID, c.HealthVisibility)
}
for _, cond := range c.Conditions {
if CheckText("condition name", cond.Name, MaxNameLen) != nil {
return fmt.Errorf("%w: combatant %q has a condition name over %d characters", ErrInvalid, c.ID, MaxNameLen)
}
if strings.TrimSpace(cond.Name) == "" || (cond.RoundsRemaining != nil && *cond.RoundsRemaining < 1) {
return fmt.Errorf("%w: combatant %q has an invalid condition", ErrInvalid, c.ID)
}
}
return nil
}
// requireSystem rejects a game system that has no definition. The No System fallback applies only
// to an encounter whose existing system lost its definition, never to choosing one: creating an
// encounter and switching its system both require the definition to exist.
func (r *Encounters) requireSystem(ctx context.Context, sysID string) error {
_, err := r.systems.Get(ctx, sysID)
if errors.Is(err, ErrNotFound) {
return invalid("the game system is not defined")
}
return err
}
// checkHealth validates the health of each combatant in cs against the encounter's game system
// definition (the default system when the encounter's has none). Only combatants that are new or
// whose health differs from existing are checked, so a stored value that a later definition change
// made invalid does not block unrelated edits. The system is looked up only when something needs
// checking.
func (r *Encounters) checkHealth(ctx context.Context, sysID string, cs, existing []Combatant) error {
before := make(map[string]map[string]int, len(existing))
for _, c := range existing {
before[c.ID] = c.Health
}
var changed []Combatant
for _, c := range cs {
if prev, ok := before[c.ID]; len(c.Health) > 0 && (!ok || !maps.Equal(prev, c.Health)) {
changed = append(changed, c)
}
}
if len(changed) == 0 {
return nil
}
sys, err := r.systems.GetOrDefault(ctx, sysID)
if errors.Is(err, ErrNotFound) {
return invalid("the encounter's game system has no definition and no default system is defined")
}
if err != nil {
return err
}
for _, c := range changed {
if err := CheckHealth(sys, c.Health); err != nil {
return err
}
}
return nil
}
// SetState validates st and writes it as the encounter's combat state with the revision check.
func (r *Encounters) SetState(ctx context.Context, ownerUserID, actingUserID, id string, expectedRevision int64, st EncounterState) (Encounter, error) {
return r.Write(ctx, ownerUserID, actingUserID, id, expectedRevision, nil, st)
}
// 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.
func (r *Encounters) Write(ctx context.Context, ownerUserID, actingUserID, id string, expectedRevision int64, settings map[string]any, st EncounterState) (Encounter, error) {
if err := validateEncounterSet(settings); err != nil {
return Encounter{}, err
}
if err := ValidateState(st); err != nil {
return Encounter{}, err
}
if sysID, ok := settings["game_system_id"].(string); ok {
if err := r.requireSystem(ctx, sysID); err != nil {
return Encounter{}, err
}
}
if slices.ContainsFunc(st.Combatants, func(c Combatant) bool { return len(c.Health) > 0 }) {
cur, err := r.Load(ctx, ownerUserID, id)
if err != nil {
return Encounter{}, err
}
sysID := cur.GameSystemID
if v, ok := settings["game_system_id"].(string); ok {
sysID = v
}
existing := cur.Combatants
if _, switched := settings["game_system_id"]; switched {
existing = nil // a new system: every combatant's health is checked afresh
}
if err := r.checkHealth(ctx, sysID, st.Combatants, existing); err != nil {
return Encounter{}, err
}
}
state := map[string]any{
"status": st.Status, "round": st.Round, "current_combatant_id": st.CurrentCombatantID,
"turn_queue": nonNil(st.TurnQueue), "combatants": nonNilC(st.Combatants),
"ref_keys": nonNil(refKeys(st.Combatants)),
}
return r.updateBoth(ctx, ownerUserID, actingUserID, id, expectedRevision, settings, state)
}
func nonNil(s []string) []string {
if s == nil {
return []string{}
}
return s
}
func nonNilC(s []Combatant) []Combatant {
if s == nil {
return []Combatant{}
}
return s
}
// Load reads owner's encounter; a miss is classified 403 (another owner's) or 404 (absent).
func (r *Encounters) Load(ctx context.Context, owner, id string) (Encounter, error) {
cur, err := r.Get(ctx, owner, id)
if errors.Is(err, ErrNotFound) {
if cerr := r.Missing(ctx, owner, id); cerr != nil {
return Encounter{}, cerr
}
}
return cur, err
}
const (
maxRefLen = 200
maxRefMatches = 100
)
// 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 RefKey(key, value string) string {
sum := sha256.Sum256([]byte(fmt.Sprintf("%d:%s%s", len(key), key, value)))
return hex.EncodeToString(sum[:])
}
// refKeys derives Encounter.RefKeys from the live (not removed) combatants.
func refKeys(cs []Combatant) []string {
var out []string
for _, c := range cs {
if c.Removed {
continue
}
for k, v := range c.ExternalRefs {
out = append(out, RefKey(k, v))
}
}
slices.Sort(out)
return slices.Compact(out)
}
// RefMatch is a combatant whose external_refs hold a looked-up pair, with its encounter's ID.
type RefMatch struct {
EncounterID string `json:"encounter_id"`
Combatant Combatant `json:"combatant"`
}
// 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 (r *Encounters) FindByExternalRef(ctx context.Context, owner, key, value string) ([]RefMatch, error) {
if err := checkUserID(owner); err != nil {
return nil, err
}
if key == "" || value == "" || len(key) > maxRefLen || len(value) > maxRefLen {
return nil, invalid("ref_key and ref_value are required, at most %d bytes", maxRefLen)
}
// Private encounters only: a session encounter is read through the session's role-aware view,
// so an owner who has left or been demoted cannot reach hidden combatants or GM-only notes here.
filter := append(scope(owner), bson.E{Key: "ref_keys", Value: RefKey(key, value)}, bson.E{Key: "session_id", Value: nil})
var encs []Encounter
if err := r.c.Find(ctx, filter, store.FindOptions{Limit: maxRefMatches}, &encs); err != nil {
return nil, err
}
var out []RefMatch
for _, e := range encs {
for _, c := range e.Combatants {
if !c.Removed && c.ExternalRefs[key] == value {
out = append(out, RefMatch{EncounterID: e.ID, Combatant: c})
}
}
}
return out, nil
}
// 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 (r *Encounters) LockGated(ctx context.Context, owner string) (int, error) {
filter := append(scope(owner),
bson.E{Key: "game_system_id", Value: bson.D{{Key: "$ne", Value: DefaultSystemID}}},
bson.E{Key: "locked_at", Value: nil})
return r.flip(ctx, filter, bson.D{{Key: "$set", Value: bson.D{{Key: "locked_at", Value: r.now()}}}})
}
// UnlockAll restores owner's locked encounters exactly as they were.
func (r *Encounters) UnlockAll(ctx context.Context, owner string) (int, error) {
filter := append(scope(owner), bson.E{Key: "locked_at", Value: bson.D{{Key: "$ne", Value: nil}}})
return r.flip(ctx, filter, bson.D{{Key: "$unset", Value: bson.D{{Key: "locked_at", Value: ""}}}})
}
func (r *Encounters) flip(ctx context.Context, filter, update bson.D) (int, error) {
n := 0
for {
var out Encounter
err := r.c.FindOneAndUpdate(ctx, filter, update, &out)
if errors.Is(err, store.ErrNotFound) {
return n, nil
}
if err != nil {
return n, err
}
r.emitCommit(ctx, commitFlag, nil, out)
n++
}
}
package data
import (
"fmt"
"maps"
"slices"
)
// HealthError reports the health field that failed validation. It wraps ErrInvalid.
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
}
func (e *HealthError) Error() string { return fmt.Sprintf("health field %q: %s", e.Field, e.Reason) }
// Unwrap lets errors.Is match ErrInvalid.
func (e *HealthError) Unwrap() error { return ErrInvalid }
// 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 CheckHealth(sys GameSystem, h map[string]int) error {
return checkHealthKeys(sys, h, slices.Sorted(maps.Keys(h)))
}
// checkHealthKeys is CheckHealth for only the named keys of h; the other keys of h are read only as
// the MaxRef values the named keys are bounded by.
func checkHealthKeys(sys GameSystem, h map[string]int, keys []string) error {
fields := make(map[string]TrackerField, len(sys.Fields))
for _, f := range sys.Fields {
fields[f.Key] = f
}
for _, k := range keys {
v := h[k]
f, ok := fields[k]
if !ok {
return &HealthError{Field: k, Reason: "not defined by the game system", Unknown: true}
}
if f.Kind == FieldFlag && v != 0 && v != 1 {
return &HealthError{Field: k, Reason: fmt.Sprintf("%d is not 0 or 1", v)}
}
if f.Min != nil && v < *f.Min {
return &HealthError{Field: k, Reason: fmt.Sprintf("%d is below the minimum %d", v, *f.Min)}
}
if f.Max != nil && v > *f.Max {
return &HealthError{Field: k, Reason: fmt.Sprintf("%d is above the maximum %d", v, *f.Max)}
}
if ref, ok := h[f.MaxRef]; f.MaxRef != "" && ok && v > ref {
return &HealthError{Field: k, Reason: fmt.Sprintf("%d is above %s (%d)", v, f.MaxRef, ref)}
}
}
return nil
}
package data
import (
"context"
"errors"
"fmt"
"time"
"github.com/sweetrpg/initiative-api/store"
"go.mongodb.org/mongo-driver/bson"
)
// ItemState is what limit enforcement needs to know about one stored item.
type ItemState struct {
ID string
CreatedAt time.Time
KeepRank int
Inactive bool
}
// ItemStates lists owner's live items oldest first, for deciding which stay active.
func (r *Owned[T, P]) ItemStates(ctx context.Context, owner string) ([]ItemState, error) {
if err := checkUserID(owner); err != nil {
return nil, err
}
return r.itemStates(ctx, r.scoped(owner))
}
func (r *Owned[T, P]) itemStates(ctx context.Context, filter bson.D) ([]ItemState, error) {
var docs []T
opts := store.FindOptions{
Sort: bson.D{{Key: "created_at", Value: 1}, {Key: "_id", Value: 1}},
Projection: bson.D{{Key: "created_at", Value: 1}, {Key: "keep_rank", Value: 1}, {Key: "inactive_at", Value: 1}},
}
if err := r.c.Find(ctx, filter, opts, &docs); err != nil {
return nil, err
}
out := make([]ItemState, 0, len(docs))
for i := range docs {
m := P(&docs[i]).GetMeta()
out = append(out, ItemState{ID: m.ID, CreatedAt: m.CreatedAt, KeepRank: m.KeepRank, Inactive: m.InactiveAt != nil})
}
return out, nil
}
// 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 (r *Owned[T, P]) SetInactive(ctx context.Context, owner, id string, inactive bool) error {
if err := checkUserID(owner); err != nil {
return err
}
id, ok := cleanID(id)
if !ok {
return ErrNotFound
}
var update bson.D
if inactive {
update = bson.D{{Key: "$set", Value: bson.D{{Key: "inactive_at", Value: r.now()}}}}
} else {
update = bson.D{{Key: "$unset", Value: bson.D{{Key: "inactive_at", Value: ""}}}}
}
var after T
err := r.c.FindOneAndUpdate(ctx, r.scopedID(owner, id), update, &after)
if errors.Is(err, store.ErrNotFound) {
return ErrNotFound
}
if err == nil {
r.committed(ctx, commitFlag, nil, &after)
}
return err
}
// 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 (r *Owned[T, P]) SetKeepRanks(ctx context.Context, owner string, ids []string) error {
states, err := r.ItemStates(ctx, owner)
if err != nil {
return err
}
want := make(map[string]int, len(ids))
for i, id := range ids {
want[id] = i + 1
}
for _, st := range states {
if st.KeepRank == want[st.ID] {
continue
}
update := bson.D{{Key: "$unset", Value: bson.D{{Key: "keep_rank", Value: ""}}}}
if n := want[st.ID]; n > 0 {
update = bson.D{{Key: "$set", Value: bson.D{{Key: "keep_rank", Value: n}}}}
}
var discard T
if err := r.c.FindOneAndUpdate(ctx, r.scopedID(owner, st.ID), update, &discard); err != nil && !errors.Is(err, store.ErrNotFound) {
return fmt.Errorf("set keep rank: %w", err)
}
}
return nil
}
// 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").
package data
import (
"time"
"github.com/sweetrpg/model-core.go/models"
)
// Meta is embedded (inline) in every owner-scoped document: identity, owner, revision, and the
// platform audit fields (PADR-0001).
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"`
}
// GetMeta lets generic code reach the embedded Meta through the document pointer.
func (m *Meta) GetMeta() *Meta { return m }
package data
import (
"context"
"errors"
"slices"
"time"
"github.com/sweetrpg/initiative-api/store"
"go.mongodb.org/mongo-driver/bson"
)
// CollectionNotificationPrefs holds each user's muted notice types per session.
const CollectionNotificationPrefs = "notification_preferences"
// NotificationPrefSpec: one document per user and session, addressed only by the caller's own id.
var NotificationPrefSpec = Spec{
Name: CollectionNotificationPrefs,
Indexes: []store.IndexSpec{{Name: "user_session", Keys: asc("user_id", "session_id"), Unique: true}},
}
type notificationPrefDoc struct {
UserID string `bson:"user_id"`
SessionID string `bson:"session_id"`
Muted []string `bson:"muted"`
UpdatedAt time.Time `bson:"updated_at"`
}
// 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.
type NotificationPrefs struct {
c store.Collection
now func() time.Time
}
// NewNotificationPrefs builds the repository on db.
func NewNotificationPrefs(db store.Database) *NotificationPrefs {
return &NotificationPrefs{c: db.Collection(CollectionNotificationPrefs), now: func() time.Time { return time.Now().UTC() }}
}
// Muted returns the notice types ownerUserID has turned off for sessionID; none when nothing is
// stored.
func (r *NotificationPrefs) Muted(ctx context.Context, ownerUserID, sessionID string) ([]string, error) {
if err := checkUserID(ownerUserID); err != nil {
return nil, err
}
id, ok := cleanID(sessionID)
if !ok {
return nil, invalid("session id is not valid")
}
var doc notificationPrefDoc
err := r.c.FindOne(ctx, prefScope(ownerUserID, id), &doc)
if errors.Is(err, store.ErrNotFound) {
return []string{}, nil
}
if err != nil {
return nil, err
}
return doc.Muted, nil
}
// SetMuted replaces ownerUserID's muted types for sessionID in one atomic upsert. Unknown types
// are rejected; duplicates collapse.
func (r *NotificationPrefs) SetMuted(ctx context.Context, ownerUserID, sessionID string, muted []string) ([]string, error) {
if err := checkUserID(ownerUserID); err != nil {
return nil, err
}
id, ok := cleanID(sessionID)
if !ok {
return nil, invalid("session id is not valid")
}
if len(muted) > len(NoticeTypes) {
return nil, invalid("at most %d notification types can be muted", len(NoticeTypes))
}
clean := make([]string, 0, len(muted))
for _, m := range muted {
if !slices.Contains(NoticeTypes, m) {
return nil, invalid("%q is not a notification type", m)
}
if !slices.Contains(clean, m) {
clean = append(clean, m)
}
}
slices.Sort(clean)
set := bson.D{{Key: "muted", Value: clean}, {Key: "updated_at", Value: r.now()}}
if err := r.c.UpsertOne(ctx, prefScope(ownerUserID, id), bson.D{{Key: "$set", Value: set}}); err != nil {
return nil, err
}
return clean, nil
}
func prefScope(ownerUserID, sessionID string) bson.D {
return bson.D{{Key: "user_id", Value: ownerUserID}, {Key: "session_id", Value: sessionID}}
}
package data
import (
"context"
"errors"
"fmt"
"maps"
"sort"
"strings"
"time"
"github.com/sweetrpg/initiative-api/store"
"github.com/sweetrpg/model-core.go/models"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
// Doc constrains P to a pointer to a document type that embeds Meta.
type Doc[T any] interface {
*T
GetMeta() *Meta
}
// 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.
type Owned[T any, P Doc[T]] struct {
c store.Collection
spec Spec
now func() time.Time
newID func() string
// extra narrows every owner-scoped read and write beyond ownership, and exclude says which
// stored documents that narrowing hides, so a miss is classified 403 instead of reading as a
// revision conflict that would return the hidden document. Encounters use them to keep the
// owner path to private encounters: a session encounter is reached only through its session
// (PADR-0035), so an owner who left or was demoted cannot read or change it here.
extra bson.D
exclude func(*T) bool
// commit, when set, is told about every successful create, write, soft delete and flag change
// with the stored document, so one place can announce them (see Encounters.SetSink).
commit func(ctx context.Context, kind commitKind, before, after *T)
}
func (r *Owned[T, P]) committed(ctx context.Context, kind commitKind, before, after *T) {
if r.commit != nil {
r.commit(ctx, kind, before, after)
}
}
// NewOwned builds the repository for spec's collection in db.
func NewOwned[T any, P Doc[T]](db store.Database, spec Spec) *Owned[T, P] {
return &Owned[T, P]{
c: db.Collection(spec.Name),
spec: spec,
now: func() time.Time { return time.Now().UTC() },
newID: func() string { return primitive.NewObjectID().Hex() },
}
}
// scope is the filter every owner-scoped query starts from.
func scope(owner string) bson.D {
return bson.D{{Key: "owner_user_id", Value: owner}, {Key: "deleted_at", Value: nil}}
}
// scopeID is the owner-scoped filter for one record. id must already have passed cleanID.
func scopeID(owner, id string) bson.D {
return append(bson.D{{Key: "_id", Value: id}}, scope(owner)...)
}
// scoped is scope plus the repository's extra narrowing.
func (r *Owned[T, P]) scoped(owner string) bson.D {
return append(scope(owner), r.extra...)
}
// scopedID is scopeID plus the repository's extra narrowing.
func (r *Owned[T, P]) scopedID(owner, id string) bson.D {
return append(bson.D{{Key: "_id", Value: id}}, r.scoped(owner)...)
}
// cleanID returns the canonical form of a client-supplied record ID, or false when it is not a
// 24-character hex ObjectID. Every ID that reaches a query filter goes through here, so a request
// value can only ever be a plain ObjectID string, never an operator document or arbitrary text.
func cleanID(id string) (string, bool) {
oid, err := primitive.ObjectIDFromHex(id)
if err != nil {
return "", false
}
return oid.Hex(), true
}
// requireOwnerActor refuses a write with no valid owner or acting user id.
func requireOwnerActor(owner, actor string) error {
if err := checkUserID(owner); err != nil {
return err
}
return checkUserID(actor)
}
// 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 (r *Owned[T, P]) Create(ctx context.Context, ownerUserID, actingUserID string, doc P) error {
return r.createWithID(ctx, ownerUserID, actingUserID, "", doc)
}
// createWithID is Create with a caller-chosen ID; an empty id means generate one.
func (r *Owned[T, P]) createWithID(ctx context.Context, ownerUserID, actingUserID, id string, doc P) error {
if err := requireOwnerActor(ownerUserID, actingUserID); err != nil {
return err
}
m := doc.GetMeta()
m.ID = id
if id == "" {
m.ID = r.newID()
}
m.OwnerUserID = ownerUserID
m.Revision = 1
m.DeletedAt, m.DeletedBy = nil, nil
models.StampCreate(&m.Auditable, actingUserID, r.now())
if err := r.mapDuplicate(r.c.InsertOne(ctx, doc)); err != nil {
return err
}
r.committed(ctx, commitCreate, nil, (*T)(doc))
return nil
}
// mapDuplicate turns a unique-index rejection into ErrConflict for specs that opt in.
func (r *Owned[T, P]) mapDuplicate(err error) error {
if r.spec.ConflictOnDuplicate && errors.Is(err, store.ErrDuplicate) {
return ErrConflict
}
return err
}
// Get returns owner's live record. Another owner's record is indistinguishable from a missing
// one on reads.
func (r *Owned[T, P]) Get(ctx context.Context, ownerUserID, id string) (T, error) {
var out T
if err := checkUserID(ownerUserID); err != nil {
return out, err
}
id, ok := cleanID(id)
if !ok {
return out, ErrNotFound
}
err := r.c.FindOne(ctx, r.scopedID(ownerUserID, id), &out)
if errors.Is(err, store.ErrNotFound) {
return out, ErrNotFound
}
return out, err
}
// reservedFields are managed by the data layer and rejected in Update's set.
var reservedFields = map[string]bool{
"_id": true, "owner_user_id": true, "revision": true,
"created_at": true, "created_by": true, "updated_at": true, "updated_by": true,
"deleted_at": true, "deleted_by": true,
}
func validateSet(spec Spec, set map[string]any) error {
if len(set) == 0 {
return fmt.Errorf("%w: nothing to update", ErrInvalid)
}
for k := range set {
if reservedFields[k] || strings.HasPrefix(k, "$") || strings.Contains(k, ".") || k == "" {
return fmt.Errorf("%w: field %q cannot be set", ErrInvalid, k)
}
if !in(spec.Updatable, k) {
return fmt.Errorf("%w: field %q is not updatable on %s", ErrInvalid, k, spec.Name)
}
}
return nil
}
func setDoc(set map[string]any, extra ...bson.E) bson.D {
keys := make([]string, 0, len(set))
for k := range set {
keys = append(keys, k)
}
sort.Strings(keys)
d := make(bson.D, 0, len(keys)+len(extra))
for _, k := range keys {
d = append(d, bson.E{Key: k, Value: set[k]})
}
return append(d, extra...)
}
// 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.
func (r *Owned[T, P]) Update(ctx context.Context, ownerUserID, actingUserID, id string, expectedRevision int64, set map[string]any) (T, error) {
var out T
if err := requireOwnerActor(ownerUserID, actingUserID); err != nil {
return out, err
}
if err := validateSet(r.spec, set); err != nil {
return out, err
}
return r.apply(ctx, ownerUserID, actingUserID, id, expectedRevision, set)
}
// updateState is Update for the spec's StateFields: values computed by domain rules, never taken
// from client input. Everything else about the write is identical (owner-scoped, compare-and-set,
// classified failures).
func (r *Owned[T, P]) updateState(ctx context.Context, ownerUserID, actingUserID, id string, expectedRevision int64, set map[string]any) (T, error) {
var out T
if err := requireOwnerActor(ownerUserID, actingUserID); err != nil {
return out, err
}
if len(set) == 0 {
return out, fmt.Errorf("%w: nothing to update", ErrInvalid)
}
for k := range set {
if !in(r.spec.StateFields, k) {
return out, fmt.Errorf("%w: field %q is not a state field of %s", ErrInvalid, k, r.spec.Name)
}
}
return r.apply(ctx, ownerUserID, actingUserID, id, expectedRevision, set)
}
// updateBoth writes settings (Updatable fields) and state (StateFields) in one atomic,
// compare-and-set write, for changes where a setting and the state derived from it must land
// together. Either map may be empty, not both.
func (r *Owned[T, P]) updateBoth(ctx context.Context, ownerUserID, actingUserID, id string, expectedRevision int64, settings, state map[string]any) (T, error) {
var out T
if err := requireOwnerActor(ownerUserID, actingUserID); err != nil {
return out, err
}
merged := make(map[string]any, len(settings)+len(state))
if len(settings) > 0 {
if err := validateSet(r.spec, settings); err != nil {
return out, err
}
maps.Copy(merged, settings)
}
for k, v := range state {
if !in(r.spec.StateFields, k) {
return out, fmt.Errorf("%w: field %q is not a state field of %s", ErrInvalid, k, r.spec.Name)
}
merged[k] = v
}
if len(merged) == 0 {
return out, fmt.Errorf("%w: nothing to update", ErrInvalid)
}
return r.apply(ctx, ownerUserID, actingUserID, id, expectedRevision, merged)
}
// readBefore reads the document a revision-guarded write is about to change, for the event the
// commit emits. It is kept only if it is at the revision the write is made against: the write
// matches that revision or fails, so a kept document is exactly what the write changed. Anything
// else (no sink, a miss, a concurrent edit) is nil, and the event is built without a before.
func (r *Owned[T, P]) readBefore(ctx context.Context, owner, id string, expectedRevision int64) *T {
if r.commit == nil {
return nil
}
var b T
if err := r.c.FindOne(ctx, r.scopedID(owner, id), &b); err != nil || P(&b).GetMeta().Revision != expectedRevision {
return nil
}
return &b
}
func (r *Owned[T, P]) apply(ctx context.Context, ownerUserID, actingUserID, id string, expectedRevision int64, set map[string]any) (T, error) {
var out T
id, ok := cleanID(id)
if !ok {
return out, ErrNotFound
}
filter := append(r.scopedID(ownerUserID, id), bson.E{Key: "revision", Value: expectedRevision}, bson.E{Key: "inactive_at", Value: nil}, bson.E{Key: "locked_at", Value: nil})
update := bson.D{
{Key: "$set", Value: setDoc(set,
bson.E{Key: "updated_at", Value: r.now()}, bson.E{Key: "updated_by", Value: actingUserID})},
{Key: "$inc", Value: bson.D{{Key: "revision", Value: 1}}},
}
before := r.readBefore(ctx, ownerUserID, id, expectedRevision)
err := r.c.FindOneAndUpdate(ctx, filter, update, &out)
if errors.Is(err, store.ErrNotFound) {
cur, cerr := r.classify(ctx, ownerUserID, id)
if errors.Is(cerr, ErrRevisionConflict) {
var zero T
switch m := P(&cur).GetMeta(); {
case m.LockedAt != nil:
return zero, ErrLocked
case m.InactiveAt != nil:
return zero, ErrInactive
}
}
return cur, cerr
}
if err = r.mapDuplicate(err); err == nil {
r.committed(ctx, commitWrite, before, &out)
}
return out, err
}
// 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 (r *Owned[T, P]) SoftDelete(ctx context.Context, ownerUserID, actingUserID, id string, expectedRevision int64) error {
if err := requireOwnerActor(ownerUserID, actingUserID); err != nil {
return err
}
now := r.now()
update := bson.D{
{Key: "$set", Value: bson.D{
{Key: "deleted_at", Value: now}, {Key: "deleted_by", Value: actingUserID},
{Key: "updated_at", Value: now}, {Key: "updated_by", Value: actingUserID}}},
{Key: "$inc", Value: bson.D{{Key: "revision", Value: 1}}},
}
if len(r.spec.UnsetOnDelete) > 0 {
unset := make(bson.D, 0, len(r.spec.UnsetOnDelete))
for _, f := range r.spec.UnsetOnDelete {
unset = append(unset, bson.E{Key: f, Value: ""})
}
update = append(update, bson.E{Key: "$unset", Value: unset})
}
id, ok := cleanID(id)
if !ok {
return ErrNotFound
}
var after T
filter := append(r.scopedID(ownerUserID, id), bson.E{Key: "revision", Value: expectedRevision})
err := r.c.FindOneAndUpdate(ctx, filter, update, &after)
if errors.Is(err, store.ErrNotFound) {
_, err = r.classify(ctx, ownerUserID, id)
}
if err == nil {
r.committed(ctx, commitDelete, nil, &after)
}
return err
}
// 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 (r *Owned[T, P]) Missing(ctx context.Context, owner, id string) error {
if err := checkUserID(owner); err != nil {
return err
}
if _, err := r.classify(ctx, owner, id); !errors.Is(err, ErrRevisionConflict) {
return err
}
return nil
}
// classify runs only after an owner-scoped write matched nothing. It does an owner-agnostic
// lookup to tell 404 from 403 from 409; it never grants access.
func (r *Owned[T, P]) classify(ctx context.Context, owner, id string) (T, error) {
var cur T
id, ok := cleanID(id)
if !ok {
return cur, ErrNotFound
}
err := r.c.FindOne(ctx, bson.D{{Key: "_id", Value: id}}, &cur)
if errors.Is(err, store.ErrNotFound) {
return cur, ErrNotFound
}
if err != nil {
return cur, err
}
m := P(&cur).GetMeta()
switch {
case m.DeletedAt == nil && m.OwnerUserID == owner && r.exclude != nil && r.exclude(&cur):
var zero T
return zero, ErrForbidden
case m.DeletedAt != nil:
var zero T
return zero, ErrNotFound
case m.OwnerUserID != owner:
var zero T
return zero, ErrForbidden
}
return cur, ErrRevisionConflict
}
package data
import (
"context"
"errors"
"strings"
"time"
"github.com/sweetrpg/initiative-api/store"
"go.mongodb.org/mongo-driver/bson"
)
// CollectionOwnerEntitlements holds the last entitlement values read with each user's own bearer.
const CollectionOwnerEntitlements = "owner_entitlements"
// OwnerEntitlement is one recorded key: a limit or a flag, and when it was read.
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"`
}
// ownerEntitlementDoc keys entries by encoded entitlement key so each is written on its own.
type ownerEntitlementDoc struct {
UserID string `bson:"_id"`
Entries map[string]OwnerEntitlement `bson:"entries"`
}
// entryField encodes a key for use as a document field name, which cannot contain ".".
func entryField(key string) string {
return strings.NewReplacer("%", "%25", ".", "%2E", "$", "%24").Replace(key)
}
// 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.
type OwnerEntitlements struct {
c store.Collection
maxAge time.Duration
now func() time.Time
}
// NewOwnerEntitlements builds the repository on db. A recorded value older than maxAge is no
// longer fresh (see Fresh).
func NewOwnerEntitlements(db store.Database, maxAge time.Duration) *OwnerEntitlements {
return &OwnerEntitlements{c: db.Collection(CollectionOwnerEntitlements), maxAge: maxAge, now: func() time.Time { return time.Now().UTC() }}
}
// 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.
func (r *OwnerEntitlements) Record(ctx context.Context, userID string, entries ...OwnerEntitlement) error {
if err := checkUserID(userID); err != nil {
return err
}
if len(entries) == 0 {
return nil
}
at := r.now()
set := make(bson.D, 0, len(entries))
for _, e := range entries {
e.ReadAt = at
set = append(set, bson.E{Key: "entries." + entryField(e.Key), Value: e})
}
return r.c.UpsertOne(ctx, bson.D{{Key: "_id", Value: userID}}, bson.D{{Key: "$set", Value: set}})
}
// Fresh reports whether e was read no longer than the configured max age ago.
func (r *OwnerEntitlements) Fresh(e OwnerEntitlement) bool {
return r.now().Sub(e.ReadAt) <= r.maxAge
}
// 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 (r *OwnerEntitlements) Get(ctx context.Context, userID, key string) (OwnerEntitlement, error) {
if err := checkUserID(userID); err != nil {
return OwnerEntitlement{}, err
}
var doc ownerEntitlementDoc
err := r.c.FindOne(ctx, bson.D{{Key: "_id", Value: userID}}, &doc)
if errors.Is(err, store.ErrNotFound) {
return OwnerEntitlement{}, ErrNotFound
}
if err != nil {
return OwnerEntitlement{}, err
}
e, ok := doc.Entries[entryField(key)]
if !ok {
return OwnerEntitlement{}, ErrNotFound
}
return e, nil
}
package data
import (
"context"
"encoding/base64"
"fmt"
"regexp"
"github.com/sweetrpg/initiative-api/store"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
// List bounds.
const (
DefaultLimit = 50
MaxLimit = 200
maxInValues = 100
maxValueLen = 128
)
// 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).
type Op string
// Filter operators.
const (
OpEq Op = "eq"
OpIn Op = "in"
OpContains Op = "contains"
)
// 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 Filter struct {
Field string
Op Op
Values []any
}
// SortKey orders a list. _id is always appended as the final tie-break so paging is stable.
type SortKey struct {
Field string
Desc bool
}
// 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 Query struct {
Filters []Filter
Sort []SortKey
Fields []string
Limit int
Cursor string
}
// Page is one page of results; NextCursor is empty on the last page.
type Page[T any] struct {
Items []T
NextCursor string
}
func invalid(format string, a ...any) error {
return fmt.Errorf("%w: %s", ErrInvalid, fmt.Sprintf(format, a...))
}
func in(list []string, s string) bool {
for _, x := range list {
if x == s {
return true
}
}
return false
}
// scalar admits only plain values, so a nested document can never smuggle in an operator.
func scalar(v any) (any, bool) {
switch x := v.(type) {
case string, bool, int64:
return x, true
case int:
return int64(x), true
case float64:
if x == float64(int64(x)) {
return int64(x), true
}
}
return nil, false
}
func filterClause(spec Spec, f Filter) (bson.D, error) {
if !in(spec.Filterable, f.Field) {
return nil, invalid("cannot filter by %q", f.Field)
}
vals := make(bson.A, 0, len(f.Values))
for _, v := range f.Values {
s, ok := scalar(v)
if !ok {
return nil, invalid("filter %q has a non-scalar value", f.Field)
}
vals = append(vals, s)
}
switch f.Op {
case OpEq:
if len(vals) != 1 {
return nil, invalid("eq on %q needs exactly one value", f.Field)
}
return bson.D{{Key: f.Field, Value: vals[0]}}, nil
case OpIn:
if len(vals) == 0 || len(vals) > maxInValues {
return nil, invalid("in on %q needs 1 to %d values", f.Field, maxInValues)
}
return bson.D{{Key: f.Field, Value: bson.D{{Key: "$in", Value: vals}}}}, nil
case OpContains:
s, ok := firstString(vals)
if len(vals) != 1 || !ok || s == "" || len(s) > maxValueLen {
return nil, invalid("contains on %q needs one non-empty string up to %d bytes", f.Field, maxValueLen)
}
return bson.D{{Key: f.Field, Value: bson.D{{Key: "$regex", Value: regexp.QuoteMeta(s)}, {Key: "$options", Value: "i"}}}}, nil
}
return nil, invalid("unknown operator %q", f.Op)
}
func firstString(v bson.A) (string, bool) {
if len(v) == 0 {
return "", false
}
s, ok := v[0].(string)
return s, ok
}
func sortKeys(spec Spec, in2 []SortKey) ([]SortKey, error) {
keys := append([]SortKey(nil), in2...)
seen := map[string]bool{}
for _, k := range keys {
if k.Field != "_id" && !in(spec.Sortable, k.Field) {
return nil, invalid("cannot sort by %q", k.Field)
}
if seen[k.Field] {
return nil, invalid("sort field %q repeated", k.Field)
}
seen[k.Field] = true
}
if !seen["_id"] {
keys = append(keys, SortKey{Field: "_id"})
}
return keys, nil
}
func projection(spec Spec, fields []string, keys []SortKey) (bson.D, error) {
if len(fields) == 0 {
return nil, nil
}
p := bson.D{}
added := map[string]bool{"_id": true}
for _, f := range fields {
if !in(spec.Projectable, f) {
return nil, invalid("cannot project %q", f)
}
if !added[f] {
added[f] = true
p = append(p, bson.E{Key: f, Value: 1})
}
}
for _, k := range keys { // the cursor needs the sort values of the last row
if !added[k.Field] {
added[k.Field] = true
p = append(p, bson.E{Key: k.Field, Value: 1})
}
}
return p, nil
}
type plan struct {
filter bson.D
opts store.FindOptions
keys []SortKey
limit int
}
func buildPlan(spec Spec, base bson.D, q Query) (plan, error) {
if q.Limit < 0 {
return plan{}, invalid("limit must not be negative")
}
limit := q.Limit
if limit == 0 {
limit = DefaultLimit
}
limit = min(limit, MaxLimit)
keys, err := sortKeys(spec, q.Sort)
if err != nil {
return plan{}, err
}
proj, err := projection(spec, q.Fields, keys)
if err != nil {
return plan{}, err
}
clauses, err := clausesFor(spec, base, q)
if err != nil {
return plan{}, err
}
if q.Cursor != "" {
vals, err := decodeCursor(q.Cursor, len(keys))
if err != nil {
return plan{}, err
}
clauses = append(clauses, after(keys, vals))
}
sortD := make(bson.D, 0, len(keys))
for _, k := range keys {
dir := 1
if k.Desc {
dir = -1
}
sortD = append(sortD, bson.E{Key: k.Field, Value: dir})
}
// Fetch one extra row to learn whether another page exists.
return plan{
filter: filterOf(clauses),
opts: store.FindOptions{Sort: sortD, Projection: proj, Limit: int64(limit + 1)},
keys: keys,
limit: limit,
}, nil
}
// filterOf ANDs clauses. MongoDB rejects an empty $and, so no clauses means an empty filter.
func filterOf(clauses bson.A) bson.D {
if len(clauses) == 0 {
return bson.D{}
}
return bson.D{{Key: "$and", Value: clauses}}
}
func clausesFor(spec Spec, base bson.D, q Query) (bson.A, error) {
clauses := bson.A{}
if len(base) > 0 {
clauses = append(clauses, base)
}
for _, f := range q.Filters {
c, err := filterClause(spec, f)
if err != nil {
return nil, err
}
clauses = append(clauses, c)
}
return clauses, nil
}
// after builds the keyset condition for rows strictly after vals in sort order.
func after(keys []SortKey, vals []any) bson.D {
ors := make(bson.A, 0, len(keys))
for i := range keys {
and := bson.D{}
for j := 0; j < i; j++ {
and = append(and, bson.E{Key: keys[j].Field, Value: vals[j]})
}
op := "$gt"
if keys[i].Desc {
op = "$lt"
}
and = append(and, bson.E{Key: keys[i].Field, Value: bson.D{{Key: op, Value: vals[i]}}})
ors = append(ors, and)
}
return bson.D{{Key: "$or", Value: ors}}
}
func encodeCursor(vals []any) (string, error) {
b, err := bson.MarshalExtJSON(bson.M{"v": bson.A(vals)}, true, false)
return base64.RawURLEncoding.EncodeToString(b), err
}
func decodeCursor(c string, want int) ([]any, error) {
b, err := base64.RawURLEncoding.DecodeString(c)
if err != nil {
return nil, invalid("malformed cursor")
}
var m bson.M
if err := bson.UnmarshalExtJSON(b, true, &m); err != nil {
return nil, invalid("malformed cursor")
}
arr, ok := m["v"].(primitive.A)
if !ok || len(arr) != want {
return nil, invalid("cursor does not match this query's sort")
}
for _, v := range arr {
switch v.(type) {
case string, int32, int64, float64, bool, primitive.DateTime:
default:
return nil, invalid("malformed cursor")
}
}
return arr, nil
}
// cursorFor encodes the sort values of the last row on a page.
func cursorFor(item any, keys []SortKey) (string, error) {
raw, err := bson.Marshal(item)
if err != nil {
return "", err
}
var m bson.M
if err := bson.Unmarshal(raw, &m); err != nil {
return "", err
}
vals := make([]any, len(keys))
for i, k := range keys {
v, ok := m[k.Field]
if !ok || v == nil {
return "", invalid("cannot page: sort field %q is missing on a record", k.Field)
}
vals[i] = v
}
return encodeCursor(vals)
}
// runQuery applies q entirely in the database: filter, sort, projection, limit, and keyset
// cursor. base is the mandatory scope (owner and live-record filters) every caller supplies.
func runQuery[T any](ctx context.Context, c store.Collection, spec Spec, base bson.D, q Query) (Page[T], error) {
p, err := buildPlan(spec, base, q)
if err != nil {
return Page[T]{}, err
}
var items []T
if err := c.Find(ctx, p.filter, p.opts, &items); err != nil {
return Page[T]{}, err
}
if len(items) <= p.limit {
return Page[T]{Items: items}, nil
}
items = items[:p.limit]
next, err := cursorFor(items[p.limit-1], p.keys)
if err != nil {
return Page[T]{}, err
}
return Page[T]{Items: items, NextCursor: next}, nil
}
// List returns one page of owner's live records.
func (r *Owned[T, P]) List(ctx context.Context, ownerUserID string, q Query) (Page[T], error) {
if err := checkUserID(ownerUserID); err != nil {
return Page[T]{}, err
}
return runQuery[T](ctx, r.c, r.spec, r.scoped(ownerUserID), q)
}
// 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 (r *Owned[T, P]) Count(ctx context.Context, ownerUserID string, filters []Filter) (int64, error) {
if err := checkUserID(ownerUserID); err != nil {
return 0, err
}
clauses, err := clausesFor(r.spec, r.scoped(ownerUserID), Query{Filters: filters})
if err != nil {
return 0, err
}
return r.c.CountDocuments(ctx, filterOf(clauses))
}
package data
import (
"context"
"errors"
"fmt"
"slices"
"github.com/sweetrpg/initiative-api/store"
"go.mongodb.org/mongo-driver/bson"
)
// maxScrubRetries bounds how often a scrub re-reads an encounter that changed under it.
const maxScrubRetries = 3
// A scrub reads scrubPageSize encounters at a time and gives up after maxScrubPages pages.
const (
scrubPageSize = 100
maxScrubPages = 1000
)
// 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 (r *Encounters) UpdateInSession(ctx context.Context, d Decision, id string, expectedRevision int64, set map[string]any) (Encounter, error) {
var out Encounter
if err := d.require(relEdit); err != nil {
return out, err
}
id, ok := cleanID(id)
if !ok {
return out, ErrNotFound
}
cs, ok := set["combatants"].([]Combatant)
if !ok || len(set) != 1 {
return out, fmt.Errorf("%w: a session write sets combatants only", ErrInvalid)
}
if len(cs) > MaxCombatants {
return out, fmt.Errorf("%w: more than %d combatants", ErrInvalid, MaxCombatants)
}
for _, c := range cs {
if err := validateCombatant(c); err != nil {
return out, err
}
}
filter := bson.D{{Key: "_id", Value: id}, {Key: "session_id", Value: d.session}, {Key: "deleted_at", Value: nil},
{Key: "revision", Value: expectedRevision}, {Key: "inactive_at", Value: nil}, {Key: "locked_at", Value: nil}}
update := bson.D{
{Key: "$set", Value: bson.D{{Key: "combatants", Value: nonNilC(cs)}, {Key: "ref_keys", Value: nonNil(refKeys(cs))},
{Key: "updated_at", Value: r.now()}, {Key: "updated_by", Value: d.actor}}},
{Key: "$inc", Value: bson.D{{Key: "revision", Value: 1}}},
}
var before *Encounter
if r.commit != nil {
var b Encounter
if r.c.FindOne(ctx, bson.D{{Key: "_id", Value: id}, {Key: "session_id", Value: d.session}, {Key: "deleted_at", Value: nil}}, &b) == nil && b.Revision == expectedRevision {
before = &b
}
}
err := r.c.FindOneAndUpdate(ctx, filter, update, &out)
if errors.Is(err, store.ErrNotFound) {
return r.classifyInSession(ctx, d, id)
}
if err == nil {
r.emitCommit(ctx, commitWrite, before, out)
}
return out, err
}
// classifyInSession explains why a session write matched nothing.
func (r *Encounters) classifyInSession(ctx context.Context, d Decision, id string) (Encounter, error) {
var cur Encounter
err := r.c.FindOne(ctx, bson.D{{Key: "_id", Value: id}, {Key: "session_id", Value: d.session}, {Key: "deleted_at", Value: nil}}, &cur)
if errors.Is(err, store.ErrNotFound) {
return Encounter{}, ErrNotFound
}
if err != nil {
return Encounter{}, err
}
switch {
case cur.LockedAt != nil:
return Encounter{}, ErrLocked
case cur.InactiveAt != nil:
return Encounter{}, ErrInactive
}
return cur, ErrRevisionConflict
}
// 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 (r *Encounters) ScrubController(ctx context.Context, d Decision, userID string) error {
need := relEdit
if userID == d.actor {
need = relView
}
if err := pairOK(d, need, userID); err != nil {
return err
}
var errs []error
after := ""
for page := 0; ; page++ {
if page == maxScrubPages {
return errors.Join(append(errs, fmt.Errorf("%w: more than %d encounters list this controller", ErrInvalid, maxScrubPages*scrubPageSize))...)
}
filter := bson.D{{Key: "session_id", Value: d.session}, {Key: "deleted_at", Value: nil},
{Key: "combatants.controller_user_ids", Value: userID}}
if after != "" {
filter = append(filter, bson.E{Key: "_id", Value: bson.D{{Key: "$gt", Value: after}}})
}
var encs []Encounter
if err := r.c.Find(ctx, filter, store.FindOptions{Sort: bson.D{{Key: "_id", Value: 1}}, Limit: scrubPageSize}, &encs); err != nil {
return errors.Join(append(errs, err)...)
}
for _, e := range encs {
if err := r.scrubOne(ctx, d, e, userID); err != nil {
errs = append(errs, err)
}
after = e.ID
}
if len(encs) < scrubPageSize {
return errors.Join(errs...)
}
}
}
func (r *Encounters) scrubOne(ctx context.Context, d Decision, e Encounter, userID string) error {
for range maxScrubRetries {
cs, changed := withoutController(e.Combatants, userID)
if !changed {
return nil
}
filter := bson.D{{Key: "_id", Value: e.ID}, {Key: "session_id", Value: d.session}, {Key: "deleted_at", Value: nil}, {Key: "revision", Value: e.Revision}}
update := bson.D{
{Key: "$set", Value: bson.D{{Key: "combatants", Value: cs}, {Key: "updated_at", Value: r.now()}, {Key: "updated_by", Value: d.actor}}},
{Key: "$inc", Value: bson.D{{Key: "revision", Value: 1}}},
}
var after Encounter
err := r.c.FindOneAndUpdate(ctx, filter, update, &after)
if err == nil {
was := e
r.emit(ctx, Change{Type: EventControllers, Before: &was, After: after, SessionID: after.SessionID, OwnerID: after.OwnerUserID, CombatantID: controllerIDsChanged(e.Combatants, cs)})
}
if !errors.Is(err, store.ErrNotFound) {
return err
}
// The encounter changed or was deleted since it was read: re-read and try again.
if err := r.c.FindOne(ctx, bson.D{{Key: "_id", Value: e.ID}, {Key: "session_id", Value: d.session}, {Key: "deleted_at", Value: nil}}, &e); err != nil {
if errors.Is(err, store.ErrNotFound) {
return nil
}
return err
}
}
return fmt.Errorf("encounter %s kept changing while scrubbing a controller", e.ID)
}
// withoutController returns cs with userID removed from every controller list, and whether
// anything changed. The input is not modified.
func withoutController(cs []Combatant, userID string) ([]Combatant, bool) {
out := slices.Clone(cs)
changed := false
for i := range out {
if !slices.Contains(out[i].ControllerUserIDs, userID) {
continue
}
changed = true
out[i].ControllerUserIDs = slices.DeleteFunc(slices.Clone(out[i].ControllerUserIDs), func(u string) bool { return u == userID })
}
return out, changed
}
// 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 (r *Encounters) ReleaseSession(ctx context.Context, d Decision) error {
if err := d.require(relGM); err != nil {
return err
}
var errs []error
after := ""
for page := 0; ; page++ {
if page == maxScrubPages {
return errors.Join(append(errs, fmt.Errorf("%w: more than %d encounters in one session; retry delete", ErrInvalid, maxScrubPages*scrubPageSize))...)
}
filter := bson.D{{Key: "session_id", Value: d.session}, {Key: "deleted_at", Value: nil}}
if after != "" {
filter = append(filter, bson.E{Key: "_id", Value: bson.D{{Key: "$gt", Value: after}}})
}
var encs []Encounter
if err := r.c.Find(ctx, filter, store.FindOptions{Sort: bson.D{{Key: "_id", Value: 1}}, Limit: scrubPageSize}, &encs); err != nil {
return errors.Join(append(errs, err)...)
}
for _, e := range encs {
if err := r.releaseOne(ctx, d, e); err != nil {
errs = append(errs, err)
}
after = e.ID
}
if len(encs) < scrubPageSize {
return errors.Join(errs...)
}
}
}
func (r *Encounters) releaseOne(ctx context.Context, d Decision, e Encounter) error {
for range maxScrubRetries {
cs := slices.Clone(e.Combatants)
for i := range cs {
cs[i].ControllerUserIDs = nil
}
filter := bson.D{{Key: "_id", Value: e.ID}, {Key: "session_id", Value: d.session}, {Key: "deleted_at", Value: nil}, {Key: "revision", Value: e.Revision}}
update := bson.D{
{Key: "$set", Value: bson.D{{Key: "combatants", Value: nonNilC(cs)}, {Key: "owner_user_id", Value: d.actor},
{Key: "updated_at", Value: r.now()}, {Key: "updated_by", Value: d.actor}}},
{Key: "$unset", Value: bson.D{{Key: "session_id", Value: ""}}},
{Key: "$inc", Value: bson.D{{Key: "revision", Value: 1}}},
}
var after Encounter
err := r.c.FindOneAndUpdate(ctx, filter, update, &after)
if err == nil {
// The audience is the session the encounter belonged to before this write.
r.emit(ctx, Change{Type: EventReleased, After: after, SessionID: d.session, OwnerID: after.OwnerUserID})
}
if !errors.Is(err, store.ErrNotFound) {
return err
}
if err := r.c.FindOne(ctx, bson.D{{Key: "_id", Value: e.ID}, {Key: "session_id", Value: d.session}, {Key: "deleted_at", Value: nil}}, &e); err != nil {
if errors.Is(err, store.ErrNotFound) {
return nil
}
return err
}
}
return fmt.Errorf("encounter %s kept changing while its session was being deleted; retry delete", e.ID)
}
// 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 (r *Encounters) ValidateCombatantChange(ctx context.Context, gameSystemID string, before, after Combatant) error {
if err := validateCombatant(after); err != nil {
return err
}
var changed []string
for k, v := range after.Health {
if old, ok := before.Health[k]; !ok || old != v {
changed = append(changed, k)
}
}
if len(changed) == 0 {
return nil
}
sys, err := r.systems.GetOrDefault(ctx, gameSystemID)
if errors.Is(err, ErrNotFound) {
return invalid("the encounter's game system has no definition and no default system is defined")
}
if err != nil {
return err
}
slices.Sort(changed)
return checkHealthKeys(sys, after.Health, changed)
}
// 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 (r *Encounters) RetractNew(ctx context.Context, d Decision, id string) error {
if err := d.require(relEdit); err != nil {
return err
}
id, ok := cleanID(id)
if !ok {
return ErrNotFound
}
now := r.now()
var after Encounter
err := r.c.FindOneAndUpdate(ctx, bson.D{{Key: "_id", Value: id}, {Key: "session_id", Value: d.session}, {Key: "deleted_at", Value: nil}},
bson.D{{Key: "$set", Value: bson.D{{Key: "deleted_at", Value: now}, {Key: "deleted_by", Value: d.actor}, {Key: "updated_at", Value: now}, {Key: "updated_by", Value: d.actor}}},
{Key: "$inc", Value: bson.D{{Key: "revision", Value: 1}}}}, &after)
if errors.Is(err, store.ErrNotFound) {
return nil
}
if err == nil {
r.emit(ctx, Change{Type: EventDeleted, After: after, SessionID: d.session, OwnerID: after.OwnerUserID})
}
return err
}
// controllerIDsChanged returns the ids of combatants whose controllers differ between before and
// after (same order and length).
func controllerIDsChanged(before, after []Combatant) []string {
var ids []string
for i := range after {
if i < len(before) && !slices.Equal(before[i].ControllerUserIDs, after[i].ControllerUserIDs) {
ids = append(ids, after[i].ID)
}
}
return ids
}
package data
import (
"context"
"errors"
"fmt"
"time"
"github.com/sweetrpg/initiative-api/store"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
// Session roles.
const (
RoleGM = "gm"
RoleCoGM = "co_gm"
RolePlayer = "player"
RoleObserver = "observer"
)
// Join request states.
const (
RequestPending = "pending"
RequestApproved = "approved"
RequestRejected = "rejected"
)
// Session is a named group owned by one GM (the owner).
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:"-"`
}
// 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 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:"-"`
}
// Invite is a join code. Only its hash is stored, so the code is shown once, at creation.
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:"-"`
}
// JoinRequest is a user's pending, approved, or rejected request to join.
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:"-"`
}
// Block keeps a user from rejoining a session.
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:"-"`
}
// 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.
type Sessions struct {
owned *Owned[Session, *Session]
c store.Collection
members, invites, requests, blocks store.Collection
now func() time.Time
}
// NewSessions builds the repository on db.
func NewSessions(db store.Database) *Sessions {
o := NewOwned[Session](db, SessionSpec)
return &Sessions{
owned: o, c: o.c,
members: db.Collection(CollectionSessionMembers), invites: db.Collection(CollectionSessionInvites),
requests: db.Collection(CollectionSessionRequests), blocks: db.Collection(CollectionSessionBlocks),
now: func() time.Time { return time.Now().UTC() },
}
}
func newID() string { return primitive.NewObjectID().Hex() }
// Every read of a membership collection filters deleted_at (PADR-0027: these records are soft
// deleted), so the two scope helpers carry it.
func sessionScope(sessionID string) bson.D {
return bson.D{{Key: "session_id", Value: sessionID}, {Key: "deleted_at", Value: nil}}
}
func sessionUser(sessionID, userID string) bson.D {
return bson.D{{Key: "session_id", Value: sessionID}, {Key: "user_id", Value: userID}, {Key: "deleted_at", Value: nil}}
}
// softDelete marks the first live record matching filter deleted by actor and returns ErrNotFound
// when there is none.
func (r *Sessions) softDelete(ctx context.Context, c store.Collection, filter bson.D, actor string) error {
var gone bson.M
err := c.FindOneAndUpdate(ctx, filter, bson.D{
{Key: "$set", Value: bson.D{{Key: "deleted_at", Value: r.now()}, {Key: "deleted_by", Value: actor}}},
{Key: "$unset", Value: bson.D{{Key: "live", Value: ""}}},
}, &gone)
if errors.Is(err, store.ErrNotFound) {
return ErrNotFound
}
return err
}
// pairOK validates the user id a call acts on.
func pairOK(d Decision, min, userID string) error {
if err := d.require(min); err != nil {
return err
}
return checkUserID(userID)
}
// checkUserID requires a plain user id, so an id from a request cannot reach a query as anything
// else.
func checkUserID(u string) error {
if u == "" || !ownerPattern.MatchString(u) {
return invalid("user id is not valid")
}
return nil
}
// 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 (r *Sessions) Open(ctx context.Context, actor, id string, s *Session) error {
id, ok := cleanID(id)
if !ok {
return invalid("session id is not valid")
}
if err := r.owned.createWithID(ctx, actor, actor, id, s); err != nil {
return err
}
m := Member{ID: newID(), SessionID: s.ID, UserID: actor, Role: RoleGM, CreatedAt: r.now(), CreatedBy: actor, Live: true}
if err := r.members.InsertOne(ctx, m); err != nil {
// Without its GM the session could never be deleted, and it would count against
// sessions_per_gm. Remove it; if even that fails, say so, since the caller ends the mint.
if derr := r.owned.SoftDelete(ctx, actor, actor, s.ID, s.Revision); derr != nil {
return fmt.Errorf("%w (and removing the session failed: %v)", err, derr)
}
return err
}
return nil
}
// Count returns how many sessions owner has, including inactive ones.
func (r *Sessions) Count(ctx context.Context, owner string) (int64, error) {
return r.owned.Count(ctx, owner, nil)
}
// SoftDelete deletes the session at expectedRevision. Only the GM may.
func (r *Sessions) SoftDelete(ctx context.Context, d Decision, expectedRevision int64) error {
if err := d.require(relGM); err != nil {
return err
}
return r.owned.SoftDelete(ctx, d.actor, d.actor, d.session, expectedRevision)
}
// Update changes the session's settings at expectedRevision and returns it. Only the GM may.
func (r *Sessions) Update(ctx context.Context, d Decision, expectedRevision int64, set map[string]any) (Session, error) {
if err := d.require(relGM); err != nil {
return Session{}, err
}
return r.owned.Update(ctx, d.actor, d.actor, d.session, expectedRevision, set)
}
// 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 (r *Sessions) ResumeDeletion(ctx context.Context, actor, sessionID string) (Decision, error) {
if err := checkUserID(actor); err != nil {
return Decision{}, err
}
id, ok := cleanID(sessionID)
if !ok {
return Decision{}, ErrNotFound
}
var s Session
err := r.c.FindOne(ctx, bson.D{{Key: "_id", Value: id}, {Key: "owner_user_id", Value: actor}, {Key: "deleted_by", Value: actor},
{Key: "deleted_at", Value: bson.D{{Key: "$ne", Value: nil}}}}, &s)
if errors.Is(err, store.ErrNotFound) {
return Decision{}, ErrNotFound
}
if err != nil {
return Decision{}, err
}
return Decision{actor: actor, session: id, relation: relGM}, nil
}
// 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.
type LimitItems struct{ o *Owned[Session, *Session] }
// Limits returns the limit reconciler's view of the sessions.
func (r *Sessions) Limits() LimitItems { return LimitItems{r.owned} }
// ItemStates lists owner's sessions with their activity state.
func (l LimitItems) ItemStates(ctx context.Context, owner string) ([]ItemState, error) {
return l.o.ItemStates(ctx, owner)
}
// SetInactive sets or clears a session's inactive mark.
func (l LimitItems) SetInactive(ctx context.Context, owner, id string, inactive bool) error {
return l.o.SetInactive(ctx, owner, id, inactive)
}
// SetKeepRanks records the owner's keep order.
func (l LimitItems) SetKeepRanks(ctx context.Context, owner string, ids []string) error {
return l.o.SetKeepRanks(ctx, owner, ids)
}
// Live returns the session if it exists and is not deleted.
func (r *Sessions) Live(ctx context.Context, d Decision) (Session, error) {
var s Session
if err := d.require(relView); err != nil {
return s, err
}
err := r.c.FindOne(ctx, bson.D{{Key: "_id", Value: d.session}, {Key: "deleted_at", Value: nil}}, &s)
if errors.Is(err, store.ErrNotFound) {
return s, ErrNotFound
}
return s, err
}
// AddMember records userID in the session with role. An existing member is ErrConflict.
func (r *Sessions) AddMember(ctx context.Context, d Decision, userID, role string) (Member, error) {
if err := pairOK(d, relApprove, userID); err != nil {
return Member{}, err
}
m := Member{ID: newID(), SessionID: d.session, UserID: userID, Role: role, CreatedAt: r.now(), CreatedBy: d.actor, Live: true}
if err := r.members.InsertOne(ctx, m); errors.Is(err, store.ErrDuplicate) {
return Member{}, ErrConflict
} else if err != nil {
return Member{}, err
}
return m, nil
}
// Member returns userID's membership, or ErrNotFound.
func (r *Sessions) Member(ctx context.Context, d Decision, userID string) (Member, error) {
var m Member
if err := pairOK(d, relView, userID); err != nil {
return m, err
}
err := r.members.FindOne(ctx, sessionUser(d.session, userID), &m)
if errors.Is(err, store.ErrNotFound) {
return m, ErrNotFound
}
return m, err
}
// CountMembers returns how many live members the session has besides its GM: co-GMs, players and
// observers, the ones the member limit counts.
func (r *Sessions) CountMembers(ctx context.Context, d Decision) (int64, error) {
if err := d.require(relView); err != nil {
return 0, err
}
return r.members.CountDocuments(ctx, append(sessionScope(d.session), bson.E{Key: "role", Value: bson.D{{Key: "$ne", Value: RoleGM}}}))
}
func byCreated(q Query) Query {
if len(q.Sort) == 0 {
q.Sort = []SortKey{{Field: "created_at"}}
}
return q
}
// Members lists the session's members, oldest first.
func (r *Sessions) Members(ctx context.Context, d Decision, q Query) (Page[Member], error) {
if err := d.require(relView); err != nil {
return Page[Member]{}, err
}
return runQuery[Member](ctx, r.members, SessionMemberSpec, sessionScope(d.session), byCreated(q))
}
// 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 (r *Sessions) ManagerIDs(ctx context.Context, sessionID string) ([]string, error) {
var ms []Member
filter := bson.D{{Key: "session_id", Value: sessionID}, {Key: "role", Value: bson.D{{Key: "$in", Value: bson.A{RoleGM, RoleCoGM}}}}, {Key: "live", Value: bson.D{{Key: "$exists", Value: true}}}}
if err := r.members.Find(ctx, filter, store.FindOptions{Limit: maxManagers}, &ms); err != nil {
return nil, err
}
ids := make([]string, 0, len(ms))
for _, m := range ms {
ids = append(ids, m.UserID)
}
return ids, nil
}
// maxManagers bounds the managers one session can notify.
const maxManagers = 100
// 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 (r *Sessions) SessionIDsOf(ctx context.Context, userID string, q Query) (Page[Member], error) {
if err := checkUserID(userID); err != nil {
return Page[Member]{}, err
}
return runQuery[Member](ctx, r.members, SessionMemberSpec, bson.D{{Key: "user_id", Value: userID}, {Key: "deleted_at", Value: nil}}, byCreated(q))
}
// 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 (r *Sessions) RecordOwnerLimits(ctx context.Context, d Decision, limits map[string]int, flags map[string]bool) error {
if err := d.require(relView); err != nil {
return err
}
var discard Session
err := r.c.FindOneAndUpdate(ctx, scopeID(d.actor, d.session), bson.D{{Key: "$set", Value: bson.D{
{Key: "owner_limits", Value: limits}, {Key: "owner_flags", Value: flags}, {Key: "owner_limits_at", Value: r.now()},
}}}, &discard)
if errors.Is(err, store.ErrNotFound) {
return ErrNotFound
}
return err
}
// SetRole changes a member's role.
func (r *Sessions) SetRole(ctx context.Context, d Decision, userID, role string) (Member, error) {
var m Member
if err := pairOK(d, relEdit, userID); err != nil {
return m, err
}
err := r.members.FindOneAndUpdate(ctx, sessionUser(d.session, userID), bson.D{{Key: "$set", Value: bson.D{{Key: "role", Value: role}}}}, &m)
if errors.Is(err, store.ErrNotFound) {
return m, ErrNotFound
}
return m, err
}
// RemoveMember ends a membership (soft delete).
func (r *Sessions) RemoveMember(ctx context.Context, d Decision, userID string) error {
need := relEdit
if userID == d.actor {
need = relView // leaving needs only membership
}
if err := pairOK(d, need, userID); err != nil {
return err
}
return r.softDelete(ctx, r.members, sessionUser(d.session, userID), d.actor)
}
// AddInvite stores an invite for the session.
func (r *Sessions) AddInvite(ctx context.Context, d Decision, codeHash string, expires time.Time) (Invite, error) {
if err := d.require(relEdit); err != nil {
return Invite{}, err
}
in := Invite{ID: newID(), SessionID: d.session, CodeHash: codeHash, ExpiresAt: expires, CreatedAt: r.now(), CreatedBy: d.actor, Live: true}
return in, r.invites.InsertOne(ctx, in)
}
// 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 JoinTicket struct{ actor, session string }
// 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 (r *Sessions) ResolveInvite(ctx context.Context, actor, codeHash string, now time.Time) (JoinTicket, error) {
if err := checkUserID(actor); err != nil {
return JoinTicket{}, err
}
if codeHash == "" {
return JoinTicket{}, ErrNotFound
}
var in Invite
err := r.invites.FindOne(ctx, bson.D{{Key: "code_hash", Value: codeHash}, {Key: "deleted_at", Value: nil}}, &in)
if errors.Is(err, store.ErrNotFound) {
return JoinTicket{}, ErrNotFound
}
if err != nil {
return JoinTicket{}, err
}
if in.RevokedAt != nil || !now.Before(in.ExpiresAt) {
return JoinTicket{}, ErrNotFound
}
return JoinTicket{actor: actor, session: in.SessionID}, nil
}
func (t JoinTicket) check() error {
if t.actor == "" || t.session == "" {
return ErrForbidden
}
return nil
}
// Invites lists the session's invites, oldest first.
func (r *Sessions) Invites(ctx context.Context, d Decision, q Query) (Page[Invite], error) {
if err := d.require(relEdit); err != nil {
return Page[Invite]{}, err
}
return runQuery[Invite](ctx, r.invites, SessionInviteSpec, sessionScope(d.session), byCreated(q))
}
// RevokeInvite ends an invite; revoking twice is harmless.
func (r *Sessions) RevokeInvite(ctx context.Context, d Decision, inviteID string) (Invite, error) {
var in Invite
if err := d.require(relEdit); err != nil {
return in, err
}
id, ok := cleanID(inviteID)
if !ok {
return in, ErrNotFound
}
filter := append(bson.D{{Key: "_id", Value: id}}, sessionScope(d.session)...)
err := r.invites.FindOne(ctx, filter, &in)
if errors.Is(err, store.ErrNotFound) {
return in, ErrNotFound
}
if err != nil || in.RevokedAt != nil {
return in, err
}
err = r.invites.FindOneAndUpdate(ctx, append(filter, bson.E{Key: "revoked_at", Value: nil}),
bson.D{{Key: "$set", Value: bson.D{{Key: "revoked_at", Value: r.now()}, {Key: "revoked_by", Value: d.actor}}}}, &in)
if errors.Is(err, store.ErrNotFound) { // revoked concurrently
return in, r.invites.FindOne(ctx, filter, &in)
}
return in, err
}
// 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 JoinState struct {
Exists, Active, Blocked, Member bool
}
// 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 (r *Sessions) ForJoin(ctx context.Context, t JoinTicket) (JoinState, error) {
var st JoinState
if err := t.check(); err != nil {
return st, err
}
actor := t.actor
var sess Session
err := r.c.FindOne(ctx, bson.D{{Key: "_id", Value: t.session}, {Key: "deleted_at", Value: nil}}, &sess)
if errors.Is(err, store.ErrNotFound) {
return st, nil
}
if err != nil {
return st, err
}
st.Exists, st.Active = true, sess.InactiveAt == nil
var b Block
switch err := r.blocks.FindOne(ctx, sessionUser(t.session, actor), &b); {
case err == nil:
st.Blocked = true
case !errors.Is(err, store.ErrNotFound):
return st, err
}
var m Member
switch err := r.members.FindOne(ctx, sessionUser(t.session, actor), &m); {
case err == nil:
st.Member = true
case !errors.Is(err, store.ErrNotFound):
return st, err
}
return st, nil
}
// 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 (r *Sessions) RequestJoin(ctx context.Context, t JoinTicket) (JoinRequest, error) {
var jr JoinRequest
if err := t.check(); err != nil {
return jr, err
}
actor, sessionID := t.actor, t.session
err := r.requests.FindOne(ctx, sessionUser(sessionID, actor), &jr)
switch {
case errors.Is(err, store.ErrNotFound):
jr = JoinRequest{ID: newID(), SessionID: sessionID, UserID: actor, Status: RequestPending, CreatedAt: r.now(), Live: true}
return jr, r.requests.InsertOne(ctx, jr)
case err != nil:
return jr, err
case jr.Status == RequestPending:
return jr, nil
}
// Decode into a fresh value: decoding over jr would keep the fields the update removed.
var reset JoinRequest
err = r.requests.FindOneAndUpdate(ctx, sessionUser(sessionID, actor), bson.D{
{Key: "$set", Value: bson.D{{Key: "status", Value: RequestPending}, {Key: "created_at", Value: r.now()}}},
{Key: "$unset", Value: bson.D{{Key: "reason", Value: ""}, {Key: "role", Value: ""}, {Key: "decided_by", Value: ""}, {Key: "decided_at", Value: ""}}},
}, &reset)
return reset, err
}
// Requests lists the session's requests, optionally only those with status.
func (r *Sessions) Requests(ctx context.Context, d Decision, status string, q Query) (Page[JoinRequest], error) {
if err := d.require(relApprove); err != nil {
return Page[JoinRequest]{}, err
}
q = byCreated(q)
if status != "" {
q.Filters = append(q.Filters, Filter{Field: "status", Op: OpEq, Values: []any{status}})
}
return runQuery[JoinRequest](ctx, r.requests, SessionRequestSpec, sessionScope(d.session), q)
}
// Decide settles a pending request as approved (with role) or rejected (with reason). A request
// already settled is ErrConflict.
func (r *Sessions) Decide(ctx context.Context, d Decision, requestID, status, role, reason string) (JoinRequest, error) {
var jr JoinRequest
if err := d.require(relApprove); err != nil {
return jr, err
}
id, ok := cleanID(requestID)
if !ok {
return jr, ErrNotFound
}
filter := append(bson.D{{Key: "_id", Value: id}}, sessionScope(d.session)...)
set := bson.D{{Key: "status", Value: status}, {Key: "decided_by", Value: d.actor}, {Key: "decided_at", Value: r.now()}}
if role != "" {
set = append(set, bson.E{Key: "role", Value: role})
}
if reason != "" {
set = append(set, bson.E{Key: "reason", Value: reason})
}
err := r.requests.FindOneAndUpdate(ctx, append(filter, bson.E{Key: "status", Value: RequestPending}), bson.D{{Key: "$set", Value: set}}, &jr)
if !errors.Is(err, store.ErrNotFound) {
return jr, err
}
if ferr := r.requests.FindOne(ctx, filter, &jr); ferr == nil {
return jr, ErrConflict
}
return jr, ErrNotFound
}
// 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 (r *Sessions) PendingUser(ctx context.Context, d Decision, requestID string) (string, error) {
if err := d.require(relApprove); err != nil {
return "", err
}
id, ok := cleanID(requestID)
if !ok {
return "", ErrNotFound
}
var jr JoinRequest
filter := append(bson.D{{Key: "_id", Value: id}, {Key: "status", Value: RequestPending}}, sessionScope(d.session)...)
if err := r.requests.FindOne(ctx, filter, &jr); err != nil {
if errors.Is(err, store.ErrNotFound) {
return "", ErrNotFound
}
return "", err
}
return jr.UserID, nil
}
// DropRequest removes userID's request, if any.
func (r *Sessions) DropRequest(ctx context.Context, d Decision, userID string) error {
if err := pairOK(d, relEdit, userID); err != nil {
return err
}
if err := r.softDelete(ctx, r.requests, sessionUser(d.session, userID), d.actor); !errors.Is(err, ErrNotFound) {
return err
}
return nil
}
// AddBlock keeps userID out of the session; blocking twice is harmless.
func (r *Sessions) AddBlock(ctx context.Context, d Decision, userID string) error {
if err := pairOK(d, relEdit, userID); err != nil {
return err
}
err := r.blocks.InsertOne(ctx, Block{ID: newID(), SessionID: d.session, UserID: userID, CreatedAt: r.now(), CreatedBy: d.actor, Live: true})
if errors.Is(err, store.ErrDuplicate) {
return nil
}
return err
}
// RemoveBlock lifts a block.
func (r *Sessions) RemoveBlock(ctx context.Context, d Decision, userID string) error {
if err := pairOK(d, relEdit, userID); err != nil {
return err
}
return r.softDelete(ctx, r.blocks, sessionUser(d.session, userID), d.actor)
}
// Blocked reports whether userID is blocked from the session.
func (r *Sessions) Blocked(ctx context.Context, d Decision, userID string) (bool, error) {
if err := pairOK(d, relEdit, userID); err != nil {
return false, err
}
var b Block
err := r.blocks.FindOne(ctx, sessionUser(d.session, userID), &b)
if errors.Is(err, store.ErrNotFound) {
return false, nil
}
return err == nil, err
}
// Blocks lists the session's blocked users.
func (r *Sessions) Blocks(ctx context.Context, d Decision, q Query) (Page[Block], error) {
if err := d.require(relEdit); err != nil {
return Page[Block]{}, err
}
return runQuery[Block](ctx, r.blocks, SessionBlockSpec, sessionScope(d.session), byCreated(q))
}
// DropSession soft-deletes every membership record of the session: members, invites, requests,
// and blocks. The session document itself is soft-deleted by SoftDelete.
func (r *Sessions) DropSession(ctx context.Context, d Decision) error {
if err := d.require(relGM); err != nil {
return err
}
return r.dropRecords(ctx, d.session, d.actor)
}
// dropRecords soft-deletes every membership record of the session as actor.
func (r *Sessions) dropRecords(ctx context.Context, sessionID, actor string) error {
for _, c := range []store.Collection{r.members, r.invites, r.requests, r.blocks} {
for {
err := r.softDelete(ctx, c, sessionScope(sessionID), actor)
if errors.Is(err, ErrNotFound) {
break
}
if err != nil {
return err
}
}
}
return nil
}
package data
import (
"context"
"errors"
"time"
"github.com/sweetrpg/initiative-api/store"
"github.com/sweetrpg/model-core.go/models"
"go.mongodb.org/mongo-driver/bson"
)
// 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 (r *Sessions) ScanMembers(ctx context.Context, q Query) (Page[Member], error) {
if len(q.Sort) == 0 {
q.Sort = []SortKey{{Field: "created_at"}}
}
return runQuery[Member](ctx, r.members, SessionMemberSpec, bson.D{}, q)
}
// 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 (r *Sessions) SessionMembers(ctx context.Context, sessionID string) ([]Member, error) {
id, ok := cleanID(sessionID)
if !ok {
return nil, ErrNotFound
}
var out []Member
cursor := ""
for {
page, err := runQuery[Member](ctx, r.members, SessionMemberSpec, bson.D{{Key: "session_id", Value: id}},
Query{Sort: []SortKey{{Field: "created_at"}}, Limit: MaxLimit, Cursor: cursor})
if err != nil {
return nil, err
}
out = append(out, page.Items...)
if page.NextCursor == "" {
return out, nil
}
cursor = page.NextCursor
}
}
// 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 (r *Sessions) LookupSessions(ctx context.Context, ids []string) (map[string]bool, error) {
var found []Session
in := make(bson.A, 0, len(ids))
for _, id := range ids {
in = append(in, id)
}
if err := r.c.Find(ctx, bson.D{{Key: "_id", Value: bson.D{{Key: "$in", Value: in}}}}, store.FindOptions{}, &found); err != nil {
return nil, err
}
out := make(map[string]bool, len(found))
for _, s := range found {
out[s.ID] = s.DeletedAt != nil
}
return out, nil
}
// liveGMFilter matches live GM member records of the sessions in session (an id or an $in). The
// live predicate lets Mongo use the partial session_user index; deleted_at alone would scan.
func liveGMFilter(session any) bson.D {
return bson.D{{Key: "session_id", Value: session}, {Key: "role", Value: RoleGM}, {Key: "live", Value: bson.D{{Key: "$exists", Value: true}}}}
}
// SessionsWithGM returns the IDs among ids that have a live GM member record. Reconciler only.
func (r *Sessions) SessionsWithGM(ctx context.Context, ids []string) (map[string]bool, error) {
in := make(bson.A, 0, len(ids))
for _, id := range ids {
in = append(in, id)
}
var gms []Member
if err := r.members.Find(ctx, liveGMFilter(bson.D{{Key: "$in", Value: in}}), store.FindOptions{}, &gms); err != nil {
return nil, err
}
out := make(map[string]bool, len(gms))
for _, m := range gms {
out[m.SessionID] = true
}
return out, nil
}
// gmLessMinAge matches the 15-minute min_age the reconciler lists mints with, and is re-checked
// here against the session itself.
const gmLessMinAge = 15 * time.Minute
// 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 (r *Sessions) RemoveGMLess(ctx context.Context, sessionID string) error {
id, ok := cleanID(sessionID)
if !ok {
return ErrNotFound
}
var s Session
err := r.c.FindOne(ctx, bson.D{{Key: "_id", Value: id}, {Key: "deleted_at", Value: nil}}, &s)
if errors.Is(err, store.ErrNotFound) {
return nil // already gone
}
if err != nil {
return err
}
if s.CreatedAt.After(r.now().Add(-gmLessMinAge)) {
return ErrConflict // too young: Open may still be between its two inserts
}
var gm Member
switch err := r.members.FindOne(ctx, liveGMFilter(id), &gm); {
case err == nil:
return ErrConflict
case !errors.Is(err, store.ErrNotFound):
return err
}
// Records first: a failure here leaves the session live, so the next pass finds it again.
if err := r.dropRecords(ctx, id, models.SystemActor); err != nil {
return err
}
return r.owned.SoftDelete(ctx, s.OwnerUserID, models.SystemActor, id, s.Revision)
}
package data
import (
"context"
"fmt"
"github.com/sweetrpg/initiative-api/store"
"go.mongodb.org/mongo-driver/bson"
)
// 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.
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
}
func asc(fields ...string) bson.D {
d := make(bson.D, 0, len(fields))
for _, f := range fields {
d = append(d, bson.E{Key: f, Value: 1})
}
return d
}
// Specs for each collection. Every owner-scoped index leads with owner_user_id, because every
// query filters by it.
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")},
},
}
)
// AllSpecs lists every collection the service owns.
func AllSpecs() []Spec {
return []Spec{RosterSpec, EncounterSpec, ThemeSpec, CredentialSpec, SystemSpec,
SessionSpec, SessionMemberSpec, SessionInviteSpec, SessionRequestSpec, SessionBlockSpec, ChangeRequestSpec, NotificationPrefSpec}
}
// EnsureIndexes creates every collection's indexes. Safe to run at each startup.
func EnsureIndexes(ctx context.Context, db store.Database) error {
for _, s := range AllSpecs() {
if err := db.Collection(s.Name).EnsureIndexes(ctx, s.Indexes); err != nil {
return fmt.Errorf("ensure indexes on %s: %w", s.Name, err)
}
}
if err := db.Collection(CollectionStreamTickets).EnsureIndexes(ctx, ticketIndexes); err != nil {
return fmt.Errorf("ensure indexes on %s: %w", CollectionStreamTickets, err)
}
if err := db.Collection(CollectionStreamLeases).EnsureIndexes(ctx, leaseIndexes); err != nil {
return fmt.Errorf("ensure indexes on %s: %w", CollectionStreamLeases, err)
}
return nil
}
package data
import (
"context"
"errors"
"fmt"
"log/slog"
"time"
"github.com/sweetrpg/initiative-api/store"
"go.mongodb.org/mongo-driver/bson"
)
// CollectionStreamLeases holds one row per open (or just dropped) event stream, so a user's
// concurrent streams can be counted across pods.
const CollectionStreamLeases = "stream_leases"
// ErrStreamLimit means the user already holds the most concurrent streams allowed.
var ErrStreamLimit = errors.New("data: too many concurrent streams")
// DeviceLimitError means one member already holds the most concurrent connections to a session.
type DeviceLimitError struct{ Limit int }
func (e *DeviceLimitError) Error() string {
return fmt.Sprintf("data: a member may hold at most %d connections to a session", e.Limit)
}
// 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).
var ErrStreamUnavailable = errors.New("data: stream seats are unavailable")
// leaseRowTTL keeps rows past their lease for a while before the TTL index removes them; the
// counts filter on Until, never on the index.
const leaseRowTTL = time.Minute
// cleanupTimeout bounds the writes that undo or release a seat, which must finish even when the
// request that took the seat is gone.
const cleanupTimeout = 5 * time.Second
var leaseIndexes = []store.IndexSpec{
{Name: "until_ttl", Keys: bson.D{{Key: "until", Value: 1}}, ExpireAfter: leaseRowTTL},
{Name: "bucket_until", Keys: bson.D{{Key: "bucket", Value: 1}, {Key: "until", Value: 1}}},
}
// 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 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"`
}
// StreamLeases is the lease store.
type StreamLeases struct {
c store.Collection
now func() time.Time
}
// NewStreamLeases returns the lease store on db.
func NewStreamLeases(db store.Database) *StreamLeases {
return &StreamLeases{c: db.Collection(CollectionStreamLeases), now: time.Now}
}
// SetClock replaces the clock seats are aged by (tests).
func (r *StreamLeases) SetClock(now func() time.Time) { r.now = now }
func (r *StreamLeases) live(l StreamLease) bson.D {
f := bson.D{{Key: "bucket", Value: l.Bucket}, {Key: "until", Value: bson.D{{Key: "$gt", Value: r.now()}}}}
if l.ClientID != "" {
// A dropped seat of the same client is the one this stream takes over, not a second seat.
// Only user and credential buckets are counted this way, and each holds one owner's seats.
f = append(f, bson.E{Key: "$or", Value: bson.A{
bson.D{{Key: "dropped", Value: bson.D{{Key: "$ne", Value: true}}}},
bson.D{{Key: "client_id", Value: bson.D{{Key: "$ne", Value: l.ClientID}}}},
}})
}
return f
}
// retract removes seat id even when the request that took it has ended.
func (r *StreamLeases) retract(ctx context.Context, id string) {
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), cleanupTimeout)
defer cancel()
if err := r.c.DeleteOne(ctx, bson.D{{Key: "_id", Value: id}}); err != nil && !errors.Is(err, store.ErrNotFound) {
slog.Error("could not give back a stream seat; it lapses on its own", "seat", id, "error", err)
}
}
// 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 (r *StreamLeases) Acquire(ctx context.Context, l StreamLease, ttl time.Duration, max int) error {
if err := checkUserID(l.UserID); err != nil {
return err
}
if l.Bucket == "" {
l.Bucket = "user:" + l.UserID
}
l.Until, l.Dropped = r.now().Add(ttl), false
if err := r.c.InsertOne(ctx, l); err != nil {
r.retract(ctx, l.ID) // the write may have landed before the error
return fmt.Errorf("%w: %v", ErrStreamUnavailable, err)
}
n, err := r.c.CountDocuments(ctx, r.live(l))
if err != nil {
r.retract(ctx, l.ID)
return fmt.Errorf("%w: %v", ErrStreamUnavailable, err)
}
if n > int64(max) {
r.retract(ctx, l.ID)
return ErrStreamLimit
}
if l.ClientID != "" {
r.takeOver(ctx, l)
}
return nil
}
// 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 (r *StreamLeases) AcquireSession(ctx context.Context, l StreamLease, ttl time.Duration, members, devices int) error {
if err := checkUserID(l.UserID); err != nil {
return err
}
l.Until, l.Dropped = r.now().Add(ttl), false
pending := l
pending.Pending = true
if err := r.c.InsertOne(ctx, pending); err != nil {
r.retract(ctx, l.ID)
return fmt.Errorf("%w: %v", ErrStreamUnavailable, err)
}
var rows []StreamLease
err := r.c.Find(ctx, bson.D{{Key: "bucket", Value: l.Bucket}, {Key: "until", Value: bson.D{{Key: "$gt", Value: r.now()}}}}, store.FindOptions{}, &rows)
if err != nil {
r.retract(ctx, l.ID)
return fmt.Errorf("%w: %v", ErrStreamUnavailable, err)
}
if err := checkSessionSeat(l, rows, members, devices); err != nil {
r.retract(ctx, l.ID)
return err
}
var out StreamLease
if err := r.c.FindOneAndUpdate(ctx, bson.D{{Key: "_id", Value: l.ID}}, bson.D{{Key: "$unset", Value: bson.D{{Key: "pending", Value: ""}}}}, &out); err != nil {
r.retract(ctx, l.ID)
return fmt.Errorf("%w: %v", ErrStreamUnavailable, err)
}
if l.ClientID != "" {
r.takeOver(ctx, l)
}
return nil
}
// checkSessionSeat applies the device and member limits to rows, the live seats of l's bucket
// including l.
func checkSessionSeat(l StreamLease, rows []StreamLease, members, devices int) error {
mine, distinct := 0, map[string]bool{}
for _, row := range rows {
if row.UserID == l.UserID && !row.Dropped {
mine++
}
if row.Counted && (row.UserID != l.UserID || row.ID == l.ID) {
distinct[row.UserID] = true
}
}
if mine > devices {
return &DeviceLimitError{Limit: devices}
}
if !l.Counted || len(distinct) <= members {
return nil
}
for _, row := range rows {
if row.UserID == l.UserID && row.ID != l.ID && row.Counted && !row.Pending {
return nil // the member already holds a seat; another connection adds no member
}
}
return ErrStreamLimit
}
// takeOver removes every dropped seat of l's user and client other than l, however many two streams that
// shared a client id left behind.
func (r *StreamLeases) takeOver(ctx context.Context, l StreamLease) {
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), cleanupTimeout)
defer cancel()
for range 8 {
err := r.c.DeleteOne(ctx, bson.D{{Key: "bucket", Value: l.Bucket}, {Key: "client_id", Value: l.ClientID}, {Key: "user_id", Value: l.UserID}, {Key: "dropped", Value: true}, {Key: "_id", Value: bson.D{{Key: "$ne", Value: l.ID}}}})
if err != nil {
return // none left, or the store failed: the stale seat lapses on its own
}
}
}
// 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 (r *StreamLeases) Renew(ctx context.Context, l StreamLease, ttl time.Duration) error {
var out StreamLease
err := r.c.FindOneAndUpdate(ctx, bson.D{{Key: "_id", Value: l.ID}},
bson.D{{Key: "$set", Value: bson.D{{Key: "until", Value: r.now().Add(ttl)}}}}, &out)
if errors.Is(err, store.ErrNotFound) {
l.Until, l.Dropped = r.now().Add(ttl), false
return r.c.InsertOne(ctx, l)
}
return err
}
// 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 (r *StreamLeases) Release(ctx context.Context, l StreamLease, grace time.Duration, keep bool) error {
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), cleanupTimeout)
defer cancel()
if !keep || grace <= 0 || l.ClientID == "" {
return ignoreMissing(r.c.DeleteOne(ctx, bson.D{{Key: "_id", Value: l.ID}}))
}
var out StreamLease
return ignoreMissing(r.c.FindOneAndUpdate(ctx, bson.D{{Key: "_id", Value: l.ID}},
bson.D{{Key: "$set", Value: bson.D{{Key: "dropped", Value: true}, {Key: "until", Value: r.now().Add(grace)}}}}, &out))
}
func ignoreMissing(err error) error {
if errors.Is(err, store.ErrNotFound) {
return nil
}
return err
}
package data
import (
"context"
"errors"
"github.com/sweetrpg/initiative-api/constants"
"time"
"github.com/sweetrpg/initiative-api/store"
"go.mongodb.org/mongo-driver/bson"
)
// CollectionStreamTickets holds the one-time tickets that open a WebSocket for a browser, which
// cannot send an Authorization header on an upgrade.
const CollectionStreamTickets = "stream_tickets"
// ticketRowTTL is the TTL index on a ticket row. MongoDB removes expired rows about once a minute,
// so Redeem checks the age itself; the index only keeps the collection small.
const ticketRowTTL = constants.MaxStreamTicketTTL
var ticketIndexes = []store.IndexSpec{{Name: "at_ttl", Keys: bson.D{{Key: "at", Value: 1}}, ExpireAfter: ticketRowTTL}}
// 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 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"`
}
// StreamTickets is the ticket store.
type StreamTickets struct {
c store.Collection
now func() time.Time
}
// NewStreamTickets returns the ticket store on db.
func NewStreamTickets(db store.Database) *StreamTickets {
return &StreamTickets{c: db.Collection(CollectionStreamTickets), now: time.Now}
}
// SetClock replaces the clock the ticket ages are read from (tests).
func (r *StreamTickets) SetClock(now func() time.Time) { r.now = now }
// Mint stores t (its ID already the hash of the ticket handed to the caller).
func (r *StreamTickets) Mint(ctx context.Context, t StreamTicket) error {
if err := checkUserID(t.UserID); err != nil {
return err
}
t.At = r.now()
return r.c.InsertOne(ctx, t)
}
// 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 (r *StreamTickets) Peek(ctx context.Context, id string, maxAge time.Duration) (StreamTicket, error) {
var t StreamTicket
if err := r.c.FindOne(ctx, bson.D{{Key: "_id", Value: id}}, &t); err != nil {
if errors.Is(err, store.ErrNotFound) {
return StreamTicket{}, ErrNotFound
}
return StreamTicket{}, err
}
if r.now().Sub(t.At) > maxAge {
return StreamTicket{}, ErrNotFound
}
return t, nil
}
// 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 (r *StreamTickets) Redeem(ctx context.Context, id string, maxAge time.Duration) (StreamTicket, error) {
var t StreamTicket
if err := r.c.FindOne(ctx, bson.D{{Key: "_id", Value: id}}, &t); err != nil {
if errors.Is(err, store.ErrNotFound) {
return StreamTicket{}, ErrNotFound
}
return StreamTicket{}, err
}
if err := r.c.DeleteOne(ctx, bson.D{{Key: "_id", Value: id}}); err != nil {
if errors.Is(err, store.ErrNotFound) {
return StreamTicket{}, ErrNotFound
}
return StreamTicket{}, err
}
if r.now().Sub(t.At) > maxAge {
return StreamTicket{}, ErrNotFound
}
return t, nil
}
// 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 (r *Sessions) IsMember(ctx context.Context, userID, sessionID string) (bool, error) {
_, err := r.TicketView(ctx, userID, sessionID, ViewGM)
switch {
case errors.Is(err, ErrNotMember):
return false, nil
case err != nil:
return false, err
}
return true, nil
}
// 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 (r *Sessions) SeatInfo(ctx context.Context, userID, sessionID string) (Session, Member, error) {
id, ok := cleanID(sessionID)
if !ok || checkUserID(userID) != nil {
return Session{}, Member{}, ErrNotMember
}
var s Session
if err := r.c.FindOne(ctx, bson.D{{Key: "_id", Value: id}, {Key: "deleted_at", Value: nil}}, &s); err != nil {
if errors.Is(err, store.ErrNotFound) {
return Session{}, Member{}, ErrNotMember
}
return Session{}, Member{}, err
}
var m Member
if err := r.members.FindOne(ctx, sessionUser(id, userID), &m); err != nil {
if errors.Is(err, store.ErrNotFound) {
return Session{}, Member{}, ErrNotMember
}
return Session{}, Member{}, err
}
return s, m, nil
}
// 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 (r *Sessions) TicketView(ctx context.Context, userID, sessionID string, minted ViewLevel) (Viewer, error) {
id, ok := cleanID(sessionID)
if !ok || checkUserID(userID) != nil {
return Viewer{}, ErrNotMember
}
var s Session
if err := r.c.FindOne(ctx, bson.D{{Key: "_id", Value: id}, {Key: "deleted_at", Value: nil}}, &s); err != nil {
if errors.Is(err, store.ErrNotFound) {
return Viewer{}, ErrNotMember
}
return Viewer{}, err
}
var m Member
if err := r.members.FindOne(ctx, sessionUser(id, userID), &m); err != nil {
if errors.Is(err, store.ErrNotFound) {
return Viewer{}, ErrNotMember
}
return Viewer{}, err
}
level := roleLevel(m.Role)
if level == ViewNone || level > minted {
return Viewer{}, ErrNotMember
}
return Viewer{actor: userID, session: id, level: level}, nil
}
// roleLevel is the view level a session role carries.
func roleLevel(role string) ViewLevel {
switch role {
case RoleGM, RoleCoGM:
return ViewGM
case RolePlayer:
return ViewPlayer
case RoleObserver:
return ViewObserver
}
return ViewNone
}
package data
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"regexp"
"time"
"github.com/sweetrpg/initiative-api/store"
"github.com/sweetrpg/model-core.go/models"
"go.mongodb.org/mongo-driver/bson"
)
// Outcome is what Upsert did with a definition.
type Outcome string
// Upsert outcomes.
const (
Created Outcome = "created"
Updated Outcome = "updated"
Unchanged Outcome = "unchanged"
)
var slug = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,63}$`)
// 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.
type SystemRepo struct {
c store.Collection
now func() time.Time
}
// NewSystemRepo builds the repository for the game_systems collection in db.
func NewSystemRepo(db store.Database) *SystemRepo {
return &SystemRepo{c: db.Collection(SystemSpec.Name), now: func() time.Time { return time.Now().UTC() }}
}
// Get returns the system whose ID or alias equals idOrAlias.
func (s *SystemRepo) Get(ctx context.Context, idOrAlias string) (GameSystem, error) {
var out GameSystem
filter := bson.D{{Key: "$or", Value: bson.A{
bson.D{{Key: "_id", Value: idOrAlias}}, bson.D{{Key: "aliases", Value: idOrAlias}},
}}}
err := s.c.FindOne(ctx, filter, &out)
if errors.Is(err, store.ErrNotFound) {
return out, ErrNotFound
}
return out, err
}
// 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.
const DefaultSystemID = "none"
// GetOrDefault returns the system for idOrAlias, or the default system when none is defined for it.
func (s *SystemRepo) GetOrDefault(ctx context.Context, idOrAlias string) (GameSystem, error) {
sys, err := s.Get(ctx, idOrAlias)
if errors.Is(err, ErrNotFound) {
return s.Get(ctx, DefaultSystemID)
}
return sys, err
}
// 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 (s *SystemRepo) List(ctx context.Context, q Query) (Page[GameSystem], error) {
return runQuery[GameSystem](ctx, s.c, SystemSpec, nil, q)
}
// 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 (s *SystemRepo) ListAvailable(ctx context.Context, q Query, entitled bool) (Page[GameSystem], error) {
var base bson.D
if !entitled {
base = bson.D{{Key: "gated", Value: bson.D{{Key: "$ne", Value: true}}}}
}
return runQuery[GameSystem](ctx, s.c, SystemSpec, base, q)
}
// 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.
func (s *SystemRepo) Upsert(ctx context.Context, sys GameSystem) (Outcome, error) {
if err := ValidateSystem(sys); err != nil {
return "", err
}
hash, err := definitionHash(sys)
if err != nil {
return "", err
}
sys.DefinitionHash = hash
// A concurrent loader can change the row between our read and write; re-read and retry once
// before giving up, so a lost race is never reported as "unchanged".
for attempt := 0; attempt < 2; attempt++ {
var (
cur GameSystem
out Outcome
)
err = s.c.FindOne(ctx, bson.D{{Key: "_id", Value: sys.ID}}, &cur)
switch {
case errors.Is(err, store.ErrNotFound):
out, err = s.create(ctx, sys)
case err != nil:
return "", err
case cur.DefinitionHash == hash:
return Unchanged, nil
default:
out, err = s.update(ctx, sys, cur.DefinitionHash)
}
if !errors.Is(err, errLostRace) {
return out, err
}
}
return "", fmt.Errorf("system %q: %w", sys.ID, errLostRace)
}
// errLostRace means another writer changed the definition between the read and the write.
var errLostRace = errors.New("data: concurrent change to system definition")
func (s *SystemRepo) create(ctx context.Context, sys GameSystem) (Outcome, error) {
sys.Revision = 1
models.StampCreate(&sys.Auditable, models.SystemActor, s.now())
err := s.c.InsertOne(ctx, sys)
if errors.Is(err, store.ErrDuplicate) {
// Another replica may have inserted this same ID first; if so, retry as an update/no-op.
var existing GameSystem
switch rerr := s.c.FindOne(ctx, bson.D{{Key: "_id", Value: sys.ID}}, &existing); {
case rerr == nil:
return "", errLostRace
case errors.Is(rerr, store.ErrNotFound):
return "", fmt.Errorf("system %q alias conflicts with another system: %w", sys.ID, err)
default:
return "", rerr
}
}
if err != nil {
return "", err
}
return Created, nil
}
func (s *SystemRepo) update(ctx context.Context, sys GameSystem, prevHash string) (Outcome, error) {
filter := bson.D{{Key: "_id", Value: sys.ID}, {Key: "definition_hash", Value: prevHash}}
update := bson.D{
{Key: "$set", Value: bson.D{
{Key: "name", Value: sys.Name}, {Key: "family", Value: sys.Family},
{Key: "aliases", Value: sys.Aliases}, {Key: "gated", Value: sys.Gated},
{Key: "fields", Value: sys.Fields}, {Key: "definition_hash", Value: sys.DefinitionHash},
{Key: "updated_at", Value: s.now()}, {Key: "updated_by", Value: models.SystemActor}}},
{Key: "$inc", Value: bson.D{{Key: "revision", Value: 1}}},
}
var out GameSystem
err := s.c.FindOneAndUpdate(ctx, filter, update, &out)
if errors.Is(err, store.ErrDuplicate) {
return "", fmt.Errorf("system %q alias conflicts with another system: %w", sys.ID, err)
}
if errors.Is(err, store.ErrNotFound) {
return "", errLostRace
}
if err != nil {
return "", err
}
return Updated, nil
}
func definitionHash(sys GameSystem) (string, error) {
b, err := json.Marshal(struct {
Name string `json:"name"`
Family string `json:"family"`
Aliases []string `json:"aliases"`
Gated bool `json:"gated"`
Fields []TrackerField `json:"fields"`
}{sys.Name, sys.Family, sys.Aliases, sys.Gated, sys.Fields})
if err != nil {
return "", err
}
sum := sha256.Sum256(b)
return hex.EncodeToString(sum[:]), nil
}
// 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 ValidateSystem(sys GameSystem) error {
bad := func(format string, a ...any) error {
return fmt.Errorf("%w: system %q: %s", ErrInvalid, sys.ID, fmt.Sprintf(format, a...))
}
if !slug.MatchString(sys.ID) {
return bad("id must be a lowercase slug")
}
if sys.Name == "" || sys.Family == "" || len(sys.Fields) == 0 {
return bad("name, family and at least one field are required")
}
for _, a := range sys.Aliases {
if !slug.MatchString(a) {
return bad("alias %q must be a lowercase slug", a)
}
}
byKey := map[string]TrackerField{}
for _, f := range sys.Fields {
if f.Key == "" || byKey[f.Key].Key != "" {
return bad("field keys must be non-empty and unique (%q)", f.Key)
}
byKey[f.Key] = f
}
for _, f := range sys.Fields {
if err := validateField(f, byKey); err != nil {
return bad("%v", err)
}
}
return nil
}
func validateField(f TrackerField, byKey map[string]TrackerField) error {
switch f.Kind {
case FieldCounter, FieldPool, FieldFlag, FieldTrack:
default:
return fmt.Errorf("field %q has unknown kind %q", f.Key, f.Kind)
}
if f.Max != nil && f.MaxRef != "" {
return fmt.Errorf("field %q sets both max and max_ref", f.Key)
}
if f.Kind == FieldFlag && (f.Def < 0 || f.Def > 1 || f.MaxRef != "" ||
(f.Min != nil && *f.Min < 0) || (f.Max != nil && *f.Max > 1)) {
return fmt.Errorf("flag field %q must stay within 0 and 1", f.Key)
}
if f.MaxRef != "" {
if ref, ok := byKey[f.MaxRef]; !ok || f.MaxRef == f.Key {
return fmt.Errorf("field %q max_ref %q does not name another field", f.Key, f.MaxRef)
} else if f.Def > ref.Def {
return fmt.Errorf("field %q default exceeds its max_ref %q default", f.Key, f.MaxRef)
}
}
if f.Min != nil && f.Max != nil && *f.Min > *f.Max {
return fmt.Errorf("field %q min exceeds max", f.Key)
}
if (f.Min != nil && f.Def < *f.Min) || (f.Max != nil && f.Def > *f.Max) {
return fmt.Errorf("field %q default is out of bounds", f.Key)
}
return nil
}
package data
import (
"context"
"errors"
"github.com/sweetrpg/initiative-api/store"
"go.mongodb.org/mongo-driver/bson"
)
// 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.
type Viewer struct {
actor, session string
level ViewLevel
}
// ViewLevel is the least a Viewer may see, weakest first. The zero value sees nothing.
type ViewLevel int
// View levels: Observer and Player both get the non-GM view; only the Player controls combatants.
const (
ViewNone ViewLevel = iota
ViewObserver
ViewPlayer
ViewGM // gm, co_gm, or the owner of a private encounter
)
// Actor returns the user the viewer is.
func (v Viewer) Actor() string { return v.actor }
// SessionID returns the session the viewer covers; empty for the owner of a private encounter.
func (v Viewer) SessionID() string { return v.session }
// Level returns what the viewer may see.
func (v Viewer) Level() ViewLevel { return v.level }
// 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 BusViewer(sessionID string) Viewer { return Viewer{session: sessionID, level: ViewObserver} }
// ownerViewer is the viewer for a private encounter the caller owns.
func ownerViewer(owner string) Viewer { return Viewer{actor: owner, level: ViewGM} }
// 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 (r *Sessions) AuthorizeView(ctx context.Context, actor, sessionID string) (Viewer, error) {
d, err := Authorize(ctx, actor, sessionID, relView)
if errors.Is(err, ErrForbidden) {
return Viewer{}, ErrNotMember
}
if err != nil {
return Viewer{}, err
}
m, err := r.Member(ctx, d, actor)
if errors.Is(err, ErrNotFound) {
return Viewer{}, ErrNotMember
}
if err != nil {
return Viewer{}, err
}
level := roleLevel(m.Role)
var relation string
switch m.Role {
case RoleGM, RoleCoGM:
relation = relEdit
case RolePlayer:
relation = RolePlayer
case RoleObserver:
relation = RoleObserver
default:
return Viewer{}, ErrNotMember
}
if _, err := Authorize(ctx, actor, sessionID, relation); errors.Is(err, ErrForbidden) {
return Viewer{}, ErrNotMember
} else if err != nil {
return Viewer{}, err
}
return Viewer{actor: d.actor, session: d.session, level: level}, nil
}
// OwnerViewer is the viewer for owner's own private encounters.
func OwnerViewer(owner string) (Viewer, error) {
if err := checkUserID(owner); err != nil {
return Viewer{}, err
}
return ownerViewer(owner), nil
}
// 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 (r *Encounters) LoadOwnedView(ctx context.Context, owner, id string) (Encounter, Viewer, error) {
e, err := r.Load(ctx, owner, id)
if err != nil {
return Encounter{}, Viewer{}, err
}
if e.SessionID != "" {
return Encounter{}, Viewer{}, ErrForbidden
}
return e, ownerViewer(owner), nil
}
// 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 (r *Encounters) LoadForViewer(ctx context.Context, v Viewer, id string) (Encounter, error) {
if v.level == ViewNone || v.session == "" {
return Encounter{}, ErrForbidden
}
id, ok := cleanID(id)
if !ok {
return Encounter{}, ErrNotFound
}
var e Encounter
err := r.c.FindOne(ctx, bson.D{{Key: "_id", Value: id}, {Key: "session_id", Value: v.session}, {Key: "deleted_at", Value: nil}}, &e)
if errors.Is(err, store.ErrNotFound) {
return Encounter{}, ErrNotFound
}
return e, err
}
// ListForViewer reads the viewer's session's encounters in display order, at most limit (the
// store default when zero).
func (r *Encounters) ListForViewer(ctx context.Context, v Viewer, limit int64) ([]Encounter, error) {
if v.level == ViewNone || v.session == "" {
return nil, ErrForbidden
}
var out []Encounter
err := r.c.Find(ctx, bson.D{{Key: "session_id", Value: v.session}, {Key: "deleted_at", Value: nil}},
store.FindOptions{Sort: bson.D{{Key: "position", Value: 1}, {Key: "_id", Value: 1}}, Limit: limit}, &out)
return out, err
}
// 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 (r *Encounters) ListOwnedViews(ctx context.Context, owner string, q Query) (Page[Encounter], Viewer, error) {
if err := checkUserID(owner); err != nil {
return Page[Encounter]{}, Viewer{}, err
}
base := append(scope(owner), bson.E{Key: "session_id", Value: nil})
page, err := runQuery[Encounter](ctx, r.c, r.spec, base, q)
return page, ownerViewer(owner), err
}
// 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 (r *Encounters) OwnedViewer(owner string, e Encounter) (Viewer, error) {
if checkUserID(owner) != nil || e.OwnerUserID != owner || e.SessionID != "" {
return Viewer{}, ErrForbidden
}
return ownerViewer(owner), nil
}
// RequireSystem rejects a game system that has no definition.
func (r *Encounters) RequireSystem(ctx context.Context, sysID string) error {
return r.requireSystem(ctx, sysID)
}
package domain
import (
"context"
"errors"
"fmt"
"log/slog"
"maps"
"slices"
"strings"
"unicode"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/store"
)
// ErrChangeStale means an approved change no longer applies: the combatant is gone, its
// requester no longer controls it, or the values no longer validate against the game system. The
// request stays pending.
var ErrChangeStale = errors.New("domain: the requested change no longer applies")
// maxApplyAttempts bounds how often an approval re-reads an encounter that changed under it.
const maxApplyAttempts = 3
// ChangeNotifier is the hook point for telling users about change requests (the GM and co-GMs
// when one is submitted, the requester when it is decided). Events arrive in a later change; an
// implementation must not block or fail the request, and the default does nothing.
type ChangeNotifier interface {
ChangeSubmitted(ctx context.Context, req data.ChangeRequest)
ChangeDecided(ctx context.Context, req data.ChangeRequest)
}
// maxRejectReason bounds a rejection reason, in runes.
const maxRejectReason = 500
// ChangeInput is what a player proposes: health values to set, and/or conditions to add (or
// update by name) and remove by name.
type ChangeInput struct {
Health map[string]int
AddConditions []data.Condition
RemoveConditions []string
}
func (in ChangeInput) empty() bool {
return len(in.Health) == 0 && len(in.AddConditions) == 0 && len(in.RemoveConditions) == 0
}
// ChangeRequests implements change requests: submit, list, approve, and reject.
type ChangeRequests struct {
repo *data.ChangeRequests
encounter *Encounters
sessions *Sessions
// Notifier is told about submissions and decisions; nil means nobody is.
Notifier ChangeNotifier
}
// NewChangeRequests builds the service on db.
func NewChangeRequests(db store.Database, encounters *Encounters, sessions *Sessions) *ChangeRequests {
return &ChangeRequests{repo: data.NewChangeRequests(db), encounter: encounters, sessions: sessions}
}
// applyChange returns c with in applied. Only health and conditions can change here, so a change
// request can never alter initiative, notes, visibility, or controllers. Health values are set;
// conditions change by name against c as it is now: removals first, then each added condition
// replaces the one with its name or is appended. Applying it twice gives the same result.
func applyChange(c data.Combatant, in ChangeInput) data.Combatant {
if len(in.Health) > 0 {
merged := maps.Clone(c.Health)
if merged == nil {
merged = map[string]int{}
}
maps.Copy(merged, in.Health)
c.Health = merged
}
if len(in.AddConditions) > 0 || len(in.RemoveConditions) > 0 {
conds := slices.DeleteFunc(slices.Clone(c.Conditions), func(x data.Condition) bool {
return slices.Contains(in.RemoveConditions, x.Name)
})
for _, add := range in.AddConditions {
if i := slices.IndexFunc(conds, func(x data.Condition) bool { return x.Name == add.Name }); i >= 0 {
conds[i] = add
} else {
conds = append(conds, add)
}
}
if conds == nil {
conds = []data.Condition{}
}
c.Conditions = conds
}
return c
}
// checkInput validates the shape of a proposal before any encounter is read.
func checkInput(in ChangeInput) error {
if in.empty() {
return invalid("a change request needs health values or conditions")
}
if len(in.AddConditions) > data.MaxConditions || len(in.RemoveConditions) > data.MaxConditions {
return invalid("at most %d conditions can be added or removed in one request", data.MaxConditions)
}
for _, name := range in.RemoveConditions {
if strings.TrimSpace(name) == "" {
return invalid("a condition to remove needs a name")
}
if err := data.CheckText("condition name", name, data.MaxNameLen); err != nil {
return err
}
}
return nil
}
// Submit records the player's change request for a combatant they control. The caller must hold
// a live player Viewer on the session and be listed on the combatant now: an observer, a GM, a
// removed member, and a stale or demoted controller are all refused. The change is validated
// against the game system at submission as well as at approval.
func (s *ChangeRequests) Submit(ctx context.Context, actor, sessionID, encounterID, combatantID string, in ChangeInput) (data.ChangeRequest, error) {
if err := checkInput(in); err != nil {
return data.ChangeRequest{}, err
}
if sess, _, _, err := s.sessions.as(ctx, actor, sessionID, ActView); err != nil {
return data.ChangeRequest{}, err
} else if sess.InactiveAt != nil {
return data.ChangeRequest{}, data.ErrInactive
}
v, err := s.sessions.Viewer(ctx, actor, sessionID)
if err != nil {
return data.ChangeRequest{}, err
}
if v.Level() != data.ViewPlayer {
return data.ChangeRequest{}, data.ErrForbidden
}
enc, err := s.encounter.repo.LoadForViewer(ctx, v, encounterID)
if err != nil {
return data.ChangeRequest{}, err
}
c, ok := findLive(enc, combatantID)
if !ok || (c.Hidden && !controls(c, v)) {
return data.ChangeRequest{}, data.ErrNotFound
}
if !controls(c, v) {
return data.ChangeRequest{}, data.ErrForbidden
}
switch {
case enc.LockedAt != nil:
return data.ChangeRequest{}, data.ErrLocked
case enc.InactiveAt != nil:
return data.ChangeRequest{}, data.ErrInactive
}
if err := s.encounter.repo.ValidateCombatantChange(ctx, enc.GameSystemID, c, applyChange(c, in)); err != nil {
return data.ChangeRequest{}, err
}
req, err := s.repo.Create(ctx, v, data.ChangeRequest{
EncounterID: enc.ID, CombatantID: c.ID, Health: in.Health, AddConditions: in.AddConditions,
RemoveConditions: in.RemoveConditions, BaseRevision: enc.Revision,
})
if err != nil {
return data.ChangeRequest{}, err
}
if s.Notifier != nil {
s.Notifier.ChangeSubmitted(ctx, req)
}
return req, nil
}
func findLive(enc data.Encounter, combatantID string) (data.Combatant, bool) {
i := slices.IndexFunc(enc.Combatants, func(c data.Combatant) bool { return c.ID == combatantID && !c.Removed })
if i < 0 {
return data.Combatant{}, false
}
return enc.Combatants[i], true
}
// List returns one page of the encounter's change requests: all of them for a GM or co-GM, the
// caller's own for a player, and an observer is refused. status narrows to one status.
func (s *ChangeRequests) List(ctx context.Context, actor, sessionID, encounterID, status string, q data.Query) (data.Page[data.ChangeRequest], error) {
v, err := s.sessions.Viewer(ctx, actor, sessionID)
if err != nil {
return data.Page[data.ChangeRequest]{}, err
}
if _, err := s.encounter.repo.LoadForViewer(ctx, v, encounterID); err != nil {
return data.Page[data.ChangeRequest]{}, err
}
return s.repo.List(ctx, v, encounterID, status, q)
}
// Approve applies a pending request through the same atomic, revision-bumping encounter write as
// any other edit, and records who approved it. The change is re-validated against the encounter
// as it is now, and the request's requester must still control the combatant as a player; a
// change that no longer applies is ErrChangeStale and the request stays pending. An encounter
// that moved on since the request was submitted is not a reason to fail: the request is applied
// to the current revision.
//
// The request moves pending -> approving -> approved. The claim is taken before the write, so a
// concurrent reject or second approval loses; if the write fails the claim is undone. A claim that
// is never finished (a crash) is younger than ClaimTimeout: 409, retry later; older: any GM's
// approval resumes it, which is safe because the change is idempotent.
func (s *ChangeRequests) Approve(ctx context.Context, actor, sessionID, encounterID, requestID string) (data.ChangeRequest, error) {
_, _, d, err := s.sessions.as(ctx, actor, sessionID, ActManageMembers)
if err != nil {
return data.ChangeRequest{}, err
}
viewer, err := s.sessions.Viewer(ctx, actor, sessionID)
if err != nil {
return data.ChangeRequest{}, err
}
req, err := s.repo.Load(ctx, d, encounterID, requestID)
if err != nil {
return data.ChangeRequest{}, err
}
next, enc, err := s.build(ctx, viewer, d, req)
if err != nil {
return data.ChangeRequest{}, err
}
if req, err = s.repo.Claim(ctx, d, encounterID, requestID); err != nil {
return data.ChangeRequest{}, err
}
applied, err := s.write(ctx, viewer, d, req, next, enc)
// Settling the claim must survive the caller going away: a request cancelled after the
// encounter write would otherwise stay approving, and a later approval would re-apply values
// that may be stale by then.
settle := context.WithoutCancel(ctx)
if err != nil {
if uerr := s.repo.Unclaim(settle, d, encounterID, req.ID); uerr != nil {
slog.ErrorContext(ctx, "could not release a change request claim after a failed approval; a GM can resume it once the claim is older than the timeout",
"request", req.ID, "session", sessionID, "encounter", encounterID, "error", uerr)
}
return data.ChangeRequest{}, err
}
done, err := s.repo.Finish(settle, d, encounterID, req.ID, applied.Revision)
if err != nil {
// The change is applied but the request was not recorded as approved: another GM resumed
// it after the timeout, it was cancelled, or the store failed. A resume re-applies the
// idempotent change, so report what happened.
slog.WarnContext(ctx, "change applied but the request was not recorded as approved", "request", req.ID,
"session", sessionID, "encounter", encounterID, "applied_revision", applied.Revision, "error", err)
req.Status, req.AppliedRevision = data.ChangeApproved, applied.Revision
done = req
}
if s.Notifier != nil {
s.Notifier.ChangeDecided(ctx, done)
}
return done, nil
}
// write stores next as the encounter's combatants at enc's revision. If the encounter changed
// since it was read it is re-read and the change rebuilt and re-validated, up to
// maxApplyAttempts times.
func (s *ChangeRequests) write(ctx context.Context, v data.Viewer, d data.Decision, req data.ChangeRequest, next []data.Combatant, enc data.Encounter) (data.Encounter, error) {
for attempt := 0; ; attempt++ {
updated, err := s.encounter.repo.UpdateInSession(data.WithOp(ctx, data.EventCombatantUpdated, req.CombatantID), d, enc.ID, enc.Revision, map[string]any{"combatants": next})
if !errors.Is(err, data.ErrRevisionConflict) || attempt+1 == maxApplyAttempts {
return updated, err
}
if next, enc, err = s.build(ctx, v, d, req); err != nil {
return data.Encounter{}, err
}
}
}
// build loads the encounter fresh and returns its combatants with req applied, and the encounter
// they were built from. Anything that stops the change applying is ErrChangeStale.
func (s *ChangeRequests) build(ctx context.Context, v data.Viewer, d data.Decision, req data.ChangeRequest) ([]data.Combatant, data.Encounter, error) {
enc, err := s.encounter.repo.LoadForViewer(ctx, v, req.EncounterID)
if err != nil {
return nil, enc, err
}
i := slices.IndexFunc(enc.Combatants, func(c data.Combatant) bool { return c.ID == req.CombatantID && !c.Removed })
if i < 0 {
return nil, enc, fmt.Errorf("%w: the combatant is gone", ErrChangeStale)
}
c := enc.Combatants[i]
if !slices.Contains(c.ControllerUserIDs, req.RequestedBy) {
return nil, enc, fmt.Errorf("%w: the requester no longer controls the combatant", ErrChangeStale)
}
m, err := s.sessions.repo.Member(ctx, d, req.RequestedBy)
switch {
case errors.Is(err, data.ErrNotFound):
return nil, enc, fmt.Errorf("%w: the requester has left the session", ErrChangeStale)
case err != nil:
return nil, enc, err
case m.Role != data.RolePlayer:
return nil, enc, fmt.Errorf("%w: the requester is no longer a player", ErrChangeStale)
}
changed := applyChange(c, ChangeInput{Health: req.Health, AddConditions: req.AddConditions, RemoveConditions: req.RemoveConditions})
if err := s.encounter.repo.ValidateCombatantChange(ctx, enc.GameSystemID, c, changed); err != nil {
if errors.Is(err, data.ErrInvalid) {
return nil, enc, fmt.Errorf("%w: %s", ErrChangeStale, strings.TrimPrefix(err.Error(), data.ErrInvalid.Error()+": "))
}
return nil, enc, err
}
cs := slices.Clone(enc.Combatants)
cs[i] = changed
return cs, enc, nil
}
// Reject settles a pending request with a reason; the combatant is unchanged and the requester
// sees the reason.
func (s *ChangeRequests) Reject(ctx context.Context, actor, sessionID, encounterID, requestID, reason string) (data.ChangeRequest, error) {
reason = strings.TrimSpace(strings.Map(func(r rune) rune {
if unicode.IsControl(r) {
return -1
}
return r
}, reason))
if reason == "" {
return data.ChangeRequest{}, invalid("a reason is required to reject a change request")
}
if err := data.CheckText("reason", reason, maxRejectReason); err != nil {
return data.ChangeRequest{}, err
}
_, _, d, err := s.sessions.as(ctx, actor, sessionID, ActManageMembers)
if err != nil {
return data.ChangeRequest{}, err
}
req, err := s.repo.Reject(ctx, d, encounterID, requestID, reason)
if err != nil {
return data.ChangeRequest{}, err
}
if s.Notifier != nil {
s.Notifier.ChangeDecided(ctx, req)
}
return req, nil
}
package domain
import (
"context"
"maps"
"slices"
"strings"
"github.com/sweetrpg/initiative-api/data"
)
// CombatantPatch is a partial combatant edit: nil fields are left alone. Health values are merged
// over the stored map (keys not in the patch keep their values); the merged map is what gets
// validated.
type CombatantPatch struct {
Name *string
Kind *string
Initiative *float64
Notes *string
Health map[string]int
// Visibility settings (initiative-player-access).
Hidden *bool
HealthVisibility *string
NotesShared *bool
// Conditions replaces the combatant's conditions when non-nil; the data layer validates each.
Conditions *[]data.Condition
}
func newCombatant(c data.Combatant, id string) (data.Combatant, error) {
c.Name = strings.TrimSpace(c.Name)
if c.Name == "" {
return c, invalid("combatant name is required")
}
if !slices.Contains(kinds, c.Kind) {
return c, invalid("combatant kind %q", c.Kind)
}
c.ID, c.Removed = id, false
c.Health, c.ExternalRefs = maps.Clone(c.Health), maps.Clone(c.ExternalRefs)
c.Conditions = slices.Clone(c.Conditions)
if c.Conditions == nil {
c.Conditions = []data.Condition{}
}
return c, nil
}
func findCombatant(st *data.EncounterState, id string) (*data.Combatant, error) {
i := slices.IndexFunc(st.Combatants, func(c data.Combatant) bool { return c.ID == id })
if i < 0 {
return nil, data.ErrNotFound
}
return &st.Combatants[i], nil
}
// AddCombatant appends c to the encounter with a new ID.
func (s *Encounters) AddCombatant(ctx context.Context, owner, actor, id string, rev int64, c data.Combatant) (data.Encounter, error) {
n, err := newCombatant(c, s.newID())
if err != nil {
return data.Encounter{}, err
}
ctx = data.WithOp(ctx, data.EventCombatantAdded, n.ID)
return s.editQueue(ctx, owner, actor, id, rev, func(st *data.EncounterState, _ data.Encounter) error {
st.Combatants = append(st.Combatants, n)
return nil
})
}
// UpdateCombatant applies patch to the combatant with ID combatantID.
func (s *Encounters) UpdateCombatant(ctx context.Context, owner, actor, id string, rev int64, combatantID string, patch CombatantPatch) (data.Encounter, error) {
ctx = data.WithOp(ctx, data.EventCombatantUpdated, combatantID)
return s.editQueue(ctx, owner, actor, id, rev, func(st *data.EncounterState, _ data.Encounter) error {
c, err := findCombatant(st, combatantID)
if err != nil {
return err
}
return applyPatch(c, patch)
})
}
func applyPatch(c *data.Combatant, p CombatantPatch) error {
if p.Name != nil {
name := strings.TrimSpace(*p.Name)
if name == "" {
return invalid("combatant name is required")
}
c.Name = name
}
if p.Kind != nil {
if !slices.Contains(kinds, *p.Kind) {
return invalid("combatant kind %q", *p.Kind)
}
c.Kind = *p.Kind
}
if p.Initiative != nil {
v := *p.Initiative
c.Initiative = &v
}
if p.Notes != nil {
c.Notes = *p.Notes
}
if p.Conditions != nil {
c.Conditions = slices.Clone(*p.Conditions)
if c.Conditions == nil {
c.Conditions = []data.Condition{}
}
}
if p.Hidden != nil {
c.Hidden = *p.Hidden
}
if p.NotesShared != nil {
c.NotesShared = *p.NotesShared
}
if p.HealthVisibility != nil {
if !slices.Contains([]string{data.HealthFull, data.HealthStatus, data.HealthHidden}, *p.HealthVisibility) {
return invalid("health visibility %q", *p.HealthVisibility)
}
c.HealthVisibility = *p.HealthVisibility
}
if p.Health != nil {
merged := maps.Clone(c.Health)
if merged == nil {
merged = map[string]int{}
}
maps.Copy(merged, p.Health)
c.Health = merged
}
return nil
}
// RemoveCombatant marks the combatant removed. It stays in the record and leaves the turn queue;
// if it was current, the turn passes to the combatant that takes its place in the queue.
func (s *Encounters) RemoveCombatant(ctx context.Context, owner, actor, id string, rev int64, combatantID string) (data.Encounter, error) {
ctx = data.WithOp(ctx, data.EventCombatantRemoved, combatantID)
return s.editQueue(ctx, owner, actor, id, rev, func(st *data.EncounterState, _ data.Encounter) error {
c, err := findCombatant(st, combatantID)
if err != nil {
return err
}
c.Removed = true
return nil
})
}
// RestoreCombatant clears the removed mark and puts the combatant back in the turn queue.
func (s *Encounters) RestoreCombatant(ctx context.Context, owner, actor, id string, rev int64, combatantID string) (data.Encounter, error) {
ctx = data.WithOp(ctx, data.EventCombatantRestored, combatantID)
return s.editQueue(ctx, owner, actor, id, rev, func(st *data.EncounterState, _ data.Encounter) error {
c, err := findCombatant(st, combatantID)
if err != nil {
return err
}
c.Removed = false
return nil
})
}
package domain
import (
"context"
"errors"
"slices"
"github.com/sweetrpg/initiative-api/data"
)
// controllerRoles are the member roles that may control a combatant. An observer has no control
// over any combatant (initiative-player-access), so assigning one is refused.
var controllerRoles = []string{data.RoleGM, data.RoleCoGM, data.RolePlayer}
// AssignControllers sets the controllers of one combatant of a session's encounter, at the
// encounter revision rev, and returns the encounter as the caller (a GM or co-GM) sees it. The
// list may be empty. Every listed user must hold a live member record in the session with a
// controlling role, checked now against the session's records; a non-member or an observer is an
// invalid argument and nothing is written. The write is one atomic compare-and-set on the
// revision (data.Encounters.UpdateInSession).
func (s *Encounters) AssignControllers(ctx context.Context, sessions *Sessions, actor, sessionID, encounterID, combatantID string, userIDs []string, rev int64) (EncounterView, error) {
_, _, d, err := sessions.as(ctx, actor, sessionID, ActManageMembers)
if err != nil {
return nil, err
}
viewer, err := sessions.Viewer(ctx, actor, sessionID)
if err != nil {
return nil, err
}
if len(userIDs) > data.MaxCombatants {
return nil, invalid("at most %d controllers", data.MaxCombatants)
}
ids, err := sessions.controllersOf(ctx, d, userIDs)
if err != nil {
return nil, err
}
enc, err := s.repo.LoadForViewer(ctx, viewer, encounterID)
if err != nil {
return nil, err
}
if enc.Revision != rev {
return nil, data.ErrRevisionConflict
}
cs := slices.Clone(enc.Combatants)
i := slices.IndexFunc(cs, func(c data.Combatant) bool { return c.ID == combatantID && !c.Removed })
if i < 0 {
return nil, data.ErrNotFound
}
cs[i].ControllerUserIDs = ids
updated, err := s.repo.UpdateInSession(data.WithOp(ctx, data.EventControllers, combatantID), d, encounterID, rev, map[string]any{"combatants": cs})
if err != nil {
return nil, err
}
// A listed user may have left between the membership check and the write. If so, scrub them
// and report a conflict so the GM reassigns against the new membership.
if gone := sessions.notControllers(ctx, d, ids); len(gone) > 0 {
for _, u := range gone {
sessions.scrubControllers(ctx, d, u)
}
return nil, data.ErrConflict
}
return s.render(ctx, updated, viewer)
}
// notControllers returns the users in ids who no longer hold a controlling membership. A lookup
// that fails for any reason counts as "gone": the user is then scrubbed, which a legitimate
// controller can undo by being assigned again, whereas keeping an unverified id could not be.
func (s *Sessions) notControllers(ctx context.Context, d data.Decision, ids []string) []string {
var gone []string
for _, u := range ids {
m, err := s.repo.Member(ctx, d, u)
if err != nil || !slices.Contains(controllerRoles, m.Role) {
gone = append(gone, u)
}
}
return gone
}
// controllersOf validates userIDs against the session's live member records and returns them
// de-duplicated, in order. nil for an empty list.
func (s *Sessions) controllersOf(ctx context.Context, d data.Decision, userIDs []string) ([]string, error) {
var out []string
for _, u := range userIDs {
if slices.Contains(out, u) {
continue
}
m, err := s.repo.Member(ctx, d, u)
if err != nil && !isNotFoundOrInvalid(err) {
return nil, err
}
if err != nil {
return nil, invalid("%q is not a member of this session", u)
}
if !slices.Contains(controllerRoles, m.Role) {
return nil, invalid("%q cannot control a combatant: an observer has no control", u)
}
out = append(out, u)
}
return out, nil
}
func isNotFoundOrInvalid(err error) bool {
return errors.Is(err, data.ErrNotFound) || errors.Is(err, data.ErrInvalid)
}
package domain
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"slices"
"strings"
"sync/atomic"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/entitlements"
"github.com/sweetrpg/initiative-api/store"
)
// KeyIntegrationCredentials is the entitlement limit on active integration credentials.
const KeyIntegrationCredentials = "initiative.integration_credentials"
// SecretPrefix starts every integration secret, so the auth middleware can tell one from a user
// token without a lookup.
const SecretPrefix = "ic_"
const maxLabel = 100
// Credentials issues, lists, revokes, and authenticates integration credentials.
type Credentials struct {
repo *data.Credentials
open atomic.Bool
}
// ErrCredentialsClosed means integration credentials are off: the auth-event consumer is not
// caught up, or it fell behind the stream's retention and awaits a reconcile (PADR-0039). It is
// fail closed, so no credential authenticates and none is issued.
var ErrCredentialsClosed = errors.New("integration credentials are closed")
// NewCredentials builds the service on db.
func NewCredentials(db store.Database) *Credentials {
return &Credentials{repo: data.NewCredentials(db)}
}
// hashSecret is the stored form of a secret. The secret is 256 random bits, so a plain SHA-256 is
// enough; a slow hash would only add cost to every request.
func hashSecret(secret string) string {
sum := sha256.Sum256([]byte(secret))
return hex.EncodeToString(sum[:])
}
func newSecret() (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", err
}
return SecretPrefix + base64.RawURLEncoding.EncodeToString(b), nil
}
func validateScopes(scopes []string) error {
if len(scopes) == 0 {
return fmt.Errorf("%w: at least one scope is required", data.ErrInvalid)
}
for _, s := range scopes {
if s != data.ScopeRead && s != data.ScopeWrite {
return fmt.Errorf("%w: unknown scope %q", data.ErrInvalid, s)
}
}
return nil
}
// Open lets credentials work, unless a persisted close from an earlier run is still in force.
// Call it once the auth-event consumer has caught up. It reports whether the gate is now open.
func (s *Credentials) Open(ctx context.Context) (bool, error) {
closed, err := s.repo.GateClosed(ctx)
if err != nil || closed {
return false, err
}
s.open.Store(true)
return true, nil
}
// Pause turns credentials off in this process without persisting it: Open reopens them (unless a
// persisted close is in force) once the auth-event consumer has caught up after an outage.
func (s *Credentials) Pause() { s.open.Store(false) }
// Close turns credentials off and persists that, so a restart stays closed until Reopen.
func (s *Credentials) Close(ctx context.Context) error {
s.open.Store(false)
return s.repo.SetGate(ctx, true, "retention-gap")
}
// Reopen clears a persisted close on an administrator's say-so; actor is recorded on the gate.
func (s *Credentials) Reopen(ctx context.Context, actor string) error {
if err := s.repo.SetGate(ctx, false, actor); err != nil {
return err
}
s.open.Store(true)
return nil
}
// RevokeOwner ends every active credential of an owner the auth service has denied or stripped of
// a role, and returns how many it ended. Credentials stay for audit.
func (s *Credentials) RevokeOwner(ctx context.Context, owner, reason string) (int, error) {
if reason != data.ReasonOwnerDenied && reason != data.ReasonOwnerRoleRemoved {
return 0, fmt.Errorf("%w: unknown revoke reason %q", data.ErrInvalid, reason)
}
return s.repo.RevokeAllByOwner(ctx, owner, reason)
}
// Create issues a credential for owner and returns it with its secret, which is never available
// again. At or over the entitled limit of active credentials it returns *EntitlementError.
func (s *Credentials) Create(ctx context.Context, owner, label string, scopes []string, chk Checker) (data.IntegrationCredential, string, error) {
if !s.open.Load() {
return data.IntegrationCredential{}, "", ErrCredentialsClosed
}
label = strings.TrimSpace(label)
if label == "" || len([]rune(label)) > maxLabel {
return data.IntegrationCredential{}, "", fmt.Errorf("%w: label is required and at most %d characters", data.ErrInvalid, maxLabel)
}
if err := validateScopes(scopes); err != nil {
return data.IntegrationCredential{}, "", err
}
res, err := chk.Check(ctx, KeyIntegrationCredentials, entitlements.FailClosed)
if err != nil {
return data.IntegrationCredential{}, "", err
}
// ponytail: count-then-insert can overshoot the limit by the number of concurrent creates.
// Tighten with a per-owner slot index if that ever matters.
n, err := s.repo.CountActive(ctx, owner)
if err != nil {
return data.IntegrationCredential{}, "", err
}
if n >= int64(res.Limit) {
return data.IntegrationCredential{}, "", &EntitlementError{Key: KeyIntegrationCredentials, Limit: res.Limit}
}
secret, err := newSecret()
if err != nil {
return data.IntegrationCredential{}, "", err
}
c := data.IntegrationCredential{Label: label, Scopes: slices.Compact(slices.Sorted(slices.Values(scopes))), SecretHash: hashSecret(secret)}
if err := s.repo.Create(ctx, owner, owner, &c); err != nil {
return data.IntegrationCredential{}, "", err
}
return c, secret, nil
}
// List returns owner's credentials, newest first. Revoked ones stay listed.
func (s *Credentials) List(ctx context.Context, owner string, q data.Query) (data.Page[data.IntegrationCredential], error) {
return s.repo.List(ctx, owner, q)
}
// Revoke ends owner's credential at once; repeating it is harmless.
func (s *Credentials) Revoke(ctx context.Context, owner, id string) (data.IntegrationCredential, error) {
return s.repo.Revoke(ctx, owner, owner, id)
}
// Authenticate resolves a presented secret to its credential and records the use. A revoked,
// deleted, or unknown secret is data.ErrNotFound; the next request after a revoke fails here.
func (s *Credentials) Authenticate(ctx context.Context, secret string) (data.IntegrationCredential, error) {
if !strings.HasPrefix(secret, SecretPrefix) {
return data.IntegrationCredential{}, data.ErrNotFound
}
if !s.open.Load() {
return data.IntegrationCredential{}, ErrCredentialsClosed
}
return s.repo.Authenticate(ctx, hashSecret(secret))
}
// ListAll returns credentials across owners for an administrator, optionally for one owner.
func (s *Credentials) ListAll(ctx context.Context, owner string, q data.Query) (data.Page[data.IntegrationCredential], error) {
if owner != "" {
return s.repo.ListOwned(ctx, owner, q)
}
return s.repo.ListAll(ctx, q)
}
// DeletePermanently removes a credential for good at an administrator's say-so and records the
// reason. The next request with its secret fails, and Live turns false for open streams.
func (s *Credentials) DeletePermanently(ctx context.Context, admin, id, reason string) (data.CredentialDeletion, error) {
return s.repo.DeletePermanently(ctx, admin, id, reason)
}
// Deletions lists the audit entries of administrator deletions, optionally for one owner.
func (s *Credentials) Deletions(ctx context.Context, owner string, q data.Query) (data.Page[data.CredentialDeletion], error) {
return s.repo.Deletions(ctx, owner, q)
}
// Live reports whether credential id can still authenticate. A stream authenticated by a
// credential calls it on each heartbeat or event and closes when it turns false.
func (s *Credentials) Live(ctx context.Context, id string) (bool, error) {
if !s.open.Load() {
return false, nil
}
return s.repo.Live(ctx, id)
}
// Items is the credential repository as limit enforcement sees it; revoked credentials are not counted.
func (s *Credentials) Items() Limited { return s.repo }
package domain
import (
"context"
cryptorand "crypto/rand"
"encoding/hex"
"errors"
"fmt"
"log/slog"
"math/rand/v2"
"slices"
"strings"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/store"
)
// randomID is a combatant ID: 12 random bytes in hex. It is not an ObjectID, whose counter and
// timestamp would let a player see gaps where hidden combatants were added between visible ones.
func randomID() string {
b := make([]byte, 12)
_, _ = cryptorand.Read(b)
return hex.EncodeToString(b)
}
// ErrTransition is returned for a status change the encounter's current status does not allow.
// It wraps data.ErrInvalid.
var ErrTransition = fmt.Errorf("%w: status transition not allowed", data.ErrInvalid)
// Encounters implements encounter and combatant rules. Turn order (turn_queue) is computed by the
// ordering engine, not here: adding, restoring, or re-scoring a combatant leaves the queue to it.
type Encounters struct {
repo *data.Encounters
themes *data.Owned[data.Theme, *data.Theme]
systems *data.SystemRepo
newID func() string
perm func(n int) []int
}
// NewEncounters builds the encounter service on db.
func NewEncounters(db store.Database) *Encounters {
return &Encounters{
repo: data.NewEncounters(db),
themes: data.NewOwned[data.Theme](db, data.ThemeSpec),
systems: data.NewSystemRepo(db),
newID: randomID,
perm: rand.Perm,
}
}
// checkTheme accepts no theme, a packaged theme, or a custom theme the owner has. Another user's
// theme and a made-up ID are the same refusal, so a probe learns nothing about other accounts.
func checkTheme(ctx context.Context, themes *data.Owned[data.Theme, *data.Theme], owner, id string) error {
if id == "" || strings.HasPrefix(id, PackagedPrefix) {
return nil
}
if _, err := themes.Get(ctx, owner, id); err != nil {
if errors.Is(err, data.ErrNotFound) {
return invalid("theme_id is not one of your themes")
}
return err
}
return nil
}
// Create stores enc as owner's new draft encounter. The name is required, the game system must
// exist, and any combatants supplied get server-assigned IDs.
func (s *Encounters) Create(ctx context.Context, owner, actor string, enc data.Encounter) (data.Encounter, error) {
// An encounter joins a session only through CreateInSession, which the session's own rules
// authorize; a caller-supplied session id here is refused.
if enc.SessionID != "" {
return data.Encounter{}, invalid("an encounter cannot be created inside a session here")
}
return s.create(ctx, owner, actor, enc, requireSystem)
}
// CreateInSession stores enc as a new draft encounter of the grant's session, owned by the GM, and
// returns it as the grantee sees it. The grant (Sessions.AuthorizeEncounterCreate) carries the
// decisions: who may create, the limit, and which game systems the owner is entitled to. Two
// creates can both pass the limit check, so the new encounter is recounted after the insert and
// retracted if it put the owner over the limit.
// ponytail: concurrent creates near the limit may all be retracted; none is ever kept over it.
func (s *Encounters) CreateInSession(ctx context.Context, g EncounterGrant, enc data.Encounter) (EncounterView, error) {
enc.SessionID = g.sessionID
created, err := s.create(ctx, g.Owner, g.actor, enc, g.systemOK)
if err != nil {
return nil, err
}
n, err := s.repo.CountAll(ctx, g.Owner)
if err == nil && n > int64(g.limit) {
err = &EntitlementError{Key: KeySavedEncounters, Limit: g.limit}
}
if err != nil {
// The encounter must not stay live over the limit while the caller is told it failed: a
// retry would add another, and the limit reconciler never lists session encounters. If it
// cannot be retracted, report that (a server error) instead of the limit.
if rerr := s.repo.RetractNew(ctx, g.decision, created.ID); rerr != nil {
slog.ErrorContext(ctx, "retracting an over-limit session encounter failed", "encounter", created.ID, "error", rerr)
return nil, fmt.Errorf("could not undo a session encounter created over the limit: %w", rerr)
}
return nil, err
}
return s.render(ctx, created, g.viewer)
}
func (s *Encounters) create(ctx context.Context, owner, actor string, enc data.Encounter, systemOK func(context.Context, string) error) (data.Encounter, error) {
if err := checkTheme(ctx, s.themes, owner, enc.ThemeID); err != nil {
return data.Encounter{}, err
}
enc.Name = strings.TrimSpace(enc.Name)
if enc.Name == "" {
return data.Encounter{}, invalid("encounter name is required")
}
_, err := s.systems.Get(ctx, enc.GameSystemID)
if errors.Is(err, data.ErrNotFound) {
return data.Encounter{}, invalid("the encounter's game system is not defined")
}
if err != nil {
return data.Encounter{}, err
}
if err := systemOK(ctx, enc.GameSystemID); err != nil {
return data.Encounter{}, err
}
combatants := make([]data.Combatant, 0, len(enc.Combatants))
for _, c := range enc.Combatants {
n, err := newCombatant(c, s.newID())
if err != nil {
return data.Encounter{}, err
}
combatants = append(combatants, n)
}
enc.Combatants = combatants
if err := s.repo.Create(ctx, owner, actor, &enc); err != nil {
return data.Encounter{}, err
}
return enc, nil
}
// Get returns owner's encounter.
func (s *Encounters) Get(ctx context.Context, owner, id string) (data.Encounter, error) {
return s.repo.Get(ctx, owner, id)
}
// List returns a page of owner's encounters.
func (s *Encounters) List(ctx context.Context, owner string, q data.Query) (data.Page[data.Encounter], error) {
return s.repo.List(ctx, owner, q)
}
// Count returns how many live encounters owner holds, private and in a session alike: both count
// against the saved-encounters limit. The limit reconciler's item list is the owner's private
// encounters only (data.NewEncounters narrows reads to session_id nil), so an owner over a reduced
// limit through session encounters clears it by deleting some or by ending the session.
func (s *Encounters) Count(ctx context.Context, owner string) (int64, error) {
return s.repo.CountAll(ctx, owner)
}
// UpdateSettings sets the encounter's settings (name, game_system_id, ordering, tie_breaker,
// display flags, theme_id, position). Combat state cannot be set here, but a new ordering, tie
// breaker, or game system recomputes the turn queue in the same write.
func (s *Encounters) UpdateSettings(ctx context.Context, owner, actor, id string, rev int64, set map[string]any) (data.Encounter, error) {
if name, ok := set["name"].(string); ok {
set["name"] = strings.TrimSpace(name)
}
if theme, ok := set["theme_id"].(string); ok {
if err := checkTheme(ctx, s.themes, owner, theme); err != nil {
return data.Encounter{}, err
}
}
if sysID, ok := set["game_system_id"].(string); ok {
if err := requireSystem(ctx, sysID); err != nil {
return data.Encounter{}, err
}
}
_, ord := set["ordering"]
_, tie := set["tie_breaker"]
_, sys := set["game_system_id"]
if !ord && !tie && !sys {
return s.repo.Update(ctx, owner, actor, id, rev, set)
}
cur, err := s.repo.Load(ctx, owner, id)
if err != nil {
return data.Encounter{}, err
}
o, t, sysID := cur.Ordering, cur.TieBreaker, cur.GameSystemID
if v, ok := set["ordering"].(string); ok {
o = v
}
if v, ok := set["game_system_id"].(string); ok {
sysID = v
}
if v, ok := set["tie_breaker"].(string); ok {
t = v
}
st := stateOf(cur)
s.recompute(&st, effectiveOrdering(o, sysID), t)
return s.repo.Write(ctx, owner, actor, id, rev, set, st)
}
func stateOf(cur data.Encounter) data.EncounterState {
return data.EncounterState{
Status: cur.Status, Round: cur.Round, CurrentCombatantID: cur.CurrentCombatantID,
TurnQueue: slices.Clone(cur.TurnQueue), Combatants: slices.Clone(cur.Combatants),
}
}
// editQueue is edit followed by a turn-queue recompute under the encounter's ordering.
func (s *Encounters) editQueue(ctx context.Context, owner, actor, id string, rev int64, change func(*data.EncounterState, data.Encounter) error) (data.Encounter, error) {
return s.edit(ctx, owner, actor, id, rev, func(st *data.EncounterState, cur data.Encounter) error {
if err := change(st, cur); err != nil {
return err
}
s.recompute(st, effectiveOrdering(cur.Ordering, cur.GameSystemID), cur.TieBreaker)
return nil
})
}
// Delete soft-deletes the encounter.
func (s *Encounters) Delete(ctx context.Context, owner, actor, id string, rev int64) error {
return s.repo.SoftDelete(ctx, owner, actor, id, rev)
}
// edit reads the encounter, applies change to its state, and writes the result compare-and-set on
// rev. A missed read is classified 403/404 like the write paths.
// change also receives the encounter as read, for its settings.
func (s *Encounters) edit(ctx context.Context, owner, actor, id string, rev int64, change func(*data.EncounterState, data.Encounter) error) (data.Encounter, error) {
cur, err := s.repo.Load(ctx, owner, id)
if err != nil {
return data.Encounter{}, err
}
st := stateOf(cur)
if err := change(&st, cur); err != nil {
return data.Encounter{}, err
}
return s.repo.SetState(ctx, owner, actor, id, rev, st)
}
// FindByExternalRef returns owner's combatants whose external_refs map key to value.
func (s *Encounters) FindByExternalRef(ctx context.Context, owner, key, value string) ([]data.RefMatch, error) {
return s.repo.FindByExternalRef(ctx, owner, key, value)
}
// SetSink installs the sink told of every committed encounter change made through this service.
func (s *Encounters) SetSink(k data.Sink) { s.repo.SetSink(k) }
// Items is the encounter repository as limit enforcement sees it.
func (s *Encounters) Items() Limited { return s.repo }
package domain
import (
"cmp"
"slices"
"strings"
"github.com/sweetrpg/initiative-api/data"
)
// Pure turn-order logic: no I/O, no clock. Randomness comes in as a permutation function.
type entry struct {
c data.Combatant
listIdx int
prevIdx int // position in the previous queue, -1 if it was not queued
rank int // random rank among newly queued combatants
}
func kindGroup(ordering, kind string) int {
if ordering != data.OrderPCVsAdversary {
return 0
}
switch kind {
case data.KindPC:
return 0
case data.KindAdversary:
return 1
}
return 2
}
// initiativeCmp orders by initiative, unset last. lowToHigh ascends; everything else descends.
func initiativeCmp(ordering string, a, b *float64) int {
switch {
case a == nil && b == nil:
return 0
case a == nil:
return 1
case b == nil:
return -1
case ordering == data.OrderLowToHigh:
return cmp.Compare(*a, *b)
}
return cmp.Compare(*b, *a)
}
func tieCmp(tie string, prevLen int, a, b entry) int {
switch tie {
case data.TieAlphabetical:
if c := strings.Compare(strings.ToLower(a.c.Name), strings.ToLower(b.c.Name)); c != 0 {
return c
}
return strings.Compare(a.c.ID, b.c.ID)
case data.TieRandom:
// Combatants already queued keep their relative order, so a recompute never reshuffles
// ties mid-combat. Newly queued ones fall in behind them in random order.
return cmp.Compare(randKey(a, prevLen), randKey(b, prevLen))
}
return cmp.Compare(a.listIdx, b.listIdx) // data.TieQuery: encounter list order
}
func randKey(e entry, prevLen int) int {
if e.prevIdx >= 0 {
return e.prevIdx
}
return prevLen + e.rank
}
// buildQueue returns the IDs of the non-removed combatants in turn order. prev is the existing
// queue. perm(n) returns a random permutation of 0..n-1.
//
// playerManaged keeps prev's order, dropping departed combatants and appending new ones in list
// order. The other orderings sort by kind group (pcVsAdversary only: pc, adversary, object), then
// initiative, then the tie breaker.
func buildQueue(ordering, tie string, cs []data.Combatant, prev []string, perm func(int) []int) []string {
prevIdx := make(map[string]int, len(prev))
for i, id := range prev {
prevIdx[id] = i
}
var es []entry
for i, c := range cs {
if c.Removed {
continue
}
pi, ok := prevIdx[c.ID]
if !ok {
pi = -1
}
es = append(es, entry{c: c, listIdx: i, prevIdx: pi})
}
if ordering == data.OrderPlayerManaged {
return manualQueue(es)
}
assignRanks(es, perm)
slices.SortStableFunc(es, func(a, b entry) int {
return cmp.Or(
cmp.Compare(kindGroup(ordering, a.c.Kind), kindGroup(ordering, b.c.Kind)),
initiativeCmp(ordering, a.c.Initiative, b.c.Initiative),
tieCmp(tie, len(prev), a, b),
cmp.Compare(a.listIdx, b.listIdx),
)
})
return ids(es)
}
func assignRanks(es []entry, perm func(int) []int) {
var fresh []int
for i, e := range es {
if e.prevIdx < 0 {
fresh = append(fresh, i)
}
}
if len(fresh) == 0 {
return
}
for r, p := range perm(len(fresh)) {
es[fresh[r]].rank = p
}
}
func manualQueue(es []entry) []string {
slices.SortStableFunc(es, func(a, b entry) int {
switch {
case a.prevIdx >= 0 && b.prevIdx >= 0:
return cmp.Compare(a.prevIdx, b.prevIdx)
case a.prevIdx >= 0:
return -1
case b.prevIdx >= 0:
return 1
}
return cmp.Compare(a.listIdx, b.listIdx)
})
return ids(es)
}
func ids(es []entry) []string {
out := make([]string, 0, len(es))
for _, e := range es {
out = append(out, e.c.ID)
}
return out
}
// expireConditions applies the start-of-turn rule to c: each timed condition loses one round and
// is removed at zero. Open-ended conditions are untouched. It builds a new slice, so shared
// backing arrays are never written.
func expireConditions(c *data.Combatant) {
next := make([]data.Condition, 0, len(c.Conditions))
for _, cond := range c.Conditions {
if cond.RoundsRemaining == nil {
next = append(next, cond)
continue
}
if left := *cond.RoundsRemaining - 1; left > 0 {
next = append(next, data.Condition{Name: cond.Name, RoundsRemaining: &left})
}
}
c.Conditions = next
}
// nextTurn returns the queue position after pos and whether it wrapped past the end. pos -1 (no
// current combatant) yields position 0 without wrapping.
func nextTurn(pos, n int) (idx int, wrapped bool) {
if pos+1 >= n {
return 0, pos >= 0
}
return pos + 1, false
}
// prevTurn returns the queue position before pos and whether it wrapped past the start.
func prevTurn(pos, n int) (idx int, wrapped bool) {
if pos <= 0 {
return n - 1, true
}
return pos - 1, false
}
package domain
import (
"context"
"errors"
"fmt"
"log/slog"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/entitlements"
)
// KeyGameSystemsExtra is the flag that unlocks every game system other than No System.
const KeyGameSystemsExtra = "initiative.game_systems_extra"
// EntitlementRequiredError is the typed denial for a flag the caller does not hold.
type EntitlementRequiredError struct{ Key string }
func (e *EntitlementRequiredError) Error() string {
return fmt.Sprintf("domain: entitlement %s is required", e.Key)
}
// ErrLimitsNotSynced is returned to an integration credential when the owner's entitlement value it
// needs has not been recorded yet. A credential has no user bearer to read entitlements with, so the
// owner must use Initiative once with their own sign-in (the app's usage and create calls record
// the values). It fails closed.
var ErrLimitsNotSynced = errors.New("domain: the owner's entitlement values have not been recorded yet")
type checkerKey struct{}
// WithChecker attaches the calling user's entitlement checker to ctx, so rules deep in the domain
// (a system switch inside a settings update) can check without every signature carrying it. The
// server sets it per request, bound to that user's own bearer (PADR-0037).
func WithChecker(ctx context.Context, c Checker) context.Context {
return context.WithValue(ctx, checkerKey{}, c)
}
// requireSystem rejects use of a gated game system by a caller without the flag. No System is
// free. Creates and switches fail closed: with no checker in ctx or entitlements unreachable the
// call is refused.
func requireSystem(ctx context.Context, systemID string) error {
if systemID == "" || systemID == data.DefaultSystemID {
return nil
}
chk, ok := ctx.Value(checkerKey{}).(Checker)
if !ok {
return entitlements.ErrUnavailable
}
res, err := chk.Check(ctx, KeyGameSystemsExtra, entitlements.FailClosed)
if err != nil {
return err
}
if !res.Flag {
return &EntitlementRequiredError{Key: KeyGameSystemsExtra}
}
return nil
}
// Locks keeps encounters that use a gated game system in step with the owner's flag: locked while
// it is missing, restored unchanged when it returns.
type Locks struct {
repo *data.Encounters
}
// Locks returns the lock reconciler for these encounters.
func (s *Encounters) Locks() *Locks { return &Locks{repo: s.repo} }
// Reconcile reads the flag and locks or unlocks owner's encounters to match. When entitlements
// cannot be read it changes nothing, so an outage never locks anyone out.
func (l *Locks) Reconcile(ctx context.Context, owner string, chk Checker) error {
res, err := chk.Check(ctx, KeyGameSystemsExtra, entitlements.FailOpen)
if err != nil {
return err
}
if res.Degraded {
return nil
}
var n int
if res.Flag {
n, err = l.repo.UnlockAll(ctx, owner)
} else {
n, err = l.repo.LockGated(ctx, owner)
}
if n > 0 {
slog.InfoContext(ctx, "game-system locks changed", "locked", !res.Flag, "count", n)
}
return err
}
package domain
import (
"context"
"log/slog"
"slices"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/entitlements"
)
// Entitlement keys for the stored-item limits.
const (
KeySavedRosters = "initiative.saved_rosters"
KeySavedEncounters = "initiative.saved_encounters"
KeySessionsPerGM = "initiative.sessions_per_gm"
// KeyMembersPerSession is recorded on each session and enforced when a member is approved.
KeyMembersPerSession = "initiative.members_per_session"
)
// Limited is a repository whose items can go inactive when the owner's limit falls.
type Limited interface {
ItemStates(ctx context.Context, owner string) ([]data.ItemState, error)
SetInactive(ctx context.Context, owner, id string, inactive bool) error
SetKeepRanks(ctx context.Context, owner string, ids []string) error
}
// Kind is one limited item type: its URL name, its entitlement key, and its items.
type Kind struct {
Name string
Key string
Repo Limited
}
// Limits keeps only as many of an owner's items active as the entitled limit allows (spec
// initiative-entitlement-gating). It never deletes or archives anything.
type Limits struct {
kinds []Kind
}
// NewLimits builds the enforcer for kinds.
func NewLimits(kinds ...Kind) *Limits { return &Limits{kinds: kinds} }
// plan returns the IDs to activate and to deactivate so that exactly the first limit items in
// preference order are active: the owner's choice (by rank) first, then oldest first. states must
// arrive oldest first.
func plan(states []data.ItemState, limit int) (activate, deactivate []string) {
ordered := slices.Clone(states)
slices.SortStableFunc(ordered, func(a, b data.ItemState) int {
switch {
case a.KeepRank > 0 && b.KeepRank > 0:
return a.KeepRank - b.KeepRank
case a.KeepRank > 0:
return -1
case b.KeepRank > 0:
return 1
}
return 0
})
for i, st := range ordered {
switch {
case i < limit && st.Inactive:
activate = append(activate, st.ID)
case i >= limit && !st.Inactive:
deactivate = append(deactivate, st.ID)
}
}
return activate, deactivate
}
func (l *Limits) kind(name string) (Kind, bool) {
for _, k := range l.kinds {
if k.Name == name {
return k, true
}
}
return Kind{}, false
}
func (l *Limits) apply(ctx context.Context, owner string, k Kind, limit int) error {
states, err := k.Repo.ItemStates(ctx, owner)
if err != nil {
return err
}
activate, deactivate := plan(states, limit)
for _, id := range deactivate {
if err := k.Repo.SetInactive(ctx, owner, id, true); err != nil {
return err
}
}
for _, id := range activate {
if err := k.Repo.SetInactive(ctx, owner, id, false); err != nil {
return err
}
}
return nil
}
// Reconcile brings every kind in line with owner's current limits. When entitlements cannot be
// read it leaves that kind as it is, so an outage never deactivates anything. It tries every
// kind and returns the first error.
func (l *Limits) Reconcile(ctx context.Context, owner string, chk Checker) error {
var first error
for _, k := range l.kinds {
res, err := chk.Check(ctx, k.Key, entitlements.FailOpen)
if err == nil && res.Degraded {
continue
}
if err == nil {
err = l.apply(ctx, owner, k, res.Limit)
}
if err != nil {
slog.WarnContext(ctx, "limit reconcile failed", "kind", k.Name, "error", err)
if first == nil {
first = err
}
}
}
return first
}
// Choose records which items of a kind the owner wants active, in order, then applies the limit.
// ids must be distinct items the owner holds, at most the limit; if fewer than the limit are
// chosen, the remaining places go to the oldest other items. Returns the active IDs afterward.
func (l *Limits) Choose(ctx context.Context, owner, kind string, ids []string, chk Checker) ([]string, error) {
k, ok := l.kind(kind)
if !ok {
return nil, data.ErrNotFound
}
res, err := chk.Check(ctx, k.Key, entitlements.FailClosed)
if err != nil {
return nil, err
}
states, err := k.Repo.ItemStates(ctx, owner)
if err != nil {
return nil, err
}
if len(ids) > res.Limit {
return nil, invalid("at most %d items can be active", res.Limit)
}
held := make(map[string]bool, len(states))
for _, st := range states {
held[st.ID] = true
}
seen := map[string]bool{}
for _, id := range ids {
if !held[id] || seen[id] {
return nil, invalid("ids must be distinct items you own")
}
seen[id] = true
}
if err := k.Repo.SetKeepRanks(ctx, owner, ids); err != nil {
return nil, err
}
if err := l.apply(ctx, owner, k, res.Limit); err != nil {
return nil, err
}
after, err := k.Repo.ItemStates(ctx, owner)
if err != nil {
return nil, err
}
active := []string{}
for _, st := range after {
if !st.Inactive {
active = append(active, st.ID)
}
}
return active, nil
}
package domain
import (
"context"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/store"
)
// NotificationPrefs lets a session member mute notice types for that session.
type NotificationPrefs struct {
repo *data.NotificationPrefs
sessions *Sessions
}
// NewNotificationPrefs builds the service on db.
func NewNotificationPrefs(db store.Database, sessions *Sessions) *NotificationPrefs {
return &NotificationPrefs{repo: data.NewNotificationPrefs(db), sessions: sessions}
}
// Get returns the types actor has muted for the session. Only a member may read them.
func (s *NotificationPrefs) Get(ctx context.Context, actor, sessionID string) ([]string, error) {
if _, _, _, err := s.sessions.as(ctx, actor, sessionID, ActView); err != nil {
return nil, err
}
return s.repo.Muted(ctx, actor, sessionID)
}
// Set replaces the types actor has muted for the session and returns the stored list.
func (s *NotificationPrefs) Set(ctx context.Context, actor, sessionID string, muted []string) ([]string, error) {
if _, _, _, err := s.sessions.as(ctx, actor, sessionID, ActView); err != nil {
return nil, err
}
return s.repo.SetMuted(ctx, actor, sessionID, muted)
}
// Muted is the event path's read of a user's mutes (stream.Preferences): the fan-out acts for the
// addressee, so it reads that one user's record and nobody else's.
func (s *NotificationPrefs) Muted(ctx context.Context, userID, sessionID string) ([]string, error) {
return s.repo.Muted(ctx, userID, sessionID)
}
// Package domain holds initiative-api's rules over the owner-scoped data layer: rosters and
// characters, and moving cast between rosters and encounters. All access goes through data's
// owner-scoped repositories, so every call carries the caller's user ID.
package domain
import (
"context"
"errors"
"fmt"
"maps"
"slices"
"strings"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/store"
"go.mongodb.org/mongo-driver/bson/primitive"
)
var kinds = data.Kinds
// Rosters implements roster and character rules.
type Rosters struct {
themes *data.Owned[data.Theme, *data.Theme]
rosters *data.Owned[data.Roster, *data.Roster]
encounters *data.Encounters
newID func() string
}
// NewRosters builds the roster service on db.
func NewRosters(db store.Database) *Rosters {
return &Rosters{
themes: data.NewOwned[data.Theme](db, data.ThemeSpec),
rosters: data.NewOwned[data.Roster](db, data.RosterSpec),
encounters: data.NewEncounters(db),
newID: func() string { return primitive.NewObjectID().Hex() },
}
}
// SetSink installs the sink told of the encounters this service creates from a roster.
func (s *Rosters) SetSink(k data.Sink) { s.encounters.SetSink(k) }
func invalid(format string, a ...any) error {
return fmt.Errorf("%w: %s", data.ErrInvalid, fmt.Sprintf(format, a...))
}
// normalize trims and validates a character, copying its maps so the stored value does not alias
// the caller's. The ID is left for the caller to assign.
func normalize(c data.Character) (data.Character, error) {
c.Name = strings.TrimSpace(c.Name)
if c.Name == "" {
return c, invalid("character name is required")
}
if err := errors.Join(data.CheckText("character name", c.Name, data.MaxNameLen), data.CheckText("character notes", c.Notes, data.MaxNotesLen),
data.CheckMaps("character", c.Health, c.ExternalRefs)); err != nil {
return c, err
}
if !slices.Contains(kinds, c.Kind) {
return c, invalid("character kind %q", c.Kind)
}
c.Health, c.ExternalRefs = maps.Clone(c.Health), maps.Clone(c.ExternalRefs)
return c, nil
}
func (s *Rosters) prepare(chars []data.Character) ([]data.Character, error) {
if len(chars) > data.MaxCharacters {
return nil, invalid("a roster holds at most %d characters", data.MaxCharacters)
}
out := make([]data.Character, 0, len(chars))
for _, c := range chars {
n, err := normalize(c)
if err != nil {
return nil, err
}
n.ID = s.newID()
out = append(out, n)
}
return out, nil
}
// Create stores a new roster for owner. Character IDs are assigned here; any supplied are ignored.
func (s *Rosters) Create(ctx context.Context, owner, actor, name string, favorite bool, chars []data.Character) (data.Roster, error) {
name = strings.TrimSpace(name)
if err := data.CheckName("roster name", name); err != nil {
return data.Roster{}, err
}
prepared, err := s.prepare(chars)
if err != nil {
return data.Roster{}, err
}
r := data.Roster{Name: name, Favorite: favorite, Characters: prepared}
if err := s.rosters.Create(ctx, owner, actor, &r); err != nil {
return data.Roster{}, err
}
return r, nil
}
// Load returns owner's roster; a miss is 403 when the roster belongs to another owner and 404
// when there is none, decided after the owner-scoped read has already failed.
func (s *Rosters) Load(ctx context.Context, owner, id string) (data.Roster, error) {
r, err := s.rosters.Get(ctx, owner, id)
if errors.Is(err, data.ErrNotFound) {
if cerr := s.rosters.Missing(ctx, owner, id); cerr != nil {
return data.Roster{}, cerr
}
}
return r, err
}
// Get returns owner's roster.
func (s *Rosters) Get(ctx context.Context, owner, id string) (data.Roster, error) {
return s.rosters.Get(ctx, owner, id)
}
// List returns a page of owner's rosters.
func (s *Rosters) List(ctx context.Context, owner string, q data.Query) (data.Page[data.Roster], error) {
return s.rosters.List(ctx, owner, q)
}
// Count returns how many rosters owner holds.
func (s *Rosters) Count(ctx context.Context, owner string) (int64, error) {
return s.rosters.Count(ctx, owner, nil)
}
// Rename sets the roster's name and favorite flag, compare-and-set on revision.
func (s *Rosters) Rename(ctx context.Context, owner, actor, id string, rev int64, name string, favorite bool) (data.Roster, error) {
name = strings.TrimSpace(name)
if err := data.CheckName("roster name", name); err != nil {
return data.Roster{}, err
}
return s.rosters.Update(ctx, owner, actor, id, rev, map[string]any{"name": name, "favorite": favorite})
}
// Delete soft-deletes the roster. Encounters created from it keep their combatants.
func (s *Rosters) Delete(ctx context.Context, owner, actor, id string, rev int64) error {
return s.rosters.SoftDelete(ctx, owner, actor, id, rev)
}
// editCharacters applies edit to a copy of the roster's characters and writes the result
// compare-and-set on rev.
func (s *Rosters) editCharacters(ctx context.Context, owner, actor, id string, rev int64, edit func([]data.Character) ([]data.Character, error)) (data.Roster, error) {
cur, err := s.rosters.Get(ctx, owner, id)
if errors.Is(err, data.ErrNotFound) {
// The read is only needed to build the new character list; classify a miss as 403 or 404
// like the write paths do.
if cerr := s.rosters.Missing(ctx, owner, id); cerr != nil {
return data.Roster{}, cerr
}
}
if err != nil {
return data.Roster{}, err
}
next, err := edit(slices.Clone(cur.Characters))
if err != nil {
return data.Roster{}, err
}
if len(next) > data.MaxCharacters {
return data.Roster{}, invalid("a roster holds at most %d characters", data.MaxCharacters)
}
return s.rosters.Update(ctx, owner, actor, id, rev, map[string]any{"characters": next})
}
func indexOf(chars []data.Character, id string) int {
return slices.IndexFunc(chars, func(c data.Character) bool { return c.ID == id })
}
// AddCharacter appends c to the roster with a new ID.
func (s *Rosters) AddCharacter(ctx context.Context, owner, actor, id string, rev int64, c data.Character) (data.Roster, error) {
n, err := normalize(c)
if err != nil {
return data.Roster{}, err
}
n.ID = s.newID()
return s.editCharacters(ctx, owner, actor, id, rev, func(cs []data.Character) ([]data.Character, error) {
return append(cs, n), nil
})
}
// UpdateCharacter replaces the roster character with ID charID, keeping its ID.
func (s *Rosters) UpdateCharacter(ctx context.Context, owner, actor, id string, rev int64, charID string, c data.Character) (data.Roster, error) {
n, err := normalize(c)
if err != nil {
return data.Roster{}, err
}
n.ID = charID
return s.editCharacters(ctx, owner, actor, id, rev, func(cs []data.Character) ([]data.Character, error) {
i := indexOf(cs, charID)
if i < 0 {
return nil, data.ErrNotFound
}
cs[i] = n
return cs, nil
})
}
// RemoveCharacter deletes the roster character with ID charID.
func (s *Rosters) RemoveCharacter(ctx context.Context, owner, actor, id string, rev int64, charID string) (data.Roster, error) {
return s.editCharacters(ctx, owner, actor, id, rev, func(cs []data.Character) ([]data.Character, error) {
i := indexOf(cs, charID)
if i < 0 {
return nil, data.ErrNotFound
}
return slices.Delete(cs, i, i+1), nil
})
}
// Items is the roster repository as limit enforcement sees it.
func (s *Rosters) Items() Limited { return s.rosters }
package domain
import (
"context"
"errors"
"fmt"
"log/slog"
"slices"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/relations"
)
// SessionAuthority is auth-api's session surface (PADR-0040): minting a session ID, ending a
// session, and writing membership tuples. *relations.Client implements it. Every call forwards the
// caller's own bearer (PADR-0037).
type SessionAuthority interface {
Mint(ctx context.Context, token string) (string, error)
EndSession(ctx context.Context, token, sessionID string) error
WriteTuples(ctx context.Context, token, sessionID string, writes, deletes []relations.Tuple) error
}
// ErrSyncPending means a membership change was saved but its OpenFGA tuple could not be written.
// The member is denied until the tuple exists, which is the safe direction; repeating the request
// finishes the write, and the reconciler repairs it within one interval otherwise.
var ErrSyncPending = errors.New("domain: membership saved, tuple sync pending")
type authorityKey struct{}
type authority struct {
svc SessionAuthority
token string
}
// WithAuthority puts auth-api's session surface and the caller's bearer on ctx. Without it every
// session change fails closed.
func WithAuthority(ctx context.Context, svc SessionAuthority, token string) context.Context {
return context.WithValue(ctx, authorityKey{}, authority{svc, token})
}
func authorityOf(ctx context.Context) (authority, error) {
a, ok := ctx.Value(authorityKey{}).(authority)
if !ok || a.svc == nil {
return authority{}, relations.ErrUnavailable
}
return a, nil
}
// memberRoles are the relations the membership endpoint writes; gm is never one.
var memberRoles = []string{data.RoleCoGM, data.RolePlayer, data.RoleObserver}
func tupleOf(user, role string) relations.Tuple {
return relations.Tuple{User: "user:" + user, Relation: role}
}
// syncGrant writes user's role tuple after the Mongo record exists. It deletes the user's other
// non-gm relations in the same atomic write, so a role change or a retry cannot leave two roles;
// a non-GM actor leaves co_gm tuples alone because only the GM changes those (PADR-0040 section 2).
// A refusal from auth-api is returned as such; an outage is ErrSyncPending. A SetRole retry by a
// co_gm when Mongo already holds the new role cannot know the old relation, so it leaves a stale
// co_gm tuple for the reconciler to remove (accepted: only the GM changes co_gm members).
func (s *Sessions) syncGrant(ctx context.Context, actorRole, sessionID, user, role string) error {
a, err := authorityOf(ctx)
if err != nil {
return fmt.Errorf("%w: %w", ErrSyncPending, err)
}
var deletes []relations.Tuple
for _, r := range memberRoles {
if r != role && (r != data.RoleCoGM || actorRole == data.RoleGM) {
deletes = append(deletes, tupleOf(user, r))
}
}
err = a.svc.WriteTuples(ctx, a.token, sessionID, []relations.Tuple{tupleOf(user, role)}, deletes)
switch {
case err == nil:
return nil
case errors.Is(err, relations.ErrUnauthorized), errors.Is(err, relations.ErrDenied),
errors.Is(err, relations.ErrLimited), errors.Is(err, relations.ErrConflict),
errors.Is(err, relations.ErrRejected):
// auth-api answered with a refusal the client should see as such (401, 403, 429, 409
// session_full). Mongo is already written, so the member is denied until the tuple exists,
// which is the safe direction; the reconciler repairs it. Only an outage is "pending".
return err
}
slog.WarnContext(ctx, "membership tuple write failed; the reconciler will repair it", "session", sessionID, "user", user, "error", err)
return fmt.Errorf("%w: %w", ErrSyncPending, err)
}
// syncRevoke deletes user's role tuple after the Mongo record is gone. The change has already taken
// effect (the member lost access when the record went), so a failure is logged and left to the
// reconciler instead of failing the request. The GM deletes all three member relations in one
// request, so a stale co_gm tuple left by a demotion whose write failed cannot outlive the removal;
// anyone else deletes only the member's own role tuple, which is all their auth-api rights cover.
func (s *Sessions) syncRevoke(ctx context.Context, actorRole, sessionID, user, role string) {
if !slices.Contains(memberRoles, role) {
return
}
deletes := []relations.Tuple{tupleOf(user, role)}
if actorRole == data.RoleGM {
deletes = deletes[:0]
for _, r := range memberRoles {
deletes = append(deletes, tupleOf(user, r))
}
}
a, err := authorityOf(ctx)
if err == nil {
err = a.svc.WriteTuples(ctx, a.token, sessionID, nil, deletes)
}
if err != nil {
slog.WarnContext(ctx, "membership tuple delete failed; the reconciler will remove it", "session", sessionID, "user", user, "error", err)
}
}
// endSession tells auth-api to drop every tuple on the session and close its mint, and returns
// the failure. Deleting a session reports it (a retry ends the session again); rolling back a
// failed create only logs it, since garbage collection closes the mint.
func (s *Sessions) endSession(ctx context.Context, sessionID string) error {
a, err := authorityOf(ctx)
if err == nil {
err = a.svc.EndSession(ctx, a.token, sessionID)
}
return err
}
// canManageRole reports whether actorRole may assign or remove role. Only the GM changes a co_gm
// (PADR-0040): a co_gm calling auth-api directly could otherwise strip other co-GMs.
func canManageRole(actorRole, role string) bool {
return role != data.RoleCoGM || actorRole == data.RoleGM
}
package domain
import (
"context"
"time"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/entitlements"
)
// defaultOwnerRecordMaxAge is the default OWNER_ENTITLEMENTS_MAX_AGE, used when
// Sessions.OwnerRecordMaxAge is not set.
const defaultOwnerRecordMaxAge = 7 * 24 * time.Hour
// ownerRecordMaxAge bounds how old the GM's entitlements recorded on a session may be when a
// co-GM acts on them: Sessions.OwnerRecordMaxAge (the configured OWNER_ENTITLEMENTS_MAX_AGE), or
// seven days when unset. Past it, or with nothing recorded, a co-GM's create fails closed until
// the GM next uses the session.
func (s *Sessions) ownerRecordMaxAge() time.Duration {
if s.OwnerRecordMaxAge > 0 {
return s.OwnerRecordMaxAge
}
return defaultOwnerRecordMaxAge
}
// EncounterGrant is the outcome of authorizing one encounter creation in a session: who may
// create, the owner it belongs to (the GM), the saved-encounters limit, how to see the result, and
// which game systems the owner is entitled to. Only AuthorizeEncounterCreate makes one.
type EncounterGrant struct {
// Owner is the GM, who owns the encounter whoever creates it.
Owner string
actor string
sessionID string
limit int
decision data.Decision
viewer data.Viewer
systemOK func(ctx context.Context, systemID string) error
}
// AuthorizeEncounterCreate decides whether actor may create an encounter in the session. The GM
// always may; a co-GM only while the GM has the setting on, read fresh on every call so turning it
// off takes effect at once. The GM's saved-encounters limit applies with private and session
// encounters counted together. The GM is checked live with their own entitlements; a co-GM is
// checked against the GM's entitlements recorded on the session, failing closed when none are
// recorded or the record is older than the configured maximum age. That covers the limit and the
// game-systems flag, so a co-GM can neither use a system the GM lacks nor be refused one the GM has.
func (s *Sessions) AuthorizeEncounterCreate(ctx context.Context, actor, id string) (EncounterGrant, error) {
sess, m, d, err := s.as(ctx, actor, id, ActCreateEncounter)
if err != nil {
return EncounterGrant{}, err
}
if m.Role == data.RoleCoGM && !sess.AllowCoGMCreateEncounter {
return EncounterGrant{}, data.ErrForbidden
}
g := EncounterGrant{Owner: sess.OwnerUserID, actor: actor, sessionID: sess.ID, decision: d}
if g.limit, g.systemOK, err = s.ownerEntitlements(ctx, sess, m.Role); err != nil {
return EncounterGrant{}, err
}
n, err := s.enc.CountAll(ctx, sess.OwnerUserID)
if err != nil {
return EncounterGrant{}, err
}
if n >= int64(g.limit) {
return EncounterGrant{}, &EntitlementError{Key: KeySavedEncounters, Limit: g.limit}
}
if g.viewer, err = s.repo.AuthorizeView(ctx, actor, id); err != nil {
return EncounterGrant{}, err
}
return g, nil
}
// ownerEntitlements returns the saved-encounters limit and the game-system gate for a creator.
func (s *Sessions) ownerEntitlements(ctx context.Context, sess data.Session, role string) (int, func(context.Context, string) error, error) {
if role == data.RoleGM {
chk, ok := ctx.Value(checkerKey{}).(Checker)
if !ok {
return 0, nil, entitlements.ErrUnavailable
}
res, err := chk.Check(ctx, KeySavedEncounters, entitlements.FailClosed)
return res.Limit, requireSystem, err
}
if sess.OwnerLimitsAt == nil || s.now().Sub(*sess.OwnerLimitsAt) > s.ownerRecordMaxAge() {
return 0, nil, ErrOwnerLimitsUnknown
}
limit, err := OwnerLimit(sess, KeySavedEncounters)
if err != nil {
return 0, nil, err
}
return limit, recordedSystemGate(sess), nil
}
// recordedSystemGate gates game systems on the owner's recorded flag. No System is always allowed.
func recordedSystemGate(sess data.Session) func(context.Context, string) error {
return func(_ context.Context, systemID string) error {
if systemID == "" || systemID == data.DefaultSystemID {
return nil
}
flag, ok := sess.OwnerFlags[KeyGameSystemsExtra]
if !ok {
return ErrOwnerLimitsUnknown
}
if !flag {
return &EntitlementRequiredError{Key: KeyGameSystemsExtra}
}
return nil
}
}
package domain
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base32"
"encoding/hex"
"errors"
"fmt"
"log/slog"
"maps"
"slices"
"strings"
"time"
"github.com/sweetrpg/initiative-api/constants"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/entitlements"
"github.com/sweetrpg/initiative-api/relations"
"github.com/sweetrpg/initiative-api/store"
)
// Action is something a session member may try to do. Allowed is the one place the role rules
// live (spec initiative-sessions, "Roles").
type Action string
// Session actions.
const (
ActView Action = "view"
ActInvite Action = "invite"
ActDecideRequest Action = "decide_request"
ActManageMembers Action = "manage_members"
ActBlock Action = "block"
ActLeave Action = "leave"
ActDelete Action = "delete_session"
ActUpdate Action = "update_session"
ActCreateEncounter Action = "create_encounter"
)
var allowed = map[Action][]string{
ActView: {data.RoleGM, data.RoleCoGM, data.RolePlayer, data.RoleObserver},
ActInvite: {data.RoleGM, data.RoleCoGM},
ActDecideRequest: {data.RoleGM, data.RoleCoGM},
ActManageMembers: {data.RoleGM, data.RoleCoGM},
ActBlock: {data.RoleGM, data.RoleCoGM},
ActLeave: {data.RoleCoGM, data.RolePlayer, data.RoleObserver},
ActDelete: {data.RoleGM},
ActUpdate: {data.RoleGM},
ActCreateEncounter: {data.RoleGM, data.RoleCoGM},
}
// Allowed reports whether a member holding role may take action.
func Allowed(role string, a Action) bool { return slices.Contains(allowed[a], role) }
// assignable are the roles a manager can give. There is exactly one gm, so gm is never assigned.
var assignable = []string{data.RoleCoGM, data.RolePlayer, data.RoleObserver}
// Invite lifetimes.
const (
defaultInviteTTL = 7 * 24 * time.Hour
minInviteTTL = time.Hour
maxInviteTTL = 30 * 24 * time.Hour
maxSessionName = 100
)
// ErrInviteInvalid covers an unknown, expired, revoked, or blocked invite alike, so a code reveals
// nothing about why it failed.
var ErrInviteInvalid = fmt.Errorf("%w: invite is not valid", data.ErrInvalid)
// ErrOwnerLimitsUnknown means the session has no recorded owner entitlements yet and the owner is
// not the caller. It is retryable: the GM's next request records them.
var ErrOwnerLimitsUnknown = errors.New("domain: session owner entitlements not recorded yet")
// ownerLimitsRefreshEvery bounds how often an unchanged record is rewritten.
const ownerLimitsRefreshEvery = time.Minute
// sessionKeys are the owner entitlements recorded on a session.
var sessionKeys = []string{KeyMembersPerSession, KeySavedEncounters}
// sessionFlags are the owner flags recorded on a session beside the limits.
var sessionFlags = []string{KeyGameSystemsExtra}
// OwnerLimit returns the owner's recorded value for key, or ErrOwnerLimitsUnknown if none yet.
func OwnerLimit(sess data.Session, key string) (int, error) {
v, ok := sess.OwnerLimits[key]
if !ok {
return 0, ErrOwnerLimitsUnknown
}
return v, nil
}
// SessionView is a session with the caller's role in it.
type SessionView struct {
data.Session
Role string `json:"role"`
// AllowCoGMEncounters is the "allow a co-GM to create an encounter" setting. It is set only for
// the GM and co-GMs; players and observers never see it.
AllowCoGMEncounters *bool `json:"allow_co_gm_create_encounter,omitempty"`
}
// viewOf builds the view of sess for a member holding role.
func viewOf(sess data.Session, role string) SessionView {
v := SessionView{Session: sess, Role: role}
if role == data.RoleGM || role == data.RoleCoGM {
v.AllowCoGMEncounters = &sess.AllowCoGMCreateEncounter
}
return v
}
// Sessions implements session membership and its rules.
type Sessions struct {
repo *data.Sessions
enc *data.Encounters
changes *data.ChangeRequests
// OwnerRecordMaxAge is how old the GM's recorded entitlements may be when a co-GM acts on
// them (the configured OWNER_ENTITLEMENTS_MAX_AGE). Zero means seven days.
OwnerRecordMaxAge time.Duration
// MaxMembers is the configured maximum of the member limit (SESSION_MEMBERS_MAX): an entitled
// value above it has no effect. NewSessions sets the default; zero (a Sessions built by hand)
// fails every member addition closed.
MaxMembers int
evictor Evictor
now func() time.Time
}
// NewSessions builds the service on db.
func NewSessions(db store.Database) *Sessions {
return &Sessions{repo: data.NewSessions(db), enc: data.NewEncounters(db), changes: data.NewChangeRequests(db), MaxMembers: constants.DefaultSessionMembersMax, now: func() time.Time { return time.Now().UTC() }}
}
// Viewer returns how actor may see the session's encounters; see data.Sessions.AuthorizeView.
func (s *Sessions) Viewer(ctx context.Context, actor, sessionID string) (data.Viewer, error) {
return s.repo.AuthorizeView(ctx, actor, sessionID)
}
// Create makes actor the GM of a new session.
// Sessions beyond the GM's entitled count are refused with *EntitlementError; inactive sessions
// count, so a GM over a reduced limit cannot create.
func (s *Sessions) Create(ctx context.Context, actor, name string) (SessionView, error) {
return s.CreateWith(ctx, actor, name, false)
}
// CreateWith is Create with the co-GM encounter-creation setting chosen up front.
func (s *Sessions) CreateWith(ctx context.Context, actor, name string, allowCoGMCreate bool) (SessionView, error) {
name, err := cleanSessionName(name)
if err != nil {
return SessionView{}, err
}
chk, ok := ctx.Value(checkerKey{}).(Checker)
if !ok {
return SessionView{}, entitlements.ErrUnavailable
}
res, err := chk.Check(ctx, KeySessionsPerGM, entitlements.FailClosed)
if err != nil {
return SessionView{}, err
}
owned, err := s.repo.Count(ctx, actor)
if err != nil {
return SessionView{}, err
}
if owned >= int64(res.Limit) {
return SessionView{}, &EntitlementError{Key: KeySessionsPerGM, Limit: res.Limit}
}
auth, err := authorityOf(ctx)
if err != nil {
return SessionView{}, err
}
id, err := auth.svc.Mint(ctx, auth.token)
if err != nil {
return SessionView{}, err
}
sess := data.Session{Name: name, AllowCoGMCreateEncounter: allowCoGMCreate}
if err := s.repo.Open(ctx, actor, id, &sess); err != nil {
// Frees the mint slot; garbage collection covers a failure here.
if eerr := s.endSession(ctx, id); eerr != nil {
slog.WarnContext(ctx, "ending a session whose creation failed did not work; garbage collection will close it", "session", id, "error", eerr)
}
return SessionView{}, err
}
return viewOf(sess, data.RoleGM), nil
}
func cleanSessionName(name string) (string, error) {
name = strings.TrimSpace(name)
if name == "" || len([]rune(name)) > maxSessionName {
return "", invalid("session name is required and at most %d characters", maxSessionName)
}
return name, nil
}
// SessionChanges are the settings the GM may change on a session; nil leaves one as it is.
type SessionChanges struct {
Name *string
AllowCoGMEncounters *bool
}
// Update changes the session's settings at rev. Only the GM may: the relation asked of OpenFGA is
// gm and the write is scoped to the session's owner, so a co-GM cannot change the setting that
// grants co-GMs a power.
func (s *Sessions) Update(ctx context.Context, actor, id string, rev int64, ch SessionChanges) (SessionView, error) {
_, m, d, err := s.as(ctx, actor, id, ActUpdate)
if err != nil {
return SessionView{}, err
}
set := map[string]any{}
if ch.Name != nil {
name, err := cleanSessionName(*ch.Name)
if err != nil {
return SessionView{}, err
}
set["name"] = name
}
if ch.AllowCoGMEncounters != nil {
set["allow_co_gm_create_encounter"] = *ch.AllowCoGMEncounters
}
if len(set) == 0 {
return SessionView{}, invalid("nothing to update")
}
sess, err := s.repo.Update(ctx, d, rev, set)
if err != nil {
return SessionView{}, err
}
return viewOf(sess, m.Role), nil
}
// actionRelation is the OpenFGA relation on the session each action needs. The role rules in
// Allowed still apply on top: OpenFGA says whether the caller may touch the session at all.
var actionRelation = map[Action]string{
ActView: "can_view", ActLeave: "can_view",
ActInvite: "can_edit", ActBlock: "can_edit", ActManageMembers: "can_edit",
ActDecideRequest: "can_approve",
ActDelete: "gm",
ActUpdate: "gm",
ActCreateEncounter: "can_edit",
}
// as authorizes actor for action a on session id with auth-api (OpenFGA), then returns the
// session, actor's membership, and the decision the data layer needs. A denial is ErrForbidden and
// reads nothing; an unavailable decision is relations.ErrUnavailable (503), never an allow.
func (s *Sessions) as(ctx context.Context, actor, id string, a Action) (data.Session, data.Member, data.Decision, error) {
d, err := data.Authorize(ctx, actor, id, actionRelation[a])
if err != nil {
return data.Session{}, data.Member{}, d, err
}
sess, err := s.repo.Live(ctx, d)
if err != nil {
return sess, data.Member{}, d, err
}
m, err := s.repo.Member(ctx, d, actor)
if errors.Is(err, data.ErrNotFound) || (err == nil && !Allowed(m.Role, a)) {
return data.Session{}, data.Member{}, d, data.ErrForbidden
}
if err != nil {
return data.Session{}, data.Member{}, d, err
}
if m.Role == data.RoleGM {
sess = s.refreshOwnerLimits(ctx, d, sess)
}
if sess.InactiveAt != nil && a != ActView && a != ActDelete && a != ActLeave {
return sess, m, d, data.ErrInactive
}
return sess, m, d, nil
}
// refreshOwnerLimits re-reads the GM's entitlements with the GM's own token (the checker in ctx)
// and records them on the session. A failed, degraded, or stale (cached past its TTL) read keeps the old record, is logged, and
// never fails the request.
func (s *Sessions) refreshOwnerLimits(ctx context.Context, d data.Decision, sess data.Session) data.Session {
chk, ok := ctx.Value(checkerKey{}).(Checker)
if !ok {
return sess
}
limits, flags := make(map[string]int, len(sessionKeys)), make(map[string]bool, len(sessionFlags))
for _, key := range append(slices.Clone(sessionKeys), sessionFlags...) {
res, err := chk.Check(ctx, key, entitlements.FailOpen)
if err != nil || res.Degraded || res.Stale {
slog.WarnContext(ctx, "session owner entitlements not refreshed", "session", sess.ID, "key", key, "error", err)
return sess
}
if slices.Contains(sessionFlags, key) {
flags[key] = res.Flag
} else {
limits[key] = res.Limit
}
}
fresh := sess.OwnerLimitsAt != nil && s.now().Sub(*sess.OwnerLimitsAt) < ownerLimitsRefreshEvery
if fresh && maps.Equal(limits, sess.OwnerLimits) && maps.Equal(flags, sess.OwnerFlags) {
return sess
}
if err := s.repo.RecordOwnerLimits(ctx, d, limits, flags); err != nil {
slog.WarnContext(ctx, "session owner entitlements not recorded", "session", sess.ID, "error", err)
return sess
}
now := s.now()
sess.OwnerLimits, sess.OwnerFlags, sess.OwnerLimitsAt = limits, flags, &now
return sess
}
// Items exposes the sessions as limited items, so the limit reconciler can deactivate those beyond
// the owner's entitled count.
func (s *Sessions) Items() Limited { return s.repo.Limits() }
// Get returns the session with actor's role. Only members may read it.
func (s *Sessions) Get(ctx context.Context, actor, id string) (SessionView, error) {
sess, m, _, err := s.as(ctx, actor, id, ActView)
return viewOf(sess, m.Role), err
}
// List returns the sessions actor belongs to.
func (s *Sessions) List(ctx context.Context, actor string, q data.Query) (data.Page[SessionView], error) {
page, err := s.repo.SessionIDsOf(ctx, actor, q)
if err != nil {
return data.Page[SessionView]{}, err
}
out := data.Page[SessionView]{NextCursor: page.NextCursor, Items: []SessionView{}}
for _, m := range page.Items {
d, err := data.Authorize(ctx, actor, m.SessionID, actionRelation[ActView])
if errors.Is(err, data.ErrForbidden) || errors.Is(err, data.ErrNotFound) {
continue // membership record the tuples don't back (yet), or malformed
}
if err != nil {
return data.Page[SessionView]{}, err
}
sess, err := s.repo.Live(ctx, d)
if errors.Is(err, data.ErrNotFound) {
continue // deleted while we listed
}
if err != nil {
return data.Page[SessionView]{}, err
}
out.Items = append(out.Items, viewOf(sess, m.Role))
}
return out, nil
}
// Delete soft-deletes the session, ends it at auth-api (every tuple and the mint), ends every
// membership, and turns the session's encounters into private encounters of the GM
// (initiative-sessions, "Session deletion"): session_id and controllers are cleared and the GM
// becomes the owner, including of encounters a co-GM authored. Only the GM may; the owner-scoped
// delete enforces it a second time. The soft delete is the commit point. Every later step is
// idempotent and is attempted even if an earlier one fails, and the errors are returned together;
// calling Delete again (the GM, same id) then finishes what is left, without the revision, because
// a deleted session can no longer be authorized through OpenFGA. On such a retry auth-api may
// already have dropped the GM's own tuple, so a denial when ending the session counts as ended.
func (s *Sessions) Delete(ctx context.Context, actor, id string, rev int64) error {
_, _, d, err := s.as(ctx, actor, id, ActDelete)
resumed := false
switch {
case err == nil:
if err := s.repo.SoftDelete(ctx, d, rev); err != nil {
return err
}
case errors.Is(err, data.ErrForbidden) || errors.Is(err, data.ErrNotFound):
// Perhaps a deletion this GM started and did not finish. Anyone else, and a session that
// was never deleted, gets the original answer.
rd, rerr := s.repo.ResumeDeletion(ctx, actor, id)
if rerr != nil {
return err
}
d, resumed = rd, true
default:
return err
}
// End the session at auth-api before dropping the member records: once the session record is
// soft-deleted a retry cannot authorize the call through OpenFGA, so it runs first.
endErr := s.endSession(ctx, d.SessionID())
if resumed && errors.Is(endErr, relations.ErrDenied) {
endErr = nil
}
err = errors.Join(
endErr,
s.repo.DropSession(ctx, d),
s.changes.CancelSession(ctx, d),
s.enc.ReleaseSession(ctx, d),
)
// After the release, so the table hears each encounter leave the session before its streams end.
s.evict(d.SessionID(), "")
return err
}
func hashCode(code string) string {
sum := sha256.Sum256([]byte(strings.ToUpper(strings.TrimSpace(code))))
return hex.EncodeToString(sum[:])
}
func newCode() (string, error) {
b := make([]byte, 10) // 80 bits
if _, err := rand.Read(b); err != nil {
return "", err
}
return base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(b), nil
}
// CreateInvite makes a join code for the session. The code is returned once; only its hash is kept.
// ttl 0 means seven days.
func (s *Sessions) CreateInvite(ctx context.Context, actor, id string, ttl time.Duration) (data.Invite, string, error) {
_, _, d, err := s.as(ctx, actor, id, ActInvite)
if err != nil {
return data.Invite{}, "", err
}
if ttl == 0 {
ttl = defaultInviteTTL
}
if ttl < minInviteTTL || ttl > maxInviteTTL {
return data.Invite{}, "", invalid("invite lifetime must be between %s and %s", minInviteTTL, maxInviteTTL)
}
code, err := newCode()
if err != nil {
return data.Invite{}, "", err
}
in, err := s.repo.AddInvite(ctx, d, hashCode(code), s.now().Add(ttl))
return in, code, err
}
// Invites lists the session's invites.
func (s *Sessions) Invites(ctx context.Context, actor, id string, q data.Query) (data.Page[data.Invite], error) {
_, _, d, err := s.as(ctx, actor, id, ActInvite)
if err != nil {
return data.Page[data.Invite]{}, err
}
return s.repo.Invites(ctx, d, q)
}
// RevokeInvite ends an invite at once.
func (s *Sessions) RevokeInvite(ctx context.Context, actor, id, inviteID string) (data.Invite, error) {
_, _, d, err := s.as(ctx, actor, id, ActInvite)
if err != nil {
return data.Invite{}, err
}
return s.repo.RevokeInvite(ctx, d, inviteID)
}
// Join turns a presented code into a pending request. A pending request grants nothing. A code
// that is unknown, expired, revoked, or from a blocked user fails the same way and creates nothing.
func (s *Sessions) Join(ctx context.Context, actor, code string) (data.JoinRequest, error) {
t, err := s.repo.ResolveInvite(ctx, actor, hashCode(code), s.now())
if errors.Is(err, data.ErrNotFound) {
return data.JoinRequest{}, ErrInviteInvalid
}
if err != nil {
return data.JoinRequest{}, err
}
st, err := s.repo.ForJoin(ctx, t)
if err != nil {
return data.JoinRequest{}, err
}
if !st.Exists || !st.Active || st.Blocked {
return data.JoinRequest{}, ErrInviteInvalid
}
if st.Member {
return data.JoinRequest{}, data.ErrConflict
}
return s.repo.RequestJoin(ctx, t)
}
// Requests lists the session's join requests (pending ones when pendingOnly).
func (s *Sessions) Requests(ctx context.Context, actor, id string, pendingOnly bool, q data.Query) (data.Page[data.JoinRequest], error) {
_, _, d, err := s.as(ctx, actor, id, ActDecideRequest)
if err != nil {
return data.Page[data.JoinRequest]{}, err
}
status := ""
if pendingOnly {
status = data.RequestPending
}
return s.repo.Requests(ctx, d, status, q)
}
// Approve makes the requester a member with role. The request settles first, so two approvals
// cannot both succeed; a block placed after the request still stops it.
func (s *Sessions) Approve(ctx context.Context, actor, id, requestID, role string) (data.Member, error) {
if !slices.Contains(assignable, role) {
return data.Member{}, invalid("role must be one of %s", strings.Join(assignable, ", "))
}
sess, am, d, err := s.as(ctx, actor, id, ActDecideRequest)
if err != nil {
return data.Member{}, err
}
if !canManageRole(am.Role, role) {
return data.Member{}, data.ErrForbidden
}
// Before the request settles, and failing closed: a stale controller id must not revive on
// admission. The user is not a member yet, so this cannot race a legitimate assignment, and a
// failure leaves the request pending to retry rather than approved with no member.
// Only a request that is not pending (a retried approval, or no such request) skips the scrub;
// any other lookup error fails closed rather than admit with stale ids intact.
switch pending, perr := s.repo.PendingUser(ctx, d, requestID); {
case perr == nil:
// A request still pending would add a member: the roster must have room, so a full one
// leaves the request pending for later. A retried approval (not pending) is not an add.
if err := s.checkRoomForMember(ctx, d, sess, am.Role); err != nil {
return data.Member{}, err
}
if err := s.enc.ScrubController(ctx, d, pending); err != nil {
return data.Member{}, err
}
case !errors.Is(perr, data.ErrNotFound):
return data.Member{}, perr
}
jr, err := s.repo.Decide(ctx, d, requestID, data.RequestApproved, role, "")
if errors.Is(err, data.ErrConflict) && jr.Status == data.RequestApproved && jr.Role == role {
return s.finishApproval(ctx, d, am.Role, jr)
}
if err != nil {
return data.Member{}, err
}
if blocked, err := s.repo.Blocked(ctx, d, jr.UserID); err != nil || blocked {
if err == nil {
err = data.ErrForbidden
}
return data.Member{}, err
}
m, err := s.repo.AddMember(ctx, d, jr.UserID, role)
if err != nil {
return data.Member{}, err
}
return m, s.syncGrant(ctx, am.Role, d.SessionID(), m.UserID, role)
}
// errMaxMembersUnset means Sessions.MaxMembers was never configured; additions fail closed.
var errMaxMembersUnset = errors.New("domain: the session member maximum is not configured")
// memberLimit is the session's member limit: the owner's recorded members_per_session value,
// clamped to the configured maximum. It fails closed with ErrOwnerLimitsUnknown when nothing is
// recorded, or (for a co-GM, who cannot read the GM's entitlements) when the record is older than
// the configured maximum age. The GM's own request refreshed the record in as(), but a record the
// GM's own path reads may be arbitrarily old when the entitlements service is down.
func (s *Sessions) memberLimit(sess data.Session, actorRole string) (int, error) {
if actorRole != data.RoleGM && (sess.OwnerLimitsAt == nil || s.now().Sub(*sess.OwnerLimitsAt) > s.ownerRecordMaxAge()) {
return 0, ErrOwnerLimitsUnknown
}
limit, err := OwnerLimit(sess, KeyMembersPerSession)
if err != nil {
return 0, err
}
if s.MaxMembers < 1 {
return 0, errMaxMembersUnset
}
return max(0, min(limit, s.MaxMembers)), nil
}
// checkRoomForMember rejects adding a member to a roster that already holds the limit of non-GM
// members, with the typed entitlement error carrying the key and the (clamped) limit. Nothing is
// removed when the limit later falls; this only stops additions. The count and the add are two
// steps, so concurrent approvals can overrun a full roster. Co-GMs are uncapped and one actor can
// approve several pending requests in parallel, so the overrun is bounded by the number of
// requests pending at that moment.
// ponytail: no post-add recount; add one that soft-deletes the member and resets the request to
// pending if overruns matter.
func (s *Sessions) checkRoomForMember(ctx context.Context, d data.Decision, sess data.Session, actorRole string) error {
limit, err := s.memberLimit(sess, actorRole)
if err != nil {
return err
}
n, err := s.repo.CountMembers(ctx, d)
if err != nil {
return err
}
if n >= int64(limit) {
return &EntitlementError{Key: KeyMembersPerSession, Limit: limit}
}
return nil
}
// finishApproval is the retry of an approval that settled but whose tuple write failed: the member
// record exists, so only the tuple is written again. Any other state is the original conflict.
func (s *Sessions) finishApproval(ctx context.Context, d data.Decision, actorRole string, jr data.JoinRequest) (data.Member, error) {
m, err := s.repo.Member(ctx, d, jr.UserID)
if err != nil || m.Role != jr.Role {
return data.Member{}, data.ErrConflict
}
return m, s.syncGrant(ctx, actorRole, d.SessionID(), m.UserID, m.Role)
}
// Reject settles a pending request with a reason; the requester stays out.
func (s *Sessions) Reject(ctx context.Context, actor, id, requestID, reason string) (data.JoinRequest, error) {
reason = strings.TrimSpace(reason)
if reason == "" {
return data.JoinRequest{}, invalid("a reason is required to reject a request")
}
_, _, d, err := s.as(ctx, actor, id, ActDecideRequest)
if err != nil {
return data.JoinRequest{}, err
}
return s.repo.Decide(ctx, d, requestID, data.RequestRejected, "", reason)
}
// Members lists the session's members (user id, role). Any member may.
func (s *Sessions) Members(ctx context.Context, actor, id string, q data.Query) (data.Page[data.Member], error) {
_, _, d, err := s.as(ctx, actor, id, ActView)
if err != nil {
return data.Page[data.Member]{}, err
}
return s.repo.Members(ctx, d, q)
}
// target loads the member a manager acts on. Nobody can act on the GM.
func (s *Sessions) target(ctx context.Context, d data.Decision, user string) (data.Member, error) {
m, err := s.repo.Member(ctx, d, user)
if err != nil {
return m, err
}
if m.Role == data.RoleGM {
return m, data.ErrForbidden
}
return m, nil
}
// SetRole changes a member's role. The gm role cannot be given or taken.
func (s *Sessions) SetRole(ctx context.Context, actor, id, user, role string) (data.Member, error) {
if !slices.Contains(assignable, role) {
return data.Member{}, invalid("role must be one of %s", strings.Join(assignable, ", "))
}
_, am, d, err := s.as(ctx, actor, id, ActManageMembers)
if err != nil {
return data.Member{}, err
}
t, err := s.target(ctx, d, user)
if err != nil {
return data.Member{}, err
}
if !canManageRole(am.Role, role) || !canManageRole(am.Role, t.Role) {
return data.Member{}, data.ErrForbidden
}
if t.Role == data.RoleObserver {
// An observer being promoted starts with no control; failing closed, so a stale id cannot revive.
if err := s.enc.ScrubController(ctx, d, user); err != nil {
return data.Member{}, err
}
}
m, err := s.repo.SetRole(ctx, d, user, role)
if err != nil {
return data.Member{}, err
}
// Close the streams opened under the old role first: a demoted co-GM must not hear another event
// that carries a hidden combatant's id, including the scrub's own.
s.evict(d.SessionID(), user)
if role == data.RoleObserver {
s.scrubControllers(ctx, d, user)
}
return m, s.syncGrant(ctx, am.Role, d.SessionID(), user, role)
}
// Remove ends a member's access.
func (s *Sessions) Remove(ctx context.Context, actor, id, user string) error {
_, am, d, err := s.as(ctx, actor, id, ActManageMembers)
if err != nil {
return err
}
t, err := s.target(ctx, d, user)
if err != nil {
return err
}
if !canManageRole(am.Role, t.Role) {
return data.ErrForbidden
}
if err := s.repo.RemoveMember(ctx, d, user); err != nil {
return err
}
s.evict(d.SessionID(), user)
s.scrubControllers(ctx, d, user)
s.syncRevoke(ctx, am.Role, d.SessionID(), user, t.Role)
return nil
}
// Leave removes actor from the session. The GM cannot leave; they delete the session.
func (s *Sessions) Leave(ctx context.Context, actor, id string) error {
_, m, d, err := s.as(ctx, actor, id, ActView)
if err != nil {
return err
}
if !Allowed(m.Role, ActLeave) {
return invalid("the GM cannot leave; delete the session instead")
}
if err := s.repo.RemoveMember(ctx, d, actor); err != nil {
return err
}
s.evict(d.SessionID(), actor)
s.scrubControllers(ctx, d, actor)
s.syncRevoke(ctx, m.Role, d.SessionID(), actor, m.Role)
return nil
}
// Block keeps user out of the session, removing them and any pending request.
func (s *Sessions) Block(ctx context.Context, actor, id, user string) error {
_, am, d, err := s.as(ctx, actor, id, ActBlock)
if err != nil {
return err
}
if user == actor {
return invalid("you cannot block yourself")
}
t, err := s.target(ctx, d, user)
if err != nil && !errors.Is(err, data.ErrNotFound) {
return err
}
if err == nil && !canManageRole(am.Role, t.Role) {
return data.ErrForbidden
}
if err := s.repo.AddBlock(ctx, d, user); err != nil {
return err
}
// The block alone ends access, so streams close now, not only if the removal below succeeds.
s.evict(d.SessionID(), user)
if err := s.repo.DropRequest(ctx, d, user); err != nil {
return err
}
switch err := s.repo.RemoveMember(ctx, d, user); {
case err == nil:
s.scrubControllers(ctx, d, user)
s.syncRevoke(ctx, am.Role, d.SessionID(), user, t.Role)
case !errors.Is(err, data.ErrNotFound):
return err
}
return nil
}
// Unblock lets user join again.
func (s *Sessions) Unblock(ctx context.Context, actor, id, user string) error {
_, _, d, err := s.as(ctx, actor, id, ActBlock)
if err != nil {
return err
}
return s.repo.RemoveBlock(ctx, d, user)
}
// Blocks lists the blocked users.
func (s *Sessions) Blocks(ctx context.Context, actor, id string, q data.Query) (data.Page[data.Block], error) {
_, _, d, err := s.as(ctx, actor, id, ActBlock)
if err != nil {
return data.Page[data.Block]{}, err
}
return s.repo.Blocks(ctx, d, q)
}
// Evictor disconnects open streams. *stream.Hub implements it.
type Evictor interface {
// Evict closes userID's streams in the session, or everyone's when userID is empty.
Evict(sessionID, userID string)
}
// SetEvictor installs the evictor told when a member loses or changes access (removed, left,
// blocked, role changed) or the session is deleted, so their open streams end at once.
func (s *Sessions) SetEvictor(e Evictor) { s.evictor = e }
func (s *Sessions) evict(sessionID, userID string) {
if s.evictor != nil {
s.evictor.Evict(sessionID, userID)
}
}
// SetSink installs the sink told of the encounter changes sessions make: controller scrubs and the
// release of a deleted session's encounters.
func (s *Sessions) SetSink(k data.Sink) { s.enc.SetSink(k) }
// scrubControllers removes user from every combatant's controllers in the session's encounters,
// so a removed, blocked, or demoted member cannot regain control by rejoining or being promoted.
// It runs after the membership write and again before admission; it is idempotent and best
// effort, because the live Viewer already denies a non-player any control (domain.controls).
func (s *Sessions) scrubControllers(ctx context.Context, d data.Decision, user string) {
if err := s.enc.ScrubController(ctx, d, user); err != nil {
slog.WarnContext(ctx, "scrubbing a member's combatant controls failed; admission scrubs again", "session", d.SessionID(), "user", user, "error", err)
}
// Their pending change requests can no longer be approved (approval needs a current player
// controller), so close them instead of leaving them in the GM's queue.
if err := s.changes.CancelPending(ctx, d, user); err != nil {
slog.WarnContext(ctx, "cancelling a member's pending change requests failed", "session", d.SessionID(), "user", user, "error", err)
}
}
// IsMember reports whether userID currently belongs to the live session (stream.Members).
func (s *Sessions) IsMember(ctx context.Context, userID, sessionID string) (bool, error) {
return s.repo.IsMember(ctx, userID, sessionID)
}
// ManagerIDs lists the GM and co-GM user ids of a session, for addressing change-request notices
// (stream.Managers).
func (s *Sessions) ManagerIDs(ctx context.Context, sessionID string) ([]string, error) {
return s.repo.ManagerIDs(ctx, sessionID)
}
package domain
import (
"context"
cryptorand "crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"github.com/sweetrpg/initiative-api/constants"
"time"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/store"
)
// ErrTicketInvalid means a stream ticket is unknown, expired, or already spent. They are one
// answer, so a probe learns nothing about which.
var ErrTicketInvalid = errors.New("stream ticket is not valid")
// DefaultTicketTTL is how long a minted ticket may be redeemed.
const DefaultTicketTTL = constants.DefaultStreamTicketTTL
// Streams issues and redeems the one-time tickets that open an event stream for a browser.
type Streams struct {
tickets *data.StreamTickets
sessions *Sessions
enc *Encounters
// TTL is how long a ticket lives; DefaultTicketTTL when zero.
TTL time.Duration
}
// NewStreams builds the stream service on db.
func NewStreams(db store.Database, sessions *Sessions, enc *Encounters) *Streams {
return &Streams{tickets: data.NewStreamTickets(db), sessions: sessions, enc: enc}
}
// SetClock replaces the clock ticket ages are read from (tests).
func (s *Streams) SetClock(now func() time.Time) { s.tickets.SetClock(now) }
func (s *Streams) ttl() time.Duration {
if s.TTL > 0 {
return s.TTL
}
return DefaultTicketTTL
}
// TicketRequest names what a ticket is for: a session's encounters (SessionID, and optionally one
// of them), or the caller's own private encounters (no SessionID, optionally one of them).
type TicketRequest struct {
SessionID string
EncounterID string
ClientID string
// UserLevel asks for the user-level stream; it excludes SessionID and EncounterID.
UserLevel bool
}
// Claim is what a redeemed ticket asks for. It is a request, not proof: View decides.
type Claim struct {
UserID, SessionID, EncounterID, ClientID string
Level data.ViewLevel
UserLevel bool
}
// Mint authorizes actor for the scope the way the REST reads do (a non-member is data.ErrNotMember)
// and returns a ticket to open it with, valid for the service's TTL. The caller's own bearer is
// what authorizes (PADR-0037).
func (s *Streams) Mint(ctx context.Context, actor string, req TicketRequest) (string, time.Duration, error) {
t := data.StreamTicket{UserID: actor, SessionID: req.SessionID, EncounterID: req.EncounterID}
if data.ValidClientID(req.ClientID) {
t.ClientID = req.ClientID
}
if req.UserLevel {
if req.SessionID != "" || req.EncounterID != "" {
return "", 0, invalid("a user-level stream takes no session or encounter")
}
t.UserLevel = true
} else if req.SessionID != "" {
v, err := s.sessions.Viewer(ctx, actor, req.SessionID)
if err != nil {
return "", 0, err
}
if req.EncounterID != "" {
if _, err := s.enc.repo.LoadForViewer(ctx, v, req.EncounterID); err != nil {
return "", 0, err
}
}
t.Level = v.Level()
t.SessionID = v.SessionID()
} else {
v, err := s.ownerView(ctx, actor, req.EncounterID)
if err != nil {
return "", 0, err
}
t.Level = v.Level()
}
raw := make([]byte, 32)
if _, err := cryptorand.Read(raw); err != nil {
return "", 0, err
}
ticket := base64.RawURLEncoding.EncodeToString(raw)
t.ID = hashTicket(ticket)
if err := s.tickets.Mint(ctx, t); err != nil {
return "", 0, err
}
return ticket, s.ttl(), nil
}
func hashTicket(ticket string) string {
sum := sha256.Sum256([]byte(ticket))
return hex.EncodeToString(sum[:])
}
// ownerView is the viewer for the owner's private scope; a named encounter must be theirs and
// private (one in a session is data.ErrForbidden, as on the REST path).
func (s *Streams) ownerView(ctx context.Context, owner, encounterID string) (data.Viewer, error) {
if encounterID == "" {
return data.OwnerViewer(owner)
}
_, v, err := s.enc.repo.LoadOwnedView(ctx, owner, encounterID)
return v, err
}
// BearerView is the viewer for a caller authenticated by bearer: the REST authorization (OpenFGA
// through the caller's own token, fail closed) for a session scope, ownership for a private one.
func (s *Streams) BearerView(ctx context.Context, actor, sessionID, encounterID string) (data.Viewer, error) {
if sessionID == "" {
return s.ownerView(ctx, actor, encounterID)
}
v, err := s.sessions.Viewer(ctx, actor, sessionID)
if err == nil && encounterID != "" {
_, err = s.enc.repo.LoadForViewer(ctx, v, encounterID)
}
return v, err
}
// ErrRecheckFailed means a stream's membership could not be read; the stream's owner counts these
// and closes it after three in a row.
var ErrRecheckFailed = errors.New("stream membership re-check failed")
// ErrAccessChanged means a stream's viewer no longer matches the member's live record.
var ErrAccessChanged = errors.New("stream access changed")
// Recheck re-reads the live member record behind an open stream. It returns ErrAccessChanged when
// the member is gone, the session is deleted, or their level is no longer the one the stream was
// granted at (it must reconnect to be authorized again). A failed read returns ErrRecheckFailed; the
// stream's owner closes it after three in a row.
func (s *Streams) Recheck(ctx context.Context, v data.Viewer) error {
if v.SessionID() == "" {
return nil
}
now, err := s.sessions.repo.TicketView(ctx, v.Actor(), v.SessionID(), v.Level())
switch {
case errors.Is(err, data.ErrNotMember):
return ErrAccessChanged
case err != nil:
return fmt.Errorf("%w: %v", ErrRecheckFailed, err)
case now.Level() != v.Level():
return ErrAccessChanged
}
return nil
}
// ConnectLimit is the cap on live non-GM connections in the session that userID's connection
// counts against: the owner's recorded members_per_session value clamped to the configured maximum
// (the same number the roster is held to). The GM is exempt (counted false). It fails closed on a
// missing or stale recorded value, like every check made for a member rather than the GM.
func (s *Streams) ConnectLimit(ctx context.Context, userID, sessionID string) (limit int, counted bool, err error) {
sess, m, err := s.sessions.repo.SeatInfo(ctx, userID, sessionID)
if err != nil {
return 0, false, err
}
if m.Role == data.RoleGM {
return 0, false, nil
}
limit, err = s.sessions.memberLimit(sess, m.Role)
return limit, err == nil, err
}
// Peek reads what a ticket stands for without spending it; the caller checks its limits and then
// calls Redeem, so a refused connect does not cost the client its ticket.
func (s *Streams) Peek(ctx context.Context, ticket string) (Claim, error) {
return s.claim(ctx, ticket, s.tickets.Peek)
}
// Redeem spends a ticket. It is the only thing that can be done with it: a second redeem, an
// expired ticket and an unknown one are all ErrTicketInvalid.
func (s *Streams) Redeem(ctx context.Context, ticket string) (Claim, error) {
return s.claim(ctx, ticket, s.tickets.Redeem)
}
func (s *Streams) claim(ctx context.Context, ticket string, take func(context.Context, string, time.Duration) (data.StreamTicket, error)) (Claim, error) {
if len(ticket) == 0 || len(ticket) > 128 {
return Claim{}, ErrTicketInvalid
}
t, err := take(ctx, hashTicket(ticket), s.ttl())
if errors.Is(err, data.ErrNotFound) {
return Claim{}, ErrTicketInvalid
}
if err != nil {
return Claim{}, err
}
return Claim{UserID: t.UserID, SessionID: t.SessionID, EncounterID: t.EncounterID, ClientID: t.ClientID, Level: t.Level, UserLevel: t.UserLevel}, nil
}
// View is the viewer a redeemed claim opens. Only the user, the scope and the minted level come
// from the ticket; access is read live (data.Sessions.TicketView), so a member removed since the
// mint, a session deleted since, or a role raised since gets nothing.
func (s *Streams) View(ctx context.Context, c Claim) (data.Viewer, error) {
if c.UserLevel {
return data.Viewer{}, nil // identity only: the stream's deliveries check membership themselves
}
if c.SessionID == "" {
return s.ownerView(ctx, c.UserID, c.EncounterID)
}
v, err := s.sessions.repo.TicketView(ctx, c.UserID, c.SessionID, c.Level)
if err != nil {
return data.Viewer{}, err
}
if c.EncounterID != "" {
if _, err := s.enc.repo.LoadForViewer(ctx, v, c.EncounterID); err != nil {
return data.Viewer{}, err
}
}
return v, nil
}
// Head is the cheapest thing a client can compare with its cache to learn whether it is current:
// the revision for a GM or co-GM, the view tag for everyone else. Nothing else about the encounter.
type Head struct {
EncounterID string `json:"encounter_id"`
Revision int64 `json:"revision,omitempty"`
ViewTag string `json:"view_tag,omitempty"`
}
// MaxHeads is the most heads a stream opens with; more is reported as truncated in hello, and the
// client lists the rest over REST.
const MaxHeads = 100
// Heads returns the head of each encounter in v's scope (or of encounterID only), built from the
// same views the REST reads return.
func (s *Streams) Heads(ctx context.Context, v data.Viewer, encounterID string) ([]Head, bool, error) {
var views []EncounterView
var err error
switch {
case v.SessionID() != "" && encounterID != "":
var one EncounterView
if one, err = s.enc.ViewForSession(ctx, v, encounterID); err == nil {
views = []EncounterView{one}
}
case v.SessionID() != "":
views, err = s.enc.ViewsForSession(ctx, v, MaxHeads+1)
case encounterID != "":
var one EncounterView
if one, err = s.enc.ViewOwned(ctx, v.Actor(), encounterID); err == nil {
views = []EncounterView{one}
}
default:
var page data.Page[EncounterView]
if page, err = s.enc.ViewsOwned(ctx, v.Actor(), data.Query{Limit: MaxHeads + 1}); err == nil {
views = page.Items
}
}
if err != nil {
return nil, false, err
}
truncated := len(views) > MaxHeads
if truncated {
views = views[:MaxHeads]
}
out := make([]Head, 0, len(views))
for _, view := range views {
h := Head{}
h.EncounterID, _ = view["id"].(string)
h.Revision, _ = view["revision"].(int64)
h.ViewTag, _ = view[FieldViewTag].(string)
out = append(out, h)
}
return out, truncated, nil
}
package domain
import (
"context"
_ "embed"
"encoding/json"
"errors"
"fmt"
"net/url"
"regexp"
"strings"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/entitlements"
"github.com/sweetrpg/initiative-api/store"
)
// KeyThemeSlots is the entitlement limit on custom theme slots (docs/entitlements-check-contract.md).
const KeyThemeSlots = "initiative.theme_slots"
// PackagedPrefix starts the ID of every packaged theme. Custom theme IDs never carry it.
const PackagedPrefix = "pkg-"
const slotRetries = 3
var (
// ErrReadOnly means the caller tried to change or delete a packaged theme.
ErrReadOnly = errors.New("domain: packaged theme is read-only")
hexColor = regexp.MustCompile(`^#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$`)
)
//go:embed packaged_themes.json
var packagedJSON []byte
// EntitlementError is the typed denial for a stored-item limit the caller has reached.
type EntitlementError struct {
Key string
Limit int
}
func (e *EntitlementError) Error() string {
return fmt.Sprintf("domain: entitlement limit reached for %s (%d)", e.Key, e.Limit)
}
// Checker answers entitlement checks for the calling user; the server binds the user and token.
type Checker interface {
Check(ctx context.Context, key string, policy entitlements.Policy) (entitlements.Result, error)
}
// ThemeInput is the full field set of a custom theme.
type ThemeInput struct {
Name, Style, MainColor, Accent1Color, Accent2Color, Background1Color, Background2Color string
PrimaryFontName, SecondaryFontName, BackgroundImage string
}
// ThemePatch changes the fields that are non-nil.
type ThemePatch struct {
Name, Style, MainColor, Accent1Color, Accent2Color, Background1Color, Background2Color *string
PrimaryFontName, SecondaryFontName, BackgroundImage *string
}
// Themes implements custom theme rules: slot enforcement and read-only packaged themes.
type Themes struct {
themes *data.Owned[data.Theme, *data.Theme]
packaged []data.Theme
}
// NewThemes builds the theme service on db.
func NewThemes(db store.Database) (*Themes, error) {
var pk []data.Theme
if err := json.Unmarshal(packagedJSON, &pk); err != nil {
return nil, fmt.Errorf("packaged themes: %w", err)
}
return &Themes{themes: data.NewOwned[data.Theme](db, data.ThemeSpec), packaged: pk}, nil
}
// Packaged returns the read-only packaged themes.
func (s *Themes) Packaged() []data.Theme { return append([]data.Theme(nil), s.packaged...) }
func isPackaged(id string) bool { return strings.HasPrefix(id, PackagedPrefix) }
// Get returns a packaged theme by ID or owner's custom theme.
func (s *Themes) Get(ctx context.Context, owner, id string) (data.Theme, error) {
if isPackaged(id) {
for _, t := range s.packaged {
if t.ID == id {
return t, nil
}
}
return data.Theme{}, data.ErrNotFound
}
return s.themes.Get(ctx, owner, id)
}
// List returns a page of owner's custom themes in slot order.
func (s *Themes) List(ctx context.Context, owner string, q data.Query) (data.Page[data.Theme], error) {
if len(q.Sort) == 0 {
q.Sort = []data.SortKey{{Field: "slot"}}
}
return s.themes.List(ctx, owner, q)
}
// Create stores a custom theme in the lowest free slot below the entitled limit. At or over the
// limit it returns *EntitlementError; if entitlements-api is unreachable, entitlements.ErrUnavailable.
func (s *Themes) Create(ctx context.Context, owner, actor string, in ThemeInput, chk Checker) (data.Theme, error) {
t, err := buildTheme(in)
if err != nil {
return data.Theme{}, err
}
res, err := chk.Check(ctx, KeyThemeSlots, entitlements.FailClosed)
if err != nil {
return data.Theme{}, err
}
// Inactive themes count toward the total owned, so a user over a reduced limit cannot create.
owned, err := s.themes.Count(ctx, owner, nil)
if err != nil {
return data.Theme{}, err
}
if owned >= int64(res.Limit) {
return data.Theme{}, &EntitlementError{Key: KeyThemeSlots, Limit: res.Limit}
}
for range slotRetries {
slot, err := s.freeSlot(ctx, owner, res.Limit)
if err != nil {
return data.Theme{}, err
}
t.Slot = &slot
err = s.themes.Create(ctx, owner, actor, &t)
if !errors.Is(err, data.ErrConflict) {
return t, err
}
}
return data.Theme{}, data.ErrConflict
}
// freeSlot returns the lowest unused slot in [0, limit), or *EntitlementError when all are used.
func (s *Themes) freeSlot(ctx context.Context, owner string, limit int) (int, error) {
page, err := s.themes.List(ctx, owner, data.Query{
Sort: []data.SortKey{{Field: "slot"}}, Fields: []string{"slot"}, Limit: limit,
})
if err != nil {
return 0, err
}
used := map[int]bool{}
for _, t := range page.Items {
if t.Slot != nil {
used[*t.Slot] = true
}
}
for i := range limit {
if !used[i] {
return i, nil
}
}
return 0, &EntitlementError{Key: KeyThemeSlots, Limit: limit}
}
// Update changes owner's custom theme, compare-and-set on rev. Packaged themes return ErrReadOnly.
func (s *Themes) Update(ctx context.Context, owner, actor, id string, rev int64, p ThemePatch) (data.Theme, error) {
if isPackaged(id) {
return data.Theme{}, ErrReadOnly
}
set, err := patchSet(p)
if err != nil {
return data.Theme{}, err
}
return s.themes.Update(ctx, owner, actor, id, rev, set)
}
// Delete soft-deletes owner's custom theme, freeing its slot. Packaged themes return ErrReadOnly.
func (s *Themes) Delete(ctx context.Context, owner, actor, id string, rev int64) error {
if isPackaged(id) {
return ErrReadOnly
}
return s.themes.SoftDelete(ctx, owner, actor, id, rev)
}
// Items is the theme repository as limit enforcement sees it.
func (s *Themes) Items() Limited { return s.themes }
// Count returns how many custom themes owner holds.
func (s *Themes) Count(ctx context.Context, owner string) (int64, error) {
return s.themes.Count(ctx, owner, nil)
}
func buildTheme(in ThemeInput) (data.Theme, error) {
set, err := patchSet(ThemePatch{
Name: &in.Name, Style: &in.Style, MainColor: &in.MainColor, Accent1Color: &in.Accent1Color,
Accent2Color: &in.Accent2Color, Background1Color: &in.Background1Color,
Background2Color: &in.Background2Color, PrimaryFontName: &in.PrimaryFontName,
SecondaryFontName: &in.SecondaryFontName, BackgroundImage: &in.BackgroundImage,
})
if err != nil {
return data.Theme{}, err
}
str := func(k string) string { v, _ := set[k].(string); return v }
return data.Theme{
Name: str("name"), Style: str("style"), MainColor: str("main_color"),
Accent1Color: str("accent1_color"), Accent2Color: str("accent2_color"),
Background1Color: str("background1_color"), Background2Color: str("background2_color"),
PrimaryFontName: str("primary_font_name"), SecondaryFontName: str("secondary_font_name"),
BackgroundImage: str("background_image"),
}, nil
}
type themeField struct {
key string
val *string
kind int // 0 required text, 1 color, 2 optional https URL
}
const (
fText = iota
fColor
fImage
)
// patchSet validates the non-nil fields of p and returns them keyed by stored field name.
func patchSet(p ThemePatch) (map[string]any, error) {
fields := []themeField{
{"name", p.Name, fText}, {"style", p.Style, fText},
{"main_color", p.MainColor, fColor}, {"accent1_color", p.Accent1Color, fColor},
{"accent2_color", p.Accent2Color, fColor}, {"background1_color", p.Background1Color, fColor},
{"background2_color", p.Background2Color, fColor},
{"primary_font_name", p.PrimaryFontName, fText}, {"secondary_font_name", p.SecondaryFontName, fText},
{"background_image", p.BackgroundImage, fImage},
}
set := map[string]any{}
for _, f := range fields {
if f.val == nil {
continue
}
v := strings.TrimSpace(*f.val)
if err := checkThemeField(f, v); err != nil {
return nil, err
}
set[f.key] = v
}
return set, nil
}
func checkThemeField(f themeField, v string) error {
switch f.kind {
case fText:
if v == "" || len(v) > 100 {
return invalid("theme %s is required and at most 100 characters", f.key)
}
case fColor:
if !hexColor.MatchString(v) {
return invalid("theme %s must be #RRGGBB or #RRGGBBAA", f.key)
}
case fImage:
if v == "" {
return nil
}
if u, err := url.Parse(v); err != nil || u.Scheme != "https" || u.Host == "" || len(v) > 2048 {
return invalid("theme %s must be an https URL", f.key)
}
}
return nil
}
package domain
import (
"context"
"maps"
"strings"
"github.com/sweetrpg/initiative-api/data"
)
// CreateEncounterFromRoster stores enc as owner's new encounter with one combatant per roster
// character, copying name, kind, notes, default health, and external refs. The source roster is
// not modified, and enc's own combatants are replaced.
func (s *Rosters) CreateEncounterFromRoster(ctx context.Context, owner, actor, rosterID string, enc data.Encounter) (data.Encounter, error) {
enc.Name = strings.TrimSpace(enc.Name)
if enc.Name == "" {
return data.Encounter{}, invalid("encounter name is required")
}
if err := checkTheme(ctx, s.themes, owner, enc.ThemeID); err != nil {
return data.Encounter{}, err
}
if err := data.CheckName("encounter name", enc.Name); err != nil {
return data.Encounter{}, err
}
// An encounter joins a session only through a path that authorizes the caller as that session's GM.
if enc.SessionID != "" {
return data.Encounter{}, invalid("an encounter cannot be created inside a session here")
}
if err := s.encounters.RequireSystem(ctx, enc.GameSystemID); err != nil {
return data.Encounter{}, err
}
if err := requireSystem(ctx, enc.GameSystemID); err != nil {
return data.Encounter{}, err
}
roster, err := s.Load(ctx, owner, rosterID)
if err != nil {
return data.Encounter{}, err
}
enc.Combatants = make([]data.Combatant, 0, len(roster.Characters))
for _, c := range roster.Characters {
enc.Combatants = append(enc.Combatants, data.Combatant{
ID: randomID(), Name: c.Name, Kind: c.Kind, Notes: c.Notes,
Health: maps.Clone(c.Health), ExternalRefs: maps.Clone(c.ExternalRefs),
Conditions: []data.Condition{}, SourceCharacterID: c.ID,
})
}
if err := s.encounters.Create(ctx, owner, actor, &enc); err != nil {
return data.Encounter{}, err
}
return enc, nil
}
// SaveAsRoster stores a new roster holding one character per combatant of owner's encounter that
// is not removed. Current health becomes the character's defaults. The encounter is not modified.
// An empty name falls back to the encounter's name.
func (s *Rosters) SaveAsRoster(ctx context.Context, owner, actor, encounterID, name string) (data.Roster, error) {
enc, err := s.encounters.Load(ctx, owner, encounterID)
if err != nil {
return data.Roster{}, err
}
if strings.TrimSpace(name) == "" {
name = enc.Name
}
chars := make([]data.Character, 0, len(enc.Combatants))
for _, c := range enc.Combatants {
if c.Removed {
continue
}
chars = append(chars, data.Character{
Name: c.Name, Kind: c.Kind, Notes: c.Notes, Health: c.Health, ExternalRefs: c.ExternalRefs,
})
}
return s.Create(ctx, owner, actor, name, false, chars)
}
package domain
import (
"context"
"errors"
"fmt"
"maps"
"github.com/sweetrpg/initiative-api/data"
)
// Start moves a draft encounter to active at round 1, builds the turn queue, and makes the first
// combatant current (its conditions tick as its turn begins).
func (s *Encounters) Start(ctx context.Context, owner, actor, id string, rev int64) (data.Encounter, error) {
ctx = data.WithOp(ctx, data.EventStarted)
return s.editQueue(ctx, owner, actor, id, rev, func(st *data.EncounterState, _ data.Encounter) error {
if st.Status != data.StatusDraft {
return fmt.Errorf("%w: cannot start from %s", ErrTransition, st.Status)
}
st.Status, st.Round = data.StatusActive, 1
return nil
})
}
// End moves an active encounter to ended.
func (s *Encounters) End(ctx context.Context, owner, actor, id string, rev int64) (data.Encounter, error) {
ctx = data.WithOp(ctx, data.EventEnded)
return s.edit(ctx, owner, actor, id, rev, func(st *data.EncounterState, _ data.Encounter) error {
if st.Status != data.StatusActive {
return fmt.Errorf("%w: cannot end from %s", ErrTransition, st.Status)
}
st.Status = data.StatusEnded
return nil
})
}
// Reset returns the encounter to draft at round 0 with no current combatant and an empty turn queue, clears every
// combatant's conditions, and sets health values back to the game system's defaults. Combatants,
// their initiative, and removed marks are kept.
func (s *Encounters) Reset(ctx context.Context, owner, actor, id string, rev int64) (data.Encounter, error) {
ctx = data.WithOp(ctx, data.EventReset)
cur, err := s.repo.Load(ctx, owner, id)
if err != nil {
return data.Encounter{}, err
}
sys, err := s.systems.GetOrDefault(ctx, cur.GameSystemID)
if errors.Is(err, data.ErrNotFound) {
return data.Encounter{}, invalid("the encounter's game system has no definition")
}
if err != nil {
return data.Encounter{}, err
}
defaults := make(map[string]int, len(sys.Fields))
for _, f := range sys.Fields {
defaults[f.Key] = f.Def
}
return s.edit(ctx, owner, actor, id, rev, func(st *data.EncounterState, _ data.Encounter) error {
st.Status, st.Round, st.CurrentCombatantID, st.TurnQueue = data.StatusDraft, 0, "", nil
for i := range st.Combatants {
c := &st.Combatants[i]
c.Conditions = []data.Condition{}
c.Health = maps.Clone(c.Health)
for k := range c.Health {
if d, ok := defaults[k]; ok {
c.Health[k] = d
}
}
}
return nil
})
}
package domain
import (
"context"
"fmt"
"slices"
"github.com/sweetrpg/initiative-api/data"
)
// effectiveOrdering is the ordering the engine applies. No System orders by initiative value only,
// whatever the stored ordering says: pcVsAdversary grouping needs a system that defines it, and
// none of the current definitions do.
func effectiveOrdering(ordering, gameSystemID string) string {
if ordering == data.OrderPCVsAdversary && gameSystemID == data.DefaultSystemID {
return data.OrderHighToLow
}
return ordering
}
// recompute rebuilds the turn queue under ordering and tie. In an active encounter it also keeps
// a current combatant: if the current one left the queue, the combatant now at its old position
// takes the turn (wrapping to the front and starting the next round if it was last), and an empty
// current picks the first.
func (s *Encounters) recompute(st *data.EncounterState, ordering, tie string) {
prev := st.TurnQueue
st.TurnQueue = buildQueue(ordering, tie, st.Combatants, prev, s.perm)
if st.Status != data.StatusActive || slices.Contains(st.TurnQueue, st.CurrentCombatantID) {
return
}
if len(st.TurnQueue) == 0 {
st.CurrentCombatantID = ""
return
}
old := slices.Index(prev, st.CurrentCombatantID)
pos := max(old, 0)
if old >= len(st.TurnQueue) {
st.Round++ // the removed combatant was last: the turn wraps to the front, a new round
}
st.CurrentCombatantID = st.TurnQueue[pos%len(st.TurnQueue)]
beginTurn(st)
}
// beginTurn ticks the conditions of the current combatant.
func beginTurn(st *data.EncounterState) {
i := slices.IndexFunc(st.Combatants, func(c data.Combatant) bool { return c.ID == st.CurrentCombatantID })
if i >= 0 {
expireConditions(&st.Combatants[i])
}
}
func queuedTurn(st *data.EncounterState) (pos int, err error) {
if st.Status != data.StatusActive {
return 0, fmt.Errorf("%w: encounter is %s", ErrTransition, st.Status)
}
if len(st.TurnQueue) == 0 {
return 0, invalid("the turn queue is empty")
}
return slices.Index(st.TurnQueue, st.CurrentCombatantID), nil
}
// Advance passes the turn to the next combatant in the queue. Past the last entry it wraps to the
// first and starts the next round. The new current combatant's timed conditions lose one round,
// and expire at zero.
func (s *Encounters) Advance(ctx context.Context, owner, actor, id string, rev int64) (data.Encounter, error) {
ctx = data.WithOp(ctx, data.EventTurn)
return s.edit(ctx, owner, actor, id, rev, func(st *data.EncounterState, _ data.Encounter) error {
pos, err := queuedTurn(st)
if err != nil {
return err
}
idx, wrapped := nextTurn(pos, len(st.TurnQueue))
if wrapped {
st.Round++
}
st.CurrentCombatantID = st.TurnQueue[idx]
beginTurn(st)
return nil
})
}
// StepBack returns the turn to the previous combatant. Stepping back past the first entry goes to
// the last and the previous round; it is rejected on the first turn of round 1. Conditions that
// already ticked are not restored.
func (s *Encounters) StepBack(ctx context.Context, owner, actor, id string, rev int64) (data.Encounter, error) {
ctx = data.WithOp(ctx, data.EventTurn)
return s.edit(ctx, owner, actor, id, rev, func(st *data.EncounterState, _ data.Encounter) error {
pos, err := queuedTurn(st)
if err != nil {
return err
}
idx, wrapped := prevTurn(pos, len(st.TurnQueue))
if wrapped {
if st.Round <= 1 {
return fmt.Errorf("%w: already at the first turn", ErrTransition)
}
st.Round--
}
st.CurrentCombatantID = st.TurnQueue[idx]
return nil
})
}
package domain
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"log/slog"
"maps"
"reflect"
"slices"
"strings"
"github.com/sweetrpg/initiative-api/data"
)
// EncounterView is an encounter as one caller may see it. It is produced only by BuildView, the
// single place that decides visibility (initiative-api-resources, "Role-aware responses"); REST
// handlers and, later, event payloads serialize nothing else. A field reaches a view only when
// the rule tables below name it and the viewer's level allows it, so a field added to a data type
// is invisible to everyone but the GM-level views until someone decides otherwise (and the test
// in view_test.go fails until they do).
type EncounterView map[string]any
// encounterRules maps each data.Encounter JSON field to the least level that sees it. Fields
// computed per viewer (see computedEncounter) are listed here too, but their raw value is never used.
var encounterRules = map[string]data.ViewLevel{
"id": data.ViewObserver, "name": data.ViewObserver, "game_system_id": data.ViewObserver,
"status": data.ViewObserver, "round": data.ViewObserver, "session_id": data.ViewObserver,
"current_combatant_id": data.ViewObserver, "turn_queue": data.ViewObserver, "combatants": data.ViewObserver,
"owner_user_id": data.ViewGM, "revision": data.ViewGM, "ordering": data.ViewGM, "tie_breaker": data.ViewGM,
"labels": data.ViewGM, "colorblind": data.ViewGM, "theme_id": data.ViewGM, "position": data.ViewGM,
"inactive_at": data.ViewGM, "locked_at": data.ViewGM,
"created_at": data.ViewGM, "created_by": data.ViewGM, "updated_at": data.ViewGM, "updated_by": data.ViewGM,
"deleted_at": data.ViewGM, "deleted_by": data.ViewGM,
}
// An encounter-level notes field, when one is added, needs a GM-only rule here; the field test in
// view_test.go fails until it has one.
// computedEncounter fields are filled from the viewer's visible combatants, never copied.
var computedEncounter = map[string]bool{"current_combatant_id": true, "turn_queue": true, "combatants": true}
// combatantRules is the same table for data.Combatant.
var combatantRules = map[string]data.ViewLevel{
"id": data.ViewObserver, "name": data.ViewObserver, "kind": data.ViewObserver, "conditions": data.ViewObserver,
"health": data.ViewObserver, "notes": data.ViewObserver,
"initiative": data.ViewGM, "removed": data.ViewGM, "source_character_id": data.ViewGM, "external_refs": data.ViewGM,
"controller_user_ids": data.ViewGM, "hidden": data.ViewGM, "health_visibility": data.ViewGM, "notes_shared": data.ViewGM,
}
// computedCombatant fields depend on the viewer and the combatant's visibility settings.
var computedCombatant = map[string]bool{"health": true, "notes": true, "conditions": true}
// conditionRules is the same table for data.Condition.
var conditionRules = map[string]data.ViewLevel{"name": data.ViewObserver, "rounds_remaining": data.ViewObserver}
// Derived view fields that no data type carries.
const (
fieldHealthStatus = "health_status"
fieldMine = "mine"
fieldCombatantCount = "combatant_count"
fieldViewTag = "view_tag"
)
// FieldViewTag is the key of a non-GM view's digest.
const FieldViewTag = fieldViewTag
// Health statuses a non-GM sees when a combatant's health is shown as status.
const (
StatusHealthy = "healthy"
StatusHurt = "hurt"
StatusNearDeath = "near_death"
StatusDown = "down"
)
// ErrNoView is returned when a view is asked of a viewer that grants nothing, or for an
// encounter outside the viewer's scope.
var ErrNoView = data.ErrForbidden
// BuildView renders enc for v. def is the encounter's game system tracker definition, used for
// the coarse health status. The viewer must come from the data layer (data.AuthorizeView or an
// owner-scoped load); BuildView does not look at membership.
func BuildView(enc data.Encounter, def []data.TrackerField, v data.Viewer) (EncounterView, error) {
if v.Level() == data.ViewNone || enc.SessionID != v.SessionID() {
return nil, ErrNoView
}
gm := v.Level() == data.ViewGM
combatants, queue, current, count := visibleCombatants(enc, def, v)
out := projectStruct(reflect.ValueOf(enc), encounterRules, v.Level(), func(name string) (any, bool) {
switch name {
case "combatants":
return combatants, true
case "turn_queue":
return queue, true
case "current_combatant_id":
return current, current != ""
}
return nil, false
}, computedEncounter)
out[fieldCombatantCount] = count
if !gm {
// The stored revision moves on every edit, hidden ones included, so a non-GM gets a tag of
// what it can see instead: it changes only when its own view does.
out[fieldViewTag] = viewTag(out)
}
return out, nil
}
// Combatant returns the combatant with id from the view, if the view has it. A combatant the
// viewer may not see is not in the view, so it is simply not found.
func (v EncounterView) Combatant(id string) (map[string]any, bool) {
list, _ := v["combatants"].([]map[string]any)
for _, c := range list {
if c["id"] == id {
return c, true
}
}
return nil, false
}
// visibleCombatants returns the combatant views, turn queue, current combatant ID and count the
// viewer may see. For a non-GM, hidden and removed combatants are absent, not redacted, and the
// queue and current turn are derived from what remains.
func visibleCombatants(enc data.Encounter, def []data.TrackerField, v data.Viewer) (list []map[string]any, queue []string, current string, count int) {
gm := v.Level() == data.ViewGM
shown := map[string]bool{}
list = []map[string]any{}
for _, c := range enc.Combatants {
if !c.Removed {
count++
}
// A hidden combatant stays visible to the player who controls it; nobody else sees it.
if !gm && (c.Removed || (c.Hidden && !controls(c, v))) {
continue
}
shown[c.ID] = true
list = append(list, combatantView(c, def, v))
}
queue = []string{}
for _, id := range enc.TurnQueue {
if shown[id] {
queue = append(queue, id)
}
}
if shown[enc.CurrentCombatantID] {
current = enc.CurrentCombatantID
}
if !gm {
// The count a non-GM sees is the count it can see.
count = len(list)
}
return list, queue, current, count
}
// controls reports whether the viewer is a player who controls c. An observer controls nothing,
// even if listed.
func controls(c data.Combatant, v data.Viewer) bool {
return v.Level() == data.ViewPlayer && slices.Contains(c.ControllerUserIDs, v.Actor())
}
func combatantView(c data.Combatant, def []data.TrackerField, v data.Viewer) map[string]any {
gm := v.Level() == data.ViewGM
own := controls(c, v)
out := projectStruct(reflect.ValueOf(c), combatantRules, v.Level(), func(name string) (any, bool) {
switch name {
case "health":
if (gm || own || c.HealthVisibility == data.HealthFull) && len(c.Health) > 0 {
return maps.Clone(c.Health), true
}
case "notes":
if gm || c.NotesShared {
return c.Notes, true
}
case "conditions":
conds := make([]map[string]any, 0, len(c.Conditions))
for _, cond := range c.Conditions {
conds = append(conds, projectStruct(reflect.ValueOf(cond), conditionRules, v.Level(), nil, nil))
}
return conds, true
}
return nil, false
}, computedCombatant)
if !gm && !own && c.HealthVisibility == data.HealthStatus {
if s, ok := healthStatus(def, c.Health); ok {
out[fieldHealthStatus] = s
}
}
if v.Level() == data.ViewPlayer {
out[fieldMine] = own
}
return out
}
// healthStatus is the coarse state of a combatant: from the first bounded counter in the
// definition (current over its maximum), else the first counter (down at its minimum, otherwise
// healthy). It reports false when the definition has no counter, so nothing is shown.
func healthStatus(def []data.TrackerField, health map[string]int) (string, bool) {
var first *data.TrackerField
for i, f := range def {
if f.Kind != data.FieldCounter {
continue
}
if first == nil {
first = &def[i]
}
if f.Max == nil && f.MaxRef == "" {
continue
}
bound, ok := boundOf(def, f, health)
if !ok {
return "", false // a bound that cannot be resolved shows no status rather than a guessed one
}
cur, ok := valueOf(def, health, f.Key)
if !ok {
return "", false
}
return statusOf(cur, minOf(f), bound), true
}
if first == nil {
return "", false
}
cur, ok := valueOf(def, health, first.Key)
if !ok {
return "", false
}
if cur <= minOf(*first) {
return StatusDown, true
}
return StatusHealthy, true
}
// valueOf is the stored value of a health key, or the definition's default when none is stored. A
// key the definition does not know and the combatant does not hold has no value, so no status is
// shown rather than a guessed one.
func valueOf(def []data.TrackerField, health map[string]int, key string) (int, bool) {
if v, ok := health[key]; ok {
return v, true
}
for _, f := range def {
if f.Key == key {
return f.Def, true
}
}
return 0, false
}
func boundOf(def []data.TrackerField, f data.TrackerField, health map[string]int) (int, bool) {
switch {
case f.Max != nil:
return *f.Max, true
case f.MaxRef != "":
return valueOf(def, health, f.MaxRef)
}
return 0, false
}
func minOf(f data.TrackerField) int {
if f.Min != nil {
return *f.Min
}
return 0
}
func statusOf(cur, min, bound int) string {
switch {
case cur <= min || bound <= min:
return StatusDown
case cur >= bound:
return StatusHealthy
case float64(cur-min) <= 0.25*float64(bound-min):
return StatusNearDeath
default:
return StatusHurt
}
}
// projectStruct copies the fields of the struct v that rules allow at level, keyed by JSON name,
// honoring omitempty. A field with no rule is skipped (default deny). A computed field takes its
// value from compute, or is skipped when compute declines; its raw value is never read.
func projectStruct(v reflect.Value, rules map[string]data.ViewLevel, level data.ViewLevel, compute func(string) (any, bool), computed map[string]bool) map[string]any {
out := map[string]any{}
t := v.Type()
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if f.Anonymous && f.Type.Kind() == reflect.Struct {
maps.Copy(out, projectStruct(v.Field(i), rules, level, compute, computed))
continue
}
name, omitEmpty, ok := jsonName(f)
if !ok {
continue
}
min, ruled := rules[name]
if !ruled || min > level {
continue
}
if computed[name] {
if val, ok := compute(name); ok {
out[name] = val
}
continue
}
if omitEmpty && v.Field(i).IsZero() {
continue
}
out[name] = v.Field(i).Interface()
}
return out
}
// jsonName returns the JSON key of f, whether it is omitempty, and false for unexported or "-" fields.
func jsonName(f reflect.StructField) (name string, omitEmpty, ok bool) {
if !f.IsExported() {
return "", false, false
}
tag := f.Tag.Get("json")
if tag == "-" {
return "", false, false
}
parts := strings.Split(tag, ",")
name = parts[0]
if name == "" {
name = f.Name
}
return name, slices.Contains(parts[1:], "omitempty"), true
}
// viewTag is a short digest of a non-GM view, for ETags and change detection.
func viewTag(view map[string]any) string {
b, err := json.Marshal(view) // map keys marshal sorted, so equal views give equal tags
if err != nil {
return ""
}
sum := sha256.Sum256(b)
return hex.EncodeToString(sum[:8])
}
// ViewOwned renders the owner's private encounter. An encounter that belongs to a session is
// reached through ViewForSession.
func (s *Encounters) ViewOwned(ctx context.Context, owner, id string) (EncounterView, error) {
enc, v, err := s.repo.LoadOwnedView(ctx, owner, id)
if err != nil {
return nil, err
}
return s.render(ctx, enc, v)
}
// ViewForSession renders one of the viewer's session's encounters. A missing encounter and one in
// another session are the same error.
func (s *Encounters) ViewForSession(ctx context.Context, v data.Viewer, id string) (EncounterView, error) {
enc, err := s.repo.LoadForViewer(ctx, v, id)
if err != nil {
return nil, err
}
return s.render(ctx, enc, v)
}
// ViewsForSession renders the viewer's session's encounters in display order.
func (s *Encounters) ViewsForSession(ctx context.Context, v data.Viewer, limit int64) ([]EncounterView, error) {
encs, err := s.repo.ListForViewer(ctx, v, limit)
if err != nil {
return nil, err
}
out := make([]EncounterView, 0, len(encs))
for _, enc := range encs {
view, err := s.render(ctx, enc, v)
if err != nil {
return nil, err
}
out = append(out, view)
}
return out, nil
}
// render looks up the encounter's tracker definition and builds the view. A system with no
// definition leaves the status out; it never widens what is shown.
func (s *Encounters) render(ctx context.Context, enc data.Encounter, v data.Viewer) (EncounterView, error) {
return BuildView(enc, s.Definition(ctx, enc), v)
}
// Definition returns the tracker fields of enc's game system, or none when they cannot be had. The
// only thing the definition adds to a view is the coarse health status, so a lookup failure must
// not turn a write that already committed into a 500: it is logged and the status is left out.
func (s *Encounters) Definition(ctx context.Context, enc data.Encounter) []data.TrackerField {
sys, err := s.systems.GetOrDefault(ctx, enc.GameSystemID)
switch {
case err == nil:
return sys.Fields
case !errors.Is(err, data.ErrNotFound):
slog.WarnContext(ctx, "game system lookup failed while building a view; omitting health status", "system", enc.GameSystemID, "error", err)
}
return nil
}
// ViewsOwned renders one page of the owner's private encounters.
func (s *Encounters) ViewsOwned(ctx context.Context, owner string, q data.Query) (data.Page[EncounterView], error) {
page, v, err := s.repo.ListOwnedViews(ctx, owner, q)
if err != nil {
return data.Page[EncounterView]{}, err
}
out := data.Page[EncounterView]{NextCursor: page.NextCursor, Items: make([]EncounterView, 0, len(page.Items))}
for _, enc := range page.Items {
view, err := s.render(ctx, enc, v)
if err != nil {
return data.Page[EncounterView]{}, err
}
out.Items = append(out.Items, view)
}
return out, nil
}
// ViewWritten renders an encounter the owner has just written, so a write's response is built by
// the same function as a read. It refuses an encounter that is not the owner's private one.
func (s *Encounters) ViewWritten(ctx context.Context, owner string, enc data.Encounter) (EncounterView, error) {
v, err := s.repo.OwnedViewer(owner, enc)
if err != nil {
return nil, err
}
return s.render(ctx, enc, v)
}
// Package entitlements is the client for entitlements-api's check routes
// (docs/entitlements-check-contract.md in the platform repo, PADR-0034).
//
// The caller's own bearer token is forwarded on every call (PADR-0037, no service tokens), so a
// check only answers for the user holding that token. Results are cached per (user, key) for the
// TTL the service returns. When the service cannot be reached, FailClosed callers (creates and
// expansions) get ErrUnavailable and FailOpen callers (reads and edits) get the last known value
// (at most maxStale past its TTL) or a Degraded result they must not gate on.
package entitlements
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"sync"
"time"
)
const (
// maxTTL bounds a service-supplied TTL so a bad value cannot pin a stale entitlement.
maxTTL = 5 * time.Minute
// maxEntries bounds the cache; past it, expired entries go first, then everything.
maxEntries = 10000
// maxStale bounds how long FailOpen may serve an expired value during an outage; past it the
// result is Degraded and the caller skips gating.
maxStale = time.Hour
callTimeout = 3 * time.Second
maxBody = 64 << 10
)
// Policy says what a check does when entitlements-api cannot be reached.
type Policy int
const (
// FailClosed returns ErrUnavailable. Use it for creates and expansions.
FailClosed Policy = iota
// FailOpen returns the last known value, or a Degraded result. Use it for reads and edits.
FailOpen
)
var (
// ErrUnavailable means entitlements-api could not be reached or answered with a server error.
ErrUnavailable = errors.New("entitlements: service unavailable")
// ErrUnauthorized means the service rejected the user's token; the caller returns 401.
ErrUnauthorized = errors.New("entitlements: token rejected")
// ErrUnknownKey means the key is not in the catalog: a programming error, never defaulted.
ErrUnknownKey = errors.New("entitlements: key not registered")
)
// Result is one checked key. Flag is set for type "flag", Limit for type "limit".
type Result struct {
Key string
Type string
Flag bool
Limit int
// Degraded is true when no value is known because the service was down under FailOpen.
// Flag and Limit are meaningless then; the caller skips gating.
Degraded bool
// Stale is true when the value is an expired cached one served because the service was down.
// It is usable for gating, but a caller that records the value must not treat it as a fresh read.
Stale bool
}
type entry struct {
res Result
expires time.Time
}
// Client calls entitlements-api. The zero value is not usable; use New.
type Client struct {
base string
http *http.Client
now func() time.Time
mu sync.Mutex
cache map[string]entry
}
// New returns a Client for the entitlements-api base URL.
func New(baseURL string) *Client {
return &Client{
base: baseURL,
http: &http.Client{Timeout: callTimeout},
now: time.Now,
cache: map[string]entry{},
}
}
// Check returns the user's value for key. user is the verified token subject (the cache key);
// token is that user's bearer token, forwarded to the service.
func (c *Client) Check(ctx context.Context, user, token, key string, policy Policy) (Result, error) {
ck := user + "\x00" + key
if res, ok := c.fresh(ck); ok {
return res, nil
}
res, ttl, err := c.fetch(ctx, token, key)
switch {
case err == nil:
c.store(ck, res, ttl)
return res, nil
case errors.Is(err, ErrUnavailable) && policy == FailOpen:
if res, ok := c.stale(ck); ok {
res.Stale = true
return res, nil
}
return Result{Key: key, Degraded: true}, nil
default:
if errors.Is(err, ErrUnknownKey) {
slog.ErrorContext(ctx, "entitlement key not registered", "key", key)
}
return Result{}, err
}
}
func (c *Client) fetch(ctx context.Context, token, key string) (Result, time.Duration, error) {
var body checkBody
if err := c.get(ctx, token, "/check?key="+url.QueryEscape(key), &body); err != nil {
return Result{}, 0, err
}
return body.result(key)
}
// Prefix returns the user's values for every key under prefix in one call and caches each. It
// has no stale fallback: any failure is returned, for callers that only display the values.
func (c *Client) Prefix(ctx context.Context, user, token, prefix string) ([]Result, error) {
var body struct {
Results []checkBody `json:"results"`
}
if err := c.get(ctx, token, "/check/batch?prefix="+url.QueryEscape(prefix), &body); err != nil {
return nil, err
}
out := make([]Result, 0, len(body.Results))
for _, b := range body.Results {
res, ttl, err := b.result(b.Key)
if err != nil {
return nil, err
}
c.store(user+"\x00"+b.Key, res, ttl)
out = append(out, res)
}
return out, nil
}
// get calls path with the user's token and decodes a 200 body into out.
func (c *Client) get(ctx context.Context, token, path string, out any) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.base+path, nil)
if err != nil {
return fmt.Errorf("entitlements: build request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Accept", "application/json")
resp, err := c.http.Do(req)
if err != nil {
slog.WarnContext(ctx, "entitlements call failed", "path", path, "error", err)
return ErrUnavailable
}
defer func() { _ = resp.Body.Close() }()
switch resp.StatusCode {
case http.StatusOK:
if err := json.NewDecoder(io.LimitReader(resp.Body, maxBody)).Decode(out); err != nil {
return ErrUnavailable
}
return nil
case http.StatusUnauthorized:
return ErrUnauthorized
case http.StatusNotFound:
return ErrUnknownKey
default:
slog.WarnContext(ctx, "entitlements call rejected", "path", path, "status", resp.StatusCode)
return ErrUnavailable
}
}
type checkBody struct {
Key string `json:"key"`
Type string `json:"type"`
Value any `json:"value"`
TTL int `json:"ttl_seconds"`
}
func (b checkBody) result(key string) (Result, time.Duration, error) {
res := Result{Key: key, Type: b.Type}
switch v := b.Value.(type) {
case bool:
res.Flag = v
case float64:
if v < 0 || v != float64(int(v)) {
return Result{}, 0, ErrUnavailable
}
res.Limit = int(v)
default:
return Result{}, 0, ErrUnavailable
}
return res, min(time.Duration(b.TTL)*time.Second, maxTTL), nil
}
func (c *Client) fresh(ck string) (Result, bool) {
c.mu.Lock()
defer c.mu.Unlock()
e, ok := c.cache[ck]
if !ok || !c.now().Before(e.expires) {
return Result{}, false
}
return e.res, true
}
func (c *Client) stale(ck string) (Result, bool) {
c.mu.Lock()
defer c.mu.Unlock()
e, ok := c.cache[ck]
return e.res, ok && c.now().Before(e.expires.Add(maxStale))
}
func (c *Client) store(ck string, res Result, ttl time.Duration) {
if ttl <= 0 {
return
}
c.mu.Lock()
defer c.mu.Unlock()
if len(c.cache) >= maxEntries {
now := c.now()
for k, e := range c.cache {
if !now.Before(e.expires) {
delete(c.cache, k)
}
}
if len(c.cache) >= maxEntries {
c.cache = map[string]entry{}
}
}
c.cache[ck] = entry{res: res, expires: c.now().Add(ttl)}
}
// Package events consumes auth-api's change events from the platform bus (PADR-0039): a deny or
// a role removal ends the subject's integration credentials. The event carries no token and the
// consumer holds no service credential (PADR-0037).
package events
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"os"
"sync"
"sync/atomic"
"time"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
"github.com/sweetrpg/initiative-api/data"
)
const (
// StreamName is auth-api's JetStream stream, subject auth.events.>.
StreamName = "AUTH_EVENTS"
FilterSubject = "auth.events.>"
defaultDurable = "initiative-api-credential-revocation"
// Change kinds the event's action carries.
kindDeny = "deny"
kindRoleRemoved = "role_removed"
)
// event is the platform envelope; entity_id is the Auth0 subject and action the change kind.
// Unknown fields are ignored so the envelope can grow.
type event struct {
EventID string `json:"event_id"`
EntityID string `json:"entity_id"`
Action string `json:"action"`
Data struct {
Service string `json:"service"`
} `json:"data"`
}
// ServiceID is the name auth-api's deny entries use for this service. A deny of any other service
// says nothing about initiative credentials.
const ServiceID = "initiative-api"
// Revoker ends a subject's credentials. domain.Credentials implements it.
type Revoker interface {
RevokeOwner(ctx context.Context, owner, reason string) (int, error)
}
// Evictor closes every open stream of a user, on this pod and the others. *stream.Hub implements
// it.
type Evictor interface {
EvictUser(userID string)
}
// Gate is the on/off switch for integration credentials. domain.Credentials implements it.
type Gate interface {
Open(ctx context.Context) (bool, error)
// Close turns credentials off and persists it, so a restart stays closed until an
// administrator's reconcile (the consumer fell behind retention).
Close(ctx context.Context) error
// Pause turns credentials off in this process only (an outage): a reconnect reopens it through
// Open once the consumer has caught up, with no administrator step.
Pause()
}
// handle applies one message. A nil error means ack it; an unparseable or irrelevant message is
// acked (redelivery cannot fix it), a failed revoke is returned so the bus redelivers.
//
// A deny for this service or a removed role ends the subject's integration credentials and then
// every open stream of that user (PADR-0039: a denied owner's open event streams close when the
// revocation lands); ev may be nil. Credentials are revoked first and a failure there is retried
// before anything is evicted; the eviction is idempotent, so a redelivery repeats it harmlessly.
func handle(ctx context.Context, rev Revoker, evict Evictor, body []byte) error {
var ev event
if err := json.Unmarshal(body, &ev); err != nil {
slog.Error("dropping unparseable auth event", "error", err)
return nil
}
reason := map[string]string{kindDeny: data.ReasonOwnerDenied, kindRoleRemoved: data.ReasonOwnerRoleRemoved}[ev.Action]
if reason == "" || ev.EntityID == "" || (ev.Action == kindDeny && ev.Data.Service != ServiceID) {
return nil
}
n, err := rev.RevokeOwner(ctx, ev.EntityID, reason)
if err != nil {
return fmt.Errorf("revoke credentials for event %s: %w", ev.EventID, err)
}
slog.Info("revoked integration credentials", "event_id", ev.EventID, "reason", reason, "count", n)
if evict != nil {
evict.EvictUser(ev.EntityID)
}
return nil
}
// behindRetention reports whether a consumer that last acknowledged ackFloor can no longer replay
// the gap because the stream's oldest retained message is firstSeq. A consumer that never existed
// has nothing to miss: credentials are not issued before it is bound.
func behindRetention(exists bool, ackFloor, firstSeq uint64) bool {
return exists && firstSeq > 1 && ackFloor+1 < firstSeq
}
// Consumer runs the durable pull consumer on AUTH_EVENTS. A Consumer is single-use: Stop latches,
// so a failed Start is followed by a new Consumer, not a second Start.
//
// Fail closed on the credential path only (PADR-0039). A NATS outage does not stop the API: the
// client reconnects forever, and when the connection has been down longer than MaxDisconnect the
// credential gate is closed, so credentials answer 503 until the consumer is back and has caught up
// (or, if the stream's retention overtook it, until a reconcile).
type Consumer struct {
rev Revoker
gate Gate
// Stream and Filter default to AUTH_EVENTS and auth.events.>; tests point them at a prefixed stream.
Stream, Filter string
// Evictor, when set, closes a denied user's open streams (see handle).
Evictor Evictor
// MaxDisconnect is how long NATS may stay unreachable before the gate closes; DefaultMaxDisconnect
// when zero.
MaxDisconnect time.Duration
conn *nats.Conn
cc jetstream.ConsumeContext
stopping atomic.Bool
disconnects atomic.Int64
resyncing atomic.Bool
dead chan struct{}
deadOnce sync.Once
stopOnce sync.Once
sleep func(time.Duration)
mu sync.Mutex
downSince time.Time // zero while connected
closedByLoss bool // the gate was closed by an outage, so a reconnect may reopen it
now func() time.Time
behind func(ctx context.Context) (bool, error) // whether retention overtook the consumer
catchUp func(ctx context.Context) // reopens the gate once nothing is pending
}
// setupTimeout bounds one attempt at looking up and binding the consumer.
const setupTimeout = 30 * time.Second
// reconnectWait is the pause between reconnect tries.
const reconnectWait = 2 * time.Second
// DefaultMaxDisconnect is how long NATS may be unreachable before credentials fail closed.
const DefaultMaxDisconnect = 10 * time.Minute
// outageCheck is how often a down connection is compared with MaxDisconnect.
const outageCheck = 5 * time.Second
func (c *Consumer) onDisconnect(err error) {
if c.stopping.Load() {
return
}
n := c.disconnects.Add(1)
c.mu.Lock()
if c.downSince.IsZero() {
c.downSince = c.now()
}
c.mu.Unlock()
slog.Warn("lost the connection to NATS; auth events are not being applied until it returns", "disconnects", n, "error", err)
}
// DownFor is how long NATS has been unreachable (zero while connected).
func (c *Consumer) DownFor() time.Duration {
c.mu.Lock()
defer c.mu.Unlock()
if c.downSince.IsZero() {
return 0
}
return c.now().Sub(c.downSince)
}
func (c *Consumer) onReconnect(ctx context.Context) {
c.mu.Lock()
c.downSince = time.Time{}
c.mu.Unlock()
slog.Info("reconnected to NATS", "disconnects", c.disconnects.Load())
go c.resync(ctx) // every reconnect: a gap shorter than MaxDisconnect can still outlast the stream's retention
}
// onClosed runs when the client gives up for good (a rejected credential, say): this consumer is
// gone, so credentials are paused and Dead is signalled; the owner builds a new Consumer. The rest of
// the API keeps serving.
func (c *Consumer) onClosed() {
if c.stopping.Load() {
return
}
slog.Error("the NATS connection is closed for good; auth events can no longer be applied and integration credentials are closed", "disconnects", c.disconnects.Load())
c.closeGate()
c.deadOnce.Do(func() { close(c.dead) })
}
// Dead is closed when the connection to NATS is lost for good. The consumer cannot recover; build
// another with New and Start it.
func (c *Consumer) Dead() <-chan struct{} { return c.dead }
func (c *Consumer) closeGate() {
c.gate.Pause() // in this process only: a restart then rechecks retention itself
c.mu.Lock()
c.closedByLoss = true
c.mu.Unlock()
}
// watchOutage closes the gate once the connection has been down past MaxDisconnect.
func (c *Consumer) watchOutage(ctx context.Context) {
t := time.NewTicker(outageCheck)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
}
if c.stopping.Load() {
return
}
c.checkOutage(ctx)
}
}
func (c *Consumer) checkOutage(ctx context.Context) {
limit := c.MaxDisconnect
if limit <= 0 {
limit = DefaultMaxDisconnect
}
c.mu.Lock()
already := c.closedByLoss
c.mu.Unlock()
if d := c.DownFor(); d > limit && !already {
slog.Error("NATS has been unreachable too long to trust the credential list; closing integration credentials", "down_for", d.String(), "limit", limit.String())
c.closeGate()
}
}
// resync runs after every reconnect, one at a time. It asks whether the stream's retention overtook
// this consumer while it was away: if so a deny may be lost for good, so the gate is closed for
// everyone (persisted, the way startup does it) until a reconcile. Otherwise, if an outage had paused
// credentials, they reopen once the consumer has drained what was pending. A failed check or close is
// retried with a growing wait until it succeeds or the consumer stops.
func (c *Consumer) resync(ctx context.Context) {
if !c.resyncing.CompareAndSwap(false, true) {
return // one already running; it will see the current state
}
defer c.resyncing.Store(false)
wait := time.Second
for !c.stopping.Load() && ctx.Err() == nil {
if c.resyncOnce(ctx) {
return
}
c.sleep(wait)
wait = min(wait*2, 30*time.Second)
}
}
// ready returns the stream-bound checks, nil until start has bound the consumer. A reconnect can
// fire while start is still waiting on JetStream (RetryOnFailedConnect); start's own checks cover
// that window.
func (c *Consumer) ready() (behind func(context.Context) (bool, error), catchUp func(context.Context)) {
c.mu.Lock()
defer c.mu.Unlock()
return c.behind, c.catchUp
}
// closeIfBehind persists the gate closure when retention overtook the consumer. done is true once
// the question is settled (the gate was closed, or the check does not apply yet); a false done with
// behind false means the consumer is within retention.
func (c *Consumer) closeIfBehind(ctx context.Context) (behind, done bool) {
check, _ := c.ready()
if check == nil {
return false, true
}
behind, err := check(ctx)
if err != nil {
slog.Error("could not check the auth-event consumer against the stream; will retry", "error", err)
return false, false
}
if !behind {
return false, true
}
slog.Error("auth-event consumer is behind stream retention; closing integration credentials until reconcile")
if err := c.gate.Close(ctx); err != nil {
slog.Error("could not persist the credential gate closure; will retry", "error", err)
return true, false
}
c.mu.Lock()
c.closedByLoss = false // a reconcile reopens it, not a reconnect
c.mu.Unlock()
return true, true
}
// resyncOnce reports whether the check is finished.
func (c *Consumer) resyncOnce(ctx context.Context) bool {
behind, done := c.closeIfBehind(ctx)
if !done || behind {
return done
}
_, catchUp := c.ready()
if catchUp == nil {
return true
}
c.mu.Lock()
reopen := c.closedByLoss
c.mu.Unlock()
if reopen {
catchUp(ctx)
c.mu.Lock()
c.closedByLoss = false
c.mu.Unlock()
}
return true
}
// New builds a consumer. The gate must start closed.
func New(rev Revoker, gate Gate) *Consumer {
return &Consumer{rev: rev, gate: gate, Stream: StreamName, Filter: FilterSubject, now: time.Now, sleep: time.Sleep, dead: make(chan struct{})}
}
// Start connects, binds the durable consumer, and begins revoking. The gate opens only after the
// consumer has drained what was pending, and stays closed when the consumer fell behind the
// stream's retention (until an administrator's reconcile reopens it). A failed Start closes its
// connection; build a new Consumer to try again.
func (c *Consumer) Start(ctx context.Context, natsURL, durable string) error {
err := c.start(ctx, natsURL, durable)
if err != nil {
c.Stop()
}
return err
}
func (c *Consumer) start(ctx context.Context, natsURL, durable string) error {
if c.Evictor == nil {
// A deny would be acked with its streams still open. Wiring the evictor is the owner's job and
// must happen before the first event can be consumed, so a consumer without one never starts.
return errors.New("auth-event consumer has no evictor")
}
if durable == "" {
durable = defaultDurable
}
opts := []nats.Option{
nats.Name(durable), nats.ReconnectWait(reconnectWait),
nats.MaxReconnects(-1), nats.RetryOnFailedConnect(true), // the outage clock, not a retry count, decides
nats.DisconnectErrHandler(func(_ *nats.Conn, err error) { c.onDisconnect(err) }),
nats.ReconnectHandler(func(*nats.Conn) { c.onReconnect(ctx) }),
nats.ClosedHandler(func(*nats.Conn) { c.onClosed() }),
}
opts = append(opts, authOptions()...)
conn, err := nats.Connect(natsURL, opts...)
if err != nil {
return fmt.Errorf("connect to NATS: %w", err)
}
c.conn = conn
js, err := jetstream.New(conn)
if err != nil {
return fmt.Errorf("create JetStream context: %w", err)
}
// Setup calls are bounded per attempt; ctx outlives them and serves the running consumer.
sctx, cancel := context.WithTimeout(ctx, setupTimeout)
defer cancel()
stream, err := js.Stream(sctx, c.Stream)
if err != nil {
return fmt.Errorf("stream %s: %w", c.Stream, err)
}
sinfo, err := stream.Info(sctx)
if err != nil {
return fmt.Errorf("stream info: %w", err)
}
prior, err := stream.Consumer(sctx, durable)
exists := err == nil
if err != nil && !errors.Is(err, jetstream.ErrConsumerNotFound) {
return fmt.Errorf("look up consumer %q: %w", durable, err)
}
if exists {
pinfo, ierr := prior.Info(sctx)
if ierr != nil {
return fmt.Errorf("consumer info: %w", ierr)
}
if behindRetention(true, pinfo.AckFloor.Stream, sinfo.State.FirstSeq) {
slog.Error("auth-event consumer is behind stream retention; integration credentials stay closed until reconcile")
if err := c.gate.Close(sctx); err != nil {
return fmt.Errorf("close credential gate: %w", err)
}
}
}
cons, err := stream.CreateOrUpdateConsumer(sctx, jetstream.ConsumerConfig{
Durable: durable, FilterSubject: c.Filter, AckPolicy: jetstream.AckExplicitPolicy,
})
if err != nil {
return fmt.Errorf("bind durable consumer %q: %w", durable, err)
}
cc, err := cons.Consume(func(msg jetstream.Msg) { c.process(ctx, msg) })
if err != nil {
return fmt.Errorf("start consuming: %w", err)
}
c.cc = cc
behind := func(ctx context.Context) (bool, error) {
si, err := stream.Info(ctx)
if err != nil {
return false, err
}
ci, err := cons.Info(ctx)
if err != nil {
return false, err
}
return behindRetention(true, ci.AckFloor.Stream, si.State.FirstSeq), nil
}
catchUp := func(ctx context.Context) { c.openWhenCaughtUp(ctx, cons) }
c.mu.Lock()
c.behind, c.catchUp = behind, catchUp
c.mu.Unlock()
go catchUp(ctx)
go c.watchOutage(ctx)
return nil
}
func (c *Consumer) process(ctx context.Context, msg jetstream.Msg) {
if err := handle(ctx, c.rev, c.Evictor, msg.Data()); err != nil {
slog.Error("auth event handling failed, will retry", "error", err)
_ = msg.Nak()
return
}
_ = msg.Ack()
}
// openWhenCaughtUp polls until nothing is pending or awaiting ack, then opens the gate. Each round
// rechecks retention first, so a poll that outlives an outage cannot open a gate the stream's
// retention has since closed; it ends when the consumer stops.
func (c *Consumer) openWhenCaughtUp(ctx context.Context, cons jetstream.Consumer) {
t := time.NewTicker(time.Second)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
}
if c.stopping.Load() {
return
}
if behind, done := c.closeIfBehind(ctx); behind && done {
return
}
info, err := cons.Info(ctx)
if err != nil || info.NumPending > 0 || info.NumAckPending > 0 {
continue
}
open, err := c.gate.Open(ctx)
if err != nil {
slog.Error("open credential gate", "error", err)
continue
}
slog.Info("integration credentials caught up", "open", open)
return
}
}
// Stop halts consumption and closes the connection. It is safe to call more than once and from
// several goroutines (the shutdown path and the Dead path can both reach it).
func (c *Consumer) Stop() {
c.stopping.Store(true)
c.stopOnce.Do(func() {
if c.cc != nil {
c.cc.Stop()
}
if c.conn != nil {
c.conn.Close()
}
})
}
// authOptions is the broker login from the environment: a NATS_CREDS file when set, else
// NATS_USER and NATS_PASSWORD.
func authOptions() []nats.Option {
if creds := os.Getenv("NATS_CREDS"); creds != "" {
return []nats.Option{nats.UserCredentials(creds)}
}
if user := os.Getenv("NATS_USER"); user != "" {
return []nats.Option{nats.UserInfo(user, os.Getenv("NATS_PASSWORD"))}
}
return nil
}
package events
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
"github.com/sweetrpg/initiative-api/events/stream"
)
// SubjectPrefix is the root of initiative's entity-change subjects:
// initiative.events.<entity>.<action> (docs/messaging-nats.md, PADR-0026). The INITIATIVE_EVENTS
// stream binds initiative.events.>.
const SubjectPrefix = "initiative.events."
// jsPublisher is the part of jetstream.JetStream the publisher uses.
type jsPublisher interface {
PublishMsg(ctx context.Context, m *nats.Msg, opts ...jetstream.PublishOpt) (*jetstream.PubAck, error)
}
// Publisher puts encounter events on the platform bus. It implements stream.Bus; the hub calls it
// from its own queue, so a slow or absent broker never reaches a write (fail-open, PADR-0024).
// There is no retry queue: an event that cannot be published is dropped and counted by the hub.
type Publisher struct {
js jsPublisher
conn *nats.Conn
}
// NewPublisher connects to natsURL with the login from the environment (NATS_CREDS, or NATS_USER
// and NATS_PASSWORD). The client keeps retrying a broker that is down at start and after a loss, so
// the service starts either way; a publication made meanwhile fails and is dropped.
func NewPublisher(natsURL string) (*Publisher, error) {
opts := append([]nats.Option{
nats.Name("initiative-api-publisher"), nats.ReconnectWait(reconnectWait),
nats.MaxReconnects(-1), nats.RetryOnFailedConnect(true),
}, authOptions()...)
conn, err := nats.Connect(natsURL, opts...)
if err != nil {
return nil, fmt.Errorf("connect to NATS: %w", err)
}
js, err := jetstream.New(conn)
if err != nil {
conn.Close()
return nil, fmt.Errorf("create JetStream context: %w", err)
}
return &Publisher{js: js, conn: conn}, nil
}
// UserSubjectPrefix is the root of the subjects of events addressed to one user:
// initiative.user.<user_id>.<type>, where the dotted type (turn.yours) stays two tokens, so a
// consumer filters with initiative.user.*.turn.>.
const UserSubjectPrefix = "initiative.user."
// Subject is the subject an event is published on.
func Subject(e stream.Event) string {
if e.UserID != "" {
parts := strings.Split(e.Type, ".")
for i := range parts {
parts[i] = token(parts[i])
}
return UserSubjectPrefix + token(e.UserID) + "." + strings.Join(parts, ".")
}
return SubjectPrefix + token(e.EntityType) + "." + token(e.Action)
}
// token keeps a value to one subject segment; a dot, wildcard or space would change the subject.
func token(s string) string {
return strings.Map(func(r rune) rune {
switch r {
case '.', '*', '>', ' ':
return '_'
}
return r
}, s)
}
// Publish sends e and waits for the stream's acknowledgement, bounded by ctx. event_id doubles as
// the Nats-Msg-Id, so a republished event is stored once inside the stream's duplicate window.
func (p *Publisher) Publish(ctx context.Context, e stream.Event) error {
body, err := json.Marshal(e)
if err != nil {
return fmt.Errorf("encode event %s: %w", e.EventID, err)
}
msg := &nats.Msg{Subject: Subject(e), Data: body, Header: nats.Header{}}
msg.Header.Set(nats.MsgIdHdr, e.EventID)
if _, err := p.js.PublishMsg(ctx, msg); err != nil {
return fmt.Errorf("publish %s: %w", msg.Subject, err)
}
return nil
}
// Close flushes what the client still has buffered and closes the connection. Call it after the
// hub's queue has stopped (Hub.Close), so events the queue already handed over are not lost on a
// deploy. A broker that is down makes Drain give up; the events are then dropped, as in any outage.
func (p *Publisher) Close() {
if err := p.conn.Drain(); err != nil {
p.conn.Close()
}
}
package stream
import (
"context"
"log/slog"
"sync"
"time"
"github.com/sweetrpg/initiative-api/data"
)
// busPublishTimeout bounds one publication, so a stuck broker cannot hold the queue.
const busPublishTimeout = 2 * time.Second
type busQueue struct {
bus Bus
ch chan Event
done chan struct{}
wg sync.WaitGroup
}
// AttachBus publishes the bus form of every event to bus from a queue of the given size, in a
// goroutine, fail-open: a full queue or a failed publication drops the event (counted by Dropped
// and logged) and never affects the write or the WebSocket subscribers. Call Close to stop it.
func (h *Hub) AttachBus(bus Bus, queue int) {
h.closeBus() // a second attach replaces the first, whose goroutine must not outlive it
q := &busQueue{bus: bus, ch: make(chan Event, max(queue, 1)), done: make(chan struct{})}
q.wg.Add(1)
go func() {
defer q.wg.Done()
for {
select {
case ev := <-q.ch:
ctx, cancel := context.WithTimeout(context.Background(), busPublishTimeout)
if err := bus.Publish(ctx, ev); err != nil {
h.dropped.Add(1)
slog.Warn("publishing an encounter event to the bus failed", "event_id", ev.EventID, "type", ev.Type, "error", err)
}
cancel()
case <-q.done:
return
}
}
}()
h.mu.Lock()
h.bus = q
h.mu.Unlock()
}
// Close stops the bus and notice goroutines, if started.
func (h *Hub) Close() {
h.closeBus()
h.stopNotices()
}
func (h *Hub) closeBus() {
h.mu.Lock()
q := h.bus
h.bus = nil
h.mu.Unlock()
if q != nil {
close(q.done)
q.wg.Wait()
}
}
// publishNoticeToBus queues one event per addressee for the bus, where a push service can consume
// it. It carries what the addressee's own stream carries and is published on the addressee's own
// subject. Two addressees are left out: one who muted the type (the consumer has no other way to
// see the mute) and one who is no longer a member of the session, since nothing ends a push the way
// a stream's eviction ends a stream (so a removed requester gets no change_request.approved).
// Fail-open like every bus publication, except the membership check, which fails closed.
func (h *Hub) publishNoticeToBus(n data.Notice, muted map[string]bool, isMember func(string) bool) {
h.mu.RLock()
q := h.bus
h.mu.RUnlock()
if q == nil {
return
}
seen := map[string]bool{}
for _, u := range n.Users {
if u == "" || seen[u] || muted[u] {
continue
}
seen[u] = true
if !isMember(u) {
continue
}
ev := noticeEvent(n, newEventID())
ev.UserID = u
select {
case q.ch <- ev:
default:
h.dropped.Add(1)
slog.Warn("the bus queue is full; dropping a notice", "event_id", ev.EventID, "type", ev.Type)
}
}
}
func (h *Hub) publishToBus(ctx context.Context, em *emission) {
h.mu.RLock()
q := h.bus
h.mu.RUnlock()
// A private encounter has no audience beyond its owner; the bus is for what a session's other
// consumers may react to.
if q == nil || (em.c.SessionID == "" && em.c.After.SessionID == "") {
return
}
ev, ok := em.busEvent()
if !ok {
return
}
select {
case q.ch <- ev:
default:
h.dropped.Add(1)
slog.WarnContext(ctx, "the bus queue is full; dropping an encounter event", "event_id", ev.EventID, "type", ev.Type)
}
}
// Package stream turns committed encounter changes into the events subscribers receive. The data
// layer reports each commit to a Sink (data.Sink); the Hub here is that sink. It renders the
// committed document once per viewer, with the same view builder REST uses, and sends each
// subscriber only what its role may see: ids, never data.
package stream
import (
"crypto/rand"
"fmt"
"strings"
"time"
"github.com/sweetrpg/initiative-api/data"
)
// Source is the publisher name in every envelope.
const Source = "initiative-api"
// Event is one envelope (docs/messaging-nats.md). Data carries ids only: the changed combatant ids
// and, for turn and state changes, the status, round and current combatant id. A client that wants
// the content fetches the encounter, so the content always passes through the view builder.
type Event struct {
EventID string `json:"event_id"`
OccurredAt time.Time `json:"occurred_at"`
Source string `json:"source"`
EncounterID string `json:"encounter_id"`
SessionID string `json:"session_id,omitempty"`
// UserID is the addressee of a notice published to the bus (one event per addressee); it is
// empty on every other event.
UserID string `json:"user_id,omitempty"`
EntityType string `json:"entity_type"`
EntityID string `json:"entity_id"`
Action string `json:"action"`
Type string `json:"type"`
// Revision orders a GM's or co-GM's events. Other viewers never get it: the stored revision
// moves on every edit, hidden ones included, so it would show them edits they cannot see.
Revision int64 `json:"revision,omitempty"`
// ViewTag is, for every other viewer, the digest of the view the change left them with (the same
// value their encounter view carries). They order events by it and refetch when it differs from
// the one they hold; a change that leaves it unchanged produces no event for them at all.
ViewTag string `json:"view_tag,omitempty"`
Origin Origin `json:"origin"`
Data map[string]any `json:"data"`
}
// Origin tags the kind of writer and, to the originating user's own streams only, the client id
// they sent, so a client can recognise its own echo.
type Origin struct {
Kind string `json:"kind"`
ClientID string `json:"client_id,omitempty"`
}
// actionOf is the last segment of an event type ("turn.advanced" is "advanced").
func actionOf(eventType string) string {
if i := strings.LastIndex(eventType, "."); i >= 0 {
return eventType[i+1:]
}
return eventType
}
// newEventID returns a random (version 4) UUID.
func newEventID() string {
var b [16]byte
_, _ = rand.Read(b[:])
b[6] = b[6]&0x0f | 0x40
b[8] = b[8]&0x3f | 0x80
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
}
// base is the envelope of c with no data and no client id: what every viewer shares.
func base(c data.Change, id string) Event {
kind := c.Origin.Kind
if kind == "" {
kind = data.OriginSystem
}
return Event{
EventID: id, OccurredAt: c.At.UTC(), Source: Source,
EncounterID: c.After.ID, SessionID: c.SessionID,
EntityType: "encounter", EntityID: c.After.ID,
Origin: Origin{Kind: kind},
Data: map[string]any{},
}
}
func typed(e Event, eventType string) Event {
e.Type, e.Action = eventType, actionOf(eventType)
return e
}
package stream
import (
"context"
"log/slog"
"sync"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/domain"
)
// emission is one committed change on its way to its subscribers. It renders the after-document
// for a viewer at most once per distinct view (the GM level needs no rendering; the others are
// keyed by level, plus the actor for a player, because a player sees a hidden combatant they
// control), and is dropped when the fan-out ends, so no snapshot outlives it.
type emission struct {
ctx context.Context
r Renderer
c data.Change
id string
// The tracker definition is looked up once per emission (after, and before only if the game
// system changed), so fan-out does no per-viewer reads.
afterDef, beforeDef []data.TrackerField
afterOnce, beforeOnce sync.Once
mu sync.Mutex
views map[viewKey]*viewInfo
}
func (em *emission) defAfter() []data.TrackerField {
em.afterOnce.Do(func() { em.afterDef = em.r.Definition(em.ctx, em.c.After) })
return em.afterDef
}
func (em *emission) defBefore() []data.TrackerField {
if em.c.Before == nil || em.c.Before.GameSystemID == em.c.After.GameSystemID {
return em.defAfter()
}
em.beforeOnce.Do(func() { em.beforeDef = em.r.Definition(em.ctx, *em.c.Before) })
return em.beforeDef
}
type viewKey struct {
level data.ViewLevel
actor string
}
// viewInfo is what one viewer's rendering of the encounter shows of the ids an event can name.
type viewInfo struct {
visible map[string]bool
current string
tag string
// beforeTag is the tag of the view before the change; known is false when the write path had no
// before-document, and then the change cannot be shown to leave the view alone.
beforeTag string
known bool
err error
}
// unchanged reports whether the change left this viewer's view as it was.
func (vi *viewInfo) unchanged() bool { return vi.err == nil && vi.known && vi.tag == vi.beforeTag }
func newEmission(ctx context.Context, r Renderer, c data.Change) *emission {
return &emission{ctx: ctx, r: r, c: c, id: newEventID(), views: map[viewKey]*viewInfo{}}
}
func (em *emission) info(v data.Viewer) *viewInfo {
k := viewKey{level: v.Level()}
if v.Level() == data.ViewPlayer {
k.actor = v.Actor()
}
em.mu.Lock()
defer em.mu.Unlock()
if vi, ok := em.views[k]; ok {
return vi
}
vi := &viewInfo{visible: map[string]bool{}}
view, err := domain.BuildView(em.c.After, em.defAfter(), v)
if err != nil {
vi.err = err
slog.WarnContext(em.ctx, "rendering an encounter for an event subscriber failed; sending it without ids", "encounter", em.c.After.ID, "error", err)
} else {
list, _ := view["combatants"].([]map[string]any)
for _, c := range list {
if id, ok := c["id"].(string); ok {
vi.visible[id] = true
}
}
vi.current, _ = view["current_combatant_id"].(string)
vi.tag, _ = view[domain.FieldViewTag].(string)
if b := em.c.Before; b != nil {
if bv, berr := domain.BuildView(*b, em.defBefore(), v); berr == nil {
vi.beforeTag, _ = bv[domain.FieldViewTag].(string)
vi.known = true
}
}
}
em.views[k] = vi
return vi
}
// idEvent reports whether t names changed combatants.
func idEvent(t string) bool {
switch t {
case data.EventCombatantAdded, data.EventCombatantUpdated, data.EventCombatantRemoved, data.EventCombatantRestored, data.EventControllers:
return true
}
return false
}
// stateEvent reports whether t carries the encounter's status, round and current combatant.
func stateEvent(t string) bool {
switch t {
case data.EventTurn, data.EventStarted, data.EventEnded, data.EventReset:
return true
}
return false
}
// forViewer is the event v may receive for the change, or false if none. It fails closed: when
// the viewer's rendering cannot be had the event is the generic encounter.updated with no ids,
// never the unfiltered one.
func (em *emission) forViewer(v data.Viewer) (Event, bool) {
c := em.c
ev := base(c, em.id)
if c.Origin.Kind == data.OriginUser && c.Origin.ClientID != "" && v.Actor() != "" && v.Actor() == c.Origin.ActorID {
ev.Origin.ClientID = c.Origin.ClientID
}
switch {
case v.Level() == data.ViewNone:
return Event{}, false
case c.GMOnly:
// A lock or inactive flag is limit and entitlement state; only the GM hears of it.
if v.Level() != data.ViewGM {
return Event{}, false
}
ev = typed(ev, data.EventUpdated)
ev.Revision = c.After.Revision
return ev, true
case v.Level() == data.ViewGM:
return em.gmEvent(ev), true
}
if c.Type == data.EventCreated || c.Type == data.EventDeleted || c.Type == data.EventReleased {
// These name no combatant and say the encounter itself appeared or went (a released
// encounter no longer belongs to the viewer's session, so it is not rendered).
return typed(ev, c.Type), true
}
vi := em.info(v)
if vi.unchanged() {
// A change the viewer cannot see: no event, no gap to explain, nothing to refetch.
return Event{}, false
}
ev.ViewTag = vi.tag
return em.filtered(ev, vi), true
}
func (em *emission) gmEvent(ev Event) Event {
c := em.c
ev = typed(ev, c.Type)
ev.Revision = c.After.Revision
switch {
case idEvent(c.Type):
if ids := ids(c); len(ids) > 0 {
ev.Data["combatant_ids"] = ids
} else {
ev = typed(ev, data.EventUpdated)
}
case stateEvent(c.Type):
ev.Data["status"], ev.Data["round"] = c.After.Status, c.After.Round
if c.After.CurrentCombatantID != "" {
ev.Data["current_combatant_id"] = c.After.CurrentCombatantID
}
}
return ev
}
// filtered is the event for a non-GM viewer: only ids the viewer's own rendering shows, and the
// current combatant only if the viewer can see it. A change that touched nothing the viewer can
// see becomes the generic encounter.updated with no ids, so the viewer refetches and a hidden
// combatant's id, name, health, notes and initiative never appear.
func (em *emission) filtered(ev Event, vi *viewInfo) Event {
c := em.c
if vi.err != nil {
return typed(ev, data.EventUpdated)
}
ev = typed(ev, c.Type)
switch {
case idEvent(c.Type):
var shown []string
for _, id := range ids(c) {
if vi.visible[id] {
shown = append(shown, id)
}
}
if len(shown) == 0 {
return typed(ev, data.EventUpdated)
}
ev.Data["combatant_ids"] = shown
case stateEvent(c.Type):
ev.Data["status"], ev.Data["round"] = c.After.Status, c.After.Round
if vi.current != "" {
ev.Data["current_combatant_id"] = vi.current
}
}
return ev
}
// busEvent is the form published to the platform bus: the observer-level rendering of the change,
// with no client id, and nothing at all for a GM-only change. Any consumer may receive it, so it
// is as restricted as a player's.
func (em *emission) busEvent() (Event, bool) {
if em.c.GMOnly {
return Event{}, false
}
ev := base(em.c, em.id)
ev.Origin.ClientID = ""
if em.c.Type == data.EventCreated || em.c.Type == data.EventDeleted || em.c.Type == data.EventReleased {
return typed(ev, em.c.Type), true
}
vi := em.info(data.BusViewer(em.c.After.SessionID))
if vi.unchanged() {
return Event{}, false
}
ev.ViewTag = vi.tag
return em.filtered(ev, vi), true
}
package stream
import (
"context"
"errors"
"log/slog"
"slices"
"sync"
"sync/atomic"
"time"
"github.com/sweetrpg/initiative-api/data"
)
// Renderer gives the hub the tracker definition BuildView needs, looked up once per change.
// *domain.Encounters implements it.
type Renderer interface {
Definition(ctx context.Context, enc data.Encounter) []data.TrackerField
}
// Bus receives the observer-level form of each event for the platform message bus. Publish must
// not block; the hub hands it events from a bounded queue and drops (and counts) when the queue is
// full, since bus publication is fail-open.
type Bus interface {
Publish(ctx context.Context, e Event) error
}
// Hub is the data.Sink: it fans each committed change out to the subscriptions it concerns, after
// the commit, without blocking the writer. There is no outbox: a crash between commit and
// publication loses the event, which clients cover by refetching when they reconnect. A viewer who
// is not a GM or co-GM is told only of changes that alter their own view (see Event.ViewTag), so a
// hidden edit leaves them no gap.
type Hub struct {
r Renderer
mu sync.RWMutex
sub map[*Subscription]struct{}
bus *busQueue
stopping atomic.Bool
live atomic.Int64 // stream handlers still running, upgraded or not
rel *Relay
prefs Preferences
managers Managers
members Members
noticeClosed bool // set under mu by Close; final
noticeOnce sync.Once
noticeQ chan noticeJob
noticeDone chan struct{}
noticeWG sync.WaitGroup
noticePending sync.WaitGroup
pendingTTL time.Duration
dropped atomic.Int64 // events not delivered: full subscriber buffer closed, or full bus queue
emitted atomic.Int64
}
// PendingTTL is how long a subscription may wait for Grant before the hub closes it, so a transport
// that never grants or closes one cannot leak it.
const PendingTTL = 10 * time.Second
// SetPendingTTL changes how long a pending subscription lives; it applies to later Opens.
func (h *Hub) SetPendingTTL(d time.Duration) {
h.mu.Lock()
h.pendingTTL = d
h.mu.Unlock()
}
// New returns a hub that renders with r.
func New(r Renderer) *Hub {
return &Hub{r: r, sub: map[*Subscription]struct{}{}, pendingTTL: PendingTTL}
}
// Dropped is the number of events not delivered because a subscriber's buffer or the bus queue was
// full.
func (h *Hub) Dropped() int64 { return h.dropped.Load() }
// Emitted is the number of committed changes the hub has handled.
func (h *Hub) Emitted() int64 { return h.emitted.Load() }
// Subscription is one connection's feed. It is made pending by Open, receives nothing until Grant
// gives it the viewer proving what the subscriber may see, and ends by Close, by Evict, or when the
// hub finds the subscriber behind. With an encounter id it follows that encounter; with none it
// follows every encounter the viewer's audience hears of (a session's, or an owner's private
// ones), which is how encounter.created reaches anyone, since a new encounter has no subscribers
// of its own. C is closed when the subscription ends.
type Subscription struct {
C chan Event
h *Hub
session string // fixed by Open; the audience Evict matches, before and after Grant
actor string
encounterID string
userLevel bool // receives only addressed events, across sessions; never has a viewer
viewer atomic.Pointer[data.Viewer] // nil until Grant
overflowed atomic.Bool
shutdown atomic.Bool // closed because the server is stopping
mu sync.Mutex // guards closed, the grant, and every send on and close of C
closed bool
timer *time.Timer // ends a subscription never granted
}
// ErrEvicted means the subscription ended (evicted, closed, or overflowed) before Grant.
var ErrEvicted = errors.New("stream: subscription ended before it was granted")
// ErrGranted means Grant was called a second time: a viewer is fixed when first granted, so a
// higher level cannot be swapped in without ending the subscription and authorizing again.
var ErrGranted = errors.New("stream: subscription already granted")
// ErrViewer means Grant was given a viewer that cannot stream: a zero one, one with no actor (such
// as BusViewer), or one for a different actor or session than Open named.
var ErrViewer = errors.New("stream: viewer does not match the subscription")
// Open registers a pending subscription of actor in the session ("" for an owner's private
// encounters) with a buffer of buf events (at least 1). An empty encounterID follows every
// encounter in the viewer's audience. A pending subscription receives nothing, but Evict already
// reaches it, so an eviction that lands while the subscriber is being authorized is not lost:
// authorize, then Grant. The transport must Close the subscription on every path that does not
// end in Grant; one still pending after PendingTTL is closed by the hub.
func (h *Hub) Open(sessionID, actor, encounterID string, buf int) *Subscription {
s := &Subscription{C: make(chan Event, max(buf, 1)), h: h, session: sessionID, actor: actor, encounterID: encounterID}
h.mu.Lock()
h.sub[s] = struct{}{}
ttl := h.pendingTTL
h.mu.Unlock()
if ttl > 0 {
s.mu.Lock()
s.timer = time.AfterFunc(ttl, s.expire)
s.mu.Unlock()
}
if h.stopping.Load() { // registered after Shutdown took its snapshot
s.shutdown.Store(true)
s.Close()
}
return s
}
// OpenUser registers a user-level subscription: the addressed events of every session actor
// belongs to, and no encounter state. It needs no Grant (there is no scope to authorize; each
// delivery checks the session membership). The transport must Close it.
func (h *Hub) OpenUser(actor string, buf int) *Subscription {
s := &Subscription{C: make(chan Event, max(buf, 1)), h: h, actor: actor, userLevel: true}
h.mu.Lock()
h.sub[s] = struct{}{}
h.mu.Unlock()
if h.stopping.Load() {
s.shutdown.Store(true)
s.Close()
}
return s
}
// Grant makes the subscription live for v, which the caller obtained by authorizing the actor
// (data.Sessions.AuthorizeView or an owner viewer). It fails with ErrEvicted if the subscription
// ended since Open, with ErrViewer if v could not stream, and with ErrGranted on a second call.
func (s *Subscription) Grant(v data.Viewer) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return ErrEvicted
}
if v.Level() == data.ViewNone || v.Actor() == "" || v.Actor() != s.actor || v.SessionID() != s.session {
return ErrViewer
}
if !s.viewer.CompareAndSwap(nil, &v) {
return ErrGranted
}
if s.timer != nil {
s.timer.Stop()
}
return nil
}
// send delivers ev without blocking. C is only ever sent on and closed under mu, so a send never
// meets a closed channel. overflow means the buffer was full.
func (s *Subscription) send(ev Event) (overflow bool) {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return false
}
select {
case s.C <- ev:
return false
default:
return true
}
}
// Close ends the subscription. It is safe to call more than once and from any goroutine.
func (s *Subscription) Close() {
s.mu.Lock()
s.closeLocked()
s.mu.Unlock()
s.unregister()
}
// closeLocked ends the subscription; s.mu must be held.
func (s *Subscription) closeLocked() {
if s.closed {
return
}
s.closed = true
close(s.C)
if s.timer != nil {
s.timer.Stop()
}
}
func (s *Subscription) unregister() {
s.h.mu.Lock()
delete(s.h.sub, s)
s.h.mu.Unlock()
}
// expire ends a subscription still pending at its deadline. The grant and the close are decided
// under s.mu, so a Grant that returned nil is never followed by this close.
func (s *Subscription) expire() {
s.mu.Lock()
if s.viewer.Load() != nil || s.closed {
s.mu.Unlock()
return
}
s.closeLocked()
s.mu.Unlock()
s.unregister()
}
// Ended reports whether the subscription has been closed (evicted, overflowed, or closed).
func (s *Subscription) Ended() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.closed
}
// ServerStopping reports whether the hub closed the subscription because the server is shutting
// down, so the transport can say so (close code 1001) and the client reconnect elsewhere.
func (s *Subscription) ServerStopping() bool { return s.shutdown.Load() }
// Overflowed reports whether the hub closed the subscription because its buffer was full.
func (s *Subscription) Overflowed() bool { return s.overflowed.Load() }
// Evict closes every subscription (pending or live) of userID on the session, or of everyone on it
// when userID is empty, here and on the other pods (see Relay). A subscription's viewer is fixed
// when it is granted, so a user who is removed, blocked, leaves, or changes role must lose it: the
// client reconnects and is authorized again, at its new level or not at all.
func (h *Hub) Evict(sessionID, userID string) {
if sessionID == "" {
return // an empty session would match every private subscription
}
h.evictLocal(sessionID, userID)
if r := h.relay(); r != nil {
r.publishEvict(sessionID, userID)
}
}
// EvictUser closes every subscription of userID, pending or live, in any session, user-level or on
// private encounters, here and on the other pods. Platform-wide access was revoked (a deny or a
// removed role in auth-api), not one session's, so nothing the user holds may stay open; the client
// reconnects and is authorized again, which auth-api refuses while the denial stands. It is not
// remembered: a user who is granted access again simply reconnects.
func (h *Hub) EvictUser(userID string) {
if userID == "" {
return // would match nobody here and, in a fan-out row, be mistaken for everybody
}
h.evictUserLocal(userID)
if r := h.relay(); r != nil {
r.publishEvict("", userID)
}
}
func (h *Hub) evictUserLocal(userID string) {
h.mu.RLock()
var gone []*Subscription
for s := range h.sub {
if s.actor == userID {
gone = append(gone, s)
}
}
h.mu.RUnlock()
for _, s := range gone {
s.Close()
}
}
func (h *Hub) evictLocal(sessionID, userID string) {
if sessionID == "" {
return // an empty session would match every private subscription
}
h.mu.RLock()
var gone []*Subscription
for s := range h.sub {
if s.session == sessionID && (userID == "" || s.actor == userID) {
gone = append(gone, s)
}
}
h.mu.RUnlock()
for _, s := range gone {
s.Close()
}
}
// evictAudience ends the subscriptions that would have heard c: a session's, or an owner's private
// ones.
func (h *Hub) evictAudience(c data.Change) {
h.mu.RLock()
var gone []*Subscription
for s := range h.sub {
if (c.SessionID != "" && s.session == c.SessionID) || (c.SessionID == "" && s.session == "" && !s.userLevel && s.actor == c.OwnerID) {
gone = append(gone, s)
}
}
h.mu.RUnlock()
for _, s := range gone {
s.Close()
}
}
// evictAll closes every subscription, pending or live, and returns how many. The relay does it when
// its tail restarts without a position, since evictions written in the gap are unknown: each client
// reconnects and is authorized again.
func (h *Hub) evictAll() int {
h.mu.RLock()
gone := make([]*Subscription, 0, len(h.sub))
for s := range h.sub {
gone = append(gone, s)
}
h.mu.RUnlock()
for _, s := range gone {
s.Close()
}
return len(gone)
}
// Emit implements data.Sink. It never blocks and never panics out: a failure to render or deliver
// for one subscriber affects only that subscriber.
func (h *Hub) Emit(ctx context.Context, c data.Change) {
h.emitted.Add(1)
em := newEmission(ctx, h.r, c)
h.deliverLocal(ctx, em)
h.publishToBus(ctx, em)
for _, n := range turnNotices(c) {
h.Notify(ctx, n)
}
if r := h.relay(); r != nil {
r.publishChange(c, em.id)
}
}
// deliverLocal sends the change to this pod's subscribers.
func (h *Hub) deliverLocal(ctx context.Context, em *emission) {
for _, s := range h.snapshot(em.c.After.ID) {
h.deliver(ctx, em, s)
}
}
// emitRemote delivers a change another pod committed to this pod's subscribers. The bus and the
// relay are the originating pod's to feed, so neither runs here.
func (h *Hub) emitRemote(ctx context.Context, c data.Change, eventID string) {
h.emitted.Add(1)
em := newEmission(ctx, h.r, c)
if eventID != "" {
em.id = eventID // the same id on every pod, so a client can recognize a duplicate
}
h.deliverLocal(ctx, em)
}
// deliver sends the event s may receive for the change, recovering from a panic so one
// subscriber's failure cannot cost the others (or the bus) the event.
func (h *Hub) deliver(ctx context.Context, em *emission, s *Subscription) {
defer func() {
if r := recover(); r != nil {
slog.ErrorContext(ctx, "delivering an encounter event to a subscriber panicked", "panic", r)
}
}()
v := s.viewer.Load()
if v == nil {
return // pending
}
if !inAudience(*v, em.c) {
return
}
ev, ok := em.forViewer(*v)
if !ok {
return
}
if s.send(ev) {
// A subscriber that cannot keep up is disconnected, not waited for: it reconnects and
// refetches.
s.overflowed.Store(true)
h.dropped.Add(1)
s.Close()
}
}
func (h *Hub) snapshot(encounterID string) []*Subscription {
h.mu.RLock()
defer h.mu.RUnlock()
out := make([]*Subscription, 0, len(h.sub))
for s := range h.sub {
if s.encounterID == "" || s.encounterID == encounterID {
out = append(out, s)
}
}
return out
}
// inAudience reports whether v may hear of c at all. A session encounter's audience is its
// session's subscribers, taken from the session the encounter belonged to before the write (so a
// release or delete still reaches them); a private encounter's is its owner's.
func inAudience(v data.Viewer, c data.Change) bool {
if v.Level() == data.ViewNone {
return false
}
if c.SessionID != "" {
return v.SessionID() == c.SessionID
}
return v.SessionID() == "" && v.Actor() == c.OwnerID
}
// ids are the ids a change reports, with duplicates removed.
func ids(c data.Change) []string {
out := slices.Clone(c.CombatantID)
slices.Sort(out)
return slices.Compact(out)
}
// ErrShuttingDown means the hub no longer takes streams: the server is stopping.
var ErrShuttingDown = errors.New("stream: the server is shutting down")
// Shutdown ends every open subscription, marked as closed by the server stopping, and makes Open
// hand out subscriptions that are already closed. Call it before the HTTP server's own shutdown,
// which does not wait for upgraded connections.
func (h *Hub) Shutdown() {
h.stopping.Store(true)
h.mu.RLock()
all := make([]*Subscription, 0, len(h.sub))
for s := range h.sub {
all = append(all, s)
}
h.mu.RUnlock()
for _, s := range all {
s.shutdown.Store(true)
s.Close()
}
}
// ShuttingDown reports whether Shutdown has been called.
func (h *Hub) ShuttingDown() bool { return h.stopping.Load() }
// Track marks one stream handler as running until the returned func is called. The HTTP server
// does not wait for hijacked (upgraded) connections, so Drain waits on these instead. Call it
// before any work that can fail and defer the result before the connection's own close.
func (h *Hub) Track() (done func()) {
h.live.Add(1)
var once sync.Once
return func() { once.Do(func() { h.live.Add(-1) }) }
}
// Drain waits until every tracked stream handler has returned (each has sent its close frame and
// closed its connection), or ctx ends.
func (h *Hub) Drain(ctx context.Context) {
t := time.NewTicker(20 * time.Millisecond)
defer t.Stop()
for h.live.Load() > 0 {
select {
case <-ctx.Done():
return
case <-t.C:
}
}
}
package stream
import (
"context"
"log/slog"
"slices"
"sync"
"time"
"github.com/sweetrpg/initiative-api/data"
)
// Preferences says which notice types a user has turned off for a session.
type Preferences interface {
Muted(ctx context.Context, userID, sessionID string) ([]string, error)
}
// Managers lists the user ids of a session's GM and co-GMs.
type Managers interface {
ManagerIDs(ctx context.Context, sessionID string) ([]string, error)
}
// Members says whether a user currently belongs to a session.
type Members interface {
IsMember(ctx context.Context, userID, sessionID string) (bool, error)
}
// SetMembers installs the membership check a user-level stream's deliveries need. Without one a
// user-level stream receives nothing (fail closed).
func (h *Hub) SetMembers(m Members) {
h.mu.Lock()
h.members = m
h.mu.Unlock()
}
// SetPreferences installs the preference store consulted before an addressed event is delivered.
// Without one every addressed event is delivered.
func (h *Hub) SetPreferences(p Preferences) {
h.mu.Lock()
h.prefs = p
h.mu.Unlock()
}
// SetManagers installs the lookup that addresses change-request submissions to the session's GM
// and co-GMs. Without one those submissions notify nobody.
func (h *Hub) SetManagers(m Managers) {
h.mu.Lock()
h.managers = m
h.mu.Unlock()
}
// noticeJob is one notice waiting for the notice worker. resolve, when set, builds the notice (a
// lookup that reads the store) on the worker; local means it came from another pod, so it is
// delivered here and goes no further.
type noticeJob struct {
n data.Notice
resolve func(ctx context.Context) (data.Notice, bool)
local bool
}
const (
noticeQueue = 1024
noticeTimeout = 3 * time.Second // bounds every store read one notice makes
)
// enqueueNotice hands j to the notice worker, started on first use. It never blocks: the
// preference, membership and manager reads a notice needs run on the worker under a timeout, so a
// slow store delays notices only, never a write, a request, or the fan-out tail's evictions. A full
// queue, or a hub that has been closed, drops the notice (counted by Dropped, logged). The send
// happens under the read lock, so Close (which takes the write lock) never races a send that would
// then have no consumer.
func (h *Hub) enqueueNotice(j noticeJob) {
h.noticeOnce.Do(h.startNotices)
h.mu.RLock()
defer h.mu.RUnlock()
if h.noticeClosed || h.noticeQ == nil {
h.dropNotice(j, "the hub is closed")
return
}
h.noticePending.Add(1)
select {
case h.noticeQ <- j:
default:
h.noticePending.Done()
h.dropNotice(j, "the notice queue is full")
}
}
func (h *Hub) dropNotice(j noticeJob, why string) {
h.dropped.Add(1)
slog.Warn("dropping a notification: "+why, "type", j.n.Type, "session", j.n.SessionID)
}
// startNotices starts the worker unless the hub has already been closed, which is final for
// notices.
func (h *Hub) startNotices() {
h.mu.Lock()
if h.noticeClosed {
h.mu.Unlock()
return
}
done := make(chan struct{})
q := make(chan noticeJob, noticeQueue)
h.noticeQ, h.noticeDone = q, done
h.mu.Unlock()
h.noticeWG.Add(1)
go func() {
defer h.noticeWG.Done()
for {
select {
case <-done: // a closed hub wins over a waiting job, so what is still queued is the drain's
h.drainNotices(q)
return
default:
}
select {
case j := <-q:
h.runNotice(j)
h.noticePending.Done()
case <-done:
h.drainNotices(q)
return
}
}
}()
}
// drainNotices discards what is still queued when the hub closes: counted and logged, not silent.
func (h *Hub) drainNotices(q chan noticeJob) {
for {
select {
case j := <-q:
h.dropNotice(j, "the hub closed before it was delivered")
h.noticePending.Done()
default:
return
}
}
}
func (h *Hub) runNotice(j noticeJob) {
ctx, cancel := context.WithTimeout(context.Background(), noticeTimeout)
defer cancel()
defer func() {
if p := recover(); p != nil {
slog.ErrorContext(ctx, "delivering a notification panicked", "panic", p)
}
}()
n := j.n
if j.resolve != nil {
var ok bool
if n, ok = j.resolve(ctx); !ok {
return
}
}
if n.SessionID == "" || len(n.Users) == 0 {
return
}
muted := h.mutedUsers(n) // one read per addressee, shared by every delivery of this notice
isMember := h.memberChecker(n)
h.notifyLocal(n, muted, isMember)
if j.local {
return
}
if r := h.relay(); r != nil {
r.publishNotice(n)
}
h.publishNoticeToBus(n, muted, isMember)
}
// Flush waits until every notice queued so far has been delivered (tests, and shutdown).
func (h *Hub) Flush() { h.noticePending.Wait() }
// stopNotices ends the notice worker for good: later notices are dropped and counted, and
// Flush returns.
func (h *Hub) stopNotices() {
h.mu.Lock()
h.noticeClosed = true
started := h.noticeDone != nil
if started {
close(h.noticeDone) // inside the lock: anyone who sees noticeClosed can rely on done being closed
h.noticeDone = nil
}
h.mu.Unlock()
if started {
h.noticeWG.Wait()
}
}
// Notify implements data.Notifier. It queues the notice; the worker delivers it to each
// addressee's open streams of the notice's session (a per-encounter stream only for that
// encounter), skipping an addressee who muted the type, and relays it to other pods. A stream's
// viewer is fixed when it is granted and ends when membership ends, so only current members of
// the session receive it. It never blocks the caller.
func (h *Hub) Notify(_ context.Context, n data.Notice) {
if n.SessionID == "" || len(n.Users) == 0 {
return
}
h.enqueueNotice(noticeJob{n: n})
}
// notifyLocal delivers n to this pod's streams only, skipping the addressees in muted.
func (h *Hub) notifyLocal(n data.Notice, muted map[string]bool, isMember func(string) bool) {
ev := noticeEvent(n, newEventID())
subs := h.snapshot(n.EncounterID)
done := map[string]bool{}
for _, u := range n.Users {
if u == "" || done[u] || muted[u] {
continue
}
done[u] = true
member := func() bool { return isMember(u) }
for _, s := range subs {
if s.addressedTo(u, n.SessionID, member) && s.send(ev) {
s.overflowed.Store(true)
h.dropped.Add(1)
s.Close()
}
}
}
}
// addressedTo reports whether s may receive a notice for user u in session: a session stream of
// u's in that session, or u's user-level stream when u is still a member (member is lazy).
func (s *Subscription) addressedTo(u, session string, member func() bool) bool {
if s.userLevel {
return s.actor == u && member()
}
v := s.viewer.Load()
return v != nil && v.Actor() == u && v.SessionID() == session
}
// memberChecker returns a membership check for n's session that reads each addressee's membership
// at most once, however many deliveries (streams, bus) ask. It is used by one worker job only.
func (h *Hub) memberChecker(n data.Notice) func(string) bool {
h.mu.RLock()
members := h.members
h.mu.RUnlock()
checks := map[string]func() bool{}
return func(u string) bool {
f, ok := checks[u]
if !ok {
f = h.memberOnce(members, u, n.SessionID)
checks[u] = f
}
return f()
}
}
// memberOnce returns a check of u's membership in session, read at most once per notice and only
// if a user-level stream needs it. A failed read counts as not a member.
func (h *Hub) memberOnce(m Members, u, session string) func() bool {
var once sync.Once
var ok bool
return func() bool {
once.Do(func() {
if m == nil {
return
}
ctx, cancel := context.WithTimeout(context.Background(), muteLookupTimeout)
defer cancel()
var err error
if ok, err = m.IsMember(ctx, u, session); err != nil {
ok = false
slog.WarnContext(ctx, "checking membership for a user-level notice failed; not delivering", "user", u, "error", err)
}
})
return ok
}
}
// muteLookupTimeout bounds each addressee's preference or membership read (a variable so a test
// can shorten it).
var muteLookupTimeout = time.Second
// mutedUsers returns the addressees who turned n's type off for its session, with one preference
// read per distinct addressee, each under its own timeout.
//
// A failed read fails open on purpose: a notification is worth more than a missed mute, and a mute
// only chooses what a client shows. It is never silent: the first failure is logged at WARN with
// how many addressees were left unchecked, and the remaining reads are skipped, so a dead store
// costs one timeout per notice, not one per addressee.
func (h *Hub) mutedUsers(n data.Notice) map[string]bool {
h.mu.RLock()
prefs := h.prefs
h.mu.RUnlock()
if prefs == nil {
return nil
}
muted := map[string]bool{}
seen := map[string]bool{}
for i, u := range n.Users {
if u == "" || seen[u] {
continue
}
seen[u] = true
ctx, cancel := context.WithTimeout(context.Background(), muteLookupTimeout)
list, err := prefs.Muted(ctx, u, n.SessionID)
cancel()
if err != nil {
slog.Warn("reading notification preferences failed; delivering without the mutes of the rest",
"type", n.Type, "session", n.SessionID, "unchecked", len(n.Users)-i, "error", err)
break
}
if slices.Contains(list, n.Type) {
muted[u] = true
}
}
return muted
}
// noticeEvent is the wire form of n. It has no revision or view tag, which belong to the encounter
// state events and would tell a non-GM about edits it cannot see.
func noticeEvent(n data.Notice, id string) Event {
d := n.Data
if d == nil {
d = map[string]any{}
}
return Event{
EventID: id, OccurredAt: n.At.UTC(), Source: Source,
EncounterID: n.EncounterID, SessionID: n.SessionID,
EntityType: "encounter", EntityID: n.EncounterID,
Type: n.Type, Action: actionOf(n.Type),
Origin: Origin{Kind: data.OriginSystem}, Data: d,
}
}
// turnNotices addresses a turn change: the new current combatant's controllers hear turn.yours and
// the next one's hear turn.next. Each carries only the combatant's id and name, which its
// controller always sees.
func turnNotices(c data.Change) []data.Notice {
e := c.After
if e.SessionID == "" || (c.Type != data.EventTurn && c.Type != data.EventStarted) || e.CurrentCombatantID == "" {
return nil
}
var out []data.Notice
add := func(kind, id string) {
cb, ok := combatantOf(e, id)
if !ok || cb.Removed || len(cb.ControllerUserIDs) == 0 {
return
}
out = append(out, data.Notice{
Type: kind, SessionID: e.SessionID, EncounterID: e.ID, Users: slices.Clone(cb.ControllerUserIDs), At: c.At,
Data: map[string]any{"combatant_id": cb.ID, "combatant_name": cb.Name, "round": e.Round},
})
}
add(data.NoticeTurnYours, e.CurrentCombatantID)
if i := slices.Index(e.TurnQueue, e.CurrentCombatantID); i >= 0 && len(e.TurnQueue) > 1 {
add(data.NoticeTurnNext, e.TurnQueue[(i+1)%len(e.TurnQueue)])
}
return out
}
func combatantOf(e data.Encounter, id string) (data.Combatant, bool) {
i := slices.IndexFunc(e.Combatants, func(c data.Combatant) bool { return c.ID == id })
if i < 0 {
return data.Combatant{}, false
}
return e.Combatants[i], true
}
// ChangeSubmitted tells the session's GM and co-GMs a player filed a change request.
func (h *Hub) ChangeSubmitted(_ context.Context, req data.ChangeRequest) {
h.mu.RLock()
m := h.managers
h.mu.RUnlock()
if m == nil {
return
}
h.enqueueNotice(noticeJob{n: data.Notice{Type: data.NoticeChangeSubmitted, SessionID: req.SessionID}, resolve: func(ctx context.Context) (data.Notice, bool) {
ids, err := m.ManagerIDs(ctx, req.SessionID)
if err != nil {
slog.WarnContext(ctx, "finding the session's managers failed; the change request notice was not sent", "session", req.SessionID, "error", err)
return data.Notice{}, false
}
return requestNotice(data.NoticeChangeSubmitted, req, ids, req.CreatedAt), true
}})
}
// ChangeDecided tells the player who filed the request that it was approved or rejected.
func (h *Hub) ChangeDecided(ctx context.Context, req data.ChangeRequest) {
kind := data.NoticeChangeRejected
if req.Status == data.ChangeApproved {
kind = data.NoticeChangeApproved
}
at := req.CreatedAt
if req.DecidedAt != nil {
at = *req.DecidedAt
}
h.Notify(ctx, requestNotice(kind, req, []string{req.RequestedBy}, at))
}
// requestNotice carries the ids of a change request and the decision, never the proposed values.
func requestNotice(kind string, req data.ChangeRequest, users []string, at time.Time) data.Notice {
return data.Notice{
Type: kind, SessionID: req.SessionID, EncounterID: req.EncounterID, Users: users, At: at,
Data: map[string]any{"change_request_id": req.ID, "combatant_id": req.CombatantID},
}
}
package stream
import (
"context"
"errors"
"log/slog"
"sync"
"sync/atomic"
"time"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/store"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
// FanoutCollection is the collection pods share to reach each other's subscribers.
const FanoutCollection = "stream_fanout"
// FanoutTTL is how long a fan-out row is meant to live. The TTL monitor removes expired rows about
// once a minute, so a row can outlive it by up to two minutes in all. A pod that is down longer than
// that misses what it would have relayed; its tail then restarts without a position and ends every
// local stream (see Relay). Changing it makes the index creation conflict with the existing one, so
// startup fails until the index is dropped.
const FanoutTTL = 60 * time.Second
// FanoutIndexes is the TTL index of the fan-out collection.
var FanoutIndexes = []store.IndexSpec{{Name: "at_ttl", Keys: bson.D{{Key: "at", Value: 1}}, ExpireAfter: FanoutTTL}}
const (
kindChange = "change"
kindEvict = "evict"
kindNotice = "notice"
)
// fanoutDoc is one row of the fan-out collection. A change row carries the data.Change the
// encounter collection already holds the content of (the encounter document, as stored); an evict
// row carries only the session and user.
type fanoutDoc struct {
ID primitive.ObjectID `bson:"_id"`
Pod string `bson:"pod"`
Kind string `bson:"kind"`
At time.Time `bson:"at"`
EventID string `bson:"event_id,omitempty"`
Change *data.Change `bson:"change,omitempty"`
Notice *data.Notice `bson:"notice,omitempty"`
Session string `bson:"session_id,omitempty"`
User string `bson:"user_id,omitempty"`
}
// Relay carries committed changes and evictions between pods through a Mongo collection: each
// commit on this pod is inserted, and every pod tails the collection with a change stream and
// delivers what other pods wrote to its own subscribers. Delivery is fail-open: when the stream
// cannot be tailed the pod keeps serving its own subscribers, logs loudly, counts the failure
// (Failures) and reports Degraded.
//
// Revocation is never silent. Evictions have their own queue and writer, so a slow insert of
// changes never delays one; each insert has a timeout and a failed one is retried for up to
// evictWindow, then logged at error level and counted (EvictFailures). The tail resumes from its
// last token after a transient error; only when the server says the history is gone (or the tail
// never had a position) does it restart from now, and then it ends every local subscription
// (GapEvictions), because evictions written in the gap are unknown and each client must reconnect
// and be authorized again. A change row dropped because this pod's remote queue is full ends that
// change's audience here for the same reason. Rows lost on the writing side (a full change queue,
// or an insert that failed through its window) cannot be recovered by the other pods, which learn
// of the gap only from clients refetching. The final bound for anything lost beyond that is each stream's membership re-check
// (server.StreamOptions.RevocationBound, 7s by default), and the stream's maximum age behind it.
type Relay struct {
h *Hub
col store.Collection
pod string
out chan fanoutDoc // changes to insert
evicts chan fanoutDoc // evictions to insert, on their own writer
in chan fanoutDoc // change rows from other pods, rendered off the tail goroutine
done chan struct{}
once sync.Once
ran atomic.Bool
flight sync.WaitGroup // evictions queued or being inserted
wg sync.WaitGroup
failures atomic.Int64 // tail errors, ever
streak atomic.Int64 // tail errors since a row last arrived; only the first logs at error level
dropped atomic.Int64 // changes not relayed or not delivered (queue full or insert failed)
evictFailures atomic.Int64 // evictions that could not be relayed
gapEvictions atomic.Int64 // times the tail restarted without a position and ended every stream
degraded atomic.Bool
tailing atomic.Bool // a change stream is open
}
const (
insertTimeout = 5 * time.Second
changeWindow = 2 * time.Second // retry window for a change row
evictWindow = 30 * time.Second // retry window for an eviction row
relayBackoff = 200 * time.Millisecond
relayMaxWait = 30 * time.Second
drainWait = 2 * time.Second // Stop's wait for queued evictions
)
// AttachRelay makes h relay through col, with pod naming this pod (a row a pod wrote is skipped by
// that pod, so the name must be unique per process). queue bounds the rows waiting to be inserted.
// Run must be called to start tailing; Stop ends both.
func (h *Hub) AttachRelay(col store.Collection, pod string, queue int) *Relay {
q := max(queue, 1)
r := &Relay{h: h, col: col, pod: pod, done: make(chan struct{}),
out: make(chan fanoutDoc, q), evicts: make(chan fanoutDoc, q), in: make(chan fanoutDoc, q)}
h.mu.Lock()
h.rel = r
h.mu.Unlock()
return r
}
func (h *Hub) relay() *Relay {
h.mu.RLock()
defer h.mu.RUnlock()
return h.rel
}
// Failures counts the times tailing failed; Dropped the changes not relayed; EvictFailures the
// evictions not relayed to other pods; GapEvictions the times every local stream was ended after a
// gap in the tail. Degraded reports that the tail is down right now.
func (r *Relay) Failures() int64 { return r.failures.Load() }
func (r *Relay) Dropped() int64 { return r.dropped.Load() }
func (r *Relay) EvictFailures() int64 { return r.evictFailures.Load() }
func (r *Relay) GapEvictions() int64 { return r.gapEvictions.Load() }
func (r *Relay) Degraded() bool { return r.degraded.Load() }
// Tailing reports that the change stream is open, so rows other pods write now will arrive.
func (r *Relay) Tailing() bool { return r.tailing.Load() }
// Run starts the writers, the delivery loop and the tail. It returns at once; Stop ends them.
func (r *Relay) Run(ctx context.Context) {
r.ran.Store(true)
ctx, cancel := context.WithCancel(ctx)
r.wg.Add(1)
go func() { defer r.wg.Done(); <-r.done; cancel() }()
for _, f := range []func(context.Context){r.writeChanges, r.writeEvicts, r.deliverRemote, r.tail} {
r.wg.Add(1)
go func() { defer r.wg.Done(); f(ctx) }()
}
}
// Stop ends the relay's goroutines and waits for them. Evictions still queued get drainWait to be
// inserted first, so a shutdown does not lose a revocation.
func (r *Relay) Stop() {
r.once.Do(func() {
if r.ran.Load() {
// Wait for every eviction queued or mid-insert, bounded by drainWait.
drained := make(chan struct{})
go func() { r.flight.Wait(); close(drained) }()
select {
case <-drained:
case <-time.After(drainWait):
}
}
close(r.done)
})
r.wg.Wait()
}
func (r *Relay) publishChange(c data.Change, eventID string) {
d := fanoutDoc{ID: primitive.NewObjectID(), Pod: r.pod, Kind: kindChange, At: time.Now(), EventID: eventID, Change: &c}
select {
case r.out <- d:
default:
r.dropped.Add(1)
slog.Warn("the fan-out queue is full; other pods miss an encounter event", "encounter", c.After.ID, "type", c.Type)
}
}
// publishNotice carries an addressed event to the other pods, whose streams may hold its
// addressees. Like a change it is dropped, with a log line, when the queue is full.
func (r *Relay) publishNotice(n data.Notice) {
d := fanoutDoc{ID: primitive.NewObjectID(), Pod: r.pod, Kind: kindNotice, At: time.Now(), Notice: &n}
select {
case r.out <- d:
default:
r.dropped.Add(1)
slog.Warn("the fan-out queue is full; other pods miss a notification", "type", n.Type, "session", n.SessionID)
}
}
func (r *Relay) publishEvict(session, user string) {
d := fanoutDoc{ID: primitive.NewObjectID(), Pod: r.pod, Kind: kindEvict, At: time.Now(), Session: session, User: user}
r.flight.Add(1)
select {
case r.evicts <- d:
default:
r.flight.Done()
r.evictFailures.Add(1)
slog.Error("the eviction queue is full; an eviction did not reach other pods, which end the stream on their own timers",
"session", session, "user", user)
}
}
func (r *Relay) writeChanges(ctx context.Context) { r.writeFrom(ctx, r.out, changeWindow, nil) }
func (r *Relay) writeEvicts(ctx context.Context) {
r.writeFrom(ctx, r.evicts, evictWindow, r.flight.Done)
}
func (r *Relay) writeFrom(ctx context.Context, q <-chan fanoutDoc, window time.Duration, done func()) {
for {
select {
case d := <-q:
r.insert(ctx, d, window)
if done != nil {
done()
}
case <-ctx.Done():
return
}
}
}
// insert writes d, each attempt under insertTimeout, retrying with backoff while window lasts. It
// does not sleep after the last attempt.
func (r *Relay) insert(ctx context.Context, d fanoutDoc, window time.Duration) {
start, wait := time.Now(), relayBackoff
var err error
for {
ictx, cancel := context.WithTimeout(ctx, insertTimeout)
err = r.col.InsertOne(ictx, d)
cancel()
if err == nil {
return
}
if ctx.Err() != nil || time.Since(start)+wait > window {
break
}
select {
case <-time.After(wait):
case <-ctx.Done():
}
wait = min(wait*2, 2*time.Second)
}
if d.Kind == kindEvict {
r.evictFailures.Add(1)
slog.Error("an eviction did not reach other pods, which end the stream on their own timers",
"session", d.Session, "user", d.User, "error", err)
return
}
r.dropped.Add(1)
slog.Warn("relaying an encounter event to other pods failed", "type", d.Change.Type, "error", err)
}
// tail follows the collection until ctx ends. After a transient error it resumes from its last
// token. A token the server cannot resume (store.ErrHistoryLost) is dropped, and whenever the tail
// opens without a position after a failure, every local subscription ends (see Relay).
func (r *Relay) tail(ctx context.Context) {
var token bson.Raw
failed := false
wait := time.Second
for ctx.Err() == nil {
cur, err := store.Watch(ctx, r.col, token)
if err != nil {
failed = true
r.fail(ctx, "cannot watch the fan-out collection; this pod delivers local events only", err)
if errors.Is(err, store.ErrHistoryLost) {
token = nil
}
wait = r.sleep(ctx, wait)
continue
}
if token == nil && failed {
n := r.h.evictAll()
r.gapEvictions.Add(1)
slog.ErrorContext(ctx, "the fan-out tail restarted without a position; every stream on this pod was ended", "streams", n)
}
// The position at open, so a failure before the first row still resumes from here.
if t := cur.Token(); t != nil && token == nil {
token = t
}
r.degraded.Store(false)
r.tailing.Store(true)
for cur.Next(ctx) {
wait = time.Second
r.streak.Store(0)
token = cur.Token()
r.handle(ctx, cur.Doc())
}
r.tailing.Store(false)
err = cur.Err()
_ = cur.Close(context.WithoutCancel(ctx))
if ctx.Err() != nil {
return
}
failed = true
if errors.Is(err, store.ErrHistoryLost) {
token = nil
}
r.fail(ctx, "the fan-out change stream ended; resuming", err)
wait = r.sleep(ctx, wait)
}
}
func (r *Relay) fail(ctx context.Context, msg string, err error) {
r.failures.Add(1)
n := r.streak.Add(1)
r.degraded.Store(true)
if n > 1 && ctx.Err() == nil {
slog.WarnContext(ctx, msg, "error", err, "failures", n) // repeated: a standalone server logs once at error level
return
}
slog.ErrorContext(ctx, msg, "error", err, "failures", n)
}
// sleep waits out the backoff and returns the next one.
func (r *Relay) sleep(ctx context.Context, d time.Duration) time.Duration {
select {
case <-time.After(d):
case <-ctx.Done():
}
return min(d*2, relayMaxWait)
}
// handle routes a row from the tail. An eviction is applied here at once; a change row is queued for
// deliverRemote, so rendering never delays the next eviction row.
func (r *Relay) handle(ctx context.Context, raw bson.Raw) {
defer func() {
if p := recover(); p != nil {
slog.ErrorContext(ctx, "handling a fan-out row panicked", "panic", p)
}
}()
var d fanoutDoc
if err := bson.Unmarshal(raw, &d); err != nil {
slog.WarnContext(ctx, "a fan-out row could not be read", "error", err)
return
}
if d.Pod == r.pod {
return
}
switch {
case d.Kind == kindEvict && d.Session == "" && d.User != "":
r.h.evictUserLocal(d.User) // a platform-wide eviction: every stream of that user
case d.Kind == kindEvict && d.Session == "":
slog.WarnContext(ctx, "dropped a fan-out eviction with no session and no user")
case d.Kind == kindEvict:
r.h.evictLocal(d.Session, d.User)
case d.Kind == kindNotice && d.Notice != nil:
r.h.enqueueNotice(noticeJob{n: *d.Notice, local: true}) // preferences are read on the worker, never on the tail
case d.Kind == kindChange && d.Change != nil:
select {
case r.in <- d:
default:
// A view_tag-suppressed stream hides a gap, so the audience must reconnect and refetch.
r.dropped.Add(1)
r.h.evictAudience(*d.Change)
slog.ErrorContext(ctx, "the remote delivery queue is full; the change's audience on this pod was disconnected to refetch")
}
}
}
func (r *Relay) deliverRemote(ctx context.Context) {
for {
select {
case d := <-r.in:
r.deliverOne(ctx, d)
case <-ctx.Done():
return
}
}
}
func (r *Relay) deliverOne(ctx context.Context, d fanoutDoc) {
defer func() {
if p := recover(); p != nil {
slog.ErrorContext(ctx, "delivering a fan-out row panicked", "panic", p)
}
}()
r.h.emitRemote(ctx, *d.Change, d.EventID)
}
package reconcile
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"time"
)
const (
readPage = 100
callTimeout = 10 * time.Second
maxBody = 1 << 20
)
// AuthAPI calls auth-api's internal tuple endpoints with the reconciler's own bearer
// (PADR-0037, PADR-0038). No service token is involved.
type AuthAPI struct {
Base string
Tokens TokenSource
HTTP *http.Client
}
// NewAuthAPI returns a client for base using one fixed token.
func NewAuthAPI(base, token string) *AuthAPI { return NewAuthAPIWithSource(base, StaticToken(token)) }
// NewAuthAPIWithSource returns a client for base that takes its bearer from tokens.
func NewAuthAPIWithSource(base string, tokens TokenSource) *AuthAPI {
return &AuthAPI{Base: base, Tokens: tokens, HTTP: &http.Client{Timeout: callTimeout}}
}
// Read returns every tuple on object, following continuation tokens.
func (a *AuthAPI) Read(ctx context.Context, object string) ([]Tuple, error) {
var all []Tuple
token := ""
for {
q := url.Values{"object": {object}, "page_size": {fmt.Sprint(readPage)}}
if token != "" {
q.Set("continuation_token", token)
}
var page struct {
Tuples []Tuple `json:"tuples"`
Next string `json:"continuation_token"`
}
if err := a.do(ctx, http.MethodGet, "/internal/openfga/tuples?"+q.Encode(), nil, &page); err != nil {
return nil, err
}
all = append(all, page.Tuples...)
if page.Next == "" {
return all, nil
}
token = page.Next
}
}
// Write applies one batch (at most 100 tuples in total) atomically.
func (a *AuthAPI) Write(ctx context.Context, writes, deletes []Tuple) error {
body, err := json.Marshal(map[string][]Tuple{"writes": writes, "deletes": deletes})
if err != nil {
return err
}
return a.do(ctx, http.MethodPost, "/internal/openfga/tuples", body, nil)
}
// do sends one request. A 401 on a cached token refreshes it and retries once. A 401 on a token
// fetched in this run, or a second 401, is ErrTokenRejected and tells the source to stop later runs
// calling Auth0. A 403 is not retried.
func (a *AuthAPI) do(ctx context.Context, method, path string, body []byte, out any) error {
token, err := a.Tokens.Token(ctx)
if err != nil {
return fmt.Errorf("reconciler token: %w", err)
}
status, err := a.send(ctx, method, path, body, token, out)
if status == http.StatusUnauthorized {
fresh, rerr := a.Tokens.Refresh(ctx)
switch {
case errors.Is(rerr, ErrNoRefresh):
return a.rejected(ctx)
case rerr != nil:
return fmt.Errorf("reconciler token: %w", rerr)
}
if status, err = a.send(ctx, method, path, body, fresh, out); status == http.StatusUnauthorized {
return a.rejected(ctx)
}
}
if err == nil {
a.Tokens.Accepted(ctx)
}
return err
}
// rejected records the rejection and returns ErrTokenRejected, noting when the record failed.
func (a *AuthAPI) rejected(ctx context.Context) error {
if err := a.Tokens.Rejected(ctx); err != nil {
return fmt.Errorf("%w (%v)", ErrTokenRejected, err)
}
return ErrTokenRejected
}
// send makes one call and returns the HTTP status (0 when none arrived) with its error.
func (a *AuthAPI) send(ctx context.Context, method, path string, body []byte, token string, out any) (int, error) {
req, err := http.NewRequestWithContext(ctx, method, a.Base+path, bytes.NewReader(body))
if err != nil {
return 0, err
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
resp, err := a.HTTP.Do(req)
if err != nil {
return 0, fmt.Errorf("auth-api %s: %w", path, err)
}
defer func() { _ = resp.Body.Close() }()
switch {
case resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden:
return resp.StatusCode, ErrTokenRejected
case resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent:
return resp.StatusCode, fmt.Errorf("auth-api %s: status %d", path, resp.StatusCode)
case out == nil:
return resp.StatusCode, nil
}
return resp.StatusCode, json.NewDecoder(io.LimitReader(resp.Body, maxBody)).Decode(out)
}
// ListMints returns one page of open mints at least minAge old (by auth-api's clock) after the
// cursor, and the cursor for the next page, empty on the last.
func (a *AuthAPI) ListMints(ctx context.Context, minAge time.Duration, after string) ([]Mint, string, error) {
q := url.Values{"min_age": {minAge.String()}, "limit": {"200"}}
if after != "" {
q.Set("after", after)
}
var page struct {
Mints []Mint `json:"mints"`
Next string `json:"next"`
}
if err := a.do(ctx, http.MethodGet, "/internal/openfga/session-mints?"+q.Encode(), nil, &page); err != nil {
return nil, "", err
}
return page.Mints, page.Next, nil
}
// CloseMint deletes every tuple on the minted session and closes its mint.
func (a *AuthAPI) CloseMint(ctx context.Context, id string) error {
return a.do(ctx, http.MethodPost, "/internal/openfga/session-mints/"+url.PathEscape(id)+"/close", nil, nil)
}
// Package reconcile rebuilds the OpenFGA session tuples from the membership collection, which is
// the source of truth (PADR-0035). It runs as the initiative-reconciler user with the
// openfga-writer role and an operator-minted bearer (PADR-0038). Every pass is idempotent: it
// reads the tuples on each session, then that session's current memberships, diffs them, and
// applies the difference, so a failed pass is finished by the next one. Reading tuples first means
// a grant or revoke that lands between the two reads is, at worst, corrected by the next pass
// (two narrow interleavings remain, accepted by PADR-0040 section 4). After the tuple pass it
// collects session mints that never became sessions (PADR-0040 section 1).
package reconcile
import (
"context"
"errors"
"fmt"
"log/slog"
"regexp"
"sort"
"strings"
"time"
"github.com/sweetrpg/initiative-api/data"
)
const (
scanPage = 500
maxBatch = 100 // auth-api's tuple write limit
userPrefix = "user:"
sessionObj = "session:"
// mintMinAge keeps garbage collection away from sessions still being created; auth-api
// compares it against its own clock.
mintMinAge = 15 * time.Minute
// maxMintPages bounds the garbage-collection paging loop so a cursor that never ends cannot
// hold the job until its deadline.
maxMintPages = 1000
// defaultGCReserve is the end of the pass's time budget kept for garbage collection, so a slow
// tuple pass cannot starve it.
defaultGCReserve = 60 * time.Second
// maxGMLessPerPass is the most GM-less sessions one pass will remove. More than that looks like
// a wrong database or an empty members collection, which would otherwise wipe every session
// older than mintMinAge and its tuples.
maxGMLessPerPass = 10
)
// mintIDPattern is what auth-api mints. Anything else matches no session, which would read as
// "missing" and close a mint that is not ours to judge.
var mintIDPattern = regexp.MustCompile(`^[0-9a-f]{24}$`)
// ErrTokenRejected means auth-api refused the reconciler's bearer (expired, revoked, or missing
// the openfga-writer role). The pass stops at once; an operator must mint a new token.
var ErrTokenRejected = errors.New("reconcile: reconciler token rejected")
// Tuple is one relationship, as auth-api's tuple endpoints carry it.
type Tuple struct {
User string `json:"user"`
Relation string `json:"relation"`
Object string `json:"object"`
}
// Members is the membership source.
type Members interface {
// ScanMembers pages through every membership record, deleted ones included. The pass uses it
// only to learn which sessions exist.
ScanMembers(ctx context.Context, q data.Query) (data.Page[data.Member], error)
// SessionMembers returns one session's membership records, deleted ones included, read fresh.
SessionMembers(ctx context.Context, sessionID string) ([]data.Member, error)
}
// Mint is an open session mint auth-api lists for garbage collection.
type Mint struct {
ID string `json:"id"`
}
// Mints is auth-api's mint surface (openfga-writer): open mints at least minAge old, paged by
// the cursor each page returns, and a close that deletes every tuple on the session.
type Mints interface {
ListMints(ctx context.Context, minAge time.Duration, after string) (mints []Mint, next string, err error)
CloseMint(ctx context.Context, id string) error
}
// Sessions looks sessions up by ID in the sessions collection, soft-deleted ones included.
type Sessions interface {
// LookupSessions maps each found ID to whether it is soft-deleted. A missing ID is absent.
LookupSessions(ctx context.Context, ids []string) (map[string]bool, error)
// SessionsWithGM returns the IDs among ids that have a live GM member record.
SessionsWithGM(ctx context.Context, ids []string) (map[string]bool, error)
// RemoveGMLess soft-deletes a live session that has no GM, and its membership records.
RemoveGMLess(ctx context.Context, sessionID string) error
}
// Tuples is auth-api's internal tuple surface.
type Tuples interface {
// Read returns every tuple on object.
Read(ctx context.Context, object string) ([]Tuple, error)
Write(ctx context.Context, writes, deletes []Tuple) error
}
// Reconciler diffs memberships against tuples.
type Reconciler struct {
Members Members
Tuples Tuples
// Mints and Sessions enable the mint garbage collection; both nil skips it.
Mints Mints
Sessions Sessions
// GCReserve is how much of ctx's deadline the tuple pass leaves for garbage collection; zero
// means 60 seconds. It has no effect when ctx has no deadline.
GCReserve time.Duration
}
// Result counts one pass.
type Result struct {
Sessions, Written, Deleted, Failed int
// MintsClosed counts mints garbage collection closed; MintsSkipped counts those it left for
// the next pass because the sessions lookup failed.
MintsClosed, MintsSkipped int
// GMLessRemoved counts live sessions with no GM that garbage collection soft-deleted.
GMLessRemoved int
// GMLessCapped is set when a pass reached maxGMLessPerPass and left further GM-less sessions.
GMLessCapped bool
}
var roleRelations = map[string]bool{data.RoleGM: true, data.RoleCoGM: true, data.RolePlayer: true, data.RoleObserver: true}
// sessionObjects lists the session objects that have any membership record, live or deleted, so a
// session whose members are all gone is still visited and its tuples removed.
func (r Reconciler) sessionObjects(ctx context.Context) ([]string, error) {
seen := map[string]bool{}
cursor := ""
for {
page, err := r.Members.ScanMembers(ctx, data.Query{Limit: scanPage, Cursor: cursor})
if err != nil {
return nil, fmt.Errorf("scan members: %w", err)
}
for _, m := range page.Items {
seen[m.SessionID] = true
}
if page.NextCursor == "" {
break
}
cursor = page.NextCursor
}
ids := make([]string, 0, len(seen))
for id := range seen {
ids = append(ids, id)
}
sort.Strings(ids)
return ids, nil
}
// wanted is the tuple set one session's live memberships call for.
func wanted(sessionID string, members []data.Member) map[Tuple]bool {
obj := sessionObj + sessionID
out := map[Tuple]bool{}
for _, m := range members {
if m.DeletedAt != nil || !roleRelations[m.Role] {
continue
}
out[Tuple{User: userPrefix + m.UserID, Relation: m.Role, Object: obj}] = true
}
return out
}
// Run does one pass. It returns ErrTokenRejected if auth-api refuses the token; other failures
// are logged per session and counted, and returned together after every session was tried.
func (r Reconciler) Run(ctx context.Context) (Result, error) {
tupleCtx, cancel := r.tuplePassContext(ctx)
defer cancel()
ids, err := r.sessionObjects(tupleCtx)
if err != nil {
return Result{}, err
}
res := Result{Sessions: len(ids)}
for i, id := range ids {
if tupleCtx.Err() != nil {
// The tuple pass's budget is spent: one line and one failure per session left, so the
// job fails and garbage collection (on the full context) still runs.
res.Failed += len(ids) - i
slog.ErrorContext(ctx, "reconcile: tuple pass ran out of time", "done", i, "left", len(ids)-i)
break
}
w, d, err := r.one(tupleCtx, id)
res.Written += w
res.Deleted += d
if errors.Is(err, ErrTokenRejected) {
return res, err
}
if err != nil {
res.Failed++
slog.ErrorContext(ctx, "reconcile session failed", "session", id, "error", err)
}
}
// Garbage collection runs on the whole context, not the tuple pass's shorter one.
if err := r.collect(ctx, &res); err != nil {
return res, err
}
if res.Failed > 0 {
return res, fmt.Errorf("reconcile: %d failures across %d sessions", res.Failed, res.Sessions)
}
return res, nil
}
// tuplePassContext is ctx with its deadline moved earlier by the GC reserve, so the tuple pass
// cannot use the budget garbage collection needs.
func (r Reconciler) tuplePassContext(ctx context.Context) (context.Context, context.CancelFunc) {
deadline, ok := ctx.Deadline()
if !ok {
return context.WithCancel(ctx)
}
reserve := r.GCReserve
if reserve <= 0 {
reserve = defaultGCReserve
}
return context.WithDeadline(ctx, deadline.Add(-reserve))
}
// collect closes mints that never became live sessions: for each open mint at least mintMinAge
// old, one sessions lookup that includes soft-deleted records. A mint is closed only when that
// lookup succeeds and returns no record or a deleted one. A failed lookup skips the whole batch
// until the next pass. It pages to the end, because live sessions stay open and would otherwise
// fill the first page and hide a leaked mint.
func (r Reconciler) collect(ctx context.Context, res *Result) error {
if r.Mints == nil || r.Sessions == nil {
return nil
}
after := ""
for page := 0; ; page++ {
if page >= maxMintPages {
res.Failed++
slog.ErrorContext(ctx, "reconcile: mint paging did not end", "pages", page)
return nil
}
mints, next, err := r.Mints.ListMints(ctx, mintMinAge, after)
if err != nil {
if errors.Is(err, ErrTokenRejected) {
return err
}
res.Failed++
slog.ErrorContext(ctx, "reconcile: listing session mints failed", "error", err)
return nil
}
if err := r.closeOrphans(ctx, mints, res); err != nil {
return err
}
if next == "" {
return nil
}
if next == after {
res.Failed++
slog.ErrorContext(ctx, "reconcile: auth-api returned the same mint cursor twice", "cursor", next)
return nil
}
after = next
}
}
func (r Reconciler) closeOrphans(ctx context.Context, mints []Mint, res *Result) error {
if len(mints) == 0 {
return nil
}
ids := make([]string, 0, len(mints))
for _, m := range mints {
if !mintIDPattern.MatchString(m.ID) {
res.MintsSkipped++
slog.ErrorContext(ctx, "reconcile: ignoring a mint with a malformed id", "mint", m.ID)
continue
}
ids = append(ids, m.ID)
}
if len(ids) == 0 {
return nil
}
found, err := r.Sessions.LookupSessions(ctx, ids)
if err != nil {
// Counted as a failure too: a Mongo outage that persists must fail the job so the stall
// alert fires, not exit 0 with the mints left open.
res.MintsSkipped += len(ids)
res.Failed++
slog.ErrorContext(ctx, "reconcile: sessions lookup failed; leaving this batch of mints for the next pass", "mints", len(ids), "error", err)
return nil
}
gmless := r.gmLess(ctx, ids, found, res)
for _, id := range ids {
if deleted, exists := found[id]; exists && !deleted {
if !gmless[id] {
continue // a live session with its GM
}
if res.GMLessRemoved >= maxGMLessPerPass {
if !res.GMLessCapped {
res.GMLessCapped = true
res.Failed++
slog.ErrorContext(ctx, "reconcile: reached the cap of sessions with no GM removed in one pass; leaving the rest", "cap", maxGMLessPerPass)
}
continue
}
err := r.Sessions.RemoveGMLess(ctx, id)
if errors.Is(err, data.ErrConflict) {
slog.InfoContext(ctx, "reconcile: session has a GM or is too new to remove; leaving it", "session", id)
continue
}
if err != nil {
res.Failed++
slog.ErrorContext(ctx, "reconcile: removing a session with no GM failed", "session", id, "error", err)
continue
}
res.GMLessRemoved++
slog.InfoContext(ctx, "reconcile: removed a live session that has no GM", "session", id)
}
if err := r.Mints.CloseMint(ctx, id); err != nil {
if errors.Is(err, ErrTokenRejected) {
return err
}
res.Failed++
slog.ErrorContext(ctx, "reconcile: closing a mint failed", "mint", id, "error", err)
continue
}
res.MintsClosed++
slog.InfoContext(ctx, "reconcile: closed a mint with no live session", "mint", id)
}
return nil
}
// gmLess returns which of the live sessions among ids have no live GM record, using one query. A
// failed query counts as a failure and returns nothing, so no session is removed on a guess.
func (r Reconciler) gmLess(ctx context.Context, ids []string, found map[string]bool, res *Result) map[string]bool {
var live []string
for _, id := range ids {
if deleted, exists := found[id]; exists && !deleted {
live = append(live, id)
}
}
if len(live) == 0 {
return nil
}
withGM, err := r.Sessions.SessionsWithGM(ctx, live)
if err != nil {
res.Failed++
slog.ErrorContext(ctx, "reconcile: GM lookup failed; leaving live sessions alone", "sessions", len(live), "error", err)
return nil
}
out := map[string]bool{}
for _, id := range live {
if !withGM[id] {
out[id] = true
}
}
return out
}
// one reconciles a single session and returns how many tuples it wrote and deleted. It reads the
// tuples first and the session's members second.
func (r Reconciler) one(ctx context.Context, sessionID string) (written, deleted int, err error) {
obj := sessionObj + sessionID
have, err := r.Tuples.Read(ctx, obj)
if err != nil {
return 0, 0, err
}
members, err := r.Members.SessionMembers(ctx, sessionID)
if err != nil {
return 0, 0, fmt.Errorf("read members: %w", err)
}
want := wanted(sessionID, members)
haveSet := map[Tuple]bool{}
var dels []Tuple
for _, t := range have {
if !roleRelations[t.Relation] || !strings.HasPrefix(t.User, userPrefix) {
continue // not a tuple this job owns
}
haveSet[t] = true
if !want[t] {
dels = append(dels, t)
}
}
var adds []Tuple
for t := range want {
if !haveSet[t] {
adds = append(adds, t)
}
}
sortTuples(adds)
sortTuples(dels)
for _, t := range adds {
slog.InfoContext(ctx, "reconcile: writing missing tuple", "user", t.User, "relation", t.Relation, "object", t.Object)
}
for _, t := range dels {
slog.InfoContext(ctx, "reconcile: deleting extra tuple", "user", t.User, "relation", t.Relation, "object", t.Object)
}
// Deletes go first so a role change (old tuple out, new in) never leaves two roles at once.
for len(dels) > 0 || len(adds) > 0 {
var bd, ba []Tuple
bd, dels = take(dels, maxBatch)
ba, adds = take(adds, maxBatch-len(bd))
if err := r.Tuples.Write(ctx, ba, bd); err != nil {
return written, deleted, err
}
written += len(ba)
deleted += len(bd)
}
return written, deleted, nil
}
func take(ts []Tuple, n int) (head, rest []Tuple) {
if n > len(ts) {
n = len(ts)
}
return ts[:n], ts[n:]
}
func sortTuples(ts []Tuple) {
sort.Slice(ts, func(i, j int) bool {
a, b := ts[i], ts[j]
return a.Object+a.Relation+a.User < b.Object+b.Relation+b.User
})
}
package reconcile
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"strconv"
"strings"
"syscall"
"time"
"github.com/gomodule/redigo/redis"
)
const (
// tokenCacheKey holds the cached Auth0 access token (PADR-0041).
tokenCacheKey = "reconciler:token"
// tokenSkew is how long before expiry a token stops being served from the cache.
tokenSkew = 120 * time.Second
// rejectedKey marks that auth-api rejected a freshly fetched token. While it exists no run
// calls Auth0, so a persistent 401 (role removed, broken login mapping, wrong audience) cannot
// spend the monthly token allowance. Delete it to retry sooner.
rejectedKey = "reconciler:rejected"
rejectedTTL = time.Hour
// fetchGuardKey is set (NX, 60s) before every Auth0 call. A Redis that cannot take writes then
// stops the run before Auth0 is called, and a working one limits fetches to one a minute, so a
// cache that silently fails to store cannot cost a token per run.
fetchGuardKey = "reconciler:fetch-guard"
fetchGuardTTL = 60 * time.Second
// auth0FailuresKey counts consecutive failed token fetches (TTL 2h, reset on success) and
// auth0BackoffKey blocks fetching while it exists, for 5m * 2^(failures-1) capped at 1h. After it
// expires the next fetch is the probe: success clears both keys, failure re-arms the backoff.
// A cached token is still served during backoff; only Auth0 calls stop.
auth0FailuresKey = "reconciler:auth0-failures"
auth0BackoffKey = "reconciler:auth0-backoff"
failuresTTL = 2 * time.Hour
backoffBase = 5 * time.Minute
backoffMax = time.Hour
// maxLifetime caps a lifetime Auth0 reports, so a bad value cannot cache a token for years.
maxLifetime = 30 * 24 * time.Hour
)
// TokenSource supplies the bearer the reconciler sends to auth-api.
type TokenSource interface {
// Token returns a usable access token.
Token(ctx context.Context) (string, error)
// Refresh discards the current token after auth-api answered 401 and returns a new one. It
// returns ErrNoRefresh when a replacement cannot help, such as a token fetched this run.
Refresh(ctx context.Context) (string, error)
// Rejected records that auth-api rejected a token fetched this run, so later runs stop. It
// returns an error when the record could not be written.
Rejected(ctx context.Context) error
// Accepted records that auth-api accepted the token, ending any earlier rejection.
Accepted(ctx context.Context)
}
// ErrAuth0Backoff is returned while earlier token fetches failed and the backoff has not expired.
// It is not a token rejection: the run fails with exit 1 and Auth0 is not called.
var ErrAuth0Backoff = errors.New("reconcile: Auth0 token fetch is backing off after earlier failures")
// ErrNoRefresh is returned by a source that cannot replace a rejected token.
var ErrNoRefresh = errors.New("reconcile: token cannot be refreshed")
// StaticToken is a TokenSource for one fixed token.
type StaticToken string
// Token returns the fixed token.
func (s StaticToken) Token(context.Context) (string, error) { return string(s), nil }
// Refresh always fails: a fixed token has no replacement.
func (s StaticToken) Refresh(context.Context) (string, error) { return "", ErrNoRefresh }
// Rejected does nothing for a fixed token.
func (s StaticToken) Rejected(context.Context) error { return nil }
// Accepted does nothing for a fixed token.
func (s StaticToken) Accepted(context.Context) {}
// ClientCredentials fetches an Auth0 machine-to-machine access token with the client-credentials
// grant and caches it in Redis until 120 seconds before it expires, so a job that runs every five
// minutes uses about 30 Auth0 tokens a month instead of 8,640 (PADR-0041). The secret is never
// logged or put in an error.
type ClientCredentials struct {
TokenURL, ClientID, ClientSecret, Audience string
Pool *redis.Pool
HTTP *http.Client
token string // this run's token, so one run reads Redis once
err error // sticky: one failed fetch fails the rest of the run without hitting Auth0 again
fetched bool // the token came from Auth0 in this run, so a 401 on it is final
accepted bool // the rejection marker was already cleared this run
}
// NewClientCredentials returns a source that caches in pool.
func NewClientCredentials(tokenURL, clientID, clientSecret, audience string, pool *redis.Pool) *ClientCredentials {
return &ClientCredentials{TokenURL: tokenURL, ClientID: clientID, ClientSecret: clientSecret, Audience: audience,
Pool: pool, HTTP: &http.Client{
Timeout: callTimeout,
// A redirect would re-send the POST body, client secret included, to wherever it points.
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}}
}
// Token returns the cached token, or fetches and caches a new one.
func (c *ClientCredentials) Token(ctx context.Context) (string, error) {
if c.err != nil {
return "", c.err
}
if c.token != "" {
return c.token, nil
}
tok, err := c.rejectionOrCached()
if err == nil && tok == "" {
tok, err = c.fetchAndStore(ctx)
}
return c.remember(tok, err)
}
// rejectionOrCached fails with ErrTokenRejected while the rejection marker exists, and otherwise
// returns the cached token ("" when there is none).
func (c *ClientCredentials) rejectionOrCached() (string, error) {
conn := c.Pool.Get()
defer func() { _ = conn.Close() }()
marked, err := redis.Bool(conn.Do("EXISTS", rejectedKey))
if err != nil {
return "", fmt.Errorf("read rejection marker: %w", err)
}
if marked {
return "", fmt.Errorf("auth-api rejected the last fresh token, not calling Auth0 until %s expires: %w", rejectedKey, ErrTokenRejected)
}
return c.cached()
}
// Refresh clears the cached token and fetches a new one.
func (c *ClientCredentials) Refresh(ctx context.Context) (string, error) {
if c.fetched {
return "", ErrNoRefresh // a token fetched this run was rejected; another would be too
}
// While Auth0 is backing off no replacement can be fetched, so keep the cached token and set no
// rejection marker: the run fails with exit 1 and the next one reuses the cache.
if err := c.checkBackoff(ctx); err != nil {
return c.remember("", err)
}
c.token, c.err = "", nil
conn := c.Pool.Get()
defer func() { _ = conn.Close() }()
if _, err := conn.Do("DEL", tokenCacheKey); err != nil {
return c.remember("", fmt.Errorf("clear cached token: %w", err))
}
tok, err := c.fetchAndStore(ctx)
return c.remember(tok, err)
}
// Rejected clears the bad cached token and sets the rejection marker, so no run calls Auth0 for an
// hour. The fetch guard still limits Auth0 calls to one a minute if the marker cannot be written.
func (c *ClientCredentials) Rejected(context.Context) error {
conn := c.Pool.Get()
defer func() { _ = conn.Close() }()
_ = conn.Send("DEL", tokenCacheKey)
if _, err := conn.Do("SET", rejectedKey, "1", "EX", int64(rejectedTTL/time.Second)); err != nil {
return fmt.Errorf("record token rejection: %w", err)
}
return nil
}
// Accepted deletes the rejection marker once per run.
func (c *ClientCredentials) Accepted(ctx context.Context) {
if c.accepted {
return
}
c.accepted = true
conn := c.Pool.Get()
defer func() { _ = conn.Close() }()
if _, err := conn.Do("DEL", rejectedKey); err != nil {
slog.ErrorContext(ctx, "reconcile: could not clear the token rejection marker", "error", err)
}
}
func (c *ClientCredentials) remember(tok string, err error) (string, error) {
if err != nil {
c.err = err
return "", err
}
c.token = tok
return tok, nil
}
// cached returns the token in Redis, or "" when there is none. Its TTL ends tokenSkew before the
// token does, so a hit is always usable.
func (c *ClientCredentials) cached() (string, error) {
conn := c.Pool.Get()
defer func() { _ = conn.Close() }()
tok, err := redis.String(conn.Do("GET", tokenCacheKey))
if errors.Is(err, redis.ErrNil) {
return "", nil
}
if err != nil {
return "", fmt.Errorf("read cached token: %w", err)
}
return tok, nil
}
func (c *ClientCredentials) fetchAndStore(ctx context.Context) (string, error) {
if err := c.checkBackoff(ctx); err != nil {
return "", err
}
if err := c.takeFetchGuard(); err != nil {
return "", err
}
tok, lifetime, err := c.fetch(ctx)
if err != nil {
return "", c.recordFailure(ctx, err)
}
c.fetched = true
defer c.clearFailures(ctx)
ttl := lifetime - tokenSkew
if ttl < time.Second {
return tok, nil // too short to cache; the next run fetches again
}
conn := c.Pool.Get()
defer func() { _ = conn.Close() }()
if _, err := conn.Do("SET", tokenCacheKey, tok, "EX", int64(ttl/time.Second)); err != nil {
return "", fmt.Errorf("cache token: %w", err)
}
return tok, nil
}
// checkBackoff fails without calling Auth0 while the backoff key exists.
func (c *ClientCredentials) checkBackoff(ctx context.Context) error {
conn := c.Pool.Get()
defer func() { _ = conn.Close() }()
left, err := redis.Int64(conn.Do("PTTL", auth0BackoffKey))
if err != nil {
return fmt.Errorf("read auth0 backoff: %w", err)
}
if left == -2 { // no key
return nil
}
if left == -1 { // a key without expiry was set by hand; fail closed rather than guess
slog.WarnContext(ctx, "reconcile: Auth0 backoff key has no expiry; not calling Auth0 until it is deleted")
return fmt.Errorf("%w (key %s has no expiry; delete it)", ErrAuth0Backoff, auth0BackoffKey)
}
remaining := (time.Duration(left) * time.Millisecond).Round(time.Second)
slog.WarnContext(ctx, "reconcile: Auth0 token fetch is backing off; not calling Auth0", "remaining", remaining.String())
return fmt.Errorf("%w (retry in %v)", ErrAuth0Backoff, remaining)
}
// recordFailure counts a failed fetch and arms the backoff: 5m, 10m, 20m, 40m, then 1h, or Auth0's
// Retry-After when that is longer (capped at 1h). It returns the fetch error, joined with the Redis
// error when the backoff could not be written. A Redis that cannot take this write could not take
// the fetch guard's either, so the run would already have stopped before calling Auth0; the error
// is still returned so a failure here is never silent.
func (c *ClientCredentials) recordFailure(ctx context.Context, fetchErr error) error {
if ctx.Err() != nil {
return fetchErr // a run timeout or SIGTERM is not Auth0's fault
}
var retryAfter time.Duration
var fe *fetchError
if errors.As(fetchErr, &fe) {
retryAfter = fe.retryAfter
}
conn := c.Pool.Get()
defer func() { _ = conn.Close() }()
reply, err := redis.Int64s(recordFailureScript.Do(conn, auth0FailuresKey, auth0BackoffKey,
int64(failuresTTL/time.Second), int64(backoffBase/time.Second), int64(backoffMax/time.Second), int64(retryAfter/time.Second)))
if err != nil || len(reply) != 2 {
return errors.Join(fetchErr, fmt.Errorf("arm auth0 backoff: %v", err))
}
slog.WarnContext(ctx, "reconcile: Auth0 token fetch failed; backing off", "failures", reply[0], "wait", (time.Duration(reply[1]) * time.Second).String())
return fetchErr
}
// recordFailureScript counts a failure and arms the backoff in one atomic step, so a failure
// between two commands cannot leave a count with no TTL or a count with no backoff. KEYS: failures,
// backoff. ARGV: failures TTL, base, max, Retry-After (seconds). Returns {count, wait seconds}.
var recordFailureScript = redis.NewScript(2, `
local n = redis.call('INCR', KEYS[1])
redis.call('EXPIRE', KEYS[1], tonumber(ARGV[1]))
local wait = tonumber(ARGV[2]) * 2 ^ math.min(n - 1, 10)
local retry = tonumber(ARGV[4])
if retry > wait then wait = retry end
wait = math.floor(math.min(wait, tonumber(ARGV[3])))
redis.call('SET', KEYS[2], '1', 'EX', wait)
return {n, wait}
`)
// clearFailures ends the backoff after a successful fetch. A failure here only leaves keys that
// expire on their own, so it is logged, not returned.
func (c *ClientCredentials) clearFailures(ctx context.Context) {
conn := c.Pool.Get()
defer func() { _ = conn.Close() }()
if _, err := conn.Do("DEL", auth0BackoffKey, auth0FailuresKey); err != nil {
slog.ErrorContext(ctx, "reconcile: could not clear the Auth0 backoff keys", "error", err)
}
}
// fetchError is a failed token request. retryAfter is Auth0's Retry-After in seconds, when sent on
// a 429.
type fetchError struct {
msg string
retryAfter time.Duration
}
func (e *fetchError) Error() string { return e.msg }
// takeFetchGuard claims the right to call Auth0. It fails when Redis cannot take the write or
// another fetch happened in the last minute, in both cases before any Auth0 call.
func (c *ClientCredentials) takeFetchGuard() error {
conn := c.Pool.Get()
defer func() { _ = conn.Close() }()
reply, err := redis.String(conn.Do("SET", fetchGuardKey, "1", "NX", "EX", int64(fetchGuardTTL/time.Second)))
if errors.Is(err, redis.ErrNil) {
return fmt.Errorf("a token was fetched in the last %v; not calling Auth0 again", fetchGuardTTL)
}
if err != nil || reply != "OK" {
return fmt.Errorf("fetch guard: redis cannot take writes, not calling Auth0: %v", err)
}
return nil
}
// fetch requests a token from Auth0. Errors carry the status, never the response body or secret.
func (c *ClientCredentials) fetch(ctx context.Context) (string, time.Duration, error) {
body, err := json.Marshal(map[string]string{
"grant_type": "client_credentials", "client_id": c.ClientID, "client_secret": c.ClientSecret, "audience": c.Audience,
})
if err != nil {
return "", 0, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.TokenURL, bytes.NewReader(body))
if err != nil {
return "", 0, errors.New("build token request")
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.HTTP.Do(req)
if err != nil {
// Only the failure class: the URL error text could echo the request.
return "", 0, &fetchError{msg: fmt.Sprintf("token endpoint unreachable (%s)", failureClass(err))}
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
fe := &fetchError{msg: fmt.Sprintf("token endpoint returned status %d", resp.StatusCode)}
if resp.StatusCode == http.StatusTooManyRequests {
fe.retryAfter = parseRetryAfter(resp.Header.Get("Retry-After"))
}
return "", 0, fe
}
var out struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int64 `json:"expires_in"`
}
if err := json.NewDecoder(io.LimitReader(resp.Body, maxBody)).Decode(&out); err != nil || strings.TrimSpace(out.AccessToken) == "" || !strings.EqualFold(out.TokenType, "Bearer") {
return "", 0, &fetchError{msg: "token endpoint returned no bearer access token"}
}
if out.ExpiresIn <= 0 {
return "", 0, &fetchError{msg: "token endpoint returned no token lifetime"}
}
return out.AccessToken, time.Duration(min(out.ExpiresIn, int64(maxLifetime/time.Second))) * time.Second, nil
}
// parseRetryAfter reads a Retry-After given in seconds, capped at the backoff maximum. A number
// too large for int64 is the cap; anything else (a date, a negative, text) is no hint.
func parseRetryAfter(v string) time.Duration {
secs, err := strconv.ParseInt(strings.TrimSpace(v), 10, 64)
switch {
case errors.Is(err, strconv.ErrRange) && !strings.HasPrefix(strings.TrimSpace(v), "-"):
return backoffMax
case err != nil || secs <= 0:
return 0
}
return time.Duration(min(secs, int64(backoffMax/time.Second))) * time.Second
}
// failureClass names why a request failed without quoting the error, which can carry the URL.
func failureClass(err error) string {
var netErr net.Error
var dns *net.DNSError
var cert *tls.CertificateVerificationError
switch {
case errors.As(err, &cert):
return "tls certificate"
case errors.As(err, &dns):
return "dns"
case errors.Is(err, syscall.ECONNREFUSED):
return "connection refused"
case errors.As(err, &netErr) && netErr.Timeout():
return "timeout"
default:
return "network"
}
}
// Package relations is the client for auth-api's POST /authz/check-relation (PADR-0035).
//
// The caller's own bearer token is forwarded on every call (PADR-0037, no service tokens), so a
// check only answers for the user holding that token. Only positive decisions are cached, for a
// few seconds, so a removal takes effect within positiveTTL and a new grant at once. Any failure
// to get a decision is an error: session data fails closed (503), never open.
package relations
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"sync"
"time"
)
const (
// positiveTTL bounds how long a removal can go unnoticed on a cached allow.
positiveTTL = 5 * time.Second
// maxEntries bounds the cache; past it, expired entries go first, then everything.
maxEntries = 10000
callTimeout = 3 * time.Second
maxBody = 4 << 10
)
var (
// ErrUnavailable means auth-api or OpenFGA could not give a decision. Callers answer 503.
ErrUnavailable = errors.New("relations: authorization unavailable")
// ErrUnauthorized means auth-api rejected the user's token. Callers answer 401.
ErrUnauthorized = errors.New("relations: token rejected")
// ErrDenied means auth-api refused the change: the caller lacks the relation, or is denied
// the service. Callers answer 403.
ErrDenied = errors.New("relations: not permitted")
// ErrLimited means auth-api's mint or tuple limits stopped the call. Callers answer 429.
ErrLimited = errors.New("relations: rate limited")
// ErrConflict means auth-api refused the change as conflicting (the session's tuple cap).
// Callers answer 409.
ErrConflict = errors.New("relations: conflict")
// ErrRejected means auth-api answered 400: this service sent a malformed request, so retrying
// the same call never helps. Callers answer 500.
ErrRejected = errors.New("relations: request rejected as malformed")
)
// Client calls auth-api. The zero value is not usable; use New.
type Client struct {
base string
http *http.Client
now func() time.Time
mu sync.Mutex
cache map[string]time.Time // key -> expiry of a cached allow
}
// New returns a Client for the auth-api base URL.
func New(baseURL string) *Client {
return &Client{base: baseURL, http: &http.Client{Timeout: callTimeout}, now: time.Now, cache: map[string]time.Time{}}
}
// Check reports whether the holder of token has relation on object (for example
// "session:abc", "can_view"). user is the verified caller ID and only keys the cache; auth-api
// decides from the token. A deny is (false, nil).
func (c *Client) Check(ctx context.Context, user, token, object, relation string) (bool, error) {
if user == "" || token == "" || object == "" || relation == "" {
return false, fmt.Errorf("relations: user, token, object and relation are required")
}
key := user + "\x00" + object + "\x00" + relation
if c.allowed(key) {
return true, nil
}
ok, err := c.fetch(ctx, token, object, relation)
if err != nil {
return false, err
}
if ok {
c.remember(key)
}
return ok, nil
}
func (c *Client) fetch(ctx context.Context, token, object, relation string) (bool, error) {
payload, err := json.Marshal(map[string]string{"object": object, "relation": relation})
if err != nil {
return false, fmt.Errorf("relations: encode request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.base+"/authz/check-relation", bytes.NewReader(payload))
if err != nil {
return false, fmt.Errorf("relations: build request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
resp, err := c.http.Do(req)
if err != nil {
slog.WarnContext(ctx, "check-relation call failed", "error", err)
return false, ErrUnavailable
}
defer func() { _ = resp.Body.Close() }()
switch resp.StatusCode {
case http.StatusOK:
var body struct {
Allowed bool `json:"allowed"`
}
if err := json.NewDecoder(io.LimitReader(resp.Body, maxBody)).Decode(&body); err != nil {
return false, ErrUnavailable
}
return body.Allowed, nil
case http.StatusUnauthorized:
return false, ErrUnauthorized
default:
slog.WarnContext(ctx, "check-relation rejected", "status", resp.StatusCode)
return false, ErrUnavailable
}
}
func (c *Client) allowed(key string) bool {
c.mu.Lock()
defer c.mu.Unlock()
exp, ok := c.cache[key]
return ok && c.now().Before(exp)
}
func (c *Client) remember(key string) {
c.mu.Lock()
defer c.mu.Unlock()
if len(c.cache) >= maxEntries {
now := c.now()
for k, exp := range c.cache {
if !now.Before(exp) {
delete(c.cache, k)
}
}
if len(c.cache) >= maxEntries {
c.cache = map[string]time.Time{}
}
}
c.cache[key] = c.now().Add(positiveTTL)
}
// Tuple is one membership relation, written for the session object the call names.
type Tuple struct {
User string `json:"user"` // "user:<canonical id>"
Relation string `json:"relation"`
}
// Mint asks auth-api for a new session ID and writes the caller's gm tuple on it. The ID comes
// from auth-api, never from the client (PADR-0040).
func (c *Client) Mint(ctx context.Context, token string) (string, error) {
var out struct {
SessionID string `json:"session_id"`
}
if err := c.call(ctx, http.MethodPost, "/authz/sessions", token, nil, http.StatusCreated, &out); err != nil {
return "", err
}
if out.SessionID == "" {
return "", ErrUnavailable
}
return out.SessionID, nil
}
// EndSession deletes every tuple on the session and closes its mint. Only the GM may.
func (c *Client) EndSession(ctx context.Context, token, sessionID string) error {
return c.call(ctx, http.MethodDelete, "/authz/sessions/"+sessionID, token, nil, http.StatusNoContent, nil)
}
// WriteTuples applies membership tuple changes on one session in a single atomic write. Writing a
// tuple that exists and deleting one that does not are no-ops, so a retry is safe.
func (c *Client) WriteTuples(ctx context.Context, token, sessionID string, writes, deletes []Tuple) error {
body := struct {
SessionID string `json:"session_id"`
Writes []Tuple `json:"writes"`
Deletes []Tuple `json:"deletes"`
}{sessionID, writes, deletes}
if body.Writes == nil {
body.Writes = []Tuple{}
}
if body.Deletes == nil {
body.Deletes = []Tuple{}
}
return c.call(ctx, http.MethodPost, "/authz/session-tuples", token, body, http.StatusOK, nil)
}
// call sends one authenticated request and maps the answer: 401 is ErrUnauthorized, 403 ErrDenied,
// 429 ErrLimited, anything else but want (or an unreadable body) ErrUnavailable.
func (c *Client) call(ctx context.Context, method, path, token string, body any, want int, out any) error {
if token == "" {
return ErrUnauthorized
}
var rdr io.Reader
if body != nil {
payload, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("relations: encode request: %w", err)
}
rdr = bytes.NewReader(payload)
}
req, err := http.NewRequestWithContext(ctx, method, c.base+path, rdr)
if err != nil {
return fmt.Errorf("relations: build request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
resp, err := c.http.Do(req)
if err != nil {
slog.WarnContext(ctx, "auth-api call failed", "path", path, "error", err)
return ErrUnavailable
}
defer func() { _ = resp.Body.Close() }()
switch resp.StatusCode {
case want:
if out == nil {
return nil
}
if err := json.NewDecoder(io.LimitReader(resp.Body, maxBody)).Decode(out); err != nil {
return ErrUnavailable
}
return nil
case http.StatusUnauthorized:
return ErrUnauthorized
case http.StatusForbidden:
return ErrDenied
case http.StatusTooManyRequests:
return ErrLimited
case http.StatusConflict:
return ErrConflict
case http.StatusBadRequest:
slog.ErrorContext(ctx, "auth-api rejected a session call as malformed", "path", path)
return ErrRejected
}
slog.WarnContext(ctx, "auth-api rejected a session call", "path", path, "status", resp.StatusCode)
return ErrUnavailable
}
// Package seed loads the versioned game-system definitions checked into this repo. Loading is
// idempotent: unchanged definitions are skipped and keep their identifiers.
package seed
import (
"context"
"embed"
"encoding/json"
"fmt"
"github.com/sweetrpg/initiative-api/data"
)
//go:embed systems/families.json systems/systems.json
var files embed.FS
// Upserter is the part of data.SystemRepo the loader needs.
type Upserter interface {
Upsert(ctx context.Context, sys data.GameSystem) (data.Outcome, error)
}
// Result counts what a load did.
type Result struct{ Created, Updated, Unchanged int }
type systemFile struct {
ID string `json:"id"`
Name string `json:"name"`
Family string `json:"family"`
Aliases []string `json:"aliases"`
Gated bool `json:"gated"`
Fields []data.TrackerField `json:"fields"` // optional override of the family's fields
}
// Definitions parses the seed files and expands each system's tracker fields from its family
// (a system may carry its own fields instead). Every result passes data.ValidateSystem.
func Definitions() ([]data.GameSystem, error) {
var families map[string][]data.TrackerField
if err := readJSON("systems/families.json", &families); err != nil {
return nil, err
}
var systems []systemFile
if err := readJSON("systems/systems.json", &systems); err != nil {
return nil, err
}
return expand(families, systems)
}
// expand builds and validates the systems, and checks identifiers across the whole set: IDs are
// unique, and no alias repeats another alias or equals any system's ID (an alias lookup must
// never be ambiguous with an ID lookup).
func expand(families map[string][]data.TrackerField, systems []systemFile) ([]data.GameSystem, error) {
out := make([]data.GameSystem, 0, len(systems))
for _, s := range systems {
fields := s.Fields
if len(fields) == 0 {
var ok bool
if fields, ok = families[s.Family]; !ok {
return nil, fmt.Errorf("seed: system %q uses unknown family %q", s.ID, s.Family)
}
}
aliases := s.Aliases
if aliases == nil {
aliases = []string{}
}
sys := data.GameSystem{ID: s.ID, Name: s.Name, Family: s.Family, Aliases: aliases, Gated: s.Gated, Fields: fields}
if err := data.ValidateSystem(sys); err != nil {
return nil, err
}
out = append(out, sys)
}
return out, checkIdentifiers(out)
}
func checkIdentifiers(systems []data.GameSystem) error {
owner := map[string]string{} // identifier -> system that claims it
for _, s := range systems {
if prev, dup := owner[s.ID]; dup {
return fmt.Errorf("seed: id %q used by both %q and %q", s.ID, prev, s.ID)
}
owner[s.ID] = s.ID
}
for _, s := range systems {
for _, a := range s.Aliases {
if prev, dup := owner[a]; dup {
return fmt.Errorf("seed: alias %q of %q collides with %q", a, s.ID, prev)
}
owner[a] = s.ID
}
}
return nil
}
func readJSON(name string, v any) error {
b, err := files.ReadFile(name)
if err != nil {
return err
}
if err := json.Unmarshal(b, v); err != nil {
return fmt.Errorf("seed: parse %s: %w", name, err)
}
return nil
}
// Load upserts every seeded definition and reports the outcomes. It stops at the first error.
func Load(ctx context.Context, repo Upserter) (Result, error) {
defs, err := Definitions()
if err != nil {
return Result{}, err
}
var r Result
for _, d := range defs {
o, err := repo.Upsert(ctx, d)
if err != nil {
return r, fmt.Errorf("seed: %s: %w", d.ID, err)
}
switch o {
case data.Created:
r.Created++
case data.Updated:
r.Updated++
default:
r.Unchanged++
}
}
return r, nil
}
package server
import (
"cmp"
"encoding/json"
"errors"
"io"
"net/http"
"regexp"
"slices"
"github.com/gin-gonic/gin"
)
// maxBodyBytes bounds a request body on the resource routes: 256 KiB, far above a roster or an
// encounter with the most combatants and conditions the data layer allows, and far below what a
// hostile client could use to pin memory.
const maxBodyBytes = 256 << 10
// limitBody caps the request body so a handler never decodes more than maxBodyBytes.
func limitBody() gin.HandlerFunc {
return func(c *gin.Context) {
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxBodyBytes)
c.Next()
}
}
var errTrailingData = errors.New("trailing data after the JSON value")
var unknownField = regexp.MustCompile(`unknown field "([^"]*)"`)
// bindJSON decodes the body into v and refuses a field v does not declare. It writes the typed
// error and returns false: 413 payload_too_large past the cap, 422 unknown_body_field naming the
// field, 400 for anything else that is not the JSON the route takes.
func bindJSON(c *gin.Context, v any) bool {
dec := json.NewDecoder(c.Request.Body)
dec.DisallowUnknownFields()
err := dec.Decode(v)
if err == nil {
// One JSON value only: trailing data is a malformed request. Reading it can still hit the cap.
_, extra := dec.Token()
if errors.Is(extra, io.EOF) {
return true
}
err = cmp.Or(extra, errTrailingData)
}
var tooBig *http.MaxBytesError
if errors.As(err, &tooBig) {
c.AbortWithStatusJSON(http.StatusRequestEntityTooLarge, ErrorBody{Code: "payload_too_large", Message: "The request body is too large.", CorrelationID: CorrelationID(c)})
return false
}
if m := unknownField.FindStringSubmatch(err.Error()); m != nil {
c.AbortWithStatusJSON(http.StatusUnprocessableEntity, ErrorBody{Code: "unknown_body_field", Message: "The request body has a field this route does not accept.", Key: m[1], CorrelationID: CorrelationID(c)})
return false
}
badRequest(c, "request body must be JSON in the shape this route takes")
return false
}
// checkFields validates a projection list against the names a resource may project. The names are
// the resource's data.Spec allow-list plus any derived keys; anything else is a 422 like every
// other rejected list parameter.
func checkFields(c *gin.Context, fields, allowed []string) bool {
for _, f := range fields {
if !slices.Contains(allowed, f) {
c.AbortWithStatusJSON(http.StatusUnprocessableEntity, ErrorBody{Code: "invalid", Message: "cannot project " + f, Key: f, CorrelationID: CorrelationID(c)})
return false
}
}
return true
}
// projectMap keeps the named keys of a rendered resource, plus always (the identity keys a
// client needs to address what it received). Projecting the rendered output rather than the stored
// document means an unselected field is absent, never a zero value that reads as real data.
func projectMap(m map[string]any, fields []string, always ...string) map[string]any {
if len(fields) == 0 {
return m
}
out := make(map[string]any, len(fields)+len(always))
for _, k := range append(slices.Clone(fields), always...) {
if v, ok := m[k]; ok {
out[k] = v
}
}
return out
}
// toMap renders v through its JSON form, for projecting a stored resource.
func toMap(v any) map[string]any {
b, err := json.Marshal(v)
if err != nil {
return map[string]any{}
}
var m map[string]any
_ = json.Unmarshal(b, &m)
return m
}
// fieldsOf reads and validates ?fields= for a route that takes no other list parameters.
func fieldsOf(c *gin.Context, allowed []string) ([]string, bool) {
fields := splitList(c.Query("fields"))
return fields, checkFields(c, fields, allowed)
}
package server
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/sweetrpg/authz-client.go/authz"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/domain"
)
type changeRequestHandlers struct{ svc *domain.ChangeRequests }
// setupChangeRequestHandlers registers change requests on a session's combatants. They sit in the
// user-only group like the session routes: integration credentials never reach them. The
// responses are request records, never encounters, so there is nothing for the view builder to
// redact here; the encounter itself still changes only through UpdateInSession.
func setupChangeRequestHandlers(g *gin.RouterGroup, svc *domain.ChangeRequests) {
h := changeRequestHandlers{svc}
g.POST("/sessions/:id/encounters/:eid/combatants/:cid/change-requests", h.submit)
g.GET("/sessions/:id/encounters/:eid/change-requests", h.list)
g.POST("/sessions/:id/encounters/:eid/change-requests/:rid/approve", h.approve)
g.POST("/sessions/:id/encounters/:eid/change-requests/:rid/reject", h.reject)
}
type changeBody struct {
Health map[string]int `json:"health"`
// Conditions change by name: add sets (adds or updates) conditions, remove drops them.
Conditions struct {
Add []data.Condition `json:"add"`
Remove []string `json:"remove"`
} `json:"conditions"`
}
func (h changeRequestHandlers) submit(c *gin.Context) {
var b changeBody
if !bindJSON(c, &b) {
return
}
req, err := h.svc.Submit(c.Request.Context(), authz.Viewer(c), c.Param("id"), c.Param("eid"), c.Param("cid"),
domain.ChangeInput{Health: b.Health, AddConditions: b.Conditions.Add, RemoveConditions: b.Conditions.Remove})
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusCreated, req)
}
func (h changeRequestHandlers) list(c *gin.Context) {
q, ok := pageQuery(c)
if !ok {
return
}
status := c.Query("status")
if status != "" && status != data.ChangePending && status != data.ChangeApproved && status != data.ChangeRejected && status != data.ChangeCancelled {
badRequest(c, "status must be pending, approved, rejected or cancelled")
return
}
p, err := h.svc.List(c.Request.Context(), authz.Viewer(c), c.Param("id"), c.Param("eid"), status, q)
writePage(c, p.Items, p.NextCursor, err)
}
func (h changeRequestHandlers) approve(c *gin.Context) {
req, err := h.svc.Approve(c.Request.Context(), authz.Viewer(c), c.Param("id"), c.Param("eid"), c.Param("rid"))
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusOK, req)
}
func (h changeRequestHandlers) reject(c *gin.Context) {
var b struct {
Reason string `json:"reason"`
}
if !bindJSON(c, &b) {
return
}
req, err := h.svc.Reject(c.Request.Context(), authz.Viewer(c), c.Param("id"), c.Param("eid"), c.Param("rid"), b.Reason)
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusOK, req)
}
package server
import (
"crypto/rand"
"encoding/hex"
"log/slog"
"github.com/gin-gonic/gin"
sloggin "github.com/samber/slog-gin"
"github.com/sweetrpg/initiative-api/constants"
)
const correlationKey = "correlation_id"
// Correlation reuses the caller's X-Correlation-ID or mints one, and echoes it on the response
// so a request can be followed across services and log lines.
func Correlation() gin.HandlerFunc {
return func(c *gin.Context) {
id := c.GetHeader(constants.CorrelationHeader)
if id == "" || len(id) > 128 {
id = newID()
}
c.Set(correlationKey, id)
c.Header(constants.CorrelationHeader, id)
sloggin.AddCustomAttributes(c, slog.String("correlation_id", id))
c.Next()
}
}
// CorrelationID returns the request's correlation ID, or "" outside the Correlation middleware.
func CorrelationID(c *gin.Context) string {
return c.GetString(correlationKey)
}
func newID() string {
b := make([]byte, 16)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}
package server
import (
"context"
"errors"
"log/slog"
"net/http"
"slices"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/sweetrpg/authz-client.go/authz"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/domain"
)
const (
credentialContextKey = "initiative.credential"
// Keys authz-client.go uses for the caller's identity; authz.Viewer and authz.Roles read them,
// so a credential principal looks like its owner to every handler. TestCredentialPrincipal
// fails if the library changes them.
authzViewerKey = "authz.viewer"
authzRolesKey = "authz.roles"
)
// authenticate lets an integration secret ("ic_..." bearer) stand in for the user token. A secret
// resolves to its owner on every request, so a revoke applies to the next one. The principal gets
// the user role only and its scopes gate the method: read for GET/HEAD/OPTIONS, write otherwise.
// Anything else goes to userAuth (auth-api) unchanged.
func authenticate(creds *domain.Credentials, userAuth gin.HandlerFunc) gin.HandlerFunc {
return func(c *gin.Context) {
secret, _ := strings.CutPrefix(c.GetHeader("Authorization"), "Bearer ")
if creds == nil || !strings.HasPrefix(secret, domain.SecretPrefix) {
userAuth(c)
return
}
cred, ok := resolvedCredential(c)
var err error
if !ok {
cred, err = creds.Authenticate(c.Request.Context(), secret)
}
if errors.Is(err, data.ErrNotFound) {
c.AbortWithStatusJSON(http.StatusUnauthorized, ErrorBody{Code: "unauthorized", Message: "Missing or invalid credential.", CorrelationID: CorrelationID(c)})
return
}
if err != nil {
writeError(c, err, nil)
return
}
need := data.ScopeWrite
switch c.Request.Method {
case http.MethodGet, http.MethodHead, http.MethodOptions:
need = data.ScopeRead
}
if !slices.Contains(cred.Scopes, need) {
c.AbortWithStatusJSON(http.StatusForbidden, ErrorBody{Code: "scope_missing", Message: "This credential lacks the " + need + " scope.", CorrelationID: CorrelationID(c)})
return
}
c.Set(authzViewerKey, cred.OwnerUserID)
c.Set(authzRolesKey, []string{authz.RoleUser})
c.Set(credentialContextKey, cred.ID)
if !isStreamUpgrade(c.Request) { // a stream rechecks on its own heartbeat
defer watchCredential(c, creds, cred.ID)()
}
c.Next()
}
}
// credentialRecheck is how often a running request made with a credential asks whether the
// credential is still live. A request shorter than this is never rechecked; it was authenticated
// against the store an instant earlier.
var credentialRecheck = 5 * time.Second
// watchCredential cancels the request's context, with errCredentialRevoked as the cause, once the
// credential stops being live (revoked, deleted, owner denied, or the gate closed), so an
// in-flight request does not outlive it by more than credentialRecheck. Store errors count like a
// stream's: fail closed after maxGuardErrors in a row. The returned func stops the watcher.
func watchCredential(c *gin.Context, creds *domain.Credentials, id string) (stop func()) {
ctx, cancel := context.WithCancelCause(c.Request.Context())
c.Request = c.Request.WithContext(ctx)
guard := liveGuard(func(ctx context.Context) (bool, error) { return creds.Live(ctx, id) })
every := credentialRecheck // read here, on the request's goroutine
go func() {
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
if guard(ctx) != nil {
cancel(errCredentialRevoked)
return
}
}
}
}()
return func() { cancel(nil) }
}
func isStreamUpgrade(r *http.Request) bool {
return r.Method == http.MethodGet && r.URL.Path == "/streams"
}
// userOnly rejects integration credentials: account-level routes need the user's own bearer
// (they forward it to entitlements-api, PADR-0037), and a credential must not manage credentials.
func userOnly(c *gin.Context) {
if _, ok := c.Get(credentialContextKey); ok {
c.AbortWithStatusJSON(http.StatusForbidden, ErrorBody{Code: "user_token_required", Message: "This request needs your own sign-in, not an integration credential.", CorrelationID: CorrelationID(c)})
return
}
c.Next()
}
type credentialHandlers struct {
svc Services
}
func setupCredentialHandlers(g *gin.RouterGroup, s Services) {
h := credentialHandlers{s}
g.POST("/credentials", h.create)
g.GET("/credentials", h.list)
g.POST("/credentials/:id/revoke", h.revoke)
}
type credentialBody struct {
Label string `json:"label"`
Scopes []string `json:"scopes"`
}
// create returns the secret once, alongside the stored record.
func (h credentialHandlers) create(c *gin.Context) {
var b credentialBody
if !bindJSON(c, &b) {
return
}
cred, secret, err := h.svc.Credentials.Create(c.Request.Context(), authz.Viewer(c), b.Label, b.Scopes, checkerFor(c, h.svc.Entitlements))
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusCreated, gin.H{"credential": cred, "secret": secret})
}
func (h credentialHandlers) list(c *gin.Context) {
page, err := h.svc.Credentials.List(c.Request.Context(), authz.Viewer(c), data.Query{Cursor: c.Query("cursor")})
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusOK, gin.H{"items": page.Items, "next_cursor": page.NextCursor})
}
func (h credentialHandlers) revoke(c *gin.Context) {
cred, err := h.svc.Credentials.Revoke(c.Request.Context(), authz.Viewer(c), c.Param("id"))
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusOK, cred)
}
// setupAdminCredentialHandlers registers the administrator's reopen. The group takes no integration
// credentials, so only an admin's own bearer reaches it.
func setupAdminCredentialHandlers(g *gin.RouterGroup, creds *domain.Credentials) {
g.POST("/admin/credentials/reopen", func(c *gin.Context) {
actor := authz.Viewer(c)
if err := creds.Reopen(c.Request.Context(), actor); err != nil {
writeError(c, err, nil)
return
}
slog.WarnContext(c.Request.Context(), "audit: integration credentials reopened", "audit", true, "actor", actor, "correlation_id", CorrelationID(c))
c.JSON(http.StatusOK, gin.H{"open": true})
})
g.GET("/admin/credentials", func(c *gin.Context) { adminListCredentials(c, creds) })
g.GET("/admin/credentials/deletions", func(c *gin.Context) { adminDeletions(c, creds) })
g.DELETE("/admin/credentials/:id", func(c *gin.Context) { adminDeleteCredential(c, creds) })
}
// pageQuery reads ?cursor and ?limit; it answers 400 and returns false on a bad limit.
func pageQuery(c *gin.Context) (data.Query, bool) {
q := data.Query{Cursor: c.Query("cursor")}
if v := c.Query("limit"); v != "" {
n, err := strconv.Atoi(v)
if err != nil || n < 1 {
badRequest(c, "limit must be a positive integer")
return q, false
}
q.Limit = n
}
return q, true
}
// adminListCredentials lists any owner's credentials; ?owner= narrows it. Secrets and hashes are
// never in the model's JSON.
func adminListCredentials(c *gin.Context, creds *domain.Credentials) {
q, ok := pageQuery(c)
if !ok {
return
}
page, err := creds.ListAll(c.Request.Context(), c.Query("owner"), q)
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusOK, gin.H{"items": page.Items, "next_cursor": page.NextCursor})
}
func adminDeletions(c *gin.Context, creds *domain.Credentials) {
q, ok := pageQuery(c)
if !ok {
return
}
page, err := creds.Deletions(c.Request.Context(), c.Query("owner"), q)
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusOK, gin.H{"items": page.Items, "next_cursor": page.NextCursor})
}
// adminDeleteCredential deletes a credential permanently. The reason is required; the audit entry
// is stored before the credential goes and is logged as well.
func adminDeleteCredential(c *gin.Context, creds *domain.Credentials) {
var b struct {
Reason string `json:"reason"`
}
// A missing or malformed body is the same 422 as an empty reason, not bindJSON's 400.
if err := c.ShouldBindJSON(&b); err != nil || strings.TrimSpace(b.Reason) == "" {
c.AbortWithStatusJSON(http.StatusUnprocessableEntity, ErrorBody{Code: "reason_required", Message: "A reason is required to delete a credential.", CorrelationID: CorrelationID(c)})
return
}
actor := authz.Viewer(c)
entry, err := creds.DeletePermanently(c.Request.Context(), actor, c.Param("id"), b.Reason)
if errors.Is(err, data.ErrNotFound) || errors.Is(err, data.ErrInvalid) {
writeError(c, err, nil)
return
}
if err != nil {
slog.ErrorContext(c.Request.Context(), "credential deletion did not complete", "actor", actor, "credential_id", c.Param("id"), "error", err, "correlation_id", CorrelationID(c))
c.AbortWithStatusJSON(http.StatusInternalServerError, ErrorBody{Code: "deletion_incomplete", Message: "The deletion did not complete and may be partly done. Retry the same request.", CorrelationID: CorrelationID(c)})
return
}
slog.WarnContext(c.Request.Context(), "audit: integration credential deleted", "audit", true, "actor", actor,
"credential_id", entry.CredentialID, "owner", entry.OwnerUserID, "label", entry.Label, "reason", entry.Reason, "correlation_id", CorrelationID(c))
c.JSON(http.StatusOK, entry)
}
package server
import (
"errors"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/sweetrpg/authz-client.go/authz"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/domain"
)
type encounterViewHandlers struct {
svc *domain.Encounters
sessions *domain.Sessions
}
// setupEncounterViewHandlers registers the read routes for encounters. Every response is a
// domain.EncounterView built for the caller's role; no handler here serializes an encounter any
// other way (initiative-api-resources, "Role-aware responses"). They sit in the user-only group,
// like the session routes.
func setupEncounterViewHandlers(g *gin.RouterGroup, svc *domain.Encounters, sessions *domain.Sessions) {
h := encounterViewHandlers{svc, sessions}
g.GET("/sessions/:id/encounters", h.list)
g.POST("/sessions/:id/encounters", h.create)
g.GET("/sessions/:id/encounters/:eid", h.get)
g.GET("/sessions/:id/encounters/:eid/combatants/:cid", h.combatant)
g.PUT("/sessions/:id/encounters/:eid/combatants/:cid/controllers", h.setControllers)
}
// viewer authorizes the caller on the session in the path. A caller who is not a member gets 403
// before anything about the session's contents is looked up.
func (h encounterViewHandlers) viewer(c *gin.Context) (data.Viewer, bool) {
v, err := h.sessions.Viewer(c.Request.Context(), authz.Viewer(c), c.Param("id"))
if err != nil {
writeError(c, err, nil)
return data.Viewer{}, false
}
return v, true
}
// create makes an encounter in the session, owned by its GM. The session decides who may and
// whether the GM's saved-encounters limit has room; the encounter service then runs the same
// validation as for a private encounter, and the response is built for the caller's role.
func (h encounterViewHandlers) create(c *gin.Context) {
var b encounterCreate
if !bindJSON(c, &b) {
return
}
if b.Name == nil {
badRequest(c, "request body must be a JSON encounter with a name")
return
}
ctx := c.Request.Context()
grant, err := h.sessions.AuthorizeEncounterCreate(ctx, authz.Viewer(c), c.Param("id"))
if err != nil {
writeError(c, err, nil)
return
}
e := b.encounter()
for _, cb := range b.Combatants {
e.Combatants = append(e.Combatants, cb.combatant())
}
view, err := h.svc.CreateInSession(ctx, grant, e)
if err != nil {
writeError(c, err, nil)
return
}
writeView(c, http.StatusCreated, view, nil)
}
func (h encounterViewHandlers) list(c *gin.Context) {
v, ok := h.viewer(c)
if !ok {
return
}
views, err := h.svc.ViewsForSession(c.Request.Context(), v, 100)
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusOK, gin.H{"items": views})
}
func (h encounterViewHandlers) get(c *gin.Context) {
v, ok := h.viewer(c)
if !ok {
return
}
view, err := h.svc.ViewForSession(c.Request.Context(), v, c.Param("eid"))
if err != nil {
writeError(c, err, nil)
return
}
writeView(c, http.StatusOK, view, nil)
}
// combatant answers from the encounter view, so a combatant the caller may not see is absent from
// the lookup and gets the same 404 as one that does not exist.
func (h encounterViewHandlers) combatant(c *gin.Context) {
v, ok := h.viewer(c)
if !ok {
return
}
view, err := h.svc.ViewForSession(c.Request.Context(), v, c.Param("eid"))
if err != nil {
writeError(c, err, nil)
return
}
cv, found := view.Combatant(c.Param("cid"))
if !found {
writeError(c, data.ErrNotFound, nil)
return
}
c.JSON(http.StatusOK, cv)
}
// writeView sends view with an ETag: the stored revision for a GM, and for everyone else the digest
// of what they can see, so a hidden edit never changes what a player's client observes.
func writeView(c *gin.Context, status int, view domain.EncounterView, fields []string) {
if tag, ok := view[domain.FieldViewTag].(string); ok {
c.Header("ETag", `"`+tag+`"`)
} else if rev, ok := view["revision"].(int64); ok {
c.Header("ETag", `"r`+strconv.FormatInt(rev, 10)+`"`)
}
c.JSON(status, projected(view, fields))
}
type controllersBody struct {
ControllerUserIDs []string `json:"controller_user_ids"`
Revision int64 `json:"revision"`
}
// setControllers assigns a combatant's controllers. Only the session's GM and co-GMs may; every
// listed user must be a session member who can control (not an observer). The revision comes from
// If-Match, the query, or the body, and a stale one is a 409 carrying the current view.
func (h encounterViewHandlers) setControllers(c *gin.Context) {
var b controllersBody
if !bindJSON(c, &b) {
return
}
if b.ControllerUserIDs == nil {
badRequest(c, "controller_user_ids is required (an empty list clears the controllers)")
return
}
rev, ok := revisionOf(c, b.Revision)
if !ok {
return
}
actor := authz.Viewer(c)
view, err := h.svc.AssignControllers(c.Request.Context(), h.sessions, actor, c.Param("id"), c.Param("eid"), c.Param("cid"), b.ControllerUserIDs, rev)
if err != nil {
var current any
if errors.Is(err, data.ErrRevisionConflict) {
if v, viewerr := h.sessions.Viewer(c.Request.Context(), actor, c.Param("id")); viewerr == nil {
if cur, cerr := h.svc.ViewForSession(c.Request.Context(), v, c.Param("eid")); cerr == nil {
current = cur
}
}
}
writeError(c, err, current)
return
}
writeView(c, http.StatusOK, view, nil)
}
package server
import (
"context"
"encoding/json"
"errors"
"net/http"
"github.com/gin-gonic/gin"
"github.com/sweetrpg/authz-client.go/authz"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/domain"
"github.com/sweetrpg/initiative-api/entitlements"
)
type encounterHandlers struct {
svc *domain.Encounters
rosters *domain.Rosters
ent *entitlements.Client
}
// setupEncounterHandlers registers the owner's private encounters: reads, writes, combatants, turn
// actions, and the roster transfers. They sit in the group that accepts integration credentials.
// Every encounter response is a domain.EncounterView written by respond, the only place these
// handlers serialize an encounter (initiative-api-resources, "Role-aware responses").
func setupEncounterHandlers(g *gin.RouterGroup, svc *domain.Encounters, rosters *domain.Rosters, ent *entitlements.Client) {
h := encounterHandlers{svc, rosters, ent}
g.GET("/encounters", h.list)
g.POST("/encounters", h.create)
g.GET("/encounters/:id", h.get)
g.PATCH("/encounters/:id", h.update)
g.DELETE("/encounters/:id", h.remove)
g.POST("/encounters/:id/combatants", h.addCombatant)
g.PATCH("/encounters/:id/combatants/:cid", h.updateCombatant)
g.DELETE("/encounters/:id/combatants/:cid", h.removeCombatant)
g.POST("/encounters/:id/combatants/:cid/restore", h.restoreCombatant)
g.POST("/encounters/:id/start", h.turnAction(svc.Start))
g.POST("/encounters/:id/end", h.turnAction(svc.End))
g.POST("/encounters/:id/reset", h.turnAction(svc.Reset))
g.POST("/encounters/:id/advance", h.turnAction(svc.Advance))
g.POST("/encounters/:id/back", h.turnAction(svc.StepBack))
if rosters != nil {
g.POST("/rosters/:id/encounters", h.fromRoster)
g.POST("/encounters/:id/save-as-roster", h.saveAsRoster)
}
}
// encounterWrite is a domain write on one encounter at a revision.
type encounterWrite func(ctx context.Context, owner, actor, id string, rev int64) (data.Encounter, error)
type conditionBody struct {
Name string `json:"name"`
RoundsRemaining *int `json:"rounds_remaining"`
}
type combatantBody struct {
Name string `json:"name"`
Kind string `json:"kind"`
Initiative *float64 `json:"initiative"`
Health map[string]int `json:"health"`
Conditions []conditionBody `json:"conditions"`
Notes string `json:"notes"`
ExternalRefs map[string]string `json:"external_refs"`
Hidden bool `json:"hidden"`
HealthVisibility string `json:"health_visibility"`
NotesShared bool `json:"notes_shared"`
}
func conditionsOf(in []conditionBody) []data.Condition {
out := make([]data.Condition, 0, len(in))
for _, c := range in {
out = append(out, data.Condition{Name: c.Name, RoundsRemaining: c.RoundsRemaining})
}
return out
}
func (b combatantBody) combatant() data.Combatant {
return data.Combatant{Name: b.Name, Kind: b.Kind, Initiative: b.Initiative, Health: b.Health, Conditions: conditionsOf(b.Conditions),
Notes: b.Notes, ExternalRefs: b.ExternalRefs, Hidden: b.Hidden, HealthVisibility: b.HealthVisibility, NotesShared: b.NotesShared}
}
// encounterSettings are the fields of an encounter a client sets. Every one is optional.
type encounterSettings struct {
Name *string `json:"name"`
GameSystemID *string `json:"game_system_id"`
Ordering *string `json:"ordering"`
TieBreaker *string `json:"tie_breaker"`
Labels *bool `json:"labels"`
Colorblind *bool `json:"colorblind"`
ThemeID *string `json:"theme_id"`
Position *int `json:"position"`
}
// encounterCreate is the body of POST /encounters: the settings plus the starting combatants.
type encounterCreate struct {
encounterSettings
Combatants []combatantBody `json:"combatants"`
}
// encounterPatch is the body of PATCH /encounters/:id. Combatants change through their own routes.
type encounterPatch struct {
encounterSettings
Revision int64 `json:"revision"`
}
// settings is the set of fields the request names, keyed as the data layer's update list.
func (b encounterSettings) settings() map[string]any {
set := map[string]any{}
if b.Name != nil {
set["name"] = *b.Name
}
if b.GameSystemID != nil {
set["game_system_id"] = *b.GameSystemID
}
if b.Ordering != nil {
set["ordering"] = *b.Ordering
}
if b.TieBreaker != nil {
set["tie_breaker"] = *b.TieBreaker
}
if b.Labels != nil {
set["labels"] = *b.Labels
}
if b.Colorblind != nil {
set["colorblind"] = *b.Colorblind
}
if b.ThemeID != nil {
set["theme_id"] = *b.ThemeID
}
if b.Position != nil {
set["position"] = *b.Position
}
return set
}
// encounter builds a new draft from the settings, defaulting the ordering mode and tie breaker.
func (b encounterSettings) encounter() data.Encounter {
e := data.Encounter{Ordering: data.OrderHighToLow, TieBreaker: data.TieRandom}
if b.Name != nil {
e.Name = *b.Name
}
if b.GameSystemID != nil {
e.GameSystemID = *b.GameSystemID
}
if b.Ordering != nil {
e.Ordering = *b.Ordering
}
if b.TieBreaker != nil {
e.TieBreaker = *b.TieBreaker
}
if b.Labels != nil {
e.Labels = *b.Labels
}
if b.Colorblind != nil {
e.Colorblind = *b.Colorblind
}
if b.ThemeID != nil {
e.ThemeID = *b.ThemeID
}
if b.Position != nil {
e.Position = *b.Position
}
return e
}
// encounterFields are the names ?fields= may select from an encounter view: the stored fields
// the spec lists plus the derived count.
var encounterFields = append(append([]string{}, data.EncounterSpec.Projectable...), "combatant_count")
// projected keeps the fields the client selected; identity keys always stay.
func projected(view domain.EncounterView, fields []string) map[string]any {
return projectMap(view, fields, "id", "revision", domain.FieldViewTag)
}
// respond is the one place these handlers write an encounter: the caller's view of enc.
func (h encounterHandlers) respond(c *gin.Context, status int, enc data.Encounter) {
view, err := h.svc.ViewWritten(c.Request.Context(), authz.Viewer(c), enc)
if err != nil {
writeError(c, err, nil)
return
}
writeView(c, status, view, nil)
}
// fail writes err; a revision conflict carries the encounter's current view.
func (h encounterHandlers) fail(c *gin.Context, err error, id string) {
var current any
if errors.Is(err, data.ErrRevisionConflict) {
if v, verr := h.svc.ViewOwned(c.Request.Context(), authz.Viewer(c), id); verr == nil {
current = v
}
}
writeError(c, err, current)
}
func (h encounterHandlers) list(c *gin.Context) {
q, ok := parseQuery(c, map[string]string{"position": typeInt})
if !ok || !checkFields(c, q.Fields, encounterFields) {
return
}
// Projected after the view is built (below), never in the query: a view built from a partly
// loaded encounter would show zero values for the fields left out.
fields := q.Fields
q.Fields = nil
page, err := h.svc.ViewsOwned(c.Request.Context(), authz.Viewer(c), q)
if err != nil {
writeError(c, err, nil)
return
}
items := make([]map[string]any, 0, len(page.Items))
for _, v := range page.Items {
items = append(items, projected(v, fields))
}
c.JSON(http.StatusOK, gin.H{"items": items, "next_cursor": page.NextCursor})
}
func (h encounterHandlers) get(c *gin.Context) {
fields, ok := fieldsOf(c, encounterFields)
if !ok {
return
}
view, err := h.svc.ViewOwned(c.Request.Context(), authz.Viewer(c), c.Param("id"))
if err != nil {
writeError(c, err, nil)
return
}
writeView(c, http.StatusOK, view, fields)
}
func (h encounterHandlers) create(c *gin.Context) {
var b encounterCreate
if !bindJSON(c, &b) {
return
}
if b.Name == nil {
badRequest(c, "request body must be a JSON encounter with a name")
return
}
if !requireRoom(c, h.ent, domain.KeySavedEncounters, h.svc.Count) {
return
}
owner := authz.Viewer(c)
e := b.encounter()
for _, cb := range b.Combatants {
e.Combatants = append(e.Combatants, cb.combatant())
}
enc, err := h.svc.Create(c.Request.Context(), owner, owner, e)
if err != nil {
writeError(c, err, nil)
return
}
h.respond(c, http.StatusCreated, enc)
}
func (h encounterHandlers) update(c *gin.Context) {
var b encounterPatch
if !bindJSON(c, &b) {
return
}
rev, ok := revisionOf(c, b.Revision)
if !ok {
return
}
owner := authz.Viewer(c)
enc, err := h.svc.UpdateSettings(c.Request.Context(), owner, owner, c.Param("id"), rev, b.settings())
if err != nil {
h.fail(c, err, c.Param("id"))
return
}
h.respond(c, http.StatusOK, enc)
}
func (h encounterHandlers) remove(c *gin.Context) {
rev, ok := revisionOf(c, 0)
if !ok {
return
}
owner := authz.Viewer(c)
if err := h.svc.Delete(c.Request.Context(), owner, owner, c.Param("id"), rev); err != nil {
h.fail(c, err, c.Param("id"))
return
}
c.Status(http.StatusNoContent)
}
func (h encounterHandlers) addCombatant(c *gin.Context) {
var b struct {
combatantBody
Revision int64 `json:"revision"`
}
if !bindJSON(c, &b) {
return
}
rev, ok := revisionOf(c, b.Revision)
if !ok {
return
}
owner := authz.Viewer(c)
enc, err := h.svc.AddCombatant(c.Request.Context(), owner, owner, c.Param("id"), rev, b.combatant())
if err != nil {
h.fail(c, err, c.Param("id"))
return
}
h.respond(c, http.StatusCreated, enc)
}
func (h encounterHandlers) updateCombatant(c *gin.Context) {
var b struct {
Revision int64 `json:"revision"`
Name *string `json:"name"`
Kind *string `json:"kind"`
Initiative *float64 `json:"initiative"`
Notes *string `json:"notes"`
Health map[string]int `json:"health"`
Conditions *[]conditionBody `json:"conditions"`
Hidden *bool `json:"hidden"`
HealthVisibility *string `json:"health_visibility"`
NotesShared *bool `json:"notes_shared"`
}
if !bindJSON(c, &b) {
return
}
rev, ok := revisionOf(c, b.Revision)
if !ok {
return
}
patch := domain.CombatantPatch{Name: b.Name, Kind: b.Kind, Initiative: b.Initiative, Notes: b.Notes, Health: b.Health,
Hidden: b.Hidden, HealthVisibility: b.HealthVisibility, NotesShared: b.NotesShared}
if b.Conditions != nil {
conds := conditionsOf(*b.Conditions)
patch.Conditions = &conds
}
owner := authz.Viewer(c)
enc, err := h.svc.UpdateCombatant(c.Request.Context(), owner, owner, c.Param("id"), rev, c.Param("cid"), patch)
if err != nil {
h.fail(c, err, c.Param("id"))
return
}
h.respond(c, http.StatusOK, enc)
}
func (h encounterHandlers) removeCombatant(c *gin.Context) {
h.combatantAction(c, h.svc.RemoveCombatant)
}
func (h encounterHandlers) restoreCombatant(c *gin.Context) {
h.combatantAction(c, h.svc.RestoreCombatant)
}
// combatantAction runs a revisioned action on one combatant and returns the encounter.
func (h encounterHandlers) combatantAction(c *gin.Context, fn func(ctx context.Context, owner, actor, id string, rev int64, combatantID string) (data.Encounter, error)) {
rev, ok := revisionOf(c, bodyRevision(c))
if !ok {
return
}
owner := authz.Viewer(c)
enc, err := fn(c.Request.Context(), owner, owner, c.Param("id"), rev, c.Param("cid"))
if err != nil {
h.fail(c, err, c.Param("id"))
return
}
h.respond(c, http.StatusOK, enc)
}
// turnAction serves the revisioned actions that change combat state: start, end, reset, advance
// and back. The body is optional; the revision may come from If-Match or the query.
func (h encounterHandlers) turnAction(fn encounterWrite) gin.HandlerFunc {
return func(c *gin.Context) {
rev, ok := revisionOf(c, bodyRevision(c))
if !ok {
return
}
owner := authz.Viewer(c)
enc, err := fn(c.Request.Context(), owner, owner, c.Param("id"), rev)
if err != nil {
h.fail(c, err, c.Param("id"))
return
}
h.respond(c, http.StatusOK, enc)
}
}
// bodyRevision reads an optional JSON body's revision field, 0 when there is no usable body.
func bodyRevision(c *gin.Context) int64 {
var b struct {
Revision int64 `json:"revision"`
}
if c.Request.Body != nil {
_ = json.NewDecoder(c.Request.Body).Decode(&b)
}
return b.Revision
}
// fromRoster creates an encounter with one combatant per character of the roster in the path.
func (h encounterHandlers) fromRoster(c *gin.Context) {
var b encounterSettings
if !bindJSON(c, &b) {
return
}
if b.Name == nil {
badRequest(c, "request body must be a JSON encounter with a name")
return
}
if !requireRoom(c, h.ent, domain.KeySavedEncounters, h.svc.Count) {
return
}
owner := authz.Viewer(c)
e := b.encounter()
enc, err := h.rosters.CreateEncounterFromRoster(c.Request.Context(), owner, owner, c.Param("id"), e)
if err != nil {
writeError(c, err, nil)
return
}
h.respond(c, http.StatusCreated, enc)
}
// saveAsRoster stores a roster from the encounter in the path. The response is the roster, which
// holds no combatant visibility data.
func (h encounterHandlers) saveAsRoster(c *gin.Context) {
var b struct {
Name string `json:"name"`
}
if c.Request.ContentLength != 0 && !bindJSON(c, &b) { // the name is optional: it defaults to the encounter's
return
}
if !requireRoom(c, h.ent, domain.KeySavedRosters, h.rosters.Count) {
return
}
owner := authz.Viewer(c)
r, err := h.rosters.SaveAsRoster(c.Request.Context(), owner, owner, c.Param("id"), b.Name)
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusCreated, r)
}
package server
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/sweetrpg/authz-client.go/authz"
"github.com/sweetrpg/initiative-api/entitlements"
)
// entitlementPrefix selects every Initiative key in the catalog.
const entitlementPrefix = "initiative."
// EntitlementItem is one key as the caller holds it. Value is a bool for flags and an integer
// for limits. Usage is the caller's count against a limit; it is omitted for flags and for limits
// whose resource this service does not store yet.
type EntitlementItem struct {
Key string `json:"key"`
Type string `json:"type"`
Value any `json:"value"`
Usage *int64 `json:"usage,omitempty"`
}
type entitlementHandlers struct {
svc Services
usage map[string]func(ctx context.Context, owner string) (int64, error)
}
func setupEntitlementHandlers(g *gin.RouterGroup, s Services) {
h := entitlementHandlers{svc: s, usage: map[string]func(context.Context, string) (int64, error){
"initiative.theme_slots": s.Themes.Count,
"initiative.saved_rosters": s.Rosters.Count,
"initiative.saved_encounters": s.Encounters.Count,
}}
g.GET("/entitlements", h.list)
}
// list shows the caller's Initiative entitlements with usage so clients can render state and
// upgrade prompts. Clients never use it to decide anything; enforcement stays in the handlers
// that create things.
func (h entitlementHandlers) list(c *gin.Context) {
owner := authz.Viewer(c)
results, err := h.svc.Entitlements.Prefix(c.Request.Context(), owner, authz.Token(c), entitlementPrefix)
if err != nil {
writeError(c, err, nil)
return
}
if len(results) > 0 {
if uc, ok := checkerFor(c, h.svc.Entitlements).(userChecker); ok && uc.record != nil {
fresh := make([]entitlements.Result, 0, len(results))
for _, r := range results {
if !r.Stale && !r.Degraded {
fresh = append(fresh, r)
}
}
uc.remember(c.Request.Context(), fresh...)
}
}
items := make([]EntitlementItem, 0, len(results))
for _, r := range results {
it := EntitlementItem{Key: r.Key, Type: r.Type}
if r.Type == "flag" {
it.Value = r.Flag
} else {
it.Value = r.Limit
}
if count, ok := h.usage[r.Key]; ok {
n, err := count(c.Request.Context(), owner)
if err != nil {
writeError(c, err, nil)
return
}
it.Usage = &n
}
items = append(items, it)
}
c.JSON(http.StatusOK, gin.H{"items": items})
}
package server
import (
"context"
"errors"
"log/slog"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/domain"
"github.com/sweetrpg/initiative-api/entitlements"
"github.com/sweetrpg/initiative-api/events/stream"
"github.com/sweetrpg/initiative-api/relations"
)
// ErrorBody is the typed error response: a stable code, a safe message, the correlation ID, and
// for entitlement denials the key and limit. Current carries the stored record on a 409.
type ErrorBody struct {
Code string `json:"code"`
Message string `json:"message"`
CorrelationID string `json:"correlation_id,omitempty"`
Key string `json:"key,omitempty"`
Limit *int `json:"limit,omitempty"`
Current any `json:"current,omitempty"`
}
// writeError maps err to a status and typed body. current is returned with revision conflicts.
// Unrecognized errors are logged and reported as an opaque 500.
func writeError(c *gin.Context, err error, current any) {
if errors.Is(context.Cause(c.Request.Context()), errCredentialRevoked) {
err = errCredentialRevoked // the request was cut short by the credential's end, whatever the store reported
}
body, status := classifyError(err)
body.CorrelationID = CorrelationID(c)
if status == http.StatusConflict && body.Code == "revision_conflict" {
body.Current = current
}
if status >= http.StatusInternalServerError && status != http.StatusServiceUnavailable {
slog.ErrorContext(c.Request.Context(), "request failed", "error", err, "correlation_id", body.CorrelationID)
}
if body.Code == "membership_sync_pending" || body.Code == "rate_limited" || body.Code == "timeout" || body.Code == "shutting_down" || body.Code == "too_many_streams" || body.Code == "streams_unavailable" {
c.Header("Retry-After", "5")
}
c.AbortWithStatusJSON(status, body)
}
func classifyError(err error) (ErrorBody, int) {
var ee *domain.EntitlementError
var dl *data.DeviceLimitError
var er *domain.EntitlementRequiredError
var he *data.HealthError
switch {
case errors.As(err, &he):
// Typed validation failure (initiative-api-resources, "Typed error responses"): the code is
// stable and the key names the offending health field, so a client can mark it.
if he.Unknown {
return ErrorBody{Code: "unknown_field", Message: "That health field is not defined by the game system.", Key: he.Field}, http.StatusUnprocessableEntity
}
return ErrorBody{Code: "field_out_of_range", Message: "That health value is outside the allowed range for the game system.", Key: he.Field}, http.StatusUnprocessableEntity
case errors.As(err, &ee):
return ErrorBody{Code: "entitlement_limit_reached", Message: "Your plan's limit for this item has been reached.", Key: ee.Key, Limit: &ee.Limit}, http.StatusForbidden
case errors.As(err, &dl):
return ErrorBody{Code: "device_limit_reached", Message: "This account already has the most connections allowed to this session. Close one and try again.", Key: "devices_per_member", Limit: &dl.Limit}, http.StatusForbidden
case errors.Is(err, domain.ErrReadOnly):
return ErrorBody{Code: "packaged_theme_read_only", Message: "Packaged themes cannot be changed. Create a custom theme from it instead."}, http.StatusForbidden
case errors.Is(err, domain.ErrCredentialsClosed):
return ErrorBody{Code: "credentials_unavailable", Message: "Integration credentials are temporarily unavailable."}, http.StatusServiceUnavailable
case errors.Is(err, domain.ErrOwnerLimitsUnknown):
return ErrorBody{Code: "owner_entitlements_pending", Message: "The session owner has not connected yet. Try again after they do."}, http.StatusServiceUnavailable
case errors.Is(err, domain.ErrSyncPending):
return ErrorBody{Code: "membership_sync_pending", Message: "Your change was saved, but access is still being updated. Repeat the request in a moment."}, http.StatusServiceUnavailable
case errors.Is(err, domain.ErrLimitsNotSynced):
return ErrorBody{Code: "entitlements_unavailable", Message: "Your plan limits have not been synced yet. Open Initiative once with your own sign-in, then try again."}, http.StatusServiceUnavailable
case errors.Is(err, relations.ErrDenied):
return ErrorBody{Code: "forbidden", Message: "You may not do that."}, http.StatusForbidden
case errors.Is(err, relations.ErrRejected):
// A malformed request is our bug and retrying cannot help; not 503. It falls to the opaque
// 500 and writeError logs it.
return ErrorBody{Code: "internal", Message: "Something went wrong."}, http.StatusInternalServerError
case errors.Is(err, relations.ErrConflict):
// The member record is already saved, and the reconciler writes tuples from Mongo through
// the internal path, which the 200-tuple cap does not cover, so a refused member is let in
// on the next pass. Accepted: the members_per_session entitlement caps a session at 20
// members, and only a direct caller of auth-api can reach the tuple cap.
return ErrorBody{Code: "session_full", Message: "The session has reached its member limit."}, http.StatusConflict
case errors.Is(err, relations.ErrLimited):
return ErrorBody{Code: "rate_limited", Message: "Too many requests. Try again shortly."}, http.StatusTooManyRequests
case errors.Is(err, relations.ErrUnavailable):
return ErrorBody{Code: "authorization_unavailable", Message: "Session access cannot be checked right now. Try again shortly."}, http.StatusServiceUnavailable
case errors.Is(err, relations.ErrUnauthorized):
return ErrorBody{Code: "unauthorized", Message: "Your session is not valid."}, http.StatusUnauthorized
case errors.Is(err, entitlements.ErrUnavailable):
return ErrorBody{Code: "entitlements_unavailable", Message: "Entitlements are temporarily unavailable. Try again shortly."}, http.StatusServiceUnavailable
case errors.Is(err, errCredentialRevoked):
return ErrorBody{Code: "unauthorized", Message: "This credential has been revoked."}, http.StatusUnauthorized
case errors.Is(err, entitlements.ErrUnauthorized):
return ErrorBody{Code: "unauthorized", Message: "Your session is not valid."}, http.StatusUnauthorized
case errors.Is(err, context.DeadlineExceeded):
return ErrorBody{Code: "timeout", Message: "The request took too long. Try again shortly."}, http.StatusServiceUnavailable
case errors.Is(err, data.ErrStreamUnavailable):
return ErrorBody{Code: "streams_unavailable", Message: "Event streams cannot be opened right now. Try again shortly."}, http.StatusServiceUnavailable
case errors.Is(err, data.ErrStreamLimit):
return ErrorBody{Code: "too_many_streams", Message: "You have too many open event streams. Close one and try again."}, http.StatusTooManyRequests
case errors.Is(err, stream.ErrShuttingDown):
return ErrorBody{Code: "shutting_down", Message: "This server is restarting. Reconnect shortly."}, http.StatusServiceUnavailable
case errors.Is(err, domain.ErrTicketInvalid):
return ErrorBody{Code: "ticket_invalid", Message: "The stream ticket is not valid. Request a new one."}, http.StatusUnauthorized
case errors.Is(err, domain.ErrChangeStale):
return ErrorBody{Code: "change_request_stale", Message: strings.TrimPrefix(err.Error(), domain.ErrChangeStale.Error()+": ")}, http.StatusConflict
case errors.Is(err, data.ErrNotFound):
return ErrorBody{Code: "not_found", Message: "Not found."}, http.StatusNotFound
case errors.Is(err, data.ErrLocked), errors.As(err, &er):
return ErrorBody{Code: "entitlement_required", Message: "This needs an entitlement your account does not currently hold.", Key: domain.KeyGameSystemsExtra}, http.StatusForbidden
case errors.Is(err, data.ErrInactive):
return ErrorBody{Code: "item_inactive", Message: "This item is over your plan's limit. You can still view or delete it; choose which items stay active to use it again."}, http.StatusForbidden
case errors.Is(err, data.ErrNotMember):
return ErrorBody{Code: "forbidden", Message: "You are not a member of this session."}, http.StatusForbidden
case errors.Is(err, data.ErrForbidden):
return ErrorBody{Code: "forbidden", Message: "You do not own this record."}, http.StatusForbidden
case errors.Is(err, data.ErrRevisionConflict):
return ErrorBody{Code: "revision_conflict", Message: "The record changed since you loaded it."}, http.StatusConflict
case errors.Is(err, data.ErrConflict):
return ErrorBody{Code: "conflict", Message: "The request conflicts with an existing record."}, http.StatusConflict
case errors.Is(err, data.ErrInvalid):
return ErrorBody{Code: "invalid", Message: strings.TrimPrefix(err.Error(), data.ErrInvalid.Error()+": ")}, http.StatusUnprocessableEntity
}
return ErrorBody{Code: "internal", Message: "Something went wrong."}, http.StatusInternalServerError
}
// badRequest reports a malformed request body or parameter.
func badRequest(c *gin.Context, msg string) {
c.AbortWithStatusJSON(http.StatusBadRequest, ErrorBody{Code: "bad_request", Message: msg, CorrelationID: CorrelationID(c)})
}
package server
import (
"log/slog"
"net/http"
"github.com/gin-gonic/gin"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/domain"
"github.com/sweetrpg/initiative-api/entitlements"
)
type gameSystemHandlers struct {
systems *data.SystemRepo
ent *entitlements.Client
}
// setupGameSystemHandlers registers the read-only game-system resource. It sits in the group that
// accepts integration credentials (read scope).
func setupGameSystemHandlers(g *gin.RouterGroup, systems *data.SystemRepo, ent *entitlements.Client) {
h := gameSystemHandlers{systems, ent}
g.GET("/game-systems", privateNoStore, h.list)
g.GET("/game-systems/:id", privateNoStore, h.get)
}
// privateNoStore keeps a shared cache from serving one caller's entitlement-dependent answer to
// another.
func privateNoStore(c *gin.Context) { c.Header("Cache-Control", "private, no-store") }
// gameSystemView is what a client receives: the definition and nothing about how it is stored
// (no revision, hash or audit fields).
type gameSystemView struct {
ID string `json:"id"`
Name string `json:"name"`
Family string `json:"family"`
Aliases []string `json:"aliases"`
Gated bool `json:"gated"`
Fields []data.TrackerField `json:"fields"`
}
func viewOf(s data.GameSystem) gameSystemView {
aliases, fields := s.Aliases, s.Fields
if aliases == nil {
aliases = []string{}
}
if fields == nil {
fields = []data.TrackerField{}
}
return gameSystemView{ID: s.ID, Name: s.Name, Family: s.Family, Aliases: aliases, Gated: s.Gated, Fields: fields}
}
// gameSystemFields are the names ?fields= may select.
var gameSystemFields = []string{"id", "name", "family", "aliases", "gated", "fields"}
// entitled reports whether the caller holds initiative.game_systems_extra, under policy. degraded
// is true when the answer is not a fresh known value (outage, no value, or an expired cached one).
// A list passes FailOpen: anything short of a known "yes" reads as "no" and the caller sees No
// System rather than an error. A get of a gated system passes FailClosed: an outage is the typed
// 503, with no stale fallback, so a revoked or newly bought flag is never answered from cache.
func (h gameSystemHandlers) entitled(c *gin.Context, policy entitlements.Policy) (flag, degraded bool, err error) {
res, err := checkerFor(c, h.ent).Check(c.Request.Context(), domain.KeyGameSystemsExtra, policy)
switch {
case err != nil:
return false, true, err
case res.Degraded:
return false, true, entitlements.ErrUnavailable
}
return res.Flag, res.Stale, nil
}
func (h gameSystemHandlers) list(c *gin.Context) {
q, ok := parseQuery(c, map[string]string{"gated": typeBool})
if !ok || !checkFields(c, q.Fields, gameSystemFields) {
return
}
fields := q.Fields
q.Fields = nil
entitled, degraded, err := h.entitled(c, entitlements.FailOpen)
if err != nil {
slog.WarnContext(c.Request.Context(), "entitlement unknown for the game-system list; listing No System only", "error", err)
}
if degraded {
c.Header("X-Entitlements-Degraded", "true")
}
page, err := h.systems.ListAvailable(c.Request.Context(), q, entitled)
if err != nil {
writeError(c, err, nil)
return
}
items := make([]map[string]any, 0, len(page.Items))
for _, s := range page.Items {
items = append(items, projectMap(toMap(viewOf(s)), fields, "id"))
}
c.JSON(http.StatusOK, gin.H{"items": items, "next_cursor": page.NextCursor})
}
// get resolves an ID or an alias (a Foundry system ID, for one). A gated system is refused to a
// caller without the flag with the typed entitlement error; when the flag cannot be read at all
// the answer is the typed 503, never a guess.
func (h gameSystemHandlers) get(c *gin.Context) {
fields, ok := fieldsOf(c, gameSystemFields)
if !ok {
return
}
id := c.Param("id")
if err := data.CheckText("game system id", id, data.MaxNameLen); err != nil {
writeError(c, data.ErrNotFound, nil)
return
}
sys, err := h.systems.Get(c.Request.Context(), id)
if err != nil {
writeError(c, err, nil)
return
}
if sys.Gated {
entitled, _, err := h.entitled(c, entitlements.FailClosed)
if err != nil {
writeError(c, err, nil)
return
}
if !entitled {
writeError(c, &domain.EntitlementRequiredError{Key: domain.KeyGameSystemsExtra}, nil)
return
}
}
c.JSON(http.StatusOK, projectMap(toMap(viewOf(sys)), fields, "id"))
}
// Package server wires the HTTP routes and middleware.
package server
import (
"github.com/gin-gonic/gin"
"github.com/sweetrpg/authz-client.go/authz"
"github.com/sweetrpg/initiative-api/constants"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/domain"
"github.com/sweetrpg/initiative-api/entitlements"
"github.com/sweetrpg/initiative-api/events/stream"
"github.com/sweetrpg/initiative-api/relations"
)
// Services are the dependencies the resource handlers need.
type Services struct {
// Ready is the deep dependency check behind /status/health; nil reports healthy.
Ready *Readiness
Authz *authz.Client
Entitlements *entitlements.Client
// OwnerLimits records the owner's entitlement values for integration credentials, which carry
// no user bearer. Optional; without it a credential's limit checks fail closed.
OwnerLimits *data.OwnerEntitlements
Themes *domain.Themes
Credentials *domain.Credentials
Limits *domain.Limits
Locks *domain.Locks
Rosters *domain.Rosters
Encounters *domain.Encounters
Sessions *domain.Sessions
// ChangeRequests handles player-submitted combatant changes; it needs Encounters and Sessions.
ChangeRequests *domain.ChangeRequests
Systems *data.SystemRepo
// Relations answers session authorization checks (PADR-0035). Without it every session
// request fails closed with 503.
Relations *relations.Client
// Streams and Hub serve the event stream; without both there is no /streams route. Stream
// holds its transport settings.
Streams *domain.Streams
Hub *stream.Hub
// NotificationPrefs holds each member's muted notice types per session.
NotificationPrefs *domain.NotificationPrefs
Stream StreamOptions
// Leases counts a user's open streams across pods; without it the per-user cap is not applied.
Leases *data.StreamLeases
}
// ProtectedGroup returns a route group whose every route requires a bearer token that auth-api
// verifies (signature, expiry, iss, aud) for this service and whose user holds one of roles
// (default: RoleUser). Missing or invalid tokens get 401, a missing role gets 403. Routes added
// to the group inherit this; handlers never repeat the check. The caller's own token is the only
// credential, per PADR-0037 (no service tokens), and a client application identity alone is a 401.
func ProtectedGroup(r *gin.Engine, client *authz.Client, creds *domain.Credentials, roles ...string) *gin.RouterGroup {
if len(roles) == 0 {
roles = []string{authz.RoleUser}
}
return r.Group("", typedErrors(), authenticate(creds, authz.RequireAnyRole(client, constants.ServiceName, roles...)))
}
// SetupHandlers registers every route group on r.
func SetupHandlers(r *gin.Engine, s Services) {
setupStatusHandlers(r, s.Ready)
g := ProtectedGroup(r, s.Authz, s.Credentials)
g.Use(limitBody(), withOrigin(), withOwnerRecord(s.OwnerLimits), withChecker(s.Entitlements), withGate(s.Relations))
if s.Limits != nil || s.Locks != nil {
g.Use(reconcileLimits(s))
}
u := g.Group("", userOnly)
setupThemeHandlers(u, s.Themes, s.Entitlements)
setupEntitlementHandlers(u, s)
setupCredentialHandlers(u, s)
setupActiveItemHandlers(u, s)
if s.Sessions != nil {
setupSessionHandlers(u, s.Sessions)
}
if s.NotificationPrefs != nil {
setupNotificationPrefHandlers(u, s.NotificationPrefs)
}
if s.Encounters != nil && s.Sessions != nil {
setupEncounterViewHandlers(u, s.Encounters, s.Sessions)
}
if s.ChangeRequests != nil {
setupChangeRequestHandlers(u, s.ChangeRequests)
}
if s.Encounters != nil {
setupEncounterHandlers(g, s.Encounters, s.Rosters, s.Entitlements)
}
if s.Rosters != nil {
setupRosterHandlers(g, s.Rosters, s.Entitlements)
}
if s.Systems != nil {
setupGameSystemHandlers(g, s.Systems, s.Entitlements)
}
setupRefHandlers(g, s.Encounters)
if s.Streams != nil && s.Hub != nil {
setupStreamHandlers(r, u, s)
}
if s.Credentials != nil {
setupAdminCredentialHandlers(ProtectedGroup(r, s.Authz, nil, authz.RoleAdmin), s.Credentials)
}
}
// withGate gives the data layer the relation checker, and the domain auth-api's session surface,
// both with the caller's own bearer token (PADR-0037), so session data can be authorized and
// membership tuples written per request. A nil client leaves ctx without a gate, which
// makes session data fail closed.
func withGate(c *relations.Client) gin.HandlerFunc {
return func(ctx *gin.Context) {
if c != nil {
token := authz.Token(ctx)
rc := data.WithGate(ctx.Request.Context(), c, token)
ctx.Request = ctx.Request.WithContext(domain.WithAuthority(rc, c, token))
}
ctx.Next()
}
}
package server
import (
"log/slog"
"net/http"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/sweetrpg/authz-client.go/authz"
"github.com/sweetrpg/initiative-api/domain"
"github.com/sweetrpg/initiative-api/entitlements"
)
// reconcileEvery bounds how often one owner's limits are re-read on ordinary requests. The
// entitlements client caches each key for its own TTL, so a changed limit applies within the
// larger of the two.
var reconcileEvery = 30 * time.Second
// reconcileLimits applies the owner's current limits (inactive items beyond a reduced limit,
// reactivation on a raise) on requests carrying the owner's own bearer: that bearer is the only
// way to read their entitlements (PADR-0037), so integration credentials are skipped. A delete or
// a revoke that succeeded reconciles at once, because it freed a place. Failures never fail the
// request.
func reconcileLimits(s Services) gin.HandlerFunc {
var last sync.Map // owner -> time of the last reconcile
run := func(c *gin.Context, owner string) {
last.Store(owner, time.Now())
chk := checkerFor(c, s.Entitlements)
if s.Limits != nil {
if err := s.Limits.Reconcile(c.Request.Context(), owner, chk); err != nil {
slog.WarnContext(c.Request.Context(), "limit reconcile failed", "error", err)
}
}
if s.Locks != nil {
if err := s.Locks.Reconcile(c.Request.Context(), owner, chk); err != nil {
slog.WarnContext(c.Request.Context(), "game-system lock reconcile failed", "error", err)
}
}
}
return func(c *gin.Context) {
// The handler (and the authenticate middleware before it) set the viewer, so read it first.
owner := authz.Viewer(c)
_, viaCredential := c.Get(credentialContextKey)
if owner == "" || viaCredential {
c.Next()
return
}
// Before the handler, so the response already reflects the current limits.
if prev, ok := last.Load(owner); !ok || time.Since(prev.(time.Time)) >= reconcileEvery {
run(c, owner)
}
c.Next()
// A delete or revoke freed a place; an inactive item takes it now.
if c.Writer.Status() < http.StatusMultipleChoices &&
(c.Request.Method == http.MethodDelete || strings.HasSuffix(c.FullPath(), "/revoke")) {
run(c, owner)
}
}
}
// withChecker puts the caller's entitlement checker on the request context for domain rules that
// check a flag mid-operation, such as choosing a gated game system.
func withChecker(ent *entitlements.Client) gin.HandlerFunc {
return func(c *gin.Context) {
c.Request = c.Request.WithContext(domain.WithChecker(c.Request.Context(), checkerFor(c, ent)))
c.Next()
}
}
type activeItemBody struct {
IDs []string `json:"ids"`
}
func setupActiveItemHandlers(g *gin.RouterGroup, s Services) {
if s.Limits == nil {
return
}
g.PUT("/entitlements/active/:kind", func(c *gin.Context) {
var b activeItemBody
if !bindJSON(c, &b) {
return
}
if b.IDs == nil {
badRequest(c, "request body must be JSON with an ids array")
return
}
active, err := s.Limits.Choose(c.Request.Context(), authz.Viewer(c), c.Param("kind"), b.IDs, checkerFor(c, s.Entitlements))
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusOK, gin.H{"kind": c.Param("kind"), "active": active})
})
}
package server
import (
"context"
"github.com/gin-gonic/gin"
"github.com/sweetrpg/authz-client.go/authz"
"github.com/sweetrpg/initiative-api/domain"
"github.com/sweetrpg/initiative-api/entitlements"
)
// requireRoom refuses a create that would exceed the caller's entitled count for key. Inactive
// items count toward the total owned, and an entitlements outage fails closed (503), while edits
// of existing items never come here (initiative-entitlement-gating, "Limit reached", "Creating
// while over the limit", "Service unavailable behavior"). It writes the error and returns false.
func requireRoom(c *gin.Context, ent *entitlements.Client, key string, owned func(ctx context.Context, owner string) (int64, error)) bool {
owner := authz.Viewer(c)
res, err := checkerFor(c, ent).Check(c.Request.Context(), key, entitlements.FailClosed)
if err != nil {
writeError(c, err, nil)
return false
}
n, err := owned(c.Request.Context(), owner)
if err != nil {
writeError(c, err, nil)
return false
}
if n >= int64(res.Limit) {
writeError(c, &domain.EntitlementError{Key: key, Limit: res.Limit}, nil)
return false
}
return true
}
package server
import (
"context"
"log/slog"
"time"
"github.com/gin-gonic/gin"
sloggin "github.com/samber/slog-gin"
"github.com/sweetrpg/initiative-api/constants"
"go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
)
// Middleware is the chain every request runs first, in the order that matters: correlation, then
// ticket redaction (before anything that logs the URL), then the access log, recovery and tracing.
// main and the tests build the router from this one list, so the order cannot drift apart.
func Middleware(accessLog *slog.Logger, requestTimeout time.Duration) []gin.HandlerFunc {
return []gin.HandlerFunc{
Correlation(),
RedactTicket(),
sloggin.New(accessLog),
gin.Recovery(),
RequestDeadline(requestTimeout),
otelgin.Middleware(constants.ServiceName),
}
}
// RequestDeadline bounds every request but the event stream's upgrade (a long-lived connection by
// design) to d, so a slow dependency cannot hold a request, and the goroutine behind it, open. A
// store call that runs past it returns context.DeadlineExceeded, which the error mapper reports as
// 503 timeout.
func RequestDeadline(d time.Duration) gin.HandlerFunc {
return func(c *gin.Context) {
if d <= 0 || isStreamUpgrade(c.Request) {
c.Next()
return
}
ctx, cancel := context.WithTimeout(c.Request.Context(), d)
defer cancel()
c.Request = c.Request.WithContext(ctx)
c.Next()
}
}
package server
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/sweetrpg/authz-client.go/authz"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/domain"
)
type prefHandlers struct{ svc *domain.NotificationPrefs }
// setupNotificationPrefHandlers registers a member's per-session notification mutes. They sit in
// the user-only group: preferences belong to a person.
func setupNotificationPrefHandlers(g *gin.RouterGroup, svc *domain.NotificationPrefs) {
h := prefHandlers{svc}
g.GET("/sessions/:id/notification-preferences", h.get)
g.PUT("/sessions/:id/notification-preferences", h.put)
}
type prefBody struct {
Muted []string `json:"muted"`
}
func writePrefs(c *gin.Context, muted []string, err error) {
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusOK, gin.H{"muted": muted, "types": data.NoticeTypes})
}
func (h prefHandlers) get(c *gin.Context) {
muted, err := h.svc.Get(c.Request.Context(), authz.Viewer(c), c.Param("id"))
writePrefs(c, muted, err)
}
func (h prefHandlers) put(c *gin.Context) {
var b prefBody
if !bindJSON(c, &b) {
return
}
muted, err := h.svc.Set(c.Request.Context(), authz.Viewer(c), c.Param("id"), b.Muted)
writePrefs(c, muted, err)
}
package server
import (
"github.com/gin-gonic/gin"
"github.com/sweetrpg/authz-client.go/authz"
"github.com/sweetrpg/initiative-api/data"
)
// clientIDHeader carries the opaque id a client picks for itself, so it can recognise the echo of
// its own writes on the event stream.
const clientIDHeader = "X-Initiative-Client-Id"
// withOrigin records who is writing, on the request context, for the event each commit emits. A
// client id that is not [A-Za-z0-9._-]{1,64} is ignored, never rejected.
func withOrigin() gin.HandlerFunc {
return func(c *gin.Context) {
o := data.Origin{Kind: data.OriginUser, ActorID: authz.Viewer(c)}
if _, viaCredential := c.Get(credentialContextKey); viaCredential {
o.Kind = data.OriginIntegration
}
if id := c.GetHeader(clientIDHeader); data.ValidClientID(id) {
o.ClientID = id
}
c.Request = c.Request.WithContext(data.WithOrigin(c.Request.Context(), o))
c.Next()
}
}
package server
import (
"strconv"
"strings"
"github.com/gin-gonic/gin"
"github.com/sweetrpg/initiative-api/data"
)
// Field value types for filter coercion. A query string carries only text, so the resource says
// which of its filterable fields are not strings.
const (
typeBool = "bool"
typeInt = "int"
)
// parseQuery reads the list conventions (PADR-0030) from the request: limit, cursor, sort
// (comma-separated field names, a leading "-" for descending), fields (projection), and
// filter[field]=value, filter[field][in]=a,b, filter[field][contains]=text. It checks shapes only;
// which fields may be filtered, sorted or projected is decided by the resource's data.Spec in the
// data layer, which rejects anything else. types names the non-string filterable fields. It writes
// the 400 and returns false on a malformed value.
func parseQuery(c *gin.Context, types map[string]string) (data.Query, bool) {
q := data.Query{Cursor: c.Query("cursor")}
if v := c.Query("limit"); v != "" {
n, err := strconv.Atoi(v)
if err != nil || n < 1 {
badRequest(c, "limit must be a positive integer")
return q, false
}
q.Limit = n
}
for _, f := range splitList(c.Query("sort")) {
q.Sort = append(q.Sort, data.SortKey{Field: strings.TrimPrefix(f, "-"), Desc: strings.HasPrefix(f, "-")})
}
q.Fields = splitList(c.Query("fields"))
for key, values := range c.Request.URL.Query() {
if !strings.HasPrefix(key, "filter") {
continue
}
field, op, ok := filterKey(key)
if !ok {
badRequest(c, "unrecognized filter parameter "+key+": use filter[field], filter[field][in] or filter[field][contains]")
return q, false
}
f := data.Filter{Field: field, Op: op}
for _, raw := range values {
parts := []string{raw}
if op == data.OpIn {
parts = splitList(raw)
}
for _, p := range parts {
v, ok := coerce(p, types[field])
if !ok {
badRequest(c, "filter "+field+" has a value of the wrong type")
return q, false
}
f.Values = append(f.Values, v)
}
}
q.Filters = append(q.Filters, f)
}
return q, true
}
// filterKey parses filter[field] and filter[field][op].
func filterKey(key string) (field string, op data.Op, ok bool) {
rest, found := strings.CutPrefix(key, "filter[")
if !found {
return "", "", false
}
field, rest, found = strings.Cut(rest, "]")
if !found || field == "" {
return "", "", false
}
switch rest {
case "":
return field, data.OpEq, true
case "[in]":
return field, data.OpIn, true
case "[contains]":
return field, data.OpContains, true
}
return "", "", false
}
func coerce(s, typ string) (any, bool) {
switch typ {
case typeBool:
b, err := strconv.ParseBool(s)
return b, err == nil
case typeInt:
n, err := strconv.ParseInt(s, 10, 64)
return n, err == nil
}
return s, true
}
func splitList(s string) []string {
var out []string
for _, p := range strings.Split(s, ",") {
if p = strings.TrimSpace(p); p != "" {
out = append(out, p)
}
}
return out
}
package server
import (
"strings"
"github.com/gin-gonic/gin"
"github.com/gomodule/redigo/redis"
"github.com/sweetrpg/api-core.go/ratelimit"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/domain"
)
// resolvedCredentialKey holds the credential the limiter step already looked up, so authenticate
// does not query it twice.
const resolvedCredentialKey = "ratelimit.credential"
// RateLimit returns the per-client limiter (PADR-0036) preceded by a step that sets its client key.
// The shared limiter keys on X-API-Key, else the IP, and both are caller-controlled, so that step
// never lets the caller's header through:
// - a bearer that resolves to a live integration credential is keyed by the credential's ID,
// so credentials are distinct clients;
// - everything else, including a made-up "ic_" secret, is keyed by IP.
func RateLimit(pool *redis.Pool, opts ratelimit.Options, creds *domain.Credentials) []gin.HandlerFunc {
return []gin.HandlerFunc{typedErrors(), clientKey(creds), ratelimit.Middleware(pool, opts)}
}
func clientKey(creds *domain.Credentials) gin.HandlerFunc {
return func(c *gin.Context) {
c.Request.Header.Del("X-API-Key")
secret, _ := strings.CutPrefix(c.GetHeader("Authorization"), "Bearer ")
if creds != nil && strings.HasPrefix(secret, domain.SecretPrefix) {
// Any failure (unknown, revoked, store error) leaves the IP key; authenticate then
// rejects or reports it.
if cred, err := creds.Authenticate(c.Request.Context(), secret); err == nil {
c.Set(resolvedCredentialKey, cred)
c.Request.Header.Set("X-API-Key", "cred:"+cred.ID)
}
}
c.Next()
}
}
func resolvedCredential(c *gin.Context) (data.IntegrationCredential, bool) {
v, ok := c.Get(resolvedCredentialKey)
if !ok {
return data.IntegrationCredential{}, false
}
cred, ok := v.(data.IntegrationCredential)
return cred, ok
}
package server
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/sweetrpg/authz-client.go/authz"
"github.com/sweetrpg/initiative-api/domain"
)
// setupRefHandlers serves the integration lookup of the caller's combatants by external reference.
func setupRefHandlers(g *gin.RouterGroup, enc *domain.Encounters) {
g.GET("/combatants", func(c *gin.Context) {
items, err := enc.FindByExternalRef(c.Request.Context(), authz.Viewer(c), c.Query("ref_key"), c.Query("ref_value"))
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusOK, gin.H{"items": items})
})
}
package server
import (
"strconv"
"strings"
"github.com/gin-gonic/gin"
)
// revisionOf reads the revision a write is based on: If-Match (`"r3"` or `r3`, the form the
// encounter ETag takes), else the `revision` query parameter, else bodyRevision (the `revision` field
// of a JSON body, 0 when absent). A write without one is a 400, so a client can never overwrite
// blindly (PADR "Revisioned writes"). It writes the 400 and returns false when none is usable.
func revisionOf(c *gin.Context, bodyRevision int64) (int64, bool) {
if h := strings.TrimSpace(c.GetHeader("If-Match")); h != "" {
h = strings.TrimPrefix(strings.Trim(h, `"`), "r")
if n, err := strconv.ParseInt(h, 10, 64); err == nil && n >= 1 {
return n, true
}
badRequest(c, "If-Match must be the revision as returned in ETag")
return 0, false
}
if v := c.Query("revision"); v != "" {
if n, err := strconv.ParseInt(v, 10, 64); err == nil && n >= 1 {
return n, true
}
badRequest(c, "revision must be a positive integer")
return 0, false
}
if bodyRevision >= 1 {
return bodyRevision, true
}
badRequest(c, "the current revision is required: send If-Match, a revision query parameter, or a revision field")
return 0, false
}
package server
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"github.com/sweetrpg/authz-client.go/authz"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/domain"
"github.com/sweetrpg/initiative-api/entitlements"
)
type rosterHandlers struct {
svc *domain.Rosters
ent *entitlements.Client
}
// setupRosterHandlers registers rosters and their characters. They sit in the group that accepts
// integration credentials (read scope for GET, write scope otherwise) because integrations use the
// same endpoints as first-party clients.
func setupRosterHandlers(g *gin.RouterGroup, svc *domain.Rosters, ent *entitlements.Client) {
h := rosterHandlers{svc, ent}
g.GET("/rosters", h.list)
g.POST("/rosters", h.create)
g.GET("/rosters/:id", h.get)
g.PATCH("/rosters/:id", h.update)
g.DELETE("/rosters/:id", h.remove)
g.POST("/rosters/:id/characters", h.addCharacter)
g.PUT("/rosters/:id/characters/:cid", h.replaceCharacter)
g.DELETE("/rosters/:id/characters/:cid", h.removeCharacter)
}
type characterBody struct {
Name string `json:"name"`
Kind string `json:"kind"`
Notes string `json:"notes"`
Health map[string]int `json:"health"`
ExternalRefs map[string]string `json:"external_refs"`
}
func (b characterBody) character() data.Character {
return data.Character{Name: b.Name, Kind: b.Kind, Notes: b.Notes, Health: b.Health, ExternalRefs: b.ExternalRefs}
}
// rosterCreate is the body of POST /rosters.
type rosterCreate struct {
Name *string `json:"name"`
Favorite *bool `json:"favorite"`
Characters []characterBody `json:"characters"`
}
// rosterPatch is the body of PATCH /rosters/:id. Characters change through their own routes.
type rosterPatch struct {
Revision int64 `json:"revision"`
Name *string `json:"name"`
Favorite *bool `json:"favorite"`
}
// conflict writes err, attaching the roster's current state to a revision conflict so the client
// can merge and retry.
func (h rosterHandlers) conflict(c *gin.Context, err error, id string) {
var current any
if errors.Is(err, data.ErrRevisionConflict) {
if r, gerr := h.svc.Get(c.Request.Context(), authz.Viewer(c), id); gerr == nil {
current = r
}
}
writeError(c, err, current)
}
func (h rosterHandlers) list(c *gin.Context) {
q, ok := parseQuery(c, map[string]string{"favorite": typeBool})
if !ok || !checkFields(c, q.Fields, data.RosterSpec.Projectable) {
return
}
// The projection is applied to the rendered roster, so an unselected field is absent rather
// than a zero value.
fields := q.Fields
q.Fields = nil
page, err := h.svc.List(c.Request.Context(), authz.Viewer(c), q)
if err != nil {
writeError(c, err, nil)
return
}
items := make([]map[string]any, 0, len(page.Items))
for _, r := range page.Items {
items = append(items, projectMap(toMap(r), fields, "id", "revision"))
}
c.JSON(http.StatusOK, gin.H{"items": items, "next_cursor": page.NextCursor})
}
func (h rosterHandlers) get(c *gin.Context) {
fields, ok := fieldsOf(c, data.RosterSpec.Projectable)
if !ok {
return
}
r, err := h.svc.Load(c.Request.Context(), authz.Viewer(c), c.Param("id"))
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusOK, projectMap(toMap(r), fields, "id", "revision"))
}
func (h rosterHandlers) create(c *gin.Context) {
var b rosterCreate
if !bindJSON(c, &b) {
return
}
if b.Name == nil {
badRequest(c, "request body must be a JSON roster with a name")
return
}
if !requireRoom(c, h.ent, domain.KeySavedRosters, h.svc.Count) {
return
}
chars := make([]data.Character, 0, len(b.Characters))
for _, ch := range b.Characters {
chars = append(chars, ch.character())
}
owner := authz.Viewer(c)
r, err := h.svc.Create(c.Request.Context(), owner, owner, *b.Name, b.Favorite != nil && *b.Favorite, chars)
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusCreated, r)
}
func (h rosterHandlers) update(c *gin.Context) {
var b rosterPatch
if !bindJSON(c, &b) {
return
}
rev, ok := revisionOf(c, b.Revision)
if !ok {
return
}
owner, id := authz.Viewer(c), c.Param("id")
cur, err := h.svc.Load(c.Request.Context(), owner, id)
if err != nil {
writeError(c, err, nil)
return
}
name, fav := cur.Name, cur.Favorite
if b.Name != nil {
name = *b.Name
}
if b.Favorite != nil {
fav = *b.Favorite
}
r, err := h.svc.Rename(c.Request.Context(), owner, owner, id, rev, name, fav)
if err != nil {
h.conflict(c, err, id)
return
}
c.JSON(http.StatusOK, r)
}
func (h rosterHandlers) remove(c *gin.Context) {
rev, ok := revisionOf(c, 0)
if !ok {
return
}
owner := authz.Viewer(c)
if err := h.svc.Delete(c.Request.Context(), owner, owner, c.Param("id"), rev); err != nil {
h.conflict(c, err, c.Param("id"))
return
}
c.Status(http.StatusNoContent)
}
// characterRequest is a character body plus the roster revision it is based on.
type characterRequest struct {
characterBody
Revision int64 `json:"revision"`
}
func (h rosterHandlers) addCharacter(c *gin.Context) {
var b characterRequest
if !bindJSON(c, &b) {
return
}
rev, ok := revisionOf(c, b.Revision)
if !ok {
return
}
owner := authz.Viewer(c)
r, err := h.svc.AddCharacter(c.Request.Context(), owner, owner, c.Param("id"), rev, b.character())
if err != nil {
h.conflict(c, err, c.Param("id"))
return
}
c.JSON(http.StatusCreated, r)
}
func (h rosterHandlers) replaceCharacter(c *gin.Context) {
var b characterRequest
if !bindJSON(c, &b) {
return
}
rev, ok := revisionOf(c, b.Revision)
if !ok {
return
}
owner := authz.Viewer(c)
r, err := h.svc.UpdateCharacter(c.Request.Context(), owner, owner, c.Param("id"), rev, c.Param("cid"), b.character())
if err != nil {
h.conflict(c, err, c.Param("id"))
return
}
c.JSON(http.StatusOK, r)
}
func (h rosterHandlers) removeCharacter(c *gin.Context) {
rev, ok := revisionOf(c, 0)
if !ok {
return
}
owner := authz.Viewer(c)
r, err := h.svc.RemoveCharacter(c.Request.Context(), owner, owner, c.Param("id"), rev, c.Param("cid"))
if err != nil {
h.conflict(c, err, c.Param("id"))
return
}
c.JSON(http.StatusOK, r)
}
package server
import (
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/sweetrpg/authz-client.go/authz"
"github.com/sweetrpg/initiative-api/domain"
)
type sessionHandlers struct{ svc *domain.Sessions }
// setupSessionHandlers registers the session routes. They sit in the user-only group: session
// membership belongs to a person, so an integration credential cannot reach it.
func setupSessionHandlers(g *gin.RouterGroup, svc *domain.Sessions) {
h := sessionHandlers{svc}
g.POST("/sessions", h.create)
g.GET("/sessions", h.list)
g.POST("/sessions/join", h.join)
g.GET("/sessions/:id", h.get)
g.PATCH("/sessions/:id", h.update)
g.DELETE("/sessions/:id", h.remove)
g.POST("/sessions/:id/leave", h.leave)
g.GET("/sessions/:id/members", h.members)
g.PATCH("/sessions/:id/members/:user", h.setRole)
g.DELETE("/sessions/:id/members/:user", h.removeMember)
g.POST("/sessions/:id/invites", h.createInvite)
g.GET("/sessions/:id/invites", h.invites)
g.DELETE("/sessions/:id/invites/:invite", h.revokeInvite)
g.GET("/sessions/:id/requests", h.requests)
g.POST("/sessions/:id/requests/:request/approve", h.approve)
g.POST("/sessions/:id/requests/:request/reject", h.reject)
g.GET("/sessions/:id/blocks", h.blocks)
g.POST("/sessions/:id/blocks", h.block)
g.DELETE("/sessions/:id/blocks/:user", h.unblock)
}
func (h sessionHandlers) create(c *gin.Context) {
var b struct {
Name string `json:"name"`
AllowCoGMEncounters bool `json:"allow_co_gm_create_encounter"`
}
if !bindJSON(c, &b) {
return
}
s, err := h.svc.CreateWith(c.Request.Context(), authz.Viewer(c), b.Name, b.AllowCoGMEncounters)
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusCreated, s)
}
func (h sessionHandlers) list(c *gin.Context) {
q, ok := pageQuery(c)
if !ok {
return
}
page, err := h.svc.List(c.Request.Context(), authz.Viewer(c), q)
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusOK, gin.H{"items": page.Items, "next_cursor": page.NextCursor})
}
func (h sessionHandlers) get(c *gin.Context) {
s, err := h.svc.Get(c.Request.Context(), authz.Viewer(c), c.Param("id"))
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusOK, s)
}
// update changes the session's name or its co-GM encounter-creation setting. GM only.
func (h sessionHandlers) update(c *gin.Context) {
var b struct {
Name *string `json:"name"`
AllowCoGMEncounters *bool `json:"allow_co_gm_create_encounter"`
Revision int64 `json:"revision"`
}
if !bindJSON(c, &b) {
return
}
rev, ok := revisionOf(c, b.Revision)
if !ok {
return
}
s, err := h.svc.Update(c.Request.Context(), authz.Viewer(c), c.Param("id"), rev, domain.SessionChanges{Name: b.Name, AllowCoGMEncounters: b.AllowCoGMEncounters})
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusOK, s)
}
func (h sessionHandlers) remove(c *gin.Context) {
rev, err := strconv.ParseInt(c.Query("revision"), 10, 64)
if err != nil || rev < 1 {
badRequest(c, "revision query parameter is required")
return
}
if err := h.svc.Delete(c.Request.Context(), authz.Viewer(c), c.Param("id"), rev); err != nil {
writeError(c, err, nil)
return
}
c.Status(http.StatusNoContent)
}
func (h sessionHandlers) leave(c *gin.Context) {
if err := h.svc.Leave(c.Request.Context(), authz.Viewer(c), c.Param("id")); err != nil {
writeError(c, err, nil)
return
}
c.Status(http.StatusNoContent)
}
func writePage(c *gin.Context, items any, next string, err error) {
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusOK, gin.H{"items": items, "next_cursor": next})
}
func (h sessionHandlers) members(c *gin.Context) {
q, ok := pageQuery(c)
if !ok {
return
}
p, err := h.svc.Members(c.Request.Context(), authz.Viewer(c), c.Param("id"), q)
writePage(c, p.Items, p.NextCursor, err)
}
func (h sessionHandlers) invites(c *gin.Context) {
q, ok := pageQuery(c)
if !ok {
return
}
p, err := h.svc.Invites(c.Request.Context(), authz.Viewer(c), c.Param("id"), q)
writePage(c, p.Items, p.NextCursor, err)
}
func (h sessionHandlers) requests(c *gin.Context) {
q, ok := pageQuery(c)
if !ok {
return
}
p, err := h.svc.Requests(c.Request.Context(), authz.Viewer(c), c.Param("id"), c.Query("status") != "all", q)
writePage(c, p.Items, p.NextCursor, err)
}
func (h sessionHandlers) blocks(c *gin.Context) {
q, ok := pageQuery(c)
if !ok {
return
}
p, err := h.svc.Blocks(c.Request.Context(), authz.Viewer(c), c.Param("id"), q)
writePage(c, p.Items, p.NextCursor, err)
}
func (h sessionHandlers) setRole(c *gin.Context) {
var b struct {
Role string `json:"role"`
}
if !bindJSON(c, &b) {
return
}
m, err := h.svc.SetRole(c.Request.Context(), authz.Viewer(c), c.Param("id"), c.Param("user"), b.Role)
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusOK, m)
}
func (h sessionHandlers) removeMember(c *gin.Context) {
if err := h.svc.Remove(c.Request.Context(), authz.Viewer(c), c.Param("id"), c.Param("user")); err != nil {
writeError(c, err, nil)
return
}
c.Status(http.StatusNoContent)
}
// createInvite returns the code once; only its hash is stored.
func (h sessionHandlers) createInvite(c *gin.Context) {
var b struct {
TTLHours int `json:"ttl_hours"`
}
if c.Request.ContentLength != 0 {
if !bindJSON(c, &b) {
return
}
if b.TTLHours < 0 {
badRequest(c, "request body must be JSON with an optional ttl_hours")
return
}
}
in, code, err := h.svc.CreateInvite(c.Request.Context(), authz.Viewer(c), c.Param("id"), time.Duration(b.TTLHours)*time.Hour)
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusCreated, gin.H{"invite": in, "code": code})
}
func (h sessionHandlers) revokeInvite(c *gin.Context) {
in, err := h.svc.RevokeInvite(c.Request.Context(), authz.Viewer(c), c.Param("id"), c.Param("invite"))
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusOK, in)
}
// join answers with the request's id and state only: a pending requester sees no session data.
func (h sessionHandlers) join(c *gin.Context) {
var b struct {
Code string `json:"code"`
}
if !bindJSON(c, &b) {
return
}
if b.Code == "" {
badRequest(c, "request body must be JSON with a code")
return
}
jr, err := h.svc.Join(c.Request.Context(), authz.Viewer(c), b.Code)
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusAccepted, gin.H{"id": jr.ID, "status": jr.Status})
}
func (h sessionHandlers) approve(c *gin.Context) {
var b struct {
Role string `json:"role"`
}
if !bindJSON(c, &b) {
return
}
m, err := h.svc.Approve(c.Request.Context(), authz.Viewer(c), c.Param("id"), c.Param("request"), b.Role)
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusOK, m)
}
func (h sessionHandlers) reject(c *gin.Context) {
var b struct {
Reason string `json:"reason"`
}
if !bindJSON(c, &b) {
return
}
jr, err := h.svc.Reject(c.Request.Context(), authz.Viewer(c), c.Param("id"), c.Param("request"), b.Reason)
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusOK, jr)
}
func (h sessionHandlers) block(c *gin.Context) {
var b struct {
UserID string `json:"user_id"`
}
if !bindJSON(c, &b) {
return
}
if err := h.svc.Block(c.Request.Context(), authz.Viewer(c), c.Param("id"), b.UserID); err != nil {
writeError(c, err, nil)
return
}
c.Status(http.StatusNoContent)
}
func (h sessionHandlers) unblock(c *gin.Context) {
if err := h.svc.Unblock(c.Request.Context(), authz.Viewer(c), c.Param("id"), c.Param("user")); err != nil {
writeError(c, err, nil)
return
}
c.Status(http.StatusNoContent)
}
package server
import (
"context"
"log/slog"
"net/http"
"sync"
"time"
"github.com/gin-gonic/gin"
apicores "github.com/sweetrpg/api-core.go/server"
"github.com/sweetrpg/api-core.go/vo"
)
// Ping is the shallow liveness and readiness probe target (PADR-0017).
//
// @Summary Ping
// @Tags status
// @Produce json
// @Success 200 {object} vo.PingResponseVO
// @Router /status/ping [get]
func ping(c *gin.Context) {
c.JSON(http.StatusOK, apicores.PingHandler())
}
// Readiness is the deep dependency check behind /status/health. PADR-0017 keeps it off the
// readiness and liveness probes (both use /status/ping): it is for operators and dashboards and
// must not gate routing or restarts. Each check runs under a timeout, and the answer is cached for ttl, so probes from every kubelet
// and load balancer cost the dependency one call per ttl, not one each.
type Readiness struct {
checks []Check
ttl time.Duration
timeout time.Duration
now func() time.Time
mu sync.Mutex
at time.Time
messages []string
}
// Check is one dependency's liveness test.
type Check struct {
Name string
Fn func(ctx context.Context) error
}
// NewReadiness builds the check set; a zero ttl or timeout takes 5s and 2s.
func NewReadiness(ttl, timeout time.Duration, checks ...Check) *Readiness {
if ttl <= 0 {
ttl = 5 * time.Second
}
if timeout <= 0 {
timeout = 2 * time.Second
}
return &Readiness{checks: checks, ttl: ttl, timeout: timeout, now: time.Now}
}
// Problems returns one message per failing check (none when ready), from the cache when it is
// younger than the ttl. It holds a lock while it checks, so concurrent probes share one round.
func (r *Readiness) Problems(ctx context.Context) []string {
r.mu.Lock()
defer r.mu.Unlock()
if !r.at.IsZero() && r.now().Sub(r.at) < r.ttl {
return r.messages
}
msgs := []string{}
// The answer is cached for every caller, so a probe that hangs up must not cancel the check
// and leave a false "unavailable" for the next ttl.
base := context.WithoutCancel(ctx)
for _, ch := range r.checks {
cctx, cancel := context.WithTimeout(base, r.timeout)
if err := ch.Fn(cctx); err != nil {
slog.ErrorContext(ctx, "health check failed", "check", ch.Name, "error", err)
msgs = append(msgs, ch.Name+": unavailable") // the detail stays in the log, not the response
}
cancel()
}
r.at, r.messages = r.now(), msgs
return msgs
}
// Health is the deep dependency check. It answers 503 while a dependency is down. Probes use
// /status/ping (PADR-0017), so this never removes a pod from the Service or restarts it.
//
// @Summary Health check
// @Tags status
// @Produce json
// @Success 200 {object} vo.HealthResponseVO
// @Failure 503 {object} vo.HealthResponseVO
// @Router /status/health [get]
func health(r *Readiness) gin.HandlerFunc {
return func(c *gin.Context) {
msgs := []string{}
if r != nil {
msgs = r.Problems(c.Request.Context())
}
status := http.StatusOK
if len(msgs) > 0 {
status = http.StatusServiceUnavailable
}
c.JSON(status, vo.HealthResponseVO{Messages: msgs, Errors: len(msgs)})
}
}
func setupStatusHandlers(r *gin.Engine, ready *Readiness) {
r.GET("/status/ping", ping)
r.GET("/status/health", health(ready))
}
package server
import (
"context"
cryptorand "crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"log/slog"
"net/http"
"net/url"
"path"
"strings"
"sync/atomic"
"time"
"github.com/coder/websocket"
"github.com/gin-gonic/gin"
"github.com/sweetrpg/authz-client.go/authz"
"github.com/sweetrpg/initiative-api/constants"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/domain"
"github.com/sweetrpg/initiative-api/events/stream"
)
// WebSocket close codes the service sends (application range 4000-4999).
const (
CloseCredentialRevoked websocket.StatusCode = 4001 // the credential that opened the stream is gone
CloseMembershipChanged websocket.StatusCode = 4002 // access changed or ended; reconnect to find out
CloseSlowConsumer websocket.StatusCode = 4003 // the client fell behind; reconnect and refetch
CloseMaxAge websocket.StatusCode = 4004 // the connection reached its maximum age
maxGuardErrors = 3
maxRecheckFailures = 3 // failed membership re-checks in a row that end a stream
checkTimeout = 2 * time.Second
readLimit = 1024
streamBuffer = 64 // events buffered per connection
writeTimeout = 10 * time.Second
pongTimeout = 60 * time.Second
ticketQuery = "ticket"
ticketKey = "initiative.stream_ticket"
ticketPresentKey = "initiative.stream_ticket_present"
redactedKey = "initiative.stream_redacted"
)
// StreamOptions are the transport settings of the event stream.
type StreamOptions struct {
// AllowedOrigins are host patterns (path.Match) a browser's Origin may match; no Origin header
// is always allowed.
AllowedOrigins []string
// MaxAge ends a stream after this long (default 1h); Heartbeat is the interval of the
// application heartbeat and the protocol ping (default 20s).
MaxAge, Heartbeat time.Duration
// RecheckInterval is how often a stream re-reads its membership and credential (default 5s,
// never above Heartbeat).
RecheckInterval time.Duration
// Buffer is how many events a stream may fall behind before it is closed (default 64).
Buffer int
// beforeWrite, when set by a test, runs before each event is written.
beforeWrite func()
// onServe, when set by a test, runs as serve starts, holding a pod slot.
onServe func()
// afterRenew, when set by a test, runs after each seat renewal attempt.
afterRenew func()
// ConcurrentMax is the most streams one user may hold (Services.Leases counts them, with
// seats lasting LeaseTTL unless renewed and kept Grace after a drop); MaxPerPod is this pod's
// cap, answered with close code 1013. Zero disables the cap.
ConcurrentMax, CredentialMax, MaxPerPod int
// DevicesMax is the most connections one member may hold to a session (zero: the default).
DevicesMax int
LeaseTTL, Grace time.Duration
// Pod names this pod on its seats.
Pod string
}
func (o StreamOptions) buffer() int {
if o.Buffer > 0 {
return o.Buffer
}
return streamBuffer
}
// devicesMax is the most connections one member may hold to a session.
func (o StreamOptions) devicesMax() int {
if o.DevicesMax > 0 {
return o.DevicesMax
}
return constants.DefaultSessionDevicesMax
}
func (o StreamOptions) leaseTTL() time.Duration {
if o.LeaseTTL > 0 {
return o.LeaseTTL
}
return constants.DefaultStreamLeaseTTL
}
func (o StreamOptions) maxAge() time.Duration {
if o.MaxAge > 0 {
return o.MaxAge
}
return constants.DefaultStreamMaxAge
}
func (o StreamOptions) recheck() time.Duration {
d := o.RecheckInterval
if d <= 0 {
d = constants.DefaultStreamRecheckInterval
}
return min(d, o.heartbeat())
}
// The re-check runs inline in the connection's loop, so a slow client delays it. The loop is held
// by one write at a time and a due re-check runs before every event write, so stallAllowance is the
// most one pass can hold it: a heartbeat write that the client takes up to writeTimeout to accept,
// then a seat renewal bounded by checkTimeout. A write that does not complete in writeTimeout ends
// the stream anyway.
const stallAllowance = writeTimeout + checkTimeout
// RevocationBound is the longest a stream stays open after its member is removed, demoted or
// blocked, when the eviction itself is lost (the evictor or the relay is down) and the client keeps
// up: one re-check interval to the next re-check, plus the time that check may take.
func (o StreamOptions) RevocationBound() time.Duration { return o.recheck() + checkTimeout }
// StalledBound is RevocationBound when the client's socket is slow enough to hold the loop for a
// whole heartbeat write and renewal first.
func (o StreamOptions) StalledBound() time.Duration { return o.RevocationBound() + stallAllowance }
// FaultBound is RevocationBound when the store cannot answer the re-checks: the stream closes at
// the third consecutive failed one, so each of three intervals may also spend a full check timeout.
func (o StreamOptions) FaultBound() time.Duration {
return maxRecheckFailures * (o.recheck() + checkTimeout)
}
// StalledFaultBound is FaultBound with a slow client.
func (o StreamOptions) StalledFaultBound() time.Duration { return o.FaultBound() + stallAllowance }
// renewTimeout bounds one seat renewal, which holds the connection's loop.
func (o StreamOptions) renewTimeout() time.Duration { return min(o.heartbeat()/2, checkTimeout) }
func (o StreamOptions) heartbeat() time.Duration {
if o.Heartbeat > 0 {
return o.Heartbeat
}
return constants.DefaultStreamHeartbeat
}
// RedactTicket takes the stream ticket out of the request URL before anything logs it, and keeps
// it for the stream handler. The ticket is single-use and short-lived, so a leaked one is mostly
// harmless, but it should never reach an access log.
func RedactTicket() gin.HandlerFunc {
return func(c *gin.Context) {
c.Set(redactedKey, true)
if c.Request.URL.RawQuery != "" {
q := c.Request.URL.Query()
if q.Has(ticketQuery) {
for _, t := range q[ticketQuery] { // the first non-empty value is the ticket
if t != "" {
c.Set(ticketKey, t)
break
}
}
c.Set(ticketPresentKey, true)
q.Del(ticketQuery)
c.Request.URL.RawQuery = q.Encode()
c.Request.RequestURI = c.Request.URL.RequestURI() // Recovery and tracing read this one
}
}
c.Next()
}
}
type streamHandlers struct {
svc Services
opts StreamOptions
open *atomic.Int64 // connections on this pod
// refusing bounds the refusals in flight (each holds a socket for the close handshake); nil is
// unbounded.
refusing chan struct{}
}
// maxRefusals is how many "pod full" closes may be in flight at once.
const maxRefusals = 32
// setupStreamHandlers registers POST /streams/tickets (user bearer only) on u, and GET /streams on
// r: with ticket= it opens the stream for that ticket, with no ticket it needs the caller's bearer
// (a user's, or an integration credential with the read scope) like every other route.
func setupStreamHandlers(r *gin.Engine, u *gin.RouterGroup, s Services) {
h := streamHandlers{svc: s, opts: s.Stream, open: new(atomic.Int64), refusing: make(chan struct{}, maxRefusals)}
u.POST("/streams/tickets", h.mint)
g := r.Group("", h.ticketGate, typedErrors(), authenticate(s.Credentials, authz.RequireAnyRole(s.Authz, constants.ServiceName, authz.RoleUser)))
g.Use(withOrigin(), withGate(s.Relations))
g.GET("/streams", h.bearerStream)
}
type ticketBody struct {
SessionID string `json:"session_id"`
EncounterID string `json:"encounter_id"`
ClientID string `json:"client_id"`
// Scope is empty for an encounter stream or "user" for the user-level stream.
Scope string `json:"scope"`
}
// scopeUser asks for the user-level stream.
const scopeUser = "user"
func (h streamHandlers) mint(c *gin.Context) {
var b ticketBody
if !bindJSON(c, &b) {
return
}
if b.Scope != "" && b.Scope != scopeUser {
writeError(c, data.ErrInvalid, nil)
return
}
ticket, ttl, err := h.svc.Streams.Mint(c.Request.Context(), authz.Viewer(c), domain.TicketRequest{SessionID: b.SessionID, EncounterID: b.EncounterID, ClientID: b.ClientID, UserLevel: b.Scope == scopeUser})
if err != nil {
writeError(c, err, nil)
return
}
c.Header("Cache-Control", "no-store")
c.JSON(http.StatusCreated, gin.H{"ticket": ticket, "expires_in": int(ttl.Seconds())})
}
// originAllowed applies the same rule the upgrade does, before a ticket is spent on it.
func (o StreamOptions) originAllowed(r *http.Request) bool {
origin := r.Header.Get("Origin")
if origin == "" {
return true
}
u, err := url.Parse(origin)
if err != nil || u.Host == "" {
return false
}
if strings.EqualFold(u.Host, r.Host) {
return true
}
for _, p := range o.AllowedOrigins {
if ok, _ := path.Match(strings.ToLower(p), strings.ToLower(u.Host)); ok {
return true
}
}
return false
}
// ticketGate serves a request that carries a ticket; any other request continues to the bearer
// chain. The ticket stands in for a bearer the browser cannot send on an upgrade.
func (h streamHandlers) ticketGate(c *gin.Context) {
if _, ok := c.Get(redactedKey); !ok && c.Request.URL.Query().Has(ticketQuery) {
// RedactTicket was not installed ahead of the access log: refuse rather than serve a
// request whose ticket may already be in a log. Wiring bug, not a client error.
slog.ErrorContext(c.Request.Context(), "a stream ticket arrived but RedactTicket is not installed; refusing")
c.AbortWithStatusJSON(http.StatusInternalServerError, ErrorBody{Code: "internal", Message: "Something went wrong.", CorrelationID: CorrelationID(c)})
return
}
if present, _ := c.Get(ticketPresentKey); present != true {
c.Next()
return
}
ticket := c.GetString(ticketKey)
if ticket == "" { // ?ticket= with no value
c.Abort()
writeError(c, domain.ErrTicketInvalid, nil)
return
}
c.Abort()
if !h.opts.originAllowed(c.Request) {
c.JSON(http.StatusForbidden, ErrorBody{Code: "origin_not_allowed", Message: "This origin may not open a stream.", CorrelationID: CorrelationID(c)})
return
}
ctx := c.Request.Context()
// Peek reads the ticket without spending it, so a junk ticket is a plain 401 (no upgrade, no
// socket held) and a refused connect leaves a real one redeemable.
claim, err := h.svc.Streams.Peek(ctx, ticket)
if err != nil {
writeError(c, err, nil)
return
}
release, ok := h.admit()
if !ok {
h.refuseFull(c)
return
}
defer release()
a := serveArgs{
actor: claim.UserID, session: claim.SessionID, encounter: claim.EncounterID, clientID: claim.ClientID,
userLevel: claim.UserLevel,
authorize: func(ctx context.Context) (data.Viewer, error) { return h.svc.Streams.View(ctx, claim) },
redeem: func(ctx context.Context) error { _, err := h.svc.Streams.Redeem(ctx, ticket); return err },
}
h.serve(c, a)
}
// bearerStream opens the stream for a caller authenticated by bearer: authorized exactly as the
// REST reads are (OpenFGA through the caller's own token, fail closed).
func (h streamHandlers) bearerStream(c *gin.Context) {
if !h.opts.originAllowed(c.Request) {
c.JSON(http.StatusForbidden, ErrorBody{Code: "origin_not_allowed", Message: "This origin may not open a stream.", CorrelationID: CorrelationID(c)})
return
}
actor, session, enc := authz.Viewer(c), c.Query("session_id"), c.Query("encounter_id")
userLevel := c.Query("scope") == scopeUser
if userLevel && (session != "" || enc != "") {
writeError(c, data.ErrInvalid, nil)
return
}
if _, viaCredential := c.Get(credentialContextKey); viaCredential && (session != "" || userLevel) {
// Session data is authorized with the caller's own bearer (PADR-0037); a credential has none.
userOnly(c)
return
}
client := c.Query("client_id")
if client == "" {
client = c.GetHeader(clientIDHeader)
}
if !data.ValidClientID(client) {
client = "" // ignored, never rejected, like the origin of a write
}
a := serveArgs{actor: actor, session: session, encounter: enc, clientID: client, userLevel: userLevel}
a.authorize = func(ctx context.Context) (data.Viewer, error) {
return h.svc.Streams.BearerView(ctx, actor, session, enc)
}
if id, ok := c.Get(credentialContextKey); ok {
a.guard = liveGuard(func(ctx context.Context) (bool, error) {
return h.svc.Credentials.Live(ctx, id.(string))
})
}
if id, ok := c.Get(credentialContextKey); ok {
a.credentialID = id.(string)
}
release, ok := h.admit()
if !ok {
h.refuseFull(c)
return
}
defer release()
h.serve(c, a)
}
var errCredentialRevoked = errors.New("credential revoked")
// liveGuard turns a liveness read into a heartbeat guard. A revoked credential ends the stream at
// once. A store error keeps it until maxGuardErrors checks in a row have failed, then closes it as
// revoked: fail closed, but not on one blip, so a missed revocation is bounded by that many
// heartbeats. A successful read resets the count.
func liveGuard(live func(context.Context) (bool, error)) func(context.Context) error {
var failed int
return func(ctx context.Context) error {
ok, err := live(ctx)
switch {
case err != nil:
if failed++; failed >= maxGuardErrors {
return errCredentialRevoked
}
case !ok:
return errCredentialRevoked
default:
failed = 0
}
return nil
}
}
type serveArgs struct {
actor, session, encounter, clientID string
// userLevel opens the user-level stream: addressed events only, no viewer, no encounter heads.
userLevel bool
authorize func(context.Context) (data.Viewer, error)
// guard runs on every re-check, besides the membership re-check; an error ends the stream.
guard func(context.Context) error
// credentialID is set when an integration credential opened the stream; its seats count in
// their own bucket. seat is the seat serve takes and releases.
credentialID string
seat seat
// redeem spends the ticket that opened the stream; nil for a bearer stream. It runs after the
// seat is taken, so a refused connect never spends it.
redeem func(context.Context) error
}
// serve opens a pending subscription, authorizes, grants, takes a seat, spends the ticket (if any),
// and upgrades. Everything that can fail does so before the upgrade, as an ordinary HTTP error.
// The seat comes after authorization so a caller who may not see the scope costs the lease store
// nothing, and the ticket after the seat so a refusal leaves it redeemable.
func (h streamHandlers) serve(c *gin.Context, a serveArgs) {
if hook := h.opts.onServe; hook != nil {
hook()
}
ctx := c.Request.Context()
defer h.svc.Hub.Track()() // outlives the connection's close below, so Drain sees the close frame sent
released := false
defer func() {
if !released {
h.release(a.seat, false) // refused before the upgrade
}
}()
if h.svc.Hub.ShuttingDown() {
writeError(c, stream.ErrShuttingDown, nil)
return
}
sub, v, err := h.openSub(ctx, a)
if err != nil {
writeError(c, err, nil)
return
}
defer sub.Close()
if a.seat, err = h.takeSeat(ctx, a); err != nil {
writeError(c, err, nil)
return
}
if a.redeem != nil {
if err = a.redeem(ctx); err != nil { // lost a race for the ticket
writeError(c, err, nil)
return
}
}
var heads []domain.Head
var truncated bool
if !a.userLevel {
if heads, truncated, err = h.svc.Streams.Heads(ctx, v, a.encounter); err != nil {
writeError(c, err, nil)
return
}
}
keep := false // only a dropped connection keeps its seat for the grace period
released = true
defer func() { h.release(a.seat, keep) }()
conn, err := websocket.Accept(c.Writer, c.Request, &websocket.AcceptOptions{OriginPatterns: h.opts.AllowedOrigins})
if err != nil {
return // Accept has answered
}
defer func() { _ = conn.CloseNow() }()
conn.SetReadLimit(readLimit) // clients send nothing but control frames
cl := &connection{h: h, conn: conn, sub: sub, v: v, a: a}
if err := cl.hello(ctx, heads, truncated); err != nil {
return
}
keep = cl.run(ctx)
}
// openSub registers the stream's subscription: a user-level one needs no scope, any other is
// authorized and granted its viewer. A subscription returned with an error is already closed.
func (h streamHandlers) openSub(ctx context.Context, a serveArgs) (*stream.Subscription, data.Viewer, error) {
if a.userLevel {
return h.svc.Hub.OpenUser(a.actor, h.opts.buffer()), data.Viewer{}, nil
}
sub := h.svc.Hub.Open(a.session, a.actor, a.encounter, h.opts.buffer())
v, err := a.authorize(ctx)
if err == nil {
err = sub.Grant(v)
if errors.Is(err, stream.ErrEvicted) && sub.ServerStopping() {
err = stream.ErrShuttingDown // closed by Shutdown after the check above
} else if errors.Is(err, stream.ErrEvicted) || errors.Is(err, stream.ErrViewer) {
err = data.ErrNotMember
}
}
if err != nil {
sub.Close()
return nil, v, err
}
return sub, v, nil
}
type headFrame struct {
Type string `json:"type"`
domain.Head
}
// seat is a stream's place in the lease store; the zero seat means none is kept (no store, or no
// cap configured).
type seat struct {
lease data.StreamLease
held bool
// session is the seat in the session's bucket, which counts a member's connections against the
// member and device limits; sessionHeld is false for a private or user-level stream and a
// credential.
session data.StreamLease
sessionHeld bool
}
// takeSeat gives the stream a seat in its bucket: the user's for a user's stream, the credential's
// own for an integration credential's, so a leaked or runaway credential cannot lock its owner out
// of their own stream. Over the cap is data.ErrStreamLimit; a store failure is
// data.ErrStreamUnavailable and a new connect fails closed (streams already open stay up).
func (h streamHandlers) takeSeat(ctx context.Context, a serveArgs) (seat, error) {
if h.svc.Leases == nil {
return seat{}, nil
}
var s seat
max, bucket := h.opts.ConcurrentMax, "user:"+a.actor
if a.credentialID != "" {
max, bucket = h.opts.CredentialMax, "cred:"+a.credentialID
}
if max > 0 {
l := data.StreamLease{ID: randomHex(), Bucket: bucket, UserID: a.actor, SessionID: a.session, ClientID: a.clientID, Pod: h.opts.Pod}
if err := h.svc.Leases.Acquire(ctx, l, h.opts.leaseTTL(), max); err != nil {
return seat{}, h.seatError(ctx, err)
}
s.lease, s.held = l, true
}
if err := h.takeSessionSeat(ctx, a, &s); err != nil {
h.release(s, false) // give the user's seat back: this connect did not happen
return seat{}, err
}
return s, nil
}
func (h streamHandlers) seatError(ctx context.Context, err error) error {
if errors.Is(err, data.ErrStreamUnavailable) {
slog.WarnContext(ctx, "the stream seat store is unavailable; refusing a new stream", "error", err)
}
return err
}
// takeSessionSeat gives a session stream its seat in the session's bucket, across pods. A member's
// connections share one member seat: the session holds at most the member limit of distinct
// non-GM members (the number that holds the roster, 7.12a; the GM holds no member seat), and one
// member, the GM included, at most DevicesMax connections. A stream that is not in a session needs
// no seat. The seat shares the user seat's client id, so a member who drops and reconnects within
// the grace period keeps it even if others joined in the meantime. Nothing ends a live connection
// because the limit fell: only a new member is counted against it.
func (h streamHandlers) takeSessionSeat(ctx context.Context, a serveArgs, s *seat) error {
if a.session == "" || a.userLevel || a.credentialID != "" {
return nil
}
limit, counted, err := h.svc.Streams.ConnectLimit(ctx, a.actor, a.session)
if err != nil {
return err
}
l := data.StreamLease{ID: randomHex(), Bucket: "session:" + a.session, UserID: a.actor, SessionID: a.session, ClientID: a.clientID, Pod: h.opts.Pod, Counted: counted}
if err := h.svc.Leases.AcquireSession(ctx, l, h.opts.leaseTTL(), limit, h.opts.devicesMax()); err != nil {
if errors.Is(err, data.ErrStreamLimit) {
return &domain.EntitlementError{Key: domain.KeyMembersPerSession, Limit: limit}
}
return h.seatError(ctx, err)
}
s.session, s.sessionHeld = l, true
return nil
}
// release ends a seat. Only a connection that dropped (keep) holds it for the grace period; one the
// server ended, or that never opened, frees it now.
func (h streamHandlers) release(s seat, keep bool) {
for _, l := range []struct {
lease data.StreamLease
held bool
}{{s.lease, s.held}, {s.session, s.sessionHeld}} {
if !l.held {
continue
}
if err := h.svc.Leases.Release(context.Background(), l.lease, h.opts.Grace, keep); err != nil {
slog.Warn("releasing a stream seat failed; it lapses on its own", "seat", l.lease.ID, "error", err)
}
}
}
// admit takes one of this pod's connection slots, or reports the pod full. A compare-and-swap, so a
// refused attempt never counts.
func (h streamHandlers) admit() (release func(), ok bool) {
max := int64(h.opts.MaxPerPod)
if max <= 0 {
return func() {}, true
}
for {
n := h.open.Load()
if n >= max {
return nil, false
}
if h.open.CompareAndSwap(n, n+1) {
return func() { h.open.Add(-1) }, true
}
}
}
// refuseFull answers a holder of a real ticket (or an authenticated caller) on a full pod: it
// accepts the upgrade and closes with 1013, since a browser cannot read the status of a refused
// upgrade. The ticket was only peeked, so the client keeps it. Each refusal holds a socket for the
// close handshake, so they are bounded; past the bound the answer is a plain 503.
func (h streamHandlers) refuseFull(c *gin.Context) {
if h.refusing != nil {
select {
case h.refusing <- struct{}{}:
defer func() { <-h.refusing }()
default:
c.Header("Retry-After", "5")
c.AbortWithStatusJSON(http.StatusServiceUnavailable, ErrorBody{Code: "pod_full", Message: "This server is full; try again shortly.", CorrelationID: CorrelationID(c)})
return
}
}
conn, err := websocket.Accept(c.Writer, c.Request, &websocket.AcceptOptions{OriginPatterns: h.opts.AllowedOrigins})
if err != nil {
return
}
_ = conn.Close(websocket.StatusTryAgainLater, "pod full")
}
func randomHex() string {
b := make([]byte, 12)
_, _ = cryptorand.Read(b)
return hex.EncodeToString(b)
}
type connection struct {
h streamHandlers
conn *websocket.Conn
sub *stream.Subscription
v data.Viewer
a serveArgs
renewFailing bool
recheckFailures int
}
func (cl *connection) write(ctx context.Context, v any) error {
b, err := json.Marshal(v)
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(ctx, writeTimeout)
defer cancel()
return cl.conn.Write(ctx, websocket.MessageText, b)
}
// scopeOf names what a stream follows: the addressed events of the user, or encounter state.
func scopeOf(a serveArgs) string {
if a.userLevel {
return scopeUser
}
return "encounter"
}
// hello sends the hello frame and one head frame per encounter in scope. They carry only what the
// viewer's own views carry: the scope they asked for and each visible encounter's revision (GM) or
// view tag.
func (cl *connection) hello(ctx context.Context, heads []domain.Head, truncated bool) error {
opts := cl.h.opts
if err := cl.write(ctx, gin.H{
"type": "hello", "scope": scopeOf(cl.a), "session_id": cl.a.session, "encounter_id": cl.a.encounter, "client_id": cl.a.clientID,
"heartbeat_seconds": int(opts.heartbeat().Seconds()), "max_age_seconds": int(opts.maxAge().Seconds()), "heads_truncated": truncated,
}); err != nil {
return err
}
for _, hd := range heads {
if err := cl.write(ctx, headFrame{"head", hd}); err != nil {
return err
}
}
return nil
}
// run delivers events until the stream ends for any reason, and closes with the code that says
// why. Client frames are read and discarded (CloseRead), so pongs reset the idle watch.
func (cl *connection) run(ctx context.Context) (keepSeat bool) {
ctx = cl.conn.CloseRead(ctx)
tick := time.NewTicker(cl.h.opts.heartbeat())
defer tick.Stop()
recheck := time.NewTicker(cl.h.opts.recheck())
defer recheck.Stop()
maxAge := time.NewTimer(cl.h.opts.maxAge())
defer maxAge.Stop()
pings := make(chan struct{}, 1)
go cl.pinger(ctx, pings)
for {
select {
case ev, ok := <-cl.sub.C:
if !ok {
if cl.sub.ServerStopping() {
_ = cl.conn.Close(websocket.StatusGoingAway, "server restarting")
} else if cl.sub.Overflowed() {
_ = cl.conn.Close(CloseSlowConsumer, "slow consumer")
} else {
_ = cl.conn.Close(CloseMembershipChanged, "membership changed")
}
return
}
// A backlog of events must not postpone the re-check: it goes first whenever it is due,
// so the loop is held by at most one write (see stallAllowance).
if code, why, due := cl.recheckIfDue(ctx, recheck); due && code != 0 {
_ = cl.conn.Close(code, why)
return false
}
if hook := cl.h.opts.beforeWrite; hook != nil {
hook()
}
if cl.sub.Ended() { // evicted: what is still buffered must not be written
continue
}
if cl.write(ctx, ev) != nil {
return true
}
case <-recheck.C:
if code, why := cl.check(ctx); code != 0 {
_ = cl.conn.Close(code, why)
return false
}
case <-tick.C:
if cl.write(ctx, gin.H{"type": "heartbeat"}) != nil {
return true
}
select {
case pings <- struct{}{}:
default:
}
cl.renew(ctx)
case <-maxAge.C:
_ = cl.conn.Close(CloseMaxAge, "maximum connection age")
return false
case <-ctx.Done():
return true
}
}
}
// renew keeps the stream's seat alive, bounded so a hung store cannot stall the heartbeat, the
// membership re-check or the credential guard. A failure leaves the stream up; the seat lapses after
// the lease TTL if renewals keep failing, and the next connect for that user then has room.
func (cl *connection) renew(ctx context.Context) {
st := cl.a.seat
if !st.held && !st.sessionHeld {
return
}
ctx, cancel := context.WithTimeout(ctx, cl.h.opts.renewTimeout()) // both seats share it: part of stallAllowance
defer cancel()
var err error
for _, l := range []struct {
lease data.StreamLease
held bool
}{{st.lease, st.held}, {st.session, st.sessionHeld}} {
if l.held {
err = errors.Join(err, cl.h.svc.Leases.Renew(ctx, l.lease, cl.h.opts.leaseTTL()))
}
}
if err != nil && !cl.renewFailing {
slog.WarnContext(ctx, "renewing a stream seat failed; it lapses if renewals keep failing", "seat", st.lease.ID, "error", err)
}
cl.renewFailing = err != nil // log the first failure of a run, not every heartbeat
if hook := cl.h.opts.afterRenew; hook != nil {
hook()
}
}
// check re-reads what the stream was authorized on, every recheck interval. Failed reads fail
// closed after three in a row, for membership and for a credential alike: a store that cannot say
// whether the member is still allowed does not keep the stream open for the maximum age. Each
// failed membership read is logged with the running count. The stream closes with
// CloseMembershipChanged, and a connect (which re-reads the member's record) is refused while the
// store is down. A user-level stream has no membership to re-check: each notice it receives is
// checked for membership instead. A credential-backed stream runs the credential guard.
func (cl *connection) check(ctx context.Context) (websocket.StatusCode, string) {
// Each read has its own timeout: a slow credential guard must not leave the membership
// re-check an expired context, which would count as a failed re-check. (A credential stream has
// no session and a session stream has no credential, so one of the two is a no-op.)
if cl.a.guard != nil {
gctx, cancel := context.WithTimeout(ctx, checkTimeout)
err := cl.a.guard(gctx)
cancel()
if errors.Is(err, errCredentialRevoked) {
return CloseCredentialRevoked, "credential revoked"
}
}
rctx, cancel := context.WithTimeout(ctx, checkTimeout) // a hung store must not stall delivery
defer cancel()
err := cl.h.svc.Streams.Recheck(rctx, cl.v)
switch {
case errors.Is(err, domain.ErrAccessChanged):
return CloseMembershipChanged, "membership changed"
case errors.Is(err, domain.ErrRecheckFailed):
cl.recheckFailures++
slog.WarnContext(ctx, "re-checking a stream's membership failed", "failures", cl.recheckFailures, "of", maxRecheckFailures, "error", err)
if cl.recheckFailures >= maxRecheckFailures {
return CloseMembershipChanged, "membership could not be verified"
}
default:
cl.recheckFailures = 0
}
return 0, ""
}
// recheckIfDue runs the re-check if its tick is waiting, without blocking.
func (cl *connection) recheckIfDue(ctx context.Context, t *time.Ticker) (code websocket.StatusCode, why string, due bool) {
select {
case <-t.C:
code, why = cl.check(ctx)
return code, why, true
default:
return 0, "", false
}
}
// pinger sends a protocol ping per request and ends the connection when no pong comes back.
func (cl *connection) pinger(ctx context.Context, pings <-chan struct{}) {
for {
select {
case <-pings:
pctx, cancel := context.WithTimeout(ctx, pongTimeout)
err := cl.conn.Ping(pctx)
cancel()
if err != nil && ctx.Err() == nil {
_ = cl.conn.Close(websocket.StatusGoingAway, "idle")
return
}
case <-ctx.Done():
return
}
}
}
package server
import (
"context"
"errors"
"log/slog"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/sweetrpg/authz-client.go/authz"
"github.com/sweetrpg/initiative-api/data"
"github.com/sweetrpg/initiative-api/domain"
"github.com/sweetrpg/initiative-api/entitlements"
)
// userChecker binds an entitlements client to one request's user and bearer token.
type userChecker struct {
client *entitlements.Client
user, token string
// record holds the user's last first-party entitlement values. A first-party check writes
// them; an integration credential, which has no user bearer to call entitlements-api with
// (PADR-0034, PADR-0037), reads them instead (viaCredential).
record *data.OwnerEntitlements
viaCredential bool
}
func (u userChecker) Check(ctx context.Context, key string, p entitlements.Policy) (entitlements.Result, error) {
if u.viaCredential {
return u.recorded(ctx, key)
}
res, err := u.client.Check(ctx, u.user, u.token, key, p)
if err == nil && u.record != nil && !res.Stale && !res.Degraded {
u.remember(ctx, res)
}
return res, err
}
// recorded answers from the owner's record. With no record of the key, or one older than the max
// age, it fails closed with ErrLimitsNotSynced: the owner has to use the app once with their own sign-in.
func (u userChecker) recorded(ctx context.Context, key string) (entitlements.Result, error) {
if u.record == nil {
return entitlements.Result{}, domain.ErrLimitsNotSynced
}
e, err := u.record.Get(ctx, u.user, key)
if errors.Is(err, data.ErrNotFound) || (err == nil && !u.record.Fresh(e)) {
return entitlements.Result{}, domain.ErrLimitsNotSynced
}
if err != nil {
return entitlements.Result{}, err
}
return entitlements.Result{Key: e.Key, Type: e.Type, Flag: e.Flag, Limit: e.Limit}, nil
}
// remember records a fresh first-party result. It is best effort: a failed write keeps the old
// record and is logged, and the request goes on.
func (u userChecker) remember(ctx context.Context, results ...entitlements.Result) {
entries := make([]data.OwnerEntitlement, 0, len(results))
for _, r := range results {
entries = append(entries, data.OwnerEntitlement{Key: r.Key, Type: r.Type, Limit: r.Limit, Flag: r.Flag})
}
if err := u.record.Record(ctx, u.user, entries...); err != nil {
slog.WarnContext(ctx, "recording owner entitlements failed", "error", err)
}
}
const ownerRecordKey = "initiative.ownerEntitlements"
// withOwnerRecord puts the owner-entitlement record on the request, for checkerFor.
func withOwnerRecord(rec *data.OwnerEntitlements) gin.HandlerFunc {
return func(c *gin.Context) {
if rec != nil {
c.Set(ownerRecordKey, rec)
}
c.Next()
}
}
func checkerFor(c *gin.Context, client *entitlements.Client) domain.Checker {
rec, _ := c.Get(ownerRecordKey)
r, _ := rec.(*data.OwnerEntitlements)
_, viaCredential := c.Get(credentialContextKey)
return userChecker{client: client, user: authz.Viewer(c), token: authz.Token(c), record: r, viaCredential: viaCredential}
}
type themeBody struct {
Name string `json:"name"`
Style string `json:"style"`
MainColor string `json:"main_color"`
Accent1Color string `json:"accent1_color"`
Accent2Color string `json:"accent2_color"`
Background1Color string `json:"background1_color"`
Background2Color string `json:"background2_color"`
PrimaryFontName string `json:"primary_font_name"`
SecondaryFontName string `json:"secondary_font_name"`
BackgroundImage string `json:"background_image"`
}
type themePatchBody struct {
Revision int64 `json:"revision"`
Name *string `json:"name"`
Style *string `json:"style"`
MainColor *string `json:"main_color"`
Accent1Color *string `json:"accent1_color"`
Accent2Color *string `json:"accent2_color"`
Background1Color *string `json:"background1_color"`
Background2Color *string `json:"background2_color"`
PrimaryFontName *string `json:"primary_font_name"`
SecondaryFontName *string `json:"secondary_font_name"`
BackgroundImage *string `json:"background_image"`
}
type themeHandlers struct {
svc *domain.Themes
ent *entitlements.Client
}
func setupThemeHandlers(g *gin.RouterGroup, svc *domain.Themes, ent *entitlements.Client) {
h := themeHandlers{svc: svc, ent: ent}
g.GET("/themes", h.list)
g.GET("/themes/packaged", h.packaged)
g.GET("/themes/:id", h.get)
g.POST("/themes", h.create)
g.PATCH("/themes/:id", h.update)
g.DELETE("/themes/:id", h.remove)
}
func (h themeHandlers) list(c *gin.Context) {
q := data.Query{Cursor: c.Query("cursor")}
if v := c.Query("limit"); v != "" {
n, err := strconv.Atoi(v)
if err != nil || n < 1 {
badRequest(c, "limit must be a positive integer")
return
}
q.Limit = n
}
page, err := h.svc.List(c.Request.Context(), authz.Viewer(c), q)
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusOK, gin.H{"items": page.Items, "next_cursor": page.NextCursor})
}
func (h themeHandlers) packaged(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"items": h.svc.Packaged()})
}
func (h themeHandlers) get(c *gin.Context) {
t, err := h.svc.Get(c.Request.Context(), authz.Viewer(c), c.Param("id"))
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusOK, t)
}
func (h themeHandlers) create(c *gin.Context) {
var b themeBody
if !bindJSON(c, &b) {
return
}
owner := authz.Viewer(c)
t, err := h.svc.Create(c.Request.Context(), owner, owner, domain.ThemeInput{
Name: b.Name, Style: b.Style, MainColor: b.MainColor, Accent1Color: b.Accent1Color,
Accent2Color: b.Accent2Color, Background1Color: b.Background1Color, Background2Color: b.Background2Color,
PrimaryFontName: b.PrimaryFontName, SecondaryFontName: b.SecondaryFontName, BackgroundImage: b.BackgroundImage,
}, checkerFor(c, h.ent))
if err != nil {
writeError(c, err, nil)
return
}
c.JSON(http.StatusCreated, t)
}
func (h themeHandlers) update(c *gin.Context) {
var b themePatchBody
if !bindJSON(c, &b) {
return
}
if b.Revision < 1 {
badRequest(c, "request body must be JSON with the theme's current revision")
return
}
owner := authz.Viewer(c)
t, err := h.svc.Update(c.Request.Context(), owner, owner, c.Param("id"), b.Revision, domain.ThemePatch{
Name: b.Name, Style: b.Style, MainColor: b.MainColor, Accent1Color: b.Accent1Color,
Accent2Color: b.Accent2Color, Background1Color: b.Background1Color, Background2Color: b.Background2Color,
PrimaryFontName: b.PrimaryFontName, SecondaryFontName: b.SecondaryFontName, BackgroundImage: b.BackgroundImage,
})
if err != nil {
writeError(c, err, t)
return
}
c.JSON(http.StatusOK, t)
}
func (h themeHandlers) remove(c *gin.Context) {
rev, err := strconv.ParseInt(c.Query("revision"), 10, 64)
if err != nil || rev < 1 {
badRequest(c, "revision query parameter is required")
return
}
owner := authz.Viewer(c)
if err := h.svc.Delete(c.Request.Context(), owner, owner, c.Param("id"), rev); err != nil {
writeError(c, err, nil)
return
}
c.Status(http.StatusNoContent)
}
package server
import (
"bytes"
"encoding/json"
"net/http"
"github.com/gin-gonic/gin"
)
// typedErrors rewrites the {"error", "message"} bodies that shared middleware writes (authz-client.go
// for 401/403/503, api-core's rate limiter for 429/503) into this API's typed {"code", "message",
// "correlation_id"} shape, so a client reads one error format. Bodies that already have a code pass
// through, and the library's error string becomes the code (the token one, invalid_token, is
// unauthorized like the credential 401). It wraps the writer once per request.
func typedErrors() gin.HandlerFunc {
return func(c *gin.Context) {
if _, done := c.Writer.(*typedWriter); !done {
c.Writer = &typedWriter{ResponseWriter: c.Writer, c: c}
}
c.Next()
}
}
type typedWriter struct {
gin.ResponseWriter
c *gin.Context
}
func (w *typedWriter) Write(b []byte) (int, error) {
switch w.Status() {
case http.StatusUnauthorized, http.StatusForbidden, http.StatusTooManyRequests, http.StatusServiceUnavailable:
var old struct {
Error string `json:"error"`
Message string `json:"message"`
Code *string `json:"code"`
}
if json.Unmarshal(bytes.TrimSpace(b), &old) == nil && old.Error != "" && old.Code == nil {
code := old.Error
if code == "invalid_token" {
code = "unauthorized"
}
out, err := json.Marshal(ErrorBody{Code: code, Message: old.Message, CorrelationID: CorrelationID(w.c)})
if err != nil {
return 0, err
}
// The rewritten body has a different length than the one the caller sized.
w.Header().Del("Content-Length")
if _, err := w.ResponseWriter.Write(out); err != nil {
return 0, err
}
return len(b), nil
}
}
return w.ResponseWriter.Write(b)
}
package startup
import (
"context"
"fmt"
"time"
"github.com/sweetrpg/mongodb.go/database"
)
// pingTimeout bounds the check that a freshly opened client reaches the server.
const pingTimeout = 10 * time.Second
// DB is what ConnectDB needs from the database package, so a test can fail it on demand.
type DB struct {
Setup func() error // opens the client; an SRV or URI failure is an error
Ping func(ctx context.Context) error
Teardown func()
}
// LiveDB is the real database package.
func LiveDB() DB {
return DB{
Setup: func() (err error) {
// SetupDatabase panics on a connect or resolve failure.
defer func() {
if r := recover(); r != nil {
err = redacted("", fmt.Errorf("%v", r)) // a URL parse panic carries the connection string
}
}()
database.SetupDatabase()
return nil
},
Ping: func(ctx context.Context) error { return database.Db.Client().Ping(ctx, nil) },
Teardown: database.TeardownDatabase,
}
}
// ConnectDatabase opens the database and checks it answers (the driver connects lazily, so a
// process would otherwise fail on its first query), retrying as p says. A client that opened but
// did not answer is closed before the next try.
func ConnectDatabase(p Policy) error {
ApplyDriverTimeouts()
return ConnectDB(LiveDB(), p)
}
// ConnectDB is ConnectDatabase over c.
func ConnectDB(c DB, p Policy) error {
return Do("connect to the database", p, func() error {
if err := c.Setup(); err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), pingTimeout)
defer cancel()
if err := c.Ping(ctx); err != nil {
c.Teardown()
return err
}
return nil
})
}
package startup
import (
"os"
"strings"
)
// Driver timeouts applied when the connection settings do not set them. Without them a dead
// database holds every request for the driver's 30s server-selection wait, and an operation on a
// half-open connection waits forever.
var driverDefaults = []struct{ key, value string }{
{"serverSelectionTimeoutMS", "5000"},
{"connectTimeoutMS", "5000"},
{"socketTimeoutMS", "30000"},
}
// WithDriverTimeouts adds the default driver timeouts to a connection string's query for each one
// it does not already name (names compare case-insensitively, as the driver does).
func WithDriverTimeouts(rawQuery string) string {
have := map[string]bool{}
for _, kv := range strings.Split(rawQuery, "&") {
if k, _, _ := strings.Cut(kv, "="); k != "" {
have[strings.ToLower(k)] = true
}
}
out := rawQuery
for _, d := range driverDefaults {
if have[strings.ToLower(d.key)] {
continue
}
if out != "" {
out += "&"
}
out += d.key + "=" + d.value
}
return out
}
// WithDriverTimeoutsURI is WithDriverTimeouts for a whole connection string. The parameters are
// appended to the raw text, so credentials, hosts and escaping come through byte for byte.
func WithDriverTimeoutsURI(raw string) string {
base, query, hasQuery := strings.Cut(raw, "?")
if frag := strings.IndexByte(query, '#'); frag >= 0 { // a fragment ends the query
return raw
}
if q := WithDriverTimeouts(query); q != query || !hasQuery {
return base + "?" + q
}
return raw
}
// ApplyDriverTimeouts puts the default timeouts into the connection settings the database package
// reads from the environment: DB_URI when that is set (the package then ignores DB_OPTS), DB_OPTS
// otherwise.
func ApplyDriverTimeouts() {
if raw, ok := os.LookupEnv("DB_URI"); ok {
_ = os.Setenv("DB_URI", WithDriverTimeoutsURI(raw))
return
}
_ = os.Setenv("DB_OPTS", WithDriverTimeouts(os.Getenv("DB_OPTS")))
}
// Package startup holds the retry that process start-up uses against its dependencies. A pod that
// starts while the cluster resolver or a dependency is briefly unreachable should wait it out, not
// crash-loop: the dependency is usually back within seconds.
package startup
import (
"errors"
"fmt"
"regexp"
"strings"
"time"
"github.com/sweetrpg/common.go/logging"
"go.mongodb.org/mongo-driver/mongo"
)
// Policy bounds a retry. Attempts are spaced by a delay that doubles from First up to Max, and stop
// once the time spent plus the next wait would pass Budget (attempt time counts, not only the
// waits). An error Permanent reports (an authentication failure, an index conflict) will not fix
// itself, so it gets PermanentAfter tries in all.
type Policy struct {
Budget, First, Max time.Duration
PermanentAfter int
Permanent func(error) bool
// Sleep and Now are time.Sleep and time.Now unless a test replaces them.
Sleep func(time.Duration)
Now func() time.Time
}
// DefaultPolicy is a minute of retries, 1s growing to 10s, and two tries for an authentication
// failure.
func DefaultPolicy() Policy {
return Policy{Budget: time.Minute, First: time.Second, Max: 10 * time.Second, PermanentAfter: 2, Permanent: IsAuthError, Sleep: time.Sleep, Now: time.Now}
}
// IndexPolicy is p for creating indexes: a conflict with an existing index never succeeds on
// retry, so it fails on the first try.
func IndexPolicy(p Policy) Policy {
p.Permanent, p.PermanentAfter = IsIndexConflict, 1
return p
}
// Do runs attempt until it succeeds, retrying as p says. Each failed attempt is logged at warn with
// what was being done; the last error is returned once the budget is spent. Connection URIs in an
// error (user:password@host) are masked in both the log and the returned error.
func Do(what string, p Policy, attempt func() error) error {
if p.Sleep == nil {
p.Sleep = time.Sleep
}
if p.Now == nil {
p.Now = time.Now
}
if p.First <= 0 {
p.First = time.Second // a zero delay would loop without waiting
}
p.Max = max(p.Max, p.First)
start := p.Now()
backoff := p.First
var permanent int
for n := 1; ; n++ {
err := attempt()
if err == nil {
return nil
}
if p.Permanent != nil && p.Permanent(err) {
if permanent++; permanent >= max(p.PermanentAfter, 1) {
return redacted(fmt.Sprintf("%s failed after %d tries and will not fix itself: ", what, permanent), err)
}
}
if elapsed := p.Now().Sub(start); elapsed+backoff > p.Budget {
return redacted(fmt.Sprintf("%s failed after %d tries over %s: ", what, n, elapsed.Round(time.Millisecond)), err)
}
logging.Logger.Warn("startup step failed; retrying", "step", what, "attempt", n, "retry_in", backoff.String(), "error", Redact(err.Error()))
p.Sleep(backoff)
backoff = min(backoff*2, p.Max)
}
}
var uriUserinfo = regexp.MustCompile(`://[^/@\s]*@`)
// Redact masks the user:password part of any connection URI in s.
func Redact(s string) string { return uriUserinfo.ReplaceAllString(s, "://***@") }
// redactedError carries a masked message and still unwraps to the original, so errors.Is and As
// work on it.
type redactedError struct {
msg string
err error
}
func (e redactedError) Error() string { return e.msg }
func (e redactedError) Unwrap() error { return e.err }
func redacted(prefix string, err error) error {
return redactedError{msg: prefix + Redact(err.Error()), err: err}
}
// IsAuthError reports whether err looks like a rejected credential, which waiting does not fix.
func IsAuthError(err error) bool {
m := strings.ToLower(err.Error())
return strings.Contains(m, "authenticationfailed") || strings.Contains(m, "authentication failed")
}
// MongoIndexOptionsConflict and MongoIndexKeySpecsConflict are the server's answers to creating an
// index that differs from an existing one of the same name or keys (a changed TTL, say). They
// only go away when someone drops or changes the index.
const (
MongoIndexOptionsConflict = 85
MongoIndexKeySpecsConflict = 86
)
// IsIndexConflict reports whether err is an index definition conflict.
func IsIndexConflict(err error) bool {
var ce mongo.CommandError
return errors.As(err, &ce) && (ce.HasErrorCode(MongoIndexOptionsConflict) || ce.HasErrorCode(MongoIndexKeySpecsConflict))
}
// Package fake is an in-memory store.Collection for tests. It evaluates the filter operators the
// data layer emits (equality, $gt/$gte/$lt/$lte/$ne/$in/$regex, $and, $or) and the $set/$unset/
// $inc update operators, and enforces _id and unique-index uniqueness.
package fake
import (
"context"
"errors"
"fmt"
"reflect"
"regexp"
"sort"
"strings"
"sync"
"time"
"github.com/sweetrpg/initiative-api/store"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
// DB is an in-memory store.Database.
type DB struct {
mu sync.Mutex
cols map[string]*Collection
}
// NewDB returns an empty DB.
func NewDB() *DB { return &DB{cols: map[string]*Collection{}} }
// Collection returns (creating on first use) the named collection.
func (d *DB) Collection(name string) store.Collection { return d.Fake(name) }
// Fake returns the concrete fake collection, for assertions on its contents.
func (d *DB) Fake(name string) *Collection {
d.mu.Lock()
defer d.mu.Unlock()
if c, ok := d.cols[name]; ok {
return c
}
c := &Collection{}
d.cols[name] = c
return c
}
// Collection is one in-memory collection.
type Collection struct {
mu sync.Mutex
docs []bson.M
Indexes []store.IndexSpec
// FindCalls records each Find's options, so tests can prove limits and sorts reach the query.
FindCalls []store.FindOptions
watchers []*cursor
lostHistory bool // the next resumed Watch fails with ErrHistoryLost
}
// Docs returns a copy of the stored documents.
func (c *Collection) Docs() []bson.M {
c.mu.Lock()
defer c.mu.Unlock()
return append([]bson.M(nil), c.docs...)
}
func toM(v any) (bson.M, error) {
b, err := bson.Marshal(v)
if err != nil {
return nil, err
}
var m bson.M
return m, bson.Unmarshal(b, &m)
}
func decode(m bson.M, out any) error {
b, err := bson.Marshal(m)
if err != nil {
return err
}
return bson.Unmarshal(b, out)
}
func (c *Collection) InsertOne(_ context.Context, doc any) error {
m, err := toM(doc)
if err != nil {
return err
}
c.mu.Lock()
defer c.mu.Unlock()
if c.violatesUnique(m, -1) {
return store.ErrDuplicate
}
c.docs = append(c.docs, m)
c.wake()
return nil
}
func (c *Collection) FindOne(_ context.Context, filter bson.D, out any) error {
c.mu.Lock()
defer c.mu.Unlock()
for _, d := range c.docs {
if ok, err := match(d, filter); err != nil {
return err
} else if ok {
return decode(d, out)
}
}
return store.ErrNotFound
}
func (c *Collection) Find(_ context.Context, filter bson.D, opts store.FindOptions, out any) error {
c.mu.Lock()
defer c.mu.Unlock()
c.FindCalls = append(c.FindCalls, opts)
var hits []bson.M
for _, d := range c.docs {
ok, err := match(d, filter)
if err != nil {
return err
}
if ok {
hits = append(hits, d)
}
}
sort.SliceStable(hits, func(i, j int) bool { return less(hits[i], hits[j], opts.Sort) })
if opts.Limit > 0 && int64(len(hits)) > opts.Limit {
hits = hits[:opts.Limit]
}
res := make(bson.A, 0, len(hits))
for _, h := range hits {
res = append(res, project(h, opts.Projection))
}
return decode(bson.M{"r": res}, &wrap{out})
}
// wrap decodes {"r": [...]} straight into a slice pointer via reflection.
type wrap struct{ out any }
func (w *wrap) UnmarshalBSON(b []byte) error {
var raw bson.Raw = b
arr, err := raw.LookupErr("r")
if err != nil {
return err
}
rv := reflect.ValueOf(w.out).Elem()
rv.Set(reflect.MakeSlice(rv.Type(), 0, 0))
vals, err := arr.Array().Values()
if err != nil {
return err
}
for _, v := range vals {
item := reflect.New(rv.Type().Elem())
if err := v.Unmarshal(item.Interface()); err != nil {
return err
}
rv.Set(reflect.Append(rv, item.Elem()))
}
return nil
}
func project(d bson.M, proj bson.D) bson.M {
if len(proj) == 0 {
return d
}
out := bson.M{"_id": d["_id"]}
for _, e := range proj {
if v, ok := d[e.Key]; ok {
out[e.Key] = v
}
}
return out
}
func (c *Collection) FindOneAndUpdate(_ context.Context, filter, update bson.D, out any) error {
c.mu.Lock()
defer c.mu.Unlock()
for i, d := range c.docs {
ok, err := match(d, filter)
if err != nil {
return err
}
if !ok {
continue
}
next := cloneM(d)
if err := applyUpdate(next, update); err != nil {
return err
}
if c.violatesUnique(next, i) {
return store.ErrDuplicate
}
c.docs[i] = next
return decode(next, out)
}
return store.ErrNotFound
}
// UpsertOne applies update to the first match, or inserts a document seeded from the filter's
// top-level equality fields and then updated.
func (c *Collection) UpsertOne(_ context.Context, filter, update bson.D) error {
c.mu.Lock()
defer c.mu.Unlock()
for i, d := range c.docs {
ok, err := match(d, filter)
if err != nil {
return err
}
if !ok {
continue
}
next := cloneM(d)
if err := applyUpdate(next, update); err != nil {
return err
}
c.docs[i] = next
return nil
}
doc := bson.M{}
for _, e := range filter {
if _, isOp := e.Value.(bson.D); !isOp && e.Key[0] != '$' {
doc[e.Key] = e.Value
}
}
if err := applyUpdate(doc, update); err != nil {
return err
}
if c.violatesUnique(doc, -1) {
return store.ErrDuplicate
}
c.docs = append(c.docs, doc)
return nil
}
func (c *Collection) DeleteOne(_ context.Context, filter bson.D) error {
c.mu.Lock()
defer c.mu.Unlock()
for i, d := range c.docs {
ok, err := match(d, filter)
if err != nil {
return err
}
if ok {
c.docs = append(c.docs[:i], c.docs[i+1:]...)
return nil
}
}
return store.ErrNotFound
}
func (c *Collection) CountDocuments(_ context.Context, filter bson.D) (int64, error) {
c.mu.Lock()
defer c.mu.Unlock()
var n int64
for _, d := range c.docs {
ok, err := match(d, filter)
if err != nil {
return 0, err
}
if ok {
n++
}
}
return n, nil
}
func (c *Collection) EnsureIndexes(_ context.Context, specs []store.IndexSpec) error {
c.mu.Lock()
defer c.mu.Unlock()
c.Indexes = append([]store.IndexSpec(nil), specs...)
return nil
}
// violatesUnique checks _id and every unique index (honoring partial filters) against m,
// ignoring the document at index skip.
func (c *Collection) violatesUnique(m bson.M, skip int) bool {
for i, d := range c.docs {
if i == skip {
continue
}
if reflect.DeepEqual(d["_id"], m["_id"]) {
return true
}
for _, ix := range c.Indexes {
if ix.Unique && sameKey(ix, d, m) {
return true
}
}
}
return false
}
func sameKey(ix store.IndexSpec, a, b bson.M) bool {
for _, d := range []bson.M{a, b} {
if len(ix.Partial) > 0 {
if ok, _ := match(d, ix.Partial); !ok {
return false
}
}
}
for _, k := range ix.Keys {
av, bv := a[k.Key], b[k.Key]
if arr, ok := av.(bson.A); ok { // multikey: any shared element collides
return anyShared(arr, bv)
}
if !reflect.DeepEqual(norm(av), norm(bv)) {
return false
}
}
return true
}
func anyShared(a bson.A, b any) bool {
barr, ok := b.(bson.A)
if !ok {
return false
}
for _, x := range a {
for _, y := range barr {
if reflect.DeepEqual(norm(x), norm(y)) {
return true
}
}
}
return false
}
func cloneM(m bson.M) bson.M {
out := make(bson.M, len(m))
for k, v := range m {
out[k] = v
}
return out
}
func applyUpdate(d bson.M, update bson.D) error {
for _, op := range update {
fields, ok := op.Value.(bson.D)
if !ok {
return fmt.Errorf("fake: update operand for %s must be bson.D", op.Key)
}
for _, f := range fields {
switch op.Key {
case "$set":
m, err := toM(bson.D{{Key: "v", Value: f.Value}})
if err != nil {
return err
}
setPath(d, f.Key, m["v"])
case "$unset":
delete(d, f.Key)
case "$inc":
cur, _ := toFloat(norm(d[f.Key]))
inc, _ := toFloat(norm(f.Value))
d[f.Key] = int64(cur + inc)
default:
return fmt.Errorf("fake: unsupported update operator %s", op.Key)
}
}
}
return nil
}
// setPath sets a dotted key (entries.k) inside nested documents, copying each level it touches
// so a stored document is never mutated in place.
func setPath(d bson.M, key string, v any) {
head, rest, nested := strings.Cut(key, ".")
if !nested {
d[key] = v
return
}
child := bson.M{}
if cur, ok := d[head].(bson.M); ok {
child = cloneM(cur)
}
setPath(child, rest, v)
d[head] = child
}
// norm maps stored and filter values to comparable canonical forms.
func norm(v any) any {
switch x := v.(type) {
case time.Time:
return int64(primitive.NewDateTimeFromTime(x))
case primitive.DateTime:
return int64(x)
case int:
return int64(x)
case int32:
return int64(x)
case float64:
if x == float64(int64(x)) {
return int64(x)
}
case *time.Time:
if x == nil {
return nil
}
return norm(*x)
}
return v
}
func toFloat(v any) (float64, bool) {
switch x := v.(type) {
case int64:
return float64(x), true
case float64:
return x, true
}
return 0, false
}
func cmp(a, b any) (int, bool) {
a, b = norm(a), norm(b)
if af, ok := toFloat(a); ok {
if bf, ok := toFloat(b); ok {
switch {
case af < bf:
return -1, true
case af > bf:
return 1, true
}
return 0, true
}
}
as, aok := a.(string)
bs, bok := b.(string)
if aok && bok {
switch {
case as < bs:
return -1, true
case as > bs:
return 1, true
}
return 0, true
}
return 0, false
}
func less(a, b bson.M, sortD bson.D) bool {
for _, k := range sortD {
c, _ := cmp(a[k.Key], b[k.Key])
if c == 0 {
continue
}
if dir, _ := toFloat(norm(k.Value)); dir < 0 {
return c > 0
}
return c < 0
}
return false
}
func match(d bson.M, filter bson.D) (bool, error) {
for _, e := range filter {
ok, err := matchElem(d, e)
if err != nil || !ok {
return false, err
}
}
return true, nil
}
func matchElem(d bson.M, e bson.E) (bool, error) {
switch e.Key {
case "$and", "$or":
clauses, ok := e.Value.(bson.A)
if !ok {
return false, fmt.Errorf("fake: %s needs bson.A", e.Key)
}
if len(clauses) == 0 {
return false, fmt.Errorf("fake: %s argument must be a non-empty array", e.Key)
}
for _, cl := range clauses {
sub, ok := cl.(bson.D)
if !ok {
return false, fmt.Errorf("fake: %s clause must be bson.D", e.Key)
}
m, err := match(d, sub)
if err != nil {
return false, err
}
if m == (e.Key == "$or") {
return m, nil
}
}
return e.Key == "$and", nil
}
if strings.Contains(e.Key, ".") {
return matchPath(d, e)
}
if ops, ok := e.Value.(bson.D); ok && len(ops) > 0 && len(ops[0].Key) > 0 && ops[0].Key[0] == '$' {
return matchOps(d[e.Key], ops)
}
return eq(d[e.Key], e.Value), nil
}
// matchPath matches a dotted key (combatants.controller_user_ids) the way Mongo does: the path
// is followed through nested documents and arrays of documents, and the condition holds if any
// value found satisfies it.
func matchPath(d bson.M, e bson.E) (bool, error) {
for _, have := range valuesAt(d, strings.Split(e.Key, ".")) {
if ops, ok := e.Value.(bson.D); ok && len(ops) > 0 && len(ops[0].Key) > 0 && ops[0].Key[0] == '$' {
m, err := matchOps(have, ops)
if err != nil || m {
return m, err
}
} else if eq(have, e.Value) {
return true, nil
}
}
return false, nil
}
func valuesAt(v any, path []string) []any {
if len(path) == 0 {
return []any{v}
}
switch x := v.(type) {
case bson.M:
if next, ok := x[path[0]]; ok {
return valuesAt(next, path[1:])
}
case bson.A:
var out []any
for _, el := range x {
out = append(out, valuesAt(el, path)...)
}
return out
}
return nil
}
func eq(have, want any) bool {
if want == nil {
return have == nil
}
if arr, ok := have.(bson.A); ok { // equality against an array field matches any element
for _, x := range arr {
if reflect.DeepEqual(norm(x), norm(want)) {
return true
}
}
}
return reflect.DeepEqual(norm(have), norm(want))
}
func matchOps(have any, ops bson.D) (bool, error) {
var pattern, opts string
for _, o := range ops {
switch o.Key {
case "$options":
opts, _ = o.Value.(string)
case "$regex":
pattern, _ = o.Value.(string)
}
}
for _, o := range ops {
ok, err := matchOp(have, o, pattern, opts)
if err != nil || !ok {
return false, err
}
}
return true, nil
}
func matchOp(have any, o bson.E, pattern, opts string) (bool, error) {
switch o.Key {
case "$options":
return true, nil
case "$ne":
return !eq(have, o.Value), nil
case "$in":
vals, ok := o.Value.(bson.A)
if !ok {
return false, fmt.Errorf("fake: $in needs bson.A")
}
for _, v := range vals {
if eq(have, v) {
return true, nil
}
}
return false, nil
case "$regex":
s, ok := have.(string)
if !ok {
return false, nil
}
if opts == "i" {
pattern = "(?i)" + pattern
}
re, err := regexp.Compile(pattern)
if err != nil {
return false, err
}
return re.MatchString(s), nil
case "$gt", "$gte", "$lt", "$lte":
c, ok := cmp(have, o.Value)
if !ok {
return false, nil
}
return (o.Key == "$gt" && c > 0) || (o.Key == "$gte" && c >= 0) ||
(o.Key == "$lt" && c < 0) || (o.Key == "$lte" && c <= 0), nil
case "$exists":
want, _ := o.Value.(bool)
return (have != nil) == want, nil
}
return false, fmt.Errorf("fake: unsupported operator %s", o.Key)
}
// wake tells every watcher a document arrived. Callers hold c.mu.
func (c *Collection) wake() {
for _, w := range c.watchers {
select {
case w.ping <- struct{}{}:
default:
}
}
}
// LoseHistory makes the next Watch that asks to resume fail with store.ErrHistoryLost, as a token
// older than the oplog does.
func (c *Collection) LoseHistory() {
c.mu.Lock()
c.lostHistory = true
c.mu.Unlock()
}
// BreakWatchers ends every open Watch cursor with an error, as a dropped change stream does. A
// Watch made after it works again.
func (c *Collection) BreakWatchers() {
c.mu.Lock()
defer c.mu.Unlock()
for _, w := range c.watchers {
w.broken = true
}
c.wake()
}
// Watch tails inserts. The resume token is the number of documents seen, so a resumed cursor
// replays what was inserted while it was down.
func (c *Collection) Watch(_ context.Context, resume bson.Raw) (store.Cursor, error) {
c.mu.Lock()
defer c.mu.Unlock()
if len(resume) > 0 && c.lostHistory {
c.lostHistory = false
return nil, store.ErrHistoryLost
}
w := &cursor{c: c, ping: make(chan struct{}, 1), pos: len(c.docs)}
if len(resume) > 0 {
w.pos = int(resume.Lookup("i").Int32())
}
c.watchers = append(c.watchers, w)
return w, nil
}
type cursor struct {
c *Collection
ping chan struct{}
pos int
broken bool // guarded by c.mu
doc bson.Raw
err error
}
func (w *cursor) Next(ctx context.Context) bool {
for {
w.c.mu.Lock()
switch {
case w.broken:
w.err = errors.New("fake: watch broken")
w.c.mu.Unlock()
return false
case w.pos < len(w.c.docs):
w.doc, w.err = bson.Marshal(w.c.docs[w.pos])
w.pos++
w.c.mu.Unlock()
return w.err == nil
}
w.c.mu.Unlock()
select {
case <-w.ping:
case <-ctx.Done():
w.err = ctx.Err()
return false
}
}
}
func (w *cursor) Doc() bson.Raw { return w.doc }
func (w *cursor) Token() bson.Raw {
t, _ := bson.Marshal(bson.D{{Key: "i", Value: int32(w.pos)}})
return t
}
func (w *cursor) Err() error { return w.err }
func (w *cursor) Close(context.Context) error { return nil }
package store
import (
"context"
"errors"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// MongoDatabase adapts a *mongo.Database to Database.
type MongoDatabase struct{ DB *mongo.Database }
// Collection returns the named collection.
func (m MongoDatabase) Collection(name string) Collection {
return mongoCollection{c: m.DB.Collection(name)}
}
type mongoCollection struct{ c *mongo.Collection }
func mapErr(err error) error {
switch {
case err == nil:
return nil
case errors.Is(err, mongo.ErrNoDocuments):
return ErrNotFound
case mongo.IsDuplicateKeyError(err):
return ErrDuplicate
}
return err
}
func (m mongoCollection) InsertOne(ctx context.Context, doc any) error {
_, err := m.c.InsertOne(ctx, doc)
return mapErr(err)
}
func (m mongoCollection) FindOne(ctx context.Context, filter bson.D, out any) error {
_, err := retryRead(ctx, "find_one", func() (struct{}, error) {
return struct{}{}, m.c.FindOne(ctx, filter).Decode(out)
})
return mapErr(err)
}
func (m mongoCollection) Find(ctx context.Context, filter bson.D, opts FindOptions, out any) error {
fo := options.Find()
if len(opts.Sort) > 0 {
fo.SetSort(opts.Sort)
}
if len(opts.Projection) > 0 {
fo.SetProjection(opts.Projection)
}
if opts.Limit > 0 {
fo.SetLimit(opts.Limit)
}
_, err := retryRead(ctx, "find", func() (struct{}, error) {
cur, err := m.c.Find(ctx, filter, fo)
if err != nil {
return struct{}{}, err
}
return struct{}{}, cur.All(ctx, out)
})
return mapErr(err)
}
func (m mongoCollection) FindOneAndUpdate(ctx context.Context, filter, update bson.D, out any) error {
opts := options.FindOneAndUpdate().SetReturnDocument(options.After)
return mapErr(m.c.FindOneAndUpdate(ctx, filter, update, opts).Decode(out))
}
func (m mongoCollection) UpsertOne(ctx context.Context, filter, update bson.D) error {
_, err := m.c.UpdateOne(ctx, filter, update, options.Update().SetUpsert(true))
return mapErr(err)
}
func (m mongoCollection) DeleteOne(ctx context.Context, filter bson.D) error {
res, err := m.c.DeleteOne(ctx, filter)
if err != nil {
return mapErr(err)
}
if res.DeletedCount == 0 {
return ErrNotFound
}
return nil
}
func (m mongoCollection) CountDocuments(ctx context.Context, filter bson.D) (int64, error) {
n, err := retryRead(ctx, "count", func() (int64, error) { return m.c.CountDocuments(ctx, filter) })
return n, mapErr(err)
}
func (m mongoCollection) EnsureIndexes(ctx context.Context, specs []IndexSpec) error {
models := make([]mongo.IndexModel, 0, len(specs))
for _, s := range specs {
o := options.Index().SetName(s.Name).SetUnique(s.Unique)
if len(s.Partial) > 0 {
o.SetPartialFilterExpression(s.Partial)
}
if s.ExpireAfter > 0 {
o.SetExpireAfterSeconds(int32(s.ExpireAfter / time.Second))
}
models = append(models, mongo.IndexModel{Keys: s.Keys, Options: o})
}
_, err := m.c.Indexes().CreateMany(ctx, models)
return mapErr(err)
}
// Watch tails the collection's inserts with a change stream (a replica set is required).
func (m mongoCollection) Watch(ctx context.Context, resume bson.Raw) (Cursor, error) {
// A getMore waits at most the await time, so an idle tail answers well inside the driver's
// socketTimeoutMS and is not mistaken for a dead connection.
opts := options.ChangeStream().SetMaxAwaitTime(time.Second)
if len(resume) > 0 {
opts.SetResumeAfter(resume)
}
pipe := mongo.Pipeline{{{Key: "$match", Value: bson.D{{Key: "operationType", Value: "insert"}}}}}
cs, err := m.c.Watch(ctx, pipe, opts)
if err != nil {
return nil, watchError(err)
}
return mongoCursor{cs}, nil
}
type mongoCursor struct{ cs *mongo.ChangeStream }
func (c mongoCursor) Next(ctx context.Context) bool { return c.cs.Next(ctx) }
func (c mongoCursor) Doc() bson.Raw {
d, _ := c.cs.Current.Lookup("fullDocument").DocumentOK()
return d
}
func (c mongoCursor) Token() bson.Raw { return c.cs.ResumeToken() }
func (c mongoCursor) Err() error { return watchError(c.cs.Err()) }
func (c mongoCursor) Close(ctx context.Context) error { return c.cs.Close(ctx) }
// watchError marks the server's history-lost answers (ChangeStreamHistoryLost 286, ChangeStreamFatalError
// 280) as ErrHistoryLost; any other error is transient and keeps its resume token.
func watchError(err error) error {
var ce mongo.CommandError
if errors.As(err, &ce) && (ce.HasErrorCode(286) || ce.HasErrorCode(280)) {
return errors.Join(ErrHistoryLost, err)
}
return err
}
package store
import (
"context"
"log/slog"
"strings"
"time"
"go.mongodb.org/mongo-driver/mongo"
)
// Reads are retried when a new connection to the server fails to open: pool growth or a replaced
// connection does a fresh handshake mid-run, and Atlas has been seen to refuse one with a SCRAM
// "bad auth" that the next attempt passes. A read changes nothing, so repeating it is safe; writes
// are not retried here (the driver's own retryable writes cover network errors).
const (
readAttempts = 3
readBackoff = 100 * time.Millisecond
)
// readSleep waits between attempts; tests replace it.
var readSleep = func(ctx context.Context, d time.Duration) {
select {
case <-time.After(d):
case <-ctx.Done():
}
}
// connectErrorClass names the kind of connection failure err is, or "" when it is not one that a
// retry can fix.
func connectErrorClass(err error) string {
if err == nil {
return ""
}
m := strings.ToLower(err.Error())
switch {
case strings.Contains(m, "auth error") || strings.Contains(m, "bad auth") || strings.Contains(m, "authenticationfailed"):
return "handshake_auth"
case strings.Contains(m, "connection handshake"):
return "handshake"
case mongo.IsNetworkError(err):
return "network"
}
return ""
}
// retryRead runs op, repeating it up to readAttempts times while it fails with a connection
// failure, and logs the class of each failure it absorbs.
func retryRead[T any](ctx context.Context, name string, op func() (T, error)) (T, error) {
backoff := readBackoff
for attempt := 1; ; attempt++ {
v, err := op()
class := connectErrorClass(err)
if class == "" || attempt >= readAttempts || ctx.Err() != nil {
return v, err
}
slog.WarnContext(ctx, "database read failed to connect; retrying", "op", name, "class", class, "attempt", attempt, "error", err.Error())
readSleep(ctx, backoff)
backoff *= 2
}
}
// Package store is the narrow MongoDB surface the data layer needs. The data layer depends on
// this interface so its owner-scoping, revision, and query logic can be tested against an
// in-memory fake (store/fake) without a database.
package store
import (
"context"
"errors"
"time"
"go.mongodb.org/mongo-driver/bson"
)
// Sentinel errors returned by every Collection implementation.
var (
// ErrNotFound means no document matched the filter.
ErrNotFound = errors.New("store: not found")
// ErrDuplicate means a unique index rejected the write.
ErrDuplicate = errors.New("store: duplicate key")
// ErrHistoryLost means a change stream cannot resume from its token: the history it needs aged
// out or the token is invalid.
ErrHistoryLost = errors.New("store: change stream history lost")
)
// FindOptions carries the query-layer sort, projection, and limit for Find.
type FindOptions struct {
Sort bson.D
Projection bson.D
Limit int64
}
// IndexSpec describes one index. Partial is a partialFilterExpression; empty means a full index.
type IndexSpec struct {
Name string
Keys bson.D
Unique bool
Partial bson.D
// ExpireAfter makes the index a TTL index on its single key: documents expire that long after
// the time the key holds. Zero means no expiry.
ExpireAfter time.Duration
}
// Collection is one MongoDB collection. Filters and updates are bson documents built from
// parameters; callers never concatenate strings into them. out arguments are pointers decoded
// from the stored document (Find takes a pointer to a slice).
type Collection interface {
InsertOne(ctx context.Context, doc any) error
FindOne(ctx context.Context, filter bson.D, out any) error
Find(ctx context.Context, filter bson.D, opts FindOptions, out any) error
// FindOneAndUpdate applies update to the first match and decodes the post-update document.
FindOneAndUpdate(ctx context.Context, filter, update bson.D, out any) error
// UpsertOne applies update to the first match, inserting a document seeded from the filter's
// equality fields when nothing matches. A single atomic write: concurrent callers touching
// different fields cannot revert one another.
UpsertOne(ctx context.Context, filter, update bson.D) error
// DeleteOne removes the first match for good; ErrNotFound when nothing matched.
DeleteOne(ctx context.Context, filter bson.D) error
CountDocuments(ctx context.Context, filter bson.D) (int64, error)
EnsureIndexes(ctx context.Context, specs []IndexSpec) error
}
// Database hands out collections by name.
type Database interface {
Collection(name string) Collection
}
// Watcher is implemented by collections that can be tailed for inserted documents (a MongoDB
// change stream). Use Watch to reach it from a Collection.
type Watcher interface {
// Watch returns a cursor over documents inserted from now on, or after the position resume names
// (a token from Cursor.Token).
Watch(ctx context.Context, resume bson.Raw) (Cursor, error)
}
// Cursor is a tail of inserted documents.
type Cursor interface {
// Next waits for the next inserted document; false means the cursor ended (see Err).
Next(ctx context.Context) bool
// Doc is the document Next found.
Doc() bson.Raw
// Token is the resume position after the document Next found.
Token() bson.Raw
Err() error
Close(ctx context.Context) error
}
// ErrNoWatch means the collection cannot be tailed.
var ErrNoWatch = errors.New("store: collection cannot be watched")
// Watch tails c for inserts, or returns ErrNoWatch when c does not support it.
func Watch(ctx context.Context, c Collection, resume bson.Raw) (Cursor, error) {
w, ok := c.(Watcher)
if !ok {
return nil, ErrNoWatch
}
return w.Watch(ctx, resume)
}