attachments

package
v0.40.1 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2026 License: MIT Imports: 12 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 attachments holds one inbound attachment upload's chunks in memory while its attachment_chunk frames arrive, refuses a stream whose framing contradicts what the transfer declared, and yields the assembled bytes only once they match the size and the digest the transfer declared.

The receiver's rules are published in docs/protocol-mobile.md § Attachments, "Reassembly & integrity (the receiver's rules)": each chunk's decoded data is stored AT ITS INDEX, so chunks may arrive in ANY ORDER, the transfer is complete once every index in [0, total_chunks) has arrived exactly once, and only then is the assembled length compared against the declared size and its lowercase-hex sha256 against the declared digest. That is deliberately weaker than the bundle stream's strict succession rule in relay.ReassembleBundle, which is the neighbouring rule a reader would otherwise copy and which the published contract warns against by name. What this package does copy from ReassembleBundle is its all-or-nothing posture: it yields the complete bytes or it fails cleanly, and never partial or corrupted output.

In-memory for accumulation and admission: nothing on those paths touches the filesystem, and EnsureDir — which resolves and creates the directory an attachment is filed under — is the sole function here that does. Nothing reads a socket or emits a wire code, and the package makes zero log calls, EnsureDir included. Every refusal is a Go sentinel so the daemon's logs and this package's tests can tell them apart; mapping the three framing refusals to the single attachment.invalid_chunk wire code and the two integrity refusals to attachment.integrity_failed is the dispatch site's job (#1744), which is also the only place that knows the attachment id and conn id worth logging.

The receiver's resource bounds are owned three separate ways, and admission runs before an Accumulator exists: how many uploads may be in flight is maxInFlightUploads, enforced by Registry's admission gate; how many bytes one may accumulate is maxUploadBytes, enforced twice in this package — the declared size at CheckDeclaredSize and the accumulated bytes at step 5 of Add — and the first-chunk total_chunks/size cross-check that refuses before allocating is CheckDeclaration, also in this package. What this package bounds on its own is the KEY SPACE: the range check means no accumulator ever holds more entries than the count it was constructed with, and nothing here is ever sized from a claim. With both admission checks run that claim is now absolute rather than merely relative — an admitted transfer declares at most 373 chunks, since maxUploadBytes at protocol.MaxAttachmentChunkBytes needs no more.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrTotalChunksMismatch reports a chunk whose declared total disagrees
	// with the count the transfer was admitted under. Discards the transfer.
	ErrTotalChunksMismatch = errors.New("attachments: chunk total_chunks disagrees with the transfer's declared count")

	// ErrIndexOutOfRange reports a chunk index outside [0, total_chunks),
	// negative or too large alike. Discards the transfer.
	ErrIndexOutOfRange = errors.New("attachments: chunk index outside [0, total_chunks)")

	// ErrDuplicateIndex reports a chunk index that has already arrived, whether
	// or not it repeats the bytes already held. Discards the transfer.
	ErrDuplicateIndex = errors.New("attachments: chunk index already received")

	// ErrSizeMismatch reports assembled bytes whose length differs from the
	// transfer's declared size. Discards the transfer.
	ErrSizeMismatch = errors.New("attachments: assembled length differs from the declared size")

	// ErrDigestMismatch reports assembled bytes whose lowercase-hex sha256
	// differs from the transfer's declared digest. Discards the transfer.
	ErrDigestMismatch = errors.New("attachments: assembled sha256 differs from the declared digest")

	// ErrIncomplete reports that at least one index has not arrived yet. It is
	// NOT a refusal: it does not discard the transfer, and a later Add can turn
	// it into bytes. It is the one sentinel here a caller must not map to a
	// client-visible reject code.
	ErrIncomplete = errors.New("attachments: transfer incomplete")
)

Sentinel errors returned by Add and Assemble. Callers distinguish them with errors.Is, never by comparing error strings: every refusal is returned wrapped with the offending numbers.

The first three are framing refusals and all three map to the one wire code protocol.CodeAttachmentInvalidChunk; the next two are integrity refusals and both map to protocol.CodeAttachmentIntegrityFailed. ErrIncomplete maps to nothing. Every one of those mappings happens at #1744's dispatch site, not here — this package still does not import codes.go. The many-to-one shape is deliberate in both families: distinguishability is wanted in-process, for these tests and for the daemon's logs, not on the wire.

View Source
var ErrConversationMismatch = errors.New("attachments: chunk names a different conversation than the transfer in flight was admitted under")

ErrConversationMismatch reports a chunk naming a different conversation than the transfer in flight for its pair was admitted under — a phone that switched conversations mid-upload. lookupAndStamp is the one place that raises it, BARE rather than wrapped, and callers distinguish it with errors.Is.

IT IS A CONSISTENCY REFUSAL AND NOT A CONTAINMENT ONE, and reading it as the latter would be a mistake with consequences: both ids have already passed the caller's membership check, EnsureDir still refuses anything escaping its root, and naming a conversation was never authorization — the rule protocol.RequestAttachmentPayload's block carries in full. What it detects is that a transfer's DECLARATION and its OUTCOME can otherwise disagree, so the bytes end up where the client attached them or nowhere.

It lives here beside its raiser rather than in either package-wide var block, for ErrUnknownUpload's own reasons: accumulator.go's opens "returned by Add and Assemble" and this one is returned by neither, and admission.go's three all refuse a DECLARATION at admission, where this one refuses a chunk against a declaration already latched.

ErrUnknownUpload is the near miss and the two are not interchangeable: that one says there is no transfer under the pair at all, this one says there is one and this chunk does not belong to its destination. An idle-expired pair answers ErrUnknownUpload rather than this, because the reap runs ahead of the comparison — see lookupAndStamp.

WHICH WIRE CODE IT MAPS TO IS #1897's map, and it needs no new one: #2143 already answers every bad-destination case with attachment.invalid_chunk, and answering a mismatch differently would split one client-visible class across two codes.

View Source
var ErrInvalidDeclaration = errors.New("attachments: transfer declaration is not admissible")

ErrInvalidDeclaration reports a transfer declaration this receiver refuses before an Accumulator exists. Every refusal CheckDeclaration returns wraps it with the offending numbers, and callers distinguish it with errors.Is rather than by comparing error strings.

It is deliberately NOT one of the sentinels in accumulator.go's var block, whose own opening sentence scopes it to Add and Assemble: this one is raised by neither, and refuses the declaration a transfer would be admitted under rather than a chunk within an admitted one. ErrTotalChunksMismatch is the nearby sentinel a reader might reach for and is a different fault — it means a chunk disagrees with the count the transfer WAS admitted under, so it presupposes the admission this error withholds.

One sentinel covers every refusal CheckDeclaration returns. ErrUploadTooLarge, the other sentinel in this file, is a deliberate second one rather than a widening of this: this one is committed to the attachment.invalid_chunk wire code, whose published repair is to RE-CHUNK, and that one to attachment.too_large, whose repair is to SHRINK THE FILE. Mapping either to its code is the dispatch site's job (#1744); this file emits no wire code and imports no codes.

View Source
var ErrInvalidID = errors.New("attachments: identifier is not of canonical shape")

ErrInvalidID reports an identifier that is not of canonical shape, whether it is the conversation id or the attachment id. Every refusal wraps it naming which of the two failed and its value, and callers distinguish it with errors.Is rather than by comparing error strings.

ONE sentinel covers both ids on purpose, where ErrUploadTooLarge is a deliberate second sentinel beside ErrInvalidDeclaration. That split exists because the client's repair differs — re-chunk versus shrink the file. Here it does not: neither refusal is retryable and neither is repairable by the client, since a non-canonical conversation id is a daemon bug and a non-canonical attachment id is a client bug. A caller that wants to know which id was bad reads the wrapped message; a caller that wants to branch has nothing to branch to.

It is deliberately distinguishable from ErrNotContained, its neighbour below: a refusal here means no path was ever built, so nothing on the filesystem was touched, while a containment refusal means both ids were canonical and the destination they name resolves somewhere else.

View Source
var ErrNotContained = errors.New("attachments: attachment directory resolves outside the destination it was built for")

ErrNotContained reports a destination whose symlink-resolved path is not the path this (conversation id, attachment id) pair maps to beneath the resolved instance directory — whether it lands outside the instance directory entirely, or inside it under another conversation. Refusals wrap it with the expected and the resolved path, and callers distinguish it with errors.Is.

The host paths in that message are for the operator's log and are safe here only because they never reach the wire: docs/protocol-mobile.md § Attachments makes attachment.storage_failed a STATIC message carrying neither the host path nor the underlying filesystem error, and #1744's mapping is what enforces that. This package emits no wire code and makes no log call.

View Source
var ErrNotFound = errors.New("attachments: no stored attachment for this conversation and attachment_id")

