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

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

#_clean_ics_url(url) ⇒ Object

We get all sorts of strange urls, fix up what we can.



210
211
212
213
214
215
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 210

def _clean_ics_url(url)
  u = URI(url)
  # https://xyz.com:80 is invalid, set it to 443 which yields https://xyz.com
  u.port = 443 if u.scheme == "https" && u.port == 80
  return u.to_s
end

#_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



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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 217

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::NotModified
      # Do not alert on 304, but do log
      self.logger.info("icalendar_fetch_not_modified", response_status: 304, request_url:, calendar_external_id:)
      return
    when Down::SSLError
      self._handle_retryable_down_error!(e, request_url:, calendar_external_id:)
    when Down::TimeoutError, Down::ConnectionError, Down::InvalidUrl, URI::InvalidURIError
      response_status = 0
      response_body = e.to_s
    when Down::ClientError
      raise e if e.response.nil?
      response_status = e.response.code.to_i
      self._handle_retryable_down_error!(e, request_url:, calendar_external_id:) if
        self._retryable_client_error?(e, request_url:)
      # These are all the errors we've seen, we can't do anything about.
      # In theory we should do this for ALL 4xx errors,
      # but we'd rather error on the WebhookDB side until we're sure
      # we want to ignore things.
      expected_errors = [
        400, 401, 402, 403, # Common access problems we can't do anything about
        404, 405, # Fundamental issues with the URL given
        409, 410, # More access problems
        417, # If someone uses an Outlook HTML calendar, fetch gives us a 417
        429, # Usually 429s are retried (as above), but in some cases they're not.
      ]
      # For most client errors, we can't do anything about it. For example,
      # and 'unshared' URL could result in a 401, 403, 404, or even a 405.
      # For now, other client errors, we can raise on,
      # in case it's something we can fix/work around.
      # For example, it's possible something like a 415 is a WebhookDB issue.
      raise e unless expected_errors.include?(response_status)
      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

#_handle_retryable_down_error!(e, request_url:, calendar_external_id:) ⇒ Object

Raises:

  • (Amigo::Retry::OrDie)


286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 286

def _handle_retryable_down_error!(e, request_url:, calendar_external_id:)
  # Retry on these, which are hopefully transient.
  # For now, if they aren't transient, die so we see the job.
  # We will probably need to do an alert if the retries on exhausted instead.
  retry_in = rand(4..60).minutes
  self.logger.debug(
    "icalendar_fetch_error_retry",
    response_status: e.respond_to?(:response) ? e.response&.code : 0,
    request_url:,
    calendar_external_id:,
    retry_at: Time.now + retry_in,
  )
  raise Amigo::Retry::OrDie.new(10, retry_in)
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

#_retryable_client_error?(e, request_url:) ⇒ Boolean

Returns:

  • (Boolean)


275
276
277
278
279
280
281
282
283
284
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 275

def _retryable_client_error?(e, request_url:)
  code = e.response.code.to_i
  # This is a bad domain that returns 429 for most requests.
  # Tell the org admins it won't sync.
  return false if code == 429 && request_url.start_with?("https://ical.schedulestar.com")
  # Other 429s can be retried.
  return true if code == 429
  # Otherwise, handle the client error normally, by telling the org admins, or raising.
  return false
end

#_sync_row(row, dep, now:) ⇒ Object



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
203
204
205
206
207
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 178

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

  upserter = Upserter.new(dep.replicator, calendar_external_id, now:)
  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.
    # Only update rows not already CANCELLED.
    ds = ds.exclude(Sequel[compound_identity: processor.upserted_identities])
    ds = ds.where(Sequel[status: nil] | ~Sequel[status: "CANCELLED"])
    ds.update(
      status: "CANCELLED",
      data: Sequel.lit('data || \'{"STATUS":{"v":"CANCELLED"}}\'::jsonb'),
      row_updated_at: now,
    )
  end
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



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

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



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

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

#sync_row(row) ⇒ Object



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

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