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
#![allow(clippy::assign_op_pattern)]

//!
//! # Spu Spec
//!
//! Spu Spec metadata information cached locally.
//!
use std::convert::TryFrom;
use std::io::Error as IoError;
use std::io::ErrorKind;
use std::fmt;

use flv_util::socket_helpers::EndPoint as SocketEndPoint;
use flv_util::socket_helpers::EndPointEncryption;
use fluvio_types::defaults::{SPU_PRIVATE_HOSTNAME, SPU_PRIVATE_PORT};
use fluvio_types::defaults::SPU_PUBLIC_PORT;
use fluvio_types::SpuId;
use flv_util::socket_helpers::ServerAddress;

use dataplane::derive::{Decode, Encode};
use dataplane::core::{Decoder, Encoder};
use dataplane::bytes::{Buf, BufMut};
use dataplane::core::Version;

#[derive(Decode, Encode, Debug, Clone, PartialEq)]
#[cfg_attr(
    feature = "use_serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct SpuSpec {
    #[cfg_attr(feature = "use_serde", serde(rename = "spuId"))]
    pub id: SpuId,
    #[cfg_attr(feature = "use_serde", serde(default))]
    pub spu_type: SpuType,
    pub public_endpoint: IngressPort,
    pub private_endpoint: Endpoint,
    #[cfg_attr(feature = "use_serde", serde(skip_serializing_if = "Option::is_none"))]
    pub rack: Option<String>,
}

impl fmt::Display for SpuSpec {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "id: {}, type: {}, public: {}",
            self.id, self.spu_type, self.public_endpoint
        )
    }
}

impl Default for SpuSpec {
    fn default() -> Self {
        SpuSpec {
            id: -1,
            spu_type: SpuType::default(),
            public_endpoint: IngressPort {
                port: SPU_PUBLIC_PORT,
                ..Default::default()
            },
            private_endpoint: Endpoint {
                port: SPU_PRIVATE_PORT,
                host: SPU_PRIVATE_HOSTNAME.to_string(),
                encryption: EncryptionEnum::default(),
            },
            rack: None,
        }
    }
}

impl From<SpuId> for SpuSpec {
    fn from(spec: SpuId) -> Self {
        Self::new(spec)
    }
}

impl SpuSpec {
    /// Given an Spu id generate a new SpuSpec
    pub fn new(id: SpuId) -> Self {
        Self {
            id,
            ..Default::default()
        }
    }

    pub fn set_custom(mut self) -> Self {
        self.spu_type = SpuType::Custom;
        self
    }

    /// Return custom type: true for custom, false otherwise
    pub fn is_custom(&self) -> bool {
        match self.spu_type {
            SpuType::Managed => false,
            SpuType::Custom => true,
        }
    }

    pub fn private_server_address(&self) -> ServerAddress {
        let private_ep = &self.private_endpoint;
        ServerAddress {
            host: private_ep.host.clone(),
            port: private_ep.port,
        }
    }

    pub fn update(&mut self, other: &Self) {
        if self.rack != other.rack {
            self.rack = other.rack.clone();
        }
        if self.public_endpoint != other.public_endpoint {
            self.public_endpoint = other.public_endpoint.clone();
        }
        if self.private_endpoint != other.private_endpoint {
            self.private_endpoint = other.private_endpoint.clone();
        }
    }
}

/// Custom Spu Spec
/// This is not real spec since when this is stored on metadata store, it will be stored as SPU
#[derive(Decode, Encode, Debug, Clone, Default, PartialEq)]
#[cfg_attr(
    feature = "use_serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct CustomSpuSpec {
    pub id: SpuId,
    pub public_endpoint: IngressPort,
    pub private_endpoint: Endpoint,
    #[cfg_attr(feature = "use_serde", serde(skip_serializing_if = "Option::is_none"))]
    pub rack: Option<String>,
}

impl CustomSpuSpec {
    pub const LABEL: &'static str = "CustomSpu";
}

impl From<CustomSpuSpec> for SpuSpec {
    fn from(spec: CustomSpuSpec) -> Self {
        Self {
            id: spec.id,
            public_endpoint: spec.public_endpoint,
            private_endpoint: spec.private_endpoint,
            rack: spec.rack,
            spu_type: SpuType::Custom,
        }
    }
}

impl From<SpuSpec> for CustomSpuSpec {
    fn from(spu: SpuSpec) -> Self {
        match spu.spu_type {
            SpuType::Custom => Self {
                id: spu.id,
                public_endpoint: spu.public_endpoint,
                private_endpoint: spu.private_endpoint,
                rack: spu.rack,
            },
            SpuType::Managed => panic!("managed spu type can't be converted into custom"),
        }
    }
}

#[derive(Decode, Encode, Default, Debug, Clone, PartialEq)]
#[cfg_attr(
    feature = "use_serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase", default)
)]
pub struct IngressPort {
    pub port: u16,
    pub ingress: Vec<IngressAddr>,
    pub encryption: EncryptionEnum,
}

impl fmt::Display for IngressPort {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}:{}", self.host_string(), self.port)
    }
}

impl From<ServerAddress> for IngressPort {
    fn from(addr: ServerAddress) -> Self {
        Self {
            port: addr.port,
            ingress: vec![IngressAddr::from_host(addr.host)],
            ..Default::default()
        }
    }
}

impl IngressPort {
    pub fn from_port_host(port: u16, host: String) -> Self {
        Self {
            port,
            ingress: vec![IngressAddr {
                hostname: Some(host),
                ip: None,
            }],
            encryption: EncryptionEnum::PLAINTEXT,
        }
    }

    // return any host whether it is IP or String
    pub fn host(&self) -> Option<String> {
        if self.ingress.is_empty() {
            None
        } else {
            self.ingress[0].host()
        }
    }

