wrpc_runtime_wasmtime/rpc/host/
transport.rs

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
use core::marker::PhantomData;

use std::sync::Arc;

use anyhow::{bail, Context as _};
use wasmtime::component::Resource;
use wasmtime_wasi::bindings::io::poll::Pollable;
use wasmtime_wasi::bindings::io::streams::{InputStream, OutputStream};
use wasmtime_wasi::pipe::{AsyncReadStream, AsyncWriteStream};
use wasmtime_wasi::subscribe;
use wrpc_transport::{Index as _, Invoke};

use crate::bindings::rpc::error::Error;
use crate::bindings::rpc::transport::{
    Host, HostIncomingChannel, HostInvocation, HostOutgoingChannel, IncomingChannel, Invocation,
    OutgoingChannel,
};
use crate::rpc::{IncomingChannelStream, OutgoingChannelStream, WrpcRpcImpl};
use crate::{WrpcView, WrpcViewExt as _};

impl<T: WrpcView> Host for WrpcRpcImpl<T> {}

impl<T: WrpcView> HostInvocation for WrpcRpcImpl<T> {
    fn subscribe(
        &mut self,
        invocation: Resource<Invocation>,
    ) -> wasmtime::Result<Resource<Pollable>> {
        subscribe(self.0.table(), invocation)
    }

    async fn finish(
        &mut self,
        invocation: Resource<Invocation>,
    ) -> wasmtime::Result<
        Result<(Resource<OutgoingChannel>, Resource<IncomingChannel>), Resource<Error>>,
    > {
        let invocation = self.0.delete_invocation(invocation)?;
        match invocation.await {
            Ok((tx, rx)) => {
                let rx = self.0.push_incoming_channel(rx)?;
                let tx = self.0.push_outgoing_channel(tx)?;
                Ok(Ok((tx, rx)))
            }
            Err(error) => {
                let error = self.0.push_error(Error::Invoke(error))?;
                Ok(Err(error))
            }
        }
    }

    fn drop(&mut self, invocation: Resource<Invocation>) -> wasmtime::Result<()> {
        _ = self.0.delete_invocation(invocation)?;
        Ok(())
    }
}

impl<T: WrpcView> HostIncomingChannel for WrpcRpcImpl<T> {
    fn data(
        &mut self,
        incoming: Resource<IncomingChannel>,
    ) -> wasmtime::Result<Option<Resource<InputStream>>> {
        let IncomingChannel(stream) = self
            .0
            .table()
            .get_mut(&incoming)
            .context("failed to get incoming channel from table")?;
        if Arc::get_mut(stream).is_none() {
            return Ok(None);
        }
        let stream = Arc::clone(stream);
        let stream = self
            .0
            .table()
            .push_child(
                Box::new(AsyncReadStream::new(IncomingChannelStream {
                    incoming: IncomingChannel(stream),
                    _ty: PhantomData::<<T::Invoke as Invoke>::Incoming>,
                })) as InputStream,
                &incoming,
            )
            .context("failed to push input stream to table")?;
        Ok(Some(stream))
    }

    fn index(
        &mut self,
        incoming: Resource<IncomingChannel>,
        path: Vec<u32>,
    ) -> wasmtime::Result<Result<Resource<IncomingChannel>, Resource<Error>>> {
        let path = path
            .into_iter()
            .map(usize::try_from)
            .collect::<Result<Box<[_]>, _>>()
            .context("failed to construct subscription path")?;
        let IncomingChannel(incoming) = self
            .0
            .table()
            .get(&incoming)
            .context("failed to get incoming channel from table")?;
        let incoming = {
            let Ok(incoming) = incoming.read() else {
                bail!("lock poisoned");
            };
            let incoming = incoming
                .downcast_ref::<<T::Invoke as Invoke>::Incoming>()
                .context("invalid incoming channel type")?;
            incoming.index(&path)
        };
        match incoming {
            Ok(incoming) => {
                let incoming = self.0.push_incoming_channel(incoming)?;
                Ok(Ok(incoming))
            }
            Err(error) => {
                let error = self.0.push_error(Error::IncomingIndex(error))?;
                Ok(Err(error))
            }
        }
    }

    fn drop(&mut self, incoming: Resource<IncomingChannel>) -> wasmtime::Result<()> {
        self.0.delete_incoming_channel(incoming)?;
        Ok(())
    }
}

impl<T: WrpcView> HostOutgoingChannel for WrpcRpcImpl<T> {
    fn data(
        &mut self,
        outgoing: Resource<OutgoingChannel>,
    ) -> wasmtime::Result<Option<Resource<OutputStream>>> {
        let OutgoingChannel(stream) = self
            .0
            .table()
            .get_mut(&outgoing)
            .context("failed to get outgoing channel from table")?;
        if Arc::get_mut(stream).is_none() {
            return Ok(None);
        }
        let stream = Arc::clone(stream);
        let stream = self
            .0
            .table()
            .push_child(
                Box::new(AsyncWriteStream::new(
                    8192,
                    OutgoingChannelStream {
                        outgoing: OutgoingChannel(stream),
                        _ty: PhantomData::<<T::Invoke as Invoke>::Outgoing>,
                    },
                )) as OutputStream,
                &outgoing,
            )
            .context("failed to push output stream to table")?;
        Ok(Some(stream))
    }

    fn index(
        &mut self,
        outgoing: Resource<OutgoingChannel>,
        path: Vec<u32>,
    ) -> wasmtime::Result<Result<Resource<OutgoingChannel>, Resource<Error>>> {
        let path = path
            .into_iter()
            .map(usize::try_from)
            .collect::<Result<Box<[_]>, _>>()
            .context("failed to construct subscription path")?;
        let OutgoingChannel(outgoing) = self
            .0
            .table()
            .get(&outgoing)
            .context("failed to get outgoing channel from table")?;
        let incoming = {
            let Ok(outgoing) = outgoing.read() else {
                bail!("lock poisoned");
            };
            let outgoing = outgoing
                .downcast_ref::<<T::Invoke as Invoke>::Outgoing>()
                .context("invalid outgoing channel type")?;
            outgoing.index(&path)
        };
        match incoming {
            Ok(outgoing) => {
                let outgoing = self.0.push_outgoing_channel(outgoing)?;
                Ok(Ok(outgoing))
            }
            Err(error) => {
                let error = self.0.push_error(Error::OutgoingIndex(error))?;
                Ok(Err(error))
            }
        }
    }

    fn drop(&mut self, outgoing: Resource<OutgoingChannel>) -> wasmtime::Result<()> {
        self.0.delete_outgoing_channel(outgoing)?;
        Ok(())
    }
}