dmsc/c/
hooks.rs

1//! Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
2//!
3//! This file is part of DMSC.
4//! The DMSC project belongs to the Dunimd Team.
5//!
6//! Licensed under the Apache License, Version 2.0 (the "License");
7//! You may not use this file except in compliance with the License.
8//! You may obtain a copy of the License at
9//!
10//!     http://www.apache.org/licenses/LICENSE-2.0
11//!
12//! Unless required by applicable law or agreed to in writing, software
13//! distributed under the License is distributed on an "AS IS" BASIS,
14//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15//! See the License for the specific language governing permissions and
16//! limitations under the License.
17
18//! # Hooks Module C API
19//!
20//! This module provides C language bindings for DMSC's hook system. The hooks module enables
21//! extensible application behavior through a publish-subscribe pattern where components can
22//! register callback functions (hooks) that are invoked at specific points in the application
23//! lifecycle or in response to specific events. This C API enables C/C++ applications to
24//! leverage DMSC's extensibility mechanisms for building modular and customizable applications.
25//!
26//! ## Module Architecture
27//!
28//! The hooks module centers around a single primary component:
29//!
30//! - **DMSCHookBus**: Central event bus for registering hooks and dispatching events. The hook
31//!   bus manages the complete lifecycle of hooks including registration, invocation, and
32//!   unregistration. It provides a thread-safe mechanism for components to communicate through
33//!   loosely-coupled event handlers.
34//!
35//! ## Hook Concepts
36//!
37//! The hook system implements several key concepts:
38//!
39//! - **Hooks**: Callback functions registered at specific points in the application lifecycle.
40//!   Hooks can modify behavior, perform side effects, or transform data as it flows through
41//!   the system.
42//!
43//! - **Hook Points**: Well-defined locations in the code where registered hooks are invoked.
44//!   Common hook points include application startup, shutdown, request processing, error
45//!   handling, and custom business events.
46//!
47//! - **Hook Priority**: Ordering mechanism that controls the sequence of hook execution when
48//!   multiple hooks are registered at the same hook point. Higher priority hooks execute first.
49//!
50//! - **Hook Context**: Data passed to hooks containing information about the event and allowing
51//!   hooks to communicate through shared context.
52//!
53//! - **Hook Filters**: Capability for hooks to filter whether they should be invoked based on
54//!   event properties without full registration overhead.
55//!
56//! ## Hook Types
57//!
58//! The system supports various hook types for different use cases:
59//!
60//! - **Synchronous Hooks**: Execute immediately when the hook point is reached. Most common
61//!   type for application extension. Blocking until all hooks complete.
62//!
63//! - **Asynchronous Hooks**: Execute in the background without blocking the main flow. Useful
64//!   for logging, metrics, or long-running operations that shouldn't delay primary processing.
65//!
66//! - **One-Time Hooks**: Execute only once, then automatically unregister. Useful for
67//!   initialization or cleanup tasks that should run a single time.
68//!
69//! - **Conditional Hooks**: Only execute when specific conditions are met. Conditions checked
70//!   before invoking the hook function, reducing overhead for hooks that rarely apply.
71//!
72//! - **Transform Hooks**: Modify data passing through the hook point. Data is passed to the
73//!   hook, transformed, and passed to the next hook or back to the caller.
74//!
75//! ## Hook Bus Architecture
76//!
77//! The hook bus implements a centralized event distribution system:
78//!
79//! - **Event Dispatching**: Efficient routing of events to registered hooks based on hook point.
80//!   Supports both synchronous and asynchronous dispatch.
81//!
82//! - **Hook Registration**: Thread-safe registration of hooks with priority, filters, and
83//!   configuration options. Supports registration during any phase of application lifecycle.
84//!
85//! - **Error Handling**: Configurable behavior when hooks return errors including stop-on-error,
86//!   continue-with-error, and error logging strategies.
87//!
88//! - **Performance Optimization**: Batch dispatch, hook filtering, and lazy evaluation minimize
89//!   overhead for high-frequency hook points.
90//!
91//! ## Common Hook Points
92//!
93//! The DMSC framework defines standard hook points:
94//!
95//! - **Application Lifecycle Hooks**: pre_startup, post_startup, pre_shutdown, post_shutdown
96//! - **Request Processing Hooks**: pre_request, post_request, on_error
97//! - **Configuration Hooks**: pre_config_load, post_config_load, on_config_change
98//! - **Logging Hooks**: on_log_message, on_log_level_change
99//! - **Custom Application Hooks**: Application-defined event types
100//!
101//! ## Hook Priority System
102//!
103//! Hooks execute in priority order from highest to lowest:
104//!
105//! - **System Hooks** (1000-900): Reserved for DMSC framework internal use
106//! - **High Priority** (800-600): Critical application extensions
107//! - **Normal Priority** (500-400): Standard application hooks
108//! - **Low Priority** (300-200): Monitoring and observability hooks
109//! - **System Low** (100-0): Reserved for cleanup and finalization
110//!
111//! Equal priority hooks execute in registration order. Consider using explicit priorities
112//! rather than relying on registration order for reproducibility.
113//!
114//! ## Memory Management
115//!
116//! All C API objects use opaque pointers with manual memory management:
117//!
118//! - Constructor functions allocate new instances on the heap
119//! - Destructor functions must be called to release memory
120//! - Hook callbacks must be properly unregistered before freeing context
121//! - Hook context data must be freed by the application
122//!
123//! ## Thread Safety
124//!
125//! The underlying implementations are thread-safe:
126//!
127//! - Hook registration is safe from any thread
128//! - Hook invocation occurs in the context of the triggering code
129//! - Asynchronous hooks run in a thread pool
130//! - Concurrent hook dispatch uses internal synchronization
131//!
132//! ## Performance Characteristics
133//!
134//! Hook operations have the following performance profiles:
135//!
136//! - Hook registration: O(1) amortized
137//! - Hook lookup: O(log n) where n is registered hook count
138//! - Synchronous dispatch: O(n * t) where n is hook count, t is execution time
139//! - Asynchronous dispatch: O(1) to queue, O(n * t) in thread pool
140//!
141//! ## Usage Example
142//!
143//! ```c
144//! // Create hook bus instance
145//! DMSCHookBus* bus = dmsc_hook_bus_new();
146//! if (bus == NULL) {
147//!     fprintf(stderr, "Failed to create hook bus\n");
148//!     return ERROR_INIT;
149//! }
150//!
151//! // Register startup hook
152//! int startup_result = dmsc_hook_bus_register(
153//!     bus,
154//!     "pre_startup",
155//!     500,  // normal priority
156//!     on_startup_hook,
157//!     NULL  // user data
158//! );
159//!
160//! if (startup_result != 0) {
161//!     fprintf(stderr, "Failed to register startup hook\n");
162//! }
163//!
164//! // Register request processing hook
165//! dmsc_hook_bus_register(bus, "pre_request", 500, on_pre_request, NULL);
166//! dmsc_hook_bus_register(bus, "post_request", 500, on_post_request, NULL);
167//!
168//! // Register shutdown hook
169//! dmsc_hook_bus_register(bus, "pre_shutdown", 300, on_shutdown, NULL);
170//!
171//! // Trigger custom event
172//! DMSCHookContext* context = dmsc_hook_context_create();
173//! dmsc_hook_context_set_string(context, "event_name", "user_action");
174//! dmsc_hook_context_set_int(context, "user_id", 12345);
175//!
176//! dmsc_hook_bus_dispatch(bus, "on_user_action", context);
177//!
178//! dmsc_hook_context_free(context);
179//!
180//! // Unregister hooks before shutdown
181//! dmsc_hook_bus_unregister(bus, "pre_startup", on_startup_hook);
182//! dmsc_hook_bus_unregister(bus, "pre_request", on_pre_request);
183//! dmsc_hook_bus_unregister(bus, "post_request", on_post_request);
184//! dmsc_hook_bus_unregister(bus, "pre_shutdown", on_shutdown);
185//!
186//! // Cleanup
187//! dmsc_hook_bus_free(bus);
188//! ```
189//!
190//! ## Hook Callback Signature
191//!
192//! Hook callbacks must conform to the following signature:
193//!
194//! ```c
195//! typedef int (*DMSCHookCallback)(
196//!     const char* hook_point,      // Name of the hook point
197//!     DMSCHookContext* context,     // Event context data
198//!     void* user_data              // User-provided data
199//! );
200//! ```
201//!
202//! Return values:
203//!
204//! - 0: Success, continue processing other hooks
205//! - Positive: Success with value, stop processing if configured
206//! - Negative: Error, stop processing if configured
207//!
208//! ## Dependencies
209//!
210//! This module depends on the following DMSC components:
211//!
212//! - `crate::hooks`: Rust hooks module implementation
213//! - `crate::prelude`: Common types and traits
214//!
215//! ## Feature Flags
216//!
217//! The hooks module is always enabled as it provides fundamental extensibility
218//! infrastructure for DMSC applications.
219
220use crate::hooks::DMSCHookBus;
221
222
223c_wrapper!(CDMSCHookBus, DMSCHookBus);
224
225// DMSCHookBus constructors and destructors
226#[no_mangle]
227pub extern "C" fn dmsc_hook_bus_new() -> *mut CDMSCHookBus {
228    let bus = DMSCHookBus::new();
229    Box::into_raw(Box::new(CDMSCHookBus::new(bus)))
230}
231c_destructor!(dmsc_hook_bus_free, CDMSCHookBus);