Repository navigation
feat(server): write gallery images and the manifest - #18
Conversation
Gallery output: with the switch on and a public base URL, a published post keeps its frame and gets a clean 2048 px sRGB JPEG with no metadata under a random key, listed in posts.json. Objects with headers go up through a short presigned PUT, since Bun's S3 client cannot set Cache-Control.
Version 1 of the format, every field listed. An entry for a select whose location is withheld, then or since, carries no coordinates in any field.
Covers the switch, Remove from gallery with a failing bucket, retries that never touch the post, a stop between the images and the manifest, and mode isolation.
…in the API GET and PUT /api/gallery, DELETE /api/gallery/posts/:id. The timer runs gallery output after publishing retries. In fake mode the fake bucket has a public base URL when BUCKET_PUBLIC_URL is set, so gallery output can be tried.
…osted Settings says why the switch is unavailable without a public base URL. Each post on the Posted screen shows its gallery state and offers Remove from gallery behind a confirmation. ADR 0008 records the decisions.
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 17 minutes. View limit details
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6a4131a33a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const selectId = selectOf(postId); | ||
| const capture = selectId === undefined ? undefined : captures.published(selectId); |
There was a problem hiding this comment.
Snapshot the capture data actually sent with the post
If a post becomes unconfirmed, its location is hidden, and the owner then marks it as posted, adopt snapshots the current capture with null coordinates rather than the capture originally sent to Instagram. The stored caption still contains the original coordinates, but withoutCoordinates cannot remove them because the gallery snapshot no longer contains their values. This publishes the withheld coordinates in posts.json indefinitely. Use the capture snapshot already stored on the post, then apply current privacy rules when building the manifest.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in f470cc3: the gallery lists the capture data stored when the post was built, and a caption and alt text built then with the location withheld. Nothing is read from the select as it is at adoption time.
| await bucket.putObject(MANIFEST_KEY, new TextEncoder().encode(body), MANIFEST_HEADERS); | ||
| Object.assign(manifest, { hash, error: null, failures: 0, nextAt: 0 }); |
There was a problem hiding this comment.
Handle late manifest uploads without deleting the current manifest
If a manifest upload times out, a retry succeeds, and the original upload subsequently completes, putObject invokes its default late-upload cleanup and deletes posts.json. This call supplies no custom callback, so the gallery retains the successful retry's hash and subsequent timer runs skip rewriting the now-missing manifest until its contents change or the process restarts. Unlike random image keys, this shared mutable key needs late-write reconciliation that restores the latest manifest rather than deleting it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 5272034: a late manifest write never deletes the manifest; the stored hash is forgotten and it is written again at once.
| db.query( | ||
| `UPDATE gallery_posts SET state = 'removed', image_key = NULL, image_url = NULL, | ||
| frame_key = NULL, frame_url = NULL, next_attempt_at = NULL WHERE post_id = ?`, | ||
| ).run(postId); | ||
| return [row.image_key, row.frame_key].filter((key): key is string => key !== null); |
There was a problem hiding this comment.
Record cleanup keys before clearing them from the gallery row
If the process crashes after this transaction commits but before discard inserts the keys into bucket_cleanup, the public images remain in the bucket with no database record of their keys. The row is already marked removed, so neither gallery retries nor the publisher's cleanup timer can delete them after restart. Insert the cleanup records inside the same transaction that clears the gallery keys, as the publisher's dropObject already does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in c4e1d2e: the keys go on the cleanup record inside the transaction that clears them.
There was a problem hiding this comment.
1 issue found across 26 files
Confidence score: 3/5
- In
docs/adr/0008-gallery-output.md, a process stop betweenfinishRemovinganddiscardcan leave clean or framed objects orphaned in the bucket. Ensure cleanup is recoverable across that gap.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="docs/adr/0008-gallery-output.md">
<violation number="1" location="docs/adr/0008-gallery-output.md:25">
P1: The removal path does not guarantee this invariant: a process stop after `finishRemoving` clears the row's keys but before `discard` records them leaves the clean or framed objects orphaned in the bucket. Make the cleanup-record insertion atomic with the state transition, or retain the keys until cleanup is durably recorded.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| - **Order of writes.** The clean image's key is recorded before its upload; an entry is listed | ||
| once its image is stored; an image is deleted only once a manifest without it is stored, and | ||
| goes through the cleanup record of [ADR 0006](0006-publishing-safety.md). A stop at any point | ||
| leaves no entry pointing at a missing image and no image nothing knows about. The manifest is |
There was a problem hiding this comment.
P1: The removal path does not guarantee this invariant: a process stop after finishRemoving clears the row's keys but before discard records them leaves the clean or framed objects orphaned in the bucket. Make the cleanup-record insertion atomic with the state transition, or retain the keys until cleanup is durably recorded.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/adr/0008-gallery-output.md, line 25:
<comment>The removal path does not guarantee this invariant: a process stop after `finishRemoving` clears the row's keys but before `discard` records them leaves the clean or framed objects orphaned in the bucket. Make the cleanup-record insertion atomic with the state transition, or retain the keys until cleanup is durably recorded.</comment>
<file context>
@@ -0,0 +1,62 @@
+- **Order of writes.** The clean image's key is recorded before its upload; an entry is listed
+ once its image is stored; an image is deleted only once a manifest without it is stored, and
+ goes through the cleanup record of [ADR 0006](0006-publishing-safety.md). A stop at any point
+ leaves no entry pointing at a missing image and no image nothing knows about. The manifest is
+ written once after each start, and whenever what it should hold changes.
+- **Gallery output never touches the post.** It is taken in after the post is recorded as
</file context>
There was a problem hiding this comment.
Fixed in c4e1d2e: the cleanup record is written in the same transaction.
… withheld from a snapshot
… it again at once
…e URL when the manifest is written
…ion that clears them
…its frame kept meanwhile
…t the in-memory bucket lost
…t it be turned off
…each removal, and moves focus to its confirmation
… format and ADR 0008
…nothing twice when the gallery is unavailable
There was a problem hiding this comment.
7 issues found across 17 files (changes from recent commits).
Confidence score: 3/5
posted.tsxcan stop polling after a transient gallery failure, leaving the Posted screen stale. Keep polling whilegalleryErroris set.docs/manifest.mdpromises a one-year immutable cache, but that behavior has not been verified for supported buckets. Verify the presigned upload persists the metadata before making that guarantee.posted.tsxloses keyboard and screen-reader users’ position after successful removal. Restore focus to a stable gallery target.gallery.test.tscan fail under CI scheduling delays because it checks before the late manifest write and replacement run finish. Wait formanifestErrorto clear, then awaitsettled().
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="docs/manifest.md">
<violation number="1" location="docs/manifest.md:63">
P3: This says a withheld location makes the framed image null because the frame prints the coordinates, but users can disable the frame's `coordinates` field. Say the frame may contain the location (or that Selects removes it conservatively) and update the parallel ADR wording.</violation>
<violation number="2" location="docs/manifest.md:76">
P3: The phrase “as the frame prints them” is not always accurate: the default frame prints DMS coordinates to whole seconds, while the manifest emits four-decimal degrees. Remove that phrase or qualify it to the decimal-coordinate frame format.</violation>
<violation number="3" location="docs/manifest.md:82">
P2: This documents a guaranteed one-year immutable cache, but the supported real-bucket path has not verified that the presigned upload persists this metadata. Verify the behavior across supported buckets before promising it, or weaken the manifest contract.</violation>
</file>
<file name="web/src/screens/posted.tsx">
<violation number="1" location="web/src/screens/posted.tsx:50">
P2: A transient gallery request failure can leave the Posted screen permanently stale. Because the retained gallery entries are settled, `pollMs` becomes `undefined` despite `galleryError`; include `galleryError` in the slower retry condition so the screen recovers automatically.</violation>
<violation number="2" location="web/src/screens/posted.tsx:214">
P3: Successful removal unmounts the focused confirmation fieldset, but this focus logic restores focus only for Keep; keyboard and screen-reader users lose their position. Return focus to a stable gallery status or row after removal.</violation>
</file>
<file name="web/src/lib/gallery.ts">
<violation number="1" location="web/src/lib/gallery.ts:57">
P3: This truncation can split an emoji in a post’s accessible removal name. Count and slice Unicode code points instead of UTF-16 units so captions remain valid when they contain emoji.</violation>
</file>
<file name="server/src/gallery.test.ts">
<violation number="1" location="server/src/gallery.test.ts:869">
P2: This test is wall-clock flaky: under modest CI scheduling delay it can assert before the late manifest write and its replacement run finish. Wait for `manifestError` to clear (then await `settled()`), rather than using a fixed 600 ms delay.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| ## Images | ||
|
|
||
| - Each image has its own random key. Keys never carry a file name, and images never change once | ||
| written. The clean image is served with `Cache-Control: public, max-age=31536000, immutable`. |
There was a problem hiding this comment.
P2: This documents a guaranteed one-year immutable cache, but the supported real-bucket path has not verified that the presigned upload persists this metadata. Verify the behavior across supported buckets before promising it, or weaken the manifest contract.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/manifest.md, line 82:
<comment>This documents a guaranteed one-year immutable cache, but the supported real-bucket path has not verified that the presigned upload persists this metadata. Verify the behavior across supported buckets before promising it, or weaken the manifest contract.</comment>
<file context>
@@ -71,17 +73,17 @@ Every field is always present. A value the select lacks is `null`, never left ou
- Each image has its own random key. Keys never carry a file name, and images never change once
- written, so they are served with `Cache-Control: public, max-age=31536000, immutable`.
+ written. The clean image is served with `Cache-Control: public, max-age=31536000, immutable`.
- The clean image is the photo upright with no frame, 2048 px on its long side (never enlarged
from a smaller original), in sRGB, as a JPEG with no embedded metadata of any kind.
</file context>
There was a problem hiding this comment.
Fixed in 645b6bf: the doc says the header is sent on upload and that a real bucket keeping it is not yet checked (ADR 0008).
| expect(manifest()?.posts[0]?.location).not.toBeNull(); | ||
|
|
||
| // The stale one lands over it, then is replaced. | ||
| await Bun.sleep(600); |
There was a problem hiding this comment.
P2: This test is wall-clock flaky: under modest CI scheduling delay it can assert before the late manifest write and its replacement run finish. Wait for manifestError to clear (then await settled()), rather than using a fixed 600 ms delay.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At server/src/gallery.test.ts, line 869:
<comment>This test is wall-clock flaky: under modest CI scheduling delay it can assert before the late manifest write and its replacement run finish. Wait for `manifestError` to clear (then await `settled()`), rather than using a fixed 600 ms delay.</comment>
<file context>
@@ -680,26 +848,82 @@ describe("manifest writes", () => {
+ expect(manifest()?.posts[0]?.location).not.toBeNull();
+
+ // The stale one lands over it, then is replaced.
+ await Bun.sleep(600);
+ await parts.gallery.settled();
+
</file context>
| await Bun.sleep(600); | |
| await new Promise<void>((resolve) => { | |
| const wait = () => { | |
| if (parts.gallery.view().manifestError === null) resolve(); | |
| else setTimeout(wait, 10); | |
| }; | |
| wait(); | |
| }); |
There was a problem hiding this comment.
Fixed in 645b6bf: the test waits for the replacement write instead of a fixed time.
| // Focus follows the confirmation that replaces the button, and back again when it is kept. | ||
| useEffect(() => { | ||
| if (confirming) confirmation.current?.focus(); | ||
| else if (returnFocus.current) ask.current?.focus(); |
There was a problem hiding this comment.
P3: Successful removal unmounts the focused confirmation fieldset, but this focus logic restores focus only for Keep; keyboard and screen-reader users lose their position. Return focus to a stable gallery status or row after removal.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At web/src/screens/posted.tsx, line 214:
<comment>Successful removal unmounts the focused confirmation fieldset, but this focus logic restores focus only for Keep; keyboard and screen-reader users lose their position. Return focus to a stable gallery status or row after removal.</comment>
<file context>
@@ -171,16 +191,33 @@ function PostRow({
+ // Focus follows the confirmation that replaces the button, and back again when it is kept.
+ useEffect(() => {
+ if (confirming) confirmation.current?.focus();
+ else if (returnFocus.current) ask.current?.focus();
+ returnFocus.current = false;
+ }, [confirming]);
</file context>
There was a problem hiding this comment.
Left as is. After a removal the row's button is gone for good; focus falls to the document as with any removed control, and the status line announces the result.
| | `posts[].images.clean.url` | string | Its public URL, on the public base URL as it is when the manifest is written. | | ||
| | `posts[].images.clean.width` | number | Its width in pixels. | | ||
| | `posts[].images.clean.height` | number | Its height in pixels. | | ||
| | `posts[].images.framed` | object or null | The framed image posted to Instagram. Null when it was not kept: a post confirmed published after its frame was deleted, or one whose location was withheld after it was posted, since the frame prints it. | |
There was a problem hiding this comment.
P3: This says a withheld location makes the framed image null because the frame prints the coordinates, but users can disable the frame's coordinates field. Say the frame may contain the location (or that Selects removes it conservatively) and update the parallel ADR wording.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/manifest.md, line 63:
<comment>This says a withheld location makes the framed image null because the frame prints the coordinates, but users can disable the frame's `coordinates` field. Say the frame may contain the location (or that Selects removes it conservatively) and update the parallel ADR wording.</comment>
<file context>
@@ -49,16 +51,16 @@ Every field is always present. A value the select lacks is `null`, never left ou
| `posts[].images.clean.width` | number | Its width in pixels. |
| `posts[].images.clean.height` | number | Its height in pixels. |
-| `posts[].images.framed` | object or null | The framed image posted to Instagram. Null when it was not kept: a post confirmed published after its frame was deleted. |
+| `posts[].images.framed` | object or null | The framed image posted to Instagram. Null when it was not kept: a post confirmed published after its frame was deleted, or one whose location was withheld after it was posted, since the frame prints it. |
| `posts[].images.framed.url` | string | Its public URL. |
| `posts[].images.framed.width` | number | 1440. |
</file context>
| | `posts[].images.framed` | object or null | The framed image posted to Instagram. Null when it was not kept: a post confirmed published after its frame was deleted, or one whose location was withheld after it was posted, since the frame prints it. | | |
| | `posts[].images.framed` | object or null | The framed image posted to Instagram. Null when it was not kept: a post confirmed published after its frame was deleted, or one whose location was withheld after it was posted; Selects removes it to avoid retaining a potentially location-bearing frame. | |
There was a problem hiding this comment.
Fixed in 645b6bf: the doc says the frame may print it.
…nly what is checked about caching
…movals when run without a public base URL
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 56b1657234
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| Object.assign(manifest, { hash: undefined, nextAt: 0 }); | ||
| void runDue(); | ||
| }); | ||
| Object.assign(manifest, { hash, error: null, failures: 0, nextAt: 0, failedHash: undefined }); |
There was a problem hiding this comment.
Preserve late-write invalidation across an in-flight manifest write
If a timed-out manifest upload lands after a newer upload has stored its body but before that newer request resolves, the late-write callback clears manifest.hash and queues reconciliation, but this assignment then overwrites that invalidation. The queued run sees the expected hash and skips uploading, leaving the stale manifest public indefinitely until its contents change or Selects restarts. This can restore withheld coordinates or references to images already deleted during removal. Unlike the earlier manifest-deletion issue, the remaining failure is the success handler overwriting an invalidation received during its await; preserve that invalidation, for example with a generation counter.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e594e79: late landings are counted, and a write that finishes with the count changed does not record its hash, so the manifest is written again.
… newer one is on its way
There was a problem hiding this comment.
1 issue found across 6 files (changes from recent commits).
Confidence score: 3/5
- In
server/src/gallery.ts, a failed base-URL migration can leave the new URL saved, so a later cleanup may rewrite gallery URLs to a base that was never committed. Save the URL only after the manifest is stored successfully.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="server/src/gallery.ts">
<violation number="1" location="server/src/gallery.ts:190">
P2: `publicBase` saves a newly configured URL before the manifest is successfully stored, so a failed base-URL migration can make a later no-public-base cleanup rewrite URLs under an uncommitted or unavailable base. Persist the base only after `putObject` succeeds, and do not update it from `view()`.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| const base = current.urlFor(""); | ||
| db.query( | ||
| "INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value", | ||
| ).run(baseKey, JSON.stringify(base)); |
There was a problem hiding this comment.
P2: publicBase saves a newly configured URL before the manifest is successfully stored, so a failed base-URL migration can make a later no-public-base cleanup rewrite URLs under an uncommitted or unavailable base. Persist the base only after putObject succeeds, and do not update it from view().
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At server/src/gallery.ts, line 190:
<comment>`publicBase` saves a newly configured URL before the manifest is successfully stored, so a failed base-URL migration can make a later no-public-base cleanup rewrite URLs under an uncommitted or unavailable base. Persist the base only after `putObject` succeeds, and do not update it from `view()`.</comment>
<file context>
@@ -173,6 +175,27 @@ export function createGallery(options: GalleryOptions) {
+ const base = current.urlFor("");
+ db.query(
+ "INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value",
+ ).run(baseKey, JSON.stringify(base));
+ return base;
+ }
</file context>
There was a problem hiding this comment.
Left as is. The saved base is the last public base URL the owner configured, which is where the bucket's objects were last meant to be read from; the manifest written under it lists the same keys either way, and it is written again on every change.
Summary
Closes #9. Part of #1.
posts.json, and its framed image is kept. Off, the framed image is deleted once published, as before.posts.jsonlists each post's image URLs, caption, alt text, capture data, location and permalink. The format is version 1 and documented indocs/manifest.md; a test checks a written manifest against it.published(id). An entry for a select whose location is withheld has no coordinates in any field, and an entry is rewritten without them on the next timer run when a location is hidden or a privacy zone is added after the post: its location and framed image are removed, the framed object is deleted, and its caption and alt text become the versions built at posting time with the location withheld. A hand-written caption is listed as empty then. Locations are listed to four decimal places.gallery_posts. Decisions are recorded as ADR 0008.Evidence
From the generated fixtures, in fake mode.
Typecheck, lint, 398 tests and the build pass locally. In fake mode I posted two fixtures with the gallery on, read the manifest and a clean image back from the fake bucket (no metadata segments, cache headers as documented), hid a location after posting and saw the entry lose its coordinates within a timer run, and removed a post from the gallery.
Merge Danger
Medium. Gallery output is public. Cache headers are set through a presigned upload whose unsigned headers are untested against a real bucket; ADR 0008 lists this as unverified until the first live run.