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 8f340da1c6

8f340da1c6dc2c274c4993a27207d77ea2e6b662

parent: 9c11fdd1ee

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-23 01:35 UTC

Add Qlty config; bounds-check CBOR; split complex functions

- The App Attest CBOR decoder read lengths and strings past the end of
  its input as NaN and truncated slices; it now fails with "cbor
  truncated".
- make-skycultures.py: removed an unreachable second return in fetch.
- SkyEngine events, satellite passes and small-body positions, the
  ObservingLog parsers, SunSummary, the server's router, launch and storm
  channel handling, validators, CelesTrak composition, solar wind
  binning, and three asset scripts split into helpers. Events, passes and
  orbit positions are bit-identical to main over a grid of dates and
  observers; the log parsers over 6k generated files; the scripts against
  stubbed inputs.
- broadcast takes its delivery options as one object.
- Qlty: vendored Astronomy Engine excluded; return_statements and
  file_complexity disabled.

Layout: unified · split

.qlty/.gitignore added +7
@@ -0,0 +1,7 @@
1*
2!configs
3!configs/**
4!hooks
5!hooks/**
6!qlty.toml
7!.gitignore
.qlty/qlty.toml added +50
@@ -0,0 +1,50 @@
1config_version = "0"
2
3exclude_patterns = [
4 # Astronomy Engine, vendored (THIRD_PARTY.org).
5 "Packages/MoonriseKit/Sources/CAstronomy/**",
6 "**/vendor/**",
7 "**/node_modules/**",
8 "**/testdata/**",
9 "**/dist/**",
10 "**/.build/**",
11 "**/build/**",
12 "**/*.min.*",
13 "**/generated/**",
14 ".claude/**",
15 "**/Pods/**",
16]
17
18test_patterns = [
19 "**/test/**",
20 "**/tests/**",
21 "**/Tests/**",
22 "**/*_test.*",
23 "**/test_*.*",
24 "**/*.test.*",
25 "**/*Tests.swift",
26 "e2e/**",
27]
28
29[[source]]
30name = "default"
31default = true
32
33[[plugin]]
34name = "osv-scanner"
35
36[[plugin]]
37name = "trufflehog"
38
39# Early returns are guard clauses, which keep the happy path unindented.
40[smells.return_statements]
41enabled = false
42
43# Total file complexity is the sum of its functions, which function_complexity
44# already checks.
45[smells.file_complexity]
46enabled = false
47
48# Exhaustive switch-over-enum lookup tables share shape but not content.
49[language.swift.smells.duplication]
50filter_patterns = ["(import_declaration _)", "(switch_statement _)"]
App/Sources/EclipseDayScreen.swift +16 −10
@@ -104,20 +104,26 @@ struct EclipseDayScreen: View {
104104 if let cue = spoken, now.timeIntervalSince(cue.date) < 20 {
105105 Text(cue.text).font(.title3.weight(.medium)).foregroundStyle(cue.warning ? accent : ink)
106106 }
107 let upcoming = t.cues.filter { $0.date > now && Int($0.text) == nil }.prefix(3)
108 if !upcoming.isEmpty {
109 VStack(alignment: .leading, spacing: 4) {
110 ForEach(upcoming, id: \.date) { c in
111 HStack(alignment: .firstTextBaseline) {
112 Text("in \(clock(c.date.timeIntervalSince(now)))").monospacedDigit().dimmed(0.6).frame(width: 90, alignment: .leading)
113 Text(c.text).foregroundStyle(c.warning ? accent : ink).lineLimit(2)
114 }
107 upcomingCues(t, at: now)
108 }
109 .accessibilityElement(children: .combine)
110 }
111
112 /// The next three spoken cues that are not a count, each with the time until it.
113 @ViewBuilder
114 private func upcomingCues(_ t: EclipseTimeline, at now: Date) -> some View {
115 let upcoming = t.cues.filter { $0.date > now && Int($0.text) == nil }.prefix(3)
116 if !upcoming.isEmpty {
117 VStack(alignment: .leading, spacing: 4) {
118 ForEach(upcoming, id: \.date) { c in
119 HStack(alignment: .firstTextBaseline) {
120 Text("in \(clock(c.date.timeIntervalSince(now)))").monospacedDigit().dimmed(0.6).frame(width: 90, alignment: .leading)
121 Text(c.text).foregroundStyle(c.warning ? accent : ink).lineLimit(2)
115122 }
116123 }
117 .font(.footnote)
118124 }
125 .font(.footnote)
119126 }
120 .accessibilityElement(children: .combine)
121127 }
122128
123129 private func label(_ contact: String, _ t: EclipseTimeline) -> String {
App/Sources/EventsScreen.swift +34 −24
@@ -92,30 +92,9 @@ struct EventsScreen: View {
9292
9393 private func row(_ e: SkyEvent, link: Bool) -> some View {
9494 HStack(alignment: .top, spacing: 14) {
95 VStack(spacing: 0) {
96 Text(e.date.formatted(.dateTime.day())).font(.title2.weight(.medium).monospacedDigit())
97 Text(e.date.formatted(.dateTime.weekday(.abbreviated))).font(.caption2).textCase(.uppercase).foregroundStyle(ink.opacity(0.6))
98 }
99 .frame(width: 40)
100 VStack(alignment: .leading, spacing: 4) {
101 HStack(alignment: .firstTextBaseline, spacing: 6) {
102 Image(systemName: symbol(e.kind)).font(.subheadline).foregroundStyle(e.visibleHere == true ? accent : ink.opacity(0.7))
103 .accessibilityHidden(true)
104 Text(e.title).font(.body.weight(.medium))
105 }
106 Text(e.date.formatted(date: .omitted, time: .shortened)).font(.footnote.monospacedDigit()).foregroundStyle(ink.opacity(0.6))
107 if !e.detail.isEmpty { Text(e.detail).font(.footnote).foregroundStyle(ink.opacity(0.8)) }
108 if let o = outlooks[e.id] { OutlookLine(outlook: o).font(.footnote.monospacedDigit()) }
109 if let v = e.visibleHere {
110 HStack(spacing: 5) {
111 Circle().fill(v ? accent : ink.opacity(0.35)).frame(width: 6, height: 6)
112 Text(v ? "Visible from here" : "Not visible from here").font(.caption.weight(.medium))
113 .foregroundStyle(v ? ink : ink.opacity(0.6))
114 }
115 .padding(.top, 2)
116 }
117 }
118 .padding(.trailing, e.activityStart(now: .now) != nil ? 44 : 0)
95 dateColumn(e)
96 details(e)
97 .padding(.trailing, e.activityStart(now: .now) != nil ? 44 : 0)
11998 Spacer(minLength: 0)
12099 if link {
121100 Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(ink.opacity(0.4)).padding(.top, 6)
@@ -130,6 +109,37 @@ struct EventsScreen: View {
130109 }
131110 }
132111
112 private func dateColumn(_ e: SkyEvent) -> some View {
113 VStack(spacing: 0) {
114 Text(e.date.formatted(.dateTime.day())).font(.title2.weight(.medium).monospacedDigit())
115 Text(e.date.formatted(.dateTime.weekday(.abbreviated))).font(.caption2).textCase(.uppercase).foregroundStyle(ink.opacity(0.6))
116 }
117 .frame(width: 40)
118 }
119
120 private func details(_ e: SkyEvent) -> some View {
121 VStack(alignment: .leading, spacing: 4) {
122 HStack(alignment: .firstTextBaseline, spacing: 6) {
123 Image(systemName: symbol(e.kind)).font(.subheadline).foregroundStyle(e.visibleHere == true ? accent : ink.opacity(0.7))
124 .accessibilityHidden(true)
125 Text(e.title).font(.body.weight(.medium))
126 }
127 Text(e.date.formatted(date: .omitted, time: .shortened)).font(.footnote.monospacedDigit()).foregroundStyle(ink.opacity(0.6))
128 if !e.detail.isEmpty { Text(e.detail).font(.footnote).foregroundStyle(ink.opacity(0.8)) }
129 if let o = outlooks[e.id] { OutlookLine(outlook: o).font(.footnote.monospacedDigit()) }
130 if let v = e.visibleHere { visibility(v) }
131 }
132 }
133
134 private func visibility(_ v: Bool) -> some View {
135 HStack(spacing: 5) {
136 Circle().fill(v ? accent : ink.opacity(0.35)).frame(width: 6, height: 6)
137 Text(v ? "Visible from here" : "Not visible from here").font(.caption.weight(.medium))
138 .foregroundStyle(v ? ink : ink.opacity(0.6))
139 }
140 .padding(.top, 2)
141 }
142
133143 private func symbol(_ k: SkyEvent.Kind) -> String {
134144 switch k {
135145 case .moonPhase: "moonphase.full.moon"
App/Sources/SolarSystem3D.swift +29 −16
@@ -785,26 +785,39 @@ struct SolarSystem3DView: View {
785785 private func labels(size: CGSize) -> some View {
786786 ZStack {
787787 ForEach(labelled(size: size), id: \.marker.id) { item in
788 let m = item.marker
789 let isSelected = m.id == selected
790 let color: Color = isSelected ? accent : m.kind == .craft ? accent.opacity(0.9) : m.kind == .comet ? Color(red: 0.7, green: 0.85, blue: 1) : ink.opacity(m.kind == .moon ? 0.7 : 0.85)
791 ZStack {
792 if item.radius < 3, m.kind != .craft, m.kind != .comet {
793 Circle().stroke(isSelected ? accent : ink.opacity(0.6), lineWidth: 1.2).frame(width: 10, height: 10)
794 }
795 if item.showName {
796 Text(m.name).font(.caption2.weight(isSelected ? .semibold : .regular))
797 .foregroundStyle(color)
798 .shadow(color: .black, radius: 2)
799 .fixedSize()
800 .offset(y: -max(item.radius, 5) - 9)
801 }
802 }
803 .position(item.point)
788 label(item.marker, radius: item.radius, showName: item.showName)
789 .position(item.point)
790 }
791 }
792 }
793
794 /// A ring for a body too small to see, and its name when there is room for it.
795 private func label(_ m: SolarMarker, radius: CGFloat, showName: Bool) -> some View {
796 let isSelected = m.id == selected
797 return ZStack {
798 if radius < 3, m.kind != .craft, m.kind != .comet {
799 Circle().stroke(isSelected ? accent : ink.opacity(0.6), lineWidth: 1.2).frame(width: 10, height: 10)
800 }
801 if showName {
802 Text(m.name).font(.caption2.weight(isSelected ? .semibold : .regular))
803 .foregroundStyle(labelColor(m, isSelected: isSelected))
804 .shadow(color: .black, radius: 2)
805 .fixedSize()
806 .offset(y: -max(radius, 5) - 9)
804807 }
805808 }
806809 }
807810
811 private func labelColor(_ m: SolarMarker, isSelected: Bool) -> Color {
812 if isSelected { return accent }
813 switch m.kind {
814 case .craft: return accent.opacity(0.9)
815 case .comet: return Color(red: 0.7, green: 0.85, blue: 1)
816 case .moon: return ink.opacity(0.7)
817 default: return ink.opacity(0.85)
818 }
819 }
820
808821 private func tap(_ location: CGPoint, size: CGSize) {
809822 let hit = screenPoints(size: size)
810823 .map { ($0.marker.id, hypot($0.point.x - location.x, $0.point.y - location.y) - max($0.radius, 0)) }
Packages/MoonriseKit/Sources/Feeds/SunSummary.swift +26 −10
@@ -34,16 +34,8 @@ public enum SunSummary {
3434 return "\(name(g)) storm (G\(g)) \(when), Kp \(String(format: "%.1f", b.kp)). Aurora possible low in the \(sky) sky."
3535 }
3636 if current.g >= 1 {
37 let needed = Geomagnetic.kpNeeded(geomagneticLatitude: geomagneticLatitude)
38 var text = "\(name(current.g)) storm (G\(current.g))\(asOf)."
39 if needed > 9 {
40 text += " Aurora at your latitude would need more than Kp 9."
41 } else if needed > 5 {
42 text += " Aurora at your latitude needs Kp \(String(format: "%.1f", needed))."
43 } else if kp.contains(where: { overlaps($0.start, bar, night) }) {
44 text += " Kp is forecast below 5 after dark."
45 }
46 return text
37 let note = auroraNote(geomagneticLatitude: geomagneticLatitude, kp: kp, bar: bar, night: night)
38 return "\(name(current.g)) storm (G\(current.g))\(asOf).\(note)"
4739 }
4840
4941 // 2. Solar radiation storm.
@@ -60,6 +52,30 @@ public enum SunSummary {
6052 }
6153
6254 // 4. Quiet.
55 return quietText(storms: storms, probabilities: probabilities, at: now, time: time)
56 }
57
58 /// What aurora at this latitude would take, during a storm already under way.
59 private static func auroraNote(geomagneticLatitude: Double, kp: [KpBar], bar: TimeInterval, night: DateInterval) -> String {
60 let needed = Geomagnetic.kpNeeded(geomagneticLatitude: geomagneticLatitude)
61 if needed > 9 {
62 return " Aurora at your latitude would need more than Kp 9."
63 }
64 if needed > 5 {
65 return " Aurora at your latitude needs Kp \(String(format: "%.1f", needed))."
66 }
67 if kp.contains(where: { overlaps($0.start, bar, night) }) {
68 return " Kp is forecast below 5 after dark."
69 }
70 return ""
71 }
72
73 private static func quietText(
74 storms: [KpBar],
75 probabilities: SolarProbabilities?,
76 at now: Date,
77 time: (Date) -> String
78 ) -> String {
6379 if let next = storms.min(by: { $0.start < $1.start }), let g = SpaceWeather.gScale(next.kp) {
6480 return "Quiet now. \(name(g)) storm (G\(g)) forecast from \(time(next.start)), Kp \(String(format: "%.1f", next.kp))."
6581 }
Packages/MoonriseKit/Sources/ObservingLog/Equipment.swift +1 −13
@@ -103,19 +103,7 @@ public struct Equipment: Sendable, Identifiable, Equatable, Hashable {
103103 public init?(org text: String) {
104104 let lines = text.components(separatedBy: "\n")
105105 guard let head = lines.first, head.hasPrefix("* ") else { return nil }
106 var props: [String: String] = [:]
107 var other: [OrgProperty] = []
108 var i = 1
109 if i < lines.count, lines[i] == ":PROPERTIES:" {
110 i += 1
111 while i < lines.count, lines[i] != ":END:" {
112 if let p = OrgProperty.parse(lines[i]) {
113 if !Self.knownKeys.contains(p.key) { other.append(p) } else if !p.value.isEmpty { props[p.key] = p.value }
114 }
115 i += 1
116 }
117 i += 1
118 }
106 let (props, other, i) = OrgProperty.drawer(in: lines, at: 1, known: Self.knownKeys)
119107 guard let id = props[":ID:"] else { return nil }
120108 func leadingNumber(_ key: String) -> Double? {
121109 props[key].flatMap { Double($0.prefix { $0.isNumber || $0 == "." }) }
Packages/MoonriseKit/Sources/ObservingLog/Observation.swift +23 −13
@@ -13,6 +13,28 @@ public struct OrgProperty: Sendable, Equatable, Hashable {
1313
1414 var line: String { value.isEmpty ? key : "\(key) \(value)" }
1515
16 /// The `:PROPERTIES:` drawer at `lines[start]`, if there is one: values of the
17 /// `known` keys that are set, every other property in order, and the index
18 /// of the first line past the drawer.
19 static func drawer(
20 in lines: [String],
21 at start: Int,
22 known: Set<String>
23 ) -> (known: [String: String], other: [OrgProperty], next: Int) {
24 var props: [String: String] = [:]
25 var other: [OrgProperty] = []
26 var i = start
27 guard i < lines.count, lines[i] == ":PROPERTIES:" else { return (props, other, i) }
28 i += 1
29 while i < lines.count, lines[i] != ":END:" {
30 if let p = parse(lines[i]) {
31 if !known.contains(p.key) { other.append(p) } else if !p.value.isEmpty { props[p.key] = p.value }
32 }
33 i += 1
34 }
35 return (props, other, i + 1)
36 }
37
1638 /// Splits a drawer line into key and value; nil for lines that are not a property.
1739 static func parse(_ line: String) -> OrgProperty? {
1840 let parts = line.split(separator: " ", maxSplits: 1).map(String.init)
@@ -102,19 +124,7 @@ public struct Observation: Sendable, Identifiable, Equatable {
102124 let lines = text.components(separatedBy: "\n")
103125 guard let head = lines.first, head.hasPrefix("* "),
104126 lines.count > 1, lines[1].hasPrefix("["), lines[1].hasSuffix("]") else { return nil }
105 var props: [String: String] = [:]
106 var other: [OrgProperty] = []
107 var i = 2
108 if i < lines.count, lines[i] == ":PROPERTIES:" {
109 i += 1
110 while i < lines.count, lines[i] != ":END:" {
111 if let p = OrgProperty.parse(lines[i]) {
112 if !Self.knownKeys.contains(p.key) { other.append(p) } else if !p.value.isEmpty { props[p.key] = p.value }
113 }
114 i += 1
115 }
116 i += 1
117 }
127 let (props, other, i) = OrgProperty.drawer(in: lines, at: 2, known: Self.knownKeys)
118128 let offset = props[":UTC_OFFSET:"].flatMap(Self.offset)
119129 guard let date = try? Date(String(lines[1].dropFirst().dropLast()), strategy: Self.orgDate(offset.flatMap(TimeZone.init(secondsFromGMT:)) ?? .current).parseStrategy) else { return nil }
120130 let notes = lines.dropFirst(i).joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines)
Packages/MoonriseKit/Sources/ObservingLog/Programs.swift +54 −25
@@ -91,6 +91,18 @@ public struct ObservingProgram: Sendable, Identifiable, Equatable {
9191
9292 public var id: String { ids.first ?? CatalogResolver.fold(name) }
9393 var keys: [String] { ids.isEmpty ? [id] : ids }
94
95 /// Applies one drawer property from a program file.
96 mutating func apply(_ p: OrgProperty) {
97 switch p.key {
98 case ":CATALOG:":
99 ids = p.value.split(separator: " ").map { CatalogResolver.designation(String($0)) ?? String($0) }
100 if CatalogResolver.designation(name) == nil { aliases = [name] }
101 case ":RA:": ra = Double(p.value)
102 case ":DEC:": dec = Double(p.value)
103 default: break
104 }
105 }
94106 }
95107
96108 public var id: String
@@ -119,33 +131,12 @@ public struct ObservingProgram: Sendable, Identifiable, Equatable {
119131
120132 /// Parses a program file (format above). Names resolve against `resolver`.
121133 public init(org text: String, id: String, resolver: CatalogResolver = .messier) {
122 var title = id
123 var objects: [Object] = []
124 var inDrawer = false
134 var parser = ProgramFileParser(title: id, resolver: resolver)
125135 for line in text.components(separatedBy: "\n") {
126 if line.lowercased().hasPrefix("#+title:") {
127 title = line.dropFirst(8).trimmingCharacters(in: .whitespaces)
128 } else if line.hasPrefix("* ") {
129 let name = line.dropFirst(2).trimmingCharacters(in: .whitespaces)
130 let id = resolver.id(for: name)
131 objects.append(Object(ids: id.map { [$0] } ?? [], name: name, aliases: [], detail: ""))
132 inDrawer = false
133 } else if !objects.isEmpty, line.trimmingCharacters(in: .whitespaces) == ":PROPERTIES:" {
134 inDrawer = true
135 } else if inDrawer, line.trimmingCharacters(in: .whitespaces) == ":END:" {
136 inDrawer = false
137 } else if inDrawer, let p = OrgProperty.parse(line.trimmingCharacters(in: .whitespaces)) {
138 let i = objects.count - 1
139 switch p.key {
140 case ":CATALOG:":
141 objects[i].ids = p.value.split(separator: " ").map { CatalogResolver.designation(String($0)) ?? String($0) }
142 if CatalogResolver.designation(objects[i].name) == nil { objects[i].aliases = [objects[i].name] }
143 case ":RA:": objects[i].ra = Double(p.value)
144 case ":DEC:": objects[i].dec = Double(p.value)
145 default: break
146 }
147 }
136 parser.read(line)
148137 }
138 let title = parser.title
139 var objects = parser.objects
149140 for i in objects.indices where objects[i].ra == nil || objects[i].dec == nil {
150141 if let m = Self.messier.objects.first(where: { $0.id == objects[i].id }) {
151142 objects[i].ra = m.ra
@@ -188,3 +179,41 @@ public struct ProgramProgress: Sendable {
188179 self.first = first
189180 }
190181}
182
183/// Reads a program file line by line: its title, its headings, and their drawers.
184private struct ProgramFileParser {
185 var title: String
186 let resolver: CatalogResolver
187 var objects: [ObservingProgram.Object] = []
188 var inDrawer = false
189
190 init(title: String, resolver: CatalogResolver) {
191 self.title = title
192 self.resolver = resolver
193 }
194
195 mutating func read(_ line: String) {
196 let trimmed = line.trimmingCharacters(in: .whitespaces)
197 if line.lowercased().hasPrefix("#+title:") {
198 title = line.dropFirst(8).trimmingCharacters(in: .whitespaces)
199 return
200 }
201 if line.hasPrefix("* ") {
202 let name = line.dropFirst(2).trimmingCharacters(in: .whitespaces)
203 let id = resolver.id(for: name)
204 objects.append(ObservingProgram.Object(ids: id.map { [$0] } ?? [], name: name, aliases: [], detail: ""))
205 inDrawer = false
206 return
207 }
208 if !objects.isEmpty, trimmed == ":PROPERTIES:" {
209 inDrawer = true
210 return
211 }
212 guard inDrawer else { return }
213 if trimmed == ":END:" {
214 inDrawer = false
215 } else if let p = OrgProperty.parse(trimmed) {
216 objects[objects.count - 1].apply(p)
217 }
218 }
219}
Packages/MoonriseKit/Sources/SkyEngine/Events.swift +52 −10
@@ -90,9 +90,21 @@ extension SkyEngine {
9090 lock.lock()
9191 defer { lock.unlock() }
9292 let end = start.addingTimeInterval(days * 86_400)
93 var out: [SkyEvent] = []
93 let kinds = [
94 moonPhaseEvents(from: start, to: end, observer: observer),
95 lunarEclipseEvents(from: start, to: end, observer: observer),
96 solarEclipseEvents(from: start, to: end, observer: observer),
97 oppositionEvents(from: start, to: end, observer: observer),
98 elongationEvents(from: start, to: end, observer: observer),
99 seasonEvents(from: start, to: end, observer: observer),
100 meteorShowerEvents(from: start, to: end, observer: observer),
101 ]
102 return kinds.flatMap { $0 }.sorted { $0.date < $1.date }
103 }
94104
95 // Full and new moons
105 /// Full and new moons.
106 private static func moonPhaseEvents(from start: Date, to end: Date, observer: Observer) -> [SkyEvent] {
107 var out: [SkyEvent] = []
96108 var t = time(start)
97109 while true {
98110 let q = Astronomy_SearchMoonQuarter(t)
@@ -105,7 +117,12 @@ extension SkyEngine {
105117 t = Astronomy_AddDays(q.time, 1)
106118 }
107119
108 // Lunar eclipses
120 return out
121 }
122
123 /// Lunar eclipses.
124 private static func lunarEclipseEvents(from start: Date, to end: Date, observer: Observer) -> [SkyEvent] {
125 var out: [SkyEvent] = []
109126 var lunar = Astronomy_SearchLunarEclipse(time(start))
110127 while lunar.status == ASTRO_SUCCESS, date(lunar.peak) <= end {
111128 var peak = lunar.peak
@@ -118,7 +135,12 @@ extension SkyEngine {
118135 lunar = Astronomy_NextLunarEclipse(lunar.peak)
119136 }
120137
121 // Solar eclipses: global, with local circumstances for the observer
138 return out
139 }
140
141 /// Solar eclipses: global, with local circumstances for the observer.
142 private static func solarEclipseEvents(from start: Date, to end: Date, observer: Observer) -> [SkyEvent] {
143 var out: [SkyEvent] = []
122144 var local: [Date: astro_local_solar_eclipse_t] = [:]
123145 var l = Astronomy_SearchLocalSolarEclipse(time(start), observer.astro)
124146 while l.status == ASTRO_SUCCESS, date(l.peak.time) <= end {
@@ -146,14 +168,24 @@ extension SkyEngine {
146168 solar = Astronomy_NextGlobalSolarEclipse(solar.peak)
147169 }
148170
149 // Oppositions of the outer planets
171 return out
172 }
173
174 /// Oppositions of the outer planets.
175 private static func oppositionEvents(from start: Date, to end: Date, observer: Observer) -> [SkyEvent] {
176 var out: [SkyEvent] = []
150177 for body in [Body.mars, .jupiter, .saturn, .uranus, .neptune] {
151178 let r = Astronomy_SearchRelativeLongitude(body.astro, 0, time(start))
152179 guard r.status == ASTRO_SUCCESS, date(r.time) <= end else { continue }
153180 out.append(SkyEvent(kind: .opposition, date: date(r.time), title: "\(body.rawValue.capitalized) at opposition", detail: "Opposite the Sun: up all night and at its closest and brightest for the year.", visibleHere: nil))
154181 }
155182
156 // Greatest elongations of Mercury and Venus
183 return out
184 }
185
186 /// Greatest elongations of Mercury and Venus.
187 private static func elongationEvents(from start: Date, to end: Date, observer: Observer) -> [SkyEvent] {
188 var out: [SkyEvent] = []
157189 for body in [Body.mercury, .venus] {
158190 var from = time(start)
159191 while true {
@@ -165,7 +197,12 @@ extension SkyEngine {
165197 }
166198 }
167199
168 // Equinoxes and solstices
200 return out
201 }
202
203 /// Equinoxes and solstices.
204 private static func seasonEvents(from start: Date, to end: Date, observer: Observer) -> [SkyEvent] {
205 var out: [SkyEvent] = []
169206 let cal = Calendar(identifier: .gregorian)
170207 let y0 = cal.component(.year, from: start)
171208 for y in y0...(y0 + 1) {
@@ -177,7 +214,13 @@ extension SkyEngine {
177214 }
178215 }
179216
180 // Meteor showers, with darkness and the Moon on the observer's night of the peak
217 return out
218 }
219
220 /// Meteor showers, with darkness and the Moon on the observer's night of the peak.
221 private static func meteorShowerEvents(from start: Date, to end: Date, observer: Observer) -> [SkyEvent] {
222 var out: [SkyEvent] = []
223 let y0 = Calendar(identifier: .gregorian).component(.year, from: start)
181224 var utc = Calendar(identifier: .gregorian)
182225 utc.timeZone = TimeZone(identifier: "UTC")!
183226 for y in y0...(y0 + 1) {
@@ -196,7 +239,6 @@ extension SkyEngine {
196239 zhr: m.zhr, moonIllumination: lit))
197240 }
198241 }
199
200 return out.sorted { $0.date < $1.date }
242 return out
201243 }
202244}
Packages/MoonriseKit/Sources/SkyEngine/Passes.swift +37 −15
@@ -105,11 +105,42 @@ extension SkyEngine {
105105 return (perp * perp).sum().squareRoot() > 6378.135
106106 }
107107
108 /// A pass from its rise to the latest sample above the horizon.
109 private struct OpenPass {
110 var rise: Date, riseAz: Double, peak: Date, maxAlt: Double
111 var visible = false
112
113 /// Records a sample above the horizon; `lit` is asked only while the pass has not yet been seen high enough.
114 mutating func observe(altitude: Double, at t: Date, minAltitude: Double, lit: () -> Bool) {
115 if altitude > maxAlt { maxAlt = altitude; peak = t }
116 if !visible, altitude >= minAltitude, lit() { visible = true }
117 }
118
119 func pass(of elements: OrbitalElements, set: Date, setAzimuth: Double) -> SatellitePass {
120 SatellitePass(name: elements.OBJECT_NAME, rise: rise, set: set, peak: peak, maxAltitude: maxAlt, riseAzimuth: riseAz, setAzimuth: setAzimuth, visible: visible, featured: elements.isFeatured)
121 }
122 }
123
124 /// 20 s samples to advance from `altitude`: further the further below the horizon (see `passes(of:)`).
125 private static func samplesToSkip(below altitude: Double) -> Int {
126 altitude > -8 ? 1 : altitude > -30 ? 3 : 9
127 }
128
129 /// Whether a satellite at `r` is in sunlight while the observer's sky is past civil twilight.
130 private static func litInDarkSky(_ r: SIMD3<Double>, at t: Date, observer: Observer) -> Bool {
131 lock.lock()
132 defer { lock.unlock() }
133 var tt = time(t)
134 let sun = Astronomy_Equator(BODY_SUN, &tt, observer.astro, EQUATOR_OF_DATE, ABERRATION)
135 let sunAlt = Astronomy_Horizon(&tt, observer.astro, sun.ra, sun.dec, REFRACTION_NORMAL).altitude
136 return sunAlt < -6 && sunlit(r, sun: sunDirection(t))
137 }
138
108139 /// Passes above `minAltitude` in the next `hours`, sampled every 20 s from 8° below the horizon up.
109140 public static func passes(of elements: OrbitalElements, from start: Date, hours: Double = 72, observer: Observer, minAltitude: Double = 10) -> [SatellitePass] {
110141 guard let sgp = try? SGP4(elements) else { return [] }
111142 var out: [SatellitePass] = []
112 var current: (rise: Date, riseAz: Double, peak: Date, maxAlt: Double, visible: Bool)?
143 var current: OpenPass?
113144 var lastAz = 0.0
114145 var i = 0
115146 var t = start
@@ -118,28 +149,19 @@ extension SkyEngine {
118149 guard let r = sgp.position(at: t) else { break }
119150 let h = lookAngles(teme: r, at: t, from: observer)
120151 if h.altitude >= 0 {
121 if current == nil { current = (t, h.azimuth, t, h.altitude, false) }
122 if h.altitude > current!.maxAlt { current!.maxAlt = h.altitude; current!.peak = t }
123 if !current!.visible, h.altitude >= minAltitude {
124 lock.lock()
125 var tt = time(t)
126 let sun = Astronomy_Equator(BODY_SUN, &tt, observer.astro, EQUATOR_OF_DATE, ABERRATION)
127 let sunAlt = Astronomy_Horizon(&tt, observer.astro, sun.ra, sun.dec, REFRACTION_NORMAL).altitude
128 if sunAlt < -6, sunlit(r, sun: sunDirection(t)) { current!.visible = true }
129 lock.unlock()
130 }
152 var c = current ?? OpenPass(rise: t, riseAz: h.azimuth, peak: t, maxAlt: h.altitude)
153 c.observe(altitude: h.altitude, at: t, minAltitude: minAltitude) { litInDarkSky(r, at: t, observer: observer) }
154 current = c
131155 lastAz = h.azimuth
132156 } else if let c = current {
133 if c.maxAlt >= minAltitude {
134 out.append(SatellitePass(name: elements.OBJECT_NAME, rise: c.rise, set: t, peak: c.peak, maxAltitude: c.maxAlt, riseAzimuth: c.riseAz, setAzimuth: lastAz, visible: c.visible, featured: elements.isFeatured))
135 }
157 if c.maxAlt >= minAltitude { out.append(c.pass(of: elements, set: t, setAzimuth: lastAz)) }
136158 current = nil
137159 }
138160 // Below the horizon altitude changes no faster than the satellite moves around Earth's centre relative to the
139161 // observer: about 4°/min in low orbit, under 6.5°/min for any orbit above the surface. A 60 s step from below
140162 // -8° skips 40 s (at most 4.3°) and a 180 s step from below -30° skips 160 s (at most 17.3°), so no 20 s sample
141163 // at or above the horizon is skipped and the passes are those of plain 20 s steps.
142 i += h.altitude > -8 ? 1 : h.altitude > -30 ? 3 : 9
164 i += samplesToSkip(below: h.altitude)
143165 t = start.addingTimeInterval(Double(i) * 20)
144166 }
145167 return out
Packages/MoonriseKit/Sources/SkyEngine/SmallBody.swift +35 −27
@@ -30,33 +30,7 @@ public struct SmallBody: Sendable, Equatable, Codable, Identifiable {
3030 /// Heliocentric position in AU on J2000 ecliptic axes.
3131 public func position(at date: Date) -> SIMD3<Double> {
3232 let dt = date.timeIntervalSince1970 / 86_400 + 2_440_587.5 - tp
33 var x: Double, y: Double
34 if abs(e - 1) < 1e-4 {
35 // Barker's equation: s + s³/3 = k Δt / √(2q³), s = tan(ν/2).
36 let w = 3 * Self.k * dt / (2 * q * q * q).squareRoot()
37 let c = cbrt(w / 2 + (w * w / 4 + 1).squareRoot())
38 let s = c - 1 / c
39 (x, y) = (q * (1 - s * s), 2 * q * s)
40 } else if e < 1 {
41 let a = q / (1 - e), m = Self.k * dt / pow(a, 1.5)
42 let mm = remainder(m, 2 * .pi)
43 var E = e < 0.8 ? mm : .pi * (mm < 0 ? -1 : 1)
44 for _ in 0..<60 {
45 let d = (E - e * sin(E) - mm) / (1 - e * cos(E))
46 E -= d
47 if abs(d) < 1e-13 { break }
48 }
49 (x, y) = (a * (cos(E) - e), a * (1 - e * e).squareRoot() * sin(E))
50 } else {
51 let a = q / (e - 1), m = Self.k * dt / pow(a, 1.5)
52 var h = asinh(m / e)
53 for _ in 0..<60 {
54 let d = (e * sinh(h) - h - m) / (e * cosh(h) - 1)
55 h -= d
56 if abs(d) < 1e-13 { break }
57 }
58 (x, y) = (a * (e - cosh(h)), a * (e * e - 1).squareRoot() * sinh(h))
59 }
33 let (x, y) = abs(e - 1) < 1e-4 ? nearParabolicPosition(dt) : e < 1 ? ellipticPosition(dt) : hyperbolicPosition(dt)
6034 let r = Double.pi / 180
6135 let (cO, sO) = (cos(node * r), sin(node * r)), (cw, sw) = (cos(peri * r), sin(peri * r)), (ci, si) = (cos(i * r), sin(i * r))
6236 return SIMD3(
@@ -66,6 +40,40 @@ public struct SmallBody: Sendable, Equatable, Codable, Identifiable {
6640 )
6741 }
6842
43 /// In-plane position for an eccentricity near 1, by Barker's equation:
44 /// s + s³/3 = k Δt / √(2q³), s = tan(ν/2).
45 private func nearParabolicPosition(_ dt: Double) -> (x: Double, y: Double) {
46 let w = 3 * Self.k * dt / (2 * q * q * q).squareRoot()
47 let c = cbrt(w / 2 + (w * w / 4 + 1).squareRoot())
48 let s = c - 1 / c
49 return (q * (1 - s * s), 2 * q * s)
50 }
51
52 /// In-plane position on an ellipse, solving Kepler's equation by Newton's method.
53 private func ellipticPosition(_ dt: Double) -> (x: Double, y: Double) {
54 let a = q / (1 - e), m = Self.k * dt / pow(a, 1.5)
55 let mm = remainder(m, 2 * .pi)
56 var E = e < 0.8 ? mm : .pi * (mm < 0 ? -1 : 1)
57 for _ in 0..<60 {
58 let d = (E - e * sin(E) - mm) / (1 - e * cos(E))
59 E -= d
60 if abs(d) < 1e-13 { break }
61 }
62 return (a * (cos(E) - e), a * (1 - e * e).squareRoot() * sin(E))
63 }
64
65 /// In-plane position on a hyperbola, solving the hyperbolic Kepler equation by Newton's method.
66 private func hyperbolicPosition(_ dt: Double) -> (x: Double, y: Double) {
67 let a = q / (e - 1), m = Self.k * dt / pow(a, 1.5)
68 var h = asinh(m / e)
69 for _ in 0..<60 {
70 let d = (e * sinh(h) - h - m) / (e * cosh(h) - 1)
71 h -= d
72 if abs(d) < 1e-13 { break }
73 }
74 return (a * (e - cosh(h)), a * (e * e - 1).squareRoot() * sinh(h))
75 }
76
6977 /// Astrometric J2000 right ascension and declination (degrees), distances (AU) and magnitude from Earth at `date`;
7078 /// light time is ignored.
7179 public func apparent(at date: Date) throws -> (ra: Double, dec: Double, r: Double, delta: Double, magnitude: Double) {
scripts/check-library.py +27 −16
@@ -30,31 +30,42 @@ def status(url, image=False):
3030 return err
3131
3232
33def main():
34 offline = "--offline" in sys.argv
35 pages, problems = [], []
36 for f in sorted(PAGES.glob("*.json")):
37 for p in json.loads(f.read_text()):
38 pages.append((f.name, p))
39 print(f"{len(pages)} pages in {len(list(PAGES.glob('*.json')))} files")
40 if offline:
41 return 0
33def load_pages():
34 """(file name, page) for every Library page, files in name order."""
35 return [(f.name, p) for f in sorted(PAGES.glob("*.json")) for p in json.loads(f.read_text())]
36
37
38def url_checks(pages):
39 """(page id, what, URL, must be an image) for each source and image a page cites."""
4240 checks = []
43 for name, p in pages:
41 for _, p in pages:
4442 for s in p.get("sources", []):
4543 if not s["url"].startswith(SKIP):
4644 checks.append((p["id"], "source", s["url"], False))
4745 if p.get("image"):
4846 checks.append((p["id"], "image", p["image"]["url"], True))
4947 checks.append((p["id"], "image page", p["image"]["page"], False))
48 return checks
49
50
51def problem(check, st):
52 """The report line for a failed check, or None when it passed."""
53 pid, kind, url, _ = check
54 # Sites that refuse scripts (403/429) but load in a browser.
55 if st in (403, 429) and any(url.startswith(p) for p in BLOCKS_SCRIPTS):
56 return None
57 return None if st == 200 else f"{pid}: {kind} {st} {url}"
58
59
60def main():
61 pages = load_pages()
62 print(f"{len(pages)} pages in {len(list(PAGES.glob('*.json')))} files")
63 if "--offline" in sys.argv:
64 return 0
65 checks = url_checks(pages)
5066 with ThreadPoolExecutor(8) as pool:
5167 results = list(pool.map(lambda c: (c, status(c[2], c[3])), checks))
52 for (pid, kind, url, _), st in results:
53 # Sites that refuse scripts (403/429) but load in a browser.
54 if st in (403, 429) and any(url.startswith(p) for p in BLOCKS_SCRIPTS):
55 continue
56 if st != 200:
57 problems.append(f"{pid}: {kind} {st} {url}")
68 problems = [line for line in (problem(c, st) for c, st in results) if line]
5869 print(f"{len(checks)} URLs checked, {len(problems)} problems")
5970 for line in problems:
6071 print(" " + line)
scripts/make-clouds.py +36 −17
@@ -40,8 +40,8 @@ def palette():
4040 return out
4141
4242
43def rgba(png):
44 """Pixels of an 8-bit RGBA, non-interlaced PNG, as rows of (r, g, b, a)."""
43def chunks(png):
44 """Width, height and the concatenated IDAT data of an 8-bit RGBA PNG."""
4545 assert png[:8] == b"\x89PNG\r\n\x1a\n"
4646 pos, data, width, height = 8, b"", 0, 0
4747 while pos < len(png):
@@ -53,35 +53,54 @@ def rgba(png):
5353 elif kind == b"IDAT":
5454 data += body
5555 pos += 12 + length
56 return width, height, data
57
58
59def paeth(a, b, c):
60 p = a + b - c
61 pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
62 return a if pa <= pb and pa <= pc else b if pb <= pc else c
63
64
65def unfilter(f, line, prev):
66 """Reverses PNG filter `f` on one scanline in place, given the previous unfiltered one (4 bytes a pixel)."""
67 for i in range(len(line)):
68 a = line[i - 4] if i >= 4 else 0
69 b, c = prev[i], prev[i - 4] if i >= 4 else 0
70 if f == 1: line[i] = (line[i] + a) & 255
71 elif f == 2: line[i] = (line[i] + b) & 255
72 elif f == 3: line[i] = (line[i] + (a + b) // 2) & 255
73 elif f == 4: line[i] = (line[i] + paeth(a, b, c)) & 255
74
75
76def rgba(png):
77 """Pixels of an 8-bit RGBA, non-interlaced PNG, as rows of (r, g, b, a)."""
78 width, height, data = chunks(png)
5679 raw, stride, rows, prev = zlib.decompress(data), width * 4, [], bytearray(width * 4)
5780 for y in range(height):
5881 f, line = raw[y * (stride + 1)], bytearray(raw[y * (stride + 1) + 1:(y + 1) * (stride + 1)])
59 for i in range(stride):
60 a = line[i - 4] if i >= 4 else 0
61 b, c = prev[i], prev[i - 4] if i >= 4 else 0
62 if f == 1: line[i] = (line[i] + a) & 255
63 elif f == 2: line[i] = (line[i] + b) & 255
64 elif f == 3: line[i] = (line[i] + (a + b) // 2) & 255
65 elif f == 4:
66 p = a + b - c
67 pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
68 line[i] = (line[i] + (a if pa <= pb and pa <= pc else b if pb <= pc else c)) & 255
82 unfilter(f, line, prev)
6983 rows.append([tuple(line[x * 4:x * 4 + 4]) for x in range(width)])
7084 prev = line
7185 return rows
7286
7387
88def accumulate(total, count, rows, colors):
89 """Adds each opaque pixel with a known colour to its cell."""
90 for y, row in enumerate(rows):
91 for x, (r, g, b, a) in enumerate(row):
92 if a and (r, g, b) in colors:
93 total[y * 360 + x] += colors[(r, g, b)]
94 count[y * 360 + x] += 1
95
96
7497def grid(month_day, colors):
7598 month, day = (int(v) for v in month_day.split("-"))
7699 total, count = [0] * 64800, [0] * 64800
77100 for year in YEARS:
78101 for offset in OFFSETS:
79102 d = datetime.date(year, month, day) + datetime.timedelta(days=offset)
80 for y, row in enumerate(rgba(get(WMS.format(layer=LAYER, day=d.isoformat())))):
81 for x, (r, g, b, a) in enumerate(row):
82 if a and (r, g, b) in colors:
83 total[y * 360 + x] += colors[(r, g, b)]
84 count[y * 360 + x] += 1
103 accumulate(total, count, rgba(get(WMS.format(layer=LAYER, day=d.isoformat()))), colors)
85104 time.sleep(1)
86105 return bytes(round(t / n) if n else 255 for t, n in zip(total, count))
87106
scripts/make-skycultures.py +53 −36
@@ -51,14 +51,18 @@ def license_section(md):
5151 return " ".join(out)
5252
5353
54def main():
54def load_hip(path):
55 """HIP number -> (RA, Dec, Vmag) from the VizieR TSV."""
5556 hip = {}
56 for line in open(sys.argv[1]):
57 for line in open(path):
5758 p = line.rstrip("\n").split("\t")
5859 if len(p) == 4 and p[0].strip().isdigit() and p[1].strip() and p[2].strip():
5960 hip[int(p[0])] = (float(p[1]), float(p[2]), float(p[3] or 99))
61 return hip
62
6063
61 bsc = json.load(open(RES / "bsc5.json"))
64def hr_matcher(hip, bsc):
65 """A function from a HIP number to the BSC (HR) star within 0.05 degrees of it, or None."""
6266 cells = {}
6367 for row in bsc:
6468 cells.setdefault((int(row[2])), []).append(row)
@@ -76,40 +80,53 @@ def main():
7680 best = (sep, int(row[0]))
7781 return best[1] if best else None
7882
79 out = []
80 for cid, name in CULTURES:
81 index = json.loads(fetch(f"{BASE}/{cid}/index.json"))
82 lic = license_section(fetch(f"{BASE}/{cid}/description.md"))
83 assert "BY-SA" in lic.replace("-BY SA", "BY-SA").replace("BY SA", "BY-SA"), (cid, lic)
84 constellations = []
85 for c in index.get("constellations", []):
86 segments = []
87 for line in c.get("lines", []):
88 current = []
89 for h in line:
90 hr = hr_for(h) if isinstance(h, int) else None
91 if hr is None:
92 if len(current) > 1:
93 segments.append(current)
94 current = []
95 else:
96 current.append(hr)
97 if len(current) > 1:
98 segments.append(current)
99 if not segments:
100 continue
101 cn = c.get("common_name", {})
102 entry = {"name": cn.get("english") or cn.get("native") or c["id"], "lines": segments}
103 if cn.get("native") and cn.get("native") != entry["name"]:
104 entry["native"] = cn["native"]
105 constellations.append(entry)
106 out.append({
107 "id": cid, "name": name, "region": index.get("region", ""),
108 "licence": lic, "source": f"https://github.com/Stellarium/stellarium-skycultures/tree/master/{cid}",
109 "constellations": constellations,
110 })
111 print(f"{cid}: {len(constellations)} of {len(index.get('constellations', []))} figures", file=sys.stderr)
83 return hr_for
84
85
86def segments(line, hr_for):
87 """A Stellarium line as runs of matched HR stars, split at stars without a match."""
88 out, current = [], []
89 for h in line:
90 hr = hr_for(h) if isinstance(h, int) else None
91 if hr is None:
92 if len(current) > 1:
93 out.append(current)
94 current = []
95 else:
96 current.append(hr)
97 if len(current) > 1:
98 out.append(current)
99 return out
100
101
102def constellation(c, hr_for):
103 """One figure for the app, or None when none of its lines survive matching."""
104 lines = [s for line in c.get("lines", []) for s in segments(line, hr_for)]
105 if not lines:
106 return None
107 cn = c.get("common_name", {})
108 entry = {"name": cn.get("english") or cn.get("native") or c["id"], "lines": lines}
109 if cn.get("native") and cn.get("native") != entry["name"]:
110 entry["native"] = cn["native"]
111 return entry
112
113
114def culture(cid, name, hr_for):
115 index = json.loads(fetch(f"{BASE}/{cid}/index.json"))
116 lic = license_section(fetch(f"{BASE}/{cid}/description.md"))
117 assert "BY-SA" in lic.replace("-BY SA", "BY-SA").replace("BY SA", "BY-SA"), (cid, lic)
118 figures = [f for f in (constellation(c, hr_for) for c in index.get("constellations", [])) if f]
119 print(f"{cid}: {len(figures)} of {len(index.get('constellations', []))} figures", file=sys.stderr)
120 return {
121 "id": cid, "name": name, "region": index.get("region", ""),
122 "licence": lic, "source": f"https://github.com/Stellarium/stellarium-skycultures/tree/master/{cid}",
123 "constellations": figures,
124 }
112125
126
127def main():
128 hr_for = hr_matcher(load_hip(sys.argv[1]), json.load(open(RES / "bsc5.json")))
129 out = [culture(cid, name, hr_for) for cid, name in CULTURES]
113130 (RES / "skycultures.json").write_text(json.dumps(out, ensure_ascii=False, separators=(",", ":")))
114131
115132
server/src/apns.ts +9 −2
@@ -105,8 +105,15 @@ async function result(res: Response, idHeader: string): Promise<ApnsResult> {
105105 return { status: res.status, apnsId: res.headers.get(idHeader), reason };
106106}
107107
108/** A Live Activity update to every device listening on a broadcast channel. `expiration` is in Unix seconds. */
109export async function broadcast(config: ApnsConfig, channelId: string, payload: unknown, sandbox: boolean, priority: 5 | 10, expiration: number): Promise<ApnsResult> {
108/** How a broadcast is delivered. `expiration` is in Unix seconds. */
109export interface BroadcastOptions {
110 sandbox: boolean;
111 priority: 5 | 10;
112 expiration: number;
113}
114
115/** A Live Activity update to every device listening on a broadcast channel. */
116export async function broadcast(config: ApnsConfig, channelId: string, payload: unknown, { sandbox, priority, expiration }: BroadcastOptions): Promise<ApnsResult> {
110117 const host = sandbox ? "api.sandbox.push.apple.com" : "api.push.apple.com";
111118 const res = await fetch(`https://${host}/4/broadcasts/apps/${config.topic}`, {
112119 method: "POST",
server/src/appattest.ts +38 −17
@@ -47,28 +47,49 @@ export const toBase64 = (b: Uint8Array) => btoa(String.fromCharCode(...b));
4747// MARK: CBOR (major types 0–5 with definite lengths, which is all App Attest uses)
4848
4949export function cbor(bytes: Uint8Array): unknown {
50 let i = 0;
51 const length = (info: number): number => {
52 if (info < 24) return info;
53 const n = info === 24 ? 1 : info === 25 ? 2 : info === 26 ? 4 : fail("cbor length");
54 let v = 0;
55 for (let k = 0; k < n; k++) v = v * 256 + bytes[i++];
56 return v;
57 };
58 const item = (): unknown => {
59 if (i >= bytes.length) fail("cbor truncated");
60 const head = bytes[i++], major = head >> 5, n = length(head & 31);
50 return new CborReader(bytes).item();
51}
52
53class CborReader {
54 private i = 0;
55 private readonly bytes: Uint8Array;
56
57 constructor(bytes: Uint8Array) {
58 this.bytes = bytes;
59 }
60
61 item(): unknown {
62 const head = this.take(1)[0], major = head >> 5, n = this.length(head & 31);
6163 switch (major) {
6264 case 0: return n;
6365 case 1: return -1 - n;
64 case 2: { const v = bytes.slice(i, i + n); i += n; return v; }
65 case 3: { const v = new TextDecoder().decode(bytes.slice(i, i + n)); i += n; return v; }
66 case 4: return Array.from({ length: n }, item);
67 case 5: { const m = new Map<unknown, unknown>(); for (let k = 0; k < n; k++) m.set(item(), item()); return m; }
66 case 2: return this.take(n);
67 case 3: return new TextDecoder().decode(this.take(n));
68 case 4: return Array.from({ length: n }, () => this.item());
69 case 5: return this.map(n);
6870 default: return fail("cbor type");
6971 }
70 };
71 return item();
72 }
73
74 private length(info: number): number {
75 if (info < 24) return info;
76 const n = info === 24 ? 1 : info === 25 ? 2 : info === 26 ? 4 : fail("cbor length");
77 return this.take(n).reduce((v, byte) => v * 256 + byte, 0);
78 }
79
80 private map(n: number): Map<unknown, unknown> {
81 const m = new Map<unknown, unknown>();
82 for (let k = 0; k < n; k++) m.set(this.item(), this.item());
83 return m;
84 }
85
86 /** The next `n` bytes; failing rather than reading past the end. */
87 private take(n: number): Uint8Array {
88 if (this.i + n > this.bytes.length) fail("cbor truncated");
89 const v = this.bytes.slice(this.i, this.i + n);
90 this.i += n;
91 return v;
92 }
7293}
7394
7495// MARK: DER
server/src/celestrak.ts +17 −7
@@ -83,10 +83,13 @@ export function parseSupGP(text: string): Row[] {
8383function complete(r: unknown): r is Row {
8484 if (typeof r !== "object" || r === null) return false;
8585 const o = r as Row;
86 return typeof o.OBJECT_NAME === "string" && typeof o.OBJECT_ID === "string" && typeof o.EPOCH === "string" && !Number.isNaN(epoch(o)) &&
87 KEYS.every((k) => k === "OBJECT_NAME" || k === "EPOCH" || (typeof o[k] === "number" && Number.isFinite(o[k])));
86 return hasNames(o) && !Number.isNaN(epoch(o)) && KEYS.every((k) => k === "OBJECT_NAME" || k === "EPOCH" || finite(o[k]));
8887}
8988
89const hasNames = (o: Row) => typeof o.OBJECT_NAME === "string" && typeof o.OBJECT_ID === "string" && typeof o.EPOCH === "string";
90
91const finite = (v: unknown) => typeof v === "number" && Number.isFinite(v);
92
9093const epoch = (r: Row) => Date.parse(`${r.EPOCH}Z`);
9194
9295/**
@@ -143,12 +146,9 @@ export function compose(visual: Row[], recent: Row[], launches: LaunchRef[], sup
143146 const groups = new Map(gp);
144147 const out: Record<string, LaunchElements> = {};
145148 for (const l of launches) {
146 const g = l.designator ? gp.get(l.designator) : undefined;
147 const s = supgp[l.id]?.length ? supgp[l.id] : undefined;
148 const source = s && (!g || newest(s) > newest(g)) ? "supgp" : "gp";
149 const rows = source === "supgp" ? s : g;
149 const { source, rows } = launchRows(l, gp, supgp);
150150 if (!rows) continue;
151 const label = l.mission?.startsWith("Starlink ") ? l.mission.slice(9) : (l.mission ?? l.designator ?? l.id);
151 const label = launchLabel(l);
152152 if (l.designator) groups.delete(l.designator);
153153 if (source === "gp" || newest(rows) <= now.getTime()) groups.set(label, rows);
154154 out[l.id] = { source, elements: launchElements(rows, label) };
@@ -156,6 +156,16 @@ export function compose(visual: Row[], recent: Row[], launches: LaunchRef[], sup
156156 return { satellites: [...pick(visual), ...starlinkTrains(groups)], launches: out };
157157}
158158
159/** A launch's elements: SupGP when it has newer rows than GP, otherwise GP. */
160function launchRows(l: LaunchRef, gp: Map<string, Row[]>, supgp: Record<string, Row[]>): { source: "supgp" | "gp"; rows: Row[] | undefined } {
161 const g = l.designator ? gp.get(l.designator) : undefined;
162 const s = supgp[l.id]?.length ? supgp[l.id] : undefined;
163 return s && (!g || newest(s) > newest(g)) ? { source: "supgp", rows: s } : { source: "gp", rows: g };
164}
165
166/** "Group 15-25" for a Starlink mission; otherwise the mission, designator or ID. */
167const launchLabel = (l: LaunchRef) => (l.mission?.startsWith("Starlink ") ? l.mission.slice(9) : (l.mission ?? l.designator ?? l.id));
168
159169/** The 5-minute tick 33 minutes after each 2-hourly poll, which runs at minute 7 of even UTC hours. */
160170export const retryTick = (now: Date) => now.getUTCHours() % 2 === 0 && now.getUTCMinutes() === 40;
161171
server/src/index.ts +169 −112
@@ -120,13 +120,26 @@ async function cached(request: Request, ctx: ExecutionContext | undefined, respo
120120/** How long clients may reuse each GET response, matched to how often its source is polled. */
121121export const MAX_AGE = { today: 60, launches: 300, satellites: 3600, live: 300, news: 600, sun: 1800, smallBodies: 3600 } as const;
122122
123/** An APNs device token: hex, 32 to 100 bytes. */
124function validToken(t: unknown): t is string {
125 return typeof t === "string" && /^[0-9a-f]{64,200}$/i.test(t);
126}
127
128function validEnvironment(e: unknown): e is DeviceRequest["environment"] {
129 return e === "sandbox" || e === "production";
130}
131
132/** A latitude band: a multiple of 5 degrees. */
133function validBand(b: unknown): b is number {
134 return Number.isInteger(b) && Math.abs(b as number) <= 90 && (b as number) % 5 === 0;
135}
136
137function validUTCOffset(m: unknown): m is number {
138 return Number.isInteger(m) && Math.abs(m as number) <= 14 * 60;
139}
140
123141function validDevice(d: Partial<DeviceRequest>): d is DeviceRequest {
124 return (
125 typeof d.token === "string" && /^[0-9a-f]{64,200}$/i.test(d.token) &&
126 (d.environment === "sandbox" || d.environment === "production") &&
127 Number.isInteger(d.band) && Math.abs(d.band!) <= 90 && d.band! % 5 === 0 &&
128 Number.isInteger(d.utcOffsetMinutes) && Math.abs(d.utcOffsetMinutes!) <= 14 * 60
129 );
142 return validToken(d.token) && validEnvironment(d.environment) && validBand(d.band) && validUTCOffset(d.utcOffsetMinutes);
130143}
131144
132145async function today(env: Env, now: Date): Promise<Response> {
@@ -155,54 +168,25 @@ export default {
155168 const now = new Date();
156169 if (request.method === "GET" && API.has(url.pathname)) return cached(request, ctx, () => api(url, env, now));
157170
158 if (request.method === "GET" && url.pathname === "/healthz") {
159 const rows = await env.DB.prepare("SELECT feed, fetched_at, ok FROM feed_snapshots").all();
160 return json({ ok: true, feeds: rows.results });
161 }
171 if (request.method === "GET" && url.pathname === "/healthz") return health(env);
162172 // The policy lives on krz.sh; older builds link here.
163173 if (request.method === "GET" && url.pathname === "/privacy") return Response.redirect(PRIVACY_URL, 301);
164174
165 if (request.method === "POST" && url.pathname === "/v1/challenge") {
166 const challenge = toBase64(crypto.getRandomValues(new Uint8Array(32)));
167 await env.DB.prepare("INSERT INTO attest_challenges (challenge, expires_at) VALUES (?1, ?2)").bind(challenge, new Date(now.getTime() + CHALLENGE_MS).toISOString()).run();
168 return json({ challenge });
169 }
175 if (request.method === "POST" && url.pathname === "/v1/challenge") return issueChallenge(env, now);
170176
171177 if (request.method === "POST" && url.pathname === "/v1/attest") return attest(request, env, now);
172178
173 if (request.method === "POST" && url.pathname === "/v1/devices") {
174 const body = new Uint8Array(await request.arrayBuffer());
175 let d: Partial<DeviceRequest>;
176 try {
177 d = JSON.parse(new TextDecoder().decode(body));
178 } catch {
179 d = {};
180 }
181 if (!validDevice(d)) return json({ error: "invalid device" }, 400);
182 const refused = await checkAssertion(env, request, body, d.challenge, now);
183 if (refused) return refused;
184 await env.DB.prepare(
185 `INSERT INTO devices (token, environment, band, utc_offset_minutes, aurora, news, last_seen) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
186 ON CONFLICT (token) DO UPDATE SET environment = ?2, band = ?3, utc_offset_minutes = ?4, aurora = ?5, news = ?6, last_seen = ?7`,
187 ).bind(d.token.toLowerCase(), d.environment, d.band, d.utcOffsetMinutes, d.aurora === false ? 0 : 1, d.news === true ? 1 : 0, now.toISOString()).run();
188 return json({ ok: true });
189 }
179 if (request.method === "POST" && url.pathname === "/v1/devices") return registerDevice(request, env, now);
190180
191181 const test = url.pathname.match(/^\/v1\/devices\/([0-9a-f]{64,200})\/test$/i);
192182 if (request.method === "POST" && test) return sendTest(env, test[1].toLowerCase(), now);
193183
194184 if (request.method === "POST" && url.pathname === "/v1/launch-starts") return registerLaunchStarts(request, env, now);
195185 const delStarts = url.pathname.match(/^\/v1\/launch-starts\/([0-9a-f]{64,200})$/i);
196 if (request.method === "DELETE" && delStarts) {
197 await env.DB.prepare("DELETE FROM launch_starts WHERE token = ?1").bind(delStarts[1].toLowerCase()).run();
198 return json({ ok: true });
199 }
186 if (request.method === "DELETE" && delStarts) return deleteRow(env, "DELETE FROM launch_starts WHERE token = ?1", delStarts[1].toLowerCase());
200187
201188 const del = url.pathname.match(/^\/v1\/devices\/([0-9a-f]{64,200})$/i);
202 if (request.method === "DELETE" && del) {
203 await env.DB.prepare("DELETE FROM devices WHERE token = ?1").bind(del[1]).run();
204 return json({ ok: true });
205 }
189 if (request.method === "DELETE" && del) return deleteRow(env, "DELETE FROM devices WHERE token = ?1", del[1]);
206190
207191 return json({ error: "not found" }, 404);
208192 },
@@ -218,6 +202,137 @@ export default {
218202 },
219203} satisfies ExportedHandler<Env>;
220204
205async function health(env: Env): Promise<Response> {
206 const rows = await env.DB.prepare("SELECT feed, fetched_at, ok FROM feed_snapshots").all();
207 return json({ ok: true, feeds: rows.results });
208}
209
210async function issueChallenge(env: Env, now: Date): Promise<Response> {
211 const challenge = toBase64(crypto.getRandomValues(new Uint8Array(32)));
212 await env.DB.prepare("INSERT INTO attest_challenges (challenge, expires_at) VALUES (?1, ?2)").bind(challenge, new Date(now.getTime() + CHALLENGE_MS).toISOString()).run();
213 return json({ challenge });
214}
215
216async function registerDevice(request: Request, env: Env, now: Date): Promise<Response> {
217 const body = new Uint8Array(await request.arrayBuffer());
218 let d: Partial<DeviceRequest>;
219 try {
220 d = JSON.parse(new TextDecoder().decode(body));
221 } catch {
222 d = {};
223 }
224 if (!validDevice(d)) return json({ error: "invalid device" }, 400);
225 const refused = await checkAssertion(env, request, body, d.challenge, now);
226 if (refused) return refused;
227 await env.DB.prepare(
228 `INSERT INTO devices (token, environment, band, utc_offset_minutes, aurora, news, last_seen) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
229 ON CONFLICT (token) DO UPDATE SET environment = ?2, band = ?3, utc_offset_minutes = ?4, aurora = ?5, news = ?6, last_seen = ?7`,
230 ).bind(d.token.toLowerCase(), d.environment, d.band, d.utcOffsetMinutes, d.aurora === false ? 0 : 1, d.news === true ? 1 : 0, now.toISOString()).run();
231 return json({ ok: true });
232}
233
234async function deleteRow(env: Env, sql: string, token: string): Promise<Response> {
235 await env.DB.prepare(sql).bind(token).run();
236 return json({ ok: true });
237}
238
239const apnsConfig = (env: Env): ApnsConfig => ({ keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC });
240
241/** A Live Activity push to a channel, kept by APNs for 8 hours. */
242function broadcastPush(config: ApnsConfig, c: { channel_id: string; environment: string }, push: { payload: unknown; priority: 5 | 10 }, now: Date) {
243 return broadcast(config, c.channel_id, push.payload, {
244 sandbox: c.environment === "sandbox",
245 priority: push.priority,
246 expiration: Math.floor(now.getTime() / 1000) + 8 * 3600,
247 });
248}
249
250/** Deletes the channels in `table` whose stored end message has expired. */
251async function deleteEndedChannels(env: Env, config: ApnsConfig, table: "launch_channels" | "storm_channels", now: Date): Promise<void> {
252 const done = await env.DB.prepare(`SELECT channel_id, environment FROM ${table} WHERE ended_at < ?1`)
253 .bind(new Date(now.getTime() - 8 * 3600_000).toISOString()).all<{ channel_id: string; environment: string }>();
254 const label = table === "storm_channels" ? "apns storm channel delete" : "apns channel delete";
255 for (const c of done.results) {
256 const r = await deleteChannel(config, c.channel_id, c.environment === "sandbox");
257 if (r.status === 204 || r.status === 404) await env.DB.prepare(`DELETE FROM ${table} WHERE channel_id = ?1`).bind(c.channel_id).run();
258 else console.error(label, r.status, r.reason);
259 }
260}
261
262/** A channel per environment for each launch that needs one: from the pool, or created when channels are managed here. */
263async function assignLaunchChannels(env: Env, config: ApnsConfig, manage: boolean, near: Near[], now: Date): Promise<void> {
264 const assigned = await env.DB.prepare("SELECT launch_id, environment FROM launch_channels WHERE launch_id IS NOT NULL").all<{ launch_id: string; environment: string }>();
265 const has = new Set(assigned.results.map((c) => `${c.launch_id}:${c.environment}`));
266 for (const l of near.filter((l) => needsChannel(l, now))) {
267 for (const environment of ["sandbox", "production"]) {
268 if (!has.has(`${l.id}:${environment}`)) await assignLaunchChannel(env, manage ? config : null, l, environment, now);
269 }
270 }
271}
272
273/** Takes a pooled channel for a launch in one environment, or creates one when `creator` may. */
274async function assignLaunchChannel(env: Env, creator: ApnsConfig | null, l: Near, environment: string, now: Date): Promise<void> {
275 const pooled = await env.DB.prepare(
276 `UPDATE launch_channels SET launch_id = ?1, net = ?2, status = ?3
277 WHERE channel_id = (SELECT channel_id FROM launch_channels WHERE launch_id IS NULL AND environment = ?4 ORDER BY created_at LIMIT 1)`,
278 ).bind(l.id, l.net, l.status, environment).run();
279 if (pooled.meta.changes) return;
280 if (!creator) {
281 console.error("launch channel pool empty", environment);
282 return;
283 }
284 const c = await createChannel(creator, environment === "sandbox");
285 if (!c.channelId) {
286 console.error("apns channel", c.status, c.reason);
287 return;
288 }
289 await env.DB.prepare("INSERT INTO launch_channels (channel_id, environment, launch_id, net, status, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)")
290 .bind(c.channelId, environment, l.id, l.net, l.status, now.toISOString()).run();
291}
292
293/** An open storm channel and what it last broadcast. */
294interface StormChannelRow {
295 channel_id: string;
296 environment: string;
297 active_at: string;
298 sent: string | null;
299 sent_at: string | null;
300}
301
302/** One new storm channel per environment, recorded as open. */
303async function openStormChannels(env: Env, config: ApnsConfig, iso: string): Promise<StormChannelRow[]> {
304 const open: StormChannelRow[] = [];
305 for (const environment of ["sandbox", "production"]) {
306 const c = await createChannel(config, environment === "sandbox");
307 if (!c.channelId) {
308 console.error("apns storm channel", c.status, c.reason);
309 continue;
310 }
311 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();
312 open.push({ channel_id: c.channelId, environment, active_at: iso, sent: null, sent_at: null });
313 }
314 return open;
315}
316
317/** Pushes the storm's change to one open channel, ending it once the storm has been calm long enough. */
318async function updateStormChannel(env: Env, config: ApnsConfig, c: StormChannelRow, state: StormState, now: Date): Promise<void> {
319 const iso = now.toISOString();
320 const active = stormActive(state);
321 const end = !active && now.getTime() - Date.parse(c.active_at) >= CALM_MS;
322 const push: StormPush | null = end ? stormEnd(state, now)
323 : stormUpdate(c.sent && c.sent_at ? { state: JSON.parse(c.sent), at: new Date(c.sent_at) } : null, state, now);
324 if (active) await env.DB.prepare("UPDATE storm_channels SET active_at = ?2 WHERE channel_id = ?1").bind(c.channel_id, iso).run();
325 if (!push) return;
326 const r = await broadcastPush(config, c, push, now)
327 .catch((e) => ({ status: 0, reason: String(e) }));
328 if (r.status !== 200) {
329 console.error("apns storm broadcast", r.status, r.reason);
330 return;
331 }
332 await env.DB.prepare("UPDATE storm_channels SET sent = ?2, sent_at = ?3, ended_at = ?4 WHERE channel_id = ?1")
333 .bind(c.channel_id, JSON.stringify(state), iso, end ? iso : null).run();
334}
335
221336const appId = (env: Env) => `${env.APNS_TEAM_ID}.${env.APNS_TOPIC}`;
222337
223338/** Deletes a challenge and says whether it was there and unexpired. */
@@ -274,7 +389,7 @@ async function sendTest(env: Env, token: string, now: Date): Promise<Response> {
274389 const claimed = await env.DB.prepare("INSERT OR IGNORE INTO alerts_sent (kind, band, event, sent_at) VALUES ('test', 0, ?1, ?2)")
275390 .bind(window, now.toISOString()).run();
276391 if (!claimed.meta.changes) return json({ error: "try again in a few minutes" }, 429);
277 const config: ApnsConfig = { keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC };
392 const config = apnsConfig(env);
278393 const payload = { aps: { alert: { title: "Moonrise test alert", body: "Alerts reach this device." }, sound: "default" } };
279394 const r = await send(config, token, payload, device.environment === "sandbox");
280395 if (r.status === 410) await env.DB.prepare("DELETE FROM devices WHERE token = ?1").bind(token).run();
@@ -385,7 +500,7 @@ async function registerLaunchStarts(request: Request, env: Env, now: Date): Prom
385500 } catch {
386501 d = {};
387502 }
388 if (typeof d.token !== "string" || !/^[0-9a-f]{64,200}$/i.test(d.token) || (d.environment !== "sandbox" && d.environment !== "production") || !RULE(d.rockets) || !RULE(d.providers)) {
503 if (!validToken(d.token) || !validEnvironment(d.environment) || !RULE(d.rockets) || !RULE(d.providers)) {
389504 return json({ error: "invalid registration" }, 400);
390505 }
391506 const refused = await checkAssertion(env, request, body, d.challenge, now);
@@ -413,7 +528,7 @@ async function startLaunches(env: Env, now: Date): Promise<void> {
413528 // A minute either side: LL2 writes "…:00Z" and toISOString "…:00.000Z", which compare unequal as text. startDue decides.
414529 ).bind(new Date(now.getTime() - 60_000).toISOString(), new Date(now.getTime() + 61 * 60_000).toISOString()).all<StartLaunch>()).results.filter((l) => startDue(l, now));
415530 if (!due.length) return;
416 const config: ApnsConfig = { keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC };
531 const config = apnsConfig(env);
417532 for (const l of due) {
418533 const channels = Object.fromEntries((await env.DB.prepare("SELECT environment, channel_id FROM launch_channels WHERE launch_id = ?1 AND ended_at IS NULL")
419534 .bind(l.id).all<{ environment: string; channel_id: string }>()).results.map((c) => [c.environment, c.channel_id]));
@@ -517,33 +632,11 @@ function upsertLaunches(env: Env, list: Launch[]): D1PreparedStatement[] {
517632 * retires a channel once its launch is over. Nothing about who follows a launch reaches the server.
518633 */
519634async function launchChannels(env: Env, near: Near[], now: Date): Promise<void> {
520 const config: ApnsConfig = { keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC };
635 const config = apnsConfig(env);
521636 const manage = env.APNS_MANAGE_CHANNELS === "1";
522637 const iso = now.toISOString();
523638
524 const assigned = await env.DB.prepare("SELECT launch_id, environment FROM launch_channels WHERE launch_id IS NOT NULL").all<{ launch_id: string; environment: string }>();
525 const has = new Set(assigned.results.map((c) => `${c.launch_id}:${c.environment}`));
526 for (const l of near.filter((l) => needsChannel(l, now))) {
527 for (const environment of ["sandbox", "production"]) {
528 if (has.has(`${l.id}:${environment}`)) continue;
529 const pooled = await env.DB.prepare(
530 `UPDATE launch_channels SET launch_id = ?1, net = ?2, status = ?3
531 WHERE channel_id = (SELECT channel_id FROM launch_channels WHERE launch_id IS NULL AND environment = ?4 ORDER BY created_at LIMIT 1)`,
532 ).bind(l.id, l.net, l.status, environment).run();
533 if (pooled.meta.changes) continue;
534 if (!manage) {
535 console.error("launch channel pool empty", environment);
536 continue;
537 }
538 const c = await createChannel(config, environment === "sandbox");
539 if (!c.channelId) {
540 console.error("apns channel", c.status, c.reason);
541 continue;
542 }
543 await env.DB.prepare("INSERT INTO launch_channels (channel_id, environment, launch_id, net, status, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)")
544 .bind(c.channelId, environment, l.id, l.net, l.status, iso).run();
545 }
546 }
639 await assignLaunchChannels(env, config, manage, near, now);
547640
548641 await broadcastChanges(env, now);
549642
@@ -552,18 +645,12 @@ async function launchChannels(env: Env, near: Near[], now: Date): Promise<void>
552645 .bind(iso, new Date(now.getTime() - 86400_000).toISOString()).run();
553646 if (!manage) return;
554647 // Deleted once the stored end message has expired.
555 const done = await env.DB.prepare("SELECT channel_id, environment FROM launch_channels WHERE ended_at < ?1")
556 .bind(new Date(now.getTime() - 8 * 3600_000).toISOString()).all<{ channel_id: string; environment: string }>();
557 for (const c of done.results) {
558 const r = await deleteChannel(config, c.channel_id, c.environment === "sandbox");
559 if (r.status === 204 || r.status === 404) await env.DB.prepare("DELETE FROM launch_channels WHERE channel_id = ?1").bind(c.channel_id).run();
560 else console.error("apns channel delete", r.status, r.reason);
561 }
648 await deleteEndedChannels(env, config, "launch_channels", now);
562649}
563650
564651/** Each change of status or NET since the last broadcast on a channel. */
565652async function broadcastChanges(env: Env, now: Date): Promise<void> {
566 const config: ApnsConfig = { keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC };
653 const config = apnsConfig(env);
567654 const changed = await env.DB.prepare(
568655 `SELECT c.channel_id, c.environment, c.net AS sent_net, c.status AS sent_status, l.net, l.status
569656 FROM launch_channels c JOIN launches l ON l.id = c.launch_id WHERE c.ended_at IS NULL AND (c.net != l.net OR c.status != l.status)`,
@@ -571,7 +658,7 @@ async function broadcastChanges(env: Env, now: Date): Promise<void> {
571658 for (const c of changed.results) {
572659 const push = activityPush({ net: c.sent_net, status: c.sent_status }, c, now)!;
573660 // APNs keeps the latest message for devices that are offline, for at most 8 hours.
574 const r = await broadcast(config, c.channel_id, push.payload, c.environment === "sandbox", push.priority, Math.floor(now.getTime() / 1000) + 8 * 3600)
661 const r = await broadcastPush(config, c, push, now)
575662 .catch((e) => ({ status: 0, reason: String(e) }));
576663 if (r.status !== 200) {
577664 console.error("apns broadcast", r.status, r.reason);
@@ -662,45 +749,15 @@ async function pollSpaceWeather(env: Env, now: Date): Promise<void> {
662749 */
663750async function stormChannels(env: Env, state: StormState, now: Date): Promise<void> {
664751 if (!env.APNS_KEY) return;
665 const config: ApnsConfig = { keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC };
752 const config = apnsConfig(env);
666753 const iso = now.toISOString();
667754 const active = stormActive(state);
668755 let open = (await env.DB.prepare("SELECT channel_id, environment, active_at, sent, sent_at FROM storm_channels WHERE ended_at IS NULL")
669 .all<{ channel_id: string; environment: string; active_at: string; sent: string | null; sent_at: string | null }>()).results;
670 if (!open.length && active && env.APNS_MANAGE_CHANNELS === "1") {
671 for (const environment of ["sandbox", "production"]) {
672 const c = await createChannel(config, environment === "sandbox");
673 if (!c.channelId) {
674 console.error("apns storm channel", c.status, c.reason);
675 continue;
676 }
677 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();
678 open.push({ channel_id: c.channelId, environment, active_at: iso, sent: null, sent_at: null });
679 }
680 }
681 for (const c of open) {
682 const end = !active && now.getTime() - Date.parse(c.active_at) >= CALM_MS;
683 const push: StormPush | null = end ? stormEnd(state, now)
684 : stormUpdate(c.sent && c.sent_at ? { state: JSON.parse(c.sent), at: new Date(c.sent_at) } : null, state, now);
685 if (active) await env.DB.prepare("UPDATE storm_channels SET active_at = ?2 WHERE channel_id = ?1").bind(c.channel_id, iso).run();
686 if (!push) continue;
687 const r = await broadcast(config, c.channel_id, push.payload, c.environment === "sandbox", push.priority, Math.floor(now.getTime() / 1000) + 8 * 3600)
688 .catch((e) => ({ status: 0, reason: String(e) }));
689 if (r.status !== 200) {
690 console.error("apns storm broadcast", r.status, r.reason);
691 continue;
692 }
693 await env.DB.prepare("UPDATE storm_channels SET sent = ?2, sent_at = ?3, ended_at = ?4 WHERE channel_id = ?1")
694 .bind(c.channel_id, JSON.stringify(state), iso, end ? iso : null).run();
695 }
756 .all<StormChannelRow>()).results;
757 if (!open.length && active && env.APNS_MANAGE_CHANNELS === "1") open = await openStormChannels(env, config, iso);
758 for (const c of open) await updateStormChannel(env, config, c, state, now);
696759 if (env.APNS_MANAGE_CHANNELS !== "1") return;
697 const done = await env.DB.prepare("SELECT channel_id, environment FROM storm_channels WHERE ended_at < ?1")
698 .bind(new Date(now.getTime() - 8 * 3600_000).toISOString()).all<{ channel_id: string; environment: string }>();
699 for (const c of done.results) {
700 const r = await deleteChannel(config, c.channel_id, c.environment === "sandbox");
701 if (r.status === 204 || r.status === 404) await env.DB.prepare("DELETE FROM storm_channels WHERE channel_id = ?1").bind(c.channel_id).run();
702 else console.error("apns storm channel delete", r.status, r.reason);
703 }
760 await deleteEndedChannels(env, config, "storm_channels", now);
704761}
705762
706763/** RTSW, reduced; the last good copy is kept on failure, and null is returned so no alert rests on old wind. */
@@ -804,7 +861,7 @@ interface Recipient {
804861 * alerts_sent and drops devices it reports gone (410). Retryable failures are not recorded, so a later run tries again.
805862 */
806863async function sendAlerts(env: Env, kind: string, recipients: Recipient[], now: Date, payload: (r: Recipient) => unknown): Promise<void> {
807 const config: ApnsConfig = { keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC };
864 const config = apnsConfig(env);
808865 const slice = recipients.slice(0, PUSH_SLICE);
809866 const results = await sendAll(config, slice.map((r) => ({ token: r.token, payload: payload(r), sandbox: r.environment === "sandbox" })), PUSH_CONCURRENCY);
810867 const sent = env.DB.prepare("INSERT OR IGNORE INTO alerts_sent (kind, band, event, sent_at) VALUES (?1, ?2, ?3, ?4)");
server/src/solarwind.ts +23 −11
@@ -29,38 +29,50 @@ const HOURS = 6;
2929const mean = (xs: number[]) => (xs.length ? Math.round((xs.reduce((a, b) => a + b, 0) / xs.length) * 10) / 10 : null);
3030const ok = (v: number | null | undefined): v is number => typeof v === "number" && Number.isFinite(v);
3131
32interface Bin { speed: number[]; density: number[]; bz: number[]; bt: number[] }
33type Binner = (tag: string) => Bin | undefined;
34
3235export function reduce(mag: MagRow[], wind: WindRow[], now: Date): SolarWind | null {
3336 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) => {
37 const bins = new Map<number, Bin>();
38 const bin: Binner = (tag) => {
3639 const t = Date.parse(tag + "Z");
3740 if (!(t >= start)) return undefined;
3841 const k = Math.floor(t / BIN) * BIN;
3942 if (!bins.has(k)) bins.set(k, { speed: [], density: [], bz: [], bt: [] });
4043 return bins.get(k)!;
4144 };
45 const latest = binMagnetometer(mag, bin);
46 binPlasma(wind, bin);
47 if (!bins.size) return null;
48 const series = [...bins.entries()].sort((a, b) => a[0] - b[0]).map(([k, b]) => ({
49 t: new Date(k).toISOString(), speed: mean(b.speed), density: mean(b.density), bz: mean(b.bz), bt: mean(b.bt),
50 }));
51 return { observedAt: new Date(latest.observed).toISOString(), source: latest.source, series };
52}
53
54/** Bins the active spacecraft's field readings; returns the time and source of the latest. */
55function binMagnetometer(mag: MagRow[], bin: Binner): { observed: number; source: string } {
4256 let observed = 0, source = "";
4357 for (const r of mag) {
44 if (!r.active) continue;
45 const b = bin(r.time_tag);
58 const b = r.active ? bin(r.time_tag) : undefined;
4659 if (!b) continue;
4760 if (ok(r.bz_gsm)) b.bz.push(r.bz_gsm);
4861 if (ok(r.bt)) b.bt.push(r.bt);
4962 const t = Date.parse(r.time_tag + "Z");
5063 if (t > observed) { observed = t; source = r.source; }
5164 }
65 return { observed, source };
66}
67
68/** Bins the active spacecraft's plasma readings. */
69function binPlasma(wind: WindRow[], bin: Binner): void {
5270 for (const r of wind) {
53 if (!r.active) continue;
54 const b = bin(r.time_tag);
71 const b = r.active ? bin(r.time_tag) : undefined;
5572 if (!b) continue;
5673 if (ok(r.proton_speed)) b.speed.push(r.proton_speed);
5774 if (ok(r.proton_density)) b.density.push(r.proton_density);
5875 }
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 };
6476}
6577
6678/**
server/test/apns.test.ts +1 −1
@@ -45,7 +45,7 @@ test("broadcast goes to the standard host with the channel, Live Activity type,
4545 const real = globalThis.fetch;
4646 globalThis.fetch = fetcher;
4747 try {
48 const r = await broadcast(await config(), "dHN0LXNyY2gtY2hubA==", { aps: { event: "update" } }, false, 5, 1_792_230_000);
48 const r = await broadcast(await config(), "dHN0LXNyY2gtY2hubA==", { aps: { event: "update" } }, { sandbox: false, priority: 5, expiration: 1_792_230_000 });
4949 assert.deepEqual(r, { status: 200, apnsId: "r", reason: null });
5050 } finally {
5151 globalThis.fetch = real;