canvas_sync 0.27.16 → 0.27.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/README.md CHANGED
@@ -9,7 +9,13 @@ Add this line to your application's Gemfile:
9
9
  ```ruby
10
10
  gem 'canvas_sync'
11
11
  ```
12
+
13
+ Mount the engine in your `config/routes.rb` (required for Live Events):
14
+
15
+ ```ruby
12
16
  mount CanvasSync::Engine, at: '/canvas_sync'
17
+ ```
18
+
13
19
  Models and migrations can be installed using the following generator:
14
20
 
15
21
  ```
@@ -26,545 +32,86 @@ bundle exec rake db:migrate
26
32
 
27
33
  For a list of currently supported models, see `CanvasSync::SUPPORTED_MODELS`.
28
34
 
29
- Additionally, your Canvas instance must have the "Proserv Provisioning Report" enabled.
30
-
31
- The following custom reports are required for the specified models:
32
- - assignments = "Assignments Report" (proserv_assignment_export_csv)
33
- - submissions = "Student Submissions" (proserv_student_submissions_csv)
34
- - assignment_groups = "Assignment Group Export" (proserv_assignment_group_export_csv)
35
- - context_modules = "Professional Services Context Modules Report" (proserv_context_modules_csv)
36
- - context_module_items = "Professional Services Context Module Items Report" (proserv_context_module_items_csv)
37
- - content_migrations = "Professional Services Content Migrations Report" (proserv_content_migrations_csv)
38
-
39
- ## Prerequisites
40
-
41
- ### Postgres
42
-
43
- The bulk inserting is made possible by using a Postgres upsert. Beause of this, you need to be using **Postgres 9.5** or above.
44
-
45
- ### Sidekiq
46
-
47
- Make sure you've setup sidekiq to work properly with ActiveJob as [outlined here](https://github.com/mperham/sidekiq/wiki/Active-Job).
48
-
49
- ### Apartment
50
-
51
- If using apartment and sidekiq make sure you include the [apartment-sidekiq](https://github.com/influitive/apartment-sidekiq) gem so that the jobs are run in the correct tenant.
52
-
53
- ### Live Events
54
- if enabling Live Events, the following additional dependencies are required:
55
- - If using Core/Data Services events: `httparty`, `json-jwt`
56
- - If using EventsManager/DejaVu events: `symmetric-encryption`
57
-
58
- ## Basic Usage
59
-
60
- Your tool must have an `ActiveJob` compatible job queue adapter configured, such as DelayedJob or Sidekiq.
61
-
62
- Once that's done and you've used the generator to create your models and migrations you can run the standard provisioning sync:
63
-
64
- ```ruby
65
- CanvasSync.provisioning_sync(<array of models to sync>, term_scope: <optional term scope>)
66
- ```
67
-
68
- *Note: pass in 'xlist' to your array of models if you would like sections to include cross listing information*
69
-
70
- Example:
71
-
72
- ```ruby
73
- CanvasSync.provisioning_sync(['users', 'courses'], term_scope: :active)
74
- ```
75
-
76
- This will kick off a string of jobs to sync your specified models.
77
-
78
- If you pass in the optional `term_scope` the provisioning reports will be run for only the terms returned by that scope. The scope must be defined on your `Term` model. (A sample one is provided in the generated `Term`.)
79
-
80
- Imports are inserted in bulk with [activerecord-import](https://github.com/zdennis/activerecord-import) so they should be very fast.
81
-
82
- ### Live Events
83
-
84
- Ensure that
85
- ```ruby
86
- mount CanvasSync::Engine, at: '/canvas_sync'
87
- ```
88
- is added to your `routes.rb`. Configure `DataServices` or `EventsManager` to send events to `https://YOUR_APP/canvas_sync/api/v1/live_event` (if using `DataServices`, event must be signed).
89
-
90
- Uncomment `include CanvasSync::Concerns::LiveEventSync` and related lines in the appropriate models. (Some models provide some basic hooks to address a "typical" workflow).
91
-
92
- When Live Events are received, the corresponding model (if present) instance will receive `process_live_event(subtype, payload, metadata)` (where `subtype` is the event name w/o the model name - eg `user_created` => `created`). The default logic is to call `ApiSyncable` and update the model from the Canvas API. `process_live_event` can be overridden directly, or hooked with the usual Rails callbacks system (eg `before_process_live_event`).
93
-
94
- You can subscribe to Live Events outside of a model context using an intializer like so:
95
- ```ruby
96
- CanvasSync::LiveEvents.subscribe(%w[Optional List of Events]) do |event|
97
- # Your code here
98
- # Note that this code is _not_ retried if it fails. If you need retries, use this block to trigger another Job.
99
- end
100
- ```
101
-
102
- #### Event Provenance
103
-
104
- When using `EventsManager` events, events are verified as having come from a legitimate source by use of `SymmetricEncryption` (and thus `PRODUCTION_KEY1` will need to be set correctly when deployed).
105
-
106
- When using `DataServices`, CanvasSync uses the `DataServices` JWK to authenticate incoming events. CanvasSync is coded to default to the Prod & Beta JWK URL at https://8axpcl50e4.execute-api.us-east-1.amazonaws.com/main/jwks, but this can be overridden with the `DATASERVICES_JWK_URL` ENV variable.
107
-
108
- Additionally, when `PandaPal` is installed too, use `https://YOUR_APP/canvas_sync/api/v1/live_event?org=ORG_ID` instead. `CanvasSync` will automatically switch to the correct organization and will validate that the event was indeed from the correct Canvas instance. If you are not using `PandaPal`, you'll need to monkey-patch `CanvasSync::Api::V1::LiveEventsController#validate_tenant!`
109
-
110
- #### Legacy-Style Event Jobs
111
-
112
- CanvasSync also supports they legacy style of Event Handlers. In this design, properly-named classes are defined in the `::LiveEvents` module, such as (`class LiveEvents::UserCreatedEvent`). Any `ActiveJob` job is compatible, but CanvasSync also provides `CanvasSync::LiveEvents::BaseHandler` as a helpful base class.
113
-
114
- When present, these jobs will, per event type (eg `user_created`), override the default behavior, meaning that `subscribe` blocks and `process_live_event` and related callbacks will _not_ be called unless you call them. In other words: If you define `class LiveEvents::UserCreatedEvent` and also
115
- ```ruby
116
- subscribe(%w[user_created user_updated]) do |event|
117
- # ...
118
- end
119
- ```
120
- the subscribe block (and User model) will receive `user_updated` events, but not `user_created` events.
121
-
122
- These jobs can also be generated from template using `bin/rails generate canvas_sync:install_live_events --events users,courses,etc`
123
-
124
- ## Advanced Usage
125
-
126
- This gem also helps with syncing and processing other reports if needed. In order to do so, you must:
127
-
128
- - Create a job class that extends `CanvasSync::Jobs::ReportSyncTask`
129
- - Define the report name and implement a `process` method for handling the results
130
- - Optionally override `report_parameters` for custom report parameters
131
-
132
- ### `updated_after`
133
- An `updated_after` param may be passed when triggering a provision or making a chain:
134
- ```ruby
135
- CanvasSync.default_provisioning_report_chain(
136
- %i[list of models to sync], updated_after: false
137
- )
138
- ```
139
- It may be one of the following values:
140
- * `false` - Will not apply any `updated_after` filtering to the requested reports
141
- * An ISO-8601 Date - Will pass the supplied date ad the `updated_after` param for the requested reports
142
- * `true` (Default) - Will use the start date of the last successful sync
143
-
144
- If `updated_after` is true, CanvasSync will, by default, perform a full sync every other Sunday.
145
- This logic can be customized by passing `full_sync_every` parameter.
146
- If you pass a date to `updated_after`, this logic will be disabled unless you explicitly pass a `full_sync_every` parameter.
147
- `full_sync_every` accepts the following format strings:
148
- - `15%` - Each sync will have a 15% chance of running a full sync
149
- - `10 days` - A full sync will be run every 10 days
150
- - `sunday` - A full sync will run every Sunday
151
- - `saturday/4` - A full sync will run every fourth Saturday
152
-
153
- #### Multiple Sync Chains
154
- If your app uses multiple Sync Chains, you may run into issues with the automatic `updated_after` and `full_sync_every` logic.
155
- You can fix this by using custom logic or by setting the `batch_genre` parameter when creating the Job Chain. Chains will only
156
- use chains of the same genre when computing `updated_after` and `full_sync_every`.
157
-
158
- ### Extensible chain
159
- It is sometimes desired to extend or customize the chain of jobs that are run with CanvasSync.
160
- This can be achieved with the following pattern:
161
-
162
- ```ruby
163
- chain = CanvasSync.default_provisioning_report_chain(
164
- %i[list of models to sync]
165
- )
166
-
167
- # Add a custom job to the end of the chain.
168
- chain << { job: CanvasSyncCompleteWorker, args: [job.id], kwargs: { job_id: job.id } }
169
-
170
- chain.process!
171
-
172
- # The chain object provides a fairly extensive API:
173
- chain.insert({ job: SomeOtherJob, args: [], kwargs: {} }) # Adds the job to the end of the chain
174
- chain.insert_at(0, { job: SomeOtherJob }) # Adds the job to the beginning of the chain
175
- chain.insert({ job: SomeOtherJob }, after: 'CanvasSync::Jobs::SyncTermsJob') # Adds the job right after the SyncTermsJob
176
- chain.insert({ job: SomeOtherJob }, before: 'CanvasSync::Jobs::SyncTermsJob') # Adds the job right before the SyncTermsJob
177
- chain.insert({ job: SomeOtherJob }, with: 'CanvasSync::Jobs::SyncTermsJob') # Adds the job to be performed concurrently with the SyncTermsJob
178
-
179
- # Some Jobs (such as the SyncTermsJob) have a sub-chain for, eg, Courses.
180
- # chain.insert is aware of these sub-chains and will recurse into them when looking for a before:/after:/with: reference
181
- chain.insert({ job: SomeOtherJob }, after: 'CanvasSync::Jobs::SyncCoursesJob') # Adds the job to be performed after SyncCoursesJob (which is a sub-job of the terms job and is duplicated for each term in the term_scope:)
182
- # You can also retrieve the sub-chain like so:
183
- chain.get_sub_chain('CanvasSync::Jobs::SyncTermsJob')
184
- ```
185
-
186
- ### Custom Report Sync Jobs
187
-
188
- To create a custom report sync job, extend `CanvasSync::Jobs::ReportSyncTask` and define your report. The gem automatically handles:
189
- - Starting the Canvas report
190
- - Polling for completion
191
- - Downloading the report file
192
- - Error handling and retries
193
- - Timeout management
194
-
195
- Let's say we have a custom Canvas report called "my_really_cool_report_csv". Here's how to create a sync job:
196
-
197
- ```ruby
198
- class MyReallyCoolReportJob < CanvasSync::Jobs::ReportSyncTask
199
- # Define the Canvas report name
200
- report_name "my_really_cool_report_csv"
201
-
202
- # Optional: Override report parameters
203
- def report_parameters
204
- super.merge(
205
- "course_ids" => [1,2,3],
206
- "param2" => "value"
207
- )
208
- end
209
-
210
- # Implement the process method to handle the downloaded report
211
- def process(file)
212
- # file is the path to the downloaded report
213
- puts "I downloaded a report to #{file}! Isn't that neat!"
214
- # Add your processing logic here, e.g.:
215
- # do_bulk_import(file, MyModel)
216
- end
217
- end
218
- ```
219
-
220
- #### Examples
221
-
222
- For simple CSV reports (single model):
223
- ```ruby
224
- class SyncRubricAssessmentsJob < CanvasSync::Jobs::ReportSyncTask
225
- report_name "rubric_assessments_csv"
226
-
227
- def process(file)
228
- do_bulk_import(file, RubricAssessment)
229
- end
230
- end
231
- ```
232
-
233
- For ZIP reports (multiple models like provisioning reports):
234
- ```ruby
235
- class SyncProvisioningReportJob < CanvasSync::Jobs::ReportSyncTask
236
- report_name "provisioning_csv"
237
-
238
- def report_parameters
239
- ...
240
- end
241
-
242
- def process(file)
243
- # Handle ZIP extraction and process each model
244
- # See lib/canvas_sync/jobs/sync_provisioning_report_job.rb for full example
245
- end
246
- end
247
- ```
248
-
249
- You can also see more examples in:
250
- - `lib/canvas_sync/jobs/sync_provisioning_report_job.rb` (ZIP report with multiple models)
251
- - `lib/canvas_sync/jobs/sync_rubric_assessments_job.rb` (Simple CSV report)
252
- - `lib/canvas_sync/jobs/sync_course_progresses_job.rb` (Simple CSV report)
253
-
254
- ### Batching
255
-
256
- The provisioning report uses the `CanvasSync::Importers::BulkImporter` class to bulk import rows with the activerecord-import gem. It inserts rows in batches of 10,000 by default. This can be customized by setting the `BULK_IMPORTER_BATCH_SIZE` environment variable.
257
-
258
- ### Mapping Overrides
259
-
260
- Overrides are useful for two scenarios:
261
-
262
- - You have an existing application where the column names do not match up with what CanvasSync expects
263
- - You want to sync some other column in the report that CanvasSync is not configured to sync
264
-
265
- Mappings can be modified by editing the Model class like such:
266
- ```ruby
267
- class User < ApplicationRecord
268
- include CanvasSync::Record
269
-
270
- sync_mapping(reset: false) do # `reset: false` is the default
271
- # The mapping can be totally cleared with `reset: true` in the `sync_mapping` call, or like such:
272
- reset_links
273
-
274
- # Add a new column:
275
- link_column :column_in_report => :column_in_database, type: :datetime
276
-
277
- # If the column name on the report and in the DB are the same, a shorthand can be used:
278
- link_column :omit_from_final_grade, type: :datetime
279
-
280
- # You can specify a block to pre-transform the value
281
- link_column :column_in_report => :column_in_database do |value, row|
282
- YAML.parse(value)
283
- end
284
-
285
- # If the defaults define a column you don't want synced, you can remove it from the mapping:
286
- unlink_column :column_in_database
287
- end
288
-
289
- # ...
290
- end
291
- ```
292
-
293
- You can also create a file called `canvas_sync_provisioning_mapping.yml` in your Rails `config` directory. However, this approach requires you to re-specify the complete table in order to modify a table. Define the tables and columns you want to override using the following format:
294
-
295
- ```ruby
296
- users:
297
- conflict_target: canvas_user_id # This must be a unique field that is present in the report and the database
298
- report_columns: # The keys specified here are the column names in the report CSV
299
- canvas_user_id_column_name_in_report:
300
- database_column_name: canvas_user_id_name_in_your_db # Sometimes the database column name might not match the report column name
301
- type: integer
302
- ```
303
-
304
- ### API Sync
305
- Several models implement the `ApiSyncable` Concern. This is done in the Model Templates so as to be customizable and tweakable.
306
- Models that `include CanvasSync::Concerns::ApiSyncable` should also call the `api_syncable` class method to configure the Synchronization.
307
- `api_syncable` takes two arguments and an optional block callback:
308
- ```ruby
309
- class CanvasSyncModel < ApplicationRecord
310
- api_syncable(
311
- {
312
- local_field: :response_field, # api_response[:response_field] will be mapped to local_field on the model.
313
- local_field: -> (api_response) { api_response[:some_field] + 5 }, # A calculated result will be mapped to local_field on the model. The lambda is executed in the context of the model instance.
314
- },
315
- -> (bearcat) { bearcat.some_request(some_model_getter) }, # A lambda, executed in the context of the model instance, to actually make the API call. Should accept 0 or 1 parameters. Must accept 0 parameters if your `canvas_sync_client` requires an `account_id`
316
- { # An optional options Hash
317
- mark_deleted: { workflow_state: 'deleted' }, # Action to take when a 404 is received from the API. May be a Hash that will be merged into the Model, A Symbol that should be sent to the model, or a lambda (both taking 0 arguments)
318
- }
319
- ) do |api_response, mapped_fields| # Must accept 1-2 parameters
320
- # Override behavior for actually applying the response to the model instance
321
- end
322
-
323
- def something()
324
- # ApiSyncable models add several instance methods:
325
-
326
- request_from_api( # Starts an API request and and returns the params
327
- retries: 3, # Number of times to retry the API call before failing
328
- )
329
-
330
- update_from_api_params(params) # Merge the API response into the model instance
331
- update_from_api_params!(params) # Merge and save! if changed
332
-
333
- sync_from_api( # Starts an API request and calls save! (if changed)
334
- retries: 3, # Number of times to retry the API call before failing
335
- )
336
- end
337
- end
338
- ```
35
+ ### Required Canvas reports
339
36
 
