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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
//! The canister interface for canisters that implement HTTP requests.

use crate::{
    call::{AsyncCall, SyncCall},
    Canister,
};
use candid::{
    types::{
        reference::FuncVisitor,
        value::{IDLValue, IDLValueVisitor},
        Compound, Serializer, Type, TypeInner,
    },
    CandidType, Deserialize, Func,
};
use ic_agent::{export::Principal, Agent};
use std::{
    borrow::Cow,
    convert::TryInto,
    fmt::Debug,
    marker::PhantomData,
    ops::{Deref, DerefMut},
};

/// A canister that can serve a HTTP request.
#[derive(Debug, Clone)]
pub struct HttpRequestCanister<'agent>(Canister<'agent>);

impl<'agent> Deref for HttpRequestCanister<'agent> {
    type Target = Canister<'agent>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// A key-value pair for a HTTP header.
#[derive(Debug, CandidType, Clone, Deserialize)]
pub struct HeaderField<'a>(pub Cow<'a, str>, pub Cow<'a, str>);

/// The important components of an HTTP request.
#[derive(Debug, Clone, CandidType)]
struct HttpRequest<'a, H> {
    /// The HTTP method string.
    pub method: &'a str,
    /// The URL that was visited.
    pub url: &'a str,
    /// The request headers.
    pub headers: H,
    /// The request body.
    pub body: &'a [u8],
    /// The certificate version.
    pub certificate_version: Option<&'a u16>,
}

/// The important components of an HTTP update request.
/// This is the same as `HttpRequest`, excluding the `certificate_version` property.
#[derive(Debug, Clone, CandidType)]
struct HttpUpdateRequest<'a, H> {
    /// The HTTP method string.
    pub method: &'a str,
    /// The URL that was visited.
    pub url: &'a str,
    /// The request headers.
    pub headers: H,
    /// The request body.
    pub body: &'a [u8],
}

/// A wrapper around an iterator of headers
#[derive(Debug, Clone)]
pub struct Headers<H>(H);

impl<'a, H: Clone + ExactSizeIterator<Item = HeaderField<'a>>> From<H> for Headers<H> {
    fn from(h: H) -> Self {
        Headers(h)
    }
}

impl<'a, H: Clone + ExactSizeIterator<Item = HeaderField<'a>>> CandidType for Headers<H> {
    fn _ty() -> Type {
        TypeInner::Vec(HeaderField::ty()).into()
    }
    fn idl_serialize<S: Serializer>(&self, serializer: S) -> Result<(), S::Error> {
        let mut ser = serializer.serialize_vec(self.0.len())?;
        for e in self.0.clone() {
            Compound::serialize_element(&mut ser, &e)?;
        }
        Ok(())
    }
}

/// A HTTP response.
#[derive(Debug, Clone, CandidType, Deserialize)]
pub struct HttpResponse<Token = self::Token, Callback = HttpRequestStreamingCallback> {
    /// The HTTP status code.
    pub status_code: u16,
    /// The response header map.
    pub headers: Vec<HeaderField<'static>>,
    /// The response body.
    #[serde(with = "serde_bytes")]
    pub body: Vec<u8>,
    /// The strategy for streaming the rest of the data, if the full response is to be streamed.
    pub streaming_strategy: Option<StreamingStrategy<Token, Callback>>,
    /// Whether the query call should be upgraded to an update call.
    pub upgrade: Option<bool>,
}

