-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_handler.py
More file actions
98 lines (86 loc) · 2.59 KB
/
lambda_handler.py
File metadata and controls
98 lines (86 loc) · 2.59 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
import json
import time
import chess
import io
from src.eval import find_best_move
# Model is loaded at module level (cold start only)
# This ensures the model stays in memory between warm invocations
print("Lambda handler initialized - model loaded")
def handler(event, context):
"""
AWS Lambda handler for chess move API.
Expected event format:
{
"body": "{\"fen\": \"...\"}"
}
or for direct invocation:
{
"fen": "...",
}
"""
# CORS headers
cors_headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods': 'POST, OPTIONS'
}
# Handle preflight OPTIONS request
if event.get('httpMethod') == 'OPTIONS' or event.get('requestContext', {}).get('http', {}).get('method') == 'OPTIONS':
return {
'statusCode': 200,
'headers': cors_headers,
'body': ''
}
# Handle API Gateway format (has 'body' key) or direct invocation
if 'body' in event:
try:
body = json.loads(event['body']) if isinstance(event['body'], str) else event['body']
except json.JSONDecodeError:
return {
'statusCode': 400,
'headers': cors_headers,
'body': json.dumps({'error': 'Invalid JSON in request body'})
}
else:
body = event
# Validate required fields
if 'fen' not in body:
return {
'statusCode': 400,
'headers': cors_headers,
'body': json.dumps({'error': 'Missing fen in request body'})
}
fen = body['fen']
print(f"Processing move for fen:\n{fen}")
try:
start_time = time.perf_counter()
move = find_best_move(chess.Board(fen))
end_time = time.perf_counter()
time_taken = (end_time - start_time) * 1000
except Exception as e:
time_taken = (time.perf_counter() - start_time) * 1000
return {
'statusCode': 500,
'headers': cors_headers,
'body': json.dumps({
'move': None,
'exception': str(e),
})
}
return {
'statusCode': 200,
'headers': cors_headers,
'body': json.dumps({
'move': move.uci(),
})
}
def health_check_handler(event, context):
"""
Simple health check endpoint.
"""
return {
'statusCode': 200,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'running': True})
}