sew-proto 0.11.6

Sew wire contracts: ids, addresses, errors, HTTP and gateway bodies, permissions, policies, audit.
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
//! Channels over mgmt: K2 creates channels in App-bound Spaces (`chat.createChannel`).
//!
//! - `POST /mgmt/v1/channels/create` ([`MgmtChannelCreateRequest`] →
//!   [`MgmtChannelCreateResponse`]): a text or voice channel in a Space bound to an App,
//!   made as the
//!   Space's owner through the client API's channel create (the same checks, events, change-log
//!   entries and audit rows, with the mgmt peer uid on them). `app_id` must name the Space's App
//!   (`409 conflict` `app_mismatch`); an unbound Space is `409 conflict` `space_unbound`.
//!   Idempotent on `(space_id, slug)`: a repeat answers the existing channel (`created: false`)
//!   with its current name and visibility (a different `name` or `private` changes nothing) and
//!   adds any listed member it lacks. A repeat naming the other `type` is `409 conflict`
//!   `channel_type_mismatch` ([`MgmtChannelTypeMismatchDetails`]).
//! - `members` (0–100, member ids or external ids) are added like `spaces/members/add` answers:
//!   `added`, `already`, `skipped` (member ids a Space ban keeps out) and
//!   `not_added` with a reason. A member must already be in the Space (an App's Space gets its
//!   members only through `spaces/members/add`).
//! - `POST /mgmt/v1/channels/bulk` ([`MgmtChannelBulkRequest`] → [`MgmtChannelBulkResponse`]):
//!   1–200 ops (`ensure`, `rename`, `archive`, `unarchive`) in a Space whose
//!   governing App is `app_id`, run as the Space's owner through the same functions as the
//!   single calls, each answered on its own ([`MgmtChannelOpResult`]). Since 0.10.0 the op
//!   `update` sets `members_can_leave` on an existing channel.
//! - Since 0.10.0, `POST /mgmt/v1/channels/{channel_id}/members/add` and
//!   `POST /mgmt/v1/channels/{channel_id}/members/remove` ([`MgmtChannelMemberRequest`] →
//!   [`MgmtChannelMemberResponse`]): one member in or out of one channel of an App-governed
//!   Space or the server-governed Space, named by external id, through the client add and
//!   remove as the Space's owner. Idempotent: `changed: false` when nothing changed.

use std::borrow::Cow;
use std::fmt;
use std::str::FromStr;

use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::addr::Slug;
use crate::api::channels::ChannelType;
use crate::error::{Validate, ValidationError, check_chars};
use crate::external_id::ExternalId;
use crate::id::{Id, parse_id_str};
use crate::limits::NAME_MAX_CHARS;

use super::spaces::{MgmtSpaceMemberRef, check_app_id};

/// Feature flag: `POST /mgmt/v1/channels/{channel_id}/members/add` and `…/members/remove`.
pub const FEATURE_CHANNEL_MEMBER_ADD_REMOVE: &str = "channel_member_add_remove";

/// Most members in one mgmt channel create.
pub const CHANNEL_MEMBERS_ADD_MAX: usize = 100;

/// A member named by its member id (decimal) or its external id (contains `:`).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum MgmtMemberRef {
    /// A member id.
    Member(Id),
    /// An external id.
    External(ExternalId),
}

impl FromStr for MgmtMemberRef {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.contains(':') {
            return s
                .parse()
                .map(MgmtMemberRef::External)
                .map_err(|e: crate::external_id::ExternalIdError| e.to_string());
        }
        parse_id_str(s)
            .map(MgmtMemberRef::Member)
            .ok_or_else(|| format!("{s:?} is neither a member id nor an external id"))
    }
}

impl From<ExternalId> for MgmtMemberRef {
    fn from(e: ExternalId) -> Self {
        MgmtMemberRef::External(e)
    }
}

impl fmt::Display for MgmtMemberRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MgmtMemberRef::Member(id) => fmt::Display::fmt(id, f),
            MgmtMemberRef::External(e) => fmt::Display::fmt(e, f),
        }
    }
}

