service

package
v1.10.0 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2026 License: MIT Imports: 16 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 service orchestrates use cases. It depends on domain and on small interfaces it declares for the infrastructure it needs. The concrete adapters live in internal/storage and are wired in cmd/hostthisd.

Index

Constants

View Source
const DefaultCreateAdmissionWidth = 2

DefaultCreateAdmissionWidth is the number of same-identity creates admitted to the metadata commit concurrently (docs/SPEC.md "Same-identity create admission: a width-2 gate"). Width 2 leaves a lone create, plus one overlapping follower, fully concurrent so the common case pays nothing. The cap matters because N same-owner commits contending at a CAS boundary amplify each other's retries (every loser re-runs its commit), so the concurrency is bounded before the storage tier rather than inside it.

Variables

View Source
var (
	// ErrRoomNotFound: the room OR the key is missing. HTTP 404, the
	// existence-not-leaked shape.
	ErrRoomNotFound = errors.New("service: room not found")
	// ErrRoomCreateRateLimited: HTTP 429. *RoomRateLimit's Scope says whether
	// the per-IP or the per-app limit tripped.
	ErrRoomCreateRateLimited = errors.New("service: room creation rate limit reached")
	// ErrRoomDataCap: the write would exceed the per-room cap. HTTP 413; the
	// prior value is intact.
	ErrRoomDataCap = errors.New("service: room is at its data cap")
	// ErrAppRoomsCap: the per-app aggregate cap is hit. HTTP 507.
	ErrAppRoomsCap = errors.New("service: app room storage is at capacity")
)

Sentinels the HTTP layer maps to status codes. Service-layer errors, so the HTTP handler never imports storage's sentinels for the room cases.

View Source
var ErrCompressedTooLarge = errors.New("service: upload exceeds 10 MiB compressed cap")

ErrCompressedTooLarge is returned when the input compressed under zstd to more than MaxPasteBytes.

View Source
var ErrDeployFailed = errors.New("service: site deploy failed")

ErrDeployFailed is the generic site-deploy failure for an unexpected backend error the deploy path cannot translate to a specific cause. Defensive: the pre-claim stages files under the manifest's own shard, so a cross-shard bind should never fire. If a routing regression makes one surface, this keeps the raw backend sentinel out of the SSH client's output; the operator sees the real error in the logs.

View Source
var ErrEmptyOwner = errors.New("service: anonymous - add an ssh key for this command")

ErrEmptyOwner is returned when an operation requires an identified owner and the caller is anonymous.

View Source
var ErrEmptySite = errors.New("service: archive contains no files")

ErrEmptySite is returned when an archive safe-untars to zero files.

View Source
var ErrInvalidName = errors.New("service: name must be 1–60 printable Unicode chars, no newlines")

ErrInvalidName is returned by Rename when the name violates the length / unicode rules.

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

ErrNotFound is returned when a paste / version doesn't exist. An owner-gated read of a slug owned by someone else maps here too, so existence never leaks to outsiders.

View Source
var ErrNotOwner = errors.New("service: not the paste owner")

ErrNotOwner is returned by an owner-gated operation when the requesting identity doesn't match the paste's. The SSH/HTTP surfaces map it to 403.

View Source
var ErrOverQuota = fmt.Errorf("service: would exceed your %d MiB total quota; delete a paste to free space", domain.UserQuotaBytes>>20)
View Source
var ErrRawTooLarge = errors.New("service: upload too large to consider (raw input exceeded 100 MiB cap)")

ErrRawTooLarge is returned when the raw input exceeded the fast-fail cap. The server stopped reading before any compression check could run.

View Source
var ErrServiceFull = errors.New("service: service is at capacity, try again later")

ErrServiceFull is the graceful translation of storage.ErrServiceFull: the object store rejected a blob Put because the bucket is at its configured hard quota (SPEC "Limits -> Durable total-bytes ceiling: an object-store quota").

View Source
var ErrSlugTaken = errors.New("service: slug taken (after retries)")

ErrSlugTaken is returned when the internal slug re-mint retry budget is exhausted.

View Source
var ErrSybilRateLimit = errors.New("service: too many new keys from this network today")

ErrSybilRateLimit is the sentinel for a subnet past its fresh-key allowance. Prefer errors.As on *SybilRefusal (which still matches errors.Is against this) to surface cap usage and when the next slot frees up.

View Source
var ErrVersionAlreadyDeleted = errors.New("service: version already deleted")

ErrVersionAlreadyDeleted is returned when the target version is already a tombstone. The caller chooses soft success or hard error.

View Source
var ErrVersionCurrentlyServed = errors.New("service: version is currently served by the URL; pin a different version first")

ErrVersionCurrentlyServed is returned when the target version is the one the URL serves. Freeing it requires `pin` to a different version, or `unpin`.

Functions

This section is empty.

Types

type ArchiveAdapter added in v0.95.0

type ArchiveAdapter struct{ Deployer *DeploySite }

ArchiveAdapter presents DeploySite as the upload service's ArchiveDeployer, so one Create call handles both cardinalities and no transport has to know there are two services behind it.

It exists only while the two services are separate. When they merge it goes away with them - it maps the multi-file result onto the shared Result rather than converting between two lasting shapes.

func (ArchiveAdapter) Deploy added in v0.95.0

func (a ArchiveAdapter) Deploy(body io.Reader, owner string) (Result, error)

type ArchiveDeployer added in v0.95.0

type ArchiveDeployer interface {
	Deploy(body io.Reader, owner string) (Result, error)
}

ArchiveDeployer is the multi-file half of an upload, injected so Create can own the whole decision rather than leaving it to the transport.

It is a PORT, not the concrete deploy service: upload does not import it, so the two can be merged without a circular dependency and the transport keeps one entry point either way (docs/SPEC.md "One paste, not two aggregates").

type BlobHandle added in v0.45.0

type BlobHandle struct {
	// Slug + SHA identify the staged blob on the standalone path. The field
	// set is internal to the seam and may grow without affecting callers,
	// which only ever pass handles back into Commit.
	Slug string
	SHA  string

	// Ref is the opaque, implementation-private staged-blob reference the
	// transactional shale path threads from Stage/StageStream into Commit. It
	// holds a cluster.BlobRef, typed as any so the service package stays free
	// of the shale/cluster dependency and its cgo/slatedb build tag. The
	// standalone path leaves it nil.
	Ref any
}

