Skip to content

Context Maps & Integration Patterns: Partnership, Shared Kernel, Customer-Supplier, Conformist, ACL, OHS/PL, Separate Ways ​

"Describe the points of contact between the models, outlining explicit translation for any communication, highlighting any sharing, isolation mechanisms, and levels of influence. Map the existing terrain. Take up transformations later." — Eric Evans، Domain-Driven Design Reference (۲۰۱۵)، بخش "Context Map"

خلاصه (Summary): نقشهٔ کانتکست (Context Map) تصویری از واقعیتِ امروز است: چه bounded contextهایی داریم، چه کسی به چه کسی وابسته است، در هر لبه مدلِ کدام طرف برنده است و هزینهٔ ترجمه را چه کسی می‌دهد. الگوها (Partnership، Shared Kernel، Customer-Supplier، Conformist، Anticorruption Layer، Open Host Service، Published Language، Separate Ways، Big Ball of Mud) نام همین رابطه‌ها هستند. تمرکز (Focus): بالادست و پایین‌دست به‌معنای قدرت، هر نُه الگو به‌تفصیل (کی پیش می‌آید، رابطهٔ تیم‌ها، هزینه، شکل کد، ریسک، راه خروج)، نشانه‌گذاری U/D از cheat sheet گروه DDD-crew و Context Mapper، نوع ارتباط روی نقشه، لایهٔ تیم‌ها، تکامل نقشه، نقشه درون modular monolith، و نقشهٔ مثال جاری با کد Go و Laravel: یک ACL جلوی ERP قدیمی، یک Open Host Service با قرارداد event منتشرشده، یک مصرف‌کنندهٔ conformist، یک shared kernel نسخه‌دار و contract test روی لبه. هدف یادگیری (Learning goal): نقشهٔ کانتکستِ یک سیستم واقعی را با نشانه‌گذاری درست بکشید، روی هر لبه رابطه و هزینه‌اش را نام ببرید، برای یکپارچه‌سازی تازه الگوی درست را انتخاب کنید، و ACL، OHS/PL و shared kernel را طوری پیاده کنید که انتخاب‌تان با کد و تست اجرا شود، نه با حسن نیت.

این فصل گروه DD 01 (طراحی راهبردی) را می‌بندد. فرض می‌کند bounded context را پیدا کردن بلدید و می‌دانید چرا هر کدام زبان مشترک (Ubiquitous Language) خودش را دارد؛ از انواع زیردامنه (Subdomain) (core، supporting، generic) برای تصمیم دربارهٔ سرمایه‌گذاری استفاده می‌کند. پرسشی که این صفحه صاحبش است: دو کانتکست چه رابطه‌ای دارند و با شرایطِ چه کسی؟ بقیه را همسایه‌ها می‌گویند: خط سرویس‌ها کجا می‌رود و چه هزینه‌ای دارد (Service Boundaries)، بایت‌ها چطور جابه‌جا می‌شوند (Service Communication)، چه کسی صاحب کدام جدول است (مالکیت داده در Microservices)، انتشار مطمئن (Transactional Outbox)، تفاوت domain event و integration event (Domain Events vs Integration Events) و تکامل schema (Message Design & Schema Evolution).

نقشهٔ صفحه (Page map) ​

دنبال چه هستیدبروید به
کل فصل در سه جدولهمه‌چیز در یک دقیقه
چرا نقشه، و چرا «امروز، نه ایده‌آل»چرا Context Map وجود دارد
از Evans ۲۰۰۳ تا DDD-crew و Context Mapperاز کجا آمده
Context map چیست و چه نیستنقشهٔ کانتکست
مدل را چه کسی تعیین می‌کند، ترجمه را چه کسی می‌پردازدبالادست، پایین‌دست و قدرت
نُه الگو، هر کدام یک بلوکPartnership، Shared Kernel، Customer-Supplier، Conformist، Anticorruption Layer، Open Host Service، Published Language، Separate Ways، Big Ball of Mud
U/D، OHS، PL، ACL، CF، SK، P روی نقشهنشانه‌گذاری
API هم‌زمان، event ناهم‌زمان، DB مشترک روی نقشهنوع ارتباط
وابستگی متقابل، بالادست/پایین‌دست، آزادلایهٔ رابطهٔ تیم‌ها
از ACL به OHS، از shared kernel به separate waysتکامل نقشه
Sales، Fulfilment، Billing، Catalog، Identity، ERPنقشهٔ مثال جاری
قدم‌های کارگاه، فایل CML، قواعد نسخه‌گذاریسازوکار
ACL، OHS/PL، conformist، shared kernel، contract testGo، Laravel
ERP قدیمی، SaaS، شکستن قرارداد، kernel متورمحل مسئله‌های کلاسیک
کدام الگو کِیانتخاب
از monolith تا دادهٔ توزیع‌شدهدر معماری
تمرین عملیآزمایشگاه
باورهای غلط، خلاصه، آزمون، واژه‌هابدفهمی‌ها، چکیده، خودآزمایی، واژه‌نامه

همه‌چیز در یک دقیقه ​

الگوها. هر سطر در فهرست مفاهیم باز می‌شود. «چه کسی می‌پردازد» یعنی هزینهٔ ترجمه و تغییر روی دوش کیست.

الگونشانهبه زبان سادهچه کسی می‌پردازدلبهٔ نمونه در فروشگاه ما
PartnershipP (متقارن)دو تیمی که با هم موفق یا شکست می‌خورند، با هم برنامه‌ریزی و منتشر می‌کنندهر دو، در جلسه‌هاSales و Fulfilment در راه‌اندازی click-and-collect
Shared KernelSK (متقارن)تکه‌ای کوچک از مدل و کد که مال هر دو تیم استهر دو، در هماهنگیMoney، Currency، قاعدهٔ گرد کردن (Sales، Billing)
Customer-SupplierU/S، D/Cنیازهای پایین‌دست وارد برنامه‌ریزی بالادست می‌شودبالادست در برنامه‌ریزی؛ پایین‌دست در درخواستSales (تأمین‌کننده) به Fulfilment (مشتری)
ConformistD، CFپایین‌دست مدل بالادست را همان‌طور که هست می‌پذیردپایین‌دست، با مدلی ضعیف‌ترSales مدل محصولِ Catalog را به کار می‌برد
Anticorruption LayerD، ACLپایین‌دست در لبهٔ خودش ترجمه می‌کندپایین‌دست، با کدی که مال خودش استSales هنگام خواندن ERP قدیمی
Open Host ServiceU، OHSیک پروتکل باز برای همهٔ مصرف‌کنندگانبالادست، با نگهداری APIeventهای Sales، OIDCِ Identity
Published LanguageU، PLقالب تبادل مستند، نه مدل داخلیبالادست، با حاکمیت schemaJSON Schemaِ sales.order.placed.v1
Separate Waysنداردیکپارچه نکن؛ کمی تکرار را بپذیرهیچ‌کس، تا وقتی نیاز عوض شودBilling و Catalog
Big Ball of MudBBoM (مرز)درهم‌ریختگی بی مرز درونی؛ دورش دیوار بکشهر کسی که به آن دست بزندERP قدیمی

قدرت و هزینه روی یک لبه.

پرسشپاسخ بالادستپاسخ پایین‌دست
روی سیم مدل چه کسی است؟مال من (OHS/PL)، مگر مذاکره کنیممال آن‌ها (CF) یا مال من پشت مترجم (ACL)
وقتی دیگری تغییر کند چه کسی باید عوض شود؟هیچ‌کس، طبق تعریفمن، در ACL یا همه‌جا (CF)
چه چیزی می‌توانم بخواهم؟هیچ؛ من تصمیم می‌گیرماولویت (C/S)، هیچ (CF/ACL)، برنامهٔ مشترک (P)
چه چیزی از من محافظت می‌کند؟نسخه‌گذاری، سیاست deprecationcontract test در CI بالادست، یک ACL

ارتباط روی نقشه.

علامت روی لبهمعناسالم برایبو (smell) وقتی
API هم‌زمان (REST، gRPC)پایین‌دست هنگام درخواست بالادست را صدا می‌زندپرس‌وجوهایی که دادهٔ تازه می‌خواهندفراخوانی روی هر درخواست است و بالادست کند است
event ناهم‌زمان (broker)بالادست منتشر می‌کند، پایین‌دست واکنش نشان می‌دهدواقعیت‌هایی که بقیه به آن واکنش دارندپایین‌دست همین حالا جواب می‌خواهد
خروجی فایل / batchdump دوره‌ایسیستم قدیمی، تحلیلتصمیم کسب‌وکار منتظر job شبانه می‌ماند
دیتابیس مشترکهر دو جدول‌های یکسان را می‌خوانند یا می‌نویسندهیچ‌وقت بین کانتکست‌هاهمیشه: قرمزش کنید

چرا Context Map وجود دارد ​

سیستمی که بیش از یک bounded context دارد لبه دارد، و هر لبه یک رابطه را حمل می‌کند، چه کسی اسمش را گذاشته باشد چه نه. وقتی بی‌نام است، تیم پایین‌دست آن را به سخت‌ترین شکل کشف می‌کند: یک تغییر نام در بالادست production را می‌شکند، درخواست یک فیلد اضافه سه ماه در backlog می‌ماند، قالب رکوردهای سیستم قدیمی هر بار با یک if تازه وارد مدل اصلی می‌شود. Evans مسئله را در Reference این‌طور می‌گوید: "People on other teams won’t be very aware of the context boundaries and will unknowingly make changes that blur the edges or complicate the interconnections. When connections must be made between different contexts, they tend to bleed into each other."

نقشهٔ کانتکست برای هر لبه سه چیز را صریح می‌کند: جهت نفوذ (بالادست یا پایین‌دست)، سازوکار فنی (API، event، کد مشترک، مترجم) و قرارداد اجتماعی (شریک، مشتری و تأمین‌کننده، یا «همین است که هست»). Vaughn Vernon در پیش‌گفتار Implementing DDD می‌گوید: "Context Maps are a powerful tool to help a team understand their business domain, the boundaries between distinct models, and how they are currently, or can be, integrated."

بدون نقشهبا نقشه
برای هر یکپارچه‌سازی «فقط API شان را صدا می‌زنیم»هر لبه الگوی نام‌دار و صاحبِ ترجمه دارد
تغییرات بالادست تیم‌های پایین‌دست را غافلگیر می‌کندلبه‌های customer-supplier در CI بالادست contract test دارند
اصطلاحات سیستم قدیمی به مدل اصلی نشت می‌کنندیک ACL آن‌ها را در لبه نگه می‌دارد
یک کتابخانهٔ مشترک به دامنهٔ مشترک تبدیل می‌شودshared kernel سقف اندازه و سیاست نسخه‌گذاری دارد
نمودار معماری آرزو را نشان می‌دهدنقشه امروز را نشان می‌دهد؛ هدف نقشهٔ دوم است
مناسب برای: هیچ چیز فراتر از یک تیممناسب برای: هر سیستمی با دو تیم یا دو کانتکست به بالا

تشبیهی که در این صفحه بارها برمی‌گردیم: رودخانه‌ها و پل‌های یک شهر. تصویر خود Evans برای بالادست و پایین‌دست دو شهر کنار یک رودخانه است: "the upstream city’s pollution primarily affects the downstream city." نقشهٔ کانتکست نقشهٔ شهری است که هر پل و هر رود را علامت زده. بعضی پل‌ها پروژهٔ مشترک‌اند (partnership)، بعضی شهرها یک تصفیه‌خانهٔ آب مشترک دارند (shared kernel)، بعضی شهرهای پایین‌دست می‌توانند به شورای بالادست عریضه بدهند (customer-supplier)، بعضی هر چه بیاید می‌نوشند (conformist)، بعضی تصفیه‌خانهٔ خودشان را می‌سازند (anticorruption layer)، بزرگ‌ترین شهر بالادست شرکت آب عمومی با استاندارد کیفیت منتشرشده دارد (open host service با published language)، بعضی چاه خودشان را می‌کنند (separate ways)، و یک محله حاشیه‌نشینِ بی‌نقشه است که دورش حصار می‌کشید (big ball of mud).

Partnershipsymmetric: plan togetherSalesFulfilmentPEvans: coordinated planning, joint integrationShared Kernelsymmetric: co-own a tiny modelSKSalesBillingMoney, Currency, rounding: nothing moreCustomer-Supplierdownstream has a saySupplierCustomerU / SD / Ccustomer needs go into supplier planningConformistdownstream adopts upstream modelCatalogSalesUD, CFno translation; upstream model insideAnticorruption Layerdownstream translates at its edgeLegacy ERPSalesACLUD, ACLtranslation layer owned by downstreamOpen Host Service + PLone protocol for manySalesOHS, PLBillingFulfilmentBIone documented contract, many consumersSeparate Waysno integration at allBillingCatalogxduplicate a little instead of integratingBig Ball of Mudmark it, wall itmixed models,no boundariesdraw a line around it; protect othersLegendinfluence flows upstream to downstreamU upstream D downstreamS supplier C customerOHS open host servicePL published languageACL anticorruption CF conformistSK shared kernel P partnership

تصویر، کل کاتالوگ به سبک DDD-crew است: الگوهای متقارن (Partnership، Shared Kernel) بی‌جهت کشیده شده‌اند، و الگوهای نامتقارن با پیکانی از بالادست (U) به پایین‌دست (D) و برچسب نقش در دو سر.

سه بدفهمی رایج، از همین اول ​

  1. «Context map همان معماری هدف است.» Evans: "Map the existing terrain. Take up transformations later." آنچه امروز درست است را بکشید، لبه‌های زشت هم؛ هدف را روی نقشهٔ دوم بکشید (Context Mapper حتی ویژگی state با مقدارهای AS_IS و TO_BE دارد).
  2. «الگوها سبک‌های فنی یکپارچه‌سازی‌اند.» بیشترشان دربارهٔ آدم‌ها هستند: چه کسی از چه کسی چه چیزی می‌تواند بخواهد. Customer-Supplier و Conformist ممکن است دقیقاً همان فراخوانی REST را داشته باشند؛ فرق در این است که تیم بالادست گوش می‌دهد یا نه.
  3. «ACL همیشه انتخاب امن است.» قیمت دارد: صفحهٔ الگوی Microsoft هشدار می‌دهد "The anti-corruption layer adds latency to calls between the two systems" و "adds an extra service that you must manage and maintain". همرنگ شدن با یک published language خوب اغلب ارزان‌تر و بهتر است.

از کجا آمده ​

Evans، ۲۰۰۳. کتاب Domain-Driven Design در بخش چهارم (طراحی راهبردی) bounded context، context map و الگوهای رابطه را معرفی کرد. مدخل bliki فاولر دربارهٔ bounded context می‌گوید "Bounded Context opens part IV (Strategic Design)" و طراحی راهبردی DDD "goes on to describe a variety of ways that you have relationships between Bounded Contexts. It's usually worthwhile to depict these using a context map."

Foote و Yoder، ۱۹۹۷/۱۹۹۹. مقالهٔ Big Ball of Mud (همان که Evans ارجاع می‌دهد؛ نسخهٔ ما تاریخ ۲۶ ژوئن ۱۹۹۹ دارد) اصطلاح را تعریف کرد: "A BIG BALL OF MUD is a casually, even haphazardly, structured system. Its organization, if one can call it that, is dictated more by expediency than design."

Vernon، ۲۰۱۳. فصل سوم Implementing Domain-Driven Design با عنوان "Context Maps" (صفحهٔ ۸۷ تا ۱۱۱) کشیدن نقشه را به یک تمرین تیمی تبدیل کرد. فاولر آن فصل را "the best source on drawing context maps" می‌نامد. ما پیش‌گفتار و صفحه‌های راهنمای کتاب (نمونهٔ ناشر) را خوانده‌ایم، نه خود فصل سوم را.

Evans، ۲۰۱۵. DDD Reference رایگان همهٔ الگوها را در قالب کوتاه "Therefore:" بازگو کرد. Partnership و Big Ball of Mud ستاره دارند و راهنمای ستاره می‌گوید "New term introduced since the 2004 book". سه واژهٔ رابطه را هم تعریف می‌کند: upstream-downstream، mutually dependent و free. این صفحه سراسر از Reference نقل می‌کند.

Khononov، ۲۰۲۱. فصل چهارم Learning Domain-Driven Design با عنوان "Integrating Bounded Contexts" الگوها را بر اساس نوع رابطهٔ تیم‌ها دسته‌بندی می‌کند: همکاری (Cooperation) (Partnership، Shared Kernel)، customer-supplier و separate ways. ما متن فصل را نخوانده‌ایم؛ این دسته‌بندی از نتایج جست‌وجویی آمده که فهرست مطالب ناشر را نشان می‌داد، و این‌جا فقط ابزار آموزشی است.

DDD-crew. مخزن جامعه‌محور context-mapping یک cheat sheet و کیت شروع Miro منتشر کرد: "There are nine context map patterns and three different team relationships."

Context Mapper. یک DSL (CML) و ابزارهایی که نقشهٔ کانتکست را به فایل متنی نسخه‌دار و قابل اعتبارسنجی تبدیل می‌کند، با قواعد معنایی صریح (مثلاً "The patterns ACL and CF cannot be applied jointly").

text
     Year        Idea                                        What it changed
1    1997/1999   Foote & Yoder: Big Ball of Mud              A name for the system with no boundaries
2    2003        Evans: context map + relationship patterns  Integration becomes a modelling decision
3    2013        Vernon IDDD ch. 3: drawing context maps     Maps become a team practice
4    2015        Evans DDD Reference: Partnership, BBoM      Nine patterns, three relationship words
5    later       DDD-crew cheat sheet, Context Mapper CML    Shared notation; maps as code
6    2021        Khononov: cooperation / C-S / separate ways  Patterns grouped by team relationship

فهرست مفاهیم ​

ترتیب هر بلوک: به زبان ساده، باور غلط رایج، تعریف دقیق، یک timeline روی مثال جاری، سناریوهای واقعی، یک جدول مقایسه، و راه‌حل در کد یا در عمل.

نقشهٔ کانتکست (Context Map) حیاتی ​

به زبان ساده: نقشهٔ کانتکست یک نقاشی (یا فایل متنی) است که همهٔ bounded contextهایی که با آن‌ها سروکار دارید، همهٔ خط‌های بینشان، و روی هر خط این‌که چه کسی خودش را با چه کسی تطبیق می‌دهد نشان می‌دهد.

بدفهمی رایج: «همان نمودار معماری خودمان است با اسم‌های DDD.» نمودار معماری deployableها و پروتکل‌ها را نشان می‌دهد؛ نقشهٔ کانتکست مدل‌ها و نفوذ را. فهرست راهنمای کتاب Vernon مدخلی دارد با عنوان "Context Maps are not EA diagrams". دو سرویس می‌توانند در یک کانتکست باشند؛ یک سیستم قدیمی ممکن است سه مدل ضمنی در خود داشته باشد.

تعریف: Evans (Reference، بخش "Context Map"): "Identify each model in play on the project and define its bounded context. This includes the implicit models of non-object-oriented subsystems. Name each bounded context, and make the names part of the ubiquitous language." و سپس: "Describe the points of contact between the models, outlining explicit translation for any communication, highlighting any sharing, isolation mechanisms, and levels of influence." README گروه DDD-crew اضافه می‌کند که نقشه‌ها "can be used to analyze existing systems or application landscapes, but they are also suitable for upfront design considerations".

text
     Drawing the first map for the shop (90-minute session, people from every team)
1    List contexts by name: Sales, Fulfilment, Billing, Catalog, Identity, "the ERP"
2    For each pair that talks: draw a line; write the mechanism (REST, events, DB, file)
3    For each line: who is upstream? ask "whose change breaks whom?"
4    Tag the relationship: Sales->Fulfilment C/S; Sales->Billing OHS/PL + CF; Billing->Sales OHS/PL + ACL; ERP->Sales ACL
5    Mark smells in red: BI reads Sales tables directly
6    Save as AS_IS; draw TO_BE separately (ERP retired, BI reads events)

سناریوی واقعی: خرده‌فروشی که می‌فهمد «Customer» در پنج سیستم با سه شیوهٔ شماره‌گذاری وجود دارد؛ بانکی که می‌بیند «هسته»اش به‌شکل conformist به مدل دادهٔ یک فروشنده وابسته است که نمی‌تواند تغییرش بدهد؛ شرکتی در حال رشد که نقشه‌اش یک تیم را بالادستِ یازده تیم دیگر نشان می‌دهد، و همین توضیح می‌دهد چرا آن تیم همیشه گلوگاه است.

