From ec2e15444925e50411d561f6178164cfcf7c4c7e Mon Sep 17 00:00:00 2001 From: Brandon Ly Date: Fri, 13 Nov 2026 11:37:09 +0000 Subject: [PATCH 01/13] feat(server): tell how each post settles through the publisher --- server/src/publisher.test.ts | 93 ++++++++++++++++++++++++++++++++++++ server/src/publisher.ts | 21 ++++++++ 2 files changed, 114 insertions(+) diff --git a/server/src/publisher.test.ts b/server/src/publisher.test.ts index 4fdb9d1..5fb3fe5 100644 --- a/server/src/publisher.test.ts +++ b/server/src/publisher.test.ts @@ -73,6 +73,7 @@ function setup( wrapApi?: (api: InstagramApi) => InstagramApi; renderer?: PublisherOptions["renderer"]; mode?: PublisherOptions["mode"]; + onSettled?: PublisherOptions["onSettled"]; } = {}, ) { const zones = createZones(db); @@ -103,6 +104,7 @@ function setup( clock, mode: options.mode ?? "fake", random: () => 0, + onSettled: options.onSettled, }); return { publisher, zones, captures, settings, captionStore, account, renderer }; } @@ -1111,3 +1113,94 @@ describe("dry run", () => { expect(instagram.media).toHaveLength(0); }); }); + +describe("a post settling", () => { + /** Every outcome the publisher tells, in order. */ + function told() { + const outcomes: string[] = []; + return { outcomes, onSettled: (outcome: string) => void outcomes.push(outcome) }; + } + + test("is told once published, and a dry run is not told", async () => { + const settled = told(); + const { publisher, account } = setup({ onSettled: settled.onSettled }); + await connect(account); + const dry = await addSelect("landscape"); + await postNow(publisher, dry, { dryRun: true }); + const id = await addSelect("portrait"); + + await postNow(publisher, id); + + expect(settled.outcomes).toEqual(["published"]); + }); + + test("is told once it fails for good, and not for an attempt that will be retried", async () => { + const settled = told(); + const { publisher, account } = setup({ onSettled: settled.onSettled }); + await connect(account); + const id = await addSelect("portrait"); + instagram.fail("container", "transient", "transient", "transient", "transient"); + + let post = await postNow(publisher, id); + expect(settled.outcomes).toEqual([]); + while (post.state === "retrying") { + await after(publisher, (post.nextAttemptAt ?? 0) - clock.now()); + post = publisher.post(post.id) ?? post; + } + + expect(post.state).toBe("failed"); + expect(settled.outcomes).toEqual(["failed"]); + }); + + test("is told when left needing a check, and again once Instagram says it was published", async () => { + const settled = told(); + const { publisher, account } = setup({ onSettled: settled.onSettled }); + await connect(account); + const id = await addSelect("portrait"); + instagram.fail("publish", "lost"); + let post = await postNow(publisher, id); + instagram.fail("status", "transient", "transient", "transient"); + while (post.state === "retrying") { + await after(publisher, (post.nextAttemptAt ?? 0) - clock.now()); + post = publisher.post(post.id) ?? post; + } + expect(settled.outcomes).toEqual(["unconfirmed"]); + + await after(publisher, (post.nextAttemptAt ?? 0) - clock.now()); + + expect(settled.outcomes).toEqual(["unconfirmed", "published"]); + }); + + test("is not told when the owner says what happened", async () => { + const settled = told(); + const { publisher, account } = setup({ onSettled: settled.onSettled }); + await connect(account); + const id = await addSelect("portrait"); + instagram.fail("publish", "lost"); + let post = await postNow(publisher, id); + instagram.fail("status", "transient", "transient", "transient"); + while (post.state === "retrying") { + await after(publisher, (post.nextAttemptAt ?? 0) - clock.now()); + post = publisher.post(post.id) ?? post; + } + + await publisher.resolve(post.id, { posted: false }); + + expect(settled.outcomes).toEqual(["unconfirmed"]); + }); + + test("a hook that throws touches nothing", async () => { + const { publisher, account } = setup({ + onSettled: () => { + throw new Error("boom"); + }, + }); + await connect(account); + const id = await addSelect("portrait"); + + const post = await postNow(publisher, id); + + expect(post.state).toBe("published"); + expect(instagram.media).toHaveLength(1); + }); +}); diff --git a/server/src/publisher.ts b/server/src/publisher.ts index 97cbcf1..b066a3b 100644 --- a/server/src/publisher.ts +++ b/server/src/publisher.ts @@ -140,6 +140,12 @@ export type PublisherOptions = { * same update. Such a post's frame is left for the gallery to take, even across a stop. */ galleryWanted?: () => boolean; + /** + * Told as a post settles: published, failed for good, or left needing a check, as Instagram or + * the attempts decide. Not told of dry runs or of what the owner says by hand. It is called + * after the post is recorded, must not throw, and nothing it does touches the post. + */ + onSettled?: (outcome: "published" | "failed" | "unconfirmed") => void; }; /** The wait before each retry: three retries over fifteen minutes. */ @@ -295,6 +301,14 @@ export function createPublisher(options: PublisherOptions) { const toGallery = () => (options.galleryWanted?.() ? 1 : 0); + const tell = (outcome: "published" | "failed" | "unconfirmed") => { + try { + options.onSettled?.(outcome); + } catch (error) { + console.error(`A post's outcome could not be passed on (${errorKind(error)}).`); + } + }; + const bucketProblem = (): string | undefined => { if (!("missing" in options.bucket)) return undefined; const names = options.bucket.missing; @@ -537,8 +551,10 @@ export function createPublisher(options: PublisherOptions) { error: `${message} ${UNCONFIRMED_MESSAGE}`, next_attempt_at: clock.now() + UNCONFIRMED_CHECK_MS, }); + tell("unconfirmed"); } else { update({ state: "failed", error: `${message} Post it again.`, next_attempt_at: null }); + tell("failed"); } console.error(`Post ${id} was made in another Instagram mode; it was not sent.`); return; @@ -567,6 +583,7 @@ export function createPublisher(options: PublisherOptions) { next_attempt_at: clock.now() + UNCONFIRMED_CHECK_MS, }); console.error(`Post ${id} needs checking after ${number} attempts: ${failure.message}`); + tell("unconfirmed"); // Instagram fetched the frame when the container was made: it need not stay in the bucket. await dropObject(id); } else if (final) { @@ -579,6 +596,7 @@ export function createPublisher(options: PublisherOptions) { console.error( `Post ${id} failed after ${number} attempt${number === 1 ? "" : "s"}: ${failure.message}`, ); + tell("failed"); await dropObject(id); } else { const delay = RETRY_DELAYS[number - 1] ?? 0; @@ -629,6 +647,7 @@ export function createPublisher(options: PublisherOptions) { }); console.log(`Post ${post.id} published.`); options.onPublished?.(post.id); + tell("published"); await dropObject(post.id); }; @@ -879,6 +898,7 @@ export function createPublisher(options: PublisherOptions) { ); console.log(`Post ${id} was published, Instagram says.`); options.onPublished?.(id); + tell("published"); return dropObject(id); } const settled = clock.now() - (found.publish_requested_at ?? 0) >= PUBLISH_SETTLE_MS; @@ -887,6 +907,7 @@ export function createPublisher(options: PublisherOptions) { "UPDATE posts SET state = 'failed', error = ?, next_attempt_at = NULL WHERE id = ? AND state = 'unconfirmed'", ).run(`Instagram shows it was not published (${status}).`, id); console.error(`Post ${id} was not published, Instagram says; its select is back in the pool.`); + tell("failed"); return dropObject(id); } From 635b7e70ad58ff8e3128b8f63e34fb0049198cbe Mon Sep 17 00:00:00 2001 From: Brandon Ly Date: Fri, 13 Nov 2026 11:37:09 +0000 Subject: [PATCH 02/13] feat(server): send notifications to an ntfy topic and a webhook --- server/src/notify.test.ts | 468 ++++++++++++++++++++++++++++++++++ server/src/notify.ts | 512 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 980 insertions(+) create mode 100644 server/src/notify.test.ts create mode 100644 server/src/notify.ts diff --git a/server/src/notify.test.ts b/server/src/notify.test.ts new file mode 100644 index 0000000..e15b9ca --- /dev/null +++ b/server/src/notify.test.ts @@ -0,0 +1,468 @@ +import type { Database } from "bun:sqlite"; +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createFakeClock, DAY, type FakeClock, HOUR } from "./clock"; +import { openDatabase } from "./db"; +import type { AccountView } from "./instagram-account"; +import { migrations } from "./migrations"; +import { + CHANNEL_IDS, + type ChannelId, + createNotifier, + DEFAULT_EVENTS, + DeliveryError, + type Notice, + type Notifier, + type NotifierOptions, +} from "./notify"; + +const TOPIC = "selects-test-topic-0001"; +const NTFY_TOKEN = "tk_fake_access_token_0001"; +const HOOK_SECRET = "hook-secret-0001"; + +type Received = { method: string; path: string; headers: Headers; body: string }; + +/** A stand-in for an ntfy server or a webhook receiver, on 127.0.0.1. Answers with `answer`. */ +function fakeReceiver(answer: (request: Request) => Response | Promise = () => new Response("ok")) { + const received: Received[] = []; + const server = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + fetch: async (request) => { + received.push({ + method: request.method, + path: new URL(request.url).pathname, + headers: request.headers, + body: await request.text(), + }); + return answer(request); + }, + }); + return { url: `http://127.0.0.1:${server.port}`, received, stop: () => server.stop(true) }; +} + +let dataDir: string; +let db: Database; +let clock: FakeClock; +let stops: (() => unknown)[]; +beforeEach(() => { + dataDir = mkdtempSync(join(tmpdir(), "selects-notify-")); + db = openDatabase(dataDir, migrations); + clock = createFakeClock(); + stops = []; +}); +afterEach(async () => { + for (const stop of stops) await stop(); + db.close(); + rmSync(dataDir, { recursive: true, force: true }); +}); + +function receiver(answer?: Parameters[0]) { + const found = fakeReceiver(answer); + stops.push(found.stop); + return found; +} + +function notifierWith(options: Partial = {}) { + return createNotifier({ + db, + clock, + mode: "live", + poolSize: () => 50, + account: () => null, + timeoutMs: 2000, + ...options, + }); +} + +describe("ntfy", () => { + test("Send test publishes to the topic, with the access token, and reports success", async () => { + const ntfy = receiver(); + const notifier = notifierWith(); + expect(notifier.setNtfy({ server: ntfy.url, topic: TOPIC, token: NTFY_TOKEN })).toEqual({ ok: true }); + + const result = await notifier.test("ntfy"); + + expect(result).toEqual({ status: "sent" }); + expect(ntfy.received).toHaveLength(1); + const [request] = ntfy.received; + expect(request?.method).toBe("POST"); + expect(request?.headers.get("authorization")).toBe(`Bearer ${NTFY_TOKEN}`); + expect(JSON.parse(request?.body ?? "")).toMatchObject({ + topic: TOPIC, + title: "Selects test", + message: "Notifications from Selects reach this topic.", + }); + }); +}); + +describe("the webhook", () => { + test("Send test POSTs JSON to the URL and reports success", async () => { + const hook = receiver(); + const notifier = notifierWith(); + expect(notifier.setWebhook({ url: `${hook.url}/hooks/${HOOK_SECRET}` })).toEqual({ ok: true }); + + expect(await notifier.test("webhook")).toEqual({ status: "sent" }); + + const [request] = hook.received; + expect(request?.path).toBe(`/hooks/${HOOK_SECRET}`); + expect(request?.headers.get("content-type")).toBe("application/json"); + expect(JSON.parse(request?.body ?? "")).toMatchObject({ event: "test", title: "Selects test" }); + }); + + test("Send test reports why it failed, and Settings keeps it as the channel's last error, without the URL", async () => { + const hook = receiver(() => new Response("no", { status: 403 })); + const notifier = notifierWith(); + notifier.setWebhook({ url: `${hook.url}/hooks/${HOOK_SECRET}` }); + + const result = await notifier.test("webhook"); + + expect(result).toEqual({ status: "failed", reason: "The server answered 403." }); + const view = notifier.view(); + expect(view.webhook?.lastError).toEqual({ at: clock.now(), reason: "The server answered 403." }); + expect(JSON.stringify(view)).not.toContain(HOOK_SECRET); + expect(JSON.stringify(view)).not.toContain("/hooks/"); + }); + + test("a redirect is not followed", async () => { + const elsewhere = receiver(); + const hook = receiver(() => Response.redirect(`${elsewhere.url}/caught`, 307)); + const notifier = notifierWith(); + notifier.setWebhook({ url: `${hook.url}/hooks/${HOOK_SECRET}` }); + + const result = await notifier.test("webhook"); + + expect(result.status).toBe("failed"); + expect(elsewhere.received).toHaveLength(0); + }); + + test("an unreachable URL fails within the timeout, with a reason", async () => { + const hook = receiver(() => new Promise(() => {})); + const notifier = notifierWith({ timeoutMs: 100 }); + notifier.setWebhook({ url: `${hook.url}/slow` }); + + expect(await notifier.test("webhook")).toEqual({ + status: "failed", + reason: "No answer within 1 second.", + }); + }); +}); + +describe("channel settings", () => { + test("only http and https URLs without a user name or password are taken", () => { + const notifier = notifierWith(); + for (const url of [ + "ftp://127.0.0.1/x", + "file:///etc/hosts", + "not a url", + "http://user:pass@127.0.0.1/x", + ]) { + expect(notifier.setWebhook({ url })).toMatchObject({ ok: false }); + expect(notifier.setNtfy({ server: url, topic: TOPIC, token: null })).toMatchObject({ ok: false }); + } + expect(notifier.view().webhook).toBeNull(); + expect(notifier.view().ntfy).toBeNull(); + }); + + test("a topic is 1 to 64 letters, digits, - or _", () => { + const notifier = notifierWith(); + for (const topic of ["", "has space", "slash/topic", "x".repeat(65)]) { + expect(notifier.setNtfy({ server: "https://ntfy.invalid", topic, token: null })).toMatchObject({ + ok: false, + }); + } + }); + + test("Settings shows a saved channel without its topic, token or the secret parts of its URL", () => { + const notifier = notifierWith(); + notifier.setNtfy({ server: "https://ntfy.invalid/", topic: TOPIC, token: NTFY_TOKEN }); + notifier.setWebhook({ url: `https://hooks.invalid/api/${HOOK_SECRET}?key=${HOOK_SECRET}` }); + + const view = notifier.view(); + + expect(view.ntfy).toMatchObject({ server: "https://ntfy.invalid", topic: "sel…", token: true }); + expect(view.webhook).toMatchObject({ url: "https://hooks.invalid/…" }); + const json = JSON.stringify(view); + for (const secret of [TOPIC, NTFY_TOKEN, HOOK_SECRET]) expect(json).not.toContain(secret); + }); +}); + +describe("fake mode", () => { + test("Send test sends nothing and says what would have been sent", async () => { + const ntfy = receiver(); + const notifier = notifierWith({ mode: "fake" }); + notifier.setNtfy({ server: ntfy.url, topic: TOPIC, token: null }); + + const result = await notifier.test("ntfy"); + + expect(result.status).toBe("would-send"); + expect(ntfy.received).toHaveLength(0); + }); +}); + +/** Channels that record what they are given; `fail` decides each attempt's error. */ +function recordingChannels(fail: (attempt: number) => Error | undefined = () => undefined) { + const sent: { channel: ChannelId; notice: Notice }[] = []; + let attempts = 0; + const channels: NotifierOptions["channels"] = (stored) => + CHANNEL_IDS.filter((id) => stored[id] !== null).map((id) => ({ + id, + send: async (notice: Notice) => { + attempts++; + const error = fail(attempts); + if (error !== undefined) throw error; + sent.push({ channel: id, notice }); + }, + })); + return { sent, channels, attempts: () => attempts }; +} + +function configured(notifier: Notifier) { + notifier.setNtfy({ server: "https://ntfy.invalid", topic: TOPIC, token: null }); + notifier.setWebhook({ url: `https://hooks.invalid/${HOOK_SECRET}` }); +} + +describe("events", () => { + test("a published post notifies through every channel, saying only that a select was posted", async () => { + const recorded = recordingChannels(); + const notifier = notifierWith({ channels: recorded.channels, poolSize: () => 12 }); + configured(notifier); + + notifier.postSettled("published"); + await notifier.idle(); + + expect(recorded.sent.map(({ channel }) => channel)).toEqual(["ntfy", "webhook"]); + expect(recorded.sent[0]?.notice).toEqual({ + event: "posted", + title: "Posted to Instagram", + message: "A select was posted. 12 selects are left in the pool.", + }); + }); + + test("a post that failed for good, and one left needing a check, notify as failed", async () => { + const recorded = recordingChannels(); + const notifier = notifierWith({ channels: recorded.channels }); + configured(notifier); + + notifier.postSettled("failed"); + notifier.postSettled("unconfirmed"); + await notifier.idle(); + + const notices = recorded.sent.filter(({ channel }) => channel === "ntfy").map(({ notice }) => notice); + expect(notices).toEqual([ + { + event: "failed", + title: "A post failed", + message: "A post failed and its select is back in the pool. The Posted screen says why.", + }, + { + event: "failed", + title: "A post needs checking", + message: + "Instagram was asked to publish a post and has not said whether it did. Say what happened on the Posted screen.", + }, + ]); + }); + + test("each event can be switched off", async () => { + const recorded = recordingChannels(); + const notifier = notifierWith({ channels: recorded.channels }); + configured(notifier); + expect(notifier.events()).toEqual({ + events: { posted: true, failed: true, token: true, pool: true }, + poolThreshold: 10, + }); + + notifier.setEvents({ + events: { posted: false, failed: true, token: true, pool: true }, + poolThreshold: 10, + }); + notifier.postSettled("published"); + notifier.postSettled("failed"); + await notifier.idle(); + + expect(recorded.sent.map(({ notice }) => notice.event)).toEqual(["failed", "failed"]); + }); + + test("a delivery that fails is tried twice more, and the channel's last error clears once one arrives", async () => { + const recorded = recordingChannels((attempt) => + attempt <= 2 ? new DeliveryError("The server answered 503.", true) : undefined, + ); + const notifier = notifierWith({ channels: recorded.channels }); + notifier.setNtfy({ server: "https://ntfy.invalid", topic: TOPIC, token: null }); + + notifier.postSettled("published"); + await notifier.idle(); + + expect(recorded.sent).toHaveLength(1); + expect(notifier.view().ntfy).toMatchObject({ lastError: null, lastSentAt: clock.now() }); + }); + + test("a delivery that keeps failing is given up on, recorded as the channel's last error, and never throws", async () => { + const recorded = recordingChannels(() => new Error(`refused at https://hooks.invalid/${HOOK_SECRET}`)); + const notifier = notifierWith({ channels: recorded.channels }); + notifier.setWebhook({ url: `https://hooks.invalid/${HOOK_SECRET}` }); + + expect(() => notifier.postSettled("failed")).not.toThrow(); + await notifier.idle(); + + expect(recorded.attempts()).toBe(3); + expect(notifier.view().webhook?.lastError).toEqual({ at: clock.now(), reason: "Something went wrong." }); + expect(notifier.recent()[0]).toMatchObject({ event: "failed", outcome: "failed" }); + }); + + test("in fake mode an event is recorded as what would have been sent, and nothing is sent", async () => { + const recorded = recordingChannels(); + const notifier = notifierWith({ mode: "fake", channels: recorded.channels }); + configured(notifier); + + notifier.postSettled("published"); + await notifier.idle(); + + expect(recorded.attempts()).toBe(0); + expect(notifier.recent()).toEqual([ + { + at: clock.now(), + event: "posted", + title: "Posted to Instagram", + message: "A select was posted. 50 selects are left in the pool.", + outcome: "would-send", + }, + ]); + }); +}); + +const account = (fields: Partial): AccountView => ({ + username: "selects_test", + status: "connected", + connectedAt: Date.parse("2026-09-01T00:00:00Z"), + expiresAt: null, + refresh: "refreshed", + ...fields, +}); + +describe("token about to expire", () => { + test("notifies once a day while the token expires within 7 days, and stops once it is fixed", async () => { + const recorded = recordingChannels(); + let current = account({ expiresAt: clock.now() + 6 * DAY, refresh: "failed" }); + const notifier = notifierWith({ channels: recorded.channels, account: () => current }); + notifier.setNtfy({ server: "https://ntfy.invalid", topic: TOPIC, token: null }); + const notices = async () => { + await notifier.idle(); + return recorded.sent.map(({ notice }) => notice); + }; + + notifier.check(); + expect(await notices()).toEqual([ + { + event: "token", + title: "The Instagram token expires soon", + message: + "The Instagram token expires in 6 days and could not be refreshed. Paste a new token in Settings before then.", + }, + ]); + + clock.advance(23 * HOUR); + notifier.check(); + expect(await notices()).toHaveLength(1); + + clock.advance(HOUR); + notifier.check(); + expect(await notices()).toHaveLength(2); + + // A new token: fixed. + current = account({ expiresAt: clock.now() + 60 * DAY }); + clock.advance(DAY); + notifier.check(); + expect(await notices()).toHaveLength(2); + }); + + test("a token Instagram no longer accepts notifies", async () => { + const recorded = recordingChannels(); + const notifier = notifierWith({ + channels: recorded.channels, + account: () => account({ status: "invalid" }), + }); + notifier.setNtfy({ server: "https://ntfy.invalid", topic: TOPIC, token: null }); + + notifier.check(); + await notifier.idle(); + + expect(recorded.sent.map(({ notice }) => notice)).toEqual([ + { + event: "token", + title: "The Instagram token no longer works", + message: + "Instagram no longer accepts the token. Nothing posts until a new token is pasted in Settings.", + }, + ]); + }); + + test("a token far from expiry, or with no account, notifies nothing", async () => { + const recorded = recordingChannels(); + let current: AccountView | null = account({ expiresAt: clock.now() + 8 * DAY }); + const notifier = notifierWith({ channels: recorded.channels, account: () => current }); + notifier.setNtfy({ server: "https://ntfy.invalid", topic: TOPIC, token: null }); + + notifier.check(); + current = null; + notifier.check(); + await notifier.idle(); + + expect(recorded.sent).toHaveLength(0); + }); +}); + +describe("pool running low", () => { + test("notifies once when the pool drops below the threshold, and again only after it has gone back up", async () => { + const recorded = recordingChannels(); + let pool = 11; + const notifier = notifierWith({ channels: recorded.channels, poolSize: () => pool }); + notifier.setNtfy({ server: "https://ntfy.invalid", topic: TOPIC, token: null }); + const count = async () => { + await notifier.idle(); + return recorded.sent.length; + }; + + notifier.check(); + pool = 10; + notifier.check(); + expect(await count()).toBe(0); + + pool = 9; + notifier.check(); + expect(recorded.sent[0]?.notice).toEqual({ + event: "pool", + title: "The pool is running low", + message: "9 selects are left in the pool, below the 10 you set. Upload more to keep posting.", + }); + pool = 3; + notifier.check(); + expect(await count()).toBe(1); + + pool = 10; + notifier.check(); + pool = 9; + notifier.check(); + expect(await count()).toBe(2); + }); + + test("a crossing while the event is off is not sent later", async () => { + const recorded = recordingChannels(); + let pool = 20; + const notifier = notifierWith({ channels: recorded.channels, poolSize: () => pool }); + notifier.setNtfy({ server: "https://ntfy.invalid", topic: TOPIC, token: null }); + notifier.setEvents({ ...DEFAULT_EVENTS, events: { ...DEFAULT_EVENTS.events, pool: false } }); + + notifier.check(); + pool = 2; + notifier.check(); + notifier.setEvents(DEFAULT_EVENTS); + notifier.check(); + await notifier.idle(); + + expect(recorded.sent).toHaveLength(0); + }); +}); diff --git a/server/src/notify.ts b/server/src/notify.ts new file mode 100644 index 0000000..f74cdc2 --- /dev/null +++ b/server/src/notify.ts @@ -0,0 +1,512 @@ +import type { Database } from "bun:sqlite"; +import { randomUUID } from "node:crypto"; +import { type Clock, DAY } from "./clock"; +import type { InstagramMode } from "./config"; +import type { AccountView } from "./instagram-account"; + +/** Where notifications go. */ +export type ChannelId = "ntfy" | "webhook"; +export const CHANNEL_IDS: readonly ChannelId[] = ["ntfy", "webhook"]; + +/** What is sent: a title and one or two plain sentences. Never a location, file name, caption or link. */ +export type Notice = { event: NotifyEvent | "test"; title: string; message: string }; + +export type NotifyEvent = "posted" | "failed" | "token" | "pool"; +export const NOTIFY_EVENTS: readonly NotifyEvent[] = ["posted", "failed", "token", "pool"]; + +/** Which events notify, and the pool size below which the pool is running low. */ +export type EventSettings = { events: Record; poolThreshold: number }; + +export const DEFAULT_EVENTS: EventSettings = { + events: { posted: true, failed: true, token: true, pool: true }, + poolThreshold: 10, +}; + +export const POOL_THRESHOLD_LIMITS = { min: 1, max: 10_000 } as const; + +/** + * A notice as it was handled: sent to every channel, not to every one, recorded only (fake mode), + * or with no channel set. + */ +export type SentNotice = Omit & { + at: number; + event: NotifyEvent; + outcome: "sent" | "failed" | "would-send" | "no-channel"; +}; + +/** How a post settled, as the publisher tells it. */ +export type PostOutcome = "published" | "failed" | "unconfirmed"; + +/** An ntfy topic: the server's URL, the topic, and an access token when the topic needs one. */ +export type NtfyConfig = { server: string; topic: string; token: string | null }; +/** A URL the server POSTs JSON to. */ +export type WebhookConfig = { url: string }; + +/** How one channel delivers a notice. Throws a `DeliveryError` when it could not. */ +export type Channel = { id: ChannelId; send(notice: Notice): Promise }; + +/** Why a notice did not arrive, in words that never carry the channel's URL or secrets. */ +export class DeliveryError extends Error { + override name = "DeliveryError"; + constructor( + message: string, + /** Worth another attempt: no answer, a timeout, a 5xx or a 429. */ + readonly retry: boolean, + ) { + super(message); + } +} + +type Stored = { ntfy: NtfyConfig | null; webhook: WebhookConfig | null }; + +/** How a channel last went: kept per channel, in words without its URL or secrets. */ +type ChannelStatus = { lastError: { at: number; reason: string } | null; lastSentAt: number | null }; + +/** A channel as Settings shows it: never its topic, token or the secret parts of its URL. */ +export type ChannelView = T & ChannelStatus; + +export type NotificationsView = { + mode: InstagramMode; + ntfy: ChannelView<{ server: string; topic: string; token: boolean }> | null; + webhook: ChannelView<{ url: string }> | null; +}; + +export type SaveResult = { ok: true } | { ok: false; problems: string[] }; + +/** An ntfy topic name, as ntfy takes it. */ +export const TOPIC_PATTERN = /^[A-Za-z0-9_-]{1,64}$/; + +export type TestResult = + | { status: "sent" } + | { status: "would-send"; message: string } + | { status: "failed"; reason: string } + | { status: "not-configured" }; + +export type NotifierOptions = { + db: Database; + clock: Clock; + /** In fake mode nothing leaves the install: notices are recorded as what would have been sent. */ + mode: InstagramMode; + /** How many selects are in the pool. */ + poolSize: () => number; + /** The connected Instagram account, for its token's expiry. */ + account: () => AccountView | null; + /** How the channels are made from what is saved. Default: HTTP requests. Tests swap them. */ + channels?: (stored: Stored, http: HttpOptions) => Channel[]; + /** How long one request may take. Default: 10 seconds. */ + timeoutMs?: number; +}; + +type HttpOptions = { timeoutMs: number }; + +const DEFAULT_TIMEOUT_MS = 10 * 1000; +/** The waits before the two retries of a delivery. */ +const RETRY_DELAYS_MS = [2 * 1000, 10 * 1000] as const; +/** Notices kept for Settings to show. */ +const RECENT_KEPT = 20; +const EVENTS_KEY = "notification-events"; +const LOG_KEY = "notification-log"; +const STATE_KEY = "notification-state"; + +/** A token this close to its expiry is about to expire. */ +export const TOKEN_WARNING_MS = 7 * DAY; +/** How often a token about to expire is told again until it is fixed. */ +const TOKEN_REPEAT_MS = DAY; + +/** What the checks remember: whether the pool was last seen low, and when the token was last told. */ +type CheckState = { poolLow: boolean; tokenWarnedAt: number | null }; + +const KEY = "notifications"; +const STATUS_KEY = "notification-status"; + +/** The problem with a channel URL, if any: http or https, and no user name or password in it. */ +export function urlProblem(value: string, what: string): string | undefined { + let url: URL; + try { + url = new URL(value); + } catch { + return `${what} must be a full http or https URL.`; + } + if (url.protocol !== "http:" && url.protocol !== "https:") return `${what} must be an http or https URL.`; + if (url.username !== "" || url.password !== "") return `${what} must not hold a user name or password.`; + if (value.length > 2048) return `${what} must be at most 2048 characters.`; + return undefined; +} + +/** The scheme and host of a URL, and "/…" when anything follows: its path may be a secret. */ +function shownUrl(value: string): string { + const url = new URL(value); + const rest = `${url.pathname}${url.search}${url.hash}`; + return rest === "/" || rest === "" ? url.origin : `${url.origin}/…`; +} + +const seconds = (ms: number) => { + const whole = Math.max(1, Math.ceil(ms / 1000)); + return `${whole} second${whole === 1 ? "" : "s"}`; +}; + +/** The channels a saved configuration makes, sending over HTTP. */ +export function httpChannels(stored: Stored, http: HttpOptions): Channel[] { + const channels: Channel[] = []; + const { ntfy, webhook } = stored; + if (ntfy !== null) { + channels.push({ + id: "ntfy", + send: (notice) => + post( + ntfy.server, + { topic: ntfy.topic, title: notice.title, message: notice.message, tags: [notice.event] }, + ntfy.token === null ? {} : { authorization: `Bearer ${ntfy.token}` }, + http, + ), + }); + } + if (webhook !== null) { + channels.push({ + id: "webhook", + send: (notice) => + post(webhook.url, { event: notice.event, title: notice.title, message: notice.message }, {}, http), + }); + } + return channels; +} + +/** + * POSTs JSON. Redirects are not followed, the answer's body is never read, and every failure + * is told in words without the URL. + */ +async function post(url: string, body: unknown, headers: Record, http: HttpOptions) { + let response: Response; + try { + response = await fetch(url, { + method: "POST", + headers: { "content-type": "application/json", ...headers }, + body: JSON.stringify(body), + redirect: "manual", + signal: AbortSignal.timeout(http.timeoutMs), + }); + } catch (error) { + if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) { + throw new DeliveryError(`No answer within ${seconds(http.timeoutMs)}.`, true); + } + throw new DeliveryError("The server could not be reached.", true); + } + await response.body?.cancel().catch(() => {}); + if (response.ok) return; + const { status } = response; + if (status >= 300 && status < 400) { + throw new DeliveryError( + `The server answered ${status}, a redirect: Selects does not follow redirects.`, + false, + ); + } + throw new DeliveryError(`The server answered ${status}.`, status >= 500 || status === 429); +} + +const TEST_NOTICE: Notice = { + event: "test", + title: "Selects test", + message: "Notifications from Selects reach this topic.", +}; + +// An unexpected error is told without its message, which may hold the URL, and tried again. +const asDeliveryError = (error: unknown) => + error instanceof DeliveryError ? error : new DeliveryError("Something went wrong.", true); + +const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`; + +/** + * Notifications (docs/PRODUCT.md, "Notifications"; ADR 0009): an ntfy topic and a webhook, and + * four events, each switchable. + */ +export function createNotifier(options: NotifierOptions) { + const { db } = options; + const http: HttpOptions = { timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS }; + const makeChannels = options.channels ?? httpChannels; + + const readKey = (key: string): Partial => { + const row = db.query<{ value: string }, [string]>("SELECT value FROM settings WHERE key = ?").get(key); + return row === null ? {} : (JSON.parse(row.value) as Partial); + }; + const writeKey = (key: string, value: unknown) => { + db.query( + "INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value", + ).run(key, JSON.stringify(value)); + }; + const read = (): Stored => { + const saved = readKey(KEY); + return { ntfy: saved.ntfy ?? null, webhook: saved.webhook ?? null }; + }; + const write = (value: Stored) => writeKey(KEY, value); + + const statuses = () => readKey>(STATUS_KEY); + const statusOf = (id: ChannelId): ChannelStatus => statuses()[id] ?? { lastError: null, lastSentAt: null }; + const setStatus = (id: ChannelId, status: ChannelStatus) => + writeKey(STATUS_KEY, { ...statuses(), [id]: status }); + /** Records how a delivery went, as the channel's last error or its last success. */ + const recordDelivery = (id: ChannelId, error: DeliveryError | undefined) => { + const status = statusOf(id); + setStatus( + id, + error === undefined + ? { lastError: null, lastSentAt: options.clock.now() } + : { ...status, lastError: { at: options.clock.now(), reason: error.message } }, + ); + }; + + const channel = (id: ChannelId) => makeChannels(read(), http).find((found) => found.id === id); + + const events = (): EventSettings => { + const saved = readKey(EVENTS_KEY); + return { + events: { ...DEFAULT_EVENTS.events, ...saved.events }, + poolThreshold: saved.poolThreshold ?? DEFAULT_EVENTS.poolThreshold, + }; + }; + + type Logged = SentNotice & { id: string }; + const logged = (): Logged[] => { + const row = db + .query<{ value: string }, [string]>("SELECT value FROM settings WHERE key = ?") + .get(LOG_KEY); + return row === null ? [] : (JSON.parse(row.value) as Logged[]); + }; + const recent = (): SentNotice[] => logged().map(({ id: _, ...entry }) => entry); + const log = (entry: Logged) => writeKey(LOG_KEY, [entry, ...logged()].slice(0, RECENT_KEPT)); + const settle = (id: string, outcome: SentNotice["outcome"]) => + writeKey( + LOG_KEY, + logged().map((entry) => (entry.id === id ? { ...entry, outcome } : entry)), + ); + + const checkState = (): CheckState => ({ + poolLow: false, + tokenWarnedAt: null, + ...readKey(STATE_KEY), + }); + const setCheckState = (state: CheckState) => writeKey(STATE_KEY, state); + + /** Deliveries on their way, so `idle` can wait for them. */ + const pending = new Set>(); + + /** One channel, with two retries for a failure worth retrying. Never throws. */ + async function deliver(target: Channel, notice: Notice): Promise { + for (let attempt = 0; ; attempt++) { + try { + await target.send(notice); + recordDelivery(target.id, undefined); + return true; + } catch (error) { + const failure = asDeliveryError(error); + const wait = RETRY_DELAYS_MS[attempt]; + if (!failure.retry || wait === undefined) { + recordDelivery(target.id, failure); + console.error(`A notification could not be sent to the ${target.id} channel: ${failure.message}`); + return false; + } + await options.clock.sleep(wait); + } + } + } + + /** + * Sends a notice for an event that is switched on, in the background: it never blocks or + * throws into its caller. In fake mode it is recorded only. + */ + function send(notice: Notice & { event: NotifyEvent }) { + try { + if (!events().events[notice.event]) return; + const targets = makeChannels(read(), http); + const id = randomUUID(); + const outcome = targets.length === 0 ? "no-channel" : options.mode === "fake" ? "would-send" : "sent"; + log({ id, at: options.clock.now(), ...notice, outcome }); + if (outcome !== "sent") return; + const delivery = Promise.all(targets.map((target) => deliver(target, notice))) + .then((results) => { + if (results.some((ok) => !ok)) settle(id, "failed"); + }) + .catch((error) => console.error(`A notification could not be sent (${errorName(error)}).`)); + pending.add(delivery); + void delivery.finally(() => pending.delete(delivery)); + } catch (error) { + console.error(`A notification could not be sent (${errorName(error)}).`); + } + } + + return { + /** Told by the publisher as each post settles. A post resolved by hand is not told. */ + postSettled(outcome: PostOutcome): void { + if (outcome === "published") { + let pool: number | undefined; + try { + pool = options.poolSize(); + } catch {} + send({ + event: "posted", + title: "Posted to Instagram", + message: `A select was posted.${pool === undefined ? "" : ` ${plural(pool, "select is", "selects are")} left in the pool.`}`, + }); + } else if (outcome === "failed") { + send({ + event: "failed", + title: "A post failed", + message: "A post failed and its select is back in the pool. The Posted screen says why.", + }); + } else { + send({ + event: "failed", + title: "A post needs checking", + message: + "Instagram was asked to publish a post and has not said whether it did. Say what happened on the Posted screen.", + }); + } + }, + + /** + * Checks the token and the pool, and notifies what needs telling. Run on a timer and after + * each slot; never throws. + */ + check(): void { + try { + const state = checkState(); + const now = options.clock.now(); + const token = tokenNotice(options.account(), now); + if (token === undefined) state.tokenWarnedAt = null; + else if ( + events().events.token && + (state.tokenWarnedAt === null || now - state.tokenWarnedAt >= TOKEN_REPEAT_MS) + ) { + send(token); + state.tokenWarnedAt = now; + } + const pool = options.poolSize(); + const { poolThreshold } = events(); + if (pool >= poolThreshold) state.poolLow = false; + else if (!state.poolLow) { + state.poolLow = true; + send({ + event: "pool", + title: "The pool is running low", + message: `${plural(pool, "select is", "selects are")} left in the pool, below the ${poolThreshold} you set. Upload more to keep posting.`, + }); + } + setCheckState(state); + } catch (error) { + console.error(`Notifications could not be checked (${errorName(error)}).`); + } + }, + + events, + + setEvents(settings: EventSettings): EventSettings { + writeKey(EVENTS_KEY, settings); + return settings; + }, + + /** The latest notices, newest first. */ + recent, + + /** Settles once every delivery on its way has finished. */ + async idle(): Promise { + while (pending.size > 0) await Promise.all([...pending]); + }, + + view(): NotificationsView { + const { ntfy, webhook } = read(); + return { + mode: options.mode, + ntfy: + ntfy === null + ? null + : { + server: ntfy.server, + topic: `${ntfy.topic.slice(0, 3)}…`, + token: ntfy.token !== null, + ...statusOf("ntfy"), + }, + webhook: webhook === null ? null : { url: shownUrl(webhook.url), ...statusOf("webhook") }, + }; + }, + + /** Saves the ntfy topic, or removes it with null. A new topic starts with no last error. */ + setNtfy(config: NtfyConfig | null): SaveResult { + if (config !== null) { + const problems = [ + urlProblem(config.server, "The server"), + TOPIC_PATTERN.test(config.topic) ? undefined : "The topic must be 1 to 64 letters, digits, - or _.", + config.token !== null && (config.token.length > 512 || /\s/.test(config.token)) + ? "The access token must be at most 512 characters, without spaces." + : undefined, + ].filter((problem): problem is string => problem !== undefined); + if (problems.length > 0) return { ok: false, problems }; + } + const server = config?.server.replace(/\/+$/, ""); + write({ ...read(), ntfy: config === null ? null : { ...config, server: server ?? config.server } }); + setStatus("ntfy", { lastError: null, lastSentAt: null }); + return { ok: true }; + }, + + /** Saves the webhook, or removes it with null. */ + setWebhook(config: WebhookConfig | null): SaveResult { + if (config !== null) { + const problem = urlProblem(config.url, "The webhook URL"); + if (problem !== undefined) return { ok: false, problems: [problem] }; + } + write({ ...read(), webhook: config }); + setStatus("webhook", { lastError: null, lastSentAt: null }); + return { ok: true }; + }, + + /** + * Sends a test notice through one channel and says how it went. In fake mode nothing is + * sent: it says what would have been. + */ + async test(id: ChannelId): Promise { + const found = channel(id); + if (found === undefined) return { status: "not-configured" }; + if (options.mode === "fake") { + return { + status: "would-send", + message: `Fake mode: nothing was sent. With INSTAGRAM_API=live, a test notice would be sent to this ${id === "ntfy" ? "topic" : "webhook"}.`, + }; + } + try { + await found.send(TEST_NOTICE); + recordDelivery(id, undefined); + return { status: "sent" }; + } catch (error) { + const failure = asDeliveryError(error); + recordDelivery(id, failure); + return { status: "failed", reason: failure.message }; + } + }, + }; +} + +export type Notifier = ReturnType; + +/** What to tell about the token, or undefined when nothing needs telling. */ +function tokenNotice(account: AccountView | null, now: number): (Notice & { event: "token" }) | undefined { + if (account === null) return undefined; + if (account.status === "invalid") { + return { + event: "token", + title: "The Instagram token no longer works", + message: + "Instagram no longer accepts the token. Nothing posts until a new token is pasted in Settings.", + }; + } + if (account.expiresAt === null || account.expiresAt - now > TOKEN_WARNING_MS) return undefined; + const days = Math.ceil((account.expiresAt - now) / DAY); + const unrefreshed = account.refresh === "failed" ? " and could not be refreshed" : ""; + return { + event: "token", + title: "The Instagram token expires soon", + message: + days <= 0 + ? "The Instagram token has expired. Paste a new token in Settings." + : `The Instagram token expires in ${plural(days, "day", "days")}${unrefreshed}. Paste a new token in Settings before then.`, + }; +} + +const errorName = (error: unknown) => (error instanceof Error ? error.name : "unknown error"); From 24b579695f486a9a12fc669933ea99349cf62dd9 Mon Sep 17 00:00:00 2001 From: Brandon Ly Date: Fri, 13 Nov 2026 11:37:09 +0000 Subject: [PATCH 03/13] feat(server): back up the database nightly, keeping seven copies --- server/src/backup.test.ts | 186 ++++++++++++++++++++++++++++++++++++++ server/src/backup.ts | 166 ++++++++++++++++++++++++++++++++++ 2 files changed, 352 insertions(+) create mode 100644 server/src/backup.test.ts create mode 100644 server/src/backup.ts diff --git a/server/src/backup.test.ts b/server/src/backup.test.ts new file mode 100644 index 0000000..db8e773 --- /dev/null +++ b/server/src/backup.test.ts @@ -0,0 +1,186 @@ +import { Database } from "bun:sqlite"; +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { BACKUPS_KEPT, createBackups } from "./backup"; +import { createFakeClock, DAY, type FakeClock, HOUR, MINUTE } from "./clock"; +import { openDatabase } from "./db"; +import { migrations } from "./migrations"; + +let dataDir: string; +let db: Database; +let clock: FakeClock; +beforeEach(() => { + dataDir = mkdtempSync(join(tmpdir(), "selects-backup-")); + db = openDatabase(dataDir, migrations); + // 09:00 UTC. + clock = createFakeClock(Date.parse("2026-11-13T09:00:00Z")); +}); +afterEach(() => { + db.close(); + rmSync(dataDir, { recursive: true, force: true }); +}); + +const backupDir = () => join(dataDir, "backups"); +const copies = () => readdirSync(backupDir()).sort(); + +function backupsWith(timeZone = "UTC") { + return createBackups({ db, dataDir, clock, timeZone: () => timeZone }); +} + +describe("a backup", () => { + test("opens as a valid database holding the rows the live one held, readable by the owner only", async () => { + db.query("INSERT INTO settings (key, value) VALUES (?, ?)").run("backup-test", '"kept"'); + const backups = backupsWith(); + + await backups.run(); + + expect(copies()).toEqual(["selects-2026-11-13.db"]); + const file = join(backupDir(), "selects-2026-11-13.db"); + expect(statSync(file).mode & 0o777).toBe(0o600); + const copy = new Database(file, { readonly: true, strict: true }); + try { + expect(copy.query("PRAGMA integrity_check").get()).toEqual({ integrity_check: "ok" }); + expect(copy.query("PRAGMA user_version").get()).toEqual({ user_version: migrations.length }); + expect(copy.query("SELECT value FROM settings WHERE key = 'backup-test'").get()).toEqual({ + value: '"kept"', + }); + } finally { + copy.close(); + } + }); + + test("taken while another connection is writing holds only what was committed", async () => { + const writer = new Database(join(dataDir, "selects.db"), { strict: true }); + try { + writer.run("BEGIN IMMEDIATE"); + writer.query("INSERT INTO settings (key, value) VALUES ('uncommitted', '1')").run(); + + await backupsWith().run(); + + writer.run("ROLLBACK"); + } finally { + writer.close(); + } + const copy = new Database(join(backupDir(), "selects-2026-11-13.db"), { readonly: true, strict: true }); + try { + expect(copy.query("SELECT key FROM settings WHERE key = 'uncommitted'").get()).toBeNull(); + expect(copy.query("PRAGMA integrity_check").get()).toEqual({ integrity_check: "ok" }); + } finally { + copy.close(); + } + }); + + test("is named by its date in the install's timezone, and seven are kept", async () => { + // Fourteen hours ahead of UTC: 11:00 UTC is already the next day there. + clock.advance(2 * HOUR); + const backups = backupsWith("Etc/GMT-14"); + + for (let day = 0; day < 9; day++) { + await backups.run(); + clock.advance(DAY); + } + + expect(BACKUPS_KEPT).toBe(7); + expect(copies()).toEqual([ + "selects-2026-11-16.db", + "selects-2026-11-17.db", + "selects-2026-11-18.db", + "selects-2026-11-19.db", + "selects-2026-11-20.db", + "selects-2026-11-21.db", + "selects-2026-11-22.db", + ]); + expect(backups.status().copies.map((copy) => copy.name)).toEqual([...copies()].reverse()); + }); + + test("taken twice on one day replaces that day's copy, and leaves no temporary file", async () => { + const backups = backupsWith(); + await backups.run(); + clock.advance(HOUR); + db.query("INSERT INTO settings (key, value) VALUES ('later', '1')").run(); + + await backups.run(); + + expect(copies()).toEqual(["selects-2026-11-13.db"]); + const copy = new Database(join(backupDir(), "selects-2026-11-13.db"), { readonly: true, strict: true }); + expect(copy.query("SELECT value FROM settings WHERE key = 'later'").get()).toEqual({ value: "1" }); + copy.close(); + }); + + test("never runs twice at once", async () => { + const backups = backupsWith(); + + const [first, second] = [backups.run(), backups.run()]; + + expect(first).toBe(second); + await first; + expect(copies()).toEqual(["selects-2026-11-13.db"]); + }); +}); + +describe("the nightly backup", () => { + test("runs at start when there is no copy, then at 03:30 in the install's timezone", async () => { + // Five hours behind UTC: 09:00 UTC is 04:00 there. + const backups = backupsWith("Etc/GMT+5"); + + await backups.runDue(); + expect(backups.status().lastAt).toBe(clock.now()); + + // 03:29 there the next day: not yet. + clock.advance(DAY - 31 * MINUTE); + await backups.runDue(); + expect(copies()).toEqual(["selects-2026-11-13.db"]); + + clock.advance(MINUTE); + await backups.runDue(); + expect(copies()).toEqual(["selects-2026-11-13.db", "selects-2026-11-14.db"]); + + // Once that night. + const at = backups.status().lastAt; + clock.advance(10 * MINUTE); + await backups.runDue(); + expect(backups.status().lastAt).toBe(at); + }); + + test("runs at start when the last copy is more than a day old, and not when it is from last night", async () => { + const backups = backupsWith(); + await backups.run(); + + // 02:00 the next day: last night's 03:30 has its copy. + clock.advance(17 * HOUR); + await backups.runDue(); + expect(backups.status().lastAt).toBe(clock.now() - 17 * HOUR); + + // Down for two days: a copy at start. + clock.advance(2 * DAY); + const restarted = backupsWith(); + await restarted.runDue(); + expect(restarted.status().lastAt).toBe(clock.now()); + }); + + test("that fails shows why in its status, and is tried again an hour later, not every minute", async () => { + // Something that is not a directory where the copies go. + writeFileSync(backupDir(), ""); + const backups = backupsWith(); + + await backups.runDue(); + const failed = backups.status(); + expect(failed.lastAt).toBeNull(); + expect(failed.lastError).toEqual({ + at: clock.now(), + reason: expect.stringMatching(/^The backup failed/), + }); + expect(failed.lastError?.reason).not.toContain(dataDir); + + rmSync(backupDir()); + clock.advance(MINUTE); + await backups.runDue(); + expect(backups.status().lastAt).toBeNull(); + + clock.advance(HOUR); + await backups.runDue(); + expect(backups.status()).toMatchObject({ lastAt: clock.now(), lastError: null }); + }); +}); diff --git a/server/src/backup.ts b/server/src/backup.ts new file mode 100644 index 0000000..86ec760 --- /dev/null +++ b/server/src/backup.ts @@ -0,0 +1,166 @@ +import type { Database } from "bun:sqlite"; +import { randomUUID } from "node:crypto"; +import { + chmodSync, + closeSync, + mkdirSync, + openSync, + readdirSync, + renameSync, + rmSync, + statSync, + utimesSync, +} from "node:fs"; +import { join } from "node:path"; +import { type Clock, DAY, HOUR } from "./clock"; +import { errorKind } from "./library"; +import { isTimeZone, localDate, zonedInstant } from "./slots"; + +/** Copies kept: a week of nights. */ +export const BACKUPS_KEPT = 7; +/** When the nightly copy is made, in the install's timezone. */ +export const BACKUP_TIME = "03:30"; +/** How long after a failed backup it is tried again. */ +const RETRY_AFTER_MS = HOUR; + +const COPY_NAME = /^selects-\d{4}-\d{2}-\d{2}\.db$/; +const TEMPORARY = /^\.selects-.*\.tmp$/; + +export type BackupCopy = { name: string; at: number; bytes: number }; + +export type BackupStatus = { + /** When the latest copy was made; null with none. */ + lastAt: number | null; + /** Why the last try failed, when it did and no copy has been made since. */ + lastError: { at: number; reason: string } | null; + /** Newest first. */ + copies: BackupCopy[]; + kept: number; + time: string; + timeZone: string; +}; + +export type BackupsOptions = { + db: Database; + dataDir: string; + clock: Clock; + /** The install's timezone: the scheduler's. */ + timeZone: () => string; +}; + +/** + * Nightly copies of the database in `backups` in the data volume (docs/PRODUCT.md, + * "Configuration and operations"; ADR 0009). Each is made with `VACUUM INTO` from the app's own + * connection: a read transaction, so the copy is one consistent snapshot while Selects runs, and + * nothing in the WAL is lost. It is written owner-only under a temporary name and renamed, so a + * copy on disk is always whole. Named by its date in the install's timezone; seven are kept. + */ +export function createBackups(options: BackupsOptions) { + const { db, clock } = options; + const dir = join(options.dataDir, "backups"); + let lastError: BackupStatus["lastError"] = null; + let running: Promise | undefined; + + const timeZone = () => { + const zone = options.timeZone(); + return isTimeZone(zone) ? zone : "UTC"; + }; + + function listCopies(): BackupCopy[] { + let names: string[]; + try { + names = readdirSync(dir); + } catch { + return []; + } + return names + .filter((name) => COPY_NAME.test(name)) + .sort() + .reverse() + .flatMap((name) => { + const stats = statSync(join(dir, name), { throwIfNoEntry: false }); + return stats?.isFile() ? [{ name, at: stats.mtimeMs, bytes: stats.size }] : []; + }); + } + + /** The latest 03:30 in the install's timezone at or before `now`. */ + function latestNight(now: number): number { + const zone = timeZone(); + const today = zonedInstant(localDate(now, zone), BACKUP_TIME, zone); + if (today <= now) return today; + return zonedInstant(localDate(now - DAY, zone), BACKUP_TIME, zone); + } + + function backUp() { + const now = clock.now(); + const name = `selects-${localDate(now, timeZone())}.db`; + mkdirSync(dir, { recursive: true, mode: 0o700 }); + // Leftovers of a copy a stop interrupted. + for (const found of readdirSync(dir)) { + if (TEMPORARY.test(found)) rmSync(join(dir, found), { force: true }); + } + const temporary = join(dir, `.${name}.${randomUUID()}.tmp`); + // Created owner-only and empty: VACUUM INTO writes into an empty file, keeping its mode. + closeSync(openSync(temporary, "wx", 0o600)); + try { + db.query("VACUUM INTO ?").run(temporary); + chmodSync(temporary, 0o600); + utimesSync(temporary, now / 1000, now / 1000); + renameSync(temporary, join(dir, name)); + } catch (error) { + rmSync(temporary, { force: true }); + throw error; + } + for (const old of listCopies().slice(BACKUPS_KEPT)) rmSync(join(dir, old.name), { force: true }); + } + + function run(): Promise { + if (running !== undefined) return running; + running = Promise.resolve() + .then(() => { + try { + backUp(); + lastError = null; + } catch (error) { + // The kind only: the message can carry the data directory's path. + lastError = { at: clock.now(), reason: `The backup failed (${errorKind(error)}).` }; + console.error(`${lastError.reason} It is tried again in an hour.`); + } + }) + .finally(() => { + running = undefined; + }); + return running; + } + + return { + /** Makes a copy now. A call while one is being made joins it. Never throws. */ + run, + + /** + * Makes a copy when the latest 03:30 has none: nightly, and at start when the last copy is + * from before last night. After a failure, waits an hour. Called on a timer. + */ + runDue(): Promise { + const now = clock.now(); + const last = listCopies()[0]?.at ?? null; + if (last !== null && last >= latestNight(now)) return Promise.resolve(); + if (lastError !== null && now - lastError.at < RETRY_AFTER_MS) return Promise.resolve(); + return run(); + }, + + status(): BackupStatus { + const copies = listCopies(); + return { + lastAt: copies[0]?.at ?? null, + lastError, + copies, + kept: BACKUPS_KEPT, + time: BACKUP_TIME, + timeZone: timeZone(), + }; + }, + }; +} + +export type Backups = ReturnType; From 58e142ea26e6fa46e710673f356d76045121499a Mon Sep 17 00:00:00 2001 From: Brandon Ly Date: Fri, 13 Nov 2026 11:39:30 +0000 Subject: [PATCH 04/13] feat(server): serve notification and backup settings, and run them on a timer --- server/src/app.ts | 39 +++++++++- server/src/main.ts | 10 +++ server/src/notify-api.test.ts | 140 ++++++++++++++++++++++++++++++++++ server/src/notify-routes.ts | 87 +++++++++++++++++++++ 4 files changed, 275 insertions(+), 1 deletion(-) create mode 100644 server/src/notify-api.test.ts create mode 100644 server/src/notify-routes.ts diff --git a/server/src/app.ts b/server/src/app.ts index 245ba7f..2ba1b60 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -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"; @@ -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 } from "./notify"; +import { notifyRoutes } from "./notify-routes"; import { passwordGate } from "./password"; import { publishRoutes } from "./publish-routes"; import { createPublisher } from "./publisher"; @@ -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"; @@ -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, @@ -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, @@ -190,6 +220,8 @@ function createServices({ gallery, bucket, scheduler, + notifier, + backups, }; } @@ -225,6 +257,8 @@ function createRoutes( gallery, bucket, scheduler, + notifier, + backups, }: Services, ) { const uploadDir = join(config.dataDir, "uploads"); @@ -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), @@ -458,6 +493,8 @@ 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 => { if (isCrossOrigin(request)) return Response.json({ error: "Forbidden" }, { status: 403 }); return (await gate?.(request)) ?? routes.handle(request); diff --git a/server/src/main.ts b/server/src/main.ts index 8b675a2..12edfd7 100644 --- a/server/src/main.ts +++ b/server/src/main.ts @@ -18,6 +18,8 @@ const RETRY_INTERVAL_MS = 30 * 1000; const GALLERY_INTERVAL_MS = 30 * 1000; /** How often the Instagram token is checked for a refresh. */ const TOKEN_CHECK_INTERVAL_MS = HOUR; +/** How often the token and the pool are checked for notifications, and the nightly backup for being due. */ +const HOUSEKEEPING_INTERVAL_MS = 60 * 1000; const webDir = resolve(import.meta.dir, "../../web/dist"); @@ -114,6 +116,13 @@ const scheduleTimer = setInterval(tick, SCHEDULE_INTERVAL_MS); const refreshToken = () => app.instagramAccount.refreshIfDue().catch(() => {}); void refreshToken(); const tokenTimer = setInterval(refreshToken, TOKEN_CHECK_INTERVAL_MS); +// Neither throws. The backup runs at start when the last copy is from before last night. +const housekeeping = () => { + app.notifier.check(); + void app.backups.runDue(); +}; +housekeeping(); +const housekeepingTimer = setInterval(housekeeping, HOUSEKEEPING_INTERVAL_MS); const shutdown = () => { clearInterval(inboxTimer); @@ -121,6 +130,7 @@ const shutdown = () => { clearInterval(galleryTimer); clearInterval(scheduleTimer); clearInterval(tokenTimer); + clearInterval(housekeepingTimer); // Let requests in flight finish, the fakes they may be using still up, before the database closes. server .stop() diff --git a/server/src/notify-api.test.ts b/server/src/notify-api.test.ts new file mode 100644 index 0000000..89faded --- /dev/null +++ b/server/src/notify-api.test.ts @@ -0,0 +1,140 @@ +import type { Database } from "bun:sqlite"; +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createApp } from "./app"; +import { createFakeClock } from "./clock"; +import { loadConfig } from "./config"; +import { openDatabase } from "./db"; +import { migrations } from "./migrations"; + +const TOPIC = "selects-api-topic-0001"; +const NTFY_TOKEN = "tk_fake_api_token_0001"; +const HOOK_SECRET = "api-hook-secret-0001"; + +let dataDir: string; +let db: Database; +let app: ReturnType; +let received: number; +let receiver: ReturnType; +beforeEach(() => { + dataDir = mkdtempSync(join(tmpdir(), "selects-notify-api-")); + db = openDatabase(dataDir, migrations); + received = 0; + receiver = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + fetch: () => { + received++; + return new Response("ok"); + }, + }); + // Fake mode, the default. + app = createApp({ + config: loadConfig({ DATA_DIR: dataDir }), + db, + webDir: join(dataDir, "no-ui"), + clock: createFakeClock(), + }); +}); +afterEach(async () => { + await receiver.stop(true); + db.close(); + rmSync(dataDir, { recursive: true, force: true }); +}); + +const send = (method: string, path: string, body?: unknown) => + app.fetch( + new Request(`http://selects.test${path}`, { + method, + headers: body === undefined ? {} : { "content-type": "application/json" }, + body: body === undefined ? undefined : JSON.stringify(body), + }), + ); + +describe("notification settings", () => { + test("an ntfy topic and a webhook are saved, shown without their secrets, and tested", async () => { + const ntfy = await send("PUT", "/api/notifications/ntfy", { + server: `http://127.0.0.1:${receiver.port}`, + topic: TOPIC, + token: NTFY_TOKEN, + }); + expect(ntfy.status).toBe(200); + const hook = await send("PUT", "/api/notifications/webhook", { + url: `http://127.0.0.1:${receiver.port}/hooks/${HOOK_SECRET}`, + }); + expect(hook.status).toBe(200); + + const view = await (await send("GET", "/api/notifications")).json(); + expect(view).toMatchObject({ + mode: "fake", + ntfy: { topic: "sel…", token: true, lastError: null }, + webhook: { url: `http://127.0.0.1:${receiver.port}/…` }, + events: { posted: true, failed: true, token: true, pool: true }, + poolThreshold: 10, + recent: [], + }); + for (const secret of [TOPIC, NTFY_TOKEN, HOOK_SECRET]) expect(JSON.stringify(view)).not.toContain(secret); + + for (const channel of ["ntfy", "webhook"]) { + const tested = await send("POST", `/api/notifications/${channel}/test`); + expect(tested.status).toBe(200); + expect(await tested.json()).toMatchObject({ status: "would-send" }); + } + // Fake mode: nothing left the process. + expect(received).toBe(0); + }); + + test("a URL that is not http or https is refused with the reason", async () => { + const response = await send("PUT", "/api/notifications/webhook", { url: "file:///etc/passwd" }); + + expect(response.status).toBe(422); + expect(await response.json()).toEqual({ problems: ["The webhook URL must be an http or https URL."] }); + }); + + test("a channel is removed", async () => { + await send("PUT", "/api/notifications/webhook", { url: "https://hooks.invalid/x" }); + + expect((await send("DELETE", "/api/notifications/webhook")).status).toBe(204); + + expect( + ((await (await send("GET", "/api/notifications")).json()) as { webhook: unknown }).webhook, + ).toBeNull(); + expect((await send("POST", "/api/notifications/webhook/test")).status).toBe(404); + }); + + test("each event's switch and the pool threshold are saved", async () => { + const saved = await send("PUT", "/api/notifications/events", { + events: { posted: false, failed: true, token: true, pool: false }, + poolThreshold: 25, + }); + + expect(saved.status).toBe(200); + expect(await (await send("GET", "/api/notifications")).json()).toMatchObject({ + events: { posted: false, failed: true, token: true, pool: false }, + poolThreshold: 25, + }); + const bad = await send("PUT", "/api/notifications/events", { + events: { posted: true, failed: true, token: true, pool: true }, + poolThreshold: 0, + }); + expect(bad.status).toBe(422); + }); +}); + +describe("backups", () => { + test("show the last copy and the copies kept", async () => { + const response = await send("GET", "/api/backups"); + + expect(response.status).toBe(200); + expect(await response.json()).toMatchObject({ + lastAt: null, + lastError: null, + copies: [], + kept: 7, + time: "03:30", + timeZone: "UTC", + }); + }); +}); diff --git a/server/src/notify-routes.ts b/server/src/notify-routes.ts new file mode 100644 index 0000000..a540630 --- /dev/null +++ b/server/src/notify-routes.ts @@ -0,0 +1,87 @@ +import { Elysia, t } from "elysia"; +import type { Backups } from "./backup"; +import { type ChannelId, type Notifier, POOL_THRESHOLD_LIMITS } from "./notify"; + +const notFound = { error: "Not found" } as const; + +const eventsSchema = t.Object( + { + events: t.Object( + { posted: t.Boolean(), failed: t.Boolean(), token: t.Boolean(), pool: t.Boolean() }, + { additionalProperties: false }, + ), + poolThreshold: t.Integer({ minimum: POOL_THRESHOLD_LIMITS.min, maximum: POOL_THRESHOLD_LIMITS.max }), + }, + { additionalProperties: false }, +); + +const channelParam = t.Object({ channel: t.Union([t.Literal("ntfy"), t.Literal("webhook")]) }); + +/** + * Notifications and backups in Settings. A channel's topic, token and URL are taken in and never + * given back whole. + */ +export function notifyRoutes({ notifier, backups }: { notifier: Notifier; backups: Backups }) { + const view = () => ({ ...notifier.view(), ...notifier.events(), recent: notifier.recent() }); + return new Elysia() + .get("/api/notifications", view) + .put( + "/api/notifications/events", + ({ body }) => { + notifier.setEvents(body); + // A threshold raised past the pool tells it now, not at the next check. + notifier.check(); + return view(); + }, + { body: eventsSchema }, + ) + .put( + "/api/notifications/ntfy", + ({ body, status }) => { + const token = body.token?.trim() ?? ""; + const saved = notifier.setNtfy({ + server: body.server.trim(), + topic: body.topic.trim(), + token: token === "" ? null : token, + }); + return saved.ok ? view() : status(422, { problems: saved.problems }); + }, + { + body: t.Object( + { + server: t.String({ maxLength: 2048 }), + topic: t.String({ maxLength: 64 }), + token: t.Optional(t.Union([t.String({ maxLength: 512 }), t.Null()])), + }, + { additionalProperties: false }, + ), + }, + ) + .put( + "/api/notifications/webhook", + ({ body, status }) => { + const saved = notifier.setWebhook({ url: body.url.trim() }); + return saved.ok ? view() : status(422, { problems: saved.problems }); + }, + { body: t.Object({ url: t.String({ maxLength: 2048 }) }, { additionalProperties: false }) }, + ) + .delete( + "/api/notifications/:channel", + ({ params, status }) => { + if (params.channel === "ntfy") notifier.setNtfy(null); + else notifier.setWebhook(null); + return status(204); + }, + { params: channelParam }, + ) + .post( + "/api/notifications/:channel/test", + async ({ params, status }) => { + const result = await notifier.test(params.channel as ChannelId); + if (result.status === "not-configured") return status(404, notFound); + return result; + }, + { params: channelParam }, + ) + .get("/api/backups", () => backups.status()); +} From 7a251bdd796d513f6d8bc1c230b88166de9e5b95 Mon Sep 17 00:00:00 2001 From: Brandon Ly Date: Fri, 13 Nov 2026 11:42:11 +0000 Subject: [PATCH 05/13] feat(web): set up notifications and show backups in Settings --- web/src/components/backup-status.tsx | 55 ++ web/src/components/notification-settings.tsx | 526 +++++++++++++++++++ web/src/lib/notifications.test.ts | 43 ++ web/src/lib/notifications.ts | 44 ++ web/src/screens/settings.tsx | 4 + 5 files changed, 672 insertions(+) create mode 100644 web/src/components/backup-status.tsx create mode 100644 web/src/components/notification-settings.tsx create mode 100644 web/src/lib/notifications.test.ts create mode 100644 web/src/lib/notifications.ts diff --git a/web/src/components/backup-status.tsx b/web/src/components/backup-status.tsx new file mode 100644 index 0000000..4936ff2 --- /dev/null +++ b/web/src/components/backup-status.tsx @@ -0,0 +1,55 @@ +import type { BackupStatus as Status } from "@selects/server"; +import { useEffect, useState } from "react"; +import { api } from "@/api"; + +const formatTime = (at: number) => + new Date(at).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" }); + +/** The nightly backup: when the last copy was made, and why the last try failed if it did. */ +export function BackupStatus() { + const [status, setStatus] = useState(); + const [loadError, setLoadError] = useState(false); + + useEffect(() => { + let live = true; + api.backups + .get() + .then(({ data, error }) => { + if (!live) return; + if (data) setStatus(data); + setLoadError(error !== null); + }) + .catch(() => { + if (live) setLoadError(true); + }); + return () => { + live = false; + }; + }, []); + + return ( +
+

+ Backups +

+ {loadError &&

Can't reach the server.

} + {status !== undefined && ( +
+

+ {status.lastAt === null ? "No copy yet." : `Last copy ${formatTime(status.lastAt)}.`} +

+ {status.lastError !== null && ( +

+ The last try failed {formatTime(status.lastError.at)}: {status.lastError.reason} Selects tries + again in an hour. +

+ )} +

+ The database is copied each night at {status.time} ({status.timeZone}) into backups{" "} + in the data folder, and the latest {status.kept} are kept. The README says how to restore one. +

+
+ )} +
+ ); +} diff --git a/web/src/components/notification-settings.tsx b/web/src/components/notification-settings.tsx new file mode 100644 index 0000000..eabba0d --- /dev/null +++ b/web/src/components/notification-settings.tsx @@ -0,0 +1,526 @@ +import type { NotificationsView, NotifyEvent, SentNotice } from "@selects/server"; +import { type FormEvent, type ReactNode, useCallback, useEffect, useMemo, useState } from "react"; +import { api } from "@/api"; +import { Button } from "@/components/ui/button"; +import { problemsIn, useAutosave } from "@/lib/autosave"; +import { + type EventSettings, + type EventsDraft, + outcomeText, + parseEvents, + testResultText, +} from "@/lib/notifications"; +import { SaveStatus } from "./schedule-editor"; + +type Notifications = NotificationsView & EventSettings & { recent: SentNotice[] }; + +const SETTLE_MS = 600; + +const EVENT_LABELS: Record = { + posted: { label: "Posted", detail: "A post reached Instagram, and how many selects are left in the pool." }, + failed: { + label: "Failed", + detail: "A post failed for good, or Instagram has not said whether it published one.", + }, + token: { + label: "Token about to expire", + detail: "Once a day while the Instagram token expires within 7 days or no longer works.", + }, + pool: { label: "Pool running low", detail: "Once when the pool drops below the number you set." }, +}; + +const formatTime = (at: number) => + new Date(at).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" }); + +/** + * Notifications in Settings: which events notify, the ntfy topic and the webhook, each with a + * Send test, and the latest notices. Never shows a topic, token or URL in full once saved. + */ +export function NotificationSettings() { + const [view, setView] = useState(); + const [loadError, setLoadError] = useState(false); + + const load = useCallback(async () => { + try { + const { data, error } = await api.notifications.get(); + if (data) setView(data); + setLoadError(error !== null); + } catch { + setLoadError(true); + } + }, []); + + useEffect(() => { + void load(); + }, [load]); + + return ( +
+