BlobHandle is the opaque token Stage / StageStream return and Commit consumes. Only handles a Stage call produced are valid to Commit; a zero BlobHandle is meaningless to the seam.

type BlobStore

type BlobStore interface {
	Put(sha string, r io.Reader, size int64) error
	PutPrecompressed(sha string, body []byte) error

	// EncodeBody encodes UNCOMPRESSED bytes into the store's at-rest format and
	// reports the payload size EXCLUDING the framing prefix: the basis quota
	// charges. Declared here so a caller needing the on-disk footprint asks the
	// component that owns the format instead of redoing the framing arithmetic.
	EncodeBody(r io.Reader) (body []byte, payloadSize int, err error)
}

BlobStore writes and reads content-addressed bytes. Put's size is required by S3-shaped backends to set Content-Length; the disk impl accepts it for interface uniformity. PutPrecompressed takes a body that is already magic-prefixed + zstd-encoded, so the streaming upload path does not re-encode its staging buffer.

type BlobUnit added in v0.45.0

type BlobUnit interface {
	// BeginUpload takes ownership of a slug's staged bytes and returns a
	// context carrying it, which the caller MUST use for the staging and the
	// Commit that follow.
	//
	// It exists because recovery may reclaim an upload it believes died, and
	// the writer may not have: ownership is what lets the commit detect that it
	// was taken over and abort, instead of binding metadata to bytes recovery
	// is deleting. An adapter with no such hazard returns ctx unchanged.
	//
	// Called ONCE, before the first Stage. Claiming later than the first staged
	// byte leaves those bytes outside the ownership the commit checks.
	BeginUpload(ctx context.Context, slug string) (context.Context, error)

	// Stage durably writes a record's blob from an ALREADY magic+zstd-encoded
	// in-memory body. Used by the single-file paste/version paths, whose
	// streaming pipeline has already produced the encoded staging buffer.
	// Metadata-first ordering (for the pending model) is the caller's choice
	// of when to Stage relative to its metadata write.
	Stage(ctx context.Context, slug, sha string, body []byte) (BlobHandle, error)
	// StagePrecompressed stages bytes that are ALREADY in the at-rest format,
	// streaming them from r rather than taking them whole. size is the exact
	// encoded length, which lets the object store pick a sane part size - an
	// unknown length makes it allocate a full multipart part buffer instead.
	StagePrecompressed(ctx context.Context, slug, sha string, r io.Reader, size int64) (BlobHandle, error)

	// StageEncoding encodes UNCOMPRESSED bytes into the adapter's at-rest
	// format, stages them, and reports the quota-relevant compressed size.
	//
	// It exists so a caller needing the on-disk footprint (the site deploy,
	// which charges the post-compression size against quota) does not have to
	// know the encoder or the framing. The adapter owns the format; the port
	// reports the number.
	StageEncoding(ctx context.Context, slug string, r io.Reader) (BlobHandle, string, int, error)

	// StageStream durably writes a record's blob by streaming r
	// (UNCOMPRESSED; the storage layer compresses at rest). size is the
	// expected uncompressed length.
	//
	// NO production caller: the site deploy stages through StageEncoding,
	// which also reports the compressed size it charges against quota. Both
	// adapters implement StageStream and their own tests cover it, but a
	// service reaching for it here would be the first to travel that path.
	StageStream(ctx context.Context, slug, sha string, r io.Reader, size int64) (BlobHandle, error)

	// Commit persists a record's metadata AND binds every staged handle as ONE
	// unit. On the standalone path Stage already wrote the bytes durably, so
	// the bind is a no-op and Commit just runs metaWrite. On the transactional
	// shale path Commit binds the handles in the SAME transaction metaWrite's
	// writes commit in.
	//
	// metaWrite receives a context.Context, NOT the ambient one: the shale
	// path derives a per-Commit child context carrying THIS call's staged
	// refs, so the metadata write binds exactly this call's blobs even when
	// two same-slug Commits run concurrently. The closure MUST thread the
	// context it is given into the repo's metadata-write method; passing a
	// different context silently drops the binds.
	//
	// metaWrite is the source of truth for slug-collision retries and quota
	// errors: Commit returns its error verbatim.
	Commit(ctx context.Context, handles []BlobHandle, metaWrite func(context.Context) error) error

	// Read streams a record's blob bytes, DECOMPRESSED, with the inner
	// (stored) byte length. The caller MUST Close the returned reader.
	Read(ctx context.Context, slug, sha string) (io.ReadCloser, int64, error)

	// UnbindOnDelete removes a record's blob references as part of the
	// record's metadata delete. On the standalone path this is a NO-OP: the
	// bytes are content-addressed and reclaimed by the global sweep once no
	// live record references their sha, so a delete never removes bytes
	// directly. It exists so the services delete uniformly across backends.
	UnbindOnDelete(ctx context.Context, slug string, shas []string) error

	// IsTransactional reports whether this unit binds a record's blob inside
	// the SAME transaction the metadata commits in, so a Stage->Commit makes
	// the row and its bytes visible together.
	//
	// It is the one place a service path varies by backend capability:
	// Upload.Create uses it to choose between READY-direct (no pending window,
	// no finalizer) and the detached-store pending/finalizer model (PENDING
	// row first, bytes in the background, then flip to ready). A transactional
	// unit MUST honor the bind metaWrite threads off the Commit context. See
	// docs/SPEC.md "Pending-collapse: a shale-collocated paste commits READY
	// directly".
	IsTransactional() bool
}

BlobUnit is the per-record blob lifecycle seam: stage the bytes, commit them alongside the record's metadata, read them back, unbind them on delete, WITHOUT exposing the storage mechanism. Both the standalone detached-store path and the transactional shale path satisfy it, so upload / manage / deploy_site / http-read run against ONE shape regardless of backend.

The "record" is a paste or a site, identified by its slug. A blob is identified within a record by its content sha. The seam maps (slug, sha) to an opaque BlobHandle the commit threads through; the services never inspect a handle's internals.

