shikibu 0.3.0 → 0.4.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.
Files changed (138) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +82 -0
  3. data/lib/shikibu/activity.rb +84 -48
  4. data/lib/shikibu/actors.rb +129 -0
  5. data/lib/shikibu/app.rb +37 -23
  6. data/lib/shikibu/blobs.rb +42 -0
  7. data/lib/shikibu/channels.rb +240 -64
  8. data/lib/shikibu/constants.rb +8 -0
  9. data/lib/shikibu/context.rb +184 -14
  10. data/lib/shikibu/errors.rb +56 -0
  11. data/lib/shikibu/fs.rb +93 -0
  12. data/lib/shikibu/integrations/sidekiq.rb +9 -13
  13. data/lib/shikibu/middleware/rack_app.rb +17 -1
  14. data/lib/shikibu/notify/pg_notify.rb +28 -3
  15. data/lib/shikibu/replay.rb +242 -107
  16. data/lib/shikibu/storage/actor_ops.rb +331 -0
  17. data/lib/shikibu/storage/channel_ops.rb +421 -0
  18. data/lib/shikibu/storage/cursor_ops.rb +37 -0
  19. data/lib/shikibu/storage/sequel_storage.rb +400 -324
  20. data/lib/shikibu/storage/sqlite_ops.rb +58 -0
  21. data/lib/shikibu/supervisor.rb +279 -0
  22. data/lib/shikibu/tasks.rb +193 -0
  23. data/lib/shikibu/version.rb +1 -1
  24. data/lib/shikibu/worker.rb +155 -73
  25. data/lib/shikibu/workflow.rb +106 -48
  26. data/lib/shikibu.rb +4 -0
  27. data/schema/SEMANTICS.md +351 -0
  28. data/schema/db/migrations/mysql/20261123000000_outbox_claimed_at.sql +5 -0
  29. data/schema/db/migrations/mysql/20261201000000_actor_registry.sql +24 -0
  30. data/schema/db/migrations/mysql/20261202000000_actor_capabilities.sql +15 -0
  31. data/schema/db/migrations/mysql/20261203000000_payload_blobs.sql +11 -0
  32. data/schema/db/migrations/mysql/20261204000000_actor_fs.sql +13 -0
  33. data/schema/db/migrations/mysql/20261205000000_actor_tasks.sql +15 -0
  34. data/schema/db/migrations/mysql/20261206000000_actor_tasks_claimed_at.sql +7 -0
  35. data/schema/db/migrations/mysql/20261207000000_add_sandboxed.sql +5 -0
  36. data/schema/db/migrations/mysql/20261208000000_widen_actor_owner_columns.sql +15 -0
  37. data/schema/db/migrations/postgresql/20261123000000_outbox_claimed_at.sql +5 -0
  38. data/schema/db/migrations/postgresql/20261201000000_actor_registry.sql +23 -0
  39. data/schema/db/migrations/postgresql/20261202000000_actor_capabilities.sql +15 -0
  40. data/schema/db/migrations/postgresql/20261203000000_payload_blobs.sql +11 -0
  41. data/schema/db/migrations/postgresql/20261204000000_actor_fs.sql +13 -0
  42. data/schema/db/migrations/postgresql/20261205000000_actor_tasks.sql +15 -0
  43. data/schema/db/migrations/postgresql/20261206000000_actor_tasks_claimed_at.sql +7 -0
  44. data/schema/db/migrations/postgresql/20261207000000_add_sandboxed.sql +5 -0
  45. data/schema/db/migrations/postgresql/20261208000000_widen_actor_owner_columns.sql +7 -0
  46. data/schema/db/migrations/sqlite/20261123000000_outbox_claimed_at.sql +5 -0
  47. data/schema/db/migrations/sqlite/20261201000000_actor_registry.sql +23 -0
  48. data/schema/db/migrations/sqlite/20261202000000_actor_capabilities.sql +15 -0
  49. data/schema/db/migrations/sqlite/20261203000000_payload_blobs.sql +11 -0
  50. data/schema/db/migrations/sqlite/20261204000000_actor_fs.sql +13 -0
  51. data/schema/db/migrations/sqlite/20261205000000_actor_tasks.sql +15 -0
  52. data/schema/db/migrations/sqlite/20261206000000_actor_tasks_claimed_at.sql +7 -0
  53. data/schema/db/migrations/sqlite/20261207000000_add_sandboxed.sql +5 -0
  54. data/schema/db/migrations/sqlite/20261208000000_widen_actor_owner_columns.sql +7 -0
  55. data/schema/docs/column-values.md +10 -0
  56. data/schema/spec/ActorFS.tla +117 -0
  57. data/schema/spec/ActorFS_lww_monotonic.cfg +7 -0
  58. data/schema/spec/ActorFS_new.cfg +8 -0
  59. data/schema/spec/ActorFS_old.cfg +7 -0
  60. data/schema/spec/CompetingMessageClaim.tla +127 -0
  61. data/schema/spec/CompetingMessageClaimSplit.tla +132 -0
  62. data/schema/spec/CompetingMessageClaimSplit_atomic_lost.cfg +7 -0
  63. data/schema/spec/CompetingMessageClaimSplit_atomic_once.cfg +7 -0
  64. data/schema/spec/CompetingMessageClaimSplit_fixed.cfg +7 -0
  65. data/schema/spec/CompetingMessageClaimSplit_split_lost.cfg +7 -0
  66. data/schema/spec/CompetingMessageClaimSplit_split_once.cfg +7 -0
  67. data/schema/spec/CompetingMessageClaimSplit_waitonly_lost.cfg +7 -0
  68. data/schema/spec/CompetingMessageClaimSplit_waitonly_once.cfg +7 -0
  69. data/schema/spec/CompetingMessageClaim_new.cfg +10 -0
  70. data/schema/spec/CompetingMessageClaim_old.cfg +11 -0
  71. data/schema/spec/EpochFencing.tla +87 -0
  72. data/schema/spec/EpochFencingRuns.tla +107 -0
  73. data/schema/spec/EpochFencingRuns_epoch.cfg +6 -0
  74. data/schema/spec/EpochFencingRuns_none.cfg +6 -0
  75. data/schema/spec/EpochFencingRuns_witness.cfg +6 -0
  76. data/schema/spec/EpochFencingRuns_worker.cfg +6 -0
  77. data/schema/spec/EpochFencingRuns_worker1.cfg +6 -0
  78. data/schema/spec/EpochFencing_new.cfg +8 -0
  79. data/schema/spec/EpochFencing_old.cfg +9 -0
  80. data/schema/spec/InstanceClaim.tla +196 -0
  81. data/schema/spec/InstanceClaimVerdict.tla +116 -0
  82. data/schema/spec/InstanceClaimVerdict_changedrows.cfg +6 -0
  83. data/schema/spec/InstanceClaimVerdict_changedrows_live.cfg +6 -0
  84. data/schema/spec/InstanceClaimVerdict_foundrows.cfg +6 -0
  85. data/schema/spec/InstanceClaimVerdict_foundrows_live.cfg +6 -0
  86. data/schema/spec/InstanceClaim_atomic_unfenced.cfg +9 -0
  87. data/schema/spec/InstanceClaim_live.cfg +9 -0
  88. data/schema/spec/InstanceClaim_new.cfg +9 -0
  89. data/schema/spec/InstanceClaim_old.cfg +11 -0
  90. data/schema/spec/InstanceClaim_racy_fenced.cfg +9 -0
  91. data/schema/spec/README.md +97 -0
  92. data/schema/spec/SupervisorRestart.tla +108 -0
  93. data/schema/spec/SupervisorRestartCAS.tla +84 -0
  94. data/schema/spec/SupervisorRestartCAS_nonsticky.cfg +6 -0
  95. data/schema/spec/SupervisorRestartCAS_snapshot.cfg +6 -0
  96. data/schema/spec/SupervisorRestartCAS_sticky.cfg +6 -0
  97. data/schema/spec/SupervisorRestart_racy.cfg +7 -0
  98. data/schema/spec/SupervisorRestart_strict.cfg +7 -0
  99. data/schema/spec/TaskClaim.tla +92 -0
  100. data/schema/spec/TaskClaimReadBack.tla +84 -0
  101. data/schema/spec/TaskClaimReadBack_byid.cfg +6 -0
  102. data/schema/spec/TaskClaimReadBack_order.cfg +6 -0
  103. data/schema/spec/TaskClaim_new.cfg +8 -0
  104. data/schema/spec/TaskClaim_old.cfg +9 -0
  105. data/schema/spec/TaskReclaim.tla +110 -0
  106. data/schema/spec/TaskReclaimAttempts.tla +73 -0
  107. data/schema/spec/TaskReclaimAttempts_attempt.cfg +6 -0
  108. data/schema/spec/TaskReclaimAttempts_claimant.cfg +6 -0
  109. data/schema/spec/TaskReclaim_new.cfg +8 -0
  110. data/schema/spec/TaskReclaim_old.cfg +8 -0
  111. data/schema/spec/WaitRegistration.tla +170 -0
  112. data/schema/spec/WaitRegistrationSub.tla +133 -0
  113. data/schema/spec/WaitRegistrationSub_fixed.cfg +6 -0
  114. data/schema/spec/WaitRegistrationSub_fixed_guarded.cfg +6 -0
  115. data/schema/spec/WaitRegistrationSub_guardonly_reg.cfg +6 -0
  116. data/schema/spec/WaitRegistrationSub_guardonly_res.cfg +6 -0
  117. data/schema/spec/WaitRegistrationSub_head_reg.cfg +6 -0
  118. data/schema/spec/WaitRegistrationSub_head_res.cfg +6 -0
  119. data/schema/spec/WaitRegistrationSub_noclear_reg.cfg +6 -0
  120. data/schema/spec/WaitRegistrationSub_noclear_res.cfg +6 -0
  121. data/schema/spec/WaitRegistrationSub_unfencedreg_reg.cfg +6 -0
  122. data/schema/spec/WaitRegistrationSub_unfencedreg_res.cfg +6 -0
  123. data/schema/spec/WaitRegistration_new.cfg +10 -0
  124. data/schema/spec/WaitRegistration_old.cfg +11 -0
  125. data/schema/spec/WaitRegistration_residual.cfg +11 -0
  126. data/schema/spec/WaitRegistration_sweep.cfg +11 -0
  127. data/schema/spec/actorfs_check_test.go +165 -0
  128. data/schema/spec/claim_check_test.go +387 -0
  129. data/schema/spec/competing_claim_test.go +194 -0
  130. data/schema/spec/epoch_check_test.go +128 -0
  131. data/schema/spec/go.mod +3 -0
  132. data/schema/spec/supervisorrestart_check_test.go +131 -0
  133. data/schema/spec/taskclaim_check_test.go +135 -0
  134. data/schema/spec/taskreclaim_check_test.go +125 -0
  135. data/schema/spec/tlc-check.sh +45 -0
  136. data/schema/spec/tlc-matrix.txt +68 -0
  137. data/schema/spec/wait_check_test.go +256 -0
  138. metadata +121 -2
