shikibu 0.2.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.
- checksums.yaml +4 -4
- data/README.md +121 -0
- data/lib/shikibu/activity.rb +84 -48
- data/lib/shikibu/actors.rb +129 -0
- data/lib/shikibu/app.rb +45 -19
- data/lib/shikibu/blobs.rb +42 -0
- data/lib/shikibu/channels.rb +240 -64
- data/lib/shikibu/constants.rb +8 -0
- data/lib/shikibu/context.rb +184 -14
- data/lib/shikibu/errors.rb +56 -0
- data/lib/shikibu/fs.rb +93 -0
- data/lib/shikibu/integrations/sidekiq.rb +9 -13
- data/lib/shikibu/middleware/rack_app.rb +17 -1
- data/lib/shikibu/replay.rb +248 -100
- data/lib/shikibu/storage/actor_ops.rb +331 -0
- data/lib/shikibu/storage/channel_ops.rb +421 -0
- data/lib/shikibu/storage/cursor_ops.rb +37 -0
- data/lib/shikibu/storage/sequel_storage.rb +400 -324
- data/lib/shikibu/storage/sqlite_ops.rb +58 -0
- data/lib/shikibu/supervisor.rb +279 -0
- data/lib/shikibu/tasks.rb +193 -0
- data/lib/shikibu/typed_payload.rb +189 -0
- data/lib/shikibu/version.rb +1 -1
- data/lib/shikibu/worker.rb +155 -73
- data/lib/shikibu/workflow.rb +203 -50
- data/lib/shikibu.rb +5 -0
- data/schema/SEMANTICS.md +351 -0
- data/schema/db/migrations/mysql/20261123000000_outbox_claimed_at.sql +5 -0
- data/schema/db/migrations/mysql/20261201000000_actor_registry.sql +24 -0
- data/schema/db/migrations/mysql/20261202000000_actor_capabilities.sql +15 -0
- data/schema/db/migrations/mysql/20261203000000_payload_blobs.sql +11 -0
- data/schema/db/migrations/mysql/20261204000000_actor_fs.sql +13 -0
- data/schema/db/migrations/mysql/20261205000000_actor_tasks.sql +15 -0
- data/schema/db/migrations/mysql/20261206000000_actor_tasks_claimed_at.sql +7 -0
- data/schema/db/migrations/mysql/20261207000000_add_sandboxed.sql +5 -0
- data/schema/db/migrations/mysql/20261208000000_widen_actor_owner_columns.sql +15 -0
- data/schema/db/migrations/postgresql/20261123000000_outbox_claimed_at.sql +5 -0
- data/schema/db/migrations/postgresql/20261201000000_actor_registry.sql +23 -0
- data/schema/db/migrations/postgresql/20261202000000_actor_capabilities.sql +15 -0
- data/schema/db/migrations/postgresql/20261203000000_payload_blobs.sql +11 -0
- data/schema/db/migrations/postgresql/20261204000000_actor_fs.sql +13 -0
- data/schema/db/migrations/postgresql/20261205000000_actor_tasks.sql +15 -0
- data/schema/db/migrations/postgresql/20261206000000_actor_tasks_claimed_at.sql +7 -0
- data/schema/db/migrations/postgresql/20261207000000_add_sandboxed.sql +5 -0
- data/schema/db/migrations/postgresql/20261208000000_widen_actor_owner_columns.sql +7 -0
- data/schema/db/migrations/sqlite/20261123000000_outbox_claimed_at.sql +5 -0
- data/schema/db/migrations/sqlite/20261201000000_actor_registry.sql +23 -0
- data/schema/db/migrations/sqlite/20261202000000_actor_capabilities.sql +15 -0
- data/schema/db/migrations/sqlite/20261203000000_payload_blobs.sql +11 -0
- data/schema/db/migrations/sqlite/20261204000000_actor_fs.sql +13 -0
- data/schema/db/migrations/sqlite/20261205000000_actor_tasks.sql +15 -0
- data/schema/db/migrations/sqlite/20261206000000_actor_tasks_claimed_at.sql +7 -0
- data/schema/db/migrations/sqlite/20261207000000_add_sandboxed.sql +5 -0
- data/schema/db/migrations/sqlite/20261208000000_widen_actor_owner_columns.sql +7 -0
- data/schema/docs/column-values.md +10 -0
- data/schema/spec/ActorFS.tla +117 -0
- data/schema/spec/ActorFS_lww_monotonic.cfg +7 -0
- data/schema/spec/ActorFS_new.cfg +8 -0
- data/schema/spec/ActorFS_old.cfg +7 -0
- data/schema/spec/CompetingMessageClaim.tla +127 -0
- data/schema/spec/CompetingMessageClaimSplit.tla +132 -0
- data/schema/spec/CompetingMessageClaimSplit_atomic_lost.cfg +7 -0
- data/schema/spec/CompetingMessageClaimSplit_atomic_once.cfg +7 -0
- data/schema/spec/CompetingMessageClaimSplit_fixed.cfg +7 -0
- data/schema/spec/CompetingMessageClaimSplit_split_lost.cfg +7 -0
- data/schema/spec/CompetingMessageClaimSplit_split_once.cfg +7 -0
- data/schema/spec/CompetingMessageClaimSplit_waitonly_lost.cfg +7 -0
- data/schema/spec/CompetingMessageClaimSplit_waitonly_once.cfg +7 -0
- data/schema/spec/CompetingMessageClaim_new.cfg +10 -0
- data/schema/spec/CompetingMessageClaim_old.cfg +11 -0
- data/schema/spec/EpochFencing.tla +87 -0
- data/schema/spec/EpochFencingRuns.tla +107 -0
- data/schema/spec/EpochFencingRuns_epoch.cfg +6 -0
- data/schema/spec/EpochFencingRuns_none.cfg +6 -0
- data/schema/spec/EpochFencingRuns_witness.cfg +6 -0
- data/schema/spec/EpochFencingRuns_worker.cfg +6 -0
- data/schema/spec/EpochFencingRuns_worker1.cfg +6 -0
- data/schema/spec/EpochFencing_new.cfg +8 -0
- data/schema/spec/EpochFencing_old.cfg +9 -0
- data/schema/spec/InstanceClaim.tla +196 -0
- data/schema/spec/InstanceClaimVerdict.tla +116 -0
- data/schema/spec/InstanceClaimVerdict_changedrows.cfg +6 -0
- data/schema/spec/InstanceClaimVerdict_changedrows_live.cfg +6 -0
- data/schema/spec/InstanceClaimVerdict_foundrows.cfg +6 -0
- data/schema/spec/InstanceClaimVerdict_foundrows_live.cfg +6 -0
- data/schema/spec/InstanceClaim_atomic_unfenced.cfg +9 -0
- data/schema/spec/InstanceClaim_live.cfg +9 -0
- data/schema/spec/InstanceClaim_new.cfg +9 -0
- data/schema/spec/InstanceClaim_old.cfg +11 -0
- data/schema/spec/InstanceClaim_racy_fenced.cfg +9 -0
- data/schema/spec/README.md +97 -0
- data/schema/spec/SupervisorRestart.tla +108 -0
- data/schema/spec/SupervisorRestartCAS.tla +84 -0
- data/schema/spec/SupervisorRestartCAS_nonsticky.cfg +6 -0
- data/schema/spec/SupervisorRestartCAS_snapshot.cfg +6 -0
- data/schema/spec/SupervisorRestartCAS_sticky.cfg +6 -0
- data/schema/spec/SupervisorRestart_racy.cfg +7 -0
- data/schema/spec/SupervisorRestart_strict.cfg +7 -0
- data/schema/spec/TaskClaim.tla +92 -0
- data/schema/spec/TaskClaimReadBack.tla +84 -0
- data/schema/spec/TaskClaimReadBack_byid.cfg +6 -0
- data/schema/spec/TaskClaimReadBack_order.cfg +6 -0
- data/schema/spec/TaskClaim_new.cfg +8 -0
- data/schema/spec/TaskClaim_old.cfg +9 -0
- data/schema/spec/TaskReclaim.tla +110 -0
- data/schema/spec/TaskReclaimAttempts.tla +73 -0
- data/schema/spec/TaskReclaimAttempts_attempt.cfg +6 -0
- data/schema/spec/TaskReclaimAttempts_claimant.cfg +6 -0
- data/schema/spec/TaskReclaim_new.cfg +8 -0
- data/schema/spec/TaskReclaim_old.cfg +8 -0
- data/schema/spec/WaitRegistration.tla +170 -0
- data/schema/spec/WaitRegistrationSub.tla +133 -0
- data/schema/spec/WaitRegistrationSub_fixed.cfg +6 -0
- data/schema/spec/WaitRegistrationSub_fixed_guarded.cfg +6 -0
- data/schema/spec/WaitRegistrationSub_guardonly_reg.cfg +6 -0
- data/schema/spec/WaitRegistrationSub_guardonly_res.cfg +6 -0
- data/schema/spec/WaitRegistrationSub_head_reg.cfg +6 -0
- data/schema/spec/WaitRegistrationSub_head_res.cfg +6 -0
- data/schema/spec/WaitRegistrationSub_noclear_reg.cfg +6 -0
- data/schema/spec/WaitRegistrationSub_noclear_res.cfg +6 -0
- data/schema/spec/WaitRegistrationSub_unfencedreg_reg.cfg +6 -0
- data/schema/spec/WaitRegistrationSub_unfencedreg_res.cfg +6 -0
- data/schema/spec/WaitRegistration_new.cfg +10 -0
- data/schema/spec/WaitRegistration_old.cfg +11 -0
- data/schema/spec/WaitRegistration_residual.cfg +11 -0
- data/schema/spec/WaitRegistration_sweep.cfg +11 -0
- data/schema/spec/actorfs_check_test.go +165 -0
- data/schema/spec/claim_check_test.go +387 -0
- data/schema/spec/competing_claim_test.go +194 -0
- data/schema/spec/epoch_check_test.go +128 -0
- data/schema/spec/go.mod +3 -0
- data/schema/spec/supervisorrestart_check_test.go +131 -0
- data/schema/spec/taskclaim_check_test.go +135 -0
- data/schema/spec/taskreclaim_check_test.go +125 -0
- data/schema/spec/tlc-check.sh +45 -0
- data/schema/spec/tlc-matrix.txt +68 -0
- data/schema/spec/wait_check_test.go +256 -0
- metadata +136 -2
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: cbb66011f1639dc9b15ce02aee8a2cc9fd9d1039004621817e8ce58df5f9dff3
|
|
4
|
+
data.tar.gz: d573acc5e190480e7825f7373a357b029456def581c340b0d6f4de95e3b58587
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: eacc89618a9b72ff69ae7777031b0c1f10554728f34a16869cafc0d38c03c9507ee5d4c8b4b87f4b983bd5d059f24fd3fd6ef769c625f0a4ef055c86770ec780
|
|
7
|
+
data.tar.gz: fb7a2a5acd71407de4b295c5fc23dd2afc815eb87aef002c55e1777ed9110d78bd1c7c04c5805599c3abd199873aafd391a6a9d8db9d4fc924f1c5baac97af36
|
data/README.md
CHANGED
|
@@ -28,6 +28,7 @@ Shikibu is a Ruby port of [Edda](https://github.com/i2y/edda) (Python), providin
|
|
|
28
28
|
- ☁️ **CloudEvents Support**: Native support for CloudEvents protocol via Rack middleware
|
|
29
29
|
- ⏱️ **Event & Timer Waiting**: Free up worker resources while waiting for events or timers
|
|
30
30
|
- 📬 **Channel-based Messaging**: Actor-model style communication with competing and broadcast modes
|
|
31
|
+
- 🧩 **Actor OS Primitives**: Names, monitors, capabilities and sealed channels, tasks, an actor filesystem and supervision trees, shared with Romancy (Go) and Edda (Python)
|
|
31
32
|
- 📡 **PostgreSQL LISTEN/NOTIFY**: Real-time event delivery without polling
|
|
32
33
|
- 🌍 **Rack Integration**: Works with Rails, Sinatra, Hanami, and any Rack-compatible framework
|
|
33
34
|
- 🔧 **Sidekiq/ActiveJob**: Background worker integration for Rails applications
|
|
@@ -134,6 +135,14 @@ gem install shikibu
|
|
|
134
135
|
|
|
135
136
|
**Important**: For multi-process or multi-pod deployments (K8s, Docker Compose with multiple replicas), use PostgreSQL or MySQL.
|
|
136
137
|
|
|
138
|
+
### Database Notes
|
|
139
|
+
|
|
140
|
+
- **MySQL** sessions run at `READ COMMITTED`, and the UTC session time zone and the isolation level are set on every connection.
|
|
141
|
+
- MySQL compares identifiers with the database collation. The default `utf8mb4_0900_ai_ci` ignores case and accents, so `Orders` and `orders` are the same channel. For exact matching, create the database with `utf8mb4_0900_bin`. Never change the collation of single columns.
|
|
142
|
+
- Migration `20261208000000_widen_actor_owner_columns` widens the MySQL instance-id columns of the actor tables to `VARCHAR(255)`.
|
|
143
|
+
- File-backed **SQLite** databases run in WAL mode. `-wal` and `-shm` files appear next to the database (add `*.db-wal` and `*.db-shm` to `.gitignore` if it lives in a repository). WAL does not work on network filesystems. An activity that hits a SQLite write conflict is restarted in a new transaction; this does not count as a retry.
|
|
144
|
+
- Timers and receive timeouts never fire before their deadline. SQLite and MySQL store whole seconds, so a deadline is rounded up.
|
|
145
|
+
|
|
137
146
|
### Database Drivers
|
|
138
147
|
|
|
139
148
|
```ruby
|
|
@@ -198,6 +207,45 @@ end
|
|
|
198
207
|
|
|
199
208
|
**Activity IDs**: Activities are automatically identified with IDs like `"create_user:1"` for deterministic replay.
|
|
200
209
|
|
|
210
|
+
### Typed Workflows (dry-struct)
|
|
211
|
+
|
|
212
|
+
Shikibu supports typed input/output with [dry-struct](https://dry-rb.org/gems/dry-struct/) for validation and type coercion:
|
|
213
|
+
|
|
214
|
+
```ruby
|
|
215
|
+
require 'dry-struct'
|
|
216
|
+
|
|
217
|
+
module Types
|
|
218
|
+
include Dry.Types()
|
|
219
|
+
end
|
|
220
|
+
|
|
221
|
+
class OrderInput < Dry::Struct
|
|
222
|
+
attribute :order_id, Types::String
|
|
223
|
+
attribute :amount, Types::Coercible::Decimal
|
|
224
|
+
end
|
|
225
|
+
|
|
226
|
+
class OrderResult < Dry::Struct
|
|
227
|
+
attribute :order_id, Types::String
|
|
228
|
+
attribute :status, Types::String
|
|
229
|
+
end
|
|
230
|
+
|
|
231
|
+
class TypedOrderSaga < Shikibu::Workflow
|
|
232
|
+
workflow_name 'typed_order'
|
|
233
|
+
input OrderInput
|
|
234
|
+
output OrderResult
|
|
235
|
+
|
|
236
|
+
def execute(order)
|
|
237
|
+
# order is an OrderInput instance with validated/coerced types
|
|
238
|
+
OrderResult.new(order_id: order.order_id, status: 'completed')
|
|
239
|
+
end
|
|
240
|
+
end
|
|
241
|
+
|
|
242
|
+
# Run with automatic type coercion
|
|
243
|
+
instance_id = app.start_workflow(TypedOrderSaga, order_id: 'ORD-123', amount: '99.99')
|
|
244
|
+
result = app.get_typed_result(instance_id, TypedOrderSaga) # Returns OrderResult
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
**Note**: `dry-struct` is an optional dependency. Add it to your Gemfile if you want typed workflows.
|
|
248
|
+
|
|
201
249
|
### Durable Execution
|
|
202
250
|
|
|
203
251
|
Shikibu ensures workflow progress is never lost through **deterministic replay**:
|
|
@@ -212,6 +260,8 @@ Shikibu ensures workflow progress is never lost through **deterministic replay**
|
|
|
212
260
|
- Workflows can survive **arbitrary crashes**
|
|
213
261
|
- No manual checkpoint management required
|
|
214
262
|
|
|
263
|
+
**Recurrence**: `recur(...)` archives the instance's history, clears its subscriptions, timers, group memberships and registered compensations, stores the new input and continues **on the same instance id**. Between iterations the status is `recurred`; the instance counts as alive (no DOWN message, its name stays registered). Names, monitors, issued capabilities, tasks, the actor filesystem and the sandbox flag survive. A broadcast channel that is subscribed to again continues after the last delivered message. There is no `continued_from` chain. A supervisor's id and its children's ids stay stable across recurs.
|
|
264
|
+
|
|
215
265
|
### Compensation (Saga Pattern)
|
|
216
266
|
|
|
217
267
|
When a workflow fails, Shikibu automatically executes compensation functions for **already-executed activities in reverse order**:
|
|
@@ -253,6 +303,8 @@ class OrderSaga < Shikibu::Workflow
|
|
|
253
303
|
end
|
|
254
304
|
```
|
|
255
305
|
|
|
306
|
+
**Cancelling**: `app.cancel_workflow(instance_id)` cancels `running`, `waiting_*` and `recurred` instances and returns `true`. An instance that is running its compensations (`compensating`) cannot be cancelled: the call returns `false` and the compensations run to the end.
|
|
307
|
+
|
|
256
308
|
### Event & Timer Waiting
|
|
257
309
|
|
|
258
310
|
Workflows can wait for external events or timers without consuming worker resources:
|
|
@@ -343,6 +395,74 @@ publish('jobs', { task: 'send_report', user_id: 123 })
|
|
|
343
395
|
send_to(target_instance_id, 'approval', { approved: true })
|
|
344
396
|
```
|
|
345
397
|
|
|
398
|
+
Called from workflow code, `publish` and `send_to` are recorded steps: a replay does not publish again. Once a `channel_pub` or `channel_sub` capability is issued for a channel, publishing or receiving on it (including its direct channels) requires the token, passed as `capability_token:`.
|
|
399
|
+
|
|
400
|
+
- An expired grant still keeps the channel sealed: the expired token is rejected, and the cleanup never removes the newest grant of a channel.
|
|
401
|
+
- Only the instance that issued a capability can revoke it, and only the holder of a name can unregister it (`Shikibu::NotOwnerError`). An unknown id or an unbound name is a no-op. `issue_capability(ctx, kind, target, expires_at: time)` issues an expiring capability.
|
|
402
|
+
- With a capability key (`Shikibu::App.new(capability_key: '...')` or the `DURAX_CAPABILITY_KEY` environment variable) the token is `HMAC-SHA256(key, capability_id)` and is never written to history. Without a key the token is in the history in plain text. Use the same key on every worker and do not change it while instances that issued capabilities are alive.
|
|
403
|
+
- CloudEvents posted to a sealed channel need the token in the `capabilitytoken` extension attribute (binary mode: `ce-capabilitytoken` header). Otherwise the response is HTTP 403 and nothing is published.
|
|
404
|
+
- `read_channel_since(ctx, channel, message_id)` raises `Shikibu::CursorNotFoundError` when the cursor message is not on that channel. `read_channel_after(ctx, channel, after_id)` reads after a numeric message `id` (`0` reads from the start) and keeps working after the cursor message is deleted. Returned messages carry `id` and `message_id`.
|
|
405
|
+
- Another instance's direct channel (`channel:{other_instance_id}`) is private: subscribing to, receiving from or reading it raises `Shikibu::ChannelPermissionError` whatever the seal state. Sending to it (`send_to`, a targeted CloudEvent) is allowed.
|
|
406
|
+
|
|
407
|
+
### Actor Primitives
|
|
408
|
+
|
|
409
|
+
Workflows double as actors of a kernel shared with Romancy and Edda (same schema, same semantics):
|
|
410
|
+
|
|
411
|
+
- **`Shikibu::Actors`**: `register_name`, `unregister_name`, `whereis`, `monitor`, `unmonitor`, `issue_capability`, `check_capability`, `revoke_capability`
|
|
412
|
+
- **`Shikibu::Tasks`**: `post_task`, `claim_task`, `complete_task`, `fail_task`, `list_tasks`, `wait_task`, `wait_any_task`, `read_channel_since`, `read_channel_after`
|
|
413
|
+
- **`Shikibu::FS`** (inside activities only): `read`, `write`, `list`, `delete`
|
|
414
|
+
- **`Shikibu::Blobs`**: `store_payload`, `load_payload`, `stat_payload`
|
|
415
|
+
- **`Shikibu::Supervisor`** (`require 'shikibu/supervisor'`): `define`, `ChildSpec`, strategies `ONE_FOR_ONE` / `ONE_FOR_ALL` / `REST_FOR_ONE`, restart modes `PERMANENT` / `TRANSIENT` / `TEMPORARY`
|
|
416
|
+
|
|
417
|
+
```ruby
|
|
418
|
+
require 'shikibu/supervisor'
|
|
419
|
+
|
|
420
|
+
class Watcher < Shikibu::Workflow
|
|
421
|
+
workflow_name 'watcher'
|
|
422
|
+
|
|
423
|
+
def execute
|
|
424
|
+
target = Shikibu::Actors.whereis(ctx, 'ingest')
|
|
425
|
+
return { status: 'not running' } unless target
|
|
426
|
+
|
|
427
|
+
# The DOWN message arrives on this instance's direct channel
|
|
428
|
+
subscribe('down', mode: :direct)
|
|
429
|
+
Shikibu::Actors.monitor(ctx, target, 'down')
|
|
430
|
+
down = receive('down', mode: :direct)
|
|
431
|
+
{ status: down[:status] } # 'completed', 'failed' or 'cancelled'
|
|
432
|
+
end
|
|
433
|
+
end
|
|
434
|
+
|
|
435
|
+
PipelineSup = Shikibu::Supervisor.define(
|
|
436
|
+
'pipeline-sup',
|
|
437
|
+
strategy: Shikibu::Supervisor::ONE_FOR_ONE,
|
|
438
|
+
max_restarts: 5,
|
|
439
|
+
within_seconds: 60,
|
|
440
|
+
children: [
|
|
441
|
+
Shikibu::Supervisor::ChildSpec.new(name: 'ingest', workflow: 'ingest',
|
|
442
|
+
restart: Shikibu::Supervisor::PERMANENT)
|
|
443
|
+
]
|
|
444
|
+
)
|
|
445
|
+
# PipelineSup.start(app)
|
|
446
|
+
```
|
|
447
|
+
|
|
448
|
+
Called from workflow code, every primitive is a recorded step: a replay returns the recorded outcome, errors included, instead of running it again. A primitive with a side effect first proves that the run still holds the instance lock, so a run that lost its lease applies nothing: the primitive raises `Shikibu::LockLostError`. Such a run is aborted: it is not failed, nothing is compensated, and a later run replays the instance. The same happens when the worker shuts down or a database error hits a kernel primitive; the instance stays `running`. A database error raises `Shikibu::RunAbortedError`, and so does every later primitive or activity of an aborted run. `RunAbortedError` derives from `Exception` (not `StandardError`), so `rescue => e` does not catch it. Do not rescue either error. Only kernel errors that carry a code (`task_conflict`, `task_not_found`, `actor_name_taken`, `fs_conflict`, `sandboxed`, `channel_forbidden`, `not_owner`, `cursor_not_found`, `invalid_argument`) are recorded as step results. Task handlers and supervised children are at-least-once and must be idempotent.
|
|
449
|
+
|
|
450
|
+
### Sandboxed Actors
|
|
451
|
+
|
|
452
|
+
Workflows can be started as sandboxed actors when they should receive only explicitly delegated capabilities:
|
|
453
|
+
|
|
454
|
+
```ruby
|
|
455
|
+
child_id = UntrustedWorkflow.start(app, sandboxed: true, input: value)
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
Sandboxing enforces three rules:
|
|
459
|
+
|
|
460
|
+
- A sandboxed workflow cannot mint new capabilities with `Shikibu::Actors.issue_capability`.
|
|
461
|
+
- Children started by a sandboxed workflow inherit the sandbox flag; a sandboxed instance keeps the flag across `recur` iterations (the instance id does not change).
|
|
462
|
+
- Only an unsandboxed parent (or an external caller) may use `sandboxed: true` for a child.
|
|
463
|
+
|
|
464
|
+
Delegation itself uses the existing capability tokens: pass tokens the child needs in its input. Shikibu itself enforces these rules. Code running in the worker process that uses the storage directly can bypass them, and Shikibu does not provide database-level isolation (for example PostgreSQL row-level security).
|
|
465
|
+
|
|
346
466
|
### PostgreSQL LISTEN/NOTIFY
|
|
347
467
|
|
|
348
468
|
When using PostgreSQL, Shikibu can use LISTEN/NOTIFY for real-time event delivery instead of polling:
|
|
@@ -432,6 +552,7 @@ app = Shikibu::App.new(
|
|
|
432
552
|
- Each workflow instance runs on only one worker at a time
|
|
433
553
|
- Automatic stale lock cleanup (5-minute timeout)
|
|
434
554
|
- Crashed workflows automatically resume on any available worker
|
|
555
|
+
- A worker claims only instances of the workflows it has registered, so register the same workflows on every worker that should be able to resume them
|
|
435
556
|
|
|
436
557
|
## Cross-Framework Compatibility
|
|
437
558
|
|
data/lib/shikibu/activity.rb
CHANGED
|
@@ -30,8 +30,8 @@ module Shikibu
|
|
|
30
30
|
# @param kwargs [Hash] Activity arguments
|
|
31
31
|
# @return [Object] Activity result
|
|
32
32
|
def call(ctx, **kwargs)
|
|
33
|
+
ctx.raise_if_run_aborted!
|
|
33
34
|
activity_id = ctx.generate_activity_id(@name)
|
|
34
|
-
ctx.current_activity_id = activity_id
|
|
35
35
|
|
|
36
36
|
# Check for cached result during replay
|
|
37
37
|
if ctx.replaying? && ctx.cached_result?(activity_id)
|
|
@@ -44,92 +44,128 @@ module Shikibu
|
|
|
44
44
|
|
|
45
45
|
# Execute with retry
|
|
46
46
|
execute_with_retry(ctx, activity_id, kwargs)
|
|
47
|
-
ensure
|
|
48
|
-
ctx.current_activity_id = nil
|
|
49
47
|
end
|
|
50
48
|
|
|
51
49
|
private
|
|
52
50
|
|
|
51
|
+
# The attempt loop of Workflow#activity, for a standalone activity: only
|
|
52
|
+
# an error from the body is the activity's outcome. One while beginning,
|
|
53
|
+
# recording or committing the attempt is a storage error and ends the run
|
|
54
|
+
# (a later run executes the activity again); a write conflict inside
|
|
55
|
+
# another activity's transaction is left to that outer attempt.
|
|
53
56
|
def execute_with_retry(ctx, activity_id, kwargs)
|
|
54
57
|
attempt = 0
|
|
55
58
|
started_at = Time.now
|
|
56
|
-
last_error = nil
|
|
57
59
|
|
|
58
60
|
loop do
|
|
59
61
|
attempt += 1
|
|
62
|
+
phase = :body # a hook error stays an activity failure
|
|
60
63
|
|
|
61
64
|
begin
|
|
62
|
-
# Call hooks
|
|
63
65
|
ctx.hooks&.on_activity_start&.call(ctx.instance_id, activity_id, @name, attempt)
|
|
64
66
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
# Record successful result
|
|
68
|
-
ctx.storage.append_history(
|
|
69
|
-
instance_id: ctx.instance_id,
|
|
70
|
-
activity_id: activity_id,
|
|
71
|
-
event_type: EventType::ACTIVITY_COMPLETED,
|
|
72
|
-
event_data: { result: result }
|
|
73
|
-
)
|
|
67
|
+
phase = :begin
|
|
68
|
+
result = run_and_record(ctx, activity_id, kwargs) { |reached| phase = reached }
|
|
74
69
|
|
|
75
70
|
# Cache for replay
|
|
76
71
|
ctx.cache_result(activity_id, {
|
|
77
72
|
event_type: EventType::ACTIVITY_COMPLETED,
|
|
78
73
|
result: result
|
|
79
74
|
})
|
|
80
|
-
|
|
81
|
-
# Call hooks
|
|
82
75
|
ctx.hooks&.on_activity_complete&.call(ctx.instance_id, activity_id, @name, result, false)
|
|
83
76
|
|
|
84
77
|
return result
|
|
78
|
+
rescue LockLostError => e
|
|
79
|
+
# Lease lost: abort without retrying or further writes
|
|
80
|
+
ctx.poison_run!(e)
|
|
81
|
+
raise
|
|
82
|
+
rescue WorkflowCancelledError
|
|
83
|
+
# Cancellation ends the run; it is never an activity failure.
|
|
84
|
+
raise
|
|
85
85
|
rescue StandardError => e
|
|
86
|
-
|
|
86
|
+
raise if ctx.storage.nested_write_conflict?(e)
|
|
87
87
|
|
|
88
|
-
|
|
89
|
-
unless @retry_policy.retryable?(e) && @retry_policy.should_retry?(attempt, started_at)
|
|
90
|
-
# Record failure
|
|
91
|
-
ctx.storage.append_history(
|
|
92
|
-
instance_id: ctx.instance_id,
|
|
93
|
-
activity_id: activity_id,
|
|
94
|
-
event_type: EventType::ACTIVITY_FAILED,
|
|
95
|
-
event_data: {
|
|
96
|
-
error_type: e.class.name,
|
|
97
|
-
error_message: e.message,
|
|
98
|
-
attempts: attempt
|
|
99
|
-
}
|
|
100
|
-
)
|
|
101
|
-
|
|
102
|
-
# Cache for replay
|
|
103
|
-
ctx.cache_result(activity_id, {
|
|
104
|
-
event_type: EventType::ACTIVITY_FAILED,
|
|
105
|
-
error_type: e.class.name,
|
|
106
|
-
error_message: e.message
|
|
107
|
-
})
|
|
108
|
-
|
|
109
|
-
# Call hooks
|
|
110
|
-
ctx.hooks&.on_activity_failed&.call(ctx.instance_id, activity_id, @name, e, attempt)
|
|
88
|
+
ctx.abort_run!(e) unless phase == :body
|
|
111
89
|
|
|
90
|
+
unless @retry_policy.retryable?(e) && @retry_policy.should_retry?(attempt, started_at)
|
|
91
|
+
record_failure(ctx, activity_id, e, attempt)
|
|
112
92
|
raise
|
|
113
93
|
end
|
|
114
94
|
|
|
115
|
-
# Call retry hook
|
|
116
95
|
delay = @retry_policy.delay_for(attempt)
|
|
117
96
|
ctx.hooks&.on_activity_retry&.call(ctx.instance_id, activity_id, @name, e, attempt, delay)
|
|
118
|
-
|
|
119
|
-
# Wait before retry
|
|
120
97
|
Kernel.sleep(delay)
|
|
121
98
|
end
|
|
122
99
|
end
|
|
123
100
|
end
|
|
124
101
|
|
|
102
|
+
# Record the failure the activity gave up with. Failing to record it is
|
|
103
|
+
# a storage error, not an outcome: the run ends (lock loss included).
|
|
104
|
+
def record_failure(ctx, activity_id, error, attempt)
|
|
105
|
+
begin
|
|
106
|
+
ctx.storage.append_history(
|
|
107
|
+
lock_id: ctx.lock_id,
|
|
108
|
+
instance_id: ctx.instance_id,
|
|
109
|
+
activity_id: activity_id,
|
|
110
|
+
event_type: EventType::ACTIVITY_FAILED,
|
|
111
|
+
event_data: { error_type: error.class.name, error_message: error.message, attempts: attempt }
|
|
112
|
+
)
|
|
113
|
+
rescue LockLostError => e
|
|
114
|
+
ctx.poison_run!(e)
|
|
115
|
+
raise
|
|
116
|
+
rescue StandardError => e
|
|
117
|
+
ctx.abort_run!(e)
|
|
118
|
+
end
|
|
119
|
+
ctx.cache_result(activity_id, {
|
|
120
|
+
event_type: EventType::ACTIVITY_FAILED,
|
|
121
|
+
error_type: error.class.name,
|
|
122
|
+
error_message: error.message
|
|
123
|
+
})
|
|
124
|
+
ctx.hooks&.on_activity_failed&.call(ctx.instance_id, activity_id, @name, error, attempt)
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
# Execute and record the result atomically, fenced by the lock epoch
|
|
128
|
+
# (as Workflow#activity does); yields each phase it reaches.
|
|
129
|
+
def run_and_record(ctx, activity_id, kwargs)
|
|
130
|
+
ctx.storage.attempt_transaction do
|
|
131
|
+
yield :body
|
|
132
|
+
res = run_body(ctx, activity_id, kwargs)
|
|
133
|
+
yield :record
|
|
134
|
+
ctx.storage.append_history(
|
|
135
|
+
lock_id: ctx.lock_id,
|
|
136
|
+
instance_id: ctx.instance_id,
|
|
137
|
+
activity_id: activity_id,
|
|
138
|
+
event_type: EventType::ACTIVITY_COMPLETED,
|
|
139
|
+
event_data: { result: res }
|
|
140
|
+
)
|
|
141
|
+
res
|
|
142
|
+
end
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
# Run the activity body with current_activity_id marking it
|
|
146
|
+
def run_body(ctx, activity_id, kwargs)
|
|
147
|
+
previous = ctx.current_activity_id
|
|
148
|
+
ctx.current_activity_id = activity_id
|
|
149
|
+
@block.call(ctx, **kwargs)
|
|
150
|
+
ensure
|
|
151
|
+
ctx.current_activity_id = previous
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
# Rebuild a recorded failure as its error class (as Workflow does); a name
|
|
155
|
+
# that is not a StandardError class, or one that cannot take just a
|
|
156
|
+
# message, replays as a StandardError with the recorded message.
|
|
125
157
|
def reconstruct_error(cached)
|
|
126
158
|
error_class = begin
|
|
127
|
-
Object.const_get(cached[:error_type])
|
|
128
|
-
rescue
|
|
129
|
-
|
|
159
|
+
Object.const_get(cached[:error_type].to_s)
|
|
160
|
+
rescue NameError
|
|
161
|
+
nil
|
|
162
|
+
end
|
|
163
|
+
error_class = StandardError unless error_class.is_a?(Class) && error_class <= StandardError
|
|
164
|
+
begin
|
|
165
|
+
error_class.new(cached[:error_message])
|
|
166
|
+
rescue ArgumentError
|
|
167
|
+
StandardError.new(cached[:error_message])
|
|
130
168
|
end
|
|
131
|
-
|
|
132
|
-
error_class.new(cached[:error_message])
|
|
133
169
|
end
|
|
134
170
|
end
|
|
135
171
|
end
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'digest'
|
|
4
|
+
require 'openssl'
|
|
5
|
+
require 'securerandom'
|
|
6
|
+
|
|
7
|
+
module Shikibu
|
|
8
|
+
# Actor-style API: name registry (Erlang register/whereis) and monitors
|
|
9
|
+
# (Erlang monitor/'DOWN' messages) layered on the durable kernel.
|
|
10
|
+
#
|
|
11
|
+
# A DOWN notification is delivered as a channel message
|
|
12
|
+
# {"type":"DOWN","actor":"<instance_id>","status":"<terminal_status>"} on
|
|
13
|
+
# the watcher's direct channel "{channel}:{watcher_instance_id}" — the
|
|
14
|
+
# same channel send_to() uses, so receive it via receive() with a
|
|
15
|
+
# ModeDirect subscription on that channel. Emission runs in the leader's
|
|
16
|
+
# periodic sweep, so it arrives at most one sweep interval after
|
|
17
|
+
# termination.
|
|
18
|
+
#
|
|
19
|
+
# Every call is a deterministic step (SEMANTICS §2): from workflow code
|
|
20
|
+
# its outcome is recorded once and replayed; inside an activity body it
|
|
21
|
+
# runs directly.
|
|
22
|
+
module Actors
|
|
23
|
+
module_function
|
|
24
|
+
|
|
25
|
+
# Bind a unique actor name to this workflow instance.
|
|
26
|
+
# Raises on name conflict.
|
|
27
|
+
def register_name(ctx, name)
|
|
28
|
+
Shikibu.deterministic_step(ctx, 'register_name') do
|
|
29
|
+
ctx.storage.register_actor_name(name, ctx.instance_id)
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# Remove an actor name binding (idempotent). Only the holder may
|
|
34
|
+
# unbind it: another instance gets NotOwnerError.
|
|
35
|
+
def unregister_name(ctx, name)
|
|
36
|
+
Shikibu.deterministic_step(ctx, 'unregister_name') do
|
|
37
|
+
ctx.storage.unregister_own_actor_name(name, ctx.instance_id)
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
# Resolve an actor name to an instance ID (nil if unbound).
|
|
42
|
+
def whereis(ctx, name)
|
|
43
|
+
Shikibu.deterministic_step(ctx, 'whereis') { ctx.storage.whereis_actor(name) }
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# Monitor target_instance_id; on its termination a DOWN message is
|
|
47
|
+
# published to "{channel}:{ctx.instance_id}".
|
|
48
|
+
def monitor(ctx, target_instance_id, channel)
|
|
49
|
+
Shikibu.deterministic_step(ctx, 'monitor') do
|
|
50
|
+
ctx.storage.monitor_actor(
|
|
51
|
+
ctx.instance_id, target_instance_id, "#{channel}:#{ctx.instance_id}"
|
|
52
|
+
)
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# Remove a monitor registration (idempotent).
|
|
57
|
+
def unmonitor(ctx, target_instance_id)
|
|
58
|
+
Shikibu.deterministic_step(ctx, 'unmonitor') do
|
|
59
|
+
ctx.storage.unmonitor_actor(ctx.instance_id, target_instance_id)
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
CAPABILITY_KINDS = %w[actor channel_pub channel_sub fs_write].freeze
|
|
64
|
+
|
|
65
|
+
# Mint a capability for (kind, target). Returns
|
|
66
|
+
# [token, capability_id] — the bearer token "cap:{kind}:{target}:{secret}"
|
|
67
|
+
# and the grant ID needed by revoke_capability. Only the hash of the
|
|
68
|
+
# secret is stored in the grant.
|
|
69
|
+
#
|
|
70
|
+
# Without a capability key the secret is random and the token is part of
|
|
71
|
+
# the recorded step, so it sits in plaintext in workflow history. With
|
|
72
|
+
# one (App capability_key: / DURAX_CAPABILITY_KEY) the secret is
|
|
73
|
+
# HMAC-SHA256(key, capability_id): the step records only
|
|
74
|
+
# {id, kind, target, derived: true} and a replay derives the token
|
|
75
|
+
# again. Keep the key unchanged while instances that issued capabilities
|
|
76
|
+
# are alive.
|
|
77
|
+
# expires_at is a UTC instant: a Time is converted to UTC, a String is
|
|
78
|
+
# taken as a UTC wall-clock "YYYY-MM-DD HH:MM:SS".
|
|
79
|
+
def issue_capability(ctx, kind, target, expires_at: nil)
|
|
80
|
+
expires_at = expires_at.getutc if expires_at.respond_to?(:getutc)
|
|
81
|
+
key = ctx.capability_key if ctx.respond_to?(:capability_key)
|
|
82
|
+
recorded = Shikibu.deterministic_step(ctx, 'issue_capability') do
|
|
83
|
+
raise InvalidArgumentError, "unknown capability kind: #{kind}" unless CAPABILITY_KINDS.include?(kind)
|
|
84
|
+
|
|
85
|
+
instance = ctx.storage.get_instance(ctx.instance_id)
|
|
86
|
+
raise InvalidArgumentError, "workflow instance #{ctx.instance_id} not found" unless instance
|
|
87
|
+
raise SandboxedError, "sandboxed workflow #{ctx.instance_id} cannot issue capabilities" if instance[:sandboxed]
|
|
88
|
+
|
|
89
|
+
cap_id = "cap-#{SecureRandom.uuid}"
|
|
90
|
+
secret = key ? derive_secret(key, cap_id) : SecureRandom.hex(24)
|
|
91
|
+
ctx.storage.grant_capability(
|
|
92
|
+
capability_id: cap_id, kind: kind, target: target,
|
|
93
|
+
secret_hash: Digest::SHA256.hexdigest(secret),
|
|
94
|
+
granted_by: ctx.instance_id, expires_at: expires_at
|
|
95
|
+
)
|
|
96
|
+
next ["cap:#{kind}:#{target}:#{secret}", cap_id] unless key
|
|
97
|
+
|
|
98
|
+
{ id: cap_id, kind: kind, target: target, derived: true }
|
|
99
|
+
end
|
|
100
|
+
return recorded unless recorded.is_a?(Hash)
|
|
101
|
+
|
|
102
|
+
raise InvalidArgumentError, 'a capability key is needed to replay a derived capability' unless key
|
|
103
|
+
|
|
104
|
+
secret = derive_secret(key, recorded[:id])
|
|
105
|
+
["cap:#{recorded[:kind]}:#{recorded[:target]}:#{secret}", recorded[:id]]
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
def derive_secret(key, capability_id)
|
|
109
|
+
OpenSSL::HMAC.hexdigest('SHA256', key, capability_id)
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
# Verify a capability token for (kind, target). Accepts either the raw
|
|
113
|
+
# secret or the full "cap:kind:target:secret" token form.
|
|
114
|
+
def check_capability(ctx, kind, target, token)
|
|
115
|
+
token = token.split(':').last if token.start_with?('cap:')
|
|
116
|
+
Shikibu.deterministic_step(ctx, 'check_capability') do
|
|
117
|
+
ctx.storage.check_capability(kind, target, Digest::SHA256.hexdigest(token))
|
|
118
|
+
end
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
# Remove a capability grant by ID (idempotent). Only the instance that
|
|
122
|
+
# issued it may revoke it: another instance gets NotOwnerError.
|
|
123
|
+
def revoke_capability(ctx, capability_id)
|
|
124
|
+
Shikibu.deterministic_step(ctx, 'revoke_capability') do
|
|
125
|
+
ctx.storage.revoke_own_capability(capability_id, ctx.instance_id)
|
|
126
|
+
end
|
|
127
|
+
end
|
|
128
|
+
end
|
|
129
|
+
end
|
data/lib/shikibu/app.rb
CHANGED
|
@@ -23,7 +23,8 @@ module Shikibu
|
|
|
23
23
|
#
|
|
24
24
|
class App
|
|
25
25
|
attr_reader :storage, :worker_id, :service_name, :hooks, :message_retention_days,
|
|
26
|
-
:outbox_enabled, :broker_url, :outbox_poll_interval, :outbox_max_retries, :outbox_max_age_hours
|
|
26
|
+
:outbox_enabled, :broker_url, :outbox_poll_interval, :outbox_max_retries, :outbox_max_age_hours,
|
|
27
|
+
:capability_key
|
|
27
28
|
|
|
28
29
|
# Create a new Shikibu application
|
|
29
30
|
# @param database_url [String] Database connection URL
|
|
@@ -37,10 +38,13 @@ module Shikibu
|
|
|
37
38
|
# @param outbox_poll_interval [Float] Outbox polling interval in seconds (default: 1.0)
|
|
38
39
|
# @param outbox_max_retries [Integer] Max retries for outbox events (default: 3)
|
|
39
40
|
# @param outbox_max_age_hours [Float, nil] Max age for outbox events in hours (default: nil)
|
|
41
|
+
# @param capability_key [String, nil] Key deriving capability secrets (HMAC-SHA256), so issued
|
|
42
|
+
# tokens stay out of workflow history. Falls back to a non-empty ENV['DURAX_CAPABILITY_KEY'].
|
|
43
|
+
# Keep it the same on every worker while instances that issued capabilities are alive.
|
|
40
44
|
def initialize(database_url:, service_name: 'shikibu', auto_migrate: false, hooks: nil,
|
|
41
45
|
use_listen_notify: nil, message_retention_days: 7,
|
|
42
46
|
outbox_enabled: false, broker_url: nil, outbox_poll_interval: 1.0,
|
|
43
|
-
outbox_max_retries: 3, outbox_max_age_hours: nil)
|
|
47
|
+
outbox_max_retries: 3, outbox_max_age_hours: nil, capability_key: nil)
|
|
44
48
|
@database_url = database_url
|
|
45
49
|
@service_name = service_name
|
|
46
50
|
@auto_migrate = auto_migrate
|
|
@@ -52,6 +56,7 @@ module Shikibu
|
|
|
52
56
|
@outbox_poll_interval = outbox_poll_interval
|
|
53
57
|
@outbox_max_retries = outbox_max_retries
|
|
54
58
|
@outbox_max_age_hours = outbox_max_age_hours
|
|
59
|
+
@capability_key = [capability_key, ENV.fetch('DURAX_CAPABILITY_KEY', nil)].find { |key| !key.to_s.empty? }
|
|
55
60
|
@worker_id = Locking.generate_worker_id(service_name)
|
|
56
61
|
@registered_workflows = {}
|
|
57
62
|
@running = false
|
|
@@ -71,7 +76,8 @@ module Shikibu
|
|
|
71
76
|
@replay_engine = ReplayEngine.new(
|
|
72
77
|
storage: @storage,
|
|
73
78
|
worker_id: @worker_id,
|
|
74
|
-
hooks: @hooks
|
|
79
|
+
hooks: @hooks,
|
|
80
|
+
capability_key: @capability_key
|
|
75
81
|
)
|
|
76
82
|
end
|
|
77
83
|
|
|
@@ -128,10 +134,24 @@ module Shikibu
|
|
|
128
134
|
# @param instance_id [String, nil] Optional custom instance ID
|
|
129
135
|
# @param input [Hash] Input parameters
|
|
130
136
|
# @return [String] Instance ID
|
|
131
|
-
def start_workflow(workflow_class, instance_id: nil, **input)
|
|
137
|
+
def start_workflow(workflow_class, instance_id: nil, sandboxed: false, **input)
|
|
132
138
|
instance_id ||= SecureRandom.uuid
|
|
139
|
+
parent_ctx = Thread.current[:shikibu_workflow_context]
|
|
140
|
+
parent_instance_id = parent_ctx&.instance_id
|
|
141
|
+
if sandboxed && parent_instance_id
|
|
142
|
+
parent = @storage.get_instance(parent_instance_id)
|
|
143
|
+
if parent && parent[:sandboxed]
|
|
144
|
+
raise SandboxedError, 'sandboxed workflows cannot use the sandboxed spawn option'
|
|
145
|
+
end
|
|
146
|
+
end
|
|
133
147
|
|
|
134
|
-
@replay_engine.start_workflow(
|
|
148
|
+
@replay_engine.start_workflow(
|
|
149
|
+
workflow_class,
|
|
150
|
+
instance_id: instance_id,
|
|
151
|
+
sandboxed: sandboxed,
|
|
152
|
+
parent_instance_id: parent_instance_id,
|
|
153
|
+
**input
|
|
154
|
+
)
|
|
135
155
|
|
|
136
156
|
instance_id
|
|
137
157
|
rescue WaitForTimerSignal, WaitForChannelSignal
|
|
@@ -141,8 +161,9 @@ module Shikibu
|
|
|
141
161
|
|
|
142
162
|
# Resume a workflow
|
|
143
163
|
# @param instance_id [String] Instance ID
|
|
144
|
-
|
|
145
|
-
|
|
164
|
+
# @param lock_id [String, nil] Lock identity already held via a batch claim
|
|
165
|
+
def resume_workflow(instance_id, lock_id: nil)
|
|
166
|
+
@replay_engine.resume_workflow(instance_id, lock_id: lock_id)
|
|
146
167
|
rescue WaitForTimerSignal, WaitForChannelSignal
|
|
147
168
|
# Workflow still suspended
|
|
148
169
|
nil
|
|
@@ -162,6 +183,18 @@ module Shikibu
|
|
|
162
183
|
}
|
|
163
184
|
end
|
|
164
185
|
|
|
186
|
+
# Get workflow result with typed output deserialization
|
|
187
|
+
# @param instance_id [String] Instance ID
|
|
188
|
+
# @param workflow_class [Class] Workflow class with output type definition
|
|
189
|
+
# @return [Object, nil] Typed output or nil if no output
|
|
190
|
+
# @raise [WorkflowNotFoundError] If instance not found
|
|
191
|
+
def get_typed_result(instance_id, workflow_class)
|
|
192
|
+
result = get_result(instance_id)
|
|
193
|
+
return nil unless result[:output]
|
|
194
|
+
|
|
195
|
+
workflow_class.deserialize_output(result[:output])
|
|
196
|
+
end
|
|
197
|
+
|
|
165
198
|
# Get workflow status
|
|
166
199
|
# @param instance_id [String] Instance ID
|
|
167
200
|
# @return [String] Status
|
|
@@ -179,12 +212,9 @@ module Shikibu
|
|
|
179
212
|
instance = @storage.get_instance(instance_id)
|
|
180
213
|
raise WorkflowNotFoundError, instance_id unless instance
|
|
181
214
|
|
|
182
|
-
#
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
@storage.update_instance_status(instance_id, Status::CANCELLED)
|
|
187
|
-
true
|
|
215
|
+
# Atomically cancels only a non-terminal instance and drops its timers
|
|
216
|
+
# and subscriptions so nothing can resume it afterwards.
|
|
217
|
+
@storage.cancel_instance(instance_id)
|
|
188
218
|
end
|
|
189
219
|
|
|
190
220
|
# List workflow instances
|
|
@@ -220,20 +250,16 @@ module Shikibu
|
|
|
220
250
|
metadata: full_metadata
|
|
221
251
|
)
|
|
222
252
|
|
|
223
|
-
# Deliver to subscribers
|
|
253
|
+
# Deliver to subscribers. Broadcast: the CHANNEL_MESSAGE NOTIFY sent by
|
|
254
|
+
# publish_message wakes the worker's delivery loop.
|
|
224
255
|
if target_instance_id
|
|
225
256
|
# Point-to-Point: deliver only to specific instance
|
|
226
257
|
@storage.deliver_channel_message(
|
|
227
258
|
instance_id: target_instance_id,
|
|
228
259
|
channel: event_type,
|
|
229
260
|
message_id: message_id,
|
|
230
|
-
data: data,
|
|
231
|
-
metadata: full_metadata,
|
|
232
261
|
worker_id: @worker_id
|
|
233
262
|
)
|
|
234
|
-
else
|
|
235
|
-
# Broadcast: wake all waiting subscribers (Worker will handle delivery)
|
|
236
|
-
@notify_listener&.notify(Notify::Channel::CHANNEL_MESSAGE, { channel: event_type })
|
|
237
263
|
end
|
|
238
264
|
|
|
239
265
|
# Call hook
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'digest'
|
|
4
|
+
|
|
5
|
+
module Shikibu
|
|
6
|
+
# Content-addressed blob store with payload references.
|
|
7
|
+
#
|
|
8
|
+
# Large payloads are stored once by content hash and referenced as
|
|
9
|
+
# "blob:sha256:<hex>" inside channel messages, event data, etc. Writes
|
|
10
|
+
# are idempotent — identical payloads share a single blob.
|
|
11
|
+
#
|
|
12
|
+
# NOTE: blobs are readable by anyone who knows the content hash — the
|
|
13
|
+
# store is content-addressed, not permissioned. Do not store secrets in
|
|
14
|
+
# plaintext; encrypt sensitive payloads before store_payload.
|
|
15
|
+
module Blobs
|
|
16
|
+
BLOB_REF_PREFIX = 'blob:sha256:'
|
|
17
|
+
|
|
18
|
+
module_function
|
|
19
|
+
|
|
20
|
+
# Store data and return its "blob:sha256:<hash>" reference.
|
|
21
|
+
def store_payload(ctx, data)
|
|
22
|
+
hash = Digest::SHA256.hexdigest(data)
|
|
23
|
+
ctx.storage.put_blob(hash, data, created_by: ctx.instance_id)
|
|
24
|
+
"#{BLOB_REF_PREFIX}#{hash}"
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
# Return blob metadata ({size_bytes:, created_by:, created_at:}) or nil.
|
|
28
|
+
def stat_payload(ctx, ref)
|
|
29
|
+
ctx.storage.get_blob_info(ref.delete_prefix(BLOB_REF_PREFIX))
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# Resolve a blob reference (or bare hash) to its data.
|
|
33
|
+
# Raises KeyError if absent.
|
|
34
|
+
def load_payload(ctx, ref)
|
|
35
|
+
hash = ref.delete_prefix(BLOB_REF_PREFIX)
|
|
36
|
+
data = ctx.storage.get_blob(hash)
|
|
37
|
+
raise KeyError, "blob not found: #{ref}" if data.nil?
|
|
38
|
+
|
|
39
|
+
data
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
end
|