canvas_sync 0.16.4 → 0.21.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (260) hide show
  1. checksums.yaml +5 -5
  2. data/README.md +235 -151
  3. data/app/controllers/{api → canvas_sync/api}/v1/health_check_controller.rb +1 -1
  4. data/app/controllers/canvas_sync/api/v1/live_events_controller.rb +122 -0
  5. data/app/models/canvas_sync/sync_batch.rb +5 -0
  6. data/config/initializers/apartment.rb +10 -1
  7. data/config/routes.rb +7 -0
  8. data/db/migrate/20170915210836_create_canvas_sync_job_log.rb +12 -31
  9. data/db/migrate/20180725155729_add_job_id_to_canvas_sync_job_logs.rb +4 -13
  10. data/db/migrate/20190916154829_add_fork_count_to_canvas_sync_job_logs.rb +3 -11
  11. data/db/migrate/20201018210836_create_canvas_sync_sync_batches.rb +11 -0
  12. data/db/migrate/20201030210836_add_full_sync_to_canvas_sync_sync_batch.rb +7 -0
  13. data/lib/canvas_sync/batch_processor.rb +41 -0
  14. data/lib/canvas_sync/concerns/ability_helper.rb +72 -0
  15. data/lib/canvas_sync/concerns/account/ancestry.rb +2 -0
  16. data/lib/canvas_sync/concerns/account/base.rb +15 -0
  17. data/lib/canvas_sync/concerns/api_syncable.rb +17 -10
  18. data/lib/canvas_sync/concerns/live_event_sync.rb +46 -0
  19. data/lib/canvas_sync/concerns/role/base.rb +57 -0
  20. data/lib/canvas_sync/concerns/sync_mapping.rb +120 -0
  21. data/lib/canvas_sync/engine.rb +80 -0
  22. data/lib/canvas_sync/generators/install_generator.rb +1 -0
  23. data/lib/canvas_sync/generators/install_live_events_generator.rb +0 -1
  24. data/lib/canvas_sync/generators/templates/migrations/create_content_migrations.rb +24 -0
  25. data/lib/canvas_sync/generators/templates/migrations/create_course_nicknames.rb +17 -0
  26. data/lib/canvas_sync/generators/templates/migrations/create_grading_period_groups.rb +18 -0
  27. data/lib/canvas_sync/generators/templates/migrations/create_grading_periods.rb +22 -0
  28. data/lib/canvas_sync/generators/templates/migrations/create_learning_outcome_results.rb +46 -0
  29. data/lib/canvas_sync/generators/templates/migrations/create_learning_outcomes.rb +30 -0
  30. data/lib/canvas_sync/generators/templates/migrations/create_rubric_assessments.rb +31 -0
  31. data/lib/canvas_sync/generators/templates/migrations/create_rubric_associations.rb +36 -0
  32. data/lib/canvas_sync/generators/templates/migrations/create_rubrics.rb +38 -0
  33. data/lib/canvas_sync/generators/templates/migrations/create_user_observers.rb +17 -0
  34. data/lib/canvas_sync/generators/templates/migrations/create_users.rb +0 -1
  35. data/lib/canvas_sync/generators/templates/models/account.rb +3 -0
  36. data/lib/canvas_sync/generators/templates/models/admin.rb +2 -0
  37. data/lib/canvas_sync/generators/templates/models/assignment.rb +3 -0
  38. data/lib/canvas_sync/generators/templates/models/assignment_group.rb +3 -0
  39. data/lib/canvas_sync/generators/templates/models/content_migration.rb +12 -0
  40. data/lib/canvas_sync/generators/templates/models/context_module.rb +3 -0
  41. data/lib/canvas_sync/generators/templates/models/context_module_item.rb +3 -0
  42. data/lib/canvas_sync/generators/templates/models/course.rb +11 -0
  43. data/lib/canvas_sync/generators/templates/models/course_nickname.rb +13 -0
  44. data/lib/canvas_sync/generators/templates/models/enrollment.rb +14 -0
  45. data/lib/canvas_sync/generators/templates/models/grading_period.rb +10 -0
  46. data/lib/canvas_sync/generators/templates/models/grading_period_group.rb +9 -0
  47. data/lib/canvas_sync/generators/templates/models/group.rb +2 -0
  48. data/lib/canvas_sync/generators/templates/models/group_membership.rb +2 -0
  49. data/lib/canvas_sync/generators/templates/models/learning_outcome.rb +24 -0
  50. data/lib/canvas_sync/generators/templates/models/learning_outcome_result.rb +48 -0
  51. data/lib/canvas_sync/generators/templates/models/pseudonym.rb +2 -0
  52. data/lib/canvas_sync/generators/templates/models/role.rb +2 -0
  53. data/lib/canvas_sync/generators/templates/models/rubric.rb +29 -0
  54. data/lib/canvas_sync/generators/templates/models/rubric_assessment.rb +17 -0
  55. data/lib/canvas_sync/generators/templates/models/rubric_association.rb +14 -0
  56. data/lib/canvas_sync/generators/templates/models/section.rb +9 -0
  57. data/lib/canvas_sync/generators/templates/models/submission.rb +3 -0
  58. data/lib/canvas_sync/generators/templates/models/term.rb +3 -0
  59. data/lib/canvas_sync/generators/templates/models/user.rb +11 -0
  60. data/lib/canvas_sync/generators/templates/models/user_observer.rb +13 -0
  61. data/lib/canvas_sync/generators/templates/services/live_events/assignment_event.rb +1 -1
  62. data/lib/canvas_sync/generators/templates/services/live_events/assignment_group_event.rb +1 -1
  63. data/lib/canvas_sync/generators/templates/services/live_events/course_event.rb +1 -3
  64. data/lib/canvas_sync/generators/templates/services/live_events/course_section_event.rb +1 -1
  65. data/lib/canvas_sync/generators/templates/services/live_events/enrollment_event.rb +1 -1
  66. data/lib/canvas_sync/generators/templates/services/live_events/grade_event.rb +1 -1
  67. data/lib/canvas_sync/generators/templates/services/live_events/module_event.rb +1 -1
  68. data/lib/canvas_sync/generators/templates/services/live_events/module_item_event.rb +1 -1
  69. data/lib/canvas_sync/generators/templates/services/live_events/submission_event.rb +1 -1
  70. data/lib/canvas_sync/generators/templates/services/live_events/syllabus_event.rb +1 -1
  71. data/lib/canvas_sync/generators/templates/services/live_events/user_event.rb +1 -3
  72. data/lib/canvas_sync/importers/bulk_importer.rb +138 -31
  73. data/lib/canvas_sync/job.rb +7 -5
  74. data/lib/canvas_sync/job_batches/active_job.rb +108 -0
  75. data/lib/canvas_sync/job_batches/batch.rb +543 -0
  76. data/lib/canvas_sync/job_batches/callback.rb +149 -0
  77. data/lib/canvas_sync/job_batches/chain_builder.rb +249 -0
  78. data/lib/canvas_sync/job_batches/context_hash.rb +159 -0
  79. data/lib/canvas_sync/job_batches/hier_batch_ids.lua +25 -0
  80. data/lib/canvas_sync/job_batches/jobs/base_job.rb +7 -0
  81. data/lib/canvas_sync/job_batches/jobs/concurrent_batch_job.rb +22 -0
  82. data/lib/canvas_sync/job_batches/jobs/managed_batch_job.rb +170 -0
  83. data/lib/canvas_sync/job_batches/jobs/serial_batch_job.rb +22 -0
  84. data/lib/canvas_sync/job_batches/pool.rb +245 -0
  85. data/lib/canvas_sync/job_batches/pool_refill.lua +47 -0
  86. data/lib/canvas_sync/job_batches/redis_model.rb +69 -0
  87. data/lib/canvas_sync/job_batches/redis_script.rb +163 -0
  88. data/lib/canvas_sync/job_batches/schedule_callback.lua +14 -0
  89. data/lib/canvas_sync/job_batches/sidekiq/web/batches_assets/css/styles.less +182 -0
  90. data/lib/canvas_sync/job_batches/sidekiq/web/batches_assets/js/batch_tree.js +108 -0
  91. data/lib/canvas_sync/job_batches/sidekiq/web/batches_assets/js/util.js +2 -0
  92. data/lib/canvas_sync/job_batches/sidekiq/web/helpers.rb +41 -0
  93. data/lib/canvas_sync/job_batches/sidekiq/web/views/_batch_tree.erb +6 -0
  94. data/lib/canvas_sync/job_batches/sidekiq/web/views/_batches_table.erb +44 -0
  95. data/lib/canvas_sync/job_batches/sidekiq/web/views/_common.erb +13 -0
  96. data/lib/canvas_sync/job_batches/sidekiq/web/views/_jobs_table.erb +21 -0
  97. data/lib/canvas_sync/job_batches/sidekiq/web/views/_pagination.erb +26 -0
  98. data/lib/canvas_sync/job_batches/sidekiq/web/views/batch.erb +81 -0
  99. data/lib/canvas_sync/job_batches/sidekiq/web/views/batches.erb +23 -0
  100. data/lib/canvas_sync/job_batches/sidekiq/web/views/pool.erb +137 -0
  101. data/lib/canvas_sync/job_batches/sidekiq/web/views/pools.erb +47 -0
  102. data/lib/canvas_sync/job_batches/sidekiq/web.rb +218 -0
  103. data/lib/canvas_sync/job_batches/sidekiq.rb +136 -0
  104. data/lib/canvas_sync/job_batches/status.rb +91 -0
  105. data/lib/canvas_sync/jobs/begin_sync_chain_job.rb +99 -0
  106. data/lib/canvas_sync/jobs/canvas_process_waiter.rb +41 -0
  107. data/lib/canvas_sync/jobs/report_checker.rb +70 -8
  108. data/lib/canvas_sync/jobs/report_processor_job.rb +4 -7
  109. data/lib/canvas_sync/jobs/report_starter.rb +34 -20
  110. data/lib/canvas_sync/jobs/sync_accounts_job.rb +3 -5
  111. data/lib/canvas_sync/jobs/sync_admins_job.rb +2 -4
  112. data/lib/canvas_sync/jobs/sync_assignment_groups_job.rb +2 -4
  113. data/lib/canvas_sync/jobs/sync_assignments_job.rb +2 -4
  114. data/lib/canvas_sync/jobs/sync_content_migrations_job.rb +20 -0
  115. data/lib/canvas_sync/jobs/sync_context_module_items_job.rb +2 -4
  116. data/lib/canvas_sync/jobs/sync_context_modules_job.rb +2 -4
  117. data/lib/canvas_sync/jobs/sync_provisioning_report_job.rb +16 -50
  118. data/lib/canvas_sync/jobs/sync_roles_job.rb +2 -5
  119. data/lib/canvas_sync/jobs/sync_rubric_assessments_job.rb +15 -0
  120. data/lib/canvas_sync/jobs/sync_rubric_associations_job.rb +15 -0
  121. data/lib/canvas_sync/jobs/sync_rubrics_job.rb +15 -0
  122. data/lib/canvas_sync/jobs/sync_simple_table_job.rb +11 -32
  123. data/lib/canvas_sync/jobs/sync_submissions_job.rb +6 -4
  124. data/lib/canvas_sync/jobs/sync_terms_job.rb +9 -8
  125. data/lib/canvas_sync/jobs/term_batches_job.rb +50 -0
  126. data/lib/canvas_sync/{generators/templates/services/live_events/base_event.rb → live_events/base_handler.rb} +6 -10
  127. data/lib/canvas_sync/live_events/process_event_job.rb +26 -0
  128. data/lib/canvas_sync/live_events.rb +38 -0
  129. data/lib/canvas_sync/misc_helper.rb +63 -0
  130. data/lib/canvas_sync/processors/assignment_groups_processor.rb +3 -8
  131. data/lib/canvas_sync/processors/assignments_processor.rb +3 -8
  132. data/lib/canvas_sync/processors/content_migrations_processor.rb +19 -0
  133. data/lib/canvas_sync/processors/context_module_items_processor.rb +3 -8
  134. data/lib/canvas_sync/processors/context_modules_processor.rb +3 -8
  135. data/lib/canvas_sync/processors/model_mappings.yml +420 -0
  136. data/lib/canvas_sync/processors/normal_processor.rb +3 -3
  137. data/lib/canvas_sync/processors/provisioning_report_processor.rb +42 -55
  138. data/lib/canvas_sync/processors/report_processor.rb +15 -9
  139. data/lib/canvas_sync/processors/rubric_assessments_processor.rb +19 -0
  140. data/lib/canvas_sync/processors/rubric_associations_processor.rb +19 -0
  141. data/lib/canvas_sync/processors/rubrics_processor.rb +19 -0
  142. data/lib/canvas_sync/processors/submissions_processor.rb +3 -8
  143. data/lib/canvas_sync/record.rb +103 -0
  144. data/lib/canvas_sync/version.rb +1 -1
  145. data/lib/canvas_sync.rb +124 -125
  146. data/spec/canvas_sync/canvas_sync_spec.rb +224 -155
  147. data/spec/canvas_sync/jobs/canvas_process_waiter_spec.rb +34 -0
  148. data/spec/canvas_sync/jobs/job_spec.rb +9 -17
  149. data/spec/canvas_sync/jobs/report_checker_spec.rb +1 -3
  150. data/spec/canvas_sync/jobs/report_processor_job_spec.rb +0 -3
  151. data/spec/canvas_sync/jobs/report_starter_spec.rb +19 -28
  152. data/spec/canvas_sync/jobs/sync_admins_job_spec.rb +1 -4
  153. data/spec/canvas_sync/jobs/sync_assignment_groups_job_spec.rb +2 -1
  154. data/spec/canvas_sync/jobs/sync_assignments_job_spec.rb +3 -2
  155. data/spec/canvas_sync/jobs/sync_content_migrations_job_spec.rb +30 -0
  156. data/spec/canvas_sync/jobs/sync_context_module_items_job_spec.rb +3 -2
  157. data/spec/canvas_sync/jobs/sync_context_modules_job_spec.rb +3 -2
  158. data/spec/canvas_sync/jobs/sync_provisioning_report_job_spec.rb +7 -41
  159. data/spec/canvas_sync/jobs/sync_roles_job_spec.rb +1 -4
  160. data/spec/canvas_sync/jobs/sync_simple_table_job_spec.rb +5 -12
  161. data/spec/canvas_sync/jobs/sync_submissions_job_spec.rb +8 -2
  162. data/spec/canvas_sync/jobs/sync_terms_job_spec.rb +1 -4
  163. data/spec/canvas_sync/live_events/live_event_sync_spec.rb +27 -0
  164. data/spec/canvas_sync/live_events/live_events_controller_spec.rb +54 -0
  165. data/spec/canvas_sync/live_events/process_event_job_spec.rb +38 -0
  166. data/spec/canvas_sync/misc_helper_spec.rb +58 -0
  167. data/spec/canvas_sync/models/assignment_spec.rb +1 -1
  168. data/spec/canvas_sync/processors/content_migrations_processor_spec.rb +13 -0
  169. data/spec/canvas_sync/processors/provisioning_report_processor_spec.rb +101 -1
  170. data/spec/canvas_sync/processors/rubric_assessments_spec.rb +16 -0
  171. data/spec/canvas_sync/processors/rubric_associations_spec.rb +16 -0
  172. data/spec/canvas_sync/processors/rubrics_processor_spec.rb +17 -0
  173. data/spec/dummy/app/models/account.rb +6 -0
  174. data/spec/dummy/app/models/admin.rb +2 -0
  175. data/spec/dummy/app/models/assignment.rb +3 -0
  176. data/spec/dummy/app/models/assignment_group.rb +3 -0
  177. data/spec/dummy/app/models/content_migration.rb +18 -0
  178. data/spec/dummy/app/models/context_module.rb +3 -0
  179. data/spec/dummy/app/models/context_module_item.rb +3 -0
  180. data/spec/dummy/app/models/course.rb +11 -0
  181. data/spec/dummy/app/models/course_nickname.rb +19 -0
  182. data/spec/dummy/app/models/enrollment.rb +14 -0
  183. data/spec/dummy/app/models/grading_period.rb +16 -0
  184. data/spec/dummy/app/models/grading_period_group.rb +15 -0
  185. data/spec/dummy/app/models/group.rb +2 -0
  186. data/spec/dummy/app/models/group_membership.rb +2 -0
  187. data/spec/dummy/app/models/learning_outcome.rb +30 -0
  188. data/spec/dummy/app/models/learning_outcome_result.rb +54 -0
  189. data/spec/dummy/app/models/pseudonym.rb +16 -0
  190. data/spec/dummy/app/models/role.rb +2 -0
  191. data/spec/dummy/app/models/rubric.rb +35 -0
  192. data/spec/dummy/app/models/rubric_assessment.rb +22 -0
  193. data/spec/dummy/app/models/rubric_association.rb +20 -0
  194. data/spec/dummy/app/models/section.rb +9 -0
  195. data/spec/dummy/app/models/submission.rb +4 -0
  196. data/spec/dummy/app/models/term.rb +3 -0
  197. data/spec/dummy/app/models/user.rb +11 -0
  198. data/spec/dummy/app/models/user_observer.rb +19 -0
  199. data/spec/dummy/app/services/live_events/assignment_event.rb +1 -1
  200. data/spec/dummy/app/services/live_events/course_event.rb +1 -3
  201. data/spec/dummy/app/services/live_events/course_section_event.rb +1 -1
  202. data/spec/dummy/app/services/live_events/enrollment_event.rb +1 -1
  203. data/spec/dummy/app/services/live_events/grade_event.rb +1 -1
  204. data/spec/dummy/app/services/live_events/module_event.rb +1 -1
  205. data/spec/dummy/app/services/live_events/module_item_event.rb +1 -1
  206. data/spec/dummy/app/services/live_events/submission_event.rb +1 -1
  207. data/spec/dummy/app/services/live_events/syllabus_event.rb +1 -1
  208. data/spec/dummy/app/services/live_events/user_event.rb +1 -3
  209. data/spec/dummy/config/environments/test.rb +2 -0
  210. data/spec/dummy/config/routes.rb +1 -0
  211. data/spec/dummy/db/migrate/20201016181346_create_pseudonyms.rb +24 -0
  212. data/spec/dummy/db/migrate/20210907233329_create_user_observers.rb +23 -0
  213. data/spec/dummy/db/migrate/20210907233330_create_grading_periods.rb +28 -0
  214. data/spec/dummy/db/migrate/20211001184920_create_grading_period_groups.rb +24 -0
  215. data/spec/dummy/db/migrate/20220308072643_create_content_migrations.rb +30 -0
  216. data/spec/dummy/db/migrate/20220712210559_create_learning_outcomes.rb +36 -0
  217. data/spec/dummy/db/migrate/{20190702203620_create_users.rb → 20220926221926_create_users.rb} +0 -1
  218. data/spec/dummy/db/migrate/20240408223326_create_course_nicknames.rb +23 -0
  219. data/spec/dummy/db/migrate/20240509105100_create_rubrics.rb +44 -0
  220. data/spec/dummy/db/migrate/20240510094100_create_rubric_associations.rb +42 -0
  221. data/spec/dummy/db/migrate/20240510101100_create_rubric_assessments.rb +37 -0
  222. data/spec/dummy/db/migrate/20240523101010_create_learning_outcome_results.rb +52 -0
  223. data/spec/dummy/db/schema.rb +244 -5
  224. data/spec/factories/user_factory.rb +0 -1
  225. data/spec/job_batching/active_job_spec.rb +107 -0
  226. data/spec/job_batching/batch_spec.rb +489 -0
  227. data/spec/job_batching/callback_spec.rb +38 -0
  228. data/spec/job_batching/context_hash_spec.rb +54 -0
  229. data/spec/job_batching/flow_spec.rb +82 -0
  230. data/spec/job_batching/integration/fail_then_succeed.rb +42 -0
  231. data/spec/job_batching/integration/integration.rb +57 -0
  232. data/spec/job_batching/integration/nested.rb +88 -0
  233. data/spec/job_batching/integration/simple.rb +47 -0
  234. data/spec/job_batching/integration/workflow.rb +134 -0
  235. data/spec/job_batching/integration_helper.rb +50 -0
  236. data/spec/job_batching/pool_spec.rb +161 -0
  237. data/spec/job_batching/sidekiq_spec.rb +125 -0
  238. data/spec/job_batching/status_spec.rb +76 -0
  239. data/spec/job_batching/support/base_job.rb +14 -0
  240. data/spec/job_batching/support/sample_callback.rb +2 -0
  241. data/spec/spec_helper.rb +17 -0
  242. data/spec/support/fixtures/reports/content_migrations.csv +3 -0
  243. data/spec/support/fixtures/reports/course_nicknames.csv +3 -0
  244. data/spec/support/fixtures/reports/grading_period_groups.csv +2 -0
  245. data/spec/support/fixtures/reports/grading_periods.csv +3 -0
  246. data/spec/support/fixtures/reports/learning_outcome_results.csv +3 -0
  247. data/spec/support/fixtures/reports/learning_outcomes.csv +3 -0
  248. data/spec/support/fixtures/reports/provisioning_csv_unzipped/courses.csv +3 -0
  249. data/spec/support/fixtures/reports/provisioning_csv_unzipped/users.csv +4 -0
  250. data/spec/support/fixtures/reports/rubric_assessments.csv +3 -0
  251. data/spec/support/fixtures/reports/rubric_associations.csv +3 -0
  252. data/spec/support/fixtures/reports/rubrics.csv +3 -0
  253. data/spec/support/fixtures/reports/user_observers.csv +3 -0
  254. data/spec/support/fixtures/reports/users.csv +3 -2
  255. data/spec/support/fixtures/reports/xlist.csv +1 -1
  256. metadata +329 -27
  257. data/app/controllers/api/v1/live_events_controller.rb +0 -18
  258. data/lib/canvas_sync/job_chain.rb +0 -57
  259. data/lib/canvas_sync/jobs/fork_gather.rb +0 -59
  260. data/spec/canvas_sync/jobs/fork_gather_spec.rb +0 -73
