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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
// =================================================================
//
//                           * WARNING *
//
//                    This file is generated!
//
//  Changes made to this file will be overwritten. If changes are
//  required to the generated code, the service_crategen project
//  must be updated to generate the changes.
//
// =================================================================

use std::error::Error;
use std::fmt;
use std::io;

#[allow(warnings)]
use futures::future;
use futures::Future;
use rusoto_core::region;
use rusoto_core::request::{BufferedHttpResponse, DispatchSignedRequest};
use rusoto_core::{Client, RusotoFuture};

use rusoto_core::credential::{CredentialsError, ProvideAwsCredentials};
use rusoto_core::request::HttpDispatchError;

use rusoto_core::signature::SignedRequest;
use serde_json;
use serde_json::from_slice;
use serde_json::Value as SerdeJsonValue;
/// <p>A BatchMeterUsageRequest contains UsageRecords, which indicate quantities of usage within your application.</p>
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct BatchMeterUsageRequest {
    /// <p>Product code is used to uniquely identify a product in AWS Marketplace. The product code should be the same as the one used during the publishing of a new product.</p>
    #[serde(rename = "ProductCode")]
    pub product_code: String,
    /// <p>The set of UsageRecords to submit. BatchMeterUsage accepts up to 25 UsageRecords at a time.</p>
    #[serde(rename = "UsageRecords")]
    pub usage_records: Vec<UsageRecord>,
}

/// <p>Contains the UsageRecords processed by BatchMeterUsage and any records that have failed due to transient error.</p>
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct BatchMeterUsageResult {
    /// <p>Contains all UsageRecords processed by BatchMeterUsage. These records were either honored by AWS Marketplace Metering Service or were invalid.</p>
    #[serde(rename = "Results")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub results: Option<Vec<UsageRecordResult>>,
    /// <p>Contains all UsageRecords that were not processed by BatchMeterUsage. This is a list of UsageRecords. You can retry the failed request by making another BatchMeterUsage call with this list as input in the BatchMeterUsageRequest.</p>
    #[serde(rename = "UnprocessedRecords")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unprocessed_records: Option<Vec<UsageRecord>>,
}

#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct MeterUsageRequest {
    /// <p>Checks whether you have the permissions required for the action, but does not make the request. If you have the permissions, the request returns DryRunOperation; otherwise, it returns UnauthorizedException.</p>
    #[serde(rename = "DryRun")]
    pub dry_run: bool,
    /// <p>Product code is used to uniquely identify a product in AWS Marketplace. The product code should be the same as the one used during the publishing of a new product.</p>
    #[serde(rename = "ProductCode")]
    pub product_code: String,
    /// <p>Timestamp of the hour, recorded in UTC. The seconds and milliseconds portions of the timestamp will be ignored.</p>
    #[serde(rename = "Timestamp")]
    pub timestamp: f64,
    /// <p>It will be one of the fcp dimension name provided during the publishing of the product.</p>
    #[serde(rename = "UsageDimension")]
    pub usage_dimension: String,
    /// <p>Consumption value for the hour.</p>
    #[serde(rename = "UsageQuantity")]
    pub usage_quantity: i64,
}

#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct MeterUsageResult {
    /// <p>Metering record id.</p>
    #[serde(rename = "MeteringRecordId")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metering_record_id: Option<String>,
}

#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct RegisterUsageRequest {
    /// <p>(Optional) To scope down the registration to a specific running software instance and guard against replay attacks.</p>
    #[serde(rename = "Nonce")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nonce: Option<String>,
    /// <p>Product code is used to uniquely identify a product in AWS Marketplace. The product code should be the same as the one used during the publishing of a new product.</p>
    #[serde(rename = "ProductCode")]
    pub product_code: String,
    /// <p>Public Key Version provided by AWS Marketplace</p>
    #[serde(rename = "PublicKeyVersion")]
    pub public_key_version: i64,
}

#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct RegisterUsageResult {
    /// <p>(Optional) Only included when public key version has expired</p>
    #[serde(rename = "PublicKeyRotationTimestamp")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub public_key_rotation_timestamp: Option<f64>,
    /// <p>JWT Token</p>
    #[serde(rename = "Signature")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
}

/// <p>Contains input to the ResolveCustomer operation.</p>
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct ResolveCustomerRequest {
    /// <p>When a buyer visits your website during the registration process, the buyer submits a registration token through the browser. The registration token is resolved to obtain a CustomerIdentifier and product code.</p>
    #[serde(rename = "RegistrationToken")]
    pub registration_token: String,
}

/// <p>The result of the ResolveCustomer operation. Contains the CustomerIdentifier and product code.</p>
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct ResolveCustomerResult {
    /// <p>The CustomerIdentifier is used to identify an individual customer in your application. Calls to BatchMeterUsage require CustomerIdentifiers for each UsageRecord.</p>
    #[serde(rename = "CustomerIdentifier")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub customer_identifier: Option<String>,
    /// <p>The product code is returned to confirm that the buyer is registering for your product. Subsequent BatchMeterUsage calls should be made using this product code.</p>
    #[serde(rename = "ProductCode")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub product_code: Option<String>,
}

