نسخه آنلاین در حال بارگذاری زمان... تهران: ۲۶°C
۲۸ کاربر آنلاین

PNo.30Light

نشریه تخصصی هوش مصنوعی، سیستم‌های سرور و مهندسی داده

تازه ترین‌ها
زیرساخت و سرور
زمان مطالعه: ۲۰ دقیقه ۰ بازدید

CloudEvents: استاندارد رویداد در معماری Event-Driven — راهنمای کامل

نویسنده: تحریریه فنی P30Light
CloudEvents: استاندارد رویداد در معماری Event-Driven — راهنمای کامل
✦ خلاصه نکات کلیدی مقاله
  • CloudEvents envelope استاندارد CNCF برای metadata رویداد — id، source، type، specversion + payload.
  • HTTP structured/binary و Kafka binding — یک event format برای EventBridge، Azure Grid، Knative، Debezium.
  • CNCF Graduated (ژانویه ۲۰۲۴) + CloudEvents SQL V1 — filter و route رویداد بدون vendor lock.

رویدادها (Events) همه‌جا هستند: S3 upload، order placed، pod crashed، payment confirmed. اما هر سرویس event را متفاوت توصیف می‌کند — AWS یک JSON، Azure یک schema، Kafka یک Avro، webhook داخلی یک format دیگر.

نتیجه: برای هر source جدید parser جدید، router جدید، dedup logic جدید — و portability صفر بین cloudها.

CloudEvents پاسخ industry است:

A specification for describing event data in a common way.

یعنی envelope استاندارد برای metadata رویداد — vendor-neutral، protocol-agnostic، با SDK در همه زبان‌های اصلی.

پروژه در CNCF Serverless Working Group ساخته شد، ژانویه ۲۰۲۴ CNCF Graduated شد، و امروز توسط Knative، Amazon EventBridge، Azure Event Grid، Google Eventarc، Debezium، Tekton، Argo Events و ده‌ها platform دیگر adopt شده است.


مشکل event format اختصاصی

بدون استاندارد:
S3 event      → { "Records": [...] }           ← AWS-specific
Azure Blob    → [{ "topic": "/subscriptions/..." }] ← Azure-specific
GitHub webhook → { "action": "opened", ... }    ← GitHub-specific
Custom app    → { "eventType": "order", ... }    ← ad-hoc

Consumer باید برای هر source کد جدا بنویسد
مشکلپیامد
Format per vendorN source = N parsers
No common routingfilter بر اساس fieldهای random
No dedup standardid field inconsistent
Tracing brokencorrelation ID ad-hoc
Multi-cloudrewrite همه integrationها
Toolingنمی‌توان generic event router ساخت

CloudEvents context attributes را normalize می‌کند — payload (data) آزاد است.


CloudEvents چیست؟

CloudEvents یک specification (نه product) برای:

  • Context attributes — metadata مشترک هر event
  • Event data — payload اختصاصی business
  • Event formats — JSON (required)، Protobuf
  • Protocol bindings — HTTP، Kafka، AMQP، MQTT، WebSocket، NATS

Spec repo: github.com/cloudevents/spec

نسخه stable: v1.0.2 (سازگار با v1.0)

Primer: cloudevents/spec — primer.md


ساختار یک CloudEvent

مثال JSON (Structured)

{
  "specversion": "1.0",
  "type": "com.example.order.placed",
  "source": "/order-service/production",
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "time": "2026-09-02T10:30:00Z",
  "datacontenttype": "application/json",
  "subject": "order-12345",
  "dataschema": "https://example.com/schemas/order/v1.json",
  "data": {
    "orderId": "12345",
    "customerId": "67890",
    "totalAmount": 99.99,
    "currency": "USD"
  }
}

Context vs Data

┌─────────────────────────────────────────┐
│           CloudEvent Envelope            │
│  ┌───────────────────────────────────┐  │
│  │  Context Attributes (metadata)     │  │
│  │  specversion, type, source, id,    │  │
│  │  time, subject, datacontenttype    │  │
│  └───────────────────────────────────┘  │
│  ┌───────────────────────────────────┐  │
│  │  data (business payload)           │  │
│  │  — schema آزاد، per event type     │  │
│  └───────────────────────────────────┘  │
└─────────────────────────────────────────┘
بخشنقش
Contextrouting، filtering، dedup، tracing
Databusiness logic — structure توسط type تعریف می‌شود

Context Attributes

