Annotation store — contract¶
The post-implementation contract for iiiris's W3C Web Annotation Protocol
store (roadmap Phase 3a). Operator how-to lives in
../annotations.md; this file is the durable "what this
subsystem guarantees" a re-implementation must satisfy.
Reference: W3C Web Annotation Protocol — https://www.w3.org/TR/annotation-protocol/
What it does¶
iiiris optionally hosts Web Annotations durably, as LDP Basic Containers of
annotations served as paged AnnotationPages, with create / replace / delete
over HTTP. Derived Presentation 3.0 manifests reference each canvas's
container so viewers display the annotations, and the bundled Mirador can
edit them through an IIIF Auth session. Off by default.
Surface¶
HTTP routes¶
| Method | Path | Purpose |
|---|---|---|
| GET, HEAD | /annotations/{container}/ |
The container (first page embedded by default); ?page=N serves AnnotationPage N (0-based) |
| POST | /annotations/{container}/ |
Create an annotation → 201 + Location + ETag + body |
| GET, HEAD | /annotations/{container}/{id} |
One annotation |
| PUT | /annotations/{container}/{id} |
Replace (requires If-Match) |
| DELETE | /annotations/{container}/{id} |
Delete (requires If-Match) → 204 |
| OPTIONS | both shapes | CORS preflight + Allow / Accept-Post |
Container names match ^[A-Za-z0-9_-]{1,240}(~[0-9]{1,9})?$; annotation ids
match ^[a-z0-9-]{1,64}$. Anything else is 400.
Config¶
annotations:
enabled: false # default off; requires dir
dir: "" # durable filesystem dir
write_token: "" # Bearer token for writes; empty ⇒ no token writes
write_profile: "" # auth.profiles key whose session authorizes browser writes
max_bytes: 262144 # request body cap
page_size: 100 # annotations per AnnotationPage
Env: IIIRIS_ANNOTATIONS_{ENABLED,DIR,WRITE_TOKEN,WRITE_PROFILE,MAX_BYTES,PAGE_SIZE}.
write_token is redacted in printed config. Server wiring: Deps.Annotations
(annostore.Containers), AnnotationsPageSize, AnnotationsMaxBytes,
AnnotationsWriteToken, AnnotationsSessionUser, AnnotationsWriteProfile.
Public Go API — internal/annostore¶
Containers interface (Create / Get / Replace / Delete / Page),
ContainerFS implementation, Entry, Page (with Revision), and the
errors ErrNotFound, ErrExists, ErrPrecondition, ErrInvalidName. The
older Store (Put/Get) used by the Content State bookmark store lives
beside it.
On-disk format¶
Each container lives in {dir}/{cdir}, where cdir is the first 32 hex
characters of the SHA-256 of the container name. Names that differ only in
case are different containers (they decode to different image identifiers),
and a hashed directory keeps them apart on case-insensitive filesystems (the
macOS and Windows defaults) too. In it: {id}.json (the annotation as
stored, without id or @id), {id}.owner (the session user that created
it; absent when none, never served), .index (ordered ids, one per line),
.rev (the container revision) and .name (the container name, written
before any annotation). Create appends to .index;
Delete rewrites it atomically. Only newline-terminated lines count: an
unterminated last line (an interrupted append) is ignored and cut off by the
next append. An annotation exists exactly when .index lists it; a body it
doesn't list (left by an interrupted Create or Delete) is not served,
replaced or deleted, and Create of its id overwrites it.
At startup the store moves each directory named by its container (the
layout before hashed names) to its hashed name, taking the name from the
directory listing, so its case is the one stored. .name is written before
the rename, so an interrupted move finishes on the next start. A directory
whose .name hashes to its own name has already moved; one with no .index
holds nothing and is left alone. Startup fails if the hashed name is already
taken.
Derived manifest reference¶
With the store enabled, each canvas of a derived v3 manifest carries
annotations: [{id: "{base}/annotations/{ImageContainer}/?page=0", type:
"AnnotationPage"}], where ImageContainer(imageIdentifier) =
base64url-raw(imageIdentifier) of the Image API identifier the canvas
paints, omitted when the encoding exceeds 240 characters.
Containers are keyed by image: adding, removing, reordering or failing to
probe other images leaves an image's container unchanged. Renaming or moving
the image file changes its identifier and so its container; the store does
not detect or migrate this. Clients find a canvas's container from this
reference and must not derive it from the canvas id (canvas ids stay
positional, {manifest}/canvas/{n}).
Targets follow the image. Because canvas ids are positional, a stored
target can name a canvas that now paints another image. When serving an
image-keyed container (its name decodes to an image identifier
{dir}/{file} whose v3 manifest has a canvas whose annotations reference
names the container), target references of the form
{any origin}{path of that manifest}/canvas/{k}[#fragment] (a target string,
or a source, id or @id string, recursively through target objects and
arrays) are served with k replaced by that canvas's number. The rest of
each reference, including the fragment, is unchanged; stored bytes are not
modified (the served JSON is re-serialised, so key order and escaping may
differ). A target naming two or more different canvases of that manifest is
served as stored, not collapsed onto one. Other containers and other
references are served as stored.
The manifest is the v3 document viewers get for the request's public base: the manifest cache entry when present, else derived and written to the manifest cache under the same key and with the same body as the Presentation route. A directory the hook redirects has no canvas. Each directory's image-to-canvas map (including "none") is reused for up to 10 seconds, so targets follow an image list change within that time. Concurrent requests that miss the map for one directory share one build. The map holds at most 1024 directories; a full map drops expired entries, else one entry, to make room.
Contracts¶
- Protocol conformance. Containers are
BasicContainer+AnnotationCollectionwithLinkheaders forldp:BasicContainerandldp:constrainedBythe protocol; annotations carryldp:Resource.Accept-Postadvertises the annotation media type. Every annotation, page and container isapplication/ld+json; profile="http://www.w3.org/ns/anno.jsonld". - Prefer. The container honours
oa#PreferContainedIRIs(page items as IRIs),oa#PreferContainedDescriptions(items inline; the default) andldp#PreferMinimalContainer(no embedded page), each only when listed in theincludeparameter of areturn=representationpreference (anyPreferheader); IRIs underomitselect nothing. Theldp#PreferContainedIRIsspelling is accepted as an alias.Vary: Accept, Prefer. - Never-written containers are empty, not missing. A valid container name
that has no annotations returns 200 with
total: 0. - Ids follow the request's public base. Stored bodies carry no
id; the server injects the annotation IRI (honouringX-Forwarded-*) on every read and write response. The server setsid,createdandmodified(RFC 3339 UTC, millisecond precision); client values forid, a top-level@idandcreatedare discarded andcreatedsurvives replace. - Validation. A write body is a JSON object whose
@contextis or includes the anno context, whosetypeis or includesAnnotation, and which has atarget; otherwise 400. Bodies overmax_bytesare 413. - Conditional writes are mandatory. PUT and DELETE without
If-Matchare 428; a non-matching value (including*, weak validators and lists) is 412. Annotation ETags are strong (a hash of the stored bytes). For an image-keyed container whose targets are rewritten, the served ETag (on GET and on POST/PUT responses) is a hash of that and the current canvas (its manifest path and number, not the host), so it changes when the image moves. For such a containerIf-Matchmust be the served ETag of the current version; any other value, including the bare stored-bytes hash, is 412. - Container and page ETags derive from a per-container revision that
changes on every create / replace / delete (it includes the annotation
count; a write whose revision update fails still succeeds and is logged),
the page number and size, the
current canvas targets are pointed at (if any), and the representation
variant (container: descriptions / IRIs / minimal; page:
descriptions / IRIs), so no two
Prefervariants share a validator; noLast-Modifiedis sent on containers or pages. Responses revalidate (Cache-Control: no-cache). - Paging bounds. Pages
0..lastexist,last = (total-1) / page_size(0 for an empty container, whose page 0 is 200 with no items). Any other non-negative page, including one whosestartIndexwould overflow, is 404; a non-integer or negative page is 400.nextis emitted only belowlast,prevonly above 0. Slugis honoured when it is a valid id and unused; otherwise a generated id is used.- Reads follow the image's access. CORS is
*; the server's own origin gets that exact origin with credentials, never*with credentials. - Which containers are gated. A container is image-keyed when its
name, without any
~Nsuffix, decodes as base64url-raw (non-strict, so every spelling of the same bytes) to non-empty UTF-8. That decoding is its image identifier. Every other container is public. - The check. For an image-keyed container, the image's auth decision
(
Authorizer.Authorize, rules thenHook.Authorize, with the request's session cookie or Bearer access token) is made on every read: container, page and annotation, GET and HEAD. - Who may read. An allowed reader may, and so may a reader the
decision gives substitute access (a hook
Substitute, or the profile'ssubstitute.max_size). Anyone else is refused with the decision's status: 401, or 500 for a hook error. - The write token reads every container.
- Caching. Responses for an identifier that a rule gates, and
responses to the write token, carry
Cache-Control: private, no-cacheandVary: Cookie, Authorization. - Session writes need the image too. A session write to an image-keyed container the session may not read is 403, or 500 for a hook error. The token is exempt.
- Writes are credentialed. An
Authorizationheader, when present, is the only credential considered (never combined with a cookie):Bearer <write_token>compared in constant time, else 401 withWWW-Authenticate. Without it, a session forwrite_profileauthorizes. With neither configured the store is read-only (401). - Token writes keep the client's
creator. The token is operator-held; bulk ingest legitimately names its own agents. - Session writes never trust the client.
Originmust equal the public origin (else 403); POST/PUT must beapplication/ld+json(else 415);@contextmust be the anno context or an array of only the anno and Presentation 3 contexts (else 400); a document is refused (400) if it contains@nest,@graph,@reverseor@includedin any object at any depth,@contextbelow the top level, or a nested node that carries acreator(any spelling) and whoseid/@idis relative or has a path (after dot-segment removal, any host) under/annotations/. The guarantee is that the top-levelcreatorof the stored and served annotation JSON is server-set: every top-level spelling of a client creator (creator,dcterms:creator, full IRI) is removed and the session user, if the profile names one, is recorded as{"type":"Person","name":…}. This is not an attestation at the JSON-LD-expansion level (see Out of scope). - Browser changes are owner-only. A session
PUT/DELETEis 403 unless the annotation's owner record (written when a session of a named user created it, kept by replace, removed by delete) equals the session user. The body, including itscreator, plays no part, so an annotation created with the token or by a user-less profile cannot be changed by a session. The request'sIf-Matchmust also name the version checked (else 412), so the version whose owner was checked is the version the store replaces or deletes. The token may replace or delete any annotation. Order: 401/403/415 (authorization), 400 (names), 403 (image access), 428 (no If-Match), 413/400 (body, PUT), 404 (missing), 403 (owner), 412 (version). - Startup is fail-fast. An enabled store fails startup when
diris not writable (a real write is probed), whenpage_sizeormax_bytes< 1, or whenwrite_profilenames no configured auth profile, or one whose login does not verify the session user. Accepted: backendoidcorexternal(any pattern), or backend builtin (""/builtin) with patternactive. Refused: everything else, including builtinclickthrough(the username is self-asserted), builtinkiosk(the client IP) andheader(no session). - Durable and non-evicting. Writes are atomic; the store never evicts.
Backup is a copy of
dir. It is single-node and separate from the Content State store's directory. Concurrency inside one process is serialised per container. - Derived manifests. The
annotationsreference is added only to derived v3 manifests (never v2, never stored manifests) and only when the store is enabled; the manifest cache key gains|annoin that case so toggling it cannot serve a stale shape. - Viewer editor gating. The Mirador Annotation Editor loads only on
/view/{id}with a path id (so a manifest of this server), Mirador (not Universal Viewer), noiiif-content, the store enabled and browser writes wired. While the store is enabled every viewer page sends a script CSP (Mirador: a nonce on its bootstrap; the UV page:script-src 'none'; the UV shim: this server, UV's pinned CDN release, and its bootstrap's hash), since any viewer may render user-written annotation HTML. Editable pages addframe-ancestors 'self'andX-Frame-Options: SAMEORIGIN. With the store disabled the viewer headers are unchanged. The adapter takes each canvas's container from theannotationsreference in the manifest Mirador loaded (a canvas without one into this store is read-only), and fails closed (refuses the save, requiring a reload) when an annotation changed under the user. Pages that are not editable are plain Mirador and never touch/annotations/themselves. - Conformance gate.
tools/iiif-annotation-conformanceasserts the wire contract above in CI (iiif-annotation-validate); the viewer e2e covers the editor.
Out of scope¶
- Roles. There are no administrator or group roles for browser changes (the token moderates).
- Gating containers that are not image keys. Annotations ingested into any other container name are public, whatever they target.
- Content Search API 2.0 — roadmap Phase 3b; it will index this store.
- Multi-replica backends (Redis/S3) — single-node filesystem only.
- Annotations on stored manifests and Presentation 2.1 — the reference is derived-v3 only; stored documents are served untouched.
- Fetching or validating targets — the store never dereferences a target.
- Editor in Universal Viewer — UV is CDN-loaded; only the self-hosted Mirador carries the editor.
- JSON-LD processing. The server does not expand or flatten documents; it
refuses the shapes listed under Session writes that would let a JSON-LD
processor merge a client-chosen
creatorinto a stored annotation. It relies on the allowed contexts defining no further aliases of those keywords. Consumers that need attested authorship should read the top-level JSONcreator. - Following renamed images. Containers are keyed by image identifier (see Derived manifest reference); content-addressed containers that survive a rename are not provided.