shikibu 0.3.0 → 0.4.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 (137) 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 +33 -19
  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/replay.rb +242 -107
  15. data/lib/shikibu/storage/actor_ops.rb +331 -0
  16. data/lib/shikibu/storage/channel_ops.rb +421 -0
  17. data/lib/shikibu/storage/cursor_ops.rb +37 -0
  18. data/lib/shikibu/storage/sequel_storage.rb +400 -324
  19. data/lib/shikibu/storage/sqlite_ops.rb +58 -0
  20. data/lib/shikibu/supervisor.rb +279 -0
  21. data/lib/shikibu/tasks.rb +193 -0
  22. data/lib/shikibu/version.rb +1 -1
  23. data/lib/shikibu/worker.rb +155 -73
  24. data/lib/shikibu/workflow.rb +106 -48
  25. data/lib/shikibu.rb +4 -0
  26. data/schema/SEMANTICS.md +351 -0
  27. data/schema/db/migrations/mysql/20261123000000_outbox_claimed_at.sql +5 -0
  28. data/schema/db/migrations/mysql/20261201000000_actor_registry.sql +24 -0
  29. data/schema/db/migrations/mysql/20261202000000_actor_capabilities.sql +15 -0
  30. data/schema/db/migrations/mysql/20261203000000_payload_blobs.sql +11 -0
  31. data/schema/db/migrations/mysql/20261204000000_actor_fs.sql +13 -0
  32. data/schema/db/migrations/mysql/20261205000000_actor_tasks.sql +15 -0
  33. data/schema/db/migrations/mysql/20261206000000_actor_tasks_claimed_at.sql +7 -0
  34. data/schema/db/migrations/mysql/20261207000000_add_sandboxed.sql +5 -0
  35. data/schema/db/migrations/mysql/20261208000000_widen_actor_owner_columns.sql +15 -0
  36. data/schema/db/migrations/postgresql/20261123000000_outbox_claimed_at.sql +5 -0
  37. data/schema/db/migrations/postgresql/20261201000000_actor_registry.sql +23 -0
  38. data/schema/db/migrations/postgresql/20261202000000_actor_capabilities.sql +15 -0
  39. data/schema/db/migrations/postgresql/20261203000000_payload_blobs.sql +11 -0
  40. data/schema/db/migrations/postgresql/20261204000000_actor_fs.sql +13 -0
  41. data/schema/db/migrations/postgresql/20261205000000_actor_tasks.sql +15 -0
  42. data/schema/db/migrations/postgresql/20261206000000_actor_tasks_claimed_at.sql +7 -0
  43. data/schema/db/migrations/postgresql/20261207000000_add_sandboxed.sql +5 -0
  44. data/schema/db/migrations/postgresql/20261208000000_widen_actor_owner_columns.sql +7 -0
  45. data/schema/db/migrations/sqlite/20261123000000_outbox_claimed_at.sql +5 -0
  46. data/schema/db/migrations/sqlite/20261201000000_actor_registry.sql +23 -0
  47. data/schema/db/migrations/sqlite/20261202000000_actor_capabilities.sql +15 -0
  48. data/schema/db/migrations/sqlite/20261203000000_payload_blobs.sql +11 -0
  49. data/schema/db/migrations/sqlite/20261204000000_actor_fs.sql +13 -0
  50. data/schema/db/migrations/sqlite/20261205000000_actor_tasks.sql +15 -0
  51. data/schema/db/migrations/sqlite/20261206000000_actor_tasks_claimed_at.sql +7 -0
  52. data/schema/db/migrations/sqlite/20261207000000_add_sandboxed.sql +5 -0
  53. data/schema/db/migrations/sqlite/20261208000000_widen_actor_owner_columns.sql +7 -0
  54. data/schema/docs/column-values.md +10 -0
  55. data/schema/spec/ActorFS.tla +117 -0
  56. data/schema/spec/ActorFS_lww_monotonic.cfg +7 -0
  57. data/schema/spec/ActorFS_new.cfg +8 -0
  58. data/schema/spec/ActorFS_old.cfg +7 -0
  59. data/schema/spec/CompetingMessageClaim.tla +127 -0
  60. data/schema/spec/CompetingMessageClaimSplit.tla +132 -0
  61. data/schema/spec/CompetingMessageClaimSplit_atomic_lost.cfg +7 -0
  62. data/schema/spec/CompetingMessageClaimSplit_atomic_once.cfg +7 -0
  63. data/schema/spec/CompetingMessageClaimSplit_fixed.cfg +7 -0
  64. data/schema/spec/CompetingMessageClaimSplit_split_lost.cfg +7 -0
  65. data/schema/spec/CompetingMessageClaimSplit_split_once.cfg +7 -0
  66. data/schema/spec/CompetingMessageClaimSplit_waitonly_lost.cfg +7 -0
  67. data/schema/spec/CompetingMessageClaimSplit_waitonly_once.cfg +7 -0
  68. data/schema/spec/CompetingMessageClaim_new.cfg +10 -0
  69. data/schema/spec/CompetingMessageClaim_old.cfg +11 -0
  70. data/schema/spec/EpochFencing.tla +87 -0
  71. data/schema/spec/EpochFencingRuns.tla +107 -0
  72. data/schema/spec/EpochFencingRuns_epoch.cfg +6 -0
  73. data/schema/spec/EpochFencingRuns_none.cfg +6 -0
  74. data/schema/spec/EpochFencingRuns_witness.cfg +6 -0
  75. data/schema/spec/EpochFencingRuns_worker.cfg +6 -0
  76. data/schema/spec/EpochFencingRuns_worker1.cfg +6 -0
  77. data/schema/spec/EpochFencing_new.cfg +8 -0
  78. data/schema/spec/EpochFencing_old.cfg +9 -0
  79. data/schema/spec/InstanceClaim.tla +196 -0
  80. data/schema/spec/InstanceClaimVerdict.tla +116 -0
  81. data/schema/spec/InstanceClaimVerdict_changedrows.cfg +6 -0
  82. data/schema/spec/InstanceClaimVerdict_changedrows_live.cfg +6 -0
  83. data/schema/spec/InstanceClaimVerdict_foundrows.cfg +6 -0
  84. data/schema/spec/InstanceClaimVerdict_foundrows_live.cfg +6 -0
  85. data/schema/spec/InstanceClaim_atomic_unfenced.cfg +9 -0
  86. data/schema/spec/InstanceClaim_live.cfg +9 -0
  87. data/schema/spec/InstanceClaim_new.cfg +9 -0
  88. data/schema/spec/InstanceClaim_old.cfg +11 -0
  89. data/schema/spec/InstanceClaim_racy_fenced.cfg +9 -0
  90. data/schema/spec/README.md +97 -0
  91. data/schema/spec/SupervisorRestart.tla +108 -0
  92. data/schema/spec/SupervisorRestartCAS.tla +84 -0
  93. data/schema/spec/SupervisorRestartCAS_nonsticky.cfg +6 -0
  94. data/schema/spec/SupervisorRestartCAS_snapshot.cfg +6 -0
  95. data/schema/spec/SupervisorRestartCAS_sticky.cfg +6 -0
  96. data/schema/spec/SupervisorRestart_racy.cfg +7 -0
  97. data/schema/spec/SupervisorRestart_strict.cfg +7 -0
  98. data/schema/spec/TaskClaim.tla +92 -0
  99. data/schema/spec/TaskClaimReadBack.tla +84 -0
  100. data/schema/spec/TaskClaimReadBack_byid.cfg +6 -0
  101. data/schema/spec/TaskClaimReadBack_order.cfg +6 -0
  102. data/schema/spec/TaskClaim_new.cfg +8 -0
  103. data/schema/spec/TaskClaim_old.cfg +9 -0
  104. data/schema/spec/TaskReclaim.tla +110 -0
  105. data/schema/spec/TaskReclaimAttempts.tla +73 -0
  106. data/schema/spec/TaskReclaimAttempts_attempt.cfg +6 -0
  107. data/schema/spec/TaskReclaimAttempts_claimant.cfg +6 -0
  108. data/schema/spec/TaskReclaim_new.cfg +8 -0
  109. data/schema/spec/TaskReclaim_old.cfg +8 -0
  110. data/schema/spec/WaitRegistration.tla +170 -0
  111. data/schema/spec/WaitRegistrationSub.tla +133 -0
  112. data/schema/spec/WaitRegistrationSub_fixed.cfg +6 -0
  113. data/schema/spec/WaitRegistrationSub_fixed_guarded.cfg +6 -0
  114. data/schema/spec/WaitRegistrationSub_guardonly_reg.cfg +6 -0
  115. data/schema/spec/WaitRegistrationSub_guardonly_res.cfg +6 -0
  116. data/schema/spec/WaitRegistrationSub_head_reg.cfg +6 -0
  117. data/schema/spec/WaitRegistrationSub_head_res.cfg +6 -0
  118. data/schema/spec/WaitRegistrationSub_noclear_reg.cfg +6 -0
  119. data/schema/spec/WaitRegistrationSub_noclear_res.cfg +6 -0
  120. data/schema/spec/WaitRegistrationSub_unfencedreg_reg.cfg +6 -0
  121. data/schema/spec/WaitRegistrationSub_unfencedreg_res.cfg +6 -0
  122. data/schema/spec/WaitRegistration_new.cfg +10 -0
  123. data/schema/spec/WaitRegistration_old.cfg +11 -0
  124. data/schema/spec/WaitRegistration_residual.cfg +11 -0
  125. data/schema/spec/WaitRegistration_sweep.cfg +11 -0
  126. data/schema/spec/actorfs_check_test.go +165 -0
  127. data/schema/spec/claim_check_test.go +387 -0
  128. data/schema/spec/competing_claim_test.go +194 -0
  129. data/schema/spec/epoch_check_test.go +128 -0
  130. data/schema/spec/go.mod +3 -0
  131. data/schema/spec/supervisorrestart_check_test.go +131 -0
  132. data/schema/spec/taskclaim_check_test.go +135 -0
  133. data/schema/spec/taskreclaim_check_test.go +125 -0
  134. data/schema/spec/tlc-check.sh +45 -0
  135. data/schema/spec/tlc-matrix.txt +68 -0
  136. data/schema/spec/wait_check_test.go +256 -0
  137. metadata +121 -2
