Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Externalize tokio-ffi oo_bindgen model and implementation #102

Merged
merged 4 commits into from
Sep 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion dep_config.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
"same-file",
"semver",
"semver-parser",
"tracing-ffi-schema",
"ucd-trie",
"unicode-segmentation",
"version_check",
Expand All @@ -43,6 +42,12 @@
},
"scursor": {
"url": "https://github.com/stepfunc/scursor"
},
"tokio-ffi-schema": {
"url": "https://github.com/stepfunc/tokio-ffi"
},
"tracing-ffi-schema": {
"url": "https://github.com/stepfunc/tracing-ffi"
}
},
"third_party": {
Expand Down
1 change: 1 addition & 0 deletions ffi/rodbus-ffi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ num_cpus = "1"
rodbus-schema = { path = "../rodbus-schema" }
rust-oo-bindgen = { git = "https://github.com/stepfunc/oo_bindgen.git", tag = "0.3.0" }
tracing-ffi-schema = { git = "https://github.com/stepfunc/tracing-ffi.git", tag = "0.1.0" }
tokio-ffi-schema = { git = "https://github.com/stepfunc/tokio-ffi.git", tag = "0.1.0" }

[features]
default = ["serial", "tls"]
Expand Down
19 changes: 16 additions & 3 deletions ffi/rodbus-ffi/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,27 @@ use std::env;
use std::io::Write;
use std::path::Path;

fn main() {
println!("cargo:rerun-if-changed=build.rs");

fn write_tracing_ffi() {
let mut file =
std::fs::File::create(Path::new(&env::var_os("OUT_DIR").unwrap()).join("tracing.rs"))
.unwrap();
file.write_all(tracing_ffi_schema::get_impl_file().as_bytes())
.unwrap();
}

fn write_tokio_ffi() {
let mut file =
std::fs::File::create(Path::new(&env::var_os("OUT_DIR").unwrap()).join("runtime.rs"))
.unwrap();
file.write_all(tokio_ffi_schema::get_impl_file().as_bytes())
.unwrap();
}

fn main() {
println!("cargo:rerun-if-changed=build.rs");

write_tracing_ffi();
write_tokio_ffi();

match rodbus_schema::build_lib() {
Ok(lib) => {
Expand Down
33 changes: 29 additions & 4 deletions ffi/rodbus-ffi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,41 @@ pub use server::*;

pub mod ffi;

lazy_static::lazy_static! {
static ref VERSION: std::ffi::CString = std::ffi::CString::new(rodbus::VERSION).unwrap();
}

fn version() -> &'static std::ffi::CStr {
&VERSION
}

// the From<> impls below are needed to map tracing and tokio ffi stuff to the actual errors used in this crate

impl From<crate::TracingInitError> for std::os::raw::c_int {
fn from(_: crate::TracingInitError) -> Self {
crate::ffi::ParamError::LoggingAlreadyConfigured.into()
}
}

lazy_static::lazy_static! {
static ref VERSION: std::ffi::CString = std::ffi::CString::new(rodbus::VERSION).unwrap();
impl From<crate::runtime::RuntimeError> for crate::ffi::ParamError {
fn from(err: crate::runtime::RuntimeError) -> Self {
match err {
crate::runtime::RuntimeError::RuntimeDestroyed => {
crate::ffi::ParamError::RuntimeDestroyed
}
crate::runtime::RuntimeError::CannotBlockWithinAsync => {
crate::ffi::ParamError::RuntimeCannotBlockWithinAsync
}
crate::runtime::RuntimeError::FailedToCreateRuntime => {
crate::ffi::ParamError::RuntimeCreationFailure
}
}
}
}

fn version() -> &'static std::ffi::CStr {
&VERSION
impl From<crate::runtime::RuntimeError> for std::os::raw::c_int {
fn from(err: crate::runtime::RuntimeError) -> Self {
let err: crate::ffi::ParamError = err.into();
err.into()
}
}
82 changes: 1 addition & 81 deletions ffi/rodbus-ffi/src/runtime.rs
Original file line number Diff line number Diff line change
@@ -1,81 +1 @@
use std::future::Future;

use crate::ffi;

pub struct Runtime {
pub(crate) inner: std::sync::Arc<tokio::runtime::Runtime>,
}

impl Runtime {
fn new(inner: tokio::runtime::Runtime) -> Self {
Self {
inner: std::sync::Arc::new(inner),
}
}

pub(crate) fn handle(&self) -> RuntimeHandle {
RuntimeHandle {
inner: std::sync::Arc::downgrade(&self.inner),
}
}
}

#[derive(Clone)]
pub(crate) struct RuntimeHandle {
inner: std::sync::Weak<tokio::runtime::Runtime>,
}

impl RuntimeHandle {
pub(crate) fn block_on<F: Future>(&self, future: F) -> Result<F::Output, ffi::ParamError> {
let inner = self
.inner
.upgrade()
.ok_or(ffi::ParamError::RuntimeDestroyed)?;
if tokio::runtime::Handle::try_current().is_ok() {
return Err(ffi::ParamError::RuntimeCannotBlockWithinAsync);
}
Ok(inner.block_on(future))
}

pub(crate) fn spawn<F>(&self, future: F) -> Result<(), ffi::ParamError>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
let inner = self
.inner
.upgrade()
.ok_or(ffi::ParamError::RuntimeDestroyed)?;
inner.spawn(future);
Ok(())
}
}

fn build_runtime<F>(f: F) -> std::result::Result<tokio::runtime::Runtime, std::io::Error>
where
F: Fn(&mut tokio::runtime::Builder) -> &mut tokio::runtime::Builder,
{
let mut builder = tokio::runtime::Builder::new_multi_thread();
f(&mut builder).enable_all().build()
}

pub(crate) unsafe fn runtime_create(
config: ffi::RuntimeConfig,
) -> Result<*mut crate::runtime::Runtime, ffi::ParamError> {
let num_threads = if config.num_core_threads == 0 {
num_cpus::get()
} else {
config.num_core_threads as usize
};

tracing::info!("creating runtime with {} threads", num_threads);
let runtime = build_runtime(|r| r.worker_threads(num_threads as usize))
.map_err(|_| ffi::ParamError::RuntimeCreationFailure)?;
Ok(Box::into_raw(Box::new(Runtime::new(runtime))))
}

pub(crate) unsafe fn runtime_destroy(runtime: *mut crate::runtime::Runtime) {
if !runtime.is_null() {
drop(Box::from_raw(runtime));
};
}
include!(concat!(env!("OUT_DIR"), "/runtime.rs"));
1 change: 1 addition & 0 deletions ffi/rodbus-schema/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ readme = "../README.md"
[dependencies]
oo-bindgen = { git = "https://github.com/stepfunc/oo_bindgen.git", tag = "0.3.0" }
tracing-ffi-schema = { git = "https://github.com/stepfunc/tracing-ffi.git", tag = "0.1.0" }
tokio-ffi-schema = { git = "https://github.com/stepfunc/tokio-ffi.git", tag = "0.1.0" }
2 changes: 1 addition & 1 deletion ffi/rodbus-schema/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ impl CommonDefinitions {
error_type: error_type.clone(),
nothing,
decode_level,
runtime_handle: crate::runtime::define(lib, error_type)?,
runtime_handle: tokio_ffi_schema::define(lib, error_type)?,
error_info: build_request_error(lib)?,
address_range: build_address_range(lib)?,
request_param: build_request_param(lib)?,
Expand Down
1 change: 0 additions & 1 deletion ffi/rodbus-schema/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use oo_bindgen::model::*;
mod client;
mod common;
mod decoding;
mod runtime;
mod server;

// derived from Cargo.toml
Expand Down
64 changes: 0 additions & 64 deletions ffi/rodbus-schema/src/runtime.rs

This file was deleted.