database

package
v0.0.56 Latest Latest
Warning

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

Go to latest
Published: Jul 10, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	FollowStatusPending  = "pending"
	FollowStatusAccepted = "accepted"
	FollowStatusRejected = "rejected"
)

Outgoing follow status constants.

Variables

View Source
var (
	ErrInvalidGlob      = errors.New("invalid tag glob")
	ErrFollowerNotFound = errors.New("follower not found")
)
View Source
var ErrPackageOwnerMismatch = errors.New("package is owned by another actor")
View Source
var ErrRepositoryBusy = errors.New("repository has open upload sessions")

ErrRepositoryBusy is returned when a repo-level delete finds unexpired upload sessions — a push is mid-flight and the delete must not race it.

View Source
var ErrRepositoryGone = errors.New("repository no longer exists")

ErrRepositoryGone means the parent packages row vanished between the push path's transactions (a repo-level delete won the race). Failing loudly here is what prevents a silently-lost push: the client retries, the retry recreates the repo, and the push lands.

PutManifestWithLayers and PutPackageTag guard against this with a SELECT EXISTS parent-exists check in the same transaction as the write. On SQLite that check is race-proof because BEGIN IMMEDIATE takes a global writer lock for the whole transaction. On Postgres, under the default READ COMMITTED isolation, that SELECT EXISTS takes no row lock and there is no FK from package_versions/package_tags to packages, so a concurrent repo delete can still commit between the check and the write there; Postgres-safe locking (e.g. SELECT ... FOR UPDATE or an FK) is a known follow-up, not a guarantee this code makes today.

Functions

This section is empty.

Types

type Activity

type Activity struct {
	bun.BaseModel `bun:"table:activities"`

	ID          int64     `bun:"id,pk,autoincrement"`
	ActivityID  string    `bun:"activity_id,notnull,unique"`
	Type        string    `bun:"type,notnull"`
	ActorURL    string    `bun:"actor_url,notnull"`
	ObjectJSON  []byte    `bun:"object_json,notnull"`
	PublishedAt time.Time `bun:"published_at,notnull,default:current_timestamp"`
	CreatedAt   time.Time `bun:"created_at,notnull,default:current_timestamp"`
}

type Actor added in v0.0.17

type Actor struct {
	bun.BaseModel `bun:"table:actors"`

	ID           int64   `bun:"id,pk,autoincrement" json:"id"`
	ActorURL     string  `bun:"actor_url,notnull,unique" json:"actor_url"`
	Name         *string `bun:"name" json:"name,omitempty"`
	Alias        *string `bun:"alias" json:"alias,omitempty"`
	Endpoint     string  `bun:"endpoint,notnull" json:"endpoint"`
	PublicKeyPEM *string `bun:"public_key_pem" json:"public_key_pem,omitempty"`

	// Inbound: they follow us
	TheyFollowUs   bool       `bun:"they_follow_us,notnull,default:false" json:"they_follow_us"`
	TheyFollowUsAt *time.Time `bun:"they_follow_us_at" json:"they_follow_us_at,omitempty"`

	// Outbound: we follow them
	WeFollowThem     bool       `bun:"we_follow_them,notnull,default:false" json:"we_follow_them"`
	WeFollowStatus   *string    `bun:"we_follow_status" json:"we_follow_status,omitempty"` // pending, accepted, rejected
	WeFollowAcceptAt *time.Time `bun:"we_follow_accept_at" json:"we_follow_accept_at,omitempty"`

	// Health & replication (for blob fetching)
	IsHealthy         bool       `bun:"is_healthy,notnull,default:true" json:"is_healthy"`
	ReplicationPolicy string     `bun:"replication_policy,notnull,default:'lazy'" json:"replication_policy"`
	LastSeenAt        *time.Time `bun:"last_seen_at" json:"last_seen_at,omitempty"`

	FederationTagGlobs *string `bun:"federation_tag_globs" json:"federation_tag_globs,omitempty"`

	CreatedAt time.Time `bun:"created_at,notnull,default:current_timestamp" json:"created_at"`
}

Actor represents a remote ActivityPub actor. Consolidates peers, follows, and outgoing_follows.

func (*Actor) GetPublicKeyPEM added in v0.0.17

func (a *Actor) GetPublicKeyPEM() string

func (*Actor) GetWeFollowStatus added in v0.0.17

func (a *Actor) GetWeFollowStatus() string

func (*Actor) HasAcceptedOutgoingFollow added in v0.0.17

func (a *Actor) HasAcceptedOutgoingFollow() bool

func (*Actor) HasPendingOrAcceptedOutgoingFollow added in v0.0.17

func (a *Actor) HasPendingOrAcceptedOutgoingFollow() bool

func (*Actor) HasPendingOutgoingFollow added in v0.0.17

func (a *Actor) HasPendingOutgoingFollow() bool

type Blob

type Blob struct {
	bun.BaseModel `bun:"table:blobs"`

	ID            int64     `bun:"id,pk,autoincrement"`
	Digest        string    `bun:"digest,notnull,unique"`
	SizeBytes     int64     `bun:"size_bytes,notnull"`
	MediaType     *string   `bun:"media_type"`
	StoredLocally bool      `bun:"stored_locally,notnull,default:false"`
	CreatedAt     time.Time `bun:"created_at,notnull,default:current_timestamp"`
}

