- ids: TestIDsAreTimeOrdered asserted strict lexicographic ordering of back-to-back UUIDv7s, but the sub-ms tail is random and not required to be monotonic. Sleep between samples so each ID lands in a distinct millisecond — the property that actually gives Postgres index locality on (org_id, id desc). - go.mod/go.sum: run go mod tidy. keyfunc/v3, prometheus/client_golang and testcontainers-go/modules/postgres are imported directly and should not be marked // indirect; also drops stale sum entries. - gofmt -w across 12 files flagged by the lint job. - security.yml: pin govulncheck to v1.2.0. @latest triggers a proxy lookup every run, which is the step that hung for 16m on the Gitea runner. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
892 lines
23 KiB
Go
892 lines
23 KiB
Go
// Package memstore is an in-memory implementation of store.Store.
|
|
//
|
|
// Intended for unit tests and for the local-dev single-binary mode where
|
|
// operators want to poke at the HTTP API without bringing up Postgres.
|
|
// Concurrency-safe via a single coarse mutex — performance is fine for
|
|
// tests but not a replacement for the pgx-backed store in production.
|
|
package memstore
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"anchorage/internal/pkg/ids"
|
|
"anchorage/internal/pkg/store"
|
|
)
|
|
|
|
// Store is the top-level in-memory store. Zero value is ready to use.
|
|
type Store struct {
|
|
mu sync.Mutex
|
|
orgs map[ids.OrgID]*store.Org
|
|
slugToOrg map[string]ids.OrgID
|
|
users map[ids.UserID]*store.User
|
|
emailToU map[string]ids.UserID
|
|
subToU map[string]ids.UserID
|
|
members map[string]*store.Membership // key: orgID + "|" + userID
|
|
tokens map[ids.TokenID]*store.APIToken
|
|
denylist map[ids.TokenID]time.Time // value = expires_at
|
|
nodes map[ids.NodeID]*store.Node
|
|
pins map[ids.PinID]*store.Pin
|
|
placements map[string]*store.Placement // key: pinID + "|" + nodeID
|
|
refcounts map[string]int // key: nodeID + "|" + cid
|
|
audit []*store.AuditEntry
|
|
nextAudit int64
|
|
}
|
|
|
|
// New returns an initialised memstore.
|
|
func New() *Store {
|
|
return &Store{
|
|
orgs: map[ids.OrgID]*store.Org{},
|
|
slugToOrg: map[string]ids.OrgID{},
|
|
users: map[ids.UserID]*store.User{},
|
|
emailToU: map[string]ids.UserID{},
|
|
subToU: map[string]ids.UserID{},
|
|
members: map[string]*store.Membership{},
|
|
tokens: map[ids.TokenID]*store.APIToken{},
|
|
denylist: map[ids.TokenID]time.Time{},
|
|
nodes: map[ids.NodeID]*store.Node{},
|
|
pins: map[ids.PinID]*store.Pin{},
|
|
placements: map[string]*store.Placement{},
|
|
refcounts: map[string]int{},
|
|
}
|
|
}
|
|
|
|
// ---- store.Store root -----------------------------------------------------
|
|
|
|
func (s *Store) Orgs() store.OrgStore { return orgStore{s} }
|
|
func (s *Store) Users() store.UserStore { return userStore{s} }
|
|
func (s *Store) Memberships() store.MembershipStore { return memStore{s} }
|
|
func (s *Store) Tokens() store.TokenStore { return tokenStore{s} }
|
|
func (s *Store) Nodes() store.NodeStore { return nodeStore{s} }
|
|
func (s *Store) Pins() store.PinStore { return pinStore{s} }
|
|
func (s *Store) Audit() store.AuditStore { return auditStore{s} }
|
|
func (s *Store) WithOrgContext(ctx context.Context, _ ids.OrgID) (context.Context, error) {
|
|
return ctx, nil
|
|
}
|
|
|
|
// Tx in a memstore is a no-op — the same Store is passed back and the
|
|
// context is forwarded unchanged. Real Postgres implementations open a
|
|
// pgx tx and derive a tx-scoped context from ctx.
|
|
func (s *Store) Tx(ctx context.Context, fn func(txCtx context.Context, tx store.Store) error) error {
|
|
return fn(ctx, s)
|
|
}
|
|
|
|
// ---- Orgs -----------------------------------------------------------------
|
|
|
|
type orgStore struct{ s *Store }
|
|
|
|
func (o orgStore) Create(_ context.Context, id ids.OrgID, slug, name string) (*store.Org, error) {
|
|
o.s.mu.Lock()
|
|
defer o.s.mu.Unlock()
|
|
if _, ok := o.s.slugToOrg[slug]; ok {
|
|
return nil, store.ErrConflict
|
|
}
|
|
now := time.Now().UTC()
|
|
row := &store.Org{ID: id, Slug: slug, Name: name, CreatedAt: now, UpdatedAt: now}
|
|
o.s.orgs[id] = row
|
|
o.s.slugToOrg[slug] = id
|
|
return cloneOrg(row), nil
|
|
}
|
|
|
|
func (o orgStore) GetByID(_ context.Context, id ids.OrgID) (*store.Org, error) {
|
|
o.s.mu.Lock()
|
|
defer o.s.mu.Unlock()
|
|
row, ok := o.s.orgs[id]
|
|
if !ok {
|
|
return nil, store.ErrNotFound
|
|
}
|
|
return cloneOrg(row), nil
|
|
}
|
|
|
|
func (o orgStore) GetBySlug(_ context.Context, slug string) (*store.Org, error) {
|
|
o.s.mu.Lock()
|
|
defer o.s.mu.Unlock()
|
|
id, ok := o.s.slugToOrg[slug]
|
|
if !ok {
|
|
return nil, store.ErrNotFound
|
|
}
|
|
return cloneOrg(o.s.orgs[id]), nil
|
|
}
|
|
|
|
func (o orgStore) UpdateName(_ context.Context, id ids.OrgID, name string) (*store.Org, error) {
|
|
o.s.mu.Lock()
|
|
defer o.s.mu.Unlock()
|
|
row, ok := o.s.orgs[id]
|
|
if !ok {
|
|
return nil, store.ErrNotFound
|
|
}
|
|
row.Name = name
|
|
row.UpdatedAt = time.Now().UTC()
|
|
return cloneOrg(row), nil
|
|
}
|
|
|
|
func (o orgStore) List(_ context.Context, limit, offset int) ([]*store.Org, error) {
|
|
o.s.mu.Lock()
|
|
defer o.s.mu.Unlock()
|
|
out := make([]*store.Org, 0, len(o.s.orgs))
|
|
for _, org := range o.s.orgs {
|
|
out = append(out, cloneOrg(org))
|
|
}
|
|
return paginate(out, limit, offset), nil
|
|
}
|
|
|
|
func cloneOrg(o *store.Org) *store.Org { v := *o; return &v }
|
|
|
|
// ---- Users ----------------------------------------------------------------
|
|
|
|
type userStore struct{ s *Store }
|
|
|
|
func (u userStore) UpsertByAuthentikSub(_ context.Context, id ids.UserID, sub, email, displayName string, isSysadmin bool) (*store.User, error) {
|
|
u.s.mu.Lock()
|
|
defer u.s.mu.Unlock()
|
|
email = strings.ToLower(email)
|
|
if existingID, ok := u.s.subToU[sub]; ok {
|
|
row := u.s.users[existingID]
|
|
row.Email = email
|
|
row.DisplayName = displayName
|
|
row.UpdatedAt = time.Now().UTC()
|
|
return cloneUser(row), nil
|
|
}
|
|
now := time.Now().UTC()
|
|
row := &store.User{
|
|
ID: id,
|
|
AuthentikSub: sub,
|
|
Email: email,
|
|
DisplayName: displayName,
|
|
IsSysadmin: isSysadmin,
|
|
CreatedAt: now,
|
|
UpdatedAt: now,
|
|
}
|
|
u.s.users[id] = row
|
|
u.s.subToU[sub] = id
|
|
u.s.emailToU[email] = id
|
|
return cloneUser(row), nil
|
|
}
|
|
|
|
func (u userStore) GetByID(_ context.Context, id ids.UserID) (*store.User, error) {
|
|
u.s.mu.Lock()
|
|
defer u.s.mu.Unlock()
|
|
row, ok := u.s.users[id]
|
|
if !ok {
|
|
return nil, store.ErrNotFound
|
|
}
|
|
return cloneUser(row), nil
|
|
}
|
|
|
|
func (u userStore) GetByEmail(_ context.Context, email string) (*store.User, error) {
|
|
u.s.mu.Lock()
|
|
defer u.s.mu.Unlock()
|
|
id, ok := u.s.emailToU[strings.ToLower(email)]
|
|
if !ok {
|
|
return nil, store.ErrNotFound
|
|
}
|
|
return cloneUser(u.s.users[id]), nil
|
|
}
|
|
|
|
func (u userStore) PromoteSysadmin(_ context.Context, id ids.UserID) error {
|
|
u.s.mu.Lock()
|
|
defer u.s.mu.Unlock()
|
|
row, ok := u.s.users[id]
|
|
if !ok {
|
|
return store.ErrNotFound
|
|
}
|
|
row.IsSysadmin = true
|
|
return nil
|
|
}
|
|
|
|
func cloneUser(u *store.User) *store.User { v := *u; return &v }
|
|
|
|
// ---- Memberships ----------------------------------------------------------
|
|
|
|
type memStore struct{ s *Store }
|
|
|
|
func memKey(org ids.OrgID, user ids.UserID) string {
|
|
return org.String() + "|" + user.String()
|
|
}
|
|
|
|
func (m memStore) Add(_ context.Context, orgID ids.OrgID, userID ids.UserID, role string) error {
|
|
m.s.mu.Lock()
|
|
defer m.s.mu.Unlock()
|
|
if role != store.RoleOrgAdmin && role != store.RoleMember {
|
|
return fmt.Errorf("memstore: invalid role %q", role)
|
|
}
|
|
now := time.Now().UTC()
|
|
m.s.members[memKey(orgID, userID)] = &store.Membership{
|
|
OrgID: orgID,
|
|
UserID: userID,
|
|
Role: role,
|
|
Created: now,
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (m memStore) Remove(_ context.Context, orgID ids.OrgID, userID ids.UserID) error {
|
|
m.s.mu.Lock()
|
|
defer m.s.mu.Unlock()
|
|
delete(m.s.members, memKey(orgID, userID))
|
|
return nil
|
|
}
|
|
|
|
func (m memStore) ListForUser(_ context.Context, userID ids.UserID) ([]*store.Membership, error) {
|
|
m.s.mu.Lock()
|
|
defer m.s.mu.Unlock()
|
|
out := []*store.Membership{}
|
|
for _, mem := range m.s.members {
|
|
if mem.UserID == userID {
|
|
row := *mem
|
|
if o, ok := m.s.orgs[mem.OrgID]; ok {
|
|
row.OrgSlug = o.Slug
|
|
row.OrgName = o.Name
|
|
}
|
|
out = append(out, &row)
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// ---- Tokens ---------------------------------------------------------------
|
|
|
|
type tokenStore struct{ s *Store }
|
|
|
|
func (t tokenStore) Create(_ context.Context, tk *store.APIToken) error {
|
|
t.s.mu.Lock()
|
|
defer t.s.mu.Unlock()
|
|
v := *tk
|
|
t.s.tokens[tk.JTI] = &v
|
|
return nil
|
|
}
|
|
|
|
func (t tokenStore) GetByJTI(_ context.Context, jti ids.TokenID) (*store.APIToken, error) {
|
|
t.s.mu.Lock()
|
|
defer t.s.mu.Unlock()
|
|
tk, ok := t.s.tokens[jti]
|
|
if !ok {
|
|
return nil, store.ErrNotFound
|
|
}
|
|
v := *tk
|
|
return &v, nil
|
|
}
|
|
|
|
func (t tokenStore) ListForUser(_ context.Context, orgID ids.OrgID, userID ids.UserID) ([]*store.APIToken, error) {
|
|
t.s.mu.Lock()
|
|
defer t.s.mu.Unlock()
|
|
out := []*store.APIToken{}
|
|
for _, tk := range t.s.tokens {
|
|
if tk.OrgID == orgID && tk.UserID == userID && tk.RevokedAt == nil {
|
|
v := *tk
|
|
out = append(out, &v)
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (t tokenStore) Revoke(_ context.Context, jti ids.TokenID) error {
|
|
t.s.mu.Lock()
|
|
defer t.s.mu.Unlock()
|
|
tk, ok := t.s.tokens[jti]
|
|
if !ok {
|
|
return store.ErrNotFound
|
|
}
|
|
now := time.Now().UTC()
|
|
tk.RevokedAt = &now
|
|
return nil
|
|
}
|
|
|
|
func (t tokenStore) TouchLastUsed(_ context.Context, jti ids.TokenID) error {
|
|
t.s.mu.Lock()
|
|
defer t.s.mu.Unlock()
|
|
tk, ok := t.s.tokens[jti]
|
|
if !ok {
|
|
return store.ErrNotFound
|
|
}
|
|
now := time.Now().UTC()
|
|
tk.LastUsedAt = &now
|
|
return nil
|
|
}
|
|
|
|
func (t tokenStore) AddDenylist(_ context.Context, jti ids.TokenID, expiresAt time.Time, _ string) error {
|
|
t.s.mu.Lock()
|
|
defer t.s.mu.Unlock()
|
|
t.s.denylist[jti] = expiresAt
|
|
return nil
|
|
}
|
|
|
|
func (t tokenStore) IsDenied(_ context.Context, jti ids.TokenID) (bool, error) {
|
|
t.s.mu.Lock()
|
|
defer t.s.mu.Unlock()
|
|
exp, ok := t.s.denylist[jti]
|
|
if !ok {
|
|
return false, nil
|
|
}
|
|
return exp.After(time.Now()), nil
|
|
}
|
|
|
|
func (t tokenStore) PruneDenylist(_ context.Context) error {
|
|
t.s.mu.Lock()
|
|
defer t.s.mu.Unlock()
|
|
now := time.Now()
|
|
for k, exp := range t.s.denylist {
|
|
if !exp.After(now) {
|
|
delete(t.s.denylist, k)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ---- Nodes ----------------------------------------------------------------
|
|
|
|
type nodeStore struct{ s *Store }
|
|
|
|
func (n nodeStore) Upsert(_ context.Context, node *store.Node) error {
|
|
n.s.mu.Lock()
|
|
defer n.s.mu.Unlock()
|
|
existing, ok := n.s.nodes[node.ID]
|
|
now := time.Now().UTC()
|
|
if ok {
|
|
// Preserve drained status; don't auto-revive a drained node.
|
|
status := existing.Status
|
|
if status != store.NodeStatusDrained {
|
|
status = store.NodeStatusUp
|
|
}
|
|
existing.DisplayName = node.DisplayName
|
|
existing.Multiaddrs = append(node.Multiaddrs[:0:0], node.Multiaddrs...)
|
|
existing.RPCURL = node.RPCURL
|
|
existing.Status = status
|
|
existing.LastSeenAt = now
|
|
existing.UpdatedAt = now
|
|
return nil
|
|
}
|
|
v := *node
|
|
v.Status = store.NodeStatusUp
|
|
v.JoinedAt = now
|
|
v.LastSeenAt = now
|
|
v.UpdatedAt = now
|
|
n.s.nodes[node.ID] = &v
|
|
return nil
|
|
}
|
|
|
|
func (n nodeStore) Get(_ context.Context, id ids.NodeID) (*store.Node, error) {
|
|
n.s.mu.Lock()
|
|
defer n.s.mu.Unlock()
|
|
node, ok := n.s.nodes[id]
|
|
if !ok {
|
|
return nil, store.ErrNotFound
|
|
}
|
|
v := *node
|
|
return &v, nil
|
|
}
|
|
|
|
func (n nodeStore) ListAll(_ context.Context) ([]*store.Node, error) {
|
|
n.s.mu.Lock()
|
|
defer n.s.mu.Unlock()
|
|
out := make([]*store.Node, 0, len(n.s.nodes))
|
|
for _, node := range n.s.nodes {
|
|
v := *node
|
|
out = append(out, &v)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (n nodeStore) ListLive(_ context.Context) ([]*store.Node, error) {
|
|
n.s.mu.Lock()
|
|
defer n.s.mu.Unlock()
|
|
out := []*store.Node{}
|
|
for _, node := range n.s.nodes {
|
|
if node.Status == store.NodeStatusUp {
|
|
v := *node
|
|
out = append(out, &v)
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (n nodeStore) TouchHeartbeat(_ context.Context, id ids.NodeID) error {
|
|
n.s.mu.Lock()
|
|
defer n.s.mu.Unlock()
|
|
node, ok := n.s.nodes[id]
|
|
if !ok {
|
|
return store.ErrNotFound
|
|
}
|
|
node.LastSeenAt = time.Now().UTC()
|
|
return nil
|
|
}
|
|
|
|
func (n nodeStore) MarkStaleDown(_ context.Context, staleAfter time.Duration) ([]ids.NodeID, error) {
|
|
n.s.mu.Lock()
|
|
defer n.s.mu.Unlock()
|
|
cutoff := time.Now().Add(-staleAfter)
|
|
out := []ids.NodeID{}
|
|
for _, node := range n.s.nodes {
|
|
if node.Status == store.NodeStatusUp && node.LastSeenAt.Before(cutoff) {
|
|
node.Status = store.NodeStatusDown
|
|
out = append(out, node.ID)
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (n nodeStore) Drain(_ context.Context, id ids.NodeID) error {
|
|
n.s.mu.Lock()
|
|
defer n.s.mu.Unlock()
|
|
node, ok := n.s.nodes[id]
|
|
if !ok {
|
|
return store.ErrNotFound
|
|
}
|
|
node.Status = store.NodeStatusDrained
|
|
return nil
|
|
}
|
|
|
|
func (n nodeStore) Uncordon(_ context.Context, id ids.NodeID) error {
|
|
n.s.mu.Lock()
|
|
defer n.s.mu.Unlock()
|
|
node, ok := n.s.nodes[id]
|
|
if !ok {
|
|
return store.ErrNotFound
|
|
}
|
|
if node.Status == store.NodeStatusDrained {
|
|
node.Status = store.NodeStatusUp
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ---- Pins -----------------------------------------------------------------
|
|
|
|
type pinStore struct{ s *Store }
|
|
|
|
func pinPlacementKey(pid ids.PinID, nid ids.NodeID) string {
|
|
return pid.String() + "|" + nid.String()
|
|
}
|
|
|
|
func refcountKey(nid ids.NodeID, cid string) string {
|
|
return nid.String() + "|" + cid
|
|
}
|
|
|
|
func (p pinStore) Create(_ context.Context, pin *store.Pin) error {
|
|
p.s.mu.Lock()
|
|
defer p.s.mu.Unlock()
|
|
// Idempotency guard: one live pin per (org, cid).
|
|
for _, existing := range p.s.pins {
|
|
if existing.OrgID == pin.OrgID && existing.CID == pin.CID && existing.Status != store.PinStatusFailed {
|
|
return store.ErrConflict
|
|
}
|
|
}
|
|
v := *pin
|
|
p.s.pins[pin.RequestID] = &v
|
|
return nil
|
|
}
|
|
|
|
func (p pinStore) Get(_ context.Context, orgID ids.OrgID, rid ids.PinID) (*store.Pin, error) {
|
|
p.s.mu.Lock()
|
|
defer p.s.mu.Unlock()
|
|
pin, ok := p.s.pins[rid]
|
|
if !ok || pin.OrgID != orgID {
|
|
return nil, store.ErrNotFound
|
|
}
|
|
v := *pin
|
|
return &v, nil
|
|
}
|
|
|
|
func (p pinStore) GetByRequestID(_ context.Context, rid ids.PinID) (*store.Pin, error) {
|
|
p.s.mu.Lock()
|
|
defer p.s.mu.Unlock()
|
|
pin, ok := p.s.pins[rid]
|
|
if !ok {
|
|
return nil, store.ErrNotFound
|
|
}
|
|
v := *pin
|
|
return &v, nil
|
|
}
|
|
|
|
func (p pinStore) GetLiveByCID(_ context.Context, orgID ids.OrgID, cid string) (*store.Pin, error) {
|
|
p.s.mu.Lock()
|
|
defer p.s.mu.Unlock()
|
|
for _, pin := range p.s.pins {
|
|
if pin.OrgID == orgID && pin.CID == cid && pin.Status != store.PinStatusFailed {
|
|
v := *pin
|
|
return &v, nil
|
|
}
|
|
}
|
|
return nil, store.ErrNotFound
|
|
}
|
|
|
|
func (p pinStore) UpdateStatus(_ context.Context, rid ids.PinID, status string, fr *string) error {
|
|
p.s.mu.Lock()
|
|
defer p.s.mu.Unlock()
|
|
pin, ok := p.s.pins[rid]
|
|
if !ok {
|
|
return store.ErrNotFound
|
|
}
|
|
pin.Status = status
|
|
pin.FailureReason = fr
|
|
pin.UpdatedAt = time.Now().UTC()
|
|
return nil
|
|
}
|
|
|
|
// Delete removes the pin and cascades through pin_placements and
|
|
// pin_refcount — matching Postgres's ON DELETE CASCADE on placements
|
|
// and the app-level refcount decrement for each placement's CID.
|
|
func (p pinStore) Delete(_ context.Context, orgID ids.OrgID, rid ids.PinID) error {
|
|
p.s.mu.Lock()
|
|
defer p.s.mu.Unlock()
|
|
pin, ok := p.s.pins[rid]
|
|
if !ok || pin.OrgID != orgID {
|
|
return store.ErrNotFound
|
|
}
|
|
// Walk placements for this pin and decrement their refcounts.
|
|
for k, pl := range p.s.placements {
|
|
if pl.RequestID != rid {
|
|
continue
|
|
}
|
|
delete(p.s.placements, k)
|
|
rk := refcountKey(pl.NodeID, pin.CID)
|
|
if c, ok := p.s.refcounts[rk]; ok {
|
|
c--
|
|
if c <= 0 {
|
|
delete(p.s.refcounts, rk)
|
|
} else {
|
|
p.s.refcounts[rk] = c
|
|
}
|
|
}
|
|
}
|
|
delete(p.s.pins, rid)
|
|
return nil
|
|
}
|
|
|
|
func (p pinStore) List(_ context.Context, orgID ids.OrgID, limit, offset int) ([]*store.Pin, error) {
|
|
p.s.mu.Lock()
|
|
defer p.s.mu.Unlock()
|
|
out := []*store.Pin{}
|
|
for _, pin := range p.s.pins {
|
|
if pin.OrgID == orgID {
|
|
v := *pin
|
|
out = append(out, &v)
|
|
}
|
|
}
|
|
// Sort by Created descending for stable pagination.
|
|
sortPins(out)
|
|
return paginate(out, limit, offset), nil
|
|
}
|
|
|
|
func (p pinStore) Filter(_ context.Context, orgID ids.OrgID, f store.PinFilter) ([]*store.Pin, error) {
|
|
p.s.mu.Lock()
|
|
defer p.s.mu.Unlock()
|
|
|
|
cidSet := map[string]bool{}
|
|
for _, c := range f.CIDs {
|
|
cidSet[c] = true
|
|
}
|
|
statusSet := map[string]bool{}
|
|
for _, s := range f.Status {
|
|
statusSet[s] = true
|
|
}
|
|
nameMatcher := newNameMatcher(f.Name, f.Match)
|
|
|
|
out := []*store.Pin{}
|
|
for _, pin := range p.s.pins {
|
|
if pin.OrgID != orgID {
|
|
continue
|
|
}
|
|
if len(cidSet) > 0 && !cidSet[pin.CID] {
|
|
continue
|
|
}
|
|
if len(statusSet) > 0 && !statusSet[pin.Status] {
|
|
continue
|
|
}
|
|
if f.Before != nil && !pin.Created.Before(*f.Before) {
|
|
continue
|
|
}
|
|
if f.After != nil && pin.Created.Before(*f.After) {
|
|
continue
|
|
}
|
|
if !nameMatcher(pin.Name) {
|
|
continue
|
|
}
|
|
if !metaContains(pin.Meta, f.Meta) {
|
|
continue
|
|
}
|
|
v := *pin
|
|
out = append(out, &v)
|
|
}
|
|
sortPins(out)
|
|
return paginate(out, f.Limit, f.Offset), nil
|
|
}
|
|
|
|
// Replace atomically swaps CID/name/meta/origins on an existing pin.
|
|
// Caller's transaction handles refcount bookkeeping.
|
|
func (p pinStore) Replace(_ context.Context, orgID ids.OrgID, rid ids.PinID, newCID string, name *string, meta map[string]any, origins []string) (*store.Pin, error) {
|
|
p.s.mu.Lock()
|
|
defer p.s.mu.Unlock()
|
|
pin, ok := p.s.pins[rid]
|
|
if !ok || pin.OrgID != orgID {
|
|
return nil, store.ErrNotFound
|
|
}
|
|
pin.CID = newCID
|
|
pin.Name = name
|
|
pin.Meta = meta
|
|
pin.Origins = origins
|
|
pin.Status = store.PinStatusQueued
|
|
pin.FailureReason = nil
|
|
pin.UpdatedAt = time.Now().UTC()
|
|
v := *pin
|
|
return &v, nil
|
|
}
|
|
|
|
// newNameMatcher compiles the spec's name/match filter into a predicate
|
|
// over (*string). An empty name field means "no restriction".
|
|
func newNameMatcher(name, match string) func(*string) bool {
|
|
if name == "" {
|
|
return func(*string) bool { return true }
|
|
}
|
|
lower := strings.ToLower(name)
|
|
switch match {
|
|
case "exact":
|
|
return func(p *string) bool { return p != nil && *p == name }
|
|
case "partial":
|
|
return func(p *string) bool { return p != nil && strings.Contains(*p, name) }
|
|
case "ipartial":
|
|
return func(p *string) bool { return p != nil && strings.Contains(strings.ToLower(*p), lower) }
|
|
case "iexact", "":
|
|
return func(p *string) bool { return p != nil && strings.EqualFold(*p, name) }
|
|
default:
|
|
return func(*string) bool { return false }
|
|
}
|
|
}
|
|
|
|
// metaContains returns true when every key/value in want is present in
|
|
// got with an equal value (jsonb @> semantics for the simple case).
|
|
func metaContains(got, want map[string]any) bool {
|
|
if len(want) == 0 {
|
|
return true
|
|
}
|
|
if got == nil {
|
|
return false
|
|
}
|
|
for k, wv := range want {
|
|
gv, ok := got[k]
|
|
if !ok || !mapValueEqual(gv, wv) {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func mapValueEqual(a, b any) bool {
|
|
// Simple deep-eq sufficient for JSON scalars + flat maps; the full
|
|
// jsonb @> recursion is only needed by the Postgres backend.
|
|
return fmt.Sprintf("%v", a) == fmt.Sprintf("%v", b)
|
|
}
|
|
|
|
func (p pinStore) InsertPlacement(_ context.Context, rid ids.PinID, nid ids.NodeID, fence int64) (*store.Placement, error) {
|
|
p.s.mu.Lock()
|
|
defer p.s.mu.Unlock()
|
|
now := time.Now().UTC()
|
|
pl := &store.Placement{
|
|
RequestID: rid,
|
|
NodeID: nid,
|
|
Status: store.PinStatusQueued,
|
|
Fence: fence,
|
|
CreatedAt: now,
|
|
UpdatedAt: now,
|
|
}
|
|
p.s.placements[pinPlacementKey(rid, nid)] = pl
|
|
v := *pl
|
|
return &v, nil
|
|
}
|
|
|
|
func (p pinStore) GetPlacement(_ context.Context, rid ids.PinID, nid ids.NodeID) (*store.Placement, error) {
|
|
p.s.mu.Lock()
|
|
defer p.s.mu.Unlock()
|
|
pl, ok := p.s.placements[pinPlacementKey(rid, nid)]
|
|
if !ok {
|
|
return nil, store.ErrNotFound
|
|
}
|
|
v := *pl
|
|
return &v, nil
|
|
}
|
|
|
|
func (p pinStore) ListPlacements(_ context.Context, rid ids.PinID) ([]*store.Placement, error) {
|
|
p.s.mu.Lock()
|
|
defer p.s.mu.Unlock()
|
|
out := []*store.Placement{}
|
|
for _, pl := range p.s.placements {
|
|
if pl.RequestID == rid {
|
|
v := *pl
|
|
if node, ok := p.s.nodes[pl.NodeID]; ok {
|
|
v.Multiaddrs = append([]string(nil), node.Multiaddrs...)
|
|
}
|
|
out = append(out, &v)
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (p pinStore) ListPlacementsForNode(_ context.Context, nid ids.NodeID, status string) ([]*store.Placement, error) {
|
|
p.s.mu.Lock()
|
|
defer p.s.mu.Unlock()
|
|
out := []*store.Placement{}
|
|
for _, pl := range p.s.placements {
|
|
if pl.NodeID == nid && (status == "" || pl.Status == status) {
|
|
v := *pl
|
|
out = append(out, &v)
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (p pinStore) UpdatePlacementFenced(_ context.Context, rid ids.PinID, nid ids.NodeID, status string, fr *string, fence int64) (int64, error) {
|
|
p.s.mu.Lock()
|
|
defer p.s.mu.Unlock()
|
|
pl, ok := p.s.placements[pinPlacementKey(rid, nid)]
|
|
if !ok || pl.Fence != fence {
|
|
return 0, nil // zero rows — fence mismatch or missing
|
|
}
|
|
pl.Status = status
|
|
pl.FailureReason = fr
|
|
pl.Attempts++
|
|
pl.UpdatedAt = time.Now().UTC()
|
|
return 1, nil
|
|
}
|
|
|
|
func (p pinStore) ReplacePlacement(_ context.Context, rid ids.PinID, oldNode, newNode ids.NodeID) (*store.Placement, error) {
|
|
p.s.mu.Lock()
|
|
defer p.s.mu.Unlock()
|
|
oldKey := pinPlacementKey(rid, oldNode)
|
|
pl, ok := p.s.placements[oldKey]
|
|
if !ok {
|
|
return nil, store.ErrNotFound
|
|
}
|
|
delete(p.s.placements, oldKey)
|
|
newPl := &store.Placement{
|
|
RequestID: rid,
|
|
NodeID: newNode,
|
|
Status: store.PinStatusQueued,
|
|
Fence: pl.Fence + 1,
|
|
CreatedAt: time.Now().UTC(),
|
|
UpdatedAt: time.Now().UTC(),
|
|
}
|
|
p.s.placements[pinPlacementKey(rid, newNode)] = newPl
|
|
v := *newPl
|
|
return &v, nil
|
|
}
|
|
|
|
func (p pinStore) StuckPlacements(_ context.Context, stuckAfter time.Duration) ([]store.Placement, error) {
|
|
p.s.mu.Lock()
|
|
defer p.s.mu.Unlock()
|
|
cutoff := time.Now().Add(-stuckAfter)
|
|
out := []store.Placement{}
|
|
for _, pl := range p.s.placements {
|
|
if pl.Status == store.PinStatusQueued && pl.CreatedAt.Before(cutoff) {
|
|
out = append(out, *pl)
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (p pinStore) IncRefcount(_ context.Context, nid ids.NodeID, cid string) error {
|
|
p.s.mu.Lock()
|
|
defer p.s.mu.Unlock()
|
|
p.s.refcounts[refcountKey(nid, cid)]++
|
|
return nil
|
|
}
|
|
|
|
func (p pinStore) DecRefcount(_ context.Context, nid ids.NodeID, cid string) (int, error) {
|
|
p.s.mu.Lock()
|
|
defer p.s.mu.Unlock()
|
|
k := refcountKey(nid, cid)
|
|
c, ok := p.s.refcounts[k]
|
|
if !ok {
|
|
return 0, store.ErrNotFound
|
|
}
|
|
c--
|
|
if c < 0 {
|
|
c = 0
|
|
}
|
|
p.s.refcounts[k] = c
|
|
return c, nil
|
|
}
|
|
|
|
func (p pinStore) DeleteRefcountIfZero(_ context.Context, nid ids.NodeID, cid string) error {
|
|
p.s.mu.Lock()
|
|
defer p.s.mu.Unlock()
|
|
k := refcountKey(nid, cid)
|
|
if p.s.refcounts[k] <= 0 {
|
|
delete(p.s.refcounts, k)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (p pinStore) CountPlacementsByStatus(_ context.Context) (map[string]int, error) {
|
|
p.s.mu.Lock()
|
|
defer p.s.mu.Unlock()
|
|
out := map[string]int{}
|
|
for _, pl := range p.s.placements {
|
|
out[pl.Status]++
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// ---- Audit ----------------------------------------------------------------
|
|
|
|
type auditStore struct{ s *Store }
|
|
|
|
func (a auditStore) Insert(_ context.Context, e *store.AuditEntry) error {
|
|
a.s.mu.Lock()
|
|
defer a.s.mu.Unlock()
|
|
a.s.nextAudit++
|
|
v := *e
|
|
v.ID = a.s.nextAudit
|
|
if v.Created.IsZero() {
|
|
v.Created = time.Now().UTC()
|
|
}
|
|
a.s.audit = append(a.s.audit, &v)
|
|
return nil
|
|
}
|
|
|
|
// List returns audit entries newest-first. A zero-value orgID is treated
|
|
// as "all orgs" (the sysadmin cluster-wide query); any non-zero orgID
|
|
// filters to entries whose OrgID matches.
|
|
func (a auditStore) List(_ context.Context, orgID ids.OrgID, limit, offset int) ([]*store.AuditEntry, error) {
|
|
a.s.mu.Lock()
|
|
defer a.s.mu.Unlock()
|
|
out := []*store.AuditEntry{}
|
|
allOrgs := orgID.IsZero()
|
|
for i := len(a.s.audit) - 1; i >= 0; i-- {
|
|
e := a.s.audit[i]
|
|
if allOrgs || (e.OrgID != nil && *e.OrgID == orgID) {
|
|
v := *e
|
|
out = append(out, &v)
|
|
}
|
|
}
|
|
return paginate(out, limit, offset), nil
|
|
}
|
|
|
|
// ---- helpers --------------------------------------------------------------
|
|
|
|
func paginate[T any](xs []T, limit, offset int) []T {
|
|
if offset < 0 {
|
|
offset = 0
|
|
}
|
|
if offset >= len(xs) {
|
|
return nil
|
|
}
|
|
xs = xs[offset:]
|
|
if limit > 0 && limit < len(xs) {
|
|
xs = xs[:limit]
|
|
}
|
|
return xs
|
|
}
|
|
|
|
func sortPins(ps []*store.Pin) {
|
|
// Bubble sort is fine — memstore is test-only.
|
|
for i := 0; i < len(ps); i++ {
|
|
for j := i + 1; j < len(ps); j++ {
|
|
if ps[j].Created.After(ps[i].Created) {
|
|
ps[i], ps[j] = ps[j], ps[i]
|
|
}
|
|
}
|
|
}
|
|
}
|