impl<T1, C1> HttpResponse<T1, C1> {
    /// Convert another streaming strategy
    pub fn from<T2: Into<T1>, C2: Into<C1>>(v: HttpResponse<T2, C2>) -> Self {
        Self {
            status_code: v.status_code,
            headers: v.headers,
            body: v.body,
            streaming_strategy: v.streaming_strategy.map(StreamingStrategy::from),
            upgrade: v.upgrade,
        }
    }
    /// Convert this streaming strategy
    pub fn into<T2, C2>(self) -> HttpResponse<T2, C2>
    where
        T1: Into<T2>,
        C1: Into<C2>,
    {
        HttpResponse::from(self)
    }
    /// Attempt to convert another streaming strategy
    pub fn try_from<T2, C2, E>(v: HttpResponse<T2, C2>) -> Result<Self, E>
    where
        T2: TryInto<T1>,
        C2: TryInto<C1>,
        T2::Error: Into<E>,
        C2::Error: Into<E>,
    {
        Ok(Self {
            status_code: v.status_code,
            headers: v.headers,
            body: v.body,
            streaming_strategy: v
                .streaming_strategy
                .map(StreamingStrategy::try_from)
                .transpose()?,
            upgrade: v.upgrade,
        })
    }
    /// Attempt to convert this streaming strategy
    pub fn try_into<T2, C2, E>(self) -> Result<HttpResponse<T2, C2>, E>
    where
        T1: TryInto<T2>,
        C1: TryInto<C2>,
        T1::Error: Into<E>,
        C1::Error: Into<E>,
    {
        HttpResponse::try_from(self)
    }
}

/// Possible strategies for a streaming response.
#[derive(Debug, Clone, CandidType, Deserialize)]
pub enum StreamingStrategy<Token = self::Token, Callback = HttpRequestStreamingCallback> {
    /// A callback-based streaming strategy, where a callback function is provided for continuing the stream.
    Callback(CallbackStrategy<Token, Callback>),
}

impl<T1, C1> StreamingStrategy<T1, C1> {
    /// Convert another streaming strategy
    pub fn from<T2: Into<T1>, C2: Into<C1>>(v: StreamingStrategy<T2, C2>) -> Self {
        match v {
            StreamingStrategy::Callback(c) => Self::Callback(c.into()),
        }
    }
    /// Convert this streaming strategy
    pub fn into<T2, C2>(self) -> StreamingStrategy<T2, C2>
    where
        T1: Into<T2>,
        C1: Into<C2>,
    {
        StreamingStrategy::from(self)
    }
    /// Attempt to convert another streaming strategy
    pub fn try_from<T2, C2, E>(v: StreamingStrategy<T2, C2>) -> Result<Self, E>
    where
        T2: TryInto<T1>,
        C2: TryInto<C1>,
        T2::Error: Into<E>,
        C2::Error: Into<E>,
    {
        Ok(match v {
            StreamingStrategy::Callback(c) => Self::Callback(c.try_into()?),
        })
    }
    /// Attempt to convert this streaming strategy
    pub fn try_into<T2, C2, E>(self) -> Result<StreamingStrategy<T2, C2>, E>
    where
        T1: TryInto<T2>,
        C1: TryInto<C2>,
        T1::Error: Into<E>,
        C1::Error: Into<E>,
    {
        StreamingStrategy::try_from(self)
    }
}

/// A callback-token pair for a callback streaming strategy.
#[derive(Debug, Clone, CandidType, Deserialize)]
pub struct CallbackStrategy<Token = self::Token, Callback = HttpRequestStreamingCallback> {
    /// The callback function to be called to continue the stream.
    pub callback: Callback,
    /// The token to pass to the function.
    pub token: Token,
}