impl Serialize for MgmtMemberRef {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for MgmtMemberRef {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = Cow::<'de, str>::deserialize(deserializer)?;
        s.parse().map_err(serde::de::Error::custom)
    }
}

impl JsonSchema for MgmtMemberRef {
    fn inline_schema() -> bool {
        true
    }

    fn schema_name() -> Cow<'static, str> {
        "MgmtMemberRef".into()
    }

    fn json_schema(_: &mut SchemaGenerator) -> Schema {
        json_schema!({
            "type": "string",
            "maxLength": 128,
            "description": "A member id (decimal string) or an external id (k2:principal:<uuid>, k2:workspace:<uuid>, k2:connect:<uuid>, k2:owner or local:<handle>)."
        })
    }
}

/// Body of `POST /mgmt/v1/channels/create`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct MgmtChannelCreateRequest {
    /// The Space; it must be bound to an App, or be the server-governed Space.
    pub space_id: Id,
    /// The Space's App; absent for the server-governed Space (governance `server`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub app_id: Option<String>,
    /// The slug, unique in the Space (the client rules). With `space_id`, the idempotency key.
    pub slug: Slug,
    /// The name, 1–100 characters. Used at create only.
    pub name: String,
    /// A private channel (its members are exactly the owner and `members`). Used at create
    /// only.
    pub private: bool,
    /// 0–100 distinct members (member ids or external ids) to add.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub members: Vec<MgmtMemberRef>,
    /// `text` (absent = text) or `voice`; `announcement` and the DM types are refused
    /// (`400 validation_failed`, field `type`). Part of the idempotency check: an existing slug
    /// of the other type is `409 conflict` `channel_type_mismatch`.
    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<ChannelType>,
    /// Voice only: at most this many people in the call, 0–99, 0 = no per-channel limit;
    /// absent = 0. On a text channel it is `400 validation_failed` (field `user_limit`). Used at
    /// create only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user_limit: Option<u8>,
    /// Since 0.10.0: the members of this channel may leave it although its Space is governed
    /// (`Channel.members_can_leave`). Absent = `false`. Used at create only; the bulk op
    /// `update` changes it later.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub members_can_leave: bool,
}

impl MgmtChannelCreateRequest {
    /// A `MgmtChannelCreateRequest` with its required fields: every flag `false`, every
    /// list empty and every optional field unset.
    pub fn new(space_id: Id, slug: Slug, name: impl Into<String>) -> Self {
        MgmtChannelCreateRequest {
            space_id,
            app_id: None,
            slug,
            name: name.into(),
            private: false,
            members: Vec::new(),
            kind: None,
            user_limit: None,
            members_can_leave: false,
        }
    }
}

impl MgmtChannelCreateRequest {
    /// The channel type asked for: `type`, absent = text.
    pub fn channel_type(&self) -> ChannelType {
        self.kind.unwrap_or(ChannelType::Text)
    }
}

impl Validate for MgmtChannelCreateRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        if let Some(a) = &self.app_id {
            check_app_id("app_id", a)?;
        }
        let kind = self.channel_type();
        if !matches!(kind, ChannelType::Text | ChannelType::Voice) {
            return Err(ValidationError::invalid(
                "type",
                "type must be text or voice",
            ));
        }
        crate::voice::check_user_limit(self.user_limit)?;
        if self.user_limit.is_some() && kind != ChannelType::Voice {
            return Err(ValidationError::invalid(
                "user_limit",
                "user_limit is for voice channels only",
            ));
        }
        check_chars("name", &self.name, 1, NAME_MAX_CHARS)?;
        if self.members.len() > CHANNEL_MEMBERS_ADD_MAX {
            return Err(ValidationError::invalid(
                "members",
                format!("at most {CHANNEL_MEMBERS_ADD_MAX} members"),
            ));
        }
        for (i, m) in self.members.iter().enumerate() {
            if self.members[..i].contains(m) {
                return Err(ValidationError::invalid(
                    format!("members.{i}"),
                    "listed twice",
                ));
            }
        }
        Ok(())
    }
}