@@ -1,24 +1,45 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ # Workflow context (replay state, lock epoch) and the deterministic-step
4
+ # helper the kernel calls use with any context.
3
5
  module Shikibu
4
6
  # Context object passed to workflow execution
5
7
  # Provides access to workflow state, history, and operations
6
8
  class WorkflowContext
7
- attr_reader :instance_id, :workflow_name, :worker_id, :storage, :hooks, :last_activity_id
9
+ KERNEL_STEP_ERROR_CODES = {
10
+ TaskConflictError => 'task_conflict',
11
+ TaskNotFoundError => 'task_not_found',
12
+ ActorNameTakenError => 'actor_name_taken',
13
+ FSConflictError => 'fs_conflict',
14
+ SandboxedError => 'sandboxed',
15
+ ChannelPermissionError => 'channel_forbidden',
16
+ NotOwnerError => 'not_owner',
17
+ CursorNotFoundError => 'cursor_not_found',
18
+ InvalidArgumentError => 'invalid_argument'
19
+ }.freeze
20
+ KERNEL_STEP_ERRORS_BY_CODE = KERNEL_STEP_ERROR_CODES.invert.freeze
21
+ KERNEL_STEP_ERRORS_BY_NAME = KERNEL_STEP_ERROR_CODES.keys.to_h { |klass| [klass.name, klass] }.freeze
22
+
23
+ attr_reader :instance_id, :workflow_name, :worker_id, :lock_id, :storage, :hooks, :last_activity_id,
24
+ :run_abort_error, :capability_key
8
25
  attr_accessor :current_activity_id
