Project: E-Commerce API — Services, Handlers, Cart, Orders, SMTP, Events, Swagger
"The easiest way to address inconsistencies in distributed state caused by failures is to implement server endpoints so that they're idempotent, which means that they can be called any number of times while guaranteeing that side effects only occur once." — Brandur Leach، «Designing robust and predictable APIs with idempotency»، وبلاگ Stripe، ۲۲ فوریهٔ ۲۰۱۷
خلاصه (Summary): یک بکاند کامل فروشگاه در Go: کاتالوگ (Catalogue) با صفحهبندی Keyset و جستوجو، سبد سمت سرور که پس از ورود باقی میماند، و ثبت خریدی که در یک تراکنش (Transaction) در PostgreSQL موجودی را رزرو میکند، سفارش و ردیفهایش را میسازد، قصد پرداخت را ثبت میکند و رویداد OrderPlaced را در Outbox مینویسد. ماشین حالت سفارش با Webhookهای امضاشدهٔ پرداخت جلو میرود؛ Relay رویداد را به Bus داخل فرایند یا RabbitMQ میرساند؛ Worker ایمیل تأیید را با SMTP و Retry میفرستد؛ Jobهای پسزمینه مهلت آزادسازی موجودی و سبدهای رهاشده را رسیدگی میکنند؛ و یک تست قرارداد OpenAPI را با کد تطبیق میدهد. تمرکز (Focus): مدل کردن محصول، دسته، کاربر، سبد، سفارش، ردیف سفارش، پرداخت و موجودی؛ مرز Handler، Service و Repository؛ پول با واحد کوچک و قواعد خالص قیمتگذاری؛ Schema و Constraint؛ جلوگیری از فروش اضافه با Transaction و قفل سطر؛ ثبت سفارش Idempotent؛ ماشین حالت، Outbox، go-mail و Template؛ Workerهای پسزمینه؛ احراز هویت و مجوز هر شیء؛ اعتبارسنجی و خطاهای RFC 9457؛ Swagger/OpenAPI، محدودسازی نرخ و Headerهای امنیتی؛ و تست همهٔ اجزا بدون پایگاه داده یا Broker. هدف یادگیری (Learning goal): جریان سفارشی بسازید و توضیح دهید که بیش از موجودی نفروشد، دوبار پول نگیرد یا کالا نفرستد، ایمیل تأیید را گم نکند و اجازه ندهد مشتری سفارش دیگری را بخواند. بدانید هر تضمین در کدام بخش کد است، کدام تست آن را اثبات میکند و با رشد فروشگاه از یک فرایند به چند سرویس چه چیزهایی تغییر میکنند.
این فصل مسیر ساخت API فروشگاه را از دامنه تا اجرای یک ماژول Go دنبال میکند: کاتالوگ و محصولات، دستهها، سبد، سفارش و ردیفهایش، وضعیت پرداخت، موجودی و کاربران. تکنیکهای فصلهای دیگر را کنار هم میگذاریم و بهجای تدریس دوباره به آنها لینک میدهیم: Handler، DTO، تابع run، ETag/If-Match و Middleware عمومی Idempotency-Key در A REST API in Go هستند؛ database/sql، pgx، Pool و Transaction در database/sql & pgx؛ Hash رمز عبور، Session و JWT در Authentication in Go؛ Watermill، مصرفکنندهٔ RabbitMQ و SQS در Event-Driven Go؛ زنجیرهٔ Middleware در Middlewares؛ و روشهای تست در Testing & Benchmarking. بخش مالی فروشگاه، شامل اتصال PSP، دفتر کل، Webhook، بازپرداخت و PCI، موضوع Payment Processing Architecture است. این پروژه قواعد همان فصل را رعایت میکند: واحد کوچک صحیح، کلید Idempotency مشتقشده برای PSP، ماشین حالت پرداخت که رویداد دیررس را نادیده میگیرد و Outbox برای هر رویداد مالی. انتخاب نوع قفل در Optimistic & Pessimistic Locking، جداسازی در Isolation Levels، صفحهبندی در Pagination، Outbox در Outbox Pattern، Idempotency در سطح سیستم در API Idempotency، و سفارش بهعنوان تجمیع (Aggregate) در Aggregates & Factories و Domain Events vs Integration Events باز میشوند.
مبنای بررسی این مطالب مستندات جاری PostgreSQL دربارهٔ SELECT ... FOR UPDATE، جداسازی Transaction، Constraint، Partial index، Generated column، جستوجوی متن، ILIKE و کدهای خطای Appendix A بوده است؛ همچنین چرخهٔ PaymentIntent و درخواستهای Idempotent در Stripe، نوشتهٔ Brandur Leach، مقالهٔ «Building Resilient Payment Systems» از Shopify Engineering در ۲۸ ژوئیهٔ ۲۰۲۲، RFC 9457، پیشنویس IETF برای Idempotency-Key، OpenAPI 3.1.0، READMEهای swaggo/swag، oapi-codegen، go-mail، pgx، amqp091-go، golang-migrate و goose، آموزشهای Go و راهنمای Publisher confirms در RabbitMQ، الگوی Money از Martin Fowler، صفحات REST Security و API Security در OWASP، یادداشتهای انتشار Go 1.22 تا 1.25 و سورس net/http، و مستندات Laravel 13 دربارهٔ روابط Eloquent، Query، Database، Queue، Mail، Cashier و Scout. ماژول go 1.24 اعلام میکند و نسخههای github.com/jackc/pgx/v5 v5.8.0، github.com/wneessen/go-mail v0.7.2، github.com/rabbitmq/amqp091-go v1.17.0 و golang.org/x/time v0.14.0 را Pin کرده است. go.mod نسخهٔ v0.7.2 از go-mail مقدار 1.24.0 دارد؛ طبق Module proxy، v0.7.3 و v0.8.0 مقدار 1.25.0 و v0.8.2 مقدار 1.26.10 دارند. Pin نسخهٔ pgx فقط برای خط Go 1.24 این ماژول است: طبق CHANGELOG، pgx 5.12.0 در ۳۰ اکتبر ۲۰۲۶ دو مشکل با شدت بالا را رفع کرد؛ SQL injection در Batchهای Simple protocol و دور زدن require_auth/channel_binding. پس کد عملیاتی روی Go 1.25+ باید آخرین 5.x را بگیرد؛ ببینید database/sql & pgx. ماژول با Go 1.27.4 روی macOS کامپایل، vet و با -race تست شده است؛ هیچ تستی به PostgreSQL، RabbitMQ یا سرور SMTP نیاز ندارد.
نقشهٔ صفحه (Page map)
| اگر دنبال این هستید | بروید به |
|---|---|
| دیدن کل پروژه در یک نگاه | همهچیز در یک دقیقه |
| چرا فروشگاه از CRUD سختتر است | چرا وجود دارد |
| ریشهٔ الگوهای بهکاررفته | از کجا آمده |
| Handler حجیم و جایگزین آن | Go |
| رابطهٔ محصول، دسته، کاربر، سبد، سفارش، پرداخت و موجودی | دامنه |
| مرز Packageها و مسئولیت Handler، Service و Repository | ساختار پروژه |
| نمایش صحیح پول، ارز و گرد کردن | پول |
| محاسبهٔ مالیات و تخفیف | قواعد قیمتگذاری |
| طراحی جدول، Constraint، Index و Migration | Schema و Migration |
اجرای Store.InTx و Retry روی 40001 | Repository و Transaction |
جلوگیری از فروش اضافه با FOR UPDATE و ستون Version | قفل یا Version برای موجودی |
| مراحل Transaction ثبت خرید | ثبت سفارش |
| مدیریت دوبار کلیک و Retry | ثبت سفارش Idempotent |
| حرکت میان created، paid، fulfilled، cancelled و refunded | ماشین حالت سفارش |
| سبد مهمان، Cookie و ورود کاربر | سبد خرید |
| صفحهبندی، فیلتر، مرتبسازی و جستوجو | فهرست کاتالوگ |
| چه کسی کدام عملیات و کدام سفارش را میبیند | احراز هویت و مجوز |
| معنای 422، 409 و problem+json | اعتبارسنجی و قالب خطا |
رساندن OrderPlaced و PaymentCaptured با Relay و RabbitMQ | رویدادها از راه Outbox |
| ایمیل تأیید با go-mail و Template | ایمیل SMTP |
| Retry، سبد رهاشده و سفارش پرداختنشده | Workerهای پسزمینه |
| اثر رویداد PSP بر سفارش | Webhook پرداخت |
| انتخاب swag یا oapi-codegen و تشخیص فاصلهٔ قرارداد از کد | Swagger/OpenAPI |
| پاسخ 429 و Headerهای HSTS و nosniff | محدودسازی نرخ و Headerهای امنیتی |
| Repository جعلی، httptest و Postgres واقعی | تست |
| دنبال کردن سفارش با Log، Metric و Trace | مشاهدهپذیری |
| خاموشی، پیکربندی و Docker | استقرار |
| ترتیب Pipeline، SQLSTATEها و پاسخهای دقیق | سازوکار |
| باگهایی که هر فروشگاه با آنها روبهرو میشود | حل مسئلههای کلاسیک |
| انتخاب ابزار متناسب با موقعیت | انتخاب |
| رشد از یک فرایند به چند سرویس | در معماری |
| اجرای پروژه روی ماشین خودتان | آزمایشگاه |
| معادلها با Eloquent، Cashier، Scout و Queue | برای توسعهدهندگان PHP/Laravel |
همهچیز در یک دقیقه (One minute)
بستهها (Packages). یک ماژول به نام academy/ecommerce-api-project داریم؛ هر سطر یک دایرکتوری با تستهای خودش است.
| Package | مسئول چیست | وابسته به | چه چیزی اثبات میشود |
|---|---|---|---|
money | Money{Amount int64, Currency}، گرد کردن Half-even و تخصیص مبلغ | stdlib | جمع دقیق، جدول گرد کردن، گم نشدن حتی یک سنت |
pricing | Quote: جمع اولیه، تخفیف، مالیات و کل به شکل تابع خالص | money | حالتهای Table-driven |
domain | محصول، موجودی، سبد، سفارش، پرداخت، رویداد و ماشین حالت | money | جدول Transition و قواعد Merge |
store | Portها: Store.InTx و یک Interface برای هر Repository | domain | فقط Interface است |
memstore | Adapter حافظهای و Repository جعلی همهٔ تستهای Service | store | Rollback و صفحههای Keyset |
pgstore | Adapter PostgreSQL با pgx v5، Migration و Retry روی 40001/40P01 | store، pgx | pgx.Tx جعلی و SQL builder؛ Postgres واقعی پشت Build tag |
service | موارد کاربرد کاتالوگ، سبد، Checkout، سفارش و نگهداری | store، pricing | تست Table-driven با Repository جعلی و همزمانی |
httpapi | Route، DTO، Auth، اعتبارسنجی، RFC 9457، Rate limit، Header و openapi.json | service | تست API با httptest و تست انحراف قرارداد |
outbox، bus، rabbit | Relay، Bus داخل فرایند و Publisher در RabbitMQ با Confirm | store | حفظ ترتیب و Retry شکست |
mailer، worker | Template، فرستندهٔ SMTP با go-mail، Retry و Job | domain، go-mail | یک ایمیل برای هر رویداد و توقف خطاهای دائمی |
config، app، cmd/api | پیکربندی محیطی، اتصال اجزا و خاموشی مرتب | همهٔ اجزا | جریان سرتاسری و توقف تمیز |
نقطههای دسترسی (Endpoints).
| Method و Path | چه کسی | کار | خطاهای معمول |
|---|---|---|---|
GET /v1/products | همه | صفحهٔ Keyset، فیلتر، Sort و Search | 422 برای Sort، Limit یا Cursor نامعتبر |
GET /v1/products/{id} | همه | یک محصول، ETag برابر Version | 404 |
POST /v1/admin/products | Admin | ساخت محصول و موجودی | 401, 403, 422 |
PUT /v1/admin/products/{id}/price | Admin | تغییر قیمت با If-Match | 412 نسخهٔ کهنه، 428 نبودن شرط |
GET /v1/cart, PUT /v1/cart/items/{productID} | مهمان یا مشتری | سبد سمت سرور، Cookie به نام cart_id برای مهمان | 404, 422 |
POST /v1/cart/merge | مشتری | ادغام سبد مهمان پس از ورود | 401 |
POST /v1/orders | مشتری | ثبت سفارش با Idempotency-Key اجباری | 400، 409 موجودی، 422 سبد یا استفادهٔ مجدد کلید |
GET /v1/orders, GET /v1/orders/{id} | مالک یا Admin | خواندن سفارشها | 404 برای سفارش دیگری |
POST /v1/orders/{id}/cancel | مالک | لغو سفارش پرداختنشده | 409 اگر پرداخت شده |
POST /v1/admin/orders/{id}/fulfil | Admin | ارسال سفارش پرداختشده | 409 اگر پرداخت نشده |
POST /v1/webhooks/psp | PSP با HMAC | اعمال رویداد پرداخت | 400 برای امضای نادرست |
GET /healthz, /readyz, /openapi.json | عملیات | زنده بودن، آمادگی و قرارداد | 503 برای آماده نبودن |
چرخهٔ سفارش: created → paid → fulfilled → cancelled/refunded. این عبارت را اینطور بخوانید: ساخته میشود، سپس پرداخت و ارسال میشود؛ پایان سفارش یا لغو پیش از پرداخت است یا بازپرداخت پس از آن.
| از | به | محرک | اثرهای جانبی در همان Transaction |
|---|---|---|---|
| هیچ | created | POST /v1/orders | رزرو موجودی، ثبت Payment intent، نوشتن order.placed در Outbox |
created | paid | payment_intent.succeeded تأییدشده | پرداخت succeeded، نوشتن payment.captured در Outbox |
created | cancelled | لغو مشتری یا پایان مهلت موجودی | یکبار آزادسازی موجودی، order.cancelled |
paid | fulfilled | ارسال توسط Admin | رزرو به ارسال تبدیل میشود؛ on_hand و reserved هر دو کم میشوند |
paid, fulfilled | refunded | ثبت بازپرداخت | سیستم پرداخت، Refund را انجام میدهد |
cancelled همراه Capture دیررس | cancelled | Capture بعد از مهلت | پرداخت refund_pending، رویداد payment.refund_requested |
هر خطر با چه چیزی مهار میشود.
| خطر | خط دفاع اول | خط دفاع آخر در پایگاه داده |
|---|---|---|
| فروش بیش از موجودی | SELECT ... FOR UPDATE روی سطرهای موجودی به ترتیب شناسهٔ محصول | CHECK (reserved <= on_hand) |
| سفارش تکراری بر اثر Retry | Idempotency-Key و Fingerprint در Transaction خرید | PRIMARY KEY (scope, key) |
| دو Payment intent | یک Intent برای هر سفارش در Service | payments.order_id UNIQUE, provider_key UNIQUE |
| رویداد گمشده یا خیالی | سطر Outbox در همان Transaction | outbox.event_id UNIQUE |
| از دست رفتن تغییر قیمت | If-Match و Compare-and-set روی version | WHERE version = $n |
| وضعیت کهنه از Webhook دیررس | ماشین حالت: بدون یال، بدون تغییر | CHECK (status IN (...)) |
| خواندن سفارش دیگری | بررسی مجوز هر شیء در Service | ندارد؛ قاعدهٔ برنامه است |
چرا وجود دارد (Why)
فروشگاه در نگاه اول CRUD با یک دکمهٔ خرید است. اما سه مسئله همزمان دارد که CRUD ساده ندارد: چند نفر در یک لحظه آخرین واحد محصول را میخواهند؛ شبکه میان مشتری، API و ارائهدهندهٔ پرداخت وسط درخواست قطع میشود؛ و کارهایی مثل ایمیل، انبار و تحلیل باید به تعداد وقوع سفارش انجام شوند، نه به تعداد Retry درخواست. نسخهای که همهچیز را در یک Handler انجام میدهد در روز خلوت جواب میدهد، ولی در اولین حراج میشکند: بیشتر از موجودی میفروشد، برای دوبار کلیک دو سفارش میسازد، با کند شدن سرور ایمیل با وجود ثبت سفارش 500 میدهد و قیمت مرورگر را باور میکند.
| فروشگاه سادهانگارانه | این پروژه |
|---|---|
| قیمت از درخواست میآید | قیمت در Transaction خرید از کاتالوگ خوانده میشود |
جمع با float64 | واحد کوچک int64، گرد کردن Half-even و تخصیص بدون گم شدن سنت |
| بررسی و سپس کاهش موجودی بدون قفل | قفل سطر، رزرو همه یا هیچ و CHECK پشتیبان |
| هر Retry سفارش تازه است | Idempotency-Key با Fingerprint و بازپخش از همان Transaction |
| ارسال ایمیل داخل درخواست | ثبت order.placed در Outbox و ارسال توسط Worker با Retry |
| وضعیت، ستون متن آزاد است | ماشین حالت با Transitionهای Versionدار |
یک بررسی isAdmin برای هر Route | Role در Route و مالکیت شیء در Service |
| تست به پایگاه داده نیاز دارد | Repository جعلی برای Service، httptest برای Handler، Postgres پشت Build tag |
| فایل کمتر | Package بیشتر و دقیقاً یک خانه برای هر قاعده |
تصویری از زندگی روزمره. شیرینیفروشیای با پیشخوان و اتاق پشتی را تصور کنید. ویترین کاتالوگ است و سینی مشتری سبد خرید؛ سینی روی پیشخوان میماند تا وقتی مشتری میگوید «کیف پولم را بیاورم» ناپدید نشود. با «اینها را میخواهم»، فروشنده شیرینیها را با یک رسید روی قفسهٔ رزرو میگذارد: موجودی رزرو و سفارش ساخته میشود. همزمان برگهٔ «وقتی آماده شد به مشتری زنگ بزنید» در سینی Outbox میگذارد. صندوقدار پول را میگیرد؛ اگر پرداخت برای رسیدی برسد که قبلاً رها شده، پول برمیگردد و سفارش زنده نمیشود. مسئول تماس سینی را خالی میکند و اگر تلفن اشغال بود بعداً دوباره زنگ میزند. اگر مشتری بهخاطر دیر جواب دادن فروشنده دوبار بگوید «اینها را میخواهم»، شمارهٔ رسید بررسی میشود و پاسخ «قبلاً انجام شد» است.
سه بدفهمی رایج، از همان اول
- «تراکنش (Transaction) جلوی فروش اضافه را میگیرد.» در
READ COMMITTEDپیشفرض PostgreSQL، دو Checkout میتوانند یک عدد موجودی را بخوانند. قفل سطر،UPDATEشرطی اتمیک، بررسی Version یاSERIALIZABLEهمراه Retry لازم است تا دومی اثر اولی را ببیند. - «Idempotency یعنی Unique constraint روی سفارش.» Constraint فقط Retry را به خطایی تبدیل میکند که کلاینت معنایش را نمیداند. Idempotency یعنی پاسخ اول دوباره برگردد و استفاده از همان کلید با Body متفاوت رد شود.
- «رویداد را بعد از Commit منتشر کن تا قابل اتکا باشد.» Crash میان Commit و Publish آن را گم میکند؛ Publish پیش از Commit سفارش Rollbackشده را اعلام میکند. رویداد باید به شکل سطر Outbox در همان Transaction باشد.
از کجا آمده (History)
این اجزا از حضور Go در بکاند وب قدیمیترند. کتاب Patterns of Enterprise Application Architecture نوشتهٔ Martin Fowler با Dave Rice و دیگران، طبق martinfowler.com در ۲۰۰۲، الگوی Money را شرح میدهد: "A large proportion of the computers in this world manipulate money, so it's always puzzled me that money isn't actually a first class data type in any mainstream programming language". الگوی Optimistic Offline Lock همان ستون Version است؛ تعریف Repository هم چنین است: "Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects". Chris Richardson در microservices.io، Transactional outbox را برای سرویسی توضیح میدهد که بدون Transaction توزیعشده باید هم پایگاه داده را تغییر دهد و هم پیام بفرستد. API شرکت Stripe استفاده از Header به نام Idempotency-Key را رایج کرد؛ نوشتهٔ فوریهٔ ۲۰۱۷ Brandur Leach آن را توضیح میدهد و مستندات Stripe برای API v1 میگویند: "saves the status code and body of the first request made with a given idempotency key". مقالهٔ ژوئیهٔ ۲۰۲۲ Shopify Engineering دربارهٔ پرداخت تابآور نکتهای دربارهٔ خود کلید دارد: جایگزینی UUIDv4 با ULID در یک سیستم پرترافیک به "a 50 percent decrease in INSERT statement duration" رسید. پیشنویس IETF به نام draft-ietf-httpapi-idempotency-key-header، Header و پاسخهای 400/409/422 آن را استاندارد میکند.
در HTTP، استاندارد RFC 9457 در ژوئیهٔ ۲۰۲۳ جای RFC 7807 را گرفت و قالب جزئیات خطا (Problem Details) را تعریف کرد. OpenAPI 3.1.0 در ۱۵ فوریهٔ ۲۰۲۱ زبان Schema را با JSON Schema همراستا کرد. Go 1.22 در فوریهٔ ۲۰۲۴ الگوهای Method و Wildcard را به net/http.ServeMux افزود؛ مطلب «Routing Enhancements for Go 1.22» در ۱۳ فوریهٔ ۲۰۲۴ شرحش میدهد. به همین دلیل این پروژه کتابخانهٔ Router نمیخواهد. swaggo/swag از Commentها Swagger 2.0 میسازد: "Swag converts Go annotations to Swagger Documentation 2.0". oapi-codegen مسیر برعکس را میرود: "to convert OpenAPI specifications to Go code". برای ایمیل، net/smtp کتابخانهٔ استاندارد "is frozen and is not accepting new features"؛ به همین دلیل از github.com/wneessen/go-mail استفاده میشود. Laravel همین اجزا را در Framework دارد: رابطههای Eloquent، lockForUpdate، Job صفشده با afterCommit، Mailable صفشده، Cashier برای Stripe و Scout برای Search؛ ببینید برای توسعهدهندگان PHP/Laravel.
Go
قبل (Before)
Checkout نسخههای اول معمولاً چنین شکلی دارد. کامپایل میشود و تست مسیر موفق را میگذراند، اما تست زیر چهار ایرادش را آشکار میکند: مرورگر قیمت را انتخاب میکند، پول float64 است، هر Retry سفارش جدید میسازد و سرور ایمیل کند، سفارش موفق را به 500 تبدیل میکند؛ پاسخی که مشتری را به خرید دوباره دعوت میکند.
// Package before is the checkout most first versions look like: one fat
// handler that trusts the client's prices, uses float64 for money, has no
// idempotency, and sends the confirmation mail inside the request. It
// works on a quiet day; the tests show what happens on a bad one.
package before
import (
"encoding/json"
"fmt"
"net/http"
"sync"
)
type Item struct {
ProductID int `json:"product_id"`
Price float64 `json:"price"` // sent by the browser
Qty int `json:"qty"`
}
type Order struct {
ID int `json:"id"`
Email string `json:"email"`
Items []Item `json:"items"`
Total float64 `json:"total"`
}
// Shop keeps everything in one struct, guarded by one mutex.
type Shop struct {
mu sync.Mutex
Stock map[int]int
Orders []Order
SendMail func(to, body string) error // net/smtp.SendMail in production
}
// PlaceOrder decodes the cart, totals it, decrements stock, stores the
// order and mails the customer, all before answering.
func (s *Shop) PlaceOrder(w http.ResponseWriter, r *http.Request) {
var in struct {
Email string `json:"email"`
Items []Item `json:"items"`
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
http.Error(w, "bad json", http.StatusBadRequest)
return
}
total := 0.0
for _, it := range in.Items {
total += it.Price * float64(it.Qty)
}
s.mu.Lock()
for _, it := range in.Items {
if s.Stock[it.ProductID] < it.Qty {
s.mu.Unlock()
http.Error(w, "out of stock", http.StatusConflict)
return
}
}
for _, it := range in.Items {
s.Stock[it.ProductID] -= it.Qty
}
o := Order{ID: len(s.Orders) + 1, Email: in.Email, Items: in.Items, Total: total}
s.Orders = append(s.Orders, o)
s.mu.Unlock()
if err := s.SendMail(in.Email, fmt.Sprintf("Order %d: total %v", o.ID, o.Total)); err != nil {
http.Error(w, "could not send confirmation", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(o)
}package before
import (
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func post(s *Shop, body string) int {
rec := httptest.NewRecorder()
s.PlaceOrder(rec, httptest.NewRequest("POST", "/orders", strings.NewReader(body)))
return rec.Code
}
func TestWhatGoesWrong(t *testing.T) {
mailDown := true
s := &Shop{Stock: map[int]int{1: 10, 2: 10}, SendMail: func(string, string) error {
if mailDown {
return errors.New("dial tcp: i/o timeout")
}
return nil
}}
body := `{"email":"alice@example.com","items":[{"product_id":1,"price":0.1,"qty":1},{"product_id":2,"price":0.2,"qty":1}]}`
// 1. SMTP is slow and fails: the customer sees 500, but the order exists.
if code := post(s, body); code != http.StatusInternalServerError || len(s.Orders) != 1 {
t.Fatalf("code %d orders %d", code, len(s.Orders))
}
// 2. The customer presses "Buy" again: a second order, stock taken twice.
mailDown = false
if code := post(s, body); code != http.StatusCreated || len(s.Orders) != 2 || s.Stock[1] != 8 {
t.Fatalf("code %d orders %d stock %d", code, len(s.Orders), s.Stock[1])
}
// 3. Float money: 0.1 + 0.2 is not 0.3.
if s.Orders[0].Total == 0.3 {
t.Fatal("float64 surprised us by being exact")
}
// 4. The browser chose the price.
post(s, `{"email":"mallory@example.com","items":[{"product_id":1,"price":0.01,"qty":5}]}`)
if s.Orders[2].Total != 0.05 {
t.Fatalf("total %v", s.Orders[2].Total)
}
}بعد (After)
همان مورد کاربرد به شکل متد Service: قیمت از کاتالوگ میآید، جمعها با تابع خالص محاسبه میشوند و موجودی بهصورت همه یا هیچ رزرو میشود. سفارش، ردیفهایش، Payment intent، سطر Outbox و رکورد Idempotency همگی در یک Transaction نوشته میشوند و تا Commit هیچچیز از فرایند بیرون نمیرود.
package service
import (
"context"
"errors"
"time"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/pricing"
"academy/ecommerce-api-project/store"
)
// Checkout places orders.
type Checkout struct{ Deps }
// PlaceOrderInput comes from POST /v1/orders. Fingerprint is a SHA-256 of
// the canonical request body, computed by the handler.
type PlaceOrderInput struct {
Who domain.Principal
IdempotencyKey string
Fingerprint string
DiscountCode string
}
// PlaceOrderResult says whether this call created the order or replayed it.
type PlaceOrderResult struct {
Order domain.Order
Payment domain.Payment
Replayed bool
}
// PlaceOrder is the heart of the project. In ONE transaction it:
// 1. replays the stored result if the Idempotency-Key was seen (422 if the
// body differs), otherwise claims the key at once, so a concurrent
// duplicate blocks on the key's primary key here and later replays,
// 2. reads the cart and prices it from the catalogue (never from the client),
// 3. reserves stock for every line, in product-id order, all or nothing,
// 4. creates the order and its items (status created),
// 5. records the payment intent with a derived PSP idempotency key,
// 6. writes OrderPlaced to the outbox,
// 7. empties the cart.
//
// Any failure rolls everything back, the key claim included. Nothing is
// published and no mail is sent here: the relay and the worker do that
// after commit, from the outbox.
func (c Checkout) PlaceOrder(ctx context.Context, in PlaceOrderInput) (PlaceOrderResult, error) {
if in.Who.UserID == 0 {
return PlaceOrderResult{}, domain.ErrForbidden
}
if l := len(in.IdempotencyKey); l < 8 || l > 255 {
return PlaceOrderResult{}, &ValidationError{Fields: []FieldError{{"Idempotency-Key", "8 to 255 characters"}}}
}
scope := "POST /v1/orders user:" + itoa(in.Who.UserID)
var res PlaceOrderResult
err := retryConflict(func() error {
return c.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
res = PlaceOrderResult{}
// 1. idempotency: replay, refuse, or claim the key before any work
now := c.Now()
orderID := c.NewID("ord")
rec, err := tx.Idempotency().Get(ctx, scope, in.IdempotencyKey)
switch {
case err == nil && rec.Fingerprint != in.Fingerprint:
return ErrIdempotencyMismatch
case err == nil:
res.Replayed = true
if res.Order, err = tx.Orders().Get(ctx, string(rec.Body)); err != nil {
return err
}
res.Payment, err = tx.Payments().ForOrder(ctx, res.Order.ID)
return err
case !errors.Is(err, domain.ErrNotFound):
return err
}
if err := tx.Idempotency().Put(ctx, store.IdemRecord{Scope: scope, Key: in.IdempotencyKey,
Fingerprint: in.Fingerprint, Status: 201, Body: []byte(orderID), CreatedAt: now}); err != nil {
return err // ErrDuplicateKey: a concurrent duplicate committed; InTx re-runs and replays
}
// 2. cart and prices
cart, err := tx.Carts().ForUser(ctx, in.Who.UserID)
if errors.Is(err, domain.ErrNotFound) || (err == nil && len(cart.Items) == 0) {
return domain.ErrEmptyCart
}
if err != nil {
return err
}
lines := make([]pricing.Line, 0, len(cart.Items))
names := map[int64]string{}
for _, it := range cart.Items {
p, err := tx.Products().Get(ctx, it.ProductID)
if err != nil {
return err
}
if !p.Active {
return domain.ErrInactiveProduct
}
names[p.ID] = p.Name
lines = append(lines, pricing.Line{ProductID: p.ID, SKU: p.SKU, Unit: p.Price, Qty: it.Qty, TaxClass: p.TaxClass})
}
var discounts []pricing.Discount
if d, ok := c.discount(in.DiscountCode); ok {
discounts = append(discounts, d)
}
totals, err := pricing.Quote(c.Currency, lines, discounts, c.TaxRates)
if err != nil {
return err
}
// 3. stock, all lines or none, in a fixed lock order
rs := make([]domain.Reservation, len(lines))
for i, l := range lines {
rs[i] = domain.Reservation{ProductID: l.ProductID, Qty: l.Qty}
}
if err := tx.Inventory().Reserve(ctx, domain.SortReservations(rs)); err != nil {
return err
}
// 4. order + items
o := domain.Order{ID: orderID, UserID: in.Who.UserID, Email: in.Who.Email,
Status: domain.OrderCreated, Subtotal: totals.Subtotal, Discount: totals.Discount,
Tax: totals.Tax, Total: totals.Total, Version: 1, CreatedAt: now, UpdatedAt: now,
ExpiresAt: now.Add(c.hold())}
for _, l := range totals.Lines {
lt, _ := l.Net.Add(l.Tax)
o.Items = append(o.Items, domain.OrderItem{ProductID: l.ProductID, SKU: l.SKU, Name: names[l.ProductID],
Unit: l.Unit, Qty: l.Qty, Discount: l.Discount, Tax: l.Tax, LineTotal: lt})
}
if err := tx.Orders().Create(ctx, &o); err != nil {
return err
}
// 5. payment intent (the PSP call happens in the payments system,
// with this derived key, so a retried attempt never charges twice)
pay := domain.Payment{ID: c.NewID("pay"), OrderID: o.ID, Amount: o.Total,
Status: domain.PaymentRequiresMethod, ProviderKey: o.ID + ":attempt:1", UpdatedAt: now}
if err := tx.Payments().Create(ctx, pay); err != nil {
return err
}
// 6. event, same transaction
ev := domain.NewEvent(domain.EvOrderPlaced, o.ID, o.Version, now, domain.OrderPlaced{
OrderID: o.ID, UserID: o.UserID, Email: o.Email, Total: o.Total.Amount, Curr: string(o.Total.Currency)})
if err := tx.Outbox().Add(ctx, ev); err != nil {
return err
}
// 7. cart gone
res.Order, res.Payment = o, pay
return tx.Carts().Delete(ctx, cart.ID, cart.Version) // conflict: an item was added meanwhile; re-run
})
})
return res, err
}
func (c Checkout) discount(code string) (pricing.Discount, bool) {
if code == "" || c.Discounts == nil {
return pricing.Discount{}, false
}
return c.Discounts(code)
}
func (d Deps) hold() time.Duration {
if d.StockHold > 0 {
return d.StockHold
}
return 15 * time.Minute
}Handler نازک است: Header را الزامی میکند، از Body اثر انگشت (Fingerprint) میگیرد، Service را فراخوانی میکند و خطاها را به Problemهای RFC 9457 نگاشت میکند. app_test.go کل مسیر را سرتاسری اثبات میکند: Checkout از HTTP، Outbox، Relay، Bus، Worker ایمیل که اولین تلاش SMTP آن شکست میخورد، و خاموشی مرتب.
package app
import (
"context"
"log/slog"
"net"
"net/http"
"strings"
"testing"
"time"
"academy/ecommerce-api-project/config"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/httpapi"
"academy/ecommerce-api-project/mailer"
"academy/ecommerce-api-project/memstore"
)
// The whole flow in one process: HTTP checkout -> outbox -> relay -> bus ->
// mail worker -> SMTP (recorded), then a graceful shutdown.
func TestOrderPlacedReachesTheMailboxAndShutdownIsClean(t *testing.T) {
cfg, _ := config.Load(func(string) string { return "" })
cfg.ShutdownTimeout = 2 * time.Second
rec := &mailer.Recorder{Fail: 1} // first SMTP attempt fails with a 421
a := New(cfg, Deps{Store: memstore.New(), Inbox: memstore.NewInbox(), Sender: rec,
Log: slog.New(slog.DiscardHandler), RelayTick: 10 * time.Millisecond, JobTick: time.Hour,
Auth: httpapi.StaticTokens{
"admin": {UserID: 1, Role: domain.RoleAdmin},
"alice": {UserID: 7, Email: "alice@example.com", Role: domain.RoleCustomer},
}})
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(t.Context())
done := make(chan error, 1)
go func() { done <- a.Serve(ctx, ln) }()
base := "http://" + ln.Addr().String()
client := &http.Client{Transport: &http.Transport{}}
send := func(method, path, token, body string, hdr ...string) *http.Response {
req, _ := http.NewRequest(method, base+path, strings.NewReader(body))
req.Header.Set("Authorization", "Bearer "+token)
for i := 0; i+1 < len(hdr); i += 2 {
req.Header.Set(hdr[i], hdr[i+1])
}
res, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
return res
}
if res := send("POST", "/v1/admin/products", "admin", `{"sku":"BOOK","name":"Go book","price":3999,"tax_class":"reduced","stock":5}`); res.StatusCode != 201 {
t.Fatalf("product: %d", res.StatusCode)
}
send("PUT", "/v1/cart/items/1", "alice", `{"qty":1}`)
if res := send("POST", "/v1/orders", "alice", `{"discount_code":"WELCOME10"}`, "Idempotency-Key", "a9b8c7d6-0001"); res.StatusCode != 201 {
t.Fatalf("order: %d", res.StatusCode)
}
deadline := time.Now().Add(5 * time.Second)
for len(rec.Sent()) == 0 && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
sent := rec.Sent()
if len(sent) != 1 || sent[0].To != "alice@example.com" || !strings.Contains(sent[0].Text, "Total: 38.51 EUR") {
t.Fatalf("mail: %+v", sent)
}
// Shutdown closes idle connections at once but treats a connection that
// never sent a request as busy for 5 s; close ours so the test is fast.
client.CloseIdleConnections()
cancel()
select {
case err := <-done:
if err != nil {
t.Fatal(err)
}
case <-time.After(5 * time.Second):
t.Fatal("no graceful shutdown")
}
}
// APP_ROLE=api: the replica serves HTTP but starts no relay and no jobs.
func TestAPIRoleRunsNoBackgroundJobs(t *testing.T) {
cfg, _ := config.Load(func(k string) string { return map[string]string{"APP_ROLE": "api"}[k] })
cfg.ShutdownTimeout = time.Second
st := memstore.New()
rec := &mailer.Recorder{}
a := New(cfg, Deps{Store: st, Inbox: memstore.NewInbox(), Sender: rec, Log: slog.New(slog.DiscardHandler),
RelayTick: 5 * time.Millisecond, JobTick: 5 * time.Millisecond,
Auth: httpapi.StaticTokens{"admin": {UserID: 1, Role: domain.RoleAdmin}, "alice": {UserID: 7, Email: "a@example.com", Role: domain.RoleCustomer}}})
ln, _ := net.Listen("tcp", "127.0.0.1:0")
ctx, cancel := context.WithCancel(t.Context())
done := make(chan error, 1)
go func() { done <- a.Serve(ctx, ln) }()
client := &http.Client{Transport: &http.Transport{}}
do := func(method, path, tok, body string, hdr ...string) int {
req, _ := http.NewRequest(method, "http://"+ln.Addr().String()+path, strings.NewReader(body))
req.Header.Set("Authorization", "Bearer "+tok)
if len(hdr) == 2 {
req.Header.Set(hdr[0], hdr[1])
}
res, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
return res.StatusCode
}
do("POST", "/v1/admin/products", "admin", `{"sku":"A","name":"A","price":100,"tax_class":"zero","stock":1}`)
do("PUT", "/v1/cart/items/1", "alice", `{"qty":1}`)
if c := do("POST", "/v1/orders", "alice", `{}`, "Idempotency-Key", "api-role-0001"); c != 201 {
t.Fatalf("order %d", c)
}
time.Sleep(100 * time.Millisecond) // 20 relay ticks if a relay were running
if len(rec.Sent()) != 0 || len(st.Unpublished()) != 1 {
t.Fatalf("api replica ran background work: sent %d, unpublished %d", len(rec.Sent()), len(st.Unpublished()))
}
client.CloseIdleConnections()
cancel()
if err := <-done; err != nil {
t.Fatal(err)
}
}زاویهٔ Go
Go این طراحی را طبیعی میکند. پیادهسازی رابط (Interface) ضمنی است؛ پس Portهای store را مصرفکننده تعریف میکند و memstore و pgstore بدون شناخت یکدیگر آنها را پیاده میکنند. تست با عوض کردن یک آرگومان Constructor، Adapter را جابهجا میکند. context.Context از r.Context() به Service و سپس pgx و go-mail میرسد تا قطع اتصال کلاینت Query خودش را متوقف کند. net/http از Go 1.22 با Method و Wildcard مسیریابی میکند؛ مثلاً "POST /v1/orders/{id}/cancel" و خواندن شناسه با r.PathValue("id"). با embed، Migrationهای SQL، Templateهای ایمیل و openapi.json داخل Binary قرار میگیرند. html/template نام محصول را در HTML ایمیل بهصورت پیشفرض Escape میکند. log/slog، Log ساختاریافته میدهد و -race به تستهای همزمانی قدرت بررسی میدهد. چیزی که Go فراهم نمیکند Frameworkی است که این تصمیمها را بهجای شما بگیرد؛ هدف از یک بار ساختن دستی همین است.
فهرست مفاهیم (Concept catalogue)
هر بلوک این فهرست یک ترتیب ثابت دارد: ابتدا توضیح به زبان ساده، بعد بدفهمی رایج و تعریف دقیق، سپس Timeline، سناریوهای واقعی، جدول مقایسه و در پایان کدی که همان کار را انجام میدهد.
دامنه: محصول، دسته، کاربر، سبد، سفارش، پرداخت و موجودی حیاتی
به زبان ساده: پیش از نوشتن Handler، اسمها و رابطههایشان را روشن کنید. محصول به یک دسته تعلق دارد و قیمت و موجودی دارد؛ مشتری یا همان User یک سبد دارد؛ Checkout سبد را به سفارش تبدیل میکند. ردیفهای سفارش نام و قیمت همان لحظه را کپی میکنند و هر سفارش دقیقاً یک قصد پرداخت (Payment intent) دارد که وضعیت ارائهدهندهٔ پرداخت را دنبال میکند.
بدفهمی رایج: «سفارش برای قیمت به محصول اشاره کند کافی است.» با این کار تغییر قیمت هفتهٔ بعد، فاکتور هفتهٔ قبل را بازنویسی میکند. ردیف سفارش یک تصویر ثابت (Snapshot) است: SKU، نام، قیمت واحد، تخفیف، مالیات و جمع ردیف هنگام ثبت سفارش کپی میشوند. بدفهمی دوم: «موجودی یک عدد روی محصول است.» دو عدد داریم: on_hand یعنی موجودی فیزیکی و reserved یعنی مقداری که به سفارشهای پرداختنشده قول دادهایم. مقدار قابل فروش تفاضل آنهاست.
تعریف: تجمیعها (Aggregates) عبارتاند از Product با سطر Stock، Cart با CartItemها و بدون قیمت، Order با OrderItemها که ریشهٔ خرید و دارای Version است، و Payment که رکورد محلی Payment intent است. User نقش Customer یا Admin دارد و متعلق به بخش احراز هویت است. هر Aggregate فقط از متدهای خودش مثل Cart.Set، Cart.Merge و Order.Transition تغییر میکند و با Repository خودش ذخیره میشود؛ ببینید Aggregates & Factories.
Customer action Aggregate touched Rows written
1 browse catalogue Product (read) none
2 add 2 x MUG to cart Cart carts, cart_items
3 log in Cart (guest -> customer) cart_items merged, guest cart deleted
4 place order Stock, Order, Payment inventory, orders, order_items, payments, outbox
5 PSP says succeeded Order, Payment orders (paid, v2), payments, outbox
6 warehouse ships Order, Stock orders (fulfilled, v3), inventory, outboxسناریوی واقعی: افزایش قیمت وسط حراج نباید سفارش ثبتشده را تغییر دهد؛ محصول خارجشده از فروش باید از کاتالوگ حذف شود ولی در سفارش قدیمی خواندنی بماند؛ مشتری پس از تغییر ایمیل باید سفارشهای قبلی را پیدا کند؛ Admin هم ممکن است همزمان با خواندن محصول در Checkout آن را ویرایش کند.
| موجودیت | هویت | روش تغییر | مالک |
|---|---|---|---|
Product | Identity از نوع BIGINT، sku UNIQUE | ویرایش Admin با version خوشبینانه | کاتالوگ |
Category | Identity، slug UNIQUE و درخت parent_id | Admin | کاتالوگ |
Stock (inventory) | product_id | رزرو، آزادسازی، ارسال | موجودی |
Cart | شناسهٔ تصادفی مبهم در Cookie، یکی برای هر کاربر | Set، Merge | سبد |
Order + OrderItem | ord_<128-bit hex> | Transition و افزایش 1 در version | سفارش |
Payment | pay_<hex>، order_id UNIQUE | رویدادهای PSP | پرداخت |
User | Identity، email UNIQUE و نقش | ثبتنام، Admin | هویت؛ Authentication in Go |
راهحل / نحوهٔ استفاده: بستهٔ Domain را از HTTP، SQL و Tagهای JSON روی Aggregateها خالی نگه دارید؛ ماشین حالت و رویدادها Go سادهاند.
package domain
import (
"fmt"
"slices"
"time"
"academy/ecommerce-api-project/money"
)
// OrderStatus is the order state machine:
// created -> paid -> fulfilled, created -> cancelled, paid|fulfilled -> refunded.
type OrderStatus string
const (
OrderCreated OrderStatus = "created"
OrderPaid OrderStatus = "paid"
OrderFulfilled OrderStatus = "fulfilled"
OrderCancelled OrderStatus = "cancelled"
OrderRefunded OrderStatus = "refunded"
)
var orderEdges = map[OrderStatus][]OrderStatus{
OrderCreated: {OrderPaid, OrderCancelled},
OrderPaid: {OrderFulfilled, OrderRefunded},
OrderFulfilled: {OrderRefunded},
}
// CanBecome reports whether s -> to is an edge of the state machine.
func (s OrderStatus) CanBecome(to OrderStatus) bool { return slices.Contains(orderEdges[s], to) }
// OrderItem is a snapshot of a product at the moment of purchase: later
// price or name changes in the catalogue do not change past orders.
type OrderItem struct {
ProductID int64
SKU string
Name string
Unit money.Money
Qty int64
Discount money.Money
Tax money.Money
LineTotal money.Money // net + tax
}
// Order is the aggregate root for one purchase.
type Order struct {
ID string
UserID int64
Email string
Status OrderStatus
Items []OrderItem
Subtotal money.Money
Discount money.Money
Tax money.Money
Total money.Money
Version int64 // starts at 1, +1 per transition
CreatedAt time.Time
UpdatedAt time.Time
ExpiresAt time.Time // unpaid orders are cancelled and their stock released after this
}
// Transition moves the order along one edge and bumps the version.
func (o *Order) Transition(to OrderStatus, now time.Time) error {
if !o.Status.CanBecome(to) {
return fmt.Errorf("%w: order %s %s -> %s", ErrInvalidTransition, o.ID, o.Status, to)
}
o.Status, o.UpdatedAt = to, now
o.Version++
return nil
}
// Reservations lists the stock this order holds.
func (o *Order) Reservations() []Reservation {
rs := make([]Reservation, 0, len(o.Items))
for _, it := range o.Items {
rs = append(rs, Reservation{ProductID: it.ProductID, Qty: it.Qty})
}
return SortReservations(rs)
}
// PaymentStatus is a separate, smaller machine (a subset of Stripe's
// PaymentIntent statuses plus our own refund bookkeeping).
type PaymentStatus string
const (
PaymentRequiresMethod PaymentStatus = "requires_payment_method"
PaymentSucceeded PaymentStatus = "succeeded"
PaymentCanceled PaymentStatus = "canceled"
PaymentRefundPending PaymentStatus = "refund_pending" // captured after the order was cancelled
PaymentRefunded PaymentStatus = "refunded"
)
// Payment is the local record of the payment intent for an order. The PSP
// call itself lives in the payments system; this service only records the
// intent and reacts to the PSP's verified events.
type Payment struct {
ID string
OrderID string
Amount money.Money
Status PaymentStatus
ProviderKey string // idempotency key sent to the PSP: <order>:attempt:<n>
ProviderRef string // PSP object id, e.g. pi_..., once known
UpdatedAt time.Time
}package domain
import (
"slices"
"time"
)
// MaxQtyPerLine caps a cart line; merging two carts cannot exceed it.
const MaxQtyPerLine = 10
// CartItem is a product and a quantity. Prices are NOT stored in the cart:
// they are read from the catalogue at checkout.
type CartItem struct {
ProductID int64
Qty int64
}
// Cart is a server-side cart. A guest cart has UserID 0 and is found by its
// ID (an opaque random token in a cookie); a customer has at most one cart.
type Cart struct {
ID string
UserID int64
Email string // customer carts only: abandoned-cart reminders
Items []CartItem
UpdatedAt time.Time
RemindedAt *time.Time // abandoned-cart mail already sent
Version int64 // 0 = not saved yet; every Save is a compare-and-set
}
// Set puts qty of product in the cart (qty 0 removes the line).
func (c *Cart) Set(productID, qty int64, now time.Time) {
qty = min(qty, MaxQtyPerLine)
i := slices.IndexFunc(c.Items, func(it CartItem) bool { return it.ProductID == productID })
switch {
case i < 0 && qty > 0:
c.Items = append(c.Items, CartItem{ProductID: productID, Qty: qty})
case i >= 0 && qty > 0:
c.Items[i].Qty = qty
case i >= 0:
c.Items = slices.Delete(c.Items, i, i+1)
}
c.UpdatedAt = now
c.RemindedAt = nil
}
// Merge adds the guest cart's lines to c (the customer's cart) on login.
// Quantities of the same product are summed and capped at MaxQtyPerLine.
func (c *Cart) Merge(guest Cart, now time.Time) {
for _, g := range guest.Items {
cur := int64(0)
if i := slices.IndexFunc(c.Items, func(it CartItem) bool { return it.ProductID == g.ProductID }); i >= 0 {
cur = c.Items[i].Qty
}
c.Set(g.ProductID, cur+g.Qty, now)
}
c.UpdatedAt = now
}ساختار پروژه: لایهٔ Service و Handler، درگاهها و Adapterها حیاتی
به زبان ساده: Handler زبان HTTP را میفهمد، Service زبان مورد کاربرد و Repository زبان SQL را. Handler هرگز Transaction باز نمیکند؛ Service هرگز http.Request نمیبیند؛ Repository هم تصمیم نمیگیرد که لغو یک سفارش مجاز است یا نه.
بدفهمی رایج: «لایهٔ سرویس (Service layer) برای API کوچک تشریفات است.» در فروشگاه یک مورد کاربرد از چند جا فراخوانی میشود: Orders.Cancel از Endpoint مشتری و Job آزادسازی موجودی، و ApplyPayment از Webhook و اسکریپت تطبیق پرداخت. اگر قاعده در Handler باشد، Job مجبور به کپی آن است. اشتباه دیگر این است که Interfaceهای Repository را کنار پیادهسازی بگذاریم. در Go، Interface متعلق به مصرفکننده است: store نیاز Serviceها را اعلام میکند و هر دو Adapter آن را برآورده میکنند.
تعریف: سه لایه و یک ریشهٔ اتصال اجزا (Composition root) داریم. httpapi در لبه Decode، اعتبارسنجی شکل، احراز هویت و نگاشت خطا را انجام میدهد. service در لایهٔ برنامه برای هر مورد کاربرد یک Transaction script روی store.Store.InTx اجرا میکند. store مجموعهٔ Interfaceهای Port است؛ memstore و pgstore Adapterهای آناند. app Adapterهای مشخصی را به هم وصل میکند که cmd/api از محیط انتخاب کرده است. پیکان وابستگی فقط رو به داخل میرود.
Request Layer Package Knows about
1 POST /v1/orders edge httpapi HTTP, JSON, headers, Principal
2 Checkout.PlaceOrder(ctx, in) application service use case, transaction boundary
3 tx.Inventory().Reserve(...) port store interface only
4 UPDATE inventory ... adapter pgstore SQL, pgx, SQLSTATEs
5 tx.Outbox().Add(event) port/adapter pgstore same transaction as 4
6 201 Created edge httpapi DTO, Location headerسناریوی واقعی: Job آزادسازی موجودی و لغو توسط مشتری از cancelInTx مشترک استفاده میکنند؛ Webhook و دکمهٔ «پرداخت شد» Admin، ApplyPayment مشترک دارند؛ CLI واردکنندهٔ محصول، Catalog.CreateProduct را صدا میزند؛ تستها هم مستقیم و بدون HTTP به Service میرسند.
| مسئولیت | Handler (httpapi) | Service (service) | Repository (pgstore) |
|---|---|---|---|
| شکل JSON، فیلد ناشناخته، اندازهٔ Body | بله | نه | نه |
| اعتبارسنجی کسبوکار؛ تعداد 0..10 و قیمت > 0 | نه | بله | نه؛ Constraint پشتیبان است |
| احراز هویت | Middleware | Principal را میگیرد | نه |
| مجوز هر شیء | نه | بله؛ CanSee | نه |
| مرز Transaction | نه | InTx | آن را پیاده میکند |
| SQL، قفل و نگاشت SQLSTATE | نه | نه | بله |
| Status code | بله، در یک تابع fail | خطای نوعدار میدهد | خطای domain میدهد |
راهحل / نحوهٔ استفاده: Portها کوتاهاند و از Aggregate نام میگیرند. Service آنها را در Struct به نام Deps همراه Clock و مولد شناسهٔ تزریقشده دریافت میکند.
// Package store declares the persistence ports the services need. There are
// two adapters: memstore (tests, local dev) and pgstore (PostgreSQL via pgx).
// The interfaces live here, next to their consumers' needs, not in the
// adapters.
package store
import (
"context"
"time"
"academy/ecommerce-api-project/domain"
)
// Store runs a unit of work. Everything fn does through tx commits or rolls
// back together: stock reservation, order, payment intent, outbox row and
// idempotency record are one transaction.
type Store interface {
InTx(ctx context.Context, fn func(ctx context.Context, tx Tx) error) error
Catalog() Catalog // read-only listing outside a transaction
}
// Tx gives access to the repositories inside one transaction.
type Tx interface {
Products() Products
Inventory() Inventory
Carts() Carts
Orders() Orders
Payments() Payments
Outbox() Outbox
Idempotency() Idempotency
}
// Catalog is the read side of the catalogue.
type Catalog interface {
ListProducts(ctx context.Context, q domain.ProductQuery) ([]domain.Product, error)
GetProduct(ctx context.Context, id int64) (domain.Product, error)
}
type Products interface {
Get(ctx context.Context, id int64) (domain.Product, error)
Create(ctx context.Context, p *domain.Product) error
// Update writes p only if the stored version is still expectedVersion
// (optimistic locking); otherwise domain.ErrConflict.
Update(ctx context.Context, p *domain.Product, expectedVersion int64) error
}
type Inventory interface {
Get(ctx context.Context, productID int64) (domain.Stock, error)
SetOnHand(ctx context.Context, productID, onHand int64) error
// Reserve holds stock for all reservations or for none
// (*domain.OutOfStockError). Input is sorted by product id.
Reserve(ctx context.Context, rs []domain.Reservation) error
Release(ctx context.Context, rs []domain.Reservation) error
// Ship turns a reservation into a shipment: on_hand -= qty, reserved -= qty.
Ship(ctx context.Context, rs []domain.Reservation) error
}
type Carts interface {
Get(ctx context.Context, id string) (domain.Cart, error)
ForUser(ctx context.Context, userID int64) (domain.Cart, error)
// Save is a compare-and-set on c.Version (0 = create): it fails with
// domain.ErrConflict if another transaction saved the cart since it was
// read, so a stale snapshot never overwrites a concurrent change. On
// success c.Version is the new version.
Save(ctx context.Context, c *domain.Cart) error
// Delete removes the cart only if it is still at version.
Delete(ctx context.Context, id string, version int64) error
// Abandoned lists customer carts not touched since before and not reminded.
Abandoned(ctx context.Context, before time.Time, limit int) ([]domain.Cart, error)
}
type Orders interface {
Create(ctx context.Context, o *domain.Order) error
Get(ctx context.Context, id string) (domain.Order, error)
// Update is a compare-and-set on version: it writes o only if the stored
// version is o.Version-1.
Update(ctx context.Context, o *domain.Order) error
ListForUser(ctx context.Context, userID int64, limit int) ([]domain.Order, error)
// Expired lists created (unpaid) orders whose ExpiresAt is before now.
Expired(ctx context.Context, now time.Time, limit int) ([]domain.Order, error)
}
type Payments interface {
Create(ctx context.Context, p domain.Payment) error
ForOrder(ctx context.Context, orderID string) (domain.Payment, error)
Update(ctx context.Context, p domain.Payment) error
}
// Outbox stores events in the business transaction; the relay publishes them.
type Outbox interface {
Add(ctx context.Context, events ...domain.Event) error
// Claim returns up to limit unpublished events, oldest first. The relay
// publishes them after this transaction and stops at the first event not
// yet due, so one relay per database keeps the order.
Claim(ctx context.Context, limit int) ([]domain.Event, error)
MarkPublished(ctx context.Context, ids []string, at time.Time) error
MarkFailed(ctx context.Context, id string, next time.Time) error
}
// IdemRecord is a stored response for an Idempotency-Key.
type IdemRecord struct {
Scope string // "POST /v1/orders user:7"
Key string
Fingerprint string // SHA-256 of the canonical request
Status int
Body []byte
CreatedAt time.Time
}
type Idempotency interface {
Get(ctx context.Context, scope, key string) (IdemRecord, error) // domain.ErrNotFound
// Put inserts the record; a concurrent insert of the same (scope, key)
// fails with ErrDuplicateKey and the whole transaction is retried, which
// then finds the winner's record and replays it.
Put(ctx context.Context, r IdemRecord) error
}
// Inbox remembers which events a consumer has already handled. Has is
// checked before the side effect and Mark called after it succeeded, so a
// crash in between repeats the side effect (at-least-once), never loses it.
type Inbox interface {
Has(ctx context.Context, consumer, eventID string) (bool, error)
Mark(ctx context.Context, consumer, eventID string) error
}// Package service is the application layer: one method per use case, each a
// transaction script over the store ports. Handlers translate HTTP to these
// calls; workers call them on a schedule. Nothing here knows about HTTP,
// SQL, RabbitMQ or SMTP.
package service
import (
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"strings"
"time"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/money"
"academy/ecommerce-api-project/pricing"
"academy/ecommerce-api-project/store"
)
// Deps are the collaborators every service shares. Clock and NewID are
// injected so tests are deterministic.
type Deps struct {
Store store.Store
Now func() time.Time
NewID func(prefix string) string
Currency money.Currency
TaxRates pricing.TaxRates
Discounts func(code string) (pricing.Discount, bool)
StockHold time.Duration // how long an unpaid order holds its stock
}
// RandomID returns prefix_ + 128 random bits in hex.
func RandomID(prefix string) string {
b := make([]byte, 16)
_, _ = rand.Read(b) // Go 1.24: "guaranteed not to fail"
return prefix + "_" + hex.EncodeToString(b)
}
// FieldError is one invalid input field.
type FieldError struct {
Field string `json:"field"`
Message string `json:"message"`
}
// ValidationError collects every invalid field (422 in the API).
type ValidationError struct{ Fields []FieldError }
func (e *ValidationError) Error() string {
parts := make([]string, len(e.Fields))
for i, f := range e.Fields {
parts[i] = f.Field + ": " + f.Message
}
return "invalid input: " + strings.Join(parts, "; ")
}
func (e *ValidationError) add(field, format string, a ...any) {
e.Fields = append(e.Fields, FieldError{Field: field, Message: fmt.Sprintf(format, a...)})
}
func (e *ValidationError) orNil() error {
if len(e.Fields) == 0 {
return nil
}
return e
}
var (
// ErrIdempotencyMismatch: the key was used before with another body (422).
ErrIdempotencyMismatch = errors.New("idempotency key reused with a different request")
// ErrAmountMismatch: the PSP reports another amount than the order total.
ErrAmountMismatch = errors.New("captured amount differs from order total")
)
func requireAdmin(p domain.Principal) error {
if !p.IsAdmin() {
return domain.ErrForbidden
}
return nil
}قیمتگذاری و پول با واحد کوچک حیاتی
به زبان ساده: قیمت یک عدد صحیح از سنت، ین یا فلس بههمراه کد ارز است. عدد صحیح را جمع کنید، نه Float را؛ یک بار در جای مشخص و با قاعدهٔ مشخص گرد کنید.
بدفهمی رایج: «اگر برای نمایش گرد کنم، float64 کافی است.» تست before نشان میدهد 0.1 + 0.2 != 0.3. وقتی هزاران ردیف را جمع و با مبلغ Captureشده در PSP مقایسه کنید، این اختلافها به تیکت پشتیبانی تبدیل میشوند. اشتباه دیگر: «همهٔ ارزها دو رقم اعشار دارند.» JPY ندارد و KWD سه رقم دارد؛ بستهٔ money جدول توان دارد و PSP هم استثناهای خودش را دارد؛ ببینید Payment Processing Architecture.
تعریف: money.Money{Amount int64, Currency} با Add/Sub/Mul کار میکند؛ ارز متفاوت را رد و Overflow را تشخیص میدهد. MulBasisPoints درصدها را با گرد کردن نیمبهزوج (Half-even یا Banker's rounding) اعمال میکند. Allocate مبلغ را به نسبت وزن تقسیم میکند تا جمع بخشها دقیقاً برابر کل بماند. ستونهای PostgreSQL از نوع BIGINT همراه CHAR(3) هستند. Fowler میگوید: "Monetary calculations are often rounded to the smallest currency unit. When you do this it's easy to lose pennies (or your local equivalent) because of rounding errors."
Step float64 money (int64 minor units)
1 0.10 EUR + 0.20 EUR 0.30000000000000004 10 + 20 = 30
2 10 % of 49.99 EUR 4.999 -> ? (display) 4999 * 1000 bp = 499.9 -> 500 (half-even)
3 spread 5.00 discount on 39.98 / 2 floats that may not Allocate([3998, 1001]) = 400 + 100 = 500
10.01 lines sum to 5.00
4 12.5 cents tax 12.5 half-even -> 12; 13.5 -> 14سناریوی واقعی: کد تخفیف 10 درصد روی سبد دوردیفی که جمع تخفیف ردیفهای فاکتور باید با تخفیف سفارش برابر باشد؛ مالیات هر ردیف روی مبلغ پس از تخفیف؛ بازپرداخت یک ردیف از سه ردیف؛ و گزارش جمع total_minor روی یک میلیون سفارش.
| محل | نوع | دلیل |
|---|---|---|
| دامنهٔ Go | money.Money یعنی int64 و کد | دقیق، ارزان و قابل مقایسه با == |
| نرخ و درصد در Go | واحد پایه (Basis point) با int64؛ 2000 = 20 % | دقیق؛ math/big.Rat فقط برای FX |
| PostgreSQL | واحد کوچک (Minor unit) با BIGINT و CHAR(3) | دقیق، قابل Index و دارای CHECK (price_minor > 0) |
| JSON | {"amount": 3999, "currency": "EUR"} | حتی در انتقال هم Float نداریم |
| Laravel | ستون صحیح، brick/money یا bcmath | همان ایده |
راهحل / نحوهٔ استفاده: کل بسته را ببینید؛ تست آن جدول قواعد گرد کردن هم هست.
// Package money is a small value type for prices: an integer amount in the
// currency's minor unit (cents, yen, fils) plus an ISO 4217 code. There is no
// float anywhere, so 0.10 + 0.20 is exactly 0.30.
package money
import (
"errors"
"fmt"
"math"
"strings"
)
// Currency is an ISO 4217 alphabetic code such as "EUR".
type Currency string
// exponent is the number of minor-unit digits per currency (ISO 4217).
var exponent = map[Currency]int{"EUR": 2, "USD": 2, "GBP": 2, "JPY": 0, "KWD": 3}
var (
ErrCurrencyMismatch = errors.New("money: currency mismatch")
ErrOverflow = errors.New("money: overflow")
ErrUnknownCurrency = errors.New("money: unknown currency")
)
// Money is an amount in minor units. The zero value is "0 of no currency".
type Money struct {
Amount int64 `json:"amount"`
Currency Currency `json:"currency"`
}
// New returns amount minor units of cur, for example New(1999, "EUR") = 19.99 EUR.
func New(amount int64, cur Currency) Money { return Money{Amount: amount, Currency: cur} }
// Zero returns 0 in cur.
func Zero(cur Currency) Money { return Money{Currency: cur} }
// Exponent reports the minor-unit digits of cur.
func Exponent(cur Currency) (int, error) {
e, ok := exponent[cur]
if !ok {
return 0, fmt.Errorf("%w: %q", ErrUnknownCurrency, cur)
}
return e, nil
}
// Add returns m+o; both must have the same currency.
func (m Money) Add(o Money) (Money, error) {
if m.Currency != o.Currency {
return Money{}, fmt.Errorf("%w: %s + %s", ErrCurrencyMismatch, m.Currency, o.Currency)
}
s := m.Amount + o.Amount
if (o.Amount > 0 && s < m.Amount) || (o.Amount < 0 && s > m.Amount) {
return Money{}, ErrOverflow
}
return Money{Amount: s, Currency: m.Currency}, nil
}
// Sub returns m-o.
func (m Money) Sub(o Money) (Money, error) {
if o.Amount == math.MinInt64 {
return Money{}, ErrOverflow
}
return m.Add(Money{Amount: -o.Amount, Currency: o.Currency})
}
// Mul returns m*q (a quantity, never a fraction).
func (m Money) Mul(q int64) (Money, error) {
if q != 0 && (m.Amount*q)/q != m.Amount {
return Money{}, ErrOverflow
}
return Money{Amount: m.Amount * q, Currency: m.Currency}, nil
}
// MulBasisPoints returns m * bp / 10000 rounded half to even (banker's
// rounding). 2000 bp is 20 %. Tax and percentage discounts use it.
func (m Money) MulBasisPoints(bp int64) Money {
return Money{Amount: divRoundHalfEven(m.Amount*bp, 10000), Currency: m.Currency}
}
func divRoundHalfEven(n, d int64) int64 {
q, r := n/d, n%d
if r == 0 {
return q
}
twice := 2 * r
if twice < 0 {
twice = -twice
}
switch {
case twice > d, twice == d && q%2 != 0:
if n < 0 {
return q - 1
}
return q + 1
}
return q
}
// Allocate splits m by integer weights so the parts always sum to m (the
// largest-remainder rule: leftover minor units go to the first parts).
// Used to spread an order-level discount over the lines.
func (m Money) Allocate(weights []int64) []Money {
var total int64
for _, w := range weights {
total += w
}
out := make([]Money, len(weights))
if total == 0 {
for i := range out {
out[i] = Zero(m.Currency)
}
return out
}
var given int64
for i, w := range weights {
out[i] = Money{Amount: m.Amount * w / total, Currency: m.Currency}
given += out[i].Amount
}
for i := 0; given < m.Amount && len(out) > 0; i = (i + 1) % len(out) {
if weights[i] == 0 {
continue
}
out[i].Amount++
given++
}
return out
}
// IsZero reports whether the amount is 0.
func (m Money) IsZero() bool { return m.Amount == 0 }
// String formats 1999 EUR as "19.99 EUR" and 500 JPY as "500 JPY".
func (m Money) String() string {
e, err := Exponent(m.Currency)
if err != nil || e == 0 {
return fmt.Sprintf("%d %s", m.Amount, m.Currency)
}
sign, a := "", m.Amount
if a < 0 {
sign, a = "-", -a
}
p := int64(math.Pow10(e))
return fmt.Sprintf("%s%d.%0*d %s", sign, a/p, e, a%p, m.Currency)
}
// Parse reads "19.99" for cur without going through float64.
func Parse(s string, cur Currency) (Money, error) {
e, err := Exponent(cur)
if err != nil {
return Money{}, err
}
neg := strings.HasPrefix(s, "-")
s = strings.TrimPrefix(s, "-")
whole, frac, _ := strings.Cut(s, ".")
if len(frac) > e || whole == "" {
return Money{}, fmt.Errorf("money: %q has more than %d decimals or no integer part", s, e)
}
frac += strings.Repeat("0", e-len(frac))
var n int64
for _, c := range whole + frac {
if c < '0' || c > '9' {
return Money{}, fmt.Errorf("money: invalid amount %q", s)
}
if n > (math.MaxInt64-int64(c-'0'))/10 {
return Money{}, ErrOverflow
}
n = n*10 + int64(c-'0')
}
if neg {
n = -n
}
return Money{Amount: n, Currency: cur}, nil
}قواعد مالیات و تخفیف به شکل تابع خالص مهم
به زبان ساده: «این سبد چقدر قیمت دارد» یک تابع از ردیفها، تخفیفها و نرخ مالیات به جمعهاست. ساعت، پایگاه داده یا درخواست را نمیخواند؛ پس با یک جدول تست میشود و ورودی یکسان دوباره همان پاسخ را میدهد.
بدفهمی رایج: «تخفیف یک UPDATE در SQL روی سفارش است.» آنوقت قاعده داخل Query بیتست پنهان میشود و سفارشی که با Idempotency بازپخش میشود شاید قیمت دیگری بگیرد. اشتباه دیگر: «مالیات کل با جمع مالیات ردیفها یکی است.» با گرد کردن و کلاسهای مالیاتی متفاوت چنین نیست؛ یک قاعده انتخاب و مستند کنید. این پروژه مالیات را برای هر ردیف روی خالص پس از تخفیف با Half-even گرد میکند.
تعریف: pricing.Quote(currency, lines, discounts, rates) مقدار Totals{Lines, Subtotal, Discount, Tax, Total, Applied} برمیگرداند. یک Discount یا PercentOff بر حسب Basis point است یا AmountOff بر حسب Minor unit که از جمع اولیه بیشتر نمیشود؛ شرط اختیاری MinSubtotal هم دارد. تخفیف سفارش با Allocate متناسب با مبلغ ناخالص ردیفها پخش میشود و مالیات هر ردیف Net * rate است. تعداد خارج از 1..99 یا کلاس مالیاتی ناشناخته خطاست.
Line Gross Discount share Net Rate Tax (half-even)
1 2 x BOOK 19.99 3998 400 3598 7 % 251.86 -> 252
2 1 x MUG 10.01 1001 100 901 20 % 180.2 -> 180
3 order 4999 500 (TEN: 10 %) 4499 432 total 4931سناریوی واقعی: «10 درصد تخفیف برای سفارش بالای 50 یورو»؛ «5 یورو تخفیف بدون منفی شدن مبلغ»؛ کتاب با VAT کاهشیافته در کنار لیوان با نرخ استاندارد؛ و برآورد صفحهٔ سبد که باید دقیقاً با مبلغ دریافتی یکی باشد.
| روش قاعدهگذاری | تستپذیری | محل اجرا | خطر |
|---|---|---|---|
تابع خالص (Pure function)، pricing.Quote | تست جدولی بدون Setup | Service و پیشنمایش سبد | خطر اضافه ندارد |
| SQL داخل Query خرید | نیازمند پایگاه داده | Repository | پنهان شدن قاعده در SQL |
| Rules engine / DSL | نیازمند موتور | هرجا | تا وقتی بازاریابی قاعده نمینویسد زیادهکاری است |
| سرویس مالیات خارجی مثل Avalara و Stripe Tax | تست قرارداد | بیرون Transaction؛ اول Quote، بعد قفل | تأخیر و دسترسپذیری |
راهحل / نحوهٔ استفاده:
// Package pricing turns cart lines into order totals. Every function here is
// pure: same input, same output, no clock, no database. That is what makes
// tax and discount rules testable with a table and safe to re-run when an
// order is replayed.
package pricing
import (
"errors"
"fmt"
"academy/ecommerce-api-project/money"
)
// Line is one cart line priced from the catalogue (never from the client).
type Line struct {
ProductID int64
SKU string
Unit money.Money
Qty int64
TaxClass string // "standard", "reduced", "zero"
}
// DiscountKind says how a discount is computed.
type DiscountKind int
const (
PercentOff DiscountKind = iota + 1 // BasisPoints of the subtotal
AmountOff // a fixed Amount, capped at the subtotal
)
// Discount is a promotion rule. MinSubtotal is in minor units.
type Discount struct {
Code string
Kind DiscountKind
BasisPoints int64
Amount int64
MinSubtotal int64
}
// TaxRates maps a tax class to a rate in basis points (2000 = 20 %).
type TaxRates map[string]int64
// PricedLine is a line after discount allocation and tax.
type PricedLine struct {
Line
Gross money.Money // Unit * Qty
Discount money.Money // share of the order discount
Net money.Money // Gross - Discount
Tax money.Money // Net * rate, rounded half-even per line
}
// Totals is the result of Quote.
type Totals struct {
Lines []PricedLine
Subtotal money.Money
Discount money.Money
Tax money.Money
Total money.Money
Applied []string // discount codes that applied
}
var (
ErrNoLines = errors.New("pricing: no lines")
ErrBadQuantity = errors.New("pricing: quantity must be between 1 and 99")
ErrUnknownTax = errors.New("pricing: unknown tax class")
)
// Quote prices the lines. Tax is computed on the discounted net amount of
// each line (tax-exclusive prices), which is how most EU and US shops do it.
func Quote(cur money.Currency, lines []Line, discounts []Discount, rates TaxRates) (Totals, error) {
if len(lines) == 0 {
return Totals{}, ErrNoLines
}
t := Totals{Subtotal: money.Zero(cur), Discount: money.Zero(cur), Tax: money.Zero(cur), Total: money.Zero(cur)}
weights := make([]int64, len(lines))
for i, l := range lines {
if l.Qty < 1 || l.Qty > 99 {
return Totals{}, fmt.Errorf("%w: %s qty %d", ErrBadQuantity, l.SKU, l.Qty)
}
gross, err := l.Unit.Mul(l.Qty)
if err != nil {
return Totals{}, err
}
if t.Subtotal, err = t.Subtotal.Add(gross); err != nil {
return Totals{}, err
}
t.Lines = append(t.Lines, PricedLine{Line: l, Gross: gross})
weights[i] = gross.Amount
}
off := int64(0)
for _, d := range discounts {
if t.Subtotal.Amount < d.MinSubtotal {
continue
}
off += discountAmount(d, t.Subtotal)
t.Applied = append(t.Applied, d.Code)
}
off = min(off, t.Subtotal.Amount) // never a negative total
t.Discount = money.New(off, cur)
shares := t.Discount.Allocate(weights)
for i := range t.Lines {
pl := &t.Lines[i]
rate, ok := rates[pl.TaxClass]
if !ok {
return Totals{}, fmt.Errorf("%w: %q", ErrUnknownTax, pl.TaxClass)
}
pl.Discount = shares[i]
pl.Net, _ = pl.Gross.Sub(pl.Discount)
pl.Tax = pl.Net.MulBasisPoints(rate)
t.Tax, _ = t.Tax.Add(pl.Tax)
}
net, _ := t.Subtotal.Sub(t.Discount)
t.Total, _ = net.Add(t.Tax)
return t, nil
}
func discountAmount(d Discount, subtotal money.Money) int64 {
switch d.Kind {
case PercentOff:
return subtotal.MulBasisPoints(d.BasisPoints).Amount
case AmountOff:
return d.Amount
}
return 0
}package pricing
import (
"errors"
"testing"
"academy/ecommerce-api-project/money"
)
var rates = TaxRates{"standard": 2000, "reduced": 700, "zero": 0}
func eur(a int64) money.Money { return money.New(a, "EUR") }
func TestQuote(t *testing.T) {
book := Line{ProductID: 1, SKU: "BOOK", Unit: eur(1999), Qty: 2, TaxClass: "reduced"}
mug := Line{ProductID: 2, SKU: "MUG", Unit: eur(1001), Qty: 1, TaxClass: "standard"}
tests := []struct {
name string
lines []Line
discounts []Discount
subtotal, discount, tax, total int64
applied int
}{
{"no discount", []Line{book, mug}, nil, 4999, 0, 280 + 200, 4999 + 480, 0},
{"10 percent off", []Line{book, mug}, []Discount{{Code: "TEN", Kind: PercentOff, BasisPoints: 1000}},
4999, 500, 252 + 180, 4499 + 432, 1},
{"amount off below threshold is ignored", []Line{mug}, []Discount{{Code: "FIVE", Kind: AmountOff, Amount: 500, MinSubtotal: 5000}},
1001, 0, 200, 1201, 0},
{"amount off capped at subtotal", []Line{mug}, []Discount{{Code: "BIG", Kind: AmountOff, Amount: 5000}},
1001, 1001, 0, 0, 1},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := Quote("EUR", tt.lines, tt.discounts, rates)
if err != nil {
t.Fatal(err)
}
if got.Subtotal.Amount != tt.subtotal || got.Discount.Amount != tt.discount ||
got.Tax.Amount != tt.tax || got.Total.Amount != tt.total || len(got.Applied) != tt.applied {
t.Fatalf("got sub %d disc %d tax %d total %d applied %v", got.Subtotal.Amount,
got.Discount.Amount, got.Tax.Amount, got.Total.Amount, got.Applied)
}
var lineDisc int64
for _, l := range got.Lines {
lineDisc += l.Discount.Amount
}
if lineDisc != got.Discount.Amount {
t.Fatalf("line discounts %d != order discount %d", lineDisc, got.Discount.Amount)
}
})
}
}
func TestQuoteRejectsBadInput(t *testing.T) {
if _, err := Quote("EUR", nil, nil, rates); !errors.Is(err, ErrNoLines) {
t.Fatalf("got %v", err)
}
if _, err := Quote("EUR", []Line{{SKU: "X", Unit: eur(1), Qty: 0, TaxClass: "zero"}}, nil, rates); !errors.Is(err, ErrBadQuantity) {
t.Fatalf("got %v", err)
}
if _, err := Quote("EUR", []Line{{SKU: "X", Unit: eur(1), Qty: 1, TaxClass: "luxury"}}, nil, rates); !errors.Is(err, ErrUnknownTax) {
t.Fatalf("got %v", err)
}
}Schema و Migration در Postgres حیاتی
به زبان ساده: ساختار داده (Schema) بخشی از قواعد کسبوکار است که حتی با وجود باگ کد پابرجا میماند. هر ستون پول باید صحیح باشد، هر وضعیت CHECK داشته باشد، هر قاعدهٔ «یکی به ازای هر کدام» با UNIQUE بیان شود و هر پیمایش پسزمینه Partial index داشته باشد. تغییر فقط از فایلهای شمارهدار Migration انجام میشود.
بدفهمی رایج: «Constraint تکرار اعتبارسنجی Go است، حذفش کنیم.» کد Go در هر بار اجرا داخل یک فرایند است، ولی Constraint برای همهٔ نویسندهها اجرا میشود؛ از Admin که ساعت دو بامداد دستی داده را اصلاح میکند تا سرویس بعدی که به جدول مینویسد. اشتباه دیگر: «برنامه هنگام بالا آمدن Migration را اجرا کند.» وقتی سه Replica همزمان شروع شوند، سه فرایند برای Migration رقابت میکنند؛ آن را مرحلهٔ جداگانهٔ استقرار کنید.
تعریف: فایلهای pgstore/migrations/0001_init.up.sql و .down.sql از نامگذاری NNNN_name.up.sql/.down.sql در golang-migrate پیروی میکنند؛ goose یک فایل با بخشهای -- +goose Up/Down دارد. Constraintهای مهم: inventory_no_oversell CHECK (reserved <= on_hand)، payments.order_id UNIQUE برای یک Intent در هر سفارش، provider_key UNIQUE برای یک کلید PSP در هر تلاش، outbox.event_id UNIQUE، idempotency_keys PRIMARY KEY (scope, key) و carts_one_per_user که Partial unique index روی user_id WHERE user_id IS NOT NULL است. ستون products.search یک Stored generated column با عبارت to_tsvector('simple', name || ' ' || sku) و Index از نوع GIN است. مستندات PostgreSQL دربارهٔ Partial index میگویند میتوان "a subset of a table" را Index کرد؛ دقیقاً همان کاری که orders_unpaid_expiry ... WHERE status = 'created' و outbox_unpublished ... WHERE published_at IS NULL میکنند. هرچقدر سفارش قدیمی جمع شود، پیمایش پسزمینه کوچک میماند.
Migration step (deploy pipeline) Effect
1 migrate -path pgstore/migrations -database $URL up applies 0001 once, records version 1
2 new replicas start no DDL at start-up, they just connect
3 0002 adds a column NULLable, backfills in batches old code still works (expand)
4 deploy code that writes the column
5 0003 sets NOT NULL contract, once all writers are newسناریوی واقعی: باگ تخفیف مقدار reserved را بالاتر از on_hand میبرد و CHECK آن را به خطا تبدیل میکند، نه فروش اضافه؛ Payment intent دوم برای یک سفارش روی order_id UNIQUE شکست میخورد؛ درج دوبارهٔ رویداد Webhook به event_id UNIQUE میخورد؛ میلیونها سبد مهمان رهاشده Job یادآوری را کند نمیکنند، چون Index فقط سبد مشتریان بدون یادآوری را پوشش میدهد.
| جدول | Constraintهای اصلی | Indexها | دلیل |
|---|---|---|---|
products | sku UNIQUE، price_minor > 0 | Index جزئی Keyset برای هر Sort، GIN روی search | فهرست و جستوجو |
inventory | reserved >= 0، reserved <= on_hand | PK | پشتیبان جلوگیری از فروش اضافه |
carts، cart_items | qty BETWEEN 1 AND 10، یک سبد برای هر کاربر | Partial index به نام carts_abandoned | سبد و یادآوری |
orders | status IN (...)، total_minor >= 0 | (user_id, created_at DESC) و Partial روی status = 'created' | تاریخچه و Job انقضا |
order_items | PK برابر (order_id, line)، qty > 0 | PK | Snapshot |
payments | order_id UNIQUE، provider_key UNIQUE، provider_ref UNIQUE | Uniqueها | یک Intent و یک شیء PSP |
outbox | event_id UNIQUE | Partial روی منتشرنشدهها | پیمایش Relay |
idempotency_keys | PK برابر (scope, key)، طول کلید 8..255 | PK | بازپخش |
processed_events | PK برابر (consumer, event_id) | PK | Inbox |
راهحل / نحوهٔ استفاده: Migration با //go:embed migrations/*.sql داخل Binary است تا زیرفرمان migrate یا تست بتواند آن را بخواند.
-- 0001_init: the e-commerce schema. Money is BIGINT minor units + CHAR(3).
CREATE TABLE users (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
role TEXT NOT NULL DEFAULT 'customer' CHECK (role IN ('customer', 'admin')),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE categories (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
slug TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
parent_id BIGINT REFERENCES categories (id)
);
CREATE TABLE products (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sku TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
category_id BIGINT REFERENCES categories (id),
price_minor BIGINT NOT NULL CHECK (price_minor > 0),
currency CHAR(3) NOT NULL,
tax_class TEXT NOT NULL,
active BOOLEAN NOT NULL DEFAULT true,
version BIGINT NOT NULL DEFAULT 1,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
search TSVECTOR GENERATED ALWAYS AS (to_tsvector('simple', name || ' ' || sku)) STORED
);
-- Keyset pagination: one index per sort order, partial on active rows.
CREATE INDEX products_newest ON products (created_at DESC, id DESC) WHERE active;
CREATE INDEX products_price ON products (price_minor, id) WHERE active;
CREATE INDEX products_name ON products ((name COLLATE "C"), id) WHERE active;
CREATE INDEX products_cat ON products (category_id, created_at DESC, id DESC) WHERE active;
CREATE INDEX products_search ON products USING GIN (search);
CREATE TABLE inventory (
product_id BIGINT PRIMARY KEY REFERENCES products (id),
on_hand BIGINT NOT NULL DEFAULT 0,
reserved BIGINT NOT NULL DEFAULT 0,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT inventory_reserved_nonneg CHECK (reserved >= 0),
CONSTRAINT inventory_no_oversell CHECK (reserved <= on_hand)
);
CREATE TABLE carts (
id TEXT PRIMARY KEY, -- opaque random token (guest cookie)
user_id BIGINT REFERENCES users (id), -- NULL for guests
email TEXT,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
reminded_at TIMESTAMPTZ,
version BIGINT NOT NULL DEFAULT 1 -- compare-and-set on every save
);
CREATE UNIQUE INDEX carts_one_per_user ON carts (user_id) WHERE user_id IS NOT NULL;
CREATE INDEX carts_abandoned ON carts (updated_at) WHERE user_id IS NOT NULL AND reminded_at IS NULL;
CREATE TABLE cart_items (
cart_id TEXT NOT NULL REFERENCES carts (id) ON DELETE CASCADE,
product_id BIGINT NOT NULL REFERENCES products (id),
qty INT NOT NULL CHECK (qty BETWEEN 1 AND 10),
PRIMARY KEY (cart_id, product_id)
);
CREATE TABLE orders (
id TEXT PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users (id),
email TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('created', 'paid', 'fulfilled', 'cancelled', 'refunded')),
subtotal_minor BIGINT NOT NULL,
discount_minor BIGINT NOT NULL DEFAULT 0,
tax_minor BIGINT NOT NULL,
total_minor BIGINT NOT NULL CHECK (total_minor >= 0),
currency CHAR(3) NOT NULL,
version BIGINT NOT NULL DEFAULT 1,
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL,
expires_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX orders_by_user ON orders (user_id, created_at DESC);
-- The stock-release job scans only unpaid orders.
CREATE INDEX orders_unpaid_expiry ON orders (expires_at) WHERE status = 'created';
CREATE TABLE order_items (
order_id TEXT NOT NULL REFERENCES orders (id) ON DELETE CASCADE,
line INT NOT NULL,
product_id BIGINT NOT NULL REFERENCES products (id),
sku TEXT NOT NULL,
name TEXT NOT NULL,
unit_minor BIGINT NOT NULL,
qty INT NOT NULL CHECK (qty > 0),
discount_minor BIGINT NOT NULL,
tax_minor BIGINT NOT NULL,
line_total_minor BIGINT NOT NULL,
PRIMARY KEY (order_id, line)
);
CREATE TABLE payments (
id TEXT PRIMARY KEY,
order_id TEXT NOT NULL UNIQUE REFERENCES orders (id), -- one intent per order
amount_minor BIGINT NOT NULL,
currency CHAR(3) NOT NULL,
status TEXT NOT NULL CHECK (status IN ('requires_payment_method', 'succeeded', 'canceled', 'refund_pending', 'refunded')),
provider_key TEXT NOT NULL UNIQUE, -- <order>:attempt:<n>
provider_ref TEXT UNIQUE, -- pi_... from the PSP
updated_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE outbox (
seq BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
event_id TEXT NOT NULL UNIQUE,
type TEXT NOT NULL,
aggregate_id TEXT NOT NULL,
payload JSONB NOT NULL,
occurred_at TIMESTAMPTZ NOT NULL,
attempts INT NOT NULL DEFAULT 0,
next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(),
published_at TIMESTAMPTZ
);
CREATE INDEX outbox_unpublished ON outbox (seq) WHERE published_at IS NULL;
CREATE TABLE idempotency_keys (
scope TEXT NOT NULL,
key TEXT NOT NULL CHECK (length(key) BETWEEN 8 AND 255),
fingerprint TEXT NOT NULL,
status INT NOT NULL,
body BYTEA NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (scope, key)
);
CREATE TABLE processed_events (
consumer TEXT NOT NULL,
event_id TEXT NOT NULL,
processed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (consumer, event_id)
);Repository و Transaction: اجرای Store.InTx و حلقهٔ Retry حیاتی
به زبان ساده: Service میگوید «این تابع را در یک تراکنش (Transaction) اجرا کن». Store آن را آغاز میکند، Repositoryهای متصل به همان Transaction را به تابع میدهد، با بازگشت nil، Commit و در غیر این صورت Rollback میکند. اگر PostgreSQL بگوید نتیجه به زمانبندی وابسته بوده، کل تابع دوباره اجرا میشود.
بدفهمی رایج: «*sql.Tx یا pgx.Tx را به Service بدهیم.» آنوقت همهٔ Serviceها Driver را Import میکنند و Fake حافظهای باید pgx را تقلید کند. اشتباه مقابل: «هر متد Repository، Transaction خودش را باز کند.» با این کار رزرو موجودی و ساخت سفارش دو Transaction میشوند و Crash میانشان موجودی را نشت میدهد. سوم: «Retry کردن Transaction برای هر تابعی امن است.» فقط وقتی اثر جانبی بیرون Transaction ندارد؛ برای همین PlaceOrder هیچ HTTP call یا Publish ندارد.
تعریف: امضا store.Store.InTx(ctx, fn func(ctx, tx store.Tx) error) error است. pgstore.Store.InTx با READ COMMITTED شروع میکند و lock_timeout را برای همان Transaction تنظیم میکند: set_config('lock_timeout', '5s', true) شکل تابعی SET LOCAL است. سپس fn را اجرا و Commit میکند. روی SQLSTATE 40001 یعنی serialization_failure، 40P01 یعنی deadlock_detected، یا باختن رقابت کلید Idempotency، تا MaxAttempts برابر 3 با Jitter کوتاه دوباره اجرا میکند. روی 55P03 یعنی lock_not_available، مقدار store.ErrBusy برمیگردد. فصل Isolation در PostgreSQL صریح است: Serialization failureها "always return with an SQLSTATE value of '40001'". Rollback از context.WithoutCancel(ctx) استفاده میکند تا حتی درخواست لغوشده قفلهایش را سریع آزاد کند.
T1 (checkout A) T2 (checkout B), same last unit
1 BEGIN; lock stock row 42 (FOR UPDATE)
2 BEGIN; lock stock row 42 -> waits
3 INSERT order, payment, outbox; COMMIT
4 lock granted, reads committed row: available 0
5 OutOfStockError -> ROLLBACK -> 409
(with SERIALIZABLE instead of the lock: T2 fails at commit with 40001 and InTx re-runs it;
the re-run reads available 0 and returns 409 the same way)سناریوی واقعی: دو Admin همزمان موجودی یک محصول را پر (restock) و اصلاح میکنند؛ Checkout و Job ارسال روی دو سطر موجودی Deadlock میکنند که ترتیب قفل جلویش را میگیرد و Retry پشتیبان آن است؛ در حراج Checkout دوم باید رزرو اولی را ببیند؛ یا مشتری وسط Transaction درخواست را لغو میکند.
| خطا | SQLSTATE / مقدار | رفتار InTx | پاسخ API |
|---|---|---|---|
| serialization_failure | 40001 | اجرای مجدد، حداکثر 3 بار | پس از 3 بار: 500 و ثبت store.ErrRetryable در Log |
| deadlock_detected | 40P01 | اجرای مجدد | مانند بالا |
unique_violation روی idempotency_keys یا ErrDuplicateKey | 23505 | اجرای مجدد که بازپخش میکند | 201 بازپخششده |
| lock_not_available | 55P03 | بازگرداندن ErrBusy | 409 busy با Retry-After: 1؛ کلید تکراری در حال اجرا یا موجودی بسیار داغ |
check_violation برای inventory_no_oversell | 23514 | بازگشت | 409 کمبود موجودی، نگاشت در SetOnHand |
خطای کسبوکار؛ ErrEmptyCart، OutOfStockError | n/a | بازگشت بدون Retry | 422 / 409 |
| context canceled | context.Canceled | بازگشت | کلاینت رفته است |
راهحل / نحوهٔ استفاده: اجراکنندهٔ Transaction در Adapter؛ SQL هر جدول در repos.go است.
// Package pgstore implements store.Store on PostgreSQL with pgx v5.
// Transactions run at READ COMMITTED with explicit row locks where the
// business needs them (stock), compare-and-set version columns where it
// does not (orders, products), and are re-run on serialization failure
// (40001), deadlock (40P01) and a lost race on an idempotency key (23505).
package pgstore
import (
"context"
"embed"
"errors"
"math/rand/v2"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"academy/ecommerce-api-project/store"
)
// Migrations holds the versioned SQL files (golang-migrate / goose naming).
//
//go:embed migrations/*.sql
var Migrations embed.FS
// beginner is the part of *pgxpool.Pool this package needs; tests fake it.
type beginner interface {
BeginTx(ctx context.Context, opts pgx.TxOptions) (pgx.Tx, error)
}
// Store is the PostgreSQL adapter.
type Store struct {
db beginner
reader querier
MaxAttempts int
LockTimeout string // SET LOCAL lock_timeout, e.g. "5s"
FullText bool // search with tsvector instead of ILIKE
}
var _ store.Store = (*Store)(nil)
// New wraps a pool (*pgxpool.Pool satisfies both interfaces).
func New(pool interface {
beginner
querier
}) *Store {
return &Store{db: pool, reader: pool, MaxAttempts: 3, LockTimeout: "5s"}
}
// InTx runs fn in a transaction and re-runs it from the start when
// PostgreSQL says the outcome depends on timing. fn must therefore have no
// side effects outside tx (no HTTP calls, no publishing).
func (s *Store) InTx(ctx context.Context, fn func(ctx context.Context, tx store.Tx) error) error {
var err error
for attempt := 1; ; attempt++ {
err = s.once(ctx, fn)
if err == nil || attempt >= max(s.MaxAttempts, 1) || !retryable(err) {
return classify(err)
}
// Jitter so two retried transactions do not collide again.
t := time.NewTimer(time.Duration(rand.IntN(20*attempt)+1) * time.Millisecond)
select {
case <-ctx.Done():
t.Stop()
return errors.Join(err, ctx.Err())
case <-t.C:
}
}
}
func (s *Store) once(ctx context.Context, fn func(ctx context.Context, tx store.Tx) error) (err error) {
tx, err := s.db.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.ReadCommitted})
if err != nil {
return err
}
defer func() {
if err != nil {
// Rollback with a context that survives the request's cancellation.
_ = tx.Rollback(context.WithoutCancel(ctx))
}
}()
if s.LockTimeout != "" {
if _, err = tx.Exec(ctx, "SELECT set_config('lock_timeout', $1, true)", s.LockTimeout); err != nil {
return err
}
}
if err = fn(ctx, &pgTx{tx: tx, fullText: s.FullText}); err != nil {
return err
}
return tx.Commit(ctx)
}
// SQLSTATE codes this package reacts to (PostgreSQL Appendix A).
const (
codeUniqueViolation = "23505"
codeCheckViolation = "23514"
codeSerialization = "40001"
codeDeadlock = "40P01"
codeLockNotAvailable = "55P03"
constraintNoOversell = "inventory_no_oversell"
constraintIdempotency = "idempotency_keys_pkey"
)
func pgCode(err error) (string, string) {
var pe *pgconn.PgError
if errors.As(err, &pe) {
return pe.Code, pe.ConstraintName
}
return "", ""
}
func retryable(err error) bool {
code, constraint := pgCode(err)
switch {
case code == codeSerialization, code == codeDeadlock:
return true
case code == codeUniqueViolation && constraint == constraintIdempotency:
return true // the winner committed; the re-run finds its record and replays
}
return errors.Is(err, store.ErrDuplicateKey)
}
// classify turns driver errors into store errors the services understand.
func classify(err error) error {
switch code, _ := pgCode(err); code {
case codeLockNotAvailable:
return errors.Join(store.ErrBusy, err)
case codeSerialization, codeDeadlock:
return errors.Join(store.ErrRetryable, err)
}
return err
}موجودی: SELECT FOR UPDATE یا Version خوشبینانه حیاتی
به زبان ساده: برای عدد داغ و پررقابت، یعنی موجودی محصول محبوب، طی چند میلیثانیهٔ Checkout قفل سطر (Row lock) بگیرید. برای دادهای که آهسته در فرم ویرایش میشود، مثل قیمت محصول، یا وضعیت سفارشی که Job تغییرش میدهد، قفل نگه ندارید؛ Version خواندهشده را به یاد بسپارید و فقط اگر تغییر نکرده بنویسید.
بدفهمی رایج: «قفلگذاری خوشبینانه (Optimistic locking) همیشه سریعتر است.» زیر رقابت، نویسندهها میبازند و Retry میکنند؛ برای 10 واحد آخر و 1,000 خریدار تقریباً همهٔ تلاشها هدر میروند. عکس آن: «همهجا FOR UPDATE امنتر است.» قفلی که طی پنج دقیقه ویرایش فرم Admin بماند همهٔ Checkoutهای محصول را متوقف میکند. برای هر منبع جدا تصمیم بگیرید. سوم: «ترتیب قفل مهم نیست.» قفل کردن محصولات 9 سپس 3 و 3 سپس 9 به Deadlock با 40P01 میرسد؛ domain.SortReservations ابتدا همهٔ رزروها را به ترتیب شناسهٔ محصول میچیند.
تعریف: در روش بدبینانه (Pessimistic locking)، SELECT product_id, on_hand - reserved FROM inventory WHERE product_id = ANY($1) ORDER BY product_id FOR UPDATE اجرا میشود؛ همهٔ ردیفها بررسی میشوند و سپس UPDATE ... SET reserved = reserved + $2 انجام میشود. PostgreSQL میگوید: "To prevent the operation from waiting for other transactions to commit, use either the NOWAIT or SKIP LOCKED option". هیچکدام برای Checkout مناسب نیست، چون «3 میلیثانیه منتظر بمان» را به شکست تبدیل میکنند؛ اما SKIP LOCKED مناسب پیمایش سبد رهاشده است. جایگزین تکردیفی، UPDATE inventory SET reserved = reserved + $2 WHERE product_id = $1 AND on_hand - reserved >= $2 و بررسی RowsAffected است. در روش خوشبینانه، UPDATE products SET ..., version = version + 1 WHERE id = $1 AND version = $2 میزنیم؛ صفر سطر یعنی دیگری برده است: domain.ErrConflict برای If-Match به 412 میرسد، یا Job با retryConflict دوباره میخواند و تلاش میکند. بحث عمومی در Optimistic & Pessimistic Locking است.
Admin A (form) Admin B (form) Checkout C
1 GET product 7 -> ETag "3" GET product 7 -> ETag "3"
2 FOR UPDATE stock 7 (3 ms) ... COMMIT
3 PUT price, If-Match "3" -> 200, version 4
4 PUT price, If-Match "3" -> 412 (version is 4)
5 GET again, decide, PUT If-Match "4" -> 200
No lock was held during the minutes between 1 and 3; the checkout never waited for an admin.سناریوی واقعی: حراج روی یک SKU نیازمند قفل است؛ ویرایش قیمت Admin نیازمند Version؛ رقابت Job آزادسازی و پرداخت دیررس روی سفارش با Version روی orders حل میشود و بازنده وضعیت جدید را میخواند؛ همگامسازی انبار که on_hand را تنظیم میکند قفل کوتاه میخواهد؛ ورود انبوه داده هم یک Transaction در هر Batch و ترتیب قفل بر اساس id میخواهد.
| منبع | رقابت | مدت نگهداری | انتخاب اینجا | شکل شکست |
|---|---|---|---|---|
سطر inventory | زیاد در حراج | میلیثانیه | SELECT ... FOR UPDATE به ترتیب id | انتظار؛ 55P03 پس از lock_timeout |
سطر products | کم | چند دقیقهٔ فرم | version و If-Match | 412؛ بارگذاری مجدد کاربر |
سطر orders | کم، اما Job در برابر Webhook | میلیثانیه | Compare-and-set روی version | ErrConflict، خواندن مجدد و Retry |
carts برای یادآوری | ندارد؛ Batch | میلیثانیه | FOR UPDATE SKIP LOCKED | Worker دوم از سطر میگذرد |
| کل Checkout | هر مقدار | میلیثانیه | SERIALIZABLE و Retry، بهعنوان جایگزین | 40001 و اجرای مجدد |
راهحل / نحوهٔ استفاده: Repositoryهای موجودی، سفارش و محصول بههمراه بقیهٔ SQL:
package pgstore
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/money"
"academy/ecommerce-api-project/store"
)
// querier is what both pgx.Tx and *pgxpool.Pool offer.
type querier interface {
Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
}
type pgTx struct {
tx pgx.Tx
fullText bool
}
func (t *pgTx) Products() store.Products { return products{t.tx} }
func (t *pgTx) Inventory() store.Inventory { return inventory{t.tx} }
func (t *pgTx) Carts() store.Carts { return carts{t.tx} }
func (t *pgTx) Orders() store.Orders { return orders{t.tx} }
func (t *pgTx) Payments() store.Payments { return payments{t.tx} }
func (t *pgTx) Outbox() store.Outbox { return outbox{t.tx} }
func (t *pgTx) Idempotency() store.Idempotency { return idem{t.tx} }
func notFound(err error) error {
if errors.Is(err, pgx.ErrNoRows) {
return domain.ErrNotFound
}
return err
}
// ---- products ----
type products struct{ q querier }
const productCols = `id, sku, name, coalesce(category_id, 0), price_minor, currency, tax_class, active, version, created_at`
func scanProduct(r pgx.Row) (domain.Product, error) {
var p domain.Product
var cur string
err := r.Scan(&p.ID, &p.SKU, &p.Name, &p.CategoryID, &p.Price.Amount, &cur, &p.TaxClass, &p.Active, &p.Version, &p.CreatedAt)
p.Price.Currency = money.Currency(cur)
return p, notFound(err)
}
func (r products) Get(ctx context.Context, id int64) (domain.Product, error) {
return scanProduct(r.q.QueryRow(ctx, `SELECT `+productCols+` FROM products WHERE id = $1`, id))
}
func (r products) Create(ctx context.Context, p *domain.Product) error {
err := r.q.QueryRow(ctx, `
INSERT INTO products (sku, name, category_id, price_minor, currency, tax_class, active, created_at)
VALUES ($1, $2, nullif($3, 0), $4, $5, $6, $7, $8) RETURNING id, version`,
p.SKU, p.Name, p.CategoryID, p.Price.Amount, string(p.Price.Currency), p.TaxClass, p.Active, p.CreatedAt,
).Scan(&p.ID, &p.Version)
if err != nil {
return err
}
_, err = r.q.Exec(ctx, `INSERT INTO inventory (product_id) VALUES ($1)`, p.ID)
return err
}
// Update is optimistic: no lock is held while the admin edits the form; the
// write succeeds only if nobody else wrote in between.
func (r products) Update(ctx context.Context, p *domain.Product, expected int64) error {
tag, err := r.q.Exec(ctx, `
UPDATE products SET name = $3, price_minor = $4, tax_class = $5, active = $6, version = version + 1
WHERE id = $1 AND version = $2`,
p.ID, expected, p.Name, p.Price.Amount, p.TaxClass, p.Active)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return domain.ErrConflict
}
p.Version = expected + 1
return nil
}
// ---- inventory ----
type inventory struct{ q querier }
func (r inventory) Get(ctx context.Context, id int64) (domain.Stock, error) {
s := domain.Stock{ProductID: id}
err := r.q.QueryRow(ctx, `SELECT on_hand, reserved FROM inventory WHERE product_id = $1`, id).Scan(&s.OnHand, &s.Reserved)
return s, notFound(err)
}
func (r inventory) SetOnHand(ctx context.Context, id, onHand int64) error {
_, err := r.q.Exec(ctx, `UPDATE inventory SET on_hand = $2, updated_at = now() WHERE product_id = $1`, id, onHand)
if code, c := pgCode(err); code == codeCheckViolation && c == constraintNoOversell {
return &domain.OutOfStockError{ProductID: id, Available: onHand}
}
return err
}
// Reserve locks every stock row of the order with SELECT ... FOR UPDATE, in
// product-id order (rs is sorted), checks availability for all of them and
// only then increments reserved. A concurrent checkout for the same product
// waits on the row lock and re-reads the committed numbers afterwards.
func (r inventory) Reserve(ctx context.Context, rs []domain.Reservation) error {
ids := make([]int64, len(rs))
for i, x := range rs {
ids[i] = x.ProductID
}
rows, err := r.q.Query(ctx, `
SELECT product_id, on_hand - reserved FROM inventory
WHERE product_id = ANY($1) ORDER BY product_id FOR UPDATE`, ids)
if err != nil {
return err
}
avail, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) ([2]int64, error) {
var v [2]int64
err := row.Scan(&v[0], &v[1])
return v, err
})
if err != nil {
return err
}
have := map[int64]int64{}
for _, v := range avail {
have[v[0]] = v[1]
}
for _, x := range rs {
if have[x.ProductID] < x.Qty {
return &domain.OutOfStockError{ProductID: x.ProductID, Wanted: x.Qty, Available: have[x.ProductID]}
}
}
return r.add(ctx, rs, 1, 0)
}
func (r inventory) Release(ctx context.Context, rs []domain.Reservation) error {
return r.add(ctx, rs, -1, 0)
}
func (r inventory) Ship(ctx context.Context, rs []domain.Reservation) error {
return r.add(ctx, rs, -1, -1)
}
func (r inventory) add(ctx context.Context, rs []domain.Reservation, reservedSign, onHandSign int64) error {
for _, x := range rs {
if _, err := r.q.Exec(ctx, `
UPDATE inventory SET reserved = reserved + $2, on_hand = on_hand + $3, updated_at = now()
WHERE product_id = $1`, x.ProductID, reservedSign*x.Qty, onHandSign*x.Qty); err != nil {
return err
}
}
return nil
}
// ---- carts ----
type carts struct{ q querier }
func (r carts) Get(ctx context.Context, id string) (domain.Cart, error) {
c := domain.Cart{ID: id}
var uid *int64
var email *string
err := r.q.QueryRow(ctx, `SELECT user_id, email, updated_at, reminded_at, version FROM carts WHERE id = $1`, id).
Scan(&uid, &email, &c.UpdatedAt, &c.RemindedAt, &c.Version)
if err != nil {
return c, notFound(err)
}
if uid != nil {
c.UserID = *uid
}
if email != nil {
c.Email = *email
}
rows, err := r.q.Query(ctx, `SELECT product_id, qty FROM cart_items WHERE cart_id = $1 ORDER BY product_id`, id)
if err != nil {
return c, err
}
c.Items, err = pgx.CollectRows(rows, pgx.RowToStructByPos[domain.CartItem])
return c, err
}
func (r carts) ForUser(ctx context.Context, userID int64) (domain.Cart, error) {
var id string
if err := r.q.QueryRow(ctx, `SELECT id FROM carts WHERE user_id = $1`, userID).Scan(&id); err != nil {
return domain.Cart{}, notFound(err)
}
return r.Get(ctx, id)
}
// Save is a compare-and-set on version. Under READ COMMITTED a concurrent
// save of the same cart makes this UPDATE wait, then re-check the WHERE
// clause against the committed row: the stale writer matches 0 rows and gets
// ErrConflict instead of replacing the items with its old snapshot. A new
// cart (version 0) is inserted; a second new cart for the same customer hits
// carts_one_per_user and is reported as a conflict too.
func (r carts) Save(ctx context.Context, c *domain.Cart) error {
var tag pgconn.CommandTag
var err error
if c.Version == 0 {
tag, err = r.q.Exec(ctx, `
INSERT INTO carts (id, user_id, email, updated_at, reminded_at, version)
VALUES ($1, nullif($2, 0), nullif($3, ''), $4, $5, 1) ON CONFLICT (id) DO NOTHING`,
c.ID, c.UserID, c.Email, c.UpdatedAt, c.RemindedAt)
} else {
tag, err = r.q.Exec(ctx, `
UPDATE carts SET user_id = nullif($3, 0), email = nullif($4, ''), updated_at = $5,
reminded_at = $6, version = version + 1
WHERE id = $1 AND version = $2`,
c.ID, c.Version, c.UserID, c.Email, c.UpdatedAt, c.RemindedAt)
}
if code, _ := pgCode(err); code == codeUniqueViolation {
return domain.ErrConflict
}
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return domain.ErrConflict
}
c.Version++
if _, err := r.q.Exec(ctx, `DELETE FROM cart_items WHERE cart_id = $1`, c.ID); err != nil {
return err
}
for _, it := range c.Items {
if _, err := r.q.Exec(ctx, `INSERT INTO cart_items (cart_id, product_id, qty) VALUES ($1, $2, $3)`,
c.ID, it.ProductID, it.Qty); err != nil {
return err
}
}
return nil
}
func (r carts) Delete(ctx context.Context, id string, version int64) error {
tag, err := r.q.Exec(ctx, `DELETE FROM carts WHERE id = $1 AND version = $2`, id, version)
if err == nil && tag.RowsAffected() == 0 {
return domain.ErrConflict
}
return err
}
func (r carts) Abandoned(ctx context.Context, before time.Time, limit int) ([]domain.Cart, error) {
rows, err := r.q.Query(ctx, `
SELECT c.id FROM carts c
WHERE c.user_id IS NOT NULL AND c.reminded_at IS NULL AND c.updated_at < $1
AND EXISTS (SELECT 1 FROM cart_items i WHERE i.cart_id = c.id)
ORDER BY c.updated_at LIMIT $2 FOR UPDATE SKIP LOCKED`, before, limit)
if err != nil {
return nil, err
}
ids, err := pgx.CollectRows(rows, pgx.RowTo[string])
if err != nil {
return nil, err
}
out := make([]domain.Cart, 0, len(ids))
for _, id := range ids {
c, err := r.Get(ctx, id)
if err != nil {
return nil, err
}
out = append(out, c)
}
return out, nil
}
// ---- orders ----
type orders struct{ q querier }
const orderCols = `id, user_id, email, status, subtotal_minor, discount_minor, tax_minor, total_minor, currency,
version, created_at, updated_at, expires_at`
func scanOrder(r pgx.Row) (domain.Order, error) {
var o domain.Order
var cur string
err := r.Scan(&o.ID, &o.UserID, &o.Email, &o.Status, &o.Subtotal.Amount, &o.Discount.Amount, &o.Tax.Amount,
&o.Total.Amount, &cur, &o.Version, &o.CreatedAt, &o.UpdatedAt, &o.ExpiresAt)
c := money.Currency(cur)
o.Subtotal.Currency, o.Discount.Currency, o.Tax.Currency, o.Total.Currency = c, c, c, c
return o, notFound(err)
}
func (r orders) Create(ctx context.Context, o *domain.Order) error {
_, err := r.q.Exec(ctx, `INSERT INTO orders (`+orderCols+`) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)`,
o.ID, o.UserID, o.Email, string(o.Status), o.Subtotal.Amount, o.Discount.Amount, o.Tax.Amount, o.Total.Amount,
string(o.Total.Currency), o.Version, o.CreatedAt, o.UpdatedAt, o.ExpiresAt)
if err != nil {
return err
}
for i, it := range o.Items {
if _, err := r.q.Exec(ctx, `
INSERT INTO order_items (order_id, line, product_id, sku, name, unit_minor, qty, discount_minor, tax_minor, line_total_minor)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`,
o.ID, i+1, it.ProductID, it.SKU, it.Name, it.Unit.Amount, it.Qty, it.Discount.Amount, it.Tax.Amount, it.LineTotal.Amount); err != nil {
return err
}
}
return nil
}
func (r orders) Get(ctx context.Context, id string) (domain.Order, error) {
o, err := scanOrder(r.q.QueryRow(ctx, `SELECT `+orderCols+` FROM orders WHERE id = $1`, id))
if err != nil {
return o, err
}
rows, err := r.q.Query(ctx, `
SELECT product_id, sku, name, unit_minor, qty, discount_minor, tax_minor, line_total_minor
FROM order_items WHERE order_id = $1 ORDER BY line`, id)
if err != nil {
return o, err
}
cur := o.Total.Currency
o.Items, err = pgx.CollectRows(rows, func(row pgx.CollectableRow) (domain.OrderItem, error) {
var it domain.OrderItem
err := row.Scan(&it.ProductID, &it.SKU, &it.Name, &it.Unit.Amount, &it.Qty, &it.Discount.Amount, &it.Tax.Amount, &it.LineTotal.Amount)
it.Unit.Currency, it.Discount.Currency, it.Tax.Currency, it.LineTotal.Currency = cur, cur, cur, cur
return it, err
})
return o, err
}
// Update is a compare-and-set on version. Under READ COMMITTED a concurrent
// UPDATE of the same row waits, then re-checks the WHERE clause against the
// committed row: the loser matches 0 rows and gets ErrConflict.
func (r orders) Update(ctx context.Context, o *domain.Order) error {
tag, err := r.q.Exec(ctx, `UPDATE orders SET status = $2, version = $3, updated_at = $4 WHERE id = $1 AND version = $3 - 1`,
o.ID, string(o.Status), o.Version, o.UpdatedAt)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return domain.ErrConflict
}
return nil
}
func (r orders) ListForUser(ctx context.Context, userID int64, limit int) ([]domain.Order, error) {
rows, err := r.q.Query(ctx, `SELECT `+orderCols+` FROM orders WHERE user_id = $1 ORDER BY created_at DESC LIMIT $2`, userID, limit)
if err != nil {
return nil, err
}
return pgx.CollectRows(rows, func(row pgx.CollectableRow) (domain.Order, error) { return scanOrder(row) })
}
func (r orders) Expired(ctx context.Context, now time.Time, limit int) ([]domain.Order, error) {
rows, err := r.q.Query(ctx, `SELECT `+orderCols+` FROM orders WHERE status = 'created' AND expires_at < $1
ORDER BY expires_at LIMIT $2`, now, limit)
if err != nil {
return nil, err
}
return pgx.CollectRows(rows, func(row pgx.CollectableRow) (domain.Order, error) { return scanOrder(row) })
}
// ---- payments ----
type payments struct{ q querier }
func (r payments) Create(ctx context.Context, p domain.Payment) error {
_, err := r.q.Exec(ctx, `INSERT INTO payments (id, order_id, amount_minor, currency, status, provider_key, updated_at)
VALUES ($1,$2,$3,$4,$5,$6,$7)`, p.ID, p.OrderID, p.Amount.Amount, string(p.Amount.Currency), string(p.Status), p.ProviderKey, p.UpdatedAt)
return err
}
func (r payments) ForOrder(ctx context.Context, orderID string) (domain.Payment, error) {
var p domain.Payment
var cur string
var ref *string
err := r.q.QueryRow(ctx, `SELECT id, order_id, amount_minor, currency, status, provider_key, provider_ref, updated_at
FROM payments WHERE order_id = $1`, orderID).
Scan(&p.ID, &p.OrderID, &p.Amount.Amount, &cur, &p.Status, &p.ProviderKey, &ref, &p.UpdatedAt)
p.Amount.Currency = money.Currency(cur)
if ref != nil {
p.ProviderRef = *ref
}
return p, notFound(err)
}
func (r payments) Update(ctx context.Context, p domain.Payment) error {
_, err := r.q.Exec(ctx, `UPDATE payments SET status = $2, provider_ref = nullif($3, ''), updated_at = $4 WHERE id = $1`,
p.ID, string(p.Status), p.ProviderRef, p.UpdatedAt)
return err
}
// ---- outbox ----
type outbox struct{ q querier }
func (r outbox) Add(ctx context.Context, evs ...domain.Event) error {
for _, e := range evs {
if _, err := r.q.Exec(ctx, `INSERT INTO outbox (event_id, type, aggregate_id, payload, occurred_at)
VALUES ($1,$2,$3,$4,$5)`, e.ID, e.Type, e.AggregateID, []byte(e.Payload), e.OccurredAt); err != nil {
return err
}
}
return nil
}
func (r outbox) Claim(ctx context.Context, limit int) ([]domain.Event, error) {
rows, err := r.q.Query(ctx, `SELECT event_id, type, aggregate_id, payload, occurred_at, attempts, next_attempt_at
FROM outbox WHERE published_at IS NULL ORDER BY seq LIMIT $1`, limit)
if err != nil {
return nil, err
}
return pgx.CollectRows(rows, func(row pgx.CollectableRow) (domain.Event, error) {
var e domain.Event
err := row.Scan(&e.ID, &e.Type, &e.AggregateID, &e.Payload, &e.OccurredAt, &e.Attempts, &e.NextAttempt)
return e, err
})
}
func (r outbox) MarkPublished(ctx context.Context, ids []string, at time.Time) error {
_, err := r.q.Exec(ctx, `UPDATE outbox SET published_at = $2 WHERE event_id = ANY($1)`, ids, at)
return err
}
func (r outbox) MarkFailed(ctx context.Context, id string, next time.Time) error {
_, err := r.q.Exec(ctx, `UPDATE outbox SET attempts = attempts + 1, next_attempt_at = $2 WHERE event_id = $1`, id, next)
return err
}
// ---- idempotency ----
type idem struct{ q querier }
func (r idem) Get(ctx context.Context, scope, key string) (store.IdemRecord, error) {
rec := store.IdemRecord{Scope: scope, Key: key}
err := r.q.QueryRow(ctx, `SELECT fingerprint, status, body, created_at FROM idempotency_keys
WHERE scope = $1 AND key = $2 AND created_at > now() - interval '24 hours'`, scope, key).
Scan(&rec.Fingerprint, &rec.Status, &rec.Body, &rec.CreatedAt)
return rec, notFound(err)
}
// Put claims the key (first statement of the checkout after the lookup), or
// takes over a row older than the 24 h window. If a concurrent transaction
// claimed the same key and has not committed, this INSERT waits on the
// primary key; once the other commits, ON CONFLICT sees a fresh row, updates
// nothing, and we report ErrDuplicateKey: InTx re-runs the whole use case,
// whose Get now finds the winner's record. If the other rolled back, the
// INSERT proceeds and this request does the work itself.
func (r idem) Put(ctx context.Context, rec store.IdemRecord) error {
tag, err := r.q.Exec(ctx, `INSERT INTO idempotency_keys (scope, key, fingerprint, status, body, created_at)
VALUES ($1,$2,$3,$4,$5,$6)
ON CONFLICT (scope, key) DO UPDATE SET fingerprint = excluded.fingerprint, status = excluded.status,
body = excluded.body, created_at = excluded.created_at
WHERE idempotency_keys.created_at <= now() - interval '24 hours'`,
rec.Scope, rec.Key, rec.Fingerprint, rec.Status, rec.Body, rec.CreatedAt)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return fmt.Errorf("%w: idempotency key %q", store.ErrDuplicateKey, rec.Key)
}
return nil
}
// ---- inbox ----
// Inbox is store.Inbox on the processed_events table.
type Inbox struct{ DB querier }
func (i Inbox) Has(ctx context.Context, consumer, id string) (bool, error) {
var ok bool
err := i.DB.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM processed_events WHERE consumer = $1 AND event_id = $2)`,
consumer, id).Scan(&ok)
return ok, err
}
func (i Inbox) Mark(ctx context.Context, consumer, id string) error {
_, err := i.DB.Exec(ctx, `INSERT INTO processed_events (consumer, event_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`, consumer, id)
return err
}ثبت سفارش: رزرو موجودی، ساخت سفارش و ثبت اتمیک قصد پرداخت حیاتی
به زبان ساده: ثبت خرید (Checkout) یک تراکنش (Transaction) هفتمرحلهای است؛ یا همهٔ مراحل انجام میشوند یا هیچکدام. اگر شبکهٔ مشتری قطع شود، موجودی یا برای سفارش موجود رزرو شده است یا اصلاً رزرو نشده است.
بدفهمی رایج: «داخل Transaction خرید از کارت پول بگیر.» فراخوانی ارائهدهندهٔ پرداخت (PSP) از صدها میلیثانیه تا چند ثانیه طول میکشد، با نتیجهٔ نامعلوم Timeout میخورد و Rollbackشدنی نیست. نگه داشتن قفل موجودی طی آن، کل فروشگاه را پشت کندترین پرداخت صف میکند. سفارش فقط قصد پرداخت (Payment intent) را با مبلغ و کلید مشتقشدهٔ ord_...:attempt:1 ثبت میکند. خود پرداخت در جریان پرداخت انجام میشود و نتیجه به شکل رویداد تأییدشده میرسد. اشتباه دیگر: «سبد را پیش از Transaction بخوان تا کوتاه بماند.» در آن فاصله سبد تغییر میکند؛ خواندن باید داخل Transaction باشد.
تعریف: Checkout.PlaceOrder داخل InTx چنین عمل میکند: (1) جستوجوی (scope, key) در idempotency_keys؛ بازپخش یا 422، و اگر کلید تازه است فوراً آن را با شناسهٔ ازپیشساختهٔ سفارش تصاحب میکند تا تکرار همزمان همینجا منتظر بماند و کار را شروع نکند؛ (2) خواندن سبد مشتری و قیمت جاری هر محصول و رد محصول غیرفعال؛ (3) اجرای pricing.Quote؛ (4) رزرو همهٔ ردیفها با Inventory().Reserve به ترتیب؛ (5) درج سفارش با created، Version برابر 1 و expires_at = now + StockHold و ردیفهایش؛ (6) درج Payment intent با requires_payment_method، مبلغ برابر کل و Provider key؛ (7) درج order.placed:<order>:v1 در Outbox و حذف سبد. سپس Commit. هر شکست همهچیز، از جمله تصاحب کلید، را Rollback میکند؛ بنابراین Retry پس از 409 دوباره اجرا میشود. اصل کار همین است: رزرو، سفارش و Intent اتمیکاند؛ انتخاب SELECT FOR UPDATE یا Version خوشبینانه، درستی مرحلهٔ موجودی و تغییر وضعیتهای بعدی را زیر همزمانی تعیین میکند.
Step Statement (pgstore) Fails with Effect of failure
1 1 SELECT ... FROM idempotency_keys WHERE scope=$1 AND key=$2 (row found) replay, nothing else runs
2 1 INSERT INTO idempotency_keys ... ON CONFLICT ... 0 rows: lost race re-run -> replay
3 2 SELECT ... FROM carts / cart_items / products ErrEmptyCart 422, nothing written
4 4 SELECT ... FROM inventory ... ORDER BY product_id FOR UPDATE OutOfStockError 409, key claim rolled back
5 5 INSERT INTO orders ...; INSERT INTO order_items ... 23505 (id clash) rollback
6 6 INSERT INTO payments ... provider_key 'ord_x:attempt:1' 23505 order_id rollback
7 7 INSERT INTO outbox ...; DELETE FROM carts ... 23505 event_id rollback
8 COMMIT 40001 / 40P01 re-run allسناریوی واقعی: 50 مشتری برای 10 واحد آخر دکمهٔ خرید میزنند؛ TestNoOversellUnderConcurrency دقیقاً 10 سفارش و 40 پاسخ 409 میبیند. در خرید دوردیفی، اگر ردیف اول رزرو و ردیف دوم تمام شود، هیچ موجودی، سفارش، رویداد یا تصاحب کلیدی نباید بماند؛ TestMultiLineCheckoutRollsBackEarlierReservations آن را بررسی میکند. شکست انتهای Transaction هم باید رزرو چند دستور قبل را آزاد کند؛ TestLateFailureRollsBackReservation. Timeout مشتری پس از Commit با Retry به Replay میرسد؛ کشته شدن فرایند میان مرحلهٔ 6 و Commit یعنی هیچ کاری رخ نداده و Retry مشتری سفارش را میسازد.
| روش | اتمیک؟ | مدت قفل | خطر پرداخت |
|---|---|---|---|
| یک Transaction، فقط Intent؛ این پروژه | بله | میلیثانیه | ندارد؛ PSP بیرون و با کلید مشتقشده فراخوانی میشود |
| Transaction با فراخوانی PSP داخل آن | بله، تا Timeout در PSP | ثانیه | نتیجهٔ نامعلوم در حالی که قفل نگه داشته شده |
| رزرو در یک Transaction و سفارش در دیگری | نه | میلیثانیه | نشت موجودی با Crash |
| Saga بین سرویس موجودی، سفارش و پرداخت | در نهایت با جبران | میلیثانیه در هر مرحله | جبران و مراحل Idempotent میخواهد؛ Payment Processing Architecture |
راهحل / نحوهٔ استفاده: Service همان Snippet بعد است؛ تستهای Table-driven زیر اتمیک بودن، Replay و ادعای همزمانی را اثبات میکنند.
package service
import (
"context"
"errors"
"strconv"
"sync"
"testing"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/store"
)
func TestPlaceOrder(t *testing.T) {
tests := []struct {
name string
stock int64
qty int64
discount string
wantErr error
total int64
}{
{"happy path", 5, 2, "", nil, 2 * 1000 * 12 / 10},
{"discount code", 5, 2, "TEN", nil, 1800 * 12 / 10},
{"unknown discount is ignored", 5, 1, "NOPE", nil, 1200},
{"out of stock", 1, 2, "", &domain.OutOfStockError{}, 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f := newFixture(t)
id := f.product(t, "MUG", 1000, tt.stock)
if _, err := f.carts.SetItem(t.Context(), Owner{Principal: alice}, id, tt.qty); err != nil {
t.Fatal(err)
}
res, err := f.checkout.PlaceOrder(t.Context(), PlaceOrderInput{Who: alice,
IdempotencyKey: "key-" + tt.name, Fingerprint: "fp", DiscountCode: tt.discount})
if tt.wantErr != nil {
var oos *domain.OutOfStockError
if !errors.As(err, &oos) {
t.Fatalf("want out of stock, got %v", err)
}
if s := f.stock(t, id); s.Reserved != 0 {
t.Fatalf("failed checkout left %d reserved", s.Reserved)
}
if len(f.store.Unpublished()) != 0 {
t.Fatal("failed checkout wrote an event")
}
return
}
if err != nil {
t.Fatal(err)
}
o := res.Order
if o.Status != domain.OrderCreated || o.Total.Amount != tt.total {
t.Fatalf("status %s total %d, want created %d", o.Status, o.Total.Amount, tt.total)
}
if res.Payment.ProviderKey != o.ID+":attempt:1" || res.Payment.Amount != o.Total {
t.Fatalf("payment %+v", res.Payment)
}
if s := f.stock(t, id); s.Reserved != tt.qty {
t.Fatalf("reserved %d", s.Reserved)
}
evs := f.store.Unpublished()
if len(evs) != 1 || evs[0].Type != domain.EvOrderPlaced || evs[0].ID != "order.placed:"+o.ID+":v1" {
t.Fatalf("outbox %v", evs)
}
if _, err := f.checkout.PlaceOrder(t.Context(), PlaceOrderInput{Who: alice, IdempotencyKey: "another-key"}); !errors.Is(err, domain.ErrEmptyCart) {
t.Fatalf("cart must be empty after checkout, got %v", err)
}
})
}
}
func TestPlaceOrderIsIdempotent(t *testing.T) {
f := newFixture(t)
id := f.product(t, "MUG", 1000, 5)
_, _ = f.carts.SetItem(t.Context(), Owner{Principal: alice}, id, 1)
in := PlaceOrderInput{Who: alice, IdempotencyKey: "8e03c2d1-retry", Fingerprint: "sha256:aaa"}
first, err := f.checkout.PlaceOrder(t.Context(), in)
if err != nil {
t.Fatal(err)
}
again, err := f.checkout.PlaceOrder(t.Context(), in)
if err != nil || !again.Replayed || again.Order.ID != first.Order.ID {
t.Fatalf("retry: %+v %v", again, err)
}
if s := f.stock(t, id); s.Reserved != 1 {
t.Fatalf("retry reserved again: %d", s.Reserved)
}
in.Fingerprint = "sha256:bbb"
if _, err := f.checkout.PlaceOrder(t.Context(), in); !errors.Is(err, ErrIdempotencyMismatch) {
t.Fatalf("other body, same key: %v", err)
}
// The key is scoped per user: Bob may use the same string.
_, _ = f.carts.SetItem(t.Context(), Owner{Principal: bob}, id, 1)
if r, err := f.checkout.PlaceOrder(t.Context(), PlaceOrderInput{Who: bob, IdempotencyKey: in.IdempotencyKey}); err != nil || r.Replayed {
t.Fatalf("bob: %+v %v", r, err)
}
}
// 50 customers race for the last 10 units: exactly 10 orders, never 11.
func TestNoOversellUnderConcurrency(t *testing.T) {
f := newFixture(t)
id := f.product(t, "LAST", 500, 10)
var wg sync.WaitGroup
var mu sync.Mutex
ok, oos := 0, 0
for i := range 50 {
u := domain.Principal{UserID: int64(100 + i), Role: domain.RoleCustomer}
if _, err := f.carts.SetItem(t.Context(), Owner{Principal: u}, id, 1); err != nil {
t.Fatal(err)
}
wg.Add(1)
go func() {
defer wg.Done()
_, err := f.checkout.PlaceOrder(t.Context(), PlaceOrderInput{Who: u, IdempotencyKey: "checkout-" + strconv.Itoa(i)})
mu.Lock()
defer mu.Unlock()
var e *domain.OutOfStockError
switch {
case err == nil:
ok++
case errors.As(err, &e):
oos++
default:
t.Error(err)
}
}()
}
wg.Wait()
if ok != 10 || oos != 40 {
t.Fatalf("ok %d out-of-stock %d", ok, oos)
}
if s := f.stock(t, id); s.Reserved != 10 || s.Available() != 0 {
t.Fatalf("stock %+v", s)
}
}
func TestOnlyCustomersPlaceOrders(t *testing.T) {
f := newFixture(t)
_, err := f.checkout.PlaceOrder(t.Context(), PlaceOrderInput{IdempotencyKey: "anonymous-key"})
if !errors.Is(err, domain.ErrForbidden) {
t.Fatalf("got %v", err)
}
var v *ValidationError
if _, err := f.checkout.PlaceOrder(t.Context(), PlaceOrderInput{Who: alice, IdempotencyKey: "short"}); !errors.As(err, &v) {
t.Fatalf("short key: %v", err)
}
}
// The first line reserves successfully, the second runs out: nothing of the
// checkout may survive (reservation, order, payment, outbox, key claim).
func TestMultiLineCheckoutRollsBackEarlierReservations(t *testing.T) {
f := newFixture(t)
a := f.product(t, "A", 1000, 5)
b := f.product(t, "B", 1000, 1)
_, _ = f.carts.SetItem(t.Context(), Owner{Principal: alice}, a, 2)
_, _ = f.carts.SetItem(t.Context(), Owner{Principal: alice}, b, 2)
in := PlaceOrderInput{Who: alice, IdempotencyKey: "multi-line-1", Fingerprint: "fp"}
var oos *domain.OutOfStockError
if _, err := f.checkout.PlaceOrder(t.Context(), in); !errors.As(err, &oos) || oos.ProductID != b {
t.Fatalf("got %v", err)
}
if s := f.stock(t, a); s.Reserved != 0 {
t.Fatalf("line A still reserved: %+v", s)
}
if len(f.store.Unpublished()) != 0 {
t.Fatal("event written by a failed checkout")
}
if c, _ := f.carts.Get(t.Context(), Owner{Principal: alice}); len(c.Items) != 2 {
t.Fatalf("cart lost: %v", c.Items)
}
// The key claim rolled back too: after a restock the same key places the order.
if err := f.store.InTx(t.Context(), func(ctx context.Context, tx store.Tx) error {
return tx.Inventory().SetOnHand(ctx, b, 5)
}); err != nil {
t.Fatal(err)
}
if r, err := f.checkout.PlaceOrder(t.Context(), in); err != nil || r.Replayed {
t.Fatalf("after restock: %+v %v", r, err)
}
}
// A write late in the transaction fails (order id clash): the stock reserved
// a few statements earlier must be released by the rollback.
func TestLateFailureRollsBackReservation(t *testing.T) {
f := newFixture(t)
a := f.product(t, "A", 1000, 5)
_, _ = f.carts.SetItem(t.Context(), Owner{Principal: alice}, a, 1)
first, err := f.checkout.PlaceOrder(t.Context(), PlaceOrderInput{Who: alice, IdempotencyKey: "late-fail-1"})
if err != nil {
t.Fatal(err)
}
_, _ = f.carts.SetItem(t.Context(), Owner{Principal: alice}, a, 2)
c := f.checkout
c.NewID = func(string) string { return first.Order.ID } // forces 23505-like duplicate on orders
if _, err := c.PlaceOrder(t.Context(), PlaceOrderInput{Who: alice, IdempotencyKey: "late-fail-2"}); !errors.Is(err, store.ErrDuplicateKey) {
t.Fatalf("got %v", err)
}
if s := f.stock(t, a); s.Reserved != 1 {
t.Fatalf("reserved %d, want only the first order's 1", s.Reserved)
}
}ثبت سفارش تکرارپذیر: Idempotency-Key حیاتی
به زبان ساده: برنامه برای هر تلاش خرید یک کلید تصادفی تازه میفرستد و برای همهٔ Retryهای همان تلاش، همان کلید را نگه میدارد. سرور «این کلید سفارش X را ساخت» را در همان تراکنش (Transaction) سفارش ثبت میکند. در نتیجه Retry همان X را میگیرد، نه سفارش دوم.
بدفهمی رایج: «اول کلید را در Redis ذخیره کن، بعد کار را انجام بده.» اگر کار شکست بخورد یا فرایند بمیرد، کلید برای سفارشی که وجود ندارد میگوید «در حال اجرا» یا «انجام شد». ثبت رکورد در Transaction خرید، ذخیرهٔ کلید و وجود سفارش را یک واقعیت میکند. دوم: «کلید یکسان از کاربر دیگر هم Replay است.» کلید دامنه دارد، مثل POST /v1/orders user:7؛ کلید Bob که تصادفاً برابر کلید Alice شده درخواست تازه است. سوم: «همان کلید کلاینت را به PSP بده.» کلید PSP از سفارش مشتق میشود، مثل ord_x:attempt:1؛ Worker پرداخت پس از Restart هم همان را میفرستد. قاعدهٔ دو کلید در Payment Processing Architecture است.
تعریف: پیشنویس IETF میگوید: "The idempotency key MUST be unique and MUST NOT be reused with another request with a different request payload" و "If the request is retried, while the original request is still being processed, the resource SHOULD reply with an HTTP 409". در Stripe API v1 پاسخ اول ذخیره میشود و "Retries with the same key return the saved response"؛ کلیدها "are up to 255 characters long" و "you can remove keys from the system automatically after they’re at least 24 hours old". اینجا Header اجباری است و نبودنش 400 میدهد؛ طول آن 8 تا 255 کاراکتر است. اثر انگشت (Fingerprint)، SHA-256 بایتهای خام Body است؛ Fingerprint متفاوت پاسخ 422 با idempotency-key-reused دارد. رکورد 24 ساعت اعتبار دارد: created_at > now() - interval '24 hours'؛ سطر منقضی با ON CONFLICT ... DO UPDATE ... WHERE created_at <= now() - interval '24 hours' واگذار میشود. کلید بلافاصله پس از Lookup و پیش از هر کار دیگری تصاحب میشود؛ این تصاحب در همان Transaction خرید است. INSERT درخواست تکراری روی Primary key منتظر میماند؛ با Commit اولی، اجرای مجدد Replay میکند و اگر اولی Rollback کند، دومی خودش کار را انجام میدهد. تصاحب دیرهنگام پس از موجودی باگ است: تکرار روی سطر موجودی منتظر میماند و برای سفارش موجود خودش 409 کمبود موجودی یا 422 سبد خالی میگیرد. فقط انتظار بیش از lock_timeout پاسخ 409 با busy و Retry-After: 1 میدهد. Replay وضعیت فعلی سفارش را با Idempotent-Replayed: true برمیگرداند؛ شاید سفارش حالا paid باشد. این سادهسازی آگاهانه نسبت به Replay بایتبهبایت Stripe است؛ Middleware عمومی ذخیرهٔ بایتهای پاسخ در A REST API in Go آمده است.
Client Tx 1 (first attempt) Tx 2 (retry, same key)
1 POST key=K body=B
2 BEGIN; idem K? no; INSERT idem K (claim)
3 reserve last unit; insert order ...
4 (timeout, retries) BEGIN; idem K? no (Tx 1 not committed)
5 INSERT idem K: waits on Tx 1's key
6 COMMIT -> 201 (response lost)
7 ON CONFLICT: fresh row, 0 rows -> ErrDuplicateKey
8 InTx re-runs: idem K? yes -> replay order
9 <- 201 same order, Idempotent-Replayed: true (never "out of stock" for its own unit)سناریوی واقعی: دوبار لمس «ثبت سفارش»؛ Retry برنامهٔ موبایل پس از جابهجایی Wi-Fi به 4G؛ پاسخ 504 از Load balancer در حالی که بکاند Commit میکند؛ ارسال دوبارهٔ Batch توسط اسکریپت پس از Crash؛ و باگ کلاینت که یک کلید را برای دو سبد متفاوت مصرف میکند و 422 میگیرد.
| حالت | Status | Body | ذخیره میشود؟ |
|---|---|---|---|
| بدون Header | 400 | idempotency-key-missing | نه |
| کلید کوتاهتر از 8 یا بلندتر از 255 | 422 | validation | نه |
| موفقیت درخواست اول | 201 | سفارش | بله، همراه سفارش |
| کلید یکسان و Body یکسان | 201 + Idempotent-Replayed: true | همان سفارش با وضعیت فعلی | بدون تغییر |
| کلید یکسان و Body متفاوت | 422 | idempotency-key-reused | بدون تغییر |
کلید یکسان وقتی اجرای اول از lock_timeout بیشتر طول میکشد | 409 + Retry-After: 1 | busy | نه |
| شکست درخواست اول بهعلت کمبود موجودی | 409 | out-of-stock | نه؛ Transaction برگشته و Retry دوباره اجرا میشود |
| پس از 24 ساعت | درخواست تازه محسوب میشود | سطر جایگزین میشود |
راهحل / نحوهٔ استفاده: مدیریت کلید مرحلهٔ 1 در PlaceOrder است؛ سمت Adapter، idem.Get/idem.Put در repos.go قرار دارند. TestPlaceOrderIsIdempotent و تست یکپارچهٔ TestSameIdempotencyKeyConcurrentlyCreatesOneOrder آن را اثبات میکنند.
ماشین حالت سفارش حیاتی
به زبان ساده: وضعیت سفارش فقط روی چند پیکان حرکت میکند. هر حرکت دیگر، از Webhook دیررس تا دوبار کلیک «ارسال» یا لغو پس از پرداخت، به «در وضعیت فعلی مجاز نیست» میرسد؛ رویداد قبلی بیصدا بازنویسی نمیشود.
بدفهمی رایج: «وضعیت یک ستون است، مقدار رویداد را در آن بنویس.» Stripe "doesn’t guarantee the delivery of events in the order that they’re generated"؛ اعمال کورکورانهٔ آخرین رویداد، سفارش پرداختشده را دوباره Pending میکند. دوم: «لغو و بازپرداخت یکیاند.» پیش از پرداخت، Cancel فقط موجودی را آزاد میکند؛ پس از پرداخت پول جابهجا شده و باید Refund شود، نه Cancel. سوم: «سفارش و پرداخت یک ستون وضعیت داشته باشند.» دو ماشین جدا هستند؛ پرداخت، PaymentIntent در PSP را بازتاب میدهد که تلاش ناموفق آن "returns to requires_payment_method so that the payment can be retried"، ولی سفارش وضعیت کسبوکار را بازتاب میدهد.
تعریف: ماشین حالت (State machine) با domain.OrderStatus یالهای created → paid | cancelled، paid → fulfilled | refunded و fulfilled → refunded را دارد. cancelled و refunded پایانیاند. Order.Transition(to, now) هر حرکت دیگر را با ErrInvalidTransition رد میکند و در حرکت مجاز Version را افزایش میدهد. Repository با WHERE version = $new - 1 مینویسد. هر Transition در همان Transaction رویدادی با شناسهٔ <type>:<order>:v<version> ثبت میکند؛ اجرای مجدد همان Transition همان Event id را میسازد. PaymentStatus یکی از requires_payment_method، succeeded، canceled، refund_pending و refunded است.
Event (arrival order) Order before Payment before Result
1 order placed - - created v1, requires_payment_method
2 payment_intent.succeeded (evt_1) created v1 requires_payment_method paid v2, succeeded, payment.captured:ord:v2
3 payment_intent.succeeded (evt_1 again) paid v2 succeeded no-op, 204 to the PSP
4 customer cancel paid v2 succeeded 409 invalid transition
5 admin fulfil paid v2 succeeded fulfilled v3, stock shippedسناریوی واقعی: Webhook سه بار تحویل میشود؛ مشتری همزمان با Capture لغو میکند و یکی با Version برنده میشود و دیگری دوباره میخواند؛ Job مهلت سفارش را لغو میکند و پرداخت یک ثانیه بعد میرسد، پس پرداخت refund_pending میشود، مطابق Workerها؛ یا Admin اشتباهاً سفارش پرداختنشده را ارسال میکند و 409 میگیرد.
| فعلی | paid | fulfilled | cancelled | refunded |
|---|---|---|---|---|
created | بله؛ Capture | نه | بله؛ مشتری یا مهلت | نه |
paid | تکراری؛ بدون اثر | بله؛ Admin | نه؛ باید Refund شود | بله |
fulfilled | نه | تکراری | نه | بله؛ مرجوعی |
cancelled | نه؛ Capture دیررس به Refund میرود | نه | تکراری | نه |
refunded | نه | نه | نه | تکراری |
راهحل / نحوهٔ استفاده: جدول Transition در domain/order.go بالاست؛ Serviceها آن را اعمال میکنند.
package service
import (
"context"
"errors"
"strconv"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/money"
)
// Orders reads and moves orders after checkout.
type Orders struct{ Deps }
func itoa(n int64) string { return strconv.FormatInt(n, 10) }
// Get returns the order if who may see it. A customer asking for someone
// else's order gets ErrNotFound, not ErrForbidden: do not confirm it exists.
func (s Orders) Get(ctx context.Context, who domain.Principal, id string) (domain.Order, error) {
var o domain.Order
err := s.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
var err error
o, err = tx.Orders().Get(ctx, id)
return err
})
if err == nil && !who.CanSee(o.UserID) {
return domain.Order{}, domain.ErrNotFound
}
return o, err
}
// List returns the caller's latest orders.
func (s Orders) List(ctx context.Context, who domain.Principal) ([]domain.Order, error) {
var out []domain.Order
err := s.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
var err error
out, err = tx.Orders().ListForUser(ctx, who.UserID, 50)
return err
})
return out, err
}
// Cancel cancels an unpaid order and releases its stock exactly once (the
// version check makes a concurrent cancel or payment lose and retry).
func (s Orders) Cancel(ctx context.Context, who domain.Principal, id string) (domain.Order, error) {
var o domain.Order
err := retryConflict(func() error {
return s.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
var err error
if o, err = tx.Orders().Get(ctx, id); err != nil {
return err
}
if !who.CanSee(o.UserID) {
return domain.ErrNotFound
}
return cancelInTx(ctx, tx, &o, s.Now(), "customer")
})
})
return o, err
}
func cancelInTx(ctx context.Context, tx Tx, o *domain.Order, now timeT, reason string) error {
if err := o.Transition(domain.OrderCancelled, now); err != nil {
return err
}
if err := tx.Orders().Update(ctx, o); err != nil {
return err
}
if err := tx.Inventory().Release(ctx, o.Reservations()); err != nil {
return err
}
if p, err := tx.Payments().ForOrder(ctx, o.ID); err == nil && p.Status == domain.PaymentRequiresMethod {
p.Status, p.UpdatedAt = domain.PaymentCanceled, now
if err := tx.Payments().Update(ctx, p); err != nil {
return err
}
}
return tx.Outbox().Add(ctx, domain.NewEvent(domain.EvOrderCancelled, o.ID, o.Version, now,
map[string]string{"order_id": o.ID, "reason": reason}))
}
// Fulfil marks a paid order shipped (admin) and turns reservations into shipments.
func (s Orders) Fulfil(ctx context.Context, who domain.Principal, id string) (domain.Order, error) {
if err := requireAdmin(who); err != nil {
return domain.Order{}, err
}
var o domain.Order
err := retryConflict(func() error {
return s.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
var err error
if o, err = tx.Orders().Get(ctx, id); err != nil {
return err
}
now := s.Now()
if err := o.Transition(domain.OrderFulfilled, now); err != nil {
return err
}
if err := tx.Orders().Update(ctx, &o); err != nil {
return err
}
if err := tx.Inventory().Ship(ctx, o.Reservations()); err != nil {
return err
}
return tx.Outbox().Add(ctx, domain.NewEvent(domain.EvOrderFulfilled, o.ID, o.Version, now,
map[string]string{"order_id": o.ID}))
})
})
return o, err
}
// PSPEvent is a verified payment event (signature already checked by the
// webhook handler; see the payment-processing chapter for that part).
type PSPEvent struct {
EventID string
Type string // "payment_intent.succeeded" | "payment_intent.payment_failed"
OrderID string
ProviderRef string
Amount money.Money
}
// ApplyPayment records a PSP event. Duplicates and late events are no-ops;
// a capture that arrives after the order was cancelled (the stock-release
// timeout won) does not resurrect the order: it asks for a refund instead.
func (s Orders) ApplyPayment(ctx context.Context, ev PSPEvent) (domain.Order, error) {
var o domain.Order
err := retryConflict(func() error {
return s.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
var err error
if o, err = tx.Orders().Get(ctx, ev.OrderID); err != nil {
return err
}
p, err := tx.Payments().ForOrder(ctx, o.ID)
if err != nil {
return err
}
if ev.Type != "payment_intent.succeeded" || (p.Status != domain.PaymentRequiresMethod && p.Status != domain.PaymentCanceled) {
return nil // failure (stays retryable at the PSP), duplicate or late: ack and ignore
}
if ev.Amount != p.Amount {
return ErrAmountMismatch
}
now := s.Now()
p.ProviderRef, p.UpdatedAt = ev.ProviderRef, now
if o.Status == domain.OrderCancelled {
p.Status = domain.PaymentRefundPending
if err := tx.Payments().Update(ctx, p); err != nil {
return err
}
return tx.Outbox().Add(ctx, domain.NewEvent(domain.EvRefundRequested, p.ID, 1, now,
domain.PaymentCaptured{OrderID: o.ID, PaymentID: p.ID, Amount: p.Amount.Amount}))
}
if err := o.Transition(domain.OrderPaid, now); err != nil {
return err
}
p.Status = domain.PaymentSucceeded
if err := tx.Orders().Update(ctx, &o); err != nil {
return err
}
if err := tx.Payments().Update(ctx, p); err != nil {
return err
}
return tx.Outbox().Add(ctx, domain.NewEvent(domain.EvPaymentCaptured, o.ID, o.Version, now,
domain.PaymentCaptured{OrderID: o.ID, PaymentID: p.ID, Amount: p.Amount.Amount}))
})
})
return o, err
}
// retryConflict re-runs fn when an optimistic version check lost.
func retryConflict(fn func() error) error {
var err error
for range 3 {
if err = fn(); !errors.Is(err, domain.ErrConflict) {
return err
}
}
return err
}سبد خرید: جدول سمت سرور یا Session و ادغام سبد مهمان هنگام ورود حیاتی
به زبان ساده: سبد خرید (Cart) در پایگاه داده است؛ برای مهمان با Token تصادفی در Cookie و برای مشتری با شناسهٔ کاربر پیدا میشود. فقط محصول و تعداد دارد، هرگز قیمت ندارد. با ورود مهمان، سبدش در سبد مشتری ادغام و سپس حذف میشود.
بدفهمی رایج: «سبد را در Session، JWT یا localStorage نگه داریم.» سبد Session با پاک شدن Session store یا عوض کردن دستگاه ناپدید میشود و Job سبد رهاشده آن را نمیبیند. اگر داخل Token سمت کلاینت باشد، کاربر میتواند داده را دستکاری کند؛ از جمله قیمت، اگر وسوسه شده باشید آن را آنجا ذخیره کنید. اشتباه دوم: «برای سریعتر شدن Checkout، قیمت را در ردیف سبد ذخیره کنیم.» سبد آنوقت قیمت منقضی نشان میدهد و Checkout در هر صورت باید قیمت جاری را داخل Transaction بخواند.
تعریف: جدول carts (id TEXT PRIMARY KEY, user_id BIGINT NULL, email, updated_at, reminded_at)، یک Partial unique index برای حداکثر یک سبد هر مشتری، ستون version و جدول cart_items (cart_id, product_id, qty 1..10) داریم. هر Save یک مقایسه و جایگذاری (Compare-and-set) است: UPDATE carts SET ..., version = version + 1 WHERE id = $1 AND version = $2؛ سپس ردیفها جایگزین میشوند. بدون آن، دو تب افزودن همزمان یکی را گم میکنند: هر دو [A] میخوانند، یکی [A, B] مینویسد و دیگری Snapshot کهنهٔ [A, C] را ذخیره میکند؛ B میرود. با Version، نویسندهٔ کهنه صفر سطر را Match میکند؛ در READ COMMITTED منتظر اولی میماند و بعد WHERE دوباره بررسی میشود. ErrConflict میگیرد و SetItem دوباره میخواند و تغییر را اعمال میکند؛ memstore همین رقابت را در TestCartSaveRejectsStaleSnapshot مدل میکند. Checkout سبد را با همان بررسی Version حذف میکند؛ اضافه شدن کالا همزمان با ثبت سفارش باعث اجرای مجدد Checkout میشود، نه ناپدید شدن کالا. Token مهمان 128 بیت تصادفی از service.RandomID است؛ Cookie به نام cart_id با HttpOnly، Secure، SameSite=Lax، Path=/ و عمر 30 روز تنظیم میشود. Carts.MergeOnLogin(guestID, principal) تعداد هر محصول را جمع و در MaxQtyPerLine برابر 10 محدود میکند، سبد مشتری را ذخیره و سبد مهمان را حذف میکند. سبدی را که قبلاً متعلق به کاربر است ادغام نمیکند تا حدس زدن شناسهٔ سبد مشتری به سرقت آن نرسد. Handler ورود بلافاصله پس از صدور Session یا Token آن را صدا میزند؛ در این پروژه کلاینت POST /v1/cart/merge را فراخوانی میکند.
Browser Server
1 PUT /v1/cart/items/1 {"qty":3} (no auth) new cart_9f.. saved, Set-Cookie: cart_id=cart_9f..; HttpOnly; Secure
2 GET /v1/cart (cookie) cart_9f..: [1 x 3]
3 POST /login session / JWT issued (authentication chapter)
4 POST /v1/cart/merge (cookie + bearer) customer cart: [1 x 9] + [1 x 3] -> [1 x 10] (cap), guest cart deleted
5 Set-Cookie: cart_id=; Max-Age=0سناریوی واقعی: مهمان روی گوشی سبد را پر میکند و پس از ورود روی همان گوشی انتظار دارد کالاها بمانند؛ مشتری از هفتهٔ قبل هم کالا دارد؛ روی رایانهٔ مشترک مهمان بعدی نباید سبد مشتری قبلی را ببیند؛ و باید به مشتریای که 24 ساعت کالاها را رها کرده ایمیل یادآوری برسد.
| محل نگهداری | پس از ورود میماند | با تعویض دستگاه میماند | Job میبیند | مقاوم به دستکاری | هزینه |
|---|---|---|---|---|---|
| جدول سمت سرور؛ این پروژه | بله، با Merge | بله، برای مشتری | بله | بله | یک جدول و Cookie |
Session سرور؛ Redis، scs | فقط اگر Session حفظ شود | نه | دشوار | بله | Session store |
| Cookie امضاشده یا JWT | منطق Merge میخواهد | نه | نه | امضاشده ولی محدود به اندازه | ندارد |
localStorage و API فقط در Checkout | Merge میخواهد | نه | نه | نه؛ کلاینت ویرایش میکند | ندارد |
| Redis hash برای هر سبد | بله، با Merge | بله | بله؛ با Scan | بله | تنظیم TTL و Store دوم |
راهحل / نحوهٔ استفاده:
package service
import (
"context"
"errors"
"academy/ecommerce-api-project/domain"
)
// Carts manages server-side carts. A guest is identified by an opaque cart
// id (cookie); a signed-in customer by user id.
type Carts struct{ Deps }
// Owner is whoever the cart belongs to: a principal, a guest cart id, or both
// (during login, when the guest cart is merged).
type Owner struct {
Principal domain.Principal
GuestID string
}
func (c Carts) load(ctx context.Context, tx Tx, o Owner) (domain.Cart, error) {
if o.Principal.UserID != 0 {
cart, err := tx.Carts().ForUser(ctx, o.Principal.UserID)
if errors.Is(err, domain.ErrNotFound) {
return domain.Cart{ID: c.NewID("cart"), UserID: o.Principal.UserID, Email: o.Principal.Email}, nil
}
return cart, err
}
if o.GuestID != "" {
cart, err := tx.Carts().Get(ctx, o.GuestID)
if err == nil && cart.UserID == 0 {
return cart, nil
}
if err != nil && !errors.Is(err, domain.ErrNotFound) {
return domain.Cart{}, err
}
}
return domain.Cart{ID: c.NewID("cart")}, nil // new guest cart; the handler sets the cookie
}
// Get returns the cart (possibly new and empty, not yet saved).
func (c Carts) Get(ctx context.Context, o Owner) (domain.Cart, error) {
var cart domain.Cart
err := c.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
var err error
cart, err = c.load(ctx, tx, o)
return err
})
return cart, err
}
// SetItem sets the quantity of one product (0 removes it).
func (c Carts) SetItem(ctx context.Context, o Owner, productID, qty int64) (domain.Cart, error) {
if qty < 0 || qty > domain.MaxQtyPerLine {
return domain.Cart{}, &ValidationError{Fields: []FieldError{{"qty", "between 0 and 10"}}}
}
var cart domain.Cart
// The cart is read and saved with a version check, so two tabs adding
// items at once cannot lose one; the loser re-reads and applies again.
err := retryConflict(func() error {
return c.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
p, err := tx.Products().Get(ctx, productID)
if err != nil {
return err
}
if !p.Active {
return domain.ErrInactiveProduct
}
if cart, err = c.load(ctx, tx, o); err != nil {
return err
}
cart.Set(productID, qty, c.Now())
return tx.Carts().Save(ctx, &cart)
})
})
return cart, err
}
// MergeOnLogin moves the guest cart into the customer's cart and deletes it.
// Called by the login handler right after the session or token is issued.
func (c Carts) MergeOnLogin(ctx context.Context, guestID string, who domain.Principal) (domain.Cart, error) {
var cart domain.Cart
err := retryConflict(func() error {
return c.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
var err error
if cart, err = c.load(ctx, tx, Owner{Principal: who}); err != nil {
return err
}
guest, err := tx.Carts().Get(ctx, guestID)
if errors.Is(err, domain.ErrNotFound) || (err == nil && guest.UserID != 0) {
return nil // nothing to merge, or not a guest cart: never steal a customer's cart
}
if err != nil {
return err
}
cart.Merge(guest, c.Now())
if err := tx.Carts().Save(ctx, &cart); err != nil {
return err
}
return tx.Carts().Delete(ctx, guest.ID, guest.Version)
})
})
return cart, err
}فهرست کاتالوگ: صفحهبندی، فیلتر، مرتبسازی، Keyset و جستوجو حیاتی
به زبان ساده: کاتالوگ (Catalogue) هزاران برابر بیشتر خوانده میشود تا نوشته. با مکاننما (Cursor) که میگوید «بعد از این سطر» صفحهبندی کنید. فیلتر و Sort فقط روی فیلدهای مجاز و دارای Index باشند. جستوجو را با ILIKE شروع کنید و وقتی جدی شد به Full-text search بروید.
بدفهمی رایج: «LIMIT 20 OFFSET 2000 کافی است.» پایگاه داده همچنان 2,000 سطر را میخواند و دور میریزد؛ محصولی که حین ورق زدن اضافه شود ممکن است دوبار دیده شود یا اصلاً دیده نشود. صفحهٔ «no offset» از Use The Index, Luke و Pagination دلیلش را توضیح میدهند. دوم: «ستون Sort را کلاینت بفرستد.» ORDER BY Bind parameter نمیشود و نام ستون به SQL چسبانده میشود؛ بهجایش چند نام محدود را به رشتههای ثابت نگاشت کنید. سوم: «ILIKE '%term%' از B-tree استفاده میکند.» Wildcard ابتدای عبارت به B-tree معمولی اجازهٔ کمک نمیدهد؛ Indexهای Trigram از نوع GIN یا GiST در افزونهٔ pg_trgm کمک میکنند.
تعریف: قرارداد GET /v1/products?q=&category=&min_price=&max_price=&sort=newest|price|-price|name&limit=1..100&cursor= است. service.Catalog.List همهچیز را به domain.ProductQuery معتبر تبدیل میکند و limit + 1 سطر میخواهد تا وجود صفحهٔ بعد معلوم شود. خروجی next_cursor، JSON مبهم Base64url از {sort, value, id} است؛ Cursor صادرشده برای یک Sort با Sort دیگر رد میشود. pgstore.listSQL آن را به مقایسهٔ سطر، مثل (price_minor, id) > ($2, $3) ORDER BY price_minor, id LIMIT $4 تبدیل میکند؛ Index پشتیبان products_price (price_minor, id) WHERE active است. جستوجوی ساده (name ILIKE $1 OR sku ILIKE $1) است و %، _ و \ Escape میشوند. با فعال بودن FullText، عبارت search @@ websearch_to_tsquery('simple', $1) روی ستون Generated از نوع tsvector و GIN آن اجرا میشود. مسیر رشد ILIKE/tsvector این است: برای چند هزار محصول از ILIKE شروع کنید؛ وقتی جستوجو قابلیت مهمی شد به tsvector برای Stemming و رتبهبندی با ts_rank یا pg_trgm برای تحمل غلط تایپی بروید؛ وقتی خودش محصول شد OpenSearch، Meilisearch یا Typesense را انتخاب کنید. Handler همچنین Link: <...cursor=...>; rel="next" میفرستد.
Page Request SQL predicate Returns
1 1 ?sort=price&limit=2 active 100, 200 (+1 probe row) next_cursor=c1
2 2 ?sort=price&limit=2&cursor=c1 active AND (price_minor, id) > (200, 2) 300, 400 next_cursor=c2
3 - admin inserts a product at 150 (page 2 already read) no duplicate, no gap after the cursor
4 3 ?sort=price&limit=2&cursor=c2 active AND (price_minor, id) > (400, 4) 500, no next_cursor
5 - ?sort=name&cursor=c2 cursor sort != name 422 cursor invalidسناریوی واقعی: کاتالوگ موبایل با Infinite scroll؛ فهرست «قیمت از کم به زیاد» در یک دسته؛ جستوجوی «go book» که باید «The Go Programming Book» را پیدا کند؛ و Crawlerی که صفحهٔ 10,000 را میکوبد و Keyset هزینهاش را مثل صفحهٔ 1 نگه میدارد.
| نیاز | این پروژه | قدم بعد | Index |
|---|---|---|---|
| صفحهبندی | Keyset با Cursor مبهم | همان | (sort_col, id) WHERE active برای هر Sort |
| فیلتر دسته و قیمت | پارامترهای فهرست مجاز | شمارش Facet در موتور Search | (category_id, created_at DESC, id DESC) |
| Sort | 4 ترتیب ثابت | Collation هر Locale | یکی برای هر ترتیب؛ اینجا name COLLATE "C" |
| جستوجوی زیررشته | ILIKE با Wildcardهای Escapeشده | GIN روی pg_trgm | ندارد؛ Seq scan، یا Trigram |
| جستوجوی کلمه | Generated column از نوع tsvector با FullText | وزن، ts_rank و مترادفها | GIN روی search |
| ارتباط، غلط تایپی و Facet در مقیاس | OpenSearch / Meilisearch / Typesense از راه Outbox | خارجی |
راهحل / نحوهٔ استفاده: ابتدا اعتبارسنجی و کد Cursor، سپس SQL builder:
package service
import (
"context"
"encoding/base64"
"encoding/json"
"strconv"
"strings"
"time"
"academy/ecommerce-api-project/domain"
)
// Catalog lists and manages products.
type Catalog struct{ Deps }
// ListParams is the raw query string, as strings, before validation.
type ListParams struct {
Search, Category, MinPrice, MaxPrice, Sort, Limit, Cursor string
}
// Page is one keyset page.
type Page struct {
Items []domain.Product
NextCursor string // empty on the last page
}
var sorts = map[string]domain.SortField{"": domain.SortNewest, "newest": domain.SortNewest,
"price": domain.SortPriceAsc, "-price": domain.SortPriceDesc, "name": domain.SortName}
// List validates the parameters, then asks the store for Limit+1 rows: the
// extra row only tells us whether there is a next page.
func (c Catalog) List(ctx context.Context, in ListParams) (Page, error) {
q, err := parseList(in)
if err != nil {
return Page{}, err
}
limit := q.Limit
q.Limit++
rows, err := c.Store.Catalog().ListProducts(ctx, q)
if err != nil {
return Page{}, err
}
p := Page{Items: rows}
if len(rows) > limit {
p.Items = rows[:limit]
p.NextCursor = EncodeCursor(cursorFor(q.Sort, p.Items[limit-1]))
}
return p, nil
}
func parseList(in ListParams) (domain.ProductQuery, error) {
var v ValidationError
q := domain.ProductQuery{Search: strings.TrimSpace(in.Search), Limit: 20}
if len(q.Search) > 100 {
v.add("q", "at most 100 characters")
}
s, ok := sorts[in.Sort]
if !ok {
v.add("sort", "one of newest, price, -price, name")
}
q.Sort = s
num := func(field, raw string, lo, hi int64) int64 {
if raw == "" {
return 0
}
n, err := strconv.ParseInt(raw, 10, 64)
if err != nil || n < lo || n > hi {
v.add(field, "integer between %d and %d", lo, hi)
}
return n
}
q.CategoryID = num("category", in.Category, 1, 1<<53)
q.MinPrice = num("min_price", in.MinPrice, 0, 1<<53)
q.MaxPrice = num("max_price", in.MaxPrice, 0, 1<<53)
if l := num("limit", in.Limit, 1, 100); l > 0 {
q.Limit = int(l)
}
if q.MaxPrice > 0 && q.MinPrice > q.MaxPrice {
v.add("min_price", "must not exceed max_price")
}
if in.Cursor != "" {
c, err := DecodeCursor(in.Cursor)
if err != nil || c.Sort != q.Sort {
v.add("cursor", "invalid or issued for another sort order")
} else {
q.After = &c
}
}
return q, v.orNil()
}
func cursorFor(s domain.SortField, p domain.Product) domain.Cursor {
c := domain.Cursor{Sort: s, ID: p.ID}
switch s {
case domain.SortPriceAsc, domain.SortPriceDesc:
c.Value = strconv.FormatInt(p.Price.Amount, 10)
case domain.SortName:
c.Value = p.Name
default:
c.Value = p.CreatedAt.UTC().Format(time.RFC3339Nano)
}
return c
}
// EncodeCursor makes the opaque next_cursor string (base64url JSON).
func EncodeCursor(c domain.Cursor) string {
b, _ := json.Marshal(c)
return base64.RawURLEncoding.EncodeToString(b)
}
// DecodeCursor reverses EncodeCursor.
func DecodeCursor(s string) (domain.Cursor, error) {
var c domain.Cursor
b, err := base64.RawURLEncoding.DecodeString(s)
if err == nil {
err = json.Unmarshal(b, &c)
}
return c, err
}
// Get returns one active product.
func (c Catalog) Get(ctx context.Context, id int64) (domain.Product, error) {
return c.Store.Catalog().GetProduct(ctx, id)
}
// ProductInput is the admin create/update body.
type ProductInput struct {
SKU, Name, TaxClass string
CategoryID int64
Price int64 // minor units
Stock int64
}
func (in ProductInput) validate(rates map[string]int64) error {
var v ValidationError
if in.SKU == "" || len(in.SKU) > 32 {
v.add("sku", "1 to 32 characters")
}
if in.Name == "" || len(in.Name) > 200 {
v.add("name", "1 to 200 characters")
}
if in.Price <= 0 {
v.add("price", "positive amount in minor units")
}
if _, ok := rates[in.TaxClass]; !ok {
v.add("tax_class", "unknown tax class")
}
if in.Stock < 0 {
v.add("stock", "must not be negative")
}
return v.orNil()
}
// CreateProduct is admin-only.
func (c Catalog) CreateProduct(ctx context.Context, who domain.Principal, in ProductInput) (domain.Product, error) {
if err := requireAdmin(who); err != nil {
return domain.Product{}, err
}
if err := in.validate(c.TaxRates); err != nil {
return domain.Product{}, err
}
p := domain.Product{SKU: in.SKU, Name: in.Name, CategoryID: in.CategoryID, TaxClass: in.TaxClass,
Price: c.money(in.Price), Active: true, CreatedAt: c.Now()}
err := c.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
if err := tx.Products().Create(ctx, &p); err != nil {
return err
}
return tx.Inventory().SetOnHand(ctx, p.ID, in.Stock)
})
return p, err
}
// UpdatePrice changes a price if nobody else changed the product since the
// admin loaded it (version from the ETag / request body).
func (c Catalog) UpdatePrice(ctx context.Context, who domain.Principal, id, price, version int64) (domain.Product, error) {
if err := requireAdmin(who); err != nil {
return domain.Product{}, err
}
if price <= 0 {
return domain.Product{}, &ValidationError{Fields: []FieldError{{"price", "positive amount in minor units"}}}
}
var p domain.Product
err := c.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
var err error
if p, err = tx.Products().Get(ctx, id); err != nil {
return err
}
p.Price = c.money(price)
return tx.Products().Update(ctx, &p, version)
})
return p, err
}package pgstore
import (
"context"
"fmt"
"strconv"
"strings"
"time"
"github.com/jackc/pgx/v5"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/store"
)
// Catalog returns the read side (it runs on the pool, outside transactions).
func (s *Store) Catalog() store.Catalog { return catalog{q: s.reader, fullText: s.FullText} }
type catalog struct {
q querier
fullText bool
}
func (c catalog) GetProduct(ctx context.Context, id int64) (domain.Product, error) {
return scanProduct(c.q.QueryRow(ctx, `SELECT `+productCols+` FROM products WHERE id = $1 AND active`, id))
}
func (c catalog) ListProducts(ctx context.Context, q domain.ProductQuery) ([]domain.Product, error) {
sql, args := listSQL(q, c.fullText)
rows, err := c.q.Query(ctx, sql, args...)
if err != nil {
return nil, err
}
return pgx.CollectRows(rows, func(row pgx.CollectableRow) (domain.Product, error) { return scanProduct(row) })
}
// order maps a sort field to its ORDER BY and keyset comparison. Only these
// four strings ever reach the SQL: user input picks a key, never a column.
var order = map[domain.SortField]struct{ by, cmp, col string }{
domain.SortNewest: {"created_at DESC, id DESC", "<", "created_at"},
domain.SortPriceAsc: {"price_minor, id", ">", "price_minor"},
domain.SortPriceDesc: {"price_minor DESC, id DESC", "<", "price_minor"},
domain.SortName: {"name COLLATE \"C\", id", ">", "name COLLATE \"C\""},
}
// listSQL builds the keyset query. Every value is a $n parameter.
func listSQL(q domain.ProductQuery, fullText bool) (string, []any) {
var where []string
var args []any
arg := func(v any) string { args = append(args, v); return "$" + strconv.Itoa(len(args)) }
where = append(where, "active")
if q.CategoryID != 0 {
where = append(where, "category_id = "+arg(q.CategoryID))
}
if q.MinPrice > 0 {
where = append(where, "price_minor >= "+arg(q.MinPrice))
}
if q.MaxPrice > 0 {
where = append(where, "price_minor <= "+arg(q.MaxPrice))
}
if q.Search != "" {
if fullText {
where = append(where, "search @@ websearch_to_tsquery('simple', "+arg(q.Search)+")")
} else {
p := arg("%" + escapeLike(q.Search) + "%")
where = append(where, "(name ILIKE "+p+" OR sku ILIKE "+p+")")
}
}
o, ok := order[q.Sort]
if !ok {
o = order[domain.SortNewest]
}
if c := q.After; c != nil {
var v any = c.Value
switch q.Sort {
case domain.SortPriceAsc, domain.SortPriceDesc:
v, _ = strconv.ParseInt(c.Value, 10, 64)
case domain.SortName:
default:
v, _ = time.Parse(time.RFC3339Nano, c.Value)
}
where = append(where, fmt.Sprintf("(%s, id) %s (%s, %s)", o.col, o.cmp, arg(v), arg(c.ID)))
}
sql := `SELECT ` + productCols + ` FROM products WHERE ` + strings.Join(where, " AND ") +
` ORDER BY ` + o.by + ` LIMIT ` + arg(q.Limit)
return sql, args
}
// escapeLike makes %, _ and \ literal inside an ILIKE pattern.
func escapeLike(s string) string {
return strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(s)
}احراز هویت، Session/JWT و مجوزها: مشتری در برابر Admin حیاتی
به زبان ساده: احراز هویت (Authentication) در Middleware، یک بار برای هر درخواست، جواب میدهد «چه کسی تماس گرفته؟». مجوزدهی (Authorization) میپرسد «آیا این فرد میتواند این کار را روی این شیء انجام دهد؟» و دو سطح دارد: Route، مثلاً Endpoint مخصوص Admin است؟ و شیء، مثلاً سفارش متعلق به همین فرد است؟
بدفهمی رایج: «اگر Route ورود بخواهد، داده امن است.» در OWASP API Security Top 10، نقص مجوز سطح شیء یا Broken Object Level Authorization رتبهٔ اول، API1:2023، است: "Every API endpoint that receives an ID of an object, and performs any action on the object, should implement object-level authorization checks." Bob واردشده با درخواست GET /v1/orders/ord_alice باید 404 بگیرد. دوم: «برای سفارش دیگری 403 بده.» 403 وجود سفارش را تأیید میکند؛ 404 چنین نمیکند. سوم: «Role را از URL یا Header کلاینت بگیر.» Role از Session یا Token تأییدشده میآید.
تعریف: httpapi.Authenticator درخواست را به domain.Principal{UserID, Email, Role} تبدیل و در Context قرار میدهد. این پروژه StaticTokens دارد؛ برای تست و دو Token توسعه در cmd/api وقتی ECOM_ENV=development. در Production، Session store یا JWT verifier فصل Authentication in Go، با Argon2id، scs و golang-jwt/jwt/v5 جای آن مینشیند. در Route، customer(h) با 401 و WWW-Authenticate: Bearer realm="shop" پاسخ میدهد و admin(h) با 403. در سطح شیء، Principal.CanSee(ownerID) داخل Orders.Get و Orders.Cancel بررسی میشود؛ requireAdmin هم در Fulfil، CreateProduct و UpdatePrice هست. این دفاع چندلایه لازم است چون Job و Script هم Service را صدا میزنند. برای فروشگاه وب، Cookie session ساده و قابل ابطال است ولی محافظت CSRF میخواهد؛ برای موبایل، JWT کوتاهعمر همراه Refresh مناسب است. هر دو در نهایت همان Principal را میسازند.
Request Middleware Route guard Service check Result
1 GET /v1/orders/ord_a (no token) no principal customer: 401 401
2 GET /v1/orders/ord_a Bearer bob Principal{8, customer} ok CanSee(7)? no 404
3 GET /v1/orders/ord_a Bearer alice Principal{7, customer} ok CanSee(7)? yes 200
4 POST /v1/admin/products Bearer alice Principal{7, customer} admin: 403 403
5 POST /v1/admin/orders/x/fulfil admin Principal{1, admin} ok requireAdmin ok 200 / 409سناریوی واقعی: شناسههای ترتیبی حدسزدنی BOLA را ساده میکنند؛ OWASP میگوید "Prefer the use of random and unpredictable values as GUIDs for records' IDs". اینجا شناسه 128 بیت تصادفی است؛ کمک میکند اما جای Authorization را نمیگیرد. نقش پشتیبان که خواندن دارد ولی Refund ندارد؛ Webhook بدون کاربر که با HMAC احراز هویت میشود؛ و برنامهٔ موبایل و فروشگاه وب با API مشترک از نمونههای دیگرند.
| بررسی | محل | پاسخ | مثال |
|---|---|---|---|
| فراخوانندهای هست؟ | Guard به نام customer | 401 + WWW-Authenticate | ثبت سفارش ناشناس |
| فراخواننده Admin است؟ | Guard به نام admin و requireAdmin | 403 | ساخت محصول توسط مشتری |
| شیء متعلق به فراخواننده است؟ | Service با CanSee | 404 | خواندن سفارش Alice توسط Bob |
| سبد متعلق به مهمان است؟ | MergeOnLogin | نادیده گرفته میشود | ادغام سبد مشتری دیگر |
| فراخواننده PSP است؟ | HMAC روی Body خام | 400 | Webhook جعلی |
راهحل / نحوهٔ استفاده: Middlewareهای احراز هویت، Guard، Rate limiter و Headerهای امنیتی در یک فایلاند.
package httpapi
import (
"context"
"crypto/rand"
"encoding/hex"
"log/slog"
"net"
"net/http"
"strings"
"sync"
"time"
"golang.org/x/time/rate"
"academy/ecommerce-api-project/domain"
)
type ctxKey struct{}
// PrincipalFrom returns the authenticated caller, if any.
func PrincipalFrom(ctx context.Context) (domain.Principal, bool) {
p, ok := ctx.Value(ctxKey{}).(domain.Principal)
return p, ok
}
// Authenticator resolves the caller. Production uses sessions or JWT (see the
// authentication chapter); tests and local runs use StaticTokens.
type Authenticator interface {
Authenticate(r *http.Request) (domain.Principal, bool)
}
// StaticTokens maps a bearer token to a principal.
type StaticTokens map[string]domain.Principal
func (s StaticTokens) Authenticate(r *http.Request) (domain.Principal, bool) {
tok, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
if !ok {
return domain.Principal{}, false
}
p, ok := s[tok]
return p, ok
}
func chain(h http.Handler, mws ...func(http.Handler) http.Handler) http.Handler {
for i := len(mws) - 1; i >= 0; i-- {
h = mws[i](h)
}
return h
}
func requestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get("X-Request-ID")
if id == "" || len(id) > 64 {
b := make([]byte, 8)
_, _ = rand.Read(b)
id = hex.EncodeToString(b)
}
w.Header().Set("X-Request-ID", id)
next.ServeHTTP(w, r)
})
}
// securityHeaders sets the headers the OWASP REST Security Cheat Sheet lists
// for API responses.
func securityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Set("Cache-Control", "no-store")
h.Set("Content-Security-Policy", "frame-ancestors 'none'")
h.Set("X-Content-Type-Options", "nosniff")
h.Set("X-Frame-Options", "DENY")
h.Set("Strict-Transport-Security", "max-age=63072000; includeSubDomains")
h.Set("Referrer-Policy", "no-referrer")
next.ServeHTTP(w, r)
})
}
func (a *API) recoverer(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if v := recover(); v != nil {
if v == http.ErrAbortHandler {
panic(v)
}
a.Log.ErrorContext(r.Context(), "panic", "value", v, "path", r.URL.Path)
writeProblem(w, r, Problem{Title: "Internal Server Error", Status: 500})
}
}()
next.ServeHTTP(w, r)
})
}
func (a *API) logRequests(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
sw := &statusWriter{ResponseWriter: w, status: 200}
next.ServeHTTP(sw, r)
a.Log.LogAttrs(r.Context(), slog.LevelInfo, "http",
slog.String("method", r.Method), slog.String("path", r.URL.Path), slog.Int("status", sw.status),
slog.Duration("took", time.Since(start)), slog.String("request_id", w.Header().Get("X-Request-ID")))
})
}
type statusWriter struct {
http.ResponseWriter
status int
}
func (s *statusWriter) WriteHeader(c int) { s.status = c; s.ResponseWriter.WriteHeader(c) }
func (a *API) authenticate(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if p, ok := a.Auth.Authenticate(r); ok {
r = r.WithContext(context.WithValue(r.Context(), ctxKey{}, p))
}
next.ServeHTTP(w, r)
})
}
// customer and admin wrap single routes: authorization per route, and the
// services check again per object.
func customer(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if _, ok := PrincipalFrom(r.Context()); !ok {
w.Header().Set("WWW-Authenticate", `Bearer realm="shop"`)
writeProblem(w, r, Problem{Title: "Unauthorized", Status: 401})
return
}
h(w, r)
}
}
func admin(h http.HandlerFunc) http.HandlerFunc {
return customer(func(w http.ResponseWriter, r *http.Request) {
if p, _ := PrincipalFrom(r.Context()); !p.IsAdmin() {
writeProblem(w, r, Problem{Title: "Forbidden", Status: 403})
return
}
h(w, r)
})
}
// IPLimiter is a token bucket per client IP (golang.org/x/time/rate). Behind
// a proxy, derive the IP from a header only the proxy can set.
type IPLimiter struct {
mu sync.Mutex
buckets map[string]*rate.Limiter
r rate.Limit
burst int
}
func NewIPLimiter(perSecond float64, burst int) *IPLimiter {
return &IPLimiter{buckets: map[string]*rate.Limiter{}, r: rate.Limit(perSecond), burst: burst}
}
func (l *IPLimiter) allow(ip string) bool {
l.mu.Lock()
b, ok := l.buckets[ip]
if !ok {
b = rate.NewLimiter(l.r, l.burst)
l.buckets[ip] = b
}
l.mu.Unlock()
return b.Allow()
}
func (a *API) rateLimit(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
ip = r.RemoteAddr
}
if a.Limiter != nil && !a.Limiter.allow(ip) {
w.Header().Set("Retry-After", "1")
writeProblem(w, r, Problem{Type: problemBase + "rate-limited", Title: "Too Many Requests", Status: 429})
return
}
next.ServeHTTP(w, r)
})
}اعتبارسنجی ورودی و قالب خطا حیاتی
به زبان ساده: درخواست بد را پیش از رسیدن به پایگاه داده رد کنید، دقیقاً بگویید کدام فیلدها نادرستاند و همهٔ خطاها را در یک شکل JSON برگردانید تا کلاینت یک روش پردازش داشته باشد.
بدفهمی رایج: «اعتبارسنجی (Validation) فقط یک لایه است.» شکل ورودی، یعنی JSON معتبر، نداشتن فیلد ناشناخته و Body زیر 1 MiB، کار Handler است. قاعدهٔ کسبوکار، یعنی تعداد 0..10، قیمت مثبت، کلاس مالیاتی شناختهشده و سازگاری Cursor با Sort، کار Service است؛ چون Job و Script هم Service را صدا میزنند. Constraint پایگاه داده پشتیبان است. دوم: «برای همهچیز 400 بده.» 400 یعنی Parse نشد یا Header اجباری نبود؛ 422 یعنی Parse شد ولی معنای نامعتبر دارد؛ 409 یعنی با وضعیت فعلی مثل موجودی، وضعیت سفارش یا کلید در حال اجرا تعارض دارد؛ 412 یعنی پیششرط If-Match شکست خورد و 428 یعنی پیششرط الزامی است.
تعریف: readBody از http.MaxBytesReader و json.Decoder با DisallowUnknownFields استفاده میکند. service.ValidationError{Fields []FieldError} همهٔ فیلدهای نامعتبر را جمع میکند. httpapi.fail هر نوع خطا را به یک Problem از RFC 9457 با application/problem+json نگاشت میکند: اعضای type، title، status، detail، instance و افزونههای request_id، errors، product_id، available. RFC 9457، "problem detail" را "to carry machine-readable details of errors in HTTP response content" تعریف میکند. خطای داخلی با Request id ثبت و با 500 عمومی بدون نشت جزئیات پاسخ داده میشود. Validation دستی ماژول را کوچک نگه میدارد؛ A REST API in Go آن را با go-playground/validator مقایسه میکند که "implements value validations for structs and individual fields based on tags".
Input Layer Answer
1 {"qty":1,"price":1} (unknown field "price") handler 422 validation, field body
2 {"qty":11} service 422 validation, field qty
3 ?sort=hack&limit=1000 service 422, two fields: sort, limit
4 POST /v1/orders without Idempotency-Key handler 400 idempotency-key-missing
5 cart line for a product with 1 left, qty 2 service 409 out-of-stock, product_id, available 1
6 a nil pointer in a handler recoverer 500, logged with request_id, body genericسناریوی واقعی: کلاینت موبایل "qty": "2" را رشته میفرستد و خطای Decoder با 422 میگیرد؛ کلاینت مخرب با فیلد اضافه قیمت میگذارد و بهخاطر فیلد ناشناخته 422 میگیرد؛ شریک تجاری نام فیلد را میخواهد تا خطا را کنار ورودی نمایش دهد؛ مهندس پشتیبانی هم با request_id داخل تصویر مشتری Logها را جستوجو میکند.
| موقعیت | Status | type؛ پسوند https://shop.example/problems/ |
|---|---|---|
| فیلد نامعتبر | 422 | validation |
| موجودی ناکافی | 409 | out-of-stock |
| وضعیت اجازه نمیدهد | 409 | invalid-transition |
If-Match کهنه | 412 | version-conflict |
| سبد خالی یا محصول غیرفعال | 422 | cart |
| استفادهٔ مجدد کلید با Body دیگر | 422 | idempotency-key-reused |
| پایان انتظار قفل؛ کلید تکراری هنوز اجرا میشود یا سطر داغ است | 409 | busy |
| نبودن کلید | 400 | idempotency-key-missing |
| عبور از نرخ مجاز | 429 | rate-limited |
| پیدا نشد، احراز نشده، ممنوع، داخلی | 404, 401, 403, 500 | about:blank |
راهحل / نحوهٔ استفاده:
package httpapi
import (
"encoding/json"
"errors"
"net/http"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/service"
"academy/ecommerce-api-project/store"
)
// Problem is the RFC 9457 error envelope, served as application/problem+json.
type Problem struct {
Type string `json:"type"`
Title string `json:"title"`
Status int `json:"status"`
Detail string `json:"detail,omitempty"`
Instance string `json:"instance,omitempty"`
RequestID string `json:"request_id,omitempty"`
Errors []service.FieldError `json:"errors,omitempty"`
ProductID int64 `json:"product_id,omitempty"`
Available *int64 `json:"available,omitempty"`
}
const problemBase = "https://shop.example/problems/"
func writeProblem(w http.ResponseWriter, r *http.Request, p Problem) {
p.Instance = r.URL.Path
p.RequestID = w.Header().Get("X-Request-ID")
if p.Type == "" {
p.Type = "about:blank"
}
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(p.Status)
_ = json.NewEncoder(w).Encode(p)
}
// fail maps service and store errors to statuses in one place.
func (a *API) fail(w http.ResponseWriter, r *http.Request, err error) {
var ve *service.ValidationError
var oos *domain.OutOfStockError
switch {
case errors.As(err, &ve):
writeProblem(w, r, Problem{Type: problemBase + "validation", Title: "Invalid input", Status: 422, Errors: ve.Fields})
case errors.As(err, &oos):
writeProblem(w, r, Problem{Type: problemBase + "out-of-stock", Title: "Not enough stock", Status: 409,
Detail: oos.Error(), ProductID: oos.ProductID, Available: &oos.Available})
case errors.Is(err, domain.ErrNotFound):
writeProblem(w, r, Problem{Title: "Not Found", Status: 404})
case errors.Is(err, domain.ErrForbidden):
writeProblem(w, r, Problem{Title: "Forbidden", Status: 403})
case errors.Is(err, domain.ErrInvalidTransition):
writeProblem(w, r, Problem{Type: problemBase + "invalid-transition", Title: "Not allowed in the current status", Status: 409, Detail: err.Error()})
case errors.Is(err, domain.ErrConflict):
writeProblem(w, r, Problem{Type: problemBase + "version-conflict", Title: "Changed by someone else", Status: 412})
case errors.Is(err, domain.ErrEmptyCart), errors.Is(err, domain.ErrInactiveProduct):
writeProblem(w, r, Problem{Type: problemBase + "cart", Title: "Cart cannot be checked out", Status: 422, Detail: err.Error()})
case errors.Is(err, service.ErrIdempotencyMismatch):
writeProblem(w, r, Problem{Type: problemBase + "idempotency-key-reused", Title: "Idempotency-Key reused with another body", Status: 422})
case errors.Is(err, store.ErrBusy):
w.Header().Set("Retry-After", "1")
// lock_timeout expired: usually a duplicate request with the same
// Idempotency-Key still running, sometimes a very hot stock row.
writeProblem(w, r, Problem{Type: problemBase + "busy", Title: "Conflicting request still running, retry shortly", Status: 409})
case errors.Is(err, service.ErrAmountMismatch):
writeProblem(w, r, Problem{Type: problemBase + "amount-mismatch", Title: "Amount differs from the order", Status: 422})
default:
a.Log.ErrorContext(r.Context(), "internal error", "err", err, "path", r.URL.Path)
writeProblem(w, r, Problem{Title: "Internal Server Error", Status: 500}) // never leak err text
}
}رویدادها: OrderPlaced و PaymentCaptured از Outbox به RabbitMQ یا Bus داخل فرایند حیاتی
به زبان ساده: وقتی سفارش ثبت یا پرداخت میشود، بخشهای دیگر سیستم باید باخبر شوند. رویداد (Event) را به شکل سطر در همان تراکنش (Transaction) تغییر بنویسید. یک واسط انتشار (Relay) سطرها را میخواند و به Bus داخل فرایند، برای مصرفکنندهٔ محلی مثل Worker ایمیل، و وقتی سرویسهای دیگر وجود دارند به RabbitMQ میدهد.
بدفهمی رایج: «بلافاصله بعد از COMMIT در RabbitMQ منتشر کن.» Crash بین این دو رویداد را گم میکند؛ سفارش هست ولی کسی ایمیل یا کالا نمیفرستد. انتشار پیش از COMMIT هم سفارش Rollbackشده را اعلام میکند. دوم: «تحویل دقیقاً یک بار است.» Relay فقط بعد از برگشت nil از Publisher سطر را منتشرشده علامت میزند؛ Crash بین این دو باعث انتشار دوباره میشود. تحویل حداقل یک بار است و مصرفکننده با نگه داشتن شناسهٔ رویداد در Inbox اثر را یکباره میکند. سوم: «چند Relay سرعت را بیشتر میکنند.» دو Relay روی یک جدول، رویدادها را دوبار و خارج از ترتیب منتشر میکنند. برای هر پایگاه داده یکی اجرا کنید؛ این پروژه با APP_ROLE و اجارهٔ رهبری آن را اعمال میکند، طبق Monolith، یا بر اساس Aggregate بخشبندی کنید.
تعریف: domain.Event{ID, Type, AggregateID, OccurredAt, Payload} شناسهٔ قطعی مثل order.placed:ord_x:v1 و payment.captured:ord_x:v2 دارد. outbox.Relay.RunOnce یک Batch را از قدیمیترین میخواند، با ORDER BY seq؛ بیرون هر Transaction منتشر میکند؛ روی اولین شکست یا اولین رویدادی که هنوز در Backoff است میایستد تا payment.captured از order.placed جلو نزند. سپس در Transaction کوتاه دوم، موفقها را علامت میزند و برای شکستخورده attempts + 1 و next_attempt_at دیرتر با رشد نمایی و سقف 10 دقیقه ثبت میکند. bus.Bus بر اساس Type به Handlerهای نامدار مسیریابی و خطاهایشان را Join میکند؛ outbox.Fanout{bus, rabbit} به هر دو میفرستد. rabbit.Publisher یک Topic exchange بادوام تعریف میکند، Channel را در Confirm mode میگذارد و با PublishWithDeferredConfirmWithContext و WaitContext منتظر Ack میماند. پیامها JSON ماندگار با MessageId برابر Event id هستند. amqp091-go خودش Reconnect نمیکند؛ سورس میگوید: "To reconnect after a transport or protocol error, register a listener here and re-run your setup process". بنابراین Publisher، NotifyClose را ثبت میکند، اتصال و Channel مرده را کنار میگذارد و Publish بعدی دوباره Dial میکند، Exchange را تعریف و Confirm را فعال میکند. بین Dialهای ناموفق Backoff نمایی دارد. هنگام قطع Broker، Publish شکست میخورد و رویداد در Outbox میماند؛ پس از Restart، Relay ادامه میدهد؛ TestPublisherRedialsAfterBrokerRestart. راهنمای RabbitMQ دلیل Confirm را روشن میگوید: "Networks can fail in less-than-obvious ways". الگوی microservices.io و انواع Relay، Polling یا CDC با Debezium، در Outbox Pattern هستند؛ مصرفکننده، Watermill و SQS در Event-Driven Go؛ و تفکیک رویداد دامنه از Integration در Domain Events vs Integration Events.
Checkout tx Relay Consumers
1 INSERT orders ... ; INSERT outbox (order.placed:ord_1:v1); COMMIT
2 SELECT ... WHERE published_at IS NULL ORDER BY seq
3 bus: mail handler -> inbox? no -> send -> mark
4 rabbit: publish, wait for confirm (ack)
5 (crash before marking)
6 restart: publish order.placed:ord_1:v1 again
7 mail inbox: seen -> skip
8 warehouse: MessageId seen -> skip
9 UPDATE outbox SET published_at = now() WHERE event_id = ANY(...)سناریوی واقعی: SMTP در Black Friday ده دقیقه قطع است؛ رویدادها Backoff میکنند و بعد به ترتیب تخلیه میشوند. RabbitMQ حین Publish دوباره راه میافتد؛ Ack نمیرسد، Publisher دوباره وصل میشود و Relay Retry میکند. سرویس تحلیل یک هفته بعد مستقر میشود و از Queue خودش Replay میکند. رسید هم هرگز نباید برای سفارشی فرستاده شود که Transaction آن Rollback شده است.
| انتقال | چه وقت | تحویل | ترتیب | اینجا |
|---|---|---|---|---|
| Bus داخل فرایند (In-process bus) | Monolith و مصرفکنندهٔ محلی | حداقل یک بار؛ Retry در Relay | در هر Relay | bus.Bus |
| RabbitMQ Topic exchange با Confirm | مصرف سرویسهای دیگر | حداقل یک بار و ماندگار | هر Queue با یک Consumer | rabbit.Publisher |
| Kafka topic با Key برابر Order id | حجم بالا و Replay | حداقل یک بار | هر Partition | Event-Driven Go |
CDC با Debezium روی outbox | بدون Polling، مبتنی بر WAL | حداقل یک بار | هر Table/Key | Outbox Pattern |
dispatch(...)->afterCommit() در Laravel | Monolith در Laravel | پس از Commit ولی بیرون Transaction | هر Queue | برای توسعهدهندگان PHP/Laravel |
راهحل / نحوهٔ استفاده: Relay، Bus و Publisher در RabbitMQ:
// Package outbox relays events from the outbox table to a publisher (the
// in-process bus or RabbitMQ). Delivery is at least once: an event is
// marked published only after Publish returned nil, so a crash in between
// publishes it again and consumers dedupe by event id.
package outbox
import (
"context"
"time"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/store"
)
// Publisher sends one event to the outside world.
type Publisher interface {
Publish(ctx context.Context, e domain.Event) error
}
// Relay polls the outbox.
type Relay struct {
Store store.Store
Pub Publisher
Now func() time.Time
Batch int
Backoff func(attempt int) time.Duration // delay before the next try of a failed event
}
// RunOnce reads a batch, publishes in order outside any transaction, and
// then records the outcome in a second short transaction. It stops at the
// first failure or at the first event still backing off: a later event
// (payment.captured) must not overtake an earlier one (order.placed). Run
// one relay per database (a single worker replica, or a leader lease) to
// keep that order; a second relay would only cause duplicates, which
// consumers drop.
func (r *Relay) RunOnce(ctx context.Context) (int, error) {
now := r.Now()
var evs []domain.Event
err := r.Store.InTx(ctx, func(ctx context.Context, tx store.Tx) error {
var err error
evs, err = tx.Outbox().Claim(ctx, max(r.Batch, 1))
return err
})
if err != nil {
return 0, err
}
var done []string
var failed *domain.Event
var pubErr error
for _, e := range evs {
if e.NextAttempt.After(now) {
break // the head of the queue is backing off; nothing may overtake it
}
if pubErr = r.Pub.Publish(ctx, e); pubErr != nil {
failed = &e
break
}
done = append(done, e.ID)
}
if len(done) == 0 && failed == nil {
return 0, nil
}
// A crash before this commit republishes done: at-least-once.
err = r.Store.InTx(context.WithoutCancel(ctx), func(ctx context.Context, tx store.Tx) error {
if len(done) > 0 {
if err := tx.Outbox().MarkPublished(ctx, done, now); err != nil {
return err
}
}
if failed != nil {
return tx.Outbox().MarkFailed(ctx, failed.ID, now.Add(r.backoff(failed.Attempts+1)))
}
return nil
})
if err != nil {
return 0, err
}
return len(done), pubErr
}
func (r *Relay) backoff(attempt int) time.Duration {
if r.Backoff != nil {
return r.Backoff(attempt)
}
return min(time.Second<<min(attempt, 10), 10*time.Minute)
}
// Run calls RunOnce every interval until ctx is done. Errors are reported
// to onErr (a logger) and never stop the loop.
func (r *Relay) Run(ctx context.Context, every time.Duration, onErr func(error)) {
t := time.NewTicker(every)
defer t.Stop()
for {
if _, err := r.RunOnce(ctx); err != nil && onErr != nil && ctx.Err() == nil {
onErr(err)
}
select {
case <-ctx.Done():
return
case <-t.C:
}
}
}
// Fanout publishes to several publishers in order (the in-process bus for
// local consumers, RabbitMQ for other services). If one fails the event is
// retried for all; every consumer dedupes by event id.
type Fanout []Publisher
func (f Fanout) Publish(ctx context.Context, e domain.Event) error {
for _, p := range f {
if err := p.Publish(ctx, e); err != nil {
return err
}
}
return nil
}// Package bus is an in-process event bus: the outbox relay publishes to it
// and the worker's handlers subscribe. It is the "monolith" transport; the
// rabbit package is a drop-in Publisher for when consumers move out.
package bus
import (
"context"
"errors"
"fmt"
"sync"
"academy/ecommerce-api-project/domain"
)
// Handler handles one event. It must be idempotent: the relay redelivers.
type Handler func(ctx context.Context, e domain.Event) error
// Bus routes events by type to named handlers.
type Bus struct {
mu sync.RWMutex
subs map[string][]sub
}
type sub struct {
name string
h Handler
}
func New() *Bus { return &Bus{subs: map[string][]sub{}} }
// Subscribe registers h for an event type under a consumer name (the name
// is the inbox key, so two consumers of the same event dedupe separately).
func (b *Bus) Subscribe(eventType, consumer string, h Handler) {
b.mu.Lock()
defer b.mu.Unlock()
b.subs[eventType] = append(b.subs[eventType], sub{consumer, h})
}
// Publish calls every handler for e.Type synchronously and joins their
// errors. A failure makes the relay retry the event for all handlers, and
// the handlers that already succeeded skip it through their inbox.
func (b *Bus) Publish(ctx context.Context, e domain.Event) error {
b.mu.RLock()
subs := b.subs[e.Type]
b.mu.RUnlock()
var errs []error
for _, s := range subs {
if err := s.h(ctx, e); err != nil {
errs = append(errs, fmt.Errorf("%s: %w", s.name, err))
}
}
return errors.Join(errs...)
}// Package rabbit is an outbox.Publisher for RabbitMQ (amqp091-go). It
// publishes to a durable topic exchange with publisher confirms, so Publish
// returns nil only after the broker has taken responsibility for the
// message; the relay then marks the outbox row published. It survives a
// broker restart by redialling.
package rabbit
import (
"context"
"errors"
"fmt"
"sync"
"time"
amqp "github.com/rabbitmq/amqp091-go"
"academy/ecommerce-api-project/domain"
)
// Confirmation is the broker's answer for one publish (*amqp.DeferredConfirmation).
type Confirmation interface {
WaitContext(ctx context.Context) (bool, error)
}
// Channel is the part of *amqp.Channel the publisher uses.
type Channel interface {
ExchangeDeclare(name, kind string, durable, autoDelete, internal, noWait bool, args amqp.Table) error
Confirm(noWait bool) error
Publish(ctx context.Context, exchange, key string, msg amqp.Publishing) (Confirmation, error)
Close() error
}
// Conn is the part of *amqp.Connection the publisher uses.
type Conn interface {
Channel() (Channel, error)
NotifyClose(receiver chan *amqp.Error) chan *amqp.Error
Close() error
}
type amqpConn struct{ c *amqp.Connection }
func (a amqpConn) Channel() (Channel, error) {
ch, err := a.c.Channel()
if err != nil {
return nil, err
}
return amqpChannel{ch}, nil
}
func (a amqpConn) NotifyClose(r chan *amqp.Error) chan *amqp.Error { return a.c.NotifyClose(r) }
func (a amqpConn) Close() error { return a.c.Close() }
type amqpChannel struct{ *amqp.Channel }
// Publish uses publisher confirms. mandatory=false: queues are declared and
// bound at deploy time; an unroutable message would be acked and dropped
// (catch that with an alternate exchange, or mandatory=true plus NotifyReturn).
func (c amqpChannel) Publish(ctx context.Context, exchange, key string, msg amqp.Publishing) (Confirmation, error) {
dc, err := c.PublishWithDeferredConfirmWithContext(ctx, exchange, key, false, false, msg)
if err != nil {
return nil, err
}
return dc, nil
}
// Dial returns a dialer for an AMQP URL.
func Dial(url string) func() (Conn, error) {
return func() (Conn, error) {
c, err := amqp.Dial(url)
if err != nil {
return nil, err
}
return amqpConn{c}, nil
}
}
// ErrUnavailable: the broker is down and the next redial is not due yet.
var ErrUnavailable = errors.New("rabbit: broker unavailable, redial backing off")
// Publisher holds one connection and one channel in confirm mode, and
// replaces both after the broker closes them. amqp091-go does not reconnect
// by itself: a closed connection stays closed and every channel on it is
// gone. NotifyClose marks the publisher broken; the next Publish redials
// (exchange declared again, confirm mode again) with exponential backoff
// between failed dials. While it is down Publish returns an error, the
// relay keeps the event in the outbox and retries it later, so nothing is
// lost and nothing overtakes it.
type Publisher struct {
dial func() (Conn, error)
exchange string
MinBackoff, MaxBackoff time.Duration
mu sync.Mutex // also serialises publishing: a channel is not safe for concurrent use
conn Conn
ch Channel
gen int
backoff time.Duration
nextDial time.Time
}
// New connects to url and declares the exchange.
func New(url, exchange string) (*Publisher, error) { return NewWithDialer(Dial(url), exchange) }
// NewWithDialer is New with an injectable dialer (tests).
func NewWithDialer(dial func() (Conn, error), exchange string) (*Publisher, error) {
p := &Publisher{dial: dial, exchange: exchange, MinBackoff: 500 * time.Millisecond, MaxBackoff: 30 * time.Second}
p.mu.Lock()
defer p.mu.Unlock()
return p, p.connectLocked()
}
func (p *Publisher) connectLocked() error {
conn, err := p.dial()
if err != nil {
return err
}
ch, err := conn.Channel()
if err == nil {
err = ch.ExchangeDeclare(p.exchange, "topic", true, false, false, false, nil)
}
if err == nil {
err = ch.Confirm(false)
}
if err != nil {
_ = conn.Close()
return err
}
p.conn, p.ch = conn, ch
p.gen++
gen := p.gen
notify := conn.NotifyClose(make(chan *amqp.Error, 1))
go func() {
for range notify { // closed by the library after the close reason (if any)
}
p.mu.Lock()
defer p.mu.Unlock()
if p.gen == gen {
p.dropLocked()
}
}()
return nil
}
func (p *Publisher) dropLocked() {
if p.ch != nil {
_ = p.ch.Close()
}
if p.conn != nil {
_ = p.conn.Close()
}
p.ch, p.conn = nil, nil
}
func (p *Publisher) broken() bool {
p.mu.Lock()
defer p.mu.Unlock()
return p.ch == nil
}
// Publish sends e with routing key e.Type ("order.placed") and waits for the
// broker's ack. A nack, a timeout or a closed channel is an error: the relay
// retries, and the consumer dedupes by MessageId.
func (p *Publisher) Publish(ctx context.Context, e domain.Event) error {
p.mu.Lock()
defer p.mu.Unlock()
if p.ch == nil {
if time.Now().Before(p.nextDial) {
return ErrUnavailable
}
if err := p.connectLocked(); err != nil {
p.backoff = min(max(p.backoff*2, p.MinBackoff), p.MaxBackoff)
p.nextDial = time.Now().Add(p.backoff)
return fmt.Errorf("rabbit: redial: %w", err)
}
p.backoff = 0
}
dc, err := p.ch.Publish(ctx, p.exchange, e.Type, ToPublishing(e))
if err != nil {
p.dropLocked() // e.g. amqp.ErrClosed: redial on the next call
return err
}
ok, err := dc.WaitContext(ctx)
if err != nil {
return err
}
if !ok {
return errors.New("rabbit: broker nacked " + e.ID)
}
return nil
}
// Close closes the channel and the connection.
func (p *Publisher) Close() error {
p.mu.Lock()
defer p.mu.Unlock()
p.gen++
p.dropLocked()
return nil
}
// ToPublishing maps an event to an AMQP message: persistent, JSON, with the
// event id as MessageId (the consumer's dedupe key).
func ToPublishing(e domain.Event) amqp.Publishing {
return amqp.Publishing{
ContentType: "application/json",
DeliveryMode: amqp.Persistent,
MessageId: e.ID,
Type: e.Type,
Timestamp: e.OccurredAt,
Headers: amqp.Table{"aggregate_id": e.AggregateID},
Body: e.Payload,
}
}
// RoutingKeyFor documents the binding a consumer uses, e.g. "order.*".
func RoutingKeyFor(aggregate string) string { return fmt.Sprintf("%s.*", aggregate) }ایمیل تأیید سفارش با SMTP: go-mail و Templateها مهم
به زبان ساده: ایمیل تأیید از دو قالب (Template)، متن ساده و HTML، که داخل Binary قرار دارند Render میشود. کتابخانهای که MIME، Encoding و Authentication را مدیریت میکند آن را با SMTP و STARTTLS میفرستد؛ هرگز داخل درخواست Checkout ارسال نمیشود.
بدفهمی رایج: «از net/smtp استفاده کن.» سورس آن میگوید "The smtp package is frozen and is not accepting new features". پیام Multipart MIME نمیسازد و مجبور میشوید Header، Boundary و Encoding را دستی بنویسید. دوم: «HTML را با text/template Render کن.» محصولی به نام <script>alert(1)</script> آنوقت در Webmail اجرا میشود؛ html/template آن را Escape میکند و تست وجود <script> را بررسی میکند. سوم: «شکست ارسال باید سفارش را شکست دهد.» سفارش قبلاً Commit شده؛ Worker ارسال را Retry میکند و اگر خطا دائمی بود هشدار میدهد.
تعریف: mailer.OrderConfirmation(order, eventID, domain)، فایل templates/order_confirmation.txt.tmpl را با text/template و .html.tmpl را با html/template اجرا میکند. هر دو با //go:embed templates/*.tmpl بارگذاری شدهاند. Message-ID برابر <eventID@domain> میشود تا ارسال مجدد پس از Crash قابل تشخیص باشد. mailer.SMTP دور کلاینت go-mail قرار میگیرد: mail.NewClient(host, mail.WithPort(587), mail.WithTLSPortPolicy(mail.TLSMandatory), mail.WithSMTPAuth(mail.SMTPAuthPlain), mail.WithUsername(...), mail.WithPassword(...)). برای هر پیام از NewMsg، From، To، Subject، SetMessageIDWithValue، SetDate، SetBodyString(mail.TypeTextPlain, ...) و AddAlternativeString(mail.TypeTextHTML, ...) استفاده میشود و ارسال با DialAndSendWithContext(ctx, msg) است. خطای *mail.SendError با ErrorCode() از خانوادهٔ 5xx به mailer.PermanentError تبدیل و Retry متوقف میشود. سورس go-mail میگوید کد "will start with 5 on permanent errors and with 4 on a temporary error"؛ برای خطایی که از سرور نیامده 0 است. شکست Dial یا TLS هم IsTemp() == false دارد؛ پس بررسی تنها IsTemp() اشتباهاً در اختلال کوتاه شبکه از ارسال دست میکشد؛ TestOnlyServer5xxIsPermanent. README، go-mail را "a modern, feature-rich library for composing and sending mail with Go" توصیف میکند که "keeps a small dependency footprint by building primarily on the Go Standard Library and the official Go extended packages". آخرین نسخه با go.mod برابر 1.24، نسخهٔ v0.7.2 است.
Worker SMTP server (submission, port 587)
1 DialAndSendWithContext(ctx, msg) 220 smtp.example ESMTP
2 EHLO -> 250 STARTTLS, AUTH PLAIN LOGIN
3 STARTTLS (TLSMandatory) TLS handshake
4 AUTH PLAIN (only inside TLS) 235 Authentication successful
5 MAIL FROM / RCPT TO / DATA 421 4.7.0 try again later -> IsTemp: retry with backoff
6 (retry 2) ... DATA 250 OK queued -> inbox.Mark(event id)سناریوی واقعی: ارائهدهندهٔ ایمیل تراکنشی مثل Postmark، SES SMTP یا Mailgun روی Port 587؛ Mailpit یا MailHog در توسعه؛ دامنهٔ مقصد که 550 5.1.1 user unknown میدهد و دائمی است، پس Retry نکنید و هشدار بدهید؛ محدودیت نرخ ارائهدهنده با 421 که موقت است و Backoff میخواهد.
| گزینه | مزایا | هزینهها |
|---|---|---|
| go-mail روی SMTP؛ این پروژه | هر ارائهدهنده، پروتکل استاندارد و MIME درست | اتصال برای هر ارسال مگر آن را باز نگه دارید |
net/smtp | کتابخانهٔ استاندارد | Frozen و بدون سازندهٔ MIME |
| HTTP API ارائهدهنده؛ SES، Postmark، SendGrid SDK | Webhook برگشت ایمیل و Template سمت ارائهدهنده | وابستگی به فروشنده و SDK دیگر |
Mail در Laravel با Mailable از نوع ShouldQueue | آماده در Framework | فقط PHP |
راهحل / نحوهٔ استفاده: Templateها، Renderer و Sender:
Hello,
thank you for your order {{.OrderID}}.
{{range .Items}}{{.Qty}} x {{.Name}} {{.LineTotal}}
{{end}}
Subtotal: {{.Subtotal}}
{{if .HasDiscount}}Discount: -{{.Discount}}
{{end}}Tax: {{.Tax}}
Total: {{.Total}}
We will e-mail you again when it ships.// Package mailer renders the order confirmation from embedded templates and
// sends it over SMTP with github.com/wneessen/go-mail. The text part uses
// text/template; the HTML part uses html/template, which escapes product
// names (a product called "<script>" stays text).
package mailer
import (
"bytes"
"context"
"embed"
htmltpl "html/template"
"sync"
texttpl "text/template"
"academy/ecommerce-api-project/domain"
)
//go:embed templates/*.tmpl
var files embed.FS
var (
textT = texttpl.Must(texttpl.ParseFS(files, "templates/order_confirmation.txt.tmpl"))
htmlT = htmltpl.Must(htmltpl.ParseFS(files, "templates/order_confirmation.html.tmpl"))
)
// Message is a rendered mail.
type Message struct {
To, Subject, Text, HTML string
MessageID string // deterministic per event: retries reuse it
}
// Sender delivers a message. Implementations: SMTP (go-mail), Recorder (tests).
type Sender interface {
Send(ctx context.Context, m Message) error
}
type line struct {
Qty int64
Name, LineTotal string
}
type view struct {
OrderID string
Items []line
Subtotal, Discount, Tax, Total string
HasDiscount bool
}
// OrderConfirmation renders the mail for o. eventID becomes the Message-ID.
func OrderConfirmation(o domain.Order, eventID, domainName string) (Message, error) {
v := view{OrderID: o.ID, Subtotal: o.Subtotal.String(), Discount: o.Discount.String(),
Tax: o.Tax.String(), Total: o.Total.String(), HasDiscount: !o.Discount.IsZero()}
for _, it := range o.Items {
v.Items = append(v.Items, line{Qty: it.Qty, Name: it.Name, LineTotal: it.LineTotal.String()})
}
var txt, html bytes.Buffer
if err := textT.Execute(&txt, v); err != nil {
return Message{}, err
}
if err := htmlT.Execute(&html, v); err != nil {
return Message{}, err
}
return Message{To: o.Email, Subject: "Your order " + o.ID, Text: txt.String(), HTML: html.String(),
MessageID: eventID + "@" + domainName}, nil
}
// Recorder is a Sender that keeps messages in memory.
type Recorder struct {
mu sync.Mutex
sent []Message
Fail int // fail this many calls first (to exercise retries)
}
func (r *Recorder) Send(_ context.Context, m Message) error {
r.mu.Lock()
defer r.mu.Unlock()
if r.Fail > 0 {
r.Fail--
return errTemporary
}
r.sent = append(r.sent, m)
return nil
}
// Sent returns a copy of what was sent.
func (r *Recorder) Sent() []Message {
r.mu.Lock()
defer r.mu.Unlock()
return append([]Message(nil), r.sent...)
}
type tempErr struct{}
func (tempErr) Error() string { return "421 4.7.0 try again later" }
func (tempErr) Temporary() bool { return true }
var errTemporary error = tempErr{}
// LogSender writes mails to a logger instead of sending them (development).
type LogSender struct {
Log interface{ Info(string, ...any) }
}
func (l LogSender) Send(_ context.Context, m Message) error {
l.Log.Info("mail (not sent)", "to", m.To, "subject", m.Subject, "message_id", m.MessageID)
return nil
}package mailer
import (
"context"
"errors"
"github.com/wneessen/go-mail"
)
// SMTPConfig comes from the environment (see the config package).
type SMTPConfig struct {
Host, Username, Password, From string
Port int
}
// SMTP sends through one go-mail Client. DialAndSendWithContext opens a
// connection per call, which is fine for a worker sending a few mails a
// second; a high-volume sender keeps the connection open (DialWithContext +
// Send) or hands the job to an e-mail API.
type SMTP struct {
c *mail.Client
from string
}
// NewSMTP builds the client: STARTTLS is mandatory and AUTH PLAIN is used,
// which is safe only because the connection is already encrypted.
func NewSMTP(cfg SMTPConfig) (*SMTP, error) {
c, err := mail.NewClient(cfg.Host,
mail.WithPort(cfg.Port),
mail.WithTLSPortPolicy(mail.TLSMandatory),
mail.WithSMTPAuth(mail.SMTPAuthPlain),
mail.WithUsername(cfg.Username),
mail.WithPassword(cfg.Password),
)
if err != nil {
return nil, err
}
return &SMTP{c: c, from: cfg.From}, nil
}
// Send delivers m. ctx bounds the whole SMTP conversation.
func (s *SMTP) Send(ctx context.Context, m Message) error {
msg, err := build(s.from, m)
if err != nil {
return Permanent(err) // a bad address will not get better with retries
}
return classify(s.c.DialAndSendWithContext(ctx, msg))
}
// classify marks only a 5xx server reply as permanent. go-mail's ErrorCode
// "will start with 5 on permanent errors and with 4 on a temporary error",
// and is 0 when the error did not come from the server (dial, TLS, timeout):
// those must be retried, even though IsTemp() reports false for them.
func classify(err error) error {
var se *mail.SendError
if errors.As(err, &se) && se.ErrorCode() >= 500 && se.ErrorCode() < 600 {
return Permanent(err)
}
return err
}
func build(from string, m Message) (*mail.Msg, error) {
msg := mail.NewMsg()
if err := msg.From(from); err != nil {
return nil, err
}
if err := msg.To(m.To); err != nil {
return nil, err
}
msg.Subject(m.Subject)
msg.SetMessageIDWithValue(m.MessageID)
msg.SetDate()
msg.SetBodyString(mail.TypeTextPlain, m.Text)
msg.AddAlternativeString(mail.TypeTextHTML, m.HTML)
return msg, nil
}
// PermanentError marks a failure that retrying cannot fix.
type PermanentError struct{ Err error }
func (e *PermanentError) Error() string { return "permanent: " + e.Err.Error() }
func (e *PermanentError) Unwrap() error { return e.Err }
// Permanent wraps err.
func Permanent(err error) error { return &PermanentError{Err: err} }Workerهای پسزمینه: کار ناهمگام با Retry، سبد رهاشده و مهلت آزادسازی موجودی حیاتی
به زبان ساده: بعضی کارها بعداً انجام میشوند: ایمیل فرستادن، پس دادن موجودی که سفارش پرداختنشده زیادی نگه داشته و یادآوری سبدی که مشتری رها کرده است. هر کدام تابع کوچکی است که با Ticker یا رویداد اجرا میشود، اجرای دوبارهاش ضرر ندارد و هنگام خاموشی تمیز متوقف میشود.
بدفهمی رایج: «یک go sendMail() در Handler برای ناهمگامی کافی است.» Goroutine با فرایند میمیرد، Retry و سابقه ندارد؛ Outbox همراه Worker از Restart جان سالم میبرد. دوم: «Job آزادسازی میتواند UPDATE orders SET status = 'cancelled' WHERE expires_at < now() بزند.» پرداخت ممکن است در همان میلیثانیه برسد؛ Job باید هر سفارش را دوباره بخواند، بررسی کند هنوز created است و با Version بنویسد تا پرداخت یا لغو، فقط یکی، برنده شود. سوم: «تا ابد Retry کن.» شکست دائمی مثل آدرس بد باید متوقف و هشدار داده شود؛ شکست موقت، عقبنشینی نمایی (Exponential backoff) با سقف و Jitter میخواهد.
تعریف: worker.OrderMail.Handle یک Handler در Bus است: ابتدا Inbox.Has و عبور از کار انجامشده، سپس خواندن سفارش، Render، اجرای Retry تا 3 تلاش با Backoff{Base: 200ms, Max: 5s} و Full jitter یعنی rand.N(min(Max, Base<<n))، و پس از موفقیت Inbox.Mark. Crash بین ارسال و Mark به ارسال مجدد میرسد، نه گم شدن ایمیل. خطای دائمی Log و انجامشده علامت میخورد؛ خطای موقت پس از آخرین تلاش برمیگردد تا Relay، Backoff کند و دوباره تحویل دهد. Housekeeping.ReleaseExpired سفارشهای created با expires_at < now را فهرست میکند؛ مهلت پیشفرض 15 دقیقه با ECOM_STOCK_HOLD است. هر سفارش در Transaction کوتاه خودش از همان cancelInTx لغو مشتری میگذرد و موجودی دقیقاً یک بار آزاد میشود. اگر Capture بعداً برسد، ApplyPayment سفارش را زنده نمیکند؛ پرداخت refund_pending و رویداد payment.refund_requested تولید میشود. Housekeeping.RemindAbandoned سبد مشتریانی را پیدا میکند که به اندازهٔ AbandonedAfter، یعنی 24 ساعت، بیفعالیت و بدون یادآوری ماندهاند؛ علامتگذاری و نوشتن cart.abandoned در یک Transaction است. FOR UPDATE SKIP LOCKED به دو Worker اجازه میدهد پیمایش را تقسیم کنند. worker.RunJobs هر Job را روی Ticker خودش اجرا میکند و وقتی Context تمام شد و همهٔ اجراهای جاری پایان یافتند، برمیگردد.
t Order ord_1 (hold 15 min) Stock-release job PSP webhook
1 10:00 created v1, reserved 3
2 10:16 Expired(now): [ord_1]
3 10:16 re-read: created, expired -> cancel v2, release 3
4 10:16 succeeded for ord_1
5 10:16 order cancelled -> payment refund_pending
6 10:17 Expired(now): [] (status is cancelled) -> nothing
Reverse order: capture first -> paid v2; the job's re-read sees paid and skips; stock stays reserved for shipping.سناریوی واقعی: مشتری صفحهٔ PSP را باز میکند و میرود؛ موجودی پس از 15 دقیقه برمیگردد. انتقال بانکی پس از مهلت تسویه میشود؛ Refund درخواست میشود یا باید برای این روش پرداخت مهلت بلندتری گذاشت. یادآوری باید یک بار برود، نه هر دقیقه. استقرار وسط Batch هم باید اجازه دهد Job سفارش جاری را تمام کند و بعد خارج شود.
| Job | محرک | دلیل Idempotent بودن | محافظ همزمانی |
|---|---|---|---|
| ایمیل تأیید | order.placed | Inbox هر Consumer، Message-ID برابر Event id | یک Relay |
| مهلت آزادسازی موجودی (Stock release timeout) | هر دقیقه | بررسی مجدد وضعیت و CAS روی Version | Version روی orders |
| یادآوری سبد رهاشده (Abandoned cart) | هر دقیقه | reminded_at در همان Transaction رویداد تنظیم میشود | FOR UPDATE SKIP LOCKED |
| Outbox relay | هر ثانیه | published_at و حذف تکرار توسط Consumer | اجارهٔ رهبر (Leader lease)، pgstore.Lease و APP_ROLE |
| بازپرداخت Capture دیررس | payment.refund_requested | کلید Refund مشتق از پرداخت | سیستم پرداخت |
راهحل / نحوهٔ استفاده:
package worker
import (
"context"
"errors"
"log/slog"
"sync"
"time"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/mailer"
"academy/ecommerce-api-project/store"
)
// OrderMail sends the confirmation for order.placed, at least once and in
// practice once: the inbox skips redeliveries, and the Message-ID is the
// event id so a duplicate after a crash is recognisable.
type OrderMail struct {
Inbox store.Inbox
LoadOrder func(ctx context.Context, id string) (domain.Order, error)
Sender mailer.Sender
Backoff Backoff
Domain string // for Message-ID, e.g. "shop.example"
Log *slog.Logger
}
const mailConsumer = "order-confirmation-mail"
// Handle is a bus.Handler.
func (w OrderMail) Handle(ctx context.Context, e domain.Event) error {
done, err := w.Inbox.Has(ctx, mailConsumer, e.ID)
if err != nil || done {
return err
}
o, err := w.LoadOrder(ctx, e.AggregateID)
if err != nil {
return err
}
msg, err := mailer.OrderConfirmation(o, e.ID, w.Domain)
if err != nil {
return err
}
err = Retry(ctx, w.Backoff, func(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
return w.Sender.Send(ctx, msg)
})
var pe *mailer.PermanentError
if errors.As(err, &pe) {
w.Log.ErrorContext(ctx, "confirmation mail rejected", "order", o.ID, "err", err)
return w.Inbox.Mark(ctx, mailConsumer, e.ID) // do not redeliver forever: alert instead
}
if err != nil {
return err // the relay backs off and redelivers
}
return w.Inbox.Mark(ctx, mailConsumer, e.ID)
}
// Job is one periodic task.
type Job struct {
Name string
Every time.Duration
Run func(ctx context.Context) (int, error)
}
// RunJobs starts every job on its own ticker and returns when ctx is done
// and every job has finished its current run (graceful shutdown).
func RunJobs(ctx context.Context, log *slog.Logger, jobs ...Job) {
var wg sync.WaitGroup
for _, j := range jobs {
wg.Add(1)
go func() {
defer wg.Done()
t := time.NewTicker(j.Every)
defer t.Stop()
for {
if n, err := j.Run(ctx); err != nil && ctx.Err() == nil {
log.ErrorContext(ctx, "job failed", "job", j.Name, "err", err)
} else if n > 0 {
log.InfoContext(ctx, "job done", "job", j.Name, "items", n)
}
select {
case <-ctx.Done():
return
case <-t.C:
}
}
}()
}
wg.Wait()
}// Package worker holds the background side of the shop: the event handlers
// (order confirmation mail) and the periodic jobs (outbox relay, stock
// release timeout, abandoned-cart reminders), all stopped by one context.
package worker
import (
"context"
"errors"
"math/rand/v2"
"time"
"academy/ecommerce-api-project/mailer"
)
// Backoff is capped exponential backoff with full jitter: attempt n waits a
// random duration in [0, min(Max, Base*2^n)).
type Backoff struct {
Base, Max time.Duration
Attempts int
}
func (b Backoff) delay(n int) time.Duration {
d := min(b.Max, b.Base<<min(n, 20))
if d <= 0 {
return 0
}
return rand.N(d)
}
// Sleep waits d or until ctx is done. Tests replace it.
var Sleep = func(ctx context.Context, d time.Duration) error {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
return nil
}
}
// Retry runs fn up to b.Attempts times. A *mailer.PermanentError or a
// cancelled ctx stops it at once.
func Retry(ctx context.Context, b Backoff, fn func(context.Context) error) error {
var err error
for n := range max(b.Attempts, 1) {
if err = fn(ctx); err == nil {
return nil
}
var pe *mailer.PermanentError
if errors.As(err, &pe) || n == b.Attempts-1 {
return err
}
if serr := Sleep(ctx, b.delay(n)); serr != nil {
return errors.Join(err, serr)
}
}
return err
}Lease که Relay و Jobها را روی یک Replica نگه میدارد، هم در حافظه و هم با Advisory lock در PostgreSQL:
package worker
import (
"context"
"log/slog"
"sync"
"time"
)
// Lease is leadership for the background side: only the holder runs the
// outbox relay and the jobs, so N worker replicas give one relay (order kept,
// no duplicate scans) and a hot standby. pgstore.Lease implements it with
// pg_try_advisory_lock on a dedicated connection; MemLease is for one process.
type Lease interface {
// TryAcquire returns ok=false at once if someone else holds the lease.
// lost is closed if the lease is lost while held (connection dropped);
// release gives it up.
TryAcquire(ctx context.Context) (release func(), lost <-chan struct{}, ok bool, err error)
}
// RunWithLease retries TryAcquire every retry until it holds the lease, then
// runs the jobs until ctx is done or the lease is lost, then releases it.
// After a loss it goes back to waiting.
func RunWithLease(ctx context.Context, lease Lease, retry time.Duration, log *slog.Logger, jobs ...Job) {
for ctx.Err() == nil {
release, lost, ok, err := lease.TryAcquire(ctx)
if err != nil && ctx.Err() == nil {
log.ErrorContext(ctx, "lease", "err", err)
}
if ok {
log.InfoContext(ctx, "lease acquired: running background jobs")
jctx, cancel := context.WithCancel(ctx)
go func() {
select {
case <-lost:
log.WarnContext(ctx, "lease lost: stopping background jobs")
cancel()
case <-jctx.Done():
}
}()
RunJobs(jctx, log, jobs...)
cancel()
release()
continue
}
t := time.NewTimer(retry)
select {
case <-ctx.Done():
t.Stop()
case <-t.C:
}
}
}
// MemLease is an in-process Lease (tests, a single binary with APP_ROLE=all).
type MemLease struct {
mu sync.Mutex
held bool
}
func NewMemLease() *MemLease { return &MemLease{} }
func (l *MemLease) TryAcquire(context.Context) (func(), <-chan struct{}, bool, error) {
l.mu.Lock()
defer l.mu.Unlock()
if l.held {
return nil, nil, false, nil
}
l.held = true
return func() { l.mu.Lock(); l.held = false; l.mu.Unlock() }, make(chan struct{}), true, nil
}package pgstore
import (
"context"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
// Lease is a leader lease on a PostgreSQL session-level advisory lock. The
// lock lives as long as the session, so it is taken on a connection checked
// out of the pool and held; if that connection dies, PostgreSQL releases the
// lock (another replica can take it) and lost is closed here.
type Lease struct {
Pool *pgxpool.Pool
Key int64 // e.g. 7340001, one per database
Check time.Duration // how often the held connection is pinged (default 5s)
}
func (l Lease) TryAcquire(ctx context.Context) (func(), <-chan struct{}, bool, error) {
conn, err := l.Pool.Acquire(ctx)
if err != nil {
return nil, nil, false, err
}
var ok bool
if err := conn.QueryRow(ctx, `SELECT pg_try_advisory_lock($1)`, l.Key).Scan(&ok); err != nil || !ok {
conn.Release()
return nil, nil, false, err
}
lost := make(chan struct{})
stop := make(chan struct{})
every := l.Check
if every <= 0 {
every = 5 * time.Second
}
go func() {
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-stop:
return
case <-t.C:
pctx, cancel := context.WithTimeout(context.Background(), every)
err := conn.Ping(pctx)
cancel()
if err != nil {
close(lost)
return
}
}
}
}()
release := func() {
close(stop)
_, _ = conn.Exec(context.Background(), `SELECT pg_advisory_unlock($1)`, l.Key)
conn.Release()
}
return release, lost, true, nil
}package service
import (
"context"
"errors"
"time"
"academy/ecommerce-api-project/domain"
)
type timeT = time.Time
// Housekeeping holds the background jobs the worker runs on a ticker.
type Housekeeping struct {
Deps
AbandonedAfter time.Duration // e.g. 24h
}
// ReleaseExpired cancels unpaid orders whose stock hold ran out. Each order
// gets its own short transaction, re-reads the order and re-checks the
// status, so an order paid a millisecond ago is left alone.
func (h Housekeeping) ReleaseExpired(ctx context.Context) (int, error) {
now := h.Now()
var ids []string
err := h.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
os, err := tx.Orders().Expired(ctx, now, 100)
for _, o := range os {
ids = append(ids, o.ID)
}
return err
})
if err != nil {
return 0, err
}
n := 0
for _, id := range ids {
err := retryConflict(func() error {
return h.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
o, err := tx.Orders().Get(ctx, id)
if err != nil {
return err
}
if o.Status != domain.OrderCreated || !o.ExpiresAt.Before(now) {
return errSkip
}
return cancelInTx(ctx, tx, &o, now, "stock hold expired")
})
})
switch {
case err == nil:
n++
case errors.Is(err, errSkip):
default:
return n, err
}
}
return n, nil
}
var errSkip = errors.New("skip")
// RemindAbandoned writes one cart.abandoned event per customer cart idle
// for AbandonedAfter and marks the cart reminded, in the same transaction.
func (h Housekeeping) RemindAbandoned(ctx context.Context) (int, error) {
now := h.Now()
n := 0
err := h.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
cs, err := tx.Carts().Abandoned(ctx, now.Add(-h.AbandonedAfter), 100)
if err != nil {
return err
}
for _, c := range cs {
c.RemindedAt = &now
if err := tx.Carts().Save(ctx, &c); err != nil {
return err
}
ev := domain.NewEvent(domain.EvCartAbandoned, c.ID, c.UpdatedAt.Unix(), now,
map[string]any{"cart_id": c.ID, "user_id": c.UserID, "email": c.Email})
if err := tx.Outbox().Add(ctx, ev); err != nil {
return err
}
n++
}
return nil
})
return n, err
}Webhook پرداخت: از رویداد PSP تا وضعیت سفارش مهم
به زبان ساده: ارائهدهندهٔ خدمات پرداخت (PSP) با فراخوانی Webhook به شما میگوید پرداخت موفق شده است. امضای Body خام را بررسی کنید، رویداد را از ماشین حالت عبور دهید و سریع 2xx بدهید؛ برای تکراریها هم همینطور.
بدفهمی رایج: «Redirect از صفحهٔ پرداخت یعنی پرداخت شده.» مرورگر میتواند قبل از Redirect بسته شود و Redirect هم قابل جعل است؛ فقط رویداد امضاشدهٔ سروربهسرور اعتبار دارد. دوم: «برای رویداد سفارشی که نمیشناسیم 500 بده.» PSP روزها Retry میکند؛ چیزی را که مربوط به شما نیست تأیید دریافت و Log کنید.
تعریف: POST /v1/webhooks/psp با MaxBytesReader Body را محدود میخواند، X-Signature: sha256=<hex> را بهعنوان HMAC-SHA256 روی Body خام با hmac.Equal و زمان ثابت بررسی میکند، Decode میکند و Orders.ApplyPayment را صدا میزند. این متد هر چیزی جز payment_intent.succeeded را نادیده میگیرد؛ اگر پرداخت قبلاً succeeded باشد تکرار را نادیده میگیرد؛ مبلغ متفاوت از Intent را با 422 و هشدار رد میکند؛ created → paid را با payment.captured اعمال میکند یا برای سفارش لغوشده refund_pending ثبت میکند. Header واقعی Stripe یعنی Stripe-Signature با Timestamp و پنجرهٔ Replay، ترتیب رویداد و Reconciliation در Payment Processing Architecture آمده است. Stripe دربارهٔ PaymentIntent با succeeded میگوید: "you can confidently fulfill the order".
PSP API Result
1 POST evt_1 succeeded, valid signature verify -> ApplyPayment -> paid v2 204
2 POST evt_1 again (retry) verify -> already succeeded -> no-op 204
3 POST forged body, signature sha256=00 hmac.Equal false 400
4 POST evt for unknown order ErrNotFound -> ack 204, logged
5 POST evt amount 1 instead of 7702 ErrAmountMismatch 422, alertسناریوی واقعی: PSP هر رویداد را حداقل یک بار میرساند؛ مهاجم برای سفارش پرداختنشدهٔ خودش «succeeded» میفرستد؛ تنظیم Partial capture مبلغ متفاوت میدهد؛ یا Webhook پیش از Redirect مرورگر میرسد.
| بررسی | بدون آن | اینجا |
|---|---|---|
| امضای Body خام | هر کسی سفارش را پرداختشده میکند | HMAC-SHA256 با hmac.Equal |
| حذف تکرار (Dedupe) | دو رویداد Paid و دو ایمیل | وضعیت پرداخت و Event id قطعی |
| مبلغ برابر Intent | پذیرش پرداخت کمتر | ErrAmountMismatch |
| ماشین حالت | رویداد دیررس وضعیت نهایی را بازنویسی میکند | بدون یال، بدون تغییر |
| 2xx سریع | Retry در PSP و انباشت تکرارها | 204 پس از یک Transaction کوتاه |
راهحل / نحوهٔ استفاده: pspWebhook و validSignature در فایل Handlerها در ادامهاند؛ ApplyPayment در service/orders.go بالاست.
Swagger/OpenAPI: Annotationهای swag یا oapi-codegen مهم
به زبان ساده: قرارداد API فایلی است که کلاینت آن را میخواند و از آن کد تولید میکند. یا اول Go مینویسید و فایل را از Comment با swag میسازید، یا اول فایل را مینویسید و Go را با oapi-codegen تولید میکنید. در هر دو روش، ناسازگاری فایل و کد باید تست را شکست دهد.
بدفهمی رایج: «swag به من OpenAPI 3 میدهد.» README آن میگوید: "Swag converts Go annotations to Swagger Documentation 2.0". برای 3.x باید تبدیل کنید یا ابزار Spec-first به کار ببرید. دوم: «مستندات تولیدشده همیشه درست است.» Comment هم مثل مستند دستی از کد فاصله میگیرد؛ فقط تست در برابر Routeهای واقعی این فاصله را آشکار میکند.
تعریف: Handlerها Commentهای اعلانی swag دارند: @Summary، @Tags، @Security BearerAuth، @Param Idempotency-Key header string true "..."، @Success 201 {object} OrderResponse، @Failure 409 {object} Problem و @Router /v1/orders [post]. پس swag init -g cmd/api/main.go بستهٔ docs/ با Swagger 2.0 میساخت که http-swagger ارائهاش میکرد؛ این پروژه آن را نساخته است. قرارداد ارائهشده اینجا httpapi/openapi.json است؛ دستی نگهداری میشود، OpenAPI 3.1.0 است، Embed شده و از GET /openapi.json میآید. TestEveryRouteIsInTheOpenAPIDocument روی API.Routes() حرکت میکند و برای هر Method و Path غایب شکست میخورد. جایگزین قراردادمحور (Spec-first)، oapi-codegen است: "to convert OpenAPI specifications to Go code, be it server-side implementations, API clients, or simply HTTP models". هدف std-http-server برای net/http دارد؛ Interface تولید میشود و Handler آن را پیاده میکند. جدول فعلی README را در نظر بگیرید: سرور تولیدشده به github.com/oapi-codegen/runtime وابسته است، "which requires Go 1.26". ماژول Pinشده روی Go 1.24 مثل این پروژه باید نسخهٔ قدیمیتر oapi-codegen بگیرد یا خط go را تغییر دهد. مقایسهٔ عمیق swag، oapi-codegen و ogen در A REST API in Go است.
Workflow Source of truth Generate Drift check
1 code-first (swag) Go comments swag init -> docs/swagger.json test routes vs generated file
2 spec-first (oapi) openapi.yaml oapi-codegen -> types + interface compiler: unimplemented method fails
3 this project openapi.json + routes (none) TestEveryRouteIsInTheOpenAPIDocumentسناریوی واقعی: تیم موبایل کلاینت Swift/Kotlin را از قرارداد میسازد؛ شریک تجاری Sandbox و مستندات میخواهد؛ API gateway درخواست را با Schema اعتبارسنجی میکند؛ و تغییر ناسازگار در Review دیده میشود چون Diff، openapi.json را هم تغییر داده است.
| ابزار | جهت | خروجی | نسخهٔ OpenAPI |
|---|---|---|---|
| swaggo/swag | کد → قرارداد | Swagger JSON/YAML و بستهٔ Go به نام docs | 2.0 |
| oapi-codegen | قرارداد → کد | Interface سرور، Model و Client | 3.0, 3.1 طبق README |
| ogen | قرارداد → کد | سرور و کلاینت نوعدار | 3.x |
| دستی همراه تست؛ اینجا | هر دو با بررسی تطابق | openapi.json | 3.1.0 |
راهحل / نحوهٔ استفاده: Handlerها همراه Annotation و جدول Routeهایی که تست پیمایش میکند:
package httpapi
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/money"
"academy/ecommerce-api-project/service"
)
const maxBody = 1 << 20
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
// readBody reads at most maxBody bytes and decodes strictly.
func readBody(w http.ResponseWriter, r *http.Request, dst any) ([]byte, error) {
raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBody))
if err != nil {
return nil, &service.ValidationError{Fields: []service.FieldError{{Field: "body", Message: "too large or unreadable"}}}
}
if len(raw) == 0 {
raw = []byte("{}")
}
dec := json.NewDecoder(strings.NewReader(string(raw)))
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
return nil, &service.ValidationError{Fields: []service.FieldError{{Field: "body", Message: err.Error()}}}
}
return raw, nil
}
func pathID(r *http.Request, name string) (int64, error) {
n, err := strconv.ParseInt(r.PathValue(name), 10, 64)
if err != nil || n <= 0 {
return 0, &service.ValidationError{Fields: []service.FieldError{{Field: name, Message: "positive integer"}}}
}
return n, nil
}
// listProducts godoc
//
// @Summary List the catalogue (keyset pagination)
// @Tags catalogue
// @Param q query string false "search in name and SKU"
// @Param category query int false "category id"
// @Param min_price query int false "minor units"
// @Param max_price query int false "minor units"
// @Param sort query string false "newest | price | -price | name"
// @Param limit query int false "1..100, default 20"
// @Param cursor query string false "next_cursor of the previous page"
// @Success 200 {object} ProductPage
// @Failure 422 {object} Problem
// @Router /v1/products [get]
func (a *API) listProducts(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
page, err := a.Catalog.List(r.Context(), service.ListParams{Search: q.Get("q"), Category: q.Get("category"),
MinPrice: q.Get("min_price"), MaxPrice: q.Get("max_price"), Sort: q.Get("sort"), Limit: q.Get("limit"),
Cursor: q.Get("cursor")})
if err != nil {
a.fail(w, r, err)
return
}
out := ProductPage{Items: []ProductResponse{}, NextCursor: page.NextCursor}
for _, p := range page.Items {
out.Items = append(out.Items, toProduct(p))
}
if page.NextCursor != "" {
q.Set("cursor", page.NextCursor)
w.Header().Set("Link", `<`+(&url.URL{Path: r.URL.Path, RawQuery: q.Encode()}).String()+`>; rel="next"`)
}
writeJSON(w, http.StatusOK, out)
}
// getProduct godoc
//
// @Summary One product; ETag carries the version
// @Tags catalogue
// @Param id path int true "product id"
// @Success 200 {object} ProductResponse
// @Failure 404 {object} Problem
// @Router /v1/products/{id} [get]
func (a *API) getProduct(w http.ResponseWriter, r *http.Request) {
id, err := pathID(r, "id")
if err == nil {
var p domain.Product
if p, err = a.Catalog.Get(r.Context(), id); err == nil {
w.Header().Set("ETag", strconv.Quote(strconv.FormatInt(p.Version, 10)))
writeJSON(w, http.StatusOK, toProduct(p))
return
}
}
a.fail(w, r, err)
}
// createProduct godoc
//
// @Summary Create a product (admin)
// @Tags admin
// @Security BearerAuth
// @Param body body CreateProductRequest true "product"
// @Success 201 {object} ProductResponse
// @Failure 401,403 {object} Problem
// @Failure 422 {object} Problem
// @Router /v1/admin/products [post]
func (a *API) createProduct(w http.ResponseWriter, r *http.Request) {
var in CreateProductRequest
if _, err := readBody(w, r, &in); err != nil {
a.fail(w, r, err)
return
}
who, _ := PrincipalFrom(r.Context())
p, err := a.Catalog.CreateProduct(r.Context(), who, service.ProductInput{SKU: in.SKU, Name: in.Name,
CategoryID: in.CategoryID, Price: in.Price, TaxClass: in.TaxClass, Stock: in.Stock})
if err != nil {
a.fail(w, r, err)
return
}
w.Header().Set("Location", "/v1/products/"+strconv.FormatInt(p.ID, 10))
writeJSON(w, http.StatusCreated, toProduct(p))
}
// updatePrice godoc
//
// @Summary Change a price; If-Match must carry the ETag (optimistic lock)
// @Tags admin
// @Security BearerAuth
// @Param id path int true "product id"
// @Param If-Match header string true "ETag from GET"
// @Param body body PriceRequest true "new price in minor units"
// @Success 200 {object} ProductResponse
// @Failure 412,428 {object} Problem
// @Router /v1/admin/products/{id}/price [put]
func (a *API) updatePrice(w http.ResponseWriter, r *http.Request) {
id, err := pathID(r, "id")
if err != nil {
a.fail(w, r, err)
return
}
version, err := strconv.ParseInt(strings.Trim(r.Header.Get("If-Match"), `"`), 10, 64)
if err != nil {
writeProblem(w, r, Problem{Title: "Precondition Required", Status: 428, Detail: "send If-Match with the ETag"})
return
}
var in PriceRequest
if _, err := readBody(w, r, &in); err != nil {
a.fail(w, r, err)
return
}
who, _ := PrincipalFrom(r.Context())
p, err := a.Catalog.UpdatePrice(r.Context(), who, id, in.Price, version)
if err != nil {
a.fail(w, r, err)
return
}
w.Header().Set("ETag", strconv.Quote(strconv.FormatInt(p.Version, 10)))
writeJSON(w, http.StatusOK, toProduct(p))
}
const cartCookie = "cart_id"
func (a *API) owner(r *http.Request) service.Owner {
o := service.Owner{}
o.Principal, _ = PrincipalFrom(r.Context())
if c, err := r.Cookie(cartCookie); err == nil {
o.GuestID = c.Value
}
return o
}
func setCartCookie(w http.ResponseWriter, id string, maxAge int) {
http.SetCookie(w, &http.Cookie{Name: cartCookie, Value: id, Path: "/", MaxAge: maxAge,
HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode})
}
// getCart godoc
//
// @Summary The caller's cart (customer, or guest via the cart_id cookie)
// @Tags cart
// @Success 200 {object} CartResponse
// @Router /v1/cart [get]
func (a *API) getCart(w http.ResponseWriter, r *http.Request) {
c, err := a.Carts.Get(r.Context(), a.owner(r))
if err != nil {
a.fail(w, r, err)
return
}
writeJSON(w, http.StatusOK, toCart(c))
}
// putCartItem godoc
//
// @Summary Set the quantity of a product in the cart (0 removes it)
// @Tags cart
// @Param productID path int true "product id"
// @Param body body CartItemRequest true "quantity 0..10"
// @Success 200 {object} CartResponse
// @Failure 404,422 {object} Problem
// @Router /v1/cart/items/{productID} [put]
func (a *API) putCartItem(w http.ResponseWriter, r *http.Request) {
pid, err := pathID(r, "productID")
var in CartItemRequest
if err == nil {
_, err = readBody(w, r, &in)
}
if err != nil {
a.fail(w, r, err)
return
}
o := a.owner(r)
c, err := a.Carts.SetItem(r.Context(), o, pid, in.Qty)
if err != nil {
a.fail(w, r, err)
return
}
if o.Principal.UserID == 0 && o.GuestID != c.ID {
setCartCookie(w, c.ID, 30*24*3600)
}
writeJSON(w, http.StatusOK, toCart(c))
}
// mergeCart godoc
//
// @Summary Merge the guest cart (cookie) into the customer's cart after login
// @Tags cart
// @Security BearerAuth
// @Success 200 {object} CartResponse
// @Router /v1/cart/merge [post]
func (a *API) mergeCart(w http.ResponseWriter, r *http.Request) {
o := a.owner(r)
c, err := a.Carts.MergeOnLogin(r.Context(), o.GuestID, o.Principal)
if err != nil {
a.fail(w, r, err)
return
}
setCartCookie(w, "", -1)
writeJSON(w, http.StatusOK, toCart(c))
}
// placeOrder godoc
//
// @Summary Place an order from the cart (idempotent)
// @Tags orders
// @Security BearerAuth
// @Param Idempotency-Key header string true "8..255 chars, a UUID per checkout attempt"
// @Param body body PlaceOrderRequest false "optional discount code"
// @Success 201 {object} OrderResponse
// @Failure 400,401 {object} Problem
// @Failure 409 {object} Problem "out of stock, or same key still in flight"
// @Failure 422 {object} Problem "validation, empty cart, key reused with another body"
// @Router /v1/orders [post]
func (a *API) placeOrder(w http.ResponseWriter, r *http.Request) {
key := r.Header.Get("Idempotency-Key")
if key == "" {
writeProblem(w, r, Problem{Type: problemBase + "idempotency-key-missing", Title: "Idempotency-Key header is required", Status: 400})
return
}
var in PlaceOrderRequest
raw, err := readBody(w, r, &in)
if err != nil {
a.fail(w, r, err)
return
}
sum := sha256.Sum256(raw)
who, _ := PrincipalFrom(r.Context())
res, err := a.Checkout.PlaceOrder(r.Context(), service.PlaceOrderInput{Who: who, IdempotencyKey: key,
Fingerprint: hex.EncodeToString(sum[:]), DiscountCode: in.DiscountCode})
if err != nil {
a.fail(w, r, err)
return
}
if res.Replayed {
w.Header().Set("Idempotent-Replayed", "true")
}
w.Header().Set("Location", "/v1/orders/"+res.Order.ID)
writeJSON(w, http.StatusCreated, toOrder(res.Order, &res.Payment))
}
// getOrder godoc
//
// @Summary One order (owner or admin)
// @Tags orders
// @Security BearerAuth
// @Param id path string true "order id"
// @Success 200 {object} OrderResponse
// @Failure 404 {object} Problem
// @Router /v1/orders/{id} [get]
func (a *API) getOrder(w http.ResponseWriter, r *http.Request) {
who, _ := PrincipalFrom(r.Context())
o, err := a.Orders.Get(r.Context(), who, r.PathValue("id"))
if err != nil {
a.fail(w, r, err)
return
}
writeJSON(w, http.StatusOK, toOrder(o, nil))
}
// listOrders godoc
//
// @Summary The caller's latest orders
// @Tags orders
// @Security BearerAuth
// @Success 200 {array} OrderResponse
// @Router /v1/orders [get]
func (a *API) listOrders(w http.ResponseWriter, r *http.Request) {
who, _ := PrincipalFrom(r.Context())
os, err := a.Orders.List(r.Context(), who)
if err != nil {
a.fail(w, r, err)
return
}
out := []OrderResponse{}
for _, o := range os {
out = append(out, toOrder(o, nil))
}
writeJSON(w, http.StatusOK, out)
}
// cancelOrder godoc
//
// @Summary Cancel an unpaid order and release its stock
// @Tags orders
// @Security BearerAuth
// @Param id path string true "order id"
// @Success 200 {object} OrderResponse
// @Failure 404 {object} Problem
// @Failure 409 {object} Problem "already paid: ask for a refund"
// @Router /v1/orders/{id}/cancel [post]
func (a *API) cancelOrder(w http.ResponseWriter, r *http.Request) {
who, _ := PrincipalFrom(r.Context())
o, err := a.Orders.Cancel(r.Context(), who, r.PathValue("id"))
if err != nil {
a.fail(w, r, err)
return
}
writeJSON(w, http.StatusOK, toOrder(o, nil))
}
// fulfilOrder godoc
//
// @Summary Mark a paid order as shipped (admin)
// @Tags admin
// @Security BearerAuth
// @Param id path string true "order id"
// @Success 200 {object} OrderResponse
// @Failure 409 {object} Problem
// @Router /v1/admin/orders/{id}/fulfil [post]
func (a *API) fulfilOrder(w http.ResponseWriter, r *http.Request) {
who, _ := PrincipalFrom(r.Context())
o, err := a.Orders.Fulfil(r.Context(), who, r.PathValue("id"))
if err != nil {
a.fail(w, r, err)
return
}
writeJSON(w, http.StatusOK, toOrder(o, nil))
}
// pspWebhook godoc
//
// @Summary Payment provider events (HMAC-SHA256 signed body)
// @Tags payments
// @Param X-Signature header string true "sha256=<hex hmac of the raw body>"
// @Success 204
// @Failure 400 {object} Problem
// @Router /v1/webhooks/psp [post]
func (a *API) pspWebhook(w http.ResponseWriter, r *http.Request) {
raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBody))
if err != nil || !a.validSignature(raw, r.Header.Get("X-Signature")) {
writeProblem(w, r, Problem{Title: "Bad signature", Status: 400})
return
}
var ev PSPWebhook
if err := json.Unmarshal(raw, &ev); err != nil {
writeProblem(w, r, Problem{Title: "Bad body", Status: 400})
return
}
_, err = a.Orders.ApplyPayment(r.Context(), service.PSPEvent{EventID: ev.ID, Type: ev.Type, OrderID: ev.Data.OrderID,
ProviderRef: ev.Data.ProviderRef, Amount: money.New(ev.Data.Amount, money.Currency(strings.ToUpper(ev.Data.Currency)))})
if errors.Is(err, domain.ErrNotFound) {
err = nil // not ours (or deleted): ack so the PSP stops retrying
}
if err != nil {
a.fail(w, r, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (a *API) validSignature(body []byte, header string) bool {
got, ok := strings.CutPrefix(header, "sha256=")
if !ok || len(a.WebhookSecret) == 0 {
return false
}
want := hmac.New(sha256.New, a.WebhookSecret)
want.Write(body)
sig, err := hex.DecodeString(got)
return err == nil && hmac.Equal(sig, want.Sum(nil))
}// Package httpapi is the HTTP edge: Go 1.22 ServeMux patterns, DTOs, RFC
// 9457 problems, authentication, per-route authorization, rate limiting and
// security headers. Handlers carry swag annotations; openapi.json is the
// served contract and a test keeps the two in step.
package httpapi
import (
_ "embed"
"log/slog"
"net/http"
"academy/ecommerce-api-project/service"
)
//go:embed openapi.json
var openapiJSON []byte
// API holds the services the handlers call.
type API struct {
Catalog service.Catalog
Carts service.Carts
Checkout service.Checkout
Orders service.Orders
Auth Authenticator
Limiter *IPLimiter
WebhookSecret []byte
Ready func() error // database ping for /readyz
Log *slog.Logger
}
// Route is one line of the routes table.
type Route struct {
Pattern string
Handler http.HandlerFunc
}
// Routes is the whole API surface in one place.
func (a *API) Routes() []Route {
return []Route{
{"GET /v1/products", a.listProducts},
{"GET /v1/products/{id}", a.getProduct},
{"POST /v1/admin/products", admin(a.createProduct)},
{"PUT /v1/admin/products/{id}/price", admin(a.updatePrice)},
{"GET /v1/cart", a.getCart},
{"PUT /v1/cart/items/{productID}", a.putCartItem},
{"POST /v1/cart/merge", customer(a.mergeCart)},
{"POST /v1/orders", customer(a.placeOrder)},
{"GET /v1/orders", customer(a.listOrders)},
{"GET /v1/orders/{id}", customer(a.getOrder)},
{"POST /v1/orders/{id}/cancel", customer(a.cancelOrder)},
{"POST /v1/admin/orders/{id}/fulfil", admin(a.fulfilOrder)},
{"POST /v1/webhooks/psp", a.pspWebhook},
{"GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) }},
{"GET /readyz", a.readyz},
{"GET /openapi.json", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(openapiJSON)
}},
}
}
func (a *API) readyz(w http.ResponseWriter, r *http.Request) {
if a.Ready != nil {
if err := a.Ready(); err != nil {
writeProblem(w, r, Problem{Title: "Not ready", Status: 503, Detail: "database unreachable"})
return
}
}
w.WriteHeader(http.StatusNoContent)
}
// Handler builds the mux and wraps it, outermost first.
func (a *API) Handler() http.Handler {
if a.Log == nil {
a.Log = slog.New(slog.DiscardHandler)
}
if a.Auth == nil {
a.Auth = StaticTokens{}
}
mux := http.NewServeMux()
for _, rt := range a.Routes() {
mux.HandleFunc(rt.Pattern, rt.Handler)
}
return chain(mux, requestID, a.logRequests, a.recoverer, securityHeaders, a.rateLimit, a.authenticate)
}محدودسازی نرخ و Headerهای امنیتی مهم
به زبان ساده: سرعت درخواست هر کلاینت را محدود کنید تا اسکریپت نتواند کارت سرقتی را آزمایش کند، کاتالوگ را Scrape کند یا با Checkout جعلی موجودی را تمام کند. چند Header پاسخ هم لازم است تا مرورگر از JSON شما استفادهٔ ناامن نکند.
بدفهمی رایج: «محدودسازی نرخ (Rate limiting) کار Gateway است.» معمولاً لایهٔ جلویی همین کار را میکند، اما برنامه اطلاعاتی دارد که Gateway ندارد؛ مثل شناسهٔ مشتری و اینکه کدام Endpoint سفارش ثبت میکند. وقتی Gateway بد پیکربندی شده، برنامه آخرین دفاع است. دوم: «IP کلاینت را از X-Forwarded-For بگیر.» هر کسی میتواند آن Header را بفرستد؛ فقط وقتی به آن اعتماد کنید که Proxy خودتان مقدار کلاینت را حذف و مقدار خودش را تنظیم کند.
تعریف: httpapi.IPLimiter برای هر IP یک سطل توکن (Token bucket) از golang.org/x/time/rate نگه میدارد: rate.NewLimiter(r, burst) و Allow(). عبور از حد، 429 با Retry-After: 1 میدهد؛ پیشفرض 20 درخواست در ثانیه و Burst برابر 40 است، با ECOM_RATE_RPS و ECOM_RATE_BURST. سورس x/time/rate میگوید: "A Limiter controls how frequently events are allowed to happen. It implements a "token bucket" of size b, initially full and refilled at rate r tokens per second." تابع securityHeaders موارد توصیهشدهٔ OWASP REST Security Cheat Sheet را برای پاسخ API میگذارد: Cache-Control: no-store، Content-Security-Policy: frame-ancestors 'none'، X-Content-Type-Options: nosniff، X-Frame-Options: DENY، Strict-Transport-Security و نیز Referrer-Policy: no-referrer. مجموعهٔ کامل Middleware شامل CORS، Compression، Logging و Recover در Middlewares است؛ الگوریتمهای Token bucket، Sliding window و محدودیت Redis برای چند Replica در Rate Limiting in Go.
Request (one IP, 1 rps, burst 2) Tokens before Answer
1 GET /healthz 2 204
2 GET /healthz 1 204
3 GET /healthz 0 429 rate-limited, Retry-After: 1
4 GET /healthz (same second) 0 429سناریوی واقعی: Card testing با سفارشهای کوچک فراوان از Checkout؛ راهحل در فصل پرداخت است. Scraper کاتالوگ را ورق میزند؛ Bot هنگام عرضه با سفارش پرداختنشده موجودی را رزرو میکند، که مهلت آزادسازی و سقف سفارش باز برای هر مشتری میخواهد؛ یا XSS در سایت دیگری میخواهد پاسخ API را داخل Frame بگذارد.
| Header | مقدار | چه چیزی را متوقف میکند |
|---|---|---|
Cache-Control | no-store | ماندن دادهٔ شخصی در Cache مشترک |
Content-Security-Policy | frame-ancestors 'none' | Framing یا Clickjacking |
X-Content-Type-Options | nosniff | تفسیر JSON به شکل HTML |
X-Frame-Options | DENY | Framing در مرورگر قدیمی |
Strict-Transport-Security | max-age=63072000; includeSubDomains | Downgrade به HTTP |
Referrer-Policy | no-referrer | نشت URL حاوی شناسه به شخص ثالث |
راهحل / نحوهٔ استفاده: securityHeaders، IPLimiter و rateLimit را در فایل Middleware ببینید. TestRateLimit توالی 204 204 429 429 را بررسی میکند.
تست: Serviceهای Table-driven با Repository جعلی، API با httptest و Transaction روی Postgres واقعی حیاتی
به زبان ساده: بیشتر قواعد سریع و موازی روی Store حافظهای تست میشوند. لایهٔ HTTP از یک سرور واقعی روی Port تصادفی بررسی میشود. چند چیزی که فقط PostgreSQL میتواند اثبات کند، یعنی قفل، ON CONFLICT و Constraint، تست جدا دارند که با درخواست شما روی پایگاه دادهٔ واقعی اجرا میشود.
بدفهمی رایج: «همهٔ متدهای Repository را با کتابخانهٔ Mock تقلید کن.» برای فروشگاه، پیادهسازی جعلیِ کارا (Working fake) مثل memstore بهتر از Mock است؛ همان قرارداد Rollback روی خطا، بررسی Version و ترتیب Keyset را اعمال میکند، پس تست Service مثل مشخصات خوانده میشود. دوم: «Store حافظهای ثابت میکند Production فروش اضافه ندارد.» آن Store با یک Mutex، Transactionها را سری میکند و از READ COMMITTED در PostgreSQL قویتر است. قاعدهٔ کسبوکار را اثبات میکند؛ قفل فقط با Integration test اثبات میشود. سوم: «go test ./... باید پایگاه داده بالا بیاورد.» آنوقت کسی تست را اجرا نمیکند؛ تست پایگاه داده را پشت Build tag نگه دارید.
تعریف: سه سطح داریم. Serviceها تستهای Table-driven دارند: TestPlaceOrder با مسیر موفق، تخفیف، کد ناشناخته و کمبود موجودی؛ همزمانی زیر -race با 50 خریدار و 10 واحد؛ رقابت انقضا و Capture هم در هر دو ترتیب و هم همزمان؛ Idempotency، BOLA و Optimistic locking. همه با memstore، ساعت جعلی و مولد شناسهٔ شمارندهاند. HTTP با httptest.NewTLSServer(api.Handler()) تست میشود؛ TLS لازم است تا Cookie سبد با Secure از cookiejar رفتوبرگشت کند. تست جدولی Problemها و تطابق Spec هم اینجاست. در Adapter، pgstore_test.go، pgx.Tx را با Embed کردن Interface و پیادهسازی فقط Exec، Commit و Rollback جعل میکند تا حلقهٔ Retry روی 40001/40P01/23505 و ErrBusy روی 55P03 اثبات شود؛ SQL builder با رشته و آرگومان تست میشود. تستهای Postgres واقعی در integration_test.go با //go:build integration و ECOM_TEST_DATABASE_URL هستند. هر اجرا Schema موقت خودش را میسازد، Migration را اعمال میکند و بررسی میکند 20 Checkout همزمان برای 5 واحد دقیقاً 5 سفارش بسازند و دو درخواست همزمان با یک Idempotency-Key فقط یک سفارش بسازند. Testcontainers-go روش معمول راهاندازی پایگاه داده از تست است؛ اینجا استفاده نشده چون آزمایشگاه Docker ندارد. روشهای عمومی در Testing & Benchmarking آمدهاند.
Level Test Needs Time (this machine)
1 unit money, pricing, domain nothing < 0.1 s
2 service checkout, orders, cart, catalogue (memstore) nothing < 0.1 s, -race ok
3 adapter pgstore retry, SQL builder, migration text nothing < 0.1 s
4 HTTP httptest server, cookies, problems, spec nothing < 0.5 s
5 end to end app: HTTP -> outbox -> relay -> mail nothing ~0.2 s
6 database -tags integration, ECOM_TEST_DATABASE_URL PostgreSQL expected, not run hereسناریوی واقعی: Review تغییر قیمتگذاری با خواندن Diff جدول تست؛ حذف ناخواستهٔ Version check در Refactor که تست انقضا در برابر Capture میگیرد؛ Handlerی که نگاشت خطای جدید را فراموش کرده و تست جدول Problem پیدا میکند؛ و Route تازهٔ بیمستند که تست Spec رد میکند.
| چه چیزی | تست اثباتکننده | فایل |
|---|---|---|
| عدم فروش اضافه؛ قاعده | TestNoOversellUnderConcurrency | service/checkout_test.go |
| عدم فروش اضافه؛ قفل | TestConcurrentCheckoutsNeverOversell | pgstore/integration_test.go |
| Replay در Retry و 422 برای Body دیگر | TestPlaceOrderIsIdempotent، TestCheckoutEndToEnd | service، httpapi |
| Capture دیررس در برابر Timeout | TestStockReleaseTimeout | service/orders_test.go |
| یک ایمیل برای هر رویداد | TestRedeliveredOrderPlacedSendsOneMail | worker/worker_test.go |
| حفظ ترتیب Relay | TestRelayStopsAtFirstFailureThenResumesInOrder | outbox/outbox_test.go |
| تطابق Spec با Route | TestEveryRouteIsInTheOpenAPIDocument | httpapi/httpapi_test.go |
| توقف مرتب | TestOrderPlacedReachesTheMailboxAndShutdownIsClean | app/app_test.go |
راهحل / نحوهٔ استفاده: Fixture سرویس و تست سفارش؛ سپس تست HTTP و Integration:
package service
import (
"errors"
"sync"
"testing"
"time"
"academy/ecommerce-api-project/domain"
)
func placed(t *testing.T, f *fixture, who domain.Principal, qty int64) (domain.Order, int64) {
t.Helper()
id := f.product(t, "SKU-"+who.Email, 1000, 10)
if _, err := f.carts.SetItem(t.Context(), Owner{Principal: who}, id, qty); err != nil {
t.Fatal(err)
}
r, err := f.checkout.PlaceOrder(t.Context(), PlaceOrderInput{Who: who, IdempotencyKey: "key-" + who.Email})
if err != nil {
t.Fatal(err)
}
return r.Order, id
}
func succeeded(o domain.Order) PSPEvent {
return PSPEvent{EventID: "evt_1", Type: "payment_intent.succeeded", OrderID: o.ID, ProviderRef: "pi_1", Amount: o.Total}
}
func TestPaymentMovesOrderToPaidOnce(t *testing.T) {
f := newFixture(t)
o, _ := placed(t, f, alice, 1)
for range 2 { // the PSP delivers the webhook twice
got, err := f.orders.ApplyPayment(t.Context(), succeeded(o))
if err != nil || got.Status != domain.OrderPaid || got.Version != 2 {
t.Fatalf("got %s v%d %v", got.Status, got.Version, err)
}
}
n := 0
for _, e := range f.store.Unpublished() {
if e.Type == domain.EvPaymentCaptured {
n++
}
}
if n != 1 {
t.Fatalf("%d payment.captured events", n)
}
bad := succeeded(o)
bad.Amount = eur(1)
o2, _ := placed(t, f, bob, 1)
bad.OrderID = o2.ID
if _, err := f.orders.ApplyPayment(t.Context(), bad); !errors.Is(err, ErrAmountMismatch) {
t.Fatalf("amount mismatch: %v", err)
}
}
func TestStateMachineThroughServices(t *testing.T) {
f := newFixture(t)
o, pid := placed(t, f, alice, 2)
if _, err := f.orders.Fulfil(t.Context(), admin, o.ID); !errors.Is(err, domain.ErrInvalidTransition) {
t.Fatalf("fulfil unpaid: %v", err)
}
if _, err := f.orders.ApplyPayment(t.Context(), succeeded(o)); err != nil {
t.Fatal(err)
}
if _, err := f.orders.Cancel(t.Context(), alice, o.ID); !errors.Is(err, domain.ErrInvalidTransition) {
t.Fatalf("cancel paid: %v", err)
}
if _, err := f.orders.Fulfil(t.Context(), alice, o.ID); !errors.Is(err, domain.ErrForbidden) {
t.Fatalf("customer fulfil: %v", err)
}
got, err := f.orders.Fulfil(t.Context(), admin, o.ID)
if err != nil || got.Status != domain.OrderFulfilled {
t.Fatalf("fulfil: %s %v", got.Status, err)
}
if s := f.stock(t, pid); s.OnHand != 8 || s.Reserved != 0 {
t.Fatalf("after shipping: %+v", s)
}
}
func TestCustomersSeeOnlyTheirOrders(t *testing.T) {
f := newFixture(t)
o, _ := placed(t, f, alice, 1)
if _, err := f.orders.Get(t.Context(), bob, o.ID); !errors.Is(err, domain.ErrNotFound) {
t.Fatalf("bob reads alice's order: %v", err)
}
if _, err := f.orders.Cancel(t.Context(), bob, o.ID); !errors.Is(err, domain.ErrNotFound) {
t.Fatalf("bob cancels alice's order: %v", err)
}
if _, err := f.orders.Get(t.Context(), admin, o.ID); err != nil {
t.Fatalf("admin: %v", err)
}
}
func TestStockReleaseTimeout(t *testing.T) {
t.Run("expiry first, late capture asks for a refund", func(t *testing.T) {
f := newFixture(t)
o, pid := placed(t, f, alice, 3)
f.clock.Add(16 * time.Minute)
for range 2 { // the job runs twice; stock is released once
if _, err := f.house.ReleaseExpired(t.Context()); err != nil {
t.Fatal(err)
}
}
if s := f.stock(t, pid); s.Reserved != 0 || s.OnHand != 10 {
t.Fatalf("stock %+v", s)
}
got, err := f.orders.ApplyPayment(t.Context(), succeeded(o))
if err != nil || got.Status != domain.OrderCancelled {
t.Fatalf("late capture: %s %v", got.Status, err)
}
if p := f.payment(t, o.ID); p.Status != domain.PaymentRefundPending {
t.Fatalf("payment %s", p.Status)
}
})
t.Run("capture first, expiry leaves the order alone", func(t *testing.T) {
f := newFixture(t)
o, pid := placed(t, f, alice, 3)
if _, err := f.orders.ApplyPayment(t.Context(), succeeded(o)); err != nil {
t.Fatal(err)
}
f.clock.Add(16 * time.Minute)
if n, err := f.house.ReleaseExpired(t.Context()); err != nil || n != 0 {
t.Fatalf("released %d %v", n, err)
}
if s := f.stock(t, pid); s.Reserved != 3 {
t.Fatalf("stock %+v", s)
}
})
t.Run("concurrent: exactly one outcome", func(t *testing.T) {
f := newFixture(t)
o, pid := placed(t, f, alice, 3)
f.clock.Add(16 * time.Minute)
var wg sync.WaitGroup
wg.Add(2)
go func() { defer wg.Done(); _, _ = f.house.ReleaseExpired(t.Context()) }()
go func() { defer wg.Done(); _, _ = f.orders.ApplyPayment(t.Context(), succeeded(o)) }()
wg.Wait()
got, _ := f.orders.Get(t.Context(), admin, o.ID)
s, p := f.stock(t, pid), f.payment(t, o.ID)
switch got.Status {
case domain.OrderPaid:
if s.Reserved != 3 || p.Status != domain.PaymentSucceeded {
t.Fatalf("paid but stock %+v payment %s", s, p.Status)
}
case domain.OrderCancelled:
if s.Reserved != 0 || p.Status != domain.PaymentRefundPending {
t.Fatalf("cancelled but stock %+v payment %s", s, p.Status)
}
default:
t.Fatalf("status %s", got.Status)
}
})
}
func TestAbandonedCartReminderOnce(t *testing.T) {
f := newFixture(t)
id := f.product(t, "BOOK", 1500, 5)
_, _ = f.carts.SetItem(t.Context(), Owner{Principal: alice}, id, 1)
_, _ = f.carts.SetItem(t.Context(), Owner{GuestID: ""}, id, 1) // guests have no e-mail: never reminded
f.clock.Add(25 * time.Hour)
for want := range []int{1, 0} {
n, err := f.house.RemindAbandoned(t.Context())
if err != nil || n != 1-want {
t.Fatalf("run %d: %d %v", want, n, err)
}
}
}package httpapi
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/memstore"
"academy/ecommerce-api-project/pricing"
"academy/ecommerce-api-project/service"
)
const secret = "whsec_test"
type harness struct {
srv *httptest.Server
store *memstore.Store
}
func newHarness(t *testing.T) *harness {
t.Helper()
var n atomic.Int64
s := memstore.New()
d := service.Deps{Store: s, Now: time.Now, Currency: "EUR",
NewID: func(p string) string { return fmt.Sprintf("%s_%d", p, n.Add(1)) },
TaxRates: pricing.TaxRates{"standard": 2000}}
api := &API{Catalog: service.Catalog{Deps: d}, Carts: service.Carts{Deps: d}, Checkout: service.Checkout{Deps: d},
Orders: service.Orders{Deps: d}, WebhookSecret: []byte(secret), Limiter: NewIPLimiter(1000, 1000),
Auth: StaticTokens{
"t-admin": {UserID: 1, Email: "admin@shop.example", Role: domain.RoleAdmin},
"t-alice": {UserID: 7, Email: "alice@example.com", Role: domain.RoleCustomer},
"t-bob": {UserID: 8, Email: "bob@example.com", Role: domain.RoleCustomer},
}}
srv := httptest.NewTLSServer(api.Handler()) // TLS so the Secure cart cookie round-trips
t.Cleanup(srv.Close)
return &harness{srv: srv, store: s}
}
type call struct {
method, path, token, body string
header map[string]string
}
func (h *harness) do(t *testing.T, c *http.Client, x call) (*http.Response, map[string]any) {
t.Helper()
req, _ := http.NewRequestWithContext(t.Context(), x.method, h.srv.URL+x.path, strings.NewReader(x.body))
if x.token != "" {
req.Header.Set("Authorization", "Bearer "+x.token)
}
for k, v := range x.header {
req.Header.Set(k, v)
}
if c == nil {
c = h.srv.Client()
}
res, err := c.Do(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
raw, _ := io.ReadAll(res.Body)
var m map[string]any
_ = json.Unmarshal(raw, &m)
return res, m
}
func (h *harness) seedProduct(t *testing.T, stock int) string {
res, body := h.do(t, nil, call{method: "POST", path: "/v1/admin/products", token: "t-admin",
body: fmt.Sprintf(`{"sku":"MUG","name":"Mug","price":1000,"tax_class":"standard","stock":%d}`, stock)})
if res.StatusCode != 201 {
t.Fatalf("seed: %d %v", res.StatusCode, body)
}
return fmt.Sprint(body["id"])
}
func TestCheckoutEndToEnd(t *testing.T) {
h := newHarness(t)
pid := h.seedProduct(t, 3)
if res, _ := h.do(t, nil, call{method: "PUT", path: "/v1/cart/items/" + pid, token: "t-alice", body: `{"qty":2}`}); res.StatusCode != 200 {
t.Fatalf("cart: %d", res.StatusCode)
}
order := call{method: "POST", path: "/v1/orders", token: "t-alice", body: `{}`,
header: map[string]string{"Idempotency-Key": "4f1c9d1e-attempt"}}
res, body := h.do(t, nil, order)
if res.StatusCode != 201 || body["status"] != "created" || res.Header.Get("Location") == "" {
t.Fatalf("place: %d %v", res.StatusCode, body)
}
if total := body["total"].(map[string]any); total["amount"] != float64(2400) || body["payment_status"] != "requires_payment_method" {
t.Fatalf("total %v", body)
}
id := body["id"].(string)
// The client timed out and retries: same order, no second reservation.
res, again := h.do(t, nil, order)
if res.StatusCode != 201 || again["id"] != id || res.Header.Get("Idempotent-Replayed") != "true" {
t.Fatalf("replay: %d %v", res.StatusCode, again)
}
order.body = `{"discount_code":"OTHER"}`
if res, p := h.do(t, nil, order); res.StatusCode != 422 || p["type"] != problemBase+"idempotency-key-reused" {
t.Fatalf("reuse: %d %v", res.StatusCode, p)
}
// Bob may not see it; the answer does not even confirm it exists.
if res, _ := h.do(t, nil, call{method: "GET", path: "/v1/orders/" + id, token: "t-bob"}); res.StatusCode != 404 {
t.Fatalf("bob: %d", res.StatusCode)
}
// Signed webhook moves the order to paid; a forged one is rejected.
hook := fmt.Sprintf(`{"id":"evt_1","type":"payment_intent.succeeded","data":{"order_id":%q,"provider_ref":"pi_1","amount":2400,"currency":"eur"}}`, id)
if res, _ := h.do(t, nil, call{method: "POST", path: "/v1/webhooks/psp", body: hook,
header: map[string]string{"X-Signature": "sha256=00"}}); res.StatusCode != 400 {
t.Fatalf("forged: %d", res.StatusCode)
}
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(hook))
sig := map[string]string{"X-Signature": "sha256=" + hex.EncodeToString(mac.Sum(nil))}
for range 2 {
if res, _ := h.do(t, nil, call{method: "POST", path: "/v1/webhooks/psp", body: hook, header: sig}); res.StatusCode != 204 {
t.Fatalf("webhook: %d", res.StatusCode)
}
}
if _, o := h.do(t, nil, call{method: "GET", path: "/v1/orders/" + id, token: "t-alice"}); o["status"] != "paid" {
t.Fatalf("after webhook: %v", o)
}
if res, _ := h.do(t, nil, call{method: "POST", path: "/v1/orders/" + id + "/cancel", token: "t-alice"}); res.StatusCode != 409 {
t.Fatalf("cancel paid: %d", res.StatusCode)
}
if res, o := h.do(t, nil, call{method: "POST", path: "/v1/admin/orders/" + id + "/fulfil", token: "t-admin"}); res.StatusCode != 200 || o["status"] != "fulfilled" {
t.Fatalf("fulfil: %d %v", res.StatusCode, o)
}
var types []string
for _, e := range h.store.Unpublished() {
types = append(types, e.Type)
}
if strings.Join(types, ",") != "order.placed,payment.captured,order.fulfilled" {
t.Fatalf("outbox %v", types)
}
}
func TestErrorsAreProblemDetails(t *testing.T) {
h := newHarness(t)
pid := h.seedProduct(t, 1)
tests := []struct {
name string
c call
status int
ptype string
}{
{"no token", call{method: "POST", path: "/v1/orders"}, 401, "about:blank"},
{"customer on admin route", call{method: "POST", path: "/v1/admin/products", token: "t-alice", body: `{}`}, 403, "about:blank"},
{"missing key", call{method: "POST", path: "/v1/orders", token: "t-alice"}, 400, problemBase + "idempotency-key-missing"},
{"empty cart", call{method: "POST", path: "/v1/orders", token: "t-alice", header: map[string]string{"Idempotency-Key": "empty-cart-1"}}, 422, problemBase + "cart"},
{"unknown field", call{method: "PUT", path: "/v1/cart/items/" + pid, token: "t-alice", body: `{"qty":1,"price":1}`}, 422, problemBase + "validation"},
{"qty too big", call{method: "PUT", path: "/v1/cart/items/" + pid, token: "t-alice", body: `{"qty":11}`}, 422, problemBase + "validation"},
{"bad sort", call{method: "GET", path: "/v1/products?sort=hack"}, 422, problemBase + "validation"},
{"price without If-Match", call{method: "PUT", path: "/v1/admin/products/" + pid + "/price", token: "t-admin", body: `{"price":5}`}, 428, "about:blank"},
{"stale If-Match", call{method: "PUT", path: "/v1/admin/products/" + pid + "/price", token: "t-admin", body: `{"price":5}`,
header: map[string]string{"If-Match": `"7"`}}, 412, problemBase + "version-conflict"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
res, p := h.do(t, nil, tt.c)
if res.StatusCode != tt.status || p["type"] != tt.ptype || res.Header.Get("Content-Type") != "application/problem+json" {
t.Fatalf("%d %v %s", res.StatusCode, p, res.Header.Get("Content-Type"))
}
if p["request_id"] == "" || res.Header.Get("X-Content-Type-Options") != "nosniff" {
t.Fatalf("missing request id or security headers: %v", res.Header)
}
})
}
// Out of stock carries the product and what is left.
h.do(t, nil, call{method: "PUT", path: "/v1/cart/items/" + pid, token: "t-bob", body: `{"qty":2}`})
res, p := h.do(t, nil, call{method: "POST", path: "/v1/orders", token: "t-bob", header: map[string]string{"Idempotency-Key": "bob-order-1"}})
if res.StatusCode != 409 || p["available"] != float64(1) {
t.Fatalf("oos: %d %v", res.StatusCode, p)
}
}
func TestGuestCartCookieAndMergeOnLogin(t *testing.T) {
h := newHarness(t)
pid := h.seedProduct(t, 10)
jar, _ := cookiejar.New(nil)
browser := h.srv.Client()
browser.Jar = jar
if res, _ := h.do(t, browser, call{method: "PUT", path: "/v1/cart/items/" + pid, body: `{"qty":3}`}); res.StatusCode != 200 ||
!strings.Contains(res.Header.Get("Set-Cookie"), "HttpOnly") {
t.Fatalf("guest add: %d %v", res.StatusCode, res.Header.Get("Set-Cookie"))
}
if _, c := h.do(t, browser, call{method: "GET", path: "/v1/cart"}); len(c["items"].([]any)) != 1 {
t.Fatalf("guest cart: %v", c)
}
_, merged := h.do(t, browser, call{method: "POST", path: "/v1/cart/merge", token: "t-alice"})
items := merged["items"].([]any)
if len(items) != 1 || items[0].(map[string]any)["qty"] != float64(3) {
t.Fatalf("merged %v", merged)
}
}
func TestKeysetLinkHeader(t *testing.T) {
h := newHarness(t)
for i := range 3 {
h.do(t, nil, call{method: "POST", path: "/v1/admin/products", token: "t-admin",
body: fmt.Sprintf(`{"sku":"S%d","name":"P%d","price":%d,"tax_class":"standard"}`, i, i, 100+i)})
}
res, page := h.do(t, nil, call{method: "GET", path: "/v1/products?sort=price&limit=2"})
link := res.Header.Get("Link")
if len(page["items"].([]any)) != 2 || !strings.Contains(link, `rel="next"`) || page["next_cursor"] == "" {
t.Fatalf("page 1: %v %s", page, link)
}
_, page2 := h.do(t, nil, call{method: "GET", path: "/v1/products?sort=price&limit=2&cursor=" + page["next_cursor"].(string)})
if len(page2["items"].([]any)) != 1 || page2["next_cursor"] != nil {
t.Fatalf("page 2: %v", page2)
}
}
func TestRateLimit(t *testing.T) {
h := newHarness(t)
srv := httptest.NewServer((&API{Limiter: NewIPLimiter(1, 2), Catalog: service.Catalog{Deps: service.Deps{Store: h.store}}}).Handler())
defer srv.Close()
codes := ""
for range 4 {
res, err := http.Get(srv.URL + "/healthz")
if err != nil {
t.Fatal(err)
}
res.Body.Close()
codes += fmt.Sprint(res.StatusCode, " ")
}
if codes != "204 204 429 429 " {
t.Fatalf("codes %s", codes)
}
}
// Spec drift: every route in the mux is documented in openapi.json.
func TestEveryRouteIsInTheOpenAPIDocument(t *testing.T) {
var spec struct {
OpenAPI string `json:"openapi"`
Paths map[string]map[string]any `json:"paths"`
}
if err := json.NewDecoder(bytes.NewReader(openapiJSON)).Decode(&spec); err != nil {
t.Fatal(err)
}
if spec.OpenAPI != "3.1.0" {
t.Fatalf("openapi %q", spec.OpenAPI)
}
for _, rt := range (&API{}).Routes() {
method, path, _ := strings.Cut(rt.Pattern, " ")
if _, ok := spec.Paths[path][strings.ToLower(method)]; !ok {
t.Errorf("%s is not documented", rt.Pattern)
}
}
}//go:build integration
// Run against a throwaway PostgreSQL:
//
// ECOM_TEST_DATABASE_URL=postgres://postgres:postgres@localhost:5432/postgres?sslmode=disable \
// go test -tags integration -race -count=1 ./pgstore/
package pgstore_test
import (
"context"
"errors"
"fmt"
"io/fs"
"os"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/pgstore"
"academy/ecommerce-api-project/pricing"
"academy/ecommerce-api-project/service"
)
func pool(t *testing.T) *pgxpool.Pool {
t.Helper()
dsn := os.Getenv("ECOM_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("ECOM_TEST_DATABASE_URL not set")
}
ctx := t.Context()
schema := fmt.Sprintf("t%d", time.Now().UnixNano())
admin, err := pgxpool.New(ctx, dsn)
if err != nil {
t.Fatal(err)
}
if _, err := admin.Exec(ctx, "CREATE SCHEMA "+schema); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _, _ = admin.Exec(context.Background(), "DROP SCHEMA "+schema+" CASCADE"); admin.Close() })
cfg, _ := pgxpool.ParseConfig(dsn)
cfg.ConnConfig.RuntimeParams["search_path"] = schema
cfg.MaxConns = 30
p, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
t.Fatal(err)
}
t.Cleanup(p.Close)
up, _ := fs.ReadFile(pgstore.Migrations, "migrations/0001_init.up.sql")
if _, err := p.Exec(ctx, string(up)); err != nil {
t.Fatal(err)
}
return p
}
func TestConcurrentCheckoutsNeverOversell(t *testing.T) {
p := pool(t)
ctx := t.Context()
var n atomic.Int64
d := service.Deps{Store: pgstore.New(p), Now: time.Now, Currency: "EUR",
NewID: func(pfx string) string { return fmt.Sprintf("%s_%d_%d", pfx, time.Now().UnixNano(), n.Add(1)) },
TaxRates: pricing.TaxRates{"standard": 2000}}
var pid int64
_ = p.QueryRow(ctx, `INSERT INTO products (sku, name, price_minor, currency, tax_class) VALUES ('LAST','Last one',500,'EUR','standard') RETURNING id`).Scan(&pid)
_, _ = p.Exec(ctx, `INSERT INTO inventory (product_id, on_hand) VALUES ($1, 5)`, pid)
var wg sync.WaitGroup
var ok, oos atomic.Int32
for i := range 20 {
var uid int64
_ = p.QueryRow(ctx, `INSERT INTO users (email) VALUES ($1) RETURNING id`, fmt.Sprintf("u%d@example.com", i)).Scan(&uid)
who := domain.Principal{UserID: uid, Email: fmt.Sprintf("u%d@example.com", i), Role: domain.RoleCustomer}
if _, err := (service.Carts{Deps: d}).SetItem(ctx, service.Owner{Principal: who}, pid, 1); err != nil {
t.Fatal(err)
}
wg.Add(1)
go func() {
defer wg.Done()
_, err := (service.Checkout{Deps: d}).PlaceOrder(ctx, service.PlaceOrderInput{Who: who, IdempotencyKey: fmt.Sprintf("checkout-%d", i)})
var e *domain.OutOfStockError
switch {
case err == nil:
ok.Add(1)
case errors.As(err, &e):
oos.Add(1)
default:
t.Error(err)
}
}()
}
wg.Wait()
var reserved int64
_ = p.QueryRow(ctx, `SELECT reserved FROM inventory WHERE product_id = $1`, pid).Scan(&reserved)
if ok.Load() != 5 || oos.Load() != 15 || reserved != 5 {
t.Fatalf("ok %d oos %d reserved %d", ok.Load(), oos.Load(), reserved)
}
}
func TestSameIdempotencyKeyConcurrentlyCreatesOneOrder(t *testing.T) {
// Stock 1 on purpose: if the duplicate did the work instead of waiting on
// the key, it would answer 409 out of stock although the order exists.
p := pool(t)
ctx := t.Context()
s := pgstore.New(p)
d := service.Deps{Store: s, Now: time.Now, Currency: "EUR", NewID: service.RandomID, TaxRates: pricing.TaxRates{"standard": 2000}}
var pid, uid int64
_ = p.QueryRow(ctx, `INSERT INTO products (sku, name, price_minor, currency, tax_class) VALUES ('MUG','Mug',1000,'EUR','standard') RETURNING id`).Scan(&pid)
_, _ = p.Exec(ctx, `INSERT INTO inventory (product_id, on_hand) VALUES ($1, 1)`, pid)
_ = p.QueryRow(ctx, `INSERT INTO users (email) VALUES ('alice@example.com') RETURNING id`).Scan(&uid)
who := domain.Principal{UserID: uid, Email: "alice@example.com", Role: domain.RoleCustomer}
_, _ = (service.Carts{Deps: d}).SetItem(ctx, service.Owner{Principal: who}, pid, 1)
var wg sync.WaitGroup
ids := make([]string, 2)
for i := range 2 {
wg.Add(1)
go func() {
defer wg.Done()
r, err := (service.Checkout{Deps: d}).PlaceOrder(ctx, service.PlaceOrderInput{Who: who, IdempotencyKey: "double-click-1", Fingerprint: "fp"})
if err != nil {
t.Error(err) // neither 409 out of stock nor 422 empty cart is acceptable
}
ids[i] = r.Order.ID
}()
}
wg.Wait()
var orders int
_ = p.QueryRow(ctx, `SELECT count(*) FROM orders`).Scan(&orders)
if orders != 1 || ids[0] == "" || ids[0] != ids[1] {
t.Fatalf("%d orders, ids %v", orders, ids)
}
}
// Two tabs add different products to one cart at the same time; with the
// version check (and the retry in SetItem) neither item is lost.
func TestConcurrentCartUpdatesLoseNothing(t *testing.T) {
p := pool(t)
ctx := t.Context()
d := service.Deps{Store: pgstore.New(p), Now: time.Now, Currency: "EUR", NewID: service.RandomID, TaxRates: pricing.TaxRates{"standard": 2000}}
var uid int64
_ = p.QueryRow(ctx, `INSERT INTO users (email) VALUES ('tabs@example.com') RETURNING id`).Scan(&uid)
who := domain.Principal{UserID: uid, Email: "tabs@example.com", Role: domain.RoleCustomer}
ids := make([]int64, 10)
for i := range ids {
_ = p.QueryRow(ctx, `INSERT INTO products (sku, name, price_minor, currency, tax_class) VALUES ($1,'P',100,'EUR','standard') RETURNING id`, fmt.Sprintf("P%d", i)).Scan(&ids[i])
}
var wg sync.WaitGroup
for _, id := range ids {
wg.Add(1)
go func() {
defer wg.Done()
if _, err := (service.Carts{Deps: d}).SetItem(ctx, service.Owner{Principal: who}, id, 1); err != nil {
t.Error(err)
}
}()
}
wg.Wait()
var n int
_ = p.QueryRow(ctx, `SELECT count(*) FROM cart_items i JOIN carts c ON c.id = i.cart_id WHERE c.user_id = $1`, uid).Scan(&n)
if n != len(ids) {
t.Fatalf("%d of %d items survived", n, len(ids))
}
}
func TestOnlyOneReplicaHoldsTheLeaderLease(t *testing.T) {
p := pool(t)
a, b := pgstore.Lease{Pool: p, Key: 99}, pgstore.Lease{Pool: p, Key: 99}
release, _, ok, err := a.TryAcquire(t.Context())
if err != nil || !ok {
t.Fatalf("a: %v %v", ok, err)
}
if _, _, ok, _ := b.TryAcquire(t.Context()); ok {
t.Fatal("b got the lease while a holds it")
}
release()
rb, _, ok, _ := b.TryAcquire(t.Context())
if !ok {
t.Fatal("b did not get the released lease")
}
rb()
}مشاهدهپذیری: Log، Metric و Trace برای فروشگاه مهم
به زبان ساده: وقتی مشتری میگوید «پول دادم ولی ایمیل نیامد»، باید بتوانید همان سفارش را در API، پایگاه داده، Relay و Worker دنبال کنید. با Request id و Order id، Log بنویسید، رویدادهای کسبوکار را بشمارید و زمان مرحلههای کند را اندازه بگیرید.
بدفهمی رایج: «Log درخواست کافی است.» فقط نشان میدهد POST /v1/orders پاسخ 201 داده؛ نشان نمیدهد ایمیل 40 ثانیه بعد در تلاش دوم ارسال شده است. رویدادهای کسبوکار، یعنی ثبت سفارش، Capture پرداخت، آزادسازی موجودی و شکست ایمیل، Log و Counter خودشان را میخواهند. دوم: «Body درخواست را Log کن.» آدرس و در جریان پرداخت بیاحتیاط حتی دادهٔ کارت داخل آن است؛ فقط شناسه را ثبت کنید، هرگز Body را نه.
تعریف: مشاهدهپذیری (Observability) اینجا از logRequests شروع میشود: یک سطر slog برای هر درخواست با method، path، status، took و request_id. تابع requestID، X-Request-ID کلاینت را تا 64 کاراکتر میپذیرد یا یکی میسازد و در Header و هر Problem body برمیگرداند. Worker، job done با items و job failed با err ثبت میکند؛ mailer.LogSender هم message_id را ثبت میکند. در Production اضافه کنید: orders_placed_total، checkout_out_of_stock_total، outbox_unpublished که Gauge حاصل از SELECT count(*) ... WHERE published_at IS NULL و بهترین تکسیگنال سلامت جریان رویداد است، outbox_oldest_age_seconds و mail_send_failures_total. برای تأخیر Checkout و تعداد تلاش InTx، Histogram بگذارید؛ دور InTx، Publish در Relay و ارسال SMTP، Spanهای OpenTelemetry بگذارید و Event id را در Headerهای RabbitMQ حمل کنید. بخش Tracing در Event-Driven Go نشان داده شده است.
Time Component Line (JSON, abridged)
1 01:02:18 api {"msg":"http","method":"POST","path":"/v1/orders","status":201,"request_id":"ae25dc..."}
2 01:02:18 worker {"msg":"mail (not sent)","to":"alice@example.com","message_id":"order.placed:ord_1c36...:v1@shop.example"}
3 01:02:18 relay {"msg":"job done","job":"outbox-relay","items":2}
4 01:02:19 api {"msg":"stopped","err":null}
(real lines from a lab run; the mail is logged because ECOM_SMTP_HOST was empty)سناریوی واقعی: رشد پنجدقیقهای outbox_unpublished هشدار قطع Broker یا SMTP میدهد؛ داشبورد پاسخهای کمبود موجودی هر محصول در عرضه؛ جستوجوی پشتیبانی با Order id میان Log API و Worker؛ و Trace که نشان میدهد علت تأخیر Checkout انتظار FOR UPDATE روی یک SKU داغ است.
| سیگنال | منبع | زمان هشدار |
|---|---|---|
outbox_unpublished و سن قدیمیترین | SQL gauge | رشد طی 5 دقیقه |
| تأخیر p99 در Checkout | Histogram دور PlaceOrder | بالاتر از SLO |
تعداد تلاش InTx > 1 | Counter | افزایش ناگهانی؛ رقابت یا Deadlock |
| نرخ کمبود موجودی هر SKU | Counter | جهش در حراج قابل انتظار است؛ با روز عادی مقایسه کنید |
| شکست دائمی ایمیل | Counter | هر مورد |
| موجودی آزادشده با Timeout | Counter | تعداد زیاد؛ مشکل Checkout یا PSP |
راهحل / نحوهٔ استفاده: logRequests، requestID و Recoverer در فایل Middleware هستند؛ Log مربوط به Job در worker.RunJobs است.
خاموشی مرتب، پیکربندی محیطی، استقرار و Docker حیاتی
به زبان ساده: پیکربندی از متغیرهای محیطی میآید، یک بار خوانده و هنگام شروع بررسی میشود. فرایند با تمام کردن کار جاری، درخواستهای در حال اجرا و Job فعلی، سپس خروج متوقف میشود. خروجی یک Container کوچک با Build دومرحلهای است و Migration پایگاه داده مرحلهٔ جداگانه دارد.
بدفهمی رایج: «روی SIGTERM، os.Exit کافی است؛ Load balancer دوباره تلاش میکند.» Checkout کشتهشده میان BEGIN و COMMIT، Rollback میشود و امن است؛ اما Relay کشتهشده پس از Publish و پیش از علامتگذاری، دوباره منتشر میکند و Worker کشتهشده وسط SMTP، دوباره میفرستد. خاموشی مرتب (Graceful shutdown) این پنجرهها را کوچک نگه میدارد. دوم: «Shutdown درخواستهای جاری را لغو میکند.» چنین نیست؛ Listenerها و اتصالهای Idle را میبندد و "indefinitely for connections to return to idle" منتظر میماند. باید با Context محدودش کنید. نکتهای که تست خود این پروژه را هم گرفتار کرد: اتصالی که هنوز درخواستی نفرستاده Busy حساب میشود تا "we haven't read the first request's header in over 5 seconds". پس تست باید پیش از Shutdown اتصالهای Idle کلاینتش را ببندد.
تعریف: config.Load(getenv) متغیرهای ECOM_* را میخواند: ECOM_ADDR، ECOM_DATABASE_URL، ECOM_AMQP_URL، ECOM_SMTP_HOST/PORT/USER/PASSWORD، ECOM_MAIL_FROM، ECOM_WEBHOOK_SECRET، ECOM_CURRENCY، ECOM_STOCK_HOLD، ECOM_ABANDONED_AFTER، ECOM_SHUTDOWN_TIMEOUT، ECOM_RATE_RPS و ECOM_RATE_BURST. همهٔ خطاها را Join میکند و در ECOM_ENV=production وجود پایگاه داده، SMTP و Webhook secret را الزامی میکند؛ قاعدهٔ Twelve-factor این است: "Store config in the environment". در cmd/api از signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM) استفاده میشود. app.Serve، http.Server را با ReadHeaderTimeout، ReadTimeout، WriteTimeout و IdleTimeout همراه Jobها اجرا میکند. با Cancel، Shutdown را با ShutdownTimeout برابر 20 ثانیه صدا میزند، بعد Jobها را Cancel میکند و منتظر پایان اجرای جاری میماند. /healthz زنده بودن را پاسخ میدهد؛ /readyz پایگاه داده را Ping میکند و اگر نشد 503 میدهد. در Docker، Build چندمرحلهای، "With multi-stage builds, you use multiple FROM statements in your Dockerfile"، Binary ایستا میسازد و در Image از نوع Distroless کپی میکند. ساختار، Makefile و Build چند Binary در Project Layout, golangci-lint, Makefile & Docker و Signalها در OS Processes, Signals & Graceful Shutdown آمدهاند.
# syntax=docker/dockerfile:1
FROM golang:1.24 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/api ./cmd/api
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/api /api
USER nonroot:nonroot
EXPOSE 8080
ENTRYPOINT ["/api"] t Kubernetes / process App
1 0 s pod marked Terminating, removed from still serving in-flight requests
Service endpoints; SIGTERM sent
2 0 s NotifyContext cancels ctx; Shutdown: listener closed
3 0.4 s last checkout commits, response written
4 0.4 s jobs cancelled; relay finishes its batch, worker its mail
5 0.6 s log "stopped", exit 0 (before terminationGracePeriodSeconds 30)سناریوی واقعی: Rolling deploy در حراج؛ Evict شدن Pod هنگام ایمیل؛ نبودن ECOM_WEBHOOK_SECRET در Production که باید در شروع آشکار شود، نه اولین Webhook؛ و Migration که باید یک بار پیش از نسخهٔ تازه اجرا شود، با Kubernetes Job یا مرحلهٔ CI و migrate -path pgstore/migrations -database "$ECOM_DATABASE_URL" up.
| موضوع | این پروژه | افزودهٔ Production |
|---|---|---|
| پیکربندی | متغیرهای ECOM_* و شکست سریع | Secret از Secret store، نه Image |
| Migration | SQL داخل Binary و نامگذاری golang-migrate | مرحلهٔ مستقل استقرار، Expand/contract |
| خاموشی | NotifyContext، Shutdown(20s) و پایان Jobها | مکث preStop تا LB ابتدا ارسال را متوقف کند |
| سلامت | /healthz و /readyz با DB ping | بررسی تأخیر Outbox در Readiness |
| Image | چندمرحلهای، Distroless، غیر Root | SBOM و امضای Image |
| Replica | Replicaهای APP_ROLE=api ترافیک میگیرند؛ Replicaهای APP_ROLE=worker فقط هنگام داشتن Advisory-lock lease، Relay و Job را اجرا میکنند | هشدار از دست رفتن Lease و خارج نگه داشتن Worker از Pool مربوط به LB |
راهحل / نحوهٔ استفاده: پیکربندی، اتصال اجزا و نقطهٔ ورود:
// Package config reads the twelve-factor environment once, at start-up, and
// fails fast with every problem listed.
package config
import (
"errors"
"fmt"
"strconv"
"time"
)
// Config is everything the process needs.
type Config struct {
Env string // "development" | "production"
Role string // APP_ROLE: "api" (HTTP only), "worker" (HTTP + relay and jobs under a lease), "all"
Addr string
DatabaseURL string // empty: in-memory store (development only)
AMQPURL string // empty: in-process bus only
SMTPHost string // empty: log mails instead of sending
SMTPPort int
SMTPUser string
SMTPPassword string
MailFrom string
WebhookSecret string
Currency string
StockHold time.Duration
AbandonedAfter time.Duration
ShutdownTimeout time.Duration
RateRPS float64
RateBurst int
}
// Load reads ECOM_* variables through getenv (os.Getenv in main, a map in tests).
func Load(getenv func(string) string) (Config, error) {
var errs []error
str := func(k, def string) string {
if v := getenv(k); v != "" {
return v
}
return def
}
dur := func(k string, def time.Duration) time.Duration {
v := getenv(k)
if v == "" {
return def
}
d, err := time.ParseDuration(v)
if err != nil || d <= 0 {
errs = append(errs, fmt.Errorf("%s: %q is not a positive duration", k, v))
}
return d
}
num := func(k string, def int) int {
v := getenv(k)
if v == "" {
return def
}
n, err := strconv.Atoi(v)
if err != nil || n <= 0 {
errs = append(errs, fmt.Errorf("%s: %q is not a positive integer", k, v))
}
return n
}
c := Config{
Env: str("ECOM_ENV", "development"),
Role: str("APP_ROLE", "all"),
Addr: str("ECOM_ADDR", ":8080"),
DatabaseURL: getenv("ECOM_DATABASE_URL"),
AMQPURL: getenv("ECOM_AMQP_URL"),
SMTPHost: getenv("ECOM_SMTP_HOST"),
SMTPPort: num("ECOM_SMTP_PORT", 587),
SMTPUser: getenv("ECOM_SMTP_USER"),
SMTPPassword: getenv("ECOM_SMTP_PASSWORD"),
MailFrom: str("ECOM_MAIL_FROM", "Shop <orders@shop.example>"),
WebhookSecret: getenv("ECOM_WEBHOOK_SECRET"),
Currency: str("ECOM_CURRENCY", "EUR"),
StockHold: dur("ECOM_STOCK_HOLD", 15*time.Minute),
AbandonedAfter: dur("ECOM_ABANDONED_AFTER", 24*time.Hour),
ShutdownTimeout: dur("ECOM_SHUTDOWN_TIMEOUT", 20*time.Second),
RateBurst: num("ECOM_RATE_BURST", 40),
}
c.RateRPS = float64(num("ECOM_RATE_RPS", 20))
if c.Role != "api" && c.Role != "worker" && c.Role != "all" {
errs = append(errs, fmt.Errorf("APP_ROLE: %q is not api, worker or all", c.Role))
}
if c.Env == "production" {
for k, v := range map[string]string{"ECOM_DATABASE_URL": c.DatabaseURL, "ECOM_SMTP_HOST": c.SMTPHost, "ECOM_WEBHOOK_SECRET": c.WebhookSecret} {
if v == "" {
errs = append(errs, fmt.Errorf("%s is required in production", k))
}
}
}
return c, errors.Join(errs...)
}// Package app wires the modular monolith: one process serving HTTP and
// running the outbox relay and the background jobs, all stopped by one
// context with a graceful shutdown.
package app
import (
"context"
"errors"
"log/slog"
"net"
"net/http"
"sync"
"time"
"academy/ecommerce-api-project/bus"
"academy/ecommerce-api-project/config"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/httpapi"
"academy/ecommerce-api-project/mailer"
"academy/ecommerce-api-project/money"
"academy/ecommerce-api-project/outbox"
"academy/ecommerce-api-project/pricing"
"academy/ecommerce-api-project/service"
"academy/ecommerce-api-project/store"
"academy/ecommerce-api-project/worker"
)
// Deps are the adapters chosen by main (PostgreSQL or memory, SMTP or log,
// RabbitMQ or nothing). Tests pass in-memory ones.
type Deps struct {
Store store.Store
Inbox store.Inbox
Sender mailer.Sender
External outbox.Publisher // optional: RabbitMQ for other services
Auth httpapi.Authenticator
Ready func() error
Lease worker.Lease // leader lease for the relay and jobs; default: in-process
Log *slog.Logger
RelayTick time.Duration // default 1s
JobTick time.Duration // default 1m
}
// App is the assembled process.
type App struct {
cfg config.Config
deps Deps
Handler http.Handler
relay *outbox.Relay
house service.Housekeeping
}
// New assembles services, the HTTP API, the bus and the relay.
func New(cfg config.Config, d Deps) *App {
sd := service.Deps{Store: d.Store, Now: time.Now, NewID: service.RandomID, Currency: money.Currency(cfg.Currency),
TaxRates: pricing.TaxRates{"standard": 2000, "reduced": 700, "zero": 0}, StockHold: cfg.StockHold,
Discounts: func(code string) (pricing.Discount, bool) {
d, ok := map[string]pricing.Discount{"WELCOME10": {Code: "WELCOME10", Kind: pricing.PercentOff, BasisPoints: 1000}}[code]
return d, ok
}}
orders := service.Orders{Deps: sd}
b := bus.New()
mail := worker.OrderMail{Inbox: d.Inbox, Sender: d.Sender, Domain: "shop.example", Log: d.Log,
Backoff: worker.Backoff{Base: 200 * time.Millisecond, Max: 5 * time.Second, Attempts: 3},
LoadOrder: func(ctx context.Context, id string) (domain.Order, error) {
return orders.Get(ctx, domain.Principal{Role: domain.RoleAdmin}, id) // system principal
}}
b.Subscribe(domain.EvOrderPlaced, "order-confirmation-mail", mail.Handle)
var pub outbox.Publisher = b
if d.External != nil {
pub = outbox.Fanout{b, d.External}
}
api := &httpapi.API{Catalog: service.Catalog{Deps: sd}, Carts: service.Carts{Deps: sd},
Checkout: service.Checkout{Deps: sd}, Orders: orders, Auth: d.Auth, Ready: d.Ready, Log: d.Log,
Limiter: httpapi.NewIPLimiter(cfg.RateRPS, cfg.RateBurst), WebhookSecret: []byte(cfg.WebhookSecret)}
return &App{cfg: cfg, deps: d, Handler: api.Handler(),
relay: &outbox.Relay{Store: d.Store, Pub: pub, Now: time.Now, Batch: 100},
house: service.Housekeeping{Deps: sd, AbandonedAfter: cfg.AbandonedAfter}}
}
// Serve runs until ctx is cancelled (SIGINT/SIGTERM in main). Every role
// serves HTTP (API traffic, or only /healthz and /readyz on workers). Only
// APP_ROLE=worker or all starts the relay and the jobs, and only while this
// replica holds the lease, so many replicas still mean one relay. On cancel:
// 1. stops accepting connections and waits for in-flight requests
// (http.Server.Shutdown, bounded by ShutdownTimeout),
// 2. stops the relay and the jobs and waits for their current run.
func (a *App) Serve(ctx context.Context, ln net.Listener) error {
srv := &http.Server{Handler: a.Handler, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second,
WriteTimeout: 30 * time.Second, IdleTimeout: 120 * time.Second,
BaseContext: func(net.Listener) context.Context { return context.WithoutCancel(ctx) }}
bg, stopBG := context.WithCancel(context.WithoutCancel(ctx))
var wg sync.WaitGroup
if a.cfg.Role != "api" {
lease := a.deps.Lease
if lease == nil {
lease = worker.NewMemLease()
}
wg.Add(1)
go func() {
defer wg.Done()
worker.RunWithLease(bg, lease, 5*time.Second, a.deps.Log,
worker.Job{Name: "outbox-relay", Every: or(a.deps.RelayTick, time.Second), Run: a.relay.RunOnce},
worker.Job{Name: "release-expired-orders", Every: or(a.deps.JobTick, time.Minute), Run: a.house.ReleaseExpired},
worker.Job{Name: "abandoned-cart-reminders", Every: or(a.deps.JobTick, time.Minute), Run: a.house.RemindAbandoned})
}()
}
errc := make(chan error, 1)
go func() { errc <- srv.Serve(ln) }()
var err error
select {
case err = <-errc: // listener failed
case <-ctx.Done():
sctx, cancel := context.WithTimeout(context.Background(), a.cfg.ShutdownTimeout)
err = srv.Shutdown(sctx)
cancel()
}
stopBG()
wg.Wait()
if errors.Is(err, http.ErrServerClosed) {
err = nil
}
return err
}
func or(d, def time.Duration) time.Duration {
if d > 0 {
return d
}
return def
}// Command api runs the shop: HTTP API, outbox relay and background jobs in
// one process. Adapters are chosen from the environment: PostgreSQL or
// memory, SMTP or log, RabbitMQ or in-process only.
package main
import (
"context"
"fmt"
"io"
"log/slog"
"net"
"os"
"os/signal"
"syscall"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"academy/ecommerce-api-project/app"
"academy/ecommerce-api-project/config"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/httpapi"
"academy/ecommerce-api-project/mailer"
"academy/ecommerce-api-project/memstore"
"academy/ecommerce-api-project/pgstore"
"academy/ecommerce-api-project/rabbit"
)
func main() {
if err := run(context.Background(), os.Getenv, os.Stdout); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run(ctx context.Context, getenv func(string) string, stdout io.Writer) error {
ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
defer stop()
cfg, err := config.Load(getenv)
if err != nil {
return err
}
log := slog.New(slog.NewJSONHandler(stdout, nil))
// Swap in the JWT or session authenticator of the authentication chapter.
// Development gets two fixed tokens so the API can be tried with curl.
auth := httpapi.StaticTokens{}
if cfg.Env == "development" {
auth["dev-admin"] = domain.Principal{UserID: 1, Email: "admin@shop.example", Role: domain.RoleAdmin}
auth["dev-alice"] = domain.Principal{UserID: 7, Email: "alice@example.com", Role: domain.RoleCustomer}
}
d := app.Deps{Log: log, Auth: auth}
if cfg.DatabaseURL != "" {
pool, err := pgxpool.New(ctx, cfg.DatabaseURL)
if err != nil {
return err
}
defer pool.Close()
d.Store, d.Inbox = pgstore.New(pool), pgstore.Inbox{DB: pool}
d.Lease = pgstore.Lease{Pool: pool, Key: 7_340_001} // one relay per database, across replicas
d.Ready = func() error {
c, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
return pool.Ping(c)
}
} else {
log.Warn("ECOM_DATABASE_URL not set: in-memory store, data is lost on exit")
d.Store, d.Inbox = memstore.New(), memstore.NewInbox()
}
if cfg.SMTPHost != "" {
s, err := mailer.NewSMTP(mailer.SMTPConfig{Host: cfg.SMTPHost, Port: cfg.SMTPPort,
Username: cfg.SMTPUser, Password: cfg.SMTPPassword, From: cfg.MailFrom})
if err != nil {
return err
}
d.Sender = s
} else {
d.Sender = mailer.LogSender{Log: log}
}
if cfg.AMQPURL != "" {
p, err := rabbit.New(cfg.AMQPURL, "shop.events") // redials by itself after a broker restart
if err != nil {
return err
}
defer p.Close()
d.External = p
}
ln, err := net.Listen("tcp", cfg.Addr)
if err != nil {
return err
}
log.Info("listening", "addr", ln.Addr().String())
err = app.New(cfg, d).Serve(ctx, ln)
log.Info("stopped", "err", err)
return err
}سازوکار (Mechanics)
Pipeline درخواست، به ترتیب مهم
app.Handler برابر chain(mux, requestID, logRequests, recoverer, securityHeaders, rateLimit, authenticate) است؛ از بیرونیترین لایه به داخل. پس هر پاسخ، حتی 429 و Panic بازیابیشده، Request id، سطر Log و Headerهای امنیتی دارد.
| ترتیب | مرحله | پاسخ ممکن | نکته |
|---|---|---|---|
| 1 | requestID | شناسهٔ کلاینت تا 64 کاراکتر حفظ میشود | |
| 2 | logRequests | Writer را برای ثبت Status میپوشاند | |
| 3 | recoverer | 500 | http.ErrAbortHandler را دوباره Panic میکند |
| 4 | securityHeaders | پیش از نوشتن Handler تنظیم میشود | |
| 5 | rateLimit | 429 | Token bucket برای هر IP |
| 6 | authenticate | Principal را در Context میگذارد؛ خودش رد نمیکند | |
| 7 | ServeMux | 404, 405 | الگوهای Go 1.22 |
| 8 | customer / admin | 401, 403 | برای هر Route |
| 9 | Handler: Decode و MaxBytesReader | 400, 422 | DisallowUnknownFields |
| 10 | Service: اعتبارسنجی، مجوز شیء، InTx | 404, 409, 412, 422 | خطاهای نوعدار |
| 11 | fail | problem+json | یک جدول نگاشت |
کدها و متن خطاهایی که میبینید حیاتی
| منبع | کد / متن | معنا در این پروژه |
|---|---|---|
| PostgreSQL | 40001 could not serialize access due to concurrent update | تعارض REPEATABLE READ/SERIALIZABLE؛ InTx دوباره اجرا میکند |
| PostgreSQL | 40P01 deadlock_detected | جایی ترتیب قفل رعایت نشده؛ اجرای مجدد |
| PostgreSQL | 23505 unique_violation | شناسهٔ سفارش، پرداخت یا رویداد تکراری، یا رقابت Idempotency |
| PostgreSQL | 23514 check_violation inventory_no_oversell | نوشتن سعی کرده reserved > on_hand کند |
| PostgreSQL | 55P03 lock_not_available | انتظار از lock_timeout گذشته |
| pgx | pgx.ErrNoRows | به domain.ErrNotFound نگاشت میشود |
| go-mail | *mail.SendError، ErrorCode() | 4xx و 0 شبکه Retry میشوند؛ 5xx دائمی است |
| amqp091-go | DeferredConfirmation.WaitContext → false | Nack از Broker؛ Retry در Relay |
| net/http | http: request body too large | رسیدن به سقف MaxBytesReader؛ 422 با body |
| Go | context canceled | کلاینت حین InTx رفته است |
پاسخهای دقیق؛ اجرای واقعی مهم
خروجی درخواست سفارش آزمایشگاه با curl -si در برابر go run ./cmd/api و Store حافظهای؛ Date، شناسهها و زمانها در هر اجرا تغییر میکنند:
$ curl -si -X POST $B/v1/orders -H "Authorization: Bearer dev-alice" -H "Idempotency-Key: 6f9c1e0a-lab-0001" -d '{"discount_code":"WELCOME10"}'
HTTP/1.1 201 Created
Cache-Control: no-store
Content-Security-Policy: frame-ancestors 'none'
Content-Type: application/json
Location: /v1/orders/ord_1c3600516daf2ad2f578716a9aac72cf
Referrer-Policy: no-referrer
Strict-Transport-Security: max-age=63072000; includeSubDomains
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-Request-Id: ae25dc86f3914501
{"id":"ord_1c3600516daf2ad2f578716a9aac72cf","status":"created","items":[{"product_id":1,"sku":"GOBOOK","name":"The Go book","qty":2,"unit_price":{"amount":3999,"currency":"EUR"},"line_total":{"amount":7702,"currency":"EUR"}}],"subtotal":{"amount":7998,"currency":"EUR"},"discount":{"amount":800,"currency":"EUR"},"tax":{"amount":504,"currency":"EUR"},"total":{"amount":7702,"currency":"EUR"},"payment_status":"requires_payment_method","pay_before":"2026-11-29T01:17:18.119928+03:30","created_at":"2026-11-29T01:02:18.119928+03:30"}تنظیمات (Knobs) تکمیلی
| تنظیم | پیشفرض | محل | اثر |
|---|---|---|---|
ECOM_STOCK_HOLD | 15m | Deps.StockHold | مدت نگهداری موجودی در سفارش پرداختنشده |
ECOM_ABANDONED_AFTER | 24h | Housekeeping | زمان بیفعالیتی تا یادآوری |
MaxAttempts | 3 | pgstore.Store | اجرای مجدد روی 40001/40P01/23505 |
LockTimeout | 5s | pgstore.Store | lock_timeout هر Transaction، سپس 55P03 → 409 |
FullText | false | pgstore.Store | tsvector بهجای ILIKE |
| Tick / Batch در Relay | 1 s / 100 | app | موازنهٔ تأخیر رویداد و بار |
| Backoff ایمیل | پایه 200 ms، سقف 5 s، 3 تلاش | app | برای هر تحویل؛ سپس Relay، Backoff میکند |
| Backoff در Relay | 2^n s، سقف 10 min | outbox.Relay | برای هر رویداد ناموفق |
ECOM_RATE_RPS / ECOM_RATE_BURST | 20 / 40 | IPLimiter | آستانهٔ 429 |
ECOM_SHUTDOWN_TIMEOUT | 20s | http.Server.Shutdown | کوتاهتر از مهلت Orchestrator نگه دارید |
APP_ROLE | all | config، app.Serve | api: فقط HTTP؛ worker: HTTP همراه Relay و Job هنگام داشتن Lease |
MaxQtyPerLine | 10 | domain | سقف هر ردیف و یک CHECK پایگاه داده |
SQL اجراشده در کد موجودی و فهرست، برای خواندن در psql:
-- Reserve (pessimistic): lock the order's stock rows in id order, then add.
BEGIN;
SELECT set_config('lock_timeout', '5s', true);
SELECT product_id, on_hand - reserved FROM inventory
WHERE product_id = ANY('{3,9}'::bigint[]) ORDER BY product_id FOR UPDATE;
UPDATE inventory SET reserved = reserved + 2, updated_at = now() WHERE product_id = 3;
UPDATE inventory SET reserved = reserved + 1, updated_at = now() WHERE product_id = 9;
COMMIT;
-- Reserve (single line, atomic conditional update): 0 rows = not enough stock.
UPDATE inventory SET reserved = reserved + 2
WHERE product_id = 3 AND on_hand - reserved >= 2;
-- Optimistic edit of a product: 0 rows = someone else changed it (412).
UPDATE products SET price_minor = 4299, version = version + 1 WHERE id = 3 AND version = 4;
-- Keyset page 2, price ascending, with the index products_price (price_minor, id) WHERE active.
SELECT id, sku, name, price_minor FROM products
WHERE active AND (price_minor, id) > (1999, 42)
ORDER BY price_minor, id LIMIT 21;
-- Search: substring now, full text later.
SELECT id, name FROM products WHERE active AND (name ILIKE '%go book%' OR sku ILIKE '%go book%');
SELECT id, name, ts_rank(search, q) AS rank
FROM products, websearch_to_tsquery('simple', 'go book') AS q
WHERE active AND search @@ q ORDER BY rank DESC LIMIT 20;
-- The two background scans, each on a partial index.
SELECT id FROM orders WHERE status = 'created' AND expires_at < now() ORDER BY expires_at LIMIT 100;
SELECT count(*), min(occurred_at) FROM outbox WHERE published_at IS NULL;حل مسئلههای کلاسیک
| مسئله | راهحل | روش | مزیت | هزینه |
|---|---|---|---|---|
| فروش اضافه در حراج | رزرو قفلشده و CHECK | FOR UPDATE به ترتیب id، همه یا هیچ | درست زیر هر همزمانی | صف میلیثانیهای خریداران یک SKU |
| سفارش تکراری با Retry | Idempotency-Key در Transaction خرید | کلید دارای Scope، Fingerprint و Replay | کلاینت میتواند بیدغدغه Retry کند | یک جدول با نگهداری 24 ساعت |
| دستکاری قیمت | قیمتگذاری سمت سرور | سبد بدون قیمت؛ Quote از کاتالوگ | چیزی برای دستکاری وجود ندارد | ندارد |
| ایمیل تأیید گمشده | Outbox و Worker | رویداد در Transaction، Relay حداقل یک بار، Inbox | تحمل Crash | تأخیر نهایی در حد ثانیه |
| ایمیل تکراری | Inbox و شناسهٔ قطعی | Has/Mark برای هر Consumer | اثر یک بار | یک جدول |
| موجودی در دست سفارش پرداختنشده | مهلت آزادسازی | expires_at و Job با Version check | موجودی برمیگردد | اجرای یک Job |
| پرداخت پس از مهلت | refund_pending | ماشین حالت یال cancelled → paid ندارد | سفارش زنده نمیشود | جریان Refund |
| خواندن سفارش مشتری دیگر | بررسی هر شیء | CanSee و 404 | بستن BOLA | رعایت در هر مورد کاربرد |
| بازنویسی ویرایش Adminها | قفل خوشبینانه | If-Match و version | قفل نگه داشته نمیشود | 412 و بارگذاری مجدد |
| جابهجایی صفحههای کاتالوگ | صفحهبندی Keyset | Cursor از (sort, id) | پایدار و سریع | پرش مستقیم به صفحهٔ 57 نداریم |
| فاصلهٔ Spec از کد | تست Spec | Routeها در برابر openapi.json | مستند درست میماند | یک تست |
| Deadlock بین Checkoutها | ترتیب قفل و Retry | SortReservations و اجرای مجدد 40P01 | نادر و خودترمیم | ندارد |
فروش بیش از موجودی
برای سبد چندردیفی رزرو همراه قفل (Lock) و برای مسیر داغ تکردیفی UPDATE شرطی به کار ببرید. CHECK (reserved <= on_hand) را نگه دارید تا باگ به خطا تبدیل شود. اگر یک SKU آنقدر داغ است که حتی قفل میلیثانیهای صف میسازد، مثل عرضهٔ بلیت، شمارنده را با DECRBY و بررسی Lua به Redis ببرید یا موجودی را از قبل به Bucket تقسیم کنید؛ سپس با PostgreSQL تطبیق دهید.
سفارش تکراری و نتیجهٔ نامعلوم
کلاینت برای هر تلاش خرید یک کلید، UUIDv4 یا ULID، میسازد و تا پاسخ قطعی نگه میدارد. سرور رکورد را در تراکنش (Transaction) همان خرید ذخیره میکند. در سمت PSP، کلید متفاوت و مشتقشدهٔ ord_x:attempt:1 از برداشت پول محافظت میکند؛ ببینید API Idempotency.
Webhook دیررس پس از آزاد شدن موجودی
سفارش را دوباره باز نکنید؛ شاید موجودی به دیگری فروخته شده باشد. refund_pending ثبت و payment.refund_requested منتشر کنید؛ سیستم پرداخت با کلید مشتقشدهٔ خودش بازپرداخت (Refund) میکند. برای روش کند مثل برداشت بانکی که "can take up to a few days to process"، مهلت طولانیتر بگذارید یا فقط پس از processing رزرو کنید.
ایمیلی که نمیرسد
اول outbox_unpublished را ببینید؛ شاید Relay یا Broker قطع است. سپس خطاهای mail send در Worker برای SMTP و بعد Webhookهای Bounce ارائهدهنده را بررسی کنید. خطای دائمی 5xx، انجامشده علامت میخورد و هشدار میدهد؛ نباید صف پشت خود را مسدود کند.
انتخاب (Choosing)
| موقعیت | پیشنهاد | تکنیک اضافه | دلیل |
|---|---|---|---|
| چند صد سفارش در روز | همین Monolith و یک PostgreSQL | Bus داخل فرایند، SMTP از ارائهدهنده | سادهترین طراحی درست |
| حراج روی چند SKU | رزرو قفلشده و Transaction کوتاه | lock_timeout و Queue جلوی Checkout | رقابت روی یک سطر است |
| بیشتر سفارشها تککالا | UPDATE ... WHERE on_hand - reserved >= n شرطی | بررسی RowsAffected | یک دستور بدون قفل صریح |
| ویرایش طولانی Admin | version خوشبینانه و If-Match | 412 و بارگذاری دوباره | قفل چنددقیقهای نداریم |
| مصرف سفارش در چند سرویس | Outbox → RabbitMQ Topic exchange | Confirm و Inbox هر Consumer | حداقل یک بار بین فرایندها |
| Replay و حجم بالا | Outbox → Kafka با Key برابر Order id | CDC بهجای Polling | ترتیب هر سفارش و Retention |
| جستوجو قابلیت محصول است | ابتدا tsvector سپس Search engine | تغذیهٔ Index با Outbox | Ranking، غلط تایپی و Facet |
| ورود فروشگاه وب | Cookie session | محافظت CSRF | ساده و قابل ابطال |
| برنامهٔ موبایل | JWT کوتاه و Refresh | Rotation و فهرست ابطال | بدون Cookie |
| قرارداد برای تیمهای دیگر | Spec-first با oapi-codegen | Client تولیدشده | قرارداد پیش از کد |
| تیم کوچک با محور Go | Code-first با swag یا قرارداد دستی و تست تطابق | انتشار Swagger UI | سریعترین شروع |
در معماری: از یک فرایند تا سیستم توزیعشده
مونولیت: یک فرایند و یک پایگاه داده
همین پروژه: یک Binary که HTTP، Relay و Jobها را اجرا میکند، با یک PostgreSQL. همهٔ تضمینها از یک تراکنش (Transaction) میآیند؛ موجودی، سفارش، Payment intent و رویداد از ابتدا سازگارند. Bus داخل فرایند برای Worker ایمیل کافی است. سادهترین استقرار درست، دو Replica از APP_ROLE=api پشت Load balancer است که فقط HTTP دارند، بدون Relay و Job؛ همراه دو Replica از APP_ROLE=worker که برای اجارهٔ رهبر (Leader lease) رقابت میکنند. این Lease با pg_try_advisory_lock روی اتصال نگهداشتهشده در pgstore.Lease است. فقط دارندهٔ آن Relay و Job اجرا میکند؛ دیگری آمادهبهکار است و با پایان Session دارنده، مسئولیت را میگیرد. همه یک پایگاه داده دارند. TestAPIRoleRunsNoBackgroundJobs و TestOnlyOneWorkerHoldsTheLease هر دو بخش را اثبات میکنند.
مونولیت ماژولار و چند پایگاه داده
بدون شبکه بر اساس ماژول جدا کنید: catalog، cart، ordering، inventory، payments و notifications. هر کدام مالک جدولهای خودش، مثلاً یک Schema، است و با Interfaceهای Go و رویدادهای Bus داخل فرایند صحبت میکند. مرز تراکنش (Transaction) روشن است: Checkout فقط تا وقتی inventory، orders، payments و outbox یک پایگاه داده دارند میتواند همه را در یک Transaction بنویسد. بهمحض جدا شدن پایگاه دادهٔ inventory، رزرو یک مرحلهٔ Saga میشود. خواندن بین ماژولها را از API ماژول مالک انجام دهید، بدون Join بین Schemaها، تا جداسازی بعدی مکانیکی باشد.
میکروسرویسها (Microservices)
سرویسهای Catalogue، Cart، Order، Inventory، Payment و Notification جدا میشوند. Checkout یک Saga هماهنگشده است: Order، PENDING میسازد و OrderPlaced را از Outbox خود منتشر میکند؛ Inventory رزرو و StockReserved یا StockRejected تولید میکند؛ Payment با کلید مشتقشده Authorize میکند و PaymentCaptured یا PaymentFailed میدهد؛ Order به paid میرود یا با ReleaseStock و VoidPayment جبران میکند. هر مرحله با Event id، Idempotent است؛ هر سرویس Outbox و Inbox دارد و مهلت آزادسازی موجودی به Timeout در Saga تبدیل میشود. آنچه باقی نمیماند Transaction واحد، خواندن نوشتهٔ خود بین سرویسها و Join ساده است. صفحهٔ سفارش شاید یک ثانیه pending نشان دهد؛ سرویس سفارش کپی نام و قیمت را نگه میدارد، همان کاری که از قبل در Order item میکرد. شکلهای Saga در Payment Processing Architecture و Consumerها در Event-Driven Go هستند.
Order svc Inventory svc Payment svc Notification svc
1 tx: order PENDING + outbox
2 -> OrderPlaced
3 tx: reserve + outbox
4 -> StockReserved
5 PSP call, key ord_1:attempt:1
6 -> PaymentCaptured
7 tx: order paid + outbox <-
8 -> OrderPaid mail (inbox dedupe)
failure at 5: PaymentFailed -> Order emits ReleaseStock -> Inventory releases (compensation)دادهٔ توزیعشده: Replica، Cache، پایگاه دادهٔ Shardشده و چند منطقه
نسخهٔ خواندنی (Read replica) کاتالوگ را پاسخ میدهد؛ یک ثانیه عقب بودن پذیرفتنی است. اما Checkout یا «سفارشهایم بلافاصله پس از پرداخت» هرگز از آن خوانده نمیشود؛ نوشتهٔ خود را از Primary یا با Version token بخوانید. CDN یا Redis cache جلوی GET /v1/products هنگام تغییر قیمت به ابطال از رویداد product.updated نیاز دارد، نه حدس TTL. موجودی قسمت سخت Sharding است: سفارش را بر اساس مشتری Shard کنید، ولی موجودی SKU داغ هنوز یک سطر است؛ آن را به Bucket تقسیم یا Inventory را بدون Shard نگه دارید. فروشگاه چندمنطقهای معمولاً یک منطقهٔ نوشتن برای موجودی و پرداخت دارد و کاتالوگ را تکثیر میکند. موجودی Active-active به سهمبندی منطقهای و تطبیق نیاز دارد.
مسیر مقیاسپذیری: 1×، 10×، 100×
در 1× همین Monolith روی یک PostgreSQL و Pool با 20 اتصال کافی است. در 10×، Replicaهای API را بیشتر کنید و pgxpool هر Replica را طوری اندازه دهید که جمع زیر max_connections بماند. گزینهٔ دیگر PgBouncer در Transaction mode است؛ Statement cache در pgx باید با پشتیبانی Pooler از Prepared statement سازگار باشد؛ تنظیمات در database/sql & pgx است. کاتالوگ را به Replica و Cache ببرید، Batch در Relay را بزرگتر و RabbitMQ را وارد مسیر Consumerها کنید. در 100×، Checkout را از کاتالوگ جدا کنید، Search را به موتور تغذیهشده از Outbox ببرید، موجودی SKU داغ را با تطبیق دورهای در Redis بگذارید، orders و outbox را بر اساس زمان Partition کنید و جایی که تیمها استقرار مستقل میخواهند به Saga بالا بروید.
آزمایشگاه (Lab)
همهٔ دستورها از docs/snippets/go/ecommerce-api-project/go با Go 1.24 یا بالاتر اجرا میشوند. آزمایشهای 1 تا 4 برای این فصل با Go 1.27.4 روی macOS و Apple M4 Pro اجرا شدهاند و خروجی همان اجرا آمده است. آزمایشهای 5 تا 7 به PostgreSQL، RabbitMQ، گیرندهٔ آزمایشی SMTP یا مولد کد نیاز دارند؛ خروجی آنها «مورد انتظار، اجرا نشده» است.
۱. اجرای همهٔ تستها؛ واقعی
gofmt -l . && go vet ./... && go vet -tags integration ./... && go test -race -count=1 ./...
# ok academy/ecommerce-api-project/app 1.729s
# ok academy/ecommerce-api-project/before 1.465s
# ok academy/ecommerce-api-project/bus 1.440s
# ok academy/ecommerce-api-project/cmd/api 1.722s
# ok academy/ecommerce-api-project/config 1.432s
# ok academy/ecommerce-api-project/domain 1.445s
# ok academy/ecommerce-api-project/httpapi 1.532s
# ok academy/ecommerce-api-project/mailer 1.485s
# ok academy/ecommerce-api-project/memstore 1.472s
# ok academy/ecommerce-api-project/money 1.449s
# ok academy/ecommerce-api-project/outbox 1.485s
# ok academy/ecommerce-api-project/pgstore 1.551s
# ok academy/ecommerce-api-project/pricing 1.631s
# ok academy/ecommerce-api-project/rabbit 1.614s
# ok academy/ecommerce-api-project/service 1.548s
# ? academy/ecommerce-api-project/store [no test files]
# ok academy/ecommerce-api-project/worker 1.572s۲. اثباتهای همزمانی و زمانبندی؛ واقعی
go test -race -count=1 -v -run 'TestNoOversellUnderConcurrency|TestStockReleaseTimeout|TestPlaceOrderIsIdempotent' ./service
# --- PASS: TestPlaceOrderIsIdempotent (0.00s)
# --- PASS: TestNoOversellUnderConcurrency (0.00s) 50 buyers, 10 units: 10 orders, 40 x out of stock
# --- PASS: TestStockReleaseTimeout (0.00s)
# --- PASS: TestStockReleaseTimeout/expiry_first,_late_capture_asks_for_a_refund (0.00s)
# --- PASS: TestStockReleaseTimeout/capture_first,_expiry_leaves_the_order_alone (0.00s)
# --- PASS: TestStockReleaseTimeout/concurrent:_exactly_one_outcome (0.00s)
go test -count=1 -v -run 'TestRedelivered|TestRelayStops' ./worker ./outbox
# --- PASS: TestRedeliveredOrderPlacedSendsOneMail (0.00s) two 421s, three deliveries, one mail
# --- PASS: TestRelayStopsAtFirstFailureThenResumesInOrder (0.00s)
go test -count=1 -v -run TestWhatGoesWrong ./before
# --- PASS: TestWhatGoesWrong (0.00s) the fat handler: 500 with an order saved, double order, 0.1+0.2, client price۳. کار با API از طریق curl؛ واقعی
ECOM_ADDR=127.0.0.1:18080 ECOM_WEBHOOK_SECRET=whsec_dev go run ./cmd/api &
B=http://127.0.0.1:18080
curl -s -X POST $B/v1/admin/products -H "Authorization: Bearer dev-admin" \
-d '{"sku":"GOBOOK","name":"The Go book","price":3999,"tax_class":"reduced","stock":2}'
# {"id":1,"sku":"GOBOOK","name":"The Go book","price":{"amount":3999,"currency":"EUR"},"version":1}
curl -s -X PUT $B/v1/cart/items/1 -H "Authorization: Bearer dev-alice" -d '{"qty":2}'
# {"id":"cart_b896c47aeb1dca45a0920a886b802442","items":[{"product_id":1,"qty":2}]}
ORDER=$(curl -s -X POST $B/v1/orders -H "Authorization: Bearer dev-alice" \
-H "Idempotency-Key: 6f9c1e0a-lab-0001" -d '{"discount_code":"WELCOME10"}')
OID=$(printf '%s' "$ORDER" | grep -o '"id":"ord_[0-9a-f]*"' | cut -d'"' -f4)
echo "$OID"; printf '%s\n' "$ORDER" | grep -o '"total":{[^}]*}'
# ord_f0f14e5515640ec2fbd34d77c4c8bec2
# "total":{"amount":7702,"currency":"EUR"}
# 7702 = (7998 - 800 WELCOME10) + 504 tax at 7 % (full response in Mechanics)
curl -si -X POST $B/v1/orders -H "Authorization: Bearer dev-alice" \
-H "Idempotency-Key: 6f9c1e0a-lab-0001" -d '{"discount_code":"WELCOME10"}' | grep -E 'HTTP/|Idempotent|Location'
# HTTP/1.1 201 Created
# Idempotent-Replayed: true
# Location: /v1/orders/ord_f0f14e5515640ec2fbd34d77c4c8bec2
curl -s -X POST $B/v1/orders -H "Authorization: Bearer dev-alice" -H "Idempotency-Key: 6f9c1e0a-lab-0001" -d '{}'
# {"type":"https://shop.example/problems/idempotency-key-reused","title":"Idempotency-Key reused with another body","status":422,"instance":"/v1/orders","request_id":"ac2b5a08aefb5207"}
curl -s -X PUT $B/v1/cart/items/1 -H "Authorization: Bearer dev-alice" -d '{"qty":1}' >/dev/null
curl -s -X POST $B/v1/orders -H "Authorization: Bearer dev-alice" -H "Idempotency-Key: 6f9c1e0a-lab-0002"
# {"type":"https://shop.example/problems/out-of-stock","title":"Not enough stock","status":409,"detail":"product 1: wanted 1, available 0","instance":"/v1/orders","request_id":"8dcc1e4f2cf2deb1","product_id":1,"available":0}
BODY='{"id":"evt_lab_1","type":"payment_intent.succeeded","data":{"order_id":"'"$OID"'","provider_ref":"pi_lab","amount":7702,"currency":"eur"}}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac whsec_dev -hex | sed 's/.*= //')
curl -s -o /dev/null -w "%{http_code}\n" -X POST $B/v1/webhooks/psp -H "X-Signature: sha256=$SIG" -d "$BODY"
curl -s -o /dev/null -w "%{http_code}\n" -X POST $B/v1/webhooks/psp -H "X-Signature: sha256=00" -d "$BODY"
# 204
# 400
curl -s "$B/v1/orders/$OID" -H "Authorization: Bearer dev-alice" | grep -o '"status":"[a-z]*"'
# "status":"paid"
curl -s "$B/v1/products?sort=hack&limit=1000"
# {"type":"https://shop.example/problems/validation","title":"Invalid input","status":422,"instance":"/v1/products","request_id":"f157852a49005f21","errors":[{"field":"sort","message":"one of newest, price, -price, name"},{"field":"limit","message":"integer between 1 and 100"}]}
curl -s -o /dev/null -w "%{http_code}\n" -X POST $B/v1/admin/products -H "Authorization: Bearer dev-alice" -d "{}"
# 403۴. مشاهدهٔ Worker و خاموشی مرتب؛ واقعی
# server log of lab 3 (JSON, abridged), then kill -TERM <pid>
# {"level":"WARN","msg":"ECOM_DATABASE_URL not set: in-memory store, data is lost on exit"}
# {"level":"INFO","msg":"listening","addr":"127.0.0.1:18080"}
# {"level":"INFO","msg":"lease acquired: running background jobs"} (APP_ROLE defaults to all)
# {"level":"INFO","msg":"http","method":"POST","path":"/v1/orders","status":201,"took":127625,"request_id":"f2dca24d56ff5690"}
# {"level":"INFO","msg":"mail (not sent)","to":"alice@example.com","subject":"Your order ord_f0f14e5515640ec2fbd34d77c4c8bec2","message_id":"order.placed:ord_f0f14e5515640ec2fbd34d77c4c8bec2:v1@shop.example"}
# {"level":"INFO","msg":"job done","job":"outbox-relay","items":2}
# {"level":"INFO","msg":"stopped","err":null}سطر ایمیل حدود نیم ثانیه پس از 201 ظاهر میشود؛ Tick مربوط به Relay، نه خود درخواست، آن را فرستاده است. Relay در آن Batch دو رویداد منتشر کرده: order.placed و payment.captured که Webhook نوشته بود.
۵. تستهای PostgreSQL واقعی؛ مورد انتظار، اجرا نشده
# any PostgreSQL 14+; the test creates and drops its own schema
export ECOM_TEST_DATABASE_URL='postgres://postgres:postgres@localhost:5432/postgres?sslmode=disable'
go test -tags integration -race -count=1 -v ./pgstore/
# --- PASS: TestConcurrentCheckoutsNeverOversell 20 checkouts, 5 units: ok 5, oos 15, reserved 5
# --- PASS: TestSameIdempotencyKeyConcurrentlyCreatesOneOrder 1 row in orders
# Then try it by hand in two psql sessions:
# A: BEGIN; SELECT * FROM inventory WHERE product_id = 1 FOR UPDATE;
# B: BEGIN; SELECT * FROM inventory WHERE product_id = 1 FOR UPDATE; -- waits
# A: UPDATE inventory SET reserved = reserved + 1 WHERE product_id = 1; COMMIT;
# B: (returns the committed row) ... SET lock_timeout = '1s' makes B fail with 55P03 instead۶. RabbitMQ و گیرندهٔ واقعی SMTP؛ مورد انتظار، اجرا نشده
# Memory store (no ECOM_DATABASE_URL): with PostgreSQL you would first run the migration
# and insert users 1 and 7, because the dev tokens' user ids are foreign keys there.
# Mailpit listens for SMTP on 1025 and shows mails on http://localhost:8025; it offers
# neither STARTTLS nor AUTH by default, so for this local test change mailer.NewSMTP to
# mail.TLSOpportunistic and mail.WithSMTPAuth(mail.SMTPAuthNoAuth) (or start Mailpit with TLS and auth).
ECOM_AMQP_URL=amqp://guest:guest@localhost:5672/ \
ECOM_SMTP_HOST=localhost ECOM_SMTP_PORT=1025 ECOM_WEBHOOK_SECRET=whsec_dev go run ./cmd/api
# rabbitmqadmin list exchanges -> shop.events topic durable
# bind a queue to "order.*" and place an order:
# message: routing_key=order.placed, message_id=order.placed:ord_...:v1, delivery_mode=2
# Mailpit shows "Your order ord_..." with a text and an HTML part۷. تولید مستندات یا کد از قرارداد؛ مورد انتظار، اجرا نشده
go install github.com/swaggo/swag/cmd/swag@latest
swag init -g cmd/api/main.go -d .,./httpapi -o ./docs # Swagger 2.0 from the annotations
# docs/swagger.json lists /v1/orders post with the Idempotency-Key header parameter
go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen@latest \
-generate types,std-http-server -package api httpapi/openapi.json > /tmp/api.gen.go
# ServerInterface with one method per operation; needs a Go version newer than this module's (see above)برای توسعهدهندگان PHP/Laravel
معادل فروشگاه در Laravel برای تقریباً هر بخش این فصل قابلیت Framework دارد؛ مفهومها هماناند و پیشفرضها فرق میکنند.
| موضوع | این پروژهٔ Go | Laravel 13 |
|---|---|---|
| Model و رابطهها | Structهای domain و Repository | Modelهای Eloquent، hasMany، belongsTo، belongsToMany |
| قفل موجودی | SELECT ... FOR UPDATE در pgstore | Product::whereKey($id)->lockForUpdate()->first() داخل DB::transaction |
| Retry روی Deadlock | InTx روی 40001/40P01 | DB::transaction(fn, attempts: 5)؛ Retry "when a deadlock occurs" |
| پول | money.Money با int64 | ستون صحیح، brick/money؛ Cashier مبلغ Stripe را صحیح ذخیره میکند |
| پرداخت | Payment intent و Webhook | Laravel Cashier: "an expressive, fluent interface to Stripe's subscription billing services" |
| رویداد پس از Commit | Outbox داخل Transaction | dispatch(...)->afterCommit() یا after_commit روی اتصال Queue |
| ایمیل تأیید | go-mail و Worker | Mailable implements ShouldQueue |
| Retry | worker.Retry و Backoff در Relay | $tries، backoff() و جدول Failed jobs |
| جستوجو | ILIKE / tsvector | Laravel Scout با Database engine: "MySQL / PostgreSQL full-text indexes and LIKE clauses" |
| اعتبارسنجی | ValidationError و 422 Problem | Form Requests و 422 JSON |
| Auth | Principal و Guardهای customer/admin | Token یا Session در Sanctum، Gates و Policies؛ Gate::authorize('view', $order) |
| زمانبند (Scheduler) | Tickerهای RunJobs | Schedule::job(...)->everyMinute() |
<?php
namespace App\Actions;
use App\Mail\OrderConfirmation;
use App\Models\Cart;
use App\Models\Order;
use App\Models\Product;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
final class PlaceOrder
{
// Migration: idempotency_keys has a primary key (user_id, key), like the Go schema.
public function __invoke(Cart $cart, string $idempotencyKey, string $fingerprint): Order
{
return DB::transaction(function () use ($cart, $idempotencyKey, $fingerprint) {
// 1. Claim the key FIRST, before any other work. On PostgreSQL insertOrIgnore is
// INSERT ... ON CONFLICT DO NOTHING: a concurrent duplicate waits here on the
// primary key until the first request commits (or rolls back).
$orderId = (string) Str::ulid();
DB::table('idempotency_keys')->insertOrIgnore([
'user_id' => $cart->user_id, 'key' => $idempotencyKey,
'fingerprint' => $fingerprint, 'order_id' => $orderId, 'created_at' => now(),
]);
$claim = DB::table('idempotency_keys')
->where('user_id', $cart->user_id)->where('key', $idempotencyKey)->first();
if ($claim->order_id !== $orderId) { // someone else holds the key: replay
abort_if($claim->fingerprint !== $fingerprint, 422, 'Idempotency-Key reused with another body');
return Order::findOrFail($claim->order_id);
}
// 2. Lock stock rows in id order, then reserve, all or nothing.
$items = $cart->items()->orderBy('product_id')->get();
$products = Product::whereIn('id', $items->pluck('product_id'))
->orderBy('id')->lockForUpdate()->get()->keyBy('id'); // SELECT ... FOR UPDATE
$order = Order::create([
'id' => $orderId, 'user_id' => $cart->user_id, 'status' => 'created',
'expires_at' => now()->addMinutes(15),
]);
$total = 0;
foreach ($items as $item) {
$product = $products[$item->product_id];
// Throwing rolls everything back, the key claim included.
abort_if($product->stock_on_hand - $product->stock_reserved < $item->qty, 409, 'out of stock');
$product->increment('stock_reserved', $item->qty);
$order->items()->create([
'product_id' => $product->id, 'qty' => $item->qty,
'unit_minor' => $product->price_minor, 'name' => $product->name,
]);
$total += $product->price_minor * $item->qty;
}
$order->update(['total_minor' => $total]);
$cart->delete();
Mail::to($cart->user)->queue((new OrderConfirmation($order))->afterCommit());
return $order;
}, attempts: 3);
}
}کلید به همان دلیل کد Go ابتدا تصاحب میشود. اگر اول بررسی و آخر درج شود، یا روی سفارش نگه داشته شود، دو درخواست همزمان با یک کلید هر دو «سفارشی نیست» میبینند؛ دومی پشت قفل موجودی منتظر میماند و بعد یا سفارش دوم میسازد یا با Unique index بهجای بازپخش خطا میگیرد. insertOrIgnore که "will ignore errors while inserting records into the database"، همراه خواندن دوبارهٔ سطر، دو حالت را بدون وابستگی به مقدار بازگشتی از هم جدا میکند. abort_if هم "throws an HTTP exception if a given boolean expression evaluates to true".
مقایسه در یک بند: Laravel، lockForUpdate، Retry برای Deadlock، Dispatch پس از Commit، ایمیل صفشده و Scout را آماده میدهد، پس فروشگاه درست با کد کمتر ساخته میشود. در Go هر کدام یک خط صریح است که میخوانید و تست میکنید. دو دام در هر دو یکسان است. afterCommit() منتظر Commit میماند ولی جزئی از آن نیست؛ Crash بعد از Commit و پیش از فرستادن Job به Redis، ایمیل را گم میکند. پس رویداد باارزش در Laravel هم جدول Outbox میخواهد. همچنین متدهای راحت Cashier کلید Idempotency سمت PSP را پنهان میکنند؛ Payment Processing Architecture نشان میدهد چطور صریح آن را بدهید.
بدفهمیهای رایج (Common misconceptions)
| باور | واقعیت |
|---|---|
| «Transaction جلوی فروش اضافه را میگیرد.» | فقط با قفل سطر، Update شرطی، Version check یا SERIALIZABLE و Retry؛ READ COMMITTED بهتنهایی به دو Checkout اجازه میدهد یک موجودی را بخوانند. |
| «سبد برای سرعت باید قیمت ذخیره کند.» | سبد فقط محصول و تعداد دارد؛ قیمت هنگام Checkout و داخل Transaction خوانده میشود. |
| «Unique constraint، POST را Idempotent میکند.» | Retry را خطا میکند؛ Idempotency نتیجهٔ اول را برمیگرداند و استفادهٔ کلید با Body دیگر را با 422 رد میکند. |
| «رویداد را بلافاصله پس از Commit منتشر کن.» | Crash در فاصلهٔ آن دو، رویداد را گم میکند؛ در همان Transaction داخل Outbox بنویسید. |
| «Outbox تحویل دقیقاً یک بار میدهد.» | تحویل حداقل یک بار همراه Dedupe مصرفکننده با Inbox و شناسهٔ قطعی، اثر دقیقاً یک بار میدهد؛ فاصلهٔ بین موفقیت SMTP و Inbox.Mark هنوز میتواند دوباره بفرستد، و Message-ID برابر Event id آن ارسال دوباره را قابلشناسایی میکند. |
| «برداشت پول داخل Transaction خرید امنتر است.» | قفل طی فراخوانی کند و Rollbackناپذیر با نتیجهٔ نامعلوم نگه داشته میشود؛ Intent را ثبت کنید، بیرون پرداخت و رویداد تأییدشده را اعمال کنید. |
| «Cancel و Refund یک Transition هستند.» | Cancel پیش از پرداخت و برای آزادسازی موجودی است؛ Refund پس از جابهجایی پول. ماشین حالت paid → cancelled ندارد. |
| «بررسی ورود روی Route سفارشها را محافظت میکند.» | مجوز هر شیء هم لازم است؛ Bob باید برای سفارش Alice پاسخ 404 بگیرد. |
| «Store حافظهای تست، قفلها را اثبات میکند.» | قواعد کسبوکار را اثبات میکند؛ Mutex واحدش از PostgreSQL قویتر است. Integration test قفلها را اثبات میکند. |
| «swag خروجی OpenAPI 3 دارد.» | Swagger 2.0 تولید میکند؛ برای 3.x مبدل یا مولد Spec-first به کار ببرید. |
«Shutdown درخواست جاری را لغو میکند.» | پذیرش را میبندد و منتظر میماند؛ با Context کوتاهتر از مهلت Orchestrator محدودش کنید. |
| «ایمیل را تا موفقیت Retry کن.» | شکست موقت (4xx و خطای شبکه با کد 0) را با Backoff سقفدار Retry کنید؛ روی دائمی 5xx متوقف شوید و هشدار بدهید. |
«ILIKE '%x%' از Index من استفاده میکند.» | از B-tree نه؛ وقتی Search مهم شد pg_trgm یا tsvector با GIN به کار ببرید. |
چکیده (Cheat sheet)
| موضوع | به یاد بسپارید |
|---|---|
| پول (Money) | واحد کوچک int64 همراه ISO code؛ Half-even؛ Allocate تا جمع بخشها برابر کل باشد |
| قیمتگذاری (Pricing) | تابع خالص از ردیف، تخفیف و نرخ به جمعها؛ مالیات هر ردیف روی خالص |
| ردیف سفارش (Order item) | Snapshot از SKU، نام، قیمت، تخفیف و مالیات هنگام خرید |
| موجودی (Stock) | on_hand، reserved؛ قفل به ترتیب Product id؛ CHECK (reserved <= on_hand) |
| ثبت خرید (Checkout) | یک Transaction: اول Lookup و تصاحب کلید، سپس سبد، قیمت، رزرو، سفارش، Payment intent، Outbox و حذف سبد |
| تکرارپذیری (Idempotency) | Scope بر اساس کاربر و Route، Fingerprint از Body، تصاحب پیش از هر کار؛ 400 برای نبودن، 422 برای استفادهٔ مجدد کلید، 409 busy پس از lock_timeout؛ اعتبار 24 ساعت |
| کلید PSP | مشتقشده: <order>:attempt:<n>؛ هرگز UUID تازه برای هر فراخوانی |
| ماشین حالت (State machine) | created → paid → fulfilled، created → cancelled، paid/fulfilled → refunded؛ Version در هر Transition |
| Capture دیررس | سفارش لغوشده میماند، پرداخت refund_pending میشود |
| صندوق خروجی (Outbox) | سطر در Transaction، یک Relay، توقف در اولین شکست، Dedupe مصرفکننده با Event id |
| ایمیل (Mail) | go-mail، STARTTLS اجباری، html/template، Message-ID برابر Event id، Retry برای 4xx و خطای شبکه (کد 0)، هرگز برای 5xx |
| Workerها | پیش از عمل دوباره بخوانید و بررسی کنید؛ SKIP LOCKED برای Scan دستهای؛ پایان کار جاری در Shutdown |
| کاتالوگ (Catalogue) | Keyset روی (sort, id)، Cursor مبهم، Sort مجاز، ابتدا ILIKE بعد tsvector |
| احراز و مجوز (Auth) | Middleware، Principal را تنظیم میکند؛ Route guard پاسخ 401/403، بررسی شیء پاسخ 404 |
| خطاها (Errors) | RFC 9457 با problem+json و request_id؛ یک تابع نگاشت |
| قرارداد (Contract) | فایل OpenAPI 3.1 و تست حضور همهٔ Routeها در آن |
| عملیات (Ops) | پیکربندی محیطی با Fail-fast، /healthz و /readyz، NotifyContext، Image چندمرحلهای Distroless، Migration در مرحلهٔ استقرار |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — چرا سبد قیمت ذخیره نمیکند و Checkout قیمت را از کجا میگیرد؟ حیاتی
پاسخ
پاسخ: قیمت سبد بهمحض تغییر کاتالوگ کهنه میشود و قیمتی که از کلاینت عبور کند قابل دستکاری است. سبد فقط شناسهٔ محصول و تعداد دارد؛ PlaceOrder قیمت جاری هر محصول را داخل Transaction خرید میخواند، جمعها را با pricing.Quote حساب میکند و نتیجه را به شکل Snapshot در ردیفهای سفارش کپی میکند. ببینید سبد و ثبت سفارش.
۲ — دو مشتری همزمان آخرین واحد را در PostgreSQL READ COMMITTED میخرند. چه چیزی مانع موفقیت هر دو میشود و آخرین دفاع پایگاه داده چیست؟ حیاتی
پاسخ
پاسخ: Inventory().Reserve سطرهای موجودی را با SELECT ... ORDER BY product_id FOR UPDATE قفل میکند؛ Transaction دوم منتظر قفل میماند، سپس سطر Commitشده را با موجودی قابل فروش 0 میخواند و OutOfStockError با 409 میدهد. پشتیبان نهایی CHECK (reserved <= on_hand) است که هر باگ منجر به فروش اضافه را خطا میکند. قفل به ترتیب شناسهٔ محصول جلوی Deadlock سبدهای چندکالایی را میگیرد. ببینید موجودی.
۳ — کارهای داخل Transaction خرید را به ترتیب بگویید. حیاتی
پاسخ
پاسخ: کلید Idempotency را جستوجو کنید تا Replay یا 422 مشخص شود و اگر تازه بود فوراً تصاحبش کنید؛ سبد و قیمت جاری را بخوانید و قیمتگذاری کنید؛ همهٔ ردیفها را به ترتیب id رزرو کنید؛ سفارش با created، Version برابر 1 و expires_at و ردیفهایش را درج کنید؛ Payment intent با کلید مشتقشدهٔ PSP را درج کنید؛ order.placed را در Outbox بنویسید؛ سبد را حذف و Commit کنید. پیش از Commit هیچ Publish یا ارسال ایمیلی رخ نمیدهد. ببینید ثبت سفارش.
۴ — کلاینت روی POST /v1/orders Timeout میخورد و با همان Idempotency-Key، حین Commit درخواست اول Retry میکند. چه میگیرد و چرا 409 نه؟ مهم
پاسخ
پاسخ: تصاحب کلید اولین Write در Transaction خرید است؛ پس INSERT تکرار در idempotency_keys روی Primary key منتظر Commit اول میماند. سپس ON CONFLICT چیزی را تغییر نمیدهد، Store مقدار ErrDuplicateKey میدهد، InTx مورد کاربرد را دوباره اجرا میکند و Lookup رکورد را پیدا و سفارش را با Idempotent-Replayed: true بازپخش میکند. اگر کلید فقط آخر کار تصاحب میشد، تکرار پشت سطر موجودی منتظر میماند و برای سفارش خودش 409 کمبود موجودی میگرفت. پاسخ 409 با busy فقط وقتی میآید که انتظار از lock_timeout بگذرد، با 55P03. ببینید Idempotency.
۵ — چرا وضعیت سفارش را مستقیم از آخرین Webhook تنظیم نمیکنیم؟ حیاتی
پاسخ
پاسخ: Webhookها تکرار میشوند و خارج از ترتیب میرسند. ماشین حالت فقط created → paid | cancelled، paid → fulfilled | refunded و fulfilled → refunded را اجازه میدهد؛ رویداد تکراری یا دیررس یالی پیدا نمیکند و چیزی را تغییر نمیدهد. هر Transition یک Version را افزایش میدهد که Repository بررسی میکند، پس دو نویسندهٔ همزمان هر دو برنده نمیشوند. ببینید ماشین حالت سفارش.
۶ — مهلت موجودی، سفارش پرداختنشده را لغو میکند و یک ثانیه بعد PSP موفقیت پرداخت را اعلام میکند. سیستم چه میکند؟ مهم
پاسخ
پاسخ: سفارش را زنده نمیکند، چون ممکن است موجودی آن فروخته شده باشد. ApplyPayment، سفارش cancelled را میبیند، پرداخت را refund_pending میکند و payment.refund_requested را در Outbox مینویسد؛ سیستم پرداخت با کلید مشتقشدهٔ خودش Refund میکند. اگر Capture زودتر برنده میشد، خواندن دوبارهٔ Job وضعیت paid را میدید و از آن میگذشت. ببینید Workerهای پسزمینه.
۷ — چرا رویداد را در جدول Outbox مینویسیم و بعد از Commit مستقیم به RabbitMQ نمیفرستیم؟ مصرفکننده چه لازم دارد؟ حیاتی
پاسخ
پاسخ: Crash میان Commit و Publish رویداد را گم میکند؛ Publish پیش از Commit هم سفارشهایی را اعلام میکند که شاید Rollback شوند. سطر Outbox همراه سفارش Commit میشود، Relay بعداً منتشر و علامتگذاری میکند؛ پس تحویل حداقل یک بار است. مصرفکننده باید با Event id قطعی، مثلاً Inbox به نام processed_events، تکرار را حذف کند تا تحویل حداقل یک بار به اثر دقیقاً یک بار برسد. ببینید رویدادها.
۸ — ایمیل تأیید چطور از ارسال دوباره یا هرگز ارسال نشدن جلوگیری میکند؟ مهم
پاسخ
پاسخ: محرکش order.placed از Outbox است، پس Crash داخل درخواست آن را گم نمیکند. Worker پیش از ارسال Inbox را بررسی و بعد از موفقیت علامت میزند؛ Crash در فاصلهٔ این دو باعث ارسال مجدد میشود، نه گم شدن. خطای موقت SMTP با Exponential backoff سقفدار و Jitter دوباره تلاش میشود، خطای دائمی 5xx متوقف میشود و Message-ID برابر Event id است. ببینید ایمیل SMTP.
۹ — Bob وارد شده و GET /v1/orders/ord_alice میخواهد. مسیر بررسیها و پاسخ را توضیح دهید. حیاتی
پاسخ
پاسخ: Middleware هویت Bob را تأیید و Principal او را در Context میگذارد؛ Guard به نام customer عبور میدهد. Service سفارش را میخواند، CanSee(ownerID) شکست میخورد و ErrNotFound میدهد. API پاسخ 404، نه 403، میدهد تا وجود سفارش را تأیید نکند؛ این همان بررسی سطح شیء OWASP با نام API1:2023 است. ببینید احراز هویت و مجوز.
۱۰ — چرا برای کاتالوگ Keyset انتخاب میکنیم و Cursor باید چه چیزهایی داشته باشد؟ مهم
پاسخ
پاسخ: OFFSET سطرها را میخواند و دور میریزد و با درج محصول میان صفحهها جابهجا میشود؛ Keyset با Index از «بعد از این سطر» ادامه میدهد. Cursor ترتیب Sort، مقدار Sort و id برای شکستن تساوی را بهصورت مبهم Encode میکند و برای Sort دیگر پذیرفته نمیشود. ببینید فهرست کاتالوگ.
۱۱ — در این پروژه چه وقت SELECT ... FOR UPDATE و چه وقت ستون Version خوشبینانه انتخاب میکنید؟ مهم
پاسخ
پاسخ: برای بخش بحرانی داغ و کوتاه، یعنی موجودی حین Checkout، قفل سطر میگیریم؛ نویسندههای خوشبینانه زیر رقابت اغلب میبازند و Retry میکنند. برای ویرایش کند یا کمرقابت، مثل تغییر قیمت Admin با If-Match یا تغییر وضعیت سفارش توسط Job و Webhook، Version میگذاریم تا هنگام فکر کردن انسان قفلی نگه داشته نشود. ببینید قفل یا Version برای موجودی.
۱۲ — Serviceها بدون پایگاه داده چطور تست میشوند و این تست چه چیزی را ثابت نمیکند؟ تکمیلی
پاسخ
پاسخ: تستهای Table-driven، Service واقعی را روی memstore اجرا میکنند؛ پیادهسازی جعلی و کارکردی (working fake) از همهٔ Repositoryها با Rollback و Version check، همراه ساعت جعلی. Handlerها هم با httptest بررسی میشوند. Store حافظهای Transactionها را با یک Mutex سری میکند، پس قواعد کسبوکار را اثبات میکند، نه قفل PostgreSQL، ON CONFLICT یا Constraintها را؛ اینها با تستهای دارای Tag به نام integration روی پایگاه دادهٔ واقعی بررسی میشوند. ببینید تست.
۱۳ — برای این API، swag یا oapi-codegen؟ در هر روش درستی قرارداد را چطور حفظ میکنید؟ تکمیلی
پاسخ
پاسخ: swag، Code-first است و از Annotation، Swagger 2.0 میسازد؛ oapi-codegen، Spec-first است و از OpenAPI 3.0/3.1 نوعهای Go و Interface سرور تولید میکند؛ Runtime فعلی آن Go 1.26 میخواهد. در هر روش، تست باید با فاصله گرفتن کد و قرارداد شکست بخورد. اینجا TestEveryRouteIsInTheOpenAPIDocument جدول Routeها را پیمایش و وجود هر Method و Path در openapi.json را بررسی میکند. ببینید Swagger/OpenAPI.
۱۴ — پس از SIGTERM، قدمبهقدم چه اتفاقی میافتد؟ تکمیلی
پاسخ
پاسخ: signal.NotifyContext، Context ریشه را Cancel میکند. app.Serve، http.Server.Shutdown را با ShutdownTimeout صدا میزند؛ Listener و اتصال Idle بسته میشوند و منتظر درخواستهای فعال میماند. سپس Context پسزمینه لغو میشود و تا پایان اجرای جاری Relay و Jobها صبر میکند؛ فرایند «stopped» را Log میکند و خارج میشود. ببینید استقرار.
واژهنامه (Glossary)
| اصطلاح | معنا |
|---|---|
| سبد رهاشده (Abandoned cart) | سبد مشتری با کالا که بیش از AbandonedAfter بیفعالیت بوده و هنوز یادآوری نگرفته است |
| تجمیع (Aggregate) | مجموعهٔ اشیایی که با یک ریشه با هم تغییر میکنند؛ سفارش و ردیفهایش |
| تخصیص (Allocate) | تقسیم مبلغ بر اساس وزن، طوری که جمع بخشها دقیقاً برابر کل شود |
| یکصدم درصد (Basis point) | 1/100 درصد؛ 2000 bp = 20 % |
| کارگر پسزمینه (Background worker) | کد بیرون درخواست: Handler رویداد و Job دورهای |
| کاتالوگ (Catalogue) | محصولات و دستههایی که مشتری مرور میکند |
| مقایسه و جایگذاری (Compare-and-set / CAS) | UPDATE ... WHERE version = $n؛ صفر سطر یعنی دیگری برنده شده |
| مکاننما (Cursor) | Token مبهم حامل موقعیت Keyset؛ Sort، مقدار و id |
| شناسهٔ رویداد (Event id) | شناسهٔ قطعی <type>:<aggregate>:v<version> برای حذف تکرار |
| اثر انگشت (Fingerprint) | SHA-256 از Body درخواست که همراه کلید Idempotency ذخیره میشود |
| اجرای سفارش (Fulfilment) | ارسال سفارش پرداختشده؛ تبدیل موجودی رزروشده به موجودی ارسالشده |
| go-mail | github.com/wneessen/go-mail؛ کتابخانهٔ SMTP و MIME برای Go |
| خاموشی مرتب (Graceful shutdown) | توقف پذیرش کار، تمام کردن کار جاری و سپس خروج |
| کلید تکرارپذیری (Idempotency-Key) | Header حاوی کلید کلاینت تا Retry نتیجهٔ اول را برگرداند |
| صندوق ورودی (Inbox) | سابقهٔ شناسهٔ رویداد پردازششده برای هر Consumer؛ processed_events |
| گذرگاه داخل فرایند (In-process bus) | bus.Bus؛ مسیریابی همگام رویداد در یک فرایند |
| موجودی (Inventory / stock) | on_hand و reserved هر محصول؛ قابل فروش تفاضل آنهاست |
| صفحهبندی کلیدمحور (Keyset pagination) | صفحهبندی با (sort value, id) > (last seen) بهجای OFFSET |
| واحد کوچک (Minor unit) | کوچکترین واحد ارز؛ سنت، ین یا فلس |
| قفلگذاری خوشبینانه (Optimistic locking) | تشخیص Write متعارض با Version بهجای نگه داشتن قفل |
| ردیف سفارش (Order item) | Snapshot ردیف خریداریشده؛ SKU، نام، قیمت و مالیات |
| صندوق خروجی (Outbox) | جدول رویدادهایی که در Transaction کسبوکار نوشته و بعداً منتشر میشوند |
| قصد پرداخت (Payment intent) | رکورد محلی یک تلاش برای دریافت مبلغ سفارش، متناظر با PSP |
| قفلگذاری بدبینانه (Pessimistic locking) | SELECT ... FOR UPDATE؛ پیش از تصمیم سطر را قفل کنید |
| هویت فراخواننده (Principal) | فراخوانندهٔ احرازشده با User id، ایمیل و Role |
| جزئیات خطا (Problem Details) | قالب JSON خطای RFC 9457 با application/problem+json |
| ارائهدهندهٔ خدمات پرداخت (PSP) | ارائهدهندهای مانند Stripe یا Adyen |
| واسط انتشار (Relay) | حلقهای که Outbox را میخواند، منتشر میکند و سطرها را علامت میزند |
| تأیید ناشر (Publisher confirms) | Ackهای RabbitMQ که به Publisher میگویند Broker پیام را گرفته است |
| رزرو (Reservation) | نگهداری موجودی برای سفارش پرداختنشده تا پرداخت یا پایان مهلت آزادسازی |
| سبد سمت سرور (Server-side cart) | سبد ذخیرهشده در پایگاه داده با Token در Cookie یا User id |
| لایهٔ سرویس (Service layer) | متدهای مورد کاربرد میان Handler و Repository |
| مهلت آزادسازی موجودی (Stock release timeout) | مهلت expires_at که پس از آن سفارش پرداختنشده لغو میشود |
| swag | swaggo/swag؛ تولید Swagger 2.0 از Commentهای Go |
| oapi-codegen | تولید نوعها، سرورها و کلاینتهای Go از OpenAPI 3.0/3.1 |
| سطل توکن (Token bucket) | الگوریتم Rate limit؛ ظرفیت Burst با نرخ ثابت پر میشود |
بردار متن tsvector | نوع سند Full-text در PostgreSQL با Index از نوع GIN |
| نقص مجوز سطح شیء (BOLA) | Broken Object Level Authorization؛ خواندن شیء کاربر دیگر با id |
| کد SQLSTATE 40001 | serialization_failure؛ Transaction را دوباره اجرا کنید |
| کد SQLSTATE 55P03 | lock_not_available؛ lock_timeout تمام شده است |
منابع (References)
- PostgreSQL documentation, SELECT (locking clause, NOWAIT, SKIP LOCKED) — https://www.postgresql.org/docs/current/sql-select.html
- PostgreSQL documentation, Transaction Isolation — https://www.postgresql.org/docs/current/transaction-iso.html
- PostgreSQL documentation, Explicit Locking — https://www.postgresql.org/docs/current/explicit-locking.html
- PostgreSQL documentation, Constraints — https://www.postgresql.org/docs/current/ddl-constraints.html
- PostgreSQL documentation, Partial Indexes — https://www.postgresql.org/docs/current/indexes-partial.html
- PostgreSQL documentation, Generated Columns — https://www.postgresql.org/docs/current/ddl-generated-columns.html
- PostgreSQL documentation, Appendix A. Error Codes — https://www.postgresql.org/docs/current/errcodes-appendix.html
- PostgreSQL documentation, Text Search introduction and tables — https://www.postgresql.org/docs/current/textsearch-intro.html, https://www.postgresql.org/docs/current/textsearch-tables.html
- PostgreSQL documentation, Pattern Matching (
ILIKE) — https://www.postgresql.org/docs/current/functions-matching.html - PostgreSQL documentation, pg_trgm — https://www.postgresql.org/docs/current/pgtrgm.html
- PostgreSQL documentation, INSERT (
ON CONFLICT) — https://www.postgresql.org/docs/current/sql-insert.html - Stripe, The PaymentIntent lifecycle — https://docs.stripe.com/payments/paymentintents/lifecycle
- Stripe, Idempotent requests — https://docs.stripe.com/api/idempotent_requests
- Stripe, Webhooks — https://docs.stripe.com/webhooks
- Brandur Leach, "Designing robust and predictable APIs with idempotency", Stripe blog (2017) — https://stripe.com/blog/idempotency
- Shopify Engineering, "Building Resilient Payment Systems" (2022) — https://shopify.engineering/building-resilient-payment-systems
- IETF, The Idempotency-Key HTTP Header Field (draft) — https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-idempotency-key-header
- RFC 9457, Problem Details for HTTP APIs — https://www.rfc-editor.org/rfc/rfc9457.txt
- OpenAPI Specification 3.1.0 — https://spec.openapis.org/oas/v3.1.0.html
- swaggo/swag README — https://raw.githubusercontent.com/swaggo/swag/master/README.md
- swaggo/http-swagger README — https://raw.githubusercontent.com/swaggo/http-swagger/master/README.md
- oapi-codegen README — https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/main/README.md
- go-playground/validator README — https://raw.githubusercontent.com/go-playground/validator/master/README.md
- wneessen/go-mail README — https://raw.githubusercontent.com/wneessen/go-mail/main/README.md
- jackc/pgx README and
pgconn/errors.go— https://raw.githubusercontent.com/jackc/pgx/master/README.md, https://raw.githubusercontent.com/jackc/pgx/master/pgconn/errors.go - rabbitmq/amqp091-go README — https://raw.githubusercontent.com/rabbitmq/amqp091-go/main/README.md
- RabbitMQ, Go tutorials one and three — https://www.rabbitmq.com/tutorials/tutorial-one-go, https://www.rabbitmq.com/tutorials/tutorial-three-go
- RabbitMQ, Consumer Acknowledgements and Publisher Confirms — https://www.rabbitmq.com/docs/confirms
- golang-migrate README — https://raw.githubusercontent.com/golang-migrate/migrate/master/README.md
- pressly/goose README — https://raw.githubusercontent.com/pressly/goose/main/README.md
- Chris Richardson, Pattern: Transactional outbox — https://microservices.io/patterns/data/transactional-outbox.html
- Martin Fowler, Money — https://martinfowler.com/eaaCatalog/money.html
- Martin Fowler, Optimistic Offline Lock — https://martinfowler.com/eaaCatalog/optimisticOfflineLock.html
- Markus Winand, "No Offset" — https://use-the-index-luke.com/no-offset
- OWASP REST Security Cheat Sheet — https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html
- OWASP HTTP Headers Cheat Sheet — https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Headers_Cheat_Sheet.html
- OWASP API1:2023 Broken Object Level Authorization — https://owasp.org/API-Security/editions/2023/en/0xa1-broken-object-level-authorization/
- OWASP Input Validation Cheat Sheet — https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html
- golang.org/x/time/rate source — https://raw.githubusercontent.com/golang/time/master/rate/rate.go
- go-mail
go.modat v0.7.2 (go 1.24.0) and v0.7.3 (go 1.25.0) — https://proxy.golang.org/github.com/wneessen/go-mail/@v/v0.7.2.mod, https://proxy.golang.org/github.com/wneessen/go-mail/@v/v0.7.3.mod - go-mail v0.7.2 source (
WithTLSPortPolicy,SetMessageIDWithValue,SendError.IsTemp) — https://raw.githubusercontent.com/wneessen/go-mail/v0.7.2/client.go, https://raw.githubusercontent.com/wneessen/go-mail/v0.7.2/msg.go, https://raw.githubusercontent.com/wneessen/go-mail/v0.7.2/senderror.go - pgx
go.modat v5.8.0 (go 1.24.0) and v5.9.0 (go 1.25.0), and CHANGELOG (5.12.0 security fixes) — https://raw.githubusercontent.com/jackc/pgx/v5.8.0/go.mod, https://raw.githubusercontent.com/jackc/pgx/v5.9.0/go.mod, https://raw.githubusercontent.com/jackc/pgx/master/CHANGELOG.md - amqp091-go v1.17.0 source (
PublishWithDeferredConfirmWithContext,DeferredConfirmation.WaitContext,Connection.NotifyClose) — https://raw.githubusercontent.com/rabbitmq/amqp091-go/v1.17.0/channel.go, https://raw.githubusercontent.com/rabbitmq/amqp091-go/v1.17.0/confirms.go, https://raw.githubusercontent.com/rabbitmq/amqp091-go/v1.17.0/connection.go - Martin Fowler, Patterns of Enterprise Application Architecture (book page) and Repository — https://martinfowler.com/books/eaa.html, https://martinfowler.com/eaaCatalog/repository.html
- Go source,
net/http/server.go(Shutdown) — https://go.dev/src/net/http/server.go - Go source,
net/smtp/smtp.go— https://go.dev/src/net/smtp/smtp.go - Go 1.22, 1.23, 1.24 and 1.25 release notes — https://go.dev/doc/go1.22, https://go.dev/doc/go1.23, https://go.dev/doc/go1.24, https://go.dev/doc/go1.25
- Go blog, Routing Enhancements for Go 1.22 — https://go.dev/blog/routing-enhancements
- The Twelve-Factor App, Config — https://12factor.net/config
- Docker, Multi-stage builds — https://docs.docker.com/build/building/multi-stage/
- Laravel 13: Eloquent relationships, queries, database, queues, mail, events, scheduling, authorization, validation, Sanctum, Cashier (Stripe), Scout — https://laravel.com/docs/13.x/eloquent-relationships, https://laravel.com/docs/13.x/queries, https://laravel.com/docs/13.x/database, https://laravel.com/docs/13.x/queues, https://laravel.com/docs/13.x/mail, https://laravel.com/docs/13.x/events, https://laravel.com/docs/13.x/scheduling, https://laravel.com/docs/13.x/authorization, https://laravel.com/docs/13.x/validation, https://laravel.com/docs/13.x/sanctum, https://laravel.com/docs/13.x/billing, https://laravel.com/docs/13.x/scout, https://laravel.com/docs/13.x/helpers (
abort_if), https://laravel.com/docs/13.x/strings (Str::ulid), https://laravel.com/docs/13.x/eloquent