-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_pdf.py
More file actions
620 lines (562 loc) Β· 35.5 KB
/
Copy pathgenerate_pdf.py
File metadata and controls
620 lines (562 loc) Β· 35.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
#!/usr/bin/env python3
"""Generate the spec PDF with embedded mockups via Playwright."""
import base64
import os
from playwright.sync_api import sync_playwright
BASE = "/root/projects/runs/b8eb8e1a-fb09-4fdf-bd9a-7f73f91733bf"
ATTACHMENTS = os.path.join(BASE, "attachments")
# Read and base64-encode all mockup PNGs
mockup_data = {}
for letter, slug in [
("A", "idle-state"),
("B", "webhook-received"),
("C", "validation"),
("D", "logging"),
("E", "success"),
("F", "health-check"),
("G", "error"),
]:
path = os.path.join(ATTACHMENTS, f"mockup-{letter.lower()}-{slug}.png")
with open(path, "rb") as f:
mockup_data[letter] = base64.b64encode(f.read()).decode("ascii")
def mockup_img(letter, caption):
return f'''
<div class="mockup-frame">
<img src="data:image/png;base64,{mockup_data[letter]}" style="width:100%;display:block;">
<div class="mockup-caption">{caption}</div>
</div>'''
html = f'''<!DOCTYPE html>
<html><head>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>
*, *::before, *::after {{ box-sizing: border-box; margin: 0; padding: 0; }}
body {{ font-family: 'Inter', system-ui, sans-serif; font-size: 13px; color: #1a1a2e; line-height: 1.6; }}
.cover {{ background: linear-gradient(135deg, #0f0c29 0%, #302b63 50%, #24243e 100%); color: #fff; height: 297mm; display: flex; flex-direction: column; justify-content: center; align-items: flex-start; padding: 60px 64px; page-break-after: always; }}
.cover h1 {{ font-size: 42px; font-weight: 700; line-height: 1.2; }}
.cover h1 span {{ color: #818cf8; }}
.cover .subtitle {{ font-size: 16px; color: rgba(255,255,255,0.7); margin-top: 16px; }}
.cover .meta {{ font-size: 12px; color: rgba(255,255,255,0.5); margin-top: 32px; }}
.page {{ padding: 28px 40px; }}
.page-break {{ page-break-before: always; }}
h1.section-title {{ font-size: 26px; font-weight: 700; color: #1e1b4b; border-bottom: 3px solid #6366f1; padding-bottom: 10px; margin: 32px 0 20px; }}
h2 {{ font-size: 16px; font-weight: 600; color: #312e81; margin: 28px 0 12px; border-left: 4px solid #6366f1; padding-left: 12px; }}
h3 {{ font-size: 14px; font-weight: 600; color: #4338ca; margin: 20px 0 8px; }}
pre {{ background: #1e1b4b; color: #c7d2fe; font-family: 'JetBrains Mono', monospace; font-size: 10.5px; padding: 16px 18px; border-radius: 8px; margin: 12px 0; line-height: 1.55; overflow-x: auto; }}
table {{ width: 100%; border-collapse: collapse; margin: 14px 0; font-size: 12px; }}
th {{ background: #312e81; color: #e0e7ff; font-weight: 600; padding: 8px 12px; text-align: left; font-size: 11px; }}
td {{ padding: 8px 12px; border-bottom: 1px solid #e5e7eb; vertical-align: top; }}
tr:nth-child(even) td {{ background: #f5f3ff; }}
.badge-ok {{ background: #dcfce7; color: #15803d; font-size: 10px; font-weight: 600; padding: 2px 8px; border-radius: 12px; }}
.badge-warn {{ background: #fef9c3; color: #92400e; font-size: 10px; font-weight: 600; padding: 2px 8px; border-radius: 12px; }}
.badge-fail {{ background: #fee2e2; color: #991b1b; font-size: 10px; font-weight: 600; padding: 2px 8px; border-radius: 12px; }}
.mockup-frame {{ border: 1px solid #e5e7eb; border-radius: 16px; overflow: hidden; box-shadow: 0 8px 30px rgba(0,0,0,0.1); margin: 16px 0; }}
.mockup-caption {{ font-size: 11px; font-weight: 600; color: #6b7280; text-align: center; padding: 10px; background: #f9fafb; border-top: 1px solid #e5e7eb; text-transform: uppercase; letter-spacing: 0.5px; }}
code {{ font-family: 'JetBrains Mono', monospace; font-size: 11px; background: #f1f0ff; color: #4338ca; padding: 1px 5px; border-radius: 4px; }}
.gap-critical {{ background: #fee2e2; border-left: 4px solid #ef4444; padding: 12px 16px; margin: 12px 0; border-radius: 0 8px 8px 0; }}
.gap-minor {{ background: #fef9c3; border-left: 4px solid #f59e0b; padding: 12px 16px; margin: 12px 0; border-radius: 0 8px 8px 0; }}
.checklist li {{ margin: 4px 0; list-style: none; }}
.checklist li::before {{ content: "β"; margin-right: 8px; color: #6366f1; }}
ul {{ padding-left: 0; }}
p {{ margin: 8px 0; }}
</style>
</head><body>
<!-- COVER PAGE -->
<div class="cover">
<h1>Shopify Product Update<br><span>Webhook Service</span></h1>
<div class="subtitle">Technical & Functional Specification</div>
<div class="meta">
Version 1.0 β’ 2025-06-05 β’ Status: Planned<br>
FastAPI β’ structlog β’ Docker β’ Python 3.12
</div>
</div>
<!-- TABLE OF CONTENTS -->
<div class="page page-break">
<h1 class="section-title">Table of Contents</h1>
<ol style="font-size:13px;line-height:2.2;">
<li>Feature Overview</li>
<li>Architecture Diagram</li>
<li>Component Map</li>
<li>API Reference</li>
<li>Data Schema</li>
<li>Protocol / Event Reference</li>
<li>State Machine</li>
<li>Message / Data Flow Diagrams</li>
<li>Visual Mockups</li>
<li>Implementation Status</li>
<li>Gap Analysis</li>
<li>Testing Requirements</li>
<li>Test Coverage Map</li>
<li>Known Edge Cases</li>
<li>Acceptance Criteria</li>
<li>Out of Scope</li>
<li>Open Questions</li>
<li>Persistence / Session Behaviour</li>
</ol>
</div>
<!-- SECTION 1: Feature Overview -->
<div class="page page-break">
<h1 class="section-title">1. Feature Overview</h1>
<h2>What the feature does</h2>
<p>A lightweight FastAPI service that exposes a single webhook endpoint for Shopify <code>product/update</code> events. When Shopify (or any HTTP client) sends a POST request with a JSON payload to <code>POST /webhooks/shopify/product-update</code>, the service:</p>
<ol>
<li>Validates the payload against a Pydantic model (top-level Shopify product fields only).</li>
<li>Logs the entire payload as a single structured JSON line via <code>structlog</code>.</li>
<li>Returns <code>200 OK</code> with a minimal JSON body.</li>
</ol>
<p>A companion <code>GET /health</code> endpoint returns <code>200 OK</code> for container health checks and load-balancer probes.</p>
<p>The service runs inside a production-grade Docker container built with a multi-stage Dockerfile, runs as a non-root user, pins all dependency versions, and includes a <code>HEALTHCHECK</code> instruction.</p>
<h2>End-to-end user journey</h2>
<ol>
<li>Shopify sends a <code>product/update</code> webhook POST to the service's <code>/webhooks/shopify/product-update</code> endpoint.</li>
<li>Uvicorn receives the request and routes it to the FastAPI app.</li>
<li>The Pydantic model validates the top-level fields of the JSON payload.</li>
<li>If validation passes, <code>structlog</code> emits a single structured JSON log line containing the full payload plus metadata (timestamp, event type, product ID).</li>
<li>The service returns <code>200 OK</code> with body <code>{"status": "received"}</code>.</li>
<li>If validation fails, the service returns <code>422 Unprocessable Entity</code> with FastAPI's standard validation error detail.</li>
<li>A Docker <code>HEALTHCHECK</code> periodically hits <code>GET /health</code>; the endpoint returns <code>200 OK</code> with body <code>{"status": "ok"}</code>.</li>
</ol>
<h2>Key design decisions</h2>
<table>
<tr><th>Decision</th><th>Rationale</th></tr>
<tr><td>Skip HMAC verification</td><td>Per user clarification β simplifies initial deployment; can be added later as middleware</td></tr>
<tr><td>Pydantic model validates top-level fields only</td><td>Shopify's product schema is large and versioned; strict full validation is fragile and breaks on schema changes</td></tr>
<tr><td><code>structlog</code> for JSON logging</td><td>Single JSON line per event is easy for log shippers (Fluentd, Datadog, CloudWatch) to ingest</td></tr>
<tr><td>Multi-stage Dockerfile</td><td>Smaller final image; build tools not included in runtime image</td></tr>
<tr><td>Non-root user in container</td><td>Security best practice; required by most Kubernetes pod security policies</td></tr>
<tr><td>No database / no retry queue</td><td>Per user clarification β this is a fire-and-forget logging sink</td></tr>
<tr><td><code>GET /health</code> endpoint</td><td>Required for Docker <code>HEALTHCHECK</code> and load-balancer probes</td></tr>
<tr><td>Python 3.12 + pip</td><td>Per user clarification β keeps Dockerfile simpler than Poetry/pdm</td></tr>
</table>
</div>
<!-- SECTION 2: Architecture Diagram -->
<div class="page page-break">
<h1 class="section-title">2. Architecture Diagram</h1>
<pre>
βββββββββββββββββββ
β Shopify β
β (Webhook Sender)β
ββββββββββ¬βββββββββ
β
HTTPS POST (JSON)
β
βΌ
ββββββββββββββββββββββββββ
β Docker Container β
β ββββββββββββββββββββ β
β β Uvicorn β β
β β (ASGI server) β β
β ββββββββββ¬ββββββββββ β
β β β
β ββββββββββΌββββββββββ β
β β FastAPI App β β
β β β β
β β POST /webhooks/ β β
β β shopify/ β β
β β product-update β β
β β β β
β β GET /health β β
β ββββββββββ¬ββββββββββ β
β β β
β ββββββββββΌββββββββββ β
β β structlog β β
β β (JSON stdout) β β
β ββββββββββ¬ββββββββββ β
β β β
β ββββββββββΌββββββββββ β
β β stdout β β
β β (container log)β β
β ββββββββββββββββββββ β
ββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββ
β Log Shipper β
β (Fluentd, β
β CloudWatch, β
β Datadog, etc.)β
βββββββββββββββββββ
</pre>
</div>
<!-- SECTION 3: Component Map -->
<div class="page page-break">
<h1 class="section-title">3. Component Map</h1>
<h2>Backend</h2>
<table>
<tr><th>File path</th><th>Role</th></tr>
<tr><td><code>app/__init__.py</code></td><td>Package marker; empty</td></tr>
<tr><td><code>app/main.py</code></td><td>App factory β creates FastAPI instance, configures structlog, includes routers</td></tr>
<tr><td><code>app/routers/__init__.py</code></td><td>Package marker; empty</td></tr>
<tr><td><code>app/routers/webhooks.py</code></td><td><code>POST /webhooks/shopify/product-update</code> endpoint and Pydantic model</td></tr>
<tr><td><code>app/routers/health.py</code></td><td><code>GET /health</code> endpoint</td></tr>
<tr><td><code>app/models.py</code></td><td>Pydantic models for Shopify product webhook payload</td></tr>
<tr><td><code>app/logging_config.py</code></td><td>structlog configuration β JSON renderer, processor chain</td></tr>
<tr><td><code>Dockerfile</code></td><td>Multi-stage production build</td></tr>
<tr><td><code>requirements.txt</code></td><td>Pinned Python dependencies</td></tr>
<tr><td><code>.dockerignore</code></td><td>Exclude unnecessary files from Docker build context</td></tr>
<tr><td><code>tests/__init__.py</code></td><td>Package marker; empty</td></tr>
<tr><td><code>tests/test_webhooks.py</code></td><td>Unit + integration tests for webhook endpoint</td></tr>
<tr><td><code>tests/test_health.py</code></td><td>Unit tests for health endpoint</td></tr>
<tr><td><code>tests/conftest.py</code></td><td>Shared fixtures (TestClient, etc.)</td></tr>
</table>
</div>
<!-- SECTION 4: API Reference -->
<div class="page page-break">
<h1 class="section-title">4. API Reference</h1>
<h2>POST /webhooks/shopify/product-update</h2>
<p>Receives a Shopify product update webhook payload, validates top-level fields, logs the payload as structured JSON, and returns 200.</p>
<h3>Request Body</h3>
<pre>{{
"id": 123456789,
"title": "Product Title",
"body_html": "<p>Description</p>",
"vendor": "Vendor Name",
"product_type": "Type",
"handle": "product-handle",
"published_at": "2025-01-01T00:00:00-00:00",
"created_at": "2025-01-01T00:00:00-00:00",
"updated_at": "2025-06-05T12:00:00-00:00",
"status": "active",
"variants": [],
"options": [],
"images": [],
"metafields": []
}}</pre>
<h3>Response β 200 OK</h3>
<pre>{{
"status": "received"
}}</pre>
<h3>Response β 422 Unprocessable Entity</h3>
<pre>{{
"detail": [
{{
"loc": ["body", "id"],
"msg": "field required",
"type": "value_error.missing"
}}
]
}}</pre>
<h3>Behaviour</h3>
<table>
<tr><th>Condition</th><th>Result</th></tr>
<tr><td>Valid JSON with required top-level fields</td><td>200, payload logged as structured JSON</td></tr>
<tr><td>Valid JSON but missing required field <code>id</code></td><td>422, FastAPI validation error</td></tr>
<tr><td>Valid JSON but missing optional fields</td><td>200, defaults applied per model</td></tr>
<tr><td>Invalid JSON (malformed body)</td><td>422, FastAPI request parsing error</td></tr>
<tr><td>Empty body</td><td>422, validation error</td></tr>
<tr><td>Request with extra nested fields</td><td>200, extra fields passed through to log (<code>extra="allow"</code>)</td></tr>
</table>
<h2>GET /health</h2>
<p>Health check endpoint for Docker <code>HEALTHCHECK</code> and load-balancer probes.</p>
<h3>Response β 200 OK</h3>
<pre>{{
"status": "ok"
}}</pre>
</div>
<!-- SECTION 5: Data Schema -->
<div class="page page-break">
<h1 class="section-title">5. Data Schema</h1>
<h2>Pydantic Model β ShopifyProductUpdatePayload</h2>
<pre>class ShopifyProductUpdatePayload(BaseModel):
model_config = ConfigDict(extra="allow")
id: int # Shopify product ID (required)
title: str # Product title (required)
body_html: str | None = None # HTML description
vendor: str | None = None # Vendor name
product_type: str | None = None # Product type
handle: str | None = None # URL handle
published_at: str | None = None # ISO 8601 datetime
created_at: str | None = None # ISO 8601 datetime
updated_at: str | None = None # ISO 8601 datetime
status: str | None = None # active, draft, archived
tags: str | None = None # Comma-separated tag string</pre>
<p>Only <code>id</code> and <code>title</code> are required β all other fields are optional with <code>None</code> defaults. <code>extra="allow"</code> β Shopify webhooks frequently include additional fields that are passed through to the log without validation. Nested objects (<code>variants</code>, <code>options</code>, <code>images</code>, <code>metafields</code>) are NOT modelled.</p>
<h2>Log Output Schema</h2>
<p>Each log line is a JSON object:</p>
<pre>{{
"event": "shopify.product_update",
"timestamp": "2025-06-05T12:00:00.000000Z",
"level": "info",
"product_id": 123456789,
"title": "Product Title",
"payload": {{ ... }}
}}</pre>
<table>
<tr><th>Field</th><th>Type</th><th>Description</th></tr>
<tr><td><code>event</code></td><td><code>str</code></td><td>Constant <code>"shopify.product_update"</code></td></tr>
<tr><td><code>timestamp</code></td><td><code>str</code></td><td>ISO 8601 UTC timestamp</td></tr>
<tr><td><code>level</code></td><td><code>str</code></td><td>Log level (<code>info</code>, <code>warning</code>, <code>error</code>)</td></tr>
<tr><td><code>product_id</code></td><td><code>int</code></td><td>Extracted from <code>payload.id</code> for quick filtering</td></tr>
<tr><td><code>title</code></td><td><code>str</code></td><td>Extracted from <code>payload.title</code> for quick filtering</td></tr>
<tr><td><code>payload</code></td><td><code>object</code></td><td>Full webhook payload as received</td></tr>
</table>
<h2>Redis / Database</h2>
<p>N/A β no persistence layer.</p>
</div>
<!-- SECTION 7: State Machine -->
<div class="page page-break">
<h1 class="section-title">7. State Machine</h1>
<p>This service is stateless. The per-request lifecycle is:</p>
<pre>
[Request Received] βββ [Parse JSON Body] βββ [Validate Pydantic Model]
β
ββββββββββββββββ΄βββββββββββββββ
β β
Valid Invalid
β β
βΌ βΌ
[Log via structlog] [422 Validation Error]
β
βΌ
[200 OK Response]
</pre>
</div>
<!-- SECTION 8: Data Flow Diagrams -->
<div class="page page-break">
<h1 class="section-title">8. Message / Data Flow Diagrams</h1>
<h2>Normal happy path β product update webhook</h2>
<pre>
Shopify Uvicorn FastAPI structlog stdout
β β β β β
β POST /webhooks/ β β β β
β shopify/ β β β β
β product-update β β β β
ββββββββββββββββββββββββ β β β
β β route to β β β
β β webhook handler β β β
β βββββββββββββββββββββ β β
β β β validate β β
β β β payload β β
β β ββββββββ β β
β β β β valid β β
β β ββββββββ β β
β β β log payload β β
β β βββββββββββββββββββββ β
β β β β JSON line β
β β β βββββββββββββββββββ
β β β return 200 β β
β βββββββββββββββββββββ β β
β 200 OK β β β β
ββββββββββββββββββββββββ β β β
</pre>
<h2>Error path β invalid payload</h2>
<pre>
Client Uvicorn FastAPI
β β β
β POST (invalid JSON) β β
ββββββββββββββββββββββββ β
β β route to β
β β webhook handler β
β βββββββββββββββββββββ
β β β validate
β β ββββββββ
β β β β invalid
β β ββββββββ
β β 422 error β
β βββββββββββββββββββββ
β 422 Unprocessable β β
ββββββββββββββββββββββββ β
</pre>
</div>
<!-- SECTION 9: Visual Mockups -->
<div class="page page-break">
<h1 class="section-title">9. Visual Mockups</h1>
<p>As a backend-only service with no user interface, mockups are rendered as flow diagrams showing system states and data flows.</p>
<h3>A β Default / Idle State</h3>
<p>Service is running, listening on port 8080, no active requests.</p>
{mockup_img("A", "A β Default / Idle State")}
<h3>B β Webhook Received</h3>
<p>A POST request arrives at the webhook endpoint; the service begins parsing and validation.</p>
{mockup_img("B", "B β Webhook Received")}
<div class="page-break"></div>
<h3>C β Validation State</h3>
<p>The Pydantic model is validating the incoming payload against the schema.</p>
{mockup_img("C", "C β Validation State")}
<h3>D β Active / Logging State</h3>
<p>Validation passed; structlog is writing the structured JSON line to stdout.</p>
{mockup_img("D", "D β Active / Logging State")}
<div class="page-break"></div>
<h3>E β Success / Completion State</h3>
<p>200 OK response returned to Shopify; log line emitted to stdout.</p>
{mockup_img("E", "E β Success / Completion State")}
<h3>F β Health Check</h3>
<p>Load balancer or Docker HEALTHCHECK hits GET /health; service responds 200 OK.</p>
{mockup_img("F", "F β Health Check")}
<div class="page-break"></div>
<h3>G β Error State</h3>
<p>Invalid payload fails Pydantic validation; 422 Unprocessable Entity returned.</p>
{mockup_img("G", "G β Error State")}
</div>
<!-- SECTION 10: Implementation Status -->
<div class="page page-break">
<h1 class="section-title">10. Implementation Status</h1>
<table>
<tr><th>Story</th><th>Description</th><th>Status</th><th>Notes</th></tr>
<tr><td>WH-1</td><td>FastAPI app factory with structlog config</td><td><span class="badge-fail">β Not built</span></td><td>Greenfield</td></tr>
<tr><td>WH-2</td><td>POST /webhooks/shopify/product-update endpoint</td><td><span class="badge-fail">β Not built</span></td><td>Greenfield</td></tr>
<tr><td>WH-3</td><td>Pydantic model for Shopify product payload</td><td><span class="badge-fail">β Not built</span></td><td>Greenfield</td></tr>
<tr><td>WH-4</td><td>GET /health endpoint</td><td><span class="badge-fail">β Not built</span></td><td>Greenfield</td></tr>
<tr><td>WH-5</td><td>Production Dockerfile (multi-stage, non-root, healthcheck)</td><td><span class="badge-fail">β Not built</span></td><td>Greenfield</td></tr>
<tr><td>WH-6</td><td>Unit + integration tests</td><td><span class="badge-fail">β Not built</span></td><td>Greenfield</td></tr>
<tr><td>WH-7</td><td>requirements.txt with pinned versions</td><td><span class="badge-fail">β Not built</span></td><td>Greenfield</td></tr>
</table>
</div>
<!-- SECTION 11: Gap Analysis -->
<div class="page page-break">
<h1 class="section-title">11. Gap Analysis</h1>
<div class="gap-critical">
<h3>π΄ GAP-1: No HMAC verification</h3>
<p>Shopify webhooks include an <code>X-Shopify-Hmac-Sha256</code> header for request authenticity. Skipping it means any client can send payloads to the endpoint.</p>
<p><strong>Recommended fix:</strong> Add optional HMAC verification middleware in a future iteration. Configurable via environment variable <code>VERIFY_HMAC=true|false</code> so it can be enabled without code changes. The HMAC secret should be read from <code>SHOPIFY_HMAC_SECRET</code> env var.</p>
</div>
<div class="gap-minor">
<h3>π‘ GAP-2: No rate limiting</h3>
<p>Without rate limiting, the endpoint is vulnerable to abuse or accidental flood (e.g., a Shopify misconfiguration sending thousands of updates).</p>
<p><strong>Recommended fix:</strong> Add an in-memory rate limiter (e.g., <code>slowapi</code>) configurable via <code>RATE_LIMIT</code> env var. Default: 100 requests/minute.</p>
</div>
<div class="gap-minor">
<h3>π‘ GAP-3: No request ID / correlation ID</h3>
<p>Log lines have no request-level correlation ID, making it hard to trace a single webhook through downstream systems (if added later).</p>
<p><strong>Recommended fix:</strong> Add a <code>request_id</code> field to every log entry. Generate UUID4 per request, or read from <code>X-Request-ID</code> header if provided.</p>
</div>
<div class="gap-minor">
<h3>π‘ GAP-4: No graceful shutdown handling</h3>
<p>Uvicorn's default shutdown may drop in-flight requests.</p>
<p><strong>Recommended fix:</strong> Configure Uvicorn with <code>--graceful-timeout 5</code> and handle <code>SIGTERM</code> to drain connections before exiting.</p>
</div>
</div>
<!-- SECTION 12: Testing Requirements -->
<div class="page page-break">
<h1 class="section-title">12. Testing Requirements</h1>
<h2>Unit Tests</h2>
<table>
<tr><th>Test</th><th>File</th><th>Assertions</th></tr>
<tr><td><code>test_webhook_valid_payload</code></td><td><code>tests/test_webhooks.py</code></td><td>POST with valid top-level fields returns 200; body contains <code>{"status": "received"}</code></td></tr>
<tr><td><code>test_webhook_minimal_payload</code></td><td><code>tests/test_webhooks.py</code></td><td>POST with only <code>id</code> and <code>title</code> returns 200</td></tr>
<tr><td><code>test_webhook_missing_id</code></td><td><code>tests/test_webhooks.py</code></td><td>POST without <code>id</code> field returns 422; error detail mentions <code>id</code></td></tr>
<tr><td><code>test_webhook_missing_title</code></td><td><code>tests/test_webhooks.py</code></td><td>POST without <code>title</code> field returns 422; error detail mentions <code>title</code></td></tr>
<tr><td><code>test_webhook_extra_fields_allowed</code></td><td><code>tests/test_webhooks.py</code></td><td>POST with extra nested fields returns 200; extra fields not rejected</td></tr>
<tr><td><code>test_webhook_invalid_json</code></td><td><code>tests/test_webhooks.py</code></td><td>POST with malformed JSON body returns 422</td></tr>
<tr><td><code>test_webhook_empty_body</code></td><td><code>tests/test_webhooks.py</code></td><td>POST with empty body returns 422</td></tr>
<tr><td><code>test_webhook_logs_payload</code></td><td><code>tests/test_webhooks.py</code></td><td>POST with valid payload causes structlog to emit a log line with <code>event=shopify.product_update</code>, correct <code>product_id</code>, and full <code>payload</code></td></tr>
<tr><td><code>test_health_endpoint</code></td><td><code>tests/test_health.py</code></td><td>GET /health returns 200 with <code>{"status": "ok"}</code></td></tr>
<tr><td><code>test_health_method_not_allowed</code></td><td><code>tests/test_health.py</code></td><td>POST /health returns 405 Method Not Allowed</td></tr>
</table>
<h2>E2E Browser Tests</h2>
<p>N/A β this is a pure backend API service with no browser UI. All testing is done via HTTP requests using <code>httpx</code>/<code>TestClient</code>.</p>
<h2>Test Infrastructure</h2>
<ul>
<li><strong>Framework:</strong> <code>pytest</code> with <code>httpx</code> (via FastAPI <code>TestClient</code>)</li>
<li><strong>Location:</strong> <code>tests/</code> directory at project root</li>
<li><strong>Run command:</strong> <code>docker run --rm <image> pytest tests/ -v</code> or <code>pytest tests/ -v</code> locally</li>
<li><strong>CI-runnable:</strong> Yes β all tests are unit/integration via <code>TestClient</code>, no external dependencies</li>
<li><strong>structlog capture:</strong> Use <code>capfd</code> or a custom structlog processor to capture log output in tests</li>
</ul>
</div>
<!-- SECTION 13: Test Coverage Map -->
<div class="page page-break">
<h1 class="section-title">13. Test Coverage Map</h1>
<table>
<tr><th>Test File</th><th>What it covers</th><th>Status</th></tr>
<tr><td><code>tests/test_webhooks.py</code></td><td>Webhook endpoint validation, response codes, logging</td><td><span class="badge-fail">β Missing</span></td></tr>
<tr><td><code>tests/test_health.py</code></td><td>Health endpoint response</td><td><span class="badge-fail">β Missing</span></td></tr>
<tr><td><code>tests/conftest.py</code></td><td>Shared fixtures (TestClient)</td><td><span class="badge-fail">β Missing</span></td></tr>
</table>
<h2>Coverage Summary</h2>
<table>
<tr><th>Area</th><th>Coverage Level</th></tr>
<tr><td>Webhook endpoint β valid payloads</td><td><span class="badge-fail">β Not tested</span></td></tr>
<tr><td>Webhook endpoint β invalid payloads</td><td><span class="badge-fail">β Not tested</span></td></tr>
<tr><td>Webhook endpoint β logging output</td><td><span class="badge-fail">β Not tested</span></td></tr>
<tr><td>Health endpoint</td><td><span class="badge-fail">β Not tested</span></td></tr>
<tr><td>Docker build</td><td><span class="badge-fail">β Not tested</span> (manual)</td></tr>
</table>
</div>
<!-- SECTION 14: Known Edge Cases -->
<div class="page page-break">
<h1 class="section-title">14. Known Edge Cases</h1>
<table>
<tr><th>Case</th><th>Current Handling</th></tr>
<tr><td>Very large payload (>1 MB)</td><td>Uvicorn default limits apply; no explicit cap configured. Could cause memory issues under sustained high volume.</td></tr>
<tr><td>Payload with null <code>id</code></td><td>Pydantic rejects β <code>id</code> is <code>int</code> (required), <code>null</code> fails validation β 422</td></tr>
<tr><td>Payload with string <code>id</code> instead of int</td><td>Pydantic rejects β type mismatch β 422</td></tr>
<tr><td>Payload with nested variants/images containing thousands of items</td><td>Accepted (<code>extra="allow"</code>), logged as-is. Could produce very large log lines.</td></tr>
<tr><td>Concurrent requests</td><td>Uvicorn handles async; no locking needed (stateless)</td></tr>
<tr><td>Missing <code>Content-Type: application/json</code></td><td>FastAPI still parses body as JSON if valid; otherwise 422</td></tr>
<tr><td>Shopify retries webhook (if we returned non-200)</td><td>Not applicable β service always returns 200 for valid payloads; no downstream failures possible</td></tr>
<tr><td>Container OOM under high load</td><td>No memory limit in Dockerfile; rely on orchestrator/resource limits</td></tr>
</table>
</div>
<!-- SECTION 15: Acceptance Criteria -->
<div class="page page-break">
<h1 class="section-title">15. Acceptance Criteria</h1>
<ul class="checklist">
<li>POST /webhooks/shopify/product-update with a valid JSON payload containing id and title returns 200 OK with body {"status": "received"}</li>
<li>POST /webhooks/shopify/product-update logs the full payload as a single structured JSON line via structlog with event="shopify.product_update", product_id, title, and payload fields</li>
<li>POST /webhooks/shopify/product-update with missing id field returns 422 Unprocessable Entity</li>
<li>POST /webhooks/shopify/product-update with missing title field returns 422 Unprocessable Entity</li>
<li>POST /webhooks/shopify/product-update with extra nested fields (variants, images, etc.) returns 200 OK β extra fields are not rejected</li>
<li>POST /webhooks/shopify/product-update with malformed JSON returns 422</li>
<li>GET /health returns 200 OK with body {"status": "ok"}</li>
<li>Dockerfile uses multi-stage build (builder stage + runtime stage)</li>
<li>Dockerfile runs the application as a non-root user</li>
<li>Dockerfile includes a HEALTHCHECK instruction targeting GET /health</li>
<li>All dependency versions in requirements.txt are pinned (e.g., fastapi==0.111.0, not fastapi>=0.111)</li>
<li>Application uses Python 3.12</li>
<li>Application uses structlog for structured JSON logging to stdout</li>
<li>No HMAC verification is performed (per requirement)</li>
<li>No database, no retry queue, no background tasks (per requirement)</li>
<li>All unit tests pass via pytest</li>
</ul>
</div>
<!-- SECTION 16: Out of Scope -->
<div class="page page-break">
<h1 class="section-title">16. Out of Scope</h1>
<ul>
<li>HMAC signature verification β explicitly skipped per user clarification</li>
<li>Any form of persistence (database, file, cache) β fire-and-forget logging only</li>
<li>Retry queue or background task processing</li>
<li>Rate limiting or throttling</li>
<li>Authentication or authorization on the endpoint</li>
<li>Webhook topic verification (verifying the <code>X-Shopify-Topic</code> header)</li>
<li>Webhook deduplication (idempotency keys)</li>
<li>Docker Compose or multi-container orchestration</li>
<li>CI/CD pipeline configuration</li>
<li>Kubernetes manifests or Helm charts</li>
<li>Monitoring / metrics endpoints (Prometheus, etc.)</li>
<li>API documentation UI (Swagger/Redoc) β FastAPI provides this by default; not a deliverable</li>
<li>Internationalization (i18n) β English-only error messages</li>
</ul>
</div>
<!-- SECTION 17: Open Questions -->
<div class="page page-break">
<h1 class="section-title">17. Open Questions</h1>
<table>
<tr><th>#</th><th>Question</th><th>Owner</th></tr>
<tr><td>β</td><td>All clarifications resolved. No open questions.</td><td>β</td></tr>
</table>
</div>
<!-- SECTION 18: Persistence / Session Behaviour -->
<div class="page">
<h1 class="section-title">18. Persistence / Session Behaviour</h1>
<p>N/A β the service is entirely stateless. No data is persisted between requests. Each webhook request is processed independently: validate β log β respond. There is no session state, no cookies, no tokens, and no in-memory caches that survive across requests.</p>
</div>
</body></html>
'''
with sync_playwright() as p:
browser = p.chromium.launch(
executable_path="/usr/local/bin/chromium",
args=["--no-sandbox"],
)
page = browser.new_page()
page.set_content(html, wait_until="networkidle")
page.wait_for_timeout(2000)
out_path = os.path.join(BASE, "spec.pdf")
page.pdf(
path=out_path,
format="A4",
margin={"top": "15mm", "bottom": "15mm", "left": "15mm", "right": "15mm"},
print_background=True,
)
page.close()
browser.close()
print(f"β PDF saved to {out_path}")