impl<T1, C1> CallbackStrategy<T1, C1> {
    /// Convert another callback strategy
    pub fn from<T2: Into<T1>, C2: Into<C1>>(v: CallbackStrategy<T2, C2>) -> Self {
        Self {
            callback: v.callback.into(),
            token: v.token.into(),
        }
    }
    /// Convert this callback strategy
    pub fn into<T2, C2>(self) -> CallbackStrategy<T2, C2>
    where
        T1: Into<T2>,
        C1: Into<C2>,
    {
        CallbackStrategy::from(self)
    }
    /// Attempt to convert another callback strategy
    pub fn try_from<T2, C2, E>(v: CallbackStrategy<T2, C2>) -> Result<Self, E>
    where
        T2: TryInto<T1>,
        C2: TryInto<C1>,
        T2::Error: Into<E>,
        C2::Error: Into<E>,
    {
        Ok(Self {
            callback: v.callback.try_into().map_err(Into::into)?,
            token: v.token.try_into().map_err(Into::into)?,
        })
    }
    /// Attempt to convert this callback strategy
    pub fn try_into<T2, C2, E>(self) -> Result<CallbackStrategy<T2, C2>, E>
    where
        T1: TryInto<T2>,
        C1: TryInto<C2>,
        T1::Error: Into<E>,
        C1::Error: Into<E>,
    {
        CallbackStrategy::try_from(self)
    }
}

/// A callback of any type, extremely permissive
#[derive(Debug, Clone)]
pub struct HttpRequestStreamingCallbackAny(pub Func);

impl CandidType for HttpRequestStreamingCallbackAny {
    fn _ty() -> Type {
        TypeInner::Reserved.into()
    }
    fn idl_serialize<S: Serializer>(&self, _serializer: S) -> Result<(), S::Error> {
        // We cannot implement serialize, since our type must be `Reserved` in order to accept anything.
        // Attempting to serialize this type is always an error and should be regarded as a compile time error.
        unimplemented!("Callback is not serializable")
    }
}

impl<'de> Deserialize<'de> for HttpRequestStreamingCallbackAny {
    fn deserialize<D: serde::de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        // Ya know it says `ignored`, but what if we just didn't ignore it.
        deserializer.deserialize_ignored_any(FuncVisitor).map(Self)
    }
}

impl From<Func> for HttpRequestStreamingCallbackAny {
    fn from(f: Func) -> Self {
        Self(f)
    }
}
impl From<HttpRequestStreamingCallbackAny> for Func {
    fn from(c: HttpRequestStreamingCallbackAny) -> Self {
        c.0
    }
}

/// A callback of type `shared query (Token) -> async StreamingCallbackHttpResponse`
#[derive(Debug, Clone)]
pub struct HttpRequestStreamingCallback<ArgToken = self::ArgToken>(
    pub Func,
    pub PhantomData<ArgToken>,
);

impl<ArgToken: CandidType> CandidType for HttpRequestStreamingCallback<ArgToken> {
    fn _ty() -> Type {
        candid::func!((ArgToken) -> (StreamingCallbackHttpResponse::<ArgToken>) query)
    }
    fn idl_serialize<S: Serializer>(&self, serializer: S) -> Result<(), S::Error> {
        self.0.idl_serialize(serializer)
    }
}

impl<'de, ArgToken> Deserialize<'de> for HttpRequestStreamingCallback<ArgToken> {
    fn deserialize<D: serde::de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        Func::deserialize(deserializer).map(Self::from)
    }
}

impl<ArgToken> From<Func> for HttpRequestStreamingCallback<ArgToken> {
    fn from(f: Func) -> Self {
        Self(f, PhantomData)
    }
}

impl<ArgToken> From<HttpRequestStreamingCallback<ArgToken>> for Func {
    fn from(c: HttpRequestStreamingCallback<ArgToken>) -> Self {
        c.0
    }
}

impl<ArgToken> Deref for HttpRequestStreamingCallback<ArgToken> {
    type Target = Func;
    fn deref(&self) -> &Func {
        &self.0
    }
}

impl<ArgToken> DerefMut for HttpRequestStreamingCallback<ArgToken> {
    fn deref_mut(&mut self) -> &mut Func {
        &mut self.0
    }
}

/// The next chunk of a streaming HTTP response.
#[derive(Debug, Clone, CandidType, Deserialize)]
pub struct StreamingCallbackHttpResponse<Token = self::Token> {
    /// The body of the stream chunk.
    #[serde(with = "serde_bytes")]
    pub body: Vec<u8>,
    /// The new stream continuation token.
    pub token: Option<Token>,
}