340
- ### AbilityHelper + JIT Sync
341
- `CanvasSync` includes the `CanvasSync::Concerns::AbilityHelper` Concern. It provides helper methods to access `User` `Role`s and permissions, as well as to map LTI launch parameters to `CanvasSync`-synced records. (See the Concern for all available methods).
37
+ Most models are synced from Canvas custom reports, which must be enabled on your Canvas instance. The "Proserv Provisioning Report" (`proservices_provisioning_csv`) is always required. Other models need their own reports:
342
38
 
343
- The built-in implementation assumes the use of `PandaPal` and our the CustomDev-typical launch_param naming:
344
- - `custom_canvas_user_id`
345
- - `custom_canvas_course_id`
346
- - `custom_canvas_account_id`
39
+ | Model(s) | Report |
40
+ |---|---|
41
+ | `assignments` | Assignments Report (`proserv_assignment_export_csv`) |
42
+ | `assignment_groups` | Assignment Group Export (`proserv_assignment_group_export_csv`) |
43
+ | `assignment_overrides` | Assignment Overrides Export (`proserv_assignment_overrides_csv`) |
44
+ | `submissions` | Student Submissions (`proserv_student_submissions_csv`) |
45
+ | `scores` | Professional Services Scores Data Report (`proserv_scores_data_csv`) |
46
+ | `course_progresses` | Student Course Completion Dates (`proserv_course_completion_csv`) |
47
+ | `context_modules` | Professional Services Context Modules Report (`proserv_context_modules_csv`) |
48
+ | `context_module_items` | Professional Services Context Module Items Report (`proserv_context_module_items_csv`) |
49
+ | `content_migrations` | Professional Services Content Migrations Report (`proserv_content_migrations_csv`) |
50
+ | `rubrics` | Rubrics Export Report (`rubrics_csv`) |
51
+ | `rubric_associations` | Rubrics Associations Export Report (`rubric_associations_csv`) |
52
+ | `rubric_assessments` | Rubrics Assessments Export Report (`rubric_assessments_csv`) |
347
53
 
