-
Notifications
You must be signed in to change notification settings - Fork 4
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
Cache GIDD exports using S3 #628
Draft
thenav56
wants to merge
2
commits into
develop
Choose a base branch
from
feature/cache-export
base: develop
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.
Draft
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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 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,133 @@ | ||
import typing | ||
import hashlib | ||
import os | ||
import json | ||
import django_filters | ||
from django.db import models | ||
from django.core.serializers.json import DjangoJSONEncoder | ||
from django.core.files.base import ContentFile | ||
from rest_framework.request import Request | ||
from storages.backends.s3boto3 import S3Boto3Storage | ||
|
||
from helix.storages import get_external_storage | ||
|
||
from .models import StatusLog, ReleaseMetadata | ||
|
||
external_storage = get_external_storage() | ||
|
||
|
||
class ExternalStorageEnableAuthString: | ||
initial_value = getattr(external_storage, 'querystring_auth', None) | ||
|
||
def __enter__(self): | ||
if isinstance(external_storage, S3Boto3Storage): | ||
external_storage.querystring_auth = True | ||
|
||
def __exit__(self, exc_type, exc_value, exc_tb): | ||
if isinstance(external_storage, S3Boto3Storage): | ||
external_storage.querystring_auth = self.initial_value | ||
|
||
|
||
class GiddExportCache: | ||
|
||
FILE_DESTINATION_PREFIX = 'gidd-cache-export' | ||
|
||
class Key(models.TextChoices): | ||
# {StatusLog.id}/{export-name}/{export-hash} | ||
DISAGGREGATION_EXPORT = 'disaggregation-export' | ||
DISAGGREGATION_EXPORT_GEOJSON = 'disaggregation-export-geojson' | ||
DISASTER_EXPORT = 'disaster-export' | ||
DISPLACEMENT_EXPORT = 'displacement-export' | ||
|
||
@staticmethod | ||
def last_release_date() -> str: | ||
return StatusLog.last_release_date(strf_format='%Y-%m-%d-%H-%M-%S') or 'NA' | ||
|
||
@classmethod | ||
def generate_cache_key(cls, key: Key, data: dict, filename: str) -> typing.Tuple[bytes, str]: | ||
last_release_date = cls.last_release_date() | ||
|
||
hashable = json.dumps( | ||
data, | ||
sort_keys=True, | ||
cls=DjangoJSONEncoder, | ||
).encode('utf-8') | ||
|
||
hash_md5 = hashlib.md5() | ||
hash_md5.update(hashable) | ||
return hashable, os.path.join( | ||
cls.FILE_DESTINATION_PREFIX, | ||
'{}', | ||
key, | ||
'{}', | ||
filename, | ||
).format(last_release_date, hash_md5.hexdigest()) | ||
|
||
@classmethod | ||
def _get_or_create( | ||
cls, | ||
key: Key, | ||
data: dict, | ||
filename: str, | ||
export_generator: typing.Callable, | ||
) -> str: | ||
key_data, cache_key = cls.generate_cache_key(key, data, filename) | ||
if external_storage.exists(cache_key): | ||
return cache_key | ||
# Save file as well | ||
external_storage.save(cache_key, ContentFile(export_generator())) | ||
# Save metadata as well | ||
external_storage.save(f"{cache_key}.json", ContentFile(key_data)) | ||
return cache_key | ||
|
||
@classmethod | ||
def get_or_create( | ||
cls, | ||
filename: str, | ||
request: Request, | ||
filter_sets: typing.List[django_filters.FilterSet], | ||
key: Key, | ||
export_generator: typing.Callable, | ||
s3_parameters: dict, | ||
) -> str: | ||
release_meta_data = ReleaseMetadata.objects.last() | ||
if not release_meta_data: | ||
# TODO: | ||
raise Exception('Release metadata is not configured.') | ||
|
||
release_year = release_meta_data.release_year | ||
if ( | ||
request.query_params.get('release_environment').lower() == | ||
ReleaseMetadata.ReleaseEnvironment.PRE_RELEASE.name.lower() | ||
): | ||
release_year = release_meta_data.pre_release_year | ||
|
||
# Only look at fields used by filter_set | ||
clean_data = { | ||
k: v | ||
for k, v in request.query_params.items() | ||
if k in [ | ||
field | ||
for filter_set in filter_sets | ||
for field in filter_set.get_filters() | ||
] | ||
} | ||
# Remove client_id is exists | ||
clean_data.pop('cliend_id', None) | ||
# release_environment is replaced by release_year | ||
clean_data.pop('release_environment', None) | ||
data = { | ||
**clean_data, | ||
'release_year': release_year, | ||
} | ||
|
||
cache_key = cls._get_or_create(key, data, filename, export_generator) | ||
if isinstance(external_storage, S3Boto3Storage): | ||
with ExternalStorageEnableAuthString(): | ||
return external_storage.url( | ||
cache_key, | ||
parameters=s3_parameters, | ||
) | ||
return request.build_absolute_uri( | ||
external_storage.url(cache_key) | ||
) |
This file contains 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
Oops, something went wrong.
Oops, something went wrong.
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.
I also saw conflict-export in the gidd export.
We need to see if we also add them.
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.
Conflict-export is generated using filter by another export.