files

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: Apache-2.0 Imports: 38 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 files is the file domain service: streaming uploads into a content-addressed store, metadata stripping, thumbnails, quotas, the permission check and headers of file serving, and the binding of uploaded files to messages.

Blobs live at <data>/files/<sha[0:2]>/<sha[2:4]>/<sha> (the thumbnail next to it as <sha>.thumb), keyed by the SHA-256 of the bytes that are stored, so identical uploads share one blob. Uploads are spooled in <data>/tmp. File names are user data: nothing in this package logs them.

Index

Constants

View Source
const (
	// ThumbEdge is the long edge of a thumbnail in pixels. Images that are
	// not larger than this get no thumbnail.
	ThumbEdge = 640
	// MaxPixels is the largest image (width x height) the service decodes.
	// Larger images are stored as they arrive and served as downloads.
	MaxPixels = 50_000_000
)
View Source
const MaxConcurrentUploads = 5

MaxConcurrentUploads is how many uploads one user may have in flight.

View Source
const MaxDecodePixels = 64_000_000

MaxDecodePixels is the budget of pixels that the whole process decodes, rotates or thumbnails at once. A rotated 50 MP JPEG peaks near 0.5 to 0.8 GB, and a Raspberry Pi 4 cannot hold five of them, so decodes queue up instead.

View Source
const MaxNameChars = 255

MaxNameChars is the longest file name the files table accepts.

View Source
const MaxPerMessage = 10

MaxPerMessage is the most files one message carries.

Variables

View Source
var (
	// ErrInsufficientStorage means the data volume has less free space than
	// the disk_reserve_bytes setting.
	ErrInsufficientStorage = errors.New("insufficient storage")
	// ErrTooManyUploads means the user already has the maximum number of
	// uploads in flight.
	ErrTooManyUploads = errors.New("too many concurrent uploads")
	// ErrNotFound means no such file, or one the caller may not see.
	ErrNotFound = errors.New("file not found")
	// ErrBadUpload means the request body could not be read as an upload.
	ErrBadUpload = errors.New("malformed upload")
)

Errors of the upload path. The HTTP layer maps them to 413, 415, 429 and 507.

View Source
var ErrMalformed = errors.New("malformed image")

ErrMalformed reports that a file is not a well-formed image of the format it claims to be. The service stores such files as plain downloads.

Functions

func CleanName

func CleanName(name string) string

CleanName turns the client's file name into a name that is safe to store, show and put into a header: only the last path element, valid UTF-8, no control or bidirectional-override characters, no trailing dots or blanks, at most 255 characters (the extension is kept). An unusable name becomes "file".

func IsInline

func IsInline(category, mime string) bool

IsInline reports whether a file of this category and media type is served inline. Files of category file are never inline, whatever their type.

func Serve

func Serve(w http.ResponseWriter, r *http.Request, c *Content)

Serve writes c to w with the headers of file serving and honours Range, If-Range and If-None-Match (ETag) requests. It does not close c.

func StripJPEG

func StripJPEG(dst io.Writer, src io.Reader) error

StripJPEG copies the JPEG in src to dst without its APP1 (EXIF, XMP), APP13 (IPTC) and COM (comment) segments. The compressed image data is copied byte for byte, so the picture is not re-encoded. Bytes after the EOI marker (thumbnails, embedded videos of motion photos) are dropped. A truncated or otherwise malformed file returns an error wrapping ErrMalformed.

func StripPNG

func StripPNG(dst io.Writer, src io.Reader) error

StripPNG copies the PNG in src to dst without its eXIf, tEXt, iTXt, zTXt and tIME chunks. All other chunks, including the image data, are copied unchanged; bytes after the IEND chunk are dropped. A file without a valid signature, with an oversized chunk or without IEND returns an error wrapping ErrMalformed.

func StripWebP

func StripWebP(dst io.Writer, src io.ReaderAt, size int64) error

