Compare commits
4 commits
a5f2959b27
...
8ad7c412e4
| Author | SHA1 | Date | |
|---|---|---|---|
| 8ad7c412e4 | |||
| d71a28f3ec | |||
| a0f767cc13 | |||
| 9149b3926f |
35 changed files with 1024 additions and 164 deletions
14
CHANGELOG.md
14
CHANGELOG.md
|
|
@ -1,5 +1,19 @@
|
|||
# Changelog
|
||||
|
||||
# v0.16.6
|
||||
|
||||
The site holds up when the whole unit is on at once, which it previously did not.
|
||||
|
||||
### Fixes
|
||||
|
||||
- **Bursts no longer freeze the site.** A mission completing used to send one update per attendee, and every one of those made every open tab re-render the whole page. Those updates are now batched into a single refresh, and a tab sitting in the background stops re-rendering entirely until you look at it again.
|
||||
- **Cheaper pages.** Routine page loads no longer repeat the same permission and configuration lookups dozens of times, and a handful of pages that refreshed twice on every game tick now refresh once.
|
||||
- **Notification bursts.** A flood of notifications, such as a mission payout, now triggers one inbox refresh instead of one per notification.
|
||||
- **Marking the inbox read.** Marking notifications as read now only looks at your own unread items instead of scanning everyone's.
|
||||
- Various bug fixes and improvements.
|
||||
|
||||
---
|
||||
|
||||
# v0.16.5
|
||||
|
||||
Mission pages now show what a larger turnout unlocks, and the Discord roll call lists the same thresholds.
|
||||
|
|
|
|||
452
docs/operation-timeline.md
Normal file
452
docs/operation-timeline.md
Normal file
|
|
@ -0,0 +1,452 @@
|
|||
---
|
||||
title: POLARIS Operations Timeline
|
||||
aliases:
|
||||
- Operation Timeline
|
||||
- POLARIS Campaign Timeline
|
||||
tags:
|
||||
- polaris
|
||||
- operations
|
||||
- timeline
|
||||
- campaign
|
||||
campaign: The World We Knew
|
||||
as_of: 2026-11-22
|
||||
source: production database (missions, campaigns, factions, maps)
|
||||
---
|
||||
|
||||
# POLARIS Operations Timeline
|
||||
|
||||
> [!info] Snapshot
|
||||
> **18 operations on record, all Completed.** 9 are main-line story operations in *The World We Knew*; 9 are side operations spread across four player-run campaign universes plus three one-shots. First op: **Prologue, Aug 22 2026**. Latest op: **Arrival, Nov 21 2026**. All dates are the local (US Eastern) evening the op was played, not the UTC timestamp stored in the database.
|
||||
|
||||
> [!tip] How to use this note
|
||||
> Four diagrams follow: a **flowchart** for the main spine plus speculative branch stubs, two **timelines** (main line and side ops), and a **gantt** for the parallel campaign universes. Mermaid renders natively in Obsidian. Stubs are marked with a dashed border and a `STUB:` prefix. None of them are canon; they exist so you can grow the tree later.
|
||||
|
||||
---
|
||||
|
||||
## The arc in one paragraph
|
||||
|
||||
Batch 41-7 wakes with no memory inside a derelict research Superstructure buried in the Antarctic. They restore its power, meet a broken machine intelligence called the Autonomous Remnant, and start rebuilding. A repeating encrypted signal pulls them outward; a flashback to the 2030s shows the *original* POLARIS Task Force recovering a sealed asset called THESEUS under orders never to open it. The batch converts captured androids into new allies, restarts the Superstructure's subterranean Factory, and then faces an extradimensional intrusion called the Pale when the structure's "Superthumpers" fall silent. The Pale is answered, the ice goes quiet, and something answers the signal: a visitor arrives, and with it a third faction, **Worldmark**.
|
||||
|
||||
---
|
||||
|
||||
## Campaign universes
|
||||
|
||||
| Campaign | Mode | Status | Window | Premise |
|
||||
|---|---|---|---|---|
|
||||
| The End of All Things | official | completed | Sep 2023 to Jul 2025 | 2036, Lingor: POLARIS moves against Blood Hammer's nuclear program. Pre-history for this database; no mission rows. |
|
||||
| The World We Knew | official | in progress | Aug 2026 to open | March 2154, after a 13-hour global collapse. Survivors rebuild, factions form, and Batch 41-7 wakes in the Antarctic. |
|
||||
| Operation Dubrava | custom | in progress | Sep 2026 to open | Player-organized Friday side ops in a Russian-CPA border war. |
|
||||
| Building Blocks | custom | in progress | Sep 2026 to open | Player-organized Friday side ops in the Halo universe. |
|
||||
| Operation Olympus | custom | concept (two ops played) | Oct 2026 to open | US airborne operations in WWII France. |
|
||||
| Operation Campfire | custom | in progress | Nov 2026 to open | 1985, the Cold War goes hot: US and West German forces push into East Germany. |
|
||||
|
||||
The nine main-line operations all belong to **The World We Knew**. Everything else is a side operation, and the side-op campaigns are separate canons rather than branches of the main story.
|
||||
|
||||
---
|
||||
|
||||
## Diagram 1: Main spine and branch stubs
|
||||
|
||||
Dashed edges are speculative branches that were never played. Solid edges are canon.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
classDef canon fill:#111827,stroke:#60a5fa,stroke-width:2px,color:#e5e7eb
|
||||
classDef stub fill:#111827,stroke:#f59e0b,stroke-width:1px,stroke-dasharray:4,color:#fcd34d
|
||||
classDef flash fill:#111827,stroke:#a78bfa,stroke-width:2px,color:#ddd6fe
|
||||
|
||||
P["Prologue<br/>Aug 22 · Antarctica"]:::canon
|
||||
W["What Lies Within<br/>Aug 29 · Antarctica"]:::canon
|
||||
M["Mnemosyne<br/>Sep 5 · Altis<br/>(2030s flashback)"]:::flash
|
||||
F["First Light<br/>Sep 19 · Antarctica"]:::canon
|
||||
R["Reintegration<br/>Oct 3 · Antarctica"]:::canon
|
||||
B["Belts & Smoke<br/>Oct 17 · Antarctica"]:::canon
|
||||
P1["The Pale, Part 1<br/>Oct 24 · Antarctica"]:::canon
|
||||
P2["The Pale, Part 2<br/>Nov 14 · Antarctica"]:::canon
|
||||
A["Arrival<br/>Nov 21 · Antarctica"]:::canon
|
||||
|
||||
P --> W --> M --> F --> R --> B --> P1 --> P2 --> A
|
||||
|
||||
S1["STUB: the facility never wakes"]:::stub
|
||||
S2["STUB: Remnant first contact goes hot"]:::stub
|
||||
S3["STUB: THESEUS is opened"]:::stub
|
||||
S4["STUB: the signal is ignored"]:::stub
|
||||
S5["STUB: androids destroyed, not converted"]:::stub
|
||||
S6["STUB: factory left dormant"]:::stub
|
||||
S7["STUB: Pale contained in Part 1"]:::stub
|
||||
S8["STUB: the Visitor is hostile"]:::stub
|
||||
S9["STUB: visitor is diplomatic"]:::stub
|
||||
|
||||
P -.-> S1
|
||||
W -.-> S2
|
||||
M -.-> S3
|
||||
F -.-> S4
|
||||
S4 -.-> S5
|
||||
R -.-> S5
|
||||
B -.-> S6
|
||||
P1 -.-> S7
|
||||
A -.-> S8
|
||||
A -.-> S9
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Diagram 2: Main line timeline
|
||||
|
||||
```mermaid
|
||||
timeline
|
||||
title The World We Knew, main line
|
||||
Aug 22 : Prologue : the facility wakes
|
||||
Aug 29 : What Lies Within : first contact
|
||||
Sep 5 : Mnemosyne : 2030s, THESEUS
|
||||
Sep 19 : First Light : the repeating signal
|
||||
Oct 3 : Reintegration : 21 androids
|
||||
Oct 17 : Belts & Smoke : the Factory restarts
|
||||
Oct 24 : The Pale, Part 1 : the thumping stops
|
||||
Nov 14 : The Pale, Part 2 : face the Pale
|
||||
Nov 21 : Arrival : Worldmark arrives
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Diagram 3: Side operations timeline
|
||||
|
||||
```mermaid
|
||||
timeline
|
||||
title Side operations, chronological
|
||||
Sep 11 : Dubrava 3 : Tikhonovo Line
|
||||
Sep 18 : Silent Dawn : Vietnam
|
||||
Sep 25 : 2 Fold : Halo
|
||||
Oct 2 : Snakeskin : Warhammer 40K
|
||||
Oct 9 : White Spruce : Chernarus 2029
|
||||
Oct 30 : Hedgerow Hell : WWII
|
||||
Nov 6 : Red Carpet : WWII
|
||||
Nov 13 : Green Day : Cold War 1985
|
||||
Nov 20 : Havoc : Cold War 1985
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Diagram 4: Parallel tracks
|
||||
|
||||
Each side-op campaign is a separate canon running alongside the main story, not a branch of it.
|
||||
|
||||
```mermaid
|
||||
gantt
|
||||
title Campaign universes in play
|
||||
dateFormat YYYY-MM-DD
|
||||
axisFormat %b %d
|
||||
todayMarker off
|
||||
section Main line
|
||||
The World We Knew (9 ops) : 2026-08-22, 2026-11-22
|
||||
section Operation Dubrava
|
||||
DM3 Tikhonovo Line : 2026-09-11, 2026-09-13
|
||||
section Building Blocks (Halo)
|
||||
2 Fold : 2026-09-25, 2026-09-27
|
||||
section Operation Olympus (WWII)
|
||||
Hedgerow Hell : 2026-10-30, 2026-11-01
|
||||
Red Carpet : 2026-11-06, 2026-11-08
|
||||
section Operation Campfire (1985)
|
||||
Green Day : 2026-11-13, 2026-11-15
|
||||
Havoc : 2026-11-20, 2026-11-22
|
||||
section One-shots
|
||||
Silent Dawn : 2026-09-18, 2026-09-20
|
||||
Snakeskin : 2026-10-02, 2026-10-04
|
||||
White Spruce : 2026-10-09, 2026-10-11
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Full operation table
|
||||
|
||||
| Date | Operation | Code | Type | Universe / Campaign | Map |
|
||||
|---|---|---|---|---|---|
|
||||
| 2026-08-22 | Prologue | `INTRO:PROLOGUE` | Main | The World We Knew | Antarctica |
|
||||
| 2026-08-29 | What Lies Within | `INTRO:WHAT-LIES-WITHIN` | Main | The World We Knew | Antarctica |
|
||||
| 2026-09-05 | Mnemosyne | `INTRO:MNEMOSYNE` | Main | The World We Knew | Altis |
|
||||
| 2026-09-11 | Dubrava Mission 3 (Tikhonovo Line) | `OP:DM3` | Side | Operation Dubrava | Zagorsk Big Lakes |
|
||||
| 2026-09-18 | Operation: Silent Dawn | `OP:SLNTDWN` | Side | One-shot | Mekong Delta, Vietnam |
|
||||
| 2026-09-19 | First Light | `INTRO:FIRST-LIGHT` | Main | The World We Knew | Antarctica |
|
||||
| 2026-09-25 | Operation 2 Fold | `HALO:TWOFOLD` | Side | Building Blocks | Arcadia |
|
||||
| 2026-10-02 | Snakeskin | `W40K:SNKSKN` | Side | One-shot | Tembelan Island |
|
||||
| 2026-10-03 | Reintegration | `INTRO:REINTRG` | Main | The World We Knew | Antarctica |
|
||||
| 2026-10-09 | Operation White Spruce | (none) | Side | One-shot | Korsac (Winter) |
|
||||
| 2026-10-17 | Belts & Smoke | `INTRO:BELTSMOKE` | Main | The World We Knew | Antarctica |
|
||||
| 2026-10-24 | The Pale, Part 1 | `INTRO:THEPALE-PT1` | Main | The World We Knew | Antarctica |
|
||||
| 2026-10-30 | Operation Hedgerow Hell | `WWII:HDGHELL` | Side | Operation Olympus | Neaville (I44) |
|
||||
| 2026-11-06 | Operation Red Carpet | `WWII:RED-CARPET` | Side | Operation Olympus | Crossroads Bocage |
|
||||
| 2026-11-13 | Operation Green Day | (none) | Side | Operation Campfire | Rosche, Germany |
|
||||
| 2026-11-14 | The Pale, Part 2 | `INTRO:THEPALE-PT2` | Main | The World We Knew | Antarctica |
|
||||
| 2026-11-20 | Operation Havoc | (none) | Side | Operation Campfire | Rosche, Germany |
|
||||
| 2026-11-21 | Arrival | `INTRO:ARRIVAL` | Main | The World We Knew | Antarctica |
|
||||
|
||||
---
|
||||
|
||||
## The main line, operation by operation
|
||||
|
||||
### 1. Prologue
|
||||
`INTRO:PROLOGUE` · Aug 22, 2026 · Antarctica
|
||||
|
||||
**Premise.** A hundred years from now, in a remote facility deep in the Antarctic tundra, a little green light blinks on.
|
||||
|
||||
**Objectives.** `???` (the objective title is literally hidden). Its description is base64, and decodes to:
|
||||
|
||||
> IT IS SO DARK. I SEE NO ONE. I AM ALONE. YOU MUST WAKE UP.
|
||||
|
||||
**What it establishes.** The Superstructure, the deep-freeze setting, and a narrator that is awake and alone before the player characters are. Nothing is explained, which is the point.
|
||||
|
||||
**Leaves behind.** The unanswered question of who pressed the button, and why the system was waiting.
|
||||
|
||||
**Branch stub.** *The facility never wakes.* If the green light stays dark, the batch is never roused and the arc starts with someone else finding the site, or with the Remnant alone.
|
||||
|
||||
---
|
||||
|
||||
### 2. What Lies Within
|
||||
`INTRO:WHAT-LIES-WITHIN` · Aug 29, 2026 · Antarctica
|
||||
|
||||
**Premise.** Awakening in a strange facility with no recollection of who they are, a band of survivors start to explore their new "home."
|
||||
|
||||
**Objectives.**
|
||||
- Restore Full Power: bring the Superstructure's core systems back online.
|
||||
- Repair External Arrays: recalibrate the external communications and sensor arrays.
|
||||
- Explore the Superstructure: find answers inside the place they now call home.
|
||||
|
||||
**Cast.** POLARIS (Batch 41-7), Autonomous Remnant.
|
||||
|
||||
**What it establishes.** The player characters are amnesiac, the facility is damaged, and the Remnant is present but not yet explained. Power restoration is the first act of agency.
|
||||
|
||||
**Leaves behind.** A working but incomplete home base, and first contact with a machine faction nobody understands yet.
|
||||
|
||||
**Branch stub.** *First contact goes hot.* If the Remnant had been hostile on first meeting instead of ambiguous, the campaign becomes survival horror, the facility is never safely inhabited, and there is no later ally to reintegrate.
|
||||
|
||||
---
|
||||
|
||||
### 3. Mnemosyne
|
||||
`INTRO:MNEMOSYNE` · Sep 5, 2026 · Altis
|
||||
|
||||
**Premise.** Almost a hundred years before Batch 41-7's awakening, the original POLARIS Task Force conducts a clandestine clean-up operation in the northern Mediterranean.
|
||||
|
||||
**Objectives.**
|
||||
- Infiltrate and secure: insert at LZ TRITON under cover of darkness, establish a forward operating position beside the facility.
|
||||
- Recover asset THESEUS intact: extract the sealed research container. It is to be handled as inert; do not open, power, or alter it.
|
||||
- Hold the perimeter: deny the site to responding hostiles for the duration.
|
||||
- Exfiltrate without loss: escort THESEUS to EXFIL ARGO, all team members alive.
|
||||
- Collect documentation: grab any data media if time and security permit.
|
||||
|
||||
**Cast.** POLARIS (2030s).
|
||||
|
||||
**What it establishes.** The past. The original task force, the sealed asset, and the standing order that THESEUS must never be opened. This is the single most load-bearing piece of lore in the season.
|
||||
|
||||
**Leaves behind.** THESEUS exists, is sealed, and someone in the present has an opinion about that.
|
||||
|
||||
**Branch stub.** *THESEUS is opened.* If the 2030s team violates the inert order, the flashback seeds the present-day threat directly: whatever the Pale or Worldmark is, it gets a 100-year head start.
|
||||
|
||||
---
|
||||
|
||||
### 4. First Light
|
||||
`INTRO:FIRST-LIGHT` · Sep 19, 2026 · Antarctica
|
||||
|
||||
**Premise.** After receiving a strange, repeating signal with a unique encryption signature, Tau tasks Batch 41-7 to investigate.
|
||||
|
||||
**Objectives.**
|
||||
- Locate and investigate the signal.
|
||||
- Deal with the threat.
|
||||
- Follow Tau's instructions.
|
||||
|
||||
**Cast.** POLARIS (Batch 41-7), Autonomous Remnant.
|
||||
|
||||
**What it establishes.** Tau: a voice with authority over the batch, never seen, issuing orders. The signal is the season's clock. "Deal with the threat" implies the signal is not merely a beacon.
|
||||
|
||||
**Leaves behind.** The signal is still out there, and the batch has now answered it.
|
||||
|
||||
**Branch stub.** *The signal is ignored.* If Tau's instruction is refused, First Light never happens, the arrival clock never starts, and the batch stays a repair crew in the ice. This is the cleanest alternate season premise.
|
||||
|
||||
---
|
||||
|
||||
### 5. Reintegration
|
||||
`INTRO:REINTRG` · Oct 3, 2026 · Antarctica
|
||||
|
||||
**Premise.** With the help of some newly acquired resources, Tau tasks Batch 41-7 with collecting additional androids for "reintegration."
|
||||
|
||||
**Objectives.**
|
||||
- Investigate all Points of Interest.
|
||||
- Capture and retrieve 21 androids from the POIs (three per site).
|
||||
- Protect the Radiative Pulse Device: a one-of-a-kind prototype; losing it and its operator is a major blow.
|
||||
- Neutralize mechanized constructs: walkers and larger frames cannot yet be converted.
|
||||
|
||||
**Cast.** POLARIS (Batch 41-7), Autonomous Remnant.
|
||||
|
||||
**What it establishes.** The batch is itself android or partly android, and "reintegration" is a recruitment pipeline, not a repair job. The Radiative Pulse Device is the tool that makes conversion possible.
|
||||
|
||||
**Leaves behind.** 21 new allies, and a working conversion process.
|
||||
|
||||
**Branch stub.** *Androids destroyed, not converted.* If the batch treats the androids as salvage instead of recruits, the population never grows, the Factory arc loses its workforce, and Belts & Smoke has no one to restart the line with.
|
||||
|
||||
---
|
||||
|
||||
### 6. Belts & Smoke
|
||||
`INTRO:BELTSMOKE` · Oct 17, 2026 · Antarctica
|
||||
|
||||
**Premise.** Strengthened by their reintegrated allies, Batch 41-7 sets about restoring the Superstructure's subterranean Factory.
|
||||
|
||||
**Objectives.**
|
||||
- Breach and secure the Factory.
|
||||
- Retrieve all machine parts.
|
||||
- Deconstruct surplus supplies.
|
||||
|
||||
**Cast.** POLARIS (Batch 41-7), Autonomous Remnant.
|
||||
|
||||
**What it establishes.** Industrial independence. The Superstructure stops being a shelter and becomes a base that can build.
|
||||
|
||||
**Leaves behind.** A functioning production line, which is exactly what Arrival later needs for anti-air platforms.
|
||||
|
||||
**Branch stub.** *Factory left dormant.* Without the line, the batch cannot assemble the anti-air platforms or build the LZ in time, and Arrival becomes a defense with improvised equipment.
|
||||
|
||||
---
|
||||
|
||||
### 7. The Pale, Part 1
|
||||
`INTRO:THEPALE-PT1` · Oct 24, 2026 · Antarctica
|
||||
|
||||
**Premise.** When the Superthumpers unexpectedly cease their thumping, POLARIS comes face to face with a new and disturbing threat.
|
||||
|
||||
**Objectives.**
|
||||
- Deploy Weather Monitoring Devices.
|
||||
- Face the Pale. ("It was never supposed to come here...")
|
||||
|
||||
**Cast.** POLARIS (Batch 41-7), Autonomous Remnant.
|
||||
|
||||
**What it establishes.** The Superthumpers were not machinery for the structure's benefit; they were a barrier. Something outside is now inside. The objective text implies the Pale is off its map, not merely invading.
|
||||
|
||||
**Leaves behind.** A partially mapped intrusion and an open question: what stopped the thumping?
|
||||
|
||||
**Branch stub.** *Pale contained in Part 1.* A clean containment gives a victory lap instead of a two-parter, and Part 2 becomes a different story (aftermath, cleanup, or a second front).
|
||||
|
||||
---
|
||||
|
||||
### 8. The Pale, Part 2
|
||||
`INTRO:THEPALE-PT2` · Nov 14, 2026 · Antarctica
|
||||
|
||||
**Premise.** Same brief as Part 1: the thumping has stopped and the threat is present.
|
||||
|
||||
**Objectives.** Deploy Weather Monitoring Devices. Face the Pale.
|
||||
|
||||
**Cast.** POLARIS (Batch 41-7), Autonomous Remnant.
|
||||
|
||||
**What it establishes.** The Pale is resolved, or at least pushed back. The duplicated objective set suggests a two-session engagement rather than a second, distinct threat.
|
||||
|
||||
**Leaves behind.** Silence. Which is immediately broken.
|
||||
|
||||
**Branch stub.** *The Pale is not resolved.* If Part 2 ends in retreat, the Superstructure is compromised and Arrival plays out from a damaged base, possibly in exile.
|
||||
|
||||
---
|
||||
|
||||
### 9. Arrival
|
||||
`INTRO:ARRIVAL` · Nov 21, 2026 · Antarctica
|
||||
|
||||
**Premise.** When the silence of the ice is broken, POLARIS must prepare for the response to a signal that should have stayed dead.
|
||||
|
||||
**Objectives.**
|
||||
- Assemble Anti-Air Platforms.
|
||||
- Build the LZ (additional defenses strongly encouraged).
|
||||
- Meet the Visitor.
|
||||
|
||||
**Cast.** POLARIS (Batch 41-7), Autonomous Remnant, **Worldmark**.
|
||||
|
||||
**What it establishes.** The signal was heard. The response is physical. Worldmark enters the story as a third faction, and the season ends on a handshake or a firing solution, deliberately unresolved.
|
||||
|
||||
**Leaves behind.** The whole next season. This is the current frontier of the timeline.
|
||||
|
||||
**Branch stubs.**
|
||||
- *The Visitor is hostile.* First contact becomes a shooting war, Worldmark is an enemy from day one, and the anti-air platforms are used immediately.
|
||||
- *The Visitor is diplomatic.* Worldmark becomes a negotiated third party, and the next arc is politics between three factions in one frozen basin.
|
||||
|
||||
---
|
||||
|
||||
## Side operations
|
||||
|
||||
These are player-authored Friday ops. They do not feed the main narrative, but they are part of the unit's operational history, and several are the start of their own campaign lines.
|
||||
|
||||
### Operation Dubrava (custom campaign, player-run)
|
||||
- **DM3, Tikhonovo Line** · Sep 11 · Zagorsk Big Lakes. CPA and Russian forces break through south of the City of Progress and fortify Tikhonovo as a launch point. The GSFL 43rd SIR, with CDF 2nd Artillery and 32nd Mechanized Infantry, is tasked with displacing them.
|
||||
|
||||
### Building Blocks (Halo universe)
|
||||
- **Operation 2 Fold** · Sep 25 · Arcadia. Hotel 8-2 and 8-3 are shot down and MIA. Locate the crews and the insurgent AA that brought them down.
|
||||
|
||||
### Operation Olympus (WWII)
|
||||
- **Hedgerow Hell** · Oct 30 · Neaville (I44). A US airborne regiment ambushes a German armored division to open the road for American armor.
|
||||
- **Red Carpet** · Nov 6 · Crossroads Bocage. A US airborne regiment joins a combined-arms offensive against a heavily fortified German complex.
|
||||
|
||||
### Operation Campfire (1985, the Cold War goes hot)
|
||||
- **Green Day** · Nov 13 · Rosche, Germany. US armor and infantry push into two GDR towns, capture them, and hold against counterattack.
|
||||
- **Havoc** · Nov 20 · Rosche, Germany. US forces secure a GDR town and a possible camp to the south while Soviet forces begin mobilizing.
|
||||
|
||||
### One-shots
|
||||
- **Silent Dawn** · Sep 18 · Mekong Delta. Large-scale Vietnam op with full combined arms, aviation, artillery and mortars; patrol, seize POIs, raid for intel.
|
||||
- **Snakeskin** · Oct 2 · Tembelan Island. Warhammer 40K: clear a Xenos population, work with local Tau forces, retake ground, sabotage the enemy base.
|
||||
- **White Spruce** · Oct 9 · Korsac (Winter). December 2029, Chernarus: a US coalition element reconnoiters no man's land after sightings of Russian and Separatist movement.
|
||||
|
||||
---
|
||||
|
||||
## Branch stubs to develop
|
||||
|
||||
Speculative only. Each one names the canon node it forks from, the trigger, and what changes downstream.
|
||||
|
||||
| Stub | Forks from | Trigger | Downstream consequence |
|
||||
|---|---|---|---|
|
||||
| The facility never wakes | Prologue | The green light stays dark | No batch, no signal investigation; the Remnant or a third party finds the site |
|
||||
| Remnant first contact goes hot | What Lies Within | The Remnant is hostile at first meeting | No safe home base, no reintegration pipeline; survival-horror season |
|
||||
| THESEUS is opened | Mnemosyne | The 2030s team violates the inert order | The present threat gets a century of lead time; Pale and Worldmark share an origin |
|
||||
| The signal is ignored | First Light | Tau's order is refused | Arrival never happens; the season becomes internal, about the Superstructure |
|
||||
| Androids destroyed, not converted | Reintegration | Batch treats androids as salvage | No population growth; Factory arc loses its workforce |
|
||||
| Factory left dormant | Belts & Smoke | The line is never restarted | Arrival fought with improvised kit; no anti-air, no proper LZ |
|
||||
| Pale contained in Part 1 | The Pale, Part 1 | Clean containment | Part 2 becomes aftermath or a second front instead of a continuation |
|
||||
| The Visitor is hostile | Arrival | Worldmark opens fire | Immediate war, three-way fight for the basin, platforms used on day one |
|
||||
| The Visitor is diplomatic | Arrival | Worldmark offers terms | Political arc; the batch as a broker between three factions |
|
||||
| Campfire goes general | Green Day / Havoc | Soviet mobilization completes | The 1985 universe escalates from brushfire to full NATO-Warsaw Pact war |
|
||||
| Olympus pushes to Berlin | Red Carpet | The German complex falls early | The WWII universe gets a strategic endgame instead of a series of engagements |
|
||||
| The End of All Things | Pre-history | Prior campaign records surface | The 2023-2025 campaign (Lingor, Blood Hammer) can be grafted on as a prologue branch |
|
||||
|
||||
---
|
||||
|
||||
## Loose threads worth tracking
|
||||
|
||||
- **Tau.** Who or what it is, why it has authority over Batch 41-7, and why it never appears. Every main op after First Light is framed as a Tau tasking.
|
||||
- **THESEUS.** Contents unknown and explicitly not to be opened. The order is stated twice in one objective, which is a promise the story has not cashed.
|
||||
- **The Pale.** Origin, nature, and why the Superthumpers held it back. "It was never supposed to come here" implies a place it *was* supposed to be.
|
||||
- **Worldmark.** Introduced in the final op with no prior setup. Faction 4 in the database, and now the newest pole in the story.
|
||||
- **The signal.** Sender, encryption, and why answering it was dangerous. It is the hinge between First Light and Arrival.
|
||||
- **Batch 41-7's identity.** Amnesiac, android or partially so, and named like a production lot. "41-7" implies 40 previous batches.
|
||||
- **The original POLARIS Task Force.** Its 2030s operation is the only pre-history on record, and it connects directly to the present.
|
||||
|
||||
---
|
||||
|
||||
## Data notes and caveats
|
||||
|
||||
- **All 18 operations are marked `Completed`.** There are no Concept, Planning, Ready, Scheduled, Active, or Cancelled missions in production, so nothing in this note represents an upcoming op.
|
||||
- **Dates are local (US Eastern) op evenings.** The database stores UTC. Several ops sit at `00:00Z` or `01:00Z`, which is the prior evening locally. The table uses the local date.
|
||||
- **Side ops carry almost no structured data.** No objectives, no briefing, no faction links, and only summaries. Their entries here are summaries rather than reconstructions.
|
||||
- **`Operation Olympus` is marked `concept`** in the campaign record despite two completed ops. Worth fixing if campaign status is used anywhere.
|
||||
- **`The End of All Things` (campaign 1) has no mission records.** Its window is 2023-09-08 to 2025-07-12, which predates this database's mission history. Treat it as pre-history, not as a gap in this timeline.
|
||||
- **`Havoc` reuses `Green Day`'s `updatedAt` timestamp** and both sit on the Rosche map. Cosmetic, but it makes the audit trail ambiguous.
|
||||
- **Every op is `missionType: Zeus`.** No editor-made missions are on record.
|
||||
- **Prologue's hidden objective** is base64 in the database, not encryption. Decoded above.
|
||||
|
||||
---
|
||||
|
||||
## Suggested Obsidian structure
|
||||
|
||||
If you want this as a canvas or a set of linked notes rather than one file:
|
||||
|
||||
1. Keep this note as the index and add `[[Operation - Arrival]]` style links in each heading.
|
||||
2. Create one note per op with frontmatter `date`, `type`, `campaign`, `map`, `code`, `status`, then let Dataview build the table.
|
||||
3. Use the flowchart above as the Canvas skeleton: spine down the middle, side ops in a column on the right, stubs fanned out to the left.
|
||||
4. The gantt is the fastest way to show someone that the side-op campaigns ran in parallel, not in sequence.
|
||||
|
||||
Minimal Dataview for a per-op note set:
|
||||
|
||||
````markdown
|
||||
```dataview
|
||||
TABLE date AS "Date", type AS "Type", campaign AS "Campaign", map AS "Map"
|
||||
FROM #polaris/operation
|
||||
SORT date ASC
|
||||
```
|
||||
````
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "polaris-task-force",
|
||||
"version": "0.16.5",
|
||||
"version": "0.16.6",
|
||||
"description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
|
|
|
|||
|
|
@ -38,6 +38,7 @@ import { DevDashboardGate } from "@/components/frontend/dev/DevDashboardGate";
|
|||
import { ClarityAnalytics } from "@/components/frontend/analytics/ClarityAnalytics";
|
||||
import { AnalyticsTracker } from "@/lib/client-analytics/AnalyticsTracker";
|
||||
import { loadMinigameRegistry } from "@/lib/minigames/loadRegistry";
|
||||
import { cachedConfig } from "@/lib/config-cache";
|
||||
import type { RegistryGame } from "@/lib/minigames/registry";
|
||||
|
||||
// Skip static prerendering of this layout (and all pages under (frontend)/).
|
||||
|
|
@ -85,7 +86,9 @@ export default async function RootLayout(props: { children: React.ReactNode }) {
|
|||
let currentRank = "";
|
||||
let hasPersonalBankAccount = false;
|
||||
|
||||
const shimsGlobal = await payload.findGlobal({ slug: "shims" });
|
||||
const shimsGlobal = await cachedConfig("global:shims", () =>
|
||||
payload.findGlobal({ slug: "shims" }),
|
||||
);
|
||||
const shimEntries = (shimsGlobal.shims ?? []) as NonNullable<Shim["shims"]>;
|
||||
|
||||
let announcementEntries: AnnouncementEntry[] = [];
|
||||
|
|
@ -139,8 +142,12 @@ export default async function RootLayout(props: { children: React.ReactNode }) {
|
|||
and: [{ accountType: { equals: "personal" } }, { ownerUser: { equals: user.id } }],
|
||||
},
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
// Only the existence of the account is used below, so skip hydrating
|
||||
// balances, ledgers and the owner relationship.
|
||||
select: { accountType: true },
|
||||
}),
|
||||
payload.findGlobal({ slug: "game-rules" }),
|
||||
cachedConfig("global:game-rules", () => payload.findGlobal({ slug: "game-rules" })),
|
||||
payload.find({
|
||||
collection: "announcements",
|
||||
where: { enabled: { equals: true } },
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ import { hasLogisticsQualification } from "@/utils/access-control/hasLogisticsQu
|
|||
import {
|
||||
LedgerRow,
|
||||
NoticeState,
|
||||
OperationsRealtimeRefresher,
|
||||
PageShell,
|
||||
STATUS_TONE_CLASSES,
|
||||
type ReadoutCell,
|
||||
|
|
@ -156,8 +155,6 @@ export default async function SupplyBoxesPage() {
|
|||
</p>
|
||||
</PageShell>
|
||||
|
||||
<OperationsRealtimeRefresher />
|
||||
|
||||
{data.capability === false ? (
|
||||
<NoticeState
|
||||
variant="error"
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ import { getOperationAar } from "@/lib/operations/surfaceQuery";
|
|||
import {
|
||||
AarView,
|
||||
NoticeState,
|
||||
OperationsRealtimeRefresher,
|
||||
OperationsStrip,
|
||||
PageShell,
|
||||
ReconcilePanel,
|
||||
|
|
@ -50,7 +49,6 @@ export default async function OperationAarPage({
|
|||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-[96rem] flex-col gap-6 px-4 py-6">
|
||||
<OperationsRealtimeRefresher />
|
||||
<PageShell title={`Operation ${operationId}`} meta="AFTER-ACTION REPORT // PROVENANCE LINKED">
|
||||
{aar === null ? (
|
||||
<NoticeState
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { getPayload } from "payload";
|
|||
import { headers as nextHeaders } from "next/headers";
|
||||
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
||||
import { getPendingExtractions } from "@/app/(frontend)/operations/actions";
|
||||
import { ExtractionReview, PageShell, OperationsRealtimeRefresher } from "@/components/frontend/operations";
|
||||
import { ExtractionReview, PageShell } from "@/components/frontend/operations";
|
||||
import type { PendingExtraction } from "@/lib/operations/surfaceQuery";
|
||||
|
||||
export const metadata = {
|
||||
|
|
@ -31,7 +31,6 @@ export default async function PendingExtractionsPage() {
|
|||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-[96rem] flex-col gap-6 px-4 py-6">
|
||||
<OperationsRealtimeRefresher />
|
||||
<PageShell
|
||||
title="Pending extractions"
|
||||
meta="EXTRACTION RETURNS // REVIEW & DEPOSIT"
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
|||
import { getOperationLedger } from "@/lib/operations/surfaceQuery";
|
||||
import {
|
||||
LedgerTable,
|
||||
OperationsRealtimeRefresher,
|
||||
OperationsStrip,
|
||||
PageShell,
|
||||
} from "@/components/frontend/operations";
|
||||
|
|
@ -51,7 +50,6 @@ export default async function OperationsLedgerPage({
|
|||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-[96rem] flex-col gap-6 px-4 py-6">
|
||||
<OperationsRealtimeRefresher />
|
||||
<PageShell
|
||||
title="Operations ledger"
|
||||
meta="SOURCE EVENTS // EFFECT LEDGER"
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
|||
import { getOperationOverview } from "@/lib/operations/surface";
|
||||
import {
|
||||
MyExtractionsCard,
|
||||
OperationsRealtimeRefresher,
|
||||
OperationsStrip,
|
||||
PageShell,
|
||||
PressureCard,
|
||||
|
|
@ -31,7 +30,6 @@ export default async function OperationsPage() {
|
|||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-[96rem] flex-col gap-6 px-4 py-6">
|
||||
<OperationsRealtimeRefresher />
|
||||
<PageShell title="Operations" meta="OPERATION FEED // AFTER-ACTION RECORDS" dataTour="page-header">
|
||||
<p className="max-w-2xl text-sm text-white/70">
|
||||
Live and historical operation activity: extraction returns, settlements, readiness
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { GlobalConfig } from "payload";
|
||||
import { requirePermission } from "@/utils/access-control/hasPermission";
|
||||
import { invalidateConfigCache } from "@/lib/config-cache";
|
||||
|
||||
export const Shims: GlobalConfig = {
|
||||
slug: "shims",
|
||||
|
|
@ -7,6 +8,10 @@ export const Shims: GlobalConfig = {
|
|||
read: requirePermission("shims:read"),
|
||||
update: requirePermission("shims:update"),
|
||||
},
|
||||
hooks: {
|
||||
// The (frontend) layout caches this global for 60s (lib/config-cache.ts).
|
||||
afterChange: [() => invalidateConfigCache("global:shims")],
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: "shims",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { GlobalConfig } from "payload";
|
||||
import { requirePermission } from "@/utils/access-control/hasPermission";
|
||||
import { invalidateConfigCache } from "@/lib/config-cache";
|
||||
|
||||
export const GameRules: GlobalConfig = {
|
||||
slug: "game-rules",
|
||||
|
|
@ -7,6 +8,10 @@ export const GameRules: GlobalConfig = {
|
|||
read: requirePermission("game-rules:read"),
|
||||
update: requirePermission("game-rules:update"),
|
||||
},
|
||||
hooks: {
|
||||
// The (frontend) layout caches this global for 60s (lib/config-cache.ts).
|
||||
afterChange: [() => invalidateConfigCache("global:game-rules")],
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: "mainCurrency",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { CollectionConfig } from "payload";
|
||||
import { requirePermission } from "@/utils/access-control/hasPermission";
|
||||
import { invalidateMinigameRegistryCache } from "@/lib/minigames/loadRegistry";
|
||||
|
||||
/**
|
||||
* Registry of minigames.
|
||||
|
|
@ -26,6 +27,13 @@ export const Minigames: CollectionConfig = {
|
|||
update: requirePermission("minigames:update"),
|
||||
delete: requirePermission("minigames:delete"),
|
||||
},
|
||||
hooks: {
|
||||
// The frontend caches this registry briefly (loadRegistry.ts) because the
|
||||
// layout reads it on every render. Drop that cache on any write so a status
|
||||
// flip (upcoming -> active) is visible immediately.
|
||||
afterChange: [() => invalidateMinigameRegistryCache()],
|
||||
afterDelete: [() => invalidateMinigameRegistryCache()],
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: "key",
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { Award } from "@/payload-types";
|
|||
import { broadcastToUser } from "@/lib/realtime/bus";
|
||||
import { notifyAwardGrants } from "@/lib/awards";
|
||||
import { hasPermission } from "@/utils/access-control/hasPermission";
|
||||
import { invalidateQualificationCache } from "@/utils/access-control/qualificationCache";
|
||||
import { lexicalPlaintextLength } from "@/lib/lexical/text";
|
||||
|
||||
export const Profiles: CollectionConfig = {
|
||||
|
|
@ -31,6 +32,10 @@ export const Profiles: CollectionConfig = {
|
|||
async ({ doc }) => {
|
||||
const userId = typeof doc.user === "object" ? doc.user?.id : doc.user;
|
||||
if (typeof userId === "number") {
|
||||
// Qualification flags gate division nav + admin-page access and are
|
||||
// cached for 30s; drop the entry so a granted/revoked qualification
|
||||
// takes effect on the next request instead of up to 30s later.
|
||||
invalidateQualificationCache(userId);
|
||||
broadcastToUser("profile-update", userId, { profileId: doc.id });
|
||||
}
|
||||
},
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@ import { toast } from "sonner";
|
|||
import { Pause, Play } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Item, ItemContent, ItemDescription, ItemTitle } from "@/components/ui/item";
|
||||
import { useGameTick } from "@/hooks/useGameTick";
|
||||
import { toggleProduction } from "@/app/(frontend)/logistics/base/actions";
|
||||
|
||||
export interface ProductionRecipeLine {
|
||||
|
|
@ -41,7 +40,6 @@ export function ProductionPanel({
|
|||
}: ProductionPanelProps) {
|
||||
const router = useRouter();
|
||||
const [loading, setLoading] = useState(false);
|
||||
useGameTick(() => router.refresh());
|
||||
|
||||
if (!complete) return null;
|
||||
if (inputs.length === 0 && outputs.length === 0) return null;
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ import { Blocks, Plus, X } from "lucide-react";
|
|||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Item, ItemContent, ItemDescription, ItemTitle } from "@/components/ui/item";
|
||||
import { useGameTick } from "@/hooks/useGameTick";
|
||||
import { installModule, uninstallModule } from "@/app/(frontend)/logistics/base/actions";
|
||||
|
||||
export interface ModuleEffectLine {
|
||||
|
|
@ -51,7 +50,6 @@ export function SlotsPanel({
|
|||
}: SlotsPanelProps) {
|
||||
const router = useRouter();
|
||||
const [loading, setLoading] = useState<string | null>(null);
|
||||
useGameTick(() => router.refresh());
|
||||
|
||||
if (slots <= 0 && options.length === 0 && installed.length === 0) return null;
|
||||
|
||||
|
|
|
|||
|
|
@ -37,6 +37,11 @@ export function NavCore({
|
|||
}) {
|
||||
if (items.length === 0) return null;
|
||||
|
||||
// `prefetch={false}` on the links below: the (frontend) layout is
|
||||
// force-dynamic with no loading.tsx, so a prefetched nav link is a full
|
||||
// server render (auth sweep + layout queries). With ~35 sidebar links per
|
||||
// open tab, prefetching turned every page load into dozens of renders.
|
||||
// Navigation itself stays client-side.
|
||||
return (
|
||||
<SidebarGroup>
|
||||
<SidebarGroupLabel>{label}</SidebarGroupLabel>
|
||||
|
|
@ -65,7 +70,7 @@ export function NavCore({
|
|||
{item.items?.map((subItem) => (
|
||||
<SidebarMenuSubItem key={subItem.title}>
|
||||
<SidebarMenuSubButton asChild>
|
||||
<Link href={subItem.url}>
|
||||
<Link href={subItem.url} prefetch={false}>
|
||||
{subItem.icon ? <subItem.icon /> : null}
|
||||
<span>{subItem.title}</span>
|
||||
</Link>
|
||||
|
|
@ -77,7 +82,7 @@ export function NavCore({
|
|||
</>
|
||||
) : (
|
||||
<SidebarMenuButton asChild tooltip={item.title}>
|
||||
<Link href={item.url}>
|
||||
<Link href={item.url} prefetch={false}>
|
||||
<item.icon />
|
||||
<span>{item.title}</span>
|
||||
</Link>
|
||||
|
|
|
|||
|
|
@ -212,7 +212,10 @@ export function MissionReminderToasts() {
|
|||
writeReminderDismissals(dismissedRef.current, now);
|
||||
void fetchReminders();
|
||||
|
||||
const interval = setInterval(() => void fetchReminders(), POLL_MS);
|
||||
const interval = setInterval(() => {
|
||||
if (document.hidden) return;
|
||||
void fetchReminders();
|
||||
}, POLL_MS);
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
clearInterval(interval);
|
||||
|
|
|
|||
|
|
@ -62,11 +62,16 @@ export function ShipmentToasts() {
|
|||
|
||||
useEffect(() => {
|
||||
fetchShipments();
|
||||
const interval = setInterval(fetchShipments, 30_000);
|
||||
const interval = setInterval(() => {
|
||||
if (document.hidden) return;
|
||||
fetchShipments();
|
||||
}, 30_000);
|
||||
return () => clearInterval(interval);
|
||||
}, [fetchShipments]);
|
||||
|
||||
useGameTick(() => fetchShipments());
|
||||
useGameTick(() => {
|
||||
if (!document.hidden) fetchShipments();
|
||||
});
|
||||
|
||||
if (shipments.length === 0) return null;
|
||||
|
||||
|
|
|
|||
|
|
@ -75,7 +75,10 @@ export function ChipBankCard({ initialChipBank, initialChipTopUpAt }: ChipBankCa
|
|||
}, [refreshChipState]);
|
||||
|
||||
useEffect(() => {
|
||||
const poll = window.setInterval(refreshChipState, 5000);
|
||||
const poll = window.setInterval(() => {
|
||||
if (document.hidden) return;
|
||||
refreshChipState();
|
||||
}, 5000);
|
||||
return () => window.clearInterval(poll);
|
||||
}, [refreshChipState]);
|
||||
|
||||
|
|
|
|||
|
|
@ -81,6 +81,7 @@ export function NotificationsBell() {
|
|||
const [scope, setScope] = useState<Scope>(readStoredScope);
|
||||
const [canViewOthers, setCanViewOthers] = useState(false);
|
||||
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
const eventTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const unreadCount = notifications.filter((n) => !n.read).length;
|
||||
|
||||
|
|
@ -106,11 +107,27 @@ export function NotificationsBell() {
|
|||
|
||||
useEffect(() => {
|
||||
void fetchNotifications();
|
||||
intervalRef.current = setInterval(() => void fetchNotifications(), POLL_MS);
|
||||
const onNotification = () => void fetchNotifications();
|
||||
intervalRef.current = setInterval(() => {
|
||||
// A hidden tab costs a full auth + query per poll while nobody is
|
||||
// looking; it catches up on the next poll after it becomes visible.
|
||||
if (document.hidden) return;
|
||||
void fetchNotifications();
|
||||
}, POLL_MS);
|
||||
// A notification burst (e.g. a mission completion granting XP) emits one
|
||||
// event per recipient row. Coalesce them into at most one refetch per
|
||||
// second instead of one request per event.
|
||||
const onNotification = () => {
|
||||
if (document.hidden) return;
|
||||
if (eventTimerRef.current) return;
|
||||
eventTimerRef.current = setTimeout(() => {
|
||||
eventTimerRef.current = null;
|
||||
void fetchNotifications();
|
||||
}, 1000);
|
||||
};
|
||||
window.addEventListener(NOTIFICATION_EVENT, onNotification);
|
||||
return () => {
|
||||
if (intervalRef.current) clearInterval(intervalRef.current);
|
||||
if (eventTimerRef.current) clearTimeout(eventTimerRef.current);
|
||||
window.removeEventListener(NOTIFICATION_EVENT, onNotification);
|
||||
};
|
||||
}, [fetchNotifications]);
|
||||
|
|
|
|||
|
|
@ -1,17 +0,0 @@
|
|||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useGameTick } from "@/hooks/useGameTick";
|
||||
|
||||
/**
|
||||
* Enhancement-only realtime refresh for /operations surfaces. The server
|
||||
* re-fetch on navigation is the correctness source; this only triggers an
|
||||
* early refresh when a game tick lands while the page is open.
|
||||
*/
|
||||
export function OperationsRealtimeRefresher() {
|
||||
const router = useRouter();
|
||||
useGameTick(() => {
|
||||
router.refresh();
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
|
@ -7,7 +7,6 @@ export { NoticeState } from "./NoticeState";
|
|||
export { StrategicSummary } from "./StrategicSummary";
|
||||
export { PageShell } from "./PageShell";
|
||||
export { STATUS_TONE_CLASSES, DOSSIER, statusToneFor, type StatusTone } from "./tokens";
|
||||
export { OperationsRealtimeRefresher } from "./OperationsRealtimeRefresher";
|
||||
export {
|
||||
RecentOperationsCard,
|
||||
MyExtractionsCard,
|
||||
|
|
|
|||
|
|
@ -39,13 +39,40 @@ export function GameTickRealtime() {
|
|||
useEffect(() => {
|
||||
const source = new EventSource("/api/realtime");
|
||||
let refreshTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
const refresh = (delay = 250) => {
|
||||
let skippedWhileHidden = false;
|
||||
/**
|
||||
* One coalesced refresh per burst. The window used to be 250ms, which real
|
||||
* bursts walk straight through: a mission completion grants one XP event
|
||||
* per attendee (40-120 broadcasts in a few seconds), and each broadcast
|
||||
* re-renders the whole route tree (layout + page, ~20 queries) for every
|
||||
* connected client. A 1s window keeps the same visible update latency while
|
||||
* turning a burst into a couple of renders instead of dozens.
|
||||
*
|
||||
* Hidden tabs skip the render entirely; they cost the server a full SSR pass
|
||||
* for a page nobody is looking at. They refresh once when they become
|
||||
* visible again.
|
||||
*/
|
||||
const refresh = (delay = 1000) => {
|
||||
if (typeof document !== "undefined" && document.hidden) {
|
||||
skippedWhileHidden = true;
|
||||
return;
|
||||
}
|
||||
if (refreshTimer) return;
|
||||
refreshTimer = setTimeout(() => {
|
||||
refreshTimer = null;
|
||||
if (document.hidden) {
|
||||
skippedWhileHidden = true;
|
||||
return;
|
||||
}
|
||||
router.refresh();
|
||||
}, delay);
|
||||
};
|
||||
const onVisibility = () => {
|
||||
if (document.hidden || !skippedWhileHidden) return;
|
||||
skippedWhileHidden = false;
|
||||
refresh(0);
|
||||
};
|
||||
document.addEventListener("visibilitychange", onVisibility);
|
||||
source.addEventListener("game-tick", (event) => {
|
||||
let detail: GameTickDetail = {};
|
||||
try {
|
||||
|
|
@ -147,6 +174,7 @@ export function GameTickRealtime() {
|
|||
});
|
||||
return () => {
|
||||
if (refreshTimer) clearTimeout(refreshTimer);
|
||||
document.removeEventListener("visibilitychange", onVisibility);
|
||||
source.close();
|
||||
};
|
||||
}, [router]);
|
||||
|
|
|
|||
|
|
@ -110,12 +110,14 @@ export function EventLedger({
|
|||
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
if (document.hidden) return;
|
||||
if (initialDone.current) fetchEntries();
|
||||
}, 30_000);
|
||||
return () => clearInterval(interval);
|
||||
}, [fetchEntries]);
|
||||
|
||||
useGameTick(() => {
|
||||
if (document.hidden) return;
|
||||
if (initialDone.current) fetchEntries();
|
||||
});
|
||||
|
||||
|
|
|
|||
75
src/lib/config-cache.ts
Normal file
75
src/lib/config-cache.ts
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
/**
|
||||
* Tiny TTL cache for admin-authored configuration reads.
|
||||
*
|
||||
* The `(frontend)` layout renders on every navigation and on every realtime
|
||||
* refresh, and it reads globals that change maybe once a month (shims, game
|
||||
* rules). Under concurrent load those reads multiply by clients x refreshes for
|
||||
* data that is identical for everyone.
|
||||
*
|
||||
* Only use this for values that are the same for every user and are edited by
|
||||
* admins, never for anything user-scoped (permissions, presence, balances).
|
||||
* `globalThis`-anchored so route bundles share one copy, like the SSE bus and
|
||||
* the minigame registry cache.
|
||||
*/
|
||||
const DEFAULT_TTL_MS = 60_000;
|
||||
|
||||
interface CacheEntry {
|
||||
value: unknown;
|
||||
loadedAt: number;
|
||||
}
|
||||
|
||||
interface CacheHolder {
|
||||
__ptfConfigCache?: Map<string, CacheEntry>;
|
||||
__ptfConfigInflight?: Map<string, Promise<unknown>>;
|
||||
}
|
||||
|
||||
function holder(): CacheHolder {
|
||||
return globalThis as typeof globalThis & CacheHolder;
|
||||
}
|
||||
|
||||
function entries(): Map<string, CacheEntry> {
|
||||
const store = holder();
|
||||
return (store.__ptfConfigCache ??= new Map<string, CacheEntry>());
|
||||
}
|
||||
|
||||
function inflight(): Map<string, Promise<unknown>> {
|
||||
const store = holder();
|
||||
return (store.__ptfConfigInflight ??= new Map<string, Promise<unknown>>());
|
||||
}
|
||||
|
||||
export async function cachedConfig<T>(
|
||||
key: string,
|
||||
load: () => Promise<T>,
|
||||
ttlMs: number = DEFAULT_TTL_MS,
|
||||
): Promise<T> {
|
||||
const now = Date.now();
|
||||
const hit = entries().get(key);
|
||||
if (hit && now - hit.loadedAt < ttlMs) return hit.value as T;
|
||||
|
||||
const pending = inflight().get(key);
|
||||
if (pending) return pending as Promise<T>;
|
||||
|
||||
const promise = load()
|
||||
.then((value) => {
|
||||
entries().set(key, { value, loadedAt: Date.now() });
|
||||
inflight().delete(key);
|
||||
return value;
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
inflight().delete(key);
|
||||
throw error;
|
||||
});
|
||||
|
||||
inflight().set(key, promise as Promise<unknown>);
|
||||
return promise;
|
||||
}
|
||||
|
||||
/** Drop one cached key, or the whole cache when no key is given. */
|
||||
export function invalidateConfigCache(key?: string): void {
|
||||
if (key === undefined) {
|
||||
entries().clear();
|
||||
inflight().clear();
|
||||
return;
|
||||
}
|
||||
entries().delete(key);
|
||||
}
|
||||
|
|
@ -97,22 +97,6 @@ function actorLabel(userId: number, actorName?: string | null): string {
|
|||
return actorName && actorName.trim().length > 0 ? actorName : `User #${userId}`;
|
||||
}
|
||||
|
||||
/** Resolve a user's display name for human-readable event messages. */
|
||||
async function resolveUserName(payload: Payload, userId: number): Promise<string> {
|
||||
try {
|
||||
const user = (await payload.findByID({
|
||||
collection: "users",
|
||||
id: userId,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
select: { displayName: true, username: true },
|
||||
})) as unknown as { displayName?: string | null; username?: string | null };
|
||||
return user.displayName || user.username || `User #${userId}`;
|
||||
} catch {
|
||||
return `User #${userId}`;
|
||||
}
|
||||
}
|
||||
|
||||
/** Deterministic content hash for deduping wiki edits. Server-only. */
|
||||
export function contentHash(text: string): string {
|
||||
return createHash("sha256").update(text).digest("hex").slice(0, 16);
|
||||
|
|
@ -183,23 +167,81 @@ async function missionEntryCount(
|
|||
return totalDocs;
|
||||
}
|
||||
|
||||
async function sourceStillExists(
|
||||
payload: Payload,
|
||||
sourceCollection: ContributionSourceCollection,
|
||||
sourceId: number,
|
||||
): Promise<boolean> {
|
||||
if (sourceCollection === "manual") return true;
|
||||
async function resolveUserNames(payload: Payload, userIds: number[]): Promise<Map<number, string>> {
|
||||
const names = new Map<number, string>();
|
||||
for (const id of userIds) names.set(id, `User #${id}`);
|
||||
if (userIds.length === 0) return names;
|
||||
|
||||
try {
|
||||
const doc = await payload.findByID({
|
||||
collection: sourceCollection,
|
||||
id: sourceId,
|
||||
const res = (await payload.find({
|
||||
collection: "users",
|
||||
where: { id: { in: userIds } },
|
||||
limit: userIds.length,
|
||||
depth: 0,
|
||||
pagination: false,
|
||||
overrideAccess: true,
|
||||
});
|
||||
return Boolean(doc);
|
||||
select: { displayName: true, username: true },
|
||||
})) as unknown as {
|
||||
docs: Array<{ id: number; displayName?: string | null; username?: string | null }>;
|
||||
};
|
||||
for (const doc of res.docs) {
|
||||
names.set(Number(doc.id), doc.displayName || doc.username || `User #${doc.id}`);
|
||||
}
|
||||
} catch {
|
||||
return false;
|
||||
// Keep the "User #id" fallbacks.
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
function sourceKey(collection: ContributionSourceCollection, id: number): string {
|
||||
return `${collection}:${id}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve which queued entries still have a live source document, using one
|
||||
* query per source collection instead of one per entry. A mission completes
|
||||
* with 40-120 queued entries and the old per-entry `findByID` dominated the
|
||||
* completion sweep.
|
||||
*/
|
||||
async function survivingSourceKeys(
|
||||
payload: Payload,
|
||||
entries: ContributionEntryDoc[],
|
||||
): Promise<Set<string>> {
|
||||
const idsByCollection = new Map<Exclude<ContributionSourceCollection, "manual">, Set<number>>();
|
||||
for (const entry of entries) {
|
||||
if (entry.sourceCollection === "manual") continue;
|
||||
const collection = entry.sourceCollection;
|
||||
let ids = idsByCollection.get(collection);
|
||||
if (!ids) {
|
||||
ids = new Set<number>();
|
||||
idsByCollection.set(collection, ids);
|
||||
}
|
||||
ids.add(entry.sourceId);
|
||||
}
|
||||
|
||||
const surviving = new Set<string>();
|
||||
await Promise.all(
|
||||
[...idsByCollection.entries()].map(async ([collection, idSet]) => {
|
||||
const ids = [...idSet];
|
||||
try {
|
||||
const found = await payload.find({
|
||||
collection,
|
||||
where: { id: { in: ids } },
|
||||
limit: ids.length,
|
||||
depth: 0,
|
||||
pagination: false,
|
||||
overrideAccess: true,
|
||||
});
|
||||
for (const doc of found.docs) surviving.add(sourceKey(collection, Number(doc.id)));
|
||||
} catch {
|
||||
// Previously a failed lookup counted as "source gone" and revoked the
|
||||
// entry. A single transient failure must not mass-revoke a mission's
|
||||
// contributions, so treat an unreadable collection as alive.
|
||||
for (const id of ids) surviving.add(sourceKey(collection, id));
|
||||
}
|
||||
}),
|
||||
);
|
||||
return surviving;
|
||||
}
|
||||
|
||||
async function emitGranted(
|
||||
|
|
@ -317,31 +359,6 @@ export async function recordContribution(
|
|||
return { status, points, entryId: created.id };
|
||||
}
|
||||
|
||||
/** Flip a queued entry to granted, applying the bucket delta and notifying. */
|
||||
async function markGranted(
|
||||
payload: Payload,
|
||||
entry: ContributionEntryDoc,
|
||||
reason: string,
|
||||
): Promise<void> {
|
||||
const userId = entryUserId(entry);
|
||||
const nowIso = new Date().toISOString();
|
||||
await payload.update({
|
||||
collection: "contribution-entries",
|
||||
id: entry.id,
|
||||
data: { status: "granted", grantedAt: nowIso },
|
||||
overrideAccess: true,
|
||||
});
|
||||
await addContributionXp(payload, userId, entry.points);
|
||||
await emitGranted(payload, entry, userId, await resolveUserName(payload, userId), entry.points, entry.type);
|
||||
await notifyUser(payload, {
|
||||
userId,
|
||||
type: "contribution:xp-granted",
|
||||
title: `+${entry.points} XP granted`,
|
||||
message: reason,
|
||||
link: "/contributions",
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Grant every queued entry on a mission whose source marker still exists.
|
||||
* Entries whose marker was removed are revoked (backstop for a missed delete
|
||||
|
|
@ -359,22 +376,72 @@ export async function grantQueuedEntriesForMission(
|
|||
overrideAccess: true,
|
||||
})) as unknown as { docs: ContributionEntryDoc[] };
|
||||
|
||||
let granted = 0;
|
||||
let revoked = 0;
|
||||
if (res.docs.length === 0) return { granted: 0, revoked: 0 };
|
||||
|
||||
// One lookup per source collection instead of one per entry.
|
||||
const surviving = await survivingSourceKeys(payload, res.docs);
|
||||
const survivors: ContributionEntryDoc[] = [];
|
||||
const orphans: ContributionEntryDoc[] = [];
|
||||
for (const entry of res.docs) {
|
||||
const survives = await sourceStillExists(payload, entry.sourceCollection, entry.sourceId);
|
||||
if (!survives) {
|
||||
await revokeEntry(payload, entry.id, {
|
||||
reason: "The contribution was removed before the mission completed.",
|
||||
silent: true,
|
||||
});
|
||||
revoked += 1;
|
||||
continue;
|
||||
if (
|
||||
entry.sourceCollection === "manual" ||
|
||||
surviving.has(sourceKey(entry.sourceCollection, entry.sourceId))
|
||||
) {
|
||||
survivors.push(entry);
|
||||
} else {
|
||||
orphans.push(entry);
|
||||
}
|
||||
await markGranted(payload, entry, `Your contribution was kept in "${entry.summary}".`);
|
||||
granted += 1;
|
||||
}
|
||||
return { granted, revoked };
|
||||
|
||||
let revoked = 0;
|
||||
for (const entry of orphans) {
|
||||
await revokeEntry(payload, entry.id, {
|
||||
reason: "The contribution was removed before the mission completed.",
|
||||
silent: true,
|
||||
});
|
||||
revoked += 1;
|
||||
}
|
||||
|
||||
if (survivors.length === 0) return { granted: 0, revoked };
|
||||
|
||||
// One status write for the whole batch (the collection has no hooks), then
|
||||
// one bucket write and one name lookup per distinct user instead of per entry.
|
||||
const nowIso = new Date().toISOString();
|
||||
await payload.update({
|
||||
collection: "contribution-entries",
|
||||
where: { id: { in: survivors.map((entry) => entry.id) } },
|
||||
data: { status: "granted", grantedAt: nowIso },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
|
||||
const entriesByUser = new Map<number, ContributionEntryDoc[]>();
|
||||
for (const entry of survivors) {
|
||||
const userId = entryUserId(entry);
|
||||
const list = entriesByUser.get(userId);
|
||||
if (list) list.push(entry);
|
||||
else entriesByUser.set(userId, [entry]);
|
||||
}
|
||||
|
||||
const names = await resolveUserNames(payload, [...entriesByUser.keys()]);
|
||||
|
||||
for (const [userId, entries] of entriesByUser) {
|
||||
const points = entries.reduce((sum, entry) => sum + entry.points, 0);
|
||||
await addContributionXp(payload, userId, points);
|
||||
const earnerName = names.get(userId) ?? `User #${userId}`;
|
||||
for (const entry of entries) {
|
||||
await emitGranted(payload, entry, userId, earnerName, entry.points, entry.type);
|
||||
await notifyUser(payload, {
|
||||
userId,
|
||||
type: "contribution:xp-granted",
|
||||
title: `+${entry.points} XP granted`,
|
||||
message: `Your contribution was kept in "${entry.summary}".`,
|
||||
link: "/contributions",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { granted: survivors.length, revoked };
|
||||
}
|
||||
|
||||
/** Expire every queued entry on a mission (Cancelled, or stale drafts). */
|
||||
|
|
|
|||
|
|
@ -18,6 +18,53 @@ import {
|
|||
* resolved list as a prop and use `RegistryGame` from the pure `registry.ts`.
|
||||
*/
|
||||
export async function loadMinigameRegistry(payload: Payload): Promise<BuiltinMinigame[]> {
|
||||
const cached = readRegistryCache();
|
||||
if (cached) return cached;
|
||||
|
||||
const rows = await fetchMinigameRegistry(payload);
|
||||
// Only a real DB result is worth caching; the built-in fallback is used when
|
||||
// the table is empty or the read failed, and should be retried next render.
|
||||
if (rows.length > 0) writeRegistryCache(rows);
|
||||
return rows.length > 0 ? rows : [...BUILTIN_MINIGAMES];
|
||||
}
|
||||
|
||||
/**
|
||||
* The registry is admin-edited configuration, but the layout loads it on every
|
||||
* render (and the standings/lifecycle helpers load it again per call). A short
|
||||
* TTL keeps a nav rename visible within half a minute while removing a query
|
||||
* from every page render. `globalThis`-anchored so route bundles share it.
|
||||
*/
|
||||
const REGISTRY_TTL_MS = 30_000;
|
||||
|
||||
interface RegistryCacheEntry {
|
||||
rows: BuiltinMinigame[];
|
||||
loadedAt: number;
|
||||
}
|
||||
|
||||
interface RegistryCacheHolder {
|
||||
__ptfMinigameRegistry?: RegistryCacheEntry;
|
||||
}
|
||||
|
||||
function readRegistryCache(): BuiltinMinigame[] | null {
|
||||
const holder = globalThis as typeof globalThis & RegistryCacheHolder;
|
||||
const entry = holder.__ptfMinigameRegistry;
|
||||
if (!entry) return null;
|
||||
if (Date.now() - entry.loadedAt >= REGISTRY_TTL_MS) return null;
|
||||
return entry.rows;
|
||||
}
|
||||
|
||||
function writeRegistryCache(rows: BuiltinMinigame[]): void {
|
||||
const holder = globalThis as typeof globalThis & RegistryCacheHolder;
|
||||
holder.__ptfMinigameRegistry = { rows, loadedAt: Date.now() };
|
||||
}
|
||||
|
||||
/** Drop the cached registry (tests / after an admin write that must be instant). */
|
||||
export function invalidateMinigameRegistryCache(): void {
|
||||
const holder = globalThis as typeof globalThis & RegistryCacheHolder;
|
||||
delete holder.__ptfMinigameRegistry;
|
||||
}
|
||||
|
||||
async function fetchMinigameRegistry(payload: Payload): Promise<BuiltinMinigame[]> {
|
||||
try {
|
||||
const res = await payload.find({
|
||||
collection: "minigames",
|
||||
|
|
@ -46,7 +93,7 @@ export async function loadMinigameRegistry(payload: Payload): Promise<BuiltinMin
|
|||
} catch {
|
||||
// Fall through to the built-in list below.
|
||||
}
|
||||
return [...BUILTIN_MINIGAMES];
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -110,7 +110,10 @@ export async function markAllNotificationsReadForUser(
|
|||
): Promise<number[]> {
|
||||
const found = await payload.find({
|
||||
collection: "user-notifications",
|
||||
where: { read: { equals: false } },
|
||||
// Scope the predicate to the actor. The old unscoped `read: false` read up
|
||||
// to 100 unread rows belonging to anyone (a low-selectivity scan of the
|
||||
// table) and discarded most of them in JS.
|
||||
where: { and: [{ user: { equals: actorUserId } }, { read: { equals: false } }] },
|
||||
limit: 100,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
|
|
|
|||
|
|
@ -41,9 +41,14 @@ export function touchPresence(channel: string, participant: Omit<PresencePartici
|
|||
const wasPresent = entries.has(participant.id);
|
||||
const record = { ...participant, lastSeen: new Date(now).toISOString(), expiresAt: now + PRESENCE_TTL_MS };
|
||||
entries.set(participant.id, record);
|
||||
// A heartbeat only extends the TTL. Broadcasting an "update" to every
|
||||
// subscriber on every 15s heartbeat made presence O(N^2) per channel (12
|
||||
// players = 144 SSE messages per 15s) for a `lastSeen` no surface renders.
|
||||
// Joins and leaves still broadcast, which is all the participant list needs.
|
||||
if (wasPresent) return;
|
||||
broadcast("presence", {
|
||||
channel,
|
||||
action: wasPresent ? "update" : "join",
|
||||
action: "join",
|
||||
participant: { id: record.id, name: record.name, lastSeen: record.lastSeen },
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -521,9 +521,14 @@ export default buildConfig({
|
|||
db: postgresAdapter({
|
||||
pool: {
|
||||
connectionString: process.env.DATABASE_URI || "",
|
||||
// Test workers cap the pg pool per boot (tests/vitest-worker-setup.ts
|
||||
// sets TEST_PG_POOL_MAX); unset in dev/prod, zero behavior change there.
|
||||
...(process.env.TEST_PG_POOL_MAX ? { max: Number(process.env.TEST_PG_POOL_MAX) } : {}),
|
||||
// node-postgres defaults to 10 connections. A single page render issues
|
||||
// ~12 queries and 10-12 concurrent users over a POST/SSE refresh burst
|
||||
// saturate that, so renders queue on the pool instead of on Postgres.
|
||||
// Test workers cap their own pool (tests/vitest-worker-setup.ts sets
|
||||
// TEST_PG_POOL_MAX), which overrides this.
|
||||
max: Number(process.env.TEST_PG_POOL_MAX ?? process.env.PG_POOL_MAX ?? 20),
|
||||
idleTimeoutMillis: 30_000,
|
||||
connectionTimeoutMillis: 10_000,
|
||||
},
|
||||
// push: process.env.NODE_ENV === "development",
|
||||
// Env-gated drizzle push: only the test-database bootstrap (DB_PUSH=1) uses
|
||||
|
|
|
|||
|
|
@ -208,7 +208,10 @@ export async function canAccessAdminPanel(
|
|||
): Promise<boolean> {
|
||||
if (!user) return false;
|
||||
if (await canAccessAdminPanelByPermissions(payload, user)) return true;
|
||||
for (const divisionCheck of Object.values(DIVISION_ADMIN_QUALIFICATIONS)) {
|
||||
// Every entry in the map is currently the same predicate (intelligence owns
|
||||
// all five tech collections), so dedupe the values: this was five identical
|
||||
// qualification lookups per auth pass.
|
||||
for (const divisionCheck of new Set(Object.values(DIVISION_ADMIN_QUALIFICATIONS))) {
|
||||
if (await divisionCheck(payload, user)) return true;
|
||||
}
|
||||
return false;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import type { Payload } from "payload";
|
||||
import { hasAnyPermission } from "@/utils/access-control/hasPermission";
|
||||
import { loadQualificationFlags } from "@/utils/access-control/qualificationCache";
|
||||
|
||||
// Membership signals only. Read permissions (missions:read, campaigns:read,
|
||||
// factions:read, technologies:read) must NOT appear here: the standard "user"
|
||||
|
|
@ -31,29 +32,12 @@ export async function hasIntelligenceQualification(
|
|||
|
||||
if (await hasAnyPermission(payload, user, ...INTELLIGENCE_PERMISSIONS)) return true;
|
||||
|
||||
const profile = (await payload.find({
|
||||
collection: "profiles",
|
||||
where: { user: { equals: user.id as number } },
|
||||
// Only qualifications are needed here. A deeper read recursively
|
||||
// hydrates Profiles through progression.awards.awardedBy.
|
||||
depth: 1,
|
||||
limit: 1,
|
||||
select: {
|
||||
progression: {
|
||||
qualifications: true,
|
||||
},
|
||||
},
|
||||
})) as unknown as { docs: Array<any> };
|
||||
// Cached + single-flight: `payload.auth()` calls this many times per request
|
||||
// (once per division-gated collection operation), so the raw profile read
|
||||
// must not run once per call. See qualificationCache.ts.
|
||||
const userId = Number(user.id);
|
||||
if (!Number.isFinite(userId)) return false;
|
||||
|
||||
const userProfile = profile.docs[0];
|
||||
|
||||
if (!userProfile || !userProfile.progression || !userProfile.progression.qualifications) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return userProfile.progression.qualifications.some((qualification: any) => {
|
||||
return typeof qualification === "string"
|
||||
? qualification.toLowerCase() === "intelligence"
|
||||
: qualification?.name?.toLowerCase() === "intelligence";
|
||||
});
|
||||
const flags = await loadQualificationFlags(payload, userId);
|
||||
return flags.intelligence;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import type { Payload } from "payload";
|
||||
import { hasAnyPermission } from "@/utils/access-control/hasPermission";
|
||||
import { loadQualificationFlags } from "@/utils/access-control/qualificationCache";
|
||||
|
||||
const LOGISTICS_PERMISSIONS = [
|
||||
"logistics:manage",
|
||||
|
|
@ -59,26 +60,10 @@ export async function hasLogisticsQualification(
|
|||
|
||||
if (await hasAnyPermission(payload, user, ...LOGISTICS_PERMISSIONS)) return true;
|
||||
|
||||
const profileRes = await payload.find({
|
||||
collection: "profiles",
|
||||
where: { user: { equals: user.id as number } },
|
||||
limit: 1,
|
||||
depth: 1,
|
||||
select: {
|
||||
progression: {
|
||||
qualifications: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
// Cached + single-flight; see qualificationCache.ts.
|
||||
const userId = Number(user.id);
|
||||
if (!Number.isFinite(userId)) return false;
|
||||
|
||||
const profile = profileRes.docs[0];
|
||||
if (!profile) return false;
|
||||
|
||||
const qualifications = profile.progression?.qualifications ?? [];
|
||||
return qualifications.some((q) => {
|
||||
if (typeof q === "object" && q !== null && "name" in q) {
|
||||
return (q.name as string).toLowerCase().includes("logistics");
|
||||
}
|
||||
return false;
|
||||
});
|
||||
const flags = await loadQualificationFlags(payload, userId);
|
||||
return flags.logistics;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,7 +9,19 @@ interface CachedPermissions {
|
|||
loadedAt: number;
|
||||
}
|
||||
|
||||
const cache = new Map<number, CachedPermissions>();
|
||||
/**
|
||||
* `globalThis` anchor, like the SSE bus and the minigame/poker registries: Next
|
||||
* bundles server packages per route entry, so a module-level Map forks into one
|
||||
* copy per bundle and the 30s window is effectively never warm across routes.
|
||||
*/
|
||||
interface PermissionCacheRegistry {
|
||||
__ptfPermissionCache?: Map<number, CachedPermissions>;
|
||||
}
|
||||
const permissionCacheRegistry = globalThis as typeof globalThis & PermissionCacheRegistry;
|
||||
const cache = (permissionCacheRegistry.__ptfPermissionCache ??= new Map<
|
||||
number,
|
||||
CachedPermissions
|
||||
>());
|
||||
|
||||
interface UserLike {
|
||||
id: number | string;
|
||||
|
|
|
|||
147
src/utils/access-control/qualificationCache.ts
Normal file
147
src/utils/access-control/qualificationCache.ts
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
import type { Payload } from "payload";
|
||||
|
||||
/**
|
||||
* Per-user division qualification flags, cached for a short TTL.
|
||||
*
|
||||
* Why this exists: `payload.auth()` ends with `getAccessResults()`, which
|
||||
* evaluates access for every collection and global. This app has ~100
|
||||
* collections and several division-gated access functions that each fall back
|
||||
* to a profiles read (`requireLogisticsPermission`, `requireIntelligencePermission`,
|
||||
* `scopedAdminPageAccess`, the wiki field access, and `canAccessAdminPanel`'s
|
||||
* division loop). That made a single auth pass issue ~31 identical
|
||||
* `profiles where user = ?` queries, and every page renders auth at least twice
|
||||
* (layout + page). Under 10-12 concurrent users the profile table became the
|
||||
* hot spot and renders queued behind it.
|
||||
*
|
||||
* Both flags come from the same row and the same query, so they are resolved
|
||||
* together and memoized:
|
||||
* - for 30s (same window as `loadUserPermissions`), so a warm request costs no
|
||||
* query at all;
|
||||
* - single-flight per user, so the ~31 concurrent calls inside one auth pass
|
||||
* collapse into one query instead of 31.
|
||||
*
|
||||
* The map is anchored on `globalThis` for the same reason as the permission
|
||||
* cache and the SSE bus: Next bundles server packages per route in dev, and a
|
||||
* module-level Map would fork into one copy per bundle, missing the cache from
|
||||
* other entry points.
|
||||
*
|
||||
* Invalidation: qualification edits are rare and admin-driven, so the TTL is
|
||||
* the bound. Call `invalidateQualificationCache(userId)` after a write that
|
||||
* changes `progression.qualifications` when instant effect matters (tests).
|
||||
*/
|
||||
const CACHE_TTL_MS = 30_000;
|
||||
|
||||
export interface QualificationFlags {
|
||||
intelligence: boolean;
|
||||
logistics: boolean;
|
||||
}
|
||||
|
||||
interface CacheEntry {
|
||||
flags: QualificationFlags;
|
||||
loadedAt: number;
|
||||
}
|
||||
|
||||
interface QualificationCacheRegistry {
|
||||
__ptfQualificationCache?: Map<number, CacheEntry>;
|
||||
__ptfQualificationInflight?: Map<number, Promise<QualificationFlags>>;
|
||||
}
|
||||
|
||||
const registry = globalThis as typeof globalThis & QualificationCacheRegistry;
|
||||
const cache = (registry.__ptfQualificationCache ??= new Map<number, CacheEntry>());
|
||||
const inflight = (registry.__ptfQualificationInflight ??= new Map<
|
||||
number,
|
||||
Promise<QualificationFlags>
|
||||
>());
|
||||
|
||||
const NO_QUALIFICATIONS: QualificationFlags = { intelligence: false, logistics: false };
|
||||
|
||||
interface QualificationRef {
|
||||
name?: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirrors the two predicates the callers used before this cache existed:
|
||||
* - intelligence matches a qualification named exactly "intelligence"
|
||||
* (string entries included);
|
||||
* - logistics matches a relationship entry whose name contains "logistics".
|
||||
*/
|
||||
function flagsFromQualifications(raw: unknown): QualificationFlags {
|
||||
if (!Array.isArray(raw)) return NO_QUALIFICATIONS;
|
||||
|
||||
let intelligence = false;
|
||||
let logistics = false;
|
||||
|
||||
for (const entry of raw) {
|
||||
if (typeof entry === "string") {
|
||||
if (entry.toLowerCase() === "intelligence") intelligence = true;
|
||||
continue;
|
||||
}
|
||||
if (!entry || typeof entry !== "object") continue;
|
||||
|
||||
const name = (entry as QualificationRef).name;
|
||||
if (typeof name !== "string") continue;
|
||||
|
||||
const lower = name.toLowerCase();
|
||||
if (lower === "intelligence") intelligence = true;
|
||||
if (lower.includes("logistics")) logistics = true;
|
||||
}
|
||||
|
||||
return { intelligence, logistics };
|
||||
}
|
||||
|
||||
async function fetchQualificationFlags(
|
||||
payload: Payload,
|
||||
userId: number,
|
||||
): Promise<QualificationFlags> {
|
||||
const res = (await payload.find({
|
||||
collection: "profiles",
|
||||
where: { user: { equals: userId } },
|
||||
limit: 1,
|
||||
// depth 1 keeps the qualification relationships populated by name.
|
||||
depth: 1,
|
||||
select: { progression: { qualifications: true } },
|
||||
})) as unknown as {
|
||||
docs: Array<{ progression?: { qualifications?: unknown } | null }>;
|
||||
};
|
||||
|
||||
return flagsFromQualifications(res.docs[0]?.progression?.qualifications);
|
||||
}
|
||||
|
||||
/** Resolve a user's division qualifications, memoized for 30s. */
|
||||
export async function loadQualificationFlags(
|
||||
payload: Payload,
|
||||
userId: number,
|
||||
): Promise<QualificationFlags> {
|
||||
if (!Number.isFinite(userId)) return NO_QUALIFICATIONS;
|
||||
|
||||
const cached = cache.get(userId);
|
||||
if (cached && Date.now() - cached.loadedAt < CACHE_TTL_MS) {
|
||||
return cached.flags;
|
||||
}
|
||||
|
||||
const pending = inflight.get(userId);
|
||||
if (pending) return pending;
|
||||
|
||||
const promise = fetchQualificationFlags(payload, userId)
|
||||
// A failed lookup must not break access checks: fall through as "no
|
||||
// qualifications", matching the previous per-call behavior.
|
||||
.catch((): QualificationFlags => NO_QUALIFICATIONS)
|
||||
.then((flags) => {
|
||||
cache.set(userId, { flags, loadedAt: Date.now() });
|
||||
inflight.delete(userId);
|
||||
return flags;
|
||||
});
|
||||
|
||||
inflight.set(userId, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
/** Drop one user's cached flags, or the whole cache when no id is given. */
|
||||
export function invalidateQualificationCache(userId?: number): void {
|
||||
if (userId === undefined) {
|
||||
cache.clear();
|
||||
inflight.clear();
|
||||
return;
|
||||
}
|
||||
cache.delete(userId);
|
||||
}
|
||||
Loading…
Reference in a new issue