holochain_conductor_api/
admin_interface.rs

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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
use std::collections::BTreeSet;

use holo_hash::*;
use holochain_types::prelude::*;
use holochain_types::websocket::AllowedOrigins;
use holochain_zome_types::cell::CellId;
use kitsune_p2p_types::agent_info::AgentInfoSigned;

use crate::{AppInfo, FullStateDump, RevokeAgentKeyPayload, StorageInfo};

/// Represents the available conductor functions to call over an admin interface.
///
/// Enum variants follow a general convention of `verb_noun` as opposed to
/// the `noun_verb` of responses.
///
/// # Errors
///
/// Returns an [`AdminResponse::Error`] with a reason why the request failed.
// Expects a serialized object with any contents of the enum on a key `data`
// and the enum variant on a key `type`, e.g.
// `{ type: 'enable_app', data: { installed_app_id: 'test_app' } }`
#[derive(Debug, serde::Serialize, serde::Deserialize, SerializedBytes)]
#[serde(rename_all = "snake_case", tag = "type", content = "data")]
pub enum AdminRequest {
    /// Set up and register one or more new admin interfaces
    /// as specified by a list of configurations.
    ///
    /// # Returns
    ///
    /// [`AdminResponse::AdminInterfacesAdded`]
    AddAdminInterfaces(Vec<crate::config::AdminInterfaceConfig>),

    /// Register a DNA for later app installation.
    ///
    /// Stores the given DNA into the Holochain DNA database and returns the hash of it.
    ///
    /// # Returns
    ///
    /// [`AdminResponse::DnaRegistered`]
    RegisterDna(Box<RegisterDnaPayload>),

    /// Get the definition of a DNA.
    ///
    /// # Returns
    ///
    /// [`AdminResponse::DnaDefinitionReturned`]
    GetDnaDefinition(Box<DnaHash>),

    /// Update coordinator zomes for an already installed DNA.
    ///
    /// Replaces any installed coordinator zomes with the same zome name.
    /// If the zome name doesn't exist then the coordinator zome is appended
    /// to the current list of coordinator zomes.
    ///
    /// # Returns
    ///
    /// [`AdminResponse::CoordinatorsUpdated`]
    UpdateCoordinators(Box<UpdateCoordinatorsPayload>),

    /// Install an app using an [`AppBundle`].
    ///
    /// Triggers genesis to be run on all Cells and to be stored.
    /// An app is intended for use by
    /// one and only one Agent and for that reason it takes an `AgentPubKey` and
    /// installs all the DNAs with that `AgentPubKey`, forming new cells.
    /// See [`InstallAppPayload`] for full details on the configuration.
    ///
    /// Note that the new app will not be enabled automatically after installation
    /// and can be enabled by calling [`EnableApp`].
    ///
    /// # Returns
    ///
    /// [`AdminResponse::AppInstalled`]
    ///
    /// [`EnableApp`]: AdminRequest::EnableApp
    InstallApp(Box<InstallAppPayload>),

    /// Uninstalls the app specified by argument `installed_app_id` from the conductor.
    ///
    /// The app will be removed from the list of installed apps, and any cells
    /// which were referenced only by this app will be disabled and removed, clearing up
    /// any persisted data.
    /// Cells which are still referenced by other installed apps will not be removed.
    ///
    /// # Returns
    ///
    /// [`AdminResponse::AppUninstalled`]
    UninstallApp {
        /// The app ID to uninstall
        installed_app_id: InstalledAppId,

        /// If anything would prevent this app from being uninstalled, such as the existence
        /// of protected dependency to one of its cells, this flag will force the uninstallation.
        /// This will generally lead to bad outcomes, and should not be used unless you're
        /// aware of the consequences.
        #[serde(default)]
        force: bool,
    },

    /// List the hashes of all installed DNAs.
    ///
    /// # Returns
    ///
    /// [`AdminResponse::DnasListed`]
    ListDnas,

    /// Generate a new [`AgentPubKey`].
    ///
    /// # Returns
    ///
    /// [`AdminResponse::AgentPubKeyGenerated`]
    GenerateAgentPubKey,

