Skip to main content

player_plugin/
hook.rs

1use std::collections::BTreeMap;
2
3use serde::{Deserialize, Serialize};
4use thiserror::Error;
5
6use crate::{
7    MAX_PLUGIN_DIAGNOSTICS, MAX_PLUGIN_ERROR_MESSAGE_BYTES, MAX_PLUGIN_EVENT_ID_BYTES,
8    MAX_PLUGIN_EVENT_NAME_BYTES, MAX_PLUGIN_MEASUREMENTS, MAX_PLUGIN_PLATFORM_BYTES,
9    MAX_PLUGIN_PROTOCOL_BYTES, MAX_PLUGIN_RESOURCE_IDENTITY_BYTES, MAX_PLUGIN_THREAD_BYTES,
10    PluginDiagnostic, PluginMeasurement, PluginProtocolViolation,
11    protocol::{validate_attributes, validate_optional_text, validate_text},
12};
13
14/// One bounded, transport-neutral event emitted by a host pipeline.
15#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
16#[serde(rename_all = "camelCase")]
17pub struct PipelineEvent {
18    pub run_id: String,
19    pub session_id: String,
20    pub platform: String,
21    pub protocol: Option<String>,
22    pub event_name: String,
23    pub timestamp_ns: u64,
24    pub thread: Option<String>,
25    pub resource_identity: Option<String>,
26    #[serde(default)]
27    pub attributes: BTreeMap<String, String>,
28    pub diagnostic: Option<PluginDiagnostic>,
29}
30
31impl PipelineEvent {
32    pub fn validate(&self) -> Result<(), PipelineEventHookError> {
33        validate_text(
34            "pipeline_event.run_id",
35            &self.run_id,
36            MAX_PLUGIN_EVENT_ID_BYTES,
37        )?;
38        validate_text(
39            "pipeline_event.session_id",
40            &self.session_id,
41            MAX_PLUGIN_EVENT_ID_BYTES,
42        )?;
43        validate_text(
44            "pipeline_event.platform",
45            &self.platform,
46            MAX_PLUGIN_PLATFORM_BYTES,
47        )?;
48        validate_optional_text(
49            "pipeline_event.protocol",
50            self.protocol.as_deref(),
51            MAX_PLUGIN_PROTOCOL_BYTES,
52        )?;
53        validate_text(
54            "pipeline_event.event_name",
55            &self.event_name,
56            MAX_PLUGIN_EVENT_NAME_BYTES,
57        )?;
58        validate_optional_text(
59            "pipeline_event.thread",
60            self.thread.as_deref(),
61            MAX_PLUGIN_THREAD_BYTES,
62        )?;
63        validate_optional_text(
64            "pipeline_event.resource_identity",
65            self.resource_identity.as_deref(),
66            MAX_PLUGIN_RESOURCE_IDENTITY_BYTES,
67        )?;
68        validate_attributes(&self.attributes)?;
69        if let Some(diagnostic) = &self.diagnostic {
70            diagnostic.validate()?;
71        }
72        Ok(())
73    }
74}
75
76#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
77#[serde(rename_all = "camelCase")]
78pub struct PipelineEventHookOutcome {
79    pub accepted: bool,
80    #[serde(default)]
81    pub measurements: Vec<PluginMeasurement>,
82    #[serde(default)]
83    pub diagnostics: Vec<PluginDiagnostic>,
84}
85
86impl PipelineEventHookOutcome {
87    pub fn accepted() -> Self {
88        Self {
89            accepted: true,
90            ..Self::default()
91        }
92    }
93
94    pub fn validate(&self) -> Result<(), PipelineEventHookError> {
95        if self.measurements.len() > MAX_PLUGIN_MEASUREMENTS {
96            return Err(PipelineEventHookError::ProtocolViolation(format!(
97                "event hook returned more than {MAX_PLUGIN_MEASUREMENTS} measurements"
98            )));
99        }
100        if self.diagnostics.len() > MAX_PLUGIN_DIAGNOSTICS {
101            return Err(PipelineEventHookError::ProtocolViolation(format!(
102                "event hook returned more than {MAX_PLUGIN_DIAGNOSTICS} diagnostics"
103            )));
104        }
105        for measurement in &self.measurements {
106            measurement.validate()?;
107        }
108        for diagnostic in &self.diagnostics {
109            diagnostic.validate()?;
110        }
111        Ok(())
112    }
113}
114
115/// A failure reported by Native event-hook author code.
116///
117/// Native adapters validate the message before exporting the existing error payload.
118#[derive(Debug, Error, Clone, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(rename_all = "camelCase", tag = "code", content = "message")]
120pub enum PipelineEventHookFailure {
121    #[error("event hook rejected invalid input: {0}")]
122    InvalidInput(String),
123    #[error("event hook rejected the event: {0}")]
124    Rejected(String),
125    #[error("event hook failed: {0}")]
126    Failed(String),
127}
128
129impl PipelineEventHookFailure {
130    /// Checks the established 1–256 UTF-8 byte message limit without changing the text.
131    pub fn validate(&self) -> Result<(), PluginProtocolViolation> {
132        let message = match self {
133            Self::InvalidInput(message) | Self::Rejected(message) | Self::Failed(message) => {
134                message
135            }
136        };
137        validate_failure_message(message)
138    }
139}
140
141/// Host-facing errors, including failures reported by a plugin.
142#[derive(Debug, Error, Clone, PartialEq, Eq, Serialize, Deserialize)]
143#[serde(rename_all = "camelCase", tag = "code", content = "message")]
144pub enum PipelineEventHookError {
145    #[error("event hook rejected invalid input: {0}")]
146    InvalidInput(String),
147    #[error("payload codec error: {0}")]
148    PayloadCodec(String),
149    #[error("plugin ABI violation: {0}")]
150    AbiViolation(String),
151    #[error("event hook rejected the event: {0}")]
152    Rejected(String),
153    #[error("event hook failed: {0}")]
154    Failed(String),
155    #[error("event hook protocol violation: {0}")]
156    ProtocolViolation(String),
157}
158
159impl PipelineEventHookError {
160    /// Projects a diagnostic into the existing mobile report message budget.
161    ///
162    /// The code is preserved. Only the outward copy is truncated on a UTF-8
163    /// boundary; internal reports retain the complete diagnostic. This is not
164    /// author-failure validation and must not be used when checking artifact bytes.
165    pub fn report_projection(&self) -> Self {
166        let project = |message: &str| {
167            if message.is_empty() {
168                "plugin host error".to_owned()
169            } else {
170                message[..message.floor_char_boundary(MAX_PLUGIN_ERROR_MESSAGE_BYTES)].to_owned()
171            }
172        };
173        match self {
174            Self::InvalidInput(message) => Self::InvalidInput(project(message)),
175            Self::PayloadCodec(message) => Self::PayloadCodec(project(message)),
176            Self::AbiViolation(message) => Self::AbiViolation(project(message)),
177            Self::Rejected(message) => Self::Rejected(project(message)),
178            Self::Failed(message) => Self::Failed(project(message)),
179            Self::ProtocolViolation(message) => Self::ProtocolViolation(project(message)),
180        }
181    }
182
183    pub fn validate_author_failure(&self) -> Result<(), Self> {
184        let message = match self {
185            Self::InvalidInput(message) | Self::Rejected(message) | Self::Failed(message) => {
186                message
187            }
188            Self::PayloadCodec(_) | Self::AbiViolation(_) | Self::ProtocolViolation(_) => {
189                return Err(Self::ProtocolViolation(
190                    "plugin returned a host-owned event-hook error kind".to_owned(),
191                ));
192            }
193        };
194        validate_failure_message(message).map_err(Self::from)
195    }
196}
197
198fn validate_failure_message(message: &str) -> Result<(), PluginProtocolViolation> {
199    validate_text(
200        "event_hook.error.message",
201        message,
202        MAX_PLUGIN_ERROR_MESSAGE_BYTES,
203    )
204}
205
206impl From<PipelineEventHookFailure> for PipelineEventHookError {
207    fn from(value: PipelineEventHookFailure) -> Self {
208        match value {
209            PipelineEventHookFailure::InvalidInput(message) => Self::InvalidInput(message),
210            PipelineEventHookFailure::Rejected(message) => Self::Rejected(message),
211            PipelineEventHookFailure::Failed(message) => Self::Failed(message),
212        }
213    }
214}
215
216/// A Native plugin's event-hook implementation, registered with [`crate::PluginBuilder`].
217///
218/// Host ABI errors cannot be returned by author code:
219///
220/// ```compile_fail,E0308
221/// use player_plugin::{
222///     PipelineEvent, PipelineEventHookError, PipelineEventHookFailure,
223///     PipelineEventHookOutcome, PluginEventHook,
224/// };
225///
226/// struct Hook;
227/// impl PluginEventHook for Hook {
228///     fn on_event(&self, _: &PipelineEvent)
229///         -> Result<PipelineEventHookOutcome, PipelineEventHookFailure>
230///     {
231///         Err(PipelineEventHookError::AbiViolation("host-only error".to_owned()))
232///     }
233/// }
234/// ```
235pub trait PluginEventHook: Send + Sync {
236    fn on_event(
237        &self,
238        event: &PipelineEvent,
239    ) -> Result<PipelineEventHookOutcome, PipelineEventHookFailure>;
240}
241
242impl From<PluginProtocolViolation> for PipelineEventHookError {
243    fn from(value: PluginProtocolViolation) -> Self {
244        Self::ProtocolViolation(value.to_string())
245    }
246}
247
248/// A checked host capability. Native authors implement [`PluginEventHook`].
249pub trait PipelineEventHook: Send + Sync {
250    fn on_event(
251        &self,
252        event: &PipelineEvent,
253    ) -> Result<PipelineEventHookOutcome, PipelineEventHookError>;
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259
260    fn event() -> PipelineEvent {
261        PipelineEvent {
262            run_id: "run-1".to_owned(),
263            session_id: "session-1".to_owned(),
264            platform: "test".to_owned(),
265            protocol: Some("hls".to_owned()),
266            event_name: "download.completed".to_owned(),
267            timestamp_ns: 1,
268            thread: None,
269            resource_identity: Some("download-task:1".to_owned()),
270            attributes: BTreeMap::new(),
271            diagnostic: None,
272        }
273    }
274
275    #[test]
276    fn event_validates_transport_fields_and_structured_diagnostic() {
277        let mut event = event();
278        assert_eq!(event.validate(), Ok(()));
279
280        event.platform.clear();
281        assert!(matches!(
282            event.validate(),
283            Err(PipelineEventHookError::ProtocolViolation(_))
284        ));
285
286        event.platform = "test".to_owned();
287        event.diagnostic = Some(PluginDiagnostic {
288            code: "x".repeat(65),
289            severity: crate::PluginDiagnosticSeverity::Error,
290            message: "invalid diagnostic".to_owned(),
291            attributes: BTreeMap::new(),
292        });
293        assert!(matches!(
294            event.validate(),
295            Err(PipelineEventHookError::ProtocolViolation(_))
296        ));
297    }
298
299    #[test]
300    fn event_accepts_awkward_valid_utf8_without_rewriting_identity() {
301        let mut event = event();
302        event.resource_identity = Some("opaque:资源 identity/with spaces".to_owned());
303        assert_eq!(event.validate(), Ok(()));
304        assert_eq!(
305            event.resource_identity.as_deref(),
306            Some("opaque:资源 identity/with spaces")
307        );
308    }
309
310    #[test]
311    fn outcome_rejects_non_finite_measurement() {
312        let outcome = PipelineEventHookOutcome {
313            accepted: true,
314            measurements: vec![PluginMeasurement {
315                name: "latency".to_owned(),
316                value: f64::INFINITY,
317                unit: "ms".to_owned(),
318                attributes: Default::default(),
319            }],
320            diagnostics: Vec::new(),
321        };
322        assert!(matches!(
323            outcome.validate(),
324            Err(PipelineEventHookError::ProtocolViolation(_))
325        ));
326    }
327}