+ Notifications +

+ {loadError &&

Can't reach the server.

} + {view !== undefined && ( + <> + {view.mode === "fake" && ( +

+ Fake mode: nothing leaves Selects. Notices are listed below as what would have been sent, and + Send test sends nothing. Set INSTAGRAM_API=live to send them. +

+ )} + setView((current) => current && { ...current, ...next })} + /> + + + + + )} +
+ ); +} + +function EventsEditor({ saved, onSaved }: { saved: EventSettings; onSaved: (next: EventSettings) => void }) { + const [draft, setDraft] = useState(() => ({ + events: saved.events, + poolThreshold: String(saved.poolThreshold), + })); + const parsed = useMemo(() => parseEvents(draft, saved), [draft, saved]); + const save = useAutosave({ + value: parsed.settings, + loaded: saved, + save: async (next) => { + const answer = await api.notifications.events.put(next); + if (answer.data) onSaved({ events: answer.data.events, poolThreshold: answer.data.poolThreshold }); + return answer; + }, + url: "/api/notifications/events", + ms: SETTLE_MS, + onNewer: (newer) => setDraft({ events: newer.events, poolThreshold: String(newer.poolThreshold) }), + }); + + return ( +
event.preventDefault()} + > +

Events

+ {(Object.keys(EVENT_LABELS) as NotifyEvent[]).map((event) => ( +
+ +

{EVENT_LABELS[event].detail}

+ {event === "pool" && ( +
+

+ Below + { + const poolThreshold = change.currentTarget.value; + setDraft((d) => ({ ...d, poolThreshold })); + }} + className="h-10 w-20 rounded-md border bg-background px-2 text-center text-base aria-invalid:border-destructive disabled:opacity-50 md:text-sm" + /> + selects in the pool. +

+ {parsed.error !== undefined && ( +

+ Pool size: {parsed.error} +

+ )} +
+ )} +
+ ))} +

