1 //! `serve()`: the server half of the wire.2 //!3 //! One reader owns the socket. One worker per job owns the model. The reader4 //! never blocks on a worker, because a worker that waits for credit would5 //! otherwise wait for the very frame the reader is not reading. Protocol.md6 //! section 8, rule 2.7 //!8 //! Every write goes through one mutex, so the frames of one stream reach the9 //! wire in one order and never interleave with another stream's frames.10 11 use std::collections::{BTreeMap, HashMap};12 use std::fs::File;13 use std::io;14 use std::net::Shutdown;15 use std::os::fd::{AsFd, BorrowedFd, OwnedFd};16 use std::os::unix::net::UnixStream;17 use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};18 use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, Weak};19 use std::thread;20 use std::time::{Duration, Instant};21 22 use inf3r_proto::body::{self, Body, Catalogue, Grant, Ready, Refusal, Welcome};23 use inf3r_proto::{Emit, Header, Job, Kind, Role, Session, recv_frame, send_frame};24 25 use crate::cache::{CacheCodec, CacheFile, CacheTransport, CacheWrite, Reserve};26 use crate::capability::{Artifact, Failure, Part, PartBody, Report, Request};27 use crate::emitter::{EmitError, Emitter};28 29 /// The highest version this build speaks; a Wire 1 peer still negotiates down.30 const PROTOCOL_VERSION: u32 = 2;31 const MIN_PROTOCOL_VERSION: u32 = 1;32 33 /// The foreign runtime that a plugin's binding was built against.34 ///35 /// The core cannot see a hand-built library in `Cargo.lock`, so `launch`36 /// compares this name and version with the runtime's own report before serving.37 #[derive(Clone, PartialEq, Eq, Debug)]38 pub struct RuntimeVersion {39 pub name: String,40 pub version: String,41 }42 43 /// What a plugin implements. The SDK calls one method per `open`.44 ///45 /// `run` takes `&self` so that one plugin can serve several jobs at once; the46 /// catalogue's `max_inflight` is the promise it makes to the core.47 pub trait Plugin: Send + Sync + 'static {48 /// The most jobs this plugin will run at the same time.49 fn max_inflight(&self) -> u16;50 /// The foreign runtime this binding needs, or `None` for pure Rust.51 fn runtime(&self) -> Option<RuntimeVersion> {52 None53 }54 /// The models, capabilities, and limits this plugin serves.55 fn catalogue(&self) -> Catalogue;56 /// The engine-specific cache codec, if this plugin persists KV state.57 fn cache(&self) -> Option<Arc<dyn CacheCodec>> {58 None59 }60 /// Loads what the grant names and reports the load time it measured.61 fn load(&self, grant: &Grant) -> Result<Ready, Failure>;62 /// Loads what the grant names, with the descriptors that it carried.63 ///64 /// A grant can hand a weight file over the socket, and only a plugin knows65 /// whether it needs those bytes instead of a path. The default drops them66 /// so an existing plugin keeps its `load`.67 fn load_fds(&self, grant: &Grant, fds: &[OwnedFd]) -> Result<Ready, Failure> {68 let _ = fds;69 self.load(grant)70 }71 /// Decides whether this job is acceptable before the SDK sends `accept`.72 ///73 /// The SDK has already checked the model, the capability, and the part74 /// kinds against the catalogue. This hook checks what only the plugin75 /// knows: parameter values, roles, and whether a descriptor holds what the76 /// capability expects. Returning `Err` sends `reject` in `OPEN`; the77 /// plugin's `run` is not called.78 fn admit(&self, _req: &Request<'_>) -> Result<(), Failure> {79 Ok(())80 }81 /// Runs one job.82 fn run(83 &self,84 capability: &str,85 req: Request<'_>,86 out: &mut dyn Emitter,87 ) -> Result<Report, Failure>;88 }89 90 /// Serves one connection until the peer closes it or the session ends.91 ///92 /// The returned `io::Result` is only about the transport. A job that fails is a93 /// `done{failed}`, not an error of this function.94 pub fn serve<P: Plugin>(socket: UnixStream, plugin: Arc<P>) -> io::Result<()> {95 let mut catalogue = plugin.catalogue();96 let codec = plugin.cache();97 if let Some(codec) = &codec98 && catalogue.cache.is_none()99 {100 catalogue.cache = Some(codec.spec());101 }102 let shared = Arc::new(Shared::new(socket.try_clone()?, catalogue));103 if let Some(codec) = &codec {104 let pipe: Arc<dyn CacheTransport> = Arc::new(CachePipe(Arc::downgrade(&shared)));105 codec.attach(pipe);106 let _ = shared.codec.set(Arc::clone(codec));107 }108 109 loop {110 if lock(&shared.session).is_closed() {111 break;112 }113 let (frame, fds) = match recv_frame(&socket) {114 Ok(Some(pair)) => pair,115 _ => {116 shared.failed.store(true, Ordering::SeqCst);117 break;118 }119 };120 let kind = frame.header.kind;121 let id = frame.header.stream;122 123 // An extension frame is read and dropped. R30: a peer that ignores the124 // whole range still completes every job.125 if kind.is_extension() {126 continue;127 }128 129 if inf3r_proto::session::is_session(kind) && lock(&shared.session).recv(kind).is_err() {130 fail(&shared, body::ErrorCode::Frame);131 break;132 }133 134 let body = match Body::decode(kind, &frame.payload) {135 Ok(body) => body,136 Err(_) => {137 fail(&shared, body::ErrorCode::Frame);138 break;139 }140 };141 142 match body {143 Body::Hello(hello) => {144 if hello.v.min > PROTOCOL_VERSION || hello.v.max < MIN_PROTOCOL_VERSION {145 fail(&shared, body::ErrorCode::Version);146 break;147 }148 let version = if hello.v.max >= 2 && hello.v.min <= 2 {149 2150 } else {151 1152 };153 shared.version.store(version, Ordering::SeqCst);154 record(&shared, Kind::Welcome);155 write_body(156 &shared,157 0,158 &Body::Welcome(Welcome {159 v: version,160 max_inflight: plugin.max_inflight(),161 }),162 &[],163 )?;164 let mut catalogue = shared.catalogue.clone();165 if version != 2 {166 // A Wire 1 peer never sees a cache declaration or a cache167 // frame. Negotiating down removes both from its view.168 catalogue.cache = None;169 }170 write_body(&shared, 0, &Body::Catalogue(catalogue), &[])?;171 record(&shared, Kind::Catalogue);172 }173 174 Body::Grant(grant) => match plugin.load_fds(&grant, &fds) {175 Ok(mut ready) => {176 if shared.version.load(Ordering::SeqCst) == 2177 && ready.cache_fingerprint.is_none()178 && let Some(codec) = shared.codec.get()179 {180 ready.cache_fingerprint = Some(codec.fingerprint());181 }182 record(&shared, Kind::Ready);183 write_body(&shared, 0, &Body::Ready(ready), &[])?184 }185 Err(failure) => {186 let refusal = Refusal {187 code: failure.code,188 detail: failure.detail.clone(),189 };190 write_body(&shared, 0, &Body::Fatal(refusal), &[])?;191 break;192 }193 },194 195 Body::Open(open) => {196 if id == 0 || shared.stream(id).is_some() {197 fail(&shared, body::ErrorCode::Stream);198 break;199 }200 shared.mark_opened(id);201 if !start(&shared, &plugin, id, open, fds)? {202 let refusal = Refusal {203 code: body::ErrorCode::Busy,204 detail: None,205 };206 write_body(&shared, id, &Body::Reject(refusal), &[])?;207 lock(&shared.session).finish_stream();208 }209 }210 211 Body::Window(window) => {212 let Some(stream) = shared.stream(id) else {213 if shared.ever_opened(id) {214 // The window crossed the terminal frame. The caller215 // could not know that the job had ended when it sent216 // it, and a closed stream takes no credit.217 continue;218 }219 fail(&shared, body::ErrorCode::Stream);220 break;221 };222 if stream.window(window.credit).is_err() {223 fail(&shared, body::ErrorCode::Credit);224 break;225 }226 }227 228 Body::Cancel(_) => {229 let Some(stream) = shared.stream(id) else {230 if shared.ever_opened(id) {231 // A cancel that crossed the terminal frame needs no232 // second terminal frame. Section 7 rule 4.233 continue;234 }235 fail(&shared, body::ErrorCode::Stream);236 break;237 };238 stream.cancel(&shared, id);239 }240 241 Body::CacheLookupRes(response) => {242 if !shared.cache_allowed() {243 fail(&shared, body::ErrorCode::Frame);244 break;245 }246 shared.cache_lookup_response(response, fds);247 }248 Body::CacheGrant(grant) => {249 if !shared.cache_allowed() {250 fail(&shared, body::ErrorCode::Frame);251 break;252 }253 shared.cache_grant_response(grant, fds);254 }255 Body::CacheFlush(flush) => {256 if !shared.cache_allowed() {257 fail(&shared, body::ErrorCode::Frame);258 break;259 }260 let codec = shared.codec.get().cloned();261 let reply = Arc::clone(&shared);262 thread::spawn(move || {263 let report = codec264 .map(|codec| codec.flush(Duration::from_millis(u64::from(flush.budget_ms))))265 .unwrap_or_default();266 let body = Body::CacheFlushed(body::CacheFlushed {267 req_id: flush.req_id,268 saved: report.saved,269 skipped: report.skipped,270 dirty_remaining: report.dirty_remaining,271 });272 let _ = write_body(&reply, 0, &body, &[]);273 });274 }275 Body::CacheLookup(_)276 | Body::CacheRelease(_)277 | Body::CacheReserve(_)278 | Body::CacheCommit(_)279 | Body::CacheFlushed(_) => {280 fail(&shared, body::ErrorCode::Frame);281 break;282 }283 Body::Ping(tick) => write_body(&shared, 0, &Body::Pong(tick), &[])?,284 Body::Pong(_) => {}285 286 Body::Bye(_) => {287 shared.draining.store(true, Ordering::SeqCst);288 }289 290 Body::Fatal(_) => {291 shared.failed.store(true, Ordering::SeqCst);292 break;293 }294 295 _ => {296 fail(&shared, body::ErrorCode::Frame);297 break;298 }299 }300 }301 302 shared.close_cache();303 if !shared.draining.load(Ordering::SeqCst) || shared.failed.load(Ordering::SeqCst) {304 shared.abort();305 }306 shared.wait_drained();307 Ok(())308 }309 310 /// The socket and the streams on it.311 struct Shared {312 session: Mutex<Session>,313 out: Mutex<UnixStream>,314 /// The catalogue is immutable for the life of the process. The SDK reads315 /// it once, for `welcome` and for the checks that precede `accept`.316 catalogue: Catalogue,317 streams: Mutex<HashMap<u16, Arc<Stream>>>,318 /// Every stream id that the caller has opened.319 ///320 /// A control frame for an ended stream is not unknown: it can cross the321 /// terminal frame in the other direction. Only an id that is not in this322 /// table was never opened, so only that one is `fatal{stream}`.323 seen: Mutex<Vec<bool>>,324 draining: AtomicBool,325 failed: AtomicBool,326 drained: Condvar,327 /// The negotiated wire version; cache frames are legal only at 2.328 version: AtomicU32,329 codec: OnceLock<Arc<dyn CacheCodec>>,330 cache_waiters: Mutex<BTreeMap<u64, Arc<CacheWaiter>>>,331 next_cache: AtomicU64,332 cache_closed: AtomicBool,333 }334 335 /// One synchronous cache request that a codec is waiting for.336 struct CacheWaiter {337 reply: Mutex<Option<CacheReply>>,338 wake: Condvar,339 }340 341 enum CacheReply {342 Lookup(Option<CacheFile>),343 Grant(Option<CacheWrite>),344 Error(String),345 }346 347 impl CacheWaiter {348 fn new() -> CacheWaiter {349 CacheWaiter {350 reply: Mutex::new(None),351 wake: Condvar::new(),352 }353 }354 355 fn set(&self, reply: CacheReply) {356 *lock(&self.reply) = Some(reply);357 self.wake.notify_all();358 }359 }360 361 /// A handle that the codec keeps. It upgrades the session only for the362 /// duration of one request, so the codec does not keep the session alive.363 struct CachePipe(Weak<Shared>);364 365 impl CacheTransport for CachePipe {366 fn lookup(367 &self,368 keys: &[[u8; 32]],369 lineage: Option<[u8; 32]>,370 timeout: Duration,371 ) -> io::Result<Option<CacheFile>> {372 let shared = self373 .0374 .upgrade()375 .ok_or_else(|| io::Error::other("the cache session closed"))?;376 if !shared.cache_allowed() {377 return Err(io::Error::other("cache frames require Wire 2"));378 }379 shared.request_lookup(keys, lineage, timeout)380 }381 382 fn reserve(&self, request: Reserve, timeout: Duration) -> io::Result<Option<CacheWrite>> {383 let shared = self384 .0385 .upgrade()386 .ok_or_else(|| io::Error::other("the cache session closed"))?;387 if !shared.cache_allowed() {388 return Err(io::Error::other("cache frames require Wire 2"));389 }390 shared.request_reserve(request, timeout)391 }392 393 fn release(&self, lease_id: u64, ok: bool, restore_ms: u32) -> io::Result<()> {394 let shared = self395 .0396 .upgrade()397 .ok_or_else(|| io::Error::other("the cache session closed"))?;398 if !shared.cache_allowed() {399 return Err(io::Error::other("cache frames require Wire 2"));400 }401 write_body(402 &shared,403 0,404 &Body::CacheRelease(body::CacheRelease {405 lease_id,406 ok,407 restore_ms,408 abandoned: false,409 }),410 &[],411 )412 }413 414 fn commit(415 &self,416 lease_id: u64,417 ok: bool,418 bytes: u64,419 crc32c: u32,420 token_count: u64,421 save_ms: u32,422 ) -> io::Result<()> {423 let shared = self424 .0425 .upgrade()426 .ok_or_else(|| io::Error::other("the cache session closed"))?;427 if !shared.cache_allowed() {428 return Err(io::Error::other("cache frames require Wire 2"));429 }430 write_body(431 &shared,432 0,433 &Body::CacheCommit(body::CacheCommit {434 lease_id,435 ok,436 bytes,437 crc32c,438 token_count,439 save_ms,440 }),441 &[],442 )443 }444 }445 446 impl Shared {447 fn new(out: UnixStream, catalogue: Catalogue) -> Shared {448 Shared {449 session: Mutex::new(Session::new(Role::Server)),450 out: Mutex::new(out),451 catalogue,452 streams: Mutex::new(HashMap::new()),453 seen: Mutex::new(vec![false; usize::from(u16::MAX) + 1]),454 draining: AtomicBool::new(false),455 failed: AtomicBool::new(false),456 drained: Condvar::new(),457 version: AtomicU32::new(1),458 codec: OnceLock::new(),459 cache_waiters: Mutex::new(BTreeMap::new()),460 next_cache: AtomicU64::new(1),461 cache_closed: AtomicBool::new(false),462 }463 }464 465 fn cache_allowed(&self) -> bool {466 self.version.load(Ordering::SeqCst) == 2 && self.catalogue.cache.is_some()467 }468 469 fn request_lookup(470 self: &Arc<Self>,471 keys: &[[u8; 32]],472 lineage: Option<[u8; 32]>,473 timeout: Duration,474 ) -> io::Result<Option<CacheFile>> {475 let id = self.next_cache.fetch_add(1, Ordering::Relaxed);476 let waiter = Arc::new(CacheWaiter::new());477 lock(&self.cache_waiters).insert(id, Arc::clone(&waiter));478 let body = Body::CacheLookup(body::CacheLookup {479 req_id: id,480 keys: keys.to_vec(),481 lineage,482 });483 if let Err(why) = write_body(self, 0, &body, &[]) {484 lock(&self.cache_waiters).remove(&id);485 return Err(why);486 }487 let reply = self.wait_cache(&waiter, timeout, id)?;488 match reply {489 CacheReply::Lookup(file) => Ok(file),490 CacheReply::Error(why) => Err(io::Error::other(why)),491 _ => Err(io::Error::other(492 "the core answered the wrong cache request",493 )),494 }495 }496 497 fn request_reserve(498 self: &Arc<Self>,499 request: Reserve,500 timeout: Duration,501 ) -> io::Result<Option<CacheWrite>> {502 let id = self.next_cache.fetch_add(1, Ordering::Relaxed);503 let waiter = Arc::new(CacheWaiter::new());504 lock(&self.cache_waiters).insert(id, Arc::clone(&waiter));505 let body = Body::CacheReserve(body::CacheReserve {506 req_id: id,507 key: request.key,508 lineage: request.lineage,509 supersedes: request.supersedes,510 kind: request.kind,511 est_bytes: request.est_bytes,512 prefill_ms: request.prefill_ms,513 token_count: request.token_count,514 pin: request.pin,515 });516 if let Err(why) = write_body(self, 0, &body, &[]) {517 lock(&self.cache_waiters).remove(&id);518 return Err(why);519 }520 let reply = self.wait_cache(&waiter, timeout, id)?;521 match reply {522 CacheReply::Grant(file) => Ok(file),523 CacheReply::Error(why) => Err(io::Error::other(why)),524 _ => Err(io::Error::other(525 "the core answered the wrong cache request",526 )),527 }528 }529 530 fn wait_cache(531 &self,532 waiter: &CacheWaiter,533 timeout: Duration,534 id: u64,535 ) -> io::Result<CacheReply> {536 let deadline = Instant::now() + timeout;537 let mut reply = lock(&waiter.reply);538 while reply.is_none() {539 if self.cache_closed.load(Ordering::SeqCst) {540 lock(&self.cache_waiters).remove(&id);541 return Err(io::Error::other("the cache session closed"));542 }543 let left = deadline.saturating_duration_since(Instant::now());544 if left.is_zero() {545 lock(&self.cache_waiters).remove(&id);546 return Err(io::Error::new(547 io::ErrorKind::TimedOut,548 "the core did not answer the cache request",549 ));550 }551 reply = wait_timeout(&waiter.wake, reply, left);552 }553 lock(&self.cache_waiters).remove(&id);554 reply555 .take()556 .ok_or_else(|| io::Error::other("the cache reply vanished"))557 }558 559 fn cache_lookup_response(self: &Arc<Self>, response: body::CacheLookupRes, fds: Vec<OwnedFd>) {560 let Some(waiter) = lock(&self.cache_waiters).remove(&response.req_id) else {561 if let Some(hit) = response.hit {562 // The caller timed out and no longer holds the descriptor.563 // Release the core lease rather than leaving it to the reaper.564 let _ = write_body(565 self,566 0,567 &Body::CacheRelease(body::CacheRelease {568 lease_id: hit.lease_id,569 ok: true,570 restore_ms: 0,571 abandoned: true,572 }),573 &[],574 );575 }576 return;577 };578 let reply = match response.hit {579 None => CacheReply::Lookup(None),580 Some(hit) => match fds581 .into_iter()582 .nth(usize::try_from(hit.fd).unwrap_or(usize::MAX))583 {584 Some(file) => CacheReply::Lookup(Some(CacheFile {585 key: hit.key,586 lease_id: hit.lease_id,587 bytes: hit.bytes,588 crc32c: hit.crc32c,589 token_count: hit.token_count,590 tier: hit.tier,591 file,592 })),593 None => CacheReply::Error("the lookup hit carried no descriptor".into()),594 },595 };596 waiter.set(reply);597 }598 599 fn cache_grant_response(self: &Arc<Self>, response: body::CacheGrant, fds: Vec<OwnedFd>) {600 let Some(waiter) = lock(&self.cache_waiters).remove(&response.req_id) else {601 if let Some(grant) = response.grant {602 let _ = write_body(603 self,604 0,605 &Body::CacheCommit(body::CacheCommit {606 lease_id: grant.lease_id,607 ok: false,608 bytes: 0,609 crc32c: 0,610 token_count: 0,611 save_ms: 0,612 }),613 &[],614 );615 }616 return;617 };618 let reply = match response.grant {619 None => CacheReply::Grant(None),620 Some(grant) => match fds621 .into_iter()622 .nth(usize::try_from(grant.fd).unwrap_or(usize::MAX))623 {624 Some(file) => CacheReply::Grant(Some(CacheWrite {625 lease_id: grant.lease_id,626 max_bytes: grant.max_bytes,627 tier: grant.tier,628 file,629 })),630 None => CacheReply::Error("the write grant carried no descriptor".into()),631 },632 };633 waiter.set(reply);634 }635 636 fn close_cache(&self) {637 self.cache_closed.store(true, Ordering::SeqCst);638 for waiter in lock(&self.cache_waiters).values() {639 waiter.set(CacheReply::Error("the cache session closed".into()));640 }641 lock(&self.cache_waiters).clear();642 }643 644 fn stream(&self, id: u16) -> Option<Arc<Stream>> {645 lock(&self.streams).get(&id).cloned()646 }647 648 fn mark_opened(&self, id: u16) {649 if let Some(slot) = lock(&self.seen).get_mut(usize::from(id)) {650 *slot = true;651 }652 }653 654 fn ever_opened(&self, id: u16) -> bool {655 lock(&self.seen)656 .get(usize::from(id))657 .copied()658 .unwrap_or(false)659 }660 661 /// Checks the fields that the catalogue owns, before the SDK accepts.662 fn admits(&self, open: &body::Open) -> Result<(), Failure> {663 let Some(model) = self664 .catalogue665 .models666 .iter()667 .find(|model| model.serve == open.model)668 else {669 return Err(Failure::new(670 body::ErrorCode::UnknownModel,671 format!("the catalogue does not serve {}", open.model),672 ));673 };674 let Some(capability) = model.capabilities.get(&open.capability) else {675 return Err(Failure::capability(format!(676 "{} has no capability {}",677 open.model, open.capability678 )));679 };680 for part in &open.parts {681 if !capability.parts.contains(&part.kind) {682 return Err(Failure::part(format!(683 "the part kind {} is not in {}",684 body::part_kind_name(part.kind),685 open.capability686 )));687 }688 }689 Ok(())690 }691 692 /// Waits for every open stream to end. The drain window is the sum of the693 /// budgets of those streams (section 6 rule 4); the workers end on their694 /// own budget, so this wait has no separate deadline.695 fn wait_drained(&self) {696 let mut streams = lock(&self.streams);697 while !streams.is_empty() {698 streams = wait(&self.drained, streams);699 }700 }701 702 /// Wakes every worker that waits for credit. The socket is gone, so no703 /// frame can arrive to grant it.704 fn abort(&self) {705 for stream in lock(&self.streams).values() {706 stream.cancel.store(true, Ordering::SeqCst);707 stream.wake.notify_all();708 }709 }710 711 fn finish(&self, id: u16) {712 let empty = {713 let mut streams = lock(&self.streams);714 streams.remove(&id);715 streams.is_empty()716 };717 if !empty {718 return;719 }720 self.drained.notify_all();721 if self.draining.load(Ordering::SeqCst) {722 // The reader is waiting for the next control frame, and there is723 // nothing left to control. A read shutdown turns that wait into an724 // end and lets `serve` return.725 let _ = lock(&self.out).shutdown(Shutdown::Read);726 }727 }728 }729 730 /// One job: its credit, its cancel flag, and where it may write.731 struct Stream {732 job: Mutex<Job>,733 cancel: AtomicBool,734 wake: Condvar,735 artifacts: Mutex<Vec<ArtifactRecord>>,736 started: Instant,737 budget: Duration,738 finished: AtomicBool,739 }740 741 /// An artifact that the worker produced and the terminal frame will carry.742 struct ArtifactRecord {743 ch: String,744 mime: String,745 len: u64,746 hold: ArtifactHold,747 }748 749 enum ArtifactHold {750 Bytes(Vec<u8>),751 File(OwnedFd),752 }753 754 impl Stream {755 fn window(&self, credit: u64) -> Result<(), inf3r_proto::JobError> {756 let mut job = lock(&self.job);757 let result = job.window(credit);758 drop(job);759 self.wake.notify_all();760 result761 }762 763 fn cancel(&self, shared: &Arc<Shared>, id: u16) {764 self.cancel.store(true, Ordering::SeqCst);765 self.wake.notify_all();766 // An active job ends here, not when its worker next checks the flag.767 // The caller released its slot as soon as it wrote this cancel, so a768 // new open can arrive before the worker wakes. A terminal frame now769 // frees the session's stream count, and the later frame from the770 // worker is ignored by `terminal`'s one-winner rule.771 let answer = lock(&self.job).cancel();772 match answer {773 inf3r_proto::Answer::Reject => {774 let body = Body::Reject(Refusal {775 code: body::ErrorCode::Cancelled,776 detail: None,777 });778 self.terminal(shared, id, body, Vec::new());779 }780 inf3r_proto::Answer::Done => {781 let body = Body::Done(body::Done {782 outcome: body::Outcome::Cancelled,783 artifacts: Vec::new(),784 usage: BTreeMap::new(),785 meta: None,786 });787 self.terminal(shared, id, body, Vec::new());788 }789 inf3r_proto::Answer::Nothing => {}790 }791 }792 793 /// Sends the one terminal frame of this stream, or nothing if another794 /// thread already did.795 fn terminal(&self, shared: &Arc<Shared>, id: u16, body: Body, fds: Vec<OwnedFd>) -> bool {796 if self.finished.swap(true, Ordering::SeqCst) {797 return false;798 }799 lock(&self.job).close();800 lock(&shared.session).finish_stream();801 let borrowed: Vec<BorrowedFd<'_>> = fds.iter().map(AsFd::as_fd).collect();802 let _ = write_body(shared, id, &body, &borrowed);803 true804 }805 806 fn remaining(&self) -> Duration {807 self.budget.saturating_sub(self.started.elapsed())808 }809 }810 811 /// The emitter that a capability writes through.812 struct Writer<'a> {813 shared: &'a Arc<Shared>,814 stream: &'a Arc<Stream>,815 id: u16,816 usage: BTreeMap<String, u64>,817 }818 819 impl Emitter for Writer<'_> {820 fn emit(&mut self, channel: &str, mime: &str, bytes: &[u8]) -> Result<Emit, EmitError> {821 let len = bytes.len() as u64;822 loop {823 if self.stream.cancel.load(Ordering::SeqCst) {824 return Err(EmitError::Cancelled);825 }826 // The guard stays with the wait. A window that arrives after827 // `emit` says Blocked must find either this thread still holding828 // the lock or this thread already asleep on the condvar. Dropping829 // the guard and taking it again would lose that wakeup.830 let mut job = lock(&self.stream.job);831 let verdict = match job.emit(len) {832 Ok(verdict) => verdict,833 Err(_) => return Err(EmitError::Cancelled),834 };835 match verdict {836 Emit::Sent => {837 drop(job);838 break;839 }840 Emit::Cancelled => return Err(EmitError::Cancelled),841 Emit::Blocked => {842 let left = self.stream.remaining();843 if left.is_zero() {844 return Err(EmitError::Blocked);845 }846 drop(wait_timeout(&self.stream.wake, job, left));847 }848 }849 }850 851 let body = Body::Event(body::Event {852 ch: channel.to_string(),853 mime: mime.to_string(),854 data: bytes.to_vec(),855 });856 match write_event(self.shared, self.stream, self.id, &body, &[]) {857 Ok(true) => Ok(Emit::Sent),858 _ => Err(EmitError::Cancelled),859 }860 }861 862 fn artifact(&mut self, channel: &str, mime: &str, body: Artifact) -> Result<(), EmitError> {863 let record = match body {864 Artifact::Bytes(bytes) => ArtifactRecord {865 ch: channel.to_string(),866 mime: mime.to_string(),867 len: bytes.len() as u64,868 hold: ArtifactHold::Bytes(bytes),869 },870 Artifact::File(fd) => {871 let file = std::fs::File::from(fd);872 let len = match file.metadata() {873 Ok(meta) => meta.len(),874 Err(_) => return Err(EmitError::Cancelled),875 };876 ArtifactRecord {877 ch: channel.to_string(),878 mime: mime.to_string(),879 len,880 hold: ArtifactHold::File(OwnedFd::from(file)),881 }882 }883 };884 lock(&self.stream.artifacts).push(record);885 Ok(())886 }887 888 fn cancelled(&self) -> bool {889 self.stream.cancel.load(Ordering::SeqCst)890 }891 892 fn remaining_ms(&self) -> u32 {893 u32::try_from(self.stream.remaining().as_millis()).unwrap_or(u32::MAX)894 }895 896 fn usage(&mut self, key: &str, value: u64) {897 self.usage.insert(key.to_string(), value);898 }899 }900 901 /// Starts one worker, or returns `false` when `max_inflight` is reached.902 fn start<P: Plugin>(903 shared: &Arc<Shared>,904 plugin: &Arc<P>,905 id: u16,906 open: body::Open,907 fds: Vec<OwnedFd>,908 ) -> io::Result<bool> {909 let stream = Arc::new(Stream {910 job: Mutex::new(Job::new(open.credit)),911 cancel: AtomicBool::new(false),912 wake: Condvar::new(),913 artifacts: Mutex::new(Vec::new()),914 started: Instant::now(),915 budget: Duration::from_millis(u64::from(open.budget_ms)),916 finished: AtomicBool::new(false),917 });918 {919 let mut streams = lock(&shared.streams);920 if streams.len() >= usize::from(plugin.max_inflight()) {921 return Ok(false);922 }923 streams.insert(id, stream.clone());924 }925 926 let shared = shared.clone();927 let plugin = plugin.clone();928 thread::spawn(move || {929 run_job(&shared, &plugin, &stream, id, open, fds);930 shared.finish(id);931 });932 Ok(true)933 }934 935 fn run_job<P: Plugin>(936 shared: &Arc<Shared>,937 plugin: &Arc<P>,938 stream: &Arc<Stream>,939 id: u16,940 open: body::Open,941 fds: Vec<OwnedFd>,942 ) {943 if let Err(failure) = shared.admits(&open) {944 reject(shared, stream, id, failure);945 return;946 }947 948 let files: Vec<File> = fds.into_iter().map(File::from).collect();949 let parts = match parts_of(&open.parts, &files) {950 Ok(parts) => parts,951 Err(failure) => {952 reject(shared, stream, id, failure);953 return;954 }955 };956 let request = Request {957 request_id: &open.request_id,958 model: &open.model,959 capability: &open.capability,960 parts: &parts,961 params: &open.params,962 };963 if let Err(failure) = plugin.admit(&request) {964 reject(shared, stream, id, failure);965 return;966 }967 968 if lock(&stream.job).accept().is_err() {969 return;970 }971 let accepted = Body::Accept(body::Accepted { est_ms: None });972 if write_body(shared, id, &accepted, &[]).is_err() {973 return;974 }975 976 let mut out = Writer {977 shared,978 stream,979 id,980 usage: BTreeMap::new(),981 };982 let result = plugin.run(&open.capability, request, &mut out);983 984 let outcome = if stream.cancel.load(Ordering::SeqCst) {985 body::Outcome::Cancelled986 } else if stream.remaining().is_zero() {987 body::Outcome::Expired988 } else {989 body::Outcome::Completed990 };991 992 let measured = std::mem::take(&mut out.usage);993 let (body, files) = match result {994 Ok(report) => {995 let records = std::mem::take(&mut *lock(&stream.artifacts));996 let (artifacts, files) = artifacts_of(records);997 let mut usage = report.usage;998 usage.extend(measured);999 (done(outcome, usage, Some(report.meta), artifacts), files)1000 }1001 Err(failure) => {1002 let outcome = if outcome == body::Outcome::Completed {1003 body::Outcome::Failed1004 } else {1005 outcome1006 };1007 let meta = error_meta(failure.code, failure.detail.as_deref());1008 (1009 done(outcome, BTreeMap::new(), Some(meta), Vec::new()),1010 Vec::new(),1011 )1012 }1013 };1014 stream.terminal(shared, id, body, files);1015 }1016 1017 /// The terminal frame of a job that the server accepted.1018 fn done(1019 outcome: body::Outcome,1020 usage: BTreeMap<String, u64>,1021 meta: Option<BTreeMap<String, inf3r_proto::Value>>,1022 artifacts: Vec<body::Artifact>,1023 ) -> Body {1024 Body::Done(body::Done {1025 outcome,1026 artifacts,1027 usage,1028 meta,1029 })1030 }1031 1032 fn error_meta(code: body::ErrorCode, detail: Option<&str>) -> BTreeMap<String, inf3r_proto::Value> {1033 let mut meta = BTreeMap::new();1034 meta.insert(1035 "error".to_string(),1036 inf3r_proto::Value::Text(code.to_string()),1037 );1038 if let Some(detail) = detail {1039 meta.insert(1040 "detail".to_string(),1041 inf3r_proto::Value::Text(detail.to_string()),1042 );1043 }1044 meta1045 }1046 1047 /// Refuses one job in `OPEN`, before any `accept` or `run`.1048 fn reject(shared: &Arc<Shared>, stream: &Arc<Stream>, id: u16, failure: Failure) {1049 let body = Body::Reject(Refusal {1050 code: failure.code,1051 detail: failure.detail,1052 });1053 stream.terminal(shared, id, body, Vec::new());1054 }1055 1056 /// Borrows each part without copying it.1057 ///1058 /// An inline part must carry exactly the length that it declares. A descriptor1059 /// must be at least that long. The reader that the plugin gets stops at the1060 /// declared length, and starts at byte zero even when the descriptor's file1061 /// offset has moved.1062 fn parts_of<'a>(parts: &'a [body::Part], files: &'a [File]) -> Result<Vec<Part<'a>>, Failure> {1063 let mut out = Vec::with_capacity(parts.len());1064 for part in parts {1065 let body = match &part.hold {1066 body::Hold::Inline(bytes) => {1067 let len = u64::try_from(bytes.len()).unwrap_or(u64::MAX);1068 if len != part.len {1069 return Err(Failure::part(format!(1070 "an inline part is {len} bytes and declares {}",1071 part.len1072 )));1073 }1074 PartBody::Inline(bytes)1075 }1076 body::Hold::Fd(index) => {1077 let index = usize::try_from(*index)1078 .map_err(|_| Failure::part("a descriptor index does not fit this machine"))?;1079 let Some(file) = files.get(index) else {1080 return Err(Failure::part(format!(1081 "there is no descriptor for part index {index}"1082 )));1083 };1084 let len = file1085 .metadata()1086 .map_err(|why| Failure::part(format!("a part descriptor: {why}")))?1087 .len();1088 if len < part.len {1089 return Err(Failure::part(format!(1090 "a part descriptor is {len} bytes and the part declares {}",1091 part.len1092 )));1093 }1094 PartBody::File(file)1095 }1096 };1097 out.push(Part {1098 kind: part.kind,1099 mime: &part.mime,1100 role: part.role.as_deref(),1101 len: part.len,1102 body,1103 });1104 }1105 Ok(out)1106 }1107 1108 /// Notes a session frame that this side sends, so the phase table advances on1109 /// both directions and not only on the frames that arrive.1110 fn record(shared: &Shared, kind: Kind) {1111 let _ = lock(&shared.session).send(kind);1112 }1113 1114 /// Writes one event unless the stream has already ended.1115 ///1116 /// The check and the write happen under the one output lock, so a cancel that1117 /// ended the stream cannot slip a terminal frame in front of this event. A1118 /// cancel sets `finished` before it takes the lock, so either this event wins1119 /// the lock and reaches the wire before the terminal frame, or it sees1120 /// `finished` and is dropped.1121 fn write_event(1122 shared: &Arc<Shared>,1123 stream: &Stream,1124 id: u16,1125 body: &Body,1126 fds: &[BorrowedFd<'_>],1127 ) -> io::Result<bool> {1128 let payload = body.encode();1129 let length = match u32::try_from(payload.len()) {1130 Ok(length) => length,1131 Err(_) => return Err(io::Error::other("the payload does not fit the header")),1132 };1133 let header = Header::new(body.kind(), id, length);1134 let out = lock(&shared.out);1135 if stream.finished.load(Ordering::SeqCst) {1136 return Ok(false);1137 }1138 send_frame(&out, header, &payload, fds).map_err(|e| match e {1139 inf3r_proto::Error::Io(e) => e,1140 other => io::Error::other(other.to_string()),1141 })?;1142 Ok(true)1143 }1144 1145 fn write_body(1146 shared: &Arc<Shared>,1147 stream: u16,1148 body: &Body,1149 fds: &[BorrowedFd<'_>],1150 ) -> io::Result<()> {1151 let payload = body.encode();1152 let length = match u32::try_from(payload.len()) {1153 Ok(length) => length,1154 Err(_) => return Err(io::Error::other("the payload does not fit the header")),1155 };1156 let header = Header::new(body.kind(), stream, length);1157 let out = lock(&shared.out);1158 send_frame(&out, header, &payload, fds).map_err(|e| match e {1159 inf3r_proto::Error::Io(e) => e,1160 other => io::Error::other(other.to_string()),1161 })1162 }1163 1164 /// Ends the session with a refusal. The socket closes when `serve` returns.1165 fn fail(shared: &Arc<Shared>, code: body::ErrorCode) {1166 shared.failed.store(true, Ordering::SeqCst);1167 let body = Body::Fatal(Refusal { code, detail: None });1168 let _ = write_body(shared, 0, &body, &[]);1169 }1170 1171 fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {1172 m.lock().unwrap_or_else(|poisoned| poisoned.into_inner())1173 }1174 1175 fn wait<'a, T>(cv: &Condvar, guard: MutexGuard<'a, T>) -> MutexGuard<'a, T> {1176 cv.wait(guard)1177 .unwrap_or_else(|poisoned| poisoned.into_inner())1178 }1179 1180 fn wait_timeout<'a, T>(cv: &Condvar, guard: MutexGuard<'a, T>, at: Duration) -> MutexGuard<'a, T> {1181 cv.wait_timeout(guard, at)1182 .unwrap_or_else(|poisoned| poisoned.into_inner())1183 .01184 }1185 1186 /// Splits the recorded artifacts into wire descriptors and the files behind1187 /// them. `Hold::Fd(n)` is the n-th descriptor of the terminal frame, so the1188 /// order here is the contract with the caller.1189 fn artifacts_of(records: Vec<ArtifactRecord>) -> (Vec<body::Artifact>, Vec<OwnedFd>) {1190 let mut artifacts = Vec::with_capacity(records.len());1191 let mut files = Vec::new();1192 for record in records {1193 let hold = match record.hold {1194 ArtifactHold::Bytes(bytes) => body::Hold::Inline(bytes),1195 ArtifactHold::File(fd) => {1196 let index = files.len() as u32;1197 files.push(fd);1198 body::Hold::Fd(index)1199 }1200 };1201 artifacts.push(body::Artifact {1202 ch: record.ch,1203 mime: record.mime,1204 len: record.len,1205 hold,1206 });1207 }1208 (artifacts, files)1209 }