bmux_client 0.0.1-alpha.3

Client component for bmux terminal multiplexer
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
//! Domain-neutral attach-provider registration and target resolution.

use std::any::Any;
use std::collections::BTreeMap;
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, OnceLock, RwLock, Weak};

use crate::BmuxClient;

/// Parsed attach target presented to provider resolvers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AttachTarget {
    raw: String,
    scheme: Option<String>,
    reference: String,
}

impl AttachTarget {
    /// Parse a target without assigning domain meaning to its scheme.
    #[must_use]
    pub fn parse(raw: impl Into<String>) -> Self {
        let raw = raw.into();
        let (scheme, reference) = raw.split_once("://").map_or_else(
            || (None, raw.clone()),
            |(scheme, reference)| {
                if valid_scheme(scheme) {
                    (Some(scheme.to_ascii_lowercase()), reference.to_string())
                } else {
                    (None, raw.clone())
                }
            },
        );
        Self {
            raw,
            scheme,
            reference,
        }
    }

    /// Original target text.
    #[must_use]
    pub fn raw(&self) -> &str {
        &self.raw
    }

    /// Normalized URI scheme, when the target has a valid `scheme://` prefix.
    #[must_use]
    pub fn scheme(&self) -> Option<&str> {
        self.scheme.as_deref()
    }

    /// Target text following a valid scheme, or the entire bare target.
    #[must_use]
    pub fn reference(&self) -> &str {
        &self.reference
    }
}

fn valid_scheme(scheme: &str) -> bool {
    let mut chars = scheme.chars();
    chars
        .next()
        .is_some_and(|first| first.is_ascii_alphabetic())
        && chars.all(|value| value.is_ascii_alphanumeric() || matches!(value, '+' | '-' | '.'))
}

/// Boxed provider future.
pub type AttachProviderFuture<'a, T> =
    Pin<Box<dyn Future<Output = Result<T, AttachProviderError>> + Send + 'a>>;

/// Future returned by a domain-neutral attach endpoint connector.
pub type AttachEndpointConnectFuture<'a> =
    Pin<Box<dyn Future<Output = Result<BmuxClient, String>> + Send + 'a>>;

/// Generic endpoint dialing supplied by the host attach runtime.
///
/// Providers choose endpoint candidates according to their own domain policy;
/// this connector only establishes one opaque target and returns a normal bmux
/// client. Targets may be host-configured aliases, direct endpoint labels, or
/// plugin-defined bootstrap references understood by the host dialer.
pub trait AttachEndpointConnector: fmt::Debug + Send + Sync + 'static {
    /// Connect to one opaque endpoint target.
    fn connect<'a>(
        &'a self,
        target: &'a str,
        client_name: &'static str,
    ) -> AttachEndpointConnectFuture<'a>;
}

/// Host capabilities supplied while opening one resolved provider target.
pub struct AttachProviderOpenContext {
    /// Existing one-server connection for providers that declare fallback use.
    pub fallback_client: Option<BmuxClient>,
    /// Generic endpoint dialer for providers that own candidate selection.
    pub endpoint_connector: Option<Arc<dyn AttachEndpointConnector>>,
}

impl fmt::Debug for AttachProviderOpenContext {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("AttachProviderOpenContext")
            .field("has_fallback_client", &self.fallback_client.is_some())
            .field("has_endpoint_connector", &self.endpoint_connector.is_some())
            .finish()
    }
}

/// Opaque provider resolution carried into attach opening.
pub trait ResolvedAttachTarget: fmt::Debug + Send + Sync + 'static {
    /// Stable provider ID that produced this plan.
    fn provider_id(&self) -> &str;

    /// Runtime downcast support for provider-private plans.
    fn as_any(&self) -> &dyn Any;
}

/// Neutral backend returned by an attach provider.
#[derive(Debug)]
pub enum AttachProviderBackend {
    /// Existing one-server request/event client path.
    Legacy(BmuxClient),
    /// Native generic provider session.
    Session(Box<dyn crate::AttachSession>),
}

/// Neutral attach input returned by providers.
#[derive(Debug)]
pub struct AttachProviderSession {
    pub backend: AttachProviderBackend,
    /// Provider-resolved session/follow target. `None` preserves caller input.
    pub target: Option<String>,
}