/// <p>A UsageRecord indicates a quantity of usage for a given product, customer, dimension and time.</p> <p>Multiple requests with the same UsageRecords as input will be deduplicated to prevent double charges.</p>
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UsageRecord {
    /// <p>The CustomerIdentifier is obtained through the ResolveCustomer operation and represents an individual buyer in your application.</p>
    #[serde(rename = "CustomerIdentifier")]
    pub customer_identifier: String,
    /// <p>During the process of registering a product on AWS Marketplace, up to eight dimensions are specified. These represent different units of value in your application.</p>
    #[serde(rename = "Dimension")]
    pub dimension: String,
    /// <p>The quantity of usage consumed by the customer for the given dimension and time.</p>
    #[serde(rename = "Quantity")]
    pub quantity: i64,
    /// <p>Timestamp of the hour, recorded in UTC. The seconds and milliseconds portions of the timestamp will be ignored.</p> <p>Your application can meter usage for up to one hour in the past.</p>
    #[serde(rename = "Timestamp")]
    pub timestamp: f64,
}

/// <p>A UsageRecordResult indicates the status of a given UsageRecord processed by BatchMeterUsage.</p>
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct UsageRecordResult {
    /// <p>The MeteringRecordId is a unique identifier for this metering event.</p>
    #[serde(rename = "MeteringRecordId")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metering_record_id: Option<String>,
    /// <p><p>The UsageRecordResult Status indicates the status of an individual UsageRecord processed by BatchMeterUsage.</p> <ul> <li> <p> <i>Success</i>- The UsageRecord was accepted and honored by BatchMeterUsage.</p> </li> <li> <p> <i>CustomerNotSubscribed</i>- The CustomerIdentifier specified is not subscribed to your product. The UsageRecord was not honored. Future UsageRecords for this customer will fail until the customer subscribes to your product.</p> </li> <li> <p> <i>DuplicateRecord</i>- Indicates that the UsageRecord was invalid and not honored. A previously metered UsageRecord had the same customer, dimension, and time, but a different quantity.</p> </li> </ul></p>
    #[serde(rename = "Status")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    /// <p>The UsageRecord that was part of the BatchMeterUsage request.</p>
    #[serde(rename = "UsageRecord")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage_record: Option<UsageRecord>,
}

/// Errors returned by BatchMeterUsage
#[derive(Debug, PartialEq)]
pub enum BatchMeterUsageError {
    /// <p>The API is disabled in the Region.</p>
    DisabledApi(String),
    /// <p>An internal error has occurred. Retry your request. If the problem persists, post a message with details on the AWS forums.</p>
    InternalServiceError(String),
    /// <p>You have metered usage for a CustomerIdentifier that does not exist.</p>
    InvalidCustomerIdentifier(String),
    /// <p>The product code passed does not match the product code used for publishing the product.</p>
    InvalidProductCode(String),
    /// <p>The usage dimension does not match one of the UsageDimensions associated with products.</p>
    InvalidUsageDimension(String),
    /// <p>The calls to the API are throttled.</p>
    Throttling(String),
    /// <p>The timestamp value passed in the meterUsage() is out of allowed range.</p>
    TimestampOutOfBounds(String),
    /// An error occurred dispatching the HTTP request
    HttpDispatch(HttpDispatchError),
    /// An error was encountered with AWS credentials.
    Credentials(CredentialsError),
    /// A validation error occurred.  Details from AWS are provided.
    Validation(String),
    /// An error occurred parsing the response payload.
    ParseError(String),
    /// An unknown error occurred.  The raw HTTP response is provided.
    Unknown(BufferedHttpResponse),
}

impl BatchMeterUsageError {
    pub fn from_response(res: BufferedHttpResponse) -> BatchMeterUsageError {
        if let Ok(json) = from_slice::<SerdeJsonValue>(&res.body) {
            let raw_error_type = json
                .get("__type")
                .and_then(|e| e.as_str())
                .unwrap_or("Unknown");
            let error_message = json.get("message").and_then(|m| m.as_str()).unwrap_or("");

            let pieces: Vec<&str> = raw_error_type.split("#").collect();
            let error_type = pieces.last().expect("Expected error type");

            match *error_type {
                "DisabledApiException" => {
                    return BatchMeterUsageError::DisabledApi(String::from(error_message));
                }
                "InternalServiceErrorException" => {
                    return BatchMeterUsageError::InternalServiceError(String::from(error_message));
                }
                "InvalidCustomerIdentifierException" => {
                    return BatchMeterUsageError::InvalidCustomerIdentifier(String::from(
                        error_message,
                    ));
                }
                "InvalidProductCodeException" => {
                    return BatchMeterUsageError::InvalidProductCode(String::from(error_message));
                }
                "InvalidUsageDimensionException" => {
                    return BatchMeterUsageError::InvalidUsageDimension(String::from(error_message));
                }
                "ThrottlingException" => {
                    return BatchMeterUsageError::Throttling(String::from(error_message));
                }
                "TimestampOutOfBoundsException" => {
                    return BatchMeterUsageError::TimestampOutOfBounds(String::from(error_message));
                }
                "ValidationException" => {
                    return BatchMeterUsageError::Validation(error_message.to_string());
                }
                _ => {}
            }
        }
        return BatchMeterUsageError::Unknown(res);
    }
}

