lambda-deps-builder 0.2.0__tar.gz → 0.3.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lambda-deps-builder
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: CDK construct that builds Python Lambda dependencies inside Lambda — no local Docker.
5
5
  License: Apache-2.0
6
6
  Keywords: aws,cdk,lambda,dependencies,dockerless,layer
@@ -55,7 +55,8 @@ deploy ──> 1. CFN creates bucket
55
55
  uv pip install -r requirements.txt --target /tmp/build/python
56
56
  (10x faster than pip; automatic fallback to pip if needed)
57
57
  zip /tmp/build → /tmp/deps.zip
58
- s3.put_object(Bucket=..., Key=deps-X.zip)
58
+ analyzer.py inspects .dist-info & sizes → layer-analysis.html
59
+ s3.put_object(Bucket=..., Key=deps-X.zip & layer-analysis-X.html)
59
60
  4. CFN creates LayerVersion (depends_on the trigger) → reads zip from S3
60
61
  5. Consumer Function(architecture=X, layers=[layer]) runs with matching deps
61
62
  ```
@@ -74,6 +75,30 @@ By default, `LambdaDepsBuilder` uses **Astral `uv`** inside the trigger Lambda.
74
75
 
75
76
  If `uv` bootstrapping or installation encounters an issue, `fallback_to_pip=True` ensures seamless automatic fallback to standard `pip`.
76
77
 
78
+ ## Interactive Layer Size Visualizer (HTML Treemap)
79
+
80
+ During each build, `LambdaDepsBuilder` analyzes the installed `/tmp/build/python` directory using `.dist-info/METADATA` and `RECORD` manifests, generates a **self-contained interactive HTML treemap** (zero external CDN dependencies), and uploads it to S3 alongside your layer zip:
81
+
82
+ - **250 MB AWS Lambda Quota Bar**: visual headroom indicator against the 262,144,000-byte unzipped limit.
83
+ - **Interactive Squarified Treemap**: click any package or subdirectory to drill down, hover for exact byte/quota/native-binary tooltips, and filter live by package or file name.
84
+ - **Sortable Package Breakdown Table**: compare unzipped size, `% of layer`, file counts, and compiled `.so` / `.pyd` native binary share.
85
+ - **CloudFormation Output**: exposes `LayerAnalysisReportUri` (`s3://<bucket>/layer-analysis-<arch>-<id>.html`) and `builder.report_s3_uri`.
86
+
87
+ Download and open the report locally after `cdk deploy`:
88
+
89
+ ```shell
90
+ aws s3 cp "$(aws cloudformation describe-stacks \
91
+ --stack-name MyStack \
92
+ --query "Stacks[0].Outputs[?OutputKey=='DepsLayerAnalysisReportUri'].OutputValue" \
93
+ --output text)" ./layer-analysis.html
94
+ ```
95
+
96
+ Configuration options on `LambdaDepsBuilder`:
97
+
98
+ - `generate_size_report: bool = True` — set to `False` to skip analysis and HTML upload.
99
+ - `report_output_key: Optional[str] = None` — override the default `layer-analysis-{ARCH}-{construct_id}.html` S3 key.
100
+ - `emit_report_cfn_output: bool = True` — set to `False` to suppress the `LayerAnalysisReportUri` `CfnOutput`.
101
+
77
102
  ## Usage
78
103
 
79
104
  ```python
@@ -29,7 +29,8 @@ deploy ──> 1. CFN creates bucket
29
29
  uv pip install -r requirements.txt --target /tmp/build/python
30
30
  (10x faster than pip; automatic fallback to pip if needed)
31
31
  zip /tmp/build → /tmp/deps.zip
32
- s3.put_object(Bucket=..., Key=deps-X.zip)
32
+ analyzer.py inspects .dist-info & sizes → layer-analysis.html
33
+ s3.put_object(Bucket=..., Key=deps-X.zip & layer-analysis-X.html)
33
34
  4. CFN creates LayerVersion (depends_on the trigger) → reads zip from S3
34
35
  5. Consumer Function(architecture=X, layers=[layer]) runs with matching deps
35
36
  ```
@@ -48,6 +49,30 @@ By default, `LambdaDepsBuilder` uses **Astral `uv`** inside the trigger Lambda.
48
49
 
49
50
  If `uv` bootstrapping or installation encounters an issue, `fallback_to_pip=True` ensures seamless automatic fallback to standard `pip`.
50
51
 
52
+ ## Interactive Layer Size Visualizer (HTML Treemap)
53
+
54
+ During each build, `LambdaDepsBuilder` analyzes the installed `/tmp/build/python` directory using `.dist-info/METADATA` and `RECORD` manifests, generates a **self-contained interactive HTML treemap** (zero external CDN dependencies), and uploads it to S3 alongside your layer zip:
55
+
56
+ - **250 MB AWS Lambda Quota Bar**: visual headroom indicator against the 262,144,000-byte unzipped limit.
57
+ - **Interactive Squarified Treemap**: click any package or subdirectory to drill down, hover for exact byte/quota/native-binary tooltips, and filter live by package or file name.
58
+ - **Sortable Package Breakdown Table**: compare unzipped size, `% of layer`, file counts, and compiled `.so` / `.pyd` native binary share.
59
+ - **CloudFormation Output**: exposes `LayerAnalysisReportUri` (`s3://<bucket>/layer-analysis-<arch>-<id>.html`) and `builder.report_s3_uri`.
60
+
61
+ Download and open the report locally after `cdk deploy`:
62
+
63
+ ```shell
64
+ aws s3 cp "$(aws cloudformation describe-stacks \
65
+ --stack-name MyStack \
66
+ --query "Stacks[0].Outputs[?OutputKey=='DepsLayerAnalysisReportUri'].OutputValue" \
67
+ --output text)" ./layer-analysis.html
68
+ ```
69
+
70
+ Configuration options on `LambdaDepsBuilder`:
71
+
72
+ - `generate_size_report: bool = True` — set to `False` to skip analysis and HTML upload.
73
+ - `report_output_key: Optional[str] = None` — override the default `layer-analysis-{ARCH}-{construct_id}.html` S3 key.
74
+ - `emit_report_cfn_output: bool = True` — set to `False` to suppress the `LayerAnalysisReportUri` `CfnOutput`.
75
+
51
76
  ## Usage
52
77
 
