ignition-core 1.1.0

Core library for ign: config, profiles, gateway client, actions, error taxonomy
Documentation
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
//! Session actions (02-03, HLTH-08): merged list + terminate — serde
//! models OUT, no printing (ARCHITECTURE.md layering: the Phase-6 TUI
//! rides this same layer).
//!
//! Stable data shape for agents: `sessions` always serializes ALL THREE
//! family keys (`designers`, `perspective`, `vision`) — a `--type`
//! filter leaves the excluded keys present as EMPTY arrays, and only
//! the requested family's endpoint is CALLED (no wasted round-trips).

use serde::Serialize;

use crate::client::GatewayApi;
use crate::client::query::ListQuery;
use crate::client::sessions::{DesignerInfo, PerspectiveSession, VisionClient};
use crate::error::CoreError;

/// Which session family a filter or termination targets. Serialized
/// kebab-case (`"designer"` / `"perspective"` / `"vision"`) — the same
/// tokens `--type` accepts on the CLI.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum SessionType {
    /// Designer sessions (terminate = prune).
    Designer,
    /// Perspective browser sessions (terminate carries the message).
    Perspective,
    /// Vision clients (terminate = close).
    Vision,
}

impl SessionType {
    /// The kebab-case token (CLI/display form).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Designer => "designer",
            Self::Perspective => "perspective",
            Self::Vision => "vision",
        }
    }
}

impl std::fmt::Display for SessionType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// `ign sessions` output model — all three families, always present.
#[derive(Debug, Serialize)]
pub struct SessionsResult {
    /// Active Designer sessions (empty when filtered out).
    pub designers: Vec<DesignerInfo>,
    /// Active Perspective sessions (empty when filtered out).
    pub perspective: Vec<PerspectiveSession>,
    /// Active Vision clients (empty when filtered out).
    pub vision: Vec<VisionClient>,
}

/// `ign sessions terminate` output model.
#[derive(Debug, Serialize)]
pub struct TerminateResult {
    /// The family that was targeted (kebab-case in JSON).
    pub kind: SessionType,
    /// The terminated session/client id.
    pub id: String,
}

/// Merge the session families (or just the requested one). Filtered-out
/// families are present-but-empty in the result and their endpoints are
/// NEVER called.
pub async fn sessions(
    api: &dyn GatewayApi,
    type_filter: Option<SessionType>,
) -> Result<SessionsResult, CoreError> {
    let query = ListQuery::default();
    let (designers, perspective, vision) = match type_filter {
        None => (
            api.designers(&query).await?.items,
            api.perspective_sessions(&query).await?.items,
            api.vision_clients(&query).await?.items,
        ),
        Some(SessionType::Designer) => (api.designers(&query).await?.items, Vec::new(), Vec::new()),
        Some(SessionType::Perspective) => (
            Vec::new(),
            api.perspective_sessions(&query).await?.items,
            Vec::new(),
        ),
        Some(SessionType::Vision) => (
            Vec::new(),
            Vec::new(),
            api.vision_clients(&query).await?.items,
        ),
    };
    Ok(SessionsResult {
        designers,
        perspective,
        vision,
    })
}

/// Terminate one session, mapping the family to its endpoint (designer →
/// prune, perspective → terminate with the optional message, vision →
/// terminate). Confirmation guarding belongs to the CALLER (the CLI
/// refuses without `--yes` before any API construction) — the action is
/// the obedient arm.
pub async fn terminate_session(
    api: &dyn GatewayApi,
    kind: SessionType,
    id: &str,
    message: Option<&str>,
) -> Result<TerminateResult, CoreError> {
    match kind {
        SessionType::Designer => api.prune_designer(id).await?,
        SessionType::Perspective => api.terminate_perspective_session(id, message).await?,
        SessionType::Vision => api.terminate_vision_client(id).await?,
    }
    Ok(TerminateResult {
        kind,
        id: id.to_string(),
    })
}

#[cfg(test)]
mod tests {
    use super::{SessionType, TerminateResult, sessions, terminate_session};
    use crate::client::GatewayApi;
    use crate::client::query::{ListEnvelope, ListMetadata};
    use crate::client::sessions::{DesignerInfo, PerspectiveSession, VisionClient};
    use crate::error::CoreError;

    use std::sync::Mutex;

    /// A recording double: counts every list call per family and every
    /// terminate call (kind + id + message), serving one item per list.
    #[derive(Default)]
    struct SessionsRig {
        list_calls: Mutex<Vec<&'static str>>,
        terminates: Mutex<Vec<(&'static str, String, Option<String>)>>,
    }