نقشهٔ کانتکست نشان می‌دهدنشان نمی‌دهد
bounded contextها (با مدل‌های ضمنی سیستم‌های قدیمی)سرورها، podها، regionها
جهت نفوذ (U/D) روی هر لبهتأخیر یا throughput فراخوانی
الگوی هر لبه (P، SK، C/S، CF، ACL، OHS، PL)نمودار کلاس
ترجمه کجا انجام می‌شود و مال کیستکل مدل دامنه
بوها: DB مشترک، big ball of mudآیندهٔ ایده‌آل (آن نقشهٔ دوم است)

راه‌حل / نحوهٔ استفاده: نقشه را کوچک و پرسش‌محور نگه دارید. اولین توصیهٔ DDD-crew: "Prefer small context maps for explicit questions"، و "Work with different perspectives and multiple context maps for those perspectives". آن را به‌صورت CML یا فایل نمودار در مخزن نگه دارید، هنگام پیشنهاد هر یکپارچه‌سازی تازه مرورش کنید و وقتی تیم‌ها عوض می‌شوند دوباره بکشید.

بالادست، پایین‌دست و قدرت (Upstream/Downstream) حیاتی ​

به زبان ساده: بالادست (Upstream) طرفی است که تغییراتش به طرف دیگر ضربه می‌زند؛ پایین‌دست (Downstream) طرفی است که ضربه می‌خورد. موضوع نفوذ است، نه جهت جریان داده.

بدفهمی رایج: «بالادست تولیدکنندهٔ پیام است و پایین‌دست مصرف‌کننده.» معمولاً، ولی نه طبق تعریف. اگر Billing یک API از Fulfilment را صدا بزند تا تاریخ تحویل بپرسد، داده از Fulfilment به Billing می‌رود و Fulfilment بالادست است، چون تغییر API آن Billing را می‌شکند. اگر Fulfilment با هر تغییر Billing مجبور به تغییر بود، پیکان برعکس می‌شد.

تعریف: Evans (Reference): upstream-downstream یعنی "A relationship between two groups in which the “upstream” group’s actions affect project success of the “downstream” group, but the actions of the downstream do not significantly affect projects upstream." و "The upstream team may succeed independently of the fate of the downstream team." دو واژهٔ دیگر: وابستگی متقابل (Mutually dependent)، "A situation in which two software development projects in separate contexts must both be delivered in order for either to be considered a success"، و آزاد (Free)، "A software development context in which the direction, success or failure of development work in other contexts has little effect on delivery." Context Mapper جهت را رمزگذاری می‌کند: "the arrow -> always points from the upstream to the downstream and thus expresses an influence flow".

text
     Who is upstream? Ask "if they change, do we break?"
1    Catalog renames "price" to "list_price"          -> Sales breaks        => Catalog upstream of Sales
2    Sales adds delivery_window to OrderPlaced         -> Fulfilment gains    => Sales upstream of Fulfilment
3    Fulfilment changes its warehouse codes            -> Sales unaffected    => no edge needed from Fulfilment
4    Billing changes invoice numbering                 -> Sales unaffected    => no edge for invoices
5    Billing renames a field in payment.captured.v1    -> Sales ACL breaks    => Billing upstream of Sales for payments
6    ERP vendor ships a new export format              -> Sales ACL breaks    => ERP upstream, Sales downstream

سناریوی واقعی: یک ارائه‌دهندهٔ پرداخت (بالادست) که نسخهٔ API را با زمان‌بندی خودش منسوخ می‌کند؛ تیم هویت داخلی که به چهل سرویس خدمت می‌دهد و همه پایین‌دست‌اند؛ دو تیم که هر کدام روی یک لبهٔ متفاوت بالادست دیگری‌اند (Sales برای سفارش‌ها بالادست Billing، Billing برای وضعیت پرداخت بالادست Sales)، که مشکلی ندارد به شرط این‌که هر لبه جداگانه نام‌گذاری شود.

قدرت و این‌که چه کسی می‌پردازد:

رابطهمدل روی سیمسهم پایین‌دستهزینهٔ ترجمه با
Partnershipتوافق مشترکبرابرهر دو، به‌شکل هماهنگی
Shared Kernelخود kernelبرای kernel برابرهر دو، به‌شکل مشورت
Customer-Supplierمدل تأمین‌کننده، شکل‌گرفته با درخواست مشتریاولویت‌ها، تست پذیرشتأمین‌کننده (برنامه‌ریزی)، مشتری (درخواست)
OHS + PLزبان منتشرشدهدرخواست‌ها ممکن است برای همه پذیرفته شوندبالادست یک بار می‌سازد؛ پایین‌دست به آن نگاشت می‌کند
Conformistمدل بالادستهیچپایین‌دست، با مدلی ضعیف‌تر
ACLمدل بالادست، ترجمه‌شدهلازم نیستپایین‌دست، با کدی که نگه می‌دارد
Separate Waysنداردموضوعیت نداردهیچ‌کس (به جایش کمی تکرار)

راه‌حل / نحوهٔ استفاده: روی هر لبه U و D بنویسید. اگر نمی‌توانید تصمیم بگیرید، از هر دو تیم بپرسید «وقتی آن یکی عوض شود چه کسی باید عوض شود؟» اگر جواب «هر دو، همیشه» است، با یک جفتِ وابستهٔ متقابل طرفید: یا آگاهانه آن را Partnership کنید، یا مرز را جابه‌جا کنید.

شراکت (Partnership) مهم ​

به زبان ساده: دو تیمی که با هم موفق یا شکست می‌خورند توافق می‌کنند interface خود را با هم برنامه‌ریزی، تغییر و منتشر کنند.

بدفهمی رایج: «Partnership یعنی رفیقیم و زیاد حرف می‌زنیم.» یک تعهد فرایندی است، نه یک حال‌وهوا. Evans: "Institute a process for coordinated planning of development and joint management of integration." بدون فرایند، «شراکت» فقط دو تیم است که جلوی هم را می‌گیرند.

تعریف: Evans (Reference): "Where development failure in either of two contexts would result in delivery failure for both, forge a partnership between the teams in charge of the two contexts." "The teams must cooperate on the evolution of their interfaces to accommodate the development needs of both systems. Interdependent features should be scheduled so that they are completed for the same release." سازوکار یکپارچه‌سازی را هم می‌دهد: "a special test suite can be defined that proves the interface meets the expectations of the client system, which can be run as part of continuous integration on the server system."

text
     Click-and-collect launch (6 weeks, Sales + Fulfilment as partners)
1    Week 0  Joint planning: Sales adds pickup_store_id; Fulfilment adds store picking
2    Week 1  Shared interface draft (event + API) reviewed by both teams
3    Week 3  Fulfilment hits a store-stock gap; joint session; Sales adds stock check
4    Week 5  Joint integration suite green in both CIs
5    Week 6  Release together
6    Week 10 Feature stable -> relationship downgraded to Customer-Supplier (see Evolution)

سناریوی واقعی: تیم اپ موبایل و تیم backend-for-frontendش که checkout تازه را با هم منتشر می‌کنند؛ کانتکست پرداخت و کانتکست تشخیص تقلب که 3-D Secure را در یک انتشار راه می‌اندازند؛ تغییری که قانون‌گذار تحمیل کرده (قاعدهٔ مالیاتی تازه) و باید در Sales و Billing در یک تاریخ فرود بیاید.

جنبهPartnership
پویایی تیم‌هابرنامه‌ریزی مشترک، آیین‌های مشترک، در عمل حق وتوی متقابل
هزینههماهنگی زیاد؛ کندترین تیم سرعت را تعیین می‌کند
شکل کدتعریف interface مشترک که هر دو مرور می‌کنند؛ تست یکپارچه‌سازی مشترک در هر دو CI
ریسکهم‌قدمی دائمی می‌شود: یک distributed monolith با توافق
راه خروجوقتی interface پایدار شد، جهت بدهید: Customer-Supplier یا OHS/PL

راه‌حل / نحوهٔ استفاده: برایش سقف زمانی بگذارید («شراکت تا راه‌اندازی، بعد customer-supplier»)، اول مجموعه تست مشترک را بنویسید و تاریخ پایان را روی نقشه بگذارید. Context Mapper آن را Sales [P]<->[P] Fulfilment مدل می‌کند، رابطه‌ای متقارن که نمی‌تواند نقش OHS، PL، ACL یا CF داشته باشد (قاعدهٔ شمارهٔ ۴).

هستهٔ مشترک (Shared Kernel) حیاتی ​

به زبان ساده: دو تیم توافق می‌کنند تکهٔ کوچک و صریحاً مرزبندی‌شده‌ای از مدل و کد را با هم مالک باشند و فقط با توافق دوطرفه تغییرش بدهند.

بدفهمی رایج: «کلاس‌های مشترک دامنه را در یک کتابخانهٔ مشترک بگذاریم.» shared kernel دقیقاً این‌طور به دامنهٔ مشترک تبدیل می‌شود: Order، Customer و Invoice در یک پکیج common که همهٔ سرویس‌ها import می‌کنند، عکسِ چیزی است که Evans می‌گوید. kernel کوچک و هم‌مالک است؛ کتابخانهٔ بزرگی که صاحب ندارد implementation coupling است.

تعریف: Evans (Reference): "Sharing a part of the model and associated code is a very intimate interdependency, which can leverage design work or undermine it." "Therefore: Designate with an explicit boundary some subset of the domain model that the teams agree to share. Keep this kernel small." "This explicitly shared stuff has special status, and shouldn’t be changed without consultation with the other team." "Define a continuous integration process that will keep the kernel model tight and align the ubiquitous language of the teams."

چه چیزی می‌تواند مشترک باشد و چه چیزی نه:

محتوای خوب kernelچرا امن استمحتوای بد kernelچرا نه
Money، Currency (ISO 4217)پایدار، value object، رفتاری که بین کانتکست‌ها فرق کند نداردentityهای Order، Customerهر کانتکست آن‌ها را جور دیگری مدل می‌کند
قاعدهٔ گرد کردن یا گرد کردن مالیات که هر دو باید اجرا کنندواگرایی یک باگ واقعی است (اختلاف یک سنتی)مدل‌های persistence، کلاس‌های ORMschemaها را به هم گره می‌زند
نوع شناسه‌ها (قالب OrderId)باید در دو طرف یکسان باشدenumهای workflow یا وضعیتهر طرف چرخهٔ عمر خودش را دارد
کدهای خطای یک پروتکل مشترکجزئی از قرارداد توافق‌شدهجعبه‌ابزار متفرقه (StringUtils)دامنه نیست؛ از یک کتابخانه استفاده کنید
text
     A change request to the kernel (Sales wants Money.Split for instalments)
1    Sales opens PR on kernel; CODEOWNERS requires one Sales + one Billing reviewer
2    Billing asks: does Split round like PercentOf? Agree: same half-away-from-zero rule
3    Version 1.2.0 -> 1.3.0 (MINOR: additive)
4    Candidate tag built; both contexts' CI run against it; both green
5    Tag 1.3.0; Billing upgrades in its own time (nothing changed for it)
     A rounding change would be MAJOR: both teams approve, both upgrade in the same cycle

سناریوی واقعی: دو تیم که مدام بین جمع سبد خرید و فاکتور یک سنت اختلاف داشتند تا وقتی یک نوع Money و یک جدول تست گرد کردن را مشترک کردند؛ مجموعه‌ای از نوع‌های مشترک .proto (به سبک google.type.Money) که گروهی از سرویس‌ها استفاده می‌کنند؛ یک کانتکست گزارش‌گیری و یک کانتکست صورت‌حساب که فهرست کدهای مالیاتیِ الزامیِ قانون را مشترک دارند.

جنبهShared Kernel
پویایی تیم‌هادو (به‌ندرت سه) تیم، اعتماد بالا، یک بازبین نام‌دار از هر تیم
هزینههر تغییر مشورت می‌خواهد؛ برای نسخهٔ MAJOR انتشارها به هم گره می‌خورند
شکل کدیک پکیج نسخه‌دار (Go module، پکیج Composer) با تست‌های خودش که هر دو تیم اجرا می‌کنند
ریسکرشد («Address را هم اضافه کن»)، پیوستن تیم سوم و چهارم، بی‌صاحب شدن
راه خروجکد را در هر کانتکست کپی کنید و اشتراک را تمام کنید (separate ways برای آن مفهوم)، یا آن را به published language تبدیل کنید

راه‌حل / نحوهٔ استفاده: سقف اندازه و سیاست نسخه‌گذاری را درون خود پکیج بنویسید (kernel در Go و پکیج shared-kernel در Laravel این را در doc comment و composer.json دارند)، جدول تست kernel را در هر دو CI اجرا کنید، و هر فصل محتوای kernel را مرور کنید: هر چیزی که یک طرف دیگر لازم ندارد بیرون می‌رود.

مشتری و تأمین‌کننده (Customer-Supplier) حیاتی ​

به زبان ساده: تیم بالادست (تأمین‌کننده) با تیم پایین‌دست مثل مشتری رفتار می‌کند و نیازهایش را وارد برنامه‌ریزی خودش می‌کند، ولی تصمیم نهایی هنوز با تأمین‌کننده است.

بدفهمی رایج: «مشتری می‌تواند تغییرات بالادست را وتو کند.» Evans دقیقاً دربارهٔ همین هشدار می‌دهد: "the freewheeling development of the upstream team will stop if the downstream team has veto power over changes." مشتری در برنامه‌ریزی صدا دارد و تست خودکار در CI تأمین‌کننده، نه حق وتو.

تعریف: Evans (Reference): "Establish a clear customer/supplier relationship between the two teams, meaning downstream priorities factor into upstream planning. Negotiate and budget tasks for downstream requirements so that everyone understands the commitment and schedule." و سازوکارش: "Jointly developed automated acceptance tests can validate the expected interface from the upstream. Adding these tests to the upstream team’s test suite, to be run as part of its continuous integration, will free the upstream team to make changes without fear of side effects downstream." Context Mapper: "A generic upstream-downstream relationship is not necessarily a customer-supplier relationship!"

text
     Fulfilment (customer) needs a delivery window on OrderPlaced
1    Fulfilment files the request at Sales' planning session with a reason (route planning)
2    Sales budgets it for the next sprint; adds optional delivery_window (v1.1, additive)
3    Fulfilment adds "delivery_window.from/to" to consumers/fulfilment.expects.json
4    Sales CI runs every consumer expectation file on each build (contract test)
5    Months later a Sales dev renames lines[].quantity -> qty: Sales CI fails before merge
6    Sales keeps quantity; the rename becomes a v2 discussion, planned with customers

سناریوی واقعی: تیم موبایل به‌عنوان مشتری یک تیم API داخلی؛ سیستم انبار که از سیستم سفارش یک فیلد اضافه می‌خواهد و فصل بعد می‌گیرد؛ یک پلتفرم داده که انتظارات مشتریان را به‌شکل قرارداد Pact منتشر می‌کند و تیم‌های تولیدکننده باید رعایتش کنند.

جنبهCustomer-Supplier
پویایی تیم‌هامشتری در جلسهٔ برنامه‌ریزی تأمین‌کننده حاضر است؛ تأمین‌کننده نقشهٔ راه منتشر می‌کند
هزینهتأمین‌کننده ظرفیت صرف درخواست مشتری می‌کند؛ مشتری باید نیازش را دقیق بگوید
شکل کدcontract test مصرف‌کننده‌محور (Pact یا فایل انتظار) در CI تأمین‌کننده
ریسکمشتری زیاد: تأمین‌کننده نمی‌تواند برای همه برنامه بریزد (وقت OHS شدن است)
راه خروجبالادست عمومی می‌شود و Open Host Service می‌سازد؛ یا پایین‌دست دیگر چیزی نمی‌خواهد و conformist می‌شود

راه‌حل / نحوهٔ استفاده: سازوکار اصلی contract test است: پایین‌دست می‌نویسد چه می‌خواند، بالادست اجرایش می‌کند. یک ظرافت ابزاری: قاعدهٔ معنایی شمارهٔ ۶ در Context Mapper می‌گوید "The OHS pattern is not applicable within a customer-supplier relationship"، با این استدلال که OHS یعنی "one API in a one for all approach". Evans این ترکیب را منع نکرده و در عمل یک تأمین‌کننده می‌تواند یک OHS منتشر کند و هم‌زمان به یک مشتری مهم اولویت برنامه‌ریزی بدهد. مثال جاری ما Sales-Fulfilment را customer-supplier روی published language نگه می‌دارد و در CML آن را Fulfilment [C]<-[S,PL] Sales می‌نویسد.

همرنگ با جماعت (Conformist) حیاتی ​

به زبان ساده: تیم پایین‌دست دست از جنگیدن برمی‌دارد و مدل بالادست را، دست‌کم در بخشی که به یکپارچه‌سازی مربوط است، مدل خودش می‌کند.

بدفهمی رایج: «Conformist همیشه یعنی شکست.» Evans مزیتش را می‌شمارد: "choosing conformity enormously simplifies integration. Also, you will share a ubiquitous language with your upstream team." همرنگ شدن با یک مدل خوب (یک published language خوش‌طراحی، یک استاندارد صنعتی، یک توکن OIDC) اغلب بهترین انتخاب است.

تعریف: Evans (Reference): وقتی "the upstream has no motivation to provide for the downstream team’s needs, the downstream team is helpless." "Therefore: Eliminate the complexity of translation between bounded contexts by slavishly adhering to the model of the upstream team. Although this cramps the style of the downstream designers and probably does not yield the ideal model for the application, choosing conformity enormously simplifies integration." قاعدهٔ شمارهٔ ۵ در Context Mapper: "The CF pattern is not applicable within a customer-supplier relationship"، چون "A conformist in contrast has no influence and simply decides to conform to what the upstream provides."

text
     Sales conforms to Catalog's product model
1    Catalog's API returns {sku, title, list_price, tax_class, variants[]}
2    Sales' cart stores CatalogProduct exactly as returned (no own Product type)
3    Catalog adds "bundle" products; Sales shows them wrong until Sales adapts
4    Team decides: still worth it (Catalog model is good, changes are rare)
5    If Catalog changes weekly or the model starts to hurt -> insert an ACL (see Evolution)

سناریوی واقعی: هر سرویسی که ID token از OIDC می‌گیرد و claimهای sub و email را همان‌طور به کار می‌برد؛ فروشگاهی که شیء charge ارائه‌دهندهٔ پرداخت را رکورد پرداخت خودش می‌کند؛ Billing در نقشهٔ ما، که نوع‌های sales.order.placed.v1 را مستقیم به کار می‌برد چون دقیقاً همان چیزی است که لازم دارد.

کِی همرنگ شدن پذیرفتنی استکِی نیست
مدل بالادست خوب یا استاندارد است (OIDC، iCalendar، ISO 20022)مدل بالادست یک big ball of mud است
کانتکست supporting یا generic است، نه coreکانتکست پایین‌دست core domain شماست
بالادست به‌ندرت و سازگار تغییر می‌کندبالادست مدام تغییر می‌کند و چیزها را می‌شکند
چند فیلد کم لازم دارید و همان‌طور استفاده می‌کنیدمی‌خواهید تغییر نام، تفسیر دوباره یا ترکیب کنید

راه‌حل / نحوهٔ استفاده: آگاهانه و محلی همرنگ شوید: نوع‌های بالادست را در یک پکیج نگه دارید (Billing فقط contracts/orderplaced را import می‌کند)، تا اگر بالادست خراب شد بتوانید دقیقاً در همان درز یک ACL بگذارید. مصرف‌کنندهٔ conformist را ببینید.

لایهٔ ضدفساد (Anticorruption Layer) حیاتی ​

به زبان ساده: تیم پایین‌دست در لبهٔ خودش یک مترجم می‌سازد تا مدل، واژه‌ها و عجایب بالادست هرگز وارد مدل خودش نشوند.

بدفهمی رایج: «ACL یک کلاس mapper است.» mapper یک تکه از آن است. Evans از لایه‌ای می‌گوید که "talks to the other system through its existing interface" و "translates in one or both directions"؛ صفحهٔ الگوی Microsoft آن را "a facade or adapter layer" می‌نامد. در عمل سه بخش دارد: نما (Facade)، وفق‌دهنده (Adapter) و مترجم (Translator). خطاها، شناسه‌ها و معنا را هم ترجمه می‌کند (دو پرچم ERP یک وضعیت اعتباری Sales می‌شوند)، نه فقط اسم فیلدها را.

تعریف: Evans (Reference): "As a downstream client, create an isolating layer to provide your system with functionality of the upstream system in terms of your own domain model. This layer talks to the other system through its existing interface, requiring little or no modification to the other system. Internally, the layer translates in one or both directions as necessary between the two models." انگیزه‌اش: "The models of legacy systems are usually weak (if not big balls of mud), and even the exception that is clearly designed may not fit the needs of the current project". صفحهٔ الگوی Microsoft: "Implement a facade or adapter layer between different subsystems that don't share the same semantics." microservices.io همین مسئله را این‌طور قاب می‌گیرد: "How do you prevent a legacy monolith’s domain model from polluting the domain model of a new service."

