Skip to content

Commit 46d5474

Browse files
committed
updated code
1 parent 85c0ea5 commit 46d5474

File tree

3 files changed

+63
-41
lines changed

3 files changed

+63
-41
lines changed
Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,26 @@
1-
fastapi==0.110.0
2-
uvicorn==0.29.0
3-
sqlalchemy==2.0.23
4-
geoalchemy2==0.14.7
5-
python-dotenv~=1.0.0
6-
requests
7-
psycopg2-binary
1+
# Common packages
2+
functions-framework==3.*
83
google-cloud-logging
9-
aiohttp
4+
psycopg2-binary==2.9.6
5+
aiohttp~=3.10.5
6+
asyncio~=3.4.3
7+
urllib3~=2.2.2
8+
requests~=2.32.3
9+
attrs~=23.1.0
10+
pluggy~=1.3.0
11+
certifi~=2024.7.4
12+
fastapi>=0.68.0
13+
uvicorn>=0.15.0
14+
functions-framework>=3.0.0
15+
asgiref>=3.4.1
16+
google-cloud-tasks>=2.11.0
17+
18+
# SQL Alchemy and Geo Alchemy
19+
SQLAlchemy==2.0.23
20+
geoalchemy2==0.14.7
21+
22+
# Google specific packages for this function
23+
cloudevents~=1.10.1
24+
25+
# Configuration
26+
python-dotenv==1.0.0

functions-python/refresh_materialized_view/src/main.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,30 @@
11
import logging
22
import os
3-
import functions_framework
4-
from flask import Request, jsonify
3+
import json
54
from google.cloud import tasks_v2
65
from datetime import datetime
6+
import functions_framework
77
from shared.helpers.logger import init_logger
88
from shared.database.database import with_db_session
99

1010
init_logger()
1111

1212

1313
@functions_framework.http
14-
def refresh_materialized_view_function(request: Request):
14+
def refresh_materialized_view_function(request):
1515
"""
16-
Enqueues a Cloud Task to refresh a materialized view asynchronously.
16+
Enqueues a Cloud Task to asynchronously refresh a materialized view.
17+
Ensures deduplication by generating a unique task name.
1718
1819
Returns:
19-
tuple: (response_message, status_code)
20+
dict: Response message and status code.
2021
"""
2122
try:
2223
logging.info("Starting materialized view refresh function.")
2324

2425
# Generate deduplication key based on current timestamp
2526
timestamp = datetime.now().strftime("%Y-%m-%d-%H-%M")
26-
task_name = f"refresh-feed-search-{timestamp}"
27+
task_name = f"refresh-materialized-view-{timestamp}"
2728

2829
# Cloud Tasks client setup
2930
client = tasks_v2.CloudTasksClient()
@@ -43,7 +44,7 @@ def refresh_materialized_view_function(request: Request):
4344
"http_method": tasks_v2.HttpMethod.POST,
4445
"url": url,
4546
"headers": {"Content-Type": "application/json"},
46-
"body": jsonify(payload).data,
47+
"body": json.dumps(payload).encode(),
4748
},
4849
}
4950

@@ -60,19 +61,18 @@ def refresh_materialized_view_function(request: Request):
6061

6162

6263
@with_db_session
63-
@functions_framework.http
64-
def refresh_materialized_view_task(request: Request, db_session):
64+
def refresh_materialized_view_task(request, db_session):
6565
"""
6666
Refreshes a materialized view using the CONCURRENTLY command to avoid
6767
table locks. This function is triggered by a Cloud Task.
6868
6969
Returns:
70-
tuple: (response_message, status_code)
70+
dict: Response message and status code.
7171
"""
7272
try:
7373
logging.info("Starting materialized view refresh task.")
7474

75-
data = request.get_json()
75+
data = request.json()
7676
view_name = data.get("view_name")
7777
deduplication_key = data.get("deduplication_key")
7878

