Class: Webhookdb::Replicator::IcalendarCalendarV1

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

Defined Under Namespace

Classes: EventProcessor, Upserter

Constant Summary collapse

RECURRENCE_PROJECTION =
5.years
CLEANUP_SERVICE_NAMES =
["icalendar_event_v1"].freeze
SYNC_PERIOD =
4.hours

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, #_backfillers, #_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, #_store_enrichment_body?, #_to_json, #_upsert_webhook, #_verify_backfill_err_msg, #_webhook_state_change_fields, #admin_dataset, #backfill, #backfill_not_supported_message, #calculate_and_backfill_state_machine, #calculate_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, #enqueue_sync_targets, #enrichment_column, #ensure_all_columns, #ensure_all_columns_modification, #find_dependent, #find_dependent!, #indices, #initialize, #on_dependency_webhook_upsert, #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_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



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 18

def self.descriptor
  return Webhookdb::Replicator::Descriptor.new(
    name: "icalendar_calendar_v1",
    ctor: ->(sint) { Webhookdb::Replicator::IcalendarCalendarV1.new(sint) },
    feature_roles: [],
    resource_name_singular: "iCalendar Calendar",
    supports_webhooks: true,
    description: "Fetch and convert an icalendar format file into a schematized and queryable database table.",
    api_docs_url: "https://icalendar.org/",
  )
end

Instance Method Details

#_denormalized_columnsObject



70
71
72
73
74
75
76
77
78
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 70

def _denormalized_columns
  col = Webhookdb::Replicator::Column
  return [
    col.new(:row_created_at, TIMESTAMP, index: true, optional: true, defaulter: :now),
    col.new(:row_updated_at, TIMESTAMP, index: true, optional: true, defaulter: :now),
    col.new(:last_synced_at, TIMESTAMP, index: true, optional: true),
    col.new(:ics_url, TEXT, converter: col.converter_gsub("^webcal", "https")),
  ]
end

#_handle_down_error(e, request_url:, calendar_external_id:) ⇒ Object



204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 204

def _handle_down_error(e, request_url:, calendar_external_id:)
  case e
    when Down::TooManyRedirects
      response_status = 301
      response_body = "<too many redirects>"
    when Down::TimeoutError, Down::SSLError, Down::ConnectionError, Down::InvalidUrl
      response_status = 0
      response_body = e.to_s
    when Down::ClientError
      raise e if e.response.nil?
      response_status = e.response.code.to_i
      expected_errors = [
        417, # If someone uses an Outlook HTML calendar, fetch gives us a 417
      ]
      is_problem_error = (response_status > 404 || response_status < 400) &&
        !expected_errors.include?(response_status)
      raise e if is_problem_error
      response_body = e.response.body.to_s
    when Down::ServerError
      response_status = e.response.code.to_i
      response_body = e.response.body.to_s
    else
      response_body = nil
      response_status = nil
  end
  raise e if response_status.nil?
  self.logger.warn("icalendar_fetch_error",
                   response_body:, response_status:, request_url:, calendar_external_id:,)
  message = Webhookdb::Messages::ErrorIcalendarFetch.new(
    self.service_integration,
    calendar_external_id,
    response_status:,
    response_body:,
    request_url:,
    request_method: "GET",
  )
  self.service_integration.organization.alerting.dispatch_alert(message)
end

#_remote_key_columnObject



66
67
68
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 66

def _remote_key_column
  return Webhookdb::Replicator::Column.new(:external_id, TEXT)
end

#_resource_and_event(request) ⇒ Object



84
85
86
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 84

def _resource_and_event(request)
  return request.body, nil
end

#_resource_to_data(resource) ⇒ Object



99
100
101
102
103
104
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 99

def _resource_to_data(resource, *)
  data = resource.dup
  # Remove the client-provided webhook fields.
  data.clear
  return data
end

#_sync_row(row, dep) ⇒ Object



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 176

def _sync_row(row, dep)
  calendar_external_id = row.fetch(:external_id)
  request_url = row.fetch(:ics_url)
  begin
    io = Webhookdb::Http.chunked_download(request_url, rewindable: false)
  rescue Down::Error => e
    self._handle_down_error(e, request_url:, calendar_external_id:)
    return
  end

  upserter = Upserter.new(dep.replicator, calendar_external_id)
  processor = EventProcessor.new(io, upserter)
  processor.process
  # Delete all the extra replicator rows, and cancel all the rows that weren't upserted.
  dep.replicator.admin_dataset do |ds|
    ds = ds.where(calendar_external_id:)
    if (delete_condition = processor.delete_condition)
      ds.where(delete_condition).delete
    end
    # Update both the status, and set the data json to match.
    ds.exclude(compound_identity: processor.upserted_identities).update(
      status: "CANCELLED",
      data: Sequel.lit('data || \'{"STATUS":{"v":"CANCELLED"}}\'::jsonb'),
    )
  end
  self.admin_dataset { |ds| ds.where(pk: row.fetch(:pk)).update(last_synced_at: Time.now) }
