Class: Mammoth::EventSerializer

Inherits:
Object
  • Object
show all
Defined in:
lib/mammoth/event_serializer.rb

Overview

Serializes CDC-core change events into webhook payloads.

The serializer projects Mammoth’s sink payload from CDC vocabulary rather than pgoutput protocol vocabulary. That keeps webhook delivery independent from PostgreSQL-specific message shapes while preserving source metadata such as commit LSN and transaction identity when available.

Constant Summary collapse

DEFAULT_SOURCE =
"postgresql"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(event) ⇒ EventSerializer

Returns a new instance of EventSerializer.

Parameters:

  • event (Hash, #to_h)

    normalized CDC event



26
27
28
# File 'lib/mammoth/event_serializer.rb', line 26

def initialize(event)
  @event = event.respond_to?(:to_h) ? event.to_h : event
end

Class Method Details

.call(event) ⇒ Hash

Serialize an event-like object into a webhook-ready Hash.

Parameters:

  • event (Hash, #to_h)

    normalized CDC event

Returns:

  • (Hash)

    webhook payload



21
22
23
# File 'lib/mammoth/event_serializer.rb', line 21

def self.call(event)
  new(event).call
end

Instance Method Details

#callHash

Return the webhook payload.

Returns:

  • (Hash)

    webhook payload



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/mammoth/event_serializer.rb', line 33

def call
  event_hash = stringify_keys(@event)
  {
    "event_id" => event_hash["event_id"] || SecureRandom.uuid,
    "source" => event_hash["source"] || DEFAULT_SOURCE,
    "operation" => normalize_operation(event_hash.fetch("operation")),
    "namespace" => event_hash["namespace"] || event_hash["schema"],
    "entity" => event_hash["entity"] || event_hash["table"],
    "identity" => event_hash["identity"] || event_hash["primary_key"],
    "source_position" => event_hash["source_position"] || event_hash["commit_lsn"],
    "transaction_id" => event_hash["transaction_id"],
    "occurred_at" => occurred_at(event_hash),
    "data" => event_data(event_hash),
    "changes" => event_hash["changes"] || [],
    "metadata" => event_hash["metadata"] || {}
  }
end

#to_json(*_args) ⇒ String

Return JSON representation of the webhook payload.

Returns:

  • (String)

    JSON representation of the payload



54
55
56
# File 'lib/mammoth/event_serializer.rb', line 54

def to_json(*_args)
  JSON.generate(call)
end