/// A token for continuing a callback streaming strategy. This type cannot be serialized despite implementing `CandidType`
#[derive(Debug, Clone, PartialEq)]
pub struct Token(pub IDLValue);

impl CandidType for Token {
    fn _ty() -> Type {
        TypeInner::Reserved.into()
    }
    fn idl_serialize<S: Serializer>(&self, _serializer: S) -> Result<(), S::Error> {
        // We cannot implement serialize, since our type must be `Reserved` in order to accept anything.
        // Attempting to serialize this type is always an error and should be regarded as a compile time error.
        unimplemented!("Token is not serializable")
    }
}

impl<'de> Deserialize<'de> for Token {
    fn deserialize<D: serde::de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        // Ya know it says `ignored`, but what if we just didn't ignore it.
        deserializer
            .deserialize_ignored_any(IDLValueVisitor)
            .map(Token)
    }
}

/// A marker type to match unconstrained callback arguments
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
pub struct ArgToken;

impl CandidType for ArgToken {
    fn _ty() -> Type {
        TypeInner::Empty.into()
    }
    fn idl_serialize<S: Serializer>(&self, _serializer: S) -> Result<(), S::Error> {
        // We cannot implement serialize, since our type must be `Empty` in order to accept anything.
        // Attempting to serialize this type is always an error and should be regarded as a compile time error.
        unimplemented!("Token is not serializable")
    }
}

impl<'agent> HttpRequestCanister<'agent> {
    /// Create an instance of a `HttpRequestCanister` interface pointing to the specified Canister ID.
    pub fn create(agent: &'agent Agent, canister_id: Principal) -> Self {
        Self(
            Canister::builder()
                .with_agent(agent)
                .with_canister_id(canister_id)
                .build()
                .unwrap(),
        )
    }

    /// Create a `HttpRequestCanister` interface from an existing canister object.
    pub fn from_canister(canister: Canister<'agent>) -> Self {
        Self(canister)
    }
}

