Compare commits

...
Author SHA1 Message Date
admin a2dff8f911 fix the action result type mapping 2026-01-07 06:46:29 -08:00
adminandClaude Opus 4.5 fa5cc43672 Fix new game creation crashes: RoundPhase and BattalionTypes
Two issues prevented CreateGame from succeeding:

1. UNKNOWN_PHASE error: GameStateProto was created without currentPhase,
   defaulting to UNKNOWN_PHASE (0) which caused ProtoConversionException

2. None.get in BattalionSuitability: newBattalionTypes was in the proto
   but commented out in the Scala model. When creating games, battalion
   types were set in ActionResult but lost during proto-to-Scala conversion,
   so they never got applied to GameState

Fixed by:
- Setting currentPhase = NEW_ROUND in PersistedHistory initial states
- Adding newBattalionTypes field to ActionResultT, ActionResultC
- Adding conversion in ActionResultProtoConverter
- Adding applyNewBattalionTypes extension method
- Calling extension in ActionResultApplierImpl

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 21:19:58 -08:00
d7afc48202 Add JWT service initialization logging (#5071)
- Log whether JWT_PRIVATE_KEY environment variable is set/empty
- Log the key ID and size when successfully loaded
- Log parse errors instead of silently swallowing them
- Helps diagnose OAuth token validation issues across environments

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 21:22:29 -08:00
54de9fe655 Refactor: unified AnimationType for animations and sounds (#5070)
- Add AnimationType enum to unify CommandType and ActionType for animations
- Change Model.PerformTargetedCommand to return CommandType? (null = failure)
- Add PlayAnimationAndSound helper that handles both animation and sound
- Add conversion functions: AnimationTypeForCommand, AnimationTypeForAction
- Update PerformAction to play sound immediately with animation
- Update ModelUpdated to use helper for other players' actions
- Skip duplicate sound for current player (already played in PerformAction)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 21:15:16 -08:00
68254d011b Hardcode auth service URL to prod for all environments (#5067)
Unity client now always connects to prod.eagle0.net:40033 for OAuth,
regardless of which Eagle server is selected for gameplay. This allows
QA testing with prod authentication.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 20:40:08 -08:00
37f099be96 Add unit-specific weapons for melee animation (#5069)
Each battalion type now has its own weapon and animation style:
- Light Infantry: Swords (swung)
- Heavy Infantry: Maces/Hammers (swung, larger, more violent)
- Light Cavalry: Small spears (thrust)
- Heavy Cavalry: Large lances (thrust, largest, most violent)
- Longbowmen: Daggers (thrust, smaller, less violent)
- Undead: Bones (thrust, violent)

Weapon configs include scale multiplier and violence multiplier for
differentiated visual feedback per unit type.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 20:37:04 -08:00
9f47a9d01c Add arrow volley animation for archery attacks (#5068)
Uses SpriteRenderer for world-space rendering (like particle effects)
instead of UI Image, which has issues with the rotated Grid Canvas.
This approach follows the proven pattern used by SetCellModifierEffect.

Key changes:
- ArrowVolleyAnimator: Creates arrows as SpriteRenderer GameObjects
  parented to gridCanvas, positioned with transform.localPosition
- HexGrid: Added GetCellLocalPosition() to expose cell positions
- ShardokGameController: Triggers animation in PerformAction() for
  player's archery commands (latency hiding) and in ModelUpdated()
  for other players' archery actions

The Grid Canvas uses Screen Space - Camera with 90° X rotation
(lies flat like a tabletop). UI Image components have rendering
issues in this configuration, but SpriteRenderers (3D objects)
render correctly - matching how particle effects already work.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 17:33:41 -08:00
9014874f0b Fix game upload to check for conflicts before overwriting (#5066)
Previously, uploading a game would extract files to disk before checking
if the game already existed, potentially losing data if the import failed.

Changes:
- Add CheckGameExists RPC to check if game exists in memory or on disk
- Implement checkGameExists in GamesManager and EagleServiceImpl
- Update admin server upload handler to check before extracting files
- When conflict detected, show options: "Use New ID" or "Replace Existing"
- "Use New ID" generates a random new game ID for the upload
- "Replace Existing" removes existing game from memory before overwriting
- Add JavaScript in games.html to handle conflict resolution flow

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 16:47:46 -08:00
93339c8fc3 Add delete game feature to admin console (#5065)
- Add DeleteGame RPC to proto with request/response messages
- Implement deleteGame in GamesManager to remove game from memory
  and optionally delete save files from disk
- Implement deleteGame override in EagleServiceImpl
- Add handleGameDelete handler in Go admin server
- Add delete button and confirmation modal to game detail page
- Modal includes checkbox to also delete save files from disk

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 16:17:23 -08:00
b10f936dfd Fix duplicate battalion IDs in destroyedBattalionIds (#5064)
A battalion could be added twice if:
1. Its size was 0, AND
2. Its unit was Captured or Outlawed

This caused "key not found" errors when the applier tried to remove
the same battalion twice.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 21:52:22 -08:00
db5446ea37 Add Admin service route to nginx port 40033 (#5063)
The QA admin server connecting to prod auth was getting 404 because
nginx only routed the Auth service, not the Admin service which
handles ListUsers RPC for admin privilege checks.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 21:27:33 -08:00
3119b0c63c Add --auth-tls flag for admin server remote auth connections (#5061)
When connecting to a remote auth server (e.g., prod.eagle0.net:40033),
TLS is required. This adds an --auth-tls flag that switches from
insecure credentials to TLS with system root CAs.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 20:49:02 -08:00
4b36870cc5 Allow disabling JFR sidecar in admin server (#5059)
When --jfr-sidecar-addr is set to empty string (""), JFR functionality
is disabled instead of failing with connection errors. This is useful
for QA environments that don't have the JFR sidecar container.

- Add jfrDisabled() helper function
- Return "JFR sidecar not configured" for /jfr/status (as JSON)
- Return 503 Service Unavailable for /jfr/start, /jfr/stop, /jfr/download
- Update startup log to indicate JFR status

Usage: --jfr-sidecar-addr ""

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 18:10:49 -08:00
b3d0c1ce29 Delete ActionResultProtoApplierImpl (no longer needed) (#5058)
After PR #5056, History classes now use the Scala ActionResultApplierImpl
instead of the proto-based applier. This removes the now-unused proto applier:

- Delete ActionResultProtoApplier.scala and ActionResultProtoApplierImpl.scala
- Delete ActionResultProtoApplierImplTest.scala
- Remove unused proto applier dependencies from BUILD files
- Update comments in MarchCommand.scala and SendSuppliesCommand.scala to
  reference ActionResultApplierImpl instead

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 18:07:32 -08:00
577c94f092 Remove unused images from Assets/Images, update references and asset audit (#5057)
- Delete all unused images from Assets/Images/ (keeping only startFire.png)
- Delete duplicate Assets/Images/bridge.png (identical to Shardok/commandImages/bridge.png)
- Update Gameplay.unity and Map Editor.unity to reference the Shardok bridge
- Update ASSET_AUDIT.md:
  - Mark previously deleted stock images as done
  - Add clip art section for bridge.png and startFire.png that need replacement
  - Update action items and recommendations

Deleted images (unused):
- Steel-Hauberk.png, bow00.png, brotherhood.png, burglar.png
- chicken-leg.png, clinking-beer-mugs.png, crystal-ball.png, faker.png
- flail.png, gift.png, jail.png, longbow.png, orders.png
- peace-dove.png, spearshield.png, supplies.png, travel.png, bridge.png

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 17:08:42 -08:00
0c271aacea Use Scala applier in History classes instead of proto applier (#5056)
- Add fromProto method to ActionResultProtoConverter to convert proto
  ActionResult to Scala ActionResultT
- Add fromProto method to ChangedProvinceConverter to convert proto
  ChangedProvince to Scala ChangedProvinceT
- Update InMemoryHistory and PersistedHistory to use ActionResultApplierImpl
  (Scala) instead of ActionResultProtoApplierImpl
- Store precomputed Scala state in ActionWithResultingState to avoid
  redundant proto-to-Scala conversions

This eliminates the need to maintain two separate applier implementations
that must stay in sync. The proto applier is no longer used by production
code and can be deleted in a follow-up.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 17:02:50 -08:00
5a82353744 Remove unused actionResultProtoApplier parameter from EngineImpl (#5055)
* Delete dead Action trait and TRandomSequentialResultsAction

- Delete Action.scala - trait with execute method, nothing implements it
- Delete TRandomSequentialResultsAction.scala - nothing extends it
- Remove :action dependency from all BUILD files
- Remove dead WaitingAction implicit class from test package.scala
- Remove unused WaitingAction imports from test files

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Remove unused actionResultProtoApplier parameter from EngineImpl

- Remove unused actionResultProtoApplier constructor parameter (declared but never used)
- Remove unused ActionResultProtoApplier/Impl imports from EngineImpl
- Remove unused RuntimeValidator import from EngineImpl
- Remove action_result_proto_applier_impl dependency from engine_impl and round_phase_advancer
- Remove unused runtime_validator dependency from engine_impl

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 14:52:32 -08:00
c9d6944b95 Delete dead Action trait and TRandomSequentialResultsAction (#5054)
- Delete Action.scala - trait with execute method, nothing implements it
- Delete TRandomSequentialResultsAction.scala - nothing extends it
- Remove :action dependency from all BUILD files
- Remove dead WaitingAction implicit class from test package.scala
- Remove unused WaitingAction imports from test files

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 14:51:48 -08:00
66efefc8d6 Replace Hetzner plan doc with latency hiding strategies (#5053)
The Hetzner on-demand compute implementation is complete:
- ARM64 builds working in CI
- Shardok running on Hetzner CAX41 in Helsinki
- Production Eagle connected via TLS + token auth
- IPv6/NAT64 networking configured

Delete the completed planning doc and add a new doc covering
future latency optimization strategies:
1. Client-side animation masking (recommended first step)
2. Split Shardok architecture (future if needed)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 13:37:53 -08:00
811de67c40 Move Custom Battle to lobby with OAuth authentication (#5051)
* Move Custom Battle to lobby, use OAuth authentication

- Remove _createConnection() from _internalCustomBattle() since connection
  already exists when called from lobby
- Hide gameSelectionPanel instead of connectionPanel when entering custom battle
- Add customBattleButton field for lobby UI button
- Add cancelCustomBattleButton and CancelCustomBattle() to return to lobby
- Wire up button click handlers in SetupLobbyUI()

The Custom Battle button should now be placed in the gameSelectionPanel (lobby)
in Unity and assigned to the customBattleButton field. A cancel button in the
customBattlePanel should be assigned to cancelCustomBattleButton.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Wire up Custom Battle and Cancel buttons in Unity scene

- Assign customBattleButton in lobby panel
- Assign cancelCustomBattleButton in custom battle panel

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix CancelCustomBattle to properly reset canvas states

Hide shardokCanvas and ensure connectionCanvas is visible when
returning to lobby from custom battle.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix Back button onClick handler in custom battle panel

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 13:32:34 -08:00
f4aa19119b Remove dead execute method from ProtolessRandomSequentialResultsAction (#5052)
* Update DEPROTO_PLAN.md: 100% action files now protoless

- ResolveBattleAction migrated to Scala types (PR #5048)
- All 52 action files are now fully protoless
- CommandChoiceHelpers fully migrated to Scala types
- Update progress summary and validation checklist

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Remove dead execute method from ProtolessRandomSequentialResultsAction

The execute(startingState: GameStateProto, applier: ActionResultProtoApplier) method
was never called - all actions using this base class now call .results() directly
and apply results via RandomStateSequencer or ActionResultApplier.

This removes the dead method and its unused dependencies (SeededRandom,
ActionResultProtoApplier, VigorXPApplier, ActionResultProtoConverter).

Note: The proto GameState export is retained because downstream actions use
ProvinceViewFilter which has overloaded methods taking both proto and Scala
GameState - overload resolution requires both types to be visible.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 13:21:08 -08:00
80023d39a0 Update DEPROTO_PLAN.md: 100% action files now protoless (#5050)
- ResolveBattleAction migrated to Scala types (PR #5048)
- All 52 action files are now fully protoless
- CommandChoiceHelpers fully migrated to Scala types
- Update progress summary and validation checklist

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 13:20:46 -08:00
ecffeb0d2c Fix Docker IPv6 check: don't require sudo (#5049)
The deploy user doesn't have passwordless sudo. Change from trying
to configure Docker (which fails) to just checking and warning.

Docker IPv6 is a one-time server setup done manually.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 13:03:28 -08:00
1936d65bea Migrate ResolveBattleAction to Scala types (#5048)
- Change ResolveBattleAction to take Scala GameState and use ActionResultApplier
- Add resolvedBattle field to ActionResultT, ActionResultC, and proto converter
- Update EngineImpl.resolveBattle to use Scala-based applier
- Update test to convert proto GameState to Scala and handle Scala results

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 13:02:28 -08:00
ea46bb4a90 Enable Docker IPv6 for connecting to Hetzner Shardok (#5047)
The Hetzner Shardok server is IPv6-only. Docker containers need
IPv6 support to reach it.

Changes:
- docker-compose.prod.yml: Add IPv6-enabled network
- docker_build.yml: Configure Docker daemon for IPv6 on deploy
  (with ip6tables for NAT)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 12:09:58 -08:00
480ae0d0c6 Fix auth service overwriting external user database changes (#5046)
The auth service loads users.pb into memory at startup. When authcli
modifies the file on disk (e.g., to grant admin), the service still has
the old in-memory copy. On next login, it would overwrite the file with
stale data, losing the admin grant.

Fix: Check file modification time before each FindOrCreateUser call.
If the file was modified externally, reload it before proceeding.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 11:06:44 -08:00
14def8899d Migrate ChronicleEventGenerator to use Scala NotificationDetails (#5045)
- Replace proto notification detail imports with Scala NotificationDetails
- Use NotificationConverter.fromProto to convert proto -> Scala
- Remove dependency on action_result_notification_details_scala_proto
- Add dependencies on notification_trait and notification_converter

The internal pattern matching now uses Scala sealed trait NotificationDetails
instead of proto case classes, reducing proto coupling in the action layer.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 11:05:43 -08:00
adminandClaude Opus 4.5 581ffb735e Make Shardok address configurable via SHARDOK_ADDRESS env var
Allows switching between local Shardok (default: shardok:40042) and
remote Hetzner Shardok (shardok.prod.eagle0.net:40042) via GitHub
Actions secrets.

To use Hetzner Shardok in production:
1. Add secret SHARDOK_ADDRESS=shardok.prod.eagle0.net:40042
2. Add secret SHARDOK_AUTH_TOKEN=<your-token>

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 10:51:52 -08:00
74383ae5d9 Fix admin console OAuth flow and route protection (#5044)
* Fix admin console OAuth flow and route protection

Changes:
- Gate all admin routes with requireAuth (games, settings, JFR, APIs)
  Only login, logout, health, and static files are public now
- Add return_url to OAuth flow so auth service redirects back to admin
  console after callback, instead of showing "close this window"
- handleLoginComplete now immediately completes login on redirect
- Update authcli help text with production usage examples

The OAuth flow now works properly for web clients:
1. User clicks Sign in -> admin console redirects to OAuth provider
2. OAuth provider calls auth service callback
3. Auth service redirects back to admin console's /login/complete
4. Admin console sets JWT cookie and redirects to /games

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix oauth_test.go for GetAuthURL signature change

Update test calls to pass empty string for the new returnURL parameter.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 10:51:23 -08:00
ba9c92222c Add asset licensing audit document (#5042)
Document all media assets in Unity project for licensing review before
potentially opening public access to game downloads. Identifies:
- Asset Store purchases (properly licensed)
- CC-licensed music with attribution
- Items needing verification (Shardok sounds, StrategyGameIcons, etc.)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 10:47:28 -08:00
f24c1209e0 Convert ProvinceEvent from sealed trait to Scala 3 enum (#5043)
- Replace sealed trait + case class pattern with Scala 3 enum
- Update all import sites to use `ProvinceEvent.{BeastsEvent, ...}` pattern
- More idiomatic Scala 3 with cleaner syntax

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 10:23:55 -08:00
e7c8df8b33 Add admin user management to admin console (#5041)
* Add admin user management to admin console

Adds functionality to view and manage user identity→display name links:

Backend (auth service):
- New admin.proto with AdminService gRPC (ListUsers, SetUserDisplayName, SetUserAdmin)
- AdminHandler validates JWT is_admin claim for authorization
- UserService methods for listing users and admin operations

Frontend (admin console):
- OAuth login flow with Discord/Google (JWT stored in HTTP-only cookie)
- Auth middleware requiring is_admin claim for /users routes
- Users page with search, display name editing, and admin toggle
- HTMX-powered table with infinite scroll pagination

Deployment:
- admin container now connects to auth service for user management

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add authcli tool for user management

CLI tool for managing auth service users directly via the users.pb file.
Useful for bootstrapping the first admin user or emergency access.

Commands:
- list: List all users with their admin status
- find <email>: Find user by email (partial match)
- set-admin <id> true|false: Set admin status by user ID
- grant-admin <email>: Grant admin to user by exact email match

Usage:
  authcli --data-dir=/app/data list
  authcli --data-dir=/app/data grant-admin your@email.com

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add authcli to auth server Docker image

- Include authcli_linux_amd64 in auth_binary_layer
- Update auth_build.yml paths to trigger on authcli and admin proto changes

Usage on VM:
  docker exec auth-server /app/authcli_linux_amd64 --data-dir=/app/data list
  docker exec auth-server /app/authcli_linux_amd64 --data-dir=/app/data grant-admin user@email.com

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 07:55:23 -08:00
c753c4995a Add Scala overloads to ProvinceEventUtils (#5040)
* Add Scala overloads to ProvinceEventUtils

- Add Scala overloads for isBlizzardEvent, isBeastsEvent, isEpidemicEvent,
  isFestivalEvent, isDroughtEvent, isFloodEvent, isImminentRiotEvent
- Add Scala overloads for beastsCount and beastInfo
- Update BUILD.bazel with required Scala model dependencies
- Add province event dependency to LegacyProvinceUtils for overload resolution

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Replace isInstanceOf with pattern matching in ProvinceEventUtils

- Use match expressions instead of isInstanceOf for type checks
- More idiomatic Scala style

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 07:42:02 -08:00
51e9e9b14a Add Scala overload to ExpandedCombatUnitUtils (#5039)
- Add protoless overload that takes ScalaGameState and CombatUnitC
- Uses BattalionViewFilter (protoless) and BattalionViewConverter for output
- Exports CombatUnitC and ScalaGameState types for downstream callers

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-04 06:00:24 -08:00
a2feaa6546 Add protoless Scala overloads to diplomacy Resolve command factories (#5038)
- EligibleDiplomacyStatuses: Add Scala overload for maybeImprisonStatus
  that takes provinces Iterable instead of proto GameState
- AvailableResolveTruceOfferCommandFactory: Add Scala overload that
  filters Scala TruceOffer instances and converts to proto output
- AvailableResolveAllianceOfferCommandFactory: Add Scala overload for
  AllianceOffer filtering
- AvailableResolveBreakAllianceCommandFactory: Add Scala overload for
  BreakAlliance filtering
- AvailableResolveInvitationCommandFactory: Add Scala overload with
  protoless invitation validation using FactionUtils
- AvailableResolveRansomOfferCommandFactory: Add Scala overload with
  protoless RansomValidity and conflict checking

All Scala overloads take ScalaGameState and output proto commands,
allowing callers with Scala model types to avoid GameStateConverter.toProto().

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 22:49:44 -08:00
4d83978951 Fix OAuth reconnection failure due to PlayerPrefs threading (#5037)
TokenStorage was calling PlayerPrefs.GetString() which can only be
called from Unity's main thread. When PersistentClientConnection
attempts to reconnect from a background thread, JwtAuthInterceptor
tries to get the access token, causing a UnityException.

This caused an infinite loop: DeadlineExceeded → reconnect attempt →
PlayerPrefs exception → reconnect fails → idle timeout → retry...

Changes:
- TokenStorage: Add in-memory cache for thread-safe token access
- OAuthManager: Initialize cache on main thread in Awake()
- PersistentClientConnection: Schedule reconnect when stream ends
  normally (was missing, causing silent connection death)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 22:38:03 -08:00
11de6872d4 Add TLS support to ExternalAuthClient for remote auth connections (#5036)
Enable QA Eagle to connect to production auth service over TLS.

- Use TLS for external connections (non-localhost hosts)
- Keep plaintext for local container-to-container connections
  (localhost, auth, 127.x.x.x)

This allows running QA Eagle with --auth-service-url prod.eagle0.net:40033
to share user accounts with production.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 22:25:50 -08:00
ecd089de59 Add Sentry integration for exception alerting (#5011)
- Add io.sentry:sentry dependency
- Initialize Sentry from SENTRY_DSN environment variable
- Report uncaught exceptions via ExceptionInterceptor
- Add SENTRY_DSN to docker-compose and CI workflow

When SENTRY_DSN is configured, uncaught exceptions in gRPC handlers
will be reported to Sentry for email/Slack alerts.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 22:20:05 -08:00
c1756cb36b Add protoless ProvinceViewFilter overload with faction filtering (#5034)
- Add filteredProvinceView(ProvinceT, ScalaGameState, FactionId) overload
- Use protoless FactionUtils.hasAlliance, Visibility.hasFullVisibility, and ProvinceUtils.incomingOthers
- Add helper methods: fullProvinceInfoScala, maybeIncomingAttackersScala, unaffiliatedHeroInfoScala
- Handle reconned provinces directly from Scala FactionT.reconnedProvinces

GameStateViewFilter improvements:
- Eliminate GameStateConverter.toProto() call in Scala overload
- Use new ProvinceViewFilter Scala overload for faction filtering
- Convert battalionTypes and chronicleEntries to proto only at output boundary

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 22:16:44 -08:00
78533a9ff0 Remove Eagle user management - forward to Go auth service (#5033)
Phase 2 of moving user management to Go auth service:
- Eagle now forwards setDisplayName, getCurrentUser, logout to Go auth
- Removed InternalUserServiceImpl and internal gRPC server (port 40034)
- UserService is now optional (only created when not using external auth)
- Updated docker-compose to remove port 40034 exposure

This makes Eagle stateless for user data when configured with
--auth-service-url, enabling QA to point to prod auth service.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 21:39:24 -08:00
8172a4e117 Migrate CheckForFulfilledQuestsAction to protoless BattalionTypeFinder (#5032)
* Migrate CheckForFulfilledQuestsAction to protoless BattalionTypeFinder

- Change battalionTypes parameter from proto Vector[BattalionType] to Scala Vector[BattalionType]
- Update callers (EngineImpl, EndVassalCommandsPhaseAction) to pass Scala types directly
- Eliminate wasteful BattalionTypeConverter.toProto() conversions
- Update test to use Scala BattalionType

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add Scala overload to ExpandedUnaffiliatedHeroUtils, eliminate proto conversions

- Add ExpandedUnaffiliatedHeroUtils.expandedUnaffiliatedHero(ScalaGameState, UnaffiliatedHeroT)
- Add UnaffiliatedHeroConverter.unaffiliatedHeroTypeToProto() helper for efficient enum conversion
- Use reverse map instead of inefficient .find() in UnaffiliatedHeroConverter.toProto()
- Update AvailablePleaseRecruitMeCommandFactory to use Scala overload directly
- Eliminate wasteful GameStateConverter.toProto() and UnaffiliatedHeroConverter.toProto() calls

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add exports to expanded_unaffiliated_hero_utils for transitive type visibility

Callers that import ExpandedUnaffiliatedHeroUtils now see both overloads in
method signatures, which exposes ScalaGameState and UnaffiliatedHeroT types.
Add these as exports so callers can compile without needing explicit deps.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 21:33:32 -08:00
fbabe9cea4 Move user management to Go auth service (Phase 1) (#5030)
* Move user management to Go auth service (Phase 1)

Auth service now manages users locally instead of calling Eagle:
- Add users.go with UserService for protobuf-based user persistence
- Implement SetDisplayName, GetCurrentUser, Logout handlers
- Extract JWT from gRPC metadata (authorization header)
- Add ValidateAccessToken function to jwt.go
- Add user_go_proto target for user.proto
- Add AUTH_DATA_DIR env var and /app/data volume mount

Auth service no longer depends on Eagle's InternalUserService.
Eagle's user management code remains for now (Phase 2 cleanup).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add unit tests and migration path for user service

- Add comprehensive unit tests for UserService (users_test.go)
- Add automatic migration from Eagle's users.pb location
- Add atomic write pattern for crash safety (write .tmp, then rename)
- Add AUTH_LEGACY_DATA_DIR config for migration path
- Mount Eagle's saves volume read-only for migration access

Migration strategy:
1. Auth service checks /app/data/users.pb first
2. If not found, reads from /app/saves/auth/users.pb (Eagle's location)
3. Saves migrated data to new location
4. Subsequent reads/writes use new location only

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 19:21:45 -08:00
7df24149f7 Deproto Phase 5: Document Legacy utility migration status (#5031)
* Add sortKey to FactionUtils to match LegacyFactionUtils API

- Add sortKey method and sortIgnoredChars constant to protoless FactionUtils
- Update LegacyFactionUtils to use direct proto field access (avoid converter
  failures on incomplete test data)
- Both implementations now have matching APIs for the deproto migration
- Update DEPROTO_PLAN.md with progress

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Document Legacy* utility migration status in DEPROTO_PLAN.md

All Legacy* utilities now have protoless equivalents with matching APIs:

**Parallel Implementations (proto mirrors protoless):**
- FactionUtils / LegacyFactionUtils - 24+ boundary callers
- HeroUtils / LegacyHeroUtils - 10 boundary callers
- ProvinceUtils / LegacyProvinceUtils - 20 boundary callers

**Awaiting migration of callers:**
- BattalionUtils / LegacyBattalionUtils - 4 callers
- BattalionViewFilter / LegacyBattalionViewFilter - 3 callers
- BattalionTypeFinder / LegacyBattalionTypeFinder - 2 callers

Legacy versions are appropriately used by boundary code (availability
factories, view filters, action appliers) that works with proto GameState.
The AI layer already uses the protoless versions.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 18:41:44 -08:00
7de74539f0 Fix LocalFilePersister to create parent directories (#5029)
When saving to paths like "auth/users.pb", the parent directory
may not exist. FileOutputStream doesn't create parent directories,
so the save would silently fail. Now we ensure parent directories
exist before writing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 17:31:54 -08:00
e9dd53fdf8 Hetzner setup: docs + Step 7 implementation (#5018)
* Update Hetzner docs with actual deployment details

- Use shardok.prod.eagle0.net as the domain name
- Step 4: Specify GitHub Actions secrets location
- Step 5: Recommend Hillsboro, OR (hil) + IPv6 floating IP
- Update all code examples and cloud-init scripts

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Wire SHARDOK_AUTH_TOKEN through Eagle's Shardok connection

Implements Step 7 of Hetzner setup guide:
- Main.scala reads SHARDOK_AUTH_TOKEN env var and creates ShardokSecurityConfig
- TLS is auto-enabled when Shardok address contains ".eagle0.net"
- Security config passed to both newGamesManager and newCustomBattleManager
- docker-compose.prod.yml passes SHARDOK_AUTH_TOKEN to Eagle container
- docker_build.yml passes secret during deployment

This is backward compatible: local Docker Shardok (shardok:40042) continues
to work without TLS/auth since the address doesn't contain ".eagle0.net".

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Update ShardokInstanceManager for DigitalOcean registry and TLS

- Update cloud-init script to use DigitalOcean Container Registry instead of ghcr.io
- Add Let's Encrypt/Certbot setup for TLS certificates
- Configure automatic certificate renewal via cron
- Pass TLS cert paths and auth token file to Shardok container
- Default to shardok.prod.eagle0.net domain

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix cloud-init to use eagle0.conf instead of environment variables

The Shardok C++ server reads configuration from /usr/local/share/eagle0/eagle0.conf,
not environment variables. Updated cloud-init script to:
- Create eagle0.conf with TLS and auth paths
- Mount the config directory into the container
- Remove unused -e environment variable flags

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Simplify spin-up strategy: trigger on human turns with 10-min idle timeout

Instead of trying to predict battles, we now:
- Spin up Shardok when any human player takes a turn
- Shut down after 10 minutes of no human turns

This is simpler and more reliable. Battles happen regularly during active
play, so Shardok will be ready when needed. The 10-minute timeout is long
enough to cover thinking time but short enough to minimize idle costs.

Updated:
- SHARDOK_ON_DEMAND_COMPUTE.md with new strategy and state machine
- ShardokInstanceManager: renamed onPlayerActivity -> onHumanTurn,
  changed default idle timeout from 60 to 10 minutes

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Document Hetzner testing progress and ARM64 blocker

Testing status:
- Hetzner CAX41 ARM64 server created in Helsinki
- Floating IPv6 configured with netplan persistence
- DNS and Let's Encrypt certificates working
- NAT64 configured for IPv6→IPv4 registry access

BLOCKER: ARM64 container crashes with runfiles error:
"cannot find runfiles (argv0="/app/shardok-server")"
Needs BUILD.bazel investigation for ARM64 image packaging.

Also documented known issues:
- IPv6-only servers need NAT64 DNS (nat64.net)
- Floating IP requires manual netplan config

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix ARM64 container crash: add missing environment variables

The ARM64 Shardok container was crashing with "cannot find runfiles"
because SHARDOK_RESOURCES_PATH and SHARDOK_MAPS_PATH weren't set.
Without these, the binary tries to use Bazel runfiles which don't
exist in the container.

Added the required environment variables to the docker run command
in the cloud-init script, matching docker-compose.prod.yml.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 17:07:10 -08:00
35e8f85627 Fix duplicate UnaffiliatedHero entries when only hero departs (#5028)
When the only ruling faction hero departed from a province, clearRulingFaction
would create duplicate UnaffiliatedHeroC entries - one from the departure logic
and another from clearRulingFaction iterating over all rulingFactionHeroIds.

Fix: Filter out heroIds that already have entries in newUnaffiliatedHeroes
before creating new ones.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 17:04:41 -08:00
35bc242582 Fix upload section styling in admin panel (#5027)
* Fix upload section styling in admin panel

- Add explicit positioning to prevent overlap with other elements
- Style the details/summary for clearer expand/collapse indicators
- Add border and background when expanded for visual clarity
- Prevent button from shrinking in flex layout

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix upload section contrast and button sizing

- Use card background color for summary with proper text contrast
- Change Upload button to btn-small class for appropriate sizing
- Add proper border and styling for expanded form area
- Remove inline styles in favor of CSS classes

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix Upload button to not be full-width

- Add width: auto !important to override Pico CSS defaults
- Add flex-grow: 0 to prevent stretching in flex container
- Add position: static to prevent any fixed/absolute positioning
- Add z-index: auto to upload section to prevent stacking issues

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 16:52:45 -08:00
c5829b1aff Remove unused Cloudflare OAuth relay worker (#5026)
This was never successfully deployed. OAuth callbacks are handled
directly by the Go auth service via nginx routing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 16:44:48 -08:00
6c78d9f733 Remove dead code from LegacyHeroUtils and LegacyFactionUtils (#5025)
* Remove dead code from LegacyHeroUtils

- Remove unused `seniorityOrder` method (protoless version in HeroUtils is used)
- Remove unused `sortOrdering` method (protoless version in HeroUtils is used)
- Remove unused `discordance` method (protoless version in HeroUtils is used)
- Remove unused `faction` method (protoless version in HeroUtils is used)
- Remove unused `Faction` import and proto dependency
- Remove corresponding tests for deleted methods

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Remove dead code from LegacyFactionUtils

- Remove unused `trust` method (protoless version in FactionUtils is used)
- Remove unused `factionHead` method
- Remove unused `ownedNeighbors` method (protoless version in FactionUtils is used)
- Remove unused `hostileNeighbors` methods (protoless version in FactionUtils is used)
- Remove unused `neutralNeighbors` method (protoless version in FactionUtils is used)
- Remove unused `truceExpirationDate` method
- Remove unused `alliedFactions` method (protoless version in FactionUtils is used)
- Remove unused `provincesWithHostileNeighbors` method
- Remove unused `ProvinceWithHostileNeighbors` case class
- Remove unused `Hero` import and `hero_scala_proto` dependency
- Remove corresponding tests for deleted methods

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 15:29:57 -08:00
1966dfbc24 Update DEPROTO_PLAN.md and remove dead code from LegacyBattalionUtils (#5022)
* Update DEPROTO_PLAN.md with Phase 5 progress

- Add section for thin wrapper refactorings (LegacyRansomValidity, LegacyRecruitmentOdds)
- Note LegacyHeroUtils dependency on LegacyFactionUtils
- Note LegacyBattalionUtils has intentionally different power multipliers

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Remove dead code from LegacyBattalionUtils

- Remove unused `power` method (superseded by BattalionPower.power)
- Remove unused `estimatedPower` method (superseded by BattalionPower.estimatedPower)
- Remove unused `powerMultiplier` map (only used by removed methods)
- Remove unused `BattalionView` import and proto dependency

All callers already use BattalionPower for power calculations.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 12:33:03 -08:00
7cd7edf9a0 Fix null reference race in lobby subscriber callbacks (#5023)
The code checked _lobbySubscriber != null before enqueueing a lambda,
but the lambda captured the field reference and executed later on the
main thread when _lobbySubscriber could have become null (e.g., during
Dispose).

Fix by capturing the subscriber in a local variable before the null
check. This ensures the lambda uses the subscriber that was active
when the message arrived, even if _lobbySubscriber changes later.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 12:32:40 -08:00
104ee5429d Add scheduled workflow to cleanup old container images (#5024)
Runs daily at 3am UTC to delete container images older than 5 days from
DigitalOcean Container Registry. Protected tags (latest, arm64-latest)
are never deleted.

Also runs garbage collection after cleanup to reclaim storage.

Includes manual trigger with dry-run option for testing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 12:31:31 -08:00
57fd73571f Refactor LegacyRecruitmentOdds to delegate to protoless RecruitmentOdds (#5021)
- Convert LegacyRecruitmentOdds from duplicated logic to thin wrapper
- Uses FactionConverter, HeroConverter, UnaffiliatedHeroConverter
- Delete LegacyRecruitmentOddsTest (protoless version already tested)
- Reduces duplicate code, centralizes recruitment odds calculation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 11:56:50 -08:00
9ea6e29752 Delete unused Legacy* utilities: LegacyProvinceDistances, LegacyBattalionSuitability, LegacyFoodConsumptionUtils, LegacyHandleRiotUtils (#5020)
Phase 5 of deproto cleanup - remove Legacy* utilities that have no production callers:

- LegacyProvinceDistances: no callers besides its own test
- LegacyBattalionSuitability: no callers besides its own test
- LegacyFoodConsumptionUtils: no callers besides its own test
- LegacyHandleRiotUtils: no callers besides its own test

Updated DEPROTO_PLAN.md to track Phase 5 progress.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 09:49:51 -08:00
8581232f70 Add Scala overloads to BattalionNameFilter and BattleFilter (#5019)
* Eliminate GameState toProto() conversion in LLM pipeline

Phase 1 of deproto optimization: Make LlmRequestWithGameState use Scala
GameState instead of proto GameState, eliminating wasteful round-trip
conversion in UnrequestedTextHandler (the heaviest proto conversion in profiles).

Changes:
- LlmResolver: Change LlmRequestWithGameState.gameState to Scala GameState
- UnrequestedTextHandler: Remove GameStateConverter.toProto() calls, pass
  gameHistory.stateAfter() directly
- Update all prompt generators (~38 files) to use Scala model types:
  - FactionT instead of proto Faction
  - HeroT instead of proto Hero
  - ProvinceT instead of proto Province
  - Scala enums (Gender.Male, Profession.Mage) instead of proto enums
- DivineMessagePromptGenerator: Rewrite quest pattern matching to use
  Scala QuestC types instead of proto quest types
- ChronicleUpdatePromptGenerator: Inline province lookup, remove
  LegacyFactionUtils dependency
- BattalionDescriptions: Add Scala BattalionT and BattalionTypeId overloads
- Update test files to use concrete Scala types (HeroC, FactionC, ProvinceC)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Make AttackCommandChooser fully protoless

- Add `estimatedPower(BattalionViewC)` to `BattalionPower` for handling recon
  data with optional training/armament (defaults to 50.0 when unknown)
- Update `AttackCommandChooser.chosenAttackCommand` to use Scala `BattalionViewC`
  instead of proto `BattalionView`
- Update `MidGameAIClient` to pass battalions directly without proto conversion
- Remove `LegacyBattalionUtils` and proto `battalion_view_scala_proto` dependencies
- Update DEPROTO_PLAN.md: Phase 1 complete, CommandChoiceHelpers fully protoless

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add Scala overloads to BattalionNameFilter and BattleFilter

- Add Scala GameState overload to BattalionNameFilter using FactionUtils.provinces
- Add Scala overload to BattleFilter using FactionUtils.hostilityStatus
- Update GameStateViewFilter Scala overload to use the new Scala sub-filters
- Add shardok_battle visibility for view_filters package
- Update DEPROTO_PLAN.md to reflect completed work

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 09:26:25 -08:00
053ac4a622 Add Scala overloads to view filters (Phase 4 deproto) (#5016)
- Add Scala overloads to Visibility.scala for hasFullVisibility using
  Vector[FactionT] instead of proto GameState
- Add Scala overload to HeroViewFilter.filteredHeroView taking HeroT
  and ScalaGameState with proper type conversions
- Add Scala overload to FactionViewFilter.filteredFactionView taking
  FactionT and ScalaGameState
- Update GameStateViewFilter Scala overload to use Scala sub-filters
  where available (HeroViewFilter, FactionViewFilter)
- Update BUILD.bazel files for visibility and exports

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 09:04:17 -08:00
09041887c8 Fix ARM64 image push: use same repo with arm64- tag prefix (#5012)
DigitalOcean free tier limits to 5 repositories. Use the existing
shardok-server repository with arm64-prefixed tags instead of a
separate shardok-server-arm64 repository.

- shardok-server:latest (x86)
- shardok-server:arm64-latest (ARM64)

Also adds HETZNER_SETUP.md with infrastructure setup instructions.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 08:27:02 -08:00
58fd3dc112 Fix user database persistence in Docker (#5017)
The user database was being written to ~/eagle0/eagle/save/ but Docker
only mounted ./saves to /app/saves. This caused user data (including
displayName) to be lost on every container restart.

Add EAGLE_SAVE_DIR and EAGLE_ARCHIVE_DIR environment variables to
SaveDirectory, defaulting to the existing paths for local development.
Docker compose now sets these to /app/saves and /app/archived which
are properly mounted to persistent volumes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 08:26:15 -08:00
d62bb747dd Optimize GetGameHistory to not load entries when only count is needed (#5015)
When the admin panel requests game history with limit=0, it only needs
the total count for pagination. Previously this would load all entries
and serialize each one to JSON, causing timeouts on games with many
actions.

Now when limit <= 0, we return just the count with empty entries,
making the count request fast regardless of history size.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 07:04:16 -08:00
f8646c7b50 Fix game ID parsing in download handler (#5014)
The download handler was using ParseInt which fails for game IDs that
have the high bit set (appear as negative when formatted as signed).
The gameID is already parsed and validated in handleGameRoutes using
ParseUint, so just pass it through instead of re-parsing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-03 07:03:52 -08:00
affd0a8180 Add Scala GameState overload to GameStateViewFilter (#5010)
- Add `filteredGameState(gs: ScalaGameState, factionId: Option[FactionId])`
  overload that converts internally for now (sub-filters still need proto)
- Update HumanPlayerClientConnectionState to pass Scala GameState directly,
  removing 3 wasteful toProto conversions at call sites
- Add visibility for view_filters to access GameStateConverter
- Export Scala GameState from game_state_view_filter target
- Update DEPROTO_PLAN.md to reflect Phase 4 progress

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 22:32:23 -08:00
a92a878465 Switch ARM64 Shardok image to DigitalOcean Container Registry (#5009)
Use DigitalOcean registry for ARM64 images instead of GitHub Container
Registry for consistency with all other images (Eagle, Shardok x86,
admin, auth, jfr-sidecar).

- Update ci/BUILD.bazel: shardok_server_push_arm64 → registry.digitalocean.com
- Update shardok_arm64_build.yml: use DO_REGISTRY_TOKEN auth
- Update docs to reflect the registry change

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 22:25:17 -08:00
10696325e9 Return new JWT from SetDisplayName with updated displayName claim (#5008)
When a user sets their display name, the current JWT still has the old
(blank) displayName. This caused games to be created with blank usernames.

Fix: SetDisplayName now returns a new access token with the updated
displayName claim. The client stores this new token so subsequent requests
(like joining games) use the correct displayName.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 22:20:00 -08:00
88273937da Add TLS and token authentication to Shardok server (#5001)
* Add TLS and token authentication support to Shardok server

Enables secure communication between Eagle and remote Shardok instances:

- TLS support: Read SSL cert/key from config paths, create SslServerCredentials
- Token auth: Validate "Authorization: Bearer <token>" header on all RPCs
- Config: Added authTokenPath to ServerConfiguration
- TokenValidator class reads token from file and validates requests
- Graceful fallback: If TLS not configured, uses insecure credentials

Configuration options (via eagle0.conf or environment):
- sslCertPath: Path to TLS certificate (e.g., Let's Encrypt fullchain.pem)
- sslPrivateKeyPath: Path to TLS private key
- authTokenPath: Path to file containing the auth token

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Update implementation plan to mark completed tasks

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add TLS and token authentication support to Eagle's Shardok client

Add ShardokSecurityConfig to configure TLS and auth token for connecting
to remote Shardok instances. When useTls is enabled, uses system trust
store for Let's Encrypt certificates. When authToken is set, adds Bearer
token to all gRPC requests via BearerTokenInterceptor.

This enables Eagle to connect securely to Shardok instances running on
Hetzner Cloud with Let's Encrypt TLS and token-based authentication.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 22:12:31 -08:00
e472ab4df2 Add ShardokInstanceManager for on-demand compute lifecycle (#4998)
Manages the lifecycle of Shardok instances on Hetzner Cloud:
- Activity-based spin-up when players connect
- Automatic shutdown after idle timeout (default 60 minutes)
- State machine tracking: Stopped -> Starting -> Ready -> InUse
- Cloud-init script generation for Docker container setup
- Health checking during startup

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 22:10:05 -08:00
11110a5f88 Client connects directly to Go auth service for OAuth (#4982)
Phase 2 of OAuth extraction: Unity client now routes OAuth RPCs
(GetOAuthUrl, CheckOAuthStatus, RefreshToken) directly to the Go
auth service on port 40033, while user RPCs (SetDisplayName,
GetCurrentUser, Logout) continue to go to Eagle.

Changes:
- AuthClient: Use separate gRPC channels for auth service and Eagle
- OAuthManager: Accept both authServiceUrl and eagleUrl parameters
- ConnectionHandler: Pass both URLs when configuring OAuthManager

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 22:06:42 -08:00
d125394028 Fix action history pagination to avoid loading all results (#5005)
Previously, getGameHistory loaded all action results with history.all
then paginated in-memory. For games with many actions, this caused
timeouts.

Now uses history.since(startIndex).take(limit) which efficiently loads
only the save files containing the requested range. The since() method
in PersistedHistory already calculates which partial game files to read.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 22:06:06 -08:00
99037c7c3a Make AttackCommandChooser fully protoless (#5007)
* Eliminate GameState toProto() conversion in LLM pipeline

Phase 1 of deproto optimization: Make LlmRequestWithGameState use Scala
GameState instead of proto GameState, eliminating wasteful round-trip
conversion in UnrequestedTextHandler (the heaviest proto conversion in profiles).

Changes:
- LlmResolver: Change LlmRequestWithGameState.gameState to Scala GameState
- UnrequestedTextHandler: Remove GameStateConverter.toProto() calls, pass
  gameHistory.stateAfter() directly
- Update all prompt generators (~38 files) to use Scala model types:
  - FactionT instead of proto Faction
  - HeroT instead of proto Hero
  - ProvinceT instead of proto Province
  - Scala enums (Gender.Male, Profession.Mage) instead of proto enums
- DivineMessagePromptGenerator: Rewrite quest pattern matching to use
  Scala QuestC types instead of proto quest types
- ChronicleUpdatePromptGenerator: Inline province lookup, remove
  LegacyFactionUtils dependency
- BattalionDescriptions: Add Scala BattalionT and BattalionTypeId overloads
- Update test files to use concrete Scala types (HeroC, FactionC, ProvinceC)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Make AttackCommandChooser fully protoless

- Add `estimatedPower(BattalionViewC)` to `BattalionPower` for handling recon
  data with optional training/armament (defaults to 50.0 when unknown)
- Update `AttackCommandChooser.chosenAttackCommand` to use Scala `BattalionViewC`
  instead of proto `BattalionView`
- Update `MidGameAIClient` to pass battalions directly without proto conversion
- Remove `LegacyBattalionUtils` and proto `battalion_view_scala_proto` dependencies
- Update DEPROTO_PLAN.md: Phase 1 complete, CommandChoiceHelpers fully protoless

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 22:05:22 -08:00
c60d4b80f2 Proxy game save downloads through gRPC for container environments (#5006)
Admin server and Eagle run in separate containers in production, so the
admin server cannot directly access Eagle's save directory. Added a streaming
gRPC endpoint DownloadGameSave that zips and streams the save directory,
with the admin server proxying the download through this endpoint.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 20:50:52 -08:00
041514bd02 Fix JWT claims to match Eagle's expected format (#5002)
* Fix JWT claims to match Eagle's expected format

Go auth service was using custom claim names (userId, displayName, isAdmin)
but Eagle's JwtServiceImpl expects standard claims:
- sub (Subject) for userId
- name for displayName
- admin for isAdmin

This fixes "User not found" error when client calls SetDisplayName after
OAuth login, because Eagle couldn't extract the userId from the JWT.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix jwt_test.go to use updated claim field names

Update tests to use Subject instead of UserID and Name instead of
DisplayName, matching the changes to EagleClaims and RefreshClaims.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 20:19:52 -08:00
c410f790ff Add game download/upload feature to admin panel (#5004)
- Add ImportGame RPC to eagle.proto for registering uploaded games
- Implement importGame in GamesManager to load saves from disk
- Add download handler: zips game save folder and serves as download
- Add upload handler: accepts zip, extracts, calls gRPC to register
- Add "Download Save" button to game detail page
- Add upload form (collapsible) to games list page

Uploaded games start with all AI players; admin can assign humans
using existing player management features.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 20:18:52 -08:00
b4d19e7b65 Remove MainQueue backlog debug logging (#5003)
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 20:14:31 -08:00
9e8169df3e Remove dead proto code from CommandChoiceHelpers and related files (#4995)
Production code:
- Remove LegacyCommandChooser trait and all legacy methods from CommandChooser.scala
- Remove all proto overloads from CommandChoiceHelpers.scala (~1100 lines removed)
- Remove proto imports and converter dependencies
- Rename chosenFulfillEasyQuestsCommandProtoless to chosenFulfillEasyQuestsCommand
- Update MidGameAIClient to use renamed method
- Remove unused CommandChooserImplicits import from AIClient

Test code:
- Update CommandChoiceHelpersTest to use Scala model types
- Update FulfillQuestsCommandSelectorTest to use Scala model types
- Update PerformVassalCommandsPhaseActionTest to use Scala model types

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 16:20:05 -08:00
f92f400f28 Route OAuth callback to Go auth service (#5000)
The /oauth/callback endpoint should proxy to auth:8080 (Go auth service)
not eagle:8080. This fixes 502 errors during OAuth flow.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 16:18:38 -08:00
28d7da9634 Use SERVER_BASE_URL for OAuth callback URL (#4999)
The Go auth service now constructs the OAuth callback URL from
SERVER_BASE_URL env var (e.g., https://prod.eagle0.net/oauth/callback),
matching the Scala implementation. This fixes "Invalid OAuth2 redirect_uri"
errors from Discord.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 16:08:47 -08:00
79aac7c9ce Add Hetzner Cloud API client for on-demand Shardok instances (#4996)
Implements a Scala client for the Hetzner Cloud API to manage
on-demand Shardok instances for tactical combat. Features:

- Create/delete servers with cloud-init user data
- Get server status and list servers by label
- Power on/off and graceful shutdown operations
- Async execution with Futures
- Proper error handling for API errors

Also updates the plan doc to track ARM64 build completion.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 16:01:58 -08:00
a530a219f1 Deploy JWT_PRIVATE_KEY via auth CI/CD pipeline (#4997)
Add JWT_PRIVATE_KEY to auth_build.yml deploy job so the auth service
can bootstrap its RSA keys from the JWK secret. This ensures the
JWT key is properly deployed without manual server intervention.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 15:59:36 -08:00
335baf96dc Fix JWK base64 decoding to handle multiple formats (#4994)
The nimbus-jose-jwt library may output standard base64 (with +/)
instead of base64url (with -_). Try multiple decode strategies:
1. base64url without padding (JWK spec)
2. base64url with padding
3. standard base64 without padding
4. standard base64 with padding

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 15:14:41 -08:00
584ccbadcb Add ARM64 Linux build infrastructure for Shardok (#4990)
* Add ARM64 Linux build infrastructure for Shardok

Infrastructure to support cross-compiling Shardok for ARM64 Linux,
enabling deployment to Hetzner ARM instances (CAX41) for on-demand
compute.

Changes:
- Add linux_arm64 platform definition
- Add LLVM toolchain for ARM64 cross-compilation
- Add ARM64 sysroot placeholder (needs workflow run to populate)
- Add ARM64 busybox for container health checks
- Add Ubuntu 24.04 ARM64 base image
- Add Shardok ARM64 container image targets
- Update sysroot build workflow to support ARM64

Next steps:
1. Run "Build Linux Sysroot" workflow with architecture=arm64
2. Update MODULE.bazel with generated sysroot SHA
3. Build and push ARM64 container

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Update ARM64 sysroot SHA from workflow build

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix ARM64 container build issues

- Use linux/arm64/v8 platform string (rules_oci requires variant suffix)
- Remove busybox_layer_arm64 due to busybox.net SSL certificate issues
- Health checks can be added later using an alternative busybox source

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add GitHub Actions workflow for ARM64 Shardok build

Builds and pushes ARM64 container image to GitHub Container Registry
for deployment on Hetzner ARM instances (CAX41).

Triggered on:
- Push to main (when Shardok-related files change)
- Manual workflow_dispatch

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 15:08:51 -08:00
06f6ba8340 Fix auth port conflict with nginx (#4993)
Remove direct port 40033 binding from auth service since nginx
now proxies this port (PR #4987). Both can't bind to the same
host port.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 11:57:02 -08:00
bfe5befff2 Auth service bootstraps JWT keys from JWK format (#4992)
- Add bootstrapKeysFromJWK() to convert JWK to PEM files on first run
- Uses only Go stdlib (no third-party JWK libraries)
- Pass JWT_PRIVATE_KEY env var to auth service in docker-compose
- PEM files persist in jwt-keys volume after first bootstrap

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 11:47:56 -08:00
521dde9503 Deproto: migrate AI files to protoless-only (#4991)
- Remove proto GameState overloads from 8 AI files, keeping only Scala model versions
- Update all AI tests to use Scala model types (GameState, FactionC, ProvinceC, HeroC)
- Clean up BUILD.bazel deps to remove proto dependencies
- Net reduction: -489 lines of code

Files converted:
- AIClientUtils.scala
- EarlyGameAIClient.scala
- FactionLeaderProvinceRanker.scala
- FixLeaderAloneCommandSelector.scala
- InvitationCommandSelector.scala
- MoveLeaderToBetterProvinceCommandChooser.scala
- ResolveDiplomacyCommandSelector.scala
- All corresponding test files

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 11:37:36 -08:00
85eccb97f0 Add Shardok on-demand compute infrastructure documentation (#4989)
Documents the architecture for running Shardok on Hetzner ARM instances
with on-demand spin-up based on player activity:

- Hetzner CAX41 (16 ARM cores) in Ashburn at ~$0.04/hr
- Activity-based spin-up: start when players connect, stop after 1hr idle
- TLS + token authentication (Let's Encrypt for certs, auto-renewed)
- Estimated cost: $2-7/month vs $20-40/month for equivalent always-on

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 11:12:07 -08:00
e270d27a4a Deproto MidGameAIClient: complete protoless migration including test (#4981)
* Deproto MidGameAIClient: flip main entry point to protoless

Completes the deproto migration of MidGameAIClient by:
- Adding protoless chosenMidGameStrategicCommand
- Flipping the main entry point so proto delegates to protoless
- Adding protoless maybeMoveToRecruitCommand to CommandChoiceHelpers
- Adding protoless chosenFulfillEasyQuestsCommandProtoless
- Adding FactionUtils.neutralNeighbors helper
- Fixing test GameState constructors to include currentPhase

The proto versions now delegate to protoless versions via
GameStateConverter.fromProto(), eliminating proto usage in the
main command selection logic.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Remove proto deps from MidGameAIClient and make test protoless

- Remove all protobuf dependencies from MidGameAIClient BUILD.bazel
- Delete legacy proto-based methods from MidGameAIClient.scala (now fully protoless)
- Convert MidGameAIClientTest to construct Scala GameState directly
- Add helper methods for creating test fixtures (makeGameState, makeFaction, etc.)
- Add visibility for battalion/concrete and state packages for test access

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 10:31:52 -08:00
d9893edcb1 Expose port 40033 for Go auth service in nginx (v2) (#4987)
Uses dynamic DNS resolution to avoid startup dependency on auth container.
Previous version failed because static upstreams resolve at nginx startup.

Changes:
- nginx.conf: Add server block on port 40033 with variable-based grpc_pass
- nginx.conf: Add /health endpoint on port 40033
- docker-compose: Expose 40033 on nginx container

Key fix: Using `set $auth_backend "auth:40033"; grpc_pass grpc://$auth_backend;`
instead of static upstream, so DNS resolution happens at request time
(cached by resolver for 10s) rather than at nginx startup.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 10:25:22 -08:00
adminandGitHub 5d4719ea19 Revert "Expose port 40033 for Go auth service in nginx (#4983)" (#4986)
This reverts commit e63a8489b6.
2026-01-02 08:43:41 -08:00
e63a8489b6 Expose port 40033 for Go auth service in nginx (#4983)
Adds nginx server block to listen on port 40033 and route gRPC
traffic to the Go auth service. This enables Phase 2 clients
to connect directly to the auth service.

Changes:
- nginx.conf: Add auth_grpc upstream and server block on port 40033
- docker-compose: Expose 40033 on nginx, add auth dependency

This is safe to deploy before Phase 2 clients - old clients still
use the Eagle proxy through port 443.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 08:24:59 -08:00
9b190254a4 Separate auth service into its own CI/CD workflow (#4985)
Auth service now has independent deployment lifecycle:
- Only triggers on authservice/** or auth proto changes
- Deploys only the auth container (no Eagle restart)
- Preserves in-memory OAuth state during Eagle deploys

docker_build.yml changes:
- Remove build-auth job
- Preserve existing AUTH_IMAGE in .env
- Only force-recreate eagle, shardok, admin, jfr-sidecar
- Auth container starts but isn't force-recreated

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 08:18:22 -08:00
eb2677bd84 Add auth service to CI/CD pipeline (#4984)
The deployment was failing because AUTH_IMAGE wasn't being built or
passed to the deploy script. This adds:

- build-auth job to build and push the Go auth service image
- AUTH_IMAGE to deploy job dependencies and env vars
- Auth image pulling in deploy script
- GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET env vars

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 08:11:50 -08:00
23d2cb3968 Extract OAuth to Go service (Phase 1) (#4980)
* Extract OAuth to Go service (Phase 1)

Move OAuth authentication handling from Eagle Scala server into a separate Go
service running in its own container. This simplifies Eagle, enables independent
deployment, and sets up for future JWT validation extraction.

Architecture:
- Go auth service handles OAuth flows, JWT creation, state management
- Eagle proxies Auth gRPC calls to Go service when configured
- Go service calls Eagle's InternalUserService for user persistence
- Shared JWT keys via volume mount

New files:
- src/main/go/net/eagle0/authservice/ - Go auth service
- auth_internal.proto - Internal gRPC for Go→Eagle communication
- InternalUserServiceImpl.scala - User service wrapper for internal gRPC
- ExternalAuthClient.scala - Client for forwarding to Go service

Backward compatible: Eagle runs in standalone mode without --auth-service-url

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add unit tests for Go auth service

- jwt_test.go: Tests for JWT token creation, validation, and refresh
- oauth_test.go: Tests for OAuth state management and status checking

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 07:32:02 -08:00
c66263cd56 Add protoless versions to 5 MidGameAIClient internal methods (#4979)
- Add protoless validateNoFactionLeaderAlone using FactionUtils
- Add protoless provincesWithFactionLeader using FactionUtils and ProvinceUtils
- Add protoless foodSurplus using ProvinceUtils.monthlyFoodSurplus
- Add protoless maybeChosenRaiseSupportCommand (removes fromProto calls)
- Add protoless chosenAttackCommandWithReconInfo using Scala BattalionView
- Proto versions now delegate to protoless versions via fromProto conversion
- Update BUILD.bazel visibility for BattalionViewConverter and BattalionView

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 06:42:27 -08:00
0ba3e0e5ae Fix missing dependency for SimpleTimedLogger in oauth_service (#4978)
Add simple_timed_logger dependency that was missing after adding
diagnostic logging in PR #4974.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 05:37:12 -08:00
860d0f3c5f Add protoless versions to MidGameAIClient relay supplies and recon commands (#4977)
- Add protoless maybeChosenRelaySuppliesCommand using FoodConsumptionUtils
  and ProvinceUtils instead of Legacy versions
- Add protoless selectedReconCommand and maybeChosenReconCommand using
  Scala Date extensions and FactionRelationshipC
- Update chosenMidGameCommand to use protoless versions via fromProto conversion
- Add required imports and BUILD.bazel dependencies

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 05:30:09 -08:00
13f79c37bc Add lobby status display and update OAuth documentation (#4976)
* Update OAUTH_NEXT_STEPS.md with current status and remaining work

- Mark completed items (headshots, logout, lobby display, etc.)
- Add new issues discovered (intermittent expired errors, token expiry bug)
- Reorganize implementation plan into Phase 2 (remaining) and Phase 3 (nice-to-haves)
- Update status of all known issues

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Wire up lobby UI elements in Unity scene

- Connect logout button
- Connect lobbyEnvironmentText and lobbyUserText fields

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add lobby environment and user display fields to ConnectionHandler

- Add lobbyEnvironmentText and lobbyUserText fields
- Add UpdateLobbyStatusDisplays() to populate them when entering lobby
- Shows OAuth DisplayName or classic login username

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 21:59:03 -08:00
87cd58f7a4 Add protoless maybeChosenTravelToRecruitCommand (#4975)
- Add protoless helper methods in CommandChoiceHelpers:
  - isInterestingUHC: uses Scala UnaffiliatedHeroT and RecruitmentInfo
  - hasInterestingUHC: uses Scala GameStateC
  - maybeChosenTravelToRecruitCommand: protoless overload
- Update MidGameAIClient to use protoless version via fromProto conversion
- Import RecruitmentInfo and UnaffiliatedHeroT for protoless checks

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 21:51:50 -08:00
e739e18d77 Add diagnostic logging to OAuth flow (#4974)
* Add diagnostic logging to OAuth flow for debugging expired errors

Adds detailed logging to trace OAuth state through the flow:
- getAuthUrl: logs state creation and map sizes
- checkStatus: logs non-pending results with map state
- handleCallback: logs entry, success, and error cases

This will help diagnose why clients sometimes get 'expired' errors
even when the OAuth callback succeeds on the server.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix expiresAt to return access token expiry instead of refresh token expiry

The CheckOAuthStatusResponse.expiresAt field was returning the refresh
token expiry (30 days) but clients interpret this as the access token
expiry (7 days). This fix calculates the correct access token expiry.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 21:48:39 -08:00
c03daf100c Add protoless version to MidGameAIClient.chosenMidGameCommand (#4973)
- Add protoless overload that takes native GameState
- Rename proto GameState import to GameStateProto for clarity
- Update AIClient to use protoless version directly
- Remove unused GameStateConverter import from AIClient
- Update BUILD.bazel dependencies

This continues the deproto migration by moving the toProto() conversion
from AIClient into MidGameAIClient, making the public API protoless.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 21:38:25 -08:00
6519850ec3 Add logout button to lobby for OAuth users (#4967)
Add a logoutButton field that can be wired in Unity, along with
OnLogoutClicked handler that:
- Clears OAuth tokens via OAuthManager.LogoutAsync()
- Disposes gRPC connection and HTTP client
- Returns to connection screen
- Re-shows appropriate auth panel

This allows OAuth users who are auto-logged in to return to the
connection screen to use a different account or auth method.

Note: The button still needs to be added in Unity and wired to
the logoutButton field.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 21:37:01 -08:00
df785f557b Eliminate toProto() call in AIClient.chooseCommand (#4972)
- Change chooseFrom to accept Scala GameState instead of proto
- Use protoless CommandChooser with protoless helper methods
- Update chooseMidGameCommandFrom to accept Scala GameState
- Move toProto() conversion to MidGameAIClient call only (mid-game path)
- Use protoless EarlyGameAIClient methods (early game path)

This eliminates the unconditional toProto() conversion in chooseCommand,
now only converting when needed for MidGameAIClient which still uses proto.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 21:22:29 -08:00
224dc3bc13 Add protoless overloads to ResolveDiplomacyCommandSelector (#4970)
- Add protoless version of resolveDiplomacySelectedCommand using
  CommandChooser instead of LegacyCommandChooser
- Add protoless versions of all private helper methods that use
  Scala GameState and extract factions/provinces from it
- Rename proto GameState import to GameStateProto to disambiguate
- For methods that don't use gameState (ransom, break alliance),
  delegate to Core implementations to avoid code duplication

This enables callers to use Scala GameState directly without
conversion, preparing for elimination of toProto() call in
AIClient.chooseFrom.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 21:12:38 -08:00
5f3095dbd3 Fix NPE in SetUnitInfoLabels when grid not initialized (#4971)
Add null check for cells array in SetUnitInfoLabels, matching
the pattern used in other methods like ClearCellLabels.

This fixes a race condition where model updates arrive before
the hex grid is fully initialized on the first battle.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 21:11:59 -08:00
fb12810105 Use public CDN for headshot fetching (#4966)
Switch from server-mediated headshot fetching (eagle0.net with auth)
to direct CDN access (eagle0-headshots.sfo3.cdn.digitaloceanspaces.com).

- No auth required (bucket is public)
- No server-side changes needed
- Works identically for QA, prod, and local testing
- Removes coupling between headshot fetching and game server

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 21:11:33 -08:00
fe2a5b0869 Add protoless overloads for AI command selection helpers (#4969)
- Add protoless overloads for handleCapturedHeroesSelectedCommand,
  resolvePleaseRecruitMeSelectedCommand, and freeForAllDecisionSelectedCommand
- These methods don't actually use gameState, so the proto versions now
  delegate to core implementations that don't take gameState
- Simplify freeForAllDecisionSelectedCommand to not use CommandChooser
  since the inner methods don't use gameState

This prepares the groundwork for eliminating toProto() calls in AIClient.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 18:45:29 -08:00
3f00ba4a03 Eliminate toProto() calls in CommandChoiceHelpers protoless overloads (#4968)
- Add protoless overloads for helper methods:
  - maybeChosenFeastCommand, maybeChosenGiftCommand
  - maybeSpreadIntoOwnedProvince, maybeSpreadIntoEmptyProvince
  - maybeChosenGetUnderHeroCapCommand
  - maybeChosenAttackToSaveLeaderCommand
  - maybeRansomLeaderCommand, chosenRescueLeaderCommand

- Update protoless overloads to use native implementations:
  - chosenLoyaltyManagementCommand now uses CommandChooser directly
  - chosenRescueLeaderIfAllPrisonersCommand uses leaderIds and
    UnaffiliatedHeroType.Prisoner instead of proto equivalents

- Add quest dependency to BUILD.bazel (required for UnaffiliatedHeroT)

This eliminates all GameStateConverter.toProto() calls from
CommandChoiceHelpers.scala protoless overloads.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 18:32:21 -08:00
3dd06c0aba Fix JWT auth to set legacy userName for backwards compatibility (#4964)
* Fix JWT auth to set legacy userName for backwards compatibility

When using JWT authentication, contextWithJwtClaims was not setting
the legacy userNameCtxKey, causing AuthorizationUtils.userName to
return null. This broke game management code that relies on userName
for mapping users to factions.

Fix by also setting userNameCtxKey to displayName when using JWT auth,
ensuring backwards compatibility with existing game management code.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add OAuth implementation next steps and design doc

Comprehensive design document covering:
- Known issues (identity fragility, headshots, logout, uniqueness)
- Proposed user identity model with userId as stable key
- Multi-provider account linking strategy
- Avatar/headshot strategy
- Phased implementation plan
- Technical debt and open questions

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Update OAuth design doc with headshot investigation

- Clarify that headshots are AI-generated character portraits, not user avatars
- Document headshot architecture: client → eagle0.net (home Mac) → S3 signed URL
- Explain why OAuth breaks headshots: eagle0.net nginx only validates Basic Auth
- Clarify PR #4964 is required now (fixes admin server NPE crash)
- Phase 2 migration to userId-based identity deferred

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 17:45:12 -08:00
d95f65d9b4 Add protoless overloads to CommandChoiceHelpers travel commands (#4965)
- Add protoless chosenBuyFoodCommand using protoless foodAmountToBuy
- Add protoless maybeChosenDivineCommand using HeroUtils.power
- Add protoless maybeChosenArmTroopsCommand using ProvinceUtils
- Add protoless maybeChosenRecruitCommand and chosenReturnCommand (impl helpers)
- Convert chosenCommandWhileTraveling to native protoless implementation
  using CommandChooser with protoless choosers

This eliminates wasteful GameStateConverter.toProto() conversions when
EarlyGameAIClient calls chosenCommandWhileTraveling with Scala GameState.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 16:24:08 -08:00
a7c1146c41 Add protoless overloads to EarlyGameAIClient (#4963)
- Add protoless isEarlyGame(GameState, FactionId) using FactionUtils and ProvinceUtils
- Add protoless chooseEarlyGameCommand using CommandChooser with protoless choosers
- Update BUILD.bazel with required deps (FactionUtils, ProvinceUtils, GameState)
- Add exports for GameState to support downstream callers

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 16:05:11 -08:00
56a5c27d42 Add protoless overloads to HeroUtils (#4961)
- Add faction(hero, factions) method
- Add loyaltyAsStatWithCondition(hero, factions) method
- Add vigorAsStatWithCondition(hero) method
- Add consideredProvinces(gameState, factionId, provinceId) method

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 15:29:43 -08:00
1d707ba5f0 Fix gRPC context propagation in AuthServiceImpl (#4960)
The userId was being read inside the Future block, which runs on a
thread from ExecutionContext.global. However, gRPC Context.current
returns the context for the current thread, not the gRPC handler
thread where the JWT claims were attached.

This caused setDisplayName and getCurrentUser to always get null/empty
userId, resulting in "User not found" errors after successful OAuth.

Fix by capturing userId before creating the Future, on the gRPC thread
where Context.current has the proper claims attached. This matches
the pattern used in EagleServiceImpl.lockAndDoWithUserName.

Also update AuthorizationInterceptor publicEndpoints to use
CheckOAuthStatus instead of the old ExchangeCode method name.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 15:19:41 -08:00
e4f3df7e26 Add protoless overloads to ArmyUtils (#4959)
- Add protoless overloads for heroCount and troopCount methods
- Protoless versions take Map[BattalionId, BattalionT] instead of GameState

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 15:19:13 -08:00
d68302d2b5 Implement client-side OAuth polling flow (#4945)
Client changes for server-mediated OAuth:
- AuthClient: Use PollForOAuthCompletionAsync instead of deep links
- OAuthManager: Remove deep link handling, use polling instead

The client now:
1. Calls GetOAuthUrl to get browser URL and state token
2. Opens browser for user to authorize
3. Polls CheckOAuthStatus every 2s until success/failure/timeout

Works in Unity Editor and all platforms without URL scheme registration.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 15:06:03 -08:00
4a7559c25d Add protoless overloads to IncomingArmyUtils and FactionUtils (#4958)
- Add factionsAreMutuallyAllied and hostilityStatus to FactionUtils
- Add protoless overloads to IncomingArmyUtils:
  - hasRelevantIncomingArmy
  - relevantIncomingArmies
  - incomingArmiesAreMutuallyAllied
  - isHostileProvince
  - stats

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 15:03:54 -08:00
1eb253d866 Add protoless versions to AIClientUtils and ResolveDiplomacyCommandSelector (#4957)
- Add protoless extraHeroCount and desiredHeroCount to AIClientUtils
- Add protoless truceOfferAcceptanceChance to ResolveDiplomacyCommandSelector
- Add protoless allianceOfferAcceptanceChance to ResolveDiplomacyCommandSelector

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 14:50:00 -08:00
c770a3693b Deploy: Write image tags to .env file (#4956)
Previously image tags were only passed via ssh-action envs, which meant
manual docker-compose restarts would fall back to :latest. Now the SHA-tagged
image names are persisted in .env.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 14:49:40 -08:00
99ad9fb49e Add protoless versions to AI command selectors (#4955)
- Add protoless overloads to FixLeaderAloneCommandSelector
- Add protoless overloads to InvitationCommandSelector
- Add protoless overloads to MoveLeaderToBetterProvinceCommandChooser
- Add protoless overloads to FactionLeaderProvinceRanker
- Add hostileNeighbors helper to FactionUtils for protoless use

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 14:26:29 -08:00
d80a151303 Nginx: Add routes for Auth gRPC service and OAuth callback (#4954)
- Add location block for /net.eagle0.eagle.api.auth.Auth gRPC service
- Add location block for /oauth/callback HTTP endpoint

These routes are required for OAuth login to work.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 12:24:17 -08:00
b9f48e14be Add protoless versions for chosenExpandCommand and chosenEntrustCommand (#4953)
Convert protoless overloads to use Vector[CommandChooser] directly instead
of delegating to legacy implementations with proto conversion.

Changes:
- chosenExpandCommand: now uses Scala GameState directly
- chosenEntrustCommand: now uses Scala GameState directly
- Added protoless overload for chosenMobilizeIfAdjacentEnemyCommand

This completes the protoless conversion for all main command chooser
entry points (chosenUniversalCommand, chosenDevelopCommand,
chosenMobilizeCommand, chosenExpandCommand, chosenEntrustCommand).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 08:20:20 -08:00
32c62357eb Add protoless versions for chosenDevelopCommand and chosenMobilizeCommand (#4952)
Convert protoless overloads to use Vector[CommandChooser] directly instead
of delegating to legacy implementations with proto conversion.

Changes:
- chosenDevelopCommand: now uses Scala GameState directly
- chosenMobilizeCommand: now uses Scala GameState directly
- Added protoless overloads for helper methods:
  - excessBeyondMaximumSupplies
  - chosenShipExcessSuppliesCommand
  - chosenImproveInfrastructureIfBelowTrainingCommand
  - maybeChosenTravelToArmTroopsCommand
  - chosenTrainCommand
  - suppliesToSend
  - preferredSuppliesDestination
  - chosenSendSuppliesCommandWithSuppliesAndDestination
  - chosenSendSuppliesCommandWithSupplies
  - maybeChosenSendSuppliesCommand

This eliminates Scala→proto→Scala conversion roundtrips for callers
that already have a Scala GameState.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 08:08:20 -08:00
a4bf652bf7 Add protoless chosenUniversalCommand using Scala GameState directly (#4951)
- Convert protoless chosenUniversalCommand overload to use Vector[CommandChooser]
  directly instead of delegating to legacy implementation with proto conversion
- Add protoless overloads for nested chooser methods:
  - chosenCommandWhileTraveling
  - chosenLoyaltyManagementCommand
  - chosenRescueLeaderIfAllPrisonersCommand
- Fix ambiguous method reference in EarlyGameAIClient by using explicit lambda

This eliminates the Scala→proto→Scala conversion roundtrip for callers
that already have a Scala GameState.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 06:53:14 -08:00
31458c2a98 Deploy: Pass Discord OAuth credentials to Eagle container (#4950)
Adds DISCORD_CLIENT_ID and DISCORD_CLIENT_SECRET to deploy config,
enabling Discord OAuth login in production.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 06:52:38 -08:00
dabf309e6d Deploy: Pass JWT_PRIVATE_KEY to Eagle container (#4949)
Enables OAuth JWT authentication in production by:
- Adding JWT_PRIVATE_KEY secret to deploy workflow env
- Passing it through SSH to the droplet .env file
- Configuring docker-compose to pass it to the Eagle container

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 00:21:53 -08:00
f3bcf44cb3 Add protoless overloads to CommandChoiceHelpers main entry points (#4948)
- Add protoless overloads for chosenUniversalCommand, chosenDevelopCommand,
  chosenMobilizeCommand, chosenExpandCommand, chosenEntrustCommand
- Add protoless helpers: foodAmountToBuy, maybeChosenTravelToBuyFoodCommand,
  chosenShouldRestCommand, chosenSuppressBeastsCommand, and beast-fighting
  command helpers
- Add protoless isUnderAttack overload to IncomingArmyUtils
- Convert PerformVassalCommandsPhaseAction to use protoless overloads,
  eliminating GameStateConverter.toProto() call
- Fix ambiguous method references in EarlyGameAIClient and MidGameAIClient
  by using explicit lambdas

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 00:19:59 -08:00
6f486cbd32 Trigger deploy when docker-compose.prod.yml or nginx config changes (#4947)
Previously, changes to these files wouldn't trigger a deploy since they
weren't in the paths filter. The deploy step already copies these files
to the droplet, it just wasn't being triggered.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 20:39:44 -08:00
bb07a90c0d Add protoless overloads to CommandChoiceHelpers and update callers (#4946)
* Add protoless overloads for CommandChoiceHelpers entry points

Add Scala GameState (GameStateC) accepting overloads for these methods:
- handleRiotGiveSelectedCommand
- handleRiotCrackDownSelectedCommand
- handleRiotDoNothingSelectedCommand
- handleRiotSelectedCommand
- resolveTributeSelectedCommand
- defendSelectedCommand
- defendingUnits
- chosenRestCommand

The proto-accepting versions now delegate to the Scala versions,
allowing callers to switch to passing Scala GameState directly
and eliminate unnecessary proto conversions.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Eliminate proto GameState conversions in action files

Update EndHandleRiotsPhaseAction and PerformVassalDefenseDecisionsAction
to call the new protoless overloads in CommandChoiceHelpers directly,
eliminating unnecessary GameStateConverter.toProto calls.

This removes the following wasteful round-trip conversions:
- EndHandleRiotsPhaseAction: handleRiotSelectedCommand call
- PerformVassalDefenseDecisionsAction: resolveTributeSelectedCommand
  and defendSelectedCommand calls

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 20:37:45 -08:00
30c3093829 Implement server-side OAuth polling flow (#4944)
Server changes for server-mediated OAuth:
- OAuthService: Store pending/completed sessions by state, handle callbacks
- AuthServiceImpl: Implement checkOAuthStatus gRPC method
- OAuthHttpHandler: New HTTP server for /oauth/callback endpoint
- Main: Start OAuth HTTP handler on configurable port (default 8080)

New command line options:
- --server-base-url: Base URL for OAuth callbacks (default: https://prod.eagle0.net)
- --oauth-http-port: Port for OAuth HTTP server (default: 8080)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 16:34:12 -08:00
d723a7e026 Add protoless CommandChooser with legacy compatibility layer (#4941)
- Convert CommandChooser trait to use Scala GameState (protoless)
- Add LegacyCommandChooser trait for callers still using proto GameState
- Add legacy implicit conversions (LegacyDeterministicCommandChooser, LegacyRandomCommandChooser)
- Convert AttackDecisionCommandChooser to fully protoless
- Add Scala overload for IncomingArmyUtils.armyPower
- Update all callers to use LegacyCommandChooser where proto GameState is used:
  - CommandChoiceHelpers, MidGameAIClient, AIClient, EarlyGameAIClient, ResolveDiplomacyCommandSelector

This establishes a migration path where new code uses CommandChooser with Scala
GameState while legacy code uses LegacyCommandChooser with proto GameState.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 16:32:35 -08:00
7c8453b6c0 Add CheckOAuthStatus RPC for server-mediated OAuth polling (#4943)
Replace client-side deep link OAuth with server-mediated polling:
- Add CheckOAuthStatus RPC and OAuthStatus enum
- Remove ExchangeCode RPC (server handles callback internally)
- Remove redirect_uri from GetOAuthUrlRequest (server uses its own)

Flow: Client opens browser → user authorizes → server receives callback →
client polls CheckOAuthStatus until success/failure.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 16:21:05 -08:00
7e87ca792e Add memory limit to Shardok container (#4942)
Set 1GB hard limit so Shardok can't OOM the entire droplet.
If exceeded, Docker kills just that container and it restarts
automatically (restart: unless-stopped).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 16:20:24 -08:00
89db5be805 Add OAuth relay worker and infrastructure (#4939)
* Add Cloudflare Worker for OAuth callback relay

Discord doesn't support custom URL schemes (eagle0://) as redirect URIs.
This worker receives the OAuth callback and redirects to the deep link.

- Worker deployed at eagle0-oauth-relay.eagle0-auth-relay.workers.dev
- GitHub Actions workflow for auto-deploy on push to main

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add GenerateJwtKey utility for generating JWT signing keys

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 15:25:10 -08:00
ec64146ca7 Add GrpcServices="Client" to auth.proto in protos.csproj (#4936)
This generates the Auth gRPC client stubs needed by the Unity OAuth
client to call GetOAuthUrl, ExchangeCode, RefreshToken, etc.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 15:10:58 -08:00
9e8f9cef0e Reduce Eagle JVM heap from 4GB to 2GB (#4938)
The 4GB droplet was running OOM because the JVM was configured to use
all 4GB, leaving nothing for the OS, Shardok, nginx, or Docker.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 14:54:34 -08:00
9999f4b1b3 Prevent duplicate headshot fetch requests with in-flight tracking (#4937)
ResourceFetcher was triggering multiple parallel HTTP requests for the same
headshot when LoadIntoRawImage or Prefetch were called before a prior fetch
completed. This occurred because there was no tracking of in-flight requests.

Add _inFlightPaths HashSet to track paths currently being fetched. FetchRemote
now checks this set before starting a fetch and returns early if the path is
already being fetched. The existing fetch will process the _imageLoadQueue
when it completes. Prefetch also checks _inFlightPaths to avoid redundant work.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 14:43:20 -08:00
85241710c9 Skip saveNow for Shardok-only updates (#4935)
When receiving battle updates from Shardok, we were calling
copyWithAtomicSave which re-serializes all Eagle recentHistory,
even though no Eagle results changed. Shardok results are already
saved in withNewShardokResults.

This was showing as ~11% of CPU time in saveNow during battles.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 11:27:41 -08:00
232ad643e5 Reduce save batch size from 200 to 25 to reduce serialization overhead (#4934)
Each call to saveNow re-serializes all results in the current batch.
With batch size 200, this means 1+2+3+...+200 = 20,100 serializations
per 200 results. Reducing to 25 gives 8 batches × 325 = 2,600
serializations, an 8x improvement.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 11:13:13 -08:00
55f16d1d6c Fix column swaps in 9239 generated heroes (#4930)
The hero generation pipeline (commit 836c975a9) output columns in a different
order than the file header. When the data was reformatted, two column pairs
were swapped:

1. wisdom ↔ charisma (columns 11 & 12)
2. vigor ↔ bravery (columns 14 & 18)

This fix swaps these columns back for all heroes added after line 1746.
Verified by checking backstories match stats (e.g., "brilliant theoretical
work" now correctly corresponds to high wisdom).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 09:43:11 -08:00
42bdd42361 Reduce profession gain chance from 10% to 7% (#4932)
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 09:30:07 -08:00
b5ad57053a Limit AI time budget for all-AI battles (#4931)
When a battle has only AI players (no humans), use the faster time budget
limit (allAiBattleTimeBudgetMaximum = 0.5s) instead of the normal limit
(lookaheadTimeBudgetMaximumSeconds = 3s). This makes all-AI battles run
faster since there's no human waiting.

The isAllAiBattle flag is computed once at battle start in MakeAIClients()
and passed to each ShardokAIClient, which uses it when calculating time
budgets.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 09:26:20 -08:00
939cb49c91 Add game state viewing to admin server (#4929)
- Add GetGameStateAtAction RPC to fetch full game state as JSON at any action index
- Add "State" button to history table rows for on-demand state viewing
- Display game state in expandable panel with close button
- Fix table layout with white-space: nowrap for button cells

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 08:27:05 -08:00
9ec79f904a Enable DebugNonSafepoints for accurate JFR profiling (#4925)
Without this flag, JFR can only get accurate stack traces at safepoints,
causing inlined methods to be invisible in profiles. This makes profiling
show time attributed to gRPC infrastructure instead of actual application
code.

The flag adds metadata during JIT compilation but has no runtime overhead.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 07:26:37 -08:00
ddea05514c Add action JSON and build info to admin server (#4927)
- Add action_json, faction_name, and game_date fields to GameHistoryEntry proto
- Serialize ActionResult to JSON in EagleServiceImpl.getGameHistory()
- Display faction name and date columns in history table
- Show full JSON inline when clicking action rows (no separate AJAX call)
- Add build timestamp and git commit to admin header on all pages
- Create workspace_status.sh for Bazel build stamping
- Enable --stamp in .bazelrc

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 07:18:45 -08:00
906da781d5 Fix final Shardok battle actions not being displayed to clients (#4926)
When a battle ended, the client would never see the final few actions
that caused the game to end (e.g., the killing blow). This was because
WaitForUpdatesAndPush() would return immediately after calling
OnGameOver() without first sending the pending updates.

The fix moves the update-sending code before the gameOver check,
ensuring all action results are streamed to clients before the
game over notification is sent.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 07:15:03 -08:00
db38c2a5b6 Add Unity OAuth client infrastructure (#4928)
* Add Unity OAuth client infrastructure

Client-side OAuth implementation for Unity:
- AuthClient: gRPC client for Auth service (GetOAuthUrl, ExchangeCode, RefreshToken, SetDisplayName)
- JwtAuthInterceptor: Adds JWT bearer token to gRPC requests
- OAuthManager: MonoBehaviour managing OAuth flow with system browser
- TokenStorage: Secure storage for access/refresh tokens using PlayerPrefs
- ConnectionHandler: OAuth panel with Google/Discord buttons, toggle to classic auth
- EagleConnection: Support for JWT-authenticated connections

The Auth gRPC service is already defined in auth.proto. Server will return
"unimplemented" until server-side OAuth is deployed, but legacy auth works
as fallback via the toggle button.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Default to Classic auth until server-side OAuth is ready

Toggle button now starts with "Use OAuth Sign-in" and shows the
legacy auth panel by default. Click to switch to OAuth view.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 07:12:18 -08:00
72e2f016e2 Add game rewind feature to admin server (Phase 3) (#4902)
* Add game rewind feature to admin server (Phase 3)

Implement the ability to rewind a game to a previous action count via the
admin web UI. This is useful for debugging, testing "what if" scenarios,
and recovering from bugs.

Changes:
- Add RewindGame RPC to eagle.proto with request/response messages
- Add truncateTo() method to GameHistory trait and implementations
- Add rewindTo() method to Engine trait and EngineImpl
- Add rewindTo() method to GameController (disconnects clients, resets AI)
- Add rewindGame() to GamesManager with validation
- Implement rewindGame RPC in EagleServiceImpl
- Add /games/{id}/rewind POST handler to admin server
- Add rewind button to each history row with confirmation dialog
- Add success/error feedback UI with alert styling
- Add tests for InMemoryHistory.truncateTo, EngineImpl.rewindTo, and
  GameController.rewindTo

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Resync connected clients on rewind instead of disconnecting them

- Add resyncAfterRewind() to HumanPlayerClientConnectionState that sends
  a starting_state with the rewound GameStateView and new action count
- Update GameController.rewindTo() to keep clients and send resync messages
- Rename proto field disconnected_clients -> resynced_clients
- Update admin server messages to reflect new behavior
- Unity client's HandleStartingState() handles the resync automatically

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-30 17:16:02 -08:00
fb2b0beb85 Clear stale state when handling StartingState for rewind/reset (#4924)
When receiving a StartingState from the server, clear all client state
that could be stale after a game rewind or reset:

- ShardokGameModels, _shardokResultCounts, _shardokNeedsResync
- CommandToken, LastPostedToken (reset to -1)
- AvailableCommandsByProvince
- _commandSubmittedTime

This fixes issues where rewinding the game caused token validation
failures or displayed stale battle/command state.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-30 17:12:18 -08:00
e1fb2391ef Update DEPROTO_PLAN.md with completed work and next steps (#4920)
- Document GameState round-trip elimination (PRs #4913, #4914, #4915)
- Add detailed next steps for CommandChoiceHelpers migration
- Outline phases for CommandChooser trait and MidGameAIClient

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-30 16:58:46 -08:00
8486ae2420 Show environment indicator (prod/qa) in connection status area (#4922)
* Show environment indicator (prod/qa) in connection status area

Adds a text field that displays the connected environment name with
color coding: green for prod, yellow for qa. The indicator appears
after connecting and clears when the connection is disposed.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Move environment indicator to Eagle game view ConnectionStatusUI

Instead of showing the environment on the Connection panel, show it
in the Eagle game view next to the connection status indicator.

- Add environmentIndicatorText field to ConnectionStatusUI
- Pass environment name from ConnectionHandler to EagleGameController
- Display "prod." in green or "qa." in yellow

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Wire up environment indicator text in Unity

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-30 16:58:26 -08:00
f1a5b2962d Fix battalion type comparison in QuestEndedGeneratorUtilities (#4923)
The UpgradeBattalionQuest case was comparing a proto BattalionTypeId
(from net.eagle0.eagle.common.battalion_type.BattalionTypeId) with
a model BattalionTypeId (from net.eagle0.eagle.model.state.BattalionTypeId).
These are different types that never match, causing .find() to return None
and .get to throw NoSuchElementException.

This caused a production crash preventing users from reconnecting to
games with UpgradeBattalionQuest quests.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-30 16:54:57 -08:00
8a1904b8c8 Add dynamic JFR control to admin console (#4921)
- Add /status, /start, /stop endpoints to JFR sidecar for dynamic recording control
- Remove -XX:StartFlightRecording from Eagle - JFR is now started on demand
- Add JFR control handlers to admin server to proxy sidecar requests
- Update admin UI with status indicator and Start/Stop/Download buttons
- Download button only shown when recording is active

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-30 16:31:17 -08:00
4157863b3d Share /tmp volume between Eagle and jfr-sidecar for JVM attach (#4919)
JVM attach (used by jcmd) communicates via socket files in /tmp.
With shared PID namespace but separate filesystems, the sidecar
couldn't find Eagle's .java_pid1 socket file.

Add a shared named volume for /tmp between both containers.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-30 16:13:10 -08:00
6171fe258f Add JFR sidecar build and deploy to CI workflow (#4918)
PR #4917 added the jfr-sidecar image configuration but the CI workflow
wasn't building or pushing it, causing deploy to fail with "image not found".

- Add build-jfr-sidecar job to build and push the sidecar image
- Add JFR_SIDECAR_IMAGE to deploy job dependencies and env vars
- Add crane pull/load steps for jfr-sidecar in deploy script

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-30 16:00:33 -08:00
78fce1ba74 Add JFR dump download to admin console via sidecar (#4917)
Add a JFR sidecar container that shares PID namespace with Eagle to
enable JFR dumps without giving admin container Docker socket access.

Components:
- jfr_server: Minimal Go HTTP server that runs jcmd and serves JFR files
- Sidecar uses shared PID namespace (pid: "service:eagle") to see Eagle JVM
- Admin console proxies /jfr/download to sidecar
- UI button in nav bar triggers download

Security:
- Sidecar can only see Eagle's processes (no Docker socket)
- No host filesystem access
- Minimal attack surface

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-30 15:52:55 -08:00
d1eac2d7e0 Eliminate GameState toProto() conversion in LLM pipeline (#4913)
* Eliminate GameState toProto() conversion in LLM pipeline

Phase 1 of deproto optimization: Make LlmRequestWithGameState use Scala
GameState instead of proto GameState, eliminating wasteful round-trip
conversion in UnrequestedTextHandler (the heaviest proto conversion in profiles).

Changes:
- LlmResolver: Change LlmRequestWithGameState.gameState to Scala GameState
- UnrequestedTextHandler: Remove GameStateConverter.toProto() calls, pass
  gameHistory.stateAfter() directly
- Update all prompt generators (~38 files) to use Scala model types:
  - FactionT instead of proto Faction
  - HeroT instead of proto Hero
  - ProvinceT instead of proto Province
  - Scala enums (Gender.Male, Profession.Mage) instead of proto enums
- DivineMessagePromptGenerator: Rewrite quest pattern matching to use
  Scala QuestC types instead of proto quest types
- ChronicleUpdatePromptGenerator: Inline province lookup, remove
  LegacyFactionUtils dependency
- BattalionDescriptions: Add Scala BattalionT and BattalionTypeId overloads
- Update test files to use concrete Scala types (HeroC, FactionC, ProvinceC)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix UnrequestedTextHandlerTest to use Scala GameState

Update test to use Scala GameState instead of proto GameState for
LlmRequestWithGameState, matching the updated API. Also remove
deprecated Scala 3 trailing underscore syntax for function references.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-30 15:27:13 -08:00
1503c20b40 Simplify PostResults to use only Scala GameState (#4915)
* Preserve Scala GameState in PostResults to avoid round-trip conversion

Add optional scalaGameState field to PostResults that preserves the Scala
GameState when it's already available. This eliminates the pattern where
we convert Scala→proto (for PostResults) and then proto→Scala (in
synchronizedHandlePostResults).

Changes:
- PostResults: Add scalaGameState field
- GameController: Pass scalaGameState when creating PostResults
- GamesManager: Use scalaGameState in synchronizedHandlePostResults if available

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Simplify PostResults to use only Scala GameState

- Change PostResults.gameState from proto to Option[GameState] (Scala model)
- Remove redundant scalaGameState field since gameState is now the Scala type
- Update all PostResults creation sites to pass Some(scalaState) or None
- CustomBattleManager returns None since it has no Eagle game state
- Remove unused GameStateConverter import from GameController

This eliminates the need to maintain both proto and Scala GameState in
PostResults. The proto was only used as a fallback when scalaGameState
was None, but all callers now provide the Scala state directly.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-30 14:26:28 -08:00
470fdd7cd4 Add confirmation panel for drop game button (#4916)
* Add confirmation panel for drop game button

- Add DropGameConfirmationPanel component with confirm/cancel buttons
- Show confirmation before dropping a game
- Falls back to direct drop if no panel is configured

Note: Requires creating and wiring up the confirmation panel prefab in Unity.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Wire up drop game confirmation panel in Unity

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-30 14:11:52 -08:00
694f853408 Cache Scala GameState in ActionWithResultingState (#4914)
Add lazy val scalaGameState to ActionWithResultingState that either uses
a precomputed Scala state or lazily converts from proto.

Key optimizations:
- When results come from Scala-based actions via withNewResultsScala(),
  preserve the Scala GameState to avoid unnecessary proto->Scala conversion
- When loaded from disk/S3 (proto only), convert lazily on first access
- The lazy val ensures conversion happens at most once per instance

Files changed:
- ActionWithResultingState: Add precomputedScalaState parameter and lazy val
- GameHistory.withNewResultsScala: Pass Scala state to avoid re-conversion
- PersistedHistory: Use scalaGameState in stateAfter()
- InMemoryHistory: Use scalaGameState in stateAfter()

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-30 09:56:48 -08:00
5f251b5482 Re-enable hero info popup (#4912)
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-30 08:00:05 -08:00
24745ac466 Make S3 saves async with coalescing to avoid blocking main thread (#4911)
* Make S3 saves async to avoid blocking the main thread

S3/DO Spaces saves take 50-200ms per request, which was blocking the
main thread during game state persistence. This change wraps S3Persister
in an AsyncS3Persister that queues saves for background execution.

- Add AsyncS3Persister that uses a single-threaded executor per game
- LocalGamePersisterCreation now wraps S3Persister in AsyncS3Persister
- Register shutdown hook to flush pending S3 writes on graceful shutdown
- If shutdown is in progress, saves happen synchronously to ensure durability

This improves server responsiveness during game saves while maintaining
data safety through the shutdown flush mechanism.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Use coalescing pattern to always save latest version

Instead of queuing saves, use a ConcurrentHashMap keyed by filename.
New saves for the same key overwrite pending ones, ensuring we always
write the most recent data and preventing backlog buildup.

A scheduled task processes pending writes every 500ms. This batches
multiple saves together and ensures the latest version is always written.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-30 06:57:52 -08:00
35a0be4c71 Add admin player management feature (#4910)
- Add proto messages and RPCs: ConvertAiToHuman, ConvertHumanToAi, ReassignFaction
- Add GameController methods: promoteAiToHuman, demoteHumanToAi, reassignFaction
- Add GamesManager methods with validation and persistence
- Add EagleServiceImpl RPC handlers
- Add Go admin server HTTP handlers under /games/{id}/player-management/
- Add UI with players table, action buttons, and modals for username input

Features:
- Assign User: Convert AI faction to human control with username input
- Drop to AI: Convert human faction back to AI (triggers AI commands if turn)
- Reassign: Change which username controls a human faction

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-30 06:51:49 -08:00
d910a7d832 Only save LLM streaming text to disk on completion, not every token (#4909)
Previously, copyWithLlmSave was called on every streaming LLM token
(~50-100ms intervals), causing excessive disk I/O. Each save serialized
all incomplete texts to protobuf and wrote multiple files.

Now we only save when the stream completes. Worst case on crash: lose
one in-progress stream which can be regenerated.

This reduces I/O from receiveStreamingLlmResponses by ~95%.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-29 21:57:54 -08:00
853d703492 Handle OperationCanceledException in ResourceFetcher (#4908)
OperationCanceledException is the base class of TaskCanceledException.
YetAnotherHttpHandler can throw OperationCanceledException directly,
which was falling through to the generic Exception handler and being
logged as "unexpected error". Now we catch OperationCanceledException
which handles both types.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-29 21:53:03 -08:00
5f40464529 Switch Eagle server base image from JRE to JDK for JFR support (#4904)
* Switch Eagle server base image from JRE to JDK for JFR support

The previous eclipse-temurin image was a JRE which doesn't include jcmd.
This prevented dumping JFR recordings from a running server. Switch to
the 17-jdk tag which includes the full JDK with jcmd.

To dump JFR recording from running server:
  docker exec eagle-server jcmd 1 JFR.dump filename=/app/jfr/profile.jfr

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Update MODULE.bazel.lock for JDK image

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-29 21:50:36 -08:00
1d3b467b8c Turn off unavailable improvement type toggles (#4907)
When a toggle becomes unavailable (e.g., Devastation when there's no
devastation), explicitly set isOn=false so it doesn't appear selected.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-29 21:50:13 -08:00
38a22f30c4 Fix ImproveCommandSelector toggle wiring (#4906)
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-29 15:36:07 -08:00
93d2e7c323 Add drop game buttons to lobby UI (#4905)
* Add DropGame API for users to leave games

- Add DropGameRequest/Response proto messages to streaming API
- Add archived directory path in SaveDirectory for game preservation
- Add delete method to Persister trait and implementations
  - LocalFilePersister: delete local files
  - S3Persister: no-op (retain as backup)
  - CompoundPersister: delete from first (local) only
- Add dropUser() and remainingHumanCount to GameController
  - Reassigns dropped faction to AI with immediate takeover
- Add archiveGame() and dropGame() to GamesManager
  - Running games: archive if last human, otherwise AI takeover
  - Waiting games: remove user or entire game if empty
- Add DropGame handler to EagleServiceImpl streaming

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add deleteAll() to Persister and tests for dropGame

- Add deleteAll() method to Persister trait and implementations
  - LocalFilePersister: deletes all files and the directory
  - S3Persister: no-op (retain as backup)
  - CompoundPersister: delegates to first persister
- Refactor archiveGame to use deleteAll() instead of java.io.File
- Add unit tests for dropGame functionality:
  - Removes entire waiting game when only player drops
  - Removes only user when other players remain
  - Returns USER_NOT_IN_GAME when user not in waiting game
  - Returns GAME_NOT_FOUND when game doesn't exist

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add drop game support to lobby UI

- Add dropButton and DropCallback to AvailableGameItem and RunningGameItem
- Add DropClicked method to both item types
- Add DropGame method to ConnectionHandler that sends DropGameRequest
- Wire up DropCallback when creating game list items

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Wire up drop buttons in lobby game prefabs

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Update lobby game prefabs

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-29 15:24:30 -08:00
d1de042a61 Add DropGame API for users to leave games (#4903)
* Add DropGame API for users to leave games

- Add DropGameRequest/Response proto messages to streaming API
- Add archived directory path in SaveDirectory for game preservation
- Add delete method to Persister trait and implementations
  - LocalFilePersister: delete local files
  - S3Persister: no-op (retain as backup)
  - CompoundPersister: delete from first (local) only
- Add dropUser() and remainingHumanCount to GameController
  - Reassigns dropped faction to AI with immediate takeover
- Add archiveGame() and dropGame() to GamesManager
  - Running games: archive if last human, otherwise AI takeover
  - Waiting games: remove user or entire game if empty
- Add DropGame handler to EagleServiceImpl streaming

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add deleteAll() to Persister and tests for dropGame

- Add deleteAll() method to Persister trait and implementations
  - LocalFilePersister: deletes all files and the directory
  - S3Persister: no-op (retain as backup)
  - CompoundPersister: delegates to first persister
- Refactor archiveGame to use deleteAll() instead of java.io.File
- Add unit tests for dropGame functionality:
  - Removes entire waiting game when only player drops
  - Removes only user when other players remain
  - Returns USER_NOT_IN_GAME when user not in waiting game
  - Returns GAME_NOT_FOUND when game doesn't exist

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-29 14:53:20 -08:00
389474f27b Replace Improve command dropdown with toggle buttons (#4889)
* Replace Improve command dropdown with toggle buttons

- Replace TMP_Dropdown with 4 toggle buttons (Economy, Agriculture,
  Infrastructure, Devastation) showing type name and current value
- Each toggle shows the improvement type and its current/effective value
- Maintains existing default selection logic (Devastation priority, then
  lowest stat)

Note: Unity prefab changes are needed to wire up the new toggle buttons.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Remove unused variable in ImproveCommandSelector

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Show unavailable improvement types as grayed-out instead of hidden

Uses CanvasGroup alpha to dim unavailable toggles and sets
interactable=false so they cannot be selected.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Wire up ImproveCommandSelector toggle buttons in Unity

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-29 13:22:51 -08:00
e799b2c966 Make MarchTowardProvinceCommandChooser fully protoless (#4901)
- Add protoless overloads to AIClientUtils for takenHeroIdsForMarchTowardFocus,
  mostPowerfulHeroes, and desiredCountForMarchTowardFocus
- Convert MarchTowardProvinceCommandChooser to use native GameState,
  ProvinceDistances, and BattalionUtils instead of Legacy* versions
- Update callers (MidGameAIClient, MoveLeaderToBetterProvinceCommandChooser)
  to convert proto GameState before calling
- Fix tests by adding currentPhase to proto GameState fixtures
- Update DEPROTO_PLAN.md

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-29 08:05:14 -08:00
580273174b Fix final Shardok battle actions not being displayed to clients (#4898)
When a battle ended, the client would never see the final few actions
that caused the game to end (e.g., the killing blow). This was because
WaitForUpdatesAndPush() would return immediately after calling
OnGameOver() without first sending the pending updates.

The fix moves the update-sending code before the gameOver check,
ensuring all action results are streamed to clients before the
game over notification is sent.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-29 07:22:24 -08:00
b1fc38343d Remove proto versions from HeroSelector and ProvinceGoldSurplusCalculator (#4899)
- Remove dead minimallyFatiguedHeroesProto from HeroSelector (no callers)
- Convert ProvinceGoldSurplusCalculator to fully protoless
  - Callers now use ProvinceConverter.fromProto() to get protoless province
  - Removed proto GameState dependency entirely
- Update callers in CommandChoiceHelpers, MarchTowardProvinceCommandChooser,
  and MidGameAIClient to use protoless versions
- Update DEPROTO_PLAN.md to reflect progress

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-29 07:13:06 -08:00
8a981710a8 Add chronicler style tracking to prevent style bleeding between chronicle entries (#4897)
- Add chronicler_style field to ChronicleEntry proto and Scala case class
- Store which chronicler style was used for each entry
- Update ChronicleUpdatePromptGenerator to label previous entries with their chronicler
- Prompt now distinguishes between same/different chronicler:
  - Same chronicler: "Continue in that same style and voice"
  - Different chronicler: "Write in YOUR OWN STYLE, don't imitate previous entries"
- Select chronicler style deterministically in NewRoundAction based on game ID and date

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-29 05:52:02 -08:00
bb111463f1 Fix spurious new faction head notifications (#4894)
Only generate NewFactionHead notification when the faction head actually
changes (i.e., when the head is killed), not when any non-head leader
is killed (e.g., a sworn brother being executed).

The bug was that maybeFactionLeaderRemovedResult was creating notifications
for every faction where any leader died, regardless of whether the faction
head changed. Now it correctly checks if originalFaction.factionHeadId !=
revisedFaction.factionHeadId before generating notifications.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 21:09:39 -08:00
800ac22ff6 Enable JFR profiling for Eagle server in Docker (#4895)
Adds Java Flight Recorder with continuous low-overhead profiling (~1%):
- Keeps 1 hour of data in a 100MB circular buffer
- Auto-dumps on JVM exit
- Stack depth of 256 for detailed traces

To capture a profile:
  docker exec eagle-server jcmd 1 JFR.dump filename=/app/jfr/profile.jfr
  docker cp eagle-server:/app/jfr/profile.jfr .

Analyze with JDK Mission Control (jmc) or IntelliJ's JFR viewer.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 21:07:21 -08:00
152a3b2388 Fix final Shardok battle results not displaying before model removal (#4892)
The ShardokGameModel was being removed from ShardokGameModels BEFORE
UpdateAction.Invoke() was called. This meant the UI callback received
a model that no longer contained the ended battle's final results.

Flow before:
1. Final Shardok results arrive with GameStatus = Victory/Defeat
2. Model updated with final results
3. Model REMOVED from ShardokGameModels
4. UpdateAction.Invoke() - UI doesn't see the model
5. Final results never displayed

Flow after:
1. Final Shardok results arrive with GameStatus = Victory/Defeat
2. Model updated with final results
3. Model STAYS in ShardokGameModels
4. UpdateAction.Invoke() - UI sees model with final results
5. Model removed AFTER callback

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 17:43:15 -08:00
39e0b9bbf8 Fix Unity build deploying from all branches instead of main only (#4893)
The deploy and manifest update steps had the branch check commented out,
causing builds from PRs and feature branches to be published to production.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 17:42:33 -08:00
df711b26eb Add settings management to admin server (Phase 2) (#4891)
* Add settings management to admin server (Phase 2)

- Add GetSettings gRPC endpoint to eagle.proto
- Enhance SettingsLoader generator to include getAllSettings method
- Implement getSettings in EagleServiceImpl
- Add settings page with live search and inline editing
- Uses existing AddSettings endpoint for updates
- Modified settings are highlighted in the UI

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Make settings table rows more compact

- Reduce cell padding and font sizes
- Make input and button elements more compact
- Override Pico CSS defaults for better density

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Make settings input fields even more compact

- Use !important to override Pico CSS defaults
- Set fixed height of 22px for input and button
- Reduce padding to 2px

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 17:37:48 -08:00
29c7ad7c58 Complete Phase 1: reverse order history and clickable action details (#4890)
- Add GetActionDetail gRPC endpoint to fetch individual action data
- Display action history in reverse chronological order (most recent first)
- Make action rows clickable to expand and show JSON representation
- Add action_detail.html template for htmx-powered action expansion
- Update CSS for clickable rows and action detail styling
- Mark Phase 1 as complete in enhancement plan

New routes:
- GET /games/{id}/action/{index} - htmx partial for action detail

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 15:17:20 -08:00
89bc355047 Fix missing battle results by always sending count updates (#4887)
When `filteredResults` was empty (e.g., AI turns filtered out as not
visible to the human player), the `update` method returned early
without sending a message to the client. However, it still advanced
the server's tracking of the client's count (`unfilteredKnownHistoryCount`).

This caused sync mismatches: the server thought the client was up-to-date
(so it wouldn't send the "missing" results on subsequent updates), but
the client never received the new count.

The fix: always call `afterSendingResults`, even when `filteredResults`
is empty. This ensures the client receives the count update (plus
`availableCommands` and `serverGameStatus`) even when there are no
visible results.

This was particularly problematic after battles ended, when AI turns
might be filtered out, causing the "last turns of the battle" to never
appear on the client.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 14:53:47 -08:00
9c7c929b0d Add Web UI to admin server with enhancement plan (#4888)
Phase 1 of admin server enhancements:
- Add Go templates with embed for layout, games list, game detail
- Add Pico CSS from CDN for styling, htmx for interactivity
- Implement htmx infinite scroll for action history
- Keep JSON API endpoints for backward compatibility

New routes:
- GET / - redirect to /games
- GET /games - HTML games list page
- GET /games/{id} - HTML game detail page
- GET /games/{id}/history - htmx partial for history rows

Also adds docs/ADMIN_SERVER_ENHANCEMENTS.md with full enhancement plan
including settings management and game rewind features.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 14:49:12 -08:00
8d444c0153 Add missing newline in PrisonerExecuted notification (#4886)
The textTemplate in PrisonerExecutedDetailsNotificationGenerator was
missing the \n\n separator between lead text and LLM-generated text,
causing them to run together. This matches the pattern used in other
notification generators like CapturedHeroExecutedDetailsNotificationGenerator.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 14:14:43 -08:00
85439d7000 Fix commands not retrying after connection drops during post (#4885)
Two bugs were causing commands to be lost when connection dropped
while posting:

1. PostRequest removed commands from pending queue even when
   DoWithStreamingCall returned false (connection dead). Now only
   removes on successful send.

2. TryPendingCommands dropped pending commands when CurrentEagleToken
   was null (which happens when HandleAvailableCommands skips due to
   LastPostedToken match). Now retries the command anyway.

Together these fixes ensure that if you post a command while the
connection is dead or dying, the command will be retried after
reconnect.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 14:10:48 -08:00
7dd9010a74 Add timeout to WriteAsync calls to prevent thread pool exhaustion (#4884)
WriteAsync can block indefinitely if a connection is dead but not yet
detected (e.g., network issues before TCP keepalive kicks in). This can
exhaust the .NET thread pool and cause the client to freeze.

Changes:
- Add 10-second timeout to DoWithStreamingCall using Task.WhenAny
- Add 10-second timeout to SendUpdateStreamRequestAsync
- Fix double PostRequest bug in TryPendingCommands where commands were
  posted twice (once in switch case, once after)
- Add ConfigureAwait(false) to network operations to avoid deadlocks

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 13:48:57 -08:00
cf2caaa992 Use HTTP/2 for headshot fetching to improve reliability on poor networks (#4883)
Switch ResourceFetcher from HttpClientHandler to YetAnotherHttpHandler with
HTTP/2 enabled. This provides:
- Connection multiplexing (all headshots to same host share one connection)
- Keep-alive pings to detect and recover from dead connections
- Same reliability settings as the gRPC connection

This should help headshots load more reliably on high-latency or lossy networks.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 13:43:29 -08:00
18697f0a38 Fix silent connection death from unhandled exceptions (#4882)
Several exception handling issues could cause the gRPC connection to die
silently with no recovery:

1. HandleStreamingCall() is async void but only caught RpcException and
   ObjectDisposedException. Any other exception type (e.g., from Logger,
   protobuf, null refs) would escape and leave the connection dead.
   Added catch-all that logs and schedules reconnect.

2. Connect() catch block logged errors but never called ScheduleReconnect().
   If Connect() failed after creating the streaming call, the connection
   would die with no recovery attempt. Now properly cleans up and reconnects.

3. Timer callbacks (idle check, heartbeat) had no exception handling.
   Exceptions in timer callbacks can stop the timer from firing again.
   Now wrapped in try-catch.

4. Task.Run(() => Connect()) fire-and-forget calls silently swallowed
   exceptions. Created RunConnectAsync() helper that logs exceptions.

5. Task.Run(() => SendHeartbeat()) also silently swallowed exceptions.
   Now properly awaits and catches exceptions inside the Task.Run.

These issues could explain "connection freezes" where the client stops
receiving updates but doesn't recover - an unhandled exception kills
the streaming thread or prevents reconnection.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 13:40:36 -08:00
d9f2c1c216 Make Logger non-blocking with dedicated writer thread (#4859)
The Logger was blocking ThreadPool threads when StreamWriter.Flush()
was slow (due to antivirus, cloud sync like OneDrive, or disk I/O).
This caused timer callbacks to stop firing, which led to heartbeat
failures and connection freezes.

The fix uses a ConcurrentQueue and dedicated background thread:
- LogLine() just enqueues the formatted message and returns immediately
- A dedicated writer thread processes the queue and handles file I/O
- File I/O blocking only affects the writer thread, not callers
- Timestamps are captured immediately when LogLine() is called

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 13:37:54 -08:00
91e5798478 Add protoless overload to FulfillQuestsCommandSelector (#4881)
- Add new overload that takes native GameState and uhsWithQuests directly
- Proto version now delegates to protoless version
- Export unaffiliated_hero_with_quest and game_state for callers
- Extract choosers list to a val for reuse

This is Part B of splitting PR #4876 - add a protoless public API while maintaining backward compatibility with CommandChooser framework.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 13:28:28 -08:00
980b42c94b Deproto UnaffiliatedHeroWithQuest to use native quest types (#4879)
- Change UnaffiliatedHeroWithQuest to use heroId: HeroId and quest: QuestT instead of uh: UnaffiliatedHero and quest: Quest proto
- Update all 9 quest command choosers to pattern match on native quest types directly (no more .quest.details unwrapping)
- Update FulfillQuestsCommandSelector to use QuestConverter.fromProto
- Update all 6 test files to use native quest types
- Add quest/concrete visibility and deps where needed

This is Part A of splitting PR #4876 - deproto the quest command selectors' internal data structures while keeping the public interface unchanged.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 13:19:07 -08:00
180c1e9429 Fix duplicate Shardok updates being sent to clients (#4878)
The shardokGameIdsToCheck list was constructed by concatenating
outstandingBattles and knownShardokResultCounts without deduplication.
When a battle appears in both lists, the same ShardokGameResultResponse
was generated and sent twice.

This caused every Shardok result to appear twice in client logs:
  #197 UPDATE ShardokResult shardok=...49cbefb8 countAfter=7 results=6
  #198 UPDATE ShardokResult shardok=...49cbefb8 countAfter=7 results=6

Fix: Add .distinct to remove duplicate shardokGameIds.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 13:12:40 -08:00
da29d394c5 Add protoless public interface to AttackDecisionCommandChooser (#4877)
- Change attackDecisionSelectedCommand to take native GameState
- Convert to proto internally using GameStateConverter.toProto
- Keep private methods using proto GameStateProto since they receive
  proto from CommandChooser lambdas
- Update callers (AIClient, CommandChoiceHelpers) to convert proto → native
- Update tests to use GameStateConverter.fromProto and add currentPhase

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 11:39:19 -08:00
3b1075069f Remove GetGameStatus RPC (now using streaming) (#4760)
* Remove legacy 5-second polling wait from GetUpdates

The wait in GetUpdates was used for long-polling to make AI turns feel
responsive. With streaming, WaitForUpdatesAndPush already waits for
updates via updateCondition.wait(), making this redundant.

GetGameStatus is deprecated in favor of SubscribeToGame streaming.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Remove GetGameStatus RPC (now using streaming)

GetGameStatus polling is no longer needed since Eagle now uses
SubscribeToGame streaming. This also removes the 5-second wait in
GetUpdates that was only needed to support long-polling.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Exclude pre-existing font files from LFS tracking

These font files were committed as regular blobs before LFS tracking
was set up for *.ttf files. Adding explicit exclusions prevents the
"files that should have been pointers" warning.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix out-of-bounds access in GetGameStateAtStartOfAction

Add upper bounds check to GetGameStateAtStartOfAction to match
GetGameHistory behavior. When requesting a state at or beyond the
current action count, return the current game state instead of
accessing an invalid array index.

This fixes signal 11 crashes in FilterNewResults called from
SubscribeToGame streaming flow.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Revert "Fix out-of-bounds access in GetGameStateAtStartOfAction"

This reverts commit c725b7a4ed87028bdc4860b4e7753497dbb3f040.

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 08:11:48 -08:00
85c8f9912b Add sequence logging for Shardok results (#4875)
Log countAfter (NewResultViewCount) for each ShardokGameResponse to
detect missing Shardok battle results. Similar to the ActionResultResponse
logging, this will show gaps in the sequence if messages are lost.

This helps diagnose why clients sometimes miss the last moves of battles -
observed as shardok sync mismatch (e.g., client=54, server=65).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 07:46:18 -08:00
097870cfd0 Complete deproto conversion of CommandChoiceHelpers (#4872)
* Complete deproto conversion of CommandChoiceHelpers

- Replace all Legacy utility usages with protoless versions:
  - LegacyFactionUtils.isFactionLeader → FactionUtils.isFactionLeader
  - LegacyProvinceUtils.containsFactionLeader → FactionUtils.factionLeaderLocation
  - LegacyProvinceUtils.effectiveInfrastructure → ProvinceUtils.effectiveInfrastructure
  - LegacyBattalionTypeFinder.battalionType → BattalionTypeFinder.battalionType
  - LegacyHeroUtils.power → HeroUtils.power
- Remove unused proto helper methods: suppressBeastsValueProto, beastPowerProto,
  closestLeaderProto, lowLoyaltyHeroesProto, provinceFoodSurplusProto, destinationCloserToProto
- Use targeted object conversion for foodAmountToBuy (convert individual objects
  rather than full GameState)
- Update DateConverter and RoundPhaseConverter to handle missing/default values
  for test compatibility (month=0 → January, UNKNOWN_PHASE → PlayerCommands)
- Remove Legacy dependencies from BUILD.bazel

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Revert converter defaults, fix tests to set required fields

- Revert DateConverter and RoundPhaseConverter to throw on invalid data
- Update tests to set currentDate and currentPhase in GameState fixtures
- Tests should explicitly set required data rather than relying on defaults

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 22:36:11 -08:00
fa02919503 Add sequence counter to LogFlow for duplicate detection (#4873)
Add incrementing counter (#1, #2, #3...) to each LogFlow call to diagnose
the duplicate logging issue observed in testing. Interpretation:
- Same seq# appears twice: two threads processing same message
- seq# increments but lines doubled: StreamWriter/Logger issue

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 19:44:14 -08:00
4f8668974b Add sequence number logging for ActionResultResponse (#4871)
Log UnfilteredResultCountAfter for each ActionResultResponse to help
diagnose sync mismatches. If we see gaps in the sequence (e.g., 2512
then 2519 with no 2513-2518), we know messages never arrived from the
server. If we see all counts but the client's internal counter doesn't
match, something dropped them internally.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 16:17:18 -08:00
3b0a85425c Add protoless destinationCloserTo using FactionUtils.ownedNeighbors (#4869)
- Add destinationCloserTo(FactionId, Map[ProvinceId, ProvinceT], ProvinceId, Vector[ProvinceId], ProvinceId)
  using FactionUtils.ownedNeighbors
- Rename proto version to destinationCloserToProto
- Add imports for ProvinceT and FactionUtils
- Update preferredSuppliesDestination to use destinationCloserToProto
- Update BUILD.bazel with protoless dependencies

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 13:04:21 -08:00
3f7b6e7d3c Add protoless beastPower helper to CommandChoiceHelpers (#4870)
- Add protoless beastPower(ProvinceT) using ProvinceUtils.beastCount/beastInfo
- Add proto version beastPowerProto(Province) and update chosenSuppressBeastsCommand
  to use it instead of inline calculation
- Also adds protoless suppressBeastsValue(HeroT) alongside proto version

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 13:01:17 -08:00
5072bd6f57 Add protoless closestLeader using ProvinceUtils.locationOf and ProvinceDistances (#4868)
- Add closestLeader(FactionId, FactionT, Map[ProvinceId, ProvinceT], ProvinceId)
  using ProvinceUtils.locationOf and ProvinceDistances.distanceThroughFriendliesOption
- Rename proto version to closestLeaderProto
- Add imports for ProvinceT and ProvinceUtils
- Update preferredSuppliesDestination to use closestLeaderProto
- Update BUILD.bazel with protoless dependencies

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 13:00:10 -08:00
334c63d1de Add protoless provinceFoodSurplus using ProvinceUtils.absoluteFoodSurplus (#4867)
- Add provinceFoodSurplus(ProvinceT, GameStateC) using protoless utilities
- Rename proto version to provinceFoodSurplusProto
- Add imports for GameStateC, ProvinceT, and ProvinceUtils
- Update BUILD.bazel with protoless dependencies

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 12:59:42 -08:00
6767e5d838 Add protoless versions of lowLoyaltyHeroes and suppressBeastsValue (#4866)
- Add lowLoyaltyHeroes(Vector[HeroT], Vector[FactionT]) using HeroUtils.effectiveLoyalty
- Add suppressBeastsValue(HeroT) using protoless Profession enum
- Rename proto versions to lowLoyaltyHeroesProto and suppressBeastsValueProto
- Update callers to use the renamed proto versions
- Add FactionT and NoProfession imports

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 12:33:39 -08:00
caa863dbbf Deproto: Add protoless utility methods to FactionUtils (#4861)
* Add protoless utility methods to FactionUtils

- Add isFactionHead(HeroId, Iterable[FactionT]) - checks if hero is any faction head
- Add leadersBesidesHead(FactionT) - gets leader IDs excluding faction head
- Add hasProvinces(FactionId, Iterable[ProvinceT]) - checks if faction owns provinces
- Add provinceCount(FactionId, Iterable[ProvinceT]) - counts faction's provinces

These mirror the proto versions in LegacyFactionUtils and enable future migration.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add tests for isFactionHead, leadersBesidesHead, hasProvinces, provinceCount

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 12:09:16 -08:00
fc291c795e Deproto: Add protoless utility methods to HeroUtils (#4860)
* Add protoless utility methods to HeroUtils

- Add seniorityOrder(FactionT, HeroId) - returns leader index or Int.MaxValue
- Add archeryCapable(HeroT) - checks if hero meets agility threshold
- Add startFireCapable(HeroT) - checks profession and stats for fire ability

These mirror the proto versions in LegacyHeroUtils and enable future migration
of CommandChoiceHelpers methods.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add tests for seniorityOrder, archeryCapable, and startFireCapable

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 12:08:51 -08:00
7081210aa5 Add comprehensive timestamped logging for connection flow tracing (#4865)
Adds LogFlow() helper for precise HH:mm:ss.fff timestamps throughout
the connection flow to diagnose reconnection issues:

PersistentClientConnection.cs:
- Connect(): state transitions, subscription start
- StreamOneGameAsync(): subscribe request/ack with counts
- HandleGameUpdate(): update types with token, command count, status
- HandleStreamingCall(): start/end with exit reason
- HandleHeartbeatResponse(): heartbeat response, sync mismatch detection
- SendHeartbeat(): heartbeat send/skip with reason
- ScheduleReconnect(): reconnect scheduling with backoff

EagleGameModel.cs:
- ReceiveGameUpdate(): token comparison and skip decision logging

This is logging-only - no behavioral changes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 11:13:15 -08:00
3bff280712 Add protoless closestProvinceThroughFriendliesOption to ProvinceDistances (#4864)
* Add protoless closestProvinceThroughFriendliesOption to ProvinceDistances

- Find closest province from candidates through friendly territory
- Mirrors LegacyProvinceDistances.closestProvinceThroughFriendliesOption

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add tests for closestProvinceThroughFriendliesOption

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 11:10:34 -08:00
78b8b83f79 Add protoless adjacentHostiles and absoluteFoodSurplus to ProvinceUtils (#4863)
* Add protoless adjacentHostiles and absoluteFoodSurplus to ProvinceUtils

- adjacentHostiles: Get provinces ruled by hostile factions
- absoluteFoodSurplus: Compute absolute food surplus for a province

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add tests for adjacentHostiles

Note: absoluteFoodSurplus tests skipped due to complex GameState requirements

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 11:08:38 -08:00
28fdcc4672 Add protoless locationOf and containsFactionLeader to ProvinceUtils (#4862)
* Add protoless locationOf and containsFactionLeader to ProvinceUtils

- locationOf: Find the province containing a hero
- containsFactionLeader: Check if a province contains the faction head

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add tests for locationOf and containsFactionLeader

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 10:56:55 -08:00
53314e7cb6 Add Console.WriteLine for timer callbacks and make Logger thread-safe (#4857)
The timers stopped logging entirely during the 28-second gap. To determine
if the timers are firing but the Logger is blocked vs timers not firing:

1. Add Console.WriteLine in timer Elapsed handlers BEFORE the callback
   - These bypass our Logger and write directly to stdout
   - Will show if timers are firing even if Logger is blocked

2. Make Logger thread-safe with locks
   - LogLine now uses lock(_lock) to prevent concurrent access issues
   - GetLogger now uses lock(_loggersLock) for thread-safe singleton access

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 21:07:34 -08:00
d4a5f48103 Add diagnostic logging for heartbeat and idle timer issues (#4856)
Add logging to diagnose why heartbeat/idle timers stop firing on Windows:
- Log when heartbeat timer fires (before any checks)
- Log when heartbeat is skipped and why (cancellation, not connected)
- Log when heartbeat send fails (stream unavailable)
- Log idle check when idle > 5s with cancellation status

This will help diagnose the 90-second gap where no heartbeat or idle
logs appear before PROTOCOL_ERROR on Windows client.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 20:38:15 -08:00
d6d1868fcb Stop timers before sync mismatch reconnect (#4854)
When HandleHeartbeatResponse detects a sync mismatch and triggers a
reconnect, it wasn't stopping the heartbeat and idle check timers.
This could cause them to fire during reconnection, potentially
interfering with the new connection.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 20:03:39 -08:00
8c9d38c546 Fix IllegalStateException when LLM stream client disconnects (#4855)
Handle the case where a gRPC stream is completed (client disconnected) but
the LLM update consumer thread still tries to send updates. This causes
IllegalStateException: "Stream is already completed, no further calls allowed".

Added catch for IllegalStateException in both humanClientsAfterUpdatingLlmStream
and humanClientsAfterPostingResults to gracefully handle disconnected clients.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 20:01:51 -08:00
139494d937 Fix race condition between heartbeat response and game updates (#4853)
The heartbeat handler was reading game state and sending responses without
holding the GamesManager lock. Since game updates ARE sent while holding
this lock, there was a race condition where:

1. AI processing holds GamesManager lock
2. Updates start being sent to clients via the stream
3. Heartbeat request arrives, acquires EagleServiceImpl lock (different lock)
4. Heartbeat reads game count and sends response (can interleave with updates)
5. Client receives heartbeat before some in-flight updates
6. Client detects sync mismatch despite updates being in transit

This particularly affected slower/remote connections (e.g., Windows clients)
because the timing window for the race was longer.

Fix: Wrap heartbeat handling in gamesManager.synchronized to ensure the
response is sent only after any in-progress game updates have been queued.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 19:33:10 -08:00
5c52dd9006 Add HTTP/2 timeout settings and upgrade YetAnotherHttpHandler to 1.11.4 (#4851)
Upgrade YetAnotherHttpHandler from 1.5.3 to 1.11.4 to get:
- ConnectTimeout support (added in 1.8.0)
- Fix deadlock during cancellation (1.11.4)
- Memory management improvements (1.11.1)
- Backpressure control (1.10.0)

Configure explicit timeouts to detect and recover from dead connections
faster, especially on Windows where firewalls may silently drop HTTP/2
keep-alive pings:

- Http2KeepAliveTimeout (5s): Close connection if ping not acknowledged
- Http2KeepAliveWhileIdle: Continue pinging during idle periods
- ConnectTimeout (10s): Don't wait forever for initial connection

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 19:10:44 -08:00
d473e5a5d6 Fix deadlock in PersistentClientConnection.Dispose() (#4850)
The Dispose() method held lock(this) while calling Thread.Join() on the
streaming thread. If the streaming thread was trying to acquire the same
lock, this caused a deadlock - making "Return to Lobby" hang indefinitely.

Fix: Capture thread reference inside lock, then join OUTSIDE the lock.

Also adds diagnostic logging for sync mismatch debugging:
- Heartbeat now logs client's count per game
- Result count updates are logged when they change

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 19:01:10 -08:00
e9b980e6d0 Add protoless shouldRest overload to CommandChoiceHelpers (#4849)
- Add protoless shouldRest(Iterable[HeroT]) using HeroUtils.fatigue
- Rename proto version to shouldRestProto(Iterable[Hero])
- Update callers (PerformVassalCommandsPhaseAction) to use shouldRestProto
- Add protoless tests using HeroC
- Add hero_utils dependency to BUILD.bazel

This follows the established pattern for incremental deproto migration.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 18:11:06 -08:00
8ba4268832 Deproto: Remove proto methods and convert tests to protoless (#4848)
* Remove SwornBrotherChooser.bestChoiceProto and convert test to protoless

- Delete bestChoiceProto method from SwornBrotherChooser
- Convert SwornBrotherChooserTest to use HeroC (protoless) instead of proto Hero
- Remove proto and LegacyHeroUtils dependencies from sworn_brother_chooser target
- Update DEPROTO_PLAN.md to mark SwornBrotherChooser as fully protoless

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Convert ImproveCommandSelectorTest to protoless and update DEPROTO_PLAN.md

- Replace proto Hero/Province/GameState with native HeroC/ProvinceC/GameState
- Remove GameStateConverter.fromProto calls - test now uses native types directly
- Remove proto dependencies from BUILD.bazel
- Update DEPROTO_PLAN.md with comprehensive status of all command selectors:
  - Document 11 fully protoless command selectors
  - Document 10 protoless quest command selectors
  - Document 2 files with dual proto/protoless versions
  - Document 4 files still blocked on proto GameState

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 17:17:17 -08:00
3a033ddf19 Fix admin server: use explicit goos/goarch for Linux binary (#4847)
The --platforms flag doesn't affect oci_image/pkg_tar dependencies -
they're exec rules that run on the host. This caused the Go binary
to be built for darwin/arm64 instead of linux/amd64.

Fix by creating an explicit admin_server_linux_amd64 target with
goos = "linux" and goarch = "amd64" set in the BUILD file.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 13:55:09 -08:00
61196d05e7 Add Go admin server to Docker deployment (#4846)
- Add oci_image, oci_load, oci_push targets for admin_server in ci/BUILD.bazel
- Add Alpine Linux 3.21 base image to MODULE.bazel (lightweight for Go binary)
- Add admin service to docker-compose.prod.yml with health check
- Add build-admin job to GitHub Actions workflow
- Update deploy job to pull and deploy admin image alongside eagle/shardok

The admin server connects to Eagle via internal Docker network (eagle:40032)
and exposes HTTP on port 8080 for the admin console.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 12:45:01 -08:00
e5a71bd3b4 Add Go admin server to Docker deployment (#4843)
* Add Go admin server to Docker deployment

- Add oci_image, oci_load, oci_push targets for admin_server in ci/BUILD.bazel
- Add Alpine Linux 3.21 base image to MODULE.bazel (lightweight for Go binary)
- Add admin service to docker-compose.prod.yml with health check
- Add build-admin job to GitHub Actions workflow
- Update deploy job to pull and deploy admin image alongside eagle/shardok

The admin server connects to Eagle via internal Docker network (eagle:40032)
and exposes HTTP on port 8080 for the admin console.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix Go cross-compilation by enabling pure Go build

Add `pure = "on"` to admin_server go_binary to disable CGO.
This avoids linker errors when cross-compiling from macOS ARM64
to Linux x86_64 with the LLVM toolchain.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Use rules_go platform for Go cross-compilation

Use @io_bazel_rules_go//go/toolchain:linux_amd64 instead of
//:linux_x86_64 for the admin server build. The rules_go platform
uses Go's native cross-compiler and doesn't involve the LLVM C
toolchain, avoiding linker errors.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 11:46:07 -08:00
e545d9c616 Remove ActionPointDistances disk cache (#4844)
Profiling showed that GenerateDistances accounts for only 0.04% of
total runtime while the disk cache consumed 168 GB of storage. The
modifier hash explosion (ice melt, fire, etc.) caused unbounded cache
growth without providing meaningful performance benefit.

The in-memory caching layers (persistent, thread-local, and shared)
remain and provide effective caching for the hot paths.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 11:24:08 -08:00
17e5135915 Add OPENAI_API_KEY and GPT_MODEL_NAME to deploy .env file (#4842)
- Pass all required env vars from GitHub secrets
- Fix .env file permissions (rm before write, chmod 600)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 10:57:47 -08:00
5c9623717d Convert SeekMoreLeadersCommandChooser and ProvinceDistances to protoless (#4840)
- Split ProvinceDistances into protoless version + LegacyProvinceDistances
- Convert SeekMoreLeadersCommandChooser to protoless (MidGameAIClient converts proto→Scala)
- Add protoless overloads to FactionUtils.provinces and CommandChoiceHelpers
- Create protoless SeekMoreLeadersCommandChooserTest using Scala model types
- Add DEPROTO_PLAN.md documenting migration status and decisions
- Update visibility for model state concrete types to support AI tests

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 10:49:34 -08:00
2ed1c5769e Enable S3/DO Spaces persistence via environment variables (#4839)
* Enable S3/DO Spaces persistence via environment variables

Add support for persisting game saves to DigitalOcean Spaces (S3-compatible)
via environment variables, preventing game state loss during deployments.

Configuration:
- EAGLE_ENABLE_S3=true to enable S3 persistence
- DO_SPACES_ACCESS_KEY and DO_SPACES_SECRET_KEY for credentials
- Falls back to ~/.s3cfg if env vars not set

Changes:
- S3Credentials: Load credentials from env vars or ~/.s3cfg
- LocalGamePersisterCreation: Read EAGLE_ENABLE_S3 from env
- ServerSetupHelpers: Enable S3 persister based on env var
- S3Utils: Fix transferManager to use credentials
- docker-compose.prod.yml: Add S3 environment variables

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Centralize S3 config and add endpoint env var

- Move all S3 config to S3Credentials (single source of truth)
- Add DO_SPACES_ENDPOINT env var (defaults to sfo3.digitaloceanspaces.com)
- Remove duplicate config reading from LocalGamePersisterCreation and ServerSetupHelpers
- Pass S3 secrets from GitHub Actions to droplet via .env file

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 07:55:01 -08:00
7a3b382623 Build Eagle Docker image for linux_x86_64 platform (#4838)
The Eagle image was being built without --platforms, defaulting to the
self-hosted runner's platform (darwin/arm64). This caused digest mismatch
errors when trying to pull the image on the linux/amd64 production droplet.

Also fix the bazel-bin symlink issue: when building with --platforms,
the output goes to a platform-specific directory. Save the resolved path
immediately after build (before other bazel commands change the symlink)
and use that path for pushing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 07:13:02 -08:00
d1e4ba4efe Delete unused ActionResultProtoUpdater type alias (#4836)
- Delete package.scala containing the unused ActionResultProtoUpdater type alias
- Remove action_pkg target from BUILD.bazel
- Remove unnecessary action_pkg dependencies from quest_creation BUILD targets

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-25 22:25:42 -08:00
481 changed files with 42768 additions and 23214 deletions
+4
View File
@@ -36,3 +36,7 @@ common --java_language_version=17
common --java_runtime_version=remotejdk_17
common --tool_java_language_version=17
common --tool_java_runtime_version=remotejdk_17
# Workspace status for build stamping (git commit, timestamp)
common --workspace_status_command=tools/workspace_status.sh
common --stamp
+177
View File
@@ -0,0 +1,177 @@
name: Auth Service Build and Deploy
on:
push:
branches: [ "main" ]
paths:
- 'src/main/go/net/eagle0/authservice/**'
- 'src/main/go/net/eagle0/authcli/**'
- 'src/main/protobuf/net/eagle0/eagle/api/auth.proto'
- 'src/main/protobuf/net/eagle0/eagle/api/admin/**'
- 'src/main/protobuf/net/eagle0/eagle/internal/auth_internal.proto'
- 'ci/BUILD.bazel'
- '.github/workflows/auth_build.yml'
workflow_dispatch:
inputs:
push_images:
description: 'Push images to container registry'
required: true
default: 'false'
type: boolean
permissions:
contents: read
jobs:
build-auth:
runs-on: self-hosted
outputs:
image_tag: ${{ steps.push-auth.outputs.image_tag }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
lfs: false
- name: Build Auth Server Docker image
id: build-auth
run: |
set -ex
# Build auth server image (Go binary has explicit goos/goarch in BUILD.bazel)
bazel build //ci:auth_server_image
# Save the resolved path before any other bazel command changes bazel-bin symlink
IMAGE_PATH=$(readlink -f bazel-bin/ci/auth_server_image)
echo "Image path: $IMAGE_PATH"
echo "image_path=$IMAGE_PATH" >> $GITHUB_OUTPUT
- name: Login to DigitalOcean Container Registry
if: github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && github.event.inputs.push_images == 'true')
env:
DO_TOKEN: ${{ secrets.DO_REGISTRY_TOKEN }}
run: |
mkdir -p ~/.docker
AUTH=$(echo -n "${DO_TOKEN}:${DO_TOKEN}" | base64)
echo "{\"auths\":{\"registry.digitalocean.com\":{\"auth\":\"${AUTH}\"}}}" > ~/.docker/config.json
mkdir -p .docker
cp ~/.docker/config.json .docker/
- name: Push Auth image to DO registry
id: push-auth
if: github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && github.event.inputs.push_images == 'true')
env:
DOCKER_CONFIG: ${{ github.workspace }}/.docker
run: |
set -ex
AUTH_IMAGE="${{ steps.build-auth.outputs.image_path }}"
echo "Using Auth image: $AUTH_IMAGE"
if [ -z "$AUTH_IMAGE" ] || [ ! -d "$AUTH_IMAGE" ]; then
echo "ERROR: Auth image not found at: $AUTH_IMAGE"
exit 1
fi
# Build the push target to get crane in runfiles
bazel build //ci:auth_server_push
# Use crane directly for push
CRANE="bazel-bin/ci/push_auth_server_push.sh.runfiles/rules_oci~~oci~oci_crane_darwin_arm64/crane"
echo "Using crane: $CRANE"
# Push with SHA tag
GIT_SHA=$(git rev-parse --short=8 HEAD)
IMAGE_TAG="registry.digitalocean.com/eagle0/auth-server:${GIT_SHA}"
echo "Pushing auth image: $IMAGE_TAG"
$CRANE push "$AUTH_IMAGE" "$IMAGE_TAG"
# Output the full image tag for deploy step
echo "image_tag=$IMAGE_TAG" >> $GITHUB_OUTPUT
# Also update :latest for convenience
echo "Copying to :latest tag"
$CRANE copy "$IMAGE_TAG" "registry.digitalocean.com/eagle0/auth-server:latest"
deploy:
runs-on: ubuntu-latest
needs: [build-auth]
if: github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && github.event.inputs.push_images == 'true')
environment: production
env:
AUTH_IMAGE: ${{ needs.build-auth.outputs.image_tag }}
DISCORD_CLIENT_ID: ${{ secrets.DISCORD_CLIENT_ID }}
DISCORD_CLIENT_SECRET: ${{ secrets.DISCORD_CLIENT_SECRET }}
GOOGLE_CLIENT_ID: ${{ secrets.GOOGLE_CLIENT_ID }}
GOOGLE_CLIENT_SECRET: ${{ secrets.GOOGLE_CLIENT_SECRET }}
JWT_PRIVATE_KEY: ${{ secrets.JWT_PRIVATE_KEY }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Deploy auth service to production
uses: appleboy/ssh-action@v1.0.3
with:
host: ${{ secrets.DO_DROPLET_IP }}
username: deploy
key: ${{ secrets.DO_SSH_KEY }}
script_stop: true
envs: AUTH_IMAGE,DISCORD_CLIENT_ID,DISCORD_CLIENT_SECRET,GOOGLE_CLIENT_ID,GOOGLE_CLIENT_SECRET,JWT_PRIVATE_KEY
script: |
set -x
cd /opt/eagle0
# Update AUTH_IMAGE in .env file (preserve other vars)
if [ -f .env ]; then
# Remove old AUTH_IMAGE line and add new one
grep -v '^AUTH_IMAGE=' .env > .env.tmp || true
echo "AUTH_IMAGE=${AUTH_IMAGE}" >> .env.tmp
# Also update OAuth credentials
grep -v '^DISCORD_CLIENT_ID=' .env.tmp > .env.tmp2 || true
echo "DISCORD_CLIENT_ID=${DISCORD_CLIENT_ID:-}" >> .env.tmp2
grep -v '^DISCORD_CLIENT_SECRET=' .env.tmp2 > .env.tmp3 || true
echo "DISCORD_CLIENT_SECRET=${DISCORD_CLIENT_SECRET:-}" >> .env.tmp3
grep -v '^GOOGLE_CLIENT_ID=' .env.tmp3 > .env.tmp4 || true
echo "GOOGLE_CLIENT_ID=${GOOGLE_CLIENT_ID:-}" >> .env.tmp4
grep -v '^GOOGLE_CLIENT_SECRET=' .env.tmp4 > .env.tmp5 || true
echo "GOOGLE_CLIENT_SECRET=${GOOGLE_CLIENT_SECRET:-}" >> .env.tmp5
# Update JWT private key (JWK format for auth service bootstrap)
grep -v '^JWT_PRIVATE_KEY=' .env.tmp5 > .env || true
echo "JWT_PRIVATE_KEY=${JWT_PRIVATE_KEY:-}" >> .env
rm -f .env.tmp .env.tmp2 .env.tmp3 .env.tmp4 .env.tmp5
chmod 600 .env
else
echo "ERROR: .env file not found. Run main deploy first."
exit 1
fi
# Login to registry
echo "${{ secrets.DO_REGISTRY_TOKEN }}" | docker login registry.digitalocean.com -u "${{ secrets.DO_REGISTRY_TOKEN }}" --password-stdin
echo "Deploying auth service: $AUTH_IMAGE"
# Use crane to pull image
echo "Installing crane..."
curl -sL https://github.com/google/go-containerregistry/releases/download/v0.20.2/go-containerregistry_Linux_x86_64.tar.gz | tar xzf - crane
chmod +x crane
echo "Pulling Auth image with crane..."
./crane pull "${AUTH_IMAGE}" auth.tar || { echo "ERROR: Failed to pull auth image"; exit 1; }
echo "Loading Auth image into Docker..."
docker load -i auth.tar
rm auth.tar
rm ./crane
# Only recreate the auth container (not eagle, shardok, etc.)
docker compose -f docker-compose.prod.yml up -d --no-deps --force-recreate auth
# Wait for health check
sleep 5
docker compose -f docker-compose.prod.yml ps auth
# Verify container is using correct image
echo "=== Verifying auth container image ==="
docker compose -f docker-compose.prod.yml images auth
# Cleanup old images
docker image prune -f
+75 -4
View File
@@ -8,12 +8,22 @@ on:
required: true
default: 'v2'
type: string
architecture:
description: 'Target architecture'
required: true
default: 'amd64'
type: choice
options:
- amd64
- arm64
- both
permissions:
contents: read
jobs:
build-sysroot:
build-sysroot-amd64:
if: ${{ inputs.architecture == 'amd64' || inputs.architecture == 'both' }}
runs-on: ubuntu-latest
steps:
- name: Checkout repository
@@ -25,7 +35,7 @@ jobs:
- name: Upload sysroot artifact
uses: actions/upload-artifact@v4
with:
name: ubuntu-noble-sysroot
name: ubuntu-noble-sysroot-amd64
path: tools/sysroot/output/
- name: Install AWS CLI
@@ -41,7 +51,7 @@ jobs:
AWS_ACCESS_KEY_ID: ${{ secrets.ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.SECRET_KEY }}
run: |
# Upload sysroot tarball to DO Spaces (using eagle0-windows bucket, same as other workflows)
# Upload sysroot tarball to DO Spaces
aws s3 cp tools/sysroot/output/ubuntu_noble_amd64_sysroot.tar.xz \
s3://eagle0-windows/sysroot/${{ inputs.version }}/ubuntu_noble_amd64_sysroot.tar.xz \
--endpoint-url https://sfo3.digitaloceanspaces.com \
@@ -54,7 +64,7 @@ jobs:
--acl public-read
echo ""
echo "=== Sysroot uploaded ==="
echo "=== AMD64 Sysroot uploaded ==="
echo "URL: https://eagle0-windows.sfo3.digitaloceanspaces.com/sysroot/${{ inputs.version }}/ubuntu_noble_amd64_sysroot.tar.xz"
echo "SHA256: $(cat tools/sysroot/output/ubuntu_noble_amd64_sysroot.sha256)"
echo ""
@@ -64,3 +74,64 @@ jobs:
echo " sha256 = \"$(cat tools/sysroot/output/ubuntu_noble_amd64_sysroot.sha256)\","
echo " urls = [\"https://eagle0-windows.sfo3.digitaloceanspaces.com/sysroot/${{ inputs.version }}/ubuntu_noble_amd64_sysroot.tar.xz\"],"
echo ")"
build-sysroot-arm64:
if: ${{ inputs.architecture == 'arm64' || inputs.architecture == 'both' }}
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up QEMU for ARM64 emulation
uses: docker/setup-qemu-action@v3
with:
platforms: arm64
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build ARM64 sysroot
run: ./tools/sysroot/build_sysroot_arm64.sh
- name: Upload sysroot artifact
uses: actions/upload-artifact@v4
with:
name: ubuntu-noble-sysroot-arm64
path: tools/sysroot/output/
- name: Install AWS CLI
run: |
if ! command -v aws &> /dev/null; then
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip -q awscliv2.zip
sudo ./aws/install
fi
- name: Upload to DigitalOcean Spaces
env:
AWS_ACCESS_KEY_ID: ${{ secrets.ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.SECRET_KEY }}
run: |
# Upload sysroot tarball to DO Spaces
aws s3 cp tools/sysroot/output/ubuntu_noble_arm64_sysroot.tar.xz \
s3://eagle0-windows/sysroot/${{ inputs.version }}/ubuntu_noble_arm64_sysroot.tar.xz \
--endpoint-url https://sfo3.digitaloceanspaces.com \
--acl public-read
# Upload sha256 file
aws s3 cp tools/sysroot/output/ubuntu_noble_arm64_sysroot.sha256 \
s3://eagle0-windows/sysroot/${{ inputs.version }}/ubuntu_noble_arm64_sysroot.sha256 \
--endpoint-url https://sfo3.digitaloceanspaces.com \
--acl public-read
echo ""
echo "=== ARM64 Sysroot uploaded ==="
echo "URL: https://eagle0-windows.sfo3.digitaloceanspaces.com/sysroot/${{ inputs.version }}/ubuntu_noble_arm64_sysroot.tar.xz"
echo "SHA256: $(cat tools/sysroot/output/ubuntu_noble_arm64_sysroot.sha256)"
echo ""
echo "Update MODULE.bazel with:"
echo "sysroot("
echo " name = \"linux_sysroot_arm64\","
echo " sha256 = \"$(cat tools/sysroot/output/ubuntu_noble_arm64_sysroot.sha256)\","
echo " urls = [\"https://eagle0-windows.sfo3.digitaloceanspaces.com/sysroot/${{ inputs.version }}/ubuntu_noble_arm64_sysroot.tar.xz\"],"
echo ")"
+290 -13
View File
@@ -5,11 +5,14 @@ on:
branches: [ "main" ]
paths:
- 'src/main/cpp/**'
- 'src/main/go/**'
- 'src/main/scala/**'
- 'src/main/protobuf/**'
- 'src/main/resources/**'
- 'ci/BUILD.bazel'
- 'MODULE.bazel'
- 'docker-compose.prod.yml'
- 'nginx/**'
- '.github/workflows/docker_build.yml'
workflow_dispatch:
inputs:
@@ -34,7 +37,15 @@ jobs:
lfs: false
- name: Build Eagle Docker image
run: bazel build //ci:eagle_server_image
id: build-eagle
run: |
set -ex
bazel build --platforms=//:linux_x86_64 //ci:eagle_server_image
# Save the resolved path before any other bazel command changes bazel-bin symlink
IMAGE_PATH=$(readlink -f bazel-bin/ci/eagle_server_image)
echo "Image path: $IMAGE_PATH"
echo "image_path=$IMAGE_PATH" >> $GITHUB_OUTPUT
- name: Login to DigitalOcean Container Registry
if: github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && github.event.inputs.push_images == 'true')
@@ -56,6 +67,40 @@ jobs:
run: |
set -ex
# Use cross-compiled image path from build step
EAGLE_IMAGE="${{ steps.build-eagle.outputs.image_path }}"
echo "Using Eagle image: $EAGLE_IMAGE"
if [ -z "$EAGLE_IMAGE" ] || [ ! -d "$EAGLE_IMAGE" ]; then
echo "ERROR: Eagle image not found at: $EAGLE_IMAGE"
exit 1
fi
# Debug: show OCI layout contents
echo "=== OCI Layout Contents ==="
cat "$EAGLE_IMAGE/index.json"
echo ""
echo "=== Blobs ==="
ls -la "$EAGLE_IMAGE/blobs/sha256/" | head -20
# Verify OCI layout consistency before pushing
echo "=== Verifying OCI layout consistency ==="
for digest in $(cat "$EAGLE_IMAGE/index.json" | grep -o '"sha256:[^"]*"' | tr -d '"'); do
blob_path="$EAGLE_IMAGE/blobs/${digest/://}"
if [ ! -f "$blob_path" ]; then
echo "ERROR: Blob not found: $blob_path"
exit 1
fi
actual_digest="sha256:$(shasum -a 256 "$blob_path" | cut -d' ' -f1)"
if [ "$digest" != "$actual_digest" ]; then
echo "ERROR: Digest mismatch for $blob_path"
echo " Index says: $digest"
echo " Actual: $actual_digest"
exit 1
fi
echo "✓ Verified: $digest"
done
# Build the push target to get crane in runfiles
bazel build //ci:eagle_server_push
@@ -67,7 +112,13 @@ jobs:
GIT_SHA=$(git rev-parse --short=8 HEAD)
IMAGE_TAG="registry.digitalocean.com/eagle0/eagle-server:${GIT_SHA}"
echo "Pushing eagle image: $IMAGE_TAG"
$CRANE push bazel-bin/ci/eagle_server_image "$IMAGE_TAG"
$CRANE push "$EAGLE_IMAGE" "$IMAGE_TAG"
# Verify push by checking what's in the registry
echo "=== Verifying push ==="
$CRANE manifest "$IMAGE_TAG" | head -50
PUSHED_DIGEST=$($CRANE digest "$IMAGE_TAG")
echo "Registry reports digest: $PUSHED_DIGEST"
# Output the full image tag for deploy step
echo "image_tag=$IMAGE_TAG" >> $GITHUB_OUTPUT
@@ -229,14 +280,169 @@ jobs:
echo "Copying to :latest tag"
$CRANE copy "$IMAGE_TAG" "registry.digitalocean.com/eagle0/shardok-server:latest"
build-admin:
runs-on: self-hosted
outputs:
image_tag: ${{ steps.push-admin.outputs.image_tag }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
lfs: false
- name: Build Admin Server Docker image
id: build-admin
run: |
set -ex
# Build admin server image (Go binary has explicit goos/goarch in BUILD.bazel)
bazel build //ci:admin_server_image
# Save the resolved path before any other bazel command changes bazel-bin symlink
IMAGE_PATH=$(readlink -f bazel-bin/ci/admin_server_image)
echo "Image path: $IMAGE_PATH"
echo "image_path=$IMAGE_PATH" >> $GITHUB_OUTPUT
- name: Login to DigitalOcean Container Registry
if: github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && github.event.inputs.push_images == 'true')
env:
DO_TOKEN: ${{ secrets.DO_REGISTRY_TOKEN }}
run: |
mkdir -p ~/.docker
AUTH=$(echo -n "${DO_TOKEN}:${DO_TOKEN}" | base64)
echo "{\"auths\":{\"registry.digitalocean.com\":{\"auth\":\"${AUTH}\"}}}" > ~/.docker/config.json
mkdir -p .docker
cp ~/.docker/config.json .docker/
- name: Push Admin image to DO registry
id: push-admin
if: github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && github.event.inputs.push_images == 'true')
env:
DOCKER_CONFIG: ${{ github.workspace }}/.docker
run: |
set -ex
ADMIN_IMAGE="${{ steps.build-admin.outputs.image_path }}"
echo "Using Admin image: $ADMIN_IMAGE"
if [ -z "$ADMIN_IMAGE" ] || [ ! -d "$ADMIN_IMAGE" ]; then
echo "ERROR: Admin image not found at: $ADMIN_IMAGE"
exit 1
fi
# Build the push target to get crane in runfiles
bazel build //ci:admin_server_push
# Use crane directly for push
CRANE="bazel-bin/ci/push_admin_server_push.sh.runfiles/rules_oci~~oci~oci_crane_darwin_arm64/crane"
echo "Using crane: $CRANE"
# Push with SHA tag
GIT_SHA=$(git rev-parse --short=8 HEAD)
IMAGE_TAG="registry.digitalocean.com/eagle0/admin-server:${GIT_SHA}"
echo "Pushing admin image: $IMAGE_TAG"
$CRANE push "$ADMIN_IMAGE" "$IMAGE_TAG"
# Output the full image tag for deploy step
echo "image_tag=$IMAGE_TAG" >> $GITHUB_OUTPUT
# Also update :latest for convenience
echo "Copying to :latest tag"
$CRANE copy "$IMAGE_TAG" "registry.digitalocean.com/eagle0/admin-server:latest"
build-jfr-sidecar:
runs-on: self-hosted
outputs:
image_tag: ${{ steps.push-jfr-sidecar.outputs.image_tag }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
lfs: false
- name: Build JFR Sidecar Docker image
id: build-jfr-sidecar
run: |
set -ex
# Build JFR sidecar image (Go binary has explicit goos/goarch in BUILD.bazel)
bazel build //ci:jfr_sidecar_image
# Save the resolved path before any other bazel command changes bazel-bin symlink
IMAGE_PATH=$(readlink -f bazel-bin/ci/jfr_sidecar_image)
echo "Image path: $IMAGE_PATH"
echo "image_path=$IMAGE_PATH" >> $GITHUB_OUTPUT
- name: Login to DigitalOcean Container Registry
if: github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && github.event.inputs.push_images == 'true')
env:
DO_TOKEN: ${{ secrets.DO_REGISTRY_TOKEN }}
run: |
mkdir -p ~/.docker
AUTH=$(echo -n "${DO_TOKEN}:${DO_TOKEN}" | base64)
echo "{\"auths\":{\"registry.digitalocean.com\":{\"auth\":\"${AUTH}\"}}}" > ~/.docker/config.json
mkdir -p .docker
cp ~/.docker/config.json .docker/
- name: Push JFR Sidecar image to DO registry
id: push-jfr-sidecar
if: github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && github.event.inputs.push_images == 'true')
env:
DOCKER_CONFIG: ${{ github.workspace }}/.docker
run: |
set -ex
JFR_IMAGE="${{ steps.build-jfr-sidecar.outputs.image_path }}"
echo "Using JFR Sidecar image: $JFR_IMAGE"
if [ -z "$JFR_IMAGE" ] || [ ! -d "$JFR_IMAGE" ]; then
echo "ERROR: JFR Sidecar image not found at: $JFR_IMAGE"
exit 1
fi
# Build the push target to get crane in runfiles
bazel build //ci:jfr_sidecar_push
# Use crane directly for push
CRANE="bazel-bin/ci/push_jfr_sidecar_push.sh.runfiles/rules_oci~~oci~oci_crane_darwin_arm64/crane"
echo "Using crane: $CRANE"
# Push with SHA tag
GIT_SHA=$(git rev-parse --short=8 HEAD)
IMAGE_TAG="registry.digitalocean.com/eagle0/jfr-sidecar:${GIT_SHA}"
echo "Pushing JFR sidecar image: $IMAGE_TAG"
$CRANE push "$JFR_IMAGE" "$IMAGE_TAG"
# Output the full image tag for deploy step
echo "image_tag=$IMAGE_TAG" >> $GITHUB_OUTPUT
# Also update :latest for convenience
echo "Copying to :latest tag"
$CRANE copy "$IMAGE_TAG" "registry.digitalocean.com/eagle0/jfr-sidecar:latest"
deploy:
runs-on: ubuntu-latest
needs: [build-eagle, build-shardok]
needs: [build-eagle, build-shardok, build-admin, build-jfr-sidecar]
if: github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && github.event.inputs.push_images == 'true')
environment: production
env:
EAGLE_IMAGE: ${{ needs.build-eagle.outputs.image_tag }}
SHARDOK_IMAGE: ${{ needs.build-shardok.outputs.image_tag }}
ADMIN_IMAGE: ${{ needs.build-admin.outputs.image_tag }}
JFR_SIDECAR_IMAGE: ${{ needs.build-jfr-sidecar.outputs.image_tag }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
GPT_MODEL_NAME: ${{ secrets.GPT_MODEL_NAME }}
EAGLE_ENABLE_S3: ${{ secrets.EAGLE_ENABLE_S3 }}
DO_SPACES_ACCESS_KEY: ${{ secrets.DO_SPACES_ACCESS_KEY }}
DO_SPACES_SECRET_KEY: ${{ secrets.DO_SPACES_SECRET_KEY }}
JWT_PRIVATE_KEY: ${{ secrets.JWT_PRIVATE_KEY }}
DISCORD_CLIENT_ID: ${{ secrets.DISCORD_CLIENT_ID }}
DISCORD_CLIENT_SECRET: ${{ secrets.DISCORD_CLIENT_SECRET }}
GOOGLE_CLIENT_ID: ${{ secrets.GOOGLE_CLIENT_ID }}
GOOGLE_CLIENT_SECRET: ${{ secrets.GOOGLE_CLIENT_SECRET }}
SHARDOK_ADDRESS: ${{ secrets.SHARDOK_ADDRESS }}
SHARDOK_AUTH_TOKEN: ${{ secrets.SHARDOK_AUTH_TOKEN }}
SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
@@ -257,23 +463,87 @@ jobs:
username: deploy
key: ${{ secrets.DO_SSH_KEY }}
script_stop: true
envs: EAGLE_IMAGE,SHARDOK_IMAGE
envs: EAGLE_IMAGE,SHARDOK_IMAGE,ADMIN_IMAGE,JFR_SIDECAR_IMAGE,OPENAI_API_KEY,GPT_MODEL_NAME,EAGLE_ENABLE_S3,DO_SPACES_ACCESS_KEY,DO_SPACES_SECRET_KEY,JWT_PRIVATE_KEY,DISCORD_CLIENT_ID,DISCORD_CLIENT_SECRET,GOOGLE_CLIENT_ID,GOOGLE_CLIENT_SECRET,SHARDOK_ADDRESS,SHARDOK_AUTH_TOKEN,SENTRY_DSN
script: |
set -x
cd /opt/eagle0
# Check Docker has IPv6 support for connecting to Hetzner Shardok
# (One-time setup: sudo tee /etc/docker/daemon.json <<< '{"ipv6": true, "ip6tables": true, "experimental": true, "fixed-cidr-v6": "fd00::/80"}' && sudo systemctl restart docker)
if ! cat /etc/docker/daemon.json 2>/dev/null | grep -q '"ip6tables"'; then
echo "WARNING: Docker IPv6 not configured. Eagle may not reach Hetzner Shardok."
echo "Run: sudo tee /etc/docker/daemon.json <<< '{\"ipv6\": true, \"ip6tables\": true, \"experimental\": true, \"fixed-cidr-v6\": \"fd00::/80\"}' && sudo systemctl restart docker"
fi
# Write env vars to .env file for docker-compose
# Preserve AUTH_IMAGE if it exists (managed by auth_build.yml)
EXISTING_AUTH_IMAGE=""
if [ -f .env ]; then
EXISTING_AUTH_IMAGE=$(grep '^AUTH_IMAGE=' .env | cut -d= -f2- || true)
fi
rm -f .env 2>/dev/null || true
cat > .env << EOF
EAGLE_IMAGE=${EAGLE_IMAGE}
SHARDOK_IMAGE=${SHARDOK_IMAGE}
ADMIN_IMAGE=${ADMIN_IMAGE}
JFR_SIDECAR_IMAGE=${JFR_SIDECAR_IMAGE}
AUTH_IMAGE=${EXISTING_AUTH_IMAGE:-registry.digitalocean.com/eagle0/auth-server:latest}
OPENAI_API_KEY=${OPENAI_API_KEY:-}
GPT_MODEL_NAME=${GPT_MODEL_NAME:-gpt-4o}
EAGLE_ENABLE_S3=${EAGLE_ENABLE_S3:-false}
DO_SPACES_ACCESS_KEY=${DO_SPACES_ACCESS_KEY:-}
DO_SPACES_SECRET_KEY=${DO_SPACES_SECRET_KEY:-}
JWT_PRIVATE_KEY=${JWT_PRIVATE_KEY:-}
DISCORD_CLIENT_ID=${DISCORD_CLIENT_ID:-}
DISCORD_CLIENT_SECRET=${DISCORD_CLIENT_SECRET:-}
GOOGLE_CLIENT_ID=${GOOGLE_CLIENT_ID:-}
GOOGLE_CLIENT_SECRET=${GOOGLE_CLIENT_SECRET:-}
SHARDOK_ADDRESS=${SHARDOK_ADDRESS:-shardok:40042}
SHARDOK_AUTH_TOKEN=${SHARDOK_AUTH_TOKEN:-}
SENTRY_DSN=${SENTRY_DSN:-}
EOF
chmod 600 .env
# Login to registry
echo "${{ secrets.DO_REGISTRY_TOKEN }}" | docker login registry.digitalocean.com -u "${{ secrets.DO_REGISTRY_TOKEN }}" --password-stdin
# Use exact image tags passed from build jobs (no :latest fallback)
echo "Using images: $EAGLE_IMAGE, $SHARDOK_IMAGE"
# Note: AUTH_IMAGE is managed separately by auth_build.yml
echo "Using images: $EAGLE_IMAGE, $SHARDOK_IMAGE, $ADMIN_IMAGE, $JFR_SIDECAR_IMAGE"
# Pull images with exact SHA tags
echo "Pulling Eagle image: $EAGLE_IMAGE"
docker pull "${EAGLE_IMAGE}" || { echo "ERROR: Failed to pull eagle image"; exit 1; }
# Use crane to pull images (handles OCI format correctly) then load into Docker
# This avoids digest mismatch from DO registry's OCI->Docker format conversion
echo "Installing crane..."
curl -sL https://github.com/google/go-containerregistry/releases/download/v0.20.2/go-containerregistry_Linux_x86_64.tar.gz | tar xzf - crane
chmod +x crane
echo "Pulling Shardok image: $SHARDOK_IMAGE"
docker pull "${SHARDOK_IMAGE}" || { echo "ERROR: Failed to pull shardok image"; exit 1; }
# crane uses Docker config for auth
echo "Pulling Eagle image with crane..."
./crane pull "${EAGLE_IMAGE}" eagle.tar || { echo "ERROR: Failed to pull eagle image"; exit 1; }
echo "Loading Eagle image into Docker..."
docker load -i eagle.tar
rm eagle.tar
echo "Pulling Shardok image with crane..."
./crane pull "${SHARDOK_IMAGE}" shardok.tar || { echo "ERROR: Failed to pull shardok image"; exit 1; }
echo "Loading Shardok image into Docker..."
docker load -i shardok.tar
rm shardok.tar
echo "Pulling Admin image with crane..."
./crane pull "${ADMIN_IMAGE}" admin.tar || { echo "ERROR: Failed to pull admin image"; exit 1; }
echo "Loading Admin image into Docker..."
docker load -i admin.tar
rm admin.tar
echo "Pulling JFR Sidecar image with crane..."
./crane pull "${JFR_SIDECAR_IMAGE}" jfr-sidecar.tar || { echo "ERROR: Failed to pull jfr-sidecar image"; exit 1; }
echo "Loading JFR Sidecar image into Docker..."
docker load -i jfr-sidecar.tar
rm jfr-sidecar.tar
rm ./crane
# Also pull other compose images
docker pull nginx:alpine || true
@@ -281,12 +551,19 @@ jobs:
echo "All images pulled successfully"
# Force recreate containers to ensure new image is used
docker compose -f docker-compose.prod.yml up -d --force-recreate --remove-orphans
# Recreate only the services we're updating (not auth - managed by auth_build.yml)
# This prevents restarting auth service during every Eagle deploy
docker compose -f docker-compose.prod.yml up -d --no-deps --force-recreate eagle shardok admin jfr-sidecar
# Ensure auth is running (but don't force-recreate it)
docker compose -f docker-compose.prod.yml up -d auth
# Restart nginx to pick up new container IPs
# (nginx caches DNS at startup, so it needs restart after eagle/shardok)
docker compose -f docker-compose.prod.yml restart nginx
docker compose -f docker-compose.prod.yml up -d --force-recreate nginx
# Cleanup orphaned containers
docker compose -f docker-compose.prod.yml up -d --remove-orphans
# Wait for health checks
sleep 10
+90
View File
@@ -0,0 +1,90 @@
name: Cleanup Old Container Images
on:
schedule:
# Run daily at 3am UTC
- cron: '0 3 * * *'
workflow_dispatch:
inputs:
dry_run:
description: 'Dry run (show what would be deleted without deleting)'
required: true
default: 'true'
type: boolean
permissions:
contents: read
jobs:
cleanup:
runs-on: ubuntu-latest
steps:
- name: Install doctl
uses: digitalocean/action-doctl@v2
with:
token: ${{ secrets.DO_REGISTRY_TOKEN }}
- name: Cleanup old images
env:
DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.dry_run == 'true' }}
run: |
set -e
RETENTION_DAYS=5
CUTOFF_DATE=$(date -d "-${RETENTION_DAYS} days" +%s)
REGISTRY="eagle0"
echo "Cleaning up images older than ${RETENTION_DAYS} days"
echo "Cutoff date: $(date -d "@${CUTOFF_DATE}" -Iseconds)"
echo "Dry run: ${DRY_RUN}"
echo ""
# List of repositories to clean
REPOS=$(doctl registry repository list-v2 --format Name --no-header)
for REPO in $REPOS; do
echo "=== Processing repository: ${REPO} ==="
# Get all manifests with their tags and dates
MANIFESTS=$(doctl registry repository list-manifests "${REPO}" --format Digest,UpdatedAt,Tags --no-header 2>/dev/null || echo "")
if [ -z "$MANIFESTS" ]; then
echo " No manifests found"
continue
fi
echo "$MANIFESTS" | while read -r DIGEST UPDATED_AT TAGS; do
# Skip if no digest
if [ -z "$DIGEST" ]; then
continue
fi
# Parse the date
MANIFEST_DATE=$(date -d "$UPDATED_AT" +%s 2>/dev/null || echo "0")
# Skip protected tags (latest, arm64-latest)
if echo "$TAGS" | grep -qE '(^|,)(latest|arm64-latest)(,|$)'; then
echo " KEEP: ${DIGEST:0:20}... (protected tag: $TAGS)"
continue
fi
# Check if older than cutoff
if [ "$MANIFEST_DATE" -lt "$CUTOFF_DATE" ]; then
echo " DELETE: ${DIGEST:0:20}... (updated: $UPDATED_AT, tags: $TAGS)"
if [ "$DRY_RUN" != "true" ]; then
doctl registry repository delete-manifest "${REPO}" "$DIGEST" --force
fi
else
echo " KEEP: ${DIGEST:0:20}... (updated: $UPDATED_AT, tags: $TAGS)"
fi
done
echo ""
done
- name: Run garbage collection
if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && github.event.inputs.dry_run == 'false')
run: |
echo "Starting garbage collection..."
doctl registry garbage-collection start --force
echo "Garbage collection started. It may take a few minutes to complete."
+159
View File
@@ -0,0 +1,159 @@
name: Shardok ARM64 Build and Push
on:
push:
branches: [ "main" ]
paths:
- 'src/main/cpp/**'
- 'src/main/protobuf/net/eagle0/shardok/**'
- 'src/main/protobuf/net/eagle0/common/**'
- 'src/main/resources/net/eagle0/shardok/**'
- 'ci/BUILD.bazel'
- 'MODULE.bazel'
- '.github/workflows/shardok_arm64_build.yml'
workflow_dispatch:
inputs:
push_images:
description: 'Push images to container registry'
required: true
default: 'true'
type: boolean
permissions:
contents: read
jobs:
build-shardok-arm64:
runs-on: self-hosted
outputs:
image_tag: ${{ steps.push-shardok.outputs.image_tag }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
lfs: false
- name: Build Shardok ARM64 binary (cross-compile for Linux ARM64)
run: |
set -ex
echo "=== Building shardok-server binary for linux-aarch64 ==="
bazel build \
--platforms=//:linux_arm64 \
--extra_toolchains=@llvm_toolchain_linux_arm64//:all \
//src/main/cpp/net/eagle0/shardok:shardok-server
LINUX_BIN="bazel-bin/src/main/cpp/net/eagle0/shardok/shardok-server"
echo "=== Checking binary at: $LINUX_BIN ==="
if [ ! -f "$LINUX_BIN" ]; then
echo "ERROR: Binary not found at $LINUX_BIN"
exit 1
fi
# Verify it's ELF (Linux) not Mach-O (macOS)
echo "=== Verifying binary format ==="
MAGIC=$(head -c 4 "$LINUX_BIN" | xxd -p)
echo "Binary magic bytes: $MAGIC"
if [ "$MAGIC" = "7f454c46" ]; then
echo "SUCCESS: Binary is ELF format (Linux)"
# Check if it's ARM64 (e_machine = 0xB7 = 183 for aarch64)
E_MACHINE=$(od -An -j18 -N2 -tx2 "$LINUX_BIN" | tr -d ' ')
echo "ELF e_machine: $E_MACHINE"
if [ "$E_MACHINE" = "b700" ]; then
echo "SUCCESS: Binary is ARM64 (aarch64)"
else
echo "WARNING: Binary e_machine is $E_MACHINE (expected b700 for aarch64)"
fi
elif [ "$MAGIC" = "cfaeedfe" ] || [ "$MAGIC" = "cffaedfe" ]; then
echo "ERROR: Binary is Mach-O format (macOS) - cross-compilation failed!"
exit 1
else
echo "WARNING: Unknown binary format: $MAGIC"
file "$LINUX_BIN" || true
fi
- name: Build Shardok ARM64 Docker image
id: build-shardok
run: |
set -ex
bazel build \
--platforms=//:linux_arm64 \
--extra_toolchains=@llvm_toolchain_linux_arm64//:all \
//ci:shardok_server_image_arm64
IMAGE_PATH=$(readlink -f bazel-bin/ci/shardok_server_image_arm64)
echo "Image path: $IMAGE_PATH"
echo "image_path=$IMAGE_PATH" >> $GITHUB_OUTPUT
# Verify the binary inside the tar layer is ARM64 ELF
echo "=== Verifying binary in image tar ==="
BINARY_TAR="bazel-bin/ci/shardok_binary_layer_arm64.tar"
if [ -f "$BINARY_TAR" ]; then
echo "Checking binary in $BINARY_TAR"
MAGIC=$(tar -xOf "$BINARY_TAR" app/shardok-server 2>/dev/null | head -c 4 | xxd -p)
echo "Binary magic in tar: $MAGIC"
if [ "$MAGIC" = "7f454c46" ]; then
echo "SUCCESS: Binary in tar is ELF format (Linux)"
else
echo "ERROR: Binary in tar is NOT ELF format!"
exit 1
fi
else
echo "WARNING: Could not find $BINARY_TAR"
fi
- name: Login to DigitalOcean Container Registry
if: github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && github.event.inputs.push_images == 'true')
env:
DO_REGISTRY_TOKEN: ${{ secrets.DO_REGISTRY_TOKEN }}
run: |
AUTH=$(echo -n "${DO_REGISTRY_TOKEN}:${DO_REGISTRY_TOKEN}" | base64)
echo "{\"auths\":{\"registry.digitalocean.com\":{\"auth\":\"${AUTH}\"}}}" > ~/.docker/config.json
- name: Push Shardok ARM64 image to DigitalOcean
id: push-shardok
if: github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && github.event.inputs.push_images == 'true')
run: |
set -ex
CROSS_IMAGE="${{ steps.build-shardok.outputs.image_path }}"
echo "Using cross-compiled image: $CROSS_IMAGE"
if [ -z "$CROSS_IMAGE" ] || [ ! -d "$CROSS_IMAGE" ]; then
echo "ERROR: Cross-compiled image not found at: $CROSS_IMAGE"
exit 1
fi
# Build a push target to get crane in runfiles
bazel build //ci:eagle_server_push
# Find the Darwin crane binary
RUNFILES="bazel-bin/ci/push_eagle_server_push.sh.runfiles"
CRANE=$(find "$RUNFILES" -path "*darwin*" -name crane 2>/dev/null | head -1)
if [ -z "$CRANE" ]; then
CRANE=$(find "$RUNFILES" -name crane 2>/dev/null | head -1)
fi
if [ -z "$CRANE" ] || [ ! -e "$CRANE" ]; then
echo "ERROR: crane not found"
exit 1
fi
echo "Using crane: $CRANE"
# Push with arm64-prefixed SHA tag (same repo as x86, different tag)
GIT_SHA=$(git rev-parse --short=8 HEAD)
IMAGE_TAG="registry.digitalocean.com/eagle0/shardok-server:arm64-${GIT_SHA}"
echo "Pushing shardok ARM64 image: $IMAGE_TAG"
$CRANE push "$CROSS_IMAGE" "$IMAGE_TAG"
echo "image_tag=$IMAGE_TAG" >> $GITHUB_OUTPUT
# Also update :arm64-latest tag for convenience
echo "Copying to :arm64-latest tag"
$CRANE copy "$IMAGE_TAG" "registry.digitalocean.com/eagle0/shardok-server:arm64-latest"
echo "=== Push complete ==="
echo "Image: $IMAGE_TAG"
echo "Also tagged as: registry.digitalocean.com/eagle0/shardok-server:arm64-latest"
+2 -2
View File
@@ -52,14 +52,14 @@ jobs:
- name: Persist Library/
run: ./ci/github_actions/persist_library.sh
- name: Deploy Windows unity
if: success() #&& github.ref == 'refs/heads/main' && github.event_name == 'push'
if: success() && github.ref == 'refs/heads/main' && github.event_name == 'push'
env:
ACCESS_KEY_ID: ${{ secrets.ACCESS_KEY_ID }}
SECRET_KEY: ${{ secrets.SECRET_KEY }}
run: bazel run //src/main/go/net/eagle0/build/unity3d_windows_build_handler:unity3d_windows_build_handler -- "/tmp/eagle0/eagle0WIN" "/tmp/unity_manifest.txt"
- name: Update unified manifest
if: success() #&& github.ref == 'refs/heads/main' && github.event_name == 'push'
if: success() && github.ref == 'refs/heads/main' && github.event_name == 'push'
env:
ACCESS_KEY_ID: ${{ secrets.ACCESS_KEY_ID }}
SECRET_KEY: ${{ secrets.SECRET_KEY }}
+9
View File
@@ -12,6 +12,15 @@ platform(
],
)
# Platform for cross-compiling to Linux ARM64
platform(
name = "linux_arm64",
constraint_values = [
"@platforms//os:linux",
"@platforms//cpu:aarch64",
],
)
gazelle(name = "gazelle")
# gazelle:proto file
+213
View File
@@ -0,0 +1,213 @@
# Deproto Migration Plan
This document tracks the migration from protobuf types to native Scala models inside the Eagle game engine.
## Architectural Decisions
1. **Keep proto for persistence**: Yes - protobuf is used for persisting game state
2. **Keep proto for Shardok communication**: Yes - protobuf is used for Eagle-Shardok gRPC communication
3. **Use Scala views inside the library**: Yes - use native Scala types like `ProvinceView`, `FactionView`, `HeroView`, etc. within the library code
## Recent Completed Work
### GameState Round-Trip Elimination (PRs #4913, #4914, #4915)
Eliminated wasteful Scala→proto→Scala conversions in the hot path:
1. **LLM Pipeline** (#4913): `LlmRequestWithGameState` now uses Scala `GameState` instead of proto. All ~38 prompt generators updated to use Scala model types (`FactionT`, `HeroT`, `ProvinceT`).
2. **ActionWithResultingState Caching** (#4914): Added `precomputedScalaState: Option[GameState]` to cache Scala state when available, avoiding `fromProto()` conversion in `stateAfter()`.
3. **PostResults Simplification** (#4915): Changed `PostResults.gameState` from proto to `Option[GameState]` (Scala), eliminating `toProto()` calls when creating PostResults.
## Migration Pattern
The codebase follows a **Legacy* pattern** for separating proto-dependent and protoless code:
- **Protoless utilities**: `FactionUtils`, `HeroUtils`, `ProvinceUtils`, `ProvinceDistances`, etc.
- **Proto-dependent utilities**: `LegacyFactionUtils`, `LegacyHeroUtils`, `LegacyProvinceUtils`, `LegacyProvinceDistances`, etc.
When migrating a file:
1. Create a `Legacy*` version containing the proto-dependent methods
2. Keep the original file name for protoless methods
3. Update callers to use the appropriate version based on their context
## Migration Status
### Fully Protoless (no proto imports)
**Utilities:**
- [x] `FactionUtils` - has protoless `ownedNeighbors` method
- [x] `ProvinceDistances` - split into protoless + `LegacyProvinceDistances`
- [x] `SwornBrotherChooser` - fully protoless (removed `bestChoiceProto`)
**Command Selectors (all use native GameState):**
- [x] `AllianceOfferCommandSelector`
- [x] `AlmsCommandSelector`
- [x] `AttackCommandChooser`
- [x] `ExpandCommandSelector`
- [x] `HeroGiftCommandSelector`
- [x] `ImproveCommandSelector`
- [x] `MarchTowardProvinceCommandChooser` - in AI folder, uses native GameState (callers convert)
- [x] `OrganizeCommandSelector`
- [x] `RansomOfferHelpers`
- [x] `SeekMoreLeadersCommandChooser` - in AI folder, uses native GameState
- [x] `TruceOfferCommandSelector`
- [x] `TrustForDiplomacy`
**Quest Command Selectors (all protoless):**
- [x] `AllianceQuestCommandChooser`
- [x] `AlmsAcrossRealmQuestCommandChooser`
- [x] `AlmsToProvinceQuestCommandChooser`
- [x] `DismissSpecificVassalCommandChooser`
- [x] `GiveToHeroesAcrossRealmQuestCommandChooser`
- [x] `GiveToHeroesInProvinceQuestCommandChooser`
- [x] `ImproveQuestCommandChooser`
- [x] `QuestCommandChooser`
- [x] `TruceCountQuestCommandChooser`
- [x] `TruceWithFactionQuestCommandChooser`
### Fully Protoless
- [x] `AIClientUtils` - has protoless overloads (`takenHeroIdsForMarchTowardFocus`, `mostPowerfulHeroes`)
- [x] `AttackCommandChooser` - uses Scala `GameState` and `BattalionViewC` (Scala view type)
- [x] `BattalionPower` - has `estimatedPower(BattalionViewC)` for recon data with optional stats
- [x] `CommandChoiceHelpers` - fully protoless, uses Scala `GameState` throughout
- [x] `ProvinceGoldSurplusCalculator` - fully protoless (callers use converters)
- [x] `HeroSelector` - fully protoless (removed dead `minimallyFatiguedHeroesProto`)
### AI Layer ✅ COMPLETE
All AI and command chooser code is now fully protoless:
- [x] `AttackDecisionCommandChooser` - uses Scala GameState
- [x] `CommandChooser` - trait uses Scala GameState
- [x] `FulfillQuestsCommandSelector` - uses Scala GameState
- [x] `MidGameAIClient` - uses Scala GameState internally
### Still Using Proto GameState (Boundary Code)
These files use proto GameState because they're at system boundaries:
**View Filters (client projection):**
- `view_filters/GameStateViewFilter` - has Scala overload, uses Scala sub-filters
- `view_filters/ProvinceViewFilter` - has Scala overloads for some methods
- `view_filters/FactionViewFilter` - has Scala overload
- `view_filters/HeroViewFilter` - has Scala overload
- `view_filters/BattalionNameFilter` - has Scala overload
- `view_filters/BattleFilter` - has Scala overload
**Legacy Utilities (to be deprecated):**
- `LegacyProvinceDistances`, `LegacyFactionUtils`, `LegacyHeroUtils`, etc.
- Used by code that still needs proto GameState
**Persistence/Action System:**
- `ActionResultTApplier`, `ActionResultProtoApplier` - apply results to proto state
- `ActionWithResultingState` - caches both proto and Scala state
**Shardok Interface (gRPC boundary):**
- `ShardokInterfaceGrpcClient`, `ShardokInterfaceProxy` - must use proto for C++ communication
## Next Steps
### Phase 1-3: AI Layer ✅ COMPLETE
The entire AI decision-making layer is now protoless.
### Phase 4: View Filters ✅ COMPLETE
The view_filters package migration is complete:
**Completed:**
- [x] `GameStateViewFilter` - added Scala GameState overload (uses Scala sub-filters)
- [x] `ProvinceViewFilter` - already has Scala overloads for server-side views
- [x] `HumanPlayerClientConnectionState` - updated to pass Scala GameState directly
- [x] `HeroViewFilter` - added Scala overload
- [x] `FactionViewFilter` - added Scala overload
- [x] `Visibility` - added Scala overloads
**Still Using Proto:**
- [x] `BattalionNameFilter` - has Scala overload
- [x] `BattleFilter` - has Scala overload
- [ ] `ActionResultFilter` - uses proto internally (boundary code)
**Strategy:**
1. Add Scala GameState overloads to view filter methods
2. Update callers to pass Scala GameState where available
3. Eventually deprecate proto versions
### Phase 5: Legacy Utility Cleanup (IN PROGRESS)
Remove Legacy* utilities by migrating remaining callers:
1. Identify callers of each Legacy* util
2. Update callers to use protoless versions
3. Delete Legacy* files when no longer needed
**Deleted (no production callers):**
- [x] `LegacyProvinceDistances` - deleted (no callers)
- [x] `LegacyBattalionSuitability` - deleted (no callers)
- [x] `LegacyFoodConsumptionUtils` - deleted (no callers)
- [x] `LegacyHandleRiotUtils` - deleted (no callers)
**Refactored to Thin Wrappers (delegating to protoless versions):**
- [x] `LegacyRansomValidity` - already a thin wrapper delegating to `RansomValidity`
- [x] `LegacyRecruitmentOdds` - refactored to delegate to `RecruitmentOdds`
**Parallel Implementations (proto mirrors protoless):**
- [x] `FactionUtils` / `LegacyFactionUtils` - both have matching APIs; LegacyFactionUtils used by boundary code (24+ callers)
- [x] `HeroUtils` / `LegacyHeroUtils` - both have matching APIs; LegacyHeroUtils used by boundary code (10 callers)
- [x] `ProvinceUtils` / `LegacyProvinceUtils` - both have matching APIs; LegacyProvinceUtils used by boundary code (20 callers: availability factories, view filters)
**Parallel Implementations (awaiting migration of callers):**
- [x] `BattalionUtils` / `LegacyBattalionUtils` - both have matching core methods; LegacyBattalionUtils used by boundary code (4 callers)
- [x] `BattalionViewFilter` / `LegacyBattalionViewFilter` - protoless version exists; Legacy used by view filters, action appliers (3 callers)
- [x] `BattalionTypeFinder` / `LegacyBattalionTypeFinder` - protoless version exists; Legacy used by validators (1 caller: RuntimeValidator)
### Recent Caller Migration
**CheckForFulfilledQuestsAction** - migrated to use protoless `BattalionTypeFinder`:
- Changed `battalionTypes` parameter from proto `Vector[BattalionType]` to Scala `Vector[BattalionType]`
- Updated callers (EngineImpl, EndVassalCommandsPhaseAction) to pass Scala types directly
- Eliminated wasteful `BattalionTypeConverter.toProto()` conversions
**ExpandedUnaffiliatedHeroUtils** - added Scala overload:
- New overload takes Scala `GameState` and `UnaffiliatedHeroT` directly
- Added `UnaffiliatedHeroConverter.unaffiliatedHeroTypeToProto()` helper for efficient enum conversion
- Proto overload retained for backward compatibility
**AvailablePleaseRecruitMeCommandFactory** - eliminated wasteful proto conversions:
- Now uses `ExpandedUnaffiliatedHeroUtils.expandedUnaffiliatedHero(ScalaGameState, UnaffiliatedHeroT)` directly
- Removed `GameStateConverter.toProto()` and `UnaffiliatedHeroConverter.toProto()` calls
- Factory is now fully protoless internally (still returns proto types for API boundary)
**ProvinceViewFilter** - added Scala overload with faction filtering:
- New `filteredProvinceView(province: ProvinceT, gs: ScalaGameState, factionId: FactionId)` overload
- Uses protoless `FactionUtils.hasAlliance`, `Visibility.hasFullVisibility`, and `ProvinceUtils.incomingOthers`
- Handles reconned provinces directly from Scala `FactionT.reconnedProvinces` (already Scala type)
- Added helper methods: `fullProvinceInfoScala`, `maybeIncomingAttackersScala`, `unaffiliatedHeroInfoScala`
- Events still converted to proto at the end (ProvinceView.knownEvents uses proto events)
**GameStateViewFilter** - eliminated GameStateConverter.toProto() call:
- Scala overload now fully protoless internally
- Uses the new ProvinceViewFilter Scala overload with faction filtering
- Converts `battalionTypes` and `chronicleEntries` to proto only at output boundary
## Key Files
### Protoless Model Types
- `src/main/scala/net/eagle0/eagle/model/state/game_state/GameState.scala` - native Scala GameState
- `src/main/scala/net/eagle0/eagle/model/state/province/ProvinceView.scala` - province view type
- `src/main/scala/net/eagle0/eagle/model/state/faction/FactionView.scala` - faction view type
- `src/main/scala/net/eagle0/eagle/model/state/hero/HeroView.scala` - hero view type
### Proto Converters
- `src/main/scala/net/eagle0/eagle/model/proto_converters/game_state/` - converts between proto and Scala types
## Notes
- The AI client code (`src/main/scala/net/eagle0/eagle/ai/`) is now fully protoless
- Proto GameState is still needed at boundaries: persistence, gRPC to Shardok
- `PerformUnaffiliatedHeroesAction` and the LLM pipeline use protoless `GameState`
- `GameStateViewFilter` Scala overload is now fully protoless internally (converts to proto only at output)
- `ProvinceViewFilter` has Scala overloads for all three modes: no filtering, faction filtering, and withdrawn-from view
+54 -7
View File
@@ -57,25 +57,47 @@ llvm.toolchain(
llvm_version = "20.1.2",
)
# Linux sysroot for cross-compilation (Chromium's Debian sysroot)
# Linux x86_64 sysroot for cross-compilation
llvm.sysroot(
name = "llvm_toolchain_linux",
label = "@linux_sysroot//sysroot",
targets = ["linux-x86_64"],
)
use_repo(llvm, "llvm_toolchain", "llvm_toolchain_linux")
# Cross-compilation toolchain (macOS -> Linux ARM64)
llvm.toolchain(
name = "llvm_toolchain_linux_arm64",
llvm_version = "20.1.2",
)
# Download the Linux sysroot (Ubuntu 24.04 Noble for C++23 support)
# Linux ARM64 sysroot for cross-compilation
llvm.sysroot(
name = "llvm_toolchain_linux_arm64",
label = "@linux_sysroot_arm64//sysroot",
targets = ["linux-aarch64"],
)
use_repo(llvm, "llvm_toolchain", "llvm_toolchain_linux", "llvm_toolchain_linux_arm64")
# Download the Linux sysroots (Ubuntu 24.04 Noble for C++23 support)
# Built by: .github/workflows/build_sysroot.yml
# To rebuild: Run the "Build Linux Sysroot" workflow with a new version, then update sha256 and URL
sysroot = use_repo_rule("@toolchains_llvm//toolchain:sysroot.bzl", "sysroot")
# x86_64 sysroot
sysroot(
name = "linux_sysroot",
sha256 = "a06475004fe8003ae7ccb4fe1d5511feb9b27cce4a8826eb1dfd686ed83f3dba",
urls = ["https://eagle0-windows.sfo3.digitaloceanspaces.com/sysroot/v3/ubuntu_noble_amd64_sysroot.tar.xz"],
)
# ARM64 sysroot
sysroot(
name = "linux_sysroot_arm64",
sha256 = "87469137737e09bc73855007dab835477eb10a7b3ce3f725f93f64e25747f3f9",
urls = ["https://eagle0-windows.sfo3.digitaloceanspaces.com/sysroot/v4/ubuntu_noble_arm64_sysroot.tar.xz"],
)
#
# Language Support - Go
#
@@ -94,6 +116,8 @@ use_repo(
"com_github_aws_aws_sdk_go_v2_config",
"com_github_aws_aws_sdk_go_v2_credentials",
"com_github_aws_aws_sdk_go_v2_service_s3",
"com_github_golang_jwt_jwt_v5",
"com_github_google_uuid",
"org_golang_google_grpc",
"org_golang_google_protobuf",
)
@@ -130,22 +154,33 @@ bazel_dep(name = "aspect_bazel_lib", version = "2.16.0")
oci = use_extension("@rules_oci//oci:extensions.bzl", "oci")
# Base image for Eagle (Java 17)
# Base image for Eagle (Java 17 JDK - includes jcmd for JFR dumps)
oci.pull(
name = "eclipse_temurin_17",
digest = "sha256:d286b5352d98777bbf727f54038b04f0145cd9b76ca83f38a67aa111d4303748",
image = "docker.io/library/eclipse-temurin",
platforms = ["linux/amd64"],
tag = "17-jdk",
)
# Base image for Shardok (Ubuntu 24.04 for C++ runtime)
oci.pull(
name = "ubuntu_24_04",
image = "docker.io/library/ubuntu",
platforms = ["linux/amd64"],
platforms = [
"linux/amd64",
"linux/arm64/v8",
],
tag = "24.04",
)
use_repo(oci, "eclipse_temurin_17", "eclipse_temurin_17_linux_amd64", "ubuntu_24_04", "ubuntu_24_04_linux_amd64")
# Base image for Admin Server (Alpine for lightweight Go binary)
oci.pull(
name = "alpine_linux",
image = "docker.io/library/alpine",
platforms = ["linux/amd64"],
tag = "3.21",
)
use_repo(oci, "alpine_linux", "alpine_linux_linux_amd64", "eclipse_temurin_17", "eclipse_temurin_17_linux_amd64", "ubuntu_24_04", "ubuntu_24_04_linux_amd64", "ubuntu_24_04_linux_arm64_v8")
#
# Java/Scala Dependencies
@@ -211,6 +246,9 @@ maven.install(
# JWT (for OAuth token handling)
"com.nimbusds:nimbus-jose-jwt:9.37.3",
# Error tracking
"io.sentry:sentry:7.19.0",
],
duplicate_version_warning = "error",
fail_if_repin_required = True,
@@ -265,6 +303,14 @@ http_file(
executable = True,
)
http_file(
name = "busybox_aarch64",
sha256 = "141adb1b625a6f44c4b114f76b4387b4ea4f7ab802b88eb40e0d2f6adcccb1c3",
urls = ["https://busybox.net/downloads/binaries/1.35.0-aarch64-linux-musl/busybox"],
downloaded_file_path = "busybox",
executable = True,
)
#
# Toolchain Registration
#
@@ -278,5 +324,6 @@ register_toolchains(
register_toolchains(
"@llvm_toolchain//:all",
"@llvm_toolchain_linux//:all",
"@llvm_toolchain_linux_arm64//:all",
dev_dependency = True,
)
+54 -5
View File
@@ -1293,7 +1293,7 @@
"@@rules_oci~//oci:extensions.bzl%oci": {
"general": {
"bzlTransitiveDigest": "FaY+7xb13bB3hmxqwAWaGp3Tf3Q4Nfdlr+F38CP5mcg=",
"usagesDigest": "BuciKSozbpJMD9EP+j0RG5ZgrYMeDPsQyiOnLUni2V8=",
"usagesDigest": "39yHQmifPoGf+JSYpnQSnJGugxbrFVge/+ENmUiqZ6M=",
"recordedFileInputs": {},
"recordedDirentsInputs": {},
"envVariables": {},
@@ -1306,7 +1306,7 @@
"scheme": "https",
"registry": "index.docker.io",
"repository": "library/eclipse-temurin",
"identifier": "sha256:d286b5352d98777bbf727f54038b04f0145cd9b76ca83f38a67aa111d4303748",
"identifier": "17-jdk",
"platform": "linux/amd64",
"target_name": "eclipse_temurin_17_linux_amd64",
"bazel_tags": []
@@ -1321,7 +1321,7 @@
"scheme": "https",
"registry": "index.docker.io",
"repository": "library/eclipse-temurin",
"identifier": "sha256:d286b5352d98777bbf727f54038b04f0145cd9b76ca83f38a67aa111d4303748",
"identifier": "17-jdk",
"platforms": {
"@@platforms//cpu:x86_64": "@eclipse_temurin_17_linux_amd64"
},
@@ -1343,6 +1343,20 @@
"bazel_tags": []
}
},
"ubuntu_24_04_linux_arm64_v8": {
"bzlFile": "@@rules_oci~//oci/private:pull.bzl",
"ruleClassName": "oci_pull",
"attributes": {
"www_authenticate_challenges": {},
"scheme": "https",
"registry": "index.docker.io",
"repository": "library/ubuntu",
"identifier": "24.04",
"platform": "linux/arm64/v8",
"target_name": "ubuntu_24_04_linux_arm64_v8",
"bazel_tags": []
}
},
"ubuntu_24_04": {
"bzlFile": "@@rules_oci~//oci/private:pull.bzl",
"ruleClassName": "oci_alias",
@@ -1354,12 +1368,44 @@
"repository": "library/ubuntu",
"identifier": "24.04",
"platforms": {
"@@platforms//cpu:x86_64": "@ubuntu_24_04_linux_amd64"
"@@platforms//cpu:x86_64": "@ubuntu_24_04_linux_amd64",
"@@platforms//cpu:arm64": "@ubuntu_24_04_linux_arm64_v8"
},
"bzlmod_repository": "ubuntu_24_04",
"reproducible": true
}
},
"alpine_linux_linux_amd64": {
"bzlFile": "@@rules_oci~//oci/private:pull.bzl",
"ruleClassName": "oci_pull",
"attributes": {
"www_authenticate_challenges": {},
"scheme": "https",
"registry": "index.docker.io",
"repository": "library/alpine",
"identifier": "3.21",
"platform": "linux/amd64",
"target_name": "alpine_linux_linux_amd64",
"bazel_tags": []
}
},
"alpine_linux": {
"bzlFile": "@@rules_oci~//oci/private:pull.bzl",
"ruleClassName": "oci_alias",
"attributes": {
"target_name": "alpine_linux",
"www_authenticate_challenges": {},
"scheme": "https",
"registry": "index.docker.io",
"repository": "library/alpine",
"identifier": "3.21",
"platforms": {
"@@platforms//cpu:x86_64": "@alpine_linux_linux_amd64"
},
"bzlmod_repository": "alpine_linux",
"reproducible": true
}
},
"oci_crane_darwin_amd64": {
"bzlFile": "@@rules_oci~//oci:repositories.bzl",
"ruleClassName": "crane_repositories",
@@ -1496,7 +1542,10 @@
"eclipse_temurin_17",
"eclipse_temurin_17_linux_amd64",
"ubuntu_24_04",
"ubuntu_24_04_linux_amd64"
"ubuntu_24_04_linux_amd64",
"ubuntu_24_04_linux_arm64_v8",
"alpine_linux",
"alpine_linux_linux_amd64"
],
"explicitRootModuleDirectDevDeps": [],
"useAllRepos": "NO",
+197 -2
View File
@@ -17,6 +17,18 @@ pkg_tar(
},
)
pkg_tar(
name = "busybox_layer_arm64",
srcs = ["@busybox_aarch64//file"],
package_dir = "/usr/local/bin",
remap_paths = {
"file/busybox": "busybox",
},
symlinks = {
"/usr/local/bin/nc": "busybox",
},
)
#
# Eagle Server Docker Image
#
@@ -51,13 +63,17 @@ oci_image(
base = "@eclipse_temurin_17_linux_amd64",
entrypoint = [
"java",
"-Xmx4g",
"-Xmx2g",
"-XX:+UseG1GC",
# JFR profiling support
"-XX:+UnlockDiagnosticVMOptions",
"-XX:+DebugNonSafepoints", # Required for JFR to see through inlined methods
"-XX:FlightRecorderOptions=stackdepth=256",
"-jar",
"/app/eagle_server_deploy.jar",
],
env = {
"JAVA_OPTS": "-Xmx4g -XX:+UseG1GC",
"JAVA_OPTS": "-Xmx2g -XX:+UseG1GC",
},
exposed_ports = ["40032/tcp"],
tars = [
@@ -150,3 +166,182 @@ oci_push(
image = ":shardok_server_image",
repository = "registry.digitalocean.com/eagle0/shardok-server",
)
#
# Shardok Server ARM64 Docker Image (for Hetzner on-demand compute)
#
# Build: bazel build //ci:shardok_server_image_arm64 --platforms=//:linux_arm64 --extra_toolchains=@llvm_toolchain_linux_arm64//:all
# Load: bazel run //ci:shardok_server_load_arm64
# Push: bazel run //ci:shardok_server_push_arm64
#
# Package the Shardok binary (ARM64 version - must be built with --platforms=//:linux_arm64)
pkg_tar(
name = "shardok_binary_layer_arm64",
srcs = ["//src/main/cpp/net/eagle0/shardok:shardok-server"],
package_dir = "/app",
)
oci_image(
name = "shardok_server_image_arm64",
base = "@ubuntu_24_04_linux_arm64_v8",
entrypoint = ["/app/shardok-server"],
exposed_ports = [
"40042/tcp",
"40052/tcp",
],
tars = [
# Note: busybox_layer_arm64 omitted - busybox.net has SSL issues
# Health checks can use the shardok-server binary itself or be added later
":shardok_binary_layer_arm64",
":shardok_resources_layer",
":shardok_maps_layer",
],
workdir = "/app",
)
# Load into Docker locally (ARM64): bazel run //ci:shardok_server_load_arm64
oci_load(
name = "shardok_server_load_arm64",
image = ":shardok_server_image_arm64",
repo_tags = ["eagle0/shardok-server:latest-arm64"],
)
# Push to DigitalOcean Container Registry (for Hetzner deployment)
# Uses same repository as x86 but with arm64- tag prefix
oci_push(
name = "shardok_server_push_arm64",
image = ":shardok_server_image_arm64",
repository = "registry.digitalocean.com/eagle0/shardok-server",
)
#
# Admin Server Docker Image (Go)
#
# Build: bazel build //ci:admin_server_image
# Load: bazel run //ci:admin_server_load
# Push: bazel run //ci:admin_server_push
#
# Package the Go admin binary (explicit Linux x86_64 target)
pkg_tar(
name = "admin_binary_layer",
srcs = ["//src/main/go/net/eagle0/admin_server:admin_server_linux_amd64"],
package_dir = "/app",
)
oci_image(
name = "admin_server_image",
base = "@alpine_linux_linux_amd64",
entrypoint = ["/app/admin_server_linux_amd64"],
exposed_ports = ["8080/tcp"],
tars = [
":busybox_layer",
":admin_binary_layer",
],
workdir = "/app",
)
# Load into Docker locally: bazel run //ci:admin_server_load
oci_load(
name = "admin_server_load",
image = ":admin_server_image",
repo_tags = ["eagle0/admin-server:latest"],
)
# Push to DigitalOcean Container Registry
oci_push(
name = "admin_server_push",
image = ":admin_server_image",
repository = "registry.digitalocean.com/eagle0/admin-server",
)
#
# JFR Sidecar Docker Image (Go + JDK for jcmd)
#
# This sidecar runs with shared PID namespace to access the Eagle JVM.
# Build: bazel build //ci:jfr_sidecar_image
# Load: bazel run //ci:jfr_sidecar_load
# Push: bazel run //ci:jfr_sidecar_push
#
# Package the Go JFR server binary
pkg_tar(
name = "jfr_sidecar_binary_layer",
srcs = ["//src/main/go/net/eagle0/jfr_server:jfr_server_linux_amd64"],
package_dir = "/app",
)
oci_image(
name = "jfr_sidecar_image",
# Use JDK base image - we need jcmd to dump JFR recordings
base = "@eclipse_temurin_17_linux_amd64",
entrypoint = ["/app/jfr_server_linux_amd64"],
exposed_ports = ["8081/tcp"],
tars = [
":jfr_sidecar_binary_layer",
],
workdir = "/app",
)
# Load into Docker locally: bazel run //ci:jfr_sidecar_load
oci_load(
name = "jfr_sidecar_load",
image = ":jfr_sidecar_image",
repo_tags = ["eagle0/jfr-sidecar:latest"],
)
# Push to DigitalOcean Container Registry
oci_push(
name = "jfr_sidecar_push",
image = ":jfr_sidecar_image",
repository = "registry.digitalocean.com/eagle0/jfr-sidecar",
)
#
# Auth Server Docker Image (Go)
#
# This is the external OAuth service that handles OAuth flows and JWT creation.
# Build: bazel build //ci:auth_server_image
# Load: bazel run //ci:auth_server_load
# Push: bazel run //ci:auth_server_push
#
# Package the Go auth binary (explicit Linux x86_64 target)
pkg_tar(
name = "auth_binary_layer",
srcs = [
"//src/main/go/net/eagle0/authcli:authcli_linux_amd64",
"//src/main/go/net/eagle0/authservice:authservice_linux_amd64",
],
package_dir = "/app",
)
oci_image(
name = "auth_server_image",
base = "@alpine_linux_linux_amd64",
entrypoint = ["/app/authservice_linux_amd64"],
exposed_ports = [
"40033/tcp", # gRPC
"8080/tcp", # HTTP OAuth callback
],
tars = [
":busybox_layer",
":auth_binary_layer",
],
workdir = "/app",
)
# Load into Docker locally: bazel run //ci:auth_server_load
oci_load(
name = "auth_server_load",
image = ":auth_server_image",
repo_tags = ["eagle0/auth-server:latest"],
)
# Push to DigitalOcean Container Registry
oci_push(
name = "auth_server_push",
image = ":auth_server_image",
repository = "registry.digitalocean.com/eagle0/auth-server",
)
+135 -3
View File
@@ -1,7 +1,7 @@
# Docker Compose for production deployment
#
# Local testing:
# Build images: bazel run //ci:eagle_server_load && bazel run //ci:shardok_server_load
# Build images: bazel run //ci:eagle_server_load && bazel run //ci:shardok_server_load && bazel run //ci:auth_server_load
# Run: docker compose -f docker-compose.prod.yml up
#
# Production deployment:
@@ -15,15 +15,36 @@ services:
- "--gpt-model-name"
- "${GPT_MODEL_NAME:-gpt-5.1}"
- "--shardok-interface-remote-address"
- "shardok:40042"
- "${SHARDOK_ADDRESS:-shardok:40042}"
- "--auth-service-url"
- "auth:40033"
ports:
- "40032:40032"
environment:
OPENAI_API_KEY: "${OPENAI_API_KEY:-}"
EAGLE_ENABLE_S3: "${EAGLE_ENABLE_S3:-false}"
DO_SPACES_ENDPOINT: "${DO_SPACES_ENDPOINT:-https://sfo3.digitaloceanspaces.com}"
DO_SPACES_ACCESS_KEY: "${DO_SPACES_ACCESS_KEY:-}"
DO_SPACES_SECRET_KEY: "${DO_SPACES_SECRET_KEY:-}"
JWT_PRIVATE_KEY: "${JWT_PRIVATE_KEY:-}"
DISCORD_CLIENT_ID: "${DISCORD_CLIENT_ID:-}"
DISCORD_CLIENT_SECRET: "${DISCORD_CLIENT_SECRET:-}"
# Auth token for remote Shardok on Hetzner (only used when shardok address contains .eagle0.net)
SHARDOK_AUTH_TOKEN: "${SHARDOK_AUTH_TOKEN:-}"
# Use persistent volume for save data (users, games, etc.)
EAGLE_SAVE_DIR: "/app/saves"
EAGLE_ARCHIVE_DIR: "/app/archived"
SENTRY_DSN: "${SENTRY_DSN:-}"
SENTRY_ENVIRONMENT: "production"
volumes:
- ./saves:/app/saves
- ./saves:/app/saves # Game saves and user database
- ./archived:/app/archived # Archived completed games
- ./jfr:/app/jfr # JFR recordings - dump with: docker exec eagle-server jcmd 1 JFR.dump filename=/app/jfr/profile.jfr
- jvm-tmp:/tmp # Shared with jfr-sidecar for JVM attach socket files
- jwt-keys:/etc/eagle0/keys # Shared JWT keys with auth service
depends_on:
- shardok
- auth
restart: unless-stopped
logging:
driver: "json-file"
@@ -37,9 +58,51 @@ services:
retries: 3
start_period: 30s
auth:
image: ${AUTH_IMAGE:-registry.digitalocean.com/eagle0/auth-server:latest}
container_name: auth-server
environment:
# gRPC port for Auth service
AUTH_GRPC_PORT: "40033"
# HTTP port for OAuth callbacks
AUTH_HTTP_PORT: "8080"
# User data persistence directory
AUTH_DATA_DIR: "/app/data"
# Legacy path for migrating users from Eagle (Phase 1 migration)
AUTH_LEGACY_DATA_DIR: "/app/saves/auth"
# OAuth provider credentials
DISCORD_CLIENT_ID: "${DISCORD_CLIENT_ID:-}"
DISCORD_CLIENT_SECRET: "${DISCORD_CLIENT_SECRET:-}"
GOOGLE_CLIENT_ID: "${GOOGLE_CLIENT_ID:-}"
GOOGLE_CLIENT_SECRET: "${GOOGLE_CLIENT_SECRET:-}"
# Server base URL for OAuth callbacks
SERVER_BASE_URL: "${SERVER_BASE_URL:-https://prod.eagle0.net}"
# JWT keys - PEM files in volume, bootstrapped from JWK on first run
JWT_KEYS_PATH: "/etc/eagle0/keys"
JWT_PRIVATE_KEY: "${JWT_PRIVATE_KEY:-}"
# Note: port 40033 is exposed via nginx, not directly
volumes:
- jwt-keys:/etc/eagle0/keys # Shared JWT keys with Eagle
- ./auth-data:/app/data # User database persistence
- ./saves:/app/saves:ro # Read-only access to Eagle's saves for migration
restart: unless-stopped
logging:
driver: "json-file"
options:
max-size: "50m"
max-file: "3"
healthcheck:
test: ["CMD-SHELL", "nc -z localhost 40033 || exit 1"]
interval: 30s
timeout: 10s
retries: 3
start_period: 10s
shardok:
image: ${SHARDOK_IMAGE:-registry.digitalocean.com/eagle0/shardok-server:latest}
container_name: shardok-server
mem_limit: 1g
memswap_limit: 1g # Prevent swap, OOM-kill cleanly instead
ports:
- "40042:40042"
- "40052:40052"
@@ -66,6 +129,7 @@ services:
ports:
- "443:443"
- "80:80"
- "40033:40033" # Go Auth service gRPC (Phase 2 direct client connections)
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
- ./certbot/conf:/etc/letsencrypt:ro
@@ -80,6 +144,59 @@ services:
max-size: "50m"
max-file: "3"
admin:
image: ${ADMIN_IMAGE:-registry.digitalocean.com/eagle0/admin-server:latest}
container_name: admin-server
command:
- "--eagle-addr"
- "eagle:40032"
- "--auth-addr"
- "auth:40033"
- "--jfr-sidecar-addr"
- "jfr-sidecar:8081"
- "--http-port"
- "8080"
ports:
- "8080:8080"
depends_on:
- eagle
- auth
- jfr-sidecar
restart: unless-stopped
logging:
driver: "json-file"
options:
max-size: "50m"
max-file: "3"
healthcheck:
test: ["CMD-SHELL", "wget -q --spider http://localhost:8080/health || exit 1"]
interval: 30s
timeout: 10s
retries: 3
start_period: 10s
jfr-sidecar:
image: ${JFR_SIDECAR_IMAGE:-registry.digitalocean.com/eagle0/jfr-sidecar:latest}
container_name: jfr-sidecar
# Share PID namespace with Eagle to access its JVM via jcmd
pid: "service:eagle"
volumes:
- jvm-tmp:/tmp # Shared with Eagle for JVM attach socket files
depends_on:
- eagle
restart: unless-stopped
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "2"
healthcheck:
test: ["CMD-SHELL", "wget -q --spider http://localhost:8081/health || exit 1"]
interval: 30s
timeout: 10s
retries: 3
start_period: 10s
certbot:
image: certbot/certbot
container_name: certbot
@@ -87,3 +204,18 @@ services:
- ./certbot/conf:/etc/letsencrypt
- ./certbot/www:/var/www/certbot
entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait $${!}; done;'"
volumes:
jvm-tmp:
# Shared /tmp for JVM attach socket files between Eagle and jfr-sidecar
jwt-keys:
# Shared JWT RSA keys between Eagle and auth service
networks:
default:
driver: bridge
enable_ipv6: true
ipam:
config:
- subnet: 172.28.0.0/16
- subnet: fd00:dead:beef::/48
+471
View File
@@ -0,0 +1,471 @@
# Admin Server Enhancement Plan
## Overview
This document outlines enhancements to the Go admin server (`src/main/go/net/eagle0/admin_server/`) to provide a proper web UI for game administration.
### Current State
The admin server provides a full web UI with htmx interactivity:
- `GET /` - Redirect to games list
- `GET /games` - Game list page (HTML)
- `GET /games/{id}` - Game detail with action history
- `GET /games/{id}/history` - History rows (htmx partial, infinite scroll)
- `GET /games/{id}/action/{index}` - Action detail (htmx partial)
- `POST /games/{id}/rewind` - Rewind game to target action
- `GET /settings` - Settings list with live search
- `POST /settings/update` - Update setting value
- `GET /health` - Health check (JSON)
- `GET /api/games` - JSON API for programmatic access
- `GET /api/games/{id}/history` - JSON API for history
### Goals
1. **Web UI**: Replace raw JSON with an interactive HTML interface
2. **Settings Management**: View and modify the 275+ game settings at runtime
3. **Game Rewind**: Restore a game to a previous action count
---
## Architecture
### Technology Choice: Go Templates + htmx
**Rationale:**
- Single binary deployment (no separate frontend build)
- htmx provides interactivity without JavaScript framework complexity
- Familiar HTML/CSS, minimal learning curve
- Excellent for admin tools where SEO and bundle size don't matter
**Alternatives Considered:**
- React/Vue SPA: Adds build complexity, separate deployment artifact
- Server-side only: Less interactive, full page reloads
### Directory Structure
```
src/main/go/net/eagle0/admin_server/
├── admin_server.go # Main entry point, HTTP routes
├── handlers/
│ ├── games.go # Game list and detail handlers
│ ├── settings.go # Settings list and update handlers
│ └── rewind.go # Game rewind handlers
├── templates/
│ ├── layout.html # Base layout with nav, htmx includes
│ ├── games/
│ │ ├── list.html # Game list page
│ │ ├── detail.html # Single game view with history
│ │ └── history.html # Partial for history table (htmx)
│ ├── settings/
│ │ ├── list.html # Settings list with search/filter
│ │ └── edit.html # Inline edit partial (htmx)
│ └── rewind/
│ └── confirm.html # Rewind confirmation modal
├── static/
│ ├── style.css # Minimal CSS (Pico CSS or similar)
│ └── htmx.min.js # htmx library
└── BUILD.bazel
```
---
## Feature 1: Web UI
### Routes
| Route | Method | Description |
|-------|--------|-------------|
| `/` | GET | Redirect to `/games` |
| `/games` | GET | Game list page (HTML) |
| `/games/{id}` | GET | Game detail page with history |
| `/games/{id}/history` | GET | History partial (htmx, for infinite scroll) |
| `/api/games` | GET | JSON API (existing, keep for programmatic access) |
| `/api/games/{id}/history` | GET | JSON API (existing) |
### Game List Page
```
┌─────────────────────────────────────────────────────────────┐
│ Eagle Admin [Settings] [Health] │
├─────────────────────────────────────────────────────────────┤
│ │
│ Running Games (3) │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Game abc123f Round 45 │ │
│ │ Players: Liu Bei (Human), Cao Cao (AI), Sun Quan │ │
│ │ Actions: 1,234 [View] [Rewind]│ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Game def456a Round 12 │ │
│ │ Players: Test Player (Human) │ │
│ │ Actions: 456 [View] [Rewind]│ │
│ └─────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
```
### Game Detail Page
Shows game info and scrollable action history:
- **Reverse chronological order**: Most recent actions displayed first
- Each action shows: index, type, round ID
- **Clickable actions**: Clicking an action row expands to show JSON representation of the full action data
- "Rewind to here" button on each action row
- Infinite scroll loads more history via htmx (loading older actions as user scrolls down)
### Implementation Notes
1. **Embed static files**: Use `//go:embed` to bundle templates and static files
2. **Template functions**: Add helpers for formatting (hex IDs, timestamps, action summaries)
3. **CSS framework**: Use Pico CSS (~10KB) for clean defaults without classes
---
## Feature 2: Settings Management
### New gRPC Endpoints (Eagle Server)
Add to `eagle.proto`:
```protobuf
message Setting {
string name = 1;
string type = 2; // "Int" or "Double"
string value = 3; // Current value as string
string default_value = 4; // Default from BUILD.bazel
string description = 5; // Optional, for UI hints
}
message GetSettingsRequest {
string filter = 1; // Optional name filter (substring match)
}
message GetSettingsResponse {
repeated Setting settings = 1;
}
message UpdateSettingRequest {
string name = 1;
string value = 2;
}
message UpdateSettingResponse {
Setting setting = 1; // Updated setting
string error = 2; // Empty on success
}
service Eagle {
// ... existing methods ...
rpc GetSettings(GetSettingsRequest) returns (GetSettingsResponse);
rpc UpdateSetting(UpdateSettingRequest) returns (UpdateSettingResponse);
}
```
### Eagle Server Implementation
Create a settings registry that:
1. Discovers all `IntSetting` and `DoubleSetting` instances via reflection or explicit registration
2. Provides get/set by name
3. Validates types on update
```scala
// src/main/scala/net/eagle0/eagle/library/settings/SettingsRegistry.scala
object SettingsRegistry {
private val settings: Map[String, Either[IntSetting, DoubleSetting]] = Map(
"ActionVigorCost" -> Left(ActionVigorCost),
"BaseFoodBuyPrice" -> Right(BaseFoodBuyPrice),
// ... register all 275 settings
)
def getAll(filter: Option[String]): Seq[Setting] = ...
def get(name: String): Option[Setting] = ...
def update(name: String, value: String): Either[String, Setting] = ...
}
```
**Alternative: Code generation**
Rather than manually registering 275 settings, modify `setting_rule.bzl` to generate a registry file during build.
### Admin Server Routes
| Route | Method | Description |
|-------|--------|-------------|
| `/settings` | GET | Settings list page with search |
| `/settings/{name}` | GET | Single setting detail (htmx partial) |
| `/settings/{name}` | PUT | Update setting value |
| `/api/settings` | GET | JSON API |
| `/api/settings/{name}` | PUT | JSON API |
### Settings UI
```
┌─────────────────────────────────────────────────────────────┐
│ Eagle Admin [Games] [Health] │
├─────────────────────────────────────────────────────────────┤
│ │
│ Settings [Search: __________ ] │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ ActionVigorCost (Int) │ │
│ │ Current: [15 ] Default: 15 [Save] │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ BaseFoodBuyPrice (Double) │ │
│ │ Current: [0.5 ] Default: 0.5 [Save] │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ ... (275 settings, virtualized/paginated) ... │
│ │
└─────────────────────────────────────────────────────────────┘
```
### Considerations
1. **Persistence**: Settings changes are in-memory only. Document that restarts reset to defaults.
2. **Validation**: Validate numeric ranges where applicable (e.g., percentages 0-100)
3. **Categories**: Consider grouping settings by prefix (AI*, Combat*, Economy*, etc.)
4. **Audit log**: Log setting changes with timestamp for debugging
---
## Feature 3: Game Rewind
### Concept
Restore a game to a previous point in its action history. This is useful for:
- Debugging issues that occurred at a specific point
- Testing "what if" scenarios
- Recovering from bugs that corrupted state
### New gRPC Endpoint
Add to `eagle.proto`:
```protobuf
message RewindGameRequest {
int64 game_id = 1;
int32 target_action_count = 2; // Rewind to state after this many actions
}
message RewindGameResponse {
bool success = 1;
string error = 2;
int32 new_action_count = 3;
int32 disconnected_clients = 4; // Number of clients that were disconnected
}
service Eagle {
// ... existing methods ...
rpc RewindGame(RewindGameRequest) returns (RewindGameResponse);
}
```
### Eagle Server Implementation
The `GameHistory` already stores `ActionWithResultingState` for each action, which includes the `GameState` after that action. Rewinding means:
1. **Validate**: Check that `target_action_count` is within valid range (0 to current count)
2. **Get target state**: Retrieve `GameState` at target action count from history
3. **Disconnect clients**: Close all human player connections (they'll need to reconnect)
4. **Replace engine**: Create new `EngineImpl` with target state and truncated history
5. **Reset AI state**: Clear any cached AI state that depends on current game state
```scala
// GameController.scala (pseudocode)
def rewindTo(targetActionCount: Int): Either[String, RewindResult] = {
if (targetActionCount < 0 || targetActionCount > engine.history.count)
return Left(s"Invalid action count: $targetActionCount")
// Get state at target point
val targetState = engine.history.stateAt(targetActionCount)
val truncatedHistory = engine.history.truncateTo(targetActionCount)
// Disconnect all human clients
val disconnectedCount = humanClients.length
humanClients.foreach(_.disconnect("Game rewound by admin"))
// Create new engine at target state
val newEngine = EngineImpl(
gameId = engine.gameId,
currentState = targetState,
history = truncatedHistory,
// ... other fields
)
// Replace controller's engine
this.engine = newEngine
Right(RewindResult(targetActionCount, disconnectedCount))
}
```
### GameHistory Enhancement
Add method to get state at a specific action count:
```scala
trait GameHistory {
// ... existing methods ...
def stateAt(actionCount: Int): GameState = {
if (actionCount == 0) initialState
else all(actionCount - 1).resultingState
}
def truncateTo(actionCount: Int): GameHistory = {
GameHistoryImpl(
initialState = initialState,
actions = all.take(actionCount)
)
}
}
```
### Admin Server Route
| Route | Method | Description |
|-------|--------|-------------|
| `/games/{id}/rewind` | POST | Rewind game (form: `target_action_count`) |
| `/games/{id}/rewind/confirm` | GET | Confirmation modal (htmx partial) |
### Rewind UI Flow
1. User views game history
2. User clicks "Rewind to here" on an action row
3. Confirmation modal appears via htmx:
```
┌─────────────────────────────────────────┐
│ Rewind Game abc123f? │
│ │
│ This will: │
│ • Restore to action 456 (Round 23) │
│ • Discard 778 subsequent actions │
│ • Disconnect 2 connected players │
│ │
│ This cannot be undone. │
│ │
│ [Cancel] [Rewind] │
└─────────────────────────────────────────┘
```
4. On confirm, POST to `/games/{id}/rewind`
5. Success: redirect to game detail showing new state
6. Error: show error message
### Safety Considerations
1. **No undo**: Rewinding discards history. Consider optional backup before rewind.
2. **Client disconnect**: All connected clients are forcibly disconnected.
3. **AI state**: Ensure AI clients restart cleanly after rewind.
4. **Concurrent access**: Lock game during rewind to prevent race conditions.
5. **Authorization**: In production, require admin authentication.
---
## Implementation Phases
### Phase 1: Web UI Foundation
**Status: Complete**
1. ✅ Set up Go templates with `embed`
2. ✅ Add Pico CSS and htmx
3. ✅ Create base layout with navigation
4. ✅ Convert `/games` to HTML with styling
5. ✅ Add game detail page with history table
6. ✅ Implement htmx infinite scroll for history
7. ✅ Reverse history order (most recent first)
8. ✅ Clickable action rows that expand to show JSON representation
9. ✅ Add `/games/{id}/action/{index}` endpoint for fetching action details
**Deliverable**: Browsable game list and history in HTML with clickable action details
### Phase 2: Settings Management
**Status: Complete**
1. ✅ Add `GetSettings` to `eagle.proto` (uses existing `AddSettings` for updates)
2. ✅ Add `getAllSettings` method to auto-generated `SettingsLoader`
3. ✅ Implement `getSettings` in `EagleServiceImpl`
4. ✅ Create settings list page with live search
5. ✅ Add inline editing with htmx
6. ✅ Modified settings are highlighted
**Deliverable**: View and edit settings via admin UI
### Phase 3: Game Rewind
**Status: Complete**
1. ✅ Add `RewindGame` to `eagle.proto`
2. ✅ Implement `stateAt` and `truncateTo` in `GameHistory`
3. ✅ Implement rewind logic in `Engine` and `GameController`
4. ✅ Add rewind confirmation (htmx `hx-confirm` dialog)
5. ✅ Handle client disconnection gracefully
6. ✅ Add rewind button to history rows
7. ✅ Implement `rewindGame` in `GamesManager` and `EagleServiceImpl`
8. ✅ Add admin server `/games/{id}/rewind` POST handler
9. ✅ Add success/error feedback UI
**Deliverable**: Rewind games to any previous action
### Phase 4: Polish
**Status: Not Started**
#### High Priority
1. **Add tests for rewind functionality**
- `PersistedHistory.truncateTo` (handles complex persisted vs recent logic)
- `InMemoryHistory.truncateTo`
- `EngineImpl.rewindTo`
- `GameController.rewindTo`
- `GamesManager.rewindGame`
2. **Improve action history display**
- Human-readable action type names (e.g., "New Round" instead of "NewRoundAction")
- Show acting faction/province when available
- Action summaries from the `summary` field in `GameHistoryEntry`
#### Medium Priority
3. **Settings improvements**
- Group settings by category prefix (AI*, Combat*, Economy*, etc.)
- Show setting descriptions where available
- Pagination for large settings lists
4. **Error handling improvements**
- Better error messages on failed operations
- Retry logic for transient gRPC failures
#### Low Priority (Nice to Have)
5. **Basic auth** - HTTP Basic Auth or OAuth for production use
6. **Audit logging** - Log admin actions with timestamps
7. **Documentation** - Usage guide, deployment notes
#### Future Considerations
- Game creation from admin UI
- Player management (view connected players, force disconnect)
- Export game history to file
- Metrics/stats dashboard
---
## Security Notes
The admin server is intended for local/trusted network use only. For production:
1. **Do not expose to public internet** without authentication
2. Consider adding HTTP Basic Auth or OAuth
3. Run on internal network or behind VPN
4. Log all admin actions for audit trail
---
## Open Questions
1. **Settings persistence**: Should we add optional persistence to disk/database?
2. **Game snapshots**: Should rewind create a backup first?
3. **Multi-admin**: Need locking if multiple admins access simultaneously?
4. **Shardok settings**: Are there Shardok (C++) settings to expose too?
+240
View File
@@ -0,0 +1,240 @@
# Eagle0 Media Asset Audit
This document catalogs all media assets in the Unity project for licensing review.
**Total Assets:** ~12,500 files | **Size:** 1.4 GB
---
## Summary by Category
| Category | Count | Notes |
|----------|-------|-------|
| Images | 10,637 | Mostly PNG icons and UI sprites |
| Audio | 1,778 | 26 music tracks + 1,752 sound effects |
| 3D Models | 52 | Bridge pack only |
| Fonts | 16 | TTF files |
---
## 1. Purchased Asset Store Packages
These are commercial Unity Asset Store purchases tied to your account:
### 4000_Fantasy_Icons
- **Location:** `Assets/4000_Fantasy_Icons/`
- **Size:** 495 MB (5,621 PNG files)
- **Contents:** Icons for armor, weapons, skills, resources
- **License:** Unity Asset Store (check invoice/account)
### GUI Pro Kit Fantasy RPG
- **Location:** `Assets/GUI Pro Kit Fantasy RPG/`
- **Size:** 117 MB (3,755 PNG files)
- **Contents:** UI sprites, animations, prefabs
- **Includes fonts:** Alata-Regular.ttf, JosefinSans-Bold.ttf
- **License:** Unity Asset Store
### Modern UI Pack v4.2.0
- **Location:** `Assets/Modern UI Pack/`
- **Size:** 40 MB (191 PNG files)
- **Author:** Michsky (support@michsky.com)
- **Website:** https://www.michsky.com
- **Includes fonts:** Open Sans family (12 variants)
- **License:** Unity Asset Store
### Pixel Fonts Megapack
- **Location:** `Assets/Pixel Fonts Megapack/`
- **Publisher ID:** 17384
- **Author:** @pixelmush_ on Twitter
- **Asset Store Link:** http://u3d.as/w4v
- **License:** Unity Asset Store
### TileableBridgePack
- **Location:** `Assets/TileableBridgePack/`
- **Size:** 3.1 MB (52 FBX models)
- **Contents:** Bridge construction pieces
- **License:** Unity Asset Store
### Fantasy Interface Sounds
- **Location:** `Assets/Fantasy Interface Sounds/`
- **Count:** 320 WAV files
- **Contents:** UI sounds (bag, book, coins, dice, etc.)
- **License:** Unity Asset Store (verify)
### Medieval Combat Sounds
- **Location:** `Assets/Medieval Combat Sounds/`
- **Count:** 1,072 WAV files
- **Contents:** Footsteps, swings, shields, weapons, magic
- **License:** Unity Asset Store (verify)
### Magic Spells Sound Effects LITE
- **Location:** `Assets/Magic Spells Sound Effects LITE/`
- **Count:** 254 WAV files
- **Contents:** Spell casting, element effects
- **Note:** "LITE" version - check if restrictions apply
- **License:** Unity Asset Store (verify)
---
## 2. Creative Commons Music (Properly Licensed)
**Location:** `Assets/Resources/Music/`
**Documentation:** `Music Credits.txt` (attribution file exists)
All 26 tracks have CC licenses with proper attribution:
| Track | Artist | License |
|-------|--------|---------|
| A Robust Crew | Darren Curtis | CC BY 3.0 |
| Asian Graveyard | Darren Curtis | CC BY 3.0 |
| Fall From Grace | Darren Curtis | CC BY 3.0 |
| Samurai Sake Showdown | Darren Curtis | CC BY 3.0 |
| Deflector | Ghostrifter Official | CC BY-SA 3.0 |
| Chase | Alexander Nakarada | CC BY 4.0 |
| Wintersong | Alexander Nakarada | CC BY 4.0 |
| One Bard Band | Alexander Nakarada | CC BY 4.0 |
| Now We Ride | Alexander Nakarada | CC BY 4.0 |
| The Northern Path | Alexander Nakarada | CC BY 4.0 |
| Victory | MaxKoMusic | CC BY-SA 3.0 |
| Sakuya2 | PeriTune | CC BY 3.0 |
| Under The Sun | Keys of Moon | CC BY 4.0 |
| One Piece of Summer | Keys of Moon | CC BY 4.0 |
| Fluffing a Duck | Kevin MacLeod | CC BY 3.0 |
| Space Jazz | Kevin MacLeod | CC BY 3.0 |
| The Ice Giants | Kevin MacLeod | CC BY 4.0 |
| Epic Cinematic Trailer ELITE | Alex-Productions | CC BY 3.0 |
| Push | Alex-Productions | CC BY 3.0 |
| Virus | Alex-Productions | CC BY 3.0 |
| Duel | Makai Symphony | CC BY-SA 3.0 |
| Dragon Castle | Makai Symphony | CC BY-SA 3.0 |
| Durandal | Makai Symphony | CC BY-SA 3.0 |
**Tracks without specific license (verify):**
- Market Day
- Shopping List
- Medieval: Victory Theme
- Tracks by Dima Koltsov (AUDIUS): No Time for Greatness, Warriors of Demacia, Forest Queen Tale, Valor, Clouds
---
## 3. CC0 / Public Domain Assets
### SimpleFileBrowser Icons
- **Location:** `Assets/Plugins/SimpleFileBrowser/Sprites/FileIcons/`
- **License:** CC0 (documented in LICENSE.txt)
- **Source:** pngrepo.com
- **Items:** Archive, Audio, Default, Drive, Folder, Image, PDF, Text, Video icons
---
## 4. Potentially Problematic Assets (Review Needed)
### Stock Images (Possible License Issues)
These appear to be stock images that may have been used as placeholders:
| File | Concern |
|------|---------|
| ~~`Assets/Eagle/79066358-stock-illustration-raster-illustration-medieval-purse-bag...jpg`~~ | **DELETED** (2025-01-04) |
| ~~`Assets/Images/kisspng-hammer-hand-saws-tool-clip-art...jpg`~~ | **DELETED** (2025-01-04) |
| ~~`Assets/Images/lee-ermy-cropped.jpg`~~ | **DELETED** (2025-01-04) |
| ~~`Assets/Eagle/images.jpeg`~~ | **DELETED** (2025-01-04) |
### Clip Art (Unknown License)
| File | Concern |
|------|---------|
| `Assets/Shardok/commandImages/bridge.png` | Clip art style wooden bridge, unknown source - **needs replacement** |
| `Assets/Images/startFire.png` | Icon, unknown source - **needs verification or replacement** |
### Shardok Sound Effects
- **Location:** `Assets/Shardok/soundEffects/`
- **Count:** 56 MP3 files
- **Contents:** Spell effects, movement, combat sounds
- **Status:** Unknown origin - may be custom or need verification
### Free Icons
- **Location:** `Assets/free_icons/`
- **Count:** 8 PNG weather icons
- **Status:** Verify "free" means commercially usable
### Terrain Hexes
- **Location:** `Assets/Terrain Hexes/`
- **Count:** 85 PNG files
- **Status:** Unknown source - verify licensing
### StrategyGameIcons
- **Location:** `Assets/StrategyGameIcons/`
- **Count:** 138 PNG files
- **Status:** Unknown source - verify licensing
---
## 5. Fonts
| Font | Location | License |
|------|----------|---------|
| Open Sans (12 variants) | Modern UI Pack | Apache 2.0 (Google Font) |
| Alata-Regular | GUI Pro Kit | SIL OFL (Google Font) |
| JosefinSans-Bold | GUI Pro Kit | SIL OFL (Google Font) |
| LiberationSans | TextMesh Pro | SIL OFL |
| NotoColorEmoji | Assets root | SIL OFL (Google) |
| Stoke-Light, Stoke-Regular | Assets root | SIL OFL (Google Font) |
All fonts appear to be open-source Google Fonts or Liberation fonts - should be fine.
---
## 6. Third-Party Code Packages
NuGet packages in `Assets/Packages/` all include LICENSE.TXT files:
- Microsoft.Extensions.* - MIT License
- System.* - MIT License
- Grpc.* - Apache 2.0
---
## Action Items
### Must Verify Before Opening Public Access:
1. ~~**Stock images** - The JPG files with stock image filenames need review.~~ **DONE** - Deleted lee-ermy, kisspng, stock-illustration, Yosemite Sam, and images.jpeg (2025-01-04)
2. **Clip art images** - Unknown license, need replacement with properly licensed alternatives:
- `Assets/Shardok/commandImages/bridge.png` - wooden bridge icon
- `Assets/Images/startFire.png` - fire icon
3. **Shardok sound effects** - 56 MP3 files of unknown origin. Either:
- Document their source
- Replace with known-licensed alternatives
- Confirm they were custom-created
4. **Terrain Hexes** - 85 hex tiles of unknown source
- **TODO:** Confirm if this is a Unity Asset Store purchase (owner believes it is)
5. **StrategyGameIcons** - 138 icons of unknown source
- **TODO:** Investigate origin - check Unity Asset Store purchase history
6. **AUDIUS music tracks** - Verify Dima Koltsov tracks are licensed for commercial use
7. **Discord logo** (`Eagle/Discord-Logo-Blurple.png`) - Likely fine for "Login with Discord" button per Discord brand guidelines, but verify usage complies with their terms
### Already Safe:
- All Asset Store purchases (license tied to your account)
- CC-licensed music (attribution in Music Credits.txt)
- CC0 SimpleFileBrowser icons
- Google Fonts / Liberation fonts
- NuGet packages
---
## Recommendation
Before removing HTTP basic auth:
1. ~~Delete or replace the 4 suspicious JPG/JPEG files in `Assets/Eagle/` and `Assets/Images/`~~ **DONE** (2025-01-04)
2. Replace clip art images (`bridge.png`, `startFire.png`) with properly licensed alternatives (e.g., from [game-icons.net](https://game-icons.net) CC BY 3.0)
3. Verify source of `Assets/Shardok/soundEffects/` MP3s
4. Verify source of `Assets/Terrain Hexes/` and `Assets/StrategyGameIcons/`
5. If any are from early development with unclear licensing, replace them
The bulk of your assets (95%+) are properly licensed Asset Store purchases or CC content.
+22 -31
View File
@@ -190,24 +190,24 @@ Change APIs to vend Scala `GameState` and `ActionResultT` instead of proto versi
| `RandomStateSequencer.scala` | Threads Scala GameState | ✅ **Complete** |
| `VigorXPApplier.scala` | Has both proto and Scala methods | Scala method exists, delete proto method when unused |
| `PerformForcedTurnBackAction.scala` | Fully protoless | ✅ **Complete** |
| `ResolveBattleAction.scala` | Heavy proto usage | Blocked by proto dependencies |
| `ResolveBattleAction.scala` | ✅ Fully protoless | Complete (PR #5048) |
| `InMemoryHistory.scala` | Stores proto results | Pending - vend Scala types |
| `PersistedHistory.scala` | Stores proto results | Pending - vend Scala types, convert for disk |
| `GameController.scala` | Uses proto for client communication | Keep proto (gRPC boundary) |
### Remaining Proto Usage in Actions
**Progress: 47 of 52 action files (90%) are fully protoless.**
**Progress: 52 of 52 action files (100%) are fully protoless.**
The following 5 actions still have proto usage:
All action files have been migrated to use Scala types:
| Action | Proto Usages | Blocker | Effort |
|--------|--------------|---------|--------|
| `ResolveBattleAction` | 24 | Shardok interface, complex battle logic | High |
| `PerformVassalCommandsPhaseAction` | 3 | `CommandChoiceHelpers` takes proto GameState | Medium |
| `EndHandleRiotsPhaseAction` | 2 | `CommandChoiceHelpers` takes proto GameState | Medium |
| `PerformVassalDefenseDecisionsAction` | 2 | `CommandChoiceHelpers` takes proto GameState | Medium |
| `EndVassalCommandsPhaseAction` | 1 | `CommandChoiceHelpers` takes proto GameState | Medium |
| Action | Status | Notes |
|--------|--------|-------|
| `ResolveBattleAction` | ✅ Complete | PR #5048 - uses Scala GameState and ActionResultApplier |
| `PerformVassalCommandsPhaseAction` | ✅ Complete | Uses Scala types via CommandChoiceHelpers |
| `EndHandleRiotsPhaseAction` | ✅ Complete | Uses Scala types via CommandChoiceHelpers |
| `PerformVassalDefenseDecisionsAction` | ✅ Complete | Uses Scala types via CommandChoiceHelpers |
| `EndVassalCommandsPhaseAction` | ✅ Complete | Uses Scala types via CommandChoiceHelpers |
**Note:** `NewRoundAction` is now fully protoless after converting `ChronicleEventGenerator` to return Scala `ChronicleEvent` types directly.
@@ -223,13 +223,13 @@ The following 5 actions still have proto usage:
| Component | Lines | Complexity | Blocks |
|-----------|-------|------------|--------|
| `CommandChoiceHelpers` to Scala | ~2000 | High | 4 vassal actions |
| `ResolveBattleAction` refactor | ~500 | High | 1 action (complex) |
| History API updates | ~100 | Low | - |
| **Total Remaining** | **~2600** | | |
| **Total Remaining** | **~100** | | |
**Completed:**
- `ChronicleEventGenerator` converted to return Scala `ChronicleEvent` types directly
- `ChronicleEventGenerator` converted to return Scala `ChronicleEvent` types directly
-`CommandChoiceHelpers` migrated to Scala types
-`ResolveBattleAction` refactored to use Scala GameState and ActionResultApplier (PR #5048)
### CommandChoiceHelpers Migration Status
@@ -246,28 +246,18 @@ Several command selectors have already been converted to use Scala types:
| `ImproveCommandSelector.scala` | ✅ **Protoless** | Uses Scala `GameState`, `ProvinceT`, `HeroT` |
| `OrganizeCommandSelector.scala` | ✅ **Protoless** | Uses Scala `GameState`, `BattalionT`, `BattalionType` |
| `RansomOfferHelpers.scala` | ✅ **Protoless** | Uses Scala `GameState`, `FactionT` |
| `CommandChoiceHelpers.scala` | ❌ Proto | Main entry point, converts to Scala when calling converted selectors |
| `ProvinceGoldSurplusCalculator.scala` | **Partial** | Has both Scala and proto overloads |
| Other selectors | ❌ Proto | Various proto dependencies |
| `CommandChoiceHelpers.scala` | **Protoless** | Uses Scala `GameState` throughout |
| `ProvinceGoldSurplusCalculator.scala` | **Protoless** | Uses Scala types |
**Pattern**: `CommandChoiceHelpers` currently uses `GameStateConverter.fromProto(gameState)` when calling already-converted selectors like `AlmsCommandSelector` and `AttackCommandChooser`. This allows incremental migration.
**Next Steps**:
1. ~~Convert `ExpandCommandSelector` to Scala types~~ ✅ Done
2. ~~Convert `ImproveCommandSelector` to Scala types~~ ✅ Done
3. ~~Convert `OrganizeCommandSelector` to Scala types~~ ✅ Done (PR #4812)
4. ~~Convert `RansomOfferHelpers` to Scala types~~ ✅ Done (PR #4821)
5. Convert remaining selectors one at a time
6. Update `CommandChoiceHelpers` to accept Scala `GameState` once all selectors are converted
**All CommandChoiceHelpers selectors have been migrated to Scala types.**
### Progress Summary
| Metric | Value |
|--------|-------|
| Action files fully protoless | 47 / 52 (90%) |
| Proto usages in remaining actions | 32 total |
| Biggest blocker | `ResolveBattleAction` (24 usages) |
| Second biggest blocker | `CommandChoiceHelpers` (blocks 4 actions) |
| Action files fully protoless | 52 / 52 (100%) |
| Proto usages in remaining actions | 0 |
| Next target | History APIs (InMemoryHistory, PersistedHistory) |
### Validation
- [x] `ActionResultApplier` created and tested
@@ -276,8 +266,9 @@ Several command selectors have already been converted to use Scala types:
- [x] `ProvinceViewFilter` has Scala overload for server-side use (PR #4752)
- [x] `FactionT.reconnedProvinces` and `ChangedFactionC.updatedReconnedProvinces` use Scala `ProvinceView`
- [x] `ProvinceViewFilter.withdrawnFromProvinceView` has Scala overload
- [x] `CommandChoiceHelpers` uses Scala types ✅
- [x] All action files (52/52) are fully protoless ✅
- [ ] `ProvinceViewFilter` faction-filtered views use Scala types
- [ ] `CommandChoiceHelpers` uses Scala types
- [ ] History APIs vend Scala types
- [ ] No `ActionResultProtoConverter.toProto()` calls except at persistence/gRPC boundaries
- [ ] All tests pass
+159
View File
@@ -0,0 +1,159 @@
# Hetzner Setup Guide
This guide walks through setting up Hetzner Cloud infrastructure for running Shardok on-demand compute.
## Prerequisites
- All code PRs merged (#4990, #4996, #4998, #5001, #5009)
- Access to DigitalOcean Container Registry (for pulling Shardok ARM64 image)
---
## Step 1: Create Hetzner Cloud Account
1. Go to https://console.hetzner.cloud/
2. Sign up and add payment method
3. Create a new project (e.g., "eagle0")
---
## Step 2: Generate Hetzner API Token
1. In Hetzner Console → Security → API Tokens
2. Click "Generate API Token"
3. Give it **Read & Write** permissions
4. Copy the token (you'll only see it once)
---
## Step 3: Generate Shardok Auth Token
Generate a 256-bit random token for Eagle-Shardok authentication:
```bash
openssl rand -hex 32
```
Save this output - it's the shared secret between Eagle and Shardok.
---
## Step 4: Store Secrets in GitHub Actions
Add these secrets in GitHub → Settings → Secrets and variables → Actions:
| Secret Name | Description |
|-------------|-------------|
| `HETZNER_API_TOKEN` | From Step 2 - for Hetzner API calls |
| `SHARDOK_AUTH_TOKEN` | From Step 3 - shared secret for gRPC auth |
Note: `DO_REGISTRY_TOKEN` already exists and will be used for Hetzner to pull container images.
These secrets will be passed to Eagle at runtime via `docker_build.yml`, similar to how `OPENAI_API_KEY` and other secrets are handled.
---
## Step 5: DNS Setup (for Let's Encrypt)
You need a domain pointing to the Shardok instance for TLS certificates.
### Option A: Floating IP (Recommended)
1. In Hetzner Console → Networking → Floating IPs
2. Create a **Floating IPv6** in **Hillsboro, Oregon (hil)** region
- IPv6 costs €1/month vs €3/month for IPv4
- Hillsboro has better latency to DigitalOcean SFO than Ashburn
- Server-to-server communication works fine with IPv6-only
3. Point `shardok.prod.eagle0.net` to this IP via AAAA record
4. The ShardokInstanceManager will attach this IP to instances on spin-up
**Location choice**: Hillsboro, OR (`hil`) is recommended for US West Coast. Same pricing as Ashburn (`ash`).
### Option B: Dynamic DNS
Update DNS programmatically when instance spins up. More complex but avoids floating IP cost.
---
## Step 6: Upload SSH Key to Hetzner
For debugging access to instances:
1. In Hetzner Console → Security → SSH Keys
2. Click "Add SSH Key"
3. Paste your public key (e.g., `~/.ssh/id_rsa.pub`)
4. Give it a name (e.g., "eagle-deploy")
---
## Step 7: Wire Security Config into Eagle
Update Eagle's startup code to use the security config when connecting to remote Shardok:
```scala
val securityConfig = ShardokSecurityConfig(
useTls = true,
authToken = Some(sys.env("SHARDOK_AUTH_TOKEN"))
)
val channel = ServerSetupHelpers.newChannel(
"shardok.prod.eagle0.net",
50051,
securityConfig
)
```
---
## Testing
### Manual Instance Spin-up
Test the Hetzner integration by triggering instance creation:
```scala
val manager = new ShardokInstanceManager(
hetznerApiToken = sys.env("HETZNER_API_TOKEN"),
// ... other config
)
manager.ensureInstanceRunning()
```
### Verify TLS and Auth
1. Instance spins up and gets Let's Encrypt certificate
2. Eagle connects via TLS
3. Auth token is validated on each request
---
## Cost Estimate
| Component | Cost |
|-----------|------|
| CAX41 (16 ARM cores) | ~$0.04/hour |
| Floating IP | ~$4/month |
| Typical usage (20 hrs/week) | ~$3.50/month compute |
**Total: ~$7-8/month** for typical usage.
---
## Troubleshooting
### Instance won't start
- Check Hetzner API token has Read & Write permissions
- Verify you're using the correct region (`hil` for Hillsboro OR, or `ash` for Ashburn VA)
### TLS certificate fails
- Ensure DNS points to the instance IP before certbot runs
- Check port 80 is open for Let's Encrypt HTTP-01 challenge
### Auth failures
- Verify `SHARDOK_AUTH_TOKEN` matches on both Eagle and Shardok
- Check the token file is readable by Shardok container
### Can't pull container image
- Ensure `DO_REGISTRY_TOKEN` is passed to cloud-init
- Verify the ARM64 image exists: `registry.digitalocean.com/eagle0/shardok-server:arm64-latest`
+383
View File
@@ -0,0 +1,383 @@
# Plan: Extract OAuth to Go Service
## Goal
Move OAuth authentication handling from the Eagle Scala server into a separate Go service. This simplifies Eagle (gRPC-only, no HTTP), reduces complexity, and sets up for potentially moving JWT validation outside Eagle too.
## Architecture Decision: Sidecar Service (Not DO Functions)
**Recommendation: Go sidecar service on the same droplet, in a separate container**
**Why not DO Functions:**
- OAuth requires **stateful sessions** (pendingOAuth/completedOAuth maps with 10-min TTL)
- Client polling pattern (every 2 seconds) would incur high function invocation costs
- Cold start latency problematic for auth flows
- State would require external store (Redis), adding complexity
**Why sidecar (separate container):**
- Simple process on same droplet, minimal network latency
- In-memory state management (like current Scala impl)
- Easy to monitor/debug alongside Eagle
- Can share filesystem for key files (RSA keys) via volume mounts
- **Independent deployment**: Deploying Eagle doesn't restart auth service (and vice versa)
- **Independent scaling**: Could move to separate droplet later if needed
## Current Architecture (What Exists)
```
Unity Client
├── GetOAuthUrl RPC → Eagle AuthServiceImpl → OAuthService.getAuthUrl()
├── [User browser auth] → HTTP callback → OAuthHttpHandler → OAuthService.handleCallback()
├── CheckOAuthStatus RPC (polling) → AuthServiceImpl → OAuthService.checkStatus()
└── All other RPCs include JWT → AuthorizationInterceptor validates
```
**Key files:**
- `src/main/scala/net/eagle0/eagle/auth/OAuthService.scala` - OAuth flow, state management
- `src/main/scala/net/eagle0/eagle/auth/JwtService.scala` - JWT creation/validation
- `src/main/scala/net/eagle0/eagle/auth/UserService.scala` - User CRUD (persisted)
- `src/main/scala/net/eagle0/eagle/service/AuthServiceImpl.scala` - gRPC Auth service
- `src/main/scala/net/eagle0/eagle/service/OAuthHttpHandler.scala` - HTTP callback handler
## Target Architecture (Phase 1)
```
Unity Client
├── GetOAuthUrl RPC ──────────────┐
├── CheckOAuthStatus RPC (polling)├──→ Eagle (port 40032) ──proxy──→ Go Auth Container (port 40033)
├── RefreshToken RPC ─────────────┘ │
├── [User browser] → HTTP callback ────────────────────────────────────────┤
│ ↓
│ (Internal gRPC: GetOrCreateUser, GetUser)
│ ↓
└── Game RPCs with JWT ─────────────────────→ Eagle (port 40032) ← JWT validation stays here
[Same Droplet]
┌─────────────────────────────────────────────────────────────────────────────┐
│ │
│ ┌──────────────────────┐ ┌────────────────────────────────────┐ │
│ │ Go Auth Container │◄────────►│ Eagle Container │ │
│ │ (eagle0-auth) │ internal │ (eagle0-server) │ │
│ │ │ gRPC │ │ │
│ │ - OAuth flow │ │ - JWT validation │ │
│ │ - JWT creation │ │ - UserService (persistence) │ │
│ │ - HTTP callback │ │ - Game logic │ │
│ └──────────────────────┘ └────────────────────────────────────┘ │
│ │ │ │
│ └────────────────┬───────────────────────┘ │
│ ▼ │
│ /etc/eagle0/keys/ (shared volume) │
│ - private.pem │
│ - public.pem │
└─────────────────────────────────────────────────────────────────────────────┘
```
## Component Responsibilities
### Go Auth Service (NEW - separate container)
- **OAuth flow**: getAuthUrl, handleCallback (HTTP), checkStatus
- **State management**: pendingOAuth, completedOAuth maps with TTL
- **JWT creation**: Issue access/refresh tokens (shares RSA private key with Eagle)
- **Token refresh**: Validate refresh token, issue new access token
- Calls Eagle's internal UserService gRPC to find/create users
### Eagle Server (SIMPLIFIED)
- **JWT validation**: AuthorizationInterceptor stays (validates tokens on game RPCs)
- **UserService**: Stays in Eagle (user persistence, display name logic)
- **New internal gRPC**: Expose GetOrCreateUser, GetUser for Go service to call
- **Proxy (Phase 1)**: Forward OAuth RPCs to Go service
- **Remove (Phase 2)**: OAuthService, OAuthHttpHandler, HTTP server setup
### Unity Client (NO CHANGES in Phase 1)
- Eagle proxies Auth RPCs to Go service
- Client still connects to Eagle on port 40032
## Implementation Phases
### Phase 1: Go Auth Service with Eagle Proxy (Zero Client Changes)
1. **Create Go service structure**
```
src/main/go/net/eagle0/authservice/
├── main.go # Entry point, starts gRPC + HTTP servers
├── oauth.go # OAuth state management, provider configs
├── jwt.go # JWT creation (copy logic from Scala)
├── handlers.go # gRPC handlers for Auth service
├── http_callback.go # HTTP handler for OAuth callback
└── BUILD.bazel
```
2. **Internal gRPC proto for Eagle UserService**
```protobuf
// src/main/protobuf/net/eagle0/eagle/internal/auth_internal.proto
service InternalUserService {
rpc GetOrCreateUser(GetOrCreateUserRequest) returns (GetOrCreateUserResponse);
rpc GetUser(GetUserRequest) returns (GetUserResponse);
}
message GetOrCreateUserRequest {
string provider = 1; // "discord" or "google"
string provider_user_id = 2;
string email = 3;
string avatar_url = 4;
}
message GetOrCreateUserResponse {
string user_id = 1;
string display_name = 2;
string avatar_url = 3;
bool is_admin = 4;
bool is_new_user = 5;
}
```
3. **Eagle: Expose InternalUserService**
- New `InternalUserServiceImpl.scala` wrapping UserService
- Bind to same port, different service name (internal only)
4. **Eagle: Proxy Auth RPCs to Go**
- AuthServiceImpl delegates GetOAuthUrl, CheckOAuthStatus, RefreshToken to Go service
- SetDisplayName, GetCurrentUser, Logout stay in Eagle
5. **Share RSA keys via volume mount**
- Go service reads same key files as Eagle
- Both can create valid JWTs
- Eagle continues to validate JWTs
6. **Docker/Container setup**
- New Dockerfile for Go auth service
- docker-compose or Kubernetes config for both containers
- Shared volume for /etc/eagle0/keys/
- Internal network for container-to-container gRPC
### Phase 2: Client Direct to Go Service (Future)
1. **Update Unity client**
- Connect to Go Auth service directly for OAuth RPCs
- Keep connecting to Eagle for game RPCs
2. **Remove Eagle proxy code**
- Delete AuthServiceImpl OAuth delegation
- AuthServiceImpl only handles SetDisplayName, GetCurrentUser, Logout
### Phase 3: Move JWT Validation to Go (Optional Future)
1. **Go service validates JWTs**
- Add ValidateToken RPC or use shared middleware pattern
2. **Eagle calls Go for validation**
- AuthorizationInterceptor calls Go to validate tokens
- OR: Use stateless validation (both share public key)
## Files to Create
### Go Service
- `src/main/go/net/eagle0/authservice/main.go`
- `src/main/go/net/eagle0/authservice/oauth.go`
- `src/main/go/net/eagle0/authservice/jwt.go`
- `src/main/go/net/eagle0/authservice/handlers.go`
- `src/main/go/net/eagle0/authservice/http_callback.go`
- `src/main/go/net/eagle0/authservice/BUILD.bazel`
### Protos
- `src/main/protobuf/net/eagle0/eagle/internal/auth_internal.proto`
### Scala
- `src/main/scala/net/eagle0/eagle/service/InternalUserServiceImpl.scala`
### Docker/Deployment
- `ci/auth_service.Dockerfile`
- Update `docker-compose.yml` (or equivalent)
## Files to Modify
### Scala (Phase 1)
- `src/main/scala/net/eagle0/eagle/service/AuthServiceImpl.scala` - Proxy OAuth RPCs to Go
- `src/main/scala/net/eagle0/eagle/Main.scala` - Start internal user service, add auth-service-url flag
### Scala (Phase 2 - Removal)
- Delete `src/main/scala/net/eagle0/eagle/auth/OAuthService.scala`
- Delete `src/main/scala/net/eagle0/eagle/service/OAuthHttpHandler.scala`
- Simplify `src/main/scala/net/eagle0/eagle/Main.scala` - Remove HTTP server
### Unity (Phase 2)
- `Assets/Auth/OAuthManager.cs` - Point OAuth RPCs to Go service port
- `Assets/EagleConnection.cs` - Add second channel for auth service
## Key Implementation Details
### State Management in Go
```go
type OAuthState struct {
Provider string
CreatedAt time.Time
}
type OAuthResult struct {
Success bool
UserInfo *ProviderUserInfo
Provider string
Error string
}
var pendingOAuth = sync.Map{} // state -> OAuthState
var completedOAuth = sync.Map{} // state -> OAuthResult
const stateExpiration = 10 * time.Minute
// Background goroutine cleans expired states every minute
func cleanupExpiredStates() {
ticker := time.NewTicker(1 * time.Minute)
for range ticker.C {
cutoff := time.Now().Add(-stateExpiration)
pendingOAuth.Range(func(key, value any) bool {
if value.(OAuthState).CreatedAt.Before(cutoff) {
pendingOAuth.Delete(key)
}
return true
})
// Similar for completedOAuth
}
}
```
### JWT Creation in Go
```go
import "github.com/golang-jwt/jwt/v5"
type EagleClaims struct {
jwt.RegisteredClaims
UserId string `json:"userId"`
DisplayName string `json:"displayName"`
IsAdmin bool `json:"isAdmin"`
}
func CreateAccessToken(userId, displayName string, isAdmin bool) (string, error) {
claims := EagleClaims{
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(7 * 24 * time.Hour)),
IssuedAt: jwt.NewNumericDate(time.Now()),
},
UserId: userId,
DisplayName: displayName,
IsAdmin: isAdmin,
}
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
return token.SignedString(privateKey)
}
```
### OAuth Provider Configs
- Read from environment variables (same as current OAuthConfig.scala)
- DISCORD_CLIENT_ID, DISCORD_CLIENT_SECRET
- GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET
- OAUTH_CALLBACK_URL (e.g., https://eagle0.shardok.games/oauth/callback)
### Container Networking
```yaml
# docker-compose.yml example
services:
eagle0-auth:
build:
context: .
dockerfile: ci/auth_service.Dockerfile
ports:
- "40033:40033" # gRPC
- "8080:8080" # HTTP callback
volumes:
- ./keys:/etc/eagle0/keys:ro
environment:
- DISCORD_CLIENT_ID
- DISCORD_CLIENT_SECRET
- GOOGLE_CLIENT_ID
- GOOGLE_CLIENT_SECRET
- EAGLE_INTERNAL_URL=eagle0-server:40034
eagle0-server:
build:
context: .
dockerfile: ci/eagle_run.Dockerfile
ports:
- "40032:40032" # Public gRPC
expose:
- "40034" # Internal gRPC (container-to-container only)
volumes:
- ./keys:/etc/eagle0/keys:ro
- ./data:/var/lib/eagle0
environment:
- AUTH_SERVICE_URL=eagle0-auth:40033
```
## Deployment
### Development
```bash
# Terminal 1: Go Auth Service
bazel run //src/main/go/net/eagle0/authservice:authservice -- \
--grpc-port=40033 \
--http-port=8080 \
--eagle-internal-url=localhost:40034
# Terminal 2: Eagle Server
bazel run //src/main/scala/net/eagle0/eagle:eagle_server -- \
--eagle-grpc-port=40032 \
--internal-grpc-port=40034 \
--auth-service-url=localhost:40033
```
### Production
- Both containers on same droplet via docker-compose
- Shared volume for RSA keys at /etc/eagle0/keys/
- Internal Docker network for container-to-container communication
- External access: 40032 (Eagle gRPC), 8080 (OAuth HTTP callback)
## Testing Strategy
1. **Unit tests for Go service**
- OAuth state management (expiration, cleanup)
- JWT creation matches Scala output (test with same keys)
- HTTP callback parsing
2. **Integration tests**
- Go service ↔ Eagle internal gRPC
- Full OAuth flow with mock provider
3. **Existing tests continue to pass**
- All Scala tests (JWT validation, user service)
4. **End-to-end test**
- Spin up both containers
- Run OAuth flow through proxy
## Risks and Mitigations
| Risk | Mitigation |
|------|------------|
| Key file permissions | Shared volume with read-only mount |
| State loss on Go restart | Document this (same as current Scala behavior); consider Redis later |
| Clock skew affecting JWT | Both on same machine |
| OAuth callback race | HTTP callback completes before gRPC poll |
| Container networking | Use docker-compose for reliable internal DNS |
| Proxy adds latency | Minimal (same machine), remove in Phase 2 |
## Estimated Scope
- **Phase 1**: ~500-700 lines Go, ~100 lines Scala changes, ~50 lines Docker config
- **Phase 2**: ~50 lines Unity, deletion of ~300 lines Scala
- **Phase 3**: Optional, separate decision
## Alternative Considered: Move Everything to Go
Could move UserService to Go as well, but:
- UserService is tightly integrated with game persistence
- Would require duplicating persistence layer
- Not worth the complexity for now
Keep UserService in Eagle, expose via internal gRPC.
## Open Questions
1. **HTTP callback routing**: Does the OAuth callback URL need to change, or can we route traffic from the existing URL to the new Go service?
2. **Health checks**: Should we add health check endpoints for container orchestration?
3. **Logging**: Should Go service log to same format/destination as Eagle?
+350
View File
@@ -0,0 +1,350 @@
# OAuth Implementation: Next Steps and Design
## Executive Summary
The OAuth implementation is functional but has several gaps that need addressing before it's production-ready. This document outlines the known issues, proposes a comprehensive user identity model, and provides a prioritized implementation plan.
## Current State (Updated January 2026)
### What Works ✅
- Discord OAuth flow (server-mediated polling)
- Google OAuth flow
- JWT token generation and validation
- User creation and display name setting
- Auto-login with stored tokens
- Basic game creation and play with OAuth users
- Headshot fetching via public CDN (no auth required)
- Logout button in lobby (preserves tokens for quick reconnect)
- Environment (prod/qa) and user display in lobby
- Game identity with userName = displayName (PR #4964 merged)
### Known Issues
#### 1. Game Identity Model Fragility (Deferred)
**Status**: Accepted for now. PR #4964 merged with `userName = displayName`.
**Current behavior**:
- Games store `userNameToFactionId: Map[String, Int]`
- For JWT users, this maps displayName → factionId
- displayName is technically mutable (users could change it)
- No migration path when displayName changes
**Why this is acceptable**:
1. We don't currently have a "change display name" feature
2. The alternative (using userId) requires more extensive changes
3. Can migrate to userId-based identity later if needed
#### 2. In-Game Headshot Fetching ✅ FIXED
**Solution**: Made the `eagle0-headshots` S3 bucket public and enabled CDN.
- Client now fetches directly from `https://eagle0-headshots.sfo3.cdn.digitaloceanspaces.com/`
- No authentication required
- Works for both OAuth and Basic Auth users
- Simpler architecture, no dependency on home Mac server
#### 3. Logout from Lobby ✅ FIXED
**Solution**: Added logout button to lobby UI (PR #4967).
- Button disconnects from server and returns to connection screen
- Intentionally does NOT clear OAuth tokens
- Allows quick reconnect with same account without full OAuth flow
#### 4. Display Name Uniqueness Not Enforced (Medium) - OPEN
**Problem**: User was able to set displayName "nolen" when that name was already taken.
**Root cause**: Unknown - needs investigation. Either:
- The uniqueness check is buggy
- The displayNameIndex wasn't populated correctly during user creation
- Race condition during concurrent registrations
#### 5. Admin Server Crashes ✅ FIXED
**Solution**: PR #4964 sets `userName = displayName` for JWT users.
#### 6. Intermittent "Expired" Errors During Login (Medium) - INVESTIGATING
**Problem**: Users occasionally get "OAuth session expired" errors even when server logs show the callback succeeded.
**Status**: Added diagnostic logging in PR #4974 to trace:
- State creation in `getAuthUrl`
- State lookup in `handleCallback`
- Result lookup in `checkStatus`
**Possible causes**:
- State mismatch between client and server
- Race condition in polling
- Cleanup running at wrong time
#### 7. Token Expiry Field Bug ✅ FIXED
**Problem**: `CheckOAuthStatusResponse.expiresAt` was returning refresh token expiry (30 days) instead of access token expiry (7 days).
**Solution**: Fixed in PR #4974 to calculate correct access token expiry.
---
## Proposed User Identity Model
### Design Principles
1. **Stable Internal Identity**: `userId` (UUID) is the only key used for persistent associations
2. **Display Name is Cosmetic**: Can change without breaking game associations
3. **Backwards Compatibility**: Basic Auth continues to work for local development
4. **Multi-Provider Support**: Users can link Discord, Google, and future providers
5. **Avatar Flexibility**: Use OAuth avatar by default, support custom uploads later
### Data Model
```
User {
userId: String (UUID) // Primary key, immutable, used for all internal references
displayName: String // Unique, user-visible, mutable with migration
displayNameLower: String // Case-insensitive uniqueness
email: String // Primary email for account recovery/linking
avatarUrl: String // Current avatar URL
avatarData: bytes // Cached avatar for offline/fast access (future)
oauthIdentities: [OAuthIdentity]
createdAt: Timestamp
lastLoginAt: Timestamp
isAdmin: Boolean
}
OAuthIdentity {
provider: String // "discord", "google", etc.
providerUserId: String // Provider's user ID
providerEmail: String // Email from this provider
avatarUrl: String // Avatar from this provider
linkedAt: Timestamp
}
```
### Identity Resolution Strategy
The key question: **What should `AuthorizationUtils.userName` return?**
#### Option A: userName = displayName (Current PR #4964)
- **Pro**: Human-readable in logs, game saves, debugging
- **Con**: Breaks if displayName changes
- **Migration**: None needed now, complex later
#### Option B: userName = userId (Recommended)
- **Pro**: Stable identity, displayName changes are safe
- **Con**: UUIDs in logs are ugly, need display name lookup for UI
- **Migration**: Cleaner long-term, but breaking change for any existing OAuth games
#### Option C: Hybrid with Migration Support
- **userName** = userId for new games
- **Legacy lookup** for old games by displayName
- **Display layer** resolves userId → displayName for UI
**Recommendation**: Option B with a display name resolution layer. The ugliness in logs is acceptable for the stability it provides. Implement a `UserService.resolveDisplayName(identifier: String): String` that returns displayName for UUIDs or the identifier itself for legacy usernames.
### Account Linking Strategy
#### Automatic Linking (Future)
When a user logs in with a new OAuth provider:
1. Check if the provider email matches an existing user's email
2. If match found, prompt: "An account exists with this email. Link accounts?"
3. If confirmed, add new OAuthIdentity to existing user
4. If declined, create separate account (different email required)
#### Manual Linking (MVP)
1. User logs in with primary account
2. User goes to Settings → Linked Accounts
3. User clicks "Link Discord" or "Link Google"
4. OAuth flow adds new identity to current user
### Avatar/Headshot Strategy
#### Phase 1: OAuth Avatars (MVP)
- Store `avatarUrl` from OAuth provider during login
- Server proxies avatar requests to avoid CORS issues
- Cache avatars locally with TTL
#### Phase 2: Avatar Caching
- Download avatar to local storage on login
- Serve from local storage for reliability
- Refresh periodically or on login
#### Phase 3: Custom Avatars (Future)
- Allow users to upload custom avatar
- Store in S3/DO Spaces
- Custom avatar overrides OAuth avatar
---
## Implementation Plan
### Phase 1: Stabilization ✅ COMPLETE
#### 1.1 Fix Display Name Uniqueness Bug - OPEN
- [ ] Investigate why "nolen" was allowed when it existed
- [ ] Add logging to `setDisplayName` to trace the issue
- [ ] Ensure `displayNameIndex` is correctly maintained
- [ ] Add unit tests for uniqueness enforcement
#### 1.2 Add Logout Button to Lobby ✅ DONE
- [x] Add "Logout" button to lobby UI
- [x] Disconnect from server
- [x] Navigate to connection screen
- [x] Preserve OAuth tokens for quick reconnect (intentional change from original plan)
#### 1.3 Merge PR #4964 (userName = displayName) ✅ DONE
- [x] Merged - games work with OAuth users
- [x] Documented limitation (games break if displayName changes)
#### 1.4 Fix Headshot Fetching ✅ DONE
- [x] Made eagle0-headshots bucket public
- [x] Client fetches directly from CDN
- [x] No authentication required
#### 1.5 Add Lobby Status Display ✅ DONE
- [x] Show environment (prod/qa) in lobby
- [x] Show current user in lobby (OAuth displayName or classic username)
### Phase 2: Remaining Work (Priority Order)
#### 2.1 Diagnose Intermittent "Expired" Errors - IN PROGRESS
- [x] Add diagnostic logging (PR #4974)
- [ ] Deploy and reproduce the issue
- [ ] Analyze logs to identify root cause
- [ ] Implement fix based on findings
#### 2.2 Fix Display Name Uniqueness
- [ ] Investigate UserService.setDisplayName logic
- [ ] Check displayNameIndex population
- [ ] Add logging to trace the issue
- [ ] Fix the bug and add tests
#### 2.3 Wire Up Lobby UI in Unity
- [ ] Connect `lobbyEnvironmentText` to TextMeshProUGUI in scene
- [ ] Connect `lobbyUserText` to TextMeshProUGUI in scene
#### 2.4 Implement Token Refresh During Gameplay
- [ ] Implement `RefreshToken` RPC on server (currently throws UNIMPLEMENTED)
- [ ] Store refresh tokens server-side for validation
- [ ] Add proactive refresh in client before token expires
- [ ] Handle refresh during reconnection attempts
### Phase 3: Nice-to-Haves (Future)
#### 3.1 Proactive Token Refresh
- [ ] Monitor token expiry in client
- [ ] Refresh automatically when < 5 minutes remaining
- [ ] Update TokenStorage with new access token
#### 3.2 Better Error Messages
- [ ] Distinguish between network errors and auth errors
- [ ] Show user-friendly messages for OAuth failures
- [ ] Add retry suggestions
#### 3.3 Session Persistence Across Server Restarts
- [ ] Move pendingOAuth from in-memory TrieMap to Redis/database
- [ ] Move completedOAuth to Redis with TTL
- [ ] Server can restart without breaking in-flight OAuth flows
#### 3.4 Migrate to userId-based Game Identity (Deferred)
- [ ] Change `AuthorizationUtils.userName` to return `userId` for JWT users
- [ ] Add `UserService.resolveDisplayName(id: String): String` for UI display
- [ ] Update game UI to resolve userIds to displayNames
- [ ] Existing Basic Auth games continue to work (userName is literal)
#### 3.5 Display Name Change Support (Requires 3.4)
- [ ] Add `ChangeDisplayName` RPC
- [ ] Validate new name is unique
- [ ] Update user record
- [ ] No game migration needed (games use userId)
### Phase 3: Multi-Provider Support (Future)
#### 3.1 Account Linking UI
- [ ] Add Settings page with "Linked Accounts" section
- [ ] Show currently linked providers
- [ ] "Link Another Account" button triggers OAuth flow
- [ ] `LinkOAuthProvider` RPC adds identity to current user
#### 3.2 Login Provider Selection
- [ ] If user has multiple providers, any can be used to login
- [ ] All resolve to same userId
- [ ] Session shows which provider was used
#### 3.3 Account Merging (Complex)
- [ ] Handle case where user created separate accounts
- [ ] Merge game history, stats, etc.
- [ ] Delete duplicate user record
- [ ] This is complex - may defer or not implement
### Phase 4: Enhanced Avatars (Future)
#### 4.1 Avatar Caching
- [ ] Download avatars to S3/DO Spaces on login
- [ ] Serve from our CDN
- [ ] Refresh on login if changed
#### 4.2 Custom Avatar Upload
- [ ] Upload endpoint with size/format validation
- [ ] Store in S3/DO Spaces
- [ ] Custom avatar overrides OAuth avatar
---
## Technical Debt to Address
1. **Context Propagation in Futures**: PR #4960 fixed `setDisplayName` and `getCurrentUser`, but audit all `Future` blocks that access `AuthorizationUtils`
2. **Dual Auth Support**: The system supports both Basic Auth and JWT. Consider:
- Should Basic Auth be deprecated for production?
- Should it remain for local development only?
- How do Basic Auth users interact with OAuth users in the same game?
3. **Token Refresh**: `RefreshToken` RPC throws UNIMPLEMENTED. Need to:
- Implement refresh token storage and validation
- Handle token refresh in client
- Consider refresh token rotation for security
4. **Session Management**: No server-side session tracking. Consider:
- Track active sessions per user
- Allow "logout all devices"
- Detect concurrent logins
---
## Open Questions
1. **What happens when a Basic Auth user and OAuth user have the same name?**
- Currently possible - Basic Auth doesn't check UserService
- Could cause confusion in games
- Solution: Require OAuth for multiplayer? Or namespace Basic Auth names?
2. **Should displayName changes be allowed?**
- With userId-based identity, it's safe
- But could cause confusion ("who is this new player?")
- Consider: rate limit changes, show "formerly known as" temporarily
3. **How to handle OAuth provider account deletion?**
- User deletes their Discord account
- Their Eagle0 account still exists
- They can't login unless they linked another provider
- Solution: Encourage linking multiple providers, or add email/password fallback
4. **Admin impersonation with OAuth**
- Currently works via X-Impersonate-User header
- Should this use userId or displayName?
- Probably userId for stability
---
## Appendix: File Locations
### Server (Scala)
- `src/main/scala/net/eagle0/eagle/auth/UserService.scala` - User CRUD
- `src/main/scala/net/eagle0/eagle/auth/JwtService.scala` - Token generation/validation
- `src/main/scala/net/eagle0/eagle/auth/OAuthService.scala` - OAuth flow
- `src/main/scala/net/eagle0/eagle/service/AuthServiceImpl.scala` - gRPC Auth service
- `src/main/scala/net/eagle0/eagle/service/AuthorizationInterceptor.scala` - Auth middleware
- `src/main/scala/net/eagle0/eagle/service/AuthorizationUtils.scala` - Context accessors
### Client (C#)
- `Assets/Auth/AuthClient.cs` - gRPC client for Auth service
- `Assets/Auth/OAuthManager.cs` - OAuth flow orchestration
- `Assets/Auth/TokenStorage.cs` - Persistent token storage
- `Assets/Auth/JwtAuthInterceptor.cs` - Attaches JWT to requests
### Protos
- `src/main/protobuf/net/eagle0/eagle/api/auth.proto` - Auth service definition
- `src/main/protobuf/net/eagle0/eagle/internal/user/user.proto` - User data model
+216
View File
@@ -0,0 +1,216 @@
# Shardok Latency Hiding Strategies
## Problem Statement
With Shardok running on Hetzner (Helsinki) and Eagle on DigitalOcean (US), the round-trip latency for human commands is ~200-400ms:
```
Human posts command:
Unity → Eagle (DO) → Shardok (Hetzner) → Eagle (DO) → Unity
~10ms ~100ms ~100ms ~10ms
Total: ~220ms round-trip
```
This latency is acceptable for AI turns (users watch animations anyway), but creates noticeable lag when humans post commands.
---
## Strategy 1: Client-Side Animation Masking
### Concept
Start animations immediately when the user clicks, before server confirmation arrives. The animation duration masks the network latency.
### Implementation by Command Type
**Movement Commands** (deterministic):
- Client knows the destination hex and movement path
- Start movement animation immediately on click
- Server confirms the move (should always match)
- If server rejects (invalid state), snap unit back to origin
**Attack Commands** (RNG-dependent):
- Show attack animation immediately (unit swings sword, fires arrow)
- Wait for server to return dice roll result
- Show damage numbers / hit effects when server responds
- Animation typically takes 300-500ms, masking most of the latency
**End Turn**:
- Latency not noticeable (user expects transition delay)
### Unity Implementation Sketch
```csharp
// In CommandHandler.cs
public void OnCommandSelected(Command command) {
// Start animation immediately
if (command.Type == CommandType.Move) {
unitController.StartMoveAnimation(command.TargetHex);
} else if (command.Type == CommandType.Attack) {
unitController.StartAttackAnimation(command.TargetUnit);
}
// Send to server in parallel
connection.SendCommand(command, (response) => {
if (response.Success) {
// Animation continues, apply result
ApplyCommandResult(response);
} else {
// Rollback animation
unitController.CancelAnimation();
ShowError(response.ErrorMessage);
}
});
}
```
### Pros
- Simple implementation
- No server-side changes
- Works with existing architecture
### Cons
- Doesn't eliminate latency for attacks with RNG (must wait for dice roll)
- Rollback needed if server rejects command (rare but possible)
### Estimated Improvement
- Movement: ~200ms latency hidden (feels instant)
- Attacks: ~100-200ms hidden by animation, ~100ms visible wait for dice result
---
## Strategy 2: Split Shardok Architecture
### Concept
Run two Shardok instances:
- **Shardok-Primary (DigitalOcean)**: Handles command processing, source of truth
- **Shardok-AI (Hetzner)**: AI computation only
Human commands go to the nearby Primary for low latency. AI computation uses the powerful Hetzner instance.
### Architecture
```
Human commands (low latency ~20ms)
Unity ←→ Eagle ←→ Shardok-Primary (DigitalOcean)
↓ state sync (when AI turn starts)
Shardok-AI (Hetzner)
↑ AI command response
```
### How It Works
**Human Turn:**
1. Human posts command → Eagle → Shardok-Primary (DO)
2. Primary processes command immediately (~10ms local)
3. Primary streams result to client via Eagle (~10ms)
4. **Total latency: ~20ms** (vs ~220ms current)
**AI Turn:**
1. When AI's turn starts, Primary sends game state snapshot to Hetzner
2. Shardok-AI computes best command using full CPU power
3. Shardok-AI returns command index to Primary
4. Primary executes command locally and streams to client
5. Repeat until AI turn ends
### Protocol Changes
```protobuf
// New service for AI-only computation
service ShardokAIService {
// Send game state, receive AI's chosen command
rpc GetAICommand(AICommandRequest) returns (AICommandResponse);
}
message AICommandRequest {
bytes game_state = 1; // Serialized game state
int32 player_id = 2; // Which AI player
repeated bytes available_commands = 3; // Available command descriptors
}
message AICommandResponse {
int32 command_index = 1; // Index into available_commands
int32 search_depth = 2; // For debugging
double best_score = 3; // For debugging
}
```
### Shardok-Primary Requirements
Shardok-Primary on DigitalOcean needs to:
- Process all commands (human and AI)
- Maintain authoritative game state
- Serialize/deserialize game state for AI requests
- Run on minimal CPU (command processing is fast)
This is essentially the current Shardok, but without running the AI search.
### Shardok-AI Requirements
Shardok-AI on Hetzner needs to:
- Receive game state snapshots
- Run AI evaluation (IterativeDeepeningAI or MCTS)
- Return best command index
- No persistent state (stateless worker)
### AI Turn Latency
Each AI command has ~200ms network latency. This is acceptable because:
1. User is watching animations anyway
2. Natural pacing lets user observe AI decisions
3. AI computation is fast on Hetzner's 16 cores
For a typical AI turn with 5 commands: 5 × 200ms = 1 second network overhead, plus AI thinking time. With animations, this feels natural.
### Implementation Phases
**Phase 1: Add Shardok-Primary (minimal)**
- Deploy existing Shardok container to DigitalOcean
- Configure Eagle to use local Shardok for all commands
- Human latency immediately improves
**Phase 2: Add AI offload**
- Implement `ShardokAIService` RPC
- Shardok-Primary calls Hetzner for AI commands
- Shardok-AI processes requests statelessly
**Phase 3: Optimize**
- Batch multiple AI actions if possible
- Pre-warm Shardok-AI connection
- Add fallback if Hetzner unavailable
### Pros
- Human command latency drops from ~220ms to ~20ms
- AI still gets Hetzner's CPU power
- Clear separation of concerns
- Shardok-Primary can fall back to local AI if Hetzner unavailable
### Cons
- Two Shardok instances to maintain
- State serialization overhead for AI requests
- Each AI action has network round-trip (acceptable with animations)
---
## Comparison
| Approach | Human Latency | AI Throughput | Complexity | Changes Required |
|----------|---------------|---------------|------------|------------------|
| Current | ~220ms | High | - | - |
| Animation masking | ~220ms (perceived ~50ms) | High | Low | Unity only |
| Split architecture | ~20ms | High | Medium | New RPC, two deployments |
---
## Recommendation
**Phase 1 (now)**: Implement animation masking in Unity client
- Quick win, no server changes
- Improves perceived latency significantly for movement
- Attacks still show dice animation while waiting
**Phase 2 (future)**: Split architecture if animation masking insufficient
- Only needed if users complain about attack latency
- More complex but provides true low latency
- Natural evolution of current architecture
+2
View File
@@ -9,6 +9,8 @@ require (
github.com/aws/aws-sdk-go-v2/config v1.28.10
github.com/aws/aws-sdk-go-v2/credentials v1.17.51
github.com/aws/aws-sdk-go-v2/service/s3 v1.72.2
github.com/golang-jwt/jwt/v5 v5.2.1
github.com/google/uuid v1.6.0
google.golang.org/grpc v1.68.0
google.golang.org/protobuf v1.36.3
)
+4
View File
@@ -34,9 +34,13 @@ github.com/aws/aws-sdk-go-v2/service/sts v1.33.6 h1:VwhTrsTuVn52an4mXx29PqRzs2Dv
github.com/aws/aws-sdk-go-v2/service/sts v1.33.6/go.mod h1:+8h7PZb3yY5ftmVLD7ocEoE98hdc8PoKS0H3wfx1dlc=
github.com/aws/smithy-go v1.22.1 h1:/HPHZQ0g7f4eUeK6HKglFz8uwVfZKgoI25rb/J+dnro=
github.com/aws/smithy-go v1.22.1/go.mod h1:irrKGvNn1InZwb2d7fkIRNucdfwR8R+Ts3wxYa/cJHg=
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
golang.org/x/text v0.25.0 h1:qVyWApTSYLk/drJRO5mDlNYskwQznZmkpV2c8q9zls4=
golang.org/x/text v0.25.0/go.mod h1:WEdwpYrmk1qmdHvhkSTNPm3app7v4rsT8F2UD6+VHIA=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+33 -2
View File
@@ -1,7 +1,7 @@
{
"__AUTOGENERATED_FILE_DO_NOT_MODIFY_THIS_FILE_MANUALLY": "THERE_IS_NO_DATA_ONLY_ZUUL",
"__INPUT_ARTIFACTS_HASH": -1064460283,
"__RESOLVED_ARTIFACTS_HASH": -1574144850,
"__INPUT_ARTIFACTS_HASH": -2049857450,
"__RESOLVED_ARTIFACTS_HASH": -1728186926,
"conflict_resolution": {
"com.google.guava:failureaccess:1.0.1": "com.google.guava:failureaccess:1.0.2",
"com.squareup.okio:okio:2.10.0": "com.squareup.okio:okio:3.6.0",
@@ -413,6 +413,12 @@
},
"version": "0.27.0"
},
"io.sentry:sentry": {
"shasums": {
"jar": "740a118182fc089d307830f4e508372e01ad94639b00b4e1b1d83762298a5f35"
},
"version": "7.19.0"
},
"javax.activation:javax.activation-api": {
"shasums": {
"jar": "43fdef0b5b6ceb31b0424b208b930c74ab58fac2ceeb7b3f6fd3aeb8b5ca4393"
@@ -1785,6 +1791,30 @@
"io.perfmark:perfmark-api": [
"io.perfmark"
],
"io.sentry:sentry": [
"io.sentry",
"io.sentry.backpressure",
"io.sentry.cache",
"io.sentry.clientreport",
"io.sentry.config",
"io.sentry.exception",
"io.sentry.hints",
"io.sentry.instrumentation.file",
"io.sentry.internal.debugmeta",
"io.sentry.internal.gestures",
"io.sentry.internal.modules",
"io.sentry.internal.viewhierarchy",
"io.sentry.metrics",
"io.sentry.profilemeasurements",
"io.sentry.protocol",
"io.sentry.rrweb",
"io.sentry.transport",
"io.sentry.util",
"io.sentry.util.thread",
"io.sentry.vendor",
"io.sentry.vendor.gson.internal.bind.util",
"io.sentry.vendor.gson.stream"
],
"javax.activation:javax.activation-api": [
"javax.activation"
],
@@ -2452,6 +2482,7 @@
"io.opencensus:opencensus-contrib-grpc-metrics",
"io.opencensus:opencensus-contrib-http-util",
"io.perfmark:perfmark-api",
"io.sentry:sentry",
"javax.activation:javax.activation-api",
"javax.xml.bind:jaxb-api",
"joda-time:joda-time",
+95
View File
@@ -81,6 +81,101 @@ http {
error_page 502 = /error502grpc;
}
# gRPC proxy for Auth service
location /net.eagle0.eagle.api.auth.Auth {
# Rate limiting
limit_req zone=grpc_limit burst=50 nodelay;
# gRPC proxy
grpc_pass grpc://eagle_grpc;
# Timeouts
grpc_read_timeout 30s;
grpc_send_timeout 30s;
# Error handling
error_page 502 = /error502grpc;
}
# OAuth callback endpoint (proxied to Go auth service)
location /oauth/callback {
proxy_pass http://auth:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# Health check endpoint
location /health {
access_log off;
return 200 "OK\n";
add_header Content-Type text/plain;
}
# gRPC error handling
location = /error502grpc {
internal;
default_type application/grpc;
add_header grpc-status 14;
add_header grpc-message "unavailable";
return 204;
}
}
# HTTPS server for Go Auth service (port 40033)
# Clients connect here directly for OAuth RPCs in Phase 2
server {
listen 40033 ssl;
http2 on;
server_name prod.eagle0.net;
# SSL certificates (same as main server)
ssl_certificate /etc/letsencrypt/live/prod.eagle0.net/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/prod.eagle0.net/privkey.pem;
# SSL configuration
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
# gRPC proxy for Auth service
# Uses variable-based resolution so nginx can start even if auth isn't ready yet
# DNS is cached by the resolver directive (valid=10s)
location /net.eagle0.eagle.api.auth.Auth {
# Rate limiting
limit_req zone=grpc_limit burst=50 nodelay;
# Dynamic upstream resolution (doesn't block nginx startup)
set $auth_backend "auth:40033";
grpc_pass grpc://$auth_backend;
# Timeouts
grpc_read_timeout 30s;
grpc_send_timeout 30s;
# Error handling
error_page 502 = /error502grpc;
}
# gRPC proxy for Admin service
location /net.eagle0.eagle.api.admin.Admin {
# Rate limiting
limit_req zone=grpc_limit burst=50 nodelay;
# Dynamic upstream resolution (doesn't block nginx startup)
set $auth_backend "auth:40033";
grpc_pass grpc://$auth_backend;
# Timeouts
grpc_read_timeout 30s;
grpc_send_timeout 30s;
# Error handling
error_page 502 = /error502grpc;
}
# Health check endpoint
location /health {
access_log off;
@@ -14,6 +14,7 @@ cc_library(
"//src/main/cpp/net/eagle0/shardok/library:engine",
"//src/main/cpp/net/eagle0/shardok/server:eagle_interface_grpc_server",
"//src/main/cpp/net/eagle0/shardok/server:server_configuration",
"//src/main/cpp/net/eagle0/shardok/server:token_auth",
"//src/main/protobuf/net/eagle0/common:common_unit_cc_proto",
"@grpc//:grpc++",
],
@@ -25,7 +25,8 @@ auto CalculateTimeBudget(
const PlayerId playerId,
const GameSettingsSPtr &settings,
const GameStateW &state,
const size_t numCommands) -> AITimeBudget {
const size_t numCommands,
const bool isAllAiBattle) -> AITimeBudget {
const auto settingsGetter = settings->GetGetter();
const auto castleCoords = AllCastleCoords(state->hex_map());
@@ -34,8 +35,10 @@ auto CalculateTimeBudget(
net::eagle0::shardok::storage::fb::GameStatus_::State_SET_UP;
// Get maximum budget cap from settings (in seconds)
// For all-AI battles, use the faster budget limit
const double maxBudgetSeconds =
settingsGetter.Backing().lookahead_time_budget_maximum_seconds();
isAllAiBattle ? settingsGetter.Backing().all_ai_battle_time_budget_maximum()
: settingsGetter.Backing().lookahead_time_budget_maximum_seconds();
const double maxBudgetMs = maxBudgetSeconds * 1000.0;
// During setup, use the setup-specific time budget
@@ -38,11 +38,13 @@ struct AITimeBudget {
// Calculate time budget based on proximity to enemies and castles
// Time budget is calculated dynamically based on number of available commands:
// budget = msPerCommand × numCommands (clamped to 200-5000ms)
// If isAllAiBattle is true, uses allAiBattleTimeBudgetMaximum instead of the normal maximum.
auto CalculateTimeBudget(
PlayerId playerId,
const GameSettingsSPtr &settings,
const GameStateW &state,
size_t numCommands) -> AITimeBudget;
size_t numCommands,
bool isAllAiBattle) -> AITimeBudget;
} // namespace shardok
@@ -53,6 +53,7 @@ auto RoundsRemaining(const GameSettingsSPtr &settings, const GameStateView &gsv)
ShardokAIClient::ShardokAIClient(
const PlayerId playerId,
const bool isDefender,
const bool isAllAiBattle,
const HexMap *hexMap,
const SettingsGetter &settings,
const AIAlgorithmType aiAlgorithmType,
@@ -60,6 +61,7 @@ ShardokAIClient::ShardokAIClient(
const mcts::MCTSConfig &mctsConfig)
: playerId(playerId),
isDefender(isDefender),
isAllAiBattle(isAllAiBattle),
aiAlgorithmType(aiAlgorithmType),
scoringCalculatorType(scoringCalculatorType),
alCache(std::make_unique<AttackLocationsCache>(hexMap, settings)),
@@ -135,7 +137,8 @@ auto ShardokAIClient::StandardChooseCommandIndex(
const auto commandCount = guessedCommands->size();
// Calculate time budget based on game situation using new dynamic per-command settings
const auto timeBudget = CalculateTimeBudget(playerId, settings, guessedState, commandCount);
const auto timeBudget =
CalculateTimeBudget(playerId, settings, guessedState, commandCount, isAllAiBattle);
// Configure MCTS based on proximity to enemy
// When far from enemy: use AVERAGING with maxPlayerFlips=0 (single-player lookahead)
@@ -41,6 +41,7 @@ class ShardokAIClient {
private:
const PlayerId playerId;
const bool isDefender;
const bool isAllAiBattle; // Whether this battle has only AI players (for faster time budgets)
const AIAlgorithmType aiAlgorithmType;
const ScoringCalculatorType scoringCalculatorType;
@@ -69,6 +70,7 @@ public:
explicit ShardokAIClient(
PlayerId playerId,
bool isDefender,
bool isAllAiBattle,
const HexMap* hexMap,
const SettingsGetter& settings,
AIAlgorithmType aiAlgorithmType,
@@ -10,7 +10,6 @@
#include "AiBattleConfig.hpp"
#include "AiBattleSimulator.hpp"
#include "src/main/cpp/net/eagle0/common/FilesystemUtils.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/action_point_distances/FixedActionPointDistances.hpp"
using shardok::ai_battle_simulator::AiBattleConfigLoader;
using shardok::ai_battle_simulator::AiBattleSimulator;
@@ -109,10 +108,6 @@ int main(int argc, char* argv[]) {
// Set exec path for FilesystemUtils
FilesystemUtils::SetExecPath(argv[0]);
// Set cache directory for ActionPointDistances
shardok::FixedActionPointDistances::SetCacheDirectory(
FilesystemUtils::CacheFilesDirectory() + "apdCache/");
try {
if (argc < 2) {
PrintUsage(argv[0]);
@@ -16,7 +16,6 @@
#include "src/main/cpp/net/eagle0/shardok/ai_testing_common/AIClientFactory.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai_testing_common/GamePhaseRunner.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/ShardokEngine.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/action_point_distances/FixedActionPointDistances.hpp"
#include "src/main/protobuf/net/eagle0/shardok/common/command_type.pb.h"
using namespace shardok;
@@ -84,10 +83,6 @@ int main(int argc, char* argv[]) {
// Set exec path so FilesystemUtils can find resource files
FilesystemUtils::SetExecPath(argv[0]);
// Set cache directory for ActionPointDistances
FixedActionPointDistances::SetCacheDirectory(
FilesystemUtils::CacheFilesDirectory() + "apdCache/");
try {
std::cout << "Shardok AI Performance Runner\n";
std::cout << "==============================\n";
@@ -24,9 +24,6 @@ using std::scoped_lock;
using std::string;
using std::unique_lock;
using std::weak_ptr;
using std::chrono::duration;
static constexpr duration kWaitForUpdatesDuration = std::chrono::milliseconds(5000);
using net::eagle0::shardok::common::GameStatus;
@@ -74,11 +71,17 @@ vector<shared_ptr<ShardokAIClient>> ShardokGameController::MakeAIClients(
mctsConfig.maxSimulationFlips = 1;
mctsConfig.simulationPolicy = mcts::MCTSSimulationPolicy::WEIGHTED_HEURISTIC;
for (const auto &pi : e->GetPlayerInfos()) {
// Check if all players are AI - if so, use faster time budgets
const auto &playerInfos = e->GetPlayerInfos();
const bool isAllAiBattle =
std::ranges::all_of(playerInfos, [](const auto &pi) { return pi.is_ai(); });
for (const auto &pi : playerInfos) {
if (pi.is_ai()) {
auto newClient = std::make_shared<ShardokAIClient>(
pi.player_id(),
pi.is_defender(),
isAllAiBattle,
e->GetCurrentGameState()->hex_map(),
e->GetGameSettings()->GetGetter(),
AIAlgorithmType::ITERATIVE_DEEPENING,
@@ -278,15 +281,9 @@ auto ShardokGameController::GetUpdates(const int64_t startingActionId) -> AllUpd
awrs = engine->GetGameHistory(startingActionId);
incomingRegistrations--;
// If the current player is an AI, wait for some results to post. Otherwise go ahead and
// return, we might be telling the caller about available commands.
if (awrs.empty() && !engine->GameIsOver() &&
engine->GetPlayerInfos()[engine->GetCurrentPlayerId()].is_ai()) {
updateCondition.wait_for(guard, kWaitForUpdatesDuration);
incomingRegistrations++;
awrs = engine->GetGameHistory(startingActionId);
incomingRegistrations--;
}
// Note: Previously this had a 5-second wait for AI players to support long-polling.
// With streaming (WaitForUpdatesAndPush), the caller already waits for updates,
// so this wait is no longer needed. GetGameStatus is deprecated in favor of streaming.
updates.mainResults.reserve(awrs.size());
std::ranges::transform(
@@ -406,12 +403,10 @@ auto ShardokGameController::WaitForUpdatesAndPush(
}
// Lock released - GetUpdates will acquire its own lock
if (gameOver) {
subscriber->OnGameOver(gameOverInfo);
return true;
}
// Get updates outside the lock (GetUpdates acquires masterLock internally)
// IMPORTANT: Send any pending updates FIRST, including the final actions
// that caused the game to end. Previously, we returned early on gameOver
// without sending these final updates, causing the client to never see
// the last few battle actions.
AllUpdates updates = GetUpdates(lastPushedActionId);
lastPushedActionId = updates.newUnfilteredCount;
@@ -422,6 +417,12 @@ auto ShardokGameController::WaitForUpdatesAndPush(
updates.newUnfilteredCount,
updates.currentGameState);
}
// Now send gameOver notification after all updates have been sent
if (gameOver) {
subscriber->OnGameOver(gameOverInfo);
return true;
}
}
return false; // Subscriber disconnected
@@ -29,8 +29,6 @@ thread_local struct {
int localMisses = 0;
int sharedAccesses = 0;
int evictionEvents = 0;
int apdLoadedFromFile = 0;
int apdGeneratedFresh = 0;
std::chrono::steady_clock::time_point lastReportTime = std::chrono::steady_clock::now();
} cacheStats;
@@ -40,16 +38,13 @@ static void MaybePrintCacheStats() {
if (std::chrono::duration_cast<std::chrono::seconds>(now - cacheStats.lastReportTime).count() >=
CACHE_STATS_FREQUENCY_SECONDS_) {
printf("Thread cache stats: %d persistent hits, %d persistent misses, %d local hits, "
"%d local misses, %d shared accesses, %d eviction events, "
"%d APD loaded from file, %d APD generated fresh\n",
"%d local misses, %d shared accesses, %d eviction events\n",
cacheStats.persistentHits,
cacheStats.persistentMisses,
cacheStats.localHits,
cacheStats.localMisses,
cacheStats.sharedAccesses,
cacheStats.evictionEvents,
cacheStats.apdLoadedFromFile,
cacheStats.apdGeneratedFresh);
cacheStats.evictionEvents);
cacheStats.lastReportTime = now;
}
}
@@ -195,25 +190,12 @@ auto ActionPointDistancesCache::GetRaw(
}
// Create new pathfinding result using factory method
auto creationResult = FixedActionPointDistances::Create(
auto result = FixedActionPointDistances::Create(
mapToUse,
mapId.terrainTypesId,
mapId.modifierId,
battalionType,
includeBravingWater,
braveWaterActionPointCost);
#if CACHE_STATS_LOGGING_
// Track whether this was loaded from file or generated fresh
if (creationResult.loadedFromFile) {
cacheStats.apdLoadedFromFile++;
} else {
cacheStats.apdGeneratedFresh++;
}
#endif
auto result = creationResult.apd;
// Store in shared cache
sharedDistances.lazy_emplace_l(
cacheKey,
@@ -22,110 +22,56 @@ static const int ASYNC_COUNT = []() {
namespace shardok {
void FixedActionPointDistances::SetCacheDirectory(const string& newDir) {
cacheDirectory = newDir;
FilesystemUtils::MakeDirectoryIfNecessary(cacheDirectory);
}
static thread_local byte_vector _scratch;
FixedActionPointDistances::FixedActionPointDistances(const HexMap* /*map*/, int columnCount)
: ActionPointDistances(columnCount) {}
auto FixedActionPointDistances::Create(
const HexMap* map,
int64_t terrainTypesHash,
int64_t modifierHash,
const BattalionTypeSPtr& battalionType,
bool includeBravingWater,
int braveWaterActionPointCost) -> CreationResult {
int braveWaterActionPointCost) -> std::shared_ptr<FixedActionPointDistances> {
// Create the object using private constructor
auto apd = std::shared_ptr<FixedActionPointDistances>(
new FixedActionPointDistances(map, map->column_count()));
CreationResult result;
result.apd = apd;
result.loadedFromFile = false;
string path = "";
if (!cacheDirectory.empty()) {
std::stringstream stream;
stream << cacheDirectory;
stream << std::hex << terrainTypesHash << '/';
if (auto directoryPath = stream.str(); !FilesystemUtils::FileExistsAtPath(directoryPath)) {
FilesystemUtils::MakeDirectoryIfNecessary(stream.str());
}
stream << std::hex << modifierHash;
stream << " " << battalionType->typeId;
if (includeBravingWater) { stream << " " << braveWaterActionPointCost; }
stream << ".apd";
path = stream.str();
}
const int indexCount = map->row_count() * map->column_count();
if (!path.empty() && FilesystemUtils::FileExistsAtPath(path)) {
apd->distances.resize(indexCount);
// load from file
const auto& bytes = _scratch.ReplaceWithPath(path);
const auto* ptr = reinterpret_cast<const DIST_T*>(bytes.data());
vector<std::future<vector<vector<DIST_T>>>> futures(indexCount);
for (int fromIndex = 0; fromIndex < indexCount; fromIndex++) {
apd->distances[fromIndex].insert(
apd->distances[fromIndex].end(),
&(ptr[0]),
&(ptr[indexCount]));
ptr += indexCount;
}
result.loadedFromFile = true;
} else {
_scratch.reserve(indexCount * indexCount * sizeof(DIST_T));
auto braveWaterPossibleCoords =
includeBravingWater ? apd->BraveWaterPossibleCoords(map) : nullptr;
vector<std::future<vector<vector<DIST_T>>>> futures(indexCount);
int chunkSize = (indexCount + ASYNC_COUNT - 1) / ASYNC_COUNT;
// Break into chunks for async
for (int chunkIdx = 0; chunkIdx < ASYNC_COUNT; chunkIdx++) {
futures[chunkIdx] = std::async(std::launch::async, [=]() -> vector<vector<DIST_T>> {
vector<vector<DIST_T>> chunkVec;
chunkVec.reserve(chunkSize);
const int chunkStartIndex = chunkIdx * chunkSize;
auto braveWaterPossibleCoords =
includeBravingWater ? apd->BraveWaterPossibleCoords(map) : nullptr;
int chunkSize = (indexCount + ASYNC_COUNT - 1) / ASYNC_COUNT;
// Break into chunks for async
for (int chunkIdx = 0; chunkIdx < ASYNC_COUNT; chunkIdx++) {
futures[chunkIdx] = std::async(std::launch::async, [=]() -> vector<vector<DIST_T>> {
vector<vector<DIST_T>> chunkVec;
chunkVec.reserve(chunkSize);
const int chunkStartIndex = chunkIdx * chunkSize;
for (int i = 0; i < chunkSize; i++) {
const auto fromIndex = chunkStartIndex + i;
if (fromIndex >= indexCount) { continue; }
chunkVec.push_back(ActionPointDistances::GenerateDistances(
fromIndex,
map,
includeBravingWater,
braveWaterActionPointCost,
battalionType,
braveWaterPossibleCoords));
}
return chunkVec;
});
}
apd->distances.reserve(indexCount);
_scratch.clear();
_scratch.reserve(indexCount * indexCount * sizeof(DIST_T));
for (int chunkIdx = 0; chunkIdx < ASYNC_COUNT; chunkIdx++) {
auto resultsVec = futures[chunkIdx].get();
apd->distances.insert(apd->distances.end(), resultsVec.begin(), resultsVec.end());
for (const auto& r : resultsVec) { _scratch.append(r); }
}
if (!path.empty()) { FilesystemUtils::AtomicallySaveToPath(path, _scratch); }
for (int i = 0; i < chunkSize; i++) {
const auto fromIndex = chunkStartIndex + i;
if (fromIndex >= indexCount) { continue; }
chunkVec.push_back(ActionPointDistances::GenerateDistances(
fromIndex,
map,
includeBravingWater,
braveWaterActionPointCost,
battalionType,
braveWaterPossibleCoords));
}
return chunkVec;
});
}
return result;
apd->distances.reserve(indexCount);
for (int chunkIdx = 0; chunkIdx < ASYNC_COUNT; chunkIdx++) {
auto resultsVec = futures[chunkIdx].get();
apd->distances.insert(apd->distances.end(), resultsVec.begin(), resultsVec.end());
}
return apd;
}
} // namespace shardok
@@ -17,31 +17,19 @@ using std::vector;
using BattalionTypeSPtr = std::shared_ptr<const BattalionType>;
class FixedActionPointDistances final : public ActionPointDistances {
public:
struct CreationResult {
std::shared_ptr<FixedActionPointDistances> apd;
bool loadedFromFile;
};
private:
vector<vector<DIST_T>> distances;
inline static string cacheDirectory = "";
// Private constructor - use Create factory method instead
explicit FixedActionPointDistances(const HexMap *map, int columnCount);
public:
static void SetCacheDirectory(const string &newDir);
// Factory method to create FixedActionPointDistances with metadata
// Factory method to create FixedActionPointDistances
static auto Create(
const HexMap *map,
int64_t terrainTypesHash,
int64_t modifierHash,
const BattalionTypeSPtr &battalionType,
bool includeBravingWater,
int braveWaterActionPointCost = -1) -> CreationResult;
int braveWaterActionPointCost = -1) -> std::shared_ptr<FixedActionPointDistances>;
~FixedActionPointDistances() override = default;
@@ -52,8 +40,6 @@ public:
[[nodiscard]] auto Distance(const Coords &from, const Coords &to) const -> DIST_T override {
return Distance(ToIndex(from), ToIndex(to));
}
friend struct CreationResult;
};
} // namespace shardok
@@ -34,6 +34,17 @@ cc_library(
],
)
cc_library(
name = "token_auth",
hdrs = ["TokenAuthInterceptor.hpp"],
copts = COPTS,
visibility = ["//src/main/cpp/net/eagle0/shardok:__subpackages__"],
deps = [
"//src/main/cpp/net/eagle0/common:protobuf_warning_suppression",
"@grpc//:grpc++",
],
)
cc_library(
name = "eagle_interface_grpc_server",
srcs = ["EagleInterfaceGrpcServer.cpp"],
@@ -42,6 +53,7 @@ cc_library(
visibility = ["//src/main/cpp/net/eagle0/shardok:__subpackages__"],
deps = [
":games_manager",
":token_auth",
"//src/main/cpp/net/eagle0/common:unit_conversions",
"//src/main/protobuf/net/eagle0/common:shardok_internal_interface_cc_grpc",
"//src/main/protobuf/net/eagle0/common:victory_condition_cc_proto",
@@ -81,8 +81,17 @@ static auto FromInternalStatus(
const std::string &kShardokGameRequestExtension = *(new string(".e0gr"));
EagleInterfaceImpl::EagleInterfaceImpl(shared_ptr<ShardokGamesManager> manager)
: gamesManager(std::move(manager)) {}
EagleInterfaceImpl::EagleInterfaceImpl(
shared_ptr<ShardokGamesManager> manager,
std::string authToken)
: gamesManager(std::move(manager)),
tokenValidator_(std::move(authToken)) {
if (tokenValidator_.IsEnabled()) {
std::cout << "Token authentication enabled" << std::endl;
} else {
std::cout << "Token authentication disabled (no token configured)" << std::endl;
}
}
auto ConvertPlayerInfo(
const google::protobuf::RepeatedPtrField<net::eagle0::common::PlayerSetupInfo> &allPis,
@@ -188,9 +197,12 @@ void EagleInterfaceImpl::StartGame(const NewGameRequest &request) {
}
auto EagleInterfaceImpl::PostCommand(
ServerContext * /*context*/,
ServerContext *context,
const PostCommandRequest *request,
GameStatusResponse *response) -> Status {
// Validate auth token
if (auto authStatus = tokenValidator_.ValidateOrStatus(context)) { return *authStatus; }
shared_ptr<ShardokGameController> controller;
try {
controller = ControllerForGame(request->game_id(), request->game_setup_info());
@@ -229,9 +241,12 @@ auto EagleInterfaceImpl::PostCommand(
}
auto EagleInterfaceImpl::PostPlacementCommands(
ServerContext * /*context*/,
ServerContext *context,
const PlacementCommandsRequest *request,
GameStatusResponse *response) -> Status {
// Validate auth token
if (auto authStatus = tokenValidator_.ValidateOrStatus(context)) { return *authStatus; }
shared_ptr<ShardokGameController> controller;
try {
controller = ControllerForGame(request->game_id(), request->game_setup_info());
@@ -322,27 +337,13 @@ void EagleInterfaceImpl::PopulateGameStatusResponse(
}
}
auto EagleInterfaceImpl::GetGameStatus(
ServerContext * /*context*/,
const GameStatusRequest *request,
GameStatusResponse *response) -> Status {
shared_ptr<ShardokGameController> controller;
try {
controller = ControllerForGame(request->game_id(), request->game_setup_info());
} catch (NewGameException &e) { return e.GetStatus(); }
PopulateGameStatusResponse(
controller,
request->game_setup_info().known_result_count(),
response);
return Status::OK;
}
auto EagleInterfaceImpl::GetHexMap(
ServerContext * /*context*/,
ServerContext *context,
const HexMapRequest *request,
HexMapResponse *response) -> Status {
// Validate auth token
if (auto authStatus = tokenValidator_.ValidateOrStatus(context)) { return *authStatus; }
// TODO: return appropriate status code if a bad map name is sent
*response->mutable_map() = LoadMap(request->map_name());
@@ -350,9 +351,12 @@ auto EagleInterfaceImpl::GetHexMap(
}
auto EagleInterfaceImpl::GetHexMapNames(
ServerContext * /*context*/,
ServerContext *context,
const HexMapNamesRequest * /*request*/,
HexMapNamesResponse *response) -> Status {
// Validate auth token
if (auto authStatus = tokenValidator_.ValidateOrStatus(context)) { return *authStatus; }
for (const string &mapName : GetMapNames()) { response->add_map_names(mapName); }
return Status::OK;
@@ -533,6 +537,9 @@ auto EagleInterfaceImpl::SubscribeToGame(
ServerContext *context,
const GameSubscriptionRequest *request,
grpc::ServerWriter<GameStatusResponse> *writer) -> Status {
// Validate auth token
if (auto authStatus = tokenValidator_.ValidateOrStatus(context)) { return *authStatus; }
shared_ptr<ShardokGameController> controller;
try {
controller = ControllerForGame(request->game_id(), request->game_setup_info());
@@ -13,8 +13,9 @@
#include <string>
#include <thread>
#include "ShardokGamesManager.hpp"
#include "src/main/cpp/net/eagle0/common/ProtobufWarningSuppression.hpp"
#include "src/main/cpp/net/eagle0/shardok/server/ShardokGamesManager.hpp"
#include "src/main/cpp/net/eagle0/shardok/server/TokenAuthInterceptor.hpp"
#pragma GCC diagnostic push
SUPPRESS_PROTOBUF_WARNINGS
#include <grpc/grpc.h>
@@ -31,7 +32,6 @@ namespace shardok {
using grpc::ServerContext;
using grpc::Status;
using net::eagle0::common::GameSetupInfo;
using net::eagle0::common::GameStatusRequest;
using net::eagle0::common::GameStatusResponse;
using net::eagle0::common::GameSubscriptionRequest;
using net::eagle0::common::HexMapNamesRequest;
@@ -47,6 +47,7 @@ using std::shared_ptr;
class EagleInterfaceImpl final : public ShardokInternalInterface::Service {
private:
std::shared_ptr<ShardokGamesManager> gamesManager;
TokenValidator tokenValidator_;
auto ControllerForGame(const GameId& gameId, const GameSetupInfo& setupInfo)
-> std::shared_ptr<ShardokGameController>;
@@ -58,7 +59,14 @@ private:
GameStatusResponse* response);
public:
explicit EagleInterfaceImpl(std::shared_ptr<ShardokGamesManager> manager);
/**
* Create the service.
*
* @param manager Games manager
* @param authToken Optional auth token. If non-empty, all requests must include
* "authorization: Bearer <token>" metadata.
*/
EagleInterfaceImpl(std::shared_ptr<ShardokGamesManager> manager, std::string authToken = "");
auto PostCommand(
ServerContext* context,
@@ -68,10 +76,6 @@ public:
ServerContext* context,
const PlacementCommandsRequest* request,
GameStatusResponse* response) -> Status override;
auto GetGameStatus(
ServerContext* context,
const GameStatusRequest* request,
GameStatusResponse* response) -> Status override;
auto GetHexMap(ServerContext* context, const HexMapRequest* request, HexMapResponse* response)
-> Status override;
@@ -24,6 +24,7 @@ const string ServerConfiguration::kEagleInterfaceGrpcAddress = "eagleInterfaceGr
const string ServerConfiguration::kEagleGrpcAddress = "eagleGrpcAddress";
const string ServerConfiguration::kSslCertPath = "sslCertPath";
const string ServerConfiguration::kSslPrivateKeyPath = "sslPrivateKeyPath";
const string ServerConfiguration::kAuthTokenPath = "authTokenPath";
#pragma GCC diagnostic pop
using std::unordered_map;
@@ -29,6 +29,7 @@ public:
const static string kEagleGrpcAddress;
const static string kSslCertPath;
const static string kSslPrivateKeyPath;
const static string kAuthTokenPath;
};
#endif /* ServerConfiguration_hpp */
@@ -15,7 +15,6 @@
#include "ServerConfiguration.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/ShardokAIClient.hpp"
#include "src/main/cpp/net/eagle0/shardok/controller/ShardokGameController.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/action_point_distances/FixedActionPointDistances.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/settings_loader/SettingsLoader.hpp"
#include "src/main/cpp/net/eagle0/shardok/util/MapLoader.hpp"
#include "src/main/flatbuffer/net/eagle0/shardok/storage/unit.hpp"
@@ -45,9 +44,6 @@ ShardokGamesManager::ShardokGamesManager(const std::vector<std::string> &extraSe
std::cerr << "NOT SETTING" << std::endl;
// setter.SetRaw(key, value);
}
FixedActionPointDistances::SetCacheDirectory(
FilesystemUtils::CacheFilesDirectory() + "apdCache/");
}
auto ShardokGamesManager::GetController(const GameId &gameId)
@@ -0,0 +1,119 @@
//
// TokenAuthInterceptor.hpp
// eagle0
//
// Token-based authentication for gRPC.
// Validates Bearer tokens in the 'authorization' metadata header.
//
#ifndef TokenAuthInterceptor_hpp
#define TokenAuthInterceptor_hpp
#include <fstream>
#include <iostream>
#include <optional>
#include <sstream>
#include <string>
#include "src/main/cpp/net/eagle0/common/ProtobufWarningSuppression.hpp"
#pragma GCC diagnostic push
SUPPRESS_PROTOBUF_WARNINGS
#include <grpcpp/server_context.h>
#include <grpcpp/support/status.h>
#pragma GCC diagnostic pop
namespace shardok {
/**
* Validates Bearer tokens in gRPC request metadata.
*
* Usage:
* TokenValidator validator(expectedToken);
* if (!validator.Validate(context)) {
* return grpc::Status(grpc::UNAUTHENTICATED, "Invalid token");
* }
*/
class TokenValidator {
public:
/**
* Create a validator with the expected token.
* If expectedToken is empty, all requests are allowed (no auth required).
*/
explicit TokenValidator(std::string expectedToken) : expectedToken_(std::move(expectedToken)) {}
/**
* Validate the authorization header in the server context.
*
* Expects: "authorization" metadata with value "Bearer <token>"
*
* @return true if valid (or no auth configured), false otherwise
*/
[[nodiscard]] auto Validate(grpc::ServerContext* context) const -> bool {
// If no auth token is configured, allow all requests
if (expectedToken_.empty()) { return true; }
const auto& metadata = context->client_metadata();
auto it = metadata.find("authorization");
if (it == metadata.end()) {
std::cerr << "Auth failed: no authorization header" << std::endl;
return false;
}
std::string authHeader(it->second.begin(), it->second.end());
std::string expectedHeader = "Bearer " + expectedToken_;
if (authHeader != expectedHeader) {
std::cerr << "Auth failed: invalid token" << std::endl;
return false;
}
return true;
}
/**
* Validate and return appropriate Status.
*
* @return std::nullopt if valid, Status(UNAUTHENTICATED) if invalid
*/
[[nodiscard]] auto ValidateOrStatus(grpc::ServerContext* context) const
-> std::optional<grpc::Status> {
if (Validate(context)) { return std::nullopt; }
return grpc::Status(grpc::UNAUTHENTICATED, "Invalid or missing authentication token");
}
/**
* Check if authentication is enabled.
*/
[[nodiscard]] auto IsEnabled() const -> bool { return !expectedToken_.empty(); }
private:
std::string expectedToken_;
};
/**
* Read auth token from a file, stripping whitespace.
* Returns empty string if file doesn't exist or is empty.
*/
inline auto ReadAuthTokenFromFile(const std::string& filePath) -> std::string {
if (filePath.empty()) { return ""; }
std::ifstream file(filePath);
if (!file.is_open()) {
std::cerr << "Warning: Could not open auth token file: " << filePath << std::endl;
return "";
}
std::stringstream buffer;
buffer << file.rdbuf();
std::string token = buffer.str();
// Trim whitespace
auto start = token.find_first_not_of(" \t\n\r");
if (start == std::string::npos) { return ""; }
auto end = token.find_last_not_of(" \t\n\r");
return token.substr(start, end - start + 1);
}
} // namespace shardok
#endif /* TokenAuthInterceptor_hpp */
@@ -7,7 +7,9 @@
//
#include <cstddef>
#include <fstream>
#include <memory>
#include <sstream>
#include <thread>
#include "src/main/cpp/net/eagle0/common/ProtobufWarningSuppression.hpp"
@@ -17,14 +19,16 @@ SUPPRESS_PROTOBUF_WARNINGS
#include <execinfo.h>
#include <grpcpp/channel.h>
#include <grpcpp/security/server_credentials.h>
#include <signal.h>
#include <unistd.h>
#pragma GCC diagnostic pop
#include "server/EagleInterfaceGrpcServer.hpp"
#include "server/ServerConfiguration.hpp"
#include "server/ShardokGamesManager.hpp"
#include "src/main/cpp/net/eagle0/shardok/server/EagleInterfaceGrpcServer.hpp"
#include "src/main/cpp/net/eagle0/shardok/server/ServerConfiguration.hpp"
#include "src/main/cpp/net/eagle0/shardok/server/ShardokGamesManager.hpp"
#include "src/main/cpp/net/eagle0/shardok/server/TokenAuthInterceptor.hpp"
using ::GameStatePersister;
using shardok::EagleInterfaceImpl;
@@ -41,12 +45,15 @@ struct ServerThreadInfo {
auto StartInThread(grpc::ServerBuilder *serverBuilder) -> ServerThreadInfo;
auto CreateServerBuilder(const string &serverAddress) -> grpc::ServerBuilder *;
auto CreateServerBuilder(const string &serverAddress, const string &certPath, const string &keyPath)
-> grpc::ServerBuilder *;
auto CreateEagleInterfaceService(
const std::shared_ptr<ServerConfiguration> &config,
std::shared_ptr<ShardokGamesManager> shardokGamesManager) -> ServerThreadInfo;
auto ReadFileContents(const string &path) -> string;
void handler(const int sig) {
void *array[10];
size_t size;
@@ -82,11 +89,46 @@ auto main(const int argc, char **argv) -> int {
eagleInterfaceInfo.thread.join();
}
auto CreateServerBuilder(const string &serverAddress) -> grpc::ServerBuilder * {
auto ReadFileContents(const string &path) -> string {
std::ifstream file(path);
if (!file.is_open()) { return ""; }
std::stringstream buffer;
buffer << file.rdbuf();
return buffer.str();
}
auto CreateServerBuilder(const string &serverAddress, const string &certPath, const string &keyPath)
-> grpc::ServerBuilder * {
auto *serverBuilder = new grpc::ServerBuilder;
const auto credentials = grpc::InsecureServerCredentials();
std::cout << "Creating insecure connection" << std::endl;
std::shared_ptr<grpc::ServerCredentials> credentials;
// Check if TLS is configured
if (!certPath.empty() && !keyPath.empty()) {
const string certContents = ReadFileContents(certPath);
const string keyContents = ReadFileContents(keyPath);
if (certContents.empty() || keyContents.empty()) {
std::cerr << "Error: Could not read TLS certificate or key file" << std::endl;
std::cerr << " cert path: " << certPath << std::endl;
std::cerr << " key path: " << keyPath << std::endl;
std::cerr << "Falling back to insecure connection" << std::endl;
credentials = grpc::InsecureServerCredentials();
} else {
grpc::SslServerCredentialsOptions::PemKeyCertPair keyCert;
keyCert.private_key = keyContents;
keyCert.cert_chain = certContents;
grpc::SslServerCredentialsOptions sslOpts;
sslOpts.pem_key_cert_pairs.push_back(keyCert);
credentials = grpc::SslServerCredentials(sslOpts);
std::cout << "TLS enabled with certificate from: " << certPath << std::endl;
}
} else {
credentials = grpc::InsecureServerCredentials();
std::cout << "Creating insecure connection (no TLS configured)" << std::endl;
}
serverBuilder->AddListeningPort(serverAddress, credentials);
return serverBuilder;
@@ -98,9 +140,19 @@ auto CreateEagleInterfaceService(
const string eagleInterfaceServerAddress =
config->stringForKey(ServerConfiguration::kEagleInterfaceGrpcAddress);
auto *eagleInterfaceServerBuilder = CreateServerBuilder(eagleInterfaceServerAddress);
// TLS configuration
const string certPath = config->stringForKey(ServerConfiguration::kSslCertPath);
const string keyPath = config->stringForKey(ServerConfiguration::kSslPrivateKeyPath);
const auto eagleInterfaceService = std::make_shared<EagleInterfaceImpl>(shardokGamesManager);
auto *eagleInterfaceServerBuilder =
CreateServerBuilder(eagleInterfaceServerAddress, certPath, keyPath);
// Auth token configuration
const string authTokenPath = config->stringForKey(ServerConfiguration::kAuthTokenPath);
const string authToken = shardok::ReadAuthTokenFromFile(authTokenPath);
const auto eagleInterfaceService =
std::make_shared<EagleInterfaceImpl>(shardokGamesManager, authToken);
eagleInterfaceServerBuilder->RegisterService(eagleInterfaceService.get());
ServerThreadInfo eagleInterfaceThreadInfo = StartInThread(eagleInterfaceServerBuilder);
@@ -68,6 +68,7 @@
<Compile Include="Assets/Eagle/CommandSelectors/ResolveInvitationCommandSelector.cs" />
<Compile Include="Assets/Modern UI Pack/Scripts/Slider/SliderManager.cs" />
<Compile Include="Assets/common/GUIUtils/TableRowHoverDetector.cs" />
<Compile Include="Assets/ConnectionHandler/DropGameConfirmationPanel.cs" />
<Compile Include="Assets/Eagle/Table Rows/DynamicHeroTextUpdater.cs" />
<Compile Include="Assets/Eagle/CommandSelectors/util/HeroDropdownController.cs" />
<Compile Include="Assets/Eagle/Notifications/PrisonerReturnedNotificationGenerator.cs" />
@@ -109,6 +110,7 @@
<Compile Include="Assets/Modern UI Pack/Scripts/UI Manager/UIManagerProgressBarLoopEditor.cs" />
<Compile Include="Assets/Eagle/BattalionUtils.cs" />
<Compile Include="Assets/Eagle/Table Rows/UnaffiliatedHeroRowController.cs" />
<Compile Include="Assets/Shardok/ArrowVolleyAnimator.cs" />
<Compile Include="Assets/Modern UI Pack/Scripts/Tooltip/TooltipContent.cs" />
<Compile Include="Assets/Eagle/ConnectionCircuitBreaker.cs" />
<Compile Include="Assets/Modern UI Pack/Scripts/UI Manager/UIManagerHSelector.cs" />
@@ -125,6 +127,7 @@
<Compile Include="Assets/Eagle/Notifications/Notification.cs" />
<Compile Include="Assets/Eagle/Notifications/ARNNotifications/QuestFailedDetailsNotificationGenerator.cs" />
<Compile Include="Assets/Eagle/Notifications/ARNNotifications/QuestFulfilledDetailsNotificationGenerator.cs" />
<Compile Include="Assets/Auth/OAuthManager.cs" />
<Compile Include="Assets/Eagle/Notifications/ARNNotifications/ProfessionGainedDetailsNotificationGenerator.cs" />
<Compile Include="Assets/Eagle/TextureList.cs" />
<Compile Include="Assets/Modern UI Pack/Scripts/Modal Window/ModalWindowManager.cs" />
@@ -146,6 +149,7 @@
<Compile Include="Assets/Eagle/Notifications/ARNNotifications/ProvinceHeldDetailsNotificationGenerator.cs" />
<Compile Include="Assets/Bluetooth/DieInfo.cs" />
<Compile Include="Assets/common/ResourceFetcher.cs" />
<Compile Include="Assets/Auth/AuthClient.cs" />
<Compile Include="Assets/Eagle/Notifications/ARNNotifications/TruceRejectedDetailsNotificationGenerator.cs" />
<Compile Include="Assets/Eagle/Notifications/RiotSuppressedNotificationGenerator.cs" />
<Compile Include="Assets/Modern UI Pack/Scripts/Modal Window/ModalWindowManagerEditor.cs" />
@@ -153,6 +157,7 @@
<Compile Include="Assets/Bluetooth/NativeDiceInterfaceImports.cs" />
<Compile Include="Assets/Eagle/Notifications/ProvinceConqueredNotificationGenerator.cs" />
<Compile Include="Assets/Eagle/Table Rows/ExtraTroopsRowController.cs" />
<Compile Include="Assets/Auth/JwtAuthInterceptor.cs" />
<Compile Include="Assets/Eagle/CommandPanelController.cs" />
<Compile Include="Assets/Eagle/Notifications/ARNNotifications/ShatteredArmyDetailsNotificationGenerator.cs" />
<Compile Include="Assets/Shardok/TurnHistoryPanelController.cs" />
@@ -176,6 +181,7 @@
<Compile Include="Assets/Shardok/Table Rows/ReserveRowController.cs" />
<Compile Include="Assets/Eagle/Notifications/ARNNotifications/OutlawSpottedDetailsNotificationGenerator.cs" />
<Compile Include="Assets/Modern UI Pack/Scripts/Fixes/UIElementInFront.cs" />
<Compile Include="Assets/Shardok/MeleeAnimator.cs" />
<Compile Include="Assets/ConnectionHandler/WaitingGameItem.cs" />
<Compile Include="Assets/Modern UI Pack/Scripts/Button/ButtonManagerBasicIcon.cs" />
<Compile Include="Assets/Modern UI Pack/Scripts/UI Manager/UIManagerSlider.cs" />
@@ -258,6 +264,7 @@
<Compile Include="Assets/Eagle/CommandSelectors/ResolveTruceCommandSelector.cs" />
<Compile Include="Assets/Eagle/ClientPregeneratedText.cs" />
<Compile Include="Assets/Eagle/CommandSelectors/SwearBrotherhoodCommandSelector.cs" />
<Compile Include="Assets/Auth/TokenStorage.cs" />
<Compile Include="Assets/Eagle/Table Rows/TableRowController.cs" />
<Compile Include="Assets/Eagle/DisplayNames.cs" />
<Compile Include="Assets/Modern UI Pack/Scripts/UI Manager/UIManagerSliderEditor.cs" />
@@ -363,6 +370,7 @@
<Compile Include="Assets/Eagle/Table Rows/AvailableHeroTableRow.cs" />
<Compile Include="Assets/Eagle/Table Rows/HeroRowController.cs" />
<Compile Include="Assets/Modern UI Pack/Scripts/UI Manager/UIManagerTooltip.cs" />
<Compile Include="Assets/Eagle/Notifications/ARNNotifications/NewFactionHeadDetailsNotificationGenerator.cs" />
<Compile Include="Assets/Shardok/HexGrid.cs" />
<Compile Include="Assets/Modern UI Pack/Scripts/Tooltip/TooltipManager.cs" />
<None Include="Assets/TextMesh Pro/Resources/Shaders/TMPro.cginc" />
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 683e069fbc3074e35ac6fc3881a03f4a
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,192 @@
using System;
using System.Threading.Tasks;
using Cysharp.Net.Http;
using Grpc.Core;
using Grpc.Core.Interceptors;
using Grpc.Net.Client;
using Net.Eagle0.Eagle.Api.Auth;
using UnityEngine;
using GrpcAuthClient = Net.Eagle0.Eagle.Api.Auth.Auth.AuthClient;
namespace Auth {
/// <summary>
/// gRPC client for the Auth service.
/// Routes OAuth requests (GetOAuthUrl, CheckOAuthStatus, RefreshToken) to the Go auth service.
/// Routes user requests (SetDisplayName, GetCurrentUser, Logout) to Eagle.
/// </summary>
public class AuthClient : IDisposable {
private const int PollIntervalMs = 2000; // Poll every 2 seconds
private const int PollTimeoutMs = 300000; // 5 minute timeout
private readonly GrpcAuthClient _authServiceClient; // Go auth service
private readonly GrpcAuthClient _eagleClient; // Eagle server
private readonly GrpcChannel _authServiceChannel;
private readonly GrpcChannel _eagleChannel;
/// <summary>
/// Create auth client with separate channels for auth service and Eagle.
/// </summary>
/// <param name="authServiceUrl">Go auth service URL, e.g.
/// "https://prod.eagle0.net:40033"</param> <param name="eagleUrl">Eagle server URL, e.g.
/// "https://prod.eagle0.net:40032"</param>
public AuthClient(string authServiceUrl, string eagleUrl) {
// Auth service channel (no JWT needed for OAuth flow)
_authServiceChannel = GrpcChannel.ForAddress(
authServiceUrl,
new GrpcChannelOptions {
HttpHandler = new YetAnotherHttpHandler { Http2Only = true },
DisposeHttpClient = true
});
_authServiceClient = new GrpcAuthClient(_authServiceChannel);
// Eagle channel with JWT interceptor for authenticated requests
_eagleChannel = GrpcChannel.ForAddress(
eagleUrl,
new GrpcChannelOptions {
HttpHandler = new YetAnotherHttpHandler { Http2Only = true },
DisposeHttpClient = true
});
CallInvoker eagleInvoker = _eagleChannel.Intercept(new JwtAuthInterceptor());
_eagleClient = new GrpcAuthClient(eagleInvoker);
Debug.Log($"[AuthClient] Configured: authService={authServiceUrl}, eagle={eagleUrl}");
}
/// <summary>
/// Get OAuth URL to open in system browser.
/// Returns both the URL and the state token for polling.
/// Routed to Go auth service.
/// </summary>
/// <param name="provider">Discord or Google</param>
/// <returns>Tuple of (URL to open in browser, state token for polling)</returns>
public async Task<(string authUrl, string state)> GetOAuthUrlAsync(OAuthProvider provider) {
var request = new GetOAuthUrlRequest { Provider = provider };
var response = await _authServiceClient.GetOAuthUrlAsync(request);
Debug.Log($"[AuthClient] Got OAuth URL for {provider}, state={response.State}");
return (response.AuthUrl, response.State);
}
/// <summary>
/// Poll for OAuth completion. Blocks until success, failure, or timeout.
/// The server handles the OAuth callback and token exchange.
/// Routed to Go auth service.
/// </summary>
/// <param name="state">State token from GetOAuthUrlAsync</param>
/// <returns>Response with tokens and user info on success</returns>
public async Task<CheckOAuthStatusResponse> PollForOAuthCompletionAsync(string state) {
var startTime = DateTime.UtcNow;
while (true) {
var request = new CheckOAuthStatusRequest { State = state };
var response = await _authServiceClient.CheckOAuthStatusAsync(request);
switch (response.Status) {
case OAuthStatus.Success:
Debug.Log(
$"[AuthClient] OAuth successful, user={response.User?.DisplayName}, isNew={response.IsNewUser}");
return response;
case OAuthStatus.Failed:
throw new Exception($"OAuth failed: {response.ErrorMessage}");
case OAuthStatus.Expired:
throw new Exception("OAuth session expired. Please try again.");
case OAuthStatus.Pending:
// Check timeout
if ((DateTime.UtcNow - startTime).TotalMilliseconds > PollTimeoutMs) {
throw new TimeoutException("OAuth login timed out. Please try again.");
}
// Wait before polling again
await Task.Delay(PollIntervalMs);
break;
default: throw new Exception($"Unknown OAuth status: {response.Status}");
}
}
}
/// <summary>
/// Refresh access token using stored refresh token.
/// Routed to Go auth service.
/// </summary>
/// <returns>New access token and expiry, or null if refresh failed</returns>
public async Task<RefreshTokenResponse> RefreshTokenAsync() {
var refreshToken = TokenStorage.RefreshToken;
if (string.IsNullOrEmpty(refreshToken)) {
throw new InvalidOperationException("No refresh token available");
}
var request = new RefreshTokenRequest { RefreshToken = refreshToken };
var response = await _authServiceClient.RefreshTokenAsync(request);
// Update stored access token
TokenStorage.UpdateAccessToken(response.AccessToken, response.ExpiresAt);
Debug.Log($"[AuthClient] Token refreshed, expires at {response.ExpiresAt}");
return response;
}
/// <summary>
/// Set display name for new users.
/// Requires valid JWT in interceptor.
/// Routed to Eagle.
/// </summary>
public async Task<SetDisplayNameResponse> SetDisplayNameAsync(string displayName) {
var request = new SetDisplayNameRequest { DisplayName = displayName };
var response = await _eagleClient.SetDisplayNameAsync(request);
if (response.Success) {
TokenStorage.UpdateDisplayName(displayName);
// Update the access token with the new one that has updated displayName claim
if (!string.IsNullOrEmpty(response.AccessToken)) {
// Token expires in 7 days from now
var expiresAt = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds();
TokenStorage.UpdateAccessToken(response.AccessToken, expiresAt);
Debug.Log($"[AuthClient] Display name set to: {displayName}, token updated");
} else {
Debug.Log($"[AuthClient] Display name set to: {displayName}");
}
} else {
Debug.LogWarning(
$"[AuthClient] Failed to set display name: {response.ErrorMessage}");
}
return response;
}
/// <summary>
/// Get current user info. Validates the stored JWT.
/// Routed to Eagle.
/// </summary>
public async Task<GetCurrentUserResponse> GetCurrentUserAsync() {
var response = await _eagleClient.GetCurrentUserAsync(new GetCurrentUserRequest());
Debug.Log($"[AuthClient] Current user: {response.User?.DisplayName}");
return response;
}
/// <summary>
/// Logout - invalidates refresh token on server.
/// Routed to Eagle.
/// </summary>
public async Task LogoutAsync() {
try {
await _eagleClient.LogoutAsync(new LogoutRequest());
} catch (Exception ex) {
Debug.LogWarning($"[AuthClient] Logout RPC failed (may be expected): {ex.Message}");
}
// Clear local tokens regardless of server response
TokenStorage.Clear();
Debug.Log("[AuthClient] Logged out, tokens cleared");
}
public void Dispose() {
_authServiceChannel?.Dispose();
_eagleChannel?.Dispose();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4ba94126c2d2145b8875612eaf5bc371
@@ -0,0 +1,75 @@
using System;
using Grpc.Core;
using Grpc.Core.Interceptors;
namespace Auth {
/// <summary>
/// gRPC interceptor that attaches JWT Bearer token to requests.
/// Reads token from TokenStorage on each request.
/// </summary>
public class JwtAuthInterceptor : Interceptor {
private const string HeaderName = "Authorization";
private string GetBearerHeader() {
var token = TokenStorage.AccessToken;
return string.IsNullOrEmpty(token) ? null : $"Bearer {token}";
}
public override TResponse BlockingUnaryCall<TRequest, TResponse>(
TRequest request,
ClientInterceptorContext<TRequest, TResponse> context,
BlockingUnaryCallContinuation<TRequest, TResponse> continuation) {
return continuation(request, ContextWithHeaders(context));
}
public override AsyncUnaryCall<TResponse> AsyncUnaryCall<TRequest, TResponse>(
TRequest request,
ClientInterceptorContext<TRequest, TResponse> context,
AsyncUnaryCallContinuation<TRequest, TResponse> continuation) {
return continuation(request, ContextWithHeaders(context));
}
public override AsyncServerStreamingCall<TResponse>
AsyncServerStreamingCall<TRequest, TResponse>(
TRequest request,
ClientInterceptorContext<TRequest, TResponse> context,
AsyncServerStreamingCallContinuation<TRequest, TResponse> continuation) {
return continuation(request, ContextWithHeaders(context));
}
public override AsyncClientStreamingCall<TRequest, TResponse>
AsyncClientStreamingCall<TRequest, TResponse>(
ClientInterceptorContext<TRequest, TResponse> context,
AsyncClientStreamingCallContinuation<TRequest, TResponse> continuation) {
return continuation(ContextWithHeaders(context));
}
public override AsyncDuplexStreamingCall<TRequest, TResponse>
AsyncDuplexStreamingCall<TRequest, TResponse>(
ClientInterceptorContext<TRequest, TResponse> context,
AsyncDuplexStreamingCallContinuation<TRequest, TResponse> continuation) {
return continuation(ContextWithHeaders(context));
}
private ClientInterceptorContext<TRequest, TResponse>
ContextWithHeaders<TRequest, TResponse>(
ClientInterceptorContext<TRequest, TResponse> original)
where TRequest : class
where TResponse : class {
var bearerHeader = GetBearerHeader();
if (string.IsNullOrEmpty(bearerHeader)) {
// No token available - return original context
// Auth service endpoints don't require token
return original;
}
var headers = new Metadata();
headers.Add(HeaderName, bearerHeader);
return new ClientInterceptorContext<TRequest, TResponse>(
original.Method,
original.Host,
original.Options.WithHeaders(headers));
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8528d8ee967e042ecb2a5e8285c425e0
@@ -0,0 +1,193 @@
using System;
using System.Threading.Tasks;
using Net.Eagle0.Eagle.Api.Auth;
using UnityEngine;
namespace Auth {
/// <summary>
/// Manages OAuth authentication flow using server-mediated polling:
/// - Opens system browser for OAuth consent
/// - Polls server for OAuth completion (no deep links needed)
/// - Token storage and refresh
/// </summary>
public class OAuthManager : MonoBehaviour {
public static OAuthManager Instance { get; private set; }
private AuthClient _authClient;
private string _currentAuthServiceUrl;
private string _currentEagleUrl;
// Events for UI updates
public event Action<UserInfo> OnLoginSuccess;
public event Action<string> OnLoginFailed;
public event Action OnLogout;
public event Action<bool> OnNewUserNeedsDisplayName; // true if new user
public bool IsAuthenticated => TokenStorage.HasValidToken;
public string DisplayName => TokenStorage.DisplayName;
public string UserId => TokenStorage.UserId;
private void Awake() {
if (Instance != null && Instance != this) {
Destroy(gameObject);
return;
}
Instance = this;
DontDestroyOnLoad(gameObject);
// Initialize TokenStorage cache from PlayerPrefs on main thread
// This allows background threads to access tokens safely
TokenStorage.InitializeCache();
// AuthClient is created lazily when SetServerUrls is called
}
/// <summary>
/// Set the server URLs for OAuth and game requests. Call this before any OAuth operations.
/// </summary>
/// <param name="authServiceUrl">Go auth service URL, e.g.
/// "https://prod.eagle0.net:40033"</param> <param name="eagleUrl">Eagle server URL, e.g.
/// "https://prod.eagle0.net:40032"</param>
public void SetServerUrls(string authServiceUrl, string eagleUrl) {
if (_currentAuthServiceUrl == authServiceUrl && _currentEagleUrl == eagleUrl &&
_authClient != null) {
return; // Already configured for these URLs
}
_authClient?.Dispose();
_currentAuthServiceUrl = authServiceUrl;
_currentEagleUrl = eagleUrl;
_authClient = new AuthClient(authServiceUrl, eagleUrl);
Debug.Log($"[OAuthManager] Configured: authService={authServiceUrl}, eagle={eagleUrl}");
}
private void OnDestroy() {
_authClient?.Dispose();
if (Instance == this) { Instance = null; }
}
private void EnsureConfigured() {
if (_authClient == null) {
throw new InvalidOperationException(
"OAuthManager not configured. Call SetServerUrls() first.");
}
}
/// <summary>
/// Start OAuth login with specified provider.
/// Opens system browser for user consent, then polls for completion.
/// </summary>
public async Task<CheckOAuthStatusResponse> LoginAsync(OAuthProvider provider) {
EnsureConfigured();
try {
// Get OAuth URL and state from server
var (authUrl, state) = await _authClient.GetOAuthUrlAsync(provider);
// Open system browser
Debug.Log($"[OAuthManager] Opening browser: {authUrl}");
Application.OpenURL(authUrl);
// Poll for OAuth completion (server handles the callback)
var response = await _authClient.PollForOAuthCompletionAsync(state);
// Store tokens
TokenStorage.StoreTokens(
response.AccessToken,
response.RefreshToken,
response.ExpiresAt,
response.User.UserId,
response.User.DisplayName ?? "");
// Notify listeners
if (response.IsNewUser) {
OnNewUserNeedsDisplayName?.Invoke(true);
} else {
OnLoginSuccess?.Invoke(response.User);
}
return response;
} catch (Exception ex) {
Debug.LogError($"[OAuthManager] Login failed: {ex.Message}");
OnLoginFailed?.Invoke(ex.Message);
throw;
}
}
/// <summary>
/// Set display name for new user after OAuth.
/// </summary>
public async Task<bool> SetDisplayNameAsync(string displayName) {
EnsureConfigured();
var response = await _authClient.SetDisplayNameAsync(displayName);
if (response.Success) { OnLoginSuccess?.Invoke(response.User); }
return response.Success;
}
/// <summary>
/// Try to restore session from stored tokens.
/// Returns true if valid session exists.
/// Must call SetServerUrls() before this method.
/// </summary>
public async Task<bool> TryRestoreSessionAsync() {
if (_authClient == null) {
Debug.Log("[OAuthManager] Not configured yet, skipping session restore");
return false;
}
if (!TokenStorage.HasValidToken && !TokenStorage.HasRefreshToken) {
Debug.Log("[OAuthManager] No stored session");
return false;
}
// If token is expired but we have refresh token, try to refresh
if (!TokenStorage.HasValidToken && TokenStorage.HasRefreshToken) {
try {
await _authClient.RefreshTokenAsync();
} catch (Exception ex) {
Debug.LogWarning($"[OAuthManager] Token refresh failed: {ex.Message}");
TokenStorage.Clear();
return false;
}
}
// Validate session with server
try {
var response = await _authClient.GetCurrentUserAsync();
Debug.Log($"[OAuthManager] Session restored for {response.User.DisplayName}");
OnLoginSuccess?.Invoke(response.User);
return true;
} catch (Exception ex) {
Debug.LogWarning($"[OAuthManager] Session validation failed: {ex.Message}");
TokenStorage.Clear();
return false;
}
}
/// <summary>
/// Refresh access token if needed.
/// Call this before making API requests.
/// </summary>
public async Task EnsureValidTokenAsync() {
EnsureConfigured();
if (TokenStorage.NeedsRefresh && TokenStorage.HasRefreshToken) {
await _authClient.RefreshTokenAsync();
}
}
/// <summary>
/// Logout and clear stored tokens.
/// </summary>
public async Task LogoutAsync() {
// LogoutAsync can work even without server connection - just clear local tokens
if (_authClient != null) {
await _authClient.LogoutAsync();
} else {
TokenStorage.Clear();
}
OnLogout?.Invoke();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 0e9d5b0cb9f26477eaf26e8a09c41707
@@ -0,0 +1,176 @@
using System;
using UnityEngine;
namespace Auth {
/// <summary>
/// Secure storage for OAuth tokens using Unity's PlayerPrefs.
/// Values are cached in memory to allow access from background threads.
/// In production, consider using platform-specific secure storage
/// (Keychain on iOS, Keystore on Android).
/// </summary>
public static class TokenStorage {
private const string AccessTokenKey = "eagle0_access_token";
private const string RefreshTokenKey = "eagle0_refresh_token";
private const string ExpiresAtKey = "eagle0_expires_at";
private const string UserIdKey = "eagle0_user_id";
private const string DisplayNameKey = "eagle0_display_name";
// In-memory cache for thread-safe access from background threads
// PlayerPrefs can only be accessed from the main thread
private static string _cachedAccessToken;
private static string _cachedRefreshToken;
private static long _cachedExpiresAt;
private static string _cachedUserId;
private static string _cachedDisplayName;
private static bool _cacheInitialized = false;
/// <summary>
/// Initialize cache from PlayerPrefs. Must be called from main thread.
/// Call this early in app startup (e.g., in Awake or Start).
/// </summary>
public static void InitializeCache() {
_cachedAccessToken = PlayerPrefs.GetString(AccessTokenKey, null);
_cachedRefreshToken = PlayerPrefs.GetString(RefreshTokenKey, null);
_cachedExpiresAt =
long.TryParse(PlayerPrefs.GetString(ExpiresAtKey, "0"), out var val) ? val : 0;
_cachedUserId = PlayerPrefs.GetString(UserIdKey, null);
_cachedDisplayName = PlayerPrefs.GetString(DisplayNameKey, null);
_cacheInitialized = true;
Debug.Log(
$"[TokenStorage] Cache initialized, hasToken={!string.IsNullOrEmpty(_cachedAccessToken)}");
}
public static bool HasValidToken {
get {
var token = AccessToken;
var expiresAt = ExpiresAt;
return !string.IsNullOrEmpty(token) &&
expiresAt > DateTimeOffset.UtcNow.ToUnixTimeSeconds();
}
}
public static bool HasRefreshToken => !string.IsNullOrEmpty(RefreshToken);
public static string AccessToken {
get {
if (!_cacheInitialized) {
Debug.LogWarning(
"[TokenStorage] Cache not initialized, returning cached value anyway");
}
return _cachedAccessToken;
}
private
set {
_cachedAccessToken = value;
PlayerPrefs.SetString(AccessTokenKey, value ?? "");
}
}
public static string RefreshToken {
get => _cachedRefreshToken;
private
set {
_cachedRefreshToken = value;
PlayerPrefs.SetString(RefreshTokenKey, value ?? "");
}
}
public static long ExpiresAt {
get => _cachedExpiresAt;
private
set {
_cachedExpiresAt = value;
PlayerPrefs.SetString(ExpiresAtKey, value.ToString());
}
}
public static string UserId {
get => _cachedUserId;
private
set {
_cachedUserId = value;
PlayerPrefs.SetString(UserIdKey, value ?? "");
}
}
public static string DisplayName {
get => _cachedDisplayName;
private
set {
_cachedDisplayName = value;
PlayerPrefs.SetString(DisplayNameKey, value ?? "");
}
}
/// <summary>
/// Store tokens received from OAuth exchange.
/// </summary>
public static void StoreTokens(
string accessToken,
string refreshToken,
long expiresAt,
string userId,
string displayName) {
AccessToken = accessToken;
RefreshToken = refreshToken;
ExpiresAt = expiresAt;
UserId = userId;
DisplayName = displayName;
PlayerPrefs.Save();
Debug.Log(
$"[TokenStorage] Stored tokens for user {displayName} (expires at {expiresAt})");
}
/// <summary>
/// Update access token after refresh.
/// </summary>
public static void UpdateAccessToken(string accessToken, long expiresAt) {
AccessToken = accessToken;
ExpiresAt = expiresAt;
PlayerPrefs.Save();
Debug.Log($"[TokenStorage] Updated access token (expires at {expiresAt})");
}
/// <summary>
/// Update display name after user sets it.
/// </summary>
public static void UpdateDisplayName(string displayName) {
DisplayName = displayName;
PlayerPrefs.Save();
}
/// <summary>
/// Clear all stored tokens (logout).
/// </summary>
public static void Clear() {
_cachedAccessToken = null;
_cachedRefreshToken = null;
_cachedExpiresAt = 0;
_cachedUserId = null;
_cachedDisplayName = null;
PlayerPrefs.DeleteKey(AccessTokenKey);
PlayerPrefs.DeleteKey(RefreshTokenKey);
PlayerPrefs.DeleteKey(ExpiresAtKey);
PlayerPrefs.DeleteKey(UserIdKey);
PlayerPrefs.DeleteKey(DisplayNameKey);
PlayerPrefs.Save();
Debug.Log("[TokenStorage] Cleared all tokens");
}
/// <summary>
/// Check if token needs refresh (expires within 5 minutes).
/// </summary>
public static bool NeedsRefresh {
get {
var expiresAt = ExpiresAt;
var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
return expiresAt > 0 && expiresAt - now < 300; // 5 minutes
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4b1f130cec656466893fa04ba789d34f
@@ -29,9 +29,9 @@ RectTransform:
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 616210323856016607}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0}
m_AnchorMax: {x: 0, y: 0}
@@ -105,20 +105,23 @@ MonoBehaviour:
m_VerticalAlignment: 512
m_textAlignment: 65535
m_characterSpacing: 0
m_characterHorizontalScale: 1
m_wordSpacing: 0
m_lineSpacing: 0
m_lineSpacingMax: 0
m_paragraphSpacing: 0
m_charWidthMaxAdj: 0
m_enableWordWrapping: 1
m_TextWrappingMode: 1
m_wordWrappingRatios: 0.4
m_overflowMode: 0
m_linkedTextComponent: {fileID: 0}
parentLinkedComponent: {fileID: 0}
m_enableKerning: 1
m_ActiveFontFeatures: 6e72656b
m_enableExtraPadding: 0
checkPaddingRequired: 0
m_isRichText: 1
m_EmojiFallbackSupport: 1
m_parseCtrlCharacters: 1
m_isOrthographic: 1
m_isCullingEnabled: 0
@@ -185,9 +188,9 @@ RectTransform:
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 616210323856016607}
m_RootOrder: 2
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0}
m_AnchorMax: {x: 0, y: 0}
@@ -261,20 +264,23 @@ MonoBehaviour:
m_VerticalAlignment: 512
m_textAlignment: 65535
m_characterSpacing: 0
m_characterHorizontalScale: 1
m_wordSpacing: 0
m_lineSpacing: 0
m_lineSpacingMax: 0
m_paragraphSpacing: 0
m_charWidthMaxAdj: 0
m_enableWordWrapping: 1
m_TextWrappingMode: 1
m_wordWrappingRatios: 0.4
m_overflowMode: 0
m_linkedTextComponent: {fileID: 0}
parentLinkedComponent: {fileID: 0}
m_enableKerning: 1
m_ActiveFontFeatures: 6e72656b
m_enableExtraPadding: 0
checkPaddingRequired: 0
m_isRichText: 1
m_EmojiFallbackSupport: 1
m_parseCtrlCharacters: 1
m_isOrthographic: 1
m_isCullingEnabled: 0
@@ -344,10 +350,10 @@ RectTransform:
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 1806945232979884877}
m_Father: {fileID: 616210323856016607}
m_RootOrder: 3
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0}
m_AnchorMax: {x: 0, y: 0}
@@ -425,6 +431,7 @@ MonoBehaviour:
atime6: 0
atime7: 0
m_Mode: 0
m_ColorSpace: -1
m_NumColorKeys: 2
m_NumAlphaKeys: 2
_gradientType: 0
@@ -564,9 +571,9 @@ RectTransform:
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 7057983938046569337}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0}
m_AnchorMax: {x: 1, y: 1}
@@ -640,20 +647,23 @@ MonoBehaviour:
m_VerticalAlignment: 512
m_textAlignment: 65535
m_characterSpacing: 0
m_characterHorizontalScale: 1
m_wordSpacing: 0
m_lineSpacing: 0
m_lineSpacingMax: 0
m_paragraphSpacing: 0
m_charWidthMaxAdj: 0
m_enableWordWrapping: 1
m_TextWrappingMode: 1
m_wordWrappingRatios: 0.4
m_overflowMode: 0
m_linkedTextComponent: {fileID: 0}
parentLinkedComponent: {fileID: 0}
m_enableKerning: 1
m_ActiveFontFeatures: 6e72656b
m_enableExtraPadding: 0
checkPaddingRequired: 0
m_isRichText: 1
m_EmojiFallbackSupport: 1
m_parseCtrlCharacters: 1
m_isOrthographic: 1
m_isCullingEnabled: 0
@@ -701,13 +711,15 @@ RectTransform:
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 2291298599107070085}
- {fileID: 8906549728612534620}
- {fileID: 6686534948942979506}
- {fileID: 6700597635350808166}
- {fileID: 8218751192785770547}
- {fileID: 7057983938046569337}
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0}
m_AnchorMax: {x: 1, y: 1}
@@ -796,31 +808,295 @@ MonoBehaviour:
playerCountField: {fileID: 8350902200036365361}
joinButton: {fileID: 437043893514773017}
buttonText: {fileID: 2170549136187147757}
--- !u!114 &2580770409874757745
dropButton: {fileID: 19903828017934214}
--- !u!1 &7127645211350815762
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 8218751192785770547}
- component: {fileID: 3533697289353260343}
m_Layer: 5
m_Name: spacer
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!224 &8218751192785770547
RectTransform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 7127645211350815762}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 616210323856016607}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0}
m_AnchorMax: {x: 0, y: 0}
m_AnchoredPosition: {x: 0, y: 0}
m_SizeDelta: {x: 0, y: 0}
m_Pivot: {x: 0.5, y: 0.5}
--- !u!114 &3533697289353260343
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 8906549728612534621}
m_GameObject: {fileID: 7127645211350815762}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 306cc8c2b49d7114eaa3623786fc2126, type: 3}
m_Name:
m_EditorClassIdentifier: UnityEngine.UI::UnityEngine.UI.LayoutElement
m_IgnoreLayout: 0
m_MinWidth: 10
m_MinHeight: -1
m_PreferredWidth: 10
m_PreferredHeight: -1
m_FlexibleWidth: -1
m_FlexibleHeight: -1
m_LayoutPriority: 1
--- !u!1 &7934454793097069971
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 6700597635350808166}
- component: {fileID: 5023923008883954850}
- component: {fileID: 19903828017934214}
- component: {fileID: 2151248441631091217}
- component: {fileID: 7406323257372084547}
m_Layer: 5
m_Name: Drop Game Button
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!224 &6700597635350808166
RectTransform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 7934454793097069971}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 1846732971937087380}
m_Father: {fileID: 616210323856016607}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0}
m_AnchorMax: {x: 0, y: 0}
m_AnchoredPosition: {x: 0, y: 0}
m_SizeDelta: {x: 0, y: 0}
m_Pivot: {x: 0.5, y: 0.5}
--- !u!222 &5023923008883954850
CanvasRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 7934454793097069971}
m_CullTransparentMesh: 0
--- !u!114 &19903828017934214
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 7934454793097069971}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 4e29b1a8efbd4b44bb3f3716e73f07ff, type: 3}
m_Name:
m_EditorClassIdentifier:
m_Navigation:
m_Mode: 0
m_WrapAround: 0
m_SelectOnUp: {fileID: 0}
m_SelectOnDown: {fileID: 0}
m_SelectOnLeft: {fileID: 0}
m_SelectOnRight: {fileID: 0}
m_Transition: 1
m_Colors:
m_NormalColor: {r: 1, g: 0.42745098, b: 0.42745098, a: 1}
m_HighlightedColor: {r: 0.84313726, g: 0.84313726, b: 0.84313726, a: 1}
m_PressedColor: {r: 0, g: 0, b: 0, a: 1}
m_SelectedColor: {r: 0.84313726, g: 0.84313726, b: 0.84313726, a: 1}
m_DisabledColor: {r: 1, g: 1, b: 1, a: 0.39215687}
m_ColorMultiplier: 1
m_FadeDuration: 0.1
m_SpriteState:
m_HighlightedSprite: {fileID: 0}
m_PressedSprite: {fileID: 0}
m_SelectedSprite: {fileID: 0}
m_DisabledSprite: {fileID: 0}
m_AnimationTriggers:
m_NormalTrigger: Normal
m_HighlightedTrigger: Highlighted
m_PressedTrigger: Pressed
m_SelectedTrigger: Highlighted
m_DisabledTrigger: Disabled
m_Interactable: 1
m_TargetGraphic: {fileID: 2151248441631091217}
m_OnClick:
m_PersistentCalls:
m_Calls:
- m_Target: {fileID: 7332722509251528870}
m_TargetAssemblyTypeName: AvailableGameItem, Assembly-CSharp
m_MethodName: DropClicked
m_Mode: 1
m_Arguments:
m_ObjectArgument: {fileID: 0}
m_ObjectArgumentAssemblyTypeName: UnityEngine.Object, UnityEngine
m_IntArgument: 0
m_FloatArgument: 0
m_StringArgument:
m_BoolArgument: 0
m_CallState: 2
--- !u!114 &2151248441631091217
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 7934454793097069971}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3}
m_Name:
m_EditorClassIdentifier:
m_Material: {fileID: 0}
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_RaycastTarget: 1
m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0}
m_Maskable: 1
m_OnCullStateChanged:
m_PersistentCalls:
m_Calls: []
m_Sprite: {fileID: 21300000, guid: f03f625cc7127f244a2f4da835b92720, type: 3}
m_Type: 1
m_PreserveAspect: 0
m_FillCenter: 1
m_FillMethod: 4
m_FillAmount: 1
m_FillClockwise: 1
m_FillOrigin: 0
m_UseSpriteMesh: 0
m_PixelsPerUnitMultiplier: 1
--- !u!114 &7406323257372084547
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 7934454793097069971}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 306cc8c2b49d7114eaa3623786fc2126, type: 3}
m_Name:
m_EditorClassIdentifier:
m_IgnoreLayout: 0
m_MinWidth: 700
m_MinWidth: 50
m_MinHeight: -1
m_PreferredWidth: 700
m_PreferredWidth: 50
m_PreferredHeight: -1
m_FlexibleWidth: 1
m_FlexibleWidth: -1
m_FlexibleHeight: -1
m_LayoutPriority: 1
--- !u!1 &8839297347726735035
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1846732971937087380}
- component: {fileID: 2464975641276684442}
- component: {fileID: 4051352560264867900}
m_Layer: 5
m_Name: Icon
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!224 &1846732971937087380
RectTransform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 8839297347726735035}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 6700597635350808166}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0}
m_AnchorMax: {x: 1, y: 1}
m_AnchoredPosition: {x: 0, y: 0}
m_SizeDelta: {x: 0, y: 0}
m_Pivot: {x: 0.5, y: 0.5}
--- !u!222 &2464975641276684442
CanvasRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 8839297347726735035}
m_CullTransparentMesh: 1
--- !u!114 &4051352560264867900
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 8839297347726735035}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 1344c3c82d62a2a41a3576d8abb8e3ea, type: 3}
m_Name:
m_EditorClassIdentifier: UnityEngine.UI::UnityEngine.UI.RawImage
m_Material: {fileID: 0}
m_Color: {r: 0, g: 0, b: 0, a: 1}
m_RaycastTarget: 1
m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0}
m_Maskable: 1
m_OnCullStateChanged:
m_PersistentCalls:
m_Calls: []
m_Texture: {fileID: 2800000, guid: 8c998213d53883d4b8fdf7a3eb3c2909, type: 3}
m_UVRect:
serializedVersion: 2
x: 0
y: 0
width: 1
height: 1
--- !u!1001 &3324269289066796519
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
serializedVersion: 3
m_TransformParent: {fileID: 616210323856016607}
m_Modifications:
- target: {fileID: 6176764421848850767, guid: 59599ef87ad824f52ada88f126d58c5f,
@@ -833,6 +1109,11 @@ PrefabInstance:
propertyPath: m_fontSizeBase
value: 24
objectReference: {fileID: 0}
- target: {fileID: 6176764421848850767, guid: 59599ef87ad824f52ada88f126d58c5f,
type: 3}
propertyPath: 'm_ActiveFontFeatures.Array.data[0]'
value: 1801810542
objectReference: {fileID: 0}
- target: {fileID: 6176764421927073094, guid: 59599ef87ad824f52ada88f126d58c5f,
type: 3}
propertyPath: m_fontSize
@@ -959,6 +1240,13 @@ PrefabInstance:
value: 0
objectReference: {fileID: 0}
m_RemovedComponents: []
m_RemovedGameObjects: []
m_AddedGameObjects: []
m_AddedComponents:
- targetCorrespondingSourceObject: {fileID: 6176764422977772730, guid: 59599ef87ad824f52ada88f126d58c5f,
type: 3}
insertIndex: -1
addedObject: {fileID: 2580770409874757745}
m_SourcePrefab: {fileID: 100100000, guid: 59599ef87ad824f52ada88f126d58c5f, type: 3}
--- !u!114 &8906549728612534595 stripped
MonoBehaviour:
@@ -984,3 +1272,23 @@ GameObject:
type: 3}
m_PrefabInstance: {fileID: 3324269289066796519}
m_PrefabAsset: {fileID: 0}
--- !u!114 &2580770409874757745
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 8906549728612534621}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 306cc8c2b49d7114eaa3623786fc2126, type: 3}
m_Name:
m_EditorClassIdentifier:
m_IgnoreLayout: 0
m_MinWidth: 700
m_MinHeight: -1
m_PreferredWidth: 700
m_PreferredHeight: -1
m_FlexibleWidth: 1
m_FlexibleHeight: -1
m_LayoutPriority: 1
@@ -16,8 +16,10 @@ public class AvailableGameItem : MonoBehaviour {
public TextMeshProUGUI playerCountField;
public Button joinButton;
public TextMeshProUGUI buttonText;
public Button dropButton;
public Action<long, string> JoinCallback;
public Action<long> DropCallback;
private List<AvailableLeader> availableLeaders;
private long gameId;
@@ -38,6 +40,8 @@ public class AvailableGameItem : MonoBehaviour {
public void JoinClicked() { JoinCallback(gameId, SelectedLeaderTextId); }
public void DropClicked() { DropCallback?.Invoke(gameId); }
public void
SetAvailableNewGame(long gameId, string playersString, List<AvailableLeader> leaders) {
availableLeaders = leaders;
@@ -7,15 +7,18 @@ using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Auth;
using common;
using common.GUIUtils;
using eagle;
using Grpc.Core;
using Grpc.Core.Interceptors;
using Net.Eagle0.Eagle.Api;
using Net.Eagle0.Eagle.Api.Auth;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using Object = System.Object;
public class AuthInterceptor : Interceptor {
@@ -82,6 +85,23 @@ public class ConnectionHandler : MonoBehaviour, ILobbySubscriber, IDisposable {
public TMP_InputField passwordField;
public TMP_Dropdown resolutionDropdown;
[Header("OAuth UI")]
public GameObject oauthPanel;
public Button discordLoginButton;
public Button googleLoginButton;
public TextMeshProUGUI oauthStatusText;
[Header("Display Name Setup")]
public GameObject displayNamePanel;
public TMP_InputField displayNameField;
public Button setDisplayNameButton;
public TextMeshProUGUI displayNameErrorText;
[Header("Legacy Auth (for testing)")]
public GameObject legacyAuthPanel;
public Button useLegacyAuthButton;
public TextMeshProUGUI useLegacyAuthButtonText;
[Header("Status Display")]
public TextMeshProUGUI connectionStatusText;
@@ -90,6 +110,13 @@ public class ConnectionHandler : MonoBehaviour, ILobbySubscriber, IDisposable {
public GameObject customBattlePanel;
public ErrorHandler errorHandler;
[Header("Lobby Controls")]
public Button logoutButton;
public Button customBattleButton;
public Button cancelCustomBattleButton;
public TextMeshProUGUI lobbyEnvironmentText;
public TextMeshProUGUI lobbyUserText;
public GameObject runningGamesListArea;
public GameObject runningGamesListItemPrefab;
@@ -98,6 +125,8 @@ public class ConnectionHandler : MonoBehaviour, ILobbySubscriber, IDisposable {
public GameObject waitingGamesListItemPrefab;
public GameObject createGameListItemPrefab;
public DropGameConfirmationPanel dropGameConfirmationPanel;
public Canvas connectionCanvas;
public Canvas eagleCanvas;
public Canvas shardokCanvas;
@@ -112,6 +141,8 @@ public class ConnectionHandler : MonoBehaviour, ILobbySubscriber, IDisposable {
private bool listen = false;
private CancellationTokenSource _cancellationTokenSource;
private readonly Object pendingReplyLock = new Object();
private int _connectedEnvironmentIndex = -1; // -1 means not connected
private bool _useOAuth = false; // Default to legacy until server-side OAuth is ready
public ClientPregeneratedText clientPregeneratedText;
@@ -125,12 +156,33 @@ public class ConnectionHandler : MonoBehaviour, ILobbySubscriber, IDisposable {
private static readonly List<string> EnvironmentDisplayNames =
new() { "prod.", "qa.", "(none)" };
/// <summary>
/// Returns the connected environment name ("prod." or "qa.") or null if not connected.
/// </summary>
public string ConnectedEnvironmentName =>
_connectedEnvironmentIndex >= 0 &&
_connectedEnvironmentIndex < EnvironmentDisplayNames.Count
? EnvironmentDisplayNames[_connectedEnvironmentIndex]
: null;
private string GetUrlFromEnvironment() {
int envIndex = environmentDropdown.value;
string prefix = EnvironmentOptions[envIndex];
return prefix + BaseDomain;
}
/// <summary>
/// Get full URL with scheme for the selected environment (Eagle server).
/// Remote servers use HTTPS, could be extended for local HTTP.
/// </summary>
private string GetEagleUrl() { return "https://" + GetUrlFromEnvironment(); }
/// <summary>
/// Get full URL with scheme for the Go auth service.
/// Always uses prod auth service - OAuth tokens work across all environments.
/// </summary>
private string GetAuthServiceUrl() { return "https://prod.eagle0.net:40033"; }
public void ReceiveLobbyUpdate(LobbyResponse lobbyResponse) {
_handleLobbyResponse(lobbyResponse);
}
@@ -166,8 +218,218 @@ public class ConnectionHandler : MonoBehaviour, ILobbySubscriber, IDisposable {
errorHandler.gameObject.SetActive(true);
// Initialize OAuth UI
SetupOAuthUI();
// Initialize Lobby UI (logout button, etc.)
SetupLobbyUI();
// Initialize status text
UpdateConnectionStatus();
// Try to restore existing OAuth session
TryRestoreSession();
}
private void SetupOAuthUI() {
// Set up OAuth button click handlers
if (discordLoginButton != null) {
discordLoginButton.onClick.AddListener(
() => OnOAuthLoginClicked(OAuthProvider.Discord));
}
if (googleLoginButton != null) {
googleLoginButton.onClick.AddListener(() => OnOAuthLoginClicked(OAuthProvider.Google));
}
if (setDisplayNameButton != null) {
setDisplayNameButton.onClick.AddListener(OnSetDisplayNameClicked);
}
if (useLegacyAuthButton != null) {
useLegacyAuthButton.onClick.AddListener(OnUseLegacyAuthClicked);
}
// Subscribe to OAuthManager events
if (OAuthManager.Instance != null) {
OAuthManager.Instance.OnLoginSuccess += OnOAuthLoginSuccess;
OAuthManager.Instance.OnLoginFailed += OnOAuthLoginFailed;
OAuthManager.Instance.OnNewUserNeedsDisplayName += OnNewUserNeedsDisplayName;
OAuthManager.Instance.OnLogout += OnOAuthLogout;
}
// Show appropriate panel based on auth state
ShowAuthPanel();
}
private void ShowAuthPanel() {
// Hide all auth panels first
if (oauthPanel != null) oauthPanel.SetActive(false);
if (displayNamePanel != null) displayNamePanel.SetActive(false);
if (legacyAuthPanel != null) legacyAuthPanel.SetActive(false);
// Show appropriate panel based on _useOAuth
if (_useOAuth) {
if (oauthPanel != null) oauthPanel.SetActive(true);
if (useLegacyAuthButtonText != null)
useLegacyAuthButtonText.text = "Use Classic Sign-in";
} else {
if (legacyAuthPanel != null) legacyAuthPanel.SetActive(true);
if (useLegacyAuthButtonText != null) useLegacyAuthButtonText.text = "Use OAuth Sign-in";
}
}
private void SetupLobbyUI() {
if (logoutButton != null) { logoutButton.onClick.AddListener(OnLogoutClicked); }
if (customBattleButton != null) { customBattleButton.onClick.AddListener(CustomBattle); }
if (cancelCustomBattleButton != null) {
cancelCustomBattleButton.onClick.AddListener(CancelCustomBattle);
}
}
private void UpdateLobbyStatusDisplays() {
// Show environment (prod/qa)
if (lobbyEnvironmentText != null) {
lobbyEnvironmentText.text = ConnectedEnvironmentName ?? "";
}
// Show current user - prefer OAuth display name, fall back to classic login name
if (lobbyUserText != null) {
if (_useOAuth && !string.IsNullOrEmpty(TokenStorage.DisplayName)) {
lobbyUserText.text = TokenStorage.DisplayName;
} else {
lobbyUserText.text = nameField.text;
}
}
}
private async void OnLogoutClicked() {
Debug.Log("[ConnectionHandler] Logout button clicked");
// Clear OAuth tokens
if (OAuthManager.Instance != null) { await OAuthManager.Instance.LogoutAsync(); }
// Disconnect from server
_persistentClientConnection?.Dispose();
eagleConnection?.Dispose();
_httpClient?.Dispose();
_cancellationTokenSource?.Dispose();
_persistentClientConnection = null;
eagleConnection = null;
_httpClient = null;
_cancellationTokenSource = null;
_connectedEnvironmentIndex = -1;
// Return to connection screen
gameSelectionPanel.SetActive(false);
connectionPanel.SetActive(true);
// Re-initialize the auth UI
ShowAuthPanel();
UpdateConnectionStatus();
}
private async void TryRestoreSession() {
if (OAuthManager.Instance == null) return;
// Configure OAuthManager with auth service and Eagle URLs
OAuthManager.Instance.SetServerUrls(GetAuthServiceUrl(), GetEagleUrl());
if (oauthStatusText != null) { oauthStatusText.text = "Checking for existing session..."; }
var restored = await OAuthManager.Instance.TryRestoreSessionAsync();
if (restored) {
// Session restored, connect to lobby
ConnectWithOAuth();
} else if (oauthStatusText != null) {
oauthStatusText.text = "";
}
}
private async void OnOAuthLoginClicked(OAuthProvider provider) {
// Configure OAuthManager with auth service and Eagle URLs (user may have changed dropdown)
OAuthManager.Instance.SetServerUrls(GetAuthServiceUrl(), GetEagleUrl());
if (oauthStatusText != null) {
oauthStatusText.text = $"Opening browser for {provider} login...";
}
try {
await OAuthManager.Instance.LoginAsync(provider);
// OnLoginSuccess or OnNewUserNeedsDisplayName will be called
} catch (Exception ex) {
Debug.LogError($"OAuth login failed: {ex.Message}");
if (oauthStatusText != null) { oauthStatusText.text = $"Login failed: {ex.Message}"; }
}
}
private void OnOAuthLoginSuccess(UserInfo user) {
MainQueue.Q.Enqueue(() => {
if (oauthStatusText != null) { oauthStatusText.text = $"Welcome, {user.DisplayName}!"; }
ConnectWithOAuth();
});
}
private void OnOAuthLoginFailed(string error) {
MainQueue.Q.Enqueue(() => {
if (oauthStatusText != null) { oauthStatusText.text = $"Login failed: {error}"; }
});
}
private void OnNewUserNeedsDisplayName(bool isNewUser) {
MainQueue.Q.Enqueue(() => {
// Show display name panel
if (oauthPanel != null) oauthPanel.SetActive(false);
if (displayNamePanel != null) displayNamePanel.SetActive(true);
if (displayNameErrorText != null) displayNameErrorText.text = "";
});
}
private async void OnSetDisplayNameClicked() {
if (displayNameField == null || OAuthManager.Instance == null) return;
var displayName = displayNameField.text.Trim();
if (string.IsNullOrEmpty(displayName)) {
if (displayNameErrorText != null) {
displayNameErrorText.text = "Please enter a display name";
}
return;
}
if (displayNameErrorText != null) { displayNameErrorText.text = "Setting display name..."; }
var success = await OAuthManager.Instance.SetDisplayNameAsync(displayName);
if (!success && displayNameErrorText != null) {
displayNameErrorText.text = "Name already taken or invalid. Try another.";
}
// OnLoginSuccess will be called if successful
}
private void OnOAuthLogout() {
MainQueue.Q.Enqueue(() => {
ShowAuthPanel();
if (oauthStatusText != null) { oauthStatusText.text = ""; }
});
}
private void OnUseLegacyAuthClicked() {
_useOAuth = !_useOAuth; // Toggle instead of just setting false
if (_useOAuth) {
// Show OAuth panel
if (oauthPanel != null) oauthPanel.SetActive(true);
if (legacyAuthPanel != null) legacyAuthPanel.SetActive(false);
if (useLegacyAuthButtonText != null)
useLegacyAuthButtonText.text = "Use Classic Sign-in";
} else {
// Show legacy panel
if (oauthPanel != null) oauthPanel.SetActive(false);
if (legacyAuthPanel != null) legacyAuthPanel.SetActive(true);
if (useLegacyAuthButtonText != null) useLegacyAuthButtonText.text = "Use OAuth Sign-in";
}
}
private void ConnectWithOAuth() {
_useOAuth = true;
_internalConnectEagle();
}
private float _statusUpdateTimer = 0f;
@@ -245,6 +507,14 @@ public class ConnectionHandler : MonoBehaviour, ILobbySubscriber, IDisposable {
public void CustomBattle() { _internalCustomBattle(); }
public void CancelCustomBattle() {
customBattlePanel.SetActive(false);
shardokCanvas.gameObject.SetActive(false);
connectionCanvas.gameObject.SetActive(true);
gameSelectionPanel.SetActive(true);
StartListeningForLobbyUpdates();
}
public void OnApplicationQuit() { Dispose(); }
public void Dispose() {
@@ -262,6 +532,8 @@ public class ConnectionHandler : MonoBehaviour, ILobbySubscriber, IDisposable {
_persistentClientConnection = null;
eagleConnection?.Dispose();
eagleConnection = null;
_connectedEnvironmentIndex = -1;
}
public void OnResolutionChanged(int dropdownIndex) {
@@ -289,6 +561,9 @@ public class ConnectionHandler : MonoBehaviour, ILobbySubscriber, IDisposable {
connectionPanel.gameObject.SetActive(false);
gameSelectionPanel.gameObject.SetActive(true);
// Update lobby status displays
UpdateLobbyStatusDisplays();
// Set up running games table
foreach (Transform row in runningGamesListArea.transform) { Destroy(row.gameObject); }
foreach (var runningGame in lobbyResponse.RunningGames) {
@@ -297,10 +572,10 @@ public class ConnectionHandler : MonoBehaviour, ILobbySubscriber, IDisposable {
runningGamesListArea.transform,
true);
listItem.transform.localScale = new Vector3 { x = 1.0f, y = 1.0f, z = 1.0f };
listItem.GetComponent<RunningGameItem>().SetRunningGame(
runningGame.GameId,
runningGame.Leader);
listItem.GetComponent<RunningGameItem>().GoCallback = this.SelectEagleGame;
var runningGameItem = listItem.GetComponent<RunningGameItem>();
runningGameItem.SetRunningGame(runningGame.GameId, runningGame.Leader);
runningGameItem.GoCallback = this.SelectEagleGame;
runningGameItem.DropCallback = this.DropGame;
}
// Set up available/waiting games table
@@ -336,14 +611,16 @@ public class ConnectionHandler : MonoBehaviour, ILobbySubscriber, IDisposable {
availableGamesListArea.transform,
true);
listItem.transform.localScale = new Vector3 { x = 1.0f, y = 1.0f, z = 1.0f };
listItem.GetComponent<AvailableGameItem>().SetAvailableNewGame(
var availableGameItem = listItem.GetComponent<AvailableGameItem>();
availableGameItem.SetAvailableNewGame(
availableGame.GameId,
string.Format(
"{0} / {1}",
availableGame.CurrentHumanPlayerCount,
availableGame.MaxHumanPlayerCount),
availableGame.AvailableLeaders.ToList());
listItem.GetComponent<AvailableGameItem>().JoinCallback = this.JoinGame;
availableGameItem.JoinCallback = this.JoinGame;
availableGameItem.DropCallback = this.DropGame;
}
});
}
@@ -357,7 +634,8 @@ public class ConnectionHandler : MonoBehaviour, ILobbySubscriber, IDisposable {
}
private void _createConnection() {
PlayerPrefs.SetInt(EnvironmentKey, environmentDropdown.value);
_connectedEnvironmentIndex = environmentDropdown.value;
PlayerPrefs.SetInt(EnvironmentKey, _connectedEnvironmentIndex);
PlayerPrefs.SetString(NameKey, nameField.text);
PlayerPrefs.SetString(PasswordKey, passwordField.text);
@@ -371,7 +649,26 @@ public class ConnectionHandler : MonoBehaviour, ILobbySubscriber, IDisposable {
_cancellationTokenSource = new CancellationTokenSource();
string url = GetUrlFromEnvironment();
eagleConnection = new EagleConnection(nameField.text, passwordField.text, url);
if (_useOAuth && TokenStorage.HasValidToken) {
// Use JWT-based connection
eagleConnection = EagleConnection.CreateWithJwt(url);
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", TokenStorage.AccessToken);
} else {
// Legacy Basic Auth connection
PlayerPrefs.SetString(NameKey, nameField.text);
PlayerPrefs.SetString(PasswordKey, passwordField.text);
eagleConnection = new EagleConnection(nameField.text, passwordField.text, url);
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", eagleConnection.authHeader);
}
_persistentClientConnection = new PersistentClientConnection(
eagleConnection.EagleGrpcClient,
eagleConnection.credentials,
@@ -379,20 +676,16 @@ public class ConnectionHandler : MonoBehaviour, ILobbySubscriber, IDisposable {
_persistentClientConnection.Connect();
errorHandler.PersistentClientConnection = _persistentClientConnection;
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", eagleConnection.authHeader);
ResourceFetcher.SetUpConnection(_httpClient);
}
private void _internalCustomBattle() {
_createConnection();
// Connection already exists when called from lobby
_persistentClientConnection.SetLobbySubscriber(this);
SetCustomBattleActive(true);
connectionPanel.SetActive(false);
gameSelectionPanel.SetActive(false);
customBattlePanel.SetActive(true);
}
@@ -440,6 +733,18 @@ public class ConnectionHandler : MonoBehaviour, ILobbySubscriber, IDisposable {
var game = _internalJoinEagleGame(gameId, leaderName);
}
private void DropGame(long gameId) {
if (dropGameConfirmationPanel != null) {
dropGameConfirmationPanel.OnConfirm = ConfirmDropGame;
dropGameConfirmationPanel.Show(gameId, "Are you sure you want to leave this game?");
} else {
// Fallback if no confirmation panel is configured
ConfirmDropGame(gameId);
}
}
private void ConfirmDropGame(long gameId) { _internalDropGame(gameId); }
private void CreateGame(string leaderNameTextId, int humanPlayerCount, int totalPlayerCount) {
var game = _internalCreateGame(leaderNameTextId, humanPlayerCount, totalPlayerCount);
}
@@ -516,6 +821,18 @@ public class ConnectionHandler : MonoBehaviour, ILobbySubscriber, IDisposable {
}
}
private async Task<bool> _internalDropGame(long gameId) {
try {
return await _persistentClientConnection.SendUpdateStreamRequestAsync(
new UpdateStreamRequest {
DropGameRequest = new DropGameRequest { GameId = gameId }
});
} catch (WebException e) {
Debug.Log(String.Format("Caught exception in DropGame {0}", e.Message));
return false;
}
}
private void SetLobbyActive(bool active) {
runningGamesListArea.SetActive(active);
availableGamesListArea.SetActive(active);
@@ -533,7 +850,8 @@ public class ConnectionHandler : MonoBehaviour, ILobbySubscriber, IDisposable {
eagleCanvas.GetComponent<EagleGameController>().SetUpGame(
gameInfo.GameId,
gameInfo.FactionId,
_persistentClientConnection);
_persistentClientConnection,
ConnectedEnvironmentName);
connectionCanvas.enabled = false;
connectionCanvas.gameObject.SetActive(false);
eagleCanvas.gameObject.SetActive(true);
@@ -0,0 +1,24 @@
using System;
using TMPro;
using UnityEngine;
public class DropGameConfirmationPanel : MonoBehaviour {
public TextMeshProUGUI messageText;
public Action<long> OnConfirm;
private long _pendingGameId;
public void Show(long gameId, string message) {
_pendingGameId = gameId;
if (messageText != null) { messageText.text = message; }
gameObject.SetActive(true);
}
public void ConfirmClicked() {
gameObject.SetActive(false);
OnConfirm?.Invoke(_pendingGameId);
}
public void CancelClicked() { gameObject.SetActive(false); }
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 558d4c7321daa4fe18dc4759a130d919
@@ -29,9 +29,9 @@ RectTransform:
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 909271087739711220}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0}
m_AnchorMax: {x: 0, y: 0}
@@ -105,20 +105,23 @@ MonoBehaviour:
m_VerticalAlignment: 512
m_textAlignment: 65535
m_characterSpacing: 0
m_characterHorizontalScale: 1
m_wordSpacing: 0
m_lineSpacing: 0
m_lineSpacingMax: 0
m_paragraphSpacing: 0
m_charWidthMaxAdj: 0
m_enableWordWrapping: 1
m_TextWrappingMode: 1
m_wordWrappingRatios: 0.4
m_overflowMode: 0
m_linkedTextComponent: {fileID: 0}
parentLinkedComponent: {fileID: 0}
m_enableKerning: 1
m_ActiveFontFeatures: 6e72656b
m_enableExtraPadding: 0
checkPaddingRequired: 0
m_isRichText: 1
m_EmojiFallbackSupport: 1
m_parseCtrlCharacters: 1
m_isOrthographic: 1
m_isCullingEnabled: 0
@@ -185,9 +188,9 @@ RectTransform:
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 909271087739711220}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0}
m_AnchorMax: {x: 0, y: 0}
@@ -261,20 +264,23 @@ MonoBehaviour:
m_VerticalAlignment: 512
m_textAlignment: 65535
m_characterSpacing: 0
m_characterHorizontalScale: 1
m_wordSpacing: 0
m_lineSpacing: 0
m_lineSpacingMax: 0
m_paragraphSpacing: 0
m_charWidthMaxAdj: 0
m_enableWordWrapping: 1
m_TextWrappingMode: 1
m_wordWrappingRatios: 0.4
m_overflowMode: 0
m_linkedTextComponent: {fileID: 0}
parentLinkedComponent: {fileID: 0}
m_enableKerning: 1
m_ActiveFontFeatures: 6e72656b
m_enableExtraPadding: 0
checkPaddingRequired: 0
m_isRichText: 1
m_EmojiFallbackSupport: 1
m_parseCtrlCharacters: 1
m_isOrthographic: 1
m_isCullingEnabled: 0
@@ -312,6 +318,216 @@ MonoBehaviour:
m_FlexibleWidth: 1
m_FlexibleHeight: -1
m_LayoutPriority: 1
--- !u!1 &4189605341159952945
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 7336928442537586311}
- component: {fileID: 3344684898730655831}
m_Layer: 5
m_Name: spacer
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!224 &7336928442537586311
RectTransform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 4189605341159952945}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 909271087739711220}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0}
m_AnchorMax: {x: 0, y: 0}
m_AnchoredPosition: {x: 0, y: 0}
m_SizeDelta: {x: 0, y: 0}
m_Pivot: {x: 0.5, y: 0.5}
--- !u!114 &3344684898730655831
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 4189605341159952945}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 306cc8c2b49d7114eaa3623786fc2126, type: 3}
m_Name:
m_EditorClassIdentifier: UnityEngine.UI::UnityEngine.UI.LayoutElement
m_IgnoreLayout: 0
m_MinWidth: 10
m_MinHeight: -1
m_PreferredWidth: 10
m_PreferredHeight: -1
m_FlexibleWidth: -1
m_FlexibleHeight: -1
m_LayoutPriority: 1
--- !u!1 &4678275134637000934
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1348356180262758599}
- component: {fileID: 8617884038396701234}
- component: {fileID: 4081637582368108930}
- component: {fileID: 5167949463556339992}
- component: {fileID: 7482580409419131173}
m_Layer: 5
m_Name: Drop Game Button
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!224 &1348356180262758599
RectTransform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 4678275134637000934}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 6454652926630703861}
m_Father: {fileID: 909271087739711220}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0}
m_AnchorMax: {x: 0, y: 0}
m_AnchoredPosition: {x: 0, y: 0}
m_SizeDelta: {x: 0, y: 0}
m_Pivot: {x: 0.5, y: 0.5}
--- !u!222 &8617884038396701234
CanvasRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 4678275134637000934}
m_CullTransparentMesh: 0
--- !u!114 &4081637582368108930
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 4678275134637000934}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 4e29b1a8efbd4b44bb3f3716e73f07ff, type: 3}
m_Name:
m_EditorClassIdentifier:
m_Navigation:
m_Mode: 0
m_WrapAround: 0
m_SelectOnUp: {fileID: 0}
m_SelectOnDown: {fileID: 0}
m_SelectOnLeft: {fileID: 0}
m_SelectOnRight: {fileID: 0}
m_Transition: 1
m_Colors:
m_NormalColor: {r: 1, g: 0.42745098, b: 0.42745098, a: 1}
m_HighlightedColor: {r: 0.84313726, g: 0.84313726, b: 0.84313726, a: 1}
m_PressedColor: {r: 0, g: 0, b: 0, a: 1}
m_SelectedColor: {r: 0.84313726, g: 0.84313726, b: 0.84313726, a: 1}
m_DisabledColor: {r: 1, g: 1, b: 1, a: 0.39215687}
m_ColorMultiplier: 1
m_FadeDuration: 0.1
m_SpriteState:
m_HighlightedSprite: {fileID: 0}
m_PressedSprite: {fileID: 0}
m_SelectedSprite: {fileID: 0}
m_DisabledSprite: {fileID: 0}
m_AnimationTriggers:
m_NormalTrigger: Normal
m_HighlightedTrigger: Highlighted
m_PressedTrigger: Pressed
m_SelectedTrigger: Highlighted
m_DisabledTrigger: Disabled
m_Interactable: 1
m_TargetGraphic: {fileID: 5167949463556339992}
m_OnClick:
m_PersistentCalls:
m_Calls:
- m_Target: {fileID: 7788402836057688155}
m_TargetAssemblyTypeName: RunningGameItem, Assembly-CSharp
m_MethodName: DropClicked
m_Mode: 1
m_Arguments:
m_ObjectArgument: {fileID: 0}
m_ObjectArgumentAssemblyTypeName: UnityEngine.Object, UnityEngine
m_IntArgument: 0
m_FloatArgument: 0
m_StringArgument:
m_BoolArgument: 0
m_CallState: 2
--- !u!114 &5167949463556339992
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 4678275134637000934}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3}
m_Name:
m_EditorClassIdentifier:
m_Material: {fileID: 0}
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_RaycastTarget: 1
m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0}
m_Maskable: 1
m_OnCullStateChanged:
m_PersistentCalls:
m_Calls: []
m_Sprite: {fileID: 21300000, guid: f03f625cc7127f244a2f4da835b92720, type: 3}
m_Type: 1
m_PreserveAspect: 0
m_FillCenter: 1
m_FillMethod: 4
m_FillAmount: 1
m_FillClockwise: 1
m_FillOrigin: 0
m_UseSpriteMesh: 0
m_PixelsPerUnitMultiplier: 1
--- !u!114 &7482580409419131173
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 4678275134637000934}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 306cc8c2b49d7114eaa3623786fc2126, type: 3}
m_Name:
m_EditorClassIdentifier:
m_IgnoreLayout: 0
m_MinWidth: 0
m_MinHeight: -1
m_PreferredWidth: 50
m_PreferredHeight: -1
m_FlexibleWidth: -1
m_FlexibleHeight: -1
m_LayoutPriority: 1
--- !u!1 &4703848583262435150
GameObject:
m_ObjectHideFlags: 0
@@ -340,9 +556,9 @@ RectTransform:
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 7341333336313446738}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0}
m_AnchorMax: {x: 1, y: 1}
@@ -416,20 +632,23 @@ MonoBehaviour:
m_VerticalAlignment: 512
m_textAlignment: 65535
m_characterSpacing: 0
m_characterHorizontalScale: 1
m_wordSpacing: 0
m_lineSpacing: 0
m_lineSpacingMax: 0
m_paragraphSpacing: 0
m_charWidthMaxAdj: 0
m_enableWordWrapping: 1
m_TextWrappingMode: 1
m_wordWrappingRatios: 0.4
m_overflowMode: 0
m_linkedTextComponent: {fileID: 0}
parentLinkedComponent: {fileID: 0}
m_enableKerning: 1
m_ActiveFontFeatures: 6e72656b
m_enableExtraPadding: 0
checkPaddingRequired: 0
m_isRichText: 1
m_EmojiFallbackSupport: 1
m_parseCtrlCharacters: 1
m_isOrthographic: 1
m_isCullingEnabled: 0
@@ -479,10 +698,10 @@ RectTransform:
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 2089905691925287270}
m_Father: {fileID: 909271087739711220}
m_RootOrder: 2
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0}
m_AnchorMax: {x: 0, y: 0}
@@ -560,6 +779,7 @@ MonoBehaviour:
atime6: 0
atime7: 0
m_Mode: 0
m_ColorSpace: -1
m_NumColorKeys: 2
m_NumAlphaKeys: 2
_gradientType: 0
@@ -702,12 +922,14 @@ RectTransform:
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 2008335870574158510}
- {fileID: 6674238761151365000}
- {fileID: 1348356180262758599}
- {fileID: 7336928442537586311}
- {fileID: 7341333336313446738}
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0}
m_AnchorMax: {x: 1, y: 1}
@@ -793,7 +1015,8 @@ MonoBehaviour:
item: {fileID: 5643565463360785033}
gameIdField: {fileID: 8058295588038032232}
leaderField: {fileID: 3311450659768657245}
goButton: {fileID: 0}
goButton: {fileID: 145214844678457394}
dropButton: {fileID: 4081637582368108930}
--- !u!114 &2208043217657811503
MonoBehaviour:
m_ObjectHideFlags: 0
@@ -814,3 +1037,75 @@ MonoBehaviour:
m_FlexibleWidth: 1
m_FlexibleHeight: 1
m_LayoutPriority: 1
--- !u!1 &7814378479006347708
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 6454652926630703861}
- component: {fileID: 374667974001408770}
- component: {fileID: 5621315126805048060}
m_Layer: 5
m_Name: Icon
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!224 &6454652926630703861
RectTransform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 7814378479006347708}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 1348356180262758599}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0}
m_AnchorMax: {x: 1, y: 1}
m_AnchoredPosition: {x: 0, y: 0}
m_SizeDelta: {x: 0, y: 0}
m_Pivot: {x: 0.5, y: 0.5}
--- !u!222 &374667974001408770
CanvasRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 7814378479006347708}
m_CullTransparentMesh: 1
--- !u!114 &5621315126805048060
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 7814378479006347708}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 1344c3c82d62a2a41a3576d8abb8e3ea, type: 3}
m_Name:
m_EditorClassIdentifier: UnityEngine.UI::UnityEngine.UI.RawImage
m_Material: {fileID: 0}
m_Color: {r: 0, g: 0, b: 0, a: 1}
m_RaycastTarget: 1
m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0}
m_Maskable: 1
m_OnCullStateChanged:
m_PersistentCalls:
m_Calls: []
m_Texture: {fileID: 2800000, guid: 8c998213d53883d4b8fdf7a3eb3c2909, type: 3}
m_UVRect:
serializedVersion: 2
x: 0
y: 0
width: 1
height: 1
@@ -10,8 +10,10 @@ public class RunningGameItem : MonoBehaviour {
public TextMeshProUGUI gameIdField;
public TextMeshProUGUI leaderField;
public Button goButton;
public Button dropButton;
public Action<long> GoCallback;
public Action<long> DropCallback;
private long gameId;
@@ -20,6 +22,8 @@ public class RunningGameItem : MonoBehaviour {
public void GoClicked() { GoCallback(gameId); }
public void DropClicked() { DropCallback?.Invoke(gameId); }
public void SetRunningGame(long gameId, AvailableLeader leader) {
this.gameId = gameId;
@@ -1,88 +0,0 @@
fileFormatVersion: 2
guid: b853582537dc740aabe996b607191fe8
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}
serializedVersion: 9
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -100
wrapU: -1
wrapV: -1
wrapW: -1
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
platformSettings:
- serializedVersion: 2
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID:
vertices: []
indices:
edges: []
weights: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using EagleGUIUtils;
@@ -6,6 +6,7 @@ using Net.Eagle0.Eagle.Api;
using Net.Eagle0.Eagle.Common;
using Net.Eagle0.Eagle.Views;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace eagle {
@@ -14,16 +15,44 @@ namespace eagle {
public class ImproveCommandSelector : CommandSelector {
public HeroDropdownController heroDropdownController;
public TMP_Dropdown typeDropdown;
public Toggle lockToggle;
// Toggle buttons for each improvement type (assign to same ToggleGroup in Unity)
public Toggle economyToggle;
public Toggle agricultureToggle;
public Toggle infrastructureToggle;
public Toggle devastationToggle;
public ToggleGroup improvementToggleGroup;
// Labels showing type name and value
public TMP_Text economyLabel;
public TMP_Text agricultureLabel;
public TMP_Text infrastructureLabel;
public TMP_Text devastationLabel;
List<HeroView> orderedHeroes;
private int SelectedTypeIndex => typeDropdown.value;
private ImproveAvailableCommand ImproveAvailableCommand => _availableCommand.ImproveCommand;
private ProvinceId ActingProvinceId => ImproveAvailableCommand.ActingProvinceId;
private ImprovementType SelectedType =>
ImproveAvailableCommand.AvailableTypes[SelectedTypeIndex];
private ImprovementType SelectedType {
get {
if (economyToggle != null && economyToggle.isOn && economyToggle.interactable)
return ImprovementType.Economy;
if (agricultureToggle != null && agricultureToggle.isOn &&
agricultureToggle.interactable)
return ImprovementType.Agriculture;
if (infrastructureToggle != null && infrastructureToggle.isOn &&
infrastructureToggle.interactable)
return ImprovementType.Infrastructure;
if (devastationToggle != null && devastationToggle.isOn &&
devastationToggle.interactable)
return ImprovementType.Devastation;
// Fallback: return first available type
return ImproveAvailableCommand.AvailableTypes.FirstOrDefault();
}
}
private float OriginalImprovementValueForType(ImprovementType type) {
var province = _model.Provinces[ActingProvinceId];
@@ -57,60 +86,142 @@ namespace eagle {
}
}
private int MinimumImprovementIndex(ProvinceView province) {
var minIndex = 0;
float minValue =
OriginalImprovementValueForType(ImproveAvailableCommand.AvailableTypes[0]);
private ImprovementType GetMinimumImprovementType() {
ImprovementType minType = ImproveAvailableCommand.AvailableTypes[0];
float minValue = OriginalImprovementValueForType(minType);
for (int i = 1; i < ImproveAvailableCommand.AvailableTypes.Count; i++) {
float thisVal =
OriginalImprovementValueForType(ImproveAvailableCommand.AvailableTypes[i]);
var thisType = ImproveAvailableCommand.AvailableTypes[i];
float thisVal = OriginalImprovementValueForType(thisType);
if (thisVal < minValue) {
minIndex = i;
minType = thisType;
minValue = thisVal;
}
}
return minIndex;
return minType;
}
private void ChooseDefaultImprovement(ProvinceView province) {
var devastationIndex =
ImproveAvailableCommand.AvailableTypes.IndexOf(ImprovementType.Devastation);
if (devastationIndex == -1) {
typeDropdown.value = MinimumImprovementIndex(province);
private ImprovementType GetDefaultImprovementType() {
// Prefer devastation if available
if (ImproveAvailableCommand.AvailableTypes.Contains(ImprovementType.Devastation)) {
return ImprovementType.Devastation;
}
// Otherwise pick the lowest stat
return GetMinimumImprovementType();
}
private Toggle GetToggleForType(ImprovementType type) {
switch (type) {
case ImprovementType.Economy: return economyToggle;
case ImprovementType.Agriculture: return agricultureToggle;
case ImprovementType.Infrastructure: return infrastructureToggle;
case ImprovementType.Devastation: return devastationToggle;
default: return null;
}
}
private TMP_Text GetLabelForType(ImprovementType type) {
switch (type) {
case ImprovementType.Economy: return economyLabel;
case ImprovementType.Agriculture: return agricultureLabel;
case ImprovementType.Infrastructure: return infrastructureLabel;
case ImprovementType.Devastation: return devastationLabel;
default: return null;
}
}
private void SelectType(ImprovementType type) {
// Turn on the selected toggle - ToggleGroup handles turning off others
var toggle = GetToggleForType(type);
if (toggle != null && toggle.interactable) { toggle.isOn = true; }
}
private const float DisabledAlpha = 0.35f;
private void ConfigureToggle(ImprovementType type, bool available) {
var toggle = GetToggleForType(type);
var label = GetLabelForType(type);
if (toggle == null) return;
// Always show the toggle, but disable if not available
toggle.gameObject.SetActive(true);
toggle.interactable = available;
// Turn off unavailable toggles so they don't appear selected
if (!available) { toggle.isOn = false; }
// Only add to toggle group if available
toggle.group = available ? improvementToggleGroup : null;
// Gray out unavailable toggles using CanvasGroup
var canvasGroup = toggle.GetComponent<CanvasGroup>();
if (canvasGroup == null) {
canvasGroup = toggle.gameObject.AddComponent<CanvasGroup>();
}
canvasGroup.alpha = available ? 1f : DisabledAlpha;
// Always show label with current value
if (label != null) { label.text = LabelStringForType(type); }
}
private string LabelStringForType(ImprovementType type) {
var originalStat =
type == ImprovementType.Devastation
? ProvinceStatUtils.RoundedDevastation(
OriginalImprovementValueForType(type))
: ProvinceStatUtils.RoundedStat(OriginalImprovementValueForType(type));
if (type == ImprovementType.Devastation) {
return GUIUtils.ColoredString(Color.red, originalStat.ToString());
}
var devastatedStat =
ProvinceStatUtils.RoundedStat(EffectiveImprovementValueForType(type));
if (devastatedStat == originalStat) {
return $"{devastatedStat}";
} else {
typeDropdown.value = devastationIndex;
return $"{GUIUtils.ColoredString(Color.red, devastatedStat.ToString())} / {originalStat}";
}
}
protected override void SetUpUI() {
var province = _model.Provinces[ImproveAvailableCommand.ActingProvinceId];
var improveCommand = ImproveAvailableCommand;
typeDropdown.ClearOptions();
orderedHeroes = ImproveAvailableCommand.AvailableHeroIds.Select(id => _model.Heroes[id])
.ToList();
heroDropdownController.AvailableHeroes = orderedHeroes;
heroDropdownController.SelectedHeroId = improveCommand.RecommendedHeroId;
typeDropdown.AddOptions(
improveCommand.AvailableTypes.Select(DropdownStringForType).ToList());
// Configure each toggle based on available types
ConfigureToggle(
ImprovementType.Economy,
improveCommand.AvailableTypes.Contains(ImprovementType.Economy));
ConfigureToggle(
ImprovementType.Agriculture,
improveCommand.AvailableTypes.Contains(ImprovementType.Agriculture));
ConfigureToggle(
ImprovementType.Infrastructure,
improveCommand.AvailableTypes.Contains(ImprovementType.Infrastructure));
ConfigureToggle(
ImprovementType.Devastation,
improveCommand.AvailableTypes.Contains(ImprovementType.Devastation));
// Determine which type to select
ImprovementType selectedType;
if (improveCommand.LockedType != ImprovementType.None) {
var lockedType = improveCommand.LockedType;
var lockedTypeIndex = improveCommand.AvailableTypes.IndexOf(lockedType);
if (lockedTypeIndex > -1) {
typeDropdown.value = lockedTypeIndex;
if (improveCommand.AvailableTypes.Contains(lockedType)) {
selectedType = lockedType;
lockToggle.isOn = true;
} else {
ChooseDefaultImprovement(province);
selectedType = GetDefaultImprovementType();
lockToggle.isOn = false;
}
} else {
ChooseDefaultImprovement(province);
selectedType = GetDefaultImprovementType();
lockToggle.isOn = false;
}
SelectType(selectedType);
}
public override AvailableCommand.SealedValueOneofCase CommandType =>
@@ -137,23 +248,5 @@ namespace eagle {
LockType = lockToggle.isOn
}
};
private string DropdownStringForType(ImprovementType type) {
var originalStat =
type == ImprovementType.Devastation
? ProvinceStatUtils.RoundedDevastation(
OriginalImprovementValueForType(type))
: ProvinceStatUtils.RoundedStat(OriginalImprovementValueForType(type));
if (type == ImprovementType.Devastation) {
return $"{type} ({GUIUtils.ColoredString(UnityEngine.Color.red, originalStat.ToString())})";
}
var devastatedStat =
ProvinceStatUtils.RoundedStat(EffectiveImprovementValueForType(type));
if (devastatedStat == originalStat) {
return $"{type} ({devastatedStat})";
} else {
return $"{type} ({GUIUtils.ColoredString(UnityEngine.Color.red, devastatedStat.ToString())} / {originalStat})";
}
}
}
}
}
@@ -26,6 +26,10 @@ namespace eagle {
private TextMeshProUGUI _textComponent;
private PersistentClientConnection _connection;
private IGameStateProvider _gameStateProvider;
private string _environmentName;
[Tooltip("Optional text component to display connected environment (prod/qa)")]
public TextMeshProUGUI environmentIndicatorText;
[Tooltip("Optional button to force immediate reconnection when server is down")]
public Button retryButton;
@@ -64,6 +68,15 @@ namespace eagle {
_gameStateProvider = provider;
}
/// <summary>
/// Set the environment name to display (e.g., "prod." or "qa.").
/// Pass null to clear the indicator.
/// </summary>
public void SetEnvironment(string environmentName) {
_environmentName = environmentName;
UpdateEnvironmentIndicator();
}
void Update() {
if (_connection == null || _textComponent == null) { return; }
@@ -165,5 +178,20 @@ namespace eagle {
private void OnRetryClicked() {
if (_connection != null) { _connection.ForceReconnect(); }
}
private void UpdateEnvironmentIndicator() {
if (environmentIndicatorText == null) return;
if (string.IsNullOrEmpty(_environmentName)) {
environmentIndicatorText.text = "";
return;
}
// Color prod green, qa yellow
environmentIndicatorText.text =
_environmentName switch { "prod." => $"<color=green>{_environmentName}</color>",
"qa." => $"<color=yellow>{_environmentName}</color>",
_ => _environmentName };
}
}
}
@@ -1,9 +1,9 @@
fileFormatVersion: 2
guid: aa2fcd8d8f12d4218aa9ee793adfe434
guid: 1fb1f6deb68f9475281c9f7c427a7024
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 12
serializedVersion: 13
mipmaps:
mipMapMode: 0
enableMipMap: 1
@@ -20,11 +20,12 @@ TextureImporter:
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMasterTextureLimit: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
@@ -62,10 +63,11 @@ TextureImporter:
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 1
cookieLightType: 1
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 3
- serializedVersion: 4
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
@@ -75,9 +77,10 @@ TextureImporter:
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
- serializedVersion: 4
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
@@ -87,24 +90,14 @@ TextureImporter:
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Server
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
customData:
physicsShape: []
bones: []
spriteID:
@@ -114,10 +107,11 @@ TextureImporter:
edges: []
weights: []
secondaryTextures: []
spriteCustomMetadata:
entries: []
nameFileIdTable: {}
spritePackingTag:
mipmapLimitGroupName:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -243,7 +243,8 @@ namespace eagle {
public void SetUpGame(
long gameId,
int? playerId,
PersistentClientConnection persistentClientConnection) {
PersistentClientConnection persistentClientConnection,
string environmentName = null) {
ModelUpdater = new GameModelUpdater(
gameId,
playerId,
@@ -269,9 +270,12 @@ namespace eagle {
ModelUpdater.ErrorHandler = errorHandler;
// Set up game state provider for connection status UI
// Set up game state provider and environment for connection status UI
var statusUI = connectionStatusLabel.GetComponent<ConnectionStatusUI>();
if (statusUI != null) { statusUI.SetGameStateProvider(ModelUpdater); }
if (statusUI != null) {
statusUI.SetGameStateProvider(ModelUpdater);
statusUI.SetEnvironment(environmentName);
}
// Fire-and-forget - subscription is awaited internally and failures are logged
MainQueue.Q.EnqueueForNextUpdate(
@@ -311,20 +311,36 @@ namespace eagle {
// Store server-reported game status for UI
if (updateItem.ActionResultResponse.ServerGameStatus != null) {
ServerStatus = updateItem.ActionResultResponse.ServerGameStatus;
_connectionLogger.LogLine(
$"[UPDATE] ServerGameStatus updated: {ServerStatus.Status}");
}
// Note: _lastUnfilteredResultCount is updated on the gRPC thread in
// UpdateResultCounts() before enqueueing. We don't update it here to avoid
// race conditions where a backlogged MainQueue update overwrites a newer count.
if (updateItem.ActionResultResponse.ActionResultViews.Any() ||
updateItem.ActionResultResponse.AvailableCommands == null ||
updateItem.ActionResultResponse.AvailableCommands.Token !=
_currentModel.CommandToken) {
var hasResults = updateItem.ActionResultResponse.ActionResultViews.Any();
var hasCommands = updateItem.ActionResultResponse.AvailableCommands != null;
var incomingToken =
hasCommands ? updateItem.ActionResultResponse.AvailableCommands.Token
: -1;
var tokenMatches = hasCommands && incomingToken == _currentModel.CommandToken;
_connectionLogger.LogLine(
$"[UPDATE] hasResults={hasResults}, hasCommands={hasCommands}, " +
$"incomingToken={incomingToken}, currentToken={_currentModel.CommandTokenString}, " +
$"tokenMatches={tokenMatches}");
if (hasResults || !hasCommands || !tokenMatches) {
HandleUpdates(updateItem.ActionResultResponse.ActionResultViews.ToList());
HandleAvailableCommands(updateItem.ActionResultResponse.AvailableCommands);
if (UpdateAction != null) UpdateAction.Invoke(_currentModel);
_connectionLogger.LogLine(
"[UPDATE] Processed update and invoked UpdateAction");
} else {
_connectionLogger.LogLine(
"[UPDATE] SKIPPED - no results, has commands, token matches");
}
break;
@@ -332,6 +348,10 @@ namespace eagle {
case GameUpdate.GameUpdateDetailsOneofCase.ShardokActionResultResponse:
var specResponse = updateItem.ShardokActionResultResponse.ShardokGameResponses;
// Collect ended games to remove AFTER the UI callback, so the UI
// can see the final battle results before the models are removed.
var endedGames = new List<ShardokGameId>();
foreach (var oneResponse in specResponse) {
if (!_currentModel.ShardokGameModels.TryGetValue(
oneResponse.ShardokGameId,
@@ -372,14 +392,22 @@ namespace eagle {
_currentModel.ShardokGameModels[oneResponse.ShardokGameId] =
shardokGameModel;
} else {
// Game ended - remove from active models so UI knows battle is over
_currentModel.ShardokGameModels.TryRemove(
oneResponse.ShardokGameId,
out _);
_shardokResultCounts.TryRemove(oneResponse.ShardokGameId, out _);
// Game ended - keep model for UI callback, mark for removal after
_currentModel.ShardokGameModels[oneResponse.ShardokGameId] =
shardokGameModel;
endedGames.Add(oneResponse.ShardokGameId);
}
}
// Invoke UI callback BEFORE removing ended games, so the UI can
// see the final battle results (with GameStatus = Victory/Defeat)
if (UpdateAction != null) UpdateAction.Invoke(_currentModel);
// Now remove ended games from active models
foreach (var endedGameId in endedGames) {
_currentModel.ShardokGameModels.TryRemove(endedGameId, out _);
_shardokResultCounts.TryRemove(endedGameId, out _);
}
break;
case GameUpdate.GameUpdateDetailsOneofCase.StreamingTextResponse:
@@ -405,9 +433,14 @@ namespace eagle {
public void UpdateResultCounts(GameUpdate update) {
switch (update.GameUpdateDetailsCase) {
case GameUpdate.GameUpdateDetailsOneofCase.ActionResultResponse:
var newCount = update.ActionResultResponse.UnfilteredResultCountAfter;
lock (_resultCountLock) {
_lastUnfilteredResultCount =
update.ActionResultResponse.UnfilteredResultCountAfter;
var oldCount = _lastUnfilteredResultCount;
_lastUnfilteredResultCount = newCount;
if (newCount != oldCount) {
_connectionLogger.LogLine(
$"[RESULT_COUNT] Updated count {oldCount} -> {newCount}");
}
}
break;
@@ -481,13 +514,22 @@ namespace eagle {
_connectionLogger.LogLine(
$"[STATE_RESYNC] timestamp={timestamp} round={startingState.CurrentRoundId} factions={startingState.Factions.Count} heroes={startingState.Heroes.Count}");
// Clear all stale state before applying new starting state.
// This handles rewind/reset scenarios where the server sends an earlier state.
_currentModel.ShardokGameModels.Clear();
_shardokResultCounts.Clear();
_shardokNeedsResync.Clear();
_currentModel.CommandToken = null;
_currentModel.LastPostedToken = -1;
_currentModel.AvailableCommandsByProvince.Clear();
_commandSubmittedTime = null;
_currentModel.GsView = startingState;
_currentModel.BattalionTypes =
startingState.BattalionTypes.ToDictionary(bt => bt.TypeId, bt => bt);
_currentModel.ChronicleEntries = startingState.ChronicleEntries.ToList();
// For any outstanding battles not in ShardokGameModels, create models and mark for
// resync. This ensures fresh clients get Shardok state for ongoing battles.
// For any outstanding battles in the new state, create models and mark for resync.
bool needsResubscribe = false;
foreach (var battle in _currentModel.ShardokBattles) {
if (!_currentModel.ShardokGameModels.ContainsKey(battle.ShardokGameId)) {
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: e9afdd2068b294a29993f07b379eb9c3
@@ -36,10 +36,10 @@ namespace eagle.Notifications.ARNNotifications {
$"{DisplayNames.ResolvedFactionString(lastFaction, currentModel)}'s hero {{HeroName}}";
}
textTemplate = $"{executingFactionName} has executed {victimDescription}!";
textTemplate = $"{executingFactionName} has executed {victimDescription}!\n\n";
heroPlaceholders["HeroName"] = (hero.NameTextId, "the hero");
} else {
textTemplate = $"{executingFactionName} has executed {{ExecutedHero}}!";
textTemplate = $"{executingFactionName} has executed {{ExecutedHero}}!\n\n";
heroPlaceholders["ExecutedHero"] = (hero.NameTextId, "the prisoner");
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e661753a1e43a4f2da81b76457cf55c8
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,9 +1,9 @@
fileFormatVersion: 2
guid: a98ea09ca5b31411688f7dd794365af8
guid: 8d524cd6fa08d47c99b2462c2686b8d0
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 10
serializedVersion: 13
mipmaps:
mipMapMode: 0
enableMipMap: 1
@@ -20,9 +20,12 @@ TextureImporter:
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
@@ -31,13 +34,13 @@ TextureImporter:
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -100
wrapU: -1
wrapV: -1
wrapW: -1
nPOTScale: 2
filterMode: 1
aniso: 1
mipBias: 0
wrapU: 0
wrapV: 0
wrapW: 0
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0
@@ -54,11 +57,17 @@ TextureImporter:
textureType: 0
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 2
- serializedVersion: 4
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
@@ -68,8 +77,10 @@ TextureImporter:
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
@@ -79,33 +90,14 @@ TextureImporter:
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: iPhone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: Android
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
customData:
physicsShape: []
bones: []
spriteID:
@@ -115,9 +107,11 @@ TextureImporter:
edges: []
weights: []
secondaryTextures: []
spritePackingTag:
spriteCustomMetadata:
entries: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -1,9 +1,9 @@
fileFormatVersion: 2
guid: c38f017a9228a44819a59ece3ccb2009
guid: 1e69ea88b87d34a48bbb45a1fbad81fc
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 10
serializedVersion: 13
mipmaps:
mipMapMode: 0
enableMipMap: 1
@@ -20,9 +20,12 @@ TextureImporter:
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
@@ -31,12 +34,12 @@ TextureImporter:
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -100
wrapU: -1
wrapV: -1
wrapW: -1
filterMode: 1
aniso: 1
mipBias: 0
wrapU: 0
wrapV: 0
wrapW: 0
nPOTScale: 1
lightmap: 0
compressionQuality: 50
@@ -49,16 +52,22 @@ TextureImporter:
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 2
- serializedVersion: 4
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
@@ -68,8 +77,10 @@ TextureImporter:
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
@@ -79,33 +90,14 @@ TextureImporter:
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: iPhone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: Android
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
customData:
physicsShape: []
bones: []
spriteID:
@@ -115,9 +107,11 @@ TextureImporter:
edges: []
weights: []
secondaryTextures: []
spritePackingTag:
spriteCustomMetadata:
entries: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -1,9 +1,9 @@
fileFormatVersion: 2
guid: c3d3ab677e7a149d29c24ca2f6f32663
guid: 1850a7332b6e84e1a9b69f5f5b4cf482
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 10
serializedVersion: 13
mipmaps:
mipMapMode: 0
enableMipMap: 1
@@ -20,9 +20,12 @@ TextureImporter:
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
@@ -31,12 +34,12 @@ TextureImporter:
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -100
wrapU: -1
wrapV: -1
wrapW: -1
filterMode: 1
aniso: 1
mipBias: 0
wrapU: 0
wrapV: 0
wrapW: 0
nPOTScale: 1
lightmap: 0
compressionQuality: 50
@@ -49,16 +52,22 @@ TextureImporter:
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 3
- serializedVersion: 4
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
@@ -68,9 +77,10 @@ TextureImporter:
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
- serializedVersion: 4
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
@@ -80,36 +90,14 @@ TextureImporter:
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: iPhone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Android
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
customData:
physicsShape: []
bones: []
spriteID:
@@ -119,9 +107,11 @@ TextureImporter:
edges: []
weights: []
secondaryTextures: []
spritePackingTag:
spriteCustomMetadata:
entries: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -44,6 +44,18 @@ namespace eagle {
private readonly Logger _remoteEagleClientLogger = Logger.GetLogger("ConnectionLogger");
private readonly Logger _timingsLogger = Logger.GetLogger("ConnectionLogger");
// Counter to diagnose duplicate logging - if logs show same seq# twice, two threads
// are processing same message. If seq# increments but lines doubled, Logger issue.
private int _logFlowSeq = 0;
/// <summary>Timestamped log for connection flow tracing.</summary>
private void LogFlow(string message) {
var seq = Interlocked.Increment(ref _logFlowSeq);
var ts = DateTime.UtcNow.ToString("HH:mm:ss.fff");
_remoteEagleClientLogger.LogLine($"[FLOW {ts}] #{seq} {message}");
}
private volatile bool _isConnecting = false;
private Timer _idleCheckTimer = null;
private Timer _heartbeatTimer = null;
@@ -77,7 +89,23 @@ namespace eagle {
_retryTimer?.Dispose();
NextReconnectAttempt = null;
LogConnectionEvent("force_reconnect", "User requested immediate reconnect");
Task.Run(() => Connect());
RunConnectAsync();
}
/// <summary>
/// Fire-and-forget wrapper for Connect() that ensures exceptions are logged
/// rather than silently swallowed by Task.Run().
/// </summary>
private void RunConnectAsync() {
Task.Run(async () => {
try {
await Connect();
} catch (Exception e) {
// Log but don't rethrow - this is fire-and-forget
Console.WriteLine($"[CONNECT] Exception in Connect: {e}");
_remoteEagleClientLogger.LogLine($"Exception in Connect: {e}");
}
});
}
private DateTime? GetDeadlineFromNow() {
@@ -122,6 +150,7 @@ namespace eagle {
_currentState = ConnectionState.Reconnecting;
NextReconnectAttempt = DateTime.UtcNow.AddSeconds(backoffSeconds);
LogFlow($"SCHEDULE_RECONNECT reason={reason} backoff={backoffSeconds:F1}s attempt={_consecutiveFailures}");
LogConnectionEvent(
"schedule_reconnect",
$"{reason}, backoff={backoffSeconds:F1}s, attempt={_consecutiveFailures}");
@@ -130,7 +159,7 @@ namespace eagle {
_retryTimer = new Timer();
_retryTimer.AutoReset = false;
_retryTimer.Interval = backoffSeconds * 1000;
_retryTimer.Elapsed += (sender, args) => Task.Run(() => Connect());
_retryTimer.Elapsed += (sender, args) => RunConnectAsync();
_retryTimer.Enabled = true;
}
@@ -149,6 +178,7 @@ namespace eagle {
private readonly Dictionary<EagleGameId, TaskCompletionSource<SubscriptionAck>>
_pendingSubscriptionAcks = new();
private const int SubscriptionAckTimeoutMs = 10000; // 10 seconds
private const int WriteAsyncTimeoutMs = 10000; // 10 seconds for WriteAsync operations
public PersistentClientConnection(
Eagle.EagleClient grpcClient,
@@ -194,6 +224,8 @@ namespace eagle {
var ackTcs = new TaskCompletionSource<SubscriptionAck>();
lock (_pendingSubscriptionAcks) { _pendingSubscriptionAcks[gameId] = ackTcs; }
var shardokCount = shardokStatuses.Count();
LogFlow($"SUBSCRIBE game={gameId} unfilteredCount={subscriber.LastUnfilteredResultCount} shardokGames={shardokCount}");
_remoteEagleClientLogger.LogLine(
$"[SUBSCRIBE] Sending StreamGameRequest for game {gameId}, " +
$"unfilteredCount={subscriber.LastUnfilteredResultCount}");
@@ -233,6 +265,7 @@ namespace eagle {
var ack = await ackTask;
if (ack.Success) {
LogFlow($"SUBSCRIBE_ACK game={gameId} success=true confirmedCount={ack.ConfirmedResultCount}");
_remoteEagleClientLogger.LogLine(
$"[SUBSCRIBE] Subscription confirmed for game {gameId}, " +
$"confirmedResultCount={ack.ConfirmedResultCount}");
@@ -244,6 +277,7 @@ namespace eagle {
return true;
} else {
LogFlow($"SUBSCRIBE_ACK game={gameId} success=false error={ack.ErrorMessage}");
LogConnectionEvent(
"subscribe_ack_failed",
$"game={gameId}, error={ack.ErrorMessage}");
@@ -268,23 +302,24 @@ namespace eagle {
public async Task Connect() {
// Prevent concurrent connection attempts
if (_isConnecting) {
_remoteEagleClientLogger.LogLine($"Connect() skipped - already connecting");
LogFlow($"Connect() SKIPPED already_connecting=true");
return;
}
// Check circuit breaker
if (!_circuitBreaker.ShouldAttemptConnection()) {
_remoteEagleClientLogger.LogLine(
$"[CIRCUIT] Connection attempt blocked - circuit {_circuitBreaker.CurrentState}");
LogFlow($"Connect() BLOCKED circuit={_circuitBreaker.CurrentState}");
LogConnectionEvent("connect_blocked", $"circuit={_circuitBreaker.CurrentState}");
return;
}
_isConnecting = true;
try {
LogFlow($"Connect() START failures={_consecutiveFailures}");
_lastConnectAttempt = DateTime.UtcNow;
_currentState = _consecutiveFailures > 0 ? ConnectionState.Reconnecting
: ConnectionState.Connecting;
LogFlow($"State -> {_currentState}");
NextReconnectAttempt = null;
LogConnectionEvent("connect_attempt");
@@ -318,8 +353,10 @@ namespace eagle {
// Stream subscriptions OUTSIDE lock (can await)
// Set state to SubscriptionPending while waiting for acks
LogFlow($"Streaming {subscribersToStream.Count} subscriptions");
if (subscribersToStream.Any()) {
_currentState = ConnectionState.SubscriptionPending;
LogFlow($"State -> {_currentState}");
}
bool allSucceeded = true;
@@ -330,6 +367,7 @@ namespace eagle {
if (!allSucceeded) {
// Subscription failed - this is critical because the game won't receive
// updates. Trigger reconnect rather than proceeding to Connected state.
LogFlow("SUBSCRIBE_FAILED triggering reconnect");
LogConnectionEvent(
"subscribe_failed",
"Subscription failed - triggering reconnect");
@@ -353,6 +391,7 @@ namespace eagle {
_lastSuccessfulConnect = DateTime.UtcNow;
_consecutiveFailures = 0; // Reset backoff on successful connection
_currentState = ConnectionState.Connected;
LogFlow($"State -> {_currentState}");
_circuitBreaker.RecordSuccess();
LogConnectionEvent("connect_success");
@@ -387,6 +426,18 @@ namespace eagle {
_pendingCommands.Add(pendingCommands.Dequeue());
}
}
// Clean up resources before reconnecting
lock (this) {
_streamingCall?.Dispose();
_streamingCall = null;
_threadCancellationTokenSource?.Cancel();
}
MarkAllShardokGamesForResync();
CancelAllPendingSubscriptionAcks();
// Schedule reconnect - without this, the connection dies silently
ScheduleReconnect($"ConnectFailed-{e.GetType().Name}");
}
} finally { _isConnecting = false; }
}
@@ -424,26 +475,35 @@ namespace eagle {
lock (this) { _pendingCommands.Add(nextCommand); }
}
} else {
// CurrentEagleToken is null - server hasn't sent us
// commands yet, or we skipped them. Retry the pending
// command anyway; if the server already processed it, it
// will be ignored as duplicate.
_remoteEagleClientLogger.LogLine(
"No matching command for token " + providedToken);
$"No current token, retrying pending command with token {providedToken}");
await PostRequest(nextCommand);
}
break;
case UniversalCommand.SealedValueOneofCase.ShardokCommand: {
Int64 providedShardokToken =
nextCommand.Command.ShardokCommand.ShardokToken;
if (subscriber.CurrentShardokToken(
nextCommand.Command.ShardokCommand.GameId)
is Int64 shardokToken &&
var currentShardokToken = subscriber.CurrentShardokToken(
nextCommand.Command.ShardokCommand.GameId);
if (currentShardokToken is Int64 shardokToken &&
shardokToken == providedShardokToken) {
_remoteEagleClientLogger.LogLine(
"Found a matching pending command with token " +
shardokToken);
await PostRequest(nextCommand);
} else if (currentShardokToken == null) {
// No current token - retry anyway
_remoteEagleClientLogger.LogLine(
$"No current Shardok token, retrying pending command with token {providedShardokToken}");
await PostRequest(nextCommand);
} else {
_remoteEagleClientLogger.LogLine(
"No matching command for token " +
providedShardokToken);
$"Shardok token mismatch: pending={providedShardokToken} current={currentShardokToken}, dropping");
}
break;
@@ -453,25 +513,27 @@ namespace eagle {
Int64 providedShardokToken =
nextCommand.Command.ShardokPlacementCommands
.ShardokToken;
if (subscriber.CurrentShardokToken(
nextCommand.Command.ShardokCommand.GameId)
is Int64 shardokToken &&
var currentShardokToken = subscriber.CurrentShardokToken(
nextCommand.Command.ShardokPlacementCommands.GameId);
if (currentShardokToken is Int64 shardokToken &&
shardokToken == providedShardokToken) {
_remoteEagleClientLogger.LogLine(
"Found a matching pending command with token " +
"Found a matching pending placement command with token " +
shardokToken);
await PostRequest(nextCommand);
} else if (currentShardokToken == null) {
// No current token - retry anyway
_remoteEagleClientLogger.LogLine(
$"No current Shardok token, retrying pending placement command with token {providedShardokToken}");
await PostRequest(nextCommand);
} else {
_remoteEagleClientLogger.LogLine(
"No matching command for token " +
providedShardokToken);
$"Shardok placement token mismatch: pending={providedShardokToken} current={currentShardokToken}, dropping");
}
break;
}
}
await PostRequest(nextCommand);
}
}
@@ -503,6 +565,9 @@ namespace eagle {
}
public void Dispose() {
Thread threadToJoin = null;
CancellationTokenSource tokenSourceToDispose = null;
lock (this) {
// Dispose timers first to stop any pending callbacks
StopIdleCheckTimer();
@@ -525,20 +590,25 @@ namespace eagle {
// Clear pending commands
_pendingCommands.Clear();
// Cancel and dispose thread cancellation token
// Cancel thread cancellation token (but don't dispose yet)
_threadCancellationTokenSource?.Cancel();
// Give thread a chance to exit gracefully
if (_streamingCallThread != null) {
if (!_streamingCallThread.Join(TimeSpan.FromSeconds(2))) {
Console.WriteLine("Warning: Streaming call thread did not exit gracefully");
}
_streamingCallThread = null;
}
_threadCancellationTokenSource?.Dispose();
// Capture thread and token source references for cleanup outside lock
threadToJoin = _streamingCallThread;
_streamingCallThread = null;
tokenSourceToDispose = _threadCancellationTokenSource;
_threadCancellationTokenSource = null;
}
// Join thread OUTSIDE lock to avoid deadlock - the streaming thread
// may be trying to acquire lock(this) when we're waiting for it
if (threadToJoin != null) {
if (!threadToJoin.Join(TimeSpan.FromSeconds(2))) {
Console.WriteLine("Warning: Streaming call thread did not exit gracefully");
}
}
tokenSourceToDispose?.Dispose();
}
public void SetLobbySubscriber(ILobbySubscriber subscriber) {
@@ -582,13 +652,25 @@ namespace eagle {
try {
lock (this) { _pendingCommands.Add(request); }
await DoWithStreamingCall(async (streamingCall) => {
var success = await DoWithStreamingCall(async (streamingCall) => {
await streamingCall.RequestStream.WriteAsync(
new UpdateStreamRequest { PostCommandRequest = request });
return true;
});
lock (this) { _pendingCommands.Remove(request); }
} catch (Exception e) { Console.WriteLine("Failed to post command: " + e); }
// Only remove from pending if successfully sent.
// If connection was dead, leave in queue for retry after reconnect.
if (success) {
lock (this) { _pendingCommands.Remove(request); }
} else {
_remoteEagleClientLogger.LogLine(
$"[POST] Command not sent (connection dead), keeping in pending queue for retry");
}
} catch (Exception e) {
Console.WriteLine("Failed to post command: " + e);
_remoteEagleClientLogger.LogLine($"[POST] Exception posting command: {e.Message}");
// Leave in _pendingCommands for retry after reconnect
}
}
private async Task
@@ -665,9 +747,38 @@ namespace eagle {
private delegate Task<bool> WithStreamingCallDelegate(
AsyncDuplexStreamingCall<UpdateStreamRequest, UpdateStreamResponse> call);
/// <summary>
/// Execute an action with the streaming call, with a timeout to prevent indefinite
/// blocking. If the action takes longer than WriteAsyncTimeoutMs, we consider the
/// connection dead and return false. This prevents thread pool exhaustion on dead
/// connections.
/// </summary>
private async Task<bool> DoWithStreamingCall(WithStreamingCallDelegate action) {
var sc = _streamingCall;
if (sc == null) return false;
try {
return await action(_streamingCall);
using var timeoutCts = new CancellationTokenSource(WriteAsyncTimeoutMs);
var actionTask = action(sc);
var timeoutTask = Task.Delay(WriteAsyncTimeoutMs, timeoutCts.Token);
var completedTask =
await Task.WhenAny(actionTask, timeoutTask).ConfigureAwait(false);
if (completedTask == timeoutTask) {
// WriteAsync timed out - connection is likely dead
LogConnectionEvent(
"write_timeout",
$"WriteAsync timed out after {WriteAsyncTimeoutMs}ms");
_remoteEagleClientLogger.LogLine(
$"[WRITE_TIMEOUT] WriteAsync timed out after {WriteAsyncTimeoutMs}ms, connection may be dead");
return false;
}
// Cancel the timeout task since action completed
timeoutCts.Cancel();
return await actionTask.ConfigureAwait(false);
} catch (RpcException e) {
if (e.StatusCode == StatusCode.Cancelled) {
// This is expected when the connection is closed.
@@ -675,9 +786,15 @@ namespace eagle {
} else {
throw;
}
} catch (OperationCanceledException) {
// Timeout was triggered
return false;
}
}
/// <summary>
/// Send a request on the streaming call with a timeout to prevent indefinite blocking.
/// </summary>
public async Task<bool> SendUpdateStreamRequestAsync(UpdateStreamRequest request) {
AsyncDuplexStreamingCall<UpdateStreamRequest, UpdateStreamResponse> sc = null;
lock (this) {
@@ -686,7 +803,30 @@ namespace eagle {
}
try {
await sc.RequestStream.WriteAsync(request, _cancellationToken);
using var timeoutCts = new CancellationTokenSource(WriteAsyncTimeoutMs);
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
_cancellationToken,
timeoutCts.Token);
var writeTask = sc.RequestStream.WriteAsync(request, linkedCts.Token);
var timeoutTask = Task.Delay(WriteAsyncTimeoutMs, timeoutCts.Token);
var completedTask =
await Task.WhenAny(writeTask, timeoutTask).ConfigureAwait(false);
if (completedTask == timeoutTask) {
// WriteAsync timed out - connection is likely dead
LogConnectionEvent(
"write_timeout",
$"SendUpdateStreamRequestAsync timed out after {WriteAsyncTimeoutMs}ms");
_remoteEagleClientLogger.LogLine(
$"[WRITE_TIMEOUT] SendUpdateStreamRequestAsync timed out after {WriteAsyncTimeoutMs}ms");
return false;
}
// Cancel the timeout task since write completed
timeoutCts.Cancel();
await writeTask.ConfigureAwait(false); // Observe any exception
return true;
} catch (RpcException e) {
if (e.StatusCode == StatusCode.Cancelled) {
@@ -695,6 +835,9 @@ namespace eagle {
} else {
throw;
}
} catch (OperationCanceledException) {
// Timeout was triggered
return false;
}
}
@@ -706,6 +849,7 @@ namespace eagle {
private void HandleGameUpdate(GameUpdate gameUpdate, DateTime receivedTime) {
switch (gameUpdate.GameUpdateDetailsCase) {
case GameUpdate.GameUpdateDetailsOneofCase.ErrorResponse:
LogFlow($"UPDATE ErrorResponse game={gameUpdate.GameId}");
_remoteEagleClientLogger.LogLine("Got an error response!");
MainQueue.Q.Enqueue(() => {
lock (this) { _subscribers.Remove(gameUpdate.GameId); }
@@ -728,16 +872,63 @@ namespace eagle {
break;
case GameUpdate.GameUpdateDetailsOneofCase.ActionResultResponse:
case GameUpdate.GameUpdateDetailsOneofCase.ShardokActionResultResponse:
var arResp = gameUpdate.ActionResultResponse;
var arCount = arResp.ActionResultViews?.Count ?? 0;
var hasStartingState = gameUpdate.StartingState != null;
var hasCommands = arResp.AvailableCommands != null;
var cmdToken = hasCommands ? arResp.AvailableCommands.Token : -1;
var cmdCount = hasCommands
? arResp.AvailableCommands.CommandsByProvince?.Count ?? 0
: 0;
var status = arResp.ServerGameStatus?.Status.ToString() ?? "null";
LogFlow($"UPDATE ActionResult game={gameUpdate.GameId} countAfter={arResp.UnfilteredResultCountAfter} " +
$"actionResults={arCount} startingState={hasStartingState} hasCommands={hasCommands} " +
$"token={cmdToken} cmdProvinces={cmdCount} status={status}");
// Update result counts IMMEDIATELY on the gRPC thread, before enqueueing.
// This ensures reconnects use accurate counts even when MainQueue is blocked
// (e.g., when Unity is backgrounded).
lock (this) {
if (_subscribers.TryGetValue(gameUpdate.GameId, out var sub)) {
sub.UpdateResultCounts(gameUpdate);
}
}
MainQueue.Q.Enqueue(async () => {
IClientConnectionSubscriber subscriber;
lock (this) {
if (_subscribers.TryGetValue(gameUpdate.GameId, out subscriber)) {
subscriber.ReceiveGameUpdate(gameUpdate);
} else {
_subscribers.Remove(gameUpdate.GameId);
}
}
await TryPendingCommands();
var processTime = (DateTime.UtcNow - receivedTime).TotalMilliseconds;
if (processTime > 100.0) {
_timingsLogger.LogLine($"PROCESS {processTime} ms");
}
});
break;
case GameUpdate.GameUpdateDetailsOneofCase.ShardokActionResultResponse:
var shardokResp = gameUpdate.ShardokActionResultResponse;
var shardokGameCount = shardokResp.ShardokGameResponses?.Count ?? 0;
// Log each Shardok game's sequence to detect missing results
foreach (var sgr in shardokResp.ShardokGameResponses) {
var resultCount = sgr.ActionResultViews?.Count ?? 0;
LogFlow($"UPDATE ShardokResult game={gameUpdate.GameId} " +
$"shardok={sgr.ShardokGameId} countAfter={sgr.NewResultViewCount} " +
$"results={resultCount}");
}
// Update result counts IMMEDIATELY on the gRPC thread, before enqueueing.
lock (this) {
if (_subscribers.TryGetValue(gameUpdate.GameId, out var sub2)) {
sub2.UpdateResultCounts(gameUpdate);
}
}
MainQueue.Q.Enqueue(async () => {
IClientConnectionSubscriber subscriber;
lock (this) {
@@ -760,6 +951,7 @@ namespace eagle {
}
private async void HandleStreamingCall() {
LogFlow("HandleStreamingCall STARTED");
try {
AsyncDuplexStreamingCall<UpdateStreamRequest, UpdateStreamResponse> sc;
CancellationToken threadToken;
@@ -789,54 +981,69 @@ namespace eagle {
HandleGameUpdate(current.GameUpdate, receivedTime);
break;
case UpdateStreamResponse.ResponseDetailsOneofCase.LobbyResponse:
if (_lobbySubscriber != null) {
case UpdateStreamResponse.ResponseDetailsOneofCase.LobbyResponse: {
// Capture subscriber reference to avoid race condition - if
// subscriber changes or is cleared during dispose, we deliver to
// whoever was subscribed when the message arrived
var lobbySubscriber = _lobbySubscriber;
if (lobbySubscriber != null) {
MainQueue.Q.Enqueue(() => {
_lobbySubscriber.ReceiveLobbyUpdate(current.LobbyResponse);
lobbySubscriber.ReceiveLobbyUpdate(current.LobbyResponse);
});
}
break;
}
case UpdateStreamResponse.ResponseDetailsOneofCase
.PregeneratedTextResponse:
if (_lobbySubscriber != null) {
.PregeneratedTextResponse: {
var lobbySubscriber = _lobbySubscriber;
if (lobbySubscriber != null) {
MainQueue.Q.Enqueue(() => {
_lobbySubscriber.ReceivePregeneratedTextUpdate(
lobbySubscriber.ReceivePregeneratedTextUpdate(
current.PregeneratedTextResponse);
});
}
break;
}
case UpdateStreamResponse.ResponseDetailsOneofCase.JoinGameResponse:
if (_lobbySubscriber != null) {
case UpdateStreamResponse.ResponseDetailsOneofCase.JoinGameResponse: {
var lobbySubscriber = _lobbySubscriber;
if (lobbySubscriber != null) {
MainQueue.Q.Enqueue(() => {
_lobbySubscriber.HandleJoinGameResponse(
lobbySubscriber.HandleJoinGameResponse(
current.JoinGameResponse);
});
}
break;
}
case UpdateStreamResponse.ResponseDetailsOneofCase.CreateGameResponse:
if (_lobbySubscriber != null) {
case UpdateStreamResponse.ResponseDetailsOneofCase.CreateGameResponse: {
var lobbySubscriber = _lobbySubscriber;
if (lobbySubscriber != null) {
MainQueue.Q.Enqueue(() => {
_lobbySubscriber.HandleCreateGameResponse(
lobbySubscriber.HandleCreateGameResponse(
current.CreateGameResponse);
});
}
break;
case UpdateStreamResponse.ResponseDetailsOneofCase.CustomBattleResponse:
if (_lobbySubscriber != null) {
}
case UpdateStreamResponse.ResponseDetailsOneofCase
.CustomBattleResponse: {
var lobbySubscriber = _lobbySubscriber;
if (lobbySubscriber != null) {
MainQueue.Q.Enqueue(() => {
_lobbySubscriber.HandleCustomBattleResponse(
lobbySubscriber.HandleCustomBattleResponse(
current.CustomBattleResponse);
});
}
break;
}
case UpdateStreamResponse.ResponseDetailsOneofCase.HexMapResponse:
var hexMapResponse = current.HexMapResponse;
@@ -875,8 +1082,26 @@ namespace eagle {
waitStartTime = DateTime.UtcNow;
}
// While loop exited normally (not via exception)
var scNull = sc == null;
var tokenCancelled = _currentThreadToken.IsCancellationRequested;
LogFlow($"HandleStreamingCall ENDED normally: sc_null={scNull} token_cancelled={tokenCancelled}");
_remoteEagleClientLogger.LogLine(
"How did we get here? This is not my beautiful wife!");
$"Stream ended normally: sc_null={scNull} token_cancelled={tokenCancelled}");
// Only schedule reconnect if:
// 1. App is not shutting down (main token not cancelled)
// 2. Thread token was NOT cancelled (if it was, something else like
// SyncMismatch already disposed the call and scheduled reconnect)
if (!_cancellationToken.IsCancellationRequested && !tokenCancelled) {
lock (this) {
_lastDisconnect = DateTime.UtcNow;
MarkAllShardokGamesForResync();
CancelAllPendingSubscriptionAcks();
}
LogConnectionEvent("disconnect", "StreamEndedNormally");
ScheduleReconnect("StreamEndedNormally");
}
} catch (RpcException e) {
lock (this) {
_lastDisconnect = DateTime.UtcNow;
@@ -941,6 +1166,19 @@ namespace eagle {
CancelAllPendingSubscriptionAcks();
ScheduleReconnect("ObjectDisposed");
} catch (Exception e) {
// Catch-all for any unexpected exceptions. Without this, exceptions in an
// async void method can crash the process or be silently lost, leaving the
// connection dead with no recovery.
_lastDisconnect = DateTime.UtcNow;
LogConnectionEvent("disconnect", $"UnexpectedException: {e.GetType().Name}");
_remoteEagleClientLogger.LogLine(
$"UNEXPECTED exception in HandleStreamingCall: {e}");
MarkAllShardokGamesForResync();
CancelAllPendingSubscriptionAcks();
ScheduleReconnect($"UnexpectedException-{e.GetType().Name}");
}
return;
@@ -974,7 +1212,17 @@ namespace eagle {
AutoReset = true,
Interval = 5000 // Check every 5 seconds
};
_idleCheckTimer.Elapsed += (sender, args) => CheckForIdleTimeout();
_idleCheckTimer.Elapsed += (sender, args) => {
try {
// Log BEFORE callback to confirm timer is firing
Console.WriteLine($"[IDLE_TIMER] Elapsed at {DateTime.UtcNow:HH:mm:ss.fff}");
CheckForIdleTimeout();
} catch (Exception e) {
// Timer callbacks must not throw - it can stop the timer from firing again
Console.WriteLine($"[IDLE_TIMER] Exception in callback: {e}");
_remoteEagleClientLogger.LogLine($"Exception in idle check timer: {e}");
}
};
_idleCheckTimer.Enabled = true;
}
@@ -987,10 +1235,16 @@ namespace eagle {
}
private void CheckForIdleTimeout() {
if (_cancellationToken.IsCancellationRequested) { return; }
var idleTime = (DateTime.UtcNow - _lastResponseReceived).TotalSeconds;
// Log every check when idle > 5s to diagnose timer issues
if (idleTime > 5.0) {
_remoteEagleClientLogger.LogLine(
$"[IDLE_CHECK] idle_time={idleTime:F1}s, cancelled={_cancellationToken.IsCancellationRequested}");
}
if (_cancellationToken.IsCancellationRequested) { return; }
// Early warnings at 10s and 20s to help diagnose slow connections
if (idleTime > 20.0 && _lastIdleWarningLevel < 2) {
_lastIdleWarningLevel = 2;
@@ -1013,7 +1267,7 @@ namespace eagle {
if (toCancel != null) {
toCancel.Dispose();
lock (this) { _streamingCall = null; }
Task.Run(() => Connect());
RunConnectAsync();
}
}
}
@@ -1022,7 +1276,26 @@ namespace eagle {
StopHeartbeatTimer();
_heartbeatTimer =
new Timer { AutoReset = true, Interval = HeartbeatIntervalSeconds * 1000 };
_heartbeatTimer.Elapsed += (sender, args) => Task.Run(() => SendHeartbeat());
_heartbeatTimer.Elapsed += (sender, args) => {
try {
// Log BEFORE Task.Run to confirm timer is firing
Console.WriteLine(
$"[HEARTBEAT_TIMER] Elapsed at {DateTime.UtcNow:HH:mm:ss.fff}");
Task.Run(async () => {
try {
await SendHeartbeat();
} catch (Exception e) {
// Log but don't rethrow - exceptions in Task.Run are silently lost
Console.WriteLine($"[HEARTBEAT] Exception in SendHeartbeat: {e}");
_remoteEagleClientLogger.LogLine($"Exception in SendHeartbeat: {e}");
}
});
} catch (Exception e) {
// Timer callbacks must not throw
Console.WriteLine($"[HEARTBEAT_TIMER] Exception in callback: {e}");
_remoteEagleClientLogger.LogLine($"Exception in heartbeat timer: {e}");
}
};
_heartbeatTimer.Enabled = true;
}
@@ -1035,8 +1308,16 @@ namespace eagle {
}
private async Task SendHeartbeat() {
if (_cancellationToken.IsCancellationRequested) { return; }
if (_currentState != ConnectionState.Connected) { return; }
LogFlow($"HEARTBEAT_START state={_currentState}");
if (_cancellationToken.IsCancellationRequested) {
LogFlow("HEARTBEAT_SKIP reason=cancellation_requested");
return;
}
if (_currentState != ConnectionState.Connected) {
LogFlow($"HEARTBEAT_SKIP reason=not_connected state={_currentState}");
return;
}
// Build sync status for all subscribed games
var heartbeatRequest = new HeartbeatRequest {
@@ -1066,8 +1347,13 @@ namespace eagle {
var sent = await SendUpdateStreamRequestAsync(request);
if (sent) {
_remoteEagleClientLogger.LogLine(
$"[HEARTBEAT] Sent heartbeat with {heartbeatRequest.GameSyncStatuses.Count} games");
var gameInfo = string.Join(
", ",
heartbeatRequest.GameSyncStatuses.Select(
g => $"{g.GameId}:{g.UnfilteredResultCount}"));
LogFlow($"HEARTBEAT_SENT games={heartbeatRequest.GameSyncStatuses.Count} ({gameInfo})");
} else {
LogFlow("HEARTBEAT_FAILED stream_unavailable");
}
}
@@ -1076,6 +1362,7 @@ namespace eagle {
private const double SyncMismatchGracePeriodSeconds = 60.0;
private void HandleHeartbeatResponse(HeartbeatResponse response) {
LogFlow($"HEARTBEAT_RESPONSE server_ts={response.ServerTimestamp}");
_remoteEagleClientLogger.LogLine(
$"[HEARTBEAT] Got response, server_timestamp={response.ServerTimestamp}");
@@ -1083,6 +1370,7 @@ namespace eagle {
bool hasMismatch = false;
foreach (var syncResult in response.GameSyncResults) {
if (!syncResult.EagleInSync) {
LogFlow($"SYNC_MISMATCH game={syncResult.GameId} server_count={syncResult.ServerUnfilteredResultCount}");
_remoteEagleClientLogger.LogLine(
$"[SYNC_MISMATCH] Game {syncResult.GameId}: Eagle out of sync, " +
$"server has {syncResult.ServerUnfilteredResultCount} results");
@@ -1126,6 +1414,9 @@ namespace eagle {
LogConnectionEvent("sync_mismatch_reconnect", "Triggering reconnect to resync");
// Schedule reconnect to resync
// Stop timers FIRST to prevent them firing during reconnection
StopHeartbeatTimer();
StopIdleCheckTimer();
lock (this) {
_streamingCall?.Dispose();
_streamingCall = null;
Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

@@ -1,5 +1,6 @@
using System;
using System.Threading;
using Auth;
using Cysharp.Net.Http;
using eagle;
using Grpc.Core;
@@ -28,11 +29,7 @@ public class EagleConnection : IDisposable {
_channel = GrpcChannel.ForAddress(
"https://" + url,
new GrpcChannelOptions {
HttpHandler =
new YetAnotherHttpHandler {
Http2Only = true,
Http2KeepAliveInterval = TimeSpan.FromSeconds(KeepAliveSeconds)
},
HttpHandler = CreateHttpHandler(),
DisposeHttpClient = true,
LoggerFactory = _loggerFactory,
MaxReceiveMessageSize = null
@@ -42,6 +39,44 @@ public class EagleConnection : IDisposable {
return invoker;
}
/// <summary>
/// Create HTTP handler with timeouts configured for reliable connection management.
/// These settings help detect and recover from dead connections, especially on Windows
/// where firewalls may silently drop HTTP/2 keep-alive pings.
/// </summary>
private static YetAnotherHttpHandler CreateHttpHandler() {
return new YetAnotherHttpHandler {
Http2Only = true,
// Send keep-alive pings every 15 seconds
Http2KeepAliveInterval = TimeSpan.FromSeconds(KeepAliveSeconds),
// Close connection if ping not acknowledged within 5 seconds
Http2KeepAliveTimeout = TimeSpan.FromSeconds(5),
// Continue pinging even when idle to detect dead connections
Http2KeepAliveWhileIdle = true,
// Don't wait forever for initial connection
ConnectTimeout = TimeSpan.FromSeconds(10)
};
}
private CallInvoker MakeJwtInvoker(string url) {
var jwtInterceptor = new JwtAuthInterceptor();
_channel = GrpcChannel.ForAddress(
"https://" + url,
new GrpcChannelOptions {
HttpHandler = CreateHttpHandler(),
DisposeHttpClient = true,
LoggerFactory = _loggerFactory,
MaxReceiveMessageSize = null
});
var invoker = _channel.Intercept(jwtInterceptor);
return invoker;
}
/// <summary>
/// Create connection using Basic Auth (legacy).
/// </summary>
public EagleConnection(string playerName, string password, string url) {
this.playerName = playerName;
credentials = new Metadata { { "user", playerName } };
@@ -53,6 +88,26 @@ public class EagleConnection : IDisposable {
EagleGrpcClient = new Eagle.EagleClient(MakeInvoker(playerName, password, url));
}
/// <summary>
/// Create connection using JWT Bearer token auth.
/// Tokens are read from TokenStorage on each request.
/// </summary>
public static EagleConnection CreateWithJwt(string url) {
return new EagleConnection(url, useJwt: true);
}
private EagleConnection(string url, bool useJwt) {
// For JWT auth, get display name from TokenStorage
playerName = TokenStorage.DisplayName ?? "Unknown";
credentials = new Metadata { { "user", TokenStorage.UserId ?? "" } };
authHeader = null; // Not used for JWT
_loggerFactory = LoggerFactory.Create(
builder => { builder.AddProvider(new CustomFileLoggerProvider()); });
EagleGrpcClient = new Eagle.EagleClient(MakeJwtInvoker(url));
}
public void Dispose() {
try {
_channel?.Dispose();
File diff suppressed because it is too large Load Diff
@@ -1,123 +0,0 @@
fileFormatVersion: 2
guid: bce4d1b8797fe3f4c924defe072627c4
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 10
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: -1
mipBias: -100
wrapU: 1
wrapV: 1
wrapW: 1
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 2
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationDetail: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
platformSettings:
- serializedVersion: 2
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: iPhone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: Android
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID: be6d2762a8fff49759a30689bd447303
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -1,90 +0,0 @@
fileFormatVersion: 2
guid: fc00df0d402d141999c4b8bf71901287
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 10
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -100
wrapU: -1
wrapV: -1
wrapW: -1
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
platformSettings:
- serializedVersion: 2
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID:
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -1,95 +0,0 @@
fileFormatVersion: 2
guid: 5b958d07f08ec0045ab8997382e9ad8f
labels:
- Bow
- Weapon
- Item
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 10
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: -1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: 16
mipBias: -100
wrapU: 1
wrapV: 1
wrapW: 1
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationDetail: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID: 5e97eb03825dee720800000000000000
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -1,88 +0,0 @@
fileFormatVersion: 2
guid: 354f50a479c2a4ca3bf062e12f528f1c
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}
serializedVersion: 7
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -100
wrapU: -1
wrapV: -1
wrapW: -1
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
platformSettings:
- serializedVersion: 2
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID:
vertices: []
indices:
edges: []
weights: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -1,91 +0,0 @@
fileFormatVersion: 2
guid: 1c5eda65433424fb183c62967354168b
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 10
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -100
wrapU: -1
wrapV: -1
wrapW: -1
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID:
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -1,92 +0,0 @@
fileFormatVersion: 2
guid: e6b5b8b76515f4724bf8e3f75512c826
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 11
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -100
wrapU: -1
wrapV: -1
wrapW: -1
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
applyGammaDecoding: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID:
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -1,91 +0,0 @@
fileFormatVersion: 2
guid: 920f658e9b2e44c0d84fc84ea483a6af
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 10
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -100
wrapU: -1
wrapV: -1
wrapW: -1
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID:
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -1,91 +0,0 @@
fileFormatVersion: 2
guid: 87492a2ffb6094da1a19b0fa5a2ace37
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 10
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -100
wrapU: -1
wrapV: -1
wrapW: -1
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID:
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -1,92 +0,0 @@
fileFormatVersion: 2
guid: ba9c4ac960a7f474497a6dcb931bc6ed
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 11
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -100
wrapU: -1
wrapV: -1
wrapW: -1
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
applyGammaDecoding: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID:
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:

Some files were not shown because too many files have changed in this diff Show More