|
| 1 | +import boto3 |
| 2 | +import json |
| 3 | +import os |
| 4 | +import argparse |
| 5 | +import logging |
| 6 | +from pathlib import Path |
| 7 | +from typing import Any, Dict, List, Optional, Union, Generator |
| 8 | +from decimal import Decimal |
| 9 | + |
| 10 | + |
| 11 | +def map_dynamo_type(value: Any) -> Dict[str, Any]: |
| 12 | + if isinstance(value, str): |
| 13 | + return {"S": value} |
| 14 | + elif isinstance(value, bool): |
| 15 | + return {"BOOL": value} |
| 16 | + elif isinstance(value, (int, float, Decimal)): |
| 17 | + return {"N": str(value)} |
| 18 | + elif value is None: |
| 19 | + return {"NULL": True} |
| 20 | + elif isinstance(value, list): |
| 21 | + return {"L": [map_dynamo_type(item) for item in value]} |
| 22 | + elif isinstance(value, dict): |
| 23 | + return {"M": {k: map_dynamo_type(v) for k, v in value.items()}} |
| 24 | + else: |
| 25 | + logging.warning(f"Unsupported value type: {type(value)}", "Converting it to string") |
| 26 | + return {"S": str(value)} |
| 27 | + |
| 28 | + |
| 29 | +def load_json_lines(filepath: Union[str, Path]) -> Generator[Dict[str, Any], None, None]: |
| 30 | + with Path.open(filepath) as f: |
| 31 | + for line in f: |
| 32 | + if line.strip(): |
| 33 | + yield json.loads(line) |
| 34 | + |
| 35 | + |
| 36 | +def upload_to_s3( |
| 37 | + s3_client: Any, |
| 38 | + bucket: str, |
| 39 | + filepath: Union[str, Path], |
| 40 | + dry_run: bool = False |
| 41 | +) -> None: |
| 42 | + |
| 43 | + filename = os.path.basename(filepath) |
| 44 | + s3_key = f"manual-uploads/{filename}" |
| 45 | + |
| 46 | + if dry_run: |
| 47 | + print(f"[DRY RUN] Would upload {filepath} to s3://{bucket}/{s3_key}") |
| 48 | + return |
| 49 | + |
| 50 | + try: |
| 51 | + s3_client.upload_file(filepath, bucket, s3_key) |
| 52 | + print(f"Uploaded {filepath} to s3://{bucket}/{s3_key}") |
| 53 | + except Exception as e: |
| 54 | + print(f"Failed to upload {filepath}: {e}") |
| 55 | + |
| 56 | + |
| 57 | +def upload_to_dynamo( |
| 58 | + dynamo_client: Any, |
| 59 | + table_name: str, |
| 60 | + filepath: Union[str, Path], |
| 61 | +) -> None: |
| 62 | + uploaded_items = 0 |
| 63 | + for item in load_json_lines(filepath): |
| 64 | + try: |
| 65 | + dynamo_client.put_item( |
| 66 | + TableName=table_name, Item={key: map_dynamo_type(value) for key, value in item.items()} |
| 67 | + ) |
| 68 | + uploaded_items += 1 |
| 69 | + except Exception as e: |
| 70 | + partition_key = item.get("NHS_NUMBER", "Unknown") |
| 71 | + sort_key = item.get("ATTRIBUTE_TYPE", "Unknown") |
| 72 | + print(f"Failed to upload item (NHS_NUMBER: {partition_key}, ATTRIBUTE_TYPE: {sort_key}) from {filepath}: {e}") |
| 73 | + |
| 74 | + if uploaded_items > 0: |
| 75 | + print(f"Uploaded {uploaded_items} items from {filepath} to DynamoDB table {table_name}") |
| 76 | + |
| 77 | +def run_upload(args: Optional[List[str]] = None) -> None: |
| 78 | + parser = argparse.ArgumentParser() |
| 79 | + parser.add_argument("--env") |
| 80 | + parser.add_argument("--upload-s3", type=Path) |
| 81 | + parser.add_argument("--upload-dynamo", type=Path) |
| 82 | + parser.add_argument("--region", default="eu-west-2") |
| 83 | + parser.add_argument("--s3-bucket") |
| 84 | + parser.add_argument("--dynamo-table") |
| 85 | + parser.add_argument("--dry-run", action="store_true") |
| 86 | + |
| 87 | + if args is None: |
| 88 | + parsed_args = parser.parse_args() |
| 89 | + else: |
| 90 | + parsed_args = parser.parse_args(args) |
| 91 | + |
| 92 | + if not parsed_args.upload_s3 and not parsed_args.upload_dynamo: |
| 93 | + logging.warning("Neither '--upload-s3' nor '--upload-dynamo' flags specified. No upload actions will be performed.") |
| 94 | + if not parsed_args.s3_bucket: |
| 95 | + parsed_args.s3_bucket = f"eligibility-signposting-api-{parsed_args.env}-eli-rules" |
| 96 | + if not parsed_args.dynamo_table: |
| 97 | + parsed_args.dynamo_table = f"eligibility-signposting-api-{parsed_args.env}-eligibility_datastore" |
| 98 | + |
| 99 | + session = boto3.Session() |
| 100 | + s3 = session.client("s3", region_name=parsed_args.region) |
| 101 | + dynamo = session.client("dynamodb", region_name=parsed_args.region) |
| 102 | + |
| 103 | + if parsed_args.upload_s3: |
| 104 | + if parsed_args.upload_s3.is_dir(): |
| 105 | + files = parsed_args.upload_s3.glob("*.json") |
| 106 | + else: |
| 107 | + files = [parsed_args.upload_s3] |
| 108 | + |
| 109 | + for filepath in files: |
| 110 | + print(f"Uploading to S3 from {filepath}") |
| 111 | + upload_to_s3(s3, parsed_args.s3_bucket, str(filepath), parsed_args.dry_run) |
| 112 | + |
| 113 | + if parsed_args.upload_dynamo: |
| 114 | + if parsed_args.upload_dynamo.is_dir(): |
| 115 | + paths = parsed_args.upload_dynamo.glob("*.json") |
| 116 | + else: |
| 117 | + paths = [parsed_args.upload_dynamo] |
| 118 | + |
| 119 | + for filepath in paths: |
| 120 | + print(f"Uploading to DynamoDB from {filepath}") |
| 121 | + upload_to_dynamo(dynamo, parsed_args.dynamo_table, str(filepath)) |
| 122 | + |
| 123 | + |
| 124 | +if __name__ == "__main__": |
| 125 | + run_upload() |
0 commit comments