Commit 69fc78ad7d
Unsigned
Layout: unified · split
App/Shared/StormActivity.swift added +32
| @@ -0,0 +1,32 @@ | ||
| 1 | import ActivityKit | |
| 2 | import Foundation | |
| 3 | ||
| 4 | /// Live Activity for a geomagnetic storm, updated over the storm's APNs broadcast channel. Shared by the app and | |
| 5 | /// the widget extension; `ContentState` matches server/src/storm.ts. | |
| 6 | struct StormActivityAttributes: ActivityAttributes { | |
| 7 | struct ContentState: Codable, Hashable { | |
| 8 | var kp: Double | |
| 9 | /// The higher of `kp` and the forecast for the 3-hour periods now and next. | |
| 10 | var expectedKp: Double | |
| 11 | /// A strongly southward solar wind: Kp usually rises within the hour. | |
| 12 | var early: Bool | |
| 13 | var bz: Double? | |
| 14 | var speed: Double? | |
| 15 | var updated: Date | |
| 16 | } | |
| 17 | ||
| 18 | var startedAt: Date | |
| 19 | } | |
| 20 | ||
| 21 | extension StormActivityAttributes.ContentState { | |
| 22 | /// NOAA G-scale: G1 at Kp 5 through G5 at Kp 9. | |
| 23 | static func scale(_ kp: Double) -> String? { | |
| 24 | kp >= 5 ? "G\(min(Int(kp.rounded(.down)) - 4, 5))" : nil | |
| 25 | } | |
| 26 | ||
| 27 | var headline: String { | |
| 28 | if let g = Self.scale(kp) { return "\(g) storm, Kp \(kp.formatted(.number.precision(.fractionLength(0...1))))" } | |
| 29 | if let g = Self.scale(expectedKp) { return "\(g) storm expected" } | |
| 30 | return early ? "Storm likely within the hour" : "Kp \(kp.formatted(.number.precision(.fractionLength(0...1))))" | |
| 31 | } | |
| 32 | } | |
App/Sources/SampleActivities.swift +6
| @@ -12,6 +12,7 @@ struct SampleActivitiesSection: View { | ||
| 12 | 12 | Button("Pass rising in 2 minutes") { startPass() } |
| 13 | 13 | Button("Launch at T−5 minutes") { startLaunch() } |
| 14 | 14 | Button("Eclipse, first contact in 3 minutes") { startEclipse() } |
| 15 | Button("G2 storm") { startStorm() } | |
| 15 | 16 | Button("End all sample activities", role: .destructive) { Task { await endAll() } } |
| 16 | 17 | if let message { |
| 17 | 18 | Text(message).font(.footnote).foregroundStyle(.secondary) |
| @@ -47,6 +48,11 @@ struct SampleActivitiesSection: View { | ||
| 47 | 48 | request(attributes, ActivityContent(state: .init(), staleDate: attributes.c4)) |
| 48 | 49 | } |
| 49 | 50 | |
| 51 | private func startStorm() { | |
| 52 | let state = StormActivityAttributes.ContentState(kp: 6.33, expectedKp: 7, early: false, bz: -14, speed: 640, updated: .now) | |
| 53 | request(StormActivityAttributes(startedAt: .now), ActivityContent(state: state, staleDate: .now.addingTimeInterval(45 * 60))) | |
| 54 | } | |
| 55 | ||
| 50 | 56 | private func request<A: ActivityAttributes>(_ attributes: A, _ content: ActivityContent<A.ContentState>) { |
| 51 | 57 | guard ActivityAuthorizationInfo().areActivitiesEnabled else { |
| 52 | 58 | message = "Live Activities are turned off for Moonrise in Settings." |
App/Sources/StormFollowButton.swift added +63
| @@ -0,0 +1,63 @@ | ||
| 1 | import ActivityKit | |
| 2 | import Feeds | |
| 3 | import SwiftUI | |
| 4 | ||
| 5 | /// Follows a geomagnetic storm on the Lock Screen. Updates arrive on the storm's broadcast channel, so the | |
| 6 | /// server never learns who follows; the activity ends when the storm does, or after iOS's 8-hour limit. | |
| 7 | struct StormFollowButton: View { | |
| 8 | var storm: StormCoverage | |
| 9 | var ink: Color | |
| 10 | @State private var following = false | |
| 11 | @State private var message: String? | |
| 12 | ||
| 13 | #if DEBUG | |
| 14 | private let environment = "sandbox" | |
| 15 | #else | |
| 16 | private let environment = "production" | |
| 17 | #endif | |
| 18 | ||
| 19 | var body: some View { | |
| 20 | if let channel = storm.channels[environment] { | |
| 21 | VStack(alignment: .leading, spacing: 6) { | |
| 22 | Button { | |
| 23 | following ? unfollow() : follow(channel) | |
| 24 | } label: { | |
| 25 | Label(following ? "Stop following" : "Follow storm on Lock Screen", systemImage: following ? "bell.slash" : "bell") | |
| 26 | .font(.subheadline.weight(.medium)) | |
| 27 | .frame(maxWidth: .infinity) | |
| 28 | .padding(.vertical, 10) | |
| 29 | .overlay(RoundedRectangle(cornerRadius: 6).stroke(ink.opacity(0.5), lineWidth: 0.5)) | |
| 30 | } | |
| 31 | .buttonStyle(.plain) | |
| 32 | if let message { Text(message).font(.footnote).dimmed(0.75) } | |
| 33 | } | |
| 34 | .padding(.top, 12) | |
| 35 | .onAppear { following = Activity<StormActivityAttributes>.activities.contains { $0.activityState == .active } } | |
| 36 | } | |
| 37 | } | |
| 38 | ||
| 39 | private func follow(_ channel: String) { | |
| 40 | guard ActivityAuthorizationInfo().areActivitiesEnabled else { | |
| 41 | message = "Live Activities are turned off for Moonrise in Settings." | |
| 42 | return | |
| 43 | } | |
| 44 | let s = storm.state | |
| 45 | let state = StormActivityAttributes.ContentState(kp: s.kp, expectedKp: s.expectedKp, early: s.early, bz: s.bz, speed: s.speed, updated: .now) | |
| 46 | let content = ActivityContent(state: state, staleDate: .now.addingTimeInterval(45 * 60)) | |
| 47 | do { | |
| 48 | _ = try Activity.request(attributes: StormActivityAttributes(startedAt: storm.startedAt), content: content, pushType: .channel(channel)) | |
| 49 | following = true | |
| 50 | message = "Kp and the solar wind will update on the Lock Screen until the storm ends." | |
| 51 | } catch { | |
| 52 | message = "Couldn't follow the storm: \(error.localizedDescription)" | |
| 53 | } | |
| 54 | } | |
| 55 | ||
| 56 | private func unfollow() { | |
| 57 | Task { | |
| 58 | for a in Activity<StormActivityAttributes>.activities { await a.end(nil, dismissalPolicy: .immediate) } | |
| 59 | following = false | |
| 60 | message = nil | |
| 61 | } | |
| 62 | } | |
| 63 | } | |
App/Sources/SunScreen.swift +6 −1
| @@ -13,6 +13,7 @@ struct SunScreen: View { | ||
| 13 | 13 | @State private var picture: Picture? |
| 14 | 14 | @State private var imageFailed = false |
| 15 | 15 | @State private var solarWind: SolarWind? |
| 16 | @State private var storm: StormCoverage? | |
| 16 | 17 | @State private var regions: [SolarRegion] = [] |
| 17 | 18 | @State private var forecast: SunForecast? |
| 18 | 19 | @AppStorage("sunRegionLabels") private var regionLabels = true |
| @@ -75,7 +76,10 @@ struct SunScreen: View { | ||
| 75 | 76 | if let c = forecast?.cycle { |
| 76 | 77 | section("Solar cycle 25", note: "Monthly sunspot numbers since the cycle began in December 2019 (bars), smoothed (red), and NOAA's prediction with its range.") { CycleChart(cycle: c, ink: ink, accent: accent) } |
| 77 | 78 | } |
| 78 | section("Geomagnetic activity (Kp)", note: "How disturbed Earth's magnetic field is, from 0 (quiet) to 9. At 5 or more it is a storm and the aurora reaches lower latitudes.") { kpChart } | |
| 79 | section("Geomagnetic activity (Kp)", note: "How disturbed Earth's magnetic field is, from 0 (quiet) to 9. At 5 or more it is a storm and the aurora reaches lower latitudes.") { | |
| 80 | kpChart | |
| 81 | if let storm { StormFollowButton(storm: storm, ink: ink) } | |
| 82 | } | |
| 79 | 83 | |
| 80 | 84 | Text("The Sun as NASA's Solar Dynamics Observatory sees it now, and the space weather it sends our way: flares, magnetic storms and the aurora.") |
| 81 | 85 | .font(.footnote).dimmed(0.6).padding(.top, 24) |
| @@ -94,6 +98,7 @@ struct SunScreen: View { | ||
| 94 | 98 | private func load(force: Bool) async { |
| 95 | 99 | if data == nil { await show(SunFeeds.lastSaved()) } |
| 96 | 100 | if let apiBase { solarWind = (try? await SolarWind.fetch(base: apiBase)) ?? solarWind } |
| 101 | if let apiBase { do { storm = try await StormCoverage.fetch(base: apiBase) } catch {} } | |
| 97 | 102 | regions = (try? await SolarRegion.fetch()) ?? regions |
| 98 | 103 | if let apiBase { forecast = (try? await SunForecast.fetch(base: apiBase)) ?? forecast } |
| 99 | 104 | if force { imageID = .now } |
App/Widgets/MoonriseWidgets.swift +1
| @@ -21,6 +21,7 @@ struct MoonriseWidgets: WidgetBundle { | ||
| 21 | 21 | EventLiveActivity() |
| 22 | 22 | EclipseLiveActivity() |
| 23 | 23 | PassLiveActivity() |
| 24 | StormLiveActivity() | |
| 24 | 25 | #endif |
| 25 | 26 | } |
| 26 | 27 | } |
App/Widgets/StormLiveActivity.swift added +115
| @@ -0,0 +1,115 @@ | ||
| 1 | import ActivityKit | |
| 2 | import SwiftUI | |
| 3 | import WidgetKit | |
| 4 | ||
| 5 | struct StormLiveActivity: Widget { | |
| 6 | private let ink = Color(red: 0.95, green: 0.95, blue: 0.93) | |
| 7 | ||
| 8 | var body: some WidgetConfiguration { | |
| 9 | ActivityConfiguration(for: StormActivityAttributes.self) { context in | |
| 10 | StormActivityView(context: context) | |
| 11 | .foregroundStyle(ink) | |
| 12 | } dynamicIsland: { context in | |
| 13 | DynamicIsland { | |
| 14 | DynamicIslandExpandedRegion(.leading) { | |
| 15 | Text("Geomagnetic storm").font(.system(size: 14, weight: .medium)).lineLimit(1) | |
| 16 | } | |
| 17 | DynamicIslandExpandedRegion(.trailing) { | |
| 18 | Text(kp(context.state.kp)).font(.system(size: 14, weight: .medium).monospacedDigit()) | |
| 19 | } | |
| 20 | DynamicIslandExpandedRegion(.bottom) { | |
| 21 | VStack(alignment: .leading, spacing: 2) { | |
| 22 | Text(context.state.headline).font(.system(size: 12)) | |
| 23 | Text(wind(context.state)).font(.system(size: 12).monospacedDigit()).opacity(0.8) | |
| 24 | } | |
| 25 | .frame(maxWidth: .infinity, alignment: .leading) | |
| 26 | } | |
| 27 | } compactLeading: { | |
| 28 | Image(systemName: "sun.max.trianglebadge.exclamationmark") | |
| 29 | } compactTrailing: { | |
| 30 | Text(StormActivityAttributes.ContentState.scale(context.state.kp) ?? kp(context.state.kp)) | |
| 31 | .font(.system(size: 12, weight: .medium).monospacedDigit()) | |
| 32 | } minimal: { | |
| 33 | Image(systemName: "sun.max.trianglebadge.exclamationmark") | |
| 34 | } | |
| 35 | } | |
| 36 | .supplementalActivityFamilies([.small]) | |
| 37 | } | |
| 38 | } | |
| 39 | ||
| 40 | private func kp(_ v: Double) -> String { "Kp \(v.formatted(.number.precision(.fractionLength(0...1))))" } | |
| 41 | ||
| 42 | /// Latest Bz and speed at L1; empty when the solar wind feed is down. | |
| 43 | private func wind(_ s: StormActivityAttributes.ContentState) -> String { | |
| 44 | [s.bz.map { "Bz \(Int($0.rounded())) nT" }, s.speed.map { "\(Int($0.rounded())) km/s" }].compactMap { $0 }.joined(separator: " · ") | |
| 45 | } | |
| 46 | ||
| 47 | private struct StormActivityView: View { | |
| 48 | @Environment(\.activityFamily) private var family | |
| 49 | @Environment(\.isActivityFullscreen) private var fullscreen | |
| 50 | var context: ActivityViewContext<StormActivityAttributes> | |
| 51 | ||
| 52 | private var state: StormActivityAttributes.ContentState { context.state } | |
| 53 | ||
| 54 | var body: some View { | |
| 55 | Group { | |
| 56 | if family == .small { small } else { medium } | |
| 57 | } | |
| 58 | // StandBy: black, to blend with the clock face. | |
| 59 | .activityBackgroundTint(fullscreen ? .black : Color(red: 0.043, green: 0.078, blue: 0.141)) | |
| 60 | } | |
| 61 | ||
| 62 | /// Apple Watch Smart Stack and CarPlay. | |
| 63 | private var small: some View { | |
| 64 | VStack(alignment: .leading, spacing: 2) { | |
| 65 | Text("Geomagnetic storm").font(.system(size: 13, weight: .medium)).lineLimit(1) | |
| 66 | Text(StormActivityAttributes.ContentState.scale(state.kp).map { "\($0) · \(kp(state.kp))" } ?? kp(state.kp)) | |
| 67 | .font(.system(size: 17, weight: .medium).monospacedDigit()) | |
| 68 | } | |
| 69 | .frame(maxWidth: .infinity, alignment: .leading) | |
| 70 | .padding(12) | |
| 71 | } | |
| 72 | ||
| 73 | private var medium: some View { | |
| 74 | VStack(alignment: .leading, spacing: 6) { | |
| 75 | Text("Geomagnetic storm").font(.system(size: 11, weight: .medium)).textCase(.uppercase).tracking(0.6).opacity(0.8) | |
| 76 | Text(state.headline).font(.system(size: 17, weight: .medium)) | |
| 77 | if state.expectedKp > state.kp, StormActivityAttributes.ContentState.scale(state.kp) != nil { | |
| 78 | Text("Up to \(kp(state.expectedKp)) in the next 3 hours").font(.system(size: 13)) | |
| 79 | } | |
| 80 | HStack { | |
| 81 | Text(wind(state)).font(.system(size: 12).monospacedDigit()).opacity(0.8) | |
| 82 | Spacer() | |
| 83 | Group { | |
| 84 | if context.isStale { | |
| 85 | Text("No update since \(state.updated.formatted(date: .omitted, time: .shortened))") | |
| 86 | } else { | |
| 87 | Text("Updated \(state.updated, style: .relative) ago") | |
| 88 | } | |
| 89 | } | |
| 90 | .font(.system(size: 12)).opacity(0.8) | |
| 91 | } | |
| 92 | } | |
| 93 | .padding(16) | |
| 94 | } | |
| 95 | } | |
| 96 | ||
| 97 | #if DEBUG | |
| 98 | private extension StormActivityAttributes.ContentState { | |
| 99 | static var g2: Self { .init(kp: 6.33, expectedKp: 7, early: false, bz: -14.2, speed: 640, updated: .now.addingTimeInterval(-300)) } | |
| 100 | static var early: Self { .init(kp: 3.67, expectedKp: 4, early: true, bz: -11, speed: 520, updated: .now) } | |
| 101 | } | |
| 102 | ||
| 103 | #Preview("Lock Screen", as: .content, using: StormActivityAttributes(startedAt: .now.addingTimeInterval(-7200))) { | |
| 104 | StormLiveActivity() | |
| 105 | } contentStates: { | |
| 106 | StormActivityAttributes.ContentState.g2 | |
| 107 | StormActivityAttributes.ContentState.early | |
| 108 | } | |
| 109 | ||
| 110 | #Preview("Expanded", as: .dynamicIsland(.expanded), using: StormActivityAttributes(startedAt: .now)) { | |
| 111 | StormLiveActivity() | |
| 112 | } contentStates: { | |
| 113 | StormActivityAttributes.ContentState.g2 | |
| 114 | } | |
| 115 | #endif | |
PLAN.org +4
| @@ -573,6 +573,10 @@ Worker; DSN Now freshness; NASA/ESA image licences; 26 LoC plates bundled. | ||
| 573 | 573 | |
| 574 | 574 | ** v5.5: Live Activities |
| 575 | 575 | - Geomagnetic storm and meteor shower peak Live Activities. |
| 576 | Done (storm): a broadcast channel pair per storm (Kp 5 now or within 3 | |
| 577 | hours, or a strongly southward wind), updated on each change of G level | |
| 578 | and every 30 minutes, ended after 3 calm hours; =/v1/today.storm= names | |
| 579 | the channels; Follow on the Sun tab's Kp section. | |
| 576 | 580 | - Push-to-start for followed launches: needs per-device tokens stored on the |
| 577 | 581 | Worker, a privacy policy change and a matching App Store privacy label. |
| 578 | 582 | |
Packages/MoonriseKit/Sources/Feeds/Storm.swift added +38
| @@ -0,0 +1,38 @@ | ||
| 1 | import Foundation | |
| 2 | ||
| 3 | /// A geomagnetic storm the backend is broadcasting Live Activity updates for: the `storm` object of /v1/today, | |
| 4 | /// nil when there is none. | |
| 5 | public struct StormCoverage: Sendable, Equatable, Decodable { | |
| 6 | public struct State: Sendable, Equatable, Decodable { | |
| 7 | public var kp: Double | |
| 8 | /// The higher of `kp` and the forecast for the 3-hour periods now and next. | |
| 9 | public var expectedKp: Double | |
| 10 | /// Bz at or below −10 nT with a fast wind for 30 minutes: Kp usually rises within the hour. | |
| 11 | public var early: Bool | |
| 12 | public var bz: Double? | |
| 13 | public var speed: Double? | |
| 14 | } | |
| 15 | ||
| 16 | public var startedAt: Date | |
| 17 | /// APNs broadcast channel by environment ("sandbox", "production"). | |
| 18 | public var channels: [String: String] | |
| 19 | /// As last broadcast. | |
| 20 | public var state: State | |
| 21 | ||
| 22 | static func decodeToday(_ data: Data) throws -> StormCoverage? { | |
| 23 | struct Today: Decodable { var storm: StormCoverage? } | |
| 24 | let d = JSONDecoder() | |
| 25 | d.dateDecodingStrategy = .custom { decoder in | |
| 26 | let s = try decoder.singleValueContainer().decode(String.self) | |
| 27 | guard let date = try? Date(s, strategy: Date.ISO8601FormatStyle(includingFractionalSeconds: true)) else { | |
| 28 | throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "bad date \(s)")) | |
| 29 | } | |
| 30 | return date | |
| 31 | } | |
| 32 | return try d.decode(Today.self, from: data).storm | |
| 33 | } | |
| 34 | ||
| 35 | public static func fetch(base: URL, session: URLSession = .shared) async throws -> StormCoverage? { | |
| 36 | try decodeToday(await session.data(from: base.appending(path: "v1/today")).0) | |
| 37 | } | |
| 38 | } | |
Packages/MoonriseKit/Tests/FeedsTests/SpaceWeatherTests.swift +10
| @@ -45,6 +45,16 @@ let forecast = Data(""" | ||
| 45 | 45 | #expect(try SolarWind.decodeToday(Data(#"{"spaceWeather":null}"#.utf8)) == nil) |
| 46 | 46 | } |
| 47 | 47 | |
| 48 | @Test func decodesBackendStorm() throws { | |
| 49 | let data = Data(#"{"spaceWeather":null,"solarWind":null,"storm":{"startedAt":"2026-10-20T22:00:00.000Z","channels":{"sandbox":"c1","production":"c2"},"state":{"kp":5.33,"expectedKp":5.67,"early":false,"bz":null,"speed":610}}}"#.utf8) | |
| 50 | let s = try #require(try StormCoverage.decodeToday(data)) | |
| 51 | #expect(s.channels["production"] == "c2") | |
| 52 | #expect(s.state.expectedKp == 5.67) | |
| 53 | #expect(s.state.bz == nil) | |
| 54 | #expect(s.startedAt == (try Date("2026-10-20T22:00:00Z", strategy: .iso8601))) | |
| 55 | #expect(try StormCoverage.decodeToday(Data(#"{"spaceWeather":null,"storm":null}"#.utf8)) == nil) | |
| 56 | } | |
| 57 | ||
| 48 | 58 | @Test func decodesBackendSun() throws { |
| 49 | 59 | let data = Data(#"{"enlil":{"fetchedAt":"x","points":[{"t":"2026-10-22T00:00:00.000Z","speed":410,"density":5,"cloud":false}]},"ccor2":{"fetchedAt":"x","frames":[{"t":"2026-10-22T03:30:00.000Z","url":"https://services.swpc.noaa.gov/images/animations/ccor2/20261022_0330_ccor2_1024by960.jpg"}]},"cycle":{"fetchedAt":null,"months":null}}"#.utf8) |
| 50 | 60 | let s = try SunForecast.decode(data) |
server/migrations/0007_storm_channels.sql added +11
| @@ -0,0 +1,11 @@ | ||
| 1 | -- APNs broadcast channels for geomagnetic storm Live Activities, one per storm and APNs environment. | |
| 2 | -- active_at is the last time the storm rule held; sent is the StormState last broadcast, as JSON. | |
| 3 | CREATE TABLE storm_channels ( | |
| 4 | channel_id TEXT PRIMARY KEY, | |
| 5 | environment TEXT NOT NULL, | |
| 6 | started_at TEXT NOT NULL, | |
| 7 | active_at TEXT NOT NULL, | |
| 8 | sent TEXT, | |
| 9 | sent_at TEXT, | |
| 10 | ended_at TEXT | |
| 11 | ); | |
server/src/index.ts +62 −1
| @@ -7,6 +7,7 @@ import { fetchLaunch, fetchLaunches, PREVIOUS_URL, throttleSeconds, Throttled, U | ||
| 7 | 7 | import { digestPayload, dueOffsets, fetchLatest, localDate, pickHeadlines, type Article } from "./news"; |
| 8 | 8 | import { fetchSolarWind, STORM_KP, stormLikely, type SolarWind } from "./solarwind"; |
| 9 | 9 | import { fetchSmallBodies } from "./smallbodies"; |
| 10 | import { CALM_MS, stormActive, stormEnd, stormUpdate, type StormPush, type StormState } from "./storm"; | |
| 10 | 11 | import { fetchCcor2, fetchCycle, fetchEnlil } from "./sun"; |
| 11 | 12 | import { fetchSpaceWeather, next24h, type SpaceWeather } from "./swpc"; |
| 12 | 13 | |
| @@ -126,9 +127,17 @@ async function today(env: Env, now: Date): Promise<Response> { | ||
| 126 | 127 | const w = JSON.parse(row.body) as SpaceWeather; |
| 127 | 128 | w.forecast = w.forecast.map((f) => ({ ...f, start: new Date(f.start) })); |
| 128 | 129 | const wind = await env.DB.prepare("SELECT body FROM feed_snapshots WHERE feed = 'rtsw' AND ok = 1").first<{ body: string }>(); |
| 130 | const storm = await env.DB.prepare("SELECT channel_id, environment, started_at, sent FROM storm_channels WHERE ended_at IS NULL AND sent IS NOT NULL") | |
| 131 | .all<{ channel_id: string; environment: string; started_at: string; sent: string }>(); | |
| 129 | 132 | return json({ |
| 130 | 133 | spaceWeather: { kpNow: w.kpNow, observedAt: w.observedAt, kpNext24h: next24h(w, now), fetchedAt: row.fetched_at }, |
| 131 | 134 | solarWind: wind ? JSON.parse(wind.body) : null, |
| 135 | // The storm Live Activity's channel for each APNs environment and the state last broadcast on it. | |
| 136 | storm: storm.results.length ? { | |
| 137 | startedAt: storm.results[0].started_at, | |
| 138 | channels: Object.fromEntries(storm.results.map((c) => [c.environment, c.channel_id])), | |
| 139 | state: JSON.parse(storm.results[0].sent), | |
| 140 | } : null, | |
| 132 | 141 | }, 200, MAX_AGE.today); |
| 133 | 142 | } |
| 134 | 143 | |
| @@ -491,7 +500,59 @@ async function pollSpaceWeather(env: Env, now: Date): Promise<void> { | ||
| 491 | 500 | await env.DB.prepare( |
| 492 | 501 | "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", |
| 493 | 502 | ).bind(now.toISOString(), JSON.stringify(w)).run(); |
| 494 | await sendAuroraAlerts(env, w, await pollSolarWind(env, now), now); | |
| 503 | const wind = await pollSolarWind(env, now); | |
| 504 | await sendAuroraAlerts(env, w, wind, now); | |
| 505 | await stormChannels(env, { | |
| 506 | kp: w.kpNow, expectedKp: actionableKp(w.kpNow, w.forecast, now), early: stormLikely(wind, now), | |
| 507 | bz: wind?.series.findLast((p) => p.bz !== null)?.bz ?? null, speed: wind?.series.findLast((p) => p.speed !== null)?.speed ?? null, | |
| 508 | }, now); | |
| 509 | } | |
| 510 | ||
| 511 | /** | |
| 512 | * Broadcast channels for the storm Live Activity: a pair (sandbox, production) opens when a storm starts, carries | |
| 513 | * its updates, and closes with an end message after 3 calm hours. Channels are deleted once that message expires. | |
| 514 | */ | |
| 515 | async function stormChannels(env: Env, state: StormState, now: Date): Promise<void> { | |
| 516 | if (!env.APNS_KEY) return; | |
| 517 | const config: ApnsConfig = { keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC }; | |
| 518 | const iso = now.toISOString(); | |
| 519 | const active = stormActive(state); | |
| 520 | let open = (await env.DB.prepare("SELECT channel_id, environment, active_at, sent, sent_at FROM storm_channels WHERE ended_at IS NULL") | |
| 521 | .all<{ channel_id: string; environment: string; active_at: string; sent: string | null; sent_at: string | null }>()).results; | |
| 522 | if (!open.length && active && env.APNS_MANAGE_CHANNELS === "1") { | |
| 523 | for (const environment of ["sandbox", "production"]) { | |
| 524 | const c = await createChannel(config, environment === "sandbox"); | |
| 525 | if (!c.channelId) { | |
| 526 | console.error("apns storm channel", c.status, c.reason); | |
| 527 | continue; | |
| 528 | } | |
| 529 | await env.DB.prepare("INSERT INTO storm_channels (channel_id, environment, started_at, active_at) VALUES (?1, ?2, ?3, ?3)").bind(c.channelId, environment, iso).run(); | |
| 530 | open.push({ channel_id: c.channelId, environment, active_at: iso, sent: null, sent_at: null }); | |
| 531 | } | |
| 532 | } | |
| 533 | for (const c of open) { | |
| 534 | const end = !active && now.getTime() - Date.parse(c.active_at) >= CALM_MS; | |
| 535 | const push: StormPush | null = end ? stormEnd(state, now) | |
| 536 | : stormUpdate(c.sent && c.sent_at ? { state: JSON.parse(c.sent), at: new Date(c.sent_at) } : null, state, now); | |
| 537 | if (active) await env.DB.prepare("UPDATE storm_channels SET active_at = ?2 WHERE channel_id = ?1").bind(c.channel_id, iso).run(); | |
| 538 | if (!push) continue; | |
| 539 | const r = await broadcast(config, c.channel_id, push.payload, c.environment === "sandbox", push.priority, Math.floor(now.getTime() / 1000) + 8 * 3600) | |
| 540 | .catch((e) => ({ status: 0, reason: String(e) })); | |
| 541 | if (r.status !== 200) { | |
| 542 | console.error("apns storm broadcast", r.status, r.reason); | |
| 543 | continue; | |
| 544 | } | |
| 545 | await env.DB.prepare("UPDATE storm_channels SET sent = ?2, sent_at = ?3, ended_at = ?4 WHERE channel_id = ?1") | |
| 546 | .bind(c.channel_id, JSON.stringify(state), iso, end ? iso : null).run(); | |
| 547 | } | |
| 548 | if (env.APNS_MANAGE_CHANNELS !== "1") return; | |
| 549 | const done = await env.DB.prepare("SELECT channel_id, environment FROM storm_channels WHERE ended_at < ?1") | |
| 550 | .bind(new Date(now.getTime() - 8 * 3600_000).toISOString()).all<{ channel_id: string; environment: string }>(); | |
| 551 | for (const c of done.results) { | |
| 552 | const r = await deleteChannel(config, c.channel_id, c.environment === "sandbox"); | |
| 553 | if (r.status === 204 || r.status === 404) await env.DB.prepare("DELETE FROM storm_channels WHERE channel_id = ?1").bind(c.channel_id).run(); | |
| 554 | else console.error("apns storm channel delete", r.status, r.reason); | |
| 555 | } | |
| 495 | 556 | } |
| 496 | 557 | |
| 497 | 558 | /** RTSW, reduced; the last good copy is kept on failure, and null is returned so no alert rests on old wind. */ |
server/src/storm.ts added +64
| @@ -0,0 +1,64 @@ | ||
| 1 | // Geomagnetic storm Live Activity updates over APNs broadcast channels: one channel per storm and environment, | |
| 2 | // so a follower never receives the end message of an earlier storm and the server never learns who follows. | |
| 3 | ||
| 4 | const MINUTE = 60_000; | |
| 5 | /** Seconds between the Unix epoch and 2001-01-01, the reference date of Swift's default Date coding. */ | |
| 6 | const REFERENCE_DATE = 978_307_200; | |
| 7 | /** G1. */ | |
| 8 | export const STORM_START_KP = 5; | |
| 9 | /** A storm ends after this long without Kp 5, a forecast of it within 3 hours, or a strongly southward wind. */ | |
| 10 | export const CALM_MS = 3 * 60 * MINUTE; | |
| 11 | /** Updates without a change go out this often, to refresh the solar wind and the stale date. */ | |
| 12 | const REFRESH_MS = 30 * MINUTE; | |
| 13 | const STALE_MS = 45 * MINUTE; | |
| 14 | ||
| 15 | export interface StormState { | |
| 16 | /** Latest 1-minute estimated Kp. */ | |
| 17 | kp: number; | |
| 18 | /** The higher of `kp` and the forecast for the 3-hour periods now and next. */ | |
| 19 | expectedKp: number; | |
| 20 | /** Bz at or below −10 nT and speed at or above 450 km/s for 30 minutes. */ | |
| 21 | early: boolean; | |
| 22 | bz: number | null; | |
| 23 | speed: number | null; | |
| 24 | } | |
| 25 | ||
| 26 | export interface StormPush { | |
| 27 | payload: { aps: Record<string, unknown> }; | |
| 28 | priority: 5 | 10; | |
| 29 | } | |
| 30 | ||
| 31 | const unix = (ms: number) => Math.floor(ms / 1000); | |
| 32 | const scale = (kp: number) => (kp >= STORM_START_KP ? Math.min(Math.floor(kp) - 4, 5) : 0); | |
| 33 | ||
| 34 | export const stormActive = (s: StormState) => s.expectedKp >= STORM_START_KP || s.early; | |
| 35 | ||
| 36 | /** Matches StormActivityAttributes.ContentState, decoded with Swift's default strategies; null values are left out. */ | |
| 37 | export function contentState(s: StormState, now: Date): Record<string, unknown> { | |
| 38 | const c: Record<string, unknown> = { kp: s.kp, expectedKp: s.expectedKp, early: s.early, updated: unix(now.getTime()) - REFERENCE_DATE }; | |
| 39 | if (s.bz !== null) c.bz = s.bz; | |
| 40 | if (s.speed !== null) c.speed = s.speed; | |
| 41 | return c; | |
| 42 | } | |
| 43 | ||
| 44 | /** | |
| 45 | * The update for the current state, or null when the last one sent still stands: a change of G level (now or | |
| 46 | * expected) or of the early warning goes at once, anything else every 30 minutes. A rise goes at priority 10. | |
| 47 | */ | |
| 48 | export function stormUpdate(sent: { state: StormState; at: Date } | null, current: StormState, now: Date): StormPush | null { | |
| 49 | const rose = !sent || scale(current.kp) > scale(sent.state.kp) || scale(current.expectedKp) > scale(sent.state.expectedKp) || (current.early && !sent.state.early); | |
| 50 | const changed = rose || scale(current.kp) !== scale(sent!.state.kp) || scale(current.expectedKp) !== scale(sent!.state.expectedKp) || current.early !== sent!.state.early; | |
| 51 | if (!changed && now.getTime() - sent!.at.getTime() < REFRESH_MS) return null; | |
| 52 | return { | |
| 53 | payload: { aps: { timestamp: unix(now.getTime()), event: "update", "content-state": contentState(current, now), "stale-date": unix(now.getTime() + STALE_MS) } }, | |
| 54 | priority: rose ? 10 : 5, | |
| 55 | }; | |
| 56 | } | |
| 57 | ||
| 58 | /** The end of a storm, left on the Lock Screen for an hour. */ | |
| 59 | export function stormEnd(current: StormState, now: Date): StormPush { | |
| 60 | return { | |
| 61 | payload: { aps: { timestamp: unix(now.getTime()), event: "end", "content-state": contentState(current, now), "dismissal-date": unix(now.getTime() + 60 * MINUTE) } }, | |
| 62 | priority: 5, | |
| 63 | }; | |
| 64 | } | |
server/test/storm.test.ts added +41
| @@ -0,0 +1,41 @@ | ||
| 1 | import assert from "node:assert/strict"; | |
| 2 | import { test } from "node:test"; | |
| 3 | import { contentState, stormActive, stormEnd, stormUpdate, type StormState } from "../src/storm.ts"; | |
| 4 | ||
| 5 | const now = new Date("2026-10-20T22:00:00Z"); | |
| 6 | const unix = (iso: string) => Date.parse(iso) / 1000; | |
| 7 | const quiet: StormState = { kp: 3, expectedKp: 3.7, early: false, bz: -2, speed: 380 }; | |
| 8 | const g1: StormState = { kp: 5.3, expectedKp: 5.7, early: false, bz: -12.4, speed: 610 }; | |
| 9 | const at = (min: number) => new Date(now.getTime() + min * 60_000); | |
| 10 | ||
| 11 | test("a storm is Kp 5 now or expected within 3 hours, or a strongly southward wind", () => { | |
| 12 | assert.equal(stormActive(quiet), false); | |
| 13 | assert.equal(stormActive({ ...quiet, expectedKp: 5 }), true); | |
| 14 | assert.equal(stormActive({ ...quiet, early: true }), true); | |
| 15 | }); | |
| 16 | ||
| 17 | test("the content state uses Swift's reference date and leaves out missing wind", () => { | |
| 18 | assert.deepEqual(contentState(g1, now), { kp: 5.3, expectedKp: 5.7, early: false, updated: unix("2026-10-20T22:00:00Z") - 978_307_200, bz: -12.4, speed: 610 }); | |
| 19 | assert.deepEqual(Object.keys(contentState({ ...g1, bz: null, speed: null }, now)), ["kp", "expectedKp", "early", "updated"]); | |
| 20 | }); | |
| 21 | ||
| 22 | test("the first update and any rise in G level go at priority 10, with a 45-minute stale date", () => { | |
| 23 | const first = stormUpdate(null, g1, now)!; | |
| 24 | assert.equal(first.priority, 10); | |
| 25 | assert.equal(first.payload.aps.event, "update"); | |
| 26 | assert.equal(first.payload.aps["stale-date"], unix("2026-10-20T22:45:00Z")); | |
| 27 | assert.equal(stormUpdate({ state: g1, at: now }, { ...g1, kp: 6.3 }, at(5))!.priority, 10); | |
| 28 | assert.equal(stormUpdate({ state: quiet, at: now }, { ...quiet, early: true }, at(5))!.priority, 10); | |
| 29 | }); | |
| 30 | ||
| 31 | test("a fall in G level goes at priority 5; small changes wait for the 30-minute refresh", () => { | |
| 32 | assert.equal(stormUpdate({ state: g1, at: now }, { ...g1, kp: 4.7 }, at(5))!.priority, 5); | |
| 33 | assert.equal(stormUpdate({ state: g1, at: now }, { ...g1, kp: 5.7, bz: -4 }, at(29)), null); | |
| 34 | assert.equal(stormUpdate({ state: g1, at: now }, { ...g1, kp: 5.7, bz: -4 }, at(30))!.priority, 5); | |
| 35 | }); | |
| 36 | ||
| 37 | test("the end stays on the Lock Screen for an hour", () => { | |
| 38 | const end = stormEnd(quiet, now); | |
| 39 | assert.equal(end.payload.aps.event, "end"); | |
| 40 | assert.equal(end.payload.aps["dismissal-date"], unix("2026-10-20T23:00:00Z")); | |
| 41 | }); | |
server/test/worker.test.ts +42
| @@ -504,3 +504,45 @@ test("a list poll leaves unchanged launches alone; a tick without a poll runs th | ||
| 504 | 504 | assert.equal(count(db, "SELECT count(*) AS n FROM writes"), 2); |
| 505 | 505 | assert.deepEqual({ ...db.prepare("SELECT status, launch_designator FROM launches").get() }, { status: "TBC", launch_designator: "2026-232" }); |
| 506 | 506 | }); |
| 507 | ||
| 508 | test("a storm opens a channel pair, updates it, and ends it after 3 calm hours; /v1/today names the channels", async () => { | |
| 509 | const { db, env } = await setup({ APNS_MANAGE_CHANNELS: "1" }); | |
| 510 | const push = apns(); | |
| 511 | const managed: string[] = []; | |
| 512 | const bodies: string[] = []; | |
| 513 | let kp = 5.3; | |
| 514 | const manage: Handler = (_url, init) => { | |
| 515 | managed.push(String(init.method)); | |
| 516 | return new Response(null, { status: init.method === "DELETE" ? 204 : 201, headers: { "apns-channel-id": `storm-${managed.length}` } }); | |
| 517 | }; | |
| 518 | network({ | |
| 519 | ...push.handlers, | |
| 520 | "api.push.apple.com": (url, init) => { bodies.push(String(init.body)); return push.handlers["api.push.apple.com"](url, init); }, | |
| 521 | "api-manage-broadcast.push.apple.com": manage, | |
| 522 | "api-manage-broadcast.sandbox.push.apple.com": manage, | |
| 523 | "services.swpc.noaa.gov": (url) => | |
| 524 | Response.json(url.pathname.includes("planetary_k_index_1m") ? [{ time_tag: "2026-10-20T22:00:00", estimated_kp: kp }] : []), | |
| 525 | }); | |
| 526 | await run(env, FIVE, "2026-10-20T22:00:00Z"); | |
| 527 | assert.deepEqual(managed, ["POST", "POST"]); | |
| 528 | assert.equal(push.state.broadcasts, 2); | |
| 529 | const today = await (await worker.fetch(new Request("https://moonrise.krz.sh/v1/today"), env as never)).json() as { storm: { channels: Record<string, string>; state: { kp: number } } }; | |
| 530 | assert.deepEqual(today.storm.channels, { sandbox: "storm-1", production: "storm-2" }); | |
| 531 | assert.equal(today.storm.state.kp, 5.3); | |
| 532 | ||
| 533 | await run(env, FIVE, "2026-10-20T22:05:00Z"); | |
| 534 | assert.equal(push.state.broadcasts, 2, "no change within 30 minutes"); | |
| 535 | kp = 3; | |
| 536 | await run(env, FIVE, "2026-10-20T22:10:00Z"); | |
| 537 | assert.equal(push.state.broadcasts, 4, "fell below G1"); | |
| 538 | await run(env, FIVE, "2026-10-21T01:00:00Z"); | |
| 539 | assert.equal(count(db, "SELECT COUNT(*) AS n FROM storm_channels WHERE ended_at IS NULL"), 2, "calm for under 3 hours since 22:05"); | |
| 540 | await run(env, FIVE, "2026-10-21T01:05:00Z"); | |
| 541 | assert.match(bodies.at(-1)!, /"event":"end"/); | |
| 542 | assert.equal(count(db, "SELECT COUNT(*) AS n FROM storm_channels WHERE ended_at IS NULL"), 0); | |
| 543 | const after = await (await worker.fetch(new Request("https://moonrise.krz.sh/v1/today?x"), env as never)).json() as { storm: unknown }; | |
| 544 | assert.equal(after.storm, null); | |
| 545 | await run(env, FIVE, "2026-10-21T09:15:00Z"); | |
| 546 | assert.deepEqual(managed, ["POST", "POST", "DELETE", "DELETE"]); | |
| 547 | assert.equal(count(db, "SELECT COUNT(*) AS n FROM storm_channels"), 0); | |
| 548 | }); | |