type BlobReconcileRow added in v0.0.38

type BlobReconcileRow struct {
	Digest        string `bun:"digest"`
	StoredLocally bool   `bun:"stored_locally"`
}

type BlobRef added in v0.0.33

type BlobRef struct {
	Digest    string
	Size      int64
	MediaType *string
}

type DB

type DB struct {
	// contains filtered or unexported fields
}

func OpenPostgres

func OpenPostgres(dsn string, maxOpen, maxIdle int, logger *slog.Logger) (*DB, error)

OpenPostgres opens a PostgreSQL database with the given DSN.

func OpenSQLite

func OpenSQLite(dataDir string, maxOpen, maxIdle int, logger *slog.Logger) (*DB, error)

OpenSQLite opens a SQLite database in the given data directory.

func (*DB) AcceptFollowRequest

func (db *DB) AcceptFollowRequest(ctx context.Context, actorURL string) error

AcceptFollowRequest promotes a follow request to a follower.

func (*DB) AcceptOutgoingFollow

func (db *DB) AcceptOutgoingFollow(ctx context.Context, actorURL string) error

AcceptOutgoingFollow marks an outgoing follow as accepted.

func (*DB) AddFollow

func (db *DB) AddFollow(ctx context.Context, actorURL, publicKeyPEM, endpoint string, alias *string) error

AddFollow adds or updates a follower (promotes from follow request).

func (*DB) AddFollowRequest

func (db *DB) AddFollowRequest(ctx context.Context, actorURL, publicKeyPEM, endpoint string, alias *string) error

AddFollowRequest creates or updates a pending follow request.

func (*DB) AddOutgoingFollow

func (db *DB) AddOutgoingFollow(ctx context.Context, actorURL string) error

func (*DB) AllBlobDigests

func (db *DB) AllBlobDigests(ctx context.Context, pageSize int) (map[string]bool, error)

AllBlobDigests returns all blob digests known in the database, paging in batches of pageSize.

func (*DB) AllUploadSessionUUIDs added in v0.0.56

func (db *DB) AllUploadSessionUUIDs(ctx context.Context) ([]string, error)

AllUploadSessionUUIDs returns every session UUID, regardless of expiry.

func (*DB) BlobExistsInRepo added in v0.0.7

func (db *DB) BlobExistsInRepo(ctx context.Context, repoName string, digest string) (bool, error)

JOIN blobs disambiguates: package_files also records index→child manifest digests, which must not be served as blobs.

func (*DB) CleanupDeliveries

func (db *DB) CleanupDeliveries(ctx context.Context, olderThan time.Duration) (int64, error)

CleanupDeliveries removes completed/failed deliveries older than the given age.

func (*DB) CleanupStalePeerBlobs

func (db *DB) CleanupStalePeerBlobs(ctx context.Context, olderThan time.Duration) (int64, error)

CleanupStalePeerBlobs removes peer blob references not verified within the given duration.

func (*DB) Close

func (db *DB) Close() error

func (*DB) CountActivities

func (db *DB) CountActivities(ctx context.Context, actorURL string) (int, error)

CountActivities returns the total number of activities for the given actor.

func (*DB) CountFollows

func (db *DB) CountFollows(ctx context.Context) (int, error)

CountFollows returns the count of actors that follow us.

func (*DB) CountOutgoingFollows added in v0.0.9

func (db *DB) CountOutgoingFollows(ctx context.Context, status string) (int, error)

CountOutgoingFollows returns the count of actors we follow with the given status.

func (*DB) CountPeers added in v0.0.13

func (db *DB) CountPeers(ctx context.Context) (int, error)

CountPeers returns the count of actors known to the system.

func (*DB) CreateUploadSession

func (db *DB) CreateUploadSession(ctx context.Context, uuid string, repoID int64, ttl time.Duration) (*UploadSession, error)

func (*DB) DeleteActor added in v0.0.21

func (db *DB) DeleteActor(ctx context.Context, actorURL string) error

DeleteActor permanently removes the actor row for the given actorURL.

func (*DB) DeleteBlob

func (db *DB) DeleteBlob(ctx context.Context, digest string) error

func (*DB) DeleteManifest

func (db *DB) DeleteManifest(ctx context.Context, repoID int64, digest string) error

func (*DB) DeleteOwnedRepositoryWithBlobs added in v0.0.53

func (db *DB) DeleteOwnedRepositoryWithBlobs(ctx context.Context, repoID int64, ownerID string) (*RepoDeletion, error)

DeleteOwnedRepositoryWithBlobs deletes an OCI repository owned by ownerID: manifests, tags, files, the packages row, and any blob rows left unreferenced. Per-manifest tombstones are recorded in the SAME transaction, so a federation peer can never resurrect the deleted content (getManifest re-stores peer fetches unless IsManifestDeleted says otherwise).

