Class: Webhookdb::Replicator::EmailOctopusEventV1

Inherits:
Base
  • Object
show all
Includes:
Appydays::Loggable
Defined in:
lib/webhookdb/replicator/email_octopus_event_v1.rb

Defined Under Namespace

Classes: EventBackfiller

Constant Summary collapse

BUILD_EVENT_MD5 =
Webhookdb::Replicator::Column::IsomorphicProc.new(
  ruby: lambda do |resource:, **|
    # MD5 includes occurred_at, event_type, email_octopus_contact_id, and email_octopus_campaign_id.
    md5 = Digest::MD5.new
    md5.update(resource.fetch("occurred_at"))
    md5.update(resource.fetch("event_type"))
    md5.update(resource.dig("contact", "id"))
    md5.update(resource.fetch("campaign_id", "missing"))
    md5.hexdigest
  end,
)
CAMPAIGN_EVENT_TYPES =
[
  "bounced",
  "clicked",
  "complained",
  "opened",
  "unsubscribed",
].freeze

Constants inherited from Base

Base::MAX_INDEX_NAME_LENGTH

Constants included from DBAdapter::ColumnTypes

DBAdapter::ColumnTypes::BIGINT, DBAdapter::ColumnTypes::BIGINT_ARRAY, DBAdapter::ColumnTypes::BOOLEAN, DBAdapter::ColumnTypes::COLUMN_TYPES, DBAdapter::ColumnTypes::DATE, DBAdapter::ColumnTypes::DECIMAL, DBAdapter::ColumnTypes::DOUBLE, DBAdapter::ColumnTypes::FLOAT, DBAdapter::ColumnTypes::INTEGER, DBAdapter::ColumnTypes::INTEGER_ARRAY, DBAdapter::ColumnTypes::OBJECT, DBAdapter::ColumnTypes::TEXT, DBAdapter::ColumnTypes::TEXT_ARRAY, DBAdapter::ColumnTypes::TIMESTAMP, DBAdapter::ColumnTypes::UUID

Instance Attribute Summary

Attributes inherited from Base

#service_integration

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#_any_subscriptions_to_notify?, #_backfill_state_change_fields, #_clear_backfill_information, #_clear_webook_information, #_coalesce_excluded_on_update, #_enqueue_backfill_jobs, #_extra_index_specs, #_fetch_enrichment, #_find_dependency_candidate, #_notify_dependents, #_parallel_backfill, #_prepare_for_insert, #_publish_rowupsert, #_resource_to_data, #_store_enrichment_body?, #_to_json, #_upsert_update_expr, #_verify_backfill_err_msg, #_webhook_state_change_fields, #admin_dataset, #backfill, #backfill_not_supported_message, #calculate_and_backfill_state_machine, #calculate_dependency_state_machine_step, #calculate_preferred_create_state_machine, chunked_row_update_bounds, #clear_backfill_information, #clear_webhook_information, #create_table, #create_table_modification, #data_column, #dbadapter_table, #denormalized_columns, #descriptor, #dispatch_request_to, #documentation_url, #enqueue_sync_targets, #enrichment_column, #ensure_all_columns, #ensure_all_columns_modification, #find_dependent, #find_dependent!, #indices, #initialize, #on_backfill_error, #preferred_create_state_machine_method, #preprocess_headers_for_logging, #primary_key_column, #process_state_change, #process_webhooks_synchronously?, #qualified_table_sequel_identifier, #readonly_dataset, #remote_key_column, #requires_sequence?, #resource_name_plural, #resource_name_singular, #schema_and_table_symbols, #storable_columns, #synchronous_processing_response_body, #timestamp_column, #upsert_has_deps?, #upsert_webhook, #upsert_webhook_body, #verify_backfill_credentials, #webhook_endpoint, #webhook_response

Constructor Details

This class inherits a constructor from Webhookdb::Replicator::Base

Class Method Details

.descriptorWebhookdb::Replicator::Descriptor



9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/webhookdb/replicator/email_octopus_event_v1.rb', line 9

