-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathfind_invalid_pointers.py
More file actions
82 lines (58 loc) · 2.33 KB
/
find_invalid_pointers.py
File metadata and controls
82 lines (58 loc) · 2.33 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
from datetime import datetime, timedelta, timezone
from typing import Any
import boto3
import fire
from nrlf.consumer.fhir.r4.model import DocumentReference
from nrlf.core.logger import logger
from nrlf.core.validators import DocumentReferenceValidator
dynamodb = boto3.client("dynamodb")
paginator = dynamodb.get_paginator("scan")
logger.setLevel("ERROR")
def _validate_document(document: str):
docref = DocumentReference.model_validate_json(document)
validator = DocumentReferenceValidator()
result = validator.validate(data=docref)
if not result.is_valid:
raise RuntimeError("Failed to validate document: " + str(result.issues))
def _find_invalid_pointers(table_name: str) -> dict[str, float | int]:
"""
Find pointers in the given table that are invalid.
Parameters:
- table_name: The name of the pointers table to use.
"""
print(f"Finding invalid pointers in table {table_name}....") # noqa
params: dict[str, Any] = {
"TableName": table_name,
"PaginationConfig": {"PageSize": 50},
}
invalid_pointers = []
total_scanned_count = 0
start_time = datetime.now(tz=timezone.utc)
for page in paginator.paginate(**params):
for item in page["Items"]:
pointer_id = item.get("id", {}).get("S")
document = item.get("document", {}).get("S", "")
try:
_validate_document(document)
except Exception as exc:
invalid_pointers.append((pointer_id, exc))
total_scanned_count += page["ScannedCount"]
if total_scanned_count % 1000 == 0:
print(".", end="", flush=True) # noqa
if total_scanned_count % 100000 == 0:
print( # noqa
f"scanned={total_scanned_count} invalid={len(invalid_pointers)}"
)
end_time = datetime.now(tz=timezone.utc)
print(" Done") # noqa
print("Writing invalid_pointers to file ./invalid_pointers.txt ...") # noqa
with open("invalid_pointers.txt", "w") as f:
for _id, err in invalid_pointers:
f.write(f"{_id}: {err}\n")
return {
"invalid_pointers": len(invalid_pointers),
"scanned_count": total_scanned_count,
"took-secs": timedelta.total_seconds(end_time - start_time),
}
if __name__ == "__main__":
fire.Fire(_find_invalid_pointers)