bible270 1.17.2 → 1.18.1
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/CHANGELOG.md +23 -1
- data/README.md +47 -0
- data/app/controllers/bible270/admin_progress_syncs_controller.rb +140 -0
- data/app/controllers/bible270/progress_sync_controller.rb +153 -0
- data/app/jobs/bible270/progress_sync_job.rb +31 -0
- data/app/models/bible270/checkoff.rb +5 -0
- data/app/models/bible270/participation.rb +10 -0
- data/app/models/bible270/progress_sync_delivery.rb +51 -0
- data/app/models/bible270/progress_sync_link.rb +36 -0
- data/app/models/bible270/reader.rb +1 -0
- data/app/views/bible270/admin/_progress_sync.html.erb +97 -0
- data/app/views/bible270/admin/_reader_completion_summary.html.erb +4 -0
- data/app/views/bible270/admin/_reader_list.html.erb +1 -2
- data/app/views/bible270/admin/show.html.erb +25 -7
- data/app/views/bible270/shared/_styles.html.erb +16 -0
- data/config/routes.rb +9 -1
- data/config/scripture_frames.yml +10 -0
- data/db/migrate/20260101000028_create_bible270_progress_sync.rb +48 -0
- data/lib/bible270/configuration.rb +9 -0
- data/lib/bible270/migration_reconciler.rb +133 -0
- data/lib/bible270/progress_sync/authentication.rb +61 -0
- data/lib/bible270/progress_sync/client.rb +147 -0
- data/lib/bible270/progress_sync.rb +406 -0
- data/lib/bible270/version.rb +1 -1
- data/lib/bible270.rb +1 -0
- data/lib/generators/bible270/install/templates/bible270.rb.tt +16 -0
- data/lib/tasks/bible270_progress_sync.rake +13 -0
- metadata +13 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: e05722a707b9ded33b258dbc2636df5f1bbf93b782649f84ff8fc6efa7b2d6a3
|
|
4
|
+
data.tar.gz: f53179ed25244dd464fe5815426543e0f32efa9ab7835713c4d99d382b17f03f
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: e8aab969ee632687d27b77e410448b1c41ad97b22ea79d2412e545f98d2fff39b70d01747317c15c11c0a19596ef9ba4d10edc2004841a77a2ebfc43999e1bd2
|
|
7
|
+
data.tar.gz: 83cf6dd7f75f5d0ac3bc22260f0db6166081e3321544f80f53f00bf01ee9101782ad8ad83fc96e9cbc2f31928e749f25c0f392ff58484a4b2b04acffda5e665f
|
data/CHANGELOG.md
CHANGED
|
@@ -6,9 +6,30 @@ Notable changes, following [Keep a Changelog](https://keepachangelog.com/en/1.1.
|
|
|
6
6
|
|
|
7
7
|
### Added
|
|
8
8
|
|
|
9
|
+
- let admins link matching reader accounts for one-way progress sync, including existing completions
|
|
10
|
+
- queue reliable delivery between trusted instances, with retries and optional immediate background jobs
|
|
11
|
+
|
|
12
|
+
**Setup:** Install migration `20260101000028` on each instance, configure trusted connections, and schedule delivery on the primary. Progress sync is off until configured.
|
|
13
|
+
|
|
14
|
+
### Changed
|
|
15
|
+
|
|
16
|
+
- collapse Progress sync, Their reflections, and Completions on Admin reader pages; keep the completion summary visible
|
|
17
|
+
|
|
18
|
+
### Fixed
|
|
19
|
+
|
|
20
|
+
- display the last sync time in the system time zone instead of UTC
|
|
21
|
+
|
|
22
|
+
## [1.17.2] - 2026-11-13
|
|
23
|
+
|
|
24
|
+
### Added
|
|
25
|
+
|
|
9
26
|
- add a session-remembered Show/Hide Scripture frames toggle in Admin
|
|
10
27
|
- expand the bundled Scripture frame collection
|
|
11
28
|
|
|
29
|
+
### Fixed
|
|
30
|
+
|
|
31
|
+
- update Admin assertions and stabilize headless browser focus tests
|
|
32
|
+
|
|
12
33
|
## [1.17.1] - 2026-11-13
|
|
13
34
|
|
|
14
35
|
### Added
|
|
@@ -880,7 +901,8 @@ This is the initial public release.
|
|
|
880
901
|
|
|
881
902
|
- Email sign-in requires working Action Mailer delivery in the host application. Set `config.mailer_from`; delivery is inline by default, or set `email_sign_in_deliver_later` when a queue backend is available.
|
|
882
903
|
|
|
883
|
-
[Unreleased]: https://github.com/avonderluft/bible270/compare/v1.17.
|
|
904
|
+
[Unreleased]: https://github.com/avonderluft/bible270/compare/v1.17.2...main
|
|
905
|
+
[1.17.2]: https://github.com/avonderluft/bible270/compare/v1.17.1...v1.17.2
|
|
884
906
|
[1.17.1]: https://github.com/avonderluft/bible270/compare/v1.17.0...v1.17.1
|
|
885
907
|
[1.17.0]: https://github.com/avonderluft/bible270/compare/v1.16.0...v1.17.0
|
|
886
908
|
[1.16.0]: https://github.com/avonderluft/bible270/compare/v1.15.1...v1.16.0
|
data/README.md
CHANGED
|
@@ -264,6 +264,8 @@ The `admin_resolver` callback takes precedence over `admin_emails`.
|
|
|
264
264
|
|
|
265
265
|
Authorized readers get an **Admin** link. **View as non-admin** hides admin details and disables all administration for this session, including role and membership changes. You remain signed in; reflections and active check-offs still work. Use **Return to admin view** in the Admin tab or sign in again to restore access. Roles and other sessions are unchanged.
|
|
266
266
|
|
|
267
|
+
Reader pages start with **Progress sync**, **Their reflections**, and **Completions** collapsed. Completion counts, percentage, and schedule status remain visible.
|
|
268
|
+
|
|
267
269
|
The panel supports:
|
|
268
270
|
|
|
269
271
|
- Sort active readers by name, completed days, activity, or consistency; **Reader Stats** follows the same sort.
|
|
@@ -274,6 +276,7 @@ The panel supports:
|
|
|
274
276
|
- Delete unprotected readers **and all their check-offs and reflections across runs**.
|
|
275
277
|
- Hide (reversibly) or delete reflections at `<mount>/admin/comments`. Posts are public immediately, without approval.
|
|
276
278
|
- Manage [Scripture frame](#scripture-frame) texts.
|
|
279
|
+
- Link readers to trusted instances for [one-way progress sync](#progress-sync).
|
|
277
280
|
- Send individually addressed email: **Write to everyone** reaches active readers; **Write to all admins** includes alumni admins. Both require an email address.
|
|
278
281
|
|
|
279
282
|
To print a progress report ordered by completed days:
|
|
@@ -310,6 +313,50 @@ Each reader's **Past runs / history** table shows read-only start/end dates, arc
|
|
|
310
313
|
|
|
311
314
|
Admin templates include `bible270/shared/admin_confirmations`, even with custom layouts. Keep this partial in host template overrides; no layout include is needed.
|
|
312
315
|
|
|
316
|
+
### Progress sync
|
|
317
|
+
|
|
318
|
+
Admins can link a reader to existing, active accounts on other installations with the same email. Readers sign in only on the primary site. New check-offs sync automatically; **Sync existing progress** copies earlier completions. Both add only missing check-offs—never uncheck readings, change dates, or copy reflections.
|
|
319
|
+
|
|
320
|
+
Install migration `20260101000028` on every participating installation. Site administrators configure trust in their host initializers; no destination credentials are entered in Admin.
|
|
321
|
+
|
|
322
|
+
On the **primary**:
|
|
323
|
+
|
|
324
|
+
```ruby
|
|
325
|
+
config.progress_sync_instance_id = 'primary'
|
|
326
|
+
if (sync_secret = ENV['B270_PRIMARY_CHURCH_SYNC_SECRET'])
|
|
327
|
+
config.progress_sync_destinations = {
|
|
328
|
+
'church' => {
|
|
329
|
+
label: 'Church', url: 'https://church.example/daily-bread',
|
|
330
|
+
secret: sync_secret
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
end
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
On the **destination**:
|
|
337
|
+
|
|
338
|
+
```ruby
|
|
339
|
+
if (sync_secret = ENV['B270_PRIMARY_CHURCH_SYNC_SECRET'])
|
|
340
|
+
config.progress_sync_sources = { 'primary' => { secret: sync_secret } }
|
|
341
|
+
end
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
Supply the secret at container runtime, not during image builds. Without it, sync stays disabled.
|
|
345
|
+
|
|
346
|
+
Use the same randomly generated secret on both sides, at least 32 characters; `bin/rails secret` can generate one. Use a separate secret for each destination. URLs must be canonical HTTPS engine mount URLs, without redirects. Trust authorizes the primary's admins to link accounts by email; grant it only to installations you control or trust.
|
|
347
|
+
|
|
348
|
+
Schedule this command **every minute on the primary**, using the host's scheduler:
|
|
349
|
+
|
|
350
|
+
```bash
|
|
351
|
+
RAILS_ENV=production bin/rails bible270:progress_sync:deliver
|
|
352
|
+
```
|
|
353
|
+
|
|
354
|
+
If the host already has a **persistent Active Job backend and running worker**, also set `config.progress_sync_deliver_later = true` for immediate delivery. Keep the scheduled task for retries and recovery; inline and in-memory adapters are not used. No worker is needed on destinations.
|
|
355
|
+
|
|
356
|
+
In **Admin → reader → Progress sync**, select a destination, **Find account**, then **Link account**. Repeat for other destinations. Use **Sync existing progress** when wanted. Status, pending deliveries, and the latest result appear beside each link; **Unlink** stops queued updates without deleting progress. A request already being delivered may still finish.
|
|
357
|
+
|
|
358
|
+
Reading assignments must match, though start dates may differ. Account links use fixed reader/run identities after matching. Alumni status, run changes (including restart/revert), or changed assignments require explicit relinking. Imported progress is never forwarded. After repeated delivery failures, inspect the error, relink, and copy existing progress again if needed.
|
|
359
|
+
|
|
313
360
|
### Consistency ranking
|
|
314
361
|
|
|
315
362
|
Consistency is the average end-of-day score on a dated schedule:
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'bible270/progress_sync'
|
|
4
|
+
require 'bible270/progress_sync/client'
|
|
5
|
+
|
|
6
|
+
module Bible270
|
|
7
|
+
class AdminProgressSyncsController < ApplicationController
|
|
8
|
+
CANDIDATE_SESSION_KEY = :bible270_progress_sync_candidate
|
|
9
|
+
CANDIDATE_PURPOSE = 'progress-sync-link'
|
|
10
|
+
|
|
11
|
+
before_action :require_admin!
|
|
12
|
+
before_action :require_admin_view!
|
|
13
|
+
before_action :load_reader
|
|
14
|
+
|
|
15
|
+
rescue_from ProgressSync::Error, with: :sync_error
|
|
16
|
+
rescue_from ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique, with: :invalid_link
|
|
17
|
+
|
|
18
|
+
# Also used by the partial after the lookup redirect; no Admin#show setup is needed.
|
|
19
|
+
def self.candidate_for(token, reader:, admin:)
|
|
20
|
+
candidate = verifier.verified(token.to_s, purpose: CANDIDATE_PURPOSE)
|
|
21
|
+
return unless candidate.is_a?(Hash) && candidate['remote'].is_a?(Hash)
|
|
22
|
+
|
|
23
|
+
context = link_context(reader: reader, admin: admin, destination: candidate['destination'])
|
|
24
|
+
return unless context.all? { |key, value| candidate[key] == value }
|
|
25
|
+
return unless normalized_email(candidate['remote']['email']) == context['email']
|
|
26
|
+
|
|
27
|
+
candidate
|
|
28
|
+
rescue ProgressSync::Error
|
|
29
|
+
nil
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
def self.verifier
|
|
33
|
+
Rails.application.message_verifier('bible270-progress-sync-link')
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
def self.link_context(reader:, admin:, destination:)
|
|
37
|
+
raise ProgressSync::Unavailable, 'Progress sync migration is not installed' unless ProgressSync.available?
|
|
38
|
+
|
|
39
|
+
membership = Participation.chosen.active.find_by(reader_id: reader.id)
|
|
40
|
+
raise ProgressSync::Conflict, 'This reader must be active in the current run before linking progress' unless membership
|
|
41
|
+
|
|
42
|
+
email = normalized_email(reader.email)
|
|
43
|
+
# Construction validates the allowlist, instance ID, HTTPS URL and secret, without HTTP.
|
|
44
|
+
ProgressSync::Client.new(destination.to_s)
|
|
45
|
+
entry = Bible270.config.progress_sync_destinations.fetch(destination.to_s)
|
|
46
|
+
{
|
|
47
|
+
'reader_id' => reader.id, 'admin_id' => admin.id,
|
|
48
|
+
'participation_id' => membership.id, 'generation' => membership.progress_sync_generation,
|
|
49
|
+
'destination' => destination.to_s, 'destination_url' => (entry[:url] || entry['url']).to_s.chomp('/'),
|
|
50
|
+
'instance_id' => Bible270.config.progress_sync_instance_id.to_s, 'email' => email
|
|
51
|
+
}
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
def self.normalized_email(email)
|
|
55
|
+
value = email.to_s.strip.downcase
|
|
56
|
+
unless value.bytesize <= 320 && value.match?(%r{\A[^@\s]+@[^@\s]+\z})
|
|
57
|
+
raise ProgressSync::Conflict, 'This reader needs a valid email address before linking progress'
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
value
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
def lookup
|
|
64
|
+
session.delete(CANDIDATE_SESSION_KEY)
|
|
65
|
+
context = self.class.link_context(reader: @reader, admin: current_reader, destination: params[:destination])
|
|
66
|
+
remote = ProgressSync.lookup(destination: context['destination'], email: context['email'])
|
|
67
|
+
unless remote.is_a?(Hash) && self.class.normalized_email(remote['email']) == context['email']
|
|
68
|
+
raise ProgressSync::Conflict, 'Destination account email does not match this reader'
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
# Keep only the authenticated lookup fields, never destination credentials.
|
|
72
|
+
candidate = context.merge('remote' => remote.slice('reader_id', 'participation_id', 'generation', 'name', 'email', 'plan_fingerprint'))
|
|
73
|
+
session[CANDIDATE_SESSION_KEY] = self.class.verifier.generate(candidate, expires_in: 10.minutes, purpose: CANDIDATE_PURPOSE)
|
|
74
|
+
redirect_to_panel
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
def create
|
|
78
|
+
session.delete(CANDIDATE_SESSION_KEY)
|
|
79
|
+
candidate = confirmed_candidate!
|
|
80
|
+
# Match the core's lock order so confirmation and link creation see the same source identity.
|
|
81
|
+
Participation.find(candidate['participation_id']).plan_run.with_lock do
|
|
82
|
+
@reader.with_lock do
|
|
83
|
+
candidate = confirmed_candidate!
|
|
84
|
+
ProgressSync.link!(reader: @reader, destination: candidate['destination'], remote: candidate['remote'],
|
|
85
|
+
expected_participation_id: candidate['participation_id'])
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
redirect_to_panel(notice: 'Account linked. Existing progress is unchanged.')
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
def copy
|
|
92
|
+
ensure_available!
|
|
93
|
+
delivery = ProgressSync.copy_existing!(owned_link)
|
|
94
|
+
redirect_to_panel(notice: delivery ? 'Existing progress queued.' : 'There is no existing progress to sync.')
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
def destroy
|
|
98
|
+
ensure_available!
|
|
99
|
+
owned_link.destroy!
|
|
100
|
+
redirect_to_panel(notice: 'Account unlinked. All check-offs are unchanged.')
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
private
|
|
104
|
+
|
|
105
|
+
def load_reader
|
|
106
|
+
@reader = Reader.find(params[:reader_id])
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
def ensure_available!
|
|
110
|
+
raise ProgressSync::Unavailable, 'Progress sync migration is not installed' unless ProgressSync.available?
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
def confirmed_candidate!
|
|
114
|
+
candidate = self.class.candidate_for(params[:candidate], reader: @reader, admin: current_reader)
|
|
115
|
+
unless candidate && params[:destination].to_s == candidate['destination']
|
|
116
|
+
raise ProgressSync::Conflict, 'Account confirmation expired or changed. Find the account again.'
|
|
117
|
+
end
|
|
118
|
+
|
|
119
|
+
candidate
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
def owned_link
|
|
123
|
+
ProgressSyncLink.joins(:participation).where(bible270_participations: { reader_id: @reader.id }).find(params[:id])
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
def redirect_to_panel(**flash)
|
|
127
|
+
redirect_to admin_reader_path(@reader, anchor: 'b270-progress-sync'), status: :see_other, **flash
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
def sync_error(error)
|
|
131
|
+
session.delete(CANDIDATE_SESSION_KEY)
|
|
132
|
+
redirect_to_panel(alert: error.message)
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
def invalid_link(_error)
|
|
136
|
+
session.delete(CANDIDATE_SESSION_KEY)
|
|
137
|
+
redirect_to_panel(alert: 'This account could not be linked. It may already be linked.')
|
|
138
|
+
end
|
|
139
|
+
end
|
|
140
|
+
end
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'json'
|
|
4
|
+
require 'bible270/progress_sync'
|
|
5
|
+
require 'bible270/progress_sync/authentication'
|
|
6
|
+
|
|
7
|
+
module Bible270
|
|
8
|
+
class ProgressSyncController < ActionController::API
|
|
9
|
+
Sync = ProgressSync
|
|
10
|
+
Authentication = Sync::Authentication
|
|
11
|
+
|
|
12
|
+
def lookup
|
|
13
|
+
email = @payload['email']
|
|
14
|
+
unless email.is_a?(String) && email.bytesize <= 320 && email.strip.match?(%r{\A[^@\s]+@[^@\s]+\z})
|
|
15
|
+
raise Sync::Conflict, 'A valid reader email is required'
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
email = email.strip.downcase
|
|
19
|
+
# Ambiguity includes archived accounts: do not select one identity merely
|
|
20
|
+
# because the other account with the same address is currently inactive.
|
|
21
|
+
readers = matching_readers(email)
|
|
22
|
+
raise Sync::Conflict, 'No unique active reader matches that email' unless readers.length == 1
|
|
23
|
+
|
|
24
|
+
reader = readers.first
|
|
25
|
+
membership = Participation.chosen.find_by(reader_id: reader.id)
|
|
26
|
+
with_membership_lock(membership, reader.id) do |current|
|
|
27
|
+
unless reader.reload.email.to_s.strip.downcase == email && matching_readers(email).map(&:id) == [reader.id]
|
|
28
|
+
raise Sync::Conflict, 'No unique active reader matches that email'
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
render json: { reader_id: reader.id, participation_id: current.id, generation: current.progress_sync_generation,
|
|
32
|
+
name: reader.display_name, email: email, plan_fingerprint: Sync.fingerprint }
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
def complete
|
|
37
|
+
reader_id = integer!('reader_id', minimum: 1)
|
|
38
|
+
participation_id = integer!('participation_id', minimum: 1)
|
|
39
|
+
generation = integer!('generation', minimum: 0)
|
|
40
|
+
readings = validated_readings!
|
|
41
|
+
membership = Participation.find_by(id: participation_id, reader_id: reader_id)
|
|
42
|
+
with_membership_lock(membership, reader_id) do |current|
|
|
43
|
+
unless current.progress_sync_generation == generation
|
|
44
|
+
raise Sync::Conflict, 'Linked membership changed; explicitly relink'
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
existing = current.checkoffs.pluck(:day, :track, :part).to_set
|
|
48
|
+
missing = readings.reject { |triple| existing.include?(triple) }
|
|
49
|
+
Sync.suppress do
|
|
50
|
+
if missing.any?
|
|
51
|
+
Checkoff.insert_all(missing.map do |day, track, part|
|
|
52
|
+
{ reader_id: reader_id, participation_id: current.id, day: day, track: track, part: part }
|
|
53
|
+
end)
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
render json: { added: missing.length, existing: readings.length - missing.length }
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
private
|
|
61
|
+
|
|
62
|
+
# Authenticate before calling super: ActionController's instrumentation reads
|
|
63
|
+
# filtered_parameters (and therefore parses JSON) before ordinary callbacks.
|
|
64
|
+
def process_action(*)
|
|
65
|
+
authenticate_request!
|
|
66
|
+
return if performed?
|
|
67
|
+
|
|
68
|
+
super
|
|
69
|
+
rescue Sync::Unauthorized
|
|
70
|
+
render json: { error: 'Progress sync authentication failed' }, status: :unauthorized
|
|
71
|
+
rescue Sync::Conflict, ActiveRecord::RecordNotFound, ActiveRecord::RecordInvalid
|
|
72
|
+
render json: { error: 'Reader, membership, plan, or completion batch is incompatible' }, status: :conflict
|
|
73
|
+
rescue Sync::Unavailable, Sync::ConfigurationError
|
|
74
|
+
render json: { error: 'Progress sync is unavailable' }, status: :service_unavailable
|
|
75
|
+
rescue JSON::ParserError, EncodingError
|
|
76
|
+
render json: { error: 'Invalid JSON payload' }, status: :bad_request
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
def authenticate_request!
|
|
80
|
+
if request.content_length.to_i > Authentication::MAX_BYTES
|
|
81
|
+
render json: { error: 'Progress sync request is too large' }, status: 413
|
|
82
|
+
return
|
|
83
|
+
end
|
|
84
|
+
body = request.body.read(Authentication::MAX_BYTES + 1)
|
|
85
|
+
request.body.rewind
|
|
86
|
+
if body.bytesize > Authentication::MAX_BYTES
|
|
87
|
+
render json: { error: 'Progress sync request is too large' }, status: 413
|
|
88
|
+
return
|
|
89
|
+
end
|
|
90
|
+
config = Bible270.config
|
|
91
|
+
sources = config.progress_sync_sources if config.respond_to?(:progress_sync_sources)
|
|
92
|
+
Authentication.authenticate!(headers: request.headers, sources: sources, method: request.request_method,
|
|
93
|
+
path: request.original_fullpath.split('?', 2).first, body: body)
|
|
94
|
+
raise Sync::Unavailable, 'Progress sync migration is not installed' unless Sync.available?
|
|
95
|
+
|
|
96
|
+
@payload = JSON.parse(body)
|
|
97
|
+
raise Sync::Conflict, 'A JSON object is required' unless @payload.is_a?(Hash)
|
|
98
|
+
raise Sync::Conflict, 'Reading plans differ' unless @payload['plan_fingerprint'] == Sync.fingerprint
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
def matching_readers(email)
|
|
102
|
+
# SQL LOWER/TRIM differ by adapter and do not match Ruby's normalization
|
|
103
|
+
# for all case mappings and surrounding whitespace. Lookup is infrequent;
|
|
104
|
+
# scan only identity columns in batches and stop once ambiguity is proven.
|
|
105
|
+
Reader.select(:id, :email).find_each.lazy.select do |reader|
|
|
106
|
+
reader.email.to_s.strip.downcase == email
|
|
107
|
+
end.take(2).force
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
def integer!(key, minimum:)
|
|
111
|
+
value = @payload[key]
|
|
112
|
+
raise Sync::Conflict, 'Invalid linked identity' unless value.is_a?(Integer) && value >= minimum
|
|
113
|
+
|
|
114
|
+
value
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
def validated_readings!
|
|
118
|
+
readings = @payload['readings']
|
|
119
|
+
unless readings.is_a?(Array) && readings.length <= 5000
|
|
120
|
+
raise Sync::Conflict, 'A batch must contain at most 5000 readings'
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
readings.each do |triple|
|
|
124
|
+
unless triple.is_a?(Array) && triple.length == 3
|
|
125
|
+
raise Sync::Conflict, 'Readings must be triples'
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
day, track, part = triple
|
|
129
|
+
unless day.is_a?(Integer) && part.is_a?(Integer) && Plan.valid_day?(day) &&
|
|
130
|
+
Plan::TRACKS.key?(track) && Plan.valid_part?(day, track, part)
|
|
131
|
+
raise Sync::Conflict, 'Invalid reading'
|
|
132
|
+
end
|
|
133
|
+
end
|
|
134
|
+
readings.uniq
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
def with_membership_lock(membership, reader_id)
|
|
138
|
+
raise Sync::Conflict, 'Linked membership no longer exists' unless membership
|
|
139
|
+
|
|
140
|
+
PlanRun.find(membership.plan_run_id).with_lock do
|
|
141
|
+
Reader.find(reader_id).with_lock do
|
|
142
|
+
membership.reload
|
|
143
|
+
unless membership.active? && PlanRun.where(id: membership.plan_run_id, current: true).exists? &&
|
|
144
|
+
Participation.chosen.where(id: membership.id).exists? && @payload['plan_fingerprint'] == Sync.fingerprint
|
|
145
|
+
raise Sync::Conflict, 'Linked membership is no longer active or compatible'
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
yield membership
|
|
149
|
+
end
|
|
150
|
+
end
|
|
151
|
+
end
|
|
152
|
+
end
|
|
153
|
+
end
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'active_job'
|
|
4
|
+
require 'bible270/progress_sync'
|
|
5
|
+
|
|
6
|
+
module Bible270
|
|
7
|
+
class ProgressSyncJob < ActiveJob::Base
|
|
8
|
+
class EnqueueFailure < StandardError; end
|
|
9
|
+
|
|
10
|
+
around_enqueue :sanitize_enqueue_failure
|
|
11
|
+
|
|
12
|
+
def perform(delivery_id)
|
|
13
|
+
return if delivery_id.nil?
|
|
14
|
+
|
|
15
|
+
# Retry timing and claims live in the outbox. The scheduled rake task
|
|
16
|
+
# recovers enqueue failures, expired leases, and transient delivery errors.
|
|
17
|
+
ProgressSync.deliver_pending(delivery_id: delivery_id)
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
private
|
|
21
|
+
|
|
22
|
+
# Active Job's enqueue instrumentation otherwise logs the adapter exception's
|
|
23
|
+
# message before the model can rescue it; that message can contain credentials.
|
|
24
|
+
def sanitize_enqueue_failure
|
|
25
|
+
yield
|
|
26
|
+
self.enqueue_error = EnqueueFailure.new(enqueue_error.class.name) if enqueue_error
|
|
27
|
+
rescue StandardError => e
|
|
28
|
+
raise EnqueueFailure, e.class.name, cause: nil
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
end
|
|
@@ -10,6 +10,7 @@ module Bible270
|
|
|
10
10
|
belongs_to :reader, class_name: 'Bible270::Reader'
|
|
11
11
|
belongs_to :participation, class_name: 'Bible270::Participation', inverse_of: :checkoffs
|
|
12
12
|
|
|
13
|
+
after_create :capture_progress_sync
|
|
13
14
|
before_validation :assign_participation
|
|
14
15
|
validate :participation_matches_reader
|
|
15
16
|
validate :participation_is_writable
|
|
@@ -78,6 +79,10 @@ module Bible270
|
|
|
78
79
|
|
|
79
80
|
private
|
|
80
81
|
|
|
82
|
+
def capture_progress_sync
|
|
83
|
+
ProgressSync.capture(participation, [[day, track, part]])
|
|
84
|
+
end
|
|
85
|
+
|
|
81
86
|
def assign_participation
|
|
82
87
|
self.participation ||= reader&.participation
|
|
83
88
|
end
|
|
@@ -10,6 +10,8 @@ module Bible270
|
|
|
10
10
|
belongs_to :plan_run, class_name: 'Bible270::PlanRun', inverse_of: :participations
|
|
11
11
|
has_many :checkoffs, class_name: 'Bible270::Checkoff', dependent: :destroy, inverse_of: :participation
|
|
12
12
|
|
|
13
|
+
before_update :invalidate_progress_sync_generation
|
|
14
|
+
|
|
13
15
|
validates :reader_id, uniqueness: { scope: :plan_run_id }
|
|
14
16
|
validates :joined_at, presence: true
|
|
15
17
|
|
|
@@ -60,6 +62,14 @@ module Bible270
|
|
|
60
62
|
self
|
|
61
63
|
end
|
|
62
64
|
|
|
65
|
+
# Reverting a run or reactivating an alumnus must not silently restore a sync link.
|
|
66
|
+
def invalidate_progress_sync_generation
|
|
67
|
+
return unless has_attribute?(:progress_sync_generation) && will_save_change_to_active? && !active?
|
|
68
|
+
|
|
69
|
+
self.progress_sync_generation += 1
|
|
70
|
+
end
|
|
71
|
+
private :invalidate_progress_sync_generation
|
|
72
|
+
|
|
63
73
|
def ensure_writable!
|
|
64
74
|
unless active? && plan_run.current?
|
|
65
75
|
raise ArchivedProgress, 'Archived progress is read-only; activate the reader in the current run first'
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Bible270
|
|
4
|
+
class ProgressSyncDelivery < ApplicationRecord
|
|
5
|
+
self.table_name = 'bible270_progress_sync_deliveries'
|
|
6
|
+
|
|
7
|
+
belongs_to :progress_sync_link, class_name: 'Bible270::ProgressSyncLink', inverse_of: :deliveries
|
|
8
|
+
|
|
9
|
+
after_create_commit :enqueue_immediate_delivery
|
|
10
|
+
|
|
11
|
+
validates :readings, presence: true
|
|
12
|
+
validates :attempts, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
|
|
13
|
+
validates :next_attempt_at, presence: true
|
|
14
|
+
|
|
15
|
+
scope :pending, -> { where(delivered_at: nil) }
|
|
16
|
+
scope :due, ->(now = Time.current) {
|
|
17
|
+
pending.where('next_attempt_at <= ?', now).where('locked_until IS NULL OR locked_until <= ?', now)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
def delivered? = delivered_at.present?
|
|
21
|
+
|
|
22
|
+
private
|
|
23
|
+
|
|
24
|
+
def enqueue_immediate_delivery
|
|
25
|
+
return unless Bible270.config.progress_sync_deliver_later
|
|
26
|
+
|
|
27
|
+
adapter = ProgressSyncJob.queue_adapter
|
|
28
|
+
if adapter.is_a?(ActiveJob::QueueAdapters::InlineAdapter) || adapter.is_a?(ActiveJob::QueueAdapters::AsyncAdapter)
|
|
29
|
+
warn_delivery_enqueue("Immediate delivery skipped: #{adapter.class.name} is not a durable worker adapter.")
|
|
30
|
+
return
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
unless ProgressSyncJob.perform_later(id)
|
|
34
|
+
warn_delivery_enqueue('Immediate delivery enqueue was not accepted.')
|
|
35
|
+
end
|
|
36
|
+
rescue StandardError => e
|
|
37
|
+
warn_delivery_enqueue("Immediate delivery enqueue failed (#{e.class.name}).")
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def warn_delivery_enqueue(detail)
|
|
41
|
+
message = "[Bible270] #{detail} Progress sync outbox retained; configure a durable Active Job adapter and worker, " \
|
|
42
|
+
'and schedule bible270:progress_sync:deliver every minute as fallback.'
|
|
43
|
+
sync_logger = defined?(Rails) && Rails.logger
|
|
44
|
+
sync_logger ||= self.class.logger
|
|
45
|
+
sync_logger ? sync_logger.warn(message) : warn(message)
|
|
46
|
+
rescue StandardError
|
|
47
|
+
# Logging and optional enqueue failures must never invalidate a checkoff.
|
|
48
|
+
nil
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
end
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Bible270
|
|
4
|
+
class ProgressSyncLink < ApplicationRecord
|
|
5
|
+
self.table_name = 'bible270_progress_sync_links'
|
|
6
|
+
|
|
7
|
+
belongs_to :participation, class_name: 'Bible270::Participation'
|
|
8
|
+
has_many :deliveries, class_name: 'Bible270::ProgressSyncDelivery', dependent: :destroy,
|
|
9
|
+
inverse_of: :progress_sync_link
|
|
10
|
+
|
|
11
|
+
attr_readonly :participation_id, :source_generation, :destination, :destination_url,
|
|
12
|
+
:remote_reader_id, :remote_participation_id, :remote_generation,
|
|
13
|
+
:remote_name, :email, :plan_fingerprint
|
|
14
|
+
|
|
15
|
+
validates :source_generation, :remote_generation, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
|
|
16
|
+
validates :remote_reader_id, :remote_participation_id, numericality: { only_integer: true, greater_than: 0 }
|
|
17
|
+
validates :destination, :destination_url, :remote_name, :email, :plan_fingerprint, presence: true
|
|
18
|
+
validates :state, inclusion: { in: %w[active paused] }
|
|
19
|
+
validates :destination, uniqueness: { scope: :participation_id, conditions: -> { where(state: 'active') } }, if: :active?
|
|
20
|
+
|
|
21
|
+
scope :active, -> { where(state: 'active') }
|
|
22
|
+
|
|
23
|
+
def active? = state == 'active'
|
|
24
|
+
def paused? = state == 'paused'
|
|
25
|
+
def usable? = active? && ProgressSync.link_usable?(self)
|
|
26
|
+
def pending_count = deliveries.where(delivered_at: nil).count
|
|
27
|
+
def delivered_count = deliveries.where.not(delivered_at: nil).count
|
|
28
|
+
|
|
29
|
+
def status
|
|
30
|
+
return 'Needs attention' if paused? || last_error.present? || !usable?
|
|
31
|
+
return 'Pending' if pending_count.positive?
|
|
32
|
+
|
|
33
|
+
last_synced_at ? 'Synced' : 'Ready'
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
end
|