Merge pull request #33 from slinkydeveloper/fetch_implementation

Reqwest integration
This commit is contained in:
Lazzaretti 2020-05-18 19:50:09 +02:00 committed by GitHub
commit 0756a68711
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 1173 additions and 196 deletions

539
Cargo.lock generated
View File

@ -279,6 +279,17 @@ version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b585a98a234c46fc563103e9278c9391fde1f4e6850334da895d27edb9580f62"
[[package]]
name = "assert-json-diff"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c356497fd3417158bcb318266ac83c391219ca3a5fa659049f42e0041ab57d6"
dependencies = [
"extend",
"serde",
"serde_json",
]
[[package]]
name = "async-trait"
version = "0.1.30"
@ -290,6 +301,17 @@ dependencies = [
"syn",
]
[[package]]
name = "atty"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
dependencies = [
"hermit-abi",
"libc",
"winapi 0.3.8",
]
[[package]]
name = "autocfg"
version = "1.0.0"
@ -379,6 +401,12 @@ dependencies = [
"libc",
]
[[package]]
name = "bumpalo"
version = "3.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5356f1d23ee24a1f785a56d1d1a5f0fd5b0f6a0c0fb2412ce11da71649ab78f6"
[[package]]
name = "byteorder"
version = "1.3.4"
@ -475,12 +503,53 @@ dependencies = [
"url",
]
[[package]]
name = "cloudevents-sdk-reqwest"
version = "0.1.0"
dependencies = [
"bytes",
"cloudevents-sdk",
"lazy_static",
"mockito",
"reqwest",
"serde_json",
"tokio",
"url",
]
[[package]]
name = "colored"
version = "1.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4ffc801dacf156c5854b9df4f425a626539c3a6ef7893cc0c5084a23f0b6c59"
dependencies = [
"atty",
"lazy_static",
"winapi 0.3.8",
]
[[package]]
name = "copyless"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ff9c56c9fb2a49c05ef0e431485a22400af20d33226dc0764d891d09e724127"
[[package]]
name = "core-foundation"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57d24c7a13c43e870e37c1556b74555437870a04514f7685f5b354e090567171"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "core-foundation-sys"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b3a71ab494c0b5b860bdc8407ae08978052417070c2ced38573a9157ad75b8ac"
[[package]]
name = "crc32fast"
version = "1.2.0"
@ -512,6 +581,12 @@ dependencies = [
"syn",
]
[[package]]
name = "difference"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "524cbf6897b527295dff137cec09ecf3a05f4fddffd7dfcd1585403449e74198"
[[package]]
name = "doc-comment"
version = "0.3.3"
@ -551,6 +626,18 @@ dependencies = [
"syn",
]
[[package]]
name = "extend"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe9db393664b0e6c6230a14115e7e798f80b70f54038dc21165db24c6b7f28fc"
dependencies = [
"proc-macro-error",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "failure"
version = "0.1.7"
@ -591,6 +678,21 @@ version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2fad85553e09a6f881f739c29f0b00b0f01357c743266d478b68951ce23285f3"
[[package]]
name = "foreign-types"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"
dependencies = [
"foreign-types-shared",
]
[[package]]
name = "foreign-types-shared"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
[[package]]
name = "fuchsia-zircon"
version = "0.3.3"
@ -787,12 +889,59 @@ dependencies = [
"itoa",
]
[[package]]
name = "http-body"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13d5ff830006f7646652e057693569bfe0d51760c0085a071769d142a205111b"
dependencies = [
"bytes",
"http",
]
[[package]]
name = "httparse"
version = "1.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd179ae861f0c2e53da70d892f5f3029f9594be0c41dc5269cd371691b1dc2f9"
[[package]]
name = "hyper"
version = "0.13.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96816e1d921eca64d208a85aab4f7798455a8e34229ee5a88c935bdee1b78b14"
dependencies = [
"bytes",
"futures-channel",
"futures-core",
"futures-util",
"h2",
"http",
"http-body",
"httparse",
"itoa",
"log",
"net2",
"pin-project",
"time",
"tokio",
"tower-service",
"want",
]
[[package]]
name = "hyper-tls"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3adcd308402b9553630734e9c36b77a7e48b3821251ca2493e8cd596763aafaa"
dependencies = [
"bytes",
"hyper",
"native-tls",
"tokio",
"tokio-tls",
]
[[package]]
name = "idna"
version = "0.2.0"
@ -840,6 +989,15 @@ version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8b7a7c0c47db5545ed3fef7468ee7bb5b74691498139e4b3f6a20685dc6dd8e"
[[package]]
name = "js-sys"
version = "0.3.39"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa5a448de267e7358beaf4a5d849518fe9a0c13fce7afd44b06e68550e5562a7"
dependencies = [
"wasm-bindgen",
]
[[package]]
name = "kernel32-sys"
version = "0.2.2"
@ -925,6 +1083,16 @@ version = "0.3.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d"
[[package]]
name = "mime_guess"
version = "2.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2684d4c2e97d99848d30b324b00c8fcc7e5c897b7cbb5819b09e7c90e8baf212"
dependencies = [
"mime",
"unicase",
]
[[package]]
name = "miniz_oxide"
version = "0.3.6"
@ -947,12 +1115,24 @@ dependencies = [
"kernel32-sys",
"libc",
"log",
"miow",
"miow 0.2.1",
"net2",
"slab",
"winapi 0.2.8",
]
[[package]]
name = "mio-named-pipes"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f5e374eff525ce1c5b7687c4cef63943e7686524a387933ad27ca7ec43779cb3"
dependencies = [
"log",
"mio",
"miow 0.3.3",
"winapi 0.3.8",
]
[[package]]
name = "mio-uds"
version = "0.6.7"
@ -976,6 +1156,52 @@ dependencies = [
"ws2_32-sys",
]
[[package]]
name = "miow"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "396aa0f2003d7df8395cb93e09871561ccc3e785f0acb369170e8cc74ddf9226"
dependencies = [
"socket2",
"winapi 0.3.8",
]
[[package]]
name = "mockito"
version = "0.25.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03dbb09048f444da040f95049763815e4352c9dcb49e4250f7ff2c6853e595dc"
dependencies = [
"assert-json-diff",
"colored",
"difference",
"httparse",
"lazy_static",
"log",
"percent-encoding",
"rand",
"regex",
"serde_json",
]
[[package]]
name = "native-tls"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b0d88c06fe90d5ee94048ba40409ef1d9315d86f6f38c2efdaad4fb50c58b2d"
dependencies = [
"lazy_static",
"libc",
"log",
"openssl",
"openssl-probe",
"openssl-sys",
"schannel",
"security-framework",
"security-framework-sys",
"tempfile",
]
[[package]]
name = "net2"
version = "0.2.33"
@ -1016,6 +1242,39 @@ dependencies = [
"libc",
]
[[package]]
name = "openssl"
version = "0.10.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cee6d85f4cb4c4f59a6a85d5b68a233d280c82e29e822913b9c8b129fbf20bdd"
dependencies = [
"bitflags",
"cfg-if",
"foreign-types",
"lazy_static",
"libc",
"openssl-sys",
]
[[package]]
name = "openssl-probe"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77af24da69f9d9341038eba93a073b1fdaaa1b788221b00a69bce9e762cb32de"
[[package]]
name = "openssl-sys"
version = "0.9.56"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f02309a7f127000ed50594f0b50ecc69e7c654e16d41b4e8156d1b3df8e0b52e"
dependencies = [
"autocfg",
"cc",
"libc",
"pkg-config",
"vcpkg",
]
[[package]]
name = "ordered-float"
version = "1.0.2"
@ -1087,12 +1346,44 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
[[package]]
name = "pkg-config"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05da548ad6865900e60eaba7f589cc0783590a92e940c26953ff81ddbab2d677"
[[package]]
name = "ppv-lite86"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74490b50b9fbe561ac330df47c08f3f33073d2d00c150f719147d7c54522fa1b"
[[package]]
name = "proc-macro-error"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "18f33027081eba0a6d8aba6d1b1c3a3be58cbb12106341c2d5759fcd9b5277e7"
dependencies = [
"proc-macro-error-attr",
"proc-macro2",
"quote",
"syn",
"version_check",
]
[[package]]
name = "proc-macro-error-attr"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a5b4b77fdb63c1eca72173d68d24501c54ab1269409f6b672c85deb18af69de"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn-mid",
"version_check",
]
[[package]]
name = "proc-macro-hack"
version = "0.5.15"
@ -1194,6 +1485,50 @@ version = "0.6.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fe5bd57d1d7414c6b5ed48563a2c855d995ff777729dcd91c369ec7fea395ae"
[[package]]
name = "remove_dir_all"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a83fa3702a688b9359eccba92d153ac33fd2e8462f9e0e3fdf155239ea7792e"
dependencies = [
"winapi 0.3.8",
]
[[package]]
name = "reqwest"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02b81e49ddec5109a9dcfc5f2a317ff53377c915e9ae9d4f2fb50914b85614e2"
dependencies = [
"base64 0.11.0",
"bytes",
"encoding_rs",
"futures-core",
"futures-util",
"http",
"http-body",
"hyper",
"hyper-tls",
"js-sys",
"lazy_static",
"log",
"mime",
"mime_guess",
"native-tls",
"percent-encoding",
"pin-project-lite",
"serde",
"serde_urlencoded",
"time",
"tokio",
"tokio-tls",
"url",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"winreg",
]
[[package]]
name = "resolv-conf"
version = "0.6.3"
@ -1238,12 +1573,44 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfa8506c1de11c9c4e4c38863ccbe02a305c8188e85a05a784c9e11e1c3910c8"
[[package]]
name = "schannel"
version = "0.1.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f05ba609c234e60bee0d547fe94a4c7e9da733d1c962cf6e59efa4cd9c8bc75"
dependencies = [
"lazy_static",
"winapi 0.3.8",
]
[[package]]
name = "scopeguard"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
[[package]]
name = "security-framework"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97bbedbe81904398b6ebb054b3e912f99d55807125790f3198ac990d98def5b0"
dependencies = [
"bitflags",
"core-foundation",
"core-foundation-sys",
"security-framework-sys",
]
[[package]]
name = "security-framework-sys"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17bf11d99252f512695eb468de5516e5cf75455521e69dfe343f3b74e4748405"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "semver"
version = "0.9.0"
@ -1384,6 +1751,17 @@ dependencies = [
"unicode-xid",
]
[[package]]
name = "syn-mid"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7be3539f6c128a931cf19dcee741c1af532c7fd387baa739c03dd2e96479338a"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "synstructure"
version = "0.12.3"
@ -1396,6 +1774,20 @@ dependencies = [
"unicode-xid",
]
[[package]]
name = "tempfile"
version = "3.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a6e24d9338a0a5be79593e2fa15a648add6138caa803e2d5bc782c371732ca9"
dependencies = [
"cfg-if",
"libc",
"rand",
"redox_syscall",
"remove_dir_all",
"winapi 0.3.8",
]
[[package]]
name = "thread_local"
version = "1.0.1"
@ -1439,13 +1831,37 @@ dependencies = [
"libc",
"memchr",
"mio",
"mio-named-pipes",
"mio-uds",
"num_cpus",
"pin-project-lite",
"signal-hook-registry",
"slab",
"tokio-macros",
"winapi 0.3.8",
]
[[package]]
name = "tokio-macros"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0c3acc6aa564495a0f2e1d59fab677cd7f81a19994cfc7f3ad0e64301560389"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tokio-tls"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a70f4fcd7b3b24fb194f837560168208f669ca8cb70d0c4b862944452396343"
dependencies = [
"native-tls",
"tokio",
]
[[package]]
name = "tokio-util"
version = "0.2.0"
@ -1474,6 +1890,12 @@ dependencies = [
"tokio",
]
[[package]]
name = "tower-service"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e987b6bf443f4b5b3b6f38704195592cca41c5bb7aedd3c3693c7081f8289860"
[[package]]
name = "trust-dns-proto"
version = "0.18.0-alpha.2"
@ -1513,6 +1935,21 @@ dependencies = [
"trust-dns-proto",
]
[[package]]
name = "try-lock"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e604eb7b43c06650e854be16a2a03155743d3752dd1c943f6829e26b7a36e382"
[[package]]
name = "unicase"
version = "2.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6"
dependencies = [
"version_check",
]
[[package]]
name = "unicode-bidi"
version = "0.3.4"
@ -1565,12 +2002,112 @@ dependencies = [
"serde",
]
[[package]]
name = "vcpkg"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fc439f2794e98976c88a2a2dafce96b930fe8010b0a256b3c2199a773933168"
[[package]]
name = "version_check"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "078775d0255232fb988e6fccf26ddc9d1ac274299aaedcedce21c6f72cc533ce"
[[package]]
name = "want"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0"
dependencies = [
"log",
"try-lock",
]
[[package]]
name = "wasi"
version = "0.9.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519"
[[package]]
name = "wasm-bindgen"
version = "0.2.62"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3c7d40d09cdbf0f4895ae58cf57d92e1e57a9dd8ed2e8390514b54a47cc5551"
dependencies = [
"cfg-if",
"serde",
"serde_json",
"wasm-bindgen-macro",
]
[[package]]
name = "wasm-bindgen-backend"
version = "0.2.62"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3972e137ebf830900db522d6c8fd74d1900dcfc733462e9a12e942b00b4ac94"
dependencies = [
"bumpalo",
"lazy_static",
"log",
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-futures"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a369c5e1dfb7569e14d62af4da642a3cbc2f9a3652fe586e26ac22222aa4b04"
dependencies = [
"cfg-if",
"js-sys",
"wasm-bindgen",
"web-sys",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.62"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2cd85aa2c579e8892442954685f0d801f9129de24fa2136b2c6a539c76b65776"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.62"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8eb197bd3a47553334907ffd2f16507b4f4f01bbec3ac921a7719e0decdfe72a"
dependencies = [
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.62"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a91c2916119c17a8e316507afaaa2dd94b47646048014bbdf6bef098c1bb58ad"
[[package]]
name = "web-sys"
version = "0.3.39"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8bc359e5dd3b46cb9687a051d50a2fdd228e4ba7cf6fcf861a5365c3d671a642"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "widestring"
version = "0.4.0"

View File

@ -33,5 +33,6 @@ name = "cloudevents"
[workspace]
members = [
".",
"cloudevents-sdk-actix-web"
"cloudevents-sdk-actix-web",
"cloudevents-sdk-reqwest"
]

View File

@ -20,6 +20,7 @@ Work in progress SDK for [CloudEvents](https://github.com/cloudevents/spec)
* `cloudevents-sdk`: Provides Event data structure, JSON Event format implementation
* `cloudevents-sdk-actix-web`: Integration with [Actix Web](https://github.com/actix/actix-web)
* `cloudevents-sdk-reqwest`: Integration with [reqwest](https://github.com/seanmonstar/reqwest)
## Development & Contributing

View File

@ -4,8 +4,8 @@ use actix_web::web::{Bytes, BytesMut};
use actix_web::{web, HttpMessage, HttpRequest};
use cloudevents::event::SpecVersion;
use cloudevents::message::{
BinaryDeserializer, BinarySerializer, Encoding, Error, MessageAttributeValue,
MessageDeserializer, StructuredDeserializer, StructuredSerializer,
BinaryDeserializer, BinarySerializer, Encoding, MessageAttributeValue, MessageDeserializer,
Result, StructuredDeserializer, StructuredSerializer,
};
use cloudevents::{message, Event};
use futures::StreamExt;
@ -24,10 +24,7 @@ impl HttpRequestDeserializer<'_> {
}
impl<'a> BinaryDeserializer for HttpRequestDeserializer<'a> {
fn deserialize_binary<R: Sized, V: BinarySerializer<R>>(
self,
mut visitor: V,
) -> Result<R, Error> {
fn deserialize_binary<R: Sized, V: BinarySerializer<R>>(self, mut visitor: V) -> Result<R> {
if self.encoding() != Encoding::BINARY {
return Err(message::Error::WrongEncoding {});
}
@ -36,7 +33,7 @@ impl<'a> BinaryDeserializer for HttpRequestDeserializer<'a> {
unwrap_optional_header!(self.req.headers(), headers::SPEC_VERSION_HEADER).unwrap()?,
)?;
visitor.set_spec_version(spec_version.clone())?;
visitor = visitor.set_spec_version(spec_version.clone())?;
let attributes = cloudevents::event::spec_version::ATTRIBUTE_NAMES
.get(&spec_version)
@ -50,12 +47,12 @@ impl<'a> BinaryDeserializer for HttpRequestDeserializer<'a> {
let name = &hn.as_str()["ce-".len()..];
if attributes.contains(&name) {
visitor.set_attribute(
visitor = visitor.set_attribute(
name,
MessageAttributeValue::String(String::from(header_value_to_str!(hv)?)),
)?
} else {
visitor.set_extension(
visitor = visitor.set_extension(
name,
MessageAttributeValue::String(String::from(header_value_to_str!(hv)?)),
)?
@ -63,7 +60,7 @@ impl<'a> BinaryDeserializer for HttpRequestDeserializer<'a> {
}
if let Some(hv) = self.req.headers().get("content-type") {
visitor.set_attribute(
visitor = visitor.set_attribute(
"datacontenttype",
MessageAttributeValue::String(String::from(header_value_to_str!(hv)?)),
)?
@ -78,10 +75,7 @@ impl<'a> BinaryDeserializer for HttpRequestDeserializer<'a> {
}
impl<'a> StructuredDeserializer for HttpRequestDeserializer<'a> {
fn deserialize_structured<R: Sized, V: StructuredSerializer<R>>(
self,
visitor: V,
) -> Result<R, Error> {
fn deserialize_structured<R: Sized, V: StructuredSerializer<R>>(self, visitor: V) -> Result<R> {
if self.encoding() != Encoding::STRUCTURED {
return Err(message::Error::WrongEncoding {});
}
@ -110,7 +104,7 @@ impl<'a> MessageDeserializer for HttpRequestDeserializer<'a> {
pub async fn request_to_event(
req: &HttpRequest,
mut payload: web::Payload,
) -> Result<Event, actix_web::error::Error> {
) -> std::result::Result<Event, actix_web::error::Error> {
let mut bytes = BytesMut::new();
while let Some(item) = payload.next().await {
bytes.extend_from_slice(&item?);

View File

@ -4,8 +4,7 @@ use actix_web::http::{HeaderName, HeaderValue};
use actix_web::HttpResponse;
use cloudevents::event::SpecVersion;
use cloudevents::message::{
BinaryDeserializer, BinarySerializer, Error, MessageAttributeValue, SerializationResult,
StructuredSerializer,
BinaryDeserializer, BinarySerializer, MessageAttributeValue, Result, StructuredSerializer,
};
use cloudevents::Event;
use std::str::FromStr;
@ -21,41 +20,41 @@ impl HttpResponseSerializer {
}
impl BinarySerializer<HttpResponse> for HttpResponseSerializer {
fn set_spec_version(&mut self, spec_version: SpecVersion) -> SerializationResult {
fn set_spec_version(mut self, spec_version: SpecVersion) -> Result<Self> {
self.builder.set_header(
headers::SPEC_VERSION_HEADER.clone(),
str_to_header_value!(spec_version.as_str())?,
);
SerializationResult::Ok(())
Ok(self)
}
fn set_attribute(&mut self, name: &str, value: MessageAttributeValue) -> SerializationResult {
fn set_attribute(mut self, name: &str, value: MessageAttributeValue) -> Result<Self> {
self.builder.set_header(
headers::ATTRIBUTES_TO_HEADERS.get(name).unwrap().clone(),
str_to_header_value!(value.to_string().as_str())?,
);
SerializationResult::Ok(())
Ok(self)
}
fn set_extension(&mut self, name: &str, value: MessageAttributeValue) -> SerializationResult {
fn set_extension(mut self, name: &str, value: MessageAttributeValue) -> Result<Self> {
self.builder.set_header(
attribute_name_to_header!(name)?,
str_to_header_value!(value.to_string().as_str())?,
);
SerializationResult::Ok(())
Ok(self)
}
fn end_with_data(mut self, bytes: Vec<u8>) -> Result<HttpResponse, Error> {
fn end_with_data(mut self, bytes: Vec<u8>) -> Result<HttpResponse> {
Ok(self.builder.body(bytes))
}
fn end(mut self) -> Result<HttpResponse, Error> {
fn end(mut self) -> Result<HttpResponse> {
Ok(self.builder.finish())
}
}
impl StructuredSerializer<HttpResponse> for HttpResponseSerializer {
fn set_structured_event(mut self, bytes: Vec<u8>) -> Result<HttpResponse, Error> {
fn set_structured_event(mut self, bytes: Vec<u8>) -> Result<HttpResponse> {
Ok(self
.builder
.set_header(
@ -70,7 +69,7 @@ impl StructuredSerializer<HttpResponse> for HttpResponseSerializer {
pub async fn event_to_response(
event: Event,
response: HttpResponseBuilder,
) -> Result<HttpResponse, actix_web::error::Error> {
) -> std::result::Result<HttpResponse, actix_web::error::Error> {
BinaryDeserializer::deserialize_binary(event, HttpResponseSerializer::new(response))
.map_err(actix_web::error::ErrorBadRequest)
}

View File

@ -0,0 +1,19 @@
[package]
name = "cloudevents-sdk-reqwest"
version = "0.1.0"
authors = ["Francesco Guardiani <francescoguard@gmail.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
cloudevents-sdk = { path = ".." }
reqwest = { version = "0.10" }
lazy_static = "1.4.0"
bytes = "^0.5"
serde_json = "^1.0"
url = { version = "^2.1", features = ["serde"] }
[dev-dependencies]
mockito = "0.25.1"
tokio = { version = "^0.2", features = ["full"] }

View File

@ -0,0 +1,172 @@
use super::headers;
use cloudevents::event::SpecVersion;
use cloudevents::message::{
BinaryDeserializer, BinarySerializer, MessageAttributeValue, Result, StructuredSerializer,
};
use cloudevents::Event;
use reqwest::RequestBuilder;
use std::str::FromStr;
/// Wrapper for [`RequestBuilder`] that implements [`StructuredSerializer`] & [`BinarySerializer`] traits
pub struct RequestSerializer {
req: RequestBuilder,
}
impl RequestSerializer {
pub fn new(req: RequestBuilder) -> RequestSerializer {
RequestSerializer { req }
}
}
impl BinarySerializer<RequestBuilder> for RequestSerializer {
fn set_spec_version(mut self, spec_version: SpecVersion) -> Result<Self> {
self.req = self
.req
.header(headers::SPEC_VERSION_HEADER.clone(), spec_version.as_str());
Ok(self)
}
fn set_attribute(mut self, name: &str, value: MessageAttributeValue) -> Result<Self> {
self.req = self.req.header(
headers::ATTRIBUTES_TO_HEADERS.get(name).unwrap().clone(),
value.to_string(),
);
Ok(self)
}
fn set_extension(mut self, name: &str, value: MessageAttributeValue) -> Result<Self> {
self.req = self
.req
.header(attribute_name_to_header!(name)?, value.to_string());
Ok(self)
}
fn end_with_data(self, bytes: Vec<u8>) -> Result<RequestBuilder> {
Ok(self.req.body(bytes))
}
fn end(self) -> Result<RequestBuilder> {
Ok(self.req)
}
}
impl StructuredSerializer<RequestBuilder> for RequestSerializer {
fn set_structured_event(self, bytes: Vec<u8>) -> Result<RequestBuilder> {
Ok(self
.req
.header(
reqwest::header::CONTENT_TYPE,
headers::CLOUDEVENTS_JSON_HEADER.clone(),
)
.body(bytes))
}
}
/// Method to transform an incoming [`HttpRequest`] to [`Event`]
pub fn event_to_request(event: Event, request_builder: RequestBuilder) -> Result<RequestBuilder> {
BinaryDeserializer::deserialize_binary(event, RequestSerializer::new(request_builder))
}
#[cfg(test)]
mod tests {
use super::*;
use mockito::{mock, Matcher};
use cloudevents::message::StructuredDeserializer;
use cloudevents::EventBuilder;
use serde_json::json;
use url::Url;
#[tokio::test]
async fn test_request() {
let url = mockito::server_url();
let m = mock("POST", "/")
.match_header("ce-specversion", "1.0")
.match_header("ce-id", "0001")
.match_header("ce-type", "example.test")
.match_header("ce-source", "http://localhost/")
.match_header("ce-someint", "10")
.match_body(Matcher::Missing)
.create();
let input = EventBuilder::new()
.id("0001")
.ty("example.test")
.source(Url::from_str("http://localhost/").unwrap())
.extension("someint", "10")
.build();
let client = reqwest::Client::new();
event_to_request(input, client.post(&url))
.unwrap()
.send()
.await
.unwrap();
m.assert();
}
#[tokio::test]
async fn test_request_with_full_data() {
let j = json!({"hello": "world"});
let url = mockito::server_url();
let m = mock("POST", "/")
.match_header("ce-specversion", "1.0")
.match_header("ce-id", "0001")
.match_header("ce-type", "example.test")
.match_header("ce-source", "http://localhost/")
.match_header("content-type", "application/json")
.match_header("ce-someint", "10")
.match_body(Matcher::Exact(j.to_string()))
.create();
let input = EventBuilder::new()
.id("0001")
.ty("example.test")
.source(Url::from_str("http://localhost").unwrap())
.data("application/json", j.clone())
.extension("someint", "10")
.build();
let client = reqwest::Client::new();
event_to_request(input, client.post(&url))
.unwrap()
.send()
.await
.unwrap();
m.assert();
}
#[tokio::test]
async fn test_structured_request_with_full_data() {
let j = json!({"hello": "world"});
let input = EventBuilder::new()
.id("0001")
.ty("example.test")
.source(Url::from_str("http://localhost").unwrap())
.data("application/json", j.clone())
.extension("someint", "10")
.build();
let url = mockito::server_url();
let m = mock("POST", "/")
.match_header("content-type", "application/cloudevents+json")
.match_body(Matcher::Exact(serde_json::to_string(&input).unwrap()))
.create();
let client = reqwest::Client::new();
StructuredDeserializer::deserialize_structured(
input,
RequestSerializer::new(client.post(&url)),
)
.unwrap()
.send()
.await
.unwrap();
m.assert();
}
}

View File

@ -0,0 +1,206 @@
use super::headers;
use bytes::Bytes;
use cloudevents::event::SpecVersion;
use cloudevents::message::{
BinaryDeserializer, BinarySerializer, Encoding, Error, MessageAttributeValue,
MessageDeserializer, Result, StructuredDeserializer, StructuredSerializer,
};
use cloudevents::{message, Event};
use reqwest::header::{HeaderMap, HeaderName};
use reqwest::Response;
use std::convert::TryFrom;
/// Wrapper for [`Response`] that implements [`MessageDeserializer`] trait
pub struct ResponseDeserializer {
headers: HeaderMap,
body: Bytes,
}
impl ResponseDeserializer {
pub fn new(headers: HeaderMap, body: Bytes) -> ResponseDeserializer {
ResponseDeserializer { headers, body }
}
}
impl BinaryDeserializer for ResponseDeserializer {
fn deserialize_binary<R: Sized, V: BinarySerializer<R>>(self, mut visitor: V) -> Result<R> {
if self.encoding() != Encoding::BINARY {
return Err(message::Error::WrongEncoding {});
}
let spec_version = SpecVersion::try_from(
unwrap_optional_header!(self.headers, headers::SPEC_VERSION_HEADER).unwrap()?,
)?;
visitor = visitor.set_spec_version(spec_version.clone())?;
let attributes = cloudevents::event::spec_version::ATTRIBUTE_NAMES
.get(&spec_version)
.unwrap();
for (hn, hv) in self
.headers
.iter()
.filter(|(hn, _)| headers::SPEC_VERSION_HEADER.ne(hn) && hn.as_str().starts_with("ce-"))
{
let name = &hn.as_str()["ce-".len()..];
if attributes.contains(&name) {
visitor = visitor.set_attribute(
name,
MessageAttributeValue::String(String::from(header_value_to_str!(hv)?)),
)?
} else {
visitor = visitor.set_extension(
name,
MessageAttributeValue::String(String::from(header_value_to_str!(hv)?)),
)?
}
}
if let Some(hv) = self.headers.get("content-type") {
visitor = visitor.set_attribute(
"datacontenttype",
MessageAttributeValue::String(String::from(header_value_to_str!(hv)?)),
)?
}
if self.body.len() != 0 {
visitor.end_with_data(self.body.to_vec())
} else {
visitor.end()
}
}
}
impl StructuredDeserializer for ResponseDeserializer {
fn deserialize_structured<R: Sized, V: StructuredSerializer<R>>(self, visitor: V) -> Result<R> {
if self.encoding() != Encoding::STRUCTURED {
return Err(message::Error::WrongEncoding {});
}
visitor.set_structured_event(self.body.to_vec())
}
}
impl MessageDeserializer for ResponseDeserializer {
fn encoding(&self) -> Encoding {
match (
unwrap_optional_header!(self.headers, reqwest::header::CONTENT_TYPE)
.map(|r| r.ok())
.flatten()
.map(|e| e.starts_with("application/cloudevents+json")),
self.headers
.get::<&'static HeaderName>(&headers::SPEC_VERSION_HEADER),
) {
(Some(true), _) => Encoding::STRUCTURED,
(_, Some(_)) => Encoding::BINARY,
_ => Encoding::UNKNOWN,
}
}
}
/// Method to transform an incoming [`Response`] to [`Event`]
pub async fn response_to_event(res: Response) -> Result<Event> {
let h = res.headers().to_owned();
let b = res.bytes().await.map_err(|e| Error::Other {
source: Box::new(e),
})?;
MessageDeserializer::into_event(ResponseDeserializer::new(h, b))
}
#[cfg(test)]
mod tests {
use super::*;
use mockito::mock;
use cloudevents::EventBuilder;
use serde_json::json;
use std::str::FromStr;
use url::Url;
#[tokio::test]
async fn test_response() {
let url = mockito::server_url();
let _m = mock("GET", "/")
.with_status(200)
.with_header("ce-specversion", "1.0")
.with_header("ce-id", "0001")
.with_header("ce-type", "example.test")
.with_header("ce-source", "http://localhost")
.with_header("ce-someint", "10")
.create();
let expected = EventBuilder::new()
.id("0001")
.ty("example.test")
.source(Url::from_str("http://localhost").unwrap())
.extension("someint", "10")
.build();
let client = reqwest::Client::new();
let res = client.get(&url).send().await.unwrap();
let resp = response_to_event(res).await.unwrap();
assert_eq!(expected, resp);
}
#[tokio::test]
async fn test_response_with_full_data() {
let j = json!({"hello": "world"});
let url = mockito::server_url();
let _m = mock("GET", "/")
.with_status(200)
.with_header("ce-specversion", "1.0")
.with_header("ce-id", "0001")
.with_header("ce-type", "example.test")
.with_header("ce-source", "http://localhost/")
.with_header("content-type", "application/json")
.with_header("ce-someint", "10")
.with_body(j.to_string())
.create();
let expected = EventBuilder::new()
.id("0001")
.ty("example.test")
.source(Url::from_str("http://localhost").unwrap())
.data("application/json", j.clone())
.extension("someint", "10")
.build();
let client = reqwest::Client::new();
let res = client.get(&url).send().await.unwrap();
let resp = response_to_event(res).await.unwrap();
assert_eq!(expected, resp);
}
#[tokio::test]
async fn test_structured_response_with_full_data() {
let j = json!({"hello": "world"});
let expected = EventBuilder::new()
.id("0001")
.ty("example.test")
.source(Url::from_str("http://localhost").unwrap())
.data("application/json", j.clone())
.extension("someint", "10")
.build();
let url = mockito::server_url();
let _m = mock("GET", "/")
.with_status(200)
.with_header(
"content-type",
"application/cloudevents+json; charset=utf-8",
)
.with_body(serde_json::to_string(&expected).unwrap())
.create();
let client = reqwest::Client::new();
let res = client.get(&url).send().await.unwrap();
let resp = response_to_event(res).await.unwrap();
assert_eq!(expected, resp);
}
}

View File

@ -0,0 +1,63 @@
use cloudevents::event::SpecVersion;
use lazy_static::lazy_static;
use reqwest::header::{HeaderName, HeaderValue};
use std::collections::HashMap;
use std::str::FromStr;
macro_rules! unwrap_optional_header {
($headers:expr, $name:expr) => {
$headers
.get::<&'static reqwest::header::HeaderName>(&$name)
.map(|a| header_value_to_str!(a))
};
}
macro_rules! header_value_to_str {
($header_value:expr) => {
$header_value
.to_str()
.map_err(|e| cloudevents::message::Error::Other {
source: Box::new(e),
})
};
}
macro_rules! str_name_to_header {
($attribute:expr) => {
reqwest::header::HeaderName::from_str($attribute).map_err(|e| {
cloudevents::message::Error::Other {
source: Box::new(e),
}
})
};
}
macro_rules! attribute_name_to_header {
($attribute:expr) => {
str_name_to_header!(&["ce-", $attribute].concat())
};
}
fn attributes_to_headers(
map: &HashMap<SpecVersion, &'static [&'static str]>,
) -> HashMap<&'static str, HeaderName> {
map.values()
.flat_map(|s| s.iter())
.map(|s| {
if *s == "datacontenttype" {
(*s, reqwest::header::CONTENT_TYPE)
} else {
(*s, attribute_name_to_header!(s).unwrap())
}
})
.collect()
}
lazy_static! {
pub(crate) static ref ATTRIBUTES_TO_HEADERS: HashMap<&'static str, HeaderName> =
attributes_to_headers(&cloudevents::event::spec_version::ATTRIBUTE_NAMES);
pub(crate) static ref SPEC_VERSION_HEADER: HeaderName =
HeaderName::from_static("ce-specversion");
pub(crate) static ref CLOUDEVENTS_JSON_HEADER: HeaderValue =
HeaderValue::from_static("application/cloudevents+json");
}

View File

@ -0,0 +1,9 @@
#[macro_use]
mod headers;
mod client_request;
mod client_response;
pub use client_request::event_to_request;
pub use client_request::RequestSerializer;
pub use client_response::response_to_event;
pub use client_response::ResponseDeserializer;

View File

@ -3,26 +3,23 @@ use super::Event;
use super::{Attributes, AttributesReader};
use crate::event::SpecVersion;
use crate::message::{
BinaryDeserializer, BinarySerializer, DeserializationResult, Error, MessageAttributeValue,
SerializationResult, StructuredDeserializer, StructuredSerializer,
BinaryDeserializer, BinarySerializer, MessageAttributeValue, Result, StructuredDeserializer,
StructuredSerializer,
};
impl StructuredDeserializer for Event {
fn deserialize_structured<R, V: StructuredSerializer<R>>(self, visitor: V) -> Result<R, Error> {
fn deserialize_structured<R, V: StructuredSerializer<R>>(self, visitor: V) -> Result<R> {
let vec: Vec<u8> = serde_json::to_vec(&self)?;
visitor.set_structured_event(vec)
}
}
impl BinaryDeserializer for Event {
fn deserialize_binary<R: Sized, V: BinarySerializer<R>>(
self,
mut visitor: V,
) -> Result<R, Error> {
visitor.set_spec_version(self.get_specversion())?;
self.attributes.deserialize_attributes(&mut visitor)?;
fn deserialize_binary<R: Sized, V: BinarySerializer<R>>(self, mut visitor: V) -> Result<R> {
visitor = visitor.set_spec_version(self.get_specversion())?;
visitor = self.attributes.deserialize_attributes(visitor)?;
for (k, v) in self.extensions.into_iter() {
visitor.set_extension(&k, v.into())?;
visitor = visitor.set_extension(&k, v.into())?;
}
match self.data {
Some(Data::String(s)) => visitor.end_with_data(s.into_bytes()),
@ -37,25 +34,15 @@ impl BinaryDeserializer for Event {
}
pub(crate) trait AttributesDeserializer {
fn deserialize_attributes<R: Sized, V: BinarySerializer<R>>(
self,
visitor: &mut V,
) -> DeserializationResult;
fn deserialize_attributes<R: Sized, V: BinarySerializer<R>>(self, visitor: V) -> Result<V>;
}
pub(crate) trait AttributesSerializer {
fn serialize_attribute(
&mut self,
name: &str,
value: MessageAttributeValue,
) -> SerializationResult;
fn serialize_attribute(&mut self, name: &str, value: MessageAttributeValue) -> Result<()>;
}
impl AttributesDeserializer for Attributes {
fn deserialize_attributes<R: Sized, V: BinarySerializer<R>>(
self,
visitor: &mut V,
) -> DeserializationResult {
fn deserialize_attributes<R: Sized, V: BinarySerializer<R>>(self, visitor: V) -> Result<V> {
match self {
Attributes::V03(v03) => v03.deserialize_attributes(visitor),
Attributes::V10(v10) => v10.deserialize_attributes(visitor),
@ -64,11 +51,7 @@ impl AttributesDeserializer for Attributes {
}
impl AttributesSerializer for Attributes {
fn serialize_attribute(
&mut self,
name: &str,
value: MessageAttributeValue,
) -> SerializationResult {
fn serialize_attribute(&mut self, name: &str, value: MessageAttributeValue) -> Result<()> {
match self {
Attributes::V03(v03) => v03.serialize_attribute(name, value),
Attributes::V10(v10) => v10.serialize_attribute(name, value),
@ -77,7 +60,7 @@ impl AttributesSerializer for Attributes {
}
impl StructuredSerializer<Event> for Event {
fn set_structured_event(mut self, bytes: Vec<u8>) -> Result<Event, Error> {
fn set_structured_event(mut self, bytes: Vec<u8>) -> Result<Event> {
let new_event: Event = serde_json::from_slice(&bytes)?;
self.attributes = new_event.attributes;
self.data = new_event.data;
@ -87,29 +70,30 @@ impl StructuredSerializer<Event> for Event {
}
impl BinarySerializer<Event> for Event {
fn set_spec_version(&mut self, spec_version: SpecVersion) -> SerializationResult {
fn set_spec_version(mut self, spec_version: SpecVersion) -> Result<Self> {
match spec_version {
SpecVersion::V03 => self.attributes = self.attributes.clone().into_v03(),
SpecVersion::V10 => self.attributes = self.attributes.clone().into_v10(),
}
Ok(())
Ok(self)
}
fn set_attribute(&mut self, name: &str, value: MessageAttributeValue) -> SerializationResult {
self.attributes.serialize_attribute(name, value)
fn set_attribute(mut self, name: &str, value: MessageAttributeValue) -> Result<Self> {
self.attributes.serialize_attribute(name, value)?;
Ok(self)
}
fn set_extension(&mut self, name: &str, value: MessageAttributeValue) -> SerializationResult {
fn set_extension(mut self, name: &str, value: MessageAttributeValue) -> Result<Self> {
self.extensions.insert(name.to_string(), value.into());
Ok(())
Ok(self)
}
fn end_with_data(mut self, bytes: Vec<u8>) -> Result<Event, Error> {
fn end_with_data(mut self, bytes: Vec<u8>) -> Result<Event> {
self.data = Some(Data::from_binary(self.get_datacontenttype(), bytes)?);
Ok(self)
}
fn end(self) -> Result<Event, Error> {
fn end(self) -> Result<Event> {
Ok(self)
}
}

View File

@ -1,7 +1,7 @@
use crate::event::attributes::{AttributeValue, AttributesConverter, DataAttributesWriter};
use crate::event::AttributesV10;
use crate::event::{AttributesReader, AttributesWriter, SpecVersion};
use chrono::{DateTime, NaiveDateTime, Utc};
use chrono::{DateTime, Utc};
use hostname::get_hostname;
use url::Url;
use uuid::Uuid;
@ -187,34 +187,40 @@ impl AttributesConverter for Attributes {
}
}
#[test]
fn iterator_test_V03() {
let a = Attributes {
id: String::from("1"),
ty: String::from("someType"),
source: Url::parse("https://example.net").unwrap(),
datacontenttype: None,
schemaurl: None,
subject: None,
time: Some(DateTime::<Utc>::from_utc(
NaiveDateTime::from_timestamp(61, 0),
Utc,
)),
};
let b = &mut a.into_iter();
let time = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(61, 0), Utc);
#[cfg(test)]
mod tests {
use super::*;
use chrono::NaiveDateTime;
assert_eq!(("id", AttributeValue::String("1")), b.next().unwrap());
assert_eq!(
("type", AttributeValue::String("someType")),
b.next().unwrap()
);
assert_eq!(
(
"source",
AttributeValue::URIRef(&Url::parse("https://example.net").unwrap())
),
b.next().unwrap()
);
assert_eq!(("time", AttributeValue::Time(&time)), b.next().unwrap());
#[test]
fn iterator_test_V03() {
let a = Attributes {
id: String::from("1"),
ty: String::from("someType"),
source: Url::parse("https://example.net").unwrap(),
datacontenttype: None,
schemaurl: None,
subject: None,
time: Some(DateTime::<Utc>::from_utc(
NaiveDateTime::from_timestamp(61, 0),
Utc,
)),
};
let b = &mut a.into_iter();
let time = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(61, 0), Utc);
assert_eq!(("id", AttributeValue::String("1")), b.next().unwrap());
assert_eq!(
("type", AttributeValue::String("someType")),
b.next().unwrap()
);
assert_eq!(
(
"source",
AttributeValue::URIRef(&Url::parse("https://example.net").unwrap())
),
b.next().unwrap()
);
assert_eq!(("time", AttributeValue::Time(&time)), b.next().unwrap());
}
}

View File

@ -1,47 +1,39 @@
use crate::message::{
BinarySerializer, DeserializationResult, Error, MessageAttributeValue, SerializationResult,
};
use crate::message::{BinarySerializer, Error, MessageAttributeValue, Result};
use std::convert::TryInto;
impl crate::event::message::AttributesDeserializer for super::Attributes {
fn deserialize_attributes<R: Sized, V: BinarySerializer<R>>(
self,
visitor: &mut V,
) -> DeserializationResult {
visitor.set_attribute("id", MessageAttributeValue::String(self.id))?;
visitor.set_attribute("type", MessageAttributeValue::String(self.ty))?;
visitor.set_attribute("source", MessageAttributeValue::UriRef(self.source))?;
fn deserialize_attributes<R: Sized, V: BinarySerializer<R>>(self, mut visitor: V) -> Result<V> {
visitor = visitor.set_attribute("id", MessageAttributeValue::String(self.id))?;
visitor = visitor.set_attribute("type", MessageAttributeValue::String(self.ty))?;
visitor = visitor.set_attribute("source", MessageAttributeValue::UriRef(self.source))?;
if self.datacontenttype.is_some() {
visitor.set_attribute(
visitor = visitor.set_attribute(
"datacontenttype",
MessageAttributeValue::String(self.datacontenttype.unwrap()),
)?;
}
if self.schemaurl.is_some() {
visitor.set_attribute(
visitor = visitor.set_attribute(
"schemaurl",
MessageAttributeValue::Uri(self.schemaurl.unwrap()),
)?;
}
if self.subject.is_some() {
visitor.set_attribute(
visitor = visitor.set_attribute(
"subject",
MessageAttributeValue::String(self.subject.unwrap()),
)?;
}
if self.time.is_some() {
visitor.set_attribute("time", MessageAttributeValue::DateTime(self.time.unwrap()))?;
visitor = visitor
.set_attribute("time", MessageAttributeValue::DateTime(self.time.unwrap()))?;
}
Ok(())
Ok(visitor)
}
}
impl crate::event::message::AttributesSerializer for super::Attributes {
fn serialize_attribute(
&mut self,
name: &str,
value: MessageAttributeValue,
) -> SerializationResult {
fn serialize_attribute(&mut self, name: &str, value: MessageAttributeValue) -> Result<()> {
match name {
"id" => self.id = value.to_string(),
"type" => self.ty = value.to_string(),

View File

@ -1,6 +1,6 @@
use crate::event::attributes::{AttributeValue, AttributesConverter, DataAttributesWriter};
use crate::event::{AttributesReader, AttributesV03, AttributesWriter, SpecVersion};
use chrono::{DateTime, NaiveDateTime, Utc};
use chrono::{DateTime, Utc};
use hostname::get_hostname;
use url::Url;
use uuid::Uuid;
@ -186,34 +186,40 @@ impl AttributesConverter for Attributes {
}
}
#[test]
fn iterator_test_V10() {
let a = Attributes {
id: String::from("1"),
ty: String::from("someType"),
source: Url::parse("https://example.net").unwrap(),
datacontenttype: None,
dataschema: None,
subject: None,
time: Some(DateTime::<Utc>::from_utc(
NaiveDateTime::from_timestamp(61, 0),
Utc,
)),
};
let b = &mut a.into_iter();
let time = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(61, 0), Utc);
#[cfg(test)]
mod tests {
use super::*;
use chrono::NaiveDateTime;
assert_eq!(("id", AttributeValue::String("1")), b.next().unwrap());
assert_eq!(
("type", AttributeValue::String("someType")),
b.next().unwrap()
);
assert_eq!(
(
"source",
AttributeValue::URIRef(&Url::parse("https://example.net").unwrap())
),
b.next().unwrap()
);
assert_eq!(("time", AttributeValue::Time(&time)), b.next().unwrap());
#[test]
fn iterator_test_V10() {
let a = Attributes {
id: String::from("1"),
ty: String::from("someType"),
source: Url::parse("https://example.net").unwrap(),
datacontenttype: None,
dataschema: None,
subject: None,
time: Some(DateTime::<Utc>::from_utc(
NaiveDateTime::from_timestamp(61, 0),
Utc,
)),
};
let b = &mut a.into_iter();
let time = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(61, 0), Utc);
assert_eq!(("id", AttributeValue::String("1")), b.next().unwrap());
assert_eq!(
("type", AttributeValue::String("someType")),
b.next().unwrap()
);
assert_eq!(
(
"source",
AttributeValue::URIRef(&Url::parse("https://example.net").unwrap())
),
b.next().unwrap()
);
assert_eq!(("time", AttributeValue::Time(&time)), b.next().unwrap());
}
}

View File

@ -1,47 +1,39 @@
use crate::message::{
BinarySerializer, DeserializationResult, Error, MessageAttributeValue, SerializationResult,
};
use crate::message::{BinarySerializer, Error, MessageAttributeValue, Result};
use std::convert::TryInto;
impl crate::event::message::AttributesDeserializer for super::Attributes {
fn deserialize_attributes<R: Sized, V: BinarySerializer<R>>(
self,
visitor: &mut V,
) -> DeserializationResult {
visitor.set_attribute("id", MessageAttributeValue::String(self.id))?;
visitor.set_attribute("type", MessageAttributeValue::String(self.ty))?;
visitor.set_attribute("source", MessageAttributeValue::UriRef(self.source))?;
fn deserialize_attributes<R: Sized, V: BinarySerializer<R>>(self, mut visitor: V) -> Result<V> {
visitor = visitor.set_attribute("id", MessageAttributeValue::String(self.id))?;
visitor = visitor.set_attribute("type", MessageAttributeValue::String(self.ty))?;
visitor = visitor.set_attribute("source", MessageAttributeValue::UriRef(self.source))?;
if self.datacontenttype.is_some() {
visitor.set_attribute(
visitor = visitor.set_attribute(
"datacontenttype",
MessageAttributeValue::String(self.datacontenttype.unwrap()),
)?;
}
if self.dataschema.is_some() {
visitor.set_attribute(
visitor = visitor.set_attribute(
"dataschema",
MessageAttributeValue::Uri(self.dataschema.unwrap()),
)?;
}
if self.subject.is_some() {
visitor.set_attribute(
visitor = visitor.set_attribute(
"subject",
MessageAttributeValue::String(self.subject.unwrap()),
)?;
}
if self.time.is_some() {
visitor.set_attribute("time", MessageAttributeValue::DateTime(self.time.unwrap()))?;
visitor = visitor
.set_attribute("time", MessageAttributeValue::DateTime(self.time.unwrap()))?;
}
Ok(())
Ok(visitor)
}
}
impl crate::event::message::AttributesSerializer for super::Attributes {
fn serialize_attribute(
&mut self,
name: &str,
value: MessageAttributeValue,
) -> SerializationResult {
fn serialize_attribute(&mut self, name: &str, value: MessageAttributeValue) -> Result<()> {
match name {
"id" => self.id = value.to_string(),
"type" => self.ty = value.to_string(),

View File

@ -1,4 +1,4 @@
use super::{BinarySerializer, Encoding, Error, StructuredSerializer};
use super::{BinarySerializer, Encoding, Result, StructuredSerializer};
use crate::Event;
pub trait StructuredDeserializer
@ -8,9 +8,9 @@ where
fn deserialize_structured<R: Sized, V: StructuredSerializer<R>>(
self,
serializer: V,
) -> Result<R, Error>;
) -> Result<R>;
fn into_event(self) -> Result<Event, Error> {
fn into_event(self) -> Result<Event> {
self.deserialize_structured(Event::default())
}
}
@ -19,12 +19,9 @@ pub trait BinaryDeserializer
where
Self: Sized,
{
fn deserialize_binary<R: Sized, V: BinarySerializer<R>>(
self,
serializer: V,
) -> Result<R, Error>;
fn deserialize_binary<R: Sized, V: BinarySerializer<R>>(self, serializer: V) -> Result<R>;
fn into_event(self) -> Result<Event, Error> {
fn into_event(self) -> Result<Event> {
self.deserialize_binary(Event::default())
}
}
@ -35,14 +32,11 @@ where
{
fn encoding(&self) -> Encoding;
fn into_event(self) -> Result<Event, Error> {
fn into_event(self) -> Result<Event> {
self.deserialize_to(Event::default())
}
fn deserialize_to_binary<R: Sized, T: BinarySerializer<R>>(
self,
serializer: T,
) -> Result<R, Error> {
fn deserialize_to_binary<R: Sized, T: BinarySerializer<R>>(self, serializer: T) -> Result<R> {
if self.encoding() == Encoding::BINARY {
return self.deserialize_binary(serializer);
}
@ -53,7 +47,7 @@ where
fn deserialize_to_structured<R: Sized, T: StructuredSerializer<R>>(
self,
serializer: T,
) -> Result<R, Error> {
) -> Result<R> {
if self.encoding() == Encoding::STRUCTURED {
return self.deserialize_structured(serializer);
}
@ -64,7 +58,7 @@ where
fn deserialize_to<R: Sized, T: BinarySerializer<R> + StructuredSerializer<R>>(
self,
serializer: T,
) -> Result<R, Error> {
) -> Result<R> {
if self.encoding() == Encoding::STRUCTURED {
self.deserialize_structured(serializer)
} else {

View File

@ -30,5 +30,4 @@ pub enum Error {
Other { source: Box<dyn std::error::Error> },
}
pub type SerializationResult = Result<(), Error>;
pub type DeserializationResult = Result<(), Error>;
pub type Result<T> = std::result::Result<T, Error>;

View File

@ -1,18 +1,21 @@
use super::{Error, MessageAttributeValue, SerializationResult};
use super::{MessageAttributeValue, Result};
use crate::event::SpecVersion;
pub trait StructuredSerializer<RETURN: Sized> {
fn set_structured_event(self, bytes: Vec<u8>) -> Result<RETURN, Error>;
fn set_structured_event(self, bytes: Vec<u8>) -> Result<RETURN>;
}
pub trait BinarySerializer<RETURN: Sized> {
fn set_spec_version(&mut self, spec_version: SpecVersion) -> SerializationResult;
pub trait BinarySerializer<RETURN: Sized>
where
Self: Sized,
{
fn set_spec_version(self, spec_version: SpecVersion) -> Result<Self>;
fn set_attribute(&mut self, name: &str, value: MessageAttributeValue) -> SerializationResult;
fn set_attribute(self, name: &str, value: MessageAttributeValue) -> Result<Self>;
fn set_extension(&mut self, name: &str, value: MessageAttributeValue) -> SerializationResult;
fn set_extension(self, name: &str, value: MessageAttributeValue) -> Result<Self>;
fn end_with_data(self, bytes: Vec<u8>) -> Result<RETURN, Error>;
fn end_with_data(self, bytes: Vec<u8>) -> Result<RETURN>;
fn end(self) -> Result<RETURN, Error>;
fn end(self) -> Result<RETURN>;
}

View File

@ -1,13 +1,13 @@
mod test_data;
use cloudevents::message::{
BinaryDeserializer, BinarySerializer, DeserializationResult, Error, MessageAttributeValue,
BinaryDeserializer, BinarySerializer, Error, MessageAttributeValue, Result,
StructuredDeserializer,
};
use test_data::*;
#[test]
fn message_v03_roundtrip_structured() -> DeserializationResult {
fn message_v03_roundtrip_structured() -> Result<()> {
assert_eq!(
v03::full_json_data(),
StructuredDeserializer::into_event(v03::full_json_data())?
@ -16,7 +16,7 @@ fn message_v03_roundtrip_structured() -> DeserializationResult {
}
#[test]
fn message_v03_roundtrip_binary() -> DeserializationResult {
fn message_v03_roundtrip_binary() -> Result<()> {
assert_eq!(
v03::full_json_data(),
BinaryDeserializer::into_event(v03::full_json_data())?
@ -25,7 +25,7 @@ fn message_v03_roundtrip_binary() -> DeserializationResult {
}
#[test]
fn message_v10_roundtrip_structured() -> DeserializationResult {
fn message_v10_roundtrip_structured() -> Result<()> {
assert_eq!(
v10::full_json_data(),
StructuredDeserializer::into_event(v10::full_json_data())?
@ -34,7 +34,7 @@ fn message_v10_roundtrip_structured() -> DeserializationResult {
}
#[test]
fn message_v10_roundtrip_binary() -> DeserializationResult {
fn message_v10_roundtrip_binary() -> Result<()> {
assert_eq!(
v10::full_json_data(),
BinaryDeserializer::into_event(v10::full_json_data())?