Skip to content

Commit ea6272f

Browse files
committed
fix: post_telemetry() should not call _get_collection (private) and refactor get_telemetry_stats()
We add new method db.insert_many instead. Signed-off-by: Denys Fedoryshchenko <denys.f@collabora.com>
1 parent 8bb0500 commit ea6272f

2 files changed

Lines changed: 33 additions & 34 deletions

File tree

api/db.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,12 @@ async def create(self, obj):
245245
obj.id = res.inserted_id
246246
return obj
247247

248+
async def insert_many(self, model, documents):
249+
"""Create multiple documents in a collection."""
250+
col = self._get_collection(model)
251+
result = await col.insert_many(documents)
252+
return result.inserted_ids
253+
248254
async def _create_recursively(self, hierarchy: Hierarchy, parent: Node,
249255
cls, col):
250256
obj = parse_node_obj(hierarchy.node)

api/main.py

Lines changed: 27 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -978,7 +978,6 @@ async def post_telemetry(
978978
status_code=status.HTTP_400_BAD_REQUEST,
979979
detail="Events list cannot be empty",
980980
)
981-
col = db._get_collection(TelemetryEvent)
982981
docs = []
983982
for event in events:
984983
try:
@@ -991,8 +990,8 @@ async def post_telemetry(
991990
doc = obj.model_dump(by_alias=True)
992991
doc.pop('_id', None)
993992
docs.append(doc)
994-
result = await col.insert_many(docs)
995-
return {"inserted": len(result.inserted_ids)}
993+
inserted_ids = await db.insert_many(TelemetryEvent, docs)
994+
return {"inserted": len(inserted_ids)}
996995

997996

998997
@app.get('/telemetry', response_model=PageModel, tags=["telemetry"])
@@ -1086,31 +1085,25 @@ async def get_telemetry_stats(request: Request):
10861085
detail=f"Invalid group_by fields: {invalid}",
10871086
)
10881087

1089-
match_stage = {}
1090-
for key in ('kind', 'runtime', 'device_type', 'job_name',
1091-
'tree', 'branch', 'arch'):
1092-
val = query_params.pop(key, None)
1093-
if val:
1094-
match_stage[key] = val
1088+
match_stage = {
1089+
key: query_params.pop(key)
1090+
for key in ('kind', 'runtime', 'device_type', 'job_name',
1091+
'tree', 'branch', 'arch')
1092+
if query_params.get(key)
1093+
}
10951094

10961095
since = query_params.pop('since', None)
10971096
until = query_params.pop('until', None)
10981097
if since or until:
1099-
ts_filter = {}
1100-
if since:
1101-
ts_filter['$gte'] = datetime.fromisoformat(since)
1102-
if until:
1103-
ts_filter['$lte'] = datetime.fromisoformat(until)
1104-
match_stage['ts'] = ts_filter
1105-
1106-
group_id = {f: f'${f}' for f in group_by}
1098+
match_stage['ts'] = {
1099+
**({'$gte': datetime.fromisoformat(since)} if since else {}),
1100+
**({'$lte': datetime.fromisoformat(until)} if until else {}),
1101+
}
11071102

1108-
pipeline = []
1109-
if match_stage:
1110-
pipeline.append({'$match': match_stage})
1103+
pipeline = [{'$match': match_stage}] if match_stage else []
11111104
pipeline.append({
11121105
'$group': {
1113-
'_id': group_id,
1106+
'_id': {f: f'${f}' for f in group_by},
11141107
'total': {'$sum': 1},
11151108
'pass': {'$sum': {
11161109
'$cond': [{'$eq': ['$result', 'pass']}, 1, 0]
@@ -1133,19 +1126,19 @@ async def get_telemetry_stats(request: Request):
11331126

11341127
results = await db.aggregate(TelemetryEvent, pipeline)
11351128

1136-
# Flatten _id into top-level fields
1137-
output = []
1138-
for doc in results:
1139-
row = doc['_id'].copy()
1140-
row['total'] = doc['total']
1141-
row['pass'] = doc['pass']
1142-
row['fail'] = doc['fail']
1143-
row['incomplete'] = doc['incomplete']
1144-
row['skip'] = doc['skip']
1145-
row['infra_error'] = doc['infra_error']
1146-
output.append(row)
1147-
1148-
return JSONResponse(content=jsonable_encoder(output))
1129+
results = await db.aggregate(TelemetryEvent, pipeline)
1130+
return JSONResponse(content=jsonable_encoder([
1131+
{
1132+
**doc['_id'].copy(),
1133+
'total': doc['total'],
1134+
'pass': doc['pass'],
1135+
'fail': doc['fail'],
1136+
'incomplete': doc['incomplete'],
1137+
'skip': doc['skip'],
1138+
'infra_error': doc['infra_error'],
1139+
}
1140+
for doc in results
1141+
]))
11491142

11501143
# This is test value, can adjust based on expected query patterns and volumes.
11511144
ANOMALY_WINDOW_MAP = {

0 commit comments

Comments
 (0)