unit_enum! {
    /// Why a listed member was not added to the channel (a ban is not a reason here: a
    /// banned member is in `skipped`).
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum MgmtChannelNotAddedReason {
        /// No member has this id or external id (provision first).
        NotProvisioned = "not_provisioned",
        /// The member is deactivated.
        Deactivated = "deactivated",
        /// An assistant never joins a channel (it reads through its person).
        Assistant = "assistant",
        /// A guest outside the Space (an App's Space takes no guests through channel adds).
        Guest = "guest",
        /// Not a member of the Space: add it with `spaces/members/add` first.
        NotSpaceMember = "not_space_member",
    }
}

/// A listed member the create did not add, and why.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct MgmtChannelNotAdded {
    /// The member as the request named it.
    pub member: MgmtMemberRef,
    /// Why.
    pub reason: MgmtChannelNotAddedReason,
}

/// Response of `POST /mgmt/v1/channels/create`, each member list in request order.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct MgmtChannelCreateResponse {
    /// The channel.
    pub channel_id: Id,
    /// Its Space.
    pub space_id: Id,
    /// Its slug.
    pub slug: Slug,
    /// Its current name (a repeat never changes it).
    pub name: String,
    /// Whether it is private (current; a repeat never changes it).
    pub private: bool,
    /// Its type, `text` or `voice` (additive; absent from an older Sew = text).
    #[serde(rename = "type", default = "text_type")]
    pub kind: ChannelType,
    /// Voice only (additive): its current per-channel limit, 0 = none. Absent for text.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user_limit: Option<u8>,
    /// Since 0.10.0: its current `members_can_leave` (a repeat never changes it). Absent from
    /// an older Sew = `false`.
    #[serde(default)]
    pub members_can_leave: bool,
    /// Whether this call created it.
    pub created: bool,
    /// Listed members this call added. The owner, who is always a member, is never here; when
    /// listed it is in `already`.
    pub added: Vec<MgmtSpaceMemberRef>,
    /// Listed members that were in the channel already.
    pub already: Vec<MgmtSpaceMemberRef>,
    /// Listed members a Space ban keeps out (member ids, the shape of `members/add`). Always
    /// present.
    #[serde(default)]
    pub skipped: Vec<Id>,
    /// Listed members that cannot join, with the reason.
    pub not_added: Vec<MgmtChannelNotAdded>,
}

impl MgmtChannelCreateResponse {
    /// A `MgmtChannelCreateResponse` with its required fields: every flag `false`, every
    /// list empty, the other fields at their serde defaults and every optional field unset.
    pub fn new(channel_id: Id, space_id: Id, slug: Slug, name: impl Into<String>) -> Self {
        MgmtChannelCreateResponse {
            channel_id,
            space_id,
            slug,
            name: name.into(),
            private: false,
            kind: text_type(),
            user_limit: None,
            members_can_leave: false,
            created: false,
            added: Vec::new(),
            already: Vec::new(),
            skipped: Vec::new(),
            not_added: Vec::new(),
        }
    }
}

fn text_type() -> ChannelType {
    ChannelType::Text
}

/// Details of `409 conflict` `channel_type_mismatch` on `POST /mgmt/v1/channels/create`:
/// the slug is held by a channel of another type.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct MgmtChannelTypeMismatchDetails {
    /// `channel_type_mismatch`.
    pub reason: String,
    /// `type`.
    pub field: String,
    /// The existing channel's type.
    pub existing_type: ChannelType,
}

/// Most ops in one `POST /mgmt/v1/channels/bulk`.
pub const CHANNEL_BULK_OPS_MAX: usize = 200;