9
26
 
10
27
  def initialize(
11
28
  instance_id:,
12
29
  workflow_name:,
13
30
  worker_id:,
14
- storage:,
31
+ storage:, lock_id: nil,
15
32
  hooks: nil,
16
33
  history_cache: {},
17
- replaying: false
34
+ replaying: false,
35
+ capability_key: nil
18
36
  )
19
37
  @instance_id = instance_id
20
38
  @workflow_name = workflow_name
21
39
  @worker_id = worker_id
40
+ # Epoch-bearing lock identity; fenced storage writes use this when set.
41
+ # nil means unfenced (e.g. standalone/test contexts holding no lock).
42
+ @lock_id = lock_id
22
43
  @storage = storage
23
44
  @hooks = hooks
24
45
  @history_cache = history_cache
@@ -27,6 +48,33 @@ module Shikibu
27
48
  @compensations = []
28
49
  @direct_subscriptions = Set.new
29
50
  @last_activity_id = nil
51
+ @run_abort_error = nil
52
+ @capability_key = capability_key
53
+ end
54
+
55
+ # True once an infrastructure error has aborted this run.
56
+ def run_aborted?
57
+ !@run_abort_error.nil?
58
+ end
59
+
60
+ # Raise the run's abort error again. Every primitive starts here so a
61
+ # poisoned run stops at once, even if workflow code rescued the first raise.
62
+ def raise_if_run_aborted!
63
+ raise @run_abort_error if @run_abort_error
64
+ end
65
+
66
+ # Mark the run aborted with cause as the original infrastructure error.
67
+ # The first abort wins: later failures are consequences of the same run ending.
68
+ def poison_run!(cause)
69
+ return @run_abort_error if @run_abort_error
70
+
71
+ @run_abort_error = build_run_abort_error(cause)
72
+ end
73
+
74
+ # Poison the context and raise its abort error.
75
+ def abort_run!(cause)
76
+ poison_run!(cause)
77
+ raise @run_abort_error
30
78
  end
