Service-Oriented Architecture (SOA)
"Service Oriented Architecture (SOA) is a paradigm for organizing and utilizing distributed capabilities that may be under the control of different ownership domains." — OASIS، Reference Model for Service Oriented Architecture 1.0، OASIS Standard، ۱۲ اکتبر ۲۰۰۶
خلاصه (Summary): SOA این ایده است که تواناییهای یک سازمان باید بهشکل سرویسهای شبکهای با قرارداد (Contract) منتشرشده عرضه شوند. پیادهسازی دههٔ ۲۰۰۰ (SOAP، WSDL، ESB، یک orchestrator مرکزی و یک canonical data model) این ایده را بیش از حد متمرکز کرد و در بسیاری از جاها شکست خورد؛ اما هستهٔ contract-first زنده مانده و امروز در میکروسرویسها، API management و هر اتصال به یک endpoint قدیمی SOAP دیده میشود. تمرکز (Focus): تاریخچه، تعریف OASIS، اصول، دستهبندی چهارلایهٔ سرویسها، ESB و موتور orchestration، پشتهٔ WS-* و دلیل سنگینیاش، canonical data model، اسطورههای governance و reuse، SOA در برابر microservices، service-based architecture، یکپارچهسازی سیستمهای قدیمی (Legacy) و یک انتقال بانکی که یک بار به سبک SOA و یک بار به سبک میکروسرویس ساخته میشود، با کد Go و Laravel. هدف یادگیری (Learning goal): برای هر سیستمی بتوانید بگویید SOA است، microservices است یا distributed monolith؛ تصمیم بگیرید کدام ایدههای SOA ارزش نگهداشتن دارند؛ یک سرویس SOAP را پشت anti-corruption layer مصرف کنید؛ و همان قابلیت را بهصورت یک سرویس REST با قرارداد contract-first عرضه کنید.
این فصل در گروه سبکهای معماری (Architecture Styles) است: سبک در برابر الگو میگوید «سبک» یعنی چه؛ client-server و pipe-and-filter همسایههای آناند؛ معماری microservices جانشین آن است و بحث کامل در آنجا آمده. اینجا سبک دههٔ ۲۰۰۰ را کامل میگوییم تا وقتی کسی گفت «این همان SOA است» دقیقاً بدانید چه چیزش یکی است و چه چیزش نه. جزئیات پیامرسانی (canonical model، routing، saga) در مسیر messaging است؛ ما فقط زاویهٔ SOA را میگوییم و ارجاع میدهیم.
نقشهٔ صفحه
| دنبال چه هستید | بروید به |
|---|---|
| کل فصل در چند جدول | همهچیز در یک دقیقه |
| چرا SOA پیدا شد و چرا دیگر اسمش را نمیآورند | چرا وجود دارد |
| CORBA، DCOM، web services، ESB، microservices | از کجا آمده |
| هشت اصل، هر کدام یک بلوک | اصول |
| business / enterprise / application / infrastructure services | دستهبندی سرویسها |
| ESB، mediation، موتور orchestration، BPEL | ESB و orchestration |
| SOAP، WSDL، UDDI، WS-Security، WS-ReliableMessaging | پشتهٔ WS-* |
| canonical data model و هزینهٔ آن | Canonical data model |
| governance، reuse و «SOAی که شکست خورد» | اسطورههای governance و reuse |
| جدول SOA در برابر microservices | SOA در برابر microservices |
| service-based architecture (راه میانه) | Service-based architecture |
| چه چیزی زنده ماند | ایدههای SOA که ماندند |
| صدا زدن SOAP از Go و Laravel | سیستم قدیمی، Go، Laravel |
| انتقال بانکی orchestrated در برابر choreographed | مثال کامل |
| از monolith تا سیستم توزیعشده | در معماری |
| تمرین عملی | آزمایشگاه |
| باورهای غلط، چکیده، خودآزمایی، واژهها | بدفهمیها، چکیده، خودآزمایی، واژهنامه |
همهچیز در یک دقیقه
واژهها. هر سطر در ادامه باز میشود.
| واژه | به زبان ساده | مثال کوچک | بدون آن چه میشود |
|---|---|---|---|
| سرویس (Service) | تواناییای که از راه یک interface منتشرشده در دسترس است | TransferFunds روی SOAP | مصرفکنندهها به درون سیستم دست میاندازند |
| قرارداد سرویس (Service contract) | قول ماشینخوانِ interface | فایل WSDL یا OpenAPI | همه فرمت پیام را حدس میزنند |
| SOAP | پروتکل پاکت XML برای پیامها | Envelope / Header / Body | هر اتصال فرمت سیم خودش را میسازد |
| WSDL | شرح XML از عملیات، پیامها، binding و نشانی | legacy-transfer.wsdl | نه کلاینت تولیدشده، نه اعتبارسنجی |
| UDDI | رجیستری برای انتشار و پیدا کردن سرویسها | «صفحات زرد» سرویسها | کسی نمیداند چه چیزی هست (و باز هم فراگیر نشد) |
| WS-* | مشخصات الحاقی: امنیت، اطمینان، policy، آدرسدهی | امضای WS-Security در header | هر vendor SOAP را جور دیگری گسترش میدهد |
| ESB | گذرگاه مرکزی با mediation، routing و transformation | Mule، IBM Integration Bus، Oracle Service Bus | اتصالهای نقطهبهنقطهٔ درهم (و در سوءاستفاده، یک مغز مرکزی تازه) |
| Orchestration | یک فرایند مرکزی سرویسها را بهترتیب صدا میزند | فرایند BPEL «افتتاح حساب» | جریان کسبوکار بین فراخوانها پخش میشود |
| Choreography | سرویسها به رویدادهای هم واکنش نشان میدهند، مرکزی نیست | TransferApproved بدهکاری را شروع میکند | مرکز گلوگاه میشود |
| Canonical data model | یک واژگان پیام سازمانی مشترک | یک schema سراسری Customer | مترجمهای N در N بین سیستمها |
| Service-based architecture | چند سرویس درشت، اغلب با یک پایگاهداده | ۴ تا ۱۲ سرویس دامنه + یک UI | هزینهٔ میکروسرویس بدون نیازش |
SOA در یک نگاه: چه میگیرید، چه میدهید.
| میگیرید | میدهید |
|---|---|
| استفادهٔ مجدد از تواناییها بین برنامهها | یک تیم مرکزی و صف جلوی هر تغییر |
| تعاملپذیری Java، .NET و mainframe | XML سنگین، ابزار سنگین، مشخصات سنگین |
| یک جا برای امنیت، لاگ و routing | نقطهٔ شکست و سرزنش واحد |
| سیستمهای قدیمی قابلفراخوانی میشوند | wrapperهایی که رفتار قدیمی را منجمد میکنند |
چهار نوع سرویس (Richards و Ford، SOA مبتنی بر orchestration):
| نوع | اندازه | مالک | مثال |
|---|---|---|---|
| Business service | درشت، نقطهٔ ورود | تحلیلگر کسبوکار + معمار | TransferFunds |
| Enterprise service | ریز، مشترک، قابلاستفادهٔ مجدد | تیم سرویسهای مشترک | GetBalance، CreateCustomer |
| Application service | مخصوص یک برنامه | تیم همان برنامه | MainframeWrapper.Post |
| Infrastructure service | مشترک بین همه | تیم پلتفرم | audit، احراز هویت، logging |
چرا وجود دارد
اواخر دههٔ ۱۹۹۰ یک شرکت بزرگ دهها برنامه داشت: mainframe برای حسابها، ERP آماده، CRM، وبسایت، اتصال به شریکها. یکپارچهسازی نقطهبهنقطه بود و هر جفت فرمت فایل یا binding شیء راه دور خودش را داشت. با N برنامه تا N×(N−1) اتصال لازم میشد. ایدهٔ SOA سه مشکل را با هم جواب میدهد: دسترسی (هر توانایی از هر جا صدا زده شود)، بیطرفی (وابسته به یک زبان یا vendor نباشد) و استفادهٔ مجدد («محاسبهٔ قیمت» را یک بار بنویس، از همهجا صدا بزن).
| یکپارچهسازی نقطهبهنقطه | یکپارچهسازی سرویسگرا |
|---|---|
| هر جفت یک فرمت خصوصی قرار میگذارد | هر سرویس یک قرارداد منتشر میکند |
| برنامهٔ N+1 یعنی N اتصال تازه | یعنی یک قرارداد تازه (در تئوری) |
| دانستنیهای درونی نشت میکند | مصرفکننده فقط interface را میبیند |
| برای ۳ سیستم ارزان، برای ۳۰ سیستم آشوب | برای ۳ سیستم سربار، برای ۳۰ سیستم قابلتحمل |
تشبیهی که در همهٔ صفحه به کار میبریم: میز پذیرش یک شرکت. مراجعهکننده وارد بخشها نمیشود؛ از میز پذیرش میپرسد، پذیرش میداند کدام بخش درست است، درخواست را به فرمهای همان بخش ترجمه میکند و جواب را برمیگرداند. یک میز پذیرش خوب (gateway نازک) نعمت است. میزی که قیمت هم تعیین کند، بازپرداخت را تأیید کند و قرارداد بنویسد (ESB با قواعد کسبوکار) قدرتمندترین و پرکارترین آدم شرکت میشود.
سه بدفهمی رایج، از همان ابتدا
- «SOA یعنی SOAP و web services.» نه. OASIS مدل مرجع را مستقل از فناوری میگیرد و SOA را یک پارادایم میداند. SOAP پیادهسازی رایج دههٔ ۲۰۰۰ بود، نه تعریف. سرویسهای REST/JSON، صف پیام و gRPC هم میتوانند سرویسگرا باشند.
- «SOA مرد و microservices جایش را گرفت.» میکروسرویسها هسته (سرویس با قرارداد، loose coupling) را به ارث بردند و عادتهای پیادهسازی دههٔ ۲۰۰۰ (bus مرکزی، canonical model، governance مرکزی) را کنار گذاشتند. Fowler مینویسد برخی microservices را «perhaps service orientation done right» میدانند.
- «نکتهٔ سرویسها reuse است.» reuse شعار فروش و بزرگترین ناامیدی بود. سود ماندگار تغییر مستقل پشت یک قرارداد پایدار است، نه اینکه ده تیم یک سرویس
Customerرا مشترکاً استفاده کنند.
از کجا آمده
نمودار بالا داستان را در پنج جعبه میگوید. جزئیات، همراه با وضعیت خواندن هر ادعا:
| دوره | چه شد | از کجا میدانیم |
|---|---|---|
| اوایل دههٔ ۱۹۹۰ | CORBA (OMG) و DCOM (Microsoft) شیء راه دور میدهند: متدی را روی شیئی در فرایند یا ماشین دیگر صدا بزن | دانش ثانویه (متلک Fowler دربارهٔ «CORBA with angle brackets» همین تبار را تأیید میکند)؛ مشخصات اصلی را نخواندهایم |
| 8 May 2000 | SOAP 1.1 بهصورت W3C Note منتشر شد | خوانده شد: مشخصات SOAP 1.2 به http://www.w3.org/TR/2000/NOTE-SOAP-20000508/ ارجاع میدهد |
| August 2000 | UDDI نوشته شد، با چشمانداز brokerهای عمومی | Wikipedia (ثانویه) |
| 15 March 2001 | WSDL 1.1 بهصورت W3C Note منتشر شد | خوانده شد: صفحهٔ اول Note |
| 27 April 2007 | SOAP 1.2 Part 1 ویراست دوم Recommendation شد و «supercedes all previous versions of SOAP, including SOAP Version 1.1» | خوانده شد |
| 26 June 2007 | WSDL 2.0 به Recommendation رسید | خوانده شد |
| 2005 | Fowler: «SOA means so many different things to different people» | خوانده شد |
| January 2006 | IBM، Microsoft و SAP نودهای عمومی UDDI را بستند | Wikipedia (ثانویه) |
| 12 October 2006 | OASIS مدل مرجع SOA 1.0 را منتشر کرد | خوانده شد |
| 25 March 2014 | Fowler و Lewis مقالهٔ microservices را با بخش Microservices and SOA منتشر کردند | خوانده شد |
CORBA و DCOM: دوران شیء روی سیم
تکمیلی به زبان ساده: اولین ایده این بود که شیء راه دور شبیه شیء محلی به نظر برسد:account.debit(100) را صدا بزنی و middleware آن را روی شبکه بفرستد.بدفهمی رایج: «اشیای توزیعشده همان میکروسرویسهای اولیه بودند.» آنها شبکه را پنهان میکردند، پس فراخوانها ریز و پرتعداد (chatty) میشد، مدل شیء مشترک بود و با هر تغییر میشکست. سرویسها قرار بود هزینهٔ شبکه را نشان بدهند: پیام درشت، قرارداد صریح، بدون گراف شیء مشترک.
Web services و موج SOA
SOAP یک پاکت مستقل از پلتفرم روی HTTP داد، WSDL آن را توصیف کرد و UDDI قرار بود منتشرش کند. یادداشت ۲۰۰۵ Fowler سردرگمیِ بعد را ثبت کرده: برای بعضی SOA یعنی استانداردهای WS-*، برای بعضی «any form of XML over http»، برای بعضی پیامرسانی غیرهمگام یعنی «EAI without all the expensive EAI vendors»، و در بدترین شکل «CORBA with angle brackets». OASIS با یک مدل مرجع عمداً بالاتر از فناوری جواب داد.
ESB و شکست
vendorها Enterprise Service Bus را محصولی فروختند که خودِ SOA است. شرکتها خریدند، همهٔ یکپارچهسازیها را در آن گذاشتند و اغلب monolithها را بدون تغییر در سرویس پیچیدند. Fowler نتیجه را فهرست میکند: «the tendency to hide complexity away in ESB's, to failed multi-year initiatives that cost millions and deliver no value, to centralised governance models that actively inhibit change».
Microservices و آرام گرفتن
تیمهای شرکتهای وب (Fowler از Netflix نام میبرد که سبکش را «fine-grained SOA» مینامید) سرویسها را نگه داشتند و bus، canonical model و کمیته را کنار گذاشتند. خلاصهٔ صادقانهٔ امروز: سرویسگرایی (Service orientation) برد؛ سبک ESB مبتنی بر orchestration نه.
تعریف OASIS، دقیق
حیاتی مدل مرجع OASIS سرویس را چنین تعریف میکند: «a mechanism to enable access to one or more capabilities, where the access is provided using a prescribed interface and is exercised consistent with constraints and policies as specified by the service description.» سه واژه بار را میکشند: capability (کاری که برای کسی انجام میشود)، prescribed interface (قرارداد) و service description (policy ماشینخوان).| مفهوم OASIS | معنا | در عمل کجا دیده میشود |
|---|---|---|
| Visibility | ارائهدهنده و مصرفکننده همدیگر را ببینند (آگاهی، تمایل، دسترسپذیری) | registry، پورتال API، نام DNS |
| Interaction | استفاده از یک capability با پیام و اثر در دنیای واقعی | یک فراخوان HTTP که پول جابهجا میکند |
| Real-world effect | نتیجهٔ مشاهدهپذیر یک interaction | موجودی عوض میشود |
| Service description | اطلاعات لازم برای استفاده از سرویس | WSDL، OpenAPI |
| Contract and policy | توافق دو طرف و شرایط آن | rate limit، احراز هویت، SLA |
| Execution context | آنچه برای وقوع interaction لازم است | دامنهٔ امنیتی، transport، context تراکنش |
مدل مرجع صریحاً میگوید چه چیزی را کنار گذاشته: «in this Reference Model we do not address the orchestration of multiple services, although orchestration and choreography may be part of the process model.» این را به خاطر بسپارید: orchestration و ESB جزو تعریف SOA نیستند. فقط یک راه رایج ساختن آناند.
اصول
اصول service-orientation از Thomas Erl معروفترین فهرست است. سایت خود او را نتوانستیم بگیریم (صفحهها مرورگر لازم دارند)، پس هشت نام زیر را از حافظه و از کتابهای او نوشتهایم، نه از صفحهای که خوانده باشیم؛ مقالهٔ Wikipedia فهرستی کمی متفاوت دارد (service longevity، location transparency، granularity و normalization را هم اضافه میکند). توضیح هر خط بازنویسی خودمان است.
Standardized service contract حیاتی
به زبان ساده: هر سرویس خودش را به شکلی توافقشده و ماشینخوان توصیف میکند و قرارداد پیش از کد طراحی میشود. بدفهمی رایج: «قرارداد از روی کد تولید میشود، پس خودبهخود استاندارد است.» قراردادی که از کلاسهایتان تولید شود درونتان را نشت میدهد؛ contract-first یعنی فایل WSDL یا OpenAPI اول با دست نوشته میشود و هر دو طرف روی آن کد میزنند. سناریوی واقعی: سرویس انتقال بانک legacy-transfer.wsdl را منتشر میکند؛ هر کلاینتی از روی آن stub میسازد.
Loose coupling حیاتی
به زبان ساده: مصرفکننده به قرارداد وابسته است، نه به زبان، پایگاهداده یا مکان ارائهدهنده. بدفهمی رایج: «SOAP روی HTTP loosely coupled است.» یک فراخوان همگام با schema مشترک canonical از نظر زمان و داده شدیداً جفت است؛ انتخاب پروتکل coupling را تعیین نمیکند.
Abstraction مهم
به زبان ساده: قرارداد «چگونه» را پنهان میکند. فراخواننده «TransferFunds» را میشناسد، نه اینکه کدام جدولها عوض میشوند. بدفهمی رایج: «پیچیدن monolith در یک سرویس abstraction است.» این فقط یک facade است؛ چرخهٔ انتشار monolith هنوز جلوی هر تغییر را میگیرد.
Reusability مهم
به زبان ساده: سرویس را طوری طراحی کن که بیش از یک مصرفکننده بتواند از آن استفاده کند. بدفهمی رایج: «از روز اول همهچیز را reusable کنیم.» سرویس عمومی برای هیچکس خوب نیست؛ reuse بعد از مصرفکنندهٔ دوم کشف میشود، نه برای مصرفکنندگان خیالی طراحی (ببینید اسطورههای governance و reuse).
Autonomy مهم
به زبان ساده: سرویس منطق و زمان اجرای خودش را کنترل میکند، پس میتواند بدون کشیدن بقیه تغییر کند و از کار بیفتد. بدفهمی رایج: «autonomy فقط دربارهٔ استقرار است.» بدون خودمختاری داده (store خودش) دو سرویسی که یک schema را مشترک دارند یک سرویس در دو فرایندند؛ ببینید مالکیت داده.
Statelessness مهم
به زبان ساده: سرویس بین درخواستها حالت گفتوگوی هر فراخواننده را نگه نمیدارد؛ state در پیام میآید یا در یک store است. بدفهمی رایج: «stateless یعنی بدون پایگاهداده.» یعنی بدون حافظهٔ session در فرایند، که اجازه میدهد N کپی یکسان اجرا کنید.
Discoverability تکمیلی
به زبان ساده: سرویسها metadata دارند تا آدمها و ابزارها پیدایشان کنند و بفهمندشان. بدفهمی رایج: «رجیستری UDDI لازم داریم.» UDDI فراگیر نشد؛ پورتال توسعهدهنده و کاتالوگ API همین کار را میکنند، و برای جستوجوی زمان اجرا ببینید service discovery.
Composability مهم
به زبان ساده: سرویسها را میشود در سرویسهای بزرگتر ترکیب کرد، هر اندازه که ترکیب باشد. بدفهمی رایج: «ترکیب به موتور مرکزی نیاز دارد.» ترکیب با orchestration به یکی نیاز دارد؛ با choreography نه (بخش بعد).
| اصل | سؤال آزمون | نمونهٔ شکست | معادل امروزی |
|---|---|---|---|
| Standardized contract | بدون حرف زدن با تیم میتوانم کلاینت تولید کنم؟ | قرارداد یک فایل Word است | OpenAPI، protobuf، WSDL |
| Loose coupling | ارائهدهنده میتواند زبان یا پایگاهداده را عوض کند و من نفهمم؟ | جدول مشترک پایگاهداده | API نسخهدار |
| Abstraction | فقط توانایی را میدانم، نه درون را؟ | متن خطا SQL را نشان میدهد | نوعهای مشکل RFC 9457 |
| Reusability | مصرفکنندهٔ دوم بدون تغییر استفاده میکند؟ | برای هر مصرفکننده یک فیلد اضافه شده | API عمومی پایدار |
| Autonomy | تنها استقرار و تنها شکست میخورد؟ | برای بالا آمدن به ESB نیاز دارد | استقرار مستقل |
| Statelessness | هر نمونه میتواند جواب دهد؟ | sticky session | token + store |
| Discoverability | تازهوارد در ۵ دقیقه پیدایش میکند؟ | صفحهٔ wiki سال ۲۰۱۱ | کاتالوگ API |
| Composability | میتواند یک گام یک جریان بزرگتر باشد؟ | عملیات تکهای از UI برمیگرداند | عملیات idempotent |
دستهبندی سرویسها: business، enterprise، application، infrastructure
Richards و Ford (کتاب Fundamentals of Software Architecture، فصل service-oriented architecture مبتنی بر orchestration؛ کتاب آزادانه قابلدریافت نیست، پس این بخش بازنویسی خودمان است، نه نقلقول) این سبک را پشتهای از چهار نوع سرویس میدانند که یک orchestration engine به هم وصل میکند:
| لایه | نقش | مالک | مثال (بانک) | مشکل رایج |
|---|---|---|---|---|
| Business services | نقطهٔ ورود؛ فقط یک نام و ورودی/خروجی، کمکد | کسبوکار + معمار | TransferFunds، OpenAccount | پوستهٔ خالیاند؛ منطق واقعی در orchestrator است |
| Enterprise services | ریز، مشترک، «اتمی» | تیم سرویسهای مشترک | GetBalance، ValidateIban، CreateCustomer | همه به آنها وابستهاند، پس کسی نمیتواند عوضشان کند |
| Application services | مخصوص یک برنامه، مشترک نیست | تیم همان برنامه | PostLedgerEntry برای سیستم هستهٔ بانکی | با enterprise serviceها تکراری میشود |
| Infrastructure services | لولهٔ مشترک | تیم پلتفرم | احراز هویت، audit، monitoring | اغلب تنها لایهای که واقعاً موفق میشود |
بدفهمی رایج: «این یک طراحی لایهای خوب است.» یک تغییر را دنبال کنید: افزودن یک فیلد به TransferFunds یعنی دست زدن به business service، جریان orchestration، یک schema canonical، شاید یک enterprise service و هر wrapper. Richards و Ford این سبک را از نظر چابکی (agility) و استقرار ضعیف میدانند، چون لایههای فنی از میان هر تغییر کسبوکار میگذرند. مقایسه کنید با layered monolith: همان مشکل، این بار روی شبکه.
یک درخواست از میان لایهها
1 Portal -> Business service TransferFunds (SOAP, WS-Security header)
2 ESB -> authenticate via infrastructure service (audit logged)
3 Orchestrator -> enterprise service ValidateIban(from), ValidateIban(to)
4 Orchestrator -> enterprise service GetBalance(from)
5 Orchestrator -> application service PostLedgerEntry (mainframe wrapper)
6 Orchestrator -> enterprise service NotifyCustomer
7 ESB -> transforms canonical Transfer to mainframe fixed-width record
8 Business service <- response mapped back to canonical, then to the portalهشت hop، در ذهن مشتری یک تراکنش، و هیچ تراکنش پایگاهدادهای در هیچجا. بخشهای مثال کامل و saga میگویند وقتی گام ۵ موفق و گام ۶ ناموفق باشد چه میشود.
ESB و موتور orchestration
حیاتی به زبان ساده: Enterprise Service Bus یک سوئیچبورد مرکزی است: هر فراخوان از آن میگذرد و میتواند فراخوانها را مسیردهی مجدد، تبدیل و ترتیبدهی کند.بدفهمی رایج: «ESB همان message broker است.» broker (RabbitMQ، Kafka) پیام را جابهجا میکند و کودن میماند؛ ESB علاوه بر آن mediation، پل پروتکل، transformation، orchestration و قواعد دارد. تفاوتشان همان بحث smart pipes در برابر dumb pipes است. الگوی کوچکتر Message Broker در کاتالوگ Enterprise Integration Patterns فقط فرستنده را از گیرنده جدا میکند.
| قابلیت ESB | چه میکند | مثال | ریسک |
|---|---|---|---|
| Mediation | بین مصرفکننده و ارائهدهنده مینشیند، endpoint را پنهان میکند | مصرفکننده یک نشانی مجازی را صدا میزند | bus یک hop اجباری میشود |
| Routing | مقصد را بر اساس محتوا، قاعده یا نسخه برمیگزیند | مسیر انتقال داخلی در برابر بینالمللی | قواعد routing منطق کسبوکار میشود |
| Transformation | قالبها (XML، fixed-width، JSON) را با XSLT یا mapping تبدیل میکند | Transfer canonical به رکورد mainframe | mappingهایی که کسی تستشان نمیکند |
| Protocol bridging | HTTP به JMS به FTP به MQ | SOAP وارد، MQ خارج | retry و timeout پنهان |
| Orchestration | یک تعریف فرایند (BPEL، BPMN) را روی سرویسها اجرا میکند | افتتاح حساب: KYC، ساخت، اعلان | مرکز مالک همهٔ جریان کسبوکار میشود |
| Security policy | WS-Security، نگاشت token، throttling | یک بار امضا را بررسی میکند | نقطهٔ حملهٔ واحد |
| Monitoring و audit | یک جا برای ثبت همهٔ فراخوانها | audit trail مرکزی | حجم لاگ، حریم خصوصی |
محصولاتی که مردم دیدند. Mule ESB (MuleSoft)، IBM WebSphere ESB و IBM Integration Bus، Oracle Service Bus، TIBCO BusinessWorks، WSO2 ESB، Apache ServiceMix، Apache Camel بهصورت کتابخانه، Microsoft BizTalk Server. امروز همین کار را API gatewayها، محصولات iPaaS و کد Camel/Spring Integration میکنند.
زبان orchestration. BPEL (Business Process Execution Language برای web services، یک استاندارد OASIS) فرایند را بهصورت XML توصیف میکرد که سرویسها را بهترتیب صدا میزند، با handlerهای خطا و جبران (compensation). مقالهٔ Fowler آن را در برابر رویکرد میکروسرویس میگذارد: سرویسها «are choreographed using simple RESTish protocols rather than complex protocols such as WS-Choreography or BPEL or orchestration by a central tool.»
Orchestration در برابر choreography
تشبیه: رهبر ارکستر به هر نوازنده میگوید کی بنوازد (orchestration)؛ رقصندههای یک سالن هر کدام موسیقی را میدانند و به همسایهشان واکنش نشان میدهند (choreography).
| ویژگی | Orchestration | Choreography |
|---|---|---|
| چه کسی کل جریان را میداند | orchestrator | هیچکس؛ پدید میآید |
| Coupling | سرویسها از هم بیخبرند؛ orchestrator همه را میشناسد | سرویسها رویدادهایی را که به آنها واکنش نشان میدهند میشناسند |
| مدیریت شکست | compensation در یک جا | هر سرویس بخش خودش را جبران میکند |
| دید | یک تعریف فرایند را بخوانید | به tracing و فهرست رویدادها نیاز دارد |
| تغییر | یک جریان را ویرایش کن؛ مرکز گلوگاه تیمی است | یک سرویس را ویرایش کن؛ خطر شگفتی برای مصرفکنندهها |
| سبک معمول | SOA با BPEL یا ESB | microservices با رویداد |
| جزئیات | Saga pattern | Event-driven architecture |
هیچکدام «درست» نیست. مثال کامل پایین هر دو را روی یک عملیات کسبوکار به کار میبرد.
پشتهٔ WS-* و چرا سنگین بود
مهم به زبان ساده: web services با «XML را روی HTTP بفرست» شروع شد؛ هر نیاز سازمانی (امنیت، اطمینان، تراکنش، آدرسدهی) بعداً بهشکل مشخصهٔ XML دیگری روی headerهای SOAP انباشته شد.بدفهمی رایج: «SOAP فقط XML روی HTTP است.» SOAP یک چارچوب پیامرسانی است: پاکت با header (نقاط توسعه) و body، مدل پردازش با واسطهها و مدل خطا (fault)؛ HTTP فقط یکی از bindingهاست. SOAP 1.2 خودش را «a lightweight protocol intended for exchanging structured information in a decentralized, distributed environment» مینامد و وزن واقعی از چیزهایی میآید که روی آن انباشته شد.
| مشخصه | هدف | نهاد و نسخهای که خواندیم | چرا سنگینی میآورد |
|---|---|---|---|
| SOAP | envelope، header، body، fault، مدل پردازش | W3C SOAP 1.2 Part 1, Second Edition, 27 April 2007 | XML پرحرف، namespace روی هر المان |
| WSDL | توصیف عملیات، پیامها، binding و نشانی | W3C WSDL 1.1 Note (2001)؛ WSDL 2.0 Recommendation (2007) | سندهای بزرگ، تولیدکنندههای کد ناهمسان |
| XML Schema (XSD) | نوع پیامها | W3C | سیستم نوع پیچیده، درد نسخهبندی |
| UDDI | انتشار و یافتن سرویسها | OASIS (کمیته ۲۰۰۷ تمام شد، به نقل Wikipedia) | رجیستریای که کسی بهروزش نگه نداشت |
| WS-Security | امضا و رمزنگاری بخشهای پیام، token | OASIS Standard 1.1.1, 18 May 2012 | canonicalization امضای XML، headerهای بزرگ |
| WS-ReliableMessaging | تحویل مطمئن بین endpointها در برابر خرابی | OASIS Standard 1.2, 2 February 2009 | sequence، ack، state در دو سر |
| WS-Addressing، WS-Policy، WS-Transaction، WS-Coordination | headerهای مسیریابی، policy، تراکنش توزیعشده | W3C / OASIS (نخواندهایم) | هر کدام header و coordinator اضافه میکند |
| BPEL، WS-CDL | زبانهای orchestration و choreography | OASIS، W3C (نخواندهایم) | برنامهنویسی در XML |
abstract مشخصهٔ WS-Security میگوید «describes enhancements to SOAP messaging to provide message integrity and confidentiality»؛ و WS-ReliableMessaging «describes a protocol that allows messages to be transferred reliably between nodes implementing this protocol in the presence of software component, system, or network failures.» هر دو مشکل واقعی را حل میکنند. هزینه: فرستنده به کتابخانهای نیاز دارد که کل پشته را سازگار پیاده کرده باشد، و تعاملپذیری بین vendorها «profile» اضافی (WS-I Basic Profile) میخواست.
چرا سنگین بود، در یک فهرست. پرحرفی XML و کار با namespace؛ تولید کد از WSDL با عجایب هر ابزار؛ مشخصههای فراوان که هر کدام نسخه و افزونهٔ vendor دارد؛ امنیت transport تکراری (TLS در برابر WS-Security)؛ دیباگ با خواندن envelope؛ و یک چارچوب برای هر زبان (Apache Axis، Apache CXF، Microsoft WCF). گلایهٔ Fowler: «central standards that have reached a complexity that is, frankly, breathtaking.»
یک تبادل SOAP 1.1 روی سیم:
1 POST /ws/transfer HTTP/1.1
2 Content-Type: text/xml; charset=utf-8
3 SOAPAction: "urn:example:bank:transfer:v1/TransferFunds"
4 <Envelope> <Body> <TransferFunds> from, to, amount, currency, reference
5 HTTP/1.1 500 Internal Server Error <- SOAP 1.1 faults use HTTP 500
6 <Envelope> <Body> <Fault> faultcode, faultstring, detail/ErrorCode=51خط ۵ را به خاطر بسپارید: fault در SOAP بهصورت HTTP 500 همراه با body میآید. کلاینت Go ما دقیقاً به همین دلیل body را قبل از نگاه به status میخواند.
Canonical data model
مهم به زبان ساده: بهجای ترجمهٔ فرمت هر سیستم به هر سیستم دیگر، یک فرمت سازمانی مشترک تعیین میکنید و هر سیستم را به آن و از آن ترجمه میکنید.بدفهمی رایج: «canonical model یک مدل داده سازمانی تمیز به ما میدهد.» به شما یک مذاکرهٔ چندساله میدهد. صفحهٔ Enterprise Integration Patterns حساب را میگوید: با ۲ برنامه، ترجمهٔ مستقیم ۲ مترجم میخواهد و canonical model ۴ مترجم؛ با ۶ برنامه ۳۰ مترجم بدون canonical model و ۱۲ با آن. این سود است. هزینه این است که هر مصرفکننده و ارائهدهنده حالا به schema Customer کمیته جفت شده است.
1 Without canonical model: A→B, A→C, B→A, B→C, C→A, C→B = 6 translators (3 apps)
2 With canonical model: A→M, M→A, B→M, M→B, C→M, M→C = 6 translators (3 apps)
3 Break-even at 3 applications; 6 apps: 30 vs 12
4 New field in M: every translator and every consumer is reviewed| جنبه | Canonical model | ترجمهٔ جفتی | Bounded contexts (DDD) |
|---|---|---|---|
| مترجم لازم | 2N | N×(N−1) | یکی برای هر رابطه، در یک ACL |
| تغییر یک فیلد | کمیته، همهٔ کاربران | دو طرف | فقط context مالک |
| معنای «Customer» | یکی، با مصالحه | هر چه هر جفت توافق کند | یکی برای هر context |
| الگوی شکست | کمترین مخرج مشترک، سالها جلسه | اسپاگتی | مفهوم تکراری، ترجمهٔ صریح |
| کجا مینشیند | دامنههای پایدار (پیامهای پرداخت، HL7 سلامت، ISO 20022) | چند سیستم | بیشتر شرکتهای محصولی |
قاعدهٔ ما: canonical فرمت پیام را فقط جایی به کار ببرید که صنعت قبلاً استانداردش کرده (ISO 20022 برای پرداخت، HL7 برای سلامت)؛ مدل دامنهٔ سراسری سازمان اختراع نکنید. سازوکار را در message transformation و جایگزین DDD را در context maps ببینید.
اسطورههای governance و reuse
مهم به زبان ساده: برنامههای SOA هیئت governance میساختند تا سرویسها را تأیید کند، بازبینی میکردند تا تکرار نشود و کاتالوگ میساختند تا سرویسهای reusable پیدا شوند، به این امید که هر پروژهٔ جدید از سرویسهای موجود سرهم شود.بدفهمی رایج: «اگر اول سرویسهای reusable بسازیم پروژهها ارزانتر میشوند.» reuse سرویس پایدار و عمومی میخواهد؛ سرویس عمومی ساختنش گرانتر است، کسی هزینهٔ اضافه را نمیدهد و بعد هر مصرفکننده پشت تیم مشترک منتظر میماند. تعبیر Fowler از نتیجه: «centralised governance models that actively inhibit change».
| اسطوره | چه شد | بهجایش چه کنیم |
|---|---|---|
| «سرویس reusable بساز، بعداً برنامهها را سرهم کن» | سرویسهایی برای هیچکس؛ مصرفکنندهها فیلد دیگری میخواستند | برای مصرفکنندهٔ اول بساز، در سومی عمومی کن |
| «هیئت مرکزی معماری را تمیز نگه میدارد» | هفتهها تأیید، دور زدن پنهانی | guardrail (linter، template)، بازبینی استثنایی |
| «registry سرویسها را قابلکشف میکند» | UDDI فراگیر نشد؛ registry پوسید | پورتال توسعهدهنده در مالکیت تیم ارائهدهنده |
| «ESB loose coupling میدهد» | هر جریان به تیم bus وابسته بود | smart endpoints, dumb pipes |
| «monolith را بپیچ، SOA داری» | همان قطار انتشار، با تأخیر تازه | استخراج بر اساس business capability |
| «یک canonical model هزینه را کم میکند» | مدل پرتغییرترین دارایی شد | مدل برای هر context + ترجمهٔ صریح |
| «موتور orchestration یعنی چابکی کسبوکار» | منطق کسبوکار در جریانهای XML پنهان شد | منطق را در کد با تست نگه دار |
Thoughtworks Technology Radar همین هشدار را در حلقهٔ hold گذاشته، زیر عنوان Overambitious API gateways: «One of our common complaints is the pushing of business smarts into middleware, resulting in application servers and enterprise service buses with ambitions to run critical application logic.» توصیه: دغدغههای عمومی (احراز هویت، rate limiting) در gateway و «any domain smarts such as data transformation or rule processing» در سرویسهای مالک.
SOA در برابر microservices
حیاتی به زبان ساده: SOA هوش را در لوله (bus) گذاشت و endpointها را نازک کرد؛ microservices هوش را در endpointها گذاشت و لوله را کودن.بدفهمی رایج: «microservices سرویسهای کوچک SOA هستند.» اندازه کماهمیتترین تفاوت است. Fowler: «the microservice style is very similar to what some advocates of SOA have been in favor of. The problem, however, is that SOA means too many different things, and that most of the time that we come across something called "SOA" it's significantly different to the style we're describing here, usually due to a focus on ESBs used to integrate monolithic applications.»
| بُعد | SOA (مبتنی بر orchestration، دههٔ ۲۰۰۰) | Microservices | Service-based architecture |
|---|---|---|---|
| هدف اصلی | reuse و یکپارچگی سراسری سازمان | تغییر و استقرار مستقل | تقسیم عملگرایانهٔ دامنه |
| اندازهٔ سرویس | business service بسیار درشت، enterprise service بسیار ریز | ریز، یک bounded context | درشت (حدود ۴ تا ۱۲ سرویس دامنه) |
| داده | پایگاهدادههای مشترک پشت wrapper، canonical model | پایگاهداده برای هر سرویس | اغلب یک پایگاهدادهٔ مشترک |
| لوله | هوشمند: ESB با routing، transformation، قواعد | کودن: HTTP یا broker | فراخوان مستقیم از UI؛ میانافزار کم |
| کنترل جریان | orchestrator مرکزی (BPEL، BPMN) | choreography با رویداد، saga محلی | داخل هر سرویس، تراکنش محلی |
| Governance | هیئت مرکزی، استانداردهای سازمانی | غیرمتمرکز، استاندارد تیمی | سبک، بهدست معمار |
| استقرار | سرویسها در application server، اغلب با هم منتشر میشوند | pipeline و container مستقل | چند استقرار مستقل |
| پروتکلها | SOAP، WSDL، WS-*، JMS، MQ | REST/JSON، gRPC، Kafka، AMQP | REST یا RPC از UI |
| سبک قرارداد | schemaهای XML canonical | API هر سرویس، consumer-driven contract | مشترک یا هر سرویس |
| مدیریت شکست | پیامرسانی مطمئن، XA / compensation در موتور | timeout، retry، circuit breaker، saga | تراکنش پایگاهداده |
| تیم معمول | تیم یکپارچهسازی مرکزی + تیمهای برنامه | تیم محصول مالک سرویس از ابتدا تا انتها | تیمهای دامنه، پلتفرم مشترک |
| کجا درد میکند | گلوگاه bus، کمیتهها، mapping XML | عملیات، داده توزیعشده، observability | coupling schema مشترک |
قاعدهٔ کوتاه: اگر برای هر تغییر یکپارچهسازی باید با یک تیم مشورت کنید، SOA به معنای دههٔ ۲۰۰۰ دارید، هر اسمی روی سرویسها باشد. بحث کامل در معماری microservices، ارتباط سرویسها و API gateway، BFF و service mesh است.
Service-based architecture: راه میانهٔ عملگرایانه
مهم به زبان ساده: سیستم را به چند سرویس بزرگِ دامنهمحور (مثلاً Orders، Payments، Customers) بشکنید، جدا مستقر کنید، معمولاً یک پایگاهداده مشترک، و UI مستقیم آنها را صدا بزند.بدفهمی رایج: «service-based و service-oriented یکیاند.» مقالهٔ Wikipedia دربارهٔ SOA یادداشتی دارد که «must not be confused»، و Richards و Ford آنها را دو سبک جدا میدانند: service-based نه ESB دارد، نه لایهٔ enterprise service، نه canonical model.
| ویژگی | Service-based architecture (Richards و Ford، بازنویسی) |
|---|---|
| تعداد سرویس | معمولاً ۴ تا ۱۲ «domain service» درشت |
| پایگاهداده | معمولاً یکی مشترک (با احتیاط میشود بهازای دامنه شکست) |
| یکپارچهسازی | UI یا لایهٔ API مستقیم سرویسها را صدا میزند؛ موتور orchestration نیست |
| استقرار | هر domain service مستقل مستقر میشود؛ pipeline خیلی کمتر از microservices |
| نقاط قوت | ارزان، قابلفهم، قابلتست، چابکی و جداسازی خطا خوب برای هزینه |
| نقاط ضعف | سرویسهای درشت هنوز schema را مشترکاً دارند؛ مقیاسپذیری و elasticity کمتر از microservices |
| تناسب | سیستمهای متوسط، تیمهای ۱۰ تا ۵۰ نفر، بخشهایی از modular monolith که استقرار مستقل میخواهند |
راه میانه در دنبالهٔ monolith در برابر microservices در برابر modular monolith جا میگیرد: اول modular monolith، بعد چند domain service استخراجشده، و microservices فقط جایی که مرز مقیاس یا تیم مستقل بخواهد.
ایدههای SOA که ماندند
| ایدهٔ SOA | امروز کجاست | مثال |
|---|---|---|
| طراحی contract-first | OpenAPI، protobuf، AsyncAPI، تست consumer-driven contract | contract/transfers.openapi.yaml همین فصل |
| Service registry | service discovery، پورتال توسعهدهنده، کاتالوگ API | Consul، Kubernetes Services، Backstage |
| mediation و policy در ESB | API gateway و management: auth، quota، نسخهبندی، analytics | Kong، Apigee، AWS API Gateway، Traefik؛ ببینید gatewayها |
| پل پروتکل در ESB | iPaaS و چارچوبهای یکپارچهسازی | Apache Camel، Spring Integration، MuleSoft |
| Canonical model | استانداردهای صنعتی؛ schema registry برای رویدادها | ISO 20022، schemaهای Avro در Confluent Schema Registry |
| موتور orchestration | workflow engine پایدار، saga | Temporal، Camunda، زنجیرهٔ صف Laravel، ببینید durable workflows |
| Enterprise integration patterns | واژگان هر سیستم مبتنی بر broker | Router، Translator، Splitter؛ ببینید routing |
| Infrastructure services | قابلیتهای پلتفرم | IdP مرکزی، pipeline مرکزی audit، observability |
| Service description و policy | policyهای gateway، پیکربندی service mesh | mTLS، retry در Envoy |
کاتالوگ EIP از Hohpe و Woolf ماندگارترین دستاورد دورهٔ SOA است؛ الگوهایش واژگان messaging امروزند.
یکپارچهسازی سیستم قدیمی: endpointهای SOAP هنوز هستند
حیاتی به زبان ساده: بانکها، بیمهها، سامانههای مالیات و گمرک، صورتحساب مخابرات و مجموعههای ERP (SAP، Oracle) هنوز سرویس SOAP/WSDL منتشر میکنند و دههها هم خواهند کرد. شما مصرفشان خواهید کرد.بدفهمی رایج: «از کد دامنه صدایش میزنیم.» آنوقت رشتههای اعشاری قدیمی، کدهای پاسخ («51»)، namespaceها و شکل faultها به همهٔ سرویسها نفوذ میکند. قرارداد قدیمی را پشت یک anti-corruption layer (اصطلاحی از domain-driven design) بگذارید: adapterای که همهٔ ترجمه را دارد تا بقیهٔ سیستم یک port تمیز ببیند. صفحهٔ الگوی Microsoft هدفش را میگوید: it «helps ensure that new component design remains uninfluenced by legacy implementations that might have different data models or business rules when you integrate with these legacy systems.»
| دغدغه | قاعده برای اتصال SOAP | کجا در کد ما |
|---|---|---|
| مرز | یک adapter، port دامنه را پیاده میکند | acl/adapter.go، LegacyTransferAdapter.php |
| پول | درون: عدد صحیح واحد خرد؛ رشتهٔ اعشاری فقط در لبه | decimal() در هر دو adapter |
| خطاها | کدهای قدیمی را یک بار به خطای دامنه نگاشت کن | translate() |
| Faultها | fault در SOAP 1.1 با HTTP 500 و body میآید: اول parse کن | soapclient/client.go |
| Timeout | همیشه connect timeout و timeout کل بگذار | connection_timeout، Http::timeout() |
| Retry | فقط وقتی ارائهدهنده با reference تکراریزدایی میکند | فیلد Reference = idempotency key |
| WSDL | cache کن؛ برای هر درخواست دانلود نکن | WSDL_CACHE_DISK |
| Contract drift | یک fixture ضبطشده و contract test نگه دار | round-trip در client_test.go |
| Strangler | ترافیک تازه را به سرویس جدید ببر، adapter را کوچک کن | strangler fig |
Go
کتابخانهٔ استاندارد Go تولیدکنندهٔ کد WSDL ندارد. برای یکی دو عملیات سادهتر است envelope را با structهای encoding/xml مدل کنید تا stub تولید کنید؛ برای WSDLهای بزرگ با یک ابزار structها را تولید کنید و همین شکل را نگه دارید. مستند پکیج encoding/xml میگوید «implements a simple XML 1.0 parser that understands XML name spaces»، و tagهای namespace (xml:"urn:... TransferFunds") باعث میشوند envelope رفتوبرگشت کند.
Port دامنه
// Package transfer is the domain model of the transfer capability.
// It knows nothing about SOAP, XML, HTTP or JSON.
package transfer
import (
"context"
"errors"
)
// Money is an integer amount of minor units (cents, rials) plus an ISO 4217 code.
type Money struct {
Minor int64
Currency string
}
// Transfer is one request to move money between two accounts.
// ID doubles as the idempotency key towards every downstream system.
type Transfer struct {
ID string
From string
To string
Amount Money
}
// Receipt proves the transfer was accepted by the system of record.
type Receipt struct {
TransferID string
AuthCode string
}
// Domain errors. Callers branch on these, never on legacy response codes.
var (
ErrInsufficientFunds = errors.New("insufficient funds")
ErrAccountRestricted = errors.New("account restricted")
ErrUnavailable = errors.New("system of record unavailable") // retryable
ErrRejected = errors.New("transfer rejected")
)
// Port is what the rest of the system depends on. The SOAP adapter and a
// future native service both implement it.
type Port interface {
Transfer(ctx context.Context, t Transfer) (Receipt, error)
}کلاینت SOAP 1.1 با encoding/xml
// Package soapclient is a minimal SOAP 1.1 client built on encoding/xml.
// Go has no WSDL code generator in the standard library, so the envelope,
// the operation messages and the Fault are plain structs.
package soapclient
import (
"bytes"
"context"
"encoding/xml"
"fmt"
"io"
"net/http"
)
const (
// EnvelopeNS is the SOAP 1.1 envelope namespace.
EnvelopeNS = "http://schemas.xmlsoap.org/soap/envelope/"
// ServiceNS is the target namespace declared in the WSDL.
ServiceNS = "urn:example:bank:transfer:v1"
// ActionTransferFunds is the SOAPAction HTTP header value for the operation.
ActionTransferFunds = ServiceNS + "/TransferFunds"
)
// TransferFundsRequest is the wrapped document/literal request message.
type TransferFundsRequest struct {
XMLName xml.Name `xml:"urn:example:bank:transfer:v1 TransferFunds"`
FromAccount string `xml:"fromAccount"`
ToAccount string `xml:"toAccount"`
Amount string `xml:"amount"` // decimal string such as "125.50"
Currency string `xml:"currency"`
Reference string `xml:"reference"`
}
// TransferFundsResponse is the success message.
type TransferFundsResponse struct {
XMLName xml.Name `xml:"urn:example:bank:transfer:v1 TransferFundsResponse"`
Status string `xml:"status"`
AuthCode string `xml:"authCode"`
}
// Fault is the SOAP 1.1 fault. faultcode and faultstring are unqualified.
type Fault struct {
Code string `xml:"faultcode"`
String string `xml:"faultstring"`
Detail struct {
ErrorCode string `xml:"ErrorCode"` // legacy business code, for example "51"
} `xml:"detail"`
}
// FaultError lets callers use errors.As on a SOAP fault.
type FaultError struct{ Fault Fault }
func (e *FaultError) Error() string {
return fmt.Sprintf("soap fault %s: %s (legacy code %q)", e.Fault.Code, e.Fault.String, e.Fault.Detail.ErrorCode)
}
type requestEnvelope struct {
XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Envelope"`
Body struct {
Content any `xml:",any"`
} `xml:"http://schemas.xmlsoap.org/soap/envelope/ Body"`
}
type responseEnvelope struct {
XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Envelope"`
Body struct {
Fault *Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault"`
Response *TransferFundsResponse `xml:"urn:example:bank:transfer:v1 TransferFundsResponse"`
} `xml:"http://schemas.xmlsoap.org/soap/envelope/ Body"`
}
// Client calls one SOAP endpoint over HTTP POST.
type Client struct {
Endpoint string
HTTP *http.Client
}
// TransferFunds sends the operation and decodes either the response or the fault.
func (c *Client) TransferFunds(ctx context.Context, in TransferFundsRequest) (*TransferFundsResponse, error) {
var env requestEnvelope
env.Body.Content = in
payload, err := xml.Marshal(env)
if err != nil {
return nil, fmt.Errorf("marshal envelope: %w", err)
}
body := append([]byte(xml.Header), payload...)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.Endpoint, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "text/xml; charset=utf-8") // SOAP 1.1
req.Header.Set("SOAPAction", `"`+ActionTransferFunds+`"`)
hc := c.HTTP
if hc == nil {
hc = http.DefaultClient
}
res, err := hc.Do(req)
if err != nil {
return nil, fmt.Errorf("soap transport: %w", err)
}
defer res.Body.Close()
raw, err := io.ReadAll(io.LimitReader(res.Body, 1<<20))
if err != nil {
return nil, fmt.Errorf("read soap response: %w", err)
}
// SOAP 1.1 over HTTP: faults come back as HTTP 500 with a Fault in the body,
// so decode the body before looking at the status code.
var out responseEnvelope
if err := xml.Unmarshal(raw, &out); err != nil {
return nil, fmt.Errorf("soap http %d, body is not a SOAP envelope: %w", res.StatusCode, err)
}
if out.Body.Fault != nil {
return nil, &FaultError{Fault: *out.Body.Fault}
}
if out.Body.Response == nil {
return nil, fmt.Errorf("soap http %d: empty body", res.StatusCode)
}
return out.Body.Response, nil
}سه نکته. بدنهٔ درخواست از نوع any است تا یک envelope به همهٔ عملیات بخورد. envelope پاسخ هم اشارهگر Fault دارد هم Response: هرکدام non-nil بود میگوید کدام رسیده. و status code آخر خوانده میشود چون faultهای SOAP 1.1 با HTTP 500 میآیند. فایل httptest کنارش (client_test.go) یک round-trip واقعی برای موفقیت و برای fault اجرا میکند؛ go vet اشتباه namespace را نمیگیرد، round-trip میگیرد.
Anti-corruption layer
// Package acl is the anti-corruption layer between the clean transfer domain
// and the legacy SOAP core-banking service. Everything legacy stays in here.
package acl
import (
"context"
"errors"
"fmt"
"academy/service-oriented-architecture/soapclient"
"academy/service-oriented-architecture/transfer"
)
// Legacy is the part of the SOAP client the adapter needs (easy to fake).
type Legacy interface {
TransferFunds(ctx context.Context, in soapclient.TransferFundsRequest) (*soapclient.TransferFundsResponse, error)
}
// Adapter implements transfer.Port on top of the legacy SOAP service.
type Adapter struct{ Legacy Legacy }
var _ transfer.Port = (*Adapter)(nil)
// exponents lists the minor-unit exponent per currency (ISO 4217).
var exponents = map[string]int{"EUR": 2, "USD": 2, "JPY": 0, "KWD": 3}
// Transfer translates the domain request, calls SOAP, translates the answer.
func (a *Adapter) Transfer(ctx context.Context, t transfer.Transfer) (transfer.Receipt, error) {
amount, err := decimal(t.Amount)
if err != nil {
return transfer.Receipt{}, err
}
res, err := a.Legacy.TransferFunds(ctx, soapclient.TransferFundsRequest{
FromAccount: t.From,
ToAccount: t.To,
Amount: amount,
Currency: t.Amount.Currency,
Reference: t.ID, // the legacy system de-duplicates on Reference
})
if err != nil {
return transfer.Receipt{}, translate(err)
}
if res.Status != "00" {
return transfer.Receipt{}, fmt.Errorf("%w: legacy status %s", transfer.ErrRejected, res.Status)
}
return transfer.Receipt{TransferID: t.ID, AuthCode: res.AuthCode}, nil
}
// translate maps legacy codes to domain errors; this is the whole point of the layer.
func translate(err error) error {
var fe *soapclient.FaultError
if !errors.As(err, &fe) {
return fmt.Errorf("%w: %v", transfer.ErrUnavailable, err) // transport trouble is retryable
}
switch fe.Fault.Detail.ErrorCode {
case "51":
return transfer.ErrInsufficientFunds
case "62":
return transfer.ErrAccountRestricted
case "91":
return fmt.Errorf("%w: %s", transfer.ErrUnavailable, fe.Fault.String)
default:
return fmt.Errorf("%w: legacy code %s", transfer.ErrRejected, fe.Fault.Detail.ErrorCode)
}
}
// decimal renders minor units as the decimal string the legacy contract wants.
func decimal(m transfer.Money) (string, error) {
exp, ok := exponents[m.Currency]
if !ok || m.Minor <= 0 {
return "", fmt.Errorf("%w: unsupported amount %d %s", transfer.ErrRejected, m.Minor, m.Currency)
}
if exp == 0 {
return fmt.Sprintf("%d", m.Minor), nil
}
pow := int64(1)
for i := 0; i < exp; i++ {
pow *= 10
}
return fmt.Sprintf("%d.%0*d", m.Minor/pow, exp, m.Minor%pow), nil
}همان قابلیت بهصورت سرویس REST/JSON با قرارداد contract-first
اول قرارداد نوشته میشود:
openapi: 3.1.0
info:
title: Transfers API
version: 1.0.0
description: Contract-first REST/JSON facade over the transfer capability.
paths:
/v1/transfers:
post:
operationId: createTransfer
summary: Move money between two accounts.
parameters:
- name: Idempotency-Key
in: header
required: true
schema: { type: string, maxLength: 64 }
description: Same key, same answer. The key is also the transfer id.
requestBody:
required: true
content:
application/json:
schema: { $ref: '#/components/schemas/CreateTransfer' }
responses:
'201':
description: Transfer completed.
content:
application/json:
schema: { $ref: '#/components/schemas/Transfer' }
'200':
description: Replay of an earlier request with the same key.
content:
application/json:
schema: { $ref: '#/components/schemas/Transfer' }
'422':
description: Business rule failed (insufficient funds, rejected).
content:
application/problem+json:
schema: { $ref: '#/components/schemas/Problem' }
'503':
description: Downstream unavailable. Retry with the same key after Retry-After.
headers:
Retry-After: { schema: { type: integer } }
content:
application/problem+json:
schema: { $ref: '#/components/schemas/Problem' }
components:
schemas:
Money:
type: object
required: [minor, currency]
properties:
minor: { type: integer, minimum: 1, description: Minor units (cents). }
currency: { type: string, pattern: '^[A-Z]{3}$' }
CreateTransfer:
type: object
additionalProperties: false
required: [from, to, amount]
properties:
from: { type: string }
to: { type: string }
amount: { $ref: '#/components/schemas/Money' }
Transfer:
type: object
required: [id, status]
properties:
id: { type: string }
status: { type: string, enum: [completed] }
authCode: { type: string }
Problem:
type: object
required: [type, title, status]
properties:
type: { type: string }
title: { type: string }
status: { type: integer }handler آن را روی port دامنه پیاده میکند، پس مهم نیست port همان adapter SOAP باشد یا یک سرویس بومی آینده:
// Package restapi exposes the transfer capability as a contract-first
// REST/JSON service. The contract is contract/transfers.openapi.yaml.
package restapi
import (
"encoding/json"
"errors"
"net/http"
"sync"
"academy/service-oriented-architecture/transfer"
)
type createTransfer struct {
From string `json:"from"`
To string `json:"to"`
Amount struct {
Minor int64 `json:"minor"`
Currency string `json:"currency"`
} `json:"amount"`
}
type transferResource struct {
ID string `json:"id"`
Status string `json:"status"`
AuthCode string `json:"authCode"`
}
// problem follows RFC 9457 (application/problem+json).
type problem struct {
Type string `json:"type"`
Title string `json:"title"`
Status int `json:"status"`
}
// Handler serves POST /v1/transfers on top of any transfer.Port.
type Handler struct {
Port transfer.Port
mu sync.Mutex
seen map[string]transferResource // Idempotency-Key -> first answer
}
// Routes registers the single operation of the contract.
func (h *Handler) Routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("POST /v1/transfers", h.create)
return mux
}
func (h *Handler) create(w http.ResponseWriter, r *http.Request) {
key := r.Header.Get("Idempotency-Key")
if key == "" {
write(w, http.StatusBadRequest, "application/problem+json", problem{"/problems/missing-idempotency-key", "Idempotency-Key header is required", 400})
return
}
h.mu.Lock()
if prev, ok := h.seen[key]; ok {
h.mu.Unlock()
write(w, http.StatusOK, "application/json", prev) // replay, not a second transfer
return
}
h.mu.Unlock()
var in createTransfer
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<16))
dec.DisallowUnknownFields()
if err := dec.Decode(&in); err != nil {
write(w, http.StatusBadRequest, "application/problem+json", problem{"/problems/invalid-body", "Invalid request body", 400})
return
}
rc, err := h.Port.Transfer(r.Context(), transfer.Transfer{
ID: key, From: in.From, To: in.To,
Amount: transfer.Money{Minor: in.Amount.Minor, Currency: in.Amount.Currency},
})
if err != nil {
st, p := mapError(err)
if st == http.StatusServiceUnavailable {
w.Header().Set("Retry-After", "5")
}
write(w, st, "application/problem+json", p)
return
}
res := transferResource{ID: rc.TransferID, Status: "completed", AuthCode: rc.AuthCode}
h.mu.Lock()
if h.seen == nil {
h.seen = map[string]transferResource{}
}
h.seen[key] = res
h.mu.Unlock()
write(w, http.StatusCreated, "application/json", res)
}
func mapError(err error) (int, problem) {
switch {
case errors.Is(err, transfer.ErrInsufficientFunds):
return 422, problem{"/problems/insufficient-funds", "Insufficient funds", 422}
case errors.Is(err, transfer.ErrAccountRestricted):
return 403, problem{"/problems/account-restricted", "Account restricted", 403}
case errors.Is(err, transfer.ErrUnavailable):
return 503, problem{"/problems/unavailable", "Temporarily unavailable, retry with the same key", 503}
default:
return 422, problem{"/problems/rejected", "Transfer rejected", 422}
}
}
func write(w http.ResponseWriter, status int, ct string, v any) {
w.Header().Set("Content-Type", ct)
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}به الزام Idempotency-Key دقت کنید. سرویس SOAP قدیمی انتقال را با reference میشناسد؛ نمای REST کلید را بهعنوان همان reference عبور میدهد. retry کلاینت آنوقت سرتاسر امن میشود، ببینید API idempotency و idempotent consumers.
زاویهٔ Go
| موضوع | رویکرد Go | نکته |
|---|---|---|
| XML | structهای encoding/xml با tag مربوط به namespace | Unmarshal بهطور پیشفرض المان ناشناخته را نادیده میگیرد: tolerant reader |
| HTTP client | net/http با http.Client{Timeout} و context | همیشه timeout بگذارید؛ کلاینت پیشفرض ندارد |
| Routing | http.ServeMux با الگوی متد (POST /v1/transfers) | به کتابخانهٔ router نیازی نیست |
| Contract-first | از OpenAPI stub سرور تولید کنید (oapi-codegen) یا دستی بنویسید | YAML را در مخزن نگه دارید |
| کتابخانههای SOAP | شخص ثالث (gosoap، hooklift/gowsdl) | کد تولیدشده را بخوانید و بعد اعتماد کنید |
| تست | httptest.NewServer و envelopeهای ضبطشده | برای هر کد fault یک تست |
Laravel
PHP کلاس SoapClient را در ext-soap دارد. راهنمای PHP میگوید «can be used in WSDL or non-WSDL mode»؛ در حالت WSDL هر عملیات یک متد میشود. وقتی retry، fake و logging کلاینت HTTP لاراول را میخواهید، آن جایگزین است، به بهای ساختن دستی envelope (Http::withBody($xml, 'text/xml') همان فراخوان مستند بدنهٔ خام است).
Port و exceptionهای دامنه
<?php
declare(strict_types=1);
namespace App\Transfers;
/** What the application depends on. Neither SOAP nor HTTP appears here. */
interface TransferPort
{
/** @throws InsufficientFunds|AccountRestricted|TransferUnavailable|TransferRejected */
public function transfer(TransferRequest $request): Receipt;
}
final readonly class TransferRequest
{
public function __construct(
public string $id, // idempotency key, also the legacy "reference"
public string $from,
public string $to,
public int $amountMinor, // minor units, never floats
public string $currency,
) {}
}
final readonly class Receipt
{
public function __construct(public string $transferId, public string $authCode) {}
}
class TransferException extends \RuntimeException {}
final class InsufficientFunds extends TransferException {}
final class AccountRestricted extends TransferException {}
final class TransferUnavailable extends TransferException {} // retryable
final class TransferRejected extends TransferException {}مصرف WSDL با SoapClient پشت anti-corruption layer
اول قراردادی که طرف قدیمی منتشر میکند:
<?xml version="1.0" encoding="UTF-8"?>
<!-- WSDL 1.1, document/literal wrapped: the contract of the legacy core-banking service. -->
<wsdl:definitions name="TransferService"
targetNamespace="urn:example:bank:transfer:v1"
xmlns:tns="urn:example:bank:transfer:v1"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
<wsdl:types>
<xsd:schema targetNamespace="urn:example:bank:transfer:v1" elementFormDefault="qualified">
<xsd:element name="TransferFunds">
<xsd:complexType><xsd:sequence>
<xsd:element name="fromAccount" type="xsd:string"/>
<xsd:element name="toAccount" type="xsd:string"/>
<xsd:element name="amount" type="xsd:decimal"/>
<xsd:element name="currency" type="xsd:string"/>
<xsd:element name="reference" type="xsd:string"/>
</xsd:sequence></xsd:complexType>
</xsd:element>
<xsd:element name="TransferFundsResponse">
<xsd:complexType><xsd:sequence>
<xsd:element name="status" type="xsd:string"/>
<xsd:element name="authCode" type="xsd:string"/>
</xsd:sequence></xsd:complexType>
</xsd:element>
</xsd:schema>
</wsdl:types>
<wsdl:message name="TransferFundsIn"><wsdl:part name="parameters" element="tns:TransferFunds"/></wsdl:message>
<wsdl:message name="TransferFundsOut"><wsdl:part name="parameters" element="tns:TransferFundsResponse"/></wsdl:message>
<wsdl:portType name="TransferPort">
<wsdl:operation name="TransferFunds">
<wsdl:input message="tns:TransferFundsIn"/>
<wsdl:output message="tns:TransferFundsOut"/>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="TransferSoapBinding" type="tns:TransferPort">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="TransferFunds">
<soap:operation soapAction="urn:example:bank:transfer:v1/TransferFunds"/>
<wsdl:input><soap:body use="literal"/></wsdl:input>
<wsdl:output><soap:body use="literal"/></wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="TransferService">
<wsdl:port name="TransferSoapPort" binding="tns:TransferSoapBinding">
<soap:address location="https://core.bank.example/ws/transfer"/>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>بعد adapter:
<?php
declare(strict_types=1);
namespace App\Transfers;
use SoapClient;
use SoapFault;
/**
* Anti-corruption layer: the only class that knows the legacy WSDL, decimal
* strings and ISO-8583-style response codes. Everything else sees TransferPort.
*/
final class LegacyTransferAdapter implements TransferPort
{
private const EXPONENTS = ['EUR' => 2, 'USD' => 2, 'JPY' => 0, 'KWD' => 3];
public function __construct(private readonly SoapClient $soap) {}
/** Build the client once; see config/services.php for the values. */
public static function fromConfig(): self
{
return new self(new SoapClient(config('services.core_bank.wsdl'), [
'soap_version' => SOAP_1_1,
'exceptions' => true, // failures become SoapFault
'trace' => false,
'connection_timeout' => 3, // connect timeout, seconds
'cache_wsdl' => WSDL_CACHE_DISK, // do not re-download the WSDL per request
]));
}
public function transfer(TransferRequest $request): Receipt
{
try {
// Document/literal wrapped: one argument object per call.
$response = $this->soap->TransferFunds([
'fromAccount' => $request->from,
'toAccount' => $request->to,
'amount' => $this->decimal($request->amountMinor, $request->currency),
'currency' => $request->currency,
'reference' => $request->id,
]);
} catch (SoapFault $fault) {
throw $this->translate($fault);
}
if ($response->status !== '00') {
throw new TransferRejected("legacy status {$response->status}");
}
return new Receipt($request->id, (string) $response->authCode);
}
private function translate(SoapFault $fault): TransferException
{
// The business code travels in <detail><ErrorCode>. Depending on the server's
// WSDL, PHP exposes detail as an object or as a raw string; handle both.
$detail = $fault->detail ?? null;
$code = match (true) {
is_object($detail) => (string) ($detail->ErrorCode ?? ''),
is_string($detail) => preg_match('~<ErrorCode>(\w+)</ErrorCode>~', $detail, $m) ? $m[1] : '',
default => '',
};
return match ($code) {
'51' => new InsufficientFunds(),
'62' => new AccountRestricted(),
'91', '' => new TransferUnavailable($fault->getMessage(), 0, $fault), // transport faults have no code
default => new TransferRejected("legacy code {$code}", 0, $fault),
};
}
private function decimal(int $minor, string $currency): string
{
$exp = self::EXPONENTS[$currency] ?? throw new TransferRejected("unsupported currency {$currency}");
if ($minor <= 0) {
throw new TransferRejected('amount must be positive');
}
$pow = 10 ** $exp;
return $exp === 0
? (string) $minor
: sprintf('%d.%0' . $exp . 'd', intdiv($minor, $pow), $minor % $pow);
}
}همان فراخوان با کلاینت HTTP لاراول
<?php
declare(strict_types=1);
namespace App\Transfers;
use Illuminate\Support\Facades\Http;
/**
* The same call without ext-soap: Laravel's HTTP client with a hand-built
* SOAP 1.1 envelope. Useful when you want retries, timeouts, fakes and logging
* from the HTTP client instead of SoapClient.
*/
final class RawSoapOverHttpClient
{
private const NS = 'urn:example:bank:transfer:v1';
public function transferFunds(TransferRequest $r, string $amountDecimal): \SimpleXMLElement
{
$xml = sprintf(
'<?xml version="1.0" encoding="UTF-8"?>'
. '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:t="%s">'
. '<soapenv:Body><t:TransferFunds><t:fromAccount>%s</t:fromAccount><t:toAccount>%s</t:toAccount>'
. '<t:amount>%s</t:amount><t:currency>%s</t:currency><t:reference>%s</t:reference></t:TransferFunds>'
. '</soapenv:Body></soapenv:Envelope>',
self::NS,
htmlspecialchars($r->from, ENT_XML1), htmlspecialchars($r->to, ENT_XML1),
$amountDecimal, htmlspecialchars($r->currency, ENT_XML1), htmlspecialchars($r->id, ENT_XML1),
);
$response = Http::withBody($xml, 'text/xml; charset=utf-8')
->withHeaders(['SOAPAction' => '"' . self::NS . '/TransferFunds"'])
->timeout(5)
->retry(2, 200, throw: false) // safe only because the legacy side de-duplicates on <reference>
->post(config('services.core_bank.endpoint'));
// SOAP 1.1 faults arrive as HTTP 500 with a body, so parse before judging the status.
$doc = simplexml_load_string($response->body());
if ($doc === false) {
throw new TransferUnavailable('legacy answered with a non-XML body, HTTP ' . $response->status());
}
return $doc;
}
}عرضهٔ قرارداد REST/JSON
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Transfers\AccountRestricted;
use App\Transfers\InsufficientFunds;
use App\Transfers\TransferPort;
use App\Transfers\TransferRejected;
use App\Transfers\TransferRequest;
use App\Transfers\TransferUnavailable;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
/** Contract-first REST/JSON facade; shape defined by contract/transfers.openapi.yaml. */
final class TransferController
{
public function __construct(private readonly TransferPort $transfers) {}
public function store(Request $request): JsonResponse
{
$key = $request->header('Idempotency-Key');
if ($key === null || $key === '') {
return $this->problem(400, 'missing-idempotency-key', 'Idempotency-Key header is required');
}
$data = $request->validate([
'from' => ['required', 'string'],
'to' => ['required', 'string'],
'amount.minor' => ['required', 'integer', 'min:1'],
'amount.currency' => ['required', 'string', 'size:3'],
]);
// Replay: the same key returns the first answer and calls nobody.
if ($first = Cache::get("transfer:$key")) {
return response()->json($first, 200);
}
try {
$receipt = $this->transfers->transfer(new TransferRequest(
$key, $data['from'], $data['to'], $data['amount']['minor'], $data['amount']['currency'],
));
} catch (InsufficientFunds) {
return $this->problem(422, 'insufficient-funds', 'Insufficient funds');
} catch (AccountRestricted) {
return $this->problem(403, 'account-restricted', 'Account restricted');
} catch (TransferUnavailable) {
return $this->problem(503, 'unavailable', 'Temporarily unavailable, retry with the same key')
->header('Retry-After', '5');
} catch (TransferRejected) {
return $this->problem(422, 'rejected', 'Transfer rejected');
}
$body = ['id' => $receipt->transferId, 'status' => 'completed', 'authCode' => $receipt->authCode];
Cache::put("transfer:$key", $body, now()->addDay());
return response()->json($body, 201);
}
private function problem(int $status, string $type, string $title): JsonResponse
{
return response()->json(
['type' => "/problems/$type", 'title' => $title, 'status' => $status],
$status,
['Content-Type' => 'application/problem+json'],
);
}
}<?php
declare(strict_types=1);
use App\Http\Controllers\TransferController;
use App\Transfers\LegacyTransferAdapter;
use App\Transfers\TransferPort;
use Illuminate\Support\Facades\Route;
// routes/api.php: the SOAP service is hidden behind the port.
// In a service provider: $this->app->bind(TransferPort::class, fn () => LegacyTransferAdapter::fromConfig());
Route::post('/v1/transfers', [TransferController::class, 'store'])->middleware('throttle:60,1');
// config/services.php:
// 'core_bank' => ['wsdl' => env('CORE_BANK_WSDL'), 'endpoint' => env('CORE_BANK_ENDPOINT')],زاویهٔ Laravel
| موضوع | رویکرد Laravel 13 / PHP 8.4 | نکته |
|---|---|---|
| کلاینت SOAP | SoapClient (ext-soap)، SOAP_1_1، exceptions => true، connection_timeout، cache_wsdl | SoapFault را بگیرید؛ در exception دامنه بپیچید |
| SOAP روی HTTP | Http::withBody()، withHeaders()، timeout()، retry() | در تست با Http::fake() جعل کنید |
| سرور SOAP | توکار نیست؛ SoapServer یا بسته، یا اصلاً نه | به سیستم جدید SOAP اضافه نکنید |
| اتصال port | $this->app->bind(TransferPort::class, ...) در provider | بعداً adapter را با سرویس بومی عوض کنید |
| اعتبارسنجی | $request->validate([...]) با کلیدهای نقطهدار | با schema در OpenAPI یکی است |
| Idempotency | Cache::get/Cache::put با کلید header، یا کلید یکتای پایگاهداده | برای پول از پایگاهداده استفاده کنید |
| Orchestration | یک کلاس سرویس یا Bus::chain() + جدول فرایند | ببینید مثال کامل |
| Choreography | رویداد و listener صفدار، ترجیحاً با broker | ببینید outbox |
مثال کامل: انتقال بانکی، به دو روش
مشتری ۱۲۵٫۵۰ یورو از حساب A به B منتقل میکند. تواناییها: بررسی تقلب (fraud)، بدهکار کردن (debit)، بستانکار کردن (credit)، اعلان. همین عملیات کسبوکار در دو سبک.
سبک SOA: یک orchestrator
// Package orchestrator is the SOA-style transfer: one central process owns the
// flow, calls each service in order and compensates in reverse on failure.
package orchestrator
import (
"context"
"errors"
"fmt"
)
// Services are the capabilities the orchestrator composes.
type Services interface {
CheckFraud(ctx context.Context, transferID string, minor int64) error
Debit(ctx context.Context, transferID, account string, minor int64) error
Credit(ctx context.Context, transferID, account string, minor int64) error
Refund(ctx context.Context, transferID, account string, minor int64) error
Notify(ctx context.Context, transferID string) error
}
// Store persists the process state so a crashed orchestrator can resume.
type Store interface {
Save(ctx context.Context, transferID, state string) error
}
// Orchestrator holds the whole business flow in one place.
type Orchestrator struct {
Svc Services
State Store
}
// Run executes the transfer. Every step is logged to the store first.
func (o *Orchestrator) Run(ctx context.Context, id, from, to string, minor int64) error {
step := func(state string, fn func() error) error {
if err := o.State.Save(ctx, id, state); err != nil {
return err
}
return fn()
}
if err := step("FRAUD_CHECK", func() error { return o.Svc.CheckFraud(ctx, id, minor) }); err != nil {
_ = o.State.Save(ctx, id, "REJECTED")
return fmt.Errorf("fraud: %w", err)
}
if err := step("DEBITING", func() error { return o.Svc.Debit(ctx, id, from, minor) }); err != nil {
_ = o.State.Save(ctx, id, "FAILED")
return fmt.Errorf("debit: %w", err)
}
if err := step("CREDITING", func() error { return o.Svc.Credit(ctx, id, to, minor) }); err != nil {
// Compensation: undo the debit. This line is the saga, written as code.
if rerr := o.Svc.Refund(ctx, id, from, minor); rerr != nil {
_ = o.State.Save(ctx, id, "NEEDS_MANUAL_REVIEW")
return errors.Join(fmt.Errorf("credit: %w", err), fmt.Errorf("refund: %w", rerr))
}
_ = o.State.Save(ctx, id, "COMPENSATED")
return fmt.Errorf("credit: %w", err)
}
_ = o.State.Save(ctx, id, "COMPLETED")
_ = o.Svc.Notify(ctx, id) // best effort: a failed email must not undo money
return nil
}<?php
declare(strict_types=1);
namespace App\Transfers;
use Illuminate\Support\Facades\DB;
/**
* SOA style: one orchestrator owns the flow, persists its state in a process
* table and compensates in reverse order. The services below are plain interfaces.
*/
final class OrchestratedTransfer
{
public function __construct(
private readonly FraudService $fraud,
private readonly AccountsService $accounts,
private readonly NotificationService $notifications,
) {}
public function run(string $id, string $from, string $to, int $minor): void
{
$state = fn (string $s) => DB::table('transfer_process')->updateOrInsert(
['transfer_id' => $id], ['state' => $s, 'updated_at' => now()],
);
$state('FRAUD_CHECK');
$this->fraud->check($id, $minor); // throws on reject
$state('DEBITING');
$this->accounts->debit($id, $from, $minor);
$state('CREDITING');
try {
$this->accounts->credit($id, $to, $minor);
} catch (\Throwable $e) {
$this->accounts->refund($id, $from, $minor); // compensation, same idempotency key
$state('COMPENSATED');
throw $e;
}
$state('COMPLETED');
rescue(fn () => $this->notifications->send($id)); // best effort, never undoes money
}
}
interface FraudService { public function check(string $id, int $minor): void; }
interface AccountsService
{
public function debit(string $id, string $account, int $minor): void;
public function credit(string $id, string $account, int $minor): void;
public function refund(string $id, string $account, int $minor): void;
}
interface NotificationService { public function send(string $id): void; }orchestrator پیش از هر گام state را ذخیره میکند تا بعد از crash ادامه بدهد، نه تکرار کند و نه فراموش:
CREATE TABLE transfer_process (
transfer_id text PRIMARY KEY, -- also the idempotency key
state text NOT NULL, -- FRAUD_CHECK, DEBITING, CREDITING, COMPLETED, COMPENSATED, NEEDS_MANUAL_REVIEW
updated_at timestamptz NOT NULL DEFAULT now()
);
-- A recovery job resumes anything stuck for more than a minute.
SELECT transfer_id, state FROM transfer_process
WHERE state IN ('DEBITING', 'CREDITING') AND updated_at < now() - interval '1 minute'
FOR UPDATE SKIP LOCKED; 1 Client -> Orchestrator: TransferFunds(t1, A, B, 125.50)
2 Orchestrator -> Fraud: check(t1) OK
3 Orchestrator -> Accounts: debit(t1, A) OK state=DEBITING
4 Orchestrator -> Accounts: credit(t1, B) FAIL beneficiary closed
5 Orchestrator -> Accounts: refund(t1, A) OK state=COMPENSATED
6 Orchestrator -> Client: error: beneficiary closedسبک میکروسرویس: choreography
// Package choreography is the microservice-style transfer: no central brain.
// Each service reacts to events and publishes its own; the bus is dumb.
package choreography
import "sync"
// Event is a fact that already happened.
type Event struct {
Name string // for example "TransferRequested"
TransferID string
Minor int64
}
// Bus is a synchronous in-memory pipe. A real system uses a broker such as
// RabbitMQ or Kafka, and then delivery is asynchronous and at-least-once.
type Bus struct {
mu sync.Mutex
subs map[string][]func(Event)
Log []string
}
// Subscribe registers a handler for one event name.
func (b *Bus) Subscribe(name string, h func(Event)) {
b.mu.Lock()
defer b.mu.Unlock()
if b.subs == nil {
b.subs = map[string][]func(Event){}
}
b.subs[name] = append(b.subs[name], h)
}
// Publish delivers to every subscriber and records the event name.
func (b *Bus) Publish(e Event) {
b.mu.Lock()
b.Log = append(b.Log, e.Name)
hs := append([]func(Event){}, b.subs[e.Name]...)
b.mu.Unlock()
for _, h := range hs {
h(e)
}
}
// Wire connects three services. Nobody owns the flow; it emerges from who
// listens to what. Funds is a stand-in for the accounts service.
func Wire(b *Bus, fraudOK func(Event) bool, debit func(Event) bool) {
// Fraud service: TransferRequested -> TransferApproved | TransferRejected.
b.Subscribe("TransferRequested", func(e Event) {
if fraudOK(e) {
b.Publish(Event{"TransferApproved", e.TransferID, e.Minor})
return
}
b.Publish(Event{"TransferRejected", e.TransferID, e.Minor})
})
// Accounts service: TransferApproved -> FundsDebited | DebitFailed.
b.Subscribe("TransferApproved", func(e Event) {
if debit(e) {
b.Publish(Event{"FundsDebited", e.TransferID, e.Minor})
return
}
b.Publish(Event{"DebitFailed", e.TransferID, e.Minor})
})
// Notification service: reacts to the facts it cares about.
b.Subscribe("FundsDebited", func(e Event) { b.Publish(Event{"CustomerNotified", e.TransferID, 0}) })
b.Subscribe("DebitFailed", func(e Event) { b.Publish(Event{"CustomerNotified", e.TransferID, 0}) })
}<?php
declare(strict_types=1);
namespace App\Transfers\Choreography;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Events\Dispatchable;
use App\Transfers\AccountsService;
/** Microservice style: no orchestrator. Each service owns one reaction. */
final readonly class TransferRequested { use Dispatchable; public function __construct(public string $id, public string $from, public int $minor) {} }
final readonly class TransferApproved { use Dispatchable; public function __construct(public string $id, public string $from, public int $minor) {} }
final readonly class FundsDebited { use Dispatchable; public function __construct(public string $id, public int $minor) {} }
final readonly class DebitFailed { use Dispatchable; public function __construct(public string $id) {} }
/** Lives in the fraud service. */
final class ApproveTransfer implements ShouldQueue
{
public function handle(TransferRequested $e): void
{
if ($e->minor <= 1_000_000) {
TransferApproved::dispatch($e->id, $e->from, $e->minor);
}
}
}
/** Lives in the accounts service. Must be idempotent: queues deliver at least once. */
final class DebitAccount implements ShouldQueue
{
public function handle(TransferApproved $e): void
{
$accounts = app(AccountsService::class);
try {
$accounts->debit($e->id, $e->from, $e->minor);
FundsDebited::dispatch($e->id, $e->minor);
} catch (\Throwable) {
DebitFailed::dispatch($e->id);
}
}
}
// In a service provider's boot():
// Event::listen(TransferRequested::class, ApproveTransfer::class);
// Event::listen(TransferApproved::class, DebitAccount::class); 1 Payments publishes TransferRequested(t1)
2 Fraud consumes, publishes TransferApproved(t1)
3 Accounts consumes, debits A, publishes FundsDebited(t1)
4 Accounts (credit side) consumes, credit fails, publishes CreditFailed(t1)
5 Accounts consumes its own CreditFailed, refunds A, publishes FundsRefunded(t1)
6 Notify consumes FundsRefunded, tells the customerبدهبستانها
| سؤال | Orchestrated (SOA) | Choreographed (microservices) |
|---|---|---|
| جریان کسبوکار کجا نوشته شده؟ | یک کلاس و یک جدول | پخش در چهار listener |
| افزودن «بررسی AML بعد از fraud» | orchestrator را ویرایش و دوباره مستقر کن | سرویس تازه به TransferApproved گوش میدهد و رویداد خودش را منتشر میکند؛ fraud و accounts باید دربارهٔ ترتیب توافق کنند |
| دیباگ یک انتقال گیرکرده | SELECT از transfer_process | رویدادها را بین سرویسها با trace id همبسته کن |
| خرابی orchestrator | انتقالها مکث میکنند؛ job بازیابی ادامه میدهد | بخش مرکزیای نیست که خراب شود؛ هر سرویس inbox خودش را retry میکند |
| Coupling | orchestrator API همهٔ سرویسها را میداند | سرویسها schema رویدادها را میدانند |
| مالکیت | تیم پلتفرم یا یکپارچهسازی مالک جریان است | هر تیم مالک واکنش خودش |
| ضمانت تحویل لازم | فراخوان مطمئن + state ذخیرهشده | رویداد at-least-once، مصرفکنندهٔ idempotent، outbox |
| تناسب | گامهای کم، audit قوی، جریان مقرراتی | تیمهای زیاد، واکنشهای زیاد، جریان در حال تحول |
توصیهٔ صادقانه: برای جابهجایی پول مقرراتی، جریان را در یک جا نگه دارید (orchestrator کوچک یا workflow engine با جدول audit) و رویداد را برای واکنشهایی به کار ببرید که نتیجه را تعیین نمیکنند (اعلان، analytics، ایندکس جستوجو). سیستمهای بالغ معمولاً به همین ترکیب میرسند؛ ببینید saga pattern.
سازوکار: یک فراخوان واقعاً از چه میگذرد
آناتومی پیام
| بخش | SOAP 1.1 | REST/JSON |
|---|---|---|
| نام عملیات | header به نام SOAPAction و المان body | متد HTTP + URL |
| بار (Payload) | Body با یک المان نوعدار | سند JSON |
| فرادادهٔ پیام | بلوکهای Header (امنیت، آدرسدهی، همبستگی) | headerهای HTTP |
| خطا | Fault با faultcode، faultstring، detail (HTTP 500) | status HTTP + problem+json |
| نوعدهی | XSD | JSON Schema در OpenAPI |
| توصیف سرویس | WSDL (types، message، portType، binding، service) | سند OpenAPI |
| Caching | ندارد (POST) | GET با ETag، Cache-Control |
| امنیت retry | بهعهدهٔ ارائهدهنده؛ فیلد reference | Idempotency-Key، PUT |
کدهای خطا و کار لازم
| کجا | نشانه | معنا | Retry؟ |
|---|---|---|---|
| SOAP | faultcode برابر Client (1.1) | پیام شما غلط است | نه |
| SOAP | faultcode برابر Server (1.1) | ارائهدهنده شکست خورد | شاید، اگر idempotent باشد |
| SOAP | detail/ErrorCode 51 | موجودی ناکافی (مثال ما) | نه |
| SOAP | detail/ErrorCode 91 | مجوزدهنده در دسترس نیست | بله، با همان reference |
| HTTP | 503 + Retry-After | بار زیاد یا نگهداری | بله، با همان کلید |
| HTTP | timeout، connection reset | نتیجه نامعلوم | بله، فقط با idempotency |
| نمای REST | 422 problem+json | رد کسبوکاری | نه |
| نمای REST | 200 در replay | همان کلید قبلاً دیده شده | لازم نیست |
حل مسئلههای کلاسیک
| مسئله | راهحل | چگونه | هزینه |
|---|---|---|---|
| ESB بهعنوان گلوگاه | منطق را به سرویسها ببر، gateway نازک نگه دار | gateway فقط auth، quota، routing | سرویسها باید validation را خودشان داشته باشند |
| بنبست canonical model | مدل هر context + anti-corruption layer | در هر مرز ترجمه کن | کد mapping بیشتر، اما صریح |
| تراکنش توزیعشده نیست | Saga با compensation | orchestrator یا رویداد؛ saga | consistency نهایی، UX برای حالتهای pending |
| فراخوان تکراری پس از timeout | idempotency key بهعنوان reference قدیمی | یک شناسه برای کل زنجیره | نگهداری کلید، سیاست انقضا |
| SOAP قدیمی پخش میشود | Anti-corruption layer | port دامنه، یک adapter | یک لایهٔ دیگر برای تست |
| Contract drift | contract test، envelopeهای ضبطشده | replay fixture در CI | نگهداری fixtureها |
| سرویس مشترک reusable جلوی تیمها را میگیرد | کپی بعد استخراج، یا consumer-driven contract | هر تیم یک برش را مالک شود | کمی تکرار |
| crash orchestrator | ذخیرهٔ state، job بازیابی | جدول transfer_process | یک جدول فرایند برای عملیات |
| گم شدن پیام بین سرویسها | outbox + at-least-once + مصرفکنندهٔ idempotent | Outbox | تأخیر، مدیریت تکرارها |
| ارائهدهندهٔ SOAP کند | timeout، circuit breaker، bulkhead | timeout با context، کتابخانهٔ breaker | قابلیتهای تنزلیافته |
انتخاب
| وضعیت | توصیه | تکنیک | دلیل |
|---|---|---|---|
| محصول جدید، یک تیم | Modular monolith | portهای درونی | ارزانترین؛ ببینید modular monolith |
| ۱۰ تا ۵۰ مهندس، دامنههای روشن | Service-based architecture | ۴ تا ۱۲ سرویس دامنه | استقرار مستقل بدون هزینهٔ microservices |
| تیمهای زیاد، نیاز مقیاس مستقل | Microservices | لوله کودن، قرارداد رویداد | خودمختاری تیم؛ ببینید microservices |
| باید API SOAP یک بانک را مصرف کنید | Anti-corruption layer | port + adapter | legacy را از دامنه بیرون نگه میدارد |
| یکپارچهسازی ۲۰ سیستم آمادهٔ موجود | پلتفرم یکپارچهسازی یا محصول شبیه ESB | Camel، MuleSoft، iPaaS؛ منطق در سیستمها بماند | کاربرد مشروع ESB: وصل کن، تصمیم نگیر |
| جریان مقرراتی چندگامی | workflow orchestrated با audit | Temporal، Camunda یا جدول فرایند | یک جا برای اثبات آنچه رخ داد |
| واکنشهای زیاد به یک رویداد | Choreography | broker و مصرفکنندهٔ idempotent | تیمها بدون release واکنش اضافه میکنند |
| API عمومی برای شریکها | REST/JSON با OpenAPI | gateway، quota، نسخهبندی | دسترسی و ابزارها |
در معماری: از یک پردازه تا سیستم توزیعشده
Monolith (یک پردازه، یک پایگاهداده)
service orientation اینجا یک انضباط طراحی است: ماژولها interface کوچکی (TransferPort) عرضه میکنند و جدولهایشان را پنهان میکنند. مثال: ماژول انتقال در یک monolith لاراول TransferPort را به adapter مبتنی بر Eloquent bind میکند؛ فراخوانندهها هرگز به جدول accounts دست نمیزنند. اگر روزی قابلیت پشت SOAP یا HTTP رفت، فقط adapter عوض میشود. در این اندازه bus، canonical model یا orchestrator نیاورید.
Modular monolith / چند پایگاهداده
هر ماژول schema خودش را دارد و رویدادهای درونفرایندی منتشر میکند (ببینید modular monolith). ارائهدهندهٔ SOAP قدیمی یک بار توسط یک ماژول ACL پیچیده میشود. مثال: ماژول payments WSDL هستهٔ بانکی را از راه LegacyTransferAdapter صدا میزند؛ ماژول ledger نتیجه را در schema خودش در یک تراکنش محلی ثبت میکند. service-based architecture قدم بعد است: payments را بهصورت سرویس مستقر مستقل استخراج کنید که هنوز مدتی پایگاهدادهٔ عملیاتی را مشترک دارد.
Microservices
تواناییها سرویسهای مستقل با دادهی خودشان میشوند. مثال جریان بین سرویسها: BFF وب payments را صدا میزند، payments با timeout ۳۰۰ میلیثانیه fraud را (HTTP) صدا میزند و TransferRequested را از راه outbox منتشر میکند؛ accounts با idempotency key بدهکار و بستانکار میکند؛ یک saga (orchestrated توسط payments یا choreographed) شکست را مدیریت میکند. درسهای SOA که اینجا مهماند: لوله را کودن نگه دارید، قرارداد را در مخزن بگذارید، هرگز پایگاهداده را مشترک نکنید، و canonical model را فقط برای پیامهای استاندارد صنعتی نگه دارید. جزئیات در مرزهای سرویس و مالکیت داده.
داده توزیعشده (replica، cache، چند منطقه)
فراخوان SOAP به سیستم رکورد یک وابستگی همگام است؛ replica و cache جلوی آن موجودی کهنه برمیگردانند. مثال: اپ موبایل موجودی را از نمای read replica دفتر کل میخواند که با رویدادهای سیستم رکورد تغذیه میشود؛ خودِ انتقال همیشه به primary میرود. جابهجایی پول داخل سیستم رکورد strongly consistent میماند؛ همهچیز اطرافش eventually consistent است و UI تا رسیدن رویداد تأییدکننده «در انتظار» نشان میدهد. ببینید replication و distributed SQL.
مسیر مقیاسپذیری (Scaling path)
| بار | طراحی | نکته |
|---|---|---|
| 1x: ۱۰ انتقال در دقیقه | monolith، یک TransferPort، adapter SOAP درون آن | timeout و idempotency از روز اول |
| 10x: ۱۰۰ در دقیقه | فراخوانهای SOAP را صف کن، workerها با همزمانی محدود | ظرفیت سیستم قدیمی سقف است؛ احترام بگذارید |
| 100x: ۱٬۰۰۰ در دقیقه | سرویس payments را استخراج کن، outbox، saga، ACL با rate limit | quotaی gateway از ارائهدهندهٔ قدیمی محافظت میکند |
| 1,000x و تیمهای زیاد | سرویس برای هر دامنه، رویداد، schema registry، workflow engine برای جریانهای مقرراتی | وقتی هسته عوض شد adapter SOAP را با strangler fig بازنشسته کن |
آزمایشگاه
تمرین: کلاینت SOAP، anti-corruption layer و نمای REST را در برابر یک سرور قدیمیِ جعلی اجرا کنید و کار کردن idempotency را ببینید.
- تستهایی را اجرا کنید که ارائهدهندهٔ جعلی قدیمی را دارند:
cd docs/snippets/architecture/service-oriented-architecture/go
go test ./... -v
# expected: soapclient TestSuccess and TestFaultOnHTTP500 pass; acl TestFaultMapping passes- قرارداد را عمداً بشکنید: در
soapclient/client_test.goنام المانfromAccountرا در fixture عوض کنید و دوباره اجرا کنید. انتظار: assertion سمت سرور شکست میخورد؛ contract drift اینطور گرفته میشود. - کد fault را از
51به91عوض کنید: نتیجهErrUnavailableاست. تستی بنویسید که ثابت کند handler REST باRetry-Afterجواب 503 میدهد. - همان
POST /v1/transfersرا دو بار با یکIdempotency-Keyبفرستید: انتظار 201 و بعد 200، و port جعلی یک فراخوان را میشمارد (ببینیدrestapi/handler_test.go). - تست orchestrator (
orchestrator_test.go) را اجرا کنید: credit شکست میخورد، state بهCOMPENSATEDمیرسد و آخرین فراخوانrefundاست. - تست choreography را با رد شدن توسط fraud گسترش دهید و لاگ رویدادها را بنویسید؛ بعد جواب دهید: اگر
CustomerNotifiedهرگز نیاید ساعت ۳ بامداد کدام تیم بیدار میشود؟
بدفهمیهای رایج
| باور | واقعیت |
|---|---|
| SOA یعنی SOAP | OASIS آن را پارادایم میداند؛ SOAP یک پیادهسازی رایج بود |
| ESB همان message broker است | broker پیام جابهجا میکند؛ ESB علاوه بر آن mediation، transformation و orchestration دارد |
| microservices سرویسهای کوچک SOA هستند | تفاوت در مالکیت داده، هوش لوله و governance است، نه اندازه |
| reuse هر سرویسی را توجیه میکند | reuse بعد از مصرفکنندهٔ سوم کشف میشود، نه از قبل طراحی |
| canonical model coupling را کم میکند | همهٔ سیستمها را به schemaی که کمیته مالک آن است جفت میکند |
| WSDL تولیدشده از کد یعنی contract-first | contract-first یعنی قرارداد پیش از کد نوشته میشود |
| پیچیدن monolith در سرویس چابکی میدهد | چرخهٔ انتشار به monolith بسته میماند |
| SOAP مرده است | بانک، دولت، ERP و مخابرات هنوز SOAP منتشر میکنند؛ باید تمیز یکپارچهشان کرد |
| choreography همیشه از orchestration بهتر است | جریانهای مقرراتی اغلب یک جا میخواهند که بتواند ثابت کند چه شد |
| UDDI راه کشف سرویس امروز است | فراگیر نشد؛ کاتالوگ و سیستمهای discovery جایش را گرفتند |
چکیدهٔ فشرده (Cheat sheet)
| موضوع | چه چیزی را به خاطر بسپارید |
|---|---|
| تعریف | OASIS: پارادایمی برای سازماندهی تواناییهای توزیعشده زیر دامنههای مالکیت متفاوت |
| ایدهٔ اصلی | سرویس با قرارداد منتشرشده و loose coupling |
| هشت اصل | contract، loose coupling، abstraction، reusability، autonomy، statelessness، discoverability، composability |
| چهار نوع سرویس | business، enterprise، application، infrastructure |
| ESB | mediation، routing، transformation، orchestration؛ لولهٔ هوشمند |
| Orchestration در برابر choreography | رهبر ارکستر در برابر رقصندههای واکنشی |
| WS-* | SOAP، WSDL، UDDI، WS-Security، WS-ReliableMessaging؛ سنگین |
| Fault در SOAP 1.1 | با HTTP 500 و body از نوع Fault میآید |
| Canonical model | در ۶ سیستم ارزان (۱۲ در برابر ۳۰ مترجم)، در governance گران |
| Governance | هیئتهای مرکزی تغییر را کند کردند؛ guardrail بگذارید |
| Microservices | smart endpoints، dumb pipes، پایگاهداده برای هر سرویس |
| Service-based | ۴ تا ۱۲ سرویس درشت، اغلب پایگاهدادهٔ مشترک |
| SOAP قدیمی | در anti-corruption layer بپیچید؛ پول درون سیستم عدد صحیح |
| Idempotency | یک شناسه از لبه تا reference سیستم قدیمی |
| چه ماند | contract-first، API management، EIP، workflow engine |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — مدل مرجع OASIS میگوید SOA چیست، و میگوید چه چیزی را پوشش نمیدهد؟ تکمیلی
پاسخ
پاسخ: پارادایمی برای سازماندهی و استفاده از تواناییهای توزیعشده که ممکن است زیر دامنههای مالکیت متفاوت باشند. orchestration چند سرویس را پوشش نمیدهد؛ orchestration و choreography بخشی از مدل فرایندند، نه تعریف.
۲ — چهار نوع سرویس در SOA مبتنی بر orchestration را با یک مثال برای هر کدام نام ببرید. تکمیلی
پاسخ
پاسخ: Business (TransferFunds)، enterprise (GetBalance)، application (wrapper یک mainframe)، infrastructure (audit، احراز هویت).
۳ — تفاوت ESB با message broker چیست؟ حیاتی
پاسخ
پاسخ: broker پیام را منتقل میکند و کودن میماند؛ ESB علاوه بر آن mediation، routing بر اساس محتوا، تبدیل قالب و گاهی orchestration و قواعد کسبوکار دارد.
۴ — چرا کلاینت SOAP 1.1 باید body را پیش از نگاه به status HTTP بخواند؟ تکمیلی
پاسخ
پاسخ: faultهای SOAP 1.1 با HTTP 500 و المان Fault میآیند؛ status بهتنهایی faultcode و detail را از دست میدهد.
۵ — ۶ برنامه با و بدون canonical data model چند مترجم لازم دارند؟ مهم
پاسخ
پاسخ: ۳۰ بدون آن، ۱۲ با آن (حساب Enterprise Integration Patterns: N×(N−1) در برابر 2N).
۶ — سه دلیل سنگین بودن پشتهٔ WS-* را بگویید. تکمیلی
پاسخ
پاسخ: XML پرحرف و namespaceها؛ مشخصههای انباشته با افزونههای vendor؛ تولید کد مخصوص هر ابزار و امنیت transport تکراری.
۷ — «smart endpoints and dumb pipes» چیست؟ حیاتی
پاسخ
پاسخ: توصیف Fowler از رویکرد میکروسرویس: منطق در سرویسهاست و ارتباط HTTP ساده یا broker ساده است؛ عکس گذاشتن routing، transformation و قواعد در ESB.
۸ — service-based architecture چه وقت از microservices بهتر است؟ مهم
پاسخ
پاسخ: برای سیستمها و تیمهای متوسطی که استقرار مستقل چند دامنه را میخواهند بدون هزینهٔ عملیاتی سرویسهای زیاد و پایگاهداده برای هر سرویس.
۹ — چرا ارائهدهندهٔ SOAP قدیمی باید پشت anti-corruption layer باشد؟ مهم
پاسخ
پاسخ: تا قالبها، کدها و faultهایش از دامنه بیرون بماند؛ adapter یک بار ترجمه میکند و بعداً با عوض کردن فقط adapter میشود سیستم قدیمی را جایگزین کرد.
۱۰ — در مثال انتقال، وقتی credit بعد از موفقیت debit شکست بخورد orchestrator چه میکند؟ مهم
پاسخ
پاسخ: با همان شناسهٔ انتقال refund را صدا میزند (compensation)، COMPENSATED را ثبت میکند و خطا را برمیگرداند؛ اگر refund هم شکست بخورد NEEDS_MANUAL_REVIEW ثبت میشود.
واژهنامه (Glossary)
| واژه | معنا |
|---|---|
| SOA | Service-Oriented Architecture: سازماندهی تواناییها بهشکل سرویس با قرارداد منتشرشده |
| سرویس (Service) | سازوکار دسترسی به یک capability از راه interface مقرر (OASIS) |
| قرارداد سرویس (Service contract) | شرح ماشینخوان عملیات، پیامها و policy |
| SOAP | چارچوب پیامرسانی XML با envelope، header، body، fault |
| WSDL | شرح XML از عملیات، پیامها، bindingها و نشانیها |
| XSD | XML Schema Definition، سیستم نوع پیامهای SOAP |
| UDDI | مشخصهٔ رجیستری برای انتشار و یافتن سرویسها |
| WS-Security | مشخصهٔ OASIS برای امضا و رمزنگاری پیامهای SOAP |
| WS-ReliableMessaging | مشخصهٔ OASIS برای تحویل مطمئن بین endpointهای SOAP |
| WS-* | خانوادهٔ مشخصههای انباشته روی SOAP |
| ESB | Enterprise Service Bus: لایهٔ مرکزی mediation، routing، transformation |
| Mediation | واسطه بین مصرفکننده و ارائهدهنده |
| Orchestration | فرایند مرکزی که سرویسها را بهترتیب صدا میزند |
| Choreography | هماهنگی سرویسها با رویداد، بدون مالک مرکزی |
| BPEL | زبان XML برای orchestration سرویسهای وب |
| Canonical data model | واژگان پیام مشترک سازمانی |
| Anti-corruption layer | adapterی که مدل بیگانه را به مدل دامنه ترجمه میکند |
| Service-based architecture | چند سرویس دامنهٔ درشت، اغلب با پایگاهدادهٔ مشترک |
| Smart pipes | میانافزاری که routing و منطق کسبوکار دارد |
| Dumb pipes | transport که فقط پیام جابهجا میکند |
| Contract-first | قرارداد را پیش از پیادهسازی بنویس |
| Idempotency key | شناسهای که تکرار درخواست را همنتیجه میکند |
| جبران (Compensation) | عملی که اثر گام قبلی را از نظر معنایی خنثی میکند |
| Strangler fig | جایگزینی تدریجی سیستم قدیمی پشت یک facade |
| API management | gateway، quota، پورتال و نسخهبندی APIها |
منابع
- OASIS, Reference Model for Service Oriented Architecture 1.0, 12 October 2006: https://docs.oasis-open.org/soa-rm/v1.0/soa-rm.html
- W3C, SOAP Version 1.2 Part 1: Messaging Framework (Second Edition), 27 April 2007: https://www.w3.org/TR/soap12-part1/
- W3C, Web Services Description Language (WSDL) 1.1, Note, 15 March 2001: https://www.w3.org/TR/2001/NOTE-wsdl-20010315
- W3C, WSDL Version 2.0 Part 1: Core Language, 26 June 2007: https://www.w3.org/TR/wsdl20/
- OASIS, Web Services Security: SOAP Message Security 1.1.1, 18 May 2012: https://docs.oasis-open.org/wss-m/wss/v1.1.1/os/wss-SOAPMessageSecurity-v1.1.1-os.html
- OASIS, WS-ReliableMessaging 1.2, 2 February 2009: https://docs.oasis-open.org/ws-rx/wsrm/v1.2/wsrm.html
- Fowler and Lewis, Microservices (smart endpoints and dumb pipes; Microservices and SOA): https://martinfowler.com/articles/microservices.html
- Fowler, Service Oriented Ambiguity, 1 July 2005: https://martinfowler.com/bliki/ServiceOrientedAmbiguity.html
- Thoughtworks Technology Radar, Overambitious API gateways: https://www.thoughtworks.com/radar/platforms/overambitious-api-gateways
- Hohpe and Woolf, Canonical Data Model (Enterprise Integration Patterns): https://www.enterpriseintegrationpatterns.com/patterns/messaging/CanonicalDataModel.html
- Microsoft Learn, Anti-corruption layer pattern: https://learn.microsoft.com/en-us/azure/architecture/patterns/anti-corruption-layer
- PHP manual, The SoapClient class: https://www.php.net/manual/en/class.soapclient.php
- Laravel 13 documentation, HTTP Client: https://laravel.com/docs/13.x/http-client
- Go documentation, package
encoding/xml: https://pkg.go.dev/encoding/xml - Wikipedia, Service-oriented architecture and Universal Description Discovery and Integration (ثانویه، برای نام اصول و تاریخچهٔ UDDI): https://en.wikipedia.org/wiki/Service-oriented_architecture
- Richards and Ford, Fundamentals of Software Architecture (O'Reilly, 2020): فصلهای service-oriented architecture مبتنی بر orchestration و service-based architecture. آنلاین دریافت نشد؛ بازنویسی بدون نقلقول.
- Newman, Building Microservices, 2nd ed. (O'Reilly, 2021): پیشزمینهٔ تاریخ SOA. دریافت نشد؛ فقط برای جهتیابی.