db

package
v0.61.0 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: Apache-2.0 Imports: 19 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package db owns the postgres connection pool, migrations, and per-table repositories.

Index

Constants

View Source
const (
	AuditActionPipeCreate  = "pipe.create"
	AuditActionPipeSet     = "pipe.set"
	AuditActionPipeDestroy = "pipe.destroy"

	// Source lifecycle. A destroy takes every pipe under the source with
	// it, so its `before` lists them.
	AuditActionSourceCreate  = "source.create"
	AuditActionSourceDestroy = "source.destroy"

	// ACL changes. An access-control edit is arguably the thing most
	// worth auditing in the product: its entire purpose is to alter who
	// can see what. docs/ACL.md listed this as a non-goal only because
	// no trail existed when that was written.
	AuditActionACLGrant   = "acl.grant"
	AuditActionACLRevoke  = "acl.revoke"
	AuditActionACLEnforce = "acl.enforce"
)

Audit actions. Dotted <noun>.<verb> so later writers (key.revoke, member.remove) read consistently alongside these. The strings are persisted on every row and the GUI labels/filters on them, so they're a stable contract — rename one and old rows become unreadable.

View Source
const (
	AuditTargetPipe   = "pipe"
	AuditTargetSource = "source"
	// AuditTargetOrg is for changes to the org itself rather than to a
	// pipe within it — the enforcement switch names the account, and
	// filing it under a pipe that does not exist would make the trail
	// lie about what was touched.
	AuditTargetOrg = "org"
)

Audit target types. Names what Target refers to.

View Source
const ServiceNameSeparator = "/"

ServiceNameSeparator scopes a service account's stored username as "<org>/<name>". users.username is globally unique, so two orgs could not otherwise both hold a "builder-bot". Every surface displays the bare name; only storage and lookup see the scoped form.

Variables

View Source
var (
	ErrDeviceCodePending = errors.New("device_code not yet verified")
	ErrDeviceCodeExpired = errors.New("device_code expired")
)
View Source
var ErrAlreadyMember = errors.New("user is already a member of this account")

ErrAlreadyMember is returned by CreateInvite when the invitee is already a member or the owner of the org. Same intent as the duplicate-pending case but a different cause — surface separately.

View Source
var ErrCannotRemoveOwner = errors.New("cannot remove the account's owner")

ErrCannotRemoveOwner is returned by RemoveMember when the caller tries to remove the org's owner. v1 has no transfer-ownership path; the owner has to stay on the org until v2 lands transfer.

View Source
var ErrDuplicatePendingInvite = errors.New("a pending invite for this user already exists")

ErrDuplicatePendingInvite is returned by CreateInvite when an active pending invite for the same (org, username) already exists. The unique partial index enforces this server-side; we surface a typed sentinel so handlers can return a clean 409.

View Source
var ErrHandleTaken = errors.New("handle taken")

ErrHandleTaken is returned when a (org, handle) row already exists.

View Source
var ErrInvalidUserMode = errors.New("user mode must be 'github', 'internal' or 'service'")

ErrInvalidUserMode is returned when a caller passes a Mode value outside the {github, internal} CHECK constraint.

View Source
var ErrInviteNotPending = errors.New("invite is not pending")

ErrInviteNotPending is returned when a transition (accept/decline/ revoke) targets an invite that is no longer pending. Caller surfaces it as 409.

View Source
var ErrNotFound = errors.New("not found")

ErrNotFound is returned by lookups when the row does not exist.

View Source
var ErrPipeNameTaken = errors.New("pipe name taken")

ErrPipeNameTaken — uniqueness collision on insert. The partial UNIQUE indexes split this by collared/uncollared shape, but both surface here.

View Source
var ErrScheduleIDAmbiguous = errors.New("schedule short id is ambiguous (matches multiple schedules)")

ErrScheduleIDAmbiguous — a short id matched more than one row in the account. InsertSchedule regenerates uuids to avoid ever minting a colliding suffix, so this is a should-never belt; `schedule rm` must still refuse to guess rather than silently delete multiple rows.

View Source
var ErrServiceExists = errors.New("service account already exists")

ErrServiceExists is returned when a name is already taken in the org.

Functions

func ACLEnforced added in v0.58.0

func ACLEnforced(ctx context.Context, p *Pool, accountID uuid.UUID) (bool, error)

ACLEnforced reports whether the org enforces ACLs. False for every org until an admin opts in.

func ACLGeneration added in v0.58.0

func ACLGeneration(ctx context.Context, p *Pool, accountID uuid.UUID) (int64, error)

ACLGeneration reads the current generation counter.

func APIKeyCreator added in v0.58.3

func APIKeyCreator(ctx context.Context, p *Pool, accountID, id uuid.UUID) (uuid.UUID, error)

APIKeyCreator returns the user who minted the account's key id. ErrNotFound if no such key belongs to the account.

func AcceptInvite added in v0.22.0

func AcceptInvite(ctx context.Context, p *Pool, inviteID, acceptingUserID uuid.UUID) error

AcceptInvite transitions a pending invite to accepted and adds the accepting user as a non-owner member of the org, atomically. The caller passes the accepting user's id; the function checks that their username matches the invite's invitee_username (so a logged-in user can't accept someone else's invite even if they know the id).

Returns:

  • ErrNotFound if the invite id doesn't exist
  • ErrInviteNotPending if the invite is no longer pending
  • errors.New("forbidden") if userID's username != invitee_username

func AddMember

func AddMember(ctx context.Context, p *Pool, accountID, userID uuid.UUID) error

AddMember records a user as a non-owner member of an org. Idempotent — re-adding an existing member is a no-op (UPSERT-style).

func ApproveDeviceCode