Required (الزامی)

AttributeTypeتوضیح
specversionStringنسخه spec — "1.0"
idStringشناسه یکتا per producer — برای deduplication
sourceURI-Referencecontext رخداد — /my-service یا https://example.com/producer
typeStringنوع event — reverse DNS: com.example.object.created

Optional (توصیه‌شده)

AttributeTypeتوضیح
datacontenttypeStringMIME type payload — application/json
dataschemaURIschema URI برای validate data
subjectStringentity مرتبط — order ID، file path
timeTimestampRFC 3339 — زمان occurrence

Extensions

vendor یا domain می‌تواند attribute اضافه کند — نام باید lowercase باشد:

{
  "traceid": "abc-123-def",
  "partitionkey": "customer-67890"
}

Naming Conventions

type — Reverse DNS

com.github.pull_request.opened
com.google.cloud.storage.object.finalize
io.knative.serving.revision.ready
com.example.order.placed
com.example.order.cancelled
  • namespace collision ندارد
  • filter در event router ساده: type.startsWith("com.example.order.")

source — URI-Reference

/order-service
https://github.com/myorg/myrepo
/k8s/namespaces/default/services/order-svc
urn:uuid:6e8c-1234-5678

id — Deduplication

  • UUID توصیه می‌شود
  • consumer: (source, id) unique — duplicate را ignore
  • at-least-once delivery safe

Protocol Bindings

CloudEvents format (JSON) را از transport (HTTP/Kafka) جدا می‌کند.

HTTP Binding

سه Content Mode:

ModeتوضیحContent-Type
Structuredکل event در bodyapplication/cloudevents+json
Binaryattributes در headers ce-*، data در bodyapplication/json (body)
Batcharray of eventsapplication/cloudevents-batch+json

Structured mode:

POST /events HTTP/1.1
Host: broker.example.com
Content-Type: application/cloudevents+json

{
  "specversion": "1.0",
  "type": "com.example.order.placed",
  "source": "/order-service",
  "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "data": { "orderId": "12345" }
}

Binary mode:

POST /orders HTTP/1.1
Host: broker.example.com
Content-Type: application/json
ce-specversion: 1.0
ce-type: com.example.order.placed
ce-source: /order-service
ce-id: a1b2c3d4-e5f6-7890-abcd-ef1234567890
ce-time: 2026-09-02T10:30:00Z

{"orderId": "12345", "totalAmount": 99.99}

Binary mode برای webhook و API gateway رایج است — body خالص business JSON.

Kafka Binding

Attributes در headers با prefix ce_:

ce_specversion: 1.0
ce_type: com.example.order.placed
ce_source: /order-service
ce_id: a1b2c3d4-e5f6-7890-abcd-ef1234567890

Value = data payload (JSON bytes).

Topic routing: بر اساس ce_type یا custom header.

سایر Bindings

ProtocolBindinguse case
AMQP 1.0application-propertiesRabbitMQ، Azure Service Bus
MQTT 3.1.1 / 5.0user propertiesIoT، edge
NATSheaderslightweight messaging
WebSocketframe metadatareal-time push
Protobufbinary format + batchinghigh-throughput

Event Formats

FormatStatusNotes
JSONRequired — همه SDKdefault
ProtobufOptionalbatching support v1.0.2+
Avrovia data + dataschemapayload schema

SDKs

از cloudevents.io — official SDKs:

LanguagePackage
Gogithub.com/cloudevents/sdk-go/v2
Pythoncloudevents
JavaScriptcloudevents (npm)
Javaio.cloudevents:cloudevents-core
C#CloudNative.CloudEvents
Rustcloudevents-sdk
Rubycloudevents
PHPcloudevents/sdk-php
PowerShellv1.0.2+

Python — produce

from cloudevents.http import CloudEvent, to_structured
import requests

attributes = {
    "type": "com.example.order.placed",
    "source": "https://order-service.example.com",
}
data = {"orderId": "12345", "amount": 99.99}

event = CloudEvent(attributes, data)
headers, body = to_structured(event)

requests.post(
    "https://broker.example.com/events",
    headers=headers,
    data=body,
)

Go — produce

import (
    cloudevents "github.com/cloudevents/sdk-go/v2"
    "github.com/google/uuid"
)

