Commit 8562cc5d8f
8562cc5d8f7e104c2da15627c9bfd7a131fd6c0a
parent: ac47347816
Unsigned
cmc <hello@cleberg.net> · 2026-10-22 00:01 UTC
Live: Horizons fair use (!101)
Per JPL's SSD API Service Fair Use Policy (https://ssd-api.jpl.nasa.gov/):
- `/v1/live` claims a `live:<event>:attempt` row in `feed_snapshots` with a conditional upsert before calling Horizons. Only the request that claims it calls Horizons, so there is one call per event per 10 minutes across requests and isolates, including after failures. Before this, every uncached request retried while no trajectory was stored.
- Horizons User-Agent: `Moonrise/4.1.0 (sh.krz.moonrise; root@krz.sh)`. The version is a constant in `live.ts` and needs bumping with releases.
- Test: a failed call is not retried within 10 minutes, is retried after, and the stored trajectory is then served from D1. It fails without the change. 59/59 server tests pass.
Layout: unified · split
server/src/index.ts
+8 −2
| @@ -167,7 +167,7 @@ async function sendTest(env: Env, token: string, now: Date): Promise<Response> { |
| 167 | 167 | /** |
| 168 | 168 | * The live event at `?at=` (default now) and its geocentric ecliptic trajectory up to then: |
| 169 | 169 | * points are [unix seconds, x, y, z] km. The cached trajectory is refreshed from Horizons at most |
| 170 | | * every 10 minutes while the event runs. |
| 170 | * every 10 minutes while the event runs, and no sooner than 10 minutes after a failed attempt. |
| 171 | 171 | */ |
| 172 | 172 | async function live(env: Env, url: URL, now: Date): Promise<Response> { |
| 173 | 173 | const atParam = url.searchParams.get("at"); |
| @@ -182,7 +182,13 @@ async function live(env: Env, url: URL, now: Date): Promise<Response> { |
| 182 | 182 | const covered = (points.at(-1)?.[0] ?? 0) * 1000; |
| 183 | 183 | const wanted = Math.min(now.getTime(), Date.parse(event.end)) - 2 * STEP_MINUTES * 60_000; |
| 184 | 184 | const stale = !row || points.length === 0 || now.getTime() - Date.parse(row.fetched_at) > 10 * 60_000; |
| 185 | | if (covered < wanted && stale) { |
| 185 | // One Horizons request per event per 10 minutes, across requests and isolates and after failures |
| 186 | // (JPL's fair use policy: no simultaneous requests, back off on errors). The request that claims the |
| 187 | // attempt row makes it. |
| 188 | const claimed = covered < wanted && stale && (await env.DB.prepare( |
| 189 | "INSERT INTO feed_snapshots (feed, fetched_at, ok) VALUES (?1, ?2, 0) ON CONFLICT (feed) DO UPDATE SET fetched_at = ?2 WHERE fetched_at < ?3", |
| 190 | ).bind(`${key}:attempt`, now.toISOString(), new Date(now.getTime() - 10 * 60_000).toISOString()).run()).meta.changes === 1; |
| 191 | if (claimed) { |
| 186 | 192 | try { |
| 187 | 193 | const fresh = await fetchTrajectory(event, now); |
| 188 | 194 | if (fresh.length === 0) throw new Error("no Horizons data"); |
server/src/live.ts
+4 −1
| @@ -42,6 +42,9 @@ export const EVENTS: LiveEvent[] = [ |
| 42 | 42 | |
| 43 | 43 | export const STEP_MINUTES = 30; |
| 44 | 44 | |
| 45 | /** JPL's SSD API fair use policy asks for the product name, version and a contact. */ |
| 46 | export const HORIZONS_USER_AGENT = "Moonrise/4.1.0 (sh.krz.moonrise; root@krz.sh)"; |
| 47 | |
| 45 | 48 | /** The event whose window contains `at`, if any. */ |
| 46 | 49 | export function activeEvent(at: Date, events = EVENTS): LiveEvent | undefined { |
| 47 | 50 | return events.find((e) => Date.parse(e.launch) <= at.getTime() && at.getTime() <= Date.parse(e.end)); |
| @@ -84,7 +87,7 @@ export async function fetchTrajectory(e: LiveEvent, until: Date, from = new Date |
| 84 | 87 | START_TIME: `'${fmt(start)}'`, STOP_TIME: `'${fmt(stop)}'`, STEP_SIZE: `'${STEP_MINUTES}m'`, |
| 85 | 88 | VEC_TABLE: "'1'", OUT_UNITS: "'KM-S'", CSV_FORMAT: "'YES'", OBJ_DATA: "'NO'", MAKE_EPHEM: "'YES'", |
| 86 | 89 | }); |
| 87 | | const res = await fetch(`https://ssd.jpl.nasa.gov/api/horizons.api?${params}`, { headers: { "user-agent": "moonrise-server (sh.krz.moonrise)" } }); |
| 90 | const res = await fetch(`https://ssd.jpl.nasa.gov/api/horizons.api?${params}`, { headers: { "user-agent": HORIZONS_USER_AGENT } }); |
| 88 | 91 | if (res.status !== 200) throw new Error(`Horizons ${res.status}`); |
| 89 | 92 | const result = ((await res.json()) as { result: string }).result; |
| 90 | 93 | const first = ephemerisLimit(result, "prior to"); |
server/test/worker.test.ts
+30 −1
| @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; |
| 2 | 2 | import { readdirSync, readFileSync } from "node:fs"; |
| 3 | 3 | import { registerHooks } from "node:module"; |
| 4 | 4 | import { DatabaseSync, type SQLInputValue } from "node:sqlite"; |
| 5 | | import { afterEach, test } from "node:test"; |
| 5 | import { afterEach, mock, test } from "node:test"; |
| 6 | 6 | |
| 7 | 7 | // src/index.ts imports without extensions, which wrangler's bundler resolves. |
| 8 | 8 | registerHooks({ |
| @@ -320,6 +320,35 @@ test("GET API responses are served from the edge cache until they expire", async |
| 320 | 320 | } |
| 321 | 321 | }); |
| 322 | 322 | |
| 323 | test("/v1/live asks Horizons at most once per 10 minutes, after failures too, and sends a contact", async () => { |
| 324 | const { env } = await setup(); |
| 325 | let up = false; |
| 326 | const agents: string[] = []; |
| 327 | const hosts = network({ |
| 328 | "ssd.jpl.nasa.gov": (_url, init) => { |
| 329 | agents.push(new Headers(init.headers).get("user-agent") ?? ""); |
| 330 | if (!up) return new Response("timeout", { status: 522 }); |
| 331 | return Response.json({ result: "$$SOE\n2461132.500000000, A.D. 2026-Apr-03 00:00:00.0000, 1.0E+05, 2.0E+05, 3.0E+04,\n$$EOE" }); |
| 332 | }, |
| 333 | }); |
| 334 | mock.timers.enable({ apis: ["Date"], now: Date.parse("2026-10-22T00:00:00Z") }); |
| 335 | const live = async () => (await (await worker.fetch(new Request("https://moonrise.test/v1/live?at=2026-04-06T23:00:00Z"), env as never)).json()) as { points: number[][] }; |
| 336 | try { |
| 337 | assert.equal((await live()).points.length, 0); |
| 338 | assert.equal((await live()).points.length, 0); |
| 339 | assert.equal(hosts.length, 1, "retried within 10 minutes of a failure"); |
| 340 | assert.match(agents[0], /^Moonrise\/\d+\.\d+\.\d+ \(sh\.krz\.moonrise; root@krz\.sh\)$/); |
| 341 | |
| 342 | up = true; |
| 343 | mock.timers.setTime(Date.parse("2026-10-22T00:11:00Z")); |
| 344 | assert.equal((await live()).points.length, 1); |
| 345 | assert.equal((await live()).points.length, 1); |
| 346 | assert.equal(hosts.length, 2, "stored trajectory read from D1"); |
| 347 | } finally { |
| 348 | mock.timers.reset(); |
| 349 | } |
| 350 | }); |
| 351 | |
| 323 | 352 | test("/privacy redirects to the policy on krz.sh", async () => { |
| 324 | 353 | const { env } = await setup(); |
| 325 | 354 | const res = await worker.fetch(new Request("https://moonrise.test/privacy"), env as never); |