func ApproveDeviceCode(ctx context.Context, p *Pool, userCode string, userID, accountID uuid.UUID) error

ApproveDeviceCode marks the user_code as verified by userID, binding it to the org accountID the user selected on the verify page. Idempotent. Returns ErrNotFound if user_code doesn't exist or is already expired.

func BumpACLGeneration added in v0.58.0

func BumpACLGeneration(ctx context.Context, p *Pool, accountID uuid.UUID) error

BumpACLGeneration marks the account's access state as changed. Phase 3 uses it to invalidate minted NATS credentials — NATS evaluates permissions only at connect, so a revoke needs an explicit nudge to reach a live connection.

func BumpScheduleFailCount added in v0.51.0

func BumpScheduleFailCount(ctx context.Context, p *Pool, id uuid.UUID) (int, error)

BumpScheduleFailCount increments the consecutive-failure counter after a failed publish and returns the post-bump count — the value the scheduler compares against its drop threshold.

func ChatCursorKey added in v0.55.0

func ChatCursorKey(kind, acting, target string) string

ChatCursorKey composes the (kind, acting, target) conversation key the read-cursor table is indexed by, so callers build map keys the same way the roster lookup does. `acting` is the viewer's handle ("" for pipes / god's-eye).

func CompleteFire added in v0.51.0

func CompleteFire(ctx context.Context, p *Pool, id uuid.UUID, next *time.Time, firedAt time.Time) error

CompleteFire settles a claimed row: next==nil deletes it (spent one-off), otherwise next_fire_at is set to *next. A non-zero firedAt stamps last_fired_at and resets fail_count (the counter tracks CONSECUTIVE failures); a beyond-grace skip advances without touching either.

func ConsumeDeviceCode

func ConsumeDeviceCode(ctx context.Context, p *Pool, deviceCode string) (uuid.UUID, *uuid.UUID, error)

ConsumeDeviceCode is the CLI poll path. Returns the user_id and the org the user selected (nil if approved without one) and marks the code consumed (single-use). State machine errors:

  • ErrDeviceCodePending if not yet verified
  • ErrDeviceCodeExpired if past TTL
  • ErrNotFound if unknown / already consumed

func DeclineInvite added in v0.22.0

func DeclineInvite(ctx context.Context, p *Pool, inviteID, decliningUserID uuid.UUID) error

DeclineInvite transitions a pending invite to declined. Same permission check as Accept: caller's username must match the invite's invitee_username.

func DeleteACLGrant added in v0.58.0

func DeleteACLGrant(ctx context.Context, p *Pool, accountID, principalID uuid.UUID, selector, perm string) error

DeleteACLGrant removes a grant. Idempotent: removing something that isn't there leaves the desired state in place, so it returns nil. Passing an empty perm removes every perm for that (principal, selector).

func DeleteChatReadCursorsForTarget added in v0.55.0

func DeleteChatReadCursorsForTarget(ctx context.Context, p *Pool, accountID uuid.UUID, kind, target string) error

