witmproxy 0.0.1-alpha

A WASM-in-the-middle proxy
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
use std::collections::HashMap;
use std::io::Cursor;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use anyhow::Result;
use bytes::Bytes;
use http_body::Body as _;
use http_body_util::BodyExt;
use http_body_util::combinators::UnsyncBoxBody;
use tokio::sync::{RwLock, mpsc};
use tokio_util::sync::PollSender;
use wasmtime::AsContextMut;
use wasmtime::StoreContextMut;
use wasmtime::component::{
    Accessor, Destination, HasData, Resource, ResourceTable, Source, StreamProducer, StreamReader,
    StreamResult,
};
use wasmtime_wasi::{WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView};
use wasmtime_wasi_http::p3::bindings::http::types::ErrorCode;
use wasmtime_wasi_http::{WasiHttpCtx, WasiHttpView};

mod runtime;

use crate::events::content::InboundContent;
use crate::plugins::capabilities::Capability;
use crate::wasm::bindgen::witmproxy::plugin::capabilities::{
    CapabilityKind, HostAnnotatorClient, HostAnnotatorClientWithStore, HostCapabilityProvider,
    HostCapabilityProviderWithStore, HostContent, HostContentWithStore, HostLocalStorageClient,
    HostLocalStorageClientWithStore, HostLogger, HostLoggerWithStore,
};
pub use runtime::Runtime;

pub mod bindgen;

/// A capability provider that holds the capability instances granted to a plugin.
/// The caller/builder is responsible for providing the necessary objects.
/// The provider simply returns what it has access to when called.
pub struct CapabilityProvider {
    logger: Option<Logger>,
    annotator: Option<AnnotatorClient>,
    local_storage: Option<LocalStorageClient>,
}

impl Default for CapabilityProvider {
    fn default() -> Self {
        Self {
            logger: None,
            annotator: None,
            local_storage: None,
        }
    }
}

impl CapabilityProvider {
    /// Create a new CapabilityProvider with no capabilities granted
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the logger capability
    pub fn with_logger(mut self, logger: Logger) -> Self {
        self.logger = Some(logger);
        self
    }

    /// Set the annotator capability
    pub fn with_annotator(mut self, annotator: AnnotatorClient) -> Self {
        self.annotator = Some(annotator);
        self
    }

    /// Set the local storage capability
    pub fn with_local_storage(mut self, local_storage: LocalStorageClient) -> Self {
        self.local_storage = Some(local_storage);
        self
    }

    /// Returns a clone of the logger if granted
    pub fn logger(&self) -> Option<Logger> {
        self.logger.clone()
    }

    /// Returns a clone of the annotator client if granted
    pub fn annotator(&self) -> Option<AnnotatorClient> {
        self.annotator.clone()
    }

    /// Returns a clone of the local storage client if granted
    pub fn local_storage(&self) -> Option<LocalStorageClient> {
        self.local_storage.clone()
    }
}

impl From<&Vec<Capability>> for CapabilityProvider {
    fn from(capabilities: &Vec<Capability>) -> Self {
        let mut provider = CapabilityProvider::new();
        for cap in capabilities {
            if cap.granted {
                match &cap.inner.kind {
                    CapabilityKind::Logger => {
                        provider = provider.with_logger(Logger::new());
                    }
                    CapabilityKind::Annotator => {
                        provider = provider.with_annotator(AnnotatorClient::new());
                    }
                    CapabilityKind::LocalStorage => {
                        provider = provider.with_local_storage(LocalStorageClient::new());
                    }
                    CapabilityKind::HandleEvent(_) => {
                        // Event handling capabilities are managed separately
                    }
                }
            }
        }
        provider
    }
}

#[derive(Clone)]
pub struct AnnotatorClient {}

impl AnnotatorClient {
    pub fn new() -> Self {
        Self {}
    }

    pub fn annotate(&self, _content: &InboundContent) {}
}

impl Default for AnnotatorClient {
    fn default() -> Self {
        Self::new()
    }
}

/// Custom StreamProducer for body streaming
pub struct BodyStreamProducer {
    body: UnsyncBoxBody<Bytes, ErrorCode>,
}

impl BodyStreamProducer {
    pub fn new(body: UnsyncBoxBody<Bytes, ErrorCode>) -> Self {
        Self { body }
    }
}

