Skip to main content

wire/
lib.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Shared protocol/auth transport types.
3//! Live authorization scope rules are owned by weft-server/src/access/scope.rs.
4
5#[cfg(test)]
6mod auth_tests;
7mod auth_token;
8mod key_binding;
9mod message_hosted;
10mod message_objects;
11mod message_pushpull;
12mod message_refs;
13mod message_status;
14mod native_pack;
15mod object_transfer;
16mod provider_pack;
17mod semantic_graph;
18
19pub use auth_token::AuthToken;
20pub use key_binding::{
21    WireKeyBinding, WireKeyBindingLiveness, WireKeyBindingRegistry, decode_key_binding_registry,
22    encode_key_binding_registry,
23};
24pub use message_hosted::{
25    HarnessIdentity, HostedGrantInfo, HostedNamespaceInfo, HostedRepositoryInfo, HostedSpoolInfo,
26    HostedSpoolKind, ProgressCheckpoint, SessionDiffSummary, SessionReportEnvelope,
27    TranscriptAttachmentRef, UsageTotals, WorktreeChangeBaseline,
28};
29pub use message_objects::{ObjectData, ObjectRequest};
30pub use message_pushpull::{PullComplete, PushComplete};
31pub use message_refs::{
32    AdvertisedRef, AdvertisedRefError, HeadInfo, RefEntry, RefFilter, RefKind, RefUpdated,
33};
34pub use message_status::{
35    Error, ErrorCode, RemoteCursorFailure, RemoteCursorReason, RemoteDuration, RemoteFailureCode,
36    RemoteFailureDetail, RemoteTimestamp,
37};
38pub use native_pack::{
39    GitPackChunkState, GrowingPackChunkReader, MAX_RECEIVED_GIT_PACK_SIZE,
40    MAX_RECEIVED_PACK_INDEX_SIZE, MAX_RECEIVED_PACK_SIZE, NativePackBundle, NativePackFileBundle,
41    NativePackStreamingWriter, PackChunkSpool, PackChunkState, PackFileChunkReader,
42    build_native_pack, install_received_pack, is_native_packable_object_type,
43    native_pack_excluded_object_types, next_pack_chunk, receive_pack_chunk,
44    reuse_native_pack_encoded_subset_in,
45};
46pub use object_transfer::{
47    MAX_PULL_FRAME_MESSAGE_SIZE, MAX_RECEIVED_REDACTIONS_BLOB_SIZE,
48    MAX_RECEIVED_STATE_VISIBILITY_BLOB_SIZE, admit_declared_received_len,
49    check_received_transfer_blob_size, chunk_bounds, chunk_count, chunk_offset, load_object_data,
50    load_requested_object, store_received_object,
51};
52pub use objects::transfer::{
53    GitLaneTransferIntent, ObjectAvailabilityPlan, ObjectId, ObjectInfo, ObjectType,
54    ObjectTypeBucket, PlannedObject, RepositoryTransferPlan, StateClosureOptions,
55    TransferPartitions, TransferPlanStats, enumerate_state_closure, enumerate_state_closure_plan,
56    enumerate_state_closure_plan_with_options, enumerate_state_closure_transfer_from_boundaries,
57    enumerate_state_closure_transfer_with_options, enumerate_state_closure_with_options,
58    has_object, is_ancestor, missing_blobs_in_tree, plan_object_availability,
59};
60pub use provider_pack::{
61    CompletedProviderPack, ProviderPackBundle, ProviderPackExtent, ProviderPackIndexEntry,
62    ProviderPackManifest, ProviderPackSpool, ProviderPackWriter, assemble_provider_pack,
63};
64pub use semantic_graph::{
65    SemanticGraphQueryKind, SemanticGraphQueryRequest, SemanticGraphQueryResponse, SemanticGraphRef,
66};
67
68/// Default port for Heddle protocol.
69pub const DEFAULT_PORT: u16 = 8421;
70
71/// Protocol version.
72pub const PROTOCOL_VERSION: u32 = 1;
73
74/// Maximum message size (64 MB).
75pub const MAX_MESSAGE_SIZE: usize = 64 * 1024 * 1024;
76
77/// Error type for protocol operations.
78#[derive(Debug, thiserror::Error)]
79pub enum ProtocolError {
80    #[error("io error: {0}")]
81    Io(#[from] std::io::Error),
82
83    #[error("serialization error: {0}")]
84    Serialization(String),
85
86    #[error("message too large: {size} bytes (max {max})")]
87    MessageTooLarge { size: usize, max: usize },
88
89    #[error("invalid message type: {0}")]
90    InvalidMessageType(u8),
91
92    #[error("protocol version mismatch: server={server}, client={client}")]
93    VersionMismatch { server: u32, client: u32 },
94
95    #[error("capability not supported: {0}")]
96    CapabilityNotSupported(String),
97
98    #[error("authentication failed: {0}")]
99    AuthenticationFailed(String),
100
101    #[error("authorization failed: {0}")]
102    AuthorizationFailed(String),
103
104    #[error("object not found: {0}")]
105    ObjectNotFound(String),
106
107    #[error("already exists: {0}")]
108    AlreadyExists(String),
109
110    #[error("invalid state: {0}")]
111    InvalidState(String),
112
113    #[error(
114        "Thread {thread} has {states} States and {operations} operations; {limit_name} limit is {limit}, required {actual}. Very large histories need server-side incremental admission (HeddleCo/weft#2432) or hosted import"
115    )]
116    PublicationLimitExceeded {
117        thread: String,
118        states: usize,
119        operations: usize,
120        limit_name: &'static str,
121        limit: usize,
122        actual: usize,
123    },
124
125    #[error(
126        "Thread {thread} operation {operation} requires {bytes} encoded bytes; one publication batch allows {batch_limit} bytes and the negotiated frame allows {frame_limit} bytes"
127    )]
128    PublicationOperationTooLarge {
129        thread: String,
130        operation: usize,
131        bytes: usize,
132        batch_limit: usize,
133        frame_limit: usize,
134    },
135
136    #[error("remote error: {0}")]
137    Remote(String),
138
139    #[error("remote failure ({code:?}): {message}")]
140    RemoteFailure {
141        code: RemoteFailureCode,
142        message: String,
143        details: Vec<RemoteFailureDetail>,
144    },
145
146    #[error("lock error: {0}")]
147    LockError(String),
148}
149
150impl From<rmp_serde::encode::Error> for ProtocolError {
151    fn from(e: rmp_serde::encode::Error) -> Self {
152        ProtocolError::Serialization(e.to_string())
153    }
154}
155
156impl From<rmp_serde::decode::Error> for ProtocolError {
157    fn from(e: rmp_serde::decode::Error) -> Self {
158        ProtocolError::Serialization(e.to_string())
159    }
160}
161
162impl From<objects::error::HeddleError> for ProtocolError {
163    fn from(e: objects::error::HeddleError) -> Self {
164        match &e {
165            // Missing objects must surface as NotFound, not degrade to a
166            // generic server error via the blanket Remote arm below.
167            objects::error::HeddleError::NotFound(_)
168            | objects::error::HeddleError::StateNotFound(_)
169            | objects::error::HeddleError::MissingObject { .. } => {
170                ProtocolError::ObjectNotFound(e.to_string())
171            }
172            _ => ProtocolError::Remote(e.to_string()),
173        }
174    }
175}
176
177impl ProtocolError {
178    pub fn client_message(&self) -> String {
179        match self {
180            ProtocolError::Io(_) => "network error".to_string(),
181            ProtocolError::Serialization(_) => "protocol error".to_string(),
182            ProtocolError::MessageTooLarge { .. } => "message too large".to_string(),
183            ProtocolError::InvalidMessageType(_) => "protocol error".to_string(),
184            ProtocolError::VersionMismatch { .. } => "protocol version mismatch".to_string(),
185            ProtocolError::CapabilityNotSupported(_) => "capability not supported".to_string(),
186            ProtocolError::AuthenticationFailed(_) => "permission denied".to_string(),
187            ProtocolError::AuthorizationFailed(_) => "permission denied".to_string(),
188            ProtocolError::ObjectNotFound(_) => "object not found".to_string(),
189            ProtocolError::AlreadyExists(_) => "resource already exists".to_string(),
190            ProtocolError::InvalidState(_) => "invalid request state".to_string(),
191            ProtocolError::PublicationLimitExceeded { .. }
192            | ProtocolError::PublicationOperationTooLarge { .. } => self.to_string(),
193            ProtocolError::Remote(_) => "internal server error".to_string(),
194            ProtocolError::RemoteFailure { message, .. } => message.clone(),
195            ProtocolError::LockError(_) => "internal server error".to_string(),
196        }
197    }
198
199    pub fn error_code(&self) -> ErrorCode {
200        match self {
201            ProtocolError::Io(_) => ErrorCode::Network,
202            ProtocolError::Serialization(_) => ErrorCode::Protocol,
203            ProtocolError::MessageTooLarge { .. } => ErrorCode::Protocol,
204            ProtocolError::InvalidMessageType(_) => ErrorCode::Protocol,
205            ProtocolError::VersionMismatch { .. } => ErrorCode::Protocol,
206            ProtocolError::CapabilityNotSupported(_) => ErrorCode::Protocol,
207            ProtocolError::AuthenticationFailed(_) => ErrorCode::PermissionDenied,
208            ProtocolError::AuthorizationFailed(_) => ErrorCode::PermissionDenied,
209            ProtocolError::ObjectNotFound(_) => ErrorCode::NotFound,
210            ProtocolError::AlreadyExists(_) => ErrorCode::InvalidArgument,
211            ProtocolError::InvalidState(_) => ErrorCode::InvalidArgument,
212            ProtocolError::PublicationLimitExceeded { .. }
213            | ProtocolError::PublicationOperationTooLarge { .. } => ErrorCode::InvalidArgument,
214            ProtocolError::Remote(_) => ErrorCode::Server,
215            ProtocolError::RemoteFailure { code, .. } => match code {
216                RemoteFailureCode::InvalidArgument
217                | RemoteFailureCode::AlreadyExists
218                | RemoteFailureCode::FailedPrecondition
219                | RemoteFailureCode::OutOfRange => ErrorCode::InvalidArgument,
220                RemoteFailureCode::NotFound => ErrorCode::NotFound,
221                RemoteFailureCode::PermissionDenied | RemoteFailureCode::Unauthenticated => {
222                    ErrorCode::PermissionDenied
223                }
224                RemoteFailureCode::DeadlineExceeded
225                | RemoteFailureCode::ResourceExhausted
226                | RemoteFailureCode::Aborted
227                | RemoteFailureCode::Unavailable
228                | RemoteFailureCode::Cancelled => ErrorCode::Network,
229                RemoteFailureCode::Unspecified
230                | RemoteFailureCode::Unknown
231                | RemoteFailureCode::Unimplemented
232                | RemoteFailureCode::Internal
233                | RemoteFailureCode::DataLoss => ErrorCode::Server,
234            },
235            ProtocolError::LockError(_) => ErrorCode::Server,
236        }
237    }
238
239    pub fn to_wire_error(&self, details: Option<String>) -> Error {
240        Error {
241            code: self.error_code(),
242            message: self.client_message(),
243            details,
244        }
245    }
246}
247
248pub type Result<T> = std::result::Result<T, ProtocolError>;
249
250#[cfg(test)]
251mod tests {
252    use std::io;
253
254    use super::{ErrorCode, ProtocolError, RemoteFailureCode};
255
256    #[test]
257    fn missing_object_errors_surface_as_not_found() {
258        use objects::error::HeddleError;
259
260        let cases = vec![
261            HeddleError::NotFound("blob missing".to_string()),
262            HeddleError::StateNotFound(objects::object::StateId::from_content_hash(
263                objects::object::ContentHash::compute(b"missing"),
264            )),
265            HeddleError::MissingObject {
266                object_type: "tree".to_string(),
267                id: "abc123".to_string(),
268            },
269        ];
270        for err in cases {
271            let protocol_error = ProtocolError::from(err);
272            assert_eq!(
273                protocol_error.error_code(),
274                ErrorCode::NotFound,
275                "missing-object errors must surface as NotFound, got {protocol_error:?}"
276            );
277            assert!(
278                !matches!(protocol_error, ProtocolError::Remote(_)),
279                "missing-object errors must not degrade to Remote/Server"
280            );
281        }
282    }
283
284    #[test]
285    fn protocol_error_public_mapping_is_stable() {
286        let cases = vec![
287            (
288                ProtocolError::Io(io::Error::new(io::ErrorKind::TimedOut, "timeout")),
289                "network error",
290                ErrorCode::Network,
291            ),
292            (
293                ProtocolError::Serialization("bad msgpack".to_string()),
294                "protocol error",
295                ErrorCode::Protocol,
296            ),
297            (
298                ProtocolError::MessageTooLarge { size: 65, max: 64 },
299                "message too large",
300                ErrorCode::Protocol,
301            ),
302            (
303                ProtocolError::InvalidMessageType(42),
304                "protocol error",
305                ErrorCode::Protocol,
306            ),
307            (
308                ProtocolError::VersionMismatch {
309                    server: 2,
310                    client: 1,
311                },
312                "protocol version mismatch",
313                ErrorCode::Protocol,
314            ),
315            (
316                ProtocolError::CapabilityNotSupported("pack-v2".to_string()),
317                "capability not supported",
318                ErrorCode::Protocol,
319            ),
320            (
321                ProtocolError::AuthenticationFailed("bad token".to_string()),
322                "permission denied",
323                ErrorCode::PermissionDenied,
324            ),
325            (
326                ProtocolError::AuthorizationFailed("missing grant".to_string()),
327                "permission denied",
328                ErrorCode::PermissionDenied,
329            ),
330            (
331                ProtocolError::ObjectNotFound("abc123".to_string()),
332                "object not found",
333                ErrorCode::NotFound,
334            ),
335            (
336                ProtocolError::AlreadyExists("__users/luke/repo".to_string()),
337                "resource already exists",
338                ErrorCode::InvalidArgument,
339            ),
340            (
341                ProtocolError::InvalidState("bad resume".to_string()),
342                "invalid request state",
343                ErrorCode::InvalidArgument,
344            ),
345            (
346                ProtocolError::Remote("database unavailable".to_string()),
347                "internal server error",
348                ErrorCode::Server,
349            ),
350            (
351                ProtocolError::RemoteFailure {
352                    code: RemoteFailureCode::InvalidArgument,
353                    message: "server supplied message".to_string(),
354                    details: Vec::new(),
355                },
356                "server supplied message",
357                ErrorCode::InvalidArgument,
358            ),
359            (
360                ProtocolError::LockError("ref locked".to_string()),
361                "internal server error",
362                ErrorCode::Server,
363            ),
364        ];
365
366        for (error, expected_message, expected_code) in cases {
367            assert_eq!(error.client_message(), expected_message);
368            assert_eq!(error.error_code(), expected_code);
369
370            let wire_error = error.to_wire_error(Some("trace id".to_string()));
371            assert_eq!(wire_error.code, expected_code);
372            assert_eq!(wire_error.message, expected_message);
373            assert_eq!(wire_error.details.as_deref(), Some("trace id"));
374        }
375    }
376}