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
@@ -86,14 +86,55 @@ module Shikibu
86
86
 
87
87
  module_function
88
88
 
89
+ # Sealed-channel semantics: while no grants of kind exist for the
90
+ # channel it is open to everyone; once the first grant is issued the
91
+ # operation requires a valid capability token.
92
+ #
93
+ # A seal on L also covers every physical name "L:..." (the direct
94
+ # channel of instance X for L is "L:X"), so naming the physical channel
95
+ # cannot bypass the seal send_to and receive enforce on L.
96
+ def enforce_channel_capability(ctx, kind, channel, token)
97
+ enforce_capability(ctx.storage, kind, channel, token)
98
+ end
99
+
100
+ # enforce_channel_capability for callers holding only the storage
101
+ # (the CloudEvents ingress).
102
+ def enforce_capability(storage, kind, channel, token)
103
+ channel_seal_scopes(channel).each do |scope|
104
+ next unless storage.capability_grants?(kind, scope)
105
+
106
+ raise ChannelPermissionError, "channel '#{scope}' is sealed for #{kind}" if token.nil? || token.empty?
107
+
108
+ secret = token.start_with?('cap:') ? token.split(':').last : token
109
+ next if storage.check_capability(kind, scope, Digest::SHA256.hexdigest(secret))
110
+
111
+ raise ChannelPermissionError, "invalid capability for channel '#{scope}'"
112
+ end
113
+ end
114
+
115
+ # A direct channel "L:X" belongs to instance X: another existing
116
+ # instance may not subscribe to, receive from or read it, sealed or not
117
+ # (sending to it stays allowed). Instance IDs may contain ':', so every
118
+ # split point is a candidate X.
119
+ def enforce_direct_privacy(ctx, channel)
120
+ owners = (1...channel.length).select { |i| channel[i] == ':' }.map { |i| channel[(i + 1)..] }
121
+ owners.each do |owner|
122
+ next if owner == ctx.instance_id || ctx.storage.get_instance(owner).nil?
123
+
124
+ raise ChannelPermissionError, "channel '#{channel}' is the direct channel of #{owner}"
125
+ end
126
+ end
127
+
89
128
  # Subscribe to a channel
90
129
  # @param ctx [WorkflowContext] Workflow context
91
130
  # @param channel [String] Channel name
92
131
  # @param mode [Symbol, String] Subscription mode (:broadcast, :competing, :direct)
93
132
  # @raise [ChannelModeConflictError] If channel is already configured with a different mode
94
133
  def subscribe(ctx, channel, mode: :broadcast)
134
+ ctx.raise_if_run_aborted! if ctx.respond_to?(:raise_if_run_aborted!)
95
135
  mode_str = mode.to_s
96
136
  validate_mode!(mode_str)
137
+ guard_direct_channel(ctx, channel) unless mode_str == ChannelMode::DIRECT
97
138
 
98
139
  # For direct mode, use instance-specific channel
99
140
  actual_channel = if mode_str == ChannelMode::DIRECT
@@ -137,7 +178,8 @@ module Shikibu
137
178
  # @param mode [Symbol, String] Subscription mode
138
179
  # @return [Message] Received message
139
180
  # @raise [MessageTimeoutError] If timeout expires
140
- def receive(ctx, channel, timeout: nil, mode: :broadcast)
181
+ def receive(ctx, channel, timeout: nil, mode: :broadcast, capability_token: nil)
182
+ ctx.raise_if_run_aborted!
141
183
  mode_str = mode.to_s
142
184
  activity_id = ctx.generate_activity_id("receive:#{channel}")
143
185
 
@@ -152,23 +194,38 @@ module Shikibu
152
194
  if ctx.replaying? && ctx.cached_result?(activity_id)
153
195
  cached = ctx.get_cached_result(activity_id)
154
196
  return build_message_from_cached(cached) if cached[:event_type] == EventType::CHANNEL_MESSAGE_RECEIVED
197
+ raise ChannelPermissionError, cached[:error_message] if cached[:event_type] == EventType::ACTIVITY_FAILED
155
198
 
156
199
  # Timeout was recorded