Sales model(Sales language only)PlaceOrderOnAccountCustomercredit: good|on_hold|blockedport: CustomerDirectorycustomerById(id)Anticorruption Layer (owned by Sales)FacadeErpCustomerDirectoryimplements the portTranslatorrecord to Customercus_77 to 0000000077pure, table-testedAdapterErpCustomerClienttimeouts, retriesstatus codesLegacy ERP(big ball of mud)KUNNR 0000000077NAME1 AcmeKTOKD Z002KLIMK 1.500,00WAERS EURSPERR XCRBLB ""GET /export/kunde/{kunnr}HTTPerrors translated:404 to CustomerNotFound5xx, timeout to unavailable

تصویر سه بخش را نشان می‌دهد: facade پورتی را پیاده می‌کند که مالکش مدل Sales است؛ adapter به پروتکل ERP حرف می‌زند (خروجی HTTP، timeout، کد وضعیت)؛ translator یک تابع خالص از رکورد ERP به Customerِ Sales است و شناسه‌ها و خطاها را هم نگاشت می‌کند.

text
     Sales places an order on account; customer data lives in the legacy ERP
1    PlaceOrderOnAccount asks CustomerDirectory.CustomerByID("cus_77")      Sales language
2    Facade: translator maps cus_77 -> KUNNR 0000000077                     id translation
3    Adapter: GET /export/kunde/0000000077 (timeout 2 s, retry on 5xx)     ERP protocol
4    ERP returns {KUNNR, NAME1, KTOKD:"Z002", KLIMK:"1.500,00", SPERR:"", CRBLB:"X"}
5    Translator: segment=business, limit=150000 EUR cents, credit=on_hold   semantics
6    Sales rule: on_hold -> order needs prepayment                          Sales language again
     404 -> sales.ErrCustomerNotFound; 5xx/timeout -> "directory unavailable" (not "not found")

سناریوی واقعی: یک سرویس core تازه جلوی یک ERP یا mainframe بیست‌ساله؛ یکپارچه‌سازی با SaaS (ارائه‌دهندهٔ پرداخت، موتور مالیات، CRM) که اشیائش نباید اشیای دامنهٔ شما شوند؛ مهاجرت strangler fig که در آن ACL همان درزی است که بعداً اجازه می‌دهد سیستم قدیمی را عوض کنید (Strangler Fig).

کجا قرار می‌گیرد و چه هزینه‌ای دارد:

جایگاهکِیهزینهمنبع
پکیجی درون سرویس پایین‌دست (پیش‌فرض ما)فقط یک پایین‌دست به این ترجمه نیاز داردکدی برای نگهداری؛ یک جا برای تغییرMicrosoft: "as a component within the application"
سرویس ACL جداچند پایین‌دست یک سیستم قدیمی مشترک دارند، یا فناوری دیگری لازم استdeployable اضافه، تأخیر، نقطهٔ شکست واحدMicrosoft: "or as an independent service"؛ "adds latency"
در پلتفرم یکپارچه‌سازی (API gateway، iPaaS)فقط تبدیل پروتکلمعنای کسب‌وکار در پیکربندی گم می‌شودMicrosoft: API Management برای "protocol concerns"
ACL رویدادمحور (event سیستم قدیمی را بگیر، event تمیز منتشر کن)throughput بالا، جداافتادگیbroker، ترتیب، idempotencyMicrosoft: "an asynchronous, event-driven approach"

facade و adapter همان الگوهای کلاسیک شیءگرا هستند (Structural Patterns)؛ شکل پورت و نگاشت همان است که برای persistence به کار می‌رود (Data Persistence in Design).

راه‌حل / نحوهٔ استفاده: پورت را در مدل پایین‌دست مالک باشید، translator را خالص و جدول‌تست‌شده نگه دارید، خطاها را به زبان خودتان ترجمه کنید، قواعد کسب‌وکار را بیرون لایه نگه دارید (Microsoft: "Avoid placing business rules or orchestration in the layer")، correlation ID و لاگ در لایه بگذارید (Microsoft: "Plan for observability")، و از اول تصمیم بگیرید که دائمی است یا با بازنشستگی سیستم قدیمی کنار می‌رود. کد: Go، Laravel.

سرویس میزبان باز (Open Host Service) حیاتی ​

به زبان ساده: بالادست به جای ساختن یکپارچه‌سازی سفارشی برای هر مصرف‌کننده، یک پروتکل خوش‌تعریف منتشر می‌کند که هر کسی می‌تواند استفاده کند.

بدفهمی رایج: «OHS یعنی یک REST API عمومی.» یعنی یک پروتکل باز برای یکپارچه‌سازی: یک API از نوع REST/gRPC، یک جریان event، یا هر دو. ویژگی تعیین‌کننده‌اش یک پروتکل برای مصرف‌کنندگان زیاد است که برای نیازهای عمومی گسترش می‌یابد و حالت‌های خاص بیرون از آن حل می‌شوند.

تعریف: Evans (Reference): "When a subsystem has to be integrated with many others, customizing a translator for each can bog down the team." "Therefore: Define a protocol that gives access to your subsystem as a set of services. Open the protocol so that all who need to integrate with you can use it. Enhance and expand the protocol to handle new integration requirements, except when a single team has idiosyncratic needs. Then, use a one-off translator to augment the protocol for that special case so that the shared protocol can stay simple and coherent." و: "Each client is downstream, and typically some of them will be conformist and some will build anticorruption layers."

text
     Sales becomes an OHS when the third consumer arrives
