This is an automated email from the ASF dual-hosted git repository.

chaokunyang pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/fory.git


The following commit(s) were added to refs/heads/main by this push:
     new dfdff7afd docs(rust): add rust thread safety and troubleshooting doc 
(#2781)
dfdff7afd is described below

commit dfdff7afd559d8d8e37241a8324e6eadfd554c2f
Author: Shawn Yang <[email protected]>
AuthorDate: Mon Oct 20 13:02:33 2025 +0800

    docs(rust): add rust thread safety and troubleshooting doc (#2781)
    
    ## Why?
    
    <!-- Describe the purpose of this PR. -->
    
    ## What does this PR do?
    
    add rust thread safety and troubleshooting doc
    
    ## Related issues
    
    <!--
    Is there any related issue? If this PR closes them you say say
    fix/closes:
    
    - #xxxx0
    - #xxxx1
    - Fixes #xxxx2
    -->
    
    ## Does this PR introduce any user-facing change?
    
    <!--
    If any user-facing interface changes, please [open an
    issue](https://github.com/apache/fory/issues/new/choose) describing the
    need to do so and update the document if necessary.
    
    Delete section if not applicable.
    -->
    
    - [ ] Does this PR introduce any public API change?
    - [ ] Does this PR introduce any binary protocol compatibility change?
    
    ## Benchmark
    
    <!--
    When the PR has an impact on performance (if you don't know whether the
    PR will have an impact on performance, you can submit the PR first, and
    if it will have impact on performance, the code reviewer will explain
    it), be sure to attach a benchmark data here.
    
    Delete section if not applicable.
    -->
---
 rust/README.md       | 42 ++++++++++++++++++++++++++++++++
 rust/fory/src/lib.rs | 67 +++++++++++++++++++++++++++++++++++++++++++---------
 2 files changed, 98 insertions(+), 11 deletions(-)

diff --git a/rust/README.md b/rust/README.md
index 849afd935..8f523b305 100644
--- a/rust/README.md
+++ b/rust/README.md
@@ -730,6 +730,48 @@ assert_eq!(prefs.values().get(0), "en");
 | Memory usage         | Full object graph in memory   | Only accessed fields 
in memory  |
 | Suitable for         | Small objects, full access    | Large objects, 
selective access |
 
+### 8. Thread-Safe Serialization
+
+Apache Fory™ Rust is fully thread-safe: `Fory` implements both `Send` and 
`Sync`, so one configured instance can be shared across threads for concurrent 
work. The internal read/write context pools are lazily initialized with 
thread-safe primitives, letting worker threads reuse buffers without 
coordination.
+
+```rust
+use fory::{Fory, Error};
+use fory::ForyObject;
+use std::sync::Arc;
+use std::thread;
+
+#[derive(ForyObject, Clone, Copy, Debug, PartialEq)]
+struct Item {
+    value: i32,
+}
+
+fn main() -> Result<(), Error> {
+    let mut fory = Fory::default();
+    fory.register::<Item>(1000)?;
+
+    let fory = Arc::new(fory);
+    let handles: Vec<_> = (0..8)
+        .map(|i| {
+            let shared = Arc::clone(&fory);
+            thread::spawn(move || {
+                let item = Item { value: i };
+                shared.serialize(&item)
+            })
+        })
+        .collect();
+
+    for handle in handles {
+        let bytes = handle.join().unwrap()?;
+        let item: Item = fory.deserialize(&bytes)?;
+        assert!(item.value >= 0);
+    }
+
+    Ok(())
+}
+```
+
+**Tip:** Perform registrations (such as `fory.register::<T>(id)`) before 
spawning threads so every worker sees the same metadata. Once configured, 
wrapping the instance in `Arc` is enough to fan out serialization and 
deserialization tasks safely.
+
 ## 🔧 Supported Types
 
 ### Primitive Types
diff --git a/rust/fory/src/lib.rs b/rust/fory/src/lib.rs
index b5c6d0117..b0b289aa1 100644
--- a/rust/fory/src/lib.rs
+++ b/rust/fory/src/lib.rs
@@ -1010,25 +1010,45 @@
 //!
 //! ## Thread Safety
 //!
-//! **Important:** `Fory` instances are **not thread-safe**. Use one instance 
per thread:
+//! `Fory` implements `Send` and `Sync`, so a single instance can be shared 
across threads
+//! (for example via `Arc<Fory>`) for concurrent serialization and 
deserialization. The
+//! internal context pools grow lazily and rely on thread-safe primitives, 
allowing multiple
+//! workers to reuse buffers without additional coordination.
 //!
 //! ```rust
-//! use std::thread_local;
-//! use std::cell::RefCell;
+//! use std::sync::Arc;
+//! use std::thread;
 //! use fory::Fory;
+//! use fory::ForyObject;
 //!
-//! thread_local! {
-//!     static FORY: RefCell<Fory> = RefCell::new(Fory::default());
+//! #[derive(ForyObject, Clone, Copy, Debug)]
+//! struct Item {
+//!     value: i32,
 //! }
 //!
-//! # fn serialize_data() -> Vec<u8> {
-//! FORY.with(|fory| {
-//!     let data = vec![1, 2, 3];
-//!     fory.borrow().serialize(&data).unwrap()
-//! })
-//! # }
+//! let mut fory = Fory::default();
+//! fory.register::<Item>(1000).unwrap();
+//! let fory = Arc::new(fory);
+//! let handles: Vec<_> = (0..8)
+//!     .map(|i| {
+//!         let shared = Arc::clone(&fory);
+//!         thread::spawn(move || {
+//!             let item = Item { value: i };
+//!             shared.serialize(&item).unwrap()
+//!         })
+//!     })
+//!     .collect();
+//!
+//! for handle in handles {
+//!     let bytes = handle.join().unwrap();
+//!     let item: Item = fory.deserialize(&bytes).unwrap();
+//!     assert!(item.value >= 0);
+//! }
 //! ```
 //!
+//! **Best practice:** Perform type registration (e.g., 
`fory.register::<T>(id)`) before
+//! spawning worker threads so metadata is ready, then share the configured 
instance.
+//!
 //! ## Examples
 //!
 //! See the `tests/` directory for comprehensive examples:
@@ -1038,6 +1058,31 @@
 //! - `tests/tests/test_weak.rs` - Circular reference handling
 //! - `tests/tests/test_cross_language.rs` - Cross-language compatibility
 //!
+//! ## Troubleshooting
+//!
+//! - **Type registry errors**: Errors such as `TypeId ... not found in 
type_info registry` mean
+//!   the type was never registered with the active `Fory` instance. Ensure 
every serializable
+//!   struct, enum, or trait implementation calls `register::<T>(type_id)` 
before use, and reuse
+//!   the same IDs when deserializing.
+//! - **Quick error lookup**: Always prefer the static constructors on
+//!   [`fory_core::error::Error`]—for example `Error::type_mismatch`, 
`Error::invalid_data`, or
+//!   `Error::unknown`. They keep diagnostics consistent and allow optional 
panic-on-error
+//!   debugging.
+//! - **Panic on error for backtraces**: Set `FORY_PANIC_ON_ERROR=1` (or 
`true`) together with
+//!   `RUST_BACKTRACE=1` while running tests or binaries to panic exactly 
where an error is
+//!   constructed. Unset the variable afterwards so production paths keep 
returning `Result`.
+//! - **Struct field tracing**: Add the `#[fory_debug]` attribute next to 
`#[derive(ForyObject)]`
+//!   when you need per-field instrumentation. Once compiled with debug hooks, 
call
+//!   `set_before_write_field_func`, `set_after_write_field_func`, 
`set_before_read_field_func`, or
+//!   `set_after_read_field_func` from `fory_core::serializer::struct_` to 
install custom
+//!   callbacks, and use `reset_struct_debug_hooks()` to restore defaults.
+//! - **Lightweight logging**: If custom callbacks are unnecessary, enable
+//!   `ENABLE_FORY_DEBUG_OUTPUT=1` to have the default hook handlers print 
field-level read/write
+//!   events. This is useful for spotting cursor misalignment or unexpected 
buffer growth.
+//! - **Test-time hygiene**: Some integration tests expect 
`FORY_PANIC_ON_ERROR` to stay unset.
+//!   Export it only during focused debugging, and rely on targeted commands 
such as
+//!   `cargo test --features tests -p fory-tests --test <case>` when isolating 
failures.
+//!
 //! ## Documentation
 //!
 //! - **[Protocol 
Specification](https://fory.apache.org/docs/specification/fory_xlang_serialization_spec)**
 - Binary protocol details


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to