348
- Additionally, if and `_id` is present but the record can't be found, CanvasSync will attempt to perform Just-in-Time syncing via the Canvas API and `api_syncable`.
54
+ This table can drift. The source of truth is `CanvasSync::ReportsMap`, and you can print the reports your app needs (based on the models and jobs it uses) with:
349
55
 
350
- If you need to sync some extra data after the sync of the record itself (eg the Sections w/i a Course), a callback is provided:
351
- ```ruby
352
- after_jit_sync do
353
- sections_response = canvas_sync_client.course_sections(canvas_id)
354
- Section.bulk_sync_from_api_result(sections_response)
355
- end
356
56
  ```
357
-
358
- `before_jit_sync` is provided as well, but it's use case in niche. It can `throw :jit_found, record` to abort the rest of the JIT process and instead return a specific record. Again, should be quite niche.
359
-
360
- ### UserViaPseudonym
361
-
362
- CanvasSync provides the `CanvasSync::Concerns::UserViaPseudonym` concern for models that need to associate with Canvas users through their pseudonym (login) records. This is particularly useful so that records will always be linked to the correct user, regardless of whether users are merged in Canvas.
363
-
364
- #### Basic Usage
365
-
366
- Include the concern in your model and use the `belongs_to_user` class method:
367
-
368
- ```ruby
369
- class MyModel < ApplicationRecord
370
- include CanvasSync::Concerns::UserViaPseudonym
371
-
372
- # Associate with user using Canvas ID
373
- belongs_to_user :teacher
374
-
375
- # Or associate using SIS ID
376
- belongs_to_user :student, using_sis_id: true
377
- end
378
- ```
379
-
380
- This translates largely into:
381
- ```ruby
382
- belongs_to :teacher_pseudonym, class_name: "Pseudonym"
383
- has_one :teacher, through: :pseudonym, class_name: "User"
384
-
385
- def user=(u)
386
- self.pseudonym = u.pseudonyms.active.last || u.pseudonyms.last
387
- end
57
+ bundle exec rake canvas_sync:reports
388
58
  ```
