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
- Variables
- func CleanName(name string) string
- func IsInline(category, mime string) bool
- func Serve(w http.ResponseWriter, r *http.Request, c *Content)
- func StripJPEG(dst io.Writer, src io.Reader) error
- func StripPNG(dst io.Writer, src io.Reader) error
- func StripWebP(dst io.Writer, src io.ReaderAt, size int64) error
- type Content
- type Format
- type Kind
- type OpenOptions
- type Options
- type Service
- func (s *Service) AttachTx(tx *store.Tx, messageID, authorID string, fileIDs []string) ([]protocol.File, error)
- func (s *Service) Begin(userID string) (release func(), err error)
- func (s *Service) DiskFree() (uint64, error)
- func (s *Service) MaxUploadBytes() int64
- func (s *Service) Open(ctx context.Context, actor chat.Actor, id string, opt OpenOptions) (*Content, error)
- func (s *Service) RemoveUnreferenced(ctx context.Context, shas []string) (int, error)
- func (s *Service) SweepOrphanBlobs(ctx context.Context, minAge time.Duration) (int, error)
- func (s *Service) SweepTmp(maxAge time.Duration) (int, error)
- func (s *Service) TotalBytes(ctx context.Context) (int64, error)
- func (s *Service) Upload(ctx context.Context, in Upload) (protocol.File, error)
- func (s *Service) UsedBytes(ctx context.Context, userID string) (int64, error)
- type TooLargeError
- type Upload
Constants ¶
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 )
const MaxConcurrentUploads = 5
MaxConcurrentUploads is how many uploads one user may have in flight.
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.
const MaxNameChars = 255
MaxNameChars is the longest file name the files table accepts.
const MaxPerMessage = 10
MaxPerMessage is the most files one message carries.
Variables ¶
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 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 ¶
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 (*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 ¶
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) MaxUploadBytes ¶
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 ¶
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 ¶
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 ¶
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 ¶
TotalBytes returns how many bytes every stored file occupies.
func (*Service) Upload ¶
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.
type TooLargeError ¶
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.
Source Files
¶
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. |