31
79
 
32
80
  # Record the last completed activity ID (for on_failure to reference)
@@ -39,6 +87,24 @@ module Shikibu
39
87
  @replaying
40
88
  end
41
89
 
90
+ # Run a storage-touching kernel call (publish, registry, capability and
91
+ # task operations, ...) as a deterministic step (SEMANTICS §2).
92
+ # From workflow code the outcome — result or raised error — is recorded
93
+ # once in history, fenced by the lock epoch, and a replay returns the
94
+ # recording without touching storage. Inside an executing activity body
95
+ # (or on a context holding no lock, i.e. standalone/test use) the call
96
+ # runs directly: the enclosing activity is the unit of caching.
97
+ # Results are JSON-normalized so fresh runs and replays see equal values.
98
+ def step(name, &)
99
+ raise_if_run_aborted!
100
+ return yield if current_activity_id || lock_id.nil?
101
+
102
+ step_id = generate_activity_id(name)
103
+ return replay_step(get_cached_result(step_id)) if cached_result?(step_id)
104
+
105
+ record_step(step_id, &)
106
+ end
107
+
42
108
  # Generate a unique activity ID for deterministic replay
43
109
  # @param name [String] Activity name
44
110
  # @return [String] Activity ID in format "name:counter"
@@ -139,9 +205,11 @@ module Shikibu
139
205
  Channels.subscriptions(self)
140
206
  end
141
207
 
142
- # Restart workflow with new input (tail recursion pattern)
208
+ # End this iteration and run the next one on this same instance with
209
+ # new input (tail recursion pattern).
143
210
  # @param new_input [Hash] New input for the workflow
144
211
  def recur(**new_input)
212
+ raise_if_run_aborted!
145
213
  raise RecurSignal, new_input
146
214
  end
147
215
 
@@ -149,13 +217,14 @@ module Shikibu
149
217
  # @param seconds [Numeric] Seconds to wait
150
218
  # @param timer_id [String, nil] Optional timer ID
151
219
  def sleep(seconds, timer_id: nil)
152
- sleep_until(Time.now + seconds, timer_id: timer_id)
220
+ sleep_until(Time.now.utc + seconds, timer_id: timer_id)
153
221
  end
154
222
 
155
223
  # Wait until a specific time
156
224
  # @param until_time [Time] Time to wait until
157
225
  # @param timer_id [String, nil] Optional timer ID
158
226
  def sleep_until(until_time, timer_id: nil)
227
+ raise_if_run_aborted!
159
228
  timer_id ||= generate_activity_id('timer')
160
229
 
161
230
  # Check if already expired in history
@@ -164,7 +233,7 @@ module Shikibu
164
233
  # Register timer and suspend
165
234
  raise WaitForTimerSignal.new(
166
235
  timer_id: timer_id,
167
- expires_at: until_time,
236
+ expires_at: until_time.respond_to?(:getutc) ? Shikibu.round_up_deadline(until_time) : until_time,
168
237
  activity_id: timer_id
169
238
  )
170
239
  end
@@ -173,26 +242,30 @@ module Shikibu
173
242
  # @param channel [String] Channel name
174
243
  # @param timeout [Numeric, nil] Timeout in seconds
175
244
  # @param mode [Symbol, String] Subscription mode
245
+ # @param capability_token [String, nil] channel_sub token for a sealed channel
176
246
  # @return [Channels::Message]
177
- def receive(channel, timeout: nil, mode: :broadcast)
178
- Channels.receive(self, channel, timeout: timeout, mode: mode)
247
+ def receive(channel, timeout: nil, mode: :broadcast, capability_token: nil)
248
+ raise_if_run_aborted!
249
+ Channels.receive(self, channel, timeout: timeout, mode: mode, capability_token: capability_token)
179
250
  end
180
251
 
181
252
  # Try to receive without blocking (returns nil if no message)
