Skip to content
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
986e15c
Wrap the Rust HTTP client with `make_deferred_yieldable`
MadLittleMods Sep 9, 2025
5e555f3
Add chagnelog
MadLittleMods Sep 9, 2025
4e0085c
Docstring for why we have a wrapper
MadLittleMods Sep 9, 2025
763cdb9
Merge branch 'develop' into madlittlemods/18357-rust-http-client-remo…
MadLittleMods Sep 9, 2025
ce6f16d
WIP: Add test
MadLittleMods Sep 9, 2025
d4558df
Merge branch 'develop' into madlittlemods/18357-rust-http-client-remo…
MadLittleMods Sep 17, 2025
dce9754
Merge branch 'develop' into madlittlemods/18357-rust-http-client-remo…
MadLittleMods Sep 22, 2025
9def6f7
Merge branch 'develop' into madlittlemods/18357-rust-http-client-remo…
MadLittleMods Sep 30, 2025
77970eb
Maintenance from merging in the latest `develop` changes
MadLittleMods Sep 30, 2025
b89fb2e
Fix `Tokio runtime is not running`
MadLittleMods Sep 30, 2025
34b6f2a
Add working test
MadLittleMods Sep 30, 2025
8a9d682
Add basic request/response test
MadLittleMods Sep 30, 2025
2d341cb
Add docstring
MadLittleMods Sep 30, 2025
58c1209
Better test that fails
MadLittleMods Sep 30, 2025
9a4e67d
Cross-link Twisted PR
MadLittleMods Sep 30, 2025
59516a4
WIP: Failing test
MadLittleMods Sep 30, 2025
74f01a9
Use `make_deferred_yieldable` in Rust
MadLittleMods Sep 30, 2025
4424a88
Clean up test
MadLittleMods Sep 30, 2025
e6df6ee
Remove Rust wrapper (no longer necessary)
MadLittleMods Sep 30, 2025
92ea10a
Note that the returned deferred follow Synapse logcontext rules now
MadLittleMods Sep 30, 2025
5c324bc
No more Rust wrapper (switch back to Rust imports)
MadLittleMods Sep 30, 2025
e243b0f
Fix lints
MadLittleMods Sep 30, 2025
ab453b7
Move imports (try fix lints)
MadLittleMods Sep 30, 2025
a0051f7
Merge branch 'develop' into madlittlemods/18357-rust-http-client-remo…
MadLittleMods Sep 30, 2025
e35c7db
Merge branch 'develop' into madlittlemods/18357-rust-http-client-remo…
MadLittleMods Oct 1, 2025
1d9ae7f
Avoid `unwrap` and return fallible
MadLittleMods Oct 1, 2025
311969f
Always `make_deferred_yieldable(...)` when `create_deferred(...)`
MadLittleMods Oct 1, 2025
b670864
Merge branch 'develop' into madlittlemods/18357-rust-http-client-remo…
MadLittleMods Oct 2, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/18903.misc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Wrap the Rust HTTP client with `make_deferred_yieldable` so it follows Synapse logcontext rules.
64 changes: 45 additions & 19 deletions rust/src/http_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use futures::TryStreamExt;
use once_cell::sync::OnceCell;
use pyo3::{create_exception, exceptions::PyException, prelude::*};
use reqwest::RequestBuilder;
use std::sync::OnceLock;
use tokio::runtime::Runtime;