    pub fn host_string(&self) -> String {
        match self.host() {
            Some(host_val) => host_val,
            None => "".to_owned(),
        }
    }

    // convert to host:addr format
    pub fn addr(&self) -> String {
        format!("{}:{}", self.host_string(), self.port)
    }
}

#[derive(Decode, Encode, Default, Debug, Clone, PartialEq)]
#[cfg_attr(feature = "use_serde", derive(serde::Serialize, serde::Deserialize))]
pub struct IngressAddr {
    pub hostname: Option<String>,
    pub ip: Option<String>,
}

impl IngressAddr {
    pub fn from_host(hostname: String) -> Self {
        Self {
            hostname: Some(hostname),
            ..Default::default()
        }
    }

    pub fn from_ip(ip: String) -> Self {
        Self {
            ip: Some(ip),
            ..Default::default()
        }
    }

    pub fn host(&self) -> Option<String> {
        if let Some(name) = &self.hostname {
            Some(name.clone())
        } else if let Some(ip) = &self.ip {
            Some(ip.clone())
        } else {
            None
        }
    }
}

#[derive(Decode, Encode, Debug, Clone, PartialEq)]
#[cfg_attr(
    feature = "use_serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "camelCase")
)]
pub struct Endpoint {
    pub port: u16,
    pub host: String,
    pub encryption: EncryptionEnum,
}

impl From<ServerAddress> for Endpoint {
    fn from(addr: ServerAddress) -> Self {
        Self {
            port: addr.port,
            host: addr.host,
            ..Default::default()
        }
    }
}

impl fmt::Display for Endpoint {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}:{}", self.host, self.port)
    }
}

impl TryFrom<&Endpoint> for SocketEndPoint {
    type Error = IoError;

    fn try_from(endpoint: &Endpoint) -> Result<Self, Self::Error> {
        flv_util::socket_helpers::host_port_to_socket_addr(&endpoint.host, endpoint.port).map(
            |addr| SocketEndPoint {
                addr,
                encryption: EndPointEncryption::PLAINTEXT,
            },
        )
    }
}

#[allow(dead_code)]
impl TryFrom<&Endpoint> for std::net::SocketAddr {
    type Error = IoError;

    fn try_from(endpoint: &Endpoint) -> Result<Self, Self::Error> {
        flv_util::socket_helpers::host_port_to_socket_addr(&endpoint.host, endpoint.port)
    }
}

impl Default for Endpoint {
    fn default() -> Self {
        Self {
            host: "127.0.0.1".to_owned(),
            port: 0,
            encryption: EncryptionEnum::default(),
        }
    }
}

impl Endpoint {
    pub fn from_port_host(port: u16, host: String) -> Self {
        Self {
            port,
            host,
            encryption: EncryptionEnum::PLAINTEXT,
        }
    }
}

#[derive(Decode, Encode, Debug, Clone, PartialEq)]
#[cfg_attr(feature = "use_serde", derive(serde::Serialize, serde::Deserialize))]
pub enum EncryptionEnum {
    PLAINTEXT,
    SSL,
}

impl Default for EncryptionEnum {
    fn default() -> Self {
        EncryptionEnum::PLAINTEXT
    }
}

#[derive(Debug, Clone, PartialEq, Encode, Decode)]
#[cfg_attr(feature = "use_serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SpuType {
    Managed,
    Custom,
}

impl Default for SpuType {
    fn default() -> Self {
        SpuType::Managed
    }
}

/// Return type label in String format
impl SpuType {
    pub fn type_label(&self) -> &str {
        match self {
            Self::Managed => "managed",
            Self::Custom => "custom",
        }
    }
}

impl fmt::Display for SpuType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:#?}", self.type_label())
    }
}

#[derive(Debug)]
pub enum CustomSpu {
    Name(String),
    Id(i32),
}

// -----------------------------------
// Implementation - CustomSpu
// -----------------------------------
impl Default for CustomSpu {
    fn default() -> CustomSpu {
        Self::Name("".to_string())
    }
}

impl Encoder for CustomSpu {
    // compute size
    fn write_size(&self, version: Version) -> usize {
        let type_size = (0u8).write_size(version);
        match self {
            Self::Name(name) => type_size + name.write_size(version),
            Self::Id(id) => type_size + id.write_size(version),
        }
    }

    // encode match
    fn encode<T>(&self, dest: &mut T, version: Version) -> Result<(), IoError>
    where
        T: BufMut,
    {
        // ensure buffer is large enough
        if dest.remaining_mut() < self.write_size(version) {
            return Err(IoError::new(
                ErrorKind::UnexpectedEof,
                format!(
                    "not enough capacity for custom spu len of {}",
                    self.write_size(version)
                ),
            ));
        }

        match self {
            Self::Name(name) => {
                let typ: u8 = 0;
                typ.encode(dest, version)?;
                name.encode(dest, version)?;
            }
            Self::Id(id) => {
                let typ: u8 = 1;
                typ.encode(dest, version)?;
                id.encode(dest, version)?;
            }
        }

        Ok(())
    }
}

impl Decoder for CustomSpu {
    fn decode<T>(&mut self, src: &mut T, version: Version) -> Result<(), IoError>
    where
        T: Buf,
    {
        let mut value: u8 = 0;
        value.decode(src, version)?;
        match value {
            0 => {
                let mut name: String = String::default();
                name.decode(src, version)?;
                *self = Self::Name(name)
            }
            1 => {
                let mut id: i32 = 0;
                id.decode(src, version)?;
                *self = Self::Id(id)
            }
            _ => {
                return Err(IoError::new(
                    ErrorKind::UnexpectedEof,
                    format!("invalid value for Custom Spu: {}", value),
                ))
            }
        }

        Ok(())
    }
}