1    Fulfilment and Billing each got a tailored payload (two code paths in Sales)
2    BI asks for a third variant; Sales team says no and designs sales.order.placed.v1
3    Contract published: JSON Schema + AsyncAPI document + example message
4    Billing conforms (uses the types as they are); Fulfilment adds its needs via C/S
5    A partner warehouse wants XML: one-off translator outside the OHS (Evans' advice)
6    The OHS stays one shape; v2 only when a breaking change is unavoidable

سناریوی واقعی: ارائه‌دهندهٔ هویت که OpenID Connect را به همهٔ برنامه‌ها عرضه می‌کند؛ تیم پرداخت که event payment.captured را برای همهٔ کانتکست‌های علاقه‌مند منتشر می‌کند؛ یک API عمومی (به سبک Stripe یا GitHub) که هزاران کلاینت پایین‌دستش هستند.

جنبهOpen Host Service
پویایی تیم‌هابالادست برای API خودش مثل تیم محصول رفتار می‌کند؛ سیاست deprecation، changelog
هزینهطراحی و نگهداری API، نسخه‌گذاری، مستندسازی
شکل کدترجمهٔ خروجی از مدل داخلی به published language؛ contract test؛ فایل‌های spec (OpenAPI، AsyncAPI، .proto)
ریسکنشت مدل داخلی («فقط entity را serialize می‌کنیم»)؛ پروتکلی که برای هر مصرف‌کننده یک فیلد اضافه می‌گیرد
راه خروجبه‌ندرت رها می‌شود؛ نسخه به نسخه جایگزین می‌شود (v1 و v2 موازی منتشر می‌شوند)

راه‌حل / نحوهٔ استفاده: خروجی را صریح نگاشت کنید (هرگز aggregate را serialize نکنید)، spec را کنار کد منتشر کنید، و تست کنید که فیلدهای داخلی نشت نمی‌کنند (کد publisher).

زبان منتشرشده (Published Language) حیاتی ​

به زبان ساده: یک قالب تبادل مستند که هر دو طرف به آن و از آن ترجمه می‌کنند، تا مدل داخلی هیچ‌کدام قرارداد نشود.

بدفهمی رایج: «مدل دامنهٔ ما همان published language است.» Evans توضیح می‌دهد چرا نه: مدل‌های داخلی "may be overly complex or poorly factored. They are probably undocumented. If one is used as a data interchange language, it essentially becomes frozen and cannot respond to new development needs."

تعریف: Evans (Reference): "Use a well-documented shared language that can express the necessary domain information as a common medium of communication, translating as necessary into and out of that language." "Many industries establish published languages in the form of data interchange standards. Project teams also develop their own for use within their organization." "Published language is often combined with open-host service." DDD-crew: "Widely known examples of a Published Language are iCalendar or vCard."

قالب‌های رایج:

قالبتوصیف می‌کندspec چه می‌گویدمناسب برای
OpenAPI 3.1APIهای HTTP"a standard, programming language-agnostic interface description for HTTP APIs"OHS هم‌زمان
AsyncAPI 3.0APIهای پیام‌محور"describe message-driven APIs in a machine-readable format. It’s protocol-agnostic" (AMQP، MQTT، Kafka و…)OHS رویدادی
JSON Schemapayloadهای JSONواژگان اعتبارسنجی (required، type، const)payload رویدادها، درون OpenAPI/AsyncAPI هم
Protocol Buffers (proto3)پیام‌ها و سرویس‌های gRPCشمارهٔ فیلد؛ شماره‌های حذف‌شده در reservedevent باینری، gRPC
استانداردهای صنعتیiCalendar، vCard، claimهای OIDC، ISO 20022، EDIFACTمالکش یک نهاد استاندارد استیکپارچه‌سازی بین شرکت‌ها

قواعد نسخه‌گذاری (Versioning) که PL را قابل‌استفاده نگه می‌دارد:

تغییرسازگار؟قاعده
افزودن فیلد اختیاریبلهMINOR (v1.0 به v1.1)؛ مصرف‌کننده فیلد ناشناخته را نادیده می‌گیرد
افزودن فیلد اجباریبرای داده‌های قدیمی تولیدکننده نهاختیاری‌اش کنید، یا v2
تغییر نام یا حذف فیلدنهv2 با نام/کلید مسیریابی تازه، v1 و v2 موازی منتشر شوند
تغییر معنا یا واحد یک فیلدنه، و بی‌صداv2؛ هرگز نامی را با معنای تازه دوباره به کار نبرید
Protobuf: حذف فیلدبله اگر reserved شودمستندات Protobuf: "add your deleted field number to the reserved list"
تغییر مقدارهای enumمعمولاً نهفقط اضافه کنید؛ مصرف‌کننده باید مقدار ناشناخته را تحمل کند
text
     Life of sales.order.placed.v1
1    v1.0  published: order_id, customer_id, currency, total_minor, lines[]
2    v1.1  + delivery_window (optional) for Fulfilment; Billing unaffected
3          margin_minor proposed by BI -> rejected (internal, commercial secret)
4    v2    "lines" restructured for bundles -> new key sales.order.placed.v2
5          Sales publishes v1 and v2 for 3 months; consumers migrate; v1 retired

راه‌حل / نحوهٔ استفاده: schema را منبع حقیقت در مخزن نگه دارید (ما: contracts/sales/order_placed.v1.schema.json، .proto، asyncapi.yaml)، binding را تولید یا دستی بنویسید، و هر دو طرف را در برابرش تست کنید. قواعد عمیق‌تر تکامل در Message Design & Schema Evolution و API Versioning است؛ ترجمه به یک قالب مشترک و از آن همان ایدهٔ Canonical Data Model در EIP است (Message Transformation)، و سبک‌های event پشت یک OHS رویدادی در Event-Driven Architecture آمده.

راه‌های جدا (Separate Ways) مهم ​

به زبان ساده: دو کانتکست که واقعاً به هم نیاز ندارند یکپارچه‌سازی را کنار می‌گذارند و هر کدام نیاز کوچکش را خودش حل می‌کند، حتی اگر کمی تکرار پیش بیاید.

بدفهمی رایج: «تکرار همیشه اتلاف است.» یکپارچه‌سازی هزینهٔ جاری دارد (قرارداد، قطعی، هماهنگی). Evans: "Integration is always expensive, and sometimes the benefit is small."

تعریف: Evans (Reference): "We must be ruthless when it comes to defining requirements. If two sets of functionality have no significant relationship, they can be completely cut loose from each other." "Therefore: Declare a bounded context to have no connection to the others at all, allowing developers to find simple, specialized solutions within this small scope."

text
     Billing wanted product descriptions on invoices
1    Option A: Billing calls Catalog per invoice line (new sync edge, Catalog outage = no invoices)
2    Option B: Billing takes sku + quantity + price from OrderPlaced; prints the SKU text it has
3    Finance agrees invoices show SKU and the order's line text; no Catalog call
4    Map: Billing and Catalog = separate ways (no line)

سناریوی واقعی: سیستم منابع انسانی و پلتفرم فروش آنلاین در یک شرکت؛ سایت بازاریابی با فهرست کوچک محصول خودش به جای یکپارچه‌سازی با PIM؛ دو ابزار داخلی که هر کدام فهرست کوتاه کشورها را نگه می‌دارند به جای صدا زدن سرویس دادهٔ مرجع.

جنبهSeparate Ways
پویایی تیم‌هاآزاد (واژهٔ سوم Evans)
هزینهکمی دادهٔ تکراری یا منطق تکراری؛ ناسازگاری احتمالی که کاربر می‌بیند
شکل کدهیچ؛ هدف همین است
ریسکنیازها رشد می‌کنند و یکپارچه‌سازیِ غیررسمی سر برمی‌آورد (spreadsheet، DB مشترک)
راه خروجوقتی سود واقعی شد، یک لبه با الگوی نام‌دار اضافه کنید

راه‌حل / نحوهٔ استفاده: «separate ways» را صریحاً روی نقشه بنویسید تا کسی یکپارچه‌سازی تصادفی اضافه نکند، و وقتی نیازها عوض شد دوباره بررسی کنید.

گلولهٔ بزرگ گِل (Big Ball of Mud) مهم ​

به زبان ساده: بعضی سیستم‌ها هیچ مرز درونیِ ارزشمندی برای کشیدن ندارند؛ کل آن را یک توده علامت بزنید و بقیه را از آن محافظت کنید.

بدفهمی رایج: «قبل از یکپارچه‌سازی باید سیستم قدیمی را درست مدل کنیم.» Evans: "It is easy to get bogged down in an attempt to describe the context boundaries of models in systems where there simply are no boundaries."

تعریف: Evans (Reference): "Draw a boundary around the entire mess and designate it a big ball of mud. Do not try to apply sophisticated modeling within this context. Be alert to the tendency for such systems to sprawl into other contexts." او با ارجاع به Foote و Yoder یادآوری می‌کند که "The big ball of mud is actually quite practical for some situations". DDD-crew: "Big Ball Of Mud is a demarcation of a bad model or system quality. You want to make sure, that this mess does not propagate into other bounded contexts."

text
     The ERP on the map
1    Draw one dashed box "Legacy ERP (BBoM)"; no inner contexts
2    Every edge from it into a modelled context gets an ACL
3    New features never go into the ERP; they go into new contexts next to it
4    Strangler fig: each moved capability shrinks the box; ACL becomes the seam

سناریوی واقعی: یک monolith پانزده‌سالهٔ PHP که جدول ordersش ۱۴۰ ستون دارد؛ یک ERP که سه شرکت مشاوره سفارشی‌اش کرده‌اند؛ یک دیتابیس «هسته»ی مشترک که یازده برنامه در آن می‌نویسند.

بکنیدنکنید
آن را یک کانتکست با مرز روشن بکشیدده‌ها کانتکست درونیِ حدسی بکشید
روی هر لبه به یک کانتکست مدل‌شده ACL بگذاریدبگذارید اصطلاحاتش وارد مدل core شود
برای کاری که خوب انجام می‌دهد همان‌طور استفاده‌اش کنیدقابلیت core تازه درونش اضافه کنید
عقب‌نشینی را با strangler fig برنامه‌ریزی کنیدبازنویسی یکباره برنامه‌ریزی کنید (Fowler: "we've seen this simple-sounding plan go down in flames most of the time")

راه‌حل / نحوهٔ استفاده: علامتش بزنید، دورش دیوار بکشید و کار تازه را از کنارش رد کنید. ACL همان دیوار است.

نشانه‌گذاری (Notation): U/D، نقش‌ها و سبک cheat sheet حیاتی ​

به زبان ساده: چند حرف کوچک در دو سر هر خط، رابطه را در یک نگاه به خواننده می‌گوید.

بدفهمی رایج: «پیکان جریان داده را نشان می‌دهد.» در سبک DDD-crew و Context Mapper پیکان نفوذ را نشان می‌دهد: از بالادست به پایین‌دست.

تعریف: اختصارهایی که CMLِ Context Mapper و cheat sheetِ DDD-crew به کار می‌برند:

علامتمعناکجا می‌آیدمثال CML
U / Dبالادست / پایین‌دستدو سر یک خط نامتقارنSales [D]<-[U] Catalog
S / Cتأمین‌کننده / مشتریدو سر customer-supplierFulfilment [C]<-[S] Sales
OHSopen host serviceفقط سر بالادست[U,OHS,PL]
PLpublished languageفقط سر بالادست[U,OHS,PL]
CFconformistفقط سر پایین‌دست[D,CF]
ACLanticorruption layerفقط سر پایین‌دست[D,ACL]
SKshared kernelهر دو سر، متقارنSales [SK]<->[SK] Billing
Ppartnershipهر دو سر، متقارنSales [P]<->[P] Fulfilment
BBoMbig ball of mudیک مرز، نه یک خطکادر خط‌چین

قواعد Context Mapper نشانه‌گذاری را دقیق می‌کنند: "The patterns OHS and PL can only be implemented by the upstream context"، "The patterns ACL and CF can only be applied by the downstream context"، "The patterns ACL and CF cannot be applied jointly"، و OHS، PL، ACL، CF "are not applicable in symmetric relationships (Partnership and Shared Kernel)". برای هر لبه ویژگی‌هایی هم ثبت می‌کند: implementationTechnology، downstreamRights (INFLUENCER، OPINION_LEADER، VETO_RIGHT، DECISION_MAKER، MONOPOLIST) و exposedAggregates، و برای هر نقشه type (SYSTEM_LANDSCAPE یا ORGANIZATIONAL) و state (AS_IS یا TO_BE).

text
     Reading one line of the map
1    Billing [D,CF]<-[U,OHS,PL] Sales { implementationTechnology = "AMQP events" }
2    "<-" : arrow points from Sales (upstream) to Billing (downstream)
3    [U,OHS,PL] : Sales offers an open host service in a published language
4    [D,CF]     : Billing conforms to that language (no ACL)
5    { ... }    : the mechanism; async events over AMQP

راه‌حل / نحوهٔ استفاده: نشانه‌گذاری را یک بار برای کل سازمان انتخاب کنید و روی خود نقشه توضیحش دهید (DDD-crew: "Document and explain the patterns you are going to use"). فایل CML را کنار کد نگه دارید: نقشهٔ ما به‌صورت CML.

نوع ارتباط روی نقشه مهم ​

به زبان ساده: الگو می‌گوید چه کسی خودش را تطبیق می‌دهد؛ نوع ارتباط می‌گوید بایت‌ها چطور می‌روند. هر دو را روی هر خط بنویسید.

بدفهمی رایج: «event ناهم‌زمان یعنی بی‌coupling.» eventها temporal coupling را برمی‌دارند؛ schemaی event هنوز قرارداد است و رابطه (conformist، ACL) هنوز برقرار است. دیتابیس مشترک بدترین حالت است چون رابطه را پنهان می‌کند: هر جدول یک published language بی‌نسخه است که هیچ‌کس رویش توافق نکرده.

تعریف: سازوکارهایی که می‌بینید و نشانشان روی نقشه:

سازوکارعلامت روی نقشهجفت معمول با الگونکته
درخواست/پاسخ هم‌زمان (REST، gRPC)خط پر، "sync REST"OHS + PL (OpenAPI / .proto)، CF یا ACL در پایین‌دستtemporal coupling: timeout، retry (Service Communication)
event ناهم‌زمان (Kafka، RabbitMQ)خط پر، "async events"OHS + PL (AsyncAPI، JSON Schema، Avro، Protobuf)انتشار از طریق outbox؛ مصرف‌کنندهٔ idempotent
کتابخانهٔ مشترکخط دوتایی / SKفقط Shared Kernelباید کوچک و نسخه‌دار باشد
خروجی فایل / batchخط‌چین، "nightly file"ACL در پایین‌دست (سیستم قدیمی)تازگی به ساعت سنجیده می‌شود
دیتابیس مشترکخط قرمز، "shared DB"هیچ: یک بو استعلامتش بزنید؛ حذفش را برنامه‌ریزی کنید (مالکیت داده)
فراخوانی درون‌پردازه‌ای (modular monolith)خط درون یک deployableOHS = interface عمومی ماژولترجمه بین مدل‌ها هنوز لازم است
text
     The same fact, three ways
1    Sync:   Billing GET /orders/1042 at invoice time -> Sales down = no invoices
2    Async:  Billing consumes sales.order.placed.v1 -> Sales down = invoices later
3    Shared: Billing SELECT * FROM sales.orders -> Sales renames a column = Billing broken

راه‌حل / نحوهٔ استفاده: روی هر لبه سازوکارش را بنویسید (implementationTechnology در CML)، لبه‌های دیتابیس مشترک را قرمز کنید و برای هر کدام برنامهٔ حذف بگذارید.

لایهٔ رابطهٔ تیم‌ها (Team relationships) تکمیلی ​

به زبان ساده: تیم‌ها را روی کانتکست‌ها بکشید؛ بیشتر مشکلات لبه‌ها مشکل تیم‌اند.

بدفهمی رایج: «همیشه یک کانتکست، یک تیم.» اغلب درست است، ولی یک تیم می‌تواند چند کانتکست داشته باشد، و کانتکستی که دو تیم صاحبش هستند علامت هشدار است.

تعریف: سه رابطهٔ تیمی DDD-crew: وابستگی متقابل (Mutually dependent) ("their software artifacts or systems need to be delivered together to be successful and work")، بالادست/پایین‌دست ("Actions of an upstream team will have an effect on the downstream team, but actions of the downstream do not have a significant impact on the upstream team") و آزاد (Free) ("changes in other Bounded Contexts do not influence its success or failure"). Context Mapper نقشهٔ ORGANIZATIONAL دارد که کانتکست‌هایش تیم‌اند.

رابطهٔ تیمیالگوهای معمول همراهشمراقب باشید
وابستگی متقابلPartnership، Shared Kernelهم‌قدمی ابدی
بالادست/پایین‌دستCustomer-Supplier، Conformist، ACL، OHS/PLبالادستِ غرق در درخواست
آزادSeparate Waysیکپارچه‌سازی پنهانی که بعداً پیدا می‌شود
text
     Overlay on our map (see the running map below)
1    Team Checkout owns Sales        -> upstream of Fulfilment, Billing; downstream of Billing (ACL) for payments
2    Team Warehouse owns Fulfilment  -> customer of Checkout
3    Team Finance Eng owns Billing   -> conformist to Sales PL; upstream OHS/PL for payments; co-owns kernel
4    Team Platform owns Identity     -> upstream of all (generic OHS)
5    Vendor + one admin own the ERP  -> upstream; no planning influence at all

راه‌حل / نحوهٔ استفاده: با زبان Team Topologies هم‌راستا کنید: تعامل X-as-a-Service یعنی OHS؛ تعامل collaboration یعنی Partnershipِ سقف‌دار.

تکامل نقشه (Evolution) مهم ​

به زبان ساده: رابطه‌ها با تغییر سیستم‌ها و تیم‌ها عوض می‌شوند؛ نقشه باید این حرکت و دلیلش را ثبت کند.

بدفهمی رایج: «وقتی الگویی انتخاب شد ثابت می‌ماند.» هر الگو یک قدم بعدی معمول دارد.

تعریف: گذارهای رایج و محرک‌شان:

ازبهمحرکچه چیزی در کد عوض می‌شود
ConformistACLمدل بالادست به core پایین‌دست آسیب می‌زندtranslator در درزی گذاشته می‌شود که نوع‌های بالادست در آن محصور بودند
ACLConformist به OHS/PLبالادست published language تمیز منتشر می‌کندبیشتر translator حذف می‌شود؛ نوع‌های PL به کار می‌روند
ACL (سیستم قدیمی)هیچstrangler fig تمام شد، سیستم قدیمی بازنشسته شدACL همراه سیستم قدیمی حذف می‌شود
Customer-SupplierOHS + PLمشتری سوم و چهارم می‌رسندpayload عمومی می‌شود؛ spec منتشر می‌شود
PartnershipCustomer-Supplierراه‌اندازی تمام شد، interface پایدار استتست‌های مشترک contract test مصرف‌کننده می‌شوند
Shared KernelSeparate Waysیک طرف kernel را استفاده نمی‌کند، یا kernel رشد می‌کندکد کپی می‌شود؛ اشتراک تمام می‌شود
Shared KernelPublished Languageمصرف‌کنندگان بیشتری می‌خواهندشکد مشترک به schema تبدیل می‌شود
DB مشترکevent با OHS/PLهر زمان؛ یک بو استمهاجرت expand/contract به eventها (مالکیت داده)
text
     Sales <- ERP over two years
1    Q1  Sales [D,ACL]<-[U] ERP           ACL translates customer master records
2    Q3  New "Customer" context strangles the ERP's customer master
3    Q4  Customer context offers OHS + PL (customer.updated.v1)
4    Q5  Sales [D,CF]<-[U,OHS,PL] Customer; ERP ACL deleted for customers
5    Q8  ERP retired; map: the BBoM box is gone

کتاب Building Microservices از Newman دلیل این را می‌گوید که چرا bounded context واحد درست جابه‌جایی است: "bounded contexts make excellent seams since by definition they represent cohesive and yet loosely coupled boundaries in an organization"؛ کتاب Monolith to Microservices او هم بخشی با عنوان "Pattern: Strangler Fig Applications" برای جابه‌جا کردن قابلیت‌ها از روی چنین درزی دارد.

راه‌حل / نحوهٔ استفاده: نقشه‌های AS_IS و TO_BE را نگه دارید؛ هر architecture decision record که یک لبه را تغییر می‌دهد، نقشه را در همان pull request به‌روز کند.

نقشهٔ مثال جاری حیاتی ​

به زبان ساده: فروشگاهی که در سراسر مسیر DDD به کار می‌بریم، همان‌طور که امروز هست.

بدفهمی رایج: «هر جفت کانتکست دقیقاً یک رابطه دارد.» Sales و Billing سه رابطه دارند: در هر جهت یک لبهٔ event از نوع OHS/PL (sales.order.placed.v1 از Sales به Billing و billing.payment.captured.v1 از Billing به Sales) و یک shared kernel کوچک. دیدگاه‌های جدا می‌توانند روی نقشه‌های جدا باشند.

تعریف: لبه‌ها، هر کدام با الگو، سازوکار و دلیل:

Salescore subdomainteam: CheckoutFulfilmentcore or supportingteam: WarehouseBillingsupportingteam: Finance EngCatalogsupportingteam: MerchandisingIdentitygeneric (OIDC provider)team: PlatformLegacy ERPbig ball of mudvendor + 1 adminBI reportsreads Sales tablesU,S,OHS,PLD,Casync eventsU,OHS,PLD,CFU,OHS,PLD,ACLSales to Billing: sales.order.placed.v1Billing to Sales: billing.payment.captured.v1domain event PaymentCaptured, asyncSKUD,CFsync RESTU,OHS,PL (OIDC)to Billing tooUD,ACLsync HTTP exportshared DB: smellBilling and Catalog:separate ways (no line)Legend: arrow = upstream to downstreamsolid = integration, dashed = smell / noteSK bar = shared kernel (symmetric)
لبهالگوسازوکارچرا این الگو
Sales به FulfilmentCustomer-Supplier روی OHS + PLِ Salessales.order.placed.v1 ناهم‌زماننیازهای Fulfilment (بازهٔ تحویل) وارد برنامه‌ریزی Sales می‌شود
Sales به BillingOHS + PL در بالادست، CF در پایین‌دستsales.order.placed.v1 ناهم‌زمانPL دقیقاً همان است که Billing لازم دارد؛ ترجمه نمی‌ارزد
Billing به SalesOHS + PL در بالادست (Billing)، ACL در پایین‌دست (Sales)billing.payment.captured.v1 ناهم‌زمان (نام یکپارچه‌سازی؛ کلاس رویداد دامنه در Billing PaymentCaptured است)Sales باید بداند کی Order.MarkPaid را صدا بزند؛ Sales هسته است، پس واژگان پرداخت Billing پشت یک ACL نازک می‌ماند (نه C/S: قاعدهٔ #7 در Context Mapper استفاده از ACL درون customer-supplier را توصیه نمی‌کند)
Sales و BillingShared KernelGo module / پکیج Composerسبد خرید و فاکتور باید یکسان گرد کنند
Catalog به SalesConformistREST هم‌زمانمدل محصول Catalog خوب و پایدار است
Identity به Sales و BillingOHS + PL (OpenID Connect)توکن، discovery، JWKSزیردامنهٔ generic؛ پروتکل استاندارد
ERP قدیمی به SalesACL در پایین‌دست؛ ERP یک BBoM استخروجی HTTP هم‌زمانمدل ERP ضعیف است؛ Sales هسته است
Billing و CatalogSeparate Waysنداردفاکتور از دادهٔ خطوط سفارش استفاده می‌کند
DB ِ Sales به گزارش‌های BIدیتابیس مشترک (بو)SQL مستقیمباید با event جایگزین شود
text
     One order across the map
1    Customer logs in: Identity (OHS/PL: OIDC) -> Sales conforms to token claims
2    Cart shows products: Catalog -> Sales (CF, sync REST)
3    Pay on account: Sales -> ERP ACL -> credit status "good"
4    Place: Sales writes order + outbox row (one transaction)
5    Relay publishes sales.order.placed.v1 -> Fulfilment (C/S) and Billing (CF)
6    Billing drafts invoice; VAT via shared-kernel rounding = same cent as the cart
7    Billing records PaymentCaptured -> outbox -> billing.payment.captured.v1 -> Sales (ACL)
8    Sales ACL translates it into Order.MarkPaid (Billing's payment words stay outside)

راه‌حل / نحوهٔ استفاده: همین نقشه به‌صورت کد contracts/contextmap.cml است. هر لبه همتای کدی در Go و Laravel دارد.

سازوکار (Mechanics) ​

کشیدن نقشهٔ کانتکست قدم به قدم حیاتی ​

  1. هر تیمی را که صاحب یک کانتکست است دعوت کنید، به‌علاوهٔ کسی که سیستم‌های قدیمی را می‌شناسد. نقشه‌ای که فقط معمارها می‌کشند آرزو را نشان می‌دهد.
  2. کانتکست‌ها را با نام فهرست کنید، از جمله مدل‌های ضمنی درون سیستم‌های قدیمی (Evans: "This includes the implicit models of non-object-oriented subsystems").
  3. برای هر جفتی که داده یا فراخوانی رد و بدل می‌کند یک خط بکشید و سازوکارش را رویش بنویسید.
  4. جهت را تعیین کنید با پرسیدن «اگر آن‌ها عوض شوند ما می‌شکنیم؟» U و D بنویسید.
  5. الگو را در هر سر نام ببرید (OHS، PL بالادست؛ CF، ACL پایین‌دست؛ یا SK، P برای متقارن).
  6. بوها را علامت بزنید: دیتابیس مشترک، big ball of mud، لبه‌های بی‌صاحب.
  7. تیم‌ها را روی نقشه بگذارید؛ جایی را که یک تیم بالادستِ تیم‌های زیادی است یادداشت کنید.
  8. به‌عنوان AS_IS ذخیره کنید؛ نقشهٔ TO_BE را فقط بعد از توافق روی همین یکی بکشید.

نقشه به‌صورت کد: CMLِ Context Mapper ​

مثال جاری به‌صورت فایل CML در پوشهٔ snippet. طوری نوشته شده که قواعد صفحهٔ Language Semantics در Context Mapper را رعایت کند (validator را اجرا نکرده‌ایم): روی لبهٔ customer-supplier نقش OHS نیامده (قاعدهٔ ۶)، با این‌که Sales از همان OHS به Fulfilment خدمت می‌دهد؛ ACL و CF هرگز با هم نیستند (قاعدهٔ ۳)؛ روی لبهٔ متقارن shared kernel نقشی نیست (قاعدهٔ ۴).

txt
/* The running example as Context Mapper CML (AS_IS = the map of today, not the wish). */
ContextMap ShopContextMap {
  type = SYSTEM_LANDSCAPE
  state = AS_IS

  contains Sales, Fulfilment, Billing, Catalog, Identity, LegacyERP

  /* Customer-supplier: Fulfilment's needs go into Sales planning.
     Context Mapper forbids OHS on a C/S edge (rule #6), so only PL is written here. */
  Fulfilment [C]<-[S,PL] Sales {
    implementationTechnology = "AMQP events: sales.order.placed.v1"
  }

  /* Open host service with a published language; Billing conforms to the PL. */
  Billing [D,CF]<-[U,OHS,PL] Sales {
    implementationTechnology = "AMQP events: sales.order.placed.v1"
  }

  /* The other way: Billing is upstream with its own OHS + PL, the integration
     event billing.payment.captured.v1 (domain event PaymentCaptured). Sales, the
     core, protects itself with a thin ACL that calls Order.MarkPaid. Not C/S:
     Context Mapper rule #7 advises against an ACL inside customer-supplier. */
  Sales [D,ACL]<-[U,OHS,PL] Billing {
    implementationTechnology = "AMQP events: billing.payment.captured.v1"
  }

  /* Tiny shared kernel: Money, Currency, rounding rule. */
  Sales [SK]<->[SK] Billing

  /* Sales takes Catalog's product model as-is. */
  Sales [D,CF]<-[U] Catalog {
    implementationTechnology = "REST: GET /products/{sku}"
  }

  /* Generic subdomain behind a standard protocol (OpenID Connect). */
  Sales [D,CF]<-[U,OHS,PL] Identity
  Billing [D,CF]<-[U,OHS,PL] Identity

  /* The ERP is a big ball of mud; Sales protects itself. */
  Sales [D,ACL]<-[U] LegacyERP {
    implementationTechnology = "HTTP export: GET /export/kunde/{kunnr}"
  }
}

BoundedContext Sales
BoundedContext Fulfilment
BoundedContext Billing
BoundedContext Catalog
BoundedContext Identity
BoundedContext LegacyERP

فایل‌های published language ​

OHSِ Sales یک قرارداد را در سه نما منتشر می‌کند: JSON Schema (منبع حقیقت)، Protobuf (برای مصرف‌کنندهٔ باینری) و AsyncAPI (کانال و عملیات).

json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://contracts.shop.example/sales/order_placed.v1.schema.json",
  "title": "sales.order.placed.v1",
  "description": "Published Language of the Sales context. Additive changes only within v1; anything else is v2.",
  "type": "object",
  "required": ["event_id", "event_type", "occurred_at", "order_id", "customer_id", "currency", "total_minor", "lines"],
  "properties": {
    "event_id": { "type": "string" },
    "event_type": { "type": "string", "const": "sales.order.placed.v1" },
    "occurred_at": { "type": "string", "format": "date-time" },
    "order_id": { "type": "string" },
    "customer_id": { "type": "string" },
    "currency": { "type": "string", "pattern": "^[A-Z]{3}$" },
    "total_minor": { "type": "integer" },
    "lines": {
      "type": "array",
      "minItems": 1,
      "items": {
        "type": "object",
        "required": ["sku", "quantity", "unit_price_minor"],
        "properties": {
          "sku": { "type": "string" },
          "quantity": { "type": "integer", "minimum": 1 },
          "unit_price_minor": { "type": "integer" }
        }
      }
    },
    "delivery_window": {
      "type": "object",
      "description": "Added in v1.1 for Fulfilment (customer-supplier request). Optional, so v1.0 consumers ignore it.",
      "properties": {
        "from": { "type": "string", "format": "date-time" },
        "to": { "type": "string", "format": "date-time" }
      }
    }
  }
}
proto
// Published Language of the Sales context, Protobuf form of sales.order.placed.v1.
// Rules: never renumber, never reuse a deleted number (reserve it), add fields only.
syntax = "proto3";

package shop.sales.v1;

option go_package = "shop.example/contracts/sales/v1;salesv1";

message OrderLine {
  string sku = 1;
  int32 quantity = 2;
  int64 unit_price_minor = 3;
}

message DeliveryWindow {
  string from = 1; // RFC 3339
  string to = 2;   // RFC 3339
}

message OrderPlaced {
  string event_id = 1;
  string occurred_at = 2; // RFC 3339
  string order_id = 3;
  string customer_id = 4;
  string currency = 5;    // ISO 4217
  int64 total_minor = 6;
  repeated OrderLine lines = 7;
  DeliveryWindow delivery_window = 8; // added in v1.1, optional
  reserved 9;                         // was "margin_minor": internal, removed before GA
  reserved "margin_minor";
}
yaml
# Open Host Service of the Sales context, described as AsyncAPI 3.0.
asyncapi: 3.0.0
info:
  title: Sales events (Open Host Service)
  version: 1.1.0
  description: Events Sales publishes for any downstream context. Owned by the Sales team.
servers:
  production:
    host: broker.shop.internal:5672
    protocol: amqp
channels:
  orderPlaced:
    address: sales.order.placed.v1
    messages:
      orderPlaced:
        $ref: '#/components/messages/OrderPlaced'
operations:
  publishOrderPlaced:
    action: send
    channel:
      $ref: '#/channels/orderPlaced'
components:
  messages:
    OrderPlaced:
      name: sales.order.placed.v1
      contentType: application/json
      payload:
        $ref: './order_placed.v1.schema.json'

هر پایین‌دست فیلدهایی را که می‌خواند ثبت می‌کند. CIِ Sales همهٔ این فایل‌ها را اجرا می‌کند (contract test):

json
{
  "consumer": "fulfilment",
  "relationship": "customer-supplier",
  "event": "sales.order.placed.v1",
  "paths": ["order_id", "occurred_at", "lines[].sku", "lines[].quantity", "delivery_window.from", "delivery_window.to"]
}

پیدا کردن لبه‌های پنهان در دیتابیس ​

دیتابیس مشترک لبه‌ای است که هیچ‌کس نکشیده. در PostgreSQL با یک role برای هر کانتکست، grantها و آمار نشان می‌دهند چه کسی به جدول‌های چه کسی دست می‌زند:

sql
-- Which roles can write tables in the sales schema? Anything but sales_app is an undrawn edge.
SELECT grantee, table_schema, table_name, privilege_type
FROM information_schema.role_table_grants
WHERE table_schema = 'sales'
  AND privilege_type IN ('INSERT', 'UPDATE', 'DELETE')
  AND grantee <> 'sales_app'
ORDER BY grantee, table_name;

-- Which sessions are reading sales tables right now, and from which application?
SELECT usename, application_name, left(query, 80) AS query
FROM pg_stat_activity
WHERE query ILIKE '%sales.%' AND usename <> 'sales_app';

-- Close the edge: BI keeps read access only to a published view, not to tables.
REVOKE SELECT ON ALL TABLES IN SCHEMA sales FROM bi_reader;
CREATE VIEW sales_published.orders_v1 AS
  SELECT id AS order_id, customer_id, currency, total_minor, placed_at
  FROM sales.orders;
GRANT USAGE ON SCHEMA sales_published TO bi_reader;
GRANT SELECT ON sales_published.orders_v1 TO bi_reader;

roleها، grantها و کمترین دسترسی در Database Security آمده‌اند. این view یک published language به شکل SQL است: شکلی نسخه‌دار و مستند که Sales قول نگه‌داشتنش را می‌دهد. پله‌ای میانی است؛ مقصد event است.

خطاها و شکست‌ها روی لبه ​

آنچه می‌بینیدکجامعنا روی نقشهبرخورد
HTTP 404 از خروجی ERPadapterِ ACLبالادست می‌گوید «چنین رکوردی نیست»ترجمه به sales.ErrCustomerNotFound / CustomerNotFound
HTTP 5xx، context deadline exceeded، ConnectionException در Laraveladapterِ ACLبالادست در دسترس نیستخطای دسترس‌پذیری، retry با backoff؛ هرگز «پیدا نشد»
protoc: شمارهٔ فیلد reserved است.protoِ PLکسی شمارهٔ فیلد حذف‌شده را دوباره به کار بردهشمارهٔ تازه بگیرید؛ Protobuf "will generate error messages if any future developers try to use these reserved field numbers"
contract test: "fulfilment needs lines[].quantity"CI تأمین‌کنندهقرارداد customer-supplier شکستهmerge نکنید؛ فیلد را نگه دارید یا v2 برنامه‌ریزی کنید
خطای decode در مصرف‌کنندهمصرف‌کنندهٔ conformistPL ناسازگار عوض شده یا تولیدکنندهٔ خرابپیام را dead-letter کنید (DLQ)؛ به بالادست هشدار دهید
event_type ناشناختهمصرف‌کنندهمسیریابی اشتباه یا نسخهٔ تازهرد کنید؛ v2 را به handler خودش بفرستید

Go ​

یک Go module (academy/context-maps-integration-patterns)، فقط کتابخانهٔ استاندارد. هر پکیج یک سر از یک لبهٔ نقشه است.

ACL: adapter، translator، facade ​

مدل Sales صاحب پورت است؛ هیچ‌وقت نام‌های ERP را نمی‌بیند.

go
// Package sales is the Sales bounded context (core). Its model speaks Sales
// language only; nothing here knows the ERP, Billing or the broker.
package sales

import (
	"context"
	"errors"

	"academy/context-maps-integration-patterns/kernel"
)

// ErrCustomerNotFound is the Sales-language "no such customer".
var ErrCustomerNotFound = errors.New("sales: customer not found")

// CustomerID identifies a customer inside Sales.
type CustomerID string

// CreditStatus is what Sales needs to decide whether an order may be placed
// on account. The ERP has no such concept; the ACL derives it.
type CreditStatus int

const (
	CreditUnknown CreditStatus = iota
	CreditGood
	CreditOnHold
	CreditBlocked
)

func (s CreditStatus) String() string {
	return [...]string{"unknown", "good", "on_hold", "blocked"}[s]
}

// Customer is the Sales view of a customer.
type Customer struct {
	ID          CustomerID
	DisplayName string
	Segment     string // "consumer" or "business"
	CreditLimit kernel.Money
	Credit      CreditStatus
}

// MayOrderOnAccount is a Sales rule, written in Sales words.
func (c Customer) MayOrderOnAccount(total kernel.Money) bool {
	return c.Credit == CreditGood && c.CreditLimit.Currency == total.Currency && total.Minor <= c.CreditLimit.Minor
}

// CustomerDirectory is the port Sales depends on. The ERP ACL implements it.
type CustomerDirectory interface {
	CustomerByID(ctx context.Context, id CustomerID) (Customer, error)
}

adapter با HTTP به ERP حرف می‌زند و رکورد خام را برمی‌گرداند:

go
// Package erp is the Anticorruption Layer between Sales and the legacy ERP.
// Three parts, each with one job:
//
//	client.go      adapter:    speaks the ERP's protocol and returns ERP records
//	translator.go  translator: ERP record -> Sales model (pure, no I/O)
//	directory.go   facade:     implements sales.CustomerDirectory for the rest of Sales
//
// Nothing outside this package imports Record or the ERP field names.
package erp

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"time"
)

// errNotFound is the adapter's "404"; the facade maps it to Sales language.
var errNotFound = errors.New("erp: record not found")

// Record is the customer master record exactly as the ERP exports it.
// SAP-style field names; every value is a string, as the export delivers it.
type Record struct {
	KUNNR string `json:"KUNNR"` // customer number, zero-padded to 10
	NAME1 string `json:"NAME1"` // name line 1
	NAME2 string `json:"NAME2"` // name line 2
	KTOKD string `json:"KTOKD"` // account group: Z001 consumer, Z002 business
	KLIMK string `json:"KLIMK"` // credit limit, decimal string "1500.00"
	WAERS string `json:"WAERS"` // currency key
	SPERR string `json:"SPERR"` // "X" = posting block
	CRBLB string `json:"CRBLB"` // "X" = credit block (on hold)
}

// Client is the adapter: it knows URLs, timeouts and status codes, nothing else.
type Client struct {
	BaseURL string
	HTTP    *http.Client
}

// NewClient returns an adapter with a bounded timeout: the ERP is slow.
func NewClient(base string) *Client {
	return &Client{BaseURL: base, HTTP: &http.Client{Timeout: 2 * time.Second}}
}

// FetchCustomer calls GET /export/kunde/{kunnr}.
func (c *Client) FetchCustomer(ctx context.Context, kunnr string) (Record, error) {
	u := c.BaseURL + "/export/kunde/" + url.PathEscape(kunnr)
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
	if err != nil {
		return Record{}, err
	}
	res, err := c.HTTP.Do(req)
	if err != nil {
		return Record{}, fmt.Errorf("erp: call failed: %w", err)
	}
	defer res.Body.Close()
	switch {
	case res.StatusCode == http.StatusNotFound:
		return Record{}, errNotFound
	case res.StatusCode != http.StatusOK:
		return Record{}, fmt.Errorf("erp: unexpected status %d", res.StatusCode)
	}
	var r Record
	if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
		return Record{}, fmt.Errorf("erp: bad payload: %w", err)
	}
	return r, nil
}

