Add closure variants to OperatorFunction for capturing external state#402
Add closure variants to OperatorFunction for capturing external state#402
Conversation
|
|
Benchmark for 3c53722Click to view benchmark
|
Co-authored-by: hsluoyz <3787410+hsluoyz@users.noreply.github.com>
Co-authored-by: hsluoyz <3787410+hsluoyz@users.noreply.github.com>
Benchmark for 3c53722Click to view benchmark
|
Benchmark for 3c53722Click to view benchmark
|
|
What if the May be the best practice is to use a pool like https://docs.rs/r2d2_sqlite/latest/r2d2_sqlite/index.html? This works well with a Here is my code: use r2d2::{self, Pool};
use r2d2_sqlite::SqliteConnectionManager;
...
#[derive(Clone)]
struct AppState {
db_connection_pool: Arc<Pool<SqliteConnectionManager>>,
casbin_enforcer: Arc<Mutex<Enforcer>>,
}
impl AppState {
fn match_product_has_storages_wrapper(&mut self) {
let db_connection_pool = self.db_connection_pool.clone();
if let Ok(mut e) = self.casbin_enforcer.lock() {
e.add_function(
"matchProductHasStorages",
OperatorFunction::Arg1Closure(Arc::new(move |product_id: Dynamic| {
let product_id: u64 = product_id.as_int().unwrap_or(0) as u64;
// TODO: manage errors.
let db_connection = db_connection_pool.get().unwrap();
// TODO: manage errors.
let result = match_product_has_storages(db_connection.deref(), product_id)
.unwrap_or_default();
result.into()
})),
);
};
}
}Thanks. |
@copilot modify based on above also fix below failed CI check: |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #402 +/- ##
=========================================
- Coverage 65.54% 0 -65.55%
=========================================
Files 25 0 -25
Lines 1956 0 -1956
=========================================
- Hits 1282 0 -1282
+ Misses 674 0 -674 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
OperatorFunctionuses rawfnpointers which cannot capture environment variables, making it impossible to access database connections or app state from custom Casbin functions.Changes
Arg0ClosurethroughArg6ClosureusingArc<dyn Fn(...) -> Dynamic + Send + Sync>register_functionto handle closure variants#[derive(Clone, Copy)]to#[derive(Clone)]sinceArcdoesn't implementCopyCUSTOM_FUNCTIONS.mdwith closure usage examplesExample
Original prompt
💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.