Skip to content

Commit 69b980f

Browse files
committed
review
1 parent 6b3af4e commit 69b980f

File tree

7 files changed

+85
-61
lines changed

7 files changed

+85
-61
lines changed

crates/matrix-sdk/src/widget/machine/driver_req.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,8 @@ where
7474
Self { request_meta: None, _phantom: PhantomData }
7575
}
7676

77+
/// Setup a callback function that will be called once the matrix driver has
78+
/// processed the request.
7779
pub(crate) fn then(
7880
self,
7981
response_handler: impl FnOnce(Result<T, crate::Error>, &mut WidgetMachine) -> Vec<Action>

crates/matrix-sdk/src/widget/machine/from_widget.rs

Lines changed: 29 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,6 @@
1212
// See the License for the specific language governing permissions and
1313
// limitations under the License.
1414

15-
use std::collections::HashMap;
16-
1715
use ruma::{
1816
api::client::{
1917
delayed_events::{delayed_message_event, delayed_state_event, update_delayed_event},
@@ -43,22 +41,23 @@ pub(super) enum FromWidgetRequest {
4341
DelayedEventUpdate(UpdateDelayedEventRequest),
4442
}
4543

44+
/// The full response a client sends to a from widget request
45+
/// in case of an error.
4646
#[derive(Serialize)]
4747
pub(super) struct FromWidgetErrorResponse {
4848
error: FromWidgetError,
4949
}
5050

51-
impl From<&HttpError> for FromWidgetErrorResponse {
52-
fn from(error: &HttpError) -> Self {
51+
impl FromWidgetErrorResponse {
52+
/// Create a error response to send to the widget from an http error.
53+
pub(crate) fn from_http_error(error: &HttpError) -> Self {
5354
Self {
5455
error: FromWidgetError {
5556
message: error.to_string(),
5657
matrix_api_error: error.as_client_api_error().and_then(
5758
|api_error| match &api_error.body {
5859
ErrorBody::Standard { kind, message } => Some(FromWidgetMatrixErrorBody {
5960
http_status: api_error.status_code.as_u16().into(),
60-
http_headers: HashMap::new(),
61-
url: "".to_owned(),
6261
response: json!({"errcode": kind.to_string(), "error": message }),
6362
}),
6463
_ => None,
@@ -67,50 +66,55 @@ impl From<&HttpError> for FromWidgetErrorResponse {
6766
},
6867
}
6968
}
70-
}
7169

72-
impl From<&Error> for FromWidgetErrorResponse {
73-
fn from(error: &Error) -> Self {
70+
/// Create a error response to send to the widget from a matrix sdk error.
71+
pub(crate) fn from_error(error: &Error) -> Self {
7472
match &error {
75-
Error::Http(e) => e.into(),
76-
Error::UnknownError(e) => e.to_string().into(),
77-
_ => error.to_string().into(),
73+
Error::Http(e) => FromWidgetErrorResponse::from_http_error(e),
74+
Error::UnknownError(e) => FromWidgetErrorResponse::from_string(e.to_string()),
75+
_ => FromWidgetErrorResponse::from_string(error.to_string()),
7876
}
7977
}
80-
}
8178

82-
impl From<String> for FromWidgetErrorResponse {
83-
fn from(error: String) -> Self {
84-
Self { error: FromWidgetError { message: error, matrix_api_error: None } }
85-
}
86-
}
87-
88-
impl From<&str> for FromWidgetErrorResponse {
89-
fn from(error: &str) -> Self {
90-
error.to_owned().into()
79+
/// Create a error response to send to the widget from a string.
80+
pub(crate) fn from_string<S: Into<String>>(error: S) -> Self {
81+
Self { error: FromWidgetError { message: error.into(), matrix_api_error: None } }
9182
}
9283
}
9384

85+
/// The serializable section of an error response send by the client as a
86+
/// response to a from widget request.
9487
#[derive(Serialize)]
9588
struct FromWidgetError {
89+
/// A unspecified error message text that caused this widget action to fail.
90+
/// This is useful to prompt the user on an issue but cannot be used to
91+
/// decide on how to deal with the error.
9692
message: String,
93+
/// An optional matrix error that contains specified
94+
/// information and helps finding a work around for specific errors.
9795
matrix_api_error: Option<FromWidgetMatrixErrorBody>,
9896
}
9997

98+
/// The serializable section of a widget response that represents a matrix
99+
/// error.
100100
#[derive(Serialize)]
101101
struct FromWidgetMatrixErrorBody {
102+
/// The status code of the http response
102103
http_status: u32,
103-
// TODO: figure out the which type to use here.
104-
http_headers: HashMap<String, String>,
105-
url: String,
104+
/// The matrix standard error response including the `errorcode` and the
105+
/// `error` message as defined in the spec: https://spec.matrix.org/v1.12/client-server-api/#standard-error-response
106106
response: Value,
107107
}
108+
109+
/// The serializable section of a widget response containing the supported
110+
/// versions.
108111
#[derive(Serialize)]
109112
pub(super) struct SupportedApiVersionsResponse {
110113
supported_versions: Vec<ApiVersion>,
111114
}
112115

113116
impl SupportedApiVersionsResponse {
117+
/// The currently supported widget api versions from the rust widget driver.
114118
pub(super) fn new() -> Self {
115119
Self {
116120
supported_versions: vec![

crates/matrix-sdk/src/widget/machine/incoming.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,9 @@ pub(crate) enum IncomingMessage {
3737
/// The ID of the request that this response corresponds to.
3838
request_id: Uuid,
3939

40-
/// The result of the request: response data or error message.
40+
/// The result of the request: response data or matrix sdk error.
41+
/// Http errors will be forwarded to the widget in a specified format
42+
/// so the widget can parse the error.
4143
response: Result<MatrixDriverResponse, crate::Error>,
4244
},
4345

crates/matrix-sdk/src/widget/machine/mod.rs

Lines changed: 42 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ use super::{
5454
filter::{MatrixEventContent, MatrixEventFilterInput},
5555
Capabilities, StateKeySelector,
5656
};
57-
use crate::{widget::EventFilter, Error};
57+
use crate::{widget::EventFilter, Result};
5858

5959
mod driver_req;
6060
mod from_widget;
@@ -204,8 +204,10 @@ impl WidgetMachine {
204204
let request = match raw_request.deserialize() {
205205
Ok(r) => r,
206206
Err(e) => {
207-
return vec![self
208-
.send_from_widget_error_response(raw_request, (&Error::SerdeJson(e)).into())]
207+
return vec![self.send_from_widget_error_response(
208+
raw_request,
209+
FromWidgetErrorResponse::from_error(&crate::Error::SerdeJson(e)),
210+
)]
209211
}
210212
};
211213

@@ -255,13 +257,17 @@ impl WidgetMachine {
255257
let CapabilitiesState::Negotiated(capabilities) = &self.capabilities else {
256258
let text =
257259
"Received send update delayed event request before capabilities were negotiated";
258-
return vec![self.send_from_widget_error_response(raw_request, text.into())];
260+
return vec![self.send_from_widget_error_response(
261+
raw_request,
262+
FromWidgetErrorResponse::from_string(text),
263+
)];
259264
};
260265
if !capabilities.update_delayed_event {
261266
return vec![self.send_from_widget_error_response(
262267
raw_request,
263-
format!("Not allowed: missing the {UPDATE_DELAYED_EVENT} capability.")
264-
.into(),
268+
FromWidgetErrorResponse::from_string(format!(
269+
"Not allowed: missing the {UPDATE_DELAYED_EVENT} capability."
270+
)),
265271
)];
266272
}
267273
let (request, request_action) =
@@ -276,7 +282,7 @@ impl WidgetMachine {
276282
// does not impl Serialize
277283
match result {
278284
Ok(response) => Ok(Into::<UpdateDelayedEventResponse>::into(response)),
279-
Err(e) => Err((&e).into()),
285+
Err(e) => Err(FromWidgetErrorResponse::from_error(&e)), //---
280286
},
281287
)]
282288
});
@@ -292,7 +298,10 @@ impl WidgetMachine {
292298
) -> Option<Action> {
293299
let CapabilitiesState::Negotiated(capabilities) = &self.capabilities else {
294300
let text = "Received read event request before capabilities were negotiated";
295-
return Some(self.send_from_widget_error_response(raw_request, text.into()));
301+
return Some(self.send_from_widget_error_response(
302+
raw_request,
303+
FromWidgetErrorResponse::from_string(text),
304+
));
296305
};
297306

298307
match request {
@@ -301,7 +310,9 @@ impl WidgetMachine {
301310
if !capabilities.read.iter().any(filter_fn) {
302311
return Some(self.send_from_widget_error_response(
303312
raw_request,
304-
"Not allowed to read message like event".into(),
313+
FromWidgetErrorResponse::from_string(
314+
"Not allowed to read message like event",
315+
),
305316
));
306317
}
307318

@@ -316,14 +327,16 @@ impl WidgetMachine {
316327
Ok(ReadEventResponse { events })
317328
}
318329
(Ok(_), CapabilitiesState::Unset) => {
319-
Err("Received read event request before capabilities negotiation"
320-
.into())
330+
Err(FromWidgetErrorResponse::from_string(
331+
"Received read event request before capabilities negotiation",
332+
))
321333
}
322334
(Ok(_), CapabilitiesState::Negotiating) => {
323-
Err("Received read event request while capabilities were negotiating"
324-
.into())
335+
Err(FromWidgetErrorResponse::from_string(
336+
"Received read event request while capabilities were negotiating",
337+
))
325338
}
326-
(Err(e), _) => Err((&e).into()),
339+
(Err(e), _) => Err(FromWidgetErrorResponse::from_error(&e)),
327340
};
328341
vec![machine.send_from_widget_result_response(raw_request, response)]
329342
});
@@ -354,14 +367,14 @@ impl WidgetMachine {
354367
request.then(|result, machine| {
355368
let response = result
356369
.map(|events| ReadEventResponse { events })
357-
.map_err(|e| (&e).into());
370+
.map_err(|e| FromWidgetErrorResponse::from_error(&e));
358371
vec![machine.send_from_widget_result_response(raw_request, response)]
359372
});
360373
action
361374
} else {
362375
Some(self.send_from_widget_error_response(
363376
raw_request,
364-
"Not allowed to read state event".into(),
377+
FromWidgetErrorResponse::from_string("Not allowed to read state event"),
365378
))
366379
}
367380
}
@@ -391,25 +404,27 @@ impl WidgetMachine {
391404
if !capabilities.send_delayed_event && request.delay.is_some() {
392405
return Some(self.send_from_widget_error_response(
393406
raw_request,
394-
format!("Not allowed: missing the {SEND_DELAYED_EVENT} capability.").into(),
407+
FromWidgetErrorResponse::from_string(format!(
408+
"Not allowed: missing the {SEND_DELAYED_EVENT} capability."
409+
)),
395410
));
396411
}
397412
if !capabilities.send.iter().any(|filter| filter.matches(&filter_in)) {
398-
return Some(
399-
self.send_from_widget_error_response(
400-
raw_request,
401-
"Not allowed to send event".into(),
402-
),
403-
);
413+
return Some(self.send_from_widget_error_response(
414+
raw_request,
415+
FromWidgetErrorResponse::from_string("Not allowed to send event"),
416+
));
404417
}
405418

406419
let (request, action) = self.send_matrix_driver_request(request);
407420
request.then(|mut result, machine| {
408421
if let Ok(r) = result.as_mut() {
409422
r.set_room_id(machine.room_id.clone());
410423
}
411-
vec![machine
412-
.send_from_widget_result_response(raw_request, result.map_err(|e| (&e).into()))]
424+
vec![machine.send_from_widget_result_response(
425+
raw_request,
426+
result.map_err(|e| FromWidgetErrorResponse::from_error(&e)),
427+
)]
413428
});
414429
action
415430
}
@@ -451,7 +466,7 @@ impl WidgetMachine {
451466
fn process_matrix_driver_response(
452467
&mut self,
453468
request_id: Uuid,
454-
response: Result<MatrixDriverResponse, Error>,
469+
response: Result<MatrixDriverResponse>,
455470
) -> Vec<Action> {
456471
match self.pending_matrix_driver_requests.extract(&request_id) {
457472
Ok(request) => request
@@ -598,7 +613,7 @@ impl ToWidgetRequestMeta {
598613
}
599614

600615
type MatrixDriverResponseFn =
601-
Box<dyn FnOnce(Result<MatrixDriverResponse, Error>, &mut WidgetMachine) -> Vec<Action> + Send>;
616+
Box<dyn FnOnce(Result<MatrixDriverResponse>, &mut WidgetMachine) -> Vec<Action> + Send>;
602617

603618
pub(crate) struct MatrixDriverRequestMeta {
604619
response_fn: Option<MatrixDriverResponseFn>,

crates/matrix-sdk/src/widget/matrix.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ impl MatrixDriver {
5252
}
5353

5454
/// Requests an OpenID token for the current user.
55-
pub(crate) async fn get_open_id(&self) -> Result<OpenIdResponse, Error> {
55+
pub(crate) async fn get_open_id(&self) -> Result<OpenIdResponse> {
5656
let user_id = self.room.own_user_id().to_owned();
5757
self.room.client.send(OpenIdRequest::new(user_id), None).await.map_err(Error::Http)
5858
}
@@ -62,7 +62,7 @@ impl MatrixDriver {
6262
&self,
6363
event_type: MessageLikeEventType,
6464
limit: u32,
65-
) -> Result<Vec<Raw<AnyTimelineEvent>>, Error> {
65+
) -> Result<Vec<Raw<AnyTimelineEvent>>> {
6666
let options = assign!(MessagesOptions::backward(), {
6767
limit: limit.into(),
6868
filter: assign!(RoomEventFilter::default(), {
@@ -78,7 +78,7 @@ impl MatrixDriver {
7878
&self,
7979
event_type: StateEventType,
8080
state_key: &StateKeySelector,
81-
) -> Result<Vec<Raw<AnyTimelineEvent>>, Error> {
81+
) -> Result<Vec<Raw<AnyTimelineEvent>>> {
8282
let room_id = self.room.room_id();
8383
let convert = |sync_or_stripped_state| match sync_or_stripped_state {
8484
RawAnySyncOrStrippedState::Sync(ev) => Some(attach_room_id(ev.cast_ref(), room_id)),
@@ -116,7 +116,7 @@ impl MatrixDriver {
116116
state_key: Option<String>,
117117
content: Box<RawJsonValue>,
118118
delayed_event_parameters: Option<delayed_events::DelayParameters>,
119-
) -> Result<SendEventResponse, Error> {
119+
) -> Result<SendEventResponse> {
120120
let type_str = event_type.to_string();
121121

122122
if let Some(redacts) = from_raw_json_value::<Value, serde_json::Error>(&content)
@@ -165,7 +165,7 @@ impl MatrixDriver {
165165
&self,
166166
delay_id: String,
167167
action: UpdateAction,
168-
) -> Result<delayed_events::update_delayed_event::unstable::Response, Error> {
168+
) -> Result<delayed_events::update_delayed_event::unstable::Response> {
169169
let r = delayed_events::update_delayed_event::unstable::Request::new(delay_id, action);
170170
self.room.client.send(r, None).await.map_err(Error::Http)
171171
}

crates/matrix-sdk/src/widget/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ use self::{
2929
},
3030
matrix::MatrixDriver,
3131
};
32-
use crate::{room::Room, Error, Result};
32+
use crate::{room::Room, Result};
3333

3434
mod capabilities;
3535
mod filter;
@@ -195,7 +195,7 @@ impl<T: CapabilitiesProvider> ProcessingContext<T> {
195195
self.to_widget_tx.send(msg).await.map_err(|_| ())?;
196196
}
197197
Action::MatrixDriverRequest { request_id, data } => {
198-
let response: Result<MatrixDriverResponse, Error> = match data {
198+
let response = match data {
199199
MatrixDriverRequestData::AcquireCapabilities(cmd) => {
200200
let obtained = self
201201
.capabilities_provider

crates/matrix-sdk/tests/integration/widget.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -688,6 +688,8 @@ async fn test_fail_sending_delay_rate_limit() {
688688
)
689689
.await;
690690

691+
// TODO convert to mock_server.mock_room_send().for_type()... once for_type is
692+
// available
691693
Mock::given(method("PUT"))
692694
.and(path_regex(r"^/_matrix/client/v3/rooms/.*/send/m.room.message/.*$"))
693695
.respond_with(ResponseTemplate::new(400).set_body_json(json!({
@@ -722,7 +724,6 @@ async fn test_fail_sending_delay_rate_limit() {
722724
json!({
723725
"error": {
724726
"matrix_api_error": {
725-
"http_headers": {},
726727
"http_status": 400,
727728
"response": {
728729
"errcode": "M_LIMIT_EXCEEDED",

0 commit comments

Comments
 (0)