Commit a40dab3f37
Unsigned
Layout: unified · split
App/Sources/SunScreen.swift +27
| @@ -12,6 +12,7 @@ struct SunScreen: View { | |||
| 12 | @State private var imageID = Date.now | 12 | @State private var imageID = Date.now |
| 13 | @State private var picture: Picture? | 13 | @State private var picture: Picture? |
| 14 | @State private var imageFailed = false | 14 | @State private var imageFailed = false |
| 15 | @State private var solarWind: SolarWind? | ||
| 15 | @Environment(\.dynamicTypeSize) private var typeSize | 16 | @Environment(\.dynamicTypeSize) private var typeSize |
| 16 | 17 | ||
| 17 | private var kp: [KpBar] { data?.kp ?? [] } | 18 | private var kp: [KpBar] { data?.kp ?? [] } |
| @@ -51,6 +52,9 @@ struct SunScreen: View { | |||
| 51 | Text(SolarImage.credit).font(.caption2).dimmed(0.5).padding(.top, 4) | 52 | Text(SolarImage.credit).font(.caption2).dimmed(0.5).padding(.top, 4) |
| 52 | 53 | ||
| 53 | section("Aurora tonight", note: "NOAA's forecast of where the aurora may be overhead in the next hour; brighter green is more likely. From a few hundred kilometres further from the pole it can still be seen low on the horizon.") { auroraMap } | 54 | section("Aurora tonight", note: "NOAA's forecast of where the aurora may be overhead in the next hour; brighter green is more likely. From a few hundred kilometres further from the pole it can still be seen low on the horizon.") { auroraMap } |
| 55 | if let solarWind { | ||
| 56 | section("Solar wind", note: "Measured 1.5 million km sunward of Earth, 30 to 60 minutes before it arrives. When Bz, the north–south part of its magnetic field, turns strongly negative (south), aurora often follows.") { solarWindPanel(solarWind) } | ||
| 57 | } | ||
| 54 | section("Solar flares, last 24 h", note: "X-rays from the Sun, measured by NOAA's GOES satellites. Spikes are flares: M and X class can disrupt radio and GPS, and the biggest can bring a storm a day or two later.") { | 58 | section("Solar flares, last 24 h", note: "X-rays from the Sun, measured by NOAA's GOES satellites. Spikes are flares: M and X class can disrupt radio and GPS, and the biggest can bring a storm a day or two later.") { |
| 55 | flares | 59 | flares |
| 56 | if let p = data?.probabilities { probabilityTable(p) } | 60 | if let p = data?.probabilities { probabilityTable(p) } |
| @@ -73,6 +77,7 @@ struct SunScreen: View { | |||
| 73 | 77 | ||
| 74 | private func load(force: Bool) async { | 78 | private func load(force: Bool) async { |
| 75 | if data == nil { await show(SunFeeds.lastSaved()) } | 79 | if data == nil { await show(SunFeeds.lastSaved()) } |
| 80 | if let apiBase { solarWind = (try? await SolarWind.fetch(base: apiBase)) ?? solarWind } | ||
| 76 | if force { imageID = .now } | 81 | if force { imageID = .now } |
| 77 | let result = await SunFeeds.load(force: force) | 82 | let result = await SunFeeds.load(force: force) |
| 78 | await show(result?.snapshot) | 83 | await show(result?.snapshot) |
| @@ -345,6 +350,28 @@ struct SunScreen: View { | |||
| 345 | } | 350 | } |
| 346 | } | 351 | } |
| 347 | 352 | ||
| 353 | private func solarWindPanel(_ w: SolarWind) -> some View { | ||
| 354 | let n = { (v: Double?, f: Int) in v.map { $0.formatted(.number.precision(.fractionLength(f))) } ?? "–" } | ||
| 355 | return VStack(alignment: .leading, spacing: 10) { | ||
| 356 | HStack(spacing: 20) { | ||
| 357 | stat("Speed, km/s", n(w.speed, 0)) | ||
| 358 | stat("Density, /cm³", n(w.density, 1)) | ||
| 359 | stat("Bz, nT", n(w.bz, 1)) | ||
| 360 | stat("Field, nT", n(w.bt, 1)) | ||
| 361 | } | ||
| 362 | Chart(w.series.filter { $0.bz != nil }) { p in | ||
| 363 | LineMark(x: .value("Time", p.t), y: .value("Bz", p.bz ?? 0)).foregroundStyle(ink) | ||
| 364 | RuleMark(y: .value("Zero", 0)).foregroundStyle(ink.opacity(0.3)) | ||
| 365 | RuleMark(y: .value("Strong south", -10)).foregroundStyle(accent.opacity(0.6)).lineStyle(StrokeStyle(lineWidth: 0.5, dash: [3, 3])) | ||
| 366 | } | ||
| 367 | .chartYAxis { AxisMarks { _ in AxisGridLine().foregroundStyle(ink.opacity(0.15)); AxisValueLabel().foregroundStyle(ink.opacity(0.6)) } } | ||
| 368 | .chartXAxis { AxisMarks(values: .stride(by: .hour, count: 2)) { _ in AxisValueLabel(format: .dateTime.hour()).foregroundStyle(ink.opacity(0.6)) } } | ||
| 369 | .frame(height: 110) | ||
| 370 | Text("Bz over 6 hours, 5-minute means. Dashed: −10 nT. From \(w.source), \(w.observedAt.formatted(date: .omitted, time: .shortened)).") | ||
| 371 | .font(.caption2).dimmed(0.6) | ||
| 372 | } | ||
| 373 | } | ||
| 374 | |||
| 348 | private func stat(_ label: String, _ value: String) -> some View { | 375 | private func stat(_ label: String, _ value: String) -> some View { |
| 349 | VStack(alignment: .leading, spacing: 2) { | 376 | VStack(alignment: .leading, spacing: 2) { |
| 350 | Text(label).font(.caption2).dimmed(0.6) | 377 | Text(label).font(.caption2).dimmed(0.6) |
PLAN.org +3 −1
| @@ -515,7 +515,9 @@ Worker; DSN Now freshness; NASA/ESA image licences; 26 LoC plates bundled. | |||
| 515 | ** v5.1: Sun | 515 | ** v5.1: Sun |
| 516 | - Solar wind from SWPC RTSW (=json/rtsw/rtsw_mag_1m.json=, | 516 | - Solar wind from SWPC RTSW (=json/rtsw/rtsw_mag_1m.json=, |
| 517 | =rtsw_wind_1m.json=), reduced on the Worker; earlier aurora alerts from | 517 | =rtsw_wind_1m.json=), reduced on the Worker; earlier aurora alerts from |
| 518 | Bz. | 518 | Bz. Done: 5-minute means over 6 h in =/v1/today=; Sun tab panel and Bz |
| 519 | chart; alerts to the Kp 6 bands when the last 30 min average Bz ≤ −10 nT | ||
| 520 | and speed ≥ 450 km/s (a rule of thumb, not a Kp model). | ||
| 519 | - Active-region labels on the SDO image. | 521 | - Active-region labels on the SDO image. |
| 520 | - Sun path, golden and blue hour, day length. | 522 | - Sun path, golden and blue hour, day length. |
| 521 | - CCOR-2 coronagraph loop, WSA-Enlil forecast line, solar cycle progress. | 523 | - CCOR-2 coronagraph loop, WSA-Enlil forecast line, solar cycle progress. |
Packages/MoonriseKit/Sources/Feeds/SolarWind.swift added +41
| @@ -0,0 +1,41 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | /// Solar wind at L1 from the backend's /v1/today: 5-minute means over 6 hours from SWPC's real-time solar wind | ||
| 4 | /// (SOLAR-1, ACE or IMAP). | ||
| 5 | public struct SolarWind: Sendable, Equatable, Decodable { | ||
| 6 | public struct Point: Sendable, Equatable, Decodable, Identifiable { | ||
| 7 | public var t: Date | ||
| 8 | public var speed: Double? | ||
| 9 | public var density: Double? | ||
| 10 | public var bz: Double? | ||
| 11 | public var bt: Double? | ||
| 12 | public var id: Date { t } | ||
| 13 | } | ||
| 14 | |||
| 15 | public var observedAt: Date | ||
| 16 | public var source: String | ||
| 17 | public var series: [Point] | ||
| 18 | |||
| 19 | /// The latest bin with each value. | ||
| 20 | public var speed: Double? { series.last { $0.speed != nil }?.speed } | ||
| 21 | public var density: Double? { series.last { $0.density != nil }?.density } | ||
| 22 | public var bz: Double? { series.last { $0.bz != nil }?.bz } | ||
| 23 | public var bt: Double? { series.last { $0.bt != nil }?.bt } | ||
| 24 | |||
| 25 | static func decodeToday(_ data: Data) throws -> SolarWind? { | ||
| 26 | struct Today: Decodable { var solarWind: SolarWind? } | ||
| 27 | let d = JSONDecoder() | ||
| 28 | d.dateDecodingStrategy = .custom { decoder in | ||
| 29 | let s = try decoder.singleValueContainer().decode(String.self) | ||
| 30 | guard let date = try? Date(s, strategy: Date.ISO8601FormatStyle(includingFractionalSeconds: true)) else { | ||
| 31 | throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "bad date \(s)")) | ||
| 32 | } | ||
| 33 | return date | ||
| 34 | } | ||
| 35 | return try d.decode(Today.self, from: data).solarWind | ||
| 36 | } | ||
| 37 | |||
| 38 | public static func fetch(base: URL, session: URLSession = .shared) async throws -> SolarWind? { | ||
| 39 | try decodeToday(await session.data(from: base.appending(path: "v1/today")).0) | ||
| 40 | } | ||
| 41 | } | ||
Packages/MoonriseKit/Tests/FeedsTests/SpaceWeatherTests.swift +10
| @@ -34,3 +34,13 @@ let forecast = Data(""" | |||
| 34 | let w = try SpaceWeather.decodeToday(data) | 34 | let w = try SpaceWeather.decodeToday(data) |
| 35 | #expect(w == SpaceWeather(kpNow: 2.33, observedAt: try Date("2026-10-22T00:05:00Z", strategy: .iso8601), kpNext24h: 4.67)) | 35 | #expect(w == SpaceWeather(kpNow: 2.33, observedAt: try Date("2026-10-22T00:05:00Z", strategy: .iso8601), kpNext24h: 4.67)) |
| 36 | } | 36 | } |
| 37 | |||
| 38 | @Test func decodesBackendSolarWind() throws { | ||
| 39 | let data = Data(#"{"spaceWeather":{"kpNow":2,"observedAt":"2026-10-22T00:05:00.000Z","kpNext24h":null,"fetchedAt":"x"},"solarWind":{"observedAt":"2026-10-22T03:36:00.000Z","source":"SOLAR1","series":[{"t":"2026-10-22T03:30:00.000Z","speed":477.8,"density":5.8,"bz":4.6,"bt":7.8},{"t":"2026-10-22T03:35:00.000Z","speed":467.5,"density":null,"bz":-3.5,"bt":7.7}]}}"#.utf8) | ||
| 40 | let w = try #require(try SolarWind.decodeToday(data)) | ||
| 41 | #expect(w.source == "SOLAR1") | ||
| 42 | #expect(w.series.count == 2) | ||
| 43 | #expect(w.bz == -3.5) | ||
| 44 | #expect(w.density == 5.8) | ||
| 45 | #expect(try SolarWind.decodeToday(Data(#"{"spaceWeather":null}"#.utf8)) == nil) | ||
| 46 | } | ||
server/src/index.ts +26 −4
| @@ -5,6 +5,7 @@ import { compose, fetchGroups, fetchSupGP, fitsLaunch, retryDue, retryTick, supg | |||
| 5 | import { activeEvent, fetchTrajectory, STEP_MINUTES } from "./live"; | 5 | import { activeEvent, fetchTrajectory, STEP_MINUTES } from "./live"; |
| 6 | import { fetchLaunch, fetchLaunches, PREVIOUS_URL, throttleSeconds, Throttled, UPCOMING_URL, type Launch } from "./ll2"; | 6 | import { fetchLaunch, fetchLaunches, PREVIOUS_URL, throttleSeconds, Throttled, UPCOMING_URL, type Launch } from "./ll2"; |
| 7 | import { digestPayload, dueOffsets, fetchLatest, localDate, pickHeadlines, type Article } from "./news"; | 7 | import { digestPayload, dueOffsets, fetchLatest, localDate, pickHeadlines, type Article } from "./news"; |
| 8 | import { fetchSolarWind, STORM_KP, stormLikely, type SolarWind } from "./solarwind"; | ||
| 8 | import { fetchSpaceWeather, next24h, type SpaceWeather } from "./swpc"; | 9 | import { fetchSpaceWeather, next24h, type SpaceWeather } from "./swpc"; |
| 9 | 10 | ||
| 10 | interface Env { | 11 | interface Env { |
| @@ -105,8 +106,10 @@ async function today(env: Env, now: Date): Promise<Response> { | |||
| 105 | if (!row) return json({ spaceWeather: null }, 200, MAX_AGE.today); | 106 | if (!row) return json({ spaceWeather: null }, 200, MAX_AGE.today); |
| 106 | const w = JSON.parse(row.body) as SpaceWeather; | 107 | const w = JSON.parse(row.body) as SpaceWeather; |
| 107 | w.forecast = w.forecast.map((f) => ({ ...f, start: new Date(f.start) })); | 108 | w.forecast = w.forecast.map((f) => ({ ...f, start: new Date(f.start) })); |
| 109 | const wind = await env.DB.prepare("SELECT body FROM feed_snapshots WHERE feed = 'rtsw' AND ok = 1").first<{ body: string }>(); | ||
| 108 | return json({ | 110 | return json({ |
| 109 | spaceWeather: { kpNow: w.kpNow, observedAt: w.observedAt, kpNext24h: next24h(w, now), fetchedAt: row.fetched_at }, | 111 | spaceWeather: { kpNow: w.kpNow, observedAt: w.observedAt, kpNext24h: next24h(w, now), fetchedAt: row.fetched_at }, |
| 112 | solarWind: wind ? JSON.parse(wind.body) : null, | ||
| 110 | }, 200, MAX_AGE.today); | 113 | }, 200, MAX_AGE.today); |
| 111 | } | 114 | } |
| 112 | 115 | ||
| @@ -469,11 +472,28 @@ async function pollSpaceWeather(env: Env, now: Date): Promise<void> { | |||
| 469 | await env.DB.prepare( | 472 | await env.DB.prepare( |
| 470 | "INSERT INTO feed_snapshots (feed, fetched_at, ok, body) VALUES ('swpc', ?1, 1, ?2) ON CONFLICT (feed) DO UPDATE SET fetched_at = ?1, ok = 1, body = ?2", | 473 | "INSERT INTO feed_snapshots (feed, fetched_at, ok, body) VALUES ('swpc', ?1, 1, ?2) ON CONFLICT (feed) DO UPDATE SET fetched_at = ?1, ok = 1, body = ?2", |
| 471 | ).bind(now.toISOString(), JSON.stringify(w)).run(); | 474 | ).bind(now.toISOString(), JSON.stringify(w)).run(); |
| 472 | await sendAuroraAlerts(env, w, now); | 475 | await sendAuroraAlerts(env, w, await pollSolarWind(env, now), now); |
| 473 | } | 476 | } |
| 474 | 477 | ||
| 475 | async function sendAuroraAlerts(env: Env, w: SpaceWeather, now: Date): Promise<void> { | 478 | /** RTSW, reduced; the last good copy is kept on failure, and null is returned so no alert rests on old wind. */ |
| 476 | const kp = actionableKp(w.kpNow, w.forecast, now); | 479 | async function pollSolarWind(env: Env, now: Date): Promise<SolarWind | null> { |
| 480 | try { | ||
| 481 | const wind = await fetchSolarWind(now); | ||
| 482 | if (!wind) return null; | ||
| 483 | await env.DB.prepare("INSERT INTO feed_snapshots (feed, fetched_at, ok, body) VALUES ('rtsw', ?1, 1, ?2) ON CONFLICT (feed) DO UPDATE SET fetched_at = ?1, ok = 1, body = ?2") | ||
| 484 | .bind(now.toISOString(), JSON.stringify(wind)).run(); | ||
| 485 | return wind; | ||
| 486 | } catch (e) { | ||
| 487 | console.error("rtsw", String(e)); | ||
| 488 | await env.DB.prepare("INSERT INTO feed_snapshots (feed, fetched_at, ok) VALUES ('rtsw:error', ?1, 0) ON CONFLICT (feed) DO UPDATE SET fetched_at = ?1").bind(now.toISOString()).run(); | ||
| 489 | return null; | ||
| 490 | } | ||
| 491 | } | ||
| 492 | |||
| 493 | async function sendAuroraAlerts(env: Env, w: SpaceWeather, wind: SolarWind | null, now: Date): Promise<void> { | ||
| 494 | const forecastKp = actionableKp(w.kpNow, w.forecast, now); | ||
| 495 | const early = stormLikely(wind, now) && forecastKp < STORM_KP; | ||
| 496 | const kp = early ? STORM_KP : forecastKp; | ||
| 477 | const bandRows = await env.DB.prepare("SELECT DISTINCT band FROM devices WHERE aurora = 1").all<{ band: number }>(); | 497 | const bandRows = await env.DB.prepare("SELECT DISTINCT band FROM devices WHERE aurora = 1").all<{ band: number }>(); |
| 478 | const bands = alertBands(kp, bandRows.results.map((r) => r.band)); | 498 | const bands = alertBands(kp, bandRows.results.map((r) => r.band)); |
| 479 | if (!bands.length || !env.APNS_KEY) return; | 499 | if (!bands.length || !env.APNS_KEY) return; |
| @@ -485,7 +505,9 @@ async function sendAuroraAlerts(env: Env, w: SpaceWeather, now: Date): Promise<v | |||
| 485 | ).bind(JSON.stringify(bands), event).all<{ token: string; environment: string; band: number; utc_offset_minutes: number }>(); | 505 | ).bind(JSON.stringify(bands), event).all<{ token: string; environment: string; band: number; utc_offset_minutes: number }>(); |
| 486 | const due = devices.results.filter((d) => isNight(now, d.utc_offset_minutes)).map((d) => ({ ...d, event: `${d.token}:${event}` })); | 506 | const due = devices.results.filter((d) => isNight(now, d.utc_offset_minutes)).map((d) => ({ ...d, event: `${d.token}:${event}` })); |
| 487 | await sendAlerts(env, "aurora", due, now, (d) => ({ | 507 | await sendAlerts(env, "aurora", due, now, (d) => ({ |
| 488 | aps: { alert: { title: "Aurora possible tonight", body: `Kp ${kp.toFixed(1)}. Look toward the ${d.band >= 0 ? "north" : "south"} after dark.` }, sound: "default" }, | 508 | aps: { alert: { title: "Aurora possible tonight", body: early |
| 509 | ? `The solar wind has turned strongly south; aurora often follows within the hour. Look toward the ${d.band >= 0 ? "north" : "south"} after dark.` | ||
| 510 | : `Kp ${kp.toFixed(1)}. Look toward the ${d.band >= 0 ? "north" : "south"} after dark.` }, sound: "default" }, | ||
| 489 | })); | 511 | })); |
| 490 | } | 512 | } |
| 491 | 513 | ||
server/src/solarwind.ts added +89
| @@ -0,0 +1,89 @@ | |||
| 1 | // Real-time solar wind at L1 (SWPC RTSW: SOLAR-1, ACE or IMAP, whichever is active). The 1-minute files are | ||
| 2 | // about 1.5 and 2.5 MB; they are reduced here to 5-minute means over 6 hours for the app and the aurora rule. | ||
| 3 | import { USER_AGENT } from "./agent.ts"; | ||
| 4 | |||
| 5 | export const MAG_URL = "https://services.swpc.noaa.gov/json/rtsw/rtsw_mag_1m.json"; | ||
| 6 | export const WIND_URL = "https://services.swpc.noaa.gov/json/rtsw/rtsw_wind_1m.json"; | ||
| 7 | |||
| 8 | export interface SolarWindPoint { | ||
| 9 | /** Start of the 5-minute bin, ISO 8601. */ | ||
| 10 | t: string; | ||
| 11 | speed: number | null; | ||
| 12 | density: number | null; | ||
| 13 | bz: number | null; | ||
| 14 | bt: number | null; | ||
| 15 | } | ||
| 16 | |||
| 17 | export interface SolarWind { | ||
| 18 | observedAt: string; | ||
| 19 | source: string; | ||
| 20 | series: SolarWindPoint[]; | ||
| 21 | } | ||
| 22 | |||
| 23 | interface MagRow { time_tag: string; active: boolean; source: string; bz_gsm: number | null; bt: number | null } | ||
| 24 | interface WindRow { time_tag: string; active: boolean; source: string; proton_speed: number | null; proton_density: number | null } | ||
| 25 | |||
| 26 | const BIN = 5 * 60_000; | ||
| 27 | const HOURS = 6; | ||
| 28 | |||
| 29 | const mean = (xs: number[]) => (xs.length ? Math.round((xs.reduce((a, b) => a + b, 0) / xs.length) * 10) / 10 : null); | ||
| 30 | const ok = (v: number | null | undefined): v is number => typeof v === "number" && Number.isFinite(v); | ||
| 31 | |||
| 32 | export function reduce(mag: MagRow[], wind: WindRow[], now: Date): SolarWind | null { | ||
| 33 | const start = Math.floor((now.getTime() - HOURS * 3600_000) / BIN) * BIN; | ||
| 34 | const bins = new Map<number, { speed: number[]; density: number[]; bz: number[]; bt: number[] }>(); | ||
| 35 | const bin = (tag: string) => { | ||
| 36 | const t = Date.parse(tag + "Z"); | ||
| 37 | if (!(t >= start)) return undefined; | ||
| 38 | const k = Math.floor(t / BIN) * BIN; | ||
| 39 | if (!bins.has(k)) bins.set(k, { speed: [], density: [], bz: [], bt: [] }); | ||
| 40 | return bins.get(k)!; | ||
| 41 | }; | ||
| 42 | let observed = 0, source = ""; | ||
| 43 | for (const r of mag) { | ||
| 44 | if (!r.active) continue; | ||
| 45 | const b = bin(r.time_tag); | ||
| 46 | if (!b) continue; | ||
| 47 | if (ok(r.bz_gsm)) b.bz.push(r.bz_gsm); | ||
| 48 | if (ok(r.bt)) b.bt.push(r.bt); | ||
| 49 | const t = Date.parse(r.time_tag + "Z"); | ||
| 50 | if (t > observed) { observed = t; source = r.source; } | ||
| 51 | } | ||
| 52 | for (const r of wind) { | ||
| 53 | if (!r.active) continue; | ||
| 54 | const b = bin(r.time_tag); | ||
| 55 | if (!b) continue; | ||
| 56 | if (ok(r.proton_speed)) b.speed.push(r.proton_speed); | ||
| 57 | if (ok(r.proton_density)) b.density.push(r.proton_density); | ||
| 58 | } | ||
| 59 | if (!bins.size) return null; | ||
| 60 | const series = [...bins.entries()].sort((a, b) => a[0] - b[0]).map(([k, b]) => ({ | ||
| 61 | t: new Date(k).toISOString(), speed: mean(b.speed), density: mean(b.density), bz: mean(b.bz), bt: mean(b.bt), | ||
| 62 | })); | ||
| 63 | return { observedAt: new Date(observed).toISOString(), source, series }; | ||
| 64 | } | ||
| 65 | |||
| 66 | /** | ||
| 67 | * Southward field strong enough, for long enough, that aurora usually follows within the hour (the wind takes | ||
| 68 | * about 30 to 60 minutes from L1): the last 30 minutes average Bz ≤ −10 nT and speed ≥ 450 km/s. | ||
| 69 | * A rule of thumb, not a forecast; it raises alerts to the bands that see aurora at Kp 6. | ||
| 70 | */ | ||
| 71 | export function stormLikely(w: SolarWind | null, now: Date): boolean { | ||
| 72 | if (!w) return false; | ||
| 73 | const recent = w.series.filter((p) => Date.parse(p.t) >= now.getTime() - 30 * 60_000); | ||
| 74 | const bz = recent.map((p) => p.bz).filter(ok), speed = recent.map((p) => p.speed).filter(ok); | ||
| 75 | if (bz.length < 4 || speed.length < 4) return false; | ||
| 76 | return mean(bz)! <= -10 && mean(speed)! >= 450; | ||
| 77 | } | ||
| 78 | |||
| 79 | export const STORM_KP = 6; | ||
| 80 | |||
| 81 | export async function fetchSolarWind(now: Date): Promise<SolarWind | null> { | ||
| 82 | const headers = { "user-agent": USER_AGENT }; | ||
| 83 | const m = await fetch(MAG_URL, { headers }); | ||
| 84 | if (!m.ok) throw new Error(`RTSW mag ${m.status}`); | ||
| 85 | const mag = (await m.json()) as MagRow[]; | ||
| 86 | const w = await fetch(WIND_URL, { headers }); | ||
| 87 | if (!w.ok) throw new Error(`RTSW wind ${w.status}`); | ||
| 88 | return reduce(mag, (await w.json()) as WindRow[], now); | ||
| 89 | } | ||
server/test/solarwind.test.ts added +26
| @@ -0,0 +1,26 @@ | |||
| 1 | import assert from "node:assert/strict"; | ||
| 2 | import { test } from "node:test"; | ||
| 3 | import { reduce, stormLikely } from "../src/solarwind.ts"; | ||
| 4 | |||
| 5 | const now = new Date("2026-10-22T06:00:00Z"); | ||
| 6 | const minutes = (n: number, f: (i: number) => object) => | ||
| 7 | Array.from({ length: n }, (_, i) => ({ time_tag: new Date(now.getTime() - (n - i) * 60_000).toISOString().slice(0, 19), active: true, source: "SOLAR1", ...f(i) })); | ||
| 8 | |||
| 9 | test("reduces 1-minute rows to 5-minute means from the active spacecraft", () => { | ||
| 10 | const mag = [...minutes(60, () => ({ bz_gsm: -4, bt: 6 })), { time_tag: "2026-10-22T05:58:00", active: false, source: "ACE", bz_gsm: 50, bt: 50 }]; | ||
| 11 | const wind = minutes(60, (i) => ({ proton_speed: 400 + i, proton_density: 5 })); | ||
| 12 | const w = reduce(mag, wind, now)!; | ||
| 13 | assert.equal(w.source, "SOLAR1"); | ||
| 14 | assert.equal(w.series.length, 12); | ||
| 15 | assert.ok(w.series.every((p) => p.bz === -4 && p.bt === 6 && p.density === 5)); | ||
| 16 | assert.equal(w.series[0].speed, 402); | ||
| 17 | }); | ||
| 18 | |||
| 19 | test("storm likely only after 30 minutes of strong southward field and fast wind", () => { | ||
| 20 | const wind = minutes(60, () => ({ proton_speed: 520, proton_density: 8 })); | ||
| 21 | assert.equal(stormLikely(reduce(minutes(60, () => ({ bz_gsm: -12, bt: 14 })), wind, now), now), true); | ||
| 22 | assert.equal(stormLikely(reduce(minutes(60, () => ({ bz_gsm: -6, bt: 14 })), wind, now), now), false); | ||
| 23 | assert.equal(stormLikely(reduce(minutes(60, (i) => ({ bz_gsm: i < 45 ? 5 : -15, bt: 15 })), wind, now), now), false); | ||
| 24 | assert.equal(stormLikely(reduce(minutes(60, () => ({ bz_gsm: -12, bt: 14 })), minutes(60, () => ({ proton_speed: 380, proton_density: 8 })), now), now), false); | ||
| 25 | assert.equal(stormLikely(null, now), false); | ||
| 26 | }); | ||
server/test/worker.test.ts +25
| @@ -244,6 +244,31 @@ test("aurora alerts go out in bounded slices and are recorded per device once an | |||
| 244 | assert.deepEqual(push.state.sent, [token(3)]); | 244 | assert.deepEqual(push.state.sent, [token(3)]); |
| 245 | }); | 245 | }); |
| 246 | 246 | ||
| 247 | test("a strongly southward solar wind alerts the Kp 6 bands before Kp rises", async () => { | ||
| 248 | const { db, env } = await setup(); | ||
| 249 | device(db, 0, { band: 45 }); | ||
| 250 | const push = apns(); | ||
| 251 | let bz = -3; | ||
| 252 | const rows = (f: (m: number) => object) => Array.from({ length: 60 }, (_, m) => | ||
| 253 | ({ time_tag: new Date(Date.parse("2026-10-20T22:05:00Z") - (60 - m) * 60_000).toISOString().slice(0, 19), active: true, source: "SOLAR1", ...f(m) })); | ||
| 254 | const payloads: string[] = []; | ||
| 255 | network({ | ||
| 256 | ...push.handlers, | ||
| 257 | "api.push.apple.com": (url, init) => { payloads.push(String(init.body)); return push.handlers["api.push.apple.com"](url, init); }, | ||
| 258 | "services.swpc.noaa.gov": (url) => { | ||
| 259 | if (url.pathname.endsWith("rtsw_mag_1m.json")) return Response.json(rows(() => ({ bz_gsm: bz, bt: 14 }))); | ||
| 260 | if (url.pathname.endsWith("rtsw_wind_1m.json")) return Response.json(rows(() => ({ proton_speed: 540, proton_density: 9 }))); | ||
| 261 | return Response.json(url.pathname.includes("planetary_k_index_1m") ? [{ time_tag: "2026-10-20T22:00:00", estimated_kp: 2 }] : []); | ||
| 262 | }, | ||
| 263 | }); | ||
| 264 | await run(env, FIVE, "2026-10-20T22:05:00Z"); | ||
| 265 | assert.equal(push.state.sent.length, 0, "quiet wind, Kp 2"); | ||
| 266 | bz = -13; | ||
| 267 | await run(env, FIVE, "2026-10-20T22:05:00Z"); | ||
| 268 | assert.deepEqual(push.state.sent, [token(0)]); | ||
| 269 | assert.match(payloads.at(-1)!, /turned strongly south/); | ||
| 270 | }); | ||
| 271 | |||
| 247 | test("an aurora run cut short leaves the remaining devices for the next run", async () => { | 272 | test("an aurora run cut short leaves the remaining devices for the next run", async () => { |
| 248 | const { db, env } = await setup(); | 273 | const { db, env } = await setup(); |
| 249 | for (let i = 0; i < 5; i++) device(db, i); | 274 | for (let i = 0; i < 5; i++) device(db, i); |