From aa0248ef17cb0117bb69f1d9f278f995bb417f16 Mon Sep 17 00:00:00 2001 From: Timur Gordon <31495328+timurgordon@users.noreply.github.com> Date: Thu, 21 Aug 2025 14:32:24 +0200 Subject: [PATCH] move rhailib to herolib --- Cargo.toml | 1 + rhailib/.gitignore | 5 + rhailib/Cargo.toml | 34 + rhailib/README.md | 114 ++++ rhailib/_archive/dispatcher/.gitignore | 1 + rhailib/_archive/dispatcher/Cargo.toml | 24 + rhailib/_archive/dispatcher/README.md | 107 +++ rhailib/_archive/dispatcher/cmd/README.md | 157 +++++ rhailib/_archive/dispatcher/cmd/dispatcher.rs | 207 ++++++ .../_archive/dispatcher/docs/ARCHITECTURE.md | 190 ++++++ .../dispatcher/examples/timeout_example.rs | 90 +++ rhailib/_archive/dispatcher/src/lib.rs | 638 ++++++++++++++++++ rhailib/_archive/engine/Cargo.toml | 38 ++ rhailib/_archive/engine/README.md | 135 ++++ rhailib/_archive/engine/build.rs | 16 + rhailib/_archive/engine/docs/ARCHITECTURE.md | 331 +++++++++ .../examples/calendar/calendar_script.rhai | 101 +++ .../engine/examples/calendar/example.rs | 70 ++ .../_archive/engine/examples/calendar/mock.rs | 60 ++ .../engine/examples/finance/example.rs | 70 ++ .../examples/finance/finance_script.rhai | 202 ++++++ .../_archive/engine/examples/finance/mock.rs | 111 +++ .../_archive/engine/examples/flow/example.rs | 162 +++++ .../engine/examples/flow/flow_script.rhai | 111 +++ rhailib/_archive/engine/examples/flow/mock.rs | 65 ++ rhailib/_archive/engine/src/lib.rs | 305 +++++++++ rhailib/_archive/engine/src/mock_db.rs | 374 ++++++++++ rhailib/_archive/flow/flow.rs | 97 +++ rhailib/_archive/flow/flow_step.rs | 86 +++ rhailib/_archive/flow/mod.rs | 17 + rhailib/_archive/flow/orchestrated_flow.rs | 154 +++++ .../_archive/flow/orchestrated_flow_step.rs | 124 ++++ .../_archive/flow/signature_requirement.rs | 145 ++++ rhailib/_archive/orchestrator/Cargo.toml | 51 ++ rhailib/_archive/orchestrator/README.md | 320 +++++++++ .../orchestrator/examples/basic_workflow.rs | 283 ++++++++ .../orchestrator/src/interface/dispatcher.rs | 61 ++ .../orchestrator/src/interface/local.rs | 111 +++ .../orchestrator/src/interface/mod.rs | 9 + .../_archive/orchestrator/src/interface/ws.rs | 117 ++++ rhailib/_archive/orchestrator/src/lib.rs | 35 + .../_archive/orchestrator/src/orchestrator.rs | 418 ++++++++++++ rhailib/_archive/orchestrator/src/services.rs | 42 ++ rhailib/_archive/worker/.gitignore | 2 + rhailib/_archive/worker/Cargo.toml | 29 + rhailib/_archive/worker/README.md | 75 ++ rhailib/_archive/worker/cmd/README.md | 113 ++++ rhailib/_archive/worker/cmd/worker.rs | 95 +++ rhailib/_archive/worker/docs/ARCHITECTURE.md | 53 ++ rhailib/_archive/worker/src/lib.rs | 259 +++++++ rhailib/benches/simple_rhai_bench/README.md | 71 ++ .../benches/simple_rhai_bench/batch_task.lua | 46 ++ rhailib/benches/simple_rhai_bench/main.rs | 183 +++++ rhailib/docs/API_INTEGRATION_GUIDE.md | 530 +++++++++++++++ rhailib/docs/ARCHITECTURE.md | 294 ++++++++ rhailib/docs/ASYNC_IMPLEMENTATION_SUMMARY.md | 254 +++++++ rhailib/docs/ASYNC_RHAI_ARCHITECTURE.md | 460 +++++++++++++ rhailib/docs/DISPATCHER_FLOW_ARCHITECTURE.md | 367 ++++++++++ .../docs/EVENT_DRIVEN_FLOW_ARCHITECTURE.md | 443 ++++++++++++ rhailib/docs/IMPLEMENTATION_SPECIFICATION.md | 593 ++++++++++++++++ rhailib/docs/NON_BLOCKING_ASYNC_DESIGN.md | 468 +++++++++++++ .../docs/SIMPLE_NON_BLOCKING_ARCHITECTURE.md | 376 +++++++++++ rhailib/docs/TASK_LIFECYCLE_VERIFICATION.md | 73 ++ .../docs/TRUE_NON_BLOCKING_IMPLEMENTATION.md | 369 ++++++++++ .../NON_BLOCKING_PAYMENT_IMPLEMENTATION.md | 222 ++++++ rhailib/examples/README.md | 11 + rhailib/examples/access_control/README.md | 41 ++ rhailib/examples/access_control/alice.rhai | 50 ++ rhailib/examples/access_control/bob.rhai | 16 + rhailib/examples/access_control/charlie.rhai | 16 + rhailib/examples/access_control/circle.rhai | 51 ++ rhailib/examples/access_control/main.rs | 172 +++++ .../new_create_payment_intent_error.rhai | 38 ++ .../new_create_payment_intent_response.rhai | 34 + rhailib/examples/non_blocking_payment_test.rs | 190 ++++++ rhailib/examples/payment_usage_example.rhai | 108 +++ rhailib/research/repl/.gitignore | 2 + rhailib/research/repl/.rhai_repl_history.txt | 5 + rhailib/research/repl/Cargo.toml | 21 + rhailib/research/repl/README.md | 77 +++ rhailib/research/repl/docs/ARCHITECTURE.md | 53 ++ .../repl/examples/connect_and_play.rs | 198 ++++++ rhailib/research/repl/src/main.rs | 275 ++++++++ rhailib/research/rhai_engine_ui/.gitignore | 3 + rhailib/research/rhai_engine_ui/Cargo.toml | 30 + rhailib/research/rhai_engine_ui/README.md | 42 ++ rhailib/research/rhai_engine_ui/Trunk.toml | 2 + .../rhai_engine_ui/docs/ARCHITECTURE.md | 57 ++ rhailib/research/rhai_engine_ui/index.html | 15 + rhailib/research/rhai_engine_ui/src/app.rs | 388 +++++++++++ rhailib/research/rhai_engine_ui/src/main.rs | 184 +++++ rhailib/research/rhai_engine_ui/styles.css | 173 +++++ rhailib/src/derive/Cargo.toml | 11 + rhailib/src/derive/README.md | 78 +++ rhailib/src/derive/docs/ARCHITECTURE.md | 67 ++ rhailib/src/derive/src/lib.rs | 117 ++++ rhailib/src/derive/src/rhai_api.rs | 116 ++++ rhailib/src/flow/Cargo.toml | 17 + rhailib/src/flow/README.md | 110 +++ .../src/flow/examples/stripe_flow_example.rs | 90 +++ rhailib/src/flow/src/builder.rs | 108 +++ rhailib/src/flow/src/executor.rs | 243 +++++++ rhailib/src/flow/src/lib.rs | 20 + rhailib/src/flow/src/mock_api.rs | 144 ++++ rhailib/src/flow/src/state.rs | 100 +++ rhailib/src/flow/src/types.rs | 66 ++ rhailib/src/lib.rs | 8 + rhailib/src/macros/Cargo.toml | 8 + rhailib/src/macros/_archive/lib.rs | 380 +++++++++++ rhailib/src/macros/docs/ARCHITECTURE.md | 303 +++++++++ rhailib/src/macros/examples/access_control.rs | 208 ++++++ rhailib/src/macros/src/lib.rs | 352 ++++++++++ rhailib/src/monitor/Cargo.toml | 23 + rhailib/src/monitor/README.md | 67 ++ rhailib/src/monitor/cmd/main.rs | 37 + rhailib/src/monitor/docs/ARCHITECTURE.md | 61 ++ rhailib/src/monitor/src/cli_logic.rs | 104 +++ rhailib/src/monitor/src/lib.rs | 10 + rhailib/src/monitor/src/main.rs | 32 + rhailib/src/monitor/src/plot.rs | 23 + rhailib/src/monitor/src/tasks.rs | 93 +++ 121 files changed, 16412 insertions(+) create mode 100644 rhailib/.gitignore create mode 100644 rhailib/Cargo.toml create mode 100644 rhailib/README.md create mode 100644 rhailib/_archive/dispatcher/.gitignore create mode 100644 rhailib/_archive/dispatcher/Cargo.toml create mode 100644 rhailib/_archive/dispatcher/README.md create mode 100644 rhailib/_archive/dispatcher/cmd/README.md create mode 100644 rhailib/_archive/dispatcher/cmd/dispatcher.rs create mode 100644 rhailib/_archive/dispatcher/docs/ARCHITECTURE.md create mode 100644 rhailib/_archive/dispatcher/examples/timeout_example.rs create mode 100644 rhailib/_archive/dispatcher/src/lib.rs create mode 100644 rhailib/_archive/engine/Cargo.toml create mode 100644 rhailib/_archive/engine/README.md create mode 100644 rhailib/_archive/engine/build.rs create mode 100644 rhailib/_archive/engine/docs/ARCHITECTURE.md create mode 100644 rhailib/_archive/engine/examples/calendar/calendar_script.rhai create mode 100644 rhailib/_archive/engine/examples/calendar/example.rs create mode 100644 rhailib/_archive/engine/examples/calendar/mock.rs create mode 100644 rhailib/_archive/engine/examples/finance/example.rs create mode 100644 rhailib/_archive/engine/examples/finance/finance_script.rhai create mode 100644 rhailib/_archive/engine/examples/finance/mock.rs create mode 100644 rhailib/_archive/engine/examples/flow/example.rs create mode 100644 rhailib/_archive/engine/examples/flow/flow_script.rhai create mode 100644 rhailib/_archive/engine/examples/flow/mock.rs create mode 100644 rhailib/_archive/engine/src/lib.rs create mode 100644 rhailib/_archive/engine/src/mock_db.rs create mode 100644 rhailib/_archive/flow/flow.rs create mode 100644 rhailib/_archive/flow/flow_step.rs create mode 100644 rhailib/_archive/flow/mod.rs create mode 100644 rhailib/_archive/flow/orchestrated_flow.rs create mode 100644 rhailib/_archive/flow/orchestrated_flow_step.rs create mode 100644 rhailib/_archive/flow/signature_requirement.rs create mode 100644 rhailib/_archive/orchestrator/Cargo.toml create mode 100644 rhailib/_archive/orchestrator/README.md create mode 100644 rhailib/_archive/orchestrator/examples/basic_workflow.rs create mode 100644 rhailib/_archive/orchestrator/src/interface/dispatcher.rs create mode 100644 rhailib/_archive/orchestrator/src/interface/local.rs create mode 100644 rhailib/_archive/orchestrator/src/interface/mod.rs create mode 100644 rhailib/_archive/orchestrator/src/interface/ws.rs create mode 100644 rhailib/_archive/orchestrator/src/lib.rs create mode 100644 rhailib/_archive/orchestrator/src/orchestrator.rs create mode 100644 rhailib/_archive/orchestrator/src/services.rs create mode 100644 rhailib/_archive/worker/.gitignore create mode 100644 rhailib/_archive/worker/Cargo.toml create mode 100644 rhailib/_archive/worker/README.md create mode 100644 rhailib/_archive/worker/cmd/README.md create mode 100644 rhailib/_archive/worker/cmd/worker.rs create mode 100644 rhailib/_archive/worker/docs/ARCHITECTURE.md create mode 100644 rhailib/_archive/worker/src/lib.rs create mode 100644 rhailib/benches/simple_rhai_bench/README.md create mode 100644 rhailib/benches/simple_rhai_bench/batch_task.lua create mode 100644 rhailib/benches/simple_rhai_bench/main.rs create mode 100644 rhailib/docs/API_INTEGRATION_GUIDE.md create mode 100644 rhailib/docs/ARCHITECTURE.md create mode 100644 rhailib/docs/ASYNC_IMPLEMENTATION_SUMMARY.md create mode 100644 rhailib/docs/ASYNC_RHAI_ARCHITECTURE.md create mode 100644 rhailib/docs/DISPATCHER_FLOW_ARCHITECTURE.md create mode 100644 rhailib/docs/EVENT_DRIVEN_FLOW_ARCHITECTURE.md create mode 100644 rhailib/docs/IMPLEMENTATION_SPECIFICATION.md create mode 100644 rhailib/docs/NON_BLOCKING_ASYNC_DESIGN.md create mode 100644 rhailib/docs/SIMPLE_NON_BLOCKING_ARCHITECTURE.md create mode 100644 rhailib/docs/TASK_LIFECYCLE_VERIFICATION.md create mode 100644 rhailib/docs/TRUE_NON_BLOCKING_IMPLEMENTATION.md create mode 100644 rhailib/examples/NON_BLOCKING_PAYMENT_IMPLEMENTATION.md create mode 100644 rhailib/examples/README.md create mode 100644 rhailib/examples/access_control/README.md create mode 100644 rhailib/examples/access_control/alice.rhai create mode 100644 rhailib/examples/access_control/bob.rhai create mode 100644 rhailib/examples/access_control/charlie.rhai create mode 100644 rhailib/examples/access_control/circle.rhai create mode 100644 rhailib/examples/access_control/main.rs create mode 100644 rhailib/examples/flows/new_create_payment_intent_error.rhai create mode 100644 rhailib/examples/flows/new_create_payment_intent_response.rhai create mode 100644 rhailib/examples/non_blocking_payment_test.rs create mode 100644 rhailib/examples/payment_usage_example.rhai create mode 100644 rhailib/research/repl/.gitignore create mode 100644 rhailib/research/repl/.rhai_repl_history.txt create mode 100644 rhailib/research/repl/Cargo.toml create mode 100644 rhailib/research/repl/README.md create mode 100644 rhailib/research/repl/docs/ARCHITECTURE.md create mode 100644 rhailib/research/repl/examples/connect_and_play.rs create mode 100644 rhailib/research/repl/src/main.rs create mode 100644 rhailib/research/rhai_engine_ui/.gitignore create mode 100644 rhailib/research/rhai_engine_ui/Cargo.toml create mode 100644 rhailib/research/rhai_engine_ui/README.md create mode 100644 rhailib/research/rhai_engine_ui/Trunk.toml create mode 100644 rhailib/research/rhai_engine_ui/docs/ARCHITECTURE.md create mode 100644 rhailib/research/rhai_engine_ui/index.html create mode 100644 rhailib/research/rhai_engine_ui/src/app.rs create mode 100644 rhailib/research/rhai_engine_ui/src/main.rs create mode 100644 rhailib/research/rhai_engine_ui/styles.css create mode 100644 rhailib/src/derive/Cargo.toml create mode 100644 rhailib/src/derive/README.md create mode 100644 rhailib/src/derive/docs/ARCHITECTURE.md create mode 100644 rhailib/src/derive/src/lib.rs create mode 100644 rhailib/src/derive/src/rhai_api.rs create mode 100644 rhailib/src/flow/Cargo.toml create mode 100644 rhailib/src/flow/README.md create mode 100644 rhailib/src/flow/examples/stripe_flow_example.rs create mode 100644 rhailib/src/flow/src/builder.rs create mode 100644 rhailib/src/flow/src/executor.rs create mode 100644 rhailib/src/flow/src/lib.rs create mode 100644 rhailib/src/flow/src/mock_api.rs create mode 100644 rhailib/src/flow/src/state.rs create mode 100644 rhailib/src/flow/src/types.rs create mode 100644 rhailib/src/lib.rs create mode 100644 rhailib/src/macros/Cargo.toml create mode 100644 rhailib/src/macros/_archive/lib.rs create mode 100644 rhailib/src/macros/docs/ARCHITECTURE.md create mode 100644 rhailib/src/macros/examples/access_control.rs create mode 100644 rhailib/src/macros/src/lib.rs create mode 100644 rhailib/src/monitor/Cargo.toml create mode 100644 rhailib/src/monitor/README.md create mode 100644 rhailib/src/monitor/cmd/main.rs create mode 100644 rhailib/src/monitor/docs/ARCHITECTURE.md create mode 100644 rhailib/src/monitor/src/cli_logic.rs create mode 100644 rhailib/src/monitor/src/lib.rs create mode 100644 rhailib/src/monitor/src/main.rs create mode 100644 rhailib/src/monitor/src/plot.rs create mode 100644 rhailib/src/monitor/src/tasks.rs diff --git a/Cargo.toml b/Cargo.toml index b19abe4..f886f4e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,7 @@ members = [ "packages/system/process", "packages/system/virt", "rhai", + "rhailib", "herodo", "packages/clients/hetznerclient", ] diff --git a/rhailib/.gitignore b/rhailib/.gitignore new file mode 100644 index 0000000..4e23a11 --- /dev/null +++ b/rhailib/.gitignore @@ -0,0 +1,5 @@ +target +worker_rhai_temp_db +dump.rdb +.DS_Store +.env \ No newline at end of file diff --git a/rhailib/Cargo.toml b/rhailib/Cargo.toml new file mode 100644 index 0000000..f05edb1 --- /dev/null +++ b/rhailib/Cargo.toml @@ -0,0 +1,34 @@ +[package] +name = "rhailib" +version = "0.1.0" +edition = "2021" # Changed to 2021 for consistency with other crates + +[dependencies] +anyhow = "1.0" +chrono = { version = "0.4", features = ["serde"] } +env_logger = "0.10" +log = "0.4" +redis = { version = "0.25.0", features = ["tokio-comp"] } +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +tokio = { version = "1", features = ["macros", "rt-multi-thread", "time", "sync", "signal"] } +rhai = "1.21.0" +derive = { path = "src/derive" } + + +[dev-dependencies] +criterion = { version = "0.5", features = ["html_reports"] } +uuid = { version = "1.6", features = ["v4", "serde"] } # For examples like dedicated_reply_queue_demo +tempfile = "3.10" + +[[bench]] +name = "simple_rhai_bench" +harness = false + +[workspace] +members = [ + ".", # Represents the root package (rhailib) + "src/monitor", # Added the new monitor package to workspace + "src/macros", "src/dsl", "src/derive", +] +resolver = "2" # Recommended for new workspaces diff --git a/rhailib/README.md b/rhailib/README.md new file mode 100644 index 0000000..ac96b58 --- /dev/null +++ b/rhailib/README.md @@ -0,0 +1,114 @@ +# rhailib: Distributed Rhai Scripting for HeroModels + +`rhailib` provides a robust infrastructure for executing Rhai scripts in a distributed manner, primarily designed to integrate with and extend the HeroModels ecosystem. It allows for dynamic scripting capabilities, offloading computation, and enabling flexible automation. + +## Overview + +The `rhailib` system is composed of three main components working together, leveraging Redis for task queuing and state management: + +1. **Rhai Engine (`src/engine`):** + This crate is the core of the scripting capability. It provides a Rhai engine pre-configured with various HeroModels modules (e.g., Calendar, Flow, Legal). Scripts executed within this engine can interact directly with HeroModels data and logic. The `engine` is utilized by the `rhai_worker` to process tasks. + +2. **Rhai Client (`src/client`):** + This crate offers an interface for applications to submit Rhai scripts as tasks to the distributed execution system. Clients can send scripts to named Redis queues (referred to as "contexts"), optionally wait for results, and handle timeouts. + +3. **Rhai Worker (`src/worker`):** + This executable component listens to one or more Redis queues ("contexts") for incoming tasks. When a task (a Rhai script) is received, the worker fetches its details, uses the `rhai_engine` to execute the script, and then updates the task's status and results back into Redis. Multiple worker instances can be deployed to scale script execution. + +## Architecture & Workflow + +The typical workflow is as follows: + +1. **Task Submission:** An application using `rhai_dispatcher` submits a Rhai script to a specific Redis list (e.g., `rhai:queue:my_context`). Task details, including the script and status, are stored in a Redis hash. +2. **Task Consumption:** A `rhai_worker` instance, configured to listen to `rhai:queue:my_context`, picks up the task ID from the queue using a blocking pop operation. +3. **Script Execution:** The worker retrieves the script from Redis and executes it using an instance of the `rhai_engine`. This engine provides the necessary HeroModels context for the script. +4. **Result Storage:** Upon completion (or error), the worker updates the task's status (e.g., `completed`, `failed`) and stores any return value or error message in the corresponding Redis hash. +5. **Result Retrieval (Optional):** The `rhai_dispatcher` can poll the Redis hash for the task's status and retrieve the results once available. + +This architecture allows for: +- Asynchronous script execution. +- Scalable processing of Rhai scripts by running multiple workers. +- Decoupling of script submission from execution. + +## Project Structure + +The core components are organized as separate crates within the `src/` directory: + +- `src/client/`: Contains the `rhai_dispatcher` library. +- `src/engine/`: Contains the `rhai_engine` library. +- `src/worker/`: Contains the `rhai_worker` library and its executable. + +Each of these directories contains its own `README.md` file with more detailed information about its specific functionality, setup, and usage. + +## Getting Started + +To work with this project: + +1. Ensure you have Rust and Cargo installed. +2. A running Redis instance is required for the `client` and `worker` components to communicate. +3. Explore the individual README files in `src/client/`, `src/worker/`, and `src/engine/` for detailed instructions on building, configuring, and running each component. + +You can typically build all components using: +```bash +cargo build --workspace +``` +Or build and run specific examples or binaries as detailed in their respective READMEs. + +## Async API Integration + +`rhailib` includes a powerful async architecture that enables Rhai scripts to perform HTTP API calls despite Rhai's synchronous nature. This allows scripts to integrate with external services like Stripe, payment processors, and other REST/GraphQL APIs. + +### Key Features + +- **Async HTTP Support**: Make API calls from synchronous Rhai scripts +- **Multi-threaded Architecture**: Uses MPSC channels to bridge sync/async execution +- **Built-in Stripe Integration**: Complete payment processing capabilities +- **Builder Pattern APIs**: Fluent, chainable API for creating complex objects +- **Error Handling**: Graceful error handling with try/catch support +- **Environment Configuration**: Secure credential management via environment variables + +### Quick Example + +```rhai +// Configure API client +configure_stripe(STRIPE_API_KEY); + +// Create a product with pricing +let product = new_product() + .name("Premium Software License") + .description("Professional software solution") + .metadata("category", "software"); + +let product_id = product.create(); + +// Create subscription pricing +let monthly_price = new_price() + .amount(2999) // $29.99 in cents + .currency("usd") + .product(product_id) + .recurring("month"); + +let price_id = monthly_price.create(); + +// Create a subscription +let subscription = new_subscription() + .customer("cus_customer_id") + .add_price(price_id) + .trial_days(14) + .create(); +``` + +### Documentation + +- **[Async Architecture Guide](docs/ASYNC_RHAI_ARCHITECTURE.md)**: Detailed technical documentation of the async architecture, including design decisions, thread safety, and extensibility patterns. +- **[API Integration Guide](docs/API_INTEGRATION_GUIDE.md)**: Practical guide with examples for integrating external APIs, error handling patterns, and best practices. + +## Purpose + +`rhailib` aims to provide a flexible and powerful way to extend applications with custom logic written in Rhai, executed in a controlled and scalable environment. This is particularly useful for tasks such as: +- Implementing dynamic business rules. +- Automating processes with external API integration. +- Running background computations. +- Processing payments and subscriptions. +- Customizing application behavior without recompilation. +- Integrating with third-party services (Stripe, webhooks, etc.). \ No newline at end of file diff --git a/rhailib/_archive/dispatcher/.gitignore b/rhailib/_archive/dispatcher/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/rhailib/_archive/dispatcher/.gitignore @@ -0,0 +1 @@ +/target diff --git a/rhailib/_archive/dispatcher/Cargo.toml b/rhailib/_archive/dispatcher/Cargo.toml new file mode 100644 index 0000000..dab9a14 --- /dev/null +++ b/rhailib/_archive/dispatcher/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "rhai_dispatcher" +version = "0.1.0" +edition = "2021" + +[[bin]] +name = "dispatcher" +path = "cmd/dispatcher.rs" + +[dependencies] +clap = { version = "4.4", features = ["derive"] } +env_logger = "0.10" +redis = { version = "0.25.0", features = ["tokio-comp"] } +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +uuid = { version = "1.6", features = ["v4", "serde"] } +chrono = { version = "0.4", features = ["serde"] } +log = "0.4" +tokio = { version = "1", features = ["macros", "rt-multi-thread"] } # For async main in examples, and general async +colored = "2.0" + +[dev-dependencies] # For examples later +env_logger = "0.10" +rhai = "1.18.0" # For examples that might need to show engine setup diff --git a/rhailib/_archive/dispatcher/README.md b/rhailib/_archive/dispatcher/README.md new file mode 100644 index 0000000..b583c90 --- /dev/null +++ b/rhailib/_archive/dispatcher/README.md @@ -0,0 +1,107 @@ +# Rhai Client + +The `rhai-client` crate provides a fluent builder-based interface for submitting Rhai scripts to a distributed task execution system over Redis. It enables applications to offload Rhai script execution to one or more worker services and await the results. + +## Features + +- **Fluent Builder API**: A `RhaiDispatcherBuilder` for easy client configuration and a `PlayRequestBuilder` for constructing and submitting script execution requests. +- **Asynchronous Operations**: Built with `tokio` for non-blocking I/O. +- **Request-Reply Pattern**: Submits tasks and awaits results on a dedicated reply queue, eliminating the need for polling. +- **Configurable Timeouts**: Set timeouts for how long the client should wait for a task to complete. +- **Direct-to-Worker-Queue Submission**: Tasks are sent to a queue named after the `worker_id`, allowing for direct and clear task routing. +- **Manual Status Check**: Provides an option to manually check the status of a task by its ID. + +## Core Components + +- **`RhaiDispatcherBuilder`**: A builder to construct a `RhaiDispatcher`. Requires a `caller_id` and Redis URL. +- **`RhaiDispatcher`**: The main client for interacting with the task system. It's used to create `PlayRequestBuilder` instances. +- **`PlayRequestBuilder`**: A fluent builder for creating and dispatching a script execution request. You can set: + - `worker_id`: The ID of the worker queue to send the task to. + - `script` or `script_path`: The Rhai script to execute. + - `request_id`: An optional unique ID for the request. + - `timeout`: How long to wait for a result. +- **Submission Methods**: + - `submit()`: Submits the request and returns immediately (fire-and-forget). + - `await_response()`: Submits the request and waits for the result or a timeout. +- **`RhaiTaskDetails`**: A struct representing the details of a task, including its script, status (`pending`, `processing`, `completed`, `error`), output, and error messages. +- **`RhaiDispatcherError`**: An enum for various errors, such as Redis errors, serialization issues, or task timeouts. + +## How It Works + +1. A `RhaiDispatcher` is created using the `RhaiDispatcherBuilder`, configured with a `caller_id` and Redis URL. +2. A `PlayRequestBuilder` is created from the client. +3. The script, `worker_id`, and an optional `timeout` are configured on the builder. +4. When `await_response()` is called: + a. A unique `task_id` (UUID v4) is generated. + b. Task details are stored in a Redis hash with a key like `rhailib:`. + c. The `task_id` is pushed to the worker's queue, named `rhailib:`. + d. The client performs a blocking pop (`BLPOP`) on a dedicated reply queue (`rhailib:reply:`), waiting for the worker to send the result. +5. A `rhai-worker` process, listening on the `rhailib:` queue, picks up the task, executes it, and pushes the final `RhaiTaskDetails` to the reply queue. +6. The client receives the result from the reply queue and returns it to the caller. + +## Prerequisites + +- A running Redis instance accessible by the client and the worker services. + +## Usage Example + +The following example demonstrates how to build a client, submit a script, and wait for the result. + +```rust +use rhai_dispatcher::{RhaiDispatcherBuilder, RhaiDispatcherError}; +use std::time::Duration; + +#[tokio::main] +async fn main() -> Result<(), Box> { + env_logger::init(); + + // 1. Build the client + let client = RhaiDispatcherBuilder::new() + .caller_id("my-app-instance-1") + .redis_url("redis://127.0.0.1/") + .build()?; + + // 2. Define the script and target worker + let script = r#" "Hello, " + worker_id + "!" "#; + let worker_id = "worker-1"; + + // 3. Use the PlayRequestBuilder to configure and submit the request + let result = client + .new_play_request() + .worker_id(worker_id) + .script(script) + .timeout(Duration::from_secs(5)) + .await_response() + .await; + + match result { + Ok(details) => { + log::info!("Task completed successfully!"); + log::info!("Status: {}", details.status); + if let Some(output) = details.output { + log::info!("Output: {}", output); + } + } + Err(RhaiDispatcherError::Timeout(task_id)) => { + log::error!("Task {} timed out.", task_id); + } + Err(e) => { + log::error!("An unexpected error occurred: {}", e); + } + } + + Ok(()) +} +``` + +Refer to the `examples/` directory for more specific use cases, such as `timeout_example.rs` which tests the timeout mechanism. + +## Building and Running Examples + +To run an example (e.g., `timeout_example`): + +```bash +cd src/client # (or wherever this client's Cargo.toml is) +cargo run --example timeout_example +``` +Ensure a Redis server is running and accessible at `redis://127.0.0.1/`. diff --git a/rhailib/_archive/dispatcher/cmd/README.md b/rhailib/_archive/dispatcher/cmd/README.md new file mode 100644 index 0000000..d297055 --- /dev/null +++ b/rhailib/_archive/dispatcher/cmd/README.md @@ -0,0 +1,157 @@ +# Rhai Client Binary + +A command-line client for executing Rhai scripts on remote workers via Redis. + +## Binary: `client` + +### Installation + +Build the binary: +```bash +cargo build --bin client --release +``` + +### Usage + +```bash +# Basic usage - requires caller and circle keys +client --caller-key --circle-key + +# Execute inline script +client -c -k --script "print('Hello World!')" + +# Execute script from file +client -c -k --file script.rhai + +# Use specific worker (defaults to circle key) +client -c -k -w --script "2 + 2" + +# Custom Redis and timeout +client -c -k --redis-url redis://localhost:6379/1 --timeout 60 + +# Remove timestamps from logs +client -c -k --no-timestamp + +# Increase verbosity +client -c -k -v --script "debug_info()" +``` + +### Command-Line Options + +| Option | Short | Default | Description | +|--------|-------|---------|-------------| +| `--caller-key` | `-c` | **Required** | Caller public key (your identity) | +| `--circle-key` | `-k` | **Required** | Circle public key (execution context) | +| `--worker-key` | `-w` | `circle-key` | Worker public key (target worker) | +| `--redis-url` | `-r` | `redis://localhost:6379` | Redis connection URL | +| `--script` | `-s` | | Rhai script to execute | +| `--file` | `-f` | | Path to Rhai script file | +| `--timeout` | `-t` | `30` | Timeout for script execution (seconds) | +| `--no-timestamp` | | `false` | Remove timestamps from log output | +| `--verbose` | `-v` | | Increase verbosity (stackable) | + +### Execution Modes + +#### Inline Script Execution +```bash +# Execute a simple calculation +client -c caller_123 -k circle_456 -s "let result = 2 + 2; print(result);" + +# Execute with specific worker +client -c caller_123 -k circle_456 -w worker_789 -s "get_user_data()" +``` + +#### Script File Execution +```bash +# Execute script from file +client -c caller_123 -k circle_456 -f examples/data_processing.rhai + +# Execute with custom timeout +client -c caller_123 -k circle_456 -f long_running_script.rhai -t 120 +``` + +#### Interactive Mode +```bash +# Enter interactive REPL mode (when no script or file provided) +client -c caller_123 -k circle_456 + +# Interactive mode with verbose logging +client -c caller_123 -k circle_456 -v --no-timestamp +``` + +### Interactive Mode + +When no script (`-s`) or file (`-f`) is provided, the client enters interactive mode: + +``` +🔗 Starting Rhai Client +📋 Configuration: + Caller Key: caller_123 + Circle Key: circle_456 + Worker Key: circle_456 + Redis URL: redis://localhost:6379 + Timeout: 30s + +✅ Connected to Redis at redis://localhost:6379 +🎮 Entering interactive mode +Type Rhai scripts and press Enter to execute. Type 'exit' or 'quit' to close. +rhai> let x = 42; print(x); +Status: completed +Output: 42 +rhai> exit +👋 Goodbye! +``` + +### Configuration Examples + +#### Development Usage +```bash +# Simple development client +client -c dev_user -k dev_circle + +# Development with clean logs +client -c dev_user -k dev_circle --no-timestamp -v +``` + +#### Production Usage +```bash +# Production client with specific worker +client \ + --caller-key prod_user_123 \ + --circle-key prod_circle_456 \ + --worker-key prod_worker_789 \ + --redis-url redis://redis-cluster:6379/0 \ + --timeout 300 \ + --file production_script.rhai +``` + +#### Batch Processing +```bash +# Process multiple scripts +for script in scripts/*.rhai; do + client -c batch_user -k batch_circle -f "$script" --no-timestamp +done +``` + +### Key Concepts + +- **Caller Key**: Your identity - used for authentication and tracking +- **Circle Key**: Execution context - defines the environment/permissions +- **Worker Key**: Target worker - which worker should execute the script (defaults to circle key) + +### Error Handling + +The client provides clear error messages for: +- Missing required keys +- Redis connection failures +- Script execution timeouts +- Worker unavailability +- Script syntax errors + +### Dependencies + +- `rhai_dispatcher`: Core client library for Redis-based script execution +- `redis`: Redis client for task queue communication +- `clap`: Command-line argument parsing +- `env_logger`: Logging infrastructure +- `tokio`: Async runtime \ No newline at end of file diff --git a/rhailib/_archive/dispatcher/cmd/dispatcher.rs b/rhailib/_archive/dispatcher/cmd/dispatcher.rs new file mode 100644 index 0000000..a26be04 --- /dev/null +++ b/rhailib/_archive/dispatcher/cmd/dispatcher.rs @@ -0,0 +1,207 @@ +use clap::Parser; +use rhai_dispatcher::{RhaiDispatcher, RhaiDispatcherBuilder}; +use log::{error, info}; +use colored::Colorize; +use std::io::{self, Write}; +use std::time::Duration; + +#[derive(Parser, Debug)] +#[command(author, version, about = "Rhai Client - Script execution client", long_about = None)] +struct Args { + /// Caller public key (caller ID) + #[arg(short = 'c', long = "caller-key", help = "Caller public key (your identity)")] + caller_id: String, + + /// Circle public key (context ID) + #[arg(short = 'k', long = "circle-key", help = "Circle public key (execution context)")] + context_id: String, + + /// Worker public key (defaults to circle public key if not provided) + #[arg(short = 'w', long = "worker-key", help = "Worker public key (defaults to circle key)")] + worker_id: String, + + /// Redis URL + #[arg(short, long, default_value = "redis://localhost:6379", help = "Redis connection URL")] + redis_url: String, + + /// Rhai script to execute + #[arg(short, long, help = "Rhai script to execute")] + script: Option, + + /// Path to Rhai script file + #[arg(short, long, help = "Path to Rhai script file")] + file: Option, + + /// Timeout for script execution (in seconds) + #[arg(short, long, default_value = "30", help = "Timeout for script execution in seconds")] + timeout: u64, + + /// Increase verbosity (can be used multiple times) + #[arg(short, long, action = clap::ArgAction::Count, help = "Increase verbosity (-v for debug, -vv for trace)")] + verbose: u8, + + /// Disable timestamps in log output + #[arg(long, help = "Remove timestamps from log output")] + no_timestamp: bool, +} + +#[tokio::main] +async fn main() -> Result<(), Box> { + let args = Args::parse(); + + // Configure logging based on verbosity level + let log_config = match args.verbose { + 0 => "warn,rhai_dispatcher=warn", + 1 => "info,rhai_dispatcher=info", + 2 => "debug,rhai_dispatcher=debug", + _ => "trace,rhai_dispatcher=trace", + }; + + std::env::set_var("RUST_LOG", log_config); + + // Configure env_logger with or without timestamps + if args.no_timestamp { + env_logger::Builder::from_default_env() + .format_timestamp(None) + .init(); + } else { + env_logger::init(); + } + + if args.verbose > 0 { + info!("🔗 Starting Rhai Dispatcher"); + info!("📋 Configuration:"); + info!(" Caller ID: {}", args.caller_id); + info!(" Context ID: {}", args.context_id); + info!(" Worker ID: {}", args.worker_id); + info!(" Redis URL: {}", args.redis_url); + info!(" Timeout: {}s", args.timeout); + info!(""); + } + + // Create the Rhai client + let client = RhaiDispatcherBuilder::new() + .caller_id(&args.caller_id) + .worker_id(&args.worker_id) + .context_id(&args.context_id) + .redis_url(&args.redis_url) + .build()?; + + if args.verbose > 0 { + info!("✅ Connected to Redis at {}", args.redis_url); + } + + // Determine execution mode + if let Some(script_content) = args.script { + // Execute inline script + if args.verbose > 0 { + info!("📜 Executing inline script"); + } + execute_script(&client, script_content, args.timeout).await?; + } else if let Some(file_path) = args.file { + // Execute script from file + if args.verbose > 0 { + info!("📁 Loading script from file: {}", file_path); + } + let script_content = std::fs::read_to_string(&file_path) + .map_err(|e| format!("Failed to read script file '{}': {}", file_path, e))?; + execute_script(&client, script_content, args.timeout).await?; + } else { + // Interactive mode + info!("🎮 Entering interactive mode"); + info!("Type Rhai scripts and press Enter to execute. Type 'exit' or 'quit' to close."); + run_interactive_mode(&client, args.timeout, args.verbose).await?; + } + + Ok(()) +} + +async fn execute_script( + client: &RhaiDispatcher, + script: String, + timeout_secs: u64, +) -> Result<(), Box> { + info!("⚡ Executing script: {:.50}...", script); + + let timeout = Duration::from_secs(timeout_secs); + + match client + .new_play_request() + .script(&script) + .timeout(timeout) + .await_response() + .await + { + Ok(result) => { + info!("✅ Script execution completed"); + println!("Status: {}", result.status); + if let Some(output) = result.output { + println!("Output: {}", output); + } + if let Some(error) = result.error { + println!("Error: {}", error); + } + } + Err(e) => { + error!("❌ Script execution failed: {}", e); + return Err(Box::new(e)); + } + } + + Ok(()) +} + +async fn run_interactive_mode( + client: &RhaiDispatcher, + timeout_secs: u64, + verbose: u8, +) -> Result<(), Box> { + let timeout = Duration::from_secs(timeout_secs); + + loop { + print!("rhai> "); + io::stdout().flush()?; + + let mut input = String::new(); + io::stdin().read_line(&mut input)?; + + let input = input.trim(); + + if input.is_empty() { + continue; + } + + if input == "exit" || input == "quit" { + info!("👋 Goodbye!"); + break; + } + + if verbose > 0 { + info!("⚡ Executing: {}", input); + } + + match client + .new_play_request() + .script(input) + .timeout(timeout) + .await_response() + .await + { + Ok(result) => { + if let Some(output) = result.output { + println!("{}", output.color("green")); + } + if let Some(error) = result.error { + println!("{}", format!("error: {}", error).color("red")); + } + } + Err(e) => { + println!("{}", format!("error: {}", e).red()); + } + } + + println!(); // Add blank line for readability + } + + Ok(()) +} \ No newline at end of file diff --git a/rhailib/_archive/dispatcher/docs/ARCHITECTURE.md b/rhailib/_archive/dispatcher/docs/ARCHITECTURE.md new file mode 100644 index 0000000..4ceecd4 --- /dev/null +++ b/rhailib/_archive/dispatcher/docs/ARCHITECTURE.md @@ -0,0 +1,190 @@ +# Architecture of the `rhai_dispatcher` Crate + +The `rhai_dispatcher` crate provides a Redis-based client library for submitting Rhai scripts to distributed worker services and awaiting their execution results. It implements a request-reply pattern using Redis as the message broker. + +## Core Architecture + +The client follows a builder pattern design with clear separation of concerns: + +```mermaid +graph TD + A[RhaiDispatcherBuilder] --> B[RhaiDispatcher] + B --> C[PlayRequestBuilder] + C --> D[PlayRequest] + D --> E[Redis Task Queue] + E --> F[Worker Service] + F --> G[Redis Reply Queue] + G --> H[Client Response] + + subgraph "Client Components" + A + B + C + D + end + + subgraph "Redis Infrastructure" + E + G + end + + subgraph "External Services" + F + end +``` + +## Key Components + +### 1. RhaiDispatcherBuilder + +A builder pattern implementation for constructing `RhaiDispatcher` instances with proper configuration validation. + +**Responsibilities:** +- Configure Redis connection URL +- Set caller ID for task attribution +- Validate configuration before building client + +**Key Methods:** +- `caller_id(id: &str)` - Sets the caller identifier +- `redis_url(url: &str)` - Configures Redis connection +- `build()` - Creates the final `RhaiDispatcher` instance + +### 2. RhaiDispatcher + +The main client interface that manages Redis connections and provides factory methods for creating play requests. + +**Responsibilities:** +- Maintain Redis connection pool +- Provide factory methods for request builders +- Handle low-level Redis operations +- Manage task status queries + +**Key Methods:** +- `new_play_request()` - Creates a new `PlayRequestBuilder` +- `get_task_status(task_id)` - Queries task status from Redis +- Internal methods for Redis operations + +### 3. PlayRequestBuilder + +A fluent builder for constructing and submitting script execution requests. + +**Responsibilities:** +- Configure script execution parameters +- Handle script loading from files or strings +- Manage request timeouts +- Provide submission methods (fire-and-forget vs await-response) + +**Key Methods:** +- `worker_id(id: &str)` - Target worker queue (determines which worker processes the task) +- `context_id(id: &str)` - Target context ID (determines execution context/circle) +- `script(content: &str)` - Set script content directly +- `script_path(path: &str)` - Load script from file +- `timeout(duration: Duration)` - Set execution timeout +- `submit()` - Fire-and-forget submission +- `await_response()` - Submit and wait for result + +**Architecture Note:** The decoupling of `worker_id` and `context_id` allows a single worker to process tasks for multiple contexts (circles), providing greater deployment flexibility. + +### 4. Data Structures + +#### RhaiTaskDetails +Represents the complete state of a task throughout its lifecycle. + +```rust +pub struct RhaiTaskDetails { + pub task_id: String, + pub script: String, + pub status: String, // "pending", "processing", "completed", "error" + pub output: Option, + pub error: Option, + pub created_at: DateTime, + pub updated_at: DateTime, + pub caller_id: String, +} +``` + +#### RhaiDispatcherError +Comprehensive error handling for various failure scenarios: +- `RedisError` - Redis connection/operation failures +- `SerializationError` - JSON serialization/deserialization issues +- `Timeout` - Task execution timeouts +- `TaskNotFound` - Missing tasks after submission + +## Communication Protocol + +### Task Submission Flow + +1. **Task Creation**: Client generates unique UUID for task identification +2. **Task Storage**: Task details stored in Redis hash: `rhailib:` +3. **Queue Submission**: Task ID pushed to worker queue: `rhailib:` +4. **Reply Queue Setup**: Client listens on: `rhailib:reply:` + +### Redis Key Patterns + +- **Task Storage**: `rhailib:` (Redis Hash) +- **Worker Queues**: `rhailib:` (Redis List) +- **Reply Queues**: `rhailib:reply:` (Redis List) + +### Message Flow Diagram + +```mermaid +sequenceDiagram + participant C as Client + participant R as Redis + participant W as Worker + + C->>R: HSET rhailib:task_id (task details) + C->>R: LPUSH rhailib:worker_id task_id + C->>R: BLPOP rhailib:reply:task_id (blocking) + + W->>R: BRPOP rhailib:worker_id (blocking) + W->>W: Execute Rhai Script + W->>R: LPUSH rhailib:reply:task_id (result) + + R->>C: Return result from BLPOP + C->>R: DEL rhailib:reply:task_id (cleanup) +``` + +## Concurrency and Async Design + +The client is built on `tokio` for asynchronous operations: + +- **Connection Pooling**: Uses Redis multiplexed connections for efficiency +- **Non-blocking Operations**: All Redis operations are async +- **Timeout Handling**: Configurable timeouts with proper cleanup +- **Error Propagation**: Comprehensive error handling with context + +## Configuration and Deployment + +### Prerequisites +- Redis server accessible to both client and workers +- Proper network connectivity between components +- Sufficient Redis memory for task storage + +### Configuration Options +- **Redis URL**: Connection string for Redis instance +- **Caller ID**: Unique identifier for client instance +- **Timeouts**: Per-request timeout configuration +- **Worker Targeting**: Direct worker queue addressing + +## Security Considerations + +- **Task Isolation**: Each task uses unique identifiers +- **Queue Separation**: Worker-specific queues prevent cross-contamination +- **Cleanup**: Automatic cleanup of reply queues after completion +- **Error Handling**: Secure error propagation without sensitive data leakage + +## Performance Characteristics + +- **Scalability**: Horizontal scaling through multiple worker instances +- **Throughput**: Limited by Redis performance and network latency +- **Memory Usage**: Efficient with connection pooling and cleanup +- **Latency**: Low latency for local Redis deployments + +## Integration Points + +The client integrates with: +- **Worker Services**: Via Redis queue protocol +- **Monitoring Systems**: Through structured logging +- **Application Code**: Via builder pattern API +- **Configuration Systems**: Through environment variables and builders \ No newline at end of file diff --git a/rhailib/_archive/dispatcher/examples/timeout_example.rs b/rhailib/_archive/dispatcher/examples/timeout_example.rs new file mode 100644 index 0000000..3948696 --- /dev/null +++ b/rhailib/_archive/dispatcher/examples/timeout_example.rs @@ -0,0 +1,90 @@ +use log::info; +use rhai_dispatcher::{RhaiDispatcherBuilder, RhaiDispatcherError}; +use std::time::{Duration, Instant}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + env_logger::builder() + .filter_level(log::LevelFilter::Info) + .init(); + + // Build the client using the new builder pattern + let client = RhaiDispatcherBuilder::new() + .caller_id("timeout-example-runner") + .redis_url("redis://127.0.0.1/") + .build()?; + info!("RhaiDispatcher created."); + + let script_content = r#" + // This script will never be executed by a worker because the recipient does not exist. + let x = 10; + let y = x + 32; + y + "#; + + // The worker_id points to a worker queue that doesn't have a worker. + let non_existent_recipient = "non_existent_worker_for_timeout_test"; + let very_short_timeout = Duration::from_secs(2); + + info!( + "Submitting script to non-existent recipient '{}' with a timeout of {:?}...", + non_existent_recipient, very_short_timeout + ); + + let start_time = Instant::now(); + + // Use the new PlayRequestBuilder + let result = client + .new_play_request() + .worker_id(non_existent_recipient) + .script(script_content) + .timeout(very_short_timeout) + .await_response() + .await; + + match result { + Ok(details) => { + log::error!( + "Timeout Example FAILED: Expected a timeout, but got Ok: {:?}", + details + ); + Err("Expected timeout, but task completed successfully.".into()) + } + Err(e) => { + let elapsed = start_time.elapsed(); + info!("Timeout Example: Received error as expected: {}", e); + info!("Elapsed time: {:?}", elapsed); + + match e { + RhaiDispatcherError::Timeout(task_id) => { + info!("Timeout Example PASSED: Correctly received RhaiDispatcherError::Timeout for task_id: {}", task_id); + // Ensure the elapsed time is close to the timeout duration + // Allow for some buffer for processing + assert!( + elapsed >= very_short_timeout + && elapsed < very_short_timeout + Duration::from_secs(1), + "Elapsed time {:?} should be close to timeout {:?}", + elapsed, + very_short_timeout + ); + info!( + "Elapsed time {:?} is consistent with timeout duration {:?}.", + elapsed, very_short_timeout + ); + Ok(()) + } + other_error => { + log::error!( + "Timeout Example FAILED: Expected RhaiDispatcherError::Timeout, but got other error: {:?}", + other_error + ); + Err(format!( + "Expected RhaiDispatcherError::Timeout, got other error: {:?}", + other_error + ) + .into()) + } + } + } + } +} diff --git a/rhailib/_archive/dispatcher/src/lib.rs b/rhailib/_archive/dispatcher/src/lib.rs new file mode 100644 index 0000000..2f19848 --- /dev/null +++ b/rhailib/_archive/dispatcher/src/lib.rs @@ -0,0 +1,638 @@ +//! # Rhai Client Library +//! +//! A Redis-based client library for submitting Rhai scripts to distributed worker services +//! and awaiting their execution results. This crate implements a request-reply pattern +//! using Redis as the message broker. +//! +//! ## Quick Start +//! +//! ```rust +//! use rhai_dispatcher::{RhaiDispatcherBuilder, RhaiDispatcherError}; +//! use std::time::Duration; +//! +//! #[tokio::main] +//! async fn main() -> Result<(), Box> { +//! // Build the client +//! let client = RhaiDispatcherBuilder::new() +//! .caller_id("my-app-instance-1") +//! .redis_url("redis://127.0.0.1/") +//! .build()?; +//! +//! // Submit a script and await the result +//! let result = client +//! .new_play_request() +//! .worker_id("worker-1") +//! .script(r#""Hello, World!""#) +//! .timeout(Duration::from_secs(5)) +//! .await_response() +//! .await?; +//! +//! println!("Result: {:?}", result); +//! Ok(()) +//! } +//! ``` + +use chrono::Utc; +use log::{debug, error, info, warn}; // Added error +use redis::AsyncCommands; +use serde::{Deserialize, Serialize}; +use std::time::Duration; // Duration is still used, Instant and sleep were removed +use uuid::Uuid; + +/// Redis namespace prefix for all rhailib-related keys +const NAMESPACE_PREFIX: &str = "rhailib:"; + +/// Represents the complete details and state of a Rhai task execution. +/// +/// This structure contains all information about a task throughout its lifecycle, +/// from submission to completion. It's used for both storing task state in Redis +/// and returning results to clients. +/// +/// # Fields +/// +/// * `task_id` - Unique identifier for the task (UUID) +/// * `script` - The Rhai script content to execute +/// * `status` - Current execution status: "pending", "processing", "completed", or "error" +/// * `output` - Script execution output (if successful) +/// * `error` - Error message (if execution failed) +/// * `created_at` - Timestamp when the task was created +/// * `updated_at` - Timestamp when the task was last modified +/// * `caller_id` - Identifier of the client that submitted the task +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct RhaiTaskDetails { + #[serde(rename = "taskId")] // Ensure consistent naming with other fields + pub task_id: String, + pub script: String, + pub status: String, // "pending", "processing", "completed", "error" + // client_rpc_id: Option is removed. + // Worker responses should ideally not include it, or Serde will ignore unknown fields by default. + pub output: Option, + pub error: Option, // Renamed from error_message for consistency + #[serde(rename = "createdAt")] + pub created_at: chrono::DateTime, + #[serde(rename = "updatedAt")] + pub updated_at: chrono::DateTime, + #[serde(rename = "callerId")] + pub caller_id: String, + #[serde(rename = "contextId")] + pub context_id: String, + #[serde(rename = "workerId")] + pub worker_id: String, +} + +/// Comprehensive error type for all possible failures in the Rhai client. +/// +/// This enum covers all error scenarios that can occur during client operations, +/// from Redis connectivity issues to task execution timeouts. +#[derive(Debug)] +pub enum RhaiDispatcherError { + /// Redis connection or operation error + RedisError(redis::RedisError), + /// JSON serialization/deserialization error + SerializationError(serde_json::Error), + /// Task execution timeout - contains the task_id that timed out + Timeout(String), + /// Task not found after submission - contains the task_id (rare occurrence) + TaskNotFound(String), + /// Context ID is missing + ContextIdMissing, +} + +impl From for RhaiDispatcherError { + fn from(err: redis::RedisError) -> Self { + RhaiDispatcherError::RedisError(err) + } +} + +impl From for RhaiDispatcherError { + fn from(err: serde_json::Error) -> Self { + RhaiDispatcherError::SerializationError(err) + } +} + +impl std::fmt::Display for RhaiDispatcherError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + RhaiDispatcherError::RedisError(e) => write!(f, "Redis error: {}", e), + RhaiDispatcherError::SerializationError(e) => write!(f, "Serialization error: {}", e), + RhaiDispatcherError::Timeout(task_id) => { + write!(f, "Timeout waiting for task {} to complete", task_id) + } + RhaiDispatcherError::TaskNotFound(task_id) => { + write!(f, "Task {} not found after submission", task_id) + } + RhaiDispatcherError::ContextIdMissing => { + write!(f, "Context ID is missing") + } + } + } +} + +impl std::error::Error for RhaiDispatcherError {} + +/// The main client for interacting with the Rhai task execution system. +/// +/// This client manages Redis connections and provides factory methods for creating +/// script execution requests. It maintains a caller ID for task attribution and +/// handles all low-level Redis operations. +/// +/// # Example +/// +/// ```rust +/// use rhai_dispatcher::RhaiDispatcherBuilder; +/// +/// let client = RhaiDispatcherBuilder::new() +/// .caller_id("my-service") +/// .redis_url("redis://localhost/") +/// .build()?; +/// ``` +pub struct RhaiDispatcher { + redis_client: redis::Client, + caller_id: String, + worker_id: String, + context_id: String, +} + +/// Builder for constructing `RhaiDispatcher` instances with proper configuration. +/// +/// This builder ensures that all required configuration is provided before +/// creating a client instance. It validates the configuration and provides +/// sensible defaults where appropriate. +/// +/// # Required Configuration +/// +/// - `caller_id`: A unique identifier for this client instance +/// +/// # Optional Configuration +/// +/// - `redis_url`: Redis connection URL (defaults to "redis://127.0.0.1/") +pub struct RhaiDispatcherBuilder { + redis_url: Option, + caller_id: String, + worker_id: String, + context_id: String, +} + +impl RhaiDispatcherBuilder { + /// Creates a new `RhaiDispatcherBuilder` with default settings. + /// + /// The builder starts with no Redis URL (will default to "redis://127.0.0.1/") + /// and an empty caller ID (which must be set before building). + pub fn new() -> Self { + Self { + redis_url: None, + caller_id: "".to_string(), + worker_id: "".to_string(), + context_id: "".to_string(), + } + } + + /// Sets the caller ID for this client instance. + /// + /// The caller ID is used to identify which client submitted a task and is + /// included in task metadata. This is required and the build will fail if + /// not provided. + /// + /// # Arguments + /// + /// * `caller_id` - A unique identifier for this client instance + pub fn caller_id(mut self, caller_id: &str) -> Self { + self.caller_id = caller_id.to_string(); + self + } + /// Sets the circle ID for this client instance. + /// + /// The circle ID is used to identify which circle's context a task should be executed in. + /// This is required at the time the client dispatches a script, but can be set on construction or on script dispatch. + /// + /// # Arguments + /// + /// * `context_id` - A unique identifier for this client instance + pub fn context_id(mut self, context_id: &str) -> Self { + self.context_id = context_id.to_string(); + self + } + + /// Sets the worker ID for this client instance. + /// + /// The worker ID is used to identify which worker a task should be executed on. + /// This is required at the time the client dispatches a script, but can be set on construction or on script dispatch. + /// + /// # Arguments + /// + /// * `worker_id` - A unique identifier for this client instance + pub fn worker_id(mut self, worker_id: &str) -> Self { + self.worker_id = worker_id.to_string(); + self + } + + /// Sets the Redis connection URL. + /// + /// If not provided, defaults to "redis://127.0.0.1/". + /// + /// # Arguments + /// + /// * `url` - Redis connection URL (e.g., "redis://localhost:6379/0") + pub fn redis_url(mut self, url: &str) -> Self { + self.redis_url = Some(url.to_string()); + self + } + + /// Builds the final `RhaiDispatcher` instance. + /// + /// This method validates the configuration and creates the Redis client. + /// It will return an error if the caller ID is empty or if the Redis + /// connection cannot be established. + /// + /// # Returns + /// + /// * `Ok(RhaiDispatcher)` - Successfully configured client + /// * `Err(RhaiDispatcherError)` - Configuration or connection error + pub fn build(self) -> Result { + let url = self + .redis_url + .unwrap_or_else(|| "redis://127.0.0.1/".to_string()); + let client = redis::Client::open(url)?; + Ok(RhaiDispatcher { + redis_client: client, + caller_id: self.caller_id, + worker_id: self.worker_id, + context_id: self.context_id, + }) + } +} + +/// Representation of a script execution request. +/// +/// This structure contains all the information needed to execute a Rhai script +/// on a worker service, including the script content, target worker, and timeout. +#[derive(Debug, Clone)] +pub struct PlayRequest { + pub id: String, + pub worker_id: String, + pub context_id: String, + pub script: String, + pub timeout: Duration, +} + +/// Builder for constructing and submitting script execution requests. +/// +/// This builder provides a fluent interface for configuring script execution +/// parameters and offers two submission modes: fire-and-forget (`submit()`) +/// and request-reply (`await_response()`). +/// +/// # Example +/// +/// ```rust +/// use std::time::Duration; +/// +/// let result = client +/// .new_play_request() +/// .worker_id("worker-1") +/// .script(r#"print("Hello, World!");"#) +/// .timeout(Duration::from_secs(30)) +/// .await_response() +/// .await?; +/// ``` +pub struct PlayRequestBuilder<'a> { + client: &'a RhaiDispatcher, + request_id: String, + worker_id: String, + context_id: String, + caller_id: String, + script: String, + timeout: Duration, + retries: u32, +} + +impl<'a> PlayRequestBuilder<'a> { + pub fn new(client: &'a RhaiDispatcher) -> Self { + Self { + client, + request_id: "".to_string(), + worker_id: client.worker_id.clone(), + context_id: client.context_id.clone(), + caller_id: client.caller_id.clone(), + script: "".to_string(), + timeout: Duration::from_secs(5), + retries: 0, + } + } + + pub fn request_id(mut self, request_id: &str) -> Self { + self.request_id = request_id.to_string(); + self + } + + pub fn worker_id(mut self, worker_id: &str) -> Self { + self.worker_id = worker_id.to_string(); + self + } + + pub fn context_id(mut self, context_id: &str) -> Self { + self.context_id = context_id.to_string(); + self + } + + pub fn script(mut self, script: &str) -> Self { + self.script = script.to_string(); + self + } + + pub fn script_path(mut self, script_path: &str) -> Self { + self.script = std::fs::read_to_string(script_path).unwrap(); + self + } + + pub fn timeout(mut self, timeout: Duration) -> Self { + self.timeout = timeout; + self + } + + pub fn build(self) -> Result { + let request_id = if self.request_id.is_empty() { + // Generate a UUID for the request_id + Uuid::new_v4().to_string() + } else { + self.request_id.clone() + }; + + if self.context_id.is_empty() { + return Err(RhaiDispatcherError::ContextIdMissing); + } + + if self.caller_id.is_empty() { + return Err(RhaiDispatcherError::ContextIdMissing); + } + + let play_request = PlayRequest { + id: request_id, + worker_id: self.worker_id.clone(), + context_id: self.context_id.clone(), + script: self.script.clone(), + timeout: self.timeout, + }; + Ok(play_request) + } + + pub async fn submit(self) -> Result<(), RhaiDispatcherError> { + // Build the request and submit using self.client + println!( + "Submitting request {} with timeout {:?}", + self.request_id, self.timeout + ); + self.client.submit_play_request(&self.build()?).await?; + Ok(()) + } + + pub async fn await_response(self) -> Result { + // Build the request and submit using self.client + let result = self + .client + .submit_play_request_and_await_result(&self.build()?) + .await; + result + } +} + +impl RhaiDispatcher { + pub fn new_play_request(&self) -> PlayRequestBuilder { + PlayRequestBuilder::new(self) + } + + // Internal helper to submit script details and push to work queue + async fn submit_play_request_using_connection( + &self, + conn: &mut redis::aio::MultiplexedConnection, + play_request: &PlayRequest, + ) -> Result<(), RhaiDispatcherError> { + let now = Utc::now(); + + let task_key = format!("{}{}", NAMESPACE_PREFIX, play_request.id); + + let worker_queue_key = format!( + "{}{}", + NAMESPACE_PREFIX, + play_request.worker_id.replace(" ", "_").to_lowercase() + ); + + debug!( + "Submitting play request: {} to worker: {} with namespace prefix: {}", + play_request.id, play_request.worker_id, NAMESPACE_PREFIX + ); + + let hset_args: Vec<(String, String)> = vec![ + ("taskId".to_string(), play_request.id.to_string()), // Add taskId + ("script".to_string(), play_request.script.clone()), // script is moved here + ("callerId".to_string(), self.caller_id.clone()), // script is moved here + ("contextId".to_string(), play_request.context_id.clone()), // script is moved here + ("status".to_string(), "pending".to_string()), + ("createdAt".to_string(), now.to_rfc3339()), + ("updatedAt".to_string(), now.to_rfc3339()), + ]; + + // Ensure hset_args is a slice of tuples (String, String) + // The redis crate's hset_multiple expects &[(K, V)] + // conn.hset_multiple::<_, String, String, ()>(&task_key, &hset_args).await?; + // Simpler: + // Explicitly type K, F, V for hset_multiple if inference is problematic. + // RV (return value of the command itself) is typically () for HSET type commands. + conn.hset_multiple::<_, _, _, ()>(&task_key, &hset_args) + .await?; + + // lpush also infers its types, RV is typically i64 (length of list) or () depending on exact command variant + // For `redis::AsyncCommands::lpush`, it's `RedisResult` where R: FromRedisValue + // Often this is the length of the list. Let's allow inference or specify if needed. + let _: redis::RedisResult = + conn.lpush(&worker_queue_key, play_request.id.clone()).await; + + Ok(()) + } + + // Internal helper to await response from worker + async fn await_response_from_connection( + &self, + conn: &mut redis::aio::MultiplexedConnection, + task_key: &String, + reply_queue_key: &String, + timeout: Duration, + ) -> Result { + // BLPOP on the reply queue + // The timeout for BLPOP is in seconds (integer) + let blpop_timeout_secs = timeout.as_secs().max(1); // Ensure at least 1 second for BLPOP timeout + + match conn + .blpop::<&String, Option<(String, String)>>(reply_queue_key, blpop_timeout_secs as f64) + .await + { + Ok(Some((_queue, result_message_str))) => { + // Attempt to deserialize the result message into RhaiTaskDetails or a similar structure + // For now, we assume the worker sends back a JSON string of RhaiTaskDetails + // or at least status, output, error. + // Let's refine what the worker sends. For now, assume it's a simplified result. + // The worker should ideally send a JSON string that can be parsed into RhaiTaskDetails. + // For this example, let's assume the worker sends a JSON string of a simplified result structure. + // A more robust approach would be for the worker to send the full RhaiTaskDetails (or relevant parts) + // and the client deserializes that. + // For now, let's assume the worker sends a JSON string of RhaiTaskDetails. + match serde_json::from_str::(&result_message_str) { + Ok(details) => { + info!( + "Task {} finished with status: {}", + details.task_id, details.status + ); + // Optionally, delete the reply queue + let _: redis::RedisResult = conn.del(&reply_queue_key).await; + Ok(details) + } + Err(e) => { + error!( + "Failed to deserialize result message from reply queue: {}", + e + ); + // Optionally, delete the reply queue + let _: redis::RedisResult = conn.del(&reply_queue_key).await; + Err(RhaiDispatcherError::SerializationError(e)) + } + } + } + Ok(None) => { + // BLPOP timed out + warn!( + "Timeout waiting for result on reply queue {} for task {}", + reply_queue_key, task_key + ); + // Optionally, delete the reply queue + let _: redis::RedisResult = conn.del(&reply_queue_key).await; + Err(RhaiDispatcherError::Timeout(task_key.clone())) + } + Err(e) => { + // Redis error + error!( + "Redis error on BLPOP for reply queue {}: {}", + reply_queue_key, e + ); + // Optionally, delete the reply queue + let _: redis::RedisResult = conn.del(&reply_queue_key).await; + Err(RhaiDispatcherError::RedisError(e)) + } + } + } + + // New method using dedicated reply queue + pub async fn submit_play_request( + &self, + play_request: &PlayRequest, + ) -> Result<(), RhaiDispatcherError> { + let mut conn = self.redis_client.get_multiplexed_async_connection().await?; + + self.submit_play_request_using_connection( + &mut conn, + &play_request, // Pass the task_id parameter + ) + .await?; + Ok(()) + } + + // New method using dedicated reply queue + pub async fn submit_play_request_and_await_result( + &self, + play_request: &PlayRequest, + ) -> Result { + let mut conn = self.redis_client.get_multiplexed_async_connection().await?; + + let reply_queue_key = format!("{}:reply:{}", NAMESPACE_PREFIX, play_request.id); // Derived from the passed task_id + + self.submit_play_request_using_connection( + &mut conn, + &play_request, // Pass the task_id parameter + ) + .await?; + + info!( + "Task {} submitted. Waiting for result on queue {} with timeout {:?}...", + play_request.id, // This is the UUID + reply_queue_key, + play_request.timeout + ); + + self.await_response_from_connection( + &mut conn, + &play_request.id, + &reply_queue_key, + play_request.timeout, + ) + .await + } + + // Method to get task status + pub async fn get_task_status( + &self, + task_id: &str, + ) -> Result, RhaiDispatcherError> { + let mut conn = self.redis_client.get_multiplexed_async_connection().await?; + let task_key = format!("{}{}", NAMESPACE_PREFIX, task_id); + + let result_map: Option> = + conn.hgetall(&task_key).await?; + + match result_map { + Some(map) => { + // Reconstruct RhaiTaskDetails from HashMap + let details = RhaiTaskDetails { + task_id: task_id.to_string(), // Use the task_id parameter passed to the function + script: map.get("script").cloned().unwrap_or_else(|| { + warn!("Task {}: 'script' field missing from Redis hash, defaulting to empty.", task_id); + String::new() + }), + status: map.get("status").cloned().unwrap_or_else(|| { + warn!("Task {}: 'status' field missing from Redis hash, defaulting to empty.", task_id); + String::new() + }), + // client_rpc_id is no longer a field in RhaiTaskDetails + output: map.get("output").cloned(), + error: map.get("error").cloned(), + created_at: map.get("createdAt") + .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok()) + .map(|dt| dt.with_timezone(&Utc)) + .unwrap_or_else(|| { + warn!("Task {}: 'createdAt' field missing or invalid in Redis hash, defaulting to Utc::now().", task_id); + Utc::now() + }), + updated_at: map.get("updatedAt") + .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok()) + .map(|dt| dt.with_timezone(&Utc)) + .unwrap_or_else(|| { + warn!("Task {}: 'updatedAt' field missing or invalid in Redis hash, defaulting to Utc::now().", task_id); + Utc::now() + }), + caller_id: map.get("callerId").cloned().expect("callerId field missing from Redis hash"), + worker_id: map.get("workerId").cloned().expect("workerId field missing from Redis hash"), + context_id: map.get("contextId").cloned().expect("contextId field missing from Redis hash"), + }; + // It's important to also check if the 'taskId' field exists in the map and matches the input task_id + // for data integrity, though the struct construction above uses the input task_id directly. + if let Some(redis_task_id) = map.get("taskId") { + if redis_task_id != task_id { + warn!("Task {}: Mismatch between requested task_id and taskId found in Redis hash ('{}'). Proceeding with requested task_id.", task_id, redis_task_id); + } + } else { + warn!("Task {}: 'taskId' field missing from Redis hash.", task_id); + } + Ok(Some(details)) + } + None => Ok(None), + } + } +} + +#[cfg(test)] +mod tests { + // use super::*; + // Basic tests can be added later, especially once examples are in place. + // For now, ensuring it compiles is the priority. + #[test] + fn it_compiles() { + assert_eq!(2 + 2, 4); + } +} diff --git a/rhailib/_archive/engine/Cargo.toml b/rhailib/_archive/engine/Cargo.toml new file mode 100644 index 0000000..363917e --- /dev/null +++ b/rhailib/_archive/engine/Cargo.toml @@ -0,0 +1,38 @@ +[package] +name = "rhailib_engine" +version = "0.1.0" +edition = "2021" +description = "Central Rhai engine for heromodels" + +[dependencies] +rhai = { version = "1.21.0", features = ["std", "sync", "decimal", "internals"] } +heromodels = { path = "../../../db/heromodels", features = ["rhai"] } +heromodels_core = { path = "../../../db/heromodels_core" } +chrono = "0.4" +heromodels-derive = { path = "../../../db/heromodels-derive" } +rhailib_dsl = { path = "../dsl" } + +[features] +default = ["calendar", "finance"] +calendar = [] +finance = [] +# Flow module is now updated to use our approach to Rhai engine registration +flow = [] +legal = [] +projects = [] +biz = [] + +[[example]] +name = "calendar_example" +path = "examples/calendar/example.rs" +required-features = ["calendar"] + +[[example]] +name = "flow_example" +path = "examples/flow/example.rs" +required-features = ["flow"] + +[[example]] +name = "finance" +path = "examples/finance/example.rs" +required-features = ["finance"] diff --git a/rhailib/_archive/engine/README.md b/rhailib/_archive/engine/README.md new file mode 100644 index 0000000..bcdc3fc --- /dev/null +++ b/rhailib/_archive/engine/README.md @@ -0,0 +1,135 @@ +# HeroModels Rhai Engine (`engine`) + +The `engine` crate provides a central Rhai scripting engine for the HeroModels project. It offers a unified way to interact with various HeroModels modules (like Calendar, Flow, Legal, etc.) through Rhai scripts, leveraging a shared database connection. + +## Overview + +This crate facilitates: + +1. **Centralized Engine Creation**: A function `create_heromodels_engine` to instantiate a Rhai engine pre-configured with common settings and all enabled HeroModels modules. +2. **Modular Registration**: HeroModels modules (Calendar, Flow, etc.) can be registered with a Rhai engine based on feature flags. +3. **Script Evaluation Utilities**: Helper functions for compiling Rhai scripts into Abstract Syntax Trees (ASTs) and for evaluating scripts or ASTs. +4. **Mock Database**: Includes a `mock_db` module for testing and running examples without needing a live database. + +## Core Components & Usage + +### Library (`src/lib.rs`) + +- **`create_heromodels_engine(db: Arc) -> Engine`**: + Creates and returns a new `rhai::Engine` instance. This engine is configured with default settings (e.g., max expression depths, string/array/map sizes) and then all available HeroModels modules (controlled by feature flags) are registered with it, using the provided `db` (an `Arc`) instance. + +- **`register_all_modules(engine: &mut Engine, db: Arc)`**: + Registers all HeroModels modules for which features are enabled (e.g., `calendar`, `flow`, `legal`, `projects`, `biz`) with the given Rhai `engine`. Each module is passed the shared `db` instance. + +- **`eval_script(engine: &Engine, script: &str) -> Result>`**: + A utility function to directly evaluate a Rhai script string using the provided `engine`. + +- **`compile_script(engine: &Engine, script: &str) -> Result>`**: + Compiles a Rhai script string into an `AST` (Abstract Syntax Tree) for potentially faster repeated execution. + +- **`run_ast(engine: &Engine, ast: &AST, scope: &mut Scope) -> Result>`**: + Runs a pre-compiled `AST` with a given `scope` using the provided `engine`. + +- **`mock_db` module**: + Provides `create_mock_db()` which returns an `Arc` instance suitable for testing and examples. This allows scripts that interact with database functionalities to run without external database dependencies. + +### Basic Usage + +```rust +use std::sync::Arc; +use engine::{create_heromodels_engine, eval_script}; +use engine::mock_db::create_mock_db; // For example usage +use heromodels::db::hero::OurDB; // Actual DB type + +// Create a mock database (or connect to a real one) +let db: Arc = create_mock_db(); + +// Create the Rhai engine with all enabled modules registered +let engine = create_heromodels_engine(db); + +// Run a Rhai script +let script = r#" + // Example: Assuming 'calendar' feature is enabled + let cal = new_calendar("My Test Calendar"); + cal.set_description("This is a test."); + print(`Created calendar: ${cal.get_name()}`); + cal.get_id() // Return the ID +"#; + +match eval_script(&engine, script) { + Ok(val) => println!("Script returned: {:?}", val), + Err(err) => eprintln!("Script error: {}", err), +} +``` + +### Using Specific Modules Manually + +If you need more fine-grained control or only want specific modules (and prefer not to rely solely on feature flags at compile time for `create_heromodels_engine`), you can initialize an engine and register modules manually: + +```rust +use std::sync::Arc; +use rhai::Engine; +use engine::mock_db::create_mock_db; // For example usage +use heromodels::db::hero::OurDB; +// Import the specific module registration function +use heromodels::models::calendar::register_calendar_rhai_module; + + +// Create a mock database +let db: Arc = create_mock_db(); + +// Create a new Rhai engine +let mut engine = Engine::new(); + +// Register only the calendar module +register_calendar_rhai_module(&mut engine, db.clone()); + +// Now you can use calendar-related functions in your scripts +let result = engine.eval::(r#" let c = new_calendar("Solo Cal"); c.get_name() "#); +match result { + Ok(name) => println!("Calendar name: {}", name), + Err(err) => eprintln!("Error: {}", err), +} +``` + +## Examples + +This crate includes several examples demonstrating how to use different HeroModels modules with Rhai. Each example typically requires its corresponding feature to be enabled. + +- `calendar_example`: Working with calendars, events, and attendees (requires `calendar` feature). +- `flow_example`: Working with flows, steps, and signature requirements (requires `flow` feature). +- `finance_example`: Working with financial models (requires `finance` feature). +- *(Additional examples for `legal`, `projects`, `biz` would follow the same pattern if present).* + +To run an example (e.g., `calendar_example`): + +```bash +cargo run --example calendar_example --features calendar +``` +*(Note: Examples in `Cargo.toml` already specify `required-features`, so simply `cargo run --example calendar_example` might suffice if those features are part of the default set or already enabled.)* + +## Features + +The crate uses feature flags to control which HeroModels modules are compiled and registered: + +- `calendar`: Enables the Calendar module. +- `finance`: Enables the Finance module. +- `flow`: Enables the Flow module. +- `legal`: Enables the Legal module. +- `projects`: Enables the Projects module. +- `biz`: Enables the Business module. + +The `default` features are `["calendar", "finance"]`. You can enable other modules by specifying them during the build or in your project's `Cargo.toml` if this `engine` crate is a dependency. + +## Dependencies + +Key dependencies include: +- `rhai`: The Rhai scripting engine. +- `heromodels`: Provides the core data models and database interaction logic, including the Rhai registration functions for each module. +- `heromodels_core`: Core utilities for HeroModels. +- `chrono`: For date/time utilities. +- `heromodels-derive`: Procedural macros used by HeroModels. + +## License + +This crate is part of the HeroModels project and shares its license. diff --git a/rhailib/_archive/engine/build.rs b/rhailib/_archive/engine/build.rs new file mode 100644 index 0000000..8b8ff97 --- /dev/null +++ b/rhailib/_archive/engine/build.rs @@ -0,0 +1,16 @@ +fn main() { + // Tell Cargo to re-run this build script if the calendar/rhai.rs file changes + println!("cargo:rerun-if-changed=../heromodels/src/models/calendar/rhai.rs"); + + // Tell Cargo to re-run this build script if the flow/rhai.rs file changes + println!("cargo:rerun-if-changed=../heromodels/src/models/flow/rhai.rs"); + + // Tell Cargo to re-run this build script if the legal/rhai.rs file changes + println!("cargo:rerun-if-changed=../heromodels/src/models/legal/rhai.rs"); + + // Tell Cargo to re-run this build script if the projects/rhai.rs file changes + println!("cargo:rerun-if-changed=../heromodels/src/models/projects/rhai.rs"); + + // Tell Cargo to re-run this build script if the biz/rhai.rs file changes + println!("cargo:rerun-if-changed=../heromodels/src/models/biz/rhai.rs"); +} diff --git a/rhailib/_archive/engine/docs/ARCHITECTURE.md b/rhailib/_archive/engine/docs/ARCHITECTURE.md new file mode 100644 index 0000000..42e8278 --- /dev/null +++ b/rhailib/_archive/engine/docs/ARCHITECTURE.md @@ -0,0 +1,331 @@ +# Architecture of the `rhailib_engine` Crate + +The `rhailib_engine` crate serves as the central Rhai scripting engine for the heromodels ecosystem. It provides a unified interface for creating, configuring, and executing Rhai scripts with access to all business domain modules through a feature-based architecture. + +## Core Architecture + +The engine acts as an orchestration layer that brings together the DSL modules and provides execution utilities: + +```mermaid +graph TD + A[rhailib_engine] --> B[Engine Creation] + A --> C[Script Execution] + A --> D[Mock Database] + A --> E[Feature Management] + + B --> B1[create_heromodels_engine] + B --> B2[Engine Configuration] + B --> B3[DSL Registration] + + C --> C1[eval_script] + C --> C2[eval_file] + C --> C3[compile_script] + C --> C4[run_ast] + + D --> D1[create_mock_db] + D --> D2[seed_mock_db] + D --> D3[Domain Data Seeding] + + E --> E1[calendar] + E --> E2[finance] + E --> E3[flow] + E --> E4[legal] + E --> E5[projects] + E --> E6[biz] + + B3 --> F[rhailib_dsl] + F --> G[All Domain Modules] +``` + +## Core Components + +### 1. Engine Factory (`create_heromodels_engine`) + +The primary entry point for creating a fully configured Rhai engine: + +```rust +pub fn create_heromodels_engine() -> Engine +``` + +**Responsibilities:** +- Creates a new Rhai engine instance +- Configures engine limits and settings +- Registers all available DSL modules +- Returns a ready-to-use engine + +**Configuration Settings:** +- **Expression Depth**: 128 levels for both expressions and functions +- **String Size Limit**: 10 MB maximum string size +- **Array Size Limit**: 10,000 elements maximum +- **Map Size Limit**: 10,000 key-value pairs maximum + +### 2. Script Execution Utilities + +#### Direct Script Evaluation +```rust +pub fn eval_script(engine: &Engine, script: &str) -> Result> +``` +Executes Rhai script strings directly with immediate results. + +#### File-Based Script Execution +```rust +pub fn eval_file(engine: &Engine, file_path: &Path) -> Result> +``` +Loads and executes Rhai scripts from filesystem with proper error handling. + +#### Compiled Script Execution +```rust +pub fn compile_script(engine: &Engine, script: &str) -> Result> +pub fn run_ast(engine: &Engine, ast: &AST, scope: &mut Scope) -> Result> +``` +Provides compilation and execution of scripts for performance optimization. + +### 3. Mock Database System + +#### Database Creation +```rust +pub fn create_mock_db() -> Arc +``` +Creates an in-memory database instance for testing and examples. + +#### Data Seeding +```rust +pub fn seed_mock_db(db: Arc) +``` +Populates the mock database with representative data across all domains. + +## Feature-Based Architecture + +The engine uses Cargo features to control which domain modules are included: + +### Available Features + +- **`calendar`** (default): Calendar and event management +- **`finance`** (default): Financial accounts, assets, and marketplace +- **`flow`**: Workflow and approval processes +- **`legal`**: Contract and legal document management +- **`projects`**: Project and task management +- **`biz`**: Business operations and entities + +### Feature Integration Pattern + +```rust +#[cfg(feature = "calendar")] +use heromodels::models::calendar::*; + +#[cfg(feature = "finance")] +use heromodels::models::finance::*; +``` + +This allows for: +- **Selective Compilation**: Only include needed functionality +- **Reduced Binary Size**: Exclude unused domain modules +- **Modular Deployment**: Different configurations for different use cases + +## Mock Database Architecture + +### Database Structure + +The mock database provides a complete testing environment: + +```mermaid +graph LR + A[Mock Database] --> B[Calendar Data] + A --> C[Finance Data] + A --> D[Flow Data] + A --> E[Legal Data] + A --> F[Projects Data] + + B --> B1[Calendars] + B --> B2[Events] + B --> B3[Attendees] + + C --> C1[Accounts] + C --> C2[Assets - ERC20/ERC721] + C --> C3[Marketplace Listings] + + D --> D1[Flows] + D --> D2[Flow Steps] + D --> D3[Signature Requirements] + + E --> E1[Contracts] + E --> E2[Contract Revisions] + E --> E3[Contract Signers] + + F --> F1[Projects] + F --> F2[Project Members] + F --> F3[Project Tags] +``` + +### Seeding Strategy + +Each domain has its own seeding function that creates realistic test data: + +#### Calendar Seeding +- Creates work calendars with descriptions +- Adds team meetings with attendees +- Sets up recurring events + +#### Finance Seeding +- Creates demo trading accounts +- Generates ERC20 tokens and ERC721 NFTs +- Sets up marketplace listings with metadata + +#### Flow Seeding (Feature-Gated) +- Creates document approval workflows +- Defines multi-step approval processes +- Sets up signature requirements + +#### Legal Seeding (Feature-Gated) +- Creates service agreements +- Adds contract revisions and versions +- Defines contract signers and roles + +#### Projects Seeding (Feature-Gated) +- Creates project instances with status tracking +- Assigns team members and priorities +- Adds project tags and categorization + +## Error Handling Architecture + +### Comprehensive Error Propagation + +```rust +Result> +``` + +All functions return proper Rhai error types that include: +- **Script Compilation Errors**: Syntax and parsing issues +- **Runtime Errors**: Execution failures and exceptions +- **File System Errors**: File reading and path resolution issues +- **Database Errors**: Mock database operation failures + +### Error Context Enhancement + +File operations include enhanced error context: +```rust +Err(Box::new(EvalAltResult::ErrorSystem( + format!("Failed to read script file: {}", file_path.display()), + Box::new(io_err), +))) +``` + +## Performance Considerations + +### Engine Configuration + +Optimized settings for production use: +- **Memory Limits**: Prevent runaway script execution +- **Depth Limits**: Avoid stack overflow from deep recursion +- **Size Limits**: Control memory usage for large data structures + +### Compilation Strategy + +- **AST Caching**: Compile once, execute multiple times +- **Scope Management**: Efficient variable scope handling +- **Module Registration**: One-time registration at engine creation + +### Mock Database Performance + +- **In-Memory Storage**: Fast access for testing scenarios +- **Temporary Directories**: Automatic cleanup after use +- **Lazy Loading**: Data seeded only when needed + +## Integration Patterns + +### Script Development Workflow + +```rust +// 1. Create engine with all modules +let engine = create_heromodels_engine(); + +// 2. Execute business logic scripts +let result = eval_script(&engine, r#" + let company = new_company() + .name("Tech Startup") + .business_type("startup"); + save_company(company) +"#)?; + +// 3. Handle results and errors +match result { + Ok(value) => println!("Success: {:?}", value), + Err(error) => eprintln!("Error: {}", error), +} +``` + +### Testing Integration + +```rust +// 1. Create mock database +let db = create_mock_db(); +seed_mock_db(db.clone()); + +// 2. Create engine +let engine = create_heromodels_engine(); + +// 3. Test scripts against seeded data +let script = r#" + let calendars = list_calendars(); + calendars.len() +"#; +let count = eval_script(&engine, script)?; +``` + +### File-Based Script Execution + +```rust +// Execute scripts from files +let result = eval_file(&engine, Path::new("scripts/business_logic.rhai"))?; +``` + +## Deployment Configurations + +### Minimal Configuration +```toml +[dependencies] +rhailib_engine = { version = "0.1.0", default-features = false, features = ["calendar"] } +``` + +### Full Configuration +```toml +[dependencies] +rhailib_engine = { version = "0.1.0", features = ["calendar", "finance", "flow", "legal", "projects", "biz"] } +``` + +### Custom Configuration +```toml +[dependencies] +rhailib_engine = { version = "0.1.0", default-features = false, features = ["finance", "biz"] } +``` + +## Security Considerations + +### Script Execution Limits +- **Resource Limits**: Prevent resource exhaustion attacks +- **Execution Time**: Configurable timeouts for long-running scripts +- **Memory Bounds**: Controlled memory allocation + +### Database Access +- **Mock Environment**: Safe testing without production data exposure +- **Temporary Storage**: Automatic cleanup prevents data persistence +- **Isolated Execution**: Each test run gets fresh database state + +## Extensibility + +### Adding New Domains +1. Create new feature flag in `Cargo.toml` +2. Add conditional imports for new models +3. Implement seeding function for test data +4. Register with DSL module system + +### Custom Engine Configuration +```rust +let mut engine = Engine::new(); +// Custom configuration +engine.set_max_expr_depths(256, 256); +// Register specific modules +rhailib_dsl::register_dsl_modules(&mut engine); +``` + +This architecture provides a robust, feature-rich foundation for Rhai script execution while maintaining flexibility, performance, and security. \ No newline at end of file diff --git a/rhailib/_archive/engine/examples/calendar/calendar_script.rhai b/rhailib/_archive/engine/examples/calendar/calendar_script.rhai new file mode 100644 index 0000000..626c226 --- /dev/null +++ b/rhailib/_archive/engine/examples/calendar/calendar_script.rhai @@ -0,0 +1,101 @@ +// calendar_script.rhai +// Example Rhai script for working with Calendar models + +// Constants for AttendanceStatus +const NO_RESPONSE = "NoResponse"; +const ACCEPTED = "Accepted"; +const DECLINED = "Declined"; +const TENTATIVE = "Tentative"; + +// Create a new calendar using builder pattern +let my_calendar = new_calendar() + .name("Team Calendar") + .description("Calendar for team events and meetings"); + +print(`Created calendar: ${my_calendar.name} (${my_calendar.id})`); + + +// Add attendees to the event +let alice = new_attendee() + .with_contact_id(1) + .with_status(NO_RESPONSE); +let bob = new_attendee() + .with_contact_id(2) + .with_status(ACCEPTED); +let charlie = new_attendee() + .with_contact_id(3) + .with_status(TENTATIVE); + + +// Create a new event using builder pattern +// Note: Timestamps are in seconds since epoch +let now = timestamp_now(); +let one_hour = 60 * 60; +let meeting = new_event() + .title("Weekly Sync") + .reschedule(now, now + one_hour) + .location("Conference Room A") + .description("Regular team sync meeting") + .add_attendee(alice) + .add_attendee(bob) + .add_attendee(charlie) + .save_event(); + +print(`Created event: ${meeting.title}`); + +meeting.delete_event(); + +print(`Deleted event: ${meeting.title}`); + +// Print attendees info +let attendees = meeting.attendees; +print(`Added attendees to the event`); + +// Update Charlie's attendee status directly +meeting.update_attendee_status(3, ACCEPTED); +print(`Updated Charlie's status to: ${ACCEPTED}`); + +// Add the event to the calendar +my_calendar.add_event_to_calendar(meeting); +// Print events info +print(`Added event to calendar`); + +// Save the calendar to the database +let saved_calendar = my_calendar.save_calendar(); +print(`Calendar saved to database with ID: ${saved_calendar.id}`); + +// Retrieve the calendar from the database using the ID from the saved calendar +let retrieved_calendar = get_calendar_by_id(saved_calendar.id); +if retrieved_calendar != () { + print(`Retrieved calendar: ${retrieved_calendar.name}`); + print(`Retrieved calendar successfully`); +} else { + print("Failed to retrieve calendar from database"); +} + +// List all calendars in the database +let all_calendars = list_calendars(); +print("\nListing all calendars in database:"); +let calendar_count = 0; +for calendar in all_calendars { + print(` - Calendar: ${calendar.name} (ID: ${calendar.id})`); + calendar_count += 1; +} +print(`Total calendars: ${calendar_count}`); + +// List all events in the database +let all_events = list_events(); +print("\nListing all events in database:"); +let event_count = 0; +for event in all_events { + print(` - Event: ${event.title} (ID: ${event.id})`); + event_count += 1; +} +print(`Total events: ${event_count}`); + +// Helper function to get current timestamp +fn timestamp_now() { + // This would typically be provided by the host application + // For this example, we'll use a fixed timestamp + 1685620800 // June 1, 2023, 12:00 PM +} diff --git a/rhailib/_archive/engine/examples/calendar/example.rs b/rhailib/_archive/engine/examples/calendar/example.rs new file mode 100644 index 0000000..9dc0889 --- /dev/null +++ b/rhailib/_archive/engine/examples/calendar/example.rs @@ -0,0 +1,70 @@ +use engine::mock_db::create_mock_db; +use engine::{create_heromodels_engine, eval_file}; +use rhai::Engine; + +mod mock; +use mock::seed_calendar_data; + +fn main() -> Result<(), Box> { + println!("Calendar Rhai Example"); + println!("====================="); + + // Create a mock database + let db = create_mock_db(); + + // Seed the database with some initial data + seed_calendar_data(db.clone()); + + // Create the Rhai engine using our central engine creator + let mut engine = create_heromodels_engine(db.clone()); + + // Register timestamp helper functions + register_timestamp_helpers(&mut engine); + + // Get the path to the script + let manifest_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let script_path = manifest_dir + .join("examples") + .join("calendar") + .join("calendar_script.rhai"); + + println!("\nRunning script: {}", script_path.display()); + println!("---------------------"); + + // Run the script + match eval_file(&engine, &script_path) { + Ok(result) => { + if !result.is_unit() { + println!("\nScript returned: {:?}", result); + } + println!("\nScript executed successfully!"); + Ok(()) + } + Err(err) => { + eprintln!("\nError running script: {}", err); + Err(Box::new(std::io::Error::new( + std::io::ErrorKind::Other, + err.to_string(), + ))) + } + } +} + +// Register timestamp helper functions with the engine +fn register_timestamp_helpers(engine: &mut Engine) { + use chrono::{TimeZone, Utc}; + + // Function to get current timestamp + engine.register_fn("timestamp_now", || Utc::now().timestamp() as i64); + + // Function to format a timestamp + engine.register_fn("format_timestamp", |ts: i64| { + let dt = Utc + .timestamp_opt(ts, 0) + .single() + .expect("Invalid timestamp"); + dt.format("%Y-%m-%d %H:%M:%S UTC").to_string() + }); + + println!("Timestamp helper functions registered successfully."); +} diff --git a/rhailib/_archive/engine/examples/calendar/mock.rs b/rhailib/_archive/engine/examples/calendar/mock.rs new file mode 100644 index 0000000..99fc961 --- /dev/null +++ b/rhailib/_archive/engine/examples/calendar/mock.rs @@ -0,0 +1,60 @@ +use chrono::Utc; +use heromodels::db::hero::OurDB; +use heromodels::db::{Collection, Db}; +use heromodels::models::calendar::{Calendar, Event}; +use heromodels_core::Model; +use std::sync::Arc; + +/// Seed the mock database with calendar data +pub fn seed_calendar_data(db: Arc) { + // Create a calendar + let calendar = Calendar::new(None, "Work Calendar".to_string()) + .description("My work schedule".to_string()); + + // Store the calendar in the database + let (calendar_id, mut saved_calendar) = db + .collection::() + .expect("Failed to get Calendar collection") + .set(&calendar) + .expect("Failed to store calendar"); + + // Create an event + let now = Utc::now().timestamp(); + let end_time = now + 3600; // Add 1 hour in seconds + + let event = Event::new() + .title("Team Meeting".to_string()) + .reschedule(now, end_time) + .location("Conference Room A".to_string()) + .description("Weekly sync".to_string()) + .build(); + + // Store the event in the database first to get its ID + let (event_id, saved_event) = db + .collection() + .expect("Failed to get Event collection") + .set(&event) + .expect("Failed to store event"); + + // Add the event ID to the calendar + saved_calendar = saved_calendar.add_event(event_id as i64); + + // Store the updated calendar in the database + let (_calendar_id, final_calendar) = db + .collection::() + .expect("Failed to get Calendar collection") + .set(&saved_calendar) + .expect("Failed to store calendar"); + + println!("Mock database seeded with calendar data:"); + println!( + " - Added calendar: {} (ID: {})", + final_calendar.name, + final_calendar.get_id() + ); + println!( + " - Added event: {} (ID: {})", + saved_event.title, + saved_event.get_id() + ); +} diff --git a/rhailib/_archive/engine/examples/finance/example.rs b/rhailib/_archive/engine/examples/finance/example.rs new file mode 100644 index 0000000..ac1d8a2 --- /dev/null +++ b/rhailib/_archive/engine/examples/finance/example.rs @@ -0,0 +1,70 @@ +use engine::mock_db::create_mock_db; +use engine::{create_heromodels_engine, eval_file}; +use rhai::Engine; +use std::path::Path; + +mod mock; +use mock::seed_finance_data; + +fn main() -> Result<(), Box> { + println!("Finance Rhai Example"); + println!("==================="); + + // Create a mock database + let db = create_mock_db(); + + // Seed the database with some initial data + seed_finance_data(db.clone()); + + // Create the Rhai engine using our central engine creator + let mut engine = create_heromodels_engine(db.clone()); + + // Register timestamp helper functions + register_timestamp_helpers(&mut engine); + + // Get the path to the script + let script_path = Path::new(file!()) + .parent() + .unwrap() + .join("finance_script.rhai"); + + println!("\nRunning script: {}", script_path.display()); + println!("---------------------"); + + // Run the script + match eval_file(&engine, &script_path) { + Ok(result) => { + if !result.is_unit() { + println!("\nScript returned: {:?}", result); + } + println!("\nScript executed successfully!"); + Ok(()) + } + Err(err) => { + eprintln!("\nError running script: {}", err); + Err(Box::new(std::io::Error::new( + std::io::ErrorKind::Other, + err.to_string(), + ))) + } + } +} + +// Register timestamp helper functions with the engine +fn register_timestamp_helpers(engine: &mut Engine) { + use chrono::{TimeZone, Utc}; + + // Function to get current timestamp + engine.register_fn("timestamp_now", || Utc::now().timestamp() as i64); + + // Function to format a timestamp + engine.register_fn("format_timestamp", |ts: i64| { + let dt = Utc + .timestamp_opt(ts, 0) + .single() + .expect("Invalid timestamp"); + dt.format("%Y-%m-%d %H:%M:%S UTC").to_string() + }); + + println!("Timestamp helper functions registered successfully."); +} diff --git a/rhailib/_archive/engine/examples/finance/finance_script.rhai b/rhailib/_archive/engine/examples/finance/finance_script.rhai new file mode 100644 index 0000000..caa0249 --- /dev/null +++ b/rhailib/_archive/engine/examples/finance/finance_script.rhai @@ -0,0 +1,202 @@ +// finance_script.rhai +// Example Rhai script for working with Finance models + +// Constants for AssetType +const NATIVE = "Native"; +const ERC20 = "Erc20"; +const ERC721 = "Erc721"; +const ERC1155 = "Erc1155"; + +// Constants for ListingStatus +const ACTIVE = "Active"; +const SOLD = "Sold"; +const CANCELLED = "Cancelled"; +const EXPIRED = "Expired"; + +// Constants for ListingType +const FIXED_PRICE = "FixedPrice"; +const AUCTION = "Auction"; +const EXCHANGE = "Exchange"; + +// Constants for BidStatus +const BID_ACTIVE = "Active"; +const BID_ACCEPTED = "Accepted"; +const BID_REJECTED = "Rejected"; +const BID_CANCELLED = "Cancelled"; + +// Create a new account using builder pattern +let alice_account = new_account() + .name("Alice's Account") + .user_id(101) + .description("Alice's primary trading account") + .ledger("ethereum") + .address("0x1234567890abcdef1234567890abcdef12345678") + .pubkey("0xabcdef1234567890abcdef1234567890abcdef12"); + +print(`Created account: ${alice_account.get_name()} (User ID: ${alice_account.get_user_id()})`); + +// Save the account to the database +let saved_alice = set_account(alice_account); +print(`Account saved to database with ID: ${saved_alice.get_id()}`); + +// Create a new asset using builder pattern +let token_asset = new_asset() + .name("HERO Token") + .description("Herocode governance token") + .amount(1000.0) + .address("0x9876543210abcdef9876543210abcdef98765432") + .asset_type(ERC20) + .decimals(18); + +print(`Created asset: ${token_asset.get_name()} (${token_asset.get_amount()} ${token_asset.get_asset_type()})`); + +// Save the asset to the database +let saved_token = set_asset(token_asset); +print(`Asset saved to database with ID: ${saved_token.get_id()}`); + +// Add the asset to Alice's account +saved_alice = saved_alice.add_asset(saved_token.get_id()); +saved_alice = set_account(saved_alice); +print(`Added asset ${saved_token.get_name()} to ${saved_alice.get_name()}`); + +// Create a new NFT asset +let nft_asset = new_asset() + .name("Herocode #42") + .description("Unique digital collectible") + .amount(1.0) + .address("0xabcdef1234567890abcdef1234567890abcdef12") + .asset_type(ERC721) + .decimals(0); + +// Save the NFT to the database +let saved_nft = set_asset(nft_asset); +print(`NFT saved to database with ID: ${saved_nft.get_id()}`); + +// Create Bob's account +let bob_account = new_account() + .name("Bob's Account") + .user_id(102) + .description("Bob's trading account") + .ledger("ethereum") + .address("0xfedcba0987654321fedcba0987654321fedcba09") + .pubkey("0x654321fedcba0987654321fedcba0987654321fe"); + +// Save Bob's account +let saved_bob = set_account(bob_account); +print(`Created and saved Bob's account with ID: ${saved_bob.get_id()}`); + +// Create a listing for the NFT +let nft_listing = new_listing() + .seller_id(saved_alice.get_id()) + .asset_id(saved_nft.get_id()) + .price(0.5) + .currency("ETH") + .listing_type(AUCTION) + .title("Rare Herocode NFT") + .description("One of a kind digital collectible") + .image_url("https://example.com/nft/42.png") + .expires_at(timestamp_now() + 86400) // 24 hours from now + .add_tag("rare") + .add_tag("collectible") + .add_tag("digital art") + .set_listing(); + +// Save the listing +print(`Created listing: ${nft_listing.get_title()} (ID: ${nft_listing.get_id()})`); +print(`Listing status: ${nft_listing.get_status()}, Type: ${nft_listing.get_listing_type()}`); +print(`Listing price: ${nft_listing.get_price()} ${nft_listing.get_currency()}`); + +// Create a bid from Bob +let bob_bid = new_bid() + .listing_id(nft_listing.get_id().to_string()) + .bidder_id(saved_bob.get_id()) + .amount(1.5) + .currency("ETH") + .set_bid(); + +// Save the bid +print(`Created bid from ${saved_bob.get_name()} for ${bob_bid.get_amount()} ${bob_bid.get_currency()}`); + +// Add the bid to the listing +nft_listing.add_bid(bob_bid); +nft_listing.set_listing(); +print(`Added bid to listing ${nft_listing.get_title()}`); + +// Create another bid with higher amount +let charlie_account = new_account() + .name("Charlie's Account") + .user_id(103) + .description("Charlie's trading account") + .ledger("ethereum") + .address("0x1122334455667788991122334455667788990011") + .pubkey("0x8877665544332211887766554433221188776655"); + +let saved_charlie = set_account(charlie_account); +print(`Created and saved Charlie's account with ID: ${saved_charlie.get_id()}`); + +let charlie_bid = new_bid() + .listing_id(nft_listing.get_id().to_string()) + .bidder_id(saved_charlie.get_id()) + .amount(2.5) + .currency("ETH") + .set_bid(); + +print(`Created higher bid from ${saved_charlie.get_name()} for ${charlie_bid.get_amount()} ${charlie_bid.get_currency()}`); + +// Add the higher bid to the listing +nft_listing.add_bid(charlie_bid) + .set_listing(); + + + +print(`Added higher bid to listing ${nft_listing.get_title()}`); + +nft_listing.sale_price(2.5) + .set_listing(); + +// Complete the sale to the highest bidder (Charlie) +nft_listing.complete_sale(saved_charlie.get_id()) + .set_listing(); + +print(`Completed sale of ${nft_listing.get_title()} to ${saved_charlie.get_name()}`); +print(`New listing status: ${saved_listing.get_status()}`); + +// Retrieve the listing from the database +let retrieved_listing = get_listing_by_id(saved_listing.get_id()); +print(`Retrieved listing: ${retrieved_listing.get_title()} (Status: ${retrieved_listing.get_status()})`); + +// Create a fixed price listing +let token_listing = new_listing() + .seller_id(saved_alice.get_id()) + .asset_id(saved_token.get_id()) + .price(100.0) + .currency("USDC") + .listing_type(FIXED_PRICE) + .title("HERO Tokens for Sale") + .description("100 HERO tokens at fixed price") + .set_listing(); + +// Save the fixed price listing +print(`Created fixed price listing: ${token_listing.get_title()} (ID: ${token_listing.get_id()})`); + +// Cancel the listing +token_listing.cancel(); +token_listing.set_listing(); +print(`Cancelled listing: ${token_listing.get_title()}`); +print(`Listing status: ${token_listing.get_status()}`); + +// Print summary of all accounts +print("\nAccount Summary:"); +print(`Alice (ID: ${saved_alice.get_id()}): ${saved_alice.get_assets().len()} assets`); +print(`Bob (ID: ${saved_bob.get_id()}): ${saved_bob.get_assets().len()} assets`); +print(`Charlie (ID: ${saved_charlie.get_id()}): ${saved_charlie.get_assets().len()} assets`); + +// Print summary of all listings +print("\nListing Summary:"); +print(`NFT Auction (ID: ${nft_listing.get_id()}): ${nft_listing.get_status()}`); +print(`Token Sale (ID: ${token_listing.get_id()}): ${token_listing.get_status()}`); + +// Print summary of all bids +print("\nBid Summary:"); +print(`Bob's bid: ${bob_bid.get_amount()} ${bob_bid.get_currency()} (Status: ${bob_bid.get_status()})`); +print(`Charlie's bid: ${charlie_bid.get_amount()} ${charlie_bid.get_currency()} (Status: ${charlie_bid.get_status()})`); diff --git a/rhailib/_archive/engine/examples/finance/mock.rs b/rhailib/_archive/engine/examples/finance/mock.rs new file mode 100644 index 0000000..49fbb5e --- /dev/null +++ b/rhailib/_archive/engine/examples/finance/mock.rs @@ -0,0 +1,111 @@ +use heromodels::db::hero::OurDB; +use heromodels::db::{Collection, Db}; +use heromodels::models::finance::account::Account; +use heromodels::models::finance::asset::{Asset, AssetType}; +use heromodels::models::finance::marketplace::{Listing, ListingType}; +use heromodels_core::Model; +use std::sync::Arc; + +/// Seed the mock database with finance data +pub fn seed_finance_data(db: Arc) { + // Create a user account + let account = Account::new() + .name("Demo Account") + .user_id(1) + .description("Demo trading account") + .ledger("ethereum") + .address("0x1234567890abcdef1234567890abcdef12345678") + .pubkey("0xabcdef1234567890abcdef1234567890abcdef12"); + + // Store the account in the database + let (account_id, mut updated_account) = db + .collection::() + .expect("Failed to get Account collection") + .set(&account) + .expect("Failed to store account"); + + // Create an ERC20 token asset + let token_asset = Asset::new() + .name("HERO Token") + .description("Herocode governance token") + .amount(1000.0) + .address("0x9876543210abcdef9876543210abcdef98765432") + .asset_type(AssetType::Erc20) + .decimals(18); + + // Store the token asset in the database + let (token_id, updated_token) = db + .collection::() + .expect("Failed to get Asset collection") + .set(&token_asset) + .expect("Failed to store token asset"); + + // Create an NFT asset + let nft_asset = Asset::new() + .name("Herocode #1") + .description("Unique digital collectible") + .amount(1.0) + .address("0xabcdef1234567890abcdef1234567890abcdef12") + .asset_type(AssetType::Erc721) + .decimals(0); + + // Store the NFT asset in the database + let (nft_id, updated_nft) = db + .collection::() + .expect("Failed to get Asset collection") + .set(&nft_asset) + .expect("Failed to store NFT asset"); + + // Add assets to the account + updated_account = updated_account.add_asset(token_id); + updated_account = updated_account.add_asset(nft_id); + + // Update the account in the database + let (_, final_account) = db + .collection::() + .expect("Failed to get Account collection") + .set(&updated_account) + .expect("Failed to store updated account"); + + // Create a listing for the NFT + let listing = Listing::new() + .seller_id(account_id) + .asset_id(nft_id) + .price(0.5) + .currency("ETH") + .listing_type(ListingType::Auction) + .title("Rare Herocode NFT".to_string()) + .description("One of a kind digital collectible".to_string()) + .image_url(Some("https://example.com/nft/1.png".to_string())) + .add_tag("rare".to_string()) + .add_tag("collectible".to_string()); + + // Store the listing in the database + let (_listing_id, updated_listing) = db + .collection::() + .expect("Failed to get Listing collection") + .set(&listing) + .expect("Failed to store listing"); + + println!("Mock database seeded with finance data:"); + println!( + " - Added account: {} (ID: {})", + final_account.name, + final_account.get_id() + ); + println!( + " - Added token asset: {} (ID: {})", + updated_token.name, + updated_token.get_id() + ); + println!( + " - Added NFT asset: {} (ID: {})", + updated_nft.name, + updated_nft.get_id() + ); + println!( + " - Added listing: {} (ID: {})", + updated_listing.title, + updated_listing.get_id() + ); +} diff --git a/rhailib/_archive/engine/examples/flow/example.rs b/rhailib/_archive/engine/examples/flow/example.rs new file mode 100644 index 0000000..d5b3dd6 --- /dev/null +++ b/rhailib/_archive/engine/examples/flow/example.rs @@ -0,0 +1,162 @@ +use engine::mock_db::create_mock_db; +use engine::{create_heromodels_engine, eval_file}; +use heromodels::models::flow::{Flow, FlowStep, SignatureRequirement}; +use heromodels_core::Model; +use rhai::Scope; +use std::path::Path; + +mod mock; +use mock::seed_flow_data; + +fn main() -> Result<(), Box> { + println!("Flow Rhai Example"); + println!("================="); + + // Create a mock database + let db = create_mock_db(); + + // Seed the database with initial data + seed_flow_data(db.clone()); + + // Create the Rhai engine with all modules registered + let engine = create_heromodels_engine(db.clone()); + + // Get the path to the script + let script_path = Path::new(file!()) + .parent() + .unwrap() + .join("flow_script.rhai"); + + println!("\nRunning script: {}", script_path.display()); + println!("---------------------"); + + // Run the script + match eval_file(&engine, &script_path.to_string_lossy()) { + Ok(result) => { + if !result.is_unit() { + println!("\nScript returned: {:?}", result); + } + println!("\nScript executed successfully!"); + } + Err(err) => { + eprintln!("\nError running script: {}", err); + return Err(Box::new(std::io::Error::new( + std::io::ErrorKind::Other, + err.to_string(), + ))); + } + } + + // Demonstrate direct Rust interaction with the Rhai-exposed flow functionality + println!("\nDirect Rust interaction with Rhai-exposed flow functionality"); + println!("----------------------------------------------------------"); + + // Create a new scope + let mut scope = Scope::new(); + + // Create a new flow using the Rhai function + let result = engine.eval::("new_flow(0, \"Direct Rust Flow\")"); + match result { + Ok(mut flow) => { + println!( + "Created flow from Rust: {} (ID: {})", + flow.name, + flow.get_id() + ); + + // Set flow status using the builder pattern + flow = flow.status("active".to_string()); + println!("Set flow status to: {}", flow.status); + + // Create a new flow step using the Rhai function + let result = engine.eval::("new_flow_step(0, 1)"); + + match result { + Ok(mut step) => { + println!( + "Created flow step from Rust: Step Order {} (ID: {})", + step.step_order, + step.get_id() + ); + + // Set step description + step = step.description("Direct Rust Step".to_string()); + println!( + "Set step description to: {}", + step.description + .clone() + .unwrap_or_else(|| "None".to_string()) + ); + + // Create a signature requirement using the Rhai function + let result = engine.eval::( + "new_signature_requirement(0, 1, \"Direct Rust Signer\", \"Please sign this document\")" + ); + + match result { + Ok(req) => { + println!( + "Created signature requirement from Rust: Public Key {} (ID: {})", + req.public_key, + req.get_id() + ); + + // Add the step to the flow using the builder pattern + flow = flow.add_step(step); + println!( + "Added step to flow. Flow now has {} steps", + flow.steps.len() + ); + + // Save the flow to the database using the Rhai function + let save_flow_script = "fn save_it(f) { return db::save_flow(f); }"; + let save_flow_ast = engine.compile(save_flow_script).unwrap(); + let result = engine.call_fn::( + &mut scope, + &save_flow_ast, + "save_it", + (flow,), + ); + match result { + Ok(saved_flow) => { + println!( + "Saved flow to database with ID: {}", + saved_flow.get_id() + ); + } + Err(err) => eprintln!("Error saving flow: {}", err), + } + + // Save the signature requirement to the database using the Rhai function + let save_req_script = + "fn save_it(r) { return db::save_signature_requirement(r); }"; + let save_req_ast = engine.compile(save_req_script).unwrap(); + let result = engine.call_fn::( + &mut scope, + &save_req_ast, + "save_it", + (req,), + ); + match result { + Ok(saved_req) => { + println!( + "Saved signature requirement to database with ID: {}", + saved_req.get_id() + ); + } + Err(err) => { + eprintln!("Error saving signature requirement: {}", err) + } + } + } + Err(err) => eprintln!("Error creating signature requirement: {}", err), + } + } + Err(err) => eprintln!("Error creating flow step: {}", err), + } + } + Err(err) => eprintln!("Error creating flow: {}", err), + } + + Ok(()) +} diff --git a/rhailib/_archive/engine/examples/flow/flow_script.rhai b/rhailib/_archive/engine/examples/flow/flow_script.rhai new file mode 100644 index 0000000..a04fa64 --- /dev/null +++ b/rhailib/_archive/engine/examples/flow/flow_script.rhai @@ -0,0 +1,111 @@ +// flow_script.rhai +// Example Rhai script for working with Flow models + +// Constants for Flow status +const STATUS_DRAFT = "draft"; +const STATUS_ACTIVE = "active"; +const STATUS_COMPLETED = "completed"; +const STATUS_CANCELLED = "cancelled"; + +// Create a new flow using builder pattern +let my_flow = new_flow(0, "flow-123"); +name(my_flow, "Document Approval Flow"); +status(my_flow, STATUS_DRAFT); + +print(`Created flow: ${get_flow_name(my_flow)} (ID: ${get_flow_id(my_flow)})`); +print(`Status: ${get_flow_status(my_flow)}`); + +// Create flow steps using builder pattern +let step1 = new_flow_step(0, 1); +description(step1, "Initial review by legal team"); +status(step1, STATUS_DRAFT); + +let step2 = new_flow_step(0, 2); +description(step2, "Approval by department head"); +status(step2, STATUS_DRAFT); + +let step3 = new_flow_step(0, 3); +description(step3, "Final signature by CEO"); +status(step3, STATUS_DRAFT); + +// Create signature requirements using builder pattern +let req1 = new_signature_requirement(0, get_flow_step_id(step1), "legal@example.com", "Please review this document"); +signed_by(req1, "Legal Team"); +status(req1, STATUS_DRAFT); + +let req2 = new_signature_requirement(0, get_flow_step_id(step2), "dept@example.com", "Department approval needed"); +signed_by(req2, "Department Head"); +status(req2, STATUS_DRAFT); + +let req3 = new_signature_requirement(0, get_flow_step_id(step3), "ceo@example.com", "Final approval required"); +signed_by(req3, "CEO"); +status(req3, STATUS_DRAFT); + +print(`Created flow steps with signature requirements`); + +// Add steps to the flow +let flow_with_steps = my_flow; +add_step(flow_with_steps, step1); +add_step(flow_with_steps, step2); +add_step(flow_with_steps, step3); + +print(`Added steps to flow. Flow now has ${get_flow_steps(flow_with_steps).len()} steps`); + +// Activate the flow +let active_flow = flow_with_steps; +status(active_flow, STATUS_ACTIVE); +print(`Updated flow status to: ${get_flow_status(active_flow)}`); + +// Save the flow to the database +let saved_flow = db::save_flow(active_flow); +print(`Flow saved to database with ID: ${get_flow_id(saved_flow)}`); + +// Save signature requirements to the database +let saved_req1 = db::save_signature_requirement(req1); +let saved_req2 = db::save_signature_requirement(req2); +let saved_req3 = db::save_signature_requirement(req3); +print(`Signature requirements saved to database with IDs: ${get_signature_requirement_id(saved_req1)}, ${get_signature_requirement_id(saved_req2)}, ${get_signature_requirement_id(saved_req3)}`); + +// Retrieve the flow from the database +let retrieved_flow = db::get_flow_by_id(get_flow_id(saved_flow)); +print(`Retrieved flow: ${get_flow_name(retrieved_flow)}`); +print(`It has ${get_flow_steps(retrieved_flow).len()} steps`); + +// Complete the flow +let completed_flow = retrieved_flow; +status(completed_flow, STATUS_COMPLETED); +print(`Updated retrieved flow status to: ${get_flow_status(completed_flow)}`); + +// Save the updated flow +db::save_flow(completed_flow); +print("Updated flow saved to database"); + +// List all flows in the database +let all_flows = db::list_flows(); +print("\nListing all flows in database:"); +let flow_count = 0; +for flow in all_flows { + print(` - Flow: ${get_flow_name(flow)} (ID: ${get_flow_id(flow)})`); + flow_count += 1; +} +print(`Total flows: ${flow_count}`); + +// List all signature requirements +let all_reqs = db::list_signature_requirements(); +print("\nListing all signature requirements in database:"); +let req_count = 0; +for req in all_reqs { + print(` - Requirement for step ${get_signature_requirement_flow_step_id(req)} (ID: ${get_signature_requirement_id(req)})`); + req_count += 1; +} +print(`Total signature requirements: ${req_count}`); + +// Clean up - delete the flow +db::delete_flow(get_flow_id(completed_flow)); +print(`Deleted flow with ID: ${get_flow_id(completed_flow)}`); + +// Clean up - delete signature requirements +db::delete_signature_requirement(get_signature_requirement_id(saved_req1)); +db::delete_signature_requirement(get_signature_requirement_id(saved_req2)); +db::delete_signature_requirement(get_signature_requirement_id(saved_req3)); +print("Deleted all signature requirements"); diff --git a/rhailib/_archive/engine/examples/flow/mock.rs b/rhailib/_archive/engine/examples/flow/mock.rs new file mode 100644 index 0000000..661a163 --- /dev/null +++ b/rhailib/_archive/engine/examples/flow/mock.rs @@ -0,0 +1,65 @@ +use heromodels::db::hero::OurDB; +use heromodels::db::{Collection, Db}; +use heromodels::models::flow::{Flow, FlowStep, SignatureRequirement}; +use heromodels_core::Model; +use std::sync::Arc; + +/// Seed the mock database with flow data +#[cfg(feature = "flow")] +pub fn seed_flow_data(db: Arc) { + // Create a flow + let flow = Flow::new(None, "Onboarding Flow".to_string()) + .description("New employee onboarding process".to_string()) + .status("active".to_string()); + + // Create a signature requirement first + let sig_req = SignatureRequirement::new( + None, + 1, + "hr_manager_pubkey".to_string(), + "Please sign the employment contract".to_string(), + ); + let (sig_req_id, saved_sig_req) = db + .collection::() + .expect("Failed to get SignatureRequirement collection") + .set(&sig_req) + .expect("Failed to store signature requirement"); + + // Create a flow step and add the signature requirement + let step = FlowStep::new(None, 1) + .description("Complete HR paperwork".to_string()) + .add_signature_requirement(sig_req_id); + + let (step_id, saved_step) = db + .collection::() + .expect("Failed to get FlowStep collection") + .set(&step) + .expect("Failed to store flow step"); + + // Add the step to the flow + let flow_with_step = flow.add_step(step_id); + + // Store the flow + let (_flow_id, saved_flow) = db + .collection::() + .expect("Failed to get Flow collection") + .set(&flow_with_step) + .expect("Failed to store flow"); + + println!("Mock database seeded with flow data:"); + println!( + " - Added flow: {} (ID: {})", + saved_flow.name, + saved_flow.get_id() + ); + println!( + " - Added step with order: {} (ID: {})", + saved_step.step_order, + saved_step.get_id() + ); + println!( + " - Added signature requirement for: {} (ID: {})", + saved_sig_req.public_key, + saved_sig_req.get_id() + ); +} diff --git a/rhailib/_archive/engine/src/lib.rs b/rhailib/_archive/engine/src/lib.rs new file mode 100644 index 0000000..acc5bdc --- /dev/null +++ b/rhailib/_archive/engine/src/lib.rs @@ -0,0 +1,305 @@ +//! # Rhailib Engine +//! +//! The central Rhai scripting engine for the heromodels ecosystem. This crate provides +//! a unified interface for creating, configuring, and executing Rhai scripts with access +//! to all business domain modules. +//! +//! ## Features +//! +//! - **Unified Engine Creation**: Pre-configured Rhai engine with all DSL modules +//! - **Script Execution Utilities**: Direct evaluation, file-based execution, and AST compilation +//! - **Mock Database System**: Complete testing environment with seeded data +//! - **Feature-Based Architecture**: Modular compilation based on required domains +//! +//! ## Quick Start +//! +//! ```rust +//! use rhailib_engine::{create_heromodels_engine, eval_script}; +//! +//! // Create a fully configured engine +//! let engine = create_heromodels_engine(); +//! +//! // Execute a business logic script +//! let result = eval_script(&engine, r#" +//! let company = new_company() +//! .name("Acme Corp") +//! .business_type("global"); +//! company.name +//! "#)?; +//! +//! println!("Company name: {}", result.as_string().unwrap()); +//! ``` +//! +//! ## Available Features +//! +//! - `calendar` (default): Calendar and event management +//! - `finance` (default): Financial accounts, assets, and marketplace +//! - `flow`: Workflow and approval processes +//! - `legal`: Contract and legal document management +//! - `projects`: Project and task management +//! - `biz`: Business operations and entities + +use rhai::{Engine, EvalAltResult, Scope, AST}; +use rhailib_dsl; +use std::fs; +use std::path::Path; + +/// Mock database module for testing and examples +pub mod mock_db; + +/// Creates a fully configured Rhai engine with all available DSL modules. +/// +/// This function creates a new Rhai engine instance, configures it with appropriate +/// limits and settings, and registers all available business domain modules based +/// on enabled features. +/// +/// # Engine Configuration +/// +/// The engine is configured with the following limits: +/// - **Expression Depth**: 128 levels for both expressions and functions +/// - **String Size**: 10 MB maximum +/// - **Array Size**: 10,000 elements maximum +/// - **Map Size**: 10,000 key-value pairs maximum +/// +/// # Registered Modules +/// +/// All enabled DSL modules are automatically registered, including: +/// - Business operations (companies, products, sales, shareholders) +/// - Financial models (accounts, assets, marketplace) +/// - Content management (collections, images, PDFs, books) +/// - Workflow management (flows, steps, signatures) +/// - And more based on enabled features +/// +/// # Returns +/// +/// A fully configured `Engine` instance ready for script execution. +/// +/// # Example +/// +/// ```rust +/// use rhailib_engine::create_heromodels_engine; +/// +/// let engine = create_heromodels_engine(); +/// +/// // Engine is now ready to execute scripts with access to all DSL functions +/// let result = engine.eval::(r#" +/// let company = new_company().name("Test Corp"); +/// company.name +/// "#).unwrap(); +/// assert_eq!(result, "Test Corp"); +/// ``` +pub fn create_heromodels_engine() -> Engine { + let mut engine = Engine::new(); + + // Configure engine settings + engine.set_max_expr_depths(128, 128); + engine.set_max_string_size(10 * 1024 * 1024); // 10 MB + engine.set_max_array_size(10 * 1024); // 10K elements + engine.set_max_map_size(10 * 1024); // 10K elements + + // Register all heromodels Rhai modules + rhailib_dsl::register_dsl_modules(&mut engine); + + engine +} + +// /// Register all heromodels Rhai modules with the engine +// pub fn register_all_modules(engine: &mut Engine, db: Arc) { +// // Register the calendar module if the feature is enabled +// heromodels::models::access::register_access_rhai_module(engine, db.clone()); +// #[cfg(feature = "calendar")] +// heromodels::models::calendar::register_calendar_rhai_module(engine, db.clone()); +// heromodels::models::contact::register_contact_rhai_module(engine, db.clone()); +// heromodels::models::library::register_library_rhai_module(engine, db.clone()); +// heromodels::models::circle::register_circle_rhai_module(engine, db.clone()); + +// // Register the flow module if the feature is enabled +// #[cfg(feature = "flow")] +// heromodels::models::flow::register_flow_rhai_module(engine, db.clone()); + +// // // Register the finance module if the feature is enabled +// // #[cfg(feature = "finance")] +// // heromodels::models::finance::register_finance_rhai_module(engine, db.clone()); + +// // Register the legal module if the feature is enabled +// #[cfg(feature = "legal")] +// heromodels::models::legal::register_legal_rhai_module(engine, db.clone()); + +// // Register the projects module if the feature is enabled +// #[cfg(feature = "projects")] +// heromodels::models::projects::register_projects_rhai_module(engine, db.clone()); + +// // Register the biz module if the feature is enabled +// #[cfg(feature = "biz")] +// heromodels::models::biz::register_biz_rhai_module(engine, db.clone()); + +// println!("Heromodels Rhai modules registered successfully."); +// } + +/// Evaluates a Rhai script string and returns the result. +/// +/// This function provides a convenient way to execute Rhai script strings directly +/// using the provided engine. It's suitable for one-off script execution or when +/// the script content is dynamically generated. +/// +/// # Arguments +/// +/// * `engine` - The Rhai engine to use for script execution +/// * `script` - The Rhai script content as a string +/// +/// # Returns +/// +/// * `Ok(Dynamic)` - The result of script execution +/// * `Err(Box)` - Script compilation or execution error +/// +/// # Example +/// +/// ```rust +/// use rhailib_engine::{create_heromodels_engine, eval_script}; +/// +/// let engine = create_heromodels_engine(); +/// let result = eval_script(&engine, r#" +/// let x = 42; +/// let y = 8; +/// x + y +/// "#)?; +/// assert_eq!(result.as_int().unwrap(), 50); +/// ``` +pub fn eval_script( + engine: &Engine, + script: &str, +) -> Result> { + engine.eval::(script) +} + +/// Evaluates a Rhai script from a file and returns the result. +/// +/// This function reads a Rhai script from the filesystem and executes it using +/// the provided engine. It handles file reading errors gracefully and provides +/// meaningful error messages. +/// +/// # Arguments +/// +/// * `engine` - The Rhai engine to use for script execution +/// * `file_path` - Path to the Rhai script file +/// +/// # Returns +/// +/// * `Ok(Dynamic)` - The result of script execution +/// * `Err(Box)` - File reading, compilation, or execution error +/// +/// # Example +/// +/// ```rust +/// use rhailib_engine::{create_heromodels_engine, eval_file}; +/// use std::path::Path; +/// +/// let engine = create_heromodels_engine(); +/// let result = eval_file(&engine, Path::new("scripts/business_logic.rhai"))?; +/// println!("Script result: {:?}", result); +/// ``` +/// +/// # Error Handling +/// +/// File reading errors are converted to Rhai `ErrorSystem` variants with +/// descriptive messages including the file path that failed to load. +pub fn eval_file( + engine: &Engine, + file_path: &Path, +) -> Result> { + match fs::read_to_string(file_path) { + Ok(script_content) => engine.eval::(&script_content), + Err(io_err) => Err(Box::new(EvalAltResult::ErrorSystem( + format!("Failed to read script file: {}", file_path.display()), + Box::new(io_err), + ))), + } +} + +/// Compiles a Rhai script string into an Abstract Syntax Tree (AST). +/// +/// This function compiles a Rhai script into an AST that can be executed multiple +/// times with different scopes. This is more efficient than re-parsing the script +/// for each execution when the same script needs to be run repeatedly. +/// +/// # Arguments +/// +/// * `engine` - The Rhai engine to use for compilation +/// * `script` - The Rhai script content as a string +/// +/// # Returns +/// +/// * `Ok(AST)` - The compiled Abstract Syntax Tree +/// * `Err(Box)` - Script compilation error +/// +/// # Example +/// +/// ```rust +/// use rhailib_engine::{create_heromodels_engine, compile_script, run_ast}; +/// use rhai::Scope; +/// +/// let engine = create_heromodels_engine(); +/// let ast = compile_script(&engine, r#" +/// let company = new_company().name(company_name); +/// save_company(company) +/// "#)?; +/// +/// // Execute the compiled script multiple times with different variables +/// let mut scope1 = Scope::new(); +/// scope1.push("company_name", "Acme Corp"); +/// let result1 = run_ast(&engine, &ast, &mut scope1)?; +/// +/// let mut scope2 = Scope::new(); +/// scope2.push("company_name", "Tech Startup"); +/// let result2 = run_ast(&engine, &ast, &mut scope2)?; +/// ``` +pub fn compile_script(engine: &Engine, script: &str) -> Result> { + Ok(engine.compile(script)?) +} + +/// Executes a compiled Rhai script AST with the provided scope. +/// +/// This function runs a pre-compiled AST using the provided engine and scope. +/// The scope can contain variables and functions that will be available to +/// the script during execution. +/// +/// # Arguments +/// +/// * `engine` - The Rhai engine to use for execution +/// * `ast` - The compiled Abstract Syntax Tree to execute +/// * `scope` - Mutable scope containing variables and functions for the script +/// +/// # Returns +/// +/// * `Ok(Dynamic)` - The result of script execution +/// * `Err(Box)` - Script execution error +/// +/// # Example +/// +/// ```rust +/// use rhailib_engine::{create_heromodels_engine, compile_script, run_ast}; +/// use rhai::Scope; +/// +/// let engine = create_heromodels_engine(); +/// let ast = compile_script(&engine, "x + y")?; +/// +/// let mut scope = Scope::new(); +/// scope.push("x", 10_i64); +/// scope.push("y", 32_i64); +/// +/// let result = run_ast(&engine, &ast, &mut scope)?; +/// assert_eq!(result.as_int().unwrap(), 42); +/// ``` +/// +/// # Performance Notes +/// +/// Using compiled ASTs is significantly more efficient than re-parsing scripts +/// for repeated execution, especially for complex scripts or when executing +/// the same logic with different input parameters. +pub fn run_ast( + engine: &Engine, + ast: &AST, + scope: &mut Scope, +) -> Result> { + engine.eval_ast_with_scope(scope, ast) +} diff --git a/rhailib/_archive/engine/src/mock_db.rs b/rhailib/_archive/engine/src/mock_db.rs new file mode 100644 index 0000000..1c1a913 --- /dev/null +++ b/rhailib/_archive/engine/src/mock_db.rs @@ -0,0 +1,374 @@ +use chrono::Utc; +use heromodels::db::hero::OurDB; +use heromodels::db::{Collection, Db}; // Import both Db and Collection traits +use heromodels::models::calendar::{Calendar, Event}; +use heromodels_core::Model; // Import Model trait to use build method +use std::env; +use std::sync::Arc; + +// Import finance models +use heromodels::models::finance::account::Account; +use heromodels::models::finance::asset::{Asset, AssetType}; +use heromodels::models::finance::marketplace::{Listing, ListingType}; + +// Conditionally import other modules based on features +#[cfg(feature = "flow")] +use heromodels::models::flow::{Flow, FlowStep, SignatureRequirement}; + +#[cfg(feature = "legal")] +use heromodels::models::legal::{ + Contract, ContractRevision, ContractSigner, ContractStatus, SignerStatus, +}; + +#[cfg(feature = "projects")] +use heromodels::models::projects::{ItemType, Priority, Project, Status as ProjectStatus}; + +/// Create a mock in-memory database for examples +pub fn create_mock_db() -> Arc { + // Create a temporary directory for the database files + let temp_dir = env::temp_dir().join("engine_examples"); + std::fs::create_dir_all(&temp_dir).expect("Failed to create temp directory"); + + // Create a new OurDB instance with reset=true to ensure it's clean + let db = OurDB::new(temp_dir, true).expect("Failed to create OurDB instance"); + + Arc::new(db) +} + +/// Seed the mock database with some initial data for all modules +pub fn seed_mock_db(db: Arc) { + // Seed calendar data + seed_calendar_data(db.clone()); + + // Seed finance data + seed_finance_data(db.clone()); + + // Seed flow data if the feature is enabled + #[cfg(feature = "flow")] + seed_flow_data(db.clone()); + + // Seed legal data if the feature is enabled + #[cfg(feature = "legal")] + seed_legal_data(db.clone()); + + // Seed projects data if the feature is enabled + #[cfg(feature = "projects")] + seed_projects_data(db.clone()); + + println!("Mock database seeded with initial data for all enabled modules."); +} + +/// Seed the mock database with calendar data +fn seed_calendar_data(db: Arc) { + // Create a calendar + let mut calendar = Calendar::new(None, "Work Calendar".to_string()); + calendar.description = Some("My work schedule".to_string()); + + // Store the calendar in the database + let (_calendar_id, _updated_calendar) = db + .collection::() + .expect("Failed to get Calendar collection") + .set(&calendar) + .expect("Failed to store calendar"); + + // Create an event + let now = Utc::now().timestamp(); + let end_time = now + 3600; // Add 1 hour in seconds + + // Use the builder pattern for Event + let event = Event::new() + .title("Team Meeting".to_string()) + .reschedule(now, end_time) + .location("Conference Room A".to_string()) + .description("Weekly sync".to_string()) + // .add_attendee(Attendee::new(1)) + // .add_attendee(Attendee::new(2)) + .build(); + + // // Add attendees to the event using the builder pattern + // let attendee1 = Attendee::new(1); + // let attendee2 = Attendee::new(2); + + // // Add attendees using the builder pattern + // event = event.add_attendee(attendee1); + // event = event.add_attendee(attendee2); + + // Call build and capture the returned value + // let event = event.build(); + + // Store the event in the database first to get its ID + let (event_id, updated_event) = db + .collection() + .expect("Failed to get Event collection") + .set(&event) + .expect("Failed to store event"); + + // Add the event ID to the calendar + calendar = calendar.add_event(event_id as i64); + + // Store the calendar in the database + let (_calendar_id, updated_calendar) = db + .collection::() + .expect("Failed to get Calendar collection") + .set(&calendar) + .expect("Failed to store calendar"); + + println!("Mock database seeded with calendar data:"); + println!( + " - Added calendar: {} (ID: {})", + updated_calendar.name, updated_calendar.base_data.id + ); + println!( + " - Added event: {} (ID: {})", + updated_event.title, updated_event.base_data.id + ); +} + +/// Seed the mock database with flow data +#[cfg(feature = "flow")] +fn seed_flow_data(db: Arc) { + // Create a flow + let mut flow = Flow::new(0, "Document Approval".to_string()); + + // Set flow properties using the builder pattern + flow = flow.status("draft".to_string()); + flow = flow.name("Document Approval Flow".to_string()); + + // Create flow steps + let mut step1 = FlowStep::new(0, 1); + step1 = step1.description("Initial review by legal team".to_string()); + step1 = step1.status("pending".to_string()); + + let mut step2 = FlowStep::new(0, 2); + step2 = step2.description("Approval by department head".to_string()); + step2 = step2.status("pending".to_string()); + + // Add signature requirements + let mut req1 = SignatureRequirement::new( + 0, + 1, + "Legal Team".to_string(), + "Please review this document".to_string(), + ); + let mut req2 = SignatureRequirement::new( + 0, + 2, + "Department Head".to_string(), + "Please approve this document".to_string(), + ); + + // Add steps to flow + flow = flow.add_step(step1); + flow = flow.add_step(step2); + + // Store in the database + let (_, updated_flow) = db + .collection::() + .expect("Failed to get Flow collection") + .set(&flow) + .expect("Failed to store flow"); + + // Store signature requirements in the database + let (_, updated_req1) = db + .collection::() + .expect("Failed to get SignatureRequirement collection") + .set(&req1) + .expect("Failed to store signature requirement"); + + let (_, updated_req2) = db + .collection::() + .expect("Failed to get SignatureRequirement collection") + .set(&req2) + .expect("Failed to store signature requirement"); + + println!("Mock database seeded with flow data:"); + println!( + " - Added flow: {} (ID: {})", + updated_flow.name, updated_flow.base_data.id + ); + println!(" - Added {} steps", updated_flow.steps.len()); + println!( + " - Added signature requirements with IDs: {} and {}", + updated_req1.base_data.id, updated_req2.base_data.id + ); +} + +/// Seed the mock database with legal data +#[cfg(feature = "legal")] +fn seed_legal_data(db: Arc) { + // Create a contract + let mut contract = Contract::new(None, "Service Agreement".to_string()); + contract.description = Some("Agreement for software development services".to_string()); + contract.status = ContractStatus::Draft; + + // Create a revision + let revision = ContractRevision::new( + None, + "Initial draft".to_string(), + "https://example.com/contract/v1".to_string(), + ); + + // Create signers + let signer1 = ContractSigner::new(None, 1, "Client".to_string()); + let signer2 = ContractSigner::new(None, 2, "Provider".to_string()); + + // Add revision and signers to contract + contract.add_revision(revision); + contract.add_signer(signer1); + contract.add_signer(signer2); + + // Store in the database + let (_, updated_contract) = db + .collection::() + .expect("Failed to get Contract collection") + .set(&contract) + .expect("Failed to store contract"); + + println!("Mock database seeded with legal data:"); + println!( + " - Added contract: {} (ID: {})", + updated_contract.name, updated_contract.base_data.id + ); + println!( + " - Added {} revisions and {} signers", + updated_contract.revisions.len(), + updated_contract.signers.len() + ); +} + +/// Seed the mock database with projects data +#[cfg(feature = "projects")] +fn seed_projects_data(db: Arc) { + // Create a project + let mut project = Project::new(None, "Website Redesign".to_string()); + project.description = Some("Redesign the company website".to_string()); + project.status = ProjectStatus::InProgress; + project.priority = Priority::High; + + // Add members and tags + project.add_member_id(1); + project.add_member_id(2); + project.add_tag("design".to_string()); + project.add_tag("web".to_string()); + + // Store in the database + let (_, updated_project) = db + .collection::() + .expect("Failed to get Project collection") + .set(&project) + .expect("Failed to store project"); + + println!("Mock database seeded with projects data:"); + println!( + " - Added project: {} (ID: {})", + updated_project.name, updated_project.base_data.id + ); + println!( + " - Status: {}, Priority: {}", + updated_project.status, updated_project.priority + ); + println!( + " - Added {} members and {} tags", + updated_project.member_ids.len(), + updated_project.tags.len() + ); +} +/// Seed the mock database with finance data +fn seed_finance_data(db: Arc) { + // Create a user account + let mut account = Account::new() + .name("Demo Account") + .user_id(1) + .description("Demo trading account") + .ledger("ethereum") + .address("0x1234567890abcdef1234567890abcdef12345678") + .pubkey("0xabcdef1234567890abcdef1234567890abcdef12"); + + // Store the account in the database + let (account_id, updated_account) = db + .collection::() + .expect("Failed to get Account collection") + .set(&account) + .expect("Failed to store account"); + + // Create an ERC20 token asset + let token_asset = Asset::new() + .name("HERO Token") + .description("Herocode governance token") + .amount(1000.0) + .address("0x9876543210abcdef9876543210abcdef98765432") + .asset_type(AssetType::Erc20) + .decimals(18); + + // Store the token asset in the database + let (token_id, updated_token) = db + .collection::() + .expect("Failed to get Asset collection") + .set(&token_asset) + .expect("Failed to store token asset"); + + // Create an NFT asset + let nft_asset = Asset::new() + .name("Herocode #1") + .description("Unique digital collectible") + .amount(1.0) + .address("0xabcdef1234567890abcdef1234567890abcdef12") + .asset_type(AssetType::Erc721) + .decimals(0); + + // Store the NFT asset in the database + let (nft_id, updated_nft) = db + .collection::() + .expect("Failed to get Asset collection") + .set(&nft_asset) + .expect("Failed to store NFT asset"); + + // Add assets to the account + account = updated_account.add_asset(token_id); + account = account.add_asset(nft_id); + + // Update the account in the database + let (_, updated_account) = db + .collection::() + .expect("Failed to get Account collection") + .set(&account) + .expect("Failed to store updated account"); + + // Create a listing for the NFT + let listing = Listing::new() + .seller_id(account_id) + .asset_id(nft_id) + .price(0.5) + .currency("ETH") + .listing_type(ListingType::Auction) + .title("Rare Herocode NFT".to_string()) + .description("One of a kind digital collectible".to_string()) + .image_url(Some("hcttps://example.com/nft/1.png".to_string())) + .add_tag("rare".to_string()) + .add_tag("collectible".to_string()); + + // Store the listing in the database + let (_listing_id, updated_listing) = db + .collection::() + .expect("Failed to get Listing collection") + .set(&listing) + .expect("Failed to store listing"); + + println!("Mock database seeded with finance data:"); + println!( + " - Added account: {} (ID: {})", + updated_account.name, updated_account.base_data.id + ); + println!( + " - Added token asset: {} (ID: {})", + updated_token.name, updated_token.base_data.id + ); + println!( + " - Added NFT asset: {} (ID: {})", + updated_nft.name, updated_nft.base_data.id + ); + println!( + " - Added listing: {} (ID: {})", + updated_listing.title, updated_listing.base_data.id + ); +} diff --git a/rhailib/_archive/flow/flow.rs b/rhailib/_archive/flow/flow.rs new file mode 100644 index 0000000..66452b0 --- /dev/null +++ b/rhailib/_archive/flow/flow.rs @@ -0,0 +1,97 @@ +use heromodels::db::Db; +use macros::{ + register_authorized_create_by_id_fn, register_authorized_delete_by_id_fn, + register_authorized_get_by_id_fn, +}; +use rhai::plugin::*; +use rhai::{Array, Dynamic, Engine, EvalAltResult, Module, INT}; +use std::mem; +use std::sync::Arc; + +use heromodels::db::hero::OurDB; +use heromodels::db::Collection; +use heromodels::models::flow::flow::Flow; +use heromodels::models::flow::flow_step::FlowStep; + +type RhaiFlow = Flow; +type RhaiFlowStep = FlowStep; + +#[export_module] +mod rhai_flow_module { + use super::{Array, Dynamic, RhaiFlow, RhaiFlowStep, INT}; + + #[rhai_fn(name = "new_flow", return_raw)] + pub fn new_flow() -> Result> { + Ok(Flow::new()) + } + + // --- Setters --- + #[rhai_fn(name = "name", return_raw)] + pub fn set_name(flow: &mut RhaiFlow, name: String) -> Result> { + let owned = std::mem::take(flow); + *flow = owned.name(name); + Ok(flow.clone()) + } + + #[rhai_fn(name = "status", return_raw)] + pub fn set_status(flow: &mut RhaiFlow, status: String) -> Result> { + let owned = std::mem::take(flow); + *flow = owned.status(status); + Ok(flow.clone()) + } + + #[rhai_fn(name = "add_step", return_raw)] + pub fn add_step( + flow: &mut RhaiFlow, + step: RhaiFlowStep, + ) -> Result> { + let owned = std::mem::take(flow); + *flow = owned.add_step(step); + Ok(flow.clone()) + } + + // --- Getters --- + #[rhai_fn(get = "id", pure)] + pub fn get_id(f: &mut RhaiFlow) -> INT { + f.base_data.id as INT + } + + #[rhai_fn(get = "name", pure)] + pub fn get_name(f: &mut RhaiFlow) -> String { + f.name.clone() + } + #[rhai_fn(get = "status", pure)] + pub fn get_status(f: &mut RhaiFlow) -> String { + f.status.clone() + } + #[rhai_fn(get = "steps", pure)] + pub fn get_steps(f: &mut RhaiFlow) -> Array { + f.steps.clone().into_iter().map(Dynamic::from).collect() + } +} + +pub fn register_flow_rhai_module(engine: &mut Engine) { + engine.build_type::(); + let mut module = exported_module!(rhai_flow_module); + + register_authorized_create_by_id_fn!( + module: &mut module, + rhai_fn_name: "save_flow", + resource_type_str: "Flow", + rhai_return_rust_type: heromodels::models::flow::flow::Flow + ); + register_authorized_get_by_id_fn!( + module: &mut module, + rhai_fn_name: "get_flow", + resource_type_str: "Flow", + rhai_return_rust_type: heromodels::models::flow::flow::Flow + ); + register_authorized_delete_by_id_fn!( + module: &mut module, + rhai_fn_name: "delete_flow", + resource_type_str: "Flow", + rhai_return_rust_type: heromodels::models::flow::flow::Flow + ); + + engine.register_global_module(module.into()); +} diff --git a/rhailib/_archive/flow/flow_step.rs b/rhailib/_archive/flow/flow_step.rs new file mode 100644 index 0000000..ffa7ddb --- /dev/null +++ b/rhailib/_archive/flow/flow_step.rs @@ -0,0 +1,86 @@ +use heromodels::db::Db; +use macros::{ + register_authorized_create_by_id_fn, register_authorized_delete_by_id_fn, + register_authorized_get_by_id_fn, +}; +use rhai::plugin::*; +use rhai::{Dynamic, Engine, EvalAltResult, Module, INT}; +use std::mem; +use std::sync::Arc; + +use heromodels::db::hero::OurDB; +use heromodels::db::Collection; +use heromodels::models::flow::flow_step::FlowStep; + +type RhaiFlowStep = FlowStep; + +#[export_module] +mod rhai_flow_step_module { + use super::{RhaiFlowStep, INT}; + + #[rhai_fn(name = "new_flow_step", return_raw)] + pub fn new_flow_step() -> Result> { + Ok(FlowStep::default()) + } + + // --- Setters --- + #[rhai_fn(name = "description", return_raw)] + pub fn set_description( + step: &mut RhaiFlowStep, + description: String, + ) -> Result> { + let owned = std::mem::take(step); + *step = owned.description(description); + Ok(step.clone()) + } + + #[rhai_fn(name = "status", return_raw)] + pub fn set_status( + step: &mut RhaiFlowStep, + status: String, + ) -> Result> { + let owned = std::mem::take(step); + *step = owned.status(status); + Ok(step.clone()) + } + + // --- Getters --- + #[rhai_fn(get = "id", pure)] + pub fn get_id(s: &mut RhaiFlowStep) -> INT { + s.base_data.id as INT + } + #[rhai_fn(get = "description", pure)] + pub fn get_description(s: &mut RhaiFlowStep) -> Option { + s.description.clone() + } + #[rhai_fn(get = "status", pure)] + pub fn get_status(s: &mut RhaiFlowStep) -> String { + s.status.clone() + } +} + +pub fn register_flow_step_rhai_module(engine: &mut Engine) { + engine.build_type::(); + let mut module = exported_module!(rhai_flow_step_module); + + register_authorized_create_by_id_fn!( + module: &mut module, + rhai_fn_name: "save_flow_step", + resource_type_str: "FlowStep", + rhai_return_rust_type: heromodels::models::flow::flow_step::FlowStep + ); + register_authorized_get_by_id_fn!( + module: &mut module, + rhai_fn_name: "get_flow_step", + resource_type_str: "FlowStep", + rhai_return_rust_type: heromodels::models::flow::flow_step::FlowStep + ); + register_authorized_delete_by_id_fn!( + module: &mut module, + rhai_fn_name: "delete_flow_step", + resource_type_str: "FlowStep", + rhai_return_rust_type: heromodels::models::flow::flow_step::FlowStep + ); + + engine.register_global_module(module.into()); +} diff --git a/rhailib/_archive/flow/mod.rs b/rhailib/_archive/flow/mod.rs new file mode 100644 index 0000000..c8d51f7 --- /dev/null +++ b/rhailib/_archive/flow/mod.rs @@ -0,0 +1,17 @@ +use rhai::Engine; + +pub mod flow; +pub mod flow_step; +pub mod signature_requirement; +pub mod orchestrated_flow; +pub mod orchestrated_flow_step; + +// Re-export the orchestrated models for easy access +pub use orchestrated_flow::{OrchestratedFlow, OrchestratorError, FlowStatus}; +pub use orchestrated_flow_step::OrchestratedFlowStep; + +pub fn register_flow_rhai_modules(engine: &mut Engine) { + flow::register_flow_rhai_module(engine); + flow_step::register_flow_step_rhai_module(engine); + signature_requirement::register_signature_requirement_rhai_module(engine); +} diff --git a/rhailib/_archive/flow/orchestrated_flow.rs b/rhailib/_archive/flow/orchestrated_flow.rs new file mode 100644 index 0000000..754203f --- /dev/null +++ b/rhailib/_archive/flow/orchestrated_flow.rs @@ -0,0 +1,154 @@ +//! Orchestrated Flow model for DAG-based workflow execution + +use heromodels_core::BaseModelData; +use serde::{Deserialize, Serialize}; +use std::collections::HashSet; +use thiserror::Error; + +use super::orchestrated_flow_step::OrchestratedFlowStep; + +/// Extended Flow with orchestrator-specific steps +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct OrchestratedFlow { + /// Base model data (id, created_at, updated_at) + pub base_data: BaseModelData, + + /// Name of the flow + pub name: String, + + /// Orchestrated steps with dependencies + pub orchestrated_steps: Vec, +} + +impl OrchestratedFlow { + /// Create a new orchestrated flow + pub fn new(name: &str) -> Self { + Self { + base_data: BaseModelData::new(), + name: name.to_string(), + orchestrated_steps: Vec::new(), + } + } + + /// Add a step to the flow + pub fn add_step(mut self, step: OrchestratedFlowStep) -> Self { + self.orchestrated_steps.push(step); + self + } + + /// Get the flow ID + pub fn id(&self) -> u32 { + self.base_data.id + } + + /// Validate the DAG structure (no cycles) + pub fn validate_dag(&self) -> Result<(), OrchestratorError> { + let mut visited = HashSet::new(); + let mut rec_stack = HashSet::new(); + + for step in &self.orchestrated_steps { + if !visited.contains(&step.id()) { + if self.has_cycle(step.id(), &mut visited, &mut rec_stack)? { + return Err(OrchestratorError::CyclicDependency); + } + } + } + + Ok(()) + } + + /// Check for cycles in the dependency graph + fn has_cycle( + &self, + step_id: u32, + visited: &mut HashSet, + rec_stack: &mut HashSet, + ) -> Result { + visited.insert(step_id); + rec_stack.insert(step_id); + + let step = self.orchestrated_steps + .iter() + .find(|s| s.id() == step_id) + .ok_or(OrchestratorError::StepNotFound(step_id))?; + + for &dep_id in &step.depends_on { + if !visited.contains(&dep_id) { + if self.has_cycle(dep_id, visited, rec_stack)? { + return Ok(true); + } + } else if rec_stack.contains(&dep_id) { + return Ok(true); + } + } + + rec_stack.remove(&step_id); + Ok(false) + } +} + +/// Orchestrator errors +#[derive(Error, Debug)] +pub enum OrchestratorError { + #[error("Database error: {0}")] + DatabaseError(String), + + #[error("Executor error: {0}")] + ExecutorError(String), + + #[error("No ready steps found - possible deadlock")] + NoReadySteps, + + #[error("Step {0} failed: {1:?}")] + StepFailed(u32, Option), + + #[error("Cyclic dependency detected in workflow")] + CyclicDependency, + + #[error("Step {0} not found")] + StepNotFound(u32), + + #[error("Invalid dependency: step {0} depends on non-existent step {1}")] + InvalidDependency(u32, u32), +} + +/// Flow execution status +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub enum FlowStatus { + Pending, + Running, + Completed, + Failed, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_orchestrated_flow_builder() { + let step1 = OrchestratedFlowStep::new("step1").script("let x = 1;"); + let step2 = OrchestratedFlowStep::new("step2").script("let y = 2;"); + + let flow = OrchestratedFlow::new("test_flow") + .add_step(step1) + .add_step(step2); + + assert_eq!(flow.name, "test_flow"); + assert_eq!(flow.orchestrated_steps.len(), 2); + } + + #[test] + fn test_dag_validation_no_cycle() { + let step1 = OrchestratedFlowStep::new("step1").script("let x = 1;"); + let step2 = OrchestratedFlowStep::new("step2") + .script("let y = 2;") + .depends_on(step1.id()); + + let flow = OrchestratedFlow::new("test_flow") + .add_step(step1) + .add_step(step2); + + assert!(flow.validate_dag().is_ok()); + } +} \ No newline at end of file diff --git a/rhailib/_archive/flow/orchestrated_flow_step.rs b/rhailib/_archive/flow/orchestrated_flow_step.rs new file mode 100644 index 0000000..dc3fcfc --- /dev/null +++ b/rhailib/_archive/flow/orchestrated_flow_step.rs @@ -0,0 +1,124 @@ +//! Orchestrated Flow Step model for DAG-based workflow execution + +use heromodels_core::BaseModelData; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; + +/// Extended FlowStep with orchestrator-specific fields +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct OrchestratedFlowStep { + /// Base model data (id, created_at, updated_at) + pub base_data: BaseModelData, + + /// Name of the flow step + pub name: String, + + /// Rhai script to execute + pub script: String, + + /// IDs of steps this step depends on + pub depends_on: Vec, + + /// Execution context (circle) + pub context_id: String, + + /// Target worker for execution + pub worker_id: String, + + /// Input parameters + pub inputs: HashMap, + + /// Output results + pub outputs: HashMap, +} + +impl OrchestratedFlowStep { + /// Create a new orchestrated flow step + pub fn new(name: &str) -> Self { + Self { + base_data: BaseModelData::new(), + name: name.to_string(), + script: String::new(), + depends_on: Vec::new(), + context_id: String::new(), + worker_id: String::new(), + inputs: HashMap::new(), + outputs: HashMap::new(), + } + } + + /// Set the script content + pub fn script(mut self, script: &str) -> Self { + self.script = script.to_string(); + self + } + + /// Add a dependency on another step + pub fn depends_on(mut self, step_id: u32) -> Self { + self.depends_on.push(step_id); + self + } + + /// Set the context ID + pub fn context_id(mut self, context_id: &str) -> Self { + self.context_id = context_id.to_string(); + self + } + + /// Set the worker ID + pub fn worker_id(mut self, worker_id: &str) -> Self { + self.worker_id = worker_id.to_string(); + self + } + + /// Add an input parameter + pub fn input(mut self, key: &str, value: &str) -> Self { + self.inputs.insert(key.to_string(), value.to_string()); + self + } + + /// Get the step ID + pub fn id(&self) -> u32 { + self.base_data.id + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_orchestrated_flow_step_builder() { + let step = OrchestratedFlowStep::new("test_step") + .script("let x = 1;") + .context_id("test_context") + .worker_id("test_worker") + .input("key1", "value1"); + + assert_eq!(step.name, "test_step"); + assert_eq!(step.script, "let x = 1;"); + assert_eq!(step.context_id, "test_context"); + assert_eq!(step.worker_id, "test_worker"); + assert_eq!(step.inputs.get("key1"), Some(&"value1".to_string())); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_orchestrated_flow_step_builder() { + let step = OrchestratedFlowStep::new("test_step") + .script("let x = 1;") + .context_id("test_context") + .worker_id("test_worker") + .input("key1", "value1"); + + assert_eq!(step.flow_step.name, "test_step"); + assert_eq!(step.script, "let x = 1;"); + assert_eq!(step.context_id, "test_context"); + assert_eq!(step.worker_id, "test_worker"); + assert_eq!(step.inputs.get("key1"), Some(&"value1".to_string())); + } +} \ No newline at end of file diff --git a/rhailib/_archive/flow/signature_requirement.rs b/rhailib/_archive/flow/signature_requirement.rs new file mode 100644 index 0000000..91ef242 --- /dev/null +++ b/rhailib/_archive/flow/signature_requirement.rs @@ -0,0 +1,145 @@ +use heromodels::db::Db; +use macros::{ + register_authorized_create_by_id_fn, register_authorized_delete_by_id_fn, + register_authorized_get_by_id_fn, +}; +use rhai::plugin::*; +use rhai::{Dynamic, Engine, EvalAltResult, Module, INT}; +use std::mem; +use std::sync::Arc; + +use heromodels::db::hero::OurDB; +use heromodels::db::Collection; +use heromodels::models::flow::signature_requirement::SignatureRequirement; + +type RhaiSignatureRequirement = SignatureRequirement; + +#[export_module] +mod rhai_signature_requirement_module { + use super::{RhaiSignatureRequirement, INT}; + + #[rhai_fn(name = "new_signature_requirement", return_raw)] + pub fn new_signature_requirement() -> Result> { + Ok(SignatureRequirement::default()) + } + + // --- Setters --- + #[rhai_fn(name = "flow_step_id", return_raw)] + pub fn set_flow_step_id( + sr: &mut RhaiSignatureRequirement, + flow_step_id: INT, + ) -> Result> { + let mut owned = std::mem::take(sr); + owned.flow_step_id = flow_step_id as u32; + *sr = owned; + Ok(sr.clone()) + } + + #[rhai_fn(name = "public_key", return_raw)] + pub fn set_public_key( + sr: &mut RhaiSignatureRequirement, + public_key: String, + ) -> Result> { + let mut owned = std::mem::take(sr); + owned.public_key = public_key; + *sr = owned; + Ok(sr.clone()) + } + + #[rhai_fn(name = "message", return_raw)] + pub fn set_message( + sr: &mut RhaiSignatureRequirement, + message: String, + ) -> Result> { + let mut owned = std::mem::take(sr); + owned.message = message; + *sr = owned; + Ok(sr.clone()) + } + + #[rhai_fn(name = "signed_by", return_raw)] + pub fn set_signed_by( + sr: &mut RhaiSignatureRequirement, + signed_by: String, + ) -> Result> { + let owned = std::mem::take(sr); + *sr = owned.signed_by(signed_by); + Ok(sr.clone()) + } + + #[rhai_fn(name = "signature", return_raw)] + pub fn set_signature( + sr: &mut RhaiSignatureRequirement, + signature: String, + ) -> Result> { + let owned = std::mem::take(sr); + *sr = owned.signature(signature); + Ok(sr.clone()) + } + + #[rhai_fn(name = "status", return_raw)] + pub fn set_status( + sr: &mut RhaiSignatureRequirement, + status: String, + ) -> Result> { + let owned = std::mem::take(sr); + *sr = owned.status(status); + Ok(sr.clone()) + } + + // --- Getters --- + #[rhai_fn(get = "id", pure)] + pub fn get_id(s: &mut RhaiSignatureRequirement) -> INT { + s.base_data.id as INT + } + #[rhai_fn(get = "flow_step_id", pure)] + pub fn get_flow_step_id(s: &mut RhaiSignatureRequirement) -> INT { + s.flow_step_id as INT + } + #[rhai_fn(get = "public_key", pure)] + pub fn get_public_key(s: &mut RhaiSignatureRequirement) -> String { + s.public_key.clone() + } + #[rhai_fn(get = "message", pure)] + pub fn get_message(s: &mut RhaiSignatureRequirement) -> String { + s.message.clone() + } + #[rhai_fn(get = "signed_by", pure)] + pub fn get_signed_by(s: &mut RhaiSignatureRequirement) -> Option { + s.signed_by.clone() + } + #[rhai_fn(get = "signature", pure)] + pub fn get_signature(s: &mut RhaiSignatureRequirement) -> Option { + s.signature.clone() + } + #[rhai_fn(get = "status", pure)] + pub fn get_status(s: &mut RhaiSignatureRequirement) -> String { + s.status.clone() + } +} + +pub fn register_signature_requirement_rhai_module(engine: &mut Engine) { + engine.build_type::(); + let mut module = exported_module!(rhai_signature_requirement_module); + + register_authorized_create_by_id_fn!( + module: &mut module, + rhai_fn_name: "save_signature_requirement", + resource_type_str: "SignatureRequirement", + rhai_return_rust_type: heromodels::models::flow::signature_requirement::SignatureRequirement + ); + register_authorized_get_by_id_fn!( + module: &mut module, + rhai_fn_name: "get_signature_requirement", + resource_type_str: "SignatureRequirement", + rhai_return_rust_type: heromodels::models::flow::signature_requirement::SignatureRequirement + ); + register_authorized_delete_by_id_fn!( + module: &mut module, + rhai_fn_name: "delete_signature_requirement", + resource_type_str: "SignatureRequirement", + rhai_return_rust_type: heromodels::models::flow::signature_requirement::SignatureRequirement + ); + + engine.register_global_module(module.into()); +} diff --git a/rhailib/_archive/orchestrator/Cargo.toml b/rhailib/_archive/orchestrator/Cargo.toml new file mode 100644 index 0000000..c0925ba --- /dev/null +++ b/rhailib/_archive/orchestrator/Cargo.toml @@ -0,0 +1,51 @@ +[package] +name = "orchestrator" +version = "0.1.0" +edition = "2021" + +[dependencies] +# Core async runtime +tokio = { version = "1", features = ["macros", "rt-multi-thread", "sync", "time"] } +async-trait = "0.1" +futures = "0.3" +futures-util = "0.3" + +# Serialization +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" + +# Error handling +thiserror = "1.0" + +# Collections +uuid = { version = "1.6", features = ["v4", "serde"] } + +# Time handling +chrono = { version = "0.4", features = ["serde"] } + +# HTTP client +reqwest = { version = "0.11", features = ["json"] } + +# WebSocket client +tokio-tungstenite = "0.20" + +# Rhai scripting +rhai = "1.21.0" + +# Database and models +heromodels = { path = "/Users/timurgordon/code/git.ourworld.tf/herocode/db/heromodels" } +heromodels_core = { path = "/Users/timurgordon/code/git.ourworld.tf/herocode/db/heromodels_core" } + +# DSL integration for flow models +rhailib_dsl = { path = "../dsl" } + +# Dispatcher integration +rhai_dispatcher = { path = "../dispatcher" } + +# Logging +log = "0.4" +tracing = "0.1" +tracing-subscriber = "0.3" + +[dev-dependencies] +tokio-test = "0.4" \ No newline at end of file diff --git a/rhailib/_archive/orchestrator/README.md b/rhailib/_archive/orchestrator/README.md new file mode 100644 index 0000000..301659e --- /dev/null +++ b/rhailib/_archive/orchestrator/README.md @@ -0,0 +1,320 @@ +# Rationale for Orchestrator + +We may have scripts that run asynchrounsly, depend on human input or depend on other scripts to complete. We want to be able to implement high-level workflows of rhai scripts. + +## Design + +Direct Acyclic Graphs (DAGs) are a natural fit for representing workflows. + +## Requirements + +1. Uses Direct Acyclic Graphs (DAGs) to represent workflows. +2. Each step in the workflow defines the script to execute, the inputs to pass to it, and the outputs to expect from it. +3. Simplicity: the output cases are binary (success or failure), and params inputted / outputted are simple key-value pairs. +4. Multiple steps can depend on the same step. +5. Scripts are executed using [RhaiDispatcher](../dispatcher/README.md). + +## Architecture + +The Orchestrator is a simple DAG-based workflow execution system that extends the heromodels flow structures to support workflows with dependencies and distributed script execution. + +### Core Component + +```mermaid +graph TB + subgraph "Orchestrator" + O[Orchestrator] --> RE[RhaiExecutor Trait] + O --> DB[(Database)] + end + + subgraph "Executor Implementations" + RE --> RD[RhaiDispatcher] + RE --> WS[WebSocketClient] + RE --> HTTP[HttpClient] + RE --> LOCAL[LocalExecutor] + end + + subgraph "Data Models (heromodels)" + F[Flow] --> FS[FlowStep] + FS --> SR[SignatureRequirement] + end + + subgraph "Infrastructure" + RD --> RQ[Redis Queues] + RD --> W[Workers] + WS --> WSS[WebSocket Server] + HTTP --> API[REST API] + end +``` + +### Execution Abstraction + +The orchestrator uses a trait-based approach for script execution, allowing different execution backends: + +#### RhaiExecutor Trait +```rust +use rhai_dispatcher::{PlayRequestBuilder, RhaiTaskDetails, RhaiDispatcherError}; + +#[async_trait] +pub trait RhaiExecutor { + async fn call(&self, request: PlayRequestBuilder<'_>) -> Result; +} +``` + +#### Executor Implementations + +**RhaiDispatcher Implementation:** +```rust +pub struct DispatcherExecutor { + dispatcher: RhaiDispatcher, +} + +#[async_trait] +impl RhaiExecutor for DispatcherExecutor { + async fn call(&self, request: PlayRequestBuilder<'_>) -> Result { + // Use RhaiDispatcher to execute script via Redis queues + request.await_response().await + } +} +``` + +**WebSocket Client Implementation:** +```rust +pub struct WebSocketExecutor { + ws_client: WebSocketClient, + endpoint: String, +} + +#[async_trait] +impl RhaiExecutor for WebSocketExecutor { + async fn call(&self, request: PlayRequestBuilder<'_>) -> Result { + // Build the PlayRequest and send via WebSocket + let play_request = request.build()?; + + // Send script execution request via WebSocket + let ws_message = serde_json::to_string(&play_request)?; + self.ws_client.send(ws_message).await?; + + // Wait for response and convert to RhaiTaskDetails + let response = self.ws_client.receive().await?; + serde_json::from_str(&response).map_err(RhaiDispatcherError::from) + } +} +``` + +**HTTP Client Implementation:** +```rust +pub struct HttpExecutor { + http_client: reqwest::Client, + base_url: String, +} + +#[async_trait] +impl RhaiExecutor for HttpExecutor { + async fn call(&self, request: PlayRequestBuilder<'_>) -> Result { + // Build the PlayRequest and send via HTTP + let play_request = request.build()?; + + // Send script execution request via HTTP API + let response = self.http_client + .post(&format!("{}/execute", self.base_url)) + .json(&play_request) + .send() + .await?; + + response.json().await.map_err(RhaiDispatcherError::from) + } +} +``` + +**Local Executor Implementation:** +```rust +pub struct LocalExecutor { + engine: Engine, +} + +#[async_trait] +impl RhaiExecutor for LocalExecutor { + async fn call(&self, request: PlayRequestBuilder<'_>) -> Result { + // Build the PlayRequest and execute locally + let play_request = request.build()?; + + // Execute script directly in local Rhai engine + let result = self.engine.eval::(&play_request.script); + + // Convert to RhaiTaskDetails format + let task_details = RhaiTaskDetails { + task_id: play_request.id, + script: play_request.script, + status: if result.is_ok() { "completed".to_string() } else { "error".to_string() }, + output: result.ok(), + error: result.err().map(|e| e.to_string()), + created_at: chrono::Utc::now(), + updated_at: chrono::Utc::now(), + caller_id: "local".to_string(), + context_id: play_request.context_id, + worker_id: "local".to_string(), + }; + + Ok(task_details) + } +} +``` + +### Data Model Extensions + +Simple extensions to the existing heromodels flow structures: + +#### Enhanced FlowStep Model +```rust +// Extends heromodels::models::flow::FlowStep +pub struct FlowStep { + // ... existing heromodels::models::flow::FlowStep fields + pub script: String, // Rhai script to execute + pub depends_on: Vec, // IDs of steps this step depends on + pub context_id: String, // Execution context (circle) + pub inputs: HashMap, // Input parameters + pub outputs: HashMap, // Output results +} +``` + +### Execution Flow + +```mermaid +sequenceDiagram + participant Client as Client + participant O as Orchestrator + participant RE as RhaiExecutor + participant DB as Database + + Client->>O: Submit Flow + O->>DB: Store flow and steps + O->>O: Find steps with no dependencies + + loop Until all steps complete + O->>RE: Execute ready steps + RE-->>O: Return results + O->>DB: Update step status + O->>O: Find newly ready steps + end + + O->>Client: Flow completed +``` + +### Flexible Orchestrator Implementation + +```rust +use rhai_dispatcher::{RhaiDispatcher, PlayRequestBuilder}; +use std::collections::HashSet; + +pub struct Orchestrator { + executor: E, + database: Arc, +} + +impl Orchestrator { + pub fn new(executor: E, database: Arc) -> Self { + Self { executor, database } + } + + pub async fn execute_flow(&self, flow: Flow) -> Result<(), OrchestratorError> { + // 1. Store flow in database + self.database.collection::()?.set(&flow)?; + + // 2. Find steps with no dependencies (depends_on is empty) + let mut pending_steps: Vec = flow.steps.clone(); + let mut completed_steps: HashSet = HashSet::new(); + + while !pending_steps.is_empty() { + // Find ready steps (all dependencies completed) + let ready_steps: Vec = pending_steps + .iter() + .filter(|step| { + step.depends_on.iter().all(|dep_id| completed_steps.contains(dep_id)) + }) + .cloned() + .collect(); + + if ready_steps.is_empty() { + return Err(OrchestratorError::NoReadySteps); + } + + // Execute ready steps concurrently + let mut tasks = Vec::new(); + for step in ready_steps { + let executor = &self.executor; + let task = async move { + // Create PlayRequestBuilder for this step + let request = RhaiDispatcher::new_play_request() + .script(&step.script) + .context_id(&step.context_id) + .worker_id(&step.worker_id); + + // Execute via the trait + let result = executor.call(request).await?; + Ok((step.base_data.id, result)) + }; + tasks.push(task); + } + + // Wait for all ready steps to complete + let results = futures::future::try_join_all(tasks).await?; + + // Update step status and mark as completed + for (step_id, task_details) in results { + if task_details.status == "completed" { + completed_steps.insert(step_id); + // Update step status in database + // self.update_step_status(step_id, "completed", task_details.output).await?; + } else { + return Err(OrchestratorError::StepFailed(step_id, task_details.error)); + } + } + + // Remove completed steps from pending + pending_steps.retain(|step| !completed_steps.contains(&step.base_data.id)); + } + + Ok(()) + } + + pub async fn get_flow_status(&self, flow_id: u32) -> Result { + // Return current status of flow and all its steps + let flow = self.database.collection::()?.get(flow_id)?; + // Implementation would check step statuses and return overall flow status + Ok(FlowStatus::Running) // Placeholder + } +} + +pub enum OrchestratorError { + DatabaseError(String), + ExecutorError(RhaiDispatcherError), + NoReadySteps, + StepFailed(u32, Option), +} + +pub enum FlowStatus { + Pending, + Running, + Completed, + Failed, +} + +// Usage examples: +// let orchestrator = Orchestrator::new(DispatcherExecutor::new(dispatcher), db); +// let orchestrator = Orchestrator::new(WebSocketExecutor::new(ws_client), db); +// let orchestrator = Orchestrator::new(HttpExecutor::new(http_client), db); +// let orchestrator = Orchestrator::new(LocalExecutor::new(engine), db); +``` + +### Key Features + +1. **DAG Validation**: Ensures no circular dependencies exist in the `depends_on` relationships +2. **Parallel Execution**: Executes independent steps concurrently via multiple workers +3. **Simple Dependencies**: Each step lists the step IDs it depends on +4. **RhaiDispatcher Integration**: Uses existing dispatcher for script execution +5. **Binary Outcomes**: Steps either succeed or fail (keeping it simple as per requirements) + +This simple architecture provides DAG-based workflow execution while leveraging the existing rhailib infrastructure and keeping complexity minimal. + + diff --git a/rhailib/_archive/orchestrator/examples/basic_workflow.rs b/rhailib/_archive/orchestrator/examples/basic_workflow.rs new file mode 100644 index 0000000..a1e3bd9 --- /dev/null +++ b/rhailib/_archive/orchestrator/examples/basic_workflow.rs @@ -0,0 +1,283 @@ +//! Basic workflow example demonstrating orchestrator usage + +use orchestrator::{ + interface::LocalInterface, + orchestrator::Orchestrator, + OrchestratedFlow, OrchestratedFlowStep, FlowStatus, +}; +use std::sync::Arc; +use std::collections::HashMap; + +#[tokio::main] +async fn main() -> Result<(), Box> { + // Initialize logging + tracing_subscriber::fmt().init(); + + // Create executor + let executor = Arc::new(LocalInterface::new()); + + // Create orchestrator + let orchestrator = Orchestrator::new(executor); + + println!("🚀 Starting basic workflow example"); + + // Example 1: Simple sequential workflow + println!("\n📋 Example 1: Sequential Workflow"); + let sequential_flow = create_sequential_workflow(); + let flow_id = orchestrator.execute_flow(sequential_flow).await?; + + // Wait for completion and show results + wait_and_show_results(&orchestrator, flow_id, "Sequential").await; + + // Example 2: Parallel workflow with convergence + println!("\n📋 Example 2: Parallel Workflow"); + let parallel_flow = create_parallel_workflow(); + let flow_id = orchestrator.execute_flow(parallel_flow).await?; + + // Wait for completion and show results + wait_and_show_results(&orchestrator, flow_id, "Parallel").await; + + // Example 3: Complex workflow with multiple dependencies + println!("\n📋 Example 3: Complex Workflow"); + let complex_flow = create_complex_workflow(); + let flow_id = orchestrator.execute_flow(complex_flow).await?; + + // Wait for completion and show results + wait_and_show_results(&orchestrator, flow_id, "Complex").await; + + // Clean up completed flows + orchestrator.cleanup_completed_flows().await; + + println!("\n✅ All examples completed successfully!"); + + Ok(()) +} + +/// Create a simple sequential workflow +fn create_sequential_workflow() -> OrchestratedFlow { + let step1 = OrchestratedFlowStep::new("data_preparation") + .script(r#" + let data = [1, 2, 3, 4, 5]; + let sum = 0; + for item in data { + sum += item; + } + let result = sum; + "#) + .context_id("sequential_context") + .worker_id("worker_1"); + + let step2 = OrchestratedFlowStep::new("data_processing") + .script(r#" + let processed_data = dep_1_result * 2; + let result = processed_data; + "#) + .depends_on(step1.id()) + .context_id("sequential_context") + .worker_id("worker_2"); + + let step3 = OrchestratedFlowStep::new("data_output") + .script(r#" + let final_result = "Processed value: " + dep_2_result; + let result = final_result; + "#) + .depends_on(step2.id()) + .context_id("sequential_context") + .worker_id("worker_3"); + + OrchestratedFlow::new("sequential_workflow") + .add_step(step1) + .add_step(step2) + .add_step(step3) +} + +/// Create a parallel workflow with convergence +fn create_parallel_workflow() -> OrchestratedFlow { + let step1 = OrchestratedFlowStep::new("fetch_user_data") + .script(r#" + let user_id = 12345; + let user_name = "Alice"; + let result = user_name; + "#) + .context_id("parallel_context") + .worker_id("user_service"); + + let step2 = OrchestratedFlowStep::new("fetch_order_data") + .script(r#" + let order_id = 67890; + let order_total = 99.99; + let result = order_total; + "#) + .context_id("parallel_context") + .worker_id("order_service"); + + let step3 = OrchestratedFlowStep::new("fetch_inventory_data") + .script(r#" + let product_id = "ABC123"; + let stock_count = 42; + let result = stock_count; + "#) + .context_id("parallel_context") + .worker_id("inventory_service"); + + let step4 = OrchestratedFlowStep::new("generate_report") + .script(r#" + let report = "User: " + dep_1_result + + ", Order Total: $" + dep_2_result + + ", Stock: " + dep_3_result + " units"; + let result = report; + "#) + .depends_on(step1.id()) + .depends_on(step2.id()) + .depends_on(step3.id()) + .context_id("parallel_context") + .worker_id("report_service"); + + OrchestratedFlow::new("parallel_workflow") + .add_step(step1) + .add_step(step2) + .add_step(step3) + .add_step(step4) +} + +/// Create a complex workflow with multiple dependency levels +fn create_complex_workflow() -> OrchestratedFlow { + // Level 1: Initial data gathering + let step1 = OrchestratedFlowStep::new("load_config") + .script(r#" + let config = #{ + api_url: "https://api.example.com", + timeout: 30, + retries: 3 + }; + let result = config.api_url; + "#) + .context_id("complex_context") + .worker_id("config_service"); + + let step2 = OrchestratedFlowStep::new("authenticate") + .script(r#" + let token = "auth_token_12345"; + let expires_in = 3600; + let result = token; + "#) + .context_id("complex_context") + .worker_id("auth_service"); + + // Level 2: Data fetching (depends on config and auth) + let step3 = OrchestratedFlowStep::new("fetch_customers") + .script(r#" + let api_url = dep_1_result; + let auth_token = dep_2_result; + let customers = ["Customer A", "Customer B", "Customer C"]; + let result = customers.len(); + "#) + .depends_on(step1.id()) + .depends_on(step2.id()) + .context_id("complex_context") + .worker_id("customer_service"); + + let step4 = OrchestratedFlowStep::new("fetch_products") + .script(r#" + let api_url = dep_1_result; + let auth_token = dep_2_result; + let products = ["Product X", "Product Y", "Product Z"]; + let result = products.len(); + "#) + .depends_on(step1.id()) + .depends_on(step2.id()) + .context_id("complex_context") + .worker_id("product_service"); + + // Level 3: Data processing (depends on fetched data) + let step5 = OrchestratedFlowStep::new("calculate_metrics") + .script(r#" + let customer_count = dep_3_result; + let product_count = dep_4_result; + let ratio = customer_count / product_count; + let result = ratio; + "#) + .depends_on(step3.id()) + .depends_on(step4.id()) + .context_id("complex_context") + .worker_id("analytics_service"); + + // Level 4: Final reporting + let step6 = OrchestratedFlowStep::new("generate_dashboard") + .script(r#" + let customer_count = dep_3_result; + let product_count = dep_4_result; + let ratio = dep_5_result; + let dashboard = "Dashboard: " + customer_count + " customers, " + + product_count + " products, ratio: " + ratio; + let result = dashboard; + "#) + .depends_on(step3.id()) + .depends_on(step4.id()) + .depends_on(step5.id()) + .context_id("complex_context") + .worker_id("dashboard_service"); + + OrchestratedFlow::new("complex_workflow") + .add_step(step1) + .add_step(step2) + .add_step(step3) + .add_step(step4) + .add_step(step5) + .add_step(step6) +} + +/// Wait for flow completion and show results +async fn wait_and_show_results( + orchestrator: &Orchestrator, + flow_id: u32, + workflow_name: &str, +) { + println!(" ⏳ Executing {} workflow (ID: {})...", workflow_name, flow_id); + + // Poll for completion + loop { + tokio::time::sleep(tokio::time::Duration::from_millis(50)).await; + + if let Some(execution) = orchestrator.get_flow_status(flow_id).await { + match execution.status { + FlowStatus::Completed => { + println!(" ✅ {} workflow completed successfully!", workflow_name); + println!(" 📊 Executed {} steps in {:?}", + execution.completed_steps.len(), + execution.completed_at.unwrap() - execution.started_at); + + // Show step results + for (step_id, outputs) in &execution.step_results { + if let Some(result) = outputs.get("result") { + let step_name = execution.flow.orchestrated_steps + .iter() + .find(|s| s.id() == *step_id) + .map(|s| s.flow_step.name.as_str()) + .unwrap_or("unknown"); + println!(" 📝 Step '{}': {}", step_name, result); + } + } + break; + } + FlowStatus::Failed => { + println!(" ❌ {} workflow failed!", workflow_name); + if !execution.failed_steps.is_empty() { + println!(" 💥 Failed steps: {:?}", execution.failed_steps); + } + break; + } + FlowStatus::Running => { + print!("."); + std::io::Write::flush(&mut std::io::stdout()).unwrap(); + } + FlowStatus::Pending => { + println!(" ⏸️ {} workflow is pending...", workflow_name); + } + } + } else { + println!(" ❓ {} workflow not found!", workflow_name); + break; + } + } +} \ No newline at end of file diff --git a/rhailib/_archive/orchestrator/src/interface/dispatcher.rs b/rhailib/_archive/orchestrator/src/interface/dispatcher.rs new file mode 100644 index 0000000..4452396 --- /dev/null +++ b/rhailib/_archive/orchestrator/src/interface/dispatcher.rs @@ -0,0 +1,61 @@ +//! Dispatcher interface implementation using RhaiDispatcher + +use crate::RhaiInterface; +use async_trait::async_trait; +use rhai_dispatcher::{PlayRequest, RhaiDispatcher, RhaiDispatcherError}; +use std::sync::Arc; + +/// Dispatcher-based interface using RhaiDispatcher +pub struct DispatcherInterface { + dispatcher: Arc, +} + +impl DispatcherInterface { + /// Create a new dispatcher interface + pub fn new(dispatcher: Arc) -> Self { + Self { dispatcher } + } +} + +#[async_trait] +impl RhaiInterface for DispatcherInterface { + async fn submit_play_request(&self, play_request: &PlayRequest) -> Result<(), RhaiDispatcherError> { + self.dispatcher.submit_play_request(play_request).await + } + + async fn submit_play_request_and_await_result(&self, play_request: &PlayRequest) -> Result { + self.dispatcher.submit_play_request_and_await_result(play_request).await + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn test_dispatcher_interface_creation() { + // This test just verifies we can create the interface + // Note: Actual testing would require a properly configured RhaiDispatcher + // For now, we'll create a mock or skip the actual dispatcher creation + + // This is a placeholder test - adjust based on actual RhaiDispatcher constructor + // let dispatcher = Arc::new(RhaiDispatcher::new()); + // let interface = DispatcherInterface::new(dispatcher); + + // Just verify the test compiles for now + assert!(true); + } + + #[tokio::test] + async fn test_dispatcher_interface_methods() { + // This test would verify the interface methods work correctly + // when a proper RhaiDispatcher is available + + let play_request = PlayRequest { + script: "let x = 5; x + 3".to_string(), + }; + + // Placeholder assertions - would test actual functionality with real dispatcher + assert_eq!(play_request.script, "let x = 5; x + 3"); + } +} \ No newline at end of file diff --git a/rhailib/_archive/orchestrator/src/interface/local.rs b/rhailib/_archive/orchestrator/src/interface/local.rs new file mode 100644 index 0000000..09ac7d3 --- /dev/null +++ b/rhailib/_archive/orchestrator/src/interface/local.rs @@ -0,0 +1,111 @@ +//! Local interface implementation for in-process script execution + +use crate::RhaiInterface; +use async_trait::async_trait; +use rhai_dispatcher::{PlayRequest, RhaiDispatcherError}; + +/// Local interface for in-process script execution +pub struct LocalInterface { + engine: rhai::Engine, +} + +impl LocalInterface { + /// Create a new local interface + pub fn new() -> Self { + let engine = rhai::Engine::new(); + Self { engine } + } + + /// Create a new local interface with custom engine + pub fn with_engine(engine: rhai::Engine) -> Self { + Self { engine } + } +} + +impl Default for LocalInterface { + fn default() -> Self { + Self::new() + } +} + +#[async_trait] +impl RhaiInterface for LocalInterface { + async fn submit_play_request(&self, _play_request: &PlayRequest) -> Result<(), RhaiDispatcherError> { + // For local interface, fire-and-forget doesn't make much sense + // We'll just execute and ignore the result + let _ = self.submit_play_request_and_await_result(_play_request).await?; + Ok(()) + } + + async fn submit_play_request_and_await_result(&self, play_request: &PlayRequest) -> Result { + let mut scope = rhai::Scope::new(); + + // Execute the script + let result = self + .engine + .eval_with_scope::(&mut scope, &play_request.script) + .map_err(|e| RhaiDispatcherError::TaskNotFound(format!("Script execution error: {}", e)))?; + + // Return the result as a string + if result.is_unit() { + Ok(String::new()) + } else { + Ok(result.to_string()) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn test_local_interface_basic() { + let interface = LocalInterface::new(); + let play_request = PlayRequest { + script: "let x = 5; x + 3".to_string(), + }; + + let result = interface.submit_play_request_and_await_result(&play_request).await; + assert!(result.is_ok()); + + let output = result.unwrap(); + assert_eq!(output, "8"); + } + + #[tokio::test] + async fn test_local_interface_fire_and_forget() { + let interface = LocalInterface::new(); + let play_request = PlayRequest { + script: "let x = 5; x + 3".to_string(), + }; + + let result = interface.submit_play_request(&play_request).await; + assert!(result.is_ok()); + } + + #[tokio::test] + async fn test_local_interface_with_error() { + let interface = LocalInterface::new(); + let play_request = PlayRequest { + script: "invalid_syntax +++".to_string(), + }; + + let result = interface.submit_play_request_and_await_result(&play_request).await; + assert!(result.is_err()); + } + + #[tokio::test] + async fn test_local_interface_empty_result() { + let interface = LocalInterface::new(); + let play_request = PlayRequest { + script: "let x = 42;".to_string(), + }; + + let result = interface.submit_play_request_and_await_result(&play_request).await; + assert!(result.is_ok()); + + let output = result.unwrap(); + assert_eq!(output, ""); + } +} \ No newline at end of file diff --git a/rhailib/_archive/orchestrator/src/interface/mod.rs b/rhailib/_archive/orchestrator/src/interface/mod.rs new file mode 100644 index 0000000..7111544 --- /dev/null +++ b/rhailib/_archive/orchestrator/src/interface/mod.rs @@ -0,0 +1,9 @@ +//! Interface implementations for different backends + +pub mod local; +pub mod ws; +pub mod dispatcher; + +pub use local::*; +pub use ws::*; +pub use dispatcher::*; \ No newline at end of file diff --git a/rhailib/_archive/orchestrator/src/interface/ws.rs b/rhailib/_archive/orchestrator/src/interface/ws.rs new file mode 100644 index 0000000..9644db3 --- /dev/null +++ b/rhailib/_archive/orchestrator/src/interface/ws.rs @@ -0,0 +1,117 @@ +//! WebSocket interface implementation for remote script execution + +use crate::RhaiInterface; +use async_trait::async_trait; +use rhai_dispatcher::{PlayRequest, RhaiDispatcherError}; +use reqwest::Client; +use serde_json::json; + +/// WebSocket-based interface for remote script execution +pub struct WsInterface { + client: Client, + base_url: String, +} + +impl WsInterface { + /// Create a new WebSocket interface + pub fn new(base_url: String) -> Self { + Self { + client: Client::new(), + base_url, + } + } +} + +#[async_trait] +impl RhaiInterface for WsInterface { + async fn submit_play_request(&self, play_request: &PlayRequest) -> Result<(), RhaiDispatcherError> { + let payload = json!({ + "script": play_request.script + }); + + let response = self + .client + .post(&format!("{}/submit", self.base_url)) + .json(&payload) + .send() + .await + .map_err(|e| RhaiDispatcherError::TaskNotFound(format!("Network error: {}", e)))?; + + if response.status().is_success() { + Ok(()) + } else { + let error_text = response + .text() + .await + .unwrap_or_else(|_| "Unknown error".to_string()); + Err(RhaiDispatcherError::TaskNotFound(format!("HTTP error: {}", error_text))) + } + } + + async fn submit_play_request_and_await_result(&self, play_request: &PlayRequest) -> Result { + let payload = json!({ + "script": play_request.script + }); + + let response = self + .client + .post(&format!("{}/execute", self.base_url)) + .json(&payload) + .send() + .await + .map_err(|e| RhaiDispatcherError::TaskNotFound(format!("Network error: {}", e)))?; + + if response.status().is_success() { + let result: String = response + .text() + .await + .map_err(|e| RhaiDispatcherError::TaskNotFound(format!("Response parsing error: {}", e)))?; + Ok(result) + } else { + let error_text = response + .text() + .await + .unwrap_or_else(|_| "Unknown error".to_string()); + Err(RhaiDispatcherError::TaskNotFound(format!("HTTP error: {}", error_text))) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_ws_interface_creation() { + let interface = WsInterface::new("http://localhost:8080".to_string()); + assert_eq!(interface.base_url, "http://localhost:8080"); + } + + #[tokio::test] + async fn test_ws_interface_call_with_mock_server() { + // This test would require a mock HTTP server + // For now, just test that we can create the interface + let interface = WsInterface::new("http://localhost:8080".to_string()); + + let play_request = PlayRequest { + script: "let x = 1;".to_string(), + }; + + // This will fail without a real server, but that's expected in unit tests + let result = interface.submit_play_request_and_await_result(&play_request).await; + assert!(result.is_err()); // Expected to fail without server + } + + #[tokio::test] + async fn test_ws_interface_fire_and_forget() { + let interface = WsInterface::new("http://localhost:8080".to_string()); + + let play_request = PlayRequest { + script: "let x = 1;".to_string(), + }; + + // This will fail without a real server, but that's expected in unit tests + let result = interface.submit_play_request(&play_request).await; + assert!(result.is_err()); // Expected to fail without server + } +} \ No newline at end of file diff --git a/rhailib/_archive/orchestrator/src/lib.rs b/rhailib/_archive/orchestrator/src/lib.rs new file mode 100644 index 0000000..8f19477 --- /dev/null +++ b/rhailib/_archive/orchestrator/src/lib.rs @@ -0,0 +1,35 @@ +//! # Orchestrator +//! +//! A simple DAG-based workflow execution system that extends the heromodels flow structures +//! to support workflows with dependencies and distributed script execution. + +use async_trait::async_trait; +use rhai_dispatcher::{PlayRequest, RhaiDispatcherError}; + +pub mod interface; +pub mod orchestrator; + +pub use interface::*; +pub use orchestrator::*; + +/// Trait for executing Rhai scripts through different backends +/// Uses the same signature as RhaiDispatcher for consistency +#[async_trait] +pub trait RhaiInterface { + /// Submit a play request without waiting for result (fire-and-forget) + async fn submit_play_request(&self, play_request: &PlayRequest) -> Result<(), RhaiDispatcherError>; + + /// Submit a play request and await the result + /// Returns just the output string on success + async fn submit_play_request_and_await_result(&self, play_request: &PlayRequest) -> Result; +} + +// Re-export the flow models from DSL +pub use rhailib_dsl::flow::{OrchestratedFlow, OrchestratedFlowStep, OrchestratorError, FlowStatus}; + +// Conversion from RhaiDispatcherError to OrchestratorError +impl From for OrchestratorError { + fn from(err: RhaiDispatcherError) -> Self { + OrchestratorError::ExecutorError(err.to_string()) + } +} diff --git a/rhailib/_archive/orchestrator/src/orchestrator.rs b/rhailib/_archive/orchestrator/src/orchestrator.rs new file mode 100644 index 0000000..69bb0b4 --- /dev/null +++ b/rhailib/_archive/orchestrator/src/orchestrator.rs @@ -0,0 +1,418 @@ +//! Main orchestrator implementation for DAG-based workflow execution + +use crate::{ + OrchestratedFlow, OrchestratedFlowStep, OrchestratorError, FlowStatus, RhaiInterface, +}; +use rhai_dispatcher::PlayRequest; +use futures::future::try_join_all; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; +use tokio::sync::RwLock; +use tracing::{debug, error, info, warn}; + +/// Main orchestrator for executing DAG-based workflows +pub struct Orchestrator { + /// Interface for running scripts + interface: Arc, + + /// Active flow executions + active_flows: Arc>>, +} + +/// Represents an active flow execution +#[derive(Debug, Clone)] +pub struct FlowExecution { + /// The flow being executed + pub flow: OrchestratedFlow, + + /// Current status + pub status: FlowStatus, + + /// Completed step IDs + pub completed_steps: HashSet, + + /// Failed step IDs + pub failed_steps: HashSet, + + /// Step results + pub step_results: HashMap>, + + /// Execution start time + pub started_at: chrono::DateTime, + + /// Execution end time + pub completed_at: Option>, +} + +impl FlowExecution { + /// Create a new flow execution + pub fn new(flow: OrchestratedFlow) -> Self { + Self { + flow, + status: FlowStatus::Pending, + completed_steps: HashSet::new(), + failed_steps: HashSet::new(), + step_results: HashMap::new(), + started_at: chrono::Utc::now(), + completed_at: None, + } + } + + /// Check if a step is ready to execute (all dependencies completed) + pub fn is_step_ready(&self, step: &OrchestratedFlowStep) -> bool { + if self.completed_steps.contains(&step.id()) || self.failed_steps.contains(&step.id()) { + return false; + } + + step.depends_on.iter().all(|dep_id| self.completed_steps.contains(dep_id)) + } + + /// Get all ready steps + pub fn get_ready_steps(&self) -> Vec<&OrchestratedFlowStep> { + self.flow + .orchestrated_steps + .iter() + .filter(|step| self.is_step_ready(step)) + .collect() + } + + /// Mark a step as completed + pub fn complete_step(&mut self, step_id: u32, outputs: HashMap) { + self.completed_steps.insert(step_id); + self.step_results.insert(step_id, outputs); + + // Check if flow is complete + if self.completed_steps.len() == self.flow.orchestrated_steps.len() { + self.status = FlowStatus::Completed; + self.completed_at = Some(chrono::Utc::now()); + } + } + + /// Mark a step as failed + pub fn fail_step(&mut self, step_id: u32) { + self.failed_steps.insert(step_id); + self.status = FlowStatus::Failed; + self.completed_at = Some(chrono::Utc::now()); + } + + /// Check if the flow execution is finished + pub fn is_finished(&self) -> bool { + matches!(self.status, FlowStatus::Completed | FlowStatus::Failed) + } +} + +impl Orchestrator { + /// Create a new orchestrator + pub fn new(interface: Arc) -> Self { + Self { + interface, + active_flows: Arc::new(RwLock::new(HashMap::new())), + } + } + + /// Start executing a flow + pub async fn execute_flow(&self, flow: OrchestratedFlow) -> Result { + let flow_id = flow.id(); + flow.validate_dag()?; + + info!("Starting execution of flow {} with {} steps", flow_id, flow.orchestrated_steps.len()); + + // Create flow execution + let mut execution = FlowExecution::new(flow); + execution.status = FlowStatus::Running; + + // Store the execution + { + let mut active_flows = self.active_flows.write().await; + active_flows.insert(flow_id, execution); + } + + // Start execution in background + let orchestrator = self.clone(); + tokio::spawn(async move { + if let Err(e) = orchestrator.execute_flow_steps(flow_id).await { + error!("Flow {} execution failed: {}", flow_id, e); + + // Mark flow as failed + let mut active_flows = orchestrator.active_flows.write().await; + if let Some(execution) = active_flows.get_mut(&flow_id) { + execution.status = FlowStatus::Failed; + execution.completed_at = Some(chrono::Utc::now()); + } + } + }); + + Ok(flow_id) + } + + /// Execute flow steps using DAG traversal + async fn execute_flow_steps(&self, flow_id: u32) -> Result<(), OrchestratorError> { + loop { + let ready_steps = { + let active_flows = self.active_flows.read().await; + let execution = active_flows + .get(&flow_id) + .ok_or(OrchestratorError::StepNotFound(flow_id))?; + + if execution.is_finished() { + info!("Flow {} execution completed with status: {:?}", flow_id, execution.status); + return Ok(()); + } + + execution.get_ready_steps().into_iter().cloned().collect::>() + }; + + if ready_steps.is_empty() { + // Check if we're deadlocked + let active_flows = self.active_flows.read().await; + let execution = active_flows + .get(&flow_id) + .ok_or(OrchestratorError::StepNotFound(flow_id))?; + + if !execution.is_finished() { + warn!("No ready steps found for flow {} - possible deadlock", flow_id); + return Err(OrchestratorError::NoReadySteps); + } + + return Ok(()); + } + + debug!("Executing {} ready steps for flow {}", ready_steps.len(), flow_id); + + // Execute ready steps concurrently + let step_futures = ready_steps.into_iter().map(|step| { + let orchestrator = self.clone(); + async move { + orchestrator.execute_step(flow_id, step).await + } + }); + + // Wait for all steps to complete + let results = try_join_all(step_futures).await?; + + // Update execution state + { + let mut active_flows = self.active_flows.write().await; + let execution = active_flows + .get_mut(&flow_id) + .ok_or(OrchestratorError::StepNotFound(flow_id))?; + + for (step_id, outputs) in results { + execution.complete_step(step_id, outputs); + } + } + + // Small delay to prevent tight loop + tokio::time::sleep(tokio::time::Duration::from_millis(10)).await; + } + } + + /// Execute a single step + async fn execute_step( + &self, + flow_id: u32, + step: OrchestratedFlowStep, + ) -> Result<(u32, HashMap), OrchestratorError> { + let step_id = step.id(); + info!("Executing step {} for flow {}", step_id, flow_id); + + // Prepare inputs with dependency outputs + let mut inputs = step.inputs.clone(); + + // Add outputs from dependency steps + { + let active_flows = self.active_flows.read().await; + let execution = active_flows + .get(&flow_id) + .ok_or(OrchestratorError::StepNotFound(flow_id))?; + + for dep_id in &step.depends_on { + if let Some(dep_outputs) = execution.step_results.get(dep_id) { + for (key, value) in dep_outputs { + inputs.insert(format!("dep_{}_{}", dep_id, key), value.clone()); + } + } + } + } + + // Create play request + let play_request = PlayRequest { + id: format!("{}_{}", flow_id, step_id), + worker_id: step.worker_id.clone(), + context_id: step.context_id.clone(), + script: step.script.clone(), + timeout: std::time::Duration::from_secs(30), // Default timeout + }; + + // Execute the script + match self.interface.submit_play_request_and_await_result(&play_request).await { + Ok(output) => { + info!("Step {} completed successfully", step_id); + let mut outputs = HashMap::new(); + outputs.insert("result".to_string(), output); + Ok((step_id, outputs)) + } + Err(e) => { + error!("Step {} failed: {}", step_id, e); + + // Mark step as failed + { + let mut active_flows = self.active_flows.write().await; + if let Some(execution) = active_flows.get_mut(&flow_id) { + execution.fail_step(step_id); + } + } + + Err(OrchestratorError::StepFailed(step_id, Some(e.to_string()))) + } + } + } + + /// Get the status of a flow execution + pub async fn get_flow_status(&self, flow_id: u32) -> Option { + let active_flows = self.active_flows.read().await; + active_flows.get(&flow_id).cloned() + } + + /// Cancel a flow execution + pub async fn cancel_flow(&self, flow_id: u32) -> Result<(), OrchestratorError> { + let mut active_flows = self.active_flows.write().await; + if let Some(execution) = active_flows.get_mut(&flow_id) { + execution.status = FlowStatus::Failed; + execution.completed_at = Some(chrono::Utc::now()); + info!("Flow {} cancelled", flow_id); + Ok(()) + } else { + Err(OrchestratorError::StepNotFound(flow_id)) + } + } + + /// List all active flows + pub async fn list_active_flows(&self) -> Vec<(u32, FlowStatus)> { + let active_flows = self.active_flows.read().await; + active_flows + .iter() + .map(|(id, execution)| (*id, execution.status.clone())) + .collect() + } + + /// Clean up completed flows + pub async fn cleanup_completed_flows(&self) { + let mut active_flows = self.active_flows.write().await; + active_flows.retain(|_, execution| !execution.is_finished()); + } +} + +impl Clone for Orchestrator { + fn clone(&self) -> Self { + Self { + interface: self.interface.clone(), + active_flows: self.active_flows.clone(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::interface::LocalInterface; + use std::collections::HashMap; + + #[tokio::test] + async fn test_simple_flow_execution() { + let interface = Arc::new(LocalInterface::new()); + let orchestrator = Orchestrator::new(interface); + + // Create a simple flow with two steps + let step1 = OrchestratedFlowStep::new("step1") + .script("let result = 10;") + .context_id("test") + .worker_id("worker1"); + + let step2 = OrchestratedFlowStep::new("step2") + .script("let result = dep_1_result + 5;") + .depends_on(step1.id()) + .context_id("test") + .worker_id("worker1"); + + let flow = OrchestratedFlow::new("test_flow") + .add_step(step1) + .add_step(step2); + + // Execute the flow + let flow_id = orchestrator.execute_flow(flow).await.unwrap(); + + // Wait for completion + tokio::time::sleep(tokio::time::Duration::from_millis(100)).await; + + let status = orchestrator.get_flow_status(flow_id).await.unwrap(); + assert_eq!(status.status, FlowStatus::Completed); + assert_eq!(status.completed_steps.len(), 2); + } + + #[tokio::test] + async fn test_parallel_execution() { + let interface = Arc::new(LocalInterface::new()); + let orchestrator = Orchestrator::new(interface); + + // Create a flow with parallel steps + let step1 = OrchestratedFlowStep::new("step1") + .script("let result = 10;") + .context_id("test") + .worker_id("worker1"); + + let step2 = OrchestratedFlowStep::new("step2") + .script("let result = 20;") + .context_id("test") + .worker_id("worker2"); + + let step3 = OrchestratedFlowStep::new("step3") + .script("let result = dep_1_result + dep_2_result;") + .depends_on(step1.id()) + .depends_on(step2.id()) + .context_id("test") + .worker_id("worker3"); + + let flow = OrchestratedFlow::new("parallel_flow") + .add_step(step1) + .add_step(step2) + .add_step(step3); + + // Execute the flow + let flow_id = orchestrator.execute_flow(flow).await.unwrap(); + + // Wait for completion + tokio::time::sleep(tokio::time::Duration::from_millis(100)).await; + + let status = orchestrator.get_flow_status(flow_id).await.unwrap(); + assert_eq!(status.status, FlowStatus::Completed); + assert_eq!(status.completed_steps.len(), 3); + } + + #[test] + fn test_flow_execution_state() { + let step1 = OrchestratedFlowStep::new("step1").script("let x = 1;"); + let step2 = OrchestratedFlowStep::new("step2") + .script("let y = 2;") + .depends_on(step1.id()); + + let flow = OrchestratedFlow::new("test_flow") + .add_step(step1.clone()) + .add_step(step2.clone()); + + let mut execution = FlowExecution::new(flow); + + // Initially, only step1 should be ready + assert!(execution.is_step_ready(&step1)); + assert!(!execution.is_step_ready(&step2)); + + // After completing step1, step2 should be ready + execution.complete_step(step1.id(), HashMap::new()); + assert!(!execution.is_step_ready(&step1)); // Already completed + assert!(execution.is_step_ready(&step2)); + + // After completing step2, flow should be complete + execution.complete_step(step2.id(), HashMap::new()); + assert_eq!(execution.status, FlowStatus::Completed); + } +} diff --git a/rhailib/_archive/orchestrator/src/services.rs b/rhailib/_archive/orchestrator/src/services.rs new file mode 100644 index 0000000..cc20137 --- /dev/null +++ b/rhailib/_archive/orchestrator/src/services.rs @@ -0,0 +1,42 @@ +//! Main orchestrator implementation for DAG-based workflow execution + +use crate::{ + OrchestratedFlow, OrchestratedFlowStep, OrchestratorError, FlowStatus, RhaiInterface, ScriptRequest, +}; +use futures::future::try_join_all; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; +use tokio::sync::RwLock; +use tracing::{debug, error, info, warn}; + +impl Orchestrator { + /// Get a flow by ID + pub fn get_flow(&self, flow_id: u32) -> Result { + self.interface + .new_play_request() + .script(format!("json_encode(get_flow({}))", flow_id)) + .submit_play_request_and_await_result() + .await + .map(|result| serde_json::from_str(&result).unwrap()) + } + + pub fn get_flows(&self) -> Result, OrchestratorError> { + self.interface + .new_play_request() + .script("json_encode(get_flows())") + .submit_play_request_and_await_result() + .await + .map(|result| serde_json::from_str(&result).unwrap()) + } + + pub fn get_active_flows(&self) -> Result, OrchestratorError> { + self.interface + .new_play_request() + .script("json_encode(get_flows())") + .submit_play_request_and_await_result() + .await + .map(|result| serde_json::from_str(&result).unwrap()) + + } + +} diff --git a/rhailib/_archive/worker/.gitignore b/rhailib/_archive/worker/.gitignore new file mode 100644 index 0000000..6f6c663 --- /dev/null +++ b/rhailib/_archive/worker/.gitignore @@ -0,0 +1,2 @@ +/target +worker_rhai_temp_db \ No newline at end of file diff --git a/rhailib/_archive/worker/Cargo.toml b/rhailib/_archive/worker/Cargo.toml new file mode 100644 index 0000000..f1ebbdb --- /dev/null +++ b/rhailib/_archive/worker/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "rhailib_worker" +version = "0.1.0" +edition = "2021" + +[lib] +name = "rhailib_worker" # Can be different from package name, or same +path = "src/lib.rs" + +[[bin]] +name = "worker" +path = "cmd/worker.rs" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +redis = { version = "0.25.0", features = ["tokio-comp"] } +rhai = { version = "1.18.0", default-features = false, features = ["sync", "decimal", "std"] } # Added "decimal" for broader script support +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] } +log = "0.4" +env_logger = "0.10" +clap = { version = "4.4", features = ["derive"] } +uuid = { version = "1.6", features = ["v4", "serde"] } # Though task_id is string, uuid might be useful +chrono = { version = "0.4", features = ["serde"] } +rhai_dispatcher = { path = "../dispatcher" } +rhailib_engine = { path = "../engine" } +heromodels = { path = "../../../db/heromodels", features = ["rhai"] } diff --git a/rhailib/_archive/worker/README.md b/rhailib/_archive/worker/README.md new file mode 100644 index 0000000..7fdd069 --- /dev/null +++ b/rhailib/_archive/worker/README.md @@ -0,0 +1,75 @@ +# Rhai Worker + +The `rhai_worker` crate implements a standalone worker service that listens for Rhai script execution tasks from a Redis queue, executes them, and posts results back to Redis. It is designed to be spawned as a separate OS process by an orchestrator like the `launcher` crate. + +## Features + +- **Redis Queue Consumption**: Listens to a specific Redis list (acting as a task queue) for incoming task IDs. The queue is determined by the `--circle-public-key` argument. +- **Rhai Script Execution**: Executes Rhai scripts retrieved from Redis based on task IDs. +- **Task State Management**: Updates task status (`processing`, `completed`, `error`) and stores results in Redis hashes. +- **Script Scope Injection**: Automatically injects two important constants into the Rhai script's scope: + - `CONTEXT_ID`: The public key of the worker's own circle. + - `CALLER_ID`: The public key of the entity that requested the script execution. +- **Asynchronous Operations**: Built with `tokio` for non-blocking Redis communication. +- **Graceful Error Handling**: Captures errors during script execution and stores them for the client. + +## Core Components + +- **`worker_lib` (Library Crate)**: + - **`Args`**: A struct (using `clap`) for parsing command-line arguments: `--redis-url` and `--circle-public-key`. + - **`run_worker_loop(engine: Engine, args: Args)`**: The main asynchronous function that: + - Connects to Redis. + - Continuously polls the designated Redis queue (`rhai_tasks:`) using `BLPOP`. + - Upon receiving a `task_id`, it fetches the task details from a Redis hash. + - It injects `CALLER_ID` and `CONTEXT_ID` into the script's scope. + - It executes the script and updates the task status in Redis with the output or error. +- **`worker` (Binary Crate - `cmd/worker.rs`)**: + - The main executable entry point. It parses command-line arguments, initializes a Rhai engine, and invokes `run_worker_loop`. + +## How It Works + +1. The worker executable is launched by an external process (e.g., `launcher`), which passes the required command-line arguments. + ```bash + # This is typically done programmatically by a parent process. + /path/to/worker --redis-url redis://127.0.0.1/ --circle-public-key 02...abc + ``` +2. The `run_worker_loop` connects to Redis and starts listening to its designated task queue (e.g., `rhai_tasks:02...abc`). +3. A `rhai_dispatcher` submits a task by pushing a `task_id` to this queue and storing the script and other details in a Redis hash. +4. The worker's `BLPOP` command picks up the `task_id`. +5. The worker retrieves the script from the corresponding `rhai_task_details:` hash. +6. It updates the task's status to "processing". +7. The Rhai script is executed within a scope that contains both `CONTEXT_ID` and `CALLER_ID`. +8. After execution, the status is updated to "completed" (with output) or "error" (with an error message). +9. The worker then goes back to listening for the next task. + +## Prerequisites + +- A running Redis instance accessible by the worker. +- An orchestrator process (like `launcher`) to spawn the worker. +- A `rhai_dispatcher` (or another system) to populate the Redis queues. + +## Building and Running + +The worker is intended to be built as a dependency and run by another program. + +1. **Build the worker:** + ```bash + # From the root of the rhailib project + cargo build --package worker + ``` + The binary will be located at `target/debug/worker`. + +2. **Running the worker:** + The worker is not typically run manually. The `launcher` crate is responsible for spawning it with the correct arguments. If you need to run it manually for testing, you must provide the required arguments: + ```bash + ./target/debug/worker --redis-url redis://127.0.0.1/ --circle-public-key + ``` + +## Dependencies + +Key dependencies include: +- `redis`: For asynchronous Redis communication. +- `rhai`: The Rhai script engine. +- `clap`: For command-line argument parsing. +- `tokio`: For the asynchronous runtime. +- `log`, `env_logger`: For logging. diff --git a/rhailib/_archive/worker/cmd/README.md b/rhailib/_archive/worker/cmd/README.md new file mode 100644 index 0000000..eb33441 --- /dev/null +++ b/rhailib/_archive/worker/cmd/README.md @@ -0,0 +1,113 @@ +# Rhai Worker Binary + +A command-line worker for executing Rhai scripts from Redis task queues. + +## Binary: `worker` + +### Installation + +Build the binary: +```bash +cargo build --bin worker --release +``` + +### Usage + +```bash +# Basic usage - requires circle public key +worker --circle-public-key + +# Custom Redis URL +worker -c --redis-url redis://localhost:6379/1 + +# Custom worker ID and database path +worker -c --worker-id my_worker --db-path /tmp/worker_db + +# Preserve tasks for debugging/benchmarking +worker -c --preserve-tasks + +# Remove timestamps from logs +worker -c --no-timestamp + +# Increase verbosity +worker -c -v # Debug logging +worker -c -vv # Full debug +worker -c -vvv # Trace logging +``` + +### Command-Line Options + +| Option | Short | Default | Description | +|--------|-------|---------|-------------| +| `--circle-public-key` | `-c` | **Required** | Circle public key to listen for tasks | +| `--redis-url` | `-r` | `redis://localhost:6379` | Redis connection URL | +| `--worker-id` | `-w` | `worker_1` | Unique worker identifier | +| `--preserve-tasks` | | `false` | Preserve task details after completion | +| `--db-path` | | `worker_rhai_temp_db` | Database path for Rhai engine | +| `--no-timestamp` | | `false` | Remove timestamps from log output | +| `--verbose` | `-v` | | Increase verbosity (stackable) | + +### Features + +- **Task Queue Processing**: Listens to Redis queues for Rhai script execution tasks +- **Performance Optimized**: Configured for maximum Rhai engine performance +- **Graceful Shutdown**: Supports shutdown signals for clean termination +- **Flexible Logging**: Configurable verbosity and timestamp control +- **Database Integration**: Uses heromodels for data persistence +- **Task Cleanup**: Optional task preservation for debugging/benchmarking + +### How It Works + +1. **Queue Listening**: Worker listens on Redis queue `rhailib:{circle_public_key}` +2. **Task Processing**: Receives task IDs, fetches task details from Redis +3. **Script Execution**: Executes Rhai scripts with configured engine +4. **Result Handling**: Updates task status and sends results to reply queues +5. **Cleanup**: Optionally cleans up task details after completion + +### Configuration Examples + +#### Development Worker +```bash +# Simple development worker +worker -c dev_circle_123 + +# Development with verbose logging (no timestamps) +worker -c dev_circle_123 -v --no-timestamp +``` + +#### Production Worker +```bash +# Production worker with custom configuration +worker \ + --circle-public-key prod_circle_456 \ + --redis-url redis://redis-server:6379/0 \ + --worker-id prod_worker_1 \ + --db-path /var/lib/worker/db \ + --preserve-tasks +``` + +#### Benchmarking Worker +```bash +# Worker optimized for benchmarking +worker \ + --circle-public-key bench_circle_789 \ + --preserve-tasks \ + --no-timestamp \ + -vv +``` + +### Error Handling + +The worker provides clear error messages for: +- Missing or invalid circle public key +- Redis connection failures +- Script execution errors +- Database access issues + +### Dependencies + +- `rhailib_engine`: Rhai engine with heromodels integration +- `redis`: Redis client for task queue management +- `rhai`: Script execution engine +- `clap`: Command-line argument parsing +- `env_logger`: Logging infrastructure \ No newline at end of file diff --git a/rhailib/_archive/worker/cmd/worker.rs b/rhailib/_archive/worker/cmd/worker.rs new file mode 100644 index 0000000..31a71f0 --- /dev/null +++ b/rhailib/_archive/worker/cmd/worker.rs @@ -0,0 +1,95 @@ +use clap::Parser; +use rhailib_engine::create_heromodels_engine; +use rhailib_worker::spawn_rhai_worker; +use tokio::sync::mpsc; + +#[derive(Parser, Debug)] +#[command(author, version, about, long_about = None)] +struct Args { + /// Worker ID for identification + #[arg(short, long)] + worker_id: String, + + /// Redis URL + #[arg(short, long, default_value = "redis://localhost:6379")] + redis_url: String, + + /// Preserve task details after completion (for benchmarking) + #[arg(long, default_value = "false")] + preserve_tasks: bool, + + /// Root directory for engine database + #[arg(long, default_value = "worker_rhai_temp_db")] + db_path: String, + + /// Disable timestamps in log output + #[arg(long, help = "Remove timestamps from log output")] + no_timestamp: bool, +} + +#[tokio::main] +async fn main() -> Result<(), Box> { + let args = Args::parse(); + + // Configure env_logger with or without timestamps + if args.no_timestamp { + env_logger::Builder::from_default_env() + .format_timestamp(None) + .init(); + } else { + env_logger::init(); + } + + + log::info!("Rhai Worker (binary) starting with performance-optimized engine."); + log::info!( + "Worker ID: {}, Redis: {}", + args.worker_id, + args.redis_url + ); + + let mut engine = create_heromodels_engine(); + + // Performance optimizations for benchmarking + engine.set_max_operations(0); // Unlimited operations for performance testing + engine.set_max_expr_depths(0, 0); // Unlimited expression depth + engine.set_max_string_size(0); // Unlimited string size + engine.set_max_array_size(0); // Unlimited array size + engine.set_max_map_size(0); // Unlimited map size + + // Enable full optimization for maximum performance + engine.set_optimization_level(rhai::OptimizationLevel::Full); + + log::info!("Engine configured for maximum performance"); + + // Create shutdown channel (for graceful shutdown, though not used in benchmarks) + let (_shutdown_tx, shutdown_rx) = mpsc::channel::<()>(1); + + // Spawn the worker + let worker_handle = spawn_rhai_worker( + args.worker_id, + args.db_path, + engine, + args.redis_url, + shutdown_rx, + args.preserve_tasks, + ); + + // Wait for the worker to complete + match worker_handle.await { + Ok(result) => match result { + Ok(_) => { + log::info!("Worker completed successfully"); + Ok(()) + } + Err(e) => { + log::error!("Worker failed: {}", e); + Err(e) + } + }, + Err(e) => { + log::error!("Worker task panicked: {}", e); + Err(Box::new(e) as Box) + } + } +} diff --git a/rhailib/_archive/worker/docs/ARCHITECTURE.md b/rhailib/_archive/worker/docs/ARCHITECTURE.md new file mode 100644 index 0000000..6b19872 --- /dev/null +++ b/rhailib/_archive/worker/docs/ARCHITECTURE.md @@ -0,0 +1,53 @@ +# Architecture of the `rhailib_worker` Crate + +The `rhailib_worker` crate implements a distributed task execution system for Rhai scripts, providing scalable, reliable script processing through Redis-based task queues. Workers are decoupled from contexts, allowing a single worker to process tasks for multiple contexts (circles). + +## Core Architecture + +```mermaid +graph TD + A[Worker Process] --> B[Task Queue Processing] + A --> C[Script Execution Engine] + A --> D[Result Management] + + B --> B1[Redis Queue Monitoring] + B --> B2[Task Deserialization] + B --> B3[Priority Handling] + + C --> C1[Rhai Engine Integration] + C --> C2[Context Management] + C --> C3[Error Handling] + + D --> D1[Result Serialization] + D --> D2[Reply Queue Management] + D --> D3[Status Updates] +``` + +## Key Components + +### Task Processing Pipeline +- **Queue Monitoring**: Continuous Redis queue polling for new tasks +- **Task Execution**: Secure Rhai script execution with proper context +- **Result Handling**: Comprehensive result and error management + +### Engine Integration +- **Rhailib Engine**: Full integration with rhailib_engine for DSL access +- **Context Injection**: Proper authentication and database context setup +- **Security**: Isolated execution environment with access controls + +### Scalability Features +- **Horizontal Scaling**: Multiple worker instances for load distribution +- **Queue-based Architecture**: Reliable task distribution via Redis +- **Fault Tolerance**: Robust error handling and recovery mechanisms + +## Dependencies + +- **Redis Integration**: Task queue management and communication +- **Rhai Engine**: Script execution with full DSL capabilities +- **Client Integration**: Shared data structures with rhai_dispatcher +- **Heromodels**: Database and business logic integration +- **Async Runtime**: Tokio for high-performance concurrent processing + +## Deployment Patterns + +Workers can be deployed as standalone processes, containerized services, or embedded components, providing flexibility for various deployment scenarios from development to production. \ No newline at end of file diff --git a/rhailib/_archive/worker/src/lib.rs b/rhailib/_archive/worker/src/lib.rs new file mode 100644 index 0000000..57e4368 --- /dev/null +++ b/rhailib/_archive/worker/src/lib.rs @@ -0,0 +1,259 @@ +use chrono::Utc; +use log::{debug, error, info}; +use redis::AsyncCommands; +use rhai::{Dynamic, Engine}; +use rhai_dispatcher::RhaiTaskDetails; // Import for constructing the reply message +use serde_json; +use std::collections::HashMap; +use tokio::sync::mpsc; // For shutdown signal +use tokio::task::JoinHandle; // For serializing the reply message + +const NAMESPACE_PREFIX: &str = "rhailib:"; +const BLPOP_TIMEOUT_SECONDS: usize = 5; + +// This function updates specific fields in the Redis hash. +// It doesn't need to know the full RhaiTaskDetails struct, only the field names. +async fn update_task_status_in_redis( + conn: &mut redis::aio::MultiplexedConnection, + task_id: &str, + status: &str, + output: Option, + error_msg: Option, +) -> redis::RedisResult<()> { + let task_key = format!("{}{}", NAMESPACE_PREFIX, task_id); + let mut updates: Vec<(&str, String)> = vec![ + ("status", status.to_string()), + ("updatedAt", Utc::now().timestamp().to_string()), + ]; + if let Some(out) = output { + updates.push(("output", out)); + } + if let Some(err) = error_msg { + updates.push(("error", err)); + } + debug!( + "Updating task {} in Redis with status: {}, updates: {:?}", + task_id, status, updates + ); + conn.hset_multiple::<_, _, _, ()>(&task_key, &updates) + .await?; + Ok(()) +} + +pub fn spawn_rhai_worker( + worker_id: String, + db_path: String, + mut engine: Engine, + redis_url: String, + mut shutdown_rx: mpsc::Receiver<()>, // Add shutdown receiver + preserve_tasks: bool, // Flag to control task cleanup +) -> JoinHandle>> { + tokio::spawn(async move { + let queue_key = format!("{}{}", NAMESPACE_PREFIX, worker_id); + info!( + "Rhai Worker for Worker ID '{}' starting. Connecting to Redis at {}. Listening on queue: {}. Waiting for tasks or shutdown signal.", + worker_id, redis_url, queue_key + ); + + let redis_client = match redis::Client::open(redis_url.as_str()) { + Ok(client) => client, + Err(e) => { + error!( + "Worker for Worker ID '{}': Failed to open Redis client: {}", + worker_id, e + ); + return Err(Box::new(e) as Box); + } + }; + let mut redis_conn = match redis_client.get_multiplexed_async_connection().await { + Ok(conn) => conn, + Err(e) => { + error!( + "Worker for Worker ID '{}': Failed to get Redis connection: {}", + worker_id, e + ); + return Err(Box::new(e) as Box); + } + }; + info!( + "Worker for Worker ID '{}' successfully connected to Redis.", + worker_id + ); + + loop { + let blpop_keys = vec![queue_key.clone()]; + tokio::select! { + // Listen for shutdown signal + _ = shutdown_rx.recv() => { + info!("Worker for Worker ID '{}': Shutdown signal received. Terminating loop.", worker_id.clone()); + break; + } + // Listen for tasks from Redis + blpop_result = redis_conn.blpop(&blpop_keys, BLPOP_TIMEOUT_SECONDS as f64) => { + debug!("Worker for Worker ID '{}': Attempting BLPOP on queue: {}", worker_id.clone(), queue_key); + let response: Option<(String, String)> = match blpop_result { + Ok(resp) => resp, + Err(e) => { + error!("Worker '{}': Redis BLPOP error on queue {}: {}. Worker for this circle might stop.", worker_id, queue_key, e); + return Err(Box::new(e) as Box); + } + }; + + if let Some((_queue_name_recv, task_id)) = response { + info!("Worker '{}' received task_id: {} from queue: {}", worker_id, task_id, _queue_name_recv); + debug!("Worker '{}', Task {}: Processing started.", worker_id, task_id); + + let task_details_key = format!("{}{}", NAMESPACE_PREFIX, task_id); + debug!("Worker '{}', Task {}: Attempting HGETALL from key: {}", worker_id, task_id, task_details_key); + + let task_details_map_result: Result, _> = + redis_conn.hgetall(&task_details_key).await; + + match task_details_map_result { + Ok(details_map) => { + debug!("Worker '{}', Task {}: HGETALL successful. Details: {:?}", worker_id, task_id, details_map); + let script_content_opt = details_map.get("script").cloned(); + let created_at_str_opt = details_map.get("createdAt").cloned(); + let caller_id = details_map.get("callerId").cloned().expect("callerId field missing from Redis hash"); + + let context_id = details_map.get("contextId").cloned().expect("contextId field missing from Redis hash"); + if context_id.is_empty() { + error!("Worker '{}', Task {}: contextId field missing from Redis hash", worker_id, task_id); + return Err("contextId field missing from Redis hash".into()); + } + if caller_id.is_empty() { + error!("Worker '{}', Task {}: callerId field missing from Redis hash", worker_id, task_id); + return Err("callerId field missing from Redis hash".into()); + } + + if let Some(script_content) = script_content_opt { + info!("Worker '{}' processing task_id: {}. Script: {:.50}...", context_id, task_id, script_content); + debug!("Worker for Context ID '{}', Task {}: Attempting to update status to 'processing'.", context_id, task_id); + if let Err(e) = update_task_status_in_redis(&mut redis_conn, &task_id, "processing", None, None).await { + error!("Worker for Context ID '{}', Task {}: Failed to update status to 'processing': {}", context_id, task_id, e); + } else { + debug!("Worker for Context ID '{}', Task {}: Status updated to 'processing'.", context_id, task_id); + } + + let mut db_config = rhai::Map::new(); + db_config.insert("DB_PATH".into(), db_path.clone().into()); + db_config.insert("CALLER_ID".into(), caller_id.clone().into()); + db_config.insert("CONTEXT_ID".into(), context_id.clone().into()); + engine.set_default_tag(Dynamic::from(db_config)); // Or pass via CallFnOptions + + debug!("Worker for Context ID '{}', Task {}: Evaluating script with Rhai engine.", context_id, task_id); + + let mut final_status = "error".to_string(); // Default to error + let mut final_output: Option = None; + let mut final_error_msg: Option = None; + + match engine.eval::(&script_content) { + Ok(result) => { + let output_str = if result.is::() { + // If the result is a string, we can unwrap it directly. + // This moves `result`, which is fine because it's the last time we use it in this branch. + result.into_string().unwrap() + } else { + result.to_string() + }; + info!("Worker for Context ID '{}' task {} completed. Output: {}", context_id, task_id, output_str); + final_status = "completed".to_string(); + final_output = Some(output_str); + } + Err(e) => { + let error_str = format!("{:?}", *e); + error!("Worker for Context ID '{}' task {} script evaluation failed. Error: {}", context_id, task_id, error_str); + final_error_msg = Some(error_str); + // final_status remains "error" + } + } + + debug!("Worker for Context ID '{}', Task {}: Attempting to update status to '{}'.", context_id, task_id, final_status); + if let Err(e) = update_task_status_in_redis( + &mut redis_conn, + &task_id, + &final_status, + final_output.clone(), // Clone for task hash update + final_error_msg.clone(), // Clone for task hash update + ).await { + error!("Worker for Context ID '{}', Task {}: Failed to update final status to '{}': {}", context_id, task_id, final_status, e); + } else { + debug!("Worker for Context ID '{}', Task {}: Final status updated to '{}'.", context_id, task_id, final_status); + } + + // Send to reply queue if specified + + let created_at = created_at_str_opt + .and_then(|s| chrono::DateTime::parse_from_rfc3339(&s).ok()) + .map(|dt| dt.with_timezone(&Utc)) + .unwrap_or_else(Utc::now); // Fallback, though createdAt should exist + + let reply_details = RhaiTaskDetails { + task_id: task_id.to_string(), // Add the task_id + script: script_content.clone(), // Include script for context in reply + status: final_status, // The final status + output: final_output, // The final output + error: final_error_msg, // The final error + created_at, // Original creation time + updated_at: Utc::now(), // Time of this final update/reply + caller_id: caller_id.clone(), + context_id: context_id.clone(), + worker_id: worker_id.clone(), + }; + let reply_queue_key = format!("{}:reply:{}", NAMESPACE_PREFIX, task_id); + match serde_json::to_string(&reply_details) { + Ok(reply_json) => { + let lpush_result: redis::RedisResult = redis_conn.lpush(&reply_queue_key, &reply_json).await; + match lpush_result { + Ok(_) => debug!("Worker for Context ID '{}', Task {}: Successfully sent result to reply queue {}", context_id, task_id, reply_queue_key), + Err(e_lpush) => error!("Worker for Context ID '{}', Task {}: Failed to LPUSH result to reply queue {}: {}", context_id, task_id, reply_queue_key, e_lpush), + } + } + Err(e_json) => { + error!("Worker for Context ID '{}', Task {}: Failed to serialize reply details for queue {}: {}", context_id, task_id, reply_queue_key, e_json); + } + } + // Clean up task details based on preserve_tasks flag + if !preserve_tasks { + // The worker is responsible for cleaning up the task details hash. + if let Err(e) = redis_conn.del::<_, ()>(&task_details_key).await { + error!("Worker for Context ID '{}', Task {}: Failed to delete task details key '{}': {}", context_id, task_id, task_details_key, e); + } else { + debug!("Worker for Context ID '{}', Task {}: Cleaned up task details key '{}'.", context_id, task_id, task_details_key); + } + } else { + debug!("Worker for Context ID '{}', Task {}: Preserving task details (preserve_tasks=true)", context_id, task_id); + } + } else { // Script content not found in hash + error!( + "Worker for Context ID '{}', Task {}: Script content not found in Redis hash. Details map: {:?}", + context_id, task_id, details_map + ); + // Clean up invalid task details based on preserve_tasks flag + if !preserve_tasks { + // Even if the script is not found, the worker should clean up the invalid task hash. + if let Err(e) = redis_conn.del::<_, ()>(&task_details_key).await { + error!("Worker for Context ID '{}', Task {}: Failed to delete invalid task details key '{}': {}", context_id, task_id, task_details_key, e); + } + } else { + debug!("Worker for Context ID '{}', Task {}: Preserving invalid task details (preserve_tasks=true)", context_id, task_id); + } + } + } + Err(e) => { + error!( + "Worker '{}', Task {}: Failed to fetch details (HGETALL) from Redis for key {}. Error: {:?}", + worker_id, task_id, task_details_key, e + ); + } + } + } else { + debug!("Worker '{}': BLPOP timed out on queue {}. No new tasks. Checking for shutdown signal again.", &worker_id, &queue_key); + } + } // End of blpop_result match + } // End of tokio::select! + } // End of loop + info!("Worker '{}' has shut down.", worker_id); + Ok(()) + }) +} diff --git a/rhailib/benches/simple_rhai_bench/README.md b/rhailib/benches/simple_rhai_bench/README.md new file mode 100644 index 0000000..1e52197 --- /dev/null +++ b/rhailib/benches/simple_rhai_bench/README.md @@ -0,0 +1,71 @@ +# Minimal Rhailib Benchmark + +A simplified, minimal benchmarking tool for rhailib performance testing. + +## Overview + +This benchmark focuses on simplicity and direct timing measurements: +- Creates a single task (n=1) using Lua script +- Measures latency using Redis timestamps +- Uses existing worker binary +- ~85 lines of code total + +## Usage + +### Prerequisites +- Redis running on `127.0.0.1:6379` +- Worker binary built: `cd src/worker && cargo build --release` + +### Run Benchmark +```bash +# From project root +cargo bench +``` + +### Expected Output +``` +🧹 Cleaning up Redis... +🚀 Starting worker... +📝 Creating single task... +⏱️ Waiting for completion... +✅ Task completed in 23.45ms +🧹 Cleaning up... +``` + +## Files + +- `simple_bench.rs` - Main benchmark binary (85 lines) +- `batch_task.lua` - Minimal Lua script for task creation (28 lines) +- `Cargo.toml` - Dependencies and binary configuration +- `README.md` - This file + +## How It Works + +1. **Cleanup**: Clear Redis queues and task details +2. **Start Worker**: Spawn single worker process +3. **Create Task**: Use Lua script to create one task with timestamp +4. **Wait & Measure**: Poll task until complete, calculate latency +5. **Cleanup**: Kill worker and clear Redis + +## Latency Calculation + +``` +latency_ms = updated_at - created_at +``` + +Where: +- `created_at`: Timestamp when task was created (Lua script) +- `updated_at`: Timestamp when worker completed task + +## Future Iterations + +- **Iteration 2**: Small batches (n=5, n=10) +- **Iteration 3**: Larger batches and script complexity +- **Iteration 4**: Performance optimizations + +## Benefits + +- **Easy to Understand**: Single file, linear flow +- **Direct Timing**: Redis timestamps, no complex stats +- **Fast to Modify**: No abstractions or frameworks +- **Reliable**: Simple Redis operations \ No newline at end of file diff --git a/rhailib/benches/simple_rhai_bench/batch_task.lua b/rhailib/benches/simple_rhai_bench/batch_task.lua new file mode 100644 index 0000000..f639aeb --- /dev/null +++ b/rhailib/benches/simple_rhai_bench/batch_task.lua @@ -0,0 +1,46 @@ +-- Minimal Lua script for single task creation (n=1) +-- Args: circle_name, rhai_script_content, task_count (optional, defaults to 1) +-- Returns: array of task keys for timing + +if #ARGV < 2 then + return redis.error_reply("Usage: EVAL script 0 circle_name rhai_script_content [task_count]") +end + +local circle_name = ARGV[1] +local rhai_script_content = ARGV[2] +local task_count = tonumber(ARGV[3]) or 1 + +-- Validate task_count +if task_count <= 0 or task_count > 10000 then + return redis.error_reply("task_count must be a positive integer between 1 and 10000") +end + +-- Get current timestamp in Unix seconds (to match worker expectations) +local rhai_task_queue = 'rhai_tasks:' .. circle_name +local task_keys = {} +local current_time = redis.call('TIME')[1] + +-- Create multiple tasks +for i = 1, task_count do + -- Generate unique task ID + local task_id = 'task_' .. redis.call('INCR', 'global_task_counter') + local task_details_key = 'rhai_task_details:' .. task_id + + -- Create task details hash with creation timestamp + redis.call('HSET', task_details_key, + 'script', rhai_script_content, + 'status', 'pending', + 'createdAt', current_time, + 'updatedAt', current_time, + 'task_sequence', tostring(i) + ) + + -- Queue the task for workers + redis.call('LPUSH', rhai_task_queue, task_id) + + -- Add key to return array + table.insert(task_keys, task_details_key) +end + +-- Return array of task keys for timing analysis +return task_keys \ No newline at end of file diff --git a/rhailib/benches/simple_rhai_bench/main.rs b/rhailib/benches/simple_rhai_bench/main.rs new file mode 100644 index 0000000..05f2a53 --- /dev/null +++ b/rhailib/benches/simple_rhai_bench/main.rs @@ -0,0 +1,183 @@ +use criterion::{criterion_group, criterion_main, Criterion}; +use redis::{Client, Commands}; +use std::fs; +use std::process::{Child, Command, Stdio}; +use std::thread; +use std::time::Duration; + +const REDIS_URL: &str = "redis://127.0.0.1:6379"; +const CIRCLE_NAME: &str = "bench_circle"; +const SIMPLE_SCRIPT: &str = "new_event()\n .title(\"Weekly Sync\")\n .location(\"Conference Room A\")\n .description(\"Regular team sync meeting\")\n .save_event();"; + +fn cleanup_redis() -> Result<(), redis::RedisError> { + let client = Client::open(REDIS_URL)?; + let mut conn = client.get_connection()?; + + // Clear task queue and any existing task details + let _: () = conn.del(format!("rhai_tasks:{}", CIRCLE_NAME))?; + let keys: Vec = conn.scan_match("rhai_task_details:*")?.collect(); + if !keys.is_empty() { + let _: () = conn.del(keys)?; + } + + Ok(()) +} + +fn start_worker() -> Result { + Command::new("cargo") + .args(&[ + "run", + "--release", + "--bin", + "worker", + "--", + "--circle", + CIRCLE_NAME, + "--redis-url", + REDIS_URL, + "--worker-id", + "bench_worker", + "--preserve-tasks", + ]) + .current_dir("src/worker") + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() +} + +fn create_batch_tasks(task_count: usize) -> Result, Box> { + let client = Client::open(REDIS_URL)?; + let mut conn = client.get_connection()?; + + // Load and execute Lua script + let lua_script = fs::read_to_string("benches/simple_rhai_bench/batch_task.lua")?; + let result: redis::Value = redis::cmd("EVAL") + .arg(lua_script) + .arg(0) + .arg(CIRCLE_NAME) + .arg(SIMPLE_SCRIPT) + .arg(task_count) + .query(&mut conn)?; + + // Parse the task keys from the response + let task_keys = match result { + redis::Value::Bulk(items) => { + let mut keys = Vec::new(); + for item in items { + if let redis::Value::Data(key_data) = item { + keys.push(String::from_utf8_lossy(&key_data).to_string()); + } + } + keys + } + _ => { + return Err(format!("Unexpected Redis response type: {:?}", result).into()); + } + }; + + Ok(task_keys) +} + +fn wait_for_batch_completion(task_keys: &[String]) -> Result> { + let client = Client::open(REDIS_URL)?; + let mut conn = client.get_connection()?; + + let start_time = std::time::Instant::now(); + let timeout = Duration::from_secs(30); + + // Wait for all tasks to complete + loop { + let mut completed_count = 0; + let mut total_latency = 0u64; + + for task_key in task_keys { + let status: Option = conn.hget(task_key, "status")?; + + match status.as_deref() { + Some("completed") | Some("error") => { + completed_count += 1; + + // Get timing data + let created_at: u64 = conn.hget(task_key, "createdAt")?; + let updated_at: u64 = conn.hget(task_key, "updatedAt")?; + total_latency += updated_at - created_at; + } + _ => {} // Still pending or processing + } + } + + if completed_count == task_keys.len() { + // All tasks completed, calculate average latency in milliseconds + let avg_latency_ms = (total_latency as f64 / task_keys.len() as f64) * 1000.0; + return Ok(avg_latency_ms); + } + + // Check timeout + if start_time.elapsed() > timeout { + return Err(format!( + "Timeout waiting for batch completion. Completed: {}/{}", + completed_count, + task_keys.len() + ) + .into()); + } + + thread::sleep(Duration::from_millis(100)); + } +} + +fn cleanup_worker(mut worker: Child) -> Result<(), std::io::Error> { + worker.kill()?; + worker.wait()?; + Ok(()) +} + +fn bench_single_rhai_task(c: &mut Criterion) { + // Setup: ensure worker is built + let _ = Command::new("cargo") + .args(&["build", "--release", "--bin", "worker"]) + .current_dir("src/worker") + .output() + .expect("Failed to build worker"); + + // Clean up before starting + cleanup_redis().expect("Failed to cleanup Redis"); + + // Start worker once and reuse it + let worker = start_worker().expect("Failed to start worker"); + thread::sleep(Duration::from_millis(1000)); // Give worker time to start + + let mut group = c.benchmark_group("rhai_task_execution"); + group.sample_size(10); // Reduce sample size + group.measurement_time(Duration::from_secs(10)); // Reduce measurement time + + group.bench_function("batch_task_latency", |b| { + b.iter_custom(|iters| { + let mut total_latency = Duration::ZERO; + + for _i in 0..iters { + // Clean up Redis between iterations + cleanup_redis().expect("Failed to cleanup Redis"); + + // Create 100 tasks and measure average latency using Redis timestamps + let task_keys = create_batch_tasks(5000).expect("Failed to create batch tasks"); + let avg_latency_ms = wait_for_batch_completion(&task_keys) + .expect("Failed to measure batch completion"); + + // Convert average latency to duration + total_latency += Duration::from_millis(avg_latency_ms as u64); + } + + total_latency + }); + }); + + group.finish(); + + // Cleanup worker + cleanup_worker(worker).expect("Failed to cleanup worker"); + cleanup_redis().expect("Failed to cleanup Redis"); +} + +criterion_group!(benches, bench_single_rhai_task); +criterion_main!(benches); diff --git a/rhailib/docs/API_INTEGRATION_GUIDE.md b/rhailib/docs/API_INTEGRATION_GUIDE.md new file mode 100644 index 0000000..a65396b --- /dev/null +++ b/rhailib/docs/API_INTEGRATION_GUIDE.md @@ -0,0 +1,530 @@ +# API Integration Guide for RhaiLib + +## Quick Start + +This guide shows you how to integrate external APIs with Rhai scripts using RhaiLib's async architecture. + +## Table of Contents + +1. [Setup and Configuration](#setup-and-configuration) +2. [Basic API Calls](#basic-api-calls) +3. [Stripe Payment Integration](#stripe-payment-integration) +4. [Error Handling Patterns](#error-handling-patterns) +5. [Advanced Usage](#advanced-usage) +6. [Extending to Other APIs](#extending-to-other-apis) + +## Setup and Configuration + +### 1. Environment Variables + +Create a `.env` file in your project: + +```bash +# .env +STRIPE_SECRET_KEY=sk_test_your_stripe_key_here +STRIPE_PUBLISHABLE_KEY=pk_test_your_publishable_key_here +``` + +### 2. Rust Setup + +```rust +use rhailib_dsl::payment::register_payment_rhai_module; +use rhai::{Engine, EvalAltResult, Scope}; +use std::env; + +fn main() -> Result<(), Box> { + // Load environment variables + dotenv::from_filename(".env").ok(); + + // Create Rhai engine and register payment module + let mut engine = Engine::new(); + register_payment_rhai_module(&mut engine); + + // Set up scope with API credentials + let mut scope = Scope::new(); + let stripe_key = env::var("STRIPE_SECRET_KEY").unwrap(); + scope.push("STRIPE_API_KEY", stripe_key); + + // Execute your Rhai script + let script = std::fs::read_to_string("payment_script.rhai")?; + engine.eval_with_scope::<()>(&mut scope, &script)?; + + Ok(()) +} +``` + +### 3. Rhai Script Configuration + +```rhai +// Configure the API client +let config_result = configure_stripe(STRIPE_API_KEY); +print(`Configuration: ${config_result}`); +``` + +## Basic API Calls + +### Simple Product Creation + +```rhai +// Create a basic product +let product = new_product() + .name("My Product") + .description("A great product"); + +try { + let product_id = product.create(); + print(`✅ Created product: ${product_id}`); +} catch(error) { + print(`❌ Error: ${error}`); +} +``` + +### Price Configuration + +```rhai +// One-time payment price +let one_time_price = new_price() + .amount(1999) // $19.99 in cents + .currency("usd") + .product(product_id); + +let price_id = one_time_price.create(); + +// Subscription price +let monthly_price = new_price() + .amount(999) // $9.99 in cents + .currency("usd") + .product(product_id) + .recurring("month"); + +let monthly_price_id = monthly_price.create(); +``` + +## Stripe Payment Integration + +### Complete Payment Workflow + +```rhai +// 1. Configure Stripe +configure_stripe(STRIPE_API_KEY); + +// 2. Create Product +let product = new_product() + .name("Premium Software License") + .description("Professional software solution") + .metadata("category", "software") + .metadata("tier", "premium"); + +let product_id = product.create(); + +// 3. Create Pricing Options +let monthly_price = new_price() + .amount(2999) // $29.99 + .currency("usd") + .product(product_id) + .recurring("month") + .metadata("billing", "monthly"); + +let annual_price = new_price() + .amount(29999) // $299.99 (save $60) + .currency("usd") + .product(product_id) + .recurring("year") + .metadata("billing", "annual") + .metadata("discount", "save_60"); + +let monthly_price_id = monthly_price.create(); +let annual_price_id = annual_price.create(); + +// 4. Create Discount Coupons +let welcome_coupon = new_coupon() + .duration("once") + .percent_off(25) + .metadata("campaign", "welcome_offer"); + +let coupon_id = welcome_coupon.create(); + +// 5. Create Payment Intent for One-time Purchase +let payment_intent = new_payment_intent() + .amount(2999) + .currency("usd") + .customer("cus_customer_id") + .description("Monthly subscription payment") + .add_payment_method_type("card") + .metadata("price_id", monthly_price_id); + +let intent_id = payment_intent.create(); + +// 6. Create Subscription +let subscription = new_subscription() + .customer("cus_customer_id") + .add_price(monthly_price_id) + .trial_days(14) + .coupon(coupon_id) + .metadata("source", "website"); + +let subscription_id = subscription.create(); +``` + +### Builder Pattern Examples + +#### Product with Metadata +```rhai +let product = new_product() + .name("Enterprise Software") + .description("Full-featured business solution") + .metadata("category", "enterprise") + .metadata("support_level", "premium") + .metadata("deployment", "cloud"); +``` + +#### Complex Pricing +```rhai +let tiered_price = new_price() + .amount(4999) // $49.99 + .currency("usd") + .product(product_id) + .recurring_with_count("month", 12) // 12 monthly payments + .metadata("tier", "professional") + .metadata("features", "advanced"); +``` + +#### Multi-item Subscription +```rhai +let enterprise_subscription = new_subscription() + .customer("cus_enterprise_customer") + .add_price_with_quantity(user_license_price_id, 50) // 50 user licenses + .add_price(support_addon_price_id) // Premium support + .add_price(analytics_addon_price_id) // Analytics addon + .trial_days(30) + .metadata("plan", "enterprise") + .metadata("contract_length", "annual"); +``` + +## Error Handling Patterns + +### Basic Error Handling + +```rhai +try { + let result = some_api_call(); + print(`Success: ${result}`); +} catch(error) { + print(`Error occurred: ${error}`); + // Continue with fallback logic +} +``` + +### Graceful Degradation + +```rhai +// Try to create with coupon, fallback without coupon +let subscription_id; +try { + subscription_id = new_subscription() + .customer(customer_id) + .add_price(price_id) + .coupon(coupon_id) + .create(); +} catch(error) { + print(`Coupon failed: ${error}, creating without coupon`); + subscription_id = new_subscription() + .customer(customer_id) + .add_price(price_id) + .create(); +} +``` + +### Validation Before API Calls + +```rhai +// Validate inputs before making API calls +if customer_id == "" { + print("❌ Customer ID is required"); + return; +} + +if price_id == "" { + print("❌ Price ID is required"); + return; +} + +// Proceed with API call +let subscription = new_subscription() + .customer(customer_id) + .add_price(price_id) + .create(); +``` + +## Advanced Usage + +### Conditional Logic + +```rhai +// Different pricing based on customer type +let price_id; +if customer_type == "enterprise" { + price_id = enterprise_price_id; +} else if customer_type == "professional" { + price_id = professional_price_id; +} else { + price_id = standard_price_id; +} + +let subscription = new_subscription() + .customer(customer_id) + .add_price(price_id); + +// Add trial for new customers +if is_new_customer { + subscription = subscription.trial_days(14); +} + +let subscription_id = subscription.create(); +``` + +### Dynamic Metadata + +```rhai +// Build metadata dynamically +let product = new_product() + .name(product_name) + .description(product_description); + +// Add metadata based on conditions +if has_support { + product = product.metadata("support", "included"); +} + +if is_premium { + product = product.metadata("tier", "premium"); +} + +if region != "" { + product = product.metadata("region", region); +} + +let product_id = product.create(); +``` + +### Bulk Operations + +```rhai +// Create multiple prices for a product +let price_configs = [ + #{amount: 999, interval: "month", name: "Monthly"}, + #{amount: 9999, interval: "year", name: "Annual"}, + #{amount: 19999, interval: "", name: "Lifetime"} +]; + +let price_ids = []; +for config in price_configs { + let price = new_price() + .amount(config.amount) + .currency("usd") + .product(product_id) + .metadata("plan_name", config.name); + + if config.interval != "" { + price = price.recurring(config.interval); + } + + let price_id = price.create(); + price_ids.push(price_id); + print(`Created ${config.name} price: ${price_id}`); +} +``` + +## Extending to Other APIs + +### Adding New API Support + +To extend the architecture to other APIs, follow this pattern: + +#### 1. Define Configuration Structure + +```rust +#[derive(Debug, Clone)] +pub struct CustomApiConfig { + pub api_key: String, + pub base_url: String, + pub client: Client, +} +``` + +#### 2. Implement Request Handler + +```rust +async fn handle_custom_api_request( + config: &CustomApiConfig, + request: &AsyncRequest +) -> Result { + let url = format!("{}/{}", config.base_url, request.endpoint); + + let response = config.client + .request(Method::from_str(&request.method).unwrap(), &url) + .header("Authorization", format!("Bearer {}", config.api_key)) + .json(&request.data) + .send() + .await + .map_err(|e| format!("Request failed: {}", e))?; + + let response_text = response.text().await + .map_err(|e| format!("Failed to read response: {}", e))?; + + Ok(response_text) +} +``` + +#### 3. Register Rhai Functions + +```rust +#[rhai_fn(name = "custom_api_call", return_raw)] +pub fn custom_api_call( + endpoint: String, + data: rhai::Map +) -> Result> { + let registry = CUSTOM_API_REGISTRY.lock().unwrap(); + let registry = registry.as_ref().ok_or("API not configured")?; + + let form_data: HashMap = data.into_iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + + registry.make_request(endpoint, "POST".to_string(), form_data) + .map_err(|e| e.to_string().into()) +} +``` + +### Example: GitHub API Integration + +```rhai +// Hypothetical GitHub API integration +configure_github_api(GITHUB_TOKEN); + +// Create a repository +let repo_data = #{ + name: "my-new-repo", + description: "Created via Rhai script", + private: false +}; + +let repo_result = github_api_call("user/repos", repo_data); +print(`Repository created: ${repo_result}`); + +// Create an issue +let issue_data = #{ + title: "Initial setup", + body: "Setting up the repository structure", + labels: ["enhancement", "setup"] +}; + +let issue_result = github_api_call("repos/user/my-new-repo/issues", issue_data); +print(`Issue created: ${issue_result}`); +``` + +## Performance Tips + +### 1. Batch Operations +```rhai +// Instead of creating items one by one, batch when possible +let items_to_create = [item1, item2, item3]; +let created_items = []; + +for item in items_to_create { + try { + let result = item.create(); + created_items.push(result); + } catch(error) { + print(`Failed to create item: ${error}`); + } +} +``` + +### 2. Reuse Configuration +```rhai +// Configure once, use multiple times +configure_stripe(STRIPE_API_KEY); + +// Multiple operations use the same configuration +let product1_id = new_product().name("Product 1").create(); +let product2_id = new_product().name("Product 2").create(); +let price1_id = new_price().product(product1_id).amount(1000).create(); +let price2_id = new_price().product(product2_id).amount(2000).create(); +``` + +### 3. Error Recovery +```rhai +// Implement retry logic for transient failures +let max_retries = 3; +let retry_count = 0; +let success = false; + +while retry_count < max_retries && !success { + try { + let result = api_operation(); + success = true; + print(`Success: ${result}`); + } catch(error) { + retry_count += 1; + print(`Attempt ${retry_count} failed: ${error}`); + if retry_count < max_retries { + print("Retrying..."); + } + } +} + +if !success { + print("❌ All retry attempts failed"); +} +``` + +## Debugging and Monitoring + +### Enable Detailed Logging + +```rhai +// The architecture automatically logs key operations: +// 🔧 Configuring Stripe... +// 🚀 Async worker thread started +// 🔄 Processing POST request to products +// 📥 Stripe response: {...} +// ✅ Request successful with ID: prod_xxx +``` + +### Monitor Request Performance + +```rhai +// Time API operations +let start_time = timestamp(); +let result = expensive_api_operation(); +let end_time = timestamp(); +print(`Operation took ${end_time - start_time}ms`); +``` + +### Handle Rate Limits + +```rhai +// Implement backoff for rate-limited APIs +try { + let result = api_call(); +} catch(error) { + if error.contains("rate limit") { + print("Rate limited, waiting before retry..."); + // In a real implementation, you'd add delay logic + } +} +``` + +## Best Practices Summary + +1. **Always handle errors gracefully** - Use try/catch blocks for all API calls +2. **Validate inputs** - Check required fields before making API calls +3. **Use meaningful metadata** - Add context to help with debugging and analytics +4. **Configure once, use many** - Set up API clients once and reuse them +5. **Implement retry logic** - Handle transient network failures +6. **Monitor performance** - Track API response times and success rates +7. **Secure credentials** - Use environment variables for API keys +8. **Test with demo data** - Use test API keys during development + +This architecture provides a robust foundation for integrating any HTTP-based API with Rhai scripts while maintaining the simplicity and safety that makes Rhai attractive for domain-specific scripting. \ No newline at end of file diff --git a/rhailib/docs/ARCHITECTURE.md b/rhailib/docs/ARCHITECTURE.md new file mode 100644 index 0000000..6fb828f --- /dev/null +++ b/rhailib/docs/ARCHITECTURE.md @@ -0,0 +1,294 @@ +# Rhailib Architecture Overview + +Rhailib is a comprehensive Rust-based ecosystem for executing Rhai scripts in distributed environments with full business domain support, authorization, and scalability features. + +## System Architecture + +```mermaid +graph TB + subgraph "Client Layer" + A[rhai_dispatcher] --> B[Redis Task Queues] + UI[rhai_engine_ui] --> B + REPL[ui_repl] --> B + end + + subgraph "Processing Layer" + B --> C[rhailib_worker] + C --> D[rhailib_engine] + D --> E[rhailib_dsl] + end + + subgraph "Core Infrastructure" + E --> F[derive - Procedural Macros] + E --> G[macros - Authorization] + D --> H[mock_db - Testing] + end + + subgraph "Operations Layer" + I[monitor] --> B + I --> C + end + + subgraph "Data Layer" + J[Redis] --> B + K[Database] --> E + end +``` + +## Crate Overview + +### Core Engine Components + +#### [`rhailib_engine`](../src/engine/docs/ARCHITECTURE.md) +The central Rhai scripting engine that orchestrates all business domain modules. +- **Purpose**: Unified engine creation and script execution +- **Features**: Mock database, feature-based architecture, performance optimization +- **Key Functions**: `create_heromodels_engine()`, script compilation and execution + +#### [`rhailib_dsl`](../src/dsl/docs/ARCHITECTURE.md) +Comprehensive Domain-Specific Language implementation exposing business models to Rhai. +- **Purpose**: Business domain integration with Rhai scripting +- **Domains**: Business operations, finance, content management, workflows, access control +- **Features**: Fluent APIs, type safety, authorization integration + +### Code Generation and Utilities + +#### [`derive`](../src/derive/docs/ARCHITECTURE.md) +Procedural macros for automatic Rhai integration code generation. +- **Purpose**: Simplify Rhai integration for custom types +- **Macros**: `RhaiApi` for DSL generation, `FromVec` for type conversion +- **Features**: Builder pattern generation, error handling + +#### [`macros`](../src/macros/docs/ARCHITECTURE.md) +Authorization macros and utilities for secure database operations. +- **Purpose**: Declarative security for Rhai functions +- **Features**: CRUD operation macros, access control, context management +- **Security**: Multi-level authorization, audit trails + +### Client and Communication + +#### [`rhai_dispatcher`](../src/client/docs/ARCHITECTURE.md) +Redis-based client library for distributed script execution. +- **Purpose**: Submit and manage Rhai script execution requests +- **Features**: Builder pattern API, timeout handling, request-reply pattern +- **Architecture**: Async operations, connection pooling, error handling + +#### [`rhailib_worker`](../src/worker/docs/ARCHITECTURE.md) +Distributed task execution system for processing Rhai scripts. +- **Purpose**: Scalable script processing with queue-based architecture +- **Features**: Multi-context support, horizontal scaling, fault tolerance, context injection +- **Architecture**: Workers decoupled from contexts, allowing single worker to serve multiple circles +- **Integration**: Full engine and DSL access, secure execution + +### User Interfaces + +#### [`ui_repl`](../src/repl/docs/ARCHITECTURE.md) +Interactive development environment for Rhai script development. +- **Purpose**: Real-time script development and testing +- **Features**: Enhanced CLI, dual execution modes, worker management +- **Development**: Syntax highlighting, script editing, immediate feedback + +#### [`rhai_engine_ui`](../src/rhai_engine_ui/docs/ARCHITECTURE.md) +Web-based interface for Rhai script management and execution. +- **Purpose**: Browser-based script execution and management +- **Architecture**: WebAssembly frontend with optional server backend +- **Features**: Real-time updates, task management, visual interface + +### Operations and Monitoring + +#### [`monitor`](../src/monitor/docs/ARCHITECTURE.md) +Command-line monitoring and management tool for the rhailib ecosystem. +- **Purpose**: System observability and task management +- **Features**: Real-time monitoring, performance metrics, queue management +- **Operations**: Multi-worker support, interactive CLI, visualization + +## Data Flow Architecture + +### Script Execution Flow + +```mermaid +sequenceDiagram + participant Client as rhai_dispatcher + participant Redis as Redis Queue + participant Worker as rhailib_worker + participant Engine as rhailib_engine + participant DSL as rhailib_dsl + participant DB as Database + + Client->>Redis: Submit script task (worker_id + context_id) + Worker->>Redis: Poll worker queue (worker_id) + Redis->>Worker: Return task with context_id + Worker->>Engine: Create configured engine + Engine->>DSL: Register domain modules + Worker->>Engine: Execute script with context_id + Engine->>DSL: Call business functions (context_id) + DSL->>DB: Perform authorized operations (context_id) + DB->>DSL: Return results + DSL->>Engine: Return processed data + Engine->>Worker: Return execution result + Worker->>Redis: Publish result to reply queue + Redis->>Client: Deliver result +``` + +### Authorization Flow + +```mermaid +sequenceDiagram + participant Script as Rhai Script + participant Macro as Authorization Macro + participant Context as Execution Context + participant Access as Access Control + participant DB as Database + + Script->>Macro: Call authorized function + Macro->>Context: Extract caller credentials + Context->>Access: Validate permissions + Access->>DB: Check resource access + DB->>Access: Return authorization result + Access->>Macro: Grant/deny access + Macro->>DB: Execute authorized operation + DB->>Script: Return results +``` + +## Worker-Context Decoupling Architecture + +A key architectural feature of rhailib is the decoupling of worker assignment from context management: + +### Traditional Model (Previous) +- **One Worker Per Circle**: Each worker was dedicated to a specific circle/context +- **Queue Per Circle**: Workers listened to circle-specific queues +- **Tight Coupling**: Worker identity was directly tied to context identity + +### New Decoupled Model (Current) +- **Worker ID**: Determines which queue the worker listens to (`rhailib:`) +- **Context ID**: Provided in task details, determines execution context and database access +- **Flexible Assignment**: Single worker can process tasks for multiple contexts + +### Benefits of Decoupling + +1. **Resource Efficiency**: Better worker utilization across multiple contexts +2. **Deployment Flexibility**: Easier scaling and resource allocation +3. **Cost Optimization**: Fewer worker instances needed for multi-context scenarios +4. **Operational Simplicity**: Centralized worker management with distributed contexts + +### Implementation Details + +```mermaid +graph LR + subgraph "Client Layer" + C[Client] --> |worker_id + context_id| Q[Redis Queue] + end + + subgraph "Worker Layer" + W1[Worker 1] --> |listens to| Q1[Queue: worker-1] + W2[Worker 2] --> |listens to| Q2[Queue: worker-2] + end + + subgraph "Context Layer" + W1 --> |processes| CTX1[Context A] + W1 --> |processes| CTX2[Context B] + W2 --> |processes| CTX1 + W2 --> |processes| CTX3[Context C] + end +``` + +## Key Design Principles + +### 1. Security First +- **Multi-layer Authorization**: Context-based, resource-specific, and operation-level security +- **Secure Execution**: Isolated script execution with proper context injection +- **Audit Trails**: Comprehensive logging and monitoring of all operations + +### 2. Scalability +- **Horizontal Scaling**: Multiple worker instances for load distribution +- **Queue-based Architecture**: Reliable task distribution and processing +- **Async Operations**: Non-blocking I/O throughout the system + +### 3. Developer Experience +- **Type Safety**: Comprehensive type checking and conversion utilities +- **Error Handling**: Detailed error messages and proper error propagation +- **Interactive Development**: REPL and web interfaces for immediate feedback + +### 4. Modularity +- **Feature Flags**: Configurable compilation based on requirements +- **Crate Separation**: Clear boundaries and responsibilities +- **Plugin Architecture**: Easy extension and customization + +## Deployment Patterns + +### Development Environment +``` +REPL + Local Engine + Mock Database +``` +- Interactive development with immediate feedback +- Full DSL access without external dependencies +- Integrated testing and debugging + +### Testing Environment +``` +Client + Worker + Redis + Mock Database +``` +- Distributed execution testing +- Queue-based communication validation +- Performance and scalability testing + +### Production Environment +``` +Multiple Clients + Redis Cluster + Worker Pool + Production Database +``` +- High availability and fault tolerance +- Horizontal scaling and load distribution +- Comprehensive monitoring and observability + +## Integration Points + +### External Systems +- **Redis**: Task queues, result delivery, system coordination +- **Databases**: Business data persistence and retrieval +- **Web Browsers**: WebAssembly-based user interfaces +- **Command Line**: Development and operations tooling + +### Internal Integration +- **Macro System**: Code generation and authorization +- **Type System**: Safe conversions and error handling +- **Module System**: Domain-specific functionality organization +- **Context System**: Security and execution environment management + +## Performance Characteristics + +### Throughput +- **Concurrent Execution**: Multiple workers processing tasks simultaneously +- **Connection Pooling**: Efficient database and Redis connection management +- **Compiled Scripts**: AST caching for repeated execution optimization + +### Latency +- **Local Execution**: Direct engine access for development scenarios +- **Queue Optimization**: Efficient task distribution and result delivery +- **Context Caching**: Reduced overhead for authorization and setup + +### Resource Usage +- **Memory Management**: Efficient ownership and borrowing patterns +- **CPU Utilization**: Async operations and non-blocking I/O +- **Network Efficiency**: Optimized serialization and communication protocols + +## Future Extensibility + +### Adding New Domains +1. Create domain module in `rhailib_dsl` +2. Implement authorization macros in `macros` +3. Add feature flags and conditional compilation +4. Update engine registration and documentation + +### Custom Authorization +1. Extend authorization macros with custom logic +2. Implement domain-specific access control functions +3. Add audit and logging capabilities +4. Update security documentation + +### New Interfaces +1. Implement client interface following existing patterns +2. Integrate with Redis communication layer +3. Add monitoring and observability features +4. Provide comprehensive documentation + +This architecture provides a robust, secure, and scalable foundation for distributed Rhai script execution while maintaining excellent developer experience and operational visibility. \ No newline at end of file diff --git a/rhailib/docs/ASYNC_IMPLEMENTATION_SUMMARY.md b/rhailib/docs/ASYNC_IMPLEMENTATION_SUMMARY.md new file mode 100644 index 0000000..f60aec2 --- /dev/null +++ b/rhailib/docs/ASYNC_IMPLEMENTATION_SUMMARY.md @@ -0,0 +1,254 @@ +# Async Implementation Summary + +## Overview + +This document summarizes the successful implementation of async HTTP API support in RhaiLib, enabling Rhai scripts to perform external API calls despite Rhai's synchronous nature. + +## Problem Solved + +**Challenge**: Rhai is fundamentally synchronous and single-threaded, making it impossible to natively perform async operations like HTTP API calls. + +**Solution**: Implemented a multi-threaded architecture using MPSC channels to bridge Rhai's synchronous execution with Rust's async ecosystem. + +## Key Technical Achievement + +### The Blocking Runtime Fix + +The most critical technical challenge was resolving the "Cannot block the current thread from within a runtime" error that occurs when trying to use blocking operations within a Tokio async context. + +**Root Cause**: Using `tokio::sync::oneshot` channels with `blocking_recv()` from within an async runtime context. + +**Solution**: +1. Replaced `tokio::sync::oneshot` with `std::sync::mpsc` channels +2. Used `recv_timeout()` instead of `blocking_recv()` +3. Implemented timeout-based polling in the async worker loop + +```rust +// Before (caused runtime panic) +let result = response_receiver.blocking_recv() + .map_err(|_| "Failed to receive response")?; + +// After (works correctly) +response_receiver.recv_timeout(Duration::from_secs(30)) + .map_err(|e| format!("Failed to receive response: {}", e))? +``` + +## Architecture Components + +### 1. AsyncFunctionRegistry +- **Purpose**: Central coordinator for async operations +- **Key Feature**: Thread-safe communication via MPSC channels +- **Location**: [`src/dsl/src/payment.rs:19`](../src/dsl/src/payment.rs#L19) + +### 2. AsyncRequest Structure +- **Purpose**: Encapsulates async operation data +- **Key Feature**: Includes response channel for result communication +- **Location**: [`src/dsl/src/payment.rs:31`](../src/dsl/src/payment.rs#L31) + +### 3. Async Worker Thread +- **Purpose**: Dedicated thread for processing async operations +- **Key Feature**: Timeout-based polling to prevent runtime blocking +- **Location**: [`src/dsl/src/payment.rs:339`](../src/dsl/src/payment.rs#L339) + +## Implementation Flow + +```mermaid +sequenceDiagram + participant RS as Rhai Script + participant RF as Rhai Function + participant AR as AsyncRegistry + participant CH as MPSC Channel + participant AW as Async Worker + participant API as External API + + RS->>RF: product.create() + RF->>AR: make_request() + AR->>CH: send(AsyncRequest) + CH->>AW: recv_timeout() + AW->>API: HTTP POST + API->>AW: Response + AW->>CH: send(Result) + CH->>AR: recv_timeout() + AR->>RF: Result + RF->>RS: product_id +``` + +## Code Examples + +### Rhai Script Usage +```rhai +// Configure API client +configure_stripe(STRIPE_API_KEY); + +// Create product with builder pattern +let product = new_product() + .name("Premium Software License") + .description("Professional software solution") + .metadata("category", "software"); + +// Async HTTP call (appears synchronous to Rhai) +let product_id = product.create(); +``` + +### Rust Implementation +```rust +pub fn make_request(&self, endpoint: String, method: String, data: HashMap) -> Result { + let (response_sender, response_receiver) = mpsc::channel(); + + let request = AsyncRequest { + endpoint, + method, + data, + response_sender, + }; + + // Send to async worker + self.request_sender.send(request) + .map_err(|_| "Failed to send request to async worker".to_string())?; + + // Wait for response with timeout + response_receiver.recv_timeout(Duration::from_secs(30)) + .map_err(|e| format!("Failed to receive response: {}", e))? +} +``` + +## Testing Results + +### Successful Test Output +``` +=== Rhai Payment Module Example === +🔑 Using Stripe API key: sk_test_your_st*** +🔧 Configuring Stripe... +🚀 Async worker thread started +🔄 Processing POST request to products +📥 Stripe response: {"error": {"message": "Invalid API Key provided..."}} +✅ Payment script executed successfully! +``` + +**Key Success Indicators**: +- ✅ No runtime panics or blocking errors +- ✅ Async worker thread starts successfully +- ✅ HTTP requests are processed correctly +- ✅ Error handling works gracefully with invalid API keys +- ✅ Script execution completes without hanging + +## Files Modified/Created + +### Core Implementation +- **[`src/dsl/src/payment.rs`](../src/dsl/src/payment.rs)**: Complete async architecture implementation +- **[`src/dsl/examples/payment/main.rs`](../src/dsl/examples/payment/main.rs)**: Environment variable loading +- **[`src/dsl/examples/payment/payment.rhai`](../src/dsl/examples/payment/payment.rhai)**: Comprehensive API usage examples + +### Documentation +- **[`docs/ASYNC_RHAI_ARCHITECTURE.md`](ASYNC_RHAI_ARCHITECTURE.md)**: Technical architecture documentation +- **[`docs/API_INTEGRATION_GUIDE.md`](API_INTEGRATION_GUIDE.md)**: Practical usage guide +- **[`README.md`](../README.md)**: Updated with async API features + +### Configuration +- **[`src/dsl/examples/payment/.env.example`](../src/dsl/examples/payment/.env.example)**: Environment variable template +- **[`src/dsl/Cargo.toml`](../src/dsl/Cargo.toml)**: Added dotenv dependency + +## Performance Characteristics + +### Throughput +- **Concurrent Processing**: Multiple async operations can run simultaneously +- **Connection Pooling**: HTTP client reuses connections efficiently +- **Channel Overhead**: Minimal (~microseconds per operation) + +### Latency +- **Network Bound**: Dominated by actual HTTP request time +- **Thread Switching**: Single context switch per request +- **Timeout Handling**: 30-second default timeout with configurable values + +### Memory Usage +- **Bounded Channels**: Prevents memory leaks from unbounded queuing +- **Connection Pooling**: Efficient memory usage for HTTP connections +- **Request Lifecycle**: Automatic cleanup when requests complete + +## Error Handling + +### Network Errors +```rust +.map_err(|e| { + println!("❌ HTTP request failed: {}", e); + format!("HTTP request failed: {}", e) +})? +``` + +### API Errors +```rust +if let Some(error) = json.get("error") { + let error_msg = format!("Stripe API error: {}", error); + Err(error_msg) +} +``` + +### Rhai Script Errors +```rhai +try { + let product_id = product.create(); + print(`✅ Product ID: ${product_id}`); +} catch(error) { + print(`❌ Failed to create product: ${error}`); +} +``` + +## Extensibility + +The architecture is designed to support any HTTP-based API: + +### Adding New APIs +1. Define configuration structure +2. Implement async request handler +3. Register Rhai functions +4. Add builder patterns for complex objects + +### Example Extension +```rust +// GraphQL API support +async fn handle_graphql_request(config: &GraphQLConfig, request: &AsyncRequest) -> Result { + // Implementation for GraphQL queries +} + +#[rhai_fn(name = "graphql_query")] +pub fn execute_graphql_query(query: String, variables: rhai::Map) -> Result> { + // Rhai function implementation +} +``` + +## Best Practices Established + +1. **Timeout-based Polling**: Always use `recv_timeout()` instead of blocking operations in async contexts +2. **Channel Type Selection**: Use `std::sync::mpsc` for cross-thread communication in mixed sync/async environments +3. **Error Propagation**: Provide meaningful error messages at each layer +4. **Resource Management**: Implement proper cleanup and timeout handling +5. **Configuration Security**: Use environment variables for sensitive data +6. **Builder Patterns**: Provide fluent APIs for complex object construction + +## Future Enhancements + +### Potential Improvements +1. **Connection Pooling**: Advanced connection management for high-throughput scenarios +2. **Retry Logic**: Automatic retry with exponential backoff for transient failures +3. **Rate Limiting**: Built-in rate limiting to respect API quotas +4. **Caching**: Response caching for frequently accessed data +5. **Metrics**: Performance monitoring and request analytics +6. **WebSocket Support**: Real-time communication capabilities + +### API Extensions +1. **GraphQL Support**: Native GraphQL query execution +2. **Database Integration**: Direct database access from Rhai scripts +3. **File Operations**: Async file I/O operations +4. **Message Queues**: Integration with message brokers (Redis, RabbitMQ) + +## Conclusion + +The async architecture successfully solves the fundamental challenge of enabling HTTP API calls from Rhai scripts. The implementation is: + +- **Robust**: Handles errors gracefully and prevents runtime panics +- **Performant**: Minimal overhead with efficient resource usage +- **Extensible**: Easy to add support for new APIs and protocols +- **Safe**: Thread-safe with proper error handling and timeouts +- **User-Friendly**: Simple, intuitive API for Rhai script authors + +This foundation enables powerful integration capabilities while maintaining Rhai's simplicity and safety characteristics, making it suitable for production use in applications requiring external API integration. \ No newline at end of file diff --git a/rhailib/docs/ASYNC_RHAI_ARCHITECTURE.md b/rhailib/docs/ASYNC_RHAI_ARCHITECTURE.md new file mode 100644 index 0000000..d55ca58 --- /dev/null +++ b/rhailib/docs/ASYNC_RHAI_ARCHITECTURE.md @@ -0,0 +1,460 @@ +# Async Rhai Architecture for HTTP API Integration + +## Overview + +This document describes the async architecture implemented in RhaiLib that enables Rhai scripts to perform HTTP API calls despite Rhai's fundamentally synchronous nature. The architecture bridges Rhai's blocking execution model with Rust's async ecosystem using multi-threading and message passing. + +## The Challenge + +Rhai is a synchronous, single-threaded scripting language that cannot natively handle async operations. However, modern applications often need to: + +- Make HTTP API calls (REST, GraphQL, etc.) +- Interact with external services (Stripe, payment processors, etc.) +- Perform I/O operations that benefit from async handling +- Maintain responsive execution while waiting for network responses + +## Architecture Solution + +### Core Components + +```mermaid +graph TB + subgraph "Rhai Thread (Synchronous)" + RS[Rhai Script] + RF[Rhai Functions] + RR[Registry Interface] + end + + subgraph "Communication Layer" + MC[MPSC Channel] + REQ[AsyncRequest] + RESP[Response Channel] + end + + subgraph "Async Worker Thread" + RT[Tokio Runtime] + AW[Async Worker Loop] + HC[HTTP Client] + API[External APIs] + end + + RS --> RF + RF --> RR + RR --> MC + MC --> REQ + REQ --> AW + AW --> HC + HC --> API + API --> HC + HC --> AW + AW --> RESP + RESP --> RR + RR --> RF + RF --> RS +``` + +### 1. AsyncFunctionRegistry + +The central coordinator that manages async operations: + +```rust +#[derive(Debug, Clone)] +pub struct AsyncFunctionRegistry { + pub request_sender: Sender, + pub stripe_config: StripeConfig, +} +``` + +**Key Features:** +- **Thread-safe communication**: Uses `std::sync::mpsc` channels +- **Request coordination**: Manages the request/response lifecycle +- **Configuration management**: Stores API credentials and HTTP client settings + +### 2. AsyncRequest Structure + +Encapsulates all information needed for an async operation: + +```rust +#[derive(Debug)] +pub struct AsyncRequest { + pub endpoint: String, + pub method: String, + pub data: HashMap, + pub response_sender: std::sync::mpsc::Sender>, +} +``` + +**Components:** +- **endpoint**: API endpoint path (e.g., "products", "payment_intents") +- **method**: HTTP method (POST, GET, PUT, DELETE) +- **data**: Form data for the request body +- **response_sender**: Channel to send the result back to the calling thread + +### 3. Async Worker Thread + +A dedicated thread running a Tokio runtime that processes async operations: + +```rust +async fn async_worker_loop(config: StripeConfig, receiver: Receiver) { + loop { + match receiver.recv_timeout(Duration::from_millis(100)) { + Ok(request) => { + let result = Self::handle_stripe_request(&config, &request).await; + if let Err(_) = request.response_sender.send(result) { + println!("⚠️ Failed to send response back to caller"); + } + } + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue, + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, + } + } +} +``` + +**Key Design Decisions:** +- **Timeout-based polling**: Uses `recv_timeout()` instead of blocking `recv()` to prevent runtime deadlocks +- **Error handling**: Gracefully handles channel disconnections and timeouts +- **Non-blocking**: Allows the async runtime to process other tasks during polling intervals + +## Request Flow + +### 1. Rhai Script Execution + +```rhai +// Rhai script calls a function +let product = new_product() + .name("Premium Software License") + .description("A comprehensive software solution"); + +let product_id = product.create(); // This triggers async HTTP call +``` + +### 2. Function Registration and Execution + +```rust +#[rhai_fn(name = "create", return_raw)] +pub fn create_product(product: &mut RhaiProduct) -> Result> { + let registry = ASYNC_REGISTRY.lock().unwrap(); + let registry = registry.as_ref().ok_or("Stripe not configured")?; + + let form_data = prepare_product_data(product); + let result = registry.make_request("products".to_string(), "POST".to_string(), form_data) + .map_err(|e| e.to_string())?; + + product.id = Some(result.clone()); + Ok(result) +} +``` + +### 3. Request Processing + +```rust +pub fn make_request(&self, endpoint: String, method: String, data: HashMap) -> Result { + let (response_sender, response_receiver) = mpsc::channel(); + + let request = AsyncRequest { + endpoint, + method, + data, + response_sender, + }; + + // Send request to async worker + self.request_sender.send(request) + .map_err(|_| "Failed to send request to async worker".to_string())?; + + // Wait for response with timeout + response_receiver.recv_timeout(Duration::from_secs(30)) + .map_err(|e| format!("Failed to receive response: {}", e))? +} +``` + +### 4. HTTP Request Execution + +```rust +async fn handle_stripe_request(config: &StripeConfig, request: &AsyncRequest) -> Result { + let url = format!("{}/{}", STRIPE_API_BASE, request.endpoint); + + let response = config.client + .post(&url) + .basic_auth(&config.secret_key, None::<&str>) + .form(&request.data) + .send() + .await + .map_err(|e| format!("HTTP request failed: {}", e))?; + + let response_text = response.text().await + .map_err(|e| format!("Failed to read response: {}", e))?; + + // Parse and validate response + let json: serde_json::Value = serde_json::from_str(&response_text) + .map_err(|e| format!("Failed to parse JSON: {}", e))?; + + if let Some(id) = json.get("id").and_then(|v| v.as_str()) { + Ok(id.to_string()) + } else if let Some(error) = json.get("error") { + Err(format!("API error: {}", error)) + } else { + Err(format!("Unexpected response: {}", response_text)) + } +} +``` + +## Configuration and Setup + +### 1. HTTP Client Configuration + +```rust +let client = Client::builder() + .timeout(Duration::from_secs(5)) + .connect_timeout(Duration::from_secs(3)) + .pool_idle_timeout(Duration::from_secs(10)) + .tcp_keepalive(Duration::from_secs(30)) + .user_agent("rhailib-payment/1.0") + .build()?; +``` + +### 2. Environment Variable Loading + +```rust +// Load from .env file +dotenv::from_filename("examples/payment/.env").ok(); + +let stripe_secret_key = env::var("STRIPE_SECRET_KEY") + .unwrap_or_else(|_| "sk_test_demo_key".to_string()); +``` + +### 3. Rhai Engine Setup + +```rust +let mut engine = Engine::new(); +register_payment_rhai_module(&mut engine); + +let mut scope = Scope::new(); +scope.push("STRIPE_API_KEY", stripe_secret_key); + +engine.eval_with_scope::<()>(&mut scope, &script)?; +``` + +## API Integration Examples + +### Stripe Payment Processing + +The architecture supports comprehensive Stripe API integration: + +#### Product Creation +```rhai +let product = new_product() + .name("Premium Software License") + .description("A comprehensive software solution") + .metadata("category", "software"); + +let product_id = product.create(); // Async HTTP POST to /v1/products +``` + +#### Price Configuration +```rhai +let monthly_price = new_price() + .amount(2999) // $29.99 in cents + .currency("usd") + .product(product_id) + .recurring("month"); + +let price_id = monthly_price.create(); // Async HTTP POST to /v1/prices +``` + +#### Subscription Management +```rhai +let subscription = new_subscription() + .customer("cus_example_customer") + .add_price(monthly_price_id) + .trial_days(14) + .coupon(coupon_id); + +let subscription_id = subscription.create(); // Async HTTP POST to /v1/subscriptions +``` + +#### Payment Intent Processing +```rhai +let payment_intent = new_payment_intent() + .amount(19999) + .currency("usd") + .customer("cus_example_customer") + .description("Premium Software License"); + +let intent_id = payment_intent.create(); // Async HTTP POST to /v1/payment_intents +``` + +## Error Handling + +### 1. Network Errors +```rust +.map_err(|e| { + println!("❌ HTTP request failed: {}", e); + format!("HTTP request failed: {}", e) +})? +``` + +### 2. API Errors +```rust +if let Some(error) = json.get("error") { + let error_msg = format!("Stripe API error: {}", error); + println!("❌ {}", error_msg); + Err(error_msg) +} +``` + +### 3. Timeout Handling +```rust +response_receiver.recv_timeout(Duration::from_secs(30)) + .map_err(|e| format!("Failed to receive response: {}", e))? +``` + +### 4. Rhai Script Error Handling +```rhai +try { + let product_id = product.create(); + print(`✅ Product ID: ${product_id}`); +} catch(error) { + print(`❌ Failed to create product: ${error}`); + return; // Exit gracefully +} +``` + +## Performance Characteristics + +### Throughput +- **Concurrent requests**: Multiple async operations can be processed simultaneously +- **Connection pooling**: HTTP client reuses connections for efficiency +- **Timeout management**: Prevents hanging requests from blocking the system + +### Latency +- **Channel overhead**: Minimal overhead for message passing (~microseconds) +- **Thread switching**: Single context switch per request +- **Network latency**: Dominated by actual HTTP request time + +### Memory Usage +- **Request buffering**: Bounded by channel capacity +- **Connection pooling**: Efficient memory usage for HTTP connections +- **Response caching**: No automatic caching (can be added if needed) + +## Thread Safety + +### 1. Global Registry +```rust +static ASYNC_REGISTRY: Mutex> = Mutex::new(None); +``` + +### 2. Channel Communication +- **MPSC channels**: Multiple producers (Rhai functions), single consumer (async worker) +- **Response channels**: One-to-one communication for each request + +### 3. Shared Configuration +- **Immutable after setup**: Configuration is cloned to worker thread +- **Thread-safe HTTP client**: reqwest::Client is thread-safe + +## Extensibility + +### Adding New APIs + +1. **Define request structures**: +```rust +#[derive(Debug)] +pub struct GraphQLRequest { + pub query: String, + pub variables: HashMap, + pub response_sender: std::sync::mpsc::Sender>, +} +``` + +2. **Implement request handlers**: +```rust +async fn handle_graphql_request(config: &GraphQLConfig, request: &GraphQLRequest) -> Result { + // Implementation +} +``` + +3. **Register Rhai functions**: +```rust +#[rhai_fn(name = "graphql_query", return_raw)] +pub fn execute_graphql_query(query: String) -> Result> { + // Implementation +} +``` + +### Custom HTTP Methods + +The architecture supports any HTTP method: +```rust +registry.make_request("endpoint".to_string(), "PUT".to_string(), data) +registry.make_request("endpoint".to_string(), "DELETE".to_string(), HashMap::new()) +``` + +## Best Practices + +### 1. Configuration Management +- Use environment variables for sensitive data (API keys) +- Validate configuration before starting async workers +- Provide meaningful error messages for missing configuration + +### 2. Error Handling +- Always handle both network and API errors +- Provide fallback behavior for failed requests +- Log errors with sufficient context for debugging + +### 3. Timeout Configuration +- Set appropriate timeouts for different types of requests +- Consider retry logic for transient failures +- Balance responsiveness with reliability + +### 4. Resource Management +- Limit concurrent requests to prevent overwhelming external APIs +- Use connection pooling for efficiency +- Clean up resources when shutting down + +## Troubleshooting + +### Common Issues + +1. **"Cannot block the current thread from within a runtime"** + - **Cause**: Using blocking operations within async context + - **Solution**: Use `recv_timeout()` instead of `blocking_recv()` + +2. **Channel disconnection errors** + - **Cause**: Worker thread terminated unexpectedly + - **Solution**: Check worker thread for panics, ensure proper error handling + +3. **Request timeouts** + - **Cause**: Network issues or slow API responses + - **Solution**: Adjust timeout values, implement retry logic + +4. **API authentication errors** + - **Cause**: Invalid or missing API keys + - **Solution**: Verify environment variable configuration + +### Debugging Tips + +1. **Enable detailed logging**: +```rust +println!("🔄 Processing {} request to {}", request.method, request.endpoint); +println!("📥 API response: {}", response_text); +``` + +2. **Monitor channel health**: +```rust +if let Err(_) = request.response_sender.send(result) { + println!("⚠️ Failed to send response back to caller"); +} +``` + +3. **Test with demo data**: +```rhai +// Use demo API keys that fail gracefully for testing +let demo_key = "sk_test_demo_key_will_fail_gracefully"; +``` + +## Conclusion + +This async architecture successfully bridges Rhai's synchronous execution model with Rust's async ecosystem, enabling powerful HTTP API integration while maintaining the simplicity and safety of Rhai scripts. The design is extensible, performant, and handles errors gracefully, making it suitable for production use in applications requiring external API integration. + +The key innovation is the use of timeout-based polling in the async worker loop, which prevents the common "cannot block within runtime" error while maintaining responsive execution. This pattern can be applied to other async operations beyond HTTP requests, such as database queries, file I/O, or any other async Rust operations that need to be exposed to Rhai scripts. \ No newline at end of file diff --git a/rhailib/docs/DISPATCHER_FLOW_ARCHITECTURE.md b/rhailib/docs/DISPATCHER_FLOW_ARCHITECTURE.md new file mode 100644 index 0000000..ee46bc1 --- /dev/null +++ b/rhailib/docs/DISPATCHER_FLOW_ARCHITECTURE.md @@ -0,0 +1,367 @@ +# Dispatcher-Based Event-Driven Flow Architecture + +## Overview + +This document describes the implementation of a non-blocking, event-driven flow architecture for Rhai payment functions using the existing RhaiDispatcher. The system transforms blocking API calls into fire-and-continue patterns where HTTP requests spawn background threads that dispatch new Rhai scripts based on API responses. + +## Architecture Principles + +### 1. **Non-Blocking API Calls** +- All payment functions (e.g., `create_payment_intent()`) return immediately +- HTTP requests happen in background threads +- No blocking of the main Rhai engine thread + +### 2. **Self-Dispatching Pattern** +- Worker dispatches scripts to itself +- Same `worker_id` and `context_id` maintained +- `caller_id` changes to reflect the API response source + +### 3. **Generic Request/Response Flow** +- Request functions: `new_..._request` pattern +- Response scripts: `new_..._response` pattern +- Consistent naming across all API operations + +## Flow Architecture + +```mermaid +graph TD + A[main.rhai] --> B[create_payment_intent] + B --> C[HTTP Thread Spawned] + B --> D[Return Immediately] + C --> E[Stripe API Call] + E --> F{API Response} + F -->|Success| G[Dispatch: new_create_payment_intent_response] + F -->|Error| H[Dispatch: new_create_payment_intent_error] + G --> I[Response Script Execution] + H --> J[Error Script Execution] +``` + +## Implementation Components + +### 1. **FlowManager** + +```rust +use rhai_dispatcher::{RhaiDispatcher, RhaiDispatcherBuilder, RhaiDispatcherError}; +use std::sync::{Arc, Mutex}; + +pub struct FlowManager { + dispatcher: RhaiDispatcher, + worker_id: String, + context_id: String, +} + +#[derive(Debug)] +pub enum FlowError { + DispatcherError(RhaiDispatcherError), + ConfigurationError(String), +} + +impl From for FlowError { + fn from(err: RhaiDispatcherError) -> Self { + FlowError::DispatcherError(err) + } +} + +impl FlowManager { + pub fn new(worker_id: String, context_id: String) -> Result { + let dispatcher = RhaiDispatcherBuilder::new() + .caller_id("stripe") // API responses come from Stripe + .worker_id(&worker_id) + .context_id(&context_id) + .redis_url("redis://127.0.0.1/") + .build()?; + + Ok(Self { + dispatcher, + worker_id, + context_id, + }) + } + + pub async fn dispatch_response_script(&self, script_name: &str, data: &str) -> Result<(), FlowError> { + let script_content = format!( + r#" + // Auto-generated response script for {} + let response_data = `{}`; + let parsed_data = parse_json(response_data); + + // Include the response script + eval_file("flows/{}.rhai"); + "#, + script_name, + data.replace('`', r#"\`"#), + script_name + ); + + self.dispatcher + .new_play_request() + .worker_id(&self.worker_id) + .context_id(&self.context_id) + .script(&script_content) + .submit() + .await?; + + Ok(()) + } + + pub async fn dispatch_error_script(&self, script_name: &str, error: &str) -> Result<(), FlowError> { + let script_content = format!( + r#" + // Auto-generated error script for {} + let error_data = `{}`; + let parsed_error = parse_json(error_data); + + // Include the error script + eval_file("flows/{}.rhai"); + "#, + script_name, + error.replace('`', r#"\`"#), + script_name + ); + + self.dispatcher + .new_play_request() + .worker_id(&self.worker_id) + .context_id(&self.context_id) + .script(&script_content) + .submit() + .await?; + + Ok(()) + } +} + +// Global flow manager instance +static FLOW_MANAGER: Mutex> = Mutex::new(None); + +pub fn initialize_flow_manager(worker_id: String, context_id: String) -> Result<(), FlowError> { + let manager = FlowManager::new(worker_id, context_id)?; + let mut global_manager = FLOW_MANAGER.lock().unwrap(); + *global_manager = Some(manager); + Ok(()) +} + +pub fn get_flow_manager() -> Result { + let global_manager = FLOW_MANAGER.lock().unwrap(); + global_manager.as_ref() + .ok_or_else(|| FlowError::ConfigurationError("Flow manager not initialized".to_string())) + .map(|manager| FlowManager { + dispatcher: manager.dispatcher.clone(), // Assuming Clone is implemented + worker_id: manager.worker_id.clone(), + context_id: manager.context_id.clone(), + }) +} +``` + +### 2. **Non-Blocking Payment Functions** + +```rust +// Transform blocking function into non-blocking +#[rhai_fn(name = "create", return_raw)] +pub fn create_payment_intent(intent: &mut RhaiPaymentIntent) -> Result> { + let form_data = prepare_payment_intent_data(intent); + + // Get flow manager + let flow_manager = get_flow_manager() + .map_err(|e| format!("Flow manager error: {:?}", e))?; + + // Spawn background thread for HTTP request + let stripe_config = get_stripe_config()?; + thread::spawn(move || { + let rt = Runtime::new().expect("Failed to create runtime"); + rt.block_on(async { + match make_stripe_request(&stripe_config, "payment_intents", &form_data).await { + Ok(response) => { + if let Err(e) = flow_manager.dispatch_response_script( + "new_create_payment_intent_response", + &response + ).await { + eprintln!("Failed to dispatch response: {:?}", e); + } + } + Err(error) => { + if let Err(e) = flow_manager.dispatch_error_script( + "new_create_payment_intent_error", + &error + ).await { + eprintln!("Failed to dispatch error: {:?}", e); + } + } + } + }); + }); + + // Return immediately with confirmation + Ok("payment_intent_request_dispatched".to_string()) +} + +// Generic async HTTP request function +async fn make_stripe_request( + config: &StripeConfig, + endpoint: &str, + form_data: &HashMap +) -> Result { + let url = format!("{}/{}", STRIPE_API_BASE, endpoint); + + let response = config.client + .post(&url) + .basic_auth(&config.secret_key, None::<&str>) + .form(form_data) + .send() + .await + .map_err(|e| format!("HTTP request failed: {}", e))?; + + let response_text = response.text().await + .map_err(|e| format!("Failed to read response: {}", e))?; + + let json: serde_json::Value = serde_json::from_str(&response_text) + .map_err(|e| format!("Failed to parse JSON: {}", e))?; + + if json.get("error").is_some() { + Err(response_text) + } else { + Ok(response_text) + } +} +``` + +### 3. **Flow Script Templates** + +#### Success Response Script +```rhai +// flows/new_create_payment_intent_response.rhai +let payment_intent_id = parsed_data.id; +let status = parsed_data.status; + +print(`✅ Payment Intent Created: ${payment_intent_id}`); +print(`Status: ${status}`); + +// Continue the flow based on status +if status == "requires_payment_method" { + print("Payment method required - ready for frontend"); + // Could dispatch another flow here +} else if status == "succeeded" { + print("Payment completed successfully!"); + // Dispatch success notification flow +} + +// Store the payment intent ID for later use +set_context("payment_intent_id", payment_intent_id); +set_context("payment_status", status); +``` + +#### Error Response Script +```rhai +// flows/new_create_payment_intent_error.rhai +let error_type = parsed_error.error.type; +let error_message = parsed_error.error.message; + +print(`❌ Payment Intent Error: ${error_type}`); +print(`Message: ${error_message}`); + +// Handle different error types +if error_type == "card_error" { + print("Card was declined - notify user"); + // Dispatch user notification flow +} else if error_type == "rate_limit_error" { + print("Rate limited - retry later"); + // Dispatch retry flow +} else { + print("Unknown error - log for investigation"); + // Dispatch error logging flow +} + +// Store error details for debugging +set_context("last_error_type", error_type); +set_context("last_error_message", error_message); +``` + +### 4. **Configuration and Initialization** + +```rust +// Add to payment module initialization +#[rhai_fn(name = "init_flows", return_raw)] +pub fn init_flows(worker_id: String, context_id: String) -> Result> { + initialize_flow_manager(worker_id, context_id) + .map_err(|e| format!("Failed to initialize flow manager: {:?}", e))?; + + Ok("Flow manager initialized successfully".to_string()) +} +``` + +## Usage Examples + +### 1. **Basic Payment Flow** + +```rhai +// main.rhai +init_flows("worker-1", "context-123"); +configure_stripe("sk_test_..."); + +let payment_intent = new_payment_intent() + .amount(2000) + .currency("usd") + .customer("cus_customer123"); + +// This returns immediately, HTTP happens in background +let result = payment_intent.create(); +print(`Request dispatched: ${result}`); + +// Script ends here, but flow continues in background +``` + +### 2. **Chained Flow Example** + +```rhai +// flows/new_create_payment_intent_response.rhai +let payment_intent_id = parsed_data.id; + +if parsed_data.status == "requires_payment_method" { + // Chain to next operation + let subscription = new_subscription() + .customer(get_context("customer_id")) + .add_price("price_monthly"); + + // This will trigger new_create_subscription_response flow + subscription.create(); +} +``` + +## Benefits + +### 1. **Non-Blocking Execution** +- Main Rhai script never blocks on HTTP requests +- Multiple API calls can happen concurrently +- Engine remains responsive for other scripts + +### 2. **Event-Driven Architecture** +- Clear separation between request and response handling +- Easy to add new flow steps +- Composable and chainable operations + +### 3. **Error Handling** +- Dedicated error flows for each operation +- Contextual error information preserved +- Retry and recovery patterns possible + +### 4. **Scalability** +- Each HTTP request runs in its own thread +- No shared state between concurrent operations +- Redis-based dispatch scales horizontally + +## Implementation Checklist + +- [ ] Implement FlowManager with RhaiDispatcher integration +- [ ] Convert all payment functions to non-blocking pattern +- [ ] Create flow script templates for all operations +- [ ] Add flow initialization functions +- [ ] Test with example payment flows +- [ ] Update documentation and examples + +## Migration Path + +1. **Phase 1**: Implement FlowManager and basic infrastructure +2. **Phase 2**: Convert payment_intent functions to non-blocking +3. **Phase 3**: Convert remaining payment functions (products, prices, subscriptions, coupons) +4. **Phase 4**: Create comprehensive flow script library +5. **Phase 5**: Add advanced features (retries, timeouts, monitoring) \ No newline at end of file diff --git a/rhailib/docs/EVENT_DRIVEN_FLOW_ARCHITECTURE.md b/rhailib/docs/EVENT_DRIVEN_FLOW_ARCHITECTURE.md new file mode 100644 index 0000000..a6803fb --- /dev/null +++ b/rhailib/docs/EVENT_DRIVEN_FLOW_ARCHITECTURE.md @@ -0,0 +1,443 @@ +# Event-Driven Flow Architecture + +## Overview + +A simple, single-threaded architecture where API calls trigger HTTP requests and spawn new Rhai scripts based on responses. No global state, no polling, no blocking - just clean event-driven flows. + +## Core Concept + +```mermaid +graph LR + RS1[Rhai Script] --> API[create_payment_intent] + API --> HTTP[HTTP Request] + HTTP --> SPAWN[Spawn Thread] + SPAWN --> WAIT[Wait for Response] + WAIT --> SUCCESS[200 OK] + WAIT --> ERROR[Error] + SUCCESS --> RS2[new_payment_intent.rhai] + ERROR --> RS3[payment_failed.rhai] +``` + +## Architecture Design + +### 1. Simple Flow Manager + +```rust +use std::thread; +use std::collections::HashMap; +use reqwest::Client; +use rhai::{Engine, Scope}; + +pub struct FlowManager { + pub client: Client, + pub engine: Engine, + pub flow_scripts: HashMap, // event_name -> script_path +} + +impl FlowManager { + pub fn new() -> Self { + let mut flow_scripts = HashMap::new(); + + // Define flow mappings + flow_scripts.insert("payment_intent_created".to_string(), "flows/payment_intent_created.rhai".to_string()); + flow_scripts.insert("payment_intent_failed".to_string(), "flows/payment_intent_failed.rhai".to_string()); + flow_scripts.insert("product_created".to_string(), "flows/product_created.rhai".to_string()); + flow_scripts.insert("subscription_created".to_string(), "flows/subscription_created.rhai".to_string()); + + Self { + client: Client::new(), + engine: Engine::new(), + flow_scripts, + } + } + + // Fire HTTP request and spawn response handler + pub fn fire_and_continue(&self, + endpoint: String, + method: String, + data: HashMap, + success_event: String, + error_event: String, + context: HashMap + ) { + let client = self.client.clone(); + let flow_scripts = self.flow_scripts.clone(); + + // Spawn thread for HTTP request + thread::spawn(move || { + let result = Self::make_http_request(&client, &endpoint, &method, &data); + + match result { + Ok(response_data) => { + // Success: dispatch success flow + Self::dispatch_flow(&flow_scripts, &success_event, response_data, context); + } + Err(error) => { + // Error: dispatch error flow + let mut error_data = HashMap::new(); + error_data.insert("error".to_string(), error); + Self::dispatch_flow(&flow_scripts, &error_event, error_data, context); + } + } + }); + + // Return immediately - no blocking! + } + + // Execute HTTP request + fn make_http_request( + client: &Client, + endpoint: &str, + method: &str, + data: &HashMap + ) -> Result, String> { + // This runs in spawned thread - can block safely + let rt = tokio::runtime::Runtime::new().unwrap(); + + rt.block_on(async { + let url = format!("https://api.stripe.com/v1/{}", endpoint); + + let response = client + .post(&url) + .form(data) + .send() + .await + .map_err(|e| format!("HTTP error: {}", e))?; + + let response_text = response.text().await + .map_err(|e| format!("Response read error: {}", e))?; + + let json: serde_json::Value = serde_json::from_str(&response_text) + .map_err(|e| format!("JSON parse error: {}", e))?; + + // Convert JSON to HashMap for Rhai + let mut result = HashMap::new(); + if let Some(id) = json.get("id").and_then(|v| v.as_str()) { + result.insert("id".to_string(), id.to_string()); + } + if let Some(status) = json.get("status").and_then(|v| v.as_str()) { + result.insert("status".to_string(), status.to_string()); + } + + Ok(result) + }) + } + + // Dispatch new Rhai script based on event + fn dispatch_flow( + flow_scripts: &HashMap, + event_name: &str, + response_data: HashMap, + context: HashMap + ) { + if let Some(script_path) = flow_scripts.get(event_name) { + println!("🎯 Dispatching flow: {} -> {}", event_name, script_path); + + // Create new engine instance for this flow + let mut engine = Engine::new(); + register_payment_rhai_module(&mut engine); + + // Create scope with response data and context + let mut scope = Scope::new(); + + // Add response data + for (key, value) in response_data { + scope.push(key, value); + } + + // Add context data + for (key, value) in context { + scope.push(format!("context_{}", key), value); + } + + // Execute flow script + if let Ok(script_content) = std::fs::read_to_string(script_path) { + match engine.eval_with_scope::<()>(&mut scope, &script_content) { + Ok(_) => println!("✅ Flow {} completed successfully", event_name), + Err(e) => println!("❌ Flow {} failed: {}", event_name, e), + } + } else { + println!("❌ Flow script not found: {}", script_path); + } + } else { + println!("⚠️ No flow defined for event: {}", event_name); + } + } +} +``` + +### 2. Simple Rhai Functions + +```rust +#[export_module] +mod rhai_flow_module { + use super::*; + + // Global flow manager instance + static FLOW_MANAGER: std::sync::OnceLock = std::sync::OnceLock::new(); + + #[rhai_fn(name = "init_flows")] + pub fn init_flows() { + FLOW_MANAGER.set(FlowManager::new()).ok(); + println!("✅ Flow manager initialized"); + } + + #[rhai_fn(name = "create_payment_intent")] + pub fn create_payment_intent( + amount: i64, + currency: String, + customer: String + ) { + let manager = FLOW_MANAGER.get().expect("Flow manager not initialized"); + + let mut data = HashMap::new(); + data.insert("amount".to_string(), amount.to_string()); + data.insert("currency".to_string(), currency); + data.insert("customer".to_string(), customer.clone()); + + let mut context = HashMap::new(); + context.insert("customer_id".to_string(), customer); + context.insert("original_amount".to_string(), amount.to_string()); + + manager.fire_and_continue( + "payment_intents".to_string(), + "POST".to_string(), + data, + "payment_intent_created".to_string(), + "payment_intent_failed".to_string(), + context + ); + + println!("🚀 Payment intent creation started"); + // Returns immediately! + } + + #[rhai_fn(name = "create_product")] + pub fn create_product(name: String, description: String) { + let manager = FLOW_MANAGER.get().expect("Flow manager not initialized"); + + let mut data = HashMap::new(); + data.insert("name".to_string(), name.clone()); + data.insert("description".to_string(), description); + + let mut context = HashMap::new(); + context.insert("product_name".to_string(), name); + + manager.fire_and_continue( + "products".to_string(), + "POST".to_string(), + data, + "product_created".to_string(), + "product_failed".to_string(), + context + ); + + println!("🚀 Product creation started"); + } + + #[rhai_fn(name = "create_subscription")] + pub fn create_subscription(customer: String, price_id: String) { + let manager = FLOW_MANAGER.get().expect("Flow manager not initialized"); + + let mut data = HashMap::new(); + data.insert("customer".to_string(), customer.clone()); + data.insert("items[0][price]".to_string(), price_id.clone()); + + let mut context = HashMap::new(); + context.insert("customer_id".to_string(), customer); + context.insert("price_id".to_string(), price_id); + + manager.fire_and_continue( + "subscriptions".to_string(), + "POST".to_string(), + data, + "subscription_created".to_string(), + "subscription_failed".to_string(), + context + ); + + println!("🚀 Subscription creation started"); + } +} +``` + +## Usage Examples + +### 1. Main Script (Initiator) + +```rhai +// main.rhai +init_flows(); + +print("Starting payment flow..."); + +// This returns immediately, spawns HTTP request +create_payment_intent(2000, "usd", "cus_customer123"); + +print("Payment intent request sent, continuing..."); + +// Script ends here, but flow continues in background +``` + +### 2. Success Flow Script + +```rhai +// flows/payment_intent_created.rhai + +print("🎉 Payment intent created successfully!"); +print(`Payment Intent ID: ${id}`); +print(`Status: ${status}`); +print(`Customer: ${context_customer_id}`); +print(`Amount: ${context_original_amount}`); + +// Continue the flow - create subscription +if status == "requires_payment_method" { + print("Creating subscription for customer..."); + create_subscription(context_customer_id, "price_monthly_plan"); +} +``` + +### 3. Error Flow Script + +```rhai +// flows/payment_intent_failed.rhai + +print("❌ Payment intent creation failed"); +print(`Error: ${error}`); +print(`Customer: ${context_customer_id}`); + +// Handle error - maybe retry or notify +print("Sending notification to customer..."); +// Could trigger email notification flow here +``` + +### 4. Subscription Success Flow + +```rhai +// flows/subscription_created.rhai + +print("🎉 Subscription created!"); +print(`Subscription ID: ${id}`); +print(`Customer: ${context_customer_id}`); +print(`Price: ${context_price_id}`); + +// Final step - send welcome email +print("Sending welcome email..."); +// Could trigger email flow here +``` + +## Flow Configuration + +### 1. Flow Mapping + +```rust +// Define in FlowManager::new() +flow_scripts.insert("payment_intent_created".to_string(), "flows/payment_intent_created.rhai".to_string()); +flow_scripts.insert("payment_intent_failed".to_string(), "flows/payment_intent_failed.rhai".to_string()); +flow_scripts.insert("product_created".to_string(), "flows/product_created.rhai".to_string()); +flow_scripts.insert("subscription_created".to_string(), "flows/subscription_created.rhai".to_string()); +``` + +### 2. Directory Structure + +``` +project/ +├── main.rhai # Main script +├── flows/ +│ ├── payment_intent_created.rhai # Success flow +│ ├── payment_intent_failed.rhai # Error flow +│ ├── product_created.rhai # Product success +│ ├── subscription_created.rhai # Subscription success +│ └── email_notification.rhai # Email flow +└── src/ + └── flow_manager.rs # Flow manager code +``` + +## Execution Flow + +```mermaid +sequenceDiagram + participant MS as Main Script + participant FM as FlowManager + participant TH as Spawned Thread + participant API as Stripe API + participant FS as Flow Script + + MS->>FM: create_payment_intent() + FM->>TH: spawn thread + FM->>MS: return immediately + Note over MS: Script ends + + TH->>API: HTTP POST /payment_intents + API->>TH: 200 OK + payment_intent data + TH->>FS: dispatch payment_intent_created.rhai + Note over FS: New Rhai execution + FS->>FM: create_subscription() + FM->>TH: spawn new thread + TH->>API: HTTP POST /subscriptions + API->>TH: 200 OK + subscription data + TH->>FS: dispatch subscription_created.rhai +``` + +## Benefits + +### 1. **Simplicity** +- No global state management +- No complex polling or callbacks +- Each flow is a simple Rhai script + +### 2. **Single-Threaded Rhai** +- Main Rhai engine never blocks +- Each flow script runs in its own engine instance +- No concurrency issues in Rhai code + +### 3. **Event-Driven** +- Clear separation of concerns +- Easy to add new flows +- Composable flow chains + +### 4. **No Blocking** +- HTTP requests happen in background threads +- Main script continues immediately +- Flows trigger based on responses + +## Advanced Features + +### 1. Flow Chaining + +```rhai +// flows/payment_intent_created.rhai +if status == "requires_payment_method" { + // Chain to next flow + create_subscription(context_customer_id, "price_monthly"); +} +``` + +### 2. Conditional Flows + +```rhai +// flows/subscription_created.rhai +if context_customer_type == "enterprise" { + // Enterprise-specific flow + create_enterprise_setup(context_customer_id); +} else { + // Standard flow + send_welcome_email(context_customer_id); +} +``` + +### 3. Error Recovery + +```rhai +// flows/payment_intent_failed.rhai +if error.contains("insufficient_funds") { + // Retry with smaller amount + let retry_amount = context_original_amount / 2; + create_payment_intent(retry_amount, "usd", context_customer_id); +} else { + // Send error notification + send_error_notification(context_customer_id, error); +} +``` + +This architecture is much simpler, has no global state, and provides clean event-driven flows that are easy to understand and maintain. \ No newline at end of file diff --git a/rhailib/docs/IMPLEMENTATION_SPECIFICATION.md b/rhailib/docs/IMPLEMENTATION_SPECIFICATION.md new file mode 100644 index 0000000..20c299e --- /dev/null +++ b/rhailib/docs/IMPLEMENTATION_SPECIFICATION.md @@ -0,0 +1,593 @@ +# Event-Driven Flow Implementation Specification + +## Overview + +This document provides the complete implementation specification for converting the blocking payment.rs architecture to an event-driven flow system using RhaiDispatcher. + +## File Structure + +``` +src/dsl/src/ +├── flow_manager.rs # New: FlowManager implementation +├── payment.rs # Modified: Non-blocking payment functions +└── lib.rs # Modified: Include flow_manager module +``` + +## 1. FlowManager Implementation + +### File: `src/dsl/src/flow_manager.rs` + +```rust +use rhai_dispatcher::{RhaiDispatcher, RhaiDispatcherBuilder, RhaiDispatcherError}; +use std::sync::{Arc, Mutex}; +use std::collections::HashMap; +use serde_json; +use tokio::runtime::Runtime; + +#[derive(Debug)] +pub enum FlowError { + DispatcherError(RhaiDispatcherError), + ConfigurationError(String), + SerializationError(serde_json::Error), +} + +impl From for FlowError { + fn from(err: RhaiDispatcherError) -> Self { + FlowError::DispatcherError(err) + } +} + +impl From for FlowError { + fn from(err: serde_json::Error) -> Self { + FlowError::SerializationError(err) + } +} + +impl std::fmt::Display for FlowError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + FlowError::DispatcherError(e) => write!(f, "Dispatcher error: {}", e), + FlowError::ConfigurationError(e) => write!(f, "Configuration error: {}", e), + FlowError::SerializationError(e) => write!(f, "Serialization error: {}", e), + } + } +} + +impl std::error::Error for FlowError {} + +#[derive(Clone)] +pub struct FlowManager { + dispatcher: RhaiDispatcher, + worker_id: String, + context_id: String, +} + +impl FlowManager { + pub fn new(worker_id: String, context_id: String, redis_url: Option) -> Result { + let redis_url = redis_url.unwrap_or_else(|| "redis://127.0.0.1/".to_string()); + + let dispatcher = RhaiDispatcherBuilder::new() + .caller_id("stripe") // API responses come from Stripe + .worker_id(&worker_id) + .context_id(&context_id) + .redis_url(&redis_url) + .build()?; + + Ok(Self { + dispatcher, + worker_id, + context_id, + }) + } + + pub async fn dispatch_response_script(&self, script_name: &str, data: &str) -> Result<(), FlowError> { + let script_content = format!( + r#" + // Auto-generated response script for {} + let response_data = `{}`; + let parsed_data = parse_json(response_data); + + // Include the response script + eval_file("flows/{}.rhai"); + "#, + script_name, + data.replace('`', r#"\`"#), + script_name + ); + + self.dispatcher + .new_play_request() + .worker_id(&self.worker_id) + .context_id(&self.context_id) + .script(&script_content) + .submit() + .await?; + + Ok(()) + } + + pub async fn dispatch_error_script(&self, script_name: &str, error: &str) -> Result<(), FlowError> { + let script_content = format!( + r#" + // Auto-generated error script for {} + let error_data = `{}`; + let parsed_error = parse_json(error_data); + + // Include the error script + eval_file("flows/{}.rhai"); + "#, + script_name, + error.replace('`', r#"\`"#), + script_name + ); + + self.dispatcher + .new_play_request() + .worker_id(&self.worker_id) + .context_id(&self.context_id) + .script(&script_content) + .submit() + .await?; + + Ok(()) + } +} + +// Global flow manager instance +static FLOW_MANAGER: Mutex> = Mutex::new(None); + +pub fn initialize_flow_manager(worker_id: String, context_id: String, redis_url: Option) -> Result<(), FlowError> { + let manager = FlowManager::new(worker_id, context_id, redis_url)?; + let mut global_manager = FLOW_MANAGER.lock().unwrap(); + *global_manager = Some(manager); + Ok(()) +} + +pub fn get_flow_manager() -> Result { + let global_manager = FLOW_MANAGER.lock().unwrap(); + global_manager.as_ref() + .ok_or_else(|| FlowError::ConfigurationError("Flow manager not initialized".to_string())) + .cloned() +} + +// Async HTTP request function for Stripe API +pub async fn make_stripe_request( + config: &super::StripeConfig, + endpoint: &str, + form_data: &HashMap +) -> Result { + let url = format!("{}/{}", super::STRIPE_API_BASE, endpoint); + + let response = config.client + .post(&url) + .basic_auth(&config.secret_key, None::<&str>) + .form(form_data) + .send() + .await + .map_err(|e| format!("HTTP request failed: {}", e))?; + + let response_text = response.text().await + .map_err(|e| format!("Failed to read response: {}", e))?; + + let json: serde_json::Value = serde_json::from_str(&response_text) + .map_err(|e| format!("Failed to parse JSON: {}", e))?; + + if json.get("error").is_some() { + Err(response_text) + } else { + Ok(response_text) + } +} +``` + +## 2. Payment.rs Modifications + +### Add Dependencies + +Add to the top of `payment.rs`: + +```rust +mod flow_manager; +use flow_manager::{get_flow_manager, initialize_flow_manager, make_stripe_request, FlowError}; +use std::thread; +use tokio::runtime::Runtime; +``` + +### Add Flow Initialization Function + +Add to the `rhai_payment_module`: + +```rust +#[rhai_fn(name = "init_flows", return_raw)] +pub fn init_flows(worker_id: String, context_id: String) -> Result> { + initialize_flow_manager(worker_id, context_id, None) + .map_err(|e| format!("Failed to initialize flow manager: {:?}", e))?; + + Ok("Flow manager initialized successfully".to_string()) +} + +#[rhai_fn(name = "init_flows_with_redis", return_raw)] +pub fn init_flows_with_redis(worker_id: String, context_id: String, redis_url: String) -> Result> { + initialize_flow_manager(worker_id, context_id, Some(redis_url)) + .map_err(|e| format!("Failed to initialize flow manager: {:?}", e))?; + + Ok("Flow manager initialized successfully".to_string()) +} +``` + +### Helper Function for Stripe Config + +Add helper function to get stripe config: + +```rust +fn get_stripe_config() -> Result> { + let registry = ASYNC_REGISTRY.lock().unwrap(); + let registry = registry.as_ref().ok_or("Stripe not configured. Call configure_stripe() first.")?; + Ok(registry.stripe_config.clone()) +} +``` + +### Convert Payment Intent Function + +Replace the existing `create_payment_intent` function: + +```rust +#[rhai_fn(name = "create", return_raw)] +pub fn create_payment_intent(intent: &mut RhaiPaymentIntent) -> Result> { + let form_data = prepare_payment_intent_data(intent); + + // Get flow manager and stripe config + let flow_manager = get_flow_manager() + .map_err(|e| format!("Flow manager error: {:?}", e))?; + let stripe_config = get_stripe_config()?; + + // Spawn background thread for HTTP request + thread::spawn(move || { + let rt = Runtime::new().expect("Failed to create runtime"); + rt.block_on(async { + match make_stripe_request(&stripe_config, "payment_intents", &form_data).await { + Ok(response) => { + if let Err(e) = flow_manager.dispatch_response_script( + "new_create_payment_intent_response", + &response + ).await { + eprintln!("Failed to dispatch response: {:?}", e); + } + } + Err(error) => { + if let Err(e) = flow_manager.dispatch_error_script( + "new_create_payment_intent_error", + &error + ).await { + eprintln!("Failed to dispatch error: {:?}", e); + } + } + } + }); + }); + + // Return immediately with confirmation + Ok("payment_intent_request_dispatched".to_string()) +} +``` + +### Convert Product Function + +Replace the existing `create_product` function: + +```rust +#[rhai_fn(name = "create", return_raw)] +pub fn create_product(product: &mut RhaiProduct) -> Result> { + let form_data = prepare_product_data(product); + + // Get flow manager and stripe config + let flow_manager = get_flow_manager() + .map_err(|e| format!("Flow manager error: {:?}", e))?; + let stripe_config = get_stripe_config()?; + + // Spawn background thread for HTTP request + thread::spawn(move || { + let rt = Runtime::new().expect("Failed to create runtime"); + rt.block_on(async { + match make_stripe_request(&stripe_config, "products", &form_data).await { + Ok(response) => { + if let Err(e) = flow_manager.dispatch_response_script( + "new_create_product_response", + &response + ).await { + eprintln!("Failed to dispatch response: {:?}", e); + } + } + Err(error) => { + if let Err(e) = flow_manager.dispatch_error_script( + "new_create_product_error", + &error + ).await { + eprintln!("Failed to dispatch error: {:?}", e); + } + } + } + }); + }); + + // Return immediately with confirmation + Ok("product_request_dispatched".to_string()) +} +``` + +### Convert Price Function + +Replace the existing `create_price` function: + +```rust +#[rhai_fn(name = "create", return_raw)] +pub fn create_price(price: &mut RhaiPrice) -> Result> { + let form_data = prepare_price_data(price); + + // Get flow manager and stripe config + let flow_manager = get_flow_manager() + .map_err(|e| format!("Flow manager error: {:?}", e))?; + let stripe_config = get_stripe_config()?; + + // Spawn background thread for HTTP request + thread::spawn(move || { + let rt = Runtime::new().expect("Failed to create runtime"); + rt.block_on(async { + match make_stripe_request(&stripe_config, "prices", &form_data).await { + Ok(response) => { + if let Err(e) = flow_manager.dispatch_response_script( + "new_create_price_response", + &response + ).await { + eprintln!("Failed to dispatch response: {:?}", e); + } + } + Err(error) => { + if let Err(e) = flow_manager.dispatch_error_script( + "new_create_price_error", + &error + ).await { + eprintln!("Failed to dispatch error: {:?}", e); + } + } + } + }); + }); + + // Return immediately with confirmation + Ok("price_request_dispatched".to_string()) +} +``` + +### Convert Subscription Function + +Replace the existing `create_subscription` function: + +```rust +#[rhai_fn(name = "create", return_raw)] +pub fn create_subscription(subscription: &mut RhaiSubscription) -> Result> { + let form_data = prepare_subscription_data(subscription); + + // Get flow manager and stripe config + let flow_manager = get_flow_manager() + .map_err(|e| format!("Flow manager error: {:?}", e))?; + let stripe_config = get_stripe_config()?; + + // Spawn background thread for HTTP request + thread::spawn(move || { + let rt = Runtime::new().expect("Failed to create runtime"); + rt.block_on(async { + match make_stripe_request(&stripe_config, "subscriptions", &form_data).await { + Ok(response) => { + if let Err(e) = flow_manager.dispatch_response_script( + "new_create_subscription_response", + &response + ).await { + eprintln!("Failed to dispatch response: {:?}", e); + } + } + Err(error) => { + if let Err(e) = flow_manager.dispatch_error_script( + "new_create_subscription_error", + &error + ).await { + eprintln!("Failed to dispatch error: {:?}", e); + } + } + } + }); + }); + + // Return immediately with confirmation + Ok("subscription_request_dispatched".to_string()) +} +``` + +### Convert Coupon Function + +Replace the existing `create_coupon` function: + +```rust +#[rhai_fn(name = "create", return_raw)] +pub fn create_coupon(coupon: &mut RhaiCoupon) -> Result> { + let form_data = prepare_coupon_data(coupon); + + // Get flow manager and stripe config + let flow_manager = get_flow_manager() + .map_err(|e| format!("Flow manager error: {:?}", e))?; + let stripe_config = get_stripe_config()?; + + // Spawn background thread for HTTP request + thread::spawn(move || { + let rt = Runtime::new().expect("Failed to create runtime"); + rt.block_on(async { + match make_stripe_request(&stripe_config, "coupons", &form_data).await { + Ok(response) => { + if let Err(e) = flow_manager.dispatch_response_script( + "new_create_coupon_response", + &response + ).await { + eprintln!("Failed to dispatch response: {:?}", e); + } + } + Err(error) => { + if let Err(e) = flow_manager.dispatch_error_script( + "new_create_coupon_error", + &error + ).await { + eprintln!("Failed to dispatch error: {:?}", e); + } + } + } + }); + }); + + // Return immediately with confirmation + Ok("coupon_request_dispatched".to_string()) +} +``` + +## 3. Remove Old Blocking Code + +### Remove from payment.rs: + +1. **AsyncFunctionRegistry struct and implementation** - No longer needed +2. **ASYNC_REGISTRY static** - No longer needed +3. **AsyncRequest struct** - No longer needed +4. **async_worker_loop function** - No longer needed +5. **handle_stripe_request function** - Replaced by make_stripe_request in flow_manager +6. **make_request method** - No longer needed + +### Keep in payment.rs: + +1. **All struct definitions** (RhaiProduct, RhaiPrice, etc.) +2. **All builder methods** (name, amount, currency, etc.) +3. **All prepare_*_data functions** +4. **All getter functions** +5. **StripeConfig struct** +6. **configure_stripe function** (but remove AsyncFunctionRegistry creation) + +## 4. Update Cargo.toml + +Add to `src/dsl/Cargo.toml`: + +```toml +[dependencies] +# ... existing dependencies ... +rhai_dispatcher = { path = "../dispatcher" } +``` + +## 5. Update lib.rs + +Add to `src/dsl/src/lib.rs`: + +```rust +pub mod flow_manager; +``` + +## 6. Flow Script Templates + +Create directory structure: +``` +flows/ +├── new_create_payment_intent_response.rhai +├── new_create_payment_intent_error.rhai +├── new_create_product_response.rhai +├── new_create_product_error.rhai +├── new_create_price_response.rhai +├── new_create_price_error.rhai +├── new_create_subscription_response.rhai +├── new_create_subscription_error.rhai +├── new_create_coupon_response.rhai +└── new_create_coupon_error.rhai +``` + +### Example Flow Scripts + +#### flows/new_create_payment_intent_response.rhai +```rhai +let payment_intent_id = parsed_data.id; +let status = parsed_data.status; + +print(`✅ Payment Intent Created: ${payment_intent_id}`); +print(`Status: ${status}`); + +// Continue the flow based on status +if status == "requires_payment_method" { + print("Payment method required - ready for frontend"); +} else if status == "succeeded" { + print("Payment completed successfully!"); +} + +// Store the payment intent ID for later use +set_context("payment_intent_id", payment_intent_id); +set_context("payment_status", status); +``` + +#### flows/new_create_payment_intent_error.rhai +```rhai +let error_type = parsed_error.error.type; +let error_message = parsed_error.error.message; + +print(`❌ Payment Intent Error: ${error_type}`); +print(`Message: ${error_message}`); + +// Handle different error types +if error_type == "card_error" { + print("Card was declined - notify user"); +} else if error_type == "rate_limit_error" { + print("Rate limited - retry later"); +} else { + print("Unknown error - log for investigation"); +} + +// Store error details for debugging +set_context("last_error_type", error_type); +set_context("last_error_message", error_message); +``` + +## 7. Usage Example + +### main.rhai +```rhai +// Initialize the flow system +init_flows("worker-1", "context-123"); + +// Configure Stripe +configure_stripe("sk_test_..."); + +// Create payment intent (non-blocking) +let payment_intent = new_payment_intent() + .amount(2000) + .currency("usd") + .customer("cus_customer123"); + +let result = payment_intent.create(); +print(`Request dispatched: ${result}`); + +// Script ends here, but flow continues in background +// Response will trigger new_create_payment_intent_response.rhai +``` + +## 8. Testing Strategy + +1. **Unit Tests**: Test FlowManager initialization and script dispatch +2. **Integration Tests**: Test full payment flow with mock Stripe responses +3. **Load Tests**: Verify non-blocking behavior under concurrent requests +4. **Error Tests**: Verify error flow handling and script dispatch + +## 9. Migration Checklist + +- [ ] Create flow_manager.rs with FlowManager implementation +- [ ] Add flow_manager module to lib.rs +- [ ] Update Cargo.toml with rhai_dispatcher dependency +- [ ] Modify payment.rs to remove blocking code +- [ ] Add flow initialization functions +- [ ] Convert all create functions to non-blocking pattern +- [ ] Create flow script templates +- [ ] Test basic payment intent flow +- [ ] Test error handling flows +- [ ] Verify non-blocking behavior +- [ ] Update documentation + +This specification provides a complete roadmap for implementing the event-driven flow architecture using RhaiDispatcher. \ No newline at end of file diff --git a/rhailib/docs/NON_BLOCKING_ASYNC_DESIGN.md b/rhailib/docs/NON_BLOCKING_ASYNC_DESIGN.md new file mode 100644 index 0000000..30f55d5 --- /dev/null +++ b/rhailib/docs/NON_BLOCKING_ASYNC_DESIGN.md @@ -0,0 +1,468 @@ +# Non-Blocking Async Architecture Design + +## Problem Statement + +The current async architecture has a critical limitation: **slow API responses block the entire Rhai engine**, preventing other scripts from executing. When an API call takes 10 seconds, the Rhai engine is blocked for the full duration. + +## Current Blocking Behavior + +```rust +// This BLOCKS the Rhai execution thread! +response_receiver.recv_timeout(Duration::from_secs(30)) + .map_err(|e| format!("Failed to receive response: {}", e))? +``` + +**Impact:** +- ✅ Async worker thread: NOT blocked (continues processing) +- ❌ Rhai engine thread: BLOCKED (cannot execute other scripts) +- ❌ Other Rhai scripts: QUEUED (must wait) + +## Callback-Based Solution + +### Architecture Overview + +```mermaid +graph TB + subgraph "Rhai Engine Thread (Non-Blocking)" + RS1[Rhai Script 1] + RS2[Rhai Script 2] + RS3[Rhai Script 3] + RE[Rhai Engine] + end + + subgraph "Request Registry" + PR[Pending Requests Map] + RID[Request IDs] + end + + subgraph "Async Worker Thread" + AW[Async Worker] + HTTP[HTTP Client] + API[External APIs] + end + + RS1 --> RE + RS2 --> RE + RS3 --> RE + RE --> PR + PR --> AW + AW --> HTTP + HTTP --> API + API --> HTTP + HTTP --> AW + AW --> PR + PR --> RE +``` + +### Core Data Structures + +```rust +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; +use uuid::Uuid; + +// Global registry for pending requests +static PENDING_REQUESTS: Mutex> = Mutex::new(HashMap::new()); + +#[derive(Debug)] +pub struct PendingRequest { + pub id: String, + pub status: RequestStatus, + pub result: Option>, + pub created_at: std::time::Instant, +} + +#[derive(Debug, Clone)] +pub enum RequestStatus { + Pending, + Completed, + Failed, + Timeout, +} + +#[derive(Debug)] +pub struct AsyncRequest { + pub id: String, // Unique request ID + pub endpoint: String, + pub method: String, + pub data: HashMap, + // No response channel - results stored in global registry +} +``` + +### Non-Blocking Request Function + +```rust +impl AsyncFunctionRegistry { + // Non-blocking version - returns immediately + pub fn make_request_async(&self, endpoint: String, method: String, data: HashMap) -> Result { + let request_id = Uuid::new_v4().to_string(); + + // Store pending request + { + let mut pending = PENDING_REQUESTS.lock().unwrap(); + pending.insert(request_id.clone(), PendingRequest { + id: request_id.clone(), + status: RequestStatus::Pending, + result: None, + created_at: std::time::Instant::now(), + }); + } + + let request = AsyncRequest { + id: request_id.clone(), + endpoint, + method, + data, + }; + + // Send to async worker (non-blocking) + self.request_sender.send(request) + .map_err(|_| "Failed to send request to async worker".to_string())?; + + // Return request ID immediately - NO BLOCKING! + Ok(request_id) + } + + // Check if request is complete + pub fn is_request_complete(&self, request_id: &str) -> bool { + let pending = PENDING_REQUESTS.lock().unwrap(); + if let Some(request) = pending.get(request_id) { + matches!(request.status, RequestStatus::Completed | RequestStatus::Failed | RequestStatus::Timeout) + } else { + false + } + } + + // Get request result (non-blocking) + pub fn get_request_result(&self, request_id: &str) -> Result { + let mut pending = PENDING_REQUESTS.lock().unwrap(); + if let Some(request) = pending.remove(request_id) { + match request.result { + Some(result) => result, + None => Err("Request not completed yet".to_string()), + } + } else { + Err("Request not found".to_string()) + } + } +} +``` + +### Updated Async Worker + +```rust +async fn async_worker_loop(config: StripeConfig, receiver: Receiver) { + println!("🚀 Async worker thread started"); + + loop { + match receiver.recv_timeout(Duration::from_millis(100)) { + Ok(request) => { + let request_id = request.id.clone(); + let result = Self::handle_stripe_request(&config, &request).await; + + // Store result in global registry instead of sending through channel + { + let mut pending = PENDING_REQUESTS.lock().unwrap(); + if let Some(pending_request) = pending.get_mut(&request_id) { + pending_request.result = Some(result.clone()); + pending_request.status = match result { + Ok(_) => RequestStatus::Completed, + Err(_) => RequestStatus::Failed, + }; + } + } + + println!("✅ Request {} completed", request_id); + } + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue, + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, + } + } +} +``` + +### Rhai Function Registration + +```rust +#[export_module] +mod rhai_payment_module { + // Async version - returns request ID immediately + #[rhai_fn(name = "create_async", return_raw)] + pub fn create_product_async(product: &mut RhaiProduct) -> Result> { + let registry = ASYNC_REGISTRY.lock().unwrap(); + let registry = registry.as_ref().ok_or("Stripe not configured")?; + + let form_data = prepare_product_data(product); + let request_id = registry.make_request_async("products".to_string(), "POST".to_string(), form_data) + .map_err(|e| e.to_string())?; + + Ok(request_id) + } + + // Check if async request is complete + #[rhai_fn(name = "is_complete", return_raw)] + pub fn is_request_complete(request_id: String) -> Result> { + let registry = ASYNC_REGISTRY.lock().unwrap(); + let registry = registry.as_ref().ok_or("Stripe not configured")?; + + Ok(registry.is_request_complete(&request_id)) + } + + // Get result of async request + #[rhai_fn(name = "get_result", return_raw)] + pub fn get_request_result(request_id: String) -> Result> { + let registry = ASYNC_REGISTRY.lock().unwrap(); + let registry = registry.as_ref().ok_or("Stripe not configured")?; + + registry.get_request_result(&request_id) + .map_err(|e| e.to_string().into()) + } + + // Convenience function - wait for result with polling + #[rhai_fn(name = "await_result", return_raw)] + pub fn await_request_result(request_id: String, timeout_seconds: i64) -> Result> { + let registry = ASYNC_REGISTRY.lock().unwrap(); + let registry = registry.as_ref().ok_or("Stripe not configured")?; + + let start_time = std::time::Instant::now(); + let timeout = Duration::from_secs(timeout_seconds as u64); + + // Non-blocking polling loop + loop { + if registry.is_request_complete(&request_id) { + return registry.get_request_result(&request_id) + .map_err(|e| e.to_string().into()); + } + + if start_time.elapsed() > timeout { + return Err("Request timeout".to_string().into()); + } + + // Small delay to prevent busy waiting + std::thread::sleep(Duration::from_millis(50)); + } + } +} +``` + +## Usage Patterns + +### 1. Fire-and-Forget Pattern +```rhai +configure_stripe(STRIPE_API_KEY); + +// Start multiple async operations immediately - NO BLOCKING! +let product_req = new_product() + .name("Product 1") + .create_async(); + +let price_req = new_price() + .amount(1000) + .create_async(); + +let coupon_req = new_coupon() + .percent_off(25) + .create_async(); + +print("All requests started, continuing with other work..."); + +// Do other work while APIs are processing +for i in 1..100 { + print(`Doing work: ${i}`); +} + +// Check results when ready +if is_complete(product_req) { + let product_id = get_result(product_req); + print(`Product created: ${product_id}`); +} +``` + +### 2. Polling Pattern +```rhai +// Start async operation +let request_id = new_product() + .name("My Product") + .create_async(); + +print("Request started, polling for completion..."); + +// Poll until complete (non-blocking) +let max_attempts = 100; +let attempt = 0; + +while attempt < max_attempts { + if is_complete(request_id) { + let result = get_result(request_id); + print(`Success: ${result}`); + break; + } + + print(`Attempt ${attempt}: still waiting...`); + attempt += 1; + + // Small delay between checks + sleep(100); +} +``` + +### 3. Await Pattern (Convenience) +```rhai +// Start async operation and wait for result +let request_id = new_product() + .name("My Product") + .create_async(); + +print("Request started, waiting for result..."); + +// This polls internally but doesn't block other scripts +try { + let product_id = await_result(request_id, 30); // 30 second timeout + print(`Product created: ${product_id}`); +} catch(error) { + print(`Failed: ${error}`); +} +``` + +### 4. Concurrent Operations +```rhai +// Start multiple operations concurrently +let requests = []; + +for i in 1..5 { + let req = new_product() + .name(`Product ${i}`) + .create_async(); + requests.push(req); +} + +print("Started 5 concurrent product creations"); + +// Wait for all to complete +let results = []; +for req in requests { + let result = await_result(req, 30); + results.push(result); + print(`Product created: ${result}`); +} + +print(`All ${results.len()} products created!`); +``` + +## Execution Flow Comparison + +### Current Blocking Architecture +```mermaid +sequenceDiagram + participant R1 as Rhai Script 1 + participant R2 as Rhai Script 2 + participant RE as Rhai Engine + participant AR as AsyncRegistry + participant AW as Async Worker + + R1->>RE: product.create() + RE->>AR: make_request() + AR->>AW: send request + Note over RE: 🚫 BLOCKED for up to 30 seconds + Note over R2: ⏳ Cannot execute - engine blocked + AW->>AR: response (after 10 seconds) + AR->>RE: unblock + RE->>R1: return result + R2->>RE: Now can execute +``` + +### New Non-Blocking Architecture +```mermaid +sequenceDiagram + participant R1 as Rhai Script 1 + participant R2 as Rhai Script 2 + participant RE as Rhai Engine + participant AR as AsyncRegistry + participant AW as Async Worker + + R1->>RE: product.create_async() + RE->>AR: make_request_async() + AR->>AW: send request + AR->>RE: return request_id (immediate) + RE->>R1: return request_id + Note over R1: Script 1 continues... + + R2->>RE: other_operation() + Note over RE: ✅ Engine available immediately + RE->>R2: result + + AW->>AR: store result in registry + R1->>RE: is_complete(request_id) + RE->>R1: true + R1->>RE: get_result(request_id) + RE->>R1: product_id +``` + +## Benefits + +### 1. **Complete Non-Blocking Execution** +- Rhai engine never blocks on API calls +- Multiple scripts can execute concurrently +- Better resource utilization + +### 2. **Backward Compatibility** +```rhai +// Keep existing blocking API for simple cases +let product_id = new_product().name("Simple").create(); + +// Use async API for concurrent operations +let request_id = new_product().name("Async").create_async(); +``` + +### 3. **Flexible Programming Patterns** +- **Fire-and-forget**: Start operation, check later +- **Polling**: Check periodically until complete +- **Await**: Convenience function with timeout +- **Concurrent**: Start multiple operations simultaneously + +### 4. **Resource Management** +```rust +// Automatic cleanup of completed requests +impl AsyncFunctionRegistry { + pub fn cleanup_old_requests(&self) { + let mut pending = PENDING_REQUESTS.lock().unwrap(); + let now = std::time::Instant::now(); + + pending.retain(|_, request| { + // Remove requests older than 5 minutes + now.duration_since(request.created_at) < Duration::from_secs(300) + }); + } +} +``` + +## Performance Comparison + +| Architecture | Blocking Behavior | Concurrent Scripts | API Latency Impact | +|-------------|------------------|-------------------|-------------------| +| **Current** | ❌ Blocks engine | ❌ Sequential only | ❌ Blocks all execution | +| **Callback** | ✅ Non-blocking | ✅ Unlimited concurrent | ✅ No impact on other scripts | + +## Implementation Strategy + +### Phase 1: Add Async Functions +- Implement callback-based functions alongside existing ones +- Add `create_async()`, `is_complete()`, `get_result()`, `await_result()` +- Maintain backward compatibility + +### Phase 2: Enhanced Features +- Add batch operations for multiple concurrent requests +- Implement request prioritization +- Add metrics and monitoring + +### Phase 3: Migration Path +- Provide migration guide for existing scripts +- Consider deprecating blocking functions in favor of async ones +- Add performance benchmarks + +## Conclusion + +The callback-based solution completely eliminates the blocking problem while maintaining a clean, intuitive API for Rhai scripts. This enables true concurrent execution of multiple scripts with external API integration, dramatically improving the system's scalability and responsiveness. + +The key innovation is replacing synchronous blocking calls with an asynchronous request/response pattern that stores results in a shared registry, allowing the Rhai engine to remain responsive while API operations complete in the background. \ No newline at end of file diff --git a/rhailib/docs/SIMPLE_NON_BLOCKING_ARCHITECTURE.md b/rhailib/docs/SIMPLE_NON_BLOCKING_ARCHITECTURE.md new file mode 100644 index 0000000..14877e9 --- /dev/null +++ b/rhailib/docs/SIMPLE_NON_BLOCKING_ARCHITECTURE.md @@ -0,0 +1,376 @@ +# Simple Non-Blocking Architecture (No Globals, No Locking) + +## Core Principle + +**Single-threaded Rhai engine with fire-and-forget HTTP requests that dispatch response scripts** + +## Architecture Flow + +```mermaid +graph TD + A[Rhai: create_payment_intent] --> B[Function: create_payment_intent] + B --> C[Spawn Thread] + B --> D[Return Immediately] + C --> E[HTTP Request to Stripe] + E --> F{Response} + F -->|Success| G[Dispatch: new_create_payment_intent_response.rhai] + F -->|Error| H[Dispatch: new_create_payment_intent_error.rhai] + G --> I[New Rhai Script Execution] + H --> J[New Rhai Script Execution] +``` + +## Key Design Principles + +1. **No Global State** - All configuration passed as parameters +2. **No Locking** - No shared state between threads +3. **Fire-and-Forget** - Functions return immediately +4. **Self-Contained Threads** - Each thread has everything it needs +5. **Script Dispatch** - Responses trigger new Rhai script execution + +## Implementation + +### 1. Simple Function Signature + +```rust +#[rhai_fn(name = "create", return_raw)] +pub fn create_payment_intent( + intent: &mut RhaiPaymentIntent, + worker_id: String, + context_id: String, + stripe_secret: String +) -> Result> { + let form_data = prepare_payment_intent_data(intent); + + // Spawn completely independent thread + thread::spawn(move || { + let rt = Runtime::new().expect("Failed to create runtime"); + rt.block_on(async { + // Create HTTP client in thread + let client = Client::new(); + + // Make HTTP request + match make_stripe_request(&client, &stripe_secret, "payment_intents", &form_data).await { + Ok(response) => { + dispatch_response_script( + &worker_id, + &context_id, + "new_create_payment_intent_response", + &response + ).await; + } + Err(error) => { + dispatch_error_script( + &worker_id, + &context_id, + "new_create_payment_intent_error", + &error + ).await; + } + } + }); + }); + + // Return immediately - no waiting! + Ok("payment_intent_request_dispatched".to_string()) +} +``` + +### 2. Self-Contained HTTP Function + +```rust +async fn make_stripe_request( + client: &Client, + secret_key: &str, + endpoint: &str, + form_data: &HashMap +) -> Result { + let url = format!("https://api.stripe.com/v1/{}", endpoint); + + let response = client + .post(&url) + .basic_auth(secret_key, None::<&str>) + .form(form_data) + .send() + .await + .map_err(|e| format!("HTTP request failed: {}", e))?; + + let response_text = response.text().await + .map_err(|e| format!("Failed to read response: {}", e))?; + + // Return raw response - let script handle parsing + Ok(response_text) +} +``` + +### 3. Simple Script Dispatch + +```rust +async fn dispatch_response_script( + worker_id: &str, + context_id: &str, + script_name: &str, + response_data: &str +) { + let script_content = format!( + r#" + // Response data from API + let response_json = `{}`; + let parsed_data = parse_json(response_json); + + // Execute the response script + eval_file("flows/{}.rhai"); + "#, + response_data.replace('`', r#"\`"#), + script_name + ); + + // Create dispatcher instance just for this dispatch + if let Ok(dispatcher) = RhaiDispatcherBuilder::new() + .caller_id("stripe") + .worker_id(worker_id) + .context_id(context_id) + .redis_url("redis://127.0.0.1/") + .build() + { + let _ = dispatcher + .new_play_request() + .script(&script_content) + .submit() + .await; + } +} + +async fn dispatch_error_script( + worker_id: &str, + context_id: &str, + script_name: &str, + error_data: &str +) { + let script_content = format!( + r#" + // Error data from API + let error_json = `{}`; + let parsed_error = parse_json(error_json); + + // Execute the error script + eval_file("flows/{}.rhai"); + "#, + error_data.replace('`', r#"\`"#), + script_name + ); + + // Create dispatcher instance just for this dispatch + if let Ok(dispatcher) = RhaiDispatcherBuilder::new() + .caller_id("stripe") + .worker_id(worker_id) + .context_id(context_id) + .redis_url("redis://127.0.0.1/") + .build() + { + let _ = dispatcher + .new_play_request() + .script(&script_content) + .submit() + .await; + } +} +``` + +## Complete Function Implementations + +### Payment Intent + +```rust +#[rhai_fn(name = "create_async", return_raw)] +pub fn create_payment_intent_async( + intent: &mut RhaiPaymentIntent, + worker_id: String, + context_id: String, + stripe_secret: String +) -> Result> { + let form_data = prepare_payment_intent_data(intent); + + thread::spawn(move || { + let rt = Runtime::new().expect("Failed to create runtime"); + rt.block_on(async { + let client = Client::new(); + match make_stripe_request(&client, &stripe_secret, "payment_intents", &form_data).await { + Ok(response) => { + dispatch_response_script(&worker_id, &context_id, "new_create_payment_intent_response", &response).await; + } + Err(error) => { + dispatch_error_script(&worker_id, &context_id, "new_create_payment_intent_error", &error).await; + } + } + }); + }); + + Ok("payment_intent_request_dispatched".to_string()) +} +``` + +### Product + +```rust +#[rhai_fn(name = "create_async", return_raw)] +pub fn create_product_async( + product: &mut RhaiProduct, + worker_id: String, + context_id: String, + stripe_secret: String +) -> Result> { + let form_data = prepare_product_data(product); + + thread::spawn(move || { + let rt = Runtime::new().expect("Failed to create runtime"); + rt.block_on(async { + let client = Client::new(); + match make_stripe_request(&client, &stripe_secret, "products", &form_data).await { + Ok(response) => { + dispatch_response_script(&worker_id, &context_id, "new_create_product_response", &response).await; + } + Err(error) => { + dispatch_error_script(&worker_id, &context_id, "new_create_product_error", &error).await; + } + } + }); + }); + + Ok("product_request_dispatched".to_string()) +} +``` + +### Price + +```rust +#[rhai_fn(name = "create_async", return_raw)] +pub fn create_price_async( + price: &mut RhaiPrice, + worker_id: String, + context_id: String, + stripe_secret: String +) -> Result> { + let form_data = prepare_price_data(price); + + thread::spawn(move || { + let rt = Runtime::new().expect("Failed to create runtime"); + rt.block_on(async { + let client = Client::new(); + match make_stripe_request(&client, &stripe_secret, "prices", &form_data).await { + Ok(response) => { + dispatch_response_script(&worker_id, &context_id, "new_create_price_response", &response).await; + } + Err(error) => { + dispatch_error_script(&worker_id, &context_id, "new_create_price_error", &error).await; + } + } + }); + }); + + Ok("price_request_dispatched".to_string()) +} +``` + +### Subscription + +```rust +#[rhai_fn(name = "create_async", return_raw)] +pub fn create_subscription_async( + subscription: &mut RhaiSubscription, + worker_id: String, + context_id: String, + stripe_secret: String +) -> Result> { + let form_data = prepare_subscription_data(subscription); + + thread::spawn(move || { + let rt = Runtime::new().expect("Failed to create runtime"); + rt.block_on(async { + let client = Client::new(); + match make_stripe_request(&client, &stripe_secret, "subscriptions", &form_data).await { + Ok(response) => { + dispatch_response_script(&worker_id, &context_id, "new_create_subscription_response", &response).await; + } + Err(error) => { + dispatch_error_script(&worker_id, &context_id, "new_create_subscription_error", &error).await; + } + } + }); + }); + + Ok("subscription_request_dispatched".to_string()) +} +``` + +## Usage Example + +### main.rhai +```rhai +// No initialization needed - no global state! + +let payment_intent = new_payment_intent() + .amount(2000) + .currency("usd") + .customer("cus_customer123"); + +// Pass all required parameters - no globals! +let result = payment_intent.create_async( + "worker-1", // worker_id + "context-123", // context_id + "sk_test_..." // stripe_secret +); + +print(`Request dispatched: ${result}`); + +// Script ends immediately, HTTP happens in background +// Response will trigger new_create_payment_intent_response.rhai +``` + +### flows/new_create_payment_intent_response.rhai +```rhai +let payment_intent_id = parsed_data.id; +let status = parsed_data.status; + +print(`✅ Payment Intent Created: ${payment_intent_id}`); +print(`Status: ${status}`); + +// Continue flow if needed +if status == "requires_payment_method" { + print("Ready for frontend payment collection"); +} +``` + +### flows/new_create_payment_intent_error.rhai +```rhai +let error_type = parsed_error.error.type; +let error_message = parsed_error.error.message; + +print(`❌ Payment Intent Failed: ${error_type}`); +print(`Message: ${error_message}`); + +// Handle error appropriately +if error_type == "card_error" { + print("Card was declined"); +} +``` + +## Benefits of This Architecture + +1. **Zero Global State** - Everything is passed as parameters +2. **Zero Locking** - No shared state to lock +3. **True Non-Blocking** - Functions return immediately +4. **Thread Independence** - Each thread is completely self-contained +5. **Simple Testing** - Easy to test individual functions +6. **Clear Data Flow** - Parameters make dependencies explicit +7. **No Memory Leaks** - No persistent global state +8. **Horizontal Scaling** - No shared state to synchronize + +## Migration from Current Code + +1. **Remove all global state** (ASYNC_REGISTRY, etc.) +2. **Remove all Mutex/locking code** +3. **Add parameters to function signatures** +4. **Create dispatcher instances in threads** +5. **Update Rhai scripts to pass parameters** + +This architecture is much simpler, has no global state, no locking, and provides true non-blocking behavior while maintaining the event-driven flow pattern you want. \ No newline at end of file diff --git a/rhailib/docs/TASK_LIFECYCLE_VERIFICATION.md b/rhailib/docs/TASK_LIFECYCLE_VERIFICATION.md new file mode 100644 index 0000000..c7e342e --- /dev/null +++ b/rhailib/docs/TASK_LIFECYCLE_VERIFICATION.md @@ -0,0 +1,73 @@ +# Task Lifecycle Verification + +## Test: Spawned Task Continues After Function Returns + +```rust +use tokio::time::{sleep, Duration}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +#[tokio::test] +async fn test_spawned_task_continues() { + let completed = Arc::new(AtomicBool::new(false)); + let completed_clone = completed.clone(); + + // Function that spawns a task and returns immediately + fn spawn_long_task(flag: Arc) -> String { + tokio::spawn(async move { + // Simulate HTTP request (2 seconds) + sleep(Duration::from_secs(2)).await; + + // Mark as completed + flag.store(true, Ordering::SeqCst); + println!("Background task completed!"); + }); + + // Return immediately + "task_spawned".to_string() + } + + // Call the function + let result = spawn_long_task(completed_clone); + assert_eq!(result, "task_spawned"); + + // Function returned, but task should still be running + assert_eq!(completed.load(Ordering::SeqCst), false); + + // Wait for background task to complete + sleep(Duration::from_secs(3)).await; + + // Verify task completed successfully + assert_eq!(completed.load(Ordering::SeqCst), true); +} +``` + +## Test Results + +✅ **Function returns immediately** (microseconds) +✅ **Spawned task continues running** (2+ seconds) +✅ **Task completes successfully** after function has returned +✅ **No blocking or hanging** + +## Real-World Behavior + +```rust +// Rhai calls this function +let result = payment_intent.create_async("worker-1", "context-123", "sk_test_..."); +// result = "payment_intent_request_dispatched" (returned in ~1ms) + +// Meanwhile, in the background (2-5 seconds later): +// 1. HTTP request to Stripe API +// 2. Response received +// 3. New Rhai script dispatched: "flows/new_create_payment_intent_response.rhai" +``` + +## Key Guarantees + +1. **Non-blocking**: Rhai function returns immediately +2. **Fire-and-forget**: HTTP request continues in background +3. **Event-driven**: Response triggers new script execution +4. **No memory leaks**: Task is self-contained with moved ownership +5. **Runtime managed**: tokio handles task scheduling and cleanup + +The spawned task is completely independent and will run to completion regardless of what happens to the function that created it. \ No newline at end of file diff --git a/rhailib/docs/TRUE_NON_BLOCKING_IMPLEMENTATION.md b/rhailib/docs/TRUE_NON_BLOCKING_IMPLEMENTATION.md new file mode 100644 index 0000000..adcca6d --- /dev/null +++ b/rhailib/docs/TRUE_NON_BLOCKING_IMPLEMENTATION.md @@ -0,0 +1,369 @@ +# True Non-Blocking Implementation (No rt.block_on) + +## Problem with Previous Approach + +The issue was using `rt.block_on()` which blocks the spawned thread: + +```rust +// THIS BLOCKS THE THREAD: +thread::spawn(move || { + let rt = Runtime::new().expect("Failed to create runtime"); + rt.block_on(async { // <-- This blocks! + // async code here + }); +}); +``` + +## Solution: Use tokio::spawn Instead + +Use `tokio::spawn` to run async code without blocking: + +```rust +// THIS DOESN'T BLOCK: +tokio::spawn(async move { + // async code runs in tokio's thread pool + let client = Client::new(); + match make_stripe_request(&client, &stripe_secret, "payment_intents", &form_data).await { + Ok(response) => { + dispatch_response_script(&worker_id, &context_id, "new_create_payment_intent_response", &response).await; + } + Err(error) => { + dispatch_error_script(&worker_id, &context_id, "new_create_payment_intent_error", &error).await; + } + } +}); +``` + +## Complete Corrected Implementation + +### Payment Intent Function (Corrected) + +```rust +#[rhai_fn(name = "create_async", return_raw)] +pub fn create_payment_intent_async( + intent: &mut RhaiPaymentIntent, + worker_id: String, + context_id: String, + stripe_secret: String +) -> Result> { + let form_data = prepare_payment_intent_data(intent); + + // Use tokio::spawn instead of thread::spawn + rt.block_on + tokio::spawn(async move { + let client = Client::new(); + match make_stripe_request(&client, &stripe_secret, "payment_intents", &form_data).await { + Ok(response) => { + dispatch_response_script( + &worker_id, + &context_id, + "new_create_payment_intent_response", + &response + ).await; + } + Err(error) => { + dispatch_error_script( + &worker_id, + &context_id, + "new_create_payment_intent_error", + &error + ).await; + } + } + }); + + // Returns immediately - no blocking! + Ok("payment_intent_request_dispatched".to_string()) +} +``` + +### Product Function (Corrected) + +```rust +#[rhai_fn(name = "create_async", return_raw)] +pub fn create_product_async( + product: &mut RhaiProduct, + worker_id: String, + context_id: String, + stripe_secret: String +) -> Result> { + let form_data = prepare_product_data(product); + + tokio::spawn(async move { + let client = Client::new(); + match make_stripe_request(&client, &stripe_secret, "products", &form_data).await { + Ok(response) => { + dispatch_response_script( + &worker_id, + &context_id, + "new_create_product_response", + &response + ).await; + } + Err(error) => { + dispatch_error_script( + &worker_id, + &context_id, + "new_create_product_error", + &error + ).await; + } + } + }); + + Ok("product_request_dispatched".to_string()) +} +``` + +### Price Function (Corrected) + +```rust +#[rhai_fn(name = "create_async", return_raw)] +pub fn create_price_async( + price: &mut RhaiPrice, + worker_id: String, + context_id: String, + stripe_secret: String +) -> Result> { + let form_data = prepare_price_data(price); + + tokio::spawn(async move { + let client = Client::new(); + match make_stripe_request(&client, &stripe_secret, "prices", &form_data).await { + Ok(response) => { + dispatch_response_script( + &worker_id, + &context_id, + "new_create_price_response", + &response + ).await; + } + Err(error) => { + dispatch_error_script( + &worker_id, + &context_id, + "new_create_price_error", + &error + ).await; + } + } + }); + + Ok("price_request_dispatched".to_string()) +} +``` + +### Subscription Function (Corrected) + +```rust +#[rhai_fn(name = "create_async", return_raw)] +pub fn create_subscription_async( + subscription: &mut RhaiSubscription, + worker_id: String, + context_id: String, + stripe_secret: String +) -> Result> { + let form_data = prepare_subscription_data(subscription); + + tokio::spawn(async move { + let client = Client::new(); + match make_stripe_request(&client, &stripe_secret, "subscriptions", &form_data).await { + Ok(response) => { + dispatch_response_script( + &worker_id, + &context_id, + "new_create_subscription_response", + &response + ).await; + } + Err(error) => { + dispatch_error_script( + &worker_id, + &context_id, + "new_create_subscription_error", + &error + ).await; + } + } + }); + + Ok("subscription_request_dispatched".to_string()) +} +``` + +### Coupon Function (Corrected) + +```rust +#[rhai_fn(name = "create_async", return_raw)] +pub fn create_coupon_async( + coupon: &mut RhaiCoupon, + worker_id: String, + context_id: String, + stripe_secret: String +) -> Result> { + let form_data = prepare_coupon_data(coupon); + + tokio::spawn(async move { + let client = Client::new(); + match make_stripe_request(&client, &stripe_secret, "coupons", &form_data).await { + Ok(response) => { + dispatch_response_script( + &worker_id, + &context_id, + "new_create_coupon_response", + &response + ).await; + } + Err(error) => { + dispatch_error_script( + &worker_id, + &context_id, + "new_create_coupon_error", + &error + ).await; + } + } + }); + + Ok("coupon_request_dispatched".to_string()) +} +``` + +## Helper Functions (Same as Before) + +```rust +async fn make_stripe_request( + client: &Client, + secret_key: &str, + endpoint: &str, + form_data: &HashMap +) -> Result { + let url = format!("https://api.stripe.com/v1/{}", endpoint); + + let response = client + .post(&url) + .basic_auth(secret_key, None::<&str>) + .form(form_data) + .send() + .await + .map_err(|e| format!("HTTP request failed: {}", e))?; + + let response_text = response.text().await + .map_err(|e| format!("Failed to read response: {}", e))?; + + Ok(response_text) +} + +async fn dispatch_response_script( + worker_id: &str, + context_id: &str, + script_name: &str, + response_data: &str +) { + let script_content = format!( + r#" + let response_json = `{}`; + let parsed_data = parse_json(response_json); + eval_file("flows/{}.rhai"); + "#, + response_data.replace('`', r#"\`"#), + script_name + ); + + if let Ok(dispatcher) = RhaiDispatcherBuilder::new() + .caller_id("stripe") + .worker_id(worker_id) + .context_id(context_id) + .redis_url("redis://127.0.0.1/") + .build() + { + let _ = dispatcher + .new_play_request() + .script(&script_content) + .submit() + .await; + } +} + +async fn dispatch_error_script( + worker_id: &str, + context_id: &str, + script_name: &str, + error_data: &str +) { + let script_content = format!( + r#" + let error_json = `{}`; + let parsed_error = parse_json(error_json); + eval_file("flows/{}.rhai"); + "#, + error_data.replace('`', r#"\`"#), + script_name + ); + + if let Ok(dispatcher) = RhaiDispatcherBuilder::new() + .caller_id("stripe") + .worker_id(worker_id) + .context_id(context_id) + .redis_url("redis://127.0.0.1/") + .build() + { + let _ = dispatcher + .new_play_request() + .script(&script_content) + .submit() + .await; + } +} +``` + +## Key Differences + +### Before (Blocking): +```rust +thread::spawn(move || { + let rt = Runtime::new().expect("Failed to create runtime"); + rt.block_on(async { // <-- BLOCKS THE THREAD + // async code + }); +}); +``` + +### After (Non-Blocking): +```rust +tokio::spawn(async move { // <-- DOESN'T BLOCK + // async code runs in tokio's thread pool +}); +``` + +## Benefits of tokio::spawn + +1. **No Blocking** - Uses tokio's async runtime, doesn't block +2. **Efficient** - Reuses existing tokio thread pool +3. **Lightweight** - No need to create new runtime per request +4. **Scalable** - Can handle many concurrent requests +5. **Simple** - Less code, cleaner implementation + +## Usage (Same as Before) + +```rhai +let payment_intent = new_payment_intent() + .amount(2000) + .currency("usd") + .customer("cus_customer123"); + +// This returns immediately, HTTP happens asynchronously +let result = payment_intent.create_async( + "worker-1", + "context-123", + "sk_test_..." +); + +print(`Request dispatched: ${result}`); +// Script ends, but HTTP continues in background +``` + +## Requirements + +Make sure your application is running in a tokio runtime context. If not, you might need to ensure the Rhai engine is running within a tokio runtime. + +This implementation provides true non-blocking behavior - the Rhai function returns immediately while the HTTP request and script dispatch happen asynchronously in the background. \ No newline at end of file diff --git a/rhailib/examples/NON_BLOCKING_PAYMENT_IMPLEMENTATION.md b/rhailib/examples/NON_BLOCKING_PAYMENT_IMPLEMENTATION.md new file mode 100644 index 0000000..0acb76c --- /dev/null +++ b/rhailib/examples/NON_BLOCKING_PAYMENT_IMPLEMENTATION.md @@ -0,0 +1,222 @@ +# Non-Blocking Payment Implementation + +This document describes the implementation of non-blocking payment functions using `tokio::spawn` based on the TRUE_NON_BLOCKING_IMPLEMENTATION architecture. + +## Overview + +The payment functions have been completely rewritten to use `tokio::spawn` instead of blocking operations, providing true non-blocking behavior with event-driven response handling. + +## Key Changes + +### 1. Removed Global State and Locking +- ❌ Removed `ASYNC_REGISTRY` static mutex +- ❌ Removed `AsyncFunctionRegistry` struct +- ❌ Removed blocking worker thread implementation +- ✅ All configuration now passed as parameters + +### 2. Implemented tokio::spawn Pattern +- ✅ All `create_async` functions use `tokio::spawn` +- ✅ Functions return immediately with dispatch confirmation +- ✅ HTTP requests happen in background +- ✅ No blocking operations + +### 3. Event-Driven Response Handling +- ✅ Uses `RhaiDispatcher` for response/error scripts +- ✅ Configurable worker_id and context_id per request +- ✅ Automatic script execution on completion + +## Function Signatures + +All payment creation functions now follow this pattern: + +```rust +#[rhai_fn(name = "create_async", return_raw)] +pub fn create_[type]_async( + object: &mut Rhai[Type], + worker_id: String, + context_id: String, + stripe_secret: String +) -> Result> +``` + +### Available Functions: +- `create_product_async()` +- `create_price_async()` +- `create_subscription_async()` +- `create_payment_intent_async()` +- `create_coupon_async()` + +## Usage Example + +```rhai +// Create a payment intent asynchronously +let payment_intent = new_payment_intent() + .amount(2000) + .currency("usd") + .customer("cus_customer123"); + +// This returns immediately - no blocking! +let result = payment_intent.create_async( + "payment-worker-1", + "context-123", + "sk_test_your_stripe_secret_key" +); + +print(`Request dispatched: ${result}`); +// Script continues immediately while HTTP happens in background +``` + +## Response Handling + +When the HTTP request completes, response/error scripts are automatically triggered: + +### Success Response +- Script: `flows/new_create_payment_intent_response.rhai` +- Data: `parsed_data` contains the Stripe response JSON + +### Error Response +- Script: `flows/new_create_payment_intent_error.rhai` +- Data: `parsed_error` contains the error message + +## Architecture Benefits + +### 1. True Non-Blocking +- Functions return in < 1ms +- No thread blocking +- Concurrent request capability + +### 2. Scalable +- Uses tokio's efficient thread pool +- No per-request thread creation +- Handles thousands of concurrent requests + +### 3. Event-Driven +- Automatic response handling +- Configurable workflows +- Error handling and recovery + +### 4. Stateless +- No global state +- Configuration per request +- Easy to test and debug + +## Testing + +### Performance Test +```bash +cd ../rhailib/examples +cargo run --bin non_blocking_payment_test +``` + +### Usage Example +```bash +# Run the Rhai script example +rhai payment_usage_example.rhai +``` + +## Implementation Details + +### HTTP Request Function +```rust +async fn make_stripe_request( + client: &Client, + secret_key: &str, + endpoint: &str, + form_data: &HashMap +) -> Result +``` + +### Response Dispatcher +```rust +async fn dispatch_response_script( + worker_id: &str, + context_id: &str, + script_name: &str, + response_data: &str +) +``` + +### Error Dispatcher +```rust +async fn dispatch_error_script( + worker_id: &str, + context_id: &str, + script_name: &str, + error_data: &str +) +``` + +## Migration from Old Implementation + +### Before (Blocking) +```rhai +// Old blocking implementation +let product = new_product().name("Test"); +let result = product.create(); // Blocks for 500ms+ +``` + +### After (Non-Blocking) +```rhai +// New non-blocking implementation +let product = new_product().name("Test"); +let result = product.create_async( + "worker-1", + "context-123", + "sk_test_key" +); // Returns immediately +``` + +## Configuration Requirements + +1. **Redis**: Required for RhaiDispatcher +2. **Tokio Runtime**: Must run within tokio context +3. **Response Scripts**: Create handler scripts in `flows/` directory + +## Error Handling + +The implementation includes comprehensive error handling: + +1. **HTTP Errors**: Network failures, timeouts +2. **API Errors**: Stripe API validation errors +3. **Dispatcher Errors**: Script execution failures + +All errors are logged and trigger appropriate error scripts. + +## Performance Characteristics + +- **Function Return Time**: < 1ms +- **Concurrent Requests**: Unlimited (tokio pool limited) +- **Memory Usage**: Minimal per request +- **CPU Usage**: Efficient async I/O + +## Files Created/Modified + +### Core Implementation +- `../rhailib/src/dsl/src/payment.rs` - Main implementation + +### Examples and Tests +- `non_blocking_payment_test.rs` - Performance test +- `payment_usage_example.rhai` - Usage example +- `flows/new_create_payment_intent_response.rhai` - Success handler +- `flows/new_create_payment_intent_error.rhai` - Error handler + +### Documentation +- `NON_BLOCKING_PAYMENT_IMPLEMENTATION.md` - This file + +## Next Steps + +1. **Integration Testing**: Test with real Stripe API +2. **Load Testing**: Verify performance under load +3. **Monitoring**: Add metrics and logging +4. **Documentation**: Update API documentation + +## Conclusion + +The non-blocking payment implementation provides: +- ✅ True non-blocking behavior +- ✅ Event-driven architecture +- ✅ Scalable concurrent processing +- ✅ No global state dependencies +- ✅ Comprehensive error handling + +This implementation follows the TRUE_NON_BLOCKING_IMPLEMENTATION pattern and provides a solid foundation for high-performance payment processing. \ No newline at end of file diff --git a/rhailib/examples/README.md b/rhailib/examples/README.md new file mode 100644 index 0000000..173e9f2 --- /dev/null +++ b/rhailib/examples/README.md @@ -0,0 +1,11 @@ +# Rhailib Examples + +This directory contains end-to-end examples demonstrating the usage of the `rhailib` project. These examples showcase how multiple crates from the workspace (such as `rhai_dispatcher`, `rhailib_engine`, and `rhailib_worker`) interact to build complete applications. + +Each example is self-contained in its own directory and includes a dedicated `README.md` with detailed explanations. + +## Available Examples + +- **[Access Control](./access_control/README.md)**: Demonstrates a practical access control scenario where a user, Alice, manages her own data, grants specific access to another user, Bob, and denies access to an unauthorized user, Charlie. This example highlights the built-in ownership and write protection provided by the Rhai worker. + +As more examples are added, they will be listed here. diff --git a/rhailib/examples/access_control/README.md b/rhailib/examples/access_control/README.md new file mode 100644 index 0000000..945b39e --- /dev/null +++ b/rhailib/examples/access_control/README.md @@ -0,0 +1,41 @@ +# Access Control Demonstration + +This example demonstrates a practical access control scenario using `rhailib`. It showcases how a user, Alice, can manage her own data within her Rhai worker, grant specific access rights to another user, Bob, and deny access to an unauthorized user, Charlie. + +## Overview + +The example involves three key participants: + +1. **Alice (`alice_pk`)**: The owner of the Rhai worker. She runs `alice.rhai` to populate her database with various objects and collections. Some of these are private, while others are explicitly shared with Bob. + +2. **Bob (`bob_pk`)**: A user who has been granted some access rights by Alice. In this example, he attempts to run `bob.rhai`, which tries to write data to Alice's worker. + +3. **Charlie (`charlie_pk`)**: An unauthorized user. He attempts to run `charlie.rhai`, which is identical to Bob's script. + +The core of the access control mechanism lies within the `rhailib_worker`. When a script is submitted for execution, the worker automatically enforces that the `CALLER_ID` matches the worker's own `CONTEXT_ID` for any write operations. This ensures that only the owner (Alice) can modify her data. + +## Scenario and Expected Outcomes + +1. **Alice Populates Her Database**: Alice's script (`alice.rhai`) runs first. It successfully creates: + - A private object. + - An object shared with Bob. + - A private collection containing a private book and slides that are individually shared with Bob. + - A shared collection. + This demonstrates that the owner of the worker can freely write to her own database. + +2. **Bob's Query**: Bob's script (`bob.rhai`) is executed next. The script attempts to create new objects in Alice's database. This operation fails with an `Insufficient authorization` error. The logs will show that `bob_pk` does not match the circle's public key, `alice_pk`. + +3. **Charlie's Query**: Charlie's script (`charlie.rhai`) also fails with the same authorization error, as he is not the owner of the worker. + +This example clearly illustrates the built-in ownership and write protection provided by the Rhai worker. + +## Running the Example + +Ensure Redis is running and accessible at `redis://127.0.0.1/`. + +From the `rhailib` root directory, run: +```bash +cargo run --example access_control +``` + +Observe the logs to see Alice's script complete successfully, followed by the authorization errors for Bob and Charlie, confirming that the access control is working as expected. diff --git a/rhailib/examples/access_control/alice.rhai b/rhailib/examples/access_control/alice.rhai new file mode 100644 index 0000000..34a3b8c --- /dev/null +++ b/rhailib/examples/access_control/alice.rhai @@ -0,0 +1,50 @@ +new_circle() + .title("Alice's Circle") + .description("Some objects in this circle are shared with Bob") + .save_circle(); + +let private_object = new_object() + .title("Alice's Private Object") + .description("This object can only be seen and modified by Alice") + .save_object(); + +let object_shared_with_bob = new_object() + .title("Alice's Shared Object") + .description("This object can be seen by Bob but modified only by Alice") + .save_object(); + +let new_access = new_access() + .object_id(object_shared_with_bob.id()) + .circle_public_key("bob_pk") + .save_access(); + +let book_private = new_book() + .title("Alice's private book") + .description("This book is prive to Alice") + .save_book(); + +let slides_shared = new_slides() + .title("Alice's shared slides") + .description("These slides, despite being in a private collection, are shared with Bob") + .save_slides(); + +let new_access = new_access() + .object_id(slides_shared.id) + .circle_public_key("bob_pk") + .save_access(); + +let collection_private = new_collection() + .title("Alice's private collection") + .description("This collection is only visible to Alice") + .add_book(book_private.id) + .add_slides(slides_shared.id) + .save_collection(); + + +let collection_shared = new_collection() + .title("Alice's shared collection") + .description("This collection is shared with Bob") + .save_collection(); + + + diff --git a/rhailib/examples/access_control/bob.rhai b/rhailib/examples/access_control/bob.rhai new file mode 100644 index 0000000..8df6954 --- /dev/null +++ b/rhailib/examples/access_control/bob.rhai @@ -0,0 +1,16 @@ +let private_object = new_object() + .title("Alice's Private Object") + .description("This object can only be seen and modified by Alice") + .save_object(); + +let object_shared_with_bob = new_object() + .title("Alice's Shared Collection") + .description("This object can be seen by Bob but modified only by Alice") + .save_object(); + +let new_access = new_access() + .object_id(object_shared_with_bob.id()) + .circle_public_key("bob_pk") + .save_access(); + + diff --git a/rhailib/examples/access_control/charlie.rhai b/rhailib/examples/access_control/charlie.rhai new file mode 100644 index 0000000..8df6954 --- /dev/null +++ b/rhailib/examples/access_control/charlie.rhai @@ -0,0 +1,16 @@ +let private_object = new_object() + .title("Alice's Private Object") + .description("This object can only be seen and modified by Alice") + .save_object(); + +let object_shared_with_bob = new_object() + .title("Alice's Shared Collection") + .description("This object can be seen by Bob but modified only by Alice") + .save_object(); + +let new_access = new_access() + .object_id(object_shared_with_bob.id()) + .circle_public_key("bob_pk") + .save_access(); + + diff --git a/rhailib/examples/access_control/circle.rhai b/rhailib/examples/access_control/circle.rhai new file mode 100644 index 0000000..fb30188 --- /dev/null +++ b/rhailib/examples/access_control/circle.rhai @@ -0,0 +1,51 @@ +new_circle() + .title("Alice and Charlie's Circle") + .description("Some objects in this circle are shared with Bob") + .add_member("alice_pk") + .add_member("charlie_pk") + .save_circle(); + +let private_object = new_object() + .title("Alice and Charlie's Private Object") + .description("This object can only be seen and modified by Alice and Charlie") + .save_object(); + +let object_shared_with_bob = new_object() + .title("Alice and Charlie's Shared Object") + .description("This object can be seen by Bob but modified only by Alice and Charlie") + .save_object(); + +let new_access = new_access() + .object_id(object_shared_with_bob.id()) + .circle_public_key("bob_pk") + .save_access(); + +let book_private = new_book() + .title("Alice and Charlie's private book") + .description("This book is prive to Alice and Charlie") + .save_book(); + +let slides_shared = new_slides() + .title("Alice and Charlie's shared slides") + .description("These slides, despite being in a private collection, are shared with Bob") + .save_slides(); + +let new_access = new_access() + .object_id(slides_shared.id) + .circle_public_key("bob_pk") + .save_access(); + +let collection_private = new_collection() + .title("Alice and Charlie's private collection") + .description("This collection is only visible to Alice and Charlie") + .add_book(book_private.id) + .add_slides(slides_shared.id) + .save_collection(); + +let collection_shared = new_collection() + .title("Alice and Charlie's shared collection") + .description("This collection is shared with Bob") + .save_collection(); + + + diff --git a/rhailib/examples/access_control/main.rs b/rhailib/examples/access_control/main.rs new file mode 100644 index 0000000..25990f3 --- /dev/null +++ b/rhailib/examples/access_control/main.rs @@ -0,0 +1,172 @@ +use rhai_dispatcher::RhaiDispatcherBuilder; +use rhailib_worker::spawn_rhai_worker; +use std::time::Duration; +use tempfile::Builder; +use tokio::sync::mpsc; + +const ALICE_ID: &str = "alice_pk"; +const BOB_ID: &str = "bob_pk"; +const CHARLIE_ID: &str = "charlie_pk"; +const CIRCLE_ID: &str = "circle_pk"; +const REDIS_URL: &str = "redis://127.0.0.1/"; + +#[tokio::main] +async fn main() -> Result<(), Box> { + env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init(); + + // Create a temporary directory for the database + let temp_dir = Builder::new().prefix("rhai-example").tempdir()?; + let db_path = temp_dir.path().to_str().unwrap().to_string(); + + // 1. Create a Rhai engine and register custom functionality + let engine = rhailib_engine::create_heromodels_engine(); + + // 2. Spawn the Rhai worker + let (shutdown_tx, shutdown_rx) = mpsc::channel(1); + let worker_handle = tokio::spawn(spawn_rhai_worker( + ALICE_ID.to_string(), + db_path.clone(), + engine, + REDIS_URL.to_string(), + shutdown_rx, + false, // use_sentinel + )); + + log::info!("Rhai worker spawned for circle: {}", ALICE_ID); + + // Give the worker a moment to start up + tokio::time::sleep(Duration::from_secs(1)).await; + + // Alice populates her rhai worker + let client_alice = RhaiDispatcherBuilder::new() + .redis_url(REDIS_URL) + .caller_id(ALICE_ID) + .build() + .unwrap(); + + client_alice + .new_play_request() + .worker_id(&ALICE_ID) + .context_id(&ALICE_ID) + .script_path("examples/access_control/alice.rhai") + .timeout(Duration::from_secs(10)) + .await_response() + .await + .unwrap(); + + log::info!("Alice's database populated."); + + // Bob queries Alice's rhai worker + let client_bob = RhaiDispatcherBuilder::new() + .redis_url(REDIS_URL) + .caller_id(BOB_ID) + .build() + .unwrap(); + + client_bob + .new_play_request() + .worker_id(&ALICE_ID) + .context_id(&ALICE_ID) + .script_path("examples/access_control/bob.rhai") + .timeout(Duration::from_secs(10)) + .await_response() + .await + .unwrap(); + + log::info!("Bob's query to Alice's database completed."); + + // Charlie queries Alice's rhai worker + let client_charlie = RhaiDispatcherBuilder::new() + .redis_url(REDIS_URL) + .caller_id(CHARLIE_ID) + .build() + .unwrap(); + + client_charlie + .new_play_request() + .worker_id(&ALICE_ID) + .context_id(&ALICE_ID) + .script_path("examples/access_control/charlie.rhai") + .timeout(Duration::from_secs(10)) + .await_response() + .await + .unwrap(); + + log::info!("Charlie's query to Alice's database completed."); + + // Spawn the Rhai worker for Alice's and Charlie's circle + let engine = rhailib_engine::create_heromodels_engine(); + let (shutdown_tx, shutdown_rx) = mpsc::channel(1); + let worker_handle = tokio::spawn(spawn_rhai_worker( + CIRCLE_ID.to_string(), + db_path.clone(), + engine, + REDIS_URL.to_string(), + shutdown_rx, + false, // use_sentinel + )); + + // Alice populates the rhai worker of their circle with Charlie. + let client_circle = RhaiDispatcherBuilder::new() + .redis_url(REDIS_URL) + .caller_id(CIRCLE_ID) + .build() + .unwrap(); + + client_circle + .new_play_request() + .worker_id(&CIRCLE_ID) + .context_id(&CIRCLE_ID) + .script_path("examples/access_control/circle.rhai") + .timeout(Duration::from_secs(10)) + .await_response() + .await + .unwrap(); + + log::info!("Circles's database populated."); + + // Give the worker a moment to start up + tokio::time::sleep(Duration::from_secs(1)).await; + + // Alice queries the rhai worker of their circle with Charlie. + client_alice + .new_play_request() + .worker_id(&CIRCLE_ID) + .context_id(&CIRCLE_ID) + .script_path("examples/access_control/alice.rhai") + .timeout(Duration::from_secs(10)) + .await_response() + .await + .unwrap(); + + log::info!("Bob's query to Alice's database completed."); + + // Charlie queries Alice's rhai worker + let client_charlie = RhaiDispatcherBuilder::new() + .redis_url(REDIS_URL) + .caller_id(CHARLIE_ID) + .build() + .unwrap(); + + client_charlie + .new_play_request() + .worker_id(&ALICE_ID) + .context_id(&ALICE_ID) + .script_path("examples/access_control/charlie.rhai") + .timeout(Duration::from_secs(10)) + .await_response() + .await + .unwrap(); + + log::info!("Charlie's query to Alice's database completed."); + + // 5. Shutdown the worker (optional, could also let it run until program exits) + log::info!("Signaling worker to shutdown..."); + let _ = shutdown_tx.send(()).await; + if let Err(e) = worker_handle.await { + log::error!("Worker task panicked or encountered an error: {:?}", e); + } + log::info!("Worker shutdown complete."); + + Ok(()) +} diff --git a/rhailib/examples/flows/new_create_payment_intent_error.rhai b/rhailib/examples/flows/new_create_payment_intent_error.rhai new file mode 100644 index 0000000..6f32d82 --- /dev/null +++ b/rhailib/examples/flows/new_create_payment_intent_error.rhai @@ -0,0 +1,38 @@ +// Error handler for failed payment intent creation +// This script is triggered when a payment intent creation fails + +print("❌ Payment Intent Creation Failed!"); +print("=================================="); + +// The error data is available as 'parsed_error' +if parsed_error != () { + print(`Error: ${parsed_error}`); + + // You can handle different types of errors + if parsed_error.contains("authentication") { + print("🔑 Authentication error - check API key"); + // eval_file("flows/handle_auth_error.rhai"); + } else if parsed_error.contains("insufficient_funds") { + print("💰 Insufficient funds error"); + // eval_file("flows/handle_insufficient_funds.rhai"); + } else if parsed_error.contains("card_declined") { + print("💳 Card declined error"); + // eval_file("flows/handle_card_declined.rhai"); + } else { + print("⚠️ General payment error"); + // eval_file("flows/handle_general_payment_error.rhai"); + } + + // Log the error for monitoring + print("📊 Logging error for analytics..."); + // eval_file("flows/log_payment_error.rhai"); + + // Notify relevant parties + print("📧 Sending error notifications..."); + // eval_file("flows/send_error_notification.rhai"); + +} else { + print("⚠️ No error data received"); +} + +print("🔄 Error handling complete!"); \ No newline at end of file diff --git a/rhailib/examples/flows/new_create_payment_intent_response.rhai b/rhailib/examples/flows/new_create_payment_intent_response.rhai new file mode 100644 index 0000000..d848a47 --- /dev/null +++ b/rhailib/examples/flows/new_create_payment_intent_response.rhai @@ -0,0 +1,34 @@ +// Response handler for successful payment intent creation +// This script is triggered when a payment intent is successfully created + +print("✅ Payment Intent Created Successfully!"); +print("====================================="); + +// The response data is available as 'parsed_data' +if parsed_data != () { + print(`Payment Intent ID: ${parsed_data.id}`); + print(`Amount: ${parsed_data.amount}`); + print(`Currency: ${parsed_data.currency}`); + print(`Status: ${parsed_data.status}`); + + if parsed_data.client_secret != () { + print(`Client Secret: ${parsed_data.client_secret}`); + } + + // You can now trigger additional workflows + print("🔄 Triggering next steps..."); + + // Example: Send confirmation email + // eval_file("flows/send_payment_confirmation_email.rhai"); + + // Example: Update user account + // eval_file("flows/update_user_payment_status.rhai"); + + // Example: Log analytics event + // eval_file("flows/log_payment_analytics.rhai"); + +} else { + print("⚠️ No response data received"); +} + +print("🎉 Payment intent response processing complete!"); \ No newline at end of file diff --git a/rhailib/examples/non_blocking_payment_test.rs b/rhailib/examples/non_blocking_payment_test.rs new file mode 100644 index 0000000..df8236c --- /dev/null +++ b/rhailib/examples/non_blocking_payment_test.rs @@ -0,0 +1,190 @@ +//! Test example to verify non-blocking payment functions +//! +//! This example demonstrates that the payment functions return immediately +//! while HTTP requests happen in the background using tokio::spawn. + +use rhai::{Engine, EvalAltResult}; +use std::time::{Duration, Instant}; +use tokio::time::sleep; + +// Import the payment module registration function +// Note: You'll need to adjust this import based on your actual module structure +// use rhailib::dsl::payment::register_payment_rhai_module; + +#[tokio::main] +async fn main() -> Result<(), Box> { + println!("🚀 Testing Non-Blocking Payment Functions"); + println!("=========================================="); + + // Create a new Rhai engine + let mut engine = Engine::new(); + + // Register the payment module + // Uncomment this when the module is properly integrated: + // register_payment_rhai_module(&mut engine); + + // Test script that demonstrates non-blocking behavior + let test_script = r#" + print("📝 Creating payment intent..."); + let start_time = timestamp(); + + // Create a payment intent + let payment_intent = new_payment_intent() + .amount(2000) + .currency("usd") + .customer("cus_test123") + .description("Test payment for non-blocking verification"); + + print("🚀 Dispatching async payment intent creation..."); + + // This should return immediately - no blocking! + let result = payment_intent.create_async( + "test-worker-1", + "test-context-123", + "sk_test_fake_key_for_testing" + ); + + let end_time = timestamp(); + let duration = end_time - start_time; + + print(`✅ Function returned in ${duration}ms: ${result}`); + print("🔄 HTTP request is happening in background..."); + + // Test multiple concurrent requests + print("\n📊 Testing concurrent requests..."); + let concurrent_start = timestamp(); + + // Create multiple payment intents concurrently + for i in 0..5 { + let intent = new_payment_intent() + .amount(1000 + i * 100) + .currency("usd") + .description(`Concurrent test ${i}`); + + let result = intent.create_async( + `worker-${i}`, + `context-${i}`, + "sk_test_fake_key" + ); + + print(`Request ${i}: ${result}`); + } + + let concurrent_end = timestamp(); + let concurrent_duration = concurrent_end - concurrent_start; + + print(`✅ All 5 concurrent requests dispatched in ${concurrent_duration}ms`); + print("🎯 This proves the functions are truly non-blocking!"); + "#; + + println!("⏱️ Measuring execution time..."); + let start = Instant::now(); + + // Execute the test script + match engine.eval::(test_script) { + Ok(_) => { + let duration = start.elapsed(); + println!("✅ Script completed in: {:?}", duration); + println!("🎯 If this completed quickly (< 100ms), the functions are non-blocking!"); + } + Err(e) => { + println!("❌ Script execution failed: {}", e); + println!("💡 Note: This is expected if the payment module isn't registered yet."); + println!(" The important thing is that when it works, it should be fast!"); + } + } + + // Demonstrate the difference with a blocking operation + println!("\n🐌 Comparing with a blocking operation..."); + let blocking_start = Instant::now(); + + // Simulate a blocking HTTP request + sleep(Duration::from_millis(500)).await; + + let blocking_duration = blocking_start.elapsed(); + println!("⏳ Blocking operation took: {:?}", blocking_duration); + + println!("\n📊 Performance Comparison:"); + println!(" Non-blocking: < 100ms (immediate return)"); + println!(" Blocking: {:?} (waits for completion)", blocking_duration); + + println!("\n🎉 Test completed!"); + println!("💡 The non-blocking implementation allows:"); + println!(" ✓ Immediate function returns"); + println!(" ✓ Concurrent request processing"); + println!(" ✓ No thread blocking"); + println!(" ✓ Better scalability"); + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU32, Ordering}; + use std::sync::Arc; + + #[tokio::test] + async fn test_non_blocking_behavior() { + // This test verifies that multiple "requests" can be processed concurrently + let counter = Arc::new(AtomicU32::new(0)); + let mut handles = vec![]; + + let start = Instant::now(); + + // Spawn multiple tasks that simulate the non-blocking payment functions + for i in 0..10 { + let counter_clone = counter.clone(); + let handle = tokio::spawn(async move { + // Simulate the immediate return of our non-blocking functions + let _result = format!("payment_intent_request_dispatched_{}", i); + + // Simulate the background HTTP work (but don't block the caller) + tokio::spawn(async move { + // This represents the actual HTTP request happening in background + sleep(Duration::from_millis(100)).await; + counter_clone.fetch_add(1, Ordering::SeqCst); + }); + + // Return immediately (non-blocking behavior) + _result + }); + handles.push(handle); + } + + // Wait for all the immediate returns (should be very fast) + for handle in handles { + let _result = handle.await.unwrap(); + } + + let immediate_duration = start.elapsed(); + + // The immediate returns should be very fast (< 50ms) + assert!(immediate_duration < Duration::from_millis(50), + "Non-blocking functions took too long: {:?}", immediate_duration); + + // Wait a bit for background tasks to complete + sleep(Duration::from_millis(200)).await; + + // Verify that background tasks eventually completed + assert_eq!(counter.load(Ordering::SeqCst), 10); + + println!("✅ Non-blocking test passed!"); + println!(" Immediate returns: {:?}", immediate_duration); + println!(" Background tasks: completed"); + } + + #[test] + fn test_data_structures() { + // Test that our data structures work correctly + use std::collections::HashMap; + + // Test RhaiProduct builder pattern + let mut metadata = HashMap::new(); + metadata.insert("test".to_string(), "value".to_string()); + + // These would be the actual structs from the payment module + // For now, just verify the test compiles + assert!(true, "Data structure test placeholder"); + } +} \ No newline at end of file diff --git a/rhailib/examples/payment_usage_example.rhai b/rhailib/examples/payment_usage_example.rhai new file mode 100644 index 0000000..7ad65fe --- /dev/null +++ b/rhailib/examples/payment_usage_example.rhai @@ -0,0 +1,108 @@ +// Example Rhai script demonstrating non-blocking payment functions +// This script shows how to use the new async payment functions + +print("🚀 Non-Blocking Payment Example"); +print("================================"); + +// Create a product asynchronously +print("📦 Creating product..."); +let product = new_product() + .name("Premium Subscription") + .description("Monthly premium subscription service") + .metadata("category", "subscription") + .metadata("tier", "premium"); + +let product_result = product.create_async( + "payment-worker-1", + "product-context-123", + "sk_test_your_stripe_secret_key" +); + +print(`Product creation dispatched: ${product_result}`); + +// Create a price asynchronously +print("💰 Creating price..."); +let price = new_price() + .amount(2999) // $29.99 in cents + .currency("usd") + .product("prod_premium_subscription") // Would be the actual product ID + .recurring("month") + .metadata("billing_cycle", "monthly"); + +let price_result = price.create_async( + "payment-worker-1", + "price-context-456", + "sk_test_your_stripe_secret_key" +); + +print(`Price creation dispatched: ${price_result}`); + +// Create a payment intent asynchronously +print("💳 Creating payment intent..."); +let payment_intent = new_payment_intent() + .amount(2999) + .currency("usd") + .customer("cus_customer123") + .description("Premium subscription payment") + .add_payment_method_type("card") + .metadata("subscription_type", "premium") + .metadata("billing_period", "monthly"); + +let payment_result = payment_intent.create_async( + "payment-worker-1", + "payment-context-789", + "sk_test_your_stripe_secret_key" +); + +print(`Payment intent creation dispatched: ${payment_result}`); + +// Create a subscription asynchronously +print("📅 Creating subscription..."); +let subscription = new_subscription() + .customer("cus_customer123") + .add_price("price_premium_monthly") // Would be the actual price ID + .trial_days(7) + .metadata("plan", "premium") + .metadata("source", "website"); + +let subscription_result = subscription.create_async( + "payment-worker-1", + "subscription-context-101", + "sk_test_your_stripe_secret_key" +); + +print(`Subscription creation dispatched: ${subscription_result}`); + +// Create a coupon asynchronously +print("🎫 Creating coupon..."); +let coupon = new_coupon() + .duration("once") + .percent_off(20) + .metadata("campaign", "new_user_discount") + .metadata("valid_until", "2024-12-31"); + +let coupon_result = coupon.create_async( + "payment-worker-1", + "coupon-context-202", + "sk_test_your_stripe_secret_key" +); + +print(`Coupon creation dispatched: ${coupon_result}`); + +print("\n✅ All payment operations dispatched!"); +print("🔄 HTTP requests are happening in the background"); +print("📨 Response/error scripts will be triggered when complete"); + +print("\n📋 Summary:"); +print(` Product: ${product_result}`); +print(` Price: ${price_result}`); +print(` Payment Intent: ${payment_result}`); +print(` Subscription: ${subscription_result}`); +print(` Coupon: ${coupon_result}`); + +print("\n🎯 Key Benefits:"); +print(" ✓ Immediate returns - no blocking"); +print(" ✓ Concurrent processing capability"); +print(" ✓ Event-driven response handling"); +print(" ✓ No global state dependencies"); +print(" ✓ Configurable per request"); \ No newline at end of file diff --git a/rhailib/research/repl/.gitignore b/rhailib/research/repl/.gitignore new file mode 100644 index 0000000..70c3426 --- /dev/null +++ b/rhailib/research/repl/.gitignore @@ -0,0 +1,2 @@ +target +temp_db_for_example_worker_default_worker \ No newline at end of file diff --git a/rhailib/research/repl/.rhai_repl_history.txt b/rhailib/research/repl/.rhai_repl_history.txt new file mode 100644 index 0000000..1b3f169 --- /dev/null +++ b/rhailib/research/repl/.rhai_repl_history.txt @@ -0,0 +1,5 @@ +#V2 +.edit +quit +.edit +exit diff --git a/rhailib/research/repl/Cargo.toml b/rhailib/research/repl/Cargo.toml new file mode 100644 index 0000000..9079656 --- /dev/null +++ b/rhailib/research/repl/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "ui_repl" +version = "0.1.0" +edition = "2024" # Keep 2024 unless issues arise + +[dependencies] +tokio = { version = "1", features = ["macros", "rt-multi-thread", "time", "sync"] } # Added "time" for potential timeouts, "sync" for worker +url = "2" # For parsing Redis URL +tracing = "0.1" # For logging +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +log = "0.4" # rhai_dispatcher uses log crate +rustyline = { version = "13.0.0", features = ["derive"] } # For enhanced REPL input +tempfile = "3.8" # For creating temporary files for editing + +rhai_dispatcher = { path = "../client" } +anyhow = "1.0" # For simpler error handling + +rhailib_worker = { path = "../worker", package = "rhailib_worker" } +rhailib_engine = { path = "../engine" } +heromodels = { path = "../../../db/heromodels", features = ["rhai"] } +rhai = { version = "1.18.0" } # Match version used by worker/engine diff --git a/rhailib/research/repl/README.md b/rhailib/research/repl/README.md new file mode 100644 index 0000000..852c174 --- /dev/null +++ b/rhailib/research/repl/README.md @@ -0,0 +1,77 @@ +# Rhai REPL CLI for Circle WebSocket Servers + +This crate provides a command-line interface (CLI) to interact with Rhai scripts executed on remote Circle WebSocket servers. It includes both an interactive REPL and a non-interactive example. + +## Prerequisites + +1. **Circle Orchestrator Running**: Ensure the `circles_orchestrator` is running. This application manages and starts the individual Circle WebSocket servers. + To run the orchestrator: + ```bash + cd /path/to/herocode/circles/cmd + cargo run + ``` + By default, this will start servers based on the `circles.json` configuration (e.g., "Alpha Circle" on `ws://127.0.0.1:8081/ws`). + +2. **Redis Server**: Ensure a Redis server is running and accessible at `redis://127.0.0.1:6379` (this is the default used by the orchestrator and its components). + +## Usage + +Navigate to this crate's directory: +```bash +cd /path/to/herocode/circles/ui_repl +``` + +### 1. Interactive REPL + +The main binary of this crate is an interactive REPL. + +**To run with default WebSocket URL (`ws://127.0.0.1:8081/ws`):** +```bash +cargo run +``` + +**To specify a WebSocket URL:** +```bash +cargo run ws://:/ws +# Example for "Beta Circle" if configured on port 8082: +# cargo run ws://127.0.0.1:8082/ws +``` + +Once connected, you can: +- Type single-line Rhai scripts directly and press Enter. +- Use Vi keybindings for editing the current input line (thanks to `rustyline`). +- Type `.edit` to open your `$EDITOR` (or `vi` by default) for multi-line script input. Save and close the editor to execute the script. +- Type `.run ` (or `run `) to execute a Rhai script from a local file. +- Type `exit` or `quit` to close the REPL. + +Command history is saved to `.rhai_repl_history.txt` in the directory where you run the REPL. + +### 2. Non-Interactive Example (`connect_and_play`) + +This example connects to a WebSocket server, sends a predefined Rhai script, prints the response, and then disconnects. + +**To run with default WebSocket URL (`ws://127.0.0.1:8081/ws`):** +```bash +cargo run --example connect_and_play +``` + +**To specify a WebSocket URL for the example:** +```bash +cargo run --example connect_and_play ws://:/ws +# Example: +# cargo run --example connect_and_play ws://127.0.0.1:8082/ws +``` + +The example script is: +```rhai +let a = 10; +let b = 32; +let message = "Hello from example script!"; +message + " Result: " + (a + b) +``` + +## Logging + +Both the REPL and the example use the `tracing` crate for logging. You can control log levels using the `RUST_LOG` environment variable. For example, to see debug logs from the `circle_client_ws` library: +```bash +RUST_LOG=info,circle_client_ws=debug cargo run --example connect_and_play \ No newline at end of file diff --git a/rhailib/research/repl/docs/ARCHITECTURE.md b/rhailib/research/repl/docs/ARCHITECTURE.md new file mode 100644 index 0000000..ee0da19 --- /dev/null +++ b/rhailib/research/repl/docs/ARCHITECTURE.md @@ -0,0 +1,53 @@ +# Architecture of the `ui_repl` Crate + +The `ui_repl` crate provides an interactive Read-Eval-Print Loop (REPL) interface for the rhailib ecosystem, enabling real-time script development, testing, and execution with integrated worker management. + +## Core Architecture + +```mermaid +graph TD + A[REPL Interface] --> B[Script Execution] + A --> C[Worker Management] + A --> D[Client Integration] + + B --> B1[Local Engine Execution] + B --> B2[Remote Worker Execution] + B --> B3[Script Editing] + + C --> C1[Worker Lifecycle] + C --> C2[Task Distribution] + C --> C3[Status Monitoring] + + D --> D1[Redis Client] + D --> D2[Task Submission] + D --> D3[Result Retrieval] +``` + +## Key Features + +### Interactive Development +- **Enhanced Input**: Rustyline for advanced command-line editing +- **Script Editing**: Temporary file editing with external editors +- **Syntax Highlighting**: Enhanced script development experience + +### Dual Execution Modes +- **Local Execution**: Direct engine execution for development +- **Remote Execution**: Worker-based execution for production testing +- **Seamless Switching**: Easy mode transitions during development + +### Integrated Worker Management +- **Worker Spawning**: Automatic worker process management +- **Lifecycle Control**: Start, stop, and restart worker processes +- **Status Monitoring**: Real-time worker health and performance + +## Dependencies + +- **Rhai Client**: Integration with rhailib client for remote execution +- **Rhailib Engine**: Direct engine access for local execution +- **Rhailib Worker**: Embedded worker management capabilities +- **Enhanced CLI**: Rustyline for superior REPL experience +- **Async Runtime**: Tokio for concurrent operations + +## Usage Patterns + +The REPL serves as the primary development interface for rhailib, providing developers with immediate feedback and testing capabilities for Rhai scripts and business logic. \ No newline at end of file diff --git a/rhailib/research/repl/examples/connect_and_play.rs b/rhailib/research/repl/examples/connect_and_play.rs new file mode 100644 index 0000000..2568d5c --- /dev/null +++ b/rhailib/research/repl/examples/connect_and_play.rs @@ -0,0 +1,198 @@ +use anyhow::Context; +use rhai_dispatcher::{RhaiDispatcher, RhaiDispatcherError, RhaiTaskDetails}; +use std::env; +use std::sync::Arc; +use std::time::Duration; +use tokio::sync::mpsc; +use tracing_subscriber::EnvFilter; + +use engine::create_heromodels_engine; +use heromodels::db::hero::OurDB; +use std::path::PathBuf; +use worker_lib::spawn_rhai_worker; + +#[tokio::main] +async fn main() -> Result<(), Box> { + tracing_subscriber::fmt() + .with_env_filter( + EnvFilter::from_default_env() + .add_directive("connect_and_play=info".parse().unwrap()) + .add_directive("rhai_dispatcher=info".parse().unwrap()), + ) + .init(); + + let args: Vec = env::args().collect(); + let redis_url = args.get(1).cloned().unwrap_or_else(|| { + let default_url = "redis://127.0.0.1/".to_string(); + println!("No Redis URL provided. Defaulting to: {}", default_url); + default_url + }); + let worker_name = args.get(2).cloned().unwrap_or_else(|| { + let default_worker = "default_worker".to_string(); + println!("No worker name provided. Defaulting to: {}", default_worker); + default_worker + }); + + // Define DB path for the worker + let db_path_str = format!("./temp_db_for_example_worker_{}", worker_name); + let db_path = PathBuf::from(&db_path_str); + + // Create shutdown channel for the worker + let (shutdown_tx, shutdown_rx) = mpsc::channel::<()>(1); + + // Spawn a worker in the background + let worker_redis_url = redis_url.clone(); + let worker_circle_name_for_task = worker_name.clone(); + let db_path_for_task = db_path_str.clone(); + + log::info!( + "[Main] Spawning worker for circle '{}' with DB path '{}'", + worker_circle_name_for_task, + db_path_for_task + ); + + let worker_join_handle = tokio::spawn(async move { + log::info!( + "[BG Worker] Starting for circle '{}' on Redis '{}'", + worker_circle_name_for_task, + worker_redis_url + ); + // The `reset: true` in OurDB::new handles pre-cleanup if the directory exists. + let db = Arc::new( + OurDB::new(&db_path_for_task, true) + .expect("Failed to create temp DB for example worker"), + ); + let mut engine = create_heromodels_engine(db); + engine.set_max_operations(0); + engine.set_max_expr_depths(0, 0); + engine.set_optimization_level(rhai::OptimizationLevel::Full); + + if let Err(e) = spawn_rhai_worker( + 1, // dummy circle_id + worker_circle_name_for_task.clone(), + engine, + worker_redis_url.clone(), + shutdown_rx, // Pass the receiver from main + false, // preserve_tasks + ) + .await + { + log::error!( + "[BG Worker] Failed to spawn or worker error for circle '{}': {}", + worker_circle_name_for_task, + e + ); + } else { + log::info!( + "[BG Worker] Worker for circle '{}' shut down gracefully.", + worker_circle_name_for_task + ); + } + }); + + // Give the worker a moment to start up + tokio::time::sleep(Duration::from_secs(1)).await; + + println!( + "Initializing RhaiDispatcher for Redis at {} to target worker '{}'...", + redis_url, worker_name + ); + let client = RhaiDispatcher::new(&redis_url) + .with_context(|| format!("Failed to create RhaiDispatcher for Redis URL: {}", redis_url))?; + println!("RhaiDispatcher initialized."); + + let script = "let a = 10; let b = 32; let message = \"Hello from example script!\"; message + \" Result: \" + (a + b)"; + println!("\nSending script:\n```rhai\n{}\n```", script); + + let timeout = Duration::from_secs(30); + match client + .submit_script_and_await_result(&worker_name, script.to_string(), None, timeout) + .await + { + Ok(task_details) => { + println!("\nWorker response:"); + if let Some(ref output) = task_details.output { + println!("Output: {}", output); + } + if let Some(ref error_msg) = task_details.error { + eprintln!("Error: {}", error_msg); + } + if task_details.output.is_none() && task_details.error.is_none() { + println!( + "Worker finished with no explicit output or error. Status: {}", + task_details.status + ); + } + } + Err(e) => match e { + RhaiDispatcherError::Timeout(task_id) => { + eprintln!( + "\nError: Script execution timed out for task_id: {}.", + task_id + ); + } + RhaiDispatcherError::RedisError(redis_err) => { + eprintln!( + "\nError: Redis communication failed: {}. Check Redis connection and server status.", + redis_err + ); + } + RhaiDispatcherError::SerializationError(serde_err) => { + eprintln!( + "\nError: Failed to serialize/deserialize task data: {}.", + serde_err + ); + } + RhaiDispatcherError::TaskNotFound(task_id) => { + eprintln!("\nError: Task {} not found after submission.", task_id); + } /* All RhaiDispatcherError variants are handled, so _ arm is not strictly needed + unless RhaiDispatcherError becomes non-exhaustive in the future. */ + }, + } + + println!("\nExample client operations finished. Shutting down worker..."); + + // Send shutdown signal to the worker + if let Err(e) = shutdown_tx.send(()).await { + eprintln!( + "[Main] Failed to send shutdown signal to worker: {} (worker might have already exited or an error occurred)", + e + ); + } + + // Wait for the worker to finish + log::info!("[Main] Waiting for worker task to join..."); + if let Err(e) = worker_join_handle.await { + eprintln!("[Main] Error waiting for worker task to join: {:?}", e); + } else { + log::info!("[Main] Worker task joined successfully."); + } + + // Clean up the database directory + log::info!( + "[Main] Cleaning up database directory: {}", + db_path.display() + ); + if db_path.exists() { + if let Err(e) = std::fs::remove_dir_all(&db_path) { + eprintln!( + "[Main] Failed to remove database directory '{}': {}", + db_path.display(), + e + ); + } else { + log::info!( + "[Main] Successfully removed database directory: {}", + db_path.display() + ); + } + } else { + log::info!( + "[Main] Database directory '{}' not found, no cleanup needed.", + db_path.display() + ); + } + + println!("Example fully completed and cleaned up."); + Ok(()) +} diff --git a/rhailib/research/repl/src/main.rs b/rhailib/research/repl/src/main.rs new file mode 100644 index 0000000..bd0e87a --- /dev/null +++ b/rhailib/research/repl/src/main.rs @@ -0,0 +1,275 @@ +use anyhow::Context; +use rhai_dispatcher::{RhaiDispatcher, RhaiDispatcherBuilder, RhaiDispatcherError}; +use rustyline::error::ReadlineError; +use rustyline::{Config, DefaultEditor, EditMode}; +use std::env; +use std::fs; +use std::process::Command; +use std::time::Duration; +use tempfile::Builder as TempFileBuilder; +use tracing_subscriber::EnvFilter; + +// Default timeout for script execution +const DEFAULT_SCRIPT_TIMEOUT_SECONDS: u64 = 30; + +async fn execute_script(client: &RhaiDispatcher, circle_name: &str, script_content: String) { + if script_content.trim().is_empty() { + println!("Script is empty, not sending."); + return; + } + println!( + "Sending script to worker '{}':\n---\n{}\n---", + circle_name, script_content + ); + + let timeout = Duration::from_secs(DEFAULT_SCRIPT_TIMEOUT_SECONDS); + + match client + .new_play_request() + .worker_id(circle_name) + .script(&script_content) + .timeout(timeout) + .await_response() + .await + { + Ok(task_details) => { + if let Some(output) = &task_details.output { + println!("worker: {}", output); + } + if let Some(error_msg) = &task_details.error { + eprintln!("Worker error: {}", error_msg); + } + if task_details.output.is_none() && task_details.error.is_none() { + println!( + "Worker finished with no explicit output or error. Status: {}", + task_details.status + ); + } + } + Err(e) => match e { + RhaiDispatcherError::Timeout(task_id) => { + eprintln!( + "Error: Script execution timed out for task_id: {}.", + task_id + ); + } + RhaiDispatcherError::RedisError(redis_err) => { + eprintln!( + "Error: Redis communication failed: {}. Check Redis connection and server status.", + redis_err + ); + } + RhaiDispatcherError::SerializationError(serde_err) => { + eprintln!( + "Error: Failed to serialize/deserialize task data: {}.", + serde_err + ); + } + RhaiDispatcherError::TaskNotFound(task_id) => { + eprintln!( + "Error: Task {} not found after submission (this should be rare).", + task_id + ); + } + }, + } +} + +async fn run_repl(redis_url: String, circle_name: String) -> anyhow::Result<()> { + println!( + "Initializing Rhai REPL for worker '{}' via Redis at {}...", + circle_name, redis_url + ); + + let client = RhaiDispatcherBuilder::new() + .redis_url(&redis_url) + .caller_id("ui_repl") // Set a caller_id + .build() + .with_context(|| format!("Failed to create RhaiDispatcher for Redis URL: {}", redis_url))?; + + // No explicit connect() needed for rhai_dispatcher, connection is handled per-operation or pooled. + println!( + "RhaiDispatcher initialized. Ready to send scripts to worker '{}'.", + circle_name + ); + println!( + "Type Rhai scripts, '.edit' to use $EDITOR, '.run ' to execute a file, or 'exit'/'quit'." + ); + println!("Vi mode enabled for input line."); + + let config = Config::builder() + .edit_mode(EditMode::Vi) + .auto_add_history(true) // Automatically add to history + .build(); + let mut rl = DefaultEditor::with_config(config)?; + + let history_file = ".rhai_repl_history.txt"; // Simple history file in current dir + if rl.load_history(history_file).is_err() { + // No history found or error loading, not critical + } + + let prompt = format!("rhai ({}) @ {}> ", circle_name, redis_url); + + loop { + let readline = rl.readline(&prompt); + match readline { + Ok(line) => { + let input = line.trim(); + + if input.eq_ignore_ascii_case("exit") || input.eq_ignore_ascii_case("quit") { + println!("Exiting REPL."); + break; + } else if input.eq_ignore_ascii_case(".edit") { + // Correct way to create a temp file with a suffix + let temp_file = TempFileBuilder::new() + .prefix("rhai_script_") // Optional: add a prefix + .suffix(".rhai") + .tempfile_in(".") // Create in current directory for simplicity + .with_context(|| "Failed to create temp file")?; + + // You can pre-populate the temp file if needed: + // use std::io::Write; // Add this import if using write_all + // if let Err(e) = temp_file.as_file().write_all(b"// Start your Rhai script here\n") { + // eprintln!("Failed to write initial content to temp file: {}", e); + // } + + let temp_path = temp_file.path().to_path_buf(); + let editor_cmd_str = env::var("EDITOR").unwrap_or_else(|_| "vi".to_string()); + + let mut editor_parts = editor_cmd_str.split_whitespace(); + let editor_executable = editor_parts.next().unwrap_or("vi"); // Default to vi if $EDITOR is empty string + let editor_args: Vec<&str> = editor_parts.collect(); + + println!( + "Launching editor: '{}' with args: {:?} for script editing. Save and exit editor to execute.", + editor_executable, editor_args + ); + + let mut command = Command::new(editor_executable); + command.args(editor_args); // Add any arguments from $EDITOR (like -w) + command.arg(&temp_path); // Add the temp file path as the last argument + + let status = command.status(); + + match status { + Ok(exit_status) if exit_status.success() => { + match fs::read_to_string(&temp_path) { + Ok(script_content) => { + execute_script(&client, &circle_name, script_content).await; + } + Err(e) => { + eprintln!("Error reading temp file {:?}: {}", temp_path, e) + } + } + } + Ok(exit_status) => eprintln!( + "Editor exited with status: {}. Script not executed.", + exit_status + ), + Err(e) => eprintln!( + "Failed to launch editor '{}': {}. Ensure it's in your PATH.", + editor_executable, e + ), // Changed 'editor' to 'editor_executable' + } + // temp_file is automatically deleted when it goes out of scope + } else if input.starts_with(".run ") || input.starts_with("run ") { + let parts: Vec<&str> = input.splitn(2, ' ').collect(); + if parts.len() == 2 { + let file_path = parts[1]; + println!("Attempting to run script from file: {}", file_path); + match fs::read_to_string(file_path) { + Ok(script_content) => { + execute_script(&client, &circle_name, script_content).await; + } + Err(e) => eprintln!("Error reading file {}: {}", file_path, e), + } + } else { + eprintln!("Usage: .run "); + } + } else if !input.is_empty() { + execute_script(&client, &circle_name, input.to_string()).await; + } + // rl.add_history_entry(line.as_str()) is handled by auto_add_history(true) + } + Err(ReadlineError::Interrupted) => { + // Ctrl-C + println!("Input interrupted. Type 'exit' or 'quit' to close."); + continue; + } + Err(ReadlineError::Eof) => { + // Ctrl-D + println!("Exiting REPL (EOF)."); + break; + } + Err(err) => { + eprintln!("Error reading input: {:?}", err); + break; + } + } + } + + if rl.save_history(history_file).is_err() { + // Failed to save history, not critical + } + + // No explicit disconnect for RhaiDispatcher as it manages connections internally. + println!("Exited REPL."); + Ok(()) +} + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + tracing_subscriber::fmt() + .with_env_filter( + EnvFilter::from_default_env() + .add_directive("ui_repl=info".parse()?) + .add_directive("rhai_dispatcher=info".parse()?), + ) + .init(); + + let args: Vec = env::args().collect(); + + let redis_url_str = if args.len() > 1 { + args[1].clone() + } else { + let default_url = "redis://127.0.0.1/".to_string(); + println!("No Redis URL provided. Defaulting to: {}", default_url); + default_url + }; + + let circle_name_str = if args.len() > 2 { + args[2].clone() + } else { + let default_circle = "default_worker".to_string(); + println!( + "No worker/circle name provided. Defaulting to: {}", + default_circle + ); + default_circle + }; + + println!( + "Usage: {} [redis_url] [worker_name]", + args.get(0).map_or("ui_repl", |s| s.as_str()) + ); + println!( + "Example: {} redis://127.0.0.1/ my_rhai_worker", + args.get(0).map_or("ui_repl", |s| s.as_str()) + ); + + // Basic validation for Redis URL (scheme) + // A more robust validation might involve trying to parse it with redis::ConnectionInfo + if !redis_url_str.starts_with("redis://") { + eprintln!( + "Warning: Redis URL '{}' does not start with 'redis://'. Attempting to use it anyway.", + redis_url_str + ); + } + + if let Err(e) = run_repl(redis_url_str, circle_name_str).await { + eprintln!("REPL error: {:#}", e); + std::process::exit(1); + } + + Ok(()) +} diff --git a/rhailib/research/rhai_engine_ui/.gitignore b/rhailib/research/rhai_engine_ui/.gitignore new file mode 100644 index 0000000..66a2386 --- /dev/null +++ b/rhailib/research/rhai_engine_ui/.gitignore @@ -0,0 +1,3 @@ +/target +/dist +Cargo.lock diff --git a/rhailib/research/rhai_engine_ui/Cargo.toml b/rhailib/research/rhai_engine_ui/Cargo.toml new file mode 100644 index 0000000..636b946 --- /dev/null +++ b/rhailib/research/rhai_engine_ui/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "rhai-engine-ui" +version = "0.1.0" +edition = "2021" + +[dependencies] +yew = { version = "0.21", features = ["csr"] } +wasm-bindgen = "0.2" +wasm-logger = "0.2" +gloo-net = "0.4" +gloo-timers = "0.3.0" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +web-sys = { version = "0.3", features = ["HtmlInputElement"] } +log = "0.4" +chrono = { version = "0.4", features = ["serde"] } +wasm-bindgen-futures = "0.4" + +# Server-side dependencies (optional) +tokio = { version = "1", features = ["full"], optional = true } +axum = { version = "0.7", optional = true } +tower = { version = "0.4", optional = true } +tower-http = { version = "0.5.0", features = ["fs", "cors"], optional = true } +rand = { version = "0.8", optional = true } +redis = { version = "0.25", features = ["tokio-comp"], optional = true } +deadpool-redis = { version = "0.15.0", features = ["rt_tokio_1"], optional = true } + +[features] +# This feature enables the server-side components +server = ["tokio", "axum", "tower", "tower-http", "rand", "redis", "deadpool-redis"] diff --git a/rhailib/research/rhai_engine_ui/README.md b/rhailib/research/rhai_engine_ui/README.md new file mode 100644 index 0000000..8db5541 --- /dev/null +++ b/rhailib/research/rhai_engine_ui/README.md @@ -0,0 +1,42 @@ +# Rhai Engine Worker UI + +A Yew-based WASM interface to monitor Rhai workers. + +## Prerequisites + +- Rust: Install from [rust-lang.org](https://www.rust-lang.org/tools/install) +- Trunk: Install with `cargo install trunk` +- A backend service providing the necessary API endpoints (see below). + +## Backend API Requirements + +This UI expects a backend service to be running that can provide data from Redis. The UI will make requests to the following (example) endpoints: + +- `GET /api/worker/{worker_name}/tasks_and_stats`: Returns initial `WorkerData` including a list of `TaskSummary` and initial `QueueStats`. + - `WorkerData`: `{ "queue_stats": { "current_size": u32, "color_code": "string" }, "tasks": [TaskSummary] }` + - `TaskSummary`: `{ "hash": "string", "created_at": i64, "status": "string" }` +- `GET /api/worker/{worker_name}/queue_stats`: Returns current `QueueStats` for polling. + - `QueueStats`: `{ "current_size": u32, "color_code": "string" }` +- `GET /api/task/{task_hash}`: Returns `TaskDetails`. + - `TaskDetails`: `{ "hash": "string", "created_at": i64, "status": "string", "script_content": "string", "result": "optional_string", "error": "optional_string" }` + +**Note:** The API endpoints are currently hardcoded with relative paths (e.g., `/api/...`). This assumes the backend API is served from the same host and port as the Trunk development server, or that a proxy is configured. + +## Development + +1. Navigate to the `rhai_engine_ui` directory: + ```bash + cd /Users/timurgordon/code/git.ourworld.tf/herocode/rhailib/rhai_engine_ui/ + ``` +2. Run the development server: + ```bash + trunk serve --port 8081 + ``` +3. Open your browser to `http://127.0.0.1:8081`. + +## Building for Release + +```bash +trunk build --release +``` +This will output static files to the `dist` directory. diff --git a/rhailib/research/rhai_engine_ui/Trunk.toml b/rhailib/research/rhai_engine_ui/Trunk.toml new file mode 100644 index 0000000..47e2d9c --- /dev/null +++ b/rhailib/research/rhai_engine_ui/Trunk.toml @@ -0,0 +1,2 @@ +[build] +target = "index.html" \ No newline at end of file diff --git a/rhailib/research/rhai_engine_ui/docs/ARCHITECTURE.md b/rhailib/research/rhai_engine_ui/docs/ARCHITECTURE.md new file mode 100644 index 0000000..ce5cc86 --- /dev/null +++ b/rhailib/research/rhai_engine_ui/docs/ARCHITECTURE.md @@ -0,0 +1,57 @@ +# Architecture of the `rhai-engine-ui` Crate + +The `rhai-engine-ui` crate provides a web-based user interface for interacting with the rhailib ecosystem, offering both client-side and server-side components for comprehensive Rhai script management and execution. + +## Core Architecture + +```mermaid +graph TD + A[Web UI] --> B[Client-Side Components] + A --> C[Server-Side Components] + A --> D[Integration Layer] + + B --> B1[Yew Frontend] + B --> B2[WebAssembly Runtime] + B --> B3[Browser Interface] + + C --> C1[Axum Web Server] + C --> C2[Redis Integration] + C --> C3[API Endpoints] + + D --> D1[Task Submission] + D --> D2[Real-time Updates] + D --> D3[Result Display] +``` + +## Key Features + +### Frontend (WebAssembly) +- **Yew Framework**: Modern Rust-based web frontend +- **Real-time Interface**: Live updates and interactive script execution +- **Browser Integration**: Native web technologies with Rust performance + +### Backend (Optional Server) +- **Axum Web Server**: High-performance async web server +- **Redis Integration**: Direct connection to rhailib task queues +- **API Layer**: RESTful endpoints for task management + +### Dual Architecture +- **Client-Only Mode**: Pure WebAssembly frontend for development +- **Full-Stack Mode**: Complete web application with server backend +- **Feature Flags**: Configurable deployment options + +## Dependencies + +### Frontend Dependencies +- **Yew**: Component-based web framework +- **WebAssembly**: Browser runtime for Rust code +- **Web APIs**: Browser integration and DOM manipulation + +### Backend Dependencies (Optional) +- **Axum**: Modern web framework +- **Redis**: Task queue integration +- **Tower**: Middleware and service abstractions + +## Deployment Options + +The UI can be deployed as a static WebAssembly application for development use or as a full-stack web application with server-side Redis integration for production environments. \ No newline at end of file diff --git a/rhailib/research/rhai_engine_ui/index.html b/rhailib/research/rhai_engine_ui/index.html new file mode 100644 index 0000000..1e84ab1 --- /dev/null +++ b/rhailib/research/rhai_engine_ui/index.html @@ -0,0 +1,15 @@ + + + + + Rhai Worker UI + + + + + + + + + + diff --git a/rhailib/research/rhai_engine_ui/src/app.rs b/rhailib/research/rhai_engine_ui/src/app.rs new file mode 100644 index 0000000..db026f2 --- /dev/null +++ b/rhailib/research/rhai_engine_ui/src/app.rs @@ -0,0 +1,388 @@ +use gloo_net::http::Request; +use gloo_timers::callback::Interval; +use serde::{Deserialize, Serialize}; +use wasm_bindgen_futures::spawn_local; +use web_sys::HtmlInputElement; +use yew::prelude::*; +use yew::{html, Component, Context, Html, TargetCast}; + +// --- Data Structures (placeholders, to be refined based on backend API) --- + +#[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] +pub struct QueueStats { + pub current_size: u32, + pub color_code: String, // e.g., "green", "yellow", "red" +} + +#[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] +pub struct TaskSummary { + pub hash: String, + pub created_at: i64, + pub status: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct TaskDetails { + pub hash: String, + pub created_at: i64, + pub status: String, + pub script_content: String, + pub result: Option, + pub error: Option, +} + +// Combined structure for initial fetch +#[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] +pub struct WorkerDataResponse { + pub queue_stats: Option, + pub tasks: Vec, +} + +// --- Component --- + +pub enum Msg { + UpdateWorkerName(String), + FetchData, + SetWorkerData(Result), + SetQueueStats(Result), + ViewTaskDetails(String), // Task hash + SetTaskDetails(Result), + ClearTaskDetails, + IntervalTick, // For interval timer, to trigger queue stats fetch +} + +pub struct App { + worker_name_input: String, + worker_name_to_monitor: Option, + tasks_list: Vec, + current_queue_stats: Option, + selected_task_details: Option, + error_message: Option, + is_loading_initial_data: bool, + is_loading_task_details: bool, + queue_poll_timer: Option, +} + +impl Component for App { + type Message = Msg; + type Properties = (); + + fn create(_ctx: &Context) -> Self { + Self { + worker_name_input: "".to_string(), + worker_name_to_monitor: None, + tasks_list: Vec::new(), + current_queue_stats: None, + selected_task_details: None, + error_message: None, + is_loading_initial_data: false, + is_loading_task_details: false, + queue_poll_timer: None, + } + } + + fn update(&mut self, ctx: &Context, msg: Self::Message) -> bool { + match msg { + Msg::UpdateWorkerName(name) => { + self.worker_name_input = name; + true + } + Msg::FetchData => { + if self.worker_name_input.trim().is_empty() { + self.error_message = Some("Please enter a worker name.".to_string()); + return true; + } + let worker_name = self.worker_name_input.trim().to_string(); + self.worker_name_to_monitor = Some(worker_name.clone()); + self.error_message = None; + self.tasks_list.clear(); + self.current_queue_stats = None; + self.selected_task_details = None; + self.is_loading_initial_data = true; + + let link = ctx.link().clone(); + let tasks_url = format!("/api/worker/{}/tasks_and_stats", worker_name); + spawn_local(async move { + match Request::get(&tasks_url).send().await { + Ok(response) => { + if response.ok() { + match response.json::().await { + Ok(data) => link.send_message(Msg::SetWorkerData(Ok(data))), + Err(e) => link.send_message(Msg::SetWorkerData(Err(format!( + "Failed to parse worker data: {}", + e + )))), + } + } else { + link.send_message(Msg::SetWorkerData(Err(format!( + "API error: {} {}", + response.status(), + response.status_text() + )))); + } + } + Err(e) => link.send_message(Msg::SetWorkerData(Err(format!( + "Network error fetching worker data: {}", + e + )))), + } + }); + + // Set up polling for queue stats + let link_for_timer = ctx.link().clone(); + let timer = Interval::new(5000, move || { + // Poll every 5 seconds + link_for_timer.send_message(Msg::IntervalTick); + }); + if let Some(old_timer) = self.queue_poll_timer.take() { + old_timer.cancel(); // Cancel previous timer if any + } + self.queue_poll_timer = Some(timer); + true + } + Msg::IntervalTick => { + if let Some(worker_name) = &self.worker_name_to_monitor { + let queue_stats_url = format!("/api/worker/{}/queue_stats", worker_name); + let link = ctx.link().clone(); + spawn_local(async move { + match Request::get(&queue_stats_url).send().await { + Ok(response) => { + if response.ok() { + match response.json::().await { + Ok(stats) => { + link.send_message(Msg::SetQueueStats(Ok(stats))) + } + Err(e) => link.send_message(Msg::SetQueueStats(Err( + format!("Failed to parse queue stats: {}", e), + ))), + } + } else { + link.send_message(Msg::SetQueueStats(Err(format!( + "API error (queue_stats): {} {}", + response.status(), + response.status_text() + )))); + } + } + Err(e) => link.send_message(Msg::SetQueueStats(Err(format!( + "Network error fetching queue stats: {}", + e + )))), + } + }); + } + false // No direct re-render, SetQueueStats will trigger it + } + Msg::SetWorkerData(Ok(data)) => { + self.tasks_list = data.tasks; + self.current_queue_stats = data.queue_stats; + self.error_message = None; + self.is_loading_initial_data = false; + true + } + Msg::SetWorkerData(Err(err_msg)) => { + self.error_message = Some(err_msg); + self.is_loading_initial_data = false; + if let Some(timer) = self.queue_poll_timer.take() { + timer.cancel(); + } + true + } + Msg::SetQueueStats(Ok(stats)) => { + self.current_queue_stats = Some(stats); + // Don't clear main error message here, as this is a background update + true + } + Msg::SetQueueStats(Err(err_msg)) => { + log::error!("Failed to update queue stats: {}", err_msg); + // Optionally show a non-blocking error for queue stats + self.current_queue_stats = None; + true + } + Msg::ViewTaskDetails(hash) => { + self.is_loading_task_details = true; + self.selected_task_details = None; // Clear previous details + let task_details_url = format!("/api/task/{}", hash); + let link = ctx.link().clone(); + spawn_local(async move { + match Request::get(&task_details_url).send().await { + Ok(response) => { + if response.ok() { + match response.json::().await { + Ok(details) => { + link.send_message(Msg::SetTaskDetails(Ok(details))) + } + Err(e) => link.send_message(Msg::SetTaskDetails(Err(format!( + "Failed to parse task details: {}", + e + )))), + } + } else { + link.send_message(Msg::SetTaskDetails(Err(format!( + "API error (task_details): {} {}", + response.status(), + response.status_text() + )))); + } + } + Err(e) => link.send_message(Msg::SetTaskDetails(Err(format!( + "Network error fetching task details: {}", + e + )))), + } + }); + true + } + Msg::SetTaskDetails(Ok(details)) => { + self.selected_task_details = Some(details); + self.error_message = None; // Clear general error if task details load + self.is_loading_task_details = false; + true + } + Msg::SetTaskDetails(Err(err_msg)) => { + self.error_message = Some(format!("Error loading task details: {}", err_msg)); + self.selected_task_details = None; + self.is_loading_task_details = false; + true + } + Msg::ClearTaskDetails => { + self.selected_task_details = None; + true + } + } + } + + fn view(&self, ctx: &Context) -> Html { + let link = ctx.link(); + let on_worker_name_input = link.callback(|e: InputEvent| { + let input: HtmlInputElement = e.target_unchecked_into(); + Msg::UpdateWorkerName(input.value()) + }); + + html! { +
+

{ "Rhai Worker Monitor" }

+ +
+ ().value()) } + })} + /> + +
+ + if let Some(err) = &self.error_message { +

{ err }

+ } + + if self.worker_name_to_monitor.is_some() && !self.is_loading_initial_data && self.error_message.is_none() { +

{ format!("Monitoring: {}", self.worker_name_to_monitor.as_ref().unwrap()) }

+ +

{ "Queue Status" }

+
+ { + if let Some(stats) = &self.current_queue_stats { + // TODO: Implement actual color coding and bar visualization + html! {

{format!("Tasks in queue: {} ({})", stats.current_size, stats.color_code)}

} + } else { + html! {

{ "Loading queue stats..." }

} + } + } +
+ +

{ "Tasks" }

+ { self.view_tasks_table(ctx) } + { self.view_selected_task_details(ctx) } + + } else if self.is_loading_initial_data { +

{ "Loading worker data..." }

+ } +
+ } + } +} + +impl App { + fn view_tasks_table(&self, ctx: &Context) -> Html { + if self.tasks_list.is_empty() + && self.worker_name_to_monitor.is_some() + && !self.is_loading_initial_data + { + return html! {

{ "No tasks found for this worker, or worker not found." }

}; + } + if !self.tasks_list.is_empty() { + html! { + + + + + + + + + + { for self.tasks_list.iter().map(|task| self.view_task_row(ctx, task)) } + +
{ "Hash (click to view)" }{ "Created At (UTC)" }{ "Status" }
+ } + } else { + html! {} + } + } + + fn view_task_row(&self, ctx: &Context, task: &TaskSummary) -> Html { + let task_hash_clone = task.hash.clone(); + let created_at_str = chrono::DateTime::from_timestamp(task.created_at, 0).map_or_else( + || "Invalid date".to_string(), + |dt| dt.format("%Y-%m-%d %H:%M:%S").to_string(), + ); + html! { + + { task.hash.chars().take(12).collect::() }{ "..." } + { created_at_str } + { &task.status } + + } + } + + fn view_selected_task_details(&self, ctx: &Context) -> Html { + if self.is_loading_task_details { + return html! {

{ "Loading task details..." }

}; + } + if let Some(details) = &self.selected_task_details { + let created_at_str = chrono::DateTime::from_timestamp(details.created_at, 0) + .map_or_else( + || "Invalid date".to_string(), + |dt| dt.format("%Y-%m-%d %H:%M:%S UTC").to_string(), + ); + html! { +
+

{ format!("Task Details: {}", details.hash) }

+

{ "Created At: " }{ created_at_str }

+

{ "Status: " }{ &details.status }

+

{ "Script Content:" }

+
{ &details.script_content }
+ if let Some(result) = &details.result { +

{ "Result:" }

+
{ result }
+ } + if let Some(error) = &details.error { +

{ "Error:" }

+
{ error }
+ } + +
+ } + } else { + html! {} + } + } +} diff --git a/rhailib/research/rhai_engine_ui/src/main.rs b/rhailib/research/rhai_engine_ui/src/main.rs new file mode 100644 index 0000000..4143f28 --- /dev/null +++ b/rhailib/research/rhai_engine_ui/src/main.rs @@ -0,0 +1,184 @@ +// The 'app' module is shared between the server and the client. +mod app; + +// --- SERVER-SIDE CODE --- // + +#[cfg(feature = "server")] +mod server { + use axum::{ + extract::{Path, State}, + http::{Method, StatusCode}, + routing::get, + Json, Router, + }; + use deadpool_redis::{Config, Pool, Runtime}; + use redis::{from_redis_value, AsyncCommands, FromRedisValue, Value}; + use std::collections::HashMap; + use std::env; + use std::net::SocketAddr; + use tower_http::cors::{Any, CorsLayer}; + use tower_http::services::ServeDir; + + // Import the shared application state and data structures + use crate::app::{QueueStats, TaskDetails, TaskSummary, WorkerDataResponse}; + + const REDIS_TASK_DETAILS_PREFIX: &str = "rhai_task_details:"; + const REDIS_QUEUE_PREFIX: &str = "rhai_tasks:"; + + // The main function to run the server + pub async fn run() { + let redis_url = env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1/".to_string()); + let cfg = Config::from_url(redis_url); + let pool = cfg + .create_pool(Some(Runtime::Tokio1)) + .expect("Failed to create Redis pool"); + + let cors = CorsLayer::new() + .allow_methods([Method::GET]) + .allow_origin(Any); + + let app = Router::new() + .route( + "/api/worker/:worker_name/tasks_and_stats", + get(get_worker_data), + ) + .route("/api/worker/:worker_name/queue_stats", get(get_queue_stats)) + .route("/api/task/:hash", get(get_task_details)) + .nest_service("/", ServeDir::new("dist")) + .with_state(pool) + .layer(cors); + + let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); + println!("Backend server listening on http://{}", addr); + println!("Serving static files from './dist' directory."); + + let listener = tokio::net::TcpListener::bind(addr).await.unwrap(); + axum::serve(listener, app).await.unwrap(); + } + + // --- API Handlers (Live Redis Data) --- + + async fn get_worker_data( + State(pool): State, + Path(worker_name): Path, + ) -> Result, (StatusCode, String)> { + let mut conn = pool.get().await.map_err(internal_error)?; + let queue_key = format!("{}{}", REDIS_QUEUE_PREFIX, worker_name); + + let task_ids: Vec = conn + .lrange(&queue_key, 0, -1) + .await + .map_err(internal_error)?; + let mut tasks = Vec::new(); + + for task_id in task_ids { + let task_key = format!("{}{}", REDIS_TASK_DETAILS_PREFIX, task_id); + let task_details: redis::Value = + conn.hgetall(&task_key).await.map_err(internal_error)?; + if let Ok(summary) = task_summary_from_redis_value(&task_details) { + tasks.push(summary); + } + } + + let queue_stats = get_queue_stats_internal(&mut conn, &worker_name).await?; + + Ok(Json(WorkerDataResponse { + tasks, + queue_stats: Some(queue_stats), + })) + } + + async fn get_queue_stats( + State(pool): State, + Path(worker_name): Path, + ) -> Result, (StatusCode, String)> { + let mut conn = pool.get().await.map_err(internal_error)?; + let stats = get_queue_stats_internal(&mut conn, &worker_name).await?; + Ok(Json(stats)) + } + + async fn get_task_details( + State(pool): State, + Path(hash): Path, + ) -> Result, (StatusCode, String)> { + let mut conn = pool.get().await.map_err(internal_error)?; + let task_key = format!("{}{}", REDIS_TASK_DETAILS_PREFIX, hash); + let task_details: redis::Value = conn.hgetall(&task_key).await.map_err(internal_error)?; + let details = task_details_from_redis_value(&task_details).map_err(internal_error)?; + Ok(Json(details)) + } + + // --- Internal Helper Functions --- + + async fn get_queue_stats_internal( + conn: &mut deadpool_redis::Connection, + worker_name: &str, + ) -> Result { + let queue_key = format!("{}{}", REDIS_QUEUE_PREFIX, worker_name); + let size: u32 = conn.llen(&queue_key).await.map_err(internal_error)?; + let color_code = match size { + 0..=10 => "green", + 11..=50 => "yellow", + _ => "red", + } + .to_string(); + Ok(QueueStats { + current_size: size, + color_code, + }) + } + + fn internal_error(err: E) -> (StatusCode, String) { + (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()) + } + + fn task_summary_from_redis_value(v: &Value) -> redis::RedisResult { + let map: HashMap = from_redis_value(v)?; + Ok(TaskSummary { + hash: map.get("hash").cloned().unwrap_or_default(), + created_at: map + .get("createdAt") + .and_then(|s| s.parse().ok()) + .unwrap_or_default(), + status: map + .get("status") + .cloned() + .unwrap_or_else(|| "Unknown".to_string()), + }) + } + + fn task_details_from_redis_value(v: &Value) -> redis::RedisResult { + let map: HashMap = from_redis_value(v)?; + Ok(TaskDetails { + hash: map.get("hash").cloned().unwrap_or_default(), + created_at: map + .get("createdAt") + .and_then(|s| s.parse().ok()) + .unwrap_or_default(), + status: map + .get("status") + .cloned() + .unwrap_or_else(|| "Unknown".to_string()), + script_content: map.get("script").cloned().unwrap_or_default(), + result: map.get("output").cloned(), + error: map.get("error").cloned(), + }) + } +} + +// --- MAIN ENTRY POINTS --- // + +// Main function for the server binary +#[cfg(feature = "server")] +#[tokio::main] +async fn main() { + server::run().await; +} + +// Main function for the WASM client (compiles when 'server' feature is not enabled) +#[cfg(not(feature = "server"))] +fn main() { + wasm_logger::init(wasm_logger::Config::default()); + log::info!("Rhai Worker UI starting..."); + yew::Renderer::::new().render(); +} diff --git a/rhailib/research/rhai_engine_ui/styles.css b/rhailib/research/rhai_engine_ui/styles.css new file mode 100644 index 0000000..584e382 --- /dev/null +++ b/rhailib/research/rhai_engine_ui/styles.css @@ -0,0 +1,173 @@ +/* --- Dark, Sleek, and Modern UI --- */ + +:root { + --bg-color: #1a1a1a; + --primary-color: #252525; + --secondary-color: #333333; + --font-color: #e0e0e0; + --highlight-color: #00aaff; + --border-color: #444444; + --error-color: #ff4d4d; + --error-bg-color: rgba(255, 77, 77, 0.1); +} + +body { + font-family: 'Inter', sans-serif; + margin: 0; + padding: 40px 20px; + background-color: var(--bg-color); + color: var(--font-color); + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +.container { + background-color: transparent; + max-width: 900px; + margin: auto; +} + +h1, h2, h3, h4 { + color: var(--font-color); + font-weight: 600; + margin-bottom: 20px; +} + +h1 { + text-align: center; + font-size: 2.5em; + letter-spacing: -1px; +} + +.input-group { + margin-bottom: 30px; + display: flex; + gap: 10px; +} + +input[type="text"] { + flex-grow: 1; + padding: 12px 15px; + border: 1px solid var(--border-color); + border-radius: 6px; + font-size: 1em; + background-color: var(--primary-color); + color: var(--font-color); + transition: border-color 0.3s, box-shadow 0.3s; +} + +input[type="text"]:focus { + outline: none; + border-color: var(--highlight-color); + box-shadow: 0 0 0 3px rgba(0, 170, 255, 0.2); +} + +button { + padding: 12px 20px; + background-color: var(--highlight-color); + color: #ffffff; + border: none; + border-radius: 6px; + cursor: pointer; + font-size: 1em; + font-weight: 500; + transition: background-color 0.3s; +} + +button:hover { + background-color: #0088cc; +} + +button:disabled { + background-color: var(--secondary-color); + cursor: not-allowed; +} + +.error { + color: var(--error-color); + margin-top: 20px; + text-align: center; + padding: 12px; + border: 1px solid var(--error-color); + background-color: var(--error-bg-color); + border-radius: 6px; +} + +.task-table { + width: 100%; + border-collapse: collapse; + margin-top: 30px; +} + +.task-table th, .task-table td { + border-bottom: 1px solid var(--border-color); + padding: 15px; + text-align: left; +} + +.task-table th { + font-weight: 600; + color: #a0a0a0; + text-transform: uppercase; + font-size: 0.85em; + letter-spacing: 0.5px; +} + +.task-table tr { + transition: background-color 0.2s; +} + +.task-table tr:hover { + background-color: var(--primary-color); + cursor: pointer; +} + +.queue-visualization { + margin-top: 30px; + padding: 25px; + border: 1px solid var(--border-color); + background-color: var(--primary-color); + border-radius: 8px; + text-align: center; + font-size: 1.2em; + font-weight: 500; +} + +.task-details-modal { + margin-top: 30px; + padding: 25px; + border: 1px solid var(--border-color); + background-color: var(--primary-color); + border-radius: 8px; +} + +.task-details-modal h4 { + margin-top: 0; + font-size: 1.5em; +} + +.task-details-modal p { + margin: 12px 0; + color: #c0c0c0; +} + +.task-details-modal p strong { + color: var(--font-color); + font-weight: 500; +} + +.task-details-modal pre { + background-color: var(--bg-color); + padding: 15px; + border-radius: 6px; + white-space: pre-wrap; + word-break: break-all; + max-height: 250px; + overflow-y: auto; + border: 1px solid var(--border-color); + font-family: 'Courier New', Courier, monospace; +} + +.task-details-modal button { + margin-top: 20px; +} diff --git a/rhailib/src/derive/Cargo.toml b/rhailib/src/derive/Cargo.toml new file mode 100644 index 0000000..6896610 --- /dev/null +++ b/rhailib/src/derive/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "derive" +version = "0.1.0" +edition = "2024" + +[lib] +proc-macro = true + +[dependencies] +syn = { version = "1.0", features = ["full"] } +quote = "1.0" diff --git a/rhailib/src/derive/README.md b/rhailib/src/derive/README.md new file mode 100644 index 0000000..0875d47 --- /dev/null +++ b/rhailib/src/derive/README.md @@ -0,0 +1,78 @@ +# Rhai Derive Macros + +This crate provides procedural macros to simplify the integration of Rust types with the Rhai scripting engine. + +## `RhaiApi` Derive Macro + +The `RhaiApi` macro automatically generates a Rhai module with a fluent, builder-style API for your Rust structs. This allows you to create and modify your structs in Rhai scripts using chained method calls. + +### How It Works + +When you derive `RhaiApi` on a struct, the macro generates: + +1. A new Rust module named `{struct_name}_rhai_dsl`. +2. A Rhai `export_module` within that module named `generated_rhai_module`. +3. A `new_{struct_name}()` function to create a new instance of your struct. +4. Setter functions for each field in your struct, allowing for method chaining. +5. An `id()` function to retrieve the object's ID. + +### Example + +**Rust Struct Definition:** + +```rust +use derive::RhaiApi; + +#[derive(RhaiApi, Clone)] +pub struct Product { + pub id: i64, + pub name: String, + pub price: f64, +} +``` + +**Generated Rhai API Usage:** + +```rhai +// Import the generated module +import product_rhai_dsl::generated_rhai_module as product_api; + +// Use the fluent API to build a new product +let my_product = product_api::new_product() + .id(1) + .name("Awesome Gadget") + .price(99.99); + +print(my_product.id()); // prints 1 +``` + +## `FromVec` Derive Macro + +The `FromVec` macro is a utility for tuple structs that contain a single field. It implements the `From` trait, where `T` is the inner type, allowing for seamless conversions. + +### Example + +**Rust Struct Definition:** + +```rust +use derive::FromVec; + +#[derive(FromVec)] +pub struct MyVec(Vec); +``` + +**Usage:** + +```rust +let data = vec![1, 2, 3]; +let my_vec = MyVec::from(data); +``` + +## Usage + +To use these macros in your project, add this crate as a dependency in your `Cargo.toml` file: + +```toml +[dependencies] +derive = { path = "../path/to/rhailib/src/derive" } +``` diff --git a/rhailib/src/derive/docs/ARCHITECTURE.md b/rhailib/src/derive/docs/ARCHITECTURE.md new file mode 100644 index 0000000..493ff0b --- /dev/null +++ b/rhailib/src/derive/docs/ARCHITECTURE.md @@ -0,0 +1,67 @@ +# Architecture of the `derive` Crate + +The `derive` crate is a procedural macro crate responsible for generating boilerplate code that integrates Rust structs with the Rhai scripting engine. It simplifies the process of exposing Rust types and their properties to Rhai scripts. + +## Core Functionality + +The crate provides two main procedural macros: + +1. `#[derive(RhaiApi)]` +2. `#[derive(FromVec)]` + +--- + +## `#[derive(RhaiApi)]` + +This is the primary macro of the crate. When applied to a Rust struct, it automatically generates a Rhai-compatible DSL (Domain-Specific Language) for that struct. + +### Generated Code Structure + +For a struct named `MyStruct`, the macro generates a new module named `my_struct_rhai_dsl`. This module contains a Rhai `export_module` with the following functions: + +* **`new_my_struct()`**: A constructor function that creates a new instance of `MyStruct` within the Rhai engine. +* **Setter Functions**: For each field in `MyStruct`, a corresponding setter function is generated. For a field named `my_field`, a Rhai function `my_field(value)` is created to set its value. +* **`id()`**: A function to retrieve the ID of the object. + +This allows for a fluent, chainable API within Rhai scripts, like so: + +```rhai +let my_object = new_my_struct().field1(42).field2("hello"); +``` + +### Implementation Details + +The implementation resides in `src/rhai_api.rs`. It uses the `syn` crate to parse the input `DeriveInput` and the `quote` crate to construct the output `TokenStream`. + +The process is as follows: + +1. The macro input is parsed into a `DeriveInput` AST (Abstract Syntax Tree). +2. The struct's name and fields are extracted from the AST. +3. A new module name is generated based on the struct's name (e.g., `MyStruct` -> `my_struct_rhai_dsl`). +4. Using the `quote!` macro, the code for the new module, the `export_module`, the constructor, and the setter functions is generated. +5. The generated code is returned as a `TokenStream`, which the compiler then incorporates into the crate. + +### Architectural Diagram + +```mermaid +graph TD + A[Rust Struct Definition] -- `#[derive(RhaiApi)]` --> B{`derive` Crate}; + B -- `syn` --> C[Parse Struct AST]; + C -- Extract Fields & Name --> D[Generate Code with `quote`]; + D -- Create --> E[Constructor `new_...()`]; + D -- Create --> F[Setter Functions `field(...)`]; + D -- Create --> G[`id()` function]; + E & F & G -- Packaged into --> H[Rhai `export_module`]; + H -- Returned as `TokenStream` --> I[Compiler]; + I -- Integrates into --> J[Final Binary]; +``` + +--- + +## `#[derive(FromVec)]` + +This is a simpler utility macro. Its purpose is to generate a `From>` implementation for a tuple struct that contains a single `Vec`. This is useful for converting a vector of items into a specific newtype-pattern struct. + +### Implementation + +The implementation is located directly in `src/lib.rs`. It parses the input struct and, if it's a single-element tuple struct, generates the corresponding `From` implementation. \ No newline at end of file diff --git a/rhailib/src/derive/src/lib.rs b/rhailib/src/derive/src/lib.rs new file mode 100644 index 0000000..3e8a961 --- /dev/null +++ b/rhailib/src/derive/src/lib.rs @@ -0,0 +1,117 @@ +//! # Derive Macros for Rhai Integration +//! +//! This crate provides procedural macros to simplify the integration of Rust structs +//! with the Rhai scripting engine. It automatically generates boilerplate code for +//! exposing Rust types to Rhai scripts. + +extern crate proc_macro; +use proc_macro::TokenStream; +use quote::quote; +use syn::{Data, DeriveInput, Fields, parse_macro_input}; + +mod rhai_api; + +/// Derives the `RhaiApi` for a struct, generating a Rhai DSL module. +/// +/// This macro creates a new module containing a Rhai `export_module` with: +/// - A constructor function (`new_()`) +/// - Setter functions for each field (chainable API) +/// - An `id()` function to retrieve the object's ID +/// +/// # Example +/// +/// ```rust +/// use derive::RhaiApi; +/// +/// #[derive(RhaiApi)] +/// struct MyStruct { +/// id: u64, +/// name: String, +/// value: i32, +/// } +/// ``` +/// +/// This generates a Rhai module that allows scripts like: +/// ```rhai +/// let obj = new_mystruct().name("test").value(42); +/// let obj_id = obj.id(); +/// ``` +/// +/// # Generated Module Structure +/// +/// For a struct `MyStruct`, this creates a module `mystruct_rhai_dsl` containing +/// the Rhai-compatible functions. The module can be registered with a Rhai engine +/// to expose the functionality to scripts. +/// +/// # Limitations +/// +/// - Only works with structs that have named fields +/// - Fields named `base_data` are ignored during generation +/// - The struct must implement an `id()` method returning a numeric type +#[proc_macro_derive(RhaiApi)] +pub fn rhai_api_derive(input: TokenStream) -> TokenStream { + rhai_api::impl_rhai_api(input) +} + +/// Derives a `From` implementation for single-element tuple structs. +/// +/// This macro generates a `From` trait implementation that allows converting +/// the inner type directly into the tuple struct wrapper. +/// +/// # Example +/// +/// ```rust +/// use derive::FromVec; +/// +/// #[derive(FromVec)] +/// struct MyWrapper(Vec); +/// ``` +/// +/// This generates: +/// ```rust +/// impl From> for MyWrapper { +/// fn from(vec: Vec) -> Self { +/// MyWrapper(vec) +/// } +/// } +/// ``` +/// +/// # Limitations +/// +/// - Only works with tuple structs containing exactly one field +/// - The struct must be a simple wrapper around another type +/// +/// # Panics +/// +/// This macro will panic at compile time if: +/// - Applied to a struct that is not a tuple struct +/// - Applied to a tuple struct with more or fewer than one field +#[proc_macro_derive(FromVec)] +pub fn from_vec_derive(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as DeriveInput); + let name = input.ident; + + let inner_type = match input.data { + Data::Struct(s) => match s.fields { + Fields::Unnamed(mut fields) => { + if fields.unnamed.len() != 1 { + panic!("FromVec can only be derived for tuple structs with one field."); + } + let field = fields.unnamed.pop().unwrap().into_value(); + field.ty + } + _ => panic!("FromVec can only be derived for tuple structs."), + }, + _ => panic!("FromVec can only be derived for structs."), + }; + + let expanded = quote! { + impl From<#inner_type> for #name { + fn from(vec: #inner_type) -> Self { + #name(vec) + } + } + }; + + TokenStream::from(expanded) +} diff --git a/rhailib/src/derive/src/rhai_api.rs b/rhailib/src/derive/src/rhai_api.rs new file mode 100644 index 0000000..d6d96ca --- /dev/null +++ b/rhailib/src/derive/src/rhai_api.rs @@ -0,0 +1,116 @@ +//! Implementation of the `RhaiApi` derive macro. +//! +//! This module contains the core logic for generating Rhai-compatible DSL modules +//! from Rust struct definitions. + +use proc_macro::TokenStream; +use quote::{format_ident, quote}; +use syn::{Data, DeriveInput, Fields, parse_macro_input}; + +/// Implements the `RhaiApi` derive macro functionality. +/// +/// This function takes a `TokenStream` representing a struct definition and generates +/// a complete Rhai DSL module with constructor, setter functions, and utility methods. +/// +/// # Generated Code Structure +/// +/// For a struct `MyStruct`, this generates: +/// - A module named `mystruct_rhai_dsl` +/// - A constructor function `new_mystruct()` +/// - Setter functions for each field (excluding `base_data`) +/// - An `id()` function for object identification +/// +/// # Arguments +/// +/// * `input` - A `TokenStream` containing the struct definition to process +/// +/// # Returns +/// +/// A `TokenStream` containing the generated Rhai DSL module code +/// +/// # Panics +/// +/// This function will panic if: +/// - The input is not a struct +/// - The struct does not have named fields +pub fn impl_rhai_api(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as DeriveInput); + let struct_name = &input.ident; + let struct_name_lowercase_str = struct_name.to_string().to_lowercase(); + + let mod_name = format_ident!("{}_rhai_dsl", struct_name_lowercase_str); + let id_fn_name = format_ident!("{}_id", struct_name_lowercase_str); + + // --- Generate `new` function --- + let new_fn_name_str = format!("new_{}", struct_name_lowercase_str); + let new_fn_name_ident = format_ident!("new_{}", struct_name_lowercase_str); + let new_fn = quote! { + #[rhai_fn(name = #new_fn_name_str, return_raw)] + pub fn #new_fn_name_ident() -> Result> { + let object = RhaiObject::new(); + Ok(object) + } + }; + + // --- Generate setter functions from struct fields --- + let fields = if let Data::Struct(s) = &input.data { + if let Fields::Named(fields) = &s.fields { + &fields.named + } else { + panic!("RhaiApi can only be derived for structs with named fields."); + } + } else { + panic!("RhaiApi can only be derived for structs."); + }; + + let setter_fns = fields.iter().map(|f| { + let field_name = f.ident.as_ref().unwrap(); + let field_type = &f.ty; + + if field_name.to_string() == "base_data" { + return quote! {}; + } + + let rhai_fn_name_str = field_name.to_string(); + let rust_fn_name = format_ident!("{}_{}", struct_name_lowercase_str, field_name); + + quote! { + #[rhai_fn(name = #rhai_fn_name_str, return_raw, global, pure)] + pub fn #rust_fn_name( + object: &mut RhaiObject, + value: #field_type, + ) -> Result> { + let owned_object = std::mem::take(object); + *object = owned_object.#field_name(value); + Ok(object.clone()) + } + } + }); + + let expanded = quote! { + pub mod #mod_name { + use rhai::plugin::*; + use rhai::{EvalAltResult, INT}; + use super::#struct_name; + use std::mem; + + type RhaiObject = #struct_name; + + #[export_module] + pub mod generated_rhai_module { + use super::*; + + #new_fn + + #[rhai_fn(name = "id", return_raw, global, pure)] + pub fn #id_fn_name(object: &mut RhaiObject) -> Result> { + Ok(object.id() as i64) + } + + #(#setter_fns)* + } + } + }; + + TokenStream::from(expanded) +} diff --git a/rhailib/src/flow/Cargo.toml b/rhailib/src/flow/Cargo.toml new file mode 100644 index 0000000..310cfd7 --- /dev/null +++ b/rhailib/src/flow/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "flow" +version = "0.1.0" +edition = "2021" +description = "Simple flow manager for Rhai scripts" + +[dependencies] +rhai = { version = "=1.21.0", features = ["std", "sync"] } +rhai_dispatcher = { path = "../dispatcher" } +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +tokio = { version = "1", features = ["full"] } +redis = { version = "0.23", features = ["tokio-comp"] } +uuid = { version = "1.0", features = ["v4"] } + +[dev-dependencies] +tempfile = "3" \ No newline at end of file diff --git a/rhailib/src/flow/README.md b/rhailib/src/flow/README.md new file mode 100644 index 0000000..4477e94 --- /dev/null +++ b/rhailib/src/flow/README.md @@ -0,0 +1,110 @@ +# Flow Manager + +A simple, generic flow manager for Rhai scripts with builder pattern API and non-blocking execution. + +## Features + +- **Builder Pattern API**: Fluent interface for creating steps and flows +- **Non-blocking Execution**: Uses `tokio::spawn` for async step execution +- **Simple State Management**: Redis-based state tracking +- **Retry Logic**: Configurable timeouts and retry attempts +- **Mock API Support**: Built-in mock API for testing different scenarios +- **RhaiDispatcher Integration**: Seamless integration with existing Rhai execution system + +## Quick Start + +```rust +use flow::{new_step, new_flow, FlowExecutor}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + // Create executor + let executor = FlowExecutor::new("redis://127.0.0.1/").await?; + + // Build steps using fluent API + let step1 = new_step("stripe_config") + .script("stripe_config_script") + .timeout(5) + .retries(2) + .build(); + + let step2 = new_step("stripe_config_confirm") + .script("script that looks up stripe config confirmation in db") + .timeout(5) + .build(); + + let step3 = new_step("create_product") + .script("create_product_script") + .timeout(10) + .retries(1) + .build(); + + // Build flow using fluent API + let flow = new_flow("stripe_payment_request") + .add_step(step1) + .add_step(step2) + .add_step(step3) + .build(); + + // Execute flow (non-blocking) + let result = executor.execute_flow(flow).await?; + println!("Flow started: {}", result); + + Ok(()) +} +``` + +## Architecture + +### Core Components + +- **Types** (`types.rs`): Core data structures (Flow, Step, Status enums) +- **Builder** (`builder.rs`): Fluent API for constructing flows and steps +- **State** (`state.rs`): Simple Redis-based state management +- **Executor** (`executor.rs`): Non-blocking flow execution engine +- **Mock API** (`mock_api.rs`): Testing utilities for different response scenarios + +### State Management + +The system tracks minimal state: + +**Flow State:** +- `flow_id: String` - unique identifier +- `status: FlowStatus` (Created, Running, Completed, Failed) +- `current_step: Option` - currently executing step +- `completed_steps: Vec` - list of finished steps + +**Step State:** +- `step_id: String` - unique identifier +- `status: StepStatus` (Pending, Running, Completed, Failed) +- `attempt_count: u32` - for retry logic +- `output: Option` - result from script execution + +**Storage:** +- Redis key-value pairs: `flow:{flow_id}` and `step:{flow_id}:{step_id}` + +## Examples + +Run the example: + +```bash +cd ../rhailib/src/flow +cargo run --example stripe_flow_example +``` + +## Testing + +```bash +cargo test +``` + +Note: Some tests require Redis to be running. Set `SKIP_REDIS_TESTS=1` to skip Redis-dependent tests. + +## Integration + +The flow manager integrates with: +- **RhaiDispatcher**: For executing Rhai scripts +- **Redis**: For state persistence +- **tokio**: For non-blocking async execution + +This provides a simple, reliable foundation for orchestrating complex workflows while maintaining the non-blocking execution pattern established in the payment system. \ No newline at end of file diff --git a/rhailib/src/flow/examples/stripe_flow_example.rs b/rhailib/src/flow/examples/stripe_flow_example.rs new file mode 100644 index 0000000..bbed26f --- /dev/null +++ b/rhailib/src/flow/examples/stripe_flow_example.rs @@ -0,0 +1,90 @@ +//! Example demonstrating the flow manager with mock Stripe API calls + +use flow::{new_step, new_flow, FlowExecutor}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + println!("=== Flow Manager Example ==="); + println!("Demonstrating the builder pattern API with mock Stripe workflow\n"); + + // Create the flow executor + let executor = FlowExecutor::new("redis://127.0.0.1/").await?; + + // Build steps using the fluent API + let step1 = new_step("stripe_config") + .script("mock_api_call stripe_config") + .timeout(5) + .retries(2) + .build(); + + let step2 = new_step("stripe_config_confirm") + .script("mock_api_call create_product") + .timeout(5) + .retries(1) + .build(); + + let step3 = new_step("create_product") + .script("mock_api_call create_product") + .timeout(10) + .retries(1) + .build(); + + // Build flow using the fluent API + let flow = new_flow("stripe_payment_request") + .add_step(step1) + .add_step(step2) + .add_step(step3) + .build(); + + println!("Created flow: {}", flow.name); + println!("Flow ID: {}", flow.id); + println!("Number of steps: {}", flow.steps.len()); + + for (i, step) in flow.steps.iter().enumerate() { + println!(" Step {}: {} (timeout: {}s, retries: {})", + i + 1, step.name, step.timeout_seconds, step.max_retries); + } + + // Execute the flow (non-blocking) + println!("\n🚀 Starting flow execution..."); + let result = executor.execute_flow(flow.clone()).await?; + println!("✅ {}", result); + + // Monitor flow progress + println!("\n📊 Monitoring flow progress..."); + for i in 0..10 { + tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; + + if let Ok(Some(flow_state)) = executor.get_flow_status(&flow.id).await { + println!(" Status: {:?}, Current step: {:?}, Completed: {}/{}", + flow_state.status, + flow_state.current_step, + flow_state.completed_steps.len(), + flow.steps.len()); + + if matches!(flow_state.status, flow::FlowStatus::Completed | flow::FlowStatus::Failed) { + break; + } + } + } + + // Check final status + if let Ok(Some(final_state)) = executor.get_flow_status(&flow.id).await { + println!("\n🎯 Final flow status: {:?}", final_state.status); + println!("Completed steps: {:?}", final_state.completed_steps); + + // Check individual step results + for step in &flow.steps { + if let Ok(Some(step_state)) = executor.get_step_status(&flow.id, &step.id).await { + println!(" Step '{}': {:?} (attempts: {})", + step.name, step_state.status, step_state.attempt_count); + if let Some(output) = &step_state.output { + println!(" Output: {}", output); + } + } + } + } + + println!("\n✨ Flow execution demonstration completed!"); + Ok(()) +} \ No newline at end of file diff --git a/rhailib/src/flow/src/builder.rs b/rhailib/src/flow/src/builder.rs new file mode 100644 index 0000000..6b1f80f --- /dev/null +++ b/rhailib/src/flow/src/builder.rs @@ -0,0 +1,108 @@ +//! Builder patterns for steps and flows + +use crate::types::{Step, Flow}; + +/// Builder for creating steps with fluent API +pub struct StepBuilder { + step: Step, +} + +impl StepBuilder { + pub fn new(name: &str) -> Self { + Self { + step: Step::new(name), + } + } + + /// Set the script content for this step + pub fn script(mut self, script: &str) -> Self { + self.step.script = script.to_string(); + self + } + + /// Set timeout in seconds + pub fn timeout(mut self, seconds: u64) -> Self { + self.step.timeout_seconds = seconds; + self + } + + /// Set maximum retry attempts + pub fn retries(mut self, count: u32) -> Self { + self.step.max_retries = count; + self + } + + /// Build the final step + pub fn build(self) -> Step { + self.step + } +} + +/// Builder for creating flows with fluent API +pub struct FlowBuilder { + flow: Flow, +} + +impl FlowBuilder { + pub fn new(name: &str) -> Self { + Self { + flow: Flow::new(name), + } + } + + /// Add a step to this flow + pub fn add_step(mut self, step: Step) -> Self { + self.flow.steps.push(step); + self + } + + /// Build the final flow + pub fn build(self) -> Flow { + self.flow + } +} + +/// Convenience function to create a new step builder +pub fn new_step(name: &str) -> StepBuilder { + StepBuilder::new(name) +} + +/// Convenience function to create a new flow builder +pub fn new_flow(name: &str) -> FlowBuilder { + FlowBuilder::new(name) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_step_builder() { + let step = new_step("test_step") + .script("print('hello world');") + .timeout(10) + .retries(3) + .build(); + + assert_eq!(step.name, "test_step"); + assert_eq!(step.script, "print('hello world');"); + assert_eq!(step.timeout_seconds, 10); + assert_eq!(step.max_retries, 3); + } + + #[test] + fn test_flow_builder() { + let step1 = new_step("step1").script("let x = 1;").build(); + let step2 = new_step("step2").script("let y = 2;").build(); + + let flow = new_flow("test_flow") + .add_step(step1) + .add_step(step2) + .build(); + + assert_eq!(flow.name, "test_flow"); + assert_eq!(flow.steps.len(), 2); + assert_eq!(flow.steps[0].name, "step1"); + assert_eq!(flow.steps[1].name, "step2"); + } +} \ No newline at end of file diff --git a/rhailib/src/flow/src/executor.rs b/rhailib/src/flow/src/executor.rs new file mode 100644 index 0000000..9c1e2e5 --- /dev/null +++ b/rhailib/src/flow/src/executor.rs @@ -0,0 +1,243 @@ +//! Simple flow executor with non-blocking step execution + +use crate::types::{Flow, Step, FlowStatus, StepStatus}; +use crate::state::{FlowState, StepState, StateManager}; +use crate::mock_api::MockAPI; +use rhai_dispatcher::RhaiDispatcherBuilder; +use std::sync::Arc; +use tokio::time::{timeout, Duration}; + +/// Simple flow executor +pub struct FlowExecutor { + state_manager: Arc, + mock_api: Arc, + redis_url: String, +} + +impl FlowExecutor { + pub async fn new(redis_url: &str) -> Result> { + let state_manager = Arc::new(StateManager::new(redis_url).await?); + let mock_api = Arc::new(MockAPI::default()); + + Ok(Self { + state_manager, + mock_api, + redis_url: redis_url.to_string(), + }) + } + + /// Execute a flow non-blocking + pub async fn execute_flow(&self, flow: Flow) -> Result> { + // Initialize flow state + let mut flow_state = FlowState::new(flow.id.clone()); + flow_state.status = FlowStatus::Running; + self.state_manager.save_flow_state(&flow_state).await?; + + // Initialize step states + for step in &flow.steps { + let step_state = StepState::new(step.id.clone()); + self.state_manager.save_step_state(&flow.id, &step_state).await?; + } + + // Spawn flow execution in background + let flow_id = flow.id.clone(); + let state_manager = self.state_manager.clone(); + let mock_api = self.mock_api.clone(); + let redis_url = self.redis_url.clone(); + + tokio::spawn(async move { + if let Err(e) = Self::execute_flow_steps(flow, state_manager, mock_api, redis_url).await { + eprintln!("Flow execution error: {}", e); + } + }); + + Ok(format!("flow_execution_started:{}", flow_id)) + } + + /// Execute all steps in a flow + async fn execute_flow_steps( + flow: Flow, + state_manager: Arc, + mock_api: Arc, + redis_url: String, + ) -> Result<(), Box> { + let mut flow_state = state_manager.load_flow_state(&flow.id).await? + .ok_or("Flow state not found")?; + + // Execute steps sequentially + for step in &flow.steps { + flow_state.current_step = Some(step.id.clone()); + state_manager.save_flow_state(&flow_state).await?; + + match Self::execute_step_with_retries( + step, + &flow.id, + state_manager.clone(), + mock_api.clone(), + redis_url.clone(), + ).await { + Ok(_) => { + flow_state.completed_steps.push(step.id.clone()); + } + Err(e) => { + eprintln!("Step {} failed: {}", step.name, e); + flow_state.status = FlowStatus::Failed; + state_manager.save_flow_state(&flow_state).await?; + return Err(e); + } + } + } + + // Mark flow as completed + flow_state.status = FlowStatus::Completed; + flow_state.current_step = None; + state_manager.save_flow_state(&flow_state).await?; + + Ok(()) + } + + /// Execute a single step with retry logic + async fn execute_step_with_retries( + step: &Step, + flow_id: &str, + state_manager: Arc, + mock_api: Arc, + redis_url: String, + ) -> Result<(), Box> { + let mut step_state = state_manager.load_step_state(flow_id, &step.id).await? + .ok_or("Step state not found")?; + + let max_attempts = step.max_retries + 1; + + for attempt in 0..max_attempts { + step_state.attempt_count = attempt + 1; + step_state.status = StepStatus::Running; + state_manager.save_step_state(flow_id, &step_state).await?; + + match Self::execute_single_step(step, &mock_api, &redis_url).await { + Ok(output) => { + step_state.status = StepStatus::Completed; + step_state.output = Some(output); + state_manager.save_step_state(flow_id, &step_state).await?; + return Ok(()); + } + Err(e) => { + if attempt + 1 >= max_attempts { + step_state.status = StepStatus::Failed; + state_manager.save_step_state(flow_id, &step_state).await?; + return Err(e); + } + // Wait before retry + tokio::time::sleep(Duration::from_millis(1000)).await; + } + } + } + + Err("Max retries exceeded".into()) + } + + /// Execute a single step + async fn execute_single_step( + step: &Step, + mock_api: &MockAPI, + redis_url: &str, + ) -> Result> { + // Execute with timeout + let result = timeout(step.timeout(), async { + // For demo, we'll use mock API calls instead of real Rhai execution + // In real implementation, this would execute the Rhai script + if step.script.contains("mock_api_call") { + // Extract endpoint from script (simple parsing) + let endpoint = if step.script.contains("stripe_config") { + "stripe_config" + } else if step.script.contains("create_product") { + "create_product" + } else { + "default_endpoint" + }; + + mock_api.call(endpoint).await + } else { + // For non-mock scripts, simulate Rhai execution via dispatcher + Self::execute_rhai_script(&step.script, redis_url).await + } + }).await; + + match result { + Ok(Ok(output)) => Ok(output), + Ok(Err(e)) => Err(e.into()), + Err(_) => Err("Step execution timed out".into()), + } + } + + /// Execute Rhai script using dispatcher (simplified) + async fn execute_rhai_script( + script: &str, + redis_url: &str, + ) -> Result> { + let dispatcher = RhaiDispatcherBuilder::new() + .caller_id("flow_executor") + .redis_url(redis_url) + .build()?; + + let result = dispatcher + .new_play_request() + .worker_id("flow_worker") + .script(script) + .timeout(Duration::from_secs(30)) + .await_response() + .await; + + match result { + Ok(task_details) => { + if task_details.status == "completed" { + Ok(task_details.output.unwrap_or_default()) + } else { + Err(format!("Script execution failed: {:?}", task_details.error).into()) + } + } + Err(e) => Err(format!("Dispatcher error: {}", e).into()), + } + } + + /// Get flow status + pub async fn get_flow_status(&self, flow_id: &str) -> Result, Box> { + self.state_manager.load_flow_state(flow_id).await + } + + /// Get step status + pub async fn get_step_status(&self, flow_id: &str, step_id: &str) -> Result, Box> { + self.state_manager.load_step_state(flow_id, step_id).await + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::builder::{new_step, new_flow}; + + #[tokio::test] + async fn test_flow_execution() { + // This test requires Redis to be running + // Skip if Redis is not available + if std::env::var("SKIP_REDIS_TESTS").is_ok() { + return; + } + + let executor = FlowExecutor::new("redis://127.0.0.1/").await.unwrap(); + + let step1 = new_step("test_step") + .script("mock_api_call stripe_config") + .timeout(5) + .retries(1) + .build(); + + let flow = new_flow("test_flow") + .add_step(step1) + .build(); + + let result = executor.execute_flow(flow).await; + assert!(result.is_ok()); + assert!(result.unwrap().starts_with("flow_execution_started:")); + } +} \ No newline at end of file diff --git a/rhailib/src/flow/src/lib.rs b/rhailib/src/flow/src/lib.rs new file mode 100644 index 0000000..7a69a1e --- /dev/null +++ b/rhailib/src/flow/src/lib.rs @@ -0,0 +1,20 @@ +//! Simple Flow Manager for Rhai Scripts +//! +//! Provides a minimal flow execution system with builder patterns: +//! - `new_step("name").script("script").timeout(5).retries(2)` +//! - `new_flow("name").add_step(step1).add_step(step2)` + +pub mod types; +pub mod builder; +pub mod executor; +pub mod state; +pub mod mock_api; + +pub use types::{Flow, Step, FlowStatus, StepStatus}; +pub use builder::{StepBuilder, FlowBuilder, new_step, new_flow}; +pub use executor::FlowExecutor; +pub use state::{FlowState, StepState, StateManager}; +pub use mock_api::MockAPI; + +// Re-export for convenience +pub use rhai_dispatcher::RhaiDispatcherBuilder; \ No newline at end of file diff --git a/rhailib/src/flow/src/mock_api.rs b/rhailib/src/flow/src/mock_api.rs new file mode 100644 index 0000000..44f6051 --- /dev/null +++ b/rhailib/src/flow/src/mock_api.rs @@ -0,0 +1,144 @@ +//! Simple mock API for testing different response types and durations + +use serde::{Serialize, Deserialize}; +use std::time::Duration; +use std::collections::HashMap; + +/// Mock API response types +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum MockResponseType { + Success, + Failure, + Timeout, +} + +/// Mock API scenario configuration +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct MockScenario { + pub response_type: MockResponseType, + pub delay_ms: u64, + pub response_data: String, +} + +impl MockScenario { + pub fn success(delay_ms: u64, data: &str) -> Self { + Self { + response_type: MockResponseType::Success, + delay_ms, + response_data: data.to_string(), + } + } + + pub fn failure(delay_ms: u64, error: &str) -> Self { + Self { + response_type: MockResponseType::Failure, + delay_ms, + response_data: error.to_string(), + } + } + + pub fn timeout(delay_ms: u64) -> Self { + Self { + response_type: MockResponseType::Timeout, + delay_ms, + response_data: "Request timed out".to_string(), + } + } +} + +/// Simple mock API for testing +pub struct MockAPI { + scenarios: HashMap, +} + +impl MockAPI { + pub fn new() -> Self { + Self { + scenarios: HashMap::new(), + } + } + + /// Add a mock scenario for an endpoint + pub fn add_scenario(&mut self, endpoint: &str, scenario: MockScenario) { + self.scenarios.insert(endpoint.to_string(), scenario); + } + + /// Call a mock endpoint + pub async fn call(&self, endpoint: &str) -> Result { + match self.scenarios.get(endpoint) { + Some(scenario) => { + // Simulate delay + tokio::time::sleep(Duration::from_millis(scenario.delay_ms)).await; + + match scenario.response_type { + MockResponseType::Success => Ok(scenario.response_data.clone()), + MockResponseType::Failure => Err(scenario.response_data.clone()), + MockResponseType::Timeout => { + // For timeout, we just return an error after the delay + Err("Request timed out".to_string()) + } + } + } + None => Err(format!("Unknown endpoint: {}", endpoint)), + } + } + + /// Setup common test scenarios + pub fn setup_test_scenarios(&mut self) { + // Fast success + self.add_scenario("stripe_config", MockScenario::success(100, r#"{"status": "configured"}"#)); + + // Slow success + self.add_scenario("create_product", MockScenario::success(2000, r#"{"id": "prod_123", "name": "Test Product"}"#)); + + // Fast failure + self.add_scenario("invalid_endpoint", MockScenario::failure(50, "Invalid API key")); + + // Timeout scenario + self.add_scenario("slow_endpoint", MockScenario::timeout(5000)); + + // Variable responses for testing retries + self.add_scenario("flaky_endpoint", MockScenario::failure(500, "Temporary server error")); + } +} + +impl Default for MockAPI { + fn default() -> Self { + let mut api = Self::new(); + api.setup_test_scenarios(); + api + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn test_mock_api_success() { + let mut api = MockAPI::new(); + api.add_scenario("test", MockScenario::success(10, "success")); + + let result = api.call("test").await; + assert!(result.is_ok()); + assert_eq!(result.unwrap(), "success"); + } + + #[tokio::test] + async fn test_mock_api_failure() { + let mut api = MockAPI::new(); + api.add_scenario("test", MockScenario::failure(10, "error")); + + let result = api.call("test").await; + assert!(result.is_err()); + assert_eq!(result.unwrap_err(), "error"); + } + + #[tokio::test] + async fn test_mock_api_unknown_endpoint() { + let api = MockAPI::new(); + let result = api.call("unknown").await; + assert!(result.is_err()); + assert!(result.unwrap_err().contains("Unknown endpoint")); + } +} \ No newline at end of file diff --git a/rhailib/src/flow/src/state.rs b/rhailib/src/flow/src/state.rs new file mode 100644 index 0000000..57d1e41 --- /dev/null +++ b/rhailib/src/flow/src/state.rs @@ -0,0 +1,100 @@ +//! Simple state management for flows and steps + +use serde::{Serialize, Deserialize}; +use crate::types::{FlowStatus, StepStatus}; + +/// Minimal flow state tracking +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FlowState { + pub flow_id: String, + pub status: FlowStatus, + pub current_step: Option, + pub completed_steps: Vec, +} + +impl FlowState { + pub fn new(flow_id: String) -> Self { + Self { + flow_id, + status: FlowStatus::Created, + current_step: None, + completed_steps: Vec::new(), + } + } +} + +/// Minimal step state tracking +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct StepState { + pub step_id: String, + pub status: StepStatus, + pub attempt_count: u32, + pub output: Option, +} + +impl StepState { + pub fn new(step_id: String) -> Self { + Self { + step_id, + status: StepStatus::Pending, + attempt_count: 0, + output: None, + } + } +} + +/// Simple Redis-based state manager +pub struct StateManager { + redis_client: redis::Client, +} + +impl StateManager { + pub async fn new(redis_url: &str) -> Result> { + let client = redis::Client::open(redis_url)?; + Ok(Self { + redis_client: client, + }) + } + + /// Save flow state to Redis + pub async fn save_flow_state(&self, state: &FlowState) -> Result<(), Box> { + let mut conn = self.redis_client.get_async_connection().await?; + let key = format!("flow:{}", state.flow_id); + let json = serde_json::to_string(state)?; + redis::cmd("SET").arg(&key).arg(&json).query_async(&mut conn).await?; + Ok(()) + } + + /// Load flow state from Redis + pub async fn load_flow_state(&self, flow_id: &str) -> Result, Box> { + let mut conn = self.redis_client.get_async_connection().await?; + let key = format!("flow:{}", flow_id); + let result: Option = redis::cmd("GET").arg(&key).query_async(&mut conn).await?; + + match result { + Some(json) => Ok(Some(serde_json::from_str(&json)?)), + None => Ok(None), + } + } + + /// Save step state to Redis + pub async fn save_step_state(&self, flow_id: &str, state: &StepState) -> Result<(), Box> { + let mut conn = self.redis_client.get_async_connection().await?; + let key = format!("step:{}:{}", flow_id, state.step_id); + let json = serde_json::to_string(state)?; + redis::cmd("SET").arg(&key).arg(&json).query_async(&mut conn).await?; + Ok(()) + } + + /// Load step state from Redis + pub async fn load_step_state(&self, flow_id: &str, step_id: &str) -> Result, Box> { + let mut conn = self.redis_client.get_async_connection().await?; + let key = format!("step:{}:{}", flow_id, step_id); + let result: Option = redis::cmd("GET").arg(&key).query_async(&mut conn).await?; + + match result { + Some(json) => Ok(Some(serde_json::from_str(&json)?)), + None => Ok(None), + } + } +} \ No newline at end of file diff --git a/rhailib/src/flow/src/types.rs b/rhailib/src/flow/src/types.rs new file mode 100644 index 0000000..cd7bd39 --- /dev/null +++ b/rhailib/src/flow/src/types.rs @@ -0,0 +1,66 @@ +//! Core types for the flow manager + +use serde::{Serialize, Deserialize}; +use std::time::Duration; + +/// Simple flow status enumeration +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub enum FlowStatus { + Created, + Running, + Completed, + Failed, +} + +/// Simple step status enumeration +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub enum StepStatus { + Pending, + Running, + Completed, + Failed, +} + +/// A single step in a flow +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Step { + pub id: String, + pub name: String, + pub script: String, + pub timeout_seconds: u64, + pub max_retries: u32, +} + +impl Step { + pub fn new(name: &str) -> Self { + Self { + id: uuid::Uuid::new_v4().to_string(), + name: name.to_string(), + script: String::new(), + timeout_seconds: 30, // default 30 seconds + max_retries: 0, // default no retries + } + } + + pub fn timeout(&self) -> Duration { + Duration::from_secs(self.timeout_seconds) + } +} + +/// A flow containing multiple steps +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Flow { + pub id: String, + pub name: String, + pub steps: Vec, +} + +impl Flow { + pub fn new(name: &str) -> Self { + Self { + id: uuid::Uuid::new_v4().to_string(), + name: name.to_string(), + steps: Vec::new(), + } + } +} \ No newline at end of file diff --git a/rhailib/src/lib.rs b/rhailib/src/lib.rs new file mode 100644 index 0000000..3832452 --- /dev/null +++ b/rhailib/src/lib.rs @@ -0,0 +1,8 @@ +//! Rhailib - Distributed Rhai Scripting Library +//! +//! This library provides infrastructure for executing Rhai scripts in a distributed +//! manner using Redis as a message broker and task queue. + +// Re-export commonly used types +pub use redis; +pub use serde_json; diff --git a/rhailib/src/macros/Cargo.toml b/rhailib/src/macros/Cargo.toml new file mode 100644 index 0000000..94ce1b5 --- /dev/null +++ b/rhailib/src/macros/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "rhailib-macros" +version = "0.1.0" +edition = "2024" + +[dependencies] +rhai = { version = "1.21.0", features = ["std", "sync", "decimal", "internals"] } +serde = { version = "1.0", features = ["derive"] } diff --git a/rhailib/src/macros/_archive/lib.rs b/rhailib/src/macros/_archive/lib.rs new file mode 100644 index 0000000..9288fdd --- /dev/null +++ b/rhailib/src/macros/_archive/lib.rs @@ -0,0 +1,380 @@ +//! # Rhai Authorization Crate +//! This crate provides authorization mechanisms for Rhai functions, particularly those interacting with a database. +//! It includes helper functions for authorization checks and macros to simplify the registration +//! of authorized Rhai functions. +//! ## Features: +//! - `is_super_admin`: Checks if a caller (identified by a public key) is a super admin. +//! - `can_access_resource`: Checks if a caller has specific access rights to a resource, using a database connection. +//! - `get_caller_public_key`: Helper to extract `CALLER_ID` from the Rhai `NativeCallContext`. +//! - `id_from_i64_to_u32`: Helper to convert `i64` Rhai IDs to `u32` Rust IDs. +//! - `register_authorized_get_by_id_fn!`: Macro to register a Rhai function that retrieves a single item by ID, with authorization checks. +//! - `register_authorized_list_fn!`: Macro to register a Rhai function that lists multiple items, filtering them based on authorization. +//! ## Usage: +//! 1. Use the macros to register your Rhai functions, providing a database connection (`Arc`) and necessary type/name information. +//! 2. The macros internally use `can_access_resource` for authorization checks. +//! 3. Ensure `CALLER_ID` is set in the Rhai engine's scope before calling authorized functions. + +use rhai::{EvalAltResult, Position}; +use std::convert::TryFrom; + +/// Extracts the `CALLER_ID` string constant from the Rhai `NativeCallContext`. +/// This key is used to identify the caller for authorization checks. +/// It first checks the current `Scope` and then falls back to the global constants cache. +/// +/// # Arguments +/// * `context`: The Rhai `NativeCallContext` of the currently executing function. +/// + +/// Converts an `i64` (common Rhai integer type) to a `u32` (common Rust ID type). +/// +/// # Arguments +/// * `id_i64`: The `i64` value to convert. +/// +/// # Errors +/// Returns `Err(EvalAltResult::ErrorMismatchDataType)` if the `i64` value cannot be represented as a `u32`. +pub fn id_from_i64_to_u32(id_i64: i64) -> Result> { + u32::try_from(id_i64).map_err(|_| { + Box::new(EvalAltResult::ErrorMismatchDataType( + "u32".to_string(), + format!("i64 value ({}) that cannot be represented as u32", id_i64), + Position::NONE, + )) + }) +} + +/// Extracts the `CALLER_ID` string constant from the Rhai `NativeCallContext`'s tag. +/// This key is used to identify the caller for authorization checks. + +/// Macro to register a Rhai function that retrieves a single resource by its ID, with authorization. +/// +/// The macro handles: +/// - Argument parsing (ID). +/// - Caller identification via `CALLER_ID`. +/// - Authorization check using `AccessControlService::can_access_resource`. +/// - Database call to fetch the resource. +/// - Error handling for type mismatches, authorization failures, DB errors, and not found errors. +/// +/// # Arguments +/// * `module`: Mutable reference to the Rhai `Module`. +/// * `db_clone`: Cloned `Arc` for database access. +/// * `acs_clone`: Cloned `Arc`. +/// * `rhai_fn_name`: String literal for the Rhai function name (e.g., "get_collection"). +/// * `resource_type_str`: String literal for the resource type (e.g., "Collection"), used in authorization checks and error messages. +/// * `db_method_name`: Identifier for the database method to call (e.g., `get_by_id`). +/// * `id_arg_type`: Rust type of the ID argument in Rhai (e.g., `i64`). +/// * `id_rhai_type_name`: String literal for the Rhai type name of the ID (e.g., "i64"), for error messages. +/// * `id_conversion_fn`: Path to a function converting `id_arg_type` to `actual_id_type` (e.g., `id_from_i64_to_u32`). +/// * `actual_id_type`: Rust type of the ID used in the database (e.g., `u32`). +/// * `rhai_return_rust_type`: Rust type of the resource returned by the DB and Rhai function (e.g., `RhaiCollection`). +#[macro_export] +macro_rules! register_authorized_get_by_id_fn { + ( + module: $module:expr, + rhai_fn_name: $rhai_fn_name:expr, // String literal for the Rhai function name (e.g., "get_collection") + resource_type_str: $resource_type_str:expr, // String literal for the resource type (e.g., "Collection") + rhai_return_rust_type: $rhai_return_rust_type:ty // Rust type of the resource returned (e.g., `RhaiCollection`) + ) => { + FuncRegistration::new($rhai_fn_name).set_into_module( + $module, + move |context: rhai::NativeCallContext, + id_val: i64| + -> Result<$rhai_return_rust_type, Box> { + let actual_id: u32 = $crate::id_from_i64_to_u32(id_val)?; + + // Inlined logic to get caller public key + let tag_map = context + .tag() + .and_then(|tag| tag.read_lock::()) + .ok_or_else(|| { + Box::new(EvalAltResult::ErrorRuntime( + "Context tag must be a Map.".into(), + context.position(), + )) + })?; + + let pk_dynamic = tag_map.get("CALLER_ID").ok_or_else(|| { + Box::new(EvalAltResult::ErrorRuntime( + "'CALLER_ID' not found in context tag Map.".into(), + context.position(), + )) + })?; + + let db_path = tag_map.get("DB_PATH").ok_or_else(|| { + Box::new(EvalAltResult::ErrorRuntime( + "'DB_PATH' not found in context tag Map.".into(), + context.position(), + )) + })?; + + let db_path = db_path.clone().into_string()?; + + let circle_pk = tag_map.get("CONTEXT_ID").ok_or_else(|| { + Box::new(EvalAltResult::ErrorRuntime( + "'CONTEXT_ID' not found in context tag Map.".into(), + context.position(), + )) + })?; + + let circle_pk = circle_pk.clone().into_string()?; + + let db_path = format!("{}/{}", db_path, circle_pk); + let db = Arc::new(OurDB::new(db_path, false).expect("Failed to create DB")); + + let caller_pk_str = pk_dynamic.clone().into_string()?; + + println!("Checking access for public key: {}", caller_pk_str); + if circle_pk != caller_pk_str { + // Use the standalone can_access_resource function from heromodels + let has_access = heromodels::models::access::access::can_access_resource( + db.clone(), + &caller_pk_str, + actual_id, + $resource_type_str, + ); + + if !has_access { + return Err(Box::new(EvalAltResult::ErrorRuntime( + format!("Access denied for public key: {}", caller_pk_str).into(), + context.position(), + ))); + } + } + + let result = db + .collection::<$rhai_return_rust_type>() + .unwrap() + .get_by_id(actual_id) + .map_err(|e| { + println!( + "Database error fetching {} with ID: {}", + $resource_type_str, actual_id + ); + Box::new(EvalAltResult::ErrorRuntime( + format!("Database error fetching {}: {:?}", $resource_type_str, e) + .into(), + context.position(), + )) + })? + .ok_or_else(|| { + Box::new(EvalAltResult::ErrorRuntime( + format!( + "Database error fetching {} with ID: {}", + $resource_type_str, actual_id + ) + .into(), + context.position(), + )) + })?; + Ok(result) + }, + ); + }; +} + +// Macro to register a Rhai function that retrieves a single resource by its ID, with authorization. +#[macro_export] +macro_rules! register_authorized_create_by_id_fn { + ( + module: $module:expr, + rhai_fn_name: $rhai_fn_name:expr, // String literal for the Rhai function name (e.g., "get_collection") + resource_type_str: $resource_type_str:expr, // String literal for the resource type (e.g., "Collection") + rhai_return_rust_type: $rhai_return_rust_type:ty // Rust type of the resource returned (e.g., `RhaiCollection`) + ) => { + FuncRegistration::new($rhai_fn_name).set_into_module( + $module, + move |context: rhai::NativeCallContext, object: $rhai_return_rust_type| -> Result<$rhai_return_rust_type, Box> { + + // Inlined logic to get caller public key + let tag_map = context + .tag() + .and_then(|tag| tag.read_lock::()) + .ok_or_else(|| Box::new(EvalAltResult::ErrorRuntime("Context tag must be a Map.".into(), context.position())))?; + + let pk_dynamic = tag_map.get("CALLER_ID") + .ok_or_else(|| Box::new(EvalAltResult::ErrorRuntime("'CALLER_ID' not found in context tag Map.".into(), context.position())))?; + + let db_path = tag_map.get("DB_PATH") + .ok_or_else(|| Box::new(EvalAltResult::ErrorRuntime("'DB_PATH' not found in context tag Map.".into(), context.position())))?; + + let db_path = db_path.clone().into_string()?; + + let circle_pk = tag_map.get("CONTEXT_ID") + .ok_or_else(|| Box::new(EvalAltResult::ErrorRuntime("'CONTEXT_ID' not found in context tag Map.".into(), context.position())))?; + + let circle_pk = circle_pk.clone().into_string()?; + + let db_path = format!("{}/{}", db_path, circle_pk); + let db = Arc::new(OurDB::new(db_path, false).expect("Failed to create DB")); + + let caller_pk_str = pk_dynamic.clone().into_string()?; + + if circle_pk != caller_pk_str { + let is_circle_member = heromodels::models::access::access::is_circle_member( + db.clone(), + &caller_pk_str, + ); + if !is_circle_member { + // TODO: check if caller pk is member of circle + return Err(Box::new(EvalAltResult::ErrorRuntime( + format!("Insufficient authorization. Caller public key {} does not match circle public key {}", caller_pk_str, circle_pk).into(), + context.position(), + ))); + } + } + + let result = db.set(&object).map_err(|e| { + Box::new(EvalAltResult::ErrorRuntime( + format!("Database error creating {}: {:?}", $resource_type_str, e).into(), + context.position(), + )) + })?; + Ok(result.1) + }, + ); + }; +} + +// Macro to register a Rhai function that retrieves a single resource by its ID, with authorization. +#[macro_export] +macro_rules! register_authorized_delete_by_id_fn { + ( + module: $module:expr, + rhai_fn_name: $rhai_fn_name:expr, // String literal for the Rhai function name (e.g., "get_collection") + resource_type_str: $resource_type_str:expr, // String literal for the resource type (e.g., "Collection") + rhai_return_rust_type: $rhai_return_rust_type:ty // Rust type of the resource returned (e.g., `RhaiCollection`) + ) => { + FuncRegistration::new($rhai_fn_name).set_into_module( + $module, + move |context: rhai::NativeCallContext, id_val: i64| -> Result<(), Box> { + let actual_id: u32 = $crate::id_from_i64_to_u32(id_val)?; + + // Inlined logic to get caller public key + let tag_map = context + .tag() + .and_then(|tag| tag.read_lock::()) + .ok_or_else(|| Box::new(EvalAltResult::ErrorRuntime("Context tag must be a Map.".into(), context.position())))?; + + let pk_dynamic = tag_map.get("CALLER_ID") + .ok_or_else(|| Box::new(EvalAltResult::ErrorRuntime("'CALLER_ID' not found in context tag Map.".into(), context.position())))?; + + let db_path = tag_map.get("DB_PATH") + .ok_or_else(|| Box::new(EvalAltResult::ErrorRuntime("'DB_PATH' not found in context tag Map.".into(), context.position())))?; + + let db_path = db_path.clone().into_string()?; + + let circle_pk = tag_map.get("CONTEXT_ID") + .ok_or_else(|| Box::new(EvalAltResult::ErrorRuntime("'CONTEXT_ID' not found in context tag Map.".into(), context.position())))?; + + let circle_pk = circle_pk.clone().into_string()?; + + let db_path = format!("{}/{}", db_path, circle_pk); + let db = Arc::new(OurDB::new(db_path, false).expect("Failed to create DB")); + + let caller_pk_str = pk_dynamic.clone().into_string()?; + + if circle_pk != caller_pk_str { + let is_circle_member = heromodels::models::access::access::is_circle_member( + db.clone(), + &caller_pk_str, + ); + if !is_circle_member { + // TODO: check if caller pk is member of circle + return Err(Box::new(EvalAltResult::ErrorRuntime( + format!("Insufficient authorization. Caller public key {} does not match circle public key {}", caller_pk_str, circle_pk).into(), + context.position(), + ))); + } + } + + let result = db + .collection::<$rhai_return_rust_type>() + .unwrap() + .delete_by_id(actual_id) + .map_err(|e| { + Box::new(EvalAltResult::ErrorRuntime( + format!("Database error deleting {}: {:?}", $resource_type_str, e).into(), + context.position(), + )) + })?; + Ok(()) + }, + ); + }; +} + +/// Macro to register a Rhai function that lists all resources of a certain type, with authorization. +/// +/// The macro handles: +/// - Caller identification via `CALLER_ID`. +/// - Fetching all items of a specific type from the database. +/// - Filtering the items based on the standalone `can_access_resource` function for each item. +/// - Wrapping the authorized items in a specified collection type (e.g., `RhaiCollectionArray`). +/// - Error handling for DB errors during fetch or authorization checks. +/// +/// # Arguments +/// * `module`: Mutable reference to the Rhai `Module`. +/// * `rhai_fn_name`: String literal for the Rhai function name (e.g., "list_collections"). +/// * `resource_type_str`: String literal for the resource type (e.g., "Collection"), used in authorization checks. +/// * `rhai_return_rust_type`: Rust type of the resource item (e.g., `RhaiCollection`). +/// * `item_id_accessor`: Identifier for the method on `rhai_return_rust_type` that returns its ID (e.g., `id`). +/// * `rhai_return_wrapper_type`: Rust type that wraps a `Vec` of `rhai_return_rust_type` for Rhai (e.g., `RhaiCollectionArray`). +#[macro_export] +macro_rules! register_authorized_list_fn { + ( + module: $module:expr, + rhai_fn_name: $rhai_fn_name:expr, + resource_type_str: $resource_type_str:expr, + rhai_return_rust_type: $rhai_return_rust_type:ty, + rhai_return_wrapper_type: $rhai_return_wrapper_type:ty + ) => { + FuncRegistration::new($rhai_fn_name).set_into_module( + $module, + move |context: rhai::NativeCallContext| -> Result<$rhai_return_wrapper_type, Box> { + // Inlined logic to get caller public key + let tag_map = context + .tag() + .and_then(|tag| tag.read_lock::()) + .ok_or_else(|| Box::new(EvalAltResult::ErrorRuntime("Context tag must be a Map.".into(), context.position())))?; + + let pk_dynamic = tag_map.get("CALLER_ID") + .ok_or_else(|| Box::new(EvalAltResult::ErrorRuntime("'CALLER_ID' not found in context tag Map.".into(), context.position())))?; + + let caller_pk_str = pk_dynamic.clone().into_string()?; + + let db_path = tag_map.get("DB_PATH") + .ok_or_else(|| Box::new(EvalAltResult::ErrorRuntime("'DB_PATH' not found in context tag Map.".into(), context.position())))?; + + let db_path = db_path.clone().into_string()?; + + let circle_pk = tag_map.get("CONTEXT_ID") + .ok_or_else(|| Box::new(EvalAltResult::ErrorRuntime("'CONTEXT_ID' not found in context tag Map.".into(), context.position())))?; + + let circle_pk = circle_pk.clone().into_string()?; + + let db_path = format!("{}/{}", db_path, circle_pk); + let db = Arc::new(OurDB::new(db_path, false).expect("Failed to create DB")); + + let all_items: Vec<$rhai_return_rust_type> = db + .collection::<$rhai_return_rust_type>() + .map_err(|e| Box::new(EvalAltResult::ErrorRuntime(format!("{:?}", e).into(), Position::NONE)))? + .get_all() + .map_err(|e| Box::new(EvalAltResult::ErrorRuntime(format!("{:?}", e).into(), Position::NONE)))?; + + let authorized_items: Vec<$rhai_return_rust_type> = all_items + .into_iter() + .filter(|item| { + let resource_id = item.id(); + heromodels::models::access::access::can_access_resource( + db.clone(), + &caller_pk_str, + resource_id, + $resource_type_str, + ) + }) + .collect(); + + Ok(authorized_items.into()) + }, + ); + }; +} diff --git a/rhailib/src/macros/docs/ARCHITECTURE.md b/rhailib/src/macros/docs/ARCHITECTURE.md new file mode 100644 index 0000000..35fa1ad --- /dev/null +++ b/rhailib/src/macros/docs/ARCHITECTURE.md @@ -0,0 +1,303 @@ +# Architecture of the `macros` Crate + +The `macros` crate provides authorization mechanisms and procedural macros for Rhai functions that interact with databases. It implements a comprehensive security layer that ensures proper access control for all database operations within the Rhai scripting environment. + +## Core Architecture + +The crate follows a macro-driven approach to authorization, providing declarative macros that generate secure database access functions: + +```mermaid +graph TD + A[macros Crate] --> B[Authorization Functions] + A --> C[Utility Functions] + A --> D[Registration Macros] + + B --> B1[Context Extraction] + B --> B2[Access Control Checks] + B --> B3[Circle Membership Validation] + + C --> C1[ID Conversion] + C --> C2[Error Handling] + + D --> D1[register_authorized_get_by_id_fn!] + D --> D2[register_authorized_create_by_id_fn!] + D --> D3[register_authorized_delete_by_id_fn!] + D --> D4[register_authorized_list_fn!] + + D1 --> E[Generated Rhai Functions] + D2 --> E + D3 --> E + D4 --> E + + E --> F[Database Operations] + F --> G[Secure Data Access] +``` + +## Security Model + +### Authentication Context + +All operations require authentication context passed through Rhai's `NativeCallContext`: + +- **`CALLER_ID`**: Identifies the requesting user +- **`CONTEXT_ID`**: Identifies the target context (the circle) +- **`DB_PATH`**: Specifies the database location + +### Authorization Levels + +1. **Owner Access**: Direct access when `CALLER_ID == CONTEXT_ID` +2. **Circle Member Access**: Verified through `is_circle_member()` function +3. **Resource-Specific Access**: Granular permissions via `can_access_resource()` + +### Access Control Flow + +```mermaid +sequenceDiagram + participant Script as Rhai Script + participant Macro as Generated Function + participant Auth as Authorization Layer + participant DB as Database + + Script->>Macro: Call authorized function + Macro->>Auth: Extract caller context + Auth->>Auth: Validate CALLER_ID + Auth->>Auth: Check circle membership + Auth->>Auth: Verify resource access + Auth->>DB: Execute database operation + DB->>Macro: Return result + Macro->>Script: Return authorized data +``` + +## Core Components + +### 1. Utility Functions + +#### ID Conversion (`id_from_i64_to_u32`) +```rust +pub fn id_from_i64_to_u32(id_i64: i64) -> Result> +``` +Safely converts Rhai's `i64` integers to Rust's `u32` IDs with proper error handling. + +### 2. Authorization Macros + +#### Get By ID (`register_authorized_get_by_id_fn!`) +Generates functions for retrieving single resources by ID with authorization checks. + +**Features:** +- ID validation and conversion +- Caller authentication +- Resource-specific access control +- Database error handling +- Not found error handling + +#### Create Resource (`register_authorized_create_by_id_fn!`) +Generates functions for creating new resources with authorization. + +**Features:** +- Circle membership validation +- Object persistence +- Creation authorization +- Database transaction handling + +#### Delete By ID (`register_authorized_delete_by_id_fn!`) +Generates functions for deleting resources by ID with authorization. + +**Features:** +- Deletion authorization +- Circle membership validation +- Cascade deletion handling +- Audit trail support + +#### List Resources (`register_authorized_list_fn!`) +Generates functions for listing resources with filtering based on access rights. + +**Features:** +- Bulk authorization checking +- Result filtering +- Collection wrapping +- Performance optimization + +## Generated Function Architecture + +### Function Signature Pattern + +All generated functions follow a consistent pattern: + +```rust +move |context: rhai::NativeCallContext, /* parameters */| -> Result> +``` + +### Context Extraction Pattern + +```rust +let tag_map = context + .tag() + .and_then(|tag| tag.read_lock::()) + .ok_or_else(|| /* error */)?; + +let caller_pk = tag_map.get("CALLER_ID")?.into_string()?; +let context_id = tag_map.get("CONTEXT_ID")?.into_string()?; +let db_path = tag_map.get("DB_PATH")?.into_string()?; +``` + +### Database Connection Pattern + +```rust +let db_path = format!("{}/{}", db_path, context_id); +let db = Arc::new(OurDB::new(db_path, false).expect("Failed to create DB")); +``` + +## Authorization Strategies + +### 1. Circle-Based Authorization + +```rust +if context_id != caller_pk_str { + let is_circle_member = heromodels::models::access::access::is_circle_member( + db.clone(), + &caller_pk_str, + ); + if !is_circle_member { + return Err(/* authorization error */); + } +} +``` + +### 2. Resource-Specific Authorization + +```rust +let has_access = heromodels::models::access::access::can_access_resource( + db.clone(), + &caller_pk_str, + actual_id, + resource_type_str, +); + +if !has_access { + return Err(/* access denied error */); +} +``` + +### 3. Bulk Authorization (for lists) + +```rust +let authorized_items: Vec = all_items + .into_iter() + .filter(|item| { + let resource_id = item.id(); + heromodels::models::access::access::can_access_resource( + db.clone(), + &caller_pk_str, + resource_id, + resource_type_str, + ) + }) + .collect(); +``` + +## Error Handling Architecture + +### Error Categories + +1. **Context Errors**: Missing or invalid authentication context +2. **Type Conversion Errors**: Invalid ID formats or type mismatches +3. **Authorization Errors**: Access denied or insufficient permissions +4. **Database Errors**: Connection failures or query errors +5. **Not Found Errors**: Requested resources don't exist + +### Error Propagation Pattern + +```rust +.map_err(|e| { + Box::new(EvalAltResult::ErrorRuntime( + format!("Database error: {:?}", e).into(), + context.position(), + )) +})? +``` + +## Performance Considerations + +### Database Connection Management + +- **Connection Per Operation**: Each function creates its own database connection +- **Path-Based Isolation**: Database paths include circle identifiers for isolation +- **Connection Pooling**: Relies on underlying database implementation + +### Authorization Caching + +- **No Caching**: Authorization checks are performed for each operation +- **Stateless Design**: No session state maintained between calls +- **Fresh Validation**: Ensures up-to-date permission checking + +### Bulk Operations Optimization + +- **Filtered Iteration**: List operations filter results after database fetch +- **Lazy Evaluation**: Authorization checks only performed on accessed items +- **Memory Efficiency**: Results collected into appropriate wrapper types + +## Integration Patterns + +### Macro Usage in DSL Modules + +```rust +register_authorized_get_by_id_fn!( + module: &mut module, + rhai_fn_name: "get_company", + resource_type_str: "Company", + rhai_return_rust_type: heromodels::models::biz::company::Company +); +``` + +### Context Setup in Engine + +```rust +let mut context_map = rhai::Map::new(); +context_map.insert("CALLER_ID".into(), caller_pk.into()); +context_map.insert("CONTEXT_ID".into(), context_id.into()); +context_map.insert("DB_PATH".into(), db_path.into()); +engine.set_tag(context_map); +``` + +## Security Considerations + +### Authentication Requirements + +- **Mandatory Context**: All operations require valid authentication context +- **Public Key Validation**: Caller identity verified through cryptographic keys +- **Circle Membership**: Hierarchical access control through circle membership + +### Authorization Granularity + +- **Resource-Level**: Individual resource access control +- **Operation-Level**: Different permissions for read/write/delete operations +- **Circle-Level**: Organization-based access boundaries + +### Audit and Logging + +- **Operation Logging**: All database operations include caller identification +- **Access Logging**: Authorization decisions are logged for audit trails +- **Error Logging**: Failed authorization attempts are recorded + +## Extensibility + +### Adding New Operations + +1. Create new macro following existing patterns +2. Implement authorization logic specific to operation +3. Add error handling for operation-specific failures +4. Register with DSL modules using macro + +### Custom Authorization Logic + +```rust +// Custom authorization can be added within macro implementations +if requires_special_permission { + let has_special_access = check_special_permission(db.clone(), &caller_pk_str); + if !has_special_access { + return Err(/* custom error */); + } +} +``` + +This architecture provides a robust, secure foundation for database operations within the Rhai scripting environment while maintaining flexibility for future extensions and customizations. \ No newline at end of file diff --git a/rhailib/src/macros/examples/access_control.rs b/rhailib/src/macros/examples/access_control.rs new file mode 100644 index 0000000..d7af50a --- /dev/null +++ b/rhailib/src/macros/examples/access_control.rs @@ -0,0 +1,208 @@ +use macros::{register_authorized_get_by_id_fn, register_authorized_list_fn}; +use rhai::{Dynamic, Engine, Module, Position, Scope}; +use std::sync::Arc; + +// Import DB traits with an alias for the Collection trait to avoid naming conflicts. +// Import DB traits from heromodels::db as suggested by compiler errors. +use heromodels::db::{Collection as DbCollection, Db}; +use heromodels::{ + db::hero::OurDB, + models::access::access::Access, + models::library::collection::Collection, // Actual data model for single items + models::library::rhai::RhaiCollectionArray, // Wrapper for arrays of collections +}; + +use rhai::{EvalAltResult, FuncRegistration}; // For macro expansion + +// Rewritten to match the new `Access` model structure. +fn grant_access(db: &Arc, user_pk: &str, resource_type: &str, resource_id: u32) { + let access_record = Access::new() + .circle_pk(user_pk.to_string()) + .object_type(resource_type.to_string()) + .object_id(resource_id) + .contact_id(0) + .group_id(0); + + db.set(&access_record).expect("Failed to set access record"); +} + +// No changes needed here, but it relies on the new imports to compile. +fn register_example_module(engine: &mut Engine, db: Arc) { + let mut module = Module::new(); + + register_authorized_get_by_id_fn!( + module: &mut module, + rhai_fn_name: "get_collection", + resource_type_str: "Collection", + rhai_return_rust_type: heromodels::models::library::collection::Collection // Use Collection struct + ); + + register_authorized_list_fn!( + module: &mut module, + db_clone: db.clone(), + rhai_fn_name: "list_all_collections", + resource_type_str: "Collection", + rhai_return_rust_type: heromodels::models::library::collection::Collection, // Use Collection struct + item_id_accessor: id, // Assumes Collection has an id() method that returns u32 + rhai_return_wrapper_type: heromodels::models::library::rhai::RhaiCollectionArray // Wrapper type for Rhai + ); + + engine.register_global_module(module.into()); +} + +fn create_alice_engine(db_dir: &str, alice_pk: &str) -> Engine { + let mut engine = Engine::new(); + + let db_path = format!("{}/{}", db_dir, alice_pk); + let db = Arc::new(OurDB::new(&db_path, false).expect("Failed to create DB")); + + // Populate DB using the new `create_collection` helper. + // Ownership is no longer on the collection itself, so we don't need owner_pk here. + let coll = Collection::new() + .title("My new collection") + .description("This is a new collection"); + + db.set(&coll).expect("Failed to set collection"); + + let coll1 = Collection::new() + .title("Alice's Private Collection") + .description("This is Alice's private collection"); + let coll3 = Collection::new() + .title("General Collection") + .description("This is a general collection"); + + db.set(&coll1).expect("Failed to set collection"); + db.set(&coll3).expect("Failed to set collection"); + + // Grant access based on the new model. + grant_access(&db, "alice_pk", "Collection", coll1.id()); + grant_access(&db, "user_pk", "Collection", coll3.id()); + + register_example_module(&mut engine, db.clone()); + let mut db_config = rhai::Map::new(); + db_config.insert("DB_PATH".into(), db_dir.clone().into()); + db_config.insert("CONTEXT_ID".into(), "alice_pk".into()); + engine.set_default_tag(Dynamic::from(db_config)); + engine +} + +fn create_bob_engine(db_dir: &str, bob_pk: &str) -> Engine { + let mut engine = Engine::new(); + + let db_path = format!("{}/{}", db_dir, bob_pk); + let db = Arc::new(OurDB::new(db_path, false).expect("Failed to create DB")); + + let coll2 = Collection::new() + .title("Bob's Shared Collection") + .description("This is Bob's shared collection Alice has access."); + + db.set(&coll2).expect("Failed to set collection"); + grant_access(&db, "alice_pk", "Collection", coll2.id()); + + register_example_module(&mut engine, db.clone()); + let mut db_config = rhai::Map::new(); + db_config.insert("DB_PATH".into(), db_dir.clone().into()); + db_config.insert("CONTEXT_ID".into(), "bob_pk".into()); + engine.set_default_tag(Dynamic::from(db_config)); + engine +} + +fn create_user_engine(db_dir: &str, user_pk: &str) -> Engine { + let mut engine = Engine::new(); + + let db_path = format!("{}/{}", db_dir, user_pk); + let db = Arc::new(OurDB::new(db_path, false).expect("Failed to create DB")); + register_example_module(&mut engine, db.clone()); + let mut db_config = rhai::Map::new(); + db_config.insert("DB_PATH".into(), db_dir.clone().into()); + db_config.insert("CONTEXT_ID".into(), "user_pk".into()); + engine.set_default_tag(Dynamic::from(db_config)); + engine +} + +fn main() -> Result<(), Box> { + let db_path = format!("{}/hero/db", std::env::var("HOME").unwrap()); + let alice_pk = "alice_pk"; + let bob_pk = "bob_pk"; + let user_pk = "user_pk"; + + let mut engine_alice = create_alice_engine(&db_path, alice_pk); + let mut engine_bob = create_bob_engine(&db_path, bob_pk); + let mut engine_user = create_user_engine(&db_path, user_pk); + + println!("--------------------------"); + println!("--- Rhai Authorization Example ---"); + + let mut scope = Scope::new(); + + // Create a Dynamic value holding your DB path or a config object + { + let mut tag_dynamic = engine_alice.default_tag_mut().as_map_mut().unwrap(); + tag_dynamic.insert("CALLER_ID".into(), "alice_pk".into()); + } + // engine_alice.set_default_tag(Dynamic::from(tag_dynamic.clone())); + + println!("Alice accessing her collection 1: Success, title"); // Access field directly + let result = engine_alice.eval::>("get_collection(1)")?; + let result_clone = result + .clone() + .expect("Failed to retrieve collection. It might not exist or you may not have access."); + println!( + "Alice accessing her collection 1: Success, title = {}", + result_clone.title + ); // Access field directly + assert_eq!(result_clone.id(), 1); + + // Scenario 2: Bob tries to access Alice's collection (Failure) + { + let mut tag_dynamic = engine_bob.default_tag_mut().as_map_mut().unwrap(); + tag_dynamic.insert("CALLER_ID".into(), "bob_pk".into()); + } + let result = + engine_alice.eval_with_scope::>(&mut scope, "get_collection(1)")?; + println!( + "Bob accessing Alice's collection 1: Failure as expected ({:?})", + result + ); + assert!(result.is_none()); + + // Scenario 3: Alice accesses Bob's collection (Success) + let mut db_config = rhai::Map::new(); + db_config.insert("CALLER_ID".into(), "alice_pk".into()); + engine_bob.set_default_tag(Dynamic::from(db_config)); + let result: Option = + engine_bob.eval_with_scope::>(&mut scope, "get_collection(2)")?; + let collection = result.expect("Alice should have access to Bob's collection"); + println!( + "Alice accessing Bob's collection 2: Success, title = {}", + collection.title + ); // Access field directly + assert_eq!(collection.id(), 2); + + // Scenario 4: General user lists collections (Sees 1) + let mut db_config = rhai::Map::new(); + db_config.insert("db_path".into(), "actual/path/to/db.sqlite".into()); + db_config.insert("CALLER_ID".into(), "general_user_pk".into()); + engine_user.set_default_tag(Dynamic::from(db_config)); + let result = engine_user + .eval_with_scope::(&mut scope, "list_all_collections()") + .unwrap(); + println!("General user listing collections: Found {}", result.0.len()); + assert_eq!(result.0.len(), 1); + assert_eq!(result.0[0].id(), 3); + + // Scenario 5: Alice lists collections (Sees 2) + let mut db_config = rhai::Map::new(); + db_config.insert("db_path".into(), "actual/path/to/db.sqlite".into()); + db_config.insert("CALLER_ID".into(), "alice_pk".into()); + engine_alice.set_default_tag(Dynamic::from(db_config)); + let collections = engine_alice + .eval_with_scope::(&mut scope, "list_all_collections()") + .unwrap(); + println!("Alice listing collections: Found {}", collections.0.len()); + assert_eq!(collections.0.len(), 2); + let ids: Vec = collections.0.iter().map(|c| c.id()).collect(); + assert!(ids.contains(&1) && ids.contains(&2)); + + Ok(()) +} diff --git a/rhailib/src/macros/src/lib.rs b/rhailib/src/macros/src/lib.rs new file mode 100644 index 0000000..10c0e29 --- /dev/null +++ b/rhailib/src/macros/src/lib.rs @@ -0,0 +1,352 @@ +//! # Rhai Authorization Crate +//! This crate provides authorization mechanisms for Rhai functions, particularly those interacting with a database. +//! It includes helper functions for authorization checks and macros to simplify the registration +//! of authorized Rhai functions. +//! ## Features: +//! - `is_super_admin`: Checks if a caller (identified by a public key) is a super admin. +//! - `can_access_resource`: Checks if a caller has specific access rights to a resource, using a database connection. +//! - `get_caller_public_key`: Helper to extract `CALLER_ID` from the Rhai `NativeCallContext`. +//! - `id_from_i64_to_u32`: Helper to convert `i64` Rhai IDs to `u32` Rust IDs. +//! - `register_authorized_get_by_id_fn!`: Macro to register a Rhai function that retrieves a single item by ID, with authorization checks. +//! - `register_authorized_list_fn!`: Macro to register a Rhai function that lists multiple items, filtering them based on authorization. +//! ## Usage: +//! 1. Use the macros to register your Rhai functions, providing a database connection (`Arc`) and necessary type/name information. +//! 2. The macros internally use `can_access_resource` for authorization checks. +//! 3. Ensure `CALLER_ID` is set in the Rhai engine's scope before calling authorized functions. + +use rhai::{EvalAltResult, Position}; +use std::convert::TryFrom; + +/// Extracts the `CALLER_ID` string constant from the Rhai `NativeCallContext`. +/// This key is used to identify the caller for authorization checks. +/// It first checks the current `Scope` and then falls back to the global constants cache. +/// +/// # Arguments +/// * `context`: The Rhai `NativeCallContext` of the currently executing function. +/// + +/// Converts an `i64` (common Rhai integer type) to a `u32` (common Rust ID type). +/// +/// # Arguments +/// * `id_i64`: The `i64` value to convert. +/// +/// # Errors +/// Returns `Err(EvalAltResult::ErrorMismatchDataType)` if the `i64` value cannot be represented as a `u32`. +pub fn id_from_i64_to_u32(id_i64: i64) -> Result> { + u32::try_from(id_i64).map_err(|_| { + Box::new(EvalAltResult::ErrorMismatchDataType( + "u32".to_string(), + format!("i64 value ({}) that cannot be represented as u32", id_i64), + Position::NONE, + )) + }) +} + +/// Extracts the `CALLER_ID` string constant from the Rhai `NativeCallContext`'s tag. +/// This key is used to identify the caller for authorization checks. + +/// Macro to register a Rhai function that retrieves a single resource by its ID, with authorization. +/// +/// The macro handles: +/// - Argument parsing (ID). +/// - Caller identification via `CALLER_ID`. +/// - Authorization check using `AccessControlService::can_access_resource`. +/// - Database call to fetch the resource. +/// - Error handling for type mismatches, authorization failures, DB errors, and not found errors. +/// +/// # Arguments +/// * `module`: Mutable reference to the Rhai `Module`. +/// * `db_clone`: Cloned `Arc` for database access. +/// * `acs_clone`: Cloned `Arc`. +/// * `rhai_fn_name`: String literal for the Rhai function name (e.g., "get_collection"). +/// * `resource_type_str`: String literal for the resource type (e.g., "Collection"), used in authorization checks and error messages. +/// * `db_method_name`: Identifier for the database method to call (e.g., `get_by_id`). +/// * `id_arg_type`: Rust type of the ID argument in Rhai (e.g., `i64`). +/// * `id_rhai_type_name`: String literal for the Rhai type name of the ID (e.g., "i64"), for error messages. +/// * `id_conversion_fn`: Path to a function converting `id_arg_type` to `actual_id_type` (e.g., `id_from_i64_to_u32`). +/// * `actual_id_type`: Rust type of the ID used in the database (e.g., `u32`). +/// * `rhai_return_rust_type`: Rust type of the resource returned by the DB and Rhai function (e.g., `RhaiCollection`). +#[macro_export] +macro_rules! register_authorized_get_by_id_fn { + ( + module: $module:expr, + rhai_fn_name: $rhai_fn_name:expr, // String literal for the Rhai function name (e.g., "get_collection") + resource_type_str: $resource_type_str:expr, // String literal for the resource type (e.g., "Collection") + rhai_return_rust_type: $rhai_return_rust_type:ty // Rust type of the resource returned (e.g., `RhaiCollection`) + ) => { + FuncRegistration::new($rhai_fn_name).set_into_module( + $module, + move |context: rhai::NativeCallContext, + id_val: i64| + -> Result<$rhai_return_rust_type, Box> { + let actual_id: u32 = $crate::id_from_i64_to_u32(id_val)?; + + // Inlined logic to get caller public key + let tag_map = context + .tag() + .and_then(|tag| tag.read_lock::()) + .ok_or_else(|| { + Box::new(EvalAltResult::ErrorRuntime( + "Context tag must be a Map.".into(), + context.position(), + )) + })?; + + let pk_dynamic = tag_map.get("CALLER_ID").ok_or_else(|| { + Box::new(EvalAltResult::ErrorRuntime( + "'CALLER_ID' not found in context tag Map.".into(), + context.position(), + )) + })?; + + let db_path = tag_map.get("DB_PATH").ok_or_else(|| { + Box::new(EvalAltResult::ErrorRuntime( + "'DB_PATH' not found in context tag Map.".into(), + context.position(), + )) + })?; + + let db_path = db_path.clone().into_string()?; + + let circle_pk = tag_map.get("CONTEXT_ID").ok_or_else(|| { + Box::new(EvalAltResult::ErrorRuntime( + "'CONTEXT_ID' not found in context tag Map.".into(), + context.position(), + )) + })?; + + let circle_pk = circle_pk.clone().into_string()?; + + let db_path = format!("{}/{}", db_path, circle_pk); + let db = Arc::new(OurDB::new(db_path, false).expect("Failed to create DB")); + + let caller_pk_str = pk_dynamic.clone().into_string()?; + + println!("Checking access for public key: {}", caller_pk_str); + if circle_pk != caller_pk_str { + // Use the standalone can_access_resource function from heromodels + let has_access = crate::models::access::access::can_access_resource( + db.clone(), + &caller_pk_str, + actual_id, + $resource_type_str, + ); + + if !has_access { + return Err(Box::new(EvalAltResult::ErrorRuntime( + format!("Access denied for public key: {}", caller_pk_str).into(), + context.position(), + ))); + } + } + + let result = db + .collection::<$rhai_return_rust_type>() + .unwrap() + .get_by_id(actual_id) + .map_err(|e| { + println!( + "Database error fetching {} with ID: {}", + $resource_type_str, actual_id + ); + Box::new(EvalAltResult::ErrorRuntime( + format!("Database error fetching {}: {:?}", $resource_type_str, e) + .into(), + context.position(), + )) + })? + .ok_or_else(|| { + Box::new(EvalAltResult::ErrorRuntime( + format!( + "Database error fetching {} with ID: {}", + $resource_type_str, actual_id + ) + .into(), + context.position(), + )) + })?; + Ok(result) + }, + ); + }; +} + +// Macro to register a Rhai function that retrieves a single resource by its ID, with authorization. +#[macro_export] +macro_rules! register_authorized_create_by_id_fn { + ( + module: $module:expr, + rhai_fn_name: $rhai_fn_name:expr, // String literal for the Rhai function name (e.g., "get_collection") + resource_type_str: $resource_type_str:expr, // String literal for the resource type (e.g., "Collection") + rhai_return_rust_type: $rhai_return_rust_type:ty // Rust type of the resource returned (e.g., `RhaiCollection`) + ) => { + FuncRegistration::new($rhai_fn_name).set_into_module( + $module, + move |context: rhai::NativeCallContext, object: $rhai_return_rust_type| -> Result<$rhai_return_rust_type, Box> { + + // Inlined logic to get caller public key + let tag_map = context + .tag() + .and_then(|tag| tag.read_lock::()) + .ok_or_else(|| Box::new(EvalAltResult::ErrorRuntime("Context tag must be a Map.".into(), context.position())))?; + + let pk_dynamic = tag_map.get("CALLER_ID") + .ok_or_else(|| Box::new(EvalAltResult::ErrorRuntime("'CALLER_ID' not found in context tag Map.".into(), context.position())))?; + + let db_path = tag_map.get("DB_PATH") + .ok_or_else(|| Box::new(EvalAltResult::ErrorRuntime("'DB_PATH' not found in context tag Map.".into(), context.position())))?; + + let db_path = db_path.clone().into_string()?; + + let circle_pk = tag_map.get("CONTEXT_ID") + .ok_or_else(|| Box::new(EvalAltResult::ErrorRuntime("'CONTEXT_ID' not found in context tag Map.".into(), context.position())))?; + + let circle_pk = circle_pk.clone().into_string()?; + + let db_path = format!("{}/{}", db_path, circle_pk); + let db = Arc::new(OurDB::new(db_path, false).expect("Failed to create DB")); + + let caller_pk_str = pk_dynamic.clone().into_string()?; + + let result = db.set(&object).map_err(|e| { + Box::new(EvalAltResult::ErrorRuntime( + format!("Database error creating {}: {:?}", $resource_type_str, e).into(), + context.position(), + )) + })?; + Ok(result.1) + }, + ); + }; +} + +// Macro to register a Rhai function that retrieves a single resource by its ID, with authorization. +#[macro_export] +macro_rules! register_authorized_delete_by_id_fn { + ( + module: $module:expr, + rhai_fn_name: $rhai_fn_name:expr, // String literal for the Rhai function name (e.g., "get_collection") + resource_type_str: $resource_type_str:expr, // String literal for the resource type (e.g., "Collection") + rhai_return_rust_type: $rhai_return_rust_type:ty // Rust type of the resource returned (e.g., `RhaiCollection`) + ) => { + FuncRegistration::new($rhai_fn_name).set_into_module( + $module, + move |context: rhai::NativeCallContext, id_val: i64| -> Result<(), Box> { + let actual_id: u32 = $crate::id_from_i64_to_u32(id_val)?; + + // Inlined logic to get caller public key + let tag_map = context + .tag() + .and_then(|tag| tag.read_lock::()) + .ok_or_else(|| Box::new(EvalAltResult::ErrorRuntime("Context tag must be a Map.".into(), context.position())))?; + + let pk_dynamic = tag_map.get("CALLER_ID") + .ok_or_else(|| Box::new(EvalAltResult::ErrorRuntime("'CALLER_ID' not found in context tag Map.".into(), context.position())))?; + + let db_path = tag_map.get("DB_PATH") + .ok_or_else(|| Box::new(EvalAltResult::ErrorRuntime("'DB_PATH' not found in context tag Map.".into(), context.position())))?; + + let db_path = db_path.clone().into_string()?; + + let circle_pk = tag_map.get("CONTEXT_ID") + .ok_or_else(|| Box::new(EvalAltResult::ErrorRuntime("'CONTEXT_ID' not found in context tag Map.".into(), context.position())))?; + + let circle_pk = circle_pk.clone().into_string()?; + + let db_path = format!("{}/{}", db_path, circle_pk); + let db = Arc::new(OurDB::new(db_path, false).expect("Failed to create DB")); + + let caller_pk_str = pk_dynamic.clone().into_string()?; + + let result = db + .collection::<$rhai_return_rust_type>() + .unwrap() + .delete_by_id(actual_id) + .map_err(|e| { + Box::new(EvalAltResult::ErrorRuntime( + format!("Database error deleting {}: {:?}", $resource_type_str, e).into(), + context.position(), + )) + })?; + Ok(()) + }, + ); + }; +} + +/// Macro to register a Rhai function that lists all resources of a certain type, with authorization. +/// +/// The macro handles: +/// - Caller identification via `CALLER_ID`. +/// - Fetching all items of a specific type from the database. +/// - Filtering the items based on the standalone `can_access_resource` function for each item. +/// - Wrapping the authorized items in a specified collection type (e.g., `RhaiCollectionArray`). +/// - Error handling for DB errors during fetch or authorization checks. +/// +/// # Arguments +/// * `module`: Mutable reference to the Rhai `Module`. +/// * `rhai_fn_name`: String literal for the Rhai function name (e.g., "list_collections"). +/// * `resource_type_str`: String literal for the resource type (e.g., "Collection"), used in authorization checks. +/// * `rhai_return_rust_type`: Rust type of the resource item (e.g., `RhaiCollection`). +/// * `item_id_accessor`: Identifier for the method on `rhai_return_rust_type` that returns its ID (e.g., `id`). +/// * `rhai_return_wrapper_type`: Rust type that wraps a `Vec` of `rhai_return_rust_type` for Rhai (e.g., `RhaiCollectionArray`). +#[macro_export] +macro_rules! register_authorized_list_fn { + ( + module: $module:expr, + rhai_fn_name: $rhai_fn_name:expr, + resource_type_str: $resource_type_str:expr, + rhai_return_rust_type: $rhai_return_rust_type:ty, + rhai_return_wrapper_type: $rhai_return_wrapper_type:ty + ) => { + FuncRegistration::new($rhai_fn_name).set_into_module( + $module, + move |context: rhai::NativeCallContext| -> Result<$rhai_return_wrapper_type, Box> { + // Inlined logic to get caller public key + let tag_map = context + .tag() + .and_then(|tag| tag.read_lock::()) + .ok_or_else(|| Box::new(EvalAltResult::ErrorRuntime("Context tag must be a Map.".into(), context.position())))?; + + let pk_dynamic = tag_map.get("CALLER_ID") + .ok_or_else(|| Box::new(EvalAltResult::ErrorRuntime("'CALLER_ID' not found in context tag Map.".into(), context.position())))?; + + let caller_pk_str = pk_dynamic.clone().into_string()?; + + let db_path = tag_map.get("DB_PATH") + .ok_or_else(|| Box::new(EvalAltResult::ErrorRuntime("'DB_PATH' not found in context tag Map.".into(), context.position())))?; + + let db_path = db_path.clone().into_string()?; + + let circle_pk = tag_map.get("CONTEXT_ID") + .ok_or_else(|| Box::new(EvalAltResult::ErrorRuntime("'CONTEXT_ID' not found in context tag Map.".into(), context.position())))?; + + let circle_pk = circle_pk.clone().into_string()?; + + let db_path = format!("{}/{}", db_path, circle_pk); + let db = Arc::new(OurDB::new(db_path, false).expect("Failed to create DB")); + + let all_items: Vec<$rhai_return_rust_type> = db + .collection::<$rhai_return_rust_type>() + .map_err(|e| Box::new(EvalAltResult::ErrorRuntime(format!("{:?}", e).into(), Position::NONE)))? + .get_all() + .map_err(|e| Box::new(EvalAltResult::ErrorRuntime(format!("{:?}", e).into(), Position::NONE)))?; + + let authorized_items: Vec<$rhai_return_rust_type> = all_items + .into_iter() + .filter(|item| { + let resource_id = item.id(); + crate::models::access::access::can_access_resource( + db.clone(), + &caller_pk_str, + resource_id, + $resource_type_str, + ) + }) + .collect(); + + Ok(authorized_items.into()) + }, + ); + }; +} diff --git a/rhailib/src/monitor/Cargo.toml b/rhailib/src/monitor/Cargo.toml new file mode 100644 index 0000000..e65bbfa --- /dev/null +++ b/rhailib/src/monitor/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "monitor" +version = "0.1.0" +edition = "2021" + +[dependencies] +anyhow = "1.0" +clap = { version = "4.4", features = ["derive"] } +tokio = { version = "1", features = ["macros", "rt-multi-thread", "signal", "time"] } # time feature might be needed later +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["fmt"] } +redis = { version = "0.25.0", features = ["tokio-comp"] } # For Redis communication +prettytable-rs = "0.10.0" # For displaying tasks in a formatted table +clearscreen = "2.0.1" # For clearing the terminal screen +chrono = { version = "0.4", features = ["serde"] } # For timestamps +futures = "0.3" + +# If the monitor library needs to use parts of rhailib (e.g. Redis connections, task definitions): +# rhailib = { path = ".." } # Assuming monitor is a direct sub-directory of rhailib workspace member + +[[bin]] +name = "monitor" +path = "src/main.rs" diff --git a/rhailib/src/monitor/README.md b/rhailib/src/monitor/README.md new file mode 100644 index 0000000..4df50a2 --- /dev/null +++ b/rhailib/src/monitor/README.md @@ -0,0 +1,67 @@ +# Rhai Worker Monitor (`monitor`) + +`monitor` is a command-line tool designed to observe and display live information about Rhai workers managed by `rhailib`. It provides insights into Redis queue congestion and a table of tasks being processed by specified workers. + +## Features (Planned) + +* **Live Redis Queue Visualization**: Displays a textual, horizontal plot showing the number of tasks in the Redis queue for each monitored worker. The plot will be color-coded to indicate congestion levels and will update by polling the queue size. +* **Task Table**: Shows a table of tasks associated with each worker, including task hash, creation date, status (e.g., pending, running, completed, failed), and potentially other details. + +## Prerequisites + +* Rust and Cargo installed. +* Access to the Redis instance used by the Rhai workers. + +## Building + +Navigate to the `rhailib/monitor` crate's root directory and build the project: + +```bash +cargo build +``` + +## Usage + +To run the monitor, you need to specify which worker queues you want to observe using the `--workers` (or `-w`) flag. Provide a comma-separated list of worker names. + +From the `rhailib/monitor` root directory: + +```bash +cargo run -- --workers [,,...] +``` + +Or from the parent `rhailib` directory (workspace root): + +```bash +cargo run -p monitor -- --workers [,,...] +``` + +**Examples:** + +* Monitor a single worker named `my_default_worker` (from `rhailib/monitor`): + + ```bash + cargo run -- --workers my_default_worker + ``` + +* Monitor multiple workers, `image_processing_worker` and `data_analysis_worker` (from `rhailib` workspace root): + + ```bash + cargo run -p monitor -- --workers image_processing_worker,data_analysis_worker + ``` + +### Command-Line Options + +* `-w, --workers `: (Required) A comma-separated list of worker names to monitor. + +(Future options might include Redis connection parameters, polling intervals, etc.) + +## Development + +The core logic for the monitor is located in `rhailib/monitor/src/`: +* `lib.rs`: Main library file, defines modules. +* `cli_logic.rs`: Handles argument parsing, Redis interaction, and orchestrates the display. +* `plot.rs`: Responsible for generating the textual queue visualization. +* `tasks.rs`: Responsible for fetching and displaying the task table. + +The binary entry point is `rhailib/monitor/src/main.rs`. diff --git a/rhailib/src/monitor/cmd/main.rs b/rhailib/src/monitor/cmd/main.rs new file mode 100644 index 0000000..5b46757 --- /dev/null +++ b/rhailib/src/monitor/cmd/main.rs @@ -0,0 +1,37 @@ +// File: /Users/timurgordon/code/git.ourworld.tf/herocode/rhailib/src/monitor/cmd/main.rs +use anyhow::Result; +use clap::Parser; + +// This assumes that `rhailib/src/lib.rs` will have `pub mod monitor;` +// and `rhailib/src/monitor/mod.rs` will have `pub mod cli_logic;` +// and `cli_logic.rs` will contain `pub async fn start_monitoring`. +// The `crate::` prefix refers to the `rhailib` crate root. + +#[derive(Parser, Debug)] +#[clap(author, version, about = "Rhai Worker Live Monitor", long_about = None)] +struct Args { + /// Comma-separated list of worker names to monitor + #[clap(short, long, value_delimiter = ',')] + workers: Vec, +} + +#[tokio::main] +async fn main() -> Result<()> { + tracing_subscriber::fmt::init(); + + let args = Args::parse(); + + if args.workers.is_empty() { + eprintln!("Error: At least one worker name must be provided via --workers."); + // Consider returning an Err or using clap's built-in required attributes. + std::process::exit(1); + } + + tracing::info!("Monitor CLI starting for workers: {:?}", args.workers); + + // Call the monitoring logic from the `cli_logic` submodule within the `monitor` module + crate::monitor::cli_logic::start_monitoring(&args.workers).await?; + + tracing::info!("Monitor CLI finished."); + Ok(()) +} diff --git a/rhailib/src/monitor/docs/ARCHITECTURE.md b/rhailib/src/monitor/docs/ARCHITECTURE.md new file mode 100644 index 0000000..f833f7e --- /dev/null +++ b/rhailib/src/monitor/docs/ARCHITECTURE.md @@ -0,0 +1,61 @@ +# Architecture of the `monitor` Crate + +The `monitor` crate provides a command-line interface for monitoring and managing Rhai task execution across the rhailib ecosystem. It offers real-time visibility into task queues, execution status, and system performance. + +## Core Architecture + +```mermaid +graph TD + A[Monitor CLI] --> B[Task Monitoring] + A --> C[Queue Management] + A --> D[Performance Metrics] + + B --> B1[Redis Task Tracking] + B --> B2[Status Visualization] + B --> B3[Real-time Updates] + + C --> C1[Queue Inspection] + C --> C2[Task Management] + C --> C3[Worker Status] + + D --> D1[Performance Plotting] + D --> D2[Metrics Collection] + D --> D3[Historical Analysis] +``` + +## Key Components + +### 1. CLI Logic (`cli_logic.rs`) +- **Command Processing**: Handles user commands and interface +- **Real-time Monitoring**: Continuous task status updates +- **Interactive Interface**: User-friendly command-line experience + +### 2. Task Management (`tasks.rs`) +- **Task Discovery**: Finds and tracks tasks across Redis queues +- **Status Reporting**: Provides detailed task execution information +- **Queue Analysis**: Monitors queue depths and processing rates + +### 3. Performance Plotting (`plot.rs`) +- **Metrics Visualization**: Creates performance charts and graphs +- **Trend Analysis**: Historical performance tracking +- **System Health**: Overall system performance indicators + +## Features + +- **Real-time Task Monitoring**: Live updates of task execution status +- **Queue Management**: Inspection and management of Redis task queues +- **Performance Metrics**: System performance visualization and analysis +- **Interactive CLI**: User-friendly command-line interface +- **Multi-worker Support**: Monitoring across multiple worker instances + +## Dependencies + +- **Redis Integration**: Direct Redis connectivity for queue monitoring +- **CLI Framework**: Clap for command-line argument parsing +- **Async Runtime**: Tokio for asynchronous operations +- **Visualization**: Pretty tables and terminal clearing for UI +- **Logging**: Tracing for structured logging and debugging + +## Usage Patterns + +The monitor serves as a central observability tool for rhailib deployments, providing operators with comprehensive visibility into system behavior and performance characteristics. \ No newline at end of file diff --git a/rhailib/src/monitor/src/cli_logic.rs b/rhailib/src/monitor/src/cli_logic.rs new file mode 100644 index 0000000..3bdb20a --- /dev/null +++ b/rhailib/src/monitor/src/cli_logic.rs @@ -0,0 +1,104 @@ +// rhailib/monitor/src/cli_logic.rs +use anyhow::Result; +use futures::stream::{self, StreamExt}; + +// Import functions from sibling modules within the same crate +use crate::plot; +use crate::tasks::{self, RhaiTask}; +use redis::{AsyncCommands, Client as RedisClient}; +use std::collections::HashMap; +use tokio::signal; +use tokio::time::{sleep, Duration}; + +const REDIS_URL: &str = "redis://127.0.0.1/"; +const POLLING_INTERVAL_MILLISECONDS: u64 = 10; // Increased polling interval for SCAN +const SCAN_COUNT: isize = 100; // Number of keys to fetch per SCAN iteration + +/// Main monitoring logic. +pub async fn start_monitoring(worker_names: &[String]) -> Result<()> { + tracing::info!("Attempting to connect to Redis at {}", REDIS_URL); + let client = RedisClient::open(REDIS_URL)?; + let mut con = client.get_multiplexed_async_connection().await?; + tracing::info!("Successfully connected to Redis."); + + let ping_result: String = redis::cmd("PING").query_async(&mut con).await?; + tracing::info!("Redis PING response: {}", ping_result); + + tracing::info!( + "Starting live monitor. Configured workers: {:?}. Press Ctrl+C to exit.", + worker_names + ); + + loop { + tokio::select! { + _ = signal::ctrl_c() => { + print!("\r"); + println!("Exiting Rhai Worker Monitor..."); + break; + } + _ = async { + let mut current_con = con.clone(); // Clone for this iteration + clearscreen::clear().unwrap_or_else(|e| tracing::warn!("Failed to clear screen: {}", e)); + println!("Rhai Worker Monitor (Press Ctrl+C to exit)"); + println!( + "Polling Redis every {}ms. Last update: {}. Configured workers: {:?}", + POLLING_INTERVAL_MILLISECONDS, + chrono::Local::now().format("%Y-%m-%d %H:%M:%S"), + worker_names + ); + + let mut all_rhai_tasks: Vec = Vec::new(); + let mut cursor: isize = 0; + loop { + // SCAN returns a tuple: (new_cursor, keys_array) + let (new_cursor, task_detail_keys): (isize, Vec) = redis::cmd("SCAN") + .arg(cursor) + .arg("MATCH") + .arg("rhai_task_details:*") + .arg("COUNT") + .arg(SCAN_COUNT) + .query_async(&mut current_con) + .await?; + + // Process keys found in this scan iteration + let tasks_futures = stream::iter(task_detail_keys) + .map(|key_with_prefix| { + let mut task_con = current_con.clone(); + async move { + let task_id = key_with_prefix.strip_prefix("rhai_task_details:").unwrap_or(&key_with_prefix).to_string(); + match task_con.hgetall::<_, HashMap>(&key_with_prefix).await { + Ok(details_map) => Some(RhaiTask::from_redis_hash(task_id, &details_map)), + Err(e) => { + tracing::warn!("Could not fetch details for task key {}: {}", key_with_prefix, e); + None + } + } + } + }) + .buffer_unordered(10) // Concurrently fetch details for 10 tasks + .collect::>() + .await; + + all_rhai_tasks.extend(tasks_futures.into_iter().flatten()); + + cursor = new_cursor; + if cursor == 0 { // SCAN returns 0 when iteration is complete + break; + } + } + + // Sort tasks by creation date (optional, assuming created_at is parsable) + // For simplicity, we'll skip sorting for now as created_at is a string. + + let pending_tasks_count = all_rhai_tasks.iter().filter(|task| task.status.to_lowercase() == "pending").count(); + + plot::display_queue_plot("Total Pending Tasks", pending_tasks_count).await?; + tasks::display_task_table(&all_rhai_tasks).await?; + + sleep(Duration::from_millis(POLLING_INTERVAL_MILLISECONDS)).await; + Result::<()>::Ok(()) + } => {} + } + } + Ok(()) +} diff --git a/rhailib/src/monitor/src/lib.rs b/rhailib/src/monitor/src/lib.rs new file mode 100644 index 0000000..ebe2ac9 --- /dev/null +++ b/rhailib/src/monitor/src/lib.rs @@ -0,0 +1,10 @@ +// rhailib/monitor/src/lib.rs + +// Declare the modules that make up this crate's library +pub mod cli_logic; +pub mod plot; +pub mod tasks; + +// Re-export the main function to be used by the binary (src/main.rs) +// and potentially by other crates if this library is used as a dependency. +pub use cli_logic::start_monitoring; diff --git a/rhailib/src/monitor/src/main.rs b/rhailib/src/monitor/src/main.rs new file mode 100644 index 0000000..9001563 --- /dev/null +++ b/rhailib/src/monitor/src/main.rs @@ -0,0 +1,32 @@ +// rhailib/monitor/src/main.rs +use anyhow::Result; +use clap::Parser; + +// Use the start_monitoring function from the monitor crate's library +use monitor::start_monitoring; + +#[derive(Parser, Debug)] +#[clap(author, version, about = "Rhai Worker Monitor CLI", long_about = None)] +struct Args { + /// List of worker names to monitor, comma-separated + #[clap(short, long, value_delimiter = ',', required = true, num_args = 1..)] + workers: Vec, + // TODO: Add other options like Redis connection details if not using a config file or env vars. +} + +#[tokio::main] +async fn main() -> Result<()> { + // Initialize logging (e.g., tracing-subscriber) + // Consider making log level configurable via CLI args or env var. + tracing_subscriber::fmt::init(); + + let args = Args::parse(); + + tracing::info!("Starting monitor for workers: {:?}", args.workers); + + // Call the main logic function from the monitor library + start_monitoring(&args.workers).await?; + + tracing::info!("Monitor finished."); + Ok(()) +} diff --git a/rhailib/src/monitor/src/plot.rs b/rhailib/src/monitor/src/plot.rs new file mode 100644 index 0000000..a87ec5a --- /dev/null +++ b/rhailib/src/monitor/src/plot.rs @@ -0,0 +1,23 @@ +// rhailib/monitor/src/plot.rs +use anyhow::Result; + +/// Placeholder for queue plotting logic. +const MAX_BAR_WIDTH: usize = 50; // Max width of the bar in characters +const BAR_CHAR: char = '█'; // Character to use for the bar + +pub async fn display_queue_plot(plot_label: &str, count: usize) -> Result<()> { + let bar_width = std::cmp::min(count, MAX_BAR_WIDTH); + let bar: String = std::iter::repeat(BAR_CHAR).take(bar_width).collect(); + + // ANSI escape code for green color can be added here if desired + // Example: let green_bar = format!("\x1b[32m{}\x1b[0m", bar); + + println!( + "{:<27} [{:, + pub status: String, + pub created_at: Option, // Keep as string for display, parsing can be complex + pub updated_at: Option, // Keep as string, might be RFC3339 or Unix timestamp + pub client_rpc_id: Option, + pub reply_to_queue: Option, + pub output: Option, + pub error: Option, +} + +impl RhaiTask { + pub fn from_redis_hash(task_id: String, details: &HashMap) -> Self { + // Helper to get optional string, converting "null" string to None + let get_opt_string = |key: &str| -> Option { + details.get(key).and_then(|s| { + if s.to_lowercase() == "null" || s.is_empty() { + None + } else { + Some(s.clone()) + } + }) + }; + + RhaiTask { + id: task_id, + script: get_opt_string("script"), + status: details + .get("status") + .cloned() + .unwrap_or_else(|| "unknown".to_string()), + created_at: get_opt_string("createdAt"), + updated_at: get_opt_string("updatedAt"), + client_rpc_id: get_opt_string("clientRpcId"), + reply_to_queue: get_opt_string("replyToQueue"), + output: get_opt_string("output"), + error: get_opt_string("error"), + } + } +} + +/// Displays all monitored Rhai tasks in a formatted table. +pub async fn display_task_table(tasks: &[RhaiTask]) -> Result<()> { + println!("\nAll Monitored Rhai Tasks:"); + + if tasks.is_empty() { + println!(" No tasks to display."); + return Ok(()); + } + + let mut table = Table::new(); + table.set_format(*format::consts::FORMAT_BOX_CHARS); + table.add_row(Row::new(vec![ + Cell::new("Task ID").style_spec("bFg"), + Cell::new("Status").style_spec("bFg"), + Cell::new("Created At").style_spec("bFg"), + Cell::new("Updated At").style_spec("bFg"), + Cell::new("Details (Output/Error)").style_spec("bFg"), + // Cell::new("Script (Excerpt)").style_spec("bFg"), // Optional: Add if needed + ])); + + for task in tasks { + let details_str = match (&task.output, &task.error) { + (Some(out), None) => format!("Output: {:.50}", out), // Truncate for display + (None, Some(err)) => format!("Error: {:.50}", err), // Truncate for display + (Some(out), Some(err)) => format!("Output: {:.30}... Error: {:.30}...", out, err), + (None, None) => "N/A".to_string(), + }; + + // let script_excerpt = task.script.as_ref().map_or("N/A".to_string(), |s| { + // if s.len() > 30 { format!("{:.27}...", s) } else { s.clone() } + // }); + + table.add_row(Row::new(vec![ + Cell::new(&task.id[..std::cmp::min(task.id.len(), 12)]), // Show first 12 chars of ID + Cell::new(&task.status), + Cell::new(task.created_at.as_deref().unwrap_or("N/A")), + Cell::new(task.updated_at.as_deref().unwrap_or("N/A")), + Cell::new(&details_str), + // Cell::new(&script_excerpt), + ])); + } + + table.printstd(); + Ok(()) +}