@@ -0,0 +1,421 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shikibu
4
+ module Storage
5
+ # Channel claim/wait-registration operations mixed into SequelStorage.
6
+ # Methods use @db and the storage helpers exactly as in SequelStorage.
7
+ module ChannelOps
8
+ # How old a channel-message claim must be before another competing
9
+ # consumer may take it over. Aligned with the workflow lock lease (300s).
10
+ CHANNEL_CLAIM_STALE_SECONDS = 300
11
+
12
+ # How old an outbox 'processing' claim must be before another relayer
13
+ # may reclaim it. Aligned with the workflow lock lease (300s).
14
+ OUTBOX_CLAIM_STALE_SECONDS = 300
15
+
16
+ def claim_message(message_id:, instance_id:)
17
+ claim_message_in_transaction(message_id: message_id, instance_id: instance_id)
18
+ end
19
+
20
+ def get_next_message(channel:, mode:, instance_id:, cursor_id: nil)
21
+ case mode
22
+ when ChannelMode::COMPETING
23
+ get_next_competing_message(channel, instance_id)
24
+ when ChannelMode::BROADCAST
25
+ get_next_broadcast_message(channel, instance_id, cursor_id)
26
+ end
27
+ end
28
+
29
+ # Deliver a pending channel message to an instance waiting on channel,
30
+ # under the instance lock (fresh epoch identity) with fenced writes.
31
+ # Only a registered wait takes a message: the instance must be
32
+ # waiting_for_message with the wait's activity id on the subscription;
33
+ # anyone else leaves the message pending for its next receive.
34
+ # Broadcast delivers the oldest message after the subscriber's cursor
35
+ # (so concurrent publishes are never skipped) and advances the cursor;
36
+ # competing/direct claims message_id (or the oldest visible message)
37
+ # and deletes it with its claim once the history record is written.
38
+ # @param worker_id [String] Worker ID (an epoch suffix is added)
39
+ # @return [Hash, nil] Delivery result or nil if nothing was delivered
40
+ def deliver_channel_message(instance_id:, channel:, worker_id:, message_id: nil)
41
+ lock_id = "#{worker_id}##{SecureRandom.hex(8)}"
42
+ return nil unless try_acquire_lock(instance_id, lock_id)
43
+
44
+ begin
45
+ result = immediate_transaction do
46
+ sub = @db[:channel_subscriptions]
47
+ .where(instance_id: instance_id, channel: channel)
48
+ .exclude(activity_id: nil)
49
+ .first
50
+ next nil unless sub
51
+
52
+ # Conditional flip: only a waiting instance is resumed by delivery
53
+ resumed = @db[:workflow_instances]
54
+ .where(instance_id: instance_id, locked_by: lock_id, status: Status::WAITING_FOR_MESSAGE)
55
+ .update(status: Status::RUNNING, updated_at: current_timestamp)
56
+ next nil if resumed.zero?
57
+
58
+ message = deliverable_message(sub, message_id)
59
+ raise Sequel::Rollback unless message
60
+
61
+ recorded = append_history(
62
+ lock_id: lock_id,
63
+ instance_id: instance_id,
64
+ activity_id: sub[:activity_id],
65
+ event_type: EventType::CHANNEL_MESSAGE_RECEIVED,
66
+ event_data: {
67
+ channel: channel,
68
+ message_id: message[:message_id],
69
+ data: message[:data],
70
+ metadata: message[:metadata],
71
+ published_at: Time.now.utc.iso8601
72
+ }
73
+ )
74
+ # The wait already has an outcome: leave the message unconsumed
75
+ raise Sequel::Rollback unless recorded
76
+
77
+ consume_delivered_message(sub, message)
78
+
79
+ { instance_id: instance_id, activity_id: sub[:activity_id] }
80
+ end
81
+
82
+ # Send NOTIFY for workflow resumable (outside transaction for PostgreSQL)
83
+ send_notify(Notify::Channel::WORKFLOW_RESUMABLE, { wf_id: instance_id }) if result
84
+
85
+ result
86
+ rescue StandardError => e
87
+ warn "[Shikibu::Storage] Failed to deliver on #{channel} to #{instance_id}: #{e.class}: #{e.message}"
88
+ nil
89
+ ensure
90
+ release_lock(instance_id, lock_id)
91
+ end
92
+ end
93
+
94
+ # A receive consumed a message on channel: clear the subscription's
95
+ # registered wait (it is satisfied) and, for broadcast, advance the
96
+ # cursor past the message's row id.
97
+ def mark_channel_message_consumed(instance_id:, channel:, cursor_message_id: nil)
98
+ updates = { activity_id: nil, timeout_at: nil }
99
+ if cursor_message_id
100
+ updates[:cursor_message_id] = cursor_message_id
101
+ record_broadcast_delivery_cursor(instance_id: instance_id, channel: channel, cursor_id: cursor_message_id)
102
+ end
103
+ @db[:channel_subscriptions].where(instance_id: instance_id, channel: channel).update(updates)
104
+ end
105
+
106
+ # Cleanup old channel messages older than retention_days
107
+ # @param retention_days [Integer] Number of days to retain messages
108
+ # @return [Integer] Number of deleted messages
109
+ def cleanup_old_channel_messages(retention_days:)
110
+ cutoff_time = current_timestamp - (retention_days * 24 * 60 * 60)
111
+ @db[:channel_messages]
112
+ .where { published_at < cutoff_time }
113
+ .delete
114
+ end
115
+
116
+ def get_next_competing_message(channel, instance_id)
117
+ # Hidden only when a *different live* instance holds a fresh claim.
118
+ # Own claims stay visible (replay drain); stale or terminal-owner
119
+ # claims are reclaimable via claim_message takeover.
120
+ stale_before = Time.now.utc - ChannelOps::CHANNEL_CLAIM_STALE_SECONDS
121
+ terminal_owners = @db[:workflow_instances]
122
+ .where(status: %w[completed failed cancelled])
123
+ .select(:instance_id)
124
+ hidden_claims = @db[:channel_message_claims]
125
+ .exclude(instance_id: instance_id)
126
+ .where { claimed_at >= stale_before }
127
+ .exclude(instance_id: terminal_owners)
128
+ .select(:message_id)
129
+
130
+ row = @db[:channel_messages]
131
+ .where(channel: channel)
132
+ .exclude(message_id: hidden_claims)
133
+ .order(:published_at)
134
+ .first
135
+ deserialize_channel_message(row)
136
+ end
137
+
138
+ def get_next_broadcast_message(channel, _instance_id, cursor_id)
139
+ query = @db[:channel_messages].where(channel: channel)
140
+ query = query.where { id > cursor_id } if cursor_id
141
+ row = query.order(:id).first
142
+ deserialize_channel_message(row)
143
+ end
144
+
145
+ def deserialize_channel_message(row)
146
+ return nil unless row
147
+
148
+ data = if row[:data_type] == DataType::BINARY
149
+ row[:data_binary]
150
+ else
151
+ parse_json(row[:data])
152
+ end
153
+ metadata = parse_json(row[:metadata])
154
+
155
+ {
156
+ id: row[:id],
157
+ message_id: row[:message_id],
158
+ channel: row[:channel],
159
+ data: data,
160
+ metadata: metadata,
161
+ published_at: row[:published_at]
162
+ }
163
+ end
164
+
165
+ def publish_message(channel:, data:, metadata: nil, data_type: DataType::JSON)
166
+ message_id = SecureRandom.uuid
167
+
168
+ if data_type == DataType::BINARY
169
+ @db[:channel_messages].insert(
170
+ channel: channel,
171
+ message_id: message_id,
172
+ data_type: data_type,
173
+ data_binary: Sequel.blob(data),
174
+ metadata: metadata ? serialize_json(metadata) : nil,
175
+ published_at: current_timestamp
176
+ )
177
+ else
178
+ @db[:channel_messages].insert(
179
+ channel: channel,
180
+ message_id: message_id,
181
+ data_type: data_type,
182
+ data: serialize_json(data),
183
+ metadata: metadata ? serialize_json(metadata) : nil,
184
+ published_at: current_timestamp
185
+ )
186
+ end
187
+
188
+ # Send NOTIFY for new message (deferred if in transaction)
189
+ notify_payload = { ch: channel, msg_id: message_id }
190
+ if in_transaction?
191
+ register_post_commit_callback do
192
+ send_notify(Notify::Channel::CHANNEL_MESSAGE, notify_payload)
193
+ end
194
+ else
195
+ send_notify(Notify::Channel::CHANNEL_MESSAGE, notify_payload)
196
+ end
197
+
198
+ message_id
199
+ end
200
+
201
+ # Atomically register that a workflow is waiting for a channel message
202
+ # and release its lock. Re-checks for a deliverable pending message
203
+ # inside the registration transaction: if one exists the wait is NOT
204
+ # registered and the instance stays 'running' (lock still released) so
205
+ # the resumable sweep replays it into the pending message. This closes
206
+ # the missed-wakeup window between the caller's pending check and the
207
+ # wait registration.
208
+ #
209
+ # @return [Boolean] true if the wait was registered, false if a pending
210
+ # message was found (workflow left running, lock released)
211
+ # @raise [LockLostError] unless worker_id still holds the lock
212
+ # @raise [InstanceTerminatedError] if the instance already terminated
213
+ def register_channel_wait(instance_id:, worker_id:, channel:, mode:, activity_id:, timeout_at: nil)
214
+ immediate_transaction do
215
+ # A broadcast subscription this registration creates takes its
216
+ # cursor before the re-check. Taken after it, under READ COMMITTED
217
+ # the cursor could pass a message committed in between that the
218
+ # re-check missed, and the requeue backstop would never see it.
219
+ if mode == ChannelMode::BROADCAST && get_subscription(instance_id: instance_id, channel: channel).nil?
220
+ subscribe_to_channel(instance_id: instance_id, channel: channel, mode: mode)
221
+ end
222
+
223
+ # Re-check pending inside the tx
224
+ if pending_channel_message?(instance_id: instance_id, channel: channel, mode: mode)
225
+ # Release the lock only (fenced); keep status='running' so the
226
+ # resumable sweep replays into the pending message.
227
+ raise LockLostError, instance_id if release_lock(instance_id, worker_id).zero?
228
+
229
+ next false
230
+ end
231
+
232
+ # Suspend and release first, fenced on the lock (terminal statuses
233
+ # are absorbing); only then register the wait on the subscription.
234
+ suspended = @db[:workflow_instances]
235
+ .where(instance_id: instance_id, locked_by: worker_id)
236
+ .exclude(status: Status::TERMINAL)
237
+ .update(status: Status::WAITING_FOR_MESSAGE, current_activity_id: activity_id,
238
+ locked_by: nil, locked_at: nil, lock_expires_at: nil, lock_timeout_seconds: nil,
239
+ updated_at: current_timestamp)
240
+ raise_status_write_refused(instance_id, worker_id) if suspended.zero?
241
+
242
+ subscribe_to_channel(
243
+ instance_id: instance_id,
244
+ channel: channel,
245
+ mode: mode,
246
+ activity_id: activity_id,
247
+ timeout_at: timeout_at
248
+ )
249
+ true
250
+ end
251
+ end
252
+
253
+ # Requeue 'waiting_for_message' workflows that have pending messages.
254
+ # Backstop for the residual missed-wakeup race: under read-committed
255
+ # isolation a publisher's waiting-subscriber scan can still run before
256
+ # the wait registration commits.
257
+ #
258
+ # @return [Integer] Number of workflows requeued
259
+ def requeue_channel_waits_with_pending
260
+ waiting = @db[:channel_subscriptions]
261
+ .join(:workflow_instances, instance_id: :instance_id)
262
+ .where(Sequel[:workflow_instances][:status] => Status::WAITING_FOR_MESSAGE)
263
+ .where(Sequel[:workflow_instances][:locked_by] => nil)
264
+ .where(Sequel[:workflow_instances][:framework] => 'ruby')
265
+ .where { Sequel.~(Sequel[:channel_subscriptions][:activity_id] => nil) }
266
+ .select_all(:channel_subscriptions)
267
+ .all
268
+
269
+ requeued = 0
270
+ waiting.each do |sub|
271
+ next unless pending_channel_message?(
272
+ instance_id: sub[:instance_id],
273
+ channel: sub[:channel],
274
+ mode: sub[:mode]
275
+ )
276
+
277
+ requeued += 1 if requeue_waiting_instance(sub[:instance_id])
278
+ end
279
+ requeued
280
+ end
281
+
282
+ # Delete a channel message and its claim (explicit claim delete first:
283
+ # SQLite may run with foreign keys off, so ON DELETE CASCADE cannot be
284
+ # relied upon).
285
+ def delete_channel_message(message_id)
286
+ @db.transaction do
287
+ @db[:channel_message_claims].where(message_id: message_id).delete
288
+ @db[:channel_messages].where(message_id: message_id).delete
289
+ end
290
+ end
291
+
292
+ # True if a deliverable pending message exists for this subscription.
293
+ # Broadcast: any message after the cursor. Competing: not hidden by a
294
+ # fresh claim of a different live instance.
295
+ def pending_channel_message?(instance_id:, channel:, mode:)
296
+ case mode
297
+ when ChannelMode::BROADCAST
298
+ sub = get_subscription(instance_id: instance_id, channel: channel)
299
+ cursor = broadcast_delivery_cursor(instance_id: instance_id, channel: channel) ||
300
+ sub&.dig(:cursor_message_id) || 0
301
+ !@db[:channel_messages]
302
+ .where(channel: channel)
303
+ .where { id > cursor }
304
+ .empty?
305
+ else # competing (+ direct, which resolves to a private channel)
306
+ stale_before = Time.now.utc - CHANNEL_CLAIM_STALE_SECONDS
307
+ terminal_owners = @db[:workflow_instances]
308
+ .where(status: %w[completed failed cancelled])
309
+ .select(:instance_id)
310
+ hidden_claims = @db[:channel_message_claims]
311
+ .exclude(instance_id: instance_id)
312
+ .where { claimed_at >= stale_before }
313
+ .exclude(instance_id: terminal_owners)
314
+ .select(:message_id)
315
+ !@db[:channel_messages]
316
+ .where(channel: channel)
317
+ .exclude(message_id: hidden_claims)
318
+ .empty?
319
+ end
320
+ end
321
+
322
+ # In-transaction variant of claim_message used by
323
+ # deliver_channel_message (same takeover rules).
324
+ def claim_message_in_transaction(message_id:, instance_id:)
325
+ # Lock the message row first (SQLite transactions are serialized
326
+ # already). Every claimer does, so competing claims of one message
327
+ # queue up here: inside a transaction the loser waits for the winner
328
+ # to commit and then finds the message consumed, instead of racing
329
+ # it into a deadlock (MySQL) or a claims FK violation over the claim
330
+ # and the message rows. A consumed message is not claimed.
331
+ message = @db[:channel_messages].where(message_id: message_id)
332
+ message = message.for_update unless @db.database_type == :sqlite
333
+ return false unless message.get(:message_id)
334
+
335
+ now = current_timestamp
336
+ stale_before = now - CHANNEL_CLAIM_STALE_SECONDS
337
+ terminal_owners = @db[:workflow_instances]
338
+ .where(status: %w[completed failed cancelled])
339
+ .select(:instance_id)
340
+
341
+ taken = @db[:channel_message_claims]
342
+ .where(message_id: message_id)
343
+ .where(
344
+ Sequel.|(
345
+ { instance_id: instance_id },
346
+ Sequel.lit('claimed_at < ?', stale_before),
347
+ Sequel.lit('instance_id IN ?', terminal_owners)
348
+ )
349
+ )
350
+ .update(instance_id: instance_id, claimed_at: now)
351
+ return true if taken.positive?
352
+
353
+ # Savepoint: losing the insert race must not abort an enclosing
354
+ # transaction on PostgreSQL.
355
+ @db.transaction(savepoint: true) do
356
+ @db[:channel_message_claims].insert(
357
+ message_id: message_id,
358
+ instance_id: instance_id,
359
+ claimed_at: now
360
+ )
361
+ end
362
+ true
363
+ rescue Sequel::UniqueConstraintViolation, Sequel::ForeignKeyConstraintViolation
364
+ # Lost the claim race, or the message was consumed meanwhile
365
+ false
366
+ end
367
+
368
+ private
369
+
370
+ # Flip one waiting, unlocked instance back to running and clear its
371
+ # wait in the same transaction: it replays into its receive, so the
372
+ # registered activity id and deadline are void (a later timeout must
373
+ # not fire for them). Conditional: a concurrent cancel/delivery since
374
+ # the scan wins. Per id, so MySQL never updates workflow_instances
375
+ # while reading it in a subquery (error 1093).
376
+ def requeue_waiting_instance(instance_id)
377
+ @db.transaction do
378
+ changed = @db[:workflow_instances]
379
+ .where(instance_id: instance_id, status: Status::WAITING_FOR_MESSAGE, locked_by: nil)
380
+ .update(status: Status::RUNNING, updated_at: current_timestamp)
381
+ next false if changed.zero?
382
+
383
+ @db[:channel_subscriptions].where(instance_id: instance_id).update(activity_id: nil, timeout_at: nil)
384
+ true
385
+ end
386
+ end
387
+
388
+ # The message deliver_channel_message should hand to sub, or nil
389
+ def deliverable_message(sub, message_id)
390
+ if sub[:mode] == ChannelMode::BROADCAST
391
+ cursor = broadcast_delivery_cursor(instance_id: sub[:instance_id], channel: sub[:channel]) ||
392
+ sub[:cursor_message_id]
393
+ return get_next_broadcast_message(sub[:channel], sub[:instance_id], cursor)
394
+ end
395
+
396
+ message = if message_id
397
+ deserialize_channel_message(@db[:channel_messages].where(message_id: message_id).first)
398
+ else
399
+ get_next_competing_message(sub[:channel], sub[:instance_id])
400
+ end
401
+ return nil unless message
402
+ return nil unless claim_message_in_transaction(message_id: message[:message_id], instance_id: sub[:instance_id])
403
+
404
+ message
405
+ end
406
+
407
+ # Consume a delivered message and clear the subscription's wait
408
+ def consume_delivered_message(sub, message)
409
+ waits = @db[:channel_subscriptions].where(instance_id: sub[:instance_id], channel: sub[:channel])
410
+ if sub[:mode] == ChannelMode::BROADCAST
411
+ waits.update(cursor_message_id: message[:id], activity_id: nil, timeout_at: nil)
412
+ record_broadcast_delivery_cursor(instance_id: sub[:instance_id], channel: sub[:channel],
413
+ cursor_id: message[:id])
414
+ else
415
+ delete_channel_message(message[:message_id])
416
+ waits.update(activity_id: nil, timeout_at: nil)
417
+ end
418
+ end
419
+ end
420
+ end
421
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shikibu
4
+ module Storage
5
+ # Durable broadcast cursors. Unlike subscription rows, these survive
6
+ # recur iteration cleanup and carry delivery progress into the next iteration.
7
+ module BroadcastCursorOps
8
+ # Durable broadcast cursor (nil when the instance never subscribed).
9
+ # Unlike the subscription row, this cursor survives recur iteration cleanup.
10
+ def broadcast_delivery_cursor(instance_id:, channel:)
11
+ row = @db[:channel_delivery_cursors]
12
+ .where(instance_id: instance_id, channel: channel)
13
+ .first
14
+ row && row[:last_delivered_id]
15
+ end
16
+
17
+ # Upsert the durable broadcast cursor. Consumption advances it in the
18
+ # same transaction as the message consumption/history record.
19
+ def record_broadcast_delivery_cursor(instance_id:, channel:, cursor_id:)
20
+ now = current_timestamp
21
+ values = {
22
+ channel: channel, instance_id: instance_id, last_delivered_id: cursor_id, updated_at: now
23
+ }
24
+ if mysql?
25
+ @db[:channel_delivery_cursors].on_duplicate_key_update(
26
+ last_delivered_id: cursor_id, updated_at: now
27
+ ).insert(values)
28
+ else
29
+ @db[:channel_delivery_cursors].insert_conflict(
30
+ target: %i[channel instance_id],
31
+ update: { last_delivered_id: cursor_id, updated_at: now }
32
+ ).insert(values)
33
+ end
34
+ end
35
+ end
36
+ end
37
+ end