### Initialize OTLP Tracing Pipeline in Rust Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/opentelemetry_otlp/index.html Demonstrates how to configure and install a simple OTLP tracing pipeline using the tonic gRPC exporter. It shows the basic setup required to start tracing application logic. ```rust use opentelemetry::global; use opentelemetry::trace::Tracer; fn main() -> Result<(), Box> { // First, create a OTLP exporter builder. Configure it as you need. let otlp_exporter = opentelemetry_otlp::new_exporter().tonic(); // Then pass it into pipeline builder let _ = opentelemetry_otlp::new_pipeline() .tracing() .with_exporter(otlp_exporter) .install_simple()?; let tracer = global::tracer("my_tracer"); tracer.in_span("doing_work", |cx| { // Traced app logic here... }); Ok(()) } ``` -------------------------------- ### Database Module Implementation Example (Rust) Source: https://docs.rs/galvyn/0.2.0/galvyn/core/trait.Module.html?search=std%3A%3Avec An example showing how a `Database` module might implement the `Module` trait. It specifies concrete types for `Setup` as `DatabaseSetup` and `PreInit` as `DatabaseConfiguration`, indicating how this module would be configured and initialized. ```rust impl Module for Database { type Setup = DatabaseSetup; type PreInit = DatabaseConfiguration; // ... other associated types and methods ... } ``` -------------------------------- ### Database Module Implementation Example (Rust) Source: https://docs.rs/galvyn/0.2.0/galvyn/core/module/trait.Module.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E An example showing how the `Database` module implements the `Module` trait. It specifies concrete types for `Setup` as `DatabaseSetup` and `PreInit` as `DatabaseConfiguration`, demonstrating a practical application of the trait. ```rust impl Module for Database { type Setup = DatabaseSetup; type PreInit = DatabaseConfiguration; // ... other implementations } ``` -------------------------------- ### Comprehensive Router Configuration Example Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/axum/struct.Router.html?search=u32+-%3E+bool Illustrates a complex `Router` setup with various routes, including static paths, captures (single and multiple types), and wildcards. It demonstrates how to define handlers for different HTTP methods and extract path parameters. ```rust use axum::{Router, routing::{get, delete}, extract::Path}; let app = Router::new() .route("/", get(root)) .route("/users", get(list_users).post(create_user)) .route("/users/{id}", get(show_user)) .route("/api/{version}/users/{id}/action", delete(do_users_action)) .route("/assets/{*path}", get(serve_asset)); async fn root() {} async fn list_users() {} async fn create_user() {} async fn show_user(Path(id): Path) {} async fn do_users_action(Path((version, id)): Path<(String, u64)>) {} async fn serve_asset(Path(path): Path) {} ``` -------------------------------- ### Database Module Implementation Example - Rust Source: https://docs.rs/galvyn/0.2.0/galvyn/core/module/trait.Module.html?search= An example implementation of the `Module` trait for a `Database` module. It shows how associated types like `Setup` and `PreInit` can be aliased to specific types (`DatabaseSetup` and `DatabaseConfiguration` respectively) for concrete module definitions. ```rust impl Module for Database { type Setup = DatabaseSetup; type PreInit = DatabaseConfiguration; ... } ``` -------------------------------- ### Database Module Implementation Example (Rust) Source: https://docs.rs/galvyn/0.2.0/galvyn/core/module/trait.Module.html?search=std%3A%3Avec Shows a partial implementation of the `Module` trait for a `Database` module. It specifies the associated types `Setup` as `DatabaseSetup` and `PreInit` as `DatabaseConfiguration`, indicating how this specific module is configured and what data is passed during initialization. ```rust impl Module for Database Source #### type Setup = DatabaseSetup Source #### type PreInit = DatabaseConfiguration Source ``` -------------------------------- ### Example: Handling Multiple HTTP Methods for a Route Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/axum/struct.Router.html?search=u32+-%3E+bool Shows two ways to configure a single route (`/`) to respond to multiple HTTP methods (GET, POST, DELETE) using Axum's `Router`. Handlers can be added simultaneously or sequentially. ```rust use axum::{Router, routing::{get, delete}, extract::Path}; let app = Router::new() .route("/", get(get_root).post(post_root).delete(delete_root)); async fn get_root() {} async fn post_root() {} async fn delete_root() {} ``` ```rust let app = Router::new() .route("/", get(get_root)) .route("/", post(post_root)) .route("/", delete(delete_root)); ``` -------------------------------- ### Module Initialization Steps (Conceptual) Source: https://docs.rs/galvyn/0.2.0/galvyn/core/trait.Module.html?search=std%3A%3Avec Explains the three-step initialization process for modules: pre-init (concurrent, no inter-module interaction), init (sequential, main initialization), and post-init (concurrent, finishing touches). Errors in any step prevent application startup. ```text Modules are initialized in three steps. If any module returns an error in any of those steps, the entire application will be prevented from starting. §pre init Every modules’ `pre_init` function is run concurrently. In this step a module may not interact with any other module but is free to load configuration or other data entirely managed by the module itself. The `pre_init` function may return data (`Self::PreInit`) which is then passed to the actual `init` function. §init Every modules’ `init` function is run sequentially in the order defined by the application author. This step should perform the module’s main initialization and returns the module singleton which is stored in globally. §post init Every modules’ `post_init` function is run concurrently. At this point every module has been initialized and is available globally. Modules which others depend on have been made aware of their dependents and may run some finishing initialization code. ``` -------------------------------- ### Module Initialization Steps Overview (Conceptual) Source: https://docs.rs/galvyn/0.2.0/galvyn/core/module/trait.Module.html?search=std%3A%3Avec Explains the three-phase initialization process for Galvyn modules: pre_init (concurrent, no inter-module access), init (sequential, main initialization), and post_init (concurrent, all modules available). Errors in any step prevent application startup. ```text Modules are initialized in three steps. If any module returns an error in any of those steps, the entire application will be prevented from starting. ### §pre init Every modules’ `pre_init` function is run concurrently. In this step a module may not interact with any other module but is free to load configuration or other data entirely managed by the module itself. The `pre_init` function may return data (`Self::PreInit`) which is then passed to the actual `init` function. ### §init Every modules’ `init` function is run sequentially in the order defined by the application author. This step should perform the module’s main initialization and returns the module singleton which is stored in globally. ### §post init Every modules’ `post_init` function is run concurrently. At this point every module has been initialized and is available globally. Modules which others depend on have been made aware of their dependents and may run some finishing initialization code. ``` -------------------------------- ### Convert Router to MakeService with `into_make_service` Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/axum/routing/struct.Router.html This example demonstrates converting an Axum `Router` into a `MakeService` using `into_make_service`. The `MakeService` is a `Service` that produces another service, suitable for starting a web server. The code snippet shows a basic setup for binding a `TcpListener` and serving the Axum application. ```rust use axum::{ routing::get, Router, }; let app = Router::new().route("/", get(|| async {{ "Hi!" }})); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, app).await.unwrap(); ``` -------------------------------- ### Get Header Value - OccupiedEntry Rust Example Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/axum/http/header/struct.OccupiedEntry.html?search=u32+-%3E+bool Shows how to get a reference to the first value associated with an occupied header entry using the `get()` method. Panics if no values are present. ```rust let mut map = HeaderMap::new(); map.insert(HOST, "hello.world".parse().unwrap()); if let Entry::Occupied(mut e) = map.entry("host") { assert_eq!(e.get(), &"hello.world"); e.append("hello.earth".parse().unwrap()); assert_eq!(e.get(), &"hello.world"); } ``` -------------------------------- ### POST /init Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/rorm/cli/init/fn.init.html?search= Initializes the database configuration file for the Galvyn project. ```APIDOC ## POST /init ### Description Creates the database configuration file required for the application to connect to the database. ### Method POST ### Endpoint /init ### Parameters #### Request Body - **database_configuration** (String) - Required - The configuration string for the database. - **driver** (InitDriver) - Required - The specific driver to be used for initialization. - **force** (bool) - Required - Whether to overwrite an existing configuration file. ### Request Example { "database_configuration": "postgres://user:pass@localhost/db", "driver": "Postgres", "force": false } ### Response #### Success Response (200) - **status** (string) - Indicates successful creation of the configuration file. #### Response Example { "status": "success" } ``` -------------------------------- ### POST /init Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/rorm/cli/init/fn.init.html?search=std%3A%3Avec Initializes the database configuration file for the Galvyn project. ```APIDOC ## POST /init ### Description Creates the database configuration file required for the application to interface with the database. ### Method POST ### Endpoint /init ### Parameters #### Request Body - **database_configuration** (String) - Required - The configuration string for the database. - **driver** (InitDriver) - Required - The specific database driver to be used. - **force** (bool) - Required - Whether to overwrite existing configuration files. ### Request Example { "database_configuration": "postgres://user:pass@localhost/db", "driver": "Postgres", "force": false } ### Response #### Success Response (200) - **result** (Result<(), Error>) - Returns an empty success object or an error if initialization fails. #### Response Example { "status": "success" } ``` -------------------------------- ### Chaining GET Method Handler Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/axum/routing/method_routing/struct.MethodRouter.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides an example of chaining a handler for GET requests using the `get` method on MethodRouter. It also notes that HEAD requests are handled by GET routes but without a body, suggesting explicit HEAD routes if needed. ```rust use axum::{routing::post, Router}; async fn handler() {} async fn other_handler() {} // Requests to `POST /` will go to `handler` and `GET /` will go to // `other_handler`. let app = Router::new().route("/", post(handler).get(other_handler)); // Note that `get` routes will also be called for `HEAD` requests but will have the response body removed. Make sure to add explicit `HEAD` routes afterwards. ``` -------------------------------- ### GET /string/starts_with Source: https://docs.rs/galvyn/0.2.0/galvyn/rorm/fields/utils/column_name/struct.ColumnName.html?search=u32+-%3E+bool Checks if the string starts with a given pattern. ```APIDOC ## GET /string/starts_with ### Description Returns true if the given pattern matches a prefix of this string slice. ### Method GET ### Endpoint /string/starts_with ### Parameters #### Query Parameters - **pat** (Pattern) - Required - The prefix pattern to check. ### Response #### Success Response (200) - **result** (boolean) - True if the string starts with the pattern. ### Response Example { "result": true } ``` -------------------------------- ### POST /init Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/rorm/cli/init/fn.init.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes the database configuration file for the Galvyn project. ```APIDOC ## POST /init ### Description Creates the database configuration file required for the Galvyn project environment. ### Method POST ### Endpoint /init ### Parameters #### Request Body - **database_configuration** (String) - Required - The configuration string for the database. - **driver** (InitDriver) - Required - The driver type to be used for initialization. - **force** (bool) - Required - Whether to overwrite existing configuration files. ### Request Example { "database_configuration": "postgres://user:pass@localhost/db", "driver": "Postgres", "force": false } ### Response #### Success Response (200) - **status** (string) - Indicates successful creation of the configuration file. #### Response Example { "status": "success" } ``` -------------------------------- ### Chaining GET Handler with MethodRouter (Rust) Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/axum/routing/method_routing/struct.MethodRouter.html Example of using the `get` method on MethodRouter to chain a handler specifically for GET requests. It also demonstrates how to chain another handler for a different method using `post`. ```Rust use axum::{routing::post, Router}; async fn handler() {} async fn other_handler() {} // Requests to `POST /` will go to `handler` and `GET /` will go to // `other_handler`. let app = Router::new().route("/", post(handler).get(other_handler)); ``` -------------------------------- ### GET /string/starts_with Source: https://docs.rs/galvyn/0.2.0/galvyn/rorm/fields/utils/column_name/struct.ColumnName.html Checks if a string starts with a specific prefix pattern. ```APIDOC ## GET /string/starts_with ### Description Returns true if the given pattern matches the prefix of the string. ### Method GET ### Endpoint /string/starts_with ### Parameters #### Query Parameters - **pat** (Pattern) - Required - The prefix pattern to check. ### Response #### Success Response (200) - **result** (boolean) - True if the string starts with the pattern. ### Response Example { "result": true } ``` -------------------------------- ### POST /init Source: https://docs.rs/galvyn/0.2.0/galvyn/rorm/cli/init/fn.init.html Initializes the database configuration file for the Galvyn RORM project. ```APIDOC ## POST /init ### Description Creates the database configuration file required for the Galvyn RORM project to connect to a database. ### Method POST ### Endpoint /init ### Parameters #### Request Body - **database_configuration** (String) - Required - The path or content of the database configuration. - **driver** (InitDriver) - Required - The database driver to be used (e.g., SQLite, Postgres). - **force** (bool) - Required - If true, overwrites existing configuration files. ### Request Example { "database_configuration": "config.toml", "driver": "Postgres", "force": false } ### Response #### Success Response (200) - **status** (string) - Indicates successful initialization. #### Response Example { "status": "success" } ``` -------------------------------- ### Routing GET Requests with MethodRouter::get Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/axum/routing/method_routing/struct.MethodRouter.html?search=std%3A%3Avec Provides an example of chaining a handler for GET requests using the `get` method on MethodRouter. It also notes that GET routes implicitly handle HEAD requests, but explicit HEAD routes should be added for full control. ```rust use axum::{routing::post, Router}; async fn handler() {} async fn other_handler() {} // Requests to `POST /` will go to `handler` and `GET /` will go to // `other_handler`. let app = Router::new().route("/", post(handler).get(other_handler)); Note that `get` routes will also be called for `HEAD` requests but will have the response body removed. Make sure to add explicit `HEAD` routes afterwards. ``` -------------------------------- ### GET /slice/rchunks Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/opentelemetry_sdk/trace/struct.SpanEvents.html?search=std%3A%3Avec Returns an iterator over chunks of a slice starting from the end of the slice. ```APIDOC ## GET /slice/rchunks ### Description Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end. If the slice length is not divisible by `chunk_size`, the final chunk will be smaller. ### Parameters #### Query Parameters - **chunk_size** (usize) - Required - The number of elements per chunk. ### Response #### Success Response (200) - **iterator** (RChunks) - Non-overlapping chunks starting from the end. ### Response Example ```json { "chunks": [["e", "m"], ["o", "r"], ["l"]] } ``` ``` -------------------------------- ### GET /iterator/rfold Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/opentelemetry/metrics/type.Callback.html?search=std%3A%3Avec Reduces an iterator's elements to a single value starting from the back of the collection. ```APIDOC ## GET /iterator/rfold ### Description Reduces the iterator's elements to a single, final value, starting from the back. This is the reverse version of the standard fold operation. ### Method GET ### Endpoint /iterator/rfold ### Parameters #### Query Parameters - **init** (B) - Required - The initial value for the reduction. - **f** (FnMut) - Required - The closure to apply to each element. ### Request Example { "init": 0, "f": "(acc, val) => acc + val" } ### Response #### Success Response (200) - **result** (B) - The final reduced value. #### Response Example { "result": 15 } ``` -------------------------------- ### Comprehensive Router Configuration Example Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/axum/struct.Router.html?search= Provides a detailed example of configuring a router with various types of routes, including static paths, captures, wildcards, and multiple methods. This showcases the flexibility of the `Router` in defining API endpoints. ```rust use axum::{ Router, routing::{get, delete}, extract::Path, }; let app = Router::new() .route("/", get(root)) .route("/users", get(list_users).post(create_user)) .route("/users/{id}", get(show_user)) .route("/api/{version}/users/{id}/action", delete(do_users_action)) .route("/assets/{*path}", get(serve_asset)); async fn root() {{}} async fn list_users() {{}} async fn create_user() {{}} async fn show_user(Path(id): Path) {{}} async fn do_users_action(Path((version, id)): Path<(String, u64)>) {{}} async fn serve_asset(Path(path): Path) {{}} ``` -------------------------------- ### Create InstrumentationLibrary Instance (Rust) Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/opentelemetry/struct.InstrumentationLibrary.html?search= Demonstrates how to create an instance of InstrumentationLibrary using its builder pattern. This example shows how to set the library name, version, and schema URL. ```rust let library = opentelemetry::InstrumentationLibrary::builder("my-crate"). with_version(env!("CARGO_PKG_VERSION")). with_schema_url("https://opentelemetry.io/schemas/1.17.0"). build(); ``` -------------------------------- ### Get Port as u16 from Authority Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/axum/http/uri/struct.Authority.html?search= Provides an example of directly getting the port number as a u16 from an Authority struct. Returns None if no port is specified. ```rust let authority: Authority = "example.org:80".parse().unwrap(); assert_eq!(authority.port_u16(), Some(80)); ``` -------------------------------- ### Configure and Build MeterProvider Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/opentelemetry_sdk/metrics/struct.MeterProviderBuilder.html Demonstrates how to use the MeterProviderBuilder to associate resources, readers, and views, and finally construct the SdkMeterProvider. ```rust use galvyn::core::re_exports::opentelemetry_sdk::metrics::MeterProviderBuilder; let provider = MeterProviderBuilder::default() .with_resource(my_resource) .with_reader(my_reader) .with_view(my_view) .build(); ``` -------------------------------- ### GET /slice/rchunks Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/rorm/linkme/struct.DistributedSlice.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns an iterator over elements of the slice in chunks of a specified size, starting from the end. ```APIDOC ## GET /slice/rchunks ### Description Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice. If `chunk_size` does not divide the length, the last chunk will be smaller. ### Parameters #### Query Parameters - **chunk_size** (usize) - Required - The number of elements per chunk. ### Response #### Success Response (200) - **iterator** (RChunks) - An iterator over slice chunks. ``` -------------------------------- ### Initialize OTLP Pipelines in Rust Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/opentelemetry_otlp/struct.OtlpPipeline.html Demonstrates how to use the OtlpPipeline builder to initialize logging, metrics, and tracing pipelines within the galvyn framework. ```rust use galvyn::core::re_exports::opentelemetry_otlp::OtlpPipeline; // Initialize a logging pipeline let log_pipeline = OtlpPipeline.logging(); // Initialize a metrics pipeline with a runtime let metrics_pipeline = OtlpPipeline.metrics(runtime); // Initialize a tracing pipeline let trace_pipeline = OtlpPipeline.tracing(); ``` -------------------------------- ### OtlpLogPipeline Configuration and Installation Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/opentelemetry_otlp/struct.OtlpLogPipeline.html?search=std%3A%3Avec Demonstrates how to configure an OtlpLogPipeline with custom resources and batch settings, followed by installing the log provider using either simple or batch processing methods. ```rust pub struct OtlpLogPipeline { /* private fields */ } // Configuration methods pub fn with_resource(self, resource: Resource) -> OtlpLogPipeline pub fn with_batch_config(self, batch_config: BatchConfig) -> OtlpLogPipeline // Installation methods pub fn install_simple(self) -> Result pub fn install_batch(self, runtime: R) -> Result where R: RuntimeChannel; ``` -------------------------------- ### Initialize Modules Source: https://docs.rs/galvyn/0.2.0/galvyn/struct.ModuleBuilder.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Finalizes the module registration process and initializes the application router. ```APIDOC ## POST /init_modules ### Description Initializes all registered modules and returns a RouterBuilder. Note: The ModuleBuilder instance should not be used after calling this method. ### Method POST ### Endpoint /init_modules ### Response #### Success Response (200) - **router_builder** (RouterBuilder) - The initialized router builder instance. #### Error Response (500) - **error** (GalvynError) - Returns an error if module initialization fails. ``` -------------------------------- ### GET /users/{id}/things Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/axum/extract/index.html?search=std%3A%3Avec Example of using multiple extractors (Path and Query) in a single handler. ```APIDOC ## GET /users/{id}/things ### Description Retrieves a list of items for a specific user with pagination support. ### Method GET ### Endpoint /users/{id}/things ### Parameters #### Path Parameters - **id** (Uuid) - Required - The unique identifier of the user #### Query Parameters - **page** (usize) - Required - The page number - **per_page** (usize) - Required - Number of items per page ### Request Example GET /users/550e8400-e29b-41d4-a716-446655440000/things?page=1&per_page=10 ### Response #### Success Response (200) - **items** (Array) - List of user things #### Response Example { "items": ["item1", "item2"] } ``` -------------------------------- ### POST /build Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/opentelemetry_otlp/struct.OtlpMetricPipeline.html?search=u32+-%3E+bool Finalizes the configuration and constructs the SdkMeterProvider. ```APIDOC ## build() ### Description Consumes the pipeline configuration and returns a configured SdkMeterProvider or a MetricsError if the build fails. ### Method POST (Internal Build Method) ### Response #### Success Response (200) - **SdkMeterProvider**: The initialized meter provider instance. #### Error Response (500) - **MetricsError**: Returned if the provider fails to initialize. ``` -------------------------------- ### GET /rsplitn Source: https://docs.rs/galvyn/0.2.0/galvyn/rorm/fields/types/struct.MaxStr.html?search= Returns an iterator over substrings separated by a pattern, starting from the end, restricted to at most n items. ```APIDOC ## GET /rsplitn ### Description Returns an iterator over substrings of this string slice, separated by a pattern, starting from the end of the string, restricted to returning at most n items. ### Method GET ### Endpoint /rsplitn ### Parameters #### Query Parameters - **n** (usize) - Required - Maximum number of substrings to return. - **pat** (Pattern) - Required - The pattern to match. ### Request Example { "n": 3, "pat": " " } ### Response #### Success Response (200) - **iterator** (RSplitN) - An iterator over the resulting substrings. #### Response Example ["lamb", "little", "Mary had a"] ``` -------------------------------- ### Initialize OTLP Pipelines in Rust Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/opentelemetry_otlp/struct.OtlpPipeline.html?search=u32+-%3E+bool Demonstrates how to use the OtlpPipeline builder to create logging, metrics, and tracing pipelines. These methods return specific pipeline types configured for OTLP export. ```rust use galvyn::core::re_exports::opentelemetry_otlp::OtlpPipeline; let pipeline = OtlpPipeline; // Create logging pipeline let log_pipeline = pipeline.logging(); // Create metrics pipeline (requires a runtime) let metrics_pipeline = pipeline.metrics(rt); // Create tracing pipeline let trace_pipeline = pipeline.tracing(); ``` -------------------------------- ### GET /slice/rchunks_exact Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/rorm/linkme/struct.DistributedSlice.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns an iterator over elements of the slice in exact chunks of a specified size, starting from the end. ```APIDOC ## GET /slice/rchunks_exact ### Description Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end. Elements that do not fit the chunk size are omitted and available via the remainder method. ### Parameters #### Query Parameters - **chunk_size** (usize) - Required - The exact number of elements per chunk. ### Response #### Success Response (200) - **iterator** (RChunksExact) - An iterator over exact slice chunks. ``` -------------------------------- ### GET /sse Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/axum/response/sse/index.html An example endpoint demonstrating how to stream Server-Sent Events to a client. ```APIDOC ## GET /sse ### Description Establishes a Server-Sent Events (SSE) connection that streams events to the client at a specified interval. ### Method GET ### Endpoint /sse ### Parameters None ### Request Example N/A ### Response #### Success Response (200) - **Content-Type** (string) - text/event-stream - **Body** (stream) - A stream of SSE events #### Response Example ``` data: hi! data: hi! ``` ``` -------------------------------- ### Configure and Install Trace Pipeline Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/opentelemetry_otlp/struct.OtlpTracePipeline.html?search= Shows how to configure trace and batch settings for the pipeline and install the provider using batch processing. ```rust use opentelemetry_otlp::WithExportConfig; let pipeline = opentelemetry_otlp::new_pipeline() .tracing() .with_trace_config(trace_config) .with_batch_config(batch_config); let tracer_provider = pipeline.install_batch(tokio::runtime::Handle::current())?; ``` -------------------------------- ### GET /openapi Source: https://docs.rs/galvyn/0.2.0/galvyn/openapi/fn.get_openapi.html?search=u32+-%3E+bool Auto-generates an OpenAPI document for your application using the Galvyn library. This function requires Galvyn to be started. ```APIDOC ## GET /openapi ### Description Auto-generates an OpenAPI document for your application. This function relies on the Galvyn application having been started. ### Method GET ### Endpoint /openapi ### Parameters None ### Request Body None ### Response #### Success Response (200) - **openapi_document** (object) - The auto-generated OpenAPI document in JSON format. #### Response Example ```json { "openapi": "3.0.0", "info": { "title": "My Application", "version": "1.0.0" }, "paths": {} } ``` ### Panics This function will panic if Galvyn has not been started yet. ``` -------------------------------- ### Initialize OTLP Pipelines in Rust Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/opentelemetry_otlp/struct.OtlpPipeline.html?search=std%3A%3Avec Demonstrates how to use the OtlpPipeline builder to initialize logging, metrics, and tracing pipelines. These methods return specific pipeline types configured for OTLP export. ```rust use galvyn::core::re_exports::opentelemetry_otlp::OtlpPipeline; let pipeline = OtlpPipeline; // Create a logging pipeline let log_pipeline = pipeline.logging(); // Create a metrics pipeline let metrics_pipeline = pipeline.metrics(runtime); // Create a tracing pipeline let trace_pipeline = pipeline.tracing(); ``` -------------------------------- ### Get Raw JSON Text Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/schemars/_serde_json/value/struct.RawValue.html?search=std%3A%3Avec Demonstrates how to access the underlying JSON text of a RawValue using the `get()` method. This allows for inspecting the raw string content, for example, to check if a payload is a JSON object or another type, without fully parsing it. ```rust use serde::Deserialize; use serde_json::{Result, value::RawValue}; #[derive(Deserialize)] struct Response<'a> { code: u32, #[serde(borrow)] payload: &'a RawValue, } fn process(input: &str) -> Result<()> { let response: Response = serde_json::from_str(input)?; let payload = response.payload.get(); if payload.starts_with('{') { // handle a payload which is a JSON map } else { // handle any other type } Ok(()) } fn main() -> Result<()> { process(r#" {"code": 200, "payload": {}} "#)?; Ok(()) } ``` -------------------------------- ### Example Usage of MockConnectInfo in Axum Tests (Rust) Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/axum/extract/connect_info/struct.MockConnectInfo.html?search=u32+-%3E+bool Demonstrates how to use MockConnectInfo within an Axum application for testing purposes. This example shows setting up a test router with MockConnectInfo and making a request to verify its behavior. It contrasts with a regular router setup. ```Rust use axum::{ Router, extract::connect_info::{MockConnectInfo, ConnectInfo}, body::Body, routing::get, http::{Request, StatusCode}, }; use std::net::SocketAddr; use tower::ServiceExt; async fn handler(ConnectInfo(addr): ConnectInfo) {} // this router you can run with `app.into_make_service_with_connect_info::()` fn app() -> Router { Router::new().route("/", get(handler)) } // use this router for tests fn test_app() -> Router { app().layer(MockConnectInfo(SocketAddr::from(([0, 0, 0, 0], 1337)))) } // #[tokio::test] async fn some_test() { let app = test_app(); let request = Request::new(Body::empty()); let response = app.oneshot(request).await.unwrap(); assert_eq!(response.status(), StatusCode::OK); } ``` -------------------------------- ### Install Simple and Batch OTLP Exporters (Rust) Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/opentelemetry_otlp/struct.OtlpTracePipeline.html?search=std%3A%3Avec Shows how to install the configured OTLP span exporter. `install_simple` installs the exporter directly, returning a TracerProvider. `install_batch` installs the exporter with a batch span processor, requiring a runtime and returning a TracerProvider. Note that `install_batch` panics if not called within a tokio runtime. ```rust pub fn install_simple(self) -> Result pub fn install_batch(self, runtime: R) -> Result where R: RuntimeChannel, ``` -------------------------------- ### GET /users/{user_id}/team/{team_id} Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/axum/extract/struct.RawPathParams.html?search=u32+-%3E+bool An example of using the RawPathParams extractor to capture path segments from a URL route. ```APIDOC ## GET /users/{user_id}/team/{team_id} ### Description Captures raw path parameters from the request URL without performing deserialization. This is useful for performance-critical endpoints where raw string access is sufficient. ### Method GET ### Endpoint /users/{user_id}/team/{team_id} ### Parameters #### Path Parameters - **user_id** (string) - Required - The unique identifier for the user. - **team_id** (string) - Required - The unique identifier for the team. ### Request Example GET /users/123/team/456 ### Response #### Success Response (200) - **params** (Map) - A collection of key-value pairs representing the captured path segments. #### Response Example { "user_id": "123", "team_id": "456" } #### Error Response (400) - **message** (string) - Returned if path parameters contain invalid UTF-8 sequences. ``` -------------------------------- ### Initialize and Configure Resource in Rust Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/opentelemetry_sdk/resource/struct.Resource.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to create a new Resource instance using key-value pairs or schema URLs. These methods handle attribute de-duplication and schema validation. ```rust use galvyn::core::re_exports::opentelemetry_sdk::Resource; // Create an empty resource let empty = Resource::empty(); // Create from key-value pairs let resource = Resource::new(vec![ KeyValue::new("service.name", "my-service"), KeyValue::new("service.version", "1.0.0") ]); // Create with a schema URL let resource_with_schema = Resource::from_schema_url( vec![KeyValue::new("host.name", "localhost")], "https://opentelemetry.io/schemas/1.20.0" ); ``` -------------------------------- ### Configure and initialize async instruments Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/opentelemetry/metrics/struct.AsyncInstrumentBuilder.html?search=std%3A%3Avec Methods for configuring an instrument's metadata and callback, followed by initialization methods. Use try_init for error handling or init for direct creation. ```rust pub fn with_description(self, description: S) -> AsyncInstrumentBuilder<'a, I, M> where S: Into>; pub fn with_unit(self, unit: S) -> AsyncInstrumentBuilder<'a, I, M> where S: Into>; pub fn with_callback(self, callback: F) -> AsyncInstrumentBuilder<'a, I, M> where F: Fn(&dyn AsyncInstrument) + Send + Sync + 'static; pub fn try_init(self) -> Result; pub fn init(self) -> I; ``` -------------------------------- ### Rust: Getting Session Expiry with Tower Sessions Source: https://docs.rs/galvyn/0.2.0/galvyn/core/session/struct.Session.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to get the session's expiry information using the `expiry` method in Tower Sessions. The example shows that initially, a session created without an explicit expiry has `None` for its expiry. ```rust use std::sync::Arc; use tower_sessions::{session::Expiry, MemoryStore, Session}; let store = Arc::new(MemoryStore::default()); let session = Session::new(None, store, None); assert_eq!(session.expiry(), None); ``` -------------------------------- ### Rust Handler Macro Variants for HTTP Methods Source: https://docs.rs/galvyn/0.2.0/galvyn/attr.handler.html?search=u32+-%3E+bool Specialized variants of the `#[handler]` macro exist for each HTTP method, simplifying the syntax. For example, `#[get(...)]` is equivalent to `#[handler(Get, ...)]`, `#[post(...)]` to `#[handler(Post, ...)]`, and so on for all standard HTTP methods. ```rust // Equivalent to #[handler(Get, ...)] #[get(...)] // Equivalent to #[handler(Post, ...)] #[post(...)] // Equivalent to #[handler(Put, ...)] #[put(...)] // Equivalent to #[handler(Delete, ...)] #[delete(...)] // Equivalent to #[handler(Head, ...)] #[head(...)] // Equivalent to #[handler(Options, ...)] #[options(...)] // Equivalent to #[handler(Patch, ...)] #[patch(...)] // Equivalent to #[handler(Trace, ...)] #[trace(...)] ``` -------------------------------- ### Configure and Install Trace Pipeline Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/opentelemetry_otlp/struct.OtlpTracePipeline.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to apply custom configurations to the pipeline and install it using batch processing. ```rust let pipeline = OtlpTracePipeline::default() .with_trace_config(trace_config) .with_batch_config(batch_config); let provider = pipeline.install_batch(tokio::runtime::Handle::current())?; ``` -------------------------------- ### Initialize NoopMeterProvider Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/opentelemetry/metrics/noop/struct.NoopMeterProvider.html?search= Demonstrates how to define the NoopMeterProvider struct and create a new instance using the new() constructor. ```rust pub struct NoopMeterProvider { /* private fields */ } impl NoopMeterProvider { pub fn new() -> NoopMeterProvider { NoopMeterProvider {} } } ``` -------------------------------- ### Example: Consuming Urn to Get Uuid Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/uuid/fmt/struct.Urn.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates the `into_uuid` method by creating an Urn from Uuid::nil() and then consuming it to retrieve the Uuid, asserting its equality with Uuid::nil(). ```rust use uuid::Uuid; let urn = Uuid::nil().urn(); assert_eq!(urn.into_uuid(), Uuid::nil()); ``` -------------------------------- ### Example: Getting Uuid Reference from Urn Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/uuid/fmt/struct.Urn.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Illustrates how to use the `as_uuid` method to obtain a reference to the Uuid from an Urn. It compares the obtained Uuid with the Uuid::nil() for verification. ```rust use uuid::Uuid; let urn = Uuid::nil().urn(); assert_eq!(*urn.as_uuid(), Uuid::nil()); ``` -------------------------------- ### Initialize and Configure GalvynRouter Source: https://docs.rs/galvyn/0.2.0/galvyn/core/struct.GalvynRouter.html?search=u32+-%3E+bool Demonstrates the basic instantiation and configuration of a GalvynRouter, including adding handlers, metadata, and middleware. ```rust use galvyn::core::GalvynRouter; let router = GalvynRouter::new() .handler(my_handler) .metadata(my_metadata) .wrap(my_middleware) .finish(); ``` -------------------------------- ### Get Month Component of Date in Rust Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/time/struct.Date.html?search= Extracts the month component from a `Date` object. The function returns a `Month` enum value, as demonstrated with examples for January and December. ```rust pub const fn month(self) -> Month ``` -------------------------------- ### Module Initialization Steps (Conceptual) Source: https://docs.rs/galvyn/0.2.0/galvyn/core/trait.Module.html Illustrates the three-step initialization process for Galvyn modules: pre-init, init, and post-init. Pre-init runs concurrently, init runs sequentially, and post-init runs concurrently after all modules are initialized. Errors in any step prevent application startup. ```text 1. Pre-init: Run concurrently. Modules can load configuration but cannot interact with other modules. Returns `PreInit` data. 2. Init: Run sequentially in defined order. Performs main initialization and returns the module singleton. 3. Post-init: Run concurrently. All modules are initialized and globally available. Finishing touches can be applied. ``` -------------------------------- ### Initialize Database Configuration Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/rorm/cli/init/fn.init.html?search=u32+-%3E+bool Initializes the database configuration file with the provided settings. ```APIDOC ## POST /galvyn/init ### Description Creates the database configuration file using the provided database connection string, driver type, and a force flag. ### Method POST ### Endpoint /galvyn/init ### Parameters #### Query Parameters - **database_configuration** (String) - Required - The connection string for the database. - **driver** (InitDriver) - Required - The type of database driver to use. - **force** (bool) - Optional - If true, overwrites existing configuration. ### Request Example ```json { "database_configuration": "postgres://user:password@host:port/database", "driver": "Postgres", "force": true } ``` ### Response #### Success Response (200) - **status** (String) - Indicates success or failure of the operation. #### Response Example ```json { "status": "Configuration created successfully." } ``` ``` -------------------------------- ### Access Response Builder Extensions (Read-Only) Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/axum/http/response/struct.Builder.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides an example of getting a read-only reference to the `Extensions` collection within the response builder. This allows inspecting stored extensions. ```rust let res = Response::builder().extension("My Extension").extension(5u32); let extensions = res.extensions_ref().unwrap(); assert_eq!(extensions.get::<&'static str>(), Some(&"My Extension")); assert_eq!(extensions.get::(), Some(&5u32)); ``` -------------------------------- ### Initialize NoopLoggerProvider Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/opentelemetry/logs/struct.NoopLoggerProvider.html?search= Demonstrates how to create a new instance of the NoopLoggerProvider using the new() constructor. ```rust pub fn new() -> NoopLoggerProvider ``` -------------------------------- ### Access Response Builder Headers (Read-Only) Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/axum/http/response/struct.Builder.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides an example of getting a read-only reference to the `HeaderMap` within the response builder. This is useful for inspecting currently set headers. ```rust let res = Response::builder() .header("Accept", "text/html") .header("X-Custom-Foo", "bar"); let headers = res.headers_ref().unwrap(); assert_eq!( headers["Accept"], "text/html" ); assert_eq!( headers["X-Custom-Foo"], "bar" ); ``` -------------------------------- ### Get Monday-Based Week Number Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/time/struct.PrimitiveDateTime.html Calculates the week number where week 1 starts on Monday, returning a value from 0 to 53. This is common in many business contexts. ```rust assert_eq!(datetime!(2019-01-01 0:00).monday_based_week(), 0); assert_eq!(datetime!(2020-01-01 0:00).monday_based_week(), 0); assert_eq!(datetime!(2020-12-31 0:00).monday_based_week(), 52); assert_eq!(datetime!(2021-01-01 0:00).monday_based_week(), 0); ``` -------------------------------- ### Initialize and Configure GalvynRouter Source: https://docs.rs/galvyn/0.2.0/galvyn/core/struct.GalvynRouter.html?search=std%3A%3Avec Demonstrates the basic instantiation and configuration of a GalvynRouter, including adding handlers and metadata. ```rust use galvyn::core::GalvynRouter; let router = GalvynRouter::new() .handler(my_handler) .metadata(my_metadata) .finish(); ``` -------------------------------- ### Initialize and Manipulate Resource in Rust Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/opentelemetry_sdk/struct.Resource.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to instantiate a Resource using various constructors and how to merge multiple resources together. These methods ensure efficient attribute management and schema URL handling. ```rust use galvyn::core::re_exports::opentelemetry_sdk::Resource; use std::time::Duration; // Create an empty resource let empty_res = Resource::empty(); // Create a resource from key-value pairs let res = Resource::new(vec![("service.name", "my-service").into()]); // Merge two resources let merged = res.merge(&empty_res); // Check properties if !merged.is_empty() { println!("Resource has {} attributes", merged.len()); } ``` -------------------------------- ### Get URI Query as Option<&str> Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/axum/http/struct.Uri.html Retrieves the query string component of a URI, starting after the '?'. The query is terminated by a '#' or the end of the URI. Returns None if no query is present. ```rust let uri: Uri = "abc://username:password@example.com:123/path/data?key=value&key2=value2#fragid1".parse().unwrap(); assert_eq!(uri.query(), Some("key=value&key2=value2")); ``` -------------------------------- ### GalvynSetup Configuration Source: https://docs.rs/galvyn/0.2.0/galvyn/struct.GalvynSetup.html Configuration structure for initializing the Galvyn framework. ```APIDOC ## Struct GalvynSetup ### Description General setup options for the Galvyn framework. This struct is non-exhaustive and controls core behavior like session management and error handling. ### Method N/A (Configuration Struct) ### Parameters #### Request Body - **disable_sessions** (bool) - Optional - If true, disables Galvyn's internal session layer, allowing the user to provide their own. - **disable_panic_hook** (bool) - Optional - If true, disables the global Galvyn panic hook which normally emits 'error!' events instead of printing to stderr. ### Request Example { "disable_sessions": false, "disable_panic_hook": false } ### Response #### Success Response (200) - **GalvynSetup** (Object) - Returns the default configuration instance. #### Response Example { "disable_sessions": false, "disable_panic_hook": false } ``` -------------------------------- ### Chaining DELETE Handlers Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/axum/routing/struct.MethodRouter.html Demonstrates chaining a handler for DELETE requests using the `delete` method on MethodRouter. It references the `get` method for a similar example. ```rust async fn handler() {} // Chain an additional handler that will only accept `DELETE` requests. let method_router = method_router.delete(handler); ``` -------------------------------- ### Construct InstrumentationLibrary using Builder Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/opentelemetry/struct.InstrumentationLibrary.html Demonstrates the recommended way to instantiate an InstrumentationLibrary using the builder pattern, which allows for fluent configuration of version and schema details. ```rust let library = opentelemetry::InstrumentationLibrary::builder("my-crate") .with_version(env!("CARGO_PKG_VERSION")) .with_schema_url("https://opentelemetry.io/schemas/1.17.0") .build(); ``` -------------------------------- ### Get Port as u16 in Rust Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/axum/http/uri/struct.Port.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides an example of how to retrieve the port number as a u16 from a Port instance. This is useful for numerical comparisons or operations. ```rust let authority: Authority = "example.org:80".parse().unwrap(); let port = authority.port().unwrap(); assert_eq!(port.as_u16(), 80); ``` -------------------------------- ### Get Entry Key - OccupiedEntry Rust Example Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/axum/http/header/struct.OccupiedEntry.html?search=u32+-%3E+bool Demonstrates how to retrieve the key of an occupied entry in a HeaderMap using the `key()` method. This is useful for verifying which header an entry corresponds to. ```rust let mut map = HeaderMap::new(); map.insert(HOST, "world".parse().unwrap()); if let Entry::Occupied(e) = map.entry("host") { assert_eq!("host", e.key()); } ``` -------------------------------- ### Initialize Deserializer from various sources Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/schemars/_serde_json/struct.Deserializer.html?search= Demonstrates how to instantiate a Deserializer using different input sources such as io::Read, slices, or string slices. These methods are the standard way to begin the deserialization process in the galvyn/serde_json ecosystem. ```rust use galvyn::core::re_exports::schemars::_serde_json::Deserializer; // From reader let reader = std::io::Cursor::new(b"{\"key\": \"value\"}"); let mut de = Deserializer::from_reader(reader); // From slice let slice = b"{\"key\": \"value\"}"; let mut de = Deserializer::from_slice(slice); // From string let s = "{\"key\": \"value\"}"; let mut de = Deserializer::from_str(s); ``` -------------------------------- ### Get Sunday-Based Week Number Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/time/struct.PrimitiveDateTime.html Calculates the week number where week 1 starts on Sunday, returning a value from 0 to 53. This provides an alternative week numbering system. ```rust assert_eq!(datetime!(2019-01-01 0:00).sunday_based_week(), 0); assert_eq!(datetime!(2020-01-01 0:00).sunday_based_week(), 0); assert_eq!(datetime!(2020-12-31 0:00).sunday_based_week(), 52); assert_eq!(datetime!(2021-01-01 0:00).sunday_based_week(), 0); ``` -------------------------------- ### Get Year Component of Date in Rust Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/time/struct.Date.html?search= Retrieves the year component from a `Date` object. The returned `i32` value represents the year, and examples show its usage with different date values. ```rust pub const fn year(self) -> i32 ``` -------------------------------- ### Initialize RegistryBuilder in Rust Source: https://docs.rs/galvyn/0.2.0/galvyn/core/module/registry/builder/struct.RegistryBuilder.html?search=std%3A%3Avec Demonstrates how to instantiate a new RegistryBuilder, register a module, and perform the asynchronous initialization process. ```rust use galvyn::core::module::registry::builder::RegistryBuilder; async fn setup_registry() -> Result<(), InitError> { let mut builder = RegistryBuilder::new(); builder.register_module::(setup_config); builder.init().await } ``` -------------------------------- ### HTTP Method Request Builders Source: https://docs.rs/galvyn/0.2.0/galvyn/core/re_exports/axum/http/struct.Request.html?search= Examples of using convenience methods to initialize Request builders with specific HTTP methods like GET, POST, PUT, DELETE, OPTIONS, and HEAD. ```rust let request = Request::get("https://www.rust-lang.org/") .body(()) .unwrap(); let request = Request::post("https://www.rust-lang.org/") .body(()) .unwrap(); let request = Request::delete("https://www.rust-lang.org/") .body(()) .unwrap(); ```