WIP: Get compiling with Tokio by commenting almost everything

Co-Authored-By: Antonio Scandurra <me@as-cii.com>
This commit is contained in:
Nathan Sobo 2022-04-22 13:33:19 -06:00
parent 53bf7b61c0
commit 447c1d2f71
8 changed files with 6860 additions and 6914 deletions

456
Cargo.lock generated
View File

@ -97,21 +97,6 @@ dependencies = [
"memchr",
]
[[package]]
name = "alloc-no-stdlib"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5192ec435945d87bc2f70992b4d818154b5feede43c09fb7592146374eac90a6"
[[package]]
name = "alloc-stdlib"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "697ed7edc0f1711de49ce108c541623a0af97c6c60b2f6e2b65229847ac843c2"
dependencies = [
"alloc-no-stdlib",
]
[[package]]
name = "ansi_term"
version = "0.11.0"
@ -160,16 +145,6 @@ dependencies = [
"rust-embed",
]
[[package]]
name = "async-attributes"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a3203e79f4dd9bdda415ed03cf14dae5a2bf775c683a00f94e9cd1faf0f596e5"
dependencies = [
"quote",
"syn",
]
[[package]]
name = "async-broadcast"
version = "0.3.4"
@ -198,7 +173,6 @@ version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5443ccbb270374a2b1055fc72da40e1f237809cd6bb0e97e66d264cd138473a6"
dependencies = [
"brotli",
"flate2",
"futures-core",
"futures-io",
@ -206,16 +180,6 @@ dependencies = [
"pin-project-lite 0.2.4",
]
[[package]]
name = "async-dup"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7427a12b8dc09291528cfb1da2447059adb4a257388c2acd6497a79d55cf6f7c"
dependencies = [
"futures-io",
"simple-mutex",
]
[[package]]
name = "async-executor"
version = "1.4.0"
@ -257,24 +221,6 @@ dependencies = [
"once_cell",
]
[[package]]
name = "async-h1"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc5142de15b549749cce62923a50714b0d7b77f5090ced141599e78899865451"
dependencies = [
"async-channel",
"async-dup",
"async-std",
"byte-pool",
"futures-core",
"http-types",
"httparse",
"lazy_static",
"log",
"pin-project",
]
[[package]]
name = "async-io"
version = "1.3.1"
@ -372,48 +318,12 @@ dependencies = [
"webpki",
]
[[package]]
name = "async-session"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "345022a2eed092cd105cc1b26fd61c341e100bd5fcbbd792df4baf31c2cc631f"
dependencies = [
"anyhow",
"async-std",
"async-trait",
"base64 0.12.3",
"bincode",
"blake3",
"chrono",
"hmac 0.8.1",
"kv-log-macro",
"rand 0.7.3",
"serde",
"serde_json",
"sha2 0.9.5",
]
[[package]]
name = "async-sse"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53bba003996b8fd22245cd0c59b869ba764188ed435392cf2796d03b805ade10"
dependencies = [
"async-channel",
"async-std",
"http-types",
"log",
"memchr",
"pin-project-lite 0.1.12",
]
[[package]]
name = "async-std"
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9f06685bad74e0570f5213741bea82158279a4103d988e57bfada11ad230341"
dependencies = [
"async-attributes",
"async-channel",
"async-global-executor",
"async-io",
@ -476,7 +386,7 @@ dependencies = [
"futures-util",
"log",
"pin-project-lite 0.2.4",
"tungstenite",
"tungstenite 0.16.0",
]
[[package]]
@ -634,21 +544,6 @@ dependencies = [
"wyz",
]
[[package]]
name = "blake3"
version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b64485778c4f16a6a5a9d335e80d449ac6c70cdd6a06d2af18a6f6f775a125b3"
dependencies = [
"arrayref",
"arrayvec 0.5.2",
"cc",
"cfg-if 0.1.10",
"constant_time_eq",
"crypto-mac 0.8.0",
"digest 0.9.0",
]
[[package]]
name = "block"
version = "0.1.6"
@ -702,27 +597,6 @@ dependencies = [
"workspace",
]
[[package]]
name = "brotli"
version = "3.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f29919120f08613aadcd4383764e00526fc9f18b6c0895814faeed0dd78613e"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
"brotli-decompressor",
]
[[package]]
name = "brotli-decompressor"
version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1052e1c3b8d4d80eb84a8b94f0a1498797b5fb96314c001156a1c761940ef4ec"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
]
[[package]]
name = "bstr"
version = "0.2.15"
@ -744,16 +618,6 @@ version = "3.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c59e7af012c713f529e7a3ee57ce9b31ddd858d4b512923602f74608b009631"
[[package]]
name = "byte-pool"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8c7230ddbb427b1094d477d821a99f3f54d36333178eeb806e279bcdcecf0ca"
dependencies = [
"crossbeam-queue",
"stable_deref_trait",
]
[[package]]
name = "bytemuck"
version = "1.5.1"
@ -838,7 +702,6 @@ dependencies = [
"libc",
"num-integer",
"num-traits",
"serde",
"time 0.1.44",
"winapi 0.3.9",
]
@ -1012,8 +875,6 @@ name = "collab"
version = "0.1.0"
dependencies = [
"anyhow",
"async-io",
"async-std",
"async-trait",
"async-tungstenite",
"base64 0.13.0",
@ -1025,6 +886,7 @@ dependencies = [
"envy",
"futures",
"gpui",
"hyper",
"json_env_logger",
"language",
"lazy_static",
@ -1039,13 +901,12 @@ dependencies = [
"serde",
"serde_json",
"settings",
"sha-1",
"sha-1 0.9.6",
"sqlx",
"surf",
"theme",
"tide",
"tide-compress",
"time 0.2.27",
"tokio",
"tokio-tungstenite",
"toml",
"util",
"workspace",
@ -1096,12 +957,6 @@ version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f92cfa0fd5690b3cf8c1ef2cabbd9b7ef22fa53cf5e1f92b05103f6d5d1cf6e7"
[[package]]
name = "constant_time_eq"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc"
[[package]]
name = "contacts_panel"
version = "0.1.0"
@ -1319,16 +1174,6 @@ dependencies = [
"typenum",
]
[[package]]
name = "crypto-mac"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b584a330336237c1eecd3e94266efb216c56ed91225d634cb2991c5f3fd1aeab"
dependencies = [
"generic-array",
"subtle",
]
[[package]]
name = "crypto-mac"
version = "0.10.0"
@ -1713,22 +1558,6 @@ dependencies = [
"instant",
]
[[package]]
name = "femme"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af1a24f391a5a94d756db5092c6576aad494b88a71a5a36b20c67b63e0df034"
dependencies = [
"cfg-if 0.1.10",
"js-sys",
"log",
"serde",
"serde_derive",
"serde_json",
"wasm-bindgen",
"web-sys",
]
[[package]]
name = "file_finder"
version = "0.1.0"
@ -2215,6 +2044,25 @@ dependencies = [
"syn",
]
[[package]]
name = "h2"
version = "0.3.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37a82c6d637fc9515a4694bbf1cb2457b79d81ce52b3108bdeea58b07dd34a57"
dependencies = [
"bytes 1.0.1",
"fnv",
"futures-core",
"futures-sink",
"futures-util",
"http",
"indexmap",
"slab",
"tokio",
"tokio-util",
"tracing",
]
[[package]]
name = "hashbrown"
version = "0.9.1"
@ -2279,16 +2127,6 @@ dependencies = [
"hmac 0.10.1",
]
[[package]]
name = "hmac"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "126888268dcc288495a26bf004b38c5fdbb31682f992c84ceb046a1f0fe38840"
dependencies = [
"crypto-mac 0.8.0",
"digest 0.9.0",
]
[[package]]
name = "hmac"
version = "0.10.1"
@ -2329,6 +2167,17 @@ dependencies = [
"base64 0.12.3",
]
[[package]]
name = "http-body"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ff4f84919677303da5f147645dbea6b1881f368d03ac84e1dc09031ebd7b2c6"
dependencies = [
"bytes 1.0.1",
"http",
"pin-project-lite 0.2.4",
]
[[package]]
name = "http-client"
version = "6.4.1"
@ -2372,12 +2221,42 @@ version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3a87b616e37e93c22fb19bcd386f02f3af5ea98a25670ad0fce773de23c5e68"
[[package]]
name = "httpdate"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421"
[[package]]
name = "humantime"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
[[package]]
name = "hyper"
version = "0.14.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b61cf2d1aebcf6e6352c97b81dc2244ca29194be1b276f5d8ad5c6330fffb11"
dependencies = [
"bytes 1.0.1",
"futures-channel",
"futures-core",
"futures-util",
"h2",
"http",
"http-body",
"httparse",
"httpdate",
"itoa 0.4.7",
"pin-project-lite 0.2.4",
"socket2 0.4.0",
"tokio",
"tower-service",
"tracing",
"want",
]
[[package]]
name = "idna"
version = "0.2.3"
@ -2480,7 +2359,7 @@ dependencies = [
"fnv",
"lazy_static",
"libc",
"mio",
"mio 0.6.23",
"rand 0.7.3",
"serde",
"tempfile",
@ -2955,12 +2834,25 @@ dependencies = [
"kernel32-sys",
"libc",
"log",
"miow",
"miow 0.2.2",
"net2",
"slab",
"winapi 0.2.8",
]
[[package]]
name = "mio"
version = "0.7.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8067b404fe97c70829f082dec8bcf4f71225d7eaea1d8645349cb76fa06205cc"
dependencies = [
"libc",
"log",
"miow 0.3.7",
"ntapi",
"winapi 0.3.9",
]
[[package]]
name = "miow"
version = "0.2.2"
@ -2973,6 +2865,15 @@ dependencies = [
"ws2_32-sys",
]
[[package]]
name = "miow"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9f1c5b025cda876f66ef43a113f91ebc9f4ccef34843000e0adf6ebbab84e21"
dependencies = [
"winapi 0.3.9",
]
[[package]]
name = "multimap"
version = "0.8.3"
@ -3023,6 +2924,15 @@ dependencies = [
"version_check",
]
[[package]]
name = "ntapi"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c28774a7fd2fbb4f0babd8237ce554b73af68021b5f695a3cebd6c59bac0980f"
dependencies = [
"winapi 0.3.9",
]
[[package]]
name = "num-bigint"
version = "0.4.0"
@ -3882,12 +3792,6 @@ dependencies = [
"winapi 0.3.9",
]
[[package]]
name = "route-recognizer"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56770675ebc04927ded3e60633437841581c285dc6236109ea25fbf3beb7b59e"
[[package]]
name = "roxmltree"
version = "0.14.1"
@ -4333,6 +4237,17 @@ dependencies = [
"opaque-debug",
]
[[package]]
name = "sha-1"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "028f48d513f9678cda28f6e4064755b3fbb2af6acd672f2c209b62323f7aea0f"
dependencies = [
"cfg-if 1.0.0",
"cpufeatures 0.2.1",
"digest 0.10.3",
]
[[package]]
name = "sha1"
version = "0.6.0"
@ -4394,15 +4309,6 @@ version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ad1d488a557b235fc46dae55512ffbfc429d2482b08b4d9435ab07384ca8aec"
[[package]]
name = "simple-mutex"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38aabbeafa6f6dead8cebf246fe9fae1f9215c8d29b3a69f93bd62a9e4a3dcd6"
dependencies = [
"event-listener",
]
[[package]]
name = "simple_asn1"
version = "0.5.3"
@ -4595,7 +4501,7 @@ dependencies = [
"rustls",
"serde",
"serde_json",
"sha-1",
"sha-1 0.9.6",
"sha2 0.9.5",
"smallvec",
"sqlformat",
@ -4640,12 +4546,6 @@ dependencies = [
"async-std",
]
[[package]]
name = "stable_deref_trait"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"
[[package]]
name = "standback"
version = "0.2.17"
@ -4970,41 +4870,6 @@ dependencies = [
"once_cell",
]
[[package]]
name = "tide"
version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c459573f0dd2cc734b539047f57489ea875af8ee950860ded20cf93a79a1dee0"
dependencies = [
"async-h1",
"async-session",
"async-sse",
"async-std",
"async-trait",
"femme",
"futures-util",
"http-client",
"http-types",
"kv-log-macro",
"log",
"pin-project-lite 0.2.4",
"route-recognizer",
"serde",
"serde_json",
]
[[package]]
name = "tide-compress"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d59e3885ecbc547a611d81e501b51bb5f52abd44c3eb3b733ac3c44ff2f2619"
dependencies = [
"async-compression",
"futures-lite",
"http-types",
"tide",
]
[[package]]
name = "tiff"
version = "0.6.1"
@ -5118,6 +4983,62 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c"
[[package]]
name = "tokio"
version = "1.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c27a64b625de6d309e8c57716ba93021dccf1b3b5c97edd6d3dd2d2135afc0a"
dependencies = [
"bytes 1.0.1",
"libc",
"memchr",
"mio 0.7.14",
"num_cpus",
"once_cell",
"parking_lot",
"pin-project-lite 0.2.4",
"signal-hook-registry",
"tokio-macros",
"winapi 0.3.9",
]
[[package]]
name = "tokio-macros"
version = "1.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b557f72f448c511a979e2564e55d74e6c4432fc96ff4f6241bc6bded342643b7"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tokio-tungstenite"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06cda1232a49558c46f8a504d5b93101d42c0bf7f911f12a105ba48168f821ae"
dependencies = [
"futures-util",
"log",
"tokio",
"tungstenite 0.17.2",
]
[[package]]
name = "tokio-util"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0edfdeb067411dba2044da6d1cb2df793dd35add7888d73c16e3381ded401764"
dependencies = [
"bytes 1.0.1",
"futures-core",
"futures-sink",
"pin-project-lite 0.2.4",
"tokio",
"tracing",
]
[[package]]
name = "toml"
version = "0.5.8"
@ -5127,6 +5048,12 @@ dependencies = [
"serde",
]
[[package]]
name = "tower-service"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "360dfd1d6d30e05fda32ace2c8c70e9c0a9da713275777f5a4dbb8a1893930c6"
[[package]]
name = "tracing"
version = "0.1.26"
@ -5247,6 +5174,12 @@ dependencies = [
"tree-sitter",
]
[[package]]
name = "try-lock"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642"
[[package]]
name = "ttf-parser"
version = "0.9.0"
@ -5272,7 +5205,26 @@ dependencies = [
"httparse",
"log",
"rand 0.8.3",
"sha-1",
"sha-1 0.9.6",
"thiserror",
"url",
"utf-8",
]
[[package]]
name = "tungstenite"
version = "0.17.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d96a2dea40e7570482f28eb57afbe42d97551905da6a9400acc5c328d24004f5"
dependencies = [
"base64 0.13.0",
"byteorder",
"bytes 1.0.1",
"http",
"httparse",
"log",
"rand 0.8.3",
"sha-1 0.10.0",
"thiserror",
"url",
"utf-8",
@ -5528,6 +5480,16 @@ dependencies = [
"winapi-util",
]
[[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"
@ -5547,8 +5509,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d54ee1d4ed486f78874278e63e4069fc1ab9f6a18ca492076ffb90c5eb2997fd"
dependencies = [
"cfg-if 1.0.0",
"serde",
"serde_json",
"wasm-bindgen-macro",
]

View File

@ -16,14 +16,15 @@ required-features = ["seed-support"]
collections = { path = "../collections" }
rpc = { path = "../rpc" }
util = { path = "../util" }
anyhow = "1.0.40"
async-io = "1.3"
async-std = { version = "1.8.0", features = ["attributes"] }
async-trait = "0.1.50"
async-tungstenite = "0.16"
base64 = "0.13"
envy = "0.4.2"
env_logger = "0.8"
futures = "0.3"
hyper = { version = "0.14", features = ["full"] }
json_env_logger = "0.1"
lipsum = { version = "0.8", optional = true }
log = { version = "0.4.16", features = ["kv_unstable_serde"] }
@ -33,9 +34,8 @@ scrypt = "0.7"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sha-1 = "0.9"
surf = "2.2.0"
tide = "0.16.0"
tide-compress = "0.9.0"
tokio = { version = "1", features = ["full"] }
tokio-tungstenite = "0.17"
time = "0.2"
toml = "0.5.8"

View File

@ -1,179 +1,179 @@
use crate::{auth, db::UserId, AppState, Request, RequestExt as _};
// use crate::{auth, db::UserId, AppState, Request, RequestExt as _};
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::json;
use std::sync::Arc;
use surf::StatusCode;
// use surf::StatusCode;
pub fn add_routes(app: &mut tide::Server<Arc<AppState>>) {
app.at("/users").get(get_users);
app.at("/users").post(create_user);
app.at("/users/:id").put(update_user);
app.at("/users/:id").delete(destroy_user);
app.at("/users/:github_login").get(get_user);
app.at("/users/:github_login/access_tokens")
.post(create_access_token);
}
// pub fn add_routes(app: &mut tide::Server<Arc<AppState>>) {
// app.at("/users").get(get_users);
// app.at("/users").post(create_user);
// app.at("/users/:id").put(update_user);
// app.at("/users/:id").delete(destroy_user);
// app.at("/users/:github_login").get(get_user);
// app.at("/users/:github_login/access_tokens")
// .post(create_access_token);
// }
async fn get_user(request: Request) -> tide::Result {
request.require_token().await?;
// async fn get_user(request: Request) -> tide::Result {
// request.require_token().await?;
let user = request
.db()
.get_user_by_github_login(request.param("github_login")?)
.await?
.ok_or_else(|| surf::Error::from_str(404, "user not found"))?;
// let user = request
// .db()
// .get_user_by_github_login(request.param("github_login")?)
// .await?
// .ok_or_else(|| surf::Error::from_str(404, "user not found"))?;
Ok(tide::Response::builder(StatusCode::Ok)
.body(tide::Body::from_json(&user)?)
.build())
}
// Ok(tide::Response::builder(StatusCode::Ok)
// .body(tide::Body::from_json(&user)?)
// .build())
// }
async fn get_users(request: Request) -> tide::Result {
request.require_token().await?;
// async fn get_users(request: Request) -> tide::Result {
// request.require_token().await?;
let users = request.db().get_all_users().await?;
// let users = request.db().get_all_users().await?;
Ok(tide::Response::builder(StatusCode::Ok)
.body(tide::Body::from_json(&users)?)
.build())
}
// Ok(tide::Response::builder(StatusCode::Ok)
// .body(tide::Body::from_json(&users)?)
// .build())
// }
async fn create_user(mut request: Request) -> tide::Result {
request.require_token().await?;
// async fn create_user(mut request: Request) -> tide::Result {
// request.require_token().await?;
#[derive(Deserialize)]
struct Params {
github_login: String,
admin: bool,
}
let params = request.body_json::<Params>().await?;
// #[derive(Deserialize)]
// struct Params {
// github_login: String,
// admin: bool,
// }
// let params = request.body_json::<Params>().await?;
let user_id = request
.db()
.create_user(&params.github_login, params.admin)
.await?;
// let user_id = request
// .db()
// .create_user(&params.github_login, params.admin)
// .await?;
let user = request.db().get_user_by_id(user_id).await?.ok_or_else(|| {
surf::Error::from_str(
StatusCode::InternalServerError,
"couldn't find the user we just created",
)
})?;
// let user = request.db().get_user_by_id(user_id).await?.ok_or_else(|| {
// surf::Error::from_str(
// StatusCode::InternalServerError,
// "couldn't find the user we just created",
// )
// })?;
Ok(tide::Response::builder(StatusCode::Ok)
.body(tide::Body::from_json(&user)?)
.build())
}
// Ok(tide::Response::builder(StatusCode::Ok)
// .body(tide::Body::from_json(&user)?)
// .build())
// }
async fn update_user(mut request: Request) -> tide::Result {
request.require_token().await?;
// async fn update_user(mut request: Request) -> tide::Result {
// request.require_token().await?;
#[derive(Deserialize)]
struct Params {
admin: bool,
}
let user_id = UserId(
request
.param("id")?
.parse::<i32>()
.map_err(|error| surf::Error::from_str(StatusCode::BadRequest, error.to_string()))?,
);
let params = request.body_json::<Params>().await?;
// #[derive(Deserialize)]
// struct Params {
// admin: bool,
// }
// let user_id = UserId(
// request
// .param("id")?
// .parse::<i32>()
// .map_err(|error| surf::Error::from_str(StatusCode::BadRequest, error.to_string()))?,
// );
// let params = request.body_json::<Params>().await?;
request
.db()
.set_user_is_admin(user_id, params.admin)
.await?;
// request
// .db()
// .set_user_is_admin(user_id, params.admin)
// .await?;
Ok(tide::Response::builder(StatusCode::Ok).build())
}
// Ok(tide::Response::builder(StatusCode::Ok).build())
// }
async fn destroy_user(request: Request) -> tide::Result {
request.require_token().await?;
let user_id = UserId(
request
.param("id")?
.parse::<i32>()
.map_err(|error| surf::Error::from_str(StatusCode::BadRequest, error.to_string()))?,
);
// async fn destroy_user(request: Request) -> tide::Result {
// request.require_token().await?;
// let user_id = UserId(
// request
// .param("id")?
// .parse::<i32>()
// .map_err(|error| surf::Error::from_str(StatusCode::BadRequest, error.to_string()))?,
// );
request.db().destroy_user(user_id).await?;
// request.db().destroy_user(user_id).await?;
Ok(tide::Response::builder(StatusCode::Ok).build())
}
// Ok(tide::Response::builder(StatusCode::Ok).build())
// }
async fn create_access_token(request: Request) -> tide::Result {
request.require_token().await?;
// async fn create_access_token(request: Request) -> tide::Result {
// request.require_token().await?;
let user = request
.db()
.get_user_by_github_login(request.param("github_login")?)
.await?
.ok_or_else(|| surf::Error::from_str(StatusCode::NotFound, "user not found"))?;
// let user = request
// .db()
// .get_user_by_github_login(request.param("github_login")?)
// .await?
// .ok_or_else(|| surf::Error::from_str(StatusCode::NotFound, "user not found"))?;
#[derive(Deserialize)]
struct QueryParams {
public_key: String,
impersonate: Option<String>,
}
// #[derive(Deserialize)]
// struct QueryParams {
// public_key: String,
// impersonate: Option<String>,
// }
let query_params: QueryParams = request.query().map_err(|_| {
surf::Error::from_str(StatusCode::UnprocessableEntity, "invalid query params")
})?;
// let query_params: QueryParams = request.query().map_err(|_| {
// surf::Error::from_str(StatusCode::UnprocessableEntity, "invalid query params")
// })?;
let mut user_id = user.id;
if let Some(impersonate) = query_params.impersonate {
if user.admin {
if let Some(impersonated_user) =
request.db().get_user_by_github_login(&impersonate).await?
{
user_id = impersonated_user.id;
} else {
return Ok(tide::Response::builder(StatusCode::UnprocessableEntity)
.body(format!(
"Can't impersonate non-existent user {}",
impersonate
))
.build());
}
} else {
return Ok(tide::Response::builder(StatusCode::Unauthorized)
.body(format!(
"Can't impersonate user {} because the real user isn't an admin",
impersonate
))
.build());
}
}
// let mut user_id = user.id;
// if let Some(impersonate) = query_params.impersonate {
// if user.admin {
// if let Some(impersonated_user) =
// request.db().get_user_by_github_login(&impersonate).await?
// {
// user_id = impersonated_user.id;
// } else {
// return Ok(tide::Response::builder(StatusCode::UnprocessableEntity)
// .body(format!(
// "Can't impersonate non-existent user {}",
// impersonate
// ))
// .build());
// }
// } else {
// return Ok(tide::Response::builder(StatusCode::Unauthorized)
// .body(format!(
// "Can't impersonate user {} because the real user isn't an admin",
// impersonate
// ))
// .build());
// }
// }
let access_token = auth::create_access_token(request.db().as_ref(), user_id).await?;
let encrypted_access_token =
auth::encrypt_access_token(&access_token, query_params.public_key.clone())?;
// let access_token = auth::create_access_token(request.db().as_ref(), user_id).await?;
// let encrypted_access_token =
// auth::encrypt_access_token(&access_token, query_params.public_key.clone())?;
Ok(tide::Response::builder(StatusCode::Ok)
.body(json!({"user_id": user_id, "encrypted_access_token": encrypted_access_token}))
.build())
}
// Ok(tide::Response::builder(StatusCode::Ok)
// .body(json!({"user_id": user_id, "encrypted_access_token": encrypted_access_token}))
// .build())
// }
#[async_trait]
pub trait RequestExt {
async fn require_token(&self) -> tide::Result<()>;
}
// #[async_trait]
// pub trait RequestExt {
// async fn require_token(&self) -> tide::Result<()>;
// }
#[async_trait]
impl RequestExt for Request {
async fn require_token(&self) -> tide::Result<()> {
let token = self
.header("Authorization")
.and_then(|header| header.get(0))
.and_then(|header| header.as_str().strip_prefix("token "))
.ok_or_else(|| surf::Error::from_str(403, "invalid authorization header"))?;
// #[async_trait]
// impl RequestExt for Request {
// async fn require_token(&self) -> tide::Result<()> {
// let token = self
// .header("Authorization")
// .and_then(|header| header.get(0))
// .and_then(|header| header.as_str().strip_prefix("token "))
// .ok_or_else(|| surf::Error::from_str(403, "invalid authorization header"))?;
if token == self.state().config.api_token {
Ok(())
} else {
Err(tide::Error::from_str(403, "invalid authorization token"))
}
}
}
// if token == self.state().config.api_token {
// Ok(())
// } else {
// Err(tide::Error::from_str(403, "invalid authorization token"))
// }
// }
// }

View File

@ -1,102 +1,102 @@
use super::{
db::{self, UserId},
errors::TideResultExt,
};
use crate::Request;
use anyhow::{anyhow, Context};
use rand::thread_rng;
use rpc::auth as zed_auth;
use scrypt::{
password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
Scrypt,
};
use std::convert::TryFrom;
use surf::StatusCode;
use tide::Error;
// use super::{
// db::{self, UserId},
// errors::TideResultExt,
// };
// use crate::Request;
// use anyhow::{anyhow, Context};
// use rand::thread_rng;
// use rpc::auth as zed_auth;
// use scrypt::{
// password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
// Scrypt,
// };
// use std::convert::TryFrom;
// use surf::StatusCode;
// use tide::Error;
pub async fn process_auth_header(request: &Request) -> tide::Result<UserId> {
let mut auth_header = request
.header("Authorization")
.ok_or_else(|| {
Error::new(
StatusCode::BadRequest,
anyhow!("missing authorization header"),
)
})?
.last()
.as_str()
.split_whitespace();
let user_id = UserId(auth_header.next().unwrap_or("").parse().map_err(|_| {
Error::new(
StatusCode::BadRequest,
anyhow!("missing user id in authorization header"),
)
})?);
let access_token = auth_header.next().ok_or_else(|| {
Error::new(
StatusCode::BadRequest,
anyhow!("missing access token in authorization header"),
)
})?;
// pub async fn process_auth_header(request: &Request) -> tide::Result<UserId> {
// let mut auth_header = request
// .header("Authorization")
// .ok_or_else(|| {
// Error::new(
// StatusCode::BadRequest,
// anyhow!("missing authorization header"),
// )
// })?
// .last()
// .as_str()
// .split_whitespace();
// let user_id = UserId(auth_header.next().unwrap_or("").parse().map_err(|_| {
// Error::new(
// StatusCode::BadRequest,
// anyhow!("missing user id in authorization header"),
// )
// })?);
// let access_token = auth_header.next().ok_or_else(|| {
// Error::new(
// StatusCode::BadRequest,
// anyhow!("missing access token in authorization header"),
// )
// })?;
let state = request.state().clone();
let mut credentials_valid = false;
for password_hash in state.db.get_access_token_hashes(user_id).await? {
if verify_access_token(&access_token, &password_hash)? {
credentials_valid = true;
break;
}
}
// let state = request.state().clone();
// let mut credentials_valid = false;
// for password_hash in state.db.get_access_token_hashes(user_id).await? {
// if verify_access_token(&access_token, &password_hash)? {
// credentials_valid = true;
// break;
// }
// }
if !credentials_valid {
Err(Error::new(
StatusCode::Unauthorized,
anyhow!("invalid credentials"),
))?;
}
// if !credentials_valid {
// Err(Error::new(
// StatusCode::Unauthorized,
// anyhow!("invalid credentials"),
// ))?;
// }
Ok(user_id)
}
// Ok(user_id)
// }
const MAX_ACCESS_TOKENS_TO_STORE: usize = 8;
// const MAX_ACCESS_TOKENS_TO_STORE: usize = 8;
pub async fn create_access_token(db: &dyn db::Db, user_id: UserId) -> tide::Result<String> {
let access_token = zed_auth::random_token();
let access_token_hash =
hash_access_token(&access_token).context("failed to hash access token")?;
db.create_access_token_hash(user_id, &access_token_hash, MAX_ACCESS_TOKENS_TO_STORE)
.await?;
Ok(access_token)
}
// pub async fn create_access_token(db: &dyn db::Db, user_id: UserId) -> tide::Result<String> {
// let access_token = zed_auth::random_token();
// let access_token_hash =
// hash_access_token(&access_token).context("failed to hash access token")?;
// db.create_access_token_hash(user_id, &access_token_hash, MAX_ACCESS_TOKENS_TO_STORE)
// .await?;
// Ok(access_token)
// }
fn hash_access_token(token: &str) -> tide::Result<String> {
// Avoid slow hashing in debug mode.
let params = if cfg!(debug_assertions) {
scrypt::Params::new(1, 1, 1).unwrap()
} else {
scrypt::Params::recommended()
};
// fn hash_access_token(token: &str) -> tide::Result<String> {
// // Avoid slow hashing in debug mode.
// let params = if cfg!(debug_assertions) {
// scrypt::Params::new(1, 1, 1).unwrap()
// } else {
// scrypt::Params::recommended()
// };
Ok(Scrypt
.hash_password(
token.as_bytes(),
None,
params,
&SaltString::generate(thread_rng()),
)?
.to_string())
}
// Ok(Scrypt
// .hash_password(
// token.as_bytes(),
// None,
// params,
// &SaltString::generate(thread_rng()),
// )?
// .to_string())
// }
pub fn encrypt_access_token(access_token: &str, public_key: String) -> tide::Result<String> {
let native_app_public_key =
zed_auth::PublicKey::try_from(public_key).context("failed to parse app public key")?;
let encrypted_access_token = native_app_public_key
.encrypt_string(&access_token)
.context("failed to encrypt access token with public key")?;
Ok(encrypted_access_token)
}
// pub fn encrypt_access_token(access_token: &str, public_key: String) -> tide::Result<String> {
// let native_app_public_key =
// zed_auth::PublicKey::try_from(public_key).context("failed to parse app public key")?;
// let encrypted_access_token = native_app_public_key
// .encrypt_string(&access_token)
// .context("failed to encrypt access token with public key")?;
// Ok(encrypted_access_token)
// }
pub fn verify_access_token(token: &str, hash: &str) -> tide::Result<bool> {
let hash = PasswordHash::new(hash)?;
Ok(Scrypt.verify_password(token.as_bytes(), &hash).is_ok())
}
// pub fn verify_access_token(token: &str, hash: &str) -> tide::Result<bool> {
// let hash = PasswordHash::new(hash)?;
// Ok(Scrypt.verify_password(token.as_bytes(), &hash).is_ok())
// }

View File

@ -1,11 +1,12 @@
use anyhow::Context;
use anyhow::Result;
use async_std::task::{block_on, yield_now};
use async_trait::async_trait;
use futures::executor::block_on;
use serde::Serialize;
pub use sqlx::postgres::PgPoolOptions as DbOptions;
use sqlx::{types::Uuid, FromRow};
use time::OffsetDateTime;
use tokio::task::yield_now;
macro_rules! test_support {
($self:ident, { $($token:tt)* }) => {{
@ -81,7 +82,7 @@ pub struct PostgresDb {
}
impl PostgresDb {
pub async fn new(url: &str, max_connections: u32) -> tide::Result<Self> {
pub async fn new(url: &str, max_connections: u32) -> Result<Self> {
let pool = DbOptions::new()
.max_connections(max_connections)
.connect(url)

View File

@ -2,18 +2,17 @@ mod api;
mod auth;
mod db;
mod env;
mod errors;
mod rpc;
use ::rpc::Peer;
use async_std::net::TcpListener;
use anyhow::Result;
use async_trait::async_trait;
use db::{Db, PostgresDb};
use serde::Deserialize;
use std::sync::Arc;
use tide_compress::CompressMiddleware;
use tokio::net::TcpListener;
type Request = tide::Request<Arc<AppState>>;
// type Request = tide::Request<Arc<AppState>>;
#[derive(Default, Deserialize)]
pub struct Config {
@ -28,7 +27,7 @@ pub struct AppState {
}
impl AppState {
async fn new(config: Config) -> tide::Result<Arc<Self>> {
async fn new(config: Config) -> Result<Arc<Self>> {
let db = PostgresDb::new(&config.database_url, 5).await?;
let this = Self {
@ -39,24 +38,24 @@ impl AppState {
}
}
#[async_trait]
trait RequestExt {
fn db(&self) -> &Arc<dyn Db>;
}
// #[async_trait]
// trait RequestExt {
// fn db(&self) -> &Arc<dyn Db>;
// }
#[async_trait]
impl RequestExt for Request {
fn db(&self) -> &Arc<dyn Db> {
&self.state().db
}
}
// #[async_trait]
// impl RequestExt for Request {
// fn db(&self) -> &Arc<dyn Db> {
// &self.state().db
// }
// }
#[async_std::main]
async fn main() -> tide::Result<()> {
#[tokio::main]
async fn main() -> Result<()> {
if std::env::var("LOG_JSON").is_ok() {
json_env_logger::init();
} else {
tide::log::start();
env_logger::init();
}
if let Err(error) = env::load_dotenv() {
@ -78,21 +77,17 @@ async fn main() -> tide::Result<()> {
Ok(())
}
pub async fn run_server(
state: Arc<AppState>,
rpc: Arc<Peer>,
listener: TcpListener,
) -> tide::Result<()> {
let mut app = tide::with_state(state.clone());
rpc::add_routes(&mut app, &rpc);
pub async fn run_server(state: Arc<AppState>, rpc: Arc<Peer>, listener: TcpListener) -> Result<()> {
// let mut app = tide::with_state(state.clone());
// rpc::add_routes(&mut app, &rpc);
let mut web = tide::with_state(state.clone());
web.with(CompressMiddleware::new());
api::add_routes(&mut web);
// let mut web = tide::with_state(state.clone());
// web.with(CompressMiddleware::new());
// api::add_routes(&mut web);
app.at("/").nest(web);
// app.at("/").nest(web);
app.listen(listener).await?;
// app.listen(listener).await?;
Ok(())
}

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,5 @@
use crate::db::{ChannelId, UserId};
use anyhow::anyhow;
use anyhow::{anyhow, Result};
use collections::{BTreeMap, HashMap, HashSet};
use rpc::{proto, ConnectionId};
use std::{collections::hash_map, path::PathBuf};
@ -99,7 +99,7 @@ impl Store {
pub fn remove_connection(
&mut self,
connection_id: ConnectionId,
) -> tide::Result<RemovedConnectionState> {
) -> Result<RemovedConnectionState> {
let connection = if let Some(connection) = self.connections.remove(&connection_id) {
connection
} else {
@ -165,7 +165,7 @@ impl Store {
}
}
pub fn user_id_for_connection(&self, connection_id: ConnectionId) -> tide::Result<UserId> {
pub fn user_id_for_connection(&self, connection_id: ConnectionId) -> Result<UserId> {
Ok(self
.connections
.get(&connection_id)
@ -258,7 +258,7 @@ impl Store {
worktree_id: u64,
connection_id: ConnectionId,
worktree: Worktree,
) -> tide::Result<()> {
) -> Result<()> {
let project = self
.projects
.get_mut(&project_id)
@ -286,7 +286,7 @@ impl Store {
&mut self,
project_id: u64,
connection_id: ConnectionId,
) -> tide::Result<Project> {
) -> Result<Project> {
match self.projects.entry(project_id) {
hash_map::Entry::Occupied(e) => {
if e.get().host_connection_id == connection_id {
@ -326,7 +326,7 @@ impl Store {
project_id: u64,
worktree_id: u64,
acting_connection_id: ConnectionId,
) -> tide::Result<(Worktree, Vec<ConnectionId>)> {
) -> Result<(Worktree, Vec<ConnectionId>)> {
let project = self
.projects
.get_mut(&project_id)
@ -363,7 +363,7 @@ impl Store {
&mut self,
project_id: u64,
connection_id: ConnectionId,
) -> tide::Result<SharedProject> {
) -> Result<SharedProject> {
if let Some(project) = self.projects.get_mut(&project_id) {
if project.host_connection_id == connection_id {
let mut share = ProjectShare::default();
@ -383,7 +383,7 @@ impl Store {
&mut self,
project_id: u64,
acting_connection_id: ConnectionId,
) -> tide::Result<UnsharedProject> {
) -> Result<UnsharedProject> {
let project = if let Some(project) = self.projects.get_mut(&project_id) {
project
} else {
@ -418,7 +418,7 @@ impl Store {
worktree_id: u64,
connection_id: ConnectionId,
summary: proto::DiagnosticSummary,
) -> tide::Result<Vec<ConnectionId>> {
) -> Result<Vec<ConnectionId>> {
let project = self
.projects
.get_mut(&project_id)
@ -443,7 +443,7 @@ impl Store {
project_id: u64,
connection_id: ConnectionId,
language_server: proto::LanguageServer,
) -> tide::Result<Vec<ConnectionId>> {
) -> Result<Vec<ConnectionId>> {
let project = self
.projects
.get_mut(&project_id)
@ -461,7 +461,7 @@ impl Store {
connection_id: ConnectionId,
user_id: UserId,
project_id: u64,
) -> tide::Result<JoinedProject> {
) -> Result<JoinedProject> {
let connection = self
.connections
.get_mut(&connection_id)
@ -498,7 +498,7 @@ impl Store {
&mut self,
connection_id: ConnectionId,
project_id: u64,
) -> tide::Result<LeftProject> {
) -> Result<LeftProject> {
let project = self
.projects
.get_mut(&project_id)
@ -533,7 +533,7 @@ impl Store {
worktree_id: u64,
removed_entries: &[u64],
updated_entries: &[proto::Entry],
) -> tide::Result<Vec<ConnectionId>> {
) -> Result<Vec<ConnectionId>> {
let project = self.write_project(project_id, connection_id)?;
let worktree = project
.share_mut()?
@ -554,13 +554,13 @@ impl Store {
&self,
project_id: u64,
acting_connection_id: ConnectionId,
) -> tide::Result<Vec<ConnectionId>> {
) -> Result<Vec<ConnectionId>> {
Ok(self
.read_project(project_id, acting_connection_id)?
.connection_ids())
}
pub fn channel_connection_ids(&self, channel_id: ChannelId) -> tide::Result<Vec<ConnectionId>> {
pub fn channel_connection_ids(&self, channel_id: ChannelId) -> Result<Vec<ConnectionId>> {
Ok(self
.channels
.get(&channel_id)
@ -573,11 +573,7 @@ impl Store {
self.projects.get(&project_id)
}
pub fn read_project(
&self,
project_id: u64,
connection_id: ConnectionId,
) -> tide::Result<&Project> {
pub fn read_project(&self, project_id: u64, connection_id: ConnectionId) -> Result<&Project> {
let project = self
.projects
.get(&project_id)
@ -600,7 +596,7 @@ impl Store {
&mut self,
project_id: u64,
connection_id: ConnectionId,
) -> tide::Result<&mut Project> {
) -> Result<&mut Project> {
let project = self
.projects
.get_mut(&project_id)
@ -755,14 +751,14 @@ impl Project {
}
}
pub fn share(&self) -> tide::Result<&ProjectShare> {
pub fn share(&self) -> Result<&ProjectShare> {
Ok(self
.share
.as_ref()
.ok_or_else(|| anyhow!("worktree is not shared"))?)
}
fn share_mut(&mut self) -> tide::Result<&mut ProjectShare> {
fn share_mut(&mut self) -> Result<&mut ProjectShare> {
Ok(self
.share
.as_mut()