catalog

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: MIT Imports: 24 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

Index

Constants

View Source
const (
	TierStandard   = "standard"
	TierNewAccount = "new"
	TierModerator  = "moderator"
	TierUnlimited  = "unlimited"
)

Quota tiers, as reported in QuotaStatus.Tier.

Variables

View Source
var (
	ErrNotFound = errors.New("not found")
	// ErrBadRemovalKind is returned for a removal kind other than
	// "content" or "technical".
	ErrBadRemovalKind = errors.New(`kind must be "content" or "technical"`)
	// ErrRemoved is returned when uploading bytes identical to an edition a
	// moderator took down — a takedown shouldn't be undone by re-uploading.
	ErrRemoved = errors.New("this file was removed by a moderator and can't be re-uploaded")
)
View Source
var ErrForbidden = errors.New("only a moderator, or the creator of a work with no editions, can remove it")

ErrForbidden is returned when the caller may not remove the work.

View Source
var ErrReasonRequired = fmt.Errorf("a reason (1-%d characters) is required", maxDeleteReasonRunes)

ErrReasonRequired is returned when a takedown has no (or an over-long) reason; the audit trail is the point of soft deletion.

Functions

This section is empty.

Types

type CreateWorkRequest

type CreateWorkRequest struct {
	Title           string `json:"title"`
	Subtitle        string `json:"subtitle"`
	Authors         string `json:"authors"`
	Description     string `json:"description"`
	Language        string `json:"language"`
	PublicationYear int    `json:"publication_year"`
	ISBN            string `json:"isbn"`
	OpenLibraryID   string `json:"openlibrary_id"`
}

CreateWorkRequest is the client-settable subset of Work (matches the OpenAPI CreateWorkRequest schema). Decoding into this rather than Work keeps server-owned fields — id, timestamps, editions, tags — out of the client's reach; unknown JSON keys are ignored.

type Download

type Download struct {
	Edition *Edition
	// WorkTitle / WorkAuthors name the downloaded file.
	WorkTitle   string
	WorkAuthors string
	Body        io.ReadCloser
	// Size is what the storage backend reports, which may differ from
	// Edition.SizeBytes if the stored object has drifted — the handler uses
	// this value, not the recorded one, to frame the response.
	Size int64
}

Download is an open edition plus what the handler needs to frame it.

type DuplicateEditionError

type DuplicateEditionError struct {
	Existing *Edition
}

DuplicateEditionError is returned by AddEdition when the uploaded bytes (after sanitization) are already stored as an edition, on this work or another one. Existing is that edition, so callers can point at it.

func (*DuplicateEditionError) Error

func (e *DuplicateEditionError) Error() string

type DuplicateEditionResponse

type DuplicateEditionResponse struct {
	Error     string    `json:"error"`
	EditionID uuid.UUID `json:"edition_id"`
	WorkID    uuid.UUID `json:"work_id"`
}

DuplicateEditionResponse is the 409 body for an upload whose content is already stored as an edition, naming that edition and its work.

type Edition

type Edition struct {
	ID        uuid.UUID `gorm:"type:uuid;primaryKey" json:"id"`
	WorkID    uuid.UUID `gorm:"type:uuid;not null;index" json:"work_id"`
	Format    string    `gorm:"not null" json:"format"`
	Language  string    `json:"language,omitempty"`
	FileKey   string    `gorm:"not null;index" json:"-"`
	SizeBytes int64     `json:"size_bytes"`
	// Unique among editions that block their bytes: a technical removal
	// (see RemovalKind) releases them, so the same file can come back.
	SHA256 string `gorm:"size:64;uniqueIndex:idx_editions_sha256,where:removal_kind <> 'technical'" json:"sha256"`
	// SourceSHA256 is the sha256 of the bytes as uploaded, before
	// sanitization. Sanitizing a PDF re-serializes it with a fresh timestamp
	// and file ID, so SHA256 (of the stored bytes) differs on every upload of
	// the same PDF; duplicate detection keys on this instead. Nullable
	// (the unique index allows many NULLs) for editions recorded without
	// the original upload's hash.
	SourceSHA256     *string   `gorm:"size:64;uniqueIndex:idx_editions_source_sha256,where:removal_kind <> 'technical'" json:"-"`
	UploadedByUserID uint      `gorm:"not null;index" json:"uploaded_by"`
	CreatedAt        time.Time `json:"created_at"`
	Removal
}

