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
#![allow(dead_code)] // triggered when you don't compile with an engine feature

use std::{
    collections::HashMap,
    io::{Cursor, Read},
    sync::Arc,
};

use anyhow::{Context, Error};
use hotg_rune_core::{SerializableRecord, Shape};

use crate::callbacks::{
    Callbacks, Model, ModelMetadata, NodeMetadata, RuneGraph,
};

/// An adapter that exposes functionality from [`Callbacks`] via functions that
/// the WebAssembly expects.
///
/// This object also manages any objects that are constructed by the Rune.
pub(crate) struct HostFunctions {
    next: u32,
    callbacks: Arc<dyn Callbacks>,
    capabilities: HashMap<u32, NodeMetadata>,
    outputs: HashMap<u32, NodeMetadata>,
    resources: HashMap<u32, Box<dyn Read + Send + Sync>>,
    models: HashMap<u32, Box<dyn Model>>,
}

impl HostFunctions {
    pub fn new(callbacks: Arc<dyn Callbacks>) -> Self {
        HostFunctions {
            callbacks,
            next: 1,
            capabilities: HashMap::new(),
            outputs: HashMap::new(),
            resources: HashMap::new(),
            models: HashMap::new(),
        }
    }

    pub(crate) fn graph(&self) -> RuneGraph<'_> {
        RuneGraph {
            capabilities: &self.capabilities,
            outputs: &self.outputs,
        }
    }

    pub(crate) fn model_by_id(&mut self, id: u32) -> Option<&mut dyn Model> {
        self.models.get_mut(&id).map(|m| &mut **m)
    }

    fn next_id(&mut self) -> u32 {
        let id = self.next;
        self.next += 1;
        id
    }

    pub fn debug(&self, message: &str) -> Result<(), Error> {
        log::debug!("Received message: {}", message);

        match serde_json::from_str::<SerializableRecord>(message) {
            Ok(record) => {
                record.with_record(|r| self.callbacks.log(r));
            },
            Err(e) => {
                log::warn!(
                    "Unable to deserialize {:?} as a log message: {}",
                    message,
                    e
                );
            },
        }

        Ok(())
    }

    pub fn request_capability(
        &mut self,
        capability_type: u32,
    ) -> Result<u32, Error> {
        let id = self.next_id();

        let capability_name =
            hotg_rune_core::capabilities::name(capability_type).with_context(
                || format!("Unknown capability type: {}", capability_type),
            )?;

        let meta = NodeMetadata {
            kind: capability_name.to_string(),
            arguments: HashMap::new(),
        };
        self.capabilities.insert(id, meta);

        Ok(id)
    }

    pub fn request_capability_set_param(
        &mut self,
        capability_id: u32,
        key: &str,
        value: impl Into<String>,
    ) -> Result<(), Error> {
        let meta =
            self.capabilities.get_mut(&capability_id).with_context(|| {
                format!(
                    "Trying to set \"{}\" on non-existent capability with ID \
                     {}",
                    key, capability_id
                )
            })?;
        meta.arguments.insert(key.to_string(), value.into());

        Ok(())
    }

    pub fn request_provider_response(
        &self,
        capability_id: u32,
        buffer: &mut [u8],
    ) -> Result<u32, Error> {
        let meta =
            self.capabilities.get(&capability_id).with_context(|| {
                format!(
                    "Tried to read from non-existent capability with ID {}",
                    capability_id
                )
            })?;

        let bytes_written = self
            .callbacks
            .read_capability(capability_id, meta, buffer)
            .context("Unable to read the input")?;

        Ok(bytes_written as u32)
    }

    pub fn tfm_model_invoke(&self) -> Result<(), Error> {
        anyhow::bail!("This feature has been removed")
    }

    pub fn tfm_preload_model(&self) -> Result<(), Error> {
        anyhow::bail!("This feature has been removed")
    }

    pub fn rune_model_load(
        &mut self,
        mimetype: &str,
        model: &[u8],
        inputs: &[Shape<'_>],
        outputs: &[Shape<'_>],
    ) -> Result<u32, Error> {
        let id = self.next_id();

        let meta = ModelMetadata {
            mimetype,
            inputs,
            outputs,
        };

        let model =
            self.callbacks
                .load_model(id, &meta, model)
                .with_context(|| {
                    format!(
                        "Unable to load the \"{}\" model with inputs {:?} and \
                         outputs {:?}",
                        mimetype, inputs, outputs
                    )
                })?;

        self.models.insert(id, model);

        Ok(id)
    }

    pub fn rune_model_infer(
        &mut self,
        model_id: u32,
        inputs: &[&[u8]],
        outputs: &mut [&mut [u8]],
    ) -> Result<(), Error> {
        let model = self.models.get_mut(&model_id).with_context(|| {
            format!("Tried to access non-existent model with ID {}", model_id)
        })?;

        model.infer(inputs, outputs)?;

        Ok(())
    }

    pub fn request_output(&mut self, output_type: u32) -> Result<u32, Error> {
        let id = self.next_id();

        let output_name = hotg_rune_core::outputs::name(output_type)
            .with_context(|| format!("Unknown output type: {}", output_type))?;

        let meta = NodeMetadata {
            kind: output_name.to_string(),
            arguments: HashMap::new(),
        };
        self.outputs.insert(id, meta);

        Ok(id)
    }

    pub fn consume_output(
        &mut self,
        output_id: u32,
        data: &[u8],
    ) -> Result<(), Error> {
        let metadata = self.outputs.get(&output_id).with_context(|| {
            format!(
                "Tried to write to non-existent output with ID {}",
                output_id
            )
        })?;

        self.callbacks
            .write_output(output_id, metadata, data)
            .context("Writing output failed")?;

        Ok(())
    }

    pub fn rune_resource_open(&mut self, name: &str) -> Result<u32, Error> {
        let resource = self
            .callbacks
            .get_resource(name)
            .with_context(|| format!("No resource named \"{}\"", name))?;

        let reader = Box::new(Cursor::new(resource.to_vec()));
        let id = self.next_id();

        self.resources.insert(id, reader);

        Ok(id)
    }

    pub fn rune_resource_read(
        &mut self,
        resource_id: u32,
        buffer: &mut [u8],
    ) -> Result<u32, Error> {
        let resource =
            self.resources.get_mut(&resource_id).with_context(|| {
                format!(
                    "Tried to read from non-existed resource with ID {}",
                    resource_id
                )
            })?;

        let bytes_read = resource
            .read(buffer)
            .context("Unable to read from the resource")?;

        Ok(bytes_read as u32)
    }

    pub fn rune_resource_close(
        &mut self,
        resource_id: u32,
    ) -> Result<(), Error> {
        let _ = self.resources.remove(&resource_id).with_context(|| {
            format!(
                "Tried to close non-existed resource with ID {}",
                resource_id
            )
        })?;

        Ok(())
    }
}