impl From<serde_json::error::Error> for BatchMeterUsageError {
    fn from(err: serde_json::error::Error) -> BatchMeterUsageError {
        BatchMeterUsageError::ParseError(err.description().to_string())
    }
}
impl From<CredentialsError> for BatchMeterUsageError {
    fn from(err: CredentialsError) -> BatchMeterUsageError {
        BatchMeterUsageError::Credentials(err)
    }
}
impl From<HttpDispatchError> for BatchMeterUsageError {
    fn from(err: HttpDispatchError) -> BatchMeterUsageError {
        BatchMeterUsageError::HttpDispatch(err)
    }
}
impl From<io::Error> for BatchMeterUsageError {
    fn from(err: io::Error) -> BatchMeterUsageError {
        BatchMeterUsageError::HttpDispatch(HttpDispatchError::from(err))
    }
}
impl fmt::Display for BatchMeterUsageError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.description())
    }
}
impl Error for BatchMeterUsageError {
    fn description(&self) -> &str {
        match *self {
            BatchMeterUsageError::DisabledApi(ref cause) => cause,
            BatchMeterUsageError::InternalServiceError(ref cause) => cause,
            BatchMeterUsageError::InvalidCustomerIdentifier(ref cause) => cause,
            BatchMeterUsageError::InvalidProductCode(ref cause) => cause,
            BatchMeterUsageError::InvalidUsageDimension(ref cause) => cause,
            BatchMeterUsageError::Throttling(ref cause) => cause,
            BatchMeterUsageError::TimestampOutOfBounds(ref cause) => cause,
            BatchMeterUsageError::Validation(ref cause) => cause,
            BatchMeterUsageError::Credentials(ref err) => err.description(),
            BatchMeterUsageError::HttpDispatch(ref dispatch_error) => dispatch_error.description(),
            BatchMeterUsageError::ParseError(ref cause) => cause,
            BatchMeterUsageError::Unknown(_) => "unknown error",
        }
    }
}
/// Errors returned by MeterUsage
#[derive(Debug, PartialEq)]
pub enum MeterUsageError {
    /// <p>A metering record has already been emitted by the same EC2 instance for the given {usageDimension, timestamp} with a different usageQuantity.</p>
    DuplicateRequest(String),
    /// <p>An internal error has occurred. Retry your request. If the problem persists, post a message with details on the AWS forums.</p>
    InternalServiceError(String),
    /// <p>The endpoint being called is in a Region different from your EC2 instance. The Region of the Metering Service endpoint and the Region of the EC2 instance must match.</p>
    InvalidEndpointRegion(String),
    /// <p>The product code passed does not match the product code used for publishing the product.</p>
    InvalidProductCode(String),
    /// <p>The usage dimension does not match one of the UsageDimensions associated with products.</p>
    InvalidUsageDimension(String),
    /// <p>The calls to the API are throttled.</p>
    Throttling(String),
    /// <p>The timestamp value passed in the meterUsage() is out of allowed range.</p>
    TimestampOutOfBounds(String),
    /// An error occurred dispatching the HTTP request
    HttpDispatch(HttpDispatchError),
    /// An error was encountered with AWS credentials.
    Credentials(CredentialsError),
    /// A validation error occurred.  Details from AWS are provided.
    Validation(String),
    /// An error occurred parsing the response payload.
    ParseError(String),
    /// An unknown error occurred.  The raw HTTP response is provided.
    Unknown(BufferedHttpResponse),
}

