Closed poborin closed 2 weeks ago
Hi, could you please firstly check whether it is related to frb or your JSON deserialize code? And could you please show Rust stacktrace during the panic
I don't think this is a rust deserealize issue, as the Rust test succeeds. The data structure provides a test case that checks it.
How can I add a stacktrace logging? I tried following in lib.rs
?
use flutter_rust_bridge::{frb, setup_default_user_utils};
use std::backtrace::Backtrace;
use std::cell::Cell;
use std::env;
pub mod api;
mod frb_generated;
thread_local! {
static BACKTRACE: Cell<Option<Backtrace>> = const { Cell::new(None) };
}
#[frb(init)]
pub fn init_app() {
env::set_var("RUST_BACKTRACE", "1");
setup_default_user_utils();
std::panic::set_hook(Box::new(|_| {
let trace = Backtrace::capture();
BACKTRACE.set(Some(trace));
}));
}
and then the catch in deserealize:
impl TrainingPlan {
#[frb(sync)]
pub fn test_deserialize(content: String) -> Result<Self, String> {
info!("<!> deserializing training plan: {}", content);
let result = panic::catch_unwind(|| {
serde_json::from_str(&content)
});
match result {
Ok(Ok(plan)) => Ok(plan),
Ok(Err(e)) => {
error!("Deserialization error: {}", e.to_string());
Err(e.to_string())
}
Err(e) => {
let b = BACKTRACE.take().unwrap();
error!("at panic:\n{}", b);
let err = format!("A panic occurred during deserialization: {e:?}");
error!("{}", err);
Err(err)
}
}
}
}
No matter what, I don't get a stack trace.
update:
fn test_panic()
just to see if I get a backtrace and it works.#[frb] fn deserialize(...)
and it fails with a different error:
<!> test async
Error loading test data: PanicException(RangeError: Maximum call stack size exceeded)
Failed to initialize: Uncaught RangeError: Maximum call stack size exceeded
stacktrace: https://cjycode.com/flutter_rust_bridge/guides/how-to/stack-trace (e.g. ensure you create a blank new project with default generated code etc)
Based on your info, I guess there may be another reason: It is not because json deserialization, but because returning the nesting type. Again, with stack trace it will be clear to see what is going on.
It would be great to have a minimal reproducible sample (e.g. if it is the nesting type problem, then we can produce a dozen line of code that reproduce it).
I created a minimal library to reproduce an error https://github.com/poborin/frb_deserialize
a command to execute:
flutter run --web-header=Cross-Origin-Opener-Policy=same-origin --web-header=Cross-Origin-Embedder-Policy=require-corp -d chrome
Great! However, "minimal reproducible sample" often means to reduce to a minimal complexity. For example, in https://github.com/poborin/frb_deserialize/blob/main/rust/src/api/training_plan.rs, maybe it can be as short as:
pub struct A {
field: Vec<A>,
}
pub fn f() -> A {
A { field: vec![A { field: vec![]]}
}
i.e. remove whatever does not cause the problem, such as unneeded fields, json deserialization, etc
I have updated the repo. It turns that deserializer fails with u8
:
use flutter_rust_bridge::frb;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct TrainingPlan {
pub(crate) weeks: u8,
}
impl TrainingPlan {
#[frb(sync)]
pub fn test_deserialize(content: String) -> Result<Self, String> {
serde_json::from_str(&content).map_err(|e| e.to_string())
}
}
{
"weeks": 10
}
Hmm, do you mean it is a serde_json::from_str
error, or an error in frb?
To isolate the problem, try
#[frb(sync)]
pub fn test_deserialize(content: String) -> Result<Self, String> {
Ok(Self {weeks: 10})
}
and also try to serde_json::from_str
in pure Rust tests (maybe Rust wasm if you are in web)
Hi, I tried to avoid calling serde_json::from_str, while still using flutter_rust_bridge, and the issue disappears. Therefore, it may be related to serde instead of flutter_rust_bridge. Feel free to reopen if you have any questions!
This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new issue.
Describe the bug
I have a fairly simple data structure:
data structure
```rust use flutter_rust_bridge::frb; use log::{error, info}; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone, Debug)] pub struct TrainingPlan { pub(crate) cycles: Vecand the corresponding test data
test JSON
```json { "title": "[Your Club Name] Rowing Team Annual Plan", "cycles": [ { "cycle_type": "macrocycle", "name": "Annual Training Cycle", "start_date": "[Please confirm the specific start date]", "end_date": "[Please confirm the specific end date]", "phases": [ { "phase": "pre-season", "weeks": 12 }, { "phase": "in-season", "weeks": 24 }, { "phase": "post-season", "weeks": 4 } ], "sub_cycles": [], "sessions": [ { "day": "tuesday", "type": "ergo", "focus_areas": "Endurance building, technique improvement", "start_time": "06:00", "duration": "1 hour", "intensity": "moderate to high", "notes": "", "recovery_focus": "", "rehab_details": "" }, { "day": "thursday", "type": "on-water", "focus_areas": "Technique work, race pace intervals", "start_time": "06:00", "duration": "1.5 hours", "intensity": "moderate", "notes": "", "recovery_focus": "", "rehab_details": "" }, { "day": "saturday", "type": "on-water", "focus_areas": "Long endurance rows, consistent pacing", "start_time": "07:00", "duration": "2 hours", "intensity": "low to moderate", "notes": "", "recovery_focus": "", "rehab_details": "" }, { "day": "monday", "type": "gym", "focus_areas": "Core stability, strength building, functional movements", "start_time": "17:00", "duration": "1 hour", "intensity": "moderate", "notes": "", "recovery_focus": "", "rehab_details": "" } ], "target": { "type": "team", "name": "Rowing Team of 20 Members" } } ] } ```So, it's a small and simple document and the data structure. However, when I execute the
deserialize()
method in the web app e.g.It fails with the
Stack Overflow
exceptionSteps to reproduce
assets/test_data/training_plan.json
at the root of the project.pubspec.yaml
flutter run --web-header=Cross-Origin-Opener-Policy=same-origin --web-header=Cross-Origin-Embedder-Policy=require-corp
Logs
Expected behavior
No response
Generated binding code
No response
OS
MacOS
Version of
flutter_rust_bridge_codegen
2.4.0
Flutter info
Version of
clang++
19.1.0
Additional context
No response