Live Updates & File Uploads

Authorized Image Storage & Display


Learning Objectives

  • You can connect stored bytes to metadata and application permissions.
  • You can distinguish explicit metadata rejection from uncertain commitment.
  • You can authorize an image read before retrieving its stored bytes.
  • You can retain a rejected upload selection and display accepted images on a later visit.

The previous chapter received bounded image bytes. Another visit needs more than a storage key: the application must identify the image, decide who may read it, and remember its validated media type. Metadata connects those responsibilities to the stored bytes.

The service and component tasks use independent starting files. The service supplies validation, storage and database integration; the component supplies HTTP helpers. You connect their documented outcomes.

Stored objects and application images

For a listing image such as lamp.png, the service validates the bytes and saves them under a generated key. A metadata row records an application image ID, ownership, the key, media type and byte length. The browser receives public metadata, without the private storage key.

StepResponsibility
Protected multipart request arrives.Check session, CSRF, ownership and bounds before storage work.
Byte storage finishes.The generated key identifies stored bytes; it grants no application permission.
Metadata commits.Link those bytes to an image resource and its visibility.
A later viewer requests the image ID.Resolve permitted metadata, read its key and return the validated content type.

An image URL such as /api/images/42 names an application resource. It must not expose a filesystem path or trust the uploaded filename. On reload, fetch stored metadata to obtain the accepted image ID.

Storage writes and metadata failures

A SQL transaction cannot automatically roll back a filesystem write. Stored bytes without a metadata row are an orphaned object. After an explicit metadata rejection, removing the new bytes is compensation for the earlier write. An uncertain commitment needs a different decision: a row may now refer to the bytes, so deleting them could break an accepted image.

The supplied storeImage helper awaits both the byte write and the complete metadata transaction. Its result distinguishes these cases:

Metadata outcomeByte handlingOperation result
Accepted row.Keep the bytes.Return accepted public metadata.
Explicit rejection.Remove the new bytes; report a cleanup failure separately if needed.Preserve the original rejection.
Thrown, uncertain outcome.Keep the bytes because a committed row may exist.Preserve the uncertainty.

Figure 1 follows that boundary after the byte write. The service supplies the metadata callback; the helper coordinates these outcomes.

Figure 1. The supplied helper compensates a known rejection while retaining bytes when commitment is uncertain.

Check upload permission and validate the file before calling storeImage. In this service, storeImage owns the byte write; calling the earlier receipt function as well would write twice.

Compensation runs only while the process can execute it. A crash between writes can leave an orphan even when ordinary rejection handling is correct. Later reconciliation compares objects with authoritative metadata; it is outside this exercise’s supplied coordination helper.

Recognize the remaining storage crash window

0 / 5 points

An upload service writes file bytes under a generated key, then inserts SQL metadata. It removes the bytes after an explicit rejection confirms that no metadata was inserted. The process instead crashes between the byte write and metadata insert. What remains possible?

Authorize before reading bytes

An application image ID and a storage key have different roles. First resolve the ID to metadata using the current actor’s permission. Only then use that row’s generated key to read bytes.

Read outcomeMetadata stepByte step
Visitor cannot see a draft.find(imageId, visitorId) returns null.Do not call storage.
Owner may see the draft.find returns permitted metadata.Read the bytes using its storage key.
Metadata exists but bytes are missing.The permitted row exists.Return not-found.

An image response uses the validated Content-Type and X-Content-Type-Options: nosniff. Do not expose an arbitrary path endpoint. Shared caching also needs the access policy: a private response must not be reused for another visitor and bypass permission checks.

Read an image for another visitor

0 / 5 points

An application stores a private document image under a generated storage key. Another signed-in user has learned its application URL, /api/images/42, but has no permission to read the document. Which read path preserves the document’s access rule?

Connect the service’s write and read paths next. Await upload permission before validation, key allocation or storage. Pass the complete metadata outcome to storeImage, keeping a pending transaction pending. On reads, resolve authorized metadata before retrieving bytes.

Connect authorized image metadata to bytes

0 / 35 points

Goal

Connect authorized image metadata with one coordinated byte write and later reads.

Files and supplied code

