glib-web 8.1.0 → 8.2.0

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.
Files changed (166) hide show
  1. checksums.yaml +4 -4
  2. data/app/controllers/concerns/glib/json/libs.rb +16 -0
  3. data/app/helpers/glib/app_feature_support_helper.rb +33 -8
  4. data/app/helpers/glib/json_ui/view_builder/fields.rb +74 -9
  5. data/app/helpers/glib/json_ui/view_builder.rb +15 -0
  6. data/app/jobs/glib/scheduled_job.rb +581 -0
  7. data/app/jobs/glib/scheduled_job_tick.rb +21 -0
  8. data/app/models/glib/scheduled_job_run.rb +16 -0
  9. data/app/views/json_ui/garage/forms/action_text.json.jbuilder +34 -0
  10. data/app/views/json_ui/garage/forms/action_text_attachment.json.jbuilder +7 -0
  11. data/app/views/json_ui/garage/forms/action_text_library.json.jbuilder +26 -0
  12. data/app/views/json_ui/garage/forms/action_text_preview.json.jbuilder +9 -0
  13. data/app/views/json_ui/garage/forms/index.json.jbuilder +6 -0
  14. data/app/views/json_ui/garage/forms/pickers.json.jbuilder +7 -0
  15. data/app/views/json_ui/garage/test_page/_header.json.jbuilder +6 -0
  16. data/app/views/json_ui/garage/test_page/fields_actionText.json.jbuilder +87 -0
  17. data/app/views/json_ui/garage/test_page/fields_sign.json.jbuilder +34 -3
  18. data/app/views/json_ui/garage/test_page/form_dirty_hooks.json.jbuilder +22 -0
  19. data/app/views/json_ui/garage/test_page/form_hidden_panels.json.jbuilder +124 -0
  20. data/app/views/layouts/json_ui/renderer.html.erb +11 -1
  21. data/engines/blog/README.md +172 -0
  22. data/engines/blog/app/assets/stylesheets/glib/blog/admin.css +855 -0
  23. data/engines/blog/app/assets/stylesheets/glib/blog/themes/clean.css +816 -0
  24. data/engines/blog/app/assets/stylesheets/glib/blog/themes/editorial.css +631 -0
  25. data/engines/blog/app/controllers/concerns/glib/blog/admin/media_listing.rb +27 -0
  26. data/engines/blog/app/controllers/concerns/glib/blog/pagination.rb +14 -0
  27. data/engines/blog/app/controllers/glib/blog/admin/application_controller.rb +28 -0
  28. data/engines/blog/app/controllers/glib/blog/admin/authors_controller.rb +55 -0
  29. data/engines/blog/app/controllers/glib/blog/admin/categories_controller.rb +53 -0
  30. data/engines/blog/app/controllers/glib/blog/admin/comment_replies_controller.rb +34 -0
  31. data/engines/blog/app/controllers/glib/blog/admin/comments_controller.rb +50 -0
  32. data/engines/blog/app/controllers/glib/blog/admin/dashboards_controller.rb +34 -0
  33. data/engines/blog/app/controllers/glib/blog/admin/direct_uploads_controller.rb +30 -0
  34. data/engines/blog/app/controllers/glib/blog/admin/editor_attachments_controller.rb +16 -0
  35. data/engines/blog/app/controllers/glib/blog/admin/media_item_trashes_controller.rb +43 -0
  36. data/engines/blog/app/controllers/glib/blog/admin/media_items_controller.rb +61 -0
  37. data/engines/blog/app/controllers/glib/blog/admin/media_picks_controller.rb +19 -0
  38. data/engines/blog/app/controllers/glib/blog/admin/post_bulk_actions_controller.rb +33 -0
  39. data/engines/blog/app/controllers/glib/blog/admin/posts_controller.rb +79 -0
  40. data/engines/blog/app/controllers/glib/blog/admin/settings_controller.rb +27 -0
  41. data/engines/blog/app/controllers/glib/blog/admin/tags_controller.rb +46 -0
  42. data/engines/blog/app/controllers/glib/blog/application_controller.rb +90 -0
  43. data/engines/blog/app/controllers/glib/blog/authors_controller.rb +15 -0
  44. data/engines/blog/app/controllers/glib/blog/categories_controller.rb +15 -0
  45. data/engines/blog/app/controllers/glib/blog/comments_controller.rb +41 -0
  46. data/engines/blog/app/controllers/glib/blog/posts_controller.rb +47 -0
  47. data/engines/blog/app/controllers/glib/blog/tags_controller.rb +15 -0
  48. data/engines/blog/app/helpers/glib/blog/admin_helper.rb +57 -0
  49. data/engines/blog/app/helpers/glib/blog/comments_helper.rb +16 -0
  50. data/engines/blog/app/helpers/glib/blog/post_list_helper.rb +26 -0
  51. data/engines/blog/app/helpers/glib/blog/theme_helper.rb +85 -0
  52. data/engines/blog/app/jobs/glib/blog/purge_trash_job.rb +13 -0
  53. data/engines/blog/app/models/concerns/glib/blog/sluggable.rb +72 -0
  54. data/engines/blog/app/models/concerns/glib/blog/uses_media.rb +35 -0
  55. data/engines/blog/app/models/glib/blog/application_record.rb +7 -0
  56. data/engines/blog/app/models/glib/blog/author.rb +47 -0
  57. data/engines/blog/app/models/glib/blog/category.rb +53 -0
  58. data/engines/blog/app/models/glib/blog/comment.rb +66 -0
  59. data/engines/blog/app/models/glib/blog/comment_token.rb +30 -0
  60. data/engines/blog/app/models/glib/blog/media_item.rb +121 -0
  61. data/engines/blog/app/models/glib/blog/media_upload.rb +97 -0
  62. data/engines/blog/app/models/glib/blog/media_usage.rb +10 -0
  63. data/engines/blog/app/models/glib/blog/post.rb +110 -0
  64. data/engines/blog/app/models/glib/blog/post_view.rb +24 -0
  65. data/engines/blog/app/models/glib/blog/setting.rb +55 -0
  66. data/engines/blog/app/models/glib/blog/slug_redirect.rb +7 -0
  67. data/engines/blog/app/models/glib/blog/tag.rb +15 -0
  68. data/engines/blog/app/models/glib/blog/tagging.rb +10 -0
  69. data/engines/blog/app/policies/glib/blog/admin/author_policy.rb +11 -0
  70. data/engines/blog/app/policies/glib/blog/admin/category_policy.rb +11 -0
  71. data/engines/blog/app/policies/glib/blog/admin/comment_policy.rb +16 -0
  72. data/engines/blog/app/policies/glib/blog/admin/comment_reply_policy.rb +12 -0
  73. data/engines/blog/app/policies/glib/blog/admin/dashboard_policy.rb +11 -0
  74. data/engines/blog/app/policies/glib/blog/admin/direct_upload_policy.rb +11 -0
  75. data/engines/blog/app/policies/glib/blog/admin/editor_attachment_policy.rb +11 -0
  76. data/engines/blog/app/policies/glib/blog/admin/media_item_policy.rb +20 -0
  77. data/engines/blog/app/policies/glib/blog/admin/media_item_trash_policy.rb +11 -0
  78. data/engines/blog/app/policies/glib/blog/admin/media_pick_policy.rb +11 -0
  79. data/engines/blog/app/policies/glib/blog/admin/post_bulk_action_policy.rb +12 -0
  80. data/engines/blog/app/policies/glib/blog/admin/post_policy.rb +16 -0
  81. data/engines/blog/app/policies/glib/blog/admin/setting_policy.rb +11 -0
  82. data/engines/blog/app/policies/glib/blog/admin/tag_policy.rb +11 -0
  83. data/engines/blog/app/policies/glib/blog/application_policy.rb +16 -0
  84. data/engines/blog/app/policies/glib/blog/author_policy.rb +9 -0
  85. data/engines/blog/app/policies/glib/blog/category_policy.rb +9 -0
  86. data/engines/blog/app/policies/glib/blog/comment_policy.rb +11 -0
  87. data/engines/blog/app/policies/glib/blog/post_policy.rb +9 -0
  88. data/engines/blog/app/policies/glib/blog/tag_policy.rb +9 -0
  89. data/engines/blog/app/views/glib/blog/admin/_delete_button.json.jbuilder +24 -0
  90. data/engines/blog/app/views/glib/blog/admin/_nav.json.jbuilder +45 -0
  91. data/engines/blog/app/views/glib/blog/admin/_status_chip.json.jbuilder +2 -0
  92. data/engines/blog/app/views/glib/blog/admin/authors/_form.json.jbuilder +17 -0
  93. data/engines/blog/app/views/glib/blog/admin/authors/edit.json.jbuilder +7 -0
  94. data/engines/blog/app/views/glib/blog/admin/authors/index.json.jbuilder +50 -0
  95. data/engines/blog/app/views/glib/blog/admin/authors/new.json.jbuilder +11 -0
  96. data/engines/blog/app/views/glib/blog/admin/categories/_form.json.jbuilder +13 -0
  97. data/engines/blog/app/views/glib/blog/admin/categories/edit.json.jbuilder +7 -0
  98. data/engines/blog/app/views/glib/blog/admin/categories/index.json.jbuilder +68 -0
  99. data/engines/blog/app/views/glib/blog/admin/categories/new.json.jbuilder +7 -0
  100. data/engines/blog/app/views/glib/blog/admin/comments/_moderation_buttons.json.jbuilder +35 -0
  101. data/engines/blog/app/views/glib/blog/admin/comments/index.json.jbuilder +59 -0
  102. data/engines/blog/app/views/glib/blog/admin/dashboards/show.json.jbuilder +109 -0
  103. data/engines/blog/app/views/glib/blog/admin/media_item_trashes/index.json.jbuilder +32 -0
  104. data/engines/blog/app/views/glib/blog/admin/media_items/_rows.json.jbuilder +32 -0
  105. data/engines/blog/app/views/glib/blog/admin/media_items/edit.json.jbuilder +68 -0
  106. data/engines/blog/app/views/glib/blog/admin/media_items/index.json.jbuilder +68 -0
  107. data/engines/blog/app/views/glib/blog/admin/media_items/new.json.jbuilder +18 -0
  108. data/engines/blog/app/views/glib/blog/admin/media_picks/index.json.jbuilder +29 -0
  109. data/engines/blog/app/views/glib/blog/admin/posts/_form.json.jbuilder +104 -0
  110. data/engines/blog/app/views/glib/blog/admin/posts/edit.json.jbuilder +1 -0
  111. data/engines/blog/app/views/glib/blog/admin/posts/index.json.jbuilder +109 -0
  112. data/engines/blog/app/views/glib/blog/admin/posts/new.json.jbuilder +1 -0
  113. data/engines/blog/app/views/glib/blog/admin/settings/edit.json.jbuilder +55 -0
  114. data/engines/blog/app/views/glib/blog/admin/tags/_form.json.jbuilder +6 -0
  115. data/engines/blog/app/views/glib/blog/admin/tags/edit.json.jbuilder +7 -0
  116. data/engines/blog/app/views/glib/blog/admin/tags/index.json.jbuilder +30 -0
  117. data/engines/blog/app/views/glib/blog/admin/tags/new.json.jbuilder +7 -0
  118. data/engines/blog/app/views/glib/blog/authors/show.json.jbuilder +4 -0
  119. data/engines/blog/app/views/glib/blog/categories/show.json.jbuilder +4 -0
  120. data/engines/blog/app/views/glib/blog/comments/pending.json.jbuilder +7 -0
  121. data/engines/blog/app/views/glib/blog/media_items/_media_item.html.erb +14 -0
  122. data/engines/blog/app/views/glib/blog/posts/_comment.json.jbuilder +23 -0
  123. data/engines/blog/app/views/glib/blog/posts/_comment_form.json.jbuilder +14 -0
  124. data/engines/blog/app/views/glib/blog/posts/_comments.json.jbuilder +21 -0
  125. data/engines/blog/app/views/glib/blog/posts/index.json.jbuilder +4 -0
  126. data/engines/blog/app/views/glib/blog/posts/show.json.jbuilder +5 -0
  127. data/engines/blog/app/views/glib/blog/shared/errors.json.jbuilder +5 -0
  128. data/engines/blog/app/views/glib/blog/tags/show.json.jbuilder +3 -0
  129. data/engines/blog/app/views/glib/blog/themes/_nav_links.json.jbuilder +12 -0
  130. data/engines/blog/app/views/glib/blog/themes/clean/_brand.json.jbuilder +11 -0
  131. data/engines/blog/app/views/glib/blog/themes/clean/_card.json.jbuilder +15 -0
  132. data/engines/blog/app/views/glib/blog/themes/clean/_featured.json.jbuilder +23 -0
  133. data/engines/blog/app/views/glib/blog/themes/clean/_footer.json.jbuilder +15 -0
  134. data/engines/blog/app/views/glib/blog/themes/clean/_header.json.jbuilder +9 -0
  135. data/engines/blog/app/views/glib/blog/themes/clean/_post.json.jbuilder +98 -0
  136. data/engines/blog/app/views/glib/blog/themes/clean/_post_list.json.jbuilder +40 -0
  137. data/engines/blog/app/views/glib/blog/themes/clean/_post_rows.json.jbuilder +10 -0
  138. data/engines/blog/app/views/glib/blog/themes/editorial/_footer.json.jbuilder +15 -0
  139. data/engines/blog/app/views/glib/blog/themes/editorial/_header.json.jbuilder +11 -0
  140. data/engines/blog/app/views/glib/blog/themes/editorial/_post.json.jbuilder +62 -0
  141. data/engines/blog/app/views/glib/blog/themes/editorial/_post_list.json.jbuilder +25 -0
  142. data/engines/blog/app/views/glib/blog/themes/editorial/_post_rows.json.jbuilder +18 -0
  143. data/engines/blog/config/locales/en.yml +500 -0
  144. data/engines/blog/config/routes.rb +33 -0
  145. data/engines/blog/db/migrate/20261103090000_create_glib_blog_tables.rb +70 -0
  146. data/engines/blog/db/migrate/20261104090000_create_glib_blog_media_tables.rb +44 -0
  147. data/engines/blog/db/migrate/20261104120000_create_glib_blog_comments.rb +23 -0
  148. data/engines/blog/db/migrate/20261105090000_add_glib_blog_comment_moderation.rb +16 -0
  149. data/engines/blog/db/migrate/20261105100000_add_deleted_at_to_glib_blog_posts.rb +6 -0
  150. data/engines/blog/db/migrate/20261105110000_add_parent_and_default_to_glib_blog_categories.rb +10 -0
  151. data/engines/blog/db/migrate/20261105120000_create_glib_blog_post_views.rb +13 -0
  152. data/engines/blog/db/migrate/20261105130000_create_glib_blog_settings.rb +26 -0
  153. data/engines/blog/db/migrate/20261106090000_add_theme_to_glib_blog_settings.rb +7 -0
  154. data/engines/blog/lib/tasks/glib_blog_tasks.rake +32 -0
  155. data/lib/generators/glib/blog/install_generator.rb +44 -0
  156. data/lib/generators/glib/blog/templates/initializer.rb +22 -0
  157. data/lib/generators/glib/scheduled_jobs_generator.rb +30 -0
  158. data/lib/generators/templates/scheduled_jobs/create_glib_scheduled_job_runs.rb +22 -0
  159. data/lib/glib/blog/engine.rb +20 -0
  160. data/lib/glib/blog/theme.rb +35 -0
  161. data/lib/glib/blog.rb +50 -0
  162. data/lib/glib/engine.rb +17 -0
  163. data/lib/glib/scheduled_jobs/config.rb +36 -0
  164. data/lib/glib/scheduled_jobs/loader.rb +98 -0
  165. data/lib/glib-web.rb +2 -0
  166. metadata +174 -3