The owner re-check, the open-upload-session check, and the delete all run in one immediate transaction: under BEGIN IMMEDIATE nothing can create a session or land a manifest between the checks and the delete. That guarantee is a SQLite property (the DSN sets _txlock=immediate, so BEGIN IMMEDIATE takes a single global writer lock for the transaction's lifetime). On Postgres, under the default READ COMMITTED isolation, these checks take no row locks, so a concurrent push can still interleave with this delete and land a manifest or tag the delete doesn't see — Postgres-safe locking (e.g. SELECT ... FOR UPDATE) is a known follow-up, not something this transaction enforces today.

Returns (nil, nil) if the repository does not exist, ErrPackageOwnerMismatch if it is not owned by ownerID, ErrRepositoryBusy if an unexpired upload session exists (a push is mid-flight).

func (*DB) DeletePackage added in v0.0.29

func (db *DB) DeletePackage(ctx context.Context, packageID int64) error

func (*DB) DeletePackageFile added in v0.0.27

func (db *DB) DeletePackageFile(ctx context.Context, versionID int64, filename string) error

func (*DB) DeletePackageTag added in v0.0.27

func (db *DB) DeletePackageTag(ctx context.Context, packageID int64, name string) error

func (*DB) DeletePackageVersion added in v0.0.27

func (db *DB) DeletePackageVersion(ctx context.Context, packageID int64, version string) error

DeletePackageVersion removes a version, its tags, and its files. Orphaned blobs are left for the GC sweep.

func (*DB) DeletePackageVersionWithBlobs added in v0.0.37

func (db *DB) DeletePackageVersionWithBlobs(ctx context.Context, packageID int64, version string) ([]string, error)

func (*DB) DeletePackageWithBlobs added in v0.0.37

func (db *DB) DeletePackageWithBlobs(ctx context.Context, packageID int64) ([]string, error)

DeletePackageWithBlobs returns digests whose blob rows it deleted; the caller removes the bytes from storage. Unlike GC, peer_blobs does not gate purge.

func (*DB) DeleteRepository added in v0.0.29

func (db *DB) DeleteRepository(ctx context.Context, repoID int64) error

func (*DB) DeleteStaleOutgoingFollows added in v0.0.14

func (db *DB) DeleteStaleOutgoingFollows(ctx context.Context, pendingTTL, rejectedTTL time.Duration) (int64, error)

DeleteStaleOutgoingFollows removes stale pending and rejected outgoing follows.

func (*DB) DeleteTag

func (db *DB) DeleteTag(ctx context.Context, repoID int64, name string) error

func (*DB) DeleteUploadSession

func (db *DB) DeleteUploadSession(ctx context.Context, uuid string) error

func (*DB) EnqueueDelivery

func (db *DB) EnqueueDelivery(ctx context.Context, activityID, inboxURL string, activityJSON []byte) error

EnqueueDelivery adds an activity delivery to the persistent queue.

func (*DB) EnqueueDeliveryInserted added in v0.0.47

func (db *DB) EnqueueDeliveryInserted(ctx context.Context, activityID, inboxURL string, activityJSON []byte) (bool, error)

EnqueueDeliveryInserted enqueues a delivery and reports whether a new row was actually inserted (false means it was already queued — a no-op), so callers don't count idempotent re-enqueues in metrics or trigger spurious wakeups.

func (*DB) ExecContext added in v0.0.30

func (db *DB) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)

ExecContext exposes raw SQL — used by tests for setup.

func (*DB) FindActorByInput added in v0.0.23

func (db *DB) FindActorByInput(ctx context.Context, input string) (*Actor, error)

FindActorByInput looks up an actor by: exact actor_url, alias, name, or endpoint domain.

func (*DB) FindFollowRequestByInput added in v0.0.24

func (db *DB) FindFollowRequestByInput(ctx context.Context, input string) (*FollowRequest, error)

FindFollowRequestByInput looks up a pending follow request by exact actor_url, alias, or endpoint domain. Used as a fallback when WebFinger returns a different URL than the one originally stored, or is unreachable.

func (*DB) FindPeersWithBlob

func (db *DB) FindPeersWithBlob(ctx context.Context, blobDigest string) ([]PeerBlob, error)

FindPeersWithBlob returns all peer blobs for a given digest from healthy actors.

func (*DB) FindRepoForBlob

func (db *DB) FindRepoForBlob(ctx context.Context, digest string) (string, error)

func (*DB) GetActivity

func (db *DB) GetActivity(ctx context.Context, activityID string) (*Activity, error)

func (*DB) GetActor added in v0.0.17

func (db *DB) GetActor(ctx context.Context, actorURL string) (*Actor, error)

GetActor retrieves an actor by URL.

func (*DB) GetBlob

func (db *DB) GetBlob(ctx context.Context, digest string) (*Blob, error)

func (*DB) GetFollow

func (db *DB) GetFollow(ctx context.Context, actorURL string) (*Actor, error)

GetFollow returns an actor that follows us.

func (*DB) GetFollowRequest

func (db *DB) GetFollowRequest(ctx context.Context, actorURL string) (*FollowRequest, error)

GetFollowRequest retrieves a pending follow request.

func (*DB) GetManifestByDigest

func (db *DB) GetManifestByDigest(ctx context.Context, repoID int64, digest string) (*Manifest, error)

func (*DB) GetManifestByTag

func (db *DB) GetManifestByTag(ctx context.Context, repoID int64, tag string) (*Manifest, error)

func (*DB) GetOrCreatePackage added in v0.0.27

func (db *DB) GetOrCreatePackage(ctx context.Context, pkgType, name, ownerID string) (*Package, error)

func (*DB) GetOrCreateRepository

func (db *DB) GetOrCreateRepository(ctx context.Context, name, ownerID string) (*Repository, error)

func (*DB) GetOutgoingFollow

func (db *DB) GetOutgoingFollow(ctx context.Context, actorURL string) (*Actor, error)

