Skip to content

web search done right

Deunsafication and testing of `sonic` protocol and introducing `sonic::service` (#72)

Oliver Bøving345bd9c1b452
diff --git a/Cargo.lock b/Cargo.lock
index 0004dcd5..f836c1f5 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -204,7 +204,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87bf87e6e8b47264efa9bde63d6225c6276a52e05e91bf37eaa8afd0032d6b71"
dependencies = [
"askama_shared",
- "proc-macro2",
+ "proc-macro2 1.0.56",
"syn 1.0.109",
]
@@ -227,8 +227,8 @@ dependencies = [
"nom",
"num-traits",
"percent-encoding",
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"serde",
"syn 1.0.109",
"toml",
@@ -275,8 +275,8 @@ version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193"
dependencies = [
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 2.0.15",
]
@@ -286,8 +286,8 @@ version = "0.1.68"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9ccdd8f2a161be9bd5c023df56f1b2a0bd1d83872ae53b71a84a12c9bf6e842"
dependencies = [
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 2.0.15",
]
@@ -423,8 +423,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bb524613be645939e280b7279f7b017f98cf7f5ef084ec374df373530e73277"
dependencies = [
"heck 0.4.1",
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 2.0.15",
]
@@ -499,8 +499,8 @@ dependencies = [
"lazy_static",
"lazycell",
"peeking_take_while",
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"regex",
"rustc-hash",
"shlex",
@@ -570,7 +570,7 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b872f3528eeeb4370ee73b51194dc1cd93680c2d0eb6c7a223889038d2c1a167"
dependencies = [
- "quote",
+ "quote 1.0.26",
"syn 1.0.109",
]
@@ -597,8 +597,8 @@ version = "0.6.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e31225543cb46f81a7e224762764f4a6a0f097b1db0b175f69e8065efaa42de5"
dependencies = [
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 1.0.109",
]
@@ -607,6 +607,20 @@ name = "bytemuck"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17febce684fd15d89027105661fec94afb475cb995fbc59d2865198446ba2eea"
+dependencies = [
+ "bytemuck_derive",
+]
+
+[[package]]
+name = "bytemuck_derive"
+version = "1.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fdde5c9cd29ebd706ce1b35600920a33550e402fc998a2e53ad3b42c3c47a192"
+dependencies = [
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
+ "syn 2.0.15",
+]
[[package]]
name = "byteorder"
@@ -821,8 +835,8 @@ checksum = "ea0c8bce528c4be4da13ea6fead8965e95b6073585a2f05204bd8f4119f82a65"
dependencies = [
"heck 0.4.1",
"proc-macro-error",
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 1.0.109",
]
@@ -833,8 +847,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9644cd56d6b87dbe899ef8b053e331c0637664e9e21a33dfcdc36093f5c5c4"
dependencies = [
"heck 0.4.1",
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 2.0.15",
]
@@ -1059,8 +1073,8 @@ dependencies = [
"itoa 0.4.8",
"matches",
"phf 0.8.0",
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"smallvec",
"syn 1.0.109",
]
@@ -1071,7 +1085,7 @@ version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfae75de57f2b2e85e8768c3ea840fd159c8f33e2b6522c7835b7abac81be16e"
dependencies = [
- "quote",
+ "quote 1.0.26",
"syn 1.0.109",
]
@@ -1126,8 +1140,8 @@ dependencies = [
"cc",
"codespan-reporting",
"once_cell",
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"scratch",
"syn 2.0.15",
]
@@ -1144,8 +1158,8 @@ version = "1.0.94"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2345488264226bf682893e25de0769f3360aac9957980ec49361b083ddaa5bc5"
dependencies = [
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 2.0.15",
]
@@ -1167,8 +1181,8 @@ checksum = "109c1ca6e6b7f82cc233a97004ea8ed7ca123a9af07a8230878fcfda9b158bf0"
dependencies = [
"fnv",
"ident_case",
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"strsim",
"syn 1.0.109",
]
@@ -1180,7 +1194,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4aab4dbc9f7611d8b55048a3a16d2d010c2c8334e46304b40ac1cc14bf3b48e"
dependencies = [
"darling_core",
- "quote",
+ "quote 1.0.26",
"syn 1.0.109",
]
@@ -1213,8 +1227,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c11bdc11a0c47bc7d37d582b5285da6849c96681023680b906673c5707af7b0f"
dependencies = [
"darling",
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 1.0.109",
]
@@ -1235,8 +1249,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321"
dependencies = [
"convert_case",
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"rustc_version",
"syn 1.0.109",
]
@@ -1628,8 +1642,8 @@ version = "0.3.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72"
dependencies = [
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 2.0.15",
]
@@ -1888,8 +1902,8 @@ dependencies = [
"log",
"mac",
"markup5ever",
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 1.0.109",
]
@@ -2225,7 +2239,7 @@ dependencies = [
"string_cache",
"term",
"tiny-keccak",
- "unicode-xid",
+ "unicode-xid 0.2.4",
]
[[package]]
@@ -2277,6 +2291,12 @@ dependencies = [
"winapi",
]
+[[package]]
+name = "libm"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f7012b1bbb0719e1097c47611d3898568c546d597c2e74d66f6087edd5233ff4"
+
[[package]]
name = "librocksdb-sys"
version = "0.8.3+7.4.4"
@@ -2354,8 +2374,8 @@ checksum = "a1d849148dbaf9661a6151d1ca82b13bb4c4c128146a88d05253b38d4e2f496c"
dependencies = [
"beef",
"fnv",
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"regex-syntax 0.6.29",
"syn 1.0.109",
]
@@ -2485,8 +2505,8 @@ version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f1b8c13cb1f814b634a96b2c725449fe7ed464a7b8781de8688be5ffbd3f305"
dependencies = [
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 1.0.109",
]
@@ -2624,8 +2644,8 @@ version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8795add3e14028f11f8e848bd3294898a8294767b3776b6f733560d33bd2530b"
dependencies = [
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 2.0.15",
]
@@ -2758,6 +2778,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd"
dependencies = [
"autocfg",
+ "libm",
]
[[package]]
@@ -2786,8 +2807,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dcbff9bc912032c62bf65ef1d5aea88983b420f4f839db1e9b0c281a25c9c799"
dependencies = [
"proc-macro-crate",
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 1.0.109",
]
@@ -2882,8 +2903,8 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
dependencies = [
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 2.0.15",
]
@@ -3098,8 +3119,8 @@ dependencies = [
"phf_generator 0.8.0",
"phf_shared 0.8.0",
"proc-macro-hack",
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 1.0.109",
]
@@ -3142,8 +3163,8 @@ version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "069bdb1e05adc7a8990dce9cc75370895fbe4e3d58b9b73bf1aee56359344a55"
dependencies = [
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 1.0.109",
]
@@ -3247,8 +3268,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"
dependencies = [
"proc-macro-error-attr",
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 1.0.109",
"version_check",
]
@@ -3259,8 +3280,8 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"
dependencies = [
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"version_check",
]
@@ -3270,6 +3291,15 @@ version = "0.5.20+deprecated"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068"
+[[package]]
+name = "proc-macro2"
+version = "0.4.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759"
+dependencies = [
+ "unicode-xid 0.1.0",
+]
+
[[package]]
name = "proc-macro2"
version = "1.0.56"
@@ -3279,6 +3309,37 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "proptest"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e35c06b98bf36aba164cc17cb25f7e232f5c4aeea73baa14b8a9f0d92dbfa65"
+dependencies = [
+ "bit-set",
+ "bitflags",
+ "byteorder",
+ "lazy_static",
+ "num-traits",
+ "rand 0.8.5",
+ "rand_chacha 0.3.1",
+ "rand_xorshift",
+ "regex-syntax 0.6.29",
+ "rusty-fork",
+ "tempfile",
+ "unarray",
+]
+
+[[package]]
+name = "proptest-derive"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "90b46295382dc76166cb7cf2bb4a97952464e4b7ed5a43e6cd34e1fec3349ddc"
+dependencies = [
+ "proc-macro2 0.4.30",
+ "quote 0.6.13",
+ "syn 0.15.44",
+]
+
[[package]]
name = "ptr_meta"
version = "0.1.4"
@@ -3294,8 +3355,8 @@ version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16b845dbfca988fa33db069c0e230574d15a3088f147a87b64c7589eb662c9ac"
dependencies = [
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 1.0.109",
]
@@ -3308,6 +3369,12 @@ dependencies = [
"bytemuck",
]
+[[package]]
+name = "quick-error"
+version = "1.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
+
[[package]]
name = "quick-xml"
version = "0.23.1"
@@ -3327,13 +3394,22 @@ dependencies = [
"serde",
]
+[[package]]
+name = "quote"
+version = "0.6.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1"
+dependencies = [
+ "proc-macro2 0.4.30",
+]
+
[[package]]
name = "quote"
version = "1.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4424af4bf778aae2051a77b60283332f386554255d722233d09fbfc7e30da2fc"
dependencies = [
- "proc-macro2",
+ "proc-macro2 1.0.56",
]
[[package]]
@@ -3423,6 +3499,15 @@ dependencies = [
"rand_core 0.5.1",
]
+[[package]]
+name = "rand_xorshift"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d25bf25ec5ae4a3f1b92f929810509a2f53d7dca2f50b794ff57e3face536c8f"
+dependencies = [
+ "rand_core 0.6.4",
+]
+
[[package]]
name = "rawpointer"
version = "0.2.1"
@@ -3607,8 +3692,8 @@ version = "0.7.41"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac1c672430eb41556291981f45ca900a0239ad007242d1cb4b4167af842db666"
dependencies = [
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 1.0.109",
]
@@ -3723,6 +3808,18 @@ version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f3208ce4d8448b3f3e7d168a73f5e0c43a61e32930de3bceeccedb388b6bf06"
+[[package]]
+name = "rusty-fork"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb3dcc6e454c328bb824492db107ab7c0ae8fcffe4ad210136ef014458c1bc4f"
+dependencies = [
+ "fnv",
+ "quick-error",
+ "tempfile",
+ "wait-timeout",
+]
+
[[package]]
name = "rxml"
version = "0.9.1"
@@ -3851,7 +3948,7 @@ version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e03b3a19daa79085439113c746d2946e5e6effd2d9039bf092bb08df915487b2"
dependencies = [
- "quote",
+ "quote 1.0.26",
"syn 1.0.109",
]
@@ -3935,8 +4032,8 @@ version = "1.0.160"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "291a097c63d8497e00160b166a967a4a79c64f3facdd01cbd7502231688d77df"
dependencies = [
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 2.0.15",
]
@@ -4137,6 +4234,7 @@ dependencies = [
"base64 0.13.1",
"bincode",
"bitvec",
+ "bytemuck",
"byteorder",
"bzip2",
"chitchat",
@@ -4173,6 +4271,8 @@ dependencies = [
"once_cell",
"optics",
"parse_wiki_text",
+ "proptest",
+ "proptest-derive",
"quick-xml 0.23.1",
"rand 0.8.5",
"rayon",
@@ -4228,8 +4328,8 @@ checksum = "6bb30289b722be4ff74a408c3cc27edeaad656e06cb1fe8fa9231fa59c728988"
dependencies = [
"phf_generator 0.10.0",
"phf_shared 0.10.0",
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
]
[[package]]
@@ -4251,8 +4351,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5bb0dc7ee9c15cea6199cde9a127fa16a4c5819af85395457ad72d68edc85a38"
dependencies = [
"heck 0.3.3",
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"rustversion",
"syn 1.0.109",
]
@@ -4263,14 +4363,25 @@ version = "2.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601"
+[[package]]
+name = "syn"
+version = "0.15.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ca4b3b69a77cbe1ffc9e198781b7acb0c7365a883670e8f1c1bc66fba79a5c5"
+dependencies = [
+ "proc-macro2 0.4.30",
+ "quote 0.6.13",
+ "unicode-xid 0.1.0",
+]
+
[[package]]
name = "syn"
version = "1.0.109"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
dependencies = [
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"unicode-ident",
]
@@ -4280,8 +4391,8 @@ version = "2.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a34fcf3e8b60f57e6a14301a2e916d323af98b0ea63c599441eec8558660c822"
dependencies = [
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"unicode-ident",
]
@@ -4495,8 +4606,8 @@ version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f"
dependencies = [
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 2.0.15",
]
@@ -4654,8 +4765,8 @@ version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61a573bdc87985e9d6ddeed1b3d864e8a302c847e40d647746df2f1de209d1ce"
dependencies = [
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 2.0.15",
]
@@ -4806,8 +4917,8 @@ version = "0.1.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4017f8f45139870ca7e672686113917c71c7a6e02d4924eda67186083c03081a"
dependencies = [
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 1.0.109",
]
@@ -4872,6 +4983,12 @@ version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba"
+[[package]]
+name = "unarray"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
+
[[package]]
name = "unicase"
version = "2.6.0"
@@ -4923,6 +5040,12 @@ version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b"
+[[package]]
+name = "unicode-xid"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc"
+
[[package]]
name = "unicode-xid"
version = "0.2.4"
@@ -5015,6 +5138,15 @@ version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
+[[package]]
+name = "wait-timeout"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f200f5b12eb75f8c1ed65abd4b2db8a6e1b138a20de009dacee265a2498f3f6"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "walkdir"
version = "2.3.3"
@@ -5072,8 +5204,8 @@ dependencies = [
"bumpalo",
"log",
"once_cell",
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 1.0.109",
"wasm-bindgen-shared",
]
@@ -5096,7 +5228,7 @@ version = "0.2.84"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c21f77c0bedc37fd5dc21f897894a5ca01e7bb159884559461862ae90c0b4c5"
dependencies = [
- "quote",
+ "quote 1.0.26",
"wasm-bindgen-macro-support",
]
@@ -5106,8 +5238,8 @@ version = "0.2.84"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2aff81306fcac3c7515ad4e177f521b5c9a15f2b08f4e32d823066102f35a5f6"
dependencies = [
- "proc-macro2",
- "quote",
+ "proc-macro2 1.0.56",
+ "quote 1.0.26",
"syn 1.0.109",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
diff --git a/Cargo.toml b/Cargo.toml
index f0da6f28..ee9874a1 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -92,4 +92,7 @@ async-channel = "1.8.0"
lru = "0.10.0"
url = { version = "2.4.0", features = ["serde"] }
anyhow = { version = "1.0.72", features = ["backtrace"] }
+bytemuck = { version = "1.13.1", features = ["derive"] }
+proptest = "1.2.0"
+proptest-derive = "0.3.0"
diff --git a/core/Cargo.toml b/core/Cargo.toml
index 417d7763..649cbfb4 100644
--- a/core/Cargo.toml
+++ b/core/Cargo.toml
@@ -92,6 +92,7 @@ async-channel = { workspace = true }
lru = { workspace = true }
url = { workspace = true }
anyhow = { workspace = true }
+bytemuck = { workspace = true }
[build-dependencies]
lalrpop = { workspace = true }
@@ -99,6 +100,8 @@ lalrpop = { workspace = true }
[dev-dependencies]
criterion = { workspace = true }
maplit = { workspace = true }
+proptest = { workspace = true }
+proptest-derive = { workspace = true }
[[bench]]
name = "search-preindexed"
diff --git a/core/examples/mapreduce_manager.rs b/core/examples/mapreduce_manager.rs
index 0c2846b4..f2fc1d8f 100644
--- a/core/examples/mapreduce_manager.rs
+++ b/core/examples/mapreduce_manager.rs
@@ -5,7 +5,7 @@ use stract::mapreduce::{Manager, Map, Reduce, StatelessWorker};
use tracing::Level;
use tracing_subscriber::FmtSubscriber;
-#[derive(Serialize, Deserialize, Debug)]
+#[derive(Clone, Serialize, Deserialize, Debug)]
struct Job {
id: usize,
}
diff --git a/core/src/api/webgraph.rs b/core/src/api/webgraph.rs
index bf25f239..4d803503 100644
--- a/core/src/api/webgraph.rs
+++ b/core/src/api/webgraph.rs
@@ -19,10 +19,8 @@ use std::{net::SocketAddr, sync::Arc, time::Duration};
use axum::{extract, response::IntoResponse, Json};
use http::StatusCode;
-use crate::{
- distributed::{cluster::Cluster, member::Service, retry_strategy::ExponentialBackoff, sonic},
- entrypoint::webgraph_server::ScoredSite,
- webgraph::Node,
+use crate::distributed::{
+ cluster::Cluster, member::Service, retry_strategy::ExponentialBackoff, sonic,
};
use super::State;
@@ -67,11 +65,11 @@ pub async fn similar_sites(
.with_limit(Duration::from_millis(200))
.take(5);
- let mut conn = sonic::ResilientConnection::create(host, retry);
+ let conn = sonic::service::ResilientConnection::create(host, retry);
match conn
- .send_with_timeout::<_, Vec<ScoredSite>>(
- &crate::entrypoint::webgraph_server::Request::SimilarSites {
+ .send_with_timeout(
+ &crate::entrypoint::webgraph_server::SimilarSites {
sites: params.sites,
top_n: params.top_n,
},
@@ -79,12 +77,11 @@ pub async fn similar_sites(
)
.await
{
- Ok(sonic::Response::Content(nodes)) => Ok(Json(nodes)),
+ Ok(nodes) => Ok(Json(nodes)),
Err(err) => {
tracing::error!("Failed to send request to webgraph: {}", err);
Err(StatusCode::INTERNAL_SERVER_ERROR)
}
- _ => Err(StatusCode::INTERNAL_SERVER_ERROR),
}
}
@@ -111,16 +108,16 @@ pub async fn knows_site(
.with_limit(Duration::from_millis(200))
.take(5);
- let mut conn = sonic::ResilientConnection::create(host, retry);
+ let conn = sonic::service::ResilientConnection::create(host, retry);
match conn
- .send_with_timeout::<_, Option<Node>>(
- &crate::entrypoint::webgraph_server::Request::Knows { site: params.site },
+ .send_with_timeout(
+ &crate::entrypoint::webgraph_server::Knows { site: params.site },
Duration::from_secs(2),
)
.await
{
- Ok(sonic::Response::Content(Some(node))) => Ok(Json(KnowsSite::Known { site: node.name })),
+ Ok(Some(node)) => Ok(Json(KnowsSite::Known { site: node.name })),
Err(err) => {
tracing::error!("Failed to send request to webgraph: {}", err);
Ok(Json(KnowsSite::Unknown))
diff --git a/core/src/crawler/mod.rs b/core/src/crawler/mod.rs
index 8beef4a4..8163b43e 100644
--- a/core/src/crawler/mod.rs
+++ b/core/src/crawler/mod.rs
@@ -175,15 +175,7 @@ impl Crawler {
}
}
-#[derive(serde::Serialize, serde::Deserialize)]
-pub enum Request {
- NewJobs {
- responses: Vec<JobResponse>,
- num_jobs: usize,
- },
-}
-
-#[derive(serde::Serialize, serde::Deserialize)]
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum Response {
NewJobs { jobs: Vec<Job> },
Done,
diff --git a/core/src/crawler/worker.rs b/core/src/crawler/worker.rs
index 9a2d0f2a..0ccb3bb6 100644
--- a/core/src/crawler/worker.rs
+++ b/core/src/crawler/worker.rs
@@ -28,8 +28,9 @@ use url::Url;
use crate::{
config::CrawlerConfig,
- crawler::{JobResponse, Request, Response},
+ crawler::{JobResponse, Response},
distributed::{retry_strategy::ExponentialBackoff, sonic},
+ entrypoint::crawler::{CoordinatorService, NewJobs},
webpage::Html,
};
@@ -90,10 +91,12 @@ impl WorkerThread {
})
}
- fn coordinator_conn(&self) -> sonic::ResilientConnection<ExponentialBackoff> {
+ fn coordinator_conn(
+ &self,
+ ) -> sonic::service::ResilientConnection<CoordinatorService, ExponentialBackoff> {
let retry = ExponentialBackoff::from_millis(1_000).with_limit(Duration::from_secs(10));
- sonic::ResilientConnection::create(self.coordinator_host, retry)
+ sonic::service::ResilientConnection::create(self.coordinator_host, retry)
}
pub async fn run(mut self) {
@@ -119,12 +122,12 @@ impl WorkerThread {
}
}
} else {
- let mut conn = self.coordinator_conn();
+ let conn = self.coordinator_conn();
let results = self.results.lock().await.drain(..).collect::<Vec<_>>();
let res = conn
- .send_with_timeout::<_, Response>(
- &Request::NewJobs {
+ .send_with_timeout(
+ &NewJobs {
responses: results,
num_jobs: 2 * self.num_jobs_per_fetch,
},
@@ -133,7 +136,7 @@ impl WorkerThread {
.await;
match res {
- Ok(sonic::Response::Content(Response::NewJobs { jobs })) => {
+ Ok(Response::NewJobs { jobs }) => {
if jobs.is_empty() {
drop(guard);
tokio::time::sleep(Duration::from_secs(30)).await;
@@ -142,7 +145,7 @@ impl WorkerThread {
guard.extend(jobs.into_iter().map(Command::Job));
}
- Ok(sonic::Response::Content(Response::Done)) => {
+ Ok(Response::Done) => {
guard.push_back(Command::Shutdown);
break;
diff --git a/core/src/distributed/sonic.rs b/core/src/distributed/sonic.rs
deleted file mode 100644
index 62d77092..00000000
--- a/core/src/distributed/sonic.rs
+++ /dev/null
@@ -1,217 +0,0 @@
-// Stract is an open source web search engine.
-// Copyright (C) 2023 Stract ApS
-//
-// This program is free software: you can redistribute it and/or modify
-// it under the terms of the GNU Affero General Public License as
-// published by the Free Software Foundation, either version 3 of the
-// License, or (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU Affero General Public License for more details.
-//
-// You should have received a copy of the GNU Affero General Public License
-// along with this program. If not, see <https://www.gnu.org/licenses/>.
-
-use std::{net::SocketAddr, time::Duration};
-
-use serde::{de::DeserializeOwned, Deserialize, Serialize};
-use thiserror::Error;
-use tokio::{
- io::{AsyncReadExt, AsyncWriteExt},
- net::{TcpListener, TcpStream, ToSocketAddrs},
-};
-
-type Result<T> = std::result::Result<T, Error>;
-
-#[derive(Error, Debug)]
-pub enum Error {
- #[error("Got an IO error")]
- IO(#[from] std::io::Error),
-
- #[error("Error while serializing/deserializing to/from bytes")]
- Serialization(#[from] bincode::Error),
-
- #[error("Failed to connect to peer: connection timeout")]
- ConnectionTimeout,
-}
-
-#[derive(Serialize, Deserialize)]
-pub enum Response<T: Serialize> {
- Empty,
- Content(T),
-}
-
-#[repr(C)]
-struct Header {
- body_size: usize,
-}
-
-pub struct Request<T> {
- stream: TcpStream,
- pub body: T,
-}
-
-unsafe fn any_as_u8_slice<T: Sized>(p: &T) -> &[u8] {
- std::slice::from_raw_parts((p as *const T) as *const u8, std::mem::size_of::<T>())
-}
-
-impl<T> Request<T> {
- pub async fn respond<R: Serialize>(mut self, response: Response<R>) -> Result<()> {
- let bytes = bincode::serialize(&response).unwrap();
- let header = Header {
- body_size: bytes.len(),
- };
-
- self.stream
- .write_all(unsafe { any_as_u8_slice(&header) })
- .await?;
- self.stream.write_all(&bytes).await?;
- self.stream.flush().await?;
-
- self.stream.shutdown().await?;
-
- Ok(())
- }
-}
-
-pub struct Server {
- listener: TcpListener,
-}
-
-impl Server {
- pub async fn bind(addr: impl ToSocketAddrs) -> Result<Self> {
- let listener = TcpListener::bind(addr).await?;
- Ok(Self { listener })
- }
-
- pub async fn accept<T>(&self) -> Result<Request<T>>
- where
- T: Serialize + DeserializeOwned,
- {
- let (mut stream, client) = self.listener.accept().await?;
- tracing::debug!("accepted connection from: {}", &client);
-
- let mut header_buf = vec![0; std::mem::size_of::<Header>()];
- stream.read_exact(&mut header_buf).await?;
- let header: Header = unsafe { std::ptr::read(header_buf.as_ptr() as *const _) };
-
- let mut buf = vec![0; header.body_size];
-
- stream.read_exact(&mut buf).await?;
- tracing::debug!("received bytes: {:?}", &buf);
-
- let body = bincode::deserialize(&buf).unwrap();
-
- Ok(Request { stream, body })
- }
-}
-
-pub struct Connection {
- stream: TcpStream,
-}
-
-impl Connection {
- pub async fn create(server: impl ToSocketAddrs) -> Result<Self> {
- Self::create_with_timeout(server, Duration::from_secs(30)).await
- }
-
- pub async fn create_with_timeout(
- server: impl ToSocketAddrs,
- timeout: Duration,
- ) -> Result<Self> {
- match tokio::time::timeout(timeout, TcpStream::connect(server)).await {
- Ok(stream) => {
- let stream = stream?;
- Ok(Connection { stream })
- }
- Err(_) => Err(Error::ConnectionTimeout),
- }
- }
-
- pub async fn send_without_timeout<T: Serialize, R: DeserializeOwned + Serialize>(
- mut self,
- request: &T,
- ) -> Result<Response<R>> {
- let bytes = bincode::serialize(&request).unwrap();
-
- let header = Header {
- body_size: bytes.len(),
- };
-
- self.stream
- .write_all(unsafe { any_as_u8_slice(&header) })
- .await?;
- self.stream.write_all(&bytes).await?;
- self.stream.flush().await?;
-
- let mut header_buf = vec![0; std::mem::size_of::<Header>()];
- self.stream.read_exact(&mut header_buf).await?;
- let header: Header = unsafe { std::ptr::read(header_buf.as_ptr() as *const _) };
-
- let mut buf = vec![0; header.body_size];
- self.stream.read_exact(&mut buf).await?;
-
- self.stream.shutdown().await?;
-
- Ok(bincode::deserialize(&buf).unwrap())
- }
-
- pub async fn send<T: Serialize, R: DeserializeOwned + Serialize>(
- self,
- request: &T,
- ) -> Result<Response<R>> {
- self.send_with_timeout(request, Duration::from_secs(30))
- .await
- }
-
- pub async fn send_with_timeout<T: Serialize, R: DeserializeOwned + Serialize>(
- self,
- request: &T,
- timeout: Duration,
- ) -> Result<Response<R>> {
- match tokio::time::timeout(timeout, self.send_without_timeout(request)).await {
- Ok(res) => res,
- Err(_) => Err(Error::ConnectionTimeout),
- }
- }
-}
-
-pub struct ResilientConnection<Rt: Iterator<Item = Duration>> {
- addr: SocketAddr,
- retry: Rt,
-}
-
-impl<Rt: Iterator<Item = Duration>> ResilientConnection<Rt> {
- pub fn create(addr: SocketAddr, retry: Rt) -> Self {
- Self { addr, retry }
- }
-
- pub async fn send_with_timeout<T: Serialize, R: DeserializeOwned + Serialize>(
- &mut self,
- request: &T,
- timeout: Duration,
- ) -> Result<Response<R>> {
- loop {
- match Connection::create_with_timeout(&self.addr, timeout).await {
- Ok(conn) => {
- let response = conn.send_with_timeout(request, timeout).await;
- if let Err(Error::ConnectionTimeout) = response {
- continue;
- }
- return response;
- }
- Err(Error::ConnectionTimeout) => {
- if let Some(timeout) = self.retry.next() {
- tokio::time::sleep(timeout).await;
- continue;
- } else {
- return Err(Error::ConnectionTimeout);
- }
- }
- Err(e) => return Err(e),
- }
- }
- }
-}
diff --git a/core/src/distributed/sonic/mod.rs b/core/src/distributed/sonic/mod.rs
new file mode 100644
index 00000000..e59d0c0a
--- /dev/null
+++ b/core/src/distributed/sonic/mod.rs
@@ -0,0 +1,253 @@
+// Stract is an open source web search engine.
+// Copyright (C) 2023 Stract ApS
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+pub mod service;
+
+use std::{marker::PhantomData, time::Duration};
+
+use serde::{de::DeserializeOwned, Serialize};
+use tokio::{
+ io::{AsyncReadExt, AsyncWriteExt},
+ net::{TcpListener, TcpStream, ToSocketAddrs},
+};
+
+pub(crate) type Result<T, E = Error> = std::result::Result<T, E>;
+
+#[derive(thiserror::Error, Debug)]
+pub enum Error {
+ #[error("Got an IO error")]
+ IO(#[from] std::io::Error),
+
+ #[error("Error while serializing/deserializing to/from bytes")]
+ Serialization(#[from] bincode::Error),
+
+ #[error("Failed to connect to peer: connection timeout")]
+ ConnectionTimeout,
+
+ #[error("Other")]
+ Other(#[from] anyhow::Error),
+}
+
+pub struct Server<Req, Res> {
+ pub(super) listener: TcpListener,
+ marker: PhantomData<(Req, Res)>,
+}
+pub struct Connection<Req, Res> {
+ stream: TcpStream,
+ marker: PhantomData<(Req, Res)>,
+}
+pub struct Request<Req, Res> {
+ stream: TcpStream,
+ body: Option<Req>,
+ marker: PhantomData<(Req, Res)>,
+}
+
+#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
+#[repr(C)]
+struct Header {
+ body_size: usize,
+}
+
+impl<Req, Res> Server<Req, Res>
+where
+ Req: DeserializeOwned,
+{
+ pub async fn bind(addr: impl ToSocketAddrs) -> Result<Self> {
+ let listener = TcpListener::bind(addr).await?;
+ Ok(Server {
+ listener,
+ marker: PhantomData,
+ })
+ }
+ pub async fn accept(&self) -> Result<Request<Req, Res>> {
+ let (mut stream, client) = self.listener.accept().await?;
+ tracing::debug!("accepted connection from: {}", &client);
+
+ let mut header_buf = vec![0; std::mem::size_of::<Header>()];
+ stream.read_exact(&mut header_buf).await?;
+ let header: Header = *bytemuck::from_bytes(&header_buf);
+
+ let mut buf = vec![0; header.body_size];
+
+ stream.read_exact(&mut buf).await?;
+ tracing::debug!("received bytes: {:?}", &buf);
+
+ let body = Some(bincode::deserialize(&buf).unwrap());
+
+ Ok(Request {
+ stream,
+ body,
+ marker: PhantomData,
+ })
+ }
+}
+
+impl<Req, Res> Connection<Req, Res>
+where
+ Req: Serialize,
+ Res: DeserializeOwned,
+{
+ pub async fn create(server: impl ToSocketAddrs) -> Result<Self> {
+ Self::create_with_timeout(server, Duration::from_secs(30)).await
+ }
+
+ pub async fn create_with_timeout(
+ server: impl ToSocketAddrs,
+ timeout: Duration,
+ ) -> Result<Self> {
+ match tokio::time::timeout(timeout, TcpStream::connect(server)).await {
+ Ok(stream) => {
+ let stream = stream?;
+ Ok(Connection {
+ stream,
+ marker: PhantomData,
+ })
+ }
+ Err(_) => Err(Error::ConnectionTimeout),
+ }
+ }
+
+ pub async fn send_without_timeout(mut self, request: &Req) -> Result<Res> {
+ let bytes = bincode::serialize(&request).unwrap();
+
+ let header = Header {
+ body_size: bytes.len(),
+ };
+
+ self.stream.write_all(bytemuck::bytes_of(&header)).await?;
+ self.stream.write_all(&bytes).await?;
+ self.stream.flush().await?;
+
+ let mut header_buf = vec![0; std::mem::size_of::<Header>()];
+ self.stream.read_exact(&mut header_buf).await?;
+ let header: Header = *bytemuck::from_bytes(&header_buf);
+
+ let mut buf = vec![0; header.body_size];
+ self.stream.read_exact(&mut buf).await?;
+
+ self.stream.shutdown().await?;
+
+ Ok(bincode::deserialize(&buf).unwrap())
+ }
+
+ pub async fn send(self, request: &Req) -> Result<Res> {
+ self.send_with_timeout(request, Duration::from_secs(30))
+ .await
+ }
+
+ pub async fn send_with_timeout(self, request: &Req, timeout: Duration) -> Result<Res> {
+ match tokio::time::timeout(timeout, self.send_without_timeout(request)).await {
+ Ok(res) => res,
+ Err(_) => Err(Error::ConnectionTimeout),
+ }
+ }
+}
+
+impl<Req, Res> Request<Req, Res>
+where
+ Res: Serialize,
+{
+ pub async fn respond(mut self, response: Res) -> Result<()> {
+ let bytes = bincode::serialize(&response).unwrap();
+ let header = Header {
+ body_size: bytes.len(),
+ };
+
+ self.stream.write_all(bytemuck::bytes_of(&header)).await?;
+ self.stream.write_all(&bytes).await?;
+ self.stream.flush().await?;
+
+ self.stream.shutdown().await?;
+
+ Ok(())
+ }
+ pub fn body(&self) -> &Req {
+ self.body.as_ref().unwrap()
+ }
+ fn take_body(&mut self) -> Req {
+ self.body.take().expect("body was taken twice")
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::{collections::HashMap, future::Future};
+
+ use proptest::prelude::*;
+ use proptest_derive::Arbitrary;
+ use serde::Deserialize;
+
+ use super::*;
+
+ fn fixture<
+ Req: Serialize + DeserializeOwned + Send + 'static,
+ Res: Serialize + DeserializeOwned + Send + 'static,
+ A: Send + 'static,
+ B: Send + 'static,
+ X: Future<Output = Result<A, TestCaseError>> + Send,
+ Y: Future<Output = Result<B, TestCaseError>> + Send,
+ >(
+ svr_fn: impl FnOnce(Server<Req, Res>) -> X + Send + 'static,
+ con_fn: impl FnOnce(Connection<Req, Res>) -> Y + Send + 'static,
+ ) -> (Result<A, TestCaseError>, Result<B, TestCaseError>) {
+ tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async move {
+ let server = Server::bind(("127.0.0.1", 0)).await.unwrap();
+ let addr = server.listener.local_addr().unwrap();
+ let connection = Connection::create(addr).await.unwrap();
+
+ let svr_task = tokio::spawn(async move { svr_fn(server).await });
+ let con_task = tokio::spawn(async move { con_fn(connection).await });
+
+ let (svr_res, con_res) = tokio::join!(svr_task, con_task);
+ (
+ svr_res.unwrap_or_else(|err| panic!("server failed: {err}")),
+ con_res.unwrap_or_else(|err| panic!("connection failed: {err}")),
+ )
+ })
+ }
+
+ #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Arbitrary)]
+ struct Message {
+ text: String,
+ other: HashMap<String, f32>,
+ }
+
+ proptest! {
+ #[test]
+ fn basic_arb(a1: Message, b1: Message) {
+ let (a2, b2) = (a1.clone(), b1.clone());
+ let (svr_res, con_res) = fixture(
+ |svr| async move {
+ let req = svr.accept().await?;
+ prop_assert_eq!(req.body(), &a1);
+ req.respond(b1).await?;
+ Ok(())
+ },
+ |con| async move {
+ let res = con.send(&a2).await?;
+ prop_assert_eq!(res, b2);
+ Ok(())
+ },
+ );
+ svr_res?;
+ con_res?;
+ }
+ }
+}
diff --git a/core/src/distributed/sonic/service.rs b/core/src/distributed/sonic/service.rs
new file mode 100644
index 00000000..07f4084f
--- /dev/null
+++ b/core/src/distributed/sonic/service.rs
@@ -0,0 +1,341 @@
+use std::{marker::PhantomData, net::SocketAddr, time::Duration};
+
+use tokio::net::ToSocketAddrs;
+
+use super::{Error, Result};
+
+#[async_trait::async_trait]
+pub trait Service: Sized {
+ type Request: serde::de::DeserializeOwned;
+ type RequestRef<'a>: serde::Serialize;
+ type Response: serde::Serialize + serde::de::DeserializeOwned;
+
+ async fn handle(req: Self::Request, server: &mut Self) -> Result<Self::Response>;
+}
+
+pub struct Connection<'a, S: Service> {
+ inner: super::Connection<S::RequestRef<'a>, S::Response>,
+}
+
+#[async_trait::async_trait]
+pub trait Message<S: Service> {
+ type Response;
+ async fn handle(self, server: &mut S) -> Result<Self::Response>;
+}
+pub trait Wrapper<S: Service>: Message<S> {
+ fn wrap_request_ref(req: &Self) -> S::RequestRef<'_>;
+ fn unwrap_response(res: S::Response) -> Option<Self::Response>;
+}
+
+pub struct Server<S: Service> {
+ inner: super::Server<S::Request, S::Response>,
+ service: S,
+}
+
+pub struct ResilientConnection<S: Service, Rt: Iterator<Item = Duration>> {
+ addr: SocketAddr,
+ retry: Rt,
+ marker: PhantomData<S>,
+}
+
+impl<S: Service> Server<S> {
+ pub async fn bind(service: S, addr: impl ToSocketAddrs) -> Result<Self> {
+ Ok(Server {
+ inner: super::Server::bind(addr).await?,
+ service,
+ })
+ }
+ pub async fn accept(&mut self) -> Result<()> {
+ let mut req = self.inner.accept().await?;
+ let res = S::handle(req.take_body(), &mut self.service).await?;
+ req.respond(res).await
+ }
+}
+
+impl<'a, S: Service> Connection<'a, S> {
+ #[allow(dead_code)]
+ pub async fn create(server: impl ToSocketAddrs) -> Result<Connection<'a, S>> {
+ Ok(Connection {
+ inner: super::Connection::create(server).await?,
+ })
+ }
+ #[allow(dead_code)]
+ pub async fn create_with_timeout(
+ server: impl ToSocketAddrs,
+ timeout: Duration,
+ ) -> Result<Connection<'a, S>> {
+ Ok(Connection {
+ inner: super::Connection::create_with_timeout(server, timeout).await?,
+ })
+ }
+ #[allow(dead_code)]
+ pub async fn send_without_timeout<R: Wrapper<S>>(self, request: &'a R) -> Result<R::Response> {
+ Ok(R::unwrap_response(
+ self.inner
+ .send_without_timeout(&R::wrap_request_ref(request))
+ .await?,
+ )
+ .unwrap())
+ }
+ #[allow(dead_code)]
+ pub async fn send<R: Wrapper<S>>(self, request: &'a R) -> Result<R::Response> {
+ Ok(R::unwrap_response(self.inner.send(&R::wrap_request_ref(request)).await?).unwrap())
+ }
+ #[allow(dead_code)]
+ pub async fn send_with_timeout<R: Wrapper<S>>(
+ self,
+ request: &'a R,
+ timeout: Duration,
+ ) -> Result<R::Response> {
+ Ok(R::unwrap_response(
+ self.inner
+ .send_with_timeout(&R::wrap_request_ref(request), timeout)
+ .await?,
+ )
+ .unwrap())
+ }
+}
+
+impl<S: Service, Rt: Iterator<Item = Duration>> ResilientConnection<S, Rt> {
+ pub fn create(addr: SocketAddr, retry: Rt) -> Self {
+ Self {
+ addr,
+ retry,
+ marker: PhantomData,
+ }
+ }
+
+ pub async fn send_with_timeout<R: Wrapper<S>>(
+ mut self,
+ request: &R,
+ timeout: Duration,
+ ) -> Result<R::Response> {
+ loop {
+ match Connection::create_with_timeout(&self.addr, timeout).await {
+ Ok(conn) => {
+ let response = conn.send_with_timeout(request, timeout).await;
+ if let Err(Error::ConnectionTimeout) = response {
+ continue;
+ }
+ return response;
+ }
+ Err(Error::ConnectionTimeout) => {
+ if let Some(timeout) = self.retry.next() {
+ tokio::time::sleep(timeout).await;
+ continue;
+ } else {
+ return Err(Error::ConnectionTimeout);
+ }
+ }
+ Err(e) => return Err(e),
+ }
+ }
+ }
+}
+
+#[macro_export]
+macro_rules! sonic_service {
+ ($service:ident, [$($req:ident),*$(,)?]) => {
+ mod service_impl__ {
+ #![allow(dead_code)]
+
+ use super::{$service, $($req),*};
+
+ use $crate::distributed::sonic;
+
+ #[derive(Debug, Clone, ::serde::Deserialize)]
+ pub enum Request {
+ $($req($req),)*
+ }
+ #[derive(Debug, Clone, ::serde::Serialize)]
+ pub enum RequestRef<'a> {
+ $($req(&'a $req),)*
+ }
+ #[derive(::serde::Serialize, ::serde::Deserialize)]
+ pub enum Response {
+ $($req(<$req as sonic::service::Message<$service>>::Response),)*
+ }
+ $(
+ impl sonic::service::Wrapper<$service> for $req {
+ fn wrap_request_ref(req: &Self) -> RequestRef {
+ RequestRef::$req(req)
+ }
+ fn unwrap_response(res: <$service as sonic::service::Service>::Response) -> Option<Self::Response> {
+ #[allow(irrefutable_let_patterns)]
+ if let Response::$req(value) = res {
+ Some(value)
+ } else {
+ None
+ }
+ }
+ }
+ )*
+ #[async_trait::async_trait]
+ impl sonic::service::Service for $service {
+ type Request = Request;
+ type RequestRef<'a> = RequestRef<'a>;
+ type Response = Response;
+
+ async fn handle(req: Request, server: &mut Self) -> sonic::Result<Response> {
+ match req {
+ $(
+ Request::$req(value) => Ok(Response::$req(sonic::service::Message::handle(value, server).await?)),
+ )*
+ }
+ }
+ }
+ impl $service {
+ pub async fn bind(self, addr: impl ::tokio::net::ToSocketAddrs) -> sonic::Result<sonic::service::Server<Self>> {
+ sonic::service::Server::bind(self, addr).await
+ }
+ }
+ }
+ };
+}
+
+#[cfg(test)]
+mod tests {
+ use proptest::prelude::*;
+
+ use std::{marker::PhantomData, net::SocketAddr};
+
+ use super::{Server, Service, Wrapper};
+ use futures::Future;
+
+ struct ConnectionBuilder<S> {
+ addr: SocketAddr,
+ marker: PhantomData<S>,
+ }
+
+ impl<S: Service> ConnectionBuilder<S> {
+ async fn send<R: Wrapper<S>>(&self, req: &R) -> Result<R::Response, anyhow::Error> {
+ Ok(super::Connection::create(self.addr)
+ .await?
+ .send(req)
+ .await?)
+ }
+ }
+
+ fn fixture<
+ S: Service + Send + Sync + 'static,
+ B: Send + Sync + 'static,
+ Y: Future<Output = Result<B, TestCaseError>> + Send,
+ >(
+ service: S,
+ con_fn: impl FnOnce(ConnectionBuilder<S>) -> Y + Send + 'static,
+ ) -> Result<B, TestCaseError>
+ where
+ S::Request: Send + Sync + 'static,
+ S::Response: Send + Sync + 'static,
+ {
+ tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(async move {
+ let mut server = Server::bind(service, ("127.0.0.1", 0)).await.unwrap();
+ let addr = server.inner.listener.local_addr().unwrap();
+
+ let svr_task: tokio::task::JoinHandle<Result<(), anyhow::Error>> =
+ tokio::spawn(async move {
+ loop {
+ server.accept().await?;
+ }
+ });
+ let con_res = tokio::spawn(async move {
+ con_fn(ConnectionBuilder {
+ addr,
+ marker: PhantomData,
+ })
+ .await
+ })
+ .await;
+ svr_task.abort();
+
+ con_res.unwrap_or_else(|err| panic!("connection failed: {err}"))
+ })
+ }
+
+ mod counter_service {
+ use proptest_derive::Arbitrary;
+ use serde::{Deserialize, Serialize};
+
+ use crate::distributed::sonic;
+
+ use super::super::Message;
+
+ pub struct CounterService {
+ pub counter: i32,
+ }
+
+ sonic_service!(CounterService, [Change, Reset]);
+
+ #[derive(Debug, Clone, Serialize, Deserialize, Arbitrary)]
+ pub struct Change {
+ pub amount: i32,
+ }
+ #[derive(Debug, Clone, Serialize, Deserialize)]
+ pub struct Reset;
+
+ #[async_trait::async_trait]
+ impl Message<CounterService> for Change {
+ type Response = i32;
+
+ async fn handle(self, server: &mut CounterService) -> sonic::Result<Self::Response> {
+ server.counter += self.amount;
+ Ok(server.counter)
+ }
+ }
+
+ #[async_trait::async_trait]
+ impl Message<CounterService> for Reset {
+ type Response = ();
+
+ async fn handle(self, server: &mut CounterService) -> sonic::Result<Self::Response> {
+ server.counter = 0;
+ Ok(())
+ }
+ }
+ }
+
+ use counter_service::*;
+
+ #[test]
+ fn simple_service() -> Result<(), TestCaseError> {
+ fixture(CounterService { counter: 0 }, |b| async move {
+ let val = b
+ .send(&Change { amount: 15 })
+ .await
+ .map_err(|e| TestCaseError::Fail(e.to_string().into()))?;
+ assert_eq!(val, 15);
+ let val = b
+ .send(&Change { amount: 15 })
+ .await
+ .map_err(|e| TestCaseError::Fail(e.to_string().into()))?;
+ assert_eq!(val, 30);
+ b.send(&Reset)
+ .await
+ .map_err(|e| TestCaseError::Fail(e.to_string().into()))?;
+ let val = b
+ .send(&Change { amount: 15 })
+ .await
+ .map_err(|e| TestCaseError::Fail(e.to_string().into()))?;
+ assert_eq!(val, 15);
+ Ok(())
+ })?;
+
+ Ok(())
+ }
+
+ proptest! {
+ #[test]
+ fn ref_serialization(a: Change) {
+ fixture(CounterService { counter: 0 }, |conn| async move {
+ conn.send(&Reset).await.map_err(|e| TestCaseError::Fail(e.to_string().into()))?;
+ let val = conn.send(&a).await.map_err(|e| TestCaseError::Fail(e.to_string().into()))?;
+ prop_assert_eq!(val, a.amount);
+ Ok(())
+ })?;
+ }
+ }
+}
diff --git a/core/src/entrypoint/crawler.rs b/core/src/entrypoint/crawler.rs
index f718262c..5657da92 100644
--- a/core/src/entrypoint/crawler.rs
+++ b/core/src/entrypoint/crawler.rs
@@ -16,11 +16,13 @@
use std::{net::SocketAddr, sync::Arc};
+use serde::{Deserialize, Serialize};
+
use crate::{
config,
- crawler::{CrawlCoordinator, Crawler},
- distributed::sonic,
- Result,
+ crawler::{CrawlCoordinator, Crawler, JobResponse},
+ distributed::sonic::{self, service::Message},
+ sonic_service, Result,
};
pub async fn worker(config: config::CrawlerConfig) -> Result<()> {
@@ -31,6 +33,35 @@ pub async fn worker(config: config::CrawlerConfig) -> Result<()> {
Ok(())
}
+pub struct CoordinatorService {
+ coordinator: Arc<CrawlCoordinator>,
+}
+
+sonic_service!(CoordinatorService, [NewJobs]);
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct NewJobs {
+ pub responses: Vec<JobResponse>,
+ pub num_jobs: usize,
+}
+#[async_trait::async_trait]
+impl Message<CoordinatorService> for NewJobs {
+ type Response = crate::crawler::Response;
+
+ async fn handle(self, server: &mut CoordinatorService) -> sonic::Result<Self::Response> {
+ server.coordinator.add_responses(&self.responses)?;
+
+ if server.coordinator.is_done() {
+ tracing::info!("Crawl is done. Waiting for workers to finish.");
+ Ok(crate::crawler::Response::Done)
+ } else {
+ let jobs = server.coordinator.sample_jobs(self.num_jobs)?;
+
+ Ok(crate::crawler::Response::NewJobs { jobs })
+ }
+ }
+}
+
pub async fn coordinator(config: config::CrawlCoordinatorConfig) -> Result<()> {
let coordinator = Arc::new(CrawlCoordinator::new(
config.crawldb_folder,
@@ -39,35 +70,11 @@ pub async fn coordinator(config: config::CrawlCoordinatorConfig) -> Result<()> {
)?);
let addr: SocketAddr = config.host;
- let server = sonic::Server::bind(addr).await.unwrap();
+ let mut server = CoordinatorService { coordinator }.bind(addr).await.unwrap();
tracing::info!("Crawl coordinator listening on {}", addr);
loop {
- if let Ok(req) = server.accept::<crate::crawler::Request>().await {
- match &req.body {
- crate::crawler::Request::NewJobs {
- responses,
- num_jobs,
- } => {
- coordinator.add_responses(responses)?;
-
- if coordinator.is_done() {
- tracing::info!("Crawl is done. Waiting for workers to finish.");
- req.respond(sonic::Response::Content(crate::crawler::Response::Done))
- .await
- .ok();
- } else {
- let jobs = coordinator.sample_jobs(*num_jobs)?;
-
- req.respond(sonic::Response::Content(
- crate::crawler::Response::NewJobs { jobs },
- ))
- .await
- .ok();
- }
- }
- }
- }
+ let _ = server.accept().await;
}
}
diff --git a/core/src/entrypoint/search_server.rs b/core/src/entrypoint/search_server.rs
index 0016d60e..53814954 100644
--- a/core/src/entrypoint/search_server.rs
+++ b/core/src/entrypoint/search_server.rs
@@ -14,9 +14,11 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
-use std::{collections::HashMap, net::SocketAddr};
+use std::collections::HashMap;
+use serde::{Deserialize, Serialize};
use tracing::info;
+use url::Url;
use crate::{
config,
@@ -27,111 +29,158 @@ use crate::{
},
entity_index::EntityIndex,
index::Index,
- inverted_index,
+ inverted_index::{self, RetrievedWebpage},
ranking::{
centrality_store::SearchCentralityStore,
models::{lambdamart::LambdaMART, linear::LinearRegression},
},
- searcher::{self, LocalSearcher},
- Result,
+ searcher::{InitialWebsiteResult, LocalSearcher, SearchQuery},
+ sonic_service, Result,
};
-pub async fn run(config: config::SearchServerConfig) -> Result<()> {
- let addr: SocketAddr = config.host;
- let server = sonic::Server::bind(addr).await.unwrap();
+sonic_service!(
+ SearchService,
+ [
+ RetrieveWebsites,
+ Search,
+ GetWebpage,
+ GetHomepageDescriptions,
+ ]
+);
+
+pub struct SearchService {
+ local_searcher: LocalSearcher,
+ // dropping the handle leaves the cluster
+ #[allow(unused)]
+ cluster_handle: Cluster,
+}
+
+impl SearchService {
+ async fn new(config: config::SearchServerConfig) -> Result<Self> {
+ let entity_index = config
+ .entity_index_path
+ .map(|path| EntityIndex::open(path).unwrap());
+ let centrality_store = config
+ .host_centrality_store_path
+ .map(SearchCentralityStore::open);
+ let search_index = Index::open(config.index_path)?;
+
+ let mut local_searcher = LocalSearcher::new(search_index);
- let entity_index = config
- .entity_index_path
- .map(|path| EntityIndex::open(path).unwrap());
- let centrality_store = config
- .host_centrality_store_path
- .map(SearchCentralityStore::open);
- let search_index = Index::open(config.index_path)?;
+ if let Some(entity_index) = entity_index {
+ local_searcher.set_entity_index(entity_index);
+ }
- let mut local_searcher = LocalSearcher::new(search_index);
+ if let Some(centrality_store) = centrality_store {
+ local_searcher.set_centrality_store(centrality_store);
+ }
- if let Some(entity_index) = entity_index {
- local_searcher.set_entity_index(entity_index);
+ if let Some(model_path) = config.linear_model_path {
+ local_searcher.set_linear_model(LinearRegression::open(model_path)?);
+ }
+
+ if let Some(model_path) = config.lambda_model_path {
+ local_searcher.set_lambda_model(LambdaMART::open(model_path)?);
+ }
+
+ local_searcher.set_collector_config(config.collector);
+ local_searcher.set_snippet_config(config.snippet);
+
+ let cluster_handle = Cluster::join(
+ Member {
+ id: config.cluster_id,
+ service: Service::Searcher {
+ host: config.host,
+ shard: config.shard_id,
+ },
+ },
+ config.gossip_addr,
+ config.gossip_seed_nodes.unwrap_or_default(),
+ )
+ .await?;
+
+ Ok(SearchService {
+ local_searcher,
+ cluster_handle,
+ })
}
+}
- if let Some(centrality_store) = centrality_store {
- local_searcher.set_centrality_store(centrality_store);
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct RetrieveWebsites {
+ pub websites: Vec<inverted_index::WebsitePointer>,
+ pub query: String,
+}
+#[async_trait::async_trait]
+impl sonic::service::Message<SearchService> for RetrieveWebsites {
+ type Response = Option<Vec<inverted_index::RetrievedWebpage>>;
+ async fn handle(self, server: &mut SearchService) -> sonic::Result<Self::Response> {
+ match server
+ .local_searcher
+ .retrieve_websites(&self.websites, &self.query)
+ {
+ Ok(response) => Ok(Some(response)),
+ Err(_) => Ok(None),
+ }
}
+}
- if let Some(model_path) = config.linear_model_path {
- local_searcher.set_linear_model(LinearRegression::open(model_path)?);
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Search {
+ pub query: SearchQuery,
+}
+#[async_trait::async_trait]
+impl sonic::service::Message<SearchService> for Search {
+ type Response = Option<InitialWebsiteResult>;
+ async fn handle(self, server: &mut SearchService) -> sonic::Result<Self::Response> {
+ match server.local_searcher.search_initial(&self.query, true) {
+ Ok(result) => Ok(Some(result)),
+ Err(_) => Ok(None),
+ }
}
+}
- if let Some(model_path) = config.lambda_model_path {
- local_searcher.set_lambda_model(LambdaMART::open(model_path)?);
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct GetWebpage {
+ pub url: String,
+}
+#[async_trait::async_trait]
+impl sonic::service::Message<SearchService> for GetWebpage {
+ type Response = Option<RetrievedWebpage>;
+ async fn handle(self, server: &mut SearchService) -> sonic::Result<Self::Response> {
+ Ok(server.local_searcher.get_webpage(&self.url))
}
+}
- local_searcher.set_collector_config(config.collector);
- local_searcher.set_snippet_config(config.snippet);
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct GetHomepageDescriptions {
+ pub urls: Vec<Url>,
+}
+#[async_trait::async_trait]
+impl sonic::service::Message<SearchService> for GetHomepageDescriptions {
+ type Response = HashMap<Url, String>;
+ async fn handle(self, server: &mut SearchService) -> sonic::Result<Self::Response> {
+ let mut result = HashMap::with_capacity(self.urls.len());
+
+ for url in &self.urls {
+ if let Some(homepage) = server.local_searcher.get_homepage(url) {
+ if let Some(desc) = homepage.description() {
+ result.insert(url.clone(), desc.clone());
+ }
+ }
+ }
- // dropping the handle leaves the cluster
- let _cluster_handle = Cluster::join(
- Member {
- id: config.cluster_id,
- service: Service::Searcher {
- host: config.host,
- shard: config.shard_id,
- },
- },
- config.gossip_addr,
- config.gossip_seed_nodes.unwrap_or_default(),
- )
- .await?;
+ Ok(result)
+ }
+}
+
+pub async fn run(config: config::SearchServerConfig) -> Result<()> {
+ let addr = config.host;
+ let mut server = SearchService::new(config).await?.bind(addr).await.unwrap();
info!("search server is ready to accept requests on {}", addr);
loop {
- if let Ok(req) = server.accept::<searcher::distributed::Request>().await {
- match &req.body {
- searcher::Request::RetrieveWebsites { websites, query } => {
- match local_searcher.retrieve_websites(websites, query) {
- Ok(response) => {
- req.respond(sonic::Response::Content(response)).await.ok();
- }
- Err(_) => {
- req.respond::<Vec<inverted_index::RetrievedWebpage>>(
- sonic::Response::Empty,
- )
- .await
- .ok();
- }
- }
- }
- searcher::Request::Search(query) => {
- match local_searcher.search_initial(query, true) {
- Ok(result) => {
- req.respond(sonic::Response::Content(result)).await.ok();
- }
- Err(_) => {
- req.respond::<inverted_index::SearchResult>(sonic::Response::Empty)
- .await
- .ok();
- }
- }
- }
- searcher::Request::GetWebpage { url } => {
- let result = local_searcher.get_webpage(url);
- req.respond(sonic::Response::Content(result)).await.ok();
- }
- searcher::Request::GetHomepageDescriptions { urls } => {
- let mut result = HashMap::with_capacity(urls.len());
-
- for url in urls {
- if let Some(homepage) = local_searcher.get_homepage(url) {
- if let Some(desc) = homepage.description() {
- result.insert(url.clone(), desc.clone());
- }
- }
- }
-
- req.respond(sonic::Response::Content(result)).await.ok();
- }
- }
- }
+ server.accept().await?;
}
}
diff --git a/core/src/entrypoint/webgraph_server.rs b/core/src/entrypoint/webgraph_server.rs
index c24e4f84..0ecd30e8 100644
--- a/core/src/entrypoint/webgraph_server.rs
+++ b/core/src/entrypoint/webgraph_server.rs
@@ -28,19 +28,15 @@ use crate::distributed::cluster::Cluster;
use crate::distributed::member::Member;
use crate::distributed::member::Service;
use crate::distributed::sonic;
+use crate::distributed::sonic::service::Message;
use crate::ranking::inbound_similarity::InboundSimilarity;
use crate::searcher::DistributedSearcher;
use crate::similar_sites::SimilarSitesFinder;
+use crate::sonic_service;
use crate::webgraph::Node;
use crate::webgraph::WebgraphBuilder;
use crate::Result;
-#[derive(Serialize, Deserialize)]
-pub enum Request {
- SimilarSites { sites: Vec<String>, top_n: usize },
- Knows { site: String },
-}
-
#[derive(serde::Serialize, serde::Deserialize)]
pub struct ScoredSite {
pub site: String,
@@ -50,6 +46,74 @@ pub struct ScoredSite {
const MAX_SITES: usize = 20;
+pub struct WebGraphService {
+ searcher: DistributedSearcher,
+ similar_sites_finder: SimilarSitesFinder,
+}
+
+sonic_service!(WebGraphService, [SimilarSites, Knows]);
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SimilarSites {
+ pub sites: Vec<String>,
+ pub top_n: usize,
+}
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Knows {
+ pub site: String,
+}
+
+#[async_trait::async_trait]
+impl Message<WebGraphService> for SimilarSites {
+ type Response = Vec<ScoredSite>;
+
+ async fn handle(self, server: &mut WebGraphService) -> sonic::Result<Self::Response> {
+ let sites = &self.sites[..std::cmp::min(self.sites.len(), MAX_SITES)];
+ let similar_sites = server
+ .similar_sites_finder
+ .find_similar_sites(sites, self.top_n);
+
+ let urls = similar_sites
+ .iter()
+ .map(|s| Url::parse(&("http://".to_string() + s.node.name.as_str())).unwrap())
+ .collect_vec();
+
+ let descriptions = server.searcher.get_homepage_descriptions(&urls).await;
+
+ let similar_sites = similar_sites
+ .into_iter()
+ .map(|site| {
+ let description = descriptions
+ .get(&Url::parse(&("http://".to_string() + site.node.name.as_str())).unwrap())
+ .cloned();
+
+ ScoredSite {
+ site: site.node.name,
+ score: site.score,
+ description,
+ }
+ })
+ .collect_vec();
+
+ Ok(similar_sites)
+ }
+}
+
+#[async_trait::async_trait]
+impl Message<WebGraphService> for Knows {
+ type Response = Option<Node>;
+
+ async fn handle(self, server: &mut WebGraphService) -> sonic::Result<Self::Response> {
+ let node = Node::from(self.site.to_string()).into_host();
+
+ if server.similar_sites_finder.knows_about(&node) {
+ Ok(Some(node))
+ } else {
+ Ok(None)
+ }
+ }
+}
+
pub async fn run(config: config::WebgraphServerConfig) -> Result<()> {
let addr: SocketAddr = config.host;
@@ -76,60 +140,17 @@ pub async fn run(config: config::WebgraphServerConfig) -> Result<()> {
config.max_similar_sites,
);
- let server = sonic::Server::bind(addr).await.unwrap();
+ let mut server = WebGraphService {
+ searcher,
+ similar_sites_finder,
+ }
+ .bind(addr)
+ .await
+ .unwrap();
info!("webgraph server is ready to accept requests on {}", addr);
loop {
- if let Ok(req) = server.accept::<Request>().await {
- match &req.body {
- Request::SimilarSites { sites, top_n } => {
- let sites = &sites[..std::cmp::min(sites.len(), MAX_SITES)];
- let similar_sites = similar_sites_finder.find_similar_sites(sites, *top_n);
-
- let urls = similar_sites
- .iter()
- .map(|s| {
- Url::parse(&("http://".to_string() + s.node.name.as_str())).unwrap()
- })
- .collect_vec();
-
- let descriptions = searcher.get_homepage_descriptions(&urls).await;
-
- let similar_sites = similar_sites
- .into_iter()
- .map(|site| {
- let description = descriptions
- .get(
- &Url::parse(&("http://".to_string() + site.node.name.as_str()))
- .unwrap(),
- )
- .cloned();
-
- ScoredSite {
- site: site.node.name,
- score: site.score,
- description,
- }
- })
- .collect_vec();
-
- req.respond(sonic::Response::Content(similar_sites))
- .await
- .ok();
- }
- Request::Knows { site } => {
- let node = Node::from(site.to_string()).into_host();
-
- if similar_sites_finder.knows_about(&node) {
- req.respond(sonic::Response::Content(Some(node))).await.ok();
- } else {
- req.respond::<Option<Node>>(sonic::Response::Content(None))
- .await
- .ok();
- }
- }
- }
- }
+ let _ = server.accept().await;
}
}
diff --git a/core/src/inverted_index.rs b/core/src/inverted_index.rs
index 00d36a5e..4d32ac79 100644
--- a/core/src/inverted_index.rs
+++ b/core/src/inverted_index.rs
@@ -501,7 +501,7 @@ pub struct SearchResult {
pub documents: Vec<RetrievedWebpage>,
}
-#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RetrievedWebpage {
pub title: String,
pub url: String,
diff --git a/core/src/lib.rs b/core/src/lib.rs
index 0074590e..b2cd7e08 100644
--- a/core/src/lib.rs
+++ b/core/src/lib.rs
@@ -111,7 +111,7 @@ pub enum Error {
UnknownRobotsMetaTag,
}
-pub(crate) type Result<T> = std::result::Result<T, anyhow::Error>;
+pub(crate) type Result<T, E = anyhow::Error> = std::result::Result<T, E>;
// taken from https://docs.rs/sled/0.34.7/src/sled/config.rs.html#445
pub fn gen_temp_path() -> PathBuf {
diff --git a/core/src/mapreduce/manager.rs b/core/src/mapreduce/manager.rs
index 96f88f0b..2ebb3326 100644
--- a/core/src/mapreduce/manager.rs
+++ b/core/src/mapreduce/manager.rs
@@ -1,7 +1,6 @@
-use super::{Error, Result, Worker};
+use super::{Error, MapReduceConnection, Result, Worker};
use super::{Map, Reduce};
use crate::distributed::retry_strategy::ExponentialBackoff;
-use crate::distributed::sonic;
use crate::mapreduce::Task;
use futures::StreamExt;
use itertools::Itertools;
@@ -28,9 +27,14 @@ impl RemoteWorker {
.take(15)
}
- async fn connect(&self) -> Result<sonic::Connection> {
+ async fn connect<W, I, O>(&self) -> Result<MapReduceConnection<I, O>>
+ where
+ W: Worker,
+ I: Map<W, O> + Send,
+ O: Serialize + DeserializeOwned + Send,
+ {
for dur in RemoteWorker::retry_strategy() {
- if let Ok(conn) = sonic::Connection::create(self.addr).await {
+ if let Ok(conn) = MapReduceConnection::create(self.addr).await {
debug!("connected");
return Ok(conn);
}
@@ -41,15 +45,15 @@ impl RemoteWorker {
Err(Error::NoResponse)
}
- async fn perform<W, I, O>(&self, job: &I) -> Result<O>
+ async fn perform<W, I, O>(&self, job: I) -> Result<O>
where
W: Worker,
I: Map<W, O> + Send,
O: Serialize + DeserializeOwned + Send,
{
- let conn = self.connect().await?;
+ let conn = self.connect::<W, I, O>().await?;
match conn.send(&Task::Job(job)).await {
- Ok(sonic::Response::Content(res)) => Ok(res),
+ Ok(Some(res)) => Ok(res),
_ => Err(Error::NoResponse),
}
}
@@ -62,9 +66,9 @@ impl RemoteWorker {
{
debug!("closing worker {:}", self.addr);
let conn = self.connect().await?;
- let res: sonic::Response<O> = conn.send(&Task::<I>::AllFinished).await?;
+ let res = conn.send(&Task::<I>::AllFinished).await?;
- debug_assert!(matches!(res, sonic::Response::Empty));
+ debug_assert!(res.is_none());
Ok(())
}
@@ -195,13 +199,13 @@ impl Manager {
async fn try_map<W, I, O>(&self, job: &I) -> Result<O>
where
W: Worker,
- I: Map<W, O> + Send,
+ I: Map<W, O> + Send + Clone,
O: Serialize + DeserializeOwned + Send,
{
loop {
match self.pool.get_worker().await? {
Some(worker) => {
- let res = worker.perform(job).await?;
+ let res = worker.perform(job.clone()).await?;
worker.success().await;
return Ok(res);
@@ -216,7 +220,7 @@ impl Manager {
pub async fn map<W, I, O>(&self, job: I) -> O
where
W: Worker,
- I: Map<W, O> + Send,
+ I: Map<W, O> + Send + Clone,
O: Serialize + DeserializeOwned + Send,
{
loop {
@@ -246,7 +250,7 @@ impl Manager {
async fn get_results<W, I, O1, O2>(&self, jobs: impl Iterator<Item = I> + Send) -> Option<O2>
where
W: Worker,
- I: Map<W, O1> + Send,
+ I: Map<W, O1> + Send + Clone,
O1: Serialize + DeserializeOwned + Send,
O2: From<O1> + Reduce<O1> + Send + Reduce<O2>,
{
@@ -270,7 +274,7 @@ impl Manager {
pub async fn run<W, I, O1, O2>(self, jobs: impl Iterator<Item = I> + Send) -> Option<O2>
where
W: Worker,
- I: Map<W, O1> + Send,
+ I: Map<W, O1> + Send + Clone,
O1: Serialize + DeserializeOwned + Send,
O2: From<O1> + Reduce<O1> + Send + Reduce<O2>,
{
diff --git a/core/src/mapreduce/mod.rs b/core/src/mapreduce/mod.rs
index b9f1ba8a..9069c1ed 100644
--- a/core/src/mapreduce/mod.rs
+++ b/core/src/mapreduce/mod.rs
@@ -62,3 +62,6 @@ enum Task<T> {
Job(T),
AllFinished,
}
+
+type MapReduceServer<I, O> = sonic::Server<Task<I>, Option<O>>;
+type MapReduceConnection<I, O> = sonic::Connection<Task<I>, Option<O>>;
diff --git a/core/src/mapreduce/worker.rs b/core/src/mapreduce/worker.rs
index fd4ff2f1..46fad548 100644
--- a/core/src/mapreduce/worker.rs
+++ b/core/src/mapreduce/worker.rs
@@ -16,7 +16,7 @@
use std::net::SocketAddr;
-use crate::distributed::sonic;
+use crate::mapreduce::MapReduceServer;
use super::{Map, Result, Task};
use async_trait::async_trait;
@@ -32,22 +32,22 @@ pub trait Worker {
where
Self: Sized,
I: Map<Self, O> + Send + Sync,
- O: Serialize + DeserializeOwned + Send,
+ O: Serialize + DeserializeOwned + Send + Sync,
{
- let server = sonic::Server::bind(addr).await?;
+ let server = MapReduceServer::<I, O>::bind(addr).await?;
info!("worker listening on: {:}", addr);
loop {
- let req: sonic::Request<Task<I>> = server.accept().await?;
+ let req = server.accept().await?;
debug!("received request");
- match &req.body {
+ match req.body() {
Task::Job(job) => {
debug!("request is a job");
let res = job.map(self);
- req.respond(sonic::Response::Content(res)).await?;
+ req.respond(Some(res)).await?;
}
Task::AllFinished => {
- req.respond::<Task<I>>(sonic::Response::Empty).await?;
+ req.respond(None).await?;
break;
}
}
diff --git a/core/src/searcher/distributed.rs b/core/src/searcher/distributed.rs
index 24fcef4c..3b3695bd 100644
--- a/core/src/searcher/distributed.rs
+++ b/core/src/searcher/distributed.rs
@@ -16,6 +16,7 @@
use crate::{
distributed::{cluster::Cluster, member::Service, retry_strategy::ExponentialBackoff},
+ entrypoint::search_server::{self, SearchService},
inverted_index::{self, RetrievedWebpage},
ranking::pipeline::{AsRankingWebsite, RankingWebsite},
Result,
@@ -54,10 +55,15 @@ pub enum Error {
impl RemoteSearcher {
async fn search(&self, query: &SearchQuery) -> Result<InitialWebsiteResult> {
- let mut conn = self.conn();
+ let conn = self.conn();
- if let Ok(sonic::Response::Content(body)) = conn
- .send_with_timeout(&Request::Search(query.clone()), Duration::from_secs(1))
+ if let Ok(Some(body)) = conn
+ .send_with_timeout(
+ &search_server::Search {
+ query: query.clone(),
+ },
+ Duration::from_secs(1),
+ )
.await
{
return Ok(body);
@@ -71,11 +77,11 @@ impl RemoteSearcher {
pointers: &[inverted_index::WebsitePointer],
original_query: &str,
) -> Result<Vec<RetrievedWebpage>> {
- let mut conn = self.conn();
+ let conn = self.conn();
- if let Ok(sonic::Response::Content(body)) = conn
+ if let Ok(Some(body)) = conn
.send_with_timeout(
- &Request::RetrieveWebsites {
+ &search_server::RetrieveWebsites {
websites: pointers.to_vec(),
query: original_query.to_string(),
},
@@ -89,11 +95,11 @@ impl RemoteSearcher {
}
async fn get_webpage(&self, url: &str) -> Result<Option<RetrievedWebpage>> {
- let mut conn = self.conn();
+ let conn = self.conn();
- if let Ok(sonic::Response::Content(body)) = conn
+ if let Ok(body) = conn
.send_with_timeout(
- &Request::GetWebpage {
+ &search_server::GetWebpage {
url: url.to_string(),
},
Duration::from_secs(1),
@@ -107,11 +113,11 @@ impl RemoteSearcher {
}
async fn get_homepage_descriptions(&self, urls: &[Url]) -> HashMap<Url, String> {
- let mut conn = self.conn();
+ let conn = self.conn();
- if let Ok(sonic::Response::Content(body)) = conn
+ if let Ok(body) = conn
.send_with_timeout(
- &Request::GetHomepageDescriptions {
+ &search_server::GetHomepageDescriptions {
urls: urls.to_vec(),
},
Duration::from_secs(1),
@@ -124,12 +130,14 @@ impl RemoteSearcher {
HashMap::new()
}
- fn conn(&self) -> sonic::ResilientConnection<impl Iterator<Item = Duration>> {
+ fn conn(
+ &self,
+ ) -> sonic::service::ResilientConnection<SearchService, impl Iterator<Item = Duration>> {
let retry = ExponentialBackoff::from_millis(30)
.with_limit(Duration::from_millis(200))
.take(5);
- sonic::ResilientConnection::create(self.addr, retry)
+ sonic::service::ResilientConnection::create(self.addr, retry)
}
}
@@ -213,21 +221,6 @@ pub struct InitialSearchResultShard {
pub shard: ShardId,
}
-#[derive(Serialize, Deserialize)]
-pub enum Request {
- Search(SearchQuery),
- RetrieveWebsites {
- websites: Vec<inverted_index::WebsitePointer>,
- query: String,
- },
- GetWebpage {
- url: String,
- },
- GetHomepageDescriptions {
- urls: Vec<Url>,
- },
-}
-
#[derive(Clone, Debug)]
pub struct ScoredWebsitePointer {
pub website: RankingWebsite,
diff --git a/core/src/searcher/mod.rs b/core/src/searcher/mod.rs
index 8d65a7e9..81ab2500 100644
--- a/core/src/searcher/mod.rs
+++ b/core/src/searcher/mod.rs
@@ -66,7 +66,7 @@ pub struct SearchQuery {
pub return_ranking_signals: bool,
}
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InitialWebsiteResult {
pub spell_corrected_query: Option<Correction>,
pub num_websites: usize,