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.
- checksums.yaml +4 -4
- data/README.md +66 -601
- data/app/controllers/canvas_sync/api/v1/live_events_controller.rb +24 -9
- data/doc/ability-helper.md +37 -0
- data/doc/api-sync.md +36 -0
- data/doc/architecture.md +222 -0
- data/doc/custom-reports.md +106 -0
- data/doc/development.md +29 -0
- data/doc/importing-and-mappings.md +98 -0
- data/doc/job-logs.md +32 -0
- data/doc/joblin.md +72 -0
- data/doc/live-events.md +55 -0
- data/doc/provisioning-sync.md +220 -0
- data/doc/upgrading.md +21 -0
- data/doc/user-via-pseudonym.md +60 -0
- data/lib/canvas_sync/version.rb +1 -1
- data/spec/canvas_sync/live_events/live_events_controller_spec.rb +77 -0
- data/spec/spec_helper.rb +5 -5
- data/spec/support/fake_canvas.rb +2 -0
- metadata +13 -1
|
@@ -1,6 +1,23 @@
|
|
|
1
1
|
module CanvasSync::Api
|
|
2
2
|
module V1
|
|
3
3
|
class LiveEventsController < ActionController::Base
|
|
4
|
+
class InvalidTenant < StandardError; end
|
|
5
|
+
|
|
6
|
+
rescue_from StandardError do |e|
|
|
7
|
+
log_rejection(e)
|
|
8
|
+
render json: { error: "Invalid live event" }, status: 422
|
|
9
|
+
end
|
|
10
|
+
|
|
11
|
+
rescue_from "JSON::JWT::Exception" do |e|
|
|
12
|
+
log_rejection(e)
|
|
13
|
+
render json: { error: "Invalid live event" }, status: 401
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
rescue_from InvalidTenant, ActiveRecord::RecordNotFound do |e|
|
|
17
|
+
log_rejection(e)
|
|
18
|
+
render json: { error: "Invalid Organization/UUID" }, status: 403
|
|
19
|
+
end
|
|
20
|
+
|
|
4
21
|
around_action :switch_tenant
|
|
5
22
|
|
|
6
23
|
def process_event
|
|
@@ -9,9 +26,6 @@ module CanvasSync::Api
|
|
|
9
26
|
else
|
|
10
27
|
process_dataservices_event
|
|
11
28
|
end
|
|
12
|
-
rescue => e
|
|
13
|
-
Rails.logger.error("Live Events Error: #{e.message} - #{e.backtrace}")
|
|
14
|
-
render json: { error: "Live Events Error: #{e.message}" }, status: 422
|
|
15
29
|
end
|
|
16
30
|
|
|
17
31
|
private
|
|
@@ -98,15 +112,16 @@ module CanvasSync::Api
|
|
|
98
112
|
JSON::JWK::Set.new(jwk_json)
|
|
99
113
|
end
|
|
100
114
|
|
|
115
|
+
def log_rejection(error)
|
|
116
|
+
Rails.logger.error("Live Events Error: #{error.class} - #{Array(error.backtrace).first(5)}")
|
|
117
|
+
end
|
|
118
|
+
|
|
101
119
|
def validate_tenant!(event_uuid)
|
|
102
120
|
if defined?(PandaPal)
|
|
103
|
-
|
|
104
|
-
root_uuid = root_info[:uuid]
|
|
121
|
+
raise InvalidTenant if current_organization.nil?
|
|
105
122
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
return
|
|
109
|
-
end
|
|
123
|
+
root_uuid = current_organization.root_account_info[:uuid]
|
|
124
|
+
raise InvalidTenant if root_uuid.blank? || root_uuid != event_uuid
|
|
110
125
|
else
|
|
111
126
|
raise "No way to validate LiveEvent is genuinely from the correct Canvas instance! Monkey-patch CanvasSync::Api::V1::LiveEventsController#validate_tenant!"
|
|
112
127
|
end
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# AbilityHelper and JIT sync
|
|
2
|
+
|
|
3
|
+
`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).
|
|
4
|
+
|
|
5
|
+
The built-in implementation assumes the use of `PandaPal` (>= 5.9.9) and the CustomDev-typical launch_param naming:
|
|
6
|
+
- `custom_canvas_user_id`
|
|
7
|
+
- `custom_canvas_course_id`
|
|
8
|
+
- `custom_canvas_account_id`
|
|
9
|
+
|
|
10
|
+
Commonly used helpers:
|
|
11
|
+
- `user` - the launching `User`
|
|
12
|
+
- `launch_context` - the launch `Course`, `Account`, or `:global` (for Global Navigation launches)
|
|
13
|
+
- `launch_account` - the `Account` of the launch (the Course's Account for Course launches)
|
|
14
|
+
- `canvas_roles`, `canvas_account_roles`, `canvas_course_roles`, `canvas_root_account_roles`, `canvas_permissions`
|
|
15
|
+
- `canvas_account_admin?(account = launch_account)` - true if the user is an Account Admin of `account` **or of any account above it**, matching Canvas. Checking parent accounts needs PandaPal >= 5.17. Older PandaPal versions only check `account` itself.
|
|
16
|
+
- `canvas_super_user?` - `canvas_account_admin?` on the account the tool is installed on
|
|
17
|
+
- `load_canvas_model(Model, canvas_id)` - find a synced record, JIT-syncing it if needed
|
|
18
|
+
|
|
19
|
+
Additionally, if an `_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`.
|
|
20
|
+
|
|
21
|
+
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:
|
|
22
|
+
```ruby
|
|
23
|
+
after_jit_sync do
|
|
24
|
+
sections_response = canvas_sync_client.course_sections(canvas_id)
|
|
25
|
+
Section.bulk_sync_from_api_result(sections_response)
|
|
26
|
+
end
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
After a JIT sync creates a record, CanvasSync publishes an `ActiveSupport::Notifications` event, `record_jit_sync.canvas_sync`, with the new record in its payload. Subscribe to it to react to records that first appear through an LTI launch:
|
|
30
|
+
```ruby
|
|
31
|
+
ActiveSupport::Notifications.subscribe("record_jit_sync.canvas_sync") do |event|
|
|
32
|
+
record = event.payload[:record]
|
|
33
|
+
# ...
|
|
34
|
+
end
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
`before_jit_sync` is provided as well, but its use case is 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.
|
data/doc/api-sync.md
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# API sync
|
|
2
|
+
|
|
3
|
+
Several models implement the `ApiSyncable` Concern. This is done in the Model Templates so as to be customizable and tweakable.
|
|
4
|
+
Models that `include CanvasSync::Concerns::ApiSyncable` should also call the `api_syncable` class method to configure the Synchronization.
|
|
5
|
+
`api_syncable` takes two arguments and an optional block callback:
|
|
6
|
+
```ruby
|
|
7
|
+
class CanvasSyncModel < ApplicationRecord
|
|
8
|
+
api_syncable(
|
|
9
|
+
{
|
|
10
|
+
local_field: :response_field, # api_response[:response_field] will be mapped to local_field on the model.
|
|
11
|
+
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.
|
|
12
|
+
},
|
|
13
|
+
-> (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`
|
|
14
|
+
{ # An optional options Hash
|
|
15
|
+
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)
|
|
16
|
+
}
|
|
17
|
+
) do |api_response, mapped_fields| # Must accept 1-2 parameters
|
|
18
|
+
# Override behavior for actually applying the response to the model instance
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
def something()
|
|
22
|
+
# ApiSyncable models add several instance methods:
|
|
23
|
+
|
|
24
|
+
request_from_api( # Starts an API request and and returns the params
|
|
25
|
+
retries: 3, # Number of times to retry the API call before failing
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
update_from_api_params(params) # Merge the API response into the model instance
|
|
29
|
+
update_from_api_params!(params) # Merge and save! if changed
|
|
30
|
+
|
|
31
|
+
sync_from_api( # Starts an API request and calls save! (if changed)
|
|
32
|
+
retries: 3, # Number of times to retry the API call before failing
|
|
33
|
+
)
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
```
|
data/doc/architecture.md
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
# Architecture
|
|
2
|
+
|
|
3
|
+
CanvasSync is a Rails engine that copies Canvas data into your app's database. Data comes in three ways:
|
|
4
|
+
|
|
5
|
+
1. **Report syncs** (bulk): CanvasSync asks Canvas to build CSV reports, downloads them, and bulk-upserts the rows. This is the main path.
|
|
6
|
+
2. **Live Events** (push): Canvas sends an event when something changes. CanvasSync updates that one record.
|
|
7
|
+
3. **JIT sync** (pull on demand): when an LTI launch refers to a record that isn't in the database yet, CanvasSync fetches it from the Canvas API.
|
|
8
|
+
|
|
9
|
+
All three write to the same models in your app. Job orchestration runs on [Joblin](joblin.md), which keeps its state in Redis.
|
|
10
|
+
|
|
11
|
+
## System overview
|
|
12
|
+
|
|
13
|
+
Arrows show which way data moves. CanvasSync starts every request except Live Events.
|
|
14
|
+
|
|
15
|
+
```mermaid
|
|
16
|
+
flowchart LR
|
|
17
|
+
subgraph Canvas
|
|
18
|
+
RAPI[Reports API]
|
|
19
|
+
LE[Live Events]
|
|
20
|
+
API[REST API]
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
subgraph bulk["1 · Report sync (scheduled)"]
|
|
24
|
+
direction LR
|
|
25
|
+
RST[ReportSyncTask] --> BI[BulkImporter]
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
subgraph push["2 · Live Events (on change)"]
|
|
29
|
+
direction LR
|
|
30
|
+
LEC[LiveEventsController] --> PEJ[ProcessEventJob]
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
subgraph pull["3 · JIT sync (on LTI launch)"]
|
|
34
|
+
JIT[AbilityHelper /<br/>find_or_jit_sync]
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
DB[(Your models<br/>in Postgres)]
|
|
38
|
+
R[(Redis)]
|
|
39
|
+
|
|
40
|
+
RAPI -- CSV reports --> RST
|
|
41
|
+
API -- terms, roles, admins --> bulk
|
|
42
|
+
LE -- signed event --> LEC
|
|
43
|
+
API -- current record --> PEJ
|
|
44
|
+
API -- missing record --> JIT
|
|
45
|
+
|
|
46
|
+
BI -- bulk upsert --> DB
|
|
47
|
+
PEJ -- save --> DB
|
|
48
|
+
JIT -- create --> DB
|
|
49
|
+
|
|
50
|
+
bulk <-. batch state, report cache,<br/>last-sync times .-> R
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Report sync
|
|
54
|
+
|
|
55
|
+
### The chain
|
|
56
|
+
|
|
57
|
+
`CanvasSync.provisioning_sync` (or `default_provisioning_report_chain(...).process!`) builds a tree of jobs and runs it. With `term_scope` set and a typical model list, the tree looks like this:
|
|
58
|
+
|
|
59
|
+
```mermaid
|
|
60
|
+
flowchart TD
|
|
61
|
+
B["BeginSyncChainJob<br/><i>creates SyncBatch, works out updated_after,<br/>opens the root Joblin batch</i>"]
|
|
62
|
+
B --> S["SerialBatchJob (top level, runs in order)"]
|
|
63
|
+
S --> C["ConcurrentBatchJob"]
|
|
64
|
+
S --> U["RefreshUserCachesJob<br/><i>(if syncing pseudonyms)</i>"]
|
|
65
|
+
S --> X["Your jobs added with chain <<"]
|
|
66
|
+
|
|
67
|
+
C --> A["SyncAccountsJob"]
|
|
68
|
+
C --> P1["SyncProvisioningReportJob<br/><i>models not scoped by term:<br/>users, pseudonyms, groups…</i>"]
|
|
69
|
+
C --> RO["SyncRolesJob / SyncAdminsJob<br/><i>(Canvas API)</i>"]
|
|
70
|
+
C --> T["SyncTermsJob<br/><i>syncs Terms from the API</i>"]
|
|
71
|
+
|
|
72
|
+
T --> TB["TermBatchesJob<br/><i>one batch per Term in term_scope,<br/>sets canvas_term_id</i>"]
|
|
73
|
+
TB --> T1["Term A (up to 8 jobs at once)"]
|
|
74
|
+
TB --> T2["Term B …"]
|
|
75
|
+
T1 --> P2["SyncProvisioningReportJob<br/><i>courses, sections, enrollments…</i>"]
|
|
76
|
+
T1 --> O["SyncAssignmentsJob, SyncSubmissionsJob,<br/>SyncContextModulesJob, …"]
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
- `BeginSyncChainJob` creates a `CanvasSync::SyncBatch` row and puts `sync_batch_id`, `batch_start_time`, `batch_genre`, `updated_after`, and any global options in the root batch's context. Every job below it reads them through `batch_context`.
|
|
80
|
+
- When the root batch finishes, the `SyncBatch` is marked `completed` or `failed`. The next run's `updated_after` comes from the last completed `SyncBatch` of the same genre.
|
|
81
|
+
- When each Term's batch succeeds, `TermBatchesJob` saves that Term's sync time in Redis. A Term that hasn't synced recently gets an older `updated_after`, so it catches up.
|
|
82
|
+
- With `term_scope: false`, the per-term step runs once, with no Term filter.
|
|
83
|
+
|
|
84
|
+
See [Provisioning sync](provisioning-sync.md) for the options and for adding your own jobs.
|
|
85
|
+
|
|
86
|
+
### Report lifecycle
|
|
87
|
+
|
|
88
|
+
Every report-based job (`SyncProvisioningReportJob`, `SyncAssignmentsJob`, your own `ReportSyncTask` subclasses) runs the same three-job cycle inside its own Joblin batch:
|
|
89
|
+
|
|
90
|
+
```mermaid
|
|
91
|
+
sequenceDiagram
|
|
92
|
+
participant Chain as Sync chain
|
|
93
|
+
participant Starter as StarterJob
|
|
94
|
+
participant Redis
|
|
95
|
+
participant Canvas as Canvas Reports API
|
|
96
|
+
participant Checker as CheckerJob
|
|
97
|
+
participant Process as ProcessJob
|
|
98
|
+
participant Task as ReportSyncTask#process
|
|
99
|
+
|
|
100
|
+
Chain->>Starter: perform_later(options)
|
|
101
|
+
opt report caching on
|
|
102
|
+
Starter->>Redis: look up cache key
|
|
103
|
+
Redis-->>Starter: cached report_id (if fresh)
|
|
104
|
+
end
|
|
105
|
+
Starter->>Canvas: start_report(account, report_name, report_parameters)
|
|
106
|
+
Canvas-->>Starter: report id
|
|
107
|
+
Starter->>Checker: enqueue (wait check_frequency)
|
|
108
|
+
loop until complete, failed, or timed out
|
|
109
|
+
Checker->>Canvas: report_status
|
|
110
|
+
alt compiling / running
|
|
111
|
+
Checker->>Checker: re-enqueue
|
|
112
|
+
else error / deleted
|
|
113
|
+
Checker->>Redis: drop cache entry (if caching)
|
|
114
|
+
Checker->>Canvas: start_report again (up to report_max_tries)
|
|
115
|
+
end
|
|
116
|
+
end
|
|
117
|
+
Checker->>Process: perform_later(attachment url)
|
|
118
|
+
Process->>Canvas: download file
|
|
119
|
+
Process->>Task: process(file_path)
|
|
120
|
+
Task->>Task: do_bulk_import → BulkImporter
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Timeouts (`report_timeout`, `report_compilation_timeout`) and retries are covered in [Global Options](provisioning-sync.md#global-options). Caching is covered in [Report caching](custom-reports.md#report-caching).
|
|
124
|
+
|
|
125
|
+
### Import pipeline
|
|
126
|
+
|
|
127
|
+
`BulkImporter` streams the CSV and upserts it in batches (10,000 rows by default):
|
|
128
|
+
|
|
129
|
+
```mermaid
|
|
130
|
+
flowchart LR
|
|
131
|
+
CSV[Report CSV] --> F["Row filter block<br/><i>(optional)</i>"]
|
|
132
|
+
F --> AR["alter_rows blocks<br/><i>edit or throw :skip</i>"]
|
|
133
|
+
AR --> M["Column mapping<br/><i>sync_mapping / YAML:<br/>rename, type-cast, transform</i>"]
|
|
134
|
+
M --> D["Drop duplicate rows<br/>(same conflict target)"]
|
|
135
|
+
D --> Bt["Batches of<br/>BULK_IMPORTER_BATCH_SIZE"]
|
|
136
|
+
Bt --> U["Postgres upsert<br/><i>activerecord-import,<br/>ON CONFLICT DO UPDATE</i>"]
|
|
137
|
+
U --> S["Set canvas_synced_at,<br/>canvas_sync_batch_id"]
|
|
138
|
+
|
|
139
|
+
subgraph cb["sync_batch_import callbacks"]
|
|
140
|
+
U
|
|
141
|
+
S
|
|
142
|
+
end
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
- The upsert only updates a row if its values actually changed, and only if the row wasn't already updated after the report started. This keeps `updated_at` meaningful and stops an old report from overwriting newer data from a Live Event.
|
|
146
|
+
- The whole import of one model runs inside the `sync_import` callbacks. Each batch runs inside `sync_batch_import`.
|
|
147
|
+
|
|
148
|
+
See [Importing and mapping overrides](importing-and-mappings.md).
|
|
149
|
+
|
|
150
|
+
## Live Events
|
|
151
|
+
|
|
152
|
+
```mermaid
|
|
153
|
+
sequenceDiagram
|
|
154
|
+
participant Canvas
|
|
155
|
+
participant C as LiveEventsController
|
|
156
|
+
participant J as ProcessEventJob
|
|
157
|
+
participant L as Legacy handler<br/>LiveEvents::*Event
|
|
158
|
+
participant H as listen blocks
|
|
159
|
+
participant M as Model with LiveEventSync
|
|
160
|
+
participant API as Canvas REST API
|
|
161
|
+
|
|
162
|
+
Canvas->>C: POST /canvas_sync/api/v1/live_event[?org=ID]
|
|
163
|
+
C->>C: verify (DataServices JWT via JWKS,<br/>or EventsManager decrypt)
|
|
164
|
+
C->>C: validate_tenant! (root_account_uuid)
|
|
165
|
+
C->>C: convert global IDs to local IDs
|
|
166
|
+
C->>J: perform_later(event)
|
|
167
|
+
alt a matching LiveEvents::*Event class exists
|
|
168
|
+
J->>L: perform_later(event)
|
|
169
|
+
else
|
|
170
|
+
J->>H: call each listener
|
|
171
|
+
H->>M: built-in listener finds the model by event prefix
|
|
172
|
+
M->>M: find_or_initialize_by(canvas_id)
|
|
173
|
+
alt payload workflow_state == deleted
|
|
174
|
+
M->>M: update workflow_state only
|
|
175
|
+
else
|
|
176
|
+
M->>API: request_from_api
|
|
177
|
+
API-->>M: current record
|
|
178
|
+
end
|
|
179
|
+
M->>M: save! if changed
|
|
180
|
+
end
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
A failing listener is logged and reported through `Rails.error`. It doesn't stop the other listeners. See [Live Events](live-events.md).
|
|
184
|
+
|
|
185
|
+
## JIT sync
|
|
186
|
+
|
|
187
|
+
```mermaid
|
|
188
|
+
sequenceDiagram
|
|
189
|
+
participant Ctrl as Controller / Ability
|
|
190
|
+
participant AH as AbilityHelper
|
|
191
|
+
participant Model
|
|
192
|
+
participant API as Canvas REST API
|
|
193
|
+
|
|
194
|
+
Ctrl->>AH: user / launch_context / launch_account
|
|
195
|
+
AH->>AH: read custom_canvas_*_id from the PandaPal session
|
|
196
|
+
AH->>Model: find_or_jit_sync(canvas_id)
|
|
197
|
+
alt record exists
|
|
198
|
+
Model-->>AH: record
|
|
199
|
+
else missing
|
|
200
|
+
Model->>Model: before_jit_sync callbacks
|
|
201
|
+
Model->>API: request_from_api (api_syncable)
|
|
202
|
+
API-->>Model: record data
|
|
203
|
+
Model->>Model: create (handles a race with another thread)
|
|
204
|
+
Model->>Model: publish record_jit_sync.canvas_sync
|
|
205
|
+
Model->>Model: after_jit_sync callbacks
|
|
206
|
+
Model-->>AH: new record
|
|
207
|
+
end
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
See [AbilityHelper and JIT sync](ability-helper.md) and [API sync](api-sync.md).
|
|
211
|
+
|
|
212
|
+
## Where state lives
|
|
213
|
+
|
|
214
|
+
| Store | What | Lifetime |
|
|
215
|
+
|---|---|---|
|
|
216
|
+
| Your models (Postgres) | Synced Canvas data, plus `canvas_synced_at` / `canvas_sync_batch_id` when those columns exist | Permanent |
|
|
217
|
+
| `canvas_sync_sync_batches` | One row per sync run: start and end time, full or delta, genre, status | Cleaned after 6 months (PandaPal) |
|
|
218
|
+
| `canvas_sync_job_logs` | One row per `CanvasSync::Job` run: arguments, status, errors | Cleaned after 3 months (PandaPal) |
|
|
219
|
+
| Redis: Joblin keys | Batch and pool state, callbacks, job counts | Removed when a batch finishes or expires |
|
|
220
|
+
| Redis: `<prefix>:<genre>:<term_id>:last_sync` | Last successful sync time per Term, used for `updated_after` | Permanent |
|
|
221
|
+
| Redis: report cache | `report_id` and start time per cache key | `max_age` (default 23 hours) |
|
|
222
|
+
| Temp directory | Downloaded report files | Deleted after `process` returns |
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
# Custom report syncs
|
|
2
|
+
|
|
3
|
+
To create a custom report sync job, extend `CanvasSync::Jobs::ReportSyncTask` and define your report. The gem automatically handles:
|
|
4
|
+
- Starting the Canvas report
|
|
5
|
+
- Polling for completion
|
|
6
|
+
- Downloading the report file
|
|
7
|
+
- Error handling and retries
|
|
8
|
+
- Timeout management
|
|
9
|
+
|
|
10
|
+
Let's say we have a custom Canvas report called "my_really_cool_report_csv". Here's how to create a sync job:
|
|
11
|
+
|
|
12
|
+
```ruby
|
|
13
|
+
class MyReallyCoolReportJob < CanvasSync::Jobs::ReportSyncTask
|
|
14
|
+
# Define the Canvas report name
|
|
15
|
+
report_name "my_really_cool_report_csv"
|
|
16
|
+
|
|
17
|
+
# Optional: Override report parameters.
|
|
18
|
+
# merge_report_params adds the current term (enrollment_term_id) and updated_after for you.
|
|
19
|
+
def report_parameters
|
|
20
|
+
merge_report_params(options, {
|
|
21
|
+
course_ids: [1, 2, 3],
|
|
22
|
+
param2: "value",
|
|
23
|
+
})
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
# Implement the process method to handle the downloaded report
|
|
27
|
+
def process(file)
|
|
28
|
+
# file is the path to the downloaded report
|
|
29
|
+
puts "I downloaded a report to #{file}! Isn't that neat!"
|
|
30
|
+
# Add your processing logic here, e.g.:
|
|
31
|
+
# do_bulk_import(file, MyModel)
|
|
32
|
+
end
|
|
33
|
+
end
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Run it on its own with `MyReallyCoolReportJob.perform_later(options)`, or add it to a chain with `chain << { job: MyReallyCoolReportJob, options: {...} }`. Inside the task, `options` holds whatever you passed. You can also override `max_tries` (default 3) and `check_frequency` (default one minute).
|
|
37
|
+
|
|
38
|
+
## Examples
|
|
39
|
+
|
|
40
|
+
For simple CSV reports (single model), you don't need a `process` method. The default bulk-imports into the model named by the class (`SyncRubricAssessmentsJob` → `RubricAssessment`), or the one you set with `model`:
|
|
41
|
+
```ruby
|
|
42
|
+
class SyncRubricAssessmentsJob < CanvasSync::Jobs::ReportSyncTask
|
|
43
|
+
report_name "rubric_assessments_csv"
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
class ImportWidgetsReport < CanvasSync::Jobs::ReportSyncTask
|
|
47
|
+
report_name "widgets_csv"
|
|
48
|
+
model "Widget"
|
|
49
|
+
end
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
For ZIP reports (multiple models like provisioning reports):
|
|
53
|
+
```ruby
|
|
54
|
+
class SyncProvisioningReportJob < CanvasSync::Jobs::ReportSyncTask
|
|
55
|
+
report_name "provisioning_csv"
|
|
56
|
+
|
|
57
|
+
def report_parameters
|
|
58
|
+
...
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
def process(file)
|
|
62
|
+
# Handle ZIP extraction and process each model
|
|
63
|
+
# See lib/canvas_sync/jobs/sync_provisioning_report_job.rb for full example
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
You can also see more examples in:
|
|
69
|
+
- `lib/canvas_sync/jobs/sync_provisioning_report_job.rb` (ZIP report with multiple models)
|
|
70
|
+
- `lib/canvas_sync/jobs/sync_rubric_assessments_job.rb` (Simple CSV report)
|
|
71
|
+
- `lib/canvas_sync/jobs/sync_course_progresses_job.rb` (Simple CSV report)
|
|
72
|
+
|
|
73
|
+
## Report caching
|
|
74
|
+
|
|
75
|
+
If several chains request the same report with the same parameters, CanvasSync can reuse one Canvas report run instead of starting a new one each time. Caching is off by default. Turn it on for every report in a chain with a global option:
|
|
76
|
+
|
|
77
|
+
```ruby
|
|
78
|
+
CanvasSync.default_provisioning_report_chain(
|
|
79
|
+
MODELS_TO_SYNC,
|
|
80
|
+
options: { global: { report_caching: { scope: :sync_batch, max_age: 12.hours } } }
|
|
81
|
+
)
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Or turn it on for one task by passing `caching: { ... }` in that task's options (for example, `options: { assignments: { caching: { max_age: 6.hours } } }`).
|
|
85
|
+
|
|
86
|
+
- `scope` (default `:sync_batch`) - `:sync_batch` only reuses reports within the same sync run. Any other value shares the cache across runs.
|
|
87
|
+
- `max_age` (default `23.hours`) - how old a cached report run can be before CanvasSync starts a new one.
|
|
88
|
+
|
|
89
|
+
The cache key is a hash of `report_parameters`. Override `caching_key` in your task to change it. If a cached report fails, CanvasSync drops the cache entry and starts a fresh report.
|
|
90
|
+
|
|
91
|
+
## Simple table syncs
|
|
92
|
+
|
|
93
|
+
To import another report straight into a table without writing a task class, add `SyncSimpleTableJob` to a chain:
|
|
94
|
+
|
|
95
|
+
```ruby
|
|
96
|
+
chain = CanvasSync.default_provisioning_report_chain
|
|
97
|
+
chain << {
|
|
98
|
+
job: CanvasSync::Jobs::SyncSimpleTableJob,
|
|
99
|
+
options: {
|
|
100
|
+
report_name: <report name>,
|
|
101
|
+
model: <model to sync>,
|
|
102
|
+
params: <hash with the parameters the report needs>
|
|
103
|
+
},
|
|
104
|
+
}
|
|
105
|
+
chain.process!
|
|
106
|
+
```
|
data/doc/development.md
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# Development
|
|
2
|
+
|
|
3
|
+
The dev Ruby version is pinned in `mise.toml`. Tests run against a [Combustion](https://github.com/pat/combustion) app in `spec/internal`, with Postgres and Redis running locally. Use [Appraisal](https://github.com/thoughtbot/appraisal) to test against multiple Rails and Sidekiq versions:
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
bundle install
|
|
7
|
+
bundle exec rake update_test_schema # Regenerate spec/internal models/migrations from the templates
|
|
8
|
+
bundle exec appraisal install
|
|
9
|
+
bundle exec appraisal rspec spec/ # Runs the appraisals enabled for your Ruby version
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
CI runs on GitHub Actions (`.github/workflows/ci.yml`). To release, bump `CanvasSync::VERSION` in `lib/canvas_sync/version.rb` in a PR. When it merges to `master` (or a `stable/<major>.<minor>` branch for backports), `.github/workflows/release.yml` runs the test matrix and publishes the gem if the version is new.
|
|
13
|
+
|
|
14
|
+
When adding to or updating this gem, make sure you do the following:
|
|
15
|
+
|
|
16
|
+
- Update the yardoc comments where necessary, and confirm the changes by running `yardoc --server`
|
|
17
|
+
- Write specs
|
|
18
|
+
- If you modify the model or migration templates, run `bundle exec rake update_test_schema` to update them in `spec/internal` (and commit those changes)
|
|
19
|
+
- Add any notable or breaking changes to `CHANGELOG.md`
|
|
20
|
+
|
|
21
|
+
## Docs
|
|
22
|
+
|
|
23
|
+
Docs can be generated using [yard](https://yardoc.org/). To view the docs:
|
|
24
|
+
|
|
25
|
+
- Clone this gem's repository
|
|
26
|
+
- `bundle install`
|
|
27
|
+
- `yard server --reload`
|
|
28
|
+
|
|
29
|
+
The yard server will give you a URL you can visit to view the docs.
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# Importing and mapping overrides
|
|
2
|
+
|
|
3
|
+
## Bulk importing
|
|
4
|
+
|
|
5
|
+
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.
|
|
6
|
+
|
|
7
|
+
Models that include `CanvasSync::Record` get two callbacks around imports:
|
|
8
|
+
- `sync_import` - runs around the whole import of a report into the model
|
|
9
|
+
- `sync_batch_import` - runs around each batch. Inside the callback, `batch` (the rows), `import_options`, and (after the import) `import_result` are available.
|
|
10
|
+
|
|
11
|
+
```ruby
|
|
12
|
+
class Course < ApplicationRecord
|
|
13
|
+
include CanvasSync::Record
|
|
14
|
+
|
|
15
|
+
after_sync_batch_import do
|
|
16
|
+
Rails.logger.info("Imported #{batch.count} courses")
|
|
17
|
+
end
|
|
18
|
+
end
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Mapping Overrides
|
|
22
|
+
|
|
23
|
+
Overrides are useful for two scenarios:
|
|
24
|
+
|
|
25
|
+
- You have an existing application where the column names do not match up with what CanvasSync expects
|
|
26
|
+
- You want to sync some other column in the report that CanvasSync is not configured to sync
|
|
27
|
+
|
|
28
|
+
Mappings can be modified by editing the Model class like such:
|
|
29
|
+
```ruby
|
|
30
|
+
class User < ApplicationRecord
|
|
31
|
+
include CanvasSync::Record
|
|
32
|
+
|
|
33
|
+
sync_mapping(reset: false) do # `reset: false` is the default
|
|
34
|
+
# The mapping can be totally cleared with `reset: true` in the `sync_mapping` call, or like such:
|
|
35
|
+
reset_links
|
|
36
|
+
|
|
37
|
+
# Add a new column:
|
|
38
|
+
link_column :column_in_report => :column_in_database, type: :datetime
|
|
39
|
+
|
|
40
|
+
# If the column name on the report and in the DB are the same, a shorthand can be used:
|
|
41
|
+
link_column :omit_from_final_grade, type: :datetime
|
|
42
|
+
|
|
43
|
+
# You can specify a block to pre-transform the value
|
|
44
|
+
link_column :column_in_report => :column_in_database do |value, row|
|
|
45
|
+
YAML.parse(value)
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# If the defaults define a column you don't want synced, you can remove it from the mapping:
|
|
49
|
+
unlink_column :column_in_database
|
|
50
|
+
|
|
51
|
+
# Change or drop raw report rows before they're mapped. The block runs in the context of the model class.
|
|
52
|
+
# `row` is a Hash keyed by the (lowercased) report column names.
|
|
53
|
+
alter_rows do |row|
|
|
54
|
+
throw :skip if row[:status] == "pending" # Drop this row
|
|
55
|
+
row[:name] = row[:name]&.strip # Or edit it in place
|
|
56
|
+
end
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
# ...
|
|
60
|
+
end
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
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:
|
|
64
|
+
|
|
65
|
+
```ruby
|
|
66
|
+
users:
|
|
67
|
+
conflict_target: canvas_user_id # This must be a unique field that is present in the report and the database
|
|
68
|
+
report_columns: # The keys specified here are the column names in the report CSV
|
|
69
|
+
canvas_user_id_column_name_in_report:
|
|
70
|
+
database_column_name: canvas_user_id_name_in_your_db # Sometimes the database column name might not match the report column name
|
|
71
|
+
type: integer
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Legacy Support
|
|
75
|
+
|
|
76
|
+
### Legacy Mappings
|
|
77
|
+
|
|
78
|
+
CanvasSync 0.10.0+, by default, changes Canvas primary-keys from `:canvas_MODEL_id` to just `:canvas_id`.
|
|
79
|
+
Because CanvasSync primarily consists of templates, this change shouldn't require any large changes in your app, but you will need to
|
|
80
|
+
apply [`model_mappings_legacy.yml`](../model_mappings_legacy.yml) to your model mappings - see [Mapping Overrides](#mapping-overrides). For the 0.26 switch to storing the Canvas ID in `id`, see [Upgrading](upgrading.md#canvas-id-as-primary-key).
|
|
81
|
+
|
|
82
|
+
### Row-by-Row Syncing
|
|
83
|
+
|
|
84
|
+
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.
|
|
85
|
+
|
|
86
|
+
Example:
|
|
87
|
+
|
|
88
|
+
```ruby
|
|
89
|
+
CanvasSync.provisioning_sync(['users', 'courses'], term_scope: :active, legacy_support: true)
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
You may also provide an array of model names. Doing so will only provide legacy support for the specified models.
|
|
93
|
+
|
|
94
|
+
```ruby
|
|
95
|
+
CanvasSync.provisioning_sync(['users', 'courses'], term_scope: :active, legacy_support: ['courses'])
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
In the above example, users will sync normally while courses will require a `create_or_update_from_csv` method.
|
data/doc/job-logs.md
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# Job logs
|
|
2
|
+
|
|
3
|
+
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.
|
|
4
|
+
|
|
5
|
+
To keep a noisy job's successful runs out of the table, add its class to `config.classes_to_only_log_errors_on` (see [Configuration](../README.md#configuration)).
|
|
6
|
+
|
|
7
|
+
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:
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
@job_log.metadata = "This job ran really well!"
|
|
11
|
+
@job_log.save!
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
When PandaPal is installed, CanvasSync schedules a nightly cleanup of old `JobLog` and `SyncBatch` rows. Set how long to keep them per organization with the `canvas_sync` setting (any duration ChronicDuration can parse):
|
|
15
|
+
|
|
16
|
+
```ruby
|
|
17
|
+
org.settings[:canvas_sync] = {
|
|
18
|
+
job_log_retention: "3 months", # Default
|
|
19
|
+
sync_batch_retention: "6 months", # Default
|
|
20
|
+
}
|
|
21
|
+
org.save!
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
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:
|
|
25
|
+
|
|
26
|
+
```ruby
|
|
27
|
+
Sidekiq.configure_server do |config|
|
|
28
|
+
config.server_middleware do |chain|
|
|
29
|
+
chain.add CanvasSync::Sidekiq::Middleware
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
```
|