def self.descriptor
  return Webhookdb::Replicator::Descriptor.new(
    name: "email_octopus_event_v1",
    ctor: ->(sint) { Webhookdb::Replicator::EmailOctopusEventV1.new(sint) },
    feature_roles: [],
    resource_name_singular: "Email Octopus Event",
    dependency_descriptor: Webhookdb::Replicator::EmailOctopusListV1.descriptor,
    supports_webhooks: true,
    supports_backfill: true,
    api_docs_url: "https://emailoctopus.com/api-documentation",
  )
end

Instance Method Details

#_backfillersObject



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/webhookdb/replicator/email_octopus_event_v1.rb', line 181

def _backfillers
  list_sint = self.service_integration.depends_on
  api_key = list_sint.replicator.backfill_key!
  campaign_sint = list_sint.replicator.find_dependent!("email_octopus_campaign_v1")
  campaign_svc = campaign_sint.replicator
  backfillers = campaign_svc.admin_dataset(timeout: :fast) do |campaign_ds|
    campaign_ds.select(:email_octopus_id).flat_map do |campaign|
      CAMPAIGN_EVENT_TYPES.map do |event_type|
        EventBackfiller.new(
          event_svc: self,
          campaign_id: campaign[:email_octopus_id],
          api_key:,
          event_type:,
        )
      end
    end
  end
  return backfillers
end

#_denormalized_columnsObject



37
38
39
40
41
42
43
44
45
# File 'lib/webhookdb/replicator/email_octopus_event_v1.rb', line 37

def _denormalized_columns
  return [
    Webhookdb::Replicator::Column.new(:email_octopus_contact_id, TEXT, data_key: ["contact", "id"]),
    Webhookdb::Replicator::Column.new(:contact_email_address, TEXT, data_key: ["contact", "email_address"]),
    Webhookdb::Replicator::Column.new(:email_octopus_campaign_id, TEXT, data_key: ["campaign_id"], optional: true),
    Webhookdb::Replicator::Column.new(:event_type, TEXT),
    Webhookdb::Replicator::Column.new(:occurred_at, TIMESTAMP, index: true, converter: :time),
  ]
end

#_remote_key_columnObject



33
34
35
# File 'lib/webhookdb/replicator/email_octopus_event_v1.rb', line 33

def _remote_key_column
  return Webhookdb::Replicator::Column.new(:unique_id, UUID, optional: true, defaulter: BUILD_EVENT_MD5)
end

#_resource_and_event(request) ⇒ Object



97
98
99
100
# File 'lib/webhookdb/replicator/email_octopus_event_v1.rb', line 97

def _resource_and_event(request)
  return nil, nil if request.body.is_a?(Hash) && !request.body.key?("occurred_at")
  return request.body, nil
end

#_timestamp_column_nameObject



47
48
49
# File 'lib/webhookdb/replicator/email_octopus_event_v1.rb', line 47

def _timestamp_column_name
  return :occurred_at
end

#_update_where_exprObject



102
103
104
105
106
107
# File 'lib/webhookdb/replicator/email_octopus_event_v1.rb', line 102

def _update_where_expr
  # 'occurred_at' is the timestamp, but it's used in the unique id,
  # so there's no way to use it as part of the conditional upsert.
  # So events are effectively immutable, and we know we shouldn't bother overwriting what's already in the DB.
  return Sequel[false]
end

#_upsert_webhook(request, upsert: true) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/webhookdb/replicator/email_octopus_event_v1.rb', line 51

