Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ PORT=3000
# The password page belongs to `bun run start`; leave this empty under `bun run dev`.
SELECTS_PASSWORD=

# Optional. `true` starts Selects with posting paused, and holds any post that was under way for
# you to check. Set it for the first start on a restored backup, then remove it.
SELECTS_START_PAUSED=

# Which Instagram to publish to: `fake` (the default) or `live`.
# `fake` runs the fake Instagram server and a fake bucket inside Selects and ignores the bucket
# below: nothing leaves the install and nothing is posted for real. Set `live` only on the
Expand Down
37 changes: 37 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,43 @@ API under `/api` and the built UI everywhere else. It needs `DATA_DIR` set: a mi
or an invalid `PORT` stops startup and names the variable. Everything under
[Running Selects](#running-selects) and [Posting to Instagram](#posting-to-instagram) applies.

### Backups and restoring

Each night at 03:30, in the timezone set on the Queue screen, Selects copies its database to
`backups/selects-YYYY-MM-DD.db` in `DATA_DIR`, keeping the latest seven. It also makes one at
start when the last copy is from before last night. Settings shows when the last copy was made
and why the last try failed, if it did. Each copy holds the Instagram token and the notification
channels, so it is readable by its owner only; keep it that way wherever you copy it.

To restore a copy:

1. Stop Selects.
2. Copy the database aside, in case you want it back: `selects.db`, `selects.db-wal` and
`selects.db-shm` in `DATA_DIR`.
3. Replace `selects.db` with the copy, named `selects.db`, and keep it owner-only
(`chmod 600 selects.db`).
4. Remove `selects.db-wal` and `selects.db-shm`. They belong to the database you replaced, and
SQLite would apply them to the copy.
5. Start Selects with `SELECTS_START_PAUSED=true`. It starts with posting paused, and a post
that was under way when the copy was made is held on the Posted screen for you to check
instead of being sent again. Without this, a slot that is due could post before you get to
the pause switch.

Restoring takes the library, posts, schedule, settings, Instagram token and notification
channels back to the night of the copy. Before you resume:

- A select posted since the copy is back in the pool and could be posted again. The Posted
screen shows only what the copy knew of, so compare your Instagram feed with the Library and
delete from the Library any select already on Instagram (its hash is kept, so it is never
picked again).
- The photos are not in the database: originals, thumbnails and fonts stay in `DATA_DIR` and
are not part of a copy. A select added since the copy is no longer in the library though its
file is still on disk; upload it again.
- If the token was replaced since the copy, paste the current one in Settings.

Then remove `SELECTS_START_PAUSED`, so a later restart does not pause again, and turn the pause
switch off on the Queue screen.

## Checks

These run in CI on every pull request, with a build of the image that is started and checked by
Expand Down
71 changes: 71 additions & 0 deletions docs/adr/0009-notifications-and-backups.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# ADR 0009: Notices say only what happened, fake mode sends none, and backups are snapshots

## Status

Accepted, November 13, 2026.

## Context

[docs/PRODUCT.md](../PRODUCT.md) settles the two channels (an ntfy topic and a webhook), the four
switchable events and the nightly backup with seven copies. It leaves open what a notice
carries, whether fake mode sends one, how often the token and pool events repeat, what a failed
delivery does, and how a copy of a live database is made safely. A notice leaves the install and
a copy holds the Instagram token, so each choice leans towards sending and keeping less.

## Decision

- **A notice says what happened, and nothing about the photo.** It never carries coordinates, a
file name, a caption or a link. Posted: that a select was posted, and how many are left in the
pool. Failed: that a post failed for good, or that Instagram has not
said whether it published one. Token: that the token expires in so many days (and could not be
refreshed), or that Instagram no longer accepts it. Pool: how many selects are left, below the
threshold. ntfy gets `topic`, `title`, `message` and the event as a tag, as JSON to the server's
URL; the webhook gets `event`, `title` and `message` as a JSON POST.
- **Fake mode sends nothing.** As with Instagram and the bucket ([ADR 0006](0006-publishing-safety.md)),
fake mode makes no outside request: each notice is recorded and shown in Settings as one that
would have been sent, and Send test says so. Only `INSTAGRAM_API=live` sends.
- **The publisher tells how each post settles** (published, failed for good, or left needing a
check), whether a slot or Post now made it, and whenever Instagram decides it later. Dry runs
and what the owner says by hand on the Posted screen are not told. The scheduler's notify hook
([ADR 0007](0007-scheduling.md)) runs the token and pool checks after each slot; a timer runs
them every minute too.
- **The token event repeats once a day until fixed.** It fires while the known expiry is within
7 days, or once Instagram refuses the token. A token whose expiry is unknown (never refreshed)
is told only once refused: its expiry is never guessed.
- **The pool event fires once per crossing.** It fires when the pool drops below the threshold
(10 by default, 1 to 10,000), and again only after the pool has been back at or above it. A
crossing while the event is off is not sent later.
- **Delivery is best effort and never holds up a post.** Each channel gets up to three tries
(waits of 2 and 10 seconds) for no answer, a timeout of 10 seconds, a 5xx or a 429; any other
answer fails at once. Sending runs in the background and never throws into the publisher or
the scheduler. Redirects are not followed and the answer's body is never read. Each channel's
last error is shown in Settings in words without its URL; the latest 20 notices are kept.
- **Channel secrets are written, never read back.** URLs must be http or https with no user name
or password. Settings shows the ntfy server, the first three characters of the topic, whether
an access token is set, and only the scheme and host of the webhook URL. They are kept in the
settings table with everything else the UI sets, so no migration was needed.
- **A backup is a snapshot made by `VACUUM INTO`** from the app's own connection: a read
transaction, so the copy is consistent while Selects runs and holds everything committed,
WAL included. It is written into an empty owner-only temporary file in `backups` in the data
volume and renamed to `selects-YYYY-MM-DD.db`, by its date in the install's timezone (the
schedule's); a second copy that day replaces the first. Seven are kept.
- **A backup runs whenever the latest 03:30 in the install's timezone has none**: nightly, and at
start after a stop. A failure is shown in Settings with its kind only and tried again an hour
later. One runs at a time. The last copy's time is read from the files, not the database, so a
restored database never misreports it.

- **A restored copy starts paused.** `SELECTS_START_PAUSED=true` starts Selects with posting
paused and holds every post that was under way as needing a check, so nothing in a restored
copy is posted or sent again before its owner has compared it with Instagram.
- **A notice is never taken by Selects itself.** Each carries a header that Selects refuses, so
a webhook set to the app's own address cannot call it in a loop.

## Consequences

- Nobody learns of a fake-mode post through a notification, and a channel can only be proven
against its real server with `INSTAGRAM_API=live`.
- A notice tells the owner to open Selects; it never shows which photo.
- A channel that fails all three tries (about 12 seconds of waits between them) misses that notice.
- A restored copy brings back the state of that night: a select posted since is back in the pool.
The README says to pause posting and check before the next slot.
- Notification settings and backups add no environment variable.
41 changes: 40 additions & 1 deletion server/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { rmSync } from "node:fs";
import { join } from "node:path";
import { Elysia, t } from "elysia";
import rootPackage from "../../package.json";
import { createBackups } from "./backup";
import { createBucket } from "./bucket";
import { captionRoutes } from "./caption-routes";
import { createCaptionStore } from "./caption-store";
Expand All @@ -24,6 +25,8 @@ import { galleryRoutes } from "./gallery-routes";
import { createInstagramApi, type InstagramApi, InstagramError, LIVE_INSTAGRAM_URL } from "./instagram";
import { createInstagramAccount } from "./instagram-account";
import { createLibrary, duplicateMessage, errorKind, type Library } from "./library";
import { createNotifier, NOTICE_HEADER } from "./notify";
import { notifyRoutes } from "./notify-routes";
import { passwordGate } from "./password";
import { publishRoutes } from "./publish-routes";
import { createPublisher } from "./publisher";
Expand All @@ -35,12 +38,14 @@ import { serveUi } from "./ui";
import { MAX_UPLOAD_BYTES, receiveUpload } from "./upload";
import { createZones } from "./zones";

export type { BackupStatus } from "./backup";
export type { CaptionOverride, CaptionTemplates, HashtagSet, LimitCheck } from "./captions";
export type { CaptureEdits, CaptureView, Withheld } from "./capture";
export type { FrameField, FrameSettings } from "./frame";
export type { GalleryPost, GalleryView } from "./gallery";
export type { AccountView } from "./instagram-account";
export type { Rejection, ScanResult, Select, UploadResult } from "./library";
export type { NotificationsView, NotifyEvent, SentNotice, TestResult } from "./notify";
export type { PickRules } from "./pick";
export type { DryRunReport, Post, PostPreview, PostState } from "./publisher";
export type { Run, RunState, Schedule } from "./scheduler";
Expand Down Expand Up @@ -159,6 +164,14 @@ function createServices({
mode: config.instagram,
clock,
});
// Sends nothing outside the process in fake mode (ADR 0009).
const notifier = createNotifier({
db,
clock,
mode: config.instagram,
poolSize: () => lib.pool().length,
account: () => account.view(),
});
const publisher = createPublisher({
db,
dataDir: config.dataDir,
Expand All @@ -174,10 +187,27 @@ function createServices({
mode: config.instagram,
galleryWanted: gallery.wanted,
onPublished: gallery.published,
onSettled: (outcome) => {
notifier.postSettled(outcome);
notifier.check();
},
// The fake finishes a container at once; only the real API is polled as Meta advises.
containerPolling: config.instagram === "fake" ? { intervalMs: 1000, limitMs: MINUTE } : undefined,
});
const scheduler = createScheduler({ db, library: lib, captures, publisher, clock });
const scheduler = createScheduler({
db,
library: lib,
captures,
publisher,
clock,
notify: () => notifier.check(),
});
const backups = createBackups({
db,
dataDir: config.dataDir,
clock,
timeZone: () => scheduler.schedule().timeZone,
});
return {
library: lib,
settings,
Expand All @@ -190,6 +220,8 @@ function createServices({
gallery,
bucket,
scheduler,
notifier,
backups,
};
}

Expand Down Expand Up @@ -225,6 +257,8 @@ function createRoutes(
gallery,
bucket,
scheduler,
notifier,
backups,
}: Services,
) {
const uploadDir = join(config.dataDir, "uploads");
Expand Down Expand Up @@ -302,6 +336,7 @@ function createRoutes(
)
.use(publishRoutes({ publisher, account, settings, bucket, instagram: config.instagram }))
.use(galleryRoutes({ gallery }))
.use(notifyRoutes({ notifier, backups }))
.use(scheduleRoutes({ scheduler, library: lib, captures, settings }))
.delete("/api/selects/:id", ({ params, status }) =>
lib.remove(params.id) ? status(204) : status(404, notFound),
Expand Down Expand Up @@ -475,8 +510,12 @@ export function createApp(options: AppOptions) {
gallery: services.gallery,
scheduler: services.scheduler,
instagramAccount: services.account,
notifier: services.notifier,
backups: services.backups,
fetch: async (request: Request): Promise<Response> => {
if (isCrossOrigin(request)) return Response.json({ error: "Forbidden" }, { status: 403 });
// A notice of Selects' own, aimed back at it by a webhook set to its own address.
if (request.headers.has(NOTICE_HEADER)) return Response.json({ error: "Forbidden" }, { status: 403 });
const refused = await gate?.(request);
if (refused === undefined) return routes.handle(request);
if (isRead(request) && new URL(request.url).pathname === "/api/health") {
Expand Down
Loading
Loading