Skip to main content

sew_proto/
error.rs

1//! Error envelope and codes.
2
3use std::fmt;
4
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7use serde_json::{Map, Value};
8
9use crate::perms::Perms;
10use crate::policy::PolicyKey;
11
12unit_enum! {
13    /// A stable machine error code. `lower_snake`; the HTTP status comes from [`Code::status`].
14    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
15    pub enum Code {
16        /// 400: the request is malformed.
17        BadRequest = "bad_request",
18        /// 400: a field failed validation; `details.field` names it.
19        ValidationFailed = "validation_failed",
20        /// 401: no or unknown credentials.
21        Unauthenticated = "unauthenticated",
22        /// 401: the session expired.
23        SessionExpired = "session_expired",
24        /// 403: a permission bit is missing.
25        MissingPermission = "missing_permission",
26        /// 403: an org policy forbids this.
27        PolicyDenied = "policy_denied",
28        /// 403: a valid pass for a principal with no Sew account.
29        NotProvisioned = "not_provisioned",
30        /// 403: act-as targeted a person; only agents can be acted as.
31        ActAsPersonForbidden = "act_as_person_forbidden",
32        /// 403: the command is off on a K2-provided install.
33        ProviderIsK2 = "provider_is_k2",
34        /// 403: a quota or count limit is reached.
35        QuotaExceeded = "quota_exceeded",
36        /// 404: missing, or hidden from the caller (masked).
37        NotFound = "not_found",
38        /// 405: only GET reads and POST mutations exist.
39        MethodNotAllowed = "method_not_allowed",
40        /// 409: conflicts with current state.
41        Conflict = "conflict",
42        /// 409: an `Idempotency-Key` was reused with a different body.
43        IdempotencyConflict = "idempotency_conflict",
44        /// 410: the cursor is behind the change-log floor; `details.floor` says where.
45        ResyncRequired = "resync_required",
46        /// 413: the body or a field is too large.
47        TooLarge = "too_large",
48        /// 422: valid request, but the target's state forbids it.
49        InvalidState = "invalid_state",
50        /// 429: rate limited; `details.retry_after_ms` says when to retry.
51        RateLimited = "rate_limited",
52        /// 500: a server bug.
53        Internal = "internal",
54        /// 503: temporarily unavailable.
55        Unavailable = "unavailable",
56        /// 416: the byte range is outside the file; `Content-Range: bytes */<size>`.
57        RangeNotSatisfiable = "range_not_satisfiable",
58        /// 507: the server's file storage is below its free-space floor.
59        StorageFull = "storage_full",
60        /// 410: the meeting has ended or was cancelled (also a voice join in its
61        /// channel).
62        MeetingEnded = "meeting_ended",
63        /// 425: too early: the meeting opens at `details.opens_at` (also a voice join
64        /// before `starts_at` − 15 min).
65        TooEarly = "too_early",
66        /// 404: a meeting link that is unknown, has a wrong secret, was revoked or rotated, or
67        /// whose meeting ended or was cancelled (one body for all four).
68        LinkInvalid = "link_invalid",
69        /// 423: the meeting is locked.
70        MeetingLocked = "meeting_locked",
71        /// 429: the meeting's lobby or room is full (`max_waiting`, `max_guests_inside`;
72        /// nothing was written).
73        LobbyFull = "lobby_full",
74        /// 403: this join nonce (or member) was turned away twice within 10 minutes and may
75        /// not knock on this meeting for an hour.
76        KnockBlocked = "knock_blocked",
77        /// 410: the feed's cursor is behind the pruned part of the log (the person
78        /// notification feed); `details.oldest_seq` says where to resume.
79        CursorExpired = "cursor_expired",
80    }
81}
82
83impl Code {
84    /// The HTTP status for this code. `Unknown` maps to 500.
85    pub const fn status(self) -> u16 {
86        match self {
87            Code::BadRequest | Code::ValidationFailed => 400,
88            Code::Unauthenticated | Code::SessionExpired => 401,
89            Code::MissingPermission
90            | Code::PolicyDenied
91            | Code::NotProvisioned
92            | Code::ActAsPersonForbidden
93            | Code::ProviderIsK2
94            | Code::QuotaExceeded
95            | Code::KnockBlocked => 403,
96            Code::NotFound | Code::LinkInvalid => 404,
97            Code::MethodNotAllowed => 405,
98            Code::Conflict | Code::IdempotencyConflict => 409,
99            Code::ResyncRequired | Code::MeetingEnded | Code::CursorExpired => 410,
100            Code::TooLarge => 413,
101            Code::RangeNotSatisfiable => 416,
102            Code::InvalidState => 422,
103            Code::MeetingLocked => 423,
104            Code::TooEarly => 425,
105            Code::RateLimited | Code::LobbyFull => 429,
106            Code::Internal | Code::Unknown => 500,
107            Code::Unavailable => 503,
108            Code::StorageFull => 507,
109        }
110    }
111}
112
113/// Every error response body: `{"ok": false, "error": {code, hint, details}}`.
114#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
115pub struct ErrorBody {
116    /// Always `false`.
117    pub ok: bool,
118    /// The error.
119    pub error: ApiError,
120}
121
122impl ErrorBody {
123    /// Wraps an error.
124    pub fn new(error: ApiError) -> Self {
125        ErrorBody { ok: false, error }
126    }
127}
128
129impl From<ApiError> for ErrorBody {
130    fn from(error: ApiError) -> Self {
131        ErrorBody::new(error)
132    }
133}
134
135/// A structured error: a stable code, a human hint, and typed details.
136#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
137pub struct ApiError {
138    /// The stable machine code.
139    pub code: Code,
140    /// For humans; may change between releases.
141    pub hint: String,
142    /// Code-specific details, such as `field`, `retry_after_ms`, `floor` or `reason`.
143    #[serde(default)]
144    pub details: Map<String, Value>,
145}
146
147impl ApiError {
148    /// An error with empty details.
149    pub fn new(code: Code, hint: impl Into<String>) -> Self {
150        ApiError {
151            code,
152            hint: hint.into(),
153            details: Map::new(),
154        }
155    }
156
157    /// Merges a details struct into `details`. A value that does not serialize to a JSON object
158    /// is stored under `"value"`.
159    pub fn with_details(mut self, details: impl Serialize) -> Self {
160        match serde_json::to_value(details) {
161            Ok(Value::Object(map)) => self.details.extend(map),
162            Ok(Value::Null) => {}
163            Ok(other) => {
164                self.details.insert("value".to_owned(), other);
165            }
166            Err(e) => {
167                self.details
168                    .insert("details_error".to_owned(), Value::String(e.to_string()));
169            }
170        }
171        self
172    }
173
174    /// The HTTP status.
175    pub fn status(&self) -> u16 {
176        self.code.status()
177    }
178}
179
180impl fmt::Display for ApiError {
181    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182        write!(f, "{} ({}): {}", self.code, self.code.status(), self.hint)
183    }
184}
185
186impl std::error::Error for ApiError {}
187
188/// Details for `validation_failed` (and `too_large` on a field): the field that failed.
189#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
190pub struct ValidationDetails {
191    /// The failing field, dotted for nested fields (for example `reference.kind`).
192    pub field: String,
193}
194
195/// Details for `rate_limited`.
196#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
197pub struct RetryAfterDetails {
198    /// Milliseconds to wait before retrying.
199    pub retry_after_ms: u64,
200    /// Which limit refused, for limits other than the plain rate buckets (`slow_mode`).
201    #[serde(default, skip_serializing_if = "Option::is_none")]
202    pub reason: Option<String>,
203}
204
205/// `details.reason` of a `429 rate_limited` from a channel's slow mode.
206pub const RATE_REASON_SLOW_MODE: &str = "slow_mode";
207
208/// `details.reason` of the `409 conflict` a role reorder answers when its list is not the
209/// space's current role set.
210pub const CONFLICT_REASON_STALE_ROLE_LIST: &str = "stale_role_list";
211
212/// Details of an error that names a reason: mgmt and act-as refusals such as
213/// `409 conflict {reason: "username_taken", field: "username"}`. The reasons are listed in
214/// `sew_proto::mgmt::reasons`.
215#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
216pub struct ReasonDetails {
217    /// Why, as a stable `lower_snake` string.
218    pub reason: String,
219    /// The field or header the reason is about.
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub field: Option<String>,
222}
223
224impl ReasonDetails {
225    /// Details with a reason only.
226    pub fn new(reason: &str) -> Self {
227        ReasonDetails {
228            reason: reason.to_owned(),
229            field: None,
230        }
231    }
232
233    /// Details with a reason and a field.
234    pub fn with_field(reason: &str, field: &str) -> Self {
235        ReasonDetails {
236            reason: reason.to_owned(),
237            field: Some(field.to_owned()),
238        }
239    }
240}
241
242unit_enum! {
243    /// Why a change-log reader must start over (`details.reason` of `410 resync_required`).
244    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
245    pub enum ResyncReason {
246        /// `since` is below the floor: entries were trimmed.
247        BehindFloor = "behind_floor",
248        /// `since` is above the head: a restore, or another install.
249        AheadOfHead = "ahead_of_head",
250        /// The entries were not contiguous (must never happen).
251        Gap = "gap",
252    }
253}
254
255/// Details for `resync_required`.
256#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
257pub struct ResyncRequiredDetails {
258    /// The change-log floor; catch up from a fresh snapshot instead.
259    pub floor: u64,
260    /// The log head at the read (K2 resets its deliveries cursor here; additive).
261    #[serde(default, skip_serializing_if = "Option::is_none")]
262    pub head: Option<u64>,
263    /// `behind_floor`, `ahead_of_head` or `gap` (additive).
264    #[serde(default, skip_serializing_if = "Option::is_none")]
265    pub reason: Option<ResyncReason>,
266    /// The install's `sync_epoch` (additive).
267    #[serde(default, skip_serializing_if = "Option::is_none")]
268    pub sync_epoch: Option<String>,
269}
270
271impl ResyncRequiredDetails {
272    /// Details with only the floor.
273    pub fn new(floor: u64) -> Self {
274        ResyncRequiredDetails {
275            floor,
276            head: None,
277            reason: None,
278            sync_epoch: None,
279        }
280    }
281}
282
283unit_enum! {
284    /// `details.reason` of a `403 missing_permission` from the permission engine.
285    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
286    pub enum PermissionReason {
287        /// A permission bit is missing; `details.missing` lists it.
288        MissingPermission = "missing_permission",
289        /// The change touches bits the actor does not hold; `details.missing` lists them.
290        UnheldBits = "unheld_bits",
291        /// The target is at or above the actor on the role ladder.
292        Hierarchy = "hierarchy",
293        /// The space owner cannot be the target.
294        OwnerImmune = "owner_immune",
295        /// Only the space owner may do this.
296        OwnerOnly = "owner_only",
297        /// Guests cannot do or receive this.
298        GuestLimit = "guest_limit",
299        /// A meeting link guest cannot do this (every route off the link-guest
300        /// allowlist, before the handler).
301        LinkGuestLimit = "link_guest_limit",
302        /// Agents cannot do or receive this.
303        AgentLimit = "agent_limit",
304        /// Needs an install role (owner, admin) or the compliance flag.
305        InstallRole = "install_role",
306        /// Only the author may do this (edits, edit history).
307        NotAuthor = "not_author",
308        /// Only the person an assistant posted for may do this (on-behalf approval).
309        NotOnBehalfPerson = "not_on_behalf_person",
310        /// The person's own session is needed: act-as cannot do this.
311        OwnSessionRequired = "own_session_required",
312        /// A relayed `Sew-On-Behalf-Of` claim is never accepted here.
313        RelayNotAllowed = "relay_not_allowed",
314        /// A session with an `app` claim (the home client included) never
315        /// reaches the server-governed Space (governance `server`), whoever the member is.
316        AppSessionNotAllowed = "app_session_not_allowed",
317        /// An App user (`k2:principal:`) never reaches the server-governed Space,
318        /// even from a session without an `app` claim.
319        AppUserNotAllowed = "app_user_not_allowed",
320        /// A call-scoped credential called a route outside its call's scope.
321        CallCredentialScope = "call_credential_scope",
322    }
323}
324
325unit_enum! {
326    /// `details.reason` of a `422 invalid_state` from the permission engine.
327    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
328    pub enum InvalidStateReason {
329        /// `@everyone` cannot be moved, deleted, assigned or removed.
330        EveryoneRole = "everyone_role",
331        /// Role position 0 belongs to `@everyone`.
332        BadPosition = "bad_position",
333        /// Bits outside the registry, or outside what an overwrite may hold.
334        UnknownBits = "unknown_bits",
335        /// The actor is the target.
336        SelfTarget = "self_target",
337        /// The space owner must transfer ownership before leaving.
338        OwnerMustTransfer = "owner_must_transfer",
339        /// Holders of ADMINISTRATOR cannot be timed out.
340        TargetIsAdministrator = "target_is_administrator",
341        /// The timeout end is not in the future.
342        TimeoutInPast = "timeout_in_past",
343        /// Timeouts last at most 28 days.
344        TimeoutTooLong = "timeout_too_long",
345        /// The channel is archived.
346        ChannelArchived = "channel_archived",
347        /// The channel has no category to sync with.
348        NoCategory = "no_category",
349        /// The target is not a member of the space.
350        NotSpaceMember = "not_space_member",
351        /// The target is deactivated.
352        InactiveTarget = "inactive_target",
353        /// A DM participant is deactivated.
354        InactiveParticipant = "inactive_participant",
355        /// A DM holds 2–9 people.
356        DmSize = "dm_size",
357        /// The install owner's role changes only by an owner transfer.
358        OwnerRoleFixed = "owner_role_fixed",
359        /// A guest's install role cannot be set here.
360        GuestRoleFixed = "guest_role_fixed",
361        /// Agents are never install admins.
362        AgentRoleFixed = "agent_role_fixed",
363        /// The space owner cannot be removed; transfer first.
364        SpaceOwner = "space_owner",
365        /// Removing oneself is `leave`.
366        UseLeave = "use_leave",
367        /// A new space owner must be an active non-guest person and a space member.
368        InvalidTransferTarget = "invalid_transfer_target",
369        /// The target would not see the channel after the add.
370        TargetCannotView = "target_cannot_view",
371        /// Assistants are never space or channel members.
372        AssistantNotJoinable = "assistant_not_joinable",
373        /// DMs cannot be renamed or changed.
374        DmImmutable = "dm_immutable",
375        /// DMs cannot be archived.
376        DmArchiveNotAllowed = "dm_archive_not_allowed",
377        /// DMs cannot be left.
378        DmLeaveNotAllowed = "dm_leave_not_allowed",
379        /// A DM's member set is fixed.
380        DmMembershipFixed = "dm_membership_fixed",
381        /// A DM needs someone besides the caller.
382        SelfDm = "self_dm",
383        /// A DM needs at least one person.
384        AgentOnlyDm = "agent_only_dm",
385        /// Guests enter a space only through a channel add.
386        GuestNeedsChannel = "guest_needs_channel",
387        // ---- Messaging
388        /// The message is deleted.
389        MessageDeleted = "message_deleted",
390        /// The thread root is deleted; the thread is closed.
391        ThreadRootDeleted = "thread_root_deleted",
392        /// Replies point at a top-level message, never at a reply.
393        NotAThreadRoot = "not_a_thread_root",
394        /// A reply or quote target is missing, deleted or in another channel.
395        ReferenceNotFound = "reference_not_found",
396        /// The other person in a 1:1 DM is deactivated; the DM is read-only.
397        DmPartnerDeactivated = "dm_partner_deactivated",
398        /// A message holds at most 1,000 versions.
399        EditLimitReached = "edit_limit_reached",
400        /// Custom emoji are not available yet.
401        CustomEmojiUnavailable = "custom_emoji_unavailable",
402        /// An edit cannot add `@here` or `@channel`.
403        BroadMentionOnEdit = "broad_mention_on_edit",
404        /// Overwrites and slow mode exist only on space channels, not DMs.
405        NotSpaceChannel = "not_space_channel",
406        /// A space holds at most 250 roles, `@everyone` included.
407        RoleLimit = "role_limit",
408        /// A channel or category holds at most 100 overwrites.
409        OverwriteLimit = "overwrite_limit",
410        // ---- Sync
411        /// The message is missing or in another channel.
412        MessageNotInChannel = "message_not_in_channel",
413        /// A thread reply not also sent to the channel (use the thread's mark unread).
414        NotATimelineMessage = "not_a_timeline_message",
415        /// The message is neither the root nor a reply of this thread.
416        MessageNotInThread = "message_not_in_thread",
417        /// Mark unread works on messages up to `[sync] mark_unread_window_days` old.
418        MarkUnreadTooOld = "mark_unread_too_old",
419        /// The space belongs to an App; its members come only through mgmt calls for that
420        /// App, never a client add, an open join or a guest channel add.
421        AppBoundSpace = "app_bound_space",
422        /// A generic channel route on a meeting channel, or a generic channel create in a
423        /// hidden Space; meeting channels change only through the meeting routes.
424        MeetingChannel = "meeting_channel",
425        // ---- Bans
426        /// Install owners and admins cannot be banned: they can lift any ban, so it would not
427        /// hold.
428        TargetIsInstallAdmin = "target_is_install_admin",
429        /// The target is banned from the space (told only to BAN_MEMBERS holders and install
430        /// owners and admins).
431        TargetBanned = "target_banned",
432        /// The target cannot join the space (what everyone else is told about a banned
433        /// target).
434        TargetCannotJoin = "target_cannot_join",
435        // ---- Private Spaces
436        /// A private Space is invite-only; make it public (`private: false`) to open it.
437        PrivateSpace = "private_space",
438        // ---- Unbound App Spaces
439        /// The Space was unbound from its App and is a read-only orphan: no posts, edits,
440        /// reactions, uploads, joins, calls or member adds until that App binds it again (or an
441        /// admin releases it). Reads, search and export still work.
442        SpaceOrphaned = "space_orphaned",
443        // ---- App-governed Spaces
444        /// The member is an App's service owner (`app:<app_id>`): it owns the App's Spaces but
445        /// is never in a DM, never mentioned and never in calls.
446        ServiceMember = "service_member",
447        /// The Space is App-governed (`governance: app`): its App decides its structure
448        /// (settings, members, roles, overwrites, channels, categories, emoji, user groups,
449        /// ownership, and leaving an assigned private channel or the Space). Only mgmt changes
450        /// it.
451        GovernedByApp = "governed_by_app",
452        /// The Space is the server-governed Space (`governance: server`): K2's daemon
453        /// decides its structure over mgmt (settings, members, roles, overwrites, channels,
454        /// categories, emoji, user groups, ownership and leaving it); clients never change it.
455        GovernedByServer = "governed_by_server",
456        /// The role is one of an App-governed Space's managed level roles (Moderator, Admin):
457        /// clients never edit, delete or assign it.
458        RoleManaged = "role_managed",
459        /// The Space's governing App has `uploads: false`: no uploads, file posts,
460        /// forwarded file copies, scheduled sends with files or recordings in it. Link previews
461        /// stay.
462        UploadsDisabled = "uploads_disabled",
463    }
464}
465
466/// Details of a `409 conflict` on a unique field: the field that is taken.
467#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
468pub struct ConflictDetails {
469    /// The taken field, for example `slug`.
470    pub field: String,
471}
472
473/// Details of a `403 quota_exceeded` count limit.
474#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
475pub struct QuotaDetails {
476    /// The config key of the limit, for example `channels_per_space`.
477    pub limit: String,
478    /// The limit.
479    pub max: u64,
480}
481
482/// Details of a `403 missing_permission` from the permission engine.
483#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
484pub struct PermissionDeniedDetails {
485    /// Why.
486    pub reason: PermissionReason,
487    /// The missing bits, for `missing_permission` and `unheld_bits`.
488    #[serde(default, skip_serializing_if = "Option::is_none")]
489    pub missing: Option<Perms>,
490}
491
492/// Details of a `403 policy_denied`: the org policy that refused.
493#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
494pub struct PolicyDeniedDetails {
495    /// The policy key.
496    pub policy: PolicyKey,
497}
498
499/// Details of a `422 invalid_state` from the permission engine.
500#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
501pub struct InvalidStateDetails {
502    /// Why.
503    pub reason: InvalidStateReason,
504}
505
506/// A request that failed its range or cross-field rules.
507#[derive(Debug, Clone, PartialEq, Eq)]
508pub struct ValidationError {
509    /// `validation_failed` or `too_large`.
510    pub code: Code,
511    /// The failing field, dotted for nested fields.
512    pub field: String,
513    /// For humans.
514    pub hint: String,
515}
516
517impl ValidationError {
518    /// A `validation_failed` error on `field`.
519    pub fn invalid(field: impl Into<String>, hint: impl Into<String>) -> Self {
520        ValidationError {
521            code: Code::ValidationFailed,
522            field: field.into(),
523            hint: hint.into(),
524        }
525    }
526
527    /// A `too_large` error on `field`.
528    pub fn too_large(field: impl Into<String>, hint: impl Into<String>) -> Self {
529        ValidationError {
530            code: Code::TooLarge,
531            field: field.into(),
532            hint: hint.into(),
533        }
534    }
535
536    /// Prefixes the field with a parent path: `reference` + `kind` → `reference.kind`.
537    pub fn nested(mut self, parent: &str) -> Self {
538        self.field = format!("{parent}.{}", self.field);
539        self
540    }
541
542    /// The API error with `details.field`.
543    pub fn into_api_error(self) -> ApiError {
544        ApiError::new(self.code, self.hint).with_details(ValidationDetails { field: self.field })
545    }
546}
547
548impl fmt::Display for ValidationError {
549    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
550        write!(f, "{} on {}: {}", self.code, self.field, self.hint)
551    }
552}
553
554impl std::error::Error for ValidationError {}
555
556impl From<ValidationError> for ApiError {
557    fn from(e: ValidationError) -> Self {
558        e.into_api_error()
559    }
560}
561
562/// Range and cross-field checks for a request type. Serde checks the shape; this checks the
563/// rest. Every request type implements it (serde rule 11).
564pub trait Validate {
565    /// `Ok` when the request is acceptable.
566    fn validate(&self) -> Result<(), ValidationError>;
567}
568
569// ---- helpers used by request validators ----
570
571pub(crate) fn check_chars(
572    field: &str,
573    value: &str,
574    min: usize,
575    max: usize,
576) -> Result<(), ValidationError> {
577    let n = value.chars().count();
578    if n < min || n > max {
579        return Err(ValidationError::invalid(
580            field,
581            format!("{field} must be {min}–{max} characters, got {n}"),
582        ));
583    }
584    Ok(())
585}
586
587pub(crate) fn check_opt_chars(
588    field: &str,
589    value: Option<&str>,
590    min: usize,
591    max: usize,
592) -> Result<(), ValidationError> {
593    match value {
594        Some(v) => check_chars(field, v, min, max),
595        None => Ok(()),
596    }
597}
598
599pub(crate) fn check_known<T: crate::registry::UnitEnum>(
600    field: &str,
601    value: T,
602) -> Result<(), ValidationError> {
603    if value.is_unknown_value() {
604        return Err(ValidationError::invalid(
605            field,
606            format!("{field} has a value this server does not know"),
607        ));
608    }
609    Ok(())
610}
611
612pub(crate) fn check_unique_ids(
613    field: &str,
614    ids: &[crate::id::Id],
615    min: usize,
616    max: usize,
617) -> Result<(), ValidationError> {
618    if ids.len() < min || ids.len() > max {
619        return Err(ValidationError::invalid(
620            field,
621            format!("{field} must hold {min}–{max} ids, got {}", ids.len()),
622        ));
623    }
624    let mut seen = std::collections::HashSet::with_capacity(ids.len());
625    for id in ids {
626        if !seen.insert(*id) {
627            return Err(ValidationError::invalid(
628                field,
629                format!("{field} holds {id} twice"),
630            ));
631        }
632    }
633    Ok(())
634}