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
12signed build (team =ZCNAX3VL9D=); the APNs device token is logged under 12signed build (team =ZCNAX3VL9D=); the APNs device token is logged under
13subsystem =sh.krz.moonrise=. 13subsystem =sh.krz.moonrise=.
14 14
15Backend: both configurations use https://moonrise-server.audit-labs.workers.dev 15Backend: both configurations use https://moonrise.krz.sh
16(=MOONRISE_API_URL= in =project.yml=). For a local Worker, set it to 16(=MOONRISE_API_URL= in =project.yml=). For a local Worker, set it to
17=http://localhost:8787= and regenerate. 17=http://localhost:8787= and regenerate.
18 18
App/Sources/SettingsScreen.swift +1 −1
@@ -61,7 +61,7 @@ struct City: Hashable, Identifiable {
61} 61}
62 62
63/// Privacy policy served by the backend. 63/// 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")!
65 65
66struct SettingsScreen: View { 66struct SettingsScreen: View {
67 @AppStorage(SettingsKey.locationMode) private var locationMode = "current" 67 @AppStorage(SettingsKey.locationMode) private var locationMode = "current"
App/project.yml +2 −2
@@ -48,9 +48,9 @@ targets:
48 settings: 48 settings:
49 configs: 49 configs:
50 Debug: 50 Debug:
51 MOONRISE_API_URL: https://moonrise-server.audit-labs.workers.dev 51 MOONRISE_API_URL: https://moonrise.krz.sh
52 Release: 52 Release:
53 MOONRISE_API_URL: https://moonrise-server.audit-labs.workers.dev 53 MOONRISE_API_URL: https://moonrise.krz.sh
54 base: 54 base:
55 PRODUCT_BUNDLE_IDENTIFIER: sh.krz.moonrise 55 PRODUCT_BUNDLE_IDENTIFIER: sh.krz.moonrise
56 DEVELOPMENT_TEAM: ZCNAX3VL9D 56 DEVELOPMENT_TEAM: ZCNAX3VL9D
PLAN.org +1 −4
@@ -470,10 +470,7 @@ Sky, System, Sun, Launches, Library core (above).
470 device and add one-object alignment with a gyroscope heading. 470 device and add one-object alignment with a gyroscope heading.
471 471
472* before publishing 472* before publishing
473- Decide on server-side caching: a custom domain with the Cache API, D1 read 473- App Store Connect: privacy policy URL https://moonrise.krz.sh/privacy.
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).
477- Decide on the Astronomical League lists (Herschel 400, Double Star, Lunar, 474- Decide on the Astronomical League lists (Herschel 400, Double Star, Lunar,
478 Binocular Messier) and Lunar 100 (Charles Wood, Sky & Telescope): ask for 475 Binocular Messier) and Lunar 100 (Charles Wood, Sky & Telescope): ask for
479 permission or leave them to user program files. 476 permission or leave them to user program files.
docs/app-store.org +1 −1
@@ -8,7 +8,7 @@
8| Bundle ID | =sh.krz.moonrise= (widgets: =sh.krz.moonrise.widgets=) | 8| Bundle ID | =sh.krz.moonrise= (widgets: =sh.krz.moonrise.widgets=) |
9| Team | ZCNAX3VL9D | 9| Team | ZCNAX3VL9D |
10| Category | Education (secondary: Weather) | 10| 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 |
12 12
13* App Privacy ("nutrition label") 13* App Privacy ("nutrition label")
14Aurora alerts (opt-in) send the push token, a 5° geomagnetic latitude 14Aurora alerts (opt-in) send the push token, a 5° geomagnetic latitude
server/README.org +1
@@ -16,6 +16,7 @@ against a deployed Worker.
16 16
17* deploy 17* deploy
18Deployed 2026-10-17: https://moonrise-server.audit-labs.workers.dev 18Deployed 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)
19(D1 =moonrise= 54a0c50d-2150-47ae-aa22-449e8204ad7b, APNS_KEY set). 20(D1 =moonrise= 54a0c50d-2150-47ae-aa22-449e8204ad7b, APNS_KEY set).
20 21
21#+begin_src sh 22#+begin_src sh
server/src/index.ts +36 −8
@@ -46,6 +46,40 @@ const PUSH_CONCURRENCY = 6;
46const json = (body: unknown, status = 200, maxAge?: number) => 46const json = (body: unknown, status = 200, maxAge?: number) =>
47 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}` } : {} });
48 48
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
49/** How long clients may reuse each GET response, matched to how often its source is polled. */ 83/** How long clients may reuse each GET response, matched to how often its source is polled. */
50export const MAX_AGE = { today: 60, launches: 300, satellites: 3600, live: 300 } as const; 84export const MAX_AGE = { today: 60, launches: 300, satellites: 3600, live: 300 } as const;
51 85
@@ -69,9 +103,10 @@ async function today(env: Env, now: Date): Promise<Response> {
69} 103}
70 104
71export default { 105export default {
72 async fetch(request: Request, env: Env): Promise<Response> { 106 async fetch(request: Request, env: Env, ctx?: ExecutionContext): Promise<Response> {
73 const url = new URL(request.url); 107 const url = new URL(request.url);
74 const now = new Date(); 108 const now = new Date();
109 if (request.method === "GET" && API.has(url.pathname)) return cached(request, ctx, () => api(url, env, now));
75 110
76 if (request.method === "GET" && url.pathname === "/healthz") { 111 if (request.method === "GET" && url.pathname === "/healthz") {
77 const rows = await env.DB.prepare("SELECT feed, fetched_at, ok FROM feed_snapshots").all(); 112 const rows = await env.DB.prepare("SELECT feed, fetched_at, ok FROM feed_snapshots").all();
@@ -79,13 +114,6 @@ export default {
79 } 114 }
80 if (request.method === "GET" && url.pathname === "/privacy") 115 if (request.method === "GET" && url.pathname === "/privacy")
81 return new Response(PRIVACY_HTML, { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "public, max-age=3600" } }); 116 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 }
89 117
90 if (request.method === "POST" && url.pathname === "/v1/devices") { 118 if (request.method === "POST" && url.pathname === "/v1/devices") {
91 const d = (await request.json().catch(() => ({}))) as Partial<DeviceRequest>; 119 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
17<body> 17<body>
18<h1>Moonrise privacy policy</h1> 18<h1>Moonrise privacy policy</h1>
19<div class="rule"></div> 19<div class="rule"></div>
20<p>Last updated 20 October 2026.</p> 20<p>Last updated 21 October 2026.</p>
21 21
22<h2>Summary</h2> 22<h2>Summary</h2>
23<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> 23<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
31<h2>Network requests</h2> 31<h2>Network requests</h2>
32<p>To show live data, the app requests:</p> 32<p>To show live data, the app requests:</p>
33<ul> 33<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>
35<li>space weather and aurora data directly from NOAA's Space Weather Prediction Center;</li> 35<li>space weather and aurora data directly from NOAA's Space Weather Prediction Center;</li>
36<li>images of the Sun from NASA's Solar Dynamics Observatory;</li> 36<li>images of the Sun from NASA's Solar Dynamics Observatory;</li>
37<li>images in the Library from NASA, ESA, ESO, NOIRLab and the Library of Congress;</li> 37<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 () => {
281 assert.equal(sandbox.launches[0].channelId, null); 281 assert.equal(sandbox.launches[0].channelId, null);
282}); 282});
283 283
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
284const ID = "3b430f81-0ff1-4d85-8a1a-cef0de326198"; 329const ID = "3b430f81-0ff1-4d85-8a1a-cef0de326198";
285const raw = (net: string, status: string, designator: string | null = null) => ({ 330const 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, 331 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 @@
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 "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,
5 "triggers": { "crons": ["*/5 * * * *", "*/2 * * * *", "*/10 * * * *", "7 */2 * * *"] }, 8 "triggers": { "crons": ["*/5 * * * *", "*/2 * * * *", "*/10 * * * *", "7 */2 * * *"] },
6 "d1_databases": [ 9 "d1_databases": [
7 { 10 {