/// Provider resolution/open failure.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum AttachProviderError {
    /// Provider rejected a target it previously claimed.
    #[error("attach provider '{provider_id}' rejected target '{target}': {reason}")]
    InvalidTarget {
        provider_id: String,
        target: String,
        reason: String,
    },
    /// Provider could not open the resolved attach target.
    #[error("attach provider '{provider_id}' failed opening target: {reason}")]
    OpenFailed { provider_id: String, reason: String },
}

/// A provider capable of recognizing, resolving, and opening attach targets.
pub trait AttachProvider: fmt::Debug + Send + Sync + 'static {
    /// Stable process-local provider identifier.
    fn id(&self) -> &str;

    /// Resolution precedence. Higher values win.
    fn priority(&self) -> i32 {
        0
    }

    /// Whether this provider owns `target`.
    fn supports(&self, target: &AttachTarget) -> bool;

    /// Whether this provider requires the caller to establish the legacy
    /// fallback client before [`open`](Self::open).
    fn requires_fallback_client(&self) -> bool {
        false
    }

    /// Whether external selection changes may retarget this opened view.
    /// Fixed-output adapters preserve the explicitly selected source identity.
    fn allows_retarget(&self) -> bool {
        true
    }

    /// Resolve the authoritative rendering viewport without claiming sizing authority.
    /// Providers own selection and detached fallback policy. Unsupported backends
    /// return an error rather than silently turn an observer into a sizing client.
    fn observe_viewport<'a>(
        &'a self,
        _client: &'a mut crate::StreamingBmuxClient,
        _target: &'a str,
        _fallback: crate::AttachProviderViewport,
    ) -> AttachProviderFuture<'a, crate::AttachProviderViewport> {
        Box::pin(async move {
            Err(AttachProviderError::OpenFailed {
                provider_id: self.id().to_string(),
                reason: "non-sizing observation is unsupported".to_string(),
            })
        })
    }

    /// Resolve target syntax/configuration into a provider-private plan.
    ///
    /// # Errors
    ///
    /// Returns a structured provider error when the claimed target is invalid
    /// or cannot be resolved.
    fn resolve(
        &self,
        target: &AttachTarget,
    ) -> Result<Arc<dyn ResolvedAttachTarget>, AttachProviderError>;

    /// Open the resolved plan into the neutral client/session input consumed by
    /// the current attach runtime. The context supplies only generic host
    /// capabilities: an optional legacy fallback client and an optional opaque
    /// endpoint connector.
    fn open(
        &self,
        resolved: Arc<dyn ResolvedAttachTarget>,
        resume: Option<crate::AttachResumeState>,
        context: AttachProviderOpenContext,
    ) -> AttachProviderFuture<'_, AttachProviderSession>;
}

/// Failure to register a provider.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum AttachProviderRegistrationError {
    /// IDs are required for deterministic diagnostics and deregistration.
    #[error("attach provider id cannot be empty")]
    EmptyId,
    /// IDs must not have surrounding whitespace.
    #[error("attach provider id cannot contain surrounding whitespace: '{id}'")]
    InvalidId { id: String },
    /// A live provider already owns this ID.
    #[error("attach provider '{id}' is already registered")]
    DuplicateId { id: String },
}

/// Failure to resolve an attach target.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum AttachProviderResolutionError {
    /// No registered provider accepted the target.
    #[error("no attach provider accepts target '{target}'")]
    NoProvider { target: String },
    /// Multiple providers at the highest priority accepted the target.
    #[error("attach target '{target}' is ambiguous between providers: {providers:?}")]
    Ambiguous {
        target: String,
        providers: Vec<String>,
    },
}

#[derive(Debug, Default)]
struct RegistryState {
    providers: BTreeMap<String, Arc<dyn AttachProvider>>,
}

/// Thread-safe attach-provider registry.
#[derive(Debug, Default)]
pub struct AttachProviderRegistry {
    state: RwLock<RegistryState>,
}