/// One op of `POST /mgmt/v1/channels/bulk`, tagged by `op`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
pub enum MgmtChannelOp {
    /// Create: ensure, never update. A repeat of an existing slug answers the channel
    /// (`created: false`) and changes neither its name nor its visibility; a slug held by the
    /// other type fails the op with `409 conflict` `channel_type_mismatch`.
    Ensure {
        /// The slug, unique in the Space.
        slug: Slug,
        /// The name, 1–100 characters. Used at create only.
        name: String,
        /// A private channel (its members are the owner until the sync adds people). Used at
        /// create only.
        private: bool,
        /// `text` (absent = text) or `voice`.
        #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
        kind: Option<ChannelType>,
        /// Voice only: at most this many people in the call, 0–99 (0 = no limit). Used at
        /// create only.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        user_limit: Option<u8>,
        /// Since 0.10.0: `Channel.members_can_leave` (absent = `false`). Used at create only;
        /// `update` changes it.
        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
        members_can_leave: bool,
    },
    /// Since 0.10.0: changes settings of a channel of the Space. An absent field is kept; at
    /// least one must be present.
    Update {
        /// The channel.
        channel_id: Id,
        /// `Channel.members_can_leave`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        members_can_leave: Option<bool>,
    },
    /// A new name (1–100 characters) for a channel of the Space.
    Rename {
        /// The channel.
        channel_id: Id,
        /// The new name.
        name: String,
    },
    /// Archives a channel of the Space (a no-op when it is archived).
    Archive {
        /// The channel.
        channel_id: Id,
    },
    /// Unarchives a channel of the Space (a no-op when it is not archived).
    Unarchive {
        /// The channel.
        channel_id: Id,
    },
}

impl MgmtChannelOp {
    /// The op's kind.
    pub fn kind(&self) -> MgmtChannelOpKind {
        match self {
            MgmtChannelOp::Ensure { .. } => MgmtChannelOpKind::Ensure,
            MgmtChannelOp::Update { .. } => MgmtChannelOpKind::Update,
            MgmtChannelOp::Rename { .. } => MgmtChannelOpKind::Rename,
            MgmtChannelOp::Archive { .. } => MgmtChannelOpKind::Archive,
            MgmtChannelOp::Unarchive { .. } => MgmtChannelOpKind::Unarchive,
        }
    }

    fn validate_at(&self, i: usize) -> Result<(), ValidationError> {
        let at = |e: ValidationError| ValidationError {
            field: format!("ops.{i}.{}", e.field),
            ..e
        };
        match self {
            MgmtChannelOp::Ensure {
                name,
                kind,
                user_limit,
                ..
            } => {
                let kind = kind.unwrap_or(ChannelType::Text);
                if !matches!(kind, ChannelType::Text | ChannelType::Voice) {
                    return Err(at(ValidationError::invalid(
                        "type",
                        "type must be text or voice",
                    )));
                }
                crate::voice::check_user_limit(*user_limit).map_err(at)?;
                if user_limit.is_some() && kind != ChannelType::Voice {
                    return Err(at(ValidationError::invalid(
                        "user_limit",
                        "user_limit is for voice channels only",
                    )));
                }
                check_chars("name", name, 1, NAME_MAX_CHARS).map_err(at)
            }
            MgmtChannelOp::Rename { name, .. } => {
                check_chars("name", name, 1, NAME_MAX_CHARS).map_err(at)
            }
            MgmtChannelOp::Update {
                members_can_leave, ..
            } => {
                if members_can_leave.is_none() {
                    return Err(at(ValidationError::invalid(
                        "members_can_leave",
                        "update needs at least one field",
                    )));
                }
                Ok(())
            }
            MgmtChannelOp::Archive { .. } | MgmtChannelOp::Unarchive { .. } => Ok(()),
        }
    }
}

unit_enum! {
    /// The kind of a bulk channel op.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
    pub enum MgmtChannelOpKind {
        /// Create (ensure, never update).
        Ensure = "ensure",
        /// A new name.
        Rename = "rename",
        /// Archive.
        Archive = "archive",
        /// Unarchive.
        Unarchive = "unarchive",
        /// Since 0.10.0: change settings (`members_can_leave`).
        Update = "update",
    }
}