Edition is a specific file attached to a Work: one Work can have many editions (pdf, epub, mobi, translations, etc.). SHA256 is unique so identical bytes uploaded twice collapse to one storage object.

type GCStats

type GCStats struct {
	Scanned int
	Deleted int
}

GCStats summarizes one CollectGarbage pass.

type Handler

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

func NewHandler

func NewHandler(service *Service, maxUploadSize int64) *Handler

func (*Handler) CreateWork

func (h *Handler) CreateWork(w http.ResponseWriter, r *http.Request)

func (*Handler) DeleteEdition

func (h *Handler) DeleteEdition(w http.ResponseWriter, r *http.Request)

DeleteEdition is the moderator takedown for one edition. Body as for DeleteWork; "technical" (a broken file) lets the same file be uploaded again.

func (*Handler) DeleteWork

func (h *Handler) DeleteWork(w http.ResponseWriter, r *http.Request)

DeleteWork removes a work and all its editions: a moderator takedown, or a creator discarding their own still-empty work. Body: {"reason": "...", "kind": "content" | "technical"} (reason required; kind defaults to content).

func (*Handler) DownloadEdition

func (h *Handler) DownloadEdition(w http.ResponseWriter, r *http.Request)

func (*Handler) GetEdition

func (h *Handler) GetEdition(w http.ResponseWriter, r *http.Request)

func (*Handler) GetWork

func (h *Handler) GetWork(w http.ResponseWriter, r *http.Request)

func (*Handler) ListWorks

func (h *Handler) ListWorks(w http.ResponseWriter, r *http.Request)

func (*Handler) SearchWorks

func (h *Handler) SearchWorks(w http.ResponseWriter, r *http.Request)

func (*Handler) UploadEdition

func (h *Handler) UploadEdition(w http.ResponseWriter, r *http.Request)

UploadEdition accepts multipart/form-data: fields `format`, optional `language`, and file field `file`.

func (*Handler) UploadQuota

func (h *Handler) UploadQuota(w http.ResponseWriter, r *http.Request)

UploadQuota is GET /me/upload-quota[?size=N]: the caller's standing against their upload quota, so clients can check a file before a large upload starts. size defaults to 0 (is there room for another file?).

type QuotaExceededError

type QuotaExceededError struct {
	RetryAfter time.Duration
	Status     QuotaStatus
}

QuotaExceededError is returned when an upload would go over the user's quota. RetryAfter is how long until it would fit.

func (*QuotaExceededError) Error

func (e *QuotaExceededError) Error() string

type QuotaLimit

type QuotaLimit struct {
	Files int
	Bytes int64
}

QuotaLimit caps how many files, and how many stored bytes, one account may upload within the quota window.

type QuotaStatus

type QuotaStatus struct {
	Tier string `json:"tier"`
	// Unlimited is true for moderators and when no quota is configured;
	// the limit and window fields are then zero.
	Unlimited     bool  `json:"unlimited"`
	WindowSeconds int64 `json:"window_seconds"`
	FilesLimit    int   `json:"files_limit"`
	FilesUsed     int   `json:"files_used"`
	BytesLimit    int64 `json:"bytes_limit"`
	BytesUsed     int64 `json:"bytes_used"`
	// NextFreeAt is when the oldest upload in the window ages out and gives
	// back its file and bytes; absent when nothing is in the window.
	NextFreeAt *time.Time `json:"next_free_at,omitempty"`
	// contains filtered or unexported fields
}

QuotaStatus is a user's standing against their upload quota (the body of GET /me/upload-quota).

func (QuotaStatus) Admit

func (st QuotaStatus) Admit(size int64) error

Admit returns a *QuotaExceededError unless one more upload of size bytes fits. RetryAfter is when enough of the window's uploads have aged out for it to fit (the whole window if it can never fit, i.e. size > BytesLimit).

type Removal

type Removal struct {
	DeletedAt    gorm.DeletedAt `gorm:"index" json:"-"`
	DeletedBy    *uint          `json:"-"`
	DeleteReason string         `json:"-"`
	// RemovalKind says why: RemovalContent ("" on live rows) keeps the
	// file's hashes, so the same bytes can't be uploaded again;
	// RemovalTechnical (a broken file) releases them.
	RemovalKind RemovalKind `gorm:"not null;default:''" json:"-"`
}