def _upsert_webhook(request, upsert: true)
  return super unless request.body.is_a?(Array)

  # If the body is an array, it means we are upserting data from webhooks and have to transform the data
  # in order to be able to upsert.
  new_bodies = request.body.
    # Events older than 30 days may not have occurred_at on free plans
    select { |wh| wh.key?("occurred_at") }.
    map do |wh|
      new_body = {
        "contact" => {
          "id" => wh.fetch("contact_id"),
          "email_address" => wh.fetch("contact_email_address"),
        },
        "occurred_at" => wh.fetch("occurred_at"),
        "event_type" => wh.fetch("type"),
      }

      # "campaign_id" isn't always populated in the webhoooks, it is only there on event types that are tied
      # to a specific "campaign", (that's Email Octopus's word for an email message), like "bounced" or "opened"
      if (campaign_id = wh["campaign_id"])
        new_body["campaign_id"] = campaign_id
      end
      new_body
    end

  new_bodies.each do |b|
    new_request = request.dup
    new_request.body = b
    super(new_request, upsert:)
  end

  list_svc = self.service_integration.depends_on.replicator
  contact_sint = list_svc.find_dependent("email_octopus_contact_v1")
  return unless contact_sint
  contact_svc = contact_sint.replicator
  # For events that pertain to a contact being created or updated in some way, we also upsert them using
  # the contact integration so that the new information can be recorded in the contact table
  contact_event_types = ["contact.created", "contact.updated", "contact.deleted"]
  contact_events = request.body.filter { |nb| contact_event_types.include?(nb.fetch("type")) }
  return if contact_events.empty?
  contact_request = request.dup
  contact_request.body = contact_events
  contact_svc._upsert_webhook(contact_request, upsert:)
end

#_webhook_response(request) ⇒ Object



109
110
111
112
113
114
115
116
117
118
# File 'lib/webhookdb/replicator/email_octopus_event_v1.rb', line 109

def _webhook_response(request)
  signature_header = request.env["HTTP_EMAILOCTOPUS_SIGNATURE"]
  return Webhookdb::WebhookResponse.error("missing signature") if signature_header.nil?

  request.body.rewind
  data = request.body.read
  verified = Webhookdb::EmailOctopus.verify_webhook(data, signature_header, self.service_integration.webhook_secret)
  return Webhookdb::WebhookResponse.ok if verified
  return Webhookdb::WebhookResponse.error("invalid signature")
end

#calculate_backfill_state_machineObject



158
159
160
161
162
163
164
165
166
167
# File 'lib/webhookdb/replicator/email_octopus_event_v1.rb', line 158

def calculate_backfill_state_machine
  if (step = self.calculate_dependency_state_machine_step(dependency_help: ""))
    return step
  end
  step = Webhookdb::Replicator::StateMachineStep.new
  # We're using the API Key from the dependency, we don't need to ask for it here
  step.output = %(Great! We are going to start replicating your #{self.resource_name_plural}.
#{self._query_help_output})
  return step.completed
end

#calculate_webhook_state_machineObject



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/webhookdb/replicator/email_octopus_event_v1.rb', line 120

def calculate_webhook_state_machine
  if (step = self.calculate_dependency_state_machine_step(dependency_help: ""))
    return step
  end
  step = Webhookdb::Replicator::StateMachineStep.new
  unless self.service_integration.webhook_secret.present?
    step.output = %(You are about to start replicating #{self.resource_name_plural} into WebhookDB.
We've made an endpoint available for #{self.resource_name_singular} webhooks:

#{self._webhook_endpoint}

- From your Email Octopus dashboard, go to Account Settings -> Integrations & API.
- Then click the 'Manage' button next to 'Webhooks'.
- Then under the "Endpoints" header, click "Add endpoint"
- In the "URL" field you can enter the URL above.
- Then check boxes for all events, because we want this webhook to listen for everything.
This includes:
- "Contact events to send" -> "Created", "Updated", and "Deleted"
- "Email events to send" -> Deleted" "Clicked", "Opened", "Bounced",
  "Complained", and "Unsubscribed"
- You can keep the checkboxes under "Exclude contact events that occur" unchecked.

- Save the endpoint.

You'll be dropped back on the Webhooks page.
Click 'View Secret' next to the endpoint you added, and Copy it.
We'll use it for webhook verification.)
    return step.secret_prompt("webhook secret").webhook_secret(self.service_integration)
  end

  step.output = %(Great! WebhookDB is now listening for #{self.resource_name_singular} webhooks.
#{self._query_help_output}
In order to backfill existing #{self.resource_name_plural}, run this from a shell:

#{self._backfill_command})
  return step.completed
end

#on_dependency_webhook_upsert(_replicator, _payload) ⇒ Object



169
170
171
# File 'lib/webhookdb/replicator/email_octopus_event_v1.rb', line 169

def on_dependency_webhook_upsert(_replicator, _payload, *)
  return
end