cdk-s3-pull-sync 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.jsii +10325 -0
- package/API.md +466 -0
- package/CHANGELOG.md +8 -0
- package/LICENSE +202 -0
- package/README.md +102 -2
- package/lambda/s3_pull_sync/__init__.py +0 -0
- package/lambda/s3_pull_sync/clients.py +51 -0
- package/lambda/s3_pull_sync/config.py +37 -0
- package/lambda/s3_pull_sync/copy_worker.py +46 -0
- package/lambda/s3_pull_sync/delete_worker.py +22 -0
- package/lambda/s3_pull_sync/diff.py +30 -0
- package/lambda/s3_pull_sync/errors.py +6 -0
- package/lambda/s3_pull_sync/listing.py +117 -0
- package/lambda/s3_pull_sync/manifest.py +41 -0
- package/lambda/s3_pull_sync/plan.py +50 -0
- package/lambda/s3_pull_sync/report.py +152 -0
- package/lib/index.d.ts +1 -0
- package/lib/index.js +18 -0
- package/lib/s3-pull-sync.d.ts +61 -0
- package/lib/s3-pull-sync.js +186 -0
- package/lib/state-machine.d.ts +15 -0
- package/lib/state-machine.js +179 -0
- package/package.json +142 -4
package/README.md
CHANGED
|
@@ -1,3 +1,103 @@
|
|
|
1
|
-
#
|
|
1
|
+
# cdk-s3-pull-sync
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Scheduled serverless incremental **pull** of objects from an S3 bucket you can only read with access keys into a bucket in your own AWS account.
|
|
4
|
+
|
|
5
|
+
Typical case: a vendor gives you a bucket name plus read-only IAM user keys. You cannot ask them to set up replication, roles, event notifications or inventory.
|
|
6
|
+
|
|
7
|
+
## When NOT to use this
|
|
8
|
+
|
|
9
|
+
| You have | Use instead |
|
|
10
|
+
|---|---|
|
|
11
|
+
| Control of the source bucket (or its owner will configure it) | [S3 Replication](https://docs.aws.amazon.com/AmazonS3/latest/userguide/replication.html), cross-account supported |
|
|
12
|
+
| A one-time copy of existing objects with replication configured | S3 Batch Replication |
|
|
13
|
+
| Large migrations, on-prem or other clouds with an agent | AWS DataSync |
|
|
14
|
+
| A long-running host and no need for serverless | `rclone sync` or `aws s3 sync` |
|
|
15
|
+
|
|
16
|
+
## Usage
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { S3PullSync } from 'cdk-s3-pull-sync';
|
|
20
|
+
|
|
21
|
+
const vendorSecret = secretsmanager.Secret.fromSecretNameV2(this, 'VendorKeys', 'vendor/s3-read');
|
|
22
|
+
// secret JSON: {"accessKeyId": "...", "secretAccessKey": "..."}
|
|
23
|
+
|
|
24
|
+
const sync = new S3PullSync(this, 'VendorSync', {
|
|
25
|
+
source: { bucket: 'vendor-exports', prefix: 'daily/', credentials: vendorSecret, region: 'eu-west-1' },
|
|
26
|
+
target: { bucket: myBucket, prefix: 'vendor/' },
|
|
27
|
+
schedule: events.Schedule.rate(Duration.hours(1)), // default
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
sync.alertTopic.addSubscription(new subs.EmailSubscription('data-team@example.com'));
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Python:
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from cdk_s3_pull_sync import S3PullSync, PullSyncSource, PullSyncTarget
|
|
37
|
+
|
|
38
|
+
S3PullSync(self, "VendorSync",
|
|
39
|
+
source=PullSyncSource(bucket="vendor-exports", prefix="daily/", credentials=vendor_secret),
|
|
40
|
+
target=PullSyncTarget(bucket=my_bucket, prefix="vendor/"),
|
|
41
|
+
)
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Set `scheduleEnabled: false` to create no schedule and start executions yourself. Passing `schedule` together with `scheduleEnabled: false` throws an error.
|
|
45
|
+
|
|
46
|
+
S3-compatible sources (Cloudflare R2, Wasabi, MinIO, Backblaze B2) work through `endpointUrl`. This is best effort: it is tested on AWS S3 only.
|
|
47
|
+
|
|
48
|
+
Tip: end prefixes with `/`. A prefix `daily` also matches `daily2/`.
|
|
49
|
+
|
|
50
|
+
## Requirements
|
|
51
|
+
|
|
52
|
+
- The vendor keys need `s3:ListBucket` on the source bucket (for the source prefix) plus `s3:GetObject` on the objects under it.
|
|
53
|
+
- Set `region` when the source bucket is in a different region than your stack.
|
|
54
|
+
- If you pass an imported secret or alert topic encrypted with a customer-managed KMS key, grant the construct's functions (or the topic's publishers) use of that key yourself.
|
|
55
|
+
- Add an `AbortIncompleteMultipartUpload` lifecycle rule to the target bucket. Large objects are copied with multipart uploads and an interrupted Lambda leaves parts behind that you pay for.
|
|
56
|
+
|
|
57
|
+
## How it works
|
|
58
|
+
|
|
59
|
+
Each run:
|
|
60
|
+
|
|
61
|
+
1. Lists the source and target prefixes once (in parallel) and merge-joins them by relative key. A folder marker object whose key equals the prefix is ignored.
|
|
62
|
+
2. Plans a copy when a key is missing in the target, the sizes differ or the source `LastModified` is newer than the target's. With `deleteExtraneous`, plans a delete for target-only keys.
|
|
63
|
+
3. Copies in parallel batches through a Step Functions Distributed Map. Manifests and results live in a construct-owned work bucket (expired after 14 days).
|
|
64
|
+
4. Writes `runs/<execution>/summary.json` and publishes per-key failures to the alert topic.
|
|
65
|
+
|
|
66
|
+
A run that finds nothing to do (`NothingToDo`) or skips because another execution is still running (`Skipped`) ends early and writes no `summary.json`.
|
|
67
|
+
|
|
68
|
+
If a whole copy or delete batch fails after retries (for example a Lambda crash or timeout), every key in that batch is reported as a per-key failure. The other batches keep syncing and the run still completes.
|
|
69
|
+
|
|
70
|
+
No state is stored between runs. A key that fails to copy still differs from the target, so the next run retries it automatically.
|
|
71
|
+
|
|
72
|
+
## Deletes
|
|
73
|
+
|
|
74
|
+
`deleteExtraneous` is off by default. **There is no safety guard: if the source lists successfully as empty, every target key under the target prefix is deleted.** A listing error (expired keys, access denied) always fails the run before anything is deleted.
|
|
75
|
+
|
|
76
|
+
## Alerts
|
|
77
|
+
|
|
78
|
+
- Per-key copy or delete failures, including every key of a batch whose worker failed after retries: one SNS message per run with counts, up to 20 failed keys and a link to the full list in the work bucket. The execution still succeeds.
|
|
79
|
+
- Infrastructure failures (listing errors in Plan, Report errors, Distributed Map failures): the execution fails and a CloudWatch alarm on `ExecutionsFailed` notifies the same topic.
|
|
80
|
+
|
|
81
|
+
## Cost
|
|
82
|
+
|
|
83
|
+
Every run lists both prefixes: about $0.005 per million objects per bucket. In the cross-account case the source owner pays for source LIST requests unless Requester Pays is enabled.
|
|
84
|
+
|
|
85
|
+
## Limits
|
|
86
|
+
|
|
87
|
+
- Plan lists both sides in parallel within one 15-minute Lambda invocation. The practical ceiling is a few million keys in total per run, depending on key length and endpoint latency. Measure on your bucket. For larger buckets shard by prefix with one construct per prefix.
|
|
88
|
+
- Single objects larger than about 40 GB may not copy within one Lambda invocation.
|
|
89
|
+
- One-way only. Versions, tags and ACLs are not synced. Content headers and user metadata are.
|
|
90
|
+
- Changes made directly to target objects are not detected when the size is unchanged.
|
|
91
|
+
- A source overwrite with an unchanged size within the same second as the previous copy is not detected, because `LastModified` has one-second precision. On S3-compatible endpoints source clock skew can hide changes the same way.
|
|
92
|
+
|
|
93
|
+
## Development
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
npx projen build # compile, jsii, jest + pytest
|
|
97
|
+
integ/run.sh # deploys to your AWS account and runs an end-to-end check
|
|
98
|
+
integ/run.sh destroy
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## License
|
|
102
|
+
|
|
103
|
+
Apache-2.0
|
|
File without changes
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from functools import cache
|
|
3
|
+
|
|
4
|
+
import boto3
|
|
5
|
+
from botocore.config import Config as BotoConfig
|
|
6
|
+
|
|
7
|
+
from .config import Config
|
|
8
|
+
|
|
9
|
+
SECRET_FORMAT_ERROR = "Source credentials secret must be JSON with accessKeyId and secretAccessKey"
|
|
10
|
+
|
|
11
|
+
_RETRIES = BotoConfig(retries={"max_attempts": 10, "mode": "adaptive"})
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@cache
|
|
15
|
+
def config() -> Config:
|
|
16
|
+
return Config.from_env()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@cache
|
|
20
|
+
def source_s3():
|
|
21
|
+
cfg = config()
|
|
22
|
+
secret_string = boto3.client("secretsmanager").get_secret_value(SecretId=cfg.source_secret_arn)["SecretString"]
|
|
23
|
+
# Never chain the original error: a JSON or key error could carry secret contents into logs.
|
|
24
|
+
try:
|
|
25
|
+
secret = json.loads(secret_string)
|
|
26
|
+
access_key_id, secret_access_key = secret["accessKeyId"], secret["secretAccessKey"]
|
|
27
|
+
except (ValueError, TypeError, KeyError):
|
|
28
|
+
raise ValueError(SECRET_FORMAT_ERROR) from None
|
|
29
|
+
return boto3.client(
|
|
30
|
+
"s3",
|
|
31
|
+
aws_access_key_id=access_key_id,
|
|
32
|
+
aws_secret_access_key=secret_access_key,
|
|
33
|
+
region_name=cfg.source_region,
|
|
34
|
+
endpoint_url=cfg.source_endpoint_url,
|
|
35
|
+
config=_RETRIES,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@cache
|
|
40
|
+
def target_s3():
|
|
41
|
+
return boto3.client("s3", config=_RETRIES)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@cache
|
|
45
|
+
def sns():
|
|
46
|
+
return boto3.client("sns")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def reset() -> None:
|
|
50
|
+
for factory in (config, source_s3, target_s3, sns):
|
|
51
|
+
factory.cache_clear()
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass(frozen=True)
|
|
8
|
+
class Config:
|
|
9
|
+
source_bucket: str
|
|
10
|
+
source_prefix: str
|
|
11
|
+
source_secret_arn: str
|
|
12
|
+
source_region: str | None
|
|
13
|
+
source_endpoint_url: str | None
|
|
14
|
+
target_bucket: str
|
|
15
|
+
target_prefix: str
|
|
16
|
+
work_bucket: str
|
|
17
|
+
delete_extraneous: bool
|
|
18
|
+
alert_topic_arn: str
|
|
19
|
+
|
|
20
|
+
@classmethod
|
|
21
|
+
def from_env(cls) -> Config:
|
|
22
|
+
env = os.environ
|
|
23
|
+
return cls(
|
|
24
|
+
source_bucket=env["SOURCE_BUCKET"],
|
|
25
|
+
source_prefix=env.get("SOURCE_PREFIX", ""),
|
|
26
|
+
source_secret_arn=env["SOURCE_SECRET_ARN"],
|
|
27
|
+
source_region=env.get("SOURCE_REGION") or None,
|
|
28
|
+
source_endpoint_url=env.get("SOURCE_ENDPOINT_URL") or None,
|
|
29
|
+
target_bucket=env["TARGET_BUCKET"],
|
|
30
|
+
target_prefix=env.get("TARGET_PREFIX", ""),
|
|
31
|
+
work_bucket=env["WORK_BUCKET"],
|
|
32
|
+
delete_extraneous=env.get("DELETE_EXTRANEOUS", "false") == "true",
|
|
33
|
+
alert_topic_arn=env["ALERT_TOPIC_ARN"],
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
def target_key(self, source_key: str) -> str:
|
|
37
|
+
return self.target_prefix + source_key[len(self.source_prefix):]
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from contextlib import closing
|
|
3
|
+
|
|
4
|
+
from . import clients
|
|
5
|
+
from .config import Config
|
|
6
|
+
from .errors import truncate_error
|
|
7
|
+
|
|
8
|
+
logger = logging.getLogger()
|
|
9
|
+
|
|
10
|
+
SAFETY_MS = 60_000
|
|
11
|
+
PRESERVED_HEADERS = (
|
|
12
|
+
"ContentType",
|
|
13
|
+
"ContentEncoding",
|
|
14
|
+
"ContentDisposition",
|
|
15
|
+
"ContentLanguage",
|
|
16
|
+
"CacheControl",
|
|
17
|
+
"Expires",
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def handler(event, context):
|
|
22
|
+
cfg = clients.config()
|
|
23
|
+
copied = deferred = 0
|
|
24
|
+
failures = []
|
|
25
|
+
for item in event["Items"]:
|
|
26
|
+
key = item["key"]
|
|
27
|
+
if context.get_remaining_time_in_millis() < SAFETY_MS:
|
|
28
|
+
deferred += 1
|
|
29
|
+
continue
|
|
30
|
+
try:
|
|
31
|
+
copy_object(cfg, key)
|
|
32
|
+
except Exception as error: # per-key failures are data, retried next run
|
|
33
|
+
logger.exception("Failed to copy %s", key)
|
|
34
|
+
failures.append({"key": key, "error": truncate_error(f"{type(error).__name__}: {error}")})
|
|
35
|
+
else:
|
|
36
|
+
copied += 1
|
|
37
|
+
return {"copied": copied, "deferred": deferred, "failures": failures}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def copy_object(cfg: Config, key: str) -> None:
|
|
41
|
+
response = clients.source_s3().get_object(Bucket=cfg.source_bucket, Key=key)
|
|
42
|
+
extra_args = {name: response[name] for name in PRESERVED_HEADERS if response.get(name)}
|
|
43
|
+
if response.get("Metadata"):
|
|
44
|
+
extra_args["Metadata"] = response["Metadata"]
|
|
45
|
+
with closing(response["Body"]) as body:
|
|
46
|
+
clients.target_s3().upload_fileobj(body, cfg.target_bucket, cfg.target_key(key), ExtraArgs=extra_args)
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
from . import clients
|
|
4
|
+
from .errors import truncate_error
|
|
5
|
+
|
|
6
|
+
logger = logging.getLogger()
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def handler(event, context):
|
|
10
|
+
cfg = clients.config()
|
|
11
|
+
keys = [item["key"] for item in event["Items"]]
|
|
12
|
+
response = clients.target_s3().delete_objects(
|
|
13
|
+
Bucket=cfg.target_bucket,
|
|
14
|
+
Delete={"Objects": [{"Key": key} for key in keys], "Quiet": True},
|
|
15
|
+
)
|
|
16
|
+
failures = [
|
|
17
|
+
{"key": e["Key"], "error": truncate_error(f"{e.get('Code')}: {e.get('Message')}")}
|
|
18
|
+
for e in response.get("Errors", [])
|
|
19
|
+
]
|
|
20
|
+
if failures:
|
|
21
|
+
logger.error("Failed to delete %d of %d keys, first: %s", len(failures), len(keys), failures[0]["key"])
|
|
22
|
+
return {"deleted": len(keys) - len(failures), "failures": failures}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from collections.abc import Iterable, Iterator
|
|
2
|
+
from typing import Literal
|
|
3
|
+
|
|
4
|
+
from .listing import Entry
|
|
5
|
+
|
|
6
|
+
Action = tuple[Literal["copy", "delete"], Entry]
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def needs_copy(src: Entry, dst: Entry) -> bool:
|
|
10
|
+
"""A target object is always written after the source version it copies,
|
|
11
|
+
so a newer source timestamp means the source was overwritten since."""
|
|
12
|
+
return src.size != dst.size or src.last_modified > dst.last_modified
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def diff(source: Iterable[Entry], target: Iterable[Entry], include_deletes: bool) -> Iterator[Action]:
|
|
16
|
+
"""Streaming merge-join of two listings sorted by rel_key."""
|
|
17
|
+
src_it, dst_it = iter(source), iter(target)
|
|
18
|
+
src, dst = next(src_it, None), next(dst_it, None)
|
|
19
|
+
while src is not None or dst is not None:
|
|
20
|
+
if dst is None or (src is not None and src.rel_key < dst.rel_key):
|
|
21
|
+
yield ("copy", src)
|
|
22
|
+
src = next(src_it, None)
|
|
23
|
+
elif src is None or dst.rel_key < src.rel_key:
|
|
24
|
+
if include_deletes:
|
|
25
|
+
yield ("delete", dst)
|
|
26
|
+
dst = next(dst_it, None)
|
|
27
|
+
else:
|
|
28
|
+
if needs_copy(src, dst):
|
|
29
|
+
yield ("copy", src)
|
|
30
|
+
src, dst = next(src_it, None), next(dst_it, None)
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import queue
|
|
2
|
+
import threading
|
|
3
|
+
from collections.abc import Iterable, Iterator
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from itertools import chain
|
|
7
|
+
from typing import TypeVar
|
|
8
|
+
|
|
9
|
+
T = TypeVar("T")
|
|
10
|
+
|
|
11
|
+
_PUT_POLL_SECONDS = 0.1
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ListingOrderError(Exception):
|
|
15
|
+
"""Raised when a listing is not in strictly ascending key order."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class Entry:
|
|
20
|
+
rel_key: str
|
|
21
|
+
key: str
|
|
22
|
+
size: int
|
|
23
|
+
last_modified: datetime
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def iter_entry_pages(client, bucket: str, prefix: str, page_size: int = 1000) -> Iterator[list[Entry]]:
|
|
27
|
+
"""Yield one list of entries per listing page, in key order.
|
|
28
|
+
|
|
29
|
+
Python str order equals UTF-8 byte order used by S3. The folder marker whose key equals
|
|
30
|
+
the prefix (relative key "") is skipped on both sides: it has no target key of its own.
|
|
31
|
+
"""
|
|
32
|
+
paginator = client.get_paginator("list_objects_v2")
|
|
33
|
+
previous: str | None = None
|
|
34
|
+
pages = paginator.paginate(Bucket=bucket, Prefix=prefix, PaginationConfig={"PageSize": page_size})
|
|
35
|
+
for page in pages:
|
|
36
|
+
entries = []
|
|
37
|
+
for obj in page.get("Contents", []):
|
|
38
|
+
key = obj["Key"]
|
|
39
|
+
if previous is not None and key <= previous:
|
|
40
|
+
raise ListingOrderError(
|
|
41
|
+
f"Listing of s3://{bucket}/{prefix} is not in ascending key order: {previous!r} then {key!r}"
|
|
42
|
+
)
|
|
43
|
+
previous = key
|
|
44
|
+
rel_key = key[len(prefix):]
|
|
45
|
+
if rel_key == "":
|
|
46
|
+
continue
|
|
47
|
+
entries.append(Entry(rel_key=rel_key, key=key, size=obj["Size"], last_modified=obj["LastModified"]))
|
|
48
|
+
yield entries
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def iter_entries(client, bucket: str, prefix: str, page_size: int = 1000) -> Iterator[Entry]:
|
|
52
|
+
"""Yield objects under prefix in key order."""
|
|
53
|
+
return chain.from_iterable(iter_entry_pages(client, bucket, prefix, page_size))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
_DONE = object()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class _Failure:
|
|
60
|
+
def __init__(self, error: BaseException):
|
|
61
|
+
self.error = error
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class prefetch(Iterator[T]): # noqa: N801 - used like a function
|
|
65
|
+
"""Consume items in a background thread through a bounded queue.
|
|
66
|
+
|
|
67
|
+
Order is preserved and a producer exception is re-raised in the consumer. Call close()
|
|
68
|
+
(or use contextlib.closing) to stop the producer early so no thread lingers in a warm Lambda.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
def __init__(self, items: Iterable[T], maxsize: int = 4):
|
|
72
|
+
self._items = items
|
|
73
|
+
self._buffer: queue.Queue = queue.Queue(maxsize=maxsize)
|
|
74
|
+
self._stop = threading.Event()
|
|
75
|
+
self._finished = False
|
|
76
|
+
self._thread = threading.Thread(target=self._produce, name="listing-prefetch", daemon=True)
|
|
77
|
+
self._thread.start()
|
|
78
|
+
|
|
79
|
+
def _put(self, value) -> bool:
|
|
80
|
+
while not self._stop.is_set():
|
|
81
|
+
try:
|
|
82
|
+
self._buffer.put(value, timeout=_PUT_POLL_SECONDS)
|
|
83
|
+
return True
|
|
84
|
+
except queue.Full:
|
|
85
|
+
continue
|
|
86
|
+
return False
|
|
87
|
+
|
|
88
|
+
def _produce(self) -> None:
|
|
89
|
+
iterator = iter(self._items)
|
|
90
|
+
try:
|
|
91
|
+
for item in iterator:
|
|
92
|
+
if not self._put(item):
|
|
93
|
+
return
|
|
94
|
+
except BaseException as error: # noqa: BLE001 - handed to the consumer
|
|
95
|
+
self._put(_Failure(error))
|
|
96
|
+
return
|
|
97
|
+
finally:
|
|
98
|
+
close = getattr(iterator, "close", None)
|
|
99
|
+
if close is not None:
|
|
100
|
+
close()
|
|
101
|
+
self._put(_DONE)
|
|
102
|
+
|
|
103
|
+
def __next__(self) -> T:
|
|
104
|
+
if self._finished:
|
|
105
|
+
raise StopIteration
|
|
106
|
+
value = self._buffer.get()
|
|
107
|
+
if value is _DONE:
|
|
108
|
+
self.close()
|
|
109
|
+
raise StopIteration
|
|
110
|
+
if isinstance(value, _Failure):
|
|
111
|
+
self.close()
|
|
112
|
+
raise value.error
|
|
113
|
+
return value
|
|
114
|
+
|
|
115
|
+
def close(self) -> None:
|
|
116
|
+
self._finished = True
|
|
117
|
+
self._stop.set()
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import tempfile
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class JsonlManifest:
|
|
7
|
+
"""Buffers JSONL records in /tmp and uploads them with managed multipart upload.
|
|
8
|
+
|
|
9
|
+
Use as a context manager so the temp file is removed even when the run fails:
|
|
10
|
+
Lambda /tmp survives across warm invocations.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
def __init__(self, s3, bucket: str, key: str):
|
|
14
|
+
self._s3 = s3
|
|
15
|
+
self._bucket = bucket
|
|
16
|
+
self._key = key
|
|
17
|
+
self._file = tempfile.NamedTemporaryFile("w", suffix=".jsonl", delete=False, encoding="utf-8")
|
|
18
|
+
self.count = 0
|
|
19
|
+
|
|
20
|
+
def __enter__(self) -> "JsonlManifest":
|
|
21
|
+
return self
|
|
22
|
+
|
|
23
|
+
def __exit__(self, *_exc) -> None:
|
|
24
|
+
self.discard()
|
|
25
|
+
|
|
26
|
+
def write(self, record: dict) -> None:
|
|
27
|
+
self._file.write(json.dumps(record, ensure_ascii=False) + "\n")
|
|
28
|
+
self.count += 1
|
|
29
|
+
|
|
30
|
+
def upload(self) -> None:
|
|
31
|
+
self._file.close()
|
|
32
|
+
try:
|
|
33
|
+
self._s3.upload_file(self._file.name, self._bucket, self._key)
|
|
34
|
+
finally:
|
|
35
|
+
self.discard()
|
|
36
|
+
|
|
37
|
+
def discard(self) -> None:
|
|
38
|
+
"""Close and delete the temp file. Safe to call more than once."""
|
|
39
|
+
self._file.close()
|
|
40
|
+
if os.path.exists(self._file.name):
|
|
41
|
+
os.unlink(self._file.name)
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from contextlib import closing
|
|
3
|
+
from itertools import chain
|
|
4
|
+
|
|
5
|
+
from . import clients
|
|
6
|
+
from .diff import diff
|
|
7
|
+
from .listing import iter_entry_pages, prefetch
|
|
8
|
+
from .manifest import JsonlManifest
|
|
9
|
+
|
|
10
|
+
logger = logging.getLogger()
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def handler(event, context):
|
|
14
|
+
cfg = clients.config()
|
|
15
|
+
run_id = event["runId"]
|
|
16
|
+
copy_key = f"runs/{run_id}/copy.jsonl"
|
|
17
|
+
delete_key = f"runs/{run_id}/delete.jsonl"
|
|
18
|
+
|
|
19
|
+
work_s3 = clients.target_s3()
|
|
20
|
+
with (
|
|
21
|
+
JsonlManifest(work_s3, cfg.work_bucket, copy_key) as copy_manifest,
|
|
22
|
+
JsonlManifest(work_s3, cfg.work_bucket, delete_key) as delete_manifest,
|
|
23
|
+
):
|
|
24
|
+
# List both sides concurrently: each listing fills a small page queue in its own thread
|
|
25
|
+
# while the merge-join below consumes them, so Plan time is the slower listing, not the sum.
|
|
26
|
+
# Build both clients before starting any thread so a setup error cannot orphan a listing thread.
|
|
27
|
+
source_s3, target_s3 = clients.source_s3(), clients.target_s3()
|
|
28
|
+
with (
|
|
29
|
+
closing(prefetch(iter_entry_pages(source_s3, cfg.source_bucket, cfg.source_prefix))) as source,
|
|
30
|
+
closing(prefetch(iter_entry_pages(target_s3, cfg.target_bucket, cfg.target_prefix))) as target,
|
|
31
|
+
):
|
|
32
|
+
for kind, entry in diff(chain.from_iterable(source), chain.from_iterable(target), cfg.delete_extraneous):
|
|
33
|
+
if kind == "copy":
|
|
34
|
+
copy_manifest.write({"key": entry.key, "size": entry.size})
|
|
35
|
+
else:
|
|
36
|
+
delete_manifest.write({"key": entry.key})
|
|
37
|
+
|
|
38
|
+
copy_manifest.upload()
|
|
39
|
+
delete_manifest.upload()
|
|
40
|
+
|
|
41
|
+
logger.info(
|
|
42
|
+
"Plan %s: %d to copy, %d to delete", run_id, copy_manifest.count, delete_manifest.count
|
|
43
|
+
)
|
|
44
|
+
return {
|
|
45
|
+
"runId": run_id,
|
|
46
|
+
"copyManifestKey": copy_key,
|
|
47
|
+
"deleteManifestKey": delete_key,
|
|
48
|
+
"copyCount": copy_manifest.count,
|
|
49
|
+
"deleteCount": delete_manifest.count,
|
|
50
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
from contextlib import closing
|
|
4
|
+
|
|
5
|
+
from . import clients
|
|
6
|
+
from .config import Config
|
|
7
|
+
from .errors import truncate_error
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger()
|
|
10
|
+
|
|
11
|
+
MAX_KEYS_IN_ALERT = 20
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def handler(event, context):
|
|
15
|
+
cfg = clients.config()
|
|
16
|
+
s3 = clients.target_s3()
|
|
17
|
+
run_id = event["runId"]
|
|
18
|
+
plan = event["plan"]
|
|
19
|
+
|
|
20
|
+
copy = MapTally("copy", ("copied", "deferred"))
|
|
21
|
+
delete = MapTally("delete", ("deleted",))
|
|
22
|
+
read_map_results(s3, event.get("copy"), copy)
|
|
23
|
+
read_map_results(s3, event.get("delete"), delete)
|
|
24
|
+
failures = copy.failures + delete.failures
|
|
25
|
+
|
|
26
|
+
failures_uri = None
|
|
27
|
+
if failures:
|
|
28
|
+
failures_key = f"runs/{run_id}/failures.jsonl"
|
|
29
|
+
s3.put_object(
|
|
30
|
+
Bucket=cfg.work_bucket,
|
|
31
|
+
Key=failures_key,
|
|
32
|
+
Body="".join(json.dumps(f, ensure_ascii=False) + "\n" for f in failures).encode("utf-8"),
|
|
33
|
+
ContentType="application/x-ndjson",
|
|
34
|
+
)
|
|
35
|
+
failures_uri = f"s3://{cfg.work_bucket}/{failures_key}"
|
|
36
|
+
|
|
37
|
+
summary = {
|
|
38
|
+
"planned": {"copy": plan["copyCount"], "delete": plan["deleteCount"]},
|
|
39
|
+
"copied": copy.counts["copied"],
|
|
40
|
+
"deferred": copy.counts["deferred"],
|
|
41
|
+
"failed": len(copy.failures),
|
|
42
|
+
"deleted": delete.counts["deleted"],
|
|
43
|
+
"deleteFailed": len(delete.failures),
|
|
44
|
+
"executionArn": event["executionArn"],
|
|
45
|
+
"failuresUri": failures_uri,
|
|
46
|
+
}
|
|
47
|
+
s3.put_object(
|
|
48
|
+
Bucket=cfg.work_bucket,
|
|
49
|
+
Key=f"runs/{run_id}/summary.json",
|
|
50
|
+
Body=json.dumps(summary).encode("utf-8"),
|
|
51
|
+
ContentType="application/json",
|
|
52
|
+
)
|
|
53
|
+
logger.info("Run summary: %s", json.dumps(summary))
|
|
54
|
+
|
|
55
|
+
if failures:
|
|
56
|
+
publish_alert(cfg, summary, failures)
|
|
57
|
+
return summary
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class MapTally:
|
|
61
|
+
"""Aggregated counts and per-key failures of one Distributed Map run."""
|
|
62
|
+
|
|
63
|
+
def __init__(self, action: str, count_fields: tuple[str, ...]):
|
|
64
|
+
self.action = action
|
|
65
|
+
self.count_fields = count_fields
|
|
66
|
+
self.counts = {name: 0 for name in count_fields}
|
|
67
|
+
self.failures: list[dict] = []
|
|
68
|
+
|
|
69
|
+
def add(self, output) -> None:
|
|
70
|
+
if not isinstance(output, dict):
|
|
71
|
+
logger.warning("Ignoring unrecognized %s map result: %r", self.action, output)
|
|
72
|
+
return
|
|
73
|
+
failed_batch = output.get("failedBatch")
|
|
74
|
+
if failed_batch is not None:
|
|
75
|
+
error = failed_batch.get("error")
|
|
76
|
+
if isinstance(error, dict): # Catch output: the whole Step Functions error object
|
|
77
|
+
self.add_failed_batch(failed_batch["items"], error.get("Error"), error.get("Cause"))
|
|
78
|
+
else:
|
|
79
|
+
self.add_failed_batch(failed_batch["items"], error, failed_batch.get("cause"))
|
|
80
|
+
return
|
|
81
|
+
for name in self.count_fields:
|
|
82
|
+
self.counts[name] += int(output.get(name, 0))
|
|
83
|
+
for failure in output.get("failures", []):
|
|
84
|
+
self.failures.append({"action": self.action, "key": failure["key"], "error": failure.get("error", "")})
|
|
85
|
+
|
|
86
|
+
def add_failed_batch(self, items: list[dict], error, cause) -> None:
|
|
87
|
+
message = truncate_error(f"{error}: {cause}" if cause else str(error))
|
|
88
|
+
for item in items:
|
|
89
|
+
self.failures.append({"action": self.action, "key": item["key"], "error": message})
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def read_map_results(s3, map_output, tally: MapTally) -> None:
|
|
93
|
+
"""Stream ResultWriter JSONL files line by line so only failures are held in memory.
|
|
94
|
+
|
|
95
|
+
Each line should be one child execution output (COMPACT). Tolerates a line that is a JSON string
|
|
96
|
+
holding the output and the non-COMPACT shape with an "Output" field.
|
|
97
|
+
"""
|
|
98
|
+
if not map_output:
|
|
99
|
+
return
|
|
100
|
+
details = map_output["ResultWriterDetails"]
|
|
101
|
+
manifest = json.loads(s3.get_object(Bucket=details["Bucket"], Key=details["Key"])["Body"].read())
|
|
102
|
+
result_files = manifest.get("ResultFiles", {})
|
|
103
|
+
for status in ("SUCCEEDED", "FAILED"):
|
|
104
|
+
for result_file in result_files.get(status) or []:
|
|
105
|
+
body = s3.get_object(Bucket=manifest["DestinationBucket"], Key=result_file["Key"])["Body"]
|
|
106
|
+
with closing(body):
|
|
107
|
+
for line in body.iter_lines():
|
|
108
|
+
if line.strip():
|
|
109
|
+
tally.add(parse_result_line(line))
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def parse_result_line(line: bytes):
|
|
113
|
+
value = json.loads(line)
|
|
114
|
+
if isinstance(value, str):
|
|
115
|
+
value = json.loads(value)
|
|
116
|
+
if isinstance(value, dict) and "Output" in value:
|
|
117
|
+
output = value["Output"]
|
|
118
|
+
return json.loads(output) if isinstance(output, str) else output
|
|
119
|
+
if isinstance(value, dict) and "Error" in value and "Input" in value:
|
|
120
|
+
# A failed child execution in the non-COMPACT shape: every key of its batch failed.
|
|
121
|
+
batch = json.loads(value["Input"]) if isinstance(value["Input"], str) else value["Input"]
|
|
122
|
+
return {"failedBatch": {"items": batch.get("Items", []), "error": value["Error"], "cause": value.get("Cause")}}
|
|
123
|
+
return value
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def publish_alert(cfg: Config, summary: dict, failures: list[dict]) -> None:
|
|
127
|
+
region = summary["executionArn"].split(":")[3]
|
|
128
|
+
console_url = (
|
|
129
|
+
f"https://{region}.console.aws.amazon.com/states/home?region={region}"
|
|
130
|
+
f"#/v2/executions/details/{summary['executionArn']}"
|
|
131
|
+
)
|
|
132
|
+
shown = failures[:MAX_KEYS_IN_ALERT]
|
|
133
|
+
lines = [
|
|
134
|
+
f"S3 pull sync from s3://{cfg.source_bucket}/{cfg.source_prefix} to s3://{cfg.target_bucket}/{cfg.target_prefix}",
|
|
135
|
+
"",
|
|
136
|
+
f"Planned copies: {summary['planned']['copy']}, planned deletes: {summary['planned']['delete']}",
|
|
137
|
+
f"Copied: {summary['copied']}, deferred: {summary['deferred']}, failed: {summary['failed']}",
|
|
138
|
+
f"Deleted: {summary['deleted']}, delete failures: {summary['deleteFailed']}",
|
|
139
|
+
"",
|
|
140
|
+
"Failed keys (retried automatically on the next run):",
|
|
141
|
+
*[f" {f['key']}: {f.get('error', '')}" for f in shown],
|
|
142
|
+
]
|
|
143
|
+
if len(failures) > len(shown):
|
|
144
|
+
lines.append(f" ...and {len(failures) - len(shown)} more")
|
|
145
|
+
lines += ["", f"Full list: {summary['failuresUri']}", f"Execution: {console_url}"]
|
|
146
|
+
|
|
147
|
+
total = summary["failed"] + summary["deleteFailed"]
|
|
148
|
+
clients.sns().publish(
|
|
149
|
+
TopicArn=cfg.alert_topic_arn,
|
|
150
|
+
Subject=f"S3 pull sync: {total} object(s) failed",
|
|
151
|
+
Message="\n".join(lines),
|
|
152
|
+
)
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './s3-pull-sync';
|