Bump pyo3 to v0.23.2 (#17966)
Some checks are pending
Build docker images / build (push) Waiting to run
Deploy the documentation / Calculate variables for GitHub Pages deployment (push) Waiting to run
Deploy the documentation / GitHub Pages (push) Blocked by required conditions
Build release artifacts / Calculate list of debian distros (push) Waiting to run
Build release artifacts / Build .deb packages (push) Blocked by required conditions
Build release artifacts / Build wheels on ubuntu-22.04 for aarch64 (push) Waiting to run
Build release artifacts / Build wheels on macos-13 for x86_64 (push) Waiting to run
Build release artifacts / Build wheels on ubuntu-22.04 for x86_64 (push) Waiting to run
Build release artifacts / Build sdist (push) Waiting to run
Build release artifacts / Attach assets to release (push) Blocked by required conditions
Tests / changes (push) Waiting to run
Tests / check-sampleconfig (push) Blocked by required conditions
Tests / check-schema-delta (push) Blocked by required conditions
Tests / check-lockfile (push) Waiting to run
Tests / lint (push) Blocked by required conditions
Tests / Typechecking (push) Blocked by required conditions
Tests / lint-crlf (push) Waiting to run
Tests / lint-newsfile (push) Waiting to run
Tests / lint-pydantic (push) Blocked by required conditions
Tests / lint-clippy (push) Blocked by required conditions
Tests / lint-clippy-nightly (push) Blocked by required conditions
Tests / trial (push) Blocked by required conditions
Tests / trial-olddeps (push) Blocked by required conditions
Tests / trial-pypy (all, pypy-3.9) (push) Blocked by required conditions
Tests / sytest (push) Blocked by required conditions
Tests / export-data (push) Blocked by required conditions
Tests / portdb (11, 3.9) (push) Blocked by required conditions
Tests / portdb (17, 3.13) (push) Blocked by required conditions
Tests / complement (monolith, Postgres) (push) Blocked by required conditions
Tests / complement (monolith, SQLite) (push) Blocked by required conditions
Tests / complement (workers, Postgres) (push) Blocked by required conditions
Tests / cargo-test (push) Blocked by required conditions
Tests / cargo-bench (push) Blocked by required conditions
Tests / tests-done (push) Blocked by required conditions
Tests / lint-rustfmt (push) Blocked by required conditions
Tests / lint-readme (push) Blocked by required conditions
Tests / linting-done (push) Blocked by required conditions
Tests / calculate-test-jobs (push) Blocked by required conditions

Keep up-to-date with pyo3 releases. This bump enables Python 3.13
support and resolves deprecations.

Links for quick reference:
https://github.com/PyO3/pyo3/releases
https://github.com/davidhewitt/pythonize/releases
https://github.com/vorner/pyo3-log
This commit is contained in:
V02460 2024-11-27 11:46:00 +01:00 committed by GitHub
parent cee9da0da5
commit a58f09acc7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 136 additions and 195 deletions

158
Cargo.lock generated
View file

@ -35,12 +35,6 @@ version = "0.21.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"
[[package]]
name = "bitflags"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1"
[[package]] [[package]]
name = "blake2" name = "blake2"
version = "0.10.6" version = "0.10.6"
@ -162,9 +156,9 @@ dependencies = [
[[package]] [[package]]
name = "heck" name = "heck"
version = "0.4.1" version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]] [[package]]
name = "hex" name = "hex"
@ -222,16 +216,6 @@ version = "0.2.154"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae743338b92ff9146ce83992f766a31066a91a8c84a45e0e9f21e7cf6de6d346" checksum = "ae743338b92ff9146ce83992f766a31066a91a8c84a45e0e9f21e7cf6de6d346"
[[package]]
name = "lock_api"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17"
dependencies = [
"autocfg",
"scopeguard",
]
[[package]] [[package]]
name = "log" name = "log"
version = "0.4.22" version = "0.4.22"
@ -265,29 +249,6 @@ version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
[[package]]
name = "parking_lot"
version = "0.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e4af0ca4f6caed20e900d564c242b8e5d4903fdacf31d3daf527b66fe6f42fb"
dependencies = [
"lock_api",
"parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.9.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"smallvec",
"windows-targets",
]
[[package]] [[package]]
name = "portable-atomic" name = "portable-atomic"
version = "1.6.0" version = "1.6.0"
@ -311,16 +272,16 @@ dependencies = [
[[package]] [[package]]
name = "pyo3" name = "pyo3"
version = "0.21.2" version = "0.23.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5e00b96a521718e08e03b1a622f01c8a8deb50719335de3f60b3b3950f069d8" checksum = "f54b3d09cbdd1f8c20650b28e7b09e338881482f4aa908a5f61a00c98fba2690"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"cfg-if", "cfg-if",
"indoc", "indoc",
"libc", "libc",
"memoffset", "memoffset",
"parking_lot", "once_cell",
"portable-atomic", "portable-atomic",
"pyo3-build-config", "pyo3-build-config",
"pyo3-ffi", "pyo3-ffi",
@ -330,9 +291,9 @@ dependencies = [
[[package]] [[package]]
name = "pyo3-build-config" name = "pyo3-build-config"
version = "0.21.2" version = "0.23.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7883df5835fafdad87c0d888b266c8ec0f4c9ca48a5bed6bbb592e8dedee1b50" checksum = "3015cf985888fe66cfb63ce0e321c603706cd541b7aec7ddd35c281390af45d8"
dependencies = [ dependencies = [
"once_cell", "once_cell",
"target-lexicon", "target-lexicon",
@ -340,9 +301,9 @@ dependencies = [
[[package]] [[package]]
name = "pyo3-ffi" name = "pyo3-ffi"
version = "0.21.2" version = "0.23.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01be5843dc60b916ab4dad1dca6d20b9b4e6ddc8e15f50c47fe6d85f1fb97403" checksum = "6fca7cd8fd809b5ac4eefb89c1f98f7a7651d3739dfb341ca6980090f554c270"
dependencies = [ dependencies = [
"libc", "libc",
"pyo3-build-config", "pyo3-build-config",
@ -350,9 +311,9 @@ dependencies = [
[[package]] [[package]]
name = "pyo3-log" name = "pyo3-log"
version = "0.10.0" version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af49834b8d2ecd555177e63b273b708dea75150abc6f5341d0a6e1a9623976c" checksum = "3eb421dc86d38d08e04b927b02424db480be71b777fa3a56f32e2f2a3a1a3b08"
dependencies = [ dependencies = [
"arc-swap", "arc-swap",
"log", "log",
@ -361,9 +322,9 @@ dependencies = [
[[package]] [[package]]
name = "pyo3-macros" name = "pyo3-macros"
version = "0.21.2" version = "0.23.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77b34069fc0682e11b31dbd10321cbf94808394c56fd996796ce45217dfac53c" checksum = "34e657fa5379a79151b6ff5328d9216a84f55dc93b17b08e7c3609a969b73aa0"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"pyo3-macros-backend", "pyo3-macros-backend",
@ -373,9 +334,9 @@ dependencies = [
[[package]] [[package]]
name = "pyo3-macros-backend" name = "pyo3-macros-backend"
version = "0.21.2" version = "0.23.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08260721f32db5e1a5beae69a55553f56b99bd0e1c3e6e0a5e8851a9d0f5a85c" checksum = "295548d5ffd95fd1981d2d3cf4458831b21d60af046b729b6fd143b0ba7aee2f"
dependencies = [ dependencies = [
"heck", "heck",
"proc-macro2", "proc-macro2",
@ -386,9 +347,9 @@ dependencies = [
[[package]] [[package]]
name = "pythonize" name = "pythonize"
version = "0.21.1" version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d0664248812c38cc55a4ed07f88e4df516ce82604b93b1ffdc041aa77a6cb3c" checksum = "91a6ee7a084f913f98d70cdc3ebec07e852b735ae3059a1500db2661265da9ff"
dependencies = [ dependencies = [
"pyo3", "pyo3",
"serde", "serde",
@ -433,15 +394,6 @@ dependencies = [
"getrandom", "getrandom",
] ]
[[package]]
name = "redox_syscall"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "469052894dcb553421e483e4209ee581a45100d31b4018de03e5a7ad86374a7e"
dependencies = [
"bitflags",
]
[[package]] [[package]]
name = "regex" name = "regex"
version = "1.11.1" version = "1.11.1"
@ -477,12 +429,6 @@ version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f"
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]] [[package]]
name = "serde" name = "serde"
version = "1.0.215" version = "1.0.215"
@ -537,12 +483,6 @@ dependencies = [
"digest", "digest",
] ]
[[package]]
name = "smallvec"
version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
[[package]] [[package]]
name = "subtle" name = "subtle"
version = "2.5.0" version = "2.5.0"
@ -694,67 +634,3 @@ dependencies = [
"js-sys", "js-sys",
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]]
name = "windows-targets"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6"
[[package]]
name = "windows_i686_gnu"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9"
[[package]]
name = "windows_i686_msvc"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0"

1
changelog.d/17966.misc Normal file
View file

@ -0,0 +1 @@
Bump pyo3 and dependencies to v0.23.2.

View file

@ -30,14 +30,14 @@ http = "1.1.0"
lazy_static = "1.4.0" lazy_static = "1.4.0"
log = "0.4.17" log = "0.4.17"
mime = "0.3.17" mime = "0.3.17"
pyo3 = { version = "0.21.0", features = [ pyo3 = { version = "0.23.2", features = [
"macros", "macros",
"anyhow", "anyhow",
"abi3", "abi3",
"abi3-py38", "abi3-py38",
] } ] }
pyo3-log = "0.10.0" pyo3-log = "0.12.0"
pythonize = "0.21.0" pythonize = "0.23.0"
regex = "1.6.0" regex = "1.6.0"
sha2 = "0.10.8" sha2 = "0.10.8"
serde = { version = "1.0.144", features = ["derive"] } serde = { version = "1.0.144", features = ["derive"] }

View file

@ -32,14 +32,14 @@ use crate::push::utils::{glob_to_regex, GlobMatchType};
/// Called when registering modules with python. /// Called when registering modules with python.
pub fn register_module(py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> { pub fn register_module(py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
let child_module = PyModule::new_bound(py, "acl")?; let child_module = PyModule::new(py, "acl")?;
child_module.add_class::<ServerAclEvaluator>()?; child_module.add_class::<ServerAclEvaluator>()?;
m.add_submodule(&child_module)?; m.add_submodule(&child_module)?;
// We need to manually add the module to sys.modules to make `from // We need to manually add the module to sys.modules to make `from
// synapse.synapse_rust import acl` work. // synapse.synapse_rust import acl` work.
py.import_bound("sys")? py.import("sys")?
.getattr("modules")? .getattr("modules")?
.set_item("synapse.synapse_rust.acl", child_module)?; .set_item("synapse.synapse_rust.acl", child_module)?;

View file

@ -41,9 +41,11 @@ use pyo3::{
pybacked::PyBackedStr, pybacked::PyBackedStr,
pyclass, pymethods, pyclass, pymethods,
types::{PyAnyMethods, PyDict, PyDictMethods, PyString}, types::{PyAnyMethods, PyDict, PyDictMethods, PyString},
Bound, IntoPy, PyAny, PyObject, PyResult, Python, Bound, IntoPyObject, PyAny, PyObject, PyResult, Python,
}; };
use crate::UnwrapInfallible;
/// Definitions of the various fields of the internal metadata. /// Definitions of the various fields of the internal metadata.
#[derive(Clone)] #[derive(Clone)]
enum EventInternalMetadataData { enum EventInternalMetadataData {
@ -60,31 +62,59 @@ enum EventInternalMetadataData {
impl EventInternalMetadataData { impl EventInternalMetadataData {
/// Convert the field to its name and python object. /// Convert the field to its name and python object.
fn to_python_pair<'a>(&self, py: Python<'a>) -> (&'a Bound<'a, PyString>, PyObject) { fn to_python_pair<'a>(&self, py: Python<'a>) -> (&'a Bound<'a, PyString>, Bound<'a, PyAny>) {
match self { match self {
EventInternalMetadataData::OutOfBandMembership(o) => { EventInternalMetadataData::OutOfBandMembership(o) => (
(pyo3::intern!(py, "out_of_band_membership"), o.into_py(py)) pyo3::intern!(py, "out_of_band_membership"),
} o.into_pyobject(py)
EventInternalMetadataData::SendOnBehalfOf(o) => { .unwrap_infallible()
(pyo3::intern!(py, "send_on_behalf_of"), o.into_py(py)) .to_owned()
} .into_any(),
EventInternalMetadataData::RecheckRedaction(o) => { ),
(pyo3::intern!(py, "recheck_redaction"), o.into_py(py)) EventInternalMetadataData::SendOnBehalfOf(o) => (
} pyo3::intern!(py, "send_on_behalf_of"),
EventInternalMetadataData::SoftFailed(o) => { o.into_pyobject(py).unwrap_infallible().into_any(),
(pyo3::intern!(py, "soft_failed"), o.into_py(py)) ),
} EventInternalMetadataData::RecheckRedaction(o) => (
EventInternalMetadataData::ProactivelySend(o) => { pyo3::intern!(py, "recheck_redaction"),
(pyo3::intern!(py, "proactively_send"), o.into_py(py)) o.into_pyobject(py)
} .unwrap_infallible()
EventInternalMetadataData::Redacted(o) => { .to_owned()
(pyo3::intern!(py, "redacted"), o.into_py(py)) .into_any(),
} ),
EventInternalMetadataData::TxnId(o) => (pyo3::intern!(py, "txn_id"), o.into_py(py)), EventInternalMetadataData::SoftFailed(o) => (
EventInternalMetadataData::TokenId(o) => (pyo3::intern!(py, "token_id"), o.into_py(py)), pyo3::intern!(py, "soft_failed"),
EventInternalMetadataData::DeviceId(o) => { o.into_pyobject(py)
(pyo3::intern!(py, "device_id"), o.into_py(py)) .unwrap_infallible()
} .to_owned()
.into_any(),
),
EventInternalMetadataData::ProactivelySend(o) => (
pyo3::intern!(py, "proactively_send"),
o.into_pyobject(py)
.unwrap_infallible()
.to_owned()
.into_any(),
),
EventInternalMetadataData::Redacted(o) => (
pyo3::intern!(py, "redacted"),
o.into_pyobject(py)
.unwrap_infallible()
.to_owned()
.into_any(),
),
EventInternalMetadataData::TxnId(o) => (
pyo3::intern!(py, "txn_id"),
o.into_pyobject(py).unwrap_infallible().into_any(),
),
EventInternalMetadataData::TokenId(o) => (
pyo3::intern!(py, "token_id"),
o.into_pyobject(py).unwrap_infallible().into_any(),
),
EventInternalMetadataData::DeviceId(o) => (
pyo3::intern!(py, "device_id"),
o.into_pyobject(py).unwrap_infallible().into_any(),
),
} }
} }
@ -247,7 +277,7 @@ impl EventInternalMetadata {
/// ///
/// Note that `outlier` and `stream_ordering` are stored in separate columns so are not returned here. /// Note that `outlier` and `stream_ordering` are stored in separate columns so are not returned here.
fn get_dict(&self, py: Python<'_>) -> PyResult<PyObject> { fn get_dict(&self, py: Python<'_>) -> PyResult<PyObject> {
let dict = PyDict::new_bound(py); let dict = PyDict::new(py);
for entry in &self.data { for entry in &self.data {
let (key, value) = entry.to_python_pair(py); let (key, value) = entry.to_python_pair(py);

View file

@ -30,7 +30,7 @@ mod internal_metadata;
/// Called when registering modules with python. /// Called when registering modules with python.
pub fn register_module(py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> { pub fn register_module(py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
let child_module = PyModule::new_bound(py, "events")?; let child_module = PyModule::new(py, "events")?;
child_module.add_class::<internal_metadata::EventInternalMetadata>()?; child_module.add_class::<internal_metadata::EventInternalMetadata>()?;
child_module.add_function(wrap_pyfunction!(filter::event_visible_to_server_py, m)?)?; child_module.add_function(wrap_pyfunction!(filter::event_visible_to_server_py, m)?)?;
@ -38,7 +38,7 @@ pub fn register_module(py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()>
// We need to manually add the module to sys.modules to make `from // We need to manually add the module to sys.modules to make `from
// synapse.synapse_rust import events` work. // synapse.synapse_rust import events` work.
py.import_bound("sys")? py.import("sys")?
.getattr("modules")? .getattr("modules")?
.set_item("synapse.synapse_rust.events", child_module)?; .set_item("synapse.synapse_rust.events", child_module)?;

View file

@ -70,7 +70,7 @@ pub fn http_request_from_twisted(request: &Bound<'_, PyAny>) -> PyResult<Request
let headers_iter = request let headers_iter = request
.getattr("requestHeaders")? .getattr("requestHeaders")?
.call_method0("getAllRawHeaders")? .call_method0("getAllRawHeaders")?
.iter()?; .try_iter()?;
for header in headers_iter { for header in headers_iter {
let header = header?; let header = header?;

View file

@ -1,3 +1,5 @@
use std::convert::Infallible;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use pyo3::prelude::*; use pyo3::prelude::*;
use pyo3_log::ResetHandle; use pyo3_log::ResetHandle;
@ -52,3 +54,16 @@ fn synapse_rust(py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
Ok(()) Ok(())
} }
pub trait UnwrapInfallible<T> {
fn unwrap_infallible(self) -> T;
}
impl<T> UnwrapInfallible<T> for Result<T, Infallible> {
fn unwrap_infallible(self) -> T {
match self {
Ok(val) => val,
Err(never) => match never {},
}
}
}

View file

@ -167,6 +167,7 @@ impl PushRuleEvaluator {
/// ///
/// Returns the set of actions, if any, that match (filtering out any /// Returns the set of actions, if any, that match (filtering out any
/// `dont_notify` and `coalesce` actions). /// `dont_notify` and `coalesce` actions).
#[pyo3(signature = (push_rules, user_id=None, display_name=None))]
pub fn run( pub fn run(
&self, &self,
push_rules: &FilteredPushRules, push_rules: &FilteredPushRules,
@ -236,6 +237,7 @@ impl PushRuleEvaluator {
} }
/// Check if the given condition matches. /// Check if the given condition matches.
#[pyo3(signature = (condition, user_id=None, display_name=None))]
fn matches( fn matches(
&self, &self,
condition: Condition, condition: Condition,

View file

@ -65,8 +65,8 @@ use anyhow::{Context, Error};
use log::warn; use log::warn;
use pyo3::exceptions::PyTypeError; use pyo3::exceptions::PyTypeError;
use pyo3::prelude::*; use pyo3::prelude::*;
use pyo3::types::{PyBool, PyList, PyLong, PyString}; use pyo3::types::{PyBool, PyInt, PyList, PyString};
use pythonize::{depythonize_bound, pythonize}; use pythonize::{depythonize, pythonize, PythonizeError};
use serde::de::Error as _; use serde::de::Error as _;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
@ -79,7 +79,7 @@ pub mod utils;
/// Called when registering modules with python. /// Called when registering modules with python.
pub fn register_module(py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> { pub fn register_module(py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
let child_module = PyModule::new_bound(py, "push")?; let child_module = PyModule::new(py, "push")?;
child_module.add_class::<PushRule>()?; child_module.add_class::<PushRule>()?;
child_module.add_class::<PushRules>()?; child_module.add_class::<PushRules>()?;
child_module.add_class::<FilteredPushRules>()?; child_module.add_class::<FilteredPushRules>()?;
@ -90,7 +90,7 @@ pub fn register_module(py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()>
// We need to manually add the module to sys.modules to make `from // We need to manually add the module to sys.modules to make `from
// synapse.synapse_rust import push` work. // synapse.synapse_rust import push` work.
py.import_bound("sys")? py.import("sys")?
.getattr("modules")? .getattr("modules")?
.set_item("synapse.synapse_rust.push", child_module)?; .set_item("synapse.synapse_rust.push", child_module)?;
@ -182,12 +182,16 @@ pub enum Action {
Unknown(Value), Unknown(Value),
} }
impl IntoPy<PyObject> for Action { impl<'py> IntoPyObject<'py> for Action {
fn into_py(self, py: Python<'_>) -> PyObject { type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PythonizeError;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
// When we pass the `Action` struct to Python we want it to be converted // When we pass the `Action` struct to Python we want it to be converted
// to a dict. We use `pythonize`, which converts the struct using the // to a dict. We use `pythonize`, which converts the struct using the
// `serde` serialization. // `serde` serialization.
pythonize(py, &self).expect("valid action") pythonize(py, &self)
} }
} }
@ -270,13 +274,13 @@ pub enum SimpleJsonValue {
} }
impl<'source> FromPyObject<'source> for SimpleJsonValue { impl<'source> FromPyObject<'source> for SimpleJsonValue {
fn extract(ob: &'source PyAny) -> PyResult<Self> { fn extract_bound(ob: &Bound<'source, PyAny>) -> PyResult<Self> {
if let Ok(s) = ob.downcast::<PyString>() { if let Ok(s) = ob.downcast::<PyString>() {
Ok(SimpleJsonValue::Str(Cow::Owned(s.to_string()))) Ok(SimpleJsonValue::Str(Cow::Owned(s.to_string())))
// A bool *is* an int, ensure we try bool first. // A bool *is* an int, ensure we try bool first.
} else if let Ok(b) = ob.downcast::<PyBool>() { } else if let Ok(b) = ob.downcast::<PyBool>() {
Ok(SimpleJsonValue::Bool(b.extract()?)) Ok(SimpleJsonValue::Bool(b.extract()?))
} else if let Ok(i) = ob.downcast::<PyLong>() { } else if let Ok(i) = ob.downcast::<PyInt>() {
Ok(SimpleJsonValue::Int(i.extract()?)) Ok(SimpleJsonValue::Int(i.extract()?))
} else if ob.is_none() { } else if ob.is_none() {
Ok(SimpleJsonValue::Null) Ok(SimpleJsonValue::Null)
@ -298,15 +302,19 @@ pub enum JsonValue {
} }
impl<'source> FromPyObject<'source> for JsonValue { impl<'source> FromPyObject<'source> for JsonValue {
fn extract(ob: &'source PyAny) -> PyResult<Self> { fn extract_bound(ob: &Bound<'source, PyAny>) -> PyResult<Self> {
if let Ok(l) = ob.downcast::<PyList>() { if let Ok(l) = ob.downcast::<PyList>() {
match l.iter().map(SimpleJsonValue::extract).collect() { match l
.iter()
.map(|it| SimpleJsonValue::extract_bound(&it))
.collect()
{
Ok(a) => Ok(JsonValue::Array(a)), Ok(a) => Ok(JsonValue::Array(a)),
Err(e) => Err(PyTypeError::new_err(format!( Err(e) => Err(PyTypeError::new_err(format!(
"Can't convert to JsonValue::Array: {e}" "Can't convert to JsonValue::Array: {e}"
))), ))),
} }
} else if let Ok(v) = SimpleJsonValue::extract(ob) { } else if let Ok(v) = SimpleJsonValue::extract_bound(ob) {
Ok(JsonValue::Value(v)) Ok(JsonValue::Value(v))
} else { } else {
Err(PyTypeError::new_err(format!( Err(PyTypeError::new_err(format!(
@ -363,15 +371,19 @@ pub enum KnownCondition {
}, },
} }
impl IntoPy<PyObject> for Condition { impl<'source> IntoPyObject<'source> for Condition {
fn into_py(self, py: Python<'_>) -> PyObject { type Target = PyAny;
pythonize(py, &self).expect("valid condition") type Output = Bound<'source, Self::Target>;
type Error = PythonizeError;
fn into_pyobject(self, py: Python<'source>) -> Result<Self::Output, Self::Error> {
pythonize(py, &self)
} }
} }
impl<'source> FromPyObject<'source> for Condition { impl<'source> FromPyObject<'source> for Condition {
fn extract_bound(ob: &Bound<'source, PyAny>) -> PyResult<Self> { fn extract_bound(ob: &Bound<'source, PyAny>) -> PyResult<Self> {
Ok(depythonize_bound(ob.clone())?) Ok(depythonize(ob)?)
} }
} }

View file

@ -29,7 +29,7 @@ use pyo3::{
exceptions::PyValueError, exceptions::PyValueError,
pyclass, pymethods, pyclass, pymethods,
types::{PyAnyMethods, PyModule, PyModuleMethods}, types::{PyAnyMethods, PyModule, PyModuleMethods},
Bound, Py, PyAny, PyObject, PyResult, Python, ToPyObject, Bound, IntoPyObject, Py, PyAny, PyObject, PyResult, Python,
}; };
use ulid::Ulid; use ulid::Ulid;
@ -37,6 +37,7 @@ use self::session::Session;
use crate::{ use crate::{
errors::{NotFoundError, SynapseError}, errors::{NotFoundError, SynapseError},
http::{http_request_from_twisted, http_response_to_twisted, HeaderMapPyExt}, http::{http_request_from_twisted, http_response_to_twisted, HeaderMapPyExt},
UnwrapInfallible,
}; };
mod session; mod session;
@ -125,7 +126,11 @@ impl RendezvousHandler {
let base = Uri::try_from(format!("{base}_synapse/client/rendezvous")) let base = Uri::try_from(format!("{base}_synapse/client/rendezvous"))
.map_err(|_| PyValueError::new_err("Invalid base URI"))?; .map_err(|_| PyValueError::new_err("Invalid base URI"))?;
let clock = homeserver.call_method0("get_clock")?.to_object(py); let clock = homeserver
.call_method0("get_clock")?
.into_pyobject(py)
.unwrap_infallible()
.unbind();
// Construct a Python object so that we can get a reference to the // Construct a Python object so that we can get a reference to the
// evict method and schedule it to run. // evict method and schedule it to run.
@ -318,7 +323,7 @@ impl RendezvousHandler {
} }
pub fn register_module(py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> { pub fn register_module(py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
let child_module = PyModule::new_bound(py, "rendezvous")?; let child_module = PyModule::new(py, "rendezvous")?;
child_module.add_class::<RendezvousHandler>()?; child_module.add_class::<RendezvousHandler>()?;
@ -326,7 +331,7 @@ pub fn register_module(py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()>
// We need to manually add the module to sys.modules to make `from // We need to manually add the module to sys.modules to make `from
// synapse.synapse_rust import rendezvous` work. // synapse.synapse_rust import rendezvous` work.
py.import_bound("sys")? py.import("sys")?
.getattr("modules")? .getattr("modules")?
.set_item("synapse.synapse_rust.rendezvous", child_module)?; .set_item("synapse.synapse_rust.rendezvous", child_module)?;