ErrNotFound reports that a (conversation id, attachment id) pair does not resolve to a stored file — whether nothing was ever stored under it, either id is not of canonical shape, or the directory the pair names resolves somewhere other than the destination it maps to. Callers distinguish it with errors.Is; the wrapped message names which step failed, for the operator.

ONE sentinel covers all of those, and unlike ErrInvalidID's single-sentinel argument this one is a contract requirement rather than a judgement call. docs/protocol-mobile.md § Error codes makes attachment.not_found deliberately indistinguishable across an unknown id, a non-canonical id and an id resolving outside the named conversation's directory — a disclosure decision, so an asking verb is not a path-existence oracle for a traversal probe. A single sentinel makes that structural: a consumer cannot branch on what it cannot distinguish, so the decision survives a careless dispatch site rather than depending on one.

It is deliberately NOT ErrInvalidID or ErrNotContained reused, though two of its causes are exactly theirs. #1897 maps both of those to CodeAttachmentStorageFailed for the upload leg; a retrieval dispatch site sharing any part of that table would answer storage_failed where the contract says attachment.not_found.

Like the three sentinels above, and unlike the six latching sentinels in accumulator.go, it carries no discard semantics: there is no accumulator state here to latch or drop.

View Source
var ErrTooManyUploads = errors.New("attachments: too many uploads in flight")

ErrTooManyUploads reports a first chunk for a NEW pair refused because this receiver already holds maxInFlightUploads uploads in flight. Registry's admission gate is the one place that raises it, wrapped by capacityRefusal with the in-flight count and the bound, and callers distinguish it with errors.Is rather than by comparing error strings.

It is the third sentinel this file publishes and the sibling ErrUploadTooLarge's doc argues for by name, rather than a widening of either neighbour. RETRYABILITY IS WHY: this one clears BY ITSELF as other uploads finish — internal/protocol's CodeAttachmentTooManyUploads is marked transient for exactly that, with a documented obligation to back off rather than resend at once — while ErrInvalidDeclaration never clears for that declaration and ErrUploadTooLarge never clears for that file. Mapping it to its wire code is the dispatch site's job (#1744); this file emits no wire code and imports no codes.

It is not in accumulator.go's var block, whose own opening sentence scopes it to Add and Assemble: neither raises this one, which refuses a transfer before its Accumulator is stored.

View Source
var ErrUnknownUpload = errors.New("attachments: no upload in flight for this conn and attachment_id")

ErrUnknownUpload reports a chunk for a conn-and-attachment_id pair the registry does not hold — never admitted, or admitted and already over. Deliver is the one place that raises it, BARE rather than wrapped, and callers distinguish it with errors.Is rather than by comparing error strings.

It lives HERE, beside the method that raises it, rather than in either package-wide var block: accumulator.go's opens "Sentinel errors returned by Add and Assemble" and this one is returned by neither, and admission.go's three all refuse a DECLARATION at admission, where this one refuses a chunk for a transfer that was never admitted or is already released. storage.go is the precedent for a sentinel living with its raiser.

ErrIncomplete is the near miss a reader might reach for and is its OPPOSITE: that one says a live transfer is waiting for more chunks, this one says there is no transfer at all. It is distinct from every other sentinel this package publishes, which is a property TestRegistry_DeliverUnheldPair_RefusesAndCreatesNothing asserts over the whole set rather than over a sample of it.

WHICH WIRE CODE IT MAPS TO IS #1744's, and no candidate is named here. None of the attachment.* codes internal/protocol publishes today means "no live transfer under this pair" — CodeAttachmentNotFound is the retrieval leg's, and its message is deliberately static — so whether this folds into an existing code or wants one of its own is that ticket's decision, and pre-empting it here would publish a mapping this package deliberately does not own.

View Source
var ErrUploadTooLarge = errors.New("attachments: upload exceeds the per-upload byte bound")

ErrUploadTooLarge reports an upload that exceeds this receiver's per-upload byte bound, maxUploadBytes, at either rung: a declared size above the bound (CheckDeclaredSize) or an arriving chunk that would take the held total past it (Add). Both wrap it with the offending numbers, and callers distinguish it with errors.Is rather than by comparing error strings.

It is deliberately NOT folded into ErrInvalidDeclaration, its neighbour above. Both wire codes are non-retryable, so collapsing them would not hot-loop a client — it would send it to RE-CHUNK an oversized file, which fails identically, forever, rather than to shrink it.

Nor is it a general resource-limit sentinel shared with ErrTooManyUploads, the concurrency refusal below, and that is why the name is specific to the byte bound. Retryability itself inverts across the two: internal/protocol's CodeAttachmentTooManyUploads is marked transient, because it clears when other uploads finish, while this one never clears for that file. Collapsing them would tell a client either to re-upload an oversized file in a loop or to abandon a bound that clears in seconds.

It is not in accumulator.go's var block either, whose own opening sentence scopes it to Add and Assemble: this one is returned by Add AND by an admission function that runs before an Accumulator exists.

View Source
var ErrWriteFailed = errors.New("attachments: attachment file could not be written")

ErrWriteFailed reports that an attachment's verified bytes could not be written into the directory they were destined for. Every refusal wraps it alongside the underlying filesystem error, so errors.Is reaches this sentinel for #1744's wire mapping and the fs error for the operator.

It is deliberately NOT named ErrStorageFailed. All three of this file's sentinels map to attachment.storage_failed at #1744, so a Go name matching the wire code would falsely suggest this one is THE storage-failure sentinel. It names what failed — the write — not the code it becomes.

Like ErrInvalidID and ErrNotContained, and unlike the six latching sentinels in accumulator.go, it carries no discard semantics: there is no accumulator state here to latch or drop.

Functions

func CheckDeclaration

func CheckDeclaration(totalChunks int, size int64) error

CheckDeclaration answers whether a first chunk's declared total_chunks and size can both be true. A nil error admits the transfer, and the same two numbers then go to NewAccumulator; every refusal wraps ErrInvalidDeclaration.

It takes the two declared numbers as scalars rather than a protocol.AttachmentChunkPayload, mirroring NewAccumulator, and the narrow signature is load-bearing twice over. It says these two fields are the whole subject — a reader must not conclude the payload's other six are checked here — and it structurally excludes Filename, SHA256, AttachmentID and Data from ever reaching an error string, which is the strongest available form of the never-log rule protocol.AttachmentChunkPayload's SECURITY block states.

PURE and stateless: no filesystem, no socket, no logger, no lock and no goroutine, so it is safe to call concurrently from any goroutine, exactly like SanitizeFilename and unlike Accumulator, which its own doc records as fed serially by one session's appFrameWorker.

WHAT IS CHECKED IS THE TWO NUMBERS, NOT THE STRIDE. A client whose chunking differs from the published one but whose count happens to conform — 45001 bytes cut at 32 KiB is 2 chunks either way — is admitted here and assembles normally, because Assemble compares the assembled length and digest against the declaration and nothing downstream needs the stride. A client whose chunking makes the count differ is refused, and that is not a regression: the published contract already obliges every chunk but the last to carry exactly protocol.MaxAttachmentChunkBytes raw bytes.

WHAT IS NOT CHECKED IS MAGNITUDE. A declaration that is arithmetically conforming but enormous — size math.MaxInt64 with its matching count — is ADMITTED here, and the per-upload byte bound that refuses it is CheckDeclaredSize, a SIBLING in this file rather than a check folded in. Folding it in would refuse that pair, and TestCheckDeclaration's row on it is the only one that reads this ceiling's exact value rather than merely asserting it is not 1 — so folding would destroy the sole pin on the arithmetic whose wrapping form silently admits the largest declaration the wire can carry. Nothing this function admits is allocated from in the meantime: NewAccumulator's map takes no capacity hint and Assemble sizes from the sum of the arrived chunk lengths.

Admission also runs IN FRONT OF the Accumulator rather than gating it. This returns an error rather than a validated type, so NewAccumulator stays constructible without passing through here, which is why Assemble's totalChunks < 1 clause is still load-bearing.

func CheckDeclaredSize

func CheckDeclaredSize(size int64) error

CheckDeclaredSize answers whether a first chunk's declared size is within this receiver's per-upload byte bound. A nil error admits the transfer; the one refusal wraps ErrUploadTooLarge with the size and the bound. It is the cheap rung of that bound — it refuses the honest oversize file on frame one, before any of its bytes are held — and Add's step 5 is the rung that makes the number a ceiling rather than a ceiling plus a per-chunk fudge factor.

It checks MAGNITUDE AND NOTHING ELSE, which is why a NEGATIVE size is admitted here rather than refused. CheckDeclaration already refuses one with its own sentinel, and a second owner for that fault would make which sentinel a caller sees depend on the order it happened to run the two checks.

