anchorage v1.0 initial tree

Greenfield Go multi-tenant IPFS Pinning Service wire-compatible with the
IPFS Pinning Services API spec. Paired 1:1 with Kubo over localhost RPC,
clustered via embedded NATS JetStream, Postgres source-of-truth with
RLS-enforced tenancy, Fiber + huma v2 for the HTTP surface, Authentik
OIDC for session login with kid-rotated HS256 JWT API tokens.

Feature-complete against the 22-milestone build plan, including the
ship-it v1.0 gap items:

  * admin CLIs: drain/uncordon, maintenance, mint-token, rotate-key,
    prune-denylist, rebalance --dry-run, cache-stats, cluster-presences
  * TTL leader election via NATS KV, fence tokens, JetStream dedup
  * rebalancer (plan/apply split), reconciler, requeue sweeper
  * ristretto caches with NATS-backed cross-node invalidation
    (placements live-nodes + token denylist)
  * maintenance watchdog for stuck cluster-pause flag
  * Prometheus /metrics with CIDR ACL, HTTP/pin/scheduler/cache gauges
  * rate limiting: session (10/min) + anonymous global (120/min)
  * integration tests: rebalance, refcount multi-org, RLS belt
  * goreleaser (tar + deb/rpm/apk + Alpine Docker) targeting Gitea

Stack: Cobra/Viper, Fiber v2 + huma v2, embedded NATS JetStream,
pgx/sqlc/golang-migrate, ristretto, TypeID, prometheus/client_golang,
testcontainers-go.
This commit is contained in:
57_Wolve committed 2026-04-16 18:13:36 -05:00
commit 12bf35caf8
112 files changed
+16884

No files matched your search