DeleteChatReadCursorsForTarget removes every read cursor (all users, all acting handles) for one window. Called when the underlying pipe/source is deleted so a same-name recreate starts fresh instead of inheriting a stale high last_read_seq (which would suppress the new stream's early unread).

func DeletePipe

func DeletePipe(ctx context.Context, p *Pool, sourceID uuid.UUID, name string) error

DeletePipe removes the row. Returns ErrNotFound when (source, name) doesn't exist. Stream cleanup is the caller's responsibility (server-side).

func DeleteScheduleByShortID added in v0.51.0

func DeleteScheduleByShortID(ctx context.Context, p *Pool, accountID uuid.UUID, shortID string) (bool, error)

DeleteScheduleByShortID removes one schedule addressed by the CLI-facing short id (last 8 hex of the uuid). Returns whether a row matched — false maps to E_SCHEDULE_NOT_FOUND at the handler. A multi-row match (per-account suffix collision — prevented at insert, guarded here as a belt) deletes nothing and returns ErrScheduleIDAmbiguous. The suffix expression can't use an index; fine at expected per-account row counts.

func DeleteServiceAccount added in v0.58.0

func DeleteServiceAccount(ctx context.Context, p *Pool, accountID uuid.UUID, orgName, name string) error

DeleteServiceAccount removes the principal. Its keys and ACL grants cascade from the users FK.

func DeleteSource added in v0.21.0

func DeleteSource(ctx context.Context, p *Pool, accountID uuid.UUID, handle string) error

func DeleteSourceByID added in v0.59.0

func DeleteSourceByID(ctx context.Context, p *Pool, accountID, id uuid.UUID) error

DeleteSourceByID deletes exactly one source (pipe rows CASCADE). Unlike DeleteSource it can't take a same-named source in another manifold with it.

func DeleteUncollaredPipe added in v0.31.0

func DeleteUncollaredPipe(ctx context.Context, p *Pool, accountID uuid.UUID, manifold, name string) error

DeleteUncollaredPipe removes an uncollared pipe row by (account, manifold, name). Stream cleanup is the caller's responsibility. Phase 1.5.

func GeneratePlaintextKey

func GeneratePlaintextKey() (string, error)

GeneratePlaintextKey returns a fresh plaintext API key. Format: "ppz_<26 hex chars>" (a UUIDv7 hex without dashes, prefixed). 30 chars total makes the 8-char display prefix human-meaningful while leaving plenty of entropy.

func GetLastSelectedAccount added in v0.50.1

func GetLastSelectedAccount(ctx context.Context, p *Pool, userID uuid.UUID) (*uuid.UUID, error)

GetLastSelectedAccount returns the org the user last authorized a CLI session into (nil if they never have, or the org was since deleted — the FK is ON DELETE SET NULL). Used to default the device-flow org dropdown.

func HashAPIKey

func HashAPIKey(plaintext string) (string, error)

HashAPIKey produces a self-describing argon2id hash:

$argon2id$v=19$m=65536,t=1,p=4$<base64-salt>$<base64-tag>

func InsertACLGrant added in v0.58.0

func InsertACLGrant(ctx context.Context, p *Pool, accountID, principalID uuid.UUID, selector, perm string, grantedBy uuid.UUID) error

InsertACLGrant adds a grant. Idempotent — regranting the same (principal, selector, perm) is a no-op rather than an error, so a retrying agent doesn't see a spurious failure.

func InsertAuditEvent added in v0.57.0

func InsertAuditEvent(ctx context.Context, p *Pool, ev AuditEvent) error

InsertAuditEvent appends one row. ID and CreatedAt are stamped here when the caller left them zero, so call sites stay short.

func IsMemberOrOwner

func IsMemberOrOwner(ctx context.Context, p *Pool, accountID, userID uuid.UUID) bool

IsMemberOrOwner returns true if userID owns accountID or is a member. Used by /auth/exchange (Phase 3.5) to validate that a multi-account user is actually entitled to the account they're requesting a JWT for.

func KeyPrefix

func KeyPrefix(plaintext string) string

KeyPrefix is the first 8 characters AFTER the "ppz_" sentinel. Used for display in the GUI and the `ppz status` line. Never use the prefix for auth.

func ListChatReadCursors added in v0.55.0

func ListChatReadCursors(ctx context.Context, p *Pool, accountID, userID uuid.UUID) (map[string]int64, error)

ListChatReadCursors returns the user's read position for every conversation in the account as a map keyed by ChatCursorKey(kind, acting, target) -> last_read_seq. Absent conversations (never opened) are missing (seq 0 to the caller). One query feeds the whole roster's unread badges.

func Migrate

func Migrate(ctx context.Context, p *Pool) error

Migrate runs every migration file in order, lexicographically by name. Each file uses IF NOT EXISTS / IF NOT EXISTS COLUMN clauses so re-running is idempotent.

func ParseServiceUsername added in v0.58.0

func ParseServiceUsername(username string) (org, name string, ok bool)

ParseServiceUsername splits a stored service username back into its org and bare name. Human usernames must never parse — otherwise the GUI would render "alice" as a service account of some phantom org.

func PipesExistAtManifold added in v0.31.1

func PipesExistAtManifold(ctx context.Context, p *Pool, accountID uuid.UUID, manifold string) (bool, error)

PipesExistAtManifold reports whether ANY pipe (collared or uncollared) exists at the given manifold prefix. Phase 1.5.1 collision check — a new source's handle at manifold M reserves the prefix path M.<handle> (or just <handle> if M is empty), so source creation rejects when pipes already live there.

func RemoveMember

func RemoveMember(ctx context.Context, p *Pool, accountID, userID uuid.UUID) error

RemoveMember drops a non-owner from the org. Returns ErrCannotRemoveOwner when targetUserID matches the org's owner — caller surfaces it as 409. ErrNotFound when the user wasn't a member.

func RevokeAPIKey

func RevokeAPIKey(ctx context.Context, p *Pool, accountID, id uuid.UUID) error

RevokeAPIKey marks the key revoked. Scoped to accountID so a caller authorised for one org can't revoke another org's key by id. Idempotent: revoking an already-revoked key is a no-op (returns nil). Returns ErrNotFound if no key with that id belongs to the account.

func RevokeInvite added in v0.22.0

func RevokeInvite(ctx context.Context, p *Pool, inviteID uuid.UUID) error

RevokeInvite transitions a pending invite to revoked. Owner-only: caller is expected to be the org's owner; this function does not re-check the role (handlers gate via owner-only middleware), but it does require the invite be in the pending state.

func ServiceUsername added in v0.58.0

func ServiceUsername(orgName, name string) string

ServiceUsername builds the stored, org-scoped username.

func SetACLEnforced added in v0.58.0

func SetACLEnforced(ctx context.Context, p *Pool, accountID uuid.UUID, on bool) error

SetACLEnforced flips the switch and bumps the generation counter, so live daemons re-exchange and pick up (or drop) compiled credentials without a restart — the same invalidation path a revoke uses.

Non-destructive in both directions: grant rows are untouched, so disabling and re-enabling restores the previous configuration exactly.

func SetLastSelectedAccount added in v0.50.1

func SetLastSelectedAccount(ctx context.Context, p *Pool, userID, accountID uuid.UUID) error

SetLastSelectedAccount records the org a user just authorized into so the next device-flow verify page defaults its dropdown to it.

func SetMemberRole added in v0.58.0

func SetMemberRole(ctx context.Context, p *Pool, accountID, userID uuid.UUID, role string) error

SetMemberRole sets a member's role within an org. 'owner' is not settable here — ownership lives on accounts.owner_user_id and moves only through the transfer flow.

func SetNATSAccount

func SetNATSAccount(ctx context.Context, p *Pool, accountID uuid.UUID, accountPub, accountJWT, signingSeed string) error

SetNATSAccount persists the Operator-signed Account JWT + the account's signing seed for an account row. Called once (lazily) on first /auth/exchange after Phase 3.5 — subsequent calls find the row already populated and skip.

func SourceExistsAtManifold added in v0.31.1

func SourceExistsAtManifold(ctx context.Context, p *Pool, accountID uuid.UUID, manifold, handle string) (bool, error)

SourceExistsAtManifold reports whether a source with the given handle exists at the manifold. Phase 1.5.1 collision check — uncollared pipe creation rejects when a source shares the proposed name at the same manifold.

func UncollaredPipeExists added in v0.31.1

func UncollaredPipeExists(ctx context.Context, p *Pool, accountID uuid.UUID, manifold, name string) (bool, error)

func UpdateLastBroadcast

func UpdateLastBroadcast(ctx context.Context, p *Pool, accountID uuid.UUID, handle string, at time.Time, payload string) error

UpdateLastBroadcast records the most recent broadcast for this source. Called by the server-side subscriber on every message. Idempotent on identical inputs.

func UpdatePipeRetention added in v0.57.0

func UpdatePipeRetention(ctx context.Context, p *Pool, id uuid.UUID, ttl *int, maxMsgs *int, maxBytes *int64) error

UpdatePipeRetention writes the retention triple for an existing row.

It takes the FULL triple, not a partial patch: a nil arg stores NULL (i.e. drops the field back to the default layer), it does not mean "leave the column alone". Merging a partial request onto the stored row belongs to the caller — the caller needs the old row anyway to echo the resolved retention back, and keeping the merge out of SQL means exactly one place decides precedence.

func UpdateSourceKind added in v0.56.0

func UpdateSourceKind(ctx context.Context, p *Pool, accountID uuid.UUID, handle string, kind SourceKind) error

UpdateSourceKind changes an existing source's kind in place. Used by the "ensure pty" upgrade path when a bare `terminal share` runs against an inbox-only (message) source: sharing a source declares it a terminal, so its kind is promoted to pty and its full pipe set provisioned. `kind` is a plain mutable column. Returns ErrNotFound when (account, handle) is absent. Idempotent: setting pty on an already-pty row affects one row, no error.

func UpsertChatReadCursor added in v0.55.0

func UpsertChatReadCursor(ctx context.Context, p *Pool, accountID, userID uuid.UUID, kind, acting, target string, seq int64) error

UpsertChatReadCursor advances the user's read position for one conversation to seq. GREATEST(existing, excluded) means the cursor only ever moves forward, so a stale/late write can't rewind a read position past what the user has seen.

func UserHasAnyPipe added in v0.31.8

func UserHasAnyPipe(ctx context.Context, p *Pool, userID uuid.UUID) (bool, error)

UncollaredPipeExists reports whether a sourceless pipe with the given (account, manifold, name) already exists. Phase 1.5.1 collision check — source creation rejects when an uncollared pipe shares the source's proposed name at the same manifold. UserHasAnyPipe reports whether the user owns or is a member of any account that has at least one pipe (collared or uncollared). Powers the dashboard onboarding panel: when this is false, the empty-state get-started instructions render; once the user creates a pipe the panel hides itself.

func UsernamesByIDs added in v0.27.0

func UsernamesByIDs(ctx context.Context, p *Pool, ids []uuid.UUID) (map[uuid.UUID]string, error)

UsernamesByIDs resolves a set of user IDs to {id → username}. Used by the server's list endpoints that need to attribute every source/pipe row to a user (HUMAN column). Single round-trip via ANY($1::uuid[]). Missing IDs are simply absent from the returned map — callers should treat that as "" so a stale ID can't break rendering.

func ValidateServiceName added in v0.58.0

func ValidateServiceName(name string) (string, error)

ValidateServiceName checks a bare service-account name. It follows the handle rules, which forbid the scope separator — a name carrying one could otherwise be stored as another org's scoped username.

func VerifyAPIKey

func VerifyAPIKey(plaintext, stored string) bool

VerifyAPIKey checks plaintext against a stored hash in constant time.

Types

type ACLGrant added in v0.58.0

type ACLGrant struct {
	ID            uuid.UUID
	AccountID     uuid.UUID
	PrincipalID   uuid.UUID
	PrincipalName string
	Selector      string
	Perm          string
	GrantedBy     uuid.UUID
	GrantedByName string
	CreatedAt     time.Time
}

ACLGrant is one stored row, joined to the principal's username so callers can render provenance without a second lookup.

func ListACLGrants added in v0.58.0

func ListACLGrants(ctx context.Context, p *Pool, accountID uuid.UUID) ([]ACLGrant, error)

ListACLGrants returns every grant in the account.

func ListACLGrantsForPrincipal added in v0.58.0

func ListACLGrantsForPrincipal(ctx context.Context, p *Pool, accountID, principalID uuid.UUID) ([]ACLGrant, error)

ListACLGrantsForPrincipal returns the grants that could apply to one principal — its own rows plus every @everyone row.

func (ACLGrant) ToACL added in v0.58.0

func (g ACLGrant) ToACL() acl.Grant

ToACL converts a stored row into the evaluator's shape.

type APIKey

type APIKey struct {
	ID              uuid.UUID
	AccountID       uuid.UUID
	CreatedByUserID uuid.UUID // user that minted the key (NOT NULL)
	// PrincipalUserID is the identity the key ACTS AS — the subject an
	// ACL grant names. Seeded from CreatedByUserID by migration 0007,
	// but distinct: an ACL Phase 1 service-account key is created_by a
	// human and acts_as the service. Never collapse the two, or the
	// service inherits the human's rights.
	PrincipalUserID uuid.UUID
	KeyHash         string
	KeyPrefix       string
	Label           string
	CreatedAt       time.Time
	// RevokedAt is nil for active keys, set to the revoke time once
	// `POST /orgs/<id>/keys/<kid>/revoke` flips it. LookupAPIKey filters
	// out revoked rows; the GUI shows them with strikethrough so the
	// audit trail stays visible.
	RevokedAt *time.Time
}

func InsertAPIKey

func InsertAPIKey(ctx context.Context, p *Pool, accountID, createdBy uuid.UUID, label string) (APIKey, string, error)

InsertAPIKey mints a key that acts as its own creator — the ordinary case. Equivalent to InsertAPIKeyAs with principal == createdBy.

func InsertAPIKeyAs added in v0.58.0

func InsertAPIKeyAs(ctx context.Context, p *Pool, accountID, createdBy, principal uuid.UUID, label string) (key APIKey, plaintext string, err error)

InsertAPIKeyAs mints a key whose principal differs from its creator.

`createdBy` is who minted it (attribution / audit); `principal` is who it ACTS AS — the subject an ACL grant names. They diverge for service accounts: a human mints a key that acts as a bot. Collapsing them would hand the bot the human's rights.

func ListAPIKeysForOrg

func ListAPIKeysForOrg(ctx context.Context, p *Pool, accountID uuid.UUID) ([]APIKey, error)

ListAPIKeysForOrg returns every key for the org, including revoked ones — the GUI shows revoked keys (with strikethrough) so the audit trail stays visible. Sorted active-first by creation time, then revoked rows.

func LookupAPIKey

func LookupAPIKey(ctx context.Context, p *Pool, plaintext string) (APIKey, error)

LookupAPIKey resolves a plaintext key to its row by scanning all keys with the matching 8-char prefix and verifying the hash. ErrNotFound when no match (including when the matching key has been revoked).

func (APIKey) Actor added in v0.58.0

func (k APIKey) Actor() uuid.UUID

Actor is the identity rows created through this key are attributed to — the principal, not the minter. For an ordinary key the two are the same; for a service-account key the minter is a human and the actor is the bot, and crediting the human would misattribute the agent's work (and, once ACLs land, evaluate the wrong subject).

Falls back to CreatedByUserID so a synthetic APIKey built by the OAuth path (which sets only that field) still resolves.

func (APIKey) Revoked

func (k APIKey) Revoked() bool

Revoked is a small accessor — useful from html/template, which can't dereference pointers cleanly.

type Account added in v0.30.0

type Account struct {
	ID          uuid.UUID
	Name        string
	OwnerUserID uuid.UUID
	CreatedAt   time.Time

	// Auth V2 §Phase 3.5 — per-account NATS credential. NULL until the
	// account's NATS credential is provisioned (lazy on first /auth/exchange).
	NATSAccountPub         string
	NATSAccountJWT         string
	NATSAccountSigningSeed string
}

Account is the ppz-side tenancy boundary. Maps 1:1 to a NATS account (see SetNATSAccount below for the credential plumbing). Pre-launch this was called "Organisation"; the rename is part of the Phase 1 surface strip (see strategy doc OSS-PIPESCLOUD-ARCHITECTURE-SPLIT, private, locked decisions #11 and #18).

func DefaultAccountFor added in v0.50.1

func DefaultAccountFor(ctx context.Context, p *Pool, userID uuid.UUID) (Account, error)

DefaultAccountFor returns the account to use for a caller who hasn't explicitly selected one: their oldest OWNED account, or — if they own none — their oldest account by MEMBERSHIP. Returns ErrNotFound only when the user neither owns nor belongs to any account.

This is the account-selection default for the OAuth path (device flow + /auth/exchange) and the requireAPIKey ?org fallback. It must consider membership: a user invited into an org (a member, not owner) otherwise has no usable default and every OAuth call 403s / errors — and listing (?org=, membership-aware) would disagree with the minted NATS creds.

func GetAccount added in v0.30.0

func GetAccount(ctx context.Context, p *Pool, id uuid.UUID) (Account, error)

func GetAccountByName added in v0.30.0

func GetAccountByName(ctx context.Context, p *Pool, name string) (Account, error)

GetAccountByName looks up an account by its unique name (used as a slug alias in the GUI: /accounts/alpha resolves the same as /accounts/<uuid>).

func InsertAccount added in v0.30.0

func InsertAccount(ctx context.Context, p *Pool, name string, ownerUserID uuid.UUID) (Account, error)

InsertAccount creates a new account owned by ownerUserID. If ownerUserID is uuid.Nil, the account defaults to the seeded unauthenticated user — preserves back-compat for tests + GUI callers that don't supply an owner yet.

func ListAccounts added in v0.30.0

func ListAccounts(ctx context.Context, p *Pool) ([]Account, error)

func ListAccountsForUser added in v0.30.0

func ListAccountsForUser(ctx context.Context, p *Pool, userID uuid.UUID) ([]Account, error)

ListAccountsForUser returns the accounts userID owns or is a member of, ordered by name. Used by the GUI dashboard so each user sees only their own tenants instead of every account in the system.

type AuditEvent added in v0.57.0

type AuditEvent struct {
	ID          uuid.UUID
	AccountID   uuid.UUID
	ActorUserID uuid.UUID
	// ActorAPIKeyID is the key the action came through; nil means it came
	// from a web session instead. Keeping this distinct is what stops a
	// shared-key change from looking like a person acting in the GUI —
	// on the API path the server only knows the key's creator.
	ActorAPIKeyID *uuid.UUID
	Action        string
	TargetType    string
	Target        string
	// Before and After are raw jsonb. Either may be nil: a create has no
	// before, a destroy has no after.
	Before    []byte
	After     []byte
	CreatedAt time.Time
}

AuditEvent is one append-only row of the trail. See migrations/0006_audit_events.sql for the column-level rationale.

func ListAuditEventsForAccount added in v0.57.0

func ListAuditEventsForAccount(ctx context.Context, p *Pool, accountID uuid.UUID, limit int) ([]AuditEvent, error)

ListAuditEventsForAccount returns the account's trail newest-first, capped at limit. Bounded because a long-lived org's trail is unbounded (no retention policy yet) and the tab renders every row it's handed.

type DeviceCode

type DeviceCode struct {
	DeviceCode string
	UserCode   string
	ClientName string
	UserID     *uuid.UUID
	AccountID  *uuid.UUID // org the user picked on the verify page
	ExpiresAt  time.Time
	VerifiedAt *time.Time
	ConsumedAt *time.Time
	CreatedAt  time.Time
}

DeviceCode is the row stored in oauth_device_codes.

func CreateDeviceCode

func CreateDeviceCode(ctx context.Context, p *Pool, ttl time.Duration, clientName string) (DeviceCode, error)

CreateDeviceCode mints a fresh pair, inserts the row, returns it. clientName is a free-form label the CLI sends so the verify page can name the calling app (e.g. "ppz CLI 0.15.0"); empty string is fine — the page falls back to generic copy.

func LookupDeviceCode

func LookupDeviceCode(ctx context.Context, p *Pool, deviceCode string) (DeviceCode, error)

func LookupDeviceCodeByUserCode

func LookupDeviceCodeByUserCode(ctx context.Context, p *Pool, userCode string) (DeviceCode, error)

type Invite added in v0.22.0

type Invite struct {
	ID              uuid.UUID
	AccountID       uuid.UUID
	InviteeUsername string
	InviterUserID   uuid.UUID
	Status          InviteStatus
	CreatedAt       time.Time
	DecidedAt       *time.Time
}

func CreateInvite added in v0.22.0

func CreateInvite(ctx context.Context, p *Pool, accountID uuid.UUID, inviteeUsername string, inviterUserID uuid.UUID) (Invite, error)

CreateInvite inserts a pending invite for inviteeUsername into accountID, recording inviterUserID as the sender. Pre-flights two error conditions before the insert:

  • inviteeUsername is already a member or the owner of accountID → ErrAlreadyMember
  • a pending invite for the same (org, username) already exists → ErrDuplicatePendingInvite

Pre-flighting the duplicate case in addition to relying on the partial unique index gives us a typed error without inspecting pg error codes.

func GetInvite added in v0.22.0

func GetInvite(ctx context.Context, p *Pool, id uuid.UUID) (Invite, error)

GetInvite fetches a single invite by id. Returns ErrNotFound if the row doesn't exist.

func ListInvitesForOrg added in v0.22.0

func ListInvitesForOrg(ctx context.Context, p *Pool, accountID uuid.UUID) ([]Invite, error)

ListInvitesForOrg returns every invite (any status) for accountID, newest first. Used by the org page to show the invite history.

type InviteStatus added in v0.22.0

type InviteStatus string

InviteStatus values mirror the CHECK constraint on invites.status.

const (
	InviteStatusPending  InviteStatus = "pending"
	InviteStatusAccepted InviteStatus = "accepted"
	InviteStatusDeclined InviteStatus = "declined"
	InviteStatusRevoked  InviteStatus = "revoked"
)

type InviteWithAccount added in v0.30.0

type InviteWithAccount struct {
	Invite
	AccountName string
}

InviteWithAccount is the dashboard projection — invite plus org name so the user can see where the invite came from without a second query.

func ListPendingInvitesForUsername added in v0.22.0

func ListPendingInvitesForUsername(ctx context.Context, p *Pool, username string) ([]InviteWithAccount, error)

ListPendingInvitesForUsername returns all pending invites whose invitee_username matches. Joined with accounts so callers can show the org name on the dashboard.

type Member

type Member struct {
	AccountID uuid.UUID
	UserID    uuid.UUID
	AddedAt   time.Time
}

type OAuthToken

type OAuthToken struct {
	ID         uuid.UUID
	UserID     uuid.UUID
	TokenHash  string
	Prefix     string
	ExpiresAt  time.Time
	RevokedAt  *time.Time
	CreatedAt  time.Time
	LastUsedAt *time.Time
}

func IssueBearerToken

func IssueBearerToken(ctx context.Context, p *Pool, userID uuid.UUID, ttl time.Duration) (string, OAuthToken, error)

func LookupBearerToken

func LookupBearerToken(ctx context.Context, p *Pool, plaintext string) (OAuthToken, error)

type Pipe

type Pipe struct {
	ID              uuid.UUID
	AccountID       uuid.UUID  // tenancy anchor (denormalised; matches source.account_id when SourceID is set)
	Manifold        string     // hierarchical-grouping segment; ” = root (NOT NULL on the DB column)
	SourceID        *uuid.UUID // nil for uncollared (sourceless) pipes
	CreatedByUserID uuid.UUID  // user that created the pipe (NOT NULL)
	Name            string
	// Retention overrides. nil = no opinion at this layer; the server
	// resolves the field from the next layer down (account default, then
	// the built-in default) — see resolveRetention in internal/server.
	// Concrete defaults live there, not here, so they can't drift.
	TTLSeconds *int
	MaxMsgs    *int
	MaxBytes   *int64
	CreatedAt  time.Time
}

Pipe is one user-creatable channel. Phase 1.5: pipes carry an explicit manifold (hierarchical-grouping segment, ” = root) and an account_id (denormalised from source.account_id for collared rows, explicit for uncollared ones). SourceID is nullable — uncollared (sourceless) pipes are symmetric many-to-many channels under a manifold.

Auto-provisioned pipes (stdin, stdout, stdctrl, inbox) are NOT stored here — they're derived from the source's kind and joined in at API response time.

func GetPipeByName

func GetPipeByName(ctx context.Context, p *Pool, sourceID uuid.UUID, name string) (Pipe, error)

GetPipeByName returns one pipe row or ErrNotFound.

func GetUncollaredPipeByName added in v0.57.0

func GetUncollaredPipeByName(ctx context.Context, p *Pool, accountID uuid.UUID, manifold, name string) (Pipe, error)

GetUncollaredPipeByName returns one sourceless pipe row addressed the uncollared way — (account, manifold, name) — or ErrNotFound. GetPipeByName only covers the collared shape (keyed on source_id), which uncollared pipes don't have.

func InsertPipe

func InsertPipe(ctx context.Context, p *Pool, accountID uuid.UUID, manifold string, sourceID *uuid.UUID, createdBy uuid.UUID, name string, ttl *int, maxMsgs *int, maxBytes *int64) (Pipe, error)

InsertPipe inserts a row. sourceID nil = uncollared (symmetric many-to-many pipe under the manifold); non-nil = collared under that source. The caller passes accountID explicitly because uncollared rows can't derive it from source.account_id. Retention overrides are NULL when the pointer arg is nil — the server provisions the JetStream stream with defaults.

func ListPipesForSource

func ListPipesForSource(ctx context.Context, p *Pool, sourceID uuid.UUID) ([]Pipe, error)

ListPipesForSource returns the user-creatable pipes for one source, sorted by name. Excludes auto-provisioned pipes (those aren't stored).

func ListUncollaredPipesForAccount added in v0.31.0

func ListUncollaredPipesForAccount(ctx context.Context, p *Pool, accountID uuid.UUID) ([]Pipe, error)

ListUncollaredPipesForAccount returns every uncollared pipe row in the account, sorted (manifold, name). Used by `ppz ls` to surface the sourceless rows that walking sources alone misses. Phase 1.5.

func UpsertPipeRetention added in v0.57.0

func UpsertPipeRetention(ctx context.Context, p *Pool, accountID uuid.UUID, manifold string, sourceID *uuid.UUID, createdBy uuid.UUID, name string, ttl *int, maxMsgs *int, maxBytes *int64) (Pipe, error)

UpsertPipeRetention stores retention for a pipe that may not have a row yet. This is what makes AUTO-PROVISIONED pipes (inbox, and stdin/stdout/stdctrl/system/heartbeat on pty sources) configurable: they're JetStream-only by design, so there was previously nowhere to persist an override — and they're precisely the pipes whose default caps users hit first.

Materialising a row rather than adding a parallel overrides table keeps one resolution path (nil column = default), and every reader already unions auto-pipe names with table rows through a set, so a materialised row does not double-list in `ppz ls` or the org page.

Distinct from InsertPipe because it must be reachable for reserved names, which InsertPipe's callers gate on. It is NOT a create path: callers verify the pipe exists (as a row or as an auto-pipe of the source) before calling.

type Pool

type Pool struct {
	*pgxpool.Pool
}

Pool is the public handle other packages use. It wraps pgxpool.Pool so the rest of the codebase doesn't import pgx directly.

func Open

func Open(ctx context.Context, url string) (*Pool, error)

type Schedule added in v0.51.0

type Schedule struct {
	ID              uuid.UUID
	AccountID       uuid.UUID
	Manifold        string
	SourceHandle    string
	Pipe            string
	Payload         string
	Sender          string
	Kind            string
	Spec            string
	TZ              string
	NextFireAt      time.Time
	LastFiredAt     *time.Time
	FailCount       int // consecutive failed fires; reset on success
	CreatedByUserID uuid.UUID
	CreatedAt       time.Time
	CreatorUsername string
}

Schedule is one live scheduled send. SourceHandle=="" targets an uncollared pipe at Manifold. Spec is display-shaped (RFC3339 for at, Go duration for every, cron expression for cron); CreatedAt anchors the interval grid for kind=every. LastFiredAt is nil until the first fire. CreatorUsername is join-filled by ListSchedules for the `schedule ls` CREATOR column (not a table column).

func ClaimDueSchedules added in v0.51.0

func ClaimDueSchedules(ctx context.Context, p *Pool, now time.Time, limit int) ([]Schedule, error)

ClaimDueSchedules atomically claims up to limit due rows (next_fire_at <= now): SKIP LOCKED against concurrent claimers, lease-bumped so the claim survives past the transaction. Returns the rows with their PRE-claim next_fire_at — the value the missfire policy (schedule.Decide) judges lateness against.

func InsertSchedule added in v0.51.0

func InsertSchedule(ctx context.Context, p *Pool, s Schedule) (Schedule, error)

InsertSchedule stores a new schedule. ID is stamped here; CreatedAt is honoured when set (it anchors kind=every's interval grid, so the handler passes the same instant it computed next_fire_at from) and stamped otherwise.

The CLI addresses schedules by ShortID (last 8 hex of the uuid), so a per-account suffix collision would make `schedule ls`/`rm` ambiguous. Astronomically unlikely (~n²/2³³), but free to prevent: regenerate the uuid when the suffix is already taken in the account.

func ListSchedules added in v0.51.0

func ListSchedules(ctx context.Context, p *Pool, accountID uuid.UUID) ([]Schedule, error)

ListSchedules returns one account's live schedules, soonest next_fire_at first, with CreatorUsername join-filled.

func (Schedule) ShortID added in v0.51.0

func (s Schedule) ShortID() string

ShortID returns the CLI-facing 8-char id: the last 8 hex of the row's uuid, matching `sent id=…`'s lastHex8 convention.

type Source

type Source struct {
	ID                   uuid.UUID
	AccountID            uuid.UUID
	CreatedByUserID      uuid.UUID // user that created the source (NOT NULL)
	Manifold             string    // hierarchical-grouping segment; ” = root (NOT NULL on the DB column)
	Handle               string
	Kind                 SourceKind
	CreatedAt            time.Time
	LastBroadcastAt      *time.Time
	LastBroadcastPayload *string
}

func GetSourceAt added in v0.59.0

func GetSourceAt(ctx context.Context, p *Pool, accountID uuid.UUID, manifold, handle string) (Source, error)

DeleteSource removes a source row. The pipes FK is ON DELETE CASCADE so pipe rows are removed automatically. JetStream stream cleanup is the caller's responsibility. Returns ErrNotFound when (org, handle) doesn't exist. GetSourceAt looks a source up by its full address. Handles are unique per (account, manifold), not per account, so this — not GetSourceByHandle — is the lookup for a caller that knows the manifold.

func GetSourceByHandle

func GetSourceByHandle(ctx context.Context, p *Pool, accountID uuid.UUID, handle string) (Source, error)

func InsertSource

func InsertSource(ctx context.Context, p *Pool, accountID, createdBy uuid.UUID, manifold, handle string, kind SourceKind) (Source, error)

InsertSource creates a row attributed to `createdBy` (NOT NULL on the table). Server callers stamp this from the API-key's CreatedByUserID (API path) or caller.UserID (OAuth path).

func ListSourcesForOrg

func ListSourcesForOrg(ctx context.Context, p *Pool, accountID uuid.UUID) ([]Source, error)

func (Source) IsAutoPipe added in v0.22.1

func (s Source) IsAutoPipe(name string) bool

IsAutoPipe reports whether name is an auto-provisioned pipe for this source kind (i.e. JetStream-only, not stored in the pipes table).

func (Source) Pipes

func (s Source) Pipes() []string

Pipes returns the pipe set for a source based on its kind. All sources have:

  • inbox: direct messages intended for this source/agent

pty sources also have:

  • stdin: input fed to the wrapped child via `ppz send`
  • stdout: byte-faithful capture of the PTY master's output (ANSI escapes intact); both `ppz read` and `ppz terminal view` consume this pipe.
  • stdctrl: control plane (resize/setsize events — device geometry).
  • system: session control plane — write-lease acquire/release requests (writer → host) and host-published lease-state events (host → observers). Distinct from stdctrl: stdctrl mutates the pty device, system coordinates who may write. See docs/WIRE.md.

`broadcast` was an auto-provisioned pipe pre-launch; it was removed in Phase 1 (locked decision #16) — teams now use explicit room pipes (`ppz pipe create team1.room` with --writers=anyone) for shared channels.

type SourceKind

type SourceKind string

SourceKind enumerates the supported source shapes.

"message" — default; two pipes: broadcast, inbox.
"pty"     — terminal source; broadcast, inbox, and terminal IO pipes.
const (
	SourceKindMessage SourceKind = "message"
	SourceKindPTY     SourceKind = "pty"
)

type User

type User struct {
	ID        uuid.UUID
	Username  string
	Email     string
	Mode      UserMode
	GitHubID  *int64 // nil for mode=internal users
	AvatarURL string
	CreatedAt time.Time
	// ServiceAccountID is the account a service account belongs to,
	// and nil for humans. The DB CHECK enforces the pairing; the
	// pointer is what makes "human with no owning org" representable.
	ServiceAccountID *uuid.UUID
}

func GetServiceAccount added in v0.58.0

func GetServiceAccount(ctx context.Context, p *Pool, accountID uuid.UUID, orgName, name string) (User, error)

GetServiceAccount resolves a bare name within an org.

func GetUser

func GetUser(ctx context.Context, p *Pool, id uuid.UUID) (User, error)

func GetUserByUsername

func GetUserByUsername(ctx context.Context, p *Pool, username string) (User, error)

func InsertServiceAccount added in v0.58.0

func InsertServiceAccount(ctx context.Context, p *Pool, accountID uuid.UUID, orgName, name string) (User, error)

InsertServiceAccount creates a service principal in the given org.

func InsertUser

func InsertUser(ctx context.Context, p *Pool, username, email string, mode UserMode) (User, error)

func ListMembers

func ListMembers(ctx context.Context, p *Pool, accountID uuid.UUID) ([]User, error)

ListMembers returns the non-owner members of an org, ordered by when they were added.

func ListServiceAccounts added in v0.58.0

func ListServiceAccounts(ctx context.Context, p *Pool, accountID uuid.UUID) ([]User, error)

ListServiceAccounts returns every service principal in the org.

func ResolvePrincipal added in v0.58.0

func ResolvePrincipal(ctx context.Context, p *Pool, accountID uuid.UUID, orgName, name string) (User, error)

ResolvePrincipal maps a name typed at the CLI to a principal in the account. Accepts a bare human username, a bare service-account name, or "@everyone".

func UpsertUserByGitHubID

func UpsertUserByGitHubID(ctx context.Context, p *Pool, githubID int64, username, email, avatarURL string) (User, bool, error)

UpsertUserByGitHubID inserts a brand new mode=github user, or updates the existing row matching the GitHub numeric id. Returns the resolved User row plus a bool indicating whether the row was freshly created (true) vs already existed (false). Callers use the bool to decide whether to auto-create the user's first org.

func (User) DisplayName added in v0.58.0

func (u User) DisplayName() string

DisplayName is the name every surface shows. Service accounts store an org-scoped username ("<org>/<name>") because users.username is globally unique; users see the bare name.

func (User) IsService added in v0.58.0

func (u User) IsService() bool

IsService reports whether this principal is a service account.

type UserMode

type UserMode string

UserMode = "github" (real OAuth identity) or "internal" (placeholder / seeded test user / pre-OAuth-era account).

const (
	UserModeGithub   UserMode = "github"
	UserModeInternal UserMode = "internal"
	// UserModeService is a service account — an agent's own identity,
	// distinct from the human who spawned it (ACL Phase 1). Key-only
	// auth, scoped to exactly one account.
	UserModeService UserMode = "service"
)

Jump to

Keyboard shortcuts

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