389
59
 
390
- #### Cached User IDs (Performance Optimization)
60
+ When PandaPal is installed, this list also prints at the end of the interactive `org:install`.
391
61
 
392
- For better performance, you can add a cached user ID column to your table. This eliminates the need for joins when you just need the user ID:
393
-
394
- ```ruby
395
- # In your migration:
396
- add_column :my_models, :cached_teacher_user_id, :bigint
397
- add_index :my_models, :cached_teacher_user_id
398
-
399
- # In your model:
400
- class MyModel < ApplicationRecord
401
- include CanvasSync::Concerns::UserViaPseudonym
402
-
403
- belongs_to_user :teacher, cache_column: :cached_teacher_user_id
404
- end
405
- ```
406
-
407
- ##### Refreshing Cached User IDs
408
-
409
- When using cached columns, you can refresh them in bulk:
410
-
411
- ```ruby
412
- # Refresh all records
413
- MyModel.update_cached_user_ids!
414
-
415
- # Or refresh specific records
416
- MyModel.where(some_condition: true).update_cached_user_ids!
417
- ```
418
-
419
- CanvasSync will also do this automatically after syncing.
420
-
421
-
422
- ### Job Batching
423
- CanvasSync adds a `CanvasSync::JobBatches` module. It adds Sidekiq/sidekiq-batch like support for Job Batches.
424
- It integrates automatically with both Sidekiq and ActiveJob. The API is highly similar to the Sidekiq-batch implementation,
425
- documentation for which can be found at https://github.com/mperham/sidekiq/wiki/Batches
426
-
427
- A batch can be created using `Sidekiq::Batch` or `CanvasSync::JobBatching::Batch`.
428
-
429
- Also see `canvas_sync/jobs/begin_sync_chain_job`, `canvas_sync/Job_batches/jobs/serial_batch_job`, or `canvas_sync/Job_batches/jobs/concurrent_batch_job` for example usage.
430
-
431
- Example:
432
- ```ruby
433
- batch = CanvasSync::JobBatches::Batch.new
434
- batch.description = "Some Batch" # Optional, but can be useful for debugging
435
-
436
- batch.on(:complete, "SomeClass.on_complete", kw_param: 1)
437
- batch.on(:success, "SomeClass.on_success", some_param: 'foo')
62
+ ## Prerequisites
438
63
 
439
- # Add context to the batch. Can be accessed as batch_context on any jobs within the batch.
440
- # Nested Batches will have their contexts merged
441
- batch.context = {
442
- some_value: 'blah',
443
- }
64
+ ### Ruby and Rails
444
65
 
445
- batch.jobs do
446
- # Enqueue jobs like normal
447
- end
448
- ```
449
-
450
- #### Job Pools
451
- A job pool is like a custom Sidekiq Queue. You can add jobs to it and it will empty itself out into one of the actual queues.
452
- However, it adds some options for tweaking the logic:
453
- - `concurrency` (default: `nil`) - Define how many jobs from the pool can run at once.
454
- - `order` (default: `fifo`) - Define how the pool will empty itself
455
- - `fifo` - First-In First-Out, a traditional queue
456
- - `lifo` - Last-In First-Out
457
- - `random` - Pluck and run jobs in random order
458
- - `priority` - Execute jobs in a priority order (NB: Due to Redis, this priority-random, meaning that items with the same priority will be run in random order, not fifo)
459
- - `clean_when_empty` (default: `true`) - Automatically clean the pool when it is empty
460
- - `on_failed_job` (default `:wait`) - If a Job fails, should the pool `:continue` and still enqueue the next job or `:wait` for the job to succeed
461
-
462
- Example:
463
- ```ruby
464
- pool = CanvasSync::JobBatches::Pool.new(concurrency: 4, order: :priority, clean_when_empty: false)
465
- pool_id = pool.pid
466
-
467
- # Add a job to the pool
468
- pool << {
469
- job: SomeJob, # The Class of a ActiveJob Job or Sidekiq Worker
470
- args: [1, 2, 3], # Array of params to pass th e Job
471
- kwargs: {},
472
- priority: 100, # Only effective if order=:priority, higher is higher
473
- }
474
-
475
- # Add many jobs to the pool
476
- pool.add_jobs([
477
- {
478
- job: SomeJob, # The Class of a ActiveJob Job or Sidekiq Worker
479
- args: [1, 2, 3], # Array of params to pass th e Job
480
- kwargs: {},
481
- priority: 100, # Only effective if order=:priority, higher is higher
482
- },
483
- # ...
484
- ])
485
-
486
- # ...Later
487
- CanvasSync::JobBatches::Pool.from_pid(pool_id).cleanup_redis
488
- ```
66
+ CanvasSync is tested against Rails 5.2 through 8.1. The current target is Ruby 3.4 / Rails 8.1.
489
67
 