end

#_timestamp_column_nameObject



80
81
82
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 80

def _timestamp_column_name
  return :row_updated_at
end

#_update_where_exprObject



88
89
90
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 88

def _update_where_expr
  return self.qualified_table_sequel_identifier[:row_updated_at] < Sequel[:excluded][:row_updated_at]
end

#_upsert_update_expr(inserting, **_kwargs) ⇒ Object



92
93
94
95
96
97
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 92

def _upsert_update_expr(inserting, **_kwargs)
  update = super
  # Only set created_at if it's not set so the initial insert isn't modified.
  self._coalesce_excluded_on_update(update, [:row_created_at])
  return update
end

#_webhook_response(request) ⇒ Object



32
33
34
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 32

def _webhook_response(request)
  return Webhookdb::WebhookResponse.for_standard_secret(request, self.service_integration.webhook_secret)
end

#calculate_webhook_state_machineObject



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 36

def calculate_webhook_state_machine
  step = Webhookdb::Replicator::StateMachineStep.new
  if self.service_integration.webhook_secret.blank?
    self.service_integration.save_changes
    step.output = %(You are about to add support for replicating iCalendar (.ics) URLs into WebhookDB.

We have detailed instructions on this process
at https://docs.webhookdb.com/guides/icalendar/.

The first step is to generate a secret you will use for signing
API requests you send to WebhookDB. You can use '#{Webhookdb::Id.rand_enc(16)}'
or generate your own value.
Copy and paste or enter a new value, and press enter.)
    return step.secret_prompt("secret").webhook_secret(self.service_integration)
  end
  step.output = %(
All set! Here is the endpoint to send requests to
from your backend. Refer to https://docs.webhookdb.com/guides/icalendar/
for details on the format of the request:

#{self.webhook_endpoint}

The secret to use for signing is:

#{self.service_integration.webhook_secret}

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

#delete_data_for_external_id(external_id) ⇒ Object



135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 135

def delete_data_for_external_id(external_id)
  relevant_integrations = self.service_integration.recursive_dependents.
    filter { |d| CLEANUP_SERVICE_NAMES.include?(d.service_name) }
  self.admin_dataset do |ds|
    ds.db.transaction do
      ds.where(external_id:).delete
      relevant_integrations.each do |sint|
        ds.db[sint.replicator.qualified_table_sequel_identifier].where(calendar_external_id: external_id).delete
      end
    end
  end
end

#documentation_urlObject



15
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 15

def documentation_url = Webhookdb::Icalendar::DOCUMENTATION_URL

#rows_needing_sync(dataset, now: Time.now) ⇒ Object



130
131
132
133
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 130

def rows_needing_sync(dataset, now: Time.now)
  cutoff = now - SYNC_PERIOD
  return dataset.where(Sequel[last_synced_at: nil] | Sequel.expr { last_synced_at < cutoff })
end

#sync_row(row) ⇒ Object



165
166
167
168
169
170
171
172
173
174
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 165

def sync_row(row)
  Appydays::Loggable.with_log_tags(icalendar_url: row.fetch(:ics_url)) do
    self.with_advisory_lock(row.fetch(:pk)) do
      if (dep = self.find_dependent("icalendar_event_v1"))
        self._sync_row(row, dep)
      end
      self.admin_dataset { |ds| ds.where(pk: row.fetch(:pk)).update(last_synced_at: Time.now) }
    end
  end
end

#upsert_has_deps?Boolean

Returns:

  • (Boolean)


30
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 30

def upsert_has_deps? = true

#upsert_webhook(request) ⇒ Object



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 106

def upsert_webhook(request)
  request_type = request.body.fetch("type")
  external_id = request.body.fetch("external_id")
  case request_type
    when "SYNC"
      super(request)
      Webhookdb::Jobs::IcalendarSync.perform_async(self.service_integration.id, external_id)
      return
    when "DELETE"
      self.delete_data_for_external_id(external_id)
      return
    when "__WHDB_UNIT_TEST"
      unless Webhookdb::RACK_ENV == "test"
        raise "someone tried to use the special unit test google event type outside of unit tests"
      end
      return super(request)
    else
      raise ArgumentError, "Unknown request type: #{request_type}"
  end
end