Removal is the moderator takedown record embedded in Work and Edition. DeletedAt is gorm.DeletedAt, so every GORM query on those models (First/Find/Preload) skips removed rows automatically; raw Table("works") queries elsewhere must add `deleted_at IS NULL` themselves. Rows are kept — not hard-deleted — so takedowns stay auditable and reversible; the blob itself is purged by CollectGarbage after a retention period.

type RemovalKind

type RemovalKind string

RemovalKind is why a work or edition was taken down.

const (
	// RemovalContent is a takedown of the content itself (rights, spam,
	// abuse): the same file stays blocked. The default.
	RemovalContent RemovalKind = "content"
	// RemovalTechnical removes a file for being broken or unreadable: the
	// same file may be uploaded again (say, once the bug that broke it is
	// fixed).
	RemovalTechnical RemovalKind = "technical"
)

type Service

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

func NewService

func NewService(db *gorm.DB, store storage.Storage) *Service

func (*Service) AddEdition

func (s *Service) AddEdition(ctx context.Context, workID uuid.UUID, format, language string, uploadedBy uint, sourceSHA string, r io.Reader) (*Edition, error)

AddEdition streams r (the sanitized bytes) into storage, then records the edition. sourceSHA is the sha256 of the bytes as uploaded, before sanitization ("" if unknown). If either the uploaded bytes or the stored bytes match an existing edition on any work, it returns a *DuplicateEditionError carrying that edition and records nothing. An upload that no longer fits uploadedBy's quota (see UploadQuota) gets a *QuotaExceededError; its blob is left for CollectGarbage.

func (*Service) CheckUploadQuota

func (s *Service) CheckUploadQuota(ctx context.Context, userID uint, size int64) error

CheckUploadQuota returns a *QuotaExceededError if an upload of size bytes (0 if unknown) would not fit in userID's quota right now. It's the cheap check made before reading an upload's body; AddEdition re-checks with the stored size when it records the edition.

func (*Service) CollectGarbage

func (s *Service) CollectGarbage(ctx context.Context, retention time.Duration) (GCStats, error)

CollectGarbage deletes stored blobs that no live edition references:

  • orphans with no edition row at all (e.g. an upload whose DB insert failed, or a re-upload of a removed file), and
  • blobs whose editions were all removed by a moderator more than `retention` ago. Within the retention window a removal can still be reverted with the file intact.

Blobs younger than gcUploadGrace are never touched. Storage is content-addressed, so a key is safe to delete only when *no* edition row shares it — that is what each batch checks. Runs on one instance at a time (runlock.KeyBlobGC); returns runlock.ErrBusy if another is already sweeping.

func (*Service) CreateWork

func (s *Service) CreateWork(ctx context.Context, w *Work) error

CreateWork inserts w as a new work. The ID is always server-generated and associations (editions, tags) are never written from here: editions only come into existence through AddEdition, which is what ties a row to bytes actually in storage.

func (*Service) DeleteEdition

func (s *Service) DeleteEdition(ctx context.Context, id uuid.UUID, by uint, reason string, kind RemovalKind) error

DeleteEdition takes a single edition down (see DeleteWork). A technical removal (kind) lets the same file be uploaded again.

func (*Service) DeleteWork

func (s *Service) DeleteWork(ctx context.Context, id uuid.UUID, by uint, reason string, kind RemovalKind) error

DeleteWork takes a work down along with all its editions. The rows are soft-deleted (hidden from list/search/get/download, library and recommendations) and the blobs are purged later by CollectGarbage.

Moderators can remove any work. Anyone else can only remove a work they created that has no editions at all — which is how the new-work upload flow cleans up after its first upload is rejected (e.g. a duplicate). kind (see RemovalKind; "" = content) applies to the editions too.

func (*Service) GetEdition

func (s *Service) GetEdition(ctx context.Context, id uuid.UUID) (*Edition, error)

func (*Service) GetWork

func (s *Service) GetWork(ctx context.Context, id uuid.UUID) (*Work, error)

func (*Service) ListWorks

func (s *Service) ListWorks(ctx context.Context, limit, offset int) ([]Work, error)

func (*Service) OpenEdition

func (s *Service) OpenEdition(ctx context.Context, id uuid.UUID) (*Download, error)

