|
| 1 | +import logging |
| 2 | +import os |
| 3 | +from google.cloud import tasks_v2 |
| 4 | +from google.protobuf.timestamp_pb2 import Timestamp |
| 5 | + |
| 6 | + |
| 7 | +def create_refresh_materialized_view_task(): |
| 8 | + """ |
| 9 | + Asynchronously refresh a materialized view. |
| 10 | + Ensures deduplication by generating a unique task name. |
| 11 | +
|
| 12 | + Returns: |
| 13 | + dict: Response message and status code. |
| 14 | + """ |
| 15 | + from google.protobuf import timestamp_pb2 |
| 16 | + from datetime import datetime, timedelta |
| 17 | + |
| 18 | + try: |
| 19 | + logging.info("Creating materialized view refresh task.") |
| 20 | + now = datetime.now() |
| 21 | + |
| 22 | + # BOUNCE WINDOW: next :00 or :30 |
| 23 | + minute = now.minute |
| 24 | + if minute < 30: |
| 25 | + bucket_time = now.replace(minute=30, second=0, microsecond=0) |
| 26 | + else: |
| 27 | + bucket_time = now.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1) |
| 28 | + |
| 29 | + timestamp_str = bucket_time.strftime("%Y-%m-%d-%H-%M") |
| 30 | + task_name = f"refresh-materialized-view-{timestamp_str}" |
| 31 | + |
| 32 | + # Convert to protobuf timestamp |
| 33 | + proto_time = timestamp_pb2.Timestamp() |
| 34 | + proto_time.FromDatetime(bucket_time) |
| 35 | + |
| 36 | + # Cloud Tasks setup |
| 37 | + client = tasks_v2.CloudTasksClient() |
| 38 | + project = os.getenv("PROJECT_ID") |
| 39 | + location = os.getenv("LOCATION") |
| 40 | + queue = os.getenv("MATERIALIZED_VIEW_QUEUE") |
| 41 | + url = ( |
| 42 | + f"https://{os.getenv('GCP_REGION')}-" |
| 43 | + f"{os.getenv('PROJECT_ID')}.cloudfunctions.net/" |
| 44 | + f"tasks-executor-{os.getenv('ENVIRONMENT_NAME')}" |
| 45 | + ) |
| 46 | + |
| 47 | + task_name = client.task_path(project, location, queue, task_name) |
| 48 | + |
| 49 | + # Enqueue the task |
| 50 | + try: |
| 51 | + create_http_task_with_name( |
| 52 | + client=client, |
| 53 | + body=b"", |
| 54 | + url=url, |
| 55 | + project_id=project, |
| 56 | + gcp_region=location, |
| 57 | + queue_name=queue, |
| 58 | + task_name=task_name, |
| 59 | + task_time=proto_time, |
| 60 | + http_method=tasks_v2.HttpMethod.GET, |
| 61 | + ) |
| 62 | + logging.info(f"Scheduled refresh materialized view task for {timestamp_str}") |
| 63 | + return {"message": f"Refresh task for {timestamp_str} scheduled."}, 200 |
| 64 | + except Exception as e: |
| 65 | + if "ALREADY_EXISTS" in str(e): |
| 66 | + logging.info(f"Task already exists for {timestamp_str}, skipping.") |
| 67 | + |
| 68 | + except Exception as error: |
| 69 | + error_msg = f"Error enqueuing task: {error}" |
| 70 | + logging.error(error_msg) |
| 71 | + return {"error": error_msg}, 500 |
| 72 | + |
| 73 | + |
| 74 | +def create_http_task_with_name( |
| 75 | + client: "tasks_v2.CloudTasksClient", |
| 76 | + body: bytes, |
| 77 | + url: str, |
| 78 | + project_id: str, |
| 79 | + gcp_region: str, |
| 80 | + queue_name: str, |
| 81 | + task_name: str, |
| 82 | + task_time: Timestamp, |
| 83 | + http_method: "tasks_v2.HttpMethod", |
| 84 | +): |
| 85 | + """Creates a GCP Cloud Task.""" |
| 86 | + |
| 87 | + token = tasks_v2.OidcToken(service_account_email=os.getenv("SERVICE_ACCOUNT_EMAIL")) |
| 88 | + |
| 89 | + task = tasks_v2.Task( |
| 90 | + name=task_name, |
| 91 | + schedule_time=task_time, |
| 92 | + http_request=tasks_v2.HttpRequest( |
| 93 | + url=url, |
| 94 | + http_method=http_method, |
| 95 | + oidc_token=token, |
| 96 | + body=body, |
| 97 | + headers={"Content-Type": "application/json"}, |
| 98 | + ), |
| 99 | + ) |
| 100 | + client.create_task(parent=client.queue_path(project_id, gcp_region, queue_name), task=task) |
0 commit comments