-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathserver.py
179 lines (140 loc) · 5.03 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
179
import aiohttp
import os
from aiohttp import web
from uuid import uuid4
import asyncio
from bpmn_model import BpmnModel, UserFormMessage, get_model_for_instance
import aiohttp_cors
import db_connector
from functools import reduce
# Setup database
db_connector.setup_db()
routes = web.RouteTableDef()
# uuid4 = lambda: 2 # hardcoded for easy testing
models = {}
for file in os.listdir("models"):
if file.endswith(".bpmn"):
m = BpmnModel(file)
models[file] = m
async def run_as_server(app):
app["bpmn_models"] = models
log = db_connector.get_running_instances_log()
for l in log:
for key, data in l.items():
if data["model_path"] in app["bpmn_models"]:
instance = await app["bpmn_models"][data["model_path"]].create_instance(
key, {}
)
instance = await instance.run_from_log(data["events"])
asyncio.create_task(instance.run())
@routes.get("/model")
async def get_models(request):
data = [m.to_json() for m in models.values()]
return web.json_response({"status": "ok", "results": data})
@routes.get("/model/{model_name}")
async def get_model(request):
model_name = request.match_info.get("model_name")
return web.FileResponse(
path=os.path.join("models", app["bpmn_models"][model_name].model_path)
)
@routes.post("/model/{model_name}/instance")
async def handle_new_instance(request):
_id = str(uuid4())
model = request.match_info.get("model_name")
instance = await app["bpmn_models"][model].create_instance(_id, {})
asyncio.create_task(instance.run())
return web.json_response({"id": _id})
@routes.post("/instance/{instance_id}/task/{task_id}/form")
async def handle_form(request):
post = await request.json()
instance_id = request.match_info.get("instance_id")
task_id = request.match_info.get("task_id")
m = get_model_for_instance(instance_id)
m.instances[instance_id].in_queue.put_nowait(UserFormMessage(task_id, post))
return web.json_response({"status": "OK"})
@routes.get("/instance")
async def search_instance(request):
params = request.rel_url.query
queries = []
try:
strip_lower = lambda x: x.strip().lower()
check_colon = lambda x: x if ":" in x else f":{x}"
queries = list(
tuple(
map(
strip_lower,
check_colon(q).split(":"),
)
)
for q in params["q"].split(",")
)
except:
return web.json_response({"error": "invalid_query"}, status=400)
result_ids = []
for (att, value) in queries:
ids = []
for m in models.values():
for _id, instance in m.instances.items():
search_atts = []
if not att:
search_atts = list(instance.variables.keys())
else:
for key in instance.variables.keys():
if not att or att in key.lower():
search_atts.append(key)
search_atts = filter(
lambda x: isinstance(instance.variables[x], str), search_atts
)
for search_att in search_atts:
if search_att and value in instance.variables[search_att].lower():
# data.append(instance.to_json())
ids.append(_id)
result_ids.append(set(ids))
ids = reduce(lambda a, x: a.intersection(x), result_ids[:-1], result_ids[0])
data = []
for _id in ids:
data.append(get_model_for_instance(_id).instances[_id].to_json())
return web.json_response({"status": "ok", "results": data})
@routes.get("/instance/{instance_id}/task/{task_id}")
async def handle_task_info(request):
instance_id = request.match_info.get("instance_id")
task_id = request.match_info.get("task_id")
m = get_model_for_instance(instance_id)
if not m:
raise aiohttp.web.HTTPNotFound
instance = m.instances[instance_id]
task = instance.model.elements[task_id]
return web.json_response(task.get_info())
@routes.get("/instance/{instance_id}")
async def handle_instance_info(request):
instance_id = request.match_info.get("instance_id")
m = get_model_for_instance(instance_id)
if not m:
raise aiohttp.web.HTTPNotFound
instance = m.instances[instance_id].to_json()
return web.json_response(instance)
app = None
def run():
global app
app = web.Application()
app.on_startup.append(run_as_server)
app.add_routes(routes)
cors = aiohttp_cors.setup(
app,
defaults={
"*": aiohttp_cors.ResourceOptions(
allow_credentials=True,
expose_headers="*",
allow_headers="*",
allow_methods="*",
)
},
)
for route in list(app.router.routes()):
cors.add(route)
return app
async def serve():
return run()
if __name__ == "__main__":
app = run()
web.run_app(app, port=9000)