Commit a0928c6710
Unsigned
Layout: unified · split
server/README.org +3
| @@ -32,6 +32,9 @@ so anonymous requests from Cloudflare often get HTTP 429. With an API key: | |||
| 32 | wrangler secret put LL2_API_KEY | 32 | wrangler secret put LL2_API_KEY |
| 33 | #+end_src | 33 | #+end_src |
| 34 | 34 | ||
| 35 | With 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 | |||
| 35 | * launch Live Activity channels | 38 | * launch Live Activity channels |
| 36 | Launch Live Activities get status and NET changes over APNs broadcast | 39 | Launch Live Activities get status and NET changes over APNs broadcast |
| 37 | channels, one per launch and APNs environment, handed out a day before NET | 40 | channels, 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. | ||
| 2 | CREATE INDEX devices_news ON devices (news, utc_offset_minutes); | ||
server/src/activity.ts +16 −4
| @@ -2,7 +2,7 @@ | |||
| 2 | // so the server never learns who follows a launch. | 2 | // so the server never learns who follows a launch. |
| 3 | 3 | ||
| 4 | const MINUTE = 60_000; | 4 | const 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. */ |
| 6 | const FOCUS_BEFORE = 60 * MINUTE; | 6 | const FOCUS_BEFORE = 60 * MINUTE; |
| 7 | const FOCUS_AFTER = 15 * MINUTE; | 7 | const FOCUS_AFTER = 15 * MINUTE; |
| 8 | /** Launch Library 2 status abbreviations that end the activity. */ | 8 | /** Launch Library 2 status abbreviations that end the activity. */ |
| @@ -31,9 +31,21 @@ export function inFocus(l: ActivityState, now: Date): boolean { | |||
| 31 | return !OUTCOMES.includes(l.status) && t - FOCUS_BEFORE <= now.getTime() && now.getTime() <= t + FOCUS_AFTER; | 31 | return !OUTCOMES.includes(l.status) && t - FOCUS_BEFORE <= now.getTime() && now.getTime() <= t + FOCUS_AFTER; |
| 32 | } | 32 | } |
| 33 | 33 | ||
| 34 | /** One launch per 5-minute tick; launches in focus at the same time take turns. */ | 34 | /** Minutes between polls of the launch in focus: 5 anonymously (15 requests/hour), 2 with a Launch Library 2 key. */ |
| 35 | export function focusPick(ids: string[], now: Date): string { | 35 | export const focusEvery = (keyed: boolean) => (keyed ? 2 : 5); |
| 36 | return ids[Math.floor(now.getTime() / (5 * MINUTE)) % ids.length]; | 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 | */ | ||
| 41 | export 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. */ | ||
| 47 | export function focusPick(ids: string[], now: Date, every = 5): string { | ||
| 48 | return ids[Math.floor(now.getTime() / (every * MINUTE)) % ids.length]; | ||
| 37 | } | 49 | } |
| 38 | 50 | ||
| 39 | /** Channels are handed out a day ahead, so a follow at any time before launch can subscribe. */ | 51 | /** 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 | |||
| 41 | return `${input}.${base64url(new Uint8Array(sig))}`; | 41 | return `${input}.${base64url(new Uint8Array(sig))}`; |
| 42 | } | 42 | } |
| 43 | 43 | ||
| 44 | /** Apple accepts a token for up to 60 minutes and rejects refreshes more often than every 20. */ | 44 | /** |
| 45 | let cached: { token: string; issuedAt: number; keyId: string } | null = null; | 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 | */ | ||
| 48 | let cached: { token: Promise<string>; issuedAt: number; keyId: string } | null = null; | ||
| 46 | 49 | ||
| 47 | async function token(config: ApnsConfig): Promise<string> { | 50 | function token(config: ApnsConfig): Promise<string> { |
| 48 | const now = Math.floor(Date.now() / 1000); | 51 | const now = Math.floor(Date.now() / 1000); |
| 49 | if (cached && cached.keyId === config.keyId && now - cached.issuedAt < 50 * 60) return cached.token; | 52 | 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)); |
| 51 | cached = { token: t, issuedAt: now, keyId: config.keyId }; | 54 | cached = { token: t, issuedAt: now, keyId: config.keyId }; |
| 55 | t.catch(() => { | ||
| 56 | if (cached?.token === t) cached = null; | ||
| 57 | }); | ||
| 52 | return t; | 58 | return t; |
| 53 | } | 59 | } |
| 54 | 60 | ||
| @@ -68,6 +74,23 @@ export async function send(config: ApnsConfig, deviceToken: string, payload: unk | |||
| 68 | return result(res, "apns-id"); | 74 | return result(res, "apns-id"); |
| 69 | } | 75 | } |
| 70 | 76 | ||
| 77 | /** `send` to each device, at most `concurrency` at a time. Results are in input order; a network error is status 0. */ | ||
| 78 | export 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. */ | ||
| 92 | export const retryable = (status: number) => status === 0 || status === 429 || status >= 500; | ||
| 93 | |||
| 71 | async function result(res: Response, idHeader: string): Promise<ApnsResult> { | 94 | async function result(res: Response, idHeader: string): Promise<ApnsResult> { |
| 72 | let reason: string | null = null; | 95 | let reason: string | null = null; |
| 73 | if (!res.ok) { | 96 | if (!res.ok) { |
server/src/aurora.ts +1 −1
| @@ -34,7 +34,7 @@ export function isNight(now: Date, utcOffsetMinutes: number): boolean { | |||
| 34 | return hour >= 20 || hour < 4; | 34 | return hour >= 20 || hour < 4; |
| 35 | } | 35 | } |
| 36 | 36 | ||
| 37 | /** One alert per band per 12-hour UTC window. */ | 37 | /** One alert per device per 12-hour UTC window. */ |
| 38 | export function eventKey(now: Date): string { | 38 | export function eventKey(now: Date): string { |
| 39 | const d = now.toISOString().slice(0, 10); | 39 | const d = now.toISOString().slice(0, 10); |
| 40 | return `${d}${now.getUTCHours() < 12 ? "a" : "b"}`; | 40 | return `${d}${now.getUTCHours() < 12 ? "a" : "b"}`; |
server/src/celestrak.ts +14 −2
| @@ -1,5 +1,6 @@ | |||
| 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 | 4 | ||
| 4 | /** ISS, Tiangong (CSS Tianhe) and Hubble; all three are in the visual group. */ | 5 | /** ISS, Tiangong (CSS Tianhe) and Hubble; all three are in the visual group. */ |
| 5 | export const FEATURED = [25544, 48274, 20580]; | 6 | export const FEATURED = [25544, 48274, 20580]; |
| @@ -154,10 +155,21 @@ export function compose(visual: Row[], recent: Row[], launches: LaunchRef[], sup | |||
| 154 | return { satellites: [...pick(visual), ...starlinkTrains(groups)], launches: out }; | 155 | return { satellites: [...pick(visual), ...starlinkTrains(groups)], launches: out }; |
| 155 | } | 156 | } |
| 156 | 157 | ||
| 158 | /** The 5-minute tick 33 minutes after each 2-hourly poll, which runs at minute 7 of even UTC hours. */ | ||
| 159 | export 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. */ | ||
| 162 | export 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 | |||
| 157 | const HEADERS = { "user-agent": "moonrise-server (sh.krz.moonrise)" }; | 168 | const HEADERS = { "user-agent": "moonrise-server (sh.krz.moonrise)" }; |
| 169 | const TIMEOUT_MS = 10_000; | ||
| 158 | 170 | ||
| 159 | async function group(name: string): Promise<Row[]> { | 171 | async 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) }); |
| 161 | if (res.status !== 200) throw new Error(`CelesTrak ${res.status} for ${name}`); | 173 | if (res.status !== 200) throw new Error(`CelesTrak ${res.status} for ${name}`); |
| 162 | return (await res.json()) as Row[]; | 174 | return (await res.json()) as Row[]; |
| 163 | } | 175 | } |
| @@ -171,7 +183,7 @@ export async function fetchGroups(): Promise<{ visual: Row[]; recent: Row[] }> { | |||
| 171 | 183 | ||
| 172 | /** One SupGP file; throws on a non-200 so the caller stops. */ | 184 | /** One SupGP file; throws on a non-200 so the caller stops. */ |
| 173 | export async function fetchSupGP(file: string): Promise<Row[]> { | 185 | export 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) }); |
| 175 | if (res.status !== 200) throw new Error(`CelesTrak SupGP ${res.status} for ${file}`); | 187 | if (res.status !== 200) throw new Error(`CelesTrak SupGP ${res.status} for ${file}`); |
| 176 | return parseSupGP(await res.text()); | 188 | return parseSupGP(await res.text()); |
| 177 | } | 189 | } |
server/src/index.ts +139 −70
| @@ -1,10 +1,10 @@ | |||
| 1 | import { activityPush, focusPick, inFocus, needsChannel, sinceNet } from "./activity"; | 1 | import { activityPush, focusEvery, focusPick, focusPollDue, inFocus, needsChannel, sinceNet, type ActivityState } from "./activity"; |
| 2 | import { broadcast, createChannel, deleteChannel, send, type ApnsConfig } from "./apns"; | 2 | import { broadcast, createChannel, deleteChannel, retryable, send, sendAll, type ApnsConfig } from "./apns"; |
| 3 | import { actionableKp, alertBands, eventKey, isNight } from "./aurora"; | 3 | import { actionableKp, alertBands, eventKey, isNight } from "./aurora"; |
| 4 | import { compose, fetchGroups, fetchSupGP, fitsLaunch, supgpFile, supgpLaunches, type LaunchElements, type LaunchRef, type Row } from "./celestrak"; | 4 | import { compose, fetchGroups, fetchSupGP, fitsLaunch, retryDue, retryTick, supgpFile, supgpLaunches, type LaunchElements, type LaunchRef, type Row } from "./celestrak"; |
| 5 | import { activeEvent, fetchTrajectory, STEP_MINUTES } from "./live"; | 5 | import { activeEvent, fetchTrajectory, STEP_MINUTES } from "./live"; |
| 6 | import { fetchLaunch, fetchLaunches, PREVIOUS_URL, UPCOMING_URL, type Launch } from "./ll2"; | 6 | import { fetchLaunch, fetchLaunches, PREVIOUS_URL, UPCOMING_URL, type Launch } from "./ll2"; |
| 7 | import { digestDue, digestPayload, fetchLatest, localDate, pickHeadlines } from "./news"; | 7 | import { digestPayload, dueOffsets, fetchLatest, localDate, pickHeadlines } from "./news"; |
| 8 | import { PRIVACY_HTML } from "./privacy"; | 8 | import { PRIVACY_HTML } from "./privacy"; |
| 9 | import { fetchSpaceWeather, next24h, type SpaceWeather } from "./swpc"; | 9 | import { fetchSpaceWeather, next24h, type SpaceWeather } from "./swpc"; |
| 10 | 10 | ||
| @@ -31,8 +31,17 @@ interface DeviceRequest { | |||
| 31 | 31 | ||
| 32 | const NEWS_CRON = "*/10 * * * *"; | 32 | const NEWS_CRON = "*/10 * * * *"; |
| 33 | const SATELLITE_CRON = "7 */2 * * *"; | 33 | const SATELLITE_CRON = "7 */2 * * *"; |
| 34 | const FOCUS_CRON = "*/2 * * * *"; | ||
| 34 | /** Launches are kept this long after NET, so a launch page and its first pass outlive liftoff. */ | 35 | /** Launches are kept this long after NET, so a launch page and its first pass outlive liftoff. */ |
| 35 | const RETENTION_MS = 14 * 86400_000; | 36 | const RETENTION_MS = 14 * 86400_000; |
| 37 | /** Devices are dropped after this long without registering; the app registers whenever iOS hands it a token. */ | ||
| 38 | const 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 | */ | ||
| 43 | const PUSH_SLICE = 20; | ||
| 44 | const PUSH_CONCURRENCY = 6; | ||
| 36 | 45 | ||
| 37 | const json = (body: unknown, status = 200, maxAge?: number) => | 46 | const json = (body: unknown, status = 200, maxAge?: number) => |
| 38 | Response.json(body, { status, headers: maxAge && status === 200 ? { "cache-control": `public, max-age=${maxAge}` } : {} }); | 47 | Response.json(body, { status, headers: maxAge && status === 200 ? { "cache-control": `public, max-age=${maxAge}` } : {} }); |
| @@ -102,9 +111,12 @@ export default { | |||
| 102 | 111 | ||
| 103 | async scheduled(controller: ScheduledController, env: Env, ctx: ExecutionContext): Promise<void> { | 112 | async scheduled(controller: ScheduledController, env: Env, ctx: ExecutionContext): Promise<void> { |
| 104 | const now = new Date(controller.scheduledTime); | 113 | const now = new Date(controller.scheduledTime); |
| 105 | if (controller.cron === NEWS_CRON) ctx.waitUntil(sendNewsDigests(env, now)); | 114 | if (controller.cron === NEWS_CRON) { |
| 106 | else if (controller.cron === SATELLITE_CRON) ctx.waitUntil(pollSatellites(env, now)); | 115 | ctx.waitUntil(sendNewsDigests(env, now)); |
| 107 | else ctx.waitUntil(Promise.all([pollSpaceWeather(env, now), launchTick(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)])); | ||
| 108 | }, | 120 | }, |
| 109 | } satisfies ExportedHandler<Env>; | 121 | } satisfies ExportedHandler<Env>; |
| 110 | 122 | ||
| @@ -158,14 +170,15 @@ async function live(env: Env, url: URL, now: Date): Promise<Response> { | |||
| 158 | /** `?environment=sandbox` gives Debug builds the channels of the APNs sandbox. */ | 170 | /** `?environment=sandbox` gives Debug builds the channels of the APNs sandbox. */ |
| 159 | async function launches(env: Env, url: URL, now: Date): Promise<Response> { | 171 | async function launches(env: Env, url: URL, now: Date): Promise<Response> { |
| 160 | const since = new Date(now.getTime() - 6 * 3600_000).toISOString(); | 172 | 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>>(); | 173 | const [rows, recent, fetched, els, ch] = await env.DB.batch<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") | 174 | env.DB.prepare("SELECT * FROM launches WHERE net >= ?1 ORDER BY net LIMIT 20").bind(since), |
| 163 | .bind(since, new Date(now.getTime() - RETENTION_MS).toISOString()).all<Record<string, unknown>>(); | 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()), |
| 164 | const fetched = await env.DB.prepare("SELECT fetched_at FROM feed_snapshots WHERE feed = 'll2' AND ok = 1").first<{ fetched_at: string }>(); | 176 | env.DB.prepare("SELECT fetched_at FROM feed_snapshots WHERE feed = 'll2' AND ok = 1"), |
| 165 | const els = await env.DB.prepare("SELECT body FROM feed_snapshots WHERE feed = 'launch-elements' AND ok = 1").first<{ body: string }>(); | 177 | env.DB.prepare("SELECT body FROM feed_snapshots WHERE feed = 'launch-elements' AND ok = 1"), |
| 166 | const elements: Record<string, LaunchElements> = els ? JSON.parse(els.body) : {}; | 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") |
| 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") | 179 | .bind(url.searchParams.get("environment") === "sandbox" ? "sandbox" : "production"), |
| 168 | .bind(url.searchParams.get("environment") === "sandbox" ? "sandbox" : "production").all<{ launch_id: string; channel_id: string }>(); | 180 | ]); |
| 181 | const elements: Record<string, LaunchElements> = els.results.length ? JSON.parse(String(els.results[0].body)) : {}; | ||
| 169 | const channels = Object.fromEntries(ch.results.map((c) => [c.launch_id, c.channel_id])); | 182 | const channels = Object.fromEntries(ch.results.map((c) => [c.launch_id, c.channel_id])); |
| 170 | const shape = (r: Record<string, unknown>) => ({ | 183 | const shape = (r: Record<string, unknown>) => ({ |
| 171 | id: r.id, name: r.name, net: r.net, windowStart: r.window_start, windowEnd: r.window_end, | 184 | 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> { | |||
| 176 | channelId: channels[String(r.id)] ?? null, | 189 | channelId: channels[String(r.id)] ?? null, |
| 177 | }); | 190 | }); |
| 178 | return json({ | 191 | return json({ |
| 179 | fetchedAt: fetched?.fetched_at ?? null, | 192 | fetchedAt: fetched.results[0]?.fetched_at ?? null, |
| 180 | launches: rows.results.map(shape), | 193 | launches: rows.results.map(shape), |
| 181 | recent: recent.results.map(shape), | 194 | recent: recent.results.map(shape), |
| 182 | }, 200, MAX_AGE.launches); | 195 | }, 200, MAX_AGE.launches); |
| 183 | } | 196 | } |
| 184 | 197 | ||
| 198 | type Near = ActivityState & { id: string }; | ||
| 199 | |||
| 200 | const 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 | |||
| 185 | /** | 203 | /** |
| 186 | * Launch Library 2 within the anonymous 15 requests per hour. Every 5 minutes: the launch in focus (T−60 to T+15) | 204 | * Launch Library 2: the launch in focus (T−60 to T+15) on its own, with the list paused; otherwise the upcoming list |
| 187 | * on its own, with the list paused; otherwise the upcoming list every 10 minutes and previous launches hourly. | 205 | * every 10 minutes and previous launches hourly. Anonymous (15 requests per hour), the launch in focus every 5 minutes: |
| 188 | * At most 12 + 1 requests in any hour. | 206 | * at most 12 + 1 requests in any hour. With a key (45 per hour), every 2 minutes with focusTick: at most 30 + 1. |
| 189 | */ | 207 | */ |
| 190 | async function launchTick(env: Env, now: Date): Promise<void> { | 208 | async 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 }>(); | 209 | const near = await nearLaunches(env, now); |
| 192 | const focus = near.results.filter((l) => inFocus(l, now)).map((l) => l.id); | 210 | const focus = near.filter((l) => inFocus(l, now)).map((l) => l.id); |
| 193 | if (focus.length) await pollLaunch(env, focusPick(focus, now), now); | 211 | const keyed = Boolean(env.LL2_API_KEY); |
| 194 | else if (now.getUTCMinutes() % 10 === 0) await pollLaunches(env, now); | 212 | const pollFocus = focus.length > 0 && focusPollDue(5, now, keyed); |
| 195 | if (env.APNS_KEY) await launchChannels(env, now); | 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. */ | ||
| 221 | async 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); | ||
| 196 | } | 227 | } |
| 197 | 228 | ||
| 198 | async function pollLaunch(env: Env, id: string, now: Date): Promise<void> { | 229 | async function pollLaunch(env: Env, id: string, now: Date): Promise<void> { |
| @@ -235,7 +266,9 @@ function upsertLaunches(env: Env, list: Launch[]): D1PreparedStatement[] { | |||
| 235 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19) | 266 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19) |
| 236 | 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, | 267 | 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, |
| 237 | mission = ?10, mission_type = ?11, mission_description = ?12, orbit = ?13, pad = ?14, location = ?15, pad_latitude = ?16, pad_longitude = ?17, last_updated = ?18, | 268 | 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))`, | ||
| 239 | ); | 272 | ); |
| 240 | 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)); | 273 | 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)); |
| 241 | } | 274 | } |
| @@ -245,15 +278,14 @@ function upsertLaunches(env: Env, list: Launch[]): D1PreparedStatement[] { | |||
| 245 | * (from the pool, or created here with APNS_MANAGE_CHANNELS), broadcasts each change of status or NET, and | 278 | * (from the pool, or created here with APNS_MANAGE_CHANNELS), broadcasts each change of status or NET, and |
| 246 | * retires a channel once its launch is over. Nothing about who follows a launch reaches the server. | 279 | * retires a channel once its launch is over. Nothing about who follows a launch reaches the server. |
| 247 | */ | 280 | */ |
| 248 | async function launchChannels(env: Env, now: Date): Promise<void> { | 281 | async function launchChannels(env: Env, near: Near[], now: Date): Promise<void> { |
| 249 | const config: ApnsConfig = { keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC }; | 282 | const config: ApnsConfig = { keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC }; |
| 250 | const manage = env.APNS_MANAGE_CHANNELS === "1"; | 283 | const manage = env.APNS_MANAGE_CHANNELS === "1"; |
| 251 | const iso = now.toISOString(); | 284 | const iso = now.toISOString(); |
| 252 | 285 | ||
| 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 }>(); | ||
| 254 | 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 }>(); | 286 | 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 }>(); |
| 255 | const has = new Set(assigned.results.map((c) => `${c.launch_id}:${c.environment}`)); | 287 | 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))) { |
| 257 | for (const environment of ["sandbox", "production"]) { | 289 | for (const environment of ["sandbox", "production"]) { |
| 258 | if (has.has(`${l.id}:${environment}`)) continue; | 290 | if (has.has(`${l.id}:${environment}`)) continue; |
| 259 | const pooled = await env.DB.prepare( | 291 | const pooled = await env.DB.prepare( |
| @@ -275,6 +307,25 @@ async function launchChannels(env: Env, now: Date): Promise<void> { | |||
| 275 | } | 307 | } |
| 276 | } | 308 | } |
| 277 | 309 | ||
| 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. */ | ||
| 327 | async 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 }; | ||
| 278 | const changed = await env.DB.prepare( | 329 | const changed = await env.DB.prepare( |
| 279 | `SELECT c.channel_id, c.environment, c.net AS sent_net, c.status AS sent_status, l.net, l.status | 330 | `SELECT c.channel_id, c.environment, c.net AS sent_net, c.status AS sent_status, l.net, l.status |
| 280 | 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)`, | 331 | 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> { | |||
| 288 | console.error("apns broadcast", r.status, r.reason); | 339 | console.error("apns broadcast", r.status, r.reason); |
| 289 | continue; | 340 | continue; |
| 290 | } | 341 | } |
| 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(); |
| 292 | } | 343 | } |
| 344 | } | ||
| 293 | 345 | ||
| 294 | // A day past NET without an outcome, or gone from the table: ended without a push, as activities last 8 hours at most. | 346 | /** One more try at a failed 2-hourly CelesTrak poll, from the 5-minute cron. */ |
| 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)") | 347 | async function retrySatellites(env: Env, now: Date): Promise<void> { |
| 296 | .bind(iso, new Date(now.getTime() - 86400_000).toISOString()).run(); | 348 | if (!retryTick(now)) return; |
| 297 | if (!manage) 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 }>(); |
| 298 | // Deleted once the stored end message has expired. | 350 | const at = Object.fromEntries(rows.results.map((r) => [r.feed, r.fetched_at])); |
| 299 | const done = await env.DB.prepare("SELECT channel_id, environment FROM launch_channels WHERE ended_at < ?1") | 351 | if (retryDue(now, at.celestrak ?? null, at["celestrak:error"] ?? null)) await pollSatellites(env, now); |
| 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 | } | ||
| 306 | } | 352 | } |
| 307 | 353 | ||
| 308 | async function pollSatellites(env: Env, now: Date): Promise<void> { | 354 | async function pollSatellites(env: Env, now: Date): Promise<void> { |
| @@ -366,31 +412,27 @@ async function sendAuroraAlerts(env: Env, w: SpaceWeather, now: Date): Promise<v | |||
| 366 | const bands = alertBands(kp, bandRows.results.map((r) => r.band)); | 412 | const bands = alertBands(kp, bandRows.results.map((r) => r.band)); |
| 367 | if (!bands.length || !env.APNS_KEY) return; | 413 | if (!bands.length || !env.APNS_KEY) return; |
| 368 | 414 | ||
| 369 | const config: ApnsConfig = { keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC }; | ||
| 370 | const event = eventKey(now); | 415 | const event = eventKey(now); |
| 371 | for (const band of bands) { | 416 | const devices = await env.DB.prepare( |
| 372 | const claimed = await env.DB.prepare("INSERT OR IGNORE INTO alerts_sent (kind, band, event, sent_at) VALUES ('aurora', ?1, ?2, ?3)") | 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)) |
| 373 | .bind(band, event, now.toISOString()).run(); | 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)`, |
| 374 | if (!claimed.meta.changes) continue; | 419 | ).bind(JSON.stringify(bands), event).all<{ token: string; environment: string; band: number; utc_offset_minutes: number }>(); |
| 375 | 420 | const due = devices.results.filter((d) => isNight(now, d.utc_offset_minutes)).map((d) => ({ ...d, event: `${d.token}:${event}` })); | |
| 376 | const devices = await env.DB.prepare("SELECT token, environment, utc_offset_minutes FROM devices WHERE aurora = 1 AND band = ?1") | 421 | await sendAlerts(env, "aurora", due, now, (d) => ({ |
| 377 | .bind(band).all<{ token: string; environment: string; utc_offset_minutes: number }>(); | 422 | aps: { alert: { title: "Aurora possible tonight", body: `Kp ${kp.toFixed(1)}. Look toward the ${d.band >= 0 ? "north" : "south"} after dark.` }, sound: "default" }, |
| 378 | for (const d of devices.results) { | 423 | })); |
| 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 | } | ||
| 386 | } | 424 | } |
| 387 | 425 | ||
| 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. */ |
| 389 | async function sendNewsDigests(env: Env, now: Date): Promise<void> { | 427 | async function sendNewsDigests(env: Env, now: Date): Promise<void> { |
| 390 | if (!env.APNS_KEY) return; | 428 | if (!env.APNS_KEY) return; |
| 391 | const rows = await env.DB.prepare("SELECT token, environment, utc_offset_minutes FROM devices WHERE news = 1") | 429 | const [first, second] = dueOffsets(now); |
| 392 | .all<{ token: string; environment: string; utc_offset_minutes: number }>(); | 430 | const rows = await env.DB.prepare( |
| 393 | const due = rows.results.filter((d) => digestDue(now, d.utc_offset_minutes)); | 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)}` })); | ||
| 394 | if (!due.length) return; | 436 | if (!due.length) return; |
| 395 | 437 | ||
| 396 | let payload; | 438 | let payload; |
| @@ -403,14 +445,41 @@ async function sendNewsDigests(env: Env, now: Date): Promise<void> { | |||
| 403 | return; | 445 | return; |
| 404 | } | 446 | } |
| 405 | 447 | ||
| 448 | await sendAlerts(env, "news", due, now, () => payload); | ||
| 449 | } | ||
| 450 | |||
| 451 | interface 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 | */ | ||
| 463 | async function sendAlerts(env: Env, kind: string, recipients: Recipient[], now: Date, payload: (r: Recipient) => unknown): Promise<void> { | ||
| 406 | const config: ApnsConfig = { keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC }; | 464 | 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) { | 465 | const slice = recipients.slice(0, PUSH_SLICE); |
| 408 | const claimed = await env.DB.prepare("INSERT OR IGNORE INTO alerts_sent (kind, band, event, sent_at) VALUES ('news', 0, ?1, ?2)") | 466 | const results = await sendAll(config, slice.map((r) => ({ token: r.token, payload: payload(r), sandbox: r.environment === "sandbox" })), PUSH_CONCURRENCY); |
| 409 | .bind(`${d.token}:${localDate(now, d.utc_offset_minutes)}`, now.toISOString()).run(); | 467 | const sent = env.DB.prepare("INSERT OR IGNORE INTO alerts_sent (kind, band, event, sent_at) VALUES (?1, ?2, ?3, ?4)"); |
| 410 | if (!claimed.meta.changes) continue; | 468 | const gone = env.DB.prepare("DELETE FROM devices WHERE token = ?1"); |
| 411 | const r = await send(config, d.token, payload, d.environment === "sandbox"); | 469 | const writes: D1PreparedStatement[] = []; |
| 412 | if (r.status === 410) await env.DB.prepare("DELETE FROM devices WHERE token = ?1").bind(d.token).run(); | 470 | slice.forEach((r, i) => { |
| 413 | else if (r.status !== 200) console.error("apns", r.status, r.reason); | 471 | const { status, reason } = results[i]; |
| 414 | } | 472 | if (status !== 200) console.error("apns", status, reason); |
| 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(); | 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. */ | ||
| 480 | async 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 | ]); | ||
| 416 | } | 485 | } |
server/src/news.ts +8 −4
| @@ -9,10 +9,14 @@ export interface Article { | |||
| 9 | 9 | ||
| 10 | export const DIGEST_HOUR = 9; | 10 | export const DIGEST_HOUR = 9; |
| 11 | 11 | ||
| 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). */ | 12 | /** |
| 13 | export function digestDue(now: Date, utcOffsetMinutes: number): boolean { | 13 | * UTC offsets in minutes whose local time is in the digest hour, as two half-open ranges within ±14 hours |
| 14 | const minutes = (((now.getUTCHours() * 60 + now.getUTCMinutes() + utcOffsetMinutes) % 1440) + 1440) % 1440; | 14 | * (either may be empty). The whole hour, so devices one run did not reach get the digest on a later run. |
| 15 | return minutes >= DIGEST_HOUR * 60 && minutes < DIGEST_HOUR * 60 + 10; | 15 | */ |
| 16 | export 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)]; | ||
| 16 | } | 20 | } |
| 17 | 21 | ||
| 18 | /** The device's local date, so each device gets one digest per local day. */ | 22 | /** 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 @@ | |||
| 1 | import assert from "node:assert/strict"; | 1 | import assert from "node:assert/strict"; |
| 2 | import { test } from "node:test"; | 2 | import { test } from "node:test"; |
| 3 | import { activityPush, focusPick, inFocus, needsChannel, sinceNet } from "../src/activity.ts"; | 3 | import { activityPush, focusEvery, focusPick, focusPollDue, inFocus, needsChannel, sinceNet } from "../src/activity.ts"; |
| 4 | 4 | ||
| 5 | const now = new Date("2026-10-20T12:00:00Z"); | 5 | const now = new Date("2026-10-20T12:00:00Z"); |
| 6 | const unix = (iso: string) => Date.parse(iso) / 1000; | 6 | const unix = (iso: string) => Date.parse(iso) / 1000; |
| @@ -21,6 +21,22 @@ test("overlapping launches take turns, one request per 5-minute tick", () => { | |||
| 21 | assert.equal(focusPick(ids, new Date("2026-10-20T12:05:00Z")), "b"); | 21 | assert.equal(focusPick(ids, new Date("2026-10-20T12:05:00Z")), "b"); |
| 22 | assert.equal(focusPick(ids, new Date("2026-10-20T12:10:00Z")), "a"); | 22 | assert.equal(focusPick(ids, new Date("2026-10-20T12:10:00Z")), "a"); |
| 23 | assert.equal(focusPick(["a"], new Date("2026-10-20T12:05:00Z")), "a"); | 23 | 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 | |||
| 27 | test("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 | } | ||
| 24 | }); | 40 | }); |
| 25 | 41 | ||
| 26 | test("a launch needs a channel within 24 hours of NET until it has an outcome", () => { | 42 | test("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 @@ | |||
| 1 | import assert from "node:assert/strict"; | 1 | import assert from "node:assert/strict"; |
| 2 | import { test } from "node:test"; | 2 | import { test } from "node:test"; |
| 3 | import { broadcast, createChannel, deleteChannel, listChannels, send, type ApnsConfig } from "../src/apns.ts"; | 3 | import { broadcast, createChannel, deleteChannel, listChannels, retryable, send, sendAll, type ApnsConfig } from "../src/apns.ts"; |
| 4 | 4 | ||
| 5 | async function config(): Promise<ApnsConfig> { | 5 | async function config(): Promise<ApnsConfig> { |
| 6 | const pair = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign"]); | 6 | const pair = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign"]); |
| @@ -92,3 +92,43 @@ test("errors report APNs' reason", async () => { | |||
| 92 | assert.equal(r.reason, "InvalidProviderToken"); | 92 | assert.equal(r.reason, "InvalidProviderToken"); |
| 93 | assert.deepEqual(r.channels, []); | 93 | assert.deepEqual(r.channels, []); |
| 94 | }); | 94 | }); |
| 95 | |||
| 96 | test("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 | |||
| 109 | test("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 | |||
| 132 | test("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 @@ | |||
| 1 | import assert from "node:assert/strict"; | 1 | import assert from "node:assert/strict"; |
| 2 | import { test } from "node:test"; | 2 | import { test } from "node:test"; |
| 3 | import { byDesignator, compose, fitsLaunch, parseSupGP, pick, starlinkTrains, supgpFile, supgpLaunches } from "../src/celestrak.ts"; | 3 | import { byDesignator, compose, fetchGroups, fitsLaunch, parseSupGP, pick, retryDue, retryTick, starlinkTrains, supgpFile, supgpLaunches } from "../src/celestrak.ts"; |
| 4 | 4 | ||
| 5 | test("keeps only the SGP4 fields", () => { | 5 | test("keeps only the SGP4 fields", () => { |
| 6 | // CelesTrak GP JSON for the ISS, 2026-10-18. | 6 | // 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", ( | |||
| 135 | assert.equal(names[0], "FALCON 9 R/B"); | 135 | assert.equal(names[0], "FALCON 9 R/B"); |
| 136 | assert.ok(!names.includes("FALCON 9 DEB")); | 136 | assert.ok(!names.includes("FALCON 9 DEB")); |
| 137 | }); | 137 | }); |
| 138 | |||
| 139 | test("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 | |||
| 153 | test("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 @@ | |||
| 1 | import assert from "node:assert/strict"; | 1 | import assert from "node:assert/strict"; |
| 2 | import { test } from "node:test"; | 2 | import { test } from "node:test"; |
| 3 | import { digestDue, digestPayload, localDate, pickHeadlines, type Article } from "../src/news.ts"; | 3 | import { digestPayload, dueOffsets, localDate, pickHeadlines, type Article } from "../src/news.ts"; |
| 4 | 4 | ||
| 5 | test("digest is due in the first 10 minutes of 09:00 local", () => { | 5 | test("digest is due for the UTC offsets whose local time is in the 09:00 hour", () => { |
| 6 | const at = (iso: string) => new Date(iso); | 6 | for (let minute = 0; minute < 1440; minute += 5) { |
| 7 | assert.equal(digestDue(at("2026-10-18T14:00:00Z"), -300), true); // 09:00 CDT | 7 | const now = new Date(Date.UTC(2026, 9, 18, 0, minute)); |
| 8 | assert.equal(digestDue(at("2026-10-18T14:09:59Z"), -300), true); | 8 | const ranges = dueOffsets(now); |
| 9 | assert.equal(digestDue(at("2026-10-18T14:10:00Z"), -300), false); | 9 | for (let offset = -840; offset <= 840; offset++) { |
| 10 | assert.equal(digestDue(at("2026-10-17T23:30:00Z"), 570), true); // 09:00 ACST, next day | 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 | ||
| 11 | }); | 17 | }); |
| 12 | 18 | ||
| 13 | test("local date follows the offset", () => { | 19 | test("local date follows the offset", () => { |
server/test/worker.test.ts added +349
| @@ -0,0 +1,349 @@ | |||
| 1 | import assert from "node:assert/strict"; | ||
| 2 | import { readdirSync, readFileSync } from "node:fs"; | ||
| 3 | import { registerHooks } from "node:module"; | ||
| 4 | import { DatabaseSync, type SQLInputValue } from "node:sqlite"; | ||
| 5 | import { afterEach, test } from "node:test"; | ||
| 6 | |||
| 7 | // src/index.ts imports without extensions, which wrangler's bundler resolves. | ||
| 8 | registerHooks({ | ||
| 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 | }); | ||
| 18 | const { default: worker } = await import("../src/index.ts"); | ||
| 19 | |||
| 20 | const FIVE = "*/5 * * * *"; | ||
| 21 | const TWO = "*/2 * * * *"; | ||
| 22 | const NEWS = "*/10 * * * *"; | ||
| 23 | const SATELLITES = "7 */2 * * *"; | ||
| 24 | |||
| 25 | interface 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. */ | ||
| 31 | function 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 | |||
| 75 | async 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 | |||
| 81 | async 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 | |||
| 87 | const real = globalThis.fetch; | ||
| 88 | afterEach(() => { | ||
| 89 | globalThis.fetch = real; | ||
| 90 | }); | ||
| 91 | |||
| 92 | type Handler = (url: URL, init: RequestInit) => Response | Promise<Response>; | ||
| 93 | |||
| 94 | /** Answers by host; anything else gets 503. Returns the hosts requested, in order. */ | ||
| 95 | function 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. */ | ||
| 107 | function 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 | |||
| 127 | function 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 | |||
| 134 | async 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 | |||
| 140 | const token = (i: number) => i.toString(16).padStart(64, "0"); | ||
| 141 | |||
| 142 | function 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 | |||
| 147 | const count = (db: DatabaseSync, sql: string) => (db.prepare(sql).get() as { n: number }).n; | ||
| 148 | |||
| 149 | test("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 | |||
| 173 | test("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 | |||
| 196 | test("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 | |||
| 214 | test("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 | |||
| 238 | test("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 | |||
| 256 | test("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 | |||
| 284 | const ID = "3b430f81-0ff1-4d85-8a1a-cef0de326198"; | ||
| 285 | const 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 | |||
| 292 | for (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 | |||
| 326 | test("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 @@ | |||
| 2 | "name": "moonrise-server", | 2 | "name": "moonrise-server", |
| 3 | "main": "src/index.ts", | 3 | "main": "src/index.ts", |
| 4 | "compatibility_date": "2026-10-01", | 4 | "compatibility_date": "2026-10-01", |
| 5 | "triggers": { "crons": ["*/5 * * * *", "*/10 * * * *", "7 */2 * * *"] }, | 5 | "triggers": { "crons": ["*/5 * * * *", "*/2 * * * *", "*/10 * * * *", "7 */2 * * *"] }, |
| 6 | "d1_databases": [ | 6 | "d1_databases": [ |
| 7 | { | 7 | { |
| 8 | "binding": "DB", | 8 | "binding": "DB", |