-
Notifications
You must be signed in to change notification settings - Fork 3
Submit STAC using transactions API #297
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ividito
wants to merge
12
commits into
dev
Choose a base branch
from
feat/transactions-api
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 8 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
6eb3d05
feat: Use stac bulk transactions
ividito cccda9e
Adjust transactions variable
ividito b793871
PR review feedback
ividito b9ccc58
refactor submit stac transactions
smohiudd c4a6e84
use keycloak for transactionss POST
smohiudd 7b0bad9
update stac transactions util
smohiudd 25ac28b
fix tf transactions boolean
smohiudd 5f40fa1
merge from dev
smohiudd b1b2314
add back success_file exception
smohiudd 2fa7e1e
remove success_file duplication
smohiudd e7df3ff
fix main.tf
smohiudd d8dae6e
add prefix to lambda trigger role
smohiudd File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
128 changes: 128 additions & 0 deletions
128
dags/veda_data_pipeline/utils/submit_stac_transactions.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,128 @@ | ||
import json | ||
import logging | ||
import requests | ||
from typing import List, TypedDict | ||
from dataclasses import dataclass | ||
|
||
import boto3 | ||
|
||
logging.basicConfig(level=logging.INFO) | ||
|
||
class Creds(TypedDict): | ||
access_token: str | ||
expires_in: int | ||
token_type: str | ||
scope: str | ||
|
||
class Secret(TypedDict): | ||
userinfo_url: str | ||
id: str | ||
secret: str | ||
auth_url: str | ||
token_url: str | ||
|
||
@dataclass | ||
class TransactionsApi: | ||
base_url: str | ||
token: str | ||
|
||
@classmethod | ||
def from_veda_auth_secret(cls, *, secret_id: str, base_url: str) -> "TransactionsApi": | ||
secret_details = cls._get_auth_service_details(secret_id) | ||
credentials = cls._get_app_credentials(**secret_details) | ||
return cls(token=credentials["access_token"], base_url=base_url) | ||
|
||
@staticmethod | ||
def _get_auth_service_details(secret_id: str) -> Secret: | ||
client = boto3.client("secretsmanager") | ||
response = client.get_secret_value(SecretId=secret_id) | ||
return json.loads(response["SecretString"]) | ||
|
||
@staticmethod | ||
def _get_app_credentials( | ||
userinfo_url: str, id: str, secret: str, auth_url: str, token_url: str, **kwargs | ||
) -> Creds: | ||
response = requests.post( | ||
token_url, | ||
headers={ | ||
"Content-Type": "application/x-www-form-urlencoded", | ||
"Accept": "application/json" | ||
}, | ||
data={ | ||
"client_id": id, | ||
"client_secret": secret, | ||
"grant_type": "client_credentials", | ||
"scope": "stac:item:create stac:collection:create stac:collection:update stac:item:update" | ||
}, | ||
) | ||
try: | ||
response.raise_for_status() | ||
except Exception as ex: | ||
print(response.text) | ||
raise RuntimeError(f"Error, {ex}") | ||
return response.json() | ||
|
||
|
||
def post_items(self, collection_id: str, items: List[dict]) -> dict: | ||
""" | ||
Perform a PUT request to update or create a STAC Item in the given collection. | ||
|
||
:param collection_id: The target collection ID. | ||
:param items: list of STAC items to be submitted. | ||
:return: The JSON response (as a dict) from the STAC API. | ||
:raises RuntimeError: If the response is not 200/201. | ||
""" | ||
headers = { | ||
"Authorization": f"Bearer {self.token}", | ||
"Content-Type": "application/json", | ||
} | ||
bulk_items = {"items": {item['id']: item for item in items}, "method": "upsert"} | ||
response = requests.post( | ||
f"{self.base_url.rstrip('/')}/collections/{collection_id}/bulk_items", | ||
headers=headers, | ||
json=bulk_items | ||
) | ||
|
||
if response.status_code not in (200, 201): | ||
logging.error("Failed PUT request: %s %s", response.status_code, response.text) | ||
raise RuntimeError(f"PUT request failed: {response.text}") | ||
|
||
return response.json() | ||
|
||
|
||
def submit_transactions_handler( | ||
event, | ||
cognito_app_secret=None, # unused, but maintains signature compatibility w/ ingest API | ||
ingest_url=None | ||
): | ||
""" | ||
Handler function that can be integrated in the same way as the existing `submission_handler`, | ||
but uses the TransactionsApi to perform a PUT request to STAC's Transactions endpoint. | ||
|
||
:param event: A dict containing the data needed for STAC item submission, | ||
including collection_id, item_id, and the STAC item body itself. | ||
:param context: (Optional) context object, for AWS Lambda or similar environments. | ||
:return: A dict representing the API response. | ||
""" | ||
|
||
collection_id = event[0].get("collection") | ||
api = TransactionsApi.from_veda_auth_secret( | ||
secret_id=cognito_app_secret, | ||
base_url=ingest_url, | ||
) | ||
try: | ||
response = api.post_items( | ||
collection_id=collection_id, | ||
items=event, | ||
) | ||
logging.info("STAC Bulk Item POST completed successfully.") | ||
except RuntimeError as err: | ||
logging.error("Error while performing POST: %s", str(err)) | ||
raise | ||
return { | ||
"statusCode": 200, | ||
"body": json.dumps({ | ||
"message": "POST request completed successfully", | ||
"response": response | ||
}) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -104,7 +104,9 @@ module "sma-base" { | |
ASSUME_ROLE_WRITE_ARN = var.assume_role_write_arn, | ||
SM2A_BASE_URL = module.sma-base.airflow_url, | ||
CLOUDFRONT_TO_INVALIDATE = var.cloudfront_to_invalidate | ||
CLOUDFRONT_PATH_TO_INVALIDATE = var.cloudfront_path_to_invalidate | ||
CLOUDFRONT_PATH_TO_INVALIDATE = var.cloudfront_path_to_invalidate, | ||
TRANSACTIONS_ENDPOINT_ENABLED = var.transactions_endpoint_enabled==true ? "True" : null | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't think tf bools are serialized in airflow in python. I used this hack but open if there's a better way. |
||
STAC_API_KEYCLOAK_CLIENT_SECRET=var.stac_api_keycloak_client_secret | ||
}, var.snapshot_bucket_name != "" ? module.rds_backups[0].rds_backup_environment : {} | ||
) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If we set deserialize_json=True, do you know if we still need to do:
in main.tf?
And maybe we refactor this file a bit so we call Variable.get in tasks rather than in the top level, since the docs seem to imply this is best practice: https://airflow.apache.org/docs/apache-airflow/2.8.4/best-practices.html#airflow-variables
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would love a refactor for this (we call the same set of
Variable.get("aws_dags_variables")
lines 16 times in our DAGs), but I think that's a different issue..airflowignore
keeps the DAG processor from parsing thegroups
andutils
folders, so there's no performance loss by having these calls here.