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
//! API extension types.

use std::{fmt, ops};

use serde::{Deserialize, Serialize};
use zng_txt::Txt;

/// Custom serialized data, in a format defined by the extension.
///
/// Note that the bytes here should represent a serialized small `struct` only, you
/// can add an [`IpcBytes`] or [`IpcBytesReceiver`] field to this struct to transfer
/// large payloads.
///
/// [`IpcBytes`]: crate::ipc::IpcBytes
/// [`IpcBytesReceiver`]: crate::ipc::IpcBytesReceiver
#[derive(Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct ApiExtensionPayload(#[serde(with = "serde_bytes")] pub Vec<u8>);
impl ApiExtensionPayload {
    /// Serialize the payload.
    pub fn serialize<T: Serialize>(payload: &T) -> bincode::Result<Self> {
        bincode::serialize(payload).map(Self)
    }

    /// Deserialize the payload.
    pub fn deserialize<T: serde::de::DeserializeOwned>(&self) -> Result<T, ApiExtensionRecvError> {
        if let Some((id, error)) = self.parse_invalid_request() {
            Err(ApiExtensionRecvError::InvalidRequest {
                extension_id: id,
                error: Txt::from_str(error),
            })
        } else if let Some(id) = self.parse_unknown_extension() {
            Err(ApiExtensionRecvError::UnknownExtension { extension_id: id })
        } else {
            bincode::deserialize(&self.0).map_err(ApiExtensionRecvError::Deserialize)
        }
    }

    /// Empty payload.
    pub const fn empty() -> Self {
        Self(vec![])
    }

    /// Value returned when an invalid extension is requested.
    ///
    /// Value is a string `"zng-view-api.unknown_extension;id={extension_id}"`.
    pub fn unknown_extension(extension_id: ApiExtensionId) -> Self {
        Self(format!("zng-view-api.unknown_extension;id={extension_id}").into_bytes())
    }

    /// Value returned when an invalid request is made for a valid extension key.
    ///
    /// Value is a string `"zng-view-api.invalid_request;id={extension_id};error={error}"`.
    pub fn invalid_request(extension_id: ApiExtensionId, error: impl fmt::Display) -> Self {
        Self(format!("zng-view-api.invalid_request;id={extension_id};error={error}").into_bytes())
    }

    /// If the payload is an [`unknown_extension`] error message, returns the key.
    ///
    /// if the payload starts with the invalid request header and the key cannot be retrieved the
    /// [`ApiExtensionId::INVALID`] is returned as the key.
    ///
    /// [`unknown_extension`]: Self::unknown_extension
    pub fn parse_unknown_extension(&self) -> Option<ApiExtensionId> {
        let p = self.0.strip_prefix(b"zng-view-api.unknown_extension;")?;
        if let Some(p) = p.strip_prefix(b"id=") {
            if let Ok(id_str) = std::str::from_utf8(p) {
                return match id_str.parse::<ApiExtensionId>() {
                    Ok(id) => Some(id),
                    Err(id) => Some(id),
                };
            }
        }
        Some(ApiExtensionId::INVALID)
    }

    /// If the payload is an [`invalid_request`] error message, returns the key and error.
    ///
    /// if the payload starts with the invalid request header and the key cannot be retrieved the
    /// [`ApiExtensionId::INVALID`] is returned as the key and the error message will mention "corrupted payload".
    ///
    /// [`invalid_request`]: Self::invalid_request
    pub fn parse_invalid_request(&self) -> Option<(ApiExtensionId, &str)> {
        let p = self.0.strip_prefix(b"zng-view-api.invalid_request;")?;
        if let Some(p) = p.strip_prefix(b"id=") {
            if let Some(id_end) = p.iter().position(|&b| b == b';') {
                if let Ok(id_str) = std::str::from_utf8(&p[..id_end]) {
                    let id = match id_str.parse::<ApiExtensionId>() {
                        Ok(id) => id,
                        Err(id) => id,
                    };
                    if let Some(p) = p[id_end..].strip_prefix(b";error=") {
                        if let Ok(err_str) = std::str::from_utf8(p) {
                            return Some((id, err_str));
                        }
                    }
                    return Some((id, "invalid request, corrupted payload, unknown error"));
                }
            }
        }
        Some((
            ApiExtensionId::INVALID,
            "invalid request, corrupted payload, unknown extension_id and error",
        ))
    }
}
impl fmt::Debug for ApiExtensionPayload {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ExtensionPayload({} bytes)", self.0.len())
    }
}

/// Identifies an API extension and version.
///
/// Note that the version is part of the name, usually in the pattern "crate-name.extension.v2",
/// there are no minor versions, all different versions are considered breaking changes and
/// must be announced and supported by exact match only. You can still communicate non-breaking changes
/// by using the extension payload
#[derive(Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct ApiExtensionName {
    name: Txt,
}
impl ApiExtensionName {
    /// New from unique name.
    ///
    /// The name must contain at least 1 characters, and match the pattern `[a-zA-Z][a-zA-Z0-9-_.]`.
    pub fn new(name: impl Into<Txt>) -> Result<Self, ApiExtensionNameError> {
        let name = name.into();
        Self::new_impl(name)
    }
    fn new_impl(name: Txt) -> Result<ApiExtensionName, ApiExtensionNameError> {
        if name.is_empty() {
            return Err(ApiExtensionNameError::NameCannotBeEmpty);
        }
        for (i, c) in name.char_indices() {
            if i == 0 {
                if !c.is_ascii_alphabetic() {
                    return Err(ApiExtensionNameError::NameCannotStartWithChar(c));
                }
            } else if !c.is_ascii_alphanumeric() && c != '_' && c != '-' && c != '.' {
                return Err(ApiExtensionNameError::NameInvalidChar(c));
            }
        }

        Ok(Self { name })
    }
}
impl fmt::Debug for ApiExtensionName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.name, f)
    }
}
impl fmt::Display for ApiExtensionName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.name, f)
    }
}
impl ops::Deref for ApiExtensionName {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.name.as_str()
    }
}
impl From<&'static str> for ApiExtensionName {
    fn from(value: &'static str) -> Self {
        Self::new(value).unwrap()
    }
}

