Skip to main content

Server

Struct Server 

Source
pub struct Server { /* private fields */ }
Expand description

An RCP/1 server.

Implementations§

Source§

impl Server

Source

pub fn new() -> Server

Examples found in repository?
examples/example_server.rs (line 57)
56fn build() -> Server {
57    let mut s = Server::new();
58    s.set_info("rcp-example", "1.0.0");
59    s.advertise(
60        Capability::Embed,
61        obj(&[("dimensions", (DIM as i64).into()), ("modes", vec![Json::from("dense")].into())]),
62    );
63    s.advertise(
64        Capability::Retrieve,
65        obj(&[
66            ("maxK", 100.into()),
67            ("modes", vec![Json::from("dense")].into()),
68            ("citations", true.into()),
69        ]),
70    );
71    s.advertise(
72        Capability::Graph,
73        obj(&[("ops", vec![Json::from("local"), Json::from("global")].into())]),
74    );
75
76    s.on(Method::EMBED, |params| {
77        // Accept `inputs` (preferred, spec §7.3) or the legacy `texts` synonym.
78        let items = params
79            .get("inputs")
80            .or_else(|| params.get("texts"))
81            .and_then(|v| v.as_array())
82            .cloned()
83            .unwrap_or_default();
84        let vectors: Vec<Json> = items
85            .iter()
86            .filter_map(|x| x.as_str())
87            .map(|t| Json::from(embed_one(t)))
88            .collect();
89        Ok(obj(&[("vectors", Json::Array(vectors)), ("dimensions", (DIM as i64).into())]))
90    });
91
92    s.on(Method::RETRIEVE, |params| {
93        let q = params.get_str("query").unwrap_or("");
94        let k = params.get("k").and_then(|v| v.as_i64()).unwrap_or(10).max(0) as usize;
95        Ok(obj(&[("hits", search(q, k))]))
96    });
97
98    s.on(Method::GRAPH, |params| {
99        let op = params.get_str("op").unwrap_or("local");
100        match op {
101            "local" => {
102                let q = params.get_str("query").unwrap_or("");
103                let k = params.get("k").and_then(|v| v.as_i64()).unwrap_or(5).max(0) as usize;
104                Ok(obj(&[("hits", search(q, k))]))
105            }
106            "global" => Ok(obj(&[
107                ("summary", "a global community summary would go here".into()),
108                ("communities", 1.into()),
109            ])),
110            other => Ok(obj(&[("op", other.into()), ("note", "unimplemented".into())])),
111        }
112    });
113
114    s
115}
Source

pub fn set_info(&mut self, name: &str, version: &str) -> &mut Self

Examples found in repository?
examples/example_server.rs (line 58)
56fn build() -> Server {
57    let mut s = Server::new();
58    s.set_info("rcp-example", "1.0.0");
59    s.advertise(
60        Capability::Embed,
61        obj(&[("dimensions", (DIM as i64).into()), ("modes", vec![Json::from("dense")].into())]),
62    );
63    s.advertise(
64        Capability::Retrieve,
65        obj(&[
66            ("maxK", 100.into()),
67            ("modes", vec![Json::from("dense")].into()),
68            ("citations", true.into()),
69        ]),
70    );
71    s.advertise(
72        Capability::Graph,
73        obj(&[("ops", vec![Json::from("local"), Json::from("global")].into())]),
74    );
75
76    s.on(Method::EMBED, |params| {
77        // Accept `inputs` (preferred, spec §7.3) or the legacy `texts` synonym.
78        let items = params
79            .get("inputs")
80            .or_else(|| params.get("texts"))
81            .and_then(|v| v.as_array())
82            .cloned()
83            .unwrap_or_default();
84        let vectors: Vec<Json> = items
85            .iter()
86            .filter_map(|x| x.as_str())
87            .map(|t| Json::from(embed_one(t)))
88            .collect();
89        Ok(obj(&[("vectors", Json::Array(vectors)), ("dimensions", (DIM as i64).into())]))
90    });
91
92    s.on(Method::RETRIEVE, |params| {
93        let q = params.get_str("query").unwrap_or("");
94        let k = params.get("k").and_then(|v| v.as_i64()).unwrap_or(10).max(0) as usize;
95        Ok(obj(&[("hits", search(q, k))]))
96    });
97
98    s.on(Method::GRAPH, |params| {
99        let op = params.get_str("op").unwrap_or("local");
100        match op {
101            "local" => {
102                let q = params.get_str("query").unwrap_or("");
103                let k = params.get("k").and_then(|v| v.as_i64()).unwrap_or(5).max(0) as usize;
104                Ok(obj(&[("hits", search(q, k))]))
105            }
106            "global" => Ok(obj(&[
107                ("summary", "a global community summary would go here".into()),
108                ("communities", 1.into()),
109            ])),
110            other => Ok(obj(&[("op", other.into()), ("note", "unimplemented".into())])),
111        }
112    });
113
114    s
115}
Source