@@ -111,7 +111,7 @@ def refresh_materialized_view(db_session, view_name):
111111
bool: True if refresh was successful, False otherwise.
112112
"""
113113
try:
114-
db_session.execute(f"REFRESH MATERIALIZED VIEW CONCURRENTLY {view_name};")
114+
db_session.execute(f"REFRESH MATERIALIZED VIEW CONCURRENTLY {view_name}")
115115
db_session.commit()
116116
return True
117117
except Exception as error:

infra/functions-python/main.tf

Lines changed: 26 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1503,16 +1503,16 @@ resource "google_project_iam_member" "service_account_workflow_act_as_binding" {
15031503
}
15041504

15051505
# 15. functions/refresh_materialized_view
1506+
# Cloud Function for refresh_materialized_view
15061507
resource "google_cloudfunctions2_function" "refresh_materialized_view" {
1507-
name = local.function_refresh_materialized_view_config.name
1508-
description = local.function_refresh_materialized_view_config.description
1508+
name = "refresh-materialized-view-${var.environment}"
1509+
description = "Function to refresh materialized views asynchronously."
15091510
location = var.gcp_region
15101511
depends_on = [google_secret_manager_secret_iam_member.secret_iam_member]
1511-
project = var.project_id
15121512

15131513
build_config {
15141514
runtime = var.python_runtime
1515-
entry_point = local.function_refresh_materialized_view_config.entry_point
1515+
entry_point = "refresh_materialized_view_function"
15161516
source {
15171517
storage_source {
15181518
bucket = google_storage_bucket.functions_bucket.name
@@ -1522,29 +1522,34 @@ resource "google_cloudfunctions2_function" "refresh_materialized_view" {
15221522
}
15231523

15241524
service_config {
1525-
available_memory = local.function_refresh_materialized_view_config.memory
1526-
timeout_seconds = local.function_refresh_materialized_view_config.timeout
1527-
available_cpu = local.function_refresh_materialized_view_config.available_cpu
1528-
max_instance_request_concurrency = local.function_refresh_materialized_view_config.max_instance_request_concurrency
1529-
max_instance_count = local.function_refresh_materialized_view_config.max_instance_count
1530-
min_instance_count = local.function_refresh_materialized_view_config.min_instance_count
1525+
environment_variables = {
1526+
PROJECT_ID = var.project_id
1527+
QUEUE_NAME = google_cloud_tasks_queue.refresh_materialized_view_queue.name
1528+
LOCATION = var.gcp_region
1529+
FUNCTION_URL = "https://${google_cloudfunctions2_function.refresh_materialized_view.name}.cloudfunctions.net"
1530+
}
1531+
available_memory = "512Mi"
1532+
timeout_seconds = 60
1533+
available_cpu = 1
1534+
max_instance_request_concurrency = 10
1535+
max_instance_count = 5
1536+
min_instance_count = 0
15311537
service_account_email = google_service_account.functions_service_account.email
1532-
ingress_settings = local.function_refresh_materialized_view_config.ingress_settings
1538+
ingress_settings = "ALLOW_ALL"
15331539
vpc_connector = data.google_vpc_access_connector.vpc_connector.id
15341540
vpc_connector_egress_settings = "PRIVATE_RANGES_ONLY"
1535-
1536-
dynamic "secret_environment_variables" {
1537-
for_each = local.function_refresh_materialized_view_config.secret_environment_variables
1538-
content {
1539-
key = secret_environment_variables.value["key"]
1540-
project_id = var.project_id
1541-
secret = "${upper(var.environment)}_${secret_environment_variables.value["key"]}"
1542-
version = "latest"
1543-
}
1544-
}
15451541
}
15461542
}
15471543

1544+
# IAM entry for invoking the refresh_materialized_view function
1545+
resource "google_cloudfunctions2_function_iam_member" "refresh_materialized_view_invoker" {
1546+
project = var.project_id
1547+
location = var.gcp_region
1548+
cloud_function = google_cloudfunctions2_function.refresh_materialized_view.name
1549+
role = "roles/cloudfunctions.invoker"
1550+
member = "serviceAccount:${google_service_account.functions_service_account.email}"
1551+
}
1552+
15481553
# Task queue to invoke refresh_materialized_view function
15491554
resource "google_cloud_tasks_queue" "refresh_materialized_view_queue" {
15501555
name = "refresh-materialized-view-queue-${var.environment}"

0 commit comments

Comments
 (0)