    fn designer(id: &str) -> DesignerInfo {
        DesignerInfo {
            id: id.into(),
            address: "192.168.1.50:52526".into(),
            user: "admin".into(),
            project: "MyProject".into(),
            memory: serde_json::json!({"used": 1}),
            uptime: 600000,
            lastcomm: 1787346747022,
            timeout: 3600000,
            timezone: "America/New_York".into(),
            extra: Default::default(),
        }
    }

    fn perspective(id: &str) -> PerspectiveSession {
        PerspectiveSession {
            id: id.into(),
            username: "admin".into(),
            authorized: true,
            project: "MyProject".into(),
            client_address: "10.0.0.5".into(),
            last_comm: 1787346747022,
            active_pages: 1,
            user_agent: "Mozilla/5.0".into(),
            extra: Default::default(),
        }
    }

    fn vision(id: &str) -> VisionClient {
        VisionClient {
            id: id.into(),
            address: "10.0.0.9:443".into(),
            user: "operator".into(),
            project: "PlantFloor".into(),
            memory: serde_json::json!({"used": 1}),
            uptime: 120000,
            lastcomm: 1787346747022,
            timeout: 3600000,
            timezone: "UTC".into(),
            tag_count: 1523,
            extra: Default::default(),
        }
    }

    fn page<T>(items: Vec<T>) -> ListEnvelope<T> {
        ListEnvelope {
            items,
            metadata: ListMetadata {
                total: 1,
                matching: 1,
                limit: -1,
                offset: 0,
            },
        }
    }

