krz/moonrise

Night-sky companion for iPhone, Apple Watch and Vision Pro: what's up tonight, the Moon, planets, launches and missions, and a Library of the solar system. SwiftUI app with a Cloudflare Workers backend. astronomy cloudflare-workers ios night-sky space swiftui visionos watchos

Commit 40f42df124

40f42df12429490c436e757bef45f99e5917adc6

parent: 8562cc5d8f

Unsigned

cmc <hello@cleberg.net> · 2026-10-22 00:14 UTC

Worker: provider usage terms (!102)

- `src/agent.ts`: `Moonrise/4.1.0 (sh.krz.moonrise; root@krz.sh)` for Horizons, LL2, SNAPI, CelesTrak and SWPC (SWPC sent none). LL2 asks for `<AppName>/<Version> (<contact>)`.
- LL2: a 429 reads `/2.3.0/api-throttle/` (not counted) and stores `ll2:throttled` until `next_use_secs` (15 min if unknown); list and focus polls skip until then. Channel handling still runs.
- CelesTrak: when `last-30-days` fails after `visual` succeeded, `visual` is kept in `celestrak:visual`; the retry 33 minutes later fetches only `last-30-days`.
- News: the 10-minute cron stores SNAPI articles (`news`), served at `GET /v1/news` (max-age 600, SNAPI field names); the digest reads them. 6 SNAPI requests/hour, replacing one per install.
- SWPC: the two Kp files are fetched one after the other.
- Tests: three new (CelesTrak retry, LL2 throttle, /v1/news); digest test now expects one SNAPI request per run. 62/62 pass; `wrangler deploy --dry-run` bundles.

Layout: unified · split