GetOutgoingFollow returns an actor we're following or have requested to follow.

func (*DB) GetPackage added in v0.0.27

func (db *DB) GetPackage(ctx context.Context, pkgType, name string) (*Package, error)

func (*DB) GetPackageByID added in v0.0.27

func (db *DB) GetPackageByID(ctx context.Context, id int64) (*Package, error)

func (*DB) GetPackageFile added in v0.0.27

func (db *DB) GetPackageFile(ctx context.Context, versionID int64, filename string) (*PackageFile, error)

func (*DB) GetPackageTag added in v0.0.27

func (db *DB) GetPackageTag(ctx context.Context, packageID int64, name string) (*PackageTag, error)

func (*DB) GetPackageVersion added in v0.0.27

func (db *DB) GetPackageVersion(ctx context.Context, packageID int64, version string) (*PackageVersion, error)

func (*DB) GetPackageVersionByTag added in v0.0.27

func (db *DB) GetPackageVersionByTag(ctx context.Context, packageID int64, tagName string) (*PackageVersion, error)

func (*DB) GetPeer

func (db *DB) GetPeer(ctx context.Context, actorURL string) (*Actor, error)

GetPeer retrieves an actor as a peer.

func (*DB) GetRepository

func (db *DB) GetRepository(ctx context.Context, name string) (*Repository, error)

func (*DB) GetTag

func (db *DB) GetTag(ctx context.Context, repoID int64, name string) (*Tag, error)

func (*DB) GetUploadSession

func (db *DB) GetUploadSession(ctx context.Context, uuid string) (*UploadSession, error)

func (*DB) HasPeerBlob added in v0.0.38

func (db *DB) HasPeerBlob(ctx context.Context, digest string) (bool, error)

func (*DB) InsertActivityIfNew added in v0.0.47

func (db *DB) InsertActivityIfNew(ctx context.Context, activityID, activityType, actorURL string, objectJSON []byte) (bool, error)

InsertActivityIfNew stores the activity for dedup and reports whether it was newly inserted. A false result means the activity already existed (a duplicate or replay), letting callers reject it durably — across restarts and concurrent requests — via the activity_id uniqueness constraint.

func (*DB) InsertPackageVersionIfNew added in v0.0.47

func (db *DB) InsertPackageVersionIfNew(ctx context.Context, v *PackageVersion) (bool, error)

InsertPackageVersionIfNew inserts a version only if (package_id, version) does not already exist, reporting whether it was newly inserted. Publish paths use it to enforce immutability atomically: a racing duplicate publish gets inserted=false instead of silently overwriting via the upsert.

func (*DB) IsBlobReferenced added in v0.0.38

func (db *DB) IsBlobReferenced(ctx context.Context, digest string) (bool, error)

func (*DB) IsManifestDeleted added in v0.0.9

func (db *DB) IsManifestDeleted(ctx context.Context, digest string) (bool, error)

func (*DB) IsPackageOwner added in v0.0.27

func (db *DB) IsPackageOwner(ctx context.Context, packageID int64, ownerID string) (bool, error)

func (*DB) IsRepositoryOwner

func (db *DB) IsRepositoryOwner(ctx context.Context, repoID int64, did string) (bool, error)

func (*DB) IsVersionDeleted added in v0.0.27

func (db *DB) IsVersionDeleted(ctx context.Context, pkgType, packageName, version string) (bool, error)