translator یک تابع خالص است: شناسه‌ها، اعشارها، پرچم‌ها و گروه‌های حساب به مفاهیم Sales تبدیل می‌شوند.

go
package erp

import (
	"fmt"
	"strconv"
	"strings"

	"academy/context-maps-integration-patterns/kernel"
	"academy/context-maps-integration-patterns/sales"
)

// ToKUNNR maps a Sales id ("cus_77") to the ERP key ("0000000077").
func ToKUNNR(id sales.CustomerID) (string, error) {
	n := strings.TrimPrefix(string(id), "cus_")
	if n == string(id) || n == "" {
		return "", fmt.Errorf("erp: %q is not a Sales customer id", id)
	}
	if _, err := strconv.ParseUint(n, 10, 64); err != nil {
		return "", fmt.Errorf("erp: %q is not numeric", id)
	}
	if len(n) > 10 {
		return "", fmt.Errorf("erp: %q is longer than KUNNR allows", id)
	}
	return strings.Repeat("0", 10-len(n)) + n, nil
}

// Translate turns an ERP record into the Sales Customer. Pure function: no
// I/O, so every legacy quirk gets a table-driven test.
func Translate(r Record) (sales.Customer, error) {
	n := strings.TrimLeft(strings.TrimSpace(r.KUNNR), "0")
	if n == "" {
		return sales.Customer{}, fmt.Errorf("erp: empty KUNNR")
	}
	limit, err := parseAmount(r.KLIMK, kernel.Currency(strings.TrimSpace(r.WAERS)))
	if err != nil {
		return sales.Customer{}, err
	}
	return sales.Customer{
		ID:          sales.CustomerID("cus_" + n),
		DisplayName: strings.TrimSpace(strings.TrimSpace(r.NAME1) + " " + strings.TrimSpace(r.NAME2)),
		Segment:     segment(r.KTOKD),
		CreditLimit: limit,
		Credit:      credit(r.SPERR, r.CRBLB),
	}, nil
}

// segment: the ERP's account groups become Sales segments.
func segment(ktokd string) string {
	switch strings.TrimSpace(ktokd) {
	case "Z002":
		return "business"
	default: // Z001 and every group nobody documented
		return "consumer"
	}
}

// credit derives a Sales concept from two ERP flags. A posting block beats a
// credit block.
func credit(sperr, crblb string) sales.CreditStatus {
	switch {
	case strings.TrimSpace(sperr) == "X":
		return sales.CreditBlocked
	case strings.TrimSpace(crblb) == "X":
		return sales.CreditOnHold
	default:
		return sales.CreditGood
	}
}

// parseAmount reads "1500.00", "1.500,00" or "" (no limit = 0) into minor units.
func parseAmount(s string, c kernel.Currency) (kernel.Money, error) {
	s = strings.TrimSpace(s)
	if s == "" {
		return kernel.New(0, c)
	}
	if strings.Contains(s, ",") { // German export: 1.500,00
		s = strings.ReplaceAll(s, ".", "")
		s = strings.ReplaceAll(s, ",", ".")
	}
	whole, frac, _ := strings.Cut(s, ".")
	frac = (frac + "00")[:2]
	minor, err := strconv.ParseInt(whole+frac, 10, 64)
	if err != nil {
		return kernel.Money{}, fmt.Errorf("erp: bad KLIMK %q: %w", s, err)
	}
	return kernel.New(minor, c)
}

facade پورت را پیاده می‌کند و خطاها را ترجمه می‌کند:

go
package erp

import (
	"context"
	"errors"
	"fmt"

	"academy/context-maps-integration-patterns/sales"
)

// fetcher is what the facade needs from the adapter (lets tests swap it).
type fetcher interface {
	FetchCustomer(ctx context.Context, kunnr string) (Record, error)
}

// Directory is the facade: the only type the rest of Sales sees, through the
// sales.CustomerDirectory port.
type Directory struct{ erp fetcher }

// NewDirectory wires the facade to an adapter.
func NewDirectory(f fetcher) *Directory { return &Directory{erp: f} }

var _ sales.CustomerDirectory = (*Directory)(nil)

// CustomerByID answers in Sales language and Sales errors only.
func (d *Directory) CustomerByID(ctx context.Context, id sales.CustomerID) (sales.Customer, error) {
	kunnr, err := ToKUNNR(id)
	if err != nil {
		return sales.Customer{}, sales.ErrCustomerNotFound
	}
	rec, err := d.erp.FetchCustomer(ctx, kunnr)
	if errors.Is(err, errNotFound) {
		return sales.Customer{}, sales.ErrCustomerNotFound
	}
	if err != nil {
		return sales.Customer{}, fmt.Errorf("customer directory unavailable: %w", err)
	}
	return Translate(rec)
}

تست‌ها: جدولی از عجایب سیستم قدیمی، و کل لایه در برابر یک ERP جعلی روی HTTP واقعی.

go
package erp

import (
	"testing"

	"academy/context-maps-integration-patterns/sales"
)

func TestTranslateLegacyQuirks(t *testing.T) {
	cases := []struct {
		name       string
		rec        Record
		wantID     sales.CustomerID
		wantSeg    string
		wantMinor  int64
		wantCredit sales.CreditStatus
	}{
		{"business, dot decimal", Record{KUNNR: "0000000077", NAME1: "Acme ", NAME2: "GmbH", KTOKD: "Z002", KLIMK: "1500.00", WAERS: "EUR"}, "cus_77", "business", 150000, sales.CreditGood},
		{"german decimal", Record{KUNNR: "0000000078", NAME1: "Kim", KTOKD: "Z001", KLIMK: "1.500,5", WAERS: "EUR"}, "cus_78", "consumer", 150050, sales.CreditGood},
		{"no limit, credit block", Record{KUNNR: "0000000079", NAME1: "Lee", KTOKD: "Z001", KLIMK: "", WAERS: "EUR", CRBLB: "X"}, "cus_79", "consumer", 0, sales.CreditOnHold},
		{"posting block wins", Record{KUNNR: "0000000080", NAME1: "Ng", KTOKD: "Z009", KLIMK: "10", WAERS: "USD", SPERR: "X", CRBLB: "X"}, "cus_80", "consumer", 1000, sales.CreditBlocked},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			got, err := Translate(c.rec)
			if err != nil {
				t.Fatal(err)
			}
			if got.ID != c.wantID || got.Segment != c.wantSeg || got.CreditLimit.Minor != c.wantMinor || got.Credit != c.wantCredit {
				t.Fatalf("got %+v", got)
			}
		})
	}
}

func TestTranslateRejectsGarbage(t *testing.T) {
	if _, err := Translate(Record{KUNNR: "0000000081", KLIMK: "lots", WAERS: "EUR"}); err == nil {
		t.Fatal("bad amount accepted")
	}
	if _, err := Translate(Record{KUNNR: "0000000082", KLIMK: "1", WAERS: "euro"}); err == nil {
		t.Fatal("bad currency accepted")
	}
}

func TestToKUNNR(t *testing.T) {
	if k, _ := ToKUNNR("cus_77"); k != "0000000077" {
		t.Fatalf("got %q", k)
	}
	if _, err := ToKUNNR("77"); err == nil {
		t.Fatal("id without prefix accepted")
	}
}
go
package erp

import (
	"context"
	"errors"
	"net/http"
	"net/http/httptest"
	"testing"

	"academy/context-maps-integration-patterns/sales"
)

// A fake ERP over real HTTP: tests the adapter, translator and facade together.
func fakeERP(t *testing.T) *httptest.Server {
	t.Helper()
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.URL.Path {
		case "/export/kunde/0000000077":
			w.Header().Set("Content-Type", "application/json")
			_, _ = w.Write([]byte(`{"KUNNR":"0000000077","NAME1":"Acme","NAME2":"GmbH","KTOKD":"Z002","KLIMK":"1500.00","WAERS":"EUR","SPERR":"","CRBLB":""}`))
		case "/export/kunde/0000000500":
			w.WriteHeader(http.StatusInternalServerError)
		default:
			w.WriteHeader(http.StatusNotFound)
		}
	}))
}

func TestDirectorySpeaksSalesLanguage(t *testing.T) {
	srv := fakeERP(t)
	defer srv.Close()
	dir := NewDirectory(NewClient(srv.URL))
	ctx := context.Background()

	c, err := dir.CustomerByID(ctx, "cus_77")
	if err != nil || c.DisplayName != "Acme GmbH" || c.Credit != sales.CreditGood {
		t.Fatalf("got %+v, %v", c, err)
	}
	if _, err := dir.CustomerByID(ctx, "cus_1"); !errors.Is(err, sales.ErrCustomerNotFound) {
		t.Fatalf("404 should become sales.ErrCustomerNotFound, got %v", err)
	}
	if _, err := dir.CustomerByID(ctx, "cus_500"); err == nil || errors.Is(err, sales.ErrCustomerNotFound) {
		t.Fatalf("500 should be an availability error, got %v", err)
	}
}

OHS و published language آن ​

binding زبان منتشرشده در Go:

go
// Package orderplaced holds the Go binding of the Published Language
// sales.order.placed.v1. The JSON Schema in contracts/sales is the source of
// truth; this file mirrors it and contract_test.go keeps them in step.
package orderplaced

// EventType is the wire name, also the broker routing key.
const EventType = "sales.order.placed.v1"

// Line is one order line on the wire.
type Line struct {
	SKU            string `json:"sku"`
	Quantity       int64  `json:"quantity"`
	UnitPriceMinor int64  `json:"unit_price_minor"`
}

// Window is the delivery window (added in v1.1, optional).
type Window struct {
	From string `json:"from"`
	To   string `json:"to"`
}

// V1 is the event payload. Additive changes only; a breaking change is V2 on
// a new routing key, published in parallel until consumers have moved.
type V1 struct {
	EventID        string  `json:"event_id"`
	EventType      string  `json:"event_type"`
	OccurredAt     string  `json:"occurred_at"`
	OrderID        string  `json:"order_id"`
	CustomerID     string  `json:"customer_id"`
	Currency       string  `json:"currency"`
	TotalMinor     int64   `json:"total_minor"`
	Lines          []Line  `json:"lines"`
	DeliveryWindow *Window `json:"delivery_window,omitempty"`
}

سفارش Sales داده‌های داخلی دارد که نباید نشت کنند:

go
package sales

import (
	"time"

	"academy/context-maps-integration-patterns/kernel"
)

// Line is one order line in the Sales model.
type Line struct {
	SKU       string
	Quantity  int64
	UnitPrice kernel.Money
}

// Order is the Sales aggregate, reduced to what this chapter needs. It holds
// internal data (MarginMinor, SalesRep) that must never leak into the
// published language.
type Order struct {
	ID          string
	CustomerID  CustomerID
	Lines       []Line
	PlacedAt    time.Time
	DeliverFrom time.Time
	DeliverTo   time.Time
	MarginMinor int64  // internal: commercial secret
	SalesRep    string // internal: commission
}

// Total sums the lines. Errors on mixed currencies.
func (o Order) Total() (kernel.Money, error) {
	if len(o.Lines) == 0 {
		return kernel.Money{}, nil
	}
	total := kernel.Money{Currency: o.Lines[0].UnitPrice.Currency}
	for _, l := range o.Lines {
		var err error
		if total, err = total.Add(l.UnitPrice.Times(l.Quantity)); err != nil {
			return kernel.Money{}, err
		}
	}
	return total, nil
}

publisher خروجی را نگاشت می‌کند و در outbox می‌نویسد:

go
// Package ohs is the Open Host Service of Sales: one protocol for every
// downstream, expressed in the published language, never in the internal model.
package ohs

import (
	"context"
	"encoding/json"
	"time"

	"academy/context-maps-integration-patterns/contracts/orderplaced"
	"academy/context-maps-integration-patterns/sales"
)

// Outbox stores the message in the same transaction as the order; a relay
// publishes it later (see the Transactional Outbox chapter).
type Outbox interface {
	Add(ctx context.Context, routingKey string, payload []byte) error
}

// Publisher maps internal orders to the published language.
type Publisher struct {
	Outbox Outbox
	NewID  func() string
}

// ToV1 is the outbound translation: internal Order -> published language.
// MarginMinor and SalesRep stay inside Sales.
func ToV1(eventID string, o sales.Order) (orderplaced.V1, error) {
	total, err := o.Total()
	if err != nil {
		return orderplaced.V1{}, err
	}
	ev := orderplaced.V1{
		EventID:    eventID,
		EventType:  orderplaced.EventType,
		OccurredAt: o.PlacedAt.UTC().Format(time.RFC3339),
		OrderID:    o.ID,
		CustomerID: string(o.CustomerID),
		Currency:   string(total.Currency),
		TotalMinor: total.Minor,
	}
	for _, l := range o.Lines {
		ev.Lines = append(ev.Lines, orderplaced.Line{SKU: l.SKU, Quantity: l.Quantity, UnitPriceMinor: l.UnitPrice.Minor})
	}
	if !o.DeliverFrom.IsZero() {
		ev.DeliveryWindow = &orderplaced.Window{
			From: o.DeliverFrom.UTC().Format(time.RFC3339),
			To:   o.DeliverTo.UTC().Format(time.RFC3339),
		}
	}
	return ev, nil
}

// OrderPlaced writes the event to the outbox.
func (p Publisher) OrderPlaced(ctx context.Context, o sales.Order) error {
	ev, err := ToV1(p.NewID(), o)
	if err != nil {
		return err
	}
	b, err := json.Marshal(ev)
	if err != nil {
		return err
	}
	return p.Outbox.Add(ctx, orderplaced.EventType, b)
}

مصرف‌کنندهٔ conformist ​

Billing نوع‌های منتشرشده را مدل ورودی خودش می‌کند، با event_id تکراری‌ها را حذف می‌کند و مالیات بر ارزش افزوده را با قاعدهٔ shared kernel حساب می‌کند:

go
// Package billing is a Conformist downstream of the Sales open host service:
// it uses the published language types as its own input model, with no
// translation layer. That is cheap and fine while the PL is stable and
// Billing's needs are a subset of it.
package billing

import (
	"encoding/json"
	"fmt"
	"sync"

	"academy/context-maps-integration-patterns/contracts/orderplaced"
	"academy/context-maps-integration-patterns/kernel"
)

// VATBasisPoints is 19% for this example.
const VATBasisPoints = 1900

// InvoiceDraft is Billing's record; its fields are named after the PL on purpose.
type InvoiceDraft struct {
	OrderID    string
	CustomerID string
	Net        kernel.Money
	VAT        kernel.Money
}

// Handler consumes sales.order.placed.v1 at least once; it deduplicates by event_id.
type Handler struct {
	mu       sync.Mutex
	seen     map[string]bool
	Invoices []InvoiceDraft
}

// NewHandler returns an empty handler.
func NewHandler() *Handler { return &Handler{seen: map[string]bool{}} }

// Handle decodes the published language directly (conformist) and drafts an invoice.
func (h *Handler) Handle(payload []byte) error {
	var ev orderplaced.V1
	if err := json.Unmarshal(payload, &ev); err != nil {
		return fmt.Errorf("billing: undecodable %s: %w", orderplaced.EventType, err)
	}
	if ev.EventType != orderplaced.EventType {
		return fmt.Errorf("billing: unexpected event type %q", ev.EventType)
	}
	h.mu.Lock()
	defer h.mu.Unlock()
	if h.seen[ev.EventID] {
		return nil // redelivery
	}
	net, err := kernel.New(ev.TotalMinor, kernel.Currency(ev.Currency))
	if err != nil {
		return err
	}
	h.Invoices = append(h.Invoices, InvoiceDraft{
		OrderID:    ev.OrderID,
		CustomerID: ev.CustomerID,
		Net:        net,
		VAT:        net.PercentOf(VATBasisPoints), // shared-kernel rounding rule
	})
	h.seen[ev.EventID] = true
	return nil
}
go
package billing

import (
	"os"
	"testing"
)

// Billing consumes the published example message, twice.
func TestConformistConsumerUsesPublishedExample(t *testing.T) {
	payload, err := os.ReadFile("../../contracts/sales/order_placed.v1.example.json")
	if err != nil {
		t.Fatal(err)
	}
	h := NewHandler()
	for i := 0; i < 2; i++ { // at-least-once delivery
		if err := h.Handle(payload); err != nil {
			t.Fatal(err)
		}
	}
	if len(h.Invoices) != 1 {
		t.Fatalf("want 1 invoice after redelivery, got %d", len(h.Invoices))
	}
	inv := h.Invoices[0]
	if inv.Net.Minor != 4500 || inv.VAT.Minor != 855 || inv.Net.Currency != "EUR" {
		t.Fatalf("got %+v", inv)
	}
}

shared kernel و سیاست نسخه‌گذاری‌اش ​