impl AttachProviderRegistry {
    /// Create an empty registry.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a provider until the returned guard is dropped.
    ///
    /// # Errors
    ///
    /// Returns an error for invalid or duplicate provider IDs.
    ///
    /// # Panics
    ///
    /// Panics if the registry lock is poisoned.
    pub fn register(
        self: &Arc<Self>,
        provider: Arc<dyn AttachProvider>,
    ) -> Result<AttachProviderRegistration, AttachProviderRegistrationError> {
        let id = provider.id().to_string();
        if id.is_empty() {
            return Err(AttachProviderRegistrationError::EmptyId);
        }
        if id.trim() != id {
            return Err(AttachProviderRegistrationError::InvalidId { id });
        }
        let mut state = self
            .state
            .write()
            .expect("attach provider registry poisoned");
        if state.providers.contains_key(&id) {
            return Err(AttachProviderRegistrationError::DuplicateId { id });
        }
        state.providers.insert(id.clone(), provider);
        drop(state);
        Ok(AttachProviderRegistration {
            registry: Arc::downgrade(self),
            id: Some(id),
        })
    }

    /// Resolve a parsed target to exactly one highest-priority provider.
    ///
    /// # Errors
    ///
    /// Returns no-provider or same-priority ambiguity errors.
    ///
    /// # Panics
    ///
    /// Panics if the registry lock is poisoned.
    pub fn resolve(
        &self,
        target: &AttachTarget,
    ) -> Result<Arc<dyn AttachProvider>, AttachProviderResolutionError> {
        let mut matches = {
            let state = self
                .state
                .read()
                .expect("attach provider registry poisoned");
            state
                .providers
                .values()
                .filter(|provider| provider.supports(target))
                .cloned()
                .collect::<Vec<_>>()
        };
        if matches.is_empty() {
            return Err(AttachProviderResolutionError::NoProvider {
                target: target.raw().to_string(),
            });
        }
        matches.sort_by(|left, right| {
            right
                .priority()
                .cmp(&left.priority())
                .then_with(|| left.id().cmp(right.id()))
        });
        let priority = matches[0].priority();
        let winners = matches
            .iter()
            .take_while(|provider| provider.priority() == priority)
            .collect::<Vec<_>>();
        if winners.len() > 1 {
            return Err(AttachProviderResolutionError::Ambiguous {
                target: target.raw().to_string(),
                providers: winners
                    .iter()
                    .map(|provider| provider.id().to_string())
                    .collect(),
            });
        }
        Ok(Arc::clone(&matches[0]))
    }

    /// Return provider IDs in stable order.
    ///
    /// # Panics
    ///
    /// Panics if the registry lock is poisoned.
    #[must_use]
    pub fn provider_ids(&self) -> Vec<String> {
        self.state
            .read()
            .expect("attach provider registry poisoned")
            .providers
            .keys()
            .cloned()
            .collect()
    }
}

/// Registration lifetime guard.
#[derive(Debug)]
pub struct AttachProviderRegistration {
    registry: Weak<AttachProviderRegistry>,
    id: Option<String>,
}

impl AttachProviderRegistration {
    /// Permanently keep this registration for the process lifetime.
    pub fn forget(mut self) {
        let _ = self.id.take();
    }
}

impl Drop for AttachProviderRegistration {
    fn drop(&mut self) {
        let (Some(registry), Some(id)) = (self.registry.upgrade(), self.id.take()) else {
            return;
        };
        registry
            .state
            .write()
            .expect("attach provider registry poisoned")
            .providers
            .remove(&id);
    }
}