@@ -0,0 +1,581 @@
1
+ module Glib
2
+ # Base class for cron-scheduled jobs: the schedule is declared on the class
3
+ # in Ruby and registered with sidekiq-cron by Glib::ScheduledJobs::Loader at
4
+ # Sidekiq boot (rails g glib:scheduled_jobs installs the gate table).
5
+ # Adopting apps delete config/schedules.yml; the loader refuses to run when
6
+ # both exist (see Glib::ScheduledJobs::Loader).
7
+ #
8
+ # Two declarations, exactly one per concrete class -- declarations do NOT
9
+ # inherit: a subclass of a declared class must declare its own schedule or
10
+ # make the parent abstract_scheduled_job, or validate_all! (and so the
11
+ # loader) rejects it (an undeclared subclass would register a duplicate
12
+ # entry and run the parent's perform a second time per period):
13
+ #
14
+ # class NightlyReportJob < Glib::ScheduledJob
15
+ # run_once per: :day
16
+ # end
17
+ #
18
+ # class InboxPollJob < Glib::ScheduledJob
19
+ # poll every: 10.minutes
20
+ # end
21
+ #
22
+ # == Choosing between poll and run_once
23
+ #
24
+ # Use +run_once per:+ only when the job's work set is defined by the period
25
+ # itself ("once per day", "once per week") AND the job has no per-record gate
26
+ # and no per-record rescue. Anything that gates or rescues per record, or
27
+ # throttles on its own watermark, uses +poll every:+ instead: a job-level
28
+ # "done" stamped after a run that rescued one record would skip that
29
+ # record's retry for the rest of the period.
30
+ #
31
+ # == The run gate (run_once only)
32
+ #
33
+ # Cron-enqueued runs of +run_once+ jobs arrive through Glib::ScheduledJobTick
34
+ # and are gated on the persisted last completed period key in
35
+ # glib_scheduled_job_runs: an equal key skips the run, a normal return
36
+ # records the key, a raise records nothing so the next poll retries. A raise
37
+ # after partial work is NOT undone -- a run that sent 50 emails and raised
38
+ # on the 51st re-sends the 50 on retry; keep perform idempotent per record.
39
+ # Direct perform_now / perform_later calls are never gated, so operators can
40
+ # rerun a job by hand and tests stay deterministic. Install the gate table
41
+ # (rails g glib:scheduled_jobs) before the first run_once subclass deploys:
42
+ # a gated run against the missing table raises.
43
+ #
44
+ # Clear a job's gate by hand (e.g. to force a re-run) with
45
+ # NightlyReportJob.reset_run_gate!.
46
+ #
47
+ # == Overriding the lock defaults
48
+ #
49
+ # Direct subclasses get
50
+ # unique :until_and_while_executing, lock_ttl: 2.days,
51
+ # runtime_lock_ttl: 1.hour, on_conflict: :log
52
+ # applied automatically. Override with the merging method, never a raw
53
+ # +unique+ call (the gem assigns lock options wholesale and would drop the
54
+ # defaults):
55
+ #
56
+ # class SlowNightlyJob < Glib::ScheduledJob
57
+ # run_once per: :day
58
+ # scheduled_lock runtime_lock_ttl: 3.hours
59
+ # end
60
+ #
61
+ # == Scheduling a class the app does not own
62
+ #
63
+ # Don't move the foreign class onto this base; write a thin host subclass
64
+ # whose perform delegates, so apps that schedule the original through a
65
+ # different mechanism keep working:
66
+ #
67
+ # class ScheduledUnattachedPurgeJob < Glib::ScheduledJob
68
+ # poll every: 1.day
69
+ # def perform(*args)
70
+ # Glib::PurgeUnattachedJob.perform_now(*args)
71
+ # end
72
+ # end
73
+ #
74
+ # Full scheduling guidance (poll frequency, due-marker polling, lock sizing)
75
+ # lives in the dev-doc best practices: 08_job.md#cron-schedule-frequency.
76
+ #
77
+ # Both scheduling gems are host-supplied on purpose (glib-web keeps no
78
+ # runtime dependency on either): activejob-uniqueness and sidekiq-cron must
79
+ # be in the Gemfile before the first subclass is defined.
80
+ class ScheduledJob < ApplicationJob
81
+ class_attribute :scheduled_kind
82
+ class_attribute :poll_interval
83
+ class_attribute :run_period
84
+ class_attribute :run_zone
85
+ class_attribute :poll_reason
86
+
87
+ class << self
88
+ # Whether THIS class body declared a schedule. Deliberately a per-class
89
+ # ivar, not a class_attribute: the DSL's values inherit into subclasses
90
+ # (readers like cron_line lean on that), but a subclass that declares
91
+ # nothing of its own must not pass as declared -- it would register a
92
+ # duplicate entry under its own cron name and run the parent's perform
93
+ # a second time per period. validate_all! reports such subclasses.
94
+ def declared_own_schedule?
95
+ @declared_own_schedule == true
96
+ end
97
+
98
+ # Declare a polling schedule: every tick runs perform. The interval is
99
+ # N minutes with N dividing 60, N hours with N dividing 24, or exactly
100
+ # 1 day -- the shapes with an exact cron line. Declarations do not
101
+ # inherit: every concrete class declares its own.
102
+ def poll(every:, name: nil)
103
+ ensure_undeclared!
104
+ validate_poll_interval!(every)
105
+
106
+ self.scheduled_kind = :poll
107
+ self.poll_interval = every
108
+ self.cron_name = name if name
109
+ @declared_own_schedule = true
110
+ end
111
+
112
+ # Declare a run-once-per-period schedule. The job runs at most once per
113
+ # period through the gate; the cron poll that drives it defaults to the
114
+ # largest valid interval not above period / 24 (capped at 1 hour), so a
115
+ # missed tick costs at most 1/24 of the period.
116
+ #
117
+ # per: :day, :week, :month, or a duration of 1, 2, 3, 4, 6, 8 or
118
+ # 12 hours. Periods are calendar-aligned in zone: (default
119
+ # the app's Time.zone): local date, ISO week, local
120
+ # calendar month, or local-midnight hour bucket. :month
121
+ # gates a once-a-month side effect (a monthly statement or
122
+ # rollup) on the calendar-month key, '2026-11'.
123
+ # poll_every: overrides the default poll in either direction; requires
124
+ # because: so the reason sits beside the declaration.
125
+ # zone: an ActiveSupport::TimeZone name.
126
+ # name: the sidekiq-cron entry name (default: the class name
127
+ # underscored, '/' -> '_').
128
+ def run_once(per:, poll_every: nil, because: nil, zone: nil, name: nil)
129
+ ensure_undeclared!
130
+ validate_period!(per)
131
+ validate_zone!(zone) if zone
132
+
133
+ effective_poll = poll_every || default_poll_interval_for(per)
134
+ if poll_every
135
+ if because.nil? || because.strip.empty?
136
+ raise ArgumentError,
137
+ "#{self}: poll_every: requires because: -- state why the poll " \
138
+ 'deviates from the period/24 default beside the declaration'
139
+ end
140
+ validate_poll_interval!(poll_every)
141
+ elsif !because.nil?
142
+ raise ArgumentError, "#{self}: because: is only valid together with poll_every:"
143
+ end
144
+ if effective_poll.to_i >= period_seconds(per)
145
+ raise ArgumentError,
146
+ "#{self}: the poll (#{effective_poll.inspect}) must be strictly shorter than " \
147
+ "the period (#{per.inspect})"
148
+ end
149
+
150
+ self.scheduled_kind = :run_once
151
+ self.poll_interval = effective_poll
152
+ self.run_period = per
153
+ self.run_zone = zone
154
+ self.poll_reason = because
155
+ self.cron_name = name if name
156
+ @declared_own_schedule = true
157
+ end
158
+
159
+ # Merge lock options over the inherited ones. Never call the gem's raw
160
+ # +unique+ from a subclass: it assigns lock options wholesale and would
161
+ # silently drop lock_ttl / on_conflict from the defaults.
162
+ def scheduled_lock(**options)
163
+ strategy = lock_strategy_class
164
+ unless strategy
165
+ raise ArgumentError, "#{self}: scheduled_lock has no lock strategy to merge into -- " \
166
+ 'subclass Glib::ScheduledJob first (direct subclasses get the defaults)'
167
+ end
168
+
169
+ unique strategy.name.demodulize.underscore.to_sym, (lock_options || {}).merge(options)
170
+ end
171
+
172
+ # Operator escape hatch: clear this job's last completed period so the
173
+ # next cron-enqueued run performs again.
174
+ def reset_run_gate!
175
+ Glib::ScheduledJobRun.where(job_name: cron_name).delete_all
176
+ end
177
+
178
+ # App-level intermediate base classes set this and skip validation;
179
+ # their concrete subclasses are validated normally. A per-class ivar on
180
+ # purpose: class_attribute would let the flag inherit into the concrete
181
+ # subclasses it is meant to exempt.
182
+ attr_writer :abstract_scheduled_job
183
+
184
+ def abstract_scheduled_job?
185
+ @abstract_scheduled_job == true
186
+ end
187
+
188
+ def cron_name
189
+ raise "#{self} has no class name (anonymous class?); pass name: in the declaration" unless name
190
+
191
+ @cron_name ||= name.underscore.tr('/', '_')
192
+ end
193
+
194
+ def cron_name=(value)
195
+ @cron_name = value.to_s
196
+ end
197
+
198
+ def cron_line
199
+ unless scheduled_kind
200
+ raise "#{self}: no schedule declaration -- call poll every: or run_once per: in the class body"
201
+ end
202
+
203
+ interval_cron(poll_interval) ||
204
+ raise(ArgumentError, "#{self}: #{poll_interval.inspect} has no exact cron form " \
205
+ '(use N minutes with N dividing 60, N hours with N dividing 24, or 1 day)')
206
+ end
207
+
208
+ # The sidekiq-cron entry for this class. run_once classes are registered
209
+ # under Glib::ScheduledJobTick with the class name as the argument (the
210
+ # tick builds the target, flags it as a scheduled run, and enqueues it);
211
+ # the entry carries no queue, so the lightweight tick itself always
212
+ # rides the 'default' queue -- the target's own queue_as decides where
213
+ # the gated work runs. poll classes are registered directly. Poll
214
+ # entries carry the resolved queue because sidekiq-cron forces
215
+ # 'default' when the entry has no queue key (job.rb:
216
+ # @queue = message_data['queue'] || 'default') and enqueues ActiveJob
217
+ # through klass.set(queue: @queue), overriding this class's queue_as.
218
+ def schedule_entry
219
+ if scheduled_kind == :run_once
220
+ description = "at most once per #{period_description}, polls every #{poll_interval.inspect}"
221
+ description += " (#{poll_reason})" if poll_reason
222
+ {
223
+ 'class' => 'Glib::ScheduledJobTick',
224
+ 'cron' => cron_line,
225
+ 'args' => [name],
226
+ 'description' => description
227
+ }
228
+ else
229
+ entry = {
230
+ 'class' => name,
231
+ 'cron' => cron_line,
232
+ 'args' => [],
233
+ 'description' => "polls every #{poll_interval.inspect}"
234
+ }
235
+ begin
236
+ resolved = queue_name
237
+ # Rails 8 defaults the class-level queue_name to a lambda; the
238
+ # instance resolves it (and any queue_as block) correctly.
239
+ resolved = new.queue_name if resolved.respond_to?(:call)
240
+ entry['queue'] = resolved.to_s
241
+ rescue StandardError
242
+ entry['queue'] = 'default'
243
+ end
244
+ entry
245
+ end
246
+ end
247
+
248
+ # The gate's period identity for a moment in time: '2026-11-18' for a
249
+ # day, '2026-11' for a calendar month, '2026-W47' for an ISO week
250
+ # (week-based year, Monday start), and '2026-11-18T06' for the
251
+ # local-midnight-aligned 6h bucket of a 6 hour period. Computed in
252
+ # run_zone (default the app's Time.zone) so date-arithmetic work
253
+ # agrees with the gate. run_once classes only: a
254
+ # poll job declares no period, so the key would be meaningless -- call
255
+ # this on one and it raises rather than dividing by the period's zero
256
+ # hours.
257
+ def period_key(at = Time.current)
258
+ unless run_period
259
+ raise "#{self}: period_key is a run_once job's period identity -- a poll job declares no period"
260
+ end
261
+
262
+ zone = run_zone ? ActiveSupport::TimeZone[run_zone] : Time.zone
263
+ local = at.in_time_zone(zone)
264
+ case run_period
265
+ when :day
266
+ local.strftime('%Y-%m-%d')
267
+ when :week
268
+ local.strftime('%G-W%V')
269
+ when :month
270
+ local.strftime('%Y-%m')
271
+ else
272
+ hours = run_period.to_i / 3600
273
+ bucket = local.hour - (local.hour % hours)
274
+ format('%<date>sT%<hour>02d', date: local.strftime('%Y-%m-%d'), hour: bucket)
275
+ end
276
+ end
277
+
278
+ # Whole-class validation, run by the loader at Sidekiq boot and by the
279
+ # DevDoc::Test::Lints::ScheduledJobs lint in the app's test suite.
280
+ # Returns a list of offense strings; empty means every concrete
281
+ # subclass declares exactly one valid schedule OF ITS OWN (declarations
282
+ # do not inherit -- a subclass of a declared class that declares nothing
283
+ # would register a duplicate entry and run the parent's perform a second
284
+ # time per period) and carries sane lock settings.
285
+ def validate_all!
286
+ offenses = []
287
+ names_seen = {}
288
+
289
+ abstract_subclasses.each do |klass|
290
+ next unless klass.declared_own_schedule?
291
+
292
+ offenses << "#{klass.name}: an abstract_scheduled_job class declares a schedule -- " \
293
+ 'declarations belong on concrete classes (subclasses must declare their own)'
294
+ end
295
+
296
+ concrete_subclasses.each do |klass|
297
+ unless klass.declared_own_schedule?
298
+ declarer = inherited_schedule_declarer(klass)
299
+ offenses << if declarer
300
+ "#{klass.name}: inherits #{declarer.name}'s schedule without declaring its own -- " \
301
+ "both classes would register and #{declarer.name}'s perform would run twice per period. " \
302
+ "Declare a schedule on #{klass.name} or make #{declarer.name} abstract_scheduled_job"
303
+ else
304
+ "#{klass.name}: no schedule declaration (poll every: or run_once per:)"
305
+ end
306
+ end
307
+
308
+ strategy = klass.respond_to?(:lock_strategy_class) ? klass.lock_strategy_class : nil
309
+ strategy_name = strategy ? strategy.name.to_s.demodulize : ''
310
+ unless %w[UntilAndWhileExecuting WhileExecuting].include?(strategy_name)
311
+ offenses << "#{klass.name}: lock strategy #{strategy ? strategy.name : 'nil'} is not " \
312
+ 'UntilAndWhileExecuting or WhileExecuting -- use scheduled_lock to change options, ' \
313
+ 'and declare the strategy through the Glib::ScheduledJob defaults'
314
+ end
315
+
316
+ options = klass.respond_to?(:lock_options) ? (klass.lock_options || {}) : {}
317
+ on_conflict = options[:on_conflict]
318
+ unless on_conflict == :log || on_conflict.respond_to?(:call)
319
+ offenses << "#{klass.name}: lock on_conflict #{on_conflict.inspect} must be :log or a callable " \
320
+ '(the gem default :raise turns an overlapped tick into a failed job)'
321
+ end
322
+
323
+ if strategy_name == 'UntilAndWhileExecuting' && klass.poll_interval &&
324
+ options[:lock_ttl].to_i < 2 * klass.poll_interval.to_i
325
+ offenses << "#{klass.name}: lock_ttl #{options[:lock_ttl].inspect} is below twice the poll " \
326
+ "interval (#{klass.poll_interval.inspect}) -- one slow start would let the next tick overlap"
327
+ end
328
+
329
+ if options[:runtime_lock_ttl].nil?
330
+ offenses << "#{klass.name}: runtime_lock_ttl is not set -- the gem silently falls back to " \
331
+ 'lock_ttl, sizing the run lock from the schedule instead of the run time'
332
+ end
333
+
334
+ if klass.const_defined?(:STALENESS_THRESHOLD)
335
+ threshold = klass::STALENESS_THRESHOLD.to_i
336
+ if klass.poll_interval && klass.poll_interval.to_i >= threshold
337
+ offenses << "#{klass.name}: poll interval #{klass.poll_interval.inspect} is not strictly below " \
338
+ "STALENESS_THRESHOLD #{klass::STALENESS_THRESHOLD.inspect}"
339
+ end
340
+ if options[:runtime_lock_ttl] && options[:runtime_lock_ttl].to_i >= threshold
341
+ offenses << "#{klass.name}: runtime_lock_ttl #{options[:runtime_lock_ttl].inspect} is not strictly " \
342
+ "below STALENESS_THRESHOLD #{klass::STALENESS_THRESHOLD.inspect}"
343
+ end
344
+ end
345
+
346
+ (names_seen[klass.cron_name] ||= []) << klass.name
347
+ end
348
+
349
+ names_seen.each do |cron_name, klass_names|
350
+ next unless klass_names.size > 1
351
+
352
+ offenses << "cron name '#{cron_name}' is used by #{klass_names.sort.join(' and ')} -- " \
353
+ 'sidekiq-cron entries must be unique (pass name: to override one)'
354
+ end
355
+
356
+ offenses
357
+ end
358
+
359
+ # Classes still linked in Ruby's native Class#subclasses (what
360
+ # descendants reads) after their constant was removed -- a zeitwerk
361
+ # reload, a test removing a fixture -- are dead code: invisible to
362
+ # validation and registration. Anonymous classes have no constant to
363
+ # resolve at all.
364
+ def live_subclass?(klass)
365
+ klass_name = klass.name
366
+ return false if klass_name.nil?
367
+
368
+ klass_name.safe_constantize.equal?(klass)
369
+ end
370
+
371
+ def concrete_subclasses
372
+ descendants.select { |klass| live_subclass?(klass) }.reject(&:abstract_scheduled_job?)
373
+ end
374
+
375
+ def abstract_subclasses
376
+ descendants.select { |klass| live_subclass?(klass) }.select(&:abstract_scheduled_job?)
377
+ end
378
+
379
+ # The nearest superclass that declared a schedule in its own body
380
+ # (declared_own_schedule? reads a per-class ivar, so it does not
381
+ # inherit). nil when no ancestor declared anything.
382
+ def inherited_schedule_declarer(klass)
383
+ ancestor = klass.superclass
384
+ while ancestor && ancestor != Glib::ScheduledJob
385
+ return ancestor if ancestor.declared_own_schedule?
386
+
387
+ ancestor = ancestor.superclass
388
+ end
389
+ nil
390
+ end
391
+
392
+ def inherited(subclass)
393
+ super
394
+ ensure_scheduler_gems!
395
+ return unless subclass.superclass == Glib::ScheduledJob
396
+
397
+ # Lock defaults on direct subclasses only: Ruby runs this hook for
398
+ # every descendant, and an unconditional default would reset an
399
+ # app-level intermediate base's own scheduled_lock settings.
400
+ subclass.unique :until_and_while_executing,
401
+ lock_ttl: 2.days, runtime_lock_ttl: 1.hour, on_conflict: :log
402
+ end
403
+
404
+ # Class-method probes so tests can stub a missing gem. Nothing in the
405
+ # class body may reference either gem directly: this engine eager-loads
406
+ # app/jobs in every host, including hosts that never subclass this
407
+ # class and carry neither gem.
408
+ def uniqueness_loaded?
409
+ !defined?(::ActiveJob::Uniqueness).nil?
410
+ end
411
+
412
+ def cron_loaded?
413
+ !defined?(::Sidekiq::Cron::Job).nil?
414
+ end
415
+
416
+ private
417
+ def ensure_scheduler_gems!
418
+ missing = []
419
+ unless uniqueness_loaded?
420
+ missing << "gem 'activejob-uniqueness', '~> 0.4.0', require: 'active_job/uniqueness/sidekiq_patch'"
421
+ end
422
+ missing << "gem 'sidekiq-cron'" unless cron_loaded?
423
+ return if missing.empty?
424
+
425
+ raise LoadError, "#{self} subclasses need the scheduling gems in the host Gemfile. Add:\n #{missing.join("\n ")}"
426
+ end
427
+
428
+ def ensure_undeclared!
429
+ # Per-class, NOT scheduled_kind: the DSL values inherit, so a
430
+ # subclass's first declaration must pass; only a second declaration
431
+ # in the SAME class body refuses.
432
+ return unless @declared_own_schedule
433
+
434
+ raise ArgumentError, "#{self}: a second schedule declaration (already #{scheduled_kind})"
435
+ end
436
+
437
+ def validate_poll_interval!(interval)
438
+ unless interval.is_a?(ActiveSupport::Duration) && interval_cron(interval)
439
+ raise ArgumentError,
440
+ "#{self}: #{interval.inspect} is not a valid schedule interval. " \
441
+ 'Use N minutes with N dividing 60, N hours with N dividing 24, or exactly 1 day.'
442
+ end
443
+ end
444
+
445
+ def validate_period!(period)
446
+ return if %i[day week month].include?(period)
447
+ return if hour_period?(period)
448
+
449
+ raise ArgumentError,
450
+ "#{self}: #{period.inspect} is not a valid run_once period. " \
451
+ 'Use :day, :week, :month, or a duration of 1, 2, 3, 4, 6, 8 or 12 hours.'
452
+ end
453
+
454
+ def validate_zone!(zone_name)
455
+ return if ActiveSupport::TimeZone[zone_name]
456
+
457
+ raise ArgumentError,
458
+ "#{self}: zone #{zone_name.inspect} does not resolve through ActiveSupport::TimeZone"
459
+ end
460
+
461
+ # Valid hour periods for run_once: under an hour a poll covers it.
462
+ VALID_HOUR_PERIODS = [1, 2, 3, 4, 6, 8, 12].freeze
463
+ VALID_POLL_MINUTES = [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60].freeze
464
+ private_constant :VALID_HOUR_PERIODS, :VALID_POLL_MINUTES
465
+
466
+ def hour_period?(period)
467
+ period.is_a?(ActiveSupport::Duration) &&
468
+ period.parts.length == 1 &&
469
+ period.parts.keys.first == :hours &&
470
+ VALID_HOUR_PERIODS.include?(period.parts.values.first)
471
+ end
472
+
473
+ def period_seconds(period)
474
+ case period
475
+ when :day then 86_400
476
+ when :week then 604_800
477
+ # 30 days (2_592_000) approximates a calendar month: only the
478
+ # period/24 default-poll target and the poll-vs-period guard
479
+ # read it.
480
+ when :month then 2_592_000
481
+ else period.to_i
482
+ end
483
+ end
484
+
485
+ # The default run_once poll: the largest valid minute interval not
486
+ # above period / 24, capped at 1 hour (daily and weekly -> 1h, 12h ->
487
+ # 30min, 6h -> 15min, 1h -> 2min). The cap is expressed in the hour
488
+ # form so its derived cron line is the hourly 0 */1 shape.
489
+ def default_poll_interval_for(period)
490
+ target = period_seconds(period) / 24.0
491
+ minutes = VALID_POLL_MINUTES.reverse.find { |candidate| candidate * 60 <= target }
492
+ minutes == 60 ? 1.hour : minutes.minutes
493
+ end
494
+
495
+ def interval_cron(interval)
496
+ parts = interval.parts
497
+ return nil unless parts.length == 1
498
+
499
+ unit, amount = parts.first
500
+ return nil unless amount.is_a?(Integer) && amount.positive?
501
+
502
+ case unit
503
+ when :minutes
504
+ return nil unless amount <= 60 && (60 % amount).zero?
505
+
506
+ amount == 1 ? '* * * * *' : "*/#{amount} * * * *"
507
+ when :hours
508
+ return nil unless amount <= 24 && (24 % amount).zero?
509
+
510
+ "0 */#{amount} * * *"
511
+ when :days
512
+ amount == 1 ? '0 0 * * *' : nil
513
+ end
514
+ end
515
+
516
+ def period_description
517
+ case run_period
518
+ when :day then 'day'
519
+ when :week then 'week'
520
+ when :month then 'month'
521
+ else run_period.inspect
522
+ end
523
+ end
524
+ end
525
+
526
+ attr_accessor :glib_scheduled_run
527
+
528
+ # Carry the scheduled-run flag in the job data (outside `arguments`, so
529
+ # the uniqueness lock key and the perform signature are unchanged). Absent
530
+ # means a direct run: perform_now and perform_later are never gated.
531
+ # Rails' documented serialize/deserialize override pair (ActiveJob::Core):
532
+ # the queue round trip goes through these, and the executing process
533
+ # rebuilds the job from the data via the instance-level reader.
534
+ def serialize
535
+ data = super
536
+ data['glib_scheduled_run'] = true if @glib_scheduled_run
537
+ data
538
+ end
539
+
540
+ def deserialize(job_data)
541
+ super
542
+ self.glib_scheduled_run = true if job_data['glib_scheduled_run']
543
+ self
544
+ end
545
+
546
+ around_perform do |_job, block|
547
+ if scheduled_run?
548
+ key = self.class.period_key
549
+ completed = Glib::ScheduledJobRun.find_by(job_name: self.class.cron_name)
550
+ if completed && completed.period_key == key
551
+ Rails.logger.info(
552
+ "[glib-web] #{self.class.cron_name} already completed period #{key} -- skipping scheduled run"
553
+ )
554
+ else
555
+ block.call
556
+ mark_run_completed!(key)
557
+ end
558
+ else
559
+ block.call
560
+ end
561
+ end
562
+
563
+ private
564
+ def scheduled_run?
565
+ self.class.scheduled_kind == :run_once && @glib_scheduled_run == true
566
+ end
567
+
568
+ def mark_run_completed!(key)
569
+ now = Time.current
570
+ # update_only keeps created_at from the first insert and lets
571
+ # record_timestamps bump updated_at; no raw conflict SQL, so the
572
+ # statement is not tied to one adapter's EXCLUDED spelling.
573
+ Glib::ScheduledJobRun.upsert(
574
+ { job_name: self.class.cron_name, period_key: key, completed_at: now,
575
+ created_at: now, updated_at: now },
576
+ unique_by: :job_name,
577
+ update_only: %i[period_key completed_at]
578
+ )
579
+ end
580
+ end
581
+ end
@@ -0,0 +1,21 @@
1
+ module Glib
2
+ # Dispatcher the loader registers as the sidekiq-cron entry for run_once
3
+ # jobs (poll jobs are registered under their own class). One lightweight
4
+ # enqueue per poll; the flag it sets is what the gate in Glib::ScheduledJob
5
+ # keys on, carried in the job data so neither the uniqueness lock key (class
6
+ # name + arguments) nor the perform signature changes.
7
+ class ScheduledJobTick < ApplicationJob
8
+ def perform(job_class_name)
9
+ klass = job_class_name.to_s.constantize
10
+ unless klass < Glib::ScheduledJob && klass.scheduled_kind == :run_once
11
+ raise ArgumentError,
12
+ "Glib::ScheduledJobTick refuses #{job_class_name}: only run_once Glib::ScheduledJob " \
13
+ 'subclasses are dispatched through the tick (poll jobs are registered under their own class)'
14
+ end
15
+
16
+ job = klass.new
17
+ job.glib_scheduled_run = true
18
+ job.enqueue
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,16 @@
1
+ module Glib
2
+ # Persisted run gate for run_once Glib::ScheduledJob subclasses: one row per
3
+ # cron name holding the last completed period key. Installed by
4
+ # `rails g glib:scheduled_jobs`. Stored in the database (not Redis) so a
5
+ # flush or a mismatched restore cannot re-send a period's side effects.
6
+ #
7
+ # The framework writes through upsert, which SKIPS these validations -- on
8
+ # that path the columns' NOT NULL constraints are the guard. The presence
9
+ # validations below only guard hand-made create!/save calls (a console, a
10
+ # script).
11
+ class ScheduledJobRun < ApplicationRecord
12
+ self.table_name = 'glib_scheduled_job_runs'
13
+
14
+ validates :job_name, :period_key, :completed_at, presence: true
15
+ end
16
+ end
@@ -0,0 +1,34 @@
1
+ json.title 'Forms'
2
+
3
+ page = json_ui_page json
4
+
5
+ render "#{@path_prefix}/nav_menu", json: json, page: page
6
+
7
+ initial_content = <<~HTML
8
+ <h1>Action Text</h1>
9
+ <div>This editor submits the same HTML as Rails' <strong>Action Text</strong> form helper, so it can be assigned straight to a has_rich_text attribute.</div>
10
+ <ul><li>Attach or paste a file to upload it.</li><li>Submit to see the rendered content.</li></ul>
11
+ HTML
12
+
13
+ page.form url: json_ui_garage_url(path: 'forms/action_text_preview'), method: 'post', padding: { top: 20, bottom: 20 }, childViews: ->(form) do
14
+ form.panels_column lg: { cols: 6 }, padding: { left: 10, right: 10 }, childViews: ->(column) do
15
+ column.fields_actionText \
16
+ width: 'matchParent',
17
+ label: 'Content',
18
+ name: 'post[content]',
19
+ value: initial_content,
20
+ directUploadUrl: glib_direct_uploads_url,
21
+ blobUrlGenerator: glib_blob_url_generators_url,
22
+ accepts: { fileType: ['image', 'pdf'], maxFileSize: 5000 }
23
+ end
24
+
25
+ form.panels_column lg: { cols: 6 }, padding: { left: 10, right: 10 }, childViews: ->(column) do
26
+ column.panels_vertical id: 'preview', childViews: ->(inner) do
27
+ inner.actionText richText: ActionText::Content.new(initial_content)
28
+ end
29
+ end
30
+
31
+ form.panels_column lg: { cols: 12 }, padding: { top: 10, left: 10, right: 10 }, childViews: ->(column) do
32
+ column.fields_submit text: 'Submit'
33
+ end
34
+ end
@@ -0,0 +1,7 @@
1
+ # Stands in for an app's attachment endpoint (`fields_actionText attachmentUrl:`): an app would
2
+ # turn the uploaded blob into its own Action Text attachable and answer with its attributes.
3
+ json.sgid "garage-attachment-#{params[:signed_id]}"
4
+ json.url 'https://picsum.photos/id/10/300/200'
5
+ json.contentType 'image/jpeg'
6
+ json.filename 'from-attachment-url.jpg'
7
+ json.previewable true
@@ -0,0 +1,26 @@
1
+ json.title 'Insert from library'
2
+
3
+ page = json_ui_page json
4
+
5
+ library = [
6
+ { sgid: 'garage-library-1', url: 'https://picsum.photos/id/20/300/200', filename: 'desk.jpg' },
7
+ { sgid: 'garage-library-2', url: 'https://picsum.photos/id/30/300/200', filename: 'mug.jpg' }
8
+ ]
9
+
10
+ page.body childViews: ->(body) do
11
+ body.panels_list width: 'matchParent', firstSection: ->(section) do
12
+ section.rows builder: ->(template) do
13
+ library.each do |file|
14
+ template.thumbnail title: file[:filename], imageUrl: file[:url], onClick: ->(action) do
15
+ action.runMultiple childActions: ->(multiple) do
16
+ multiple.components_invoke \
17
+ targetId: params[:target],
18
+ name: 'insertAttachment',
19
+ arguments: file.merge(contentType: 'image/jpeg', previewable: true)
20
+ multiple.dialogs_close
21
+ end
22
+ end
23
+ end
24
+ end
25
+ end
26
+ end