go
// Package kernel is the Shared Kernel between Sales and Billing.
//
// What is in it: Money, Currency and the one rounding rule both contexts must
// agree on. Nothing else. No Order, no Customer, no Invoice.
//
// Versioning policy (co-owned by the Sales and Billing teams):
//   - Semantic versioning; Version below is the single source of truth.
//   - PATCH: bug fix, no behaviour change visible to callers.
//   - MINOR: additive only (a new function or currency); both teams review.
//   - MAJOR: any change to existing behaviour, including rounding; both teams
//     must approve, and both upgrade in the same planning cycle.
//   - Every change needs a green CI run in both contexts before it is tagged.
//   - Owners: CODEOWNERS lists one reviewer from each team for this directory.
package kernel

import (
	"errors"
	"fmt"
)

// Version of the shared kernel. Bump according to the policy above.
const Version = "1.2.0"

// ErrCurrencyMismatch is returned when two amounts in different currencies meet.
var ErrCurrencyMismatch = errors.New("kernel: currency mismatch")

// Currency is an ISO 4217 code such as "EUR".
type Currency string

// Valid reports whether the code has three upper-case letters.
func (c Currency) Valid() bool {
	if len(c) != 3 {
		return false
	}
	for _, r := range c {
		if r < 'A' || r > 'Z' {
			return false
		}
	}
	return true
}

// Money is an amount in minor units (cents) and a currency.
type Money struct {
	Minor    int64
	Currency Currency
}

// New returns Money or an error for an invalid currency.
func New(minor int64, c Currency) (Money, error) {
	if !c.Valid() {
		return Money{}, fmt.Errorf("kernel: invalid currency %q", c)
	}
	return Money{Minor: minor, Currency: c}, nil
}

// Add sums two amounts of the same currency.
func (m Money) Add(o Money) (Money, error) {
	if m.Currency != o.Currency {
		return Money{}, ErrCurrencyMismatch
	}
	return Money{Minor: m.Minor + o.Minor, Currency: m.Currency}, nil
}

// Times multiplies by a quantity.
func (m Money) Times(q int64) Money { return Money{Minor: m.Minor * q, Currency: m.Currency} }

// PercentOf returns basisPoints/10000 of m, rounded half away from zero.
// This is THE rounding rule: Sales shows it on the cart, Billing puts it on
// the invoice. If the two ever disagree by one cent, customers complain.
func (m Money) PercentOf(basisPoints int64) Money {
	n := m.Minor * basisPoints
	q, r := n/10000, n%10000
	if r >= 5000 {
		q++
	} else if r <= -5000 {
		q--
	}
	return Money{Minor: q, Currency: m.Currency}
}
go
package kernel

import "testing"

// These cases are the kernel's contract. Both teams run them in CI.
func TestRoundingRuleIsShared(t *testing.T) {
	eur := Currency("EUR")
	cases := []struct {
		minor, bp, want int64
	}{
		{1000, 1900, 190}, // 19% VAT on 10.00
		{1999, 1900, 380}, // 379.81 -> 380
		{1050, 500, 53},   // 52.5 -> 53 (half away from zero)
		{-1050, 500, -53}, // refunds round the same way
		{1, 1900, 0},      // 0.19 cent -> 0
		{4500, 0, 0},      // zero rate
		{12345, 10000, 12345},
	}
	for _, c := range cases {
		got := Money{Minor: c.minor, Currency: eur}.PercentOf(c.bp)
		if got.Minor != c.want {
			t.Errorf("PercentOf(%d, %d) = %d, want %d", c.minor, c.bp, got.Minor, c.want)
		}
	}
}

func TestAddRejectsMixedCurrencies(t *testing.T) {
	a, _ := New(100, "EUR")
	b, _ := New(100, "USD")
	if _, err := a.Add(b); err != ErrCurrencyMismatch {
		t.Fatalf("want ErrCurrencyMismatch, got %v", err)
	}
}

func TestNewRejectsBadCurrency(t *testing.T) {
	if _, err := New(1, "eur"); err == nil {
		t.Fatal("lower-case code accepted")
	}
}

contract test روی لبه ​

یک فایل تست چهار قول را بررسی می‌کند: مثال و خروجی واقعی publisher هر دو با schema می‌خوانند؛ هیچ فیلد داخلی نشت نمی‌کند؛ binding در Go و schema همان ویژگی‌ها را دارند؛ فایل انتظار هر مصرف‌کننده برآورده می‌شود.

go
package orderplaced_test

import (
	"encoding/json"
	"os"
	"path/filepath"
	"reflect"
	"regexp"
	"strings"
	"testing"
	"time"

	"academy/context-maps-integration-patterns/contracts/orderplaced"
	"academy/context-maps-integration-patterns/kernel"
	"academy/context-maps-integration-patterns/sales"
	"academy/context-maps-integration-patterns/sales/ohs"
)

const dir = "../../../contracts/sales/"

func load(t *testing.T, name string) any {
	t.Helper()
	b, err := os.ReadFile(dir + name)
	if err != nil {
		t.Fatal(err)
	}
	var v any
	if err := json.Unmarshal(b, &v); err != nil {
		t.Fatal(err)
	}
	return v
}

// validate checks the subset of JSON Schema used by our contracts: type,
// required, properties, items, const, pattern, minItems, minimum. A real
// project would use a full validator library; the idea is the same.
func validate(schema map[string]any, v any, path string) []string {
	var errs []string
	switch schema["type"] {
	case "object":
		obj, ok := v.(map[string]any)
		if !ok {
			return []string{path + ": not an object"}
		}
		for _, r := range asSlice(schema["required"]) {
			if _, ok := obj[r.(string)]; !ok {
				errs = append(errs, path+"."+r.(string)+": required")
			}
		}
		props, _ := schema["properties"].(map[string]any)
		for k, val := range obj {
			if ps, ok := props[k].(map[string]any); ok {
				errs = append(errs, validate(ps, val, path+"."+k)...)
			}
		}
	case "array":
		arr, ok := v.([]any)
		if !ok {
			return []string{path + ": not an array"}
		}
		if m, ok := schema["minItems"].(float64); ok && float64(len(arr)) < m {
			errs = append(errs, path+": too few items")
		}
		if is, ok := schema["items"].(map[string]any); ok {
			for _, it := range arr {
				errs = append(errs, validate(is, it, path+"[]")...)
			}
		}
	case "string":
		s, ok := v.(string)
		if !ok {
			return []string{path + ": not a string"}
		}
		if c, ok := schema["const"].(string); ok && s != c {
			errs = append(errs, path+": must be "+c)
		}
		if p, ok := schema["pattern"].(string); ok && !regexp.MustCompile(p).MatchString(s) {
			errs = append(errs, path+": does not match "+p)
		}
	case "integer":
		n, ok := v.(float64)
		if !ok || n != float64(int64(n)) {
			return []string{path + ": not an integer"}
		}
		if m, ok := schema["minimum"].(float64); ok && n < m {
			errs = append(errs, path+": below minimum")
		}
	}
	return errs
}

func asSlice(v any) []any { s, _ := v.([]any); return s }

func sampleOrder() sales.Order {
	eur := kernel.Currency("EUR")
	at := time.Date(2026, 11, 25, 10, 15, 0, 0, time.UTC)
	return sales.Order{
		ID: "ord_1042", CustomerID: "cus_77", PlacedAt: at,
		DeliverFrom: at.Add(46 * time.Hour), DeliverTo: at.Add(50 * time.Hour),
		Lines: []sales.Line{
			{SKU: "MUG-RED", Quantity: 2, UnitPrice: kernel.Money{Minor: 1250, Currency: eur}},
			{SKU: "TEA-ASSAM", Quantity: 1, UnitPrice: kernel.Money{Minor: 2000, Currency: eur}},
		},
		MarginMinor: 1900, SalesRep: "rep-12",
	}
}

func publisherOutput(t *testing.T) any {
	t.Helper()
	ev, err := ohs.ToV1("evt_test", sampleOrder())
	if err != nil {
		t.Fatal(err)
	}
	b, _ := json.Marshal(ev)
	var v any
	_ = json.Unmarshal(b, &v)
	return v
}

// The published example and the real publisher output both satisfy the schema.
func TestPublishedLanguageSchema(t *testing.T) {
	schema := load(t, "order_placed.v1.schema.json").(map[string]any)
	for name, doc := range map[string]any{"example": load(t, "order_placed.v1.example.json"), "publisher": publisherOutput(t)} {
		if errs := validate(schema, doc, "$"); len(errs) > 0 {
			t.Errorf("%s violates the published language: %v", name, errs)
		}
	}
}

// Internal Sales data never leaks into the published language.
func TestNoInternalFieldsLeak(t *testing.T) {
	out := publisherOutput(t).(map[string]any)
	for _, k := range []string{"margin_minor", "MarginMinor", "sales_rep", "SalesRep"} {
		if _, ok := out[k]; ok {
			t.Errorf("internal field %q leaked", k)
		}
	}
}

// Every property in the schema has a JSON tag in the Go binding, and back.
func TestGoBindingMatchesSchema(t *testing.T) {
	schema := load(t, "order_placed.v1.schema.json").(map[string]any)
	props := schema["properties"].(map[string]any)
	tags := map[string]bool{}
	typ := reflect.TypeOf(orderplaced.V1{})
	for i := 0; i < typ.NumField(); i++ {
		tag, _, _ := strings.Cut(typ.Field(i).Tag.Get("json"), ",")
		tags[tag] = true
		if _, ok := props[tag]; !ok {
			t.Errorf("Go field %s (%q) not in schema", typ.Field(i).Name, tag)
		}
	}
	for p := range props {
		if !tags[p] {
			t.Errorf("schema property %q missing in Go binding", p)
		}
	}
}

// Consumer-driven contracts: each downstream lists the paths it reads; the
// supplier's CI (this test) fails before a release that would break them.
func TestConsumerExpectations(t *testing.T) {
	files, _ := filepath.Glob(dir + "consumers/*.expects.json")
	if len(files) == 0 {
		t.Fatal("no consumer expectations found")
	}
	out := publisherOutput(t)
	for _, f := range files {
		exp := load(t, "consumers/"+filepath.Base(f)).(map[string]any)
		for _, p := range asSlice(exp["paths"]) {
			if !has(out, strings.Split(p.(string), ".")) {
				t.Errorf("%s needs %q, publisher does not provide it", exp["consumer"], p)
			}
		}
	}
}

func has(v any, path []string) bool {
	if len(path) == 0 {
		return true
	}
	key := path[0]
	if strings.HasSuffix(key, "[]") {
		obj, ok := v.(map[string]any)
		if !ok {
			return false
		}
		arr, ok := obj[strings.TrimSuffix(key, "[]")].([]any)
		if !ok || len(arr) == 0 {
			return false
		}
		return has(arr[0], path[1:])
	}
	obj, ok := v.(map[string]any)
	if !ok {
		return false
	}
	next, ok := obj[key]
	return ok && has(next, path[1:])
}

نگاه Go ​

  • پکیج‌ها درزها هستند. sales/acl/erp تنها پکیجی است که نام فیلدهای ERP را می‌شناسد؛ contracts/orderplaced تنها چیزی است که Billing از Sales import می‌کند. پوشهٔ internal/ در Go می‌تواند این قاعده را به کامپایلر بسپارد (رکورد ERP را به sales/acl/erp/internal/ ببرید).
  • پورت‌ها به‌شکل interfaceهای کوچک. sales.CustomerDirectory یک متد دارد؛ facade آن را ضمنی برآورده می‌کند (var _ sales.CustomerDirectory = (*Directory)(nil) مستندش می‌کند).
  • net/http/httptest یک بالادست جعلی روی HTTP واقعی می‌دهد، تا adapter، translator و facade با هم و بدون ERP تست شوند.
  • context.Context مهلت را تا adapter می‌برد؛ http.Client.Timeout فراخوانی کند سیستم قدیمی را محدود می‌کند.
  • Schemaها: struct tagهای encoding/json همان binding هستند؛ در production یک validator کامل JSON Schema یا نوع‌های تولیدشده با protoc-gen-go گزینه‌اند. در دنیای واقعی shared kernel یک Go module جداست (go get shop.example/kernel@v1.2.0)، تا نسخه‌اش در go.mod هر کانتکست دیده شود.
  • Watermill یا یک کلاینت سادهٔ AMQP eventها را حمل می‌کند؛ الگو به کتابخانه وابسته نیست.

Laravel ​

Laravel 13، PHP 8.4. کانتکست‌ها ماژول‌هایی زیر app/Modules/<Context> هستند؛ shared kernel یک پکیج path در Composer است.

ACL: adapter، translator، facade ​

php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Domain;

/** Port owned by Sales. The ERP anticorruption layer implements it. */
interface CustomerDirectory
{
    /**
     * @throws CustomerNotFound             the customer does not exist
     * @throws CustomerDirectoryUnavailable the source cannot be asked right now
     */
    public function customerById(string $id): Customer;
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Domain;

use RuntimeException;

/** Sales-language "we cannot ask right now"; never confused with "not found". */
final class CustomerDirectoryUnavailable extends RuntimeException {}
php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Domain;

use Shop\SharedKernel\Money;

/** The Sales view of a customer. No ERP field name appears here. */
final readonly class Customer
{
    public function __construct(
        public string $id,            // "cus_77"
        public string $displayName,
        public string $segment,       // "consumer" | "business"
        public Money $creditLimit,
        public CreditStatus $credit,
    ) {}

    public function mayOrderOnAccount(Money $total): bool
    {
        return $this->credit === CreditStatus::Good
            && $total->currency === $this->creditLimit->currency
            && $total->minor <= $this->creditLimit->minor;
    }
}

adapter از timeout، connectTimeout، retry و throw در HTTP client استفاده می‌کند (همه در صفحهٔ HTTP Client در Laravel 13 مستند شده‌اند):

php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Acl\Erp;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Throwable;

/**
 * Adapter: speaks the ERP's export protocol and returns the raw record.
 * Knows URLs, timeouts and status codes; knows nothing about Sales.
 */
final class ErpCustomerClient
{
    public function __construct(private readonly string $baseUrl) {}

    /**
     * @return array<string, string>|null  the KNA1-style record, or null on 404
     *
     * @throws RequestException on any other failure
     */
    public function fetch(string $kunnr): ?array
    {
        $response = Http::baseUrl($this->baseUrl)
            ->acceptJson()
            ->connectTimeout(1)
            ->timeout(2)
            // Retry only what can heal: network errors and 5xx, never a 404.
            ->retry(2, 200, fn (Throwable $e) => $e instanceof ConnectionException
                || ($e instanceof RequestException && $e->response->serverError()), throw: false)
            ->get('/export/kunde/'.rawurlencode($kunnr));

        if ($response->status() === 404) {
            return null;
        }

        return $response->throw()->json();
    }
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Acl\Erp;

use App\Modules\Sales\Domain\CreditStatus;
use App\Modules\Sales\Domain\Customer;
use InvalidArgumentException;
use Shop\SharedKernel\Money;

/** Translator: ERP record -> Sales model. Pure; every quirk has a test. */
final class ErpCustomerTranslator
{
    public static function toKunnr(string $salesId): string
    {
        if (preg_match('/^cus_(\d{1,10})$/', $salesId, $m) !== 1) {
            throw new InvalidArgumentException("{$salesId} is not a Sales customer id");
        }

        return str_pad($m[1], 10, '0', STR_PAD_LEFT);
    }

    /** @param array<string, string> $r */
    public function toCustomer(array $r): Customer
    {
        $number = ltrim(trim($r['KUNNR'] ?? ''), '0');
        if ($number === '') {
            throw new InvalidArgumentException('Empty KUNNR');
        }

        return new Customer(
            id: 'cus_'.$number,
            displayName: trim(trim($r['NAME1'] ?? '').' '.trim($r['NAME2'] ?? '')),
            segment: trim($r['KTOKD'] ?? '') === 'Z002' ? 'business' : 'consumer',
            creditLimit: $this->amount($r['KLIMK'] ?? '', trim($r['WAERS'] ?? '')),
            credit: match (true) {
                trim($r['SPERR'] ?? '') === 'X' => CreditStatus::Blocked,
                trim($r['CRBLB'] ?? '') === 'X' => CreditStatus::OnHold,
                default => CreditStatus::Good,
            },
        );
    }

    /** "1500.00", "1.500,00" or "" (no limit) -> minor units. */
    private function amount(string $raw, string $currency): Money
    {
        $s = trim($raw);
        if ($s === '') {
            return new Money(0, $currency);
        }
        if (str_contains($s, ',')) {
            $s = str_replace(['.', ','], ['', '.'], $s);
        }
        if (preg_match('/^(-?\d+)(?:\.(\d{1,2}))?$/', $s, $m) !== 1) {
            throw new InvalidArgumentException("Bad KLIMK {$raw}");
        }

        return new Money((int) ($m[1].str_pad($m[2] ?? '', 2, '0')), $currency);
    }
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Acl\Erp;

use App\Modules\Sales\Domain\Customer;
use App\Modules\Sales\Domain\CustomerDirectory;
use App\Modules\Sales\Domain\CustomerDirectoryUnavailable;
use App\Modules\Sales\Domain\CustomerNotFound;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use InvalidArgumentException;

/**
 * Facade: the only ACL class the rest of Sales sees (through the port).
 * Errors are translated too: no Laravel HTTP exception crosses the port.
 */
final class ErpCustomerDirectory implements CustomerDirectory
{
    public function __construct(
        private readonly ErpCustomerClient $client,
        private readonly ErpCustomerTranslator $translator,
    ) {}

