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

+145
View File
@@ -0,0 +1,145 @@
// Package ids defines anchorage's typed identifier system.
//
// Every domain entity gets its own compile-time-distinct ID type built on
// the TypeID spec (https://github.com/jetify-com/typeid-go): a human-readable
// prefix joined to a base32-encoded UUIDv7 by an underscore. For example:
//
// org_01h7rfxv6qefr4twn2jg5p4k3z
// pin_01h7rfxz5pehmy08b3tybczg2y
//
// Properties:
//
// - UUIDv7 is time-ordered, giving Postgres index locality close to a
// sequential bigint without the coordination cost.
// - The prefix is self-describing in logs, audit rows, and UIs, and is
// enforced by a per-table CHECK constraint in the schema.
// - Each subtype (OrgID, PinID, ...) is a distinct Go type. Passing an
// OrgID where a PinID is expected is a compile-time error.
//
// To accept an ID on an API boundary, use the matching Parse* helper — it
// will reject a value with the wrong prefix, giving tenant isolation a
// second layer of defense at the type level.
package ids
import (
"fmt"
"go.jetify.com/typeid"
)
// Entity prefix tokens. Kept as constants so schema migrations, CHECK
// constraints, and log filters can reference a single source of truth.
const (
OrgPrefixToken = "org"
UserPrefixToken = "usr"
PinPrefixToken = "pin"
TokenPrefixToken = "tok"
NodePrefixToken = "nod"
)
// OrgPrefix tags an Organization ID.
type OrgPrefix struct{}
// Prefix returns OrgPrefixToken.
func (OrgPrefix) Prefix() string { return OrgPrefixToken }
// UserPrefix tags a User ID.
type UserPrefix struct{}
// Prefix returns UserPrefixToken.
func (UserPrefix) Prefix() string { return UserPrefixToken }
// PinPrefix tags a Pin request ID.
type PinPrefix struct{}
// Prefix returns PinPrefixToken.
func (PinPrefix) Prefix() string { return PinPrefixToken }
// TokenPrefix tags an API-token JTI.
type TokenPrefix struct{}
// Prefix returns TokenPrefixToken.
func (TokenPrefix) Prefix() string { return TokenPrefixToken }
// NodePrefix tags a cluster Node ID.
type NodePrefix struct{}
// Prefix returns NodePrefixToken.
func (NodePrefix) Prefix() string { return NodePrefixToken }
// OrgID identifies an Organization.
type OrgID struct{ typeid.TypeID[OrgPrefix] }
// UserID identifies a User.
type UserID struct{ typeid.TypeID[UserPrefix] }
// PinID identifies a pin request (returned to clients as PinStatus.requestid).
type PinID struct{ typeid.TypeID[PinPrefix] }
// TokenID identifies an API token (the JWT's jti claim).
type TokenID struct{ typeid.TypeID[TokenPrefix] }
// NodeID identifies a cluster node.
type NodeID struct{ typeid.TypeID[NodePrefix] }
// NewOrg returns a fresh OrgID backed by a random UUIDv7.
func NewOrg() (OrgID, error) { return typeid.New[OrgID]() }
// NewUser returns a fresh UserID backed by a random UUIDv7.
func NewUser() (UserID, error) { return typeid.New[UserID]() }
// NewPin returns a fresh PinID backed by a random UUIDv7.
func NewPin() (PinID, error) { return typeid.New[PinID]() }
// NewToken returns a fresh TokenID backed by a random UUIDv7.
func NewToken() (TokenID, error) { return typeid.New[TokenID]() }
// NewNode returns a fresh NodeID backed by a random UUIDv7.
func NewNode() (NodeID, error) { return typeid.New[NodeID]() }
// MustNewOrg is the panic-on-error companion of NewOrg.
//
// The underlying UUIDv7 generator only fails on a crypto/rand read error;
// if that happens, the process is in a state where panicking is the right
// response, so call-site ergonomics win.
func MustNewOrg() OrgID { return typeid.Must(NewOrg()) }
// MustNewUser is the panic-on-error companion of NewUser.
func MustNewUser() UserID { return typeid.Must(NewUser()) }
// MustNewPin is the panic-on-error companion of NewPin.
func MustNewPin() PinID { return typeid.Must(NewPin()) }
// MustNewToken is the panic-on-error companion of NewToken.
func MustNewToken() TokenID { return typeid.Must(NewToken()) }
// MustNewNode is the panic-on-error companion of NewNode.
func MustNewNode() NodeID { return typeid.Must(NewNode()) }
// ParseOrg parses s as an OrgID, rejecting any value that does not carry
// the "org" prefix.
func ParseOrg(s string) (OrgID, error) { return parseTyped[OrgID](s, OrgPrefixToken) }
// ParseUser parses s as a UserID.
func ParseUser(s string) (UserID, error) { return parseTyped[UserID](s, UserPrefixToken) }
// ParsePin parses s as a PinID.
func ParsePin(s string) (PinID, error) { return parseTyped[PinID](s, PinPrefixToken) }
// ParseToken parses s as a TokenID.
func ParseToken(s string) (TokenID, error) { return parseTyped[TokenID](s, TokenPrefixToken) }
// ParseNode parses s as a NodeID.
func ParseNode(s string) (NodeID, error) { return parseTyped[NodeID](s, NodePrefixToken) }
// parseTyped is a small wrapper that normalises the "wrong prefix" error so
// callers can print a useful message without unwrapping typeid's internal
// validation error type.
func parseTyped[T typeid.Subtype, PT typeid.SubtypePtr[T]](s, want string) (T, error) {
id, err := typeid.Parse[T, PT](s)
if err != nil {
var zero T
return zero, fmt.Errorf("parse %s id %q: %w", want, s, err)
}
return id, nil
}
+144
View File
@@ -0,0 +1,144 @@
package ids_test
import (
"strings"
"testing"
"anchorage/internal/pkg/ids"
)
func TestNewConstructorsReturnCorrectPrefixes(t *testing.T) {
tests := []struct {
name string
gen func(t *testing.T) (string, string)
prefix string
}{
{"org", func(t *testing.T) (string, string) {
id, err := ids.NewOrg()
if err != nil {
t.Fatalf("NewOrg: %v", err)
}
return id.Prefix(), id.String()
}, ids.OrgPrefixToken},
{"user", func(t *testing.T) (string, string) {
id, err := ids.NewUser()
if err != nil {
t.Fatalf("NewUser: %v", err)
}
return id.Prefix(), id.String()
}, ids.UserPrefixToken},
{"pin", func(t *testing.T) (string, string) {
id, err := ids.NewPin()
if err != nil {
t.Fatalf("NewPin: %v", err)
}
return id.Prefix(), id.String()
}, ids.PinPrefixToken},
{"token", func(t *testing.T) (string, string) {
id, err := ids.NewToken()
if err != nil {
t.Fatalf("NewToken: %v", err)
}
return id.Prefix(), id.String()
}, ids.TokenPrefixToken},
{"node", func(t *testing.T) (string, string) {
id, err := ids.NewNode()
if err != nil {
t.Fatalf("NewNode: %v", err)
}
return id.Prefix(), id.String()
}, ids.NodePrefixToken},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
prefix, str := tt.gen(t)
if prefix != tt.prefix {
t.Errorf("Prefix() = %q, want %q", prefix, tt.prefix)
}
if !strings.HasPrefix(str, tt.prefix+"_") {
t.Errorf("String() = %q, want prefix %q", str, tt.prefix+"_")
}
})
}
}
func TestMustConstructorsDoNotPanicInHappyPath(t *testing.T) {
// Smoke-test: they must return the same prefix as the error-returning
// counterpart, and not panic under normal operation.
if p := ids.MustNewOrg().Prefix(); p != ids.OrgPrefixToken {
t.Errorf("MustNewOrg prefix = %q", p)
}
if p := ids.MustNewUser().Prefix(); p != ids.UserPrefixToken {
t.Errorf("MustNewUser prefix = %q", p)
}
if p := ids.MustNewPin().Prefix(); p != ids.PinPrefixToken {
t.Errorf("MustNewPin prefix = %q", p)
}
if p := ids.MustNewToken().Prefix(); p != ids.TokenPrefixToken {
t.Errorf("MustNewToken prefix = %q", p)
}
if p := ids.MustNewNode().Prefix(); p != ids.NodePrefixToken {
t.Errorf("MustNewNode prefix = %q", p)
}
}
func TestIDsAreUniquePerCall(t *testing.T) {
// UUIDv7 suffixes must differ between calls even back-to-back.
a := ids.MustNewPin().String()
b := ids.MustNewPin().String()
if a == b {
t.Fatalf("two consecutive NewPin() calls produced the same id: %s", a)
}
}
func TestIDsAreTimeOrdered(t *testing.T) {
// UUIDv7 is time-ordered, so later-generated IDs should sort after
// earlier ones lexicographically. This is the property that gives
// Postgres index locality on (org_id, id desc).
prev := ids.MustNewPin().String()
for i := 0; i < 32; i++ {
next := ids.MustNewPin().String()
if next <= prev {
t.Fatalf("UUIDv7 ordering violated: %q followed %q", next, prev)
}
prev = next
}
}
func TestParseRoundTrip(t *testing.T) {
orig := ids.MustNewOrg()
parsed, err := ids.ParseOrg(orig.String())
if err != nil {
t.Fatalf("ParseOrg: %v", err)
}
if parsed.String() != orig.String() {
t.Errorf("round-trip changed value: %q -> %q", orig, parsed)
}
}
func TestParseRejectsWrongPrefix(t *testing.T) {
// An org ID string must not parse as a pin ID.
orgStr := ids.MustNewOrg().String()
if _, err := ids.ParsePin(orgStr); err == nil {
t.Errorf("ParsePin accepted an org id %q", orgStr)
}
}
func TestParseRejectsGarbage(t *testing.T) {
tests := []string{
"",
"not-a-typeid",
"org_",
"_01h7rfxv6qefr4twn2jg5p4k3z",
"org_too-short",
"org_01h7rfxv6qefr4twn2jg5p4k3Z", // uppercase base32 char: invalid
}
for _, s := range tests {
t.Run(s, func(t *testing.T) {
if _, err := ids.ParseOrg(s); err == nil {
t.Errorf("ParseOrg(%q) should have failed", s)
}
})
}
}