/// Process-wide attach-provider registry.
#[must_use]
pub fn global_attach_provider_registry() -> Arc<AttachProviderRegistry> {
    static REGISTRY: OnceLock<Arc<AttachProviderRegistry>> = OnceLock::new();
    Arc::clone(REGISTRY.get_or_init(|| Arc::new(AttachProviderRegistry::new())))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Debug)]
    struct TestResolvedTarget {
        provider_id: &'static str,
    }

    impl ResolvedAttachTarget for TestResolvedTarget {
        fn provider_id(&self) -> &str {
            self.provider_id
        }

        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    #[derive(Debug)]
    struct SchemeProvider {
        id: &'static str,
        scheme: Option<&'static str>,
        priority: i32,
    }

    impl AttachProvider for SchemeProvider {
        fn id(&self) -> &str {
            self.id
        }

        fn priority(&self) -> i32 {
            self.priority
        }

        fn supports(&self, target: &AttachTarget) -> bool {
            target.scheme() == self.scheme
        }

        fn resolve(
            &self,
            _target: &AttachTarget,
        ) -> Result<Arc<dyn ResolvedAttachTarget>, AttachProviderError> {
            Ok(Arc::new(TestResolvedTarget {
                provider_id: self.id,
            }))
        }

        fn open(
            &self,
            _resolved: Arc<dyn ResolvedAttachTarget>,
            _resume: Option<crate::AttachResumeState>,
            _context: AttachProviderOpenContext,
        ) -> AttachProviderFuture<'_, AttachProviderSession> {
            Box::pin(async move {
                Err(AttachProviderError::OpenFailed {
                    provider_id: self.id.to_string(),
                    reason: "test provider does not open clients".to_string(),
                })
            })
        }
    }

    #[test]
    fn target_parser_normalizes_valid_schemes_and_preserves_bare_targets() {
        let target = AttachTarget::parse("SYNTHETIC://workspace/main");
        assert_eq!(target.scheme(), Some("synthetic"));
        assert_eq!(target.reference(), "workspace/main");
        assert_eq!(target.raw(), "SYNTHETIC://workspace/main");

        let bare = AttachTarget::parse("main");
        assert_eq!(bare.scheme(), None);
        assert_eq!(bare.reference(), "main");

        let invalid = AttachTarget::parse("1bad://main");
        assert_eq!(invalid.scheme(), None);
        assert_eq!(invalid.reference(), "1bad://main");
    }

    #[test]
    fn resolves_one_matching_provider() {
        let registry = Arc::new(AttachProviderRegistry::new());
        let _registration = registry
            .register(Arc::new(SchemeProvider {
                id: "synthetic",
                scheme: Some("synthetic"),
                priority: 10,
            }))
            .expect("register provider");
        let provider = registry
            .resolve(&AttachTarget::parse("synthetic://main"))
            .expect("resolve provider");
        assert_eq!(provider.id(), "synthetic");
    }

    #[test]
    fn higher_priority_provider_wins_and_ties_are_rejected() {
        let registry = Arc::new(AttachProviderRegistry::new());
        let _low = registry
            .register(Arc::new(SchemeProvider {
                id: "low",
                scheme: Some("synthetic"),
                priority: 1,
            }))
            .unwrap();
        let high = registry
            .register(Arc::new(SchemeProvider {
                id: "high",
                scheme: Some("synthetic"),
                priority: 2,
            }))
            .unwrap();
        assert_eq!(
            registry
                .resolve(&AttachTarget::parse("synthetic://main"))
                .unwrap()
                .id(),
            "high"
        );
        drop(high);
        let _tie = registry
            .register(Arc::new(SchemeProvider {
                id: "tie",
                scheme: Some("synthetic"),
                priority: 1,
            }))
            .unwrap();
        assert!(matches!(
            registry.resolve(&AttachTarget::parse("synthetic://main")),
            Err(AttachProviderResolutionError::Ambiguous { providers, .. })
                if providers == ["low", "tie"]
        ));
    }

    #[test]
    fn duplicate_ids_are_rejected_and_drop_unregisters() {
        let registry = Arc::new(AttachProviderRegistry::new());
        let registration = registry
            .register(Arc::new(SchemeProvider {
                id: "provider",
                scheme: None,
                priority: 0,
            }))
            .unwrap();
        assert!(matches!(
            registry.register(Arc::new(SchemeProvider {
                id: "provider",
                scheme: Some("other"),
                priority: 0,
            })),
            Err(AttachProviderRegistrationError::DuplicateId { .. })
        ));
        drop(registration);
        assert!(registry.provider_ids().is_empty());
    }

    #[test]
    fn no_match_is_structured() {
        let registry = AttachProviderRegistry::new();
        assert!(matches!(
            registry.resolve(&AttachTarget::parse("unknown://main")),
            Err(AttachProviderResolutionError::NoProvider { target })
                if target == "unknown://main"
        ));
    }
}