pub fn advertise(&mut self, cap: Capability, meta: Json) -> &mut Self

Advertise a capability with optional metadata (pass Json::object() for none). Advertising is independent of registering a handler; a gated call needs both or it is CapabilityMissing.

Examples found in repository?
examples/example_server.rs (lines 59-62)
56fn build() -> Server {
57    let mut s = Server::new();
58    s.set_info("rcp-example", "1.0.0");
59    s.advertise(
60        Capability::Embed,
61        obj(&[("dimensions", (DIM as i64).into()), ("modes", vec![Json::from("dense")].into())]),
62    );
63    s.advertise(
64        Capability::Retrieve,
65        obj(&[
66            ("maxK", 100.into()),
67            ("modes", vec![Json::from("dense")].into()),
68            ("citations", true.into()),
69        ]),
70    );
71    s.advertise(
72        Capability::Graph,
73        obj(&[("ops", vec![Json::from("local"), Json::from("global")].into())]),
74    );
75
76    s.on(Method::EMBED, |params| {
77        // Accept `inputs` (preferred, spec §7.3) or the legacy `texts` synonym.
78        let items = params
79            .get("inputs")
80            .or_else(|| params.get("texts"))
81            .and_then(|v| v.as_array())
82            .cloned()
83            .unwrap_or_default();
84        let vectors: Vec<Json> = items
85            .iter()
86            .filter_map(|x| x.as_str())
87            .map(|t| Json::from(embed_one(t)))
88            .collect();
89        Ok(obj(&[("vectors", Json::Array(vectors)), ("dimensions", (DIM as i64).into())]))
90    });
91
92    s.on(Method::RETRIEVE, |params| {
93        let q = params.get_str("query").unwrap_or("");
94        let k = params.get("k").and_then(|v| v.as_i64()).unwrap_or(10).max(0) as usize;
95        Ok(obj(&[("hits", search(q, k))]))
96    });
97
98    s.on(Method::GRAPH, |params| {
99        let op = params.get_str("op").unwrap_or("local");
100        match op {
101            "local" => {
102                let q = params.get_str("query").unwrap_or("");
103                let k = params.get("k").and_then(|v| v.as_i64()).unwrap_or(5).max(0) as usize;
104                Ok(obj(&[("hits", search(q, k))]))
105            }
106            "global" => Ok(obj(&[
107                ("summary", "a global community summary would go here".into()),
108                ("communities", 1.into()),
109            ])),
110            other => Ok(obj(&[("op", other.into()), ("note", "unimplemented".into())])),
111        }
112    });
113
114    s
115}
Source

pub fn on<F>(&mut self, method: &str, handler: F) -> &mut Self
where F: FnMut(&Json) -> Result<Json, RcpError> + 'static,

Register a handler for method (a Method::* constant or its string).

