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 471e78f395

471e78f39552c3f38307914a3695698845711eed

parent: bd24190a6c

Unsigned

cmc <hello@cleberg.net> · 2026-10-21 17:26 UTC

Edge-cached API on moonrise.krz.sh (!84)

- GET /v1/today, /v1/launches, /v1/live and /v1/satellites go through `cached()`: answered from `caches.default` when fresh, otherwise from D1 and stored for their max-age. Keyed by URL, so `?environment=` and `?at=` are separate. Only 200 responses with Cache-Control are stored; /healthz, /privacy and POST/DELETE are not.
- `wrangler.jsonc`: custom domain `moonrise.krz.sh`; `workers_dev` kept on for existing builds (the Cache API does nothing there).
- App `MOONRISE_API_URL`, the Settings privacy link, privacy text, App Store doc and READMEs move to https://moonrise.krz.sh.
- PLAN.org: caching decision replaced by updating the privacy policy URL in App Store Connect.

Tests: server 57 (2 new: cache hit without D1, separate keys, no caching of errors/health/POST; works without a cache). swift test and xcodebuild test pass; the audit shows no News & launches issues because that screen had no data before the domain exists.

Deploy right after merging: it creates the custom domain, which the app now calls.

Layout: unified · split

App/README.org +1 −1
@@ -12,7 +12,7 @@ Simulator: an iOS 26+ runtime is required. Push registration needs a
1212signed build (team =ZCNAX3VL9D=); the APNs device token is logged under
1313subsystem =sh.krz.moonrise=.
1414
15Backend: both configurations use https://moonrise-server.audit-labs.workers.dev
15Backend: both configurations use https://moonrise.krz.sh
1616(=MOONRISE_API_URL= in =project.yml=). For a local Worker, set it to
1717=http://localhost:8787= and regenerate.
1818
App/Sources/SettingsScreen.swift +1 −1
@@ -61,7 +61,7 @@ struct City: Hashable, Identifiable {
6161}
6262
6363/// Privacy policy served by the backend.
64let privacyPolicyURL = URL(string: "https://moonrise-server.audit-labs.workers.dev/privacy")!
64let privacyPolicyURL = URL(string: "https://moonrise.krz.sh/privacy")!
6565
6666struct SettingsScreen: View {
6767 @AppStorage(SettingsKey.locationMode) private var locationMode = "current"
App/project.yml +2 −2
@@ -48,9 +48,9 @@ targets:
4848 settings:
4949 configs:
5050 Debug:
51 MOONRISE_API_URL: https://moonrise-server.audit-labs.workers.dev
51 MOONRISE_API_URL: https://moonrise.krz.sh
5252 Release:
53 MOONRISE_API_URL: https://moonrise-server.audit-labs.workers.dev
53 MOONRISE_API_URL: https://moonrise.krz.sh
5454 base:
5555 PRODUCT_BUNDLE_IDENTIFIER: sh.krz.moonrise
5656 DEVELOPMENT_TEAM: ZCNAX3VL9D
PLAN.org +1 −4
@@ -470,10 +470,7 @@ Sky, System, Sun, Launches, Library core (above).
470470 device and add one-object alignment with a gyroscope heading.
471471
472472* before publishing
473- Decide on server-side caching: a custom domain with the Cache API, D1 read
474 replication or Smart Placement. =workers.dev= does not cache Worker
475 responses, and every D1 round trip goes to San Jose (about 85 ms from the
476 US east coast).
473- App Store Connect: privacy policy URL https://moonrise.krz.sh/privacy.
477474- Decide on the Astronomical League lists (Herschel 400, Double Star, Lunar,
478475 Binocular Messier) and Lunar 100 (Charles Wood, Sky & Telescope): ask for
479476 permission or leave them to user program files.
docs/app-store.org +1 −1
@@ -8,7 +8,7 @@
88| Bundle ID | =sh.krz.moonrise= (widgets: =sh.krz.moonrise.widgets=) |
99| Team | ZCNAX3VL9D |
1010| Category | Education (secondary: Weather) |
11| Privacy policy URL | https://moonrise-server.audit-labs.workers.dev/privacy |
11| Privacy policy URL | https://moonrise.krz.sh/privacy |
1212
1313* App Privacy ("nutrition label")
1414Aurora alerts (opt-in) send the push token, a 5° geomagnetic latitude
server/README.org +1
@@ -16,6 +16,7 @@ against a deployed Worker.
1616
1717* deploy
1818Deployed 2026-10-17: https://moonrise-server.audit-labs.workers.dev
19Custom domain since 2026-10-21: https://moonrise.krz.sh (edge-cached GETs; workers.dev stays on for older builds)
1920(D1 =moonrise= 54a0c50d-2150-47ae-aa22-449e8204ad7b, APNS_KEY set).
2021
2122#+begin_src sh
server/src/index.ts +36 −8
@@ -46,6 +46,40 @@ const PUSH_CONCURRENCY = 6;
4646const json = (body: unknown, status = 200, maxAge?: number) =>
4747 Response.json(body, { status, headers: maxAge && status === 200 ? { "cache-control": `public, max-age=${maxAge}` } : {} });
4848
49/** Read-only endpoints whose responses are the same for everyone. */
50const API = new Set(["/v1/today", "/v1/launches", "/v1/live", "/v1/satellites"]);
51
52function api(url: URL, env: Env, now: Date): Promise<Response> {
53 switch (url.pathname) {
54 case "/v1/today": return today(env, now);
55 case "/v1/launches": return launches(env, url, now);
56 case "/v1/live": return live(env, url, now);
57 default: return satellites(env);
58 }
59}
60
61async function satellites(env: Env): Promise<Response> {
62 const row = await env.DB.prepare("SELECT fetched_at, body FROM feed_snapshots WHERE feed = 'celestrak' AND ok = 1").first<{ fetched_at: string; body: string }>();
63 return json({ fetchedAt: row?.fetched_at ?? null, satellites: row ? JSON.parse(row.body) : [] }, 200, MAX_AGE.satellites);
64}
65
66/**
67 * Answers from the data centre's cache when it holds a fresh copy, keyed by URL (so ?environment= and ?at= are
68 * separate), and stores 200 responses for their max-age. The Cache API does nothing on workers.dev.
69 */
70async function cached(request: Request, ctx: ExecutionContext | undefined, respond: () => Promise<Response>): Promise<Response> {
71 const cache = typeof caches === "undefined" ? undefined : caches.default;
72 const hit = await cache?.match(request);
73 if (hit) return hit;
74 const res = await respond();
75 if (cache && res.status === 200 && res.headers.has("cache-control")) {
76 const put = cache.put(request, res.clone());
77 if (ctx) ctx.waitUntil(put);
78 else await put;
79 }
80 return res;
81}
82
4983/** How long clients may reuse each GET response, matched to how often its source is polled. */
5084export const MAX_AGE = { today: 60, launches: 300, satellites: 3600, live: 300 } as const;
5185
@@ -69,9 +103,10 @@ async function today(env: Env, now: Date): Promise<Response> {
69103}
70104
71105export default {
72 async fetch(request: Request, env: Env): Promise<Response> {
106 async fetch(request: Request, env: Env, ctx?: ExecutionContext): Promise<Response> {
73107 const url = new URL(request.url);
74108 const now = new Date();
109 if (request.method === "GET" && API.has(url.pathname)) return cached(request, ctx, () => api(url, env, now));
75110
76111 if (request.method === "GET" && url.pathname === "/healthz") {
77112 const rows = await env.DB.prepare("SELECT feed, fetched_at, ok FROM feed_snapshots").all();
@@ -79,13 +114,6 @@ export default {
79114 }
80115 if (request.method === "GET" && url.pathname === "/privacy")
81116 return new Response(PRIVACY_HTML, { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "public, max-age=3600" } });
82 if (request.method === "GET" && url.pathname === "/v1/today") return today(env, now);
83 if (request.method === "GET" && url.pathname === "/v1/launches") return launches(env, url, now);
84 if (request.method === "GET" && url.pathname === "/v1/live") return live(env, url, now);
85 if (request.method === "GET" && url.pathname === "/v1/satellites") {
86 const row = await env.DB.prepare("SELECT fetched_at, body FROM feed_snapshots WHERE feed = 'celestrak' AND ok = 1").first<{ fetched_at: string; body: string }>();
87 return json({ fetchedAt: row?.fetched_at ?? null, satellites: row ? JSON.parse(row.body) : [] }, 200, MAX_AGE.satellites);
88 }
89117
90118 if (request.method === "POST" && url.pathname === "/v1/devices") {
91119 const d = (await request.json().catch(() => ({}))) as Partial<DeviceRequest>;
server/src/privacy.ts +2 −2
@@ -17,7 +17,7 @@ h2 { font-weight: 500; font-size: 1.1em; margin-top: 1.8em; border-top: 1px soli
1717<body>
1818<h1>Moonrise privacy policy</h1>
1919<div class="rule"></div>
20<p>Last updated 20 October 2026.</p>
20<p>Last updated 21 October 2026.</p>
2121
2222<h2>Summary</h2>
2323<p>Moonrise has no accounts, no advertising, no analytics and no tracking. Your location is never sent to our server. If you turn on aurora alerts or news alerts, it sends our server four things needed to deliver them, described below. If you turn on cloud forecasts, it sends a rounded location to Apple's weather service. Nothing else is collected.</p>
@@ -31,7 +31,7 @@ h2 { font-weight: 500; font-size: 1.1em; margin-top: 1.8em; border-top: 1px soli
3131<h2>Network requests</h2>
3232<p>To show live data, the app requests:</p>
3333<ul>
34<li>space weather and launch schedules from our server, moonrise-server.audit-labs.workers.dev, which runs on Cloudflare Workers;</li>
34<li>space weather and launch schedules from our server, moonrise.krz.sh, which runs on Cloudflare Workers;</li>
3535<li>space weather and aurora data directly from NOAA's Space Weather Prediction Center;</li>
3636<li>images of the Sun from NASA's Solar Dynamics Observatory;</li>
3737<li>images in the Library from NASA, ESA, ESO, NOIRLab and the Library of Congress;</li>
server/test/worker.test.ts +45
@@ -281,6 +281,51 @@ test("GET /v1/launches reads everything in one D1 batch", async () => {
281281 assert.equal(sandbox.launches[0].channelId, null);
282282});
283283
284test("GET API responses are served from the edge cache until they expire", async () => {
285 const { db, env, calls } = await setup();
286 db.exec("INSERT INTO feed_snapshots (feed, fetched_at, ok, body) VALUES ('celestrak', '2026-10-20T10:07:00.000Z', 1, '[]')");
287 const store = new Map<string, Response>();
288 const puts: string[] = [];
289 (globalThis as { caches?: unknown }).caches = {
290 default: {
291 match: async (r: Request) => store.get(r.url)?.clone(),
292 put: async (r: Request, res: Response) => { puts.push(r.url); store.set(r.url, res); },
293 },
294 };
295 const pending: Promise<unknown>[] = [];
296 const ctx = { waitUntil: (p: Promise<unknown>) => pending.push(p), passThroughOnException() {} };
297 const get = async (path: string) => {
298 const res = await worker.fetch(new Request(`https://moonrise.test${path}`), env as never, ctx as never);
299 await Promise.all(pending);
300 return res;
301 };
302 try {
303 const first = await (await get("/v1/satellites")).json();
304 const queries = calls.length;
305 assert.ok(queries > 0);
306 const second = await (await get("/v1/satellites")).json();
307 assert.equal(calls.length, queries, "second request read D1");
308 assert.deepEqual(second, first);
309
310 await get("/v1/launches");
311 await get("/v1/launches?environment=sandbox");
312 assert.deepEqual(puts, ["https://moonrise.test/v1/satellites", "https://moonrise.test/v1/launches", "https://moonrise.test/v1/launches?environment=sandbox"]);
313
314 await get("/v1/live?at=nonsense");
315 await get("/healthz");
316 await worker.fetch(new Request("https://moonrise.test/v1/devices", { method: "POST", body: "{}" }), env as never, ctx as never);
317 assert.equal(puts.length, 3, "error, health or POST response was cached");
318 } finally {
319 delete (globalThis as { caches?: unknown }).caches;
320 }
321});
322
323test("GET API responses work without an edge cache", async () => {
324 const { env } = await setup();
325 const res = await worker.fetch(new Request("https://moonrise.test/v1/today"), env as never);
326 assert.equal(res.status, 200);
327});
328
284329const ID = "3b430f81-0ff1-4d85-8a1a-cef0de326198";
285330const raw = (net: string, status: string, designator: string | null = null) => ({
286331 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,
server/wrangler.jsonc +3
@@ -2,6 +2,9 @@
22 "name": "moonrise-server",
33 "main": "src/index.ts",
44 "compatibility_date": "2026-10-01",
5 "routes": [{ "pattern": "moonrise.krz.sh", "custom_domain": true }],
6 // Kept for builds that still call moonrise-server.audit-labs.workers.dev; workers.dev has no edge cache.
7 "workers_dev": true,
58 "triggers": { "crons": ["*/5 * * * *", "*/2 * * * *", "*/10 * * * *", "7 */2 * * *"] },
69 "d1_databases": [
710 {