use crate::errors::HttpResponseException;
Expand Down Expand Up @@ -218,29 +219,34 @@ impl HttpClient {
builder: RequestBuilder,
response_limit: usize,
) -> PyResult<Bound<'a, PyAny>> {
create_deferred(py, self.reactor.bind(py), async move {
let response = builder.send().await.context("sending request")?;

let status = response.status();

let mut stream = response.bytes_stream();
let mut buffer = Vec::new();
while let Some(chunk) = stream.try_next().await.context("reading body")? {
if buffer.len() + chunk.len() > response_limit {
Err(anyhow::anyhow!("Response size too large"))?;
// We use `make_deferred_yieldable` to make the returned deferred follow Synapse
// logcontext rules.
Ok(make_deferred_yieldable(
py,
&create_deferred(py, self.reactor.bind(py), async move {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would make the make_deferred_yieldable logic part of create_deferred. I don't see a scenario where we don't want this

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that makes sense 👍

Usually, we use make_deferred_yieldable(...) on third-party code (out of our control) that doesn't follow Synapse logcontext rules. But we control this code and can make the deferred do the right thing as we create it.

let response = builder.send().await.context("sending request")?;

let status = response.status();

let mut stream = response.bytes_stream();
let mut buffer = Vec::new();
while let Some(chunk) = stream.try_next().await.context("reading body")? {
if buffer.len() + chunk.len() > response_limit {
Err(anyhow::anyhow!("Response size too large"))?;
}

buffer.extend_from_slice(&chunk);
}

buffer.extend_from_slice(&chunk);
}

if !status.is_success() {
return Err(HttpResponseException::new(status, buffer));
}
if !status.is_success() {
return Err(HttpResponseException::new(status, buffer));
}

let r = Python::with_gil(|py| buffer.into_pyobject(py).map(|o| o.unbind()))?;
let r = Python::with_gil(|py| buffer.into_pyobject(py).map(|o| o.unbind()))?;

Ok(r)
})
Ok(r)
})?,
))
}
}

Expand Down Expand Up @@ -301,3 +307,23 @@ where

Ok(deferred)
}

static MAKE_DEFERRED_YIELDABLE: OnceLock<pyo3::Py<pyo3::PyAny>> = OnceLock::new();

/// Given a deferred, make it follow the Synapse logcontext rules
fn make_deferred_yieldable<'py>(
py: Python<'py>,
deferred: &Bound<'py, PyAny>,
) -> Bound<'py, PyAny> {
let make_deferred_yieldable = MAKE_DEFERRED_YIELDABLE.get_or_init(|| {
let sys = PyModule::import(py, "synapse.logging.context").unwrap();
let func = sys.getattr("make_deferred_yieldable").unwrap().unbind();
func
});

make_deferred_yieldable
.call1(py, (deferred,))
.unwrap()
.extract(py)
.unwrap()
}
Comment on lines 308 to 320
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is based on @reivilibre suggestion in #18903 (comment)

But please double-check that I didn't fumble the lifetimes, etc trying to kludge things together.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ideally we'd avoid unwrap as much as possible, especially when a function call can potentially raise. Unfortunately OnceCell::get_or_try_init is unstable so we can't avoid it here easily, but the call to make_deferred_yieldable can bubble up errorsa

Suggested change
/// Given a deferred, make it follow the Synapse logcontext rules
fn make_deferred_yieldable<'py>(
py: Python<'py>,
deferred: &Bound<'py, PyAny>,
) -> Bound<'py, PyAny> {
let make_deferred_yieldable = MAKE_DEFERRED_YIELDABLE.get_or_init(|| {
let sys = PyModule::import(py, "synapse.logging.context").unwrap();
let func = sys.getattr("make_deferred_yieldable").unwrap().unbind();
func
});
make_deferred_yieldable
.call1(py, (deferred,))
.unwrap()
.extract(py)
.unwrap()
}
/// Given a deferred, make it follow the Synapse logcontext rules
fn make_deferred_yieldable<'py>(
py: Python<'py>,
deferred: &Bound<'py, PyAny>,
) -> PyErr<Bound<'py, PyAny>> {
let make_deferred_yieldable = MAKE_DEFERRED_YIELDABLE.get_or_init(|| {
let sys = PyModule::import(py, "synapse.logging.context").unwrap();
let func = sys.getattr("make_deferred_yieldable").unwrap().unbind();
func
});
make_deferred_yieldable
.call1(py, (deferred,))?
.extract(py)
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Had to adjust it a bit. Updated to this:

static MAKE_DEFERRED_YIELDABLE: OnceLock<pyo3::Py<pyo3::PyAny>> = OnceLock::new();

