-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
178 lines (140 loc) · 5.09 KB
/
server.py
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
import time
import uuid
from multiprocessing import Process, Queue, Event, Manager
from flask import Flask, request, jsonify, Response
from simulation_manager import simulation_process
from flask_cors import CORS
from utils import update_api_key
import logging
app = Flask(__name__)
CORS(app)
# Helper function to handle internal errors
def handle_internal_error(e):
response = {
"internal_error": "An unexpected error occurred.",
"details": str(e)
}
return jsonify(response), 500
# Helper function to send commands to the simulation and wait for the correct response
def send_command(command, **kwargs):
request_id = str(uuid.uuid4())
command_queue.put({'command': command, 'id': request_id, **kwargs})
while True:
if request_id in response_dict:
response = response_dict.pop(request_id)
logging.debug(f"Send command response: {response}")
if 'error' in response:
raise Exception(response['error'])
return response['result']
@app.route('/api/status', methods=['GET'])
def get_status():
try:
status = send_command('status')
return jsonify(status), 200
except Exception as e:
return handle_internal_error(e)
@app.route('/api/start', methods=['GET'])
def start_sim():
try:
no_turns = request.args.get('no_turns', default=1, type=int)
# Generator function to yield the results
def generate():
request_id = str(uuid.uuid4())
command_queue.put({'command': 'run', 'id': request_id, 'no_turns': no_turns})
while True:
if request_id in response_dict:
response = response_dict.pop(request_id)
if 'error' in response:
yield f"ERROR: {response['error']}\n\n"
break
if response['result'] == 'Simulation run completed':
break
else:
yield f"{response['result']}\n\n"
time.sleep(0.1)
return Response(generate(), content_type='text/event-stream')
except Exception as e:
return handle_internal_error(e)
@app.route('/api/narration', methods=['GET'])
def get_narration():
try:
narration = send_command('narration')
return jsonify(narration), 200
except Exception as e:
return handle_internal_error(e)
@app.route('/api/last_narration', methods=['GET'])
def get_last_narration():
try:
last_narration = send_command('last_narration')
return jsonify(last_narration), 200
except Exception as e:
return handle_internal_error(e)
@app.route('/api/user_input', methods=['POST'])
def submit_player_input():
try:
data = request.json
user_input = data.get('input')
result = send_command('user_input', user_input=user_input)
return jsonify(result), 200
except Exception as e:
return handle_internal_error(e)
@app.route('/api/environments', methods=['GET'])
def get_environments():
try:
environments = send_command('environments')
return jsonify(environments), 200
except Exception as e:
return handle_internal_error(e)
@app.route('/api/entities', methods=['GET'])
def get_entities():
try:
entities = send_command('entities')
return jsonify(entities), 200
except Exception as e:
return handle_internal_error(e)
@app.route('/api/perspective', methods=['GET'])
def set_perspective():
try:
character = request.args.get('character', default=1, type=str)
if character == 1:
return jsonify({"msg": "Missing character in request"}), 200
resp = send_command('perspective', character_name=character)
return jsonify(resp), 200
except Exception as e:
return handle_internal_error(e)
@app.route('/api/reset', methods=['GET'])
def reset_simulation():
try:
result = send_command('reset')
return jsonify(result), 200
except Exception as e:
return handle_internal_error(e)
@app.route('/api/api_key', methods=['POST'])
def set_api_key():
try:
key = request.json.get('key')
update_api_key(key)
send_command('restart_process')
return jsonify({"msg": "api key updated"}), 200
except Exception as e:
return handle_internal_error(e)
# Error handling for 404 (Not Found)
@app.errorhandler(404)
def resource_not_found(e):
return jsonify(error="Resource not found"), 404
# Run the server
if __name__ == '__main__':
global command_queue, response_dict, shutdown_event
# Command Queue
command_queue = Queue()
shutdown_event = Event()
# Create a manager for shared data structures
manager = Manager()
response_dict = manager.dict() # Shared dictionary to store responses
simulation_proc = Process(target=simulation_process, args=(command_queue, response_dict, shutdown_event))
simulation_proc.start()
try:
app.run(debug=False, host='0.0.0.0', port=5500)
finally:
shutdown_event.set()
simulation_proc.join()