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 a0928c6710

a0928c67109a7aa503bf5a9b4bd98ca6aafe11f4

parent: 2863037e46

Unsigned

cmc <hello@cleberg.net> · 2026-10-21 04:34 UTC

Server: push slices, CelesTrak retry, 2-minute keyed focus poll, retention (!73)

## Changes

- **CelesTrak**: fetches time out after 10 s. A failed 2-hourly poll (:07 of even hours) is retried once from the `*/5` cron at :40 of the same hour. A failed retry is not retried. Each attempt still stops on the first non-200, so there are at most 2 errors per 2 hours (CelesTrak blocks an IP after more than 50 errors in 2 hours).
- **Aurora and news pushes**: an `alerts_sent` row is written per device only after APNs answers. 200 and other 4xx are recorded, 410 deletes the device, and network errors, 429 and 5xx are left for a later run. Each run sends to at most 20 devices (`PUSH_SLICE`), 6 at a time, and writes the results in one D1 batch. The rest go out on later runs. Concurrent sends share one provider token.
  - Aurora: one alert per device per 12-hour window (key `token:eventKey`), sent once it is night for that device, instead of one claim per band.
  - News: devices are due for the whole local 09:00 hour (6 runs), so later runs reach the devices an earlier run did not.
- **/v1/launches**: its five queries go in one `env.DB.batch`.
- **LL2**: with `LL2_API_KEY`, the launch in focus is polled every 2 minutes. A new `*/2` cron covers the even minutes the `*/5` cron does not run on, and broadcasts changes. Without a key the `*/2` cron returns before any I/O, and polling stays at 5 minutes.
  - Worst case, simulated with the scheduling functions over every NET alignment and pairs of overlapping launches: **31 requests in any 60 minutes with a key** (30 focus polls plus the hourly `previous`), 13 anonymous (unchanged).
- **Retention**: at 00:00 UTC the news cron deletes `alerts_sent` rows older than 3 days (all kinds) and devices whose `last_seen` is older than 180 days. The app registers at every launch, so only devices whose app has not been opened in 6 months lose alerts.
- **Index**: migration `0006_devices_news.sql` adds `devices (news, utc_offset_minutes)`. The news query filters by the due offset ranges and uses MULTI-INDEX OR range searches (checked with EXPLAIN QUERY PLAN on local D1). Before, it scanned all devices.
- The launch upsert skips rows where no column changed. The `near` query is not repeated on `*/5` ticks without an LL2 poll. After a poll it is read again so channels are handed out with current state.

## Tests

`server/test/worker.test.ts` runs the Worker's `fetch`/`scheduled` handlers against node:sqlite with the migrations applied and a stubbed `fetch`. Against origin/main, all 9 of its tests fail:

| Check | main | this branch |
|-|-|-|
| CelesTrak requests at 02:40 after a failed 02:07 | 0 | 1 (none after that) |
| APNs sends in one aurora run, 30 devices due | 30 | 20, at most 6 in flight; 30 subrequests in total |
| Aurora run that hits the subrequest limit after 2 sends | throws; the band claim drops the other 3 | 2 recorded, other 3 sent on the next run |
| News sends at 09:00 local, 25 devices | 25 at :00, none later | 20 at :00, 5 at :10, SNAPI not fetched at :20 |
| Old `test`/`aurora` keys and 180-day-idle devices at 00:00 | kept | deleted |
| D1 round trips for GET /v1/launches | 5 | 1 |
| LL2 requests in a focus hour (key / no key) | 42* / 12 | 30 / 12 |
| Launch rows rewritten on an unchanged list poll | 1 per launch | 0 |
| `near` queries on a `*/5` tick without a poll | 2 | 1 |
| Provider tokens signed for 6 concurrent sends | 6 | 1 |

\* main has no `*/2` handler, so that cron would run the whole `*/5` job.

`npm test`: 55 pass. `swift test` (MoonriseKit): pass. Bundle checked with `wrangler deploy --dry-run`. Migrations applied to local D1, and the new SQL (json_each, `date()` with an offset modifier, row-value `IS NOT`) run on workerd's SQLite. Under `wrangler dev`: `/v1/launches` and the midnight prune ran against local D1.

## Deploy

1. `wrangler d1 migrations apply moonrise --remote` (adds `0006_devices_news.sql`) before deploying.
2. `wrangler deploy`. This adds a fourth cron trigger (`*/2`). The Free plan allows 5 cron triggers per account.
3. `PUSH_SLICE` (20) is sized for Free's 50 subrequests per invocation. Raise it after moving to Paid.
4. Expected once after deploy: devices that got an aurora alert under a band claim earlier in the same 12-hour window can get one more.

Layout: unified · split