157
200
  raise MessageTimeoutError.new(channel, timeout)
158
201
  end
159
202
 
160
- # Try to get pending message immediately
161
- message = try_receive_immediate(ctx, actual_channel, mode_str)
203
+ # Enforcement after the replay cache lookup: replays never re-check.
204
+ # A refusal is itself the receive's recorded outcome.
205
+ begin
206
+ # A direct receive reads this instance's own channel by construction.
207
+ enforce_direct_privacy(ctx, channel) unless mode_str == ChannelMode::DIRECT
208
+ enforce_channel_capability(ctx, 'channel_sub', channel, capability_token)
209
+ rescue ChannelPermissionError => e
210
+ record_receive_refusal(ctx, activity_id, e)
211
+ raise
212
+ end
213
+ mode_str = subscribed_mode(ctx, actual_channel, mode_str)
214
+
215
+ # Try to get pending message immediately (consumed atomically with
216
+ # its history record)
217
+ message = take_pending_message(ctx, actual_channel, mode_str) do |msg|
218
+ record_message_received(ctx, activity_id, actual_channel, msg)
219
+ end
162
220
  if message
163
221
  # Call hook
164
222
  ctx.hooks&.on_event_received&.call(ctx.instance_id, actual_channel, message.data)
165
223
 
166
- record_message_received(ctx, activity_id, actual_channel, message)
167
224
  return message
168
225
  end
169
226
 
170
227
  # No message available, suspend workflow
171
- timeout_at = timeout ? Time.now + timeout : nil
228
+ timeout_at = timeout ? Shikibu.round_up_deadline(Time.now.utc + timeout) : nil
172
229
 