StripWebP copies the WebP file in src (size bytes) to dst without its EXIF and XMP chunks and clears the matching flags of the VP8X header, fixing the RIFF size. Image data and the colour profile are copied unchanged. A file that is not a well-formed RIFF/WebP container returns an error wrapping ErrMalformed.

Types

type Content

type Content struct {
	io.ReadSeekCloser
	// ModTime is the upload time; the content never changes after it.
	ModTime time.Time
	// ContentType is the file's own type for allowlisted inline types and
	// application/octet-stream for everything else.
	ContentType string
	// Disposition is the Content-Disposition header value.
	Disposition string
	// ETag is the quoted validator derived from the SHA-256.
	ETag string
}

Content is an opened file ready to be served. The caller closes it.

type Format

type Format int

Format is a container format the service can strip and thumbnail.

const (
	FormatNone Format = iota
	FormatJPEG
	FormatPNG
	FormatGIF
	FormatWebP
)

The formats of processed images. FormatNone marks files that are stored as they arrive.

type Kind

type Kind struct {
	// Mime is the media type without parameters.
	Mime string
	// Category is one of protocol.FileImage, FileVideo, FileAudio, FileOther.
	Category string
	// Inline reports that Mime is on the inline allowlist and the file may be
	// served with its own Content-Type.
	Inline bool
	// Format is set for the image formats the service strips and thumbnails.
	Format Format
}

Kind is what the sniffer decided about an upload.

func Sniff

func Sniff(head []byte, name string) Kind

Sniff decides the type of a file from its first bytes (at most 512 are looked at) cross-checked with the extension of name. The content decides: a file that does not sniff as an inline type is a plain file whatever its extension says, and a file whose extension names a different category than its content (a ".png" holding audio) is demoted to a plain file too.

type OpenOptions

type OpenOptions struct {
	// Thumb serves the thumbnail instead of the file.
	Thumb bool
	// Download forces Content-Disposition: attachment.
	Download bool
}

OpenOptions select what Open returns.

type Options

type Options struct {
	// DB is the store; required.
	DB *store.DB
	// Settings supplies upload_max_bytes, user_quota_bytes and
	// disk_reserve_bytes; required.
	Settings *settings.Store
	// DataDir is the data directory; blobs go to <DataDir>/files and the
	// upload spool to <DataDir>/tmp. Required.
	DataDir string
	// Logger receives non-fatal errors; nil discards them.
	Logger *slog.Logger
	// Now is the clock of the tmp sweep; nil means time.Now.
	Now func() time.Time
	// FreeSpace reports the bytes available on the volume holding dir; nil
	// means the operating system's answer. Tests inject it.
	FreeSpace func(dir string) (uint64, error)
}

Options configure a Service.

type Service

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

Service is the file domain service.

func New

func New(o Options) (*Service, error)

New returns a Service and makes sure its directories exist.

func (*Service) AttachTx

func (s *Service) AttachTx(tx *store.Tx, messageID, authorID string, fileIDs []string) ([]protocol.File, error)

AttachTx binds uploaded files to a message inside the message's transaction. Every file must exist, have been uploaded by authorID and not be attached to another message yet; at most MaxPerMessage files are allowed. The attachments rows keep the order of fileIDs (position = index). The returned wire views are in the same order. A problem is reported as a chat validation error on file_ids that does not say which case applied, so ids of other users' files cannot be probed.

func (*Service) Begin

func (s *Service) Begin(userID string) (release func(), err error)

Begin reserves one of the user's concurrent upload slots. The returned function releases it. A user with MaxConcurrentUploads uploads in flight gets ErrTooManyUploads.

func (*Service) DiskFree

func (s *Service) DiskFree() (uint64, error)

DiskFree returns the bytes available on the data volume.

func (*Service) MaxUploadBytes

func (s *Service) MaxUploadBytes() int64

MaxUploadBytes is the current per-file size limit (upload_max_bytes).

func (*Service) Open

