openc3-cosmos-constellation 0.8.6 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 51bde7c55be278ade78a46733b7f9f3b1a023319db4eb4c1b2b53e4f72805590
4
- data.tar.gz: a4fa9ea070e72599b8f06035a0dee42920e8230a46fb5d02de2ec58ca54799b6
3
+ metadata.gz: 2c572e1300a99399b60505111f300fbb0252d6a18f068e545bb1101543c73586
4
+ data.tar.gz: 16332d58cb180465ab2e46f4576397a4717abcab993e79eccea9e9e878259202
5
5
  SHA512:
6
- metadata.gz: '0619f3bdd0418d80b90c7bd5e2d15bc6be92ce4d382bfa6f8d7008d142b3f552f9f7d772cde109107bce3e1a4ea401773df9fadca6cedc6e0364a01656259f92'
7
- data.tar.gz: 056b3424a67754308d6adb803c10a21e1f6f85764ce759edc5e11dee19fde1300824346e72514c7d62e8493eea4a9366c48370680c2ed370dc240baa0ac2df1e
6
+ metadata.gz: a6bd56e30b1356d386fd1e09aa00da8a66f0cd1e413011fb717dc85895fe697f420986ba3323d94f6d787b39b111caa7a3432d2576c25f5931172b5028063398
7
+ data.tar.gz: 83e50e58575f8e3e134302a0bd940252d8f01845a9516e4880a7e85b28fd572bf7fae6f8f787a8f34b2261917ecf833702e41745980a2c50f9cb3eb85505a8a9
data/Rakefile CHANGED
@@ -1,5 +1,5 @@
1
- # Builds openc3-cosmos-constellation-<VERSION>.gem: rake build VERSION=0.8.6
2
- # (or ./openc3.sh cli rake build VERSION=0.8.6 inside a COSMOS checkout).
1
+ # Builds openc3-cosmos-constellation-<VERSION>.gem: rake build VERSION=0.10.0
2
+ # (or ./openc3.sh cli rake build VERSION=0.10.0 inside a COSMOS checkout).
3
3
  PLUGIN_NAME = Dir['*.gemspec'][0].split('.')[0..-2].join('.')
4
4
 
5
5
  # The tool draws the shared Constellation Forecast view, copied in from this repo when it is here.
@@ -13,7 +13,7 @@ SHARED_RESULTS = '../../clients/python/src/constellation_space/results.py'
13
13
  SHARED_LICENSE = '../../LICENSE'
14
14
 
15
15
  task :build do
16
- abort('VERSION is required: rake build VERSION=0.8.6') unless ENV['VERSION']
16
+ abort('VERSION is required: rake build VERSION=0.10.0') unless ENV['VERSION']
17
17
  FileUtils.cp(SHARED_VIEW, VIEW) if File.exist?(SHARED_VIEW)
18
18
  abort("#{VIEW} is missing: copy bridges/shared/forecast-view.js there") unless File.exist?(VIEW)
19
19
  if File.exist?(SHARED_RESULTS)
@@ -9,16 +9,25 @@ target's packets (targets/CONSTELLATION/cmd_tlm/tlm.txt):
9
9
  NEXT_PASS the next predicted pass and its expected GB, and whether it is at risk
10
10
  as the Platform says (AT_RISK), against the contract minimum
11
11
  NEXT_PASS_<NAME> the same for each satellite the plugin's `satellites` variable names
12
- NEXT_24H passes and expected GB over the next 24 hours, and how many are at risk
12
+ NEXT_24H passes and expected GB over the day from when the run was made, as the
13
+ API totals them (only once it serves totals), and how many are at risk
13
14
  SWAP the soonest rain-fade swap to decide, as advice (add a backup pass or move to
14
15
  it), its backup's AOS, LOS and GB, the gain, and minutes left (limits go
15
16
  yellow, then red)
16
17
  HELD the soonest swap Constellation holds for a person to decide, read from
17
18
  GET /predictions/actions, with the ids the APPROVE_SWAP and DECLINE_SWAP
