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
- CLEANUP_SERVICE_NAMES =
["icalendar_event_v1"].freeze
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
-
#_remote_key_column ⇒ Object
-
#_resource_and_event(request) ⇒ Object
-
#_resource_to_data(resource) ⇒ Object
-
#_retryable_client_error?(e, request_url:) ⇒ Boolean
-
#_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
-
#rows_needing_sync(dataset, now: Time.now) ⇒ Object
-
#sync_row(row) ⇒ 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_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_backfill_error, #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
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.
223
224
225
226
227
228
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 223
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
|
# 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),
]
end
|
#_handle_down_error(e, request_url:, calendar_external_id:) ⇒ Object
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 230
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, 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:)
expected_errors = [
400, 401, 402, 403, 404, 405, 409, 410, 417, 429, ]
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?
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 313
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&.code : 0,
request_url:,
calendar_external_id:,
retry_at: Time.now + retry_in,
)
raise Amigo::Retry::OrDie.new(10, retry_in)
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
87
88
89
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 87
def _resource_and_event(request)
return request.body, nil
end
|
#_resource_to_data(resource) ⇒ Object
102
103
104
105
106
107
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 102
def _resource_to_data(resource, *)
data = resource.dup
data.clear
return data
end
|
#_retryable_client_error?(e, request_url:) ⇒ Boolean
302
303
304
305
306
307
308
309
310
311
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 302
def _retryable_client_error?(e, request_url:)
code = e.response.code.to_i
return false if code == 429 && request_url.start_with?("https://ical.schedulestar.com")
return true if code == 429
return false
end
|
#_sync_row(row, dep, now:) ⇒ Object
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
215
216
217
218
219
220
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 190
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
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
83
84
85
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 83
def _timestamp_column_name
return :row_updated_at
end
|
#_update_where_expr ⇒ Object
91
92
93
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 91
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
95
96
97
98
99
100
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 95
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
137
138
139
140
141
142
143
144
145
146
147
148
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 137
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_url ⇒ Object
#rows_needing_sync(dataset, now: Time.now) ⇒ Object
132
133
134
135
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 132
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 169
def sync_row(row)
Appydays::Loggable.with_log_tags(icalendar_url: row.fetch(:ics_url)) do
self.with_advisory_lock(row.fetch(:pk)) do
start = Time.now
now = Time.now
if (dep = self.find_dependent("icalendar_event_v1"))
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,
)
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
|
# File 'lib/webhookdb/replicator/icalendar_calendar_v1.rb', line 109
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
|