182
253
  # @param channel [String] Channel name
183
254
  # @param mode [Symbol, String] Subscription mode
255
+ # @param capability_token [String, nil] channel_sub token for a sealed channel
184
256
  # @return [Channels::Message, nil]
185
- def try_receive(channel, mode: :broadcast)
186
- Channels.try_receive(self, channel, mode: mode)
257
+ def try_receive(channel, mode: :broadcast, capability_token: nil)
258
+ Channels.try_receive(self, channel, mode: mode, capability_token: capability_token)
187
259
  end
188
260
 
189
261
  # Publish a message to a channel
190
262
  # @param channel [String] Channel name
191
263
  # @param data [Object] Message data
192
264
  # @param metadata [Hash, nil] Optional metadata
265
+ # @param capability_token [String, nil] channel_pub token for a sealed channel
193
266
  # @return [String] Message ID
194
- def publish(channel, data, metadata: nil)
195
- Channels.publish(self, channel, data, metadata: metadata)
267
+ def publish(channel, data, metadata: nil, capability_token: nil)
268
+ Channels.publish(self, channel, data, metadata: metadata, capability_token: capability_token)
196
269
  end
197
270
 
198
271
  # Send a message directly to another workflow instance
@@ -200,9 +273,106 @@ module Shikibu
200
273
  # @param channel [String] Channel name
201
274
  # @param data [Object] Message data
202
275
  # @param metadata [Hash, nil] Optional metadata
276
+ # @param capability_token [String, nil] channel_pub token for a sealed channel
203
277
  # @return [String] Message ID
204
- def send_to(target_instance_id, channel, data, metadata: nil)
205
- Channels.send_to(self, target_instance_id, channel, data, metadata: metadata)
278
+ def send_to(target_instance_id, channel, data, metadata: nil, capability_token: nil)
279
+ Channels.send_to(self, target_instance_id, channel, data, metadata: metadata,
280
+ capability_token: capability_token)
281
+ end
282
+
283
+ private
284
+
285
+ def record_step(step_id)
286
+ result = storage.transaction do
287
+ # Lock proof first: a run that lost its lease applies no effect, and
288
+ # the instance row is locked before the effect's rows (the order a
289
+ # cancel or a delivery takes them in), so neither deadlocks the step.
290
+ storage.assert_lock_held!(instance_id, lock_id)
291
+ value = normalize_step_result(yield)
292
+ storage.append_history(
293
+ lock_id: lock_id, instance_id: instance_id, activity_id: step_id,
294
+ event_type: EventType::ACTIVITY_COMPLETED, event_data: { result: value }
295
+ )
296
+ value
297
+ end
298
+ cache_result(step_id, { event_type: EventType::ACTIVITY_COMPLETED, result: result })
299
+ result
300
+ rescue LockLostError => e
301
+ poison_run!(e)
302
+ raise
303
+ rescue StandardError => e
304
+ # SQLite's Sequel adapter wraps every ArgumentError in DatabaseError
305
+ # (ArgumentError is also its driver-error class). Kernel validation
306
+ # errors must keep their own class and code despite that wrapping.
307
+ error = e.is_a?(Sequel::DatabaseError) && KERNEL_STEP_ERROR_CODES[e.cause.class] ? e.cause : e
308
+ error = InvalidArgumentError.new("invalid JSON payload: #{e.message}") if e.is_a?(JSON::GeneratorError)
309
+ code = KERNEL_STEP_ERROR_CODES[error.class]
310
+ abort_run!(error) unless code
311
+
312
+ record_kernel_step_error(step_id, error, code)
313
+ raise error
206
314
  end