    public function customerById(string $id): Customer
    {
        try {
            $kunnr = ErpCustomerTranslator::toKunnr($id);
        } catch (InvalidArgumentException) {
            throw new CustomerNotFound($id);
        }

        try {
            $record = $this->client->fetch($kunnr);
        } catch (ConnectionException|RequestException $e) {
            throw new CustomerDirectoryUnavailable('ERP customer export unavailable', previous: $e);
        }

        if ($record === null) {
            throw new CustomerNotFound($id);
        }

        return $this->translator->toCustomer($record);
    }
}

provider لبه را سیم‌کشی می‌کند: پورت Sales به ACLِ ERP بسته می‌شود.

php
<?php

declare(strict_types=1);

namespace App\Providers;

use App\Modules\Sales\Acl\Erp\ErpCustomerClient;
use App\Modules\Sales\Acl\Erp\ErpCustomerDirectory;
use App\Modules\Sales\Acl\Erp\ErpCustomerTranslator;
use App\Modules\Sales\Domain\CustomerDirectory;
use Illuminate\Support\ServiceProvider;

/** Wires each edge of the context map to its implementation. */
final class ContextMapServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // Sales <- LegacyERP: anticorruption layer behind a Sales-owned port.
        $this->app->singleton(CustomerDirectory::class, fn () => new ErpCustomerDirectory(
            new ErpCustomerClient(config('services.erp.base_url')),
            new ErpCustomerTranslator(),
        ));
    }
}

تست‌ها با Pest؛ Http::fake جای ERP را می‌گیرد:

php
<?php

declare(strict_types=1);

use App\Modules\Sales\Acl\Erp\ErpCustomerClient;
use App\Modules\Sales\Acl\Erp\ErpCustomerDirectory;
use App\Modules\Sales\Acl\Erp\ErpCustomerTranslator;
use App\Modules\Sales\Domain\CreditStatus;
use App\Modules\Sales\Domain\CustomerDirectoryUnavailable;
use App\Modules\Sales\Domain\CustomerNotFound;
use Illuminate\Support\Facades\Http;

describe('translator', function () {
    it('translates legacy quirks into Sales language', function (array $record, string $id, string $segment, int $limit, CreditStatus $credit) {
        $c = (new ErpCustomerTranslator())->toCustomer($record);

        expect($c->id)->toBe($id)
            ->and($c->segment)->toBe($segment)
            ->and($c->creditLimit->minor)->toBe($limit)
            ->and($c->credit)->toBe($credit);
    })->with([
        'business, dot decimal' => [['KUNNR' => '0000000077', 'NAME1' => 'Acme', 'KTOKD' => 'Z002', 'KLIMK' => '1500.00', 'WAERS' => 'EUR'], 'cus_77', 'business', 150000, CreditStatus::Good],
        'german decimal' => [['KUNNR' => '0000000078', 'NAME1' => 'Kim', 'KTOKD' => 'Z001', 'KLIMK' => '1.500,5', 'WAERS' => 'EUR'], 'cus_78', 'consumer', 150050, CreditStatus::Good],
        'credit block' => [['KUNNR' => '0000000079', 'NAME1' => 'Lee', 'KTOKD' => 'Z001', 'KLIMK' => '', 'WAERS' => 'EUR', 'CRBLB' => 'X'], 'cus_79', 'consumer', 0, CreditStatus::OnHold],
        'posting block wins' => [['KUNNR' => '0000000080', 'NAME1' => 'Ng', 'KTOKD' => 'Z009', 'KLIMK' => '10', 'WAERS' => 'USD', 'SPERR' => 'X', 'CRBLB' => 'X'], 'cus_80', 'consumer', 1000, CreditStatus::Blocked],
    ]);

    it('maps ids both ways', function () {
        expect(ErpCustomerTranslator::toKunnr('cus_77'))->toBe('0000000077');
    });
});

describe('directory (facade + adapter + translator)', function () {
    beforeEach(function () {
        Http::fake([
            'erp.test/export/kunde/0000000077' => Http::response([
                'KUNNR' => '0000000077', 'NAME1' => 'Acme', 'NAME2' => 'GmbH', 'KTOKD' => 'Z002',
                'KLIMK' => '1500.00', 'WAERS' => 'EUR', 'SPERR' => '', 'CRBLB' => '',
            ], 200),
            'erp.test/export/kunde/0000000500' => Http::response([], 500),
            'erp.test/*' => Http::response([], 404),
        ]);
        $this->directory = new ErpCustomerDirectory(new ErpCustomerClient('https://erp.test'), new ErpCustomerTranslator());
    });

    it('answers in Sales language', function () {
        $c = $this->directory->customerById('cus_77');

        expect($c->displayName)->toBe('Acme GmbH')->and($c->credit)->toBe(CreditStatus::Good);
    });

    it('turns an ERP 404 into a Sales exception', function () {
        $this->directory->customerById('cus_1');
    })->throws(CustomerNotFound::class);

    it('turns an ERP 5xx into "unavailable", never "not found"', function () {
        $this->directory->customerById('cus_500');
    })->throws(CustomerDirectoryUnavailable::class);
});

OHS، published language و job همرنگ ​

php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Contracts;

/**
 * Published Language: sales.order.placed.v1. Mirrors
 * contracts/sales/order_placed.v1.schema.json, which is the source of truth.
 * Additive changes only; a breaking change is OrderPlacedV2 on a new key.
 */
final readonly class OrderPlacedV1
{
    public const string TYPE = 'sales.order.placed.v1';

    /** @param list<array{sku: string, quantity: int, unit_price_minor: int}> $lines */
    public function __construct(
        public string $eventId,
        public string $occurredAt,
        public string $orderId,
        public string $customerId,
        public string $currency,
        public int $totalMinor,
        public array $lines,
        public ?array $deliveryWindow = null, // v1.1, optional: {from, to}
    ) {}

    /** @return array<string, mixed> */
    public function toArray(): array
    {
        return array_filter([
            'event_id' => $this->eventId,
            'event_type' => self::TYPE,
            'occurred_at' => $this->occurredAt,
            'order_id' => $this->orderId,
            'customer_id' => $this->customerId,
            'currency' => $this->currency,
            'total_minor' => $this->totalMinor,
            'lines' => $this->lines,
            'delivery_window' => $this->deliveryWindow,
        ], fn ($v) => $v !== null);
    }

    /** @param array<string, mixed> $p */
    public static function fromArray(array $p): self
    {
        return new self(
            eventId: $p['event_id'],
            occurredAt: $p['occurred_at'],
            orderId: $p['order_id'],
            customerId: $p['customer_id'],
            currency: $p['currency'],
            totalMinor: $p['total_minor'],
            lines: $p['lines'],
            deliveryWindow: $p['delivery_window'] ?? null,
        );
    }
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Sales\Ohs;

use App\Modules\Sales\Contracts\OrderPlacedV1;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

/**
 * Open Host Service: maps the internal order to the published language and
 * stores it in the outbox inside the caller's transaction. A relay publishes
 * the outbox to the broker (see the Transactional Outbox chapter).
 */
final class OrderPlacedPublisher
{
    /**
     * @param array{id: string, customer_id: string, currency: string, placed_at: \DateTimeInterface,
     *              lines: list<array{sku: string, quantity: int, unit_price_minor: int}>,
     *              margin_minor: int, sales_rep: string,
     *              deliver_from?: \DateTimeInterface, deliver_to?: \DateTimeInterface} $order
     */
    public static function toV1(array $order, string $eventId): OrderPlacedV1
    {
        $total = array_sum(array_map(fn ($l) => $l['quantity'] * $l['unit_price_minor'], $order['lines']));

        // margin_minor and sales_rep are internal: they are simply not mapped.
        return new OrderPlacedV1(
            eventId: $eventId,
            occurredAt: $order['placed_at']->format(DATE_RFC3339),
            orderId: $order['id'],
            customerId: $order['customer_id'],
            currency: $order['currency'],
            totalMinor: $total,
            lines: array_map(fn ($l) => [
                'sku' => $l['sku'],
                'quantity' => $l['quantity'],
                'unit_price_minor' => $l['unit_price_minor'],
            ], $order['lines']),
            deliveryWindow: isset($order['deliver_from'], $order['deliver_to']) ? [
                'from' => $order['deliver_from']->format(DATE_RFC3339),
                'to' => $order['deliver_to']->format(DATE_RFC3339),
            ] : null,
        );
    }

    /** Call inside the same DB::transaction that saved the order. */
    public function publish(array $order): void
    {
        $event = self::toV1($order, (string) Str::ulid());

        DB::table('outbox')->insert([
            'id' => $event->eventId,
            'routing_key' => OrderPlacedV1::TYPE,
            'payload' => json_encode($event->toArray(), JSON_THROW_ON_ERROR),
            'created_at' => now(),
        ]);
    }
}
php
<?php

declare(strict_types=1);

namespace App\Modules\Billing\Jobs;

use App\Modules\Sales\Contracts\OrderPlacedV1;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;
use Shop\SharedKernel\Money;

/**
 * Billing is a Conformist downstream of the Sales OHS: it takes the published
 * language class as its input model, with no translation of its own.
 */
final class CreateInvoiceFromOrderPlaced implements ShouldQueue
{
    use Queueable;

    private const int VAT_BASIS_POINTS = 1900;

    /** @param array<string, mixed> $payload the decoded broker message */
    public function __construct(public array $payload) {}

    public function handle(): void
    {
        $event = OrderPlacedV1::fromArray($this->payload);
        $net = new Money($event->totalMinor, $event->currency);

        // Idempotent: the unique key on event_id absorbs redeliveries.
        DB::table('billing_invoice_drafts')->insertOrIgnore([
            'event_id' => $event->eventId,
            'order_id' => $event->orderId,
            'customer_id' => $event->customerId,
            'currency' => $net->currency,
            'net_minor' => $net->minor,
            'vat_minor' => $net->percentOf(self::VAT_BASIS_POINTS)->minor, // shared-kernel rule
            'created_at' => now(),
        ]);
    }
}

پکیج shared kernel ​

json
{
    "name": "shop/shared-kernel",
    "description": "Shared Kernel of Sales and Billing: Money, Currency, the rounding rule. Nothing else.",
    "type": "library",
    "version": "1.2.0",
    "license": "proprietary",
    "require": {
        "php": "^8.4"
    },
    "autoload": {
        "psr-4": {
            "Shop\\SharedKernel\\": "src/"
        }
    },
    "extra": {
        "owners": ["team-sales", "team-billing"],
        "versioning-policy": [
            "SemVer. PATCH = fix with no visible behaviour change.",
            "MINOR = additive only (new method, new currency); one reviewer from each team.",
            "MAJOR = any change to existing behaviour, rounding included; both teams approve and upgrade in the same cycle.",
            "A tag is cut only after both contexts' CI is green against the candidate."
        ]
    }
}
php
<?php

declare(strict_types=1);

namespace Shop\SharedKernel;

use InvalidArgumentException;

/**
 * Shared Kernel (Sales + Billing). Amount in minor units and an ISO 4217 code.
 * Same rules as the Go kernel package; the same test cases run in both CIs.
 */
final readonly class Money
{
    public const string VERSION = '1.2.0';

    public function __construct(
        public int $minor,
        public string $currency,
    ) {
        if (preg_match('/^[A-Z]{3}$/', $currency) !== 1) {
            throw new InvalidArgumentException("Invalid currency {$currency}");
        }
    }

    public function add(self $other): self
    {
        if ($other->currency !== $this->currency) {
            throw new InvalidArgumentException('Currency mismatch');
        }

        return new self($this->minor + $other->minor, $this->currency);
    }

    public function times(int $quantity): self
    {
        return new self($this->minor * $quantity, $this->currency);
    }

    /** basisPoints/10000 of the amount, rounded half away from zero: THE shared rule. */
    public function percentOf(int $basisPoints): self
    {
        $n = $this->minor * $basisPoints;
        $q = intdiv($n, 10000);
        $r = $n % 10000;
        if ($r >= 5000) {
            $q++;
        } elseif ($r <= -5000) {
            $q--;
        }

        return new self($q, $this->currency);
    }
}

contract test روی لبه ​

تست PHP همان schema، مثال و فایل‌های مصرف‌کننده را می‌خواند که تست Go می‌خواند: یک published language، دو پیاده‌سازی، یک مجموعه قول.

php
<?php

declare(strict_types=1);

use App\Modules\Sales\Contracts\OrderPlacedV1;
use App\Modules\Sales\Ohs\OrderPlacedPublisher;

// The same schema, example and consumer expectations the Go side tests against.
const CONTRACTS = __DIR__.'/../../../contracts/sales/';

function contract(string $file): array
{
    return json_decode(file_get_contents(CONTRACTS.$file), true, flags: JSON_THROW_ON_ERROR);
}

function publishedSample(): array
{
    $at = new DateTimeImmutable('2026-11-25T10:15:00Z');

    return OrderPlacedPublisher::toV1([
        'id' => 'ord_1042', 'customer_id' => 'cus_77', 'currency' => 'EUR', 'placed_at' => $at,
        'lines' => [
            ['sku' => 'MUG-RED', 'quantity' => 2, 'unit_price_minor' => 1250],
            ['sku' => 'TEA-ASSAM', 'quantity' => 1, 'unit_price_minor' => 2000],
        ],
        'margin_minor' => 1900, 'sales_rep' => 'rep-12',
        'deliver_from' => $at->modify('+46 hours'), 'deliver_to' => $at->modify('+50 hours'),
    ], 'evt_test')->toArray();
}

it('publishes every required field of the schema', function () {
    $schema = contract('order_placed.v1.schema.json');

    expect(array_keys(publishedSample()))->toContain(...$schema['required']);
    expect(publishedSample()['event_type'])->toBe(OrderPlacedV1::TYPE);
});

it('never leaks internal Sales fields', function () {
    expect(publishedSample())
        ->not->toHaveKey('margin_minor')
        ->not->toHaveKey('sales_rep');
});

it('satisfies every consumer expectation (customer-supplier tests in the supplier CI)', function (string $file) {
    $expects = contract('consumers/'.$file);
    $event = publishedSample();

    foreach ($expects['paths'] as $path) {
        $value = $event;
        foreach (explode('.', $path) as $key) {
            if (str_ends_with($key, '[]')) {
                $value = $value[substr($key, 0, -2)][0] ?? null;
            } else {
                $value = $value[$key] ?? null;
            }
        }
        expect($value)->not->toBeNull("{$expects['consumer']} needs {$path}");
    }
})->with(['fulfilment.expects.json', 'billing.expects.json']);

it('round-trips the published example', function () {
    $example = contract('order_placed.v1.example.json');

    expect(OrderPlacedV1::fromArray($example)->toArray())->toEqual($example);
});

نگاه Laravel ​

  • bindingهای service container همان نقشه در کد هستند. ContextMapServiceProvider تنها جایی است که یک پورت Sales به یک پیاده‌سازی می‌رسد؛ عوض کردن ACLِ ERP با کلاینت کانتکست Customer در آینده یک خط است.
  • HTTP client: Http::fake همراه Http::response adapter را بدون ERP تست می‌کند؛ retry(..., throw: false) با callbackِ when فقط خطای شبکه و 5xx را تکرار می‌کند.
  • صف‌ها: مصرف‌کنندهٔ conformist یک job صف‌شده است (ShouldQueue + Queueable)؛ insertOrIgnore روی event_id یکتا، تحویل دوباره را بی‌خطر می‌کند (Idempotent Consumer). با afterCommit dispatch کنید یا از outbox منتشر کنید.
  • path repositoryهای Composer اجازه می‌دهند shared kernel در monorepo به‌صورت packages/shared-kernel با نسخهٔ خودش زندگی کند؛ هر دو ماژول shop/shared-kernel: ^1.2 را require می‌کنند.
  • تست معماری (arch() در Pest) می‌تواند استفادهٔ App\Modules\Sales\Domain از App\Modules\Sales\Acl را ممنوع کند و وابستگی هر ماژولی جز Billing به namespaceِ Billing را هم.

حل مسئله‌های کلاسیک ​

ERP قدیمی به مدل core نشت می‌کند ​

راه‌حلچطورمزیتهزینه / محدودیت
ACL درون سرویس coreپورت + facade + adapter + translator (بالا)core تمیز می‌ماند؛ یک جا برای تغییرکد برای نگهداری؛ تأخیر فراخوانی سیستم قدیمی
ACL به‌عنوان سرویس جداdeployable جدا که برای چند مصرف‌کننده ترجمه می‌کندمشترک بین چند نفرسرویس اضافه، نقطهٔ شکست واحد (Microsoft)
ACL رویدادمحورCDC روی جدول‌های ERP، انتشار event تمیزجدا از uptimeِ ERPراه‌اندازی CDC (Change Data Capture)
همرنگ شدنرکوردهای ERP را مستقیم به کار ببرصفر کد ترجمهمدل ERP مدل core شما می‌شود: برای core دوری کنید

مدل یک ارائه‌دهندهٔ SaaS (پرداخت، مالیات، CRM) ​

ارائه‌دهنده را بالادستی ببینید که نمی‌توانید رویش اثر بگذارید. جایی که مدلش همان استاندارد دامنه است همرنگ شوید (مقدارهای وضعیت یک payment intent)، و جایی که قواعد core شما زندگی می‌کند ACL بگذارید (aggregateِ Payment شما نباید شیء charge ارائه‌دهنده باشد). شناسه‌های ارائه‌دهنده را به‌عنوان ویژگی نگه دارید، نه هویت، تا بشود ارائه‌دهندهٔ دوم را اضافه کرد.

راه‌حلچطورمزیتهزینه / محدودیت
ACL نازکاشیای ارائه‌دهنده را به Payment خودتان و webhookها را به eventهای خودتان نگاشت کنیدعوض کردن ارائه‌دهنده محلی استکد نگاشت
همرنگ در لبه، ACL در coreنوع‌های ارائه‌دهنده فقط درون ماژول یکپارچه‌سازیکد کمانضباط: SDKِ ارائه‌دهنده هرگز در دامنه import نشود

تغییر شکننده در یک published language ​

راه‌حلچطورمزیتهزینه / محدودیت
نشکنفقط فیلد اختیاری اضافه کنبی‌نیاز از هماهنگیschema فیلد انباشته می‌کند
انتشار موازی نسخه‌هاv1 و v2 را منتشر کن؛ v1 را با تاریخ منسوخ کنمصرف‌کنندگان با زمان‌بندی خودشان جابه‌جا می‌شوندمدتی دو خروجی
مترجم یک‌بارهنیاز خاص یک مصرف‌کننده بیرون از OHS حل می‌شود (Evans)OHS ساده می‌ماندکسی باید صاحب مترجم باشد
contract test مصرف‌کننده در CIbuild را پیش از انتشار بشکنزود پیدا می‌شودمصرف‌کنندگان باید انتظارشان را بنویسند

shared kernel مدام بزرگ‌تر می‌شود ​

راه‌حلچطورمزیتهزینه / محدودیت
سقف اندازهٔ نوشته‌شده«Money، Currency، گرد کردن: و دیگر هیچ» در doc پکیجقاعدهٔ روشناجرایش در code review لازم است
CODEOWNERS دوتیمیهر تغییر هر دو را می‌خواهدهم‌مالکی واقعیتغییر کندتر (عمداً)
تقسیمش کنکد یک‌طرفه را به کانتکست خودش برگردانkernel کوچک می‌شودکمی تکرار
جایگزینی با PLschemaی مشترک به جای کد مشترکبی‌گره بودن انتشارهاهر طرف کد خودش را می‌نویسد

پایین‌دستِ conformist آسیب می‌بیند ​

وقتی تغییرات بالادست مدام شما را می‌شکند، در درزی که نوع‌های بالادست را در آن محصور کرده بودید یک ACL بگذارید (دلیل محصور کردن همین است). اگر بالادست گوش شنوا دارد، وضعیت Customer-Supplier با contract test بخواهید.

دیتابیس مشترک بین کانتکست‌ها ​

قرمزش کنید، یک view به‌عنوان published language موقت منتشر کنید (ببینید سازوکار)، سپس خواننده‌ها را به event ببرید. جزئیات مهاجرت: مالکیت داده در Microservices و Microservices Data Patterns.

انتخاب ​

موقعیتالگوتکنیک تکمیلیدلیل
دو تیم باید یک قابلیت را با هم، یک بار، منتشر کنندPartnership (سقف‌دار)مجموعه تست مشترک، تاریخ پایان روی نقشهشکست هر کدام شکست هر دوست
یک مفهوم کوچک باید در دو طرف یکسان باشدShared Kernelسیاست نسخه‌گذاری، بازبینی دوتیمیواگرایی باگ است
پایین‌دست چیزهایی لازم دارد و بالادست گوش می‌دهدCustomer-Suppliercontract test مصرف‌کننده در CI بالادستبرنامه‌ریزی، نه امید
بالادست گوش نمی‌دهد، مدلش خوب استConformistنوع‌های بالادست را در یک پکیج محصور کنارزان‌ترین یکپارچه‌سازی
بالادست گوش نمی‌دهد، مدلش بد استAnticorruption Layerپورت + facade + adapter + translatorاز مدل خودت محافظت کن
پایین‌دست core domain توست، بالادست هر چیز دیگرAnticorruption Layer (یا CF به یک PL تمیز)معنا را ترجمه کن، نه فقط نام رامدل core دارایی است
مصرف‌کنندگان زیاد برای یک کانتکستOpen Host Service + Published LanguageOpenAPI / AsyncAPI / Protobuf، نسخه‌گذارییک پروتکل بهتر از N مترجم
تبادل بین شرکت‌ها یا صنعتPublished Language (استاندارد)iCalendar، vCard، OIDC، ISO 20022مال هیچ‌کس نیست؛ همه می‌فهمندش
ارزش یکپارچه‌سازی کم استSeparate Waysروی نقشه بنویسیکپارچه‌سازی همیشه گران است
سیستم قدیمی بی‌ساختار درونیBig Ball of Mud + ACLstrangler figآشفتگی را مدل نکن
زیردامنهٔ generic که به‌صورت محصول خریده شدهConformist به OHS/PL آنACL فقط جایی که به قواعد core می‌رسدمحصول را عوض نمی‌کنید

در معماری: از یک پردازه تا سیستم توزیع‌شده ​

نقشهٔ کانتکست به شیوهٔ استقرار وابسته نیست. همین الگوها در یک پردازه و در صد سرویس ظاهر می‌شوند؛ چیزی که عوض می‌شود هزینهٔ هر لبه است.

Monolith (یکپارچه): یک پردازه، یک دیتابیس ​

در یک monolith ساده کانتکست‌ها اغلب ضمنی‌اند، و نقشه دقیقاً به همین دلیل کمک می‌کند: نشان می‌دهد «ماژول سفارش» در چهار قابلیت با چهار معنا به کار می‌رود. ساده‌ترین حرکت درست این است که کانتکست‌ها را نام‌گذاری کنید، برای هر کانتکست یک پکیج یا namespace بسازید، و جایی که دو مدل به هم می‌رسند ترجمه بگذارید. مثال: monolithِ فروشگاه Orderی دارد که checkout و صفحه‌های انبار هر دو استفاده‌اش می‌کنند؛ نقشه دو کانتکست (Sales، Fulfilment) و یک ترجمهٔ غایب نشان می‌دهد، پس تیم Order را به sales.Order و fulfilment.PickList تقسیم می‌کند، با یک تابع نگاشت بینشان.

Modular monolith: OHS درون‌پردازه‌ای، و هنوز ترجمه ​

در یک modular monolith interface عمومی هر ماژول همان Open Host Service آن است و DTOهای روی آن Published Language آن. ترجمه هنوز لازم است: ماژولی که entityهای داخلی ماژول دیگر را import می‌کند در بهترین حالت conformist است و در بدترین حالت shared kernelی که هیچ‌کس رویش توافق نکرده.

go
// Inside one binary: the Sales module's public API is its OHS.
package salesapi // the only Sales package other modules may import

type OrderSummary struct { // published language, in-process
	OrderID    string
	TotalMinor int64
	Currency   string
}

type API interface {
	OrderSummary(ctx context.Context, id string) (OrderSummary, error)
}

نقشه را با تست معماری اجرا کنید (قواعد import در Go، arch() در Pest)، به هر ماژول schema و role دیتابیس خودش را بدهید، و برای لبه‌هایی که بعداً ناهم‌زمان می‌شوند از event درون‌پردازه‌ای (eventهای Laravel، یک event bus در Go) استفاده کنید. مثال: Billing امروز درون‌پردازه به OrderPlaced گوش می‌دهد؛ چون از همین حالا شکل منتشرشده را مصرف می‌کند، جدا کردن Billing در آینده فقط حمل‌ونقل را عوض می‌کند، نه مدل را.

Microservices (میکروسرویس): هر لبه شبکه و قرارداد دارد ​

بین سرویس‌ها نام الگوها به مصنوعات مشخص تبدیل می‌شوند: OHS + PL یعنی یک سند OpenAPI یا AsyncAPI در مخزن؛ Customer-Supplier یعنی contract test مصرف‌کننده در pipelineِ تأمین‌کننده؛ ACL یعنی یک پکیج یا سرویس با monitoring خودش؛ Shared Kernel یعنی کتابخانهٔ نسخه‌دار با گره انتشار (کوچکش نگه دارید). جریان نمونه:

text
     Sales service           broker                  Fulfilment / Billing
1    tx: insert order + outbox row
2    relay -> publish sales.order.placed.v1  -->   Fulfilment consumes (C/S, uses delivery_window)
3                                            -->   Billing consumes (CF), insertOrIgnore by event_id
4    Sales CI: contract_test reads consumers/*.expects.json before every release
5    ERP ACL in Sales: sync HTTP with 2 s timeout; 5xx -> retry; still down -> order waits

برای timeout و retry به Service Communication و وقتی لبه یک فرایند چندمرحله‌ای را حمل می‌کند به Saga سر بزنید.

دادهٔ توزیع‌شده: replica، cache و چندمنطقه‌ای ​

لبه‌ای که داده جابه‌جا می‌کند کپی می‌سازد. مصرف‌کنندهٔ conformist که دادهٔ بالادست را ذخیره می‌کند یک replica از مدل بالادست با تأخیر دارد؛ ACLی که رکوردهای ترجمه‌شده را cache می‌کند replicaی ترجمه‌شده‌ای دارد که از دو راه کهنه می‌شود (بالادست عوض شد، یا قواعد ترجمه عوض شد). تازگی را روی نقشه بنویسید («Billing: کپی سفارش‌ها، تأخیر زیر ۵ ثانیه»)، قواعد ترجمه را نسخه‌گذاری کنید تا بشود دوباره ترجمه کرد، و برای لبه‌های بین‌منطقه‌ای event را بر polling ترجیح دهید. در چیدمان چندمنطقه‌ای یک OHS اغلب در هر منطقه تکثیر می‌شود ولی published language جهانی می‌ماند؛ schema registry (یا فایل‌های schema در مخزن) تنها منبع حقیقت است.

مسیر مقیاس: ۱×، ۱۰×، ۱۰۰× ​

مقیاسنقشهتغییر معمول
1× (یک تیم)یک نقاشی روی وایت‌برد؛ کانتکست‌ها به‌شکل پکیجنام‌گذاری کانتکست‌ها؛ یک ACL برای سیستم قدیمی
10× (۵ تا ۱۰ تیم)فایل CML در مخزن که برای هر یکپارچه‌سازی مرور می‌شودcontract test برای customer-supplier؛ اولین OHS با PL؛ shared kernel با سیاست
100× (ده‌ها تیم)چند نقشه برای پرسش‌های مختلف؛ نقشهٔ تیم جدا از نقشهٔ سیستمOHS برای کانتکست‌های پرمصرف؛ schema registry؛ قالب‌های ACL که پلتفرم می‌دهد؛ SLA برای deprecation

آزمایشگاه: نقشه را بکش، پیاده کن، بشکن ​

همه‌چیز آفلاین و فقط با Go نصب‌شده اجرا می‌شود.

آماده‌سازی.

bash
cd docs/snippets/ddd/context-maps-integration-patterns/go
go vet ./...
go test ./...
# ok  academy/context-maps-integration-patterns/billing
# ok  academy/context-maps-integration-patterns/contracts/orderplaced
# ok  academy/context-maps-integration-patterns/kernel
# ok  academy/context-maps-integration-patterns/sales/acl/erp

قدم ۱: نقشهٔ امروز را بکشید. برای سیستمی که می‌شناسید کانتکست‌ها را فهرست کنید و هر لبه را با U/D و برچسب الگو بکشید. انتظار: دست‌کم یک لبه که نمی‌توانید طبقه‌بندی‌اش کنید. آن لبه تصمیمی است که هیچ‌کس نگرفته.

قدم ۲: قرارداد customer-supplier را بشکنید. در go/contracts/orderplaced/v1.go تگ json:"quantity" را به json:"qty" تغییر دهید و go test ./contracts/... را اجرا کنید. انتظار:

text
--- FAIL: TestPublishedLanguageSchema
    publisher violates the published language: [$.lines[].quantity: required ...]
--- FAIL: TestConsumerExpectations
    billing needs "lines[].quantity", publisher does not provide it
    fulfilment needs "lines[].quantity", publisher does not provide it

دقت کنید که go test ./billing/... هنوز سبز است: تست conformist فایل مثال را می‌خواند، نه خروجی publisher را. اهمیت contract test در سمت تأمین‌کننده دقیقاً همین است. برگردانید.

قدم ۳: یک فیلد داخلی را نشت دهید. در contracts/orderplaced/v1.go فیلد MarginMinor int64 `json:"margin_minor"` را به V1 اضافه کنید و در ToV1 (sales/ohs/publisher.go) آن را از o.MarginMinor پر کنید. انتظار: TestGoBindingMatchesSchema با Go field MarginMinor ("margin_minor") not in schema و TestNoInternalFieldsLeak با internal field "margin_minor" leaked شکست می‌خورند. برگردانید.

قدم ۴: یک عجیبهٔ تازه به ACL اضافه کنید. ERP برای بعضی مشتری‌ها KLIMK را به‌صورت "1500" بدون اعشار می‌فرستد. یک case به translator_test.go اضافه کنید که 150000 انتظار دارد، اجرا کنید و اگر لازم بود parseAmount را درست کنید. انتظار: فقط translator عوض می‌شود؛ کد Sales دست نمی‌خورد.

قدم ۵: shared kernel را عوض کنید. گرد کردن در kernel.PercentOf را به round half to even تغییر دهید. انتظار: TestRoundingRuleIsShared روی {1050, 500, 53} شکست می‌خورد. بحث: طبق سیاست این یک نسخهٔ MAJOR است؛ هر دو تیم باید تأیید کنند.

قدم ۶: نقشه را به CML بنویسید. contracts/contextmap.cml را در IDE آنلاین Context Mapper یا افزونهٔ VS Code باز کنید، Fulfilment [C,ACL]<-[S,OHS] Sales را اضافه کنید و پیام validator را بخوانید. انتظار، طبق صفحهٔ Language Semantics: برای OHS روی لبهٔ customer-supplier خطا (قاعدهٔ ۶) و برای ACL روی آن هشدار (قاعدهٔ ۷، که خود صفحه آن را قاعدهٔ نرم می‌نامد).

بدفهمی‌های رایج ​

باورواقعیت
Context map همان معماری هدف استواقعیت امروز است؛ هدف یک نقشهٔ TO_BE جداست
بالادست یعنی «داده را می‌فرستد»بالادست یعنی «تغییراتش روی طرف دیگر اثر می‌گذارد»
Conformist همیشه بد استهمرنگ شدن با یک PL خوب یا یک استاندارد اغلب بهترین است
ACL فقط یک کلاس mapper استfacade + adapter + translator؛ خطا، شناسه و معنا را هم ترجمه می‌کند
shared kernel همان کتابخانهٔ common استکوچک، صریح، هم‌مالک و نسخه‌دار است؛ کتابخانهٔ common بزرگ implementation coupling است
Customer-Supplier به مشتری حق وتو می‌دهدصدا در برنامه‌ریزی و تست در CI می‌دهد؛ Evans دربارهٔ حق وتو هشدار می‌دهد
OHS یعنی RESTیعنی یک پروتکل یکپارچه‌سازی باز؛ eventها هم حساب‌اند
entityهای ما می‌توانند published language باشندمدل داخلی وقتی برای تبادل به کار رود "essentially becomes frozen"
eventها همهٔ couplingها را برمی‌دارندفقط temporal coupling را؛ schema هنوز قرارداد است
Separate Ways تنبلی استتصمیمی آگاهانه است که یکپارچه‌سازی بیش از سودش هزینه دارد
باید سیستم قدیمی را پیش از یکپارچه‌سازی مدل کرددور آشفتگی مرز بکشید (Big Ball of Mud) و جلویش ACL بگذارید
هر جفت کانتکست یک رابطه داردیک جفت می‌تواند چند لبه داشته باشد (مثلاً event با OHS/PL و یک shared kernel)

چکیده (Cheat sheet) ​

موضوعبه خاطر بسپارید
Context mapکانتکست‌های امروز، لبه‌ها، جهت، الگو، سازوکار؛ نقشه‌های کوچک برای هر پرسش
بالادست/پایین‌دستجریان نفوذ؛ «اگر آن‌ها عوض شوند ما می‌شکنیم؟»
Partnershipتیم‌های وابستهٔ متقابل؛ برنامه‌ریزی مشترک؛ سقف زمانی بگذارید
Shared Kernelکوچک، هم‌مالک، نسخه‌دار، تست‌شده در هر دو CI
Customer-Supplierاولویت پایین‌دست در برنامه‌ریزی بالادست؛ تست مصرف‌کننده در CI بالادست؛ بی حق وتو
Conformistمدل بالادست را بپذیر؛ برای مدل خوب و کانتکست غیرcore خوب است؛ نوع‌ها را محصور کن
Anticorruption Layerfacade + adapter + translator، مال پایین‌دست؛ قاعدهٔ کسب‌وکار درونش نه
Open Host Serviceیک پروتکل برای همه؛ حالت خاص در مترجم یک‌باره
Published Languageقالب تبادل مستند (OpenAPI، AsyncAPI، JSON Schema، Protobuf، استانداردها)
Separate Waysیکپارچه‌سازی نکن؛ روی نقشه بنویس
Big Ball of Mudعلامت بزن، دیوار بکش، strangler fig
نشانه‌گذاریU/D، S/C؛ OHS و PL در بالادست؛ CF و ACL در پایین‌دست؛ SK و P متقارن
دیتابیس مشترکلبهٔ قرمز؛ اول view منتشر کن، بعد event
Modular monolithAPI ماژول = OHS؛ DTOها = PL؛ ترجمه هنوز لازم است
تکاملCF به ACL، ACL به CF روی PL تمیز، C/S به OHS، SK به separate ways

خودآزمایی: پرسش و پاسخ ​

نمایش:
  • حیاتی تقریباً در هر مصاحبه پرسیده می‌شود
  • مهم پرتکرار؛ در سطح senior انتظار می‌رود
  • تکمیلی عمق بیشتر؛ تمایز ایجاد می‌کند

۱ — نقشهٔ کانتکست چه چیزی را نشان می‌دهد که نمودار معماری نشان نمی‌دهد؟ حیاتی ​

پاسخ

پاسخ: مدل‌ها و نفوذ: چه bounded contextهایی هست (با مدل‌های ضمنی سیستم‌های قدیمی)، روی هر لبه چه کسی بالادست است، کدام الگو بر لبه حاکم است و ترجمه کجا انجام می‌شود. ببینید نقشهٔ کانتکست.

۲ — Billing یک API از Fulfilment را صدا می‌زند تا تاریخ تحویل بگیرد. بالادست کیست؟ حیاتی ​

پاسخ

پاسخ: Fulfilment: تغییر API آن Billing را می‌شکند، نه برعکس. بالادست دربارهٔ نفوذ است، نه این‌که چه کسی فراخوانی را شروع می‌کند. ببینید بالادست، پایین‌دست و قدرت.

۳ — چرا Evans دربارهٔ دادن حق وتو به مشتری در Customer-Supplier هشدار می‌دهد؟ تکمیلی ​

پاسخ

پاسخ: "the freewheeling development of the upstream team will stop if the downstream team has veto power over changes." به جایش مشتری نفوذ در برنامه‌ریزی و تست پذیرش خودکار در CI بالادست می‌گیرد. ببینید Customer-Supplier.

۴ — سه چیز که می‌تواند در shared kernel باشد و سه چیز که نباید را نام ببرید. مهم ​

پاسخ

پاسخ: می‌تواند: Money/Currency، قاعدهٔ گرد کردنی که هر دو باید اجرا کنند، قالب شناسه‌ها. نباید: entityهایی مثل Order یا Customer، مدل‌های persistence، جعبه‌ابزار متفرقه. ببینید Shared Kernel.

۵ — Conformist کِی انتخاب درستی است؟ حیاتی ​

پاسخ

پاسخ: وقتی بالادست خودش را با شما تطبیق نمی‌دهد، مدلش خوب (یا استاندارد) است، کانتکست شما core نیست و داده را همان‌طور استفاده می‌کنید. نوع‌های بالادست را در یک پکیج محصور کنید تا بعداً بشود ACL گذاشت. ببینید Conformist.

۶ — سه بخش ACL کدام‌اند و هر کدام چه می‌کند؟ مهم ​

پاسخ

پاسخ: Facade: پورتی را که مال پایین‌دست است پیاده می‌کند. Adapter: پروتکل بالادست را حرف می‌زند (URL، timeout، کد وضعیت). Translator: رکوردها، شناسه‌ها، معنا و خطاها را به مدل پایین‌دست نگاشت می‌کند. ببینید Anticorruption Layer.

۷ — چرا مدل داخلی دامنه نباید published language باشد؟ مهم ​

پاسخ

پاسخ: Evans: مدل‌های داخلی ممکن است پیچیده، بدساختار و بی‌مستند باشند، و "If one is used as a data interchange language, it essentially becomes frozen and cannot respond to new development needs." ببینید Published Language.

۸ — یک مصرف‌کنندهٔ OHS به جای JSON، XML می‌خواهد. توصیهٔ Evans چیست؟ تکمیلی ​

پاسخ

پاسخ: پروتکل مشترک را ساده نگه دارید: "use a one-off translator to augment the protocol for that special case". ببینید Open Host Service.

۹ — Context Mapper کدام ترکیب‌ها را رد می‌کند و چرا؟ تکمیلی ​

پاسخ

پاسخ: ACL و CF با هم (یا محافظت یا همرنگی، نه هر دو)، OHS/PL/ACL/CF روی رابطهٔ متقارن (SK، P)، CF روی لبهٔ customer-supplier (مشتری نفوذ دارد)، OHS روی customer-supplier (یکی-برای-همه در برابر سفارشی). ACL روی C/S فقط هشدار است. ببینید نشانه‌گذاری.

۱۰ — لبهٔ دیتابیس مشترک را چطور نشان می‌دهید و بعد حذف می‌کنید؟ مهم ​

پاسخ

پاسخ: روی نقشه قرمزش کنید؛ با grantها و pg_stat_activity پیدایش کنید؛ دسترسی جدول را با یک view منتشرشده به‌عنوان PL موقت جایگزین کنید؛ خواننده‌ها را به event ببرید. ببینید پیدا کردن لبه‌های پنهان.

۱۱ — در modular monolith چه چیزی نقش OHS و PL را بازی می‌کند؟ مهم ​

پاسخ

پاسخ: interface عمومی ماژول OHS است و DTOهای روی آن PL. ماژول‌های دیگر هنوز به مدل خودشان ترجمه می‌کنند. ببینید Modular monolith.

۱۲ — قدم بعدی معمول برای لبهٔ Conformistی که آسیب می‌زند چیست؟ مهم ​

پاسخ

پاسخ: در درزی که نوع‌های بالادست محصور بودند یک ACL بگذارید؛ اگر بالادست مایل است، وضعیت Customer-Supplier با contract test بخواهید. ببینید تکامل نقشه.

واژه‌نامه (Glossary) ​

واژهمعنا
نقشهٔ کانتکست (Context map)توصیف bounded contextها و رابطه‌های بینشان، همان‌طور که امروز هستند
Bounded contextمرزی که درونش یک مدل و یک زبان معتبر است (Bounded Context)
بالادست (Upstream)طرفی که کارهایش روی موفقیت طرف دیگر اثر می‌گذارد
پایین‌دست (Downstream)طرفی که از کارهای طرف دیگر اثر می‌پذیرد
وابستگی متقابل (Mutually dependent)دو کانتکست که هر دو باید تحویل شوند تا هیچ‌کدام موفق حساب شود
آزاد (Free)کانتکستی که موفقیتش به کار کانتکست‌های دیگر وابسته نیست
شراکت (Partnership، P)تیم‌های وابستهٔ متقابل با برنامه‌ریزی هماهنگ و یکپارچه‌سازی مشترک
هستهٔ مشترک (Shared Kernel، SK)زیرمجموعهٔ کوچک، صریحاً مرزبندی‌شده و هم‌مالکی از مدل و کد
مشتری-تأمین‌کننده (Customer-Supplier، C/S)بالادست/پایین‌دستی که اولویت پایین‌دست وارد برنامه‌ریزی بالادست می‌شود
همرنگ (Conformist، CF)پایین‌دست مدل بالادست را بی‌ترجمه می‌پذیرد
لایهٔ ضدفساد (Anticorruption Layer، ACL)لایه‌ای مال پایین‌دست که مدل بالادست را به مدل خودش ترجمه می‌کند
نما (Facade)بخشی از ACL که پورت پایین‌دست را عرضه می‌کند
وفق‌دهنده (Adapter)بخشی از ACL که پروتکل بالادست را حرف می‌زند
مترجم (Translator)بخشی از ACL که داده، شناسه، معنا و خطا را نگاشت می‌کند
سرویس میزبان باز (Open Host Service، OHS)یک پروتکل باز که دسترسی به کانتکست را برای همهٔ یکپارچه‌کنندگان فراهم می‌کند
زبان منتشرشده (Published Language، PL)زبان تبادل مشترک و خوب‌مستندشده، اغلب همراه OHS
راه‌های جدا (Separate Ways)تصمیم آگاهانه برای یکپارچه نکردن دو کانتکست
گلولهٔ بزرگ گِل (Big Ball of Mud، BBoM)سیستمی با مدل‌های درهم و بی‌مرز ثابت؛ روی نقشه دیوارکشی می‌شود
U/D، S/Cعلامت بالادست/پایین‌دست و تأمین‌کننده/مشتری روی خط‌های نقشه
Context Mapper / CMLDSL و ابزاری برای نقشهٔ کانتکست به‌صورت فایل متنی با اعتبارسنجی معنایی
AS_IS / TO_BEوضعیت‌های Context Mapper برای نقشهٔ فعلی و مطلوب
downstreamRightsویژگی CML: INFLUENCER، OPINION_LEADER، VETO_RIGHT، DECISION_MAKER، MONOPOLIST
OpenAPIتوصیف interface مستقل از زبان برای APIهای HTTP
AsyncAPIتوصیف ماشین‌خوان و مستقل از پروتکل برای APIهای پیام‌محور
JSON Schemaواژگانی برای توصیف و اعتبارسنجی سندهای JSON
Protocol Buffersزبان schema باینری؛ شماره‌های فیلد حذف‌شده به reserved می‌روند
قرارداد مصرف‌کننده‌محور (Consumer-driven contract)انتظاراتی که پایین‌دست می‌نویسد و در CI بالادست اجرا می‌شود (مثلاً Pact)
Pactابزار contract testing کدمحور برای یکپارچه‌سازی HTTP و پیام
Strangler figجایگزینی تدریجی سیستم قدیمی حول یک درز مثل ACL
Outboxنوشتن event در همان تراکنش وضعیت، که بعداً یک relay منتشرش می‌کند
دیتابیس مشترک (Shared database، بو)دو کانتکست که جدول‌های یکسان را می‌خوانند یا می‌نویسند: لبه‌ای نکشیده و بی‌نسخه
iCalendar، vCardpublished languageهای صنعتی که DDD-crew مثال می‌زند
رابطه‌های تیمی (Team relationships)سه رابطهٔ DDD-crew: وابستگی متقابل، بالادست/پایین‌دست، آزاد
OpenID Connect (OIDC)پروتکل هویت که ارائه‌دهندگان هویت به‌عنوان OHS/PLِ generic به کار می‌برند

منابع (References) ​

ساخته‌شده توسط Morteza Negahi