173
230
  raise WaitForChannelSignal.new(
174
231
  channel: actual_channel,
@@ -184,23 +241,34 @@ module Shikibu
184
241
  # @param data [Object] Message data
185
242
  # @param metadata [Hash, nil] Optional metadata
186
243
  # @return [String] Message ID
187
- def publish(ctx, channel, data, metadata: nil)
188
- full_metadata = (metadata || {}).merge(
189
- source_instance_id: ctx.instance_id,
190
- source_workflow: ctx.workflow_name,
191
- published_at: Time.now.iso8601
192
- )
244
+ def publish(ctx, channel, data, metadata: nil, capability_token: nil)
245
+ # Deterministic step: a replay returns the recorded message ID
246
+ # instead of publishing again.
247
+ Shikibu.deterministic_step(ctx, "publish:#{channel}") do
248
+ full_metadata = (metadata || {}).merge(
249
+ source_instance_id: ctx.instance_id,
250
+ source_workflow: ctx.workflow_name,
251
+ published_at: Time.now.iso8601
252
+ )
193
253
 
194
- result = ctx.storage.publish_message(
195
- channel: channel,
196
- data: data,
197
- metadata: full_metadata
198
- )
254
+ enforce_channel_capability(ctx, 'channel_pub', channel, capability_token)
199
255
 
200
- # Call hook
201
- ctx.hooks&.on_event_sent&.call(channel, ctx.workflow_name, data)
256
+ message_id = ctx.storage.publish_message(
257
+ channel: channel,
258
+ data: data,
259
+ metadata: full_metadata
260
+ )
261
+
262
+ # Waiting subscribers are woken only after the publish commits
263
+ ctx.storage.after_commit do
264
+ wake_waiting_subscribers(ctx.storage, channel, message_id, worker_id: ctx.worker_id)
265
+ end
202
266
 
203
- result
267
+ # Call hook
268
+ ctx.hooks&.on_event_sent&.call(channel, ctx.workflow_name, data)
269
+
270
+ message_id
271
+ end
204
272
  end
205
273
 
206
274
  # Send a message directly to a specific workflow instance
@@ -210,21 +278,32 @@ module Shikibu
210
278
  # @param data [Object] Message data
211
279
  # @param metadata [Hash, nil] Optional metadata
212
280
  # @return [String] Message ID
213
- def send_to(ctx, target_instance_id, channel, data, metadata: nil)
214
- direct_channel = "#{channel}:#{target_instance_id}"
215
-
216
- full_metadata = (metadata || {}).merge(
217
- source_instance_id: ctx.instance_id,
218
- source_workflow: ctx.workflow_name,
219
- target_instance_id: target_instance_id,
220
- published_at: Time.now.iso8601
221
- )
281
+ def send_to(ctx, target_instance_id, channel, data, metadata: nil, capability_token: nil)
282
+ Shikibu.deterministic_step(ctx, "send_to:#{channel}") do
283
+ direct_channel = "#{channel}:#{target_instance_id}"
284
+
285
+ full_metadata = (metadata || {}).merge(
286
+ source_instance_id: ctx.instance_id,
287
+ source_workflow: ctx.workflow_name,
288
+ target_instance_id: target_instance_id,
289
+ published_at: Time.now.iso8601
290
+ )
222
291
 
223
- ctx.storage.publish_message(
224
- channel: direct_channel,
225
- data: data,
226
- metadata: full_metadata
227
- )
292
+ enforce_channel_capability(ctx, 'channel_pub', channel, capability_token)
293
+
294
+ message_id = ctx.storage.publish_message(
295
+ channel: direct_channel,
296
+ data: data,
297
+ metadata: full_metadata
298
+ )
299
+
300
+ ctx.storage.after_commit do
301
+ wake_waiting_subscribers(ctx.storage, direct_channel, message_id,
302
+ worker_id: ctx.worker_id, target_instance_id: target_instance_id)
303
+ end
304
+
305
+ message_id
306
+ end
228
307
  end
229
308
 
230
309
  # Receive without blocking (returns nil if no message)
@@ -232,7 +311,7 @@ module Shikibu
232
311
  # @param channel [String] Channel name
233
312
  # @param mode [Symbol, String] Subscription mode
234
313
  # @return [Message, nil] Message or nil
235
- def try_receive(ctx, channel, mode: :broadcast)
314
+ def try_receive(ctx, channel, mode: :broadcast, capability_token: nil)
236
315
  mode_str = mode.to_s
237
316
  actual_channel = if mode_str == ChannelMode::DIRECT
238
317
  "#{channel}:#{ctx.instance_id}"
@@ -240,7 +319,14 @@ module Shikibu
240
319
  channel
241
320
  end
242
321
 
243
- try_receive_immediate(ctx, actual_channel, mode_str)
322
+ # Deterministic step: the outcome (message or nil) is recorded and
323
+ # replayed; sealing is enforced like receive, before any read.
324
+ message = Shikibu.deterministic_step(ctx, "try_receive:#{channel}") do
325
+ enforce_direct_privacy(ctx, channel) unless mode_str == ChannelMode::DIRECT
326
+ enforce_channel_capability(ctx, 'channel_sub', channel, capability_token)
327
+ take_pending_message(ctx, actual_channel, subscribed_mode(ctx, actual_channel, mode_str))&.to_h
328
+ end
329
+ message && Message.new(**message.slice(:id, :channel, :data, :metadata, :published_at))
244
330
  end
245
331
 
246
332
  # List active subscriptions for an instance
@@ -263,17 +349,96 @@ module Shikibu
263
349
  class << self
264
350
  private
265
351
 
352
+ def wake_waiting_subscribers(storage, channel, message_id, worker_id:, target_instance_id: nil)
353
+ if target_instance_id
354
+ storage.deliver_channel_message(
355
+ instance_id: target_instance_id,
356
+ channel: channel,
357
+ message_id: message_id,
358
+ worker_id: worker_id
359
+ )
360
+ return
361
+ end
362
+
363
+ storage.find_waiting_subscriptions(channel: channel).each do |sub|
364
+ delivered = storage.deliver_channel_message(
365
+ instance_id: sub[:instance_id],
366
+ channel: channel,
367
+ message_id: message_id,
368
+ worker_id: worker_id
369
+ )
370
+ break if delivered && sub[:mode] == ChannelMode::COMPETING
371
+ end
372
+ rescue StandardError => e
373
+ # Best-effort wake-up after commit: the worker's delivery poll and
374
+ # the requeue sweep still pick the message up.
375
+ warn "[Shikibu::Channels] Wake-up on #{channel} failed: #{e.class}: #{e.message}"
376
+ end
377
+
378
+ # channel followed by each of its prefixes that ends before a ':' —
379
+ # the channels whose seal applies to it.
380
+ def channel_seal_scopes(channel)
381
+ [channel] + (channel.length - 1).downto(1).select { |i| channel[i] == ':' }.map { |i| channel[0...i] }
382
+ end
383
+
384
+ # subscribe is no step of its own; a channel that can be someone's
385
+ # direct channel gets a recorded privacy check, so a refusal replays.
386
+ def guard_direct_channel(ctx, channel)
387
+ return unless channel.include?(':')
388
+
389
+ Shikibu.deterministic_step(ctx, "subscribe:#{channel}") do
390
+ enforce_direct_privacy(ctx, channel)
391
+ nil
392
+ end
393
+ end
394
+
266
395
  def validate_mode!(mode)
267
396
  return if ChannelMode::ALL.include?(mode)
268
397
 
269
- raise ArgumentError, "Invalid channel mode: #{mode}. Must be one of: #{ChannelMode::ALL.join(', ')}"
398
+ raise InvalidArgumentError, "Invalid channel mode: #{mode}. Must be one of: #{ChannelMode::ALL.join(', ')}"
399
+ end
400
+
401
+ # Take the next pending message for this instance and consume it in
402
+ # one transaction with the caller's history record (the block):
403
+ # competing/direct deletes the message and its claim, broadcast
404
+ # advances the cursor; a wait still registered on the subscription
405
+ # (requeued instance) is satisfied and cleared.
406
+ def take_pending_message(ctx, channel, mode)
407
+ ctx.storage.transaction do
408
+ # Lock proof first: a run that lost its lease consumes nothing
409
+ ctx.storage.assert_lock_held!(ctx.instance_id, ctx.lock_id) if ctx.lock_id
410
+ message, claimed, row_id = try_receive_immediate(ctx, channel, mode)
411
+ next nil unless message
412
+
413
+ yield message if block_given?
414
+ ctx.storage.delete_channel_message(message.id) if claimed
415
+ ctx.storage.mark_channel_message_consumed(instance_id: ctx.instance_id, channel: channel,
416
+ cursor_message_id: claimed ? nil : row_id)
417
+ message
418
+ end
419
+ end
420
+
421
+ # An existing subscription decides the delivery mode (subscribe
422
+ # 'jobs', mode: :competing, then receive 'jobs'); the mode argument
423
+ # selects the direct channel and shapes an implicit subscription.
424
+ def subscribed_mode(ctx, channel, mode)
425
+ return mode if mode == ChannelMode::DIRECT
426
+
427
+ ctx.storage.get_subscription(instance_id: ctx.instance_id, channel: channel)&.dig(:mode) || mode
270
428
  end
271
429
 
272
430
  def try_receive_immediate(ctx, channel, mode)
273
431
  sub = ctx.storage.get_subscription(instance_id: ctx.instance_id, channel: channel)
432
+ if sub.nil? && mode == ChannelMode::BROADCAST
433
+ # Implicit subscription: like an explicit one, it only sees
434
+ # messages published from now on.
435
+ ctx.storage.subscribe_to_channel(instance_id: ctx.instance_id, channel: channel, mode: mode)
436
+ return [nil, false, nil]
437
+ end
274
438
 
275
- # Get cursor for broadcast mode
276
- cursor_id = sub&.dig(:cursor_message_id)
439
+ # Get cursor for broadcast mode (the durable cursor survives recur)
440
+ cursor_id = ctx.storage.broadcast_delivery_cursor(instance_id: ctx.instance_id, channel: channel) ||
441
+ sub&.dig(:cursor_message_id)
277
442
 
278
443
  row = ctx.storage.get_next_message(
279
444
  channel: channel,
@@ -282,45 +447,30 @@ module Shikibu
282
447
  cursor_id: cursor_id
283
448
  )
284
449
 
285
- return nil unless row
450
+ return [nil, false, nil] unless row
286
451
 
287
- # For competing mode, try to claim
288
- if mode == ChannelMode::COMPETING
452
+ # Competing and direct (private channel) both claim the message
453
+ claimed = false
454
+ if [ChannelMode::COMPETING, ChannelMode::DIRECT].include?(mode)
289
455
  claimed = ctx.storage.claim_message(
290
456
  message_id: row[:message_id],
291
457
  instance_id: ctx.instance_id
292
458
  )
293
- return nil unless claimed
459
+ return [nil, false, nil] unless claimed
294
460
  end
295
461
 
296
- # Update cursor for broadcast mode
297
- update_broadcast_cursor(ctx, channel, row[:id]) if mode == ChannelMode::BROADCAST
298
-
299
- build_message(row)
300
- end
301
-
302
- def update_broadcast_cursor(ctx, channel, message_id)
303
- ctx.storage.db[:channel_subscriptions]
304
- .where(instance_id: ctx.instance_id, channel: channel)
305
- .update(cursor_message_id: message_id)
462
+ [build_message(row), claimed, row[:id]]
306
463
  end
307
464
 
465
+ # row is a message from storage.get_next_message, already decoded:
466
+ # decoding its data again breaks string payloads ("hello" fails to
467
+ # parse, "42" turns into 42) and binary ones.
308
468
  def build_message(row)
309
- data = if row[:data_type] == DataType::BINARY
310
- row[:data_binary]
311
- else
312
- raw_data = row[:data]
313
- raw_data.is_a?(String) ? JSON.parse(raw_data, symbolize_names: true) : raw_data
314
- end
315
-
316
- metadata = row[:metadata]
317
- metadata = JSON.parse(metadata, symbolize_names: true) if metadata.is_a?(String)
318
-
319
469
  Message.new(
320
470
  id: row[:message_id],
321
471
  channel: row[:channel],
322
- data: data,
323
- metadata: metadata,
472
+ data: row[:data],
473
+ metadata: row[:metadata],
324
474
  published_at: row[:published_at]
325
475
  )
326
476
  end
@@ -337,8 +487,34 @@ module Shikibu
337
487
  )
