1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
// Location: ./crates/cpex-core/src/hooks/trait_def.rs
// Copyright 2025
// SPDX-License-Identifier: Apache-2.0
// Authors: Teryl Taylor
//
// HookTypeDef trait and PluginResult type.
//
// Every hook in the CPEX framework is defined by a marker type that
// implements HookTypeDef. This associates a typed PluginPayload and
// PluginResult with a string name used for registry lookup and config.
//
// The hook type does NOT declare an access pattern (read-only vs
// mutating). The plugin's mode (from PluginRef.trusted_config)
// determines scheduling and authority at runtime. Security invariants
// come from the types inside the payload (Arc<T>, MonotonicSet,
// Guarded<T>), not from borrow mechanics.
//
// Extensions are always a separate parameter — never part of the
// payload. This allows capability-filtered views per plugin and
// independent modification of extensions without copying the payload.
use cratePluginContext;
use cratePluginViolation;
use crate;
use cratePlugin;
// ---------------------------------------------------------------------------
// HookTypeDef Trait
// ---------------------------------------------------------------------------
/// Defines a hook's contract: what goes in and what comes out.
///
/// Each hook type is a zero-sized marker struct that implements this
/// trait. The framework uses the associated types for compile-time
/// dispatch and the NAME constant for registry lookup.
///
/// The hook type does **not** declare an access pattern. The plugin's
/// mode (from `PluginRef.trusted_config`) determines whether the
/// executor passes a borrow or a clone:
///
/// | Mode | Receives | Can Block? | Can Modify? |
/// |-----------------|-----------------|------------|-------------|
/// | Sequential | owned (clone) | Yes | Yes |
/// | Transform | owned (clone) | No | Yes |
/// | Audit | &Payload | No | No |
/// | Concurrent | &Payload | Yes | No |
/// | FireAndForget | &Payload | No | No |
///
/// # Defining a Hook
///
/// Use the [`define_hook!`] macro instead of implementing this trait
/// manually — the macro generates the marker struct, the trait impl,
/// and the handler trait in one declaration.
// ---------------------------------------------------------------------------
// Hook Handler Trait
// ---------------------------------------------------------------------------
/// Typed handler for a specific hook type.
///
/// Plugin authors implement this trait (alongside [`Plugin`]) to handle
/// a specific hook. The type parameter `H` ties the handler to a
/// `HookTypeDef`, ensuring the correct payload and result types at
/// compile time. The framework creates a type-erased adapter internally
/// when you register — you never touch `AnyHookHandler` directly.
///
/// # Async by design
///
/// `handle` is an `async fn`. Plugins that don't need to `.await`
/// anything still write `async fn handle(...)` and return synchronously
/// — the compiler emits a trivially-ready future and LLVM inlines it
/// at the adapter site, so there's no observable runtime cost over a
/// plain function. Plugins that *do* need to `.await` (fresh JWKS
/// fetch, RPC to an authz service, dynamic policy lookup) just use
/// `.await` inside the body.
///
/// **Best practice:** even when async is available, prefer pre-loading
/// state in [`Plugin::initialize`] and reading from cache in `handle`.
/// Hot-path I/O is the most common source of latency regressions.
///
/// # Native AFIT, not `#[async_trait]`
///
/// The trait uses native `async fn` (return-position `impl Future`)
/// rather than `#[async_trait]`. This avoids a per-call heap
/// allocation: the returned future is monomorphized into the
/// [`TypedHandlerAdapter`] rather than boxed. The trait is therefore
/// **not object-safe** — you cannot have `Box<dyn HookHandler<H>>`.
/// We don't need that; type erasure happens one layer up at
/// [`AnyHookHandler`].
///
/// # Examples
///
/// ```rust,ignore
/// // Synchronous plugin — no .await, no extra cost
/// impl HookHandler<CmfHook> for AllowPlugin {
/// async fn handle(
/// &self,
/// _payload: &MessagePayload,
/// _extensions: &Extensions,
/// _ctx: &mut PluginContext,
/// ) -> PluginResult<MessagePayload> {
/// PluginResult::allow()
/// }
/// }
///
/// // Async plugin — calls .await inside the body
/// impl HookHandler<MyHook> for AuthzPlugin {
/// async fn handle(
/// &self,
/// payload: &MyPayload,
/// _extensions: &Extensions,
/// _ctx: &mut PluginContext,
/// ) -> PluginResult<MyPayload> {
/// match self.client.check(&payload.user).await {
/// Ok(true) => PluginResult::allow(),
/// _ => PluginResult::deny(/* ... */),
/// }
/// }
/// }
///
/// // Registration is the same for both:
/// manager.register_handler::<MyHook, _>(plugin, config)?;
/// ```
///
/// [`PluginManager::register_handler`]: crate::manager::PluginManager::register_handler
/// [`AnyHookHandler`]: crate::registry::AnyHookHandler
/// [`TypedHandlerAdapter`]: crate::hooks::adapter::TypedHandlerAdapter
// ---------------------------------------------------------------------------
// Plugin Result
// ---------------------------------------------------------------------------
/// Result returned by a hook handler.
///
/// Payload and extension modifications are **separate** — this is a
/// core design decision. Extension-only changes (add a label, set a
/// header) don't require copying the payload. The payload is only
/// present in `modified_payload` when message content actually changed.
///
/// The executor interprets the result based on the plugin's mode:
/// - Sequential/Transform: `modified_payload` and `modified_extensions` are accepted.
/// - Audit/Concurrent/FireAndForget: modifications are discarded.
/// - Sequential/Concurrent: `continue_processing = false` halts the pipeline.
/// - Transform/Audit/FireAndForget: blocks are suppressed.
///
/// Mirrors Python's `PluginResult[T]` with separate `modified_payload`
/// and `modified_extensions` fields.
///
/// # Examples
///
/// ```
/// use cpex_core::hooks::{PluginPayload, PluginResult};
/// use cpex_core::error::PluginViolation;
///
/// // Define a simple payload
/// #[derive(Debug, Clone)]
/// struct TestPayload { value: i32 }
/// cpex_core::impl_plugin_payload!(TestPayload);
///
/// // Allow — no changes
/// let result: PluginResult<TestPayload> = PluginResult::allow();
/// assert!(result.continue_processing);
/// assert!(result.modified_payload.is_none());
///
/// // Deny
/// let result: PluginResult<TestPayload> = PluginResult::deny(
/// PluginViolation::new("forbidden", "not allowed")
/// );
/// assert!(!result.continue_processing);
/// assert!(result.violation.is_some());
/// ```