/// Body of `POST /mgmt/v1/channels/bulk`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct MgmtChannelBulkRequest {
    /// The Space; `app_id` must be its governing App (absent: the server-governed Space).
    pub space_id: Id,
    /// The Space's governing App; absent for the server-governed Space (governance
    /// `server`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub app_id: Option<String>,
    /// 1–200 ops, run in order, each on its own; one failing op fails only itself.
    pub ops: Vec<MgmtChannelOp>,
}

impl Validate for MgmtChannelBulkRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        if let Some(a) = &self.app_id {
            check_app_id("app_id", a)?;
        }
        if self.ops.is_empty() || self.ops.len() > CHANNEL_BULK_OPS_MAX {
            return Err(ValidationError::invalid(
                "ops",
                format!("1–{CHANNEL_BULK_OPS_MAX} ops"),
            ));
        }
        for (i, op) in self.ops.iter().enumerate() {
            op.validate_at(i)?;
        }
        Ok(())
    }
}

/// One op's answer in `POST /mgmt/v1/channels/bulk`, in request order.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct MgmtChannelOpResult {
    /// The op's kind.
    pub op: MgmtChannelOpKind,
    /// Whether the op succeeded (a no-op repeat succeeds).
    pub ok: bool,
    /// The channel: the ensured one, or the one the op named. Absent when an `ensure` failed
    /// before a channel was found.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub channel_id: Option<Id>,
    /// `ensure` that succeeded: whether this op created the channel.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub created: Option<bool>,
    /// `rename`, `archive`, `unarchive` and `update` that succeeded: whether the op changed the
    /// channel
    /// (`false`: it already had that name or state, and nothing was written).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub changed: Option<bool>,
    /// A failed op: the error the single call would have answered (its code, hint and
    /// details, such as `channel_type_mismatch` or `channel_not_found`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<crate::error::ApiError>,
}

/// Body of `POST /mgmt/v1/channels/{channel_id}/members/add` and
/// `POST /mgmt/v1/channels/{channel_id}/members/remove` (since 0.10.0).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct MgmtChannelMemberRequest {
    /// The channel's Space's governing App; absent for the server-governed Space (the same
    /// rule as `channels/create`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub app_id: Option<String>,
    /// The member.
    pub external_id: ExternalId,
}

impl Validate for MgmtChannelMemberRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        if let Some(a) = &self.app_id {
            check_app_id("app_id", a)?;
        }
        Ok(())
    }
}

/// Response of `POST /mgmt/v1/channels/{channel_id}/members/add` and `…/members/remove`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct MgmtChannelMemberResponse {
    /// The channel.
    pub channel_id: Id,
    /// Its Space.
    pub space_id: Id,
    /// The member, as named.
    pub external_id: ExternalId,
    /// The member's id.
    pub member_id: Id,
    /// Whether this call changed the membership: `false` when the member was already in the
    /// channel (add) or not in it (remove).
    pub changed: bool,
}

/// Response of `POST /mgmt/v1/channels/bulk`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct MgmtChannelBulkResponse {
    /// The Space.
    pub space_id: Id,
    /// One answer per op, in request order.
    pub results: Vec<MgmtChannelOpResult>,
}

#[cfg(test)]
// The package has no clippy.toml (Sew's allows unwrap in tests); the module says it itself.
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;

    #[test]
    fn member_ref_parses_both_forms() {
        let id: MgmtMemberRef = "48831765147549697".parse().unwrap();
        assert!(matches!(id, MgmtMemberRef::Member(_)));
        let ext: MgmtMemberRef = "k2:owner".parse().unwrap();
        assert_eq!(ext, MgmtMemberRef::External(ExternalId::K2Owner));
        for bad in ["", "abc", "k2:nope", "-1"] {
            assert!(bad.parse::<MgmtMemberRef>().is_err(), "{bad}");
        }
        assert_eq!(
            serde_json::to_string(&ext).unwrap(),
            "\"k2:owner\"".to_owned()
        );
    }
}