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 @@
1// CelesTrak GP data. CelesTrak updates every 2 hours and blocks IPs that fetch more 1// CelesTrak GP data. CelesTrak updates every 2 hours and blocks IPs that fetch more
2// often or keep requesting after errors, so poll every 2 hours and stop on any non-200. 2// often or keep requesting after errors, so poll every 2 hours and stop on any non-200.
3// A failed poll is tried once more 33 minutes later: at most 2 errors in 2 hours. 3// A failed poll is tried once more 33 minutes later: at most 2 errors in 2 hours.
4import { USER_AGENT } from "./agent.ts";
4 5
5/** ISS, Tiangong (CSS Tianhe) and Hubble; all three are in the visual group. */ 6/** ISS, Tiangong (CSS Tianhe) and Hubble; all three are in the visual group. */
6export const FEATURED = [25544, 48274, 20580]; 7export const FEATURED = [25544, 48274, 20580];
@@ -165,7 +166,7 @@ export function retryDue(now: Date, lastOk: string | null, lastError: string | n
165 return error >= now.getTime() - 33 * 60_000 && error < now.getTime() && (!lastOk || Date.parse(lastOk) < error); 166 return error >= now.getTime() - 33 * 60_000 && error < now.getTime() && (!lastOk || Date.parse(lastOk) < error);
166} 167}
167 168
168const HEADERS = { "user-agent": "moonrise-server (sh.krz.moonrise)" }; 169const HEADERS = { "user-agent": USER_AGENT };
169const TIMEOUT_MS = 10_000; 170const TIMEOUT_MS = 10_000;
170 171
171async function group(name: string): Promise<Row[]> { 172async function group(name: string): Promise<Row[]> {
@@ -174,11 +175,17 @@ async function group(name: string): Promise<Row[]> {
174 return (await res.json()) as Row[]; 175 return (await res.json()) as Row[];
175} 176}
176 177
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. */ 178/**
178export async function fetchGroups(): Promise<{ visual: Row[]; recent: Row[] }> { 179 * The visual group (about 150 bright objects) and the last 30 days' launches; throws on the first non-200 so nothing
179 const visual = await group("visual"); 180 * more is requested. `visual` from earlier in the same 2-hourly update is reused rather than downloaded again.
180 const recent = await group("last-30-days"); 181 */
181 return { visual, recent }; 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 }
182} 189}
183 190
184/** One SupGP file; throws on a non-200 so the caller stops. */ 191/** 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
3import { actionableKp, alertBands, eventKey, isNight } from "./aurora"; 3import { actionableKp, alertBands, eventKey, isNight } from "./aurora";
4import { compose, fetchGroups, fetchSupGP, fitsLaunch, retryDue, retryTick, supgpFile, supgpLaunches, type LaunchElements, type LaunchRef, type Row } from "./celestrak"; 4import { compose, fetchGroups, fetchSupGP, fitsLaunch, retryDue, retryTick, supgpFile, supgpLaunches, type LaunchElements, type LaunchRef, type Row } from "./celestrak";
5import { activeEvent, fetchTrajectory, STEP_MINUTES } from "./live"; 5import { activeEvent, fetchTrajectory, STEP_MINUTES } from "./live";
6import { fetchLaunch, fetchLaunches, PREVIOUS_URL, UPCOMING_URL, type Launch } from "./ll2"; 6import { fetchLaunch, fetchLaunches, PREVIOUS_URL, throttleSeconds, Throttled, UPCOMING_URL, type Launch } from "./ll2";
7import { digestPayload, dueOffsets, fetchLatest, localDate, pickHeadlines } from "./news"; 7import { digestPayload, dueOffsets, fetchLatest, localDate, pickHeadlines, type Article } from "./news";
8import { fetchSpaceWeather, next24h, type SpaceWeather } from "./swpc"; 8import { fetchSpaceWeather, next24h, type SpaceWeather } from "./swpc";
9 9
10interface Env { 10interface Env {
@@ -48,17 +48,24 @@ const json = (body: unknown, status = 200, maxAge?: number) =>
48const PRIVACY_URL = "https://krz.sh/privacy/moonrise/"; 48const PRIVACY_URL = "https://krz.sh/privacy/moonrise/";
49 49
50/** Read-only endpoints whose responses are the same for everyone. */ 50/** 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"]);
52 52
53function api(url: URL, env: Env, now: Date): Promise<Response> { 53function api(url: URL, env: Env, now: Date): Promise<Response> {
54 switch (url.pathname) { 54 switch (url.pathname) {
55 case "/v1/today": return today(env, now); 55 case "/v1/today": return today(env, now);
56 case "/v1/launches": return launches(env, url, now); 56 case "/v1/launches": return launches(env, url, now);
57 case "/v1/live": return live(env, url, now); 57 case "/v1/live": return live(env, url, now);
58 case "/v1/news": return news(env);
58 default: return satellites(env); 59 default: return satellites(env);
59 } 60 }
60} 61}
61 62
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
62async function satellites(env: Env): Promise<Response> { 69async function satellites(env: Env): Promise<Response> {
63 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 }>(); 70 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 }>();
64 return json({ fetchedAt: row?.fetched_at ?? null, satellites: row ? JSON.parse(row.body) : [] }, 200, MAX_AGE.satellites); 71 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
82} 89}
83 90
84/** How long clients may reuse each GET response, matched to how often its source is polled. */ 91/** 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;
86 93
87function validDevice(d: Partial<DeviceRequest>): d is DeviceRequest { 94function validDevice(d: Partial<DeviceRequest>): d is DeviceRequest {
88 return ( 95 return (
@@ -141,7 +148,7 @@ export default {
141 async scheduled(controller: ScheduledController, env: Env, ctx: ExecutionContext): Promise<void> { 148 async scheduled(controller: ScheduledController, env: Env, ctx: ExecutionContext): Promise<void> {
142 const now = new Date(controller.scheduledTime); 149 const now = new Date(controller.scheduledTime);
143 if (controller.cron === NEWS_CRON) { 150 if (controller.cron === NEWS_CRON) {
144 ctx.waitUntil(sendNewsDigests(env, now)); 151 ctx.waitUntil(pollNews(env, now).then(() => sendNewsDigests(env, now)));
145 if (now.getUTCHours() === 0 && now.getUTCMinutes() === 0) ctx.waitUntil(prune(env, now)); 152 if (now.getUTCHours() === 0 && now.getUTCMinutes() === 0) ctx.waitUntil(prune(env, now));
146 } else if (controller.cron === SATELLITE_CRON) ctx.waitUntil(pollSatellites(env, now)); 153 } else if (controller.cron === SATELLITE_CRON) ctx.waitUntil(pollSatellites(env, now));
147 else if (controller.cron === FOCUS_CRON) ctx.waitUntil(focusTick(env, now)); 154 else if (controller.cron === FOCUS_CRON) ctx.waitUntil(focusTick(env, now));
@@ -242,10 +249,11 @@ const nearLaunches = async (env: Env, now: Date): Promise<Near[]> =>
242 */ 249 */
243async function launchTick(env: Env, now: Date): Promise<void> { 250async function launchTick(env: Env, now: Date): Promise<void> {
244 const near = await nearLaunches(env, now); 251 const near = await nearLaunches(env, now);
252 const throttled = await ll2Throttled(env, now);
245 const focus = near.filter((l) => inFocus(l, now)).map((l) => l.id); 253 const focus = near.filter((l) => inFocus(l, now)).map((l) => l.id);
246 const keyed = Boolean(env.LL2_API_KEY); 254 const keyed = Boolean(env.LL2_API_KEY);
247 const pollFocus = focus.length > 0 && focusPollDue(5, now, keyed); 255 const pollFocus = !throttled && focus.length > 0 && focusPollDue(5, now, keyed);
248 const pollList = !focus.length && now.getUTCMinutes() % 10 === 0; 256 const pollList = !throttled && !focus.length && now.getUTCMinutes() % 10 === 0;
249 if (pollFocus) await pollLaunch(env, focusPick(focus, now, focusEvery(keyed)), now); 257 if (pollFocus) await pollLaunch(env, focusPick(focus, now, focusEvery(keyed)), now);
250 else if (pollList) await pollLaunches(env, now); 258 else if (pollList) await pollLaunches(env, now);
251 // Channels are handed out with the launch's current state, so a poll means reading it again. 259 // 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> {
254 262
255/** With an LL2 key: the launch in focus on the even minutes the 5-minute cron does not run on, and its broadcasts. */ 263/** With an LL2 key: the launch in focus on the even minutes the 5-minute cron does not run on, and its broadcasts. */
256async function focusTick(env: Env, now: Date): Promise<void> { 264async 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;
258 const focus = (await nearLaunches(env, now)).filter((l) => inFocus(l, now)).map((l) => l.id); 266 const focus = (await nearLaunches(env, now)).filter((l) => inFocus(l, now)).map((l) => l.id);
259 if (!focus.length) return; 267 if (!focus.length) return;
260 await pollLaunch(env, focusPick(focus, now, focusEvery(true)), now); 268 await pollLaunch(env, focusPick(focus, now, focusEvery(true)), now);
261 if (env.APNS_KEY) await broadcastChanges(env, now); 269 if (env.APNS_KEY) await broadcastChanges(env, now);
262} 270}
263 271
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
264async function pollLaunch(env: Env, id: string, now: Date): Promise<void> { 285async function pollLaunch(env: Env, id: string, now: Date): Promise<void> {
265 try { 286 try {
266 await env.DB.batch(upsertLaunches(env, [await fetchLaunch(id, env.LL2_API_KEY)])); 287 await env.DB.batch(upsertLaunches(env, [await fetchLaunch(id, env.LL2_API_KEY)]));
267 } catch (e) { 288 } catch (e) {
268 console.error("ll2 launch", String(e)); 289 console.error("ll2 launch", String(e));
290 if (e instanceof Throttled) await ll2Throttle(env, now);
269 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(); 291 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();
270 } 292 }
271} 293}
@@ -277,6 +299,7 @@ async function pollLaunches(env: Env, now: Date): Promise<void> {
277 list = await fetchLaunches(UPCOMING_URL, env.LL2_API_KEY); 299 list = await fetchLaunches(UPCOMING_URL, env.LL2_API_KEY);
278 } catch (e) { 300 } catch (e) {
279 console.error("ll2", String(e)); 301 console.error("ll2", String(e));
302 if (e instanceof Throttled) await ll2Throttle(env, now);
280 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(); 303 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();
281 return; 304 return;
282 } 305 }
@@ -286,6 +309,7 @@ async function pollLaunches(env: Env, now: Date): Promise<void> {
286 list = [...list, ...(await fetchLaunches(PREVIOUS_URL, env.LL2_API_KEY))]; 309 list = [...list, ...(await fetchLaunches(PREVIOUS_URL, env.LL2_API_KEY))];
287 } catch (e) { 310 } catch (e) {
288 console.error("ll2 previous", String(e)); 311 console.error("ll2 previous", String(e));
312 if (e instanceof Throttled) await ll2Throttle(env, now);
289 } 313 }
290 } 314 }
291 await env.DB.batch([ 315 await env.DB.batch([
@@ -388,11 +412,18 @@ async function retrySatellites(env: Env, now: Date): Promise<void> {
388 412
389async function pollSatellites(env: Env, now: Date): Promise<void> { 413async function pollSatellites(env: Env, now: Date): Promise<void> {
390 let groups: { visual: Row[]; recent: Row[] }; 414 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 }>();
391 try { 418 try {
392 groups = await fetchGroups(); 419 groups = await fetchGroups(kept ? JSON.parse(kept.body) : undefined);
393 } catch (e) { 420 } catch (e) {
394 console.error("celestrak", String(e)); 421 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 ]);
396 return; 427 return;
397 } 428 }
398 const launches = await env.DB.prepare("SELECT id, mission, provider, net, launch_designator AS designator FROM launches WHERE net >= ?1") 429 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
458 })); 489 }));
459} 490}
460 491
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
461/** The daily news digest, sent in the 09:00 local hour to devices that opted in, once per local day. */ 503/** The daily news digest, sent in the 09:00 local hour to devices that opted in, once per local day. */
462async function sendNewsDigests(env: Env, now: Date): Promise<void> { 504async function sendNewsDigests(env: Env, now: Date): Promise<void> {
463 if (!env.APNS_KEY) return; 505 if (!env.APNS_KEY) return;
@@ -470,15 +512,10 @@ async function sendNewsDigests(env: Env, now: Date): Promise<void> {
470 const due = rows.results.map((d) => ({ ...d, band: 0, event: `${d.token}:${localDate(now, d.utc_offset_minutes)}` })); 512 const due = rows.results.map((d) => ({ ...d, band: 0, event: `${d.token}:${localDate(now, d.utc_offset_minutes)}` }));
471 if (!due.length) return; 513 if (!due.length) return;
472 514
473 let payload; 515 const row = await env.DB.prepare("SELECT body FROM feed_snapshots WHERE feed = 'news' AND ok = 1").first<{ body: string }>();
474 try { 516 const headlines = pickHeadlines(row ? JSON.parse(row.body) as Article[] : [], now);
475 const headlines = pickHeadlines(await fetchLatest(), now); 517 if (!headlines.length) return;
476 if (!headlines.length) return; 518 const payload = digestPayload(headlines);
477 payload = digestPayload(headlines);
478 } catch (e) {
479 console.error("snapi", String(e));
480 return;
481 }
482 519
483 await sendAlerts(env, "news", due, now, () => payload); 520 await sendAlerts(env, "news", due, now, () => payload);
484} 521}
server/src/live.ts +2 −3
@@ -1,5 +1,6 @@
1// Live coverage of a crewed or lunar mission: its trajectory from JPL Horizons, cached while the event runs. 1// Live coverage of a crewed or lunar mission: its trajectory from JPL Horizons, cached while the event runs.
2// To cover a new mission, add it to EVENTS (Horizons ID, window, phases) and deploy. 2// To cover a new mission, add it to EVENTS (Horizons ID, window, phases) and deploy.
3import { USER_AGENT } from "./agent.ts";
3 4
4export interface LiveEvent { 5export interface LiveEvent {
5 id: string; 6 id: string;
@@ -42,8 +43,6 @@ export const EVENTS: LiveEvent[] = [
42 43
43export const STEP_MINUTES = 30; 44export const STEP_MINUTES = 30;
44 45
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)";
47 46
48/** The event whose window contains `at`, if any. */ 47/** The event whose window contains `at`, if any. */
49export function activeEvent(at: Date, events = EVENTS): LiveEvent | undefined { 48export function activeEvent(at: Date, events = EVENTS): LiveEvent | undefined {
@@ -87,7 +86,7 @@ export async function fetchTrajectory(e: LiveEvent, until: Date, from = new Date
87 START_TIME: `'${fmt(start)}'`, STOP_TIME: `'${fmt(stop)}'`, STEP_SIZE: `'${STEP_MINUTES}m'`, 86 START_TIME: `'${fmt(start)}'`, STOP_TIME: `'${fmt(stop)}'`, STEP_SIZE: `'${STEP_MINUTES}m'`,
88 VEC_TABLE: "'1'", OUT_UNITS: "'KM-S'", CSV_FORMAT: "'YES'", OBJ_DATA: "'NO'", MAKE_EPHEM: "'YES'", 87 VEC_TABLE: "'1'", OUT_UNITS: "'KM-S'", CSV_FORMAT: "'YES'", OBJ_DATA: "'NO'", MAKE_EPHEM: "'YES'",
89 }); 88 });
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 } });
91 if (res.status !== 200) throw new Error(`Horizons ${res.status}`); 90 if (res.status !== 200) throw new Error(`Horizons ${res.status}`);
92 const result = ((await res.json()) as { result: string }).result; 91 const result = ((await res.json()) as { result: string }).result;
93 const first = ephemerisLimit(result, "prior to"); 92 const first = ephemerisLimit(result, "prior to");
server/src/ll2.ts +15 −1
@@ -1,5 +1,6 @@
1// Launch Library 2 (The Space Devs). Anonymous limit: 15 requests per hour. 1// Launch Library 2 (The Space Devs). Anonymous limit: 15 requests per hour.
2// Images are not used: their licences are often "Unknown". 2// Images are not used: their licences are often "Unknown".
3import { USER_AGENT } from "./agent.ts";
3 4
4export const UPCOMING_URL = "https://ll.thespacedevs.com/2.3.0/launches/upcoming/?limit=20&mode=normal"; 5export const UPCOMING_URL = "https://ll.thespacedevs.com/2.3.0/launches/upcoming/?limit=20&mode=normal";
5/** Recent launches, for the international designator, which is assigned only after liftoff. */ 6/** Recent launches, for the international designator, which is assigned only after liftoff. */
@@ -73,13 +74,26 @@ export function normalize(r: Raw): Launch {
73 74
74/** `apiKey` lifts the anonymous per-IP limit, which Cloudflare's shared egress IPs often exhaust (HTTP 429). */ 75/** `apiKey` lifts the anonymous per-IP limit, which Cloudflare's shared egress IPs often exhaust (HTTP 429). */
75async function get<T>(url: string, apiKey?: string): Promise<T> { 76async 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 };
77 if (apiKey) headers.authorization = `Token ${apiKey}`; 78 if (apiKey) headers.authorization = `Token ${apiKey}`;
78 const res = await fetch(url, { headers }); 79 const res = await fetch(url, { headers });
80 if (res.status === 429) throw new Throttled();
79 if (!res.ok) throw new Error(`LL2 ${res.status}`); 81 if (!res.ok) throw new Error(`LL2 ${res.status}`);
80 return (await res.json()) as T; 82 return (await res.json()) as T;
81} 83}
82 84
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
83export async function fetchLaunches(url: string, apiKey?: string): Promise<Launch[]> { 97export async function fetchLaunches(url: string, apiKey?: string): Promise<Launch[]> {
84 return (await get<{ results: Raw[] }>(url, apiKey)).results.map(normalize); 98 return (await get<{ results: Raw[] }>(url, apiKey)).results.map(normalize);
85} 99}
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";
2 3
3export interface Article { 4export interface Article {
4 id: number; 5 id: number;
5 title: string; 6 title: string;
6 news_site: string; 7 news_site: string;
7 published_at: string; 8 published_at: string;
9 summary?: string;
10 url?: string;
11 image_url?: string | null;
8} 12}
9 13
10export const DIGEST_HOUR = 9; 14export const DIGEST_HOUR = 9;
@@ -50,8 +54,9 @@ export function digestPayload(headlines: Article[]) {
50 54
51export async function fetchLatest(): Promise<Article[]> { 55export async function fetchLatest(): Promise<Article[]> {
52 const res = await fetch("https://api.spaceflightnewsapi.net/v4/articles/?limit=50", { 56 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 },
54 }); 58 });
55 if (res.status !== 200) throw new Error(`SNAPI ${res.status}`); 59 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 }));
57} 62}
server/src/swpc.ts +4 −1
@@ -1,4 +1,5 @@
1// NOAA SWPC feeds. Responses carry cache-control max-age=60; poll no faster. 1// NOAA SWPC feeds. Responses carry cache-control max-age=60; poll no faster.
2import { USER_AGENT } from "./agent.ts";
2 3
3export const KP_NOW_URL = "https://services.swpc.noaa.gov/json/planetary_k_index_1m.json"; 4export const KP_NOW_URL = "https://services.swpc.noaa.gov/json/planetary_k_index_1m.json";
4export const KP_FORECAST_URL = "https://services.swpc.noaa.gov/products/noaa-planetary-k-index-forecast.json"; 5export 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 {
27} 28}
28 29
29export async function fetchSpaceWeather(): Promise<SpaceWeather> { 30export 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 });
31 if (!a.ok || !b.ok) throw new Error(`SWPC ${a.status}/${b.status}`); 34 if (!a.ok || !b.ok) throw new Error(`SWPC ${a.status}/${b.status}`);
32 return decode(await a.json(), await b.json()); 35 return decode(await a.json(), await b.json());
33} 36}
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
170 assert.equal(await requests(FIVE, "2026-10-21T08:40:00Z"), 0); 170 assert.equal(await requests(FIVE, "2026-10-21T08:40:00Z"), 0);
171}); 171});
172 172
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
173test("aurora alerts go out in bounded slices and are recorded per device once answered", async () => { 224test("aurora alerts go out in bounded slices and are recorded per device once answered", async () => {
174 const { db, env, calls } = await setup(); 225 const { db, env, calls } = await setup();
175 for (let i = 0; i < PUSH_SLICE + 10; i++) device(db, i); 226 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
227 assert.equal(new Set(push.state.sent).size, PUSH_SLICE + 5); 278 assert.equal(new Set(push.state.sent).size, PUSH_SLICE + 5);
228 await run(env, NEWS, "2026-10-20T14:20:00Z"); 279 await run(env, NEWS, "2026-10-20T14:20:00Z");
229 assert.equal(push.state.sent.length, PUSH_SLICE + 5); 280 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");
231 assert.equal(count(db, "SELECT count(*) AS n FROM alerts_sent WHERE kind = 'news' AND event LIKE '%:2026-10-20'"), PUSH_SLICE + 5); 282 assert.equal(count(db, "SELECT count(*) AS n FROM alerts_sent WHERE kind = 'news' AND event LIKE '%:2026-10-20'"), PUSH_SLICE + 5);
232 283
233 const q = calls.find((c) => c.sql.includes("news = 1"))!; 284 const q = calls.find((c) => c.sql.includes("news = 1"))!;