338
488
  end
339
489
 
490
+ def record_receive_refusal(ctx, activity_id, error)
491
+ code = WorkflowContext::KERNEL_STEP_ERROR_CODES[error.class]
492
+ event_data = { error_type: error.class.name, error_message: error.message, code: code }
493
+ begin
494
+ ctx.storage.append_history(
495
+ lock_id: ctx.lock_id,
496
+ instance_id: ctx.instance_id,
497
+ activity_id: activity_id,
498
+ event_type: EventType::ACTIVITY_FAILED,
499
+ event_data: event_data
500
+ )
501
+ rescue LockLostError => e
502
+ ctx.poison_run!(e)
503
+ raise e
504
+ rescue StandardError => e
505
+ ctx.abort_run!(e)
506
+ end
507
+ ctx.cache_result(activity_id, {
508
+ event_type: EventType::ACTIVITY_FAILED,
509
+ error_type: error.class.name,
510
+ error_message: error.message,
511
+ code: code
512
+ })
513
+ end
514
+
340
515
  def record_message_received(ctx, activity_id, channel, message)
341
516
  ctx.storage.append_history(
517
+ lock_id: ctx.lock_id,
342
518
  instance_id: ctx.instance_id,
343
519
  activity_id: activity_id,
344
520
  event_type: EventType::CHANNEL_MESSAGE_RECEIVED,
@@ -24,6 +24,14 @@ module Shikibu
24
24
  CANCELLED,
25
25
  RECURRED
26
26
  ].freeze
27
+
28
+ # Final statuses: never left again (no flip back to running/waiting).
29
+ # RECURRED is deliberately absent: it is the live boundary between iterations.
30
+ TERMINAL = [COMPLETED, FAILED, CANCELLED].freeze
31
+
32
+ # Statuses cancel_instance may move to cancelled. COMPENSATING is absent:
33
+ # its compensations must run to the end.
34
+ CANCELLABLE = [RUNNING, WAITING_FOR_EVENT, WAITING_FOR_TIMER, WAITING_FOR_MESSAGE, RECURRED].freeze
27
35
  end
28
36
 
29
37
  # History event types (shared with Python/Go)