IsVersionDeleted: pass packageName="" to look up by version alone (OCI's digest-based tombstone), or a non-empty name to scope by (type, name).

func (*DB) ListActivitiesPage

func (db *DB) ListActivitiesPage(ctx context.Context, actorURL string, beforeID int64, limit int) ([]Activity, error)

ListActivitiesPage returns a page of activities with cursor-based pagination.

func (*DB) ListActors added in v0.0.17

func (db *DB) ListActors(ctx context.Context) ([]Actor, error)

ListActors returns all actors.

func (*DB) ListAllOutgoingFollows added in v0.0.14

func (db *DB) ListAllOutgoingFollows(ctx context.Context) ([]Actor, error)

ListAllOutgoingFollows returns all actors we follow regardless of status.

func (*DB) ListAllPeers

func (db *DB) ListAllPeers(ctx context.Context) ([]Actor, error)

ListAllPeers returns all actors (alias for health checking compatibility).

func (*DB) ListBlobsForReconcile added in v0.0.38

func (db *DB) ListBlobsForReconcile(ctx context.Context, startAfter string, limit int) ([]BlobReconcileRow, error)

func (*DB) ListExpiredUploadSessions added in v0.0.4

func (db *DB) ListExpiredUploadSessions(ctx context.Context, limit int) ([]string, error)

ListExpiredUploadSessions returns UUIDs of upload sessions that have passed their expiry time.

func (*DB) ListFollowRequests

func (db *DB) ListFollowRequests(ctx context.Context) ([]FollowRequest, error)

ListFollowRequests returns all pending follow requests.

func (*DB) ListFollowers added in v0.0.17

func (db *DB) ListFollowers(ctx context.Context) ([]Actor, error)

ListFollowers returns all actors that follow us.

func (*DB) ListFollowing added in v0.0.17

func (db *DB) ListFollowing(ctx context.Context) ([]Actor, error)

ListFollowing returns all actors we follow (accepted).

func (*DB) ListFollows

func (db *DB) ListFollows(ctx context.Context) ([]Actor, error)

ListFollows returns followers (alias for compatibility).

func (*DB) ListFollowsBatch

func (db *DB) ListFollowsBatch(ctx context.Context, afterID int64, limit int) ([]Actor, error)

ListFollowsBatch returns followers using cursor-based pagination.

func (*DB) ListFollowsPage

func (db *DB) ListFollowsPage(ctx context.Context, offset, limit int) ([]Actor, error)

ListFollowsPage returns followers with pagination.

func (*DB) ListHealthyActors added in v0.0.17

func (db *DB) ListHealthyActors(ctx context.Context) ([]Actor, error)

ListHealthyActors returns all actors marked as healthy.

func (*DB) ListLocallyHostedRepos added in v0.0.28

func (db *DB) ListLocallyHostedRepos(ctx context.Context) ([]RepoWithStats, error)

func (*DB) ListManifestsBySubject

func (db *DB) ListManifestsBySubject(ctx context.Context, repoID int64, subjectDigest string) ([]Manifest, error)

func (*DB) ListOCIPackagesForRetention added in v0.0.30

func (db *DB) ListOCIPackagesForRetention(ctx context.Context, startAfter string, limit int) ([]PackageRetention, error)

func (*DB) ListOutgoingFollows

func (db *DB) ListOutgoingFollows(ctx context.Context, status string) ([]Actor, error)

ListOutgoingFollows returns all actors we follow with the given status.

func (*DB) ListOutgoingFollowsBatch added in v0.0.47

func (db *DB) ListOutgoingFollowsBatch(ctx context.Context, status string, afterID int64, limit int) ([]Actor, error)

ListOutgoingFollowsBatch returns outgoing follows using keyset (id cursor) pagination so concurrent follow/remove doesn't shift the window and skip or duplicate entries under OFFSET paging.

func (*DB) ListOutgoingFollowsPage added in v0.0.9

func (db *DB) ListOutgoingFollowsPage(ctx context.Context, status string, limit, offset int) ([]Actor, error)

ListOutgoingFollowsPage returns actors we follow with pagination.

func (*DB) ListPackageFiles added in v0.0.27

func (db *DB) ListPackageFiles(ctx context.Context, versionID int64) ([]PackageFile, error)

func (*DB) ListPackageTags added in v0.0.27

func (db *DB) ListPackageTags(ctx context.Context, packageID int64) ([]PackageTag, error)

func (*DB) ListPackageTagsAfter added in v0.0.27

func (db *DB) ListPackageTagsAfter(ctx context.Context, packageID int64, startAfter string, limit int) ([]string, error)

func (*DB) ListPackageVersions added in v0.0.27

func (db *DB) ListPackageVersions(ctx context.Context, packageID int64) ([]PackageVersion, error)

func (*DB) ListPackageVersionsBySubject added in v0.0.27

func (db *DB) ListPackageVersionsBySubject(ctx context.Context, packageID int64, subjectDigest string) ([]PackageVersion, error)

func (*DB) ListPackages added in v0.0.27

func (db *DB) ListPackages(ctx context.Context, pkgType, startAfter string, limit int) ([]Package, error)

func (*DB) ListPackagesPendingWithdrawal added in v0.0.37

func (db *DB) ListPackagesPendingWithdrawal(ctx context.Context, pkgType string) ([]Package, error)

func (*DB) ListReposWithStats added in v0.0.13

func (db *DB) ListReposWithStats(ctx context.Context, query string) ([]RepoWithStats, error)

func (*DB) ListReposWithStatsPaginated added in v0.0.14

func (db *DB) ListReposWithStatsPaginated(ctx context.Context, query string, page, pageSize int) (*ReposPage, error)

func (*DB) ListRepositoriesAfter

func (db *DB) ListRepositoriesAfter(ctx context.Context, startAfter string, limit int) ([]Repository, error)

func (*DB) ListTagsAfter

func (db *DB) ListTagsAfter(ctx context.Context, repoID int64, startAfter string, limit int) ([]string, error)

func (*DB) ListTagsForRetention added in v0.0.30

func (db *DB) ListTagsForRetention(ctx context.Context, packageID int64) ([]TagForRetention, error)

func (*DB) ListTagsWithDetails added in v0.0.14

func (db *DB) ListTagsWithDetails(ctx context.Context, repoID int64, page, pageSize int) (*TagsPage, error)

func (*DB) ListUploadSessions added in v0.0.56

func (db *DB) ListUploadSessions(ctx context.Context) ([]UploadSession, error)

ListUploadSessions returns every current upload session, newest first.

func (*DB) MarkDelivered

func (db *DB) MarkDelivered(ctx context.Context, id int64) error

MarkDelivered marks a delivery as successfully completed.

func (*DB) MarkDeliveryFailed

func (db *DB) MarkDeliveryFailed(ctx context.Context, id int64, attempts, maxAttempts int, lastError string) error

MarkDeliveryFailed records a failed attempt and schedules retry with backoff.

func (*DB) MarkPackageWithdrawn added in v0.0.37

func (db *DB) MarkPackageWithdrawn(ctx context.Context, packageID int64) error

func (*DB) OrphanedBlobs

func (db *DB) OrphanedBlobs(ctx context.Context, limit int, createdBefore time.Time) ([]string, error)

peer_blobs gates only stored_locally=false rows (federation-redirect targets). Local bytes must not be pinned by remote-location hints. createdBefore protects in-flight uploads (row written, manifest commit not yet).

func (*DB) PendingDeliveries

func (db *DB) PendingDeliveries(ctx context.Context, limit int) ([]Delivery, error)

PendingDeliveries returns deliveries ready to be attempted, up to limit.

func (*DB) Ping

func (db *DB) Ping() error

func (*DB) PruneDeletedManifests added in v0.0.9

func (db *DB) PruneDeletedManifests(ctx context.Context, olderThan time.Duration) (int64, error)

func (*DB) PruneDeletedVersions added in v0.0.27

func (db *DB) PruneDeletedVersions(ctx context.Context, olderThan time.Duration) (int64, error)

func (*DB) PruneUntaggedManifests added in v0.0.30

func (db *DB) PruneUntaggedManifests(ctx context.Context, olderThan time.Duration, limit int) ([]UntaggedManifest, error)

PruneUntaggedManifests deletes OCI manifests older than olderThan that have no tag, no OCI referrer (subject), and no parent manifest (index child). Cascades package_files.

func (*DB) PutActivity

func (db *DB) PutActivity(ctx context.Context, activityID, activityType, actorURL string, objectJSON []byte) error

func (*DB) PutBlob

func (db *DB) PutBlob(ctx context.Context, digest string, sizeBytes int64, mediaType *string, storedLocally bool) error

func (*DB) PutBlobReferences added in v0.0.27

func (db *DB) PutBlobReferences(ctx context.Context, versionID int64, refs []BlobRef) error

func (*DB) PutManifest

func (db *DB) PutManifest(ctx context.Context, m *Manifest) error

func (*DB) PutManifestLayers

func (db *DB) PutManifestLayers(ctx context.Context, manifestID int64, refs []BlobRef) error

func (*DB) PutManifestWithLayers added in v0.0.47

func (db *DB) PutManifestWithLayers(ctx context.Context, m *Manifest, refs []BlobRef) error

PutManifestWithLayers stores the manifest and its blob references in a single transaction, so a stored manifest never coexists with missing package_files rows. Without this atomicity, the GC orphan-blob sweep could reap a layer that a just-stored manifest references but whose package_files row hasn't been written yet (the manifest and refs were previously separate writes).

func (*DB) PutPackageFile added in v0.0.27

func (db *DB) PutPackageFile(ctx context.Context, f *PackageFile) error

func (*DB) PutPackageTag added in v0.0.27

func (db *DB) PutPackageTag(ctx context.Context, packageID int64, name, version string) error

PutPackageTag upserts a tag, repointing it at version if it already exists. The parent-exists check runs in the same transaction so a tag can never be written for a package that a concurrent repo delete just removed.

func (*DB) PutPackageVersion added in v0.0.27

func (db *DB) PutPackageVersion(ctx context.Context, v *PackageVersion) error

func (*DB) PutPeerBlob

func (db *DB) PutPeerBlob(ctx context.Context, peerActor, blobDigest, peerEndpoint string) error

PutPeerBlob records that a peer has a blob.

func (*DB) PutTag

func (db *DB) PutTag(ctx context.Context, repoID int64, name, manifestDigest string) error

func (*DB) QueryContext

func (db *DB) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)