impl<D> StreamProducer<D> for BodyStreamProducer
where
    D: 'static,
{
    type Item = u8;
    type Buffer = Cursor<Bytes>;

    fn poll_produce<'a>(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        mut store: StoreContextMut<'a, D>,
        mut dst: Destination<'a, Self::Item, Self::Buffer>,
        finish: bool,
    ) -> Poll<wasmtime::Result<StreamResult>> {
        use core::num::NonZeroUsize;

        let cap = match dst.remaining(&mut store).map(NonZeroUsize::new) {
            Some(Some(cap)) => Some(cap),
            Some(None) => {
                // On 0-length the best we can do is check that underlying stream has not
                // reached the end yet
                if self.body.is_end_stream() {
                    return Poll::Ready(Ok(StreamResult::Dropped));
                } else {
                    return Poll::Ready(Ok(StreamResult::Completed));
                }
            }
            None => None,
        };

        match Pin::new(&mut self.body).poll_frame(cx) {
            Poll::Ready(Some(Ok(frame))) => {
                // Try to extract data from the frame
                match frame.into_data().map_err(http_body::Frame::into_trailers) {
                    Ok(mut data_frame) => {
                        if let Some(cap) = cap {
                            let n = data_frame.len();
                            let cap_usize = cap.into();
                            if n > cap_usize {
                                // Data doesn't fit, buffer the rest
                                dst.set_buffer(Cursor::new(data_frame.split_off(cap_usize)));
                                let mut dst_direct = dst.as_direct(store, cap_usize);
                                dst_direct.remaining().copy_from_slice(&data_frame);
                                dst_direct.mark_written(cap_usize);
                            } else {
                                // Copy the whole frame
                                let mut dst_direct = dst.as_direct(store, n);
                                dst_direct.remaining()[..n].copy_from_slice(&data_frame);
                                dst_direct.mark_written(n);
                            }
                        } else {
                            // No capacity info, just buffer it
                            dst.set_buffer(Cursor::new(data_frame));
                        }
                        Poll::Ready(Ok(StreamResult::Completed))
                    }
                    Err(Ok(_trailers)) => {
                        // Trailers received - we're done with body data
                        // Note: In a full implementation, trailers would be stored in the resource table
                        // For now, we just signal completion
                        Poll::Ready(Ok(StreamResult::Dropped))
                    }
                    Err(Err(..)) => {
                        // Frame is neither data nor trailers - protocol error
                        Poll::Ready(Ok(StreamResult::Dropped))
                    }
                }
            }
            Poll::Ready(Some(Err(_err))) => Poll::Ready(Ok(StreamResult::Dropped)),
            Poll::Ready(None) => Poll::Ready(Ok(StreamResult::Dropped)),
            Poll::Pending if finish => Poll::Ready(Ok(StreamResult::Cancelled)),
            Poll::Pending => Poll::Pending,
        }
    }
}

#[derive(Clone)]
pub struct Logger {}

impl Logger {
    pub fn new() -> Self {
        Self {}
    }

    pub fn info(&self, message: String) {
        tracing::info!("{}", message);
    }

    pub fn warn(&self, message: String) {
        tracing::warn!("{}", message);
    }

    pub fn error(&self, message: String) {
        tracing::error!("{}", message);
    }

    pub fn debug(&self, message: String) {
        tracing::debug!("{}", message);
    }
}

impl Default for Logger {
    fn default() -> Self {
        Self::new()
    }
}

/// A local storage client with shared mutable state via Arc<RwLock<>>.
/// Clone is cheap (just Arc clone) and all clones share the same storage.
/// Uses Bytes internally for efficient storage and cheap cloning.
#[derive(Clone)]
pub struct LocalStorageClient {
    store: Arc<RwLock<HashMap<String, Bytes>>>,
}

impl Default for LocalStorageClient {
    fn default() -> Self {
        Self::new()
    }
}