53
78
  ```python
@@ -1,4 +1,4 @@
1
1
  from lambda_deps_builder.construct import LambdaDepsBuilder
2
2
 
3
- __version__ = "0.2.0"
3
+ __version__ = "0.3.0"
4
4
  __all__ = ["LambdaDepsBuilder", "__version__"]
@@ -0,0 +1,843 @@
1
+ """Analyze installed Python Lambda dependencies and render a self-contained HTML treemap."""
2
+
3
+ import csv
4
+ import json
5
+ import os
6
+ import posixpath
7
+ from pathlib import Path
8
+ from typing import Any, Dict, List, Optional, Tuple
9
+
10
+ LAMBDA_UNZIPPED_LIMIT_BYTES = 262_144_000 # 250 MB (AWS Lambda unzipped layer limit)
11
+
12
+ _NATIVE_BINARY_SUFFIXES = {".so", ".pyd", ".dll", ".dylib"}
13
+
14
+
15
+ def _is_native_binary(rel_path: str) -> bool:
16
+ """Return True if the file path looks like a compiled native shared library."""
17
+ name = posixpath.basename(rel_path).lower()
18
+ if ".so." in name:
19
+ return True
20
+ _, ext = posixpath.splitext(name)
21
+ return ext in _NATIVE_BINARY_SUFFIXES
22
+
23
+
24
+ def _parse_metadata(dist_info_dir: Path) -> Tuple[str, str]:
25
+ """Extract (Name, Version) from a `.dist-info/METADATA` file."""
26
+ fallback_name = dist_info_dir.name[: -len(".dist-info")].split("-", 1)[0]
27
+ metadata_file = dist_info_dir / "METADATA"
28
+ if not metadata_file.is_file():
29
+ return fallback_name, ""
30
+
31
+ name = ""
32
+ version = ""
33
+ with metadata_file.open("r", encoding="utf-8", errors="replace") as fh:
34
+ for line in fh:
35
+ stripped = line.rstrip("\r\n")
36
+ if stripped == "":
37
+ break
38
+ if stripped.startswith("Name:") and not name:
39
+ name = stripped[5:].strip()
40
+ elif stripped.startswith("Version:") and not version:
41
+ version = stripped[8:].strip()
42
+ if name and version:
43
+ break
44
+
45
+ return (name or fallback_name), version
46
+
47
+
48
+ def _normalize_rel_path(raw_path: str) -> Optional[str]:
49
+ """Normalize a RECORD relative path and reject entries escaping target_dir."""
50
+ cleaned = raw_path.strip().replace("\\", "/")
51
+ if not cleaned or cleaned.startswith("/"):
52
+ return None
53
+ normalized = posixpath.normpath(cleaned)
54
+ if normalized in ("", ".") or normalized.startswith("../") or normalized == "..":
55
+ return None
56
+ return normalized
57
+
58
+
59
+ def _insert_tree_file(root: Dict[str, Any], parts: List[str], size: int, is_native: bool) -> None:
60
+ """Insert a file and accumulate size/file_count/native_bytes along its path."""
61
+ root["size"] += size
62
+ root["file_count"] += 1
63
+ if is_native:
64
+ root["native_bytes"] += size
65
+
66
+ node = root
67
+ for idx, part in enumerate(parts):
68
+ children = node.setdefault("_children_map", {})
69
+ child = children.get(part)
70
+ if child is None:
71
+ child = {
72
+ "name": part,
73
+ "size": 0,
74
+ "file_count": 0,
75
+ "native_bytes": 0,
76
+ }
77
+ children[part] = child
78
+ child["size"] += size
79
+ child["file_count"] += 1
80
+ if is_native:
81
+ child["native_bytes"] += size
82
+ if idx < len(parts) - 1:
83
+ node = child
84
+
85
+
86
+ def _finalize_tree(node: Dict[str, Any]) -> Dict[str, Any]:
87
+ """Convert internal `_children_map` dicts into sorted `children` lists."""
88
+ children_map = node.pop("_children_map", None)
89
+ if children_map:
90
+ children = [_finalize_tree(c) for c in children_map.values()]
91
+ children.sort(key=lambda item: item["size"], reverse=True)
92
+ node["children"] = children
93
+ return node
94
+
95
+
96
+ def analyze_directory(target_dir: Path) -> Dict[str, Any]:
97
+ """
98
+ Walk `target_dir` and attribute files to Python distributions via `.dist-info/RECORD`
99
+ and `METADATA`, building a hierarchical size tree per package.
100
+
101
+ :param target_dir: Root directory containing installed Python packages.
102
+ :return: JSON-serializable analysis summary and hierarchical package tree.
103
+ """
104
+ files_map: Dict[str, int] = {}
105
+ for dirpath, _, filenames in os.walk(target_dir, followlinks=False):
106
+ rel_dir = Path(dirpath).relative_to(target_dir).as_posix()
107
+ for fname in filenames:
108
+ full_path = Path(dirpath) / fname
109
+ if full_path.is_symlink() or not full_path.is_file():
110
+ continue
111
+ rel_path = fname if rel_dir == "." else f"{rel_dir}/{fname}"
112
+ files_map[rel_path] = full_path.stat().st_size
113
+
114
+ claimed: set[str] = set()
115
+ # Keyed by (dist_name.lower(), version) to merge cleanly if needed, storing display name
116
+ pkg_buckets: Dict[str, Dict[str, Any]] = {}
117
+
118
+ for dist_info_dir in sorted(target_dir.glob("*.dist-info")):
119
+ if not dist_info_dir.is_dir():
120
+ continue
121
+ pkg_name, pkg_version = _parse_metadata(dist_info_dir)
122
+ bucket_key = pkg_name.lower()
123
+ bucket = pkg_buckets.setdefault(
124
+ bucket_key,
125
+ {
126
+ "name": pkg_name,
127
+ "version": pkg_version,
128
+ "size": 0,
129
+ "file_count": 0,
130
+ "native_bytes": 0,
131
+ "_children_map": {},
132
+ },
133
+ )
134
+ if not bucket["version"] and pkg_version:
135
+ bucket["version"] = pkg_version
136
+
137
+ record_file = dist_info_dir / "RECORD"
138
+ if record_file.is_file():
139
+ with record_file.open("r", encoding="utf-8", errors="replace", newline="") as fh:
140
+ reader = csv.reader(fh)
141
+ for row in reader:
142
+ if not row:
143
+ continue
144
+ rel_path = _normalize_rel_path(row[0])
145
+ if rel_path is None or rel_path in claimed:
146
+ continue
147
+ if rel_path in files_map:
148
+ claimed.add(rel_path)
149
+ size = files_map[rel_path]
150
+ _insert_tree_file(
151
+ bucket,
152
+ rel_path.split("/"),
153
+ size,
154
+ _is_native_binary(rel_path),
155
+ )
156
+
157
+ # Also claim any files inside the .dist-info directory itself not listed in RECORD
158
+ dist_prefix = f"{dist_info_dir.name}/"
159
+ for rel_path, size in files_map.items():
160
+ if rel_path.startswith(dist_prefix) and rel_path not in claimed:
161
+ claimed.add(rel_path)
162
+ _insert_tree_file(
163
+ bucket,
164
+ rel_path.split("/"),
165
+ size,
166
+ _is_native_binary(rel_path),
167
+ )
168
+
169
+ # Group any unrecorded files by top-level directory or "(root)"
170
+ for rel_path, size in files_map.items():
171
+ if rel_path in claimed:
172
+ continue
173
+ parts = rel_path.split("/")
174
+ group_name = parts[0] if len(parts) > 1 else "(root)"
175
+ bucket_key = f"__unclaimed__:{group_name.lower()}"
176
+ bucket = pkg_buckets.setdefault(
177
+ bucket_key,
178
+ {
179
+ "name": group_name,
180
+ "version": "",
181
+ "size": 0,
182
+ "file_count": 0,
183
+ "native_bytes": 0,
184
+ "_children_map": {},
185
+ },
186
+ )
187
+ _insert_tree_file(bucket, parts, size, _is_native_binary(rel_path))
188
+
189
+ total_unzipped = sum(files_map.values())
190
+ total_files = len(files_map)
191
+ total_native = 0
192
+
193
+ packages: List[Dict[str, Any]] = []
194
+ for bucket in pkg_buckets.values():
195
+ if bucket["file_count"] == 0:
196
+ continue
197
+ finalized = _finalize_tree(bucket)
198
+ finalized["percent"] = (
199
+ round(finalized["size"] / total_unzipped * 100, 2)
200
+ if total_unzipped > 0
201
+ else 0.0
202
+ )
203
+ total_native += finalized["native_bytes"]
204
+ packages.append(finalized)
205
+
206
+ packages.sort(key=lambda item: item["size"], reverse=True)
207
+
208
+ return {
209
+ "total_unzipped_bytes": total_unzipped,
210
+ "quota_limit_bytes": LAMBDA_UNZIPPED_LIMIT_BYTES,
211
+ "quota_percent": round(total_unzipped / LAMBDA_UNZIPPED_LIMIT_BYTES * 100, 2),
212
+ "package_count": len(packages),
213
+ "file_count": total_files,
214
+ "native_binary_bytes": total_native,
215
+ "packages": packages,
216
+ }
217
+
218
+
219
+ def render_treemap_html(
220
+ analysis: Dict[str, Any],
221
+ *,
222
+ zip_bytes: int,
223
+ metadata: Optional[Dict[str, Any]] = None,
224
+ ) -> str:
225
+ """
226
+ Render a self-contained interactive HTML treemap report with zero external CDN dependencies.
227
+
228
+ :param analysis: Output dictionary from :func:`analyze_directory`.
229
+ :param zip_bytes: Compressed `.zip` archive size in bytes.
230
+ :param metadata: Optional build metadata (`runtime`, `architecture`, `engine`, etc.).
231
+ :return: Complete HTML5 document as a UTF-8 string.
232
+ """
233
+ payload = {
234
+ "analysis": analysis,
235
+ "zip_bytes": zip_bytes,
236
+ "metadata": metadata or {},
237
+ }
238
+ safe_json = (
239
+ json.dumps(payload, separators=(",", ":"))
240
+ .replace("</", "<\\/")
241
+ .replace("\u2028", "\\u2028")
242
+ .replace("\u2029", "\\u2029")
243
+ )
244
+
245
+ return _HTML_TEMPLATE.replace("__LAYER_DATA_JSON__", safe_json)
246
+
247
+
248
+ _HTML_TEMPLATE = """<!DOCTYPE html>
249
+ <html lang="en">
250
+ <head>
251
+ <meta charset="utf-8">
252
+ <meta name="viewport" content="width=device-width, initial-scale=1">
253
+ <title>Lambda Layer Size Analysis</title>
254
+ <style>
255
+ :root {
256
+ --bg: #0b1020;
257
+ --surface: #121931;
258
+ --surface-2: #182242;
259
+ --border: #26335c;
260
+ --text: #e6ecff;
261
+ --muted: #93a3c8;
262
+ --accent: #6366f1;
263
+ --ok: #10b981;
264
+ --warn: #f59e0b;
265
+ --danger: #f43f5e;
266
+ }
267
+ * { box-sizing: border-box; }
268
+ body {
269
+ margin: 0;
270
+ padding: 24px;
271
+ background: var(--bg);
272
+ color: var(--text);
273
+ font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif;
274
+ line-height: 1.45;
275
+ }
276
+ .container { max-width: 1280px; margin: 0 auto; }
277
+ header {
278
+ display: flex;
279
+ flex-wrap: wrap;
280
+ align-items: center;
281
+ justify-content: space-between;
282
+ gap: 12px;
283
+ margin-bottom: 20px;
284
+ }
285
+ h1 { margin: 0; font-size: 1.45rem; font-weight: 700; letter-spacing: -0.02em; }
286
+ .subtitle { color: var(--muted); font-size: 0.88rem; margin-top: 2px; }
287
+ .badges { display: flex; flex-wrap: wrap; gap: 8px; }
288
+ .badge {
289
+ background: var(--surface-2);
290
+ border: 1px solid var(--border);
291
+ color: var(--text);
292
+ padding: 4px 10px;
293
+ border-radius: 999px;
294
+ font-size: 0.78rem;
295
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
296
+ }
297
+ .card {
298
+ background: var(--surface);
299
+ border: 1px solid var(--border);
300
+ border-radius: 12px;
301
+ padding: 16px 18px;
302
+ margin-bottom: 16px;
303
+ }
304
+ .quota-header {
305
+ display: flex;
306
+ justify-content: space-between;
307
+ align-items: baseline;
308
+ flex-wrap: wrap;
309
+ gap: 8px;
310
+ margin-bottom: 8px;
311
+ font-size: 0.9rem;
312
+ }
313
+ .progress-track {
314
+ width: 100%;
315
+ height: 12px;
316
+ background: var(--surface-2);
317
+ border-radius: 999px;
318
+ overflow: hidden;
319
+ border: 1px solid var(--border);
320
+ }
321
+ .progress-fill { height: 100%; transition: width 0.25s ease; }
322
+ .kpis {
323
+ display: grid;
324
+ grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
325
+ gap: 12px;
326
+ margin-bottom: 16px;
327
+ }
328
+ .kpi-label { color: var(--muted); font-size: 0.78rem; text-transform: uppercase; letter-spacing: 0.04em; }
329
+ .kpi-value { font-size: 1.3rem; font-weight: 700; margin-top: 4px; font-variant-numeric: tabular-nums; }
330
+ .kpi-sub { color: var(--muted); font-size: 0.78rem; margin-top: 2px; }
331
+ .toolbar {
332
+ display: flex;
333
+ flex-wrap: wrap;
334
+ align-items: center;
335
+ justify-content: space-between;
336
+ gap: 12px;
337
+ margin-bottom: 12px;
338
+ }
339
+ .breadcrumbs { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; font-size: 0.88rem; }
340
+ .crumb {
341
+ background: var(--surface-2);
342
+ border: 1px solid var(--border);
343
+ color: var(--text);
344
+ padding: 4px 10px;
345
+ border-radius: 6px;
346
+ cursor: pointer;
347
+ font-size: 0.82rem;
348
+ }
349
+ .crumb:hover { border-color: var(--accent); }
350
+ .crumb.active { background: var(--accent); border-color: var(--accent); cursor: default; }
351
+ .search-input {
352
+ background: var(--surface-2);
353
+ border: 1px solid var(--border);
354
+ color: var(--text);
355
+ padding: 7px 12px;
356
+ border-radius: 8px;
357
+ font-size: 0.86rem;
358
+ min-width: 240px;
359
+ outline: none;
360
+ }
361
+ .search-input:focus { border-color: var(--accent); }
362
+ #treemap {
363
+ position: relative;
364
+ width: 100%;
365
+ height: 460px;
366
+ background: var(--bg);
367
+ border: 1px solid var(--border);
368
+ border-radius: 8px;
369
+ overflow: hidden;
370
+ }
371
+ .tile {
372
+ position: absolute;
373
+ border: 1px solid rgba(11, 16, 32, 0.75);
374
+ padding: 6px 8px;
375
+ overflow: hidden;
376
+ cursor: pointer;
377
+ transition: filter 0.12s ease, opacity 0.12s ease;
378
+ display: flex;
379
+ flex-direction: column;
380
+ justify-content: space-between;
381
+ }
382
+ .tile:hover { filter: brightness(1.14); z-index: 2; }
383
+ .tile.dimmed { opacity: 0.25; }
384
+ .tile-title {
385
+ font-size: 0.8rem;
386
+ font-weight: 600;
387
+ color: #ffffff;
388
+ text-shadow: 0 1px 2px rgba(0,0,0,0.55);
389
+ white-space: nowrap;
390
+ overflow: hidden;
391
+ text-overflow: ellipsis;
392
+ }
393
+ .tile-size {
394
+ font-size: 0.72rem;
395
+ color: rgba(255,255,255,0.88);
396
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
397
+ white-space: nowrap;
398
+ overflow: hidden;
399
+ text-overflow: ellipsis;
400
+ }
401
+ #tooltip {
402
+ position: fixed;
403
+ pointer-events: none;
404
+ background: rgba(11, 16, 32, 0.96);
405
+ border: 1px solid var(--border);
406
+ border-radius: 8px;
407
+ padding: 10px 12px;
408
+ font-size: 0.8rem;
409
+ color: var(--text);
410
+ box-shadow: 0 10px 28px rgba(0,0,0,0.45);
411
+ z-index: 50;
412
+ display: none;
413
+ max-width: 320px;
414
+ }
415
+ .tt-name { font-weight: 700; margin-bottom: 4px; word-break: break-word; }
416
+ .tt-row { display: flex; justify-content: space-between; gap: 16px; color: var(--muted); }
417
+ .tt-row strong { color: var(--text); font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
418
+ table { width: 100%; border-collapse: collapse; font-size: 0.86rem; }
419
+ th, td { text-align: left; padding: 9px 10px; border-bottom: 1px solid var(--border); }
420
+ th {
421
+ color: var(--muted);
422
+ font-weight: 600;
423
+ font-size: 0.78rem;
424
+ text-transform: uppercase;
425
+ letter-spacing: 0.04em;
426
+ cursor: pointer;
427
+ user-select: none;
428
+ }
429
+ th:hover { color: var(--text); }
430
+ tbody tr { cursor: pointer; }
431
+ tbody tr:hover { background: var(--surface-2); }
432
+ .num { text-align: right; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
433
+ .bar-cell { width: 120px; }
434
+ .mini-bar { height: 7px; background: var(--surface-2); border-radius: 999px; overflow: hidden; }
435
+ .mini-bar > div { height: 100%; background: var(--accent); }
436
+ .empty-state {
437
+ display: flex;
438
+ align-items: center;
439
+ justify-content: center;
440
+ height: 100%;
441
+ color: var(--muted);
442
+ font-size: 0.9rem;
443
+ }
444
+ </style>
445
+ </head>
446
+ <body>
447
+ <div class="container">
448
+ <header>
449
+ <div>
450
+ <h1>Lambda Layer Size Analysis</h1>
451
+ <div class="subtitle" id="subtitle">Generated by lambda_deps_builder</div>
452
+ </div>
453
+ <div class="badges" id="badges"></div>
454
+ </header>
455
+
456
+ <section class="card">
457
+ <div class="quota-header">
458
+ <span><strong>250 MB AWS Lambda Unzipped Quota</strong></span>
459
+ <span id="quota-summary"></span>
460
+ </div>
461
+ <div class="progress-track">
462
+ <div class="progress-fill" id="quota-bar"></div>
463
+ </div>
464
+ </section>
465
+
466
+ <section class="kpis" id="kpis"></section>
467
+
468
+ <section class="card">
469
+ <div class="toolbar">
470
+ <div class="breadcrumbs" id="breadcrumbs"></div>
471
+ <input class="search-input" id="search" type="search" placeholder="Filter packages or files...">
472
+ </div>
473
+ <div id="treemap"></div>
474
+ </section>
475
+
476
+ <section class="card">
477
+ <div class="toolbar" style="margin-bottom: 6px;">
478
+ <strong>Package Breakdown</strong>
479
+ <span class="subtitle" id="table-count"></span>
480
+ </div>
481
+ <div style="overflow-x: auto;">
482
+ <table>
483
+ <thead>
484
+ <tr>
485
+ <th data-sort="name">Package</th>
486
+ <th data-sort="version">Version</th>
487
+ <th class="num" data-sort="size">Unzipped</th>
488
+ <th class="num" data-sort="percent">% Layer</th>
489
+ <th class="num" data-sort="file_count">Files</th>
490
+ <th class="num" data-sort="native_bytes">Native (.so)</th>
491
+ <th class="bar-cell">Share</th>
492
+ </tr>
493
+ </thead>
494
+ <tbody id="pkg-tbody"></tbody>
495
+ </table>
496
+ </div>
497
+ </section>
498
+ </div>
499
+
500
+ <div id="tooltip"></div>
501
+
502
+ <script id="layer-data" type="application/json">__LAYER_DATA_JSON__</script>
503
+ <script>
504
+ (function () {
505
+ "use strict";
506
+ const payload = JSON.parse(document.getElementById("layer-data").textContent);
507
+ const analysis = payload.analysis;
508
+ const zipBytes = payload.zip_bytes || 0;
509
+ const meta = payload.metadata || {};
510
+
511
+ const PALETTE = [
512
+ "#4f46e5", "#0891b2", "#059669", "#d97706", "#db2777",
513
+ "#7c3aed", "#2563eb", "#0d9488", "#ea580c", "#9333ea"
514
+ ];
515
+
516
+ function fmtBytes(bytes) {
517
+ if (bytes === 0) return "0 B";
518
+ const units = ["B", "KB", "MB", "GB"];
519
+ const i = Math.min(units.length - 1, Math.floor(Math.log(bytes) / Math.log(1024)));
520
+ const val = bytes / Math.pow(1024, i);
521
+ return (i === 0 ? val : val.toFixed(2)) + " " + units[i];
522
+ }
523
+
524
+ function el(tag, className, text) {
525
+ const node = document.createElement(tag);
526
+ if (className) node.className = className;
527
+ if (text !== undefined && text !== null) node.textContent = String(text);
528
+ return node;
529
+ }
530
+
531
+ // Header metadata
532
+ const badgesEl = document.getElementById("badges");
533
+ const badgePairs = [
534
+ ["arch", meta.architecture],
535
+ ["runtime", meta.runtime],
536
+ ["engine", meta.engine],
537
+ ["build", meta.build_duration_sec !== undefined ? meta.build_duration_sec + "s" : null]
538
+ ];
539
+ badgePairs.forEach(function (pair) {
540
+ if (pair[1]) {
541
+ badgesEl.appendChild(el("span", "badge", pair[0] + ": " + pair[1]));
542
+ }
543
+ });
544
+ if (meta.object_key) {
545
+ document.getElementById("subtitle").textContent = "Artifact: " + meta.object_key;
546
+ }
547
+
548
+ // Quota bar
549
+ const pct = Math.min(100, analysis.quota_percent || 0);
550
+ const quotaBar = document.getElementById("quota-bar");
551
+ quotaBar.style.width = pct + "%";
552
+ quotaBar.style.background = pct > 85 ? "var(--danger)" : pct >= 60 ? "var(--warn)" : "var(--ok)";
553
+ const remaining = Math.max(0, analysis.quota_limit_bytes - analysis.total_unzipped_bytes);
554
+ document.getElementById("quota-summary").textContent =
555
+ fmtBytes(analysis.total_unzipped_bytes) + " / " + fmtBytes(analysis.quota_limit_bytes) +
556
+ " (" + analysis.quota_percent + "% used, " + fmtBytes(remaining) + " headroom)";
557
+
558
+ // KPIs
559
+ const kpisEl = document.getElementById("kpis");
560
+ const compRatio = analysis.total_unzipped_bytes > 0
561
+ ? ((1 - zipBytes / analysis.total_unzipped_bytes) * 100).toFixed(1) + "% smaller zipped"
562
+ : "n/a";
563
+ const topPkg = analysis.packages[0];
564
+ const kpis = [
565
+ ["Unzipped Size", fmtBytes(analysis.total_unzipped_bytes), analysis.quota_percent + "% of 250 MB limit"],
566
+ ["Zipped Size", fmtBytes(zipBytes), compRatio],
567
+ ["Packages", String(analysis.package_count), analysis.file_count + " total files"],
568
+ ["Native Binaries", fmtBytes(analysis.native_binary_bytes), ".so / .pyd / .dll"],
569
+ ["Largest Package", topPkg ? topPkg.name : "-", topPkg ? fmtBytes(topPkg.size) + " (" + topPkg.percent + "%)" : ""]
570
+ ];
571
+ kpis.forEach(function (item) {
572
+ const card = el("div", "card");
573
+ card.style.marginBottom = "0";
574
+ card.appendChild(el("div", "kpi-label", item[0]));
575
+ card.appendChild(el("div", "kpi-value", item[1]));
576
+ card.appendChild(el("div", "kpi-sub", item[2]));
577
+ kpisEl.appendChild(card);
578
+ });
579
+
580
+ // Navigation & search state
581
+ const rootNode = {
582
+ name: "All Packages",
583
+ size: analysis.total_unzipped_bytes,
584
+ file_count: analysis.file_count,
585
+ native_bytes: analysis.native_binary_bytes,
586
+ children: analysis.packages
587
+ };
588
+ let pathStack = [rootNode];
589
+ let searchQuery = "";
590
+ let sortCol = "size";
591
+ let sortAsc = false;
592
+
593
+ // Squarified treemap layout
594
+ function squarify(items, x, y, w, h) {
595
+ const valid = items.filter(function (d) { return d.size > 0; });
596
+ const total = valid.reduce(function (s, d) { return s + d.size; }, 0);
597
+ if (!valid.length || total <= 0 || w <= 0 || h <= 0) return [];
598
+
599
+ const rects = [];
600
+ const areaScale = (w * h) / total;
601
+ const scaled = valid.map(function (d) {
602
+ return { node: d, area: d.size * areaScale };
603
+ });
604
+
605
+ function worstAspect(row, side) {
606
+ if (!row.length || side <= 0) return Infinity;
607
+ const sum = row.reduce(function (s, r) { return s + r.area; }, 0);
608
+ let maxA = 0, minA = Infinity;
609
+ for (let i = 0; i < row.length; i++) {
610
+ if (row[i].area > maxA) maxA = row[i].area;
611
+ if (row[i].area < minA) minA = row[i].area;
612
+ }
613
+ const s2 = sum * sum;
614
+ const w2 = side * side;
615
+ return Math.max((w2 * maxA) / s2, s2 / (w2 * minA));
616
+ }
617
+
618
+ let cx = x, cy = y, cw = w, ch = h;
619
+ let row = [];
620
+ let idx = 0;
621
+
622
+ function layoutRow(r) {
623
+ const sum = r.reduce(function (s, it) { return s + it.area; }, 0);
624
+ if (cw >= ch) {
625
+ const rw = sum / ch;
626
+ let ry = cy;
627
+ for (let i = 0; i < r.length; i++) {
628
+ const rh = r[i].area / rw;
629
+ rects.push({ node: r[i].node, x: cx, y: ry, w: rw, h: rh });
630
+ ry += rh;
631
+ }
632
+ cx += rw;
633
+ cw -= rw;
634
+ } else {
635
+ const rh = sum / cw;
636
+ let rx = cx;
637
+ for (let i = 0; i < r.length; i++) {
638
+ const rw = r[i].area / rh;
639
+ rects.push({ node: r[i].node, x: rx, y: cy, w: rw, h: rh });
640
+ rx += rw;
641
+ }
642
+ cy += rh;
643
+ ch -= rh;
644
+ }
645
+ }
646
+
647
+ while (idx < scaled.length) {
648
+ const item = scaled[idx];
649
+ const side = Math.min(cw, ch);
650
+ const nextRow = row.concat([item]);
651
+ if (!row.length || worstAspect(nextRow, side) <= worstAspect(row, side)) {
652
+ row = nextRow;
653
+ idx++;
654
+ } else {
655
+ layoutRow(row);
656
+ row = [];
657
+ }
658
+ }
659
+ if (row.length) layoutRow(row);
660
+ return rects;
661
+ }
662
+
663
+ const tooltip = document.getElementById("tooltip");
664
+ function showTooltip(ev, node) {
665
+ tooltip.textContent = "";
666
+ const title = el("div", "tt-name", node.name + (node.version ? " v" + node.version : ""));
667
+ tooltip.appendChild(title);
668
+ const layerPct = analysis.total_unzipped_bytes > 0
669
+ ? ((node.size / analysis.total_unzipped_bytes) * 100).toFixed(2) + "%"
670
+ : "0%";
671
+ const quotaPct = ((node.size / analysis.quota_limit_bytes) * 100).toFixed(2) + "%";
672
+ const rows = [
673
+ ["Size", fmtBytes(node.size)],
674
+ ["% of Layer", layerPct],
675
+ ["% of 250 MB Quota", quotaPct],
676
+ ["Files", String(node.file_count || 0)],
677
+ ["Native (.so)", fmtBytes(node.native_bytes || 0)]
678
+ ];
679
+ rows.forEach(function (r) {
680
+ const row = el("div", "tt-row");
681
+ row.appendChild(el("span", null, r[0]));
682
+ row.appendChild(el("strong", null, r[1]));
683
+ tooltip.appendChild(row);
684
+ });
685
+ tooltip.style.display = "block";
686
+ moveTooltip(ev);
687
+ }
688
+ function moveTooltip(ev) {
689
+ const pad = 14;
690
+ const tx = Math.min(window.innerWidth - 330, ev.clientX + pad);
691
+ const ty = Math.min(window.innerHeight - 150, ev.clientY + pad);
692
+ tooltip.style.left = Math.max(8, tx) + "px";
693
+ tooltip.style.top = Math.max(8, ty) + "px";
694
+ }
695
+ function hideTooltip() {
696
+ tooltip.style.display = "none";
697
+ }
698
+
699
+ function renderBreadcrumbs() {
700
+ const bc = document.getElementById("breadcrumbs");
701
+ bc.textContent = "";
702
+ pathStack.forEach(function (node, idx) {
703
+ const btn = el("button", "crumb" + (idx === pathStack.length - 1 ? " active" : ""), node.name);
704
+ btn.type = "button";
705
+ if (idx < pathStack.length - 1) {
706
+ btn.addEventListener("click", function () {
707
+ pathStack = pathStack.slice(0, idx + 1);
708
+ renderAll();
709
+ });
710
+ }
711
+ bc.appendChild(btn);
712
+ });
713
+ }
714
+
715
+ function renderTreemap() {
716
+ const container = document.getElementById("treemap");
717
+ container.textContent = "";
718
+ const current = pathStack[pathStack.length - 1];
719
+ const children = (current.children || []).slice();
720
+ if (!children.length) {
721
+ container.appendChild(el("div", "empty-state", "No sub-items inside " + current.name));
722
+ return;
723
+ }
724
+
725
+ const rect = container.getBoundingClientRect();
726
+ const rects = squarify(children, 0, 0, rect.width, rect.height);
727
+ const q = searchQuery.trim().toLowerCase();
728
+
729
+ rects.forEach(function (r, idx) {
730
+ const tile = el("div", "tile");
731
+ tile.style.left = r.x + "px";
732
+ tile.style.top = r.y + "px";
733
+ tile.style.width = Math.max(0, r.w) + "px";
734
+ tile.style.height = Math.max(0, r.h) + "px";
735
+ tile.style.background = PALETTE[idx % PALETTE.length];
736
+
737
+ if (q && !r.node.name.toLowerCase().includes(q)) {
738
+ tile.classList.add("dimmed");
739
+ }
740
+
741
+ if (r.w > 46 && r.h > 24) {
742
+ tile.appendChild(el("div", "tile-title", r.node.name));
743
+ if (r.h > 40) {
744
+ tile.appendChild(el("div", "tile-size", fmtBytes(r.node.size)));
745
+ }
746
+ }
747
+
748
+ tile.addEventListener("mouseenter", function (ev) { showTooltip(ev, r.node); });
749
+ tile.addEventListener("mousemove", moveTooltip);
750
+ tile.addEventListener("mouseleave", hideTooltip);
751
+ tile.addEventListener("click", function () {
752
+ if (r.node.children && r.node.children.length > 0) {
753
+ hideTooltip();
754
+ pathStack.push(r.node);
755
+ renderAll();
756
+ }
757
+ });
758
+
759
+ container.appendChild(tile);
760
+ });
761
+ }
762
+
763
+ function renderTable() {
764
+ const tbody = document.getElementById("pkg-tbody");
765
+ tbody.textContent = "";
766
+ const q = searchQuery.trim().toLowerCase();
767
+ const filtered = analysis.packages.filter(function (p) {
768
+ return !q || p.name.toLowerCase().includes(q);
769
+ });
770
+ filtered.sort(function (a, b) {
771
+ const av = a[sortCol] || "";
772
+ const bv = b[sortCol] || "";
773
+ if (typeof av === "number" && typeof bv === "number") {
774
+ return sortAsc ? av - bv : bv - av;
775
+ }
776
+ return sortAsc
777
+ ? String(av).localeCompare(String(bv))
778
+ : String(bv).localeCompare(String(av));
779
+ });
780
+
781
+ document.getElementById("table-count").textContent =
782
+ filtered.length + " of " + analysis.packages.length + " packages";
783
+
784
+ filtered.forEach(function (pkg) {
785
+ const tr = document.createElement("tr");
786
+ tr.appendChild(el("td", null, pkg.name));
787
+ tr.appendChild(el("td", null, pkg.version || "-"));
788
+ tr.appendChild(el("td", "num", fmtBytes(pkg.size)));
789
+ tr.appendChild(el("td", "num", pkg.percent + "%"));
790
+ tr.appendChild(el("td", "num", String(pkg.file_count)));
791
+ tr.appendChild(el("td", "num", fmtBytes(pkg.native_bytes)));
792
+
793
+ const barTd = el("td", "bar-cell");
794
+ const miniBar = el("div", "mini-bar");
795
+ const fill = document.createElement("div");
796
+ fill.style.width = Math.min(100, pkg.percent) + "%";
797
+ miniBar.appendChild(fill);
798
+ barTd.appendChild(miniBar);
799
+ tr.appendChild(barTd);
800
+
801
+ tr.addEventListener("click", function () {
802
+ if (pkg.children && pkg.children.length > 0) {
803
+ pathStack = [rootNode, pkg];
804
+ renderAll();
805
+ window.scrollTo({ top: 0, behavior: "smooth" });
806
+ }
807
+ });
808
+ tbody.appendChild(tr);
809
+ });
810
+ }
811
+
812
+ function renderAll() {
813
+ renderBreadcrumbs();
814
+ renderTreemap();
815
+ renderTable();
816
+ }
817
+
818
+ document.getElementById("search").addEventListener("input", function (ev) {
819
+ searchQuery = ev.target.value;
820
+ renderTreemap();
821
+ renderTable();
822
+ });
823
+
824
+ document.querySelectorAll("th[data-sort]").forEach(function (th) {
825
+ th.addEventListener("click", function () {
826
+ const col = th.getAttribute("data-sort");
827
+ if (sortCol === col) {
828
+ sortAsc = !sortAsc;
829
+ } else {
830
+ sortCol = col;
831
+ sortAsc = col === "name" || col === "version";
832
+ }
833
+ renderTable();
834
+ });
835
+ });
836
+
837
+ window.addEventListener("resize", renderTreemap);
838
+ renderAll();
839
+ })();
840
+ </script>
841
+ </body>
842
+ </html>
843
+ """
@@ -2,14 +2,21 @@ import os
2
2
  import shutil
3
3
  import subprocess
4
4
  import sys
5
+ import time
5
6
  from pathlib import Path
6
7
 
7
8
  import boto3
8
9
 
10
+ try:
11
+ from . import analyzer
12
+ except ImportError: # pragma: no cover - flat Lambda /var/task layout
13
+ import analyzer # type: ignore[no-redef]
14
+
9
15
  _REQUIREMENTS_FILE = Path("/var/task/requirements.txt")
10
16
  _BUILD_ROOT = Path("/tmp/build")
11
17
  _ZIP_BASE = Path("/tmp/deps")
12
18
  _ZIP_PATH = _ZIP_BASE.with_suffix(".zip")
19
+ _REPORT_PATH = Path("/tmp/layer-analysis.html")
13
20
 
14
21
  _BUNDLED_UV = Path("/var/task/bin/uv")
15
22
  _WARM_UV_DIR = Path("/tmp/uv_tool")
@@ -155,6 +162,16 @@ def handler(event, context):
155
162
  build_engine = os.environ.get("BUILD_ENGINE", "uv").lower()
156
163
  uv_package_spec = os.environ.get("UV_PACKAGE_SPEC", "uv")
157
164
  fallback_to_pip = os.environ.get("FALLBACK_TO_PIP", "1").lower() in ("1", "true", "yes")
165
+ generate_size_report = os.environ.get("GENERATE_SIZE_REPORT", "0").lower() in (
166
+ "1",
167
+ "true",
168
+ "yes",
169
+ )
170
+ report_object_key = os.environ.get("REPORT_OBJECT_KEY", "")
171
+ target_runtime = os.environ.get("TARGET_RUNTIME", "")
172
+ target_architecture = os.environ.get("TARGET_ARCHITECTURE", "")
173
+
174
+ start_time = time.monotonic()
158
175
 
159
176
  # Warm-container reuse can leave previous installs on /tmp; start clean so the
160
177
  # produced zip reflects only the current requirements.txt.
@@ -188,13 +205,54 @@ def handler(event, context):
188
205
  "pip install produced no files; requirements.txt is empty or matched no packages"
189
206
  )
190
207
 
208
+ should_report = generate_size_report and bool(report_object_key)
209
+ analysis = analyzer.analyze_directory(target) if should_report else None
210
+
191
211
  shutil.make_archive(str(_ZIP_BASE), "zip", root_dir=str(_BUILD_ROOT), base_dir="python")
212
+ zip_size = _ZIP_PATH.stat().st_size
192
213
 
193
- boto3.client("s3").upload_file(str(_ZIP_PATH), bucket_name, object_key)
214
+ s3_client = boto3.client("s3")
215
+ s3_client.upload_file(str(_ZIP_PATH), bucket_name, object_key)
194
216
 
195
- return {
217
+ result = {
196
218
  "bucket": bucket_name,
197
219
  "key": object_key,
198
- "size": _ZIP_PATH.stat().st_size,
220
+ "size": zip_size,
199
221
  "engine": used_engine,
200
222
  }
223
+
224
+ if should_report and analysis is not None:
225
+ duration_sec = round(time.monotonic() - start_time, 2)
226
+ html_report = analyzer.render_treemap_html(
227
+ analysis,
228
+ zip_bytes=zip_size,
229
+ metadata={
230
+ "runtime": target_runtime,
231
+ "architecture": target_architecture,
232
+ "engine": used_engine,
233
+ "build_duration_sec": duration_sec,
234
+ "bucket": bucket_name,
235
+ "object_key": object_key,
236
+ },
237
+ )
238
+ _REPORT_PATH.write_text(html_report, encoding="utf-8")
239
+ s3_client.upload_file(
240
+ str(_REPORT_PATH),
241
+ bucket_name,
242
+ report_object_key,
243
+ ExtraArgs={"ContentType": "text/html; charset=utf-8"},
244
+ )
245
+ unzipped_mb = analysis["total_unzipped_bytes"] / (1024 * 1024)
246
+ zipped_mb = zip_size / (1024 * 1024)
247
+ print(
248
+ f"[INFO] Layer size: {unzipped_mb:.2f} MB unzipped "
249
+ f"({analysis['quota_percent']}% of 250 MB limit), "
250
+ f"{zipped_mb:.2f} MB zipped across {analysis['package_count']} packages. "
251
+ f"Report: s3://{bucket_name}/{report_object_key} "
252
+ f"(download: aws s3 cp s3://{bucket_name}/{report_object_key} ./layer-analysis.html)"
253
+ )
254
+ result["report_key"] = report_object_key
255
+ result["unzipped_size"] = analysis["total_unzipped_bytes"]
256
+ result["package_count"] = analysis["package_count"]
257
+
258
+ return result
@@ -4,7 +4,7 @@ import tempfile
4
4
  from pathlib import Path
5
5
  from typing import Optional, List, Literal
6
6
 
7
- from aws_cdk import Duration, RemovalPolicy, Size
7
+ from aws_cdk import CfnOutput, Duration, RemovalPolicy, Size
8
8
  from aws_cdk import aws_lambda as lambda_
9
9
  from aws_cdk import aws_s3 as s3
10
10
  from aws_cdk import triggers
@@ -49,6 +49,12 @@ class LambdaDepsBuilder(Construct):
49
49
  installation.
50
50
  :param fallback_to_pip: whether to fall back to standard pip install if uv installation
51
51
  or execution fails inside Lambda. Defaults to True.
52
+ :param generate_size_report: whether to analyze installed package sizes inside Lambda
53
+ and upload a self-contained interactive HTML treemap report to S3. Defaults to True.
54
+ :param report_output_key: S3 key for the HTML treemap report. Defaults to
55
+ ``layer-analysis-{ARCH}-{construct_id}.html``.
56
+ :param emit_report_cfn_output: whether to emit a CloudFormation Output containing the
57
+ S3 URI of the generated HTML treemap report. Defaults to True.
52
58
  """
53
59
 
54
60
  def __init__(
@@ -68,6 +74,9 @@ class LambdaDepsBuilder(Construct):
68
74
  uv_package_spec: str = "uv",
69
75
  uv_binary_path: Optional[Path] = None,
70
76
  fallback_to_pip: bool = True,
77
+ generate_size_report: bool = True,
78
+ report_output_key: Optional[str] = None,
79
+ emit_report_cfn_output: bool = True,
71
80
  ) -> None:
72
81
  super().__init__(scope, construct_id)
73
82
 
@@ -94,6 +103,16 @@ class LambdaDepsBuilder(Construct):
94
103
  self._build_engine = build_engine
95
104
  self._uv_package_spec = uv_package_spec
96
105
  self._fallback_to_pip = fallback_to_pip
106
+ self._generate_size_report = generate_size_report
107
+ self._report_key: Optional[str] = (
108
+ (
109
+ report_output_key
110
+ if report_output_key is not None
111
+ else f"layer-analysis-{target_architecture.name}-{construct_id}.html"
112
+ )
113
+ if generate_size_report
114
+ else None
115
+ )
97
116
 
98
117
  if deps_bucket is None:
99
118
  deps_bucket = s3.Bucket(
@@ -110,6 +129,19 @@ class LambdaDepsBuilder(Construct):
110
129
  requirements_txt_file, uv_binary_path=uv_binary_path
111
130
  )
112
131
 
132
+ trigger_env = {
133
+ "BUCKET_NAME": deps_bucket.bucket_name,
134
+ "OBJECT_KEY": self._deps_key,
135
+ "BUILD_ENGINE": self._build_engine,
136
+ "UV_PACKAGE_SPEC": self._uv_package_spec,
137
+ "FALLBACK_TO_PIP": "1" if self._fallback_to_pip else "0",
138
+ "GENERATE_SIZE_REPORT": "1" if self._generate_size_report else "0",
139
+ "TARGET_RUNTIME": target_runtime.name,
140
+ "TARGET_ARCHITECTURE": target_architecture.name,
141
+ }
142
+ if self._report_key is not None:
143
+ trigger_env["REPORT_OBJECT_KEY"] = self._report_key
144
+
113
145
  self._trigger = triggers.TriggerFunction(
114
146
  self,
115
147
  "Builder",
@@ -120,15 +152,23 @@ class LambdaDepsBuilder(Construct):
120
152
  timeout=build_timeout,
121
153
  memory_size=build_memory_mb,
122
154
  ephemeral_storage_size=Size.gibibytes(ephemeral_storage_gib),
123
- environment={
124
- "BUCKET_NAME": deps_bucket.bucket_name,
125
- "OBJECT_KEY": self._deps_key,
126
- "BUILD_ENGINE": self._build_engine,
127
- "UV_PACKAGE_SPEC": self._uv_package_spec,
128
- "FALLBACK_TO_PIP": "1" if self._fallback_to_pip else "0",
129
- },
155
+ environment=trigger_env,
130
156
  )
131
157
  deps_bucket.grant_put(self._trigger, objects_key_pattern=self._deps_key)
158
+ if self._report_key is not None:
159
+ deps_bucket.grant_put(self._trigger, objects_key_pattern=self._report_key)
160
+
161
+ if (
162
+ self._generate_size_report
163
+ and emit_report_cfn_output
164
+ and self._report_key is not None
165
+ ):
166
+ CfnOutput(
167
+ self,
168
+ "LayerAnalysisReportUri",
169
+ value=f"s3://{deps_bucket.bucket_name}/{self._report_key}",
170
+ description="S3 URI of the interactive HTML layer size treemap report",
171
+ )
132
172
 
133
173
  @property
134
174
  def target_architecture(self) -> lambda_.Architecture:
@@ -158,6 +198,20 @@ class LambdaDepsBuilder(Construct):
158
198
  def fallback_to_pip(self) -> bool:
159
199
  return self._fallback_to_pip
160
200
 
201
+ @property
202
+ def generate_size_report(self) -> bool:
203
+ return self._generate_size_report
204
+
205
+ @property
206
+ def report_key(self) -> Optional[str]:
207
+ return self._report_key
208
+
209
+ @property
210
+ def report_s3_uri(self) -> Optional[str]:
211
+ if self._report_key is None:
212
+ return None
213
+ return f"s3://{self._deps_bucket.bucket_name}/{self._report_key}"
214
+
161
215
  def as_layer_version(
162
216
  self,
163
217
  scope: Construct,
@@ -231,6 +285,7 @@ def _stage_handler_asset(
231
285
  staged_dir = Path(tempfile.mkdtemp(prefix="lambda-deps-builder-"))
232
286
  atexit.register(shutil.rmtree, staged_dir, ignore_errors=True)
233
287
  shutil.copy(_HANDLER_SOURCE_DIR / "handler.py", staged_dir / "handler.py")
288
+ shutil.copy(_HANDLER_SOURCE_DIR / "analyzer.py", staged_dir / "analyzer.py")
234
289
  shutil.copy(requirements_txt_file, staged_dir / "requirements.txt")
235
290
  if uv_binary_path is not None:
236
291
  bin_dir = staged_dir / "bin"
@@ -26,6 +26,7 @@ class ExampleStack(Stack):
26
26
  block_public_access=s3.BlockPublicAccess.BLOCK_ALL,
27
27
  enforce_ssl=True,
28
28
  )
29
+ CfnOutput(self, "DepsBucketName", value=shared_bucket.bucket_name)
29
30
 
30
31
  for arch_name, arch in [
31
32
  ("X86", lambda_.Architecture.X86_64),
@@ -41,6 +42,9 @@ class ExampleStack(Stack):
41
42
  )
42
43
  layer = builder.as_layer_version(self, f"RequestsLayer{arch_name}")
43
44
 
45
+ if builder.report_key is not None:
46
+ CfnOutput(self, f"ReportKey{arch_name}", value=builder.report_key)
47
+
44
48
  consumer = lambda_.Function(
45
49
  self,
46
50
  f"Consumer{arch_name}",
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "lambda-deps-builder"
3
- version = "0.2.0"
3
+ version = "0.3.0"
4
4
  description = "CDK construct that builds Python Lambda dependencies inside Lambda — no local Docker."
5
5
  authors = ["Alexy Grabov <alexy.grabov@gmail.com>"]
6
6
  license = "Apache-2.0"