Edit api/src/images/image-service.ts. The supplied module supplied.ts provides ImageError(code, status), validateImage(file), storeImage, ImageRepository and ObjectStorage.

  • repo.inspect(listingId, actorId) checks upload permission or rejects.
  • repo.attach(id, actor, key, mediaType, byteLength) resolves after its complete transaction to {ok:true,value} or {ok:false,error}. A thrown error leaves commitment uncertain.
  • repo.find(imageId, actorId?) applies visibility and returns metadata plus storageKey, or null.
  • validateImage(file) resolves to {bytes,mediaType} or rejects. storage.get(key) resolves to bytes or null.
  • storeImage(storage, commitMetadata, key, bytes, report) writes once, then awaits commitMetadata({key,byteLength}). It returns accepted metadata, compensates explicit rejection, and retains bytes on uncertain commitment. This helper, SQL, locking, unique constraints and protected multipart routes are complete supplied code.

Interfaces of the supplied boundary:

type PublicImage = {
id: number;
listingId: number;
mediaType: string;
byteLength: number;
};
type ImageRow = PublicImage & { storageKey: string };
type MetadataCommit<T> = { ok: true; value: T } | { ok: false; error: unknown };
type ImageRepository = {
inspect(id: number, actor: number): Promise<void>;
attach(
id: number,
actor: number,
key: string,
mediaType: string,
byteLength: number,
): Promise<MetadataCommit<PublicImage>>;
find(id: number, actor?: number): Promise<ImageRow | null>;
};
type ObjectStorage = {
put(key: string, bytes: Uint8Array): Promise<void>;
get(key: string): Promise<Uint8Array | null>;
remove(key: string): Promise<void>;
};
declare const validateImage: (file: File | null) => Promise<{
bytes: Uint8Array;
mediaType: string;
}>;
declare const storeImage: <T>(
storage: Pick<ObjectStorage, "put" | "remove">,
commitMetadata: (value: {
key: string;
byteLength: number;
}) => Promise<MetadataCommit<T>>,
key: string,
bytes: Uint8Array,
report: (error: unknown) => void,
) => Promise<T>;

ImageError extends Error and takes a code plus HTTP status. These declarations are supplied through that module; submit only the named service file.

Task

Complete createImageService(repo, storage, makeKey, report). In upload(id, actor, file), await inspect before validating the file. After validation, generate one key and pass the bytes to storeImage. Its metadata callback must return the complete attach outcome so that a pending transaction keeps the upload pending.

Keep an explicit metadata rejection distinct from a thrown uncertain outcome. Call the supplied helper once to coordinate the byte write and compensation.

In read(id, actor?), call find with the actor before reading bytes. Missing metadata or bytes must throw ImageError('NOT_FOUND',404). For a permitted row, read its generated storage key and return {bytes,mediaType}.

IDs, actors and dependency outcomes follow their types. File validation belongs to the supplied validator. The reporter does not throw.

Examples

A denied actor causes no key allocation or write. A pending metadata transaction does not complete upload. A known rejection removes its temporary bytes through the helper; a thrown uncertain outcome retains them. A permitted read of image 71 can use storage key key-1.

Check and submit

Choose Submit solution to run the checks. Submit only api/src/images/image-service.ts. Authorization/validation is worth 10 points; coordination/failures 15; authorized reads 5; real protected multipart/PostgreSQL persistence 5. No setup, SQL or test authoring is required.

Observe permission and persistence boundaries

A recording storage fake can establish that a denied upload never calls put. Control the metadata outcome to check the helper’s decisions: explicit rejection removes the new bytes, while uncertain commitment retains them. Hold the metadata promise pending to check that upload remains pending too.

Those observations exercise service decisions. Use the protected multipart route with PostgreSQL to check permissions and the actual uniqueness constraint. A denied request should leave no new object or metadata. A second permitted upload for the same listing should conflict with the already accepted image.

The image-service fixture includes these route and PostgreSQL checks with sequential uploads and simulated session/CSRF values. Establishing behavior under contention needs overlapping transactions; checking real session protection needs the session middleware from Part 5.

The service now connects accepted bytes to application identity and visibility. Its accepted metadata can also drive the browser’s later visits.

Display accepted images and recover rejected uploads

The component’s HTTP helpers manage cookies, CSRF and FormData. Their results drive three states: retain the selected file after a known rejection, show pending feedback during upload, and display the stored image after acceptance. Connect its read and upload operations to those helpers.

