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 no capture of its own; run `heddle capture -m \"...\"` in its checkout, then push again"
115    )]
116    ThreadCaptureRequired { thread: String },
117
118    #[error(
119        "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"
120    )]
121    PublicationLimitExceeded {
122        thread: String,
123        states: usize,
124        operations: usize,
125        limit_name: &'static str,
126        limit: usize,
127        actual: usize,
128    },
129
130    #[error(
131        "Thread {thread} operation {operation} requires {bytes} encoded bytes; one publication batch allows {batch_limit} bytes and the negotiated frame allows {frame_limit} bytes"
132    )]
133    PublicationOperationTooLarge {
134        thread: String,
135        operation: usize,
136        bytes: usize,
137        batch_limit: usize,
138        frame_limit: usize,
139    },
140
141    #[error("remote error: {0}")]
142    Remote(String),
143
144    #[error("remote failure ({code:?}): {message}")]
145    RemoteFailure {
146        code: RemoteFailureCode,
147        message: String,
148        details: Vec<RemoteFailureDetail>,
149    },
150
151    #[error("lock error: {0}")]
152    LockError(String),
153}
154
155impl From<rmp_serde::encode::Error> for ProtocolError {
156    fn from(e: rmp_serde::encode::Error) -> Self {
157        ProtocolError::Serialization(e.to_string())
158    }
159}
160
161impl From<rmp_serde::decode::Error> for ProtocolError {
162    fn from(e: rmp_serde::decode::Error) -> Self {
163        ProtocolError::Serialization(e.to_string())
164    }
165}
166
167impl From<objects::error::HeddleError> for ProtocolError {
168    fn from(e: objects::error::HeddleError) -> Self {
169        match &e {
170            // Missing objects must surface as NotFound, not degrade to a
171            // generic server error via the blanket Remote arm below.
172            objects::error::HeddleError::NotFound(_)
173            | objects::error::HeddleError::StateNotFound(_)
174            | objects::error::HeddleError::MissingObject { .. } => {
175                ProtocolError::ObjectNotFound(e.to_string())
176            }
177            _ => ProtocolError::Remote(e.to_string()),
178        }
179    }
180}
181
182impl ProtocolError {
183    pub fn client_message(&self) -> String {
184        match self {
185            ProtocolError::Io(_) => "network error".to_string(),
186            ProtocolError::Serialization(_) => "protocol error".to_string(),
187            ProtocolError::MessageTooLarge { .. } => "message too large".to_string(),
188            ProtocolError::InvalidMessageType(_) => "protocol error".to_string(),
189            ProtocolError::VersionMismatch { .. } => "protocol version mismatch".to_string(),
190            ProtocolError::CapabilityNotSupported(_) => "capability not supported".to_string(),
191            ProtocolError::AuthenticationFailed(_) => "permission denied".to_string(),
192            ProtocolError::AuthorizationFailed(_) => "permission denied".to_string(),
193            ProtocolError::ObjectNotFound(_) => "object not found".to_string(),
194            ProtocolError::AlreadyExists(_) => "resource already exists".to_string(),
195            ProtocolError::InvalidState(_) => "invalid request state".to_string(),
196            ProtocolError::ThreadCaptureRequired { .. } => self.to_string(),
197            ProtocolError::PublicationLimitExceeded { .. }
198            | ProtocolError::PublicationOperationTooLarge { .. } => self.to_string(),
199            ProtocolError::Remote(_) => "internal server error".to_string(),
200            ProtocolError::RemoteFailure { message, .. } => message.clone(),
201            ProtocolError::LockError(_) => "internal server error".to_string(),
202        }
203    }
204
205    pub fn error_code(&self) -> ErrorCode {
206        match self {
207            ProtocolError::Io(_) => ErrorCode::Network,
208            ProtocolError::Serialization(_) => ErrorCode::Protocol,
209            ProtocolError::MessageTooLarge { .. } => ErrorCode::Protocol,
210            ProtocolError::InvalidMessageType(_) => ErrorCode::Protocol,
211            ProtocolError::VersionMismatch { .. } => ErrorCode::Protocol,
212            ProtocolError::CapabilityNotSupported(_) => ErrorCode::Protocol,
213            ProtocolError::AuthenticationFailed(_) => ErrorCode::PermissionDenied,
214            ProtocolError::AuthorizationFailed(_) => ErrorCode::PermissionDenied,
215            ProtocolError::ObjectNotFound(_) => ErrorCode::NotFound,
216            ProtocolError::AlreadyExists(_) => ErrorCode::InvalidArgument,
217            ProtocolError::InvalidState(_) => ErrorCode::InvalidArgument,
218            ProtocolError::ThreadCaptureRequired { .. } => ErrorCode::InvalidArgument,
219            ProtocolError::PublicationLimitExceeded { .. }
220            | ProtocolError::PublicationOperationTooLarge { .. } => ErrorCode::InvalidArgument,
221            ProtocolError::Remote(_) => ErrorCode::Server,
222            ProtocolError::RemoteFailure { code, .. } => match code {
223                RemoteFailureCode::InvalidArgument
224                | RemoteFailureCode::AlreadyExists
225                | RemoteFailureCode::FailedPrecondition
226                | RemoteFailureCode::OutOfRange => ErrorCode::InvalidArgument,
227                RemoteFailureCode::NotFound => ErrorCode::NotFound,
228                RemoteFailureCode::PermissionDenied | RemoteFailureCode::Unauthenticated => {
229                    ErrorCode::PermissionDenied
230                }
231                RemoteFailureCode::DeadlineExceeded
232                | RemoteFailureCode::ResourceExhausted
233                | RemoteFailureCode::Aborted
234                | RemoteFailureCode::Unavailable
235                | RemoteFailureCode::Cancelled => ErrorCode::Network,
236                RemoteFailureCode::Unspecified
237                | RemoteFailureCode::Unknown
238                | RemoteFailureCode::Unimplemented
239                | RemoteFailureCode::Internal
240                | RemoteFailureCode::DataLoss => ErrorCode::Server,
241            },
242            ProtocolError::LockError(_) => ErrorCode::Server,
243        }
244    }
245
246    pub fn to_wire_error(&self, details: Option<String>) -> Error {
247        Error {
248            code: self.error_code(),
249            message: self.client_message(),
250            details,
251        }
252    }
253}
254
255pub type Result<T> = std::result::Result<T, ProtocolError>;
256
257#[cfg(test)]
258mod tests {
259    use std::io;
260
261    use super::{ErrorCode, ProtocolError, RemoteFailureCode};
262
263    #[test]
264    fn missing_object_errors_surface_as_not_found() {
265        use objects::error::HeddleError;
266
267        let cases = vec![
268            HeddleError::NotFound("blob missing".to_string()),
269            HeddleError::StateNotFound(objects::object::StateId::from_content_hash(
270                objects::object::ContentHash::compute(b"missing"),
271            )),
272            HeddleError::MissingObject {
273                object_type: "tree".to_string(),
274                id: "abc123".to_string(),
275            },
276        ];
277        for err in cases {
278            let protocol_error = ProtocolError::from(err);
279            assert_eq!(
280                protocol_error.error_code(),
281                ErrorCode::NotFound,
282                "missing-object errors must surface as NotFound, got {protocol_error:?}"
283            );
284            assert!(
285                !matches!(protocol_error, ProtocolError::Remote(_)),
286                "missing-object errors must not degrade to Remote/Server"
287            );
288        }
289    }
290
291    #[test]
292    fn protocol_error_public_mapping_is_stable() {
293        let cases = vec![
294            (
295                ProtocolError::Io(io::Error::new(io::ErrorKind::TimedOut, "timeout")),
296                "network error",
297                ErrorCode::Network,
298            ),
299            (
300                ProtocolError::Serialization("bad msgpack".to_string()),
301                "protocol error",
302                ErrorCode::Protocol,
303            ),
304            (
305                ProtocolError::MessageTooLarge { size: 65, max: 64 },
306                "message too large",
307                ErrorCode::Protocol,
308            ),
309            (
310                ProtocolError::InvalidMessageType(42),
311                "protocol error",
312                ErrorCode::Protocol,
313            ),
314            (
315                ProtocolError::VersionMismatch {
316                    server: 2,
317                    client: 1,
318                },
319                "protocol version mismatch",
320                ErrorCode::Protocol,
321            ),
322            (
323                ProtocolError::CapabilityNotSupported("pack-v2".to_string()),
324                "capability not supported",
325                ErrorCode::Protocol,
326            ),
327            (
328                ProtocolError::AuthenticationFailed("bad token".to_string()),
329                "permission denied",
330                ErrorCode::PermissionDenied,
331            ),
332            (
333                ProtocolError::AuthorizationFailed("missing grant".to_string()),
334                "permission denied",
335                ErrorCode::PermissionDenied,
336            ),
337            (
338                ProtocolError::ObjectNotFound("abc123".to_string()),
339                "object not found",
340                ErrorCode::NotFound,
341            ),
342            (
343                ProtocolError::AlreadyExists("__users/luke/repo".to_string()),
344                "resource already exists",
345                ErrorCode::InvalidArgument,
346            ),
347            (
348                ProtocolError::InvalidState("bad resume".to_string()),
349                "invalid request state",
350                ErrorCode::InvalidArgument,
351            ),
352            (
353                ProtocolError::Remote("database unavailable".to_string()),
354                "internal server error",
355                ErrorCode::Server,
356            ),
357            (
358                ProtocolError::RemoteFailure {
359                    code: RemoteFailureCode::InvalidArgument,
360                    message: "server supplied message".to_string(),
361                    details: Vec::new(),
362                },
363                "server supplied message",
364                ErrorCode::InvalidArgument,
365            ),
366            (
367                ProtocolError::LockError("ref locked".to_string()),
368                "internal server error",
369                ErrorCode::Server,
370            ),
371        ];
372
373        for (error, expected_message, expected_code) in cases {
374            assert_eq!(error.client_message(), expected_message);
375            assert_eq!(error.error_code(), expected_code);
376
377            let wire_error = error.to_wire_error(Some("trace id".to_string()));
378            assert_eq!(wire_error.code, expected_code);
379            assert_eq!(wire_error.message, expected_message);
380            assert_eq!(wire_error.details.as_deref(), Some("trace id"));
381        }
382    }
383}