func sendEvent(ctx context.Context, client cloudevents.Client) error {
    event := cloudevents.NewEvent()
    event.SetSpecVersion(cloudevents.VersionV1)
    event.SetType("com.example.order.placed")
    event.SetSource("/order-service")
    event.SetID(uuid.New().String())
    event.SetData(cloudevents.ApplicationJSON, map[string]interface{}{
        "orderId": "12345",
        "amount":  99.99,
    })
    return client.Send(ctx, event)
}

Go — consume

func receive(ctx context.Context, event cloudevents.Event) {
    fmt.Printf("type=%s source=%s id=%s\n",
        event.Type(), event.Source(), event.ID())

    var order map[string]interface{}
    event.DataAs(&order)
}

CloudEvents SQL

ژوئن ۲۰۲۴ — CloudEvents SQL V1 approve شد:

query و filter روی stream رویداد با syntax استاندارد:

-- مثال مفهومی
SELECT * FROM events
WHERE type LIKE 'com.example.order.%'
  AND source = '/order-service'
  AND time > '2026-09-01T00:00:00Z'

برای event router، filter subscription، audit query — بدون custom DSL per platform.


Adopters و Ecosystem

CloudEvents توسط همه hyperscalerها و ecosystem cloud-native adopt شده:

Cloud Providers

Platformسرویس
AWSAmazon EventBridge — CloudEvents v1.0 JSON
AzureAzure Event Grid — native CloudEvents
GoogleEventarc
AlibabaEventBridge
TencentEventBridge
IBMCode Engine
OracleOCI Events

Kubernetes / CNCF

Projectنقش
Knative Eventingهمه event data CloudEvents compliant
Argo EventsCloudEvents trigger برای workflow
Tekton Pipelinesemit CloudEvents on task/pipeline run
DebeziumCDC events در format CloudEvents
Falcosecurity policy violation events
Flyteworkflow progress events
Harborregistry artifact events
TriggerMeshevent routing
OpenFaaSCloudEvents trigger
wasmCloudcontrol plane events

Knative Eventing

Knative Eventing CloudEvents-only:

Producer → Broker → Trigger (filter by type/attributes) → Subscriber

                └── Channel (Kafka, NATS, InMemory)

Broker + Trigger YAML:

apiVersion: eventing.knative.dev/v1
kind: Trigger
metadata:
  name: order-placed-trigger
  namespace: default
spec:
  broker: default
  filter:
    attributes:
      type: com.example.order.placed
  subscriber:
    ref:
      apiVersion: serving.knative.dev/v1
      kind: Service
      name: order-processor

Knative automatically wraps/delivers CloudEvents — consumer فقط type و data را handle می‌کند.


Argo Events

Argo Events — event-driven automation روی Kubernetes:

apiVersion: argoproj.io/v1alpha1
kind: Sensor
metadata:
  name: order-sensor
spec:
  dependencies:
    - name: order-placed
      eventSourceName: webhook
      eventName: order
      filters:
        data:
          - path: body.type
            type: string
            value:
              - com.example.order.placed
  triggers:
    - template:
        name: run-workflow
        k8s:
          operation: create
          source:
            resource:
              apiVersion: argoproj.io/v1alpha1
              kind: Workflow
              # ...

EventSource webhook → CloudEvents → Sensor → Workflow/Job/Knative.


Debezium + CloudEvents

Debezium CDC (Change Data Capture) می‌تواند change events را CloudEvents format emit کند:

{
  "specversion": "1.0",
  "type": "io.debezium.postgresql.data.change",
  "source": "/debezium/postgresql/orderdb/orders",
  "id": "001-00000000000000000001-00000000000000000001-0",
  "time": "2026-09-02T10:30:00Z",
  "datacontenttype": "application/json",
  "data": {
    "before": null,
    "after": { "id": 12345, "status": "placed" },
    "op": "c"
  }
}

Database change → Kafka → Knative/Argo/custom consumer — یک format end-to-end.


Event Router Pattern

                    ┌──────────────┐
  S3 ──► CE ───────►│              │
  GitHub ──► CE ───►│ Event Router │──► filter by type ──► Service A
  Debezium ──► CE ─►│  (generic)   │──► filter by source ─► Service B
  Custom ──► CE ───►│              │──► dead letter queue
                    └──────────────┘

با CloudEvents envelope، یک router همه sourceها را handle می‌کند — بدون N custom adapter.


مقایسه