impl MeterUsageError {
    pub fn from_response(res: BufferedHttpResponse) -> MeterUsageError {
        if let Ok(json) = from_slice::<SerdeJsonValue>(&res.body) {
            let raw_error_type = json
                .get("__type")
                .and_then(|e| e.as_str())
                .unwrap_or("Unknown");
            let error_message = json.get("message").and_then(|m| m.as_str()).unwrap_or("");

            let pieces: Vec<&str> = raw_error_type.split("#").collect();
            let error_type = pieces.last().expect("Expected error type");

            match *error_type {
                "DuplicateRequestException" => {
                    return MeterUsageError::DuplicateRequest(String::from(error_message));
                }
                "InternalServiceErrorException" => {
                    return MeterUsageError::InternalServiceError(String::from(error_message));
                }
                "InvalidEndpointRegionException" => {
                    return MeterUsageError::InvalidEndpointRegion(String::from(error_message));
                }
                "InvalidProductCodeException" => {
                    return MeterUsageError::InvalidProductCode(String::from(error_message));
                }
                "InvalidUsageDimensionException" => {
                    return MeterUsageError::InvalidUsageDimension(String::from(error_message));
                }
                "ThrottlingException" => {
                    return MeterUsageError::Throttling(String::from(error_message));
                }
                "TimestampOutOfBoundsException" => {
                    return MeterUsageError::TimestampOutOfBounds(String::from(error_message));
                }
                "ValidationException" => {
                    return MeterUsageError::Validation(error_message.to_string());
                }
                _ => {}
            }
        }
        return MeterUsageError::Unknown(res);
    }
}

impl From<serde_json::error::Error> for MeterUsageError {
    fn from(err: serde_json::error::Error) -> MeterUsageError {
        MeterUsageError::ParseError(err.description().to_string())
    }
}
impl From<CredentialsError> for MeterUsageError {
    fn from(err: CredentialsError) -> MeterUsageError {
        MeterUsageError::Credentials(err)
    }
}
impl From<HttpDispatchError> for MeterUsageError {
    fn from(err: HttpDispatchError) -> MeterUsageError {
        MeterUsageError::HttpDispatch(err)
    }
}
impl From<io::Error> for MeterUsageError {
    fn from(err: io::Error) -> MeterUsageError {
        MeterUsageError::HttpDispatch(HttpDispatchError::from(err))
    }
}
impl fmt::Display for MeterUsageError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.description())
    }
}
impl Error for MeterUsageError {
    fn description(&self) -> &str {
        match *self {
            MeterUsageError::DuplicateRequest(ref cause) => cause,
            MeterUsageError::InternalServiceError(ref cause) => cause,
            MeterUsageError::InvalidEndpointRegion(ref cause) => cause,
            MeterUsageError::InvalidProductCode(ref cause) => cause,
            MeterUsageError::InvalidUsageDimension(ref cause) => cause,
            MeterUsageError::Throttling(ref cause) => cause,
            MeterUsageError::TimestampOutOfBounds(ref cause) => cause,
            MeterUsageError::Validation(ref cause) => cause,
            MeterUsageError::Credentials(ref err) => err.description(),
            MeterUsageError::HttpDispatch(ref dispatch_error) => dispatch_error.description(),
            MeterUsageError::ParseError(ref cause) => cause,
            MeterUsageError::Unknown(_) => "unknown error",
        }
    }
}
/// Errors returned by RegisterUsage
#[derive(Debug, PartialEq)]
pub enum RegisterUsageError {
    /// <p>Exception thrown when the customer does not have a valid subscription for the product.</p>
    CustomerNotEntitled(String),
    /// <p>The API is disabled in the Region.</p>
    DisabledApi(String),
    /// <p>An internal error has occurred. Retry your request. If the problem persists, post a message with details on the AWS forums.</p>
    InternalServiceError(String),
    /// <p>The product code passed does not match the product code used for publishing the product.</p>
    InvalidProductCode(String),
    /// <p>Public Key version is invalid.</p>
    InvalidPublicKeyVersion(String),
    /// <p>RegisterUsage must be called in the same AWS Region the ECS task was launched in. This prevents a container from hardcoding a Region (e.g. withRegion(“us-east-1”) when calling RegisterUsage.</p>
    InvalidRegion(String),
    /// <p>AWS Marketplace does not support metering usage from the underlying platform. Currently, only Amazon ECS is supported.</p>
    PlatformNotSupported(String),
    /// <p>The calls to the API are throttled.</p>
    Throttling(String),
    /// An error occurred dispatching the HTTP request
    HttpDispatch(HttpDispatchError),
    /// An error was encountered with AWS credentials.
    Credentials(CredentialsError),
    /// A validation error occurred.  Details from AWS are provided.
    Validation(String),
    /// An error occurred parsing the response payload.
    ParseError(String),
    /// An unknown error occurred.  The raw HTTP response is provided.
    Unknown(BufferedHttpResponse),
}