impl LocalStorageClient {
    pub fn new() -> Self {
        Self {
            store: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Set a key-value pair in the store (async)
    pub async fn set(&self, key: String, value: Vec<u8>) {
        self.store.write().await.insert(key, Bytes::from(value));
    }

    /// Get a value by key (async). Returns cloned Bytes which is cheap.
    pub async fn get(&self, key: &str) -> Option<Bytes> {
        self.store.read().await.get(key).cloned()
    }

    /// Delete a key from the store (async)
    pub async fn delete(&self, key: &str) {
        self.store.write().await.remove(key);
    }
}

/// Builder-style structure used to create a [`WitmProxyCtx`].
#[derive(Default)]
pub struct WitmProxyCtxBuilder {
    // Add any initial configuration here
}

impl WitmProxyCtxBuilder {
    /// Creates a builder for a new context with default parameters set.
    pub fn new() -> Self {
        Default::default()
    }

    /// Uses the configured context so far to construct the final [`WitmProxyCtx`].
    pub fn build(self) -> WitmProxyCtx {
        WitmProxyCtx {
            // Initialize context state
        }
    }
}

/// Capture the state necessary for use in the `witmproxy:plugin` API implementation.
pub struct WitmProxyCtx {
    // Add context state here
}

impl WitmProxyCtx {
    /// Convenience function for calling [`WitmProxyCtxBuilder::new`].
    pub fn builder() -> WitmProxyCtxBuilder {
        WitmProxyCtxBuilder::new()
    }
}

/// A wrapper capturing the needed internal `witmproxy:plugin` state.
pub struct WitmProxyCtxView<'a> {
    _ctx: &'a WitmProxyCtx,
    pub table: &'a mut ResourceTable,
}

impl<'a> WitmProxyCtxView<'a> {
    /// Create a new view into the `witmproxy:plugin` state.
    pub fn new(ctx: &'a WitmProxyCtx, table: &'a mut ResourceTable) -> Self {
        Self { _ctx: ctx, table }
    }
}

/// Minimal WASI host state for each Store.
pub struct Host {
    pub table: ResourceTable,
    pub wasi: WasiCtx,
    pub http: WasiHttpCtx,
    pub p3_http: P3Ctx,
    pub witmproxy_ctx: WitmProxyCtx,
}

impl Default for Host {
    fn default() -> Self {
        Self {
            table: ResourceTable::new(),
            wasi: WasiCtxBuilder::new().build(),
            http: WasiHttpCtx::new(),
            p3_http: P3Ctx {},
            witmproxy_ctx: WitmProxyCtxBuilder::new().build(),
        }
    }
}

impl HostContentWithStore for WitmProxy {
    async fn drop<T>(
        accessor: &Accessor<T, Self>,
        rep: wasmtime::component::Resource<InboundContent>,
    ) -> wasmtime::Result<()> {
        accessor.with(|mut access| {
            let state: &mut WitmProxyCtxView = &mut access.get();
            state.table.delete(rep)
        })?;
        Ok(())
    }

    async fn content_type<T>(
        accessor: &Accessor<T, Self>,
        self_: wasmtime::component::Resource<InboundContent>,
    ) -> wasmtime::Result<String> {
        let content_type = accessor.with(|mut access| {
            let state: &mut WitmProxyCtxView = &mut access.get();
            let content = state.table.get(&self_)?;
            Ok::<String, wasmtime::component::ResourceTableError>(content.content_type())
        })?;
        Ok(content_type)
    }

    async fn body<T>(
        accessor: &wasmtime::component::Accessor<T, Self>,
        self_: wasmtime::component::Resource<InboundContent>,
    ) -> wasmtime::Result<wasmtime::component::StreamReader<u8>> {
        // Get mutable access to extract the data without consuming the resource
        let data = accessor.with(|mut access| {
            let state: &mut WitmProxyCtxView = &mut access.get();
            let content = state.table.get_mut(&self_)?;
            // Take the data out, leaving None in its place
            // body() returns Result<Option<...>, Error> but we can unwrap the Result part
            Ok::<Option<UnsyncBoxBody<Bytes, ErrorCode>>, wasmtime::component::ResourceTableError>(
                content.body().unwrap_or(None),
            )
        })?;

        // If data is None, it was already taken
        let body = data.ok_or_else(|| {
            wasmtime::Error::msg(
                "Content data has already been consumed. Use set_data to refill it.",
            )
        })?;

        let reader = accessor.with(|mut access| {
            let store = &mut access.as_context_mut();
            let stream_reader = StreamReader::new(store, BodyStreamProducer::new(body));
            Ok::<wasmtime::component::StreamReader<u8>, wasmtime::component::ResourceTableError>(
                stream_reader,
            )
        })?;
        Ok(reader)
    }