    /// Revoke an agent key for an app.
    ///
    /// When an agent key is revoked, it becomes invalid and can no longer be used to author
    /// actions for that app. The key is revoked in the Deepkey service if installed and deleted on
    /// the source chains of all cells of the app, making them read-only. Cloning a cell of this app will fail.
    ///
    /// If the key could not be deleted from all cells, this call can be re-attempted to delete the key from the remaining cells.
    ///
    /// # Returns
    ///
    /// [`AdminResponse::AgentKeyRevoked`]
    RevokeAgentKey(Box<RevokeAgentKeyPayload>),

    /// List the IDs of all live cells currently running in the conductor.
    ///
    /// # Returns
    ///
    /// [`AdminResponse::CellIdsListed`]
    ListCellIds,

    /// List the apps and their information that are installed in the conductor.
    ///
    /// If `status_filter` is `Some(_)`, it will return only the apps with the specified status.
    ///
    /// # Returns
    ///
    /// [`AdminResponse::AppsListed`]
    ListApps {
        /// An optional status to filter the list of apps by
        status_filter: Option<AppStatusFilter>,
    },

    /// Changes the specified app from a disabled to an enabled state in the conductor.
    ///
    /// It is likely to want to call this after calling [`AdminRequest::InstallApp`], since a freshly
    /// installed app is not enabled automatically. Once the app is enabled,
    /// zomes can be immediately called and it will also be loaded and enabled automatically on any reboot of the conductor.
    ///
    /// # Returns
    ///
    /// [`AdminResponse::AppEnabled`]
    EnableApp {
        /// The app ID to enable
        installed_app_id: InstalledAppId,
    },

    /// Changes the specified app from an enabled to a disabled state in the conductor.
    ///
    /// When an app is disabled, zome calls can no longer be made, and the app will not be
    /// loaded on a reboot of the conductor.
    ///
    /// # Returns
    ///
    /// [`AdminResponse::AppDisabled`]
    DisableApp {
        /// The app ID to disable
        installed_app_id: InstalledAppId,
    },

    /// Open up a new websocket for processing [`AppRequest`]s. Any active app will be
    /// callable via the attached app interface.
    ///
    /// **NB:** App interfaces are persisted when shutting down the conductor and are
    /// restored when restarting the conductor. Unused app interfaces are _not_ cleaned
    /// up. It is therefore recommended to reuse existing interfaces. They can be queried
    /// with the call [`AdminRequest::ListAppInterfaces`].
    ///
    /// # Returns
    ///
    /// [`AdminResponse::AppInterfaceAttached`]
    ///
    /// # Arguments
    ///
    /// Optionally a `port` parameter can be passed to this request. If it is `None`,
    /// a free port is chosen by the conductor.
    ///
    /// An `allowed_origins` parameter to control which origins are allowed to connect
    /// to the app interface.
    ///
    /// [`AppRequest`]: super::AppRequest
    AttachAppInterface {
        /// Optional port number
        port: Option<u16>,

        /// Allowed origins for this app interface.
        ///
        /// This should be one of:
        /// - A comma separated list of origins - `http://localhost:3000,http://localhost:3001`,
        /// - A single origin - `http://localhost:3000`,
        /// - Any origin - `*`
        ///
        /// Connections from any origin which is not permitted by this config will be rejected.
        allowed_origins: AllowedOrigins,

        /// Optionally bind this app interface to a specific installed app.
        ///
        /// If this is `None` then the interface can be used to establish a connection for any app.
        ///
        /// If this is `Some` then the interface will only accept connections for the specified app.
        /// Those connections will only be able to make calls to and receive signals from that app.
        installed_app_id: Option<InstalledAppId>,
    },

    /// List all the app interfaces currently attached with [`AttachAppInterface`].
    ///
    /// # Returns
    ///
    /// [`AdminResponse::AppInterfacesListed`], a list of websocket ports that can
    /// process [`AppRequest`]s.
    ///
    /// [`AttachAppInterface`]: AdminRequest::AttachAppInterface
    /// [`AppRequest`]: super::AppRequest
    ListAppInterfaces,

