1use std::{borrow::Cow, collections::HashMap};
4
5use parse_display_derive::{Display, FromStr};
6use schemars::JsonSchema;
7use serde::{Deserialize, Serialize};
8#[cfg(feature = "slog")]
9use slog::{Record, Serializer, KV};
10use uuid::Uuid;
11
12use crate::{
13 id::ModelingCmdId,
14 ok_response::OkModelingCmdResponse,
15 shared::{EngineErrorCode, ExportFile},
16 ModelingCmd,
17};
18
19#[derive(Display, FromStr, Copy, Eq, PartialEq, Debug, JsonSchema, Deserialize, Serialize, Clone, Ord, PartialOrd)]
21#[serde(rename_all = "snake_case")]
22pub enum ErrorCode {
23 InternalEngine,
25 InternalApi,
27 BadRequest,
31 AuthTokenMissing,
33 AuthTokenInvalid,
35 InvalidJson,
37 InvalidBson,
39 WrongProtocol,
41 ConnectionProblem,
43 MessageTypeNotAccepted,
45 MessageTypeNotAcceptedForWebRTC,
48}
49
50impl From<EngineErrorCode> for ErrorCode {
53 fn from(value: EngineErrorCode) -> Self {
54 match value {
55 EngineErrorCode::InternalEngine => Self::InternalEngine,
56 EngineErrorCode::BadRequest => Self::BadRequest,
57 }
58 }
59}
60
61#[derive(Debug, Clone, Deserialize, Serialize)]
63#[cfg_attr(feature = "derive-jsonschema-on-enums", derive(schemars::JsonSchema))]
64pub struct ModelingCmdReq {
65 pub cmd: ModelingCmd,
67 pub cmd_id: ModelingCmdId,
69}
70
71#[allow(clippy::large_enum_variant)]
73#[derive(Serialize, Deserialize, Debug, Clone)]
74#[cfg_attr(feature = "derive-jsonschema-on-enums", derive(schemars::JsonSchema))]
75#[serde(tag = "type", rename_all = "snake_case")]
76pub enum WebSocketRequest {
77 TrickleIce {
80 candidate: Box<RtcIceCandidateInit>,
82 },
83 SdpOffer {
85 offer: Box<RtcSessionDescription>,
87 },
88 ModelingCmdReq(ModelingCmdReq),
90 ModelingCmdBatchReq(ModelingBatch),
92 Ping {},
94
95 MetricsResponse {
97 metrics: Box<ClientMetrics>,
99 },
100
101 Debug {},
103
104 Headers {
106 headers: HashMap<String, String>,
108 },
109}
110
111#[derive(Serialize, Deserialize, Debug, Clone)]
113#[cfg_attr(feature = "derive-jsonschema-on-enums", derive(schemars::JsonSchema))]
114#[serde(rename_all = "snake_case")]
115pub struct ModelingBatch {
116 pub requests: Vec<ModelingCmdReq>,
118 pub batch_id: ModelingCmdId,
122 #[serde(default)]
125 pub responses: bool,
126}
127
128impl std::default::Default for ModelingBatch {
129 fn default() -> Self {
131 Self {
132 requests: Default::default(),
133 batch_id: Uuid::new_v4().into(),
134 responses: false,
135 }
136 }
137}
138
139impl ModelingBatch {
140 pub fn push(&mut self, req: ModelingCmdReq) {
142 self.requests.push(req);
143 }
144
145 pub fn is_empty(&self) -> bool {
147 self.requests.is_empty()
148 }
149}
150
151#[derive(serde::Serialize, serde::Deserialize, Debug, JsonSchema, Clone)]
155pub struct IceServer {
156 pub urls: Vec<String>,
160 pub credential: Option<String>,
162 pub username: Option<String>,
164}
165
166#[derive(Serialize, Deserialize, Debug, Clone)]
168#[cfg_attr(feature = "derive-jsonschema-on-enums", derive(schemars::JsonSchema))]
169#[serde(tag = "type", content = "data", rename_all = "snake_case")]
170pub enum OkWebSocketResponseData {
171 IceServerInfo {
173 ice_servers: Vec<IceServer>,
175 },
176 TrickleIce {
179 candidate: Box<RtcIceCandidateInit>,
181 },
182 SdpAnswer {
184 answer: Box<RtcSessionDescription>,
186 },
187 Modeling {
189 modeling_response: OkModelingCmdResponse,
191 },
192 ModelingBatch {
194 responses: HashMap<ModelingCmdId, BatchResponse>,
197 },
198 Export {
200 files: Vec<RawFile>,
202 },
203
204 MetricsRequest {},
206
207 ModelingSessionData {
209 session: ModelingSessionData,
211 },
212
213 Pong {},
215
216 Debug {
218 name: String,
220 },
221}
222
223#[derive(Debug, Serialize, Deserialize, Clone)]
225#[cfg_attr(feature = "derive-jsonschema-on-enums", derive(schemars::JsonSchema))]
226#[serde(rename_all = "snake_case")]
227pub struct SuccessWebSocketResponse {
228 pub success: bool,
230 pub request_id: Option<Uuid>,
234 pub resp: OkWebSocketResponseData,
237}
238
239#[derive(JsonSchema, Debug, Serialize, Deserialize, Clone)]
241#[serde(rename_all = "snake_case")]
242pub struct FailureWebSocketResponse {
243 pub success: bool,
245 pub request_id: Option<Uuid>,
249 pub errors: Vec<ApiError>,
251}
252
253#[derive(Debug, Serialize, Deserialize, Clone)]
256#[cfg_attr(feature = "derive-jsonschema-on-enums", derive(schemars::JsonSchema))]
257#[serde(rename_all = "snake_case", untagged)]
258pub enum WebSocketResponse {
259 Success(SuccessWebSocketResponse),
261 Failure(FailureWebSocketResponse),
263}
264
265#[derive(Debug, Serialize, Deserialize, Clone)]
268#[cfg_attr(feature = "derive-jsonschema-on-enums", derive(schemars::JsonSchema))]
269#[serde(rename_all = "snake_case", untagged)]
270pub enum BatchResponse {
271 Success {
273 response: OkModelingCmdResponse,
275 },
276 Failure {
278 errors: Vec<ApiError>,
280 },
281}
282
283impl WebSocketResponse {
284 pub fn success(request_id: Option<Uuid>, resp: OkWebSocketResponseData) -> Self {
286 Self::Success(SuccessWebSocketResponse {
287 success: true,
288 request_id,
289 resp,
290 })
291 }
292
293 pub fn failure(request_id: Option<Uuid>, errors: Vec<ApiError>) -> Self {
295 Self::Failure(FailureWebSocketResponse {
296 success: false,
297 request_id,
298 errors,
299 })
300 }
301
302 pub fn is_success(&self) -> bool {
304 matches!(self, Self::Success(_))
305 }
306
307 pub fn is_failure(&self) -> bool {
309 matches!(self, Self::Failure(_))
310 }
311
312 pub fn request_id(&self) -> Option<Uuid> {
314 match self {
315 WebSocketResponse::Success(x) => x.request_id,
316 WebSocketResponse::Failure(x) => x.request_id,
317 }
318 }
319}
320
321#[derive(Debug, Serialize, Deserialize, JsonSchema, Clone)]
324#[cfg_attr(feature = "python", pyo3::pyclass, pyo3_stub_gen::derive::gen_stub_pyclass)]
325pub struct RawFile {
326 pub name: String,
328 #[serde(
330 serialize_with = "serde_bytes::serialize",
331 deserialize_with = "serde_bytes::deserialize"
332 )]
333 pub contents: Vec<u8>,
334}
335
336#[cfg(feature = "python")]
337#[pyo3_stub_gen::derive::gen_stub_pymethods]
338#[pyo3::pymethods]
339impl RawFile {
340 #[getter]
341 fn contents(&self) -> Vec<u8> {
342 self.contents.clone()
343 }
344
345 #[getter]
346 fn name(&self) -> String {
347 self.name.clone()
348 }
349}
350
351impl From<ExportFile> for RawFile {
352 fn from(f: ExportFile) -> Self {
353 Self {
354 name: f.name,
355 contents: f.contents.0,
356 }
357 }
358}
359
360#[derive(Debug, Serialize, Deserialize, JsonSchema)]
362pub struct LoggableApiError {
363 pub error: ApiError,
365 pub msg_internal: Option<Cow<'static, str>>,
367}
368
369#[cfg(feature = "slog")]
370impl KV for LoggableApiError {
371 fn serialize(&self, _rec: &Record, serializer: &mut dyn Serializer) -> slog::Result {
372 if let Some(ref msg_internal) = self.msg_internal {
373 serializer.emit_str("msg_internal", msg_internal)?;
374 }
375 serializer.emit_str("msg_external", &self.error.message)?;
376 serializer.emit_str("error_code", &self.error.error_code.to_string())
377 }
378}
379
380#[derive(Debug, Serialize, Deserialize, JsonSchema, Eq, PartialEq, Clone)]
382pub struct ApiError {
383 pub error_code: ErrorCode,
385 pub message: String,
387}
388
389impl ApiError {
390 pub fn no_internal_message(self) -> LoggableApiError {
392 LoggableApiError {
393 error: self,
394 msg_internal: None,
395 }
396 }
397 pub fn with_message(self, msg_internal: Cow<'static, str>) -> LoggableApiError {
399 LoggableApiError {
400 error: self,
401 msg_internal: Some(msg_internal),
402 }
403 }
404
405 pub fn should_log_internal_message(&self) -> bool {
407 use ErrorCode as Code;
408 match self.error_code {
409 Code::InternalEngine | Code::InternalApi => true,
411 Code::MessageTypeNotAcceptedForWebRTC
413 | Code::MessageTypeNotAccepted
414 | Code::BadRequest
415 | Code::WrongProtocol
416 | Code::AuthTokenMissing
417 | Code::AuthTokenInvalid
418 | Code::InvalidBson
419 | Code::InvalidJson => false,
420 Code::ConnectionProblem => cfg!(debug_assertions),
422 }
423 }
424}
425
426#[derive(Debug, Serialize, Deserialize, JsonSchema)]
429#[serde(rename_all = "snake_case", rename = "SnakeCaseResult")]
430pub enum SnakeCaseResult<T, E> {
431 Ok(T),
433 Err(E),
435}
436
437impl<T, E> From<SnakeCaseResult<T, E>> for Result<T, E> {
438 fn from(value: SnakeCaseResult<T, E>) -> Self {
439 match value {
440 SnakeCaseResult::Ok(x) => Self::Ok(x),
441 SnakeCaseResult::Err(x) => Self::Err(x),
442 }
443 }
444}
445
446impl<T, E> From<Result<T, E>> for SnakeCaseResult<T, E> {
447 fn from(value: Result<T, E>) -> Self {
448 match value {
449 Ok(x) => Self::Ok(x),
450 Err(x) => Self::Err(x),
451 }
452 }
453}
454
455#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
457pub struct ClientMetrics {
458 pub rtc_frames_dropped: Option<u32>,
463
464 pub rtc_frames_decoded: Option<u64>,
469
470 pub rtc_frames_received: Option<u64>,
475
476 pub rtc_frames_per_second: Option<u8>, pub rtc_freeze_count: Option<u32>,
488
489 pub rtc_jitter_sec: Option<f64>,
499
500 pub rtc_keyframes_decoded: Option<u32>,
510
511 pub rtc_total_freezes_duration_sec: Option<f32>,
515
516 pub rtc_frame_height: Option<u32>,
520
521 pub rtc_frame_width: Option<u32>,
525
526 pub rtc_packets_lost: Option<u32>,
530
531 pub rtc_pli_count: Option<u32>,
535
536 pub rtc_pause_count: Option<u32>,
540
541 pub rtc_total_pauses_duration_sec: Option<f32>,
545
546 pub rtc_stun_rtt_sec: Option<f32>,
554}
555
556#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
558pub struct RtcIceCandidate {
559 pub stats_id: String,
561 pub foundation: String,
563 pub priority: u32,
565 pub address: String,
567 pub protocol: RtcIceProtocol,
569 pub port: u16,
571 pub typ: RtcIceCandidateType,
573 pub component: u16,
575 pub related_address: String,
577 pub related_port: u16,
579 pub tcp_type: String,
581}
582
583#[cfg(feature = "webrtc")]
584impl From<webrtc::ice_transport::ice_candidate::RTCIceCandidate> for RtcIceCandidate {
585 fn from(candidate: webrtc::ice_transport::ice_candidate::RTCIceCandidate) -> Self {
586 Self {
587 stats_id: candidate.stats_id,
588 foundation: candidate.foundation,
589 priority: candidate.priority,
590 address: candidate.address,
591 protocol: candidate.protocol.into(),
592 port: candidate.port,
593 typ: candidate.typ.into(),
594 component: candidate.component,
595 related_address: candidate.related_address,
596 related_port: candidate.related_port,
597 tcp_type: candidate.tcp_type,
598 }
599 }
600}
601
602#[cfg(feature = "webrtc")]
603impl From<RtcIceCandidate> for webrtc::ice_transport::ice_candidate::RTCIceCandidate {
604 fn from(candidate: RtcIceCandidate) -> Self {
605 Self {
606 stats_id: candidate.stats_id,
607 foundation: candidate.foundation,
608 priority: candidate.priority,
609 address: candidate.address,
610 protocol: candidate.protocol.into(),
611 port: candidate.port,
612 typ: candidate.typ.into(),
613 component: candidate.component,
614 related_address: candidate.related_address,
615 related_port: candidate.related_port,
616 tcp_type: candidate.tcp_type,
617 }
618 }
619}
620
621#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
623#[serde(rename_all = "snake_case")]
624pub enum RtcIceCandidateType {
625 #[default]
627 Unspecified,
628
629 Host,
635
636 Srflx,
643
644 Prflx,
649
650 Relay,
654}
655
656#[cfg(feature = "webrtc")]
657impl From<webrtc::ice_transport::ice_candidate_type::RTCIceCandidateType> for RtcIceCandidateType {
658 fn from(candidate_type: webrtc::ice_transport::ice_candidate_type::RTCIceCandidateType) -> Self {
659 match candidate_type {
660 webrtc::ice_transport::ice_candidate_type::RTCIceCandidateType::Host => RtcIceCandidateType::Host,
661 webrtc::ice_transport::ice_candidate_type::RTCIceCandidateType::Srflx => RtcIceCandidateType::Srflx,
662 webrtc::ice_transport::ice_candidate_type::RTCIceCandidateType::Prflx => RtcIceCandidateType::Prflx,
663 webrtc::ice_transport::ice_candidate_type::RTCIceCandidateType::Relay => RtcIceCandidateType::Relay,
664 webrtc::ice_transport::ice_candidate_type::RTCIceCandidateType::Unspecified => {
665 RtcIceCandidateType::Unspecified
666 }
667 }
668 }
669}
670
671#[cfg(feature = "webrtc")]
672impl From<RtcIceCandidateType> for webrtc::ice_transport::ice_candidate_type::RTCIceCandidateType {
673 fn from(candidate_type: RtcIceCandidateType) -> Self {
674 match candidate_type {
675 RtcIceCandidateType::Host => webrtc::ice_transport::ice_candidate_type::RTCIceCandidateType::Host,
676 RtcIceCandidateType::Srflx => webrtc::ice_transport::ice_candidate_type::RTCIceCandidateType::Srflx,
677 RtcIceCandidateType::Prflx => webrtc::ice_transport::ice_candidate_type::RTCIceCandidateType::Prflx,
678 RtcIceCandidateType::Relay => webrtc::ice_transport::ice_candidate_type::RTCIceCandidateType::Relay,
679 RtcIceCandidateType::Unspecified => {
680 webrtc::ice_transport::ice_candidate_type::RTCIceCandidateType::Unspecified
681 }
682 }
683 }
684}
685
686#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
689#[serde(rename_all = "snake_case")]
690pub enum RtcIceProtocol {
691 #[default]
693 Unspecified,
694
695 Udp,
697
698 Tcp,
700}
701
702#[cfg(feature = "webrtc")]
703impl From<webrtc::ice_transport::ice_protocol::RTCIceProtocol> for RtcIceProtocol {
704 fn from(protocol: webrtc::ice_transport::ice_protocol::RTCIceProtocol) -> Self {
705 match protocol {
706 webrtc::ice_transport::ice_protocol::RTCIceProtocol::Udp => RtcIceProtocol::Udp,
707 webrtc::ice_transport::ice_protocol::RTCIceProtocol::Tcp => RtcIceProtocol::Tcp,
708 webrtc::ice_transport::ice_protocol::RTCIceProtocol::Unspecified => RtcIceProtocol::Unspecified,
709 }
710 }
711}
712
713#[cfg(feature = "webrtc")]
714impl From<RtcIceProtocol> for webrtc::ice_transport::ice_protocol::RTCIceProtocol {
715 fn from(protocol: RtcIceProtocol) -> Self {
716 match protocol {
717 RtcIceProtocol::Udp => webrtc::ice_transport::ice_protocol::RTCIceProtocol::Udp,
718 RtcIceProtocol::Tcp => webrtc::ice_transport::ice_protocol::RTCIceProtocol::Tcp,
719 RtcIceProtocol::Unspecified => webrtc::ice_transport::ice_protocol::RTCIceProtocol::Unspecified,
720 }
721 }
722}
723
724#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
726#[serde(rename_all = "camelCase")]
727pub struct RtcIceCandidateInit {
729 pub candidate: String,
731 pub sdp_mid: Option<String>,
734 #[serde(rename = "sdpMLineIndex")]
737 pub sdp_mline_index: Option<u16>,
738 pub username_fragment: Option<String>,
741}
742
743#[cfg(feature = "webrtc")]
744impl From<webrtc::ice_transport::ice_candidate::RTCIceCandidateInit> for RtcIceCandidateInit {
745 fn from(candidate: webrtc::ice_transport::ice_candidate::RTCIceCandidateInit) -> Self {
746 Self {
747 candidate: candidate.candidate,
748 sdp_mid: candidate.sdp_mid,
749 sdp_mline_index: candidate.sdp_mline_index,
750 username_fragment: candidate.username_fragment,
751 }
752 }
753}
754
755#[cfg(feature = "webrtc")]
756impl From<RtcIceCandidateInit> for webrtc::ice_transport::ice_candidate::RTCIceCandidateInit {
757 fn from(candidate: RtcIceCandidateInit) -> Self {
758 Self {
759 candidate: candidate.candidate,
760 sdp_mid: candidate.sdp_mid,
761 sdp_mline_index: candidate.sdp_mline_index,
762 username_fragment: candidate.username_fragment,
763 }
764 }
765}
766
767#[derive(Default, Debug, Clone, Serialize, Deserialize, JsonSchema)]
769pub struct RtcSessionDescription {
770 #[serde(rename = "type")]
772 pub sdp_type: RtcSdpType,
773
774 pub sdp: String,
776}
777
778#[cfg(feature = "webrtc")]
779impl From<webrtc::peer_connection::sdp::session_description::RTCSessionDescription> for RtcSessionDescription {
780 fn from(desc: webrtc::peer_connection::sdp::session_description::RTCSessionDescription) -> Self {
781 Self {
782 sdp_type: desc.sdp_type.into(),
783 sdp: desc.sdp,
784 }
785 }
786}
787
788#[cfg(feature = "webrtc")]
789impl TryFrom<RtcSessionDescription> for webrtc::peer_connection::sdp::session_description::RTCSessionDescription {
790 type Error = anyhow::Error;
791
792 fn try_from(desc: RtcSessionDescription) -> Result<Self, Self::Error> {
793 let result = match desc.sdp_type {
794 RtcSdpType::Offer => {
795 webrtc::peer_connection::sdp::session_description::RTCSessionDescription::offer(desc.sdp)?
796 }
797 RtcSdpType::Pranswer => {
798 webrtc::peer_connection::sdp::session_description::RTCSessionDescription::pranswer(desc.sdp)?
799 }
800 RtcSdpType::Answer => {
801 webrtc::peer_connection::sdp::session_description::RTCSessionDescription::answer(desc.sdp)?
802 }
803 RtcSdpType::Rollback => anyhow::bail!("Rollback is not supported"),
804 RtcSdpType::Unspecified => anyhow::bail!("Unspecified is not supported"),
805 };
806
807 Ok(result)
808 }
809}
810
811#[derive(Default, Debug, PartialEq, Eq, Copy, Clone, Serialize, Deserialize, JsonSchema)]
813#[serde(rename_all = "snake_case")]
814pub enum RtcSdpType {
815 #[default]
817 Unspecified = 0,
818
819 Offer,
821
822 Pranswer,
827
828 Answer,
833
834 Rollback,
840}
841
842#[cfg(feature = "webrtc")]
843impl From<webrtc::peer_connection::sdp::sdp_type::RTCSdpType> for RtcSdpType {
844 fn from(sdp_type: webrtc::peer_connection::sdp::sdp_type::RTCSdpType) -> Self {
845 match sdp_type {
846 webrtc::peer_connection::sdp::sdp_type::RTCSdpType::Offer => Self::Offer,
847 webrtc::peer_connection::sdp::sdp_type::RTCSdpType::Pranswer => Self::Pranswer,
848 webrtc::peer_connection::sdp::sdp_type::RTCSdpType::Answer => Self::Answer,
849 webrtc::peer_connection::sdp::sdp_type::RTCSdpType::Rollback => Self::Rollback,
850 webrtc::peer_connection::sdp::sdp_type::RTCSdpType::Unspecified => Self::Unspecified,
851 }
852 }
853}
854
855#[cfg(feature = "webrtc")]
856impl From<RtcSdpType> for webrtc::peer_connection::sdp::sdp_type::RTCSdpType {
857 fn from(sdp_type: RtcSdpType) -> Self {
858 match sdp_type {
859 RtcSdpType::Offer => Self::Offer,
860 RtcSdpType::Pranswer => Self::Pranswer,
861 RtcSdpType::Answer => Self::Answer,
862 RtcSdpType::Rollback => Self::Rollback,
863 RtcSdpType::Unspecified => Self::Unspecified,
864 }
865 }
866}
867#[derive(JsonSchema, Debug, Serialize, Deserialize, Clone)]
869#[serde(rename_all = "snake_case")]
870pub struct ModelingSessionData {
871 pub api_call_id: String,
874}
875
876#[cfg(test)]
877mod tests {
878 use super::*;
879 use crate::output;
880
881 const REQ_ID: Uuid = uuid::uuid!("cc30d5e2-482b-4498-b5d2-6131c30a50a4");
882
883 #[test]
884 fn serialize_websocket_modeling_ok() {
885 let actual = WebSocketResponse::Success(SuccessWebSocketResponse {
886 success: true,
887 request_id: Some(REQ_ID),
888 resp: OkWebSocketResponseData::Modeling {
889 modeling_response: OkModelingCmdResponse::CurveGetControlPoints(output::CurveGetControlPoints {
890 control_points: vec![],
891 }),
892 },
893 });
894 let expected = serde_json::json!({
895 "success": true,
896 "request_id": "cc30d5e2-482b-4498-b5d2-6131c30a50a4",
897 "resp": {
898 "type": "modeling",
899 "data": {
900 "modeling_response": {
901 "type": "curve_get_control_points",
902 "data": { "control_points": [] }
903 }
904 }
905 }
906 });
907 assert_json_eq(actual, expected);
908 }
909
910 #[test]
911 fn serialize_websocket_webrtc_ok() {
912 let actual = WebSocketResponse::Success(SuccessWebSocketResponse {
913 success: true,
914 request_id: Some(REQ_ID),
915 resp: OkWebSocketResponseData::IceServerInfo { ice_servers: vec![] },
916 });
917 let expected = serde_json::json!({
918 "success": true,
919 "request_id": "cc30d5e2-482b-4498-b5d2-6131c30a50a4",
920 "resp": {
921 "type": "ice_server_info",
922 "data": {
923 "ice_servers": []
924 }
925 }
926 });
927 assert_json_eq(actual, expected);
928 }
929
930 #[test]
931 fn serialize_websocket_export_ok() {
932 let actual = WebSocketResponse::Success(SuccessWebSocketResponse {
933 success: true,
934 request_id: Some(REQ_ID),
935 resp: OkWebSocketResponseData::Export { files: vec![] },
936 });
937 let expected = serde_json::json!({
938 "success": true,
939 "request_id": "cc30d5e2-482b-4498-b5d2-6131c30a50a4",
940 "resp": {
941 "type": "export",
942 "data": {"files": [] }
943 }
944 });
945 assert_json_eq(actual, expected);
946 }
947
948 #[test]
949 fn serialize_websocket_err() {
950 let actual = WebSocketResponse::Failure(FailureWebSocketResponse {
951 success: false,
952 request_id: Some(REQ_ID),
953 errors: vec![ApiError {
954 error_code: ErrorCode::InternalApi,
955 message: "you fucked up!".to_owned(),
956 }],
957 });
958 let expected = serde_json::json!({
959 "success": false,
960 "request_id": "cc30d5e2-482b-4498-b5d2-6131c30a50a4",
961 "errors": [
962 {
963 "error_code": "internal_api",
964 "message": "you fucked up!"
965 }
966 ],
967 });
968 assert_json_eq(actual, expected);
969 }
970
971 #[test]
972 fn serialize_websocket_metrics() {
973 let actual = WebSocketRequest::MetricsResponse {
974 metrics: Box::new(ClientMetrics {
975 rtc_frames_dropped: Some(1),
976 rtc_frames_decoded: Some(2),
977 rtc_frames_per_second: Some(3),
978 rtc_frames_received: Some(4),
979 rtc_freeze_count: Some(5),
980 rtc_jitter_sec: Some(6.7),
981 rtc_keyframes_decoded: Some(8),
982 rtc_total_freezes_duration_sec: Some(9.1),
983 rtc_frame_height: Some(100),
984 rtc_frame_width: Some(100),
985 rtc_packets_lost: Some(0),
986 rtc_pli_count: Some(0),
987 rtc_pause_count: Some(0),
988 rtc_total_pauses_duration_sec: Some(0.0),
989 rtc_stun_rtt_sec: Some(0.005),
990 }),
991 };
992 let expected = serde_json::json!({
993 "type": "metrics_response",
994 "metrics": {
995 "rtc_frames_dropped": 1,
996 "rtc_frames_decoded": 2,
997 "rtc_frames_per_second": 3,
998 "rtc_frames_received": 4,
999 "rtc_freeze_count": 5,
1000 "rtc_jitter_sec": 6.7,
1001 "rtc_keyframes_decoded": 8,
1002 "rtc_total_freezes_duration_sec": 9.1,
1003 "rtc_frame_height": 100,
1004 "rtc_frame_width": 100,
1005 "rtc_packets_lost": 0,
1006 "rtc_pli_count": 0,
1007 "rtc_pause_count": 0,
1008 "rtc_total_pauses_duration_sec": 0.0,
1009 "rtc_stun_rtt_sec": 0.005,
1010 },
1011 });
1012 assert_json_eq(actual, expected);
1013 }
1014
1015 fn assert_json_eq<T: Serialize>(actual: T, expected: serde_json::Value) {
1016 let json_str = serde_json::to_string(&actual).unwrap();
1017 let actual: serde_json::Value = serde_json::from_str(&json_str).unwrap();
1018 assert_eq!(actual, expected, "got\n{actual:#}\n, expected\n{expected:#}\n");
1019 }
1020}