    async fn set_body<T>(
        accessor: &wasmtime::component::Accessor<T, Self>,
        self_: wasmtime::component::Resource<InboundContent>,
        content: wasmtime::component::StreamReader<u8>,
    ) -> wasmtime::Result<()> {
        // Convert StreamReader back to UnsyncBoxBody
        // This requires reading the stream and converting it to a body
        // using a channel-based approach

        use http_body::Frame;
        use http_body_util::StreamBody;

        // Create the channel within the ambient tokio runtime context
        let (tx, rx) = mpsc::channel::<Result<Frame<Bytes>, ErrorCode>>(65536);
        let body = StreamBody::new(tokio_stream::wrappers::ReceiverStream::new(rx)).boxed_unsync();

        accessor.with(|mut access| {
            let state: &mut WitmProxyCtxView = &mut access.get();
            let content = state.table.get_mut(&self_)?;
            content.set_body(body);
            Ok::<(), wasmtime::component::ResourceTableError>(())
        })?;

        // Create a StreamConsumer that forwards data to the channel
        struct ChannelStreamConsumer {
            tx: PollSender<Result<Frame<Bytes>, ErrorCode>>,
        }

        impl<D> wasmtime::component::StreamConsumer<D> for ChannelStreamConsumer {
            type Item = u8;

            fn poll_consume(
                mut self: Pin<&mut Self>,
                cx: &mut Context<'_>,
                store: StoreContextMut<D>,
                source: Source<Self::Item>,
                finish: bool,
            ) -> Poll<wasmtime::Result<StreamResult>> {
                // First check if channel is ready to receive data
                match self.tx.poll_reserve(cx) {
                    Poll::Ready(Ok(())) => {
                        // Channel is ready, read from source
                        let mut src = source.as_direct(store);
                        let buf = src.remaining();
                        let n = buf.len();

                        // Only send frame if there's data
                        if n > 0 {
                            let buf = Bytes::copy_from_slice(buf);
                            match self.tx.send_item(Ok(Frame::data(buf))) {
                                Ok(()) => {
                                    src.mark_read(n);
                                    Poll::Ready(Ok(StreamResult::Completed))
                                }
                                Err(..) => {
                                    // Receiver dropped
                                    Poll::Ready(Ok(StreamResult::Dropped))
                                }
                            }
                        } else {
                            // No data available, signal completion
                            Poll::Ready(Ok(StreamResult::Completed))
                        }
                    }
                    Poll::Ready(Err(..)) => {
                        // Channel closed
                        Poll::Ready(Ok(StreamResult::Dropped))
                    }
                    Poll::Pending if finish => {
                        // Stream is finishing but channel not ready
                        Poll::Ready(Ok(StreamResult::Cancelled))
                    }
                    Poll::Pending => Poll::Pending,
                }
            }
        }

        // Pipe the stream reader to the channel consumer
        let poll_sender = PollSender::new(tx);
        accessor.with(|mut access| {
            content.pipe(&mut access, ChannelStreamConsumer { tx: poll_sender });
        });

        Ok(())
    }
}

// Implement the Host traits using the accessor pattern
impl HostLocalStorageClientWithStore for WitmProxy {
    async fn set<T>(
        accessor: &Accessor<T, Self>,
        self_: Resource<LocalStorageClient>,
        key: String,
        value: Vec<u8>,
    ) -> wasmtime::Result<()> {
        // Clone the client (cheap Arc clone) to use outside the accessor closure
        let client = accessor.with(|mut access| {
            let state: &mut WitmProxyCtxView = &mut access.get();
            let client = state.table.get(&self_)?;
            Ok::<LocalStorageClient, wasmtime::component::ResourceTableError>(client.clone())
        })?;
        // Call async method on the cloned client (shares Arc storage)
        client.set(key, value).await;
        Ok(())
    }

    async fn get<T>(
        accessor: &Accessor<T, Self>,
        self_: Resource<LocalStorageClient>,
        key: String,
    ) -> wasmtime::Result<Option<Vec<u8>>> {
        // Clone the client (cheap Arc clone) to use outside the accessor closure
        let client = accessor.with(|mut access| {
            let state: &mut WitmProxyCtxView = &mut access.get();
            let client = state.table.get(&self_)?;
            Ok::<LocalStorageClient, wasmtime::component::ResourceTableError>(client.clone())
        })?;
        // Call async method and convert Bytes to Vec<u8> for WIT interface
        Ok(client.get(&key).await.map(|bytes| bytes.to_vec()))
    }