    /// Dump the state of the cell specified by argument `cell_id`,
    /// including its chain, as a string containing JSON.
    ///
    /// # Returns
    ///
    /// [`AdminResponse::StateDumped`]
    DumpState {
        /// The cell ID for which to dump state
        cell_id: Box<CellId>,
    },

    /// Dump the state of the conductor, including the in-memory representation
    /// and the persisted ConductorState, as JSON.
    ///
    /// # Returns
    ///
    /// [`AdminResponse::ConductorStateDumped`]
    DumpConductorState,

    /// Dump the full state of the Cell specified by argument `cell_id`,
    /// including its chain and DHT shard, as a string containing JSON.
    ///
    /// **Warning**: this API call is subject to change, and will not be available to hApps.
    /// This is meant to be used by introspection tooling.
    ///
    /// Note that the response to this call can be very big, as it's requesting for
    /// the full database of the cell.
    ///
    /// Also note that while DHT ops about private entries will be returned (like `StoreRecord`),
    /// the entry in itself will be missing, as it's not actually stored publicly in the DHT shard.
    ///
    /// # Returns
    ///
    /// [`AdminResponse::FullStateDumped`]
    DumpFullState {
        /// The cell ID for which to dump the state
        cell_id: Box<CellId>,
        /// The last seen DhtOp RowId, returned in the full dump state.
        /// Only DhtOps with RowId greater than the cursor will be returned.
        dht_ops_cursor: Option<u64>,
    },

    /// Dump the network metrics tracked by kitsune.
    ///
    /// # Returns
    ///
    /// [`AdminResponse::NetworkMetricsDumped`]
    DumpNetworkMetrics {
        /// If set, limits the metrics dumped to a single DNA hash space.
        dna_hash: Option<DnaHash>,
    },

    /// Dump raw json network statistics from the backend networking lib.
    DumpNetworkStats,

    /// Add a list of agents to this conductor's peer store.
    ///
    /// This is a way of shortcutting peer discovery and is useful for testing.
    ///
    /// It is also helpful if you know other
    /// agents on the network and they can send you
    /// their agent info.
    ///
    /// # Returns
    ///
    /// [`AdminResponse::AgentInfoAdded`]
    AddAgentInfo {
        /// list of signed agent info to add to peer store
        agent_infos: Vec<AgentInfoSigned>,
    },

    /// Request the [`AgentInfoSigned`] stored in this conductor's
    /// peer store.
    ///
    /// You can:
    /// - Get all agent info by leaving `cell_id` to `None`.
    /// - Get a specific agent info by setting the `cell_id`.
    ///
    /// This is how you can send your agent info to another agent.
    /// It is also useful for testing across networks.
    ///
    /// # Returns
    ///
    /// [`AdminResponse::AgentInfo`]
    AgentInfo {
        /// Optionally choose the agent info of a specific cell.
        cell_id: Option<CellId>,
    },

    /// "Graft" [`Record`]s onto the source chain of the specified [`CellId`].
    ///
    /// The records must form a valid chain segment (ascending sequence numbers,
    /// and valid `prev_action` references). If the first record contains a `prev_action`
    /// which matches the existing records, then the new records will be "grafted" onto
    /// the existing chain at that point, and any other records following that point which do
    /// not match the new records will be removed.
    ///
    /// If this operation is called when there are no forks, the final state will also have
    /// no forks.
    ///
    /// **BEWARE** that this may result in the deletion of data! Any existing records which form
    /// a fork with respect to the new records will be deleted.
    ///
    /// All records must be authored and signed by the same agent.
    /// The [`DnaFile`] (but not necessarily the cell) must already be installed
    /// on this conductor.
    ///
    /// Care is needed when using this command as it can result in
    /// an invalid chain.
    /// Additionally, if conflicting source chain records are
    /// inserted on different nodes, then the chain will be forked.
    ///
    /// If an invalid or forked chain is inserted
    /// and then pushed to the DHT, it can't be undone.
    ///
    /// Note that the cell does not need to exist to run this command.
    /// It is possible to insert records into a source chain before
    /// the cell is created. This can be used to restore from backup.
    ///
    /// If the cell is installed, it is best to call [`AdminRequest::DisableApp`]
    /// before running this command, as otherwise the chain head may move.
    /// If `truncate` is true, the chain head is not checked and any new
    /// records will be lost.
    ///
    /// # Returns
    ///
    /// [`AdminResponse::RecordsGrafted`]
    GraftRecords {
        /// The cell that the records are being inserted into.
        cell_id: CellId,
        /// If this is `true`, then the records will be validated before insertion.
        /// This is much slower but is useful for verifying the chain is valid.
        ///
        /// If this is `false`, then records will be inserted as is.
        /// This could lead to an invalid chain.
        validate: bool,
        /// The records to be inserted into the source chain.
        records: Vec<Record>,
    },

