Message Transformation: Translator, Enricher, Normalizer, Canonical Model
"Use a special filter, a Message Translator, between other filters or applications to translate one data format into another." — Hohpe و Woolf، Enterprise Integration Patterns، Message Translator
خلاصه (Summary): اتصال سیستمها به معنی یکسانشدن مدل دادهٔ آنها نیست. تبدیل پیام (Message Transformation) شکل، محتوا یا پوشش پیام را در مرحلههای مستقل تغییر میدهد؛ قرارداد مشترک فقط آن چیزی است که واقعاً باید مبادله شود. تمرکز (Focus): هفت الگوی EIP، میزبان اجرای هرکدام، پاکت چندلایه، تبدیل واحد و زمان، غنیسازی، فیلتر اطلاعات شخصی، مدل مرجع، نگاشت دامنه، آزمون و خطاهای مصرف و انتشار در Go و Laravel 13. هدف یادگیری (Learning goal): سه قالب سفارش شریک تجاری را به OrderPlaced تبدیل کنید، خطای نامعتبر را از اختلال گذرا جدا کنید و توضیح دهید انتشار خروجی چه زمانی اجازهٔ تأیید ورودی را میدهد.
این صفحه مرجع الگوهای مترجم پیام (Message Translator)، پوشانندهٔ پاکت (Envelope Wrapper)، غنیساز محتوا (Content Enricher)، پالایهٔ محتوا (Content Filter)، یکسانساز (Normalizer)، مدل دادهٔ مرجع (Canonical Data Model) و نگاشتگر پیام (Messaging Mapper) است. فیلدهای پاکت، نسخهگذاری و Claim Check در طراحی پیام قرار دارند. کانال پیام نامعتبر در سبکها و کانالها، شکست تحویل در DLQ، حذف کل پیام و شکستن آن در مسیریابی پیشرفته و انتخاب مسیر در توپولوژیها بررسی میشوند. پردازش حالتدار جریان متعلق به Stream Processing است.
نقشهٔ صفحه
| اگر دنبال این هستید | بروید به |
|---|---|
| هفت الگو در یک نگاه | یک دقیقه |
| دلیل جداکردن تبدیل از منطق مصرفکننده | چرایی |
| ریشهٔ واژهها و تفاوت EIP و DDD | تاریخچه |
| تعریف، خطای رایج، توالی و کد هر الگو | کاتالوگ |
| هدر، امضا، رمزنگاری و بازکردن پاکت | Envelope Wrapper |
| مدل مشترک، زبان منتشرشده و لایهٔ ضدفساد | Canonical Data Model |
| محل اجرای تبدیل و پشتیبانی محصولات | میزبانها |
| تبدیل تکرکوردی و کتابخانهٔ جریان Kafka | Connect و Streams |
| خطا، قطعیت، واحد پول و زمان | سازوکار |
| آزمون طلایی، ویژگیها، متریک و حافظه | کیفیت |
| سه ورودی شریک تا یک رویداد سفارش | خط لوله |
| راهکارهای Go و Laravel | حل مسئله |
| مقایسهٔ RabbitMQ، Kafka و Redis Streams | تفاوت واسطها |
| انتخاب الگو برای وضعیت مشخص | انتخاب |
| مونولیت تا چندمنطقهای | معماری |
| آزمایش با نتیجهٔ مورد انتظار | آزمایشگاه |
| مرور و بازیابی اصطلاحها | بدفهمیها، چکیده، واژهنامه |
همهچیز در یک دقیقه
هفت الگوی تبدیل (Transformation patterns). تفاوت در چیزی است که تغییر میدهند، نه زبان برنامهنویسی.
| الگو | به زبان ساده | مثال کوچک | تغییر |
|---|---|---|---|
| مترجم پیام (Message Translator) | معنا را در قالب دیگری بیان کن | XML با قیمت 19,99 به JSON با مقدار صحیح 1999 | شکل و نمایش |
| پوشانندهٔ پاکت (Envelope Wrapper) | داده را برای زیرساخت بستهبندی و در مقصد باز کن | امضا و رمزنگاری دور بدنهٔ سامانهٔ قدیمی | پوشش |
| غنیساز محتوا (Content Enricher) | اطلاعات غایب را پیدا و اضافه کن | افزودن سطح و کشور مشتری به سفارش | محتوای بیشتر |
| پالایهٔ محتوا (Content Filter) | فقط دادهٔ لازم برای مخاطب را نگه دار | فهرست SKU برای تحلیل، بدون شناسهٔ مشتری | محتوای کمتر |
| یکسانساز (Normalizer) | چند قالب هممعنا را از مترجمهای جدا عبور بده | سه شریک به یک Draft | چند شکل به یک شکل |
| مدل دادهٔ مرجع (Canonical Data Model) | یک قرارداد مستقل برای تبادل داشته باش | OrderPlaced مشترک در محدودهٔ سفارش | قرارداد |
| نگاشتگر پیام (Messaging Mapper) | مدل دامنه را از شکل پیام جدا کن | Order به OrderPlaced و برعکس | مرز لایه |
میزبان اجرا (Host). Connect و Streams بیرون از فرایند broker اجرا میشوند.
| میزبان | الگوهای متداول | قوت | محدودیت |
|---|---|---|---|
| لبهٔ تولیدکننده (Producer edge) | Mapper، Wrapper، Content Filter | دسترسی به مدل دامنه، یک استقرار | تکرار در تولیدکنندهها |
| برنامهٔ Kafka Connect یا Kafka Streams | تبدیل سبک، حذف فیلد، مسیریابی و پوشاندن داده | ابزار آماده برای حالتهای ساده | وابستگی به اکوسیستم Kafka و چرخهٔ استقرار مستقل |
| لبهٔ مصرفکننده (Consumer edge) | Translator، Normalizer، Enricher | حفاظت از مدل مصرفکننده | تکرار تبدیل در مصرفکنندهها |
| دروازه یا سکوی یکپارچهسازی (Gateway / ESB / iPaaS) | Normalizer، Translator، Wrapper | محل واحد برای شرکای متعدد | تیم و نقطهٔ شکست مرکزی |
هر مرحله یک مسئولیت دارد. خطای نامعتبر (Invalid) باید ثبت و از مسیر عادی خارج شود؛ خطای گذرا (Transient) به تلاش مجدد نیاز دارد. اگر دادهٔ غنیسازی برای قرارداد ضروری است، قطعی منبع مجوز انتشار پیام ناقص نیست.
چرا تبدیل لازم است
حسابداری شناسهٔ مالیاتی را میشناسد، CRM شمارهٔ تماس را، و شریک تجاری قیمت را با ممیز دیگری میفرستد. پیامرسانی (Messaging) این تفاوتها را حذف نمیکند؛ فقط جابهجایی داده را ممکن میکند. اگر تبدیل مرز مشخصی نداشته باشد، نام فیلدها و قراردادهای شریک تا هستهٔ سامانه نفوذ میکنند.
| بدون مرحلهٔ تبدیل مستقل | با مرحلهٔ تبدیل مستقل |
|---|---|
| تجزیه، تبدیل واحد، جستوجو و لاگ در یک handler | مرحلههای کوچک با آزمون مستقل |
| فیلدهای شریک همان API عمومی ما میشوند | قرارداد خودمان در مرز تولید میشود |
| قالب جدید یعنی تغییر handler مرکزی | قالب جدید یعنی مترجم و ثبت جدید |
همهٔ شکستها یک خطای 500 هستند | مرحله و قابلیت retry مشخص است |
| اطلاعات شخصی همراه هر پیام پخش میشود | هر مخاطب خروجی پالایششدهٔ خودش را دارد |
تصویر روزمره: در مرز، مترجم حرف مسافر را قابل فهم میکند؛ فرم گمرکی پوشش استاندارد چمدان است؛ مأمور با شمارهٔ ویزا اطلاعات غایب را پیدا میکند؛ کارمند فقط صفحهٔ لازم را برای پرونده برمیدارد. باجهای که گذرنامههای مختلف را میپذیرد و یک کارت واحد میدهد Normalizer است؛ شکل آن کارت، مدل مرجع است.
سه برداشت غلط را از همین ابتدا کنار بگذارید:
- سریالسازی (Serialization) شیء را به بایت تبدیل میکند؛ تبدیل پیام ممکن است واحد، شناسه، منطقهٔ زمانی یا ساختار را عوض کند.
- واسط پیام (Broker) همهٔ تبدیلها را اجرا نمیکند. Connect و Streams برنامههای جدا هستند؛ RabbitMQ و Redis Streams برای تبدیل دلخواه بدنه به کد مصرفکننده نیاز دارند.
- مدل مرجع وابستگی را حذف نمیکند؛ وابستگیهای زوجی را به توافق روی یک قرارداد تبدیل میکند. هزینهٔ این توافق را بسنجید.
واژهها از کجا آمدهاند
کتاب Enterprise Integration Patterns اثر Hohpe و Woolf در ۲۰۰۳، زبان مشترکی برای یکپارچهسازی ساخت. در لولهها و پالایهها (Pipes and Filters)، مرحلهها با کانال به هم وصلاند؛ هر الگوی تبدیل یکی از این مرحلهها یا ترکیبی از آنهاست. جدول زیر بازگویی مسئله و راهحل صفحههای اصلی EIP است، نه نقل طولانی از کتاب.
| الگو | مسئله به بیان خودمان | راهحل به بیان خودمان |
|---|---|---|
| Message Translator | دو سامانه قالب دادهٔ یکسان ندارند | یک مرحلهٔ تبدیل میان آنها قرار بده |
| Envelope Wrapper | نرمافزار قدیمی الزامات هدر یا رمزنگاری زیرساخت را ندارد | در مرز پوشش اضافه و در مقصد آن را جدا کن |
| Content Enricher | فرستنده همهٔ اطلاعات مورد نیاز گیرنده را ندارد | دادهٔ تکمیلی را محاسبه یا از منبع دیگری دریافت کن |
| Content Filter | از پیام بزرگ فقط چند داده لازم است | خروجی کوچکتر با فیلدهای لازم بساز |
| Normalizer | دادههای هممعنا با قالبهای متعدد میرسند | نوع ورودی را تشخیص بده و از مترجم متناظر عبور بده |
| Canonical Data Model | تعداد اتصالهای زوجی زیاد شده است | قرارداد مستقلی انتخاب کن که هر سیستم به آن نگاشت شود |
| Messaging Mapper | دامنه و زیرساخت نباید شکل یکدیگر را تعیین کنند | نگاشت را در جزء سومی نگه دار |
Translator با سازگارکننده (Adapter) در GoF خویشاوند است؛ Messaging Mapper نیز تخصصی از Mapper و نزدیک به Data Mapper است. در بررسی تبدیل، چهار لایه را از هم جدا کنید: انتقال (Transport)، نمایش داده (Representation)، نوع داده (Data type) و ساختار (Structure). عوضکردن JSON با XML بهتنهایی مشکل «رشتهای که قیمت است» یا «زمان بدون منطقه» را حل نمیکند.
در طراحی دامنهمحور (DDD)، زبان منتشرشده (Published Language) و لایهٔ ضدفساد (Anticorruption Layer) همین مرز را با مالکیت متفاوت حل میکنند: لازم نیست کل شرکت یک مدل داخلی داشته باشد. نقشهٔ بافتها رابطهٔ بالادست و پاییندست را توضیح میدهد؛ مدل مرجع هزینهٔ انتخابها را مقایسه میکند.
کاتالوگ مفاهیم
مترجم پیام (Message Translator) حیاتی
به زبان ساده: همان واقعیت را طوری بیان کنید که سامانهٔ مقصد بفهمد. نامگذاری فیلد فقط کوچکترین قسمت کار است.
بدفهمی رایج (Common misunderstanding): «یک نگاشت JSON به JSON کافی است.» برای تبدیل 19,99 باید بدانیم واحد پول چیست، چند رقم اعشار دارد و مقدار ورودی واحد اصلی است یا خرد. برای زمان محلی هم منطقه و قاعدهٔ تغییر ساعت لازم است.
تعریف: مرحلهای با یک ورودی و یک خروجی که قالب یا نمایش داده را تبدیل میکند؛ تصمیم مسیریابی و تصمیم کسبوکار مسئولیت مرحلههای دیگر است.
1 partner XML -> Translator EUR + unit="19,99"
2 currency table EUR has 2 minor-unit digits
3 decimal string -> integer 1999; extra decimals/overflow => invalid
4 Berlin 25/11/2026 10:00 2026-11-25T09:00:00Z
5 output OrderPlaced namespaced id + UTC + integer amountسناریوها: XML شریک به JSON داخلی، پیام داخلی به رکورد ثابت ERP، سازگارکردن رویداد برای CloudEvents، یا ارتقای payload نسخهٔ قدیمی. ارتقادهنده (Upcaster) نوع خاصی از Translator است که در تکامل schema شرح داده میشود.
| محصول | ابزار تبدیل |
|---|---|
| RabbitMQ | مصرفکننده یا sidecar؛ تبدیل آمادهٔ دلخواه بدنه در broker ندارد |
| Kafka | SMT سبک در Connect، mapValues در Streams یا سرویس consumer-producer |
| Redis Streams | worker گروه مصرفکننده که نتیجه را XADD میکند |
| Laravel | job، فرمان Artisan یا زنجیرهٔ Pipeline |
| Go | تابع نوعدار func(ctx, In) (Out, error) و ترکیب تابعها |
راهکار: مرز هر مرحله را با نوع مشخص کنید. خطای ورودی نامعتبر باید ErrInvalid یا InvalidMessage باشد؛ خطای تبدیل را با retry بیپایان پنهان نکنید. کران عدد صحیح هم بخشی از اعتبارسنجی مبلغ است.
package after
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"math"
"strings"
"time"
)
// Func is one Message Translator: a typed step that can be chained.
type Func[In, Out any] func(context.Context, In) (Out, error)
// Then composes two translators; the Pipes-and-Filters shape in one line.
func Then[A, B, C any](f Func[A, B], g Func[B, C]) Func[A, C] {
return func(ctx context.Context, a A) (C, error) {
b, err := f(ctx, a)
if err != nil {
var zero C
return zero, err
}
return g(ctx, b)
}
}
// minorDigits are ISO 4217 minor-unit digits; unknown codes are rejected
// rather than guessed (guessing 2 digits for JPY is a 100x price bug).
var minorDigits = map[string]int{"USD": 2, "EUR": 2, "GBP": 2, "JPY": 0, "KWD": 3}
// ParseMinor turns "19.99" or "5,50" into minor units without floats.
// More fractional digits than the currency allows is an error, never a rounding.
func ParseMinor(s string, digits int) (int64, error) {
if digits < 0 || digits > 3 {
return 0, invalid("translate", "unsupported minor-unit precision")
}
s = strings.TrimSpace(s)
if strings.Count(s, ",")+strings.Count(s, ".") > 1 {
return 0, invalid("translate", "ambiguous decimal %q", s)
}
s = strings.Replace(s, ",", ".", 1)
whole, frac, decimal := strings.Cut(s, ".")
if whole == "" || (decimal && frac == "") || len(frac) > digits {
return 0, invalid("translate", "bad amount %q for %d digits", s, digits)
}
frac += strings.Repeat("0", digits-len(frac))
var n int64
for _, r := range whole + frac {
if r < '0' || r > '9' {
return 0, invalid("translate", "bad amount %q", s)
}
digit := int64(r - '0')
if n > (math.MaxInt64-digit)/10 {
return 0, invalid("translate", "amount exceeds int64")
}
n = n*10 + digit
}
return n, nil
}
// HashEmail pseudonymises the e-mail with a keyed hash (HMAC-SHA256), so the
// canonical event never carries it but a directory can still be keyed by it.
func HashEmail(key []byte, email string) string {
m := hmac.New(sha256.New, key)
m.Write([]byte(strings.ToLower(strings.TrimSpace(email))))
return hex.EncodeToString(m.Sum(nil))
}
// ToCanonical maps the partner-shaped Draft onto the Canonical Data Model:
// namespaced id, UTC time, integer minor units, hashed e-mail.
func ToCanonical(hashKey []byte) Func[Draft, OrderPlaced] {
return func(_ context.Context, d Draft) (OrderPlaced, error) {
digits, ok := minorDigits[d.Currency]
if !ok {
return OrderPlaced{}, invalid("translate", "unsupported currency %q", d.Currency)
}
if d.PartnerOrderID == "" || len(d.Lines) == 0 || d.PlacedAt.IsZero() {
return OrderPlaced{}, invalid("translate", "missing id, lines or time")
}
out := OrderPlaced{
OrderID: d.Partner + ":" + d.PartnerOrderID,
Partner: d.Partner,
PlacedAt: d.PlacedAt.UTC().Truncate(time.Second),
Customer: Customer{EmailHash: HashEmail(hashKey, d.CustomerEmail)},
}
var total int64
for _, l := range d.Lines {
if l.Qty <= 0 || l.SKU == "" {
return OrderPlaced{}, invalid("translate", "qty %d for %s", l.Qty, l.SKU)
}
var minor int64
var err error
if l.PriceIsMinor {
minor, err = ParseMinor(l.Price, 0)
} else {
minor, err = ParseMinor(l.Price, digits)
}
if err != nil {
return OrderPlaced{}, err
}
out.Lines = append(out.Lines, Line{SKU: l.SKU, Qty: l.Qty, UnitPrice: Money{minor, d.Currency}})
if minor > math.MaxInt64/int64(l.Qty) {
return OrderPlaced{}, invalid("translate", "line amount exceeds int64")
}
lineTotal := minor * int64(l.Qty)
if total > math.MaxInt64-lineTotal {
return OrderPlaced{}, invalid("translate", "order total exceeds int64")
}
total += lineTotal
}
out.Total = Money{total, d.Currency}
out.Enrichment = "ok"
return out, nil
}
}
// Upcast lifts an old payload one version at a time, on a generic map.
// An upcaster is just a Message Translator whose input and output are two
// versions of the same type (see message-design-schema-evolution).
var upcasters = map[int]func(map[string]any) map[string]any{
1: func(m map[string]any) map[string]any { // v1 -> v2: flat hash becomes a nested customer
if h, ok := m["customer_email_hash"].(string); ok {
m["customer"] = map[string]any{"email_hash": h}
delete(m, "customer_email_hash")
}
return m
},
}
func Upcast(m map[string]any, from, to int) (map[string]any, error) {
if from < 1 || to > SchemaVersionOrder || from > to {
return nil, invalid("translate", "unsupported schema range")
}
for v := from; v < to; v++ {
up, ok := upcasters[v]
if !ok {
return nil, invalid("translate", "missing upcaster")
}
m = up(m)
}
return m, nil
}<?php
namespace App\Messaging\Transform;
use DateTimeZone;
/** Message Translator: partner-shaped Draft to the canonical OrderPlaced. */
final class Translator
{
/** ISO 4217 minor-unit digits; unknown currencies are rejected, never guessed. */
private const DIGITS = ['USD' => 2, 'EUR' => 2, 'GBP' => 2, 'JPY' => 0, 'KWD' => 3];
public function __construct(private readonly string $hashKey) {}
public function translate(Draft $d): OrderPlaced
{
$digits = self::DIGITS[$d->currency]
?? throw new InvalidMessage('translate', "unsupported currency {$d->currency}");
if ($d->partnerOrderId === '' || $d->lines === []) {
throw new InvalidMessage('translate', 'missing id or lines');
}
$lines = [];
$total = 0;
foreach ($d->lines as $l) {
if ($l['qty'] <= 0 || $l['sku'] === '') {
throw new InvalidMessage('translate', "qty {$l['qty']} for {$l['sku']}");
}
$minor = $this->parseMinor($l['price'], $l['minor'] ? 0 : $digits);
$lines[] = ['sku' => $l['sku'], 'qty' => $l['qty'], 'unit_price' => ['amount_minor' => $minor, 'currency' => $d->currency]];
if ($minor > intdiv(PHP_INT_MAX, $l['qty']) || $total > PHP_INT_MAX - $minor * $l['qty']) {
throw new InvalidMessage('translate', 'amount exceeds integer range');
}
$total += $minor * $l['qty'];
}
return new OrderPlaced(
orderId: $d->partner.':'.$d->partnerOrderId,
partner: $d->partner,
placedAt: $d->placedAt->setTimezone(new DateTimeZone('UTC')),
customer: ['email_hash' => hash_hmac('sha256', strtolower(trim($d->email)), $this->hashKey)],
lines: $lines,
totalMinor: $total,
currency: $d->currency,
);
}
/** "19.99" or "5,50" to minor units with no floats; extra digits are an error, not a rounding. */
public function parseMinor(string $s, int $digits): int
{
if ($digits < 0 || $digits > 3) { throw new InvalidMessage('translate', 'unsupported minor-unit precision'); }
$s = str_replace(',', '.', trim($s));
if (substr_count($s, '.') > 1 || ! preg_match('/^\d+(\.\d+)?$/', $s)) {
throw new InvalidMessage('translate', "bad amount {$s}");
}
[$whole, $frac] = array_pad(explode('.', $s, 2), 2, '');
if (strlen($frac) > $digits) {
throw new InvalidMessage('translate', "amount {$s} has more than {$digits} decimals");
}
$value = ltrim($whole.str_pad($frac, $digits, '0'), '0') ?: '0';
$max = (string) PHP_INT_MAX;
if (strlen($value) > strlen($max) || (strlen($value) === strlen($max) && strcmp($value, $max) > 0)) {
throw new InvalidMessage('translate', 'amount exceeds integer range');
}
return (int) $value;
}
}پوشانندهٔ پاکت (Envelope Wrapper) حیاتی
به زبان ساده: برنامهٔ قدیمی فقط بدنه را میشناسد؛ adapter خروجی، پوشش لازم را دور آن قرار میدهد و adapter مقصد پوشش را برمیدارد.
بدفهمی رایج (Common misunderstanding): «پاکت همان هدرهای broker است.» هدر انتقال فقط یک لایه است. شناسه و نوع کسبوکار، امضا، رمزنگاری و هدرهای انتقال ممکن است چند لایهٔ مستقل باشند؛ ترتیب بازکردن معکوس ترتیب بستن است.
تعریف: Wrapper داده را با نیازهای زیرساخت از نظر metadata، احراز اصالت یا محرمانگی سازگار میکند؛ بازکننده (Unwrapper) دادهٔ اصلی را بازیابی میکند. انتخاب ترتیب امضا و رمزنگاری تصمیم امنیتی است، نه سلیقهٔ قالببندی.
| سبک پاکت | محل فیلدها | مناسب برای | نقطهٔ شکست |
|---|---|---|---|
| سبک هدر (Header style) | propertyها و هدرهای AMQP یا رکورد Kafka | مسیریابی و ردگیری بدون تجزیهٔ بدنه | hop ممکن است هدر را حذف کند؛ Redis Streams هدر مجزا ندارد |
| درون بدنه (In-body style) | JSON/Avro دور بایتهای payload | عبور از چند پروتکل و امضای کل پیام | بایت در JSON با base64 حدود یکسوم بزرگتر میشود؛ دسترسی به metadata نیازمند parse است |
ترکیب این دو معمول است: حقایق مسیریابی در هدر و نسخهٔ کامل پاکت در بدنه. اینکه چه فیلدی لازم است در طراحی پیام و CloudEvents آمده است.
Sender Receiver
1 raw payload 9 return original payload
2 business envelope 8 parse/check type/version
3 HMAC-SHA256 tag + envelope 7 constant-time tag check
4 AES-GCM with fresh random nonce 6 authenticated decrypt
5 transport headers + publish ----------------> 5 read transport metadataسناریوها: دریافت webhook خام شریک با شناسهٔ پایدار، امضای پیام میان سرویسها، رمزنگاری اطلاعات شخصی پیش از ذخیره، عبور از پلی که فقط بدنه را حفظ میکند و ارائهٔ قالب استاندارد برای مشترک بیرونی.
| محصول | امکان حمل پاکت | نکته |
|---|---|---|
| RabbitMQ / AMQP 0-9-1 | message_id، type، correlation_id، timestamp، content_type و headers | interceptorهای آماده metadata میافزایند؛ بدنه را ترجمه نمیکنند |
| Kafka | key، value، timestamp و record headers | serializerهای رایج Confluent نیز شناسهٔ schema را در framing مقدار میگذارند |
| Redis Streams | زوجهای field-value | metadata و body فیلدهای همسطحاند |
| Laravel | payload صف و ShouldBeEncrypted | پاکت job همان CloudEvent نیست |
راهکار: Layer یک Wrap و یک Unwrap دارد. Stack ترتیب را مدیریت میکند؛ Signer از HMAC-SHA256 و Sealer از AES-GCM استفاده میکند. مدیریت کلید و چرخش آن در امنیت پیامرسانی است.
package after
import (
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"strconv"
"time"
)
// Envelope is the in-body style of Envelope Wrapper: the application data is
// opaque bytes (any partner format), the envelope carries what the messaging
// infrastructure needs. Broker headers can carry the same fields instead
// (see Headers); the in-body style survives hops that drop headers.
type Envelope struct {
ID string `json:"id"`
Type string `json:"type"`
Source string `json:"source"`
Version int `json:"version"`
OccurredAt time.Time `json:"occurred_at"`
CorrelationID string `json:"correlation_id,omitempty"`
CausationID string `json:"causation_id,omitempty"`
ContentType string `json:"content_type"`
Key string `json:"key,omitempty"` // partition / routing key, e.g. the order id
Data []byte `json:"data"` // base64 in JSON
}
// Headers is the header-style view, for brokers with a header section
// (AMQP application headers, Kafka record headers). Redis Streams has no
// header section, so these become sibling fields of the entry.
func (e Envelope) Headers() map[string]string {
h := map[string]string{
"id": e.ID, "type": e.Type, "source": e.Source,
"version": fmt.Sprint(e.Version),
"occurred-at": e.OccurredAt.UTC().Format(time.RFC3339Nano),
"content-type": e.ContentType,
}
if e.CorrelationID != "" {
h["correlation-id"] = e.CorrelationID
}
if e.CausationID != "" {
h["causation-id"] = e.CausationID
}
return h
}
// WrapRaw is the Envelope Wrapper at the edge: a partner payload we did not
// design is put, untouched, inside an envelope the infrastructure understands.
func WrapRaw(partner, contentType string, body []byte, receivedAt time.Time) Envelope {
sum := sha256.Sum256(append([]byte(partner+"|"), body...))
return Envelope{
ID: hex.EncodeToString(sum[:16]), // same webhook retry, same id
Type: "partner.order.received",
Source: "partner/" + partner,
Version: 1,
OccurredAt: receivedAt.UTC(),
ContentType: contentType,
Data: body,
}
}
// Layer is one wrapping step; Unwrap must undo Wrap exactly.
type Layer interface {
Wrap(plain []byte) ([]byte, error)
Unwrap(wrapped []byte) ([]byte, error)
}
// Stack applies layers in order on Wrap and in reverse order on Unwrap.
type Stack []Layer
func (s Stack) Wrap(b []byte) ([]byte, error) {
for _, l := range s {
var err error
if b, err = l.Wrap(b); err != nil {
return nil, err
}
}
return b, nil
}
func (s Stack) Unwrap(b []byte) ([]byte, error) {
for i := len(s) - 1; i >= 0; i-- {
var err error
if b, err = s[i].Unwrap(b); err != nil {
return nil, err
}
}
return b, nil
}
// Signer prefixes an HMAC-SHA256 so a consumer can reject a tampered message.
type Signer struct{ Key []byte }
func (s Signer) Wrap(p []byte) ([]byte, error) {
m := hmac.New(sha256.New, s.Key)
m.Write(p)
return append(m.Sum(nil), p...), nil
}
func (s Signer) Unwrap(w []byte) ([]byte, error) {
if len(w) < sha256.Size {
return nil, errors.New("signer: message too short")
}
m := hmac.New(sha256.New, s.Key)
m.Write(w[sha256.Size:])
if !hmac.Equal(m.Sum(nil), w[:sha256.Size]) {
return nil, errors.New("signer: bad signature")
}
return w[sha256.Size:], nil
}
// Sealer encrypts with AES-256-GCM: nonce || ciphertext+tag.
type Sealer struct{ aead cipher.AEAD }
func NewSealer(key []byte) (Sealer, error) {
if len(key) != 32 {
return Sealer{}, errors.New("sealer: AES-256 requires 32 bytes")
}
blk, err := aes.NewCipher(key) // 32-byte key selects AES-256
if err != nil {
return Sealer{}, err
}
g, err := cipher.NewGCM(blk)
return Sealer{aead: g}, err
}
func (s Sealer) Wrap(p []byte) ([]byte, error) {
nonce := make([]byte, s.aead.NonceSize())
if _, err := rand.Read(nonce); err != nil {
return nil, err
}
return s.aead.Seal(nonce, nonce, p, nil), nil
}
func (s Sealer) Unwrap(w []byte) ([]byte, error) {
n := s.aead.NonceSize()
if len(w) < n {
return nil, errors.New("sealer: message too short")
}
return s.aead.Open(nil, w[:n], w[n:], nil)
}
// Encode serialises an envelope and applies the layer stack.
func Encode(e Envelope, layers Stack) ([]byte, error) {
b, err := json.Marshal(e)
if err != nil {
return nil, err
}
return layers.Wrap(b)
}
// Decode is the Unwrapper: undo the layers, then parse the envelope.
func Decode(b []byte, layers Stack) (Envelope, error) {
plain, err := layers.Unwrap(b)
if err != nil {
return Envelope{}, err
}
var e Envelope
return e, json.Unmarshal(plain, &e)
}
// FromHeaders rebuilds an envelope from header-style metadata plus a body.
func FromHeaders(h map[string]string, body []byte) Envelope {
at, _ := time.Parse(time.RFC3339Nano, h["occurred-at"])
v, _ := strconv.Atoi(h["version"])
return Envelope{
ID: h["id"], Type: h["type"], Source: h["source"], Version: v, OccurredAt: at,
CorrelationID: h["correlation-id"], CausationID: h["causation-id"],
ContentType: h["content-type"], Data: body,
}
}<?php
namespace App\Messaging\Transform;
use DateTimeImmutable;
use DateTimeInterface;
/**
* Envelope Wrapper, in-body style: opaque application data plus the fields the
* infrastructure needs. The same fields can travel as broker headers instead.
*/
final readonly class Envelope
{
public function __construct(
public string $id,
public string $type,
public string $source,
public int $version,
public DateTimeImmutable $occurredAt,
public string $contentType,
public string $data,
public ?string $correlationId = null,
public ?string $causationId = null,
public ?string $key = null,
) {}
/** The edge wrapper: a partner payload is stored untouched inside an envelope. */
public static function wrapRaw(string $partner, string $contentType, string $body): self
{
return new self(
// Same webhook retry, same id: the id is derived from the content.
id: substr(hash('sha256', $partner.'|'.$body), 0, 32),
type: 'partner.order.received',
source: 'partner/'.$partner,
version: 1,
occurredAt: new DateTimeImmutable('now', new \DateTimeZone('UTC')),
contentType: $contentType,
data: $body,
);
}
/** Header-style view for AMQP application headers and Kafka record headers. */
public function headers(): array
{
return array_filter([
'id' => $this->id,
'type' => $this->type,
'source' => $this->source,
'version' => (string) $this->version,
'occurred-at' => $this->occurredAt->format(DateTimeInterface::RFC3339_EXTENDED),
'content-type' => $this->contentType,
'correlation-id' => $this->correlationId,
'causation-id' => $this->causationId,
], fn ($v) => $v !== null);
}
public static function fromHeaders(array $h, string $body, ?string $key = null): self
{
return new self(
id: $h['id'], type: $h['type'], source: $h['source'], version: (int) $h['version'],
occurredAt: new DateTimeImmutable($h['occurred-at']), contentType: $h['content-type'],
data: $body, correlationId: $h['correlation-id'] ?? null,
causationId: $h['causation-id'] ?? null, key: $key,
);
}
public function toJson(): string
{
return json_encode([
...$this->headers(), 'key' => $this->key, 'data' => base64_encode($this->data),
], JSON_THROW_ON_ERROR);
}
}دامها: قبل از تفسیر payload امضا را با مقایسهٔ زمانثابت (Constant-time comparison) بررسی کنید. hmac.Equal و hash_equals برای همیناند. nonce زیر یک کلید نباید تکرار شود. محدودیت فراخوانی GCM در NIST SP 800-38D برای ساختار IV تصادفی شامل سقف 2^32 است؛ مصرف کلید را بشمارید و پیش از کران سیاست چرخش داشته باشید. nonce، طول کلید و نسخهٔ پاکت را حدس نزنید.
غنیساز محتوا (Content Enricher) حیاتی
به زبان ساده: پیامی که رسیده بخشی از اطلاعات لازم را ندارد؛ یک مرحله آن را پیدا و به پیام اضافه میکند.
بدفهمی رایج (Common misunderstanding): «فقط یک lookup ارزان است.» تماس شبکهای روی مسیر داغ، زمان و شکست مستقل دارد. باید برای نبودن داده، قطعی سرویس، مهلت پاسخ و کهنگی cache سیاست جدا داشته باشید.
تعریف: تبدیلکنندهای که بر اساس دادهٔ موجود پیام، اطلاعات تکمیلی را محاسبه میکند، از محیط میگیرد یا از سامانهای دیگر میخواند. کشور از IP، منطقهٔ استقرار از محیط و سطح مشتری از directory سه منبع متفاوتاند.
1 order(email_hash=h) -> cache
2 fresh hit use cached customer
3 miss/expired lookup with deadline; coalesce same key
4 directory 404 cache short-lived missing sentinel
5 directory 5xx + cold cache transient -> retry later
6 directory 5xx + bounded old use old snapshot, mark degradedدر Laravel، Cache::flexible مسیر stale-while-revalidate دارد؛ Go نمونه هنگام انقضا lookup میکند و فقط در خطا از stale استفاده میکند. این دو سیاست یکسان نیستند.
سناریوها: tier و کشور سفارش، اطلاعات جغرافیایی کلیک، حساب تسویهٔ پذیرنده، منطقهٔ استقرار لاگ و فیلد محاسبهشدهٔ جمع سفارش.
| محصول | اجرای معمول غنیسازی |
|---|---|
| RabbitMQ | مصرف raw، تماس با منبع، انتشار به exchange خروجی |
| Kafka | join جریان با KTable یا consumer دارای cache؛ InsertField فقط ثابت و metadata اضافه میکند |
| Redis Streams | worker گروه مصرفکننده و cache محلی یا Redis |
| Laravel | pipe با Http، timeout و Cache::flexible |
راهکار Go: حافظهٔ نهان با TTL، کش منفی (Negative caching)، ادغام درخواستهای همزمان (singleflight)، deadline و stale-on-error. پاسخ منفی TTL کوتاهتری میخواهد چون مشتری ممکن است لحظهای بعد ساخته شود.
package after
import (
"context"
"errors"
"sync"
"time"
"golang.org/x/sync/singleflight"
)
// Directory is the external source the Content Enricher asks.
type Directory interface {
ByEmailHash(ctx context.Context, hash string) (Customer, error)
}
// ErrNotFound is a normal answer ("new customer"), not a failure.
var ErrNotFound = errors.New("customer not found")
type cached struct {
c Customer
missing bool
expires time.Time
}
// Enricher adds customer data to the canonical event. It protects the
// directory with a TTL cache, negative caching and request coalescing, and it
// protects the pipeline with a deadline and a stale-on-error fallback.
type Enricher struct {
Dir Directory
TTL time.Duration // how long an answer is fresh
NegTTL time.Duration // how long "not found" is remembered
StaleOK time.Duration // how long an expired answer may still be used if the directory fails
Timeout time.Duration // per lookup
Now func() time.Time
mu sync.Mutex
cache map[string]cached
group singleflight.Group
}
func (e *Enricher) now() time.Time {
if e.Now != nil {
return e.Now()
}
return time.Now()
}
func (e *Enricher) Enrich(ctx context.Context, o OrderPlaced) (OrderPlaced, error) {
key := o.Customer.EmailHash
e.mu.Lock()
hit, ok := e.cache[key]
e.mu.Unlock()
if ok && e.now().Before(hit.expires) {
return apply(o, hit), nil
}
// One lookup per key at a time: a burst of orders from one customer is one call.
v, err, _ := e.group.Do(key, func() (any, error) {
lctx, cancel := context.WithTimeout(ctx, e.Timeout)
defer cancel()
c, err := e.Dir.ByEmailHash(lctx, key)
if errors.Is(err, ErrNotFound) {
return cached{missing: true, expires: e.now().Add(e.NegTTL)}, nil
}
if err != nil {
return nil, err
}
return cached{c: c, expires: e.now().Add(e.TTL)}, nil
})
if err != nil {
// Directory down or slow: an old answer beats no answer, up to StaleOK.
if ok && e.now().Before(hit.expires.Add(e.StaleOK)) {
o = apply(o, hit)
o.Enrichment = "degraded"
return o, nil
}
return OrderPlaced{}, transient("enrich", err) // retry later; never publish half an event
}
res := v.(cached)
e.mu.Lock()
if e.cache == nil {
e.cache = map[string]cached{}
}
e.cache[key] = res
e.mu.Unlock()
return apply(o, res), nil
}
func apply(o OrderPlaced, c cached) OrderPlaced {
if c.missing {
o.Enrichment = "unknown-customer"
return o
}
o.Customer.ID, o.Customer.Tier, o.Customer.Country = c.c.ID, c.c.Tier, c.c.Country
o.Enrichment = "ok"
return o
}محدودیت نمونهٔ آموزشی: map حافظهٔ نهان (Cache) کلیدهای منقضی را حذف نمیکند؛ در production از cache محدود استفاده کنید. singleflight.Do context فراخوانندهٔ پیشرو را برای lookup مشترک به کار میبرد و انتظار هر caller با لغو context خودش مستقل قطع نمیشود. deadline این کد برای lookup است، نه تضمین مهلت جدا برای هر منتظر.
راهکار Laravel 13: Cache::flexible مقدار تازه را مستقیم، مقدار stale را همراه callback تعویقی بازسازی و مقدار منقضی یا غایب را همزمان محاسبه میکند. null در این مسیر miss حساب میشود؛ به همین دلیل پاسخ «پیدا نشد» با sentinel ذخیره میشود. تعداد تلاشهای Http::retry شامل تلاش اول است.
<?php
namespace App\Messaging\Transform;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
/**
* Content Enricher: ask the customer service, remember the answer.
* Cache::flexible gives stale-while-revalidate: fresh for 5 minutes, served
* as stale for up to an hour while a deferred, locked refresh recomputes it
* (read in Illuminate\Cache\Repository). A cold cache computes inline.
*/
final class CustomerEnricher
{
public function enrich(OrderPlaced $o): OrderPlaced
{
$hash = $o->customer['email_hash'];
try {
// flexible() treats a cached null as a miss, so "not found" is stored as a sentinel array.
$found = Cache::flexible("customer:{$hash}", [300, 3600], fn () => $this->lookup($hash) ?? ['missing' => true]);
} catch (ConnectionException|RequestException $e) {
// Cold cache and the service is down: do not publish half an event.
throw new TransientFailure('enrich', $e);
}
return isset($found['missing'])
? $o->withCustomer([], 'unknown-customer') // new customer: a normal answer
: $o->withCustomer($found, 'ok');
}
/** @return array{id:string,tier:string,country:string}|null null = not found */
private function lookup(string $hash): ?array
{
$r = Http::baseUrl(config('services.customers.url'))
->connectTimeout(1)->timeout(2) // a deadline per lookup
->retry(2, 100, throw: false) // two attempts total, then fall through
->get("/customers/by-email-hash/{$hash}");
if ($r->status() === 404) {
return null;
}
$r->throw(); // 5xx and 4xx other than 404 become exceptions
return Arr::only($r->json(), ['id', 'tier', 'country']);
}
}دامها: دادهٔ غنیشده یک تصویر لحظهای (Snapshot) است. زمان و وضعیت آن را ثبت کنید. با Event-carried State Transfer یا مدل خواندنی محلیِ تغذیهشده از رویدادها میتوان تماس همزمان را حذف کرد، اما حجم پیام و هزینهٔ نگهداری بیشتر میشود.
پالایهٔ محتوا (Content Filter) مهم
به زبان ساده: پیام را برای همین مخاطب کوچک کنید: فیلد اضافی را حذف، ساختار را تخت یا مقدار حساس را بپوشانید.
بدفهمی رایج (Common misunderstanding): «Filter یعنی دور انداختن پیام.» پالایهٔ پیام (Message Filter) کل رکورد را عبور میدهد یا حذف میکند؛ Content Filter همان پیام را با محتوای کمتر نگه میدارد. filter در Streams و Filter در Connect از نوع اولاند؛ ReplaceField، MaskField و نگاشت mapValues به نوع کوچکتر از نوع دوم.
تعریف: تبدیل ساختار یا حذف بخشهای غیرلازم پیام برای نیاز گیرنده. مدلهای خروجی ERP اغلب انعکاس پایگاه دادهٔ نرمالشدهاند؛ گیرنده شاید فقط فهرست کالا را بخواهد.
1 OrderPlaced(customer, lines, exact timestamp)
2 allowlist: order_id, partner, total, country, tier
3 lines -> skus[]
4 timestamp -> placed_day
5 AnalyticsOrder: no customer id/email hash/line priceسناریوها: topic تحلیلی بدون شناسهٔ مشتری، feed شریک محدود به قرارداد، پوشاندن شمارهٔ کارت در لاگ و نمای تخت برای نمایهٔ جستوجو.
فهرست مجاز (Allowlist) یا فهرست حذف (Denylist): ساخت نوع خروجی کوچک باعث میشود فیلد تازه خودکار نشت نکند. Denylist برای payload بیگانه قابل استفاده است، اما تنها گزینه نیست؛ حتی آنجا میتوان projection مجاز ساخت. حذف نامهای شناختهشده در برابر فیلد حساس جدید باز میماند.
| محصول | ابزار Content Filter |
|---|---|
| Kafka Connect | ReplaceField با include/exclude/renames، MaskField با fields/replacement، ExtractField و Flatten |
| Kafka Streams | mapValues به نوع کوچکتر، بدون تغییر کلید |
| RabbitMQ | کد consumer؛ تبدیل آمادهٔ بدنه ندارد |
| Redis Streams | کد worker |
| Laravel | resource یا متد allowlist صریح |
package after
import (
"strings"
)
// AnalyticsOrder is a Content Filter by allowlist: a new struct that has only
// the fields the analytics audience may see. Adding a field to OrderPlaced
// does not leak it, because this type has to be changed on purpose.
type AnalyticsOrder struct {
OrderID string `json:"order_id"`
Partner string `json:"partner"`
PlacedDay string `json:"placed_day"` // time reduced to a date
SKUs []string `json:"skus"` // nested lines flattened to a list
Total Money `json:"total"`
Country string `json:"country,omitempty"`
Tier string `json:"tier,omitempty"`
}
// ForAnalytics drops customer id and hash and the exact time, flattens lines.
func ForAnalytics(o OrderPlaced) AnalyticsOrder {
a := AnalyticsOrder{
OrderID: o.OrderID, Partner: o.Partner,
PlacedDay: o.PlacedAt.UTC().Format("2006-01-02"),
Total: o.Total, Country: o.Customer.Country, Tier: o.Customer.Tier,
}
for _, l := range o.Lines {
a.SKUs = append(a.SKUs, l.SKU)
}
return a
}
// StripFields is a Content Filter by denylist for payloads we do not own
// (partner JSON). Paths are dotted ("payment.card"); arrays are walked.
// Use it for logs and for what the invalid-message channel stores in clear.
func StripFields(doc map[string]any, deny ...string) {
for _, p := range deny {
strip(doc, strings.Split(p, "."))
}
}
func strip(node any, path []string) {
switch n := node.(type) {
case map[string]any:
if len(path) == 1 {
delete(n, path[0])
return
}
strip(n[path[0]], path[1:])
case []any:
for _, e := range n {
strip(e, path)
}
}
}<?php
namespace App\Messaging\Transform;
/** Content Filter: an allowlist for audiences, a denylist for payloads we do not own. */
final class ContentFilter
{
/** The analytics audience gets a new, smaller shape, not a copy with holes. */
public function forAnalytics(OrderPlaced $o): array
{
return [
'order_id' => $o->orderId,
'partner' => $o->partner,
'placed_day' => $o->placedAt->format('Y-m-d'),
'skus' => array_column($o->lines, 'sku'), // nested lines flattened
'total' => ['amount_minor' => $o->totalMinor, 'currency' => $o->currency],
'country' => $o->customer['country'] ?? null,
'tier' => $o->customer['tier'] ?? null,
];
}
/** Remove dotted paths ("payment.card", "items.card"); lists are walked. */
public function strip(array $doc, string ...$deny): array
{
foreach ($deny as $path) {
$doc = $this->remove($doc, explode('.', $path));
}
return $doc;
}
private function remove(array $node, array $path): array
{
$head = array_shift($path);
if (array_is_list($node)) {
return array_map(fn ($n) => is_array($n) ? $this->remove($n, [$head, ...$path]) : $n, $node);
}
if ($path === []) {
unset($node[$head]);
} elseif (isset($node[$head]) && is_array($node[$head])) {
$node[$head] = $this->remove($node[$head], $path);
}
return $node;
}
}فیلتر، انتشار اطلاعات شخصی (PII) را محدود میکند؛ دادهٔ قبلاً نوشتهشده را پاک نمیکند. retention و erasure در امنیت جدا بررسی میشوند.
یکسانساز (Normalizer) حیاتی
به زبان ساده: سفارش از سه شریک میآید، اما ادامهٔ مسیر فقط یک شکل میبیند. تشخیص نوع و تبدیل هر نوع دو مسئولیت جدا هستند.
بدفهمی رایج (Common misunderstanding): «یک switch بزرگ در parser کافی است.» الگوی EIP ترکیب Router و چند Translator است. اضافهکردن شریک باید registration و parser جدید بخواهد، نه تغییر منطق همهٔ شریکها.
تعریف: مسیریاب (Router) نوع ورودی را انتخاب و آن را به مترجم متناظر میدهد؛ خروجی مترجمها شکل مشترک دارد. تشخیص میتواند بر پایهٔ header، ریشهٔ XML، XPath، تعداد و نوع ستون CSV یا نام فایل/پوشه باشد.
1 acme application/json -> JSON parser
2 berlin-shop application/xml -> XML parser
3 tokyo-mart text/csv -> delimited-record parser
4 all parsers -> Draft(partner, id, currency, placed_at, lines)
5 new partner -> new parser + registration + golden fileسناریوها: سفارش B2B از تأمینکنندهها، رویداد نسخههای مختلف SDK، لاگ چند فروشنده و فایل پرداخت بانکی با MT103، ISO 20022 و CSV.
تفاوت با Translator: برای یک قالب یک مترجم کافی است. برای چند قالب هممعنا Normalizer شکل را به Draft تبدیل میکند و Translator بعدی واحد، شناسه و معنای فیلد را استاندارد میکند. parser نمونهٔ CSV یک قرارداد جداشده با ; است، نه پیادهسازی عمومی همهٔ قواعد CSV.
package after
import (
"bytes"
"encoding/json"
"encoding/xml"
"mime"
"strconv"
"strings"
"time"
_ "time/tzdata" // embed the zone database: slim containers have none
)
// Draft is the Normalizer's output: one structure for three partner formats.
// Values are still the partner's (decimal strings, partner ids); making them
// canonical is the Message Translator's job.
type Draft struct {
Partner string
PartnerOrderID string
CustomerEmail string
Currency string
PlacedAt time.Time
Lines []DraftLine
}
type DraftLine struct {
SKU string
Qty int
Price string // "19.99", "5,50" or "1999" when PriceIsMinor
PriceIsMinor bool
}
type Format string
const (
FormatJSON Format = "json"
FormatXML Format = "xml"
FormatCSV Format = "csv"
)
// Inbound is what the Normalizer sees after the envelope is unwrapped.
type Inbound struct {
Partner string
ContentType string
Body []byte
}
// Detect is the router half of the EIP Normalizer. A declared content type
// wins; otherwise sniff, because "the world is far from perfect".
func Detect(in Inbound) (Format, error) {
if mt, _, err := mime.ParseMediaType(in.ContentType); err == nil {
switch mt {
case "application/json":
return FormatJSON, nil
case "application/xml", "text/xml":
return FormatXML, nil
case "text/csv":
return FormatCSV, nil
}
}
switch b := bytes.TrimSpace(in.Body); {
case len(b) == 0:
return "", invalid("normalize", "empty body")
case b[0] == '{':
return FormatJSON, nil
case b[0] == '<':
return FormatXML, nil
case bytes.Contains(b, []byte(";")):
return FormatCSV, nil
}
return "", invalid("normalize", "unknown format (content type %q)", in.ContentType)
}
// Normalizer routes each input to the parser for its format.
type Normalizer struct {
Parsers map[Format]func(Inbound) (Draft, error)
}
func DefaultNormalizer() Normalizer {
return Normalizer{Parsers: map[Format]func(Inbound) (Draft, error){
FormatJSON: parseJSON, FormatXML: parseXML, FormatCSV: parseCSV,
}}
}
func (n Normalizer) Normalize(in Inbound) (Draft, error) {
f, err := Detect(in)
if err != nil {
return Draft{}, err
}
p, ok := n.Parsers[f]
if !ok {
return Draft{}, invalid("normalize", "no parser for %s", f)
}
d, err := p(in)
d.Partner = in.Partner
return d, err
}
// Partner A: JSON, ISO 8601 with offset, decimal major units as strings.
func parseJSON(in Inbound) (Draft, error) {
var w struct {
OrderID string `json:"orderId"`
Email string `json:"email"`
PlacedAt string `json:"placedAt"`
Currency string `json:"currency"`
Items []struct {
SKU string `json:"sku"`
Qty int `json:"qty"`
Price string `json:"price"`
} `json:"items"`
}
if err := json.Unmarshal(in.Body, &w); err != nil {
return Draft{}, invalid("normalize", "json: %v", err)
}
at, err := time.Parse(time.RFC3339, w.PlacedAt)
if err != nil {
return Draft{}, invalid("normalize", "json placedAt: %v", err)
}
d := Draft{PartnerOrderID: w.OrderID, CustomerEmail: w.Email, Currency: w.Currency, PlacedAt: at}
for _, it := range w.Items {
d.Lines = append(d.Lines, DraftLine{SKU: it.SKU, Qty: it.Qty, Price: it.Price})
}
return d, nil
}
// xmlOrder is partner B's wire shape: local time without offset
// (Europe/Berlin) and a decimal comma.
type xmlOrder struct {
ID string `xml:"id,attr"`
Email string `xml:"Buyer>Email"`
Date string `xml:"Date"`
Cur string `xml:"Cur"`
Lines []struct {
SKU string `xml:"sku,attr"`
Qty int `xml:"qty,attr"`
Unit string `xml:"unit,attr"`
} `xml:"Line"`
}
func parseXML(in Inbound) (Draft, error) {
var w xmlOrder
if err := xml.Unmarshal(in.Body, &w); err != nil {
return Draft{}, invalid("normalize", "xml: %v", err)
}
return xmlDraft(w)
}
func xmlDraft(w xmlOrder) (Draft, error) {
loc, err := time.LoadLocation("Europe/Berlin")
if err != nil {
return Draft{}, err
}
at, err := time.ParseInLocation("02/01/2006 15:04", w.Date, loc)
if err != nil {
return Draft{}, invalid("normalize", "xml Date: %v", err)
}
d := Draft{PartnerOrderID: w.ID, CustomerEmail: w.Email, Currency: w.Cur, PlacedAt: at}
for _, l := range w.Lines {
d.Lines = append(d.Lines, DraftLine{SKU: l.SKU, Qty: l.Qty, Price: l.Unit})
}
return d, nil
}
// Partner C: one CSV line, epoch seconds, prices already in minor units:
// id;email;epoch;currency;sku:qty:minor|sku:qty:minor
func parseCSV(in Inbound) (Draft, error) {
f := strings.Split(strings.TrimSpace(string(in.Body)), ";")
if len(f) != 5 {
return Draft{}, invalid("normalize", "csv: want 5 fields, got %d", len(f))
}
sec, err := strconv.ParseInt(f[2], 10, 64)
if err != nil {
return Draft{}, invalid("normalize", "csv epoch: %v", err)
}
d := Draft{PartnerOrderID: f[0], CustomerEmail: f[1], Currency: f[3], PlacedAt: time.Unix(sec, 0)}
for _, part := range strings.Split(f[4], "|") {
x := strings.Split(part, ":")
if len(x) != 3 {
return Draft{}, invalid("normalize", "csv line %q", part)
}
q, err := strconv.Atoi(x[1])
if err != nil {
return Draft{}, invalid("normalize", "csv qty: %v", err)
}
d.Lines = append(d.Lines, DraftLine{SKU: x[0], Qty: q, Price: x[2], PriceIsMinor: true})
}
return d, nil
}<?php
namespace App\Messaging\Transform;
use DateTimeImmutable;
use DateTimeZone;
use JsonException;
/** EIP Normalizer: detect the format, route to the parser, emit one Draft shape. */
final class Normalizer
{
public function normalize(Envelope $raw): Draft
{
$partner = substr($raw->source, strlen('partner/'));
$draft = match ($this->detect($raw)) {
'json' => $this->json($raw->data),
'xml' => $this->xml($raw->data),
'csv' => $this->csv($raw->data),
};
return new Draft($partner, ...$draft);
}
/** A declared content type wins; otherwise sniff the first bytes. */
private function detect(Envelope $raw): string
{
$type = strtolower(trim(explode(';', $raw->contentType)[0]));
$body = ltrim($raw->data);
return match (true) {
$type === 'application/json' => 'json',
in_array($type, ['application/xml', 'text/xml'], true) => 'xml',
$type === 'text/csv' => 'csv',
$body === '' => throw new InvalidMessage('normalize', 'empty body'),
$body[0] === '{' => 'json',
$body[0] === '<' => 'xml',
str_contains($body, ';') => 'csv',
default => throw new InvalidMessage('normalize', "unknown format ({$raw->contentType})"),
};
}
/** Partner A: JSON, ISO 8601 with offset, decimal major units as strings. */
private function json(string $body): array
{
try {
$w = json_decode($body, true, 16, JSON_THROW_ON_ERROR);
$stamp = $w['placedAt'] ?? '';
if (! is_string($stamp) || ! preg_match('/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/D', $stamp)) { throw new InvalidMessage('normalize', 'json: explicit RFC3339 offset required'); }
$at = new DateTimeImmutable($stamp);
$errors = DateTimeImmutable::getLastErrors();
if ($errors !== false && ($errors['warning_count'] || $errors['error_count'])) { throw new InvalidMessage('normalize', 'json: invalid date'); }
} catch (JsonException|\Exception $e) {
throw new InvalidMessage('normalize', 'json: '.$e->getMessage());
}
return [
'partnerOrderId' => (string) ($w['orderId'] ?? ''),
'email' => (string) ($w['email'] ?? ''),
'currency' => (string) ($w['currency'] ?? ''),
'placedAt' => $at,
'lines' => array_map(fn ($i) => [
'sku' => (string) $i['sku'], 'qty' => $this->quantity($i['qty']), 'price' => (string) $i['price'], 'minor' => false,
], $w['items'] ?? []),
];
}
/** Partner B: XML, local time without offset (Europe/Berlin), decimal comma. */
private function xml(string $body): array
{
$prev = libxml_use_internal_errors(true);
$x = simplexml_load_string($body, options: LIBXML_NONET); // no DTD, no network: XXE-safe defaults
libxml_use_internal_errors($prev);
if ($x === false) {
throw new InvalidMessage('normalize', 'xml: not well-formed');
}
$at = DateTimeImmutable::createFromFormat('!d/m/Y H:i', (string) $x->Date, new DateTimeZone('Europe/Berlin'));
if ($at === false || $at->format('d/m/Y H:i') !== (string) $x->Date) {
throw new InvalidMessage('normalize', 'xml Date: bad format');
}
$lines = [];
foreach ($x->Line as $l) {
$lines[] = ['sku' => (string) $l['sku'], 'qty' => $this->quantity((string) $l['qty']), 'price' => (string) $l['unit'], 'minor' => false];
}
return [
'partnerOrderId' => (string) $x['id'], 'email' => (string) $x->Buyer->Email,
'currency' => (string) $x->Cur, 'placedAt' => $at, 'lines' => $lines,
];
}
/** Partner C: id;email;epoch;currency;sku:qty:minor|sku:qty:minor */
private function csv(string $body): array
{
$f = explode(';', trim($body));
if (count($f) !== 5 || ! ctype_digit($f[2])) {
throw new InvalidMessage('normalize', 'csv: want 5 fields with a numeric epoch');
}
$lines = [];
foreach (explode('|', $f[4]) as $part) {
$p = explode(':', $part);
if (count($p) !== 3) {
throw new InvalidMessage('normalize', "csv line {$part}");
}
$lines[] = ['sku' => $p[0], 'qty' => $this->quantity($p[1]), 'price' => $p[2], 'minor' => true];
}
return [
'partnerOrderId' => $f[0], 'email' => $f[1], 'currency' => $f[3],
'placedAt' => (new DateTimeImmutable('@'.$f[2])), 'lines' => $lines,
];
}
private function quantity(mixed $value): int
{
if ((! is_string($value) && ! is_int($value)) || ! preg_match('/^[0-9]+$/D', (string) $value)) {
throw new InvalidMessage('normalize', 'quantity must be a positive integer');
}
$digits = ltrim((string) $value, '0') ?: '0';
$max = (string) PHP_INT_MAX;
if (strlen($digits) > strlen($max) || (strlen($digits) === strlen($max) && strcmp($digits, $max) > 0) || $digits === '0') {
throw new InvalidMessage('normalize', 'quantity outside range');
}
return (int) $digits;
}
}دامها: Content-Type معتبر را ترجیح دهید و sniffing را fallback محدود بدانید. DTD و دسترسی شبکه در parser XML باید غیرفعال بماند؛ LIBXML_NONET جایگزین بازبینی همهٔ گزینههای XML نیست. Go بهطور پیشفرض external entity را از شبکه دریافت نمیکند. پایگاه منطقهٔ زمانی (Time-zone database) را در deployment حداقلی فراموش نکنید؛ import بستهٔ time/tzdata آن را همراه binary میآورد. تاریخ نامعتبر، زمان بدون offset و ابهام DST باید سیاست مشخص داشته باشند؛ برای ساعت تکرارشدهٔ محلی از شریک offset بخواهید.
مدل دادهٔ مرجع (Canonical Data Model) مهم
به زبان ساده: هر سیستم به جای یادگرفتن قالب همهٔ همسایهها، به یک قرارداد تبادل نگاشت میشود.
بدفهمی رایج (Common misunderstanding): «پس باید کل مدل دادهٔ شرکت را یکجا کامل کنیم.» قرارداد پیام توصیف چیزی است که مبادله میشود، نه اجتماع همهٔ جدولها و فیلدهای سازمان. مدل بیشازحد عمومی تغییر هر تیم را وابسته به کمیته میکند.
تعریف: مدل مستقلی از برنامههای مشارکتکننده که مبنای تولید و مصرف پیام میشود. در اتصال کامل جهتدار، تعداد مترجم زوجی n(n-1) و با مدل مرجع 2n است: برای 2 سیستم، 2 در برابر 4؛ برای 3 سیستم هر دو 6؛ برای 6 سیستم 30 در برابر 12. این حساب فرض اتصال همهبههمه دارد و الزام معماری نیست.
| رویکرد | ایده | شرایط مناسب | هزینه |
|---|---|---|---|
| Canonical Data Model در EIP | یک مدل مشترکِ تبادل | تعداد زیادی سامانه، integration hub، مفاهیم نسبتاً پایدار، مالک مرکزی | توافق دشوار، نشت مدل بزرگترین سیستم، هماهنگی هر تغییر |
| زبان منتشرشده (Published Language) و خدمت میزبان باز (Open Host Service) | مالک بالادست قالب مستند خود را منتشر میکند | مالک روشن برای هر واقعیت و مصرفکنندههای متعدد | چند ناشر با معنای متعارض برای یک مفهوم |
| لایهٔ ضدفساد (Anticorruption Layer) | پاییندست در مرز خود ترجمه میکند | upstream قدیمی یا غیرقابل تغییر | تکرار تبدیل، latency و نگهداری adapter یا سرویس اضافه |
در نمونه، مدل مرجع فقط برای واقعیت OrderPlaced است و مالک آن بافت سفارش است. شریکها در مرز Normalizer دارند؛ مصرفکنندهها در صورت نیاز ACL یا Content Filter خودشان را میسازند. نسخهگذاری در طراحی پیام و رابطهٔ بافتها در Context Maps تعریف میشود.
1 Sales publishes sales.order_placed.v2 -> owned published language
2 Fulfilment consumes unchanged -> conformist
3 Finance maps to ledger entries -> anticorruption layer
4 Analytics takes smaller projection -> content filter
5 Partner XML stops at intake -> normalizerچه زمانی ضرر دارد؟ مدل از پیش برای سیستمهای فرضی، قرارداد برابر schema یک ERP، پیام غولآسا با فیلد اختیاری برای هر مصرفکننده یا قرارداد بیمالک. چه زمانی کمک میکند؟ hub واقعی، شرکای متعدد و مدل کوچک با مالک و روند تغییر مشخص.
نگاشتگر پیام (Messaging Mapper) مهم
به زبان ساده: جزء سومی هم مدل دامنه و هم شکل پیام را میشناسد؛ این دو لازم نیست از وجود یکدیگر خبر داشته باشند.
بدفهمی رایج (Common misunderstanding): «روی entity یک toJson() بگذاریم.» در این حالت تغییر ستون یا ساختار داخلی، API عمومی را تغییر میدهد و domain به کتابخانهٔ پیامرسانی وابسته میشود.
تعریف: نگاشت مستقل میان اشیای دامنه (Domain objects) و دادهٔ پیام. هویت، null، تغییر جزئی و روابط شیء باید به نمایش قابل مبادله تبدیل شوند. نگاشتگر اجازه ندارد constructor یا invariant دامنه را دور بزند.
سناریوها: aggregate سفارش به OrderPlaced، رویداد PaymentSettled به متد دامنه و Eloquent model به قرارداد عمومی بدون افشای کلید داخلی.
قاعدهها: شناسهٔ عمومی منتشر کنید، سازگاری ارز و مجموع سطرها را بررسی کنید و Mapper را قطعی (Deterministic) نگه دارید. ساعت، random و lookup خارجی به این مرحله تعلق ندارند. property test باید رفتوبرگشت شناسه و مبلغ را بررسی کند.
// Package domain is the inside of the order service. It knows nothing about
// JSON, brokers or partners; the Messaging Mapper is the only code that does.
package domain
import (
"errors"
"math"
"time"
)
// Money is a value object in minor units (cents).
type Money struct {
minor int64
currency string
}
func NewMoney(minor int64, currency string) (Money, error) {
if minor < 0 || len(currency) != 3 {
return Money{}, errors.New("domain: invalid money")
}
return Money{minor: minor, currency: currency}, nil
}
func (m Money) Minor() int64 { return m.minor }
func (m Money) Currency() string { return m.currency }
// Line is one order line.
type Line struct {
sku string
qty int
price Money
}
func NewLine(sku string, qty int, price Money) (Line, error) {
if sku == "" || qty <= 0 || len(price.currency) != 3 || price.minor < 0 || price.minor > math.MaxInt64/int64(qty) {
return Line{}, errors.New("domain: invalid line")
}
return Line{sku: sku, qty: qty, price: price}, nil
}
func (l Line) SKU() string { return l.sku }
func (l Line) Qty() int { return l.qty }
func (l Line) Price() Money { return l.price }
func (l Line) Total() int64 { return l.price.minor * int64(l.qty) }
func (l Line) Currency() string { return l.price.currency }
// Order is the aggregate. Its invariants live here, not in the mapper.
type Order struct {
id string
customerID string
placedAt time.Time
lines []Line
}
func NewOrder(id, customerID string, placedAt time.Time, lines []Line) (Order, error) {
if id == "" || len(lines) == 0 {
return Order{}, errors.New("domain: an order needs an id and at least one line")
}
cur := lines[0].Currency()
var sum int64
for _, l := range lines {
if l.qty <= 0 || l.sku == "" || l.price.minor < 0 || l.price.minor > math.MaxInt64/int64(l.qty) || sum > math.MaxInt64-l.Total() {
return Order{}, errors.New("domain: invalid or overflowing line")
}
sum += l.Total()
if l.Currency() != cur {
return Order{}, errors.New("domain: mixed currencies")
}
}
return Order{id: id, customerID: customerID, placedAt: placedAt, lines: append([]Line(nil), lines...)}, nil
}
func (o Order) ID() string { return o.id }
func (o Order) CustomerID() string { return o.customerID }
func (o Order) PlacedAt() time.Time { return o.placedAt }
func (o Order) Lines() []Line { return append([]Line(nil), o.lines...) }
// Total sums the lines in the order currency.
func (o Order) Total() Money {
var sum int64
for _, l := range o.lines {
sum += l.Total()
}
return Money{minor: sum, currency: o.lines[0].Currency()}
}package after
import (
"errors"
"academy/message-transformation/domain"
)
// OrderMapper is the Messaging Mapper: the only code that knows both the
// domain aggregate and the message. Neither knows the mapper exists.
type OrderMapper struct{}
func (OrderMapper) ToMessage(o domain.Order) OrderPlaced {
m := OrderPlaced{
OrderID: o.ID(),
PlacedAt: o.PlacedAt(),
Customer: Customer{ID: o.CustomerID()},
Total: Money{o.Total().Minor(), o.Total().Currency()},
}
for _, l := range o.Lines() {
m.Lines = append(m.Lines, Line{SKU: l.SKU(), Qty: l.Qty(), UnitPrice: Money{l.Price().Minor(), l.Price().Currency()}})
}
return m
}
// FromMessage rebuilds the aggregate through its constructor, so a bad message
// cannot create an invalid object, and checks that the sender's total agrees.
func (OrderMapper) FromMessage(m OrderPlaced) (domain.Order, error) {
var lines []domain.Line
for _, l := range m.Lines {
p, err := domain.NewMoney(l.UnitPrice.AmountMinor, l.UnitPrice.Currency)
if err != nil {
return domain.Order{}, invalid("map", "%v", err)
}
dl, err := domain.NewLine(l.SKU, l.Qty, p)
if err != nil {
return domain.Order{}, invalid("map", "%v", err)
}
lines = append(lines, dl)
}
o, err := domain.NewOrder(m.OrderID, m.Customer.ID, m.PlacedAt, lines)
if err != nil {
return domain.Order{}, invalid("map", "%v", err)
}
if o.Total().Minor() != m.Total.AmountMinor || o.Total().Currency() != m.Total.Currency {
return domain.Order{}, invalid("map", "%v", errors.New("total does not match lines"))
}
return o, nil
}<?php
namespace App\Messaging\Transform;
use App\Models\Order;
use DateTimeImmutable;
use DateTimeZone;
/**
* Messaging Mapper: the one class that knows both the Eloquent model and the
* canonical message. The model has no toMessage(); the message has no model.
*/
final class OrderMapper
{
public function toMessage(Order $order): OrderPlaced
{
$lines = $order->lines->map(fn ($l) => [
'sku' => $l->sku,
'qty' => $l->quantity,
'unit_price' => ['amount_minor' => $l->unit_price_minor, 'currency' => $order->currency],
])->all();
return new OrderPlaced(
orderId: (string) $order->public_id, // never the auto-increment key
partner: 'internal',
placedAt: DateTimeImmutable::createFromInterface($order->placed_at)->setTimezone(new DateTimeZone('UTC')),
// An internal order has no partner e-mail; the hash stays empty by design.
customer: ['email_hash' => '', 'id' => (string) $order->customer_public_id],
lines: $lines,
totalMinor: array_sum(array_map(fn ($l) => $l['qty'] * $l['unit_price']['amount_minor'], $lines)),
currency: $order->currency,
);
}
/** Build a model from a message and refuse messages whose total disagrees with their lines. */
public function fromMessage(OrderPlaced $m): Order
{
if ($m->orderId === '' || $m->lines === []) { throw new InvalidMessage('map', 'id and lines required'); }
$sum = 0;
foreach ($m->lines as $line) {
$qty = $line['qty'];
$minor = $line['unit_price']['amount_minor'];
if (! is_int($qty) || $qty <= 0 || ! is_int($minor) || $minor < 0 || $line['sku'] === '' || $line['unit_price']['currency'] !== $m->currency) {
throw new InvalidMessage('map', 'invalid line or currency');
}
if ($minor > intdiv(PHP_INT_MAX, $qty) || $sum > PHP_INT_MAX - $minor * $qty) {
throw new InvalidMessage('map', 'total exceeds integer range');
}
$sum += $minor * $qty;
}
if ($sum !== $m->totalMinor) {
throw new InvalidMessage('map', 'total does not match lines');
}
$order = new Order([
'public_id' => $m->orderId,
'currency' => $m->currency,
'placed_at' => $m->placedAt,
]);
$order->setRelation('lines', collect($m->lines)->map(fn ($l) => new \App\Models\OrderLine([
'sku' => $l['sku'], 'quantity' => $l['qty'], 'unit_price_minor' => $l['unit_price']['amount_minor'],
])));
return $order;
}
}الگوهای مرتبط با مالکیت صفحهٔ دیگر تکمیلی
| الگو | یک جمله | صفحهٔ مالک |
|---|---|---|
| ارجاع payload (Claim Check) | بدنهٔ بزرگ جدا ذخیره و مرجع حمل میشود | طراحی پیام |
| پالایهٔ پیام (Message Filter) | کل پیام نامنطبق حذف میشود | مسیریابی پیشرفته |
| مسیریاب مبتنی بر محتوا (Content-Based Router) | دادهٔ پیام مسیر را تعیین میکند؛ نیمهٔ اول Normalizer | توپولوژیها |
| شکافنده و تجمیعکننده (Splitter / Aggregator) | یک پیام به جزءها یا جزءها به یک پیام | مسیریابی پیشرفته |
| کانال پیام نامعتبر (Invalid Message Channel) | ورودی پردازشناپذیر را جدا میکند | کانالها |
| کانال مرده (Dead Letter Channel) | شکست تحویل را نگه میدارد | DLQ |
| سازگارکنندهٔ کانال (Channel Adapter) | برنامه یا HTTP را به کانال وصل میکند | کانالها |
| تاریخچه و انشعاب نظارتی (Message History / Wire Tap) | مسیر و نسخهٔ نظارتی پیام | مدیریت سامانه |
تبدیل کجا اجرا میشود؟
میزبان تبدیل (Transformation host) با مالک داده و مالک کد انتخاب میشود. عبارت «سمت broker» نباید با «داخل فرایند broker» اشتباه شود.
| میزبان | مسئولیت | مالک | انتخاب معمول |
|---|---|---|---|
| لبهٔ تولیدکننده | Mapper، Wrapper و پالایش قرارداد عمومی | تیم تولیدکننده | انتشار واقعیت خودمان به زبان خودمان |
| برنامهٔ Connect یا Streams | SMT یا عملگرهای جریان | تیم platform/data | ماسک، حذف فیلد، تغییر شکل سبک و topic routing |
| لبهٔ مصرفکننده | Translator، Normalizer، Enricher و ACL | تیم مصرفکننده | حفاظت از مدل داخلی |
| Gateway، ESB یا iPaaS | ورود شرکا، تبدیل پروتکل و سیاست پاکت | تیم یکپارچهسازی | B2B با تعداد زیاد شریک |
| سرویس تبدیل یا sidecar | هر الگوی لازم در فرایند جدا | تیم مالک سرویس | رفتار شبیه سکوی تبدیل کنار RabbitMQ یا Redis Streams |
| قابلیت | RabbitMQ | Kafka | Redis Streams | صف Laravel |
|---|---|---|---|---|
| تبدیل آمادهٔ بدنه در broker | ندارد؛ interceptor سفارشی Erlang قابلیت توسعه است، built-inها metadata میافزایند؛ Streams protocol خارج از این hook است | broker تبدیل عمومی ندارد؛ Connect و Streams جدا اجرا میشوند | ندارد | driver تبدیل دامنهای انجام نمیدهد |
| افزودن metadata | set_header_timestamp، set_header_routing_node؛ Shovel با dest-publish-properties و x-shovelled | timestamp رکورد، InsertField و InsertHeader در Connect | id ورودی با بخش زمانمانند؛ ساعت کسبوکار نیست | uuid و attempts در payload/driver |
| محل worker | queue A به exchange B | consumer-producer، Streams یا Connect | consumer group | job یا Artisan command |
| خروجی همراه تأیید ورودی | confirm سپس ack؛ اتمیک نیست | transaction برای records و offsets با مصرف read_committed | publish سپس ack؛ MULTI rollback ندارد و خطای XADD جلوی XACK را نمیگیرد | پایان job، نوشتن DB و انتشار خارجی را اتمیک نمیکند |
| هزینهٔ hop اضافه | queue دیگر | topic و retention دیگر | stream دیگر | صف و اجرای job دیگر |
میزبانهای Kafka: SMT و Streams
تبدیل تکپیام (Single Message Transform / SMT) در taskهای Kafka Connect اجرا میشود. transforms ترتیب aliasها را تعیین میکند؛ transforms.<alias>.type کلاس و کلیدهای دیگر تنظیم آن کلاساند. این API برای تغییر سبک هر رکورد مناسب است، نه تماس شبکهای طولانی در مسیر ingest.
| SMT | نسبت با EIP | کاربرد |
|---|---|---|
ReplaceField$Value با exclude/include/renames | Content Filter و Translator ساده | حذف phone و تغییر نام cust_id |
MaskField$Value با fields/replacement | Content Filter | پوشاندن شمارهٔ کارت |
ExtractField، HoistField، Flatten | Translator ساختاری | بازکردن، پوشاندن یا تختکردن ساختار |
InsertField، InsertHeader، HeaderFrom | Wrapper و Enricher سبک | مقدار ثابت، metadata رکورد یا انتقال فیلد به هدر |
Cast، TimestampConverter | Translator نوع داده | رشته به عدد، epoch به زمان |
RegexRouter، TimestampRouter، ValueToKey | مسیریابی و کلید | نام topic و کلید partition |
Filter و شرط (Predicate) | Message Filter | TopicNameMatches، HasHeaderKey، RecordIsTombstone و وارونگی negate |
EventRouter در Debezium | Translator و Router | outbox row به رویداد، رجوع به CDC |
{
"name": "orders-source",
"config": {
"connector.class": "<any source connector that emits order records>",
"topic.prefix": "partner",
"transforms": "dropPii,maskCard,stamp,route",
"transforms.dropPii.type": "org.apache.kafka.connect.transforms.ReplaceField$Value",
"transforms.dropPii.exclude": "phone,shipping_address",
"transforms.maskCard.type": "org.apache.kafka.connect.transforms.MaskField$Value",
"transforms.maskCard.fields": "card_number",
"transforms.maskCard.replacement": "****",
"transforms.stamp.type": "org.apache.kafka.connect.transforms.InsertField$Value",
"transforms.stamp.static.field": "data_source",
"transforms.stamp.static.value": "partner-feed",
"transforms.route.type": "org.apache.kafka.connect.transforms.RegexRouter",
"transforms.route.regex": "partner\\.(.*)",
"transforms.route.replacement": "orders.raw.$1",
"errors.tolerance": "none",
"errors.log.enable": "true"
}
}# Drop test traffic and tombstones before they reach the topic:
# Filter removes a record, a predicate decides which records it applies to.
transforms=dropTest
transforms.dropTest.type=org.apache.kafka.connect.transforms.Filter
transforms.dropTest.predicate=isTest
predicates=isTest
predicates.isTest.type=org.apache.kafka.connect.transforms.predicates.TopicNameMatches
predicates.isTest.pattern=.*\\.testپیکربندیها expected, not run هستند. custom SMT از نظر Java میتواند سرویس خارجی صدا بزند، اما built-inها lookup دلخواه ندارند و فراخوانی بلوکهکننده throughput و retry را به سرویس بیرونی گره میزند. برای آن از Enricher مستقل یا state store استفاده کنید. DropHeaders و SetSchemaMetadata نیز هدر و metadata schema را مدیریت میکنند. SMT سفارشی را میتوان با ساخت SourceRecord/SinkRecord و صداکردن apply آزمود؛ آزمون کامل connector محیط Connect لازم دارد.
پیشفرض errors.tolerance=none خطا را شکست task میداند؛ all رکورد خطادار را رد میکند. errors.log.enable و errors.deadletterqueue.topic.name را آگاهانه تنظیم کنید؛ DLQ استاندارد Connect برای sink پشتیبانی میشود و تضمین عمومی source connector نیست. جزئیات در DLQ است.
Kafka Streams DSL: عملگرهای بیحالت (Stateless) مانند map، mapValues، flatMap، flatMapValues، filter، selectKey، peek و split برای هر رکورد کار میکنند. mapValues کلید را نگه میدارد؛ map یا selectKey میتواند جریان را برای بازپارتیشنبندی (Repartitioning) علامت بزند. ایجاد hop بازپارتیشن معمولاً هنگام عملیات وابسته به کلید مانند join/group رخ میدهد، نه الزاماً همان لحظهٔ map. غنیسازی با KTable یک join حالتدار است و در پردازش جریان پوشش دارد.
// Illustrative Kafka Streams topology (Java, not compiled here): a Content
// Filter and a flatten as stateless operators inside the broker ecosystem.
import java.util.Map;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.KStream;
public class AnalyticsTopology {
public static void build(StreamsBuilder b) {
KStream<String, Map<String, Object>> placed = b.stream("orders.placed"); // value serde configured elsewhere
placed
.filter((orderId, order) -> order != null) // drop tombstones
.filter((orderId, order) -> !"degraded".equals(order.get("enrichment")))
.mapValues(AnalyticsTopology::forAnalytics) // value only: key kept, no repartition
.to("orders.analytics");
}
// Allowlist: build a new, smaller map instead of deleting from the old one.
static Map<String, Object> forAnalytics(Map<String, Object> order) {
return Map.of(
"order_id", order.get("order_id"),
"partner", order.get("partner"),
"total", order.get("total"));
}
}نمونهٔ Java توضیحی و expected, not run است؛ کامپایل نشده. دو filter رکورد را حذف میکنند و mapValues محتوای رکورد باقیمانده را کوچک میکند.
دروازهها و سکوها: API gateway میتواند header و body را طبق policy تغییر دهد؛ ESB و iPaaS Normalizer و mapper گرافیکی دارند. EventBridge Pipes نیز enrichment جدا دارد. هزینهٔ محل مرکزی، مالکیت و گلوگاه مرکزی است؛ Gateway/BFF و ارتباط سرویسها مرز HTTP و پیام را باز میکنند.
سازوکار
ترکیب مرحلهها (Composition) در Go همان Then(f, g) و در Laravel همان Pipeline::send()->through()->thenReturn() است. هر pipe متد handle($passable, Closure $next) دارد و وابستگیهایش از container میآیند.
| دستهٔ خطا | مثال | retry مفید است؟ | اقدام | Go | Laravel |
|---|---|---|---|---|---|
| نامعتبر (Invalid) | ارز ناشناخته، XML خراب، مقدار صفر | خیر؛ ورودی ثابت میماند | fingerprint را پایدار ثبت، سپس ack | ErrInvalid | InvalidMessage |
| گذرا (Transient) | timeout منبع، شکست انتشار | بله، با فاصله و سقف | retry با backoff و در نهایت DLQ | ErrTransient | TransientFailure یا release($delay) |
| باگ (Bug) | nil dereference یا invariant شکسته | تا اصلاح کد خیر | alert و توقف/نگهداری امن ورودی | panic؛ supervisor باید worker را بازیابی کند | exception و سیاست failed job |
رکورد کانال پیام نامعتبر (Invalid Message Channel) شامل مرحله، reason امن، شناسه و SHA-256 بدنه است. خطای parser ممکن است بخشی از ورودی حساس را در متن خود قرار دهد؛ بنابراین متن خام exception را به کانال یا لاگ منتقل نکنید. اصل payload در raw log فقط به اندازهٔ retention قابل بازپخش است؛ برای نگهداری مستقل آن encryption و سیاست دسترسی لازم است.
قطعیت (Determinism): شناسهٔ raw از شریک و بدنه و شناسهٔ خروجی از raw id و type مشتق میشود. retry همان شناسه را تولید میکند تا Inbox تکرار را تشخیص دهد. این طراحی به معنی byte-identical بودن همهٔ خروجیها نیست: enrichment میتواند بین تلاشها تغییر کند و زمان دریافت webhook جدید متفاوت باشد. مصرفکننده باید سیاست snapshot و dedup روشن داشته باشد. برای رویدادهای واقعاً جدا با بدنهٔ یکسان، شناسهٔ رخداد صادرشده از شریک را نیز در هویت ورودی بیاورید.
دو خروجی: ابتدا orders.placed و سپس orders.analytics منتشر میشود. شکست دومی ممکن است اولی را باقی گذاشته باشد؛ retry اولی را با همان id تکرار میکند. اگر دو خروجی باید همراه یک تغییر DB ثبت شوند، Outbox به کار ببرید؛ id ثابت، نوشتن را اتمیک نمیکند.
پول، زمان و شناسه: مبلغ را بدون float به واحد خرد (Minor unit) تبدیل کنید؛ جدول رسمی ISO 4217 از SIX برای EUR دو، JPY صفر و KWD سه رقم دارد. اعشار اضافه، مقدار خارج از کران integer و overflow ضرب/جمع را رد کنید. ارز کنار مبلغ بماند. زمان با offset یا zone صریح وارد و به UTC تبدیل شود؛ زمان محلی تکرارشده/ناموجود در DST به قرارداد رفع ابهام نیاز دارد. شناسهٔ شریک را namespace کنید تا berlin-shop:B-77 با سفارش شریک دیگر یکی نشود.
تکامل schema: Upcaster باید هر پلهٔ نسخه را مشخص و نسخهٔ ناشناخته را رد کند، نه اینکه آن را ظاهراً به نسخهٔ جدید برچسب بزند. قواعد سازگاری در Schema Evolution و replay رویدادهای قدیمی در Event Sourcing است.
ترتیب و فشار برگشتی: تغییر key در Kafka میتواند partition و قلمرو ترتیب را عوض کند؛ Ordering را رعایت کنید. غنیساز کند پیام را در پرواز نگه میدارد؛ با prefetch برابر 20 تا 20 پیام منتظر میمانند. deadline و همزمانی محدود از Backpressure میآیند.
آزمون، مشاهدهپذیری و کارایی
تبدیل خالص را بدون broker آزمون کنید؛ معیار، رفتار قرارداد است، نه صرفاً عبور compiler.
| آزمون | چه چیزی بررسی میشود | روش |
|---|---|---|
| فایل طلایی (Golden file) | خروجی دقیق ورودی ثبتشده تغییر نکرده | testdata/، مقایسهٔ JSON و بازبینی diff هنگام -update |
| آزمون ویژگی (Property test) | قانون رفتوبرگشت و حفظ معنا | testing/quick، حفظ id/total، unwrap(wrap(x)) و رد bit flip |
| جدول خطا (Error-table test) | همهٔ کلاسهای invalid به مسیر درست میروند | ورودی خراب، خروجی صفر، fingerprint بدون PII |
| آزمون قرارداد (Contract test) | مصرفکننده خروجی جدید را میفهمد | Testing Messaging |
برای هر شریک golden مستقل داشته باشید. خط خالی، فیلد اضافه، BOM و encoding نامعتبر را در corpus بیاورید. آزمون «عدم نشت PII» باید هم خروجی موفق و هم reason خطا را با ایمیل شناختهشده بررسی کند.
package after
import (
"bytes"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"testing/quick"
"time"
"academy/message-transformation/domain"
)
var update = flag.Bool("update", false, "rewrite golden files")
var hashKey = []byte("test-key")
type fakeDir struct {
calls atomic.Int32
fn func(string) (Customer, error)
}
func (f *fakeDir) ByEmailHash(_ context.Context, h string) (Customer, error) {
f.calls.Add(1)
return f.fn(h)
}
type memPub struct {
mu sync.Mutex
sent map[string][]Envelope
}
func (m *memPub) Publish(_ context.Context, dest string, e Envelope) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.sent == nil {
m.sent = map[string][]Envelope{}
}
m.sent[dest] = append(m.sent[dest], e)
return nil
}
func okDir() *fakeDir {
return &fakeDir{fn: func(string) (Customer, error) { return Customer{ID: "c-1", Tier: "gold", Country: "DE"}, nil }}
}
func newPipeline(dir Directory, pub Publisher) *Pipeline {
return &Pipeline{
Normalizer: DefaultNormalizer(),
Translate: ToCanonical(hashKey),
Enricher: &Enricher{Dir: dir, TTL: time.Minute, NegTTL: time.Minute, StaleOK: time.Hour, Timeout: time.Second},
Out: pub,
}
}
// Golden files: the exact canonical JSON for each partner input.
func TestGoldenPartners(t *testing.T) {
cases := []struct{ partner, in, ct string }{
{"acme", "partner_a.json", "application/json"},
{"berlin-shop", "partner_b.xml", "application/xml; charset=utf-8"},
{"tokyo-mart", "partner_c.csv", ""}, // no content type: sniffed
}
for _, c := range cases {
t.Run(c.partner, func(t *testing.T) {
body, err := os.ReadFile(filepath.Join("testdata", c.in))
if err != nil {
t.Fatal(err)
}
pub := &memPub{}
out, err := newPipeline(okDir(), pub).Handle(context.Background(),
WrapRaw(c.partner, c.ct, body, time.Date(2026, 11, 25, 7, 0, 0, 0, time.UTC)))
if err != nil || out != Ack {
t.Fatalf("outcome %v err %v", out, err)
}
var pretty bytes.Buffer
if err := json.Indent(&pretty, pub.sent[TopicCanonical][0].Data, "", " "); err != nil {
t.Fatal(err)
}
pretty.WriteByte('\n')
golden := filepath.Join("testdata", c.partner+".golden.json")
if *update {
_ = os.WriteFile(golden, pretty.Bytes(), 0o644)
}
want, _ := os.ReadFile(golden)
if !bytes.Equal(pretty.Bytes(), want) {
t.Errorf("golden mismatch for %s\n--- got\n%s--- want\n%s", c.partner, pretty.Bytes(), want)
}
})
}
}
// The canonical event and the analytics event never contain the e-mail.
func TestNoPIILeaks(t *testing.T) {
body, _ := os.ReadFile("testdata/partner_a.json")
pub := &memPub{}
_, _ = newPipeline(okDir(), pub).Handle(context.Background(), WrapRaw("acme", "application/json", body, time.Now()))
for dest, evs := range pub.sent {
for _, e := range evs {
if strings.Contains(strings.ToLower(string(e.Data)), "alice@example.com") {
t.Errorf("%s leaks the e-mail", dest)
}
}
}
if strings.Contains(string(pub.sent[TopicAnalytics][0].Data), "customer") {
t.Error("analytics event must not carry customer data")
}
}
// Invalid input goes to the invalid channel, is acknowledged, and is not stored in clear.
func TestInvalidMessageChannel(t *testing.T) {
bad := map[string]string{
"not json": `{"orderId":`,
"bad currency": `{"orderId":"1","email":"a@b.c","placedAt":"2026-11-25T10:00:00Z","currency":"XXX","items":[{"sku":"s","qty":1,"price":"1"}]}`,
"too many cents": `{"orderId":"1","email":"a@b.c","placedAt":"2026-11-25T10:00:00Z","currency":"JPY","items":[{"sku":"s","qty":1,"price":"1.50"}]}`,
"zero qty": `{"orderId":"1","email":"a@b.c","placedAt":"2026-11-25T10:00:00Z","currency":"USD","items":[{"sku":"s","qty":0,"price":"1"}]}`,
}
for name, in := range bad {
t.Run(name, func(t *testing.T) {
pub := &memPub{}
out, err := newPipeline(okDir(), pub).Handle(context.Background(), WrapRaw("acme", "application/json", []byte(in), time.Now()))
if out != Ack || err != nil {
t.Fatalf("want Ack/nil, got %v/%v", out, err)
}
if len(pub.sent[TopicInvalid]) != 1 || len(pub.sent[TopicCanonical]) != 0 {
t.Fatalf("routing wrong: %v", pub.sent)
}
if strings.Contains(string(pub.sent[TopicInvalid][0].Data), "a@b.c") {
t.Error("invalid record stored the payload in clear")
}
})
}
}
func TestEnricherCoalescesAndCaches(t *testing.T) {
dir := &fakeDir{fn: func(string) (Customer, error) {
time.Sleep(20 * time.Millisecond)
return Customer{ID: "c-9", Tier: "silver"}, nil
}}
e := &Enricher{Dir: dir, TTL: time.Minute, NegTTL: time.Minute, Timeout: time.Second}
var wg sync.WaitGroup
for i := 0; i < 20; i++ {
wg.Add(1)
go func() {
defer wg.Done()
_, _ = e.Enrich(context.Background(), OrderPlaced{Customer: Customer{EmailHash: "h"}})
}()
}
wg.Wait()
_, _ = e.Enrich(context.Background(), OrderPlaced{Customer: Customer{EmailHash: "h"}})
if n := dir.calls.Load(); n != 1 {
t.Fatalf("directory called %d times, want 1", n)
}
}
func TestEnricherStaleOnErrorAndTransient(t *testing.T) {
now := time.Now()
fail := false
dir := &fakeDir{fn: func(string) (Customer, error) {
if fail {
return Customer{}, errors.New("directory down")
}
return Customer{ID: "c-1", Tier: "gold"}, nil
}}
e := &Enricher{Dir: dir, TTL: time.Minute, StaleOK: time.Hour, Timeout: time.Second, Now: func() time.Time { return now }}
if _, err := e.Enrich(context.Background(), OrderPlaced{Customer: Customer{EmailHash: "h"}}); err != nil {
t.Fatal(err)
}
now = now.Add(10 * time.Minute) // expired but within StaleOK
fail = true
o, err := e.Enrich(context.Background(), OrderPlaced{Customer: Customer{EmailHash: "h"}})
if err != nil || o.Enrichment != "degraded" || o.Customer.Tier != "gold" {
t.Fatalf("want degraded gold, got %+v %v", o, err)
}
_, err = e.Enrich(context.Background(), OrderPlaced{Customer: Customer{EmailHash: "never-seen"}})
if !errors.Is(err, ErrTransient) {
t.Fatalf("want ErrTransient, got %v", err)
}
}
// Property: formatting n minor units as a decimal string and parsing it back is the identity.
func TestParseMinorRoundTrip(t *testing.T) {
f := func(n uint32, d uint8) bool {
digits := int(d % 4)
pow := int64(1)
for i := 0; i < digits; i++ {
pow *= 10
}
s := fmt.Sprint(int64(n) / pow)
if digits > 0 {
s += fmt.Sprintf(".%0*d", digits, int64(n)%pow)
}
got, err := ParseMinor(s, digits)
return err == nil && got == int64(n)
}
if err := quick.Check(f, nil); err != nil {
t.Error(err)
}
}
// Property: the Messaging Mapper round-trips every valid order.
func TestMapperRoundTrip(t *testing.T) {
f := func(qty1, qty2 uint8, p1, p2 uint16) bool {
cur := "EUR"
mk := func(sku string, q uint8, p uint16) domain.Line {
m, _ := domain.NewMoney(int64(p), cur)
l, _ := domain.NewLine(sku, int(q%9)+1, m)
return l
}
o, err := domain.NewOrder("o-1", "c-1", time.Unix(1_700_000_000, 0).UTC(), []domain.Line{mk("a", qty1, p1), mk("b", qty2, p2)})
if err != nil {
return false
}
m := OrderMapper{}
back, err := m.FromMessage(m.ToMessage(o))
return err == nil && back.Total() == o.Total() && back.ID() == o.ID() && len(back.Lines()) == 2
}
if err := quick.Check(f, nil); err != nil {
t.Error(err)
}
}
// Property: unwrap(wrap(x)) == x for the sign+seal stack; any flipped bit is rejected.
func TestEnvelopeStack(t *testing.T) {
sealer, err := NewSealer(bytes.Repeat([]byte{7}, 32))
if err != nil {
t.Fatal(err)
}
st := Stack{Signer{Key: []byte("k")}, sealer}
f := func(body []byte) bool {
e := WrapRaw("acme", "application/json", body, time.Unix(1_700_000_000, 0))
b, err := Encode(e, st)
if err != nil {
return false
}
got, err := Decode(b, st)
return err == nil && got.ID == e.ID && bytes.Equal(got.Data, e.Data)
}
if err := quick.Check(f, nil); err != nil {
t.Error(err)
}
b, _ := Encode(WrapRaw("acme", "text/plain", []byte("x"), time.Now()), st)
b[len(b)-1] ^= 1
if _, err := Decode(b, st); err == nil {
t.Error("tampered message was accepted")
}
}
func TestStripFields(t *testing.T) {
var doc map[string]any
_ = json.Unmarshal([]byte(`{"email":"a@b.c","items":[{"sku":"s","card":"4111"}],"payment":{"card":"4111","kind":"visa"}}`), &doc)
StripFields(doc, "email", "items.card", "payment.card")
b, _ := json.Marshal(doc)
if strings.Contains(string(b), "4111") || strings.Contains(string(b), "a@b.c") {
t.Errorf("not stripped: %s", b)
}
}مشاهدهپذیری (Observability): شمارندهٔ transform_total{stage,outcome}، histogram زمان هر مرحله، نسبت cache hit و تعداد degraded را ثبت کنید. افزایش نرخ invalid برای یک شریک از عدد مطلق کل مفیدتر است. correlation id همان raw id باشد تا مسیر از webhook تا خروجی قابل دنبالکردن شود. جزئیات trace و broker metric در Observability است.
کارایی (Performance): جدول زیر فرضیهٔ آزمایش است؛ اندازهگیری این نوبت نیست. ورودی باید از reader محدود خوانده شود؛ اگر ابتدا کل فایل را در حافظه بار کنید، streaming مزیت مورد انتظار را ندارد.
| روش | زمان هر batch | بایت تخصیصیافته | تعداد allocation | حافظهٔ زنده برای 100000 سفارش |
|---|---|---|---|---|
| decode کل آرایه سپس تبدیل | اندازهگیری شود | وابسته به همهٔ اشیای آرایه | اندازهگیری شود | با تعداد اشیای decoded رشد میکند |
json.Decoder با Token/More/Decode | ممکن است کمتر یا بیشتر باشد | مجموع کار الزاماً کمتر نیست | ممکن است بیشتر باشد | در صورت خروجی تدریجی با اندازهٔ رکورد جاری محدود میشود |
خواندن جریانی (Streaming) قول سرعت بیشتر نمیدهد؛ هدف محدودکردن peak memory است. یکبار decode و یکبار encode کنید، نوع مشخص را به map[string]any ترجیح دهید و buffer reuse یا sync.Pool را بعد از profile اضافه کنید. payload بزرگ با Claim Check از broker خارج میشود؛ base64 پاکت حدود یکسوم حجم اضافه میکند.
package after
import (
"encoding/json"
"encoding/xml"
"io"
)
// StreamJSONOrders turns a huge partner JSON array into one Draft at a time.
// Memory stays at one order, not the whole file; fn returning an error stops
// the stream. Use this for batch files and bulk webhooks, not for the small
// one-order messages that make up most traffic.
func StreamJSONOrders(r io.Reader, fn func(Draft) error) error {
dec := json.NewDecoder(r)
token, err := dec.Token()
if err != nil || token != json.Delim('[') {
return invalid("normalize", "json batch must be an array")
}
for dec.More() {
var raw json.RawMessage
if err := dec.Decode(&raw); err != nil {
return invalid("normalize", "json batch element: %v", err)
}
d, err := parseJSON(Inbound{Body: raw})
if err != nil {
return err
}
if err := fn(d); err != nil {
return err
}
}
token, err = dec.Token()
if err != nil || token != json.Delim(']') {
return invalid("normalize", "json batch missing closing bracket")
}
if _, err := dec.Token(); err != io.EOF {
return invalid("normalize", "json batch has trailing data")
}
return nil
}
// StreamXMLOrders does the same for a large XML document, one <Order> element
// at a time, using the token API instead of unmarshalling the whole tree.
func StreamXMLOrders(r io.Reader, fn func(Draft) error) error {
dec := xml.NewDecoder(r)
for {
tok, err := dec.Token()
if err == io.EOF {
return nil
}
if err != nil {
return invalid("normalize", "xml batch: %v", err)
}
se, ok := tok.(xml.StartElement)
if !ok || se.Name.Local != "Order" {
continue
}
var w xmlOrder
if err := dec.DecodeElement(&w, &se); err != nil {
return invalid("normalize", "xml order: %v", err)
}
d, err := xmlDraft(w)
if err != nil {
return err
}
if err := fn(d); err != nil {
return err
}
}
}در PHP، XMLReader همراه generator و LazyCollection اجازه میدهد map و chunk lazy بمانند:
<?php
namespace App\Messaging\Transform;
use Illuminate\Support\LazyCollection;
use XMLReader;
/**
* Streaming a large partner batch: memory holds one order at a time.
* XMLReader is a pull parser; each <Order> is expanded on its own and the
* rest of the document is never in memory. LazyCollection wraps the generator
* so the normal collection pipeline (map, chunk, each) stays lazy.
*/
final class StreamOrders
{
/** @return LazyCollection<int, string> one <Order> element as an XML string */
public static function xmlOrders(string $path): LazyCollection
{
return LazyCollection::make(function () use ($path) {
$r = new XMLReader;
if (! $r->open($path, null, LIBXML_NONET)) { throw new \RuntimeException('cannot open XML input'); }
try {
$available = $r->read();
while ($available) {
if ($r->nodeType === XMLReader::ELEMENT && $r->name === 'Order') {
yield $r->readOuterXml();
$available = $r->next(); // Already positioned at the next sibling.
continue;
}
$available = $r->read();
}
} finally {
$r->close();
}
});
}
/** NDJSON (one JSON object per line) is the easiest format to stream. */
public static function ndjsonOrders(string $path): LazyCollection
{
return LazyCollection::make(function () use ($path) {
$h = fopen($path, 'rb');
if ($h === false) { throw new \RuntimeException('cannot open NDJSON input'); }
try {
while (($line = fgets($h)) !== false) {
if (trim($line) !== '') {
yield $line;
}
}
} finally {
fclose($h);
}
});
}
}
// Usage inside a console command: each order is normalized and translated
// one at a time; chunk(500) bounds the size of the publish batch.
//
// StreamOrders::xmlOrders($path)
// ->map(fn (string $xml) => $normalizer->normalize(Envelope::wrapRaw('berlin', 'application/xml', $xml)))
// ->map(fn (Draft $d) => $translator->translate($d))
// ->chunk(500)
// ->each(fn ($orders) => $publisher->publishBatch($orders));خط لولهٔ نمونه: webhook شریک تا OrderPlaced
سه شریک قالب متفاوت دارند: acme از JSON، زمان ISO 8601 و مبلغ رشتهای استفاده میکند؛ berlin-shop از XML، زمان محلی Berlin و ممیز ویرگول؛ tokyo-mart از رکورد ;، epoch و مبلغ خرد. سرویسهای داخلی OrderPlaced و analytics نمای کوچکی بدون دادهٔ مشتری میخواهند.
ورودیهای آزمون (Test inputs):
{"orderId":"A-1001","email":"Alice@Example.com","placedAt":"2026-11-25T10:00:00+03:30","currency":"USD","items":[{"sku":"SKU-1","qty":2,"price":"19.99"},{"sku":"SKU-2","qty":1,"price":"5"}]}<Order id="B-77"><Buyer><Email>alice@example.com</Email></Buyer><Date>25/11/2026 10:00</Date><Cur>EUR</Cur><Line sku="SKU-1" qty="1" unit="5,50"/><Line sku="SKU-3" qty="3" unit="0,99"/></Order>C-9;alice@example.com;1795600800;JPY;SKU-1:2:1999|SKU-2:1:5001 webhook + content type -> wrap raw, deterministic id, 202 after durable enqueue
2 raw envelope -> partner.orders.raw retained for replay
3 Normalizer -> Draft; unknown format => invalid
4 Translator -> UTC, integer minor units, namespaced id, HMAC email
5 Enricher -> customer/tier/country; cold timeout => retry
6 canonical publish -> orders.placed, key=order id
7 Content Filter -> AnalyticsOrder without customer id/hash
8 analytics publish -> orders.analytics
9 invalid path -> safe fingerprint record, then acknowledgeGo: مرحلههای نوعدار
Pipeline نتیجهٔ acknowledge یا retry را برمیگرداند؛ adapter broker مسئول settlement واقعی است. generic functionها خطای اتصال نوع مرحلهها را زود مشخص میکنند. publisher از domain جدا است و آزمون میتواند نسخهٔ حافظهای آن را تزریق کند.
package after
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
)
// Publisher sends one envelope to one destination; the broker files implement it.
type Publisher interface {
Publish(ctx context.Context, dest string, e Envelope) error
}
// Outcome tells the consumer loop what to do with the incoming message.
type Outcome int
const (
Ack Outcome = iota // published, or sent to the invalid channel: done
Retry // transient: nack/requeue or do not commit
)
// Pipeline is: Normalizer -> Translator -> Enricher, then publish twice
// (canonical for services, filtered for analytics).
type Pipeline struct {
Normalizer Normalizer
Translate Func[Draft, OrderPlaced]
Enricher *Enricher
Out Publisher
}
func (p *Pipeline) stages() Func[Inbound, OrderPlaced] {
norm := func(_ context.Context, in Inbound) (Draft, error) { return p.Normalizer.Normalize(in) }
enrich := func(ctx context.Context, o OrderPlaced) (OrderPlaced, error) { return p.Enricher.Enrich(ctx, o) }
return Then(Then(norm, p.Translate), enrich)
}
// Handle processes one raw envelope. Errors are classified: invalid messages
// go to TopicInvalid and are acknowledged (retrying cannot help); transient
// ones are retried; a publish failure is transient too.
func (p *Pipeline) Handle(ctx context.Context, raw Envelope) (Outcome, error) {
order, err := p.stages()(ctx, Inbound{
Partner: partnerOf(raw.Source),
ContentType: raw.ContentType,
Body: raw.Data,
})
switch {
case errors.Is(err, ErrInvalid):
return Ack, p.reject(ctx, raw, err)
case err != nil:
return Retry, err
}
// Deterministic ids: a redelivered raw message yields the same event ids,
// so consumers can deduplicate (see idempotent-consumer-inbox).
body, _ := json.Marshal(order)
canonical := p.event(raw, TypeOrderPlaced, order.OrderID, body)
analytics, _ := json.Marshal(ForAnalytics(order))
if err := p.Out.Publish(ctx, TopicCanonical, canonical); err != nil {
return Retry, err
}
if err := p.Out.Publish(ctx, TopicAnalytics, p.event(raw, "order.placed.analytics", order.OrderID, analytics)); err != nil {
return Retry, err // the canonical copy is re-sent: same id, deduplicated downstream
}
return Ack, nil
}
func (p *Pipeline) event(raw Envelope, typ, key string, body []byte) Envelope {
sum := sha256.Sum256([]byte(raw.ID + "|" + typ))
return Envelope{
ID: hex.EncodeToString(sum[:16]), Type: typ, Source: "order-intake", Key: key,
Version: SchemaVersionOrder, OccurredAt: raw.OccurredAt,
CorrelationID: raw.ID, CausationID: raw.ID,
ContentType: "application/json", Data: body,
}
}
// Reject is the Invalid Message Channel record: what failed, where, and a
// fingerprint of the input. The payload itself is NOT stored in clear.
type Reject struct {
Stage string `json:"stage"`
Reason string `json:"reason"`
RawID string `json:"raw_id"`
Source string `json:"source"`
PayloadSHA string `json:"payload_sha256"`
}
func (p *Pipeline) reject(ctx context.Context, raw Envelope, cause error) error {
var se *StageError
errors.As(cause, &se)
sum := sha256.Sum256(raw.Data)
b, _ := json.Marshal(Reject{
Stage: se.Stage, Reason: "invalid_" + se.Stage, RawID: raw.ID, Source: raw.Source,
PayloadSHA: hex.EncodeToString(sum[:]),
})
return p.Out.Publish(ctx, TopicInvalid, Envelope{
ID: raw.ID + ".invalid", Type: "partner.order.invalid", Source: "order-intake",
Version: 1, OccurredAt: raw.OccurredAt, CorrelationID: raw.ID,
ContentType: "application/json", Data: b,
})
}
func partnerOf(source string) string {
const prefix = "partner/"
if len(source) > len(prefix) {
return source[len(prefix):]
}
return source
}Laravel 13: کنترلر، job و pipeها
کنترلر سازگارکنندهٔ کانال (Channel Adapter) و پوشانندهٔ پاکت است؛ job با ShouldBeEncrypted دادهٔ حساس را در queue payload محافظت میکند. این رمزنگاری جایگزین HTTPS، webhook authentication یا رمزنگاری raw topic نیست. bindingهای Publisher و تنظیم customer service باید در برنامهٔ میزبان فراهم شوند.
<?php
namespace App\Http\Controllers;
use App\Messaging\Transform\Envelope;
use App\Messaging\Transform\Jobs\TransformPartnerOrder;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
/**
* Channel Adapter + Envelope Wrapper at the edge: take whatever the partner
* sent, wrap it untouched, queue it, answer fast. Verifying the partner's
* signature header belongs here too (see messaging-security).
*/
final class PartnerWebhookController
{
public function __invoke(Request $request, string $partner): Response
{
$raw = Envelope::wrapRaw($partner, (string) $request->header('Content-Type', ''), $request->getContent());
TransformPartnerOrder::dispatch($raw)->onQueue('intake');
return response('', 202);
}
}<?php
use App\Http\Controllers\PartnerWebhookController;
use Illuminate\Support\Facades\Route;
// routes/api.php: one URL per partner, any body format.
Route::post('/webhooks/{partner}/orders', PartnerWebhookController::class)
->where('partner', '[a-z0-9-]+');<?php
namespace App\Messaging\Transform\Jobs;
use App\Messaging\Transform\Envelope;
use App\Messaging\Transform\InvalidMessage;
use App\Messaging\Transform\OrderIntake;
use App\Messaging\Transform\TransientFailure;
use Illuminate\Contracts\Queue\ShouldBeEncrypted;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;
/**
* The consumer-edge transformation step. ShouldBeEncrypted keeps the raw
* partner payload (e-mail, maybe a card) unreadable inside the queue backend.
*/
final class TransformPartnerOrder implements ShouldBeEncrypted, ShouldQueue
{
use Queueable;
public int $tries = 6;
public function __construct(public Envelope $raw) {}
/** Seconds before attempts 2, 3, 4...: transient failures only. */
public function backoff(): array
{
return [5, 30, 120, 600];
}
public function handle(OrderIntake $intake): void
{
try {
$intake->handle($this->raw);
} catch (InvalidMessage $e) {
// Invalid message channel: record why, keep a fingerprint, do not retry.
DB::table('invalid_messages')->insert([
'raw_id' => $this->raw->id,
'source' => $this->raw->source,
'stage' => $e->stage,
'reason' => 'invalid_'.$e->stage, // Never persist parser text containing input data.
'payload_sha256' => hash('sha256', $this->raw->data),
'created_at' => now(),
]);
} catch (TransientFailure $e) {
$this->release($this->backoff()[min($this->attempts() - 1, 3)]);
}
}
}<?php
namespace App\Messaging\Transform;
use App\Messaging\Transform\Pipes\Enrich;
use App\Messaging\Transform\Pipes\Normalize;
use App\Messaging\Transform\Pipes\Translate;
use Illuminate\Pipeline\Pipeline;
/**
* Pipes and Filters with Laravel's Pipeline: send a state object through
* classes that each expose handle($state, $next). Pipes are resolved from the
* container, so their dependencies are injected.
*/
final class OrderIntake
{
public function __construct(
private readonly Pipeline $pipeline,
private readonly ContentFilter $filter,
private readonly Publisher $publisher,
) {}
/** @throws InvalidMessage|TransientFailure */
public function handle(Envelope $raw): void
{
$state = $this->pipeline
->send(new IntakeState($raw))
->through([Normalize::class, Translate::class, Enrich::class])
->thenReturn();
$order = $state->order;
// Deterministic ids: a redelivered raw message produces the same event ids.
$this->publisher->publish('orders.placed', $this->event($raw, 'order.placed', $order->orderId, $order->toArray()));
$this->publisher->publish('orders.analytics', $this->event($raw, 'order.placed.analytics', $order->orderId, $this->filter->forAnalytics($order)));
}
private function event(Envelope $raw, string $type, string $key, array $body): Envelope
{
return new Envelope(
id: substr(hash('sha256', $raw->id.'|'.$type), 0, 32),
type: $type, source: 'order-intake', version: 2, occurredAt: $raw->occurredAt,
contentType: 'application/json', data: json_encode($body, JSON_THROW_ON_ERROR),
correlationId: $raw->id, causationId: $raw->id, key: $key,
);
}
}<?php
namespace App\Messaging\Transform;
/** The passable that travels through the pipes; each stage fills one field. */
final class IntakeState
{
public ?Draft $draft = null;
public ?OrderPlaced $order = null;
public function __construct(public readonly Envelope $raw) {}
}<?php
namespace App\Messaging\Transform\Pipes;
use App\Messaging\Transform\IntakeState;
use App\Messaging\Transform\Normalizer;
use Closure;
final class Normalize
{
public function __construct(private readonly Normalizer $normalizer) {}
public function handle(IntakeState $s, Closure $next): mixed
{
$s->draft = $this->normalizer->normalize($s->raw);
return $next($s);
}
}<?php
namespace App\Messaging\Transform\Pipes;
use App\Messaging\Transform\IntakeState;
use App\Messaging\Transform\Translator;
use Closure;
final class Translate
{
public function __construct(private readonly Translator $translator) {}
public function handle(IntakeState $s, Closure $next): mixed
{
$s->order = $this->translator->translate($s->draft);
return $next($s);
}
}<?php
namespace App\Messaging\Transform\Pipes;
use App\Messaging\Transform\CustomerEnricher;
use App\Messaging\Transform\IntakeState;
use Closure;
final class Enrich
{
public function __construct(private readonly CustomerEnricher $enricher) {}
public function handle(IntakeState $s, Closure $next): mixed
{
$s->order = $this->enricher->enrich($s->order);
return $next($s);
}
}اشیای داده (Value objects)، exceptionها و قرارداد publisher مشترکاند:
<?php
namespace App\Messaging\Transform;
use DateTimeImmutable;
/** Normalizer output: one shape for every partner format, partner values intact. */
final readonly class Draft
{
/** @param list<array{sku:string,qty:int,price:string,minor:bool}> $lines */
public function __construct(
public string $partner,
public string $partnerOrderId,
public string $email,
public string $currency,
public DateTimeImmutable $placedAt,
public array $lines,
) {}
}<?php
namespace App\Messaging\Transform;
use DateTimeImmutable;
use DateTimeZone;
/** The Canonical Data Model for "order placed". */
final readonly class OrderPlaced
{
/**
* @param list<array{sku:string,qty:int,unit_price:array{amount_minor:int,currency:string}}> $lines
* @param array{email_hash:string,id?:string,tier?:string,country?:string} $customer
*/
public function __construct(
public string $orderId,
public string $partner,
public DateTimeImmutable $placedAt,
public array $customer,
public array $lines,
public int $totalMinor,
public string $currency,
public string $enrichment = 'ok',
) {}
public function withCustomer(array $extra, string $enrichment): self
{
return new self(
$this->orderId, $this->partner, $this->placedAt,
[...$this->customer, ...$extra], $this->lines,
$this->totalMinor, $this->currency, $enrichment,
);
}
public function toArray(): array
{
return [
'order_id' => $this->orderId,
'partner' => $this->partner,
'placed_at' => $this->placedAt->setTimezone(new DateTimeZone('UTC'))->format('Y-m-d\TH:i:s\Z'),
'customer' => $this->customer,
'lines' => $this->lines,
'total' => ['amount_minor' => $this->totalMinor, 'currency' => $this->currency],
'enrichment' => $this->enrichment,
];
}
}<?php
namespace App\Messaging\Transform;
use RuntimeException;
/** Can never succeed: send to the invalid message channel, do not retry. */
final class InvalidMessage extends RuntimeException
{
public function __construct(public readonly string $stage, string $reason)
{
parent::__construct("{$stage}: {$reason}");
}
}<?php
namespace App\Messaging\Transform;
use RuntimeException;
use Throwable;
/** May succeed later (lookup timed out): release the job, retry with backoff. */
final class TransientFailure extends RuntimeException
{
public function __construct(public readonly string $stage, Throwable $previous)
{
parent::__construct("{$stage}: {$previous->getMessage()}", 0, $previous);
}
}<?php
namespace App\Messaging\Transform;
interface Publisher
{
public function publish(string $destination, Envelope $envelope): void;
}ثبت پیام نامعتبر و query پشتیبانی در PostgreSQL:
CREATE TABLE invalid_messages (
id BIGSERIAL PRIMARY KEY,
raw_id VARCHAR(64) NOT NULL,
source VARCHAR(255) NOT NULL,
stage VARCHAR(32) NOT NULL,
reason TEXT NOT NULL,
payload_sha256 CHAR(64) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX invalid_messages_source_created ON invalid_messages (source, created_at DESC);
SELECT source, stage, reason, count(*) AS n, min(created_at) AS first_seen
FROM invalid_messages
WHERE created_at > now() - interval '1 day'
GROUP BY source, stage, reason
ORDER BY n DESC
LIMIT 20;Migration و feature test متناظر؛ اجرای Laravel به برنامهٔ میزبان و dependencyهای آن نیاز دارد و اینجا expected, not run است:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('invalid_messages', function (Blueprint $table) {
$table->id();
$table->string('raw_id', 64)->index(); // the envelope id of the raw message
$table->string('source');
$table->string('stage', 32); // normalize | translate | map
$table->text('reason');
$table->char('payload_sha256', 64); // a fingerprint, never the payload
$table->timestamp('created_at');
});
}
};<?php
namespace Tests\Feature;
use App\Messaging\Transform\Envelope;
use App\Messaging\Transform\InvalidMessage;
use App\Messaging\Transform\OrderIntake;
use App\Messaging\Transform\Publisher;
use App\Messaging\Transform\TransientFailure;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;
final class OrderIntakeTest extends TestCase
{
private object $sent;
protected function setUp(): void
{
parent::setUp();
config(['services.customers.url' => 'https://customers.test']);
$this->sent = new class implements Publisher {
public array $byTopic = [];
public function publish(string $destination, Envelope $envelope): void
{
$this->byTopic[$destination][] = $envelope;
}
};
$this->app->instance(Publisher::class, $this->sent);
}
public function test_three_partner_formats_become_one_canonical_event(): void
{
Http::fake(['customers.test/*' => Http::response(['id' => 'c-1', 'tier' => 'gold', 'country' => 'DE'])]);
$inputs = [
['acme', 'application/json', '{"orderId":"A-1","email":"Alice@Example.com","placedAt":"2026-11-25T10:00:00+03:30","currency":"USD","items":[{"sku":"S1","qty":2,"price":"19.99"}]}'],
['berlin', 'application/xml', '<Order id="B-1"><Buyer><Email>alice@example.com</Email></Buyer><Date>25/11/2026 10:00</Date><Cur>EUR</Cur><Line sku="S1" qty="2" unit="19,99"/></Order>'],
['tokyo', '', 'C-1;alice@example.com;1795600800;JPY;S1:2:1999'],
];
foreach ($inputs as [$partner, $type, $body]) {
app(OrderIntake::class)->handle(Envelope::wrapRaw($partner, $type, $body));
}
$events = array_map(fn ($e) => json_decode($e->data, true), $this->sent->byTopic['orders.placed']);
$this->assertSame([3998, 3998, 3998], array_map(fn ($e) => $e['total']['amount_minor'], $events));
$this->assertCount(1, array_unique(array_map(fn ($e) => $e['customer']['email_hash'], $events)));
$this->assertStringNotContainsString('alice@example.com', json_encode($events));
}
public function test_bad_currency_is_invalid_not_retryable(): void
{
$this->expectException(InvalidMessage::class);
app(OrderIntake::class)->handle(Envelope::wrapRaw('acme', 'application/json',
'{"orderId":"1","email":"a@b.c","placedAt":"2026-11-25T10:00:00Z","currency":"XXX","items":[{"sku":"s","qty":1,"price":"1"}]}'));
}
public function test_directory_down_with_cold_cache_is_transient(): void
{
Cache::flush();
Http::fake(['customers.test/*' => Http::response('boom', 503)]);
$this->expectException(TransientFailure::class);
app(OrderIntake::class)->handle(Envelope::wrapRaw('acme', 'application/json',
'{"orderId":"1","email":"a@b.c","placedAt":"2026-11-25T10:00:00Z","currency":"USD","items":[{"sku":"s","qty":1,"price":"1"}]}'));
}
}حل مسئلههای کلاسیک
| مسئله | راهحل | روش | مزیت | هزینه یا محدودیت |
|---|---|---|---|---|
| چند قالب شریک، یک مسیر داخلی | Normalizer | تشخیص و parser مستقل تا Draft | افزودن شریک محلی میماند | تشخیص اشتباه داده را خراب میکند |
| واحد، زمان و شناسه متفاوت | Translator | عدد صحیح، UTC، namespace و رد ابهام | معنای یکسان | جدول ارز و قرارداد زمان باید نگهداری شود |
| دادهٔ لازم در پیام نیست | Enricher | cache، deadline، singleflight و sentinel | مصرفکننده سادهتر | وابستگی و کهنگی |
| مخاطب نباید همهٔ داده را ببیند | Content Filter | allowlist خروجی، denylist کمکی | PII کمتر | denylist فیلد تازه را عبور میدهد |
| سیستم قدیمی پوشش لازم ندارد | Envelope Wrapper | wrap/unwrap در مرزها | عدم تغییر legacy | ترتیب لایه و مدیریت کلید |
| دامنه و پیام به هم جوش خوردهاند | Messaging Mapper | جزء مستقل و constructorهای معتبر | تغییر مستقل | کد نگاشت و آزمون |
| مترجمهای زوجی زیاد | Canonical Data Model محدود به واقعیت | دو جهت نگاشت برای هر سیستم | 2n در فرض اتصال کامل | مالک و روند تغییر مشترک |
| چند نسخهٔ payload | Upcaster chain | ارتقا پلهبهپله | مصرفکننده نسخهٔ جدید را میبیند | زنجیرهٔ نسخههای قدیمی باقی میماند |
| فایل میلیونسفارشی | Streaming parser | decoder تدریجی و خروجی bounded | حافظهٔ محدود | پیچیدگی و احتمال CPU بیشتر |
| تغییر خاموش قالب شریک | Golden file و invalid-rate alert | ذخیرهٔ ورودی و replay پس از اصلاح | تشخیص و بازیابی | retention باید بازهٔ کشف را پوشش دهد |
| قطعی directory | Stale-on-error سپس retry | stale محدود با degraded | تداوم کنترلشده | مخاطب باید کهنگی را تحمل کند |
مسئلهٔ ۱: سه قالب شریک
یکسانساز (Normalizer) و مترجم (Translator) را جدا نگه دارید. شریک جدید یعنی parser و golden جدید؛ اگر نوع تشخیص داده نشد، invalid برگردانید و fingerprint را ثبت کنید. guess موفقنما از شکست صریح خطرناکتر است.
مسئلهٔ ۲: اطلاعات شخصی نباید پخش شود
سه دفاع داریم: در مدل مرجع ایمیل خام قرار ندهیم؛ برای analytics نوع allowlist بسازیم؛ payload لاگ یا پارکشده را نیز پالایش کنیم. شبهناشناسسازی (Pseudonymisation) با HMAC، ناشناسسازی (Anonymisation) نیست: دارندهٔ کلید و فهرست ایمیلهای احتمالی میتواند تطبیق دهد. چرخش کلید و retention در امنیت باید با lookup directory هماهنگ باشند.
مسئلهٔ ۳: شریک قالب را بیخبر عوض کرده
1 09:00 partner changes XML Date to ISO 8601
2 09:01 Normalizer rejects unexpected date contract
3 09:01 safe invalid record: source=partner/berlin-shop, stage=normalize
4 09:05 alert: invalid rate >5% for 5 minutes
5 09:30 add supported layout + golden fixture; deploy
6 09:40 replay retained raw inputs from 09:00
7 09:41 stable output ids let inbox ignore already-applied resultsبازپخش (Replay) در Kafka با گروه/offset جدید، در Redis با XRANGE و در RabbitMQ فقط از stream یا ذخیرهٔ بیرونی ممکن است؛ queue مصرفشده آرشیو نیست.
مسئلهٔ ۴: چه چیزی در Enricher cache شود؟
| داده | TTL پیشنهادی | کش منفی (Negative cache) | دلیل |
|---|---|---|---|
| tier و کشور مشتری | چند دقیقه، مثلاً 5 | چند ثانیه تا دقیقه | تغییر نسبتاً کم و تحمل کهنگی |
| نام و دستهٔ محصول | چند ساعت | چند دقیقه | تغییر کم |
| امتیاز تقلب | میان پیامها cache نشود مگر قرارداد اجازه دهد | ندارد | تصمیم به دادهٔ تازه وابسته است |
| نرخ ارز | پنجرهٔ اعتبار نرخ | ندارد | نرخ غلط اثر مالی دارد |
| مشتری تازهساختهشده که فعلاً پیدا نیست | چند ثانیه | خود پاسخ منفی کوتاهعمر است | replica ممکن است عقب باشد؛ دادهٔ توزیعشده |
تفاوت brokerها (Broker differences)
مرحلههای تبدیل مشترکاند؛ دریافت، انتشار و تسویهٔ ورودی (Settlement) در adapter هر broker فرق میکند. پاسخ موفق publish باید معنای مشخصی داشته باشد.
RabbitMQ
RabbitMQ بهطور آماده محتوای کسبوکار را ترجمه نمیکند. interceptorهای آماده metadata میافزایند و Shovel/Federation پیام را جابهجا میکنند. worker از partner.orders.raw میخواند، به exchange به نام orders میفرستد و پس از تأیید انتشار (Publisher confirm) ورودی را ack میکند. confirm مثبت بهتنهایی اثبات وجود queue مقصد نیست؛ mandatory و basic.return برای کشف پیام بیمسیر لازماند. نمونه یک کانال انتشار اختصاصی با یک publish در پرواز فرض میکند.
پیشواکشی (Prefetch) با Qos محدود میشود. خطای Ack/Nack باید worker را متوقف کند تا supervisor کانال تازه بسازد. Nack با requeue فوری در زمان قطعی directory حلقهٔ داغ میسازد؛ محیط واقعی باید retry تأخیردار و سقف تلاش داشته باشد. ورودی نامعتبر فقط بعد از انتشار پایدار fingerprint تأیید میشود. برای replay، queue معمولی کافی نیست؛ RabbitMQ stream یا آرشیو بیرونی لازم است. فصل RabbitMQ تفاوت queue و stream را باز میکند.
package after
import (
"context"
"fmt"
"sync"
amqp "github.com/rabbitmq/amqp091-go"
)
// RabbitPublisher publishes with publisher confirms: Publish returns only
// after the broker has taken responsibility for the message.
type RabbitPublisher struct {
Ch *amqp.Channel // Confirm(false) must have been called on it
Exchange string // topic exchange; dest is the routing key
mu sync.Mutex
returns <-chan amqp.Return
}
// NewRabbitPublisher needs a dedicated channel with no other publishers.
func NewRabbitPublisher(ch *amqp.Channel, exchange string) (*RabbitPublisher, error) {
if err := ch.Confirm(false); err != nil {
return nil, err
}
return &RabbitPublisher{Ch: ch, Exchange: exchange, returns: ch.NotifyReturn(make(chan amqp.Return, 1))}, nil
}
func (r *RabbitPublisher) Publish(ctx context.Context, dest string, e Envelope) error {
r.mu.Lock()
defer r.mu.Unlock()
if r.returns == nil {
return fmt.Errorf("use NewRabbitPublisher with a dedicated channel")
}
headers := amqp.Table{"version": int32(e.Version), "source": e.Source}
if e.CausationID != "" {
headers["causation-id"] = e.CausationID
}
dc, err := r.Ch.PublishWithDeferredConfirmWithContext(ctx, r.Exchange, dest, true, false, amqp.Publishing{
MessageId: e.ID, Type: e.Type, Timestamp: e.OccurredAt,
CorrelationId: e.CorrelationID, ContentType: e.ContentType,
DeliveryMode: amqp.Persistent, Headers: headers, Body: e.Data,
})
if err != nil {
return err
}
if dc == nil {
return fmt.Errorf("publisher confirms required")
}
ok, err := dc.WaitContext(ctx)
if err != nil {
_ = r.Ch.Close() // Unknown confirm outcome: do not reuse this publisher.
return err
}
select {
case ret, open := <-r.returns:
if !open {
return fmt.Errorf("publisher return channel closed")
}
return fmt.Errorf("unroutable output: %d %s", ret.ReplyCode, ret.ReplyText)
default:
}
if !ok {
return fmt.Errorf("broker nacked publish to %s", dest)
}
return nil
}
func rabbitEnvelope(d amqp.Delivery) Envelope {
str := func(k string) string { s, _ := d.Headers[k].(string); return s }
v, _ := d.Headers["version"].(int32)
return Envelope{
ID: d.MessageId, Type: d.Type, Source: str("source"), Version: int(v),
OccurredAt: d.Timestamp, CorrelationID: d.CorrelationId,
CausationID: str("causation-id"), ContentType: d.ContentType, Data: d.Body,
}
}
// RunRabbit is the consumer-edge transformation worker: RabbitMQ cannot
// transform, so a consumer reads the raw queue and publishes the result.
// Ack only after Handle succeeded. Limitation: Nack with requeue puts the
// message straight back, which is a hot loop while the directory is down; a
// real worker routes it to a delayed retry queue instead
// (see retry-backoff-delayed) and caps attempts (see dead-letter-queue).
func RunRabbit(ctx context.Context, ch *amqp.Channel, queue string, p *Pipeline) error {
if err := ch.Qos(20, 0, false); err != nil {
return err
}
msgs, err := ch.ConsumeWithContext(ctx, queue, "order-intake", false, false, false, false, nil)
if err != nil {
return err
}
for d := range msgs {
out, err := p.Handle(ctx, rabbitEnvelope(d))
if out == Retry || err != nil {
if err := d.Nack(false, true); err != nil {
return err
}
continue
}
if err := d.Ack(false); err != nil {
return err
}
}
if err := ctx.Err(); err != nil {
return err
}
return fmt.Errorf("RabbitMQ delivery stream closed; reconnect")
}در Laravel، job روی connection سازگار RabbitMQ قرار میگیرد؛ سازگاری نسخهٔ package با Laravel 13 باید در پروژهٔ میزبان بررسی شود. نمونهٔ مستقیم زیر از php-amqplib استفاده میکند و publisher را به confirm و mandatory return وابسته میکند؛ basic_publish بهتنهایی تضمین پذیرش broker نیست.
<?php
namespace App\Messaging\Transform\Brokers;
use App\Messaging\Transform\Envelope;
use App\Messaging\Transform\Publisher;
use PhpAmqpLib\Channel\AMQPChannel;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;
/**
* RabbitMQ: no broker-side transformation, so the transformation worker is an
* ordinary consumer. Written against php-amqplib, the client under
* vladimir-yuldashev/laravel-queue-rabbitmq, whose README documents no per-message API.
*/
final class RabbitMq implements Publisher
{
private bool $returned = false;
private bool $nacked = false;
/** Dedicated publisher channel: one in-flight publication, no other owner. */
public function __construct(private readonly AMQPChannel $channel, private readonly string $exchange = 'orders')
{
$channel->confirm_select();
$channel->set_return_listener(function (): void { $this->returned = true; });
$channel->set_nack_handler(function (): void { $this->nacked = true; });
}
public function publish(string $destination, Envelope $e): void
{
$this->returned = $this->nacked = false;
$this->channel->basic_publish(new AMQPMessage($e->data, [
'content_type' => $e->contentType,
'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
'message_id' => $e->id,
'type' => $e->type,
'correlation_id' => $e->correlationId,
'timestamp' => $e->occurredAt->getTimestamp(),
'application_headers' => new AMQPTable(['source' => $e->source, 'version' => $e->version]),
]), $this->exchange, $destination, true);
$this->channel->wait_for_pending_acks_returns(5.0);
if ($this->returned || $this->nacked) {
throw new \RuntimeException('output was unroutable or negatively confirmed');
}
}
/** Consumer: ack only after the transformation published its outputs. */
public function consume(string $queue, callable $handle): void
{
$this->channel->basic_qos(0, 20, false);
$this->channel->basic_consume($queue, '', false, false, false, false, function (AMQPMessage $m) use ($handle) {
$h = $m->get('application_headers')->getNativeData();
try {
$handle(new Envelope(
id: $m->get('message_id'), type: $m->get('type'), source: $h['source'], version: $h['version'],
occurredAt: (new \DateTimeImmutable)->setTimestamp($m->get('timestamp')),
contentType: $m->get('content_type'), data: $m->getBody(),
));
$m->ack();
} catch (\Throwable $e) {
$m->nack(requeue: true);
throw $e; // Supervisor recreates channels; no hot retry loop here.
}
});
$this->channel->consume();
}
}Kafka
Connect و Streams میزبانهای جدا از broker هستند. برای تماس خارجی، cache و branching پیچیده، سرویس consumer-producer مرز روشنتری دارد. کلید رکورد (Record key) را order id بگذارید و routing facts را در header حمل کنید. offset تنها پس از تولید خروجی commit میشود.
CommitRecords بالاترین offset هر partition را جلو میبرد؛ اگر رکورد قبلی شکست بخورد، commit رکورد بعدی همان partition آن را رد میکند. حلقهٔ Go در اولین شکست هر partition متوقف و client هنگام خروج بسته میشود؛ supervisor باید client جدید بسازد. صداکردن دوبارهٔ حلقه با همان client، fetch position محلی را به committed offset برنمیگرداند. client باید با DisableAutoCommit و BlockRebalanceOnPoll ساخته شود؛ batch موفق با AllowRebalance اجازهٔ انتقال مالکیت میدهد. مدت پردازش باید در کران rebalance timeout بماند؛ تراکنش و fencing موضوع جدا هستند. همهٔ fetch errorها باید بررسی شوند.
تراکنش میان topicها همراه offset به client transactional و مصرف read_committed نیاز دارد؛ تضمین تحویل و Kafka مالک جزئیاتاند. بازپخش raw topic با گروه و offset جدا از گروه production انجام میشود.
package after
import (
"context"
"fmt"
"github.com/twmb/franz-go/pkg/kgo"
)
// KafkaPublisher writes the envelope as record headers plus the body as value.
// The key (the order id) decides the partition, so one order stays ordered.
type KafkaPublisher struct{ Client *kgo.Client }
func (k KafkaPublisher) Publish(ctx context.Context, dest string, e Envelope) error {
rec := &kgo.Record{Topic: dest, Key: []byte(e.Key), Value: e.Data, Timestamp: e.OccurredAt}
for name, v := range e.Headers() {
rec.Headers = append(rec.Headers, kgo.RecordHeader{Key: name, Value: []byte(v)})
}
return k.Client.ProduceSync(ctx, rec).FirstErr()
}
func kafkaEnvelope(r *kgo.Record) Envelope {
h := make(map[string]string, len(r.Headers))
for _, x := range r.Headers {
h[x.Key] = string(x.Value)
}
e := FromHeaders(h, r.Value)
e.Key = string(r.Key)
return e
}
// RunKafka is consume-transform-produce with manual commits: offsets are
// committed only after the outputs were produced (at-least-once). Build the
// client with kgo.DisableAutoCommit() and kgo.BlockRebalanceOnPoll().
// Bound handler time below the configured rebalance timeout. This function
// owns and closes cl; restart with a NEW client after any failure. CommitRecords commits per partition up
// to the records it is given, so we stop at the FIRST record that needs a
// retry: committing a later record of the same partition would skip it.
// Closing lets a new client resume from committed offsets; reusing the same
// client would retain its advanced local fetch position. For exactly-once between topics use
// kgo.NewGroupTransactSession (see delivery-guarantees).
func RunKafka(ctx context.Context, cl *kgo.Client, p *Pipeline) error {
defer cl.CloseAllowingRebalance()
for {
fetches := cl.PollFetches(ctx)
if errs := fetches.Errors(); len(errs) > 0 {
return fmt.Errorf("fetch %s/%d: %w", errs[0].Topic, errs[0].Partition, errs[0].Err)
}
var done []*kgo.Record
var failed error
fetches.EachPartition(func(part kgo.FetchTopicPartition) {
for _, r := range part.Records {
out, err := p.Handle(ctx, kafkaEnvelope(r))
if out != Ack || err != nil {
failed = err // stop this partition at the failure
if failed == nil {
failed = fmt.Errorf("pipeline requested retry")
}
return
}
done = append(done, r)
}
})
if len(done) > 0 {
if err := cl.CommitRecords(ctx, done...); err != nil {
return err
}
}
if failed != nil {
return failed
}
cl.AllowRebalance()
}
}در Laravel Kafka، serializer و deserializer پیشفرض JSON با بدنهٔ خام JSON/XML/CSV یکسان نیستند. adapter باید بایت خام را حفظ کند و روی شکست handler مصرف را متوقف کند؛ عبور به رکورد بعدی همان partition ممکن است شکست قبلی را پشت commit پنهان کند. package و رفتار stop-on-failure را به نسخهٔ نصبشده pin و آزمون کنید.
<?php
namespace App\Messaging\Transform\Brokers;
use App\Messaging\Transform\Envelope;
use App\Messaging\Transform\Publisher;
use Junges\Kafka\Contracts\ConsumerMessage;
use Junges\Kafka\Contracts\MessageConsumer;
use Junges\Kafka\Contracts\MessageSerializer;
use Junges\Kafka\Contracts\MessageDeserializer;
use Junges\Kafka\Contracts\ProducerMessage;
use Junges\Kafka\Facades\Kafka as KafkaFacade;
use Junges\Kafka\Message\Message;
/** Kafka: envelope as record headers, payload as value, order id as key. */
final class Kafka implements Publisher
{
public function publish(string $destination, Envelope $e): void
{
$sent = KafkaFacade::publish('broker')
->usingSerializer(new class implements MessageSerializer {
public function serialize(ProducerMessage $message): ProducerMessage { return $message; }
})
->onTopic($destination)
->withMessage(new Message(headers: $e->headers(), body: $e->data, key: $e->key))
->send();
if (! $sent) { throw new \RuntimeException('Kafka output was not delivered'); }
}
/** Consumer edge: the group id is the service name; the handler runs once per record. */
public function consume(string $topic, callable $handle): void
{
KafkaFacade::consumer([$topic], 'order-intake', 'broker')
->usingDeserializer(new class implements MessageDeserializer {
public function deserialize(ConsumerMessage $message): ConsumerMessage { return $message; }
})
->stopOnFailure()
->withHandler(function (ConsumerMessage $m, MessageConsumer $consumer) use ($handle) {
$handle(Envelope::fromHeaders($m->getHeaders(), (string) $m->getBody(), $m->getKey()));
})
->build()
->consume();
}
}Redis Streams
Redis Streams هدر جدا یا hook تبدیل عمومی ندارد؛ metadata کنار body در field-valueها قرار میگیرد. worker با XREADGROUP میخواند، خروجی را XADD و سپس ورودی را XACK میکند. crash میان این دو میتواند خروجی تکراری بسازد، بنابراین شناسهٔ پایدار و inbox لازم است.
تراکنش MULTI/EXEC اجرای دستورات را از دستورات client دیگر جدا میکند، اما rollback ندارد. اگر XADD با WRONGTYPE شکست بخورد، XACK بعدی هنوز میتواند اجرا شود. پس آن را بدون پیششرط و سیاست خطا معادل «نتیجه و ack حتماً با هم» ندانید؛ نمونهٔ ترتیبی زیر فقط بعد از موفقیت انتشار ack میکند و ambiguity شبکه را با dedup مدیریت میکند.
ورودی retry در فهرست معلق (Pending Entries List / PEL) میماند. خواندن > فقط پیام جدید میدهد؛ recovery worker باید با XAUTOCLAIM ورودی idle را پس بگیرد و همان handler را اجرا کند. این حلقه recovery کامل ندارد؛ Acknowledgment مالک آن است. MAXLEN تاریخچه را حذف میکند، حتی اگر replay بعداً لازم شود. Redis Streams و Redis زمینهٔ ذخیرهسازی را توضیح میدهند.
package after
import (
"context"
"github.com/redis/go-redis/v9"
)
// StreamPublisher flattens the envelope into stream fields: an entry has no
// header section, so metadata and body are sibling field-value pairs.
type StreamPublisher struct{ Rdb *redis.Client }
func (s StreamPublisher) Publish(ctx context.Context, dest string, e Envelope) error {
values := map[string]any{"body": e.Data, "key": e.Key}
for k, v := range e.Headers() {
values[k] = v
}
return s.Rdb.XAdd(ctx, &redis.XAddArgs{Stream: dest, Values: values}).Err()
}
func streamEnvelope(x redis.XMessage) Envelope {
h := map[string]string{}
for k, v := range x.Values {
if s, ok := v.(string); ok && k != "body" {
h[k] = s
}
}
body, _ := x.Values["body"].(string)
e := FromHeaders(h, []byte(body))
e.Key, _ = x.Values["key"].(string)
return e
}
// RunStream reads a consumer group, transforms, publishes, then XACKs.
// A crash between publish and XACK redelivers the entry: same input, same
// deterministic output ids. Limitation: an entry whose Handle returned Retry
// is left un-ACKed in the pending entries list; this loop reads only new
// entries (">"), so a second loop must reclaim idle ones with XAUTOCLAIM
// (see message-acknowledgment).
func RunStream(ctx context.Context, rdb *redis.Client, stream, group, consumer string, p *Pipeline) error {
for {
res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
Group: group, Consumer: consumer, Streams: []string{stream, ">"}, Count: 20, Block: 0,
}).Result()
if err != nil {
return err
}
for _, s := range res {
for _, x := range s.Messages {
if out, err := p.Handle(ctx, streamEnvelope(x)); out == Ack && err == nil {
if err := rdb.XAck(ctx, stream, group, x.ID).Err(); err != nil {
return err
}
}
}
}
}
}
// PublishAndAck deliberately publishes first, then acknowledges. MULTI/EXEC
// does not roll back: a runtime XADD error could otherwise still execute XACK.
// A crash or lost reply can duplicate the output; consumers deduplicate e.ID.
func PublishAndAck(ctx context.Context, rdb *redis.Client, in, group, id, out string, e Envelope) error {
if err := (StreamPublisher{Rdb: rdb}).Publish(ctx, out, e); err != nil {
return err
}
return rdb.XAck(ctx, in, group, id).Err()
}driver صف Laravel از list و sorted set استفاده میکند، نه Streams. adapter مستقیم Redis برای phpredis نوشته شده و binding کلاینت باید با آن سازگار باشد. خطای XACK نباید نادیده گرفته شود.
<?php
namespace App\Messaging\Transform\Brokers;
use App\Messaging\Transform\Envelope;
use App\Messaging\Transform\Publisher;
use Illuminate\Support\Facades\Redis;
/**
* Redis Streams: an entry has no header section, so the envelope fields and the
* body are sibling field-value pairs. Uses the Redis facade (phpredis client):
* Laravel's own redis queue driver uses lists, not streams.
* The group must exist: XGROUP CREATE partner.orders.raw intake $ MKSTREAM
*/
final class RedisStreams implements Publisher
{
public function publish(string $destination, Envelope $e): void
{
Redis::xadd($destination, '*', [...$e->headers(), 'key' => (string) $e->key, 'body' => $e->data]);
}
public function consume(string $stream, string $group, string $consumer, callable $handle): void
{
while (true) {
$res = Redis::xreadgroup($group, $consumer, [$stream => '>'], 20, 5000);
foreach ($res[$stream] ?? [] as $id => $fields) {
$body = $fields['body'];
$key = ($fields['key'] ?? '') ?: null;
unset($fields['body'], $fields['key']);
$handle(Envelope::fromHeaders($fields, $body, $key));
if (Redis::xack($stream, $group, [$id]) !== 1) {
throw new \RuntimeException('stream entry was not acknowledged');
} // after the outputs were published
}
}
}
}| پرسش | RabbitMQ | Kafka | Redis Streams |
|---|---|---|---|
| تبدیل کجا اجرا میشود؟ | consumer یا sidecar | Connect، Streams یا consumer جدا | worker گروه مصرفکننده |
| فیلدهای پاکت کجا هستند؟ | properties و headers | record headers | fieldهای همسطح |
| چه زمانی ack/commit شود؟ | پس از confirm و نبود mandatory return | پس از خروجی، به ترتیب partition | پس از XADD موفق |
| replay ورودی raw چگونه است؟ | stream یا آرشیو بیرونی | گروه جدید از offset/time | XRANGE یا گروه جدید از 0 |
| retry گذرا چیست؟ | صف تأخیردار | توقف partition یا retry topic | باقیماندن در PEL و XAUTOCLAIM |
| کانال invalid کجاست؟ | queue/exchange مجزا | topic مجزا | stream مجزا |
انتخاب
| وضعیت | الگو | میزبان | دلیل |
|---|---|---|---|
| یک شریک و یک قالب | Translator | لبهٔ consumer | framework عمومی لازم نیست |
| چند قالب با معنای واحد | Normalizer | سرویس ورودی یا gateway | تغییر شریک به core سرایت نکند |
| app قدیمی امضا/رمزنگاری نمیشناسد | Envelope Wrapper | هر دو لبه | برنامهٔ قدیمی ساده میماند |
| دادهٔ لازم در event نیست | Content Enricher | consumer با cache | تولیدکننده سادهتر، وابستگی lookup بیشتر |
| حذف وابستگی lookup با پذیرش پیام بزرگتر | Event-carried State Transfer | producer | دادهٔ مورد نیاز همراه رویداد میآید |
| مخاطب نباید بعضی فیلدها را ببیند | Content Filter با allowlist | producer edge | فیلد تازه خودکار نشت نمیکند |
| پوشاندن فیلد بدون سرویس تازه در Kafka | MaskField | Connect | تنظیم آماده |
| حذف traffic آزمایشی | Message Filter | Connect با predicate یا router | کل پیام حذف میشود |
| استقلال مدل دامنه | Messaging Mapper | هر دو لبه | تکامل مستقل |
| چند سیستم با تیم integration مرکزی | Canonical Data Model | hub | کاهش نگاشت زوجی در فرض اتصال کامل |
| تیم مستقل و مالک روشن واقعیت | Published Language + ACL | لبهها | حذف نیاز به مدل واحد سازمانی |
| upstream قدیمی و غیرقابل تغییر | Anticorruption Layer | consumer | حفاظت از مدل پاییندست |
| فایل بسیار بزرگ | Streaming Normalizer | batch worker | peak memory محدود |
| تبدیل کنار RabbitMQ/Redis Streams | سرویس یا sidecar | فرایند مستقل | broker تبدیل عمومی بدنه ندارد |
در معماری: از یک فرایند تا سامانهٔ توزیعشده
مونولیت، یک برنامه و یک پایگاه داده
در تکبرنامه (Monolith)، کنترلر Laravel ورودی را در Envelope قرار میدهد و job با driver database یا redis پردازش میشود. worker صف معمولاً فرایند جدا است، حتی اگر از همان codebase استفاده کند؛ تنها اجرای synchronous واقعاً در همان process است. مرحلههای Normalize، Translate و Enrich میتوانند در worker پشت سر هم اجرا شوند و مشتری را از DB محلی بخوانند. Mapper داخل تراکنش DB مدل سفارش را میسازد؛ این تراکنش انتشار broker بیرونی را اتمیک نمیکند.
در Go همان زنجیره از HTTP handler یا worker فراخوانی میشود. الگوی before همهٔ parse، lookup، logging و publish را مخلوط کرده است؛ کد بد برای آموزش است، نه انتخاب production.
// Package before is the shape most teams start with: one consumer function
// that parses, converts, looks up, logs and publishes in the same place.
// It works on the happy path and fails in every way described on the page.
package before
import (
"encoding/json"
"log"
"net/http"
)
// partnerOrder is the partner's wire format used directly as our model.
type partnerOrder struct {
OrderID string `json:"orderId"`
Email string `json:"email"`
Total float64 `json:"total"` // 19.99 as a float: rounding bugs waiting
Card string `json:"card"` // PII we never needed
}
type customerService interface {
Get(email string) (tier string, err error)
}
type publisher interface {
Publish(topic string, body []byte) error
}
// Handle is a webhook handler doing six jobs.
func Handle(cs customerService, pub publisher) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var in partnerOrder
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
http.Error(w, "bad json", 400) // the partner's only format; the XML partner is "not supported"
return
}
log.Printf("order received: %+v", in) // logs the e-mail and the card number
tier, err := cs.Get(in.Email) // one network call per message, no cache, no timeout
if err != nil {
http.Error(w, "customer lookup failed", 500) // partner retries, we call again
return
}
out, _ := json.Marshal(map[string]any{
"id": in.OrderID, "email": in.Email, "total": in.Total, "tier": tier, "card": in.Card,
})
_ = pub.Publish("orders", out) // error ignored; every consumer now depends on the partner's field names
w.WriteHeader(202)
}
}مونولیت ماژولار
در تکبرنامهٔ ماژولار (Modular monolith)، Orders، Billing و Fulfilment مدل داخلی مشترک ندارند. هر ماژول namespace کوچک Contracts دارد که زبان منتشرشدهٔ خودش است. Mapper داخل ماژول event میسازد؛ مصرفکننده در مرز خود آن را به مدل خویش تبدیل میکند. Enricher از interface عمومی ماژول دیگر میخواند، نه جدول داخلی آن؛ استخراج بعدی به سرویس، پیادهسازی interface را عوض میکند. Context Maps و رویداد دامنه و integration مالک این مرزها هستند.
ریزخدمتها
در ریزخدمتها (Microservices)، pipeline از شبکه و مالکیت تیم عبور میکند:
partner POST -> intake (Channel Adapter + Envelope Wrapper)
-> partner.orders.raw (retained)
-> transformer (Normalize -> Translate -> Enrich)
-> partner.orders.invalid (fingerprints)
-> orders.placed -> Billing ACL / Fulfilment
-> orders.analytics -> warehouse loaderتیم intake قالب شریک، تیم سفارش قرارداد OrderPlaced و هر مصرفکننده مدل خودش را مالک است. invalid فقط بعد از ثبت امن تأیید میشود؛ transient retry محدود دارد؛ Inbox خروجی تکراری را مهار میکند. نوشتن DB همراه رویداد Outbox میخواهد؛ گردش کار چندسرویسی Saga است. تبدیل پیام جایگزین هیچکدام نیست.
دادهٔ توزیعشده: cache، replica و چند منطقه
غنیسازی از replica و cache تصویری لحظهای (Snapshot) میدهد که ممکن است کهنه یا نادرست باشد.
| شکست | نتیجه | مهار |
|---|---|---|
| مشتری تازه و عقبماندگی replica | 404 برای مشتری موجود | TTL منفی کوتاه، retry با فاصله برای ایجاد تازه و رویداد اصلاحی؛ Replication |
| cache سطح مشتری پس از upgrade کهنه است | gold مدتی silver پردازش میشود | TTL کوتاه یا invalidation روی customer.updated |
| از دسترفتن cache node | هجوم lookup به directory | singleflight، قفل refresh در Cache::flexible و سقف concurrency؛ Redis |
| تولیدکننده v2 در یک منطقه و مصرفکننده v1 در دیگری | قراردادها متفاوتاند | تغییر سازگار و upcaster در مرز؛ Schema Evolution |
| ارسال دوباره به دو منطقه | یک رخداد دوبار دیده میشود | هویت پایدار رخداد و dedup مشترک متناسب با قلمرو؛ Inbox |
| ساعت محلی در منطقهٔ اشتباه | زمان رویداد جابهجا میشود | zone/offset قراردادی شریک، نه zone سرور |
قواعد read-your-writes و اجماع پشت این انتخابها در Distributed SQL آمده است.
مسیر رشد
| بار | شکل | تغییر لازم |
|---|---|---|
| 1x، چند ده سفارش در دقیقه | job در مونولیت، pipeline داخل worker | golden، جدول invalid و متریک مرحله |
| 10x | worker pool، cache و صف اختصاصی | cache hit و latency منبع، encryption job و backoff |
| 100x | transformer مستقل، partition ورودی بر اساس شریک، SMT برای ماسک | parser جریانی، سهمیهٔ شریک و read model مشتری به جای lookup؛ Scaling |
| تیم و شریک زیاد | Published Language برای هر واقعیت، registry و ACL | مالکیت قرارداد، platform برای normalization و Contract tests |
در سیستمهای واقعی
- Apache Kafka، زنجیرهٔ SMT، predicateها و پیشفرض fail-fast را مستند میکند؛ این کد در Connect worker اجرا میشود.
- Debezium با Outbox Event Router ردیف outbox را به رویداد مسیریابیشده تبدیل میکند؛ CDC سازوکار استخراج را توضیح میدهد.
- RabbitMQ interceptor را مکانیزم توسعه میداند؛ built-inهای timestamp/routing node با تبدیل عمومی بدنه فرق دارند و پروتکل Streams در این مسیر intercept نمیشود.
- EIP نمونهٔ Content Enricher با EventBridge Pipes، شناسههای ورودی، Lambda و DynamoDB را نشان میدهد.
- Laravel 13 در
Pipelineزنجیرهٔ pipe و درCache::flexibleبازسازی تعویقی همراه lock را پیاده میکند؛ رفتار cache را با طول عمر queue worker نیز بسنجید.
آزمایشگاه
همهٔ سناریوهای این بخش expected, not run هستند؛ نتیجهٔ مشاهدهشده یا benchmark این نوبت محسوب نمیشوند. Docker اجرا نمیشود. فرمانهای broker فقط برای محیط ازقبلفراهمشدهٔ خوانندهاند. اجرای QA کد در گزارش HANDOFF جدا ثبت میشود.
1 cd docs/snippets/messaging/message-transformation/go
gofmt -l .
go vet ./...
go test -count=1 ./...
# expected, not run: no formatting/vet errors; tests pass
2 go test ./after -run TestGolden -v
# expected, not run: acme, berlin-shop, tokyo-mart golden outputs match
3 go test ./after -run '^$' -bench Batch -benchmem
# expected, not run: compare timings/allocations on your host; no promised values
4 go test ./after -run LiveHeap -v
# expected, not run: streaming retains less decoded data with a bounded reader/output5 Kafka Connect SMT, existing Connect installation only
curl -X POST -H 'Content-Type: application/json' --data @connect/orders-source-connector.json \
http://localhost:8083/connectors
# expected, not run: supplied connector must exist and emit a structured order
# expected: phone/shipping_address removed, card_number masked, data_source added
6 RabbitMQ, topology + envelope-aware producer + worker already configured
# publish a raw Envelope to partner.orders.raw, not an unadorned payload
# expected, not run: confirmed orders.placed + orders.analytics, then input ack
# remove output binding: mandatory return must prevent input ack
7 Redis Streams, group + worker already configured
redis-cli XGROUP CREATE partner.orders.raw intake '$' MKSTREAM
redis-cli XADD partner.orders.raw '*' id x type partner.order.received source partner/tokyo-mart version 1 occurred-at 2026-11-25T07:00:00Z content-type text/plain body 'C-9;a@b.c;1795600800;JPY;S:1:100'
redis-cli XRANGE orders.placed - +
# expected, not run: canonical output; input ack follows successful publication
8 Laravel 13 host with bindings, models, migrations, cache and Http fake
php artisan test --filter OrderIntakeTest
# expected, not run: valid formats pass; invalid and cold-directory failure follow policyخرابکردن عمدی (Fault injection): ارز را XXX کنید؛ انتظار invalid و خروجی موفق صفر است. directory را با cache سرد قطع کنید؛ انتظار retry است. یک بیت پاکت رمزشده را عوض کنید؛ انتظار رد احراز اصالت است. در Redis کلید خروجی را با نوع اشتباه بسازید؛ انتظار عدم ack ورودی است. اینها آزمایش پیشنهادیاند، نه ادعای اجرای broker.
بدفهمیهای رایج
| باور | واقعیت |
|---|---|
| تبدیل همان Serialization است | تبدیل واحد، زمان و ساختار با نمایش بایت فرق دارد |
| Content Filter پیام را حذف میکند | Message Filter کل پیام را حذف میکند |
Streams filter پالایهٔ محتواست | رکورد را حذف میکند؛ projection با mapValues محتوا را کوچک میکند |
| RabbitMQ بدنه را خودکار تبدیل میکند | built-in interceptor metadata میافزاید؛ تبدیل در consumer یا توسعهٔ سفارشی است |
| مدل مرجع وابستگی را حذف میکند | وابستگی به قرارداد مشترک ایجاد میکند |
| یک مدل برای کل شرکت هدف است | مدل کوچکِ هر واقعیت با مالک روشن معمولاً قابل تغییرتر است |
| float برای قیمت کافی است | عدد صحیح با ارز، کنترل اعشار و overflow لازم است |
| شکست enrichment را میتوان نادیده گرفت | retry یا stale/degraded آگاهانه، نه پیام ناقص بیعلامت |
| هش ایمیل anonymous است | HMAC pseudonymous است و با کلید و candidate list قابل تطبیق |
| امضا و encryption یک لایهاند | نقش و ترتیب متفاوت دارند؛ قبل از parse اعتبار بررسی شود |
| Upcaster مکانیزمی مستقل از Translator است | ترجمه میان نسخههای یک type است |
| Invalid Message Channel باید payload خام داشته باشد | fingerprint و reason امن؛ raw جدا با retention/access policy |
چکیده
| موضوع | یادآوری |
|---|---|
| Translator | نوع مشخص؛ واحد، زمان، id و overflow مهمتر از تغییر ناماند |
| Envelope Wrapper | ترتیب wrap و unwrap معکوس؛ verify پیش از parse |
| Enricher | cache، deadline، coalescing، sentinel، stale محدود و retry |
| Content Filter | محتوای کمتر، پیام باقی؛ allowlist در برابر فیلد جدید بسته است |
| Message Filter | حذف کل پیام؛ Connect Filter و Streams filter |
| Normalizer | Router + مترجم مستقل هر قالب |
| Canonical Data Model | n(n-1) به 2n تحت فرض اتصال کامل؛ مالک محدود |
| Messaging Mapper | استقلال دو طرف و بررسی invariant در constructor |
| محل اجرا | لبهها، gateway، برنامهٔ Connect/Streams؛ نه کد عمومی داخل broker |
| شکست | invalid ثبت سپس ack؛ transient با backoff؛ bug با alert |
| قطعیت | شناسهٔ پایدار، نه الزاماً enrichment یکسان در retry |
| آزمون | golden هر شریک، property و عدم نشت PII در success/error |
| کارایی | streaming برای حافظه؛ benchmark محلی برای زمان |
| Kafka | کلید ثابت؛ commit به ترتیب؛ failure با client تازه بازیابی شود |
| Redis Streams | publish سپس XACK، بررسی خطا و recovery PEL با XAUTOCLAIM |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — Content Filter و Message Filter چه تفاوتی دارند؟ مهم
پاسخ
پاسخ: اولی محتوای پیام را کوچک میکند و دومی کل پیام را عبور میدهد یا حذف میکند. Connect Filter و Streams filter از نوع دوماند؛ ReplaceField و MaskField از نوع اول.
۲ — برای 19,99 EUR و 1999 JPY چه اطلاعاتی لازم است؟ حیاتی
پاسخ
پاسخ: رقم واحد خرد ارز و اینکه ورودی major است یا minor. EUR دو و JPY صفر رقم دارد. اعشار اضافی و overflow باید رد شوند؛ float لازم نیست.
۳ — چرا Router و parserهای Normalizer جدا هستند؟ مهم
پاسخ
پاسخ: تا هر قالب آزمون مستقل داشته باشد و قالب جدید به registration و parser محدود شود؛ منطق core تغییر نکند.
۴ — lookup با cache سرد timeout میشود. چه کنیم؟ حیاتی
پاسخ
پاسخ: خطای گذرا و retry با backoff. اگر snapshot قدیمی در پنجرهٔ مجاز موجود است میتوان آن را با degraded مصرف کرد؛ بدون این سیاست پیام ناقص منتشر نمیشود.
۵ — ترتیب بازکردن پاکت امضاشده و رمزشده چیست؟ تکمیلی
پاسخ
پاسخ: metadata انتقال، decrypt معتبر، بررسی امضا، parse پاکت، تحویل payload. ترتیب معکوس wrap است.
۶ — مدل مرجع کجا ضرر دارد؟ مهم
پاسخ
پاسخ: وقتی مدل کل شرکت، schema تحمیلی یک ERP، پیام با فیلدهای اختیاری نامحدود یا قرارداد بیمالک شود. مدل کوچک برای واقعیت مشخص با مالک روشن قابل ادارهتر است.
۷ — چرا برای تبدیل مقدار mapValues انتخاب میکنیم؟ مهم
پاسخ
پاسخ: کلید حفظ میشود. map/selectKey میتوانند نیاز به repartition را برای عملیات وابسته به کلید بعدی ایجاد کنند و قلمرو ترتیب را تغییر دهند.
۸ — آیا RabbitMQ body transformer آماده دارد؟ حیاتی
پاسخ
پاسخ: خیر. interceptor سفارشی قابلیت توسعه دارد ولی built-inها metadata میافزایند؛ Shovel نیز translator دامنه نیست. consumer یا sidecar انتخاب معمول است.
۹ — شناسهٔ خروجی چرا ثابت است و چه تضمینی نمیدهد؟ مهم
پاسخ
پاسخ: برای dedup از raw id و type مشتق میشود. این بهتنهایی دو publish یا DB+publish را اتمیک نمیکند و enrichment را در دو تلاش ثابت نگه نمیدارد.
۱۰ — اگر streaming سریعتر نباشد چرا استفاده کنیم؟ تکمیلی
پاسخ
پاسخ: تا حجم اشیای decoded همزمان محدود شود. reader و خروجی هم باید bounded باشند؛ عدد benchmark از پیش تضمین نمیشود.
۱۱ — در رکورد invalid چه چیزی ذخیره میشود؟ مهم
پاسخ
پاسخ: stage، reason امن، source، raw id و fingerprint. بدنه و exception حاوی ورودی حساس نباید در clear ذخیره شوند؛ اصل داده جدا با retention مناسب نگهداری میشود.
واژهنامه
| اصطلاح | تعریف |
|---|---|
| مترجم پیام (Message Translator) | تبدیل قالب یا نمایش با حفظ معنای قراردادی |
| پوشانندهٔ پاکت (Envelope Wrapper) | افزودن پوشش مورد نیاز زیرساخت به دادهٔ برنامه |
| بازکننده (Unwrapper) | حذف لایههای پاکت در مقصد |
| غنیساز محتوا (Content Enricher) | افزودن داده از محاسبه، محیط یا منبع خارجی |
| پالایهٔ محتوا (Content Filter) | حذف یا تختکردن دادهٔ داخل پیام |
| پالایهٔ پیام (Message Filter) | تصمیم عبور یا حذف کل پیام |
| یکسانساز (Normalizer) | Router و مترجمهای قالبهای متفاوت با خروجی واحد |
| مدل دادهٔ مرجع (Canonical Data Model) | قرارداد تبادل مستقل از مدل داخلی برنامهها |
| نگاشتگر پیام (Messaging Mapper) | جزء مستقلِ آشنا با دامنه و پیام |
| لولهها و پالایهها (Pipes and Filters) | مرحلههای مستقل متصل با کانال |
| لایهٔ ضدفساد (Anticorruption Layer) | ترجمهٔ پاییندست برای حفاظت از مدل خود |
| زبان منتشرشده (Published Language) | قالب مستند تبادل که مالک بالادست منتشر میکند |
| خدمت میزبان باز (Open Host Service) | پروتکل عمومی بالادست برای مصرفکنندههای متعدد |
| تبدیل تکپیام (SMT / Single Message Transform) | تغییر سبک یک رکورد در Kafka Connect |
| شرط Connect (Predicate) | انتخاب رکورد برای SMT؛ negate نتیجه را معکوس میکند |
| زبان جریان (Kafka Streams DSL) | عملگرهای map، filter، join و دیگر عملیات جریان |
| بازپارتیشنبندی (Repartitioning) | توزیع مجدد رکوردها طبق کلید جدید |
| ارتقادهنده (Upcaster) | Translator از نسخهٔ قدیم payload به نسخهٔ بعد |
| پیشنویس مشترک (Draft) | خروجی Normalizer پیش از تبدیل معنا |
| واحد خرد (Minor units) | مقدار صحیح با توان ده تعریفشده برای ارز |
| امضای هش کلیددار (HMAC) | احراز اصالت یا pseudonymisation با کلید محرمانه |
| رمزنگاری احرازشده (AES-GCM) | رمزنگاری همراه tag؛ nonce باید برای هر کلید یکتا باشد |
| عدد یکبارمصرف (Nonce) | ورودی غیرتکراری هر encryption زیر یک کلید |
| ادغام درخواست همزمان (singleflight) | یک lookup مشترک برای فراخوانیهای همزمان یک key |
| کش منفی (Negative caching) | ذخیرهٔ پاسخ پیدا نشد با TTL محدود |
| کهنه هنگام بازسازی (Stale-while-revalidate) | پاسخ stale همراه refresh پسزمینه |
| فایل طلایی (Golden file) | خروجی مورد انتظار ذخیرهشده برای مقایسهٔ دقیق |
| آزمون ویژگی (Property test) | بررسی قانون روی ورودی تولیدشده |
| کانال نامعتبر (Invalid Message Channel) | مسیر جدای ورودی غیرقابل پردازش |
| سازگارکنندهٔ کانال (Channel Adapter) | اتصال برنامه یا پروتکل به کانال |
| فرایند جانبی (Sidecar) | helper مستقر کنار سرویس |
| سکوی یکپارچهسازی (ESB / iPaaS) | میزبان مرکزی تبدیل و مسیریابی |
| فهرست مجاز / فهرست حذف (Allowlist / Denylist) | اولی فقط فیلد مصوب را میسازد؛ دومی فقط نامهای مشخص را حذف میکند. | | اطلاعات شخصی / شبهناشناسسازی / ناشناسسازی (PII / Pseudonymisation / Anonymisation) | HMAC شناسه را پنهان میکند ولی با کلید و فهرست احتمالی قابل تطبیق است. | | قطعیت / تصویر لحظهای (Determinism / Snapshot) | شناسهٔ پایدار از snapshot غنیسازی که ممکن است تغییر کند جداست. | | عمر cache / کهنه در خطا (TTL / Stale-on-error / degraded) | پنجرهٔ تازگی و استفادهٔ محدود از پاسخ قدیمی همراه برچسب افت کیفیت. | | تأیید انتشار و بازگشت بیمسیر (Publisher confirm / mandatory / basic.return) | confirm مثبت بهتنهایی مسیر مقصد را ثابت نمیکند؛ return باید بررسی شود. | | تأیید، رد و پیشواکشی (Ack / Nack / Prefetch) | تعیین سرنوشت delivery و محدودکردن تعداد تأییدنشدگان. | | ثبت offset دستی (CommitRecords / DisableAutoCommit) | offset بعد از خروجی و به ترتیب partition ثبت میشود. | | مهار جابهجایی مالکیت (BlockRebalanceOnPoll / AllowRebalance) | هنگام batch از تغییر مالکیت جلوگیری و پس از آن آزاد میکند؛ timeout همچنان مهم است. | | نوشتن، دریافت و تأیید جریان (XADD / XREADGROUP / XACK) | فرمانهای پایهٔ lifecycle ورودی در Redis Streams. | | فهرست معلق و پسگیری (PEL / XAUTOCLAIM) | ورودی بیتأیید و انتقال مالکیت آن پس از idle؛ علامت > فقط پیام تازه میدهد. | | تراکنش Redis و نوع کلید غلط (MULTI/EXEC / WRONGTYPE) | اجرای بدون interleaving، نه rollback در خطای runtime. | | زنجیره و تحمل خطا (transforms / errors.tolerance / DLQ) | ترتیب SMT، سیاست توقف یا حذف و کانال شکست پشتیبانیشدهٔ sink. | | تبدیل فیلد در Connect (ReplaceField / MaskField / ExtractField / HoistField / Flatten) | انتخاب، تغییر نام، پوشاندن، استخراج، پوشش و تختکردن فیلدها. | | مدیریت metadata (InsertField / InsertHeader / HeaderFrom / DropHeaders) | افزودن ثابت یا metadata، انتقال فیلد به هدر و حذف هدر. | | نوع و schema در Connect (Cast / TimestampConverter / SetSchemaMetadata) | تبدیل نوع و زمان یا تنظیم metadata schema. | | انتخاب topic و key (RegexRouter / TimestampRouter / ValueToKey) | تغییر مقصد و کلید رکورد، با اثر روی partition. | | شرطها و وارونگی (TopicNameMatches / HasHeaderKey / RecordIsTombstone / negate) | انتخاب رکورد بر اساس topic، هدر یا tombstone و معکوسکردن شرط. | | تبدیل و جدول جریان (map / mapValues / selectKey / KTable) | حفظ یا تغییر key و state جدول برای join غنیسازی. | | زنجیره، cache و job رمزشده (Pipeline / Cache::flexible / ShouldBeEncrypted) | ابزارهای Laravel 13 برای مرحلهبندی، refresh و حفاظت queue payload. | | خواندن تدریجی (XMLReader / LazyCollection / json.Decoder) | parse مرحلهای که با reader و خروجی محدود، حافظه را کنترل میکند. | | سریالسازی و لایههای تبدیل (Serialization / Transport / Representation / Data type / Structure) | نمایش بایت، انتقال، قرارداد نمایش، نوع مقدار و ساختار فیلد از هم جدا هستند. | | زمان و واحد عددی (UTC / DST / ISO 4217 / Overflow) | قرارداد زمان، ابهام تغییر ساعت، رقم واحد خرد ارز و سرریز عدد صحیح. | | لاگ خام و بازپخش (Raw log / Replay / Retention / MAXLEN) | تاریخچه فقط تا زمانی که retention یا trim اجازه دهد قابل بازخوانی است. | | صندوق خروجی و ورودی (Outbox / Inbox / Idempotency) | ثبت خروجی کنار state محلی و تشخیص ورودی تکراری؛ مالکیت در صفحههای همسایه. |
منابع
- Hohpe and Woolf, Enterprise Integration Patterns: Message Translator, Envelope Wrapper, Content Enricher, Content Filter, Normalizer, Canonical Data Model, Messaging Mapper, Pipes and Filters. The site pages are summaries; the transformation layers (transport, representation, types, structures) and the Envelope Wrapper steps come from the book.
- Apache Kafka, Connect user guide (transformations, predicates, error reporting): raw source in the Kafka repository; the generated transformation reference.
- Apache Kafka, Streams DSL (stateless transformations,
mapversusmapValues): raw source. - RabbitMQ, Intercepting Messages and Dynamic Shovel parameters (rabbitmq-website repository, because rabbitmq.com sits behind Cloudflare).
- Redis, Transactions.
- Debezium, Outbox Event Router.
- Microsoft Learn, Anti-Corruption Layer pattern.
- Laravel 13, Cache (
Cache::flexible), HTTP client, Queues; framework source Pipeline and Cache Repository. - NIST SP 800-38D, Galois/Counter Mode (IV and invocation limits).
- SIX (ISO 4217 maintenance agency), official current currency list, including minor-unit digits.
- Go local package docs:
time/tzdata,encoding/xml,golang.org/x/sync/singleflight; franz-go consumer implementation and RabbitMQ amqp091-go channel implementation. - PHP client implementations: php-amqplib channel, Laravel Kafka consumer, consumer builder, producer builder, serializer contract, deserializer contract.
- Related pages: message design and schema evolution, integration styles and channels, advanced routing, context maps, designing for failure and reliable messaging, service communication.