-
Notifications
You must be signed in to change notification settings - Fork 2
/
clkhash_service.py
419 lines (328 loc) · 12.2 KB
/
clkhash_service.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
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
import base64
import csv
import functools
import io
import itertools
import json
import os
import urllib.parse
import clkhash
import clkhash.validate_data
import connexion
import sqlalchemy
import sqlalchemy.exc
import sqlalchemy.orm
import sqlalchemy.sql
from flask import abort, jsonify, Response, request
import clkhash_worker
from database import Clk, db_session, ClkStatus, Project
CHUNK_SIZE = 1000
connexion_app = connexion.App(__name__)
flask_app = connexion_app.app
_POST_SUCCESS_RESPONSE = Response(status=201)
del _POST_SUCCESS_RESPONSE.headers['Content-Type']
_DELETE_SUCCESS_RESPONSE = Response(status=204)
del _DELETE_SUCCESS_RESPONSE.headers['Content-Type']
def _abort_with_msg(msg, status):
"""Abort with specified message and status code."""
response = jsonify(errMsg=msg)
response.status_code = status
abort(response)
def _abort_project_id_not_found(project_id):
"""Abort with message that the project was not found."""
_abort_with_msg("no such project '{}'".format(project_id), 404)
def _does_project_exist(project_id):
"""Returns True iff project with ID `project_id` exists."""
return db_session.query(
sqlalchemy.sql.exists().where(Project.id == project_id)
).scalar()
def _str_to_status_or_abort(status_str):
"""Convert string to ClkStatus; abort if input is unrecognised."""
try:
status_enum = ClkStatus(status_str)
except ValueError:
_abort_with_msg("'{}' is not a valid status".format(status_str), 400)
return status_enum
def _abort_if_project_not_found(function):
@functools.wraps(function)
def retval(project_id, *args, **kwargs):
if not _does_project_exist(project_id):
_abort_project_id_not_found(project_id)
else:
return function(project_id, *args, **kwargs)
return retval
def _intersperse(iterable, item):
iterator = iter(iterable) # Remember where we left off
try:
yield next(iterator)
except StopIteration:
return
for i in iterator:
yield item
yield i
def _query_statuses_to_enum_or_abort(query_statuses):
if query_statuses is None:
return None
status_strs = query_statuses.split(',')
status_enums = frozenset(map(_str_to_status_or_abort, status_strs))
return status_enums
def _make_clk_query(project_id, index_range_start, index_range_end, status):
query = db_session.query(Clk).filter(Clk.project_id == project_id)
if index_range_start is not None:
query = query.filter(Clk.index >= index_range_start)
if index_range_end is not None:
query = query.filter(Clk.index < index_range_end)
if status is not None:
query = query.filter(Clk.status.in_(status))
return query
def get_projects():
project_ids = db_session.query(Project.id)
return {
'projects': [id_ for id_, in project_ids]
}
def post_project(project_id, secret_key, body):
schema = body
# Check that the schema is valid.
try:
clkhash.schema.validate_schema_dict(schema)
except clkhash.schema.SchemaError as e:
msg, *_ = e.args
_abort_with_msg('invalid schema\n\n{}'.format(msg), 422)
# unquote secret key (will still be a base64 string)
b64_secret_key = urllib.parse.unquote(secret_key)
# Validate the base64:
try:
base64.b64decode(b64_secret_key, validate=True)
except ValueError:
msg = "'{}' is not a valid base64 string".format(b64_secret_key)
_abort_with_msg(msg, 422)
project = Project(
id=project_id,
schema=schema,
key=b64_secret_key)
db_session.add(project)
try:
db_session.flush()
except sqlalchemy.exc.IntegrityError:
db_session.rollback()
_abort_with_msg("Project '{}' already exists.".format(project_id), 409)
db_session.commit()
return _POST_SUCCESS_RESPONSE
def get_project(project_id):
project = db_session.query(Project).options(
sqlalchemy.orm.load_only(Project.schema)
).filter(
Project.id == project_id
).one_or_none()
if project is None:
_abort_project_id_not_found(project_id)
# We're purposefully not exposing the keys.
return {
'projectId': project_id,
'schema': project.schema
}
def delete_project(project_id):
delete_count = db_session.query(Project).filter(
Project.id == project_id
).delete()
if delete_count == 0:
_abort_project_id_not_found(project_id)
elif delete_count == 1:
# Delete clks also.
db_session.query(Clk).filter(Clk.project_id == project_id).delete()
db_session.commit()
return _DELETE_SUCCESS_RESPONSE
else:
# This should not happen.
raise ValueError(
'delete count is {}, when it is expected to be 0 or 1'
.format(delete_count))
def _first_last(iterable):
iterator = iter(iterable)
try:
first = last = next(iterator)
except StopIteration:
raise ValueError('empty iterable')
for last in iterator:
pass
return first, last
def _group_clks(clks):
for _, group in itertools.groupby(
enumerate(clks),
key=lambda x: (x[1].status, # Group by status and
x[1].index - x[0])): # by offset from start.
(_, first_clk), (_, last_clk) = _first_last(group)
yield {'status': first_clk.status.value,
'rangeStart': first_clk.index,
'rangeEnd': last_clk.index + 1}
def _stream_clk_groups(clk_groups):
yield '{"clksStatus":['
yield from _intersperse(map(json.dumps, clk_groups), ',')
yield ']}'
@_abort_if_project_not_found
def get_clks_status(project_id):
clks = db_session.query(Clk).filter(
Clk.project_id == project_id
).options(
sqlalchemy.orm.load_only(Clk.index, Clk.status)
).order_by(Clk.index)
clk_groups = _group_clks(clks)
clk_group_stream = _stream_clk_groups(clk_groups)
return Response(clk_group_stream, content_type='application/json')
@_abort_if_project_not_found
def post_pii(project_id, body, header, validate):
pii_table = body
pii_table = pii_table.decode(request.charset)
pii_table_stream = io.StringIO(pii_table)
reader = csv.reader(pii_table_stream)
if header != 'false':
try:
headings = next(reader)
except StopIteration:
_abort_with_msg('Header expected but not present.', 422)
if header == 'true':
project = db_session.query(Project).options(
sqlalchemy.orm.load_only(Project.schema)
).filter(
Project.id == project_id
).one_or_none()
if project is None:
# Project deleted in the meantime
_abort_project_id_not_found(project_id)
schema = clkhash.schema.from_json_dict(project.schema)
try:
clkhash.validate_data.validate_header(schema.fields, headings)
except clkhash.validate_data.FormatError as e:
msg, *_ = e.args
_abort_with_msg(msg, 422)
pii_table = tuple(reader)
records_num = len(pii_table)
# Atomically increase clk counter to reserve space for PII.
stmt = sqlalchemy.update(Project).where(
Project.id == project_id
).values(
clk_count=Project.clk_count + records_num
).returning(Project.clk_count)
result = db_session.execute(stmt)
db_session.commit()
result_scalar = result.scalar()
if result_scalar is None:
# Project deleted in the meantime
_abort_project_id_not_found(project_id)
start_index = result_scalar - records_num
clk_mappings = [
dict(project_id=project_id, index=i, status=ClkStatus.QUEUED, pii=row)
for i, row in enumerate(pii_table, start=start_index)]
try:
db_session.bulk_insert_mappings(Clk, clk_mappings)
except sqlalchemy.exc.IntegrityError:
# Project deleted in the meantime. All good, we'll just abort.
_abort_project_id_not_found(project_id)
# Queue up for the worker.
end_index = start_index + records_num
clk_indices = range(start_index, end_index)
for i in range(0, clk_indices.stop - clk_indices.start, CHUNK_SIZE):
this_indices = clk_indices[i:i + CHUNK_SIZE]
clkhash_worker.hash.delay(project_id,
validate,
this_indices.start,
this_indices.stop)
# Only commit once we know that the queueing succeeded.
db_session.commit()
return {
'dataIds': {
'rangeStart': start_index,
'rangeEnd': end_index
}
}, 202
def _clk_to_dict(clk):
return {
'index': clk.index,
'status': clk.status.value,
'errMsg': clk.err_msg,
'hash': base64.b64encode(clk.hash).decode('ascii')
if clk.hash is not None
else None
}
def _stream_clks(clks, page_limit):
clk_iter = iter(clks) # Remember where we left off
returned_clks = (clk_iter
if page_limit is None
else itertools.islice(clk_iter, page_limit))
yield '{"clks":['
# First clk is a special case since we need to intersperse ","
try:
clk = next(returned_clks)
except StopIteration:
pass
else:
last_index = clk.index
yield json.dumps(_clk_to_dict(clk))
for clk in returned_clks:
yield ','
last_index = clk.index
yield json.dumps(_clk_to_dict(clk))
yield '],"responseMetadata":'
try: # See if there are clks we haven't returned
next(clk_iter)
except StopIteration:
cursor = None
else:
cursor = str(last_index)
yield json.dumps({'nextCursor': cursor})
yield '}'
@_abort_if_project_not_found
def get_clks(project_id,
index_range_start=None,
index_range_end=None,
status=None,
page_limit=None,
cursor=None):
# Deal with cursor. Currently, it's just the index of the last
# returned element. However, its type is str so we can extend it
# in the future.
if cursor is not None:
try:
last_returned_index = int(cursor)
except ValueError:
_abort_with_msg('the cursor is not parseable', 400)
if ((index_range_start is not None
and last_returned_index < index_range_start)
or (index_range_end is not None
and index_range_end <= last_returned_index)):
# Impossible that the cursor comes from the last call.
_abort_with_msg('the cursor does not match the request', 422)
index_range_start = last_returned_index + 1
status_enums = _query_statuses_to_enum_or_abort(status)
query = _make_clk_query(project_id,
index_range_start, index_range_end,
status_enums)
query = query.order_by(Clk.index)
if page_limit is not None:
# Already ordered. Limit by `page_limit + 1` so we can check
# if there are leftover elements.
query = query.limit(page_limit + 1)
clks = query.options(
sqlalchemy.orm.load_only(
Clk.index, Clk.status, Clk.err_msg, Clk.hash))
return Response(_stream_clks(clks, page_limit),
content_type='application/json')
@_abort_if_project_not_found
def delete_clks(project_id,
index_range_start=None,
index_range_end=None,
status=None):
status_enums = _query_statuses_to_enum_or_abort(status)
query = _make_clk_query(project_id,
index_range_start, index_range_end,
status_enums)
query.delete(synchronize_session=False)
db_session.commit()
return _DELETE_SUCCESS_RESPONSE
@flask_app.teardown_appcontext
def shutdown_session(exception=None):
db_session.remove()
connexion_app.add_api('openapi.yaml')
if __name__ == '__main__':
connexion_app.run(port=int(os.environ.get('HTTP_PORT', 8080)),
debug=True)