PAIRING OBLIGATION: the caller runs BOTH checks on the first chunk, before constructing an Accumulator, and that is load-bearing for more than tidiness. CheckDeclaration bounds total_chunks from above, this bounds size from above, and only TOGETHER do they bound the accumulator's key space: with both run, an admitted transfer declares at most 373 chunks, so its map can hold at most 373 entries. Run alone, this one admits a declaration of 2^31-1 ZERO-BYTE chunks, which no byte bound can refuse, because Σ len(Data) stays 0. Registry.Admit is where that obligation is discharged: it runs both before constructing an Accumulator, and it is the registry's only exported way in. That is ONE CALLER THAT RUNS BOTH, NOT A GATE. Neither function can enforce the other's presence — admission runs IN FRONT OF the Accumulator rather than gating it, as CheckDeclaration's own doc records — and NewAccumulator stays exported and constructible without passing through Admit, so a second caller could still run one check or neither.

PURE and stateless: no filesystem, no socket, no logger, no lock and no goroutine, so it is safe to call concurrently from any goroutine, exactly like CheckDeclaration and SanitizeFilename.

func EnsureDir

func EnsureDir(instanceDir string, conversationID conversations.ConversationID, attachmentID string) (string, error)

EnsureDir resolves and creates the directory one attachment of one conversation is filed under, returning its symlink-resolved absolute path. Writing bytes into it is #1782's; dispatching to it and mapping the two sentinels above to wire codes is #1744's.

The layout beneath instanceDir is conversations/<conversation-id>/ attachments/<attachment-id>, every level created 0o700, matching Registry.Save in internal/conversations and in internal/devices. A conversations DIRECTORY and the existing conversations.json FILE coexist under one parent without colliding. The per-attachment-id component is what lets two attachments in one conversation carry the same client-supplied filename.