Examples found in repository?
examples/example_server.rs (lines 76-90)
56fn build() -> Server {
57    let mut s = Server::new();
58    s.set_info("rcp-example", "1.0.0");
59    s.advertise(
60        Capability::Embed,
61        obj(&[("dimensions", (DIM as i64).into()), ("modes", vec![Json::from("dense")].into())]),
62    );
63    s.advertise(
64        Capability::Retrieve,
65        obj(&[
66            ("maxK", 100.into()),
67            ("modes", vec![Json::from("dense")].into()),
68            ("citations", true.into()),
69        ]),
70    );
71    s.advertise(
72        Capability::Graph,
73        obj(&[("ops", vec![Json::from("local"), Json::from("global")].into())]),
74    );
75
76    s.on(Method::EMBED, |params| {
77        // Accept `inputs` (preferred, spec §7.3) or the legacy `texts` synonym.
78        let items = params
79            .get("inputs")
80            .or_else(|| params.get("texts"))
81            .and_then(|v| v.as_array())
82            .cloned()
83            .unwrap_or_default();
84        let vectors: Vec<Json> = items
85            .iter()
86            .filter_map(|x| x.as_str())
87            .map(|t| Json::from(embed_one(t)))
88            .collect();
89        Ok(obj(&[("vectors", Json::Array(vectors)), ("dimensions", (DIM as i64).into())]))
90    });
91
92    s.on(Method::RETRIEVE, |params| {
93        let q = params.get_str("query").unwrap_or("");
94        let k = params.get("k").and_then(|v| v.as_i64()).unwrap_or(10).max(0) as usize;
95        Ok(obj(&[("hits", search(q, k))]))
96    });
97
98    s.on(Method::GRAPH, |params| {
99        let op = params.get_str("op").unwrap_or("local");
100        match op {
101            "local" => {
102                let q = params.get_str("query").unwrap_or("");
103                let k = params.get("k").and_then(|v| v.as_i64()).unwrap_or(5).max(0) as usize;
104                Ok(obj(&[("hits", search(q, k))]))
105            }
106            "global" => Ok(obj(&[
107                ("summary", "a global community summary would go here".into()),
108                ("communities", 1.into()),
109            ])),
110            other => Ok(obj(&[("op", other.into()), ("note", "unimplemented".into())])),
111        }
112    });
113
114    s
115}
Source

pub fn handle(&mut self, request: &Json) -> Option<Json>

Handle one JSON-RPC request → reply, or None for a notification that warrants no response. Never panics.

Source

pub fn handle_line(&mut self, line: &str) -> String

Parse a JSON line, dispatch (single or batch), and return the reply string (“” when there is no response, e.g. an all-notification batch).

Source

pub fn serve_stdio(&mut self)

Serve newline-delimited JSON-RPC over stdin/stdout until shutdown/EOF.

Examples found in repository?
examples/example_server.rs (line 124)
117fn main() {
118    let args: Vec<String> = std::env::args().collect();
119    let mut s = build();
120    if args.len() >= 3 && args[1] == "--http" {
121        let port: u16 = args[2].parse().unwrap_or(8000);
122        let _ = s.serve_http(port);
123    } else {
124        s.serve_stdio();
125    }
126}
Source

pub fn serve_http(&mut self, port: u16) -> Result<(), RcpError>

Serve JSON-RPC over minimal HTTP/1.1 on 127.0.0.1:port (200 for a response, 204 for a notification). Loops until an accept error.

Examples found in repository?
examples/example_server.rs (line 122)
117fn main() {
118    let args: Vec<String> = std::env::args().collect();
119    let mut s = build();
120    if args.len() >= 3 && args[1] == "--http" {
121        let port: u16 = args[2].parse().unwrap_or(8000);
122        let _ = s.serve_http(port);
123    } else {
124        s.serve_stdio();
125    }
126}

Trait Implementations§

Source§

impl Default for Server

Source§

fn default() -> Server

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Server

§

impl !Send for Server

§

impl !Sync for Server

§

impl !UnwindSafe for Server

§

impl Freeze for Server

§

impl Unpin for Server

§

impl UnsafeUnpin for Server

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.