    /// Request capability grant for making zome calls.
    ///
    /// # Returns
    ///
    /// [`AdminResponse::ZomeCallCapabilityGranted`]
    GrantZomeCallCapability(Box<GrantZomeCallCapabilityPayload>),

    /// Delete a clone cell that was previously disabled.
    ///
    /// # Returns
    ///
    /// [`AdminResponse::CloneCellDeleted`]
    DeleteCloneCell(Box<DeleteCloneCellPayload>),

    /// Info about storage used by apps
    StorageInfo,

    /// Connecting to an app over an app websocket requires an authentication token. This endpoint
    /// is used to issue those tokens for use by app clients.
    ///
    /// # Returns
    ///
    /// [`AdminResponse::AppAuthenticationTokenIssued`]
    IssueAppAuthenticationToken(IssueAppAuthenticationTokenPayload),

    /// Revoke an issued app authentication token.
    ///
    /// # Returns
    ///
    /// [`AdminResponse::AppAuthenticationTokenRevoked`]
    RevokeAppAuthenticationToken(AppAuthenticationToken),

    /// Find installed cells which use a DNA that's forward-compatible with the given DNA hash.
    /// Namely, this finds cells with DNAs whose manifest lists the given DNA hash in its `lineage` field.
    GetCompatibleCells(DnaHash),
}

/// Represents the possible responses to an [`AdminRequest`]
/// and follows a general convention of `noun_verb` as opposed to
/// the `verb_noun` of `AdminRequest`.
///
/// Will serialize as an object with any contents of the enum on a key `data`
/// and the enum variant on a key `type`, e.g.
/// `{ type: 'app_interface_attached', data: { port: 4000 } }`
#[derive(Debug, serde::Serialize, serde::Deserialize, SerializedBytes)]
#[cfg_attr(test, derive(Clone))]
#[serde(rename_all = "snake_case", tag = "type", content = "data")]
pub enum AdminResponse {
    /// Can occur in response to any [`AdminRequest`].
    ///
    /// There has been an error during the handling of the request.
    Error(ExternalApiWireError),

    /// The successful response to an [`AdminRequest::RegisterDna`]
    DnaRegistered(DnaHash),

    /// The successful response to an [`AdminRequest::GetDnaDefinition`]
    DnaDefinitionReturned(DnaDef),

    /// The successful response to an [`AdminRequest::UpdateCoordinators`]
    CoordinatorsUpdated,

    /// The successful response to an [`AdminRequest::InstallApp`].
    ///
    /// The resulting [`AppInfo`] contains the app ID,
    /// the [`RoleName`]s and, most usefully, [`CellInfo`](crate::CellInfo)s
    /// of the newly installed DNAs.
    AppInstalled(AppInfo),

    /// The successful response to an [`AdminRequest::UninstallApp`].
    ///
    /// It means the app was uninstalled successfully.
    AppUninstalled,

    /// The successful response to an [`AdminRequest::AddAdminInterfaces`].
    ///
    /// It means the `AdminInterface`s have successfully been added.
    AdminInterfacesAdded,

    /// The successful response to an [`AdminRequest::GenerateAgentPubKey`].
    ///
    /// Contains a new [`AgentPubKey`] generated by the keystore.
    AgentPubKeyGenerated(AgentPubKey),