18
19
  commands take (cmd_tlm/cmd.txt, with the plugin's approvals on)
19
- CAPACITY one day's capacity across the antennas, and the tightest
20
+ CAPACITY one day's antennas and the tightest, and the run's passes, minutes and GB
21
+ across them as the API totals them
20
22
  MODCOD the next pass's MODCOD plan
21
23
  RUN the latest workflow run received, of any kind
24
+ PASS_TRACE with the plugin's trace on: NEXT_PASS's pass trace as the API sent it
25
+ (usable seconds, conditions, what limits it, its worst margin); TRACED NO
26
+ for a pass without one
27
+ MINIMUM the latest contract-minimum (SLA) alert, its own feed entry: at risk,
28
+ missed or cleared (LEVEL goes yellow, then red), its scope, period and
29
+ numbers as the API sent them; each also a line in COSMOS's log messages
30
+ (a warning at risk or missed), once per alert key
22
31
 
23
32
  A packet is injected only once a run of its kind has arrived; HELD once a swap run has.
24
33
 
@@ -60,7 +69,7 @@ from typing import Any
60
69
 
61
70
  from constellation_space import results
62
71
 
63
- VERSION = "0.8.6"
72
+ VERSION = "0.10.0"
64
73
  TARGET = "CONSTELLATION"
65
74
  POLL_S = int(os.environ.get("POLL_SECONDS", "15"))
66
75
  # COSMOS shows a packet stale 30 s after its last value: re-inject every poll so a quiet feed
@@ -127,6 +136,7 @@ def packet_name(name: str) -> str:
127
136
  SATELLITES = pairs(os.environ.get("SATELLITES", ""))
128
137
  OUTCOMES = pairs(os.environ.get("OUTCOMES", ""))
129
138
  TIMELINE_ON = os.environ.get("TIMELINE", "off").strip().lower() == "on"
139
+ TRACE_ON = os.environ.get("TRACE", "off").strip().lower() == "on"
130
140
 
131
141
 
132
142
  # The bytes of each STRING item in tlm.txt, by item name (a test holds them to it). COSMOS drops
@@ -134,6 +144,7 @@ TIMELINE_ON = os.environ.get("TIMELINE", "off").strip().lower() == "on"
134
144
  # takes ids longer than these, so a value is cut to fit. Its OVERFLOW TRUNCATE does not do it for
135
145
  # a string in the Python decom of 7.0 to 7.5.
136
146
  STRING_BYTES = {
147
+ "SOURCE": 32,
137
148
  "SATELLITE": 64,
138
149
  "ANTENNA": 64,
139
150
  "AOS": 32,
@@ -153,13 +164,33 @@ STRING_BYTES = {
153
164
  "RUN_ID": 64,
154
165
  "ITEM_ID": 64,
155
166
  "RECEIVED": 32,
167
+ "KIND": 32,
168
+ "BAND": 8,
169
+ "PERIOD": 16,
170
+ "PERIOD_START": 32,
171
+ "PERIOD_END": 32,
172
+ "MEASURE": 16,
173
+ "UNIT": 16,
174
+ "EVIDENCE": 256,
175
+ "MINIMUM_ID": 32,
176
+ "RAISED": 32,
177
+ "CONDITIONS": 16,
178
+ "LIMIT": 16,
179
+ "WORST_CAUSE": 16,
180
+ "WORST_AT": 32,
181
+ "TRUNCATED": 16,
156
182
  }
157
183
 
158
184
 
159
185
  def fit(values: dict[str, Any]) -> dict[str, Any]:
160
- """The values with each string cut to its item's bytes, never mid-character."""
186
+ """The values with each string cut to its item's bytes, never mid-character, and each float
187
+ rounded to 3 decimals, finer than any item shows, so none reads with float noise."""
161
188
  return {
162
- k: v.encode()[: STRING_BYTES[k]].decode(errors="ignore") if k in STRING_BYTES else v
189
+ k: v.encode()[: STRING_BYTES[k]].decode(errors="ignore")
190
+ if k in STRING_BYTES
191
+ else round(v, 3)
192
+ if isinstance(v, float)
193
+ else v
163
194
  for k, v in values.items()
164
195
  }
165
196
 
@@ -244,10 +275,11 @@ def documents(
244
275
  blocks: list[str],
245
276
  index: dict[str, Any],
246
277
  now: datetime,
278
+ totals: dict[str, Any] | None = None,
247
279
  ) -> dict[str, dict[str, Any]]:
248
- """The run as the Constellation Forecast view reads it: workflow-<slug>.json, and index.json
249
- with this workflow's entry replaced. Kept identical to publish_widget() in the Yamcs bridge
250
- (a test compares them)."""
280
+ """The run as the Constellation Forecast view reads it: workflow-<slug>.json, with the run's
281
+ totals as the API serves them, and index.json with this workflow's entry replaced. Kept
282
+ identical to publish_widget() in the Yamcs bridge (a test compares them)."""
251
283
  slug = resource.get("constellation.workflow") or "workflow"
252
284
  entry = {
253
285
  "workflow": slug,
@@ -261,7 +293,7 @@ def documents(
261
293
  workflows = {w["workflow"]: w for w in index.get("workflows", [])}
262
294
  workflows[slug] = entry
263
295
  return {
264
- f"workflow-{slug}.json": {**entry, "items": items},
296
+ f"workflow-{slug}.json": {**entry, "totals": totals, "items": items},
265
297
  "index.json": {"workflows": sorted(workflows.values(), key=lambda w: w["workflow"])},
266
298
  }
267
299
 
@@ -274,12 +306,15 @@ def bucket() -> tuple[Any, str]:
274
306
 
275
307
 
276
308
  def publish_documents(
277
- resource: dict[str, Any], items: list[dict[str, Any]], blocks: list[str]
309
+ resource: dict[str, Any],
310
+ items: list[dict[str, Any]],
311
+ blocks: list[str],
312
+ totals: dict[str, Any] | None = None,
278
313
  ) -> None:
279
314
  client, name = bucket()
280
315
  found = client.get_object(bucket=name, key=f"{DOCS}/index.json")
281
316
  index = json.loads(found["Body"].read()) if found else {}
282
- for key, doc in documents(resource, items, blocks, index, datetime.now(UTC)).items():
317
+ for key, doc in documents(resource, items, blocks, index, datetime.now(UTC), totals).items():
283
318
  body = json.dumps(doc).encode()
284
319
  client.put_object(
285
320
  bucket=name, key=f"{DOCS}/{key}", body=body, content_type="application/json"
@@ -347,6 +382,7 @@ NO_PASS: dict[str, Any] = {
347
382
  "CONTRACT_MIN_GB": 0.0,
348
383
  # A state item: COSMOS takes its state's name for a converted value.
349
384
  "AT_RISK": "NO",
385
+ "SOURCE": "",
350
386
  }
351
387
 
352
388
  # The same for CAPACITY and MODCOD, with no antenna-day or no plan ahead.
@@ -359,6 +395,7 @@ NO_CAPACITY: dict[str, Any] = {
359
395
  "GB_P50": 0.0,
360
396
  "TIGHTEST_ANTENNA": "NONE",
361
397
  "TIGHTEST_GB_P50": 0.0,
398
+ "PARTIAL_DAY": "NO",
362
399
  }
363
400
  NO_MODCOD: dict[str, Any] = {
364
401
  "SATELLITE": "NONE",
@@ -394,9 +431,13 @@ NO_SWAP: dict[str, Any] = {
394
431
  }
395
432
 
396
433
 
397
- def capacity_packet(items: list[dict[str, Any]], now: datetime) -> dict[str, Any] | None:
398
- """CAPACITY: one day's capacity across the antennas (today's, else the next day forecast),
399
- and the antenna with the least of it. None without antenna-day items."""
434
+ def capacity_packet(
435
+ items: list[dict[str, Any]], now: datetime, totals: dict[str, Any] | None = None
436
+ ) -> dict[str, Any] | None:
437
+ """CAPACITY: one day's antennas (today's, else the next day forecast) and the one with the
438
+ least, with the run's passes, minutes and GB across them as the API totals them (`totals`,
439
+ its whole window; 0 when it serves none), never summed here. None without antenna-day
440
+ items."""
400
441
  days = [
401
442
  i
402
443
  for i in items
@@ -409,17 +450,19 @@ def capacity_packet(items: list[dict[str, Any]], now: datetime) -> dict[str, Any
409
450
  day = today if today in dates else next((d for d in dates if d > today), dates[-1])
410
451
  rows = [d for d in days if d["target_at"][:10] == day]
411
452
  tightest = min(rows, key=lambda d: d["value"]["p50"])
412
- # A run that forecasts p50 only has no wet tail: 0, as the packet field cannot be empty.
413
- wet_tail = all(isinstance(r["value"].get("p10"), int | float) for r in rows)
453
+ run = (totals or {}).get("overall") or {}
414
454
  return {
415
455
  "DAY": day,
416
456
  "ANTENNAS": len(rows),
417
- "PASSES": sum(int(r["value"].get("passes") or 0) for r in rows),
418
- "SELLABLE_MIN": round(sum(float(r["value"].get("sellable_min") or 0) for r in rows), 1),
419
- "GB_P10": round(sum(r["value"]["p10"] for r in rows), 3) if wet_tail else 0.0,
420
- "GB_P50": round(sum(r["value"]["p50"] for r in rows), 3),
457
+ "PASSES": run.get("counted_passes", 0),
458
+ "SELLABLE_MIN": run.get("minutes", 0.0),
459
+ # Deprecated: the API totals no p10.
460
+ "GB_P10": 0.0,
461
+ "GB_P50": run.get("gb", 0.0),
421
462
  "TIGHTEST_ANTENNA": tightest["entity"]["id"],
422
463
  "TIGHTEST_GB_P50": round(tightest["value"]["p50"], 3),
464
+ # The run's window covers only part of the day: its numbers are that part's.
465
+ "PARTIAL_DAY": "YES" if any(r["value"].get("partial_day") for r in rows) else "NO",
423
466
  }
424
467
 
425
468
 
@@ -489,6 +532,56 @@ def pass_values(item: dict[str, Any], minimum: float | None) -> dict[str, Any]:
489
532
  "MAX_ELEVATION": float(results.max_elevation(item) or 0.0),
490
533
  "CONTRACT_MIN_GB": float(minimum or 0.0),
491
534
  "AT_RISK": "YES" if at_risk(item, minimum) else "NO",
535
+ "SOURCE": str(item["entity"].get("source") or ""),
536
+ }
537
+
538
+
539
+ NO_TRACE: dict[str, Any] = {
540
+ "SATELLITE": "NONE",
541
+ "ANTENNA": "NONE",
542
+ "AOS": "",
543
+ "TRACED": "NO",
544
+ "USABLE_S": 0.0,
545
+ "DURATION_S": 0.0,
546
+ "CONDITIONS": "",
547
+ "LIMIT": "",
548
+ "WORST_MARGIN_DB": 0.0,
549
+ "WORST_CAUSE": "",
550
+ "WORST_AT": "",
551
+ "TRUNCATED": "",
552
+ }
553
+
554
+
555
+ def trace_packet(passes: list[dict[str, Any]], now: datetime) -> dict[str, Any]:
556
+ """PASS_TRACE: the trace of the pass NEXT_PASS shows, its values as the API sent them; a
557
+ pass without one (a run from before traces) is TRACED NO and the rest empty or 0."""
558
+ ahead = sorted(
559
+ (p for p in passes if datetime.fromisoformat(p["target_at"]) > now),
560
+ key=lambda p: p["target_at"],
561
+ )
562
+ if not ahead:
563
+ return dict(NO_TRACE)
564
+ nxt = ahead[0]
565
+ out = {
566
+ **NO_TRACE,
567
+ "SATELLITE": nxt["entity"]["satellite_id"],
568
+ "ANTENNA": nxt["entity"]["antenna_id"],
569
+ "AOS": _minute(nxt["target_at"]),
570
+ }
571
+ v = results.trace_summary(nxt)
572
+ if v is None:
573
+ return out
574
+ return {
575
+ **out,
576
+ "TRACED": "YES",
577
+ "USABLE_S": _number(v["usable_s"]),
578
+ "DURATION_S": _number(v["duration_s"]),
579
+ "CONDITIONS": v["conditions"] or "",
580
+ "LIMIT": v["limit"] or "",
581
+ "WORST_MARGIN_DB": _number(v["worst_margin_db"]),
582
+ "WORST_CAUSE": v["worst_cause"] or "",
583
+ "WORST_AT": _minute(v["worst_at"]),
584
+ "TRUNCATED": v["truncated"] or "",
492
585
  }
493
586
 
494
587
 
@@ -545,6 +638,33 @@ def held_packet(waiting: list[dict[str, Any]], now: datetime) -> dict[str, Any]:
545
638
  }
546
639
 
547
640
 
641
+ def minimum_packet(alert: dict[str, Any]) -> dict[str, Any]:
642
+ """MINIMUM's values for one SLA alert, its numbers as the API sent them: an amount it lacks
643
+ (the forecast of a missed minimum, what an at-risk one delivered) is 0, as KIND says."""
644
+ v = results.sla_values(alert)
645
+ return {
646
+ # A state item: COSMOS takes its state's name for a converted value, never its number.
647
+ "LEVEL": "MISSED" if v["kind"] == "minimum_missed" else "CLEARED" if v["cleared"] else "AT_RISK",
648
+ "KIND": v["kind"],
649
+ "SATELLITE": v["satellite"] or "",
650
+ "BAND": v["band"] or "",
651
+ "PERIOD": v["period"] or "",
652
+ "PERIOD_START": _minute(v["period_start"]),
653
+ "PERIOD_END": _minute(v["period_end"]),
654
+ "MEASURE": v["measure"] or "",
655
+ "UNIT": v["unit"] or "",
656
+ "TARGET": v["target"] or 0.0,
657
+ "FORECAST": v["forecast"] or 0.0,
658
+ "DELIVERED": v["delivered"] or 0.0,
659
+ "SHORTFALL": v["shortfall"] or 0.0,
660
+ "DEADLINE": _minute(v["deadline"]),
661
+ "EVIDENCE": v["evidence"] or "",
662
+ "MINIMUM_ID": v["minimum_id"] or "",
663
+ "RUN_ID": v["run_id"] or "",
664
+ "RAISED": _minute(v["raised_at"]),
665
+ }
666
+
667
+
548
668
  def packets(
549
669
  passes: list[dict[str, Any]],
550
670
  swaps: list[dict[str, Any]],
@@ -553,17 +673,20 @@ def packets(
553
673
  minimum: float | None = None,
554
674
  satellites: dict[str, str] | None = None,
555
675
  waiting: list[dict[str, Any]] | None = None,
676
+ day: dict[str, Any] | None = None,
556
677
  ) -> dict[str, dict[str, Any]]:
557
678
  """The CONSTELLATION packets for what is forecast now, from spec items: values only, ready to
558
679
  inject. `pending` is how many swaps the newest swap run holds for approval in Constellation,
559
680
  `minimum` the workspace's contract minimum in GB, `satellites` those with a NEXT_PASS packet
560
- of their own (Constellation id to COSMOS name), and `waiting` the actions read from
561
- GET /predictions/actions (None: no HELD packet)."""
681
+ of their own (Constellation id to COSMOS name), `waiting` the actions read from
682
+ GET /predictions/actions (None: no HELD packet), and `day` the pass run's totals.next_24h as
683
+ the API serves it: NEXT_24H's passes and GB are its overall, never a sum here (None: no
684
+ NEXT_24H)."""
562
685
  upcoming = sorted(
563
686
  (p for p in passes if datetime.fromisoformat(p["until"]) > now),
564
687
  key=lambda p: p["target_at"],
565
688
  )
566
- day = [
689
+ upcoming_day = [
567
690
  p for p in upcoming if datetime.fromisoformat(p["target_at"]) < now + timedelta(hours=24)
568
691
  ]
569
692
  open_swaps = sorted(
@@ -571,15 +694,20 @@ def packets(
571
694
  key=lambda s: s["action"]["deadline"],
572
695
  )
573
696
  out: dict[str, dict[str, Any]] = {
574
- "NEXT_24H": {
575
- "PASSES": len(day),
576
- "EXPECTED_GB_P10": round(sum(results.expected_gb(p)["p10"] for p in day), 3),
577
- "EXPECTED_GB_P50": round(sum(results.expected_gb(p)["p50"] for p in day), 3),
578
- "AT_RISK": sum(at_risk(p, minimum) for p in day),
579
- },
580
697
  "NEXT_PASS": {**NO_PASS, "CONTRACT_MIN_GB": float(minimum or 0.0)},
581
698
  "SWAP": {**NO_SWAP, "PENDING": pending},
582
699
  }
700
+ if day is not None:
701
+ out = {
702
+ "NEXT_24H": {
703
+ "PASSES": day["overall"]["counted_passes"],
704
+ # Deprecated: the API totals no p10.
705
+ "EXPECTED_GB_P10": 0.0,
706
+ "EXPECTED_GB_P50": day["overall"]["gb"],
707
+ "AT_RISK": sum(at_risk(p, minimum) for p in upcoming_day),
708
+ },
709
+ **out,
710
+ }
583
711
  if waiting is not None:
584
712
  out["HELD"] = held_packet(waiting, now)
585
713
  # The next AOS, as the Forecast tool shows it: a pass already under way counts in the day only.
@@ -633,7 +761,11 @@ class Forecast:
633
761
  # be approved (held_until): counted until then, not shown. None only in a 0.8.0 state.
634
762
  self.held: list[str | None] = []
635
763
  self.capacity: list[dict[str, Any]] | None = None
764
+ # The capacity run's totals as the API serves them; None when it serves none.
765
+ self.capacity_totals: dict[str, Any] | None = None
636
766
  self.plans: list[dict[str, Any]] | None = None
767
+ # The pass run's totals.next_24h as the API serves it; None when it serves none.
768
+ self.day: dict[str, Any] | None = None
637
769
  self.run: dict[str, Any] = {}
638
770
  # Approvals already reported carried out, by decision: each run shows them again.
639
771
  self.acted: dict[str, str] = {}
@@ -643,8 +775,26 @@ class Forecast:
643
775
  # (GET /predictions/actions), for HELD.
644
776
  self.swap_workflows: list[str] = []
645
777
  self.waiting: list[dict[str, Any]] = []
646
-
647
- def take(self, resource: dict[str, Any], items: list[dict[str, Any]]) -> int:
778
+ # The latest SLA alert's MINIMUM values, and every alert key shown (results.unfired).
779
+ self.minimum_alert: dict[str, Any] | None = None
780
+ self.fired: dict[str, str] = {}
781
+
782
+ def alert(self, alert: dict[str, Any]) -> None:
783
+ """Shows an SLA alert in MINIMUM and says it in COSMOS's log messages; it counts as
784
+ fired (fire()) only once the packet is injected."""
785
+ self.minimum_alert = minimum_packet(alert)
786
+ log(f"{results.sla_level(alert)}: {results.sla_text(alert)}", warn=not alert.get("cleared"))
787
+
788
+ def fire(self, alerts: list[dict[str, Any]]) -> None:
789
+ for alert in alerts:
790
+ self.fired[alert["key"]] = results.fired_until(alert)
791
+
792
+ def take(
793
+ self,
794
+ resource: dict[str, Any],
795
+ items: list[dict[str, Any]],
796
+ totals: dict[str, Any] | None = None,
797
+ ) -> int:
648
798
  answers = resource.get("constellation.template") or results.kind(items)
649
799
  if answers == "rain-fade-swap":
650
800
  self.swaps = swap_items(items)
@@ -654,10 +804,12 @@ class Forecast:
654
804
  self.swap_workflows.append(slug)
655
805
  elif answers == "antenna-capacity":
656
806
  self.capacity = items
807
+ self.capacity_totals = totals
657
808
  elif answers == "modcod-plan":
658
809
  self.plans = modcod_plans(items)
659
810
  elif answers == "pass-yield":
660
811
  self.passes = priced_passes(items)
812
+ self.day = (totals or {}).get("next_24h")
661
813
  self.run = {
662
814
  "WORKFLOW": resource.get("constellation.workflow") or "",
663
815
  "TEMPLATE": answers,
@@ -691,18 +843,23 @@ class Forecast:
691
843
  self.minimum,
692
844
  SATELLITES,
693
845
  self.waiting if self.swap_workflows else None,
846
+ self.day,
694
847
  )
695
848
  if self.passes is None:
696
849
  for name in [n for n in out if n == "NEXT_24H" or n.startswith("NEXT_PASS")]:
697
850
  del out[name]
851
+ elif TRACE_ON:
852
+ out["PASS_TRACE"] = trace_packet(self.passes, now)
698
853
  if self.swaps is None:
699
854
  del out["SWAP"]
700
855
  if self.capacity is not None:
701
- out["CAPACITY"] = capacity_packet(self.capacity, now) or NO_CAPACITY
856
+ out["CAPACITY"] = capacity_packet(self.capacity, now, self.capacity_totals) or NO_CAPACITY
702
857
  if self.plans is not None:
703
858
  out["MODCOD"] = modcod_packet(self.plans, now) or NO_MODCOD
704
859
  if self.run:
705
860
  out["RUN"] = self.run
861
+ if self.minimum_alert is not None:
862
+ out["MINIMUM"] = self.minimum_alert
706
863
  for packet, values in out.items():
707
864
  inject(packet, fit(values))
708
865
  return len(out)
@@ -783,7 +940,8 @@ class Delivered:
783
940
  self.readings: dict[str, list[list[float]]] = {}
784
941
  # pass id -> the pass, from the forecast, until it is measured or given up.
785
942
  self.watch: dict[str, dict[str, Any]] = {}
786
- # pass id -> when its record was sent, kept 7 days so no pass is sent twice.
943
+ # pass id -> when its record was sent or it was given up, kept 7 days so no pass is
944
+ # sent, or said given up, twice.
787
945
  self.sent: dict[str, float] = {}
788
946
  # The key Constellation refused telemetry:write for; sending waits for another.
789
947
  self.refused = ""
@@ -898,9 +1056,8 @@ class Delivered:
898
1056
  records.append((pid, record))
899
1057
  return records, dropped
900
1058
 
901
- def drop(self, pids: dict[str, str]) -> None:
902
- for pid in pids:
903
- self.watch.pop(pid, None)
1059
+ def drop(self, pids: dict[str, str], now_s: float) -> None:
1060
+ self.mark_sent(list(pids), now_s)
904
1061
 
905
1062
  def mark_sent(self, pids: list[str], now_s: float) -> None:
906
1063
  for pid in pids:
@@ -931,7 +1088,7 @@ def measure_delivered(delivered: Delivered, forecast: Forecast, key: str, said:
931
1088
  records, dropped = delivered.due(now)
932
1089
  for pid, why in dropped.items():
933
1090
  log(f"no outcome for {pid}: {why}")
934
- delivered.drop(dropped)
1091
+ delivered.drop(dropped, now.timestamp())
935
1092
  if not records or key == delivered.refused:
936
1093
  return bool(dropped)
937
1094
  try:
@@ -1164,7 +1321,7 @@ def main() -> None:
1164
1321
  not only with runs."""
1165
1322
  nonlocal refreshed
1166
1323
  while seconds > 0:
1167
- if time.time() - refreshed > REFRESH_S and forecast.run:
1324
+ if time.time() - refreshed > REFRESH_S and (forecast.run or forecast.minimum_alert):
1168
1325
  try:
1169
1326
  forecast.publish(datetime.now(UTC))
1170
1327
  refreshed = time.time()
@@ -1221,6 +1378,13 @@ def main() -> None:
1221
1378
  log(lost, warn=True)
1222
1379
  for entry in page["entries"]:
1223
1380
  entry = results.whole(entry, lambda c, n: results.rest_of_run(call, consumer, c, n))
1381
+ # An SLA alert entry is no run: shown, never reported.
1382
+ alerts = results.unfired(results.sla_alerts(entry["otlp"], consumer, log), forecast.fired)
1383
+ if alerts:
1384
+ for alert in alerts:
1385
+ forecast.alert(alert)
1386
+ forecast.publish(datetime.now(UTC))
1387
+ forecast.fire(alerts)
1224
1388
  parts = results.unpack(entry["otlp"], consumer, log)
1225
1389
  if not parts:
1226
1390
  cursor = entry["cursor"]
@@ -1243,7 +1407,10 @@ def main() -> None:
1243
1407
  if bad := len(items) - len(good):
1244
1408
  applied["malformed"] = applied.get("malformed", 0) + bad
1245
1409
  items = good
1246
- applied["forecasts"] += forecast.take(resource, items)
1410
+ totals = results.run_totals(
1411
+ call, resource.get("constellation.run_id"), lambda m: note(said, m)
1412
+ )
1413
+ applied["forecasts"] += forecast.take(resource, items, totals)
1247
1414
  # Approved swaps it shows as approved advice: the platform shows them acted on.
1248
1415
  shown = f"shown in the {TARGET} SWAP packet"
1249
1416
  if acted := results.first_acted(
@@ -1252,7 +1419,7 @@ def main() -> None:
1252
1419
  applied["acted"] = applied.get("acted", 0) + acted
1253
1420
  widget = output_of(resource).get("widget") or {}
1254
1421
  if widget.get("on"):
1255
- publish_documents(resource, items, widget["blocks"])
1422
+ publish_documents(resource, items, widget["blocks"], totals)
1256
1423
  applied["widget_updates"] = applied.get("widget_updates", 0) + 1
1257
1424
  applied["parameters"] = forecast.publish(datetime.now(UTC))
1258
1425
  refreshed = time.time()
@@ -169,13 +169,15 @@ def first_acted(
169
169
  acted: dict[str, str],
170
170
  outcomes: list[dict[str, str]] | None = None,
171
171
  how: str = "",
172
+ unshown: Callable[[dict[str, Any]], str] = lambda item: "",
172
173
  ) -> int:
173
174
  """How many of these items are approved actions still open (before their deadline) carried
174
175
  out for the first time. A bridge that enforces or shows approvals on every run, rather than
175
176
  acting once, counts each decision (action_key) once: `acted` maps each counted to when it may
176
177
  be forgotten (acted_until), kept in the bridge's state, and loses keys long over. Each one
177
178
  counted goes in `outcomes` as acted (`how` says how), and an approval first seen past its
178
- deadline as refused, each once (outcome())."""
179
+ deadline, or one `unshown` gives a reason it is not carried out, as refused, each once
180
+ (outcome())."""
179
181
  _drop_over(acted)
180
182
  first = 0
181
183
  for item in items:
@@ -185,6 +187,8 @@ def first_acted(
185
187
  acted[key] = acted_until(item)
186
188
  if past_deadline(item):
187
189
  said = outcome(item, "refused", too_late(item))
190
+ elif why := unshown(item):
191
+ said = outcome(item, "refused", why)
188
192
  else:
189
193
  first += 1
190
194
  said = outcome(item, "acted", how)
@@ -218,6 +222,18 @@ def minute(value: Any) -> str:
218
222
  return at.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%MZ") if at else ""
219
223
 
220
224
 
225
+ # Where a pass comes from (its entity.source), as a person reads it; any other value as sent.
226
+ SOURCES = {
227
+ "computed": "computed from orbits",
228
+ "computed:continuous": "a continuous slot of one UTC day",
229
+ }
230
+
231
+
232
+ def source(item: dict[str, Any]) -> str:
233
+ raw = str((item.get("entity") or {}).get("source") or "")
234
+ return SOURCES.get(raw, raw)
235
+
236
+
221
237
  # Why a swap advises its action (the action's `reason`), as a person reads it.
222
238
  REASONS = {
223
239
  "adds_capacity": "it adds capacity",
@@ -453,14 +469,17 @@ def unpack(
453
469
  ) -> list[tuple[dict[str, Any], list[dict[str, Any]]]]:
454
470
  """A results entry's parts for this connection: each resourceLogs (one per feed output of the
455
471
  run) whose constellation.connection is `consumer`, as its resource attributes and its items.
456
- Parts for other connections are left alone; a part in an item shape this bridge does not read
457
- is skipped and logged."""
472
+ Parts for other connections, and SLA alerts (sla_alerts()), are left alone; a part in an item
473
+ shape this bridge does not read is skipped and logged."""
458
474
  parts = []
459
475
  for logs in otlp.get("resourceLogs", []):
460
476
  resource = {
461
477
  kv["key"]: plain(kv["value"]) for kv in logs.get("resource", {}).get("attributes", [])
462
478
  }
463
- if resource.get("constellation.connection") != consumer:
479
+ if (
480
+ resource.get("constellation.connection") != consumer
481
+ or resource.get("constellation.kind") == SLA_KIND
482
+ ):
464
483
  continue
465
484
  records = [r for scope in logs.get("scopeLogs", []) for r in scope.get("logRecords", [])]
466
485
  if newer := newer_shapes(records):
@@ -473,6 +492,129 @@ def unpack(
473
492
  return parts
474
493
 
475
494
 
495
+ # Contract-minimum (SLA) alerts: each its own feed entry, never a run, so a bridge shows it and
496
+ # reads on past it with nothing to apply or report (no POST /predictions/feed/deliveries).
497
+ SLA_KIND = "sla_alert"
498
+ SLA_SCHEMA = "constellation.sla_alert/v1"
499
+ SLA_KINDS = ("minimum_at_risk", "minimum_missed")
500
+
501
+
502
+ def sla_alerts(
503
+ otlp: dict[str, Any], consumer: str, log: Callable[[str], None] = print
504
+ ) -> list[dict[str, Any]]:
505
+ """The SLA alerts in a feed entry for this connection: each record of its resources whose
506
+ constellation.kind is sla_alert. One in another shape, or without the key and kind every
507
+ bridge reads, is skipped and logged; any other field may be missing, and is then not shown."""
508
+ found = []
509
+ for logs in otlp.get("resourceLogs", []):
510
+ resource = {
511
+ kv["key"]: plain(kv["value"]) for kv in logs.get("resource", {}).get("attributes", [])
512
+ }
513
+ if (
514
+ resource.get("constellation.connection") != consumer
515
+ or resource.get("constellation.kind") != SLA_KIND
516
+ ):
517
+ continue
518
+ for record in (r for s in logs.get("scopeLogs", []) for r in s.get("logRecords", [])):
519
+ (shape,) = newer_shapes([record]) or {SCHEMA}
520
+ alert = plain(record.get("body") or {})
521
+ kind = alert.get("kind") if isinstance(alert, dict) else None
522
+ if shape != SLA_SCHEMA or kind not in SLA_KINDS or not isinstance(alert.get("key"), str):
523
+ log(f"skipped an SLA alert this bridge does not read: {shape}, kind {kind}")
524
+ continue
525
+ found.append(alert)
526
+ return found
527
+
528
+
529
+ def unfired(alerts: list[dict[str, Any]], fired: dict[str, str]) -> list[dict[str, Any]]:
530
+ """The alerts not fired before, once each, by their key: the API's idempotency key, one per
531
+ minimum and period, and per re-fire or clearing of an at-risk one. `fired` is the bridge's
532
+ state, key to fired_until(), so neither the feed read again nor a restart fires one twice;
533
+ a bridge adds a key once the alert is shown, and keys long over are dropped here."""
534
+ _drop_over(fired)
535
+ return list({a["key"]: a for a in alerts if a["key"] not in fired}.values())
536
+
537
+
538
+ def fired_until(alert: dict[str, Any]) -> str:
539
+ """When a fired alert's key may be forgotten: KEEP_ACTED past its period's end, or now."""
540
+ end = parse_time(sla_field(alert, "period", "end")) or now()
541
+ return (max(end, now()) + KEEP_ACTED).isoformat(timespec="seconds")
542
+
543
+
544
+ def sla_field(alert: dict[str, Any], *path: str) -> Any:
545
+ """The value at `path` in an alert, or None where it has none."""
546
+ value: Any = alert
547
+ for key in path:
548
+ value = value.get(key) if isinstance(value, dict) else None
549
+ return value
550
+
551
+
552
+ def sla_level(alert: dict[str, Any]) -> str:
553
+ """CRITICAL for a missed minimum, INFO for an at-risk one cleared, else WARNING."""
554
+ if alert["kind"] == "minimum_missed":
555
+ return "CRITICAL"
556
+ return "INFO" if alert.get("cleared") is True else "WARNING"
557
+
558
+
559
+ def sla_values(alert: dict[str, Any]) -> dict[str, Any]:
560
+ """An alert's fields as plain values, as the API sends them: numbers never computed here, and
561
+ None for any the alert lacks (forecast on a missed minimum, delivered on an at-risk one)."""
562
+
563
+ def number(*path: str) -> float | None:
564
+ v = sla_field(alert, *path)
565
+ return float(v) if isinstance(v, int | float) and not isinstance(v, bool) else None
566
+
567
+ def text(*path: str) -> str | None:
568
+ v = sla_field(alert, *path)
569
+ return v if isinstance(v, str) else None
570
+
571
+ evidence = alert.get("evidence_pass_ids")
572
+ return {
573
+ "kind": alert["kind"],
574
+ "cleared": alert.get("cleared") is True,
575
+ "key": alert["key"],
576
+ "minimum_id": text("minimum_id"),
577
+ "satellite": text("scope", "satellite_id"),
578
+ "band": text("scope", "band"),
579
+ "period": text("period", "kind"),
580
+ "period_start": text("period", "start"),
581
+ "period_end": text("period", "end"),
582
+ "measure": text("measure"),
583
+ "unit": text("unit"),
584
+ "target": number("target"),
585
+ "forecast": number("forecast"),
586
+ "delivered": number("delivered"),
587
+ "shortfall": number("shortfall"),
588
+ "deadline": text("deadline"),
589
+ "evidence": ", ".join(e for e in evidence if isinstance(e, str))
590
+ if isinstance(evidence, list)
591
+ else None,
592
+ "run_id": text("run_id"),
593
+ "raised_at": text("raised_at"),
594
+ }
595
+
596
+
597
+ def sla_text(alert: dict[str, Any]) -> str:
598
+ """An alert as a person reads it: the API's own title and text, the words its Slack and email
599
+ alerts use, else its kind and scope."""
600
+ said = (alert.get("title"), alert.get("text"))
601
+ words = [w.rstrip(".") for w in said if isinstance(w, str) and w]
602
+ if words:
603
+ return ". ".join(words) + "."
604
+ v = sla_values(alert)
605
+ scope = (v["satellite"] or "a satellite") + (f" {v['band']}-band" if v["band"] else "")
606
+ what = "missed" if v["kind"] == "minimum_missed" else "cleared" if v["cleared"] else "at risk"
607
+ return f"{scope}: contract minimum {what}" + (
608
+ f" for the {v['period']} from {minute(v['period_start'])}" if v["period"] else ""
609
+ )
610
+
611
+
612
+ def sla_incident(alert: dict[str, Any]) -> str:
613
+ """The incident an alert is about, one per minimum and period: a later alert of it (a re-fire,
614
+ its clearing, the period missed) replaces the one shown."""
615
+ return f"{alert.get('minimum_id')}|{sla_field(alert, 'period', 'start')}"
616
+
617
+
476
618
  def expired(page: dict[str, Any], cursor: str) -> str | None:
477
619
  """Why runs were lost when the feed no longer holds `cursor` (it sorts before the page's
478
620
  oldest entry: runs after it expired unread); None when it still does."""
@@ -492,6 +634,26 @@ def results_page(call: Callable[..., Any], consumer: str, after: str) -> dict[st
492
634
  return call("GET", f"/predictions/feed?{urllib.parse.urlencode(query)}")
493
635
 
494
636
 
637
+ def run_totals(
638
+ call: Callable[..., Any], run_id: str | None, log: Callable[[str], None]
639
+ ) -> dict[str, Any] | None:
640
+ """The run's totals as the API serves them (GET /predictions?run_id=, its `totals`): every
641
+ count and GB a bridge shows over more than one pass comes from here, never its own sum, as
642
+ overlapping passes of one radio or one antenna count once only by the API's rule. None when
643
+ the API serves none (a run finished before it did, or a run of links) or the read fails: the
644
+ bridge then shows nothing for them."""
645
+ if not run_id:
646
+ return None
647
+ query = urllib.parse.urlencode({"run_id": run_id, "page_records": 1})
648
+ try:
649
+ body = call("GET", f"/predictions?{query}")
650
+ except Exception as exc:
651
+ log(f"could not read the totals of run {run_id} ({type(exc).__name__}: {exc}): showing none")
652
+ return None
653
+ totals = body.get("totals") if isinstance(body, dict) else None
654
+ return totals if isinstance(totals, dict) else None
655
+
656
+
495
657
  def rest_of_run(call: Callable[..., Any], consumer: str, cursor: str, page: int) -> dict[str, Any]:
496
658
  """Page `page` of the run at `cursor`."""
497
659
  query = {"cursor": cursor, "page": page, "page_records": PAGE_RECORDS, "consumer": consumer}
@@ -575,7 +737,7 @@ def report(
575
737
  raise
576
738
  error = _detail(getattr(exc, "body", b"") or b"").get("error")
577
739
  why = {
578
- "action_not_sent": "one was declined or approved on the demo fleet, so never sent",
740
+ "action_not_sent": "one was declined, so never sent",
579
741
  "unknown_decision": "a decision on one changed after this run",
580
742
  }.get(error, "this API does not take outcomes" if status == 422 else "it refused them")
581
743
  log(
@@ -640,3 +802,33 @@ def expected_gb(item: dict[str, Any]) -> dict[str, Any] | None:
640
802
  ):
641
803
  return gb
642
804
  return None
805
+
806
+
807
+ def trace_summary(item: dict[str, Any]) -> dict[str, Any] | None:
808
+ """A priced pass's trace summary as the API sent it (os computes every value; none is
809
+ derived here): None for an item without one. A field the trace lacks is None."""
810
+ trace = item.get("trace")
811
+ if not isinstance(trace, dict):
812
+ return None
813
+
814
+ def number(*path: str) -> float | None:
815
+ v = sla_field(trace, *path)
816
+ return float(v) if isinstance(v, int | float) and not isinstance(v, bool) else None
817
+
818
+ def text(*path: str) -> str | None:
819
+ v = sla_field(trace, *path)
820
+ return v if isinstance(v, str) else None
821
+
822
+ truncated = trace.get("truncated")
823
+ return {
824
+ "usable_s": number("usable_s"),
825
+ "duration_s": number("duration_s"),
826
+ "conditions": text("conditions"),
827
+ "limit": text("limit"),
828
+ "worst_margin_db": number("worst", "margin_db"),
829
+ "worst_cause": text("worst", "cause"),
830
+ "worst_at": text("worst", "at"),
831
+ "truncated": ", ".join(t for t in truncated if isinstance(t, str))
832
+ if isinstance(truncated, list)
833
+ else None,
834
+ }
data/plugin.txt CHANGED
@@ -17,6 +17,14 @@ VARIABLE timeline off
17
17
  VARIABLE_DESCRIPTION "COSMOS Enterprise only. on: forecast passes of the next 48 hours as reserve activities on a CONSTELLATION timeline, which Enterprise's Calendar shows; on Core the bridge says so in its log and makes no timeline"
18
18
  VARIABLE_STATE Off off
19
19
  VARIABLE_STATE On on
20
+ VARIABLE trace off
21
+ VARIABLE_DESCRIPTION "on: a PASS_TRACE packet with the next pass's trace (usable seconds, conditions, limit, worst margin) as Constellation sends it"
22
+ VARIABLE_STATE Off off
23
+ VARIABLE_STATE On on
24
+ VARIABLE pass_profile off
25
+ VARIABLE_DESCRIPTION "Deprecated, read for one release: on is the same as trace on"
26
+ VARIABLE_STATE Off off
27
+ VARIABLE_STATE On on
20
28
 
21
29
  TARGET CONSTELLATION CONSTELLATION
22
30
 
@@ -34,6 +42,7 @@ MICROSERVICE BRIDGE constellation-bridge
34
42
  ENV SATELLITES "<%= satellites %>"
35
43
  ENV OUTCOMES "<%= outcomes %>"
36
44
  ENV TIMELINE <%= timeline %>
45
+ ENV TRACE <%= [trace, pass_profile].include?("on") ? "on" : "off" %>
37
46
  # Admin > Secrets: CONSTELLATION_API_KEY (a key with predictions:read; telemetry:write too for
38
47
  # outcomes). The bridge reads it there at each poll, so it can be added or changed after
39
48
  # installing.
@@ -14,27 +14,28 @@ TELEMETRY CONSTELLATION <%= packet %> BIG_ENDIAN "Forecast: <%= what %>"
14
14
  APPEND_ITEM ANTENNA 512 STRING "Antenna id"
15
15
  APPEND_ITEM AOS 256 STRING "Predicted acquisition of signal, UTC"
16
16
  APPEND_ITEM LOS 256 STRING "Predicted loss of signal, UTC"
17
- APPEND_ITEM EXPECTED_GB_P10 32 FLOAT "Deprecated, kept only so layouts do not break. Read EXPECTED_GB_P50"
17
+ APPEND_ITEM EXPECTED_GB_P10 64 FLOAT "Deprecated, kept only so layouts do not break. Read EXPECTED_GB_P50"
18
18
  UNITS Gigabytes GB
19
19
  FORMAT_STRING "%.3f"
20
- APPEND_ITEM EXPECTED_GB_P50 32 FLOAT "Expected GB (p50)"
20
+ APPEND_ITEM EXPECTED_GB_P50 64 FLOAT "Expected GB (p50)"
21
21
  UNITS Gigabytes GB
22
22
  FORMAT_STRING "%.3f"
23
- APPEND_ITEM EXPECTED_GB_P90 32 FLOAT "Deprecated, kept only so layouts do not break. Read EXPECTED_GB_P50"
23
+ APPEND_ITEM EXPECTED_GB_P90 64 FLOAT "Deprecated, kept only so layouts do not break. Read EXPECTED_GB_P50"
24
24
  UNITS Gigabytes GB
25
25
  FORMAT_STRING "%.3f"
26
- APPEND_ITEM MAX_ELEVATION 32 FLOAT "Peak elevation"
26
+ APPEND_ITEM MAX_ELEVATION 64 FLOAT "Peak elevation"
27
27
  UNITS Degrees deg
28
28
  FORMAT_STRING "%.2f"
29
- APPEND_ITEM CONTRACT_MIN_GB 32 FLOAT "The workspace's contract minimum, 0 when none is set"
29
+ APPEND_ITEM CONTRACT_MIN_GB 64 FLOAT "The workspace's contract minimum, 0 when none is set"
30
30
  UNITS Gigabytes GB
31
31
  FORMAT_STRING "%.3f"
32
32
  APPEND_ITEM AT_RISK 8 UINT "At risk, as on the Platform: expected to deliver nothing or under the contract minimum, a value unfilled, or flagged"
33
33
  STATE NO 0 GREEN
34
34
  STATE YES 1 YELLOW
35
+ APPEND_ITEM SOURCE 256 STRING "Where the pass comes from: computed (from orbits) or computed:continuous (a geostationary slot of one UTC day)"
35
36
 
36
37
  <%- end -%>
37
- TELEMETRY CONSTELLATION NEXT_24H BIG_ENDIAN "Forecast: every predicted pass in the next 24 hours, summed"
38
+ TELEMETRY CONSTELLATION NEXT_24H BIG_ENDIAN "Forecast: the passes and GB of the day from when the pass run was made, as Constellation totals them"
38
39
  ALLOW_SHORT
39
40
  APPEND_ITEM PASSES 32 UINT "Predicted passes"
40
41
  APPEND_ITEM EXPECTED_GB_P10 64 FLOAT "Deprecated, kept only so layouts do not break. Read EXPECTED_GB_P50"
@@ -52,16 +53,16 @@ TELEMETRY CONSTELLATION SWAP BIG_ENDIAN "Forecast: the soonest open rain-fade sw
52
53
  APPEND_ITEM SATELLITE 512 STRING "Satellite id"
53
54
  APPEND_ITEM ANTENNA 512 STRING "Antenna at risk"
54
55
  APPEND_ITEM AOS 256 STRING "Predicted AOS of the pass at risk, UTC"
55
- APPEND_ITEM KEEPS_GB_P10 32 FLOAT "Deprecated, kept only so layouts do not break. Read EXPECTED_GB_P50"
56
+ APPEND_ITEM KEEPS_GB_P10 64 FLOAT "Deprecated, kept only so layouts do not break. Read EXPECTED_GB_P50"
56
57
  UNITS Gigabytes GB
57
58
  FORMAT_STRING "%.3f"
58
- APPEND_ITEM EXPECTED_GB_P50 32 FLOAT "GB the pass is expected to carry in the rain (p50)"
59
+ APPEND_ITEM EXPECTED_GB_P50 64 FLOAT "GB the pass is expected to carry in the rain (p50)"
59
60
  UNITS Gigabytes GB
60
61
  FORMAT_STRING "%.3f"
61
62
  APPEND_ITEM BACKUP_ANTENNA 512 STRING "Antenna of the backup pass advised, or NONE"
62
63
  APPEND_ITEM BACKUP_AOS 256 STRING "Backup pass AOS, UTC"
63
64
  APPEND_ITEM DEADLINE 256 STRING "Decide by, UTC"
64
- APPEND_ITEM MINUTES_TO_DEADLINE 32 FLOAT "Minutes left to decide: yellow at 30 or less, red at 15 or less (99999 when no swap is open)"
65
+ APPEND_ITEM MINUTES_TO_DEADLINE 64 FLOAT "Minutes left to decide: yellow at 30 or less, red at 15 or less (99999 when no swap is open)"
65
66
  UNITS Minutes min
66
67
  FORMAT_STRING "%.1f"
67
68
  LIMITS DEFAULT 1 ENABLED 15 30 100000 100000
@@ -70,10 +71,10 @@ TELEMETRY CONSTELLATION SWAP BIG_ENDIAN "Forecast: the soonest open rain-fade sw
70
71
  APPEND_ITEM PENDING 32 UINT "Swaps held for approval in Constellation, deadline ahead"
71
72
  APPEND_ITEM ADVICE 2048 STRING "The advice in words: add a backup pass (keep this one) or move to the backup, its gain and why"
72
73
  APPEND_ITEM BACKUP_LOS 256 STRING "Backup pass LOS, UTC"
73
- APPEND_ITEM BACKUP_GB 32 FLOAT "GB the backup pass is expected to carry (p50)"
74
+ APPEND_ITEM BACKUP_GB 64 FLOAT "GB the backup pass is expected to carry (p50)"
74
75
  UNITS Gigabytes GB
75
76
  FORMAT_STRING "%.3f"
76
- APPEND_ITEM GAIN_GB 32 FLOAT "GB the advice adds over doing nothing (p50)"
77
+ APPEND_ITEM GAIN_GB 64 FLOAT "GB the advice adds over doing nothing (p50)"
77
78
  UNITS Gigabytes GB
78
79
  FORMAT_STRING "%.3f"
79
80
 
@@ -89,33 +90,36 @@ TELEMETRY CONSTELLATION HELD BIG_ENDIAN "The soonest rain-fade swap Constellatio
89
90
  APPEND_ITEM ADVICE 2048 STRING "The advice in words: add a backup pass (keep this one) or move to the backup, its gain and why"
90
91
  APPEND_ITEM BACKUP_ANTENNA 512 STRING "Antenna of the backup pass advised, or NONE"
91
92
  APPEND_ITEM BACKUP_AOS 256 STRING "Backup pass AOS, UTC"
92
- APPEND_ITEM GAIN_GB 32 FLOAT "GB the advice adds over doing nothing (p50)"
93
+ APPEND_ITEM GAIN_GB 64 FLOAT "GB the advice adds over doing nothing (p50)"
93
94
  UNITS Gigabytes GB
94
95
  FORMAT_STRING "%.3f"
95
96
  APPEND_ITEM DEADLINE 256 STRING "Decide by, UTC: it expires then and nothing is sent"
96
- APPEND_ITEM MINUTES_TO_DEADLINE 32 FLOAT "Minutes left to decide: yellow at 30 or less, red at 15 or less (99999 with nothing held)"
97
+ APPEND_ITEM MINUTES_TO_DEADLINE 64 FLOAT "Minutes left to decide: yellow at 30 or less, red at 15 or less (99999 with nothing held)"
97
98
  UNITS Minutes min
98
99
  FORMAT_STRING "%.1f"
99
100
  LIMITS DEFAULT 1 ENABLED 15 30 100000 100000
100
101
 
101
- TELEMETRY CONSTELLATION CAPACITY BIG_ENDIAN "Forecast: one day's capacity across the antennas, and the tightest"
102
+ TELEMETRY CONSTELLATION CAPACITY BIG_ENDIAN "Forecast: one day's antennas and the tightest, and the capacity run's totals across them"
102
103
  ALLOW_SHORT
103
104
  APPEND_ITEM DAY 128 STRING "Day, UTC"
104
105
  APPEND_ITEM ANTENNAS 32 UINT "Antennas forecast"
105
- APPEND_ITEM PASSES 32 UINT "Predicted passes"
106
- APPEND_ITEM SELLABLE_MIN 32 FLOAT "Sellable contact minutes"
106
+ APPEND_ITEM PASSES 32 UINT "Passes the run counts, as Constellation totals them (0 when it serves no totals)"
107
+ APPEND_ITEM SELLABLE_MIN 64 FLOAT "Sellable contact minutes over the run, as Constellation totals them"
107
108
  UNITS Minutes min
108
109
  FORMAT_STRING "%.1f"
109
110
  APPEND_ITEM GB_P10 64 FLOAT "Deprecated, kept only so layouts do not break. Read GB_P50"
110
111
  UNITS Gigabytes GB
111
112
  FORMAT_STRING "%.3f"
112
- APPEND_ITEM GB_P50 64 FLOAT "Expected GB (p50)"
113
+ APPEND_ITEM GB_P50 64 FLOAT "Expected GB (p50) over the run, as Constellation totals them"
113
114
  UNITS Gigabytes GB
114
115
  FORMAT_STRING "%.3f"
115
116
  APPEND_ITEM TIGHTEST_ANTENNA 512 STRING "Antenna with the least expected GB that day"
116
- APPEND_ITEM TIGHTEST_GB_P50 32 FLOAT "Its expected GB (p50)"
117
+ APPEND_ITEM TIGHTEST_GB_P50 64 FLOAT "Its expected GB (p50)"
117
118
  UNITS Gigabytes GB
118
119
  FORMAT_STRING "%.3f"
120
+ APPEND_ITEM PARTIAL_DAY 8 UINT "YES when the run's window covers only part of the day, so these are that part's numbers, not the day's"
121
+ STATE NO 0
122
+ STATE YES 1
119
123
 
120
124
  TELEMETRY CONSTELLATION MODCOD BIG_ENDIAN "Forecast: the next pass's MODCOD plan"
121
125
  ALLOW_SHORT
@@ -125,7 +129,7 @@ TELEMETRY CONSTELLATION MODCOD BIG_ENDIAN "Forecast: the next pass's MODCOD plan
125
129
  APPEND_ITEM CHANGES 32 UINT "MODCOD changes over the pass, after the one at AOS"
126
130
  APPEND_ITEM FIRST 256 STRING "MODCOD at AOS"
127
131
  APPEND_ITEM LAST 256 STRING "MODCOD at LOS"
128
- APPEND_ITEM MIN_SINR_DB 32 FLOAT "Lowest planned SINR (p50) at a MODCOD change"
132
+ APPEND_ITEM MIN_SINR_DB 64 FLOAT "Lowest planned SINR (p50) at a MODCOD change"
129
133
  UNITS Decibels dB
130
134
  FORMAT_STRING "%.2f"
131
135
  APPEND_ITEM PLANNED_PASSES 32 UINT "Passes ahead with a plan"
@@ -138,3 +142,53 @@ TELEMETRY CONSTELLATION RUN BIG_ENDIAN "The latest workflow run received, of any
138
142
  APPEND_ITEM RUN_ID 512 STRING "Run id"
139
143
  APPEND_ITEM RESULTS 32 UINT "Results in the run"
140
144
  APPEND_ITEM RECEIVED 256 STRING "When this COSMOS received the run, UTC"
145
+
146
+ TELEMETRY CONSTELLATION MINIMUM BIG_ENDIAN "The latest contract-minimum alert: a satellite's minimum for a period at risk, missed, or cleared"
147
+ ALLOW_SHORT
148
+ APPEND_ITEM LEVEL 8 UINT "CLEARED, AT_RISK (forecast under the minimum) or MISSED (the period closed under it)"
149
+ STATE CLEARED 0 GREEN
150
+ STATE AT_RISK 1 YELLOW
151
+ STATE MISSED 2 RED
152
+ APPEND_ITEM KIND 256 STRING "minimum_at_risk or minimum_missed"
153
+ APPEND_ITEM SATELLITE 512 STRING "Satellite id"
154
+ APPEND_ITEM BAND 64 STRING "Band, empty for every band"
155
+ APPEND_ITEM PERIOD 128 STRING "day, week or month"
156
+ APPEND_ITEM PERIOD_START 256 STRING "The period's start, UTC"
157
+ APPEND_ITEM PERIOD_END 256 STRING "The period's end (exclusive), UTC"
158
+ APPEND_ITEM MEASURE 128 STRING "gb_delivered, contacts or minutes"
159
+ APPEND_ITEM UNIT 128 STRING "GB, contacts or minutes: the unit of the amounts below"
160
+ APPEND_ITEM TARGET 64 FLOAT "The minimum for the period"
161
+ FORMAT_STRING "%.3f"
162
+ APPEND_ITEM FORECAST 64 FLOAT "At risk: the forecast for the whole period (0 on a missed alert)"
163
+ FORMAT_STRING "%.3f"
164
+ APPEND_ITEM DELIVERED 64 FLOAT "Missed: what the pass logs say was delivered (0 on an at-risk alert)"
165
+ FORMAT_STRING "%.3f"
166
+ APPEND_ITEM SHORTFALL 64 FLOAT "The minimum less the forecast or delivered amount"
167
+ FORMAT_STRING "%.3f"
168
+ APPEND_ITEM DEADLINE 256 STRING "At risk: when to decide on the backups by, UTC"
169
+ APPEND_ITEM EVIDENCE 2048 STRING "Pass ids behind it: at risk, those driving the shortfall; missed, those failed, missed or unlogged"
170
+ APPEND_ITEM MINIMUM_ID 256 STRING "The contract minimum"
171
+ APPEND_ITEM RUN_ID 512 STRING "The run whose forecast raised it; empty when the period close did"
172
+ APPEND_ITEM RAISED 256 STRING "When Constellation raised it, UTC"
173
+ TELEMETRY CONSTELLATION PASS_TRACE BIG_ENDIAN "Forecast: the next pass's trace, as Constellation sent it (plugin trace on)"
174
+ ALLOW_SHORT
175
+ APPEND_ITEM SATELLITE 512 STRING "Satellite id"
176
+ APPEND_ITEM ANTENNA 512 STRING "Antenna id"
177
+ APPEND_ITEM AOS 256 STRING "Predicted acquisition of signal, UTC"
178
+ APPEND_ITEM TRACED 8 UINT "YES when the pass has a trace; NO for a run from before traces, the rest then empty or 0"
179
+ STATE NO 0
180
+ STATE YES 1
181
+ APPEND_ITEM USABLE_S 64 FLOAT "Seconds the link closes (margin at or above 0 dB)"
182
+ UNITS Seconds s
183
+ FORMAT_STRING "%.0f"
184
+ APPEND_ITEM DURATION_S 64 FLOAT "Pass length"
185
+ UNITS Seconds s
186
+ FORMAT_STRING "%.0f"
187
+ APPEND_ITEM CONDITIONS 128 STRING "clear_sky, rain, outage or no_link"
188
+ APPEND_ITEM LIMIT 128 STRING "What caps the pass's GB most: geometry, weather, interference, equipment or none"
189
+ APPEND_ITEM WORST_MARGIN_DB 64 FLOAT "Lowest link margin over the pass (p50); below 0 is an outage"
190
+ UNITS Decibels dB
191
+ FORMAT_STRING "%.2f"
192
+ APPEND_ITEM WORST_CAUSE 128 STRING "Why the margin is lowest there: rain, elevation, interference or none"
193
+ APPEND_ITEM WORST_AT 256 STRING "When the margin is lowest, UTC"
194
+ APPEND_ITEM TRUNCATED 128 STRING "The ends the run window cuts (aos, los), empty when none"
@@ -113,6 +113,50 @@ TABBOOK
113
113
  END
114
114
  END
115
115
  END
116
+ TABITEM "Contract minimum"
117
+ HORIZONTAL
118
+ VERTICAL
119
+ LABELVALUEDESC CONSTELLATION MINIMUM LEVEL "Alert" CONVERTED 18
120
+ LABELVALUEDESC CONSTELLATION MINIMUM SATELLITE "Satellite" CONVERTED 18
121
+ LABELVALUEDESC CONSTELLATION MINIMUM BAND "Band" CONVERTED 18
122
+ LABELVALUEDESC CONSTELLATION MINIMUM PERIOD "Period" CONVERTED 18
123
+ LABELVALUEDESC CONSTELLATION MINIMUM PERIOD_START "From" CONVERTED 18
124
+ LABELVALUEDESC CONSTELLATION MINIMUM DEADLINE "Decide by" CONVERTED 18
125
+ END
126
+ VERTICAL
127
+ LABELVALUEDESC CONSTELLATION MINIMUM UNIT "Unit" CONVERTED 18
128
+ LABELVALUEDESC CONSTELLATION MINIMUM TARGET "Minimum" CONVERTED 18
129
+ LABELVALUEDESC CONSTELLATION MINIMUM FORECAST "Forecast" CONVERTED 18
130
+ LABELVALUEDESC CONSTELLATION MINIMUM DELIVERED "Delivered" CONVERTED 18
131
+ LABELVALUEDESC CONSTELLATION MINIMUM SHORTFALL "Short by" CONVERTED 18
132
+ LABELVALUEDESC CONSTELLATION MINIMUM RAISED "Raised" CONVERTED 18
133
+ END
134
+ END
135
+ SPACER 0 8
136
+ TEXTBOX CONSTELLATION MINIMUM EVIDENCE 900 44
137
+ END
138
+ <%- if [trace, pass_profile].any? { |v| v.to_s.strip.downcase == "on" } -%>
139
+ TABITEM "Pass trace"
140
+ HORIZONTAL
141
+ VERTICAL
142
+ LABELVALUEDESC CONSTELLATION PASS_TRACE SATELLITE "Satellite" CONVERTED 18
143
+ LABELVALUEDESC CONSTELLATION PASS_TRACE ANTENNA "Antenna" CONVERTED 18
144
+ LABELVALUEDESC CONSTELLATION PASS_TRACE AOS "AOS" CONVERTED 18
145
+ LABELVALUEDESC CONSTELLATION PASS_TRACE TRACED "Traced" CONVERTED 18
146
+ LABELVALUEDESC CONSTELLATION PASS_TRACE TRUNCATED "Cut by window" CONVERTED 18
147
+ END
148
+ VERTICAL
149
+ LABELVALUEDESC CONSTELLATION PASS_TRACE USABLE_S "Usable" WITH_UNITS 18
150
+ LABELVALUEDESC CONSTELLATION PASS_TRACE DURATION_S "Length" WITH_UNITS 18
151
+ LABELVALUEDESC CONSTELLATION PASS_TRACE CONDITIONS "Conditions" CONVERTED 18
152
+ LABELVALUEDESC CONSTELLATION PASS_TRACE LIMIT "Limited by" CONVERTED 18
153
+ LABELVALUEDESC CONSTELLATION PASS_TRACE WORST_MARGIN_DB "Worst margin" WITH_UNITS 18
154
+ LABELVALUEDESC CONSTELLATION PASS_TRACE WORST_CAUSE "Worst from" CONVERTED 18
155
+ LABELVALUEDESC CONSTELLATION PASS_TRACE WORST_AT "Worst at" CONVERTED 18
156
+ END
157
+ END
158
+ END
159
+ <%- end -%>
116
160
  TABITEM "MODCOD plan"
117
161
  HORIZONTAL
118
162
  VERTICAL
@@ -60,8 +60,6 @@ const gbOf = (item) => {
60
60
  // A MODCOD plan's series holds each switch, the first at AOS: its changes are the steps after it,
61
61
  // as the COSMOS MODCOD packet's CHANGES and the Lattice bridge count them.
62
62
  const changes = (series) => `${series.length - 1} change${series.length === 2 ? '' : 's'}`;
63
- // A row's value for the per-key bars: the expected GB.
64
- const expected = (item) => (gbOf(item) ? { value: gbOf(item).p50 } : null);
65
63
  const ledgerOf = (item) => item.explain?.ledger?.value || {};
66
64
  // A pass's max elevation: the ledger entry the orbit wrote, under whichever node wrote it.
67
65
  const elevationOf = (item) =>
@@ -75,7 +73,6 @@ const sourceLabel = (source) =>
75
73
  const shortAntenna = (id) => (id && id.includes('__') ? id.split('__').pop() : id);
76
74
  // "SITE-000000000001__ant0" as "000001 ant0": enough of the station to tell rows apart.
77
75
  const stationTag = (id) => (id && id.includes('__') ? `${id.split('__')[0].slice(-6)} ${shortAntenna(id)}` : id);
78
- const stationOf = (item) => item.entity.ground_station_id;
79
76
  const linkLabel = (item) =>
80
77
  item.entity.type === 'antenna'
81
78
  ? `${item.entity.id}`
@@ -86,42 +83,6 @@ const linkLabel = (item) =>
86
83
  const W = 640;
87
84
  const tip = (text) => `data-tip="${esc(text)}"`;
88
85
 
89
- function axisTicks(max, n = 4) {
90
- if (!(max > 0)) return [0];
91
- const raw = max / n;
92
- const mag = 10 ** Math.floor(Math.log10(raw));
93
- const step = [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= raw) || raw;
94
- // The top tick is at or above max, so the data never runs past the axis.
95
- const out = [0];
96
- while (out[out.length - 1] < max - step * 0.01) out.push(out[out.length - 1] + step);
97
- return out;
98
- }
99
-
100
- /** The expected value as a line over time buckets. */
101
- function lineChart(buckets, { height = 180, unit = 'GB' } = {}) {
102
- const pad = { l: 44, r: 12, t: 12, b: 26 };
103
- const h = height;
104
- const max = Math.max(...buckets.map((b) => b.p50), 0.001);
105
- const ticks = axisTicks(max);
106
- const top = ticks[ticks.length - 1];
107
- const x = (i) => pad.l + (i / Math.max(buckets.length - 1, 1)) * (W - pad.l - pad.r);
108
- const y = (v) => h - pad.b - (v / top) * (h - pad.t - pad.b);
109
- const line = buckets.map((b, i) => `${i ? 'L' : 'M'}${x(i)},${y(b.p50)}`).join(' ');
110
- const grid = ticks
111
- .map((t) => `<line class="cf-grid" x1="${pad.l}" x2="${W - pad.r}" y1="${y(t)}" y2="${y(t)}"/><text class="cf-axis" x="${pad.l - 6}" y="${y(t) + 4}" text-anchor="end">${big(t)}</text>`)
112
- .join('');
113
- const labels = buckets
114
- .map((b, i) => (i % Math.ceil(buckets.length / 8) === 0 ? `<text class="cf-axis" x="${x(i)}" y="${h - 8}" text-anchor="middle">${esc(b.label)}</text>` : ''))
115
- .join('');
116
- const hits = buckets
117
- .map(
118
- (b, i) =>
119
- `<rect class="cf-hit" x="${x(i) - (W - pad.l - pad.r) / buckets.length / 2}" y="${pad.t}" width="${(W - pad.l - pad.r) / buckets.length}" height="${h - pad.t - pad.b}" ${tip(`${b.label} · ${num(b.p50)} ${unit} expected · ${b.count} passes`)}/>`,
120
- )
121
- .join('');
122
- return `<svg class="cf-chart" viewBox="0 0 ${W} ${h}" role="img" aria-label="Expected ${unit} over time">${grid}<path class="cf-line" d="${line}"/>${labels}${hits}</svg>`;
123
- }
124
-
125
86
  /** Horizontal bars, one row per key, each with an optional line from the bar to `to`. */
126
87
  function rangeBars(rows, { unit = 'GB', digits = 1 } = {}) {
127
88
  const rowH = 20;
@@ -219,34 +180,15 @@ function upcoming(run) {
219
180
  return run.items.filter((i) => !i.until || Date.parse(i.until) > now).sort((a, b) => a.target_at.localeCompare(b.target_at));
220
181
  }
221
182
 
222
- function hourly(items) {
223
- const now = Date.now();
224
- const start = Math.floor(now / 3600e3) * 3600e3;
225
- const buckets = Array.from({ length: 24 }, (_, k) => ({ label: new Date(start + k * 3600e3).toISOString().slice(11, 16), p50: 0, count: 0 }));
226
- for (const item of items) {
227
- const g = gbOf(item);
228
- const k = Math.floor((Date.parse(item.target_at) - start) / 3600e3);
229
- if (!g || !(k >= 0 && k < 24)) continue;
230
- buckets[k].p50 += g.p50;
231
- buckets[k].count += 1;
232
- }
233
- return buckets;
183
+ /** One row per group of a breakdown the run's totals serve (run.totals.by_*), largest first:
184
+ * never summed here, as overlapping passes of one radio or antenna count once only by its rule. */
185
+ function served(groups, row) {
186
+ return Object.entries(groups || {})
187
+ .map(([label, g]) => ({ label, ...row(g) }))
188
+ .sort((a, b) => b.value - a.value);
234
189
  }
235
190
 
236
- function perKey(items, key, value) {
237
- const out = new Map();
238
- for (const item of items) {
239
- const k = key(item);
240
- const g = value(item);
241
- if (!k || !g) continue;
242
- const row = out.get(k) || { label: k, value: 0, count: 0 };
243
- row.value += g.value;
244
- if (g.to !== undefined) row.to = (row.to ?? 0) + g.to;
245
- row.count += 1;
246
- out.set(k, row);
247
- }
248
- return [...out.values()].sort((a, b) => b.value - a.value);
249
- }
191
+ const unserved = '<p class="cf-empty">Constellation serves no totals for this run.</p>';
250
192
 
251
193
  const tile = (label, value, hint) => `<div class="cf-tile"><div class="cf-tile-value">${esc(value)}</div><div class="cf-tile-label">${esc(label)}</div>${hint ? `<div class="cf-tile-hint">${esc(hint)}</div>` : ''}</div>`;
252
194
  const section = (title, body, note) => `<section class="cf-section"><h3>${esc(title)}</h3>${note ? `<p class="cf-note">${esc(note)}</p>` : ''}${body}</section>`;
@@ -301,6 +243,8 @@ export function loss(item) {
301
243
  const SHARES = ['probability', 'share'];
302
244
  // rfi-watch items are links whose value is RFI in dB (read as its p50) with a lock-loss risk (a
303
245
  // share), and whose action is a reroute with no deadline: never GB, never a swap.
246
+ // Where a pass comes from (entity.source), as constellation_space.results.SOURCES words it.
247
+ const SOURCES = { computed: 'computed from orbits', 'computed:continuous': 'a continuous slot of one UTC day' };
304
248
  const pct = (v) => (typeof v === 'number' ? `${Math.round(v * 100)}%` : num(v));
305
249
  const RFI = {
306
250
  tiles(run, items) {
@@ -354,34 +298,32 @@ const RFI = {
354
298
  };
355
299
 
356
300
  export const VIEWS = {
301
+ // Every total is the run's as Constellation serves it (run.totals), never a sum of the items
302
+ // here: overlapping passes of one radio or antenna count once only by its rule. A run it
303
+ // serves no totals for shows —.
357
304
  tiles(run, items) {
358
305
  if (run.kind === 'rfi-watch') return RFI.tiles(run, items);
306
+ const all = run.totals?.overall;
359
307
  if (run.kind === 'audit-ledger') {
360
- const possible = items.reduce((s, i) => s + (ledgerOf(i).possible_gb ?? 0), 0);
361
- const delivered = items.reduce((s, i) => s + (ledgerOf(i).delivered_gb ?? 0), 0);
362
- const dead = items.filter((i) => ledgerOf(i).dead).length;
363
- return `<div class="cf-tiles">${tile('passes audited', items.length)}${tile('GB delivered', big(delivered), `of ${big(possible)} possible`)}${tile('delivered', possible ? `${Math.round((delivered / possible) * 100)}%` : '—')}${tile('dead passes', dead, 'failed, missed or unlogged')}</div>`;
308
+ return `<div class="cf-tiles">${tile('passes audited', items.length)}${tile('GB delivered', big(all?.delivered_gb), all ? `of ${big(all.possible_gb)} possible` : '')}${tile('delivered', pct(all?.delivered_share))}${tile('dead passes', all?.dead_passes ?? '—', 'failed or missed')}</div>`;
364
309
  }
365
310
  if (run.kind === 'antenna-capacity') {
366
- const gb = items.reduce((s, i) => s + (gbOf(i)?.p50 ?? 0), 0);
367
- const minutes = items.reduce((s, i) => s + (gbOf(i)?.sellable_min ?? 0), 0);
368
- return `<div class="cf-tiles">${tile('antenna-days', items.length)}${tile('sellable minutes', big(minutes))}${tile('GB expected', big(gb), 'p50, summed')}${tile('antennas', new Set(items.map((i) => i.entity.id)).size)}</div>`;
311
+ return `<div class="cf-tiles">${tile('antenna-days', items.length)}${tile('sellable minutes', big(all?.minutes))}${tile('GB expected', big(all?.gb), 'p50, the whole run')}${tile('antennas', new Set(items.map((i) => i.entity.id)).size)}</div>`;
369
312
  }
370
313
  if (run.kind === 'rain-fade-swap') {
371
314
  const swaps = items.filter(actionable).sort((a, b) => a.action.deadline.localeCompare(b.action.deadline));
372
315
  const approved = swaps.filter((i) => actionState(i) === 'approved').length;
373
316
  const held = items.filter((i) => actionState(i) === 'pending').length;
374
- const gain = swaps.reduce((s, i) => s + (typeof i.action.gain_gb === 'number' ? i.action.gain_gb : 0), 0);
375
317
  const soonest = swaps.find((i) => Date.parse(i.action.deadline) > Date.now());
376
318
  const booked = swaps.filter((i) => i.action.to).length;
377
319
  const hint = approved || held ? `${approved} approved · ${held} awaiting approval` : `${booked} with a better backup`;
378
- return `<div class="cf-tiles">${tile('swaps to decide', swaps.length - approved, hint)}${tile('GB the advice adds', big(gain), 'over doing nothing (p50), summed')}${tile('soonest decision', soonest ? until(soonest.action.deadline) : '—', soonest ? `decide by ${minute(soonest.action.deadline)}` : '')}${tile('workflow version', `v${run.workflow_version}`)}</div>`;
320
+ return `<div class="cf-tiles">${tile('swaps to decide', swaps.length - approved, hint)}${tile('GB recovered', big(all?.recovered_gb), 'by the swaps that count (p50)')}${tile('soonest decision', soonest ? until(soonest.action.deadline) : '—', soonest ? `decide by ${minute(soonest.action.deadline)}` : '')}${tile('workflow version', `v${run.workflow_version}`)}</div>`;
379
321
  }
380
- const day = items.filter((i) => Date.parse(i.target_at) < Date.now() + 86400e3);
381
- const p50 = day.reduce((s, i) => s + (gbOf(i)?.p50 ?? 0), 0);
322
+ // The day from when the run was made.
323
+ const day = run.totals?.next_24h?.overall;
382
324
  const swaps = items.filter(actionable).length;
383
325
  const next = items.find((i) => Date.parse(i.target_at) > Date.now());
384
- return `<div class="cf-tiles">${tile('passes, next 24 h', day.length)}${tile('GB expected', big(p50), 'next 24 h, summed')}${swaps ? tile('swaps advised', swaps, 'see Risk below') : tile('next pass', next ? `${hhmm(next.target_at)}Z` : '—', next ? `${next.entity.satellite_id} @ ${shortAntenna(next.entity.antenna_id)}` : '')}${tile('workflow version', `v${run.workflow_version}`)}</div>`;
326
+ return `<div class="cf-tiles">${tile('passes, next 24 h', day?.counted_passes ?? '—')}${tile('GB expected', big(day?.gb), 'next 24 h from the run')}${swaps ? tile('swaps advised', swaps, 'see Risk below') : tile('next pass', next ? `${hhmm(next.target_at)}Z` : '—', next ? `${next.entity.satellite_id} @ ${shortAntenna(next.entity.antenna_id)}` : '')}${tile('workflow version', `v${run.workflow_version}`)}</div>`;
385
327
  },
386
328
 
387
329
  chart(run, items) {
@@ -424,10 +366,10 @@ export const VIEWS = {
424
366
  );
425
367
  }
426
368
  if (run.kind === 'audit-ledger') {
427
- const rows = perKey(items, stationOf, (i) => ({ value: ledgerOf(i).delivered_gb ?? 0, to: ledgerOf(i).possible_gb ?? 0 }));
369
+ const rows = served(run.totals?.by_station, (g) => ({ value: g.delivered_gb ?? 0, to: g.possible_gb ?? 0, count: g.passes }));
428
370
  return section(
429
371
  'Delivered against possible, per station',
430
- rangeBars(rows.map((r) => ({ ...r, tip: `${r.label}: ${num(r.value)} GB delivered of ${num(r.to)} possible, ${r.count} passes` }))),
372
+ rows.length ? rangeBars(rows.map((r) => ({ ...r, tip: `${r.label}: ${num(r.value)} GB delivered of ${num(r.to)} possible, ${r.count} passes` }))) : unserved,
431
373
  'The bar is what was delivered; the line runs to what was possible.',
432
374
  );
433
375
  }
@@ -437,20 +379,23 @@ export const VIEWS = {
437
379
  const rows = [...mix.entries()].sort((a, b) => b[1] - a[1]).slice(0, 12).map(([label, value]) => ({ label, value, tip: `${label}: chosen ${value} times across the plan` }));
438
380
  return section('MODCOD mix across the plan', rangeBars(rows, { unit: 'steps', digits: 0 }), 'How often each MODCOD is planned. Select a pass below to see its own plan.');
439
381
  }
440
- return section('Expected GB over the next 24 hours', lineChart(hourly(items)), 'Hover an hour for its passes.');
382
+ const rows = served(run.totals?.next_24h?.by_satellite, (g) => ({ value: g.gb, count: g.counted_passes }));
383
+ return section(
384
+ 'Expected GB per satellite, next 24 h',
385
+ rows.length ? rangeBars(rows.map((r) => ({ ...r, tip: `${r.label}: ${num(r.value)} GB expected over ${r.count} passes` }))) : unserved,
386
+ 'From when the run was made, as Constellation totals it.',
387
+ );
441
388
  },
442
389
 
443
390
  breakdown(run, items) {
444
391
  if (['audit-ledger', 'modcod-plan', 'rfi-watch'].includes(run.kind)) return '';
392
+ const rows = served(run.totals?.by_antenna, (g) => ({ value: g.gb, count: g.counted_passes })).slice(0, 14);
445
393
  if (run.kind === 'antenna-capacity') {
446
- const rows = perKey(items, (i) => i.entity.id, expected).slice(0, 14);
447
- return section('Antennas ranked by expected GB', rangeBars(rows.map((r) => ({ ...r, label: shortAntenna(r.label) === r.label ? r.label : `${r.label.split('__')[0].slice(-6)} ${shortAntenna(r.label)}`, tip: `${r.label}: ${num(r.value)} GB expected over ${r.count} days` }))));
394
+ return section('Antennas ranked by expected GB', rows.length ? rangeBars(rows.map((r) => ({ ...r, label: shortAntenna(r.label) === r.label ? r.label : `${r.label.split('__')[0].slice(-6)} ${shortAntenna(r.label)}`, tip: `${r.label}: ${num(r.value)} GB expected over ${r.count} passes` }))) : unserved);
448
395
  }
449
- const day = items.filter((i) => Date.parse(i.target_at) < Date.now() + 86400e3);
450
- const rows = perKey(day, (i) => i.entity.antenna_id, expected).slice(0, 14);
451
396
  return section(
452
- 'Where the GB lands: antennas, next 24 h',
453
- rangeBars(rows.map((r) => ({ ...r, label: stationTag(r.label), tip: `${r.label}: ${num(r.value)} GB expected over ${r.count} passes` }))),
397
+ 'Where the GB lands: antennas, the whole run',
398
+ rows.length ? rangeBars(rows.map((r) => ({ ...r, label: stationTag(r.label), tip: `${r.label}: ${num(r.value)} GB expected over ${r.count} passes` }))) : unserved,
454
399
  );
455
400
  },
456
401
 
@@ -520,7 +465,8 @@ export const VIEWS = {
520
465
  const range = g
521
466
  ? `<div class="cf-range-labels"><b>${num(g.p50)} GB expected</b></div>`
522
467
  : '';
523
- return `<aside class="cf-ledger"><h3>${run.kind === 'rfi-watch' ? 'Why this link is flagged' : 'Why this pass is worth what it is'}</h3><div class="cf-ledger-title">${esc(linkLabel(item))}<span>${minute(item.target_at)}${item.until ? ` – ${hhmm(item.until)}Z` : ''}</span></div>${range}<table class="cf-table cf-compact">${laneRows}</table>${plan}<p class="cf-note">Workflow ${esc(run.workflow)} v${esc(item.workflow_version ?? run.workflow_version)} · run ${esc(run.run_id)}</p></aside>`;
468
+ const source = item.entity.source ? `<p class="cf-note">Source: ${esc(SOURCES[item.entity.source] ?? item.entity.source)}</p>` : '';
469
+ return `<aside class="cf-ledger"><h3>${run.kind === 'rfi-watch' ? 'Why this link is flagged' : 'Why this pass is worth what it is'}</h3><div class="cf-ledger-title">${esc(linkLabel(item))}<span>${minute(item.target_at)}${item.until ? ` – ${hhmm(item.until)}Z` : ''}</span></div>${source}${range}<table class="cf-table cf-compact">${laneRows}</table>${plan}<p class="cf-note">Workflow ${esc(run.workflow)} v${esc(item.workflow_version ?? run.workflow_version)} · run ${esc(run.run_id)}</p></aside>`;
524
470
  },
525
471
  };
526
472
 
@@ -559,7 +505,6 @@ const STYLE = `
559
505
  .cf-note { color:var(--cf-muted); font-size:12px; margin:0 0 6px; }
560
506
  .cf-empty { color:var(--cf-muted); }
561
507
  .cf-chart { width:100%; height:auto; display:block; overflow:visible; }
562
- .cf-grid { stroke:var(--cf-line); stroke-width:1; }
563
508
  .cf-axis, .cf-label, .cf-value { font-size:9.5px; fill:var(--cf-muted); }
564
509
  .cf-chart { max-width:820px; }
565
510
  .cf-label { fill:var(--cf-ink); }
@@ -570,11 +515,9 @@ const STYLE = `
570
515
  .cf-dot { fill:var(--cf-series); stroke:var(--cf-surface); stroke-width:2; }
571
516
  .cf-dot-warn { fill:var(--cf-warn); stroke:var(--cf-surface); stroke-width:2; }
572
517
  .cf-heat { fill:var(--cf-series); fill-opacity:calc(.08 + var(--share) * .92); }
573
- .cf-hit { fill:transparent; }
574
518
  .cf-heat-label { font-size:9.5px; fill:var(--cf-ink); }
575
519
  .cf-on-dark { fill:#fff; }
576
520
  .cf-step-label { font-size:10px; fill:var(--cf-ink); }
577
- .cf-hit:hover { fill:var(--cf-line); }
578
521
  g[data-tip]:hover .cf-bar, g[data-tip]:hover .cf-dot { filter:brightness(1.15); }
579
522
  .cf-cards { display:grid; grid-template-columns:repeat(auto-fill, minmax(260px,1fr)); gap:10px; }
580
523
  .cf-card { border:1px solid var(--cf-line); border-left:3px solid var(--cf-warn); border-radius:8px; padding:10px 12px; background:var(--cf-surface); }
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: openc3-cosmos-constellation
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.8.6
4
+ version: 0.10.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Constellation Space Corp
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-11-25 00:00:00.000000000 Z
11
+ date: 2026-12-04 00:00:00.000000000 Z
12
12
  dependencies: []
13
13
  description: 'A CONSTELLATION target whose packets a bridge microservice fills from
14
14
  the Constellation feed: the next predicted pass, the next 24 hours, the soonest