315
+
316
+ def normalize_step_result(value)
317
+ JSON.parse(JSON.generate(value), symbolize_names: true)
318
+ rescue JSON::GeneratorError, TypeError => e
319
+ raise InvalidArgumentError, "step result is not JSON-serializable: #{e.message}"
320
+ end
321
+
322
+ def record_kernel_step_error(step_id, error, code)
323
+ event_data = { error_type: error.class.name, error_message: error.message, code: code }
324
+ begin
325
+ storage.append_history(
326
+ lock_id: lock_id, instance_id: instance_id, activity_id: step_id,
327
+ event_type: EventType::ACTIVITY_FAILED, event_data: event_data
328
+ )
329
+ rescue LockLostError => e
330
+ poison_run!(e)
331
+ raise
332
+ rescue StandardError => e
333
+ abort_run!(e)
334
+ end
335
+ cache_result(step_id, { event_type: EventType::ACTIVITY_FAILED,
336
+ error_type: error.class.name, error_message: error.message, code: code })
337
+ end
338
+
339
+ def replay_step(cached)
340
+ return cached[:result] if cached[:event_type] == EventType::ACTIVITY_COMPLETED
341
+
342
+ error_class = replayable_step_error_class(cached)
343
+ error = error_class ? error_class.new(cached[:error_message]) : StandardError.new(cached[:error_message])
344
+ raise error
345
+ end
346
+
347
+ def replayable_step_error_class(cached)
348
+ by_code = cached[:code] && KERNEL_STEP_ERRORS_BY_CODE[cached[:code].to_s]
349
+ by_code || KERNEL_STEP_ERRORS_BY_NAME[cached[:error_type].to_s]
350
+ end
351
+
352
+ def build_run_abort_error(cause)
353
+ raise RunAbortedError.new("workflow run aborted after #{cause.class}: #{cause.message}"), cause: cause
354
+ rescue RunAbortedError => e
355
+ e
356
+ end
357
+ end
358
+
359
+ # Run block as a deterministic step of ctx (see WorkflowContext#step);
360
+ # other context objects (activity helpers, tests) run it directly.
361
+ def self.deterministic_step(ctx, name, &)
362
+ return yield unless ctx.is_a?(WorkflowContext)
363
+
364
+ ctx.step(name, &)
365
+ end
366
+
367
+ # A deadline that never passes early (S13): MySQL stores TIMESTAMP(0)
368
+ # rounded to the nearest second, and the sweeps expire a deadline when
369
+ # `deadline <= now`, so a deadline with a fraction is rounded up to a whole
370
+ # second (UTC) before it is stored. One already past is left as it is: it
371
+ # fires at the next sweep.
372
+ def self.round_up_deadline(deadline, now = Time.now.utc)
373
+ deadline = deadline.getutc
374
+ return deadline if deadline <= now || deadline.subsec.zero?
375
+
376
+ Time.at(deadline.to_i + 1).utc
207
377
  end
208
378
  end
@@ -70,6 +70,31 @@ module Shikibu
70
70
  end
71
71
  end
72
72
 
73
+ # Raised when a sandboxed workflow attempts a forbidden operation
74
+ class SandboxedError < Error; end
75
+
76
+ # Raised when an infrastructure error aborts the current run. This is
77
+ # deliberately outside StandardError so ordinary workflow rescue clauses
78
+ # cannot swallow it.
79
+ class RunAbortedError < Exception # rubocop:disable Lint/InheritException -- rescue StandardError must not catch it
80
+ end
81
+
82
+ # Raised when a fenced write detects the lock epoch is no longer held
83
+ class LockLostError < Error
84
+ def initialize(instance_id, message = nil)
85
+ super(message || "Lock lost for instance #{instance_id}")
86
+ end
87
+ end
88
+
89
+ # Raised when a fenced status write finds the instance already terminated
90
+ # (e.g. cancelled while this run held the lock). Terminal statuses are
91
+ # absorbing; like a lost lock, the run stops without further writes.
92
+ class InstanceTerminatedError < LockLostError
93
+ def initialize(instance_id)
94
+ super(instance_id, "Instance #{instance_id} already terminated")
95
+ end
96
+ end
97
+
73
98
  # Raised when a lock cannot be acquired
74
99
  class LockNotAcquiredError < Error
75
100
  attr_reader :instance_id
@@ -135,3 +160,34 @@ module Shikibu
135
160
  end
136
161
  end
137
162
  end
