Skip to content

refactor: narrow exclusive write lock duration in App.add_exception_handler #288

Open

Description

@ZhuchkaTriplesix

Problem Description

In src/lib.rs#L738-L755:

    fn add_exception_handler(
        &self,
        exc_type: pyo3::Bound<'_, pyo3::types::PyType>,
        handler: Py<PyAny>,
    ) -> PyResult<()> {
        let mut st = self.state.write();
        let is_async = pyo3::Python::with_gil(|py| -> PyResult<bool> {
            let inspect = py.import(inspect)?;
            inspect
                .getattr(iscoroutinefunction)?
                .call1((&handler,))?
                .extract::<bool>()
        })
        .unwrap_or(false);
        Arc::make_mut(&mut st.exception_handlers).push((exc_type.unbind(), handler, is_async));
        st.rebuild_snapshot();
        Ok(())
    }

The exclusive write lock self.state.write() is acquired before dynamically importing inspect and invoking inspect.iscoroutinefunction. This unnecessarily extends the exclusive write lock duration across multiple Python attribute lookups and function calls.

Proposed Solution

  1. Receive py: Python<'_> in the method signature or compute is_async before taking self.state.write().
  2. Restrict state.write() only to the push and st.rebuild_snapshot() operations.

Acceptance Criteria

  • iscoroutinefunction check is performed prior to acquiring the write lock.
  • Exclusive write lock duration is minimized.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions