brokk-mj-controller 2.23.2

Daemon-side controller, session manager, and web server for Mjolnir
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
use super::*;

#[derive(Debug, Clone)]
pub struct SessionManagerUpdate {
    pub session_id: String,
    pub view: ManagedSessionView,
}

pub struct SessionManagerChannels {
    pub targets: watch::Sender<Vec<RelaySessionTarget>>,
    pub control: SessionManagerControl,
    pub updates: SessionManagerUpdates,
    pub shutdown: SessionManagerShutdown,
}

/// Client-side half of a remotely owned session manager.
///
/// The daemon remains the only process with relay connections. A control
/// surface publishes the daemon's latest views here and forwards requests from
/// [`RemoteSessionRequests`] over its authenticated transport.
pub struct RemoteSessionManagerChannels {
    pub targets: watch::Sender<Vec<RelaySessionTarget>>,
    pub control: SessionManagerControl,
    pub updates: SessionManagerUpdates,
    pub shutdown: SessionManagerShutdown,
    pub publisher: RemoteSessionPublisher,
    pub requests: RemoteSessionRequests,
}

#[derive(Clone)]
pub struct RemoteSessionPublisher {
    pub(super) updates: mpsc::UnboundedSender<RemoteManagerUpdate>,
}

impl RemoteSessionPublisher {
    pub async fn publish(&self, session_id: String, view: ManagedSessionView) -> Result<()> {
        self.updates
            .send(RemoteManagerUpdate::Publish { session_id, view })
            .context("remote session manager stopped")
    }

    pub fn try_publish(&self, session_id: String, view: ManagedSessionView) -> Result<()> {
        self.updates
            .send(RemoteManagerUpdate::Publish { session_id, view })
            .context("remote session manager update queue is unavailable")
    }
}

pub struct RemoteSessionRequests {
    pub(super) requests: mpsc::Receiver<RemoteSessionRequest>,
}

impl RemoteSessionRequests {
    pub async fn recv(&mut self) -> Option<RemoteSessionRequest> {
        self.requests.recv().await
    }
}

pub enum RemoteSessionRequest {
    Submit {
        session_id: String,
        command_id: String,
        command: RelayCommand,
        admission: Option<ReviewDeliveryAdmission>,
        reply: oneshot::Sender<std::result::Result<u64, mj_client::session::SubmitFailure>>,
    },
    Sync {
        session_id: String,
        reply: oneshot::Sender<std::result::Result<(), String>>,
    },
    RespondElicitation {
        session_id: String,
        elicitation_id: String,
        response: ElicitationResponse,
        reply: oneshot::Sender<std::result::Result<(), String>>,
    },
    StopBackgroundTask {
        session_id: String,
        background_task_id: String,
        reply: oneshot::Sender<std::result::Result<(), String>>,
    },
    Reviewer {
        session_id: String,
        /// Which reviewing role the action drives; `None` is the default one.
        role: Option<String>,
        action: ReviewerAction,
        reply: oneshot::Sender<std::result::Result<ReviewerOutcome, String>>,
    },
}

impl RemoteSessionRequest {
    /// The session this request acts on. Requests for one session have to be
    /// carried out in the order they were made.
    pub fn session_id(&self) -> &str {
        match self {
            Self::Submit { session_id, .. }
            | Self::Sync { session_id, .. }
            | Self::RespondElicitation { session_id, .. }
            | Self::StopBackgroundTask { session_id, .. }
            | Self::Reviewer { session_id, .. } => session_id,
        }
    }
}

/// Admission bounds include running work, queued work, and dispatcher messages.
const REQUESTS_PER_STREAM: usize = 32;
const REQUESTS_TOTAL: usize = 256;
type ForwardRequest = std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>>;
type RequestBudgets = Arc<Mutex<std::collections::HashMap<SessionRequestStream, usize>>>;

/// One supervisor drains accepted requests even when its bridge disconnects.
/// Each primary/reviewer stream runs in order, independently of other streams.
/// Dropping the bridge closes admission but leaves its supervisor draining:
/// disconnecting a caller cannot cancel a mutation that may already be accepted.
/// Owners that can await shutdown use `drain` to observe that completion.
pub struct SessionRequestOrder {
    sender: mpsc::Sender<OrderedRequest>,
    budgets: RequestBudgets,
    supervisor: tokio::task::JoinHandle<()>,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(super) enum SessionRequestStream {
    Primary(String),
    Reviewer(String, Option<String>),
}

struct RequestPermit {
    budgets: RequestBudgets,
    stream: SessionRequestStream,
}

impl Drop for RequestPermit {
    fn drop(&mut self) {
        let mut budgets = self.budgets.lock().expect("request budgets poisoned");
        let count = budgets.get_mut(&self.stream).expect("admitted request");
        *count -= 1;
        if *count == 0 {
            budgets.remove(&self.stream);
        }
    }
}

struct OrderedRequest {
    permit: RequestPermit,
    forward: ForwardRequest,
}

impl RemoteSessionRequest {
    pub(crate) fn reject(self, message: &str) {
        match self {
            Self::Submit { reply, .. } => {
                let _ = reply.send(Err(message.to_owned().into()));
            }
            Self::Sync { reply, .. }
            | Self::RespondElicitation { reply, .. }
            | Self::StopBackgroundTask { reply, .. } => {
                let _ = reply.send(Err(message.to_owned()));
            }
            Self::Reviewer { reply, .. } => {
                let _ = reply.send(Err(message.to_owned()));
            }
        }
    }
}

impl Default for SessionRequestOrder {
    fn default() -> Self {
        Self::new()
    }
}

impl SessionRequestOrder {
    #[must_use]
    pub fn new() -> Self {
        let (sender, receiver) = mpsc::channel(REQUESTS_TOTAL);
        Self {
            sender,
            budgets: Default::default(),
            supervisor: tokio::spawn(supervise_requests(receiver)),
        }
    }

    /// Overload is an explicit non-admission, never ambiguous delivery.
    pub fn dispatch<F, Fut>(&mut self, request: RemoteSessionRequest, forward: F)
    where
        F: FnOnce(RemoteSessionRequest) -> Fut + Send + 'static,
        Fut: std::future::Future<Output = ()> + Send + 'static,
    {
        let stream = match &request {
            RemoteSessionRequest::Reviewer {
                session_id, role, ..
            } => SessionRequestStream::Reviewer(session_id.clone(), role.clone()),
            _ => SessionRequestStream::Primary(request.session_id().to_owned()),
        };
        let mut budgets = self.budgets.lock().expect("request budgets poisoned");
        if budgets.get(&stream).copied().unwrap_or(0) >= REQUESTS_PER_STREAM
            || budgets.values().sum::<usize>() >= REQUESTS_TOTAL
        {
            drop(budgets);
            request.reject("session request queue is full; request was not accepted");
            return;
        }
        // Reserve the bounded channel before constructing the forwarded future,
        // so even a failed supervisor can refuse with a definite non-delivery.
        let Ok(slot) = self.sender.try_reserve() else {
            drop(budgets);
            request.reject("session request dispatcher is unavailable; request was not accepted");
            return;
        };
        *budgets.entry(stream.clone()).or_default() += 1;
        drop(budgets);
        slot.send(OrderedRequest {
            permit: RequestPermit {
                budgets: self.budgets.clone(),
                stream,
            },
            forward: Box::pin(async move { forward(request).await }),
        });
    }

    /// Close admission and wait for all admitted work, including queued work.
    pub async fn drain(self) -> Result<()> {
        drop(self.sender);
        self.supervisor
            .await
            .context("session request supervisor failed")
    }
}

async fn supervise_requests(mut requests: mpsc::Receiver<OrderedRequest>) {
    let mut tasks = tokio::task::JoinSet::new();
    let mut running = std::collections::HashMap::new();
    let mut pending =
        std::collections::HashMap::<SessionRequestStream, VecDeque<OrderedRequest>>::new();
    let mut closed = false;
    loop {
        tokio::select! {
            // Reap ready tasks before accepting another message; completed task
            // records cannot accumulate behind a continuously busy producer.
            biased;
            completed = tasks.join_next_with_id(), if !tasks.is_empty() => {
                let task_id = match completed.expect("nonempty request tasks") {
                    Ok((id, ())) => id,
                    Err(error) => {
                        tracing::error!(stream = ?running.get(&error.id()), %error, "session request task failed");
                        error.id()
                    }
                };
                let stream = running.remove(&task_id).expect("registered request task");
                if let Some(queue) = pending.get_mut(&stream) {
                    if let Some(request) = queue.pop_front() {
                        let handle = tasks.spawn(async move {
                            let _permit = request.permit;
                            request.forward.await;
                        });
                        running.insert(handle.id(), stream.clone());
                    }
                    if queue.is_empty() { pending.remove(&stream); }
                }
            }
            request = requests.recv(), if !closed => {
                match request {
                    Some(request) => {
                        let stream = request.permit.stream.clone();
                        if running.values().any(|active| active == &stream) {
                            pending.entry(stream).or_default().push_back(request);
                        } else {
                            let handle = tasks.spawn(async move {
                                let _permit = request.permit;
                                request.forward.await;
                            });
                            running.insert(handle.id(), stream);
                        }
                    }
                    None => closed = true,
                }
            }
        }
        if closed && tasks.is_empty() {
            break;
        }
    }
}

/// Exclusive owner of the manager task and every relay actor below it.
///
/// Long-running control surfaces explicitly await [`Self::shutdown`] before
/// their Tokio runtime goes away. Drop remains an aborting fallback for tests
/// and early-return paths that cannot await.
pub struct SessionManagerShutdown {
    pub(super) signal: Option<oneshot::Sender<()>>,
    pub(super) task: Option<tokio::task::JoinHandle<()>>,
}

impl SessionManagerShutdown {
    pub async fn shutdown(mut self) -> Result<()> {
        if let Some(signal) = self.signal.take() {
            let _ = signal.send(());
        }
        if let Some(task) = self.task.take() {
            task.await.context("session manager shutdown task failed")?;
        }
        Ok(())
    }
}

impl Drop for SessionManagerShutdown {
    fn drop(&mut self) {
        if let Some(signal) = self.signal.take() {
            let _ = signal.send(());
        }
        if let Some(task) = self.task.take() {
            task.abort();
        }
    }
}

#[derive(Clone)]
pub(crate) struct CoalescedUpdateSender {
    producers: Arc<Mutex<BTreeMap<String, Arc<()>>>>,
    producer: Option<Arc<UpdateProducer>>,
    pub(super) delegation: Option<DelegationSender>,
    pub(super) observer: Option<Arc<DelegationPublisher>>,
    pub(super) pending: Arc<Mutex<BTreeMap<String, PendingUpdate>>>,
    pub(super) wake: mpsc::Sender<()>,
}

struct UpdateProducer {
    registry: Arc<Mutex<BTreeMap<String, Arc<()>>>>,
    session_id: String,
    identity: Arc<()>,
}

impl Drop for UpdateProducer {
    fn drop(&mut self) {
        let mut registry = self
            .registry
            .lock()
            .expect("session producer registry poisoned");
        if registry
            .get(&self.session_id)
            .is_some_and(|current| Arc::ptr_eq(current, &self.identity))
        {
            registry.remove(&self.session_id);
        }
    }
}

/// Bounded latest-state feed for the dashboard. At most one snapshot per
/// session is retained while the consumer is busy.
pub struct SessionManagerUpdates {
    pub(super) pending: Arc<Mutex<BTreeMap<String, PendingUpdate>>>,
    pub(super) wake: mpsc::Receiver<()>,
    // Keep the update owned until the consumer asks for another one. Its
    // completion edge can schedule a review or continuation in the meantime.
    delivered_work: Option<crate::upgrade::Work>,
}

pub(super) struct PendingUpdate {
    update: SessionManagerUpdate,
    work: Option<crate::upgrade::Work>,
}

impl CoalescedUpdateSender {
    pub(super) fn for_actor(&self, session_id: &str) -> Self {
        assert!(
            self.producer.is_none(),
            "only the manager registers producers"
        );
        let identity = Arc::new(());
        let mut registry = self
            .producers
            .lock()
            .expect("session producer registry poisoned");
        registry.insert(session_id.to_owned(), identity.clone());
        // Replacing a producer also invalidates its undelivered observation.
        self.pending
            .lock()
            .expect("session update coalescer poisoned")
            .remove(session_id);
        let mut sender = self.clone();
        sender.producer = Some(Arc::new(UpdateProducer {
            registry: self.producers.clone(),
            session_id: session_id.to_owned(),
            identity,
        }));
        sender
    }

    pub(crate) fn send(&self, update: SessionManagerUpdate) {
        let registry = self
            .producers
            .lock()
            .expect("session producer registry poisoned");
        if let Some(producer) = &self.producer {
            assert_eq!(producer.session_id, update.session_id);
            if !registry
                .get(&update.session_id)
                .is_some_and(|current| Arc::ptr_eq(current, &producer.identity))
            {
                return;
            }
        }
        if let Some(observer) = &self.observer {
            observer.publish(&update.view);
        }
        if self.wake.is_closed() {
            return;
        }
        self.pending
            .lock()
            .expect("session update coalescer poisoned")
            .insert(
                update.session_id.clone(),
                PendingUpdate {
                    update,
                    work: crate::upgrade::activity("session update").ok(),
                },
            );
        let _ = self.wake.try_send(());
    }
}

impl SessionManagerUpdates {
    pub(super) fn pop_pending(&mut self) -> Option<SessionManagerUpdate> {
        self.delivered_work = None;
        let pending = self
            .pending
            .lock()
            .expect("session update coalescer poisoned")
            .pop_first()
            .map(|(_, update)| update)?;
        self.delivered_work = pending.work;
        Some(pending.update)
    }

    pub async fn recv(&mut self) -> Option<SessionManagerUpdate> {
        loop {
            if let Some(update) = self.pop_pending() {
                return Some(update);
            }
            self.wake.recv().await?;
        }
    }

    pub fn try_recv(
        &mut self,
    ) -> std::result::Result<SessionManagerUpdate, mpsc::error::TryRecvError> {
        if let Some(update) = self.pop_pending() {
            return Ok(update);
        }
        self.wake.try_recv()?;
        self.pop_pending().ok_or(mpsc::error::TryRecvError::Empty)
    }
}

pub(crate) fn coalesced_update_channel() -> (CoalescedUpdateSender, SessionManagerUpdates) {
    let pending = Arc::new(Mutex::new(BTreeMap::new()));
    let (wake_tx, wake_rx) = mpsc::channel(1);
    (
        CoalescedUpdateSender {
            producers: Default::default(),
            producer: None,
            delegation: None,
            observer: None,
            pending: pending.clone(),
            wake: wake_tx,
        },
        SessionManagerUpdates {
            pending,
            wake: wake_rx,
            delivered_work: None,
        },
    )
}