ferroq 0.1.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 +7 -0
- data/Cargo.toml +32 -0
- data/README.md +20 -0
- data/bin/ferroq +34 -0
- data/crates/ferroq/Cargo.toml +12 -0
- data/crates/ferroq/src/lib.rs +6 -0
- data/crates/ferroq-core/Cargo.toml +20 -0
- data/crates/ferroq-core/src/conformance.rs +186 -0
- data/crates/ferroq-core/src/crypto.rs +118 -0
- data/crates/ferroq-core/src/engine.rs +175 -0
- data/crates/ferroq-core/src/error.rs +21 -0
- data/crates/ferroq-core/src/job.rs +168 -0
- data/crates/ferroq-core/src/lib.rs +12 -0
- data/crates/ferroq-core/src/storage.rs +65 -0
- data/crates/ferroq-node/Cargo.toml +19 -0
- data/crates/ferroq-node/build.rs +3 -0
- data/crates/ferroq-node/src/lib.rs +215 -0
- data/crates/ferroq-storage-sqlite/Cargo.toml +14 -0
- data/crates/ferroq-storage-sqlite/src/lib.rs +508 -0
- data/ext/ferroq/Cargo.toml +17 -0
- data/ext/ferroq/extconf.rb +6 -0
- data/ext/ferroq/src/lib.rs +308 -0
- data/lib/active_job/queue_adapters/ferroq_adapter.rb +53 -0
- data/lib/ferroq/configuration.rb +32 -0
- data/lib/ferroq/job.rb +83 -0
- data/lib/ferroq/version.rb +5 -0
- data/lib/ferroq/worker.rb +127 -0
- data/lib/ferroq.rb +51 -0
- metadata +81 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: ee40361ab29cea5bc0ffa785630b915a0017af11d1a31ccd3e3bfc803a59f2c6
|
|
4
|
+
data.tar.gz: a4353a2c34abee2285dadbe5da092f0276508dcecf1baceb61640c5289faa828
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 8e3c87d6025b732091a70dce706fee5b15cf2256b80ac333a6fcf2c43056b0a947909c3f0524915eb1629a45e295e1f02b1ca55d19d1545c0267d7497e809ae8
|
|
7
|
+
data.tar.gz: f349217306cadfe033ed97dfb2f02bf8c147a069ff7b80a5115170a2b26ce01ab1b83b974b7b4113822449aaa6daee3817a4f080d380678644772d1872a917b4
|
data/Cargo.toml
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[workspace]
|
|
2
|
+
resolver = "2"
|
|
3
|
+
members = [
|
|
4
|
+
"crates/ferroq",
|
|
5
|
+
"crates/ferroq-core",
|
|
6
|
+
"crates/ferroq-storage-sqlite",
|
|
7
|
+
"crates/ferroq-node",
|
|
8
|
+
"ext/ferroq",
|
|
9
|
+
]
|
|
10
|
+
|
|
11
|
+
[workspace.package]
|
|
12
|
+
version = "0.1.0"
|
|
13
|
+
edition = "2021"
|
|
14
|
+
license = "MIT"
|
|
15
|
+
authors = ["Ferroq Contributors"]
|
|
16
|
+
|
|
17
|
+
[workspace.dependencies]
|
|
18
|
+
aes-gcm = "0.10"
|
|
19
|
+
base64 = "0.22"
|
|
20
|
+
blake3 = "1.5"
|
|
21
|
+
parking_lot = "0.12"
|
|
22
|
+
rand = "0.8"
|
|
23
|
+
rusqlite = { version = "0.32", features = ["bundled"] }
|
|
24
|
+
serde = { version = "1", features = ["derive"] }
|
|
25
|
+
serde_json = "1"
|
|
26
|
+
thiserror = "2"
|
|
27
|
+
uuid = { version = "1", features = ["v7", "serde"] }
|
|
28
|
+
|
|
29
|
+
[profile.release]
|
|
30
|
+
opt-level = 3
|
|
31
|
+
lto = "thin"
|
|
32
|
+
codegen-units = 1
|
data/README.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# Ferroq
|
|
2
|
+
|
|
3
|
+
Next-generation Rust-powered background job and workflow engine for Ruby.
|
|
4
|
+
|
|
5
|
+
## Key Features (Phase 1)
|
|
6
|
+
- **GVL-free Rust Core (`ferroq-core`)**: Storage I/O, AES-256-GCM encryption, lease management, and retry scheduling execute in Rust without holding the Ruby GVL.
|
|
7
|
+
- **Pluggable Storage Architecture**: Unified `StorageBackend` trait + shared Conformance Test Suite.
|
|
8
|
+
- Phase 1: Embedded SQLite WAL (`ferroq-storage-sqlite`) — zero external dependencies.
|
|
9
|
+
- Upcoming: Redis / Valkey (`ferroq-storage-redis`), PostgreSQL (`ferroq-storage-postgres`).
|
|
10
|
+
- **Reliable Delivery**: Lease-based fetch/ACK/NACK, automatic stalled job recovery, exponential backoff retries, and Dead-Letter Queue (DLQ).
|
|
11
|
+
- **Transparent Encryption**: AES-256-GCM payload encryption at rest.
|
|
12
|
+
|
|
13
|
+
## Development
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
cargo test -p ferroq-core -p ferroq-storage-sqlite
|
|
17
|
+
bundle exec rake compile
|
|
18
|
+
bundle exec rspec
|
|
19
|
+
ruby benchmarks/bench_ferroq.rb
|
|
20
|
+
```
|
data/bin/ferroq
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
#!/usr/bin/env ruby
|
|
2
|
+
# frozen_string_literal: true
|
|
3
|
+
|
|
4
|
+
require "optparse"
|
|
5
|
+
require "ferroq"
|
|
6
|
+
|
|
7
|
+
options = {
|
|
8
|
+
concurrency: Ferroq.configuration.concurrency,
|
|
9
|
+
queues: Ferroq.configuration.queues,
|
|
10
|
+
database_path: Ferroq.configuration.database_path
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
OptionParser.new do |opts|
|
|
14
|
+
opts.banner = "Usage: ferroq [options]"
|
|
15
|
+
opts.on("-c", "--concurrency N", Integer, "Number of Ruby worker threads") { |v| options[:concurrency] = v }
|
|
16
|
+
opts.on("-q", "--queue NAME", "Queue to process (repeatable)") { |v| (options[:custom_queues] ||= []) << v }
|
|
17
|
+
opts.on("-d", "--database PATH", "Embedded SQLite WAL database path") { |v| options[:database_path] = v }
|
|
18
|
+
opts.on("-r", "--require PATH", "Ruby file to load job classes") { |v| require File.expand_path(v) }
|
|
19
|
+
end.parse!
|
|
20
|
+
|
|
21
|
+
Ferroq.configure do |config|
|
|
22
|
+
config.database_path = options[:database_path]
|
|
23
|
+
config.concurrency = options[:concurrency]
|
|
24
|
+
config.queues = options[:custom_queues] if options[:custom_queues]
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
worker = Ferroq::Worker.new
|
|
28
|
+
trap("INT") { worker.stop }
|
|
29
|
+
trap("TERM") { worker.stop }
|
|
30
|
+
|
|
31
|
+
puts "Ferroq #{Ferroq::VERSION} starting (storage=#{Ferroq.configuration.storage}, concurrency=#{Ferroq.configuration.concurrency}, queues=#{Ferroq.configuration.queues.join(',')})"
|
|
32
|
+
worker.start
|
|
33
|
+
sleep 0.2 while worker.instance_variable_get(:@running)
|
|
34
|
+
puts "Ferroq stopped cleanly (processed=#{worker.processed_count}, failed=#{worker.failed_count})"
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
[package]
|
|
2
|
+
name = "ferroq"
|
|
3
|
+
version = "0.0.1"
|
|
4
|
+
edition.workspace = true
|
|
5
|
+
license.workspace = true
|
|
6
|
+
description = "Next-generation Rust-powered background job and workflow engine with pluggable storage backends"
|
|
7
|
+
keywords = ["queue", "jobs", "worker", "background-jobs", "bullmq"]
|
|
8
|
+
categories = ["asynchronous", "concurrency"]
|
|
9
|
+
readme = "../../README.md"
|
|
10
|
+
|
|
11
|
+
[dependencies]
|
|
12
|
+
ferroq-core = { version = "0.0.1", path = "../ferroq-core" }
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
[package]
|
|
2
|
+
name = "ferroq-core"
|
|
3
|
+
version = "0.0.1"
|
|
4
|
+
edition.workspace = true
|
|
5
|
+
license.workspace = true
|
|
6
|
+
description = "Core Rust engine, storage trait, and AES-256-GCM encryption for Ferroq background job queue"
|
|
7
|
+
keywords = ["queue", "jobs", "worker", "background-jobs", "sidekiq"]
|
|
8
|
+
categories = ["asynchronous", "concurrency"]
|
|
9
|
+
readme = "../../README.md"
|
|
10
|
+
|
|
11
|
+
[dependencies]
|
|
12
|
+
aes-gcm.workspace = true
|
|
13
|
+
base64.workspace = true
|
|
14
|
+
blake3.workspace = true
|
|
15
|
+
parking_lot.workspace = true
|
|
16
|
+
rand.workspace = true
|
|
17
|
+
serde.workspace = true
|
|
18
|
+
serde_json.workspace = true
|
|
19
|
+
thiserror.workspace = true
|
|
20
|
+
uuid.workspace = true
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
use crate::job::{EnqueueRequest, JobStatus};
|
|
2
|
+
use crate::storage::StorageBackend;
|
|
3
|
+
|
|
4
|
+
/// Shared behavioral contract suite that EVERY Ferroq storage backend
|
|
5
|
+
/// (SQLite WAL, Redis/Valkey, PostgreSQL) must pass identically.
|
|
6
|
+
pub fn run_storage_conformance_suite<S: StorageBackend>(storage: &S) {
|
|
7
|
+
test_enqueue_fetch_ack(storage);
|
|
8
|
+
test_priority_and_delayed_ordering(storage);
|
|
9
|
+
test_retry_and_dead_letter_queue(storage);
|
|
10
|
+
test_stalled_lease_recovery(storage);
|
|
11
|
+
test_progress_and_result(storage);
|
|
12
|
+
test_batch_enqueue_and_ack(storage);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
fn test_enqueue_fetch_ack<S: StorageBackend>(storage: &S) {
|
|
16
|
+
storage.clear().unwrap();
|
|
17
|
+
let now = 1_000_000_i64;
|
|
18
|
+
let job = EnqueueRequest::new("default", "EmailJob", r#"["a@b.com"]"#).into_job(now);
|
|
19
|
+
let id = storage.enqueue(job).unwrap();
|
|
20
|
+
|
|
21
|
+
let stats = storage.stats().unwrap();
|
|
22
|
+
assert_eq!(stats.pending, 1);
|
|
23
|
+
assert_eq!(stats.running, 0);
|
|
24
|
+
|
|
25
|
+
let fetched = storage
|
|
26
|
+
.fetch(&["default".into()], 10, "worker-1", 5_000, now)
|
|
27
|
+
.unwrap();
|
|
28
|
+
assert_eq!(fetched.len(), 1);
|
|
29
|
+
assert_eq!(fetched[0].id, id);
|
|
30
|
+
assert_eq!(fetched[0].status, JobStatus::Running);
|
|
31
|
+
assert_eq!(fetched[0].worker_id.as_deref(), Some("worker-1"));
|
|
32
|
+
assert_eq!(fetched[0].lease_until_ms, Some(now + 5_000));
|
|
33
|
+
|
|
34
|
+
// Second fetch should not return already-leased job
|
|
35
|
+
let fetched2 = storage
|
|
36
|
+
.fetch(&["default".into()], 10, "worker-2", 5_000, now)
|
|
37
|
+
.unwrap();
|
|
38
|
+
assert!(fetched2.is_empty());
|
|
39
|
+
|
|
40
|
+
assert!(storage.ack(&id, Some(r#"{"ok":true}"#.into()), now + 10).unwrap());
|
|
41
|
+
|
|
42
|
+
let stats = storage.stats().unwrap();
|
|
43
|
+
assert_eq!(stats.pending, 0);
|
|
44
|
+
assert_eq!(stats.running, 0);
|
|
45
|
+
assert_eq!(stats.completed, 1);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
fn test_priority_and_delayed_ordering<S: StorageBackend>(storage: &S) {
|
|
49
|
+
storage.clear().unwrap();
|
|
50
|
+
let now = 2_000_000_i64;
|
|
51
|
+
|
|
52
|
+
let mut low = EnqueueRequest::new("default", "LowJob", "[]");
|
|
53
|
+
low.priority = 1;
|
|
54
|
+
let low_id = storage.enqueue(low.into_job(now)).unwrap();
|
|
55
|
+
|
|
56
|
+
let mut high = EnqueueRequest::new("default", "HighJob", "[]");
|
|
57
|
+
high.priority = 10;
|
|
58
|
+
let high_id = storage.enqueue(high.into_job(now)).unwrap();
|
|
59
|
+
|
|
60
|
+
let mut delayed = EnqueueRequest::new("default", "DelayedJob", "[]");
|
|
61
|
+
delayed.priority = 100;
|
|
62
|
+
delayed.delay_ms = 5_000;
|
|
63
|
+
let delayed_id = storage.enqueue(delayed.into_job(now)).unwrap();
|
|
64
|
+
|
|
65
|
+
// At `now`, delayed job must NOT be fetched even though its priority is 100.
|
|
66
|
+
let batch = storage
|
|
67
|
+
.fetch(&["default".into()], 10, "w1", 5_000, now)
|
|
68
|
+
.unwrap();
|
|
69
|
+
assert_eq!(batch.len(), 2);
|
|
70
|
+
assert_eq!(batch[0].id, high_id);
|
|
71
|
+
assert_eq!(batch[1].id, low_id);
|
|
72
|
+
|
|
73
|
+
// After delay elapses, delayed job becomes fetchable.
|
|
74
|
+
let batch2 = storage
|
|
75
|
+
.fetch(&["default".into()], 10, "w1", 5_000, now + 5_000)
|
|
76
|
+
.unwrap();
|
|
77
|
+
assert_eq!(batch2.len(), 1);
|
|
78
|
+
assert_eq!(batch2[0].id, delayed_id);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
fn test_retry_and_dead_letter_queue<S: StorageBackend>(storage: &S) {
|
|
82
|
+
storage.clear().unwrap();
|
|
83
|
+
let now = 3_000_000_i64;
|
|
84
|
+
|
|
85
|
+
let mut req = EnqueueRequest::new("default", "FlakyJob", "[]");
|
|
86
|
+
req.max_retries = 1;
|
|
87
|
+
let id = storage.enqueue(req.into_job(now)).unwrap();
|
|
88
|
+
|
|
89
|
+
let _ = storage.fetch(&["default".into()], 1, "w1", 5_000, now).unwrap();
|
|
90
|
+
|
|
91
|
+
// First failure schedules retry
|
|
92
|
+
let status = storage
|
|
93
|
+
.fail(&id, "boom 1", Some(now + 1_000), now + 10)
|
|
94
|
+
.unwrap();
|
|
95
|
+
assert_eq!(status, JobStatus::Pending);
|
|
96
|
+
|
|
97
|
+
// Not due yet
|
|
98
|
+
assert!(storage
|
|
99
|
+
.fetch(&["default".into()], 1, "w1", 5_000, now + 500)
|
|
100
|
+
.unwrap()
|
|
101
|
+
.is_empty());
|
|
102
|
+
|
|
103
|
+
// Due at now + 1_000
|
|
104
|
+
let retried = storage
|
|
105
|
+
.fetch(&["default".into()], 1, "w1", 5_000, now + 1_000)
|
|
106
|
+
.unwrap();
|
|
107
|
+
assert_eq!(retried.len(), 1);
|
|
108
|
+
assert_eq!(retried[0].attempt, 1);
|
|
109
|
+
assert_eq!(retried[0].last_error.as_deref(), Some("boom 1"));
|
|
110
|
+
|
|
111
|
+
// Final failure routes to Dead (DLQ)
|
|
112
|
+
let status = storage.fail(&id, "boom final", None, now + 1_050).unwrap();
|
|
113
|
+
assert_eq!(status, JobStatus::Dead);
|
|
114
|
+
|
|
115
|
+
let dead_job = storage.get_job(&id).unwrap().unwrap();
|
|
116
|
+
assert_eq!(dead_job.status, JobStatus::Dead);
|
|
117
|
+
assert_eq!(dead_job.last_error.as_deref(), Some("boom final"));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
fn test_stalled_lease_recovery<S: StorageBackend>(storage: &S) {
|
|
121
|
+
storage.clear().unwrap();
|
|
122
|
+
let now = 4_000_000_i64;
|
|
123
|
+
|
|
124
|
+
let mut req = EnqueueRequest::new("default", "CrashJob", "[]");
|
|
125
|
+
req.max_retries = 2;
|
|
126
|
+
let id = storage.enqueue(req.into_job(now)).unwrap();
|
|
127
|
+
|
|
128
|
+
let _ = storage.fetch(&["default".into()], 1, "dead-worker", 1_000, now).unwrap();
|
|
129
|
+
|
|
130
|
+
// Before lease expires, recovery reclaims nothing
|
|
131
|
+
assert_eq!(storage.recover_stalled(now + 500).unwrap(), 0);
|
|
132
|
+
|
|
133
|
+
// Renew lease pushes expiration forward
|
|
134
|
+
assert!(storage
|
|
135
|
+
.renew_lease(&id, "dead-worker", now + 3_000, now + 500)
|
|
136
|
+
.unwrap());
|
|
137
|
+
assert_eq!(storage.recover_stalled(now + 2_000).unwrap(), 0);
|
|
138
|
+
|
|
139
|
+
// After lease expires, recovery reclaims job back to Pending
|
|
140
|
+
assert_eq!(storage.recover_stalled(now + 3_001).unwrap(), 1);
|
|
141
|
+
|
|
142
|
+
let recovered = storage
|
|
143
|
+
.fetch(&["default".into()], 1, "healthy-worker", 5_000, now + 3_002)
|
|
144
|
+
.unwrap();
|
|
145
|
+
assert_eq!(recovered.len(), 1);
|
|
146
|
+
assert_eq!(recovered[0].id, id);
|
|
147
|
+
assert_eq!(recovered[0].attempt, 1);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
fn test_progress_and_result<S: StorageBackend>(storage: &S) {
|
|
151
|
+
storage.clear().unwrap();
|
|
152
|
+
let now = 5_000_000_i64;
|
|
153
|
+
let id = storage
|
|
154
|
+
.enqueue(EnqueueRequest::new("default", "ReportJob", "[]").into_job(now))
|
|
155
|
+
.unwrap();
|
|
156
|
+
let _ = storage.fetch(&["default".into()], 1, "w1", 5_000, now).unwrap();
|
|
157
|
+
|
|
158
|
+
assert!(storage.update_progress(&id, 55, now + 10).unwrap());
|
|
159
|
+
let job = storage.get_job(&id).unwrap().unwrap();
|
|
160
|
+
assert_eq!(job.progress, Some(55));
|
|
161
|
+
|
|
162
|
+
assert!(storage
|
|
163
|
+
.ack(&id, Some(r#"{"rows":1000}"#.into()), now + 20)
|
|
164
|
+
.unwrap());
|
|
165
|
+
let job = storage.get_job(&id).unwrap().unwrap();
|
|
166
|
+
assert_eq!(job.result.as_deref(), Some(r#"{"rows":1000}"#));
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
fn test_batch_enqueue_and_ack<S: StorageBackend>(storage: &S) {
|
|
170
|
+
storage.clear().unwrap();
|
|
171
|
+
let now = 6_000_000_i64;
|
|
172
|
+
let jobs: Vec<_> = (0..50)
|
|
173
|
+
.map(|i| EnqueueRequest::new("bulk", "BulkJob", format!("[{i}]")).into_job(now))
|
|
174
|
+
.collect();
|
|
175
|
+
let ids = storage.enqueue_batch(jobs).unwrap();
|
|
176
|
+
assert_eq!(ids.len(), 50);
|
|
177
|
+
|
|
178
|
+
let fetched = storage
|
|
179
|
+
.fetch(&["bulk".into()], 50, "w1", 5_000, now)
|
|
180
|
+
.unwrap();
|
|
181
|
+
assert_eq!(fetched.len(), 50);
|
|
182
|
+
|
|
183
|
+
let acked = storage.ack_batch(&ids, now + 10).unwrap();
|
|
184
|
+
assert_eq!(acked, 50);
|
|
185
|
+
assert_eq!(storage.stats().unwrap().completed, 50);
|
|
186
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
use crate::error::{FerroqError, Result};
|
|
2
|
+
use aes_gcm::{
|
|
3
|
+
aead::{Aead, KeyInit},
|
|
4
|
+
Aes256Gcm, Nonce,
|
|
5
|
+
};
|
|
6
|
+
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
|
|
7
|
+
use rand::RngCore;
|
|
8
|
+
|
|
9
|
+
const ENVELOPE_PREFIX: &str = "enc:v1:";
|
|
10
|
+
const NONCE_LEN: usize = 12;
|
|
11
|
+
|
|
12
|
+
/// High-performance AES-256-GCM payload encryption engine.
|
|
13
|
+
/// Runs completely inside Rust without touching Ruby GVL.
|
|
14
|
+
#[derive(Clone)]
|
|
15
|
+
pub struct CryptoEngine {
|
|
16
|
+
cipher: Aes256Gcm,
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
impl CryptoEngine {
|
|
20
|
+
/// Creates a CryptoEngine from a 32-byte key.
|
|
21
|
+
pub fn from_raw_key(key: &[u8; 32]) -> Self {
|
|
22
|
+
Self {
|
|
23
|
+
cipher: Aes256Gcm::new(key.into()),
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/// Derives a 32-byte key from an arbitrary passphrase/secret using BLAKE3.
|
|
28
|
+
pub fn from_secret(secret: &str) -> Result<Self> {
|
|
29
|
+
if secret.is_empty() {
|
|
30
|
+
return Err(FerroqError::InvalidArgument(
|
|
31
|
+
"encryption secret cannot be empty".into(),
|
|
32
|
+
));
|
|
33
|
+
}
|
|
34
|
+
let hash = blake3::hash(secret.as_bytes());
|
|
35
|
+
Ok(Self::from_raw_key(hash.as_bytes()))
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
pub fn encrypt(&self, plaintext: &str) -> Result<String> {
|
|
39
|
+
let mut nonce_bytes = [0u8; NONCE_LEN];
|
|
40
|
+
rand::thread_rng().fill_bytes(&mut nonce_bytes);
|
|
41
|
+
let nonce = Nonce::from_slice(&nonce_bytes);
|
|
42
|
+
|
|
43
|
+
let ciphertext = self
|
|
44
|
+
.cipher
|
|
45
|
+
.encrypt(nonce, plaintext.as_bytes())
|
|
46
|
+
.map_err(|e| FerroqError::Crypto(format!("encryption failed: {e}")))?;
|
|
47
|
+
|
|
48
|
+
let mut combined = Vec::with_capacity(NONCE_LEN + ciphertext.len());
|
|
49
|
+
combined.extend_from_slice(&nonce_bytes);
|
|
50
|
+
combined.extend_from_slice(&ciphertext);
|
|
51
|
+
|
|
52
|
+
Ok(format!("{ENVELOPE_PREFIX}{}", BASE64.encode(&combined)))
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
pub fn decrypt(&self, envelope: &str) -> Result<String> {
|
|
56
|
+
let encoded = envelope
|
|
57
|
+
.strip_prefix(ENVELOPE_PREFIX)
|
|
58
|
+
.ok_or_else(|| FerroqError::Crypto("invalid encrypted payload prefix".into()))?;
|
|
59
|
+
|
|
60
|
+
let combined = BASE64
|
|
61
|
+
.decode(encoded)
|
|
62
|
+
.map_err(|e| FerroqError::Crypto(format!("invalid base64 payload: {e}")))?;
|
|
63
|
+
|
|
64
|
+
if combined.len() <= NONCE_LEN {
|
|
65
|
+
return Err(FerroqError::Crypto("encrypted payload too short".into()));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
let (nonce_bytes, ciphertext) = combined.split_at(NONCE_LEN);
|
|
69
|
+
let nonce = Nonce::from_slice(nonce_bytes);
|
|
70
|
+
|
|
71
|
+
let plaintext = self
|
|
72
|
+
.cipher
|
|
73
|
+
.decrypt(nonce, ciphertext)
|
|
74
|
+
.map_err(|e| FerroqError::Crypto(format!("decryption failed: {e}")))?;
|
|
75
|
+
|
|
76
|
+
String::from_utf8(plaintext)
|
|
77
|
+
.map_err(|e| FerroqError::Crypto(format!("decrypted payload is not valid UTF-8: {e}")))
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/// Fast, collision-resistant BLAKE3 digest for unique job deduplication.
|
|
82
|
+
pub fn compute_unique_digest(queue: &str, job_class: &str, payload: &str) -> String {
|
|
83
|
+
let mut hasher = blake3::Hasher::new();
|
|
84
|
+
hasher.update(queue.as_bytes());
|
|
85
|
+
hasher.update(b"\0");
|
|
86
|
+
hasher.update(job_class.as_bytes());
|
|
87
|
+
hasher.update(b"\0");
|
|
88
|
+
hasher.update(payload.as_bytes());
|
|
89
|
+
hasher.finalize().to_hex().to_string()
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
#[cfg(test)]
|
|
93
|
+
mod tests {
|
|
94
|
+
use super::*;
|
|
95
|
+
|
|
96
|
+
#[test]
|
|
97
|
+
fn roundtrip_encryption_produces_distinct_ciphertexts() {
|
|
98
|
+
let crypto = CryptoEngine::from_secret("super-secret-ferroq-key").unwrap();
|
|
99
|
+
let plain = r#"{"user_id":42,"ssn":"123-45-6789"}"#;
|
|
100
|
+
|
|
101
|
+
let c1 = crypto.encrypt(plain).unwrap();
|
|
102
|
+
let c2 = crypto.encrypt(plain).unwrap();
|
|
103
|
+
|
|
104
|
+
assert!(c1.starts_with("enc:v1:"));
|
|
105
|
+
assert_ne!(c1, c2, "random nonce must produce distinct ciphertexts");
|
|
106
|
+
assert!(!c1.contains("123-45-6789"));
|
|
107
|
+
assert_eq!(crypto.decrypt(&c1).unwrap(), plain);
|
|
108
|
+
assert_eq!(crypto.decrypt(&c2).unwrap(), plain);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
#[test]
|
|
112
|
+
fn wrong_key_fails_decryption() {
|
|
113
|
+
let c1 = CryptoEngine::from_secret("key-a").unwrap();
|
|
114
|
+
let c2 = CryptoEngine::from_secret("key-b").unwrap();
|
|
115
|
+
let enc = c1.encrypt("secret").unwrap();
|
|
116
|
+
assert!(c2.decrypt(&enc).is_err());
|
|
117
|
+
}
|
|
118
|
+
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
use crate::crypto::CryptoEngine;
|
|
2
|
+
use crate::error::{FerroqError, Result};
|
|
3
|
+
use crate::job::{compute_retry_delay_ms, now_ms, EnqueueRequest, Job, JobStatus, QueueStats};
|
|
4
|
+
use crate::storage::StorageBackend;
|
|
5
|
+
use std::sync::Arc;
|
|
6
|
+
|
|
7
|
+
#[derive(Debug, Clone)]
|
|
8
|
+
pub struct EngineConfig {
|
|
9
|
+
pub default_lease_ms: i64,
|
|
10
|
+
pub retry_base_delay_ms: i64,
|
|
11
|
+
pub encryption_secret: Option<String>,
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
impl Default for EngineConfig {
|
|
15
|
+
fn default() -> Self {
|
|
16
|
+
Self {
|
|
17
|
+
default_lease_ms: 30_000,
|
|
18
|
+
retry_base_delay_ms: 1_000,
|
|
19
|
+
encryption_secret: None,
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/// Core Ferroq engine coordinating storage, transparent encryption,
|
|
25
|
+
/// reliable lease delivery, exponential retry backoff, and stalled job recovery.
|
|
26
|
+
pub struct FerroqEngine {
|
|
27
|
+
storage: Arc<dyn StorageBackend>,
|
|
28
|
+
crypto: Option<CryptoEngine>,
|
|
29
|
+
config: EngineConfig,
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
impl FerroqEngine {
|
|
33
|
+
pub fn new(storage: Arc<dyn StorageBackend>, config: EngineConfig) -> Result<Self> {
|
|
34
|
+
let crypto = match &config.encryption_secret {
|
|
35
|
+
Some(secret) => Some(CryptoEngine::from_secret(secret)?),
|
|
36
|
+
None => None,
|
|
37
|
+
};
|
|
38
|
+
Ok(Self {
|
|
39
|
+
storage,
|
|
40
|
+
crypto,
|
|
41
|
+
config,
|
|
42
|
+
})
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
pub fn storage(&self) -> &Arc<dyn StorageBackend> {
|
|
46
|
+
&self.storage
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
pub fn enqueue(&self, req: EnqueueRequest) -> Result<String> {
|
|
50
|
+
let mut job = req.into_job(now_ms());
|
|
51
|
+
self.maybe_encrypt(&mut job)?;
|
|
52
|
+
self.storage.enqueue(job)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
pub fn enqueue_batch(&self, requests: Vec<EnqueueRequest>) -> Result<Vec<String>> {
|
|
56
|
+
let ts = now_ms();
|
|
57
|
+
let mut jobs = Vec::with_capacity(requests.len());
|
|
58
|
+
for req in requests {
|
|
59
|
+
let mut job = req.into_job(ts);
|
|
60
|
+
self.maybe_encrypt(&mut job)?;
|
|
61
|
+
jobs.push(job);
|
|
62
|
+
}
|
|
63
|
+
self.storage.enqueue_batch(jobs)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
pub fn fetch(
|
|
67
|
+
&self,
|
|
68
|
+
queues: &[String],
|
|
69
|
+
batch_size: usize,
|
|
70
|
+
worker_id: &str,
|
|
71
|
+
lease_ms: Option<i64>,
|
|
72
|
+
) -> Result<Vec<Job>> {
|
|
73
|
+
if batch_size == 0 || queues.is_empty() {
|
|
74
|
+
return Ok(Vec::new());
|
|
75
|
+
}
|
|
76
|
+
let lease = lease_ms.unwrap_or(self.config.default_lease_ms);
|
|
77
|
+
let mut jobs = self
|
|
78
|
+
.storage
|
|
79
|
+
.fetch(queues, batch_size, worker_id, lease, now_ms())?;
|
|
80
|
+
for job in &mut jobs {
|
|
81
|
+
self.maybe_decrypt(job)?;
|
|
82
|
+
}
|
|
83
|
+
Ok(jobs)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
pub fn ack(&self, job_id: &str, result: Option<String>) -> Result<bool> {
|
|
87
|
+
self.storage.ack(job_id, result, now_ms())
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
pub fn ack_batch(&self, job_ids: &[String]) -> Result<usize> {
|
|
91
|
+
if job_ids.is_empty() {
|
|
92
|
+
return Ok(0);
|
|
93
|
+
}
|
|
94
|
+
self.storage.ack_batch(job_ids, now_ms())
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/// Fails a job, automatically scheduling an exponential backoff retry if
|
|
98
|
+
/// `attempt < max_retries`, otherwise routing it to the Dead-Letter Queue (`Dead`).
|
|
99
|
+
pub fn fail(&self, job_id: &str, error: &str) -> Result<JobStatus> {
|
|
100
|
+
let ts = now_ms();
|
|
101
|
+
let job = self
|
|
102
|
+
.storage
|
|
103
|
+
.get_job(job_id)?
|
|
104
|
+
.ok_or_else(|| FerroqError::NotFound(job_id.to_string()))?;
|
|
105
|
+
|
|
106
|
+
let next_attempt = job.attempt + 1;
|
|
107
|
+
let next_run_at = if next_attempt <= job.max_retries {
|
|
108
|
+
Some(ts + compute_retry_delay_ms(next_attempt, self.config.retry_base_delay_ms))
|
|
109
|
+
} else {
|
|
110
|
+
None
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
self.storage.fail(job_id, error, next_run_at, ts)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
pub fn renew_lease(&self, job_id: &str, worker_id: &str, lease_ms: Option<i64>) -> Result<bool> {
|
|
117
|
+
let ts = now_ms();
|
|
118
|
+
let lease = lease_ms.unwrap_or(self.config.default_lease_ms);
|
|
119
|
+
self.storage
|
|
120
|
+
.renew_lease(job_id, worker_id, ts + lease, ts)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
pub fn recover_stalled(&self) -> Result<usize> {
|
|
124
|
+
self.storage.recover_stalled(now_ms())
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
pub fn update_progress(&self, job_id: &str, progress: u8) -> Result<bool> {
|
|
128
|
+
if progress > 100 {
|
|
129
|
+
return Err(FerroqError::InvalidArgument(
|
|
130
|
+
"progress must be between 0 and 100".into(),
|
|
131
|
+
));
|
|
132
|
+
}
|
|
133
|
+
self.storage.update_progress(job_id, progress, now_ms())
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
pub fn get_job(&self, job_id: &str) -> Result<Option<Job>> {
|
|
137
|
+
let mut job = self.storage.get_job(job_id)?;
|
|
138
|
+
if let Some(ref mut j) = job {
|
|
139
|
+
self.maybe_decrypt(j)?;
|
|
140
|
+
}
|
|
141
|
+
Ok(job)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
pub fn stats(&self) -> Result<QueueStats> {
|
|
145
|
+
self.storage.stats()
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
pub fn clear(&self) -> Result<()> {
|
|
149
|
+
self.storage.clear()
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
fn maybe_encrypt(&self, job: &mut Job) -> Result<()> {
|
|
153
|
+
if job.encrypted {
|
|
154
|
+
let crypto = self.crypto.as_ref().ok_or_else(|| {
|
|
155
|
+
FerroqError::Crypto(
|
|
156
|
+
"job requested encryption, but no encryption_secret is configured".into(),
|
|
157
|
+
)
|
|
158
|
+
})?;
|
|
159
|
+
job.payload = crypto.encrypt(&job.payload)?;
|
|
160
|
+
}
|
|
161
|
+
Ok(())
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
fn maybe_decrypt(&self, job: &mut Job) -> Result<()> {
|
|
165
|
+
if job.encrypted {
|
|
166
|
+
let crypto = self.crypto.as_ref().ok_or_else(|| {
|
|
167
|
+
FerroqError::Crypto(
|
|
168
|
+
"job payload is encrypted, but no encryption_secret is configured".into(),
|
|
169
|
+
)
|
|
170
|
+
})?;
|
|
171
|
+
job.payload = crypto.decrypt(&job.payload)?;
|
|
172
|
+
}
|
|
173
|
+
Ok(())
|
|
174
|
+
}
|
|
175
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
use thiserror::Error;
|
|
2
|
+
|
|
3
|
+
#[derive(Debug, Error)]
|
|
4
|
+
pub enum FerroqError {
|
|
5
|
+
#[error("storage error: {0}")]
|
|
6
|
+
Storage(String),
|
|
7
|
+
|
|
8
|
+
#[error("crypto error: {0}")]
|
|
9
|
+
Crypto(String),
|
|
10
|
+
|
|
11
|
+
#[error("serialization error: {0}")]
|
|
12
|
+
Serialization(String),
|
|
13
|
+
|
|
14
|
+
#[error("invalid argument: {0}")]
|
|
15
|
+
InvalidArgument(String),
|
|
16
|
+
|
|
17
|
+
#[error("job not found: {0}")]
|
|
18
|
+
NotFound(String),
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
pub type Result<T> = std::result::Result<T, FerroqError>;
|