server/src/agent.ts added +2
@@ -0,0 +1,2 @@
1/** Sent to every data provider: product, version and a contact, as JPL's and The Space Devs' usage notes ask. */
2export const USER_AGENT = "Moonrise/4.1.0 (sh.krz.moonrise; root@krz.sh)";
server/src/celestrak.ts +13 −6
@@ -1,6 +1,7 @@
11// CelesTrak GP data. CelesTrak updates every 2 hours and blocks IPs that fetch more
22// often or keep requesting after errors, so poll every 2 hours and stop on any non-200.
33// A failed poll is tried once more 33 minutes later: at most 2 errors in 2 hours.
4import { USER_AGENT } from "./agent.ts";
45
56/** ISS, Tiangong (CSS Tianhe) and Hubble; all three are in the visual group. */
67export const FEATURED = [25544, 48274, 20580];
@@ -165,7 +166,7 @@ export function retryDue(now: Date, lastOk: string | null, lastError: string | n
165166 return error >= now.getTime() - 33 * 60_000 && error < now.getTime() && (!lastOk || Date.parse(lastOk) < error);
166167}
167168
168const HEADERS = { "user-agent": "moonrise-server (sh.krz.moonrise)" };
169const HEADERS = { "user-agent": USER_AGENT };
169170const TIMEOUT_MS = 10_000;
170171
171172async function group(name: string): Promise<Row[]> {
@@ -174,11 +175,17 @@ async function group(name: string): Promise<Row[]> {
174175 return (await res.json()) as Row[];
175176}
176177
177/** The visual group (about 150 bright objects) and the last 30 days' launches; throws on the first non-200 so nothing more is requested. */
178export async function fetchGroups(): Promise<{ visual: Row[]; recent: Row[] }> {
179 const visual = await group("visual");
180 const recent = await group("last-30-days");
181 return { visual, recent };
178/**
179 * The visual group (about 150 bright objects) and the last 30 days' launches; throws on the first non-200 so nothing
180 * more is requested. `visual` from earlier in the same 2-hourly update is reused rather than downloaded again.
181 */
182export async function fetchGroups(visual?: Row[]): Promise<{ visual: Row[]; recent: Row[] }> {
183 visual ??= await group("visual");
184 try {
185 return { visual, recent: await group("last-30-days") };
186 } catch (e) {
187 throw Object.assign(e as Error, { visual });
188 }
182189}
183190
184191/** One SupGP file; throws on a non-200 so the caller stops. */
server/src/index.ts +56 −19
@@ -3,8 +3,8 @@ import { broadcast, createChannel, deleteChannel, retryable, send, sendAll, type
33import { actionableKp, alertBands, eventKey, isNight } from "./aurora";
44import { compose, fetchGroups, fetchSupGP, fitsLaunch, retryDue, retryTick, supgpFile, supgpLaunches, type LaunchElements, type LaunchRef, type Row } from "./celestrak";
55import { activeEvent, fetchTrajectory, STEP_MINUTES } from "./live";
6import { fetchLaunch, fetchLaunches, PREVIOUS_URL, UPCOMING_URL, type Launch } from "./ll2";
7import { digestPayload, dueOffsets, fetchLatest, localDate, pickHeadlines } from "./news";
6import { fetchLaunch, fetchLaunches, PREVIOUS_URL, throttleSeconds, Throttled, UPCOMING_URL, type Launch } from "./ll2";
7import { digestPayload, dueOffsets, fetchLatest, localDate, pickHeadlines, type Article } from "./news";
88import { fetchSpaceWeather, next24h, type SpaceWeather } from "./swpc";
99
1010interface Env {
@@ -48,17 +48,24 @@ const json = (body: unknown, status = 200, maxAge?: number) =>
4848const PRIVACY_URL = "https://krz.sh/privacy/moonrise/";
4949
5050/** Read-only endpoints whose responses are the same for everyone. */
51const API = new Set(["/v1/today", "/v1/launches", "/v1/live", "/v1/satellites"]);
51const API = new Set(["/v1/today", "/v1/launches", "/v1/live", "/v1/satellites", "/v1/news"]);
5252
5353function api(url: URL, env: Env, now: Date): Promise<Response> {
5454 switch (url.pathname) {
5555 case "/v1/today": return today(env, now);
5656 case "/v1/launches": return launches(env, url, now);
5757 case "/v1/live": return live(env, url, now);
58 case "/v1/news": return news(env);
5859 default: return satellites(env);
5960 }
6061}
6162
63/** Spaceflight News API articles in its own field names, so clients do not call The Space Devs directly. */
64async function news(env: Env): Promise<Response> {
65 const row = await env.DB.prepare("SELECT fetched_at, body FROM feed_snapshots WHERE feed = 'news' AND ok = 1").first<{ fetched_at: string; body: string }>();
66 return json({ fetchedAt: row?.fetched_at ?? null, results: row ? JSON.parse(row.body) : [] }, 200, MAX_AGE.news);
67}
68
6269async function satellites(env: Env): Promise<Response> {
6370 const row = await env.DB.prepare("SELECT fetched_at, body FROM feed_snapshots WHERE feed = 'celestrak' AND ok = 1").first<{ fetched_at: string; body: string }>();
6471 return json({ fetchedAt: row?.fetched_at ?? null, satellites: row ? JSON.parse(row.body) : [] }, 200, MAX_AGE.satellites);
@@ -82,7 +89,7 @@ async function cached(request: Request, ctx: ExecutionContext | undefined, respo
8289}
8390
8491/** How long clients may reuse each GET response, matched to how often its source is polled. */
85export const MAX_AGE = { today: 60, launches: 300, satellites: 3600, live: 300 } as const;
92export const MAX_AGE = { today: 60, launches: 300, satellites: 3600, live: 300, news: 600 } as const;
8693
8794function validDevice(d: Partial<DeviceRequest>): d is DeviceRequest {
8895 return (
@@ -141,7 +148,7 @@ export default {
141148 async scheduled(controller: ScheduledController, env: Env, ctx: ExecutionContext): Promise<void> {
142149 const now = new Date(controller.scheduledTime);
143150 if (controller.cron === NEWS_CRON) {
144 ctx.waitUntil(sendNewsDigests(env, now));
151 ctx.waitUntil(pollNews(env, now).then(() => sendNewsDigests(env, now)));
145152 if (now.getUTCHours() === 0 && now.getUTCMinutes() === 0) ctx.waitUntil(prune(env, now));
146153 } else if (controller.cron === SATELLITE_CRON) ctx.waitUntil(pollSatellites(env, now));
147154 else if (controller.cron === FOCUS_CRON) ctx.waitUntil(focusTick(env, now));
@@ -242,10 +249,11 @@ const nearLaunches = async (env: Env, now: Date): Promise<Near[]> =>
242249 */
243250async function launchTick(env: Env, now: Date): Promise<void> {
244251 const near = await nearLaunches(env, now);
252 const throttled = await ll2Throttled(env, now);
245253 const focus = near.filter((l) => inFocus(l, now)).map((l) => l.id);
246254 const keyed = Boolean(env.LL2_API_KEY);
247 const pollFocus = focus.length > 0 && focusPollDue(5, now, keyed);
248 const pollList = !focus.length && now.getUTCMinutes() % 10 === 0;
255 const pollFocus = !throttled && focus.length > 0 && focusPollDue(5, now, keyed);
256 const pollList = !throttled && !focus.length && now.getUTCMinutes() % 10 === 0;
249257 if (pollFocus) await pollLaunch(env, focusPick(focus, now, focusEvery(keyed)), now);
250258 else if (pollList) await pollLaunches(env, now);
251259 // Channels are handed out with the launch's current state, so a poll means reading it again.
@@ -254,18 +262,32 @@ async function launchTick(env: Env, now: Date): Promise<void> {
254262
255263/** With an LL2 key: the launch in focus on the even minutes the 5-minute cron does not run on, and its broadcasts. */
256264async function focusTick(env: Env, now: Date): Promise<void> {
257 if (!focusPollDue(2, now, Boolean(env.LL2_API_KEY))) return;
265 if (!focusPollDue(2, now, Boolean(env.LL2_API_KEY)) || await ll2Throttled(env, now)) return;
258266 const focus = (await nearLaunches(env, now)).filter((l) => inFocus(l, now)).map((l) => l.id);
259267 if (!focus.length) return;
260268 await pollLaunch(env, focusPick(focus, now, focusEvery(true)), now);
261269 if (env.APNS_KEY) await broadcastChanges(env, now);
262270}
263271
272/** Whether LL2 said to wait (HTTP 429) and the wait has not passed. */
273async function ll2Throttled(env: Env, now: Date): Promise<boolean> {
274 const row = await env.DB.prepare("SELECT body FROM feed_snapshots WHERE feed = 'll2:throttled'").first<{ body: string }>();
275 return row !== null && Date.parse(row.body) > now.getTime();
276}
277
278/** After a 429, no LL2 requests until /api-throttle/ says the limit has reset (15 minutes if it cannot say). */
279async function ll2Throttle(env: Env, now: Date): Promise<void> {
280 const seconds = await throttleSeconds(env.LL2_API_KEY).catch(() => 0) || 15 * 60;
281 await env.DB.prepare("INSERT INTO feed_snapshots (feed, fetched_at, ok, body) VALUES ('ll2:throttled', ?1, 0, ?2) ON CONFLICT (feed) DO UPDATE SET fetched_at = ?1, body = ?2")
282 .bind(now.toISOString(), new Date(now.getTime() + seconds * 1000).toISOString()).run();
283}
284
264285async function pollLaunch(env: Env, id: string, now: Date): Promise<void> {
265286 try {
266287 await env.DB.batch(upsertLaunches(env, [await fetchLaunch(id, env.LL2_API_KEY)]));
267288 } catch (e) {
268289 console.error("ll2 launch", String(e));
290 if (e instanceof Throttled) await ll2Throttle(env, now);
269291 await env.DB.prepare("INSERT INTO feed_snapshots (feed, fetched_at, ok) VALUES ('ll2:error', ?1, 0) ON CONFLICT (feed) DO UPDATE SET fetched_at = ?1").bind(now.toISOString()).run();
270292 }
271293}
@@ -277,6 +299,7 @@ async function pollLaunches(env: Env, now: Date): Promise<void> {
277299 list = await fetchLaunches(UPCOMING_URL, env.LL2_API_KEY);
278300 } catch (e) {
279301 console.error("ll2", String(e));
302 if (e instanceof Throttled) await ll2Throttle(env, now);
280303 await env.DB.prepare("INSERT INTO feed_snapshots (feed, fetched_at, ok) VALUES ('ll2:error', ?1, 0) ON CONFLICT (feed) DO UPDATE SET fetched_at = ?1").bind(now.toISOString()).run();
281304 return;
282305 }
@@ -286,6 +309,7 @@ async function pollLaunches(env: Env, now: Date): Promise<void> {
286309 list = [...list, ...(await fetchLaunches(PREVIOUS_URL, env.LL2_API_KEY))];
287310 } catch (e) {
288311 console.error("ll2 previous", String(e));
312 if (e instanceof Throttled) await ll2Throttle(env, now);
289313 }
290314 }
291315 await env.DB.batch([
@@ -388,11 +412,18 @@ async function retrySatellites(env: Env, now: Date): Promise<void> {
388412
389413async function pollSatellites(env: Env, now: Date): Promise<void> {
390414 let groups: { visual: Row[]; recent: Row[] };
415 // A visual group downloaded earlier in this 2-hourly update, kept when last-30-days failed.
416 const kept = await env.DB.prepare("SELECT body FROM feed_snapshots WHERE feed = 'celestrak:visual' AND fetched_at > ?1")
417 .bind(new Date(now.getTime() - 60 * 60_000).toISOString()).first<{ body: string }>();
391418 try {
392 groups = await fetchGroups();
419 groups = await fetchGroups(kept ? JSON.parse(kept.body) : undefined);
393420 } catch (e) {
394421 console.error("celestrak", String(e));
395 await env.DB.prepare("INSERT INTO feed_snapshots (feed, fetched_at, ok) VALUES ('celestrak:error', ?1, 0) ON CONFLICT (feed) DO UPDATE SET fetched_at = ?1").bind(now.toISOString()).run();
422 const visual = (e as { visual?: Row[] }).visual;
423 await env.DB.batch([
424 env.DB.prepare("INSERT INTO feed_snapshots (feed, fetched_at, ok) VALUES ('celestrak:error', ?1, 0) ON CONFLICT (feed) DO UPDATE SET fetched_at = ?1").bind(now.toISOString()),
425 ...(visual && !kept ? [env.DB.prepare("INSERT INTO feed_snapshots (feed, fetched_at, ok, body) VALUES ('celestrak:visual', ?1, 1, ?2) ON CONFLICT (feed) DO UPDATE SET fetched_at = ?1, body = ?2").bind(now.toISOString(), JSON.stringify(visual))] : []),
426 ]);
396427 return;
397428 }
398429 const launches = await env.DB.prepare("SELECT id, mission, provider, net, launch_designator AS designator FROM launches WHERE net >= ?1")
@@ -458,6 +489,17 @@ async function sendAuroraAlerts(env: Env, w: SpaceWeather, now: Date): Promise<v
458489 }));
459490}
460491
492/** Spaceflight News API every 10 minutes, matching its cache lifetime; the last good copy is kept on failure. */
493async function pollNews(env: Env, now: Date): Promise<void> {
494 try {
495 const articles = await fetchLatest();
496 await env.DB.prepare("INSERT INTO feed_snapshots (feed, fetched_at, ok, body) VALUES ('news', ?1, 1, ?2) ON CONFLICT (feed) DO UPDATE SET fetched_at = ?1, ok = 1, body = ?2")
497 .bind(now.toISOString(), JSON.stringify(articles)).run();
498 } catch (e) {
499 console.error("snapi", String(e));
500 }
501}
502
461503/** The daily news digest, sent in the 09:00 local hour to devices that opted in, once per local day. */
462504async function sendNewsDigests(env: Env, now: Date): Promise<void> {
463505 if (!env.APNS_KEY) return;
@@ -470,15 +512,10 @@ async function sendNewsDigests(env: Env, now: Date): Promise<void> {
470512 const due = rows.results.map((d) => ({ ...d, band: 0, event: `${d.token}:${localDate(now, d.utc_offset_minutes)}` }));
471513 if (!due.length) return;
472514
473 let payload;
474 try {
475 const headlines = pickHeadlines(await fetchLatest(), now);
476 if (!headlines.length) return;
477 payload = digestPayload(headlines);
478 } catch (e) {
479 console.error("snapi", String(e));
480 return;
481 }
515 const row = await env.DB.prepare("SELECT body FROM feed_snapshots WHERE feed = 'news' AND ok = 1").first<{ body: string }>();
516 const headlines = pickHeadlines(row ? JSON.parse(row.body) as Article[] : [], now);
517 if (!headlines.length) return;
518 const payload = digestPayload(headlines);
482519
483520 await sendAlerts(env, "news", due, now, () => payload);
484521}
server/src/live.ts +2 −3
@@ -1,5 +1,6 @@
11// Live coverage of a crewed or lunar mission: its trajectory from JPL Horizons, cached while the event runs.
22// To cover a new mission, add it to EVENTS (Horizons ID, window, phases) and deploy.
3import { USER_AGENT } from "./agent.ts";
34
45export interface LiveEvent {
56 id: string;
@@ -42,8 +43,6 @@ export const EVENTS: LiveEvent[] = [
4243
4344export const STEP_MINUTES = 30;
4445
45/** JPL's SSD API fair use policy asks for the product name, version and a contact. */
46export const HORIZONS_USER_AGENT = "Moonrise/4.1.0 (sh.krz.moonrise; root@krz.sh)";
4746
4847/** The event whose window contains `at`, if any. */
4948export function activeEvent(at: Date, events = EVENTS): LiveEvent | undefined {
@@ -87,7 +86,7 @@ export async function fetchTrajectory(e: LiveEvent, until: Date, from = new Date
8786 START_TIME: `'${fmt(start)}'`, STOP_TIME: `'${fmt(stop)}'`, STEP_SIZE: `'${STEP_MINUTES}m'`,
8887 VEC_TABLE: "'1'", OUT_UNITS: "'KM-S'", CSV_FORMAT: "'YES'", OBJ_DATA: "'NO'", MAKE_EPHEM: "'YES'",
8988 });
90 const res = await fetch(`https://ssd.jpl.nasa.gov/api/horizons.api?${params}`, { headers: { "user-agent": HORIZONS_USER_AGENT } });
89 const res = await fetch(`https://ssd.jpl.nasa.gov/api/horizons.api?${params}`, { headers: { "user-agent": USER_AGENT } });
9190 if (res.status !== 200) throw new Error(`Horizons ${res.status}`);
9291 const result = ((await res.json()) as { result: string }).result;
9392 const first = ephemerisLimit(result, "prior to");
server/src/ll2.ts +15 −1
@@ -1,5 +1,6 @@
11// Launch Library 2 (The Space Devs). Anonymous limit: 15 requests per hour.
22// Images are not used: their licences are often "Unknown".
3import { USER_AGENT } from "./agent.ts";
34
45export const UPCOMING_URL = "https://ll.thespacedevs.com/2.3.0/launches/upcoming/?limit=20&mode=normal";
56/** Recent launches, for the international designator, which is assigned only after liftoff. */
@@ -73,13 +74,26 @@ export function normalize(r: Raw): Launch {
7374
7475/** `apiKey` lifts the anonymous per-IP limit, which Cloudflare's shared egress IPs often exhaust (HTTP 429). */
7576async function get<T>(url: string, apiKey?: string): Promise<T> {
76 const headers: Record<string, string> = { "user-agent": "moonrise-server (sh.krz.moonrise)" };
77 const headers: Record<string, string> = { "user-agent": USER_AGENT };
7778 if (apiKey) headers.authorization = `Token ${apiKey}`;
7879 const res = await fetch(url, { headers });
80 if (res.status === 429) throw new Throttled();
7981 if (!res.ok) throw new Error(`LL2 ${res.status}`);
8082 return (await res.json()) as T;
8183}
8284
85export class Throttled extends Error {
86 constructor() {
87 super("LL2 429");
88 }
89}
90
91/** Seconds until LL2 accepts requests again, from /api-throttle/, which does not count towards the limit. */
92export async function throttleSeconds(apiKey?: string): Promise<number> {
93 const t = await get<{ next_use_secs: number }>("https://ll.thespacedevs.com/2.3.0/api-throttle/", apiKey);
94 return t.next_use_secs;
95}
96
8397export async function fetchLaunches(url: string, apiKey?: string): Promise<Launch[]> {
8498 return (await get<{ results: Raw[] }>(url, apiKey)).results.map(normalize);
8599}
server/src/news.ts +8 −3
@@ -1,10 +1,14 @@
1// Spaceflight News API (The Space Devs). Free, no key. Used only for the daily news digest push.
1// Spaceflight News API (The Space Devs). Free, no key. Polled every 10 minutes for /v1/news and the daily digest push.
2import { USER_AGENT } from "./agent.ts";
23
34export interface Article {
45 id: number;
56 title: string;
67 news_site: string;
78 published_at: string;
9 summary?: string;
10 url?: string;
11 image_url?: string | null;
812}
913
1014export const DIGEST_HOUR = 9;
@@ -50,8 +54,9 @@ export function digestPayload(headlines: Article[]) {
5054
5155export async function fetchLatest(): Promise<Article[]> {
5256 const res = await fetch("https://api.spaceflightnewsapi.net/v4/articles/?limit=50", {
53 headers: { "user-agent": "moonrise-server (sh.krz.moonrise)" },
57 headers: { "user-agent": USER_AGENT },
5458 });
5559 if (res.status !== 200) throw new Error(`SNAPI ${res.status}`);
56 return ((await res.json()) as { results: Article[] }).results;
60 return ((await res.json()) as { results: Article[] }).results
61 .map(({ id, title, summary, url, image_url, news_site, published_at }) => ({ id, title, summary, url, image_url, news_site, published_at }));
5762}
server/src/swpc.ts +4 −1
@@ -1,4 +1,5 @@
11// NOAA SWPC feeds. Responses carry cache-control max-age=60; poll no faster.
2import { USER_AGENT } from "./agent.ts";
23
34export const KP_NOW_URL = "https://services.swpc.noaa.gov/json/planetary_k_index_1m.json";
45export const KP_FORECAST_URL = "https://services.swpc.noaa.gov/products/noaa-planetary-k-index-forecast.json";
@@ -27,7 +28,9 @@ export function decode(nowJson: unknown, forecastJson: unknown): SpaceWeather {
2728}
2829
2930export async function fetchSpaceWeather(): Promise<SpaceWeather> {
30 const [a, b] = await Promise.all([fetch(KP_NOW_URL), fetch(KP_FORECAST_URL)]);
31 const headers = { "user-agent": USER_AGENT };
32 const a = await fetch(KP_NOW_URL, { headers });
33 const b = await fetch(KP_FORECAST_URL, { headers });
3134 if (!a.ok || !b.ok) throw new Error(`SWPC ${a.status}/${b.status}`);
3235 return decode(await a.json(), await b.json());
3336}
server/test/worker.test.ts +52 −1
@@ -170,6 +170,57 @@ test("a failed CelesTrak poll is tried once more 33 minutes later, from the 5-mi
170170 assert.equal(await requests(FIVE, "2026-10-21T08:40:00Z"), 0);
171171});
172172
173test("a CelesTrak retry downloads only the group that failed", async () => {
174 const { env } = await setup({ APNS_KEY: "" });
175 let recentStatus = 522;
176 const paths: string[] = [];
177 network({
178 "celestrak.org": (url) => {
179 paths.push(url.searchParams.get("GROUP") ?? url.pathname);
180 return url.searchParams.get("GROUP") === "last-30-days" ? new Response("[]", { status: recentStatus }) : Response.json([]);
181 },
182 });
183 await run(env, SATELLITES, "2026-10-21T02:07:00Z");
184 assert.deepEqual(paths, ["visual", "last-30-days"]);
185 recentStatus = 200;
186 await run(env, FIVE, "2026-10-21T02:40:00Z");
187 assert.deepEqual(paths, ["visual", "last-30-days", "last-30-days"]);
188 await run(env, SATELLITES, "2026-10-21T04:07:00Z");
189 assert.equal(paths.at(-2), "visual", "next update downloads visual again");
190});
191
192test("an LL2 429 stops LL2 requests until /api-throttle/ says the limit has reset", async () => {
193 const { env } = await setup({ APNS_KEY: "" });
194 let limited = true;
195 const paths: string[] = [];
196 network({
197 "ll.thespacedevs.com": (url) => {
198 paths.push(url.pathname);
199 if (url.pathname.endsWith("/api-throttle/")) return Response.json({ next_use_secs: 1800 });
200 return limited ? new Response("{}", { status: 429 }) : Response.json({ results: [] });
201 },
202 });
203 await run(env, FIVE, "2026-10-20T10:10:00Z");
204 assert.deepEqual(paths, ["/2.3.0/launches/upcoming/", "/2.3.0/api-throttle/"]);
205 limited = false;
206 await run(env, FIVE, "2026-10-20T10:20:00Z");
207 await run(env, FIVE, "2026-10-20T10:30:00Z");
208 assert.equal(paths.length, 2, "polled while throttled");
209 await run(env, FIVE, "2026-10-20T10:40:00Z");
210 assert.equal(paths.length, 3);
211});
212
213test("/v1/news serves the articles the 10-minute cron stored", async () => {
214 const { env } = await setup({ APNS_KEY: "" });
215 const article = { id: 7, title: "t", summary: "s", url: "https://example.com/a", image_url: null, news_site: "ESA", published_at: "2026-10-20T13:00:00Z", authors: [] };
216 network({ "api.spaceflightnewsapi.net": () => Response.json({ results: [article] }) });
217 await run(env, NEWS, "2026-10-20T14:00:00Z");
218 const res = await worker.fetch(new Request("https://moonrise.test/v1/news"), env as never);
219 const { authors: _, ...stored } = article;
220 assert.deepEqual(((await res.json()) as { results: unknown[] }).results, [stored]);
221 assert.equal(res.headers.get("cache-control"), "public, max-age=600");
222});
223
173224test("aurora alerts go out in bounded slices and are recorded per device once answered", async () => {
174225 const { db, env, calls } = await setup();
175226 for (let i = 0; i < PUSH_SLICE + 10; i++) device(db, i);
@@ -227,7 +278,7 @@ test("news digests go out in slices during the local 09:00 hour, once per local
227278 assert.equal(new Set(push.state.sent).size, PUSH_SLICE + 5);
228279 await run(env, NEWS, "2026-10-20T14:20:00Z");
229280 assert.equal(push.state.sent.length, PUSH_SLICE + 5);
230 assert.equal(snapi(), 2);
281 assert.equal(snapi(), 3, "polled once per 10-minute run");
231282 assert.equal(count(db, "SELECT count(*) AS n FROM alerts_sent WHERE kind = 'news' AND event LIKE '%:2026-10-20'"), PUSH_SLICE + 5);
232283
233284 const q = calls.find((c) => c.sql.includes("news = 1"))!;