-
Notifications
You must be signed in to change notification settings - Fork 5
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 all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
384ec29
feat: Use stac bulk transactions
ividito 5846f51
Adjust transactions variable
ividito 68bd6fb
PR review feedback
ividito ffa335b
refactor submit stac transactions
smohiudd 8f3d093
use keycloak for transactionss POST
smohiudd 3a8c520
update stac transactions util
smohiudd f057378
fix tf transactions boolean
smohiudd d2687c3
add back success_file exception
smohiudd 03a6546
remove success_file duplication
smohiudd cf893e6
fix main.tf
smohiudd 8b60e81
add prefix to lambda trigger role
smohiudd bef1371
use transactions PUT instead of bulk items
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
129 changes: 129 additions & 0 deletions
129
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,129 @@ | ||
| 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: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, item: 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", | ||
| } | ||
| collection_id = item.get("collection") | ||
| item_id = item.get("id") | ||
|
|
||
| response = requests.put( | ||
| f"{self.base_url.rstrip('/')}/collections/{collection_id}/items/{item_id}", | ||
| headers=headers, | ||
| json=item | ||
| ) | ||
|
|
||
| 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. | ||
| """ | ||
|
|
||
|
|
||
| api = TransactionsApi.from_veda_auth_secret( | ||
| secret_id=cognito_app_secret, | ||
| base_url=ingest_url, | ||
| ) | ||
| try: | ||
| response = api.post_items( | ||
| item=event, | ||
| ) | ||
| logging.info("STAC Item PUT completed successfully.") | ||
| except RuntimeError as err: | ||
| logging.error("Error while performing {PUT}: %s", str(err)) | ||
| raise | ||
| return { | ||
| "statusCode": 200, | ||
| "body": json.dumps({ | ||
| "message": "PUT 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
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 |
|---|---|---|
|
|
@@ -103,8 +103,10 @@ module "sma-base" { | |
| ASSUME_ROLE_READ_ARN = var.assume_role_read_arn, | ||
| 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_TO_INVALIDATE = var.cloudfront_to_invalidate, | ||
| CLOUDFRONT_PATH_TO_INVALIDATE = var.cloudfront_path_to_invalidate, | ||
| TRANSACTIONS_ENDPOINT_ENABLED = var.transactions_endpoint_enabled==true ? "True" : null, | ||
|
Contributor
Author
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. Related fix that removes the need for the ternary here: NASA-IMPACT/self-managed-apache-airflow#18 |
||
| 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..airflowignorekeeps the DAG processor from parsing thegroupsandutilsfolders, so there's no performance loss by having these calls here.