    /// The successful response to an [`AdminRequest::RevokeAgentKey`].
    ///
    /// Contains a list of errors of the cells where deletion was unsuccessful.
    ///
    /// If the key could not be deleted from all cells, the call
    /// [`AdminRequest::RevokeAgentKey`] can be re-attempted to delete the key from the remaining cells.
    AgentKeyRevoked(Vec<(CellId, String)>),

    /// The successful response to an [`AdminRequest::ListDnas`].
    ///
    /// Contains a list of the hashes of all installed DNAs.
    DnasListed(Vec<DnaHash>),

    /// The successful response to an [`AdminRequest::ListCellIds`].
    ///
    /// Contains a list of all the cell IDs in the conductor.
    CellIdsListed(Vec<CellId>),

    /// The successful response to an [`AdminRequest::ListApps`].
    ///
    /// Contains a list of the `InstalledAppInfo` of the installed apps in the conductor.
    AppsListed(Vec<AppInfo>),

    /// The successful response to an [`AdminRequest::AttachAppInterface`].
    ///
    /// Contains the port number of the attached app interface.
    AppInterfaceAttached {
        /// Networking port of the new `AppInterfaceApi`
        port: u16,
    },

    /// The list of attached app interfaces.
    AppInterfacesListed(Vec<AppInterfaceInfo>),

    /// The successful response to an [`AdminRequest::EnableApp`].
    ///
    /// It means the app was enabled successfully. If it was possible to
    /// put the app in a running state, it will be running, otherwise it will
    /// be paused.
    ///
    /// Contains the app info and list of errors for cells that could not be enabled.
    AppEnabled {
        app: AppInfo,
        errors: Vec<(CellId, String)>,
    },

    /// The successful response to an [`AdminRequest::DisableApp`].
    ///
    /// It means the app was disabled successfully.
    AppDisabled,

    /// The successful response to an [`AdminRequest::DumpState`].
    ///
    /// The result contains a string of serialized JSON data which can be deserialized to access the
    /// full state dump and inspect the source chain.
    StateDumped(String),

    /// The successful response to an [`AdminRequest::DumpFullState`].
    ///
    /// The result contains a string of serialized JSON data which can be deserialized to access the
    /// full state dump and inspect the source chain.
    ///
    /// Note that this result can be very big, as it's requesting the full database of the cell.
    FullStateDumped(FullStateDump),

    /// The successful response to an [`AdminRequest::DumpConductorState`].
    ///
    /// Simply a JSON serialized snapshot of `Conductor` and `ConductorState` from the `holochain` crate.
    ConductorStateDumped(String),

    /// The successful result of a call to [`AdminRequest::DumpNetworkMetrics`].
    ///
    /// The string is a JSON blob of the metrics results.
    NetworkMetricsDumped(String),

    /// The successful result of a call to [`AdminRequest::DumpNetworkStats`].
    ///
    /// The string is a raw JSON blob returned directly from the backend
    /// networking library.
    NetworkStatsDumped(String),

    /// The successful response to an [`AdminRequest::AddAgentInfo`].
    ///
    /// This means the agent info was successfully added to the peer store.
    AgentInfoAdded,

    /// The successful response to an [`AdminRequest::AgentInfo`].
    ///
    /// This is all the agent info that was found for the request.
    AgentInfo(Vec<AgentInfoSigned>),

    /// The successful response to an [`AdminRequest::GraftRecords`].
    RecordsGrafted,

    /// The successful response to an [`AdminRequest::GrantZomeCallCapability`].
    ZomeCallCapabilityGranted,

    /// The successful response to an [`AdminRequest::DeleteCloneCell`].
    CloneCellDeleted,

    /// The successful response to an [`AdminRequest::StorageInfo`].
    StorageInfo(StorageInfo),

    /// The successful response to an [`AdminRequest::IssueAppAuthenticationToken`].
    AppAuthenticationTokenIssued(AppAuthenticationTokenIssued),

    /// The successful response to an [`AdminRequest::RevokeAppAuthenticationToken`].
    AppAuthenticationTokenRevoked,