Custom JSONAvro (Kafka)CloudEvents
Metadata standard❌ ad-hocschema registry✅ spec
Routingcustomtopic-basedtype + attributes
Dedupcustomoffsetid + source
Multi-cloudrewriteKafka-only✅ universal
SDKDIYAvro libs9+ languages
Payload freedom✅ (with schema)

CloudEvents جایگزین Avro/Protobuf نیست — envelope روی هر format می‌نشیند.


Security و Privacy

از spec — Privacy & Security:

نگرانیراهکار
PII در dataencrypt payload، minimize fields
source spoofingauthenticate producer (mTLS، API key)
Replay attackid dedup + time window
Sensitive metadataextension attributes را careful expose کنید
Size limitsspec توصیه size limit per binding

CloudEvents authentication را define نمی‌کند — transport layer (HTTPS، Kafka SASL) مسئول است.


Best Practices

  1. type با reverse DNScom.company.domain.event.action
  2. id = UUID — dedup reliable
  3. time همیشه set — ordering و audit
  4. subject برای entity ID — filter آسان
  5. dataschema برای contract — consumer validation
  6. Structured mode برای debugging — Binary برای performance
  7. Observe before route — log type/source distribution
  8. Version event typescom.example.order.placed.v2 نه breaking change در v1
  9. Dead letter queue — eventهای unprocessable
  10. Idempotent consumer(source, id) check

چه زمانی CloudEvents؟

✅ مناسب

  • Event-driven architecture — microservices، serverless
  • Multi-cloud / hybrid — یک format everywhere
  • Knative / Argo Events / Tekton stack
  • CDC با Debezium → downstream consumers
  • Webhook normalization — gateway تبدیل به CE
  • Generic event router — filter by type
  • IoT → cloud pipeline — MQTT/HTTP binding

❌ کمتر مناسب

وضعیتجایگزین
Request/Response sync APIREST/gRPC
High-throughput binary only internalProtobuf gRPC بدون envelope
Single vendor lock acceptablenative format (S3-only)
Stream processing با schema evolution سنگینAvro + Schema Registry (می‌توان CE + Avro data)

CloudEvents در stack P30Light

Database (Debezium CDC)

    ▼ CloudEvents
Kafka / Knative Broker

    ├── Trigger → Knative Service
    ├── [Argo Events](/blog/argo-project-kubernetes-gitops-cicd/) Sensor → Workflow
    └── [Cilium](/blog/cilium-ebpf-kubernetes-networking/) Hubble (network events)

GitOps با Argo CD — Trigger/Broker YAML در Git.


Troubleshooting

مشکلعلتfix
Consumer reject eventmissing required attrcheck specversion, id, source, type
Duplicate processingno id dedupstore (source, id)
Wrong routingtype typoreverse DNS convention
Binary mode parse failmissing ce-* headervalidate HTTP binding
Schema mismatchdata vs dataschemacontract test
Knative Trigger no matchfilter attributeskubectl describe trigger
# Knative — inspect broker events
kubectl get triggers -A
kubectl describe trigger order-placed-trigger

# Argo Events — sensor logs
kubectl logs -n argo-events deploy/sensor-controller -f

Timeline پروژه

تاریخmilestone
اکتبر ۲۰۱۹CloudEvents v1.0 release + CNCF Incubator
دسامبر ۲۰۲۰v1.0.1 — WebSocket binding
فوریه ۲۰۲۲v1.0.2 — PowerShell SDK، Protobuf batching
ژانویه ۲۰۲۴CNCF Graduated
ژوئن ۲۰۲۴CloudEvents SQL V1

جمع‌بندی

بدون CloudEventsبا CloudEvents
N event formatsیک envelope
custom routingtype + attributes
ad-hoc dedupid + source
vendor lockportable across cloud
no generic toolingSDK + router + SQL

CloudEvents specification است — not a product. اما adoption توسط همه cloud major و CNCF ecosystem آن را de facto standard event envelope کرده است.

اگر event-driven architecture دارید — یا plan می‌کنید — CloudEvents اولین تصمیم معماری باید باشد، نه afterthought.

قدم بعدی

  1. Specification را بخوانید
  2. SDK زبان خود را نصب کنید — یک producer + consumer تست
  3. HTTP structured mode → webhook endpoint
  4. Knative Broker + Trigger روی staging cluster
  5. Debezium CloudEvents format → Kafka topic
  6. CloudEvents SQL — filter subscription design

منابع:


منتشر شده در P30Light — بخش زیرساخت سرور و Cloud Native.

لینک گزارش با موفقیت کپی گردید!