1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
/*!
* Worker execution module
*
* Extracted from main.rs to reduce complexity and improve maintainability.
* Handles intent worker loops and message processing from NATS JetStream.
*/
use anyhow::Result;
use std::sync::Arc;
use std::time::Instant;
use tracing::{info, instrument};
use uuid::Uuid;
use smith_config::PolicyDerivations;
// smith_protocol types used in admission_pipeline module
use crate::{
admission_pipeline::ProcessingOutcome, audit, config::Config, idempotency, metrics, nats,
policy, runners, schema, security, trace,
};
/// Main worker execution loop for processing intents from NATS JetStream
#[instrument(
skip_all,
fields(
capability = %capability,
worker_id = %worker_id,
capability_digest = %capability_digest[..8]
)
)]
pub async fn run_worker(
capability: String,
worker_id: u32,
nats_client: nats::NatsClient,
idempotency_store: idempotency::IdempotencyStore,
policy_engine: policy::PolicyEngine,
schema_validator: Arc<schema::SchemaValidator>,
runner_registry: Arc<runners::RunnerRegistry>,
trusted_signers: Arc<security::TrustedSigners>,
config: Config,
metrics: Arc<tokio::sync::RwLock<metrics::ExecutorMetrics>>,
audit_logger: Arc<tokio::sync::Mutex<audit::AuditLogger>>,
capability_digest: String,
derivations: Arc<PolicyDerivations>,
) -> Result<()> {
info!(
capability = %capability,
worker_id = %worker_id,
capability_digest = %capability_digest[..8],
"Worker starting for capability processing"
);
// Create JetStream consumer for this capability
let stream_config = config
.executor
.intent_streams
.get(&capability)
.ok_or_else(|| anyhow::anyhow!("No stream config found for capability: {}", capability))?;
let mut consumer = match nats_client
.create_consumer(&capability, stream_config)
.await
{
Ok(consumer) => consumer,
Err(err) => {
tracing::error!(
capability = %capability,
worker_id = worker_id,
error = %err,
error_debug = ?err,
"Failed to create JetStream consumer"
);
return Err(err);
}
};
loop {
// Create NATS pull span for tracing
let nats_span = trace::ExecutorTracer::span_nats_pull(
&capability,
&format!("{}-worker-{}", capability, worker_id),
);
let pull_start = Instant::now();
// Pull message from JetStream
match consumer.next().await {
Ok(Some(message)) => {
let pull_duration = pull_start.elapsed();
{
let m = metrics.read().await;
m.record_nats_pull_latency(pull_duration.as_secs_f64() * 1000.0);
}
let _nats_duration = nats_span.finish_success();
let intent_id = Uuid::new_v4(); // This will be extracted from message
let trace_id = trace::generate_trace_id();
tracing::info!(
trace_id = trace_id,
intent_id = %intent_id,
capability = capability,
worker_id = worker_id,
seq = 0,
status = "pulled",
"Intent message pulled from NATS"
);
// Process the intent through admission pipeline
match crate::admission_pipeline::process_intent(
message.message,
&idempotency_store,
&policy_engine,
&schema_validator,
&runner_registry,
&trusted_signers,
&config,
&nats_client,
&metrics,
&audit_logger,
&capability,
&intent_id.to_string(),
&trace_id,
&capability_digest,
&derivations,
)
.await
{
Ok(ProcessingOutcome::Completed) => {
tracing::info!(
trace_id = trace_id,
intent_id = %intent_id,
capability = capability,
status = "completed",
code = "SUCCESS",
"Intent processed successfully"
);
}
Ok(ProcessingOutcome::Denied { reason }) => {
tracing::info!(
trace_id = trace_id,
intent_id = %intent_id,
capability = capability,
status = "denied",
code = "POLICY_DENIED",
denial_reason = %reason,
"Intent denied by policy"
);
}
Err(e) => {
tracing::error!(
trace_id = trace_id,
intent_id = %intent_id,
capability = capability,
status = "error",
code = "PROCESSING_ERROR",
error = %e,
"Intent processing failed"
);
{
let m = metrics.read().await;
m.record_result_error();
}
}
}
}
Ok(None) => {
let _nats_duration = nats_span.finish_success();
// Update queue depth metric to 0 when no messages
{
let m = metrics.read().await;
m.set_queue_depth(&capability, 0);
}
// No messages available, continue polling
tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
}
Err(e) => {
let _nats_duration = nats_span.finish_error(&e.to_string());
{
let m = metrics.read().await;
m.record_nats_connection_error();
}
tracing::error!(
capability = capability,
worker_id = worker_id,
error = %e,
"Error pulling message from NATS"
);
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
}
}
}
}