+142
View File
@@ -0,0 +1,142 @@
package postgres
import (
"context"
"errors"
"fmt"
"github.com/golang-migrate/migrate/v4"
_ "github.com/golang-migrate/migrate/v4/database/postgres" // register postgres:// driver
"github.com/golang-migrate/migrate/v4/source/iofs"
"github.com/jackc/pgx/v5/pgxpool"
"anchorage/internal/pkg/store/postgres/migrations"
)
// MigrateDirection selects up/down for Migrate.
type MigrateDirection int
const (
// MigrateUp applies all pending up migrations.
MigrateUp MigrateDirection = iota
// MigrateDown reverts every applied migration (dev / test only).
MigrateDown
)
// MigrateOptions tunes migration behavior.
type MigrateOptions struct {
// LockID is the key used with pg_advisory_lock to serialize concurrent
// migration attempts from N replicas starting simultaneously. Must be
// stable across deploys. Any non-zero int64 works; the default is fine
// unless an operator has a collision with another app sharing the DB.
LockID int64
}
// DefaultLockID is the advisory-lock key anchorage uses for schema migrations.
// Chosen arbitrarily but stably.
const DefaultLockID int64 = 0x616e63686f726167 // "anchorag" as hex
// Migrate runs the embedded schema migrations against the DSN.
//
// The pgxpool is only used to discover the DSN so we don't open two
// connections to the same database — golang-migrate's postgres driver
// wants a *sql.DB, which pgx does not provide directly. We read the DSN
// back from the pool config and let migrate open its own driver.
//
// golang-migrate acquires a Postgres advisory lock before running, so N
// replicas starting simultaneously all block on the same lock and exactly
// one of them actually runs the migration; the others see a no-op.
func Migrate(ctx context.Context, pool *pgxpool.Pool, dir MigrateDirection, opts MigrateOptions) error {
if pool == nil {
return errors.New("migrate: pool is required")
}
dsn := pool.Config().ConnString()
return MigrateDSN(ctx, dsn, dir, opts)
}
// MigrateDSN is the pool-less variant, used by CLI subcommands that have
// a DSN but don't need a warm pool.
func MigrateDSN(ctx context.Context, dsn string, dir MigrateDirection, opts MigrateOptions) error {
src, err := iofs.New(migrations.FS, ".")
if err != nil {
return fmt.Errorf("open embedded migrations: %w", err)
}
lockID := opts.LockID
if lockID == 0 {
lockID = DefaultLockID
}
// golang-migrate v4's postgres driver reads config from URL query params:
// x-migrations-table, x-advisory-lock-id, and others. Append ours without
// clobbering user-supplied params.
migrateDSN := appendQuery(dsn, "x-migrations-table", "anchorage_schema_migrations")
migrateDSN = appendQuery(migrateDSN, "x-advisory-lock-id", fmt.Sprintf("%d", lockID))
m, err := migrate.NewWithSourceInstance("iofs", src, migrateDSN)
if err != nil {
return fmt.Errorf("init migrate: %w", err)
}
defer func() {
_, _ = m.Close()
}()
runCh := make(chan error, 1)
go func() {
switch dir {
case MigrateUp:
runCh <- m.Up()
case MigrateDown:
runCh <- m.Down()
default:
runCh <- fmt.Errorf("unknown migrate direction %d", dir)
}
}()
select {
case err := <-runCh:
if err != nil && !errors.Is(err, migrate.ErrNoChange) {
return fmt.Errorf("run migrations: %w", err)
}
return nil
case <-ctx.Done():
// migrate has no ctx plumbing; surface the cancellation but let
// the goroutine finish so we don't leak a connection.
return ctx.Err()
}
}
// MigrationVersion returns the currently-applied schema version and
// whether the last migration is in a dirty state. Used by `anchorage
// migrate status`.
func MigrationVersion(ctx context.Context, dsn string) (version uint, dirty bool, err error) {
src, err := iofs.New(migrations.FS, ".")
if err != nil {
return 0, false, fmt.Errorf("open embedded migrations: %w", err)
}
m, err := migrate.NewWithSourceInstance("iofs", src, dsn)
if err != nil {
return 0, false, fmt.Errorf("init migrate: %w", err)
}
defer func() { _, _ = m.Close() }()
v, d, err := m.Version()
if errors.Is(err, migrate.ErrNilVersion) {
return 0, false, nil
}
return v, d, err
}
// appendQuery adds a key=value to a DSN's query string, preserving
// existing params. Handles both postgres:// URL form and space-delimited
// libpq form; on failure to parse, falls back to unmodified.
func appendQuery(dsn, k, v string) string {
sep := "?"
for _, c := range dsn {
if c == '?' {
sep = "&"
break
}
}
return dsn + sep + k + "=" + v
}
@@ -0,0 +1,16 @@
BEGIN;
DROP TABLE IF EXISTS audit_log CASCADE;
DROP TABLE IF EXISTS pin_refcount CASCADE;
DROP TABLE IF EXISTS pin_placements CASCADE;
DROP TABLE IF EXISTS pins CASCADE;
DROP TABLE IF EXISTS nodes CASCADE;
DROP TABLE IF EXISTS token_denylist CASCADE;
DROP TABLE IF EXISTS api_tokens CASCADE;
DROP TABLE IF EXISTS memberships CASCADE;
DROP TABLE IF EXISTS users CASCADE;
DROP TABLE IF EXISTS orgs CASCADE;
DROP FUNCTION IF EXISTS anchorage_touch_updated_at();
COMMIT;
@@ -0,0 +1,217 @@
-- anchorage initial schema.
--
-- Every tenant-scoped table carries org_id and enables row-level security
-- so a Go-layer bug cannot bleed rows across orgs. The application sets
-- current_setting('anchorage.org_id') per-transaction via the auth middleware.
BEGIN;
CREATE EXTENSION IF NOT EXISTS citext;
CREATE EXTENSION IF NOT EXISTS pg_trgm;
-- ---------------------------------------------------------------------------
-- orgs
-- ---------------------------------------------------------------------------
CREATE TABLE orgs (
id text PRIMARY KEY CHECK (id LIKE 'org_%'),
slug text NOT NULL UNIQUE,
name text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
-- ---------------------------------------------------------------------------
-- users
-- ---------------------------------------------------------------------------
CREATE TABLE users (
id text PRIMARY KEY CHECK (id LIKE 'usr_%'),
authentik_sub text UNIQUE,
email citext NOT NULL UNIQUE,
display_name text NOT NULL DEFAULT '',
is_sysadmin boolean NOT NULL DEFAULT false,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
-- ---------------------------------------------------------------------------
-- memberships
-- ---------------------------------------------------------------------------
CREATE TABLE memberships (
org_id text NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
user_id text NOT NULL REFERENCES users(id) ON DELETE CASCADE,
role text NOT NULL CHECK (role IN ('orgadmin', 'member')),
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (org_id, user_id)
);
CREATE INDEX memberships_user_idx ON memberships (user_id);
-- ---------------------------------------------------------------------------
-- api_tokens — JWT metadata only; the signed token is never stored
-- ---------------------------------------------------------------------------
CREATE TABLE api_tokens (
jti text PRIMARY KEY CHECK (jti LIKE 'tok_%'),
org_id text NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
user_id text NOT NULL REFERENCES users(id) ON DELETE CASCADE,
label text NOT NULL,
scopes text[] NOT NULL DEFAULT '{}',
expires_at timestamptz NOT NULL,
revoked_at timestamptz,
last_used_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX api_tokens_org_idx ON api_tokens (org_id, created_at DESC);
CREATE INDEX api_tokens_expiry_idx ON api_tokens (expires_at) WHERE revoked_at IS NULL;
-- ---------------------------------------------------------------------------
-- token_denylist — explicit revocation cache, TTL'd by expires_at
-- ---------------------------------------------------------------------------
CREATE TABLE token_denylist (
jti text PRIMARY KEY,
expires_at timestamptz NOT NULL,
reason text NOT NULL DEFAULT 'revoked',
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX token_denylist_expiry_idx ON token_denylist (expires_at);
-- ---------------------------------------------------------------------------
-- nodes — cluster registry populated on boot and maintained by heartbeats
-- ---------------------------------------------------------------------------
CREATE TABLE nodes (
id text PRIMARY KEY CHECK (id LIKE 'nod_%'),
display_name text NOT NULL DEFAULT '',
multiaddrs text[] NOT NULL DEFAULT '{}',
rpc_url text NOT NULL,
status text NOT NULL CHECK (status IN ('up', 'down', 'drained')),
last_seen_at timestamptz NOT NULL DEFAULT now(),
joined_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX nodes_status_idx ON nodes (status, last_seen_at DESC);
-- ---------------------------------------------------------------------------
-- pins — logical pin records (spec: PinStatus)
-- ---------------------------------------------------------------------------
CREATE TABLE pins (
request_id text PRIMARY KEY CHECK (request_id LIKE 'pin_%'),
org_id text NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
cid text NOT NULL,
name text,
meta jsonb NOT NULL DEFAULT '{}'::jsonb,
origins text[] NOT NULL DEFAULT '{}',
status text NOT NULL CHECK (status IN ('queued', 'pinning', 'pinned', 'failed')),
failure_reason text,
created timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX pins_org_created_idx ON pins (org_id, created DESC);
CREATE INDEX pins_org_status_created_idx ON pins (org_id, status, created DESC);
CREATE INDEX pins_org_cid_idx ON pins (org_id, cid);
CREATE INDEX pins_org_lower_name_idx ON pins (org_id, lower(name) text_pattern_ops);
CREATE INDEX pins_name_trgm_idx ON pins USING gin (lower(name) gin_trgm_ops);
CREATE INDEX pins_meta_gin_idx ON pins USING gin (meta jsonb_path_ops);
-- Idempotent create: `POST /v1/pins` with the same (org_id, cid) collapses
-- to the existing live row. Failed pins may be retried with the same CID.
CREATE UNIQUE INDEX pins_org_cid_live_uniq
ON pins (org_id, cid) WHERE status <> 'failed';
-- ---------------------------------------------------------------------------
-- pin_placements — per-node scheduling rows; fence guards against zombies
-- ---------------------------------------------------------------------------
CREATE TABLE pin_placements (
request_id text NOT NULL REFERENCES pins(request_id) ON DELETE CASCADE,
node_id text NOT NULL REFERENCES nodes(id) ON DELETE RESTRICT,
status text NOT NULL CHECK (status IN ('queued', 'pinning', 'pinned', 'failed')),
failure_reason text,
attempts int NOT NULL DEFAULT 0,
fence bigint NOT NULL DEFAULT 1,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (request_id, node_id)
);
CREATE INDEX pin_placements_node_status_idx ON pin_placements (node_id, status);
CREATE INDEX pin_placements_request_id_idx ON pin_placements (request_id);
-- ---------------------------------------------------------------------------
-- pin_refcount — per-(node, cid) reference counting; row deletion = unpin
-- ---------------------------------------------------------------------------
CREATE TABLE pin_refcount (
node_id text NOT NULL REFERENCES nodes(id) ON DELETE RESTRICT,
cid text NOT NULL,
count int NOT NULL CHECK (count >= 0),
updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (node_id, cid)
);
-- ---------------------------------------------------------------------------
-- audit_log — append-only; bigserial is fine here (not user-facing)
-- ---------------------------------------------------------------------------
CREATE TABLE audit_log (
id bigserial PRIMARY KEY,
org_id text REFERENCES orgs(id) ON DELETE CASCADE,
actor_user_id text REFERENCES users(id) ON DELETE SET NULL,
actor_token_jti text,
action text NOT NULL,
target text NOT NULL,
result text NOT NULL CHECK (result IN ('ok', 'error')),
detail jsonb NOT NULL DEFAULT '{}'::jsonb,
created timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX audit_log_org_created_idx ON audit_log (org_id, created DESC);
CREATE INDEX audit_log_actor_created_idx ON audit_log (actor_user_id, created DESC);
-- ---------------------------------------------------------------------------
-- updated_at trigger
-- ---------------------------------------------------------------------------
CREATE OR REPLACE FUNCTION anchorage_touch_updated_at() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.updated_at := now();
RETURN NEW;
END;
$$;
CREATE TRIGGER orgs_touch BEFORE UPDATE ON orgs FOR EACH ROW EXECUTE FUNCTION anchorage_touch_updated_at();
CREATE TRIGGER users_touch BEFORE UPDATE ON users FOR EACH ROW EXECUTE FUNCTION anchorage_touch_updated_at();
CREATE TRIGGER memberships_touch BEFORE UPDATE ON memberships FOR EACH ROW EXECUTE FUNCTION anchorage_touch_updated_at();
CREATE TRIGGER api_tokens_touch BEFORE UPDATE ON api_tokens FOR EACH ROW EXECUTE FUNCTION anchorage_touch_updated_at();
CREATE TRIGGER nodes_touch BEFORE UPDATE ON nodes FOR EACH ROW EXECUTE FUNCTION anchorage_touch_updated_at();
CREATE TRIGGER pins_touch BEFORE UPDATE ON pins FOR EACH ROW EXECUTE FUNCTION anchorage_touch_updated_at();
CREATE TRIGGER pin_placements_touch BEFORE UPDATE ON pin_placements FOR EACH ROW EXECUTE FUNCTION anchorage_touch_updated_at();
CREATE TRIGGER pin_refcount_touch BEFORE UPDATE ON pin_refcount FOR EACH ROW EXECUTE FUNCTION anchorage_touch_updated_at();
-- ---------------------------------------------------------------------------
-- Row-level security — belt-and-suspenders tenant isolation
-- ---------------------------------------------------------------------------
ALTER TABLE memberships ENABLE ROW LEVEL SECURITY;
ALTER TABLE api_tokens ENABLE ROW LEVEL SECURITY;
ALTER TABLE pins ENABLE ROW LEVEL SECURITY;
-- current_setting with the second arg = true returns NULL for unset keys
-- instead of raising. An unset GUC means "no tenant context" and returns
-- zero rows, which is the safe default.
CREATE POLICY memberships_tenant_isolation ON memberships
FOR ALL
USING (org_id = current_setting('anchorage.org_id', true))
WITH CHECK (org_id = current_setting('anchorage.org_id', true));
CREATE POLICY api_tokens_tenant_isolation ON api_tokens
FOR ALL
USING (org_id = current_setting('anchorage.org_id', true))
WITH CHECK (org_id = current_setting('anchorage.org_id', true));
CREATE POLICY pins_tenant_isolation ON pins
FOR ALL
USING (org_id = current_setting('anchorage.org_id', true))
WITH CHECK (org_id = current_setting('anchorage.org_id', true));
COMMIT;
@@ -0,0 +1,15 @@
// Package migrations holds anchorage's Postgres schema as an embed.FS so
// the binary is self-contained and migrations can never drift from the
// code that expects them.
package migrations
import "embed"
// FS is the embedded iofs source passed to golang-migrate.
//
// Each migration is two files named NNNN_description.up.sql and
// NNNN_description.down.sql; golang-migrate treats the leading integer
// as the version number.
//
//go:embed *.sql
var FS embed.FS
+59
View File
@@ -0,0 +1,59 @@
// Package postgres is anchorage's Postgres adapter: pgxpool lifecycle,
// schema migrations, and the concrete implementation of the store
// interfaces defined in internal/pkg/store.
package postgres
import (
"context"
"fmt"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
// PoolConfig is the subset of config.PostgresConfig the pool needs. Kept
// as a local struct so callers (tests, migrate subcommand) can construct
// one without importing the full config package.
type PoolConfig struct {
DSN string
MaxConns int
}
// NewPool constructs a pgxpool.Pool and verifies connectivity with a ping.
//
// The caller is responsible for calling pool.Close() at shutdown. A zero
// or negative MaxConns falls back to pgxpool's default.
func NewPool(ctx context.Context, cfg PoolConfig) (*pgxpool.Pool, error) {
if cfg.DSN == "" {
return nil, fmt.Errorf("postgres dsn is required")
}
poolCfg, err := pgxpool.ParseConfig(cfg.DSN)
if err != nil {
return nil, fmt.Errorf("parse postgres dsn: %w", err)
}
if cfg.MaxConns > 0 {
poolCfg.MaxConns = int32(cfg.MaxConns)
}
// Keep idle conns short so Postgres restarts don't wedge old tcp
// connections that will never work again.
poolCfg.MaxConnIdleTime = 5 * time.Minute
poolCfg.MaxConnLifetime = 30 * time.Minute
poolCfg.HealthCheckPeriod = 30 * time.Second
pool, err := pgxpool.NewWithConfig(ctx, poolCfg)
if err != nil {
return nil, fmt.Errorf("open postgres pool: %w", err)
}
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
if err := pool.Ping(pingCtx); err != nil {
pool.Close()
return nil, fmt.Errorf("ping postgres: %w", err)
}
return pool, nil
}
@@ -0,0 +1,9 @@
-- name: InsertAudit :exec
INSERT INTO audit_log (org_id, actor_user_id, actor_token_jti, action, target, result, detail)
VALUES ($1, $2, $3, $4, $5, $6, $7);
-- name: ListAudit :many
SELECT * FROM audit_log
WHERE org_id = $1
ORDER BY created DESC
LIMIT $2 OFFSET $3;
@@ -0,0 +1,37 @@
-- name: UpsertNode :one
INSERT INTO nodes (id, display_name, multiaddrs, rpc_url, status)
VALUES ($1, $2, $3, $4, 'up')
ON CONFLICT (id) DO UPDATE
SET display_name = EXCLUDED.display_name,
multiaddrs = EXCLUDED.multiaddrs,
rpc_url = EXCLUDED.rpc_url,
status = CASE WHEN nodes.status = 'drained' THEN 'drained' ELSE 'up' END,
last_seen_at = now()
RETURNING *;
-- name: GetNode :one
SELECT * FROM nodes WHERE id = $1;
-- name: ListLiveNodes :many
SELECT * FROM nodes WHERE status = 'up' ORDER BY id;
-- name: ListAllNodes :many
SELECT * FROM nodes ORDER BY id;
-- name: TouchNodeHeartbeat :exec
UPDATE nodes SET last_seen_at = now() WHERE id = $1;
-- name: MarkNodeDown :exec
UPDATE nodes SET status = 'down' WHERE id = $1 AND status = 'up';
-- name: DrainNode :exec
UPDATE nodes SET status = 'drained' WHERE id = $1;
-- name: UncordonNode :exec
UPDATE nodes SET status = 'up' WHERE id = $1 AND status = 'drained';
-- name: MarkStaleNodesDown :many
UPDATE nodes
SET status = 'down'
WHERE status = 'up' AND last_seen_at < (now() - make_interval(secs => $1))
RETURNING id;
@@ -0,0 +1,16 @@
-- name: CreateOrg :one
INSERT INTO orgs (id, slug, name)
VALUES ($1, $2, $3)
RETURNING *;
-- name: GetOrgByID :one
SELECT * FROM orgs WHERE id = $1;
-- name: GetOrgBySlug :one
SELECT * FROM orgs WHERE slug = $1;
-- name: UpdateOrgName :one
UPDATE orgs SET name = $2 WHERE id = $1 RETURNING *;
-- name: ListOrgs :many
SELECT * FROM orgs ORDER BY id DESC LIMIT $1 OFFSET $2;
@@ -0,0 +1,122 @@
-- name: CreatePin :one
INSERT INTO pins (request_id, org_id, cid, name, meta, origins, status)
VALUES ($1, $2, $3, $4, $5, $6, 'queued')
RETURNING *;
-- name: GetPin :one
SELECT * FROM pins WHERE request_id = $1 AND org_id = $2;
-- name: GetExistingLivePinByCID :one
SELECT * FROM pins
WHERE org_id = $1 AND cid = $2 AND status <> 'failed'
LIMIT 1;
-- name: UpdatePinStatus :exec
UPDATE pins SET status = $2, failure_reason = $3 WHERE request_id = $1;
-- name: DeletePin :exec
DELETE FROM pins WHERE request_id = $1 AND org_id = $2;
-- name: ListPins :many
SELECT * FROM pins
WHERE org_id = $1
ORDER BY created DESC
LIMIT $2 OFFSET $3;
-- FilterPins honors the full IPFS Pinning API spec filter surface.
--
-- All filters are optional; empty arrays / NULL values short-circuit to
-- "no restriction" via the IS NULL / array-length guards. Name matching
-- supports four modes through a single `match` discriminator:
--
-- 'exact' — LIKE (case-sensitive, no wildcards)
-- 'iexact' — ILIKE anchored both ends
-- 'partial' — LIKE %name%
-- 'ipartial' — ILIKE %name% (uses pg_trgm GIN)
--
-- `meta` is treated as a jsonb "contains" check — the pin's meta must
-- be a superset of the requested map.
--
-- name: FilterPins :many
SELECT *
FROM pins
WHERE org_id = $1
AND (COALESCE(array_length(sqlc.arg(cids)::text[], 1), 0) = 0
OR cid = ANY(sqlc.arg(cids)::text[]))
AND (COALESCE(array_length(sqlc.arg(statuses)::text[], 1), 0) = 0
OR status = ANY(sqlc.arg(statuses)::text[]))
AND (sqlc.narg(name)::text IS NULL
OR (sqlc.arg(match_mode)::text = 'exact' AND name = sqlc.narg(name)::text)
OR (sqlc.arg(match_mode)::text = 'iexact' AND lower(name) = lower(sqlc.narg(name)::text))
OR (sqlc.arg(match_mode)::text = 'partial' AND name LIKE '%' || sqlc.narg(name)::text || '%')
OR (sqlc.arg(match_mode)::text = 'ipartial' AND name ILIKE '%' || sqlc.narg(name)::text || '%'))
AND (sqlc.narg(before)::timestamptz IS NULL OR created < sqlc.narg(before)::timestamptz)
AND (sqlc.narg(after)::timestamptz IS NULL OR created >= sqlc.narg(after)::timestamptz)
AND (sqlc.arg(meta_filter)::jsonb = '{}'::jsonb
OR meta @> sqlc.arg(meta_filter)::jsonb)
ORDER BY created DESC
LIMIT sqlc.arg(pin_limit)
OFFSET sqlc.arg(pin_offset);
-- ReplacePin swaps a pin's CID atomically. Used by POST /v1/pins/{rid}
-- (pin replace per spec). Placements + refcount are left to the caller
-- to rearrange in the same transaction.
--
-- name: ReplacePin :one
UPDATE pins
SET cid = $3,
name = $4,
meta = $5,
origins = $6,
status = 'queued',
failure_reason = NULL
WHERE request_id = $1 AND org_id = $2
RETURNING *;
-- name: InsertPlacement :one
INSERT INTO pin_placements (request_id, node_id, status, fence)
VALUES ($1, $2, 'queued', $3)
RETURNING *;
-- name: GetPlacement :one
SELECT * FROM pin_placements WHERE request_id = $1 AND node_id = $2;
-- name: ListPlacementsForPin :many
SELECT pp.*, n.multiaddrs
FROM pin_placements pp JOIN nodes n ON n.id = pp.node_id
WHERE pp.request_id = $1;
-- name: ListPlacementsForNode :many
SELECT * FROM pin_placements
WHERE node_id = $1 AND status = $2
ORDER BY created_at;
-- name: UpdatePlacementStatusFenced :execrows
UPDATE pin_placements
SET status = $3, failure_reason = $4, attempts = attempts + 1
WHERE request_id = $1 AND node_id = $2 AND fence = $5;
-- name: ReplacePlacementFence :one
UPDATE pin_placements
SET node_id = $3, fence = fence + 1, status = 'queued', failure_reason = NULL
WHERE request_id = $1 AND node_id = $2
RETURNING *;
-- name: StuckPlacements :many
SELECT request_id, node_id, fence
FROM pin_placements
WHERE status = 'queued' AND created_at < (now() - make_interval(secs => $1));
-- name: IncRefcount :exec
INSERT INTO pin_refcount (node_id, cid, count)
VALUES ($1, $2, 1)
ON CONFLICT (node_id, cid) DO UPDATE SET count = pin_refcount.count + 1;
-- name: DecRefcount :one
UPDATE pin_refcount
SET count = count - 1
WHERE node_id = $1 AND cid = $2
RETURNING count;
-- name: DeleteRefcount :exec
DELETE FROM pin_refcount WHERE node_id = $1 AND cid = $2 AND count <= 0;
@@ -0,0 +1,31 @@
-- name: CreateAPIToken :one
INSERT INTO api_tokens (jti, org_id, user_id, label, scopes, expires_at)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING *;
-- name: GetAPITokenByJTI :one
SELECT * FROM api_tokens WHERE jti = $1;
-- name: ListAPITokensForUser :many
SELECT * FROM api_tokens
WHERE org_id = $1 AND user_id = $2 AND revoked_at IS NULL
ORDER BY created_at DESC;
-- name: RevokeAPIToken :exec
UPDATE api_tokens SET revoked_at = now() WHERE jti = $1;
-- name: TouchAPITokenLastUsed :exec
UPDATE api_tokens SET last_used_at = now() WHERE jti = $1;
-- name: AddTokenDenylist :exec
INSERT INTO token_denylist (jti, expires_at, reason)
VALUES ($1, $2, $3)
ON CONFLICT (jti) DO NOTHING;
-- name: IsTokenDenied :one
SELECT EXISTS(
SELECT 1 FROM token_denylist WHERE jti = $1 AND expires_at > now()
);
-- name: PruneTokenDenylist :exec
DELETE FROM token_denylist WHERE expires_at <= now();
@@ -0,0 +1,30 @@
-- name: UpsertUserByAuthentikSub :one
INSERT INTO users (id, authentik_sub, email, display_name, is_sysadmin)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (authentik_sub) DO UPDATE
SET email = EXCLUDED.email,
display_name = EXCLUDED.display_name
RETURNING *;
-- name: GetUserByID :one
SELECT * FROM users WHERE id = $1;
-- name: GetUserByEmail :one
SELECT * FROM users WHERE email = $1;
-- name: PromoteSysadmin :exec
UPDATE users SET is_sysadmin = true WHERE id = $1;
-- name: ListMemberships :many
SELECT m.*, o.slug, o.name
FROM memberships m JOIN orgs o ON o.id = m.org_id
WHERE m.user_id = $1
ORDER BY m.org_id;
-- name: AddMembership :exec
INSERT INTO memberships (org_id, user_id, role)
VALUES ($1, $2, $3)
ON CONFLICT (org_id, user_id) DO UPDATE SET role = EXCLUDED.role;
-- name: RemoveMembership :exec
DELETE FROM memberships WHERE org_id = $1 AND user_id = $2;
@@ -0,0 +1,83 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
// source: audit.sql
package sqlc
import (
"context"
"anchorage/internal/pkg/ids"
)
const insertAudit = `-- name: InsertAudit :exec
INSERT INTO audit_log (org_id, actor_user_id, actor_token_jti, action, target, result, detail)
VALUES ($1, $2, $3, $4, $5, $6, $7)
`
type InsertAuditParams struct {
OrgID ids.OrgID
ActorUserID ids.UserID
ActorTokenJti *string
Action string
Target string
Result string
Detail []byte
}
func (q *Queries) InsertAudit(ctx context.Context, arg InsertAuditParams) error {
_, err := q.db.Exec(ctx, insertAudit,
arg.OrgID,
arg.ActorUserID,
arg.ActorTokenJti,
arg.Action,
arg.Target,
arg.Result,
arg.Detail,
)
return err
}
const listAudit = `-- name: ListAudit :many
SELECT id, org_id, actor_user_id, actor_token_jti, action, target, result, detail, created FROM audit_log
WHERE org_id = $1
ORDER BY created DESC
LIMIT $2 OFFSET $3
`
type ListAuditParams struct {
OrgID ids.OrgID
Limit int32
Offset int32
}
func (q *Queries) ListAudit(ctx context.Context, arg ListAuditParams) ([]AuditLog, error) {
rows, err := q.db.Query(ctx, listAudit, arg.OrgID, arg.Limit, arg.Offset)
if err != nil {
return nil, err
}
defer rows.Close()
var items []AuditLog
for rows.Next() {
var i AuditLog
if err := rows.Scan(
&i.ID,
&i.OrgID,
&i.ActorUserID,
&i.ActorTokenJti,
&i.Action,
&i.Target,
&i.Result,
&i.Detail,
&i.Created,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
+32
View File
@@ -0,0 +1,32 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
package sqlc
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
type DBTX interface {
Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
Query(context.Context, string, ...interface{}) (pgx.Rows, error)
QueryRow(context.Context, string, ...interface{}) pgx.Row
}
func New(db DBTX) *Queries {
return &Queries{db: db}
}
type Queries struct {
db DBTX
}
func (q *Queries) WithTx(tx pgx.Tx) *Queries {
return &Queries{
db: tx,
}
}
+110
View File
@@ -0,0 +1,110 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
package sqlc
import (
"anchorage/internal/pkg/ids"
"github.com/jackc/pgx/v5/pgtype"
)
type ApiToken struct {
Jti ids.TokenID
OrgID ids.OrgID
UserID ids.UserID
Label string
Scopes []string
ExpiresAt pgtype.Timestamptz
RevokedAt pgtype.Timestamptz
LastUsedAt pgtype.Timestamptz
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type AuditLog struct {
ID int64
OrgID ids.OrgID
ActorUserID ids.UserID
ActorTokenJti *string
Action string
Target string
Result string
Detail []byte
Created pgtype.Timestamptz
}
type Membership struct {
OrgID ids.OrgID
UserID ids.UserID
Role string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type Node struct {
ID ids.NodeID
DisplayName string
Multiaddrs []string
RpcUrl string
Status string
LastSeenAt pgtype.Timestamptz
JoinedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type Org struct {
ID ids.OrgID
Slug string
Name string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type Pin struct {
RequestID ids.PinID
OrgID ids.OrgID
Cid string
Name *string
Meta []byte
Origins []string
Status string
FailureReason *string
Created pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type PinPlacement struct {
RequestID ids.PinID
NodeID ids.NodeID
Status string
FailureReason *string
Attempts int32
Fence int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type PinRefcount struct {
NodeID ids.NodeID
Cid string
Count int32
UpdatedAt pgtype.Timestamptz
}
type TokenDenylist struct {
Jti string
ExpiresAt pgtype.Timestamptz
Reason string
CreatedAt pgtype.Timestamptz
}
type User struct {
ID ids.UserID
AuthentikSub *string
Email string
DisplayName string
IsSysadmin bool
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
@@ -0,0 +1,201 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
// source: nodes.sql
package sqlc
import (
"context"
"anchorage/internal/pkg/ids"
)
const drainNode = `-- name: DrainNode :exec
UPDATE nodes SET status = 'drained' WHERE id = $1
`
func (q *Queries) DrainNode(ctx context.Context, id ids.NodeID) error {
_, err := q.db.Exec(ctx, drainNode, id)
return err
}
const getNode = `-- name: GetNode :one
SELECT id, display_name, multiaddrs, rpc_url, status, last_seen_at, joined_at, updated_at FROM nodes WHERE id = $1
`
func (q *Queries) GetNode(ctx context.Context, id ids.NodeID) (Node, error) {
row := q.db.QueryRow(ctx, getNode, id)
var i Node
err := row.Scan(
&i.ID,
&i.DisplayName,
&i.Multiaddrs,
&i.RpcUrl,
&i.Status,
&i.LastSeenAt,
&i.JoinedAt,
&i.UpdatedAt,
)
return i, err
}
const listAllNodes = `-- name: ListAllNodes :many
SELECT id, display_name, multiaddrs, rpc_url, status, last_seen_at, joined_at, updated_at FROM nodes ORDER BY id
`
func (q *Queries) ListAllNodes(ctx context.Context) ([]Node, error) {
rows, err := q.db.Query(ctx, listAllNodes)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Node
for rows.Next() {
var i Node
if err := rows.Scan(
&i.ID,
&i.DisplayName,
&i.Multiaddrs,
&i.RpcUrl,
&i.Status,
&i.LastSeenAt,
&i.JoinedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listLiveNodes = `-- name: ListLiveNodes :many
SELECT id, display_name, multiaddrs, rpc_url, status, last_seen_at, joined_at, updated_at FROM nodes WHERE status = 'up' ORDER BY id
`
func (q *Queries) ListLiveNodes(ctx context.Context) ([]Node, error) {
rows, err := q.db.Query(ctx, listLiveNodes)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Node
for rows.Next() {
var i Node
if err := rows.Scan(
&i.ID,
&i.DisplayName,
&i.Multiaddrs,
&i.RpcUrl,
&i.Status,
&i.LastSeenAt,
&i.JoinedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const markNodeDown = `-- name: MarkNodeDown :exec
UPDATE nodes SET status = 'down' WHERE id = $1 AND status = 'up'
`
func (q *Queries) MarkNodeDown(ctx context.Context, id ids.NodeID) error {
_, err := q.db.Exec(ctx, markNodeDown, id)
return err
}
const markStaleNodesDown = `-- name: MarkStaleNodesDown :many
UPDATE nodes
SET status = 'down'
WHERE status = 'up' AND last_seen_at < (now() - make_interval(secs => $1))
RETURNING id
`
func (q *Queries) MarkStaleNodesDown(ctx context.Context, secs float64) ([]ids.NodeID, error) {
rows, err := q.db.Query(ctx, markStaleNodesDown, secs)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ids.NodeID
for rows.Next() {
var id ids.NodeID
if err := rows.Scan(&id); err != nil {
return nil, err
}
items = append(items, id)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const touchNodeHeartbeat = `-- name: TouchNodeHeartbeat :exec
UPDATE nodes SET last_seen_at = now() WHERE id = $1
`
func (q *Queries) TouchNodeHeartbeat(ctx context.Context, id ids.NodeID) error {
_, err := q.db.Exec(ctx, touchNodeHeartbeat, id)
return err
}
const uncordonNode = `-- name: UncordonNode :exec
UPDATE nodes SET status = 'up' WHERE id = $1 AND status = 'drained'
`
func (q *Queries) UncordonNode(ctx context.Context, id ids.NodeID) error {
_, err := q.db.Exec(ctx, uncordonNode, id)
return err
}
const upsertNode = `-- name: UpsertNode :one
INSERT INTO nodes (id, display_name, multiaddrs, rpc_url, status)
VALUES ($1, $2, $3, $4, 'up')
ON CONFLICT (id) DO UPDATE
SET display_name = EXCLUDED.display_name,
multiaddrs = EXCLUDED.multiaddrs,
rpc_url = EXCLUDED.rpc_url,
status = CASE WHEN nodes.status = 'drained' THEN 'drained' ELSE 'up' END,
last_seen_at = now()
RETURNING id, display_name, multiaddrs, rpc_url, status, last_seen_at, joined_at, updated_at
`
type UpsertNodeParams struct {
ID ids.NodeID
DisplayName string
Multiaddrs []string
RpcUrl string
}
func (q *Queries) UpsertNode(ctx context.Context, arg UpsertNodeParams) (Node, error) {
row := q.db.QueryRow(ctx, upsertNode,
arg.ID,
arg.DisplayName,
arg.Multiaddrs,
arg.RpcUrl,
)
var i Node
err := row.Scan(
&i.ID,
&i.DisplayName,
&i.Multiaddrs,
&i.RpcUrl,
&i.Status,
&i.LastSeenAt,
&i.JoinedAt,
&i.UpdatedAt,
)
return i, err
}
@@ -0,0 +1,128 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
// source: orgs.sql
package sqlc
import (
"context"
"anchorage/internal/pkg/ids"
)
const createOrg = `-- name: CreateOrg :one
INSERT INTO orgs (id, slug, name)
VALUES ($1, $2, $3)
RETURNING id, slug, name, created_at, updated_at
`
type CreateOrgParams struct {
ID ids.OrgID
Slug string
Name string
}
func (q *Queries) CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error) {
row := q.db.QueryRow(ctx, createOrg, arg.ID, arg.Slug, arg.Name)
var i Org
err := row.Scan(
&i.ID,
&i.Slug,
&i.Name,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const getOrgByID = `-- name: GetOrgByID :one
SELECT id, slug, name, created_at, updated_at FROM orgs WHERE id = $1
`
func (q *Queries) GetOrgByID(ctx context.Context, id ids.OrgID) (Org, error) {
row := q.db.QueryRow(ctx, getOrgByID, id)
var i Org
err := row.Scan(
&i.ID,
&i.Slug,
&i.Name,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const getOrgBySlug = `-- name: GetOrgBySlug :one
SELECT id, slug, name, created_at, updated_at FROM orgs WHERE slug = $1
`
func (q *Queries) GetOrgBySlug(ctx context.Context, slug string) (Org, error) {
row := q.db.QueryRow(ctx, getOrgBySlug, slug)
var i Org
err := row.Scan(
&i.ID,
&i.Slug,
&i.Name,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const listOrgs = `-- name: ListOrgs :many
SELECT id, slug, name, created_at, updated_at FROM orgs ORDER BY id DESC LIMIT $1 OFFSET $2
`
type ListOrgsParams struct {
Limit int32
Offset int32
}
func (q *Queries) ListOrgs(ctx context.Context, arg ListOrgsParams) ([]Org, error) {
rows, err := q.db.Query(ctx, listOrgs, arg.Limit, arg.Offset)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Org
for rows.Next() {
var i Org
if err := rows.Scan(
&i.ID,
&i.Slug,
&i.Name,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const updateOrgName = `-- name: UpdateOrgName :one
UPDATE orgs SET name = $2 WHERE id = $1 RETURNING id, slug, name, created_at, updated_at
`
type UpdateOrgNameParams struct {
ID ids.OrgID
Name string
}
func (q *Queries) UpdateOrgName(ctx context.Context, arg UpdateOrgNameParams) (Org, error) {
row := q.db.QueryRow(ctx, updateOrgName, arg.ID, arg.Name)
var i Org
err := row.Scan(
&i.ID,
&i.Slug,
&i.Name,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
@@ -0,0 +1,600 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
// source: pins.sql
package sqlc
import (
"context"
"anchorage/internal/pkg/ids"
"github.com/jackc/pgx/v5/pgtype"
)
const createPin = `-- name: CreatePin :one
INSERT INTO pins (request_id, org_id, cid, name, meta, origins, status)
VALUES ($1, $2, $3, $4, $5, $6, 'queued')
RETURNING request_id, org_id, cid, name, meta, origins, status, failure_reason, created, updated_at
`
type CreatePinParams struct {
RequestID ids.PinID
OrgID ids.OrgID
Cid string
Name *string
Meta []byte
Origins []string
}
func (q *Queries) CreatePin(ctx context.Context, arg CreatePinParams) (Pin, error) {
row := q.db.QueryRow(ctx, createPin,
arg.RequestID,
arg.OrgID,
arg.Cid,
arg.Name,
arg.Meta,
arg.Origins,
)
var i Pin
err := row.Scan(
&i.RequestID,
&i.OrgID,
&i.Cid,
&i.Name,
&i.Meta,
&i.Origins,
&i.Status,
&i.FailureReason,
&i.Created,
&i.UpdatedAt,
)
return i, err
}
const decRefcount = `-- name: DecRefcount :one
UPDATE pin_refcount
SET count = count - 1
WHERE node_id = $1 AND cid = $2
RETURNING count
`
type DecRefcountParams struct {
NodeID ids.NodeID
Cid string
}
func (q *Queries) DecRefcount(ctx context.Context, arg DecRefcountParams) (int32, error) {
row := q.db.QueryRow(ctx, decRefcount, arg.NodeID, arg.Cid)
var count int32
err := row.Scan(&count)
return count, err
}
const deletePin = `-- name: DeletePin :exec
DELETE FROM pins WHERE request_id = $1 AND org_id = $2
`
type DeletePinParams struct {
RequestID ids.PinID
OrgID ids.OrgID
}
func (q *Queries) DeletePin(ctx context.Context, arg DeletePinParams) error {
_, err := q.db.Exec(ctx, deletePin, arg.RequestID, arg.OrgID)
return err
}
const deleteRefcount = `-- name: DeleteRefcount :exec
DELETE FROM pin_refcount WHERE node_id = $1 AND cid = $2 AND count <= 0
`
type DeleteRefcountParams struct {
NodeID ids.NodeID
Cid string
}
func (q *Queries) DeleteRefcount(ctx context.Context, arg DeleteRefcountParams) error {
_, err := q.db.Exec(ctx, deleteRefcount, arg.NodeID, arg.Cid)
return err
}
const filterPins = `-- name: FilterPins :many
SELECT request_id, org_id, cid, name, meta, origins, status, failure_reason, created, updated_at
FROM pins
WHERE org_id = $1
AND (COALESCE(array_length($2::text[], 1), 0) = 0
OR cid = ANY($2::text[]))
AND (COALESCE(array_length($3::text[], 1), 0) = 0
OR status = ANY($3::text[]))
AND ($4::text IS NULL
OR ($5::text = 'exact' AND name = $4::text)
OR ($5::text = 'iexact' AND lower(name) = lower($4::text))
OR ($5::text = 'partial' AND name LIKE '%' || $4::text || '%')
OR ($5::text = 'ipartial' AND name ILIKE '%' || $4::text || '%'))
AND ($6::timestamptz IS NULL OR created < $6::timestamptz)
AND ($7::timestamptz IS NULL OR created >= $7::timestamptz)
AND ($8::jsonb = '{}'::jsonb
OR meta @> $8::jsonb)
ORDER BY created DESC
LIMIT $10
OFFSET $9
`
type FilterPinsParams struct {
OrgID ids.OrgID
Cids []string
Statuses []string
Name *string
MatchMode string
Before pgtype.Timestamptz
After pgtype.Timestamptz
MetaFilter []byte
PinOffset int32
PinLimit int32
}
// FilterPins honors the full IPFS Pinning API spec filter surface.
//
// All filters are optional; empty arrays / NULL values short-circuit to
// "no restriction" via the IS NULL / array-length guards. Name matching
// supports four modes through a single `match` discriminator:
//
// 'exact' — LIKE (case-sensitive, no wildcards)
// 'iexact' — ILIKE anchored both ends
// 'partial' — LIKE %name%
// 'ipartial' — ILIKE %name% (uses pg_trgm GIN)
//
// `meta` is treated as a jsonb "contains" check — the pin's meta must
// be a superset of the requested map.
func (q *Queries) FilterPins(ctx context.Context, arg FilterPinsParams) ([]Pin, error) {
rows, err := q.db.Query(ctx, filterPins,
arg.OrgID,
arg.Cids,
arg.Statuses,
arg.Name,
arg.MatchMode,
arg.Before,
arg.After,
arg.MetaFilter,
arg.PinOffset,
arg.PinLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Pin
for rows.Next() {
var i Pin
if err := rows.Scan(
&i.RequestID,
&i.OrgID,
&i.Cid,
&i.Name,
&i.Meta,
&i.Origins,
&i.Status,
&i.FailureReason,
&i.Created,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const getExistingLivePinByCID = `-- name: GetExistingLivePinByCID :one
SELECT request_id, org_id, cid, name, meta, origins, status, failure_reason, created, updated_at FROM pins
WHERE org_id = $1 AND cid = $2 AND status <> 'failed'
LIMIT 1
`
type GetExistingLivePinByCIDParams struct {
OrgID ids.OrgID
Cid string
}
func (q *Queries) GetExistingLivePinByCID(ctx context.Context, arg GetExistingLivePinByCIDParams) (Pin, error) {
row := q.db.QueryRow(ctx, getExistingLivePinByCID, arg.OrgID, arg.Cid)
var i Pin
err := row.Scan(
&i.RequestID,
&i.OrgID,
&i.Cid,
&i.Name,
&i.Meta,
&i.Origins,
&i.Status,
&i.FailureReason,
&i.Created,
&i.UpdatedAt,
)
return i, err
}
const getPin = `-- name: GetPin :one
SELECT request_id, org_id, cid, name, meta, origins, status, failure_reason, created, updated_at FROM pins WHERE request_id = $1 AND org_id = $2
`
type GetPinParams struct {
RequestID ids.PinID
OrgID ids.OrgID
}
func (q *Queries) GetPin(ctx context.Context, arg GetPinParams) (Pin, error) {
row := q.db.QueryRow(ctx, getPin, arg.RequestID, arg.OrgID)
var i Pin
err := row.Scan(
&i.RequestID,
&i.OrgID,
&i.Cid,
&i.Name,
&i.Meta,
&i.Origins,
&i.Status,
&i.FailureReason,
&i.Created,
&i.UpdatedAt,
)
return i, err
}
const getPlacement = `-- name: GetPlacement :one
SELECT request_id, node_id, status, failure_reason, attempts, fence, created_at, updated_at FROM pin_placements WHERE request_id = $1 AND node_id = $2
`
type GetPlacementParams struct {
RequestID ids.PinID
NodeID ids.NodeID
}
func (q *Queries) GetPlacement(ctx context.Context, arg GetPlacementParams) (PinPlacement, error) {
row := q.db.QueryRow(ctx, getPlacement, arg.RequestID, arg.NodeID)
var i PinPlacement
err := row.Scan(
&i.RequestID,
&i.NodeID,
&i.Status,
&i.FailureReason,
&i.Attempts,
&i.Fence,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const incRefcount = `-- name: IncRefcount :exec
INSERT INTO pin_refcount (node_id, cid, count)
VALUES ($1, $2, 1)
ON CONFLICT (node_id, cid) DO UPDATE SET count = pin_refcount.count + 1
`
type IncRefcountParams struct {
NodeID ids.NodeID
Cid string
}
func (q *Queries) IncRefcount(ctx context.Context, arg IncRefcountParams) error {
_, err := q.db.Exec(ctx, incRefcount, arg.NodeID, arg.Cid)
return err
}
const insertPlacement = `-- name: InsertPlacement :one
INSERT INTO pin_placements (request_id, node_id, status, fence)
VALUES ($1, $2, 'queued', $3)
RETURNING request_id, node_id, status, failure_reason, attempts, fence, created_at, updated_at
`
type InsertPlacementParams struct {
RequestID ids.PinID
NodeID ids.NodeID
Fence int64
}
func (q *Queries) InsertPlacement(ctx context.Context, arg InsertPlacementParams) (PinPlacement, error) {
row := q.db.QueryRow(ctx, insertPlacement, arg.RequestID, arg.NodeID, arg.Fence)
var i PinPlacement
err := row.Scan(
&i.RequestID,
&i.NodeID,
&i.Status,
&i.FailureReason,
&i.Attempts,
&i.Fence,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const listPins = `-- name: ListPins :many
SELECT request_id, org_id, cid, name, meta, origins, status, failure_reason, created, updated_at FROM pins
WHERE org_id = $1
ORDER BY created DESC
LIMIT $2 OFFSET $3
`
type ListPinsParams struct {
OrgID ids.OrgID
Limit int32
Offset int32
}
func (q *Queries) ListPins(ctx context.Context, arg ListPinsParams) ([]Pin, error) {
rows, err := q.db.Query(ctx, listPins, arg.OrgID, arg.Limit, arg.Offset)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Pin
for rows.Next() {
var i Pin
if err := rows.Scan(
&i.RequestID,
&i.OrgID,
&i.Cid,
&i.Name,
&i.Meta,
&i.Origins,
&i.Status,
&i.FailureReason,
&i.Created,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listPlacementsForNode = `-- name: ListPlacementsForNode :many
SELECT request_id, node_id, status, failure_reason, attempts, fence, created_at, updated_at FROM pin_placements
WHERE node_id = $1 AND status = $2
ORDER BY created_at
`
type ListPlacementsForNodeParams struct {
NodeID ids.NodeID
Status string
}
func (q *Queries) ListPlacementsForNode(ctx context.Context, arg ListPlacementsForNodeParams) ([]PinPlacement, error) {
rows, err := q.db.Query(ctx, listPlacementsForNode, arg.NodeID, arg.Status)
if err != nil {
return nil, err
}
defer rows.Close()
var items []PinPlacement
for rows.Next() {
var i PinPlacement
if err := rows.Scan(
&i.RequestID,
&i.NodeID,
&i.Status,
&i.FailureReason,
&i.Attempts,
&i.Fence,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listPlacementsForPin = `-- name: ListPlacementsForPin :many
SELECT pp.request_id, pp.node_id, pp.status, pp.failure_reason, pp.attempts, pp.fence, pp.created_at, pp.updated_at, n.multiaddrs
FROM pin_placements pp JOIN nodes n ON n.id = pp.node_id
WHERE pp.request_id = $1
`
type ListPlacementsForPinRow struct {
RequestID ids.PinID
NodeID ids.NodeID
Status string
FailureReason *string
Attempts int32
Fence int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
Multiaddrs []string
}
func (q *Queries) ListPlacementsForPin(ctx context.Context, requestID ids.PinID) ([]ListPlacementsForPinRow, error) {
rows, err := q.db.Query(ctx, listPlacementsForPin, requestID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListPlacementsForPinRow
for rows.Next() {
var i ListPlacementsForPinRow
if err := rows.Scan(
&i.RequestID,
&i.NodeID,
&i.Status,
&i.FailureReason,
&i.Attempts,
&i.Fence,
&i.CreatedAt,
&i.UpdatedAt,
&i.Multiaddrs,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const replacePin = `-- name: ReplacePin :one
UPDATE pins
SET cid = $3,
name = $4,
meta = $5,
origins = $6,
status = 'queued',
failure_reason = NULL
WHERE request_id = $1 AND org_id = $2
RETURNING request_id, org_id, cid, name, meta, origins, status, failure_reason, created, updated_at
`
type ReplacePinParams struct {
RequestID ids.PinID
OrgID ids.OrgID
Cid string
Name *string
Meta []byte
Origins []string
}
// ReplacePin swaps a pin's CID atomically. Used by POST /v1/pins/{rid}
// (pin replace per spec). Placements + refcount are left to the caller
// to rearrange in the same transaction.
func (q *Queries) ReplacePin(ctx context.Context, arg ReplacePinParams) (Pin, error) {
row := q.db.QueryRow(ctx, replacePin,
arg.RequestID,
arg.OrgID,
arg.Cid,
arg.Name,
arg.Meta,
arg.Origins,
)
var i Pin
err := row.Scan(
&i.RequestID,
&i.OrgID,
&i.Cid,
&i.Name,
&i.Meta,
&i.Origins,
&i.Status,
&i.FailureReason,
&i.Created,
&i.UpdatedAt,
)
return i, err
}
const replacePlacementFence = `-- name: ReplacePlacementFence :one
UPDATE pin_placements
SET node_id = $3, fence = fence + 1, status = 'queued', failure_reason = NULL
WHERE request_id = $1 AND node_id = $2
RETURNING request_id, node_id, status, failure_reason, attempts, fence, created_at, updated_at
`
type ReplacePlacementFenceParams struct {
RequestID ids.PinID
NodeID ids.NodeID
NodeID_2 ids.NodeID
}
func (q *Queries) ReplacePlacementFence(ctx context.Context, arg ReplacePlacementFenceParams) (PinPlacement, error) {
row := q.db.QueryRow(ctx, replacePlacementFence, arg.RequestID, arg.NodeID, arg.NodeID_2)
var i PinPlacement
err := row.Scan(
&i.RequestID,
&i.NodeID,
&i.Status,
&i.FailureReason,
&i.Attempts,
&i.Fence,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const stuckPlacements = `-- name: StuckPlacements :many
SELECT request_id, node_id, fence
FROM pin_placements
WHERE status = 'queued' AND created_at < (now() - make_interval(secs => $1))
`
type StuckPlacementsRow struct {
RequestID ids.PinID
NodeID ids.NodeID
Fence int64
}
func (q *Queries) StuckPlacements(ctx context.Context, secs float64) ([]StuckPlacementsRow, error) {
rows, err := q.db.Query(ctx, stuckPlacements, secs)
if err != nil {
return nil, err
}
defer rows.Close()
var items []StuckPlacementsRow
for rows.Next() {
var i StuckPlacementsRow
if err := rows.Scan(&i.RequestID, &i.NodeID, &i.Fence); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const updatePinStatus = `-- name: UpdatePinStatus :exec
UPDATE pins SET status = $2, failure_reason = $3 WHERE request_id = $1
`
type UpdatePinStatusParams struct {
RequestID ids.PinID
Status string
FailureReason *string
}
func (q *Queries) UpdatePinStatus(ctx context.Context, arg UpdatePinStatusParams) error {
_, err := q.db.Exec(ctx, updatePinStatus, arg.RequestID, arg.Status, arg.FailureReason)
return err
}
const updatePlacementStatusFenced = `-- name: UpdatePlacementStatusFenced :execrows
UPDATE pin_placements
SET status = $3, failure_reason = $4, attempts = attempts + 1
WHERE request_id = $1 AND node_id = $2 AND fence = $5
`
type UpdatePlacementStatusFencedParams struct {
RequestID ids.PinID
NodeID ids.NodeID
Status string
FailureReason *string
Fence int64
}
func (q *Queries) UpdatePlacementStatusFenced(ctx context.Context, arg UpdatePlacementStatusFencedParams) (int64, error) {
result, err := q.db.Exec(ctx, updatePlacementStatusFenced,
arg.RequestID,
arg.NodeID,
arg.Status,
arg.FailureReason,
arg.Fence,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
@@ -0,0 +1,83 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
package sqlc
import (
"context"
"anchorage/internal/pkg/ids"
)
type Querier interface {
AddMembership(ctx context.Context, arg AddMembershipParams) error
AddTokenDenylist(ctx context.Context, arg AddTokenDenylistParams) error
CreateAPIToken(ctx context.Context, arg CreateAPITokenParams) (ApiToken, error)
CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error)
CreatePin(ctx context.Context, arg CreatePinParams) (Pin, error)
DecRefcount(ctx context.Context, arg DecRefcountParams) (int32, error)
DeletePin(ctx context.Context, arg DeletePinParams) error
DeleteRefcount(ctx context.Context, arg DeleteRefcountParams) error
DrainNode(ctx context.Context, id ids.NodeID) error
// FilterPins honors the full IPFS Pinning API spec filter surface.
//
// All filters are optional; empty arrays / NULL values short-circuit to
// "no restriction" via the IS NULL / array-length guards. Name matching
// supports four modes through a single `match` discriminator:
//
// 'exact' — LIKE (case-sensitive, no wildcards)
// 'iexact' — ILIKE anchored both ends
// 'partial' — LIKE %name%
// 'ipartial' — ILIKE %name% (uses pg_trgm GIN)
//
// `meta` is treated as a jsonb "contains" check — the pin's meta must
// be a superset of the requested map.
//
FilterPins(ctx context.Context, arg FilterPinsParams) ([]Pin, error)
GetAPITokenByJTI(ctx context.Context, jti ids.TokenID) (ApiToken, error)
GetExistingLivePinByCID(ctx context.Context, arg GetExistingLivePinByCIDParams) (Pin, error)
GetNode(ctx context.Context, id ids.NodeID) (Node, error)
GetOrgByID(ctx context.Context, id ids.OrgID) (Org, error)
GetOrgBySlug(ctx context.Context, slug string) (Org, error)
GetPin(ctx context.Context, arg GetPinParams) (Pin, error)
GetPlacement(ctx context.Context, arg GetPlacementParams) (PinPlacement, error)
GetUserByEmail(ctx context.Context, email string) (User, error)
GetUserByID(ctx context.Context, id ids.UserID) (User, error)
IncRefcount(ctx context.Context, arg IncRefcountParams) error
InsertAudit(ctx context.Context, arg InsertAuditParams) error
InsertPlacement(ctx context.Context, arg InsertPlacementParams) (PinPlacement, error)
IsTokenDenied(ctx context.Context, jti string) (bool, error)
ListAPITokensForUser(ctx context.Context, arg ListAPITokensForUserParams) ([]ApiToken, error)
ListAllNodes(ctx context.Context) ([]Node, error)
ListAudit(ctx context.Context, arg ListAuditParams) ([]AuditLog, error)
ListLiveNodes(ctx context.Context) ([]Node, error)
ListMemberships(ctx context.Context, userID ids.UserID) ([]ListMembershipsRow, error)
ListOrgs(ctx context.Context, arg ListOrgsParams) ([]Org, error)
ListPins(ctx context.Context, arg ListPinsParams) ([]Pin, error)
ListPlacementsForNode(ctx context.Context, arg ListPlacementsForNodeParams) ([]PinPlacement, error)
ListPlacementsForPin(ctx context.Context, requestID ids.PinID) ([]ListPlacementsForPinRow, error)
MarkNodeDown(ctx context.Context, id ids.NodeID) error
MarkStaleNodesDown(ctx context.Context, secs float64) ([]ids.NodeID, error)
PromoteSysadmin(ctx context.Context, id ids.UserID) error
PruneTokenDenylist(ctx context.Context) error
RemoveMembership(ctx context.Context, arg RemoveMembershipParams) error
// ReplacePin swaps a pin's CID atomically. Used by POST /v1/pins/{rid}
// (pin replace per spec). Placements + refcount are left to the caller
// to rearrange in the same transaction.
//
ReplacePin(ctx context.Context, arg ReplacePinParams) (Pin, error)
ReplacePlacementFence(ctx context.Context, arg ReplacePlacementFenceParams) (PinPlacement, error)
RevokeAPIToken(ctx context.Context, jti ids.TokenID) error
StuckPlacements(ctx context.Context, secs float64) ([]StuckPlacementsRow, error)
TouchAPITokenLastUsed(ctx context.Context, jti ids.TokenID) error
TouchNodeHeartbeat(ctx context.Context, id ids.NodeID) error
UncordonNode(ctx context.Context, id ids.NodeID) error
UpdateOrgName(ctx context.Context, arg UpdateOrgNameParams) (Org, error)
UpdatePinStatus(ctx context.Context, arg UpdatePinStatusParams) error
UpdatePlacementStatusFenced(ctx context.Context, arg UpdatePlacementStatusFencedParams) (int64, error)
UpsertNode(ctx context.Context, arg UpsertNodeParams) (Node, error)
UpsertUserByAuthentikSub(ctx context.Context, arg UpsertUserByAuthentikSubParams) (User, error)
}
var _ Querier = (*Queries)(nil)
@@ -0,0 +1,174 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
// source: tokens.sql
package sqlc
import (
"context"
"anchorage/internal/pkg/ids"
"github.com/jackc/pgx/v5/pgtype"
)
const addTokenDenylist = `-- name: AddTokenDenylist :exec
INSERT INTO token_denylist (jti, expires_at, reason)
VALUES ($1, $2, $3)
ON CONFLICT (jti) DO NOTHING
`
type AddTokenDenylistParams struct {
Jti string
ExpiresAt pgtype.Timestamptz
Reason string
}
func (q *Queries) AddTokenDenylist(ctx context.Context, arg AddTokenDenylistParams) error {
_, err := q.db.Exec(ctx, addTokenDenylist, arg.Jti, arg.ExpiresAt, arg.Reason)
return err
}
const createAPIToken = `-- name: CreateAPIToken :one
INSERT INTO api_tokens (jti, org_id, user_id, label, scopes, expires_at)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING jti, org_id, user_id, label, scopes, expires_at, revoked_at, last_used_at, created_at, updated_at
`
type CreateAPITokenParams struct {
Jti ids.TokenID
OrgID ids.OrgID
UserID ids.UserID
Label string
Scopes []string
ExpiresAt pgtype.Timestamptz
}
func (q *Queries) CreateAPIToken(ctx context.Context, arg CreateAPITokenParams) (ApiToken, error) {
row := q.db.QueryRow(ctx, createAPIToken,
arg.Jti,
arg.OrgID,
arg.UserID,
arg.Label,
arg.Scopes,
arg.ExpiresAt,
)
var i ApiToken
err := row.Scan(
&i.Jti,
&i.OrgID,
&i.UserID,
&i.Label,
&i.Scopes,
&i.ExpiresAt,
&i.RevokedAt,
&i.LastUsedAt,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const getAPITokenByJTI = `-- name: GetAPITokenByJTI :one
SELECT jti, org_id, user_id, label, scopes, expires_at, revoked_at, last_used_at, created_at, updated_at FROM api_tokens WHERE jti = $1
`
func (q *Queries) GetAPITokenByJTI(ctx context.Context, jti ids.TokenID) (ApiToken, error) {
row := q.db.QueryRow(ctx, getAPITokenByJTI, jti)
var i ApiToken
err := row.Scan(
&i.Jti,
&i.OrgID,
&i.UserID,
&i.Label,
&i.Scopes,
&i.ExpiresAt,
&i.RevokedAt,
&i.LastUsedAt,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const isTokenDenied = `-- name: IsTokenDenied :one
SELECT EXISTS(
SELECT 1 FROM token_denylist WHERE jti = $1 AND expires_at > now()
)
`
func (q *Queries) IsTokenDenied(ctx context.Context, jti string) (bool, error) {
row := q.db.QueryRow(ctx, isTokenDenied, jti)
var exists bool
err := row.Scan(&exists)
return exists, err
}
const listAPITokensForUser = `-- name: ListAPITokensForUser :many
SELECT jti, org_id, user_id, label, scopes, expires_at, revoked_at, last_used_at, created_at, updated_at FROM api_tokens
WHERE org_id = $1 AND user_id = $2 AND revoked_at IS NULL
ORDER BY created_at DESC
`
type ListAPITokensForUserParams struct {
OrgID ids.OrgID
UserID ids.UserID
}
func (q *Queries) ListAPITokensForUser(ctx context.Context, arg ListAPITokensForUserParams) ([]ApiToken, error) {
rows, err := q.db.Query(ctx, listAPITokensForUser, arg.OrgID, arg.UserID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ApiToken
for rows.Next() {
var i ApiToken
if err := rows.Scan(
&i.Jti,
&i.OrgID,
&i.UserID,
&i.Label,
&i.Scopes,
&i.ExpiresAt,
&i.RevokedAt,
&i.LastUsedAt,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const pruneTokenDenylist = `-- name: PruneTokenDenylist :exec
DELETE FROM token_denylist WHERE expires_at <= now()
`
func (q *Queries) PruneTokenDenylist(ctx context.Context) error {
_, err := q.db.Exec(ctx, pruneTokenDenylist)
return err
}
const revokeAPIToken = `-- name: RevokeAPIToken :exec
UPDATE api_tokens SET revoked_at = now() WHERE jti = $1
`
func (q *Queries) RevokeAPIToken(ctx context.Context, jti ids.TokenID) error {
_, err := q.db.Exec(ctx, revokeAPIToken, jti)
return err
}
const touchAPITokenLastUsed = `-- name: TouchAPITokenLastUsed :exec
UPDATE api_tokens SET last_used_at = now() WHERE jti = $1
`
func (q *Queries) TouchAPITokenLastUsed(ctx context.Context, jti ids.TokenID) error {
_, err := q.db.Exec(ctx, touchAPITokenLastUsed, jti)
return err
}
@@ -0,0 +1,174 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
// source: users.sql
package sqlc
import (
"context"
"anchorage/internal/pkg/ids"
"github.com/jackc/pgx/v5/pgtype"
)
const addMembership = `-- name: AddMembership :exec
INSERT INTO memberships (org_id, user_id, role)
VALUES ($1, $2, $3)
ON CONFLICT (org_id, user_id) DO UPDATE SET role = EXCLUDED.role
`
type AddMembershipParams struct {
OrgID ids.OrgID
UserID ids.UserID
Role string
}
func (q *Queries) AddMembership(ctx context.Context, arg AddMembershipParams) error {
_, err := q.db.Exec(ctx, addMembership, arg.OrgID, arg.UserID, arg.Role)
return err
}
const getUserByEmail = `-- name: GetUserByEmail :one
SELECT id, authentik_sub, email, display_name, is_sysadmin, created_at, updated_at FROM users WHERE email = $1
`
func (q *Queries) GetUserByEmail(ctx context.Context, email string) (User, error) {
row := q.db.QueryRow(ctx, getUserByEmail, email)
var i User
err := row.Scan(
&i.ID,
&i.AuthentikSub,
&i.Email,
&i.DisplayName,
&i.IsSysadmin,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const getUserByID = `-- name: GetUserByID :one
SELECT id, authentik_sub, email, display_name, is_sysadmin, created_at, updated_at FROM users WHERE id = $1
`
func (q *Queries) GetUserByID(ctx context.Context, id ids.UserID) (User, error) {
row := q.db.QueryRow(ctx, getUserByID, id)
var i User
err := row.Scan(
&i.ID,
&i.AuthentikSub,
&i.Email,
&i.DisplayName,
&i.IsSysadmin,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const listMemberships = `-- name: ListMemberships :many
SELECT m.org_id, m.user_id, m.role, m.created_at, m.updated_at, o.slug, o.name
FROM memberships m JOIN orgs o ON o.id = m.org_id
WHERE m.user_id = $1
ORDER BY m.org_id
`
type ListMembershipsRow struct {
OrgID ids.OrgID
UserID ids.UserID
Role string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
Slug string
Name string
}
func (q *Queries) ListMemberships(ctx context.Context, userID ids.UserID) ([]ListMembershipsRow, error) {
rows, err := q.db.Query(ctx, listMemberships, userID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListMembershipsRow
for rows.Next() {
var i ListMembershipsRow
if err := rows.Scan(
&i.OrgID,
&i.UserID,
&i.Role,
&i.CreatedAt,
&i.UpdatedAt,
&i.Slug,
&i.Name,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const promoteSysadmin = `-- name: PromoteSysadmin :exec
UPDATE users SET is_sysadmin = true WHERE id = $1
`
func (q *Queries) PromoteSysadmin(ctx context.Context, id ids.UserID) error {
_, err := q.db.Exec(ctx, promoteSysadmin, id)
return err
}
const removeMembership = `-- name: RemoveMembership :exec
DELETE FROM memberships WHERE org_id = $1 AND user_id = $2
`
type RemoveMembershipParams struct {
OrgID ids.OrgID
UserID ids.UserID
}
func (q *Queries) RemoveMembership(ctx context.Context, arg RemoveMembershipParams) error {
_, err := q.db.Exec(ctx, removeMembership, arg.OrgID, arg.UserID)
return err
}
const upsertUserByAuthentikSub = `-- name: UpsertUserByAuthentikSub :one
INSERT INTO users (id, authentik_sub, email, display_name, is_sysadmin)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (authentik_sub) DO UPDATE
SET email = EXCLUDED.email,
display_name = EXCLUDED.display_name
RETURNING id, authentik_sub, email, display_name, is_sysadmin, created_at, updated_at
`
type UpsertUserByAuthentikSubParams struct {
ID ids.UserID
AuthentikSub *string
Email string
DisplayName string
IsSysadmin bool
}
func (q *Queries) UpsertUserByAuthentikSub(ctx context.Context, arg UpsertUserByAuthentikSubParams) (User, error) {
row := q.db.QueryRow(ctx, upsertUserByAuthentikSub,
arg.ID,
arg.AuthentikSub,
arg.Email,
arg.DisplayName,
arg.IsSysadmin,
)
var i User
err := row.Scan(
&i.ID,
&i.AuthentikSub,
&i.Email,
&i.DisplayName,
&i.IsSysadmin,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
+800
View File
@@ -0,0 +1,800 @@
// Package postgres is anchorage's pgx-backed implementation of
// store.Store. Sub-store methods are thin wrappers over sqlc-generated
// query objects in internal/pkg/store/postgres/sqlc; the file you're
// reading is the bridge between anchorage's domain types and the
// sqlc Pgx types (pgtype.Timestamptz → time.Time, etc).
//
// Transactions: Tx opens a pgx tx, sets the `anchorage.org_id` GUC when
// a tenant context is active, and hands the closure a Store wrapping
// the transactional Queries. Commit / rollback follows the standard
// Go "defer rollback-unless-committed" idiom.
package postgres
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"anchorage/internal/pkg/ids"
"anchorage/internal/pkg/store"
"anchorage/internal/pkg/store/postgres/sqlc"
)
// ctxKey namespaces the context values this package stashes (currently
// just the RLS org id).
type ctxKey struct{ name string }
var orgCtxKey = ctxKey{"anchorage-org-id"}
// Store implements store.Store on top of a pgxpool.Pool. A separate
// *Store is constructed per transaction (see Tx); the top-level one
// holds the pool directly.
type Store struct {
pool *pgxpool.Pool
// If non-nil, all sub-stores use this Queries (scoped to a
// transaction). The top-level Store has txQ=nil and lazily wraps
// pool.
txQ *sqlc.Queries
txOrgID *ids.OrgID // set inside Tx so GUC stays consistent
}
// New builds a pool-backed Store.
func New(pool *pgxpool.Pool) *Store {
return &Store{pool: pool}
}
// queries returns a sqlc.Queries over the correct dbtx handle — either
// the transactional one from Tx, or a pool-backed one.
func (s *Store) queries() *sqlc.Queries {
if s.txQ != nil {
return s.txQ
}
return sqlc.New(s.pool)
}
// ---- Root store.Store interface --------------------------------------------
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 membershipStore{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} }
// WithOrgContext returns a context tagged with orgID. The Tx handler
// reads this to SET LOCAL anchorage.org_id inside the transaction.
func (s *Store) WithOrgContext(ctx context.Context, orgID ids.OrgID) (context.Context, error) {
return context.WithValue(ctx, orgCtxKey, orgID), nil
}
// Tx opens a pgx transaction, sets the anchorage.org_id GUC if an org
// has been tagged on ctx via WithOrgContext, and passes fn a Store
// bound to that transaction.
func (s *Store) Tx(ctx context.Context, fn func(txCtx context.Context, tx store.Store) error) error {
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
if err != nil {
return fmt.Errorf("begin tx: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
q := sqlc.New(tx).WithTx(tx)
txStore := &Store{pool: s.pool, txQ: q}
// If the caller wrapped ctx with WithOrgContext, apply the GUC so
// RLS policies on the tenant tables kick in.
if v, ok := ctx.Value(orgCtxKey).(ids.OrgID); ok && !v.IsZero() {
if _, err := tx.Exec(ctx, "SET LOCAL anchorage.org_id = $1", v.String()); err != nil {
return fmt.Errorf("set org guc: %w", err)
}
txStore.txOrgID = &v
}
if err := fn(ctx, txStore); err != nil {
return err
}
return tx.Commit(ctx)
}
// ---- Converters ------------------------------------------------------------
func tsToTime(t pgtype.Timestamptz) time.Time {
if !t.Valid {
return time.Time{}
}
return t.Time
}
func timePtr(t pgtype.Timestamptz) *time.Time {
if !t.Valid {
return nil
}
v := t.Time
return &v
}
func tsFrom(t time.Time) pgtype.Timestamptz {
return pgtype.Timestamptz{Time: t.UTC(), Valid: !t.IsZero()}
}
func tsFromPtr(t *time.Time) pgtype.Timestamptz {
if t == nil {
return pgtype.Timestamptz{}
}
return tsFrom(*t)
}
func mapErr(err error) error {
switch {
case err == nil:
return nil
case errors.Is(err, pgx.ErrNoRows):
return store.ErrNotFound
}
return err
}
// ---- Orgs -----------------------------------------------------------------
type orgStore struct{ s *Store }
func (o orgStore) Create(ctx context.Context, id ids.OrgID, slug, name string) (*store.Org, error) {
row, err := o.s.queries().CreateOrg(ctx, sqlc.CreateOrgParams{ID: id, Slug: slug, Name: name})
if err != nil {
// pgx reports unique-constraint violations with SQLSTATE 23505;
// surface as ErrConflict so callers can 409 cleanly.
if isUniqueViolation(err) {
return nil, store.ErrConflict
}
return nil, err
}
return orgFromRow(row), nil
}
func (o orgStore) GetByID(ctx context.Context, id ids.OrgID) (*store.Org, error) {
row, err := o.s.queries().GetOrgByID(ctx, id)
if err != nil {
return nil, mapErr(err)
}
return orgFromRow(row), nil
}
func (o orgStore) GetBySlug(ctx context.Context, slug string) (*store.Org, error) {
row, err := o.s.queries().GetOrgBySlug(ctx, slug)
if err != nil {
return nil, mapErr(err)
}
return orgFromRow(row), nil
}
func (o orgStore) UpdateName(ctx context.Context, id ids.OrgID, name string) (*store.Org, error) {
row, err := o.s.queries().UpdateOrgName(ctx, sqlc.UpdateOrgNameParams{ID: id, Name: name})
if err != nil {
return nil, mapErr(err)
}
return orgFromRow(row), nil
}
func (o orgStore) List(ctx context.Context, limit, offset int) ([]*store.Org, error) {
rows, err := o.s.queries().ListOrgs(ctx, sqlc.ListOrgsParams{Limit: int32(limit), Offset: int32(offset)})
if err != nil {
return nil, err
}
out := make([]*store.Org, 0, len(rows))
for _, r := range rows {
out = append(out, orgFromRow(r))
}
return out, nil
}
func orgFromRow(r sqlc.Org) *store.Org {
return &store.Org{
ID: r.ID, Slug: r.Slug, Name: r.Name,
CreatedAt: tsToTime(r.CreatedAt),
UpdatedAt: tsToTime(r.UpdatedAt),
}
}
// ---- Users ----------------------------------------------------------------
type userStore struct{ s *Store }
func (u userStore) UpsertByAuthentikSub(ctx context.Context, id ids.UserID, sub, email, displayName string, isSysadmin bool) (*store.User, error) {
row, err := u.s.queries().UpsertUserByAuthentikSub(ctx, sqlc.UpsertUserByAuthentikSubParams{
ID: id,
AuthentikSub: &sub,
Email: email,
DisplayName: displayName,
IsSysadmin: isSysadmin,
})
if err != nil {
return nil, err
}
return userFromRow(row), nil
}
func (u userStore) GetByID(ctx context.Context, id ids.UserID) (*store.User, error) {
row, err := u.s.queries().GetUserByID(ctx, id)
if err != nil {
return nil, mapErr(err)
}
return userFromRow(row), nil
}
func (u userStore) GetByEmail(ctx context.Context, email string) (*store.User, error) {
row, err := u.s.queries().GetUserByEmail(ctx, email)
if err != nil {
return nil, mapErr(err)
}
return userFromRow(row), nil
}
func (u userStore) PromoteSysadmin(ctx context.Context, id ids.UserID) error {
return mapErr(u.s.queries().PromoteSysadmin(ctx, id))
}
func userFromRow(r sqlc.User) *store.User {
out := &store.User{
ID: r.ID, Email: r.Email, DisplayName: r.DisplayName, IsSysadmin: r.IsSysadmin,
CreatedAt: tsToTime(r.CreatedAt), UpdatedAt: tsToTime(r.UpdatedAt),
}
if r.AuthentikSub != nil {
out.AuthentikSub = *r.AuthentikSub
}
return out
}
// ---- Memberships ---------------------------------------------------------
type membershipStore struct{ s *Store }
func (m membershipStore) Add(ctx context.Context, orgID ids.OrgID, userID ids.UserID, role string) error {
return m.s.queries().AddMembership(ctx, sqlc.AddMembershipParams{OrgID: orgID, UserID: userID, Role: role})
}
func (m membershipStore) Remove(ctx context.Context, orgID ids.OrgID, userID ids.UserID) error {
return m.s.queries().RemoveMembership(ctx, sqlc.RemoveMembershipParams{OrgID: orgID, UserID: userID})
}
func (m membershipStore) ListForUser(ctx context.Context, userID ids.UserID) ([]*store.Membership, error) {
rows, err := m.s.queries().ListMemberships(ctx, userID)
if err != nil {
return nil, err
}
out := make([]*store.Membership, 0, len(rows))
for _, r := range rows {
out = append(out, &store.Membership{
OrgID: r.OrgID, UserID: r.UserID, Role: r.Role,
OrgSlug: r.Slug, OrgName: r.Name,
Created: tsToTime(r.CreatedAt),
})
}
return out, nil
}
// ---- Tokens --------------------------------------------------------------
type tokenStore struct{ s *Store }
func (t tokenStore) Create(ctx context.Context, tk *store.APIToken) error {
_, err := t.s.queries().CreateAPIToken(ctx, sqlc.CreateAPITokenParams{
Jti: tk.JTI,
OrgID: tk.OrgID,
UserID: tk.UserID,
Label: tk.Label,
Scopes: tk.Scopes,
ExpiresAt: tsFrom(tk.ExpiresAt),
})
return err
}
func (t tokenStore) GetByJTI(ctx context.Context, jti ids.TokenID) (*store.APIToken, error) {
row, err := t.s.queries().GetAPITokenByJTI(ctx, jti)
if err != nil {
return nil, mapErr(err)
}
return apiTokenFromRow(row), nil
}
func (t tokenStore) ListForUser(ctx context.Context, orgID ids.OrgID, userID ids.UserID) ([]*store.APIToken, error) {
rows, err := t.s.queries().ListAPITokensForUser(ctx, sqlc.ListAPITokensForUserParams{OrgID: orgID, UserID: userID})
if err != nil {
return nil, err
}
out := make([]*store.APIToken, 0, len(rows))
for _, r := range rows {
out = append(out, apiTokenFromRow(r))
}
return out, nil
}
func (t tokenStore) Revoke(ctx context.Context, jti ids.TokenID) error {
return mapErr(t.s.queries().RevokeAPIToken(ctx, jti))
}
func (t tokenStore) TouchLastUsed(ctx context.Context, jti ids.TokenID) error {
return mapErr(t.s.queries().TouchAPITokenLastUsed(ctx, jti))
}
func (t tokenStore) AddDenylist(ctx context.Context, jti ids.TokenID, expiresAt time.Time, reason string) error {
return t.s.queries().AddTokenDenylist(ctx, sqlc.AddTokenDenylistParams{
Jti: jti.String(), ExpiresAt: tsFrom(expiresAt), Reason: reason,
})
}
func (t tokenStore) IsDenied(ctx context.Context, jti ids.TokenID) (bool, error) {
return t.s.queries().IsTokenDenied(ctx, jti.String())
}
func (t tokenStore) PruneDenylist(ctx context.Context) error {
return t.s.queries().PruneTokenDenylist(ctx)
}
func apiTokenFromRow(r sqlc.ApiToken) *store.APIToken {
return &store.APIToken{
JTI: r.Jti, OrgID: r.OrgID, UserID: r.UserID,
Label: r.Label, Scopes: r.Scopes,
ExpiresAt: tsToTime(r.ExpiresAt),
RevokedAt: timePtr(r.RevokedAt), LastUsedAt: timePtr(r.LastUsedAt),
CreatedAt: tsToTime(r.CreatedAt), UpdatedAt: tsToTime(r.UpdatedAt),
}
}
// ---- Nodes ---------------------------------------------------------------
type nodeStore struct{ s *Store }
func (n nodeStore) Upsert(ctx context.Context, nd *store.Node) error {
_, err := n.s.queries().UpsertNode(ctx, sqlc.UpsertNodeParams{
ID: nd.ID, DisplayName: nd.DisplayName, Multiaddrs: nd.Multiaddrs, RpcUrl: nd.RPCURL,
})
return err
}
func (n nodeStore) Get(ctx context.Context, id ids.NodeID) (*store.Node, error) {
row, err := n.s.queries().GetNode(ctx, id)
if err != nil {
return nil, mapErr(err)
}
return nodeFromRow(row), nil
}
func (n nodeStore) ListAll(ctx context.Context) ([]*store.Node, error) {
rows, err := n.s.queries().ListAllNodes(ctx)
if err != nil {
return nil, err
}
out := make([]*store.Node, 0, len(rows))
for _, r := range rows {
out = append(out, nodeFromRow(r))
}
return out, nil
}
func (n nodeStore) ListLive(ctx context.Context) ([]*store.Node, error) {
rows, err := n.s.queries().ListLiveNodes(ctx)
if err != nil {
return nil, err
}
out := make([]*store.Node, 0, len(rows))
for _, r := range rows {
out = append(out, nodeFromRow(r))
}
return out, nil
}
func (n nodeStore) TouchHeartbeat(ctx context.Context, id ids.NodeID) error {
return n.s.queries().TouchNodeHeartbeat(ctx, id)
}
func (n nodeStore) MarkStaleDown(ctx context.Context, staleAfter time.Duration) ([]ids.NodeID, error) {
return n.s.queries().MarkStaleNodesDown(ctx, staleAfter.Seconds())
}
func (n nodeStore) Drain(ctx context.Context, id ids.NodeID) error {
return n.s.queries().DrainNode(ctx, id)
}
func (n nodeStore) Uncordon(ctx context.Context, id ids.NodeID) error {
return n.s.queries().UncordonNode(ctx, id)
}
func nodeFromRow(r sqlc.Node) *store.Node {
return &store.Node{
ID: r.ID, DisplayName: r.DisplayName, Multiaddrs: r.Multiaddrs, RPCURL: r.RpcUrl,
Status: r.Status,
LastSeenAt: tsToTime(r.LastSeenAt), JoinedAt: tsToTime(r.JoinedAt), UpdatedAt: tsToTime(r.UpdatedAt),
}
}
// ---- Pins ----------------------------------------------------------------
type pinStore struct{ s *Store }
func (p pinStore) Create(ctx context.Context, pn *store.Pin) error {
meta, err := json.Marshal(pn.Meta)
if err != nil {
return fmt.Errorf("marshal meta: %w", err)
}
_, err = p.s.queries().CreatePin(ctx, sqlc.CreatePinParams{
RequestID: pn.RequestID, OrgID: pn.OrgID, Cid: pn.CID,
Name: pn.Name, Meta: meta, Origins: pn.Origins,
})
if isUniqueViolation(err) {
return store.ErrConflict
}
return err
}
func (p pinStore) Get(ctx context.Context, orgID ids.OrgID, rid ids.PinID) (*store.Pin, error) {
row, err := p.s.queries().GetPin(ctx, sqlc.GetPinParams{RequestID: rid, OrgID: orgID})
if err != nil {
return nil, mapErr(err)
}
return pinFromRow(row)
}
func (p pinStore) GetByRequestID(ctx context.Context, rid ids.PinID) (*store.Pin, error) {
// The sqlc GetPin requires org_id; fall back to filtered list of one.
// We work around by using GetPin with a scratched filter — but sqlc
// doesn't expose that. Use a raw query via the pool.
var orgID ids.OrgID
var cid string
var name *string
var meta []byte
var origins []string
var status string
var failureReason *string
var created, updated pgtype.Timestamptz
err := p.s.pool.QueryRow(ctx,
"SELECT org_id, cid, name, meta, origins, status, failure_reason, created, updated_at FROM pins WHERE request_id = $1",
rid,
).Scan(&orgID, &cid, &name, &meta, &origins, &status, &failureReason, &created, &updated)
if err != nil {
return nil, mapErr(err)
}
return pinFromFields(rid, orgID, cid, name, meta, origins, status, failureReason, created, updated)
}
func (p pinStore) GetLiveByCID(ctx context.Context, orgID ids.OrgID, cid string) (*store.Pin, error) {
row, err := p.s.queries().GetExistingLivePinByCID(ctx, sqlc.GetExistingLivePinByCIDParams{OrgID: orgID, Cid: cid})
if err != nil {
return nil, mapErr(err)
}
return pinFromRow(row)
}
func (p pinStore) UpdateStatus(ctx context.Context, rid ids.PinID, status string, failureReason *string) error {
return p.s.queries().UpdatePinStatus(ctx, sqlc.UpdatePinStatusParams{
RequestID: rid, Status: status, FailureReason: failureReason,
})
}
func (p pinStore) Delete(ctx context.Context, orgID ids.OrgID, rid ids.PinID) error {
return mapErr(p.s.queries().DeletePin(ctx, sqlc.DeletePinParams{RequestID: rid, OrgID: orgID}))
}
func (p pinStore) List(ctx context.Context, orgID ids.OrgID, limit, offset int) ([]*store.Pin, error) {
rows, err := p.s.queries().ListPins(ctx, sqlc.ListPinsParams{
OrgID: orgID, Limit: int32(limit), Offset: int32(offset),
})
if err != nil {
return nil, err
}
out := make([]*store.Pin, 0, len(rows))
for _, r := range rows {
p, err := pinFromRow(r)
if err != nil {
return nil, err
}
out = append(out, p)
}
return out, nil
}
func (p pinStore) Filter(ctx context.Context, orgID ids.OrgID, f store.PinFilter) ([]*store.Pin, error) {
meta := []byte("{}")
if len(f.Meta) > 0 {
b, err := json.Marshal(f.Meta)
if err != nil {
return nil, fmt.Errorf("marshal meta filter: %w", err)
}
meta = b
}
var namePtr *string
if f.Name != "" {
namePtr = &f.Name
}
matchMode := f.Match
if matchMode == "" {
matchMode = "exact"
}
limit := int32(f.Limit)
if limit <= 0 {
limit = 10
}
rows, err := p.s.queries().FilterPins(ctx, sqlc.FilterPinsParams{
OrgID: orgID,
Cids: f.CIDs,
Statuses: f.Status,
Name: namePtr,
MatchMode: matchMode,
Before: tsFromPtr(f.Before),
After: tsFromPtr(f.After),
MetaFilter: meta,
PinLimit: limit,
PinOffset: int32(f.Offset),
})
if err != nil {
return nil, err
}
out := make([]*store.Pin, 0, len(rows))
for _, r := range rows {
p, err := pinFromRow(r)
if err != nil {
return nil, err
}
out = append(out, p)
}
return out, nil
}
func (p pinStore) Replace(ctx context.Context, orgID ids.OrgID, rid ids.PinID, newCID string, name *string, meta map[string]any, origins []string) (*store.Pin, error) {
metaBytes, err := json.Marshal(meta)
if err != nil {
return nil, err
}
row, err := p.s.queries().ReplacePin(ctx, sqlc.ReplacePinParams{
RequestID: rid, OrgID: orgID, Cid: newCID, Name: name, Meta: metaBytes, Origins: origins,
})
if err != nil {
return nil, mapErr(err)
}
return pinFromRow(row)
}
func (p pinStore) InsertPlacement(ctx context.Context, rid ids.PinID, nid ids.NodeID, fence int64) (*store.Placement, error) {
row, err := p.s.queries().InsertPlacement(ctx, sqlc.InsertPlacementParams{RequestID: rid, NodeID: nid, Fence: fence})
if err != nil {
return nil, err
}
return placementFromRow(row), nil
}
func (p pinStore) GetPlacement(ctx context.Context, rid ids.PinID, nid ids.NodeID) (*store.Placement, error) {
row, err := p.s.queries().GetPlacement(ctx, sqlc.GetPlacementParams{RequestID: rid, NodeID: nid})
if err != nil {
return nil, mapErr(err)
}
return placementFromRow(row), nil
}
func (p pinStore) ListPlacements(ctx context.Context, rid ids.PinID) ([]*store.Placement, error) {
rows, err := p.s.queries().ListPlacementsForPin(ctx, rid)
if err != nil {
return nil, err
}
out := make([]*store.Placement, 0, len(rows))
for _, r := range rows {
out = append(out, &store.Placement{
RequestID: r.RequestID, NodeID: r.NodeID,
Status: r.Status, FailureReason: r.FailureReason,
Attempts: int(r.Attempts), Fence: r.Fence,
CreatedAt: tsToTime(r.CreatedAt), UpdatedAt: tsToTime(r.UpdatedAt),
Multiaddrs: r.Multiaddrs,
})
}
return out, nil
}
func (p pinStore) ListPlacementsForNode(ctx context.Context, nid ids.NodeID, status string) ([]*store.Placement, error) {
rows, err := p.s.queries().ListPlacementsForNode(ctx, sqlc.ListPlacementsForNodeParams{NodeID: nid, Status: status})
if err != nil {
return nil, err
}
out := make([]*store.Placement, 0, len(rows))
for _, r := range rows {
out = append(out, placementFromRow(r))
}
return out, nil
}
func (p pinStore) UpdatePlacementFenced(ctx context.Context, rid ids.PinID, nid ids.NodeID, status string, failureReason *string, fence int64) (int64, error) {
return p.s.queries().UpdatePlacementStatusFenced(ctx, sqlc.UpdatePlacementStatusFencedParams{
RequestID: rid, NodeID: nid, Status: status, FailureReason: failureReason, Fence: fence,
})
}
func (p pinStore) ReplacePlacement(ctx context.Context, rid ids.PinID, oldNode, newNode ids.NodeID) (*store.Placement, error) {
row, err := p.s.queries().ReplacePlacementFence(ctx, sqlc.ReplacePlacementFenceParams{
RequestID: rid, NodeID: oldNode, NodeID_2: newNode,
})
if err != nil {
return nil, mapErr(err)
}
return placementFromRow(row), nil
}
func (p pinStore) StuckPlacements(ctx context.Context, stuckAfter time.Duration) ([]store.Placement, error) {
rows, err := p.s.queries().StuckPlacements(ctx, stuckAfter.Seconds())
if err != nil {
return nil, err
}
out := make([]store.Placement, 0, len(rows))
for _, r := range rows {
out = append(out, store.Placement{
RequestID: r.RequestID, NodeID: r.NodeID, Fence: r.Fence,
})
}
return out, nil
}
func (p pinStore) IncRefcount(ctx context.Context, nid ids.NodeID, cid string) error {
return p.s.queries().IncRefcount(ctx, sqlc.IncRefcountParams{NodeID: nid, Cid: cid})
}
func (p pinStore) DecRefcount(ctx context.Context, nid ids.NodeID, cid string) (int, error) {
v, err := p.s.queries().DecRefcount(ctx, sqlc.DecRefcountParams{NodeID: nid, Cid: cid})
if err != nil {
return 0, mapErr(err)
}
return int(v), nil
}
func (p pinStore) DeleteRefcountIfZero(ctx context.Context, nid ids.NodeID, cid string) error {
return p.s.queries().DeleteRefcount(ctx, sqlc.DeleteRefcountParams{NodeID: nid, Cid: cid})
}
// CountPlacementsByStatus runs a GROUP BY query directly against the
// pool. Not in sqlc because we never needed a typed result for it
// elsewhere — only the gauge-refresh goroutine consumes it.
func (p pinStore) CountPlacementsByStatus(ctx context.Context) (map[string]int, error) {
rows, err := p.s.pool.Query(ctx,
`SELECT status, COUNT(*) FROM pin_placements GROUP BY status`)
if err != nil {
return nil, err
}
defer rows.Close()
out := map[string]int{}
for rows.Next() {
var status string
var n int
if err := rows.Scan(&status, &n); err != nil {
return nil, err
}
out[status] = n
}
return out, rows.Err()
}
func pinFromRow(r sqlc.Pin) (*store.Pin, error) {
return pinFromFields(r.RequestID, r.OrgID, r.Cid, r.Name, r.Meta, r.Origins, r.Status, r.FailureReason, r.Created, r.UpdatedAt)
}
func pinFromFields(rid ids.PinID, orgID ids.OrgID, cid string, name *string, meta []byte, origins []string, status string, fr *string, created, updated pgtype.Timestamptz) (*store.Pin, error) {
var metaMap map[string]any
if len(meta) > 0 {
if err := json.Unmarshal(meta, &metaMap); err != nil {
return nil, fmt.Errorf("decode meta: %w", err)
}
}
return &store.Pin{
RequestID: rid, OrgID: orgID, CID: cid, Name: name,
Meta: metaMap, Origins: origins, Status: status, FailureReason: fr,
Created: tsToTime(created), UpdatedAt: tsToTime(updated),
}, nil
}
func placementFromRow(r sqlc.PinPlacement) *store.Placement {
return &store.Placement{
RequestID: r.RequestID, NodeID: r.NodeID,
Status: r.Status, FailureReason: r.FailureReason,
Attempts: int(r.Attempts), Fence: r.Fence,
CreatedAt: tsToTime(r.CreatedAt), UpdatedAt: tsToTime(r.UpdatedAt),
}
}
// ---- Audit ---------------------------------------------------------------
type auditStore struct{ s *Store }
func (a auditStore) Insert(ctx context.Context, e *store.AuditEntry) error {
detail, err := json.Marshal(e.Detail)
if err != nil {
return err
}
var orgID ids.OrgID
if e.OrgID != nil {
orgID = *e.OrgID
}
var userID ids.UserID
if e.ActorUserID != nil {
userID = *e.ActorUserID
}
return a.s.queries().InsertAudit(ctx, sqlc.InsertAuditParams{
OrgID: orgID, ActorUserID: userID, ActorTokenJti: e.ActorTokenJTI,
Action: e.Action, Target: e.Target, Result: e.Result, Detail: detail,
})
}
func (a auditStore) List(ctx context.Context, orgID ids.OrgID, limit, offset int) ([]*store.AuditEntry, error) {
// Zero OrgID → sysadmin cluster-wide listing; sqlc's ListAudit is
// scoped per-org so we drop to a raw query for that path.
if orgID.IsZero() {
rows, err := a.s.pool.Query(ctx,
"SELECT id, org_id, actor_user_id, actor_token_jti, action, target, result, detail, created FROM audit_log ORDER BY created DESC LIMIT $1 OFFSET $2",
limit, offset)
if err != nil {
return nil, err
}
defer rows.Close()
out := []*store.AuditEntry{}
for rows.Next() {
var (
id int64
org ids.OrgID
actorUser ids.UserID
actorTokenJti *string
action, target, result string
detail []byte
created pgtype.Timestamptz
)
if err := rows.Scan(&id, &org, &actorUser, &actorTokenJti, &action, &target, &result, &detail, &created); err != nil {
return nil, err
}
out = append(out, auditRowToEntry(id, org, actorUser, actorTokenJti, action, target, result, detail, created))
}
return out, rows.Err()
}
rows, err := a.s.queries().ListAudit(ctx, sqlc.ListAuditParams{OrgID: orgID, Limit: int32(limit), Offset: int32(offset)})
if err != nil {
return nil, err
}
out := make([]*store.AuditEntry, 0, len(rows))
for _, r := range rows {
out = append(out, auditRowToEntry(r.ID, r.OrgID, r.ActorUserID, r.ActorTokenJti, r.Action, r.Target, r.Result, r.Detail, r.Created))
}
return out, nil
}
func auditRowToEntry(id int64, orgID ids.OrgID, actorUser ids.UserID, actorTokenJti *string, action, target, result string, detail []byte, created pgtype.Timestamptz) *store.AuditEntry {
var detailMap map[string]any
if len(detail) > 0 {
_ = json.Unmarshal(detail, &detailMap)
}
out := &store.AuditEntry{
ID: id, Action: action, Target: target, Result: result,
Detail: detailMap, ActorTokenJTI: actorTokenJti,
Created: tsToTime(created),
}
if !orgID.IsZero() {
v := orgID
out.OrgID = &v
}
if !actorUser.IsZero() {
v := actorUser
out.ActorUserID = &v
}
return out
}
// ---- Helpers ---------------------------------------------------------------
// isUniqueViolation recognises Postgres SQLSTATE 23505.
func isUniqueViolation(err error) bool {
if err == nil {
return false
}
var pgErr interface{ SQLState() string }
if !errors.As(err, &pgErr) {
return false
}
return pgErr.SQLState() == "23505"
}