|
8 | 8 | from fastapi import FastAPI |
9 | 9 | from pydantic import TypeAdapter |
10 | 10 | from servicelib.logging_utils import log_context |
| 11 | +from tenacity import wait_exponential |
11 | 12 | from tenacity.asyncio import AsyncRetrying |
12 | 13 | from tenacity.before_sleep import before_sleep_log |
13 | 14 | from tenacity.wait import wait_fixed |
@@ -44,14 +45,29 @@ async def _on_startup() -> None: |
44 | 45 | assert client # nosec |
45 | 46 | app.state.s3_client = client |
46 | 47 |
|
47 | | - with log_context(_logger, logging.DEBUG, msg="setup.s3_bucket.cleanup_ctx"): |
| 48 | + async for attempt in AsyncRetrying( |
| 49 | + wait=wait_exponential(min=1), # 1, 2, 4, 8, ... |
| 50 | + before_sleep=before_sleep_log(_logger, logging.WARNING), |
| 51 | + reraise=True, |
| 52 | + ): |
48 | 53 | assert settings.STORAGE_S3 # nosec |
49 | | - await client.create_bucket( |
50 | | - bucket=settings.STORAGE_S3.S3_BUCKET_NAME, |
51 | | - region=TypeAdapter( |
52 | | - BucketLocationConstraintType | Literal["us-east-1"] |
53 | | - ).validate_python(settings.STORAGE_S3.S3_REGION), |
54 | | - ) |
| 54 | + with attempt, log_context( |
| 55 | + _logger, logging.DEBUG, msg="setup.s3_bucket.cleanup_ctx" |
| 56 | + ): |
| 57 | + if await client.bucket_exists( |
| 58 | + bucket=settings.STORAGE_S3.S3_BUCKET_NAME |
| 59 | + ): |
| 60 | + _logger.info( |
| 61 | + "S3 bucket %s exists already, skipping creation", |
| 62 | + settings.STORAGE_S3.S3_BUCKET_NAME, |
| 63 | + ) |
| 64 | + break |
| 65 | + await client.create_bucket( |
| 66 | + bucket=settings.STORAGE_S3.S3_BUCKET_NAME, |
| 67 | + region=TypeAdapter( |
| 68 | + BucketLocationConstraintType | Literal["us-east-1"] |
| 69 | + ).validate_python(settings.STORAGE_S3.S3_REGION), |
| 70 | + ) |
55 | 71 |
|
56 | 72 | async def _on_shutdown() -> None: |
57 | 73 | if app.state.s3_client: |
|
0 commit comments