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
//! An execution of a WhizzML script.

use serde::de;
use serde::de::DeserializeOwned;
use serde::ser::SerializeSeq;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json;
use std::fmt;
use std::result;
use url::Url;

use super::id::*;
use super::status::*;
use super::{Library, Script};
use super::{Resource, ResourceCommon};
use crate::client::Client;
use crate::errors::*;

mod args;
mod execution_status;

pub use self::args::*;
pub use self::execution_status::*;

/// An execution of a WhizzML script.
///
/// TODO: Still lots of missing fields.
#[derive(Clone, Debug, Deserialize, Resource, Serialize)]
#[api_name = "execution"]
pub struct Execution {
    /// Common resource information. These fields will be serialized at the
    /// top-level of this structure by `serde`.
    #[serde(flatten)]
    pub common: ResourceCommon,

    /// The ID of this resource.
    pub resource: Id<Execution>,

    /// The current status of this execution.
    pub status: ExecutionStatus,

    /// Further information about this execution.
    pub execution: Data,

    /// Placeholder to allow extensibility without breaking the API.
    #[serde(skip)]
    _placeholder: (),
}

/// Data about a script execution.
///
/// TODO: Lots of missing fields.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Data {
    /// Outputs from this script.
    #[serde(default)]
    pub outputs: Vec<Output>,

    /// Result values from the script.  This is literally whatever value is
    /// returned at the end of the WhizzML script.
    pub result: Option<serde_json::Value>,

    /// Log entries generated by the script.
    #[serde(default)]
    pub logs: Vec<LogEntry>,

    /// BigML resources created by the script.
    #[serde(default)]
    pub output_resources: Vec<OutputResource>,

    /// Source files used as inputs to this execution.
    #[serde(default)]
    pub sources: Vec<Source>,

    /// Placeholder to allow extensibility without breaking the API.
    #[serde(skip)]
    _placeholder: (),
}

impl Data {
    /// Get a named output of this execution.
    pub fn get<D: DeserializeOwned>(&self, name: &str) -> Result<D> {
        for output in &self.outputs {
            if output.name == name {
                return output.get();
            }
        }
        Err(Error::could_not_get_output(name, format_err!("not found")))
    }
}

/// Information about a source code resource.
#[derive(Clone, Debug)]
pub struct Source {
    /// The script or library associated with this source.
    pub id: SourceId,
    /// The description associated with this source.
    pub description: String,
    /// Placeholder to allow extensibility without breaking the API.
    _placeholder: (),
}

impl<'de> Deserialize<'de> for Source {
    fn deserialize<D>(deserializer: D) -> result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct Visitor;

        // Do a whole bunch of annoying work needed to deserialize mixed-type
        // arrays.
        impl<'de> de::Visitor<'de> for Visitor {
            type Value = Source;

            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "a list with a source ID and a description")
            }

            fn visit_seq<V>(
                self,
                mut visitor: V,
            ) -> result::Result<Self::Value, V::Error>
            where
                V: de::SeqAccess<'de>,
            {
                use serde::de::Error;

                let id = visitor
                    .next_element()?
                    .ok_or_else(|| V::Error::custom("no id field in source"))?;
                let description = visitor.next_element()?.ok_or_else(|| {
                    V::Error::custom("no description field in source")
                })?;

                Ok(Source {
                    id,
                    description,
                    _placeholder: (),
                })
            }
        }

        deserializer.deserialize_seq(Visitor)
    }
}

impl Serialize for Source {
    fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut seq = serializer.serialize_seq(Some(2))?;
        seq.serialize_element(&self.id)?;
        seq.serialize_element(&self.description)?;
        seq.end()
    }
}

/// Either a script or library ID.
#[derive(Clone, Debug)]
pub enum SourceId {
    /// A library ID.
    Library(Id<Library>),
    /// A script ID.
    Script(Id<Script>),
}

impl SourceId {
    /// Build a URL pointing to the BigML dashboard view for this script.
    pub fn dashboard_url(&self) -> Url {
        match self {
            SourceId::Library(id) => id.dashboard_url(),
            SourceId::Script(id) => id.dashboard_url(),
        }
    }

    /// Download the corresponding source code.
    pub async fn fetch_source_code(&self, client: &Client) -> Result<String> {
        match *self {
            SourceId::Library(ref id) => Ok(client.fetch(id).await?.source_code),
            SourceId::Script(ref id) => Ok(client.fetch(id).await?.source_code),
        }
    }
}

impl fmt::Display for SourceId {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            SourceId::Library(ref id) => id.fmt(fmt),
            SourceId::Script(ref id) => id.fmt(fmt),
        }
    }
}

impl<'de> Deserialize<'de> for SourceId {
    fn deserialize<D>(deserializer: D) -> result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct Visitor;

        // Do a whole bunch of annoying work needed to deserialize mixed-type
        // arrays.
        impl<'de> de::Visitor<'de> for Visitor {
            type Value = SourceId;

            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "a script or library ID")
            }

            fn visit_str<E>(self, value: &str) -> result::Result<Self::Value, E>
            where
                E: de::Error,
            {
                if value.starts_with(Library::id_prefix()) {
                    let id = value
                        .parse()
                        .map_err(|e| de::Error::custom(format!("{}", e)))?;
                    Ok(SourceId::Library(id))
                } else if value.starts_with(Script::id_prefix()) {
                    let id = value
                        .parse()
                        .map_err(|e| de::Error::custom(format!("{}", e)))?;
                    Ok(SourceId::Script(id))
                } else {
                    Err(de::Error::custom("expected script or library ID"))
                }
            }
        }

        deserializer.deserialize_str(Visitor)
    }
}

impl Serialize for SourceId {
    fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match *self {
            SourceId::Library(ref id) => id.serialize(serializer),
            SourceId::Script(ref id) => id.serialize(serializer),
        }
    }
}