    #[async_trait::async_trait]
    impl GatewayApi for SessionsRig {
        async fn bundle_generate(
            &self,
        ) -> Result<crate::client::diagnostics::BundleStatusWire, CoreError> {
            unreachable!("not part of this action")
        }
        async fn bundle_status(
            &self,
        ) -> Result<crate::client::diagnostics::BundleStatusWire, CoreError> {
            unreachable!("not part of this action")
        }
        async fn bundle_download(
            &self,
            _out: &std::path::Path,
        ) -> Result<crate::client::projects::ExportMeta, CoreError> {
            unreachable!("not part of this action")
        }
        async fn tag_provider_list(
            &self,
            _query: &crate::client::query::ListQuery,
        ) -> Result<
            crate::client::query::ListEnvelope<crate::client::tags::TagProviderRecord>,
            CoreError,
        > {
            unreachable!("not part of this action")
        }
        async fn tag_provider_find(
            &self,
            _name: &str,
        ) -> Result<crate::client::tags::TagProviderRecord, CoreError> {
            unreachable!("not part of this action")
        }
        async fn tag_provider_create(
            &self,
            _body: &[crate::client::tags::TagProviderCreate],
        ) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn tag_provider_delete(
            &self,
            _name: &str,
            _signature: &str,
        ) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn trial_status_wire(&self) -> Result<crate::client::trial::TrialWire, CoreError> {
            unreachable!("not part of this action")
        }
        async fn banners(&self) -> Result<crate::client::trial::BannerSet, CoreError> {
            unreachable!("not part of this action")
        }
        async fn trial_reset_wire(&self) -> Result<crate::client::trial::TrialWire, CoreError> {
            unreachable!("not part of this action")
        }
        async fn backup_download(
            &self,
            _out: &std::path::Path,
            _backup_type: crate::client::backup::BackupType,
        ) -> Result<crate::client::projects::ExportMeta, CoreError> {
            unreachable!("not part of this action")
        }
        async fn backup_restore(&self, _gwbk: &std::path::Path) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_task_history(
            &self,
            _limit: Option<u32>,
            _search: Option<&str>,
        ) -> Result<crate::client::query::ListEnvelope<crate::client::eam::EamHistoryItem>, CoreError>
        {
            unreachable!("not part of this action")
        }
        async fn eam_task_definitions(
            &self,
        ) -> Result<crate::client::query::ListEnvelope<crate::client::eam::EamTaskRecord>, CoreError>
        {
            unreachable!("not part of this action")
        }
        async fn eam_task_find(
            &self,
            _name: &str,
        ) -> Result<crate::client::eam::EamTaskRecord, CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_task_create(&self, _definition: &serde_json::Value) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_task_force(&self, _owner: &str, _name: &str) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_task_suspend(&self, _name: &str) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_task_resume(&self, _name: &str) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_task_cancel(&self, _name: &str) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_tasks_scheduled(
            &self,
            _running: bool,
        ) -> Result<Vec<crate::client::eam::EamScheduledTask>, CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_task_modify(
            &self,
            _definition: &serde_json::Value,
        ) -> Result<Option<crate::client::eam::ModifyOutcome>, CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_task_delete(
            &self,
            _name: &str,
            _signature: &str,
            _confirm: bool,
        ) -> Result<crate::client::eam::DeleteOutcome, CoreError> {
            unreachable!("not part of this action")
        }
        async fn api_call(
            &self,
            _call: &crate::client::apicall::ApiCallRequest,
        ) -> Result<crate::client::apicall::ApiCallData, CoreError> {
            unreachable!("not part of this action")
        }
        async fn license_status(
            &self,
        ) -> Result<crate::client::license::LicenseStatusWire, CoreError> {
            unreachable!("not part of this action")
        }
        async fn redundancy_status(
            &self,
        ) -> Result<crate::client::redundancy::RedundancyStatusWire, CoreError> {
            unreachable!("not part of this action")
        }
        async fn gan_status(&self) -> Result<crate::client::gan::GanStatusWire, CoreError> {
            unreachable!("not part of this action")
        }
        async fn gateway_info(&self) -> Result<crate::client::version::GatewayInfo, CoreError> {
            unreachable!("not part of this action")
        }
        async fn overview(&self) -> Result<crate::client::status::Overview, CoreError> {
            unreachable!("not part of this action")
        }
        async fn status_ping(&self) -> Result<crate::client::status::StatusPing, CoreError> {
            unreachable!("not part of this action")
        }
        async fn modules(
            &self,
            _quarantined: bool,
            _query: &crate::client::query::ListQuery,
        ) -> Result<ListEnvelope<crate::client::status::ModuleInfo>, CoreError> {
            unreachable!("not part of this action")
        }
        async fn metrics_current(
            &self,
        ) -> Result<crate::client::metrics::CurrentGauges, CoreError> {
            unreachable!("not part of this action")
        }
        async fn metrics_historic(
            &self,
        ) -> Result<crate::client::metrics::PerformanceCharts, CoreError> {
            unreachable!("not part of this action")
        }
        async fn metrics_threads(&self) -> Result<crate::client::metrics::ThreadCounts, CoreError> {
            unreachable!("not part of this action")
        }
        async fn designers(
            &self,
            _query: &crate::client::query::ListQuery,
        ) -> Result<ListEnvelope<DesignerInfo>, CoreError> {
            self.list_calls.lock().unwrap().push("designers");
            Ok(page(vec![designer("d-1")]))
        }
        async fn perspective_sessions(
            &self,
            _query: &crate::client::query::ListQuery,
        ) -> Result<ListEnvelope<PerspectiveSession>, CoreError> {
            self.list_calls.lock().unwrap().push("perspective");
            Ok(page(vec![perspective("psess-1")]))
        }
        async fn vision_clients(
            &self,
            _query: &crate::client::query::ListQuery,
        ) -> Result<ListEnvelope<VisionClient>, CoreError> {
            self.list_calls.lock().unwrap().push("vision");
            Ok(page(vec![vision("v-1")]))
        }
        async fn terminate_perspective_session(
            &self,
            id: &str,
            message: Option<&str>,
        ) -> Result<(), CoreError> {
            self.terminates.lock().unwrap().push((
                "perspective",
                id.into(),
                message.map(str::to_string),
            ));
            Ok(())
        }
        async fn terminate_vision_client(&self, id: &str) -> Result<(), CoreError> {
            self.terminates
                .lock()
                .unwrap()
                .push(("vision", id.into(), None));
            Ok(())
        }
        async fn prune_designer(&self, id: &str) -> Result<(), CoreError> {
            self.terminates
                .lock()
                .unwrap()
                .push(("designer", id.into(), None));
            Ok(())
        }
        async fn database_connections(
            &self,
        ) -> Result<ListEnvelope<crate::client::connections::GatewayConnection>, CoreError>
        {
            unreachable!("not part of this action")
        }
        async fn opc_connections(
            &self,
        ) -> Result<ListEnvelope<crate::client::connections::GatewayConnection>, CoreError>
        {
            unreachable!("not part of this action")
        }