163
+
164
+ module Shikibu
165
+ # Optimistic-concurrency conflict on the shared actor filesystem.
166
+ class FSConflictError < Error; end
167
+
168
+ # Permission denied on the shared actor filesystem.
169
+ class ChannelPermissionError < StandardError; end
170
+
171
+ class FSForbiddenError < Error; end
172
+
173
+ # FS operation attempted outside an activity body or during replay.
174
+ class FSOutsideActivityError < Error; end
175
+
176
+ # Task state transition lost the race (already claimed/completed).
177
+ class TaskConflictError < Error; end
178
+
179
+ # Actor name already bound to another instance.
180
+ class ActorNameTakenError < Error; end
181
+
182
+ # Task ID does not exist.
183
+ class TaskNotFoundError < Error; end
184
+
185
+ # The caller does not own the object it tried to change.
186
+ class NotOwnerError < Error; end
187
+
188
+ # A channel-read cursor no longer names an existing message.
189
+ class CursorNotFoundError < Error; end
190
+
191
+ # Kernel argument validation failed before storage was touched.
192
+ class InvalidArgumentError < ArgumentError; end
193
+ end
data/lib/shikibu/fs.rb ADDED
@@ -0,0 +1,93 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shikibu
4
+ # Shared actor filesystem: versioned files under "/actor/{id}/" (private)
5
+ # and "/shared/" (common space).
6
+ #
7
+ # Writes are CAS on version — fs_read returns the version, pass it to
8
+ # fs_write as expected_version; a mismatch raises FSConflictError.
9
+ #
10
+ # Permissions: "/actor/{id}/" is read/written only by its owner
11
+ # (ownership derived from the path); "/shared/" reads are open, writes
12
+ # require an fs_write capability token for the path or "/shared/".
13
+ #
14
+ # FS operations are non-deterministic I/O and MUST run inside an
15
+ # activity: they are allowed exactly while an activity body executes
16
+ # (also in a resumed run — replayed activities never run their bodies);
17
+ # anywhere else they raise FSOutsideActivityError.
18
+ module FS
19
+ module_function
20
+
21
+ def check_activity!(ctx)
22
+ raise FSOutsideActivityError, 'fs operations must run inside an activity' \
23
+ if ctx.current_activity_id.nil?
24
+ end
25
+
26
+ def authorize!(ctx, path, capability_token)
27
+ if path.start_with?('/actor/')
28
+ owner = path.delete_prefix('/actor/').split('/', 2).first
29
+ raise FSForbiddenError, "/actor/#{owner} is owned by another instance" \
30
+ unless owner == ctx.instance_id
31
+
32
+ return
33
+ end
34
+ if path.start_with?('/shared/')
35
+ raise FSForbiddenError, '/shared/ writes require an fs_write capability' \
36
+ if capability_token.nil?
37
+
38
+ ok = Actors.check_capability(ctx, 'fs_write', path, capability_token)
39
+ ok ||= Actors.check_capability(ctx, 'fs_write', '/shared/', capability_token)
40
+ raise FSForbiddenError, "invalid fs_write capability for #{path}" unless ok
41
+
42
+ return
43
+ end
44
+ raise FSForbiddenError, 'path must be under /actor/{id}/ or /shared/'
45
+ end
46
+
47
+ # Read path; returns [data, version] or [nil, 0] when absent.
48
+ def read(ctx, path)
49
+ check_activity!(ctx)
50
+ if path.start_with?('/actor/')
51
+ owner = path.delete_prefix('/actor/').split('/', 2).first
52
+ raise FSForbiddenError, "cannot read another actor's private path" \
53
+ unless owner == ctx.instance_id
54
+ end
55
+ obj = ctx.storage.fs_get(path)
56
+ obj ? [obj[:data], obj[:version]] : [nil, 0]
57
+ end
58
+
59
+ # CAS write: expected 0 = create (fails if exists), >0 = update iff
60
+ # stored version matches. Raises FSConflictError on mismatch.
61
+ def write(ctx, path, data, expected_version, capability_token: nil)
62
+ check_activity!(ctx)
63
+ authorize!(ctx, path, capability_token)
64
+ ctx.storage.fs_put(path, data, ctx.instance_id, expected_version)
65
+ end
66
+
67
+ # List FS objects (path/owner/version — no data) under prefix, ordered
68
+ # by path. Permissions follow read: an actor may only list its own
69
+ # /actor/{id}/ space; /shared/ is open. The prefix is normalized to the
70
+ # owner boundary ("/actor/{id}" -> "/actor/{id}/", "/shared" ->
71
+ # "/shared/") so it cannot match a sibling such as "/actor/{id}-2/".
72
+ def list(ctx, prefix)
73
+ check_activity!(ctx)
74
+ own = "/actor/#{ctx.instance_id}/"
75
+ prefix = own if prefix == own.chomp('/')
76
+ prefix = '/shared/' if prefix == '/shared'
77
+ if prefix.start_with?('/actor/')
78
+ raise FSForbiddenError, "cannot list another actor's private space" \
79
+ unless prefix.start_with?(own)
80
+ elsif !prefix.start_with?('/shared/')
81
+ raise FSForbiddenError, 'prefix must be under /actor/{id}/ or /shared/'
82
+ end
83
+ ctx.storage.fs_list(prefix)
84
+ end
85
+
86
+ # Delete path (expected_version 0 = unconditional).
87
+ def delete(ctx, path, expected_version, capability_token: nil)
88
+ check_activity!(ctx)
89
+ authorize!(ctx, path, capability_token)
90
+ ctx.storage.fs_delete(path, expected_version)
91
+ end
92
+ end
93
+ end
@@ -60,26 +60,22 @@ module Shikibu
60
60
  end