impl<'agent> HttpRequestCanister<'agent> {
    /// Performs a HTTP request, receiving a HTTP response.
    pub fn http_request<'canister: 'agent>(
        &'canister self,
        method: impl AsRef<str>,
        url: impl AsRef<str>,
        headers: impl IntoIterator<
            Item = HeaderField<'agent>,
            IntoIter = impl 'agent + Send + Sync + Clone + ExactSizeIterator<Item = HeaderField<'agent>>,
        >,
        body: impl AsRef<[u8]>,
        certificate_version: Option<&u16>,
    ) -> impl 'agent + SyncCall<(HttpResponse,)> {
        self.http_request_custom(
            method.as_ref(),
            url.as_ref(),
            headers.into_iter(),
            body.as_ref(),
            certificate_version,
        )
    }

    /// Performs a HTTP request, receiving a HTTP response.
    /// `T` and `C` are the `token` and `callback` types for the `streaming_strategy`.
    pub fn http_request_custom<'canister: 'agent, H, T, C>(
        &'canister self,
        method: &str,
        url: &str,
        headers: H,
        body: &[u8],
        certificate_version: Option<&u16>,
    ) -> impl 'agent + SyncCall<(HttpResponse<T, C>,)>
    where
        H: 'agent + Send + Sync + Clone + ExactSizeIterator<Item = HeaderField<'agent>>,
        T: 'agent + Send + Sync + CandidType + for<'de> Deserialize<'de>,
        C: 'agent + Send + Sync + CandidType + for<'de> Deserialize<'de>,
    {
        self.query("http_request")
            .with_arg(HttpRequest {
                method,
                url,
                headers: Headers(headers),
                body,
                certificate_version,
            })
            .build()
    }

    /// Performs a HTTP request over an update call. Unlike query calls, update calls must pass consensus
    /// and therefore cannot be tampered with by a malicious node.
    pub fn http_request_update<'canister: 'agent>(
        &'canister self,
        method: impl AsRef<str>,
        url: impl AsRef<str>,
        headers: impl 'agent + Send + Sync + Clone + ExactSizeIterator<Item = HeaderField<'agent>>,
        body: impl AsRef<[u8]>,
    ) -> impl 'agent + AsyncCall<(HttpResponse,)> {
        self.http_request_update_custom(method.as_ref(), url.as_ref(), headers, body.as_ref())
    }

    /// Performs a HTTP request over an update call. Unlike query calls, update calls must pass consensus
    /// and therefore cannot be tampered with by a malicious node.
    /// `T` and `C` are the `token` and `callback` types for the `streaming_strategy`.
    pub fn http_request_update_custom<'canister: 'agent, H, T, C>(
        &'canister self,
        method: &str,
        url: &str,
        headers: H,
        body: &[u8],
    ) -> impl 'agent + AsyncCall<(HttpResponse<T, C>,)>
    where
        H: 'agent + Send + Sync + Clone + ExactSizeIterator<Item = HeaderField<'agent>>,
        T: 'agent + Send + Sync + CandidType + for<'de> Deserialize<'de>,
        C: 'agent + Send + Sync + CandidType + for<'de> Deserialize<'de>,
    {
        self.update("http_request_update")
            .with_arg(HttpUpdateRequest {
                method,
                url,
                headers: Headers(headers),
                body,
            })
            .build()
    }

    /// Retrieves the next chunk of a stream from a streaming callback, using the method from [`CallbackStrategy`].
    pub fn http_request_stream_callback<'canister: 'agent>(
        &'canister self,
        method: impl AsRef<str>,
        token: Token,
    ) -> impl 'agent + SyncCall<(StreamingCallbackHttpResponse,)> {
        self.query(method.as_ref()).with_value_arg(token.0).build()
    }

    /// Retrieves the next chunk of a stream from a streaming callback, using the method from [`CallbackStrategy`].
    /// `T` is the `token` type.
    pub fn http_request_stream_callback_custom<'canister: 'agent, T>(
        &'canister self,
        method: impl AsRef<str>,
        token: T,
    ) -> impl 'agent + SyncCall<(StreamingCallbackHttpResponse<T>,)>
    where
        T: 'agent + Send + Sync + CandidType + for<'de> Deserialize<'de>,
    {
        self.query(method.as_ref()).with_arg(token).build()
    }
}

#[cfg(test)]
mod test {
    use crate::interfaces::http_request::HttpRequestStreamingCallbackAny;

    use super::{
        CallbackStrategy, HttpRequestStreamingCallback, HttpResponse,
        StreamingCallbackHttpResponse, StreamingStrategy, Token,
    };
    use candid::{
        types::value::{IDLField, IDLValue},
        CandidType, Decode, Deserialize, Encode,
    };
    use serde::de::DeserializeOwned;

    mod pre_update_legacy {
        use candid::{define_function, CandidType, Deserialize, Nat};
        use serde_bytes::ByteBuf;

        #[derive(CandidType, Deserialize)]
        pub struct Token {
            pub key: String,
            pub content_encoding: String,
            pub index: Nat,
            pub sha256: Option<ByteBuf>,
        }

        define_function!(pub CallbackFunc : () -> ());
        #[derive(CandidType, Deserialize)]
        pub struct CallbackStrategy {
            pub callback: CallbackFunc,
            pub token: Token,
        }

        #[derive(CandidType, Clone, Deserialize)]
        pub struct HeaderField(pub String, pub String);

        #[derive(CandidType, Deserialize)]
        pub enum StreamingStrategy {
            Callback(CallbackStrategy),
        }

        #[derive(CandidType, Deserialize)]
        pub struct HttpResponse {
            pub status_code: u16,
            pub headers: Vec<HeaderField>,
            #[serde(with = "serde_bytes")]
            pub body: Vec<u8>,
            pub streaming_strategy: Option<StreamingStrategy>,
        }
    }