    /// The successful response to an [`AdminRequest::GetCompatibleCells`].
    CompatibleCells(CompatibleCells),
}

pub type CompatibleCells = BTreeSet<(InstalledAppId, BTreeSet<CellId>)>;

/// Error type that goes over the websocket wire.
/// This intends to be application developer facing
/// so it should be readable and relevant
#[derive(Debug, serde::Serialize, serde::Deserialize, SerializedBytes, Clone)]
#[serde(rename_all = "snake_case", tag = "type", content = "data")]
pub enum ExternalApiWireError {
    // TODO: B-01506 Constrain these errors so they are relevant to
    // application developers and what they would need
    // to react to using code (i.e. not just print)
    /// Any internal error
    InternalError(String),
    /// The input to the API failed to deseralize.
    Deserialization(String),
    /// The DNA path provided was invalid.
    DnaReadError(String),
    /// There was an error in the ribosome.
    RibosomeError(String),
    /// Error activating app.
    ActivateApp(String),
    /// The zome call is unauthorized.
    ZomeCallUnauthorized(String),
    /// A countersigning session has failed.
    CountersigningSessionError(String),
}

impl ExternalApiWireError {
    /// Convert the error from the display.
    pub fn internal<T: std::fmt::Display>(e: T) -> Self {
        // Display format is used because
        // this version intended for users.
        ExternalApiWireError::InternalError(e.to_string())
    }
}

#[derive(Debug, serde::Serialize, serde::Deserialize, SerializedBytes, Clone)]
/// Filter for [`AdminRequest::ListApps`].
///
/// App Status is a combination of two pieces of independent state:
/// - Enabled/Disabled, which is a designation set by the user via the conductor interface.
/// - Running/Stopped, which is a fact about the reality of the app in the course of its operation.
pub enum AppStatusFilter {
    /// Filter on apps which are Enabled, which can include both Running and Paused apps.
    Enabled,
    /// Filter only on apps which are Disabled.
    Disabled,
    /// Filter on apps which are currently Running (meaning they are also Enabled).
    Running,
    /// Filter on apps which are Stopped, i.e. not Running.
    /// This includes apps in the Disabled status, as well as the Paused status.
    Stopped,
    /// Filter only on Paused apps.
    Paused,
}

/// Informational response for listing app interfaces.
#[derive(Debug, serde::Serialize, serde::Deserialize, SerializedBytes, Clone)]
pub struct AppInterfaceInfo {
    /// The port that the app interface is listening on.
    pub port: u16,

    /// The allowed origins for this app interface.
    pub allowed_origins: AllowedOrigins,

    /// The optional association with a specific installed app.
    pub installed_app_id: Option<InstalledAppId>,
}

/// Request payload for [AdminRequest::IssueAppAuthenticationToken].
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct IssueAppAuthenticationTokenPayload {
    /// The app ID to issue a connection token for.
    pub installed_app_id: InstalledAppId,

    /// The number of seconds that the token should be valid for. After this number of seconds, the
    /// token will no longer be accepted by the conductor.
    ///
    /// This is 30s by default which is reasonably high but with [IssueAppAuthenticationTokenPayload::single_use]
    /// set to `true`, the token will be invalidated after the first use anyway.
    ///
    /// Set this to 0 to create a token that does not expire.
    #[serde(default = "default_expiry_seconds")]
    pub expiry_seconds: u64,

    /// Whether the token should be single-use. This is `true` by default and will cause the token
    /// to be invalidated after the first use, irrespective of connection success.
    ///
    /// Set this to `false` to allow the token to be used multiple times.
    #[serde(default = "default_single_use")]
    pub single_use: bool,
}

fn default_expiry_seconds() -> u64 {
    30
}

fn default_single_use() -> bool {
    true
}

impl IssueAppAuthenticationTokenPayload {
    /// Create a new payload for issuing a connection token for the specified app.
    ///
    /// The token will be valid for 30 seconds and for a single use.
    pub fn for_installed_app_id(installed_app_id: InstalledAppId) -> Self {
        installed_app_id.into()
    }