func (s *Service) Open(ctx context.Context, actor chat.Actor, id string, opt OpenOptions) (*Content, error)

Open returns the file id (or its thumbnail) for actor. A file is visible to its uploader, to anyone who may view a channel that holds a live message attaching it, and, when it is somebody's avatar, to every signed-in user. Everything else, including files that do not exist, is ErrNotFound.

func (*Service) RemoveUnreferenced

func (s *Service) RemoveUnreferenced(ctx context.Context, shas []string) (int, error)

RemoveUnreferenced deletes the blobs (and thumbnails) of the given SHA-256 values that no files row refers to any more, and returns how many blobs it removed. Callers delete the rows first and call this after the transaction committed; the check is repeated here, under the same lock uploads hold, so an upload of identical content racing with the removal keeps its blob. The lock is taken per SHA-256, so uploads are not stalled for the whole list.

func (*Service) SweepOrphanBlobs

func (s *Service) SweepOrphanBlobs(ctx context.Context, minAge time.Duration) (int, error)

SweepOrphanBlobs walks the blob store and removes the blobs and thumbnails that no files row refers to, and returns how many blobs it removed. Entries modified within the last minAge are spared: an upload writes its blob before its row, so a young blob may belong to an upload still in flight. Each candidate is checked again under the upload lock before it goes.

func (*Service) SweepTmp

func (s *Service) SweepTmp(maxAge time.Duration) (int, error)

SweepTmp deletes the entries of the temporary directory that are older than maxAge (0 deletes them all) and returns how many it removed. Uploads that were cut off by a restart leave such files behind.

func (*Service) TotalBytes

func (s *Service) TotalBytes(ctx context.Context) (int64, error)

TotalBytes returns how many bytes every stored file occupies.

func (*Service) Upload

func (s *Service) Upload(ctx context.Context, in Upload) (protocol.File, error)

Upload stores one file for in.UserID and returns its wire view. The content is spooled to <data>/tmp while its SHA-256 is computed, sniffed, stripped of metadata and thumbnailed when it is a supported image, then moved into the content-addressed store. Errors: *TooLargeError (file larger than upload_max_bytes, or quota exceeded), ErrInsufficientStorage, ErrBadUpload.

func (*Service) UsedBytes

func (s *Service) UsedBytes(ctx context.Context, userID string) (int64, error)

UsedBytes returns how many bytes the files of userID occupy (every files row counts, whether or not it is attached yet).

type TooLargeError

type TooLargeError struct {
	Quota bool
	Limit int64
	Used  int64
}

TooLargeError reports an upload that exceeds the per-file limit or the user's quota. Limit is the exceeded limit in bytes; for a quota Used is what the user stores already.

func (*TooLargeError) Details

func (e *TooLargeError) Details() map[string]any

Details are the machine-readable details of the 413 answer.

func (*TooLargeError) Error

func (e *TooLargeError) Error() string

type Upload

type Upload struct {
	// UserID is the uploader.
	UserID string
	// Name is the file name the client announced; it is cleaned before use.
	Name string
	// Body is the file content. It is read to its end or until the size limit.
	Body io.Reader
	// SizeHint is the announced size of the request, or 0 when unknown; it
	// only makes the free-space check stricter.
	SizeHint int64
}

Upload is one file to store.

Directories

Path Synopsis
Package filestest builds the image fixtures of the file tests in Go, so no binary test data is checked in: JPEGs with EXIF (GPS and orientation), XMP, IPTC and comments, PNGs with text and EXIF chunks, WebP files with metadata chunks, an oversized PNG header and an SVG with a script.
Package filestest builds the image fixtures of the file tests in Go, so no binary test data is checked in: JPEGs with EXIF (GPS and orientation), XMP, IPTC and comments, PNGs with text and EXIF chunks, WebP files with metadata chunks, an oversized PNG header and an SVG with a script.

Jump to

Keyboard shortcuts

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