Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
623 lines (565 loc) · 24.1 KB
/
Copy pathapp.py
File metadata and controls
623 lines (565 loc) · 24.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
"""
AstroWebEngine — Entry Point
Run with: python app.py (or: uvicorn app:app --host 0.0.0.0 --port 8000)
"""
__version__ = "0.99.0"
import asyncio
import logging
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from fastapi.middleware.cors import CORSMiddleware
from pathlib import Path
# ── Detailed logging setup ──
LOG_DIR = Path(__file__).resolve().parent
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
handlers=[
logging.FileHandler(str(LOG_DIR / "server.log"), encoding="utf-8"),
logging.StreamHandler(),
]
)
awe_logger = logging.getLogger("awe")
awe_logger.setLevel(logging.DEBUG)
from database import engine, ModelBase, SessionLocal
from engine_identity import ENGINE_NAME, engine_identity
import mod_hooks
from auth import init_default_configs, get_config_int, get_config_float
from universe import _auto_migrate_sqlite, ensure_wormholes
from config_defaults import *
from models import ShipQueue, Colony, User, Fleet
# ── App setup ──
STATIC_DIR = Path(__file__).resolve().parent / "static"
app = FastAPI(title="AstroWebEngine")
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"])
# ── Request logging middleware ──
import time
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
class RequestLogMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
if request.url.path.startswith("/static"):
response = await call_next(request)
response.headers["X-Powered-By"] = ENGINE_NAME
if request.url.path.endswith((".js", ".css")):
response.headers["Cache-Control"] = "no-cache, must-revalidate"
return response
start = time.time()
response = await call_next(request)
response.headers["X-Powered-By"] = ENGINE_NAME
elapsed = (time.time() - start) * 1000
status = response.status_code
log_level = logging.WARNING if status >= 400 else logging.INFO
awe_logger.log(log_level, f"{request.method} {request.url.path} -> {status} ({elapsed:.0f}ms) [{request.client.host if request.client else '?'}]")
return response
app.add_middleware(RequestLogMiddleware)
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
# ── Register all routes ──
from routes_auth import register_auth_routes
from routes_map import register_map_routes
from routes_player import register_player_routes
from routes_admin import register_admin_routes
from routes_guild import register_guild_routes
from routes_tutorial import register_tutorial_routes
from routes_fleet_utils import register_fleet_util_routes
from routes_galaxy_report import register_galaxy_report_routes
from routes_commanders import register_commander_routes
from routes_catalog import register_catalog_routes
from routes_ws import register_ws_routes
register_auth_routes(app)
register_map_routes(app)
register_player_routes(app)
# Admin routes: skip if running with separate admin server (--admin-port)
import os as _os
if not _os.environ.get("AWE_ADMIN_SEPARATE"):
register_admin_routes(app)
from mcp_server import mount_mcp
mount_mcp(app) # AI assistant endpoint at /mcp (admin API tokens)
else:
awe_logger.info("Admin routes excluded — running on separate admin port")
register_guild_routes(app)
register_tutorial_routes(app)
register_fleet_util_routes(app)
register_galaxy_report_routes(app)
register_commander_routes(app)
register_catalog_routes(app)
register_ws_routes(app)
# ── Version endpoint ──
@app.get("/api/version")
async def get_version():
return {"version": __version__}
# ── Engine identity (see engine_identity.py). Lets a deployment identify the
# engine and version it runs, and lets the optional registry verify a listing. ──
@app.get("/api/engine")
async def get_engine_identity():
return engine_identity(__version__)
@app.get("/.well-known/astrowebengine")
async def get_engine_well_known():
return engine_identity(__version__)
@app.get("/api/engine-config")
async def get_engine_config():
"""Public endpoint: returns the active game definition's engine config and meta.
Used by the frontend to adapt UI based on game type (map depth, defense model, etc.)."""
from game_definition import get_game_definition
defn = get_game_definition()
return {
"meta": defn.get("meta", {}),
"engine": defn.get("engine", {}),
# Optional UI overrides a ruleset can set (e.g. nav.* tab labels) so the
# shell isn't hardcoded to one game's vocabulary.
"ui": defn.get("ui", {}),
}
@app.get("/sw.js")
async def serve_sw():
return FileResponse(str(STATIC_DIR / "sw.js"), media_type="application/javascript",
headers={"Service-Worker-Allowed": "/"})
# ── Static pages ──
# The SPA HTML shells must always be revalidated (no-cache = revalidate via
# etag, not "don't store"), so a deploy's renamed classes / bumped ?v= asset
# links are picked up immediately instead of a stale shell pinning old assets.
_SHELL_HEADERS = {"Cache-Control": "no-cache"}
@app.get("/")
async def serve_index():
return FileResponse(str(STATIC_DIR / "index.html"), media_type="text/html", headers=_SHELL_HEADERS)
@app.get("/game")
async def serve_game():
return FileResponse(str(STATIC_DIR / "game.html"), media_type="text/html", headers=_SHELL_HEADERS)
@app.get("/setup")
async def serve_setup():
"""Galaxy selection + tutorial page (post-registration)."""
return FileResponse(str(STATIC_DIR / "setup.html"), media_type="text/html")
@app.get("/gallery")
async def serve_gallery():
"""Public 'Made with AstroWebEngine' showcase gallery (links out to creator-hosted games)."""
return FileResponse(str(STATIC_DIR / "gallery.html"), media_type="text/html")
if not _os.environ.get("AWE_ADMIN_SEPARATE"):
@app.get("/admin")
async def serve_admin():
return FileResponse(str(STATIC_DIR / "admin.html"), media_type="text/html",
headers={"Cache-Control": "no-cache, must-revalidate"})
# ── Run sync DB work in thread pool to avoid blocking the event loop ──
async def _run_in_thread(func, *args):
"""Run a synchronous function in the default thread pool executor."""
loop = asyncio.get_event_loop()
return await loop.run_in_executor(None, func, *args)
async def _leader_job(func, skipped):
"""Run a game-wide background job only in the worker holding the scheduler
lease (scheduler_lease.py); other workers return `skipped` and check again
on their next pass. Without this every worker ran every job."""
import scheduler_lease
if not scheduler_lease.is_leader():
return skipped
return await _run_in_thread(func)
# ── Background bot tick task ──
def _bot_tick_sync():
db = SessionLocal()
try:
from bot_logic import tick_bots
tick_bots(db)
mod_hooks.fire("on_tick", {"tick_type": "bots", "db": db})
return get_config_int(db, "bot_tick_interval", 60)
finally:
db.close()
async def _bot_tick_loop():
"""Periodically run bot AI ticks in the background."""
while True:
try:
bot_interval = await _leader_job(_bot_tick_sync, 15)
except Exception as e:
awe_logger.error(f"[bot-tick] {e}")
bot_interval = 60
await asyncio.sleep(bot_interval)
def _npc_stability_tick_sync():
db = SessionLocal()
try:
from bot_logic import process_settlers_stability
result = process_settlers_stability(db)
mod_hooks.fire("on_tick", {"tick_type": "daily_stability", "db": db, "result": result})
return result
finally:
db.close()
async def _npc_stability_tick_loop():
"""Run NPC stability decay once per day at server midnight."""
from datetime import datetime, timedelta
while True:
try:
now = datetime.utcnow()
next_tick = (now + timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
wait_secs = max(1, (next_tick - now).total_seconds())
await asyncio.sleep(wait_secs)
result = await _leader_job(_npc_stability_tick_sync, {})
if result.get("processed") or result.get("disbanded") or result.get("created"):
awe_logger.info(
f"[npc-stability] Processed {result.get('processed', 0)} Settlers bases, "
f"disbanded {result.get('disbanded', 0)}, "
f"created {result.get('created', 0)}"
)
except Exception as e:
awe_logger.error(f"[npc-stability] {e}")
await asyncio.sleep(60)
# ── Background galaxy-network reshuffle tick (dynamic_wormholes) ──
def _galaxy_reshuffle_sync():
db = SessionLocal()
try:
import galaxy_network
if galaxy_network.maybe_reshuffle_galaxy_links(db):
awe_logger.info("[galaxy-reshuffle] regenerated the dynamic wormhole graph")
finally:
db.close()
async def _galaxy_reshuffle_tick_loop():
"""Reshuffle the galaxy-link graph when dynamic_wormholes is active and a new
reshuffle period has begun (no-op for every other topology)."""
while True:
try:
await _leader_job(_galaxy_reshuffle_sync, None)
except Exception as e:
awe_logger.error(f"[galaxy-reshuffle] {e}")
await asyncio.sleep(300) # check every 5 min; reshuffles only on epoch rollover
# ── Background debris collection tick (once per hour at :30) ──
def _recycler_tick_sync():
db = SessionLocal()
try:
from game_scouting import process_recycler_tick
process_recycler_tick(db)
mod_hooks.fire("on_tick", {"tick_type": "recycler", "db": db})
finally:
db.close()
async def _recycler_tick_loop():
"""Run debris auto-collection once per hour at the :30 mark."""
from datetime import datetime, timedelta
while True:
try:
now = datetime.utcnow()
if now.minute < 30:
next_tick = now.replace(minute=30, second=0, microsecond=0)
else:
next_tick = (now + timedelta(hours=1)).replace(minute=30, second=0, microsecond=0)
wait_secs = max(1, (next_tick - now).total_seconds())
await asyncio.sleep(wait_secs)
await _leader_job(_recycler_tick_sync, None)
awe_logger.info(f"[recycler-tick] Collected debris at {datetime.utcnow().strftime('%H:%M')}")
except Exception as e:
awe_logger.error(f"[recycler-tick] {e}")
# ── Background queue tick (every 10s) ──
def _queue_tick_sync():
from datetime import datetime
db = SessionLocal()
try:
from game_logic import _check_completions
from models import User
now = datetime.utcnow()
users = db.query(User).all()
for user in users:
_check_completions(user, db, now)
db.commit()
mod_hooks.fire("on_tick", {"tick_type": "queue", "db": db, "now": now})
return max(1, int(get_config_float(db, "QUEUE_TICK_INTERVAL", QUEUE_TICK_INTERVAL)))
finally:
db.close()
async def _queue_tick_loop():
"""Advance construction and research queues for all players."""
while True:
try:
interval = await _leader_job(_queue_tick_sync, 5)
except Exception as e:
awe_logger.error(f"[queue-tick] {e}")
interval = QUEUE_TICK_INTERVAL
await asyncio.sleep(max(1, interval))
# ── Background fleet-arrival tick (default every 1s) ──
def _fleet_arrival_tick_sync():
from datetime import datetime
db = SessionLocal()
try:
from game_logic import _process_fleet_arrivals
now = datetime.utcnow()
due_user_ids = [
user_id
for (user_id,) in (
db.query(Fleet.user_id)
.filter(
Fleet.is_moving == True,
Fleet.arrival_time != None,
Fleet.arrival_time <= now,
)
.distinct()
.all()
)
]
processed_users = 0
for user_id in due_user_ids:
user = db.query(User).filter(User.id == user_id).first()
if not user:
continue
_process_fleet_arrivals(user, db)
processed_users += 1
interval = max(1, int(get_config_float(
db, "FLEET_ARRIVAL_TICK_INTERVAL", FLEET_ARRIVAL_TICK_INTERVAL
)))
mod_hooks.fire("on_tick", {"tick_type": "fleet_arrival", "db": db, "now": now,
"processed_users": processed_users})
return {"processed_users": processed_users, "interval": interval}
finally:
db.close()
async def _fleet_arrival_tick_loop():
"""Process due fleet arrivals independently of player page loads."""
while True:
try:
result = await _leader_job(_fleet_arrival_tick_sync, {"interval": FLEET_ARRIVAL_TICK_INTERVAL})
interval = result["interval"]
except Exception as e:
awe_logger.error(f"[fleet-arrival-tick] {e}")
interval = FLEET_ARRIVAL_TICK_INTERVAL
await asyncio.sleep(max(1, interval))
# ── Background autoscout tick (every 10s) ──
def _autoscout_tick_sync():
db = SessionLocal()
try:
from game_scouting import process_autoscout_tick
process_autoscout_tick(db)
mod_hooks.fire("on_tick", {"tick_type": "autoscout", "db": db})
return max(1, int(get_config_float(db, "AUTOSCOUT_TICK_INTERVAL", AUTOSCOUT_TICK_INTERVAL)))
finally:
db.close()
async def _autoscout_tick_loop():
"""Move autoscout fleets through the galaxy."""
while True:
try:
interval = await _leader_job(_autoscout_tick_sync, 10)
except Exception as e:
awe_logger.error(f"[autoscout-tick] {e}")
interval = AUTOSCOUT_TICK_INTERVAL
await asyncio.sleep(max(1, interval))
# ── Background guild-history tick (once per hour) ──
def _guild_history_tick_sync():
db = SessionLocal()
try:
from routes_guild import capture_guild_history_snapshots
captured = capture_guild_history_snapshots(db)
mod_hooks.fire("on_tick", {"tick_type": "guild_history", "db": db, "captured": captured})
return captured
finally:
db.close()
async def _guild_history_tick_loop():
"""Capture guild graph history once per hour on a clean minute boundary."""
from datetime import datetime, timedelta
while True:
try:
now = datetime.utcnow()
next_tick = (now + timedelta(hours=1)).replace(minute=5, second=0, microsecond=0)
if now.minute < 5:
next_tick = now.replace(minute=5, second=0, microsecond=0)
wait_secs = max(1, (next_tick - now).total_seconds())
await asyncio.sleep(wait_secs)
captured = await _leader_job(_guild_history_tick_sync, False)
if captured:
awe_logger.info(f"[guild-history] Captured guild graph snapshot at {datetime.utcnow().strftime('%H:%M')}")
except Exception as e:
awe_logger.error(f"[guild-history] {e}")
# ── Background income tick (every 5 minutes) ──
def _income_tick_sync():
db = SessionLocal()
try:
from datetime import datetime
from game_logic import collect_resources
game_speed = get_config_float(db, "game_speed", 1.0)
users = db.query(User).filter(User.is_bot == False).all()
credited_users = 0
total_earned = 0.0
for user in users:
earned = collect_resources(user, db, game_speed, include_completions=False)
if earned > 0:
credited_users += 1
total_earned += earned
# Conquest mode (opt-in): escalate long-held occupations to permanent
# capture. No-op unless the occupation_capture engine flag is set.
try:
import conquest
captures = conquest.process_occupation_capture(db, now=datetime.utcnow())
if captures:
db.commit()
awe_logger.info(f"[conquest] {len(captures)} base(s) captured this tick")
except Exception as e:
awe_logger.error(f"[conquest] capture sweep failed: {e}")
db.rollback()
mod_hooks.fire("on_tick", {"tick_type": "income", "db": db, "game_speed": game_speed,
"credited_users": credited_users, "total_earned": total_earned})
return {"credited_users": credited_users, "total_earned": round(total_earned, 2)}
finally:
db.close()
async def _income_tick_loop():
"""Sweep hourly income for offline players so credits accrue while logged out."""
while True:
await asyncio.sleep(300)
try:
result = await _leader_job(_income_tick_sync, {"credited_users": 0, "total_earned": 0})
if result["credited_users"] > 0:
awe_logger.info(
f"[income-tick] Credited {result['credited_users']} players for {result['total_earned']}"
)
except Exception as e:
awe_logger.error(f"[income-tick] {e}")
def _migrate_research_queue_colony_ids(db):
"""One-time migration: assign colony_id to research queue items that don't have one."""
from models import ResearchQueue, Colony
from game_logic import get_building_level
orphans = db.query(ResearchQueue).filter(ResearchQueue.colony_id == None).all()
if not orphans:
return
# Group by user_id
by_user = {}
for rq in orphans:
by_user.setdefault(rq.user_id, []).append(rq)
for user_id, items in by_user.items():
# Find best research base for this user
colonies = db.query(Colony).filter(Colony.user_id == user_id).all()
# Ruleset-agnostic: pick the base with the most lab levels, however the
# active definition names the building that provides them.
from game_logic import calc_base_stats as _cbs
best = max(colonies,
key=lambda c: _cbs(c, c.user, 1.0).get("research_lab_level", 0),
default=None)
if best:
for rq in items:
rq.colony_id = best.id
else:
# No colonies — delete orphaned queue items
for rq in items:
db.delete(rq)
db.commit()
awe_logger.info(f"[migration] Assigned colony_id to {len(orphans)} research queue items")
def _repair_stuck_queues(db):
"""Fix ship queue items that lost next_complete during a server restart."""
from game_logic import _ship_build_time
from auth import get_config_float
from datetime import datetime, timedelta
game_speed = get_config_float(db, "game_speed", 1.0)
stuck = db.query(ShipQueue).filter(
ShipQueue.position == 0,
ShipQueue.started_at != None,
ShipQueue.next_complete == None,
).all()
if not stuck:
return
now = datetime.utcnow()
for q in stuck:
colony = db.query(Colony).filter(Colony.id == q.colony_id).first()
user = db.query(User).filter(User.id == q.user_id).first()
if not colony or not user:
continue
remaining = q.count - q.built
per_ship = _ship_build_time(q.ship_type, colony, user, game_speed, db)
q.next_complete = q.started_at + timedelta(seconds=per_ship * remaining)
db.commit()
if stuck:
awe_logger.info(f"[startup] Repaired {len(stuck)} stuck ship queue items")
# ── Startup ──
def _registry_sync():
db = SessionLocal()
try:
from awe_registry import register_sync, is_registry_enabled
if not is_registry_enabled(db):
return {"ok": False, "reason": "disabled"}
return register_sync(db, __version__)
finally:
db.close()
async def _registry_heartbeat_loop():
"""Opt-in: refresh this game's listing in the AstroWebEngine registry."""
await asyncio.sleep(15) # let the server settle before the first ping
while True:
try:
await _leader_job(_registry_sync, None)
except Exception as e:
awe_logger.error(f"[registry] {e}")
await asyncio.sleep(3600) # hourly heartbeat
def _runtime_sync():
import runtime_sync
db = SessionLocal()
try:
import scheduler_lease
was_leader = scheduler_lease.is_leader()
if scheduler_lease.renew(db) != was_leader:
awe_logger.info(f"[sync] {'now running' if not was_leader else 'stopped running'} "
f"the background jobs (worker {scheduler_lease.WORKER_ID})")
result = runtime_sync.sync_once(db)
if result["reloaded"]:
awe_logger.info("[sync] active ruleset changed in another worker - reloaded")
finally:
db.close()
async def _runtime_sync_loop():
"""Pick up admin settings and ruleset activations made through other workers."""
import runtime_sync
while True:
try:
await _run_in_thread(_runtime_sync)
except Exception as e:
awe_logger.error(f"[sync] {e}")
await asyncio.sleep(runtime_sync.SYNC_SECONDS)
@app.on_event("startup")
async def startup():
ModelBase.metadata.create_all(bind=engine)
_auto_migrate_sqlite()
# Runtime state written next to the code by older versions → AWE_DATA_DIR.
import data_paths
for moved in data_paths.migrate_legacy_runtime_files():
awe_logger.info(f"[data] moved {moved}")
awe_logger.info(f"[data] runtime state in {data_paths.data_dir()}")
# SQLite PRAGMAs (WAL, busy_timeout) are set per-connection in database.py
db = SessionLocal()
init_default_configs(db)
ensure_wormholes(db)
# Behavioral-mod hooks (opt-in, default off — see mod_hooks.load_mod_hooks)
try:
import mod_hooks
hook_report = mod_hooks.load_mod_hooks(db)
if hook_report.get("loaded"):
awe_logger.info(f"[mods] loaded hooks from: {hook_report['loaded']}")
except Exception as e:
awe_logger.error(f"[startup mod-hooks] {e}")
try:
from routes_guild import capture_guild_history_snapshots
capture_guild_history_snapshots(db)
except Exception as e:
awe_logger.error(f"[startup guild-history] {e}")
_migrate_research_queue_colony_ids(db)
_repair_stuck_queues(db)
try:
from bot_logic import process_settlers_stability
process_settlers_stability(db)
except Exception as e:
awe_logger.error(f"[startup npc-stability] {e}")
db.close()
# Resolve the active game definition:
# 1. AWE_GAME_DEFINITION env (universe manager / ops override)
# 2. admin-persisted selection (Build Game / import / mods) — survives restart
# 3. built-in default
game_def_path = _os.environ.get("AWE_GAME_DEFINITION")
if game_def_path and _os.path.exists(game_def_path):
from game_definition import activate_env_definition
defn = activate_env_definition(game_def_path)
awe_logger.info(f"Loaded game definition from env: {defn.get('meta', {}).get('name', game_def_path)}")
else:
from game_definition import restore_persisted_definition
_rdb = SessionLocal()
try:
_restored = restore_persisted_definition(_rdb)
finally:
_rdb.close()
if _restored:
awe_logger.info(f"Restored persisted game definition: {_restored}")
# Start background tick loops
asyncio.create_task(_bot_tick_loop())
asyncio.create_task(_npc_stability_tick_loop())
asyncio.create_task(_recycler_tick_loop())
asyncio.create_task(_galaxy_reshuffle_tick_loop())
asyncio.create_task(_queue_tick_loop())
asyncio.create_task(_fleet_arrival_tick_loop())
asyncio.create_task(_autoscout_tick_loop())
asyncio.create_task(_guild_history_tick_loop())
asyncio.create_task(_income_tick_loop())
asyncio.create_task(_registry_heartbeat_loop())
asyncio.create_task(_runtime_sync_loop())
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)