    #[test]
    fn deserialize_legacy_http_response() {
        let bytes: Vec<u8> = Encode!(&pre_update_legacy::HttpResponse {
            status_code: 100,
            headers: Vec::new(),
            body: Vec::new(),
            streaming_strategy: None,
        })
        .unwrap();

        let _response = Decode!(&bytes, HttpResponse).unwrap();
    }

    #[test]
    fn deserialize_response_with_token() {
        use candid::{types::Label, Func, Principal};

        fn decode<C: CandidType + DeserializeOwned>(bytes: &[u8]) {
            let response = Decode!(bytes, HttpResponse::<_, C>).unwrap();
            assert_eq!(response.status_code, 100);
            let token = match response.streaming_strategy {
                Some(StreamingStrategy::Callback(CallbackStrategy { token, .. })) => token,
                _ => panic!("streaming_strategy was missing"),
            };
            let fields = match token {
                Token(IDLValue::Record(fields)) => fields,
                _ => panic!("token type mismatched {:?}", token),
            };
            assert!(fields.contains(&IDLField {
                id: Label::Named("key".into()),
                val: IDLValue::Text("foo".into())
            }));
            assert!(fields.contains(&IDLField {
                id: Label::Named("content_encoding".into()),
                val: IDLValue::Text("bar".into())
            }));
            assert!(fields.contains(&IDLField {
                id: Label::Named("index".into()),
                val: IDLValue::Nat(42u8.into())
            }));
            assert!(fields.contains(&IDLField {
                id: Label::Named("sha256".into()),
                val: IDLValue::None
            }));
        }

        // Test if we can load legacy responses that use the `Func` workaround hack
        let bytes = Encode!(&HttpResponse {
            status_code: 100,
            headers: Vec::new(),
            body: Vec::new(),
            streaming_strategy: Some(StreamingStrategy::Callback(CallbackStrategy {
                callback: pre_update_legacy::CallbackFunc(Func {
                    principal: Principal::from_text("2chl6-4hpzw-vqaaa-aaaaa-c").unwrap(),
                    method: "callback".into()
                }),
                token: pre_update_legacy::Token {
                    key: "foo".into(),
                    content_encoding: "bar".into(),
                    index: 42u8.into(),
                    sha256: None,
                },
            })),
            upgrade: None,
        })
        .unwrap();
        decode::<pre_update_legacy::CallbackFunc>(&bytes);
        decode::<HttpRequestStreamingCallbackAny>(&bytes);

        let bytes = Encode!(&HttpResponse {
            status_code: 100,
            headers: Vec::new(),
            body: Vec::new(),
            streaming_strategy: Some(StreamingStrategy::Callback(CallbackStrategy::<
                _,
                HttpRequestStreamingCallback,
            > {
                callback: Func {
                    principal: Principal::from_text("2chl6-4hpzw-vqaaa-aaaaa-c").unwrap(),
                    method: "callback".into()
                }
                .into(),
                token: pre_update_legacy::Token {
                    key: "foo".into(),
                    content_encoding: "bar".into(),
                    index: 42u8.into(),
                    sha256: None,
                },
            })),
            upgrade: None,
        })
        .unwrap();
        decode::<HttpRequestStreamingCallback>(&bytes);
        decode::<HttpRequestStreamingCallbackAny>(&bytes);
    }