OpenEdition loads the edition and its parent work's naming fields and opens the stored bytes. The caller must close Body.

func (*Service) SearchWorks

func (s *Service) SearchWorks(ctx context.Context, q string, limit, offset int) ([]Work, error)

SearchWorks finds works whose title/subtitle/authors/description match q, most relevant first. A query shaped like an ISBN also matches the isbn column exactly, ignoring hyphens, spaces and case, and those hits rank first.

Driver-aware: on Postgres it matches the weighted `search_vector` tsvector (GIN-indexed; see internal/migrations) with websearch_to_tsquery — so users can type `"exact phrase"`, `or`, and `-exclude` — with every word matched as a prefix (search runs as the user types), and orders by ts_rank, which prefers title hits over author hits over description hits. On sqlite (the test DB) it falls back to `LOWER(col) LIKE` and approximates the ranking: title matches, then subtitle/author matches, then description-only matches. Ties break newest-first on both.

Empty q is the handler's concern (returns 400); the service treats it as a no-op returning an empty slice rather than scanning the table.

func (*Service) SetUploadQuota

func (s *Service) SetUploadQuota(q UploadQuota)

SetUploadQuota sets the per-account upload quota (zero value = none).

func (*Service) UploadQuotaStatus

func (s *Service) UploadQuotaStatus(ctx context.Context, userID uint) (QuotaStatus, error)

UploadQuotaStatus reports where userID stands against their quota.

type Tag

type Tag struct {
	ID    uuid.UUID `gorm:"type:uuid;primaryKey" json:"id"`
	Name  string    `gorm:"uniqueIndex;not null" json:"name"`
	Works []Work    `gorm:"many2many:work_tags;" json:"-"`
}

type UploadQuota

type UploadQuota struct {
	Window time.Duration
	// Standard applies to verified accounts older than NewAccountAge.
	Standard QuotaLimit
	// NewAccount applies to accounts younger than NewAccountAge or whose
	// email isn't verified.
	NewAccount    QuotaLimit
	NewAccountAge time.Duration
}

UploadQuota is the per-account upload allowance. It counts editions the user actually uploaded (by uploaded_by_user_id and created_at, taken-down ones included), so rejected attempts — duplicates, failed safety checks, cancelled uploads — don't use it up. The window is rolling, not a clock hour, and the count lives in the database, so every replica sees the same numbers. Kong's per-IP limit stays in front as a coarse flood guard.

The zero value (Window == 0) means no quota.

type UploadQuotaResponse

type UploadQuotaResponse struct {
	QuotaStatus
	Fits              bool  `json:"fits"`
	RetryAfterSeconds int64 `json:"retry_after_seconds"`
}

UploadQuotaResponse is GET /me/upload-quota's body: the status, plus whether a file of the requested size fits now and, if not, when it will.

type Work

type Work struct {
	ID       uuid.UUID `gorm:"type:uuid;primaryKey" json:"id"`
	Title    string    `gorm:"not null;index" json:"title"`
	Subtitle string    `json:"subtitle,omitempty"`
	// Authors is semicolon-separated for Phase 1; normalized into its own
	// table in Phase 2 alongside crowdsourced contributions.
	Authors         string    `json:"authors,omitempty"`
	Description     string    `json:"description,omitempty"`
	Language        string    `json:"language,omitempty"`
	PublicationYear int       `json:"publication_year,omitempty"`
	ISBN            string    `gorm:"index" json:"isbn,omitempty"`
	OpenLibraryID   string    `gorm:"index" json:"openlibrary_id,omitempty"`
	CreatedAt       time.Time `json:"created_at"`
	UpdatedAt       time.Time `json:"updated_at"`
	// CreatedByUserID lets a creator remove their own work while it has no
	// editions (e.g. its first upload was rejected) — see DeleteWork.
	CreatedByUserID *uint `gorm:"index" json:"-"`
	Removal

	Editions []Edition `gorm:"foreignKey:WorkID;constraint:OnDelete:CASCADE" json:"editions,omitempty"`
	Tags     []Tag     `gorm:"many2many:work_tags;" json:"tags,omitempty"`
}

Work is the canonical record for a book/document — the abstract thing (e.g. "Moby-Dick"), independent of any particular file.

Jump to

Keyboard shortcuts

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