@@ -0,0 +1,249 @@
1
+ module CanvasSync
2
+ module JobBatches
3
+ class ChainBuilder
4
+ VALID_PLACEMENT_PARAMETERS = %i[before after with].freeze
5
+
6
+ attr_reader :base_job
7
+
8
+ def initialize(base_type = SerialBatchJob)
9
+ if base_type.is_a?(Hash)
10
+ @base_job = base_type
11
+ @base_job[:args] ||= @base_job[:parameters] || []
12
+ @base_job[:kwargs] ||= {}
13
+ else
14
+ @base_job = build_job_hash(base_type)
15
+ end
16
+
17
+ self.class.get_chain_parameter(base_job)
18
+ end
19
+
20
+ def process!
21
+ normalize!
22
+ self.class.enqueue_job(base_job)
23
+ end
24
+
25
+ def [](key)
26
+ if key.is_a?(Class)
27
+ get_sub_chain(key)
28
+ else
29
+ # Legacy Support
30
+ key = :args if key == :parameters
31
+
32
+ @base_job[key]
33
+ end
34
+ end
35
+
36
+ def args; return self[:args]; end
37
+ def kwargs; return self[:kwargs]; end
38
+
39
+ def <<(new_job)
40
+ insert_at(-1, new_job)
41
+ end
42
+
43
+ def insert_at(position, new_jobs, *args, **kwargs, &blk)
44
+ chain = self.class.get_chain_parameter(base_job)
45
+ if new_jobs.is_a?(Class) || new_jobs.is_a?(String)
46
+ new_jobs = build_job_hash(new_jobs, args: args, kwargs: kwargs, &blk)
47
+ elsif args.count > 0 || kwargs.count > 0
48
+ raise "Unexpected number of arguments"
49
+ end
50
+ new_jobs = [new_jobs] unless new_jobs.is_a?(Array)
51
+ chain.insert(position, *new_jobs)
52
+ end
53
+
54
+ def insert(new_jobs, *args, **kwargs, &blk)
55
+ if new_jobs.is_a?(Class) || new_jobs.is_a?(String)
56
+ job_kwargs = kwargs.except(*VALID_PLACEMENT_PARAMETERS)
57
+ new_jobs = build_job_hash(new_jobs, args: args, kwargs: job_kwargs, &blk)
58
+ kwargs = kwargs.slice(*VALID_PLACEMENT_PARAMETERS)
59
+ else
60
+ invalid_params = kwargs.keys - VALID_PLACEMENT_PARAMETERS
61
+ raise "Invalid placement parameters: #{invalid_params.map(&:to_s).join(', ')}" if invalid_params.present?
62
+ raise "At most one placement parameter may be provided" if kwargs.values.compact.length > 1
63
+ raise "Unexpected number of arguments" if args.length > 0
64
+ end
65
+
66
+ new_jobs = [new_jobs] unless new_jobs.is_a?(Array)
67
+
68
+ if !kwargs.present?
69
+ insert_at(-1, new_jobs)
70
+ else
71
+ placement = kwargs.keys[0]
72
+ relative_to = kwargs.values[0]
73
+
74
+ matching_jobs = find_matching_jobs(relative_to).to_a
75
+ raise "Could not find a \"#{relative_to}\" job in the chain" if matching_jobs.count == 0
76
+ raise "Found multiple \"#{relative_to}\" jobs in the chain" if matching_jobs.count > 1
77
+
78
+ relative_job, parent_job, sub_index = matching_jobs[0]
79
+ needed_parent_type = placement == :with ? ConcurrentBatchJob : SerialBatchJob
80
+
81
+ chain = self.class.get_chain_parameter(parent_job)
82
+
83
+ if parent_job[:job] != needed_parent_type
84
+ old_job = chain[sub_index]
85
+ parent_job = chain[sub_index] = {
86
+ job: needed_parent_type,
87
+ parameters: [],
88
+ }
89
+ sub_index = 0
90
+ chain = self.class.get_chain_parameter(parent_job)
91
+ chain << old_job
92
+ end
93
+
94
+ if placement == :with
95
+ chain.insert(-1, *new_jobs)
96
+ else
97
+ sub_index += 1 if placement == :after
98
+ chain.insert(sub_index, *new_jobs)
99
+ end
100
+ end
101
+ end
102
+
103
+ def empty?
104
+ self.class.get_chain_parameter(self).empty?
105
+ end
106
+
107
+ def get_sub_chain(sub_type)
108
+ matching_jobs = find_matching_jobs(sub_type).to_a
109
+ raise "Found multiple \"#{sub_type}\" jobs in the chain" if matching_jobs.count > 1
110
+ return nil if matching_jobs.count == 0
111
+
112
+ job = matching_jobs[0][0]
113
+ job = self.class.new(job) unless job.is_a?(ChainBuilder)
114
+ job
115
+ end
116
+
117
+ def normalize!(job_def = self.base_job)
118
+ if job_def.is_a?(ChainBuilder)
119
+ job_def.normalize!
120
+ else
121
+ job_def[:job] = job_def[:job].to_s
122
+ if (chain = self.class.get_chain_parameter(job_def, raise_error: false)).present?
123
+ chain.map! { |sub_job| normalize!(sub_job) }
124
+ end
125
+ job_def
126
+ end
127
+ end
128
+
129
+ def apply_block(&blk)
130
+ return unless blk.present?
131
+ instance_exec(&blk)
132
+ end
133
+
134
+ private
135
+
136
+ def build_job_hash(job, args: [], kwargs: {}, &blk)
137
+ hsh = {
138
+ job: job,
139
+ args: args,
140
+ kwargs: kwargs,
141
+ }
142
+ self.class.new(hsh).apply_block(&blk) if blk.present?
143
+ hsh
144
+ end
145
+
146
+ def find_matching_jobs(search_job, parent_job = self.base_job)
147
+ return to_enum(:find_matching_jobs, search_job, parent_job) unless block_given?
148
+
149
+ sub_jobs = self.class.get_chain_parameter(parent_job)
150
+ sub_jobs.each_with_index do |sub_job, i|
151
+ if sub_job[:job].to_s == search_job.to_s
152
+ yield [sub_job, parent_job, i]
153
+ elsif self.class._job_type_definitions[sub_job[:job].to_s]
154
+ find_matching_jobs(search_job, sub_job) { |item| yield item }
155
+ end
156
+ end
157
+ end
158
+
159
+ def find_parent_job(job_def)
160
+ iterate_job_tree do |job, path|
161
+ return path[-1] if job == job_def
162
+ end
163
+ nil
164
+ end
165
+
166
+ def iterate_job_tree(root: self.base_job, path: [], &blk)
167
+ blk.call(root, path)
168
+
169
+ if self.class._job_type_definitions[root[:job]]
170
+ sub_jobs = self.class.get_chain_parameter(root)
171
+ sub_jobs.each_with_index do |sub_job, i|
172
+ iterate_job_tree(root: sub_job, path: [*path, root], &blk)
173
+ end
174
+ end
175
+ end
176
+
177
+ class << self
178
+ # Support builder syntaxt/DSL
179
+ # Chain.build(ConcurrentBatchJob) do
180
+ # insert(SomeJob, arg1, kwarg: 1)
181
+ # insert(SerialBatchJob) do
182
+ # insert(SomeJob, arg1, kwarg: 1)
183
+ # end
184
+ # end
185
+ def build(job, *args, **kwargs, &blk)
186
+ new(job).tap do |ch|
187
+ ch.base_job[:args] = args
188
+ ch.base_job[:kwargs] = kwargs
189
+ ch.apply_block(&blk)
190
+ end
191
+ end
192
+
193
+ def _job_type_definitions
194
+ @job_type_definitions ||= {}
195
+ end
196
+
197
+ def register_chain_job(job_class, chain_parameter, **options)
198
+ _job_type_definitions[job_class.to_s] = {
199
+ **options,
200
+ chain_parameter: chain_parameter,
201
+ }
202
+ end
203
+
204
+ def get_chain_parameter(job_def, raise_error: true)
205
+ unless _job_type_definitions[job_def[:job].to_s].present?
206
+ raise "Job Type #{job_def[:job].to_s} does not accept a sub-chain" if raise_error
207
+ return nil
208
+ end
209
+
210
+ key = _job_type_definitions[job_def[:job].to_s][:chain_parameter]
211
+ if key.is_a?(Numeric)
212
+ job_def[:args][key] ||= []
213
+ else
214
+ job_def[:kwargs][key] ||= []
215
+ end
216
+ end
217
+
218
+ # TODO: Add a Chain progress web View
219
+ # Augment Batch tree-view with Chain data
220
+ # > [DONE] Tree view w/o Chain will only show Parent/Current batches and Job Counts
221
+ # > If augmented with Chain data, the above will be annotated with Chain-related info and will be able to show Jobs defined in the Chain
222
+ # > Chain-jobs will be supplied chain_id and chain_step_id metadata
223
+ # > Using server-middleware, if a Chain-job (has chain_id and chain_step_id) creates a Batch, tag the Batch w/ the chain_id and chain_step_id
224
+ # > UI will map Batches to Chain-steps using the chain_step_id. UI will add entries for any Chain-steps that were not tied to a Batch
225
+ # > [DONE] Use a Lua script to find child batch IDs. Support max_depth, items_per_depth, top_depth_slice parameters
226
+ def enqueue_job(job_def)
227
+ job_class = job_def[:job].constantize
228
+ job_args = job_def[:args] || job_def[:parameters] || []
229
+ job_kwargs = job_def[:kwargs] || {}
230
+
231
+ # Legacy Support
232
+ if job_def[:options]
233
+ job_args << {} unless job_args[-1].is_a?(Hash)
234
+ job_args[-1].merge!(job_def[:options])
235
+ end
236
+
237
+ if job_class.respond_to? :perform_async
238
+ job_class.perform_async(*job_args, **job_kwargs)
239
+ else
240
+ job_class.perform_later(*job_args, **job_kwargs)
241
+ end
242
+ end
243
+ end
244
+ end
245
+
246
+ ChainBuilder.register_chain_job(ConcurrentBatchJob, 0)
247
+ ChainBuilder.register_chain_job(SerialBatchJob, 0)
248
+ end
249
+ end
@@ -0,0 +1,159 @@
1
+ module CanvasSync
2
+ module JobBatches
3
+ class ContextHash
4
+ delegate_missing_to :flatten
5
+
6
+ def initialize(bid, hash = nil)
7
+ @bid_stack = [bid]
8
+ @hash_map = {}
9
+ @dirty = false
10
+ @flattened = nil
11
+ @hash_map[bid] = hash.with_indifferent_access if hash
12
+ end
13
+
14
+ # Local is "the nearest batch with a context value"
15
+ # This allows for, for example, SerialBatchJob to have a modifiable context stored on it's main Batch
16
+ # that can be accessed transparently from one of it's internal, context-less Batches
17
+ def local_bid
18
+ bid = @bid_stack[-1]
19
+ while bid.present?
20
+ bhash = resolve_hash(bid)
21
+ return bid if bhash
22
+ bid = get_parent_bid(bid)
23
+ end
24
+ nil
25
+ end
26
+
27
+ def local
28
+ @hash_map[local_bid]
29
+ end
30
+
31
+ def own
32
+ resolve_hash(@bid_stack[-1]) || {}
33
+ end
34
+
35
+ def set_local(new_hash)
36
+ @dirty = true
37
+ local.clear.merge!(new_hash)
38
+ end
39
+
40
+ def clear
41
+ local.clear
42
+ @flattened = nil
43
+ @dirty = true
44
+ self
45
+ end
46
+
47
+ def []=(key, value)
48
+ @flattened = nil
49
+ @dirty = true
50
+ local[key] = value
51
+ end
52
+
53
+ def [](key)
54
+ bid = @bid_stack[-1]
55
+ while bid.present?
56
+ bhash = resolve_hash(bid)
57
+ return bhash[key] if bhash&.key?(key)
58
+ bid = get_parent_bid(bid)
59
+ end
60
+ nil
61
+ end
62
+
63
+ def reload!
64
+ @dirty = false
65
+ @hash_map = {}
66
+ self
67
+ end
68
+
69
+ def save!(force: false)
70
+ return unless dirty? || force
71
+ Batch.redis do |r|
72
+ r.hset("BID-#{local_bid}", 'context', JSON.unparse(local))
73
+ end
74
+ end
75
+
76
+ def dirty?
77
+ @dirty
78
+ end
79
+
80
+ def is_a?(arg)
81
+ return true if Hash <= arg
82
+ super
83
+ end
84
+
85
+ def flatten
86
+ return @flattened if @flattened
87
+
88
+ load_all
89
+ flattened = {}
90
+ @bid_stack.compact.each do |bid|
91
+ flattened.merge!(@hash_map[bid]) if @hash_map[bid]
92
+ end
93
+ flattened.freeze
94
+
95
+ @flattened = flattened.with_indifferent_access
96
+ end
97
+
98
+ def to_h
99
+ flatten
100
+ end
101
+
102
+ private
103
+
104
+ def get_parent_hash(bid)
105
+ resolve_hash(get_parent_bid(bid)).freeze
106
+ end
107
+
108
+ def get_parent_bid(bid)
109
+ index = @bid_stack.index(bid)
110
+ raise "Invalid BID #{bid}" if index.nil? # Sanity Check - this shouldn't happen
111
+
112
+ index -= 1
113
+ if index >= 0
114
+ @bid_stack[index]
115
+ else
116
+ pbid = Batch.redis do |r|
117
+ callback_params = JSON.parse(r.hget("BID-#{bid}", "callback_params") || "{}")
118
+ callback_params['for_bid'] || r.hget("BID-#{bid}", "parent_bid")
119
+ end
120
+ @bid_stack.unshift(pbid)
121
+ pbid
122
+ end
123
+ end
124
+
125
+ def resolve_hash(bid)
126
+ return nil unless bid.present?
127
+ return @hash_map[bid] if @hash_map.key?(bid)
128
+
129
+ context_json, editable = Batch.redis do |r|
130
+ r.multi do |r|
131
+ r.hget("BID-#{bid}", "context")
132
+ r.hget("BID-#{bid}", "allow_context_changes")
133
+ end
134
+ end
135
+
136
+ if context_json.present?
137
+ context_hash = JSON.parse(context_json)
138
+ context_hash = context_hash.with_indifferent_access
139
+ context_hash.each do |k, v|
140
+ v.freeze
141
+ end
142
+ context_hash.freeze unless editable
143
+
144
+ @hash_map[bid] = context_hash
145
+ else
146
+ @hash_map[bid] = nil
147
+ end
148
+ end
149
+
150
+ def load_all
151
+ resolve_hash(@bid_stack[0]).freeze
152
+ while @bid_stack[0].present?
153
+ get_parent_hash(@bid_stack[0])
154
+ end
155
+ @hash_map
156
+ end
157
+ end
158
+ end
159
+ end
@@ -0,0 +1,25 @@
1
+
2
+ local function add_bids(root, depth)
3
+ local result_data = {}
4
+
5
+ if depth > 0 then
6
+ local sbids
7
+ if depth == tonumber(ARGV[2]) and ARGV[4] then
8
+ local min, max = ARGV[4]:match('(%d+):(%d+)')
9
+ sbids = redis.call('ZRANGE', 'BID-' .. root .. '-bids', min, max)
10
+ else
11
+ sbids = redis.call('ZRANGE', 'BID-' .. root .. '-bids', 0, tonumber(ARGV[3]) - 1)
12
+ end
13
+
14
+ local sub_data = {}
15
+ for _,v in ipairs(sbids) do
16
+ table.insert(sub_data, add_bids(v, depth - 1))
17
+ end
18
+
19
+ return { root, sub_data }
20
+ end
21
+
22
+ return { root, result_data}
23
+ end
24
+
25
+ return add_bids(ARGV[1], tonumber(ARGV[2]))
@@ -0,0 +1,7 @@
1
+ module CanvasSync
2
+ module JobBatches
3
+ class BaseJob < ::ActiveJob::Base
4
+
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,22 @@
1
+ require_relative './base_job'
2
+
3
+ module CanvasSync
4
+ module JobBatches
5
+ class ConcurrentBatchJob < BaseJob
6
+ def self.make_batch(sub_jobs, **kwargs, &blk)
7
+ ManagedBatchJob.make_batch(
8
+ sub_jobs,
9
+ **kwargs,
10
+ ordered: false,
11
+ concurrency: true,
12
+ desc_prefix: 'ConcurrentBatchJob: ',
13
+ &blk
14
+ )
15
+ end
16
+
17
+ def perform(sub_jobs, **kwargs)
18
+ self.class.make_batch(sub_jobs, **kwargs)
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,170 @@
1
+ require_relative './base_job'
2
+
3
+ module CanvasSync
4
+ module JobBatches
5
+ class ManagedBatchJob < BaseJob
6
+ def self.make_batch(sub_jobs, ordered: true, concurrency: nil, context: nil, preflight_check: nil, desc_prefix: nil, &blk)
7
+ desc_prefix ||= ''
8
+
9
+ if concurrency == 0 || concurrency == nil || concurrency == true
10
+ concurrency = sub_jobs.count
11
+ elsif concurrency == false
12
+ concurrency = 1
13
+ end
14
+
15
+ root_batch = Batch.new
16
+ man_batch_id = nil
17
+
18
+ if concurrency < sub_jobs.count
19
+ man_batch_id = SecureRandom.urlsafe_base64(10)
20
+
21
+ Batch.redis do |r|
22
+ r.multi do |r|
23
+ r.hset("MNGBID-#{man_batch_id}", "root_bid", root_batch.bid)
24
+ r.hset("MNGBID-#{man_batch_id}", "ordered", ordered ? 1 : 0)
25
+ r.hset("MNGBID-#{man_batch_id}", "concurrency", concurrency)
26
+ r.hset("MNGBID-#{man_batch_id}", "preflight_check", preflight_check) if preflight_check.present?
27
+ r.expire("MNGBID-#{man_batch_id}", Batch::BID_EXPIRE_TTL)
28
+
29
+ mapped_sub_jobs = sub_jobs.each_with_index.map do |j, i|
30
+ j['_mngbid_index_'] = i # This allows duplicate jobs when a Redis Set is used
31
+ j = ::ActiveJob::Arguments.serialize([j])
32
+ JSON.unparse(j)
33
+ end
34
+ if ordered
35
+ r.rpush("MNGBID-#{man_batch_id}-jobs", mapped_sub_jobs)
36
+ else
37
+ r.sadd("MNGBID-#{man_batch_id}-jobs", mapped_sub_jobs)
38
+ end
39
+ r.expire("MNGBID-#{man_batch_id}-jobs", Batch::BID_EXPIRE_TTL)
40
+ end
41
+ end
42
+
43
+ root_batch.allow_context_changes = (concurrency == 1)
44
+ root_batch.on(:success, "#{to_s}.cleanup_redis", managed_batch_id: man_batch_id)
45
+
46
+ desc_prefix = "MGD(#{man_batch_id}): #{desc_prefix}"
47
+ end
48
+
49
+ root_batch.context = context
50
+
51
+ blk.call(ManagedBatchProxy.new(root_batch)) if blk.present?
52
+
53
+ root_batch.description = "#{desc_prefix}#{root_batch.description || 'Root'}"
54
+
55
+ root_batch.context["managed_batch_bid"] = man_batch_id if man_batch_id
56
+
57
+ if concurrency < sub_jobs.count
58
+ root_batch.jobs {}
59
+ concurrency.times do
60
+ perform_next_sequence_job(man_batch_id, skip_preflight: true)
61
+ end
62
+ else
63
+ root_batch.jobs do
64
+ sub_jobs.each do |j|
65
+ ChainBuilder.enqueue_job(j)
66
+ end
67
+ end
68
+ end
69
+
70
+ root_batch
71
+ end
72
+
73
+ def perform(sub_jobs, **kwargs)
74
+ self.class.make_batch(sub_jobs, **kwargs)
75
+ end
76
+
77
+ def self.cleanup_redis(status, options)
78
+ man_batch_id = options['managed_batch_id']
79
+ Batch.redis do |r|
80
+ r.del(
81
+ "MNGBID-#{man_batch_id}",
82
+ "MNGBID-#{man_batch_id}-jobs",
83
+ )
84
+ end
85
+ end
86
+
87
+ def self.job_succeeded_callback(status, options)
88
+ man_batch_id = options['managed_batch_id']
89
+ perform_next_sequence_job(man_batch_id)
90
+ end
91
+
92
+ protected
93
+
94
+ def self.perform_next_sequence_job(man_batch_id, skip_preflight: false)
95
+ root_bid, ordered, preflight_check = Batch.redis do |r|
96
+ r.multi do |r|
97
+ r.hget("MNGBID-#{man_batch_id}", "root_bid")
98
+ r.hget("MNGBID-#{man_batch_id}", "ordered")
99
+ r.hget("MNGBID-#{man_batch_id}", "preflight_check")
100
+ end
101
+ end
102
+
103
+ if !skip_preflight && preflight_check.present?
104
+ if preflight_check.include?(".")
105
+ clazz, method_name = preflight_check.split('.')
106
+ clazz = clazz.constantize
107
+ else
108
+ clazz = Object
109
+ method_name = preflight_check
110
+ end
111
+ preflight_check = ->(*args) { clazz.send(method_name, *args) }
112
+ else
113
+ preflight_check = ->(*args) { true }
114
+ end
115
+
116
+ ordered = CanvasSync::MiscHelper.to_boolean(ordered)
117
+
118
+ loop do
119
+ next_job_json = Batch.redis do |r|
120
+ if ordered
121
+ r.lpop("MNGBID-#{man_batch_id}-jobs")
122
+ else
123
+ r.spop("MNGBID-#{man_batch_id}-jobs")
124
+ end
125
+ end
126
+
127
+ break unless next_job_json.present?
128
+
129
+ next_job = JSON.parse(next_job_json)
130
+ next_job = ::ActiveJob::Arguments.deserialize(next_job)[0]
131
+
132
+ preflight_result = preflight_check.call(next_job)
133
+ if preflight_result == :abort
134
+ cleanup_redis(nil, { "managed_batch_id" => man_batch_id })
135
+ break
136
+ elsif !preflight_check
137
+ next
138
+ end
139
+
140
+ Batch.new(root_bid).jobs do
141
+ Batch.new.tap do |batch|
142
+ batch.description = "Managed Batch Fiber (#{man_batch_id})"
143
+ batch.on(:success, "#{self.to_s}.job_succeeded_callback", managed_batch_id: man_batch_id)
144
+ batch.jobs do
145
+ ChainBuilder.enqueue_job(next_job)
146
+ end
147
+ end
148
+ end
149
+
150
+ break
151
+ end
152
+ end
153
+
154
+ class ManagedBatchProxy
155
+ def initialize(real_batch)
156
+ @real_batch = real_batch
157
+ end
158
+
159
+ delegate_missing_to :real_batch
160
+
161
+ def jobs
162
+ raise "Managed Batches do not support calling .jobs directly!"
163
+ end
164
+
165
+ private
166
+ attr_reader :real_batch
167
+ end
168
+ end
169
+ end
170
+ end
@@ -0,0 +1,22 @@
1
+ require_relative './base_job'
2
+
3
+ module CanvasSync
4
+ module JobBatches
5
+ class SerialBatchJob < BaseJob
6
+ def self.make_batch(sub_jobs, **kwargs, &blk)
7
+ ManagedBatchJob.make_batch(
8
+ sub_jobs,
9
+ **kwargs,
10
+ ordered: true,
11
+ concurrency: false,
12
+ desc_prefix: 'SerialBatchJob: ',
13
+ &blk
14
+ )
15
+ end
16
+
17
+ def perform(sub_jobs, **kwargs)
18
+ self.class.make_batch(sub_jobs, **kwargs)
19
+ end
20
+ end
21
+ end
22
+ end