The domain stays pure: BlobUnit and BlobHandle live in the service layer, the implementations in internal/storage, and the domain types never reference a handle.

type CacheInvalidating added in v0.51.0

type CacheInvalidating struct {
	PasteManager
	// contains filtered or unexported fields
}

CacheInvalidating decorates a PasteManager with CDN cache invalidation, firing the purger after a SUCCESSFUL mutation that changes the bytes served at a paste's public URL (Update / Delete / Pin / Unpin). Verbs that do NOT change served bytes are delegated untouched through the embedded interface, so no purge fires; that includes DeleteVersion, which is refused outright for the currently-served version.

The inner verb service holds no CachePurger and makes no purge calls: that is the point of composing invalidation here at the edge.

The purge is best-effort. PurgePaste errors are swallowed (the mutation already succeeded on origin, and the impl logs internally), so a transient CDN issue never turns a successful update or delete into a failure.

func (*CacheInvalidating) Delete added in v0.51.0

func (c *CacheInvalidating) Delete(slug domain.Slug, owner string) error

Delete purges even on error, unlike its siblings. A failed update leaves the cached bytes correct; a failed delete may not, because the removal can land and the call still report an error, and the edge would then serve deleted content until max-age expires. Purging a paste that survived is harmless, so the ambiguous case resolves toward purging.

The pre-mutation rejections are excluded, and that exclusion is load-bearing: without it, attempting to delete a slug you do not own would purge it, letting any caller spend the CDN's finite purge budget on paste they have no rights to.

func (*CacheInvalidating) Pin added in v0.51.0

func (c *CacheInvalidating) Pin(slug domain.Slug, owner string, verNum int) (domain.Version, error)

func (*CacheInvalidating) Unpin added in v0.51.0

func (c *CacheInvalidating) Unpin(slug domain.Slug, owner string) error

func (*CacheInvalidating) Update added in v0.51.0

func (c *CacheInvalidating) Update(slug domain.Slug, owner string, body io.Reader, typeHint string) (UpdateResult, error)

type CachePurger

type CachePurger interface {
	PurgePaste(slug domain.Slug) error
}

CachePurger drops a paste's cached representations from a CDN edge.