+ Notices never carry a location, a file name, a caption or a link: only what happened. +

+ + + ); +} + +type ChannelStatus = { lastError: { at: number; reason: string } | null; lastSentAt: number | null }; + +/** The channel's last delivery, and Send test with its result, beside the channel's other buttons. */ +function ChannelFooter({ + channel, + status, + onChange, + children, +}: { + channel: "ntfy" | "webhook"; + status: ChannelStatus; + onChange: () => Promise; + children: ReactNode; +}) { + const [testing, setTesting] = useState(false); + const [result, setResult] = useState<{ text: string; failed: boolean } | undefined>(); + + const test = async () => { + setTesting(true); + setResult(undefined); + try { + const { data, error } = await api.notifications({ channel }).test.post(); + if (data) setResult({ text: testResultText(data), failed: data.status === "failed" }); + else if (error) setResult({ text: "Couldn't send the test. Try again.", failed: true }); + await onChange(); + } catch { + setResult({ text: "Couldn't reach the server.", failed: true }); + } finally { + setTesting(false); + } + }; + + return ( + <> + {status.lastError !== null && ( +

+ Last failed {formatTime(status.lastError.at)}: {status.lastError.reason} +

+ )} + {status.lastSentAt !== null && status.lastError === null && ( +

Last sent {formatTime(status.lastSentAt)}.

+ )} +
+ + {children} +
+ {result !== undefined && ( +

+ {result.text} +

+ )} + + ); +} + +/** Remove, after a second press. */ +function RemoveChannel({ + channel, + onChange, +}: { + channel: "ntfy" | "webhook"; + onChange: () => Promise; +}) { + const [confirm, setConfirm] = useState(false); + const [failed, setFailed] = useState(false); + const remove = async () => { + setFailed(false); + try { + const { error } = await api.notifications({ channel }).delete(); + if (error) throw error; + setConfirm(false); + await onChange(); + } catch { + setFailed(true); + } + }; + return ( + <> + {confirm ? ( + <> + + + + ) : ( + + )} + {failed &&

Couldn't remove it. Try again.

} + + ); +} + +const inputClass = "h-10 rounded-md border bg-background px-3 text-base md:text-sm"; + +function NtfyChannel({ + channel, + onChange, +}: { + channel: Notifications["ntfy"]; + onChange: () => Promise; +}) { + const [editing, setEditing] = useState(false); + const [server, setServer] = useState(""); + const [topic, setTopic] = useState(""); + const [token, setToken] = useState(""); + const [busy, setBusy] = useState(false); + const [problems, setProblems] = useState(); + + const close = () => { + // What was typed and not saved does not stay on the page. + setServer(""); + setTopic(""); + setToken(""); + setProblems(undefined); + setEditing(false); + }; + + const submit = async (event: FormEvent) => { + event.preventDefault(); + setBusy(true); + setProblems(undefined); + try { + const { error } = await api.notifications.ntfy.put({ + server, + topic, + token: token === "" ? null : token, + }); + if (error) { + setProblems(problemsIn(error.value)); + return; + } + close(); + await onChange(); + } catch { + setProblems([]); + } finally { + setBusy(false); + } + }; + + return ( +
+

ntfy

+ {channel !== null && !editing && ( +
+
Server
+
{channel.server}
+
Topic
+
{channel.topic}
+
Access token
+
{channel.token ? "Set" : "None"}
+
+ )} + {channel === null && !editing &&

Not set.

} + {editing ? ( +
+ + setServer(event.currentTarget.value)} + className={inputClass} + /> + + setTopic(event.currentTarget.value)} + className={inputClass} + /> + + setToken(event.currentTarget.value)} + className={inputClass} + /> +

+ Anyone who knows a topic's name can read it: choose one hard to guess. The topic and token are + kept on this server and never shown again in full. Saving replaces both. +

+ {problems !== undefined && ( +

+ {problems.length > 0 ? problems.join(" ") : "Couldn't save. Try again."} +

+ )} +
+ + +
+
+ ) : ( + <> + {channel === null ? ( +
+ +
+ ) : ( + + + + + )} + + )} +
+ ); +} + +function WebhookChannel({ + channel, + onChange, +}: { + channel: Notifications["webhook"]; + onChange: () => Promise; +}) { + const [editing, setEditing] = useState(false); + const [url, setUrl] = useState(""); + const [busy, setBusy] = useState(false); + const [problems, setProblems] = useState(); + + const close = () => { + setUrl(""); + setProblems(undefined); + setEditing(false); + }; + + const submit = async (event: FormEvent) => { + event.preventDefault(); + setBusy(true); + setProblems(undefined); + try { + const { error } = await api.notifications.webhook.put({ url }); + if (error) { + setProblems(problemsIn(error.value)); + return; + } + close(); + await onChange(); + } catch { + setProblems([]); + } finally { + setBusy(false); + } + }; + + return ( +
+

Webhook

+

+ The Selects server, not your browser, sends each notice to this URL as a JSON POST with its{" "} + event, title and message. Redirects are not followed. +

+ {channel !== null && !editing && ( +

+ {channel.url} +

+ )} + {channel === null && !editing &&

Not set.

} + {editing ? ( +
+ + setUrl(event.currentTarget.value)} + className={inputClass} + /> +

+ An http or https URL. Only its scheme and host are shown again: the rest may be a secret. +

+ {problems !== undefined && ( +

+ {problems.length > 0 ? problems.join(" ") : "Couldn't save. Try again."} +

+ )} +
+ + +
+
+ ) : ( + <> + {channel === null ? ( +
+ +
+ ) : ( + + + + + )} + + )} +
+ ); +} + +function RecentNotices({ recent }: { recent: SentNotice[] }) { + if (recent.length === 0) return null; + return ( +
+

Latest notices

+
    + {recent.slice(0, 5).map((notice) => ( +
  • + {notice.title} + {notice.message} + + {formatTime(notice.at)} · {outcomeText(notice.outcome)} + +
  • + ))} +
+
+ ); +} diff --git a/web/src/lib/notifications.test.ts b/web/src/lib/notifications.test.ts new file mode 100644 index 0000000..95d64cc --- /dev/null +++ b/web/src/lib/notifications.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, test } from "bun:test"; +import { outcomeText, parseEvents, testResultText } from "./notifications"; + +const saved = { events: { posted: true, failed: true, token: true, pool: true }, poolThreshold: 10 }; + +describe("parseEvents", () => { + test("takes the switches and a whole-number threshold", () => { + const draft = { events: { ...saved.events, posted: false }, poolThreshold: " 25 " }; + + expect(parseEvents(draft, saved)).toEqual({ + settings: { events: { ...saved.events, posted: false }, poolThreshold: 25 }, + error: undefined, + }); + }); + + test("keeps the saved threshold while the one typed is not a whole number from 1 to 10,000", () => { + for (const poolThreshold of ["0", "", "2.5", "10001"]) { + expect(parseEvents({ events: saved.events, poolThreshold }, saved)).toEqual({ + settings: saved, + error: "A whole number from 1 to 10,000.", + }); + } + }); +}); + +describe("what Settings says", () => { + test("about a notice", () => { + expect(outcomeText("sent")).toBe("Sent"); + expect(outcomeText("failed")).toBe("Not sent to every channel"); + expect(outcomeText("would-send")).toBe("Would have been sent (fake mode)"); + expect(outcomeText("no-channel")).toBe("No channel set"); + }); + + test("about a test", () => { + expect(testResultText({ status: "sent" })).toBe("Sent. Check that it arrived."); + expect(testResultText({ status: "failed", reason: "The server answered 403." })).toBe( + "Couldn't send: The server answered 403.", + ); + expect(testResultText({ status: "would-send", message: "Fake mode: nothing was sent." })).toBe( + "Fake mode: nothing was sent.", + ); + }); +}); diff --git a/web/src/lib/notifications.ts b/web/src/lib/notifications.ts new file mode 100644 index 0000000..94ba800 --- /dev/null +++ b/web/src/lib/notifications.ts @@ -0,0 +1,44 @@ +import type { SentNotice, TestResult } from "@selects/server"; +import { wholeNumber } from "./schedule"; + +export type EventSwitches = { posted: boolean; failed: boolean; token: boolean; pool: boolean }; +export type EventSettings = { events: EventSwitches; poolThreshold: number }; +export type EventsDraft = { events: EventSwitches; poolThreshold: string }; + +export const POOL_THRESHOLD = { min: 1, max: 10_000 } as const; + +/** The events to save: the threshold as typed while it is valid, and otherwise the one saved. */ +export function parseEvents( + draft: EventsDraft, + saved: EventSettings, +): { settings: EventSettings; error: string | undefined } { + const parsed = wholeNumber(draft.poolThreshold, POOL_THRESHOLD); + return { + settings: { events: draft.events, poolThreshold: parsed.ok ? parsed.value : saved.poolThreshold }, + error: parsed.ok ? undefined : parsed.problem, + }; +} + +export function outcomeText(outcome: SentNotice["outcome"]): string { + switch (outcome) { + case "sent": + return "Sent"; + case "failed": + return "Not sent to every channel"; + case "would-send": + return "Would have been sent (fake mode)"; + case "no-channel": + return "No channel set"; + } +} + +export function testResultText(result: Exclude): string { + switch (result.status) { + case "sent": + return "Sent. Check that it arrived."; + case "failed": + return `Couldn't send: ${result.reason}`; + case "would-send": + return result.message; + } +} diff --git a/web/src/screens/settings.tsx b/web/src/screens/settings.tsx index 4553760..d186cc6 100644 --- a/web/src/screens/settings.tsx +++ b/web/src/screens/settings.tsx @@ -1,6 +1,8 @@ import { useEffect, useState } from "react"; import { api } from "@/api"; +import { BackupStatus } from "@/components/backup-status"; import { GallerySettings } from "@/components/gallery-settings"; +import { NotificationSettings } from "@/components/notification-settings"; import { PrivacyZones } from "@/components/privacy-zones"; import { PublishingSettings } from "@/components/publishing-settings"; import { Screen } from "./screen"; @@ -44,12 +46,14 @@ export function SettingsScreen() { +

Privacy zones

+

About From 98252e7e33bd3659c83bca6ec14a37323074cb04 Mon Sep 17 00:00:00 2001 From: Brandon Ly Date: Fri, 13 Nov 2026 11:43:03 +0000 Subject: [PATCH 06/13] docs(repo): say how backups are made and how to restore one --- README.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/README.md b/README.md index 417d612..c2bda31 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,32 @@ or you say whether it was posted. Try a post with the Dry run switch on first: the Posted screen shows the frame, caption and everything a real post would send. +### 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. + +The photos are not in the database: originals, thumbnails and fonts stay in `DATA_DIR` and are +not part of a copy. Restoring takes the library, posts, schedule and settings back to the night +of the copy. A select posted since then is back in the pool and could be posted again, so as +soon as Selects starts, turn on the pause switch on the Queue screen, compare the Posted screen +with Instagram, and delete from the Library any select already on Instagram (its hash is kept, +so it is never picked again). Then turn the pause switch off. + ## Checks These run in CI on every pull request: From 5818d9a34d913475b1a443d2afcc9499bf8e8a56 Mon Sep 17 00:00:00 2001 From: Brandon Ly Date: Fri, 13 Nov 2026 11:43:03 +0000 Subject: [PATCH 07/13] docs(adr): record notification and backup decisions --- docs/adr/0009-notifications-and-backups.md | 65 ++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 docs/adr/0009-notifications-and-backups.md diff --git a/docs/adr/0009-notifications-and-backups.md b/docs/adr/0009-notifications-and-backups.md new file mode 100644 index 0000000..fe33380 --- /dev/null +++ b/docs/adr/0009-notifications-and-backups.md @@ -0,0 +1,65 @@ +# 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 and its select is back in the pool, 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. + +## 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. From 62c13570316e92dbf2bb4c2229e034443b9db82f Mon Sep 17 00:00:00 2001 From: Brandon Ly Date: Fri, 13 Nov 2026 11:43:10 +0000 Subject: [PATCH 08/13] fix(server): word the test notice for either channel --- server/src/notify.test.ts | 2 +- server/src/notify.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/server/src/notify.test.ts b/server/src/notify.test.ts index e15b9ca..a2d76ff 100644 --- a/server/src/notify.test.ts +++ b/server/src/notify.test.ts @@ -93,7 +93,7 @@ describe("ntfy", () => { expect(JSON.parse(request?.body ?? "")).toMatchObject({ topic: TOPIC, title: "Selects test", - message: "Notifications from Selects reach this topic.", + message: "A test notice from Selects: notifications arrive here.", }); }); }); diff --git a/server/src/notify.ts b/server/src/notify.ts index f74cdc2..a2a4a70 100644 --- a/server/src/notify.ts +++ b/server/src/notify.ts @@ -206,7 +206,7 @@ async function post(url: string, body: unknown, headers: Record, const TEST_NOTICE: Notice = { event: "test", title: "Selects test", - message: "Notifications from Selects reach this topic.", + message: "A test notice from Selects: notifications arrive here.", }; // An unexpected error is told without its message, which may hold the URL, and tried again. From b6cf77e78727c698303354a43c121f3c98a4ca13 Mon Sep 17 00:00:00 2001 From: Brandon Ly Date: Fri, 13 Nov 2026 11:46:02 +0000 Subject: [PATCH 09/13] refactor(web): drop fragments left around single children --- web/src/components/notification-settings.tsx | 56 +++++++++----------- 1 file changed, 24 insertions(+), 32 deletions(-) diff --git a/web/src/components/notification-settings.tsx b/web/src/components/notification-settings.tsx index eabba0d..e7041e5 100644 --- a/web/src/components/notification-settings.tsx +++ b/web/src/components/notification-settings.tsx @@ -378,23 +378,19 @@ function NtfyChannel({ + ) : channel === null ? ( +
+ +
) : ( - <> - {channel === null ? ( -
- -
- ) : ( - - - - - )} - + + + + )} ); @@ -481,23 +477,19 @@ function WebhookChannel({ + ) : channel === null ? ( +
+ +
) : ( - <> - {channel === null ? ( -
- -
- ) : ( - - - - - )} - + + + + )} ); From 343c44489f7482c57a7afc354ae73c8b4de4c841 Mon Sep 17 00:00:00 2001 From: Brandon Ly Date: Fri, 13 Nov 2026 12:08:16 +0000 Subject: [PATCH 10/13] fix(server): start paused on a restored copy, refuse a notice aimed at Selects itself and show less of the ntfy channel --- .env.example | 4 +++ README.md | 27 ++++++++++++++------ docs/adr/0009-notifications-and-backups.md | 8 +++++- server/src/app.ts | 4 ++- server/src/backup.ts | 11 ++++++-- server/src/config.test.ts | 11 ++++++++ server/src/config.ts | 12 +++++++++ server/src/main.ts | 7 ++++- server/src/notify.test.ts | 16 +++++++++++- server/src/notify.ts | 18 +++++++++---- server/src/publisher.test.ts | 22 ++++++++++++++++ server/src/publisher.ts | 14 +++++++++- web/src/components/backup-status.tsx | 4 +-- web/src/components/notification-settings.tsx | 25 ++++++++++++------ 14 files changed, 153 insertions(+), 30 deletions(-) diff --git a/.env.example b/.env.example index 59345be..df8351a 100644 --- a/.env.example +++ b/.env.example @@ -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 diff --git a/README.md b/README.md index c2bda31..71fb955 100644 --- a/README.md +++ b/README.md @@ -131,14 +131,25 @@ To restore a copy: (`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. - -The photos are not in the database: originals, thumbnails and fonts stay in `DATA_DIR` and are -not part of a copy. Restoring takes the library, posts, schedule and settings back to the night -of the copy. A select posted since then is back in the pool and could be posted again, so as -soon as Selects starts, turn on the pause switch on the Queue screen, compare the Posted screen -with Instagram, and delete from the Library any select already on Instagram (its hash is kept, -so it is never picked again). Then turn the pause switch off. +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 diff --git a/docs/adr/0009-notifications-and-backups.md b/docs/adr/0009-notifications-and-backups.md index fe33380..1cf0f90 100644 --- a/docs/adr/0009-notifications-and-backups.md +++ b/docs/adr/0009-notifications-and-backups.md @@ -16,7 +16,7 @@ a copy holds the Instagram token, so each choice leans towards sending and keepi - **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 and its select is back in the pool, or that Instagram has not + 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 @@ -54,6 +54,12 @@ a copy holds the Instagram token, so each choice leans towards sending and keepi 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 diff --git a/server/src/app.ts b/server/src/app.ts index 2ba1b60..f2aa409 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -25,7 +25,7 @@ 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 } from "./notify"; +import { createNotifier, NOTICE_HEADER } from "./notify"; import { notifyRoutes } from "./notify-routes"; import { passwordGate } from "./password"; import { publishRoutes } from "./publish-routes"; @@ -497,6 +497,8 @@ export function createApp(options: AppOptions) { backups: services.backups, fetch: async (request: Request): Promise => { 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 }); return (await gate?.(request)) ?? routes.handle(request); }, }; diff --git a/server/src/backup.ts b/server/src/backup.ts index 86ec760..ee62fc8 100644 --- a/server/src/backup.ts +++ b/server/src/backup.ts @@ -24,7 +24,7 @@ export const BACKUP_TIME = "03:30"; const RETRY_AFTER_MS = HOUR; const COPY_NAME = /^selects-\d{4}-\d{2}-\d{2}\.db$/; -const TEMPORARY = /^\.selects-.*\.tmp$/; +const TEMPORARY = /^\.selects-.*\.tmp(-journal)?$/; export type BackupCopy = { name: string; at: number; bytes: number }; @@ -95,6 +95,8 @@ export function createBackups(options: BackupsOptions) { const now = clock.now(); const name = `selects-${localDate(now, timeZone())}.db`; mkdirSync(dir, { recursive: true, mode: 0o700 }); + // A folder that was already there keeps its mode otherwise. + chmodSync(dir, 0o700); // Leftovers of a copy a stop interrupted. for (const found of readdirSync(dir)) { if (TEMPORARY.test(found)) rmSync(join(dir, found), { force: true }); @@ -111,7 +113,12 @@ export function createBackups(options: BackupsOptions) { rmSync(temporary, { force: true }); throw error; } - for (const old of listCopies().slice(BACKUPS_KEPT)) rmSync(join(dir, old.name), { force: true }); + // The copy is made: a copy too many that cannot be removed now goes on the next night. + try { + for (const old of listCopies().slice(BACKUPS_KEPT)) rmSync(join(dir, old.name), { force: true }); + } catch (error) { + console.error(`An old backup could not be removed (${errorKind(error)}).`); + } } function run(): Promise { diff --git a/server/src/config.test.ts b/server/src/config.test.ts index b8d0fc3..b790366 100644 --- a/server/src/config.test.ts +++ b/server/src/config.test.ts @@ -171,3 +171,14 @@ describe("loadConfig: the fake bucket", () => { expect(loadConfig({ ...minimal, BUCKET_PUBLIC_URL: "https://cdn.test" }).fakePublicUrl).toBe(true); }); }); + +describe("starting paused", () => { + test("is off unless SELECTS_START_PAUSED says true, and anything else is refused by name", () => { + expect(loadConfig({ DATA_DIR: "/data" }).startPaused).toBe(false); + expect(loadConfig({ DATA_DIR: "/data", SELECTS_START_PAUSED: "true" }).startPaused).toBe(true); + expect(loadConfig({ DATA_DIR: "/data", SELECTS_START_PAUSED: "false" }).startPaused).toBe(false); + expect(() => loadConfig({ DATA_DIR: "/data", SELECTS_START_PAUSED: "maybe" })).toThrow( + /SELECTS_START_PAUSED/, + ); + }); +}); diff --git a/server/src/config.ts b/server/src/config.ts index 2ed94a2..e7adda2 100644 --- a/server/src/config.ts +++ b/server/src/config.ts @@ -55,6 +55,11 @@ export class Config { * of its own, so gallery output can be tried; the variable's value is not used. */ readonly fakePublicUrl = false, + /** + * Start with posting paused and posts that were under way held for checking. For the first + * start on a restored copy, whose selects may have been posted since it was made. + */ + readonly startPaused = false, ) { this.#password = password; } @@ -110,6 +115,12 @@ export function loadConfig(env: Env): Config { problems.push("INSTAGRAM_API must be fake or live"); } + const rawPaused = read("SELECTS_START_PAUSED"); + const startPaused = rawPaused === "true" || rawPaused === "1"; + if (rawPaused !== undefined && !startPaused && rawPaused !== "false" && rawPaused !== "0") { + problems.push("SELECTS_START_PAUSED must be true or false"); + } + if (problems.length > 0 || dataDir === undefined) { throw new ConfigError(`Invalid configuration:\n - ${problems.join("\n - ")}`); } @@ -121,6 +132,7 @@ export function loadConfig(env: Env): Config { bucket, instagram, read("BUCKET_PUBLIC_URL") !== undefined, + startPaused, ); } diff --git a/server/src/main.ts b/server/src/main.ts index 12edfd7..8ce2ec1 100644 --- a/server/src/main.ts +++ b/server/src/main.ts @@ -51,11 +51,16 @@ const app = createApp({ fakeBucket: fakes?.bucket, }); // Posts a stop left mid-attempt are taken up again, before any request can start a new one. -app.publisher.recover(); +app.publisher.recover({ hold: config.startPaused }); // Posts a stop left recorded for the gallery and not yet taken in, before any frame is cleaned up. // In fake mode the fake bucket starts empty: the gallery writes again what it lost. app.gallery.recover({ bucketEmptied: config.instagram === "fake" }); // Slots a stop left part way are settled before the schedule runs: never posted twice. +// Asked to start paused, as on a restored copy: no slot posts until its owner resumes. +if (config.startPaused) { + app.scheduler.setPaused(true); + console.log("Started with posting paused (SELECTS_START_PAUSED). Resume on the Queue screen."); +} app.scheduler.recover(); const server = Bun.serve({ diff --git a/server/src/notify.test.ts b/server/src/notify.test.ts index a2d76ff..03d2c53 100644 --- a/server/src/notify.test.ts +++ b/server/src/notify.test.ts @@ -255,7 +255,7 @@ describe("events", () => { { event: "failed", title: "A post failed", - message: "A post failed and its select is back in the pool. The Posted screen says why.", + message: "A post failed for good. The Posted screen says why.", }, { event: "failed", @@ -416,6 +416,20 @@ describe("token about to expire", () => { }); describe("pool running low", () => { + test("a pool already low before any channel is set is told once a channel is", async () => { + const recorded = recordingChannels(); + const notifier = notifierWith({ channels: recorded.channels, poolSize: () => 0 }); + notifier.check(); + await notifier.idle(); + expect(recorded.sent).toHaveLength(0); + + notifier.setNtfy({ server: "https://ntfy.invalid", topic: TOPIC, token: null }); + notifier.check(); + await notifier.idle(); + + expect(recorded.sent.map(({ notice }) => notice.event)).toEqual(["pool"]); + }); + test("notifies once when the pool drops below the threshold, and again only after it has gone back up", async () => { const recorded = recordingChannels(); let pool = 11; diff --git a/server/src/notify.ts b/server/src/notify.ts index a2a4a70..c323148 100644 --- a/server/src/notify.ts +++ b/server/src/notify.ts @@ -175,12 +175,15 @@ export function httpChannels(stored: Stored, http: HttpOptions): Channel[] { * POSTs JSON. Redirects are not followed, the answer's body is never read, and every failure * is told in words without the URL. */ +/** Marks a request as a notice from Selects, so Selects refuses one aimed at itself. */ +export const NOTICE_HEADER = "x-selects-notice"; + async function post(url: string, body: unknown, headers: Record, http: HttpOptions) { let response: Response; try { response = await fetch(url, { method: "POST", - headers: { "content-type": "application/json", ...headers }, + headers: { "content-type": "application/json", [NOTICE_HEADER]: "1", ...headers }, body: JSON.stringify(body), redirect: "manual", signal: AbortSignal.timeout(http.timeoutMs), @@ -233,6 +236,10 @@ export function createNotifier(options: NotifierOptions) { "INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value", ).run(key, JSON.stringify(value)); }; + const hasChannel = () => { + const { ntfy, webhook } = read(); + return ntfy !== null || webhook !== null; + }; const read = (): Stored => { const saved = readKey(KEY); return { ntfy: saved.ntfy ?? null, webhook: saved.webhook ?? null }; @@ -350,7 +357,7 @@ export function createNotifier(options: NotifierOptions) { send({ event: "failed", title: "A post failed", - message: "A post failed and its select is back in the pool. The Posted screen says why.", + message: "A post failed for good. The Posted screen says why.", }); } else { send({ @@ -382,7 +389,8 @@ export function createNotifier(options: NotifierOptions) { const pool = options.poolSize(); const { poolThreshold } = events(); if (pool >= poolThreshold) state.poolLow = false; - else if (!state.poolLow) { + else if (!state.poolLow && hasChannel()) { + // Marked only once there is a channel to tell: a crossing before one is set is told then. state.poolLow = true; send({ event: "pool", @@ -419,8 +427,8 @@ export function createNotifier(options: NotifierOptions) { ntfy === null ? null : { - server: ntfy.server, - topic: `${ntfy.topic.slice(0, 3)}…`, + server: shownUrl(ntfy.server), + topic: ntfy.topic.length > 6 ? `${ntfy.topic.slice(0, 3)}…` : "…", token: ntfy.token !== null, ...statusOf("ntfy"), }, diff --git a/server/src/publisher.test.ts b/server/src/publisher.test.ts index 5fb3fe5..82bfde4 100644 --- a/server/src/publisher.test.ts +++ b/server/src/publisher.test.ts @@ -853,6 +853,28 @@ describe("a publish interrupted part way", () => { expect(post?.permalink).toBe(instagram.media[0]?.permalink ?? "missing"); }); + test("on a start that holds, as on a restored copy, is not sent again and waits to be checked", async () => { + const before = setup(); + await connect(before.account); + const id = await addSelect("portrait"); + instagram.fail("container", "transient"); + const first = await postNow(before.publisher, id); + expect(first.state).toBe("retrying"); + const requests = instagram.requests.length; + + const { publisher } = setup(); + publisher.recover({ hold: true }); + clock.advance(5 * MINUTE); + await publisher.runDue(); + + expect(publisher.post(first.id)?.state).toBe("unconfirmed"); + expect(instagram.media).toHaveLength(0); + expect(instagram.requests.filter((r) => r.operation === "container")).toHaveLength( + instagram.requests.slice(0, requests).filter((r) => r.operation === "container").length, + ); + expect(library.pool()).toEqual([]); + }); + test("by a restart is finished after it, and published once", async () => { const before = setup(); await connect(before.account); diff --git a/server/src/publisher.ts b/server/src/publisher.ts index b066a3b..392fb41 100644 --- a/server/src/publisher.ts +++ b/server/src/publisher.ts @@ -1017,7 +1017,19 @@ export function createPublisher(options: PublisherOptions) { * Takes up posts a stop left mid-attempt: the next `runDue` resumes them. Called once at * start, before anything is published. */ - recover(): void { + recover({ hold = false }: { hold?: boolean } = {}): void { + if (hold) { + // A restored copy: what was under way when it was made has long since ended one way or + // the other. Nothing is sent again; each waits for its owner to say what became of it. + db.query( + `UPDATE posts SET state = 'unconfirmed', next_attempt_at = ?, error = ? + WHERE state IN ('publishing', 'retrying')`, + ).run( + clock.now() + UNCONFIRMED_CHECK_MS, + "Selects started on a restored copy while this post was under way. Check Instagram, then say whether it was posted.", + ); + return; + } db.query("UPDATE posts SET state = 'retrying', next_attempt_at = ? WHERE state = 'publishing'").run( clock.now(), ); diff --git a/web/src/components/backup-status.tsx b/web/src/components/backup-status.tsx index 4936ff2..192880b 100644 --- a/web/src/components/backup-status.tsx +++ b/web/src/components/backup-status.tsx @@ -40,8 +40,8 @@ export function BackupStatus() {

{status.lastError !== null && (

- The last try failed {formatTime(status.lastError.at)}: {status.lastError.reason} Selects tries - again in an hour. + Last try {formatTime(status.lastError.at)}: {status.lastError.reason} Selects tries again in an + hour.

)}

diff --git a/web/src/components/notification-settings.tsx b/web/src/components/notification-settings.tsx index e7041e5..cabe0de 100644 --- a/web/src/components/notification-settings.tsx +++ b/web/src/components/notification-settings.tsx @@ -202,7 +202,12 @@ function ChannelFooter({

Last sent {formatTime(status.lastSentAt)}.

)}
- {children} @@ -249,7 +254,11 @@ function RemoveChannel({ ) : ( - )} @@ -365,7 +374,7 @@ function NtfyChannel({ kept on this server and never shown again in full. Saving replaces both.

{problems !== undefined && ( -

+

{problems.length > 0 ? problems.join(" ") : "Couldn't save. Try again."}

)} @@ -380,13 +389,13 @@ function NtfyChannel({ ) : channel === null ? (
-
) : ( - @@ -464,7 +473,7 @@ function WebhookChannel({ An http or https URL. Only its scheme and host are shown again: the rest may be a secret.

{problems !== undefined && ( -

+

{problems.length > 0 ? problems.join(" ") : "Couldn't save. Try again."}

)} @@ -479,13 +488,13 @@ function WebhookChannel({ ) : channel === null ? (
-
) : ( - From baee3d7954feaed6bd49bc4371fbbcaf76338a9e Mon Sep 17 00:00:00 2001 From: Brandon Ly Date: Fri, 13 Nov 2026 12:12:42 +0000 Subject: [PATCH 11/13] fix(server): start the token notice's day only once a channel is set --- server/src/notify.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/server/src/notify.ts b/server/src/notify.ts index c323148..a048aa6 100644 --- a/server/src/notify.ts +++ b/server/src/notify.ts @@ -381,6 +381,8 @@ export function createNotifier(options: NotifierOptions) { if (token === undefined) state.tokenWarnedAt = null; else if ( events().events.token && + // Counted only once there is a channel to tell, like the pool below. + hasChannel() && (state.tokenWarnedAt === null || now - state.tokenWarnedAt >= TOKEN_REPEAT_MS) ) { send(token); From 77be853c43262c40fccb59d7b6d4515587a1e251 Mon Sep 17 00:00:00 2001 From: Brandon Ly Date: Fri, 13 Nov 2026 12:24:29 +0000 Subject: [PATCH 12/13] fix(server): leave a restored post held until its owner says what became of it --- server/src/backup.ts | 9 +++++++-- server/src/publisher.test.ts | 7 +++++-- server/src/publisher.ts | 5 +++-- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/server/src/backup.ts b/server/src/backup.ts index ee62fc8..b191109 100644 --- a/server/src/backup.ts +++ b/server/src/backup.ts @@ -78,8 +78,13 @@ export function createBackups(options: BackupsOptions) { .sort() .reverse() .flatMap((name) => { - const stats = statSync(join(dir, name), { throwIfNoEntry: false }); - return stats?.isFile() ? [{ name, at: stats.mtimeMs, bytes: stats.size }] : []; + // A folder that can be listed but not looked into leaves its copies unknown, not a crash. + try { + const stats = statSync(join(dir, name), { throwIfNoEntry: false }); + return stats?.isFile() ? [{ name, at: stats.mtimeMs, bytes: stats.size }] : []; + } catch { + return []; + } }); } diff --git a/server/src/publisher.test.ts b/server/src/publisher.test.ts index 82bfde4..64cecb4 100644 --- a/server/src/publisher.test.ts +++ b/server/src/publisher.test.ts @@ -864,8 +864,11 @@ describe("a publish interrupted part way", () => { const { publisher } = setup(); publisher.recover({ hold: true }); - clock.advance(5 * MINUTE); - await publisher.runDue(); + // Well past the time an unconfirmed post is checked on its own: this one never is. + for (let i = 0; i < 6; i++) { + clock.advance(5 * MINUTE); + await publisher.runDue(); + } expect(publisher.post(first.id)?.state).toBe("unconfirmed"); expect(instagram.media).toHaveLength(0); diff --git a/server/src/publisher.ts b/server/src/publisher.ts index 392fb41..a63a73c 100644 --- a/server/src/publisher.ts +++ b/server/src/publisher.ts @@ -1022,10 +1022,11 @@ export function createPublisher(options: PublisherOptions) { // A restored copy: what was under way when it was made has long since ended one way or // the other. Nothing is sent again; each waits for its owner to say what became of it. db.query( - `UPDATE posts SET state = 'unconfirmed', next_attempt_at = ?, error = ? + `UPDATE posts SET state = 'unconfirmed', next_attempt_at = NULL, error = ? WHERE state IN ('publishing', 'retrying')`, ).run( - clock.now() + UNCONFIRMED_CHECK_MS, + // No time for a check of its own: the container the copy knew may have been replaced + // since, so only its owner can say what became of it. "Selects started on a restored copy while this post was under way. Check Instagram, then say whether it was posted.", ); return; From 79e67a19bea58262be25add804f443cc5d47ffab Mon Sep 17 00:00:00 2001 From: Brandon Ly Date: Fri, 13 Nov 2026 12:27:17 +0000 Subject: [PATCH 13/13] test(server): a restored post with a container is never checked on its own --- server/src/publisher.test.ts | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/server/src/publisher.test.ts b/server/src/publisher.test.ts index 64cecb4..0e3a57e 100644 --- a/server/src/publisher.test.ts +++ b/server/src/publisher.test.ts @@ -878,6 +878,30 @@ describe("a publish interrupted part way", () => { expect(library.pool()).toEqual([]); }); + test("on a start that holds, a post with a container is never checked on its own", async () => { + const before = setup(); + await connect(before.account); + const id = await addSelect("portrait"); + // The container is made, then checking on it fails: the copy knows a container. + instagram.fail("status", "transient"); + const first = await postNow(before.publisher, id); + expect(first.state).toBe("retrying"); + + const { publisher } = setup(); + publisher.recover({ hold: true }); + const statusChecks = () => instagram.requests.filter((r) => r.operation === "status").length; + const checked = statusChecks(); + for (let i = 0; i < 6; i++) { + clock.advance(5 * MINUTE); + await publisher.runDue(); + } + + expect(statusChecks()).toBe(checked); + expect(publisher.post(first.id)?.state).toBe("unconfirmed"); + expect(instagram.media).toHaveLength(0); + expect(library.pool()).toEqual([]); + }); + test("by a restart is finished after it, and published once", async () => { const before = setup(); await connect(before.account);