/// API extension invalid name.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum ApiExtensionNameError {
    /// Name cannot empty `""`.
    NameCannotBeEmpty,
    /// Name can only start with ASCII alphabetic chars `[a-zA-Z]`.
    NameCannotStartWithChar(char),
    /// Name can only contains `[a-zA-Z0-9-_.]`.
    NameInvalidChar(char),
}
impl fmt::Display for ApiExtensionNameError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ApiExtensionNameError::NameCannotBeEmpty => write!(f, "API extension name cannot be empty"),
            ApiExtensionNameError::NameCannotStartWithChar(c) => {
                write!(f, "API cannot start with '{c}', name pattern `[a-zA-Z][a-zA-Z0-9-_.]`")
            }
            ApiExtensionNameError::NameInvalidChar(c) => write!(f, "API cannot contain '{c}', name pattern `[a-zA-Z][a-zA-Z0-9-_.]`"),
        }
    }
}
impl std::error::Error for ApiExtensionNameError {}

/// List of available API extensions.
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ApiExtensions(Vec<ApiExtensionName>);
impl ops::Deref for ApiExtensions {
    type Target = [ApiExtensionName];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl ApiExtensions {
    /// New Empty.
    pub fn new() -> Self {
        Self::default()
    }

    /// Gets the position of the `ext` in the list of available extensions. This index
    /// identifies the API extension in the [`Api::app_extension`] and [`Api::render_extension`].
    ///
    /// The key can be cached only for the duration of the view process, each view re-instantiation
    /// must query for the presence of the API extension again, and it may change position on the list.
    ///
    /// [`Api::app_extension`]: crate::Api::app_extension
    /// [`Api::render_extension`]: crate::Api::render_extension
    pub fn id(&self, ext: &ApiExtensionName) -> Option<ApiExtensionId> {
        self.0.iter().position(|e| e == ext).map(ApiExtensionId::from_index)
    }

    /// Push the `ext` to the list, if it is not already inserted.
    ///
    /// Returns `Ok(key)` if inserted or `Err(key)` is was already in list.
    pub fn insert(&mut self, ext: ApiExtensionName) -> Result<ApiExtensionId, ApiExtensionId> {
        if let Some(key) = self.id(&ext) {
            Err(key)
        } else {
            let key = self.0.len();
            self.0.push(ext);
            Ok(ApiExtensionId::from_index(key))
        }
    }
}

/// Identifies an [`ApiExtensionName`] in a list.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ApiExtensionId(u32);
impl fmt::Debug for ApiExtensionId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if *self == Self::INVALID {
            if f.alternate() {
                write!(f, "ApiExtensionId::")?;
            }
            write!(f, "INVALID")
        } else {
            write!(f, "ApiExtensionId({})", self.0 - 1)
        }
    }
}
impl fmt::Display for ApiExtensionId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if *self == Self::INVALID {
            write!(f, "invalid")
        } else {
            write!(f, "{}", self.0 - 1)
        }
    }
}
impl ApiExtensionId {
    /// Dummy ID.
    pub const INVALID: Self = Self(0);

    /// Gets the ID as a list index.
    ///
    /// # Panics
    ///
    /// Panics if called in `INVALID`.
    pub fn index(self) -> usize {
        self.0.checked_sub(1).expect("invalid id") as _
    }

    /// New ID from the index of an [`ApiExtensionName`] in a list.
    ///
    /// # Panics
    ///
    /// Panics if `idx > u32::MAX - 1`.
    pub fn from_index(idx: usize) -> Self {
        if idx > (u32::MAX - 1) as _ {
            panic!("index out-of-bounds")
        }
        Self(idx as u32 + 1)
    }
}
impl std::str::FromStr for ApiExtensionId {
    type Err = Self;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.parse::<u32>() {
            Ok(i) => {
                let r = Self::from_index(i as _);
                if r == Self::INVALID {
                    Err(r)
                } else {
                    Ok(r)
                }
            }
            Err(_) => Err(Self::INVALID),
        }
    }
}

/// Error in the response of an API extension call.
#[derive(Debug)]
pub enum ApiExtensionRecvError {
    /// Requested extension was not in the list of extensions.
    UnknownExtension {
        /// Extension that was requested.
        ///
        /// Is `INVALID` only if error message is corrupted.
        extension_id: ApiExtensionId,
    },
    /// Invalid request format.
    InvalidRequest {
        /// Extension that was requested.
        ///
        /// Is `INVALID` only if error message is corrupted.
        extension_id: ApiExtensionId,
        /// Message from the view-process.
        error: Txt,
    },
    /// Failed to deserialize to the expected response type.
    Deserialize(bincode::Error),
}
impl fmt::Display for ApiExtensionRecvError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ApiExtensionRecvError::UnknownExtension { extension_id } => write!(f, "invalid API request for unknown id {extension_id:?}"),
            ApiExtensionRecvError::InvalidRequest { extension_id, error } => {
                write!(f, "invalid API request for extension id {extension_id:?}, {error}")
            }
            ApiExtensionRecvError::Deserialize(e) => write!(f, "API extension response failed to deserialize, {e}"),
        }
    }
}
impl std::error::Error for ApiExtensionRecvError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        if let Self::Deserialize(e) = self {
            Some(e)
        } else {
            None
        }
    }
}