impl RegisterUsageError {
    pub fn from_response(res: BufferedHttpResponse) -> RegisterUsageError {
        if let Ok(json) = from_slice::<SerdeJsonValue>(&res.body) {
            let raw_error_type = json
                .get("__type")
                .and_then(|e| e.as_str())
                .unwrap_or("Unknown");
            let error_message = json.get("message").and_then(|m| m.as_str()).unwrap_or("");

            let pieces: Vec<&str> = raw_error_type.split("#").collect();
            let error_type = pieces.last().expect("Expected error type");

            match *error_type {
                "CustomerNotEntitledException" => {
                    return RegisterUsageError::CustomerNotEntitled(String::from(error_message));
                }
                "DisabledApiException" => {
                    return RegisterUsageError::DisabledApi(String::from(error_message));
                }
                "InternalServiceErrorException" => {
                    return RegisterUsageError::InternalServiceError(String::from(error_message));
                }
                "InvalidProductCodeException" => {
                    return RegisterUsageError::InvalidProductCode(String::from(error_message));
                }
                "InvalidPublicKeyVersionException" => {
                    return RegisterUsageError::InvalidPublicKeyVersion(String::from(error_message));
                }
                "InvalidRegionException" => {
                    return RegisterUsageError::InvalidRegion(String::from(error_message));
                }
                "PlatformNotSupportedException" => {
                    return RegisterUsageError::PlatformNotSupported(String::from(error_message));
                }
                "ThrottlingException" => {
                    return RegisterUsageError::Throttling(String::from(error_message));
                }
                "ValidationException" => {
                    return RegisterUsageError::Validation(error_message.to_string());
                }
                _ => {}
            }
        }
        return RegisterUsageError::Unknown(res);
    }
}

impl From<serde_json::error::Error> for RegisterUsageError {
    fn from(err: serde_json::error::Error) -> RegisterUsageError {
        RegisterUsageError::ParseError(err.description().to_string())
    }
}
impl From<CredentialsError> for RegisterUsageError {
    fn from(err: CredentialsError) -> RegisterUsageError {
        RegisterUsageError::Credentials(err)
    }
}
impl From<HttpDispatchError> for RegisterUsageError {
    fn from(err: HttpDispatchError) -> RegisterUsageError {
        RegisterUsageError::HttpDispatch(err)
    }
}
impl From<io::Error> for RegisterUsageError {
    fn from(err: io::Error) -> RegisterUsageError {
        RegisterUsageError::HttpDispatch(HttpDispatchError::from(err))
    }
}
impl fmt::Display for RegisterUsageError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.description())
    }
}
impl Error for RegisterUsageError {
    fn description(&self) -> &str {
        match *self {
            RegisterUsageError::CustomerNotEntitled(ref cause) => cause,
            RegisterUsageError::DisabledApi(ref cause) => cause,
            RegisterUsageError::InternalServiceError(ref cause) => cause,
            RegisterUsageError::InvalidProductCode(ref cause) => cause,
            RegisterUsageError::InvalidPublicKeyVersion(ref cause) => cause,
            RegisterUsageError::InvalidRegion(ref cause) => cause,
            RegisterUsageError::PlatformNotSupported(ref cause) => cause,
            RegisterUsageError::Throttling(ref cause) => cause,
            RegisterUsageError::Validation(ref cause) => cause,
            RegisterUsageError::Credentials(ref err) => err.description(),
            RegisterUsageError::HttpDispatch(ref dispatch_error) => dispatch_error.description(),
            RegisterUsageError::ParseError(ref cause) => cause,
            RegisterUsageError::Unknown(_) => "unknown error",
        }
    }
}
/// Errors returned by ResolveCustomer
#[derive(Debug, PartialEq)]
pub enum ResolveCustomerError {
    /// <p>The API is disabled in the Region.</p>
    DisabledApi(String),
    /// <p>The submitted registration token has expired. This can happen if the buyer's browser takes too long to redirect to your page, the buyer has resubmitted the registration token, or your application has held on to the registration token for too long. Your SaaS registration website should redeem this token as soon as it is submitted by the buyer's browser.</p>
    ExpiredToken(String),
    /// <p>An internal error has occurred. Retry your request. If the problem persists, post a message with details on the AWS forums.</p>
    InternalServiceError(String),
    /// <p>Registration token is invalid.</p>
    InvalidToken(String),
    /// <p>The calls to the API are throttled.</p>
    Throttling(String),
    /// An error occurred dispatching the HTTP request
    HttpDispatch(HttpDispatchError),
    /// An error was encountered with AWS credentials.
    Credentials(CredentialsError),
    /// A validation error occurred.  Details from AWS are provided.
    Validation(String),
    /// An error occurred parsing the response payload.
    ParseError(String),
    /// An unknown error occurred.  The raw HTTP response is provided.
    Unknown(BufferedHttpResponse),
}

impl ResolveCustomerError {
    pub fn from_response(res: BufferedHttpResponse) -> ResolveCustomerError {
        if let Ok(json) = from_slice::<SerdeJsonValue>(&res.body) {
            let raw_error_type = json
                .get("__type")
                .and_then(|e| e.as_str())
                .unwrap_or("Unknown");
            let error_message = json.get("message").and_then(|m| m.as_str()).unwrap_or("");

            let pieces: Vec<&str> = raw_error_type.split("#").collect();
            let error_type = pieces.last().expect("Expected error type");

            match *error_type {
                "DisabledApiException" => {
                    return ResolveCustomerError::DisabledApi(String::from(error_message));
                }
                "ExpiredTokenException" => {
                    return ResolveCustomerError::ExpiredToken(String::from(error_message));
                }
                "InternalServiceErrorException" => {
                    return ResolveCustomerError::InternalServiceError(String::from(error_message));
                }
                "InvalidTokenException" => {
                    return ResolveCustomerError::InvalidToken(String::from(error_message));
                }
                "ThrottlingException" => {
                    return ResolveCustomerError::Throttling(String::from(error_message));
                }
                "ValidationException" => {
                    return ResolveCustomerError::Validation(error_message.to_string());
                }
                _ => {}
            }
        }
        return ResolveCustomerError::Unknown(res);
    }
}

