Skip to content

Commit 5d95123

Browse files
authored
Merge pull request #251 from matrix-org/rav/jslogger
Allow JS side to pass a `logger` instance in
2 parents 9a9e467 + 5611b07 commit 5d95123

File tree

10 files changed

+302
-114
lines changed

10 files changed

+302
-114
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
- Add support for received room key bundle data, as required by encrypted history sharing ((MSC4268)[https://github.com/matrix-org/matrix-spec-proposals/pull/4268)). ([#5276](https://github.com/matrix-org/matrix-rust-sdk/pull/5276))
66

7+
- Extend `OlmMachine` constructor functions to accept an optional `logger` instance. This logger is associated with the machine for its lifetime, and used instead of the global `console` to write any log messages from the underlying rust library. Similarly, the legacy store migration functions (in the `Migration` class), and the `StoreHandle` open functions are extended to accept an optional logger, to be used for the duration of that operation. ([#251](https://github.com/matrix-org/matrix-rust-sdk-crypto-wasm/pull/251))
8+
79
- Add a new error code for `MegolmDecryptionError`, `DecryptionErrorCode::MismatchedSender`, indicating that the sender of the event does not match the owner of the device that established the Megolm session. ([#248](https://github.com/matrix-org/matrix-rust-sdk-crypto-wasm/pull/248))
810

911
# matrix-sdk-crypto-wasm v15.0.0

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ thiserror = "2.0.12"
7474
tracing = { version = "0.1.36", default-features = false, features = ["std"] }
7575
tracing-subscriber = { version = "0.3.14", default-features = false, features = ["registry", "std", "ansi"] }
7676
url = "2.5.0"
77-
wasm-bindgen = "0.2.89"
77+
wasm-bindgen = "0.2.100"
7878
wasm-bindgen-futures = "0.4.33"
7979
zeroize = "1.6.0"
8080
wasm-bindgen-test = "0.3.37"

index.d.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,13 @@ export declare function initAsync(url?: URL | string): Promise<void>;
5151
// The auto-generated typescript definitions are a good start, but could do with tightening up in a lot of areas.
5252
// The following is a manually-curated set of typescript definitions.
5353
declare module "./pkg/matrix_sdk_crypto_wasm.js" {
54+
interface JsLogger {
55+
debug(data: any): void;
56+
info(data: any): void;
57+
warn(data: any): void;
58+
error(data: any): void;
59+
}
60+
5461
/** The types returned by {@link OlmMachine.outgoingRequests}. */
5562
type OutgoingRequest =
5663
| KeysUploadRequest

src/future.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use std::future::Future;
22

33
use js_sys::Promise;
4+
use tracing::instrument::WithSubscriber;
45
use wasm_bindgen::{JsError, JsValue, UnwrapThrowExt};
56
use wasm_bindgen_futures::spawn_local;
67

@@ -9,6 +10,10 @@ use wasm_bindgen_futures::spawn_local;
910
* Javascript [`Promise`] which either resolves with an object of type `T`,
1011
* or rejects with an error of type [`Error`].
1112
*
13+
* Also applies [`WithSubscriber::with_current_subscriber`] to the future,
14+
* to ensure that the active tracing subscriber remains active while the
15+
* future is polled.
16+
*
1217
* [`Error`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
1318
*/
1419
pub(crate) fn future_to_promise<F, T>(future: F) -> Promise
@@ -23,14 +28,18 @@ where
2328
* Convert a Rust [`Future`] which returns [`Result<T, E>`] into a
2429
* Javascript [`Promise`] which either resolves with an object of type `T`,
2530
* or rejects with an error of type `E`.
31+
*
32+
* Also applies [`WithSubscriber::with_current_subscriber`] to the future,
33+
* to ensure that the active tracing subscriber remains active while the
34+
* future is polled.
2635
*/
2736
pub(crate) fn future_to_promise_with_custom_error<F, T, E>(future: F) -> Promise
2837
where
2938
F: Future<Output = Result<T, E>> + 'static,
3039
T: Into<JsValue>,
3140
E: Into<JsValue>,
3241
{
33-
let mut future = Some(future);
42+
let mut future = Some(future.with_current_subscriber());
3443

3544
Promise::new(&mut |resolve, reject| {
3645
let future = future.take().unwrap_throw();

src/libolm_migration.rs

Lines changed: 48 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,10 @@
1616
1717
use std::time::Duration;
1818

19-
use js_sys::{Date, Uint8Array};
20-
use matrix_sdk_common::ruma::{
21-
DeviceKeyAlgorithm, MilliSecondsSinceUnixEpoch, SecondsSinceUnixEpoch, UInt,
19+
use js_sys::{Date, Promise, Uint8Array};
20+
use matrix_sdk_common::{
21+
js_tracing::JsLogger,
22+
ruma::{DeviceKeyAlgorithm, MilliSecondsSinceUnixEpoch, SecondsSinceUnixEpoch, UInt},
2223
};
2324
use matrix_sdk_crypto::{
2425
olm::PrivateCrossSigningIdentity,
@@ -31,11 +32,14 @@ use matrix_sdk_crypto::{
3132
vodozemac::{Curve25519PublicKey, Ed25519PublicKey},
3233
Session,
3334
};
35+
use tracing::dispatcher;
3436
use wasm_bindgen::prelude::*;
3537

3638
use crate::{
39+
future::future_to_promise,
3740
identifiers::{DeviceId, RoomId, UserId},
3841
store::StoreHandle,
42+
tracing::logger_to_dispatcher,
3943
};
4044

4145
type Result<T, E = JsError> = std::result::Result<T, E>;
@@ -52,7 +56,7 @@ pub struct Migration {}
5256
///
5357
/// Can be imported into the rust store with {@link Migration::migrateBaseData}.
5458
#[wasm_bindgen(getter_with_clone)]
55-
#[derive(Debug, Default)]
59+
#[derive(Debug, Default, Clone)]
5660
pub struct BaseMigrationData {
5761
/// The user id of the account owner.
5862
#[wasm_bindgen(js_name = "userId")]
@@ -115,15 +119,23 @@ impl Migration {
115119
/// account objects.
116120
/// * `store_handle` - A connection to the CryptoStore which will be used to
117121
/// store the vodozemac data.
118-
#[wasm_bindgen(js_name = "migrateBaseData")]
119-
pub async fn migrate_base_data(
122+
/// * `logger` - An optional logger instance to use for writing log messages
123+
/// during the migration operation. An instance of `JsLogger`.
124+
#[wasm_bindgen(js_name = "migrateBaseData", unchecked_return_type = "Promise<void>")]
125+
pub fn migrate_base_data(
120126
data: &BaseMigrationData,
121127
pickle_key: Uint8Array,
122128
store_handle: &StoreHandle,
123-
) -> Result<JsValue, JsError> {
124-
migrate_base_data_to_store(data, &(pickle_key.to_vec()), store_handle.store.as_ref())
125-
.await?;
126-
Ok(JsValue::UNDEFINED)
129+
logger: Option<JsLogger>,
130+
) -> Promise {
131+
let _guard = dispatcher::set_default(&logger_to_dispatcher(logger));
132+
let store_handle = store_handle.clone();
133+
let data = data.clone();
134+
future_to_promise(async move {
135+
migrate_base_data_to_store(&data, &(pickle_key.to_vec()), store_handle.store.as_ref())
136+
.await?;
137+
Ok(JsValue::UNDEFINED)
138+
})
127139
}
128140
}
129141

@@ -241,21 +253,30 @@ impl Migration {
241253
/// session objects.
242254
/// * `store_handle` - A connection to the CryptoStore which will be used to
243255
/// store the vodozemac data.
244-
#[wasm_bindgen(js_name = "migrateOlmSessions")]
245-
pub async fn migrate_olm_sessions(
256+
/// * `logger` - An optional logger instance to use for writing log messages
257+
/// during the migration operation. An instance of `JsLogger`.
258+
#[wasm_bindgen(js_name = "migrateOlmSessions", unchecked_return_type = "Promise<void>")]
259+
pub fn migrate_olm_sessions(
246260
sessions: Vec<PickledSession>,
247261
pickle_key: Uint8Array,
248262
store_handle: &StoreHandle,
249-
) -> Result<JsValue, JsError> {
263+
logger: Option<JsLogger>,
264+
) -> Result<Promise, JsError> {
265+
let _guard = dispatcher::set_default(&logger_to_dispatcher(logger));
266+
250267
let pickle_key = pickle_key.to_vec();
251268

252269
let rust_sessions = sessions
253270
.into_iter()
254271
.map(|session| libolm_pickled_session_to_rust_pickled_session(session, &pickle_key))
255272
.collect::<Result<_>>()?;
256273

257-
import_olm_sessions_to_store(rust_sessions, store_handle.store.as_ref()).await?;
258-
Ok(JsValue::UNDEFINED)
274+
let store_handle = store_handle.clone();
275+
276+
Ok(future_to_promise(async move {
277+
import_olm_sessions_to_store(rust_sessions, store_handle.store.as_ref()).await?;
278+
Ok(JsValue::UNDEFINED)
279+
}))
259280
}
260281
}
261282

@@ -393,12 +414,16 @@ impl Migration {
393414
/// megolm session objects.
394415
/// * `store_handle` - A connection to the CryptoStore which will be used to
395416
/// store the vodozemac data.
396-
#[wasm_bindgen(js_name = "migrateMegolmSessions")]
397-
pub async fn migrate_megolm_sessions(
417+
/// * `logger` - An optional logger instance to use for writing log messages
418+
/// during the migration operation. An instance of `JsLogger`.
419+
#[wasm_bindgen(js_name = "migrateMegolmSessions", unchecked_return_type = "Promise<void>")]
420+
pub fn migrate_megolm_sessions(
398421
sessions: Vec<PickledInboundGroupSession>,
399422
pickle_key: Uint8Array,
400423
store_handle: &StoreHandle,
401-
) -> Result<JsValue, JsError> {
424+
logger: Option<JsLogger>,
425+
) -> Result<Promise, JsError> {
426+
let _guard = dispatcher::set_default(&logger_to_dispatcher(logger));
402427
let pickle_key = pickle_key.to_vec();
403428

404429
let rust_sessions = sessions
@@ -408,8 +433,11 @@ impl Migration {
408433
})
409434
.collect::<Result<_>>()?;
410435

411-
import_megolm_sessions_to_store(rust_sessions, store_handle.store.as_ref()).await?;
412-
Ok(JsValue::UNDEFINED)
436+
let store_handle = store_handle.clone();
437+
Ok(future_to_promise(async move {
438+
import_megolm_sessions_to_store(rust_sessions, store_handle.store.as_ref()).await?;
439+
Ok(JsValue::UNDEFINED)
440+
}))
413441
}
414442
}
415443

0 commit comments

Comments
 (0)