crates/edge/bind/src/caps.rs 25.0 KiB 768 lines Raw
1 //! The capabilities that an HTTP runtime can carry.2 //!3 //! The seven OpenAI-shaped capabilities map the neutral request to the request4 //! shape that an OpenAI-compatible server uses, and map the reply back to the5 //! channels that the capability page defines. The five neutral capabilities6 //! use one JSON request and one event stream with no vendor route. Nothing here7 //! names a model or a vendor.8 9 use std::io::{BufRead, Read};10 use std::time::{Duration, Instant};11 12 use inf3r_json::Value as J;13 use inf3r_plugin_sdk::Failure;14 use inf3r_plugin_sdk::capability::{Artifact, Part, PartBody, Report, Request};15 use inf3r_plugin_sdk::emitter::Emitter;16 use inf3r_proto::Emit;17 use inf3r_proto::Value as P;18 use inf3r_proto::body::{ErrorCode, PartKind};19 20 use crate::http;21 use crate::manifest::ModelSpec;22 23 /// The MIME of a text event.24 const TEXT_MIME: &str = "text/plain; charset=utf-8";25 /// The MIME of a CBOR embedding artifact.26 const CBOR_MIME: &str = "application/cbor";27 /// The MIME of an image artifact.28 const PNG_MIME: &str = "image/png";29 /// The largest event that an audio reply is cut into.30 const AUDIO_CHUNK: usize = 8 << 10;31 /// How often a streamed bridge checks cancellation and its deadline.32 const STREAM_POLL: Duration = Duration::from_millis(20);33 34 /// Runs one non-chat capability against the engine at `base`.35 pub fn run(36     base: &str,37     capability: &str,38     model: &ModelSpec,39     req: &Request<'_>,40     out: &mut dyn Emitter,41     timeout: Duration,42 ) -> Result<Report, Failure> {43     match capability {44         "embed" => embed(base, model, req, out, timeout),45         "rerank" => rerank(base, model, req, out, timeout),46         "stt" => stt(base, model, req, out, timeout),47         "tts" => tts(base, model, req, out, timeout),48         "image-gen" => image_gen(base, model, req, out, timeout),49         "image-edit" => image_edit(base, model, req, out, timeout),50         "music" | "t2v-gen" | "i2v-gen" | "decide" | "extract" => {51             generic(base, capability, model, req, out, timeout)52         }53         other => Err(Failure::capability(other)),54     }55 }56 57 fn embed(58     base: &str,59     model: &ModelSpec,60     req: &Request<'_>,61     out: &mut dyn Emitter,62     timeout: Duration,63 ) -> Result<Report, Failure> {64     let texts = texts(req)?;65     if texts.is_empty() {66         return Err(Failure::part("embed needs at least one text part"));67     }68     let mut body = params(req.params);69     body = body70         .put("model", J::str(model.serve.clone()))71         .put("input", J::Array(texts.into_iter().map(J::Str).collect()));72     let reply = post(base, "/embeddings", &body, timeout)?;73     let data = reply74         .get("data")75         .and_then(J::as_array)76         .ok_or_else(|| failure("the embedding reply has no data array"))?;77     let mut vectors = Vec::with_capacity(data.len());78     for row in data {79         let values = row80             .get("embedding")81             .and_then(J::as_array)82             .ok_or_else(|| failure("an embedding row has no vector"))?;83         let mut vector = Vec::with_capacity(values.len());84         for value in values {85             let number = value86                 .as_f64()87                 .ok_or_else(|| failure("an embedding value is not a number"))?;88             vector.push(inf3r_proto::cbor::Value::Float(number));89         }90         vectors.push(P::Array(vector));91     }92     let dims = vectors.first().and_then(|vector| match vector {93         P::Array(values) => Some(values.len()),94         _ => None,95     });96     let mut bytes = Vec::new();97     inf3r_proto::cbor::encode(&P::Array(vectors), &mut bytes);98     out.artifact("embedding", CBOR_MIME, Artifact::Bytes(bytes))99         .map_err(|why| failure(format!("the embedding artifact: {why}")))?;100     let mut report = Report::default();101     if let Some(tokens) = usage(&reply).get("prompt_tokens").and_then(J::as_u64) {102         report.usage.insert("tokens_in".to_string(), tokens);103     }104     insert_meta(&mut report, "model", J::str(model.serve.clone()));105     if let Some(dims) = dims {106         insert_meta(&mut report, "dims", J::Int(dims as i64));107     }108     Ok(report)109 }110 111 fn rerank(112     base: &str,113     model: &ModelSpec,114     req: &Request<'_>,115     out: &mut dyn Emitter,116     timeout: Duration,117 ) -> Result<Report, Failure> {118     let query = req119         .parts120         .iter()121         .find(|part| part.kind == PartKind::Text && part.role == Some("query"))122         .ok_or_else(|| Failure::part("rerank needs a text part with role query"))?;123     let query = text(query)?;124     let documents = req125         .parts126         .iter()127         .find(|part| part.kind == PartKind::Json && part.role == Some("documents"))128         .ok_or_else(|| Failure::part("rerank needs a json part with role documents"))?;129     let documents = json(documents)?;130     let documents = documents131         .get("documents")132         .and_then(J::as_array)133         .ok_or_else(|| Failure::part("the documents part has no documents array"))?;134     let mut body = params(req.params);135     body = body136         .put("model", J::str(model.serve.clone()))137         .put("query", J::str(query))138         .put("documents", J::Array(documents.to_vec()));139     let reply = post(base, "/rerank", &body, timeout)?;140     let scores = reply141         .get("results")142         .or_else(|| reply.get("data"))143         .and_then(J::as_array)144         .ok_or_else(|| failure("the rerank reply has no results"))?;145     let mut values = Vec::with_capacity(scores.len());146     for row in scores {147         let score = row148             .get("relevance_score")149             .or_else(|| row.get("score"))150             .and_then(J::as_f64)151             .ok_or_else(|| failure("a rerank row has no score"))?;152         values.push(inf3r_proto::cbor::Value::Float(score));153     }154     let mut bytes = Vec::new();155     inf3r_proto::cbor::encode(&P::Array(values), &mut bytes);156     out.artifact("embedding", CBOR_MIME, Artifact::Bytes(bytes))157         .map_err(|why| failure(format!("the rerank artifact: {why}")))?;158     let mut report = Report::default();159     if let Some(tokens) = usage(&reply).get("prompt_tokens").and_then(J::as_u64) {160         report.usage.insert("tokens_in".to_string(), tokens);161     }162     insert_meta(&mut report, "model", J::str(model.serve.clone()));163     Ok(report)164 }165 166 fn tts(167     base: &str,168     model: &ModelSpec,169     req: &Request<'_>,170     out: &mut dyn Emitter,171     timeout: Duration,172 ) -> Result<Report, Failure> {173     let input = texts(req)?.join("");174     if input.is_empty() {175         return Err(Failure::part("tts needs text"));176     }177     let mut body = params(req.params);178     body = body179         .put("model", J::str(model.serve.clone()))180         .put("input", J::str(input));181     let reply = post_reply(base, "/audio/speech", &body, timeout)?;182     let mime = reply183         .content_type184         .clone()185         .unwrap_or_else(|| "application/octet-stream".to_string());186     let mut reader = reply.reader;187     let mut chunk = vec![0u8; AUDIO_CHUNK];188     loop {189         if out.cancelled() {190             return Ok(Report::default());191         }192         let read = reader193             .read(&mut chunk)194             .map_err(|why| failure(format!("the audio reply: {why}")))?;195         if read == 0 {196             break;197         }198         match out.emit("pcm", &mime, &chunk[..read]) {199             Ok(Emit::Sent | Emit::Blocked) => {}200             Ok(Emit::Cancelled) | Err(_) => return Ok(Report::default()),201         }202     }203     let mut report = Report::default();204     insert_meta(&mut report, "model", J::str(model.serve.clone()));205     Ok(report)206 }207 208 fn stt(209     base: &str,210     model: &ModelSpec,211     req: &Request<'_>,212     out: &mut dyn Emitter,213     timeout: Duration,214 ) -> Result<Report, Failure> {215     let audio = req216         .parts217         .iter()218         .find(|part| part.kind == PartKind::Audio)219         .ok_or_else(|| Failure::part("stt needs an audio part"))?;220     let prompt = req221         .parts222         .iter()223         .find(|part| part.kind == PartKind::Text && part.role == Some("prompt"))224         .map(text)225         .transpose()?;226     let mut fields = vec![227         Field::file("file", "audio", audio.mime, bytes(audio)?),228         Field::text("model", &model.serve),229     ];230     if let Some(prompt) = prompt {231         fields.push(Field::text("prompt", &prompt));232     }233     for key in ["language", "response_format", "temperature"] {234         if let Some(value) = param_str(req.params, key) {235             fields.push(Field::text(key, &value));236         }237     }238     let reply = post_multipart(base, "/audio/transcriptions", fields, timeout)?;239     let (text, meta) = if let Some(value) = reply.get("text").and_then(J::as_str) {240         (value.to_string(), reply)241     } else if let Some(value) = reply.get("segments").and_then(J::as_array) {242         let text = value243             .iter()244             .filter_map(|segment| segment.get("text").and_then(J::as_str))245             .collect::<String>();246         (text, reply)247     } else {248         (String::new(), reply)249     };250     if !text.is_empty() {251         match out.emit("text", TEXT_MIME, text.as_bytes()) {252             Ok(Emit::Sent | Emit::Blocked) => {}253             Ok(Emit::Cancelled) | Err(_) => return Ok(Report::default()),254         }255     }256     let mut report = Report::default();257     insert_meta(&mut report, "model", J::str(model.serve.clone()));258     for (from, to) in [("language", "language"), ("duration", "duration")] {259         if let Some(value) = meta.get(from) {260             insert_meta(&mut report, to, value.clone());261         }262     }263     if let Some(segments) = meta.get("segments") {264         insert_meta(&mut report, "segments", segments.clone());265     }266     Ok(report)267 }268 269 fn image_gen(270     base: &str,271     model: &ModelSpec,272     req: &Request<'_>,273     out: &mut dyn Emitter,274     timeout: Duration,275 ) -> Result<Report, Failure> {276     let prompt = req277         .parts278         .iter()279         .filter(|part| part.kind == PartKind::Text)280         .map(text)281         .collect::<Result<Vec<_>, _>>()?282         .join("\n");283     if prompt.is_empty() {284         return Err(Failure::part("image-gen needs prompt text"));285     }286     let mut body = params(req.params);287     body = body288         .put("model", J::str(model.serve.clone()))289         .put("prompt", J::str(prompt))290         .put("n", J::int(1))291         .put("response_format", J::str("b64_json"));292     let reply = post(base, "/images/generations", &body, timeout)?;293     image_reply(&reply, model, out)294 }295 296 fn image_edit(297     base: &str,298     model: &ModelSpec,299     req: &Request<'_>,300     out: &mut dyn Emitter,301     timeout: Duration,302 ) -> Result<Report, Failure> {303     let source = req304         .parts305         .iter()306         .find(|part| part.kind == PartKind::Image && part.role == Some("source"))307         .ok_or_else(|| Failure::part("image-edit needs a source image"))?;308     let instruction = req309         .parts310         .iter()311         .find(|part| part.kind == PartKind::Text && part.role == Some("instruction"))312         .map(text)313         .transpose()?314         .ok_or_else(|| Failure::part("image-edit needs an instruction"))?;315     let mut fields = vec![316         Field::file("image", "source.png", source.mime, bytes(source)?),317         Field::text("model", &model.serve),318         Field::text("prompt", &instruction),319         Field::text("response_format", "b64_json"),320     ];321     if let Some(mask) = req322         .parts323         .iter()324         .find(|part| part.kind == PartKind::Image && part.role == Some("mask"))325     {326         fields.push(Field::file("mask", "mask.png", mask.mime, bytes(mask)?));327     }328     for key in ["size", "steps", "guidance", "strength", "seed"] {329         if let Some(value) = param_str(req.params, key) {330             fields.push(Field::text(key, &value));331         }332     }333     let reply = post_multipart_json(base, "/images/edits", fields, timeout)?;334     image_reply(&reply, model, out)335 }336 337 fn image_reply(reply: &J, model: &ModelSpec, out: &mut dyn Emitter) -> Result<Report, Failure> {338     let data = reply339         .get("data")340         .and_then(J::as_array)341         .ok_or_else(|| failure("the image reply has no data array"))?;342     let first = data343         .first()344         .ok_or_else(|| failure("the image reply is empty"))?;345     let encoded = first346         .get("b64_json")347         .and_then(J::as_str)348         .ok_or_else(|| failure("the image reply has no b64_json"))?;349     let bytes = inf3r_json::b64::decode(encoded)350         .ok_or_else(|| failure("the image b64_json is not base64"))?;351     out.artifact("image", PNG_MIME, Artifact::Bytes(bytes))352         .map_err(|why| failure(format!("the image artifact: {why}")))?;353     let mut report = Report::default();354     report.usage.insert("images".to_string(), 1);355     insert_meta(&mut report, "model", J::str(model.serve.clone()));356     Ok(report)357 }358 359 /// The neutral bridge for capabilities without an OpenAI-shaped route.360 ///361 /// The request is the same object that a binary engine reads. A reply is a362 /// single JSON object, an array of events, line-delimited JSON, or SSE; every363 /// event has the same `channel`, `done`, and `error` words as the resident364 /// binary worker. The bridge does not guess a vendor route.365 fn generic(366     base: &str,367     capability: &str,368     model: &ModelSpec,369     req: &Request<'_>,370     out: &mut dyn Emitter,371     timeout: Duration,372 ) -> Result<Report, Failure> {373     let body = crate::bridge_body(model, capability, req, None);374     if body.len() > crate::MAX_BRIDGE_BODY {375         return Err(Failure::new(376             ErrorCode::Size,377             format!(378                 "the bridge request is {} bytes, above the {} byte cap",379                 body.len(),380                 crate::MAX_BRIDGE_BODY381             ),382         ));383     }384     let url = format!("{base}/{}", capability);385     let mut reply = http::post(386         &url,387         "application/json",388         "application/json, application/x-ndjson, text/event-stream",389         body.as_bytes(),390         timeout,391     )392     .map_err(|why| failure(format!("the engine at {url}: {why}")))?;393     reply394         .set_read_timeout(STREAM_POLL)395         .map_err(|why| failure(format!("the engine at {url}: {why}")))?;396     let content_type = reply.content_type.clone().unwrap_or_default();397     let budget = timeout.max(Duration::from_millis(1));398     let deadline = Instant::now() + budget;399     let multiline = content_type.contains("event-stream") || content_type.contains("ndjson");400     if multiline {401         loop {402             match stream_line(&mut *reply.reader, deadline, out)? {403                 StreamLine::Data(line) => {404                     let line = line.trim();405                     if line.is_empty() {406                         continue;407                     }408                     let line = line.strip_prefix("data:").map_or(line, str::trim);409                     let Ok(value) = inf3r_json::parse(line) else {410                         continue;411                     };412                     if let Some(report) = crate::bridge_event(out, &value)? {413                         return Ok(report);414                     }415                 }416                 StreamLine::End => return Ok(Report::default()),417                 StreamLine::Cancelled => return Ok(Report::default()),418                 StreamLine::Timeout => {419                     return Err(Failure::new(420                         ErrorCode::Timeout,421                         format!("the bridge sent no event within {} ms", budget.as_millis()),422                     ));423                 }424             }425         }426     }427 428     let text = read_body(&mut *reply.reader, deadline, out)?;429     let text = String::from_utf8(text).map_err(|_| failure("the bridge reply is not UTF-8"))?;430     let value =431         inf3r_json::parse(&text).map_err(|why| failure(format!("the reply JSON: {why}")))?;432     if let inf3r_json::Value::Array(events) = &value {433         for event in events {434             if out.cancelled() {435                 return Ok(Report::default());436             }437             if let Some(report) = crate::bridge_event(out, event)? {438                 return Ok(report);439             }440         }441         return Ok(Report::default());442     }443     Ok(crate::bridge_event(out, &value)?.unwrap_or_default())444 }445 446 /// What one streamed line yielded.447 enum StreamLine {448     Data(String),449     End,450     Cancelled,451     Timeout,452 }453 454 /// Reads one line with a hard byte ceiling and a short read timeout.455 ///456 /// The socket timeout is a poll interval, so a silent engine cannot keep the457 /// job blocked past the deadline and a cancel is visible between reads.458 fn stream_line(459     reader: &mut dyn BufRead,460     deadline: Instant,461     out: &dyn Emitter,462 ) -> Result<StreamLine, Failure> {463     let mut bytes = Vec::new();464     loop {465         if out.cancelled() {466             return Ok(StreamLine::Cancelled);467         }468         if Instant::now() >= deadline {469             return Ok(StreamLine::Timeout);470         }471         let available = match reader.fill_buf() {472             Ok(available) => available,473             Err(why) if retryable(&why) => continue,474             Err(why) => return Err(failure(format!("the bridge reply: {why}"))),475         };476         if available.is_empty() {477             if bytes.is_empty() {478                 return Ok(StreamLine::End);479             }480             break;481         }482         let newline = available.iter().position(|byte| *byte == b'\n');483         let take = newline.map_or(available.len(), |index| index + 1);484         if bytes.len().saturating_add(take) > crate::MAX_BRIDGE_BODY {485             return Err(Failure::new(486                 ErrorCode::Size,487                 "a bridge reply line is above the bridge cap".to_string(),488             ));489         }490         bytes.extend_from_slice(&available[..take]);491         reader.consume(take);492         if newline.is_some() {493             break;494         }495     }496     String::from_utf8(bytes)497         .map(StreamLine::Data)498         .map_err(|_| failure("a bridge reply line is not UTF-8"))499 }500 501 /// Reads a bounded non-streaming body, checking cancel and the deadline502 /// between reads.503 fn read_body(504     reader: &mut dyn Read,505     deadline: Instant,506     out: &dyn Emitter,507 ) -> Result<Vec<u8>, Failure> {508     let mut body = Vec::new();509     let mut chunk = [0u8; 8192];510     loop {511         if out.cancelled() {512             return Ok(body);513         }514         if Instant::now() >= deadline {515             return Err(Failure::new(516                 ErrorCode::Timeout,517                 "the bridge reply did not finish before the deadline".to_string(),518             ));519         }520         match reader.read(&mut chunk) {521             Ok(0) => return Ok(body),522             Ok(read) => {523                 if body.len().saturating_add(read) > crate::MAX_BRIDGE_BODY {524                     return Err(Failure::new(525                         ErrorCode::Size,526                         "a bridge reply is above the bridge cap".to_string(),527                     ));528                 }529                 body.extend_from_slice(&chunk[..read]);530             }531             Err(why) if retryable(&why) => {}532             Err(why) => return Err(failure(format!("the bridge reply: {why}"))),533         }534     }535 }536 537 fn retryable(why: &std::io::Error) -> bool {538     matches!(539         why.kind(),540         std::io::ErrorKind::WouldBlock541             | std::io::ErrorKind::TimedOut542             | std::io::ErrorKind::Interrupted543     )544 }545 546 fn texts(req: &Request<'_>) -> Result<Vec<String>, Failure> {547     req.parts548         .iter()549         .filter(|part| part.kind == PartKind::Text)550         .map(text)551         .collect()552 }553 554 fn text(part: &Part<'_>) -> Result<String, Failure> {555     match part.body {556         PartBody::Inline(bytes) => std::str::from_utf8(bytes)557             .map(str::to_string)558             .map_err(|_| Failure::part("a text part is not UTF-8")),559         PartBody::File(_) => {560             String::from_utf8(bytes(part)?).map_err(|_| Failure::part("a text part is not UTF-8"))561         }562     }563 }564 565 fn json(part: &Part<'_>) -> Result<J, Failure> {566     inf3r_json::parse_bytes(&bytes(part)?)567         .map_err(|why| Failure::part(format!("a json part: {why}")))568 }569 570 fn bytes(part: &Part<'_>) -> Result<Vec<u8>, Failure> {571     let mut out = Vec::with_capacity(usize::try_from(part.len).unwrap_or(0));572     part.reader()573         .take(part.len)574         .read_to_end(&mut out)575         .map_err(|why| Failure::part(format!("a part: {why}")))?;576     Ok(out)577 }578 579 fn params(params: &P) -> inf3r_json::Object {580     let mut body = J::object();581     if let Some(entries) = inf3r_proto::mirror::to_json(params).as_object() {582         for (key, value) in entries {583             body = body.put(key.clone(), value.clone());584         }585     }586     body587 }588 589 fn param(params: &P, key: &str) -> Option<J> {590     inf3r_proto::mirror::to_json(params).get(key).cloned()591 }592 593 fn param_str(params: &P, key: &str) -> Option<String> {594     param(params, key)595         .as_ref()596         .and_then(J::as_str)597         .map(str::to_string)598 }599 600 fn usage(reply: &J) -> &J {601     reply.get("usage").unwrap_or(&J::Null)602 }603 604 fn post(605     base: &str,606     route: &str,607     body: &inf3r_json::Object,608     timeout: Duration,609 ) -> Result<J, Failure> {610     let value = inf3r_json::to_string(&body.clone().build());611     post_json(base, route, value.as_bytes(), timeout)612 }613 614 fn post_reply(615     base: &str,616     route: &str,617     body: &inf3r_json::Object,618     timeout: Duration,619 ) -> Result<http::Reply, Failure> {620     let value = inf3r_json::to_string(&body.clone().build());621     http::post(622         &format!("{base}{route}"),623         "application/json",624         "*/*",625         value.as_bytes(),626         timeout,627     )628     .map_err(|why| failure(format!("the engine at {base}{route}: {why}")))629 }630 631 fn post_json(base: &str, route: &str, body: &[u8], timeout: Duration) -> Result<J, Failure> {632     let mut reply = http::post(633         &format!("{base}{route}"),634         "application/json",635         "*/*",636         body,637         timeout,638     )639     .map_err(|why| failure(format!("the engine at {base}{route}: {why}")))?;640     let mut text = String::new();641     reply642         .reader643         .read_to_string(&mut text)644         .map_err(|why| failure(format!("the reply body: {why}")))?;645     inf3r_json::parse(&text).map_err(|why| failure(format!("the reply JSON: {why}")))646 }647 648 fn post_multipart(649     base: &str,650     route: &str,651     fields: Vec<Field>,652     timeout: Duration,653 ) -> Result<J, Failure> {654     let (body, content_type) = multipart(fields);655     let mut reply = http::post(656         &format!("{base}{route}"),657         &content_type,658         "*/*",659         &body,660         timeout,661     )662     .map_err(|why| failure(format!("the engine at {base}{route}: {why}")))?;663     let mut text = String::new();664     reply665         .reader666         .read_to_string(&mut text)667         .map_err(|why| failure(format!("the reply body: {why}")))?;668     inf3r_json::parse(&text).map_err(|why| failure(format!("the reply JSON: {why}")))669 }670 671 fn post_multipart_json(672     base: &str,673     route: &str,674     fields: Vec<Field>,675     timeout: Duration,676 ) -> Result<J, Failure> {677     post_multipart(base, route, fields, timeout)678 }679 680 /// One multipart field.681 struct Field {682     name: String,683     filename: Option<String>,684     mime: String,685     bytes: Vec<u8>,686 }687 688 impl Field {689     fn text(name: &str, value: &str) -> Field {690         Field {691             name: name.to_string(),692             filename: None,693             mime: "text/plain; charset=utf-8".to_string(),694             bytes: value.as_bytes().to_vec(),695         }696     }697 698     fn file(name: &str, filename: &str, mime: &str, bytes: Vec<u8>) -> Field {699         Field {700             name: name.to_string(),701             filename: Some(filename.to_string()),702             mime: mime.to_string(),703             bytes,704         }705     }706 }707 708 fn multipart(fields: Vec<Field>) -> (Vec<u8>, String) {709     let mut stamp = 0u64;710     let boundary = loop {711         stamp = stamp.wrapping_add(1);712         let candidate = format!(713             "inf3r-bind-{}-{}-{stamp}",714             std::process::id(),715             std::time::SystemTime::now()716                 .duration_since(std::time::UNIX_EPOCH)717                 .map(|time| time.as_nanos())718                 .unwrap_or_default()719         );720         if fields721             .iter()722             .all(|field| !contains(&field.bytes, candidate.as_bytes()))723         {724             break candidate;725         }726     };727     let mut body = Vec::new();728     for field in fields {729         body.extend_from_slice(format!("--{boundary}\r\n").as_bytes());730         match field.filename {731             Some(filename) => body.extend_from_slice(732                 format!(733                     "Content-Disposition: form-data; name=\"{}\"; filename=\"{filename}\"\r\n",734                     field.name735                 )736                 .as_bytes(),737             ),738             None => body.extend_from_slice(739                 format!(740                     "Content-Disposition: form-data; name=\"{}\"\r\n",741                     field.name742                 )743                 .as_bytes(),744             ),745         }746         body.extend_from_slice(format!("Content-Type: {}\r\n\r\n", field.mime).as_bytes());747         body.extend_from_slice(&field.bytes);748         body.extend_from_slice(b"\r\n");749     }750     body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());751     (body, format!("multipart/form-data; boundary={boundary}"))752 }753 754 fn contains(haystack: &[u8], needle: &[u8]) -> bool {755     haystack756         .windows(needle.len())757         .any(|window| window == needle)758 }759 760 fn insert_meta(report: &mut Report, key: &str, value: J) {761     if let Some(value) = inf3r_proto::mirror::from_json(&value) {762         report.meta.insert(key.to_string(), value);763     }764 }765 766 fn failure(message: impl Into<String>) -> Failure {767     Failure::new(ErrorCode::Dependency, message)768 }