        async fn logs(
            &self,
            _filter: &crate::client::logs::LogQuery,
        ) -> Result<ListEnvelope<crate::client::logs::LogEntry>, CoreError> {
            unreachable!("not part of this double's actions")
        }
        async fn logs_download(&self) -> Result<crate::client::logs::LogDownload, CoreError> {
            unreachable!("not part of this double's actions")
        }
        async fn loggers(
            &self,
            _query: &crate::client::query::ListQuery,
        ) -> Result<ListEnvelope<crate::client::logs::LoggerInfo>, CoreError> {
            unreachable!("not part of this double's actions")
        }
        async fn set_logger_level(&self, _logger: &str, _level: &str) -> Result<(), CoreError> {
            unreachable!("not part of this double's actions")
        }
        async fn reset_logger_levels(&self) -> Result<(), CoreError> {
            unreachable!("not part of this double's actions")
        }
        async fn restart(&self) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn scan_projects(&self) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn security_properties(
            &self,
        ) -> Result<crate::client::restart::SecurityProperties, CoreError> {
            unreachable!("not part of this action")
        }
        async fn webdev_route_status(&self, _route: &str) -> Result<u16, CoreError> {
            unreachable!("not part of this action")
        }
        async fn webdev_route_call(
            &self,
            _project: &str,
            _route: &str,
            _body: &serde_json::Value,
            _extra_headers: &[(&str, &str)],
        ) -> Result<serde_json::Value, CoreError> {
            unreachable!("not part of this action")
        }
        async fn webdev_route_probe(
            &self,
            _project: &str,
            _route: &str,
            _extra_headers: &[(&str, &str)],
        ) -> Result<crate::client::webdev::RouteProbe, CoreError> {
            unreachable!("not part of this action")
        }
        async fn projects(
            &self,
            _query: &crate::client::query::ListQuery,
        ) -> Result<
            crate::client::query::ListEnvelope<crate::client::projects::ProjectRecord>,
            CoreError,
        > {
            unreachable!("not part of this action")
        }
        async fn project_find(
            &self,
            _name: &str,
        ) -> Result<crate::client::projects::ProjectRecord, CoreError> {
            unreachable!("not part of this action")
        }
        async fn project_create(
            &self,
            _body: &crate::client::projects::ProjectCreate,
        ) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn project_copy(&self, _from: &str, _to: &str) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn project_rename(&self, _name: &str, _new_name: &str) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn project_modify(
            &self,
            _name: &str,
            _body: &crate::client::projects::ProjectModify,
        ) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn project_delete(&self, _name: &str) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn project_export_to_file(
            &self,
            _name: &str,
            _out: &std::path::Path,
        ) -> Result<crate::client::projects::ExportMeta, CoreError> {
            unreachable!("not part of this action")
        }
        async fn project_import(
            &self,
            _name: &str,
            _zip: Vec<u8>,
            _overwrite: bool,
        ) -> Result<crate::client::projects::ImportOutcome, CoreError> {
            unreachable!("not part of this action")
        }
    }

    /// Unfiltered: all three families called and present. Filtered: ONLY
    /// the requested family is called; the others stay present-but-empty
    /// (the stable agent shape).
    #[tokio::test]
    async fn sessions_filter_calls_only_the_requested_family() {
        let rig = SessionsRig::default();
        let merged = sessions(&rig, None).await.expect("merged list");
        assert_eq!(merged.designers.len(), 1);
        assert_eq!(merged.perspective.len(), 1);
        assert_eq!(merged.vision.len(), 1);
        assert_eq!(
            *rig.list_calls.lock().unwrap(),
            vec!["designers", "perspective", "vision"]
        );

        let rig = SessionsRig::default();
        let filtered = sessions(&rig, Some(SessionType::Perspective))
            .await
            .expect("filtered list");
        assert!(filtered.designers.is_empty(), "excluded key stays present");
        assert_eq!(filtered.perspective.len(), 1);
        assert!(filtered.vision.is_empty());
        assert_eq!(
            *rig.list_calls.lock().unwrap(),
            vec!["perspective"],
            "no round-trips for excluded families"
        );

        // The JSON shape keeps all three keys (agent contract).
        let json = serde_json::to_value(&filtered).expect("serialize");
        let mut keys: Vec<&str> = json
            .as_object()
            .unwrap()
            .keys()
            .map(String::as_str)
            .collect();
        keys.sort_unstable();
        assert_eq!(keys, ["designers", "perspective", "vision"]);
    }

    /// Termination maps kind → endpoint exactly: designer → prune,
    /// perspective → terminate (message rides along), vision →
    /// terminate.
    #[tokio::test]
    async fn terminate_maps_each_kind_to_its_endpoint() {
        let rig = SessionsRig::default();
        let result: TerminateResult =
            terminate_session(&rig, SessionType::Perspective, "psess-1", Some("bye"))
                .await
                .expect("perspective terminates");
        assert_eq!(result.kind, SessionType::Perspective);
        assert_eq!(result.id, "psess-1");
        assert_eq!(
            serde_json::to_value(&result).unwrap()["kind"],
            "perspective",
            "kind serializes kebab-case"
        );

        terminate_session(&rig, SessionType::Designer, "d-1", Some("ignored"))
            .await
            .expect("designer prunes (message not applicable)");
        terminate_session(&rig, SessionType::Vision, "v-1", None)
            .await
            .expect("vision terminates");
        assert_eq!(
            *rig.terminates.lock().unwrap(),
            vec![
                ("perspective", "psess-1".into(), Some("bye".into())),
                ("designer", "d-1".into(), None),
                ("vision", "v-1".into(), None),
            ]
        );
    }
}