490
- ### Custom Bearcat Instance
491
- You can define a global `canvas_sync_client` method to return a Bearcat Client instance for CanvasSync to use:
492
- ```ruby
493
- # config/initializers/canvas_sync.rb
494
- def canvas_sync_client
495
- Bearcat::Client.new(token: current_organization.settings[:api_token], prefix: current_organization.settings[:base_url])
496
- end
497
- ```
68
+ ### Postgres
498
69
 
499
- (Having the client defined here means the sensitive API token doesn't have to be passed in plain text between jobs.)
70
+ The bulk inserting is made possible by using a Postgres upsert, so you need **Postgres 9.5** or above. CI runs against Postgres 18.
500
71
 
501
- This used to be required, but when both CanvasSync and PandaPal are up to date, this is defined automagically.
72
+ ### Redis
502
73
 
74
+ Job orchestration (via [Joblin](doc/joblin.md)), `updated_after` tracking, and report caching use Redis. Both CanvasSync and Joblin read `BEARCAT_REDIS_URL`, falling back to `REDIS_URL`.
503
75
 
504
- ## Legacy Support
76
+ ### Sidekiq
505
77
 
506
- ### Legacy Mappings
78
+ Make sure you've setup sidekiq to work properly with ActiveJob as [outlined here](https://github.com/sidekiq/sidekiq/wiki/Active-Job).
507
79
 
508
- CanvasSync 0.10.0+, by default, changes Canvas primary-keys from `:canvas_MODEL_id` to just `:canvas_id`.
509
- Because CanvasSync primarily consists of templates, this change shouldn't require any large changes in your app, but you will need to
510
- apply the `model_mappings_legacy.yml` (located in the root of this repo) to your model mappings - see [Mapping Overrides](#mapping-overrides).
80
+ ### Apartment
511
81
 
512
- ### Row-by-Row Syncing
82
+ If using apartment and sidekiq make sure you include the [apartment-sidekiq](https://github.com/influitive/apartment-sidekiq) gem so that the jobs are run in the correct tenant.
513
83
 
514
- If you have an old style tool that needs to sync data on a row by row basis, you can pass in the `legacy_support: true` option. In order for this to work, your models must have a `create_or_update_from_csv` class method defined that accepts a row argument. This method will get passed each row from the CSV, and it's up to you to persist it.
84
+ ### Live Events
515
85
 
516
- Example:
86
+ Live Events need a few extra gems. See [Live Events](doc/live-events.md#dependencies).
517
87
 
518
- ```ruby
519
- CanvasSync.provisioning_sync(['users', 'courses'], term_scope: :active, legacy_support: true)
520
- ```
88
+ ## Quick start
521
89
 
522
- You may also provide an array of model names. Doing so will only provide legacy support for the specified models.
90
+ Your tool needs an `ActiveJob` queue adapter, such as Sidekiq. Once you've generated your models and run the migrations, start a provisioning sync:
523
91
 
524
92
  ```ruby
525
- CanvasSync.provisioning_sync(['users', 'courses'], term_scope: :active, legacy_support: ['courses'])
526
- ```
527
-
528
- In the above example, users will sync normally while courses will require a `create_or_update_from_csv` method.
529
-
530
- ## CanvasSync::JobLog
531
-
532
- Running the migrations will create a `canvas_sync_job_logs` table. All the jobs written in this gem will create a `CanvasSync::JobLog` and store data about their arguments, job class, any exceptions, and start/completion time. This will work regardless of your queue adapter.
533
-
534
- If you want your own jobs to also log to the table all you have to do is have your job class inherit from `CanvasSync::Job`. You can also persist extra data you might need later by saving to the `metadata` column:
535
-
536
- ```
537
- @job_log.metadata = "This job ran really well!"
538
- @job_log.save!
93
+ CanvasSync.provisioning_sync(['users', 'courses'], term_scope: :active)
539
94
  ```
540
95
 
541
- If you want to be able to utilize the `CanvasSync::JobLog` without `ActiveJob` (so you can get access to `Sidekiq` features that `ActiveJob` doesn't support), then add the following to an initializer in your Rails app:
96
+ This kicks off a chain of jobs that pulls the Canvas reports for those models and bulk-upserts them with [activerecord-import](https://github.com/zdennis/activerecord-import). See [Provisioning sync](doc/provisioning-sync.md) for the options.
542
97
 
543
- ```ruby
544
- Sidekiq.configure_server do |config|
545
- config.server_middleware do |chain|
546
- chain.add CanvasSync::Sidekiq::Middleware
547
- end
548
- end
549
- ```
98
+ ## Features
550
99
 
551
- ## Syncronize different reports
552
- CanvasSync provides the functionality to import data from other reports into an specific table.
100
+ Start with [Architecture](doc/architecture.md) for how data moves from Canvas into your database.
553
101
 
554
- This can be achieved by using the following method
555
-
556
- ```ruby
557
- chain = CanvasSync.default_provisioning_report_chain
558
- chain << {
559
- job: CanvasSync::Jobs::SyncSimpleTableJob,
560
- options: {
561
- report_name: <report name>,
562
- model: <model to sync>,
563
- params: <hash with the require parameters the report needs to sync>
564
- },
565
- }
566
- chain.process!
567
- ```
102
+ | Feature | What it does |
103
+ |---|---|
104
+ | [Provisioning sync](doc/provisioning-sync.md) | Syncs the models you pick, with term scoping, `updated_after` delta syncs, scheduled full syncs, [custom jobs](doc/provisioning-sync.md#adding-custom-jobs), chain options, and failure handling. |
105
+ | [Custom report syncs](doc/custom-reports.md) | Runs any Canvas report through `ReportSyncTask` (start, poll, download, retry, and import), with optional report caching. |
106
+ | [Importing and mapping overrides](doc/importing-and-mappings.md) | Controls bulk imports: batch size, import callbacks, column mappings, `alter_rows`, and legacy row-by-row syncing. |
107
+ | [Live Events](doc/live-events.md) | Receives Canvas Live Events, checks where they came from, and updates models or calls your subscribers. |
108
+ | [API sync](doc/api-sync.md) | Syncs a single record from the Canvas API with `api_syncable`. |
109
+ | [AbilityHelper and JIT sync](doc/ability-helper.md) | Maps LTI launches to synced records, roles, and permissions, and fetches missing records just in time. |
110
+ | [UserViaPseudonym](doc/user-via-pseudonym.md) | Links your models to Canvas users through pseudonyms, so links survive user merges. |
111
+ | [Job orchestration (Joblin)](doc/joblin.md) | Provides batches, pools, job uniqueness, background tasks, and a Sidekiq Web UI. |
112
+ | [Job logs](doc/job-logs.md) | Records each job run in `canvas_sync_job_logs` and cleans up old rows. |
113
+ | [Upgrading](doc/upgrading.md) | Covers re-running generators, schema changes, and fitting CanvasSync into an existing app. |
114
+ | [Development](doc/development.md) | Explains how to run the test suite, release the gem, and build the YARD docs. |
568
115
 
569
116
  ## Configuration
570
117
 
@@ -579,101 +126,19 @@ end
579
126
  Available config options (if you add more, please update this!):
580
127
 
581
128
  * `config.classes_to_only_log_errors_on` - use this if you are utilizing the `CanvasSync::JobLog` table, but want certain classes to only persist in the `job_logs` table if an error is encountered. This is useful if you've got a very frequently used job that's filling up your database, and only really care about tracking failures.
129
+ * `config.redis_key_prefix` (default `"cs"`) - the prefix for the per-Term "last synced" Redis keys used by `updated_after`. With Apartment, the current tenant is prepended automatically.
582
130
 
583
-
584
- ## Job Chain options
585
-
586
- Options can be passed into the job_chain and delivered to specific jobs tied to models.
587
- For example: options { roles: { show_inherited: true } } will pass "show_inherited" into the SyncRolesJob.
588
-
589
- * roles
590
- * `show_inherited` - this applies to the roles model. If it is set to true we will use the "show_inherited" option when pulling roles from Canvas API.
591
- "show_inherited" will include things like shadow records. It will also include roles from parent accounts if you are not syncing at the root account.
592
-
593
- * `global` - See "Global Options"
594
-
595
- ## Global Options
596
- You can pass in global_options to a job chain. Global options are added to the batch_context and referenced by
597
- various internal processes.
598
-
599
- Pass global options into a job chain, using the options param nested in a :global key.
600
- `options: { global: {...} }`
601
-
602
- report_timeout (integer): Number of days until a Canvas report should timeout. Default is 1.
603
- report_compilation_timeout (integer): Number of days until a Canvas report should timeout. Default is 1 hour.
604
- You can likely pass a float to achieve sub-day timeouts, but not tested.
605
- report_max_tries (integer): The number of times to attempt a report before giving up. A report is considered failed
606
- if it has an 'error' status in Canvas or is deleted.
607
-
608
- This is an example job chain with global options:
609
- ```ruby
610
- job_chain = CanvasSync.default_provisioning_report_chain(
611
- MODELS_TO_SYNC,
612
- term_scope: :active,
613
- full_sync_every: 'sunday',
614
- options: { global: { report_timeout: 2 } }
615
- )
616
- ```
617
-
618
- ## Handling Job errors
619
-
620
- If you need custom handling for when a CanvasSync Job fails, you can add an `:on_failure` option to you Job Chain's `:global_options`.
621
- The value should be a String in the following format: `ModuleOrClass::AnotherModuleOrClass.class_method`.
622
- The given method of the given class will be called when an error occurs.
623
- The handling method should accept 2 arguments: `[error, **options]`
624
-
625
- The current parameters provided in `**options` are:
626
- - `job_chain`
627
- - `job_log`
628
-
629
- Example:
131
+ ### Custom Bearcat instance
132
+ You can define a global `canvas_sync_client` method to return a Bearcat Client instance for CanvasSync to use:
630
133
  ```ruby
631
- class CanvasSyncStarterWorker
632
- def perform
633
- job_chain = CanvasSync.default_provisioning_report_chain(
634
- %w[desired models],
635
- options: {
636
- global: {
637
- on_failure: 'CanvasSyncStarterWorker.handle_canvas_sync_error',
638
- }
639
- }
640
- )
641
- end
642
-
643
- def self.handle_canvas_sync_error(error, **options)
644
- # Do Stuff
645
- end
134
+ # config/initializers/canvas_sync.rb
135
+ def canvas_sync_client
136
+ Bearcat::Client.new(token: current_organization.settings[:api_token], prefix: current_organization.settings[:base_url])
646
137
  end
647
138
  ```
648
139
 
649
- ## Upgrading
650
-
651
- Re-running the generator when there's been a gem change will give you several choices if it detects conflicts between your local files and the updated generators. You can either view a diff or allow the generator to overwrite your local file. In most cases you may just want to add the code from the diff yourself so as not to break any of your customizations.
652
-
653
- Additionally, if there have been schema changes to an existing model you may have to run your own migration to bring it up to speed.
654
-
655
- Also see `CHANGELOG.md`.
656
-
657
- If you make updates to the gem please add any upgrade instructions to `CHANGELOG.md`.
658
-
659
- ## Integrating with existing applications
660
-
661
- In order for this to work properly your database tables will need to have at least the columns defined in this gem. (Adding additional columns is fine.) As such, you may need to run some migrations to rename existing columns or add missing ones. The generator only works well in a situation where that table does not already exist. Take a look at the migration templates in `lib/canvas_sync/generators/templates` to see what you need.
662
-
663
- ## Development
664
-
665
- When adding to or updating this gem, make sure you do the following:
666
-
667
- - Update the yardoc comments where necessary, and confirm the changes by running `yardoc --server`
668
- - Write specs
669
- - If you modify the model or migration templates, run `bundle exec rake update_test_schema` to update them in the Rails Dummy application (and commit those changes)
670
-
671
- ## Docs
672
-
673
- Docs can be generated using [yard](https://yardoc.org/). To view the docs:
140
+ This used to be required, but when both CanvasSync and PandaPal are up to date, this is defined automagically.
674
141
 
675
- - Clone this gem's repository
676
- - `bundle install`
677
- - `yard server --reload`
142
+ ## Changelog
678
143
 
679
- The yard server will give you a URL you can visit to view the docs.
144
+ See [`CHANGELOG.md`](CHANGELOG.md) for major and breaking changes.