-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2667 lines (2220 loc) · 107 KB
/
Copy pathapp.py
File metadata and controls
2667 lines (2220 loc) · 107 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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Flask backend for bot arena prototype (refactored).
Architecture:
- API Layer (app.py): Routes HTTP, validation inputs
- Service Layer (services/): Logique métier
- Repository Layer (repositories/): Accès données
- Domain Layer (game_sdk, models): Entités et règles métier
SOLID compliant avec séparation des responsabilités.
"""
from flask import Flask, jsonify, request, send_from_directory, send_file
from werkzeug.utils import secure_filename
from referees.pacman_referee_v2 import PacmanRefereeV2
import os
import pathlib
from game_sdk import Referee, make_bot_runner, BotRunner
from runner.docker_runner import get_last_run_debug, set_console_tracing, is_console_tracing_enabled
from flask_cors import CORS
from flask_jwt_extended import JWTManager, jwt_required, get_jwt_identity
from models import db, User, Bot, Match
from auth import register_user, login_user, get_current_user
from arena import ArenaManager
from boss_system import BossSystem
from leagues import League, LeagueManager
import uuid
import subprocess
import logging
import errno
import json
import re
import traceback
import datetime as dt
# Import des services et repositories (DIP)
from services.bot_service import BotService
from services.game_service import GameService
from repositories.bot_repository import BotRepository
from repositories.game_repository import GameRepository
from repositories.user_repository import UserRepository
# Configure basic logging so INFO logs appear in the Flask console by default
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(name)s: %(message)s')
# Ensure Flask and werkzeug loggers propagate at INFO level
logging.getLogger('werkzeug').setLevel(logging.INFO)
app = Flask(__name__, static_folder=None) # Désactiver le static folder automatique
# Ensure app logger level
app.logger.setLevel(logging.INFO)
# Configuration
import secrets
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', secrets.token_hex(32))
app.config['JWT_SECRET_KEY'] = os.environ.get('JWT_SECRET_KEY', secrets.token_hex(32))
app.config['WTF_CSRF_ENABLED'] = True
app.config['WTF_CSRF_TIME_LIMIT'] = None
app.config['WTF_CSRF_CHECK_DEFAULT'] = False # Désactiver vérification auto, on vérifie manuellement
app.config['JWT_TOKEN_LOCATION'] = ['headers']
app.config['JWT_HEADER_NAME'] = 'Authorization'
app.config['JWT_HEADER_TYPE'] = 'Bearer'
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', f"sqlite:///{os.path.abspath('instance/gamearena.db')}")
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Initialize extensions
# Configuration CORS étendue pour Private Network Access
CORS(app,
supports_credentials=True,
origins='*',
allow_headers=['Content-Type', 'Authorization', 'X-CSRF-Token', 'Access-Control-Request-Private-Network'],
expose_headers=['Access-Control-Allow-Private-Network'])
db.init_app(app)
jwt = JWTManager(app)
from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect(app)
# Middleware pour Private Network Access (CORS preflight)
@app.after_request
def add_private_network_headers(response):
"""Ajoute les headers nécessaires pour Private Network Access.
Permet les requêtes depuis des domaines publics vers localhost.
Voir: https://developer.chrome.com/blog/private-network-access-preflight/
"""
# Si la requête contient le header de demande d'accès au réseau privé
if request.headers.get('Access-Control-Request-Private-Network'):
response.headers['Access-Control-Allow-Private-Network'] = 'true'
# Ajouter les headers CORS standards pour toutes les réponses
response.headers['Access-Control-Allow-Origin'] = request.headers.get('Origin', '*')
response.headers['Access-Control-Allow-Credentials'] = 'true'
response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization, Access-Control-Request-Private-Network'
return response
# JWT error handlers
@jwt.invalid_token_loader
def invalid_token_callback(error):
return jsonify({'error': 'Invalid token', 'message': str(error)}), 422
@jwt.unauthorized_loader
def missing_token_callback(error):
return jsonify({'error': 'Authorization required', 'message': str(error)}), 401
@jwt.expired_token_loader
def expired_token_callback(jwt_header, jwt_payload):
return jsonify({'error': 'Token has expired'}), 401
# Initialize arena manager
arena_manager = ArenaManager(referee_type='pacman')
# Create tables
with app.app_context():
db.create_all()
# Directory where edited player bots are persisted so they can be mounted into Docker
PERSISTENT_BOTS_DIR = os.environ.get('PERSISTENT_BOTS_DIR', 'persistent_bots')
try:
pathlib.Path(PERSISTENT_BOTS_DIR).mkdir(parents=True, exist_ok=True)
except OSError as e:
if e.errno != errno.EEXIST:
raise
# Simple games index persisted to disk to allow short-lived server restarts without losing game ids
GAMES_INDEX_PATH = os.path.join(PERSISTENT_BOTS_DIR, 'games_index.json')
# In-memory games store (legacy, sera progressivement remplacé par GameService)
GAMES = {}
# Import du nouveau referee v2
from referees.pacman_referee_v2 import PacmanRefereeV2
REFEREES = {
'pacman': PacmanRefereeV2, # V2 est maintenant le referee par défaut (support ligues)
'pacman_v2': PacmanRefereeV2 # Alias explicite
}
# -------------------- Service Layer Initialization (DIP) --------------------
# Les services sont injectés avec leurs dépendances (repositories)
# Pattern: Dependency Injection pour faciliter les tests et respecter SOLID
game_repository = GameRepository(PERSISTENT_BOTS_DIR, 'games_index.json')
bot_repository = BotRepository()
user_repository = UserRepository()
bot_service = BotService(bot_repository, game_repository)
game_service = GameService(REFEREES, game_repository, bot_repository)
# -------------------- helpers --------------------
def load_games_index():
try:
if os.path.exists(GAMES_INDEX_PATH):
with open(GAMES_INDEX_PATH, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception:
logging.getLogger(__name__).exception('failed to load games index')
return {}
def save_games_index_entry(game_id: str, meta: dict):
idx = load_games_index()
idx[game_id] = meta
try:
with open(GAMES_INDEX_PATH, 'w', encoding='utf-8') as f:
json.dump(idx, f)
except Exception:
logging.getLogger(__name__).exception('failed to write games index')
def restore_game_from_index(game_id: str):
idx = load_games_index()
meta = idx.get(game_id)
if not meta:
return None
maker = REFEREES.get(meta.get('referee', 'pacman'))
if not maker:
return None
ref = maker()
ref.init_game({})
game_entry = {
'id': game_id,
'ref': ref,
'player_code': None,
'player_bot_id': meta.get('player_bot_id'),
'opponent': meta.get('opponent', 'Boss'),
'bot_runner': meta.get('bot_runner'),
'history': ref.history
}
GAMES[game_id] = game_entry
# Log restore so operator sees which opponent is associated
try:
logging.getLogger(__name__).info('restored game %s from index, opponent=%s, player_bot_id=%s', game_id, game_entry.get('opponent'), game_entry.get('player_bot_id'))
except Exception:
pass
return game_entry
# Helper: run bot code in a subprocess (unused normally, kept for debugging)
def run_bot_python(bot_code: str, input_str: str, timeout_ms: int = 50):
cmd = ['python3', '-c', bot_code]
try:
proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
try:
out, err = proc.communicate(input=input_str, timeout=timeout_ms/1000.0)
return out, err, proc.returncode
except subprocess.TimeoutExpired:
proc.kill()
return '', 'timeout', -1
except Exception as e:
return '', str(e), -1
# Validate action text
# V1: Une seule commande MOVE
ACTION_RE_V1 = re.compile(r'^(MOVE\s+-?\d+\s+-?\d+(?:\s+-?\d+)?)$', re.IGNORECASE)
# V2: Multiples commandes séparées par |
ACTION_RE_V2 = re.compile(r'^((MOVE|SPEED|SWITCH)\s+[^|]+)(\s*\|\s*(MOVE|SPEED|SWITCH)\s+[^|]+)*$', re.IGNORECASE)
def validate_action_format(raw_output: str, normalized_action: str, allow_multi_commands: bool = False):
# Check if bot produced no output
if not raw_output or not raw_output.strip():
return normalized_action, 'no output from bot'
first_line = ''
for ln in raw_output.splitlines():
if ln and ln.strip():
first_line = ln.strip()
break
if not first_line:
return normalized_action, 'no valid output from bot'
# Vérifier selon le format attendu
if allow_multi_commands:
# V2: accepter plusieurs commandes
if ACTION_RE_V2.match(first_line) or ACTION_RE_V1.match(first_line):
return normalized_action, ''
else:
# V1: une seule commande
if ACTION_RE_V1.match(first_line):
return normalized_action, ''
return normalized_action, f'invalid action format: "{first_line}"'
# Run a bot for a role using BotRunner (file or inline code)
def _run_bot_for_role(game: dict, ref: Referee, role: str, bot_cli_input: str, initial_map_block: str, timeout_ms: int, memory_mb: int, cpus: float):
bot_code = None
bot_path = None
is_arena_match = game.get('is_arena_match', False)
mode = game.get('mode', 'player-vs-bot')
# Bot-vs-bot mode: map player/opponent roles to bot1/bot2
if mode == 'bot-vs-bot':
bot_setting = game.get('bot1') if role == 'player' else game.get('bot2')
try:
bot_id = int(bot_setting)
from models import Bot
bot = Bot.query.get(bot_id)
if bot:
if is_arena_match and bot.latest_version_number > 0:
active_version = bot.get_active_version()
if active_version:
bot_code = active_version.code
bot_path = f'db:bot:{bot_id}:v{active_version.version_number}'
logging.getLogger(__name__).info(f'Using bot from Arena ({role}): id=%s, name=%s, version=%s',
bot_id, bot.name, active_version.version_name)
else:
bot_code = bot.code
bot_path = f'db:bot:{bot_id}'
else:
bot_code = bot.code
bot_path = f'db:bot:{bot_id}:draft'
logging.getLogger(__name__).info(f'Using bot draft ({role}): id=%s, name=%s', bot_id, bot.name)
except (ValueError, TypeError):
# Fallback to Boss or other default
if bot_setting == 'Boss' or not bot_setting:
bot_path = 'bots/Boss.py'
if os.path.exists(bot_path):
try:
with open(bot_path, 'r', encoding='utf-8') as f:
bot_code = f.read()
except Exception:
pass
if not bot_code:
bot_code = 'print("STAY")'
elif role == 'player':
# Check if player is specified by bot ID (Arena match)
player_bot_id = game.get('player_bot_id')
if player_bot_id:
from models import Bot
bot = Bot.query.get(player_bot_id)
if bot:
if is_arena_match and bot.latest_version_number > 0:
# Use Arena version for player
active_version = bot.get_active_version()
if active_version:
bot_code = active_version.code
bot_path = f'db:bot:{player_bot_id}:v{active_version.version_number}'
logging.getLogger(__name__).info('Using player bot from Arena: id=%s, name=%s, version=%s',
player_bot_id, bot.name, active_version.version_name)
else:
bot_code = bot.code
bot_path = f'db:bot:{player_bot_id}'
logging.getLogger(__name__).warning('Player bot %s has no Arena version, using draft code', player_bot_id)
else:
# Use current working draft (Playground)
bot_code = bot.code
bot_path = f'db:bot:{player_bot_id}:draft'
logging.getLogger(__name__).info('Using player bot draft from Playground: id=%s, name=%s', player_bot_id, bot.name)
# Fallback to legacy player_bot_path or player_code
if not bot_code:
bot_path = game.get('player_bot_path')
if bot_path and os.path.exists(bot_path):
try:
with open(bot_path, 'r', encoding='utf-8') as f:
bot_code = f.read()
except Exception:
bot_code = None
if not bot_code:
bot_code = game.get('player_code')
else:
opp_setting = game.get('opponent')
# Check if opponent is a bot ID (integer or string digit)
try:
bot_id = int(opp_setting)
from models import Bot
bot = Bot.query.get(bot_id)
if bot:
# For Arena matches, use the latest submitted version
# For Playground testing, use current working code
if is_arena_match and bot.latest_version_number > 0:
# Use Arena version
active_version = bot.get_active_version()
if active_version:
bot_code = active_version.code
bot_path = f'db:bot:{bot_id}:v{active_version.version_number}'
logging.getLogger(__name__).info('Using bot from Arena: id=%s, name=%s, version=%s',
bot_id, bot.name, active_version.version_name)
else:
bot_code = bot.code
bot_path = f'db:bot:{bot_id}'
logging.getLogger(__name__).warning('Bot %s has no Arena version, using draft code', bot_id)
else:
# Use current working draft (Playground)
bot_code = bot.code
bot_path = f'db:bot:{bot_id}:draft'
logging.getLogger(__name__).info('Using bot draft from Playground: id=%s, name=%s', bot_id, bot.name)
except (ValueError, TypeError):
# Not a bot ID, check if it's a file path
if opp_setting and os.path.exists(opp_setting):
bot_path = opp_setting
try:
with open(bot_path, 'r', encoding='utf-8') as f:
bot_code = f.read()
except Exception:
bot_code = None
else:
# Default opponent (Boss)
default_opp = os.path.join('bots', 'Boss.py')
if os.path.exists(default_opp):
bot_path = default_opp
try:
with open(bot_path, 'r', encoding='utf-8') as f:
bot_code = f.read()
except Exception:
bot_code = None
if not bot_code:
try:
ref.on_bot_timeout(role, ref.turn, 'no bot implementation')
except Exception:
pass
logging.getLogger(__name__).info('game %s role=%s: no bot implementation (path=%s)', game.get('id'), role, bot_path)
return 'STAY', {'stdout': '', 'stderr': 'no bot implementation', 'rc': -1, 'runner': 'engine', 'path': bot_path}
# If the bot source contains a top-level while loop we can run it in parsed-mode
# so that initialization runs once and the per-turn body is invoked repeatedly.
# This avoids running the whole script in a subprocess where stdin is closed after
# sending a single combined input (which causes EOFError on the next input()).
try:
# prepare storage for parsed bots per game
parsed_store = game.setdefault('parsed_bots', {})
parsed_entry = parsed_store.get(role)
if not parsed_entry:
# Try to parse bot code and detect a per-turn loop
try:
from game_sdk import parse_bot_code, run_parsed_init, run_parsed_turn
parsed = parse_bot_code(bot_code)
# Run init once using the initial_map_block
logging.getLogger(__name__).debug('game %s role=%s: running parsed init with map block length=%d', game.get('id'), role, len(initial_map_block or ''))
out_init, err_init, rc_init = run_parsed_init(parsed, initial_map_block or '', timeout_ms=max(2000, timeout_ms))
# Check if init succeeded
if rc_init != 0:
logging.getLogger(__name__).warning('game %s role=%s: parsed init failed (rc=%d, stderr=%s)', game.get('id'), role, rc_init, err_init)
parsed_entry = None
else:
# store parsed object and its init outputs for subsequent turns
parsed_store[role] = {'parsed': parsed, 'init_stdout': out_init or '', 'init_stderr': err_init or ''}
parsed_entry = parsed_store[role]
logging.getLogger(__name__).debug('game %s role=%s: parsed init succeeded', game.get('id'), role)
except Exception as e:
logging.getLogger(__name__).exception('game %s role=%s: exception during parsed init', game.get('id'), role)
parsed_entry = None
# If we have a parsed entry with turn code, run it for this turn
if parsed_entry:
try:
from game_sdk import run_parsed_turn
parsed_obj = parsed_entry.get('parsed') if isinstance(parsed_entry, dict) else parsed_entry
out, err, rc = run_parsed_turn(parsed_obj, bot_cli_input or '', timeout_ms=max(2000, timeout_ms))
runner_used = 'parsed'
if rc == -1:
try:
ref.on_bot_timeout(role, ref.turn, err or 'timeout')
except Exception:
pass
logging.getLogger(__name__).info('game %s role=%s: parsed execution failed/timeout (path=%s) runner=%s', game.get('id'), role, bot_path, runner_used)
return 'STAY', {'stdout': out or '', 'stderr': err or 'timeout', 'rc': rc, 'runner': runner_used, 'parsed': True, 'path': bot_path}
action = ref.parse_bot_output(role, out)
# V2 referee accepte plusieurs commandes
allow_multi = ref.__class__.__name__ == 'PacmanRefereeV2'
action, fmt_err = validate_action_format(out, action, allow_multi_commands=allow_multi)
# Treat invalid actions as fatal errors
if fmt_err:
try:
ref.on_bot_timeout(role, ref.turn, fmt_err)
except Exception:
pass
logging.getLogger(__name__).warning('game %s role=%s: invalid action detected (path=%s) error=%s', game.get('id'), role, bot_path, fmt_err)
return 'STAY', {'stdout': out or '', 'stderr': fmt_err, 'rc': -1, 'runner': runner_used, 'parsed': True, 'path': bot_path}
stderr_field = (err or '') + (('; ' + fmt_err) if fmt_err else '')
# include init stderr if present (helps debug init failures)
if isinstance(parsed_entry, dict):
if parsed_entry.get('init_stderr'):
stderr_field = (parsed_entry.get('init_stderr') or '') + (('; ' + stderr_field) if stderr_field else '')
# logging.getLogger(__name__).info('game %s role=%s: executed parsed bot (path=%s) runner=%s', game.get('id'), role, bot_path, runner_used)
return action, {'stdout': out, 'stderr': stderr_field, 'rc': rc, 'runner': runner_used, 'parsed': True, 'path': bot_path}
except Exception as e:
# parsing-based execution failed; fall back to normal runner below
logging.getLogger(__name__).exception('parsed execution failed for role %s in game %s', role, game.get('id'))
# remove parsed entry to avoid repeated failures
try:
parsed_store.pop(role, None)
except Exception:
pass
# Fallback: run via BotRunner (docker/subprocess)
game_runner_mode = game.get('bot_runner')
runner = BotRunner(mode=game_runner_mode) if game_runner_mode else make_bot_runner()
full_input = (initial_map_block or '') + (bot_cli_input or '')
out, err, rc, runner_used = runner.run(bot_code, full_input, timeout_ms=timeout_ms, memory_mb=memory_mb, cpus=cpus, host_bot_dir=(os.path.dirname(bot_path) if bot_path else None))
if rc == -1:
try:
ref.on_bot_timeout(role, ref.turn, err or 'timeout')
except Exception:
pass
logging.getLogger(__name__).info('game %s role=%s: runner execution failed (path=%s) runner=%s err=%s', game.get('id'), role, bot_path, runner_used, err)
return 'STAY', {'stdout': out or '', 'stderr': err or 'timeout', 'rc': rc, 'runner': runner_used, 'path': bot_path}
action = ref.parse_bot_output(role, out)
# V2 referee accepte plusieurs commandes
allow_multi = ref.__class__.__name__ == 'PacmanRefereeV2'
action, fmt_err = validate_action_format(out, action, allow_multi_commands=allow_multi)
# Treat invalid actions as fatal errors
if fmt_err:
try:
ref.on_bot_timeout(role, ref.turn, fmt_err)
except Exception:
pass
logging.getLogger(__name__).warning('game %s role=%s: invalid action detected (path=%s) error=%s', game.get('id'), role, bot_path, fmt_err)
return 'STAY', {'stdout': out or '', 'stderr': fmt_err, 'rc': -1, 'runner': runner_used, 'path': bot_path}
stderr_field = (err or '') + (('; ' + fmt_err) if fmt_err else '')
logging.getLogger(__name__).info('game %s role=%s: executed runner bot (path=%s) runner=%s', game.get('id'), role, bot_path, runner_used)
return action, {'stdout': out, 'stderr': stderr_field, 'rc': rc, 'runner': runner_used, 'path': bot_path}
except Exception as e:
logging.getLogger(__name__).exception('game %s role=%s: unexpected error executing bot at path=%s', game.get('id'), role, bot_path)
return 'STAY', {'stdout': '', 'stderr': str(e), 'rc': -1, 'runner': 'runner', 'path': bot_path}
# -------------------- HTTP endpoints --------------------
@app.route('/api/csrf-token', methods=['GET'])
def get_csrf_token():
from flask_wtf.csrf import generate_csrf
token = generate_csrf()
response = jsonify({'csrf_token': token})
# S'assurer que le cookie de session est défini
response.set_cookie('csrf_token', token, samesite='Lax')
return response
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def index(path):
"""
Route principale qui sert index.html pour toutes les routes SPA React Router.
Gère aussi le logging des connexions clientes et les fichiers statiques.
"""
STATIC_DIR = 'static'
# Si le path demandé correspond à un fichier statique existant, le servir
if path and not path.startswith('api/'):
static_file = os.path.join(STATIC_DIR, path)
if os.path.exists(static_file) and os.path.isfile(static_file):
return send_from_directory(STATIC_DIR, path)
# Logging des connexions (seulement pour la route racine)
if not path:
ip = request.headers.get('X-Forwarded-For', request.remote_addr)
ua_string = request.headers.get('User-Agent', '')
client_os = 'Unknown'
browser = 'Unknown'
if 'Windows' in ua_string:
client_os = 'Windows'
elif 'Mac' in ua_string or 'Darwin' in ua_string:
client_os = 'macOS'
elif 'Linux' in ua_string:
client_os = 'Linux'
if 'Chrome' in ua_string:
browser = 'Chrome'
elif 'Firefox' in ua_string:
browser = 'Firefox'
elif 'Safari' in ua_string:
browser = 'Safari'
date = dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
logging.getLogger(__name__).info('Client connected: IP=%s, OS=%s, Browser=%s, Date=%s', ip, client_os, browser, date)
# Servir index.html pour toutes les routes React Router
return send_from_directory(STATIC_DIR, 'index.html')
@app.route('/api/referees')
def list_referees():
ip = request.headers.get('X-Forwarded-For', request.remote_addr)
ua_string = request.headers.get('User-Agent', '')
os = 'Unknown'
browser = 'Unknown'
if 'Windows' in ua_string:
os = 'Windows'
elif 'Mac' in ua_string or 'Darwin' in ua_string:
os = 'macOS'
elif 'Linux' in ua_string:
os = 'Linux'
if 'Chrome' in ua_string:
browser = 'Chrome'
elif 'Firefox' in ua_string:
browser = 'Firefox'
elif 'Safari' in ua_string:
browser = 'Safari'
date = dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
logging.getLogger(__name__).info('Client connected: IP=%s, OS=%s, Browser=%s, Date=%s', ip, os, browser, date)
data = {}
for name, maker in REFEREES.items():
ref = maker()
data[name] = ref.get_protocol()
return jsonify(data)
@app.route('/api/template')
@app.route('/api/player/template')
def get_player_template():
try:
tpl_path = os.path.join('bots', 'player_template.py')
with open(tpl_path, 'r', encoding='utf-8') as f:
src = f.read()
return jsonify({'template': src})
except Exception as e:
return jsonify({'error': str(e)}), 500
# Old /api/player/code endpoint removed - bot code now stored in database only
@app.route('/api/games', methods=['POST'])
@jwt_required(optional=True)
def create_game():
"""Crée une nouvelle partie.
API Layer: Validation des inputs et délégation au GameService.
Responsabilité: HTTP handling uniquement (SRP).
"""
body = request.json or {}
# Extraction et validation des paramètres
referee_name = body.get('referee', 'pacman_v2') # Utiliser v2 par défaut (support des ligues)
mode = body.get('mode', 'player-vs-bot')
bot_runner = body.get('bot_runner')
# Récupérer la ligue de l'utilisateur courant (déterminée par son bot principal)
user_league = None
try:
user = get_current_user()
if user and user.bots:
# Utiliser le bot avec le plus haut ELO pour déterminer la ligue
user_bot = max(user.bots, key=lambda b: b.elo_rating) if user.bots else None
if user_bot:
user_league = LeagueManager.get_league_from_elo(user_bot.elo_rating).value
logging.getLogger(__name__).info(f"Creating game for user {user.username} in league {user_league}")
except Exception as e:
logging.getLogger(__name__).warning(f"Could not get user league: {e}")
try:
# Délégation à la couche service (SRP + DIP)
if mode == 'bot-vs-bot':
result = game_service.create_game(
referee_name=referee_name,
mode='bot-vs-bot',
bot1=body.get('bot1', 'Boss'),
bot2=body.get('bot2', 'Boss'),
bot_runner=bot_runner,
user_league=user_league
)
else:
result = game_service.create_game(
referee_name=referee_name,
mode='player-vs-bot',
player_code=body.get('player_code'),
opponent=body.get('opponent', 'Boss'),
player_bot_id=body.get('player_bot_id'),
bot_runner=bot_runner,
user_league=user_league
)
# Sync avec le store legacy (transition progressive)
game_id = result['game_id']
game_entry = game_service.get_game(game_id)
if game_entry:
GAMES[game_id] = game_entry
return jsonify(result), 200
except ValueError as e:
return jsonify({'error': str(e)}), 400
except Exception as e:
logging.getLogger(__name__).exception('Failed to create game')
return jsonify({'error': 'Internal server error'}), 500
@app.route('/api/games/<game_id>', methods=['GET'])
def get_game_info(game_id):
"""Récupère les informations d'une partie.
API Layer: Validation et délégation au GameService.
"""
try:
# Essai avec le store legacy d'abord (transition)
g = GAMES.get(game_id)
if not g:
g = game_service.get_game(game_id)
if not g:
g = restore_game_from_index(game_id)
if not g:
return jsonify({'error': 'Game not found'}), 404
info = {
'id': g.get('id'),
'player_bot_id': g.get('player_bot_id'),
'opponent': g.get('opponent')
}
return jsonify({'game': info}), 200
except Exception as e:
logging.getLogger(__name__).exception('Failed to get game info')
return jsonify({'error': 'Internal server error'}), 500
@app.route('/api/games/<game_id>/step', methods=['POST'])
def step_game(game_id):
try:
game = GAMES.get(game_id)
if not game:
game = restore_game_from_index(game_id)
if not game:
return jsonify({'error': 'not found'}), 404
logging.getLogger(__name__).debug('step_game called for game_id=%s', game_id)
ref: Referee = game['ref']
timeout_ms = ref.get_protocol().get('constraints', {}).get('time_ms', 50)
memory_mb = ref.get_protocol().get('constraints', {}).get('memory_mb', 64)
cpus = ref.get_protocol().get('constraints', {}).get('cpus', 0.5)
if ref.is_finished():
return jsonify({'finished': True, 'state': ref.get_state(), 'history': ref.history})
actions = {}
player_log = {'stdout': '', 'stderr': '', 'rc': 0, 'runner': ''}
opponent_log = {'stdout': '', 'stderr': '', 'rc': 0, 'runner': ''}
player_input = ref.make_bot_input('player')
opponent_input = ref.make_bot_input('opponent')
try:
width = getattr(ref, 'width')
height = getattr(ref, 'height')
rows = [''.join(ref.grid[y]) for y in range(height)]
initial_map_block = f"{width} {height}\n" + '\n'.join(rows) + '\n'
except Exception:
initial_map_block = ''
try:
action_player, player_log = _run_bot_for_role(game, ref, 'player', player_input, initial_map_block, timeout_ms, memory_mb, cpus)
except Exception as e:
logging.getLogger(__name__).exception('error running player bot for game %s', game.get('id'))
action_player, player_log = 'STAY', {'stdout': '', 'stderr': str(e), 'rc': -1, 'runner': 'exception'}
actions['player'] = action_player or 'STAY'
# Log which opponent will be used for this step so it's visible in console
# try:
# # Use info level so the opponent name is visible in normal Flask logs
# logging.getLogger(__name__).info('game %s: opponent=%s', game_id, game.get('opponent'))
# except Exception:
# pass
try:
action_opp, opponent_log = _run_bot_for_role(game, ref, 'opponent', opponent_input, initial_map_block, timeout_ms, memory_mb, cpus)
except Exception as e:
logging.getLogger(__name__).exception('error running opponent bot for game %s', game.get('id'))
action_opp, opponent_log = 'STAY', {'stdout': '', 'stderr': str(e), 'rc': -1, 'runner': 'exception'}
actions['opponent'] = action_opp or 'STAY'
state, stdout, stderr = ref.step(actions)
entry = ref.history[-1]
entry['bot_logs'] = {'player': player_log, 'opponent': opponent_log}
entry['__global_stdout'] = stdout
entry['__global_stderr'] = stderr
return jsonify({'state': state, 'history_entry': entry})
except Exception as e:
logging.getLogger(__name__).exception('Error in step_game for game_id=%s', game_id)
return jsonify({'error': 'internal error', 'detail': str(e)}), 500
@app.route('/api/games/<game_id>/history')
def get_history(game_id):
game = GAMES.get(game_id)
if not game:
game = restore_game_from_index(game_id)
if not game:
return jsonify({'error': 'not found'}), 404
ref: Referee = game['ref']
return jsonify({'history': ref.history})
@app.route('/api/runner/check')
def check_runner():
try:
proc = subprocess.run(['docker', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=5)
if proc.returncode == 0:
return jsonify({'available': True, 'version': proc.stdout.strip()})
else:
return jsonify({'available': False, 'error': proc.stderr.strip() or proc.stdout.strip()}), 500
except FileNotFoundError:
return jsonify({'available': False, 'error': 'docker not found'}), 500
except subprocess.TimeoutExpired:
return jsonify({'available': False, 'error': 'docker timeout'}), 500
@app.route('/api/runner/verify', methods=['GET'])
def verify_runner_execution():
test_code = """import sys
_ = sys.stdin.read()
print('PING')
"""
timeout_ms = 2000
old_flag = os.environ.get('DOCKER_RUNNER_PER_RUN_CHECKS')
os.environ['DOCKER_RUNNER_PER_RUN_CHECKS'] = '1'
try:
runner = make_bot_runner()
out, err, rc, runner_used = runner.run(test_code, "", timeout_ms=timeout_ms, memory_mb=64, cpus=0.5)
debug = get_last_run_debug()
return jsonify({'ok': True, 'runner_used': runner_used, 'stdout': out, 'stderr': err, 'rc': rc, 'debug': debug})
except Exception as e:
debug = get_last_run_debug()
return jsonify({'ok': False, 'error': str(e), 'debug': debug}), 500
finally:
if old_flag is None:
os.environ.pop('DOCKER_RUNNER_PER_RUN_CHECKS', None)
else:
os.environ['DOCKER_RUNNER_PER_RUN_CHECKS'] = old_flag
@app.route('/api/runner/logging', methods=['GET'])
def get_runner_logging():
try:
enabled = is_console_tracing_enabled()
return jsonify({'enabled': bool(enabled)})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/runner/logging', methods=['POST'])
def set_runner_logging():
body = request.json or {}
if 'enabled' not in body:
return jsonify({'error': 'missing "enabled" boolean in request body'}), 400
try:
enabled = bool(body.get('enabled'))
set_console_tracing(enabled)
return jsonify({'enabled': is_console_tracing_enabled()})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/runner/env', methods=['GET'])
def get_runner_env():
import pkgutil
import subprocess as _subp
import sys as _sys
import json as _json
try:
limit = int(request.args.get('limit', '200'))
if limit < 0:
limit = 0
except Exception:
limit = 200
try:
py_exec = _sys.executable
py_version = _sys.version
all_mods = sorted([m.name for m in pkgutil.iter_modules()])
subprocess_info = {'executable': py_exec, 'version': py_version, 'modules_count': len(all_mods), 'modules_sample': all_mods[:limit]}
except Exception as e:
subprocess_info = {'error': str(e)}
docker_image = os.environ.get('BOT_DOCKER_IMAGE', 'python:3.11-slim')
docker_info = {'image': docker_image, 'available': False}
try:
check = _subp.run(['docker', '--version'], stdout=_subp.PIPE, stderr=_subp.PIPE, text=True, timeout=3)
docker_info['available'] = (check.returncode == 0)
docker_info['docker_version'] = (check.stdout or check.stderr or '').strip()
except Exception as e:
docker_info['available'] = False
docker_info['error'] = str(e)
if docker_info.get('available'):
try:
snippet = """import sys,pkgutil,json
mods = sorted([m.name for m in pkgutil.iter_modules()])
print(json.dumps({'version': sys.version, 'modules': mods}))
"""
cmd = ['docker', 'run', '--rm', '--network', 'none', docker_image, 'python3', '-c', snippet]
proc = _subp.run(cmd, stdout=_subp.PIPE, stderr=_subp.PIPE, text=True, timeout=30)
if proc.returncode == 0:
try:
payload = _json.loads(proc.stdout)
mods = payload.get('modules', []) or []
docker_info['python_version'] = payload.get('version')
docker_info['modules_count'] = len(mods)
docker_info['modules_sample'] = mods[:limit]
except Exception as e:
docker_info['error'] = f'failed to parse docker output: {e}'; docker_info['raw_stdout'] = proc.stdout[:2000]
else:
docker_info['error'] = (proc.stderr or proc.stdout).strip()
except Exception as e:
docker_info['available'] = False
docker_info['error'] = str(e)
return jsonify({'subprocess': subprocess_info, 'docker': docker_info})
@app.route('/static/<path:path>')
def send_static(path):
return send_from_directory('static', path)
@app.errorhandler(Exception)
def _handle_unexpected_error(e):
logging.getLogger(__name__).exception('Unhandled exception in request')
try:
pathlib.Path(PERSISTENT_BOTS_DIR).mkdir(parents=True, exist_ok=True)
err_path = os.path.join(PERSISTENT_BOTS_DIR, 'error.log')
with open(err_path, 'a', encoding='utf-8') as ef:
ef.write('\n==== Exception on request ====' + '\n')
ef.write(traceback.format_exc())
ef.write('\n')
except Exception:
logging.getLogger(__name__).exception('failed to write persistent error log')
try:
from werkzeug.exceptions import HTTPException
if isinstance(e, HTTPException):
return jsonify({'error': str(e)}), e.code
except Exception:
pass
return jsonify({'error': str(e)}), 500
# ==================== AUTHENTICATION ENDPOINTS ====================
@app.route('/api/auth/register', methods=['POST'])
def api_register():
"""Register a new user."""
data = request.get_json()
username = data.get('username')
email = data.get('email')
password = data.get('password')
user_dict, error = register_user(username, email, password)
if error:
return jsonify({'error': error}), 400
return jsonify({'user': user_dict, 'message': 'User registered successfully'}), 201
@app.route('/api/auth/login', methods=['POST'])
def api_login():
"""Login and get JWT tokens."""
data = request.get_json()
username = data.get('username')
password = data.get('password')
result, error = login_user(username, password)
if error:
return jsonify({'error': error}), 401
return jsonify(result), 200
@app.route('/api/auth/debug', methods=['GET'])
def api_debug_auth():
"""Debug endpoint to check authentication headers."""
headers = dict(request.headers)
auth_header = request.headers.get('Authorization', 'NOT_FOUND')
return jsonify({
'authorization_header': auth_header,
'all_headers': headers
}), 200
@app.route('/api/auth/me', methods=['GET'])
@jwt_required()
def api_get_current_user():
"""Get current user info from JWT token."""
user = get_current_user()
if not user:
return jsonify({'error': 'User not found'}), 404
return jsonify({'user': user.to_dict()}), 200
@app.route('/api/user/profile', methods=['GET'])
@jwt_required()
def api_get_user_profile():
"""Get current user's profile information."""
user = get_current_user()
if not user:
return jsonify({'error': 'User not found'}), 404
return jsonify({'user': user.to_dict()}), 200
@app.route('/api/user/avatar', methods=['GET'])
@jwt_required()
def api_get_user_avatar():
"""Get current user's avatar."""
user = get_current_user()
if not user:
return jsonify({'error': 'User not found'}), 404
return jsonify({'avatar': user.avatar or 'my_bot'}), 200
@app.route('/api/user/avatar', methods=['POST'])
@jwt_required()
def api_set_user_avatar():
"""Set current user's avatar."""
user = get_current_user()
if not user:
return jsonify({'error': 'User not found'}), 404
data = request.get_json()
avatar = data.get('avatar')
if not avatar:
return jsonify({'error': 'Avatar is required'}), 400
# Validate avatar (optional - list of allowed avatars)
allowed_avatars = ['my_bot', 'boss', 'ninja', 'warrior', 'wizard', 'knight', 'archer', 'alien']
if not avatar.startswith('custom_') and avatar not in allowed_avatars:
return jsonify({'error': 'Invalid avatar'}), 400
user.avatar = avatar
db.session.commit()
return jsonify({'success': True, 'avatar': user.avatar}), 200
@app.route('/api/user/avatar/upload', methods=['POST'])
@jwt_required()
def api_upload_avatar():
"""Upload a custom avatar image."""
user = get_current_user()
if not user:
return jsonify({'error': 'User not found'}), 404
# Check if file is present
if 'avatar' not in request.files:
return jsonify({'error': 'No file provided'}), 400