Class: Webhookdb::Replicator::IcalendarCalendarV1
- Inherits:
-
Base
- Object
- Base
- Webhookdb::Replicator::IcalendarCalendarV1
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
Constants inherited
from Base
Base::MAX_INDEX_NAME_LENGTH
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
-
#_clean_ics_url(url) ⇒ Object
We get all sorts of strange urls, fix up what we can.
-
#_denormalized_columns ⇒ Object
-
#_handle_down_error(e, request_url:, calendar_external_id:) ⇒ Object
-
#_handle_retryable_down_error!(e, request_url:, calendar_external_id:) ⇒ Object
-
#_make_ics_request(request_url, last_fetch_context) ⇒ Object
-
#_remote_key_column ⇒ Object
-
#_resource_and_event(request) ⇒ Object
-
#_resource_to_data(resource) ⇒ Object
-
#_retryable_client_error?(e, request_url:) ⇒ Boolean
-
#_safe_read_body(e) ⇒ Object
We can hit an error while reading the error body, since it was opened as a stream.
-
#_sync_row(row, dep, now:) ⇒ Object
-
#_timestamp_column_name ⇒ Object
-
#_update_where_expr ⇒ Object
-
#_upsert_update_expr(inserting, **_kwargs) ⇒ Object
-
#_webhook_response(request) ⇒ Object
-
#calculate_webhook_state_machine ⇒ Object
-
#delete_data_for_external_id(external_id) ⇒ Object
-
#documentation_url ⇒ Object
-
#feed_changed?(row) ⇒ Boolean
Return true if the data in the feed has changed from what was last synced, or false if it has not so the sync can be skipped.
-
#rows_needing_sync(dataset, now: Time.now) ⇒ Object
-
#sync_row(row, force: false, now: Time.now) ⇒ Object
-
#upsert_has_deps? ⇒ Boolean
-
#upsert_webhook(request) ⇒ Object
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_conflict_target, #_upsert_webhook, #_upsert_webhook_single_resource, #_verify_backfill_err_msg, #_webhook_state_change_fields, #admin_dataset, #avoid_writes?, #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, #create_table_partitions, #data_column, #dbadapter_table, #denormalized_columns, #descriptor, #dispatch_request_to, #enqueue_sync_targets, #enrichment_column, #ensure_all_columns, #ensure_all_columns_modification, #existing_partitions, #find_dependent, #find_dependent!, #indices, #initialize, #on_backfill_error, #on_dependency_webhook_upsert, #partition?, #partitioning, #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, #with_advisory_lock
Class Method Details
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.
272
273
274
275
276
277
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 272
def _clean_ics_url(url)
u = URI(url)
u.port = 443 if u.scheme == "https" && u.port == 80
return u.to_s
end
|
#_denormalized_columns ⇒ Object
70
71
72
73
74
75
76
77
78
79
80
81
82
|
# 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")),
col.new(:event_count, INTEGER, optional: true),
col.new(:feed_bytes, INTEGER, optional: true),
col.new(:last_sync_duration_ms, INTEGER, optional: true),
col.new(:last_fetch_context, OBJECT, optional: true),
]
end
|
#_handle_down_error(e, request_url:, calendar_external_id:) ⇒ Object
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 279
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
self.logger.info("icalendar_fetch_not_modified", response_status: 304, request_url:, calendar_external_id:)
return
when Down::SSLError
is_fatal =
e.to_s.include?("unsafe legacy renegotiation disabled") ||
e.to_s.include?("certificate verify failed")
if is_fatal
response_status = 0
response_body = e.to_s
else
self._handle_retryable_down_error!(e, request_url:, calendar_external_id:)
end
when Down::TimeoutError, Down::ConnectionError, Down::InvalidUrl,
Errno::ECONNRESET,
URI::InvalidURIError,
HTTPX::NativeResolveError, HTTPX::InsecureRedirectError,
HTTPX::Connection::HTTP2::Error,
EOFError
response_status = 0
response_body = e.to_s
when Down::ClientError
raise e if e.response.nil?
response_status = e.response.status.to_i
self._handle_retryable_down_error!(e, request_url:, calendar_external_id:) if
self._retryable_client_error?(e, request_url:)
expected_errors = [
400, 401, 402, 403, 404, 405, 409, 410, 417, 422, 429, 500, 503, 504, 599, ]
if response_status == 421 && (origin_err = e.response.["Ical-Proxy-Origin-Error"])
response_status = origin_err.to_i
end
raise e unless expected_errors.include?(response_status)
response_body = self._safe_read_body(e)
when Down::ServerError
response_status = e.response.status.to_i
response_body = self._safe_read_body(e)
else
response_body = nil
response_status = nil
end
raise e if response_status.nil?
loggable_body = response_body && response_body[..256]
self.logger.warn("icalendar_fetch_error",
response_body: loggable_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, separate_connection: false)
end
|
#_handle_retryable_down_error!(e, request_url:, calendar_external_id:) ⇒ Object
381
382
383
384
385
386
387
388
389
390
391
392
393
394
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 381
def _handle_retryable_down_error!(e, request_url:, calendar_external_id:)
retry_in = rand(4..60).minutes
self.logger.debug(
"icalendar_fetch_error_retry",
response_status: e.respond_to?(:response) ? e.response&.status : 0,
request_url:,
calendar_external_id:,
retry_at: Time.now + retry_in,
)
raise Amigo::Retry::OrDie.new(10, retry_in)
end
|
#_make_ics_request(request_url, last_fetch_context) ⇒ Object
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 253
def _make_ics_request(request_url, last_fetch_context)
= {
"Accept" => "text/calendar,*/*",
}
["If-None-Match"] = last_fetch_context["etag"] if last_fetch_context & ["etag"]
if (proxy_url = Webhookdb::Icalendar.proxy_url).present?
request_url = "#{proxy_url.delete_suffix('/')}/?url=#{URI.encode_www_form_component(request_url)}"
["Authorization"] = "Apikey #{Webhookdb::Icalendar.proxy_api_key}" if
Webhookdb::Icalendar.proxy_api_key.present?
end
resp = Webhookdb::Http.chunked_download(request_url, rewindable: false, headers:)
return resp
end
|
#_remote_key_column ⇒ Object
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
88
89
90
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 88
def _resource_and_event(request)
return request.body, nil
end
|
#_resource_to_data(resource) ⇒ Object
103
104
105
106
107
108
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 103
def _resource_to_data(resource, *)
data = resource.dup
data.clear
return data
end
|
#_retryable_client_error?(e, request_url:) ⇒ Boolean
370
371
372
373
374
375
376
377
378
379
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 370
def _retryable_client_error?(e, request_url:)
code = e.response.status.to_i
return false if code == 429 && request_url.start_with?("https://ical.schedulestar.com")
return true if code == 429
return false
end
|
#_safe_read_body(e) ⇒ Object
We can hit an error while reading the error body, since it was opened as a stream. Ignore those errors.
364
365
366
367
368
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 364
def _safe_read_body(e)
return e.response.body.to_s
rescue OpenSSL::SSL::SSLError, HTTPX::Error
return "<error reading body>"
end
|
#_sync_row(row, dep, now:) ⇒ Object
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
242
243
244
245
246
247
248
249
250
251
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 216
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 = self._make_ics_request(request_url, row.fetch(:last_fetch_context))
rescue Down::Error,
URI::InvalidURIError,
HTTPX::NativeResolveError,
HTTPX::InsecureRedirectError,
HTTPX::Connection::HTTP2::Error,
EOFError => 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:, headers: io.data[:headers])
processor.process
dep.replicator.admin_dataset do |ds|
ds = ds.where(calendar_external_id:)
if (delete_condition = processor.delete_condition)
ds.where(delete_condition).delete
end
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
return processor
end
|
#_timestamp_column_name ⇒ Object
84
85
86
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 84
def _timestamp_column_name
return :row_updated_at
end
|
#_update_where_expr ⇒ Object
92
93
94
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 92
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
96
97
98
99
100
101
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 96
def _upsert_update_expr(inserting, **_kwargs)
update = super
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_machine ⇒ Object
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
136
137
138
139
140
141
142
143
144
145
146
147
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 136
def delete_data_for_external_id(external_id)
relevant_integrations = self.service_integration.recursive_dependents.
filter { |d| Webhookdb::Icalendar::EVENT_REPLICATORS.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_url ⇒ Object
#feed_changed?(row) ⇒ Boolean
Return true if the data in the feed has changed from what was last synced, or false if it has not so the sync can be skipped. This operation is meant to be resource-light (most of the work is the HTTP request), so should be done in a threadpool.
-
If we have no previous fetch context, we sync.
-
If the fetch errors, sync, because we want the normal error handler to figure it out (alert admins, etc).
-
If the last fetch’s content type and length is different from the current, we sync.
-
Download the bytes. If the hash of the bytes is different from what was last processed, sync. Since this involves reading the streaming body, we must return a copy of the body (a StringIO).
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 688
def feed_changed?(row)
last_fetch = row.fetch(:last_fetch_context)
return true if last_fetch.nil? || last_fetch.empty?
begin
url = self._clean_ics_url(row.fetch(:ics_url))
resp = self._make_ics_request(url, last_fetch)
rescue Down::NotModified
return false
rescue StandardError
return true
end
= resp.data[:headers] || {}
content_type_match = ["Content-Type"] == last_fetch["content_type"] &&
["Content-Length"] == last_fetch["content_length"]
return true unless content_type_match
last_hash = last_fetch["hash"]
return true if last_hash.nil?
hash = Digest::MD5.new
while (line = resp.gets)
hash.update(line)
end
return hash.hexdigest != last_hash
end
|
#rows_needing_sync(dataset, now: Time.now) ⇒ Object
131
132
133
134
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 131
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, force: false, now: Time.now) ⇒ Object
168
169
170
171
172
173
174
175
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
203
204
205
206
207
208
209
210
211
212
213
214
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 168
def sync_row(row, force: false, now: Time.now)
Appydays::Loggable.with_log_tags(icalendar_url: row.fetch(:ics_url)) do
last_synced_at = row.fetch(:last_synced_at)
should_sync = force ||
last_synced_at.nil? ||
Webhookdb::Icalendar.proxy_url.present? ||
last_synced_at < (now - Webhookdb::Icalendar.sync_period_hours.hours)
unless should_sync
self.logger.info("skip_sync_recently_synced", last_synced_at:)
return
end
self.with_advisory_lock(row.fetch(:pk)) do
start = Time.now
if (dep = self.find_dependent(Webhookdb::Icalendar::EVENT_REPLICATORS))
if dep.replicator.avoid_writes?
self.logger.info("skip_sync_table_locked")
raise Amigo::Retry::Retry, 60.seconds + (rand * 10.seconds)
end
processor = self._sync_row(row, dep, now:)
end
self.admin_dataset do |ds|
ds.where(pk: row.fetch(:pk)).
update(
last_synced_at: now,
event_count: processor&.upserted_identities&.count,
feed_bytes: processor&.read_bytes,
last_sync_duration_ms: (Time.now - start).in_milliseconds,
last_fetch_context: {
"hash" => processor&.feed_hash,
"content_type" => processor&.&.fetch("Content-Type", nil),
"content_length" => processor&.&.fetch("Content-Length", nil),
"etag" => processor&.&.fetch("Etag", nil),
}.to_json,
)
end
end
end
end
|
#upsert_has_deps? ⇒ Boolean
30
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 30
def upsert_has_deps? = true
|
#upsert_webhook(request) ⇒ Object
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 110
def upsert_webhook(request)
request_type = request.body.fetch("type")
external_id = request.body.fetch("external_id")
case request_type
when "SYNC"
super
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
else
raise ArgumentError, "Unknown request type: #{request_type}"
end
end
|