61
61
  end
62
62
 
63
- # Worker for processing expired timers
63
+ # Worker for processing expired timers: fires through the same
64
+ # fenced path as the in-process timer loop (Worker#fire_timer). A
65
+ # timer that is gone, not yet due, or whose instance is not waiting
66
+ # for it is left alone; the scheduler enqueues it again while it is
67
+ # due and still there.
64
68
  class TimerWorker
65
69
  include ::Sidekiq::Job
66
70
 
67
71
  sidekiq_options queue: 'shikibu', retry: 3
68
72
 
69
73
  def perform(instance_id, timer_id)
70
- storage = Shikibu.app.storage
71
-
72
- storage.append_history(
73
- instance_id: instance_id,
74
- activity_id: timer_id,
75
- event_type: EventType::TIMER_EXPIRED,
76
- event_data: { timer_id: timer_id, expired_at: Time.now.iso8601 }
77
- )
78
-
79
- storage.remove_timer(instance_id: instance_id, timer_id: timer_id)
80
- storage.update_instance_status(instance_id, Status::RUNNING)
74
+ app = Shikibu.app
75
+ timer = app.storage.find_expired_timer(instance_id: instance_id, timer_id: timer_id)
76
+ return unless timer
81
77
 
82
- ResumeWorker.perform_async(instance_id)
78
+ ResumeWorker.perform_async(instance_id) if Shikibu::Worker.new(app).fire_timer(timer)
83
79
  end
84
80
  end
85
81
 
@@ -70,12 +70,14 @@ module Shikibu
70
70
  # Route event to workflow
71
71
  event_type = event[:type]
72
72
  target_instance_id = event[:shikibuinstanceid]
73
+ token = event[:capabilitytoken]
74
+ authorize_publish(event_type, target_instance_id, token)
73
75
 
74
76
  # Send event to waiting workflows (Point-to-Point or Broadcast)
75
77
  Shikibu.app.send_event(
76
78
  event_type,
77
79
  event[:data],
78
- metadata: event,
80
+ metadata: event.except(:capabilitytoken),
79
81
  target_instance_id: target_instance_id
80
82
  )
81
83
 
@@ -86,12 +88,21 @@ module Shikibu
86
88
  end
87
89
 
88
90
  accepted
91
+ rescue ChannelPermissionError => e
92
+ forbidden(e.message)
89
93
  rescue JSON::ParserError
90
94
  bad_request('Invalid JSON')
91
95
  rescue StandardError => e
92
96
  internal_error(e.message)
93
97
  end
94
98
 
99
+ # A sealed channel takes events only with a valid channel_pub token
100
+ # (the CloudEvents attribute capabilitytoken), like a publish.
101
+ def authorize_publish(event_type, target_instance_id, token)
102
+ channel = target_instance_id ? "#{event_type}:#{target_instance_id}" : event_type.to_s
103
+ Channels.enforce_capability(Shikibu.app.storage, 'channel_pub', channel, token)
104
+ end
105
+
95
106
  def handle_status(instance_id)
96
107
  status = Shikibu.status(instance_id)
97
108
  json_response(200, { instance_id: instance_id, status: status })
@@ -138,6 +149,7 @@ module Shikibu
138
149
  type: request.get_header('HTTP_CE_TYPE'),
139
150
  specversion: request.get_header('HTTP_CE_SPECVERSION') || '1.0',
140
151
  shikibuinstanceid: request.get_header('HTTP_CE_SHIKIBUINSTANCEID'),
152
+ capabilitytoken: request.get_header('HTTP_CE_CAPABILITYTOKEN'),
141
153
  data: JSON.parse(body, symbolize_names: true)
142
154
  }
143
155
  end
@@ -181,6 +193,10 @@ module Shikibu
181
193
  json_response(400, { error: message })
182
194
  end
183
195
 
196
+ def forbidden(message)
197
+ json_response(403, { error: message, error_type: 'Forbidden', retryable: false })
198
+ end
199
+
184
200
  def not_found
185
201
  json_response(404, { error: 'Not found' })
186
202
  end