/// Given a deferred, make it follow the Synapse logcontext rules
fn make_deferred_yieldable<'py>(
    py: Python<'py>,
    deferred: &Bound<'py, PyAny>,
) -> PyResult<Bound<'py, PyAny>> {
    let make_deferred_yieldable = MAKE_DEFERRED_YIELDABLE.get_or_init(|| {
        let sys = PyModule::import(py, "synapse.logging.context").unwrap();
        let func = sys.getattr("make_deferred_yieldable").unwrap().unbind();
        func
    });

    make_deferred_yieldable.call1(py, (deferred,))?.extract(py)
}

16 changes: 7 additions & 9 deletions synapse/api/auth/mas.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,14 @@
UnrecognizedRequestError,
)
from synapse.http.site import SynapseRequest
from synapse.logging.context import PreserveLoggingContext
from synapse.logging.opentracing import (
active_span,
force_tracing,
inject_request_headers,
start_active_span,
)
from synapse.metrics import SERVER_NAME_LABEL
from synapse.synapse_rust.http_client import HttpClient
from synapse.synapse_rust_wrapper.http_client import HttpClient
from synapse.types import JsonDict, Requester, UserID, create_requester
from synapse.util.caches.cached_call import RetryOnExceptionCachedCall
from synapse.util.caches.response_cache import ResponseCache, ResponseCacheContext
Expand Down Expand Up @@ -229,13 +228,12 @@ async def _introspect_token(
try:
with start_active_span("mas-introspect-token"):
inject_request_headers(raw_headers)
with PreserveLoggingContext():
resp_body = await self._rust_http_client.post(
url=self._introspection_endpoint,
response_limit=1 * 1024 * 1024,
headers=raw_headers,
request_body=body,
)
resp_body = await self._rust_http_client.post(
url=self._introspection_endpoint,
response_limit=1 * 1024 * 1024,
headers=raw_headers,
request_body=body,
)
except HttpResponseException as e:
end_time = self._clock.time()
introspection_response_timer.labels(
Expand Down
16 changes: 7 additions & 9 deletions synapse/api/auth/msc3861_delegated.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,14 @@
UnrecognizedRequestError,
)
from synapse.http.site import SynapseRequest
from synapse.logging.context import PreserveLoggingContext
from synapse.logging.opentracing import (
active_span,
force_tracing,
inject_request_headers,
start_active_span,
)
from synapse.metrics import SERVER_NAME_LABEL
from synapse.synapse_rust.http_client import HttpClient
from synapse.synapse_rust_wrapper.http_client import HttpClient
from synapse.types import Requester, UserID, create_requester
from synapse.util.caches.cached_call import RetryOnExceptionCachedCall
from synapse.util.caches.response_cache import ResponseCache, ResponseCacheContext
Expand Down Expand Up @@ -327,13 +326,12 @@ async def _introspect_token(
try:
with start_active_span("mas-introspect-token"):
inject_request_headers(raw_headers)
with PreserveLoggingContext():
resp_body = await self._rust_http_client.post(
url=uri,
response_limit=1 * 1024 * 1024,
headers=raw_headers,
request_body=body,
)
resp_body = await self._rust_http_client.post(
url=uri,
response_limit=1 * 1024 * 1024,
headers=raw_headers,
request_body=body,
)
except HttpResponseException as e:
end_time = self._clock.time()
introspection_response_timer.labels(
Expand Down
4 changes: 4 additions & 0 deletions synapse/synapse_rust/http_client.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ from twisted.internet.defer import Deferred
from synapse.types import ISynapseReactor

class HttpClient:
"""
The returned deferreds follow Synapse logcontext rules.
"""
Comment on lines +20 to +22
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps we should just remove this as we should just assume that everything in Synapse does follow the Synapse logcontext rules unless otherwise stated.

For example:

Returns:
Deferred which returns the result of func, or `None` if func raises.
Note that the returned Deferred does not follow the synapse logcontext
rules.


def __init__(self, reactor: ISynapseReactor, user_agent: str) -> None: ...
def get(self, url: str, response_limit: int) -> Deferred[bytes]: ...
def post(
Expand Down
11 changes: 11 additions & 0 deletions tests/synapse_rust/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# This file is licensed under the Affero General Public License (AGPL) version 3.
#
# Copyright (C) 2025 New Vector, Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# See the GNU Affero General Public License for more details:
# <https://www.gnu.org/licenses/agpl-3.0.html>.
Loading
Loading