impl From<serde_json::error::Error> for ResolveCustomerError {
    fn from(err: serde_json::error::Error) -> ResolveCustomerError {
        ResolveCustomerError::ParseError(err.description().to_string())
    }
}
impl From<CredentialsError> for ResolveCustomerError {
    fn from(err: CredentialsError) -> ResolveCustomerError {
        ResolveCustomerError::Credentials(err)
    }
}
impl From<HttpDispatchError> for ResolveCustomerError {
    fn from(err: HttpDispatchError) -> ResolveCustomerError {
        ResolveCustomerError::HttpDispatch(err)
    }
}
impl From<io::Error> for ResolveCustomerError {
    fn from(err: io::Error) -> ResolveCustomerError {
        ResolveCustomerError::HttpDispatch(HttpDispatchError::from(err))
    }
}
impl fmt::Display for ResolveCustomerError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.description())
    }
}
impl Error for ResolveCustomerError {
    fn description(&self) -> &str {
        match *self {
            ResolveCustomerError::DisabledApi(ref cause) => cause,
            ResolveCustomerError::ExpiredToken(ref cause) => cause,
            ResolveCustomerError::InternalServiceError(ref cause) => cause,
            ResolveCustomerError::InvalidToken(ref cause) => cause,
            ResolveCustomerError::Throttling(ref cause) => cause,
            ResolveCustomerError::Validation(ref cause) => cause,
            ResolveCustomerError::Credentials(ref err) => err.description(),
            ResolveCustomerError::HttpDispatch(ref dispatch_error) => dispatch_error.description(),
            ResolveCustomerError::ParseError(ref cause) => cause,
            ResolveCustomerError::Unknown(_) => "unknown error",
        }
    }
}
/// Trait representing the capabilities of the AWSMarketplace Metering API. AWSMarketplace Metering clients implement this trait.
pub trait MarketplaceMetering {
    /// <p>BatchMeterUsage is called from a SaaS application listed on the AWS Marketplace to post metering records for a set of customers.</p> <p>For identical requests, the API is idempotent; requests can be retried with the same records or a subset of the input records.</p> <p>Every request to BatchMeterUsage is for one product. If you need to meter usage for multiple products, you must make multiple calls to BatchMeterUsage.</p> <p>BatchMeterUsage can process up to 25 UsageRecords at a time.</p>
    fn batch_meter_usage(
        &self,
        input: BatchMeterUsageRequest,
    ) -> RusotoFuture<BatchMeterUsageResult, BatchMeterUsageError>;

    /// <p>API to emit metering records. For identical requests, the API is idempotent. It simply returns the metering record ID.</p> <p>MeterUsage is authenticated on the buyer's AWS account, generally when running from an EC2 instance on the AWS Marketplace.</p>
    fn meter_usage(
        &self,
        input: MeterUsageRequest,
    ) -> RusotoFuture<MeterUsageResult, MeterUsageError>;

    /// <p><p>Paid container software products sold through AWS Marketplace must integrate with the AWS Marketplace Metering Service and call the RegisterUsage operation for software entitlement and metering. Calling RegisterUsage from containers running outside of ECS is not currently supported. Free and BYOL products for ECS aren&#39;t required to call RegisterUsage, but you may choose to do so if you would like to receive usage data in your seller reports. The sections below explain the behavior of RegisterUsage. RegisterUsage performs two primary functions: metering and entitlement.</p> <ul> <li> <p> <i>Entitlement</i>: RegisterUsage allows you to verify that the customer running your paid software is subscribed to your product on AWS Marketplace, enabling you to guard against unauthorized use. Your container image that integrates with RegisterUsage is only required to guard against unauthorized use at container startup, as such a CustomerNotSubscribedException/PlatformNotSupportedException will only be thrown on the initial call to RegisterUsage. Subsequent calls from the same Amazon ECS task instance (e.g. task-id) will not throw a CustomerNotSubscribedException, even if the customer unsubscribes while the Amazon ECS task is still running.</p> </li> <li> <p> <i>Metering</i>: RegisterUsage meters software use per ECS task, per hour, with usage prorated to the second. A minimum of 1 minute of usage applies to tasks that are short lived. For example, if a customer has a 10 node ECS cluster and creates an ECS service configured as a Daemon Set, then ECS will launch a task on all 10 cluster nodes and the customer will be charged: (10 * hourly_rate). Metering for software use is automatically handled by the AWS Marketplace Metering Control Plane -- your software is not required to perform any metering specific actions, other than call RegisterUsage once for metering of software use to commence. The AWS Marketplace Metering Control Plane will also continue to bill customers for running ECS tasks, regardless of the customers subscription state, removing the need for your software to perform entitlement checks at runtime.</p> </li> </ul></p>
    fn register_usage(
        &self,
        input: RegisterUsageRequest,
    ) -> RusotoFuture<RegisterUsageResult, RegisterUsageError>;