attachmentID is CLIENT-CHOSEN on the upload leg and conversationID is daemon-side, but both become path components here so both are validated here. protocol.MaxAttachmentIDBytes is not the defence and does not need to be consulted: conversations.ValidID admits 36 characters of lowercase hex and dashes at fixed offsets and nothing else, so a passing id contains no '/', no '.', no NUL and no "..", cannot spell any path component other than itself, and fits the ceiling structurally. Its lowercase-only alphabet is load-bearing beyond traversal: it is what keeps the id-to-directory mapping injective on a case-insensitive filesystem, which APFS is by default. A replacement shape (#1744 publishes the client-visible contract) must keep that property, or two distinct ids resolve to one directory on macOS and #1782's writes cross-contaminate without any symlink involved.

conversationID is typed and attachmentID is not, deliberately. Both are canonical UUIDv4 strings, so a caller that swaps them produces a VALID but wrong path that no validator can catch; typing one of the two makes the swap a compile error at every call site. There is no AttachmentID type to use for the other — protocol.AttachmentChunkPayload's field is a plain string, and minting a type for it is #1744's contract to make.

Idempotent: a second call for a pair whose directory already exists returns the same path and no error, so a re-delivered upload is not a storage failure. Safe for concurrent use by construction — no state, no lock, and MkdirAll races benignly against itself.

The path returned is the EvalSymlinks output rather than the textually built one. They are provably equal by the time it returns, and returning the resolved one is the honest expression of what the caller is promised.

func ResolvePath

func ResolvePath(instanceDir string, conversationID conversations.ConversationID, attachmentID string) (string, error)

ResolvePath returns the on-host path of the file stored under one conversation's one attachment — EnsureDir's read-side counterpart, and the reason a consumer need not re-derive the storage layout for itself. Intake.Receive deliberately discards the path Store answers and reports the attachment id alone, and the client filename is retained nowhere else, so the path cannot be re-derived from the id without reading the directory back.

PRECONDITION, and it carries the whole security property: conversationID MUST already have been validated against the daemon's own registry — a lookup key, never a value trusted as sent. This function cannot check that, and a caller that gets it wrong defeats every check below — the pair then genuinely does resolve inside the conversation it named. docs/protocol-mobile.md § Naming a message's attachments is explicit that confinement to the message's own conversation — not attachment_id's shape, and not its randomness — is what keeps an identifier that document repeatedly calls NOT a capability from becoming one.

BOTH LEGS DISCHARGE IT THE SAME WAY, and that is newer than it reads. handleRequestAttachment always passed a CLIENT-ASSERTED id that KnownConversation had validated; the upload leg reached its conversation through a follow-active resolver instead, and this block used to name that asymmetry as the shape to copy. #2143 removed it: attachment_chunk carries a conversation_id (#2142), handleAttachmentChunk gates it through the same membership check, and Intake.Receive takes the validated destination as a per-transfer argument. So the rule is one rule — validated by the caller, on both legs — rather than a rule and an exception.

IT CREATES NOTHING, and that is the shape of the function rather than a guard inside it: where EnsureDir creates the anchor before resolving it, this one resolves what is there, so an absent instance, conversation or attachment directory simply fails to resolve. A lookup that MkdirAll'd what it failed to find would turn every miss into a state change on disk, and #1746's attachment.not_found path would then leave an empty directory behind for every traversal probe it refuses.

Containment is EnsureDir's discipline minus the creation: the resolved instance directory is the anchor, the destination is built TEXTUALLY beneath it, and the comparison is full-path EQUALITY rather than a filepath.Rel-style "is it under the root" test. Equality is strictly stronger and is what refuses a conversation directory symlinked at a SIBLING conversation, which stays inside the instance directory and passes any containment test. Only plain files are eligible, so a symlink parked in an attachment directory is skipped rather than followed — the leaf half of the same property, without which the directory is confined and the file answered is not.

A directory holding more than one file answers the lexicographically smallest eligible name, on every call. Intake.Receive calls Store(dir, chunk.Filename, data), so one attachment id uploaded twice under two client filenames leaves two files in one directory; the published contract treats that as last-writer-wins and explicitly not a privilege boundary, so what is owed here is a deterministic answer rather than a refusal.

An entry beginning with '.' is never eligible. Store creates its temp file inside the destination directory — which is what makes the rename intra-filesystem and therefore atomic — and the defer os.Remove that normally clears it does not survive a kill, so a leftover .attachment-*.tmp is reachable. The exclusion is written against SanitizeFilename's guarantee that a stored component never begins with '.', not against Store's temp pattern, because that guarantee is the invariant making the exclusion sound.

The check-then-use window between reading the directory here and a caller opening the path is real, and accepted on EnsureDir's bound: exploiting it needs write access inside the daemon's own 0o700 state directory, and anyone holding that can already rewrite devices.json. Answering an open handle would close the window and is declined because #2038 needs a path as prompt text and never opens it.

No state, no lock, no goroutine, and nothing written, so it is safe for concurrent use by construction — including against a concurrent Store on the same pair, whose rename is atomic.

LOGGING OBLIGATION on the consumer. The returned path is NOT fully daemon-authored: its leaf is SanitizeFilename's rendering of a client filename, and docs/protocol-mobile.md § Attachments bans logging a filename for a privacy reason sanitising does not lift. Do not log the returned path. No error built here names it either, nor any directory entry — every refusal names directory paths only, which are built from two canonical-shape-checked ids and carry no client text, exactly as ErrNotContained's already are.

func SanitizeFilename

func SanitizeFilename(name string) string

SanitizeFilename turns a client-supplied filename into one safe path component. It is TOTAL — every string has a safe answer, so there is nothing to refuse and no error to return — and PURE: it touches no filesystem, constructs no path, holds no state and takes no lock, so it is safe to call concurrently from any goroutine. That is worth saying next to Accumulator, which carries the opposite constraint and is documented as fed serially by one session's appFrameWorker goroutine.

The returned value is exactly one path component: never empty, never "." or "..", never containing '/', never containing a control character, never beginning with '.', valid UTF-8, and at most protocol.MaxAttachmentFilenameBytes BYTES measured by len — bytes, not characters. Every rune outside the allowlist a-z A-Z 0-9 _ . - becomes '_', which is cmd/pyry's sanitizeName allowlist byte for byte; the shape is that function's, which cannot be imported (unexported, package main).

What it does NOT return is a UNIQUE name, and not an identifier. Distinct client names collide: "a/b" and "a_b" both answer "a_b", every unusable name answers fallbackFilename, and a case-insensitive host (APFS by default) folds "Report.pdf" into "report.pdf". A caller that names a stored file by this component alone lets one upload silently overwrite another — storage keys by the canonical-shape-checked attachment_id and treats this as display material at most.

Do NOT call this on AttachmentChunkPayload.AttachmentID. Sanitising an id changes which attachment is addressed and a mangled id passes silently where a check would reject; the id's contract is a canonical-shape check on conversations.ValidID's precedent, per AttachmentChunkPayload's SECURITY block.

This is also not the enforcement point for the wire bound. An over-long filename is truncated here, never refused — protocol's attachment bounds are producer-side contracts with no validator, and refusing the frame outright, if the daemon ever wants to, belongs to the admission pass.

The never-log rule survives this function. Sanitising removes the LOG-INJECTION half of the hazard — the output can forge no log line — but docs/protocol-mobile.md § Attachments bans logging a filename for a second, independent reason: a filename is often private in itself. The output is no more loggable than the input.

func Store

func Store(dir, filename string, data []byte) (string, error)

Store writes verified attachment bytes into dir under a name derived from the client-supplied filename, atomically, and returns the path it wrote. The bytes are expected to have already matched their declared size and digest — that comparison is Accumulator.Assemble's and is not repeated here.

PRECONDITION: dir must be a path EnsureDir returned. Store TRUSTS it and resolves nothing — every containment guarantee already happened above EnsureDir, and re-deriving the path here would fork the check EnsureDir exists to own. It would also break the same-filename property below, since the per-attachment-id component of that directory is the entire reason two attachments in one conversation can carry one client filename.

The returned path is dir joined with SanitizeFilename's single-component form of filename — which is NOT unique across conversations or attachments, since distinct client names collide and every unusable name answers one fallback. It is safe as a leaf beneath dir precisely because dir is keyed by attachment id; nothing may name a stored file by that component alone.

Idempotent: a second call with the same dir and filename overwrites with no error, so a phone that drops mid-upload and re-sends is not a storage failure. There is deliberately no O_EXCL and no existence pre-check — either would turn an ordinary reconnect into attachment.storage_failed at #1744, which the wire contract marks retryable and which the client would then hot-loop against.

Safe for concurrent use on distinct dir values, which is the only way #1744 can reach it. Two concurrent calls sharing a dir and a filename are last-writer-wins, atomically: each writes its own uniquely named temp file and the renames serialise in the kernel, so a reader sees one complete file or the other, never a mixture.

On any failure it returns ("", err) and leaves no temporary file behind.

LOGGING OBLIGATION on the consumer. The error text names dir, never the sanitised filename — except on the rename path, where os.Rename returns an *os.LinkError whose Error() prints its destination and therefore the sanitised component. docs/protocol-mobile.md § Attachments bans logging a filename for a privacy reason that sanitising does not lift, so #1744 must map this to attachment.storage_failed's STATIC wire message and, if it logs, log the sentinel and the ids rather than the error text. This is ErrNotContained's "safe only because they never reach the wire" note plus that one clause.

Types

type Accumulator

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

Accumulator holds one attachment transfer's chunks, addressed by index, until every index has arrived. Feed it one chunk at a time with Add; ask Assemble whether the transfer is complete and, if it is, for its bytes.

NOT SAFE FOR CONCURRENT USE, and it deliberately carries no mutex. One Accumulator is owned by one session and fed serially: the frames that drive it arrive on relay's appFrameWorker, exactly one goroutine per session with strict FIFO ordering and no two handlers for one conn running concurrently. That is a CALLER OBLIGATION rather than a happy accident. Synchronising the registry of in-flight uploads belongs to Registry, which holds its own mutex across each whole operation, the release path included — never to this type.

func NewAccumulator

func NewAccumulator(totalChunks int, size int64, sha256 string) *Accumulator

NewAccumulator latches the transfer's three declared facts and returns an empty accumulator. It cannot fail: refusing an implausible declaration is CheckDeclaration's job, which runs before this type exists.

Admission runs IN FRONT OF this constructor and does not replace its own safety. This function stays exported and constructible without passing through CheckDeclaration — the error return is the only signal, and no validated type carries the decision here — so nothing below may assume the declaration was ever checked.

The chunk map is created WITHOUT a capacity hint. On the inbound leg totalChunks is an attacker-chosen integer — see the NEVER ALLOCATE FROM A CLAIM block on protocol.AttachmentChunkPayload — and make(map[int][]byte, totalChunks) on a claimed 2^31-1 pre-allocates the bucket array from a single ~60 KB frame, which is that attack wearing a shape the block does not literally spell out. Storage grows with what actually arrives, which is what makes the hint-free map safe standing alone — independently of whether the caller ran CheckDeclaration first.

func (*Accumulator) Add

Add stores one chunk's bytes at its index, or refuses the chunk and discards the transfer. Once refused the transfer stays refused: every later Add and every later Assemble answers with the identical error value, so the offending numbers survive into whatever the dispatch site logs.

The checks run in a fixed order, and the order is part of the contract — a frame carrying two faults yields one deterministic sentinel:

  1. the transfer is already refused → the latched error, verbatim.
  2. the chunk's total disagrees with the declared count → ErrTotalChunksMismatch. First, because a disagreeing count invalidates the frame of reference the range check below uses. This is stronger than the published "disagreeing with the stream's earlier chunks": the comparison is against the latched declaration, so the first chunk of a transfer can be refused for it.
  3. the index falls outside [0, declared count) → ErrIndexOutOfRange.
  4. the index has already arrived → ErrDuplicateIndex. There is no idempotent-retry carve-out: completion is every index arriving EXACTLY ONCE, so a re-send is refused even when it repeats the bytes already held. Accepting it would also let a client probe which indices the receiver holds by observing which re-sends are accepted.
  5. the chunk's bytes would take the held total past maxUploadBytes → ErrUploadTooLarge. This rung sits on the DATA PATH and so cannot be skipped the way the two admission functions can, which is what bounds retained memory even for a caller that ran neither.

Three properties of step 5 are contract rather than preference:

  • LAST, NOT FIRST. received counts only bytes this accumulator actually retains, so the check belongs with the store rather than ahead of the checks that decide whether a store happens at all. Its one observable consequence is which sentinel a frame carrying two faults gets — every unstored chunk rejects the transfer, so a counter that moved for one could never be read afterwards — and placing it last leaves every existing two-fault frame answering the sentinel it answers today.
  • SUBTRACTION, NOT A SUM. received + len > bound forms a sum that could in principle wrap; len > bound - received cannot, because the invariant on received keeps the right operand within [0, maxUploadBytes]. The addend here is a materialised slice length rather than a claimed number, so the wrap is not reachable in practice — the safe form is written anyway, and it is the INVARIANT rather than the unreachability doing the work, so a later reader neither simplifies it back nor concludes that CheckDeclaration's overflow discipline was cargo cult.
  • `>` AND NOT `>=`. A transfer landing exactly on the bound is admitted: the bound is a ceiling on what may be held, not on what may be approached.

Add reads exactly three of the payload's eight fields — Index, TotalChunks and Data — and the omissions are deliberate rather than oversights. AttachmentID is not checked because the caller looks this accumulator up BY it, so a foreign chunk cannot reach here and a check would invent a fourth framing sentinel no rule covers. Size and SHA256 are not checked HERE, because Assemble compares the LATCHED declaration against the assembled bytes rather than anything a chunk restates, so a later chunk carrying a different size or digest changes nothing that is checked — that is the security property, and it is why only a total disagreement is a framing refusal. Filename and MimeType are never read at all.

PRECONDITION: chunk.Data is retained WITHOUT being copied, so the caller must not mutate it, nor decode into a reused buffer, after Add returns. That holds for today's caller because encoding/json allocates a fresh slice for each base64 field. A defensive copy is deliberately not made: it would double peak memory for every upload against maxUploadBytes, whose doc carries that arithmetic.

func (*Accumulator) Assemble

func (a *Accumulator) Assemble() ([]byte, error)

Assemble returns the transfer's bytes once every index in [0, declared count) has arrived exactly once AND the assembled bytes match both facts the transfer declared. It neither consumes nor mutates the accumulator, so an incomplete transfer can be completed by a later Add and assembled then, and a caller may assemble a complete one repeatedly.

A refused transfer never yields bytes, however complete it looks: the latched refusal is returned instead.

ErrIncomplete IS NOT A REFUSAL. It neither latches nor discards, and a later chunk can turn it into bytes. That single difference is why this type is stateful where relay.ReassembleBundle is one pure call taking every frame at once, whose "incomplete" no later frame can revisit.

A declared count below 1 is never complete. Without that clause the exactly-once test is vacuously true for a declared count of zero, and such a transfer would assemble to empty bytes — a success from a declaration the published contract forbids (total_chunks >= 1). It is not a fourth sentinel: no index is admissible for such a transfer, so permanently incomplete is the honest answer, and CheckDeclaration refuses such a declaration once, at admission. That does NOT make this clause newly dead: admission runs in front of this type rather than gating it, and NewAccumulator stays constructible without passing through CheckDeclaration, so this clause is still the only thing standing between such a caller and a vacuous success.

The returned slice is freshly allocated on every call and sized from the SUM OF THE ARRIVED CHUNK LENGTHS, never from the declared size — sizing from a claim is the same attack the constructor's hint-free map avoids. The single-chunk case is deliberately not fast-pathed to the stored slice either: a caller that mutates what it gets back must not be able to corrupt the accumulator or a second caller's copy, and the fresh copy is also what keeps the two checks below from being a check-then-use over aliased memory — THE BYTES VERIFIED ARE THE BYTES RETURNED.

Only once the transfer is complete are those bytes compared against what the transfer declared, per docs/protocol-mobile.md § Attachments, "Reassembly & integrity (the receiver's rules)": the assembled length against the declared size, then its lowercase-hex sha256 against the declared digest. Either mismatch discards the transfer exactly as a framing fault does, and no bytes are yielded — the receiver never emits partial or corrupted output. Both comparisons read the assembled slice itself rather than a proxy computed from the chunk map, so a later regression in the loop above cannot slip past a green check.

THE LENGTH IS CHECKED FIRST, and the order is part of the contract rather than a preference. A digest mismatch is observable on its own — same length, different bytes — while every wrong-length stream also fails the digest, so no fixture can reach the digest check by being the wrong length alone. Checking the length first is what makes ErrSizeMismatch the answer a wrong-length stream gets at all; swapping the two is what the wrong-length row of TestAccumulator_IntegrityFaults_RejectAndDiscard exists to catch.

The digest comparison is EXACT STRING EQUALITY, and softening it is the one change this method must not accept. internal/update's VerifySHA256 is the repo's nearest "bytes against a declared hex digest" comparison and folds case, which is defensible where it lives and a hole here: the published contract calls a case-insensitive or prefix comparison one, in the same sentence that mandates lowercase hex and answers the availability worry by obliging clients to send that form. There is likewise no well-formedness carve-out — an uppercase, truncated, non-hex or EMPTY claim simply loses the comparison — because the claim is attacker-supplied, so skipping the check for some claim value would hand the sender an opt-out from integrity checking while leaving the reject path looking live.

A SUCCESSFUL RETURN IS NOT A SAFETY VERDICT. The same party supplied the bytes and the digest, so a match proves the transfer was not corrupted and proves nothing about whether the content is safe — integrity, not authenticity, as protocol.AttachmentChunkPayload's doc block states. The consumers of these bytes are the readers of that sentence: #1772's filename sanitiser, #1773's storage and #1746's retrieval.

type Intake

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

Intake drives one decoded attachment chunk from admission to stored bytes: the package's composite entry point, and the one thing the wire layer calls. Every primitive it sequences is exported beside it, but the ORDER is not obvious and two steps of it are decisions rather than sequencing taste — the fork and the three-way answer — so this type owns them in one place rather than leaving them to each caller. The destination conversation is NOT one of those decisions: it arrives on Receive already decided and already validated (#2143).

ONE PER DAEMON. maxInFlightUploads is a daemon-wide entry-count ceiling, so a second Intake beside the first would be a second budget of the same size and the bound would no longer mean what it says. That is also why the Registry is OWNED rather than injected: there is exactly one, and publishing a way to hand one in would publish a way to have two.

It maps nothing to the wire. Turning the sentinels it hands back into attachment.* codes and declaring the seam interface this type satisfies are both #1897's, which is also this package's first production caller. Validating the destination conversation before it reaches Receive is #2143's, and it is the CALLER's obligation rather than this type's — see Receive.

It holds no lock of its own and spawns no goroutine, so it has no shutdown path; the Registry's mutex stays a leaf beneath it (see Receive).

func NewIntake

func NewIntake(instanceDir string) *Intake

NewIntake builds the driver over instanceDir.

IT TAKES NO CONVERSATION, and that is the whole of #2143 at this constructor. Until then it held a resolver over the daemon's follow-active cursor and the destination was whatever that cursor said when a transfer completed. The shape was published as a security property — attachment_chunk carried no conversation_id, so a client could not steer bytes into another conversation's directory — and what the omission actually bought was the absence of a field rather than isolation between conversations. It cost two misfiles: an attachment added before a conversation's first message could never be stored at all, because only a successful send_message route stamps that cursor; and a client that sent in A, sent in B and returned to A filed its bytes under B.

The destination is a Receive PARAMETER now, validated by the caller against the daemon's own registry — the same confinement the retrieval leg already used, and the reason a paired client naming a conversation gains nothing by it.

func (*Intake) Receive

func (i *Intake) Receive(connID, conversationID string, chunk protocol.AttachmentChunkPayload) (attachmentID string, stored bool, err error)

Receive routes one decoded chunk of one conn's upload and answers ONE OF THREE THINGS:

  • ("", false, nil) — the chunk was accepted and the transfer wants more. This is what MOST chunks of a healthy upload get, and it is NOT a refusal.
  • (attachment_id, true, nil) — the completing chunk's verified bytes are on the host, filed under the conversation the caller named.
  • ("", false, err) — refused. err is some layer's own sentinel.

So err != nil is the caller's whole refusal test and stored separates the other two: a caller never tests for a particular sentinel to decide what to emit. That shape exists because Deliver reports "accepted, not yet complete" as ErrIncomplete IN AN ERROR POSITION, and it is the one sentinel in this package that neither latches nor discards. A caller reading every non-nil error as a refusal answers the phone a reject code for every chunk of a perfectly healthy upload, so ErrIncomplete is the ONE error this method interprets rather than passes on.

THE FORK. A chunk whose pair the registry does not hold goes through Admit — where the declaration cross-check and both resource bounds live — and one whose pair is already in flight routes to that transfer. The look-up is Lookup, which is a pure read that stamps nothing and reaps nothing, and admission is therefore the ONLY way an entry is ever created on this path: there is no route into the registry that skips CheckDeclaration, CheckDeclaredSize or maxInFlightUploads. First means FIRST TO ARRIVE and never index == 0 — docs/protocol-mobile.md § Attachments publishes that chunks may arrive in any order, deliberately weaker than debug_bundle_chunk's strict seq, so a fork gated on the index refuses a conforming client whose opening chunk carries another one.

The alternative fork — call Deliver and admit on ErrUnknownUpload — is rejected on purpose: it reinterprets a refusal sentinel as a routing decision, and this method reinterprets exactly one error and it is not that one.

ADMIT'S RETURNED ACCUMULATOR IS DISCARDED and Deliver is called with the SAME CHUNK, looking the pair back up. Feeding the returned accumulator directly bypasses every release Deliver owns and re-opens the lockout for single-chunk transfers, which is the sequencing constraint the package overview states.

NOTHING HERE WRAPS, ANNOTATES OR REINTERPRETS A REFUSAL. Every error out of this method is another function's verbatim, so errors.Is reaches ErrInvalidDeclaration, ErrUploadTooLarge, ErrTooManyUploads, the six accumulator sentinels, ErrInvalidID, ErrNotContained and ErrWriteFailed unchanged, and the numbers each one wrapped survive with them.

ErrUnknownUpload is not reachable on a single-feeder path — a chunk either finds its transfer or has just admitted one — but it is not impossible either, and when it happens it travels out verbatim like the rest. Two third parties can empty the pair between the look-up and the delivery: ReleaseConn on the teardown goroutine, and uploadIdleTimeout's lazy reap firing inside Deliver's own look-up. Both mean the transfer is genuinely gone. A chunk arriving for an already-reaped pair takes the other branch instead and is admitted as a fresh transfer, which is the honest reading of "no transfer in flight": the reap already returned the slot, so nothing leaks, and the restarted transfer completes only if the client re-sends every chunk.

THE DESTINATION IS conversationID, AND ITS VALIDATION IS A PRECONDITION, AND IT IS THE CALLER'S — the contract V2SessionConfig.HistoryPage states in the same words for the same reason. conversationID MUST already have passed the daemon's KnownConversation membership check, because it becomes a path component below this method; handleAttachmentChunk is the caller that discharges it, on EVERY chunk rather than only the completing one, so a transfer naming an unusable conversation dies on its first frame instead of after every byte has crossed the wire. Nothing is re-validated here.

EnsureDir's conversations.ValidID check is the remaining fail-closed backstop and NOT the gate: it refuses the empty id and any non-canonical one with ErrInvalidID before it touches the filesystem, so a caller that skips the membership check still cannot escape the instance directory — but it CAN file bytes under a canonical id the daemon does not host, which is why the precondition is a contract and not merely advice. That check was belt-only while the id came from the daemon's own cursor; from #2143 the value is client-authored and the check is load-bearing.

conversationID is a STRING and not a conversations.ConversationID, which is the seam's typing rather than an oversight: internal/relay does not import internal/conversations — only internal/relay/handlers does — and KnownConversation is primitive-typed on purpose to keep it that way. Converting to the typed id is this package's side of the seam, at the EnsureDir call below.

IT IS FIXED BY THE TRANSFER'S FIRST CHUNK AND NO LATER CHUNK MAY MOVE IT (#2146). The registry latches the destination on the first chunk it delivers and compares every later one against it, so a phone that switches conversations mid-upload is REFUSED with ErrConversationMismatch rather than having its attachment filed under whichever conversation its completing chunk happened to name. Until then the id was read on the completing chunk only, and a transfer declared against A could complete against B.

The refusal costs the client ONE CHUNK AND NOT THE TRANSFER: the incumbent keeps its accumulator, its entry and its idle stamp, so a client that goes back to naming the original conversation resumes where it was. That posture is Admit's own for a repeat whose declaration disagrees with the live transfer, and the stamp half of it is load-bearing rather than tidy — a refusal that stamped would let a client hold a slot open indefinitely by spamming mismatching chunks.

THE LATCHED VALUE AND THE DIRECTORY THE BYTES LAND IN ARE ONE VALUE BY CONSTRUCTION, and the line below is what makes it so rather than a caller obligation: conversationID — the argument, already validated — is stamped onto the local copy of the chunk handed to the registry, so what the transfer latches is exactly what EnsureDir resolves. The chunk arrives carrying the client's own conversation_id in that field and the two agree at the one production call site, but agreeing is not the same as being the same value, and a check guarding a value that is not the one becoming a path component would guard nothing. The assignment touches only this frame's copy; chunk is a value parameter.

It is NOT the destination that is compared against the registry's membership list a second time — that is the caller's, discharged per chunk, and this check is a CONSISTENCY one between two ids that have both already passed it. Two valid conversations disagreeing is what it detects; #2143 owns the boundary and EnsureDir owns confinement.

A refusal on the completion half arrives AFTER the transfer is over: Deliver released the entry and the bytes assembled cleanly, so no slot leaks and the client must re-upload. Two conns uploading under one attachment_id into one conversation resolve to the SAME directory and stored name and are last-writer-wins, atomically — which corrects the clause in Store's doc assuming the dispatch site can only ever reach it with distinct dirs. It is not a privilege boundary: both conns are already-paired devices of one account, the id is client-chosen and published as not-a-capability, and separating them would need a per-conn path component retrieval does not address by.

THE ANSWER NAMES THE ATTACHMENT AND NOTHING ELSE. It is the client's own id, echoed, which is the whole of AttachmentStoredPayload's single field. Store's returned path is DISCARDED deliberately: it embeds the sanitised filename, and that payload's doc block names reaching for it as the natural wrong move. The success answer carries no bytes, no filename and no digest, and it cannot — it is a string and a bool.

THERE IS NO FORMAT STRING IN THIS BODY, which is how the never-log rule protocol.AttachmentChunkPayload's SECURITY block states stays structural at the second function in this package holding all four of the strings it bans; Deliver is the first and makes the same argument. LOGGING OBLIGATION ON THE CONSUMER, inherited from Store and repeated here because this is where it crosses out of the package: Store's rename leg wraps an *os.LinkError whose Error() prints its destination and therefore the sanitised filename, so #1897 must map it to attachment.storage_failed's STATIC wire message and, if it logs, log the sentinel and the ids rather than the error text. EnsureDir's refusals likewise carry host paths and the daemon's own conversation id, which are operator-log material the same static mapping keeps off the wire.

PRECONDITION: exactly ONE GOROUTINE AT A TIME may call this for a given conn. It is Admit's and Deliver's precondition, inherited rather than re-derived, because both hand an *Accumulator back off-lock and Accumulator carries no mutex by design. #1897 discharges it — relay spawns exactly one appFrameWorker per session — and ReleaseConn is the documented exception to it. Distinct conns are safe concurrently: the conn is in the registry key, and EnsureDir and Store are both safe for concurrent use on the distinct destinations that follows.

It TAKES NO LOCK. The Registry takes its own for each call, and none is held across EnsureDir or Store, so the mutex stays a leaf at the first call site to put filesystem I/O on the same path as it.

func (*Intake) ReleaseConn

func (i *Intake) ReleaseConn(connID string)

ReleaseConn drops every upload still in flight for one conn, so a phone that goes away holds none of the daemon-wide capacity. It is the other half of the seam #1897 names, and a no-op for a conn holding nothing.

IT CARRIES NO SINGLE-FEEDER PRECONDITION, unlike Receive. ReleaseConn on the Registry is remove-only and touches no accumulator, so it is meant to run on the teardown goroutine rather than on the one feeding that conn's frames — a teardown that had to join the frame worker first would need a lifecycle this package does not own.

A teardown landing between Receive's Deliver and its Store still files those bytes: they were authenticated and integrity-checked before the conn went away, and cancelling mid-store would need a context this seam does not have.

type Registry

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

Registry holds the attachment uploads currently in flight, one entry per conn-and-attachment_id pair — that pair's *Accumulator, the time a chunk last arrived for it, and the conversation it was admitted under — and SYNCHRONISES ITSELF rather than documenting a caller obligation the way Accumulator does.

The map's value is a struct held BY VALUE rather than a *entry. A pointer would let any in-package caller keep the entry after a look-up returned and read or write lastChunkAt with mu released; a value forecloses that structurally, since the stamp can then only change by storing into the map and the map can only be written under mu. That is uploadKey's own argument for being a struct rather than a concatenated string — foreclose it in the type instead of documenting a caller obligation — and the cost is one small copy per map read, bounded by maxInFlightUploads entries.

mu is taken once per operation and held for that whole operation, never once to look up and again to write. That is more than race-freedom: a registry splitting the two still tells two concurrent inserts of one pair that both were fresh, and it is the exact shape the count-then-admit gate (#1796) cannot be built on, whose "the registry holds exactly the uploads it held before the chunk arrived" needs look-up-then-count-then-insert to be indivisible. The precedent is sessions' Pool.capMu, whose doc names the sequence it serializes so a later caller re-uses it rather than wrapping it; the sequence this one serializes is check-the-declaration-then-check-the-pair-then-write-the-map, and the maxInFlightUploads gate re-uses that one acquisition rather than wrapping it in a second lock of its own.

mu is a LEAF: never held across a call into Accumulator — not Add, not Assemble — and never nested with another lock. NO METHOD TAKES mu AND THEN CALLS ANOTHER THAT TAKES IT, because sync.Mutex is not reentrant: the eight locked methods — Admit, insert, Lookup, lookupAndStamp, Release, ReleaseConn, count and lastChunkAt — take mu for their whole body and never call one another. THREE methods here take no lock, and the third is a second member of the first of the two OPPOSITE reasons rather than a third reason. insertLocked and reapExpiredLocked both run with mu held BY THEIR CALLERS: that is what lets Admit and insert run ONE critical section rather than two copies free to drift, and what lets the reap share the acquisition insertLocked's capacity gate and lookupAndStamp's map read already hold, which a reap taking mu itself could not. The Locked suffix is this repo's signal for a caller-holds-the-lock body, as in sessions' saveLocked. Deliver holds mu at NO POINT: it composes lookupAndStamp and Release, each of which takes it for its own whole body, and feeds the accumulator between them off-lock. That composer breaches nothing above — "no method takes mu and then calls another that takes it" is satisfied by a method that takes it never — and it is what keeps the feed off-lock while the entry accounting stays inside this type. The maxInFlightUploads gate keeps it that way: a count read under one acquisition followed by an insert under another does not deadlock, it is the split lock above, which is why the enforcing check lives inside the section Admit already holds and reads len(uploads) directly rather than calling count.

Feeding happens OFF-LOCK: the caller takes the *Accumulator back and feeds it with mu released. That is sound BECAUSE the key carries the conn — relay spawns exactly one appFrameWorker per session, whose own doc records that no two handlers for one conn run concurrently — so exactly one goroutine can ever reach any one accumulator, which preserves Accumulator's mutex-free contract rather than quietly widening it.

THE CLOCK IS A SEAM, and it is read WITH mu HELD at every site: the admission store in insertLocked, the delivery stamp in lookupAndStamp, and once per pass in reapExpiredLocked, which each of those two bodies runs inside its own acquisition. So the reading and the store it lands in are one critical section and two stampers of one pair cannot commit out of order. That is the type's only call out to a caller-supplied function under its only mutex, and the three constraints it puts on that function are stated where one can be supplied: newRegistryWithClock. The single lock order is Registry.mu → whatever the clock locks, never the reverse, which is a total order only because the clock never calls back in. The stamp itself is never read off-lock, and holding the map value by value rather than by pointer is what makes that a property of the type instead of a caller obligation.

func NewRegistry

func NewRegistry() *Registry

NewRegistry returns an empty Registry reading the REAL WALL CLOCK, and is the only construction path outside this package's tests. The clock-taking way in is newRegistryWithClock, which this delegates to with a nil clock rather than building a Registry of its own, so the nil substitution exists in one place.

func (*Registry) Admit

func (r *Registry) Admit(connID, attachmentID string, totalChunks int, size int64, sha256 string) (*Accumulator, error)

Admit is the registry's only exported way in: it runs BOTH declaration checks on a first chunk and, only on a nil answer from both, constructs the Accumulator from the declared numbers and offers it to insertLocked, which stores it unless the pair is held or the registry is at maxInFlightUploads. EVERY refusal stores nothing, so the registry is left exactly as it was and nothing about the refused pair is remembered — no id is blacklisted, and the same attachment_id is admitted as soon as it carries an admissible declaration and there is a free slot: immediately for a declaration refusal, which never took one, and on the next Release for a capacity refusal.

THE WHOLE DECISION RUNS UNDER ONE ACQUISITION of mu — declaration verdict, construction, the idle reap, incumbent look-up, capacity, store, in the order the bodies run them — so the entry cap reads the count and admits without releasing it in between, which is what a cap needs and what a split acquisition cannot give it. mu stays a LEAF: both checks are pure and stateless per their own docs, insertLocked takes no lock, and NewAccumulator allocates and returns. That last one is bounded work only BECAUSE its chunk map takes no capacity hint — a rule stated there on independent grounds that this critical section now depends on, since a hint read from the attacker-chosen totalChunks would put an attacker-scaled allocation inside this package's only mutex. All four return paths release mu through the one defer: three of them are refusals a client triggers at will — two with a single malformed declaration, one by holding the bound's worth of transfers open — and an explicit unlock missed on any would wedge the registry for every conn rather than race.

AT CAPACITY NewAccumulator STILL RUNS and its result is dropped, deliberately and cheaply. Checking capacity here, ahead of the construction, would have to redo insertLocked's incumbent look-up to keep a held pair exempt, reaching into r.uploads from a method that does not touch it today; the dropped allocation is bounded for the reason above, and the whole decision stays in one acquisition.

It CONSTRUCTS NO ERROR OF ITS OWN. Each refusal is another function's error verbatim, neither wrapped nor annotated here — a check's, or insertLocked's capacityRefusal. That remains the never-log rule protocol.AttachmentChunkPayload's SECURITY block states at a function that necessarily holds two of the four strings that rule bans: there is no format string in this body for attachmentID or sha256 to enter, and the one format string the admission path now has lives in capacityRefusal, whose only parameter is an int and which therefore cannot see either. The other two, Filename and Data, are excluded structurally instead, by taking the declaration as scalars the way NewAccumulator and CheckDeclaration do — decoding a payload into them is the dispatch site's job (#1744). errors.Is therefore reaches ErrInvalidDeclaration and ErrUploadTooLarge unchanged through here, and the numbers each check wrapped survive verbatim.

WHICH CHECK RUNS FIRST IS NOT A CONTRACT. A doubly-bad declaration gets whichever sentinel runs first, and nothing has decided which that should be; CheckDeclaration runs first because it mirrors the file order, so no caller and no test may read an order out of it. WHERE THE CONCURRENCY BOUND SITS IS A CONTRACT, and it is BEHIND both of them, in insertLocked and behind the incumbent look-up: at capacity, a first chunk whose declaration is also invalid answers the declaration sentinel, so a client is told the fault that will never clear ahead of the one that clears by itself. That is the only ordering pinned here — which of the two declaration checks runs first stays undecided.

A NIL ERROR CERTIFIES THE TWO NUMBERS AND NOTHING ELSE. Not the attachment_id, whose canonical-shape check before it may become a path component is EnsureDir's (#1781), and not the declared digest, which is copied into the accumulator uninspected and compared only by Assemble.

BOTH CHECKS RUN ON A REPEAT under a pair already held, ahead of the look-up that finds the incumbent, and that is a DECISION rather than an accident of statement order. A repeat whose declaration disagrees with the live transfer is a client error worth naming, so it answers its own sentinel and the incumbent is left untouched; handing back the incumbent instead would answer an accumulator latched with the FIRST declaration's numbers, which that client's next chunk fails to feed anyway. It also keeps the capacity gate honest — exempting a held pair from a capacity REFUSAL is not the same thing as short-circuiting the checks. TestRegistry_AdmitRefusedRepeatUnderAHeldPair_KeepsTheIncumbent pins it.

AN ADMISSIBLE REPEAT answers the INCUMBENT with a nil error and drops the accumulator just built, because insertLocked never replaces. The caller then feeds the repeat's first chunk into an accumulator latched with the FIRST declaration's numbers, so Add refuses it — ErrTotalChunksMismatch when the two declarations disagree on the count, ErrDuplicateIndex when they agree — and that transfer is rejected. Which is the point: the numbers a transfer was admitted under can never be swapped underneath bytes it already holds.

PRECONDITION on what comes back: the accumulator is fed by ONE GOROUTINE AT A TIME. Admit releases mu before returning and hands the accumulator back off-lock, and Accumulator carries no mutex by design; that is sound because the conn is in the key and relay spawns exactly one appFrameWorker per session. Two Admit calls for one pair hand back the SAME POINTER, so two goroutines feeding one pair is a data race rather than two transfers.

func (*Registry) Deliver

func (r *Registry) Deliver(connID string, chunk protocol.AttachmentChunkPayload) ([]byte, error)

Deliver routes one chunk to the transfer in flight for its pair and answers the transfer's assembled bytes once they are complete and verified. It is the counterpart to Admit: Admit takes the slot, this gives it back, so maxInFlightUploads bounds LIVE transfers rather than counting a lifetime quota. Named for the custodial register the rest of this type uses (Admit, Lookup, Release) rather than Add, which is Accumulator's and would be ambiguous at every call site across two types in one package.

The steps, in the order the body runs them:

  1. look the pair up, CHECK THE CHUNK AGAINST THE TRANSFER'S DESTINATION AND STAMP IT — a chunk has arrived for it. On a miss, ErrUnknownUpload and NOTHING IS STORED: lookupAndStamp creates no entry and stamps none, and neither does this path. On a chunk naming a different conversation than the transfer was admitted under, ErrConversationMismatch verbatim and NOTHING IS STORED EITHER — the incumbent keeps its accumulator, its entry and its idle stamp. That refusal returns HERE, ahead of step 2, so the accumulator is never fed and the pair is never released; it is the only refusing outcome in this method that leaves the transfer alive.
  2. feed the accumulator off-lock. On ANY non-nil answer from Add, release the pair and return that error verbatim.
  3. assemble. Keep the entry when — and ONLY when — the answer is ErrIncomplete, and return it verbatim.
  4. every other outcome releases, the nil-error one included: the assembled bytes on success, the latched refusal on an integrity mismatch.

THE STAMP SITS AT THE LOOK-UP rather than after Add accepts, and the two are observationally identical. The entry survives exactly ONE of the four outcomes above — Assemble answering ErrIncomplete — and on that one Add had already accepted, so "a chunk arrived" and "a chunk arrived and was accepted" agree wherever the stamp can still be read; every other outcome releases the entry and takes its stamp with it. Stamping after Add would buy nothing and cost a third acquisition of mu.

THE KEEP CASE IS THE ALLOW-LIST AND THAT POLARITY IS THE CONTRACT. Written the other way — enumerate the refusals that release — a further latching answer added to Assemble later would silently leak a slot per corrupt transfer, which is exactly the lockout this method exists to remove. Same polarity on the Add leg: every non-nil answer from Add latches, so err != nil is the release condition rather than a list of four sentinels.

THE KEY COMES OUT OF THE CHUNK, not from a second parameter beside it. Two ids in one call can disagree, and a caller passing the wrong one would route this chunk's bytes into a DIFFERENT transfer's accumulator with nothing downstream to catch it, since Add reads neither the id nor the declared size or digest. One id in play forecloses that structurally, and it is what turns Add's claim that a foreign chunk cannot reach it from a caller obligation into a property of this package. connID stays a scalar because it is not on the wire: it is the receiver's own name for the conn the frame arrived on, and it is the half of the key that makes a client-chosen attachment_id safe to key on at all.

ASSEMBLE RUNS AFTER EVERY ACCEPTED CHUNK, not only the last, and that is cheap by construction: its completion check answers ErrIncomplete before allocating or hashing anything, so only the completing chunk pays for the copy and the digest.

It TAKES mu AT NO POINT. lookupAndStamp and Release each take it for their own whole body and the accumulator is fed between them with the lock released, so AT MOST TWO acquisitions per delivered chunk — one on a miss, one on a destination mismatch and one when Assemble answers ErrIncomplete, since none of the three releases; two on every path that does release, which is any non-nil answer from Add, an integrity mismatch, and the completing chunk. Never three: nothing on this path calls Admit, and the destination check runs INSIDE lookupAndStamp's own acquisition rather than as a locked method beside it — a separate compare would make three, and mu is not reentrant. mu stays a LEAF — never held across Add or Assemble, which is the rule Registry's type doc states and which this method must not be the first to break. The gap between the look-up and the release is not a TOCTOU hole: the conn is in the key and relay spawns exactly one appFrameWorker per session, so exactly one goroutine can reach any one accumulator. That is the same precondition Admit already hands its accumulator back under, inherited here rather than re-derived.

It CONSTRUCTS NO ERROR OF ITS OWN: ErrUnknownUpload bare, everything else another function's verbatim. There is no format string in this body, which is how the never-log rule protocol.AttachmentChunkPayload's SECURITY block states stays structural at the one function in this package that holds ALL FOUR of the strings that rule bans — AttachmentID, Filename, SHA256 and Data. There is nothing to add anyway: the pair is the caller's own two values.

Three consequences worth stating, because each is a question a reader would otherwise have to re-derive:

  • reject's LATCH STAYS LOAD-BEARING and must not be touched. Release recovers the ENTRY; reject recovers the MEMORY, at the moment of refusal, and is the only thing that does. A refused accumulator is simply no longer reachable through the registry once this method has released it.
  • A CHUNK ARRIVING AFTER A REFUSAL ANSWERS ErrUnknownUpload, not the latched sentinel, and that is correct: the latch exists so one LIVE transfer cannot produce two contradictory diagnoses of its own bytes, and after release there is no transfer left to diagnose. "No such transfer" is a statement about the registry, not a second verdict on the bytes.
  • A RE-ADMITTED PAIR IS A NEW TRANSFER and a straggler from the old one cannot corrupt it. The same attachment_id may be admitted again the moment its slot is free — no blacklist — so a late chunk can land in the successor's accumulator, and because Assemble compares the declared size and digest against the WHOLE assembled slice, the only reachable outcome is that the client's own new transfer fails its own integrity check. Cross-client contamination is foreclosed a level up, by the conn being in the key.

A STALLED UPLOAD EXPIRES, so an entry can vanish between this method's look-up and its release — reaped by lookupAndStamp's own head, or by a concurrent Admit — and both halves are safe: Release on a pair the registry no longer holds is a documented no-op, and a look-up that misses answers ErrUnknownUpload, the honest answer for a transfer that has been reaped. The window is uploadIdleTimeout, measured from the last chunk this method routed.

func (*Registry) Lookup

func (r *Registry) Lookup(connID, attachmentID string) (*Accumulator, bool)

Lookup answers the transfer in flight under the pair, comma-ok. Presence comes from map-key membership and never from the stored value. It is a PURE READ, for #1744's dispatch site and for diagnostics; Deliver's own look-up is lookupAndStamp, and it is THAT method's bool — not this one — that becomes "chunk for an unknown transfer", ErrUnknownUpload.

IT DELIBERATELY DOES NOT STAMP. A look-up that moved the entry's lastChunkAt would let a diagnostic, or a dispatch-site read that routes no bytes at all, keep a dead upload alive indefinitely — the exact slot-exhaustion path uploadIdleTimeout closes, and that window is what makes the hazard load- bearing rather than merely untidy, since the stamp is the reap's only input. Only a chunk that actually arrived may move that time, which is why the stamping look-up is a second method rather than a flag on this one.

IT DOES NOT REAP EITHER, so a true answer may name an entry the next Admit or Deliver will reap. That is the same polarity as the paragraph above — a look-up that reaped would be a look-up with a side effect — and it is consistent with uploadKey's "MEMBERSHIP CERTIFIES NOTHING": the authoritative answer to whether a chunk may resume a transfer is Deliver's, which reaps before it looks.

func (*Registry) Release

func (r *Registry) Release(connID, attachmentID string)

Release removes exactly the pair's entry, leaving another conn's transfer of the same attachment_id untouched; releasing a pair the registry does not hold is a no-op. It returns nothing because Deliver releases what it just looked up and #1744, the caller that decides when this and ReleaseConn are called, wants no answer either, so a presence answer would only invite a caller to branch on it outside the lock, where it is already stale.

THE CONN-WIDE RELEASE IS ReleaseConn AND IS NOT BUILT ON THIS METHOD. A teardown path holds the conn and never the attachment_ids that conn was admitted under, so it is a SIBLING beside this one rather than a caller looping over it, and it deletes directly under its own acquisition for the same non-reentrancy reason the reap does.

THE IDLE REAP IS NOT BUILT ON THIS METHOD either, and a reader must not expect it to be: this one takes mu and sync.Mutex is not reentrant, so a reap running inside a body that already holds it would deadlock rather than race. reapExpiredLocked deletes directly under its caller's acquisition instead.

func (*Registry) ReleaseConn

func (r *Registry) ReleaseConn(connID string)

ReleaseConn removes every upload the conn holds and NOTHING ELSE, leaving another conn's transfer of the same attachment_id in flight; a conn holding none is a no-op. It is the way in that a teardown path needs and Release cannot give it: that path holds the conn and never the list of attachment_ids the conn was admitted under, so composing Release per pair would oblige the caller to keep a shadow copy of this type's own bookkeeping.

THE PREDICATE IS EXACT EQUALITY ON THE CONN HALF OF THE KEY — no trimming, no folding, no prefix match, and no validation of connID — and both halves of that are load-bearing. A fold or a prefix match would let one conn's teardown remove another conn's entries, which is the isolation the key exists for defeated in the predicate rather than at the key. And it must accept EXACTLY WHAT Admit STORES, which stores the connID it is handed verbatim and unvalidated: a normalising release would refuse to remove an entry Admit had happily stored, leaving it permanently unreleasable, which is a slot leak. Validating the conn namespace is not this type's job — connID is the receiver's own name for the conn and never appears on the wire, which is what makes a client-chosen attachment_id safe to key on at all.

IT DOES NOT REAP, like Release and Lookup and unlike Admit and Deliver. The reap exists to protect a DECISION — insertLocked's capacity gate must not count dead entries, lookupAndStamp must not resume an expired transfer — and this body decides nothing, it removes unconditionally, so there is no verdict a stale entry could corrupt. Nothing is lost by walking past one: it is taken by the very next Admit or Deliver, the only two bodies whose correctness depends on its being gone. It also keeps the clock out of a body that otherwise needs none. TestRegistry_ReleaseConnHoldingNothing_ChangesNothingAndDoesNotReap is the sole red for a reap added here, and it is what keeps the decision measured rather than satisfied by construction.

IT TAKES mu ITSELF AND DELETES DIRECTLY, and MUST NOT be built on Release: that one takes mu and sync.Mutex is not reentrant, so a per-pair loop over it would DEADLOCK rather than race — and a deadlock is not something -race reports, which is why this is a constraint and not a preference. It is the same rule reapExpiredLocked's doc states from the other side. There is no releaseConnLocked core, because insertLocked and reapExpiredLocked are lock-free cores only where TWO bodies share one; nothing shares this one, and a Locked variant with a single caller would publish a seam no one asked for. It joins the locked roster as the EIGHTH member — see Registry's type doc, whose leaf rule this satisfies unchanged.

ONE PASS AND NO KEY-COLLECTION SLICE, reapExpiredLocked's precedent: deleting from a map while ranging over it is defined, and an entry deleted before the iteration reaches it is simply not produced. THE PASS IS BOUNDED BY maxInFlightUploads, which is what makes an O(len(uploads)) sweep under this package's ONLY mutex safe rather than one conn's teardown stalling every other conn's admissions and deliveries. That bound is #1796's gate in insertLocked making "the registry never holds more than maxInFlightUploads" a property of the CONTAINER rather than of one entry point, so this is at most four comparisons however many entries the conn holds — a real dependency, and a later ticket that lifts the cap lifts this sweep's cost with it.

IT CALLS NOTHING ON Accumulator, and never reject, verbatim the rule reapExpiredLocked states. Dropping the map entry drops the registry's last reference and the bytes become collectable; reject is an UNLOCKED mutator on a type that carries no mutex by design, and mu does not cover an accumulator — a pointer to one may already be held off-lock by a goroutine that took it from Admit, Lookup or Deliver — so a reject from here would be a data race and not merely a leaf breach.

IT IS SILENT AND RETURNS NOTHING. The map key holds the client-chosen attachment_id, one of the four strings protocol.AttachmentChunkPayload's SECURITY block bans from ever reaching a log or an error string, so there is no logger and no format string in this body and the rule stays structural. The absent return is Release's own reason rather than a privacy one — a COUNT would be injection-free, since an int cannot carry an attachment_id — namely that an answer here invites a caller to branch on it outside the lock. #1744 is where a released-count would be added, if it turns out to have an operator log line that wants one.

IT IS THE FIRST REMOVER MEANT TO RUN ON A GOROUTINE OTHER THAN THE ONE FEEDING THAT CONN'S ACCUMULATORS, and that is the point: a teardown that had to join the conn's frame worker first would need a lifecycle this package does not own. It is safe for reapExpiredLocked's already-recorded reason — this body is REMOVE-ONLY. A Deliver sitting between its look-up and its release holds a pointer this may drop from the map; its Assemble still returns integrity-verified bytes or none, and its Release is a documented no-op on an already-absent key. Nothing here touches the accumulator, so the one-appFrameWorker-per-conn precondition — which is about who FEEDS an accumulator — is neither used nor weakened. This adds a SECOND third party to the one that paragraph names: alongside another conn's Admit, the teardown goroutine for your OWN conn. The residual stated there is unchanged — a late Release deletes BY KEY and would take a successor's entry had the pair been re-admitted in the gap — and whether a conn id can be reused across a teardown is a question about the call site, so #1744's rather than this primitive's.

Jump to

Keyboard shortcuts

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