Kruchten's 4+1 View Model: Logical, Process, Development, Physical & Scenarios
"As a remedy, we propose to organize the description of a software architecture using several concurrent views, each one addressing one specific set of concerns." — Philippe Kruchten، Architectural Blueprints—The "4+1" View Model of Software Architecture، IEEE Software 12(6)، نوامبر ۱۹۹۵
خلاصه (Summary): یک نمودار نمیتواند همزمان بگوید چه چیزی اجرا میشود، چه چیزی کامپایل میشود، چه چیزی کجا مستقر است و کسبوکار از هر جزء چه منظوری دارد؛ مدل 4+1 توصیف معماری را به چهار نما (View) برای چهار گروه از آدمها میشکند (منطقی، پردازه، توسعه، فیزیکی) و آنها را با چند سناریو (Scenario) به هم میدوزد؛ سناریوهایی که هم طراحی را جلو میبرند و هم درستیاش را ثابت میکنند. تمرکز (Focus): پنج نما با عمق کامل (هدف، ذینفعان، عنصرها، اتصالدهندهها، نمادگذاری، پرسشها، نمودارها)، اینکه سناریوها چطور نماها را به هم وصل و اعتبارسنجی میکنند، قاعدههای تناظر میان نماها، واژگان بعدی (viewpoint و view در ISO/IEC/IEEE 42010، روش Views and Beyond مؤسسهٔ SEI، C4، arc42، Rozanski و Woods)، نگاشت به انواع نمودار UML، اینکه کدام نما در کدام مقیاس مهم است، یک مثال کامل از سکوی سفارش آنلاین با کد Go و Laravel، همگام نگه داشتن نماها، ضدالگوها و یک چکلیست. هدف یادگیری (Learning goal): برای هر سیستمی، کمترین مجموعهٔ نماهایی را که ذینفعانش لازم دارند بسازید، هر کدام را با عنصرها و اتصالدهندههای درست بکشید، سه تا پنج سناریو بنویسید که از همهٔ نماها عبور کنند، و build را طوری سیمکشی کنید که نمای توسعه و نمای فیزیکی بیصدا از کد فاصله نگیرند.
این صفحه صاحب بخش مستندسازی معماری است: سیستم را چطور توصیف کنیم که هر مخاطب پاسخ خودش را پیدا کند. فرض میکند تعریفهای What Software Architecture Is و تفکیک سطحها در Architecture vs Design را خواندهاید. نمادگذاری خود نمودارها را دوباره درس نمیدهد (آن کار UML in Practice است)، ثبت یک تصمیم را هم نه (آن کار Architecture Decisions و ADR است)، و استخراج محرکهای معماری را هم نه (آن کار From Requirements to Architecture است). سبکهایی که نماها در نهایت نشان میدهند در Layered Monolith، Modular Monolith و Microservices آموزش داده میشوند.
نقشهٔ صفحه
| دنبال چه هستید | بروید به |
|---|---|
| پنج نما در چند جدول | همهچیز در یک دقیقه |
| چرا یک نمودار هرگز کافی نیست | چرا وجود دارد |
| Perry و Wolf، Kruchten 1995، RUP، IEEE 1471، ISO 42010، V&B، C4 | از کجا آمده |
| منطقی، پردازه، توسعه، فیزیکی، سناریوها، هر کدام یک بلوک | فهرست مفهومها |
| عنصرهای یک نما چطور به نمای دیگر نگاشت میشوند (inside-out و outside-in) | تناظر میان نماها |
| stakeholder، concern، viewpoint، view، model در ISO 42010 | Viewpoint و view |
| module، component-and-connector، allocation | Views and Beyond |
| سطحهای C4، بخشهای arc42، viewpointهای Rozanski و Woods | C4، arc42، Rozanski و Woods |
| 4+1 در برابر انواع نمودار UML و سامانههای دیگر | جدول نگاشت |
| ساختار Software Architecture Document، انتخاب نماها، diagrams as code | سازوکار |
| یک سکوی سفارش آنلاین که در هر پنج نما مستند شده | مثال کامل |
| کد Go و Laravel که به نماها گره خورده | Go، Laravel |
| نمودار غولآسا، نمایی که کسی نمیخواند، نمای کهنه | حل مسئلههای کلاسیک |
| کدام نماها برای کدام سیستم | انتخاب |
| از monolith تا سیستم توزیعشده | در معماری |
| تمرین عملی | آزمایشگاه |
| پیش از انتشار چه چیزی را بررسی کنیم | چکلیست مستندسازی |
| باورهای غلط، چکیده، خودآزمایی، واژهها | بدفهمیها، چکیده، خودآزمایی، واژهنامه |
همهچیز در یک دقیقه
پنج نما. ذینفعان و دغدغهها در سطرهای نخست از جدول خلاصهٔ خود Kruchten (Table 1 مقاله) آمدهاند؛ سطرهای «امروز» برداشت ماست.
| منطقی (Logical) | پردازه (Process) | توسعه (Development) | فیزیکی (Physical) | سناریوها (+1) | |
|---|---|---|---|---|---|
| به زبان ساده | سیستم با زبان دامنه چه میکند | چه چیزی همزمان اجرا میشود و چطور حرف میزند | کد چطور سازماندهی و build میشود | کجا اجرا میشود | چند داستان که از هر چهار نما رد میشوند |
| Components (Kruchten) | Class | Task | Module، subsystem | Node | Step، scripts |
| Connectors (Kruchten) | Association، inheritance، containment | Rendez-vous، message، broadcast، RPC | Compilation dependency، بند "with"، "include" | Communication medium، LAN، WAN، bus | (اتصالدهندههای نمای پردازه) |
| Containers (Kruchten) | Class category | Process | Subsystem (library) | Physical subsystem | Web |
| Stakeholders (Kruchten) | End-user | System designer، integrator | Developer، manager | System designer | End-user، developer |
| Concerns (Kruchten) | Functionality | Performance، availability، S/W fault-tolerance، integrity | Organization، reuse، portability، line-of-product | Scalability، performance، availability | Understandability |
| UML امروز | Class، object، state machine | Sequence، activity، communication | Package، component | Deployment | Use case، sequence |
| C4 امروز | Context، component | Container، dynamic | Component، code | Deployment | Dynamic |
| پرسشی که پاسخ میدهد | «قاعده کجا زندگی میکند؟» | «چه چیزی منتظر چه چیزی است و چقدر؟» | «مالک کدام پوشه کیست، چه چیزی میتواند چه چیزی را import کند؟» | «اگر این node بمیرد چه چیزی میمیرد؟» | «آیا طراحی واقعاً برای این داستان کار میکند؟» |
یک سیستم، پنج پاسخ (مثال کامل در مثال کامل):
| نما | سکوی سفارش آنلاین در یک خط |
|---|---|
| منطقی | Ordering (aggregate به نام Order، سطرها، وضعیت)، Catalog، Inventory، Payments، Shipping |
| پردازه | orders-api ×3 (HTTP همگام)، outbox-relay ×1 (دورهای)، workerها (ناهمگام، با retry) |
| توسعه | یک ماژول Go یا یک اپ Laravel؛ برای هر پردازه یک cmd/، برای هر ماژول یک پوشه، platform در لایهٔ پایین |
| فیزیکی | Load balancer، Kubernetes روی دو zone، PostgreSQL اصلی + standby، سه node برای broker |
| سناریوها | S1 ثبت سفارش، S2 ناموجودی، S3 رد پرداخت، S4 کرش relay، S5 از دست رفتن zone |
واژگان پیرامون آن.
| واژه | منبع | یک خط |
|---|---|---|
| نما (View) | Kruchten، ISO 42010، V&B | بازنمایی سیستم از دید یک دسته دغدغه |
| دیدگاه (Viewpoint) | ISO 42010، Rozanski و Woods | قراردادها (نمادگذاری، قاعده، دغدغه) برای ساختن یک نوع نما |
| ذینفع / دغدغه (Stakeholder / concern) | ISO 42010 | چه کسی ذینفع است / ذینفعی او در چیست |
| مدل (Model؛ در ۲۰۲۲ view component) | ISO 42010 | یک نمودار یا متن درون یک نما |
| تناظر (Correspondence) | ISO 42010؛ در V&B «mapping between views» | پیوند ثبتشده میان عنصرهای نماهای مختلف |
| Module / C&C / allocation | SEI Views and Beyond | واحدهای کد / عنصرهای زمان اجرا / نگاشت به چیزهای غیرنرمافزاری |
| C4 | Simon Brown | نمودارهای Context، Container، Component، Code بهعلاوهٔ deployment و dynamic |
| arc42 | قالب arc42 | دوازده بخش؛ ۵ building block، ۶ runtime، ۷ deployment |
چرا وجود دارد
هر wiki را باز کنید «نمودار معماری» را پیدا میکنید: جعبه، فلش، استوانهٔ دیتابیس، آیکن ابر. Kruchten مقالهاش را دقیقاً با همین تصویر شروع میکند و میپرسد جعبهها چه هستند: "Are the boxes representing running programs? Or chunks of source code? Or physical computers? Or merely logical groupings of functionality? Are the arrows representing compilation dependencies? Or control flows? Or data flows? Usually it is a bit of everything." تصویری که همهٔ اینها را قاطی کند به هیچکدام پاسخ نمیدهد: توسعهدهنده نمیبیند کدام package اجازه دارد کدام را import کند، اپراتور نمیبیند کدام پردازه روی کدام node اجرا میشود، و صاحب محصول نمیبیند قاعدهٔ تخفیف کجا زندگی میکند.
| یک نمودار پربار | چند نما بهعلاوهٔ سناریوها |
|---|---|
| کشیدنش سریع، خواندنش کند | هر نما کوچک است و یک مخاطب دارد |
| فلشها یعنی «یک چیزی» | هر نما معنای جعبه و فلش را ثابت میکند |
| کسی نمیتواند آن را با کد مقایسه کند | نمای توسعه و فیزیکی را میشود تولید یا تست کرد |
| ریسک همروندی و استقرار را پنهان میکند | نمای پردازه و فیزیکی این پرسشها را به زور مطرح میکنند |
| بیصدا کهنه میشود | هر نما مالک و منبع حقیقت دارد |
| مناسب برای: یک اسلاید معرفی | مناسب برای: ساختن، اداره کردن و تغییر دادن یک سیستم واقعی |
تصویر شکل Figure 1 مقالهٔ Kruchten است: چهار نما دور سناریوها. خطچینها تناظرهاییاند که مقاله توصیف میکند (class به module، object به task، process به node)؛ پرههای توپر سناریوهاییاند که به هر نما دست میزنند.
تمثیلی که در این صفحه بارها برمیگردیم: نقشههای یک خانه. معمار ساختمان یک نقشه به بنّا نمیدهد. نقشهٔ پلان هست (اتاقها و کاربردشان: نمای منطقی)، نقشهٔ برق و لولهکشی (وقتی خانه در استفاده است چه چیزی کجا جریان دارد: نمای پردازه)، برنامهٔ اجرا با تیمها و فازها (چه کسی کدام بخش را به چه ترتیبی میسازد: نمای توسعه)، و نقشهٔ محوطه (خانه کجای زمین نشسته و چطور به خیابان، آب و برق وصل است: نمای فیزیکی). بعد خانواده یک روز معمولی را، «بیدار شدن، دوش، آشپزی، بیرون رفتن»، همزمان روی همهٔ نقشهها مرور میکند (سناریوها): اگر دوش در پلان هست ولی در نقشهٔ لولهکشی لوله ندارد، همین مرور پیدایش میکند. arc42 هم همین تصویر را به کار میبرد: نمای building block آن "is the floor plan".
سه بدفهمی رایج، از همین اول
- «4+1 یعنی برای هر سیستم باید پنج نمودار بکشم.» خود Kruchten: "Not all software architecture need the full “4+1” views." نمای فیزیکی وقتی یک پردازنده دارید و نمای پردازه وقتی یک پردازه دارید میتواند حذف شود. سناریوها تنها نماییاند که او "in all circumstances" نگه میدارد.
- «نمای منطقی همان class diagram کد است.» نمای منطقی انتزاعهای کلیدی دامنهٔ مسئله در سطحی است که از نظر معماری مهم است: برای یک سیستم بزرگ چند ده class که در دستهها گروهبندی شدهاند. class diagram سطح کد طراحی است، نه معماری.
- «4+1 چیزی مخصوص UML است.» مقالهٔ ۱۹۹۵ از نمادگذاری Booch و Rational Rose استفاده میکند؛ UML هنوز وجود نداشت. نگاشت به انواع نمودار UML بعدها از راه Rational Unified Process و تجربهٔ عملی آمد. هر نمادگذاری کار میکند به شرط آنکه هر نما راهنما (key) داشته باشد.
از کجا آمده
Perry و Wolf، ۱۹۹۲. مقالهٔ Foundations for the Study of Software Architecture (ACM Software Engineering Notes) فرمولی را داد که Kruchten بر آن بنا میکند، به نقل خودش "modified by Boehm": "Software architecture = {Elements, Forms, Rationale/Constraints}". Kruchten این فرمول را برای هر نما جداگانه به کار میبرد: برای هر نما نوع عنصرها (components، containers، connectors)، فرمها و الگوها، و دلیلها را انتخاب کن.
Kruchten، ۱۹۹۵. Philippe Kruchten که آن زمان در Rational Software Corp. بود، مقالهٔ Architectural Blueprints—The "4+1" View Model of Software Architecture را در IEEE Software 12(6)، نوامبر ۱۹۹۵، صفحههای ۴۲ تا ۵۰ منتشر کرد. مثالها از یک PABX (سوئیچ تلفن، از کار در Alcatel) و سیستمهای کنترل ترافیک هوایی (Hughes Aircraft of Canada) میآیند. مقاله میگوید مدل "has been used with success on several large projects" و نماهای پیشنهادی دیگر "could usually be folded into one of the 4": نمای هزینه و زمانبندی در نمای توسعه، نمای داده در نمای منطقی، نمای اجرا در ترکیب پردازه و فیزیکی.
RUP. Rational Unified Process مدل 4+1 را ستون فقرات توصیف معماریاش کرد؛ یادداشتهای فنی SEI میگویند "the Rational Unified Process (RUP), which is based on Kruchten's 4+1 view approach". ساختار Software Architecture Document در خود مقاله (Figure 13) بخشبهبخش از نماها پیروی میکند؛ به سازوکار نگاه کنید.
IEEE 1471-2000 تا ISO/IEC/IEEE 42010. این استاندارد ایده را عمومی کرد: مجموعهٔ ثابتی از نماها تجویز نمیکند، بلکه مفهوم دیدگاه (Viewpoint) را تجویز میکند که از دغدغههای ذینفعان انتخاب میشود. ویرایش ۲۰۱۱ همان ISO/IEC/IEEE 42010:2011 است؛ ویرایش دوم در ۲۰۲۲ آمد که «Architecture Model» را به «View Component» تغییر نام داد و «System of Interest» را به «Entity of Interest» عمومی کرد (به گفتهٔ سایت نگهدارندگان استاندارد). همان سایت «Kruchten’s 4+1 View Model» را نمونهای از یک architecture framework میشمارد.
Views and Beyond مؤسسهٔ SEI، ۲۰۰۲ و ۲۰۱۰. کتاب Documenting Software Architectures: Views and Beyond از Clements، Bachmann، Bass، Garlan، Ivers، Little، Merson، Nord و Stafford (ویرایش دوم در صفحهٔ SEI با تاریخ October 5, 2010) نماها را در سه خانوادهٔ module، component-and-connector و allocation گروه میکند و مستنداتی را اضافه میکند که «فراتر» از نماها هستند. یادداشتهای فنی SEI که خواندیم 4+1 را یکی از روشهایی میدانند که "prescribe a fixed set of views"، در حالی که V&B به معمار اجازه میدهد "whatever views are useful for the system at hand" را انتخاب کند.
Rozanski و Woods. کتاب Software Systems Architecture فهرستی از دیدگاهها (Context، Functional، Information، Concurrency، Development، Deployment، Operational) میسازد و perspectiveها را برای ویژگیهای کیفی که از همهٔ نماها عبور میکنند اضافه میکند. سایتشان میگوید: "In his introductory paper, Kruchten defined four standard views, namely, Logical, Process, Physical, and Development."
C4، دههٔ ۲۰۱۰. صفحهٔ تاریخچهٔ Simon Brown ریشهٔ نمودارهای C4 را به کارگاههایش برمیگرداند: یک کارگاه در QCon London 2010 و ظاهر شدن سلسلهمراتب "systems, containers, components, and classes" تا ۲۰۱۱. پرسشوپاسخ C4 صریح میگوید "the C4 model was inspired by UML and the 4+1 model for software architecture".
arc42. یک قالب رایگان با دوازده بخش؛ بخشهای ۵، ۶ و ۷ آن (نمای building block، runtime و deployment) جاییاند که نماهای 4+1 وقتی تیمی از arc42 استفاده میکند در آن فرود میآیند.
Year Idea What changed in practice
1 1992 Perry & Wolf: elements, forms, rationale Architecture as a structure plus reasons
2 1995 Kruchten: 4 views + scenarios One description per audience
3 2000 RUP book (cited by the SEI as Kruchten 00) Software Architecture Document template
4 2000 IEEE 1471: viewpoint, view, concern Views chosen from stakeholder concerns
5 2002/2010 SEI Views and Beyond Module / C&C / allocation + docs beyond views
6 2000s Rozanski & Woods Viewpoint catalogue + quality perspectives
7 2010+ C4 model Developer-friendly zoom levels, notation-free
8 2011 ISO/IEC/IEEE 42010:2011 International standard for architecture descriptions
9 2022 42010 second edition Entity of interest, view components, aspectsفهرست مفهومها
هر بلوک ترتیب ثابتی دارد: به زبان ساده، باور غلط رایج، تعریف دقیق، یک توالی، سناریوهای واقعی، اینکه ابزارهای امروز چطور فراهمش میکنند، و چطور تولیدش کنیم. مثال جاری همان سکوی سفارش آنلاینِ مثال کامل است.
نمای منطقی (Logical view) حیاتی
به زبان ساده: نمای منطقی نقشهٔ اینکه سیستم دربارهٔ چیست است: مفهومهای کلیدی کسبوکار، مسئولیتها، و اینکه کدام بخش از کدام بخش چه چیزی میخواهد. نه thread، نه سرور، نه پوشه.
بدفهمی رایج: «نمای منطقی همان class diagram کاملی است که از کد تولید میشود.» نمادگذاری Kruchten "considerably simplified to take into account only the items that are architecturally significant" است؛ مثال کنترل ترافیک هوایی او در سطح بالا "8 class categories" را برای "a much bigger system, which contains a few dozen classes of architectural significance" نشان میدهد. نمودار تولیدشدهٔ ۴۰۰ class جزئیاتی است که در IDE نگاهش میکنید، نه یک نما.
تعریف: "The logical architecture primarily supports the functional requirements—what the system should provide in terms of services to its users." سیستم به "key abstractions, taken (mostly) from the problem domain" شکسته میشود، با انتزاع (Abstraction)، کپسولهسازی (Encapsulation) و وراثت (Inheritance)؛ classهای مرتبط در class categoryها جمع میشوند. مقاله شکل غیرشیءگرا را هم میپذیرد: "Alternatively to an OO approach, an application that is very data-driven may use some other form of logical view, such as E-R diagrams." رهنمود سبکی اصلی Kruchten: "keep a single, coherent object model across the whole system".
| جنبه | نمای منطقی |
|---|---|
| عنصرها | Class، class category (امروز: ماژول، bounded context، aggregate) |
| اتصالدهندهها | Association، usage، composition، inheritance، instantiation |
| ذینفعان | کاربران نهایی، تحلیلگران، کارشناسان دامنه، صاحبان محصول |
| دغدغهها | کارکرد (Functionality)، مسئولیتها، واژگان کسبوکار |
| نمادگذاری آن زمان / امروز | class diagram و class template به سبک Booch در Rational Rose / class diagram، object diagram و state machine در UML، E-R diagram، component diagram در C4 |
| نمودارهای معمول | نقشهٔ ماژولها در سطح بالا، طرح classهای دامنه برای هر ماژول، state machine موجودیت اصلی، E-R جدولهای هسته |
| پرسشهایی که پاسخ میدهد | قاعدهٔ کسبوکار کجا زندگی میکند؟ کدام ماژول مالک کدام داده است؟ «سفارش» اینجا یعنی چه؟ |
| پرسشهایی که پاسخ نمیدهد | چند پردازه، کدام پوشه، کدام سرور |
Feature request: "gold customers get free shipping" Logical view question at each step
1 Product owner describes the rule Which concept owns "free shipping"? Shipping or Ordering?
2 Architect looks at the module map Shipping computes cost; Ordering only asks for a quote
3 Team adds Customer.tier to the Catalog/Customer model New attribute in an existing abstraction, no new module
4 Shipping.Quote(order, tier) changes Responsibility stays inside one module
5 Scenario S1 is replayed on paper The interaction diagram still has the same arrowsسناریوهای واقعی:
- منطق checkout هم در controller وب و هم در API موبایل تکرار شده: نمای منطقی نشان میدهد «قیمتگذاری» خانه ندارد؛ یک ماژول برایش بسازید.
- سیستم گزارشگیری دادهمحور: همانطور که Kruchten اجازه میدهد، E-R diagram را نمای منطقی کنید و class را فقط برای چند سرویس نگه دارید.
- دو تیم هر دو خود را «مالک» آدرس مشتری میدانند: نمای منطقی باید یک مالک بدهد و نشان دهد چه کسی آن را میخواند.
- وضعیت سفارش در پنج جا تغییر میکند: یک state machine در نمای منطقی گذارهای مجاز را صریح میکند (pending به confirmed یا rejected، سپس shipped).
امروز چه چیزی فراهمش میکند:
| زمینه | نمای منطقی کجا زندگی میکند |
|---|---|
| Go | نام packageها و typeهای export شده (ordering.Order، ordering.Service)، portها بهشکل interfaceهای کوچکی که مصرفکننده تعریف میکند |
| Laravel | app/Modules/<Name>/Domain (مدلهای Eloquent، enum، value object)، Application (use caseها)، Api (قراردادها) |
| UML | Class diagram، state machine، package diagram برای دستهها |
| C4 | System context (دامنه) و component diagram درون یک container |
| DDD | Bounded context و aggregate (به مسیر DDD نگاه کنید) |
| داده | schema هسته بهشکل DDL یا E-R diagram |
چطور تولیدش کنیم: اول سناریوها را فهرست کنید، اسمها و فعلها را علامت بزنید، انتزاعهایی را نگه دارید که در بیش از یک سناریو ظاهر میشوند، آنها را در پنج تا نه دسته گروه کنید و فقط فلشهایی را بکشید که یک سناریو لازم دارد. برای هستهٔ دادهمحور، DDL بخشی از نمای منطقی است:
-- Logical view, data form (Kruchten: "E-R diagrams" for data-driven systems).
-- PostgreSQL 17. Ownership: the Ordering module owns these three tables.
CREATE TABLE orders (
id text PRIMARY KEY, -- ULID from the application
customer_id text NOT NULL,
total_cents bigint NOT NULL CHECK (total_cents >= 0),
status text NOT NULL CHECK (status IN ('pending', 'confirmed', 'rejected', 'shipped')),
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE order_lines (
order_id text NOT NULL REFERENCES orders (id),
sku text NOT NULL,
quantity integer NOT NULL CHECK (quantity > 0),
price_cents bigint NOT NULL CHECK (price_cents >= 0),
PRIMARY KEY (order_id, sku)
);
-- The outbox belongs to the same module and the same transaction (process view, step 4).
CREATE TABLE outbox (
id bigserial PRIMARY KEY,
type text NOT NULL,
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
sent_at timestamptz
);
CREATE INDEX outbox_unsent ON outbox (id) WHERE sent_at IS NULL;بیان Go و Laravel همین نما در Go (internal/ordering) و Laravel (app/Modules/Ordering/Domain) آمده است.
نمای پردازه (Process view) حیاتی
به زبان ساده: نمای پردازه نشان میدهد چه چیزی همزمان اجرا میشود، چه چیزی منتظر چه چیزی است و قطعههای در حال اجرا چطور با هم حرف میزنند: درخواست، thread، worker، صف، timeout، retry.
بدفهمی رایج: «نمای پردازه یعنی فرایند کسبوکار (BPMN).» «process» در حرف Kruchten یک واحد اجرا در سطح سیستمعامل است: "A process is a grouping of tasks that form an executable unit." گردش کار کسبوکار یک سناریو است؛ نمای پردازه دربارهٔ همروندی (Concurrency) و توزیع (Distribution) است.
تعریف: "The process architecture takes into account some non-functional requirements, such as performance and availability. It addresses issues of concurrency and distribution, of system's integrity, of fault-tolerance, and how the main abstractions from the logical view fit within the process architecture—on which thread of control is an operation for an object actually executed." پردازهها "the level at which the process architecture can be tactically controlled (i.e., started, recovered, reconfigured, and shut down)" هستند و "can be replicated for increased distribution of the processing load, or for improved availability". یک task یعنی "a separate thread of control". taskهای اصلی (Major tasks) از راه "synchronous and asynchronous message-based communication services, remote procedure calls, event broadcast, etc." حرف میزنند؛ taskهای فرعی (Minor tasks) محلیاند (timeout، buffering). یک قاعده از ۱۹۹۵ که مثل قاعدهٔ microservices خوانده میشود: "Major tasks shall not make assumptions about their collocation in the same process or processing node."
| جنبه | نمای پردازه |
|---|---|
| عنصرها | پردازهها، taskها و threadها (امروز: سرویسها، پردازهٔ اصلی podها، workerها، consumerها، cron jobها) |
| اتصالدهندهها | Message، RPC، پیام دوطرفه، event broadcast (امروز: HTTP، gRPC، AMQP، Kafka، و دیتابیس مشترک بهعنوان ضداتصالدهنده) |
| ذینفعان | طراحان سیستم، یکپارچهسازها، مهندسان کارایی، SREها |
| دغدغهها | کارایی، دسترسپذیری، تحمل خطای نرمافزار، یکپارچگی، throughput، بودجهٔ تأخیر |
| نمادگذاری آن زمان / امروز | نمادگذاری tasking زبان Ada به سبک Booch با نشانهٔ «periodic process» / sequence، activity و communication diagram در UML؛ container و dynamic diagram در C4 |
| نمودارهای معمول | توپولوژی پردازهها با فلش همگام و ناهمگام، یک sequence diagram برای هر سناریوی حیاتی، جدول timeout و retry |
| پرسشهایی که پاسخ میدهد | چه چیزی یک درخواست را معطل میکند؟ کدام فراخوانی ممکن است timeout شود؟ چه چیزی retry میشود و آیا idempotent است؟ اگر این پردازه وسط کار کرش کند چه میشود؟ |
One POST /orders inside orders-api (Go) Process view property
1 LB picks a pod; net/http starts a goroutine One thread of control per request
2 context.WithTimeout(ctx, 2s) Latency budget for the whole request
3 inventory.Reserve (in-process call, ~1 ms) Sync, same process: no network failure mode
4 payments.Authorize -> HTTPS to provider (~300 ms) Sync, remote: timeout + retry + idempotency key
5 BEGIN; INSERT orders, lines, outbox; COMMIT Integrity: one local transaction
6 201 returned; goroutine ends Nothing else waits on this request
7 outbox-relay ticker (500 ms) reads unsent rows Separate periodic process, at-least-once
8 shipping-worker consumes OrderPlaced, acks Async; crash before ack = redeliveryسناریوهای واقعی:
- checkout پشت سر هم چهار سرویس را صدا میزند، هر کدام با timeout پنج ثانیه، پشت یک load balancer با timeout ده ثانیه: فقط نمای پردازه نشان میدهد این بودجهها با هم جور نیستند.
- ایمیلهایی که درون درخواست وب فرستاده میشوند checkout را کند میکنند و وقتی سرور ایمیل کند است شکستش میدهند: نمای پردازه آنها را به یک worker منتقل میکند.
- یک cron job و یک queue worker هر دو «فاکتورهای ارسالنشده» را پردازش میکنند: نمای پردازه دو thread of control روی یک سطرها را نشان میدهد، پس قفل اضافه میکنید.
- PABX در مقالهٔ Kruchten: یک task اسکن ۲۰۰ میلیثانیهای و یک task ۱۰ میلیثانیهای درون یک پردازهٔ controller، بهخاطر قیدهای سخت بیدرنگ.
- Kruchten یک معماری پردازهٔ «hollow» پیشنهاد میکند "with dummy loads for the processes" تا کارایی روی سیستم مقصد اندازه گرفته شود؛ امروز این همان load test روی سرویسهای stub است.
امروز چه چیزی فراهمش میکند:
| زمینه | واحد نمای پردازه | اتصالدهنده |
|---|---|---|
| Go | یک پردازهٔ سیستمعامل برای هر binary زیر cmd/؛ goroutineها بهعنوان task؛ deadline با context | net/http، gRPC، channel درون یک پردازه، clientهای broker |
| Laravel (PHP-FPM) | برای هر درخواست یک پردازهٔ worker در FPM، بدون حافظهٔ مشترک میان درخواستها | HTTP، صفها (ShouldQueue)، eventها |
| Laravel Octane (FrankenPHP، Open Swoole، Swoole، RoadRunner) | workerهای ماندگار که درخواستهای زیادی را سرویس میدهند؛ --workers، --max-requests | همان، بهعلاوهٔ state در حافظه که باید reset شود |
| queue worker در Laravel | پردازههای php artisan queue:work | درایورهای صف Redis، database، SQS |
| scheduler در Laravel | php artisan schedule:work (یا cron که schedule:run را صدا میزند) | job یا command را dispatch میکند |
| Kubernetes | پردازهٔ اصلی container؛ replicaها؛ probeها | Serviceها، DNS |
چطور تولیدش کنیم: ماژولهای منطقی را بردارید و برای هر انتزاع چهار پرسش Kruchten را بپرسید: فعال است یا منفعل، ماندگار یا گذرا، تابع شیء دیگری است یا نه، توزیعشده است یا نه؟ بعد با دو راهبردی که در تناظر آمده گروهبندی کنید. برای هر فلش بنویسید: همگام یا ناهمگام، timeout، سیاست retry، کلید idempotency. بهجای درس دوباره، به منابع عمیقتر پیوند بدهید: Service Communication، outbox، retry.
نمای توسعه (Development view) حیاتی
به زبان ساده: نمای توسعه نشان میدهد کد چطور به پوشه، package، کتابخانه و مخزن بریده میشود، مالک هر بخش کیست، چه چیزی میتواند به چه چیزی وابسته باشد و چطور build میشود.
بدفهمی رایج: «نمای توسعه همان نمای منطقی است با اسم فایلها.» Kruchten عکسش را دید: "The logical and development views are very close, but address very different concerns. We have found that the larger the project, the greater the distance between these views." مثال او: دستهٔ «External interfaces—Gateway» در چند لایه پخش شده است، از subsystemهای پروتکل در لایهٔ ۱ تا gatewayهای مشخص در لایهٔ ۵.
تعریف: "The development architecture focuses on the actual software module organization on the software development environment. The software is packaged in small chunks—program libraries, or subsystems—that can be developed by one or a small number of developers." subsystemها در لایهها سازمان مییابند، "each layer providing a narrow and well-defined interface to the layers above it". حتی پیش از شناختن همهٔ ماژولها "possible to list the rules that govern the development architecture: partitioning, grouping, visibility". دغدغههایش "internal requirements related to the ease of development, software management, reuse or commonality, and to the constraints imposed by the toolset, or the programming language" است. این نما "serves as the basis for requirement allocation, for allocation of work to teams (or even for team organization), for cost evaluation and planning, for monitoring the progress of the project, for reasoning about software reuse, portability and security. It is the basis for establishing a line-of-product." توصیهٔ سبکی: "We recommend adopting a layered style for the development view, defining some 4 to 6 layers of subsystems"، و هر subsystem فقط میتواند به subsystemهای همان لایه یا لایههای پایینتر وابسته باشد. قاعدهٔ سرانگشتی اندازه از مقاله: "typically 5K to 20K SLOC per subsystem".
| جنبه | نمای توسعه |
|---|---|
| عنصرها | Module، subsystem، layer، کتابخانه (امروز: package و module در Go، package در Composer، ماژول Laravel، مخزن، هدف build، image) |
| اتصالدهندهها | وابستگی کامپایل ("with"، "include"، import، use) |
| ذینفعان | توسعهدهندگان، tech leadها، مدیران پروژه و پیکربندی، بازبینهای امنیت |
| دغدغهها | سازماندهی، استفادهٔ دوباره، قابلیت حمل، زمان build، مالکیت تیمی، راهبرد انتشار |
| نمادگذاری آن زمان / امروز | نمودار module/subsystem به سبک Booch، Rational Apex قاعدهها را اعمال میکرد / package و component diagram در UML، component در C4، گراف importِ تولیدشده، درخت مخزن |
| نمودارهای معمول | نمودار لایهها با وابستگیهای مجاز، جدول مالکیت ماژول (CODEOWNERS)، خط لولهٔ build (Build pipeline) |
| پرسشهایی که پاسخ میدهد | کد جدید را کجا بگذارم؟ آیا ordering اجازه دارد payments/internal را import کند؟ چه کسی این پوشه را بازبینی میکند؟ چه چیزی دوباره build میشود؟ |
A pull request that breaks the development view What catches it
1 Dev adds `import ".../payments/internal/gateway"` in ordering
2 go build Go: "use of internal package ... not allowed"
3 (Laravel) `use App\Modules\Payments\Internal\...` PHP does not stop it at compile time
4 CI runs tests: archtest / Pest arch() Rule table = the development view, fails the build
5 CI runs viewgen + git diff Generated diagram changed: reviewer sees a new arrow
6 Reviewer either rejects or updates the rule + ADR The view changes on purpose, not by accidentسناریوهای واقعی:
- دوازده تیم در یک مخزن: نمای توسعه پوشهها را به تیمها میسپارد (و CODEOWNERS بازبینی را اجباری میکند)؛ «allocation of work to teams» حرف Kruchten امروز این شکلی است.
- اپ Laravel که هر model در همهجا استفاده شده: کشیدن نمای توسعه یک گلولهٔ گِل (Big ball of mud) را نشان میدهد؛ یک modular monolith با پوشههای
Api/وInternal/و قاعدههایarch()در Pest شکل را درست میکند. - خط محصول (فروشگاه white-label برای چند برند): ایدهٔ line-of-product حرف Kruchten؛ لایههای ۱ و ۲ مشترک، لایهٔ بالایی مخصوص برند.
- build چهل دقیقه طول میکشد: نمای توسعه نشان میدهد کدام ماژول کدام build را راه میاندازد و چه چیزی cache پذیر است.
- جدا کردن یک سرویس در آینده: اگر نمای توسعه از قبل ماژولی با API باریک دارد، جدا کردن یعنی «پوشه را جابهجا کن و یک client شبکه پشت همان interface بگذار».
امروز چه چیزی فراهمش میکند:
| سازوکار | Go | Laravel / PHP |
|---|---|---|
| پنهانسازی | پوشههای internal/ (کامپایلر اعمالش میکند) | قرارداد (namespace به نام Internal/) + arch() در Pest یا Deptrac |
| مرز ماژول | ماژول Go (go.mod)، package | package در Composer، app/Modules/<Name> + service provider |
| قاعدهٔ وابستگی | گراف import بدون خطای go vet + تستی مثل archtest | arch()->expect(...)->not->toUse(...) در Pest، layer و ruleset در Deptrac |
| نقطهٔ ورود | cmd/<binary>/main.go (composition root) | routes/، bootstrap/app.php، bootstrap/providers.php |
| Build | go build ./cmd/...، یک image برای هر command | یک image، چند command (web، worker، scheduler) |
| مالکیت | CODEOWNERS | CODEOWNERS |
چطور تولیدش کنیم: از قاعدهها شروع کنید (partitioning، grouping، visibility)، نه از درخت کامل. جدول وابستگیهای مجاز را بنویسید، آن را در یک تست بگذارید و بعد تصویر را از روی تست بکشید یا تولیدش کنید (سازوکار).
نمای فیزیکی (Physical view) حیاتی
به زبان ساده: نمای فیزیکی ماشینها، containerها، شبکهها و انبارهای داده را نشان میدهد و اینکه هر پردازهٔ در حال اجرا کجا نشسته است.
بدفهمی رایج: «فقط یک نمای فیزیکی وجود دارد.» Kruchten: "We expect that several different physical configurations will be used: some for development and testing, others for the deployment of the system for various sites or for different customers." C4 هم همین را میگوید: اطلاعات استقرار "better captured via one or more deployment diagrams, one per environment" است. لپتاپ شما، staging و production سه نمای فیزیکیِ یک معماریاند.
تعریف: "The physical architecture takes into account primarily the non-functional requirements of the system such as availability, reliability (fault-tolerance), performance (throughput), and scalability." نرمافزار روی "a network of computers, or processing nodes" اجرا میشود؛ "networks, processes, tasks, and objects—need to be mapped onto the various nodes". نیاز کلیدی: "The mapping of the software to the nodes therefore needs to be highly flexible and have a minimal impact on the source code itself." مثال PABX او همان پردازهها را روی یک پیکربندی سختافزاری کوچک و یک پیکربندی بزرگ نگاشت میکند (Figure 9 و Figure 10).
| جنبه | نمای فیزیکی |
|---|---|
| عنصرها | پردازنده، دستگاه، node (امروز: VM، node و pod در Kubernetes، دیتابیس مدیریتشده، load balancer، zone، region) |
| اتصالدهندهها | خط ارتباطی، bus، LAN، WAN (امروز: شبکهٔ VPC، service mesh، VPN، پیوند replication) |
| ذینفعان | مهندسان سیستم، اپراتورها، SREها، امنیت، مالی (هزینه) |
| دغدغهها | دسترسپذیری، قابلیت اطمینان، throughput، مقیاسپذیری، توپولوژی، تأخیر میان nodeها، هزینه |
| نمادگذاری آن زمان / امروز | نمادهای processor و device مقالهٔ Kruchten / deployment diagram در UML، deployment diagram در C4، آیکنهای ارائهدهندهٔ ابر با راهنما |
| نمودارهای معمول | یک deployment diagram برای هر محیط؛ چیدمان zone و region؛ مسیرهای replication داده |
| پرسشهایی که پاسخ میدهد | چه چیزهایی با هم از کار میافتند؟ primary کجاست؟ شعاع انفجار قطعی یک zone چقدر است؟ کدام پرش شبکه کند است؟ |
Zone A goes down (production physical view) What the view must already show
1 2 of 3 orders-api pods disappear Replicas spread over zones (topologySpreadConstraints)
2 LB health checks mark them unhealthy Readiness probe on /healthz
3 PostgreSQL primary was in zone A Standby in zone B + failover procedure
4 Standby promoted; apps reconnect Connection strings point at a service, not an IP
5 outbox-relay pod rescheduled in zone B Only one relay: singleton, needs leader/lock
6 Broker node 1 lost; quorum (2 of 3) remains Three nodes in three zones, quorum queuesسناریوهای واقعی:
- همهچیز «افزونه» است ولی هر دو node دیتابیس روی یک آرایهٔ ذخیرهسازیاند: فقط نمای فیزیکیای که ذخیرهسازی را نشان میدهد این تکنقطهٔ شکست را پیدا میکند.
- ارائهدهندهٔ پرداخت یک IP خروجی ثابت میخواهد: نمای فیزیکی باید NAT gateway هر zone را نشان دهد.
- یک batch job شبانه پیوند شبکه به دیتابیس را اشباع میکند: نمای فیزیکی این پیوند مشترک را نشان میدهد.
- اقامت داده (دادهٔ مشتریان اروپایی باید در regionهای اروپا بماند): نمای فیزیکی جایی است که این را ثابت میکنید.
امروز چه چیزی فراهمش میکند: زیرساخت بهشکل کد (Infrastructure as code) همان نمای فیزیکی بهشکل کد است: Dockerfileها (image چه چیزی دارد)، Docker Compose (توپولوژی یک محیط)، manifestهای Kubernetes یا chartهای Helm (replica، probe، zone)، Terraform (شبکهها، دیتابیسها). مثال کامل هر سه را برای سکوی سفارش نشان میدهد.
چطور تولیدش کنیم: برای هر محیط یک نمودار بکشید؛ برای هر node پردازههایی از نمای پردازه را که رویش اجرا میشوند، تعداد replica و اتفاق هنگام از دست رفتنش را بنویسید. نگاشت را دادهمحور نگه دارید (Kruchten ابزاری داشت که آن را "without source code modifications" تغییر میداد؛ ما از متغیر محیطی و manifest استفاده میکنیم).
سناریوها: نمای «+1» (Scenarios) حیاتی
به زبان ساده: چند داستان مهم (use case) از هر چهار نما عبور داده میشوند؛ از راه آنها معماری را اول پیدا میکنید و بعد ثابت میکنید که سر پا میماند.
بدفهمی رایج: «سناریوها فهرست کامل use caseها هستند.» آنها "a small set of important scenarios"، یعنی "instances of more general use cases" هستند که بر پایهٔ ریسک و اهمیت انتخاب میشوند. ده سناریوی خوب از دویست user story بهتر است.
تعریف: Kruchten: "The scenarios are in some sense an abstraction of the most important requirements." این نما "is redundant with the other ones (hence the “+1”), but it serves two main purposes": "as a driver to discover the architectural elements during the architecture design" و "as a validation and illustration role after this architecture design is complete, both on paper and as the starting point for the tests of an architectural prototype". هر سناریو یک script دارد: "sequences of interactions between objects, and between processes". «حیاتی» یعنی "the most important, the raison d’être of the system, or that have the highest frequency of use, or that present some significant technical risk that must be mitigated".
نمودار بالا سناریوی S1 مثال کامل بهشکل sequence است: گامهای ۱ تا ۵ درون یک درخواست HTTP اجرا میشوند و گامهای ۶ تا ۹ بعداً در پردازههای دیگر. هر فلش باید در یک نمای دیگر وجود داشته باشد: Order و portها در نمای منطقی، goroutine و relay در نمای پردازه، سه binary در نمای توسعه، podها و primary دیتابیس در نمای فیزیکی.
| سناریو (سکوی سفارش) | چرا انتخاب شد | نماهایی که فشار میخورند |
|---|---|---|
| S1 ثبت سفارش (مسیر خوش) | دلیل وجود سیستم، بیشترین تکرار | هر چهار نما |
| S2 کالا ناموجود | قاعدهٔ کسبوکار، نباید پول کم شود | منطقی، پردازه |
| S3 رد پرداخت یا timeout ارائهدهنده | وابستگی بیرونی، پول | پردازه، فیزیکی (خروجی شبکه) |
| S4 کرش relay بعد از publish و پیش از mark-sent | رویدادهای تکراری | پردازه (consumer idempotent) |
| S5 از دست رفتن zone A در اوج بار | دسترسپذیری | فیزیکی، پردازه |
| S6 توسعهدهندهٔ تازه روش پرداخت «کارت هدیه» اضافه میکند | تغییرپذیری | توسعه، منطقی |
حلقهٔ تکرارشوندهٔ مقاله بهشکل توالی:
Kruchten's scenario-driven iteration Ordering platform, iteration 1
1 Choose a few scenarios by risk and criticality S1, S3 (money and an external dependency)
2 Put a strawman architecture in place One Go binary, PostgreSQL, a fake PSP
3 "Script" the scenarios: (object, operation) pairs Order.place, Payments.authorize, Store.save
4 Lay the elements on the 4 blueprints Draw logical/process/development/physical
5 Implement, test, measure (under load, target env if possible) k6 at 200 orders/s; p99 of step 4 = 900 ms
6 Capture lessons, reassess risks PSP latency dominates: add timeout + async capture?
7 Next iteration: add scenarios, update all 4 views S4, S5; outbox relay appears in process view
8 Stop when no new abstractions, processes, interfaces appear Kruchten: "after 2 or 3 iterations"چطور تولیدش کنیم: سه تا شش سناریو را بهشکل script شمارهدار بنویسید؛ برای هر گام عنصری را که در هر نما لمس میکند یادداشت کنید؛ هر کدام را به یک تست خودکار تبدیل کنید (acceptance test برای بخش منطقی و پردازه، تمرین chaos یا failover برای بخش فیزیکی). بخش Go سناریوهای S1 تا S3 و بخش Laravel سناریوهای S1 و S3 را بهشکل تست نشان میدهند.
تناظر میان نماها (Correspondence) مهم
به زبان ساده: نماها نقاشیهای مستقل نیستند؛ هر class در یک ماژول فرود میآید، در یک پردازه اجرا میشود و روی یک node مینشیند. نوشتن این پیوندهاست که چهار نقاشی را یک معماری نگه میدارد.
بدفهمی رایج: «اگر نماها جدا هستند، آدمهای جدا میتوانند مستقل طراحیشان کنند.» مقاله: "The various views are not fully orthogonal or independent. Elements of one view are connected to elements in other views, following certain design rules and heuristics."
تعریف: Kruchten سه نگاشت را توصیف میکند. منطقی به پردازه: هر class را بر اساس خودمختاری (active، passive، protected)، ماندگاری (Persistence)، تبعیت (Subordination) و توزیع (Distribution) دستهبندی کنید و بعد با دو راهبرد همزمان خوشهبندی کنید: inside-out ("Starting from the logical architecture: define agent tasks which multiplex a single thread of control") و outside-in ("Starting with the physical architecture: identify external stimuli (requests) to the system, define client processes to handle the stimuli and servers processes that only provide services and do not initiate them"). منطقی به توسعه: "A class is usually implemented as a module"؛ class categoryها subsystem میشوند و بر اساس سازمان تیم، اندازهٔ کد، استفادهٔ دوباره و لایهبندی تنظیم میشوند، پس معمولاً تناظر یکبهیک وجود ندارد. پردازه به فیزیکی: پردازهها و گروههای پردازه روی سختافزار نگاشت میشوند "in various configurations for testing or deployment". ISO 42010 بعدها این را بهشکل correspondence و correspondence rule رسمی کرد؛ V&B اسمش را «mapping between views» میگذارد.
Element (logical) Development (module) Process (thread of control) Physical (node)
1 Order, OrderLine internal/ordering orders-api request goroutine orders-api pods, zones A+B
2 PaymentsApi internal/payments same goroutine, HTTPS call to PSP orders-api pods; egress NAT
3 OutboxEvent internal/platform/outbox outbox-relay (periodic, single) 1 pod, any zone
4 Shipment internal/shipping shipping-worker (consumer x2) worker pods
5 (data) orders table migrations in ordering PostgreSQL backend processes primary zone A, standby zone Bسناریوی واقعی: در بازبینی یک حادثه میپرسند «کدام کد روی nodeای اجرا میشد که حافظهاش تمام شد؟» بدون جدول تناظر کسی سریع جواب نمیدهد؛ با آن، جواب یک جستوجوی ساده است. microservices تناظر توسعه به پردازه را پیشپاافتاده میکند (یک مخزن، یک پردازه) و تناظر پردازه به فیزیکی را حیاتی (صدها pod).
چطور تولیدش کنیم: جدول بالا را در سند معماری نگه دارید؛ ستون توسعه به پردازه را از فایلهای build (پوشههای cmd/، خطهای command: در Compose) و ستون پردازه به فیزیکی را از manifestها تولید کنید.
دیدگاه و نما: ISO/IEC/IEEE 42010 (Viewpoint و view) مهم
به زبان ساده: 42010 استانداردی است که واژهها را توضیح میدهد: یک ذینفع (Stakeholder) دغدغههایی (Concerns) دارد؛ یک دیدگاه (Viewpoint) دستورپخت پاسخ دادن به چند دغدغه است؛ یک نما (View) همان دستورپخت است که روی سیستم شما اجرا شده؛ هر نما مدلهایی (نمودار، جدول، متن) دارد.
بدفهمی رایج: «view و viewpoint مترادفاند.» viewpoint میان سیستمها قابل استفادهٔ دوباره است («دیدگاه استقرار: node، پیوند، این نمادها، این پرسشها»)؛ view مشخص است («استقرار production سکوی سفارش»). 4+1 در زبان 42010 یک architecture framework است که پنج viewpoint را ثابت میکند.
تعریف (نقل از صفحهٔ conceptual model نگهدارندگان استاندارد):
| مفهوم | تعریف (نقلقول) |
|---|---|
| معماری (Architecture) | "fundamental concepts or properties of a system in its environment embodied in its elements, relationships, and in the principles of its design and evolution" |
| توصیف معماری (Architecture description) | "a work product used to express the Architecture of some System Of Interest" |
| ذینفع (Stakeholder) | "individuals, groups or organizations holding Concerns for the System of Interest" |
| دغدغه (Concern) | "any interest in the system" |
| دیدگاه معماری (Architecture viewpoint) | "a set of conventions for constructing, interpreting, using and analyzing one type of Architecture View" |
| نمای معماری (Architecture view) | "expresses the Architecture of the System of Interest from the perspective of one or more Stakeholders to address specific Concerns, using the conventions established by its viewpoint" |
| نوع مدل (Model kind) | "defines the conventions for one type of Architecture Model" |
| تناظر (Correspondence) | "express a relation between AD Elements" |
| دلیل معماری (Architecture rationale) | "records the explanation, justification or reasoning about Architecture Decisions that have been made and architectural alternatives not chosen" |
| چارچوب معماری (Architecture framework) | "establishes a common practice for creating, interpreting, analyzing and using architecture descriptions"؛ نمونهها شامل "Kruchten’s 4+1 View Model" |
ویرایش دوم ۲۰۲۲ (به گفتهٔ همان سایت): "Architecture Model is changed to View Component"، موضوع توصیف بهجای «System of Interest» یک «Entity of Interest» است، و «Stakeholder Perspectives» (برای گروهبندی دغدغهها) و «Architecture Aspects» اضافه شدهاند.
42010 chain for the ordering platform
1 Stakeholder: SRE team
2 Concern: "what is lost if one availability zone fails?"
3 Viewpoint: deployment (model kinds: node diagram, replica table; rule: one diagram per environment)
4 View: "Production deployment, eu-central, November 2026"
5 Models: the physical SVG + the Kubernetes manifests + the replica/failover table
6 Correspondence: process "orders-api" -> 3 pods, zones A, A, B
7 Rationale: ADR-0012 "standby in a second zone, not a second region"سناریوی واقعی: یک نهاد ناظر «مستندات معماری» را میخواهد. پاسخ همشکل 42010 اول ذینفعان و دغدغهها را فهرست میکند، بعد اینکه کدام viewpoint به کدام دغدغه پاسخ میدهد، و بعد نماها را. این فهرست فهرست مطالب یک سند خوب 4+1 هم هست.
Views and Beyond: module، component-and-connector، allocation مهم
به زبان ساده: روش SEI همهٔ نماهای ممکن را در سه خانواده گروه میکند: کد چطور بریده شده (module)، چه چیزی اجرا میشود و حرف میزند (component-and-connector یا C&C)، و نرمافزار چطور به چیزهای غیرنرمافزاری نگاشت میشود (allocation). بعد مستنداتی را اضافه میکند که از نماها فراترند.
بدفهمی رایج: «V&B جای 4+1 را میگیرد.» آن را عمومی میکند: یادداشت SEI میگوید برخی نویسندگان "prescribe a fixed set of views" (و از RUP/4+1 و Siemens Four Views نام میبرد)، در حالی که "architects should produce whatever views are useful for the system at hand". نماهای 4+1 در این سه خانواده جا میگیرند.
تعریف (از یادداشتهای فنی CMU/SEI-2005-TN-017 و CMU/SEI-2003-TN-023): "Documenting an architecture is a matter of documenting the relevant views and then adding documentation that applies to more than one view."
| خانوادهٔ V&B | عبارت SEI | سبکهای معمول | معادل در 4+1 |
|---|---|---|---|
| Module views | "how the system is to be structured as a set of code units" | Decomposition، uses، generalization، layered، data model | منطقی (decomposition، داده) و توسعه (لایهها، uses) |
| Component-and-connector (C&C) views | "how the system is to be structured as a set of interacting runtime elements" | Pipe-and-filter، client-server، publish-subscribe، shared data | پردازه |
| Allocation views | "how the system relates to non-software structures in its environment" | Deployment، implementation (فایلها)، work assignment | فیزیکی (deployment)، توسعه (work assignment، فایلها) |
انتخاب نماها یک رویهٔ سهگامی است: (۱) جدول ذینفع/نما بسازید و برای هر خانه یکی از «none، overview only، detailed» را بزنید؛ (۲) نماهایی را که مخاطب ضعیف دارند یا تناظر قوی عنصری دارند ادغام کنید («combined view»)؛ (۳) اولویت بدهید. هر نما قالب استاندارد دارد: primary presentation (با راهنما)، element catalog، context diagram، variability guide، rationale، سایر اطلاعات. بخش «فراتر از نماها» شامل documentation roadmap، view template، system overview، mapping between views، directory، و glossary و فهرست اختصارها است.
Stakeholder/view table (V&B step 1) for the ordering platform
stakeholder decomposition uses C&C deployment work assignment
1 product owner overview none none none none
2 new developer detailed detail overv none overview
3 SRE none none detail detailed none
4 security reviewer overview overv detail detailed none
5 engineering mgr overview none none overview detailed
-> combine uses + decomposition; deployment is mandatory; work assignment = CODEOWNERS tableمدل C4 (C4 model) حیاتی
به زبان ساده: C4 یک بزرگنمایی است: system context (سیستم و کسانی که از آن استفاده میکنند)، containerها (اپها و انبارهای داده)، componentها (درون یک container)، code؛ بهعلاوهٔ نمودارهای deployment و dynamic. رایجترین راهی است که تیمها امروز محتوای 4+1 را میکشند.
بدفهمی رایج: «container در C4 همان container داکر است.» سایت C4 میگوید "Not Docker!": "a container represents an application or a data store"، مثلاً یک وباپ سمت سرور، یک single-page app، یک schema دیتابیس یا یک bucket در S3.
تعریف: "A set of hierarchical abstractions - software systems, containers, components, and code"، "a set of hierarchical diagrams - system context, containers, components, and code" و "an additional set of supporting diagrams - system landscape, dynamic, and deployment"؛ "Notation independent" و "Tooling independent". سایت فقط چیزی را توصیه میکند که ارزش اضافه کند: "the system context and container diagrams are sufficient for most software development teams". نمودار dynamic "is based upon a UML communication diagram" و نمودار deployment "based upon a UML deployment diagram" است. پرسشوپاسخ C4: "the C4 model was inspired by UML and the 4+1 model for software architecture".
| نمودار C4 | توصیهشده؟ (c4model.com) | نزدیکترین نمای 4+1 |
|---|---|---|
| System context | بله | دامنهٔ همهٔ نماها؛ منطقی در بازترین بزرگنمایی |
| Container | بله | پردازه (واحدهای زمان اجرا و نحوهٔ گفتوگو) با کمی نشانهٔ فیزیکی |
| Component | "No, only create component diagrams if you feel they add value" | منطقی درون یک container؛ توسعه |
| Code | "No, particularly for long-lived documentation" | منطقی و توسعه در سطح طراحی |
| Deployment | بله | فیزیکی |
| Dynamic | "No, dynamic diagrams should be used sparingly" | سناریوها |
مقایسهٔ عمیقتر نمادگذاری C4 و UML در UML and the C4 model آمده است.
arc42 تکمیلی
به زبان ساده: arc42 قالبی پرکردنی با دوازده بخش شمارهدار است؛ سه بخش از آن همان نماهای 4+1 با اسم دیگرند.
بدفهمی رایج: «arc42 و 4+1 رقیباند.» arc42 ساختار سند است؛ 4+1 مجموعهای از نماهاست؛ میتوانید نماهای 4+1 را در بخشهای arc42 بگذارید.
| بخش arc42 | چه چیزی در آن است (از docs.arc42.org) | معادل در 4+1 |
|---|---|---|
| 1 Introduction and Goals | نیازمندیها، ذینفعان، هدفهای کیفی اصلی | ورودی انتخاب سناریو |
| 3 Context and Scope | زمینهٔ کسبوکاری و فنی، interfaceهای بیرونی | context در C4؛ فیزیکی (زمینهٔ فنی) |
| 4 Solution Strategy | تصمیمها و ایدههای بنیادین | دلیلها در همهٔ نماها |
| 5 Building Block View | "static decomposition of the system into building blocks"؛ "mandatory"؛ "the floor plan" | منطقی + توسعه |
| 6 Runtime View | سناریوها: use caseها، interfaceهای حیاتی، راهاندازی، خطاها | پردازه + سناریوها |
| 7 Deployment View | زیرساخت و "the mapping of (software) building blocks to that infrastructure" | فیزیکی |
| 8 Crosscutting Concepts | الگوها و رویههای تکرارشونده | perspectiveهای Rozanski و Woods |
| 9 Architecture Decisions | ADRها | دلیلها (Rationale) |
| 10 Quality Requirements | سناریوهای کیفیت | سناریوها |
| 11 Risks and Technical Debt | مشکلات شناختهشده | ورودی تکرار بعدی |
| 12 Glossary | واژهها | واژگان نمای منطقی |
Rozanski و Woods: دیدگاهها و perspectiveها تکمیلی
به زبان ساده: فهرستی از دیدگاههای آماده برای سیستمهای اطلاعاتی، بهعلاوهٔ perspectiveها: چکلیستهایی برای ویژگیهای کیفی (امنیت، دسترسپذیری، کارایی) که روی همهٔ نماها اعمال میکنید، بهجای کشیدن یک «نمای امنیت».
بدفهمی رایج: «امنیت نمای مخصوص خودش را لازم دارد.» سایتشان: "trying to address these aspects of an architecture by using viewpoints doesn’t work well"؛ perspective یعنی "a collection of activities, tactics, and guidelines that are used to ensure that a system exhibits a particular set of related quality properties that require consideration across a number of the system’s architectural views".
| دیدگاه Rozanski و Woods | چه چیزی را توصیف میکند (از سایتشان) | معادل در 4+1 |
|---|---|---|
| Context | رابطهها با محیط | context در C4 |
| Functional | "functional elements, their responsibilities, interfaces, and primary interactions" | منطقی |
| Information | "the way that the architecture stores, manipulates, manages, and distributes information" | منطقی (شکل داده) |
| Concurrency | نگاشت "functional elements to concurrency units" | پردازه |
| Development | پشتیبانی از "the software development process" | توسعه |
| Deployment | "the environment into which the system will be deployed" | فیزیکی |
| Operational | "how the system will be operated, administered, and supported" | فیزیکی + runbookها (در 4+1 غایب) |
هشدار آنها با شروع مقالهٔ Kruchten همخوان است: "It is not possible to capture the functional features and quality properties of a complex system in a single comprehensible model that is understandable by and of value to all stakeholders."
نگاشت 4+1 به UML، C4، Views and Beyond و arc42
این جدول جمعبندی خود ماست. Kruchten در ۱۹۹۵ پیش از UML مینوشت و از نمادگذاری Booch استفاده میکرد؛ RUP و تجربهٔ بعدی انواع نمودار UML را به نماها چسباندند؛ C4، V&B، arc42 و Rozanski و Woods هر کدام مجموعهٔ خود را تعریف میکنند و هیچکدام نگاشت رسمی یکبهیک به 4+1 منتشر نکرده است. آن را ابزار ترجمه ببینید، نه قاعده.
| نمای 4+1 | انواع نمودار UML (به UML in Practice نگاه کنید) | چرا این نمودار |
|---|---|---|
| منطقی | Class، object، state machine | انتزاعها، رابطهها، چرخهٔ عمر موجودیت اصلی |
| پردازه | Sequence، activity، communication | چه کسی چه کسی را صدا میزند، با چه ترتیبی، موازی یا نه |
| توسعه | Package، component | واحدهای کد و وابستگیهایشان |
| فیزیکی | Deployment | nodeها، artifactها، مسیرهای ارتباطی |
| سناریوها | Use case، sequence | داستان و script آن |
سازوکار (Mechanics)
ساختار Software Architecture Document مهم
مقالهٔ Kruchten با سندی تمام میشود که نماها را حمل میکند (Figure 13) و سند دومی به نام Software Design Guidelines که "captures (among other things) the most important design decisions that must be respected to maintain the architectural integrity of the system".
| بخش (Kruchten، Fig. 13) | امروز چه بنویسیم | معمولاً کجا زندگی میکند |
|---|---|---|
| 1 Scope، 2 References | سیستم در یک پاراگراف، پیوندها | docs/architecture/README.md |
| 3 Software Architecture | سبک در دو جمله + context diagram در C4 | همان |
| 4 Architectural Goals and Constraints | ۳ تا ۵ هدف کیفی اصلی، قیدهای سخت | بخشهای ۱ و ۲ arc42 |
| 5 Logical Architecture | نقشهٔ ماژولها، schema هسته، state machine | docs/architecture/logical.md |
| 6 Process Architecture | توپولوژی پردازهها، جدول timeout و retry | process.md |
| 7 Development Architecture | قاعدههای لایه و وابستگی، مالکیت، pipeline | development.md + archtest + CODEOWNERS |
| 8 Physical Architecture | برای هر محیط یک deployment diagram | physical.md + deploy/ |
| 9 Scenarios | ۳ تا ۶ سناریوی scriptشده، هر کدام پیوندخورده به یک تست | scenarios.md + تستها |
| 10 Size and Performance | فرضهای بار، عددهای اندازهگیریشده | گزارشهای load test |
| 11 Quality | سناریوهای کیفیت و راه راستیآزماییشان | بخش ۱۰ arc42 |
| پیوستها: اختصارها، تعریفها، اصول طراحی | واژهنامه؛ اصول؛ فهرست ADRها | docs/adr/ |
انتخاب نماها: رویهای سهگامی
Step Output for the ordering platform
1 List stakeholders and their concerns PO: functionality; devs: where code goes; SRE: zone loss; security: data flows
2 Match each concern to a view logical, development, process, physical (prod + staging), scenarios
3 Apply Kruchten's tailoring rules 1 process + 1 server? drop process and physical (not our case)
4 Combine weak views (V&B step 2) logical + development as one module map with folder names
5 Prioritize (V&B step 3) process + physical first (risk), then development rules
6 Decide the source of truth per view code, manifests, tests, or a hand-drawn diagram with an ownerنمودار بهشکل کد و نماهای تولیدشده از کد (Diagrams as code) حیاتی
نمایی که در یک ابزار نقاشی زندگی میکند فردای بازبینی کهنه میشود. سه تکنیک آن را صادق نگه میدارند:
| تکنیک | نمونهٔ ابزار | کدام نماها | بررسی کهنگی |
|---|---|---|---|
| نمودار متنی در مخزن | Mermaid (C4Context، C4Container، C4Deployment، C4Dynamic)، C4-PlantUML، Structurizr DSL | همه | در همان pull request کد بازبینی میشود |
| تولید از کد منبع | گراف import (همین viewgen)، class diagram در IDE، گراف وابستگی Deptrac | توسعه، منطقی (سطح کد) | در CI دوباره تولید و git diff --exit-code |
| تولید از زیرساخت بهشکل کد | فایلهای Compose، manifestهای Kubernetes، state در Terraform | فیزیکی | نمودار از همان فایلهایی ساخته میشود که مستقر میکنند |
| قاعدهٔ اجرایی | archtest در Go، arch() در Pest، Deptrac | توسعه | با import ممنوع تست شکست میخورد |
| سناریوی اجرایی | acceptance test، contract test، تمرین chaos | سناریوها، پردازه | وقتی داستان بشکند تست شکست میخورد |
پشتیبانی C4 در Mermaid میگوید "C4 diagram syntax is compatible with plantUML" و C4Context، C4Container، C4Component، C4Dynamic و C4Deployment را پشتیبانی میکند. Structurizr DSL "provides a way to define a software architecture model (based upon the C4 model) using a text-based domain specific language". نمای container سکوی سفارش بهشکل متن Mermaid که کنار کد نگهداری میشود:
C4Container
title Online ordering platform - containers (modular monolith, step 2 of 3)
Person(customer, "Customer", "Buys products in a browser or the app")
System_Ext(psp, "Payment provider", "Authorizes cards")
Container_Boundary(shop, "Ordering platform") {
Container(api, "orders-api", "Go, net/http", "Catalog, cart, ordering, payments modules")
Container(relay, "outbox-relay", "Go", "Publishes committed events")
ContainerDb(db, "shop", "PostgreSQL 17", "orders, order_lines, outbox")
ContainerQueue(mq, "events", "RabbitMQ 4", "OrderPlaced, PaymentAuthorized")
}
Rel(customer, api, "Places orders", "HTTPS/JSON")
Rel(api, psp, "Authorizes payment", "HTTPS")
Rel(api, db, "Reads and writes", "SQL")
Rel(relay, db, "Polls outbox", "SQL")
Rel(relay, mq, "Publishes", "AMQP 0-9-1")همگام نگه داشتن پنج نما حیاتی
| نما | منبع حقیقت | تولید یا بررسی با | چه کسی دستی بهروز میکند |
|---|---|---|---|
| منطقی | APIهای ماژول و schema هسته (DDL، migrationها) | dump از schema؛ فهرست packageها | معمار + مالکان ماژول، وقتی ماژول جدید یا تغییر مالکیت داریم |
| پردازه | نقطههای ورود (cmd/)، پیکربندی صف و topic، timeoutها در کد | جستوجو در cmd/، خطهای command: در Compose | تیمی که یک پردازه یا اتصالدهنده اضافه میکند |
| توسعه | درخت پوشهها، go.mod، composer.json، قاعدههای وابستگی | viewgen + archtest، arch() در Pest، Deptrac | هیچکس: تولیدی است؛ تغییر قاعده ADR میخواهد |
| فیزیکی | Dockerfileها، Compose، Kubernetes، Terraform | رندر از manifestها | تیم platform برای هر محیط |
| سناریوها | acceptance testها و تمرینها | CI، game dayها | محصول + معمار، در هر تکرار |
پیامهایی که واقعاً میبینید
| کجا | پیام | کدام نما نقض شد |
|---|---|---|
| کامپایلر Go | use of internal package m/a/internal/x not allowed | توسعه (قاعدهٔ visibility) |
| تست Go (همین صفحه) | ../../internal/ordering/zz_violation.go imports internal/payments: not allowed by the development view | توسعه (قاعدهٔ وابستگی) |
| Pest | شکست یک انتظار arch() با نام class و namespace ممنوع (متن دقیق به نسخهٔ Pest بستگی دارد) | توسعه |
CI (git diff --exit-code پس از viewgen) | خروج غیرصفر و diff فایل .mmd | نمودار توسعه کهنه است |
| رویدادهای Kubernetes | شکست probe مثل Liveness probe failed: ... (شکست readiness هم به همین شکل گزارش میشود) | فیزیکی (قرارداد سلامت میان پردازه و node) |
context در Go | context deadline exceeded | پردازه (بودجهٔ تأخیر) |
| container در Laravel | Target [App\Modules\Payments\Api\PaymentsApi] is not instantiable | توسعه (provider ماژول در bootstrap/providers.php ثبت نشده) |
مثال کامل: یک سکوی سفارش آنلاین در هر پنج نما
سیستم. یک فروشگاه اینترنتی: مشتری کاتالوگ را میبیند، سفارش میدهد، با کارت از راه یک ارائهدهندهٔ پرداخت بیرونی پول میدهد و بستهاش ارسال میشود. هدفهای کیفی: سفارشی نباید بدون ثبت شدن پول کم کند (یکپارچگی)، p99 در checkout زیر ۱٫۵ ثانیه در ۲۰۰ سفارش در ثانیه (کارایی)، تحمل از دست رفتن یک availability zone (دسترسپذیری)، و اینکه سه تیم بدون پا گذاشتن روی کار هم کار کنند (تغییرپذیری). امروز یک modular monolith به زبان Go است (نسخهٔ Laravel همان شکل را دارد)؛ نماها طوری نوشته شدهاند که جدا کردن بعدی به سرویسها نمای پردازه و فیزیکی را عوض کند، نه نمای منطقی را.
نمای منطقی مثال
پنج class category. Ordering هسته است: Order aggregate root است با OrderLineها و یک state machine به نام OrderStatus؛ PlaceOrder همان use case است و به سه port که خودش مالکشان است وابسته است (Inventory، Payments، Store). Catalog قیمت میدهد، Inventory موجودی رزرو میکند، Payments پشت interface به نام PaymentsApi پول را authorize میکند و Shipping به رویداد OrderPlaced واکنش نشان میدهد. شکل دادهٔ آن همان DDL در بلوک نمای منطقی است.
نمای پردازهٔ مثال
| پردازه | Replica | محرک | با چه چیزی حرف میزند | Timeout / retry | هنگام کرش |
|---|---|---|---|---|---|
orders-api | 3 | درخواست HTTP | PSP (همگام)، PostgreSQL | ۲ ثانیه برای هر درخواست؛ فراخوانی PSP دو بار با کلید idempotency تکرار میشود | درخواست شکست میخورد؛ چیزی نیمهکاره نوشته نمیشود (یک تراکنش) |
outbox-relay | 1 | تایمر، ۵۰۰ میلیثانیه | PostgreSQL، broker | در tick بعدی دوباره | دوباره راه میافتد؛ سطرهای ارسالنشده را دوباره میفرستد (at-least-once) |
shipping-worker | 2 | پیام | broker، API شرکت حمل | backoff، سپس DLQ | تحویل دوباره؛ consumer روی order_id idempotent است |
notify-worker | 1 | پیام | broker، ارائهدهندهٔ ایمیل | backoff | تحویل دوباره؛ ایمیل تکراری با کلید سرکوب میشود |
همین نما در Laravel سه پردازه از یک image دارد: web (Octane روی FrankenPHP یا PHP-FPM)، queue:work و schedule:work:
# PROCESS view made concrete: three processes from the same code base.
services:
web:
build:
context: ..
dockerfile: deploy/app.dockerfile
ports:
- "8000:8000"
env_file: ../.env
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_started
worker:
build:
context: ..
dockerfile: deploy/app.dockerfile
command: ["php", "artisan", "queue:work", "--tries=3"]
env_file: ../.env
depends_on:
- postgres
- redis
scheduler:
build:
context: ..
dockerfile: deploy/app.dockerfile
command: ["php", "artisan", "schedule:work"]
env_file: ../.env
depends_on:
- redis
postgres:
image: postgres:17
environment:
POSTGRES_USER: shop
POSTGRES_PASSWORD: shop
POSTGRES_DB: shop
healthcheck:
test: ["CMD-SHELL", "pg_isready -U shop"]
interval: 5s
retries: 10
redis:
image: redis:7-alpineنمای توسعهٔ مثال
go/ Laravel equivalent
1 go.mod composer.json
2 cmd/orders-api/main.go public/index.php + routes/ (web process)
3 cmd/outbox-relay/main.go app/Modules/Ordering/Jobs/RelayOutbox.php + routes/console.php
4 internal/ordering/ app/Modules/Ordering/{Domain,Application}
5 internal/payments/ app/Modules/Payments/{Api,Internal}
6 internal/platform/outbox/ app/Support/ (shared, no business rules)
7 internal/archtest/ tests/Architecture/DevelopmentViewTest.php
8 tools/viewgen/ (Deptrac can render its graph)
9 deploy/ deploy/pipelineای که این نما را اعمال میکند خودش بخشی از آن است:
# Development view: the build pipeline is part of "how the software is
# organized in its development environment". Rules from the view run here.
name: ci
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
defaults:
run:
working-directory: go
steps:
- uses: actions/checkout@v7
- uses: actions/setup-go@v7
with:
go-version-file: go/go.mod
- run: go vet ./...
- run: go test ./... # scenarios + development-view rules
- run: go run ./tools/viewgen . > ../docs/development-view.mmd
- run: git diff --exit-code ../docs/development-view.mmd # stale view = red build
- run: docker build -f ../deploy/orders.dockerfile --build-arg CMD=orders-api -t shop/orders-api .نمای فیزیکی مثال
نمای فیزیکی بهشکل کد. image (چه چیزی روی یک node اجرا میشود):
# Physical view as code: one image per process from the same Go module.
# Build: docker build -f deploy/orders.dockerfile --build-arg CMD=orders-api -t shop/orders-api .
FROM golang:1.24-alpine AS build
WORKDIR /src
COPY go.mod ./
RUN go mod download
COPY . .
ARG CMD=orders-api
RUN CGO_ENABLED=0 go build -trimpath -o /out/app ./cmd/${CMD}
FROM gcr.io/distroless/static-debian13:nonroot
COPY --from=build /out/app /app
EXPOSE 8080
ENTRYPOINT ["/app"]محیط لپتاپ (هر node یک container است):
# Physical view for ONE environment (a developer laptop): every node of the
# deployment diagram is a service here. Production differs; document both.
services:
orders-api:
build:
context: ../go
dockerfile: ../deploy/orders.dockerfile
args:
CMD: orders-api
ports:
- "8080:8080"
environment:
DATABASE_URL: postgres://shop:shop@postgres:5432/shop?sslmode=disable
depends_on:
postgres:
condition: service_healthy
outbox-relay:
build:
context: ../go
dockerfile: ../deploy/orders.dockerfile
args:
CMD: outbox-relay
environment:
DATABASE_URL: postgres://shop:shop@postgres:5432/shop?sslmode=disable
AMQP_URL: amqp://guest:guest@rabbitmq:5672/
depends_on:
postgres:
condition: service_healthy
rabbitmq:
condition: service_started
postgres:
image: postgres:17
environment:
POSTGRES_USER: shop
POSTGRES_PASSWORD: shop
POSTGRES_DB: shop
healthcheck:
test: ["CMD-SHELL", "pg_isready -U shop"]
interval: 5s
retries: 10
rabbitmq:
image: rabbitmq:4-management
ports:
- "15672:15672"قاعدهٔ جایگذاری در production (replicaهای پخش در zoneها، قرارداد سلامت):
# Physical view for PRODUCTION: replicas, zones and health are architecture
# decisions, and this file is where they are actually enforced.
apiVersion: apps/v1
kind: Deployment
metadata:
name: orders-api
labels:
app: orders-api
spec:
replicas: 3
selector:
matchLabels:
app: orders-api
template:
metadata:
labels:
app: orders-api
spec:
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
app: orders-api
containers:
- name: orders-api
image: registry.example.com/shop/orders-api:1.4.2
ports:
- containerPort: 8080
readinessProbe:
httpGet:
path: /healthz
port: 8080
periodSeconds: 10
resources:
requests:
cpu: 250m
memory: 128MitopologySpreadConstraints با topologyKey: topology.kubernetes.io/zone و whenUnsatisfiable: DoNotSchedule شکل manifest این جمله است: «orders-api از دست رفتن یک zone را تاب میآورد»؛ readinessProbe روی /healthz قرارداد میان نمای پردازه (سرور جواب میدهد) و نمای فیزیکی (load balancer فقط به podهای آماده ترافیک میفرستد) است.
سناریوهای مثال
توالی S1 بالاتر کشیده شده است. S1 تا S3 در ادامه بهشکل تست در Go و S1 و S3 در Laravel خودکار شدهاند؛ S4 (کرش relay) با consumer idempotent و یک تست یکپارچگی که relay را میان publish و mark-sent میکشد پوشش داده میشود؛ S5 (از دست رفتن zone) یک game day فصلی است که nodeهای یک zone را در staging از مدار خارج (cordon) میکند.
S3 Payment declined (Laravel variant), script across the views
1 Logical: PlaceOrder.handle(customer, lines); total computed in cents
2 Process: web worker calls PaymentsApi::authorize -> Http::timeout(2)->retry(2, 100)
3 Physical: egress from the pod through the zone's NAT to the provider
4 Provider answers 402 -> PaymentDeclined thrown before DB::transaction starts
5 Logical: no Order row, no outbox row; the customer sees "payment declined"
6 Development: the test tests/Feature/PlaceOrderScenarioTest.php (S3) proves it on every buildGo
کد Go یک ماژول قابل اجراست (docs/snippets/architecture/kruchten-4plus1-views/go)؛ gofmt -l . خالی است و go vet ./... و go test ./... میگذرند. سرآیند هر فایل میگوید به کدام نما تعلق دارد.
مثال: نمای منطقی در کد
// Package ordering is the core of the LOGICAL view: the key abstractions
// (Order, Line, Status) and the PlaceOrder use case. It depends only on
// small ports it defines itself; payments, stock and messaging are
// adapters that live elsewhere in the DEVELOPMENT view.
package ordering
import (
"context"
"errors"
"fmt"
"time"
)
// Status is the life cycle of an order (a state machine in the logical view).
type Status string
const (
StatusPending Status = "pending"
StatusConfirmed Status = "confirmed"
StatusRejected Status = "rejected"
StatusShipped Status = "shipped"
)
// Line is one product in an order. Money is integer cents.
type Line struct {
SKU string
Quantity int
PriceCents int64
}
// Order is the aggregate root of the ordering context.
type Order struct {
ID string
CustomerID string
Lines []Line
TotalCents int64
Status Status
PlacedAt time.Time
}
// ErrEmptyOrder and ErrOutOfStock are business errors the scenario expects.
var (
ErrEmptyOrder = errors.New("ordering: order has no lines")
ErrOutOfStock = errors.New("ordering: out of stock")
)
// Inventory reserves stock (a port; the adapter may be in-process or remote).
type Inventory interface {
Reserve(ctx context.Context, orderID string, lines []Line) error
}
// Payments authorizes money (a port; owned by ordering, implemented by payments).
type Payments interface {
Authorize(ctx context.Context, orderID string, cents int64) (authID string, err error)
}
// Store persists the order and its outgoing event in ONE local transaction
// (the transactional outbox), so the process view can relay it later.
type Store interface {
SaveWithEvent(ctx context.Context, o Order, eventType string, payload []byte) error
}
// Service is the application service that scenario "place order" walks through.
type Service struct {
Inventory Inventory
Payments Payments
Store Store
Now func() time.Time
NewID func() string
}
// PlaceOrder is scenario S1. Each numbered step maps to one arrow in the
// scenario diagram and to one element in the other four views.
func (s Service) PlaceOrder(ctx context.Context, customerID string, lines []Line) (Order, error) {
if len(lines) == 0 {
return Order{}, ErrEmptyOrder
}
o := Order{ID: s.NewID(), CustomerID: customerID, Lines: lines, Status: StatusPending, PlacedAt: s.Now()}
for _, l := range lines {
o.TotalCents += int64(l.Quantity) * l.PriceCents
}
// Step 2: reserve stock (logical: Inventory port; process: sync call).
if err := s.Inventory.Reserve(ctx, o.ID, lines); err != nil {
return Order{}, fmt.Errorf("reserve stock for %s: %w", o.ID, err)
}
// Step 3: authorize payment (process: sync call with a timeout budget).
if _, err := s.Payments.Authorize(ctx, o.ID, o.TotalCents); err != nil {
o.Status = StatusRejected
return o, fmt.Errorf("authorize payment for %s: %w", o.ID, err)
}
o.Status = StatusConfirmed
// Step 4: commit order + OrderPlaced event atomically (physical: one PostgreSQL primary).
payload := fmt.Appendf(nil, `{"order_id":%q,"total_cents":%d}`, o.ID, o.TotalCents)
if err := s.Store.SaveWithEvent(ctx, o, "OrderPlaced", payload); err != nil {
return Order{}, fmt.Errorf("save order %s: %w", o.ID, err)
}
return o, nil
}// Package payments is a separate module in the DEVELOPMENT view. In the
// monolith it runs in the same process; after a split it becomes its own
// deployable and only the adapter in cmd/ changes.
package payments
import (
"context"
"errors"
"fmt"
)
// ErrDeclined is returned when the payment provider declines the charge.
var ErrDeclined = errors.New("payments: declined")
// Authorizer talks to the external payment provider (a box outside the
// system boundary in the C4 context diagram).
type Authorizer struct {
LimitCents int64
}
// Authorize satisfies ordering.Payments without importing ordering:
// the dependency points from ordering's port to this implementation
// only in the composition root (cmd/orders-api).
func (a Authorizer) Authorize(_ context.Context, orderID string, cents int64) (string, error) {
if cents > a.LimitCents {
return "", fmt.Errorf("order %s for %d cents: %w", orderID, cents, ErrDeclined)
}
return "auth-" + orderID, nil
}مثال: نمای پردازه در کد
دو binary از یک ماژول یعنی دو پردازه. orders-api پردازهٔ درخواستمحور است با deadline برای هر درخواست و خاموشی آرام روی SIGTERM:
// Command orders-api is one PROCESS (and one container image in the
// PHYSICAL view). main is the composition root: the only place where the
// logical modules are wired to concrete adapters.
package main
import (
"context"
"encoding/json"
"errors"
"log/slog"
"net/http"
"os"
"os/signal"
"strconv"
"sync"
"syscall"
"time"
"academy/kruchten-4plus1-views/internal/ordering"
"academy/kruchten-4plus1-views/internal/payments"
)
// alwaysInStock stands in for the inventory module in this snippet.
type alwaysInStock struct{}
func (alwaysInStock) Reserve(context.Context, string, []ordering.Line) error { return nil }
// memStore stands in for PostgreSQL (orders + outbox tables in one transaction).
type memStore struct {
mu sync.Mutex
orders map[string]ordering.Order
outbox [][]byte
}
func (m *memStore) SaveWithEvent(_ context.Context, o ordering.Order, _ string, payload []byte) error {
m.mu.Lock()
defer m.mu.Unlock()
m.orders[o.ID] = o
m.outbox = append(m.outbox, payload)
return nil
}
func main() {
log := slog.New(slog.NewJSONHandler(os.Stdout, nil))
var seq int64
var seqMu sync.Mutex
svc := ordering.Service{
Inventory: alwaysInStock{},
Payments: payments.Authorizer{LimitCents: 500_000},
Store: &memStore{orders: map[string]ordering.Order{}},
Now: time.Now,
NewID: func() string {
seqMu.Lock()
defer seqMu.Unlock()
seq++
return "ord-" + strconv.FormatInt(seq, 10)
},
}
mux := http.NewServeMux()
// Readiness endpoint used by the PHYSICAL view (load balancer, Kubernetes probe).
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
})
mux.HandleFunc("POST /orders", func(w http.ResponseWriter, r *http.Request) {
var req struct {
CustomerID string `json:"customer_id"`
Lines []ordering.Line `json:"lines"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad json", http.StatusBadRequest)
return
}
// Process view: every request has a deadline that covers the sync calls.
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
o, err := svc.PlaceOrder(ctx, req.CustomerID, req.Lines)
switch {
case errors.Is(err, ordering.ErrEmptyOrder):
http.Error(w, err.Error(), http.StatusUnprocessableEntity)
return
case errors.Is(err, payments.ErrDeclined):
http.Error(w, err.Error(), http.StatusPaymentRequired)
return
case err != nil:
log.Error("place order", "err", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(o)
})
addr := ":" + envOr("PORT", "8080")
srv := &http.Server{Addr: addr, Handler: mux, ReadHeaderTimeout: 5 * time.Second}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go func() {
log.Info("orders-api listening", "addr", addr)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Error("listen", "err", err)
stop()
}
}()
<-ctx.Done()
// Graceful shutdown: Kubernetes sends SIGTERM before removing the pod.
shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_ = srv.Shutdown(shutdown)
}
func envOr(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}outbox-relay پردازهٔ دورهای است؛ حلقهٔ relay خودش در لایهٔ platform زندگی میکند:
// Package outbox is infrastructure shared by modules (bottom layer of the
// DEVELOPMENT view). The Relay type is what the PROCESS view calls the
// "outbox relay" task: a separate thread of control (its own process in
// production) that moves committed events to the broker.
package outbox
import (
"context"
"log/slog"
"time"
)
// Event is a row of the outbox table.
type Event struct {
ID int64
Type string
Payload []byte
}
// Source reads unpublished events and marks them as sent.
type Source interface {
Pending(ctx context.Context, limit int) ([]Event, error)
MarkSent(ctx context.Context, id int64) error
}
// Publisher sends one event to the broker (RabbitMQ, Kafka, ...).
type Publisher interface {
Publish(ctx context.Context, e Event) error
}
// Relay polls Source and publishes to Publisher (at-least-once delivery).
type Relay struct {
Source Source
Publisher Publisher
Interval time.Duration
Batch int
Log *slog.Logger
}
// Run blocks until ctx is cancelled. One Relay per database primary is enough;
// more replicas of this process need a lock (e.g. FOR UPDATE SKIP LOCKED).
func (r Relay) Run(ctx context.Context) error {
t := time.NewTicker(r.Interval)
defer t.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
r.tick(ctx)
}
}
}
func (r Relay) tick(ctx context.Context) {
events, err := r.Source.Pending(ctx, r.Batch)
if err != nil {
r.Log.Error("outbox read failed", "err", err)
return
}
for _, e := range events {
if err := r.Publisher.Publish(ctx, e); err != nil {
r.Log.Warn("publish failed, will retry", "id", e.ID, "err", err)
return
}
if err := r.Source.MarkSent(ctx, e.ID); err != nil {
r.Log.Error("mark sent failed", "id", e.ID, "err", err)
return
}
}
}// Command outbox-relay is a second PROCESS built from the same module.
// Same code base (development view), different thread of control (process
// view), different container and replica count (physical view).
package main
import (
"context"
"log/slog"
"os"
"os/signal"
"syscall"
"time"
"academy/kruchten-4plus1-views/internal/platform/outbox"
)
// emptySource stands in for "SELECT ... FROM outbox WHERE sent_at IS NULL".
type emptySource struct{}
func (emptySource) Pending(context.Context, int) ([]outbox.Event, error) { return nil, nil }
func (emptySource) MarkSent(context.Context, int64) error { return nil }
// logPublisher stands in for a RabbitMQ or Kafka producer.
type logPublisher struct{ log *slog.Logger }
func (p logPublisher) Publish(_ context.Context, e outbox.Event) error {
p.log.Info("published", "id", e.ID, "type", e.Type)
return nil
}
func main() {
log := slog.New(slog.NewJSONHandler(os.Stdout, nil))
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
r := outbox.Relay{
Source: emptySource{},
Publisher: logPublisher{log: log},
Interval: 500 * time.Millisecond,
Batch: 100,
Log: log,
}
log.Info("outbox-relay started")
if err := r.Run(ctx); err != nil && ctx.Err() == nil {
log.Error("relay stopped", "err", err)
os.Exit(1)
}
}مثال: نمای توسعه در کد
قاعدههای وابستگی بهشکل تست (جدول همان نمودار است)، و مولدی که گراف import را از کد منبع میکشد:
// Package archtest turns the DEVELOPMENT view's dependency rules into a
// test. The table below IS the development view diagram, in code: if a
// pull request adds an arrow the diagram does not allow, CI fails.
package archtest
import (
"go/parser"
"go/token"
"io/fs"
"path/filepath"
"strconv"
"strings"
"testing"
)
const module = "academy/kruchten-4plus1-views/"
// allowed lists, for each package, the module packages it may import.
var allowed = map[string][]string{
"internal/ordering": {},
"internal/payments": {},
"internal/platform/outbox": {},
"cmd/orders-api": {"internal/ordering", "internal/payments"},
"cmd/outbox-relay": {"internal/platform/outbox"},
"tools/viewgen": {},
"internal/archtest": {},
}
func TestDevelopmentViewRules(t *testing.T) {
root := filepath.Join("..", "..")
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() || !strings.HasSuffix(path, ".go") {
return err
}
rel, _ := filepath.Rel(root, filepath.Dir(path))
pkg := filepath.ToSlash(rel)
f, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly)
if err != nil {
return err
}
for _, imp := range f.Imports {
p, _ := strconv.Unquote(imp.Path.Value)
target, ok := strings.CutPrefix(p, module)
if !ok || target == pkg {
continue
}
if !contains(allowed[pkg], target) {
t.Errorf("%s imports %s: not allowed by the development view", path, target)
}
}
return nil
})
if err != nil {
t.Fatal(err)
}
}
func contains(list []string, s string) bool {
for _, x := range list {
if x == s {
return true
}
}
return false
}// Command viewgen GENERATES the development view from the source tree:
// it parses every .go file, collects imports between packages of this
// module and prints a Mermaid flowchart. Run it in CI and commit the
// output next to the hand-drawn views, so this one can never go stale.
//
// go run ./tools/viewgen . > docs/architecture/development-view.mmd
package main
import (
"fmt"
"go/parser"
"go/token"
"io/fs"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
)
func main() {
root := "."
if len(os.Args) > 1 {
root = os.Args[1]
}
module, err := modulePath(filepath.Join(root, "go.mod"))
if err != nil {
fmt.Fprintln(os.Stderr, "viewgen:", err)
os.Exit(1)
}
edges := map[string]bool{}
err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
return err
}
f, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly)
if err != nil {
return err
}
rel, _ := filepath.Rel(root, filepath.Dir(path))
from := filepath.ToSlash(rel)
for _, imp := range f.Imports {
p, _ := strconv.Unquote(imp.Path.Value)
if to, ok := strings.CutPrefix(p, module+"/"); ok {
edges[fmt.Sprintf(" %s --> %s", id(from), id(to))] = true
}
}
return nil
})
if err != nil {
fmt.Fprintln(os.Stderr, "viewgen:", err)
os.Exit(1)
}
lines := make([]string, 0, len(edges))
for e := range edges {
lines = append(lines, e)
}
sort.Strings(lines)
fmt.Println("flowchart TD")
fmt.Println(strings.Join(lines, "\n"))
}
func modulePath(gomod string) (string, error) {
b, err := os.ReadFile(gomod)
if err != nil {
return "", err
}
for _, line := range strings.Split(string(b), "\n") {
if m, ok := strings.CutPrefix(strings.TrimSpace(line), "module "); ok {
return strings.TrimSpace(m), nil
}
}
return "", fmt.Errorf("no module line in %s", gomod)
}
// id makes a Mermaid-safe node id that still reads like the path.
func id(pkg string) string {
return strings.NewReplacer("/", "_", "-", "_").Replace(pkg) + "[" + pkg + "]"
}اجرای آن روی همین ماژول چاپ میکند:
flowchart TD
cmd_orders_api[cmd/orders-api] --> internal_ordering[internal/ordering]
cmd_orders_api[cmd/orders-api] --> internal_payments[internal/payments]
cmd_outbox_relay[cmd/outbox-relay] --> internal_platform_outbox[internal/platform/outbox]مثال: سناریوها بهشکل تست
package ordering_test
import (
"context"
"errors"
"testing"
"time"
"academy/kruchten-4plus1-views/internal/ordering"
)
// The "+1" view as an executable artifact: each scenario from the
// architecture document is a test that walks the same steps.
type fakeInventory struct{ fail bool }
func (f fakeInventory) Reserve(context.Context, string, []ordering.Line) error {
if f.fail {
return ordering.ErrOutOfStock
}
return nil
}
var errDeclined = errors.New("declined")
type fakePayments struct {
calls int
decline bool
}
func (f *fakePayments) Authorize(context.Context, string, int64) (string, error) {
f.calls++
if f.decline {
return "", errDeclined
}
return "auth-1", nil
}
type memStore struct{ events []string }
func (m *memStore) SaveWithEvent(_ context.Context, _ ordering.Order, eventType string, _ []byte) error {
m.events = append(m.events, eventType)
return nil
}
func newService(inv ordering.Inventory, pay ordering.Payments, st ordering.Store) ordering.Service {
return ordering.Service{
Inventory: inv, Payments: pay, Store: st,
Now: func() time.Time { return time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC) },
NewID: func() string { return "ord-1" },
}
}
func TestScenarioS1PlaceOrderHappyPath(t *testing.T) {
pay, st := &fakePayments{}, &memStore{}
svc := newService(fakeInventory{}, pay, st)
o, err := svc.PlaceOrder(context.Background(), "cus-7", []ordering.Line{{SKU: "BOOK-1", Quantity: 2, PriceCents: 1500}})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if o.Status != ordering.StatusConfirmed || o.TotalCents != 3000 {
t.Fatalf("got status %s total %d", o.Status, o.TotalCents)
}
if len(st.events) != 1 || st.events[0] != "OrderPlaced" {
t.Fatalf("outbox events = %v, want [OrderPlaced]", st.events)
}
}
func TestScenarioS2OutOfStockNeverCharges(t *testing.T) {
pay, st := &fakePayments{}, &memStore{}
svc := newService(fakeInventory{fail: true}, pay, st)
_, err := svc.PlaceOrder(context.Background(), "cus-7", []ordering.Line{{SKU: "BOOK-1", Quantity: 1, PriceCents: 1500}})
if !errors.Is(err, ordering.ErrOutOfStock) {
t.Fatalf("err = %v, want ErrOutOfStock", err)
}
if pay.calls != 0 || len(st.events) != 0 {
t.Fatalf("payment calls %d, events %v: a rejected order must not charge or publish", pay.calls, st.events)
}
}
func TestScenarioS3PaymentDeclinedWritesNothing(t *testing.T) {
pay, st := &fakePayments{decline: true}, &memStore{}
svc := newService(fakeInventory{}, pay, st)
o, err := svc.PlaceOrder(context.Background(), "cus-7", []ordering.Line{{SKU: "BOOK-1", Quantity: 1, PriceCents: 1500}})
if !errors.Is(err, errDeclined) {
t.Fatalf("err = %v, want the payment error", err)
}
if o.Status != ordering.StatusRejected || len(st.events) != 0 {
t.Fatalf("status %s, events %v: a declined order is rejected and publishes nothing", o.Status, st.events)
}
}نگاه Go
| نما | سازوکار Go | نکته |
|---|---|---|
| منطقی | package همان ماژول نمای منطقی است؛ interfaceهای کوچک را مصرفکننده تعریف میکند | portها کنار use case میمانند |
| پردازه | برای هر پوشهٔ cmd/ یک binary؛ goroutineها همان minor taskهای Kruchtenاند؛ context.Context deadline را حمل میکند | signal.NotifyContext + Server.Shutdown برای توقف تمیز |
| توسعه | visibility پوشهٔ internal/ را کامپایلر اعمال میکند؛ go list و go/parser برای تولید گراف | راهنمای چیدمان ماژولهای Go استفاده از internal را برای packageهایی توصیه میکند که نمیخواهید دیگران به آنها وابسته شوند |
| فیزیکی | binary ایستا (CGO_ENABLED=0) در imageهای کوچک (distroless) | یک image در همهٔ محیطها؛ توپولوژی از manifestها |
| سناریوها | go test با fake برای portها؛ httptest برای لایهٔ HTTP | نام تستها را از شناسهٔ سناریو بگیرید |
Laravel
Laravel 13 روی PHP 8.4. کد زیر بازبینی شده، نه اجرا (روی ماشین build، PHP نصب نیست). همان نماها، همان سناریوها.
مثال: نمای منطقی در کد
<?php
declare(strict_types=1);
namespace App\Modules\Ordering\Domain;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* LOGICAL view: the Order aggregate. Status is a small state machine;
* money is integer cents.
*
* @property string $id
* @property string $customer_id
* @property int $total_cents
* @property OrderStatus $status
*/
#[Table('orders', keyType: 'string', incrementing: false)]
#[Fillable(['id', 'customer_id', 'total_cents', 'status'])]
final class Order extends Model
{
protected function casts(): array
{
return ['status' => OrderStatus::class, 'total_cents' => 'integer'];
}
public function lines(): HasMany
{
return $this->hasMany(OrderLine::class, 'order_id');
}
public function confirm(): void
{
if ($this->status !== OrderStatus::Pending) {
throw new \DomainException("Order {$this->id} is {$this->status->value}, cannot confirm");
}
$this->status = OrderStatus::Confirmed;
}
}<?php
declare(strict_types=1);
namespace App\Modules\Ordering\Domain;
enum OrderStatus: string
{
case Pending = 'pending';
case Confirmed = 'confirmed';
case Rejected = 'rejected';
case Shipped = 'shipped';
}<?php
declare(strict_types=1);
namespace App\Modules\Ordering\Domain;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
/**
* @property string $order_id
* @property string $sku
* @property int $quantity
* @property int $price_cents
*
* Composite primary key (order_id, sku) in the DDL, so no auto-increment id.
*/
#[Table('order_lines', incrementing: false, timestamps: false)]
#[Fillable(['order_id', 'sku', 'quantity', 'price_cents'])]
final class OrderLine extends Model
{
}<?php
declare(strict_types=1);
namespace App\Modules\Ordering\Application;
use App\Modules\Ordering\Domain\Order;
use App\Modules\Ordering\Domain\OrderStatus;
use App\Modules\Payments\Api\PaymentsApi;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
/**
* Scenario S1 "place order" as an application service. The numbered
* comments are the steps of the scenario diagram.
*/
final class PlaceOrder
{
public function __construct(private readonly PaymentsApi $payments)
{
}
/** @param list<array{sku: string, quantity: int, price_cents: int}> $lines */
public function handle(string $customerId, array $lines): Order
{
if ($lines === []) {
throw new \InvalidArgumentException('Order has no lines');
}
$orderId = (string) Str::ulid();
$total = array_sum(array_map(fn (array $l): int => $l['quantity'] * $l['price_cents'], $lines));
// Step 3: synchronous payment authorization (outside the DB transaction).
$this->payments->authorize($orderId, $total);
// Step 4: order, lines and the OrderPlaced event in ONE transaction (outbox).
return DB::transaction(function () use ($orderId, $customerId, $lines, $total): Order {
$order = Order::create([
'id' => $orderId,
'customer_id' => $customerId,
'total_cents' => $total,
'status' => OrderStatus::Pending,
]);
$order->lines()->createMany($lines);
$order->confirm();
$order->save();
DB::table('outbox')->insert([
'type' => 'OrderPlaced',
'payload' => json_encode(['order_id' => $orderId, 'total_cents' => $total]),
'created_at' => now(),
]);
return $order;
});
}
}<?php
declare(strict_types=1);
namespace App\Modules\Payments\Api;
/**
* The ONLY door into the payments module (development view rule:
* other modules may use Payments\Api, never Payments\Internal).
*/
interface PaymentsApi
{
/** @throws PaymentDeclined */
public function authorize(string $orderId, int $amountCents): string;
}<?php
declare(strict_types=1);
namespace App\Modules\Payments\Api;
final class PaymentDeclined extends \RuntimeException
{
}مثال: نمای پردازه در کد
فراخوانی پرداخت درون پردازهٔ وب همگام است، پس timeout، retry محدود و کلید idempotency دارد:
<?php
declare(strict_types=1);
namespace App\Modules\Payments\Internal;
use App\Modules\Payments\Api\PaymentDeclined;
use App\Modules\Payments\Api\PaymentsApi;
use Illuminate\Support\Facades\Http;
/**
* Talks to the external payment provider. In the PROCESS view this is a
* synchronous call inside the web request, so it gets a hard timeout.
*/
final class HttpPaymentsGateway implements PaymentsApi
{
public function __construct(private readonly string $baseUrl, private readonly string $token)
{
}
public function authorize(string $orderId, int $amountCents): string
{
$response = Http::baseUrl($this->baseUrl)
->withToken($this->token)
->timeout(2)
->retry(2, 100, throw: false)
->withHeaders(['Idempotency-Key' => "order-{$orderId}"])
->post('/authorizations', ['reference' => $orderId, 'amount' => $amountCents]);
if ($response->status() === 402) {
throw new PaymentDeclined("Payment for order {$orderId} declined");
}
$response->throw();
return (string) $response->json('id');
}
}relay در یک پردازهٔ queue worker اجرا میشود و پردازهٔ scheduler آن را زمانبندی میکند:
<?php
declare(strict_types=1);
namespace App\Modules\Ordering\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
/**
* PROCESS view: runs in a queue worker process (php artisan queue:work),
* not in the web process. Scheduled every few seconds by the scheduler
* process (php artisan schedule:work).
*/
final class RelayOutbox implements ShouldQueue
{
use Queueable;
public int $tries = 3;
public function handle(): void
{
DB::transaction(function (): void {
$rows = DB::table('outbox')
->whereNull('sent_at')
->orderBy('id')
->limit(100)
->lockForUpdate() // a second worker waits instead of double-publishing
->get();
foreach ($rows as $row) {
// At-least-once: consumers must be idempotent on order_id.
Redis::xadd('events:orders', '*', ['type' => $row->type, 'payload' => $row->payload]);
DB::table('outbox')->where('id', $row->id)->update(['sent_at' => now()]);
}
});
}
}<?php
use App\Modules\Ordering\Jobs\RelayOutbox;
use Illuminate\Support\Facades\Schedule;
// PROCESS view: the scheduler process enqueues the relay; a worker runs it.
Schedule::job(new RelayOutbox)->everyFiveSeconds();مثال: نمای توسعه در کد
هر ماژول خودش را ثبت میکند؛ فهرست providerها همان فهرست ماژولهای نمای توسعه است:
<?php
// DEVELOPMENT view: each module registers itself through one provider.
return [
App\Providers\AppServiceProvider::class,
App\Modules\Ordering\OrderingServiceProvider::class,
App\Modules\Payments\PaymentsServiceProvider::class,
];<?php
declare(strict_types=1);
namespace App\Modules\Payments;
use App\Modules\Payments\Api\PaymentsApi;
use App\Modules\Payments\Internal\HttpPaymentsGateway;
use Illuminate\Support\ServiceProvider;
final class PaymentsServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->singleton(PaymentsApi::class, fn (): PaymentsApi => new HttpPaymentsGateway(
(string) config('services.payments.url'),
(string) config('services.payments.token'),
));
}
}<?php
declare(strict_types=1);
namespace App\Modules\Ordering;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;
final class OrderingServiceProvider extends ServiceProvider
{
public function boot(): void
{
$this->loadMigrationsFrom(__DIR__.'/database/migrations');
Route::middleware('api')->prefix('api')->group(__DIR__.'/routes.php');
}
}قاعدهها بهشکل تست معماری Pest:
<?php
// DEVELOPMENT view rules as Pest architecture tests
// (https://pestphp.com/docs/arch-testing). The diagram says "ordering
// uses payments only through Payments\Api"; this file makes it true.
arch('ordering uses payments only through its API')
->expect('App\Modules\Ordering')
->not->toUse('App\Modules\Payments\Internal');
arch('payments does not know ordering')
->expect('App\Modules\Payments')
->not->toUse('App\Modules\Ordering');
arch('payments internals stay inside payments')
->expect('App\Modules\Payments\Internal')
->toOnlyBeUsedIn('App\Modules\Payments');
arch('domain code does not touch HTTP')
->expect('App\Modules\Ordering\Domain')
->not->toUse(['Illuminate\Http', 'Illuminate\Support\Facades\Http']);مثال: نمای فیزیکی در کد
یک image (image رسمی FrankenPHP با install-php-extensions)، چند پردازه که با command انتخاب میشوند:
# PHYSICAL view as code: ONE image, three processes (web, worker, scheduler)
# chosen by the command in compose.yaml or the Kubernetes manifest.
FROM composer:2 AS vendor
WORKDIR /app
COPY composer.json composer.lock ./
RUN composer install --no-dev --no-scripts --prefer-dist --no-interaction
FROM dunglas/frankenphp:php8.4
RUN install-php-extensions pdo_pgsql redis pcntl opcache
WORKDIR /app
COPY . /app
COPY --from=vendor /app/vendor /app/vendor
RUN php artisan route:cache && php artisan view:cache
EXPOSE 8000
# config:cache needs the runtime environment (.env / env vars), so it runs at start.
CMD ["sh", "-c", "php artisan config:cache && exec php artisan octane:frankenphp --host=0.0.0.0 --port=8000"]مثال: سناریوها بهشکل تست
<?php
// SCENARIO view as tests: S1 (happy path) and S3 (payment declined).
use App\Modules\Ordering\Application\PlaceOrder;
use App\Modules\Payments\Api\PaymentDeclined;
use App\Modules\Payments\Api\PaymentsApi;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
uses(Tests\TestCase::class, RefreshDatabase::class);
it('S1: places an order and writes OrderPlaced to the outbox', function () {
$this->app->instance(PaymentsApi::class, new class implements PaymentsApi {
public function authorize(string $orderId, int $amountCents): string
{
return 'auth-1';
}
});
$order = app(PlaceOrder::class)->handle('cus-7', [
['sku' => 'BOOK-1', 'quantity' => 2, 'price_cents' => 1500],
]);
expect($order->total_cents)->toBe(3000)
->and($order->status->value)->toBe('confirmed')
->and(DB::table('outbox')->where('type', 'OrderPlaced')->count())->toBe(1);
});
it('S3: a declined payment leaves no order and no event', function () {
$this->app->instance(PaymentsApi::class, new class implements PaymentsApi {
public function authorize(string $orderId, int $amountCents): string
{
throw new PaymentDeclined('declined');
}
});
expect(fn () => app(PlaceOrder::class)->handle('cus-7', [
['sku' => 'BOOK-1', 'quantity' => 1, 'price_cents' => 1500],
]))->toThrow(PaymentDeclined::class);
expect(DB::table('orders')->count())->toBe(0)
->and(DB::table('outbox')->count())->toBe(0);
});نگاه Laravel
| نما | سازوکار Laravel | نکته |
|---|---|---|
| منطقی | مدلهای Eloquent با cast به enum بهعنوان state machine؛ کلاسهای Action و use case؛ قراردادها در Api/ | HTTP را بیرون از Domain/ نگه دارید (قاعدهٔ Pest) |
| پردازه | Web (workerهای PHP-FPM یا Octane)، queue:work، schedule:work؛ jobهای ShouldQueue؛ Http::timeout()->retry() | Octane اپ را در حافظه نگه میدارد: state درخواست در singleton نه |
| توسعه | app/Modules/<Name> + یک service provider برای هر کدام، فهرستشده در bootstrap/providers.php؛ arch() در Pest؛ layerهای Deptrac | PHP پوشهٔ Internal/ را اعمال نمیکند؛ تستها میکنند |
| فیزیکی | یک image، سه command؛ مسیر سلامت /up (health check پیشفرض Laravel) برای probeها | مستندات Laravel: مسیر سلامت را میشود برای "an uptime monitor, load balancer, or orchestration system such as Kubernetes" به کار برد |
| سناریوها | feature testهای Pest با RefreshDatabase، fake در container با $this->app->instance() | برای هر شناسهٔ سناریو یک تست |
حل مسئلههای کلاسیک
سه ضدالگوی مستندسازی (Anti-patterns) مدام تکرار میشوند (one giant diagram، views that nobody reads، stale views)، بهعلاوهٔ دو ضدالگوی طراحی که نماها آشکارشان میکنند.
یک نمودار غولآسا
ضدالگویی که هم Kruchten و هم Rozanski و Woods با آن شروع میکنند: یک برگه که کد، پردازه، سرور و مفهوم کسبوکار را قاطی میکند. Rozanski و Woods: "a monolithic AD is often incomplete, incorrect, or out-of-date".
| راهحل | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|
| شکستن بر اساس نما | برای هر دغدغه یک نمودار، هر کدام با راهنما | هر مخاطب یک تصویر کوچک میخواند | جدول تناظر لازم است |
| سطحهای بزرگنمایی C4 | Context، سپس container، سپس component؛ هرگز قاطی نه | توسعهدهندهها از قبل میشناسندش | جزئیات پردازه و فیزیکی نمودار اضافه میخواهد |
| چکلیست بازبینی نمودار | عنوان، نوع، دامنه، راهنما، فلش برچسبدار (چکلیست C4) | ارزان، بیشتر ابهامها را میگیرد | انضباط در بازبینی |
نماهایی که کسی نمیخواند
| راهحل | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|
| شروع از ذینفعان | جدول ذینفع/نمای V&B؛ خانههای «none» را حذف کنید | هر نما خواننده دارد | یک کارگاه برای هر سیستم |
| پاسخ به پرسش، نه پر کردن قالب | هر نما با ۳ تا ۵ پرسشی که پاسخ میدهد شروع شود | خواننده نما را با پرسش خودش پیدا میکند | پرسشها هم نگهداری میخواهند |
| نما را جایی بگذارید که مردم کار میکنند | Markdown در مخزن، پیوند از README و runbookها | در code review و حادثه خوانده میشود | از ابزار wiki کمزرقوبرقتر |
| حذف نمای بیمالک | هر فایل تیم مالکش را نام میبرد | مجموعهٔ کوچکتر و قابل اعتماد | «همهچیز را مستند کن» سختتر میشود |
نماهای کهنه
| راهحل | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|
| تولید از کد | viewgen، گراف Deptrac، dump از schema | نمیتواند فاصله بگیرد | تصویر تولیدی کمتر گزیده است |
| تولید از زیرساخت بهشکل کد | نمودار از Compose، Kubernetes، Terraform | نمای فیزیکی برابر واقعیت است | ابزار برای هر سکو |
| قاعدههای اجرایی | archtest، arch() در Pest | فاصله گرفتن build را میشکند | فقط برای قاعدههایی که بیانپذیرند |
| نمودار بهشکل کد، بازبینی همراه کد | Mermaid، PlantUML، Structurizr در PR | بازبینی ناهمخوانی را میگیرد | باز هم آدم باید متوجه شود |
| تاریخ و نسخه برای هر نما | «استقرار production، تا ۲۰۲۶-۱۱» | خواننده میداند چقدر اعتماد کند | دستی |
نمای پردازهٔ غایب
تیمها برای سرویسها جعبه میکشند و زمان اجرا را جا میاندازند، بعد در production یک زنجیرهٔ ششتایی از فراخوانیهای همگام کشف میکنند.
| راهحل | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|
| یک sequence برای هر سناریوی حیاتی | S1 را با timeout روی هر فلش بکشید | بودجهٔ تأخیر و حالتهای شکست را نشان میدهد | یک نمودار برای هر سناریو |
| جدول اتصالدهندهها | برای هر فلش: همگام یا ناهمگام، timeout، retry، idempotency | فهرستی قابل بازبینی | باید کنار کد نگه داشته شود |
| prototype توخالی | «dummy loads» حرف Kruchten؛ امروز: stub + load test | اندازهگیری پیش از ساختن | تلاش در ابتدای کار |
نمای منطقی چسبیده به استقرار
| راهحل | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|
| portهایی که مالکشان use case است | interface به نام ordering.Payments؛ adapterها در cmd/ | یک ماژول را بدون دست زدن به منطق به سرویس تبدیل کنید | یک لایهٔ غیرمستقیم بیشتر |
| قاعدهٔ هممکانی Kruchten | major taskها "shall not make assumptions about their collocation" | همان کد در یک پردازه یا چند پردازه اجرا میشود | باید شکستهای راه دور را همهجا مدیریت کنید |
| نگاشت دادهمحور | توپولوژی در manifest و متغیر محیطی، نه در کد | چند نمای فیزیکی، یک پایهٔ کد | پیکربندی بیشتر |
انتخاب: کدام نماها، چقدر
| موقعیت | نماهایی که بنویسید | عمق | دلیل |
|---|---|---|---|
| Prototype، یک توسعهدهنده، یک پردازه | سناریوها + طرح نمای منطقی | عکس وایتبرد | Kruchten: سیستمهای کوچک میتوانند منطقی و توسعه را یکی کنند؛ سناریوها همیشه مفیدند |
| Monolith در Laravel یا Go، یک تیم | منطقی + توسعه + ۲ تا ۳ سناریو؛ فیزیکی در یک خط | نقشهٔ ماژول، قاعدههای وابستگی | ریسک اصلی سازماندهی کد است |
| Modular monolith، چند تیم | منطقی + توسعه (مفصل) + پردازه (web و workerها) + سناریوها | قاعده بهشکل تست، CODEOWNERS | مرز تیمها در نمای توسعه زندگی میکند |
| Microservices | پردازه + فیزیکی (مفصل)، منطقی برای هر سرویس، سناریوهای میانسرویسی | sequence برای هر سناریو، deployment برای هر محیط | شکستها میان پردازهها و nodeها زندگی میکنند |
| چند region / دادهٔ توزیعشده | فیزیکی برای هر region + مسیرهای replication، پردازه با یادداشت سازگاری، سناریو بهشکل تمرین شکست | runbookهای failover پیوندخورده | partition و lag درستی را تعیین میکنند |
| حوزهٔ تحت مقررات یا ایمنیمحور | توصیف کامل به سبک 42010، همهٔ نماها، دلیل برای هر تصمیم | بازبینی رسمی | ممیزها ردیابیپذیری میخواهند |
| خط محصول / white-label | اول نمای توسعه (لایههای مشترک در برابر لایهٔ محصول) | قاعدههای لایه | Kruchten: "the basis for establishing a line-of-product" |
| مستندات ورود نیروی تازه (Onboarding) | context و container در C4 + نمای توسعه | مرور کلی | تازهواردها «چه چیزی کجاست» را لازم دارند |
در معماری: از یک پردازه تا سیستم توزیعشده
این جدول قضاوت ماست، لنگرانداخته روی قاعدهٔ تنظیم (Tailoring) Kruchten: "Views that are useless can be omitted from the architecture description, such as the physical view, if there is only one processor, and the process view if there is only process or program. For very small system, it is even possible that the logical view and the development view are so similar that they do not require separate descriptions. The scenarios are useful in all circumstances."
Monolith: یک پردازه، یک دیتابیس
مثال ساده: یک فروشگاه Laravel روی یک VM با PHP-FPM، MySQL و یک صف Redis. نمای منطقی: پنج ماژول در یک صفحه. نمای توسعه: پوشهها و قاعدهٔ «controller، action را صدا میزند؛ action، model را». نمای پردازه: یک خط («web + یک queue worker + cron»). نمای فیزیکی: یک جعبه. سناریوها: S1 و S3 بهشکل feature test.
مثال production: یک layered monolith با ۳۰۰ هزار خط و ۲۵ توسعهدهنده. نمای منطقی و نمای توسعه شروع به فاصله گرفتن میکنند (shared kernel، ابزارها)، پس نمای توسعه ابزار اصلی برای معقول نگه داشتن بار build و بازبینی میشود. نمای پردازه از لحظهای بزرگ میشود که workerهای Octane (حافظهٔ مشترک میان درخواستها) یا صف دوم اضافه کنید.
Modular monolith و چند دیتابیس
مثال ساده: ماژول Go همین صفحه: یک binary برای API، یکی برای relay، ماژولها زیر internal/ با قاعدهها در archtest. ماژول منطقی = ماژول توسعه = تیم مالک.
مثال production: یک modular monolith که هر ماژولش مالک schema خودش است (schema یا دیتابیس جدا در PostgreSQL). حالا نمای منطقی باید مالکیت داده را نشان دهد، نمای توسعه باید دسترسی میانماژولی به جدولها را ممنوع کند (قاعدهٔ Pest که Ordering هرگز Payments\Internal را استفاده نکند، و برای هر ماژول یک نقش دیتابیس)، و نمای پردازه رویدادهای درونپردازهای و برای هر ماژول یک outbox پیدا میکند. جدول تناظر نقشهٔ راه هر جداسازی آینده میشود.
Microservices: نمای پردازه و فیزیکی غالب میشوند
مثال ساده: Payments به سرویس جدایی تبدیل میشود. نمای منطقی تقریباً عوض نمیشود (port به نام PaymentsApi میماند)؛ نمای توسعه یک مخزن و یک package برای client اضافه میکند؛ نمای پردازه یک فلش شبکه با timeout، retry و کلید idempotency پیدا میکند؛ نمای فیزیکی podها، یک Service و یک network policy میگیرد.
مثال production: چهل سرویس. حالا نمای پردازه حیاتی است: زنجیرههای همگام، fan-out، saga برای گردشکارهای چندمرحلهای، outbox برای رویدادها، consumer idempotent، API gateway و service mesh. نمای فیزیکی از manifestها تولید میشود و zoneها، meshها و خروجی شبکه را نشان میدهد. نمای توسعه بیشتر مرز تیمها و قانون Conway است. سناریوها از سرویسها عبور میکنند و به contract test و trace توزیعشده تبدیل میشوند.
S1 after the split (microservices) View that changed
1 gateway -> orders (HTTP) Process: new hop, auth at the edge
2 orders -> inventory (gRPC, 300 ms timeout) Process: remote call replaces in-process call
3 orders -> payments (HTTP, idempotency key, 2 retries) Process + physical (egress)
4 orders commits order + outbox Same (logical unchanged)
5 relay -> Kafka topic orders.events (key = order_id) Process: ordering per key
6 shipping consumes, saga step "create shipment" Process: compensation if carrier rejectsدادهٔ توزیعشده: replicaها، cacheها و چند region
حالا نمای فیزیکی درستی را حمل میکند، نه فقط ظرفیت را. مسیرهای replication و lag را بکشید؛ علامت بزنید کدام خواندنها میتوانند به replica بروند (به replication و failover نگاه کنید)، cacheها کجا نشستهاند و چطور باطل میشوند، کدام داده باید در کدام region بماند. نمای پردازه مدل سازگاری را برای هر فلش اضافه میکند («read-your-writes پس از checkout: تا ۵ ثانیه از primary بخوان»). سناریوها به تمرین شکست تبدیل میشوند: تخلیهٔ region، lag سیثانیهای replica، cache stampede.
| دغدغه | نمایی که باید نشانش دهد | یادداشت نمونه |
|---|---|---|
| Lag در replica | فیزیکی + پردازه | «تاریخچهٔ سفارش از replica؛ تأیید checkout از primary» |
| جای cache | فیزیکی + پردازه | «Catalog در Redis، TTL شصت ثانیه، با رویداد تغییر قیمت باطل میشود» |
| اقامت داده | فیزیکی | «سفارشهای مشتریان اروپایی فقط در eu-central-1 و eu-west-1» |
| Failover | فیزیکی + سناریوها | «ارتقای standby زیر ۶۰ ثانیه، هر فصل تمرین میشود» |
| سازگاری میان سرویسها | پردازه + سناریوها | «Inventory در نهایت سازگار؛ فروش بیش از موجودی با جبران (compensation) مدیریت میشود» |
مسیر مقیاس: ۱×، ۱۰×، ۱۰۰×
| بار | چه چیزی عوض میشود | کدام نماها عوض میشوند |
|---|---|---|
| 1× (۲۰ سفارش در ثانیه) | یک VM یا یک cluster کوچک؛ سناریوها بهشکل تست | فیزیکی = یک جعبه؛ پردازه = web + worker |
| 10× (۲۰۰ سفارش در ثانیه) | replicaها، read replica، broker، relay | پردازه (پردازههای تازه)، فیزیکی (replica، zone) |
| 100× (۲۰۰۰ سفارش در ثانیه) | جدا کردن ماژولهای داغ به سرویس، partition کردن topicها با order_id، shard یا رفتن به distributed SQL | پردازه و فیزیکی غالباند؛ توسعه مخزنها را جدا میکند؛ اگر portها درست بودند منطقی پایدار میماند |
آزمایشگاه: مستندسازی یک سیستم در 4+1 و صادق نگه داشتنش
پیشنیاز: Go 1.24 یا بالاتر، Docker با Compose v2. پوشهٔ docs/snippets/architecture/kruchten-4plus1-views/ را در یک پوشهٔ کاری کپی کنید.
- سناریوها و قاعدههای نمای توسعه را اجرا کنید.
cd go
go vet ./... && go test ./...
# ok academy/kruchten-4plus1-views/internal/archtest
# ok academy/kruchten-4plus1-views/internal/ordering- نمای توسعه را عمداً بشکنید و شکست build را ببینید.
printf 'package ordering\n\nimport _ "academy/kruchten-4plus1-views/internal/payments"\n' > internal/ordering/zz_violation.go
go test ./internal/archtest/
# --- FAIL: TestDevelopmentViewRules
# ../../internal/ordering/zz_violation.go imports internal/payments: not allowed by the development view
rm internal/ordering/zz_violation.go- نمای توسعه را تولید کنید و در هر renderer مربوط به Mermaid بچسبانید.
go run ./tools/viewgen .
# flowchart TD
# cmd_orders_api[cmd/orders-api] --> internal_ordering[internal/ordering]
# ...- نمای فیزیکی لپتاپ را بالا بیاورید و سناریوی S1 را دستی طی کنید.
cd ../deploy && docker compose up -d --build
curl -s -X POST localhost:8080/orders -d '{"customer_id":"cus-7","lines":[{"SKU":"BOOK-1","Quantity":2,"PriceCents":1500}]}'
# {"ID":"ord-1","CustomerID":"cus-7",...,"TotalCents":3000,"Status":"confirmed",...}
curl -s -o /dev/null -w '%{http_code}\n' localhost:8080/healthz # 200
docker compose down -v4+1 سیستم خودتان را بنویسید، هر نما در یک صفحه. برای سیستمی که میشناسید: ذینفعان و دغدغهها را فهرست کنید؛ چهار نما را بکشید (هر کدام با راهنما)؛ سه سناریو بهشکل script شمارهدار بنویسید؛ جدول تناظر را پر کنید؛ برای هر نما منبع حقیقتش را علامت بزنید. سقف زمان: دو ساعت.
کهنگی را اندازه بگیرید. برای هر نمودار موجود در wiki تیم، تاریخ آخرین ویرایش را ثبت کنید و با آخرین تغییر کد یا manifestی که توصیف میکند مقایسه کنید. هر چیزی قدیمیتر از آخرین تغییر ساختاری یک یافته است.
چکلیست مستندسازی
| بررسی | وقتی قبول است که |
|---|---|
| ذینفعان و دغدغهها فهرست شدهاند | هر نما میگوید چه کسی آن را میخواند و به چه پرسشهایی پاسخ میدهد |
| هر نمودار عنوان، نوع، دامنه و راهنما دارد | چکلیست C4: راهنما برای شکل، رنگ، نوع خط و فلش |
| هر فلش برچسب دارد | قصد و در صورت لزوم پروتکل یا فناوری |
| نمای منطقی | پنج تا نه ماژول؛ هر کدام با یک مالک و دادهٔ خودش |
| نمای پردازه | هر فلش میانپردازهای: همگام یا ناهمگام، timeout، retry، idempotency |
| نمای توسعه | قاعدههای وابستگی نوشته شده و با تست اعمال میشوند |
| نمای فیزیکی | برای هر محیط یک نمودار؛ replica، zone، انبار داده، failover |
| سناریوها | سه تا شش، انتخابشده بر پایهٔ ریسک؛ هر کدام پیوندخورده به یک تست یا تمرین |
| تناظر | جدولی ماژولها را به پردازهها و پردازهها را به nodeها نگاشت میکند |
| دلیلها | هر انتخاب مهم به یک ADR پیوند دارد |
| تازگی | هر نما تاریخ دارد یا در CI تولید میشود |
| مکان | نماها در مخزن زندگی میکنند و از README پیوند دارند |
بدفهمیهای رایج
| باور | واقعیت |
|---|---|
| «4+1 برای هر سیستم پنج نمودار میخواهد» | Kruchten: نماهایی "that are useless can be omitted"؛ فقط سناریوها همیشه میمانند |
| «نمای منطقی همان class diagram تولیدشده است» | فقط انتزاعهای مهم از نظر معماری را نشان میدهد؛ برای یک سیستم بزرگ چند ده class |
| «نمای پردازه همان فرایند کسبوکار است» | دربارهٔ thread of control، همروندی و توزیع است |
| «نمای منطقی و توسعه یک چیزند» | نزدیکاند، اما "the larger the project, the greater the distance between these views" |
| «فقط یک نمای فیزیکی وجود دارد» | برای هر محیط یکی: لپتاپ، staging، production، هر سایت مشتری |
| «سناریوها کاتالوگ کامل use caseها هستند» | مجموعهای کوچک که بر پایهٔ اهمیت، تکرار و ریسک فنی انتخاب شده |
| «4+1 یعنی UML» | مقالهٔ ۱۹۹۵ نمادگذاری Booch را به کار برد؛ نگاشت به UML بعدتر آمد |
| «C4 جای 4+1 را گرفت» | C4 میگوید "inspired by UML and the 4+1 model" بوده؛ ساختار ایستا را پوشش میدهد و deployment و dynamic نمودار پشتیباناند |
| «container در C4 همان container داکر است» | "Not Docker!": یک اپلیکیشن یا یک انبار داده |
| «ISO 42010 تعیین میکند کدام نماها را بکشیم» | تعیین میکند نماها را چطور انتخاب و توصیف کنیم (viewpoint از روی دغدغه)؛ 4+1 یک چارچوب است |
| «امنیت نمای خودش را لازم دارد» | Rozanski و Woods: کیفیتها perspectiveهاییاند که روی همهٔ نماها اعمال میشوند |
| «مستندات بعد از معماری نوشته میشود» | Kruchten و V&B: نماها هنگام طراحی ساخته میشوند؛ سناریوها طراحی را میرانند |
| «نمودارهای تولیدی نماهای دستکش را بیمصرف میکنند» | مولدها آنچه هست را نشان میدهند؛ نمای منطقی و دلیلها همچنان آدم میخواهند |
چکیده (Cheat sheet)
| موضوع | به خاطر بسپارید |
|---|---|
| منطقی (Logical) | کارکرد؛ انتزاعهای کلیدی؛ کاربران نهایی؛ class، state، E-R |
| پردازه (Process) | کارایی، دسترسپذیری، یکپارچگی؛ task و process؛ همگام در برابر ناهمگام؛ timeout |
| توسعه (Development) | سازماندهی، استفادهٔ دوباره، قابلیت حمل؛ ماژول، لایه (۴ تا ۶)، قاعدهٔ visibility؛ تیمها |
| فیزیکی (Physical) | دسترسپذیری، مقیاسپذیری؛ nodeها؛ برای هر محیط یک نمودار |
| سناریوها (Scenarios) | «+1» زائد؛ اول کشف را میرانند، بعد اعتبارسنجی میکنند؛ script؛ تست |
| تنظیم (Tailoring) | با یک پردازنده فیزیکی را حذف کن، با یک پردازه نمای پردازه را؛ سناریوها را نگه دار |
| تناظر | inside-out از منطقی، outside-in از فیزیکی؛ class، سپس module، سپس process، سپس node |
| ISO 42010 | Stakeholder، concern، viewpoint، view، model (در ۲۰۲۲ view component) |
| Views and Beyond | module، C&C، allocation؛ نماها + اطلاعات فراتر از نماها |
| C4 | context + container برای همه؛ component فقط اگر مفید است؛ deployment؛ dynamic با صرفهجویی |
| arc42 | ۵ building block، ۶ runtime، ۷ deployment |
| همگام نگه داشتن | نمودار بهشکل کد، تولید از کد و IaC، قاعده بهشکل تست، سناریو بهشکل تست |
| مقیاس | Monolith: منطقی + توسعه؛ microservices: پردازه + فیزیکی؛ توزیعشده: فیزیکی + سناریوهای شکست |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — چهار نما و «+1» را نام ببرید و برای هر کدام یک ذینفع و یک دغدغه از جدول Kruchten بگویید. مهم
پاسخ
پاسخ: منطقی: کاربر نهایی، کارکرد. پردازه: طراح سیستم و یکپارچهساز؛ کارایی، دسترسپذیری، تحمل خطا، یکپارچگی. توسعه: توسعهدهنده و مدیر؛ سازماندهی، استفادهٔ دوباره، قابلیت حمل، خط محصول. فیزیکی: طراح سیستم؛ مقیاسپذیری، کارایی، دسترسپذیری. سناریوها: کاربر نهایی و توسعهدهنده؛ فهمپذیری.
۲ — چرا Kruchten نمای سناریوها را «زائد» میخواند و چرا باز هم نگهش میدارد؟ تکمیلی
پاسخ
پاسخ: هر عنصری که در یک سناریو هست از قبل در یکی از چهار نما آمده، پس عنصر تازهای اضافه نمیکند. نگهش میدارد چون هنگام طراحی کشف عنصرهای معماری را میراند و بعد از طراحی آن را اعتبارسنجی میکند، هم روی کاغذ و هم بهعنوان نقطهٔ شروع تست prototype معماری.
۳ — سیستم شما یک اپ Laravel روی یک سرور و بدون صف است. کدام نماها را مینویسید؟ مهم
پاسخ
پاسخ: با قاعدهٔ تنظیم: نمای پردازه حذف (یک پردازه) و نمای فیزیکی حذف (یک پردازنده، یا یک یادداشت یکخطی). برای سیستم خیلی کوچک منطقی و توسعه حتی میتوانند یکی شوند. چند سناریو را نگه دارید.
۴ — همتیمیتان میگوید «نمای توسعه همان نمای منطقی است با اسم پوشهها». جواب چیست؟ مهم
پاسخ
پاسخ: به دغدغههای متفاوتی پاسخ میدهند: کارکرد در برابر سازماندهی، build، استفادهٔ دوباره، مالکیت و قیدهای ابزار. Kruchten دید هر چه پروژه بزرگتر، فاصلهٔ این دو بیشتر؛ یک دستهٔ منطقی ممکن است در چند لایهٔ توسعه پخش شود.
۵ — inside-out و outside-in در نگاشت نمای منطقی به پردازه چه هستند؟ تکمیلی
پاسخ
پاسخ: inside-out از classهای منطقی شروع میکند و objectهای فعال را روی agent taskها خوشه میکند تا تعداد پردازهها کم شود. outside-in از معماری فیزیکی و محرکهای بیرونی شروع میکند، برای محرکها پردازهٔ client و برای سرویسها پردازهٔ server تعریف میکند و بعد objectها را تخصیص میدهد. Kruchten هر دو را با هم و بهشکل تکراری به کار میبرد.
۶ — در زبان ISO 42010 تفاوت viewpoint و view چیست؟ مهم
پاسخ
پاسخ: viewpoint مجموعهای قابل استفادهٔ دوباره از قراردادهاست (model kindها، نمادگذاری، روشها) که دغدغههای مشخصی را قاب میگیرد؛ view همان viewpoint است که روی یک سیستم مشخص اعمال شده و از مدلها (در ویرایش ۲۰۲۲، view componentها) تشکیل میشود.
۷ — هر نمای 4+1 بیشتر در کدام خانوادهٔ V&B میافتد؟ تکمیلی
پاسخ
پاسخ: منطقی و توسعه: module views (decomposition، uses، layered). پردازه: component-and-connector views. فیزیکی: allocation (deployment)؛ work assignment نمای توسعه هم allocation است.
۸ — container در C4 چیست و container diagram بیشتر به کدام نمای 4+1 خدمت میکند؟ حیاتی
پاسخ
پاسخ: یک اپلیکیشن یا انبار داده که برای کار کردن سیستم باید در حال اجرا باشد (نه container داکر). container diagram بیشتر به نمای پردازه خدمت میکند (واحدهای زمان اجرا و گفتوگویشان) با کمی نشانهٔ فیزیکی؛ استقرار جایش در deployment diagram است.
۹ — سه تکنیک نام ببرید که نمای توسعه را از کهنه شدن حفظ میکنند. مهم
پاسخ
پاسخ: قاعدههای وابستگی را با تست اعمال کنید (archtest در Go، arch() در Pest، Deptrac)؛ گراف import را در CI از کد منبع تولید کنید و با diff شکست بدهید؛ از پوشههای internal در Go استفاده کنید تا کامپایلر import ممنوع را رد کند.
۱۰ — با رفتن از modular monolith به microservices، کدام نماها بیشترین تغییر را میکنند و کدام باید تقریباً ثابت بمانند؟ مهم
پاسخ
پاسخ: نمای پردازه (فراخوانی شبکه، timeout، retry، پیامرسانی ناهمگام) و نمای فیزیکی (pod، Service، zone) بیشتر عوض میشوند. اگر ماژولها در همان مرزها بریده شده و به portها وابسته بوده باشند، نمای منطقی باید تقریباً ثابت بماند.
۱۱ — اگر ویژگیهای کیفی مثل امنیت نمای جدا ندارند، کجا میروند؟ مهم
پاسخ
پاسخ: Rozanski و Woods آنها را بهشکل perspective روی همهٔ نماها اعمال میکنند؛ arc42 سناریوهای کیفیت را در بخش ۱۰ و راهحلهای تکرارشونده را در بخش ۸ میگذارد؛ در 4+1 به سناریو و یادداشت در هر نمای درگیر تبدیل میشوند.
۱۲ — Software Architecture Document حرف Kruchten علاوه بر چهار نما و سناریوها چه چیزهایی داشت؟ تکمیلی
پاسخ
پاسخ: Scope، References، مرور معماری، هدفها و قیدهای معماری، اندازه و کارایی، کیفیت، و پیوستهایی برای اختصارها، تعریفها و اصول طراحی. یک سند جدا به نام Software Design Guidelines تصمیمهای مهم طراحی را نگه میداشت.
واژهنامه (Glossary)
| واژه | معنا |
|---|---|
| مدل نماهای 4+1 (4+1 view model) | مدل ۱۹۹۵ Kruchten: نماهای منطقی، پردازه، توسعه و فیزیکی بهعلاوهٔ سناریوها |
| نما (View) | بازنمایی کل سیستم از دید یک دسته دغدغه |
| دیدگاه (Viewpoint) | قراردادهای ساختن و استفاده از یک نوع نما (ISO 42010) |
| ذینفع (Stakeholder) | فرد، گروه یا سازمانی که در سیستم ذینفعی (concern) دارد |
| دغدغه (Concern) | هر ذینفعی در سیستم: کارکرد، هزینه، ایمنی، کارایی |
| توصیف معماری (Architecture description، AD) | محصول کاری که یک معماری را بیان میکند (سند، مدلها، مخزن) |
| مدل / نوع مدل (Model / model kind) | یک نمودار یا متن درون یک نما / قراردادهای یک نوع مدل |
| View component | نام ویرایش ۲۰۲۲ استاندارد 42010 برای چیزی که ویرایش ۲۰۱۱ architecture model مینامید |
| تناظر (Correspondence) | رابطهٔ ثبتشده میان عنصرهای نماها یا توصیفهای مختلف |
| چارچوب معماری (Architecture framework) | قراردادهای توصیف در یک حوزه؛ 4+1، TOGAF و RM-ODP نمونهاند |
| نمای منطقی (Logical view) | انتزاعهای کلیدی و رابطههایشان؛ پشتیبان نیازمندیهای کارکردی |
| نمای پردازه (Process view) | پردازهها، taskها و ارتباطشان؛ همروندی، توزیع، دسترسپذیری |
| نمای توسعه (Development view) | ماژولها، subsystemها، لایهها و وابستگیهای کامپایل؛ سازماندهی و استفادهٔ دوباره |
| نمای فیزیکی (Physical view) | nodeها و شبکهها و نگاشت پردازهها روی آنها |
| سناریو (Scenario) | نمونهای از یک use case که در همهٔ نماها script شده؛ طراحی را میراند و اعتبارسنجی میکند |
| Script | توالی تعاملهای (object، operation) یک سناریو |
| Class category | گروهی از classهای مرتبط در نمای منطقی |
| Subsystem | واحدی از نمای توسعه که مالکش یک یا چند توسعهدهنده است |
| Major / minor task | thread of control قابل دیدن در معماری / thread محلی برای timeout و buffering |
| شیء Active / passive / protected | عملیات را آغاز میکند / هرگز آغاز نمیکند / آغاز نمیکند ولی میان فراخوانیها داوری میکند |
| Inside-out / outside-in | راهبرد نگاشت از classهای منطقی به بیرون / از محرکهای بیرونی به درون |
| معماری پردازهٔ توخالی (Hollow process architecture) | پردازهها با بار ساختگی برای اندازهگیری کارایی پیش از وجود کد واقعی |
| Software Architecture Document (SAD) | سند Kruchten که حول نماهای 4+1 سازمان یافته |
| Prototype معماری (Architectural prototype) | prototype تکاملی که به خود سیستم تبدیل میشود و سناریوها روی آن تست میشوند |
| Views and Beyond (V&B) | روش SEI: نماهای مرتبط را مستند کن، بهعلاوهٔ اطلاعاتی که میان نماهاست |
| Module view | خانوادهٔ V&B: واحدهای کد و رابطههایشان |
| Component-and-connector (C&C) view | خانوادهٔ V&B: عنصرهای زمان اجرا و تعاملشان |
| Allocation view | خانوادهٔ V&B: نگاشت نرمافزار به ساختارهای غیرنرمافزاری (سختافزار، فایل، تیم) |
| Combined (hybrid) view | یک نما که دو نمای دارای تناظر قوی عنصری را ادغام میکند |
| مدل C4 (C4 model) | نمودارهای context، container، component، code از Simon Brown بهعلاوهٔ deployment و dynamic |
| Container (C4) | اپلیکیشن یا انبار دادهای که برای کار سیستم باید اجرا شود |
| arc42 | قالب مستندسازی دوازدهبخشی؛ بخشهای ۵ تا ۷ نماهای building block، runtime و deployment را نگه میدارند |
| Perspective | Rozanski و Woods: فعالیتها و تاکتیکهایی برای یک ویژگی کیفی در سراسر نماها |
| نمودار بهشکل کد (Diagrams as code) | منبع متنی نمودار (Mermaid، PlantUML، Structurizr DSL) که همراه کد نسخهبندی میشود |
| Fitness function | بررسی خودکاری که نشان میدهد یک ویژگی معماری هنوز برقرار است (مثلاً archtest) |
| Deptrac | ابزار تحلیل ایستای PHP که قاعدههای وابستگی لایهها را اعمال میکند |
arch() در Pest | API تست معماری Pest (expect(...)->not->toUse(...)) |
| Composition root | تنها جایی (cmd/.../main.go، service providerها) که ماژولها به adapterها سیمکشی میشوند |
منابع (References)
- Philippe Kruchten, Architectural Blueprints—The "4+1" View Model of Software Architecture, IEEE Software 12(6), November 1995, pp. 42–50. PDF copy: https://www.cs.ubc.ca/~gregor/teaching/papers/4+1view-architecture.pdf
- ISO/IEC/IEEE 42010 conceptual model (maintainers' site): http://www.iso-architecture.org/ieee-1471/cm/ and overview: http://www.iso-architecture.org/42010/
- SEI, Views and Beyond collection: https://www.sei.cmu.edu/library/views-and-beyond-collection/
- Paul Clements, Comparing the SEI's Views and Beyond Approach for Documenting Software Architectures with ANSI-IEEE 1471-2000, CMU/SEI-2005-TN-017: https://www.sei.cmu.edu/documents/2072/2005_004_001_14498.pdf
- Clements, Ivers, Little, Nord, Stafford, Documenting Software Architectures in an Agile World, CMU/SEI-2003-TN-023: https://www.sei.cmu.edu/documents/2028/2003_004_001_14171.pdf
- SEI, Views and Beyond: The SEI Approach for Architecture Documentation (brochure, 2018): https://www.sei.cmu.edu/documents/2546/2018_010_001_513864.pdf
- Clements et al., Documenting Software Architectures: Views and Beyond, 2nd ed., Addison-Wesley, 2010 (book; cited through the SEI pages above, not read in full)
- C4 model: https://c4model.com/, diagrams: https://c4model.com/diagrams, container: https://c4model.com/abstractions/container, deployment: https://c4model.com/diagrams/deployment, dynamic: https://c4model.com/diagrams/dynamic, checklist: https://c4model.com/diagrams/checklist, FAQ: https://c4model.com/faq, history: https://c4model.com/history
- arc42 documentation: https://docs.arc42.org/home/, building block view: https://docs.arc42.org/section-5/, runtime view: https://docs.arc42.org/section-6/, deployment view: https://docs.arc42.org/section-7/
- Nick Rozanski and Eoin Woods, Software Systems Architecture, viewpoints: https://www.viewpoints-and-perspectives.info/home/viewpoints/, perspectives: https://www.viewpoints-and-perspectives.info/home/perspectives/
- Mermaid C4 diagrams: https://mermaid.js.org/syntax/c4.html; C4-PlantUML: https://github.com/plantuml-stdlib/C4-PlantUML; Structurizr DSL: https://docs.structurizr.com/dsl
- Pest architecture testing: https://pestphp.com/docs/arch-testing; Deptrac: https://deptrac.github.io/deptrac/
- Go modules layout: https://go.dev/doc/modules/layout
- Laravel 13: deployment (health route, FrankenPHP): https://laravel.com/docs/13.x/deployment, queues: https://laravel.com/docs/13.x/queues, scheduling: https://laravel.com/docs/13.x/scheduling, service providers: https://laravel.com/docs/13.x/providers, query builder locking: https://laravel.com/docs/13.x/queries
- FrankenPHP Docker images and Laravel: https://frankenphp.dev/docs/docker/, https://frankenphp.dev/docs/laravel/
- Docker Compose services reference: https://docs.docker.com/reference/compose-file/services/
- Kubernetes: Deployments https://kubernetes.io/docs/concepts/workloads/controllers/deployment/, probes https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/, topology spread constraints https://kubernetes.io/docs/concepts/scheduling-eviction/topology-spread-constraints/
- Distroless images: https://github.com/GoogleContainerTools/distroless
- Laravel 13: Octane https://laravel.com/docs/13.x/octane, HTTP client https://laravel.com/docs/13.x/http-client, Eloquent https://laravel.com/docs/13.x/eloquent, casts https://laravel.com/docs/13.x/eloquent-mutators, relationships https://laravel.com/docs/13.x/eloquent-relationships, Redis https://laravel.com/docs/13.x/redis
- RabbitMQ quorum queues: https://www.rabbitmq.com/docs/quorum-queues