    /// <p>ResolveCustomer is called by a SaaS application during the registration process. When a buyer visits your website during the registration process, the buyer submits a registration token through their browser. The registration token is resolved through this API to obtain a CustomerIdentifier and product code.</p>
    fn resolve_customer(
        &self,
        input: ResolveCustomerRequest,
    ) -> RusotoFuture<ResolveCustomerResult, ResolveCustomerError>;
}
/// A client for the AWSMarketplace Metering API.
#[derive(Clone)]
pub struct MarketplaceMeteringClient {
    client: Client,
    region: region::Region,
}

impl MarketplaceMeteringClient {
    /// Creates a client backed by the default tokio event loop.
    ///
    /// The client will use the default credentials provider and tls client.
    pub fn new(region: region::Region) -> MarketplaceMeteringClient {
        MarketplaceMeteringClient {
            client: Client::shared(),
            region: region,
        }
    }

    pub fn new_with<P, D>(
        request_dispatcher: D,
        credentials_provider: P,
        region: region::Region,
    ) -> MarketplaceMeteringClient
    where
        P: ProvideAwsCredentials + Send + Sync + 'static,
        P::Future: Send,
        D: DispatchSignedRequest + Send + Sync + 'static,
        D::Future: Send,
    {
        MarketplaceMeteringClient {
            client: Client::new_with(credentials_provider, request_dispatcher),
            region: region,
        }
    }
}

impl MarketplaceMetering for MarketplaceMeteringClient {
    /// <p>BatchMeterUsage is called from a SaaS application listed on the AWS Marketplace to post metering records for a set of customers.</p> <p>For identical requests, the API is idempotent; requests can be retried with the same records or a subset of the input records.</p> <p>Every request to BatchMeterUsage is for one product. If you need to meter usage for multiple products, you must make multiple calls to BatchMeterUsage.</p> <p>BatchMeterUsage can process up to 25 UsageRecords at a time.</p>
    fn batch_meter_usage(
        &self,
        input: BatchMeterUsageRequest,
    ) -> RusotoFuture<BatchMeterUsageResult, BatchMeterUsageError> {
        let mut request = SignedRequest::new("POST", "aws-marketplace", &self.region, "/");
        request.set_endpoint_prefix("metering.marketplace".to_string());
        request.set_content_type("application/x-amz-json-1.1".to_owned());
        request.add_header("x-amz-target", "AWSMPMeteringService.BatchMeterUsage");
        let encoded = serde_json::to_string(&input).unwrap();
        request.set_payload(Some(encoded.into_bytes()));

        self.client.sign_and_dispatch(request, |response| {
            if response.status.is_success() {
                Box::new(response.buffer().from_err().map(|response| {
                    let mut body = response.body;

                    if body.is_empty() || body == b"null" {
                        body = b"{}".to_vec();
                    }

                    serde_json::from_str::<BatchMeterUsageResult>(
                        String::from_utf8_lossy(body.as_ref()).as_ref(),
                    )
                    .unwrap()
                }))
            } else {
                Box::new(
                    response
                        .buffer()
                        .from_err()
                        .and_then(|response| Err(BatchMeterUsageError::from_response(response))),
                )
            }
        })
    }

    /// <p>API to emit metering records. For identical requests, the API is idempotent. It simply returns the metering record ID.</p> <p>MeterUsage is authenticated on the buyer's AWS account, generally when running from an EC2 instance on the AWS Marketplace.</p>
    fn meter_usage(
        &self,
        input: MeterUsageRequest,
    ) -> RusotoFuture<MeterUsageResult, MeterUsageError> {
        let mut request = SignedRequest::new("POST", "aws-marketplace", &self.region, "/");
        request.set_endpoint_prefix("metering.marketplace".to_string());
        request.set_content_type("application/x-amz-json-1.1".to_owned());
        request.add_header("x-amz-target", "AWSMPMeteringService.MeterUsage");
        let encoded = serde_json::to_string(&input).unwrap();
        request.set_payload(Some(encoded.into_bytes()));

        self.client.sign_and_dispatch(request, |response| {
            if response.status.is_success() {
                Box::new(response.buffer().from_err().map(|response| {
                    let mut body = response.body;

                    if body.is_empty() || body == b"null" {
                        body = b"{}".to_vec();
                    }

                    serde_json::from_str::<MeterUsageResult>(
                        String::from_utf8_lossy(body.as_ref()).as_ref(),
                    )
                    .unwrap()
                }))
            } else {
                Box::new(
                    response
                        .buffer()
                        .from_err()
                        .and_then(|response| Err(MeterUsageError::from_response(response))),
                )
            }
        })
    }

