Skip to main content

hyprstream_core/services/
mod.rs

1//! Service layer for hyprstream
2//!
3//! This module provides services for inference and registry operations.
4//! Services use Cap'n Proto for serialization via moq-net + UDS transport.
5//!
6//! # Security
7//!
8//! All requests are wrapped in `SignedEnvelope` for authentication:
9//! - `process_request` verifies Ed25519 signatures before dispatching
10//! - Handlers receive `EnvelopeContext` with verified identity
11//! - Services use `ctx.subject()` for policy checks and resource isolation
12//!
13//! # Architecture
14//!
15//! ```text
16//! ┌─────────────────────────────────────────────────────────────┐
17//! │  hyprstream/src/services/                                   │
18//! │  ├── core.rs      ← RequestService trait re-exports           │
19//! │  ├── types.rs     ← Shared types (FsDirEntry, ModelInfo, etc.)│
20//! │  ├── registry.rs  ← Registry server                        │
21//! │  └── inference.rs ← Inference server                       │
22//! └─────────────────────────────────────────────────────────────┘
23//! ```
24//!
25//! # Usage
26//!
27//! Services implement `RequestService` and are automatically `Spawnable` via blanket impl:
28//!
29//! ```rust,ignore
30//! use crate::services::{EnvelopeContext, RequestService};
31//! use hyprstream_rpc::prelude::*;
32//! use hyprstream_rpc::transport::TransportConfig;
33//!
34//! struct MyService {
35//!     transport: TransportConfig,
36//!     signing_key: SigningKey,
37//! }
38//!
39//! impl RequestService for MyService {
40//!     async fn handle_request(&self, ctx: &EnvelopeContext, payload: &[u8]) -> Result<(Vec<u8>, Option<Continuation>)> {
41//!         println!("Request from: {}", ctx.subject());
42//!         Ok((vec![], None))
43//!     }
44//!
45//!     fn name(&self) -> &str { "my-service" }
46//!     fn transport(&self) -> &TransportConfig { &self.transport }
47//!     fn signing_key(&self) -> SigningKey { self.signing_key.clone() }
48//! }
49//!
50//! let service = MyService { transport, signing_key };
51//! let manager = InprocManager::new();
52//! let handle = manager.spawn(Box::new(service)).await?;
53//!
54//! // Connect a client (signing is automatic)
55//! let client = ZmqClient::new("inproc://my-service", context, signing_key, identity);
56//! let response = client.call(payload, None).await?;
57//!
58//! // Stop the service
59//! handle.stop().await;
60//! ```
61
62mod core;
63mod types;
64use hyprstream_rpc_std::{discovery_client::DiscoveryClient, policy_client::PolicyClient};
65// 9P worktree convenience helpers moved to `hyprstream-inference` with the
66// training checkpoint path (Wave B); re-exported so existing
67// `crate::services::{StatResult, WorktreeClientExt}` paths keep resolving.
68pub use hyprstream_inference::worktree_ext::StatResult;
69pub(crate) use hyprstream_inference::worktree_ext::WorktreeClientExt;
70// contained_root replaced by hyprstream-containedfs crate
71#[cfg(feature = "rocksdb")]
72pub mod at9p_renewal;
73pub mod discovery;
74pub mod editing;
75pub mod factories;
76#[cfg(feature = "metrics")]
77pub mod flight;
78pub mod fs;
79pub mod generated;
80#[cfg(feature = "oci-image")]
81pub mod image_substrate;
82pub mod inference;
83pub mod kata_9p_backend;
84pub mod mcp_service;
85#[cfg(feature = "metrics")]
86pub mod metrics;
87pub mod model;
88pub mod namespace_builder;
89pub mod native_event_policy;
90pub mod ninep_bridge;
91pub mod oai;
92pub mod oauth;
93pub mod policy;
94pub mod public_repo;
95pub mod registry;
96pub mod remote_mount;
97pub mod remote_registry_mount;
98pub mod revocation;
99pub mod router;
100pub mod rpc_types;
101pub mod typed;
102pub mod worker;
103pub mod xet;
104pub mod xet_provenance;
105
106#[cfg(test)]
107pub(crate) mod restart_diag {
108    use std::sync::atomic::{AtomicBool, Ordering};
109    use std::sync::OnceLock;
110    use std::time::Instant;
111
112    static ENABLED: AtomicBool = AtomicBool::new(false);
113    static STARTED: OnceLock<Instant> = OnceLock::new();
114
115    pub(crate) fn enable() {
116        STARTED.get_or_init(Instant::now);
117        ENABLED.store(true, Ordering::Release);
118    }
119
120    pub(crate) fn phase(label: &'static str) {
121        if !ENABLED.load(Ordering::Acquire) {
122            return;
123        }
124        let elapsed_ms = STARTED
125            .get()
126            .map_or(0, |started| started.elapsed().as_millis());
127        let mut stderr = std::io::stderr().lock();
128        let _ = std::io::Write::write_fmt(
129            &mut stderr,
130            format_args!("RESTART_DIAG_PHASE={label} elapsed_ms={elapsed_ms}\n"),
131        );
132        let _ = std::io::Write::flush(&mut stderr);
133    }
134}
135
136// Postgres-backed PDS record store (#1257) — gated behind `pds-postgres`.
137// When a `[rds]` config section is present, the factory selects this backend;
138// otherwise the RocksDB local backend is used. D2 invariant: signed bytes are
139// the source of truth, SQL is a projection-free KV shell.
140#[cfg(feature = "pds-postgres")]
141pub(crate) mod pds_record_pg;
142// The PDS record store's local RocksDB backend + publisher/resolver/ingest
143// stack (the `rocksdb` feature, valkey precedent). Re-exported through
144// `services::discovery` so callers keep their paths.
145#[cfg(feature = "rocksdb")]
146pub(crate) mod pds_record_rocksdb;
147
148/// Phase-1 cellular-ledger local-enforcer (epic #922, #925). Gated behind the
149/// `ledger` cargo feature, default off — the scheduler quota path is unchanged
150/// until an operator opts in.
151#[cfg(feature = "ledger")]
152pub mod ledger;
153
154/// Settlement/tariff service (#1399). Behind the `pay` cargo feature.
155/// Implements the MIT `hyprstream_pay` traits with AGPL service logic.
156#[cfg(feature = "pay")]
157pub mod pay;
158
159pub use core::{Continuation, EnvelopeContext, RequestService};
160
161// Remaining domain types
162pub use types::{
163    FsDirEntryInfo, DEFAULT_IOUNIT, DMDIR, MAX_FDS_GLOBAL, MAX_FDS_PER_CLIENT, MAX_FS_IO_SIZE,
164    MAX_IOUNIT, ORCLOSE, ORDWR, OREAD, OTRUNC, OWRITE, QTDIR, QTFILE,
165};
166// Open mode constants also re-exported from hyprstream-vfs::mount for VFS consumers.
167
168pub use discovery::DiscoveryService;
169#[cfg(feature = "metrics")]
170pub use flight::FlightService;
171#[cfg(feature = "oci-image")]
172pub use image_substrate::{
173    create_image_substrate_router, ImageSubstratePolicy, ImageSubstrateState,
174};
175pub use inference::{InferenceService, InferenceServiceConfig, INFERENCE_ENDPOINT};
176pub use model::{ModelService, ModelServiceConfig, StagingModelPin, MODEL_ENDPOINT};
177pub use namespace_builder::{build_standard_namespace, StandardNamespaceConfig};
178pub use oai::OAIService;
179#[cfg(test)]
180pub(crate) use oai::{
181    await_required_native_dependencies as oai_await_required_native_dependencies,
182    healthy_registry as oai_healthy_registry,
183    prove_model_reachability_denial as oai_prove_model_reachability_denial,
184};
185pub use oauth::OAuthService;
186pub use policy::PolicyService;
187pub use registry::RegistryService;
188pub use worker::build_authorize_fn;
189pub use xet::{XetService, XetState};
190
191/// Construct on the caller's runtime, using the authenticated process profile.
192pub fn policy_client_for_process(
193    signing_key: ed25519_dalek::SigningKey,
194    compatibility_key: ed25519_dalek::VerifyingKey,
195    token: Option<String>,
196) -> anyhow::Result<PolicyClient> {
197    if hyprstream_discovery::native_network_required() {
198        PolicyClient::from_provider(
199            &hyprstream_discovery::ProductionRpcClientProvider,
200            signing_key,
201            token,
202        )
203    } else {
204        PolicyClient::for_local_bootstrap(signing_key, compatibility_key, token)
205    }
206}
207
208/// Discovery's required reach/evidence comes from the checkpoint-backed resolver.
209pub fn discovery_client_for_process(
210    signing_key: ed25519_dalek::SigningKey,
211    compatibility_key: ed25519_dalek::VerifyingKey,
212    token: Option<String>,
213) -> anyhow::Result<DiscoveryClient> {
214    if hyprstream_discovery::native_network_required() {
215        DiscoveryClient::from_provider(
216            &hyprstream_discovery::ProductionRpcClientProvider,
217            signing_key,
218            token,
219        )
220    } else {
221        DiscoveryClient::for_local_bootstrap(signing_key, compatibility_key, token)
222    }
223}
224pub use mcp_service::{McpConfig, McpService};
225#[cfg(feature = "metrics")]
226pub use metrics::MetricsService;
227
228/// Authenticated Event transport and profile-aware initialization.
229pub mod event_network;
230
231/// Native producer/Streams carrier admission and lifecycle.
232pub mod stream_network;