    /// Set the expiry time for the token.
    pub fn expiry_seconds(mut self, expiry_seconds: u64) -> Self {
        self.expiry_seconds = expiry_seconds;
        self
    }

    /// Set whether the token should be single-use.
    pub fn single_use(mut self, single_use: bool) -> Self {
        self.single_use = single_use;
        self
    }
}

impl From<InstalledAppId> for IssueAppAuthenticationTokenPayload {
    fn from(installed_app_id: InstalledAppId) -> Self {
        // Defaults here should match the serde defaults in the struct definition
        Self {
            installed_app_id,
            expiry_seconds: 30,
            single_use: true,
        }
    }
}

/// A token issued by the conductor that can be used to authenticate a connection to an app interface.
pub type AppAuthenticationToken = Vec<u8>;

/// Response payload for [AdminResponse::AppAuthenticationTokenIssued].
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct AppAuthenticationTokenIssued {
    /// A token issued by the conductor that can be used to authenticate a connection to an app interface.
    /// This is expected to be passed from the caller of the admin interface to the client that will
    /// use the app interface. It should be treated as secret and kept from other parties.
    pub token: AppAuthenticationToken,

    /// The timestamp after which Holochain will consider the token invalid. This should be
    /// considered informational only and the client should not rely on the token being accepted
    /// following a client-side check that the token has not yet expired.
    ///
    /// If the token was created with [IssueAppAuthenticationTokenPayload::expiry_seconds] set to `0`
    /// then this field will be `None`.
    // TODO Kitsune type used in the conductor interface
    pub expires_at: Option<Timestamp>,
}

#[cfg(test)]
mod tests {
    use serde::Deserialize;

    use crate::{AdminRequest, AdminResponse, ExternalApiWireError};

    #[test]
    fn admin_request_serialization() {
        use rmp_serde::Deserializer;

        // make sure requests are serialized as expected
        let request = AdminRequest::DisableApp {
            installed_app_id: "some_id".to_string(),
        };
        let serialized_request = holochain_serialized_bytes::encode(&request).unwrap();
        assert_eq!(
            serialized_request,
            vec![
                130, 164, 116, 121, 112, 101, 171, 100, 105, 115, 97, 98, 108, 101, 95, 97, 112,
                112, 164, 100, 97, 116, 97, 129, 176, 105, 110, 115, 116, 97, 108, 108, 101, 100,
                95, 97, 112, 112, 95, 105, 100, 167, 115, 111, 109, 101, 95, 105, 100
            ]
        );

        let json_expected = r#"{"type":"disable_app","data":{"installed_app_id":"some_id"}}"#;
        let mut deserializer = Deserializer::new(&*serialized_request);
        let json_value: serde_json::Value = Deserialize::deserialize(&mut deserializer).unwrap();
        let json_actual = serde_json::to_string(&json_value).unwrap();

        assert_eq!(json_actual, json_expected);

        // make sure responses are serialized as expected
        let response = AdminResponse::Error(ExternalApiWireError::RibosomeError(
            "error_text".to_string(),
        ));
        let serialized_response = holochain_serialized_bytes::encode(&response).unwrap();
        assert_eq!(
            serialized_response,
            vec![
                130, 164, 116, 121, 112, 101, 165, 101, 114, 114, 111, 114, 164, 100, 97, 116, 97,
                130, 164, 116, 121, 112, 101, 174, 114, 105, 98, 111, 115, 111, 109, 101, 95, 101,
                114, 114, 111, 114, 164, 100, 97, 116, 97, 170, 101, 114, 114, 111, 114, 95, 116,
                101, 120, 116
            ]
        );

        let json_expected =
            r#"{"type":"error","data":{"type":"ribosome_error","data":"error_text"}}"#;
        let mut deserializer = Deserializer::new(&*serialized_response);
        let json_value: serde_json::Value = Deserialize::deserialize(&mut deserializer).unwrap();
        let json_actual = serde_json::to_string(&json_value).unwrap();

        assert_eq!(json_actual, json_expected);
    }
}