This table follows the same Desk lamp view through one rejected attempt and a successful retry. Its final row is a new read-only visit.

ViewFile and actionFeedback or image
Opening metadata read is pending.No chooser or upload button yet.Checking the stored image.
Read succeeds without an image; user chooses a file.Image for Desk lamp: lamp.png; Attach image is available.No accepted image yet.
Upload is pending.Selection remains; Uploading… is disabled.Wait for the result.
Application rejects the format.Selection remains; Attach image is available again.Format rejected.
Retry is accepted.Upload form is hidden.Stored image 71, with text Image of Desk lamp.
Permitted read-only viewer mounts.No chooser or upload button.Read metadata and display the same image 71.

Read-only viewers must load accepted metadata without uploading first. Await the opening read before offering an upload: otherwise an older read returning no image could overwrite a newly accepted upload. The supplied component keeps upload unavailable after a failed read and until a successful reload. It also supplies descriptive image text, container sizing and component-removal guards.

A lost response raises a separate recovery question: metadata may have committed before delivery failed. The supplied helper distinguishes that uncertainty from a known application rejection. The supplied view then blocks another upload and asks for a reload, which rereads authorized metadata. If an image exists, display it; if the read fails, retain uncertainty. The supplied view handles these states; the recap returns to the recovery decision.

Recover uploads and display stored images

0 / 30 points

Goal

Connect persisted image reads and accepted uploads to an existing image view.

Files and supplied code

Edit only client/src/lib/components/ListingImage.svelte, completing the two marked blocks. The host supplies listingId, title and editable props. The starter supplies the accessible markup, pending/retry behavior, opening-read guard and component-removal cleanup. Its showImage(value) stores returned metadata (or null) and ignores results after removal. Keep that surrounding code.

Supplied API interfaces from #lib/api/image-api:

type ListingImage = {
id: number;
listingId: number;
mediaType: string;
byteLength: number;
};
declare const readListingImage: (id: number) => Promise<ListingImage | null>;
declare const uploadListingImage: (id: number, file: File) => Promise<ListingImage>;
declare const imageUrl: (imageId: number) => string;
declare class UploadOutcomeUnknown extends Error {}

The helper handles cookies, CSRF and FormData; do not set multipart Content-Type yourself. A successful upload resolves to accepted metadata. This API’s 4xx response is a known application rejection and rejects with its explanation. A network failure, server failure or unreadable accepted response instead throws UploadOutcomeUnknown: commitment may already have happened.

The supplied component blocks another upload after that uncertain outcome and asks the user to reload, which reads authorized metadata again. Implement retry after known application rejection.

Task

In the opening-read block, await readListingImage(listingId) and pass its result to showImage. Read for read-only viewers as well as editors. The supplied code offers upload controls only after this read succeeds; a failed read leaves them unavailable until a successful reload.

In the upload block, await uploadListingImage(listingId, selected) and pass its accepted metadata to showImage. A selected file is only a proposal; do not display it as accepted or announce success while the upload is pending.

The supplied view retains the selection after a known rejection, enables retry, hides the form after acceptance, and displays descriptive image text and responsive sizing. Its stopped guards ignore results after removal. Keep these behaviors.

Examples

While the opening read is pending, no upload is offered. A known rejected upload retains lamp.png; another click retries it. After acceptance a fresh read-only mount displays the stored image without uploading again. An uncertain response blocks retry until a new read can establish the stored result.

Check and submit

Choose Submit solution to run the checks. Submit only the named component. Persisted read/display and opening-read ordering are worth 10 points, awaited upload/known-rejection retry 15, and accepted display/accessibility 5.

An accepted image can now appear on a later visit from stored metadata, without a newly selected file. That later visit checks persisted display; the service and integration observations check permission and storage failure decisions. Include a denied-visitor read when checking image permissions.

Check Your Understanding

  1. Why can an explicit metadata rejection permit byte removal while an uncertain outcome cannot?
  2. Why must permission checks happen before byte writes and before byte reads?
  3. What can still go wrong if the process stops between storing bytes and metadata?
  4. Why does the later viewer need an image ID rather than the uploaded filename?
  5. How do accepted metadata, a rejected request and a lost response imply different UI decisions?