    async fn delete<T>(
        accessor: &Accessor<T, Self>,
        self_: Resource<LocalStorageClient>,
        key: String,
    ) -> wasmtime::Result<()> {
        // Clone the client (cheap Arc clone) to use outside the accessor closure
        let client = accessor.with(|mut access| {
            let state: &mut WitmProxyCtxView = &mut access.get();
            let client = state.table.get(&self_)?;
            Ok::<LocalStorageClient, wasmtime::component::ResourceTableError>(client.clone())
        })?;
        // Call async method on the cloned client (shares Arc storage)
        client.delete(&key).await;
        Ok(())
    }

    async fn drop<T>(
        accessor: &Accessor<T, Self>,
        rep: Resource<LocalStorageClient>,
    ) -> wasmtime::Result<()> {
        accessor.with(|mut access| {
            let state: &mut WitmProxyCtxView = &mut access.get();
            state.table.delete(rep)
        })?;
        Ok(())
    }
}

impl HostAnnotatorClientWithStore for WitmProxy {
    async fn annotate<T>(
        accessor: &Accessor<T, Self>,
        self_: Resource<AnnotatorClient>,
        content: Resource<InboundContent>,
    ) -> wasmtime::Result<()> {
        let _ = accessor.with(|mut access| {
            let state: &mut WitmProxyCtxView = &mut access.get();
            let annotator = state.table.get(&self_)?;
            let content = state.table.get(&content)?;
            annotator.annotate(content);
            Ok::<(), wasmtime::component::ResourceTableError>(())
        });
        Ok(())
    }

    async fn drop<T>(
        accessor: &Accessor<T, Self>,
        rep: Resource<AnnotatorClient>,
    ) -> wasmtime::Result<()> {
        accessor.with(|mut access| {
            let state: &mut WitmProxyCtxView = &mut access.get();
            state.table.delete(rep)
        })?;
        Ok(())
    }
}

impl HostLoggerWithStore for WitmProxy {
    async fn info<T>(
        accessor: &Accessor<T, Self>,
        self_: Resource<Logger>,
        message: String,
    ) -> wasmtime::Result<()> {
        let _ = accessor.with(|mut access| {
            let state: &mut WitmProxyCtxView = &mut access.get();
            let logger = state.table.get(&self_)?;
            logger.info(message);
            Ok::<(), wasmtime::component::ResourceTableError>(())
        });
        Ok(())
    }

    async fn warn<T>(
        accessor: &Accessor<T, Self>,
        self_: Resource<Logger>,
        message: String,
    ) -> wasmtime::Result<()> {
        let _ = accessor.with(|mut access| {
            let state: &mut WitmProxyCtxView = &mut access.get();
            let logger = state.table.get(&self_)?;
            logger.warn(message);
            Ok::<(), wasmtime::component::ResourceTableError>(())
        })?;
        Ok(())
    }

    async fn error<T>(
        accessor: &Accessor<T, Self>,
        self_: Resource<Logger>,
        message: String,
    ) -> wasmtime::Result<()> {
        let _ = accessor.with(|mut access| {
            let state: &mut WitmProxyCtxView = &mut access.get();
            let logger = state.table.get(&self_)?;
            logger.error(message);
            Ok::<(), wasmtime::component::ResourceTableError>(())
        })?;
        Ok(())
    }

    async fn debug<T>(
        accessor: &Accessor<T, Self>,
        self_: Resource<Logger>,
        message: String,
    ) -> wasmtime::Result<()> {
        let _ = accessor.with(|mut access| {
            let state: &mut WitmProxyCtxView = &mut access.get();
            let logger = state.table.get(&self_)?;
            logger.debug(message);
            Ok::<(), wasmtime::component::ResourceTableError>(())
        })?;
        Ok(())
    }

    async fn drop<T>(accessor: &Accessor<T, Self>, rep: Resource<Logger>) -> wasmtime::Result<()> {
        accessor.with(|mut access| {
            let state: &mut WitmProxyCtxView = &mut access.get();
            state.table.delete(rep)
        })?;
        Ok(())
    }
}

impl HostCapabilityProviderWithStore for WitmProxy {
    async fn logger<T>(
        accessor: &Accessor<T, Self>,
        cap: Resource<CapabilityProvider>,
    ) -> wasmtime::Result<Option<Resource<Logger>>> {
        Ok(accessor
            .with(|mut access| {
                let state: &mut WitmProxyCtxView = &mut access.get();
                let provider = state.table.get(&cap)?;
                // Get a clone of the logger if granted (cheap clone)
                match provider.logger() {
                    Some(logger) => Ok::<
                        Option<Resource<Logger>>,
                        wasmtime::component::ResourceTableError,
                    >(Some(state.table.push(logger)?)),
                    None => Ok(None),
                }
            })
            .unwrap_or(None))
    }