The caller names only the slug; the implementation owns which URL variants that slug is reachable at (the page plus the markdown shell's "?raw=1" content fetch) and purges all of them.

A purge is best-effort: the CacheInvalidating decorator swallows the returned error so a transient CDN issue never blocks the mutation that triggered it. Implementations still return it so it stays testable.

type CreateAdmission added in v0.67.0

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

CreateAdmission is a per-key counting semaphore: each key admits at most `width` concurrent holders, further acquirers for the SAME key queue (no FIFO fairness guarantee), and distinct keys are fully independent. An entry exists only while its key has holders or waiters, so idle keys hold no memory.

The gate is generic; the create path keys it by owning identity via GateCreates.

func NewCreateAdmission added in v0.67.0

func NewCreateAdmission(width int) *CreateAdmission

NewCreateAdmission returns a gate admitting `width` concurrent holders per key. Widths below 1 clamp to 1: a zero-width gate deadlocks every acquirer.

func (*CreateAdmission) Acquire added in v0.67.0

func (a *CreateAdmission) Acquire(key string) (release func())

Acquire admits the caller for key, blocking while `width` holders are already inside. The caller must invoke the returned release when it leaves the gated section; extra calls are no-ops.

type DeleteVersionResult added in v0.42.0

type DeleteVersionResult struct {
	VerNum     int
	FreedBytes int
}

DeleteVersionResult reports what DeleteVersion did so the SSH layer can format messaging like "deleted v2. freed 187.3k.".

type DeploySite added in v0.44.0

type DeploySite struct {
	Sites  SiteRepo
	Pastes PasteByteSummer
	Blob   BlobUnit
	Now    func() time.Time
	// Logger records outcomes the caller never sees: the compensating release
	// of a pre-claimed slug runs on the way out of a failed deploy and its own
	// failure must not replace the deploy's error. nil discards.
	Logger *log.Logger
}

DeploySite is the application service for a static-site upload. It safe-untars the archive, stores each file as a content-addressed blob, builds the manifest, and persists the Site, enforcing the per-identity quota BOTH mid-untar (the decompression-bomb guard) AND at persistence time (the atomic check in InsertWithQuotaCheck).

func NewDeploySite added in v0.44.0

func NewDeploySite(sites SiteRepo, pastes PasteByteSummer, blob BlobUnit) *DeploySite

NewDeploySite wires defaults.

func (*DeploySite) Delete added in v0.52.1

func (d *DeploySite) Delete(slug domain.Slug, owner string) error

Delete removes an owned static site by slug. A non-site slug and a foreign-owned site both collapse to ErrNotFound, the same sentinel the paste-delete path returns, so existence and ownership never leak.

func (*DeploySite) Deploy added in v0.44.0

func (d *DeploySite) Deploy(body io.Reader, owner string) (SiteResult, error)

Deploy reads a gzip-tar archive from body, untars it safely, stores the files, and persists a new Site owned by owner.

body is the SAME live stream a single-file upload reads, consumed once mid-untar, so peak memory is one file at a time (buffered to hash + compress before the blob write), never the whole inflated archive.

Returns:

  • domain.ErrUnsupportedKind: not a valid gzip-tar, or holds no web content
  • ErrOverQuota: the archive expands past the owner's remaining quota, caught mid-untar by the decompression-bomb guard or at persistence time by the atomic check
  • ErrTooManyFiles-family errors surfaced verbatim via domain

func (*DeploySite) DeployToSlug added in v0.44.0

func (d *DeploySite) DeployToSlug(slug domain.Slug, body io.Reader, owner string) (SiteResult, error)

DeployToSlug re-deploys a SITE at an existing owned slug in place. Same pipeline as Deploy, but it targets slug instead of minting one and charges the REPLACE DELTA against the owner's quota rather than the full new size.

A slug that is not a site, or is a site owned by someone else, returns ErrNotFound: the same shape any not-found yields, so a non-owner cannot probe which slugs exist or who owns them. The mid-untar budget EXCLUDES this site's current deduped bytes, so a same-size re-deploy has the same headroom the original deploy did; ReplaceWithQuotaCheck applies the precise delta atomically.

Returns:

  • ErrEmptyOwner: anonymous / empty identity
  • ErrNotFound: slug is not a site owned by owner
  • domain.ErrUnsupportedKind / domain.ErrNoWebContent: not web content
  • ErrOverQuota / ErrServiceFull: over the per-identity / service cap
  • ErrEmptySite: the archive safe-untars to zero files

func (*DeploySite) ListSites added in v0.59.0

func (d *DeploySite) ListSites(owner string) ([]domain.Site, error)

ListSites returns the owner's active static sites. Anonymous / empty owners get an empty list: only keyed identities own content.

type KeyGate

type KeyGate struct {
	Repo                  KeyGateRepo
	MaxFreshKeysPerSubnet int
	Window                time.Duration
	Now                   func() time.Time
}

KeyGate gates new SSH sessions: a fresh (identity, ip-subnet) pair is admitted only if the subnet has not already first-seen more than MaxFreshKeysPerSubnet distinct fingerprints within Window. An already-recorded pair passes through with no accounting.

The SSH server calls Admit once per session, before any verb dispatch.

There is no background prune. Rows leave when a read that already walks them notices they are out of window, which keeps the family bounded by the subnets still connecting rather than by every subnet that ever did (see docs/SPEC.md "Sybil rate limit").

func NewKeyGate

func NewKeyGate(repo KeyGateRepo) *KeyGate

NewKeyGate wires the documented defaults: 20 fresh / 24h.

func (*KeyGate) Admit

func (g *KeyGate) Admit(identity, ipSubnet string) error

Admit gates one session. Both identity and ipSubnet must be non-empty. On refusal returns *SybilRefusal (which is also errors.Is(ErrSybilRateLimit)).

func (*KeyGate) Inspect added in v0.44.0

func (g *KeyGate) Inspect(identity, ipSubnet string) (SessionInfo, error)

Inspect returns the rollup KeyGate state for an admitted session. It runs after Admit and never gates admission.

type KeyGateRepo

type KeyGateRepo interface {
	// AdmitNewKey is the atomic check: returns knownAlready=true if
	// (identity, subnet) is already on file (no rate-limit accounting),
	// or admits + records a fresh key when subnet hasn't hit
	// `limitPerSubnet` distinct new fingerprints in the window.
	AdmitNewKey(identity, subnet string, now time.Time, limitPerSubnet int, window time.Duration) (knownAlready bool, err error)

	// SubnetSnapshot returns how many rows from this subnet count toward the
	// per-subnet cap, and the earliest in-window first_seen: adding `window`
	// to it gives the moment the next slot frees up. A subnet with no
	// in-window rows returns (0, time.Time{}).
	//
	// Implementations MAY drop the out-of-window rows they walk past. Nothing
	// reads them again: they are outside the window, so no admission decision
	// can turn on them.
	SubnetSnapshot(subnet string, now time.Time, window time.Duration) (freshCount int, oldestFirstSeen time.Time, err error)

	// SubnetsForIdentity returns how many distinct subnets this identity has
	// in-window rows for: the count of networks its key is grandfathered on.
	SubnetsForIdentity(identity string, now time.Time, window time.Duration) (int, error)
}

KeyGateRepo is the persistence interface backing the per-IP-subnet Sybil rate limit. internal/storage.KeyGateRepo satisfies it.

type Manage

type Manage struct {
	// Sniff classifies bytes for DetectKind's text-only rule. A PORT
	// (domain.MIMESniffer).
	Sniff   domain.MIMESniffer
	Repo    PasteAdmin
	Blob    BlobUnit // Show (ReadAll), Update (Stage+Commit), Delete (UnbindOnDelete)
	KeyGate *KeyGate // optional; populates WhoamiInfo.Session when set
	Now     func() time.Time
}

Manage is the verb-level service. Each method maps to one ssh verb (or HTTP endpoint) and is owner-gated.

func NewManage

func NewManage(repo PasteAdmin, blob BlobUnit) *Manage

func (*Manage) Delete

func (m *Manage) Delete(slug domain.Slug, owner string) error

Delete removes a paste and its versions (FK cascade). A delete whose paste row is already gone but whose slug lingers in the caller's own index heals that residue and succeeds (docs/SPEC.md "Delete heals its own lost tail").

func (*Manage) DeleteVersion added in v0.42.0

func (m *Manage) DeleteVersion(slug domain.Slug, owner string, verNum int) (DeleteVersionResult, error)

DeleteVersion frees a single version's blob bytes (tombstones the row). Refused when:

  • paste doesn't exist or owner doesn't match → ErrNotFound
  • target version doesn't exist → ErrNotFound
  • target is already tombstoned → ErrVersionAlreadyDeleted
  • target is the version the URL currently serves → ErrVersionCurrentlyServed

The freed byte count is the row's pre-deletion size column.

func (*Manage) List

func (m *Manage) List(owner string) ([]domain.Paste, error)

List returns the owner's pastes.

func (*Manage) Pin

func (m *Manage) Pin(slug domain.Slug, owner string, verNum int) (domain.Version, error)

Pin sets which version_num the public URL serves and makes it sticky, so later `update`s do not bump it. Only Update does that.

func (*Manage) Rename

func (m *Manage) Rename(slug domain.Slug, owner, name string) error

Rename sets the human label. Empty string clears it.

func (*Manage) Show

func (m *Manage) Show(slug domain.Slug, owner string) (domain.Paste, io.ReadCloser, error)

Show streams the bytes + paste metadata for owner-controlled read. The caller MUST Close the reader.

It streams rather than buffering because the bytes it serves are the DECOMPRESSED document, which can be an order of magnitude larger than the compressed per-paste cap that bounds everything else; buffering made this the largest allocation the service could be asked for (docs/SPEC.md "Reads are constant-memory too").

func (*Manage) Unpin

func (m *Manage) Unpin(slug domain.Slug, owner string) error

Unpin clears a sticky pin, reverting the URL to "always serve the latest version".

func (*Manage) Update

func (m *Manage) Update(slug domain.Slug, owner string, body io.Reader, typeHint string) (UpdateResult, error)

Update appends a new version to an existing slug. On an UNPINNED paste (the default) the new version also becomes the served one; on a PINNED paste the pin holds and the new version is recorded but not served.

func (*Manage) Versions

func (m *Manage) Versions(slug domain.Slug, owner string) ([]domain.Version, error)

Versions returns the slug's full history (newest first), including tombstoned rows, which the `versions` verb renders with a `deleted` marker.

func (*Manage) Whoami

func (m *Manage) Whoami(owner, subnet string) (WhoamiInfo, error)

Whoami populates WhoamiInfo for an owner (key fingerprint). An empty subnet, or a nil KeyGate, leaves the session fields zero.

type PasteAdmin

type PasteAdmin interface {
	Get(domain.Slug) (domain.Paste, error)
	ListByOwner(owner string) ([]domain.Paste, error)
	// Delete and SetName take the caller-authorized paste identity + CreatedAt
	// so the storage layer can re-check them INSIDE its {slug} transaction: the
	// service ownership check runs outside any transaction, so a delete+re-mint
	// of the same slug in the window would otherwise let the op hit a different
	// paste. CreatedAt is immutable per paste, so it names the exact instance.
	Delete(slug domain.Slug, wantIdentity domain.Identity, wantCreatedAt time.Time) error
	SetName(slug domain.Slug, name string, wantIdentity domain.Identity, wantCreatedAt time.Time) error
	SetPinnedVersion(domain.Slug, domain.Version) error
	Unpin(domain.Slug) error
	AppendVersionWithQuotaCheck(ctx context.Context, slug domain.Slug, kind domain.ContentKind, contentSHA string, size int, userCap int64, now time.Time) (domain.AppendResult, error)
	ListVersions(domain.Slug) ([]domain.Version, error)
	GetVersion(domain.Slug, int) (domain.Version, error)
	// IsVersionServed reports whether ver is the version the URL serves,
	// decided from the authoritative head + rows (never a disposable read
	// cache), so the delete guard below can never free the served blob.
	IsVersionServed(domain.Slug, int) (bool, error)
	DeleteVersion(domain.Slug, int) error
	CountByOwner(owner string) (int, error)
	SumActiveBytesByOwner(owner string, now time.Time) (int, error)
	OwnerFirstSeen(owner string) (time.Time, error)
	// OwnerSummary is whoami's roll-up in one call: count + first-seen +
	// paste bytes + site bytes. The used total is PasteBytes + SiteBytes,
	// so a repo whose site bytes already live in the paste sum reports
	// SiteBytes zero.
	OwnerSummary(owner string, now time.Time) (domain.OwnerSummary, error)
	// DropStaleOwnerEntry removes slug from owner's OWN index (both the
	// owner-doc entry and the enumeration row, in one guarded write) when
	// the authoritative paste row is ABSENT and the entry is old enough to
	// be residue rather than a mid-insert: the leftovers a crash between
	// Delete's two transactions strands. When a paste row exists - any
	// owner - or the entry is young, it drops nothing and reports false,
	// so callers keep existence collapsed to not-found. TRUE means the
	// guarded drop was ATTEMPTED against the stamp it captured; a
	// stamp-changing race makes the write a no-op, which a later delete
	// retries. A repo whose delete cannot strand such residue satisfies
	// this by always reporting false.
	DropStaleOwnerEntry(slug domain.Slug, owner string) (bool, error)
}

PasteAdmin is the persistence interface for everything except "create a new paste". internal/storage.PasteRepo satisfies it.

type PasteByteSummer added in v0.44.0

type PasteByteSummer interface {
	SumActiveBytesByOwner(owner string, now time.Time) (int, error)
}

PasteByteSummer is the slice of the paste repo the deploy path needs for its remaining-budget computation. internal/storage.PasteRepo satisfies it.

type PasteManager added in v0.51.0

type PasteManager interface {
	List(owner string) ([]domain.Paste, error)
	Show(slug domain.Slug, owner string) (domain.Paste, io.ReadCloser, error)
	Update(slug domain.Slug, owner string, body io.Reader, typeHint string) (UpdateResult, error)
	Rename(slug domain.Slug, owner, name string) error
	Delete(slug domain.Slug, owner string) error
	Versions(slug domain.Slug, owner string) ([]domain.Version, error)
	DeleteVersion(slug domain.Slug, owner string, verNum int) (DeleteVersionResult, error)
	Pin(slug domain.Slug, owner string, verNum int) (domain.Version, error)
	Unpin(slug domain.Slug, owner string) error
	Whoami(owner, subnet string) (WhoamiInfo, error)
}

PasteManager is the verb-level surface the SSH layer consumes. Exposing an interface rather than the concrete *Manage is what lets cache invalidation be a decorator the composition root layers on, invisible to callers and to the verb service itself.

func NewCacheInvalidating added in v0.51.0

func NewCacheInvalidating(inner PasteManager, purger CachePurger) PasteManager

NewCacheInvalidating wraps inner so its mutating verbs also purge the CDN. A nil purger means no CDN in front and returns inner unwrapped, so the composition root can call this unconditionally.

type PasteRepo

type PasteRepo interface {
	InsertWithQuotaCheck(ctx context.Context, p domain.Paste, userCap int64, now time.Time) error
	Get(domain.Slug) (domain.Paste, error)
	// MarkReady / MarkFailed advance a still-PENDING paste only (MarkFailed
	// also releases its reservation), so a late finalizer cannot resurrect a
	// reconciler-failed paste; both no-op on a missing or non-pending paste.
	// docs/SPEC.md "Paste lifecycle status".
	MarkReady(domain.Slug) error
	MarkFailed(domain.Slug) error
}

PasteRepo is the persistence interface the upload service needs. internal/storage.PasteRepo satisfies it.

func GateCreates added in v0.67.0

func GateCreates(repo PasteRepo, gate *CreateAdmission) PasteRepo

GateCreates wraps repo so create commits are admitted through gate, keyed by the paste's owning identity.

type Result

type Result struct {
	Paste domain.Paste
}

Result is what Create produced, for the SSH and HTTP layers to format.

type RoomRateLimit added in v0.44.0

type RoomRateLimit struct {
	Scope  string // "ip" or "app"
	Window time.Duration
}

RoomRateLimit enriches ErrRoomCreateRateLimited with the scope that tripped and the window, so the HTTP layer can set a Retry-After. errors.Is(err, ErrRoomCreateRateLimited) holds.

func (*RoomRateLimit) Error added in v0.44.0

func (e *RoomRateLimit) Error() string

func (*RoomRateLimit) Is added in v0.44.0

func (e *RoomRateLimit) Is(target error) bool

type RoomRepo added in v0.44.0

type RoomRepo interface {
	// CreateRoom records a new empty room + its creation-accounting row,
	// enforcing the per-app aggregate cap. ErrSlugTaken if (app, id)
	// collides (caller retries); domain.ErrAppRoomsFull past the app cap.
	CreateRoom(room domain.Room, subnet string, appCap int64, now time.Time) error
	// GetRoom returns the room record or domain.ErrNotFound.
	GetRoom(appSlug domain.Slug, id domain.RoomID) (domain.Room, error)
	// GetValue returns one value or domain.ErrNotFound.
	GetValue(appSlug domain.Slug, id domain.RoomID, key string) ([]byte, error)
	// ScanRoom returns the whole namespace, stamped with the EXACT per-room
	// sequence the snapshot reflects (RoomKV.Seq): every mutation with
	// seq <= Seq is in the state, none with seq > Seq is. The relay's
	// late-join splice contract rides this fence.
	ScanRoom(appSlug domain.Slug, id domain.RoomID) (domain.RoomKV, error)
	// PutValue writes one value, enforcing the per-room + per-app caps and
	// bumping the room's clock, and returns the mutation's assigned
	// per-room sequence: dense, +1 per committed mutation, assigned inside the
	// same transaction that commits the value (SPEC "The per-room sequence:
	// assignment at commit"). domain.ErrNotFound if the room is gone,
	// domain.ErrRoomDataFull / domain.ErrAppRoomsFull on caps. Rooms hold no
	// blobs, so this path touches no object-store quota and has no
	// service-wide byte cap.
	PutValue(appSlug domain.Slug, id domain.RoomID, key string, val []byte, appCap int64, now time.Time) (uint64, error)
	// DeleteValue removes one value (idempotent) and resets the clock,
	// returning the assigned per-room sequence (an absent-key delete still
	// commits a touch, so it still assigns one).
	DeleteValue(appSlug domain.Slug, id domain.RoomID, key string, now time.Time) (uint64, error)
	// CountRoomCreates returns in-window creation counts (perSubnet, perApp)
	// for the room-creation rate limit.
	CountRoomCreates(appSlug domain.Slug, subnet string, now time.Time, window time.Duration) (perSubnet, perApp int, err error)
}

RoomRepo is the persistence contract the Rooms service needs, declared here rather than in storage so the service layer owns it (as with PasteRepo / SiteRepo / SweepRepo / KeyGateRepo). internal/storage.RoomKVRepo satisfies it.

type Rooms added in v0.44.0

type Rooms struct {
	Repo RoomRepo

	// Tunables, defaulted by NewRooms; main can override from flags/env.
	MaxRoomsPerIP  int           // per source-IP-subnet creation cap per CreateWindow
	MaxRoomsPerApp int           // per app creation cap per CreateWindow
	CreateWindow   time.Duration // rolling window for the creation limits
	PerAppByteCap  int64         // per-app aggregate byte cap (0 = unlimited)

	Now func() time.Time
}

Rooms is the application service for the no-auth room persistence tier (SPEC.md "Rooms (app persistence)"): room creation under the per-IP + per-app rate limit, and the KV verbs. It carries no I/O of its own; the repo is the only adapter.

func NewRooms added in v0.44.0

func NewRooms(repo RoomRepo) *Rooms

NewRooms wires the SPEC defaults: 60 rooms/IP-subnet/hour, 300 rooms/app/hour, 64 MiB per-app aggregate.

func (*Rooms) Create added in v0.44.0

func (s *Rooms) Create(appSlug domain.Slug, subnet string) (domain.Room, error)

Create mints a fresh UUIDv4 and creates an empty room under appSlug, after checking the per-IP-subnet AND per-app creation rate limits. subnet is the canonical /24 (IPv4) or /48 (IPv6) the request came from, the same shape the SSH Sybil gate uses.

On rate-limit returns *RoomRateLimit (also errors.Is ErrRoomCreateRateLimited). On per-app aggregate full returns ErrAppRoomsCap.

The rate-limit count is read OUTSIDE the CreateRoom transaction, making the creation gate a SOFT bound: N concurrent creators can each observe the same in-window count and all pass before their accounting rows commit, slightly overshooting the cap. Accepted for a coarse abuse bound; the hard bounds are the per-app aggregate and service-wide byte caps, enforced inside the tx.

func (*Rooms) Delete added in v0.44.0

func (s *Rooms) Delete(appSlug domain.Slug, id domain.RoomID, key string) (uint64, error)

Delete removes key (idempotent) and bumps the room's clock, returning the assigned per-room sequence. An absent-key delete still commits and so still assigns one: a seq bump with no mirror frame would read as a permanent hole to a relay subscriber. ErrRoomNotFound only when the ROOM does not exist; deleting an absent key in a real room is a success. key must already be validated.

func (*Rooms) Get added in v0.44.0

func (s *Rooms) Get(appSlug domain.Slug, id domain.RoomID, key string) ([]byte, error)

Get returns one value from a room. The room-existence check makes a missing ROOM and a missing KEY both surface as ErrRoomNotFound, the 404 that does not leak room existence. key must already be validated by the caller.

func (*Rooms) Put added in v0.44.0

func (s *Rooms) Put(appSlug domain.Slug, id domain.RoomID, key string, val []byte) (uint64, error)

Put writes val under key and returns the mutation's assigned per-room sequence, the dense counter the relay stamps onto the live mirror frame. Returns ErrRoomNotFound if the room is gone, ErrRoomDataCap (413) on the per-room cap, ErrAppRoomsCap (507) on the per-app aggregate. key must already be validated by the caller.

func (*Rooms) Scan added in v0.44.0

func (s *Rooms) Scan(appSlug domain.Slug, id domain.RoomID) (domain.RoomKV, error)

Scan returns the room's whole namespace. A scan of a nonexistent room is a 404, not an empty 200, so existence is not leaked the other way either.

type SessionInfo added in v0.44.0

type SessionInfo struct {
	Subnet           string // canonical /24 or /48 the session came from
	SubnetFreshCount int    // current rows in this subnet's window
	SubnetCap        int    // configured limit per subnet
	IdentitySubnets  int    // distinct subnets this identity has rows for
}

SessionInfo is the per-session keygate state surfaced by `whoami`. Zero values are acceptable.

type SiteRepo added in v0.44.0

type SiteRepo interface {
	InsertWithQuotaCheck(ctx context.Context, s domain.Site, storedBytes int, userCap int64, now time.Time) error
	// ReplaceWithQuotaCheck re-deploys an EXISTING owned site in place,
	// atomically swapping its manifest for s.Manifest under the same
	// serializable boundary InsertWithQuotaCheck uses. s.Slug names the
	// target; s.Identity is the connecting key.
	//
	//   - A slug that is not a site, and a site owned by another identity,
	//     both return domain.ErrNotFound: the same sentinel a missing slug
	//     yields, so "not yours" is indistinguishable from "does not exist".
	//   - The quota check is the REPLACE DELTA, evaluated against
	//     (existing_owned - old_deduped + storedBytes) in the SAME critical
	//     section as the swap, so a same-size re-deploy does not
	//     double-count and a smaller one frees the diff. ErrServiceFull /
	//     ErrOverUserQuota on overflow.
	//   - On success manifest, deduped_size and updated_at are replaced from
	//     s; slug and created_at are unchanged. One transaction: the URL serves the old
	//     manifest until it lands, the new one immediately after.
	ReplaceWithQuotaCheck(ctx context.Context, s domain.Site, storedBytes int, userCap int64, now time.Time) error
	Get(domain.Slug) (domain.Site, error)
	// Delete removes a site by slug. The caller-authorized identity + CreatedAt
	// are threaded so the storage layer re-checks them inside its {slug}
	// transaction: the service ownership check is outside any transaction, so a
	// delete+re-mint of the slug by another identity in the window would
	// otherwise let this delete destroy the new owner's paste.
	Delete(slug domain.Slug, wantIdentity domain.Identity, wantCreatedAt time.Time) error
	// SumActiveBytesByOwner returns the identity's active SITE bytes. The
	// deploy path adds the paste-side sum to compute the budget the untar may
	// fill before the persistence-time check.
	SumActiveBytesByOwner(owner string, now time.Time) (int64, error)
	// ListSitesByOwner returns the identity's active sites so the SSH `list`
	// verb can show them alongside pastes: a site counts against the shared
	// quota, so without this it silently consumes quota the owner can neither
	// see nor free.
	ListSitesByOwner(owner string, now time.Time) ([]domain.Site, error)
	// PreClaimSlug stakes a metadata-only single-shard claim on slug BEFORE
	// the deploy consumes the one-shot untar stream, so a transactional blob
	// path can stage every file under slug's shard and the manifest and blob
	// pointers co-route to the SAME shard at commit. It is a cheap existence
	// claim, NOT a blob reservation: no two-store coupling, no quota charge.
	// Returns domain.ErrSlugTaken if slug is already a paste or a site, so the
	// caller re-mints and re-claims before reading the body.
	//
	// On the standalone blob path the slug routes no blob, so this is a no-op
	// returning nil and the caller mints in the post-untar insert retry loop
	// where the authoritative insert is the collision authority.
	PreClaimSlug(ctx context.Context, slug domain.Slug, owner string, now time.Time) error
}

SiteRepo is the persistence interface the site-deploy + site-read services need. internal/storage.SiteRepo satisfies it.

type SiteResult added in v0.44.0

type SiteResult struct {
	Site domain.Site
}

SiteResult is what Deploy produced for the SSH layer to format.

type SlugClaimReleaser added in v0.81.0

type SlugClaimReleaser interface {
	ReleaseSlugClaim(ctx context.Context, slug domain.Slug, owner string) error
}

SlugClaimReleaser is the compensating half of SiteRepo.PreClaimSlug: it drops a claim no record was committed under, so a deploy that aborts after staking one (unreadable archive, no web content, a failed commit) does not remove the slug from the namespace for good. The claim is durable and no other path undoes it.

Optional rather than part of SiteRepo: a backend whose PreClaimSlug is a no-op has nothing to release, and the deploy path skips the compensation when the repo does not implement this.

An implementation MUST NOT drop a claim a paste or site was actually committed under, and MUST be a no-op on an absent or foreign claim so a repeated release is harmless.

type StandaloneBlobUnit added in v0.45.0

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

StandaloneBlobUnit adapts the detached content-addressed blob store (a *storage.CompressedBlobStore) to the BlobUnit seam. Bytes are durable the moment Stage/StageStream returns, so the ordering is blob-first and Commit has nothing to bind.

func NewStandaloneBlobUnit added in v0.45.0

func NewStandaloneBlobUnit(store interface {
	BlobStore
	blobReadStore
}) *StandaloneBlobUnit

NewStandaloneBlobUnit wraps a content-addressed blob store as a BlobUnit.

func (*StandaloneBlobUnit) BeginUpload added in v0.97.0

func (u *StandaloneBlobUnit) BeginUpload(ctx context.Context, _ string) (context.Context, error)

BeginUpload is a no-op on the standalone path: its Stage writes bytes that are immediately durable and content-addressed, so there is no staged-but- unowned window for a recovery to reclaim and therefore nothing to fence.

func (*StandaloneBlobUnit) Commit added in v0.45.0

func (u *StandaloneBlobUnit) Commit(ctx context.Context, _ []BlobHandle, metaWrite func(context.Context) error) error

Commit runs the record's metadata write. The staged bytes are already durable, so there is nothing to bind: Commit returns metaWrite's error verbatim, preserving the caller's slug-collision / quota error handling.

func (*StandaloneBlobUnit) IsTransactional added in v0.45.0

func (u *StandaloneBlobUnit) IsTransactional() bool

IsTransactional is false: the bytes land in a detached store with no co-commit, so Upload.Create keeps the pending/finalizer model on this path (commit a PENDING row, write the bytes in the background, flip to ready).

func (*StandaloneBlobUnit) Read added in v0.45.0

Read streams the decompressed bytes for sha. slug is unused: blobs are keyed by content sha alone.

func (*StandaloneBlobUnit) Stage added in v0.45.0

func (u *StandaloneBlobUnit) Stage(_ context.Context, slug, sha string, body []byte) (BlobHandle, error)

Stage writes the precompressed body and returns its (slug, sha) handle.

func (*StandaloneBlobUnit) StageEncoding added in v0.75.0

func (u *StandaloneBlobUnit) StageEncoding(ctx context.Context, slug string, r io.Reader) (BlobHandle, string, int, error)

func (*StandaloneBlobUnit) StagePrecompressed added in v1.0.0

func (u *StandaloneBlobUnit) StagePrecompressed(ctx context.Context, slug, sha string, r io.Reader, _ int64) (BlobHandle, error)

StageEncoding implements BlobUnit for the standalone path, on the same contract as the transactional adapter: encode to the at-rest format, stage it, report the compressed size excluding the framing prefix. StagePrecompressed reads the body whole. This is the local dev/test store, writing to a disk it owns, and its Put takes a slice - it carries none of the multi-node blob plane's constraints.

func (*StandaloneBlobUnit) StageStream added in v0.45.0

func (u *StandaloneBlobUnit) StageStream(_ context.Context, slug, sha string, r io.Reader, size int64) (BlobHandle, error)

StageStream streams r (uncompressed) into the store, which compresses it at rest, and returns the (slug, sha) handle.

func (*StandaloneBlobUnit) UnbindOnDelete added in v0.45.0

func (u *StandaloneBlobUnit) UnbindOnDelete(_ context.Context, _ string, _ []string) error

UnbindOnDelete is a no-op: the global content-addressed sweep reclaims blobs no live record references, so a delete never removes bytes directly.

type SybilRefusal added in v0.44.0

type SybilRefusal struct {
	Subnet               string
	Cap                  int
	FreshCountInWindow   int
	OldestEntryFirstSeen time.Time
	Window               time.Duration
}

SybilRefusal enriches ErrSybilRateLimit with what the SSH layer needs for a self-diagnosing message: which subnet, how full the cap is, and when the oldest in-window entry ages out.

func (*SybilRefusal) Error added in v0.44.0

func (e *SybilRefusal) Error() string

func (*SybilRefusal) Is added in v0.44.0

func (e *SybilRefusal) Is(target error) bool

func (*SybilRefusal) NextSlotFreesAt added in v0.44.0

func (e *SybilRefusal) NextSlotFreesAt() time.Time

NextSlotFreesAt returns when the oldest in-window entry ages out and frees a slot. Zero time if there are none.

type UpdateResult

type UpdateResult struct {
	Paste     domain.Paste
	NewVer    int
	WasPinned bool
	PinnedAt  int // ver_num of the still-served version if WasPinned
}

UpdateResult tells the SSH layer whether the paste was pinned at update time, in which case the new version was saved but is not being served.

type Upload

type Upload struct {
	Repo PasteRepo
	// Blob is the per-record blob lifecycle seam (Stage/Commit/Read/
	// UnbindOnDelete). On the standalone path the metadata row commits first
	// and the finalizer Stages the bytes in the background.
	Blob BlobUnit
	Now  func() time.Time
	// Sniff is the port DetectKind's text-only rule calls: the domain owns the
	// rule, an adapter supplies the algorithm. Overridable so a test can drive
	// a branch without hunting for bytes that sniff a particular way.
	Sniff domain.MIMESniffer
	// Archive handles the multi-file shape. nil disables archive uploads, which
	// is what a deploy with no site support wants.
	Archive ArchiveDeployer

	// Logger records background-finalize outcomes: the blob write runs after
	// Create returned the URL, so a failure there cannot reach the caller.
	// nil discards.
	Logger *log.Logger

	// SyncBlob makes Create commit the row READY and write the blob INLINE on
	// the ack path, skipping the pending/MarkReady flip. A BENCHMARK TOGGLE
	// (env HOSTTHIS_BLOB_SYNC) for A/B-ing sync against async on one binary,
	// not a production mode.
	SyncBlob bool
	// contains filtered or unexported fields
}

Upload is the application service for new paste creation.

func NewUpload

func NewUpload(repo PasteRepo, blob BlobUnit) *Upload

NewUpload wires defaults.

func (*Upload) Create

func (u *Upload) Create(body io.Reader, owner string, name string, typeHint string) (Result, error)

Create persists a new paste owned by owner, a "key:<fp>" identity built from the uploader's ssh public key fingerprint. That identity gates quota: its active pastes plus this body cannot exceed UserQuotaBytes.

body is consumed in a single streaming pass (hash + compress + count, peak memory ~MaxPasteBytes), and type detection runs on the captured 512-byte prefix so the source is never re-read. Unsupported types return domain.ErrUnsupportedKind for the caller to surface verbatim.

func (*Upload) WaitFinalize added in v0.44.0

func (u *Upload) WaitFinalize()

WaitFinalize blocks until every background finalize this Upload started has completed, so a graceful shutdown does not strand pending pastes for the reconciler to age out.

Per-instance. A package-level WaitGroup would make one Upload's WaitFinalize block on every other instance's in-flight work, coupling unrelated servers and any tests that run in parallel.

type WhoamiInfo

type WhoamiInfo struct {
	Identity   string
	Active     int
	FirstSeen  time.Time
	UsedBytes  int         // compressed bytes summed across active non-deleted versions
	QuotaBytes int         // domain.UserQuotaBytes, surfaced so the SSH formatter need not import domain
	Session    SessionInfo // per-session keygate state; zero value if KeyGate isn't wired
}

WhoamiInfo is the per-owner summary the `whoami` verb renders.

Jump to

Keyboard shortcuts

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