    /// <p><p>Paid container software products sold through AWS Marketplace must integrate with the AWS Marketplace Metering Service and call the RegisterUsage operation for software entitlement and metering. Calling RegisterUsage from containers running outside of ECS is not currently supported. Free and BYOL products for ECS aren&#39;t required to call RegisterUsage, but you may choose to do so if you would like to receive usage data in your seller reports. The sections below explain the behavior of RegisterUsage. RegisterUsage performs two primary functions: metering and entitlement.</p> <ul> <li> <p> <i>Entitlement</i>: RegisterUsage allows you to verify that the customer running your paid software is subscribed to your product on AWS Marketplace, enabling you to guard against unauthorized use. Your container image that integrates with RegisterUsage is only required to guard against unauthorized use at container startup, as such a CustomerNotSubscribedException/PlatformNotSupportedException will only be thrown on the initial call to RegisterUsage. Subsequent calls from the same Amazon ECS task instance (e.g. task-id) will not throw a CustomerNotSubscribedException, even if the customer unsubscribes while the Amazon ECS task is still running.</p> </li> <li> <p> <i>Metering</i>: RegisterUsage meters software use per ECS task, per hour, with usage prorated to the second. A minimum of 1 minute of usage applies to tasks that are short lived. For example, if a customer has a 10 node ECS cluster and creates an ECS service configured as a Daemon Set, then ECS will launch a task on all 10 cluster nodes and the customer will be charged: (10 * hourly_rate). Metering for software use is automatically handled by the AWS Marketplace Metering Control Plane -- your software is not required to perform any metering specific actions, other than call RegisterUsage once for metering of software use to commence. The AWS Marketplace Metering Control Plane will also continue to bill customers for running ECS tasks, regardless of the customers subscription state, removing the need for your software to perform entitlement checks at runtime.</p> </li> </ul></p>
    fn register_usage(
        &self,
        input: RegisterUsageRequest,
    ) -> RusotoFuture<RegisterUsageResult, RegisterUsageError> {
        let mut request = SignedRequest::new("POST", "aws-marketplace", &self.region, "/");
        request.set_endpoint_prefix("metering.marketplace".to_string());
        request.set_content_type("application/x-amz-json-1.1".to_owned());
        request.add_header("x-amz-target", "AWSMPMeteringService.RegisterUsage");
        let encoded = serde_json::to_string(&input).unwrap();
        request.set_payload(Some(encoded.into_bytes()));

        self.client.sign_and_dispatch(request, |response| {
            if response.status.is_success() {
                Box::new(response.buffer().from_err().map(|response| {
                    let mut body = response.body;

                    if body.is_empty() || body == b"null" {
                        body = b"{}".to_vec();
                    }

                    serde_json::from_str::<RegisterUsageResult>(
                        String::from_utf8_lossy(body.as_ref()).as_ref(),
                    )
                    .unwrap()
                }))
            } else {
                Box::new(
                    response
                        .buffer()
                        .from_err()
                        .and_then(|response| Err(RegisterUsageError::from_response(response))),
                )
            }
        })
    }

    /// <p>ResolveCustomer is called by a SaaS application during the registration process. When a buyer visits your website during the registration process, the buyer submits a registration token through their browser. The registration token is resolved through this API to obtain a CustomerIdentifier and product code.</p>
    fn resolve_customer(
        &self,
        input: ResolveCustomerRequest,
    ) -> RusotoFuture<ResolveCustomerResult, ResolveCustomerError> {
        let mut request = SignedRequest::new("POST", "aws-marketplace", &self.region, "/");
        request.set_endpoint_prefix("metering.marketplace".to_string());
        request.set_content_type("application/x-amz-json-1.1".to_owned());
        request.add_header("x-amz-target", "AWSMPMeteringService.ResolveCustomer");
        let encoded = serde_json::to_string(&input).unwrap();
        request.set_payload(Some(encoded.into_bytes()));

        self.client.sign_and_dispatch(request, |response| {
            if response.status.is_success() {
                Box::new(response.buffer().from_err().map(|response| {
                    let mut body = response.body;

                    if body.is_empty() || body == b"null" {
                        body = b"{}".to_vec();
                    }

                    serde_json::from_str::<ResolveCustomerResult>(
                        String::from_utf8_lossy(body.as_ref()).as_ref(),
                    )
                    .unwrap()
                }))
            } else {
                Box::new(
                    response
                        .buffer()
                        .from_err()
                        .and_then(|response| Err(ResolveCustomerError::from_response(response))),
                )
            }
        })
    }
}

#[cfg(test)]
mod protocol_tests {}