Skip to main content

arachne_runtime/
client.rs

1use serde::{Deserialize, Serialize};
2use serde_json::{Value, json};
3
4use crate::{
5    WorkspacePhase, cancel, close, create, create_lan, create_nearby, create_relay, create_wan,
6    create_wan_only, describe, execute, execute_stored, wait_for_work,
7};
8
9/// Address discovery and transport selection for a typed runtime client.
10#[derive(Clone, Copy, Debug, Eq, PartialEq)]
11pub enum Network {
12    Direct,
13    Lan,
14    Nearby,
15    Wan,
16    RelayOnly,
17    WanOnly,
18}
19
20/// Configuration for one workspace-facing runtime client.
21#[derive(Clone, Debug, Eq, PartialEq)]
22pub struct ClientConfig {
23    pub network: Network,
24    pub secret: Option<[u8; 32]>,
25}
26
27#[derive(Clone, Copy, Debug, Eq, PartialEq)]
28pub enum ErrorKind {
29    Closed,
30    InvalidInput,
31    Capacity,
32    Storage,
33    Transport,
34    Cancelled,
35    Internal,
36}
37
38#[derive(Clone, Debug, Eq, PartialEq)]
39pub struct Error {
40    kind: ErrorKind,
41    message: String,
42}
43
44impl Error {
45    pub fn kind(&self) -> ErrorKind {
46        self.kind
47    }
48
49    pub fn message(&self) -> &str {
50        &self.message
51    }
52}
53
54impl std::fmt::Display for Error {
55    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        formatter.write_str(&self.message)
57    }
58}
59
60impl std::error::Error for Error {}
61
62pub type Result<T> = std::result::Result<T, Error>;
63
64#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
65pub struct EndpointInfo {
66    pub endpoint_key: [u8; 32],
67    pub bound_address: String,
68    pub workspace_ready: bool,
69}
70
71#[derive(Clone, Debug, Eq, PartialEq)]
72pub struct WorkspaceState {
73    pub endpoint_key: [u8; 32],
74    pub workspace: Option<[u8; 32]>,
75    pub workspace_ready: bool,
76    pub durable: bool,
77    pub phase: WorkspacePhase,
78    pub reason: Option<String>,
79}
80
81#[derive(Clone, Debug, Eq, PartialEq)]
82pub struct WorkspaceInfo {
83    pub workspace: [u8; 32],
84    pub workspace_name: Option<String>,
85    pub epoch: u64,
86    pub member_count: usize,
87    pub durable: bool,
88    pub phase: WorkspacePhase,
89    pub reason: Option<String>,
90}
91
92#[derive(Clone, Copy, Debug, Eq, PartialEq)]
93pub enum MemberKind {
94    Person,
95    Service,
96}
97
98#[derive(Clone, Copy, Debug, Eq, PartialEq)]
99pub enum Presence {
100    SelfMember,
101    Unknown,
102    Reachable,
103    Stale,
104}
105
106#[derive(Clone, Debug, Eq, PartialEq)]
107pub struct MemberInfo {
108    pub id: [u8; 32],
109    pub endpoint: [u8; 32],
110    pub administrator: bool,
111    pub self_member: bool,
112    pub display_name: Option<String>,
113    pub kind: MemberKind,
114    pub presence: Presence,
115    pub last_contact_age_ms: Option<u64>,
116    pub presence_fresh_for_ms: Option<u64>,
117}
118
119#[derive(Clone, Debug, Eq, PartialEq)]
120pub struct MemberRoster {
121    pub workspace: [u8; 32],
122    pub workspace_name: Option<String>,
123    pub workspace_name_revision: u64,
124    pub workspace_name_head: [u8; 32],
125    pub epoch: u64,
126    pub members: Vec<MemberInfo>,
127    pub profile_count: usize,
128    pub profiles_retained: bool,
129}
130
131#[derive(Clone, Debug, Eq, PartialEq)]
132pub struct RouteHint {
133    pub peer: [u8; 32],
134    pub address: String,
135}
136
137#[derive(Clone, Debug, Eq, PartialEq)]
138pub struct InvitationInfo {
139    pub workspace: [u8; 32],
140    pub workspace_name: Option<String>,
141    pub invitation: Vec<u8>,
142    pub invitation_key: [u8; 32],
143    pub checkpoint: Vec<u8>,
144    pub peer: [u8; 32],
145    pub bootstrap_peers: Vec<[u8; 32]>,
146    pub address: String,
147    pub routes: Vec<RouteHint>,
148}
149
150#[derive(Clone, Debug, Eq, PartialEq)]
151pub struct InvitationDetails {
152    pub workspace: [u8; 32],
153    pub invitation_key: [u8; 32],
154    pub workspace_name: Option<String>,
155    pub epoch: u64,
156    pub personal: bool,
157    pub automatic: bool,
158    pub expires_at: u64,
159}
160
161#[derive(Clone, Debug, Eq, PartialEq)]
162pub struct JoinRequest {
163    pub workspace: [u8; 32],
164    pub member: [u8; 32],
165    pub endpoint: [u8; 32],
166    pub admission_request: Vec<u8>,
167}
168
169#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
170pub struct AdmissionAuthorization {
171    pub invitation_key: [u8; 32],
172    pub grant_signature: Vec<u8>,
173    pub redemption_signature: Vec<u8>,
174}
175
176#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
177pub struct JoinAdmissionStep {
178    pub commit: Vec<u8>,
179    pub authorization: AdmissionAuthorization,
180}
181
182#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
183pub struct AdmissionReply {
184    pub workspace: [u8; 32],
185    pub epoch: u64,
186    pub commit: Vec<u8>,
187    pub welcome: Vec<u8>,
188    pub authorization: AdmissionAuthorization,
189}
190
191#[derive(Clone, Debug, Eq, PartialEq)]
192pub struct WorkspaceCandidate {
193    pub workspace: [u8; 32],
194    pub snapshot: Vec<u8>,
195}
196
197#[derive(Clone, Debug, Eq, PartialEq)]
198pub enum RouteKind {
199    Direct,
200    Relay,
201    Custom(String),
202}
203
204#[derive(Clone, Debug, Eq, PartialEq)]
205pub struct PeerRoute {
206    pub member: [u8; 32],
207    pub route: RouteKind,
208    pub rtt_ms: u64,
209}
210
211#[derive(Clone, Debug, Eq, PartialEq)]
212pub struct ConnectivityReport {
213    pub workspace: [u8; 32],
214    pub paths: Vec<PeerRoute>,
215    pub paths_limited: bool,
216    pub receive_queue: usize,
217    pub repair_jobs: usize,
218}
219
220/// A bounded, read-only snapshot for native adapters and diagnostics.
221///
222/// The snapshot contains local workspace state and counters only. It does not
223/// initiate repair, dialing, admission or publication work. Qualification
224/// receipts use a separate redacted projection; do not export this value as a
225/// public telemetry record because its path members are workspace-local IDs.
226#[derive(Clone, Debug, Eq, PartialEq)]
227pub struct WorkspaceMetrics {
228    pub workspace: [u8; 32],
229    pub phase: WorkspacePhase,
230    pub reason: Option<String>,
231    pub received_bytes: u64,
232    pub sent_bytes: u64,
233    pub receive_queue: usize,
234    pub admission_queue: usize,
235    pub admission_queue_bytes: usize,
236    pub admission_waiters: usize,
237    pub admission_in_flight: usize,
238    pub approval_pending: usize,
239    pub pending_objects: usize,
240    pub repair_jobs: usize,
241    pub gossip_neighbors: usize,
242    pub control_timing: ControlTimingMetrics,
243    pub membership_gossip: MembershipGossipMetrics,
244    pub connection_capacity: ConnectionCapacityMetrics,
245    pub paths: Vec<PeerRoute>,
246    pub paths_limited: bool,
247}
248
249/// A duration series measured in microseconds since the endpoint started.
250#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
251pub struct DurationSummary {
252    pub count: u64,
253    pub total_us: u64,
254    pub max_us: u64,
255}
256
257#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
258pub struct ControlTimingMetrics {
259    pub inquiry: DurationSummary,
260    pub host_wait: DurationSummary,
261    pub host_service: DurationSummary,
262}
263
264#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
265pub struct MembershipGossipMetrics {
266    pub sent: u64,
267    pub no_overlay: u64,
268    pub failed: u64,
269    pub received: u64,
270    pub staged: u64,
271    pub rejected: u64,
272    pub range_pulled: u64,
273    pub range_failed: u64,
274}
275
276#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
277pub struct ConnectionCapacityMetrics {
278    pub evicted: u64,
279    pub refused: u64,
280}
281
282#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
283pub struct PeerPolicy {
284    pub peer: [u8; 32],
285    pub publish: Vec<String>,
286    pub subscribe: Vec<String>,
287}
288
289#[derive(Clone, Debug, Eq, PartialEq)]
290pub struct DeliveryFailure {
291    pub peer: [u8; 32],
292    pub error: String,
293}
294
295#[derive(Clone, Debug, Eq, PartialEq)]
296pub struct DeliveryReport {
297    pub admitted: Vec<[u8; 32]>,
298    pub queued: bool,
299    pub failed: Vec<DeliveryFailure>,
300}
301
302#[derive(Clone, Debug, Eq, PartialEq)]
303pub struct PublicationCandidate {
304    pub workspace: [u8; 32],
305    pub snapshot: Vec<u8>,
306}
307
308#[derive(Clone, Debug, Eq, PartialEq)]
309pub struct InterestObservation {
310    pub workspace: [u8; 32],
311    pub revision: u64,
312    pub topic: String,
313    pub subscribed: bool,
314    pub admission: DeliveryReport,
315}
316
317#[derive(Clone, Debug, Eq, PartialEq)]
318pub struct Publication {
319    pub workspace: [u8; 32],
320    pub revision: u64,
321    pub sender: [u8; 32],
322    pub topic: String,
323    pub payload: Vec<u8>,
324}
325
326#[derive(Clone, Debug, Eq, PartialEq)]
327pub struct RecoveredPublication {
328    pub workspace: [u8; 32],
329    pub revision: u64,
330    pub member: [u8; 32],
331    pub endpoint: [u8; 32],
332    pub topic: String,
333    pub id: [u8; 16],
334    pub sequence: Option<u64>,
335    pub payload: Vec<u8>,
336}
337
338#[derive(Clone, Debug, Eq, PartialEq)]
339pub struct RecoveryRangeRequest {
340    pub peer: Option<[u8; 32]>,
341    pub author: Option<[u8; 32]>,
342    pub revision: u64,
343    pub topics: Vec<String>,
344    pub after: Option<u64>,
345    pub through: Option<u64>,
346}
347
348#[derive(Clone, Debug, Eq, PartialEq)]
349pub struct RecoveryRangeReady {
350    pub workspace: [u8; 32],
351    pub author: [u8; 32],
352    pub peer: [u8; 32],
353    pub epoch: u64,
354    pub revision: u64,
355    pub after: u64,
356    pub through: u64,
357    pub packet_count: usize,
358    pub retained_bytes: usize,
359    pub automatic_source: bool,
360    pub attempted: Option<usize>,
361}
362
363#[derive(Clone, Debug, Eq, PartialEq)]
364pub enum RecoveryRangeStatus {
365    Pending {
366        candidate_count: usize,
367        automatic_source: bool,
368    },
369    Ready(RecoveryRangeReady),
370    SourceWaiting {
371        automatic_source: bool,
372    },
373    SourceUnavailable {
374        attempted: usize,
375        reason: String,
376        automatic_source: bool,
377    },
378    Rejected {
379        reason: String,
380    },
381    Cancelled,
382}
383
384#[derive(Clone, Debug, Eq, PartialEq)]
385pub struct RecoveryCandidate {
386    pub workspace: [u8; 32],
387    pub snapshot: Vec<u8>,
388    pub publication_count: usize,
389    pub already_received: usize,
390    pub durable: bool,
391}
392
393#[derive(Clone, Debug, Eq, PartialEq)]
394pub enum RecoveryStage {
395    Candidate(RecoveryCandidate),
396    AlreadyCovered,
397    NoNewObjects,
398}
399
400#[derive(Clone, Debug, Eq, PartialEq)]
401pub struct RecoveryAdoption {
402    pub workspace: [u8; 32],
403    pub epoch: u64,
404    pub member_count: usize,
405    pub durable: bool,
406    pub recovered_publications: usize,
407    pub missing_publications: usize,
408}
409
410/// Typed adopter seam over the portable runtime. The JSON dispatcher remains
411/// private to adapters; consumers use typed lifecycle operations here.
412pub struct Client {
413    handle: Option<i64>,
414}
415
416impl Client {
417    pub fn open(config: ClientConfig) -> Result<Self> {
418        let handle = match config.network {
419            Network::Direct => {
420                create(config.secret.as_ref()).map_err(|message| map_error(&message))
421            }
422            Network::Lan => create_required_secret(config.secret.as_ref(), "LAN", create_lan),
423            Network::Nearby => {
424                create_required_secret(config.secret.as_ref(), "nearby", create_nearby)
425            }
426            Network::Wan => create_required_secret(config.secret.as_ref(), "WAN", create_wan),
427            Network::RelayOnly => {
428                create_required_secret(config.secret.as_ref(), "relay-only", create_relay)
429            }
430            Network::WanOnly => {
431                create_required_secret(config.secret.as_ref(), "WAN-only", create_wan_only)
432            }
433        };
434        Ok(Self {
435            handle: Some(handle?),
436        })
437    }
438
439    pub fn endpoint(&self) -> Result<EndpointInfo> {
440        let description = describe(self.handle()?).map_err(|message| map_error(&message))?;
441        serde_json::from_str(&description).map_err(|parse_error| {
442            error(
443                ErrorKind::Internal,
444                format!("invalid endpoint description: {parse_error}"),
445            )
446        })
447    }
448
449    pub fn workspace_state(&self) -> Result<WorkspaceState> {
450        let endpoint_key = self.endpoint()?.endpoint_key;
451        let response = self.request(json!({"op": "workspace_state"}))?;
452        let activity = response
453            .get("activity")
454            .ok_or_else(|| error(ErrorKind::Internal, "workspace state has no activity"))?;
455        let projection: ActivityProjection =
456            serde_json::from_value(activity.clone()).map_err(|parse_error| {
457                error(
458                    ErrorKind::Internal,
459                    format!("invalid workspace activity: {parse_error}"),
460                )
461            })?;
462        Ok(WorkspaceState {
463            endpoint_key,
464            workspace: response
465                .get("workspace")
466                .map(|value| serde_json::from_value(value.clone()))
467                .transpose()
468                .map_err(|parse_error| {
469                    error(
470                        ErrorKind::Internal,
471                        format!("invalid workspace id: {parse_error}"),
472                    )
473                })?,
474            workspace_ready: response
475                .get("workspace_ready")
476                .and_then(Value::as_bool)
477                .ok_or_else(|| error(ErrorKind::Internal, "workspace state has no readiness"))?,
478            durable: response
479                .get("durable")
480                .and_then(Value::as_bool)
481                .ok_or_else(|| error(ErrorKind::Internal, "workspace state has no durability"))?,
482            phase: projection.phase,
483            reason: projection.reason,
484        })
485    }
486
487    pub fn create_workspace(
488        &self,
489        display_name: &str,
490        workspace_name: Option<&str>,
491    ) -> Result<WorkspaceInfo> {
492        let response = self.request(json!({
493            "op": "create_workspace",
494            "display_name": display_name,
495            "workspace_name": workspace_name,
496        }))?;
497        let raw: RawWorkspaceInfo = serde_json::from_value(response).map_err(|parse_error| {
498            error(
499                ErrorKind::Internal,
500                format!("invalid workspace creation result: {parse_error}"),
501            )
502        })?;
503        Ok(WorkspaceInfo {
504            workspace: raw.workspace,
505            workspace_name: raw.workspace_name,
506            epoch: raw.epoch,
507            member_count: raw.members,
508            durable: raw.durable,
509            phase: raw.activity.phase,
510            reason: raw.activity.reason,
511        })
512    }
513
514    pub fn begin_join(
515        &self,
516        invitation: &[u8],
517        checkpoint: &[u8],
518        display_name: &str,
519    ) -> Result<JoinRequest> {
520        let response = self.request(json!({
521            "op": "begin_join",
522            "invitation": invitation,
523            "checkpoint": checkpoint,
524            "display_name": display_name,
525        }))?;
526        let raw: RawJoinRequest = serde_json::from_value(response).map_err(|parse_error| {
527            error(
528                ErrorKind::Internal,
529                format!("invalid join request: {parse_error}"),
530            )
531        })?;
532        Ok(JoinRequest {
533            workspace: raw.workspace,
534            member: raw.member.id,
535            endpoint: raw.endpoint,
536            admission_request: raw
537                .admission_request
538                .ok_or_else(|| error(ErrorKind::InvalidInput, "invitation has no admission request"))?,
539        })
540    }
541
542    pub fn stage_admission(
543        &self,
544        authenticated_endpoint: [u8; 32],
545        request: &[u8],
546    ) -> Result<WorkspaceCandidate> {
547        let metadata = serde_json::to_vec(&json!({
548            "op": "stage_admission",
549            "authenticated_endpoint": authenticated_endpoint,
550            "request": request,
551        }))
552        .map_err(|parse_error| error(ErrorKind::Internal, parse_error.to_string()))?;
553        let [metadata, snapshot] = execute_stored(self.handle()?, &metadata, &[])
554            .map_err(|message| map_error(&message))?;
555        parse_workspace_candidate(&metadata, snapshot, "admission")
556    }
557
558    pub fn adopt_admission(&self, snapshot: &[u8]) -> Result<WorkspaceInfo> {
559        let [metadata, _] = execute_stored(
560            self.handle()?,
561            br#"{"op":"adopt_admission"}"#,
562            snapshot,
563        )
564        .map_err(|message| map_error(&message))?;
565        parse_workspace_info(&metadata, "admission adoption")
566    }
567
568    pub fn retained_admission(
569        &self,
570        authenticated_endpoint: [u8; 32],
571        request: &[u8],
572    ) -> Result<AdmissionReply> {
573        let response = self.request(json!({
574            "op": "retained_admission",
575            "authenticated_endpoint": authenticated_endpoint,
576            "request": request,
577        }))?;
578        serde_json::from_value(response).map_err(|parse_error| {
579            error(
580                ErrorKind::Internal,
581                format!("invalid admission reply: {parse_error}"),
582            )
583        })
584    }
585
586    pub fn stage_join(
587        &self,
588        welcome: &[u8],
589        commits: &[JoinAdmissionStep],
590    ) -> Result<WorkspaceCandidate> {
591        let metadata = serde_json::to_vec(&json!({
592            "op": "stage_join",
593            "commits": commits,
594        }))
595        .map_err(|parse_error| error(ErrorKind::Internal, parse_error.to_string()))?;
596        let [metadata, snapshot] = execute_stored(self.handle()?, &metadata, welcome)
597            .map_err(|message| map_error(&message))?;
598        parse_workspace_candidate(&metadata, snapshot, "join")
599    }
600
601    pub fn adopt_join(&self, snapshot: &[u8]) -> Result<WorkspaceInfo> {
602        let [metadata, _] = execute_stored(
603            self.handle()?,
604            br#"{"op":"adopt_join"}"#,
605            snapshot,
606        )
607        .map_err(|message| map_error(&message))?;
608        parse_workspace_info(&metadata, "join adoption")
609    }
610
611    pub fn member_roster(&self) -> Result<MemberRoster> {
612        let response = self.request(json!({"op": "member_roster"}))?;
613        let raw: RawMemberRoster = serde_json::from_value(response).map_err(|parse_error| {
614            error(
615                ErrorKind::Internal,
616                format!("invalid member roster: {parse_error}"),
617            )
618        })?;
619        let members = raw
620            .members
621            .into_iter()
622            .map(MemberInfo::try_from)
623            .collect::<Result<Vec<_>>>()?;
624        Ok(MemberRoster {
625            workspace: raw.workspace,
626            workspace_name: raw.workspace_name,
627            workspace_name_revision: raw.workspace_name_revision,
628            workspace_name_head: raw.workspace_name_head,
629            epoch: raw.epoch,
630            members,
631            profile_count: raw.profiles.len(),
632            profiles_retained: raw.profiles_retained.unwrap_or(true),
633        })
634    }
635
636    pub fn issue_invitation(&self) -> Result<InvitationInfo> {
637        let response = self.request(json!({"op": "issue_invitation"}))?;
638        let raw: RawInvitationInfo = serde_json::from_value(response).map_err(|parse_error| {
639            error(
640                ErrorKind::Internal,
641                format!("invalid invitation: {parse_error}"),
642            )
643        })?;
644        Ok(InvitationInfo {
645            workspace: raw.workspace,
646            workspace_name: raw.workspace_name,
647            invitation: raw.invitation,
648            invitation_key: raw.invitation_key,
649            checkpoint: raw.checkpoint,
650            peer: raw.peer,
651            bootstrap_peers: raw.bootstrap_peers,
652            address: raw.address,
653            routes: raw
654                .routes
655                .into_iter()
656                .map(|route| RouteHint {
657                    peer: route.peer,
658                    address: route.address,
659                })
660                .collect(),
661        })
662    }
663
664    pub fn inspect_invitation(
665        &self,
666        invitation: &[u8],
667        checkpoint: &[u8],
668    ) -> Result<InvitationDetails> {
669        let response = self.request(json!({
670            "op": "inspect_invitation",
671            "invitation": invitation,
672            "checkpoint": checkpoint,
673        }))?;
674        let raw: RawInvitationDetails =
675            serde_json::from_value(response).map_err(|parse_error| {
676                error(
677                    ErrorKind::Internal,
678                    format!("invalid invitation details: {parse_error}"),
679                )
680            })?;
681        Ok(InvitationDetails {
682            workspace: raw.workspace,
683            invitation_key: raw.invitation_key,
684            workspace_name: raw.workspace_name,
685            epoch: raw.epoch,
686            personal: raw.personal_invitation,
687            automatic: raw.automatic_approval,
688            expires_at: raw.expires_at,
689        })
690    }
691
692    pub fn connectivity(&self) -> Result<ConnectivityReport> {
693        let metrics = self.metrics()?;
694        Ok(ConnectivityReport {
695            workspace: metrics.workspace,
696            paths: metrics.paths,
697            paths_limited: metrics.paths_limited,
698            receive_queue: metrics.receive_queue,
699            repair_jobs: metrics.repair_jobs,
700        })
701    }
702
703    pub fn metrics(&self) -> Result<WorkspaceMetrics> {
704        let response = self.request(json!({"op": "workspace_metrics"}))?;
705        let raw: RawWorkspaceMetrics =
706            serde_json::from_value(response).map_err(|parse_error| {
707                error(
708                    ErrorKind::Internal,
709                    format!("invalid workspace metrics: {parse_error}"),
710                )
711            })?;
712        Ok(WorkspaceMetrics {
713            workspace: raw.workspace,
714            phase: raw.activity.phase,
715            reason: raw.activity.reason,
716            received_bytes: raw.received_bytes,
717            sent_bytes: raw.sent_bytes,
718            receive_queue: raw.receive_queue,
719            admission_queue: raw.admission_queue,
720            admission_queue_bytes: raw.admission_queue_bytes,
721            admission_waiters: raw.admission_waiters,
722            admission_in_flight: raw.admission_in_flight,
723            approval_pending: raw.approval_pending,
724            pending_objects: raw.pending_objects,
725            repair_jobs: raw.repair_jobs,
726            gossip_neighbors: raw.gossip_neighbors,
727            control_timing: raw.control_timing,
728            membership_gossip: raw.membership_gossip,
729            connection_capacity: raw.connection_capacity,
730            paths: raw
731                .paths
732                .into_iter()
733                .map(|path| PeerRoute {
734                    member: path.member,
735                    route: match path.route.as_str() {
736                        "direct" => RouteKind::Direct,
737                        "relay" => RouteKind::Relay,
738                        other => RouteKind::Custom(other.to_owned()),
739                    },
740                    rtt_ms: path.rtt_ms,
741                })
742                .collect(),
743            paths_limited: raw.paths_limited,
744        })
745    }
746
747    pub fn network_change(&self) -> Result<()> {
748        self.request(json!({"op": "network_change"}))?;
749        Ok(())
750    }
751
752    pub fn cancel(&self) -> Result<()> {
753        cancel(self.handle()?).map_err(|message| map_error(&message))
754    }
755
756    pub fn wait_for_work(&self) -> Result<bool> {
757        wait_for_work(self.handle()?).map_err(|message| map_error(&message))
758    }
759
760    /// Service one queued peer-control exchange and report whether one was served.
761    pub fn poll_control(&self) -> Result<bool> {
762        Ok(!self.request(json!({"op": "poll_admission"}))?.is_null())
763    }
764
765    pub fn add_address_hint(&self, peer: [u8; 32], address: &str) -> Result<()> {
766        self.request(json!({
767            "op": "add_address_hint",
768            "peer": peer,
769            "address": address,
770        }))?;
771        Ok(())
772    }
773
774    pub fn install_policy(
775        &self,
776        workspace: [u8; 32],
777        revision: u64,
778        endpoints: &[PeerPolicy],
779    ) -> Result<()> {
780        self.request(json!({
781            "op": "install_verified_policy",
782            "workspace": workspace,
783            "revision": revision,
784            "endpoints": endpoints,
785        }))?;
786        Ok(())
787    }
788
789    pub fn install_workspace_policy(&self, revision: u64) -> Result<()> {
790        self.request(json!({
791            "op": "install_workspace_policy",
792            "revision": revision,
793        }))?;
794        Ok(())
795    }
796
797    pub fn stage_protected_publication(
798        &self,
799        workspace: [u8; 32],
800        revision: u64,
801        topic: &str,
802        id: [u8; 16],
803        payload: Vec<u8>,
804    ) -> Result<PublicationCandidate> {
805        let request = serde_json::to_vec(&json!({
806            "op": "stage_network_publication",
807            "revision": revision,
808            "topic": topic,
809            "id": id,
810            "payload": payload,
811        }))
812        .map_err(|parse_error| error(ErrorKind::Internal, parse_error.to_string()))?;
813        let [metadata, snapshot] =
814            execute_stored(self.handle()?, &request, &[]).map_err(|message| map_error(&message))?;
815        let value: Value = serde_json::from_slice(&metadata).map_err(|parse_error| {
816            error(
817                ErrorKind::Internal,
818                format!("invalid publication candidate: {parse_error}"),
819            )
820        })?;
821        let candidate_workspace = value
822            .get("workspace")
823            .ok_or_else(|| error(ErrorKind::Internal, "publication candidate has no workspace"))
824            .and_then(|value| {
825                serde_json::from_value(value.clone()).map_err(|parse_error| {
826                    error(
827                        ErrorKind::Internal,
828                        format!("invalid publication candidate workspace: {parse_error}"),
829                    )
830                })
831            })?;
832        if candidate_workspace != workspace {
833            return Err(error(
834                ErrorKind::Internal,
835                "publication candidate workspace mismatch",
836            ));
837        }
838        Ok(PublicationCandidate {
839            workspace: candidate_workspace,
840            snapshot,
841        })
842    }
843
844    pub fn adopt_protected_publication(&self, snapshot: &[u8]) -> Result<DeliveryReport> {
845        let [metadata, _] = execute_stored(
846            self.handle()?,
847            br#"{"op":"adopt_publication"}"#,
848            snapshot,
849        )
850        .map_err(|message| map_error(&message))?;
851        let value: Value = serde_json::from_slice(&metadata).map_err(|parse_error| {
852            error(
853                ErrorKind::Internal,
854                format!("invalid publication result: {parse_error}"),
855            )
856        })?;
857        if let Some(message) = value.get("network_error").and_then(Value::as_str) {
858            return Err(error(ErrorKind::Transport, message));
859        }
860        let admission = value
861            .get("admission")
862            .ok_or_else(|| error(ErrorKind::Internal, "publication result has no admission"))?;
863        serde_json::from_value::<RawDeliveryReport>(admission.clone())
864            .map(Into::into)
865            .map_err(|parse_error| {
866                error(
867                    ErrorKind::Internal,
868                    format!("invalid publication admission: {parse_error}"),
869                )
870            })
871    }
872
873    pub fn set_interest(
874        &self,
875        workspace: [u8; 32],
876        revision: u64,
877        topic: &str,
878        subscribed: bool,
879    ) -> Result<()> {
880        self.request(json!({
881            "op": "set_interest",
882            "workspace": workspace,
883            "revision": revision,
884            "topic": topic,
885            "subscribed": subscribed,
886        }))?;
887        Ok(())
888    }
889
890    pub fn poll_interest(&self) -> Result<Option<InterestObservation>> {
891        let response = self.request(json!({"op": "poll_interest"}))?;
892        if response.is_null()
893            || matches!(
894                response.get("state").and_then(Value::as_str),
895                Some("interest_pending")
896            )
897        {
898            return Ok(None);
899        }
900        if response.get("state").and_then(Value::as_str) == Some("interest_failed") {
901            return Err(error(
902                ErrorKind::Transport,
903                response
904                    .get("error")
905                    .and_then(Value::as_str)
906                    .unwrap_or("interest update failed"),
907            ));
908        }
909        let raw: RawInterestObservation =
910            serde_json::from_value(response).map_err(|parse_error| {
911                error(
912                    ErrorKind::Internal,
913                    format!("invalid interest observation: {parse_error}"),
914                )
915            })?;
916        Ok(Some(InterestObservation {
917            workspace: raw.workspace,
918            revision: raw.revision,
919            topic: raw.topic,
920            subscribed: raw.subscribed,
921            admission: raw.admission.into(),
922        }))
923    }
924
925    pub fn publish(
926        &self,
927        workspace: [u8; 32],
928        revision: u64,
929        topic: &str,
930        payload: Vec<u8>,
931    ) -> Result<DeliveryReport> {
932        let response = self.request(json!({
933            "op": "publish",
934            "workspace": workspace,
935            "revision": revision,
936            "topic": topic,
937            "payload": payload,
938        }))?;
939        serde_json::from_value::<RawDeliveryReport>(response)
940            .map(Into::into)
941            .map_err(|parse_error| {
942                error(
943                    ErrorKind::Internal,
944                    format!("invalid delivery report: {parse_error}"),
945                )
946            })
947    }
948
949    pub fn poll(&self) -> Result<Option<Publication>> {
950        let response = self.request(json!({"op": "poll"}))?;
951        if response.is_null() {
952            return Ok(None);
953        }
954        serde_json::from_value::<RawPublication>(response)
955            .map(Into::into)
956            .map(Some)
957            .map_err(|parse_error| {
958                error(
959                    ErrorKind::Internal,
960                    format!("invalid publication: {parse_error}"),
961                )
962            })
963    }
964
965    pub fn poll_recovered_publication(&self) -> Result<Option<RecoveredPublication>> {
966        let response = self.request(json!({"op": "poll_recovered_publication"}))?;
967        if response.is_null() {
968            return Ok(None);
969        }
970        serde_json::from_value::<RawRecoveredPublication>(response)
971            .map(Into::into)
972            .map(Some)
973            .map_err(|parse_error| {
974                error(
975                    ErrorKind::Internal,
976                    format!("invalid recovered publication: {parse_error}"),
977                )
978            })
979    }
980
981    pub fn fetch_recovery_range(
982        &self,
983        request: RecoveryRangeRequest,
984    ) -> Result<RecoveryRangeStatus> {
985        let response = self.request(json!({
986            "op": "fetch_recovery_range",
987            "peer": request.peer,
988            "author": request.author,
989            "revision": request.revision,
990            "topics": request.topics,
991            "after": request.after,
992            "through": request.through,
993        }))?;
994        parse_recovery_range_status(response)
995    }
996
997    pub fn poll_recovery_range(&self) -> Result<Option<RecoveryRangeStatus>> {
998        let response = self.request(json!({"op": "poll_recovery_range"}))?;
999        if response.is_null() {
1000            return Ok(None);
1001        }
1002        parse_recovery_range_status(response).map(Some)
1003    }
1004
1005    pub fn cancel_recovery_range(&self) -> Result<()> {
1006        match parse_recovery_range_status(self.request(json!({
1007            "op": "cancel_recovery_range"
1008        }))?)? {
1009            RecoveryRangeStatus::Cancelled => Ok(()),
1010            _ => Err(error(
1011                ErrorKind::Internal,
1012                "invalid recovery cancellation response",
1013            )),
1014        }
1015    }
1016
1017    pub fn stage_recovery_range(&self, retain_until: u64) -> Result<RecoveryStage> {
1018        let metadata = serde_json::to_vec(&json!({
1019            "op": "stage_recovery_range",
1020            "retain_until": retain_until,
1021        }))
1022        .map_err(|parse_error| error(ErrorKind::Internal, parse_error.to_string()))?;
1023        let [metadata, snapshot] = execute_stored(self.handle()?, &metadata, &[])
1024            .map_err(|message| map_error(&message))?;
1025        let value: Value = serde_json::from_slice(&metadata).map_err(|parse_error| {
1026            error(
1027                ErrorKind::Internal,
1028                format!("invalid recovery stage: {parse_error}"),
1029            )
1030        })?;
1031        let state = value
1032            .get("state")
1033            .and_then(Value::as_str)
1034            .ok_or_else(|| error(ErrorKind::Internal, "recovery stage has no state"))?;
1035        match state {
1036            "awaiting_recovery_save" => {
1037                let raw: RawRecoveryCandidate =
1038                    serde_json::from_value(value).map_err(|parse_error| {
1039                        error(
1040                            ErrorKind::Internal,
1041                            format!("invalid recovery candidate: {parse_error}"),
1042                        )
1043                    })?;
1044                Ok(RecoveryStage::Candidate(RecoveryCandidate {
1045                    workspace: raw.workspace,
1046                    snapshot,
1047                    publication_count: raw.publication_count,
1048                    already_received: raw.already_received,
1049                    durable: raw.durable,
1050                }))
1051            }
1052            "recovery_already_covered" => Ok(RecoveryStage::AlreadyCovered),
1053            "recovery_no_new_objects" => Ok(RecoveryStage::NoNewObjects),
1054            other => Err(error(
1055                ErrorKind::Internal,
1056                format!("unknown recovery stage: {other}"),
1057            )),
1058        }
1059    }
1060
1061    pub fn adopt_recovery(&self, snapshot: &[u8]) -> Result<RecoveryAdoption> {
1062        let [metadata, _] = execute_stored(
1063            self.handle()?,
1064            br#"{"op":"adopt_recovery"}"#,
1065            snapshot,
1066        )
1067        .map_err(|message| map_error(&message))?;
1068        let raw: RawRecoveryAdoption = serde_json::from_slice(&metadata).map_err(|parse_error| {
1069            error(
1070                ErrorKind::Internal,
1071                format!("invalid recovery adoption: {parse_error}"),
1072            )
1073        })?;
1074        let (recovered_publications, missing_publications) = match raw.state.as_str() {
1075            "recovery_adopted" => (raw.publication_count, 0),
1076            "direct_miss_adopted" => (0, raw.missing_count),
1077            other => {
1078                return Err(error(
1079                    ErrorKind::Internal,
1080                    format!("unknown recovery adoption: {other}"),
1081                ));
1082            }
1083        };
1084        Ok(RecoveryAdoption {
1085            workspace: raw.workspace,
1086            epoch: raw.epoch,
1087            member_count: raw.members,
1088            durable: raw.durable,
1089            recovered_publications,
1090            missing_publications,
1091        })
1092    }
1093
1094    pub fn close(&mut self) -> Result<()> {
1095        let handle = self
1096            .handle
1097            .take()
1098            .ok_or_else(|| error(ErrorKind::Closed, "client is closed"))?;
1099        close(handle).map_err(|message| map_error(&message))
1100    }
1101
1102    fn handle(&self) -> Result<i64> {
1103        self.handle
1104            .ok_or_else(|| error(ErrorKind::Closed, "client is closed"))
1105    }
1106
1107    fn request(&self, request: Value) -> Result<Value> {
1108        let bytes = serde_json::to_vec(&request).map_err(|parse_error| {
1109            error(
1110                ErrorKind::Internal,
1111                format!("request encoding failed: {parse_error}"),
1112            )
1113        })?;
1114        let reply = execute(self.handle()?, &bytes).map_err(|message| map_error(&message))?;
1115        serde_json::from_slice(&reply).map_err(|parse_error| {
1116            error(
1117                ErrorKind::Internal,
1118                format!("response decoding failed: {parse_error}"),
1119            )
1120        })
1121    }
1122}
1123
1124impl Drop for Client {
1125    fn drop(&mut self) {
1126        if let Some(handle) = self.handle.take() {
1127            let _ = close(handle);
1128        }
1129    }
1130}
1131
1132#[derive(Deserialize)]
1133struct ActivityProjection {
1134    #[serde(rename = "state")]
1135    phase: WorkspacePhase,
1136    reason: Option<String>,
1137}
1138
1139#[derive(Deserialize)]
1140struct RawWorkspaceInfo {
1141    workspace: [u8; 32],
1142    workspace_name: Option<String>,
1143    epoch: u64,
1144    members: usize,
1145    durable: bool,
1146    activity: ActivityProjection,
1147}
1148
1149#[derive(Deserialize)]
1150struct RawJoinMember {
1151    id: [u8; 32],
1152}
1153
1154#[derive(Deserialize)]
1155struct RawJoinRequest {
1156    workspace: [u8; 32],
1157    endpoint: [u8; 32],
1158    member: RawJoinMember,
1159    admission_request: Option<Vec<u8>>,
1160}
1161
1162#[derive(Deserialize)]
1163struct RawWorkspaceCandidate {
1164    workspace: [u8; 32],
1165}
1166
1167#[derive(Deserialize)]
1168struct RawMemberRoster {
1169    workspace: [u8; 32],
1170    workspace_name: Option<String>,
1171    workspace_name_revision: u64,
1172    workspace_name_head: [u8; 32],
1173    epoch: u64,
1174    members: Vec<RawMemberInfo>,
1175    #[serde(default)]
1176    profiles: Vec<Vec<u8>>,
1177    profiles_retained: Option<bool>,
1178}
1179
1180#[derive(Deserialize)]
1181struct RawMemberInfo {
1182    id: [u8; 32],
1183    endpoint: [u8; 32],
1184    administrator: bool,
1185    #[serde(rename = "self")]
1186    self_member: bool,
1187    display_name: Option<String>,
1188    kind: String,
1189    presence: String,
1190    last_contact_age_ms: Option<u64>,
1191    presence_fresh_for_ms: Option<u64>,
1192}
1193
1194#[derive(Deserialize)]
1195struct RawInvitationInfo {
1196    workspace: [u8; 32],
1197    workspace_name: Option<String>,
1198    invitation: Vec<u8>,
1199    invitation_key: [u8; 32],
1200    checkpoint: Vec<u8>,
1201    peer: [u8; 32],
1202    #[serde(default)]
1203    bootstrap_peers: Vec<[u8; 32]>,
1204    address: String,
1205    #[serde(default)]
1206    routes: Vec<RawRouteHint>,
1207}
1208
1209#[derive(Deserialize)]
1210struct RawInvitationDetails {
1211    workspace: [u8; 32],
1212    invitation_key: [u8; 32],
1213    workspace_name: Option<String>,
1214    epoch: u64,
1215    personal_invitation: bool,
1216    automatic_approval: bool,
1217    expires_at: u64,
1218}
1219
1220#[derive(Deserialize)]
1221struct RawRouteHint {
1222    peer: [u8; 32],
1223    address: String,
1224}
1225
1226#[derive(Deserialize)]
1227struct RawWorkspaceMetrics {
1228    workspace: [u8; 32],
1229    activity: ActivityProjection,
1230    received_bytes: u64,
1231    sent_bytes: u64,
1232    receive_queue: usize,
1233    admission_queue: usize,
1234    admission_queue_bytes: usize,
1235    admission_waiters: usize,
1236    admission_in_flight: usize,
1237    approval_pending: usize,
1238    pending_objects: usize,
1239    repair_jobs: usize,
1240    gossip_neighbors: usize,
1241    control_timing: ControlTimingMetrics,
1242    membership_gossip: MembershipGossipMetrics,
1243    connection_capacity: ConnectionCapacityMetrics,
1244    paths: Vec<RawPeerRoute>,
1245    paths_limited: bool,
1246}
1247
1248#[derive(Deserialize)]
1249struct RawPeerRoute {
1250    member: [u8; 32],
1251    route: String,
1252    rtt_ms: u64,
1253}
1254
1255fn parse_workspace_info(bytes: &[u8], context: &str) -> Result<WorkspaceInfo> {
1256    let raw: RawWorkspaceInfo = serde_json::from_slice(bytes).map_err(|parse_error| {
1257        error(
1258            ErrorKind::Internal,
1259            format!("invalid {context} result: {parse_error}"),
1260        )
1261    })?;
1262    Ok(WorkspaceInfo {
1263        workspace: raw.workspace,
1264        workspace_name: raw.workspace_name,
1265        epoch: raw.epoch,
1266        member_count: raw.members,
1267        durable: raw.durable,
1268        phase: raw.activity.phase,
1269        reason: raw.activity.reason,
1270    })
1271}
1272
1273fn parse_workspace_candidate(
1274    metadata: &[u8],
1275    snapshot: Vec<u8>,
1276    context: &str,
1277) -> Result<WorkspaceCandidate> {
1278    let raw: RawWorkspaceCandidate = serde_json::from_slice(metadata).map_err(|parse_error| {
1279        error(
1280            ErrorKind::Internal,
1281            format!("invalid {context} candidate: {parse_error}"),
1282        )
1283    })?;
1284    Ok(WorkspaceCandidate {
1285        workspace: raw.workspace,
1286        snapshot,
1287    })
1288}
1289
1290impl TryFrom<RawMemberInfo> for MemberInfo {
1291    type Error = Error;
1292
1293    fn try_from(value: RawMemberInfo) -> Result<Self> {
1294        let kind = match value.kind.as_str() {
1295            "person" => MemberKind::Person,
1296            "service" => MemberKind::Service,
1297            _ => return Err(error(ErrorKind::Internal, "invalid member kind")),
1298        };
1299        let presence = match value.presence.as_str() {
1300            "self" => Presence::SelfMember,
1301            "unknown" => Presence::Unknown,
1302            "reachable" => Presence::Reachable,
1303            "stale" => Presence::Stale,
1304            _ => return Err(error(ErrorKind::Internal, "invalid member presence")),
1305        };
1306        Ok(Self {
1307            id: value.id,
1308            endpoint: value.endpoint,
1309            administrator: value.administrator,
1310            self_member: value.self_member,
1311            display_name: value.display_name,
1312            kind,
1313            presence,
1314            last_contact_age_ms: value.last_contact_age_ms,
1315            presence_fresh_for_ms: value.presence_fresh_for_ms,
1316        })
1317    }
1318}
1319
1320#[derive(Deserialize)]
1321struct RawDeliveryReport {
1322    admitted: Vec<[u8; 32]>,
1323    queued: bool,
1324    failed: Vec<RawDeliveryFailure>,
1325}
1326
1327#[derive(Deserialize)]
1328struct RawDeliveryFailure {
1329    peer: [u8; 32],
1330    error: String,
1331}
1332
1333#[derive(Deserialize)]
1334struct RawInterestObservation {
1335    workspace: [u8; 32],
1336    revision: u64,
1337    topic: String,
1338    subscribed: bool,
1339    admission: RawDeliveryReport,
1340}
1341
1342#[derive(Deserialize)]
1343struct RawPublication {
1344    workspace: [u8; 32],
1345    revision: u64,
1346    sender: [u8; 32],
1347    topic: String,
1348    payload: Vec<u8>,
1349}
1350
1351#[derive(Deserialize)]
1352struct RawRecoveredPublication {
1353    workspace: [u8; 32],
1354    revision: u64,
1355    member: [u8; 32],
1356    endpoint: [u8; 32],
1357    topic: String,
1358    id: [u8; 16],
1359    sequence: Option<u64>,
1360    payload: Vec<u8>,
1361}
1362
1363#[derive(Deserialize)]
1364struct RawRecoveryRangePending {
1365    candidate_count: usize,
1366    automatic_source: bool,
1367}
1368
1369#[derive(Deserialize)]
1370struct RawRecoveryRangeReady {
1371    workspace: [u8; 32],
1372    author: [u8; 32],
1373    peer: [u8; 32],
1374    epoch: u64,
1375    revision: u64,
1376    after: u64,
1377    through: u64,
1378    packet_count: usize,
1379    retained_bytes: usize,
1380    automatic_source: bool,
1381    #[serde(default)]
1382    attempted: Option<usize>,
1383}
1384
1385#[derive(Deserialize)]
1386struct RawRecoverySourceUnavailable {
1387    attempted: usize,
1388    reason: String,
1389    automatic_source: bool,
1390}
1391
1392#[derive(Deserialize)]
1393struct RawRecoveryCandidate {
1394    workspace: [u8; 32],
1395    #[serde(default)]
1396    publication_count: usize,
1397    #[serde(default)]
1398    already_received: usize,
1399    durable: bool,
1400}
1401
1402#[derive(Deserialize)]
1403struct RawRecoveryAdoption {
1404    workspace: [u8; 32],
1405    epoch: u64,
1406    members: usize,
1407    durable: bool,
1408    state: String,
1409    #[serde(default)]
1410    publication_count: usize,
1411    #[serde(default)]
1412    missing_count: usize,
1413}
1414
1415fn parse_recovery_range_status(value: Value) -> Result<RecoveryRangeStatus> {
1416    let state = value
1417        .get("state")
1418        .and_then(Value::as_str)
1419        .ok_or_else(|| error(ErrorKind::Internal, "recovery range has no state"))?;
1420    match state {
1421        "recovery_range_pending" => {
1422            let raw: RawRecoveryRangePending =
1423                serde_json::from_value(value).map_err(|parse_error| {
1424                    error(
1425                        ErrorKind::Internal,
1426                        format!("invalid recovery range status: {parse_error}"),
1427                    )
1428                })?;
1429            Ok(RecoveryRangeStatus::Pending {
1430                candidate_count: raw.candidate_count,
1431                automatic_source: raw.automatic_source,
1432            })
1433        }
1434        "recovery_range_ready" => {
1435            let raw: RawRecoveryRangeReady =
1436                serde_json::from_value(value).map_err(|parse_error| {
1437                    error(
1438                        ErrorKind::Internal,
1439                        format!("invalid recovery range: {parse_error}"),
1440                    )
1441                })?;
1442            Ok(RecoveryRangeStatus::Ready(RecoveryRangeReady {
1443                workspace: raw.workspace,
1444                author: raw.author,
1445                peer: raw.peer,
1446                epoch: raw.epoch,
1447                revision: raw.revision,
1448                after: raw.after,
1449                through: raw.through,
1450                packet_count: raw.packet_count,
1451                retained_bytes: raw.retained_bytes,
1452                automatic_source: raw.automatic_source,
1453                attempted: raw.attempted,
1454            }))
1455        }
1456        "recovery_source_waiting" => Ok(RecoveryRangeStatus::SourceWaiting {
1457            automatic_source: value
1458                .get("automatic_source")
1459                .and_then(Value::as_bool)
1460                .unwrap_or(true),
1461        }),
1462        "recovery_source_unavailable" => {
1463            let raw: RawRecoverySourceUnavailable =
1464                serde_json::from_value(value).map_err(|parse_error| {
1465                    error(
1466                        ErrorKind::Internal,
1467                        format!("invalid recovery source status: {parse_error}"),
1468                    )
1469                })?;
1470            Ok(RecoveryRangeStatus::SourceUnavailable {
1471                attempted: raw.attempted,
1472                reason: raw.reason,
1473                automatic_source: raw.automatic_source,
1474            })
1475        }
1476        "recovery_range_rejected" => Ok(RecoveryRangeStatus::Rejected {
1477            reason: value
1478                .get("reason")
1479                .and_then(Value::as_str)
1480                .unwrap_or("recovery range rejected")
1481                .to_owned(),
1482        }),
1483        "recovery_range_cancelled" => Ok(RecoveryRangeStatus::Cancelled),
1484        other => Err(error(
1485            ErrorKind::Internal,
1486            format!("unknown recovery range state: {other}"),
1487        )),
1488    }
1489}
1490
1491impl From<RawDeliveryReport> for DeliveryReport {
1492    fn from(value: RawDeliveryReport) -> Self {
1493        Self {
1494            admitted: value.admitted,
1495            queued: value.queued,
1496            failed: value
1497                .failed
1498                .into_iter()
1499                .map(|failure| DeliveryFailure {
1500                    peer: failure.peer,
1501                    error: failure.error,
1502                })
1503                .collect(),
1504        }
1505    }
1506}
1507
1508impl From<RawPublication> for Publication {
1509    fn from(value: RawPublication) -> Self {
1510        Self {
1511            workspace: value.workspace,
1512            revision: value.revision,
1513            sender: value.sender,
1514            topic: value.topic,
1515            payload: value.payload,
1516        }
1517    }
1518}
1519
1520impl From<RawRecoveredPublication> for RecoveredPublication {
1521    fn from(value: RawRecoveredPublication) -> Self {
1522        Self {
1523            workspace: value.workspace,
1524            revision: value.revision,
1525            member: value.member,
1526            endpoint: value.endpoint,
1527            topic: value.topic,
1528            id: value.id,
1529            sequence: value.sequence,
1530            payload: value.payload,
1531        }
1532    }
1533}
1534
1535fn error(kind: ErrorKind, message: impl Into<String>) -> Error {
1536    Error {
1537        kind,
1538        message: message.into(),
1539    }
1540}
1541
1542fn map_error(message: &str) -> Error {
1543    let lower = message.to_ascii_lowercase();
1544    let kind = if lower.contains("invalid or closed") || lower == "node is closed" {
1545        ErrorKind::Closed
1546    } else if lower.contains("limit") || lower.contains("capacity") || lower.contains("queue") {
1547        ErrorKind::Capacity
1548    } else if lower.contains("storage") || lower.contains("snapshot") || lower.contains("record") {
1549        ErrorKind::Storage
1550    } else if lower.contains("cancel") {
1551        ErrorKind::Cancelled
1552    } else if lower.contains("transport")
1553        || lower.contains("peer")
1554        || lower.contains("address")
1555        || lower.contains("timeout")
1556        || lower.contains("route")
1557        || lower.contains("connection")
1558    {
1559        ErrorKind::Transport
1560    } else if lower.contains("invalid")
1561        || lower.contains("requires")
1562        || lower.contains("must ")
1563        || lower.contains("unknown")
1564    {
1565        ErrorKind::InvalidInput
1566    } else {
1567        ErrorKind::Internal
1568    };
1569    error(kind, message)
1570}
1571
1572fn create_required_secret(
1573    secret: Option<&[u8; 32]>,
1574    name: &str,
1575    create: fn(&[u8; 32]) -> std::result::Result<i64, String>,
1576) -> Result<i64> {
1577    let secret = secret
1578        .ok_or_else(|| error(ErrorKind::InvalidInput, format!("{name} requires a secret")))?;
1579    create(secret).map_err(|message| map_error(&message))
1580}