use super::*;
impl Hasher for FxHasher {
#[inline(always)]
fn finish(&self) -> u64 {
let Self { state } = *self;
state
}
#[inline(always)]
fn write(&mut self, bytes: &[u8]) {
let Self { state } = self;
let mut h: u64 = *state;
let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
for chunk in chunks {
h = (h.rotate_left(5) ^ u64::from_ne_bytes(*chunk)).wrapping_mul(FX_HASH_K);
}
let mut tail: &[u8] = rem;
if tail.len() >= 4 {
let word: u32 = u32::from_ne_bytes([tail[0], tail[1], tail[2], tail[3]]);
h = (h.rotate_left(5) ^ u64::from(word)).wrapping_mul(FX_HASH_K);
tail = &tail[4..];
}
if tail.len() >= 2 {
let half: u16 = u16::from_ne_bytes([tail[0], tail[1]]);
h = (h.rotate_left(5) ^ u64::from(half)).wrapping_mul(FX_HASH_K);
tail = &tail[2..];
}
if let Some(&b) = tail.first() {
h = (h.rotate_left(5) ^ u64::from(b)).wrapping_mul(FX_HASH_K);
}
*state = h;
}
#[inline(always)]
fn write_u8(&mut self, i: u8) {
let Self { state } = self;
*state = (state.rotate_left(5) ^ u64::from(i)).wrapping_mul(FX_HASH_K);
}
}
impl<'de> Visitor<'de> for RpcFieldKeyVisitor {
type Value = RpcFieldKey;
fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str(EXPECT_FIELD_KEY)
}
#[inline(always)]
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(match v {
FIELD_JSONRPC => RpcFieldKey::Jsonrpc,
FIELD_METHOD => RpcFieldKey::Method,
FIELD_PARAMS => RpcFieldKey::Params,
FIELD_ID => RpcFieldKey::Id,
_ => RpcFieldKey::Other,
})
}
}
impl<'de> Deserialize<'de> for RpcFieldKey {
#[inline(always)]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_identifier(RpcFieldKeyVisitor)
}
}
impl<'de> Visitor<'de> for LenientStrVisitor {
type Value = LenientStr<'de>;
fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str(EXPECT_LENIENT_STR)
}
#[inline(always)]
fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(LenientStr::Valid(Cow::Borrowed(v)))
}
#[inline]
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(LenientStr::Valid(Cow::Owned(v.to_owned())))
}
#[inline]
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(LenientStr::Valid(Cow::Owned(v)))
}
fn visit_bool<E>(self, _: bool) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(LenientStr::Invalid)
}
fn visit_i64<E>(self, _: i64) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(LenientStr::Invalid)
}
fn visit_u64<E>(self, _: u64) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(LenientStr::Invalid)
}
fn visit_f64<E>(self, _: f64) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(LenientStr::Invalid)
}
fn visit_unit<E>(self) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(LenientStr::Null)
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
while seq.next_element::<IgnoredAny>()?.is_some() {}
Ok(LenientStr::Invalid)
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
while map.next_entry::<IgnoredAny, IgnoredAny>()?.is_some() {}
Ok(LenientStr::Invalid)
}
}
impl<'de> Deserialize<'de> for LenientStr<'de> {
#[inline(always)]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_any(LenientStrVisitor)
}
}
impl<'de> Visitor<'de> for LenientIdVisitor {
type Value = LenientId;
fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str(EXPECT_RPC_ID)
}
#[inline(always)]
fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(LenientId::Valid(Some(RpcId::Number(v))))
}
#[inline(always)]
fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(match i64::try_from(v) {
Ok(n) => LenientId::Valid(Some(RpcId::Number(n))),
Err(_) => LenientId::Invalid,
})
}
#[inline]
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(LenientId::Valid(Some(RpcId::Text(v.to_owned()))))
}
#[inline]
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(LenientId::Valid(Some(RpcId::Text(v))))
}
#[inline(always)]
fn visit_unit<E>(self) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(LenientId::Valid(None))
}
fn visit_bool<E>(self, _: bool) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(LenientId::Invalid)
}
fn visit_f64<E>(self, _: f64) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(LenientId::Invalid)
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
while seq.next_element::<IgnoredAny>()?.is_some() {}
Ok(LenientId::Invalid)
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
while map.next_entry::<IgnoredAny, IgnoredAny>()?.is_some() {}
Ok(LenientId::Invalid)
}
}
impl<'de> Deserialize<'de> for LenientId {
#[inline(always)]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_any(LenientIdVisitor)
}
}
impl<'de> Visitor<'de> for BorrowedBatchItemVisitor {
type Value = BorrowedBatchItem<'de>;
fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str(EXPECT_BATCH_ITEM)
}
#[inline]
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut jsonrpc: Option<Cow<'de, str>> = None;
let mut method: Option<Cow<'de, str>> = None;
let mut params: Option<Value> = None;
let mut id: Option<RpcId> = None;
let mut seen: u8 = 0;
let mut bad: bool = false;
while let Some(key) = map.next_key::<RpcFieldKey>()? {
match key {
RpcFieldKey::Jsonrpc => {
if (seen & 0x01) != 0 {
bad = true;
}
seen |= 0x01;
match map.next_value::<LenientStr<'de>>()? {
LenientStr::Valid(s) => jsonrpc = Some(s),
LenientStr::Null => jsonrpc = None,
LenientStr::Invalid => bad = true,
}
}
RpcFieldKey::Method => {
if (seen & 0x02) != 0 {
bad = true;
}
seen |= 0x02;
match map.next_value::<LenientStr<'de>>()? {
LenientStr::Valid(s) => method = Some(s),
LenientStr::Null => method = None,
LenientStr::Invalid => bad = true,
}
}
RpcFieldKey::Params => {
if (seen & 0x04) != 0 {
bad = true;
}
seen |= 0x04;
params = map.next_value::<Option<Value>>()?;
}
RpcFieldKey::Id => {
if (seen & 0x08) != 0 {
bad = true;
}
seen |= 0x08;
match map.next_value::<LenientId>()? {
LenientId::Valid(parsed) => id = parsed,
LenientId::Invalid => bad = true,
}
}
RpcFieldKey::Other => {
let _: IgnoredAny = map.next_value()?;
}
}
}
if bad {
return Ok(BorrowedBatchItem::Invalid);
}
Ok(BorrowedBatchItem::Request(BorrowedRpcRequest {
jsonrpc,
method,
params,
id,
}))
}
fn visit_bool<E>(self, _: bool) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(BorrowedBatchItem::Invalid)
}
fn visit_i64<E>(self, _: i64) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(BorrowedBatchItem::Invalid)
}
fn visit_u64<E>(self, _: u64) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(BorrowedBatchItem::Invalid)
}
fn visit_f64<E>(self, _: f64) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(BorrowedBatchItem::Invalid)
}
fn visit_str<E>(self, _: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(BorrowedBatchItem::Invalid)
}
fn visit_unit<E>(self) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(BorrowedBatchItem::Invalid)
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
while seq.next_element::<IgnoredAny>()?.is_some() {}
Ok(BorrowedBatchItem::Invalid)
}
}
impl<'de> Deserialize<'de> for BorrowedBatchItem<'de> {
#[inline(always)]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_any(BorrowedBatchItemVisitor)
}
}
impl Display for RpcError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(
f,
"JSON-RPC error {}: {}",
self.get_code(),
self.get_message()
)
}
}
impl Error for RpcError {}
impl RpcError {
pub fn parse_error() -> Self {
Self::custom(RPC_PARSE_ERROR, MSG_PARSE_ERROR, None)
}
pub fn invalid_request() -> Self {
Self::custom(RPC_INVALID_REQUEST, MSG_INVALID_REQUEST, None)
}
pub fn method_not_found() -> Self {
Self::custom(RPC_METHOD_NOT_FOUND, MSG_METHOD_NOT_FOUND, None)
}
pub fn invalid_params(data: Option<Value>) -> Self {
Self::custom(RPC_INVALID_PARAMS, MSG_INVALID_PARAMS, data)
}
pub fn internal_error(data: Option<Value>) -> Self {
Self::custom(RPC_INTERNAL_ERROR, MSG_INTERNAL_ERROR, data)
}
pub fn custom<M>(code: i64, message: M, data: Option<Value>) -> Self
where
M: Into<String>,
{
Self {
code,
message: message.into(),
data,
}
}
}
impl RpcResponse {
pub fn success(id: RpcId, result: Value) -> Self {
Self {
jsonrpc: JSONRPC_VERSION.to_owned(),
result: Some(result),
error: None,
id,
}
}
pub fn failure(id: RpcId, error: RpcError) -> Self {
Self {
jsonrpc: JSONRPC_VERSION.to_owned(),
result: None,
error: Some(error),
id,
}
}
}
impl Default for RpcConfig {
fn default() -> Self {
Self {
endpoint: DEFAULT_RPC_ENDPOINT.to_owned(),
max_body_size: DEFAULT_RPC_MAX_BODY_SIZE,
max_batch_size: DEFAULT_RPC_MAX_BATCH_SIZE,
}
}
}
impl RpcConfig {
pub fn with_endpoint<E>(mut self, endpoint: E) -> Self
where
E: Into<String>,
{
self.set_endpoint(endpoint.into());
self
}
pub fn with_max_body_size(mut self, max_body_size: usize) -> Self {
self.set_max_body_size(max_body_size);
self
}
pub fn with_max_batch_size(mut self, max_batch_size: usize) -> Self {
self.set_max_batch_size(max_batch_size);
self
}
}
impl Default for RpcRouter {
fn default() -> Self {
Self {
methods: HashMap::default(),
interceptors: Vec::new(),
}
}
}
impl CompactRpcResponse {
#[inline(always)]
pub(crate) fn success(id: RpcId, result: Value) -> Self {
Self {
body: CompactRpcBody::Result(result),
id,
}
}
#[inline(always)]
pub(crate) fn failure(id: RpcId, error: RpcError) -> Self {
Self {
body: CompactRpcBody::Error(error),
id,
}
}
#[inline(always)]
pub(crate) fn static_error(id: RpcId, raw_error: &'static [u8]) -> Self {
Self {
body: CompactRpcBody::StaticError(raw_error),
id,
}
}
}
impl RpcRouter {
pub fn new() -> Self {
Self::default()
}
pub fn add_interceptor(&mut self, interceptor: Arc<dyn RpcInterceptor>) -> &mut Self {
let Self { interceptors, .. } = self;
interceptors.push(interceptor);
self
}
pub fn register<N, F, Fut>(&mut self, name: N, handler: F) -> &mut Self
where
N: Into<String>,
F: Fn(Option<Value>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<Value, RpcError>> + Send + 'static,
{
let Self { methods, .. } = self;
let boxed: RpcHandler = Arc::new(move |params: Option<Value>| Box::pin(handler(params)));
methods.insert(name.into(), boxed);
self
}
pub fn has_method(&self, name: &str) -> bool {
let Self { methods, .. } = self;
methods.contains_key(name)
}
pub fn method_names(&self) -> Vec<String> {
let Self { methods, .. } = self;
methods.keys().cloned().collect()
}
fn prepare_call(&self, raw: Value) -> PreparedRpcCall {
let Self {
methods,
interceptors,
} = self;
let req: RpcRequest = match from_value(raw) {
Ok(parsed) => parsed,
Err(_) => {
return Err(Some(Box::new(RpcResponse::failure(
RpcId::Null,
RpcError::invalid_request(),
))));
}
};
let RpcRequest {
jsonrpc,
method,
params,
id,
}: RpcRequest = req;
if jsonrpc != JSONRPC_VERSION || method.is_empty() {
return Err(Some(Box::new(RpcResponse::failure(
id.unwrap_or(RpcId::Null),
RpcError::invalid_request(),
))));
}
for interceptor in interceptors {
if let Err(err) = interceptor.before_call(&method, ¶ms) {
return Err(id.map(|corr: RpcId| Box::new(RpcResponse::failure(corr, err))));
}
}
let Some(handler) = methods.get(method.as_str()) else {
return Err(id.map(|corr: RpcId| {
Box::new(RpcResponse::failure(corr, RpcError::method_not_found()))
}));
};
Ok((Arc::clone(handler), params, id))
}
#[inline]
fn prepare_borrowed_call(&self, req: BorrowedRpcRequest<'_>) -> PreparedBorrowedCall<'_> {
let Self {
methods,
interceptors,
} = self;
let BorrowedRpcRequest {
jsonrpc,
method,
params,
id,
}: BorrowedRpcRequest<'_> = req;
let Some(method_name) = method else {
return Err(Some(CompactRpcResponse::static_error(
id.unwrap_or(RpcId::Null),
STATIC_ERR_INVALID_REQUEST,
)));
};
let version_ok: bool = matches!(
jsonrpc.as_deref(),
Some(ver) if ver == JSONRPC_VERSION
);
if !version_ok || method_name.is_empty() {
return Err(Some(CompactRpcResponse::static_error(
id.unwrap_or(RpcId::Null),
STATIC_ERR_INVALID_REQUEST,
)));
}
let method_str: &str = method_name.as_ref();
for interceptor in interceptors {
if let Err(err) = interceptor.before_call(method_str, ¶ms) {
return Err(id.map(|corr: RpcId| CompactRpcResponse::failure(corr, err)));
}
}
let Some(handler) = methods.get(method_str) else {
return Err(id.map(|corr: RpcId| {
CompactRpcResponse::static_error(corr, STATIC_ERR_METHOD_NOT_FOUND)
}));
};
Ok((handler, params, id))
}
#[inline]
async fn dispatch_single_object(
&self,
raw: &[u8],
) -> Result<Option<CompactRpcResponse>, &'static [u8]> {
let item: BorrowedBatchItem<'_> = match from_slice(raw) {
Ok(parsed) => parsed,
Err(_) => return Err(PREBUILT_PARSE_ERROR),
};
let BorrowedBatchItem::Request(req) = item else {
return Err(PREBUILT_INVALID_REQUEST);
};
match self.prepare_borrowed_call(req) {
Ok((handler, params, id_opt)) => {
let outcome: Result<Value, RpcError> = handler(params).await;
let Some(id) = id_opt else {
return Ok(None);
};
let compact: CompactRpcResponse = match outcome {
Ok(value) => CompactRpcResponse::success(id, value),
Err(err) => CompactRpcResponse::failure(id, err),
};
Ok(Some(compact))
}
Err(immediate) => Ok(immediate),
}
}
pub async fn dispatch_value(&self, raw: Value) -> Option<RpcResponse> {
match self.prepare_call(raw) {
Ok((handler, params, id_opt)) => {
let outcome: Result<Value, RpcError> = handler(params).await;
let id: RpcId = id_opt?;
match outcome {
Ok(value) => Some(RpcResponse::success(id, value)),
Err(err) => Some(RpcResponse::failure(id, err)),
}
}
Err(immediate) => immediate.map(|resp: Box<RpcResponse>| *resp),
}
}
pub async fn dispatch_bytes(&self, raw: &[u8], config: &RpcConfig) -> Option<Vec<u8>> {
let Some(first_byte) = first_non_ws_byte(raw) else {
return Some(PREBUILT_PARSE_ERROR.to_vec());
};
if first_byte == BYTE_LBRACE {
return match self.dispatch_single_object(raw).await {
Ok(Some(compact)) => Some(encode_compact_response(&compact)),
Ok(None) => None,
Err(static_err) => Some(static_err.to_vec()),
};
}
if first_byte == BYTE_LBRACKET {
let items: Vec<BorrowedBatchItem<'_>> = match from_slice(raw) {
Ok(parsed) => parsed,
Err(_) => return Some(PREBUILT_PARSE_ERROR.to_vec()),
};
if items.is_empty() {
return Some(PREBUILT_INVALID_REQUEST.to_vec());
}
if items.len() > config.get_max_batch_size() {
return Some(PREBUILT_BATCH_TOO_LARGE.to_vec());
}
let mut slots: Vec<Option<BatchDispatchSlot>> = Vec::with_capacity(items.len());
let mut stack_active: [usize; DEFAULT_RPC_MAX_BATCH_SIZE] =
[0usize; DEFAULT_RPC_MAX_BATCH_SIZE];
let mut stack_active_len: usize = 0;
let mut heap_active: Vec<usize> = Vec::new();
for item in items {
match item {
BorrowedBatchItem::Request(req) => match self.prepare_borrowed_call(req) {
Ok((handler, params, id)) => {
let idx: usize = slots.len();
if stack_active_len < DEFAULT_RPC_MAX_BATCH_SIZE {
stack_active[stack_active_len] = idx;
stack_active_len += 1;
} else {
if heap_active.is_empty() {
heap_active.extend_from_slice(&stack_active);
}
heap_active.push(idx);
}
slots.push(Some(BatchDispatchSlot::Pending {
future: handler(params),
id,
}));
}
Err(immediate) => {
slots.push(immediate.map(BatchDispatchSlot::Ready));
}
},
BorrowedBatchItem::Invalid => {
slots.push(Some(BatchDispatchSlot::Ready(
CompactRpcResponse::static_error(
RpcId::Null,
STATIC_ERR_INVALID_REQUEST,
),
)));
}
}
}
if !heap_active.is_empty() {
poll_fn(|cx: &mut task::Context<'_>| {
let mut i: usize = 0;
while i < heap_active.len() {
let slot_idx: usize = heap_active[i];
let slot_opt: &mut Option<BatchDispatchSlot> = &mut slots[slot_idx];
if let Some(BatchDispatchSlot::Pending { future, .. }) = slot_opt
&& let Poll::Ready(outcome) = future.as_mut().poll(cx)
{
let ready_slot: Option<BatchDispatchSlot> = match slot_opt.take() {
Some(BatchDispatchSlot::Pending { id: Some(corr), .. }) => {
let compact: CompactRpcResponse = match outcome {
Ok(value) => CompactRpcResponse::success(corr, value),
Err(err) => CompactRpcResponse::failure(corr, err),
};
Some(BatchDispatchSlot::Ready(compact))
}
_ => None,
};
*slot_opt = ready_slot;
let _: usize = heap_active.swap_remove(i);
} else {
i += 1;
}
}
if heap_active.is_empty() {
Poll::Ready(())
} else {
Poll::Pending
}
})
.await;
} else if stack_active_len > 0 {
poll_fn(|cx: &mut task::Context<'_>| {
let mut i: usize = 0;
while i < stack_active_len {
let slot_idx: usize = stack_active[i];
let slot_opt: &mut Option<BatchDispatchSlot> = &mut slots[slot_idx];
if let Some(BatchDispatchSlot::Pending { future, .. }) = slot_opt
&& let Poll::Ready(outcome) = future.as_mut().poll(cx)
{
let ready_slot: Option<BatchDispatchSlot> = match slot_opt.take() {
Some(BatchDispatchSlot::Pending { id: Some(corr), .. }) => {
let compact: CompactRpcResponse = match outcome {
Ok(value) => CompactRpcResponse::success(corr, value),
Err(err) => CompactRpcResponse::failure(corr, err),
};
Some(BatchDispatchSlot::Ready(compact))
}
_ => None,
};
*slot_opt = ready_slot;
stack_active_len -= 1;
stack_active[i] = stack_active[stack_active_len];
} else {
i += 1;
}
}
if stack_active_len == 0 {
Poll::Ready(())
} else {
Poll::Pending
}
})
.await;
}
return encode_ready_batch_slots(&slots);
}
if from_slice::<IgnoredAny>(raw).is_ok() {
Some(PREBUILT_INVALID_REQUEST.to_vec())
} else {
Some(PREBUILT_PARSE_ERROR.to_vec())
}
}
#[inline]
pub(crate) async fn dispatch_and_send_http11(
&self,
stream: &mut Stream,
raw: &[u8],
config: &RpcConfig,
) {
let Some(first_byte) = first_non_ws_byte(raw) else {
let mut wire_stack: [u8; RPC_WIRE_STACK_CAP] = [0u8; RPC_WIRE_STACK_CAP];
if let Some(len) = format_http11_json_wire_stack(PREBUILT_PARSE_ERROR, &mut wire_stack)
{
let _: Result<(), ResponseError> = stream.try_send(&wire_stack[..len]).await;
}
return;
};
if first_byte == BYTE_LBRACE {
match self.dispatch_single_object(raw).await {
Ok(Some(compact)) => {
let mut payload_stack: [u8; RPC_PAYLOAD_STACK_CAP] =
[0u8; RPC_PAYLOAD_STACK_CAP];
if let Some(plen) = write_compact_response_stack(&compact, &mut payload_stack) {
let mut wire_stack: [u8; RPC_WIRE_STACK_CAP] = [0u8; RPC_WIRE_STACK_CAP];
if let Some(wlen) =
format_http11_json_wire_stack(&payload_stack[..plen], &mut wire_stack)
{
let _: Result<(), ResponseError> =
stream.try_send(&wire_stack[..wlen]).await;
return;
}
}
let payload: Vec<u8> = encode_compact_response(&compact);
let wire: Vec<u8> = build_http11_json_wire_vec(&payload);
let _: Result<(), ResponseError> = stream.try_send(&wire).await;
}
Ok(None) => {
let wire: &[u8] =
get_prebuilt_empty_wire(&WIRE_204_CACHE, HttpStatus::NoContent);
let _: Result<(), ResponseError> = stream.try_send(wire).await;
}
Err(static_err) => {
let mut wire_stack: [u8; RPC_WIRE_STACK_CAP] = [0u8; RPC_WIRE_STACK_CAP];
if let Some(wlen) = format_http11_json_wire_stack(static_err, &mut wire_stack) {
let _: Result<(), ResponseError> =
stream.try_send(&wire_stack[..wlen]).await;
}
}
}
return;
}
match self.dispatch_bytes(raw, config).await {
Some(payload) => {
let mut wire_stack: [u8; RPC_WIRE_STACK_CAP] = [0u8; RPC_WIRE_STACK_CAP];
if let Some(wlen) = format_http11_json_wire_stack(&payload, &mut wire_stack) {
let _: Result<(), ResponseError> = stream.try_send(&wire_stack[..wlen]).await;
} else {
let wire: Vec<u8> = build_http11_json_wire_vec(&payload);
let _: Result<(), ResponseError> = stream.try_send(&wire).await;
}
}
None => {
let wire: &[u8] = get_prebuilt_empty_wire(&WIRE_204_CACHE, HttpStatus::NoContent);
let _: Result<(), ResponseError> = stream.try_send(wire).await;
}
}
}
}
impl RpcPlugin {
pub fn init(config: RpcConfig, router: RpcRouter) -> &'static Self {
RPC_PLUGIN.get_or_init(|| Self { config, router })
}
pub fn get() -> Option<&'static Self> {
RPC_PLUGIN.get()
}
pub fn get_config(&self) -> &RpcConfig {
let Self { config, .. } = self;
config
}
pub fn get_router(&self) -> &RpcRouter {
let Self { router, .. } = self;
router
}
}
impl ServerHook for RpcHook {
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
let Some(plugin) = RpcPlugin::get() else {
return Status::Continue;
};
let config: &RpcConfig = plugin.get_config();
if ctx.get_request().get_path() != config.get_endpoint() {
return Status::Continue;
}
let resp: &Response = ctx.get_response();
let can_fast_wire: bool = ctx.get_request().get_version().is_http1_1()
&& resp.get_version().is_http1_1()
&& resp.get_headers().is_empty()
&& (resp.get_reason_phrase().is_empty() || resp.get_reason_phrase().as_str() == OK);
if !ctx.get_request().get_method().is_post() {
if can_fast_wire {
let wire: &[u8] =
get_prebuilt_empty_wire(&WIRE_405_CACHE, HttpStatus::MethodNotAllowed);
let _: Result<(), ResponseError> = stream.try_send(wire).await;
return Status::Reject;
}
ctx.get_mut_response()
.set_status_code(HttpStatus::MethodNotAllowed.code())
.set_body(Vec::new());
let wire: Vec<u8> = ctx.get_mut_response().build();
let _: Result<(), ResponseError> = stream.try_send(&wire).await;
return Status::Reject;
}
let body: &[u8] = ctx.get_request().get_body();
if body.len() > config.get_max_body_size() {
if can_fast_wire {
let wire: &[u8] =
get_prebuilt_empty_wire(&WIRE_413_CACHE, HttpStatus::PayloadTooLarge);
let _: Result<(), ResponseError> = stream.try_send(wire).await;
return Status::Reject;
}
ctx.get_mut_response()
.set_status_code(HttpStatus::PayloadTooLarge.code())
.set_body(Vec::new());
let wire: Vec<u8> = ctx.get_mut_response().build();
let _: Result<(), ResponseError> = stream.try_send(&wire).await;
return Status::Reject;
}
if can_fast_wire {
plugin
.get_router()
.dispatch_and_send_http11(stream, body, config)
.await;
return Status::Reject;
}
match plugin.get_router().dispatch_bytes(body, config).await {
Some(payload) => {
ctx.get_mut_response()
.set_status_code(HttpStatus::Ok.code())
.set_header(CONTENT_TYPE, APPLICATION_JSON);
*ctx.get_mut_response().get_mut_body() = payload;
}
None => {
ctx.get_mut_response()
.set_status_code(HttpStatus::NoContent.code())
.get_mut_body()
.clear();
}
}
let wire: Vec<u8> = ctx.get_mut_response().build();
let _: Result<(), ResponseError> = stream.try_send(&wire).await;
Status::Reject
}
}