Skip to main content

player_plugin/
sdk.rs

1//! Safe author-facing construction and generated native adapters.
2
3#![deny(unsafe_code)]
4
5use std::collections::HashSet;
6use std::path::Path;
7use std::sync::Arc;
8
9use player_plugin_abi::export::{
10    ExportFailure, ExportInterface as RawExportInterface, ExportInterfaceKind, ExportInvocation,
11    ExportOperation, ExportPlugin as RawExportPlugin, ExportProgress,
12};
13use player_plugin_abi::{
14    VESPER_MAX_CAPABILITY_INSTANCE_ID_BYTES, VESPER_MAX_PLUGIN_ID_BYTES,
15    VESPER_MAX_PLUGIN_NAME_BYTES, status,
16};
17use serde::Serialize;
18use serde::de::DeserializeOwned;
19use thiserror::Error;
20
21use crate::plugin_reference::is_reverse_dns;
22use crate::{
23    BenchmarkEventBatch, BenchmarkSinkError, MAX_PIPELINE_EVENT_INPUT_BYTES, PipelineEvent,
24    PipelineEventHookError, PluginBenchmarkSink, PluginEventHook, PostDownloadProcessor,
25    ProcessorError, ProcessorProgress,
26};
27
28mod session;
29mod session_capabilities;
30
31/// Capability families that can be exported by a native Rust plugin.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
33pub enum PluginCapability {
34    PostDownloadProcessor,
35    PipelineEventHook,
36    BenchmarkSink,
37    NativeDecoder,
38    FrameProcessor,
39    AudioProcessor,
40    SourceNormalizerPacket,
41    SourceNormalizerResource,
42}
43
44impl From<ExportInterfaceKind> for PluginCapability {
45    fn from(value: ExportInterfaceKind) -> Self {
46        match value {
47            ExportInterfaceKind::PostDownloadProcessor => Self::PostDownloadProcessor,
48            ExportInterfaceKind::PipelineEventHook => Self::PipelineEventHook,
49            ExportInterfaceKind::BenchmarkSink => Self::BenchmarkSink,
50            ExportInterfaceKind::NativeDecoder => Self::NativeDecoder,
51            ExportInterfaceKind::FrameProcessor => Self::FrameProcessor,
52            ExportInterfaceKind::AudioProcessor => Self::AudioProcessor,
53            ExportInterfaceKind::SourceNormalizerPacket => Self::SourceNormalizerPacket,
54            ExportInterfaceKind::SourceNormalizerResource => Self::SourceNormalizerResource,
55        }
56    }
57}
58
59/// Errors reported while constructing one exported plugin root.
60#[derive(Debug, Error, Clone, PartialEq, Eq)]
61pub enum PluginBuildError {
62    #[error("plugin_id must be a valid reverse-DNS identity")]
63    InvalidPluginId,
64    #[error("capability instance id must be a valid reverse-DNS identity")]
65    InvalidCapabilityInstanceId,
66    #[error("plugin_name must contain between 1 and {VESPER_MAX_PLUGIN_NAME_BYTES} UTF-8 bytes")]
67    InvalidPluginName,
68    #[error("plugin must expose at least one capability interface")]
69    NoInterfaces,
70    #[error("duplicate {capability:?} capability instance `{instance_id}`")]
71    DuplicateInterface {
72        capability: PluginCapability,
73        instance_id: String,
74    },
75}
76
77/// Safe builder used by Rust plugin authors.
78pub struct PluginBuilder {
79    plugin_id: String,
80    plugin_name: String,
81    interfaces: Vec<Arc<dyn RawExportInterface>>,
82    interface_keys: HashSet<(ExportInterfaceKind, String)>,
83}
84
85impl PluginBuilder {
86    pub fn new(
87        plugin_id: impl Into<String>,
88        plugin_name: impl Into<String>,
89    ) -> Result<Self, PluginBuildError> {
90        let plugin_id = plugin_id.into();
91        if !is_reverse_dns(&plugin_id, VESPER_MAX_PLUGIN_ID_BYTES) {
92            return Err(PluginBuildError::InvalidPluginId);
93        }
94        let plugin_name = plugin_name.into();
95        if plugin_name.is_empty() || plugin_name.len() > VESPER_MAX_PLUGIN_NAME_BYTES {
96            return Err(PluginBuildError::InvalidPluginName);
97        }
98        Ok(Self {
99            plugin_id,
100            plugin_name,
101            interfaces: Vec::new(),
102            interface_keys: HashSet::new(),
103        })
104    }
105
106    pub fn with_post_download_processor<P>(
107        self,
108        instance_id: impl Into<String>,
109        processor: P,
110    ) -> Result<Self, PluginBuildError>
111    where
112        P: PostDownloadProcessor + 'static,
113    {
114        let instance_id = instance_id.into();
115        self.with_interface(
116            ExportInterfaceKind::PostDownloadProcessor,
117            instance_id.clone(),
118            Arc::new(PostDownloadAdapter {
119                instance_id,
120                processor,
121            }),
122        )
123    }
124
125    /// Registers a Native author hook. Checked host capabilities are not author implementations.
126    ///
127    /// ```compile_fail,E0277
128    /// use player_plugin::{PipelineEventHook, PluginBuildError, PluginBuilder};
129    ///
130    /// fn register<H: PipelineEventHook + 'static>(hook: H) -> Result<PluginBuilder, PluginBuildError> {
131    ///     PluginBuilder::new("dev.example.plugin", "Example")?
132    ///         .with_pipeline_event_hook("dev.example.plugin.hook", hook)
133    /// }
134    /// ```
135    pub fn with_pipeline_event_hook<H>(
136        self,
137        instance_id: impl Into<String>,
138        hook: H,
139    ) -> Result<Self, PluginBuildError>
140    where
141        H: PluginEventHook + 'static,
142    {
143        let instance_id = instance_id.into();
144        self.with_interface(
145            ExportInterfaceKind::PipelineEventHook,
146            instance_id.clone(),
147            Arc::new(PipelineEventHookAdapter { instance_id, hook }),
148        )
149    }
150
151    /// Registers a Native author sink. Checked host capabilities are not author implementations.
152    ///
153    /// ```compile_fail,E0277
154    /// use player_plugin::{BenchmarkSink, PluginBuildError, PluginBuilder};
155    ///
156    /// fn register<S: BenchmarkSink + 'static>(sink: S) -> Result<PluginBuilder, PluginBuildError> {
157    ///     PluginBuilder::new("dev.example.plugin", "Example")?
158    ///         .with_benchmark_sink("dev.example.plugin.benchmark", sink)
159    /// }
160    /// ```
161    pub fn with_benchmark_sink<S>(
162        self,
163        instance_id: impl Into<String>,
164        sink: S,
165    ) -> Result<Self, PluginBuildError>
166    where
167        S: PluginBenchmarkSink + 'static,
168    {
169        let instance_id = instance_id.into();
170        self.with_interface(
171            ExportInterfaceKind::BenchmarkSink,
172            instance_id.clone(),
173            Arc::new(BenchmarkSinkAdapter { instance_id, sink }),
174        )
175    }
176
177    pub fn with_native_decoder<F>(
178        self,
179        instance_id: impl Into<String>,
180        factory: F,
181    ) -> Result<Self, PluginBuildError>
182    where
183        F: crate::NativeDecoderPluginFactory + 'static,
184    {
185        let instance_id = instance_id.into();
186        self.with_interface(
187            ExportInterfaceKind::NativeDecoder,
188            instance_id.clone(),
189            Arc::new(session_capabilities::NativeDecoderAdapter::new(
190                instance_id,
191                factory,
192            )),
193        )
194    }
195
196    pub fn with_frame_processor<F>(
197        self,
198        instance_id: impl Into<String>,
199        factory: F,
200    ) -> Result<Self, PluginBuildError>
201    where
202        F: crate::FrameProcessorPluginFactory + 'static,
203    {
204        let instance_id = instance_id.into();
205        self.with_interface(
206            ExportInterfaceKind::FrameProcessor,
207            instance_id.clone(),
208            Arc::new(session_capabilities::FrameProcessorAdapter::new(
209                instance_id,
210                factory,
211            )),
212        )
213    }
214
215    pub fn with_audio_processor<F>(
216        self,
217        instance_id: impl Into<String>,
218        factory: F,
219    ) -> Result<Self, PluginBuildError>
220    where
221        F: crate::AudioProcessorPluginFactory + 'static,
222    {
223        let instance_id = instance_id.into();
224        self.with_interface(
225            ExportInterfaceKind::AudioProcessor,
226            instance_id.clone(),
227            Arc::new(session_capabilities::AudioProcessorAdapter::new(
228                instance_id,
229                factory,
230            )),
231        )
232    }
233
234    pub fn with_source_normalizer_packet<F>(
235        self,
236        instance_id: impl Into<String>,
237        factory: F,
238    ) -> Result<Self, PluginBuildError>
239    where
240        F: crate::SourceNormalizerPacketPluginFactory + 'static,
241    {
242        let instance_id = instance_id.into();
243        self.with_interface(
244            ExportInterfaceKind::SourceNormalizerPacket,
245            instance_id.clone(),
246            Arc::new(session_capabilities::SourceNormalizerPacketAdapter::new(
247                instance_id,
248                factory,
249            )),
250        )
251    }
252
253    pub fn with_source_normalizer_resource<F>(
254        self,
255        instance_id: impl Into<String>,
256        factory: F,
257    ) -> Result<Self, PluginBuildError>
258    where
259        F: crate::SourceNormalizerResourcePluginFactory + 'static,
260    {
261        let instance_id = instance_id.into();
262        self.with_interface(
263            ExportInterfaceKind::SourceNormalizerResource,
264            instance_id.clone(),
265            Arc::new(session_capabilities::SourceNormalizerResourceAdapter::new(
266                instance_id,
267                factory,
268            )),
269        )
270    }
271
272    pub fn build(self) -> Result<Plugin, PluginBuildError> {
273        if self.interfaces.is_empty() {
274            return Err(PluginBuildError::NoInterfaces);
275        }
276        Ok(Plugin {
277            plugin_id: self.plugin_id,
278            plugin_name: self.plugin_name,
279            interfaces: self.interfaces,
280        })
281    }
282
283    fn with_interface(
284        mut self,
285        kind: ExportInterfaceKind,
286        instance_id: String,
287        interface: Arc<dyn RawExportInterface>,
288    ) -> Result<Self, PluginBuildError> {
289        if !is_reverse_dns(&instance_id, VESPER_MAX_CAPABILITY_INSTANCE_ID_BYTES) {
290            return Err(PluginBuildError::InvalidCapabilityInstanceId);
291        }
292        if !self.interface_keys.insert((kind, instance_id.clone())) {
293            return Err(PluginBuildError::DuplicateInterface {
294                capability: kind.into(),
295                instance_id,
296            });
297        }
298        self.interfaces.push(interface);
299        Ok(self)
300    }
301}
302
303/// Fully validated plugin definition returned by an exported factory.
304pub struct Plugin {
305    plugin_id: String,
306    plugin_name: String,
307    interfaces: Vec<Arc<dyn RawExportInterface>>,
308}
309
310impl Plugin {
311    pub fn builder(
312        plugin_id: impl Into<String>,
313        plugin_name: impl Into<String>,
314    ) -> Result<PluginBuilder, PluginBuildError> {
315        PluginBuilder::new(plugin_id, plugin_name)
316    }
317
318    fn invalid() -> Self {
319        Self {
320            plugin_id: String::new(),
321            plugin_name: String::new(),
322            interfaces: Vec::new(),
323        }
324    }
325}
326
327impl RawExportPlugin for Plugin {
328    fn plugin_id(&self) -> &str {
329        &self.plugin_id
330    }
331
332    fn plugin_name(&self) -> &str {
333        &self.plugin_name
334    }
335
336    fn interfaces(&self) -> Vec<Arc<dyn RawExportInterface>> {
337        self.interfaces.clone()
338    }
339}
340
341#[doc(hidden)]
342pub trait PluginFactoryResult {
343    fn into_plugin(self) -> Option<Plugin>;
344}
345
346impl PluginFactoryResult for Plugin {
347    fn into_plugin(self) -> Option<Plugin> {
348        Some(self)
349    }
350}
351
352impl<E> PluginFactoryResult for Result<Plugin, E> {
353    fn into_plugin(self) -> Option<Plugin> {
354        self.ok()
355    }
356}
357
358pub(crate) fn export_plugin<R>(factory: fn() -> R) -> *const player_plugin_abi::VesperPluginRoot
359where
360    R: PluginFactoryResult,
361{
362    player_plugin_abi::export::export_plugin(move || {
363        factory().into_plugin().unwrap_or_else(Plugin::invalid)
364    })
365}
366
367impl ProcessorProgress for ExportProgress<'_> {
368    fn on_progress(&self, ratio: f32) {
369        ExportProgress::on_progress(self, f64::from(ratio));
370    }
371
372    fn is_cancelled(&self) -> bool {
373        ExportProgress::is_cancelled(self)
374    }
375}
376
377struct PostDownloadAdapter<P> {
378    instance_id: String,
379    processor: P,
380}
381
382impl<P> RawExportInterface for PostDownloadAdapter<P>
383where
384    P: PostDownloadProcessor,
385{
386    fn kind(&self) -> ExportInterfaceKind {
387        ExportInterfaceKind::PostDownloadProcessor
388    }
389
390    fn instance_id(&self) -> &str {
391        &self.instance_id
392    }
393
394    fn invoke(&self, operation: ExportOperation<'_>) -> Result<ExportInvocation, ExportFailure> {
395        match operation {
396            ExportOperation::Capabilities => json_invocation(&self.processor.capabilities()),
397            ExportOperation::PostDownloadProcess {
398                input_json,
399                output_path,
400                progress,
401                assemble,
402            } => {
403                let input =
404                    decode::<crate::CompletedDownloadInfo>(input_json).map_err(|error| {
405                        failure(
406                            status::INVALID_ARGUMENT,
407                            &ProcessorError::PayloadCodec(error),
408                        )
409                    })?;
410                let output_path = std::str::from_utf8(output_path).map_err(|error| {
411                    failure(
412                        status::INVALID_ARGUMENT,
413                        &ProcessorError::OutputPath(error.to_string()),
414                    )
415                })?;
416                let result = if assemble {
417                    self.processor
418                        .assemble(&input, Path::new(output_path), &progress)
419                } else {
420                    self.processor
421                        .process(&input, Path::new(output_path), &progress)
422                };
423                match result {
424                    Ok(output) => json_invocation(&output),
425                    Err(error) => {
426                        let status = match error {
427                            ProcessorError::Cancelled => status::CANCELLED,
428                            ProcessorError::AbiViolation(_) => status::ABI_VIOLATION,
429                            _ => status::FAILURE,
430                        };
431                        Err(failure(status, &error))
432                    }
433                }
434            }
435            _ => Err(unexpected_operation("post-download processor")),
436        }
437    }
438}
439
440struct PipelineEventHookAdapter<H> {
441    instance_id: String,
442    hook: H,
443}
444
445impl<H> RawExportInterface for PipelineEventHookAdapter<H>
446where
447    H: PluginEventHook,
448{
449    fn kind(&self) -> ExportInterfaceKind {
450        ExportInterfaceKind::PipelineEventHook
451    }
452
453    fn instance_id(&self) -> &str {
454        &self.instance_id
455    }
456
457    fn invoke(&self, operation: ExportOperation<'_>) -> Result<ExportInvocation, ExportFailure> {
458        let ExportOperation::PipelineEvent { event_json } = operation else {
459            return Err(unexpected_operation("pipeline event hook"));
460        };
461        if event_json.len() > MAX_PIPELINE_EVENT_INPUT_BYTES {
462            return Err(failure(
463                status::INVALID_ARGUMENT,
464                &PipelineEventHookError::ProtocolViolation(format!(
465                    "pipeline event input exceeds the {MAX_PIPELINE_EVENT_INPUT_BYTES}-byte transport limit"
466                )),
467            ));
468        }
469        let event = decode::<PipelineEvent>(event_json).map_err(|error| {
470            failure(
471                status::INVALID_ARGUMENT,
472                &PipelineEventHookError::PayloadCodec(error),
473            )
474        })?;
475        event
476            .validate()
477            .map_err(|error| failure(status::INVALID_ARGUMENT, &error))?;
478        let outcome = match self.hook.on_event(&event) {
479            Ok(outcome) => outcome,
480            Err(error) => {
481                if let Err(protocol_error) = error.validate() {
482                    return Err(failure(
483                        status::ABI_VIOLATION,
484                        &PipelineEventHookError::from(protocol_error),
485                    ));
486                }
487                return Err(failure(
488                    status::FAILURE,
489                    &PipelineEventHookError::from(error),
490                ));
491            }
492        };
493        outcome
494            .validate()
495            .map_err(|error| failure(status::ABI_VIOLATION, &error))?;
496        json_invocation(&outcome)
497    }
498}
499
500struct BenchmarkSinkAdapter<S> {
501    instance_id: String,
502    sink: S,
503}
504
505impl<S> RawExportInterface for BenchmarkSinkAdapter<S>
506where
507    S: PluginBenchmarkSink,
508{
509    fn kind(&self) -> ExportInterfaceKind {
510        ExportInterfaceKind::BenchmarkSink
511    }
512
513    fn instance_id(&self) -> &str {
514        &self.instance_id
515    }
516
517    fn invoke(&self, operation: ExportOperation<'_>) -> Result<ExportInvocation, ExportFailure> {
518        match operation {
519            ExportOperation::BenchmarkBatch { batch_json } => {
520                let batch = decode::<BenchmarkEventBatch>(batch_json).map_err(|error| {
521                    failure(
522                        status::INVALID_ARGUMENT,
523                        &BenchmarkSinkError::PayloadCodec(error),
524                    )
525                })?;
526                batch
527                    .validate()
528                    .map_err(|error| failure(status::INVALID_ARGUMENT, &error))?;
529                let sink_status = self
530                    .sink
531                    .on_event_batch(&batch)
532                    .map_err(|error| failure(status::FAILURE, &BenchmarkSinkError::from(error)))?;
533                sink_status
534                    .validate_for_batch(batch.events.len())
535                    .map_err(|error| failure(status::ABI_VIOLATION, &error))?;
536                json_invocation(&sink_status)
537            }
538            ExportOperation::BenchmarkFlush => {
539                let report = self
540                    .sink
541                    .flush()
542                    .map_err(|error| failure(status::FAILURE, &BenchmarkSinkError::from(error)))?;
543                report
544                    .validate()
545                    .map_err(|error| failure(status::ABI_VIOLATION, &error))?;
546                json_invocation(&report)
547            }
548            _ => Err(unexpected_operation("benchmark sink")),
549        }
550    }
551}
552
553fn decode<T>(bytes: &[u8]) -> Result<T, String>
554where
555    T: DeserializeOwned,
556{
557    serde_json::from_slice(bytes).map_err(|error| error.to_string())
558}
559
560fn json_invocation<T>(value: &T) -> Result<ExportInvocation, ExportFailure>
561where
562    T: Serialize,
563{
564    encode(value).map(ExportInvocation::Json)
565}
566
567fn encode<T>(value: &T) -> Result<Vec<u8>, ExportFailure>
568where
569    T: Serialize,
570{
571    serde_json::to_vec(value).map_err(|error| {
572        ExportFailure::with_status(status::ABI_VIOLATION, error.to_string().into_bytes())
573    })
574}
575
576fn failure<T>(failure_status: u32, value: &T) -> ExportFailure
577where
578    T: Serialize,
579{
580    let payload = serde_json::to_vec(value).unwrap_or_else(|error| error.to_string().into_bytes());
581    ExportFailure::with_status(failure_status, payload)
582}
583
584fn unexpected_operation(interface: &str) -> ExportFailure {
585    ExportFailure::with_status(
586        status::ABI_VIOLATION,
587        format!("unexpected operation for {interface}").into_bytes(),
588    )
589}
590
591#[cfg(test)]
592mod tests {
593    use super::*;
594    use crate::{PipelineEventHookFailure, PipelineEventHookOutcome, PluginDiagnostic};
595
596    fn pipeline_event(event_name: &str) -> PipelineEvent {
597        PipelineEvent {
598            run_id: "run-1".to_owned(),
599            session_id: "session-1".to_owned(),
600            platform: "test".to_owned(),
601            protocol: None,
602            event_name: event_name.to_owned(),
603            timestamp_ns: 1,
604            thread: None,
605            resource_identity: Some("download-task:1".to_owned()),
606            attributes: Default::default(),
607            diagnostic: None,
608        }
609    }
610
611    struct Hook;
612
613    impl PluginEventHook for Hook {
614        fn on_event(
615            &self,
616            _event: &PipelineEvent,
617        ) -> Result<PipelineEventHookOutcome, PipelineEventHookFailure> {
618            Ok(PipelineEventHookOutcome::accepted())
619        }
620    }
621
622    #[test]
623    fn builder_validates_identity_and_duplicate_interfaces() {
624        assert!(matches!(
625            PluginBuilder::new("invalid", "Fixture"),
626            Err(PluginBuildError::InvalidPluginId)
627        ));
628        let builder = PluginBuilder::new("dev.vesper.fixture", "Fixture")
629            .and_then(|builder| builder.with_pipeline_event_hook("dev.vesper.fixture.hook", Hook))
630            .expect("first interface");
631        assert!(matches!(
632            builder.with_pipeline_event_hook("dev.vesper.fixture.hook", Hook),
633            Err(PluginBuildError::DuplicateInterface { .. })
634        ));
635    }
636
637    #[test]
638    fn hook_adapter_round_trips_typed_json() {
639        let plugin = PluginBuilder::new("dev.vesper.fixture", "Fixture")
640            .and_then(|builder| builder.with_pipeline_event_hook("dev.vesper.fixture.hook", Hook))
641            .and_then(PluginBuilder::build)
642            .expect("plugin");
643        let event = pipeline_event("download.task.completed");
644        let input = serde_json::to_vec(&event).expect("serialize event");
645        let invocation = plugin.interfaces[0]
646            .invoke(ExportOperation::PipelineEvent { event_json: &input })
647            .expect("invoke hook");
648        let ExportInvocation::Json(output) = invocation else {
649            panic!("expected JSON output");
650        };
651        let outcome: PipelineEventHookOutcome =
652            serde_json::from_slice(&output).expect("decode outcome");
653        assert!(outcome.accepted);
654        assert!(outcome.diagnostics.is_empty());
655    }
656
657    #[test]
658    fn hook_adapter_rejects_protocol_violations() {
659        struct InvalidHook;
660
661        impl PluginEventHook for InvalidHook {
662            fn on_event(
663                &self,
664                _event: &PipelineEvent,
665            ) -> Result<PipelineEventHookOutcome, PipelineEventHookFailure> {
666                Ok(PipelineEventHookOutcome {
667                    accepted: true,
668                    measurements: Vec::new(),
669                    diagnostics: vec![PluginDiagnostic {
670                        code: "x".repeat(300),
671                        severity: crate::PluginDiagnosticSeverity::Error,
672                        message: "invalid".to_owned(),
673                        attributes: Default::default(),
674                    }],
675                })
676            }
677        }
678
679        let plugin = PluginBuilder::new("dev.vesper.fixture", "Fixture")
680            .and_then(|builder| {
681                builder.with_pipeline_event_hook("dev.vesper.fixture.hook", InvalidHook)
682            })
683            .and_then(PluginBuilder::build)
684            .expect("plugin");
685        let input = serde_json::to_vec(&pipeline_event("download.task.completed"))
686            .expect("serialize event");
687        assert!(
688            plugin.interfaces[0]
689                .invoke(ExportOperation::PipelineEvent { event_json: &input })
690                .is_err()
691        );
692    }
693
694    #[test]
695    fn hook_adapter_rejects_oversized_input_before_invoking_author_code() {
696        use std::sync::atomic::{AtomicUsize, Ordering};
697
698        struct CountingHook(Arc<AtomicUsize>);
699
700        impl PluginEventHook for CountingHook {
701            fn on_event(
702                &self,
703                _event: &PipelineEvent,
704            ) -> Result<PipelineEventHookOutcome, PipelineEventHookFailure> {
705                self.0.fetch_add(1, Ordering::SeqCst);
706                Ok(PipelineEventHookOutcome::accepted())
707            }
708        }
709
710        let calls = Arc::new(AtomicUsize::new(0));
711        let plugin = PluginBuilder::new("dev.vesper.fixture", "Fixture")
712            .and_then(|builder| {
713                builder.with_pipeline_event_hook(
714                    "dev.vesper.fixture.hook",
715                    CountingHook(calls.clone()),
716                )
717            })
718            .and_then(PluginBuilder::build)
719            .expect("plugin");
720        let input = vec![b' '; MAX_PIPELINE_EVENT_INPUT_BYTES + 1];
721        let error = plugin.interfaces[0]
722            .invoke(ExportOperation::PipelineEvent { event_json: &input })
723            .expect_err("oversized input must be rejected");
724
725        assert_eq!(error.status(), status::INVALID_ARGUMENT);
726        assert_eq!(calls.load(Ordering::SeqCst), 0);
727    }
728
729    #[test]
730    fn hook_adapter_accepts_unknown_event_names_and_ignores_appended_json_fields() {
731        let plugin = PluginBuilder::new("dev.vesper.fixture", "Fixture")
732            .and_then(|builder| builder.with_pipeline_event_hook("dev.vesper.fixture.hook", Hook))
733            .and_then(PluginBuilder::build)
734            .expect("plugin");
735        let mut value = serde_json::to_value(pipeline_event("vendor.future.event"))
736            .expect("serialize event value");
737        value.as_object_mut().expect("event object").insert(
738            "futureField".to_owned(),
739            serde_json::json!({ "nested": true }),
740        );
741        let input = serde_json::to_vec(&value).expect("serialize extended event");
742
743        assert!(
744            plugin.interfaces[0]
745                .invoke(ExportOperation::PipelineEvent { event_json: &input })
746                .is_ok()
747        );
748    }
749
750    #[test]
751    fn author_hook_failures_keep_failure_status_and_existing_json_payloads() {
752        struct FailingHook(PipelineEventHookFailure);
753        impl PluginEventHook for FailingHook {
754            fn on_event(
755                &self,
756                _: &PipelineEvent,
757            ) -> Result<PipelineEventHookOutcome, PipelineEventHookFailure> {
758                Err(self.0.clone())
759            }
760        }
761
762        let input = serde_json::to_vec(&pipeline_event("download.task.completed"))
763            .expect("serialize event");
764        for (failure_kind, code) in [
765            (
766                PipelineEventHookFailure::InvalidInput("input".to_owned()),
767                "invalidInput",
768            ),
769            (
770                PipelineEventHookFailure::Rejected("rejected".to_owned()),
771                "rejected",
772            ),
773            (
774                PipelineEventHookFailure::Failed("failed".to_owned()),
775                "failed",
776            ),
777        ] {
778            let expected = serde_json::to_value(&failure_kind).expect("serialize failure");
779            let plugin = PluginBuilder::new("dev.vesper.fixture", "Fixture")
780                .and_then(|builder| {
781                    builder.with_pipeline_event_hook(
782                        "dev.vesper.fixture.hook",
783                        FailingHook(failure_kind),
784                    )
785                })
786                .and_then(PluginBuilder::build)
787                .expect("plugin");
788            let error = plugin.interfaces[0]
789                .invoke(ExportOperation::PipelineEvent { event_json: &input })
790                .expect_err("author failure");
791            assert_eq!(error.status(), status::FAILURE);
792            let payload: serde_json::Value =
793                serde_json::from_slice(error.payload()).expect("decode failure payload");
794            assert_eq!(payload, expected);
795            assert_eq!(payload["code"], code);
796        }
797    }
798
799    #[test]
800    fn author_benchmark_failures_keep_sink_failed_for_batch_and_flush() {
801        use crate::{BenchmarkSinkFailure, BenchmarkSinkReport, BenchmarkSinkStatus};
802
803        struct FailingSink(String);
804        impl PluginBenchmarkSink for FailingSink {
805            fn name(&self) -> &str {
806                "fixture"
807            }
808            fn on_event_batch(
809                &self,
810                _: &BenchmarkEventBatch,
811            ) -> Result<BenchmarkSinkStatus, BenchmarkSinkFailure> {
812                Err(BenchmarkSinkFailure::Failed(self.0.clone()))
813            }
814            fn flush(&self) -> Result<BenchmarkSinkReport, BenchmarkSinkFailure> {
815                Err(BenchmarkSinkFailure::Failed(self.0.clone()))
816            }
817        }
818
819        let input = serde_json::to_vec(&BenchmarkEventBatch { events: Vec::new() })
820            .expect("serialize batch");
821        for message in [String::new(), "  保留 \n".to_owned(), "界".repeat(86)] {
822            let plugin = PluginBuilder::new("dev.vesper.fixture", "Fixture")
823                .and_then(|builder| {
824                    builder.with_benchmark_sink(
825                        "dev.vesper.fixture.benchmark",
826                        FailingSink(message.clone()),
827                    )
828                })
829                .and_then(PluginBuilder::build)
830                .expect("plugin");
831            for operation in [
832                ExportOperation::BenchmarkBatch { batch_json: &input },
833                ExportOperation::BenchmarkFlush,
834            ] {
835                let error = plugin.interfaces[0]
836                    .invoke(operation)
837                    .expect_err("author failure");
838                assert_eq!(error.status(), status::FAILURE);
839                assert_eq!(
840                    serde_json::from_slice::<serde_json::Value>(error.payload())
841                        .expect("decode failure payload"),
842                    serde_json::json!({ "code": "sinkFailed", "message": message }),
843                );
844            }
845        }
846    }
847
848    #[test]
849    fn hook_adapter_marks_invalid_author_messages_as_abi_violations() {
850        struct InvalidErrorHook;
851
852        impl PluginEventHook for InvalidErrorHook {
853            fn on_event(
854                &self,
855                _event: &PipelineEvent,
856            ) -> Result<PipelineEventHookOutcome, PipelineEventHookFailure> {
857                Err(PipelineEventHookFailure::Failed(
858                    "x".repeat(crate::MAX_PLUGIN_ERROR_MESSAGE_BYTES + 1),
859                ))
860            }
861        }
862
863        let plugin = PluginBuilder::new("dev.vesper.fixture", "Fixture")
864            .and_then(|builder| {
865                builder.with_pipeline_event_hook("dev.vesper.fixture.hook", InvalidErrorHook)
866            })
867            .and_then(PluginBuilder::build)
868            .expect("plugin");
869        let input = serde_json::to_vec(&pipeline_event("download.task.completed"))
870            .expect("serialize event");
871        let error = plugin.interfaces[0]
872            .invoke(ExportOperation::PipelineEvent { event_json: &input })
873            .expect_err("invalid author message must fail the ABI contract");
874
875        assert_eq!(error.status(), status::ABI_VIOLATION);
876    }
877}