QueryContext exposes raw SQL — used by tests for assertions.

func (*DB) RecordDeletedManifest added in v0.0.9

func (db *DB) RecordDeletedManifest(ctx context.Context, digest, repoName, sourceActor string) error

func (*DB) RecordDeletedVersion added in v0.0.27

func (db *DB) RecordDeletedVersion(ctx context.Context, pkgType, packageName, version, sourceActor string) error

func (*DB) RefreshFollow added in v0.0.8

func (db *DB) RefreshFollow(ctx context.Context, actorURL, publicKeyPEM, endpoint string, alias *string) error

RefreshFollow updates actor-derived fields for an existing follower.

func (*DB) RefreshFollowRequest added in v0.0.8

func (db *DB) RefreshFollowRequest(ctx context.Context, actorURL, publicKeyPEM, endpoint string, alias *string) error

RefreshFollowRequest updates actor-derived fields for a pending follow request.

func (*DB) RefreshOutgoingFollow added in v0.0.24

func (db *DB) RefreshOutgoingFollow(ctx context.Context, actorURL, publicKeyPEM, endpoint string, alias *string) error

RefreshOutgoingFollow updates actor-derived fields for an actor we follow. Intended for the periodic refresh of outgoing-only peers (where they don't follow us, so RefreshFollow's WHERE clause doesn't match).

func (*DB) RejectFollowRequest

func (db *DB) RejectFollowRequest(ctx context.Context, actorURL string) error

RejectFollowRequest deletes a pending follow request.

func (*DB) RejectOutgoingFollow

func (db *DB) RejectOutgoingFollow(ctx context.Context, actorURL string) error

RejectOutgoingFollow marks an outgoing follow as rejected.

func (*DB) RemoveFollow

func (db *DB) RemoveFollow(ctx context.Context, actorURL string) error

RemoveFollow removes an inbound follower.

func (*DB) RemoveOutgoingFollow

func (db *DB) RemoveOutgoingFollow(ctx context.Context, actorURL string) error

RemoveOutgoingFollow removes an outgoing follow.

func (*DB) SetActorHealth added in v0.0.17

func (db *DB) SetActorHealth(ctx context.Context, actorURL string, healthy bool) error

SetActorHealth updates the health status of an actor.

func (*DB) SetBlobStoredLocally added in v0.0.38

func (db *DB) SetBlobStoredLocally(ctx context.Context, digest string, stored bool) error

func (*DB) SetPackagePrivate added in v0.0.27

func (db *DB) SetPackagePrivate(ctx context.Context, id int64, private bool) error

func (*DB) SetPeerHealth

func (db *DB) SetPeerHealth(ctx context.Context, actorURL string, healthy bool) error

SetPeerHealth updates the health status of an actor (alias for compatibility).

func (*DB) SetPeerHealthByDomain added in v0.0.9

func (db *DB) SetPeerHealthByDomain(ctx context.Context, domain string, healthy bool) error

SetPeerHealthByDomain updates is_healthy for all actors whose endpoint hostname matches. Matches endpoints like https://domain/..., https://domain:port/..., and https://domain (no path).

func (*DB) SetRepositoryPrivate added in v0.0.10

func (db *DB) SetRepositoryPrivate(ctx context.Context, id int64, private bool) error

func (*DB) UnhealthyPeerDomains added in v0.0.9

func (db *DB) UnhealthyPeerDomains(ctx context.Context) ([]string, error)

UnhealthyPeerDomains returns the hostnames of all unhealthy actors.

func (*DB) UpdateFollowFilter added in v0.0.30

func (db *DB) UpdateFollowFilter(ctx context.Context, actorURL string, tagGlobs []string) error

UpdateFollowFilter sets the follower's federation_tag_globs. Empty list clears it.

func (*DB) UploadSessionUUIDsByRepo added in v0.0.56

func (db *DB) UploadSessionUUIDsByRepo(ctx context.Context, repoID int64) ([]string, error)

UploadSessionUUIDsByRepo returns every session UUID for a repository, regardless of expiry (the recovery path must clear stale rows too).

func (*DB) UpsertActor added in v0.0.17

func (db *DB) UpsertActor(ctx context.Context, a *Actor) error

UpsertActor inserts or updates an actor.

func (*DB) UpsertPeer

func (db *DB) UpsertPeer(ctx context.Context, actorURL, endpoint string, name *string, replicationPolicy string, isHealthy bool) error

UpsertPeer inserts or updates an actor as a peer (for blob replication).

type DeletedVersion added in v0.0.27

type DeletedVersion struct {
	bun.BaseModel `bun:"table:deleted_versions"`

	ID          int64     `bun:"id,pk,autoincrement"`
	PackageType string    `bun:"package_type,notnull"`
	PackageName string    `bun:"package_name,notnull"`
	Version     string    `bun:"version,notnull"`
	SourceActor string    `bun:"source_actor,notnull"`
	DeletedAt   time.Time `bun:"deleted_at,notnull,default:current_timestamp"`
}

DeletedVersion tombstones a deleted version so federation cannot re-create it. OCI uses a digest-only lookup; other backends key by (type, name).

type Delivery

type Delivery struct {
	bun.BaseModel `bun:"table:delivery_queue"`

	ID            int64     `bun:"id,pk,autoincrement"`
	ActivityID    string    `bun:"activity_id,notnull"`
	InboxURL      string    `bun:"inbox_url,notnull"`
	ActivityJSON  []byte    `bun:"activity_json,notnull"`
	Attempts      int       `bun:"attempts,notnull,default:0"`
	MaxAttempts   int       `bun:"max_attempts,notnull,default:10"`
	NextAttemptAt time.Time `bun:"next_attempt_at,notnull,default:current_timestamp"`
	LastError     *string   `bun:"last_error"`
	Status        string    `bun:"status,notnull,default:'pending'"`
	CreatedAt     time.Time `bun:"created_at,notnull,default:current_timestamp"`
}

type FollowRequest

type FollowRequest struct {
	bun.BaseModel `bun:"table:follow_requests"`

	ID           int64     `bun:"id,pk,autoincrement"`
	ActorURL     string    `bun:"actor_url,notnull,unique"`
	PublicKeyPEM string    `bun:"public_key_pem,notnull"`
	Endpoint     string    `bun:"endpoint,notnull"`
	Alias        *string   `bun:"alias"`
	RequestedAt  time.Time `bun:"requested_at,notnull,default:current_timestamp"`
}

type Manifest

type Manifest struct {
	ID            int64
	RepositoryID  int64
	Digest        string
	MediaType     string
	SizeBytes     int64
	Content       []byte
	SourceActor   *string
	SubjectDigest *string
	ArtifactType  *string
	CreatedAt     time.Time
}

Manifest is an OCI-shaped DTO over package_versions (Digest=Version, Content=Metadata).

type Package added in v0.0.27

type Package struct {
	bun.BaseModel `bun:"table:packages"`

	ID                    int64      `bun:"id,pk,autoincrement"`
	Type                  string     `bun:"type,notnull"`
	Name                  string     `bun:"name,notnull"`
	OwnerID               string     `bun:"owner_id,notnull"`
	Private               bool       `bun:"private,notnull,default:false"`
	CreatedAt             time.Time  `bun:"created_at,notnull,default:current_timestamp"`
	FederationWithdrawnAt *time.Time `bun:"federation_withdrawn_at"`
}

Package: (Type, Name) is unique. Name format is backend-specific ("foo.com/myapp" for OCI, "@scope/foo" for npm, "com.example:lib" for Maven).

type PackageFile added in v0.0.27

type PackageFile struct {
	bun.BaseModel `bun:"table:package_files"`

	ID          int64     `bun:"id,pk,autoincrement"`
	VersionID   int64     `bun:"version_id,notnull"`
	Filename    string    `bun:"filename,notnull"`
	BlobDigest  string    `bun:"blob_digest,notnull"`
	SizeBytes   int64     `bun:"size_bytes,notnull"`
	ContentType *string   `bun:"content_type"`
	CreatedAt   time.Time `bun:"created_at,notnull,default:current_timestamp"`
}

PackageFile attaches a blob to a version. For OCI Filename == BlobDigest.

type PackageRetention added in v0.0.30

type PackageRetention struct {
	ID      int64
	Name    string
	OwnerID string
}

type PackageTag added in v0.0.27

type PackageTag struct {
	bun.BaseModel `bun:"table:package_tags"`

	ID        int64     `bun:"id,pk,autoincrement"`
	PackageID int64     `bun:"package_id,notnull"`
	Name      string    `bun:"name,notnull"`
	Version   string    `bun:"version,notnull"`
	UpdatedAt time.Time `bun:"updated_at,notnull,default:current_timestamp"`
}

PackageTag points a name to a version string. Version is denormalized (not an FK) to match the prior OCI tag→digest semantics.

type PackageVersion added in v0.0.27

type PackageVersion struct {
	bun.BaseModel `bun:"table:package_versions"`

	ID            int64     `bun:"id,pk,autoincrement"`
	PackageID     int64     `bun:"package_id,notnull"`
	Version       string    `bun:"version,notnull"`
	Metadata      []byte    `bun:"metadata"`
	MediaType     string    `bun:"media_type,notnull,default:''"`
	SizeBytes     int64     `bun:"size_bytes,notnull,default:0"`
	SourceActor   *string   `bun:"source_actor"`
	SubjectDigest *string   `bun:"subject_digest"`
	ArtifactType  *string   `bun:"artifact_type"`
	CreatedAt     time.Time `bun:"created_at,notnull,default:current_timestamp"`
}

PackageVersion's Version is the backend's identifier (digest for OCI, semver for npm, GAV.V for Maven). Metadata holds the canonical bytes for backends that need them (the manifest body for OCI). MediaType/SizeBytes describe Metadata. SubjectDigest/ArtifactType implement OCI referrers.

type PeerBlob

type PeerBlob struct {
	bun.BaseModel `bun:"table:peer_blobs"`

	ID             int64      `bun:"id,pk,autoincrement"`
	PeerActor      string     `bun:"peer_actor,notnull"`
	BlobDigest     string     `bun:"blob_digest,notnull"`
	PeerEndpoint   string     `bun:"peer_endpoint,notnull"`
	LastVerifiedAt *time.Time `bun:"last_verified_at"`
}

type RepoDeletion added in v0.0.53

type RepoDeletion struct {
	Name            string
	ManifestDigests []string
	TagNames        []string
	PurgedBlobs     []string
}

RepoDeletion reports what a repo-level delete removed.

type RepoWithStats added in v0.0.13

type RepoWithStats struct {
	ID        int64
	Name      string
	OwnerID   string
	Tags      []string
	SizeBytes int64
	UpdatedAt time.Time
}

type ReposPage added in v0.0.14

type ReposPage struct {
	Repos      []RepoWithStats
	TotalCount int
	Page       int
	PageSize   int
	TotalPages int
}

type Repository

type Repository struct {
	ID        int64
	Name      string
	OwnerID   string
	Private   bool
	CreatedAt time.Time
}

Repository is an OCI-shaped DTO over the packages table (type='oci').

type Tag

type Tag struct {
	ID             int64
	RepositoryID   int64
	Name           string
	ManifestDigest string
	UpdatedAt      time.Time
}

Tag is an OCI-shaped DTO over package_tags (ManifestDigest=Version).

type TagForRetention added in v0.0.30

type TagForRetention struct {
	Name      string
	UpdatedAt time.Time
}

type TagWithDetails added in v0.0.14

type TagWithDetails struct {
	Name            string
	Digest          string
	MediaType       string
	ArtifactType    *string
	SizeBytes       int64
	UpdatedAt       time.Time
	ManifestContent []byte
}

type TagsPage added in v0.0.14

type TagsPage struct {
	Tags       []TagWithDetails
	TotalCount int
	Page       int
	PageSize   int
	TotalPages int
}

type UntaggedManifest added in v0.0.30

type UntaggedManifest struct {
	PackageID   int64
	PackageName string
	OwnerID     string
	Digest      string
}

type UploadSession

type UploadSession struct {
	bun.BaseModel `bun:"table:upload_sessions"`

	ID            int64     `bun:"id,pk,autoincrement"`
	UUID          string    `bun:"uuid,notnull,unique"`
	RepositoryID  int64     `bun:"repository_id,notnull"`
	BytesReceived int64     `bun:"bytes_received,notnull,default:0"`
	CreatedAt     time.Time `bun:"created_at,notnull,default:current_timestamp"`
	ExpiresAt     time.Time `bun:"expires_at,notnull"`
}

Jump to

Keyboard shortcuts

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