server/README.org +3
@@ -32,6 +32,9 @@ so anonymous requests from Cloudflare often get HTTP 429. With an API key:
3232wrangler secret put LL2_API_KEY
3333#+end_src
3434
35With the key, the launch in focus (T−60 to T+15) is polled every 2 minutes
36(at most 31 requests an hour); without it, every 5 (at most 13).
37
3538* launch Live Activity channels
3639Launch Live Activities get status and NET changes over APNs broadcast
3740channels, one per launch and APNs environment, handed out a day before NET
server/migrations/0006_devices_news.sql added +2
@@ -0,0 +1,2 @@
1-- The news cron selects opted-in devices by UTC offset.
2CREATE INDEX devices_news ON devices (news, utc_offset_minutes);
server/src/activity.ts +16 −4
@@ -2,7 +2,7 @@
22// so the server never learns who follows a launch.
33
44const MINUTE = 60_000;
5/** A launch is polled on its own every 5 minutes from T−60 to T+15. */
5/** A launch is polled on its own from T−60 to T+15. */
66const FOCUS_BEFORE = 60 * MINUTE;
77const FOCUS_AFTER = 15 * MINUTE;
88/** Launch Library 2 status abbreviations that end the activity. */
@@ -31,9 +31,21 @@ export function inFocus(l: ActivityState, now: Date): boolean {
3131 return !OUTCOMES.includes(l.status) && t - FOCUS_BEFORE <= now.getTime() && now.getTime() <= t + FOCUS_AFTER;
3232}
3333
34/** One launch per 5-minute tick; launches in focus at the same time take turns. */
35export function focusPick(ids: string[], now: Date): string {
36 return ids[Math.floor(now.getTime() / (5 * MINUTE)) % ids.length];
34/** Minutes between polls of the launch in focus: 5 anonymously (15 requests/hour), 2 with a Launch Library 2 key. */
35export const focusEvery = (keyed: boolean) => (keyed ? 2 : 5);
36
37/**
38 * Whether the 5-minute or the 2-minute cron polls the launch in focus on this tick. With a key the 2-minute cron
39 * takes the even minutes the 5-minute cron does not run on.
40 */
41export function focusPollDue(cron: 2 | 5, now: Date, keyed: boolean): boolean {
42 const m = now.getUTCMinutes();
43 return cron === 5 ? m % focusEvery(keyed) === 0 : keyed && m % 5 !== 0;
44}
45
46/** One launch per poll; launches in focus at the same time take turns. */
47export function focusPick(ids: string[], now: Date, every = 5): string {
48 return ids[Math.floor(now.getTime() / (every * MINUTE)) % ids.length];
3749}
3850
3951/** Channels are handed out a day ahead, so a follow at any time before launch can subscribe. */
server/src/apns.ts +27 −4
@@ -41,14 +41,20 @@ export async function providerToken(keyId: string, teamId: string, key: CryptoKe
4141 return `${input}.${base64url(new Uint8Array(sig))}`;
4242}
4343
44/** Apple accepts a token for up to 60 minutes and rejects refreshes more often than every 20. */
45let cached: { token: string; issuedAt: number; keyId: string } | null = null;
44/**
45 * Apple accepts a token for up to 60 minutes and rejects refreshes more often than every 20. The promise is
46 * cached, so concurrent sends share one token.
47 */
48let cached: { token: Promise<string>; issuedAt: number; keyId: string } | null = null;
4649
47async function token(config: ApnsConfig): Promise<string> {
50function token(config: ApnsConfig): Promise<string> {
4851 const now = Math.floor(Date.now() / 1000);
4952 if (cached && cached.keyId === config.keyId && now - cached.issuedAt < 50 * 60) return cached.token;
50 const t = await providerToken(config.keyId, config.teamId, await importKey(config.privateKey), now);
53 const t = importKey(config.privateKey).then((key) => providerToken(config.keyId, config.teamId, key, now));
5154 cached = { token: t, issuedAt: now, keyId: config.keyId };
55 t.catch(() => {
56 if (cached?.token === t) cached = null;
57 });
5258 return t;
5359}
5460
@@ -68,6 +74,23 @@ export async function send(config: ApnsConfig, deviceToken: string, payload: unk
6874 return result(res, "apns-id");
6975}
7076
77/** `send` to each device, at most `concurrency` at a time. Results are in input order; a network error is status 0. */
78export async function sendAll(config: ApnsConfig, sends: { token: string; payload: unknown; sandbox: boolean }[], concurrency: number): Promise<ApnsResult[]> {
79 const out: ApnsResult[] = new Array(sends.length);
80 let next = 0;
81 const worker = async () => {
82 while (next < sends.length) {
83 const i = next++;
84 out[i] = await send(config, sends[i].token, sends[i].payload, sends[i].sandbox).catch((e) => ({ status: 0, apnsId: null, reason: String(e) }));
85 }
86 };
87 await Promise.all(Array.from({ length: Math.min(concurrency, sends.length) }, worker));
88 return out;
89}
90
91/** Failures that may pass: network errors, 429 and 5xx. Other statuses are final for that device. */
92export const retryable = (status: number) => status === 0 || status === 429 || status >= 500;
93
7194async function result(res: Response, idHeader: string): Promise<ApnsResult> {
7295 let reason: string | null = null;
7396 if (!res.ok) {
server/src/aurora.ts +1 −1
@@ -34,7 +34,7 @@ export function isNight(now: Date, utcOffsetMinutes: number): boolean {
3434 return hour >= 20 || hour < 4;
3535}
3636
37/** One alert per band per 12-hour UTC window. */
37/** One alert per device per 12-hour UTC window. */
3838export function eventKey(now: Date): string {
3939 const d = now.toISOString().slice(0, 10);
4040 return `${d}${now.getUTCHours() < 12 ? "a" : "b"}`;
server/src/celestrak.ts +14 −2
@@ -1,5 +1,6 @@
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.
3// A failed poll is tried once more 33 minutes later: at most 2 errors in 2 hours.
34
45/** ISS, Tiangong (CSS Tianhe) and Hubble; all three are in the visual group. */
56export const FEATURED = [25544, 48274, 20580];
@@ -154,10 +155,21 @@ export function compose(visual: Row[], recent: Row[], launches: LaunchRef[], sup
154155 return { satellites: [...pick(visual), ...starlinkTrains(groups)], launches: out };
155156}
156157
158/** The 5-minute tick 33 minutes after each 2-hourly poll, which runs at minute 7 of even UTC hours. */
159export const retryTick = (now: Date) => now.getUTCHours() % 2 === 0 && now.getUTCMinutes() === 40;
160
161/** Whether this tick's 2-hourly poll failed and nothing has succeeded since. A failed retry is not retried. */
162export function retryDue(now: Date, lastOk: string | null, lastError: string | null): boolean {
163 if (!retryTick(now) || !lastError) return false;
164 const error = Date.parse(lastError);
165 return error >= now.getTime() - 33 * 60_000 && error < now.getTime() && (!lastOk || Date.parse(lastOk) < error);
166}
167
157168const HEADERS = { "user-agent": "moonrise-server (sh.krz.moonrise)" };
169const TIMEOUT_MS = 10_000;
158170
159171async function group(name: string): Promise<Row[]> {
160 const res = await fetch(`https://celestrak.org/NORAD/elements/gp.php?GROUP=${name}&FORMAT=JSON`, { headers: HEADERS });
172 const res = await fetch(`https://celestrak.org/NORAD/elements/gp.php?GROUP=${name}&FORMAT=JSON`, { headers: HEADERS, signal: AbortSignal.timeout(TIMEOUT_MS) });
161173 if (res.status !== 200) throw new Error(`CelesTrak ${res.status} for ${name}`);
162174 return (await res.json()) as Row[];
163175}
@@ -171,7 +183,7 @@ export async function fetchGroups(): Promise<{ visual: Row[]; recent: Row[] }> {
171183
172184/** One SupGP file; throws on a non-200 so the caller stops. */
173185export async function fetchSupGP(file: string): Promise<Row[]> {
174 const res = await fetch(`https://celestrak.org/NORAD/elements/supplemental/sup-gp.php?FILE=${file}&FORMAT=JSON`, { headers: HEADERS });
186 const res = await fetch(`https://celestrak.org/NORAD/elements/supplemental/sup-gp.php?FILE=${file}&FORMAT=JSON`, { headers: HEADERS, signal: AbortSignal.timeout(TIMEOUT_MS) });
175187 if (res.status !== 200) throw new Error(`CelesTrak SupGP ${res.status} for ${file}`);
176188 return parseSupGP(await res.text());
177189}
server/src/index.ts +139 −70
@@ -1,10 +1,10 @@
1import { activityPush, focusPick, inFocus, needsChannel, sinceNet } from "./activity";
2import { broadcast, createChannel, deleteChannel, send, type ApnsConfig } from "./apns";
1import { activityPush, focusEvery, focusPick, focusPollDue, inFocus, needsChannel, sinceNet, type ActivityState } from "./activity";
2import { broadcast, createChannel, deleteChannel, retryable, send, sendAll, type ApnsConfig } from "./apns";
33import { actionableKp, alertBands, eventKey, isNight } from "./aurora";
4import { compose, fetchGroups, fetchSupGP, fitsLaunch, 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";
55import { activeEvent, fetchTrajectory, STEP_MINUTES } from "./live";
66import { fetchLaunch, fetchLaunches, PREVIOUS_URL, UPCOMING_URL, type Launch } from "./ll2";
7import { digestDue, digestPayload, fetchLatest, localDate, pickHeadlines } from "./news";
7import { digestPayload, dueOffsets, fetchLatest, localDate, pickHeadlines } from "./news";
88import { PRIVACY_HTML } from "./privacy";
99import { fetchSpaceWeather, next24h, type SpaceWeather } from "./swpc";
1010
@@ -31,8 +31,17 @@ interface DeviceRequest {
3131
3232const NEWS_CRON = "*/10 * * * *";
3333const SATELLITE_CRON = "7 */2 * * *";
34const FOCUS_CRON = "*/2 * * * *";
3435/** Launches are kept this long after NET, so a launch page and its first pass outlive liftoff. */
3536const RETENTION_MS = 14 * 86400_000;
37/** Devices are dropped after this long without registering; the app registers whenever iOS hands it a token. */
38const DEVICE_RETENTION_MS = 180 * 86400_000;
39/**
40 * Alert pushes per run; the rest go on later runs. Sized for the Free plan's 50 subrequests per invocation, shared
41 * with the rest of the run; raise it on Paid. Workers keep at most 6 connections open at once.
42 */
43const PUSH_SLICE = 20;
44const PUSH_CONCURRENCY = 6;
3645
3746const json = (body: unknown, status = 200, maxAge?: number) =>
3847 Response.json(body, { status, headers: maxAge && status === 200 ? { "cache-control": `public, max-age=${maxAge}` } : {} });
@@ -102,9 +111,12 @@ export default {
102111
103112 async scheduled(controller: ScheduledController, env: Env, ctx: ExecutionContext): Promise<void> {
104113 const now = new Date(controller.scheduledTime);
105 if (controller.cron === NEWS_CRON) ctx.waitUntil(sendNewsDigests(env, now));
106 else if (controller.cron === SATELLITE_CRON) ctx.waitUntil(pollSatellites(env, now));
107 else ctx.waitUntil(Promise.all([pollSpaceWeather(env, now), launchTick(env, now)]));
114 if (controller.cron === NEWS_CRON) {
115 ctx.waitUntil(sendNewsDigests(env, now));
116 if (now.getUTCHours() === 0 && now.getUTCMinutes() === 0) ctx.waitUntil(prune(env, now));
117 } else if (controller.cron === SATELLITE_CRON) ctx.waitUntil(pollSatellites(env, now));
118 else if (controller.cron === FOCUS_CRON) ctx.waitUntil(focusTick(env, now));
119 else ctx.waitUntil(Promise.all([pollSpaceWeather(env, now), launchTick(env, now), retrySatellites(env, now)]));
108120 },
109121} satisfies ExportedHandler<Env>;
110122
@@ -158,14 +170,15 @@ async function live(env: Env, url: URL, now: Date): Promise<Response> {
158170/** `?environment=sandbox` gives Debug builds the channels of the APNs sandbox. */
159171async function launches(env: Env, url: URL, now: Date): Promise<Response> {
160172 const since = new Date(now.getTime() - 6 * 3600_000).toISOString();
161 const rows = await env.DB.prepare("SELECT * FROM launches WHERE net >= ?1 ORDER BY net LIMIT 20").bind(since).all<Record<string, unknown>>();
162 const recent = await env.DB.prepare("SELECT * FROM launches WHERE net < ?1 AND net >= ?2 ORDER BY net DESC LIMIT 20")
163 .bind(since, new Date(now.getTime() - RETENTION_MS).toISOString()).all<Record<string, unknown>>();
164 const fetched = await env.DB.prepare("SELECT fetched_at FROM feed_snapshots WHERE feed = 'll2' AND ok = 1").first<{ fetched_at: string }>();
165 const els = await env.DB.prepare("SELECT body FROM feed_snapshots WHERE feed = 'launch-elements' AND ok = 1").first<{ body: string }>();
166 const elements: Record<string, LaunchElements> = els ? JSON.parse(els.body) : {};
167 const ch = await env.DB.prepare("SELECT launch_id, channel_id FROM launch_channels WHERE environment = ?1 AND launch_id IS NOT NULL AND ended_at IS NULL")
168 .bind(url.searchParams.get("environment") === "sandbox" ? "sandbox" : "production").all<{ launch_id: string; channel_id: string }>();
173 const [rows, recent, fetched, els, ch] = await env.DB.batch<Record<string, unknown>>([
174 env.DB.prepare("SELECT * FROM launches WHERE net >= ?1 ORDER BY net LIMIT 20").bind(since),
175 env.DB.prepare("SELECT * FROM launches WHERE net < ?1 AND net >= ?2 ORDER BY net DESC LIMIT 20").bind(since, new Date(now.getTime() - RETENTION_MS).toISOString()),
176 env.DB.prepare("SELECT fetched_at FROM feed_snapshots WHERE feed = 'll2' AND ok = 1"),
177 env.DB.prepare("SELECT body FROM feed_snapshots WHERE feed = 'launch-elements' AND ok = 1"),
178 env.DB.prepare("SELECT launch_id, channel_id FROM launch_channels WHERE environment = ?1 AND launch_id IS NOT NULL AND ended_at IS NULL")
179 .bind(url.searchParams.get("environment") === "sandbox" ? "sandbox" : "production"),
180 ]);
181 const elements: Record<string, LaunchElements> = els.results.length ? JSON.parse(String(els.results[0].body)) : {};
169182 const channels = Object.fromEntries(ch.results.map((c) => [c.launch_id, c.channel_id]));
170183 const shape = (r: Record<string, unknown>) => ({
171184 id: r.id, name: r.name, net: r.net, windowStart: r.window_start, windowEnd: r.window_end,
@@ -176,23 +189,41 @@ async function launches(env: Env, url: URL, now: Date): Promise<Response> {
176189 channelId: channels[String(r.id)] ?? null,
177190 });
178191 return json({
179 fetchedAt: fetched?.fetched_at ?? null,
192 fetchedAt: fetched.results[0]?.fetched_at ?? null,
180193 launches: rows.results.map(shape),
181194 recent: recent.results.map(shape),
182195 }, 200, MAX_AGE.launches);
183196}
184197
198type Near = ActivityState & { id: string };
199
200const nearLaunches = async (env: Env, now: Date): Promise<Near[]> =>
201 (await env.DB.prepare("SELECT id, net, status FROM launches WHERE net >= ?1 ORDER BY net").bind(sinceNet(now)).all<Near>()).results;
202
185203/**
186 * Launch Library 2 within the anonymous 15 requests per hour. Every 5 minutes: the launch in focus (T−60 to T+15)
187 * on its own, with the list paused; otherwise the upcoming list every 10 minutes and previous launches hourly.
188 * At most 12 + 1 requests in any hour.
204 * Launch Library 2: the launch in focus (T−60 to T+15) on its own, with the list paused; otherwise the upcoming list
205 * every 10 minutes and previous launches hourly. Anonymous (15 requests per hour), the launch in focus every 5 minutes:
206 * at most 12 + 1 requests in any hour. With a key (45 per hour), every 2 minutes with focusTick: at most 30 + 1.
189207 */
190208async function launchTick(env: Env, now: Date): Promise<void> {
191 const near = await env.DB.prepare("SELECT id, net, status FROM launches WHERE net >= ?1 ORDER BY net").bind(sinceNet(now)).all<{ id: string; net: string; status: string }>();
192 const focus = near.results.filter((l) => inFocus(l, now)).map((l) => l.id);
193 if (focus.length) await pollLaunch(env, focusPick(focus, now), now);
194 else if (now.getUTCMinutes() % 10 === 0) await pollLaunches(env, now);
195 if (env.APNS_KEY) await launchChannels(env, now);
209 const near = await nearLaunches(env, now);
210 const focus = near.filter((l) => inFocus(l, now)).map((l) => l.id);
211 const keyed = Boolean(env.LL2_API_KEY);
212 const pollFocus = focus.length > 0 && focusPollDue(5, now, keyed);
213 const pollList = !focus.length && now.getUTCMinutes() % 10 === 0;
214 if (pollFocus) await pollLaunch(env, focusPick(focus, now, focusEvery(keyed)), now);
215 else if (pollList) await pollLaunches(env, now);
216 // Channels are handed out with the launch's current state, so a poll means reading it again.
217 if (env.APNS_KEY) await launchChannels(env, pollFocus || pollList ? await nearLaunches(env, now) : near, now);
218}
219
220/** With an LL2 key: the launch in focus on the even minutes the 5-minute cron does not run on, and its broadcasts. */
221async function focusTick(env: Env, now: Date): Promise<void> {
222 if (!focusPollDue(2, now, Boolean(env.LL2_API_KEY))) return;
223 const focus = (await nearLaunches(env, now)).filter((l) => inFocus(l, now)).map((l) => l.id);
224 if (!focus.length) return;
225 await pollLaunch(env, focusPick(focus, now, focusEvery(true)), now);
226 if (env.APNS_KEY) await broadcastChanges(env, now);
196227}
197228
198229async function pollLaunch(env: Env, id: string, now: Date): Promise<void> {
@@ -235,7 +266,9 @@ function upsertLaunches(env: Env, list: Launch[]): D1PreparedStatement[] {
235266 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19)
236267 ON CONFLICT (id) DO UPDATE SET name = ?2, net = ?3, window_start = ?4, window_end = ?5, status = ?6, status_name = ?7, provider = ?8, rocket = ?9,
237268 mission = ?10, mission_type = ?11, mission_description = ?12, orbit = ?13, pad = ?14, location = ?15, pad_latitude = ?16, pad_longitude = ?17, last_updated = ?18,
238 launch_designator = COALESCE(?19, launch_designator)`,
269 launch_designator = COALESCE(?19, launch_designator)
270 WHERE (name, net, window_start, window_end, status, status_name, provider, rocket, mission, mission_type, mission_description, orbit, pad, location, pad_latitude, pad_longitude, last_updated, launch_designator)
271 IS NOT (?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, COALESCE(?19, launch_designator))`,
239272 );
240273 return list.map((l) => upsert.bind(l.id, l.name, l.net, l.windowStart, l.windowEnd, l.status, l.statusName, l.provider, l.rocket, l.mission, l.missionType, l.missionDescription, l.orbit, l.pad, l.location, l.padLatitude, l.padLongitude, l.lastUpdated, l.designator));
241274}
@@ -245,15 +278,14 @@ function upsertLaunches(env: Env, list: Launch[]): D1PreparedStatement[] {
245278 * (from the pool, or created here with APNS_MANAGE_CHANNELS), broadcasts each change of status or NET, and
246279 * retires a channel once its launch is over. Nothing about who follows a launch reaches the server.
247280 */
248async function launchChannels(env: Env, now: Date): Promise<void> {
281async function launchChannels(env: Env, near: Near[], now: Date): Promise<void> {
249282 const config: ApnsConfig = { keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC };
250283 const manage = env.APNS_MANAGE_CHANNELS === "1";
251284 const iso = now.toISOString();
252285
253 const near = await env.DB.prepare("SELECT id, net, status FROM launches WHERE net >= ?1").bind(sinceNet(now)).all<{ id: string; net: string; status: string }>();
254286 const assigned = await env.DB.prepare("SELECT launch_id, environment FROM launch_channels WHERE launch_id IS NOT NULL").all<{ launch_id: string; environment: string }>();
255287 const has = new Set(assigned.results.map((c) => `${c.launch_id}:${c.environment}`));
256 for (const l of near.results.filter((l) => needsChannel(l, now))) {
288 for (const l of near.filter((l) => needsChannel(l, now))) {
257289 for (const environment of ["sandbox", "production"]) {
258290 if (has.has(`${l.id}:${environment}`)) continue;
259291 const pooled = await env.DB.prepare(
@@ -275,6 +307,25 @@ async function launchChannels(env: Env, now: Date): Promise<void> {
275307 }
276308 }
277309
310 await broadcastChanges(env, now);
311
312 // A day past NET without an outcome, or gone from the table: ended without a push, as activities last 8 hours at most.
313 await env.DB.prepare("UPDATE launch_channels SET ended_at = ?1 WHERE launch_id IS NOT NULL AND ended_at IS NULL AND launch_id NOT IN (SELECT id FROM launches WHERE net >= ?2)")
314 .bind(iso, new Date(now.getTime() - 86400_000).toISOString()).run();
315 if (!manage) return;
316 // Deleted once the stored end message has expired.
317 const done = await env.DB.prepare("SELECT channel_id, environment FROM launch_channels WHERE ended_at < ?1")
318 .bind(new Date(now.getTime() - 8 * 3600_000).toISOString()).all<{ channel_id: string; environment: string }>();
319 for (const c of done.results) {
320 const r = await deleteChannel(config, c.channel_id, c.environment === "sandbox");
321 if (r.status === 204 || r.status === 404) await env.DB.prepare("DELETE FROM launch_channels WHERE channel_id = ?1").bind(c.channel_id).run();
322 else console.error("apns channel delete", r.status, r.reason);
323 }
324}
325
326/** Each change of status or NET since the last broadcast on a channel. */
327async function broadcastChanges(env: Env, now: Date): Promise<void> {
328 const config: ApnsConfig = { keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC };
278329 const changed = await env.DB.prepare(
279330 `SELECT c.channel_id, c.environment, c.net AS sent_net, c.status AS sent_status, l.net, l.status
280331 FROM launch_channels c JOIN launches l ON l.id = c.launch_id WHERE c.ended_at IS NULL AND (c.net != l.net OR c.status != l.status)`,
@@ -288,21 +339,16 @@ async function launchChannels(env: Env, now: Date): Promise<void> {
288339 console.error("apns broadcast", r.status, r.reason);
289340 continue;
290341 }
291 await env.DB.prepare("UPDATE launch_channels SET net = ?2, status = ?3, ended_at = ?4 WHERE channel_id = ?1").bind(c.channel_id, c.net, c.status, push.end ? iso : null).run();
342 await env.DB.prepare("UPDATE launch_channels SET net = ?2, status = ?3, ended_at = ?4 WHERE channel_id = ?1").bind(c.channel_id, c.net, c.status, push.end ? now.toISOString() : null).run();
292343 }
344}
293345
294 // A day past NET without an outcome, or gone from the table: ended without a push, as activities last 8 hours at most.
295 await env.DB.prepare("UPDATE launch_channels SET ended_at = ?1 WHERE launch_id IS NOT NULL AND ended_at IS NULL AND launch_id NOT IN (SELECT id FROM launches WHERE net >= ?2)")
296 .bind(iso, new Date(now.getTime() - 86400_000).toISOString()).run();
297 if (!manage) return;
298 // Deleted once the stored end message has expired.
299 const done = await env.DB.prepare("SELECT channel_id, environment FROM launch_channels WHERE ended_at < ?1")
300 .bind(new Date(now.getTime() - 8 * 3600_000).toISOString()).all<{ channel_id: string; environment: string }>();
301 for (const c of done.results) {
302 const r = await deleteChannel(config, c.channel_id, c.environment === "sandbox");
303 if (r.status === 204 || r.status === 404) await env.DB.prepare("DELETE FROM launch_channels WHERE channel_id = ?1").bind(c.channel_id).run();
304 else console.error("apns channel delete", r.status, r.reason);
305 }
346/** One more try at a failed 2-hourly CelesTrak poll, from the 5-minute cron. */
347async function retrySatellites(env: Env, now: Date): Promise<void> {
348 if (!retryTick(now)) return;
349 const rows = await env.DB.prepare("SELECT feed, fetched_at FROM feed_snapshots WHERE feed IN ('celestrak', 'celestrak:error')").all<{ feed: string; fetched_at: string }>();
350 const at = Object.fromEntries(rows.results.map((r) => [r.feed, r.fetched_at]));
351 if (retryDue(now, at.celestrak ?? null, at["celestrak:error"] ?? null)) await pollSatellites(env, now);
306352}
307353
308354async function pollSatellites(env: Env, now: Date): Promise<void> {
@@ -366,31 +412,27 @@ async function sendAuroraAlerts(env: Env, w: SpaceWeather, now: Date): Promise<v
366412 const bands = alertBands(kp, bandRows.results.map((r) => r.band));
367413 if (!bands.length || !env.APNS_KEY) return;
368414
369 const config: ApnsConfig = { keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC };
370415 const event = eventKey(now);
371 for (const band of bands) {
372 const claimed = await env.DB.prepare("INSERT OR IGNORE INTO alerts_sent (kind, band, event, sent_at) VALUES ('aurora', ?1, ?2, ?3)")
373 .bind(band, event, now.toISOString()).run();
374 if (!claimed.meta.changes) continue;
375
376 const devices = await env.DB.prepare("SELECT token, environment, utc_offset_minutes FROM devices WHERE aurora = 1 AND band = ?1")
377 .bind(band).all<{ token: string; environment: string; utc_offset_minutes: number }>();
378 for (const d of devices.results) {
379 if (!isNight(now, d.utc_offset_minutes)) continue;
380 const payload = { aps: { alert: { title: "Aurora possible tonight", body: `Kp ${kp.toFixed(1)}. Look toward the ${band >= 0 ? "north" : "south"} after dark.` }, sound: "default" } };
381 const r = await send(config, d.token, payload, d.environment === "sandbox");
382 if (r.status === 410) await env.DB.prepare("DELETE FROM devices WHERE token = ?1").bind(d.token).run();
383 else if (r.status !== 200) console.error("apns", r.status, r.reason);
384 }
385 }
416 const devices = await env.DB.prepare(
417 `SELECT token, environment, band, utc_offset_minutes FROM devices d WHERE d.aurora = 1 AND d.band IN (SELECT value FROM json_each(?1))
418 AND NOT EXISTS (SELECT 1 FROM alerts_sent a WHERE a.kind = 'aurora' AND a.band = d.band AND a.event = d.token || ':' || ?2)`,
419 ).bind(JSON.stringify(bands), event).all<{ token: string; environment: string; band: number; utc_offset_minutes: number }>();
420 const due = devices.results.filter((d) => isNight(now, d.utc_offset_minutes)).map((d) => ({ ...d, event: `${d.token}:${event}` }));
421 await sendAlerts(env, "aurora", due, now, (d) => ({
422 aps: { alert: { title: "Aurora possible tonight", body: `Kp ${kp.toFixed(1)}. Look toward the ${d.band >= 0 ? "north" : "south"} after dark.` }, sound: "default" },
423 }));
386424}
387425
388/** The daily news digest, sent at 09:00 local time to devices that opted in, once per local day. */
426/** The daily news digest, sent in the 09:00 local hour to devices that opted in, once per local day. */
389427async function sendNewsDigests(env: Env, now: Date): Promise<void> {
390428 if (!env.APNS_KEY) return;
391 const rows = await env.DB.prepare("SELECT token, environment, utc_offset_minutes FROM devices WHERE news = 1")
392 .all<{ token: string; environment: string; utc_offset_minutes: number }>();
393 const due = rows.results.filter((d) => digestDue(now, d.utc_offset_minutes));
429 const [first, second] = dueOffsets(now);
430 const rows = await env.DB.prepare(
431 `SELECT token, environment, utc_offset_minutes FROM devices d WHERE d.news = 1
432 AND (d.utc_offset_minutes >= ?1 AND d.utc_offset_minutes < ?2 OR d.utc_offset_minutes >= ?3 AND d.utc_offset_minutes < ?4)
433 AND NOT EXISTS (SELECT 1 FROM alerts_sent a WHERE a.kind = 'news' AND a.band = 0 AND a.event = d.token || ':' || date(?5, d.utc_offset_minutes || ' minutes'))`,
434 ).bind(...first, ...second, now.toISOString()).all<{ token: string; environment: string; utc_offset_minutes: number }>();
435 const due = rows.results.map((d) => ({ ...d, band: 0, event: `${d.token}:${localDate(now, d.utc_offset_minutes)}` }));
394436 if (!due.length) return;
395437
396438 let payload;
@@ -403,14 +445,41 @@ async function sendNewsDigests(env: Env, now: Date): Promise<void> {
403445 return;
404446 }
405447
448 await sendAlerts(env, "news", due, now, () => payload);
449}
450
451interface Recipient {
452 token: string;
453 environment: string;
454 band: number;
455 /** The alerts_sent key for this device. */
456 event: string;
457}
458
459/**
460 * Sends to the first PUSH_SLICE recipients, then in one batch records every send APNs answered for good in
461 * alerts_sent and drops devices it reports gone (410). Retryable failures are not recorded, so a later run tries again.
462 */
463async function sendAlerts(env: Env, kind: string, recipients: Recipient[], now: Date, payload: (r: Recipient) => unknown): Promise<void> {
406464 const config: ApnsConfig = { keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC };
407 for (const d of due) {
408 const claimed = await env.DB.prepare("INSERT OR IGNORE INTO alerts_sent (kind, band, event, sent_at) VALUES ('news', 0, ?1, ?2)")
409 .bind(`${d.token}:${localDate(now, d.utc_offset_minutes)}`, now.toISOString()).run();
410 if (!claimed.meta.changes) continue;
411 const r = await send(config, d.token, payload, d.environment === "sandbox");
412 if (r.status === 410) await env.DB.prepare("DELETE FROM devices WHERE token = ?1").bind(d.token).run();
413 else if (r.status !== 200) console.error("apns", r.status, r.reason);
414 }
415 await env.DB.prepare("DELETE FROM alerts_sent WHERE kind = 'news' AND sent_at < ?1").bind(new Date(now.getTime() - 3 * 86400_000).toISOString()).run();
465 const slice = recipients.slice(0, PUSH_SLICE);
466 const results = await sendAll(config, slice.map((r) => ({ token: r.token, payload: payload(r), sandbox: r.environment === "sandbox" })), PUSH_CONCURRENCY);
467 const sent = env.DB.prepare("INSERT OR IGNORE INTO alerts_sent (kind, band, event, sent_at) VALUES (?1, ?2, ?3, ?4)");
468 const gone = env.DB.prepare("DELETE FROM devices WHERE token = ?1");
469 const writes: D1PreparedStatement[] = [];
470 slice.forEach((r, i) => {
471 const { status, reason } = results[i];
472 if (status !== 200) console.error("apns", status, reason);
473 if (status === 410) writes.push(gone.bind(r.token));
474 else if (!retryable(status)) writes.push(sent.bind(kind, r.band, r.event, now.toISOString()));
475 });
476 if (writes.length) await env.DB.batch(writes);
477}
478
479/** Daily: alert keys older than 3 days (the longest is a local day) and devices not registered in DEVICE_RETENTION_MS. */
480async function prune(env: Env, now: Date): Promise<void> {
481 await env.DB.batch([
482 env.DB.prepare("DELETE FROM alerts_sent WHERE sent_at < ?1").bind(new Date(now.getTime() - 3 * 86400_000).toISOString()),
483 env.DB.prepare("DELETE FROM devices WHERE last_seen < ?1").bind(new Date(now.getTime() - DEVICE_RETENTION_MS).toISOString()),
484 ]);
416485}
server/src/news.ts +8 −4
@@ -9,10 +9,14 @@ export interface Article {
99
1010export const DIGEST_HOUR = 9;
1111
12/** Whether the device's local time is in the first 10 minutes of the digest hour (the 10-minute cron fires once in it). */
13export function digestDue(now: Date, utcOffsetMinutes: number): boolean {
14 const minutes = (((now.getUTCHours() * 60 + now.getUTCMinutes() + utcOffsetMinutes) % 1440) + 1440) % 1440;
15 return minutes >= DIGEST_HOUR * 60 && minutes < DIGEST_HOUR * 60 + 10;
12/**
13 * UTC offsets in minutes whose local time is in the digest hour, as two half-open ranges within ±14 hours
14 * (either may be empty). The whole hour, so devices one run did not reach get the digest on a later run.
15 */
16export function dueOffsets(now: Date): [[number, number], [number, number]] {
17 const start = DIGEST_HOUR * 60 - now.getUTCHours() * 60 - now.getUTCMinutes();
18 const clip = (lo: number): [number, number] => [Math.max(lo, -840), Math.min(lo + 60, 841)];
19 return [clip(start), clip(start + 1440)];
1620}
1721
1822/** The device's local date, so each device gets one digest per local day. */
server/test/activity.test.ts +17 −1
@@ -1,6 +1,6 @@
11import assert from "node:assert/strict";
22import { test } from "node:test";
3import { activityPush, focusPick, inFocus, needsChannel, sinceNet } from "../src/activity.ts";
3import { activityPush, focusEvery, focusPick, focusPollDue, inFocus, needsChannel, sinceNet } from "../src/activity.ts";
44
55const now = new Date("2026-10-20T12:00:00Z");
66const unix = (iso: string) => Date.parse(iso) / 1000;
@@ -21,6 +21,22 @@ test("overlapping launches take turns, one request per 5-minute tick", () => {
2121 assert.equal(focusPick(ids, new Date("2026-10-20T12:05:00Z")), "b");
2222 assert.equal(focusPick(ids, new Date("2026-10-20T12:10:00Z")), "a");
2323 assert.equal(focusPick(["a"], new Date("2026-10-20T12:05:00Z")), "a");
24 assert.deepEqual([0, 2, 4, 6].map((m) => focusPick(ids, new Date(Date.UTC(2026, 9, 20, 12, m)), 2)), ["a", "b", "a", "b"]);
25});
26
27test("the launch in focus is polled every 5 minutes anonymously and every even minute with a key", () => {
28 for (const keyed of [false, true]) {
29 const polled: number[] = [];
30 for (let m = 0; m < 60; m++) {
31 const at = new Date(Date.UTC(2026, 9, 20, 12, m));
32 const five = m % 5 === 0 && focusPollDue(5, at, keyed);
33 const two = m % 2 === 0 && focusPollDue(2, at, keyed);
34 assert.ok(!(five && two), `both crons poll at minute ${m}`);
35 if (five || two) polled.push(m);
36 }
37 const every = focusEvery(keyed);
38 assert.deepEqual(polled, Array.from({ length: 60 / every }, (_, i) => i * every));
39 }
2440});
2541
2642test("a launch needs a channel within 24 hours of NET until it has an outcome", () => {
server/test/apns.test.ts +41 −1
@@ -1,6 +1,6 @@
11import assert from "node:assert/strict";
22import { test } from "node:test";
3import { broadcast, createChannel, deleteChannel, listChannels, send, type ApnsConfig } from "../src/apns.ts";
3import { broadcast, createChannel, deleteChannel, listChannels, retryable, send, sendAll, type ApnsConfig } from "../src/apns.ts";
44
55async function config(): Promise<ApnsConfig> {
66 const pair = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign"]);
@@ -92,3 +92,43 @@ test("errors report APNs' reason", async () => {
9292 assert.equal(r.reason, "InvalidProviderToken");
9393 assert.deepEqual(r.channels, []);
9494});
95
96test("concurrent sends share one provider token", async () => {
97 const { seen, fetcher } = recorder(() => new Response(null, { status: 200 }));
98 const real = globalThis.fetch;
99 globalThis.fetch = fetcher;
100 try {
101 const c = { ...(await config()), keyId: "SHARED0001" };
102 await Promise.all(Array.from({ length: 6 }, (_, i) => send(c, i.toString(16).padStart(64, "0"), {}, false)));
103 } finally {
104 globalThis.fetch = real;
105 }
106 assert.equal(new Set(seen.map((s) => s.headers.authorization)).size, 1);
107});
108
109test("sendAll keeps order, bounds concurrency and turns network errors into status 0", async () => {
110 let inFlight = 0;
111 let max = 0;
112 const real = globalThis.fetch;
113 globalThis.fetch = (async (url: string) => {
114 inFlight++;
115 max = Math.max(max, inFlight);
116 await new Promise((r) => setTimeout(r, 2));
117 inFlight--;
118 if (url.endsWith("1".padStart(64, "0"))) throw new Error("network");
119 return new Response(null, { status: url.includes("sandbox") ? 410 : 200 });
120 }) as typeof fetch;
121 let results;
122 try {
123 const c = await config();
124 results = await sendAll(c, Array.from({ length: 10 }, (_, i) => ({ token: i.toString(16).padStart(64, "0"), payload: {}, sandbox: i === 2 })), 3);
125 } finally {
126 globalThis.fetch = real;
127 }
128 assert.equal(max, 3);
129 assert.deepEqual(results.map((r) => r.status), [200, 0, 410, 200, 200, 200, 200, 200, 200, 200]);
130});
131
132test("only network errors, 429 and 5xx are worth retrying", () => {
133 assert.deepEqual([0, 200, 400, 403, 410, 429, 500, 503].map(retryable), [true, false, false, false, false, true, true, true]);
134});
server/test/celestrak.test.ts +31 −1
@@ -1,6 +1,6 @@
11import assert from "node:assert/strict";
22import { test } from "node:test";
3import { byDesignator, compose, fitsLaunch, parseSupGP, pick, starlinkTrains, supgpFile, supgpLaunches } from "../src/celestrak.ts";
3import { byDesignator, compose, fetchGroups, fitsLaunch, parseSupGP, pick, retryDue, retryTick, starlinkTrains, supgpFile, supgpLaunches } from "../src/celestrak.ts";
44
55test("keeps only the SGP4 fields", () => {
66 // CelesTrak GP JSON for the ISS, 2026-10-18.
@@ -135,3 +135,33 @@ test("other launches list rocket bodies first, skip debris and stop at eight", (
135135 assert.equal(names[0], "FALCON 9 R/B");
136136 assert.ok(!names.includes("FALCON 9 DEB"));
137137});
138
139test("a failed 2-hourly poll gets one retry, at minute 40 of the same even hour", () => {
140 const at = (iso: string) => new Date(iso);
141 assert.equal(retryTick(at("2026-10-21T02:40:00Z")), true);
142 assert.equal(retryTick(at("2026-10-21T03:40:00Z")), false);
143 assert.equal(retryTick(at("2026-10-21T02:35:00Z")), false);
144 const now = at("2026-10-21T02:40:00Z");
145 assert.equal(retryDue(now, "2026-10-21T00:07:00.000Z", "2026-10-21T02:07:00.000Z"), true);
146 assert.equal(retryDue(now, null, "2026-10-21T02:07:00.000Z"), true);
147 assert.equal(retryDue(now, "2026-10-21T02:07:00.000Z", "2026-10-20T22:07:00.000Z"), false);
148 assert.equal(retryDue(now, "2026-10-20T22:07:00.000Z", "2026-10-21T00:40:00.000Z"), false);
149 assert.equal(retryDue(now, null, null), false);
150 assert.equal(retryDue(at("2026-10-21T02:45:00Z"), null, "2026-10-21T02:07:00.000Z"), false);
151});
152
153test("CelesTrak requests carry a timeout", async () => {
154 const signals: (AbortSignal | null | undefined)[] = [];
155 const real = globalThis.fetch;
156 globalThis.fetch = (async (_url: string, init: RequestInit) => {
157 signals.push(init.signal);
158 return Response.json([]);
159 }) as typeof fetch;
160 try {
161 await fetchGroups();
162 } finally {
163 globalThis.fetch = real;
164 }
165 assert.equal(signals.length, 2);
166 assert.ok(signals.every((s) => s instanceof AbortSignal && !s.aborted));
167});
server/test/news.test.ts +13 −7
@@ -1,13 +1,19 @@
11import assert from "node:assert/strict";
22import { test } from "node:test";
3import { digestDue, digestPayload, localDate, pickHeadlines, type Article } from "../src/news.ts";
3import { digestPayload, dueOffsets, localDate, pickHeadlines, type Article } from "../src/news.ts";
44
5test("digest is due in the first 10 minutes of 09:00 local", () => {
6 const at = (iso: string) => new Date(iso);
7 assert.equal(digestDue(at("2026-10-18T14:00:00Z"), -300), true); // 09:00 CDT
8 assert.equal(digestDue(at("2026-10-18T14:09:59Z"), -300), true);
9 assert.equal(digestDue(at("2026-10-18T14:10:00Z"), -300), false);
10 assert.equal(digestDue(at("2026-10-17T23:30:00Z"), 570), true); // 09:00 ACST, next day
5test("digest is due for the UTC offsets whose local time is in the 09:00 hour", () => {
6 for (let minute = 0; minute < 1440; minute += 5) {
7 const now = new Date(Date.UTC(2026, 9, 18, 0, minute));
8 const ranges = dueOffsets(now);
9 for (let offset = -840; offset <= 840; offset++) {
10 const local = (((minute + offset) % 1440) + 1440) % 1440;
11 const due = ranges.some(([lo, hi]) => offset >= lo && offset < hi);
12 assert.equal(due, local >= 540 && local < 600, `${now.toISOString()} ${offset}`);
13 }
14 }
15 assert.deepEqual(dueOffsets(new Date("2026-10-18T14:00:00Z")), [[-300, -240], [1140, 841]]); // 09:00 CDT
16 assert.deepEqual(dueOffsets(new Date("2026-10-17T23:30:00Z")), [[-840, -810], [570, 630]]); // 09:00 ACST, next day
1117});
1218
1319test("local date follows the offset", () => {
server/test/worker.test.ts added +349
@@ -0,0 +1,349 @@
1import assert from "node:assert/strict";
2import { readdirSync, readFileSync } from "node:fs";
3import { registerHooks } from "node:module";
4import { DatabaseSync, type SQLInputValue } from "node:sqlite";
5import { afterEach, test } from "node:test";
6
7// src/index.ts imports without extensions, which wrangler's bundler resolves.
8registerHooks({
9 resolve(specifier, context, next) {
10 try {
11 return next(specifier, context);
12 } catch (e) {
13 if (specifier.startsWith(".")) return next(`${specifier}.ts`, context);
14 throw e;
15 }
16 },
17});
18const { default: worker } = await import("../src/index.ts");
19
20const FIVE = "*/5 * * * *";
21const TWO = "*/2 * * * *";
22const NEWS = "*/10 * * * *";
23const SATELLITES = "7 */2 * * *";
24
25interface Call {
26 sql: string;
27 params: SQLInputValue[];
28}
29
30/** D1 over node:sqlite with the migrations applied. Each call is one D1 round trip; a batch is one call. */
31function database() {
32 const db = new DatabaseSync(":memory:");
33 const dir = new URL("../migrations/", import.meta.url);
34 for (const f of readdirSync(dir).sort()) db.exec(readFileSync(new URL(f, dir), "utf8"));
35 const calls: Call[] = [];
36 const statement = (sql: string, params: SQLInputValue[] = []) => ({
37 sql,
38 params,
39 bind: (...p: SQLInputValue[]) => statement(sql, p),
40 exec() {
41 const results = db.prepare(sql).all(...params);
42 return { results, success: true, meta: { changes: (db.prepare("SELECT changes() AS n").get() as { n: number }).n } };
43 },
44 async all() {
45 calls.push({ sql, params });
46 return this.exec();
47 },
48 async first() {
49 calls.push({ sql, params });
50 return this.exec().results[0] ?? null;
51 },
52 async run() {
53 calls.push({ sql, params });
54 return this.exec();
55 },
56 });
57 const DB = {
58 prepare: (sql: string) => statement(sql),
59 async batch(statements: ReturnType<typeof statement>[]) {
60 calls.push({ sql: "batch", params: [] });
61 db.exec("BEGIN");
62 try {
63 const out = statements.map((s) => s.exec());
64 db.exec("COMMIT");
65 return out;
66 } catch (e) {
67 db.exec("ROLLBACK");
68 throw e;
69 }
70 },
71 };
72 return { db, DB, calls };
73}
74
75async function apnsKey(): Promise<string> {
76 const pair = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign"]);
77 const der = new Uint8Array(await crypto.subtle.exportKey("pkcs8", pair.privateKey));
78 return `-----BEGIN PRIVATE KEY-----\n${btoa(String.fromCharCode(...der))}\n-----END PRIVATE KEY-----\n`;
79}
80
81async function setup(vars: Record<string, string> = {}) {
82 const { db, DB, calls } = database();
83 const env = { DB, APNS_KEY_ID: "KEY1234567", APNS_TEAM_ID: "TEAM123456", APNS_TOPIC: "sh.krz.moonrise", APNS_KEY: await apnsKey(), ...vars };
84 return { db, env, calls };
85}
86
87const real = globalThis.fetch;
88afterEach(() => {
89 globalThis.fetch = real;
90});
91
92type Handler = (url: URL, init: RequestInit) => Response | Promise<Response>;
93
94/** Answers by host; anything else gets 503. Returns the hosts requested, in order. */
95function network(handlers: Record<string, Handler>): string[] {
96 const hosts: string[] = [];
97 globalThis.fetch = (async (input: string, init: RequestInit = {}) => {
98 const url = new URL(String(input));
99 hosts.push(url.hostname);
100 const h = handlers[url.hostname];
101 return h ? h(url, init) : new Response("unavailable", { status: 503 });
102 }) as typeof fetch;
103 return hosts;
104}
105
106/** APNs alert sends: status by device token (default 200); `fail` throws, as fetch does past the subrequest limit. */
107function apns(status: Record<string, number> = {}) {
108 const state = { sent: [] as string[], broadcasts: 0, inFlight: 0, maxInFlight: 0, fail: (_n: number) => false };
109 const handler: Handler = async (url) => {
110 if (url.pathname.startsWith("/4/broadcasts/")) {
111 state.broadcasts++;
112 return new Response(null, { status: 200 });
113 }
114 if (state.fail(state.sent.length)) throw new Error("Too many subrequests.");
115 const token = url.pathname.split("/").at(-1)!;
116 state.sent.push(token);
117 state.inFlight++;
118 state.maxInFlight = Math.max(state.maxInFlight, state.inFlight);
119 await new Promise((r) => setTimeout(r, 2));
120 state.inFlight--;
121 const s = status[token] ?? 200;
122 return new Response(s === 200 ? null : JSON.stringify({ reason: "x" }), { status: s });
123 };
124 return { state, handlers: { "api.push.apple.com": handler, "api.sandbox.push.apple.com": handler } };
125}
126
127function swpc(kp: number): Record<string, Handler> {
128 return {
129 "services.swpc.noaa.gov": (url) =>
130 Response.json(url.pathname.includes("planetary_k_index_1m") ? [{ time_tag: "2026-10-20T22:00:00", estimated_kp: kp }] : []),
131 };
132}
133
134async function run(env: object, cron: string, iso: string): Promise<void> {
135 const pending: Promise<unknown>[] = [];
136 await worker.scheduled({ cron, scheduledTime: Date.parse(iso) } as never, env as never, { waitUntil: (p: Promise<unknown>) => pending.push(p) } as never);
137 await Promise.all(pending);
138}
139
140const token = (i: number) => i.toString(16).padStart(64, "0");
141
142function device(db: DatabaseSync, i: number, d: { band?: number; offset?: number; aurora?: number; news?: number; lastSeen?: string } = {}) {
143 db.prepare("INSERT INTO devices (token, environment, band, utc_offset_minutes, aurora, news, last_seen) VALUES (?, 'production', ?, ?, ?, ?, ?)")
144 .run(token(i), d.band ?? 55, d.offset ?? 0, d.aurora ?? 1, d.news ?? 0, d.lastSeen ?? "2026-10-20T00:00:00.000Z");
145}
146
147const count = (db: DatabaseSync, sql: string) => (db.prepare(sql).get() as { n: number }).n;
148
149test("a failed CelesTrak poll is tried once more 33 minutes later, from the 5-minute cron", async () => {
150 const { db, env } = await setup({ APNS_KEY: "" });
151 let status = 522;
152 const hosts = network({ "celestrak.org": () => new Response("[]", { status }) });
153 const requests = async (cron: string, iso: string) => {
154 const before = hosts.filter((h) => h === "celestrak.org").length;
155 await run(env, cron, iso);
156 return hosts.filter((h) => h === "celestrak.org").length - before;
157 };
158 assert.equal(await requests(SATELLITES, "2026-10-21T02:07:00Z"), 1);
159 assert.equal(await requests(FIVE, "2026-10-21T02:35:00Z"), 0);
160 assert.equal(await requests(FIVE, "2026-10-21T02:40:00Z"), 1);
161 assert.equal(await requests(FIVE, "2026-10-21T02:45:00Z"), 0);
162 assert.equal(await requests(FIVE, "2026-10-21T03:40:00Z"), 0);
163 assert.equal(await requests(FIVE, "2026-10-21T04:40:00Z"), 0);
164
165 assert.equal(await requests(SATELLITES, "2026-10-21T06:07:00Z"), 1);
166 status = 200;
167 assert.equal(await requests(FIVE, "2026-10-21T06:40:00Z"), 2);
168 assert.equal(count(db, "SELECT count(*) AS n FROM feed_snapshots WHERE feed = 'celestrak' AND ok = 1 AND fetched_at = '2026-10-21T06:40:00.000Z'"), 1);
169 assert.equal(await requests(SATELLITES, "2026-10-21T08:07:00Z"), 2);
170 assert.equal(await requests(FIVE, "2026-10-21T08:40:00Z"), 0);
171});
172
173test("aurora alerts go out in bounded slices and are recorded per device once answered", async () => {
174 const { db, env, calls } = await setup();
175 for (let i = 0; i < 30; i++) device(db, i);
176 device(db, 30, { offset: 720 }); // 10:05 local: not night
177 const push = apns({ [token(3)]: 503, [token(4)]: 410, [token(5)]: 400 });
178 const hosts = network({ ...swpc(6), ...push.handlers });
179
180 await run(env, FIVE, "2026-10-20T22:05:00Z");
181 assert.equal(push.state.sent.length, 20);
182 assert.ok(push.state.maxInFlight <= 6, `max in flight ${push.state.maxInFlight}`);
183 assert.ok(hosts.length + calls.length <= 50, `${hosts.length} fetches + ${calls.length} D1 calls`);
184 assert.equal(count(db, "SELECT count(*) AS n FROM alerts_sent WHERE kind = 'aurora'"), 18);
185 assert.equal(count(db, `SELECT count(*) AS n FROM devices WHERE token = '${token(4)}'`), 0);
186
187 push.state.sent = [];
188 await run(env, FIVE, "2026-10-20T22:10:00Z");
189 assert.deepEqual(push.state.sent.sort(), [3, ...Array.from({ length: 10 }, (_, i) => 20 + i)].map(token).sort());
190
191 push.state.sent = [];
192 await run(env, FIVE, "2026-10-20T22:15:00Z");
193 assert.deepEqual(push.state.sent, [token(3)]);
194});
195
196test("an aurora run cut short leaves the remaining devices for the next run", async () => {
197 const { db, env } = await setup();
198 for (let i = 0; i < 5; i++) device(db, i);
199 const push = apns();
200 push.state.fail = (n) => n >= 2;
201 network({ ...swpc(6), ...push.handlers });
202
203 await run(env, FIVE, "2026-10-20T22:05:00Z");
204 assert.equal(count(db, "SELECT count(*) AS n FROM alerts_sent WHERE kind = 'aurora'"), 2);
205
206 push.state.fail = () => false;
207 const first = push.state.sent;
208 push.state.sent = [];
209 await run(env, FIVE, "2026-10-20T22:10:00Z");
210 assert.equal(push.state.sent.length, 3);
211 assert.ok(push.state.sent.every((t) => !first.includes(t)));
212});
213
214test("news digests go out in slices during the local 09:00 hour, once per local day", async () => {
215 const { db, env, calls } = await setup();
216 for (let i = 0; i < 25; i++) device(db, i, { offset: -300, aurora: 0, news: 1 });
217 device(db, 25, { offset: 330, aurora: 0, news: 1 });
218 const push = apns();
219 const articles = [{ id: 1, title: "t1", news_site: "ESA", published_at: "2026-10-20T13:00:00Z" }];
220 const hosts = network({ ...push.handlers, "api.spaceflightnewsapi.net": () => Response.json({ results: articles }) });
221 const snapi = () => hosts.filter((h) => h === "api.spaceflightnewsapi.net").length;
222
223 await run(env, NEWS, "2026-10-20T14:00:00Z");
224 assert.equal(push.state.sent.length, 20);
225 await run(env, NEWS, "2026-10-20T14:10:00Z");
226 assert.equal(push.state.sent.length, 25);
227 assert.equal(new Set(push.state.sent).size, 25);
228 await run(env, NEWS, "2026-10-20T14:20:00Z");
229 assert.equal(push.state.sent.length, 25);
230 assert.equal(snapi(), 2);
231 assert.equal(count(db, "SELECT count(*) AS n FROM alerts_sent WHERE kind = 'news' AND event LIKE '%:2026-10-20'"), 25);
232
233 const q = calls.find((c) => c.sql.includes("news = 1"))!;
234 const plan = db.prepare(`EXPLAIN QUERY PLAN ${q.sql}`).all(...q.params).map((r) => String(r.detail)).join("\n");
235 assert.match(plan, /SEARCH d USING INDEX devices_news \(news=\? AND utc_offset_minutes>\? AND utc_offset_minutes<\?\)/);
236});
237
238test("a daily prune removes alert keys older than 3 days and devices not seen in 180 days", async () => {
239 const { db, env } = await setup({ APNS_KEY: "" });
240 const sent = db.prepare("INSERT INTO alerts_sent (kind, band, event, sent_at) VALUES (?, 0, ?, ?)");
241 for (const kind of ["aurora", "news", "test"]) {
242 sent.run(kind, "old", "2026-10-17T23:59:00.000Z");
243 sent.run(kind, "new", "2026-10-18T00:01:00.000Z");
244 }
245 device(db, 1, { lastSeen: "2026-04-23T23:59:00.000Z" });
246 device(db, 2, { lastSeen: "2026-04-24T00:01:00.000Z" });
247 network({});
248
249 await run(env, NEWS, "2026-10-20T23:50:00Z");
250 assert.equal(count(db, "SELECT count(*) AS n FROM alerts_sent"), 6);
251 await run(env, NEWS, "2026-10-21T00:00:00Z");
252 assert.deepEqual(db.prepare("SELECT DISTINCT event FROM alerts_sent").all().map((r) => r.event), ["new"]);
253 assert.deepEqual(db.prepare("SELECT token FROM devices").all().map((r) => r.token), [token(2)]);
254});
255
256test("GET /v1/launches reads everything in one D1 batch", async () => {
257 const { db, env, calls } = await setup();
258 const launch = db.prepare(
259 "INSERT INTO launches (id, name, net, status, status_name, provider, rocket, pad, location, last_updated) VALUES (?, ?, ?, 'Go', 'Go for Launch', 'SpaceX', 'Falcon 9', 'SLC-40', 'Cape', '2026-10-01T00:00:00Z')",
260 );
261 const day = (n: number) => new Date(Date.now() + n * 86400_000).toISOString();
262 launch.run("up", "Upcoming", day(1));
263 launch.run("past", "Past", day(-2));
264 db.exec(`INSERT INTO feed_snapshots (feed, fetched_at, ok, body) VALUES ('ll2', '2026-10-20T11:50:00.000Z', 1, NULL),
265 ('launch-elements', '2026-10-20T10:07:00.000Z', 1, '{"up":{"source":"supgp","elements":[{"OBJECT_NAME":"x"}]}}');
266 INSERT INTO launch_channels (channel_id, environment, launch_id, net, status, created_at) VALUES ('ch1', 'production', 'up', 'x', 'Go', 'x')`);
267
268 const res = await worker.fetch(new Request("https://moonrise.test/v1/launches"), env as never);
269 assert.deepEqual(calls.map((c) => c.sql), ["batch"]);
270 const body = await res.json();
271 assert.equal(res.headers.get("cache-control"), "public, max-age=300");
272 assert.equal(body.fetchedAt, "2026-10-20T11:50:00.000Z");
273 assert.deepEqual(body.launches.map((l: { id: string }) => l.id), ["up"]);
274 assert.deepEqual(body.recent.map((l: { id: string }) => l.id), ["past"]);
275 assert.equal(body.launches[0].channelId, "ch1");
276 assert.equal(body.launches[0].elementsSource, "supgp");
277 assert.deepEqual(body.launches[0].elements, [{ OBJECT_NAME: "x" }]);
278 assert.equal(body.recent[0].elementsSource, null);
279
280 const sandbox = await (await worker.fetch(new Request("https://moonrise.test/v1/launches?environment=sandbox"), env as never)).json();
281 assert.equal(sandbox.launches[0].channelId, null);
282});
283
284const ID = "3b430f81-0ff1-4d85-8a1a-cef0de326198";
285const raw = (net: string, status: string, designator: string | null = null) => ({
286 id: ID, name: "Falcon 9 Block 5 | Bandwagon 5", net, window_start: net, window_end: net, last_updated: "2026-10-17T20:00:00Z", launch_designator: designator,
287 status: { name: status, abbrev: status }, launch_service_provider: { name: "SpaceX" }, rocket: { configuration: { name: "Falcon 9", full_name: "Falcon 9 Block 5" } },
288 mission: { name: "Bandwagon 5", type: "Dedicated Rideshare", description: "Rideshare.", orbit: { abbrev: "LEO" } },
289 pad: { name: "Space Launch Complex 40", latitude: "28.56", longitude: "-80.57", location: { name: "Cape Canaveral SFS, FL, USA" } },
290});
291
292for (const keyed of [true, false]) {
293 test(`the launch in focus is polled every ${keyed ? 2 : 5} minutes ${keyed ? "with" : "without"} an LL2 key`, async () => {
294 const { db, env, calls } = await setup(keyed ? { LL2_API_KEY: "k" } : {});
295 const net = "2026-10-20T12:30:00Z";
296 db.prepare("INSERT INTO launches (id, name, net, status, status_name, provider, rocket, pad, location, last_updated) VALUES (?, 'x', ?, 'Go', 'Go', 'SpaceX', 'Falcon 9', 'SLC-40', 'Cape', 'x')").run(ID, net);
297 for (const e of ["sandbox", "production"])
298 db.prepare("INSERT INTO launch_channels (channel_id, environment, launch_id, net, status, created_at) VALUES (?, ?, ?, ?, 'Go', 'x')").run(`ch-${e}`, e, ID, net);
299 let status = "Go";
300 const auth: (string | undefined)[] = [];
301 const push = apns();
302 const hosts = network({
303 ...swpc(0),
304 ...push.handlers,
305 "ll.thespacedevs.com": (url, init) => {
306 auth.push((init.headers as Record<string, string>).authorization);
307 return Response.json(url.pathname.endsWith(`/launches/${ID}/`) ? raw(net, status) : { results: [] });
308 },
309 });
310
311 for (let m = 0; m < 60; m++) {
312 const iso = new Date(Date.parse("2026-10-20T11:30:00Z") + m * 60_000).toISOString();
313 if (m === 12) status = "Hold";
314 const before = calls.length;
315 if (m % 2 === 0) await run(env, TWO, iso);
316 if (!keyed) assert.equal(calls.length, before, "the 2-minute cron does nothing without a key");
317 if (m % 5 === 0) await run(env, FIVE, iso);
318 if (m === 12) assert.equal(push.state.broadcasts, keyed ? 2 : 0);
319 }
320 assert.equal(hosts.filter((h) => h === "ll.thespacedevs.com").length, keyed ? 30 : 12);
321 assert.ok(auth.every((a) => a === (keyed ? "Token k" : undefined)));
322 assert.equal(push.state.broadcasts, 2);
323 });
324}
325
326test("a list poll leaves unchanged launches alone; a tick without a poll runs the near query once", async () => {
327 const { db, env, calls } = await setup();
328 db.exec(`CREATE TEMP TABLE writes (id TEXT);
329 CREATE TEMP TRIGGER launch_update AFTER UPDATE ON launches BEGIN INSERT INTO writes VALUES (NEW.id); END`);
330 let launch = raw("2026-10-25T12:00:00Z", "Go");
331 network({ "ll.thespacedevs.com": () => Response.json({ results: [launch] }) });
332 const near = () => calls.filter((c) => /^SELECT id, net, status FROM launches WHERE net >= /.test(c.sql)).length;
333
334 await run(env, FIVE, "2026-10-20T10:10:00Z");
335 const polled = near();
336 await run(env, FIVE, "2026-10-20T10:15:00Z");
337 assert.equal(near() - polled, 1);
338 await run(env, FIVE, "2026-10-20T10:20:00Z");
339 assert.equal(count(db, "SELECT count(*) AS n FROM writes"), 0);
340
341 launch = raw("2026-10-25T12:00:00Z", "TBC");
342 await run(env, FIVE, "2026-10-20T10:30:00Z");
343 launch = raw("2026-10-25T12:00:00Z", "TBC", "2026-232");
344 await run(env, FIVE, "2026-10-20T10:40:00Z");
345 launch = raw("2026-10-25T12:00:00Z", "TBC");
346 await run(env, FIVE, "2026-10-20T10:50:00Z");
347 assert.equal(count(db, "SELECT count(*) AS n FROM writes"), 2);
348 assert.deepEqual({ ...db.prepare("SELECT status, launch_designator FROM launches").get() }, { status: "TBC", launch_designator: "2026-232" });
349});
server/wrangler.jsonc +1 −1
@@ -2,7 +2,7 @@
22 "name": "moonrise-server",
33 "main": "src/index.ts",
44 "compatibility_date": "2026-10-01",
5 "triggers": { "crons": ["*/5 * * * *", "*/10 * * * *", "7 */2 * * *"] },
5 "triggers": { "crons": ["*/5 * * * *", "*/2 * * * *", "*/10 * * * *", "7 */2 * * *"] },
66 "d1_databases": [
77 {
88 "binding": "DB",