    #[test]
    fn deserialize_streaming_response_with_token() {
        use candid::types::Label;

        let bytes: Vec<u8> = Encode!(&StreamingCallbackHttpResponse {
            body: b"this is a body".as_ref().into(),
            token: Some(pre_update_legacy::Token {
                key: "foo".into(),
                content_encoding: "bar".into(),
                index: 42u8.into(),
                sha256: None,
            }),
        })
        .unwrap();

        let response = Decode!(&bytes, StreamingCallbackHttpResponse).unwrap();
        assert_eq!(response.body, b"this is a body");
        let fields = match response.token {
            Some(Token(IDLValue::Record(fields))) => fields,
            _ => panic!("token type mismatched {:?}", response.token),
        };
        assert!(fields.contains(&IDLField {
            id: Label::Named("key".into()),
            val: IDLValue::Text("foo".into())
        }));
        assert!(fields.contains(&IDLField {
            id: Label::Named("content_encoding".into()),
            val: IDLValue::Text("bar".into())
        }));
        assert!(fields.contains(&IDLField {
            id: Label::Named("index".into()),
            val: IDLValue::Nat(42u8.into())
        }));
        assert!(fields.contains(&IDLField {
            id: Label::Named("sha256".into()),
            val: IDLValue::None
        }));
    }

    #[test]
    fn deserialize_streaming_response_without_token() {
        mod missing_token {
            use candid::{CandidType, Deserialize};
            /// The next chunk of a streaming HTTP response.
            #[derive(Debug, Clone, CandidType, Deserialize)]
            pub struct StreamingCallbackHttpResponse {
                /// The body of the stream chunk.
                #[serde(with = "serde_bytes")]
                pub body: Vec<u8>,
            }
        }
        let bytes: Vec<u8> = Encode!(&missing_token::StreamingCallbackHttpResponse {
            body: b"this is a body".as_ref().into(),
        })
        .unwrap();

        let response = Decode!(&bytes, StreamingCallbackHttpResponse).unwrap();
        assert_eq!(response.body, b"this is a body");
        assert_eq!(response.token, None);

        let bytes: Vec<u8> = Encode!(&StreamingCallbackHttpResponse {
            body: b"this is a body".as_ref().into(),
            token: Option::<pre_update_legacy::Token>::None,
        })
        .unwrap();

        let response = Decode!(&bytes, StreamingCallbackHttpResponse).unwrap();
        assert_eq!(response.body, b"this is a body");
        assert_eq!(response.token, None);
    }

    #[test]
    fn deserialize_with_enum_token() {
        #[derive(Debug, Clone, CandidType, Deserialize)]
        pub enum EnumToken {
            Foo,
            Bar,
            Baz,
        }
        #[derive(Debug, Clone, CandidType, Deserialize)]
        pub struct EmbedToken {
            value: String,
            other_value: EnumToken,
        }

        let bytes: Vec<u8> = Encode!(&StreamingCallbackHttpResponse {
            body: b"this is a body".as_ref().into(),
            token: Some(EnumToken::Foo),
        })
        .unwrap();

        let response = Decode!(&bytes, StreamingCallbackHttpResponse).unwrap();
        assert_eq!(response.body, b"this is a body");
        assert!(response.token.is_some());

        let bytes: Vec<u8> = Encode!(&StreamingCallbackHttpResponse {
            body: b"this is a body".as_ref().into(),
            token: Option::<EnumToken>::None,
        })
        .unwrap();

        let response = Decode!(&bytes, StreamingCallbackHttpResponse).unwrap();
        assert_eq!(response.body, b"this is a body");
        assert_eq!(response.token, None);

        let bytes: Vec<u8> = Encode!(&StreamingCallbackHttpResponse {
            body: b"this is a body".as_ref().into(),
            token: Some(EmbedToken {
                value: "token string".into(),
                other_value: EnumToken::Foo
            }),
        })
        .unwrap();

        let response = Decode!(&bytes, StreamingCallbackHttpResponse).unwrap();
        assert_eq!(response.body, b"this is a body");
        assert!(response.token.is_some());

        let bytes: Vec<u8> = Encode!(&StreamingCallbackHttpResponse {
            body: b"this is a body".as_ref().into(),
            token: Option::<EmbedToken>::None,
        })
        .unwrap();

        let response = Decode!(&bytes, StreamingCallbackHttpResponse).unwrap();
        assert_eq!(response.body, b"this is a body");
        assert_eq!(response.token, None);
    }
}