    async fn local_storage<T>(
        accessor: &Accessor<T, Self>,
        cap: Resource<CapabilityProvider>,
    ) -> wasmtime::Result<Option<Resource<LocalStorageClient>>> {
        Ok(accessor
            .with(|mut access| {
                let state: &mut WitmProxyCtxView = &mut access.get();
                let provider = state.table.get(&cap)?;
                // Get a clone of the local storage client if granted (cheap Arc clone)
                match provider.local_storage() {
                    Some(client) => Ok::<
                        Option<Resource<LocalStorageClient>>,
                        wasmtime::component::ResourceTableError,
                    >(Some(state.table.push(client)?)),
                    None => Ok(None),
                }
            })
            .unwrap_or(None))
    }

    async fn annotator<T>(
        accessor: &Accessor<T, Self>,
        cap: Resource<CapabilityProvider>,
    ) -> wasmtime::Result<Option<Resource<AnnotatorClient>>> {
        Ok(accessor
            .with(|mut access| {
                let state: &mut WitmProxyCtxView = &mut access.get();
                let provider = state.table.get(&cap)?;
                // Get a clone of the annotator client if granted (cheap clone)
                match provider.annotator() {
                    Some(client) => Ok::<
                        Option<Resource<AnnotatorClient>>,
                        wasmtime::component::ResourceTableError,
                    >(Some(state.table.push(client)?)),
                    None => Ok(None),
                }
            })
            .unwrap_or(None))
    }

    async fn drop<T>(
        accessor: &Accessor<T, Self>,
        rep: Resource<CapabilityProvider>,
    ) -> wasmtime::Result<()> {
        accessor.with(|mut access| {
            let state: &mut WitmProxyCtxView = &mut access.get();
            state.table.delete(rep)
        })?;
        Ok(())
    }
}

// Implement the generated capabilities::Host trait
impl bindgen::witmproxy::plugin::capabilities::Host for WitmProxyCtxView<'_> {}

// Implement the non-WithStore traits for WitmProxyCtxView
impl HostContent for WitmProxyCtxView<'_> {}
impl HostCapabilityProvider for WitmProxyCtxView<'_> {}
impl HostLocalStorageClient for WitmProxyCtxView<'_> {}
impl HostAnnotatorClient for WitmProxyCtxView<'_> {}
impl HostLogger for WitmProxyCtxView<'_> {}

pub struct P3Ctx {}
impl wasmtime_wasi_http::p3::WasiHttpCtx for P3Ctx {}

impl WasiView for Host {
    fn ctx(&mut self) -> WasiCtxView<'_> {
        WasiCtxView {
            ctx: &mut self.wasi,
            table: &mut self.table,
        }
    }
}

impl WasiHttpView for Host {
    fn ctx(&mut self) -> &mut WasiHttpCtx {
        &mut self.http
    }

    fn table(&mut self) -> &mut ResourceTable {
        &mut self.table
    }
}

impl wasmtime_wasi_http::p3::WasiHttpView for Host {
    fn http(&mut self) -> wasmtime_wasi_http::p3::WasiHttpCtxView<'_> {
        wasmtime_wasi_http::p3::WasiHttpCtxView {
            table: &mut self.table,
            ctx: &mut self.p3_http,
        }
    }
}

/// Add all the `witmproxy:plugin` world's interfaces to a [`wasmtime::component::Linker`].
pub fn add_to_linker<T: Send + 'static>(
    l: &mut wasmtime::component::Linker<T>,
    f: fn(&mut T) -> WitmProxyCtxView<'_>,
) -> Result<()> {
    bindgen::witmproxy::plugin::capabilities::add_to_linker::<_, WitmProxy>(l, f)?;
    Ok(())
}

struct WitmProxy;

impl HasData for WitmProxy {
    type Data<'a> = WitmProxyCtxView<'a>;
}