Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e79b15bbf | ||
|
|
b0a2877f20 | ||
|
|
e46f2199c9 | ||
|
|
03d78b25f2 | ||
|
|
67749364aa | ||
|
|
dd3c60fb5a | ||
|
|
e83c226b1b | ||
|
|
8335f44bfe | ||
|
|
3745a7cbe6 | ||
|
|
610b4f9ad1 | ||
|
|
879aeafa9e | ||
|
|
a7b6af7caf | ||
|
|
260db9fcc7 | ||
|
|
1cbc61c558 | ||
|
|
d2f406e0e8 | ||
|
|
a816e3decd | ||
|
|
989a20e99c | ||
|
|
1cf9da26bf | ||
|
|
55a2ff025f | ||
|
|
76660bf189 | ||
|
|
df727688ef | ||
|
|
902404d48d | ||
|
|
b813c34642 | ||
|
|
ab7835dedb | ||
|
|
9bb4c3cd01 | ||
|
|
fce22362d4 | ||
|
|
41ec7cf5d0 | ||
|
|
49ade0cfbd | ||
|
|
0eeba86b32 | ||
|
|
6b06fc9707 | ||
|
|
bd63797213 | ||
|
|
2c4f966d60 | ||
|
|
8174b16c38 | ||
|
|
6666aae5a5 | ||
|
|
0f045890eb | ||
|
|
9cb99a05e0 | ||
|
|
dc85a8fafd | ||
|
|
fcd127aadc | ||
|
|
5df6b8cd5f | ||
|
|
5c776e9ba7 | ||
|
|
c209775abd | ||
|
|
5e924227b6 | ||
|
|
734c4637f0 | ||
|
|
e0072eff63 | ||
|
|
cae2b200cc | ||
|
|
918df9ca6d | ||
|
|
387e864659 | ||
|
|
c84960df91 | ||
|
|
32db4c09a0 | ||
|
|
0d33cc4acd | ||
|
|
666e1d30a3 | ||
|
|
f43fd6a475 | ||
|
|
1587f2cd52 | ||
|
|
f121978897 | ||
|
|
80533bfab2 | ||
|
|
08a3326431 | ||
|
|
fe3b5d32a7 | ||
|
|
e20f55970e | ||
|
|
728e176a06 | ||
|
|
7d14a46607 | ||
|
|
68cc743f2a | ||
|
|
56e5d5e3d2 | ||
|
|
f0ac7ed933 | ||
|
|
0f8ecdc625 | ||
|
|
cfaa900e83 | ||
|
|
f5273f7eb1 | ||
|
|
0fcefa4125 | ||
|
|
d07762f596 | ||
|
|
d253f9236a | ||
|
|
ec44f3d568 | ||
|
|
167e903a56 | ||
|
|
0a8dadb797 | ||
|
|
678ce0abc6 | ||
|
|
e7a51c07d0 | ||
|
|
79bf7fc597 | ||
|
|
7e579f8d34 | ||
|
|
0f2dc9a239 | ||
|
|
59d538206f | ||
|
|
faa283d35b | ||
|
|
86160597ea | ||
|
|
d6b37480e7 | ||
|
|
3ce75d1f02 | ||
|
|
a50abeedad | ||
|
|
130b9841da | ||
|
|
ffa10a68b9 | ||
|
|
124b5484b5 | ||
|
|
2babff1e41 | ||
|
|
cdd01262d2 | ||
|
|
092221ca3f | ||
|
|
5d8ad4fd72 | ||
|
|
7054f74783 | ||
|
|
82a4ec9cbd | ||
|
|
f924ebf8a6 | ||
|
|
b1993421c2 | ||
|
|
8e2d6f7e43 | ||
|
|
d76e95e8fc | ||
|
|
661101c9ae | ||
|
|
f7ecf83ac3 | ||
|
|
9a4789efdc | ||
|
|
eaa4c77641 | ||
|
|
9268b33c3f | ||
|
|
9de32ae12f | ||
|
|
952fb75795 | ||
|
|
e12b1ff863 | ||
|
|
e15e6d4405 | ||
|
|
1c25492a7e | ||
|
|
8c44312485 | ||
|
|
ac0027756e | ||
|
|
f3e806096b | ||
|
|
e1b89c1248 | ||
|
|
be6b6c3cf0 | ||
|
|
15471d9ac4 | ||
|
|
3c236fb671 | ||
|
|
9d4fa9a220 | ||
|
|
bd4bd58612 | ||
|
|
0eec1cc696 | ||
|
|
3fa09ff57d | ||
|
|
0080932aef | ||
|
|
888a2f7fa1 | ||
|
|
dcb5e5900f | ||
|
|
4732aa6782 | ||
|
|
699f77671f | ||
|
|
fcfb9b51de | ||
|
|
36681dd3ac | ||
|
|
13c0beafa6 | ||
|
|
a313a93ff5 | ||
|
|
6a96cfaac1 | ||
|
|
09a8737f24 |
@@ -0,0 +1,11 @@
|
|||||||
|
---
|
||||||
|
name: "Issue with / Feature Request for Conduit"
|
||||||
|
about: "Please file issues on GitLab: https://gitlab.com/famedly/conduit/-/issues/new"
|
||||||
|
title: "CLOSE ME"
|
||||||
|
---
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
**⚠️ Conduit development does not happen on GitHub. Issues opened here will not be addressed**
|
||||||
|
|
||||||
|
Please open issues on GitLab: https://gitlab.com/famedly/conduit/-/issues/new
|
||||||
+157
-44
@@ -1,19 +1,19 @@
|
|||||||
stages:
|
stages:
|
||||||
- test
|
|
||||||
- build
|
- build
|
||||||
- publish artifacts
|
- build docker image
|
||||||
- release nightly
|
- test
|
||||||
|
- upload artifacts
|
||||||
|
|
||||||
variables:
|
variables:
|
||||||
GIT_SUBMODULE_STRATEGY: recursive
|
GIT_SUBMODULE_STRATEGY: recursive
|
||||||
FF_USE_FASTZIP: 1
|
FF_USE_FASTZIP: 1
|
||||||
CACHE_COMPRESSION_LEVEL: fastest
|
CACHE_COMPRESSION_LEVEL: fastest
|
||||||
|
|
||||||
|
|
||||||
test:cargo:
|
test:cargo:
|
||||||
stage: "test"
|
stage: "test"
|
||||||
needs: []
|
needs: []
|
||||||
image: "rust:latest"
|
image: "rust:latest"
|
||||||
|
tags: ["docker"]
|
||||||
variables:
|
variables:
|
||||||
CARGO_HOME: "cargohome"
|
CARGO_HOME: "cargohome"
|
||||||
cache:
|
cache:
|
||||||
@@ -29,10 +29,66 @@ test:cargo:
|
|||||||
- rustup component add clippy rustfmt
|
- rustup component add clippy rustfmt
|
||||||
script:
|
script:
|
||||||
- rustc --version && cargo --version # Print version info for debugging
|
- rustc --version && cargo --version # Print version info for debugging
|
||||||
- cargo test --workspace --verbose --locked
|
|
||||||
- cargo fmt --all -- --check
|
- cargo fmt --all -- --check
|
||||||
|
- cargo test --workspace --verbose --locked
|
||||||
- cargo clippy
|
- cargo clippy
|
||||||
|
|
||||||
|
test:sytest:
|
||||||
|
stage: "test"
|
||||||
|
allow_failure: true
|
||||||
|
needs:
|
||||||
|
- "build:cargo:x86_64-unknown-linux-musl"
|
||||||
|
image:
|
||||||
|
name: "valkum/sytest-conduit:latest"
|
||||||
|
entrypoint: [""]
|
||||||
|
tags: ["docker"]
|
||||||
|
variables:
|
||||||
|
PLUGINS: "https://github.com/valkum/sytest_conduit/archive/master.tar.gz"
|
||||||
|
before_script:
|
||||||
|
- "mkdir -p /app"
|
||||||
|
- "cp ./conduit-x86_64-unknown-linux-musl /app/conduit"
|
||||||
|
- "chmod +x /app/conduit"
|
||||||
|
- "rm -rf /src && ln -s $CI_PROJECT_DIR/ /src"
|
||||||
|
- "mkdir -p /work/server-0/database/ && mkdir -p /work/server-1/database/ && mkdir -p /work/server-2/database/"
|
||||||
|
- "cd /"
|
||||||
|
script:
|
||||||
|
- "SYTEST_EXIT_CODE=0"
|
||||||
|
- "/bootstrap.sh conduit || SYTEST_EXIT_CODE=1"
|
||||||
|
- "perl /sytest/tap-to-junit-xml.pl --puretap --input /logs/results.tap --output $CI_PROJECT_DIR/sytest.xml \"Sytest\" && cp /logs/results.tap $CI_PROJECT_DIR/results.tap"
|
||||||
|
- "exit $SYTEST_EXIT_CODE"
|
||||||
|
artifacts:
|
||||||
|
when: always
|
||||||
|
paths:
|
||||||
|
- "$CI_PROJECT_DIR/sytest.xml"
|
||||||
|
- "$CI_PROJECT_DIR/results.tap"
|
||||||
|
reports:
|
||||||
|
junit: "$CI_PROJECT_DIR/sytest.xml"
|
||||||
|
|
||||||
|
|
||||||
|
test:register:element-web-stable:
|
||||||
|
stage: "test"
|
||||||
|
needs:
|
||||||
|
- "build:cargo:x86_64-unknown-linux-gnu"
|
||||||
|
image: "buildkite/puppeteer:latest"
|
||||||
|
tags: ["docker"]
|
||||||
|
interruptible: true
|
||||||
|
script:
|
||||||
|
- "CONDUIT_CONFIG=tests/test-config.toml ./conduit-x86_64-unknown-linux-gnu > conduit.log &"
|
||||||
|
- "cd tests/client-element-web/"
|
||||||
|
- "npm install puppeteer"
|
||||||
|
- "node test-element-web-registration.js \"https://app.element.io/\" \"http://localhost:6167\""
|
||||||
|
- "killall --regexp \"conduit\""
|
||||||
|
- "cd ../.."
|
||||||
|
- "cat conduit.log"
|
||||||
|
artifacts:
|
||||||
|
paths:
|
||||||
|
- "tests/client-element-web/*.png"
|
||||||
|
- "*.log"
|
||||||
|
expire_in: 1 week
|
||||||
|
when: always
|
||||||
|
retry: 1
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------- #
|
# --------------------------------------------------------------------- #
|
||||||
# Cargo: Compiling for different architectures #
|
# Cargo: Compiling for different architectures #
|
||||||
# --------------------------------------------------------------------- #
|
# --------------------------------------------------------------------- #
|
||||||
@@ -44,6 +100,7 @@ test:cargo:
|
|||||||
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
|
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
|
||||||
interruptible: true
|
interruptible: true
|
||||||
image: "rust:latest"
|
image: "rust:latest"
|
||||||
|
tags: ["docker"]
|
||||||
cache:
|
cache:
|
||||||
paths:
|
paths:
|
||||||
- cargohome
|
- cargohome
|
||||||
@@ -58,18 +115,24 @@ test:cargo:
|
|||||||
- "apt-get install -yqq --no-install-recommends $NEEDED_PACKAGES"
|
- "apt-get install -yqq --no-install-recommends $NEEDED_PACKAGES"
|
||||||
- "rustup target add $TARGET"
|
- "rustup target add $TARGET"
|
||||||
script:
|
script:
|
||||||
|
# Set some cargo tuning here, because targets overwrite the 'variables'
|
||||||
|
- "export CARGO_INCREMENTAL=true"
|
||||||
|
- "export CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16"
|
||||||
|
- "export CARGO_PROFILE_RELEASE_LTO=thin"
|
||||||
- time cargo build --target $TARGET --release
|
- time cargo build --target $TARGET --release
|
||||||
- 'mv "target/$TARGET/release/conduit" "conduit-$TARGET"'
|
- 'mv "target/$TARGET/release/conduit" "conduit-$TARGET"'
|
||||||
artifacts:
|
|
||||||
name: "conduit-$TARGET"
|
|
||||||
expose_as: "Binary"
|
|
||||||
paths:
|
|
||||||
- "conduit-$TARGET"
|
|
||||||
|
|
||||||
build:cargo:x86_64-unknown-linux-gnu:
|
build:cargo:x86_64-unknown-linux-gnu:
|
||||||
extends: .build-cargo-shared-settings
|
extends: .build-cargo-shared-settings
|
||||||
variables:
|
variables:
|
||||||
TARGET: "x86_64-unknown-linux-gnu"
|
TARGET: "x86_64-unknown-linux-gnu"
|
||||||
|
rules:
|
||||||
|
- if: "$CI_COMMIT_BRANCH"
|
||||||
|
artifacts:
|
||||||
|
name: "conduit-x86_64-unknown-linux-gnu"
|
||||||
|
paths:
|
||||||
|
- "conduit-x86_64-unknown-linux-gnu"
|
||||||
|
expose_as: "Release binary x86_64-unknown-linux-gnu"
|
||||||
|
|
||||||
build:cargo:armv7-unknown-linux-gnueabihf:
|
build:cargo:armv7-unknown-linux-gnueabihf:
|
||||||
extends: .build-cargo-shared-settings
|
extends: .build-cargo-shared-settings
|
||||||
@@ -79,6 +142,11 @@ build:cargo:armv7-unknown-linux-gnueabihf:
|
|||||||
CARGO_TARGET_ARMV7_UNKNOWN_LINUX_GNUEABIHF_LINKER: arm-linux-gnueabihf-gcc
|
CARGO_TARGET_ARMV7_UNKNOWN_LINUX_GNUEABIHF_LINKER: arm-linux-gnueabihf-gcc
|
||||||
CC_armv7_unknown_linux_gnueabihf: arm-linux-gnueabihf-gcc
|
CC_armv7_unknown_linux_gnueabihf: arm-linux-gnueabihf-gcc
|
||||||
CXX_armv7_unknown_linux_gnueabihf: arm-linux-gnueabihf-g++
|
CXX_armv7_unknown_linux_gnueabihf: arm-linux-gnueabihf-g++
|
||||||
|
artifacts:
|
||||||
|
name: "conduit-armv7-unknown-linux-gnueabihf"
|
||||||
|
paths:
|
||||||
|
- "conduit-armv7-unknown-linux-gnueabihf"
|
||||||
|
expose_as: "Release binary armv7-unknown-linux-gnueabihf"
|
||||||
|
|
||||||
build:cargo:aarch64-unknown-linux-gnu:
|
build:cargo:aarch64-unknown-linux-gnu:
|
||||||
extends: .build-cargo-shared-settings
|
extends: .build-cargo-shared-settings
|
||||||
@@ -90,6 +158,30 @@ build:cargo:aarch64-unknown-linux-gnu:
|
|||||||
CXX_aarch64_unknown_linux_gnu: aarch64-linux-gnu-g++
|
CXX_aarch64_unknown_linux_gnu: aarch64-linux-gnu-g++
|
||||||
TARGET_CC: "/usr/bin/aarch64-linux-gnu-gcc-8"
|
TARGET_CC: "/usr/bin/aarch64-linux-gnu-gcc-8"
|
||||||
TARGET_AR: "/usr/bin/aarch64-linux-gnu-gcc-ar-8"
|
TARGET_AR: "/usr/bin/aarch64-linux-gnu-gcc-ar-8"
|
||||||
|
artifacts:
|
||||||
|
name: "conduit-aarch64-unknown-linux-gnu"
|
||||||
|
paths:
|
||||||
|
- "conduit-aarch64-unknown-linux-gnu"
|
||||||
|
expose_as: "Release binary aarch64-unknown-linux-gnu"
|
||||||
|
|
||||||
|
build:cargo:x86_64-unknown-linux-musl:
|
||||||
|
extends: .build-cargo-shared-settings
|
||||||
|
image: "rust:alpine"
|
||||||
|
rules:
|
||||||
|
- if: '$CI_COMMIT_BRANCH' # Always run
|
||||||
|
variables:
|
||||||
|
TARGET: "x86_64-unknown-linux-musl"
|
||||||
|
before_script:
|
||||||
|
- 'echo "Building for target $TARGET"'
|
||||||
|
- 'mkdir -p cargohome && CARGOHOME="cargohome"'
|
||||||
|
- "cat /etc/*-release && rustc --version && cargo --version" # Print version info for debugging
|
||||||
|
- "rustup target add $TARGET"
|
||||||
|
- "apk add libc-dev"
|
||||||
|
artifacts:
|
||||||
|
name: "conduit-x86_64-unknown-linux-musl"
|
||||||
|
paths:
|
||||||
|
- "conduit-x86_64-unknown-linux-musl"
|
||||||
|
expose_as: "Release binary x86_64-unknown-linux-musl"
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------- #
|
# --------------------------------------------------------------------- #
|
||||||
@@ -104,6 +196,7 @@ build:cargo:aarch64-unknown-linux-gnu:
|
|||||||
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
|
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
|
||||||
interruptible: true
|
interruptible: true
|
||||||
image: "rust:latest"
|
image: "rust:latest"
|
||||||
|
tags: ["docker"]
|
||||||
cache:
|
cache:
|
||||||
paths:
|
paths:
|
||||||
- cargohome
|
- cargohome
|
||||||
@@ -121,35 +214,80 @@ build:cargo:aarch64-unknown-linux-gnu:
|
|||||||
script:
|
script:
|
||||||
- time cargo deb --target $TARGET
|
- time cargo deb --target $TARGET
|
||||||
- 'mv target/$TARGET/debian/*.deb "conduit-$TARGET.deb"'
|
- 'mv target/$TARGET/debian/*.deb "conduit-$TARGET.deb"'
|
||||||
artifacts:
|
|
||||||
name: "conduit-$TARGET.deb"
|
|
||||||
expose_as: "Debian Package"
|
|
||||||
paths:
|
|
||||||
- "conduit-$TARGET.deb"
|
|
||||||
|
|
||||||
build:cargo-deb:x86_64-unknown-linux-gnu:
|
build:cargo-deb:x86_64-unknown-linux-gnu:
|
||||||
extends: .build-cargo-deb-shared-settings
|
extends: .build-cargo-deb-shared-settings
|
||||||
variables:
|
variables:
|
||||||
TARGET: "x86_64-unknown-linux-gnu"
|
TARGET: "x86_64-unknown-linux-gnu"
|
||||||
NEEDED_PACKAGES: ""
|
NEEDED_PACKAGES: ""
|
||||||
|
artifacts:
|
||||||
|
name: "conduit-x86_64-unknown-linux-gnu.deb"
|
||||||
|
paths:
|
||||||
|
- "conduit-x86_64-unknown-linux-gnu.deb"
|
||||||
|
expose_as: "Debian Package x86_64"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------- #
|
# --------------------------------------------------------------------- #
|
||||||
# Storing and releasing compiled binaries #
|
# Create and publish docker image #
|
||||||
|
# --------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
.docker-shared-settings:
|
||||||
|
stage: "build docker image"
|
||||||
|
needs: []
|
||||||
|
interruptible: true
|
||||||
|
image:
|
||||||
|
name: "gcr.io/kaniko-project/executor:debug"
|
||||||
|
entrypoint: [""]
|
||||||
|
tags: ["docker"]
|
||||||
|
variables:
|
||||||
|
# Configure Kaniko Caching: https://cloud.google.com/build/docs/kaniko-cache
|
||||||
|
KANIKO_CACHE_ARGS: "--cache=true --cache-copy-layers=true --cache-ttl=120h --cache-repo $CI_REGISTRY_IMAGE/kaniko-ci-cache"
|
||||||
|
before_script:
|
||||||
|
- "mkdir -p /kaniko/.docker"
|
||||||
|
- 'echo "{\"auths\":{\"$CI_REGISTRY\":{\"username\":\"$CI_REGISTRY_USER\",\"password\":\"$CI_REGISTRY_PASSWORD\"},\"$DOCKER_HUB\":{\"username\":\"$DOCKER_HUB_USER\",\"password\":\"$DOCKER_HUB_PASSWORD\"}}}" > /kaniko/.docker/config.json'
|
||||||
|
|
||||||
|
|
||||||
|
# Build a docker image by packaging up the x86_64-unknown-linux-musl binary into an alpine image
|
||||||
|
build:docker:main:
|
||||||
|
extends: .docker-shared-settings
|
||||||
|
needs:
|
||||||
|
- "build:cargo:x86_64-unknown-linux-musl"
|
||||||
|
script:
|
||||||
|
- >
|
||||||
|
/kaniko/executor
|
||||||
|
$KANIKO_CACHE_ARGS
|
||||||
|
--context $CI_PROJECT_DIR
|
||||||
|
--build-arg CREATED=$(date -u +'%Y-%m-%dT%H:%M:%SZ')
|
||||||
|
--build-arg VERSION=$(grep -m1 -o '[0-9].[0-9].[0-9]' Cargo.toml)
|
||||||
|
--build-arg "GIT_REF=$CI_COMMIT_REF_NAME"
|
||||||
|
--dockerfile "$CI_PROJECT_DIR/docker/ci-binaries-packaging.Dockerfile"
|
||||||
|
--destination "$CI_REGISTRY_IMAGE/conduit:latest"
|
||||||
|
--destination "$CI_REGISTRY_IMAGE/conduit:alpine"
|
||||||
|
--destination "$CI_REGISTRY_IMAGE/conduit:commit-$CI_COMMIT_SHORT_SHA"
|
||||||
|
--destination "$DOCKER_HUB_IMAGE/matrixconduit/matrix-conduit:latest"
|
||||||
|
--destination "$DOCKER_HUB_IMAGE/matrixconduit/matrix-conduit:alpine"
|
||||||
|
--destination "$DOCKER_HUB_IMAGE/matrixconduit/matrix-conduit:commit-$CI_COMMIT_SHORT_SHA"
|
||||||
|
rules:
|
||||||
|
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------- #
|
||||||
|
# Store binaries as package so they have download urls #
|
||||||
# --------------------------------------------------------------------- #
|
# --------------------------------------------------------------------- #
|
||||||
|
|
||||||
publish:package:
|
publish:package:
|
||||||
stage: "publish artifacts"
|
stage: "upload artifacts"
|
||||||
needs:
|
needs:
|
||||||
- "build:cargo:x86_64-unknown-linux-gnu"
|
- "build:cargo:x86_64-unknown-linux-gnu"
|
||||||
- "build:cargo:armv7-unknown-linux-gnueabihf"
|
- "build:cargo:armv7-unknown-linux-gnueabihf"
|
||||||
- "build:cargo:aarch64-unknown-linux-gnu"
|
- "build:cargo:aarch64-unknown-linux-gnu"
|
||||||
|
- "build:cargo:x86_64-unknown-linux-musl"
|
||||||
- "build:cargo-deb:x86_64-unknown-linux-gnu"
|
- "build:cargo-deb:x86_64-unknown-linux-gnu"
|
||||||
rules:
|
rules:
|
||||||
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
|
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
|
||||||
image: curlimages/curl:latest
|
image: curlimages/curl:latest
|
||||||
|
tags: ["docker"]
|
||||||
variables:
|
variables:
|
||||||
GIT_STRATEGY: "none" # Don't need a clean copy of the code, we just operate on artifacts
|
GIT_STRATEGY: "none" # Don't need a clean copy of the code, we just operate on artifacts
|
||||||
script:
|
script:
|
||||||
@@ -157,32 +295,7 @@ publish:package:
|
|||||||
- 'curl --header "JOB-TOKEN: $CI_JOB_TOKEN" --upload-file conduit-x86_64-unknown-linux-gnu "${BASE_URL}/conduit-x86_64-unknown-linux-gnu"'
|
- 'curl --header "JOB-TOKEN: $CI_JOB_TOKEN" --upload-file conduit-x86_64-unknown-linux-gnu "${BASE_URL}/conduit-x86_64-unknown-linux-gnu"'
|
||||||
- 'curl --header "JOB-TOKEN: $CI_JOB_TOKEN" --upload-file conduit-armv7-unknown-linux-gnueabihf "${BASE_URL}/conduit-armv7-unknown-linux-gnueabihf"'
|
- 'curl --header "JOB-TOKEN: $CI_JOB_TOKEN" --upload-file conduit-armv7-unknown-linux-gnueabihf "${BASE_URL}/conduit-armv7-unknown-linux-gnueabihf"'
|
||||||
- 'curl --header "JOB-TOKEN: $CI_JOB_TOKEN" --upload-file conduit-aarch64-unknown-linux-gnu "${BASE_URL}/conduit-aarch64-unknown-linux-gnu"'
|
- 'curl --header "JOB-TOKEN: $CI_JOB_TOKEN" --upload-file conduit-aarch64-unknown-linux-gnu "${BASE_URL}/conduit-aarch64-unknown-linux-gnu"'
|
||||||
|
- 'curl --header "JOB-TOKEN: $CI_JOB_TOKEN" --upload-file conduit-x86_64-unknown-linux-musl "${BASE_URL}/conduit-x86_64-unknown-linux-musl"'
|
||||||
- 'curl --header "JOB-TOKEN: $CI_JOB_TOKEN" --upload-file conduit-x86_64-unknown-linux-gnu.deb "${BASE_URL}/conduit-x86_64-unknown-linux-gnu.deb"'
|
- 'curl --header "JOB-TOKEN: $CI_JOB_TOKEN" --upload-file conduit-x86_64-unknown-linux-gnu.deb "${BASE_URL}/conduit-x86_64-unknown-linux-gnu.deb"'
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
publish:nightly:
|
|
||||||
stage: "release nightly"
|
|
||||||
image: registry.gitlab.com/gitlab-org/release-cli:latest
|
|
||||||
needs:
|
|
||||||
- job: "publish:package"
|
|
||||||
artifacts: false
|
|
||||||
variables:
|
|
||||||
GIT_STRATEGY: "none" # Don't need a clean copy of the code, we just operate on artifacts
|
|
||||||
script: "echo 'Releasing current state as release'"
|
|
||||||
rules:
|
|
||||||
- if: "$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH" # Run this job on the main branch
|
|
||||||
release:
|
|
||||||
name: 'Nightly'
|
|
||||||
description: '⚠️ The latest development version of the day, fresh from the repository. Use at your own risk!'
|
|
||||||
tag_name: 'nightly'
|
|
||||||
assets:
|
|
||||||
links:
|
|
||||||
- name: 'conduit-x86_64-unknown-linux-gnu'
|
|
||||||
url: "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/conduit-${CI_COMMIT_REF_SLUG}/build-${CI_PIPELINE_ID}/conduit-x86_64-unknown-linux-gnu"
|
|
||||||
- name: 'conduit-armv7-unknown-linux-gnueabihf'
|
|
||||||
url: "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/conduit-${CI_COMMIT_REF_SLUG}/build-${CI_PIPELINE_ID}/conduit-armv7-unknown-linux-gnueabihf"
|
|
||||||
- name: 'conduit-aarch64-unknown-linux-gnu'
|
|
||||||
url: "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/conduit-${CI_COMMIT_REF_SLUG}/build-${CI_PIPELINE_ID}/conduit-aarch64-unknown-linux-gnu"
|
|
||||||
- name: 'conduit-x86_64-unknown-linux-gnu.deb'
|
|
||||||
url: "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/conduit-${CI_COMMIT_REF_SLUG}/build-${CI_PIPELINE_ID}/conduit-x86_64-unknown-linux-gnu.deb"
|
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
<!--
|
||||||
|
If you're requesting a new feature, that isn't part of this project yet,
|
||||||
|
then please consider filling out a "Feature Request" instead!
|
||||||
|
|
||||||
|
If you need a hand setting up your conduit server, feel free to ask for help in the
|
||||||
|
Conduit Matrix Chat: https://matrix.to/#/#conduit:fachschaften.org.
|
||||||
|
-->
|
||||||
|
|
||||||
|
### Description
|
||||||
|
<!-- What did you do and what happened? Why is that bad? -->
|
||||||
|
|
||||||
|
### System Configuration
|
||||||
|
<!-- Other data that might help us debug this issue, like os, conduit version, database backend -->
|
||||||
|
|
||||||
|
Conduit Version:
|
||||||
|
Database backend (default is sqlite): sqlite
|
||||||
|
|
||||||
|
|
||||||
|
/label ~conduit
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<!--
|
||||||
|
If you want to report a bug or an error,
|
||||||
|
then please consider filling out a "Bug Report" instead!
|
||||||
|
-->
|
||||||
|
|
||||||
|
|
||||||
|
### Is your feature request related to a problem? Please describe.
|
||||||
|
|
||||||
|
<!-- Eg. I'm always frustrated when [...] -->
|
||||||
|
|
||||||
|
|
||||||
|
### Describe the solution you'd like
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/label ~conduit
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
# Headline
|
|
||||||
|
|
||||||
### Description
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/label ~conduit
|
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
|
||||||
|
<!-- Please describe your changes here -->
|
||||||
|
|
||||||
|
-----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
- [ ] I ran `cargo fmt` and `cargo test`
|
||||||
|
- [ ] I agree to release my code and all other changes of this MR under the Apache-2.0 license
|
||||||
|
|
||||||
Generated
+480
-395
File diff suppressed because it is too large
Load Diff
+25
-23
@@ -14,45 +14,44 @@ edition = "2018"
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
# Used to handle requests
|
# Used to handle requests
|
||||||
# TODO: This can become optional as soon as proper configs are supported
|
# TODO: This can become optional as soon as proper configs are supported
|
||||||
rocket = { git = "https://github.com/SergioBenitez/Rocket.git", rev = "801e04bd5369eb39e126c75f6d11e1e9597304d8", features = ["tls"] } # Used to handle requests
|
# rocket = { git = "https://github.com/SergioBenitez/Rocket.git", rev = "801e04bd5369eb39e126c75f6d11e1e9597304d8", features = ["tls"] } # Used to handle requests
|
||||||
|
rocket = { version = "0.5.0-rc.1", features = ["tls"] } # Used to handle requests
|
||||||
|
|
||||||
# Used for matrix spec type definitions and helpers
|
# Used for matrix spec type definitions and helpers
|
||||||
ruma = { git = "https://github.com/ruma/ruma", rev = "174555857ef90d49e4b9a672be9e2fe0acdc2687", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] }
|
#ruma = { git = "https://github.com/ruma/ruma", rev = "eb19b0e08a901b87d11b3be0890ec788cc760492", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] }
|
||||||
|
ruma = { git = "https://github.com/timokoesters/ruma", rev = "a2d93500e1dbc87e7032a3c74f3b2479a7f84e93", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] }
|
||||||
#ruma = { path = "../ruma/crates/ruma", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] }
|
#ruma = { path = "../ruma/crates/ruma", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] }
|
||||||
|
|
||||||
# Used for long polling and federation sender, should be the same as rocket::tokio
|
# Used for long polling and federation sender, should be the same as rocket::tokio
|
||||||
tokio = "1.2.0"
|
tokio = "1.8.2"
|
||||||
# Used for storing data permanently
|
# Used for storing data permanently
|
||||||
sled = { version = "0.34.6", features = ["compression", "no_metrics"], optional = true }
|
sled = { version = "0.34.6", features = ["compression", "no_metrics"], optional = true }
|
||||||
rocksdb = { version = "0.16.0", features = ["multi-threaded-cf"], optional = true }
|
|
||||||
#sled = { git = "https://github.com/spacejam/sled.git", rev = "e4640e0773595229f398438886f19bca6f7326a2", features = ["compression"] }
|
#sled = { git = "https://github.com/spacejam/sled.git", rev = "e4640e0773595229f398438886f19bca6f7326a2", features = ["compression"] }
|
||||||
|
|
||||||
# Used for the http request / response body type for Ruma endpoints used with reqwest
|
# Used for the http request / response body type for Ruma endpoints used with reqwest
|
||||||
bytes = "1.0.1"
|
bytes = "1.0.1"
|
||||||
# Used for emitting log entries
|
|
||||||
log = "0.4.14"
|
|
||||||
# Used for rocket<->ruma conversions
|
# Used for rocket<->ruma conversions
|
||||||
http = "0.2.3"
|
http = "0.2.4"
|
||||||
# Used to find data directory for default db path
|
# Used to find data directory for default db path
|
||||||
directories = "3.0.1"
|
directories = "3.0.2"
|
||||||
# Used for ruma wrapper
|
# Used for ruma wrapper
|
||||||
serde_json = { version = "1.0.64", features = ["raw_value"] }
|
serde_json = { version = "1.0.64", features = ["raw_value"] }
|
||||||
# Used for appservice registration files
|
# Used for appservice registration files
|
||||||
serde_yaml = "0.8.17"
|
serde_yaml = "0.8.17"
|
||||||
# Used for pdu definition
|
# Used for pdu definition
|
||||||
serde = "1.0.123"
|
serde = "1.0.126"
|
||||||
# Used for secure identifiers
|
# Used for secure identifiers
|
||||||
rand = "0.8.3"
|
rand = "0.8.4"
|
||||||
# Used to hash passwords
|
# Used to hash passwords
|
||||||
rust-argon2 = "0.8.3"
|
rust-argon2 = "0.8.3"
|
||||||
# Used to send requests
|
# Used to send requests
|
||||||
reqwest = { version = "0.11.3", default-features = false, features = ["rustls-tls-native-roots", "socks"] }
|
reqwest = { version = "0.11.4", default-features = false, features = ["rustls-tls-native-roots", "socks"] }
|
||||||
# Custom TLS verifier
|
# Custom TLS verifier
|
||||||
rustls = { version = "0.19", features = ["dangerous_configuration"] }
|
rustls = { version = "0.19.1", features = ["dangerous_configuration"] }
|
||||||
rustls-native-certs = "0.5.0"
|
rustls-native-certs = "0.5.0"
|
||||||
webpki = "0.21.0"
|
webpki = "0.21.0"
|
||||||
# Used for conduit::Error type
|
# Used for conduit::Error type
|
||||||
thiserror = "1.0.24"
|
thiserror = "1.0.26"
|
||||||
# Used to generate thumbnails for images
|
# Used to generate thumbnails for images
|
||||||
image = { version = "0.23.14", default-features = false, features = ["jpeg", "png", "gif"] }
|
image = { version = "0.23.14", default-features = false, features = ["jpeg", "png", "gif"] }
|
||||||
# Used to encode server public key
|
# Used to encode server public key
|
||||||
@@ -60,30 +59,33 @@ base64 = "0.13.0"
|
|||||||
# Used when hashing the state
|
# Used when hashing the state
|
||||||
ring = "0.16.20"
|
ring = "0.16.20"
|
||||||
# Used when querying the SRV record of other servers
|
# Used when querying the SRV record of other servers
|
||||||
trust-dns-resolver = "0.20.0"
|
trust-dns-resolver = "0.20.3"
|
||||||
# Used to find matching events for appservices
|
# Used to find matching events for appservices
|
||||||
regex = "1.4.3"
|
regex = "1.5.4"
|
||||||
# jwt jsonwebtokens
|
# jwt jsonwebtokens
|
||||||
jsonwebtoken = "7.2.0"
|
jsonwebtoken = "7.2.0"
|
||||||
# Performance measurements
|
# Performance measurements
|
||||||
tracing = "0.1.25"
|
tracing = { version = "0.1.26", features = ["release_max_level_warn"] }
|
||||||
opentelemetry = "0.12.0"
|
opentelemetry = "0.15.0"
|
||||||
tracing-subscriber = "0.2.16"
|
tracing-subscriber = "0.2.19"
|
||||||
tracing-opentelemetry = "0.11.0"
|
tracing-opentelemetry = "0.14.0"
|
||||||
opentelemetry-jaeger = "0.11.0"
|
tracing-flame = "0.1.0"
|
||||||
|
opentelemetry-jaeger = "0.14.0"
|
||||||
pretty_env_logger = "0.4.0"
|
pretty_env_logger = "0.4.0"
|
||||||
lru-cache = "0.1.2"
|
lru-cache = "0.1.2"
|
||||||
rusqlite = { version = "0.25.3", optional = true, features = ["bundled"] }
|
rusqlite = { version = "0.25.3", optional = true, features = ["bundled"] }
|
||||||
parking_lot = { version = "0.11.1", optional = true }
|
parking_lot = { version = "0.11.1", optional = true }
|
||||||
crossbeam = { version = "0.8.1", optional = true }
|
crossbeam = { version = "0.8.1", optional = true }
|
||||||
num_cpus = { version = "1.13.0", optional = true }
|
num_cpus = "1.13.0"
|
||||||
|
threadpool = "1.8.1"
|
||||||
|
heed = { git = "https://github.com/timokoesters/heed.git", rev = "f6f825da7fb2c758867e05ad973ef800a6fe1d5d", optional = true }
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["conduit_bin", "backend_sqlite"]
|
default = ["conduit_bin", "backend_sqlite"]
|
||||||
backend_sled = ["sled"]
|
backend_sled = ["sled"]
|
||||||
backend_rocksdb = ["rocksdb"]
|
|
||||||
backend_sqlite = ["sqlite"]
|
backend_sqlite = ["sqlite"]
|
||||||
sqlite = ["rusqlite", "parking_lot", "crossbeam", "num_cpus", "tokio/signal"]
|
backend_heed = ["heed", "crossbeam"]
|
||||||
|
sqlite = ["rusqlite", "parking_lot", "crossbeam", "tokio/signal"]
|
||||||
conduit_bin = [] # TODO: add rocket to this when it is optional
|
conduit_bin = [] # TODO: add rocket to this when it is optional
|
||||||
|
|
||||||
[[bin]]
|
[[bin]]
|
||||||
|
|||||||
@@ -8,10 +8,17 @@ If you run into any problems while setting up Conduit, write an email to `timo@k
|
|||||||
|
|
||||||
You may simply download the binary that fits your machine. Run `uname -m` to see
|
You may simply download the binary that fits your machine. Run `uname -m` to see
|
||||||
what you need. Now copy the right url:
|
what you need. Now copy the right url:
|
||||||
- x84_64: `https://conduit.rs/master/x86_64/conduit-bin`
|
|
||||||
- armv7: `https://conduit.rs/master/armv7/conduit-bin`
|
| CPU Architecture | GNU (Ubuntu, Debian, ArchLinux, ...) | MUSL (Alpine, ... ) |
|
||||||
- armv8: `https://conduit.rs/master/armv8/conduit-bin`
|
| -------------------- | ------------------------------------- | ----------------------- |
|
||||||
- arm: `https://conduit.rs/master/arm/conduit-bin`
|
| x84_64 / amd64 | [Download][x84_64-gnu] | [Download][x84_64-musl] |
|
||||||
|
| armv7 (Raspberry Pi) | [Download][armv7-gnu] | - |
|
||||||
|
| armv8 / aarch64 | [Download][armv8-gnu] | - |
|
||||||
|
|
||||||
|
[x84_64-gnu]: https://gitlab.com/famedly/conduit/-/jobs/artifacts/master/raw/conduit-x86_64-unknown-linux-gnu?job=build:cargo:x86_64-unknown-linux-gnu
|
||||||
|
[x84_64-musl]: https://gitlab.com/famedly/conduit/-/jobs/artifacts/master/raw/conduit-x86_64-unknown-linux-musl?job=build:cargo:x86_64-unknown-linux-musl
|
||||||
|
[armv7-gnu]: https://gitlab.com/famedly/conduit/-/jobs/artifacts/master/raw/conduit-armv7-unknown-linux-gnueabihf?job=build:cargo:armv7-unknown-linux-gnueabihf
|
||||||
|
[armv8-gnu]: https://gitlab.com/famedly/conduit/-/jobs/artifacts/master/raw/conduit-aarch64-unknown-linux-gnu?job=build:cargo:aarch64-unknown-linux-gnu
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ sudo wget -O /usr/local/bin/matrix-conduit <url>
|
$ sudo wget -O /usr/local/bin/matrix-conduit <url>
|
||||||
@@ -26,6 +33,7 @@ Note that this currently requires Rust 1.50.
|
|||||||
|
|
||||||
If you want to cross compile Conduit to another architecture, read the [Cross-Compile Guide](CROSS_COMPILE.md).
|
If you want to cross compile Conduit to another architecture, read the [Cross-Compile Guide](CROSS_COMPILE.md).
|
||||||
|
|
||||||
|
|
||||||
## Adding a Conduit user
|
## Adding a Conduit user
|
||||||
|
|
||||||
While Conduit can run as any user it is usually better to use dedicated users for different services.
|
While Conduit can run as any user it is usually better to use dedicated users for different services.
|
||||||
@@ -106,11 +114,13 @@ allow_federation = true
|
|||||||
|
|
||||||
trusted_servers = ["matrix.org"]
|
trusted_servers = ["matrix.org"]
|
||||||
|
|
||||||
#db_cache_capacity = 1073741824 # in bytes, 1024 * 1024 * 1024
|
|
||||||
#max_concurrent_requests = 100 # How many requests Conduit sends to other servers at the same time
|
#max_concurrent_requests = 100 # How many requests Conduit sends to other servers at the same time
|
||||||
#workers = 4 # default: cpu core count * 2
|
#workers = 4 # default: cpu core count * 2
|
||||||
|
|
||||||
address = "127.0.0.1" # This makes sure Conduit can only be reached using the reverse proxy
|
address = "127.0.0.1" # This makes sure Conduit can only be reached using the reverse proxy
|
||||||
|
|
||||||
|
# The total amount of memory that the database will use.
|
||||||
|
#db_cache_capacity_mb = 200
|
||||||
```
|
```
|
||||||
|
|
||||||
## Setting the correct file permissions
|
## Setting the correct file permissions
|
||||||
|
|||||||
+8
-13
@@ -5,7 +5,7 @@
|
|||||||
|
|
||||||
########################## BUILD IMAGE ##########################
|
########################## BUILD IMAGE ##########################
|
||||||
# Alpine build image to build Conduit's statically compiled binary
|
# Alpine build image to build Conduit's statically compiled binary
|
||||||
FROM alpine:3.12 as builder
|
FROM alpine:3.14 as builder
|
||||||
|
|
||||||
# Specifies if the local project is build or if Conduit gets build
|
# Specifies if the local project is build or if Conduit gets build
|
||||||
# from the official git repository. Defaults to the git repo.
|
# from the official git repository. Defaults to the git repo.
|
||||||
@@ -13,11 +13,6 @@ ARG LOCAL=false
|
|||||||
# Specifies which revision/commit is build. Defaults to HEAD
|
# Specifies which revision/commit is build. Defaults to HEAD
|
||||||
ARG GIT_REF=origin/master
|
ARG GIT_REF=origin/master
|
||||||
|
|
||||||
# Add 'edge'-repository to get Rust 1.45
|
|
||||||
RUN sed -i \
|
|
||||||
-e 's|v3\.12|edge|' \
|
|
||||||
/etc/apk/repositories
|
|
||||||
|
|
||||||
# Install packages needed for building all crates
|
# Install packages needed for building all crates
|
||||||
RUN apk add --no-cache \
|
RUN apk add --no-cache \
|
||||||
cargo \
|
cargo \
|
||||||
@@ -36,7 +31,7 @@ RUN if [[ $LOCAL == "true" ]]; then \
|
|||||||
########################## RUNTIME IMAGE ##########################
|
########################## RUNTIME IMAGE ##########################
|
||||||
# Create new stage with a minimal image for the actual
|
# Create new stage with a minimal image for the actual
|
||||||
# runtime image/container
|
# runtime image/container
|
||||||
FROM alpine:3.12
|
FROM alpine:3.14
|
||||||
|
|
||||||
ARG CREATED
|
ARG CREATED
|
||||||
ARG VERSION
|
ARG VERSION
|
||||||
@@ -61,8 +56,8 @@ LABEL org.opencontainers.image.created=${CREATED} \
|
|||||||
org.label-schema.docker.build="docker build . -t matrixconduit/matrix-conduit:latest --build-arg CREATED=$(date -u +'%Y-%m-%dT%H:%M:%SZ') --build-arg VERSION=$(grep -m1 -o '[0-9].[0-9].[0-9]' Cargo.toml)" \
|
org.label-schema.docker.build="docker build . -t matrixconduit/matrix-conduit:latest --build-arg CREATED=$(date -u +'%Y-%m-%dT%H:%M:%SZ') --build-arg VERSION=$(grep -m1 -o '[0-9].[0-9].[0-9]' Cargo.toml)" \
|
||||||
maintainer="Weasy666"
|
maintainer="Weasy666"
|
||||||
|
|
||||||
# Standard port on which Rocket launches
|
# Standard port on which Conduit launches. You still need to map the port when using the docker command or docker-compose.
|
||||||
EXPOSE 8000
|
EXPOSE 6167
|
||||||
|
|
||||||
# Copy config files from context and the binary from
|
# Copy config files from context and the binary from
|
||||||
# the "builder" stage to the current stage into folder
|
# the "builder" stage to the current stage into folder
|
||||||
@@ -86,11 +81,11 @@ RUN apk add --no-cache \
|
|||||||
curl \
|
curl \
|
||||||
libgcc
|
libgcc
|
||||||
|
|
||||||
# Create a volume for the database, to persist its contents
|
|
||||||
VOLUME ["/srv/conduit/.local/share/conduit"]
|
|
||||||
|
|
||||||
# Test if Conduit is still alive, uses the same endpoint as Element
|
# Test if Conduit is still alive, uses the same endpoint as Element
|
||||||
HEALTHCHECK --start-period=2s CMD curl --fail -s http://localhost:8000/_matrix/client/versions || curl -k --fail -s https://localhost:8000/_matrix/client/versions || exit 1
|
HEALTHCHECK --start-period=5s \
|
||||||
|
CMD curl --fail -s "http://localhost:$(grep -m1 -o 'port\s=\s[0-9]*' conduit.toml | grep -m1 -o '[0-9]*')/_matrix/client/versions" || \
|
||||||
|
curl -k --fail -s "https://localhost:$(grep -m1 -o 'port\s=\s[0-9]*' conduit.toml | grep -m1 -o '[0-9]*')/_matrix/client/versions" || \
|
||||||
|
exit 1
|
||||||
|
|
||||||
# Set user to www-data
|
# Set user to www-data
|
||||||
USER www-data
|
USER www-data
|
||||||
|
|||||||
@@ -38,8 +38,8 @@ are not aware of such a bug today, but we would like to do more testing.
|
|||||||
There are still a few important features missing:
|
There are still a few important features missing:
|
||||||
|
|
||||||
- Database stability (currently you might have to do manual upgrades or even wipe the db for new versions)
|
- Database stability (currently you might have to do manual upgrades or even wipe the db for new versions)
|
||||||
- End-to-end encrypted chats over federation
|
- Edge cases for end-to-end encryption over federation
|
||||||
- Typing, presence, read receipts etc. over federation
|
- Typing and presence over federation
|
||||||
- Lots of testing
|
- Lots of testing
|
||||||
|
|
||||||
Check out the [Conduit 1.0 Release Milestone](https://gitlab.com/famedly/conduit/-/milestones/3).
|
Check out the [Conduit 1.0 Release Milestone](https://gitlab.com/famedly/conduit/-/milestones/3).
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
#server_name = "your.server.name"
|
#server_name = "your.server.name"
|
||||||
|
|
||||||
# This is the only directory where Conduit will save its data
|
# This is the only directory where Conduit will save its data
|
||||||
database_path = "/var/lib/conduit/conduit.db"
|
database_path = "/var/lib/conduit/"
|
||||||
|
|
||||||
# The port Conduit will be running on. You need to set up a reverse proxy in
|
# The port Conduit will be running on. You need to set up a reverse proxy in
|
||||||
# your web server (e.g. apache or nginx), so all requests to /_matrix on port
|
# your web server (e.g. apache or nginx), so all requests to /_matrix on port
|
||||||
@@ -35,7 +35,6 @@ max_request_size = 20_000_000 # in bytes
|
|||||||
|
|
||||||
trusted_servers = ["matrix.org"]
|
trusted_servers = ["matrix.org"]
|
||||||
|
|
||||||
#db_cache_capacity = 1073741824 # in bytes, 1024 * 1024 * 1024
|
|
||||||
#max_concurrent_requests = 100 # How many requests Conduit sends to other servers at the same time
|
#max_concurrent_requests = 100 # How many requests Conduit sends to other servers at the same time
|
||||||
#log = "info,state_res=warn,rocket=off,_=off,sled=off"
|
#log = "info,state_res=warn,rocket=off,_=off,sled=off"
|
||||||
#workers = 4 # default: cpu core count * 2
|
#workers = 4 # default: cpu core count * 2
|
||||||
@@ -43,3 +42,6 @@ trusted_servers = ["matrix.org"]
|
|||||||
address = "127.0.0.1" # This makes sure Conduit can only be reached using the reverse proxy
|
address = "127.0.0.1" # This makes sure Conduit can only be reached using the reverse proxy
|
||||||
|
|
||||||
proxy = "none" # more examples can be found at src/database/proxy.rs:6
|
proxy = "none" # more examples can be found at src/database/proxy.rs:6
|
||||||
|
|
||||||
|
# The total amount of memory that the database will use.
|
||||||
|
#db_cache_capacity_mb = 200
|
||||||
|
|||||||
Vendored
+3
-1
@@ -73,10 +73,12 @@ max_request_size = 20_000_000 # in bytes
|
|||||||
# Enable jaeger to support monitoring and troubleshooting through jaeger.
|
# Enable jaeger to support monitoring and troubleshooting through jaeger.
|
||||||
#allow_jaeger = false
|
#allow_jaeger = false
|
||||||
|
|
||||||
#db_cache_capacity = 1073741824 # in bytes, 1024 * 1024 * 1024
|
|
||||||
#max_concurrent_requests = 100 # How many requests Conduit sends to other servers at the same time
|
#max_concurrent_requests = 100 # How many requests Conduit sends to other servers at the same time
|
||||||
#log = "info,state_res=warn,rocket=off,_=off,sled=off"
|
#log = "info,state_res=warn,rocket=off,_=off,sled=off"
|
||||||
#workers = 4 # default: cpu core count * 2
|
#workers = 4 # default: cpu core count * 2
|
||||||
|
|
||||||
|
# The total amount of memory that the database will use.
|
||||||
|
#db_cache_capacity_mb = 200
|
||||||
EOF
|
EOF
|
||||||
fi
|
fi
|
||||||
;;
|
;;
|
||||||
|
|||||||
+13
-13
@@ -3,33 +3,33 @@ version: '3'
|
|||||||
|
|
||||||
services:
|
services:
|
||||||
homeserver:
|
homeserver:
|
||||||
### If you already built the Conduit image with 'docker build' or want to use the Docker Hub image,
|
### If you already built the Conduit image with 'docker build' or want to use a registry image,
|
||||||
### then you are ready to go.
|
### then you are ready to go.
|
||||||
#image: matrixconduit/matrix-conduit:latest
|
image: matrixconduit/matrix-conduit:latest
|
||||||
### If you want to build a fresh image from the sources, then comment the image line and uncomment the
|
### If you want to build a fresh image from the sources, then comment the image line and uncomment the
|
||||||
### build lines. If you want meaningful labels in your built Conduit image, you should run docker-compose like this:
|
### build lines. If you want meaningful labels in your built Conduit image, you should run docker-compose like this:
|
||||||
### CREATED=$(date -u +'%Y-%m-%dT%H:%M:%SZ') VERSION=$(grep -m1 -o '[0-9].[0-9].[0-9]' Cargo.toml) docker-compose up -d
|
### CREATED=$(date -u +'%Y-%m-%dT%H:%M:%SZ') VERSION=$(grep -m1 -o '[0-9].[0-9].[0-9]' Cargo.toml) docker-compose up -d
|
||||||
build:
|
# build:
|
||||||
context: .
|
# context: .
|
||||||
args:
|
# args:
|
||||||
CREATED: '2021-03-16T08:18:27Z'
|
# CREATED: '2021-03-16T08:18:27Z'
|
||||||
VERSION: '0.1.0'
|
# VERSION: '0.1.0'
|
||||||
LOCAL: 'false'
|
# LOCAL: 'false'
|
||||||
GIT_REF: origin/master
|
# GIT_REF: origin/master
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
ports:
|
ports:
|
||||||
- 8448:8000
|
- 8448:6167
|
||||||
volumes:
|
volumes:
|
||||||
- db:/srv/conduit/.local/share/conduit
|
- db:/srv/conduit/.local/share/conduit
|
||||||
### Uncomment if you want to use conduit.toml to configure Conduit
|
### Uncomment if you want to use conduit.toml to configure Conduit
|
||||||
### Note: Set env vars will override conduit.toml values
|
### Note: Set env vars will override conduit.toml values
|
||||||
# - ./conduit.toml:/srv/conduit/conduit.toml
|
# - ./conduit.toml:/srv/conduit/conduit.toml
|
||||||
environment:
|
environment:
|
||||||
CONDUIT_SERVER_NAME: localhost:8000 # replace with your own name
|
CONDUIT_SERVER_NAME: localhost:6167 # replace with your own name
|
||||||
CONDUIT_TRUSTED_SERVERS: '["matrix.org"]'
|
CONDUIT_TRUSTED_SERVERS: '["matrix.org"]'
|
||||||
### Uncomment and change values as desired
|
### Uncomment and change values as desired
|
||||||
# CONDUIT_ADDRESS: 127.0.0.1
|
# CONDUIT_ADDRESS: 0.0.0.0
|
||||||
# CONDUIT_PORT: 8000
|
# CONDUIT_PORT: 6167
|
||||||
# CONDUIT_CONFIG: '/srv/conduit/conduit.toml' # if you want to configure purely by env vars, set this to an empty string ''
|
# CONDUIT_CONFIG: '/srv/conduit/conduit.toml' # if you want to configure purely by env vars, set this to an empty string ''
|
||||||
# Available levels are: error, warn, info, debug, trace - more info at: https://docs.rs/env_logger/*/env_logger/#enabling-logging
|
# Available levels are: error, warn, info, debug, trace - more info at: https://docs.rs/env_logger/*/env_logger/#enabling-logging
|
||||||
# CONDUIT_LOG: info # default is: "info,rocket=off,_=off,sled=off"
|
# CONDUIT_LOG: info # default is: "info,rocket=off,_=off,sled=off"
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
# ---------------------------------------------------------------------------------------------------------
|
||||||
|
# This Dockerfile is intended to be built as part of Conduit's CI pipeline.
|
||||||
|
# It does not build Conduit in Docker, but just copies the matching build artifact from the build job.
|
||||||
|
# As a consequence, this is not a multiarch capable image. It always expects and packages a x86_64 binary.
|
||||||
|
#
|
||||||
|
# It is mostly based on the normal Conduit Dockerfile, but adjusted in a few places to maximise caching.
|
||||||
|
# Credit's for the original Dockerfile: Weasy666.
|
||||||
|
# ---------------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
FROM alpine:3.14
|
||||||
|
|
||||||
|
ARG CREATED
|
||||||
|
ARG VERSION
|
||||||
|
ARG GIT_REF
|
||||||
|
|
||||||
|
ENV CONDUIT_CONFIG="/srv/conduit/conduit.toml"
|
||||||
|
|
||||||
|
# Labels according to https://github.com/opencontainers/image-spec/blob/master/annotations.md
|
||||||
|
# including a custom label specifying the build command
|
||||||
|
LABEL org.opencontainers.image.created=${CREATED} \
|
||||||
|
org.opencontainers.image.authors="Conduit Contributors" \
|
||||||
|
org.opencontainers.image.title="Conduit" \
|
||||||
|
org.opencontainers.image.version=${VERSION} \
|
||||||
|
org.opencontainers.image.vendor="Conduit Contributors" \
|
||||||
|
org.opencontainers.image.description="A Matrix homeserver written in Rust" \
|
||||||
|
org.opencontainers.image.url="https://conduit.rs/" \
|
||||||
|
org.opencontainers.image.revision=${GIT_REF} \
|
||||||
|
org.opencontainers.image.source="https://gitlab.com/famedly/conduit.git" \
|
||||||
|
org.opencontainers.image.licenses="Apache-2.0" \
|
||||||
|
org.opencontainers.image.documentation="" \
|
||||||
|
org.opencontainers.image.ref.name=""
|
||||||
|
|
||||||
|
# Standard port on which Conduit launches. You still need to map the port when using the docker command or docker-compose.
|
||||||
|
EXPOSE 6167
|
||||||
|
|
||||||
|
# create data folder for database
|
||||||
|
RUN mkdir -p /srv/conduit/.local/share/conduit
|
||||||
|
|
||||||
|
# Add www-data user and group with UID 82, as used by alpine
|
||||||
|
# https://git.alpinelinux.org/aports/tree/main/nginx/nginx.pre-install
|
||||||
|
RUN set -x ; \
|
||||||
|
addgroup -Sg 82 www-data 2>/dev/null ; \
|
||||||
|
adduser -S -D -H -h /srv/conduit -G www-data -g www-data www-data 2>/dev/null ; \
|
||||||
|
addgroup www-data www-data 2>/dev/null && exit 0 ; exit 1
|
||||||
|
|
||||||
|
# Change ownership of Conduit files to www-data user and group
|
||||||
|
RUN chown -cR www-data:www-data /srv/conduit
|
||||||
|
|
||||||
|
# Install packages needed to run Conduit
|
||||||
|
RUN apk add --no-cache \
|
||||||
|
ca-certificates \
|
||||||
|
curl \
|
||||||
|
libgcc
|
||||||
|
|
||||||
|
# Test if Conduit is still alive, uses the same endpoint as Element
|
||||||
|
HEALTHCHECK --start-period=5s \
|
||||||
|
CMD curl --fail -s "http://localhost:$(grep -m1 -o 'port\s=\s[0-9]*' conduit.toml | grep -m1 -o '[0-9]*')/_matrix/client/versions" || \
|
||||||
|
curl -k --fail -s "https://localhost:$(grep -m1 -o 'port\s=\s[0-9]*' conduit.toml | grep -m1 -o '[0-9]*')/_matrix/client/versions" || \
|
||||||
|
exit 1
|
||||||
|
|
||||||
|
# Set user to www-data
|
||||||
|
USER www-data
|
||||||
|
# Set container home directory
|
||||||
|
WORKDIR /srv/conduit
|
||||||
|
# Run Conduit
|
||||||
|
ENTRYPOINT [ "/srv/conduit/conduit" ]
|
||||||
|
|
||||||
|
|
||||||
|
# Copy the Conduit binary into the image at the latest possible moment to maximise caching:
|
||||||
|
COPY ./conduit-x86_64-unknown-linux-musl /srv/conduit/conduit
|
||||||
@@ -12,8 +12,8 @@ services:
|
|||||||
# build:
|
# build:
|
||||||
# context: .
|
# context: .
|
||||||
# args:
|
# args:
|
||||||
# CREATED:
|
# CREATED: '2021-03-16T08:18:27Z'
|
||||||
# VERSION:
|
# VERSION: '0.1.0'
|
||||||
# LOCAL: 'false'
|
# LOCAL: 'false'
|
||||||
# GIT_REF: origin/master
|
# GIT_REF: origin/master
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
@@ -25,12 +25,12 @@ services:
|
|||||||
networks:
|
networks:
|
||||||
- proxy
|
- proxy
|
||||||
environment:
|
environment:
|
||||||
CONDUIT_SERVER_NAME: localhost:8000 # replace with your own name
|
CONDUIT_SERVER_NAME: localhost:6167 # replace with your own name
|
||||||
CONDUIT_TRUSTED_SERVERS: '["matrix.org"]'
|
CONDUIT_TRUSTED_SERVERS: '["matrix.org"]'
|
||||||
### Uncomment and change values as desired
|
### Uncomment and change values as desired
|
||||||
# CONDUIT_ADDRESS: 127.0.0.1
|
# CONDUIT_ADDRESS: 0.0.0.0
|
||||||
# CONDUIT_PORT: 8000
|
# CONDUIT_PORT: 6167
|
||||||
# CONDUIT_CONFIG: '/srv/conduit/conduit.toml' # if want to configure purely by env vars, set this to an empty string ''
|
# CONDUIT_CONFIG: '/srv/conduit/conduit.toml' # if you want to configure purely by env vars, set this to an empty string ''
|
||||||
# Available levels are: error, warn, info, debug, trace - more info at: https://docs.rs/env_logger/*/env_logger/#enabling-logging
|
# Available levels are: error, warn, info, debug, trace - more info at: https://docs.rs/env_logger/*/env_logger/#enabling-logging
|
||||||
# CONDUIT_LOG: info # default is: "info,rocket=off,_=off,sled=off"
|
# CONDUIT_LOG: info # default is: "info,rocket=off,_=off,sled=off"
|
||||||
# CONDUIT_ALLOW_JAEGER: 'false'
|
# CONDUIT_ALLOW_JAEGER: 'false'
|
||||||
@@ -59,7 +59,7 @@ volumes:
|
|||||||
db:
|
db:
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
# This is the network Traefik listens to, if you network has a different
|
# This is the network Traefik listens to, if your network has a different
|
||||||
# name, don't forget to change it here and in the docker-compose.override.yml
|
# name, don't forget to change it here and in the docker-compose.override.yml
|
||||||
proxy:
|
proxy:
|
||||||
external: true
|
external: true
|
||||||
|
|||||||
+1
-1
@@ -1 +1 @@
|
|||||||
1.51.0
|
1.52
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
use crate::{utils, Error, Result};
|
use crate::{utils, Error, Result};
|
||||||
use bytes::BytesMut;
|
use bytes::BytesMut;
|
||||||
use log::warn;
|
|
||||||
use ruma::api::{IncomingResponse, OutgoingRequest, SendAccessToken};
|
use ruma::api::{IncomingResponse, OutgoingRequest, SendAccessToken};
|
||||||
use std::{
|
use std::{
|
||||||
convert::{TryFrom, TryInto},
|
convert::{TryFrom, TryInto},
|
||||||
@@ -8,6 +7,7 @@ use std::{
|
|||||||
mem,
|
mem,
|
||||||
time::Duration,
|
time::Duration,
|
||||||
};
|
};
|
||||||
|
use tracing::warn;
|
||||||
|
|
||||||
pub async fn send_request<T: OutgoingRequest>(
|
pub async fn send_request<T: OutgoingRequest>(
|
||||||
globals: &crate::database::globals::Globals,
|
globals: &crate::database::globals::Globals,
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
use std::{collections::BTreeMap, convert::TryInto, sync::Arc};
|
use std::{
|
||||||
|
collections::BTreeMap,
|
||||||
|
convert::{TryFrom, TryInto},
|
||||||
|
sync::Arc,
|
||||||
|
};
|
||||||
|
|
||||||
use super::{DEVICE_ID_LENGTH, SESSION_ID_LENGTH, TOKEN_LENGTH};
|
use super::{DEVICE_ID_LENGTH, SESSION_ID_LENGTH, TOKEN_LENGTH};
|
||||||
use crate::{database::DatabaseGuard, pdu::PduBuilder, utils, ConduitResult, Error, Ruma};
|
use crate::{database::DatabaseGuard, pdu::PduBuilder, utils, ConduitResult, Error, Ruma};
|
||||||
use log::info;
|
|
||||||
use ruma::{
|
use ruma::{
|
||||||
api::client::{
|
api::client::{
|
||||||
error::ErrorKind,
|
error::ErrorKind,
|
||||||
@@ -11,6 +14,7 @@ use ruma::{
|
|||||||
change_password, deactivate, get_username_availability, register, whoami,
|
change_password, deactivate, get_username_availability, register, whoami,
|
||||||
ThirdPartyIdRemovalStatus,
|
ThirdPartyIdRemovalStatus,
|
||||||
},
|
},
|
||||||
|
contact::get_contacts,
|
||||||
uiaa::{AuthFlow, UiaaInfo},
|
uiaa::{AuthFlow, UiaaInfo},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -21,8 +25,10 @@ use ruma::{
|
|||||||
},
|
},
|
||||||
EventType,
|
EventType,
|
||||||
},
|
},
|
||||||
|
identifiers::RoomName,
|
||||||
push, RoomAliasId, RoomId, RoomVersionId, UserId,
|
push, RoomAliasId, RoomId, RoomVersionId, UserId,
|
||||||
};
|
};
|
||||||
|
use tracing::info;
|
||||||
|
|
||||||
use register::RegistrationKind;
|
use register::RegistrationKind;
|
||||||
#[cfg(feature = "conduit_bin")]
|
#[cfg(feature = "conduit_bin")]
|
||||||
@@ -156,16 +162,18 @@ pub async fn register_route(
|
|||||||
return Err(Error::Uiaa(uiaainfo));
|
return Err(Error::Uiaa(uiaainfo));
|
||||||
}
|
}
|
||||||
// Success!
|
// Success!
|
||||||
} else {
|
} else if let Some(json) = body.json_body {
|
||||||
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
||||||
db.uiaa.create(
|
db.uiaa.create(
|
||||||
&UserId::parse_with_server_name("", db.globals.server_name())
|
&UserId::parse_with_server_name("", db.globals.server_name())
|
||||||
.expect("we know this is valid"),
|
.expect("we know this is valid"),
|
||||||
"".into(),
|
"".into(),
|
||||||
&uiaainfo,
|
&uiaainfo,
|
||||||
&body.json_body.expect("body is json"),
|
&json,
|
||||||
)?;
|
)?;
|
||||||
return Err(Error::Uiaa(uiaainfo));
|
return Err(Error::Uiaa(uiaainfo));
|
||||||
|
} else {
|
||||||
|
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,6 +193,11 @@ pub async fn register_route(
|
|||||||
// Create user
|
// Create user
|
||||||
db.users.create(&user_id, password)?;
|
db.users.create(&user_id, password)?;
|
||||||
|
|
||||||
|
let displayname = format!("{} ⚡️", user_id.localpart());
|
||||||
|
|
||||||
|
db.users
|
||||||
|
.set_displayname(&user_id, Some(displayname.clone()))?;
|
||||||
|
|
||||||
// Initial data
|
// Initial data
|
||||||
db.account_data.update(
|
db.account_data.update(
|
||||||
None,
|
None,
|
||||||
@@ -236,15 +249,15 @@ pub async fn register_route(
|
|||||||
|
|
||||||
let room_id = RoomId::new(db.globals.server_name());
|
let room_id = RoomId::new(db.globals.server_name());
|
||||||
|
|
||||||
let mutex = Arc::clone(
|
let mutex_state = Arc::clone(
|
||||||
db.globals
|
db.globals
|
||||||
.roomid_mutex
|
.roomid_mutex_state
|
||||||
.write()
|
.write()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.entry(room_id.clone())
|
.entry(room_id.clone())
|
||||||
.or_default(),
|
.or_default(),
|
||||||
);
|
);
|
||||||
let mutex_lock = mutex.lock().await;
|
let state_lock = mutex_state.lock().await;
|
||||||
|
|
||||||
let mut content = ruma::events::room::create::CreateEventContent::new(conduit_user.clone());
|
let mut content = ruma::events::room::create::CreateEventContent::new(conduit_user.clone());
|
||||||
content.federate = true;
|
content.federate = true;
|
||||||
@@ -263,7 +276,7 @@ pub async fn register_route(
|
|||||||
&conduit_user,
|
&conduit_user,
|
||||||
&room_id,
|
&room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
// 2. Make conduit bot join
|
// 2. Make conduit bot join
|
||||||
@@ -276,6 +289,7 @@ pub async fn register_route(
|
|||||||
avatar_url: None,
|
avatar_url: None,
|
||||||
is_direct: None,
|
is_direct: None,
|
||||||
third_party_invite: None,
|
third_party_invite: None,
|
||||||
|
blurhash: None,
|
||||||
})
|
})
|
||||||
.expect("event is valid, we just created it"),
|
.expect("event is valid, we just created it"),
|
||||||
unsigned: None,
|
unsigned: None,
|
||||||
@@ -285,7 +299,7 @@ pub async fn register_route(
|
|||||||
&conduit_user,
|
&conduit_user,
|
||||||
&room_id,
|
&room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
// 3. Power levels
|
// 3. Power levels
|
||||||
@@ -310,7 +324,7 @@ pub async fn register_route(
|
|||||||
&conduit_user,
|
&conduit_user,
|
||||||
&room_id,
|
&room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
// 4.1 Join Rules
|
// 4.1 Join Rules
|
||||||
@@ -328,7 +342,7 @@ pub async fn register_route(
|
|||||||
&conduit_user,
|
&conduit_user,
|
||||||
&room_id,
|
&room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
// 4.2 History Visibility
|
// 4.2 History Visibility
|
||||||
@@ -348,7 +362,7 @@ pub async fn register_route(
|
|||||||
&conduit_user,
|
&conduit_user,
|
||||||
&room_id,
|
&room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
// 4.3 Guest Access
|
// 4.3 Guest Access
|
||||||
@@ -366,19 +380,18 @@ pub async fn register_route(
|
|||||||
&conduit_user,
|
&conduit_user,
|
||||||
&room_id,
|
&room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
// 6. Events implied by name and topic
|
// 6. Events implied by name and topic
|
||||||
|
let room_name =
|
||||||
|
Box::<RoomName>::try_from(format!("{} Admin Room", db.globals.server_name()))
|
||||||
|
.expect("Room name is valid");
|
||||||
db.rooms.build_and_append_pdu(
|
db.rooms.build_and_append_pdu(
|
||||||
PduBuilder {
|
PduBuilder {
|
||||||
event_type: EventType::RoomName,
|
event_type: EventType::RoomName,
|
||||||
content: serde_json::to_value(
|
content: serde_json::to_value(name::NameEventContent::new(Some(room_name)))
|
||||||
name::NameEventContent::new("Admin Room".to_owned()).map_err(|_| {
|
.expect("event is valid, we just created it"),
|
||||||
Error::BadRequest(ErrorKind::InvalidParam, "Name is invalid.")
|
|
||||||
})?,
|
|
||||||
)
|
|
||||||
.expect("event is valid, we just created it"),
|
|
||||||
unsigned: None,
|
unsigned: None,
|
||||||
state_key: Some("".to_owned()),
|
state_key: Some("".to_owned()),
|
||||||
redacts: None,
|
redacts: None,
|
||||||
@@ -386,7 +399,7 @@ pub async fn register_route(
|
|||||||
&conduit_user,
|
&conduit_user,
|
||||||
&room_id,
|
&room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
db.rooms.build_and_append_pdu(
|
db.rooms.build_and_append_pdu(
|
||||||
@@ -403,7 +416,7 @@ pub async fn register_route(
|
|||||||
&conduit_user,
|
&conduit_user,
|
||||||
&room_id,
|
&room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
// Room alias
|
// Room alias
|
||||||
@@ -426,7 +439,7 @@ pub async fn register_route(
|
|||||||
&conduit_user,
|
&conduit_user,
|
||||||
&room_id,
|
&room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
db.rooms.set_alias(&alias, Some(&room_id), &db.globals)?;
|
db.rooms.set_alias(&alias, Some(&room_id), &db.globals)?;
|
||||||
@@ -441,6 +454,7 @@ pub async fn register_route(
|
|||||||
avatar_url: None,
|
avatar_url: None,
|
||||||
is_direct: None,
|
is_direct: None,
|
||||||
third_party_invite: None,
|
third_party_invite: None,
|
||||||
|
blurhash: None,
|
||||||
})
|
})
|
||||||
.expect("event is valid, we just created it"),
|
.expect("event is valid, we just created it"),
|
||||||
unsigned: None,
|
unsigned: None,
|
||||||
@@ -450,17 +464,18 @@ pub async fn register_route(
|
|||||||
&conduit_user,
|
&conduit_user,
|
||||||
&room_id,
|
&room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
db.rooms.build_and_append_pdu(
|
db.rooms.build_and_append_pdu(
|
||||||
PduBuilder {
|
PduBuilder {
|
||||||
event_type: EventType::RoomMember,
|
event_type: EventType::RoomMember,
|
||||||
content: serde_json::to_value(member::MemberEventContent {
|
content: serde_json::to_value(member::MemberEventContent {
|
||||||
membership: member::MembershipState::Join,
|
membership: member::MembershipState::Join,
|
||||||
displayname: None,
|
displayname: Some(displayname),
|
||||||
avatar_url: None,
|
avatar_url: None,
|
||||||
is_direct: None,
|
is_direct: None,
|
||||||
third_party_invite: None,
|
third_party_invite: None,
|
||||||
|
blurhash: None,
|
||||||
})
|
})
|
||||||
.expect("event is valid, we just created it"),
|
.expect("event is valid, we just created it"),
|
||||||
unsigned: None,
|
unsigned: None,
|
||||||
@@ -470,7 +485,7 @@ pub async fn register_route(
|
|||||||
&user_id,
|
&user_id,
|
||||||
&room_id,
|
&room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
// Send welcome message
|
// Send welcome message
|
||||||
@@ -489,13 +504,13 @@ pub async fn register_route(
|
|||||||
&conduit_user,
|
&conduit_user,
|
||||||
&room_id,
|
&room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
info!("{} registered on this server", user_id);
|
info!("{} registered on this server", user_id);
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(register::Response {
|
Ok(register::Response {
|
||||||
access_token: Some(token),
|
access_token: Some(token),
|
||||||
@@ -547,15 +562,13 @@ pub async fn change_password_route(
|
|||||||
return Err(Error::Uiaa(uiaainfo));
|
return Err(Error::Uiaa(uiaainfo));
|
||||||
}
|
}
|
||||||
// Success!
|
// Success!
|
||||||
} else {
|
} else if let Some(json) = body.json_body {
|
||||||
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
||||||
db.uiaa.create(
|
db.uiaa
|
||||||
&sender_user,
|
.create(&sender_user, &sender_device, &uiaainfo, &json)?;
|
||||||
&sender_device,
|
|
||||||
&uiaainfo,
|
|
||||||
&body.json_body.expect("body is json"),
|
|
||||||
)?;
|
|
||||||
return Err(Error::Uiaa(uiaainfo));
|
return Err(Error::Uiaa(uiaainfo));
|
||||||
|
} else {
|
||||||
|
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
|
||||||
}
|
}
|
||||||
|
|
||||||
db.users
|
db.users
|
||||||
@@ -573,9 +586,9 @@ pub async fn change_password_route(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(change_password::Response.into())
|
Ok(change_password::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// # `GET _matrix/client/r0/account/whoami`
|
/// # `GET _matrix/client/r0/account/whoami`
|
||||||
@@ -639,23 +652,27 @@ pub async fn deactivate_route(
|
|||||||
return Err(Error::Uiaa(uiaainfo));
|
return Err(Error::Uiaa(uiaainfo));
|
||||||
}
|
}
|
||||||
// Success!
|
// Success!
|
||||||
} else {
|
} else if let Some(json) = body.json_body {
|
||||||
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
||||||
db.uiaa.create(
|
db.uiaa
|
||||||
&sender_user,
|
.create(&sender_user, &sender_device, &uiaainfo, &json)?;
|
||||||
&sender_device,
|
|
||||||
&uiaainfo,
|
|
||||||
&body.json_body.expect("body is json"),
|
|
||||||
)?;
|
|
||||||
return Err(Error::Uiaa(uiaainfo));
|
return Err(Error::Uiaa(uiaainfo));
|
||||||
|
} else {
|
||||||
|
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Leave all joined rooms and reject all invitations
|
// Leave all joined rooms and reject all invitations
|
||||||
for room_id in db.rooms.rooms_joined(&sender_user).chain(
|
let all_rooms = db
|
||||||
db.rooms
|
.rooms
|
||||||
.rooms_invited(&sender_user)
|
.rooms_joined(&sender_user)
|
||||||
.map(|t| t.map(|(r, _)| r)),
|
.chain(
|
||||||
) {
|
db.rooms
|
||||||
|
.rooms_invited(&sender_user)
|
||||||
|
.map(|t| t.map(|(r, _)| r)),
|
||||||
|
)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
for room_id in all_rooms {
|
||||||
let room_id = room_id?;
|
let room_id = room_id?;
|
||||||
let event = member::MemberEventContent {
|
let event = member::MemberEventContent {
|
||||||
membership: member::MembershipState::Leave,
|
membership: member::MembershipState::Leave,
|
||||||
@@ -663,17 +680,18 @@ pub async fn deactivate_route(
|
|||||||
avatar_url: None,
|
avatar_url: None,
|
||||||
is_direct: None,
|
is_direct: None,
|
||||||
third_party_invite: None,
|
third_party_invite: None,
|
||||||
|
blurhash: None,
|
||||||
};
|
};
|
||||||
|
|
||||||
let mutex = Arc::clone(
|
let mutex_state = Arc::clone(
|
||||||
db.globals
|
db.globals
|
||||||
.roomid_mutex
|
.roomid_mutex_state
|
||||||
.write()
|
.write()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.entry(room_id.clone())
|
.entry(room_id.clone())
|
||||||
.or_default(),
|
.or_default(),
|
||||||
);
|
);
|
||||||
let mutex_lock = mutex.lock().await;
|
let state_lock = mutex_state.lock().await;
|
||||||
|
|
||||||
db.rooms.build_and_append_pdu(
|
db.rooms.build_and_append_pdu(
|
||||||
PduBuilder {
|
PduBuilder {
|
||||||
@@ -686,7 +704,7 @@ pub async fn deactivate_route(
|
|||||||
&sender_user,
|
&sender_user,
|
||||||
&room_id,
|
&room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -695,7 +713,7 @@ pub async fn deactivate_route(
|
|||||||
|
|
||||||
info!("{} deactivated their account", sender_user);
|
info!("{} deactivated their account", sender_user);
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(deactivate::Response {
|
Ok(deactivate::Response {
|
||||||
id_server_unbind_result: ThirdPartyIdRemovalStatus::NoSupport,
|
id_server_unbind_result: ThirdPartyIdRemovalStatus::NoSupport,
|
||||||
@@ -703,16 +721,17 @@ pub async fn deactivate_route(
|
|||||||
.into())
|
.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
/*/
|
/// # `GET _matrix/client/r0/account/3pid`
|
||||||
|
///
|
||||||
|
/// Get a list of third party identifiers associated with this account.
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
feature = "conduit_bin",
|
feature = "conduit_bin",
|
||||||
get("/_matrix/client/r0/account/3pid", data = "<body>")
|
get("/_matrix/client/r0/account/3pid", data = "<body>")
|
||||||
)]
|
)]
|
||||||
pub async fn third_party_route(
|
pub async fn third_party_route(
|
||||||
body: Ruma<account::add_3pid::Request<'_>>,
|
body: Ruma<get_contacts::Request>,
|
||||||
) -> ConduitResult<account::add_3pid::Response> {
|
) -> ConduitResult<get_contacts::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
|
|
||||||
Ok(account::add_3pid::Response::default().into())
|
Ok(get_contacts::Response::new(Vec::new()).into())
|
||||||
}
|
}
|
||||||
*/
|
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ pub async fn create_alias_route(
|
|||||||
db.rooms
|
db.rooms
|
||||||
.set_alias(&body.room_alias, Some(&body.room_id), &db.globals)?;
|
.set_alias(&body.room_alias, Some(&body.room_id), &db.globals)?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(create_alias::Response::new().into())
|
Ok(create_alias::Response::new().into())
|
||||||
}
|
}
|
||||||
@@ -47,7 +47,7 @@ pub async fn delete_alias_route(
|
|||||||
) -> ConduitResult<delete_alias::Response> {
|
) -> ConduitResult<delete_alias::Response> {
|
||||||
db.rooms.set_alias(&body.room_alias, None, &db.globals)?;
|
db.rooms.set_alias(&body.room_alias, None, &db.globals)?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(delete_alias::Response::new().into())
|
Ok(delete_alias::Response::new().into())
|
||||||
}
|
}
|
||||||
@@ -85,8 +85,7 @@ pub async fn get_alias_helper(
|
|||||||
match db.rooms.id_from_alias(&room_alias)? {
|
match db.rooms.id_from_alias(&room_alias)? {
|
||||||
Some(r) => room_id = Some(r),
|
Some(r) => room_id = Some(r),
|
||||||
None => {
|
None => {
|
||||||
let iter = db.appservice.iter_all()?;
|
for (_id, registration) in db.appservice.all()? {
|
||||||
for (_id, registration) in iter.filter_map(|r| r.ok()) {
|
|
||||||
let aliases = registration
|
let aliases = registration
|
||||||
.get("namespaces")
|
.get("namespaces")
|
||||||
.and_then(|ns| ns.get("aliases"))
|
.and_then(|ns| ns.get("aliases"))
|
||||||
|
|||||||
+11
-11
@@ -26,7 +26,7 @@ pub async fn create_backup_route(
|
|||||||
.key_backups
|
.key_backups
|
||||||
.create_backup(&sender_user, &body.algorithm, &db.globals)?;
|
.create_backup(&sender_user, &body.algorithm, &db.globals)?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(create_backup::Response { version }.into())
|
Ok(create_backup::Response { version }.into())
|
||||||
}
|
}
|
||||||
@@ -44,9 +44,9 @@ pub async fn update_backup_route(
|
|||||||
db.key_backups
|
db.key_backups
|
||||||
.update_backup(&sender_user, &body.version, &body.algorithm, &db.globals)?;
|
.update_backup(&sender_user, &body.version, &body.algorithm, &db.globals)?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(update_backup::Response.into())
|
Ok(update_backup::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
@@ -117,9 +117,9 @@ pub async fn delete_backup_route(
|
|||||||
|
|
||||||
db.key_backups.delete_backup(&sender_user, &body.version)?;
|
db.key_backups.delete_backup(&sender_user, &body.version)?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(delete_backup::Response.into())
|
Ok(delete_backup::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Add the received backup keys to the database.
|
/// Add the received backup keys to the database.
|
||||||
@@ -147,7 +147,7 @@ pub async fn add_backup_keys_route(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(add_backup_keys::Response {
|
Ok(add_backup_keys::Response {
|
||||||
count: (db.key_backups.count_keys(sender_user, &body.version)? as u32).into(),
|
count: (db.key_backups.count_keys(sender_user, &body.version)? as u32).into(),
|
||||||
@@ -179,7 +179,7 @@ pub async fn add_backup_key_sessions_route(
|
|||||||
)?
|
)?
|
||||||
}
|
}
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(add_backup_key_sessions::Response {
|
Ok(add_backup_key_sessions::Response {
|
||||||
count: (db.key_backups.count_keys(sender_user, &body.version)? as u32).into(),
|
count: (db.key_backups.count_keys(sender_user, &body.version)? as u32).into(),
|
||||||
@@ -209,7 +209,7 @@ pub async fn add_backup_key_session_route(
|
|||||||
&db.globals,
|
&db.globals,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(add_backup_key_session::Response {
|
Ok(add_backup_key_session::Response {
|
||||||
count: (db.key_backups.count_keys(sender_user, &body.version)? as u32).into(),
|
count: (db.key_backups.count_keys(sender_user, &body.version)? as u32).into(),
|
||||||
@@ -288,7 +288,7 @@ pub async fn delete_backup_keys_route(
|
|||||||
db.key_backups
|
db.key_backups
|
||||||
.delete_all_keys(&sender_user, &body.version)?;
|
.delete_all_keys(&sender_user, &body.version)?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(delete_backup_keys::Response {
|
Ok(delete_backup_keys::Response {
|
||||||
count: (db.key_backups.count_keys(sender_user, &body.version)? as u32).into(),
|
count: (db.key_backups.count_keys(sender_user, &body.version)? as u32).into(),
|
||||||
@@ -311,7 +311,7 @@ pub async fn delete_backup_key_sessions_route(
|
|||||||
db.key_backups
|
db.key_backups
|
||||||
.delete_room_keys(&sender_user, &body.version, &body.room_id)?;
|
.delete_room_keys(&sender_user, &body.version, &body.room_id)?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(delete_backup_key_sessions::Response {
|
Ok(delete_backup_key_sessions::Response {
|
||||||
count: (db.key_backups.count_keys(sender_user, &body.version)? as u32).into(),
|
count: (db.key_backups.count_keys(sender_user, &body.version)? as u32).into(),
|
||||||
@@ -334,7 +334,7 @@ pub async fn delete_backup_key_session_route(
|
|||||||
db.key_backups
|
db.key_backups
|
||||||
.delete_room_key(&sender_user, &body.version, &body.room_id, &body.session_id)?;
|
.delete_room_key(&sender_user, &body.version, &body.room_id, &body.session_id)?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(delete_backup_key_session::Response {
|
Ok(delete_backup_key_session::Response {
|
||||||
count: (db.key_backups.count_keys(sender_user, &body.version)? as u32).into(),
|
count: (db.key_backups.count_keys(sender_user, &body.version)? as u32).into(),
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
use crate::ConduitResult;
|
use crate::ConduitResult;
|
||||||
|
use crate::Ruma;
|
||||||
use ruma::{
|
use ruma::{
|
||||||
api::client::r0::capabilities::{
|
api::client::r0::capabilities::{
|
||||||
get_capabilities, Capabilities, RoomVersionStability, RoomVersionsCapability,
|
get_capabilities, Capabilities, RoomVersionStability, RoomVersionsCapability,
|
||||||
@@ -13,10 +14,16 @@ use rocket::get;
|
|||||||
/// # `GET /_matrix/client/r0/capabilities`
|
/// # `GET /_matrix/client/r0/capabilities`
|
||||||
///
|
///
|
||||||
/// Get information on this server's supported feature set and other relevent capabilities.
|
/// Get information on this server's supported feature set and other relevent capabilities.
|
||||||
#[cfg_attr(feature = "conduit_bin", get("/_matrix/client/r0/capabilities"))]
|
#[cfg_attr(
|
||||||
#[tracing::instrument]
|
feature = "conduit_bin",
|
||||||
pub async fn get_capabilities_route() -> ConduitResult<get_capabilities::Response> {
|
get("/_matrix/client/r0/capabilities", data = "<_body>")
|
||||||
|
)]
|
||||||
|
#[tracing::instrument(skip(_body))]
|
||||||
|
pub async fn get_capabilities_route(
|
||||||
|
_body: Ruma<get_capabilities::Request>,
|
||||||
|
) -> ConduitResult<get_capabilities::Response> {
|
||||||
let mut available = BTreeMap::new();
|
let mut available = BTreeMap::new();
|
||||||
|
available.insert(RoomVersionId::Version5, RoomVersionStability::Stable);
|
||||||
available.insert(RoomVersionId::Version6, RoomVersionStability::Stable);
|
available.insert(RoomVersionId::Version6, RoomVersionStability::Stable);
|
||||||
|
|
||||||
let mut capabilities = Capabilities::new();
|
let mut capabilities = Capabilities::new();
|
||||||
|
|||||||
@@ -43,9 +43,9 @@ pub async fn set_global_account_data_route(
|
|||||||
&db.globals,
|
&db.globals,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(set_global_account_data::Response.into())
|
Ok(set_global_account_data::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
@@ -78,9 +78,9 @@ pub async fn set_room_account_data_route(
|
|||||||
&db.globals,
|
&db.globals,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(set_room_account_data::Response.into())
|
Ok(set_room_account_data::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
@@ -98,7 +98,7 @@ pub async fn get_global_account_data_route(
|
|||||||
.account_data
|
.account_data
|
||||||
.get::<Box<RawJsonValue>>(None, sender_user, body.event_type.clone().into())?
|
.get::<Box<RawJsonValue>>(None, sender_user, body.event_type.clone().into())?
|
||||||
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Data not found."))?;
|
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Data not found."))?;
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
let account_data = serde_json::from_str::<ExtractGlobalEventContent>(event.get())
|
let account_data = serde_json::from_str::<ExtractGlobalEventContent>(event.get())
|
||||||
.map_err(|_| Error::bad_database("Invalid account data event in db."))?
|
.map_err(|_| Error::bad_database("Invalid account data event in db."))?
|
||||||
@@ -129,7 +129,7 @@ pub async fn get_room_account_data_route(
|
|||||||
body.event_type.clone().into(),
|
body.event_type.clone().into(),
|
||||||
)?
|
)?
|
||||||
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Data not found."))?;
|
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Data not found."))?;
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
let account_data = serde_json::from_str::<ExtractRoomEventContent>(event.get())
|
let account_data = serde_json::from_str::<ExtractRoomEventContent>(event.get())
|
||||||
.map_err(|_| Error::bad_database("Invalid account data event in db."))?
|
.map_err(|_| Error::bad_database("Invalid account data event in db."))?
|
||||||
|
|||||||
+16
-20
@@ -71,9 +71,9 @@ pub async fn update_device_route(
|
|||||||
db.users
|
db.users
|
||||||
.update_device_metadata(&sender_user, &body.device_id, &device)?;
|
.update_device_metadata(&sender_user, &body.device_id, &device)?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(update_device::Response.into())
|
Ok(update_device::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
@@ -112,22 +112,20 @@ pub async fn delete_device_route(
|
|||||||
return Err(Error::Uiaa(uiaainfo));
|
return Err(Error::Uiaa(uiaainfo));
|
||||||
}
|
}
|
||||||
// Success!
|
// Success!
|
||||||
} else {
|
} else if let Some(json) = body.json_body {
|
||||||
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
||||||
db.uiaa.create(
|
db.uiaa
|
||||||
&sender_user,
|
.create(&sender_user, &sender_device, &uiaainfo, &json)?;
|
||||||
&sender_device,
|
|
||||||
&uiaainfo,
|
|
||||||
&body.json_body.expect("body is json"),
|
|
||||||
)?;
|
|
||||||
return Err(Error::Uiaa(uiaainfo));
|
return Err(Error::Uiaa(uiaainfo));
|
||||||
|
} else {
|
||||||
|
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
|
||||||
}
|
}
|
||||||
|
|
||||||
db.users.remove_device(&sender_user, &body.device_id)?;
|
db.users.remove_device(&sender_user, &body.device_id)?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(delete_device::Response.into())
|
Ok(delete_device::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
@@ -166,22 +164,20 @@ pub async fn delete_devices_route(
|
|||||||
return Err(Error::Uiaa(uiaainfo));
|
return Err(Error::Uiaa(uiaainfo));
|
||||||
}
|
}
|
||||||
// Success!
|
// Success!
|
||||||
} else {
|
} else if let Some(json) = body.json_body {
|
||||||
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
||||||
db.uiaa.create(
|
db.uiaa
|
||||||
&sender_user,
|
.create(&sender_user, &sender_device, &uiaainfo, &json)?;
|
||||||
&sender_device,
|
|
||||||
&uiaainfo,
|
|
||||||
&body.json_body.expect("body is json"),
|
|
||||||
)?;
|
|
||||||
return Err(Error::Uiaa(uiaainfo));
|
return Err(Error::Uiaa(uiaainfo));
|
||||||
|
} else {
|
||||||
|
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
|
||||||
}
|
}
|
||||||
|
|
||||||
for device_id in &body.devices {
|
for device_id in &body.devices {
|
||||||
db.users.remove_device(&sender_user, &device_id)?
|
db.users.remove_device(&sender_user, &device_id)?
|
||||||
}
|
}
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(delete_devices::Response.into())
|
Ok(delete_devices::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
|
use std::convert::TryInto;
|
||||||
|
|
||||||
use crate::{database::DatabaseGuard, ConduitResult, Database, Error, Result, Ruma};
|
use crate::{database::DatabaseGuard, ConduitResult, Database, Error, Result, Ruma};
|
||||||
use log::info;
|
|
||||||
use ruma::{
|
use ruma::{
|
||||||
api::{
|
api::{
|
||||||
client::{
|
client::{
|
||||||
@@ -22,6 +23,7 @@ use ruma::{
|
|||||||
serde::Raw,
|
serde::Raw,
|
||||||
ServerName, UInt,
|
ServerName, UInt,
|
||||||
};
|
};
|
||||||
|
use tracing::{info, warn};
|
||||||
|
|
||||||
#[cfg(feature = "conduit_bin")]
|
#[cfg(feature = "conduit_bin")]
|
||||||
use rocket::{get, post, put};
|
use rocket::{get, post, put};
|
||||||
@@ -87,22 +89,22 @@ pub async fn set_room_visibility_route(
|
|||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
|
|
||||||
match &body.visibility {
|
match &body.visibility {
|
||||||
room::Visibility::_Custom(_s) => {
|
|
||||||
return Err(Error::BadRequest(
|
|
||||||
ErrorKind::InvalidParam,
|
|
||||||
"Room visibility type is not supported.",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
room::Visibility::Public => {
|
room::Visibility::Public => {
|
||||||
db.rooms.set_public(&body.room_id, true)?;
|
db.rooms.set_public(&body.room_id, true)?;
|
||||||
info!("{} made {} public", sender_user, body.room_id);
|
info!("{} made {} public", sender_user, body.room_id);
|
||||||
}
|
}
|
||||||
room::Visibility::Private => db.rooms.set_public(&body.room_id, false)?,
|
room::Visibility::Private => db.rooms.set_public(&body.room_id, false)?,
|
||||||
|
_ => {
|
||||||
|
return Err(Error::BadRequest(
|
||||||
|
ErrorKind::InvalidParam,
|
||||||
|
"Room visibility type is not supported.",
|
||||||
|
));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(set_room_visibility::Response.into())
|
Ok(set_room_visibility::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
@@ -231,10 +233,18 @@ pub async fn get_public_rooms_filtered_helper(
|
|||||||
.map_err(|_| {
|
.map_err(|_| {
|
||||||
Error::bad_database("Invalid room name event in database.")
|
Error::bad_database("Invalid room name event in database.")
|
||||||
})?
|
})?
|
||||||
.name()
|
.name
|
||||||
.map(|n| n.to_owned()))
|
.map(|n| n.to_owned().into()))
|
||||||
})?,
|
})?,
|
||||||
num_joined_members: (db.rooms.room_members(&room_id).count() as u32).into(),
|
num_joined_members: db
|
||||||
|
.rooms
|
||||||
|
.room_joined_count(&room_id)?
|
||||||
|
.unwrap_or_else(|| {
|
||||||
|
warn!("Room {} has no member count", room_id);
|
||||||
|
0
|
||||||
|
})
|
||||||
|
.try_into()
|
||||||
|
.expect("user count should not be that big"),
|
||||||
topic: db
|
topic: db
|
||||||
.rooms
|
.rooms
|
||||||
.room_state_get(&room_id, &EventType::RoomTopic, "")?
|
.room_state_get(&room_id, &EventType::RoomTopic, "")?
|
||||||
@@ -316,7 +326,7 @@ pub async fn get_public_rooms_filtered_helper(
|
|||||||
.map(|q| q.to_lowercase())
|
.map(|q| q.to_lowercase())
|
||||||
{
|
{
|
||||||
if let Some(name) = &chunk.name {
|
if let Some(name) = &chunk.name {
|
||||||
if name.to_lowercase().contains(&query) {
|
if name.as_str().to_lowercase().contains(&query) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+97
-25
@@ -1,19 +1,23 @@
|
|||||||
use super::SESSION_ID_LENGTH;
|
use super::SESSION_ID_LENGTH;
|
||||||
use crate::{database::DatabaseGuard, utils, ConduitResult, Database, Error, Result, Ruma};
|
use crate::{database::DatabaseGuard, utils, ConduitResult, Database, Error, Result, Ruma};
|
||||||
use ruma::{
|
use ruma::{
|
||||||
api::client::{
|
api::{
|
||||||
error::ErrorKind,
|
client::{
|
||||||
r0::{
|
error::ErrorKind,
|
||||||
keys::{
|
r0::{
|
||||||
claim_keys, get_key_changes, get_keys, upload_keys, upload_signatures,
|
keys::{
|
||||||
upload_signing_keys,
|
claim_keys, get_key_changes, get_keys, upload_keys, upload_signatures,
|
||||||
|
upload_signing_keys,
|
||||||
|
},
|
||||||
|
uiaa::{AuthFlow, UiaaInfo},
|
||||||
},
|
},
|
||||||
uiaa::{AuthFlow, UiaaInfo},
|
|
||||||
},
|
},
|
||||||
|
federation,
|
||||||
},
|
},
|
||||||
encryption::UnsignedDeviceInfo,
|
encryption::UnsignedDeviceInfo,
|
||||||
DeviceId, DeviceKeyAlgorithm, UserId,
|
DeviceId, DeviceKeyAlgorithm, UserId,
|
||||||
};
|
};
|
||||||
|
use serde_json::json;
|
||||||
use std::collections::{BTreeMap, HashSet};
|
use std::collections::{BTreeMap, HashSet};
|
||||||
|
|
||||||
#[cfg(feature = "conduit_bin")]
|
#[cfg(feature = "conduit_bin")]
|
||||||
@@ -60,7 +64,7 @@ pub async fn upload_keys_route(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(upload_keys::Response {
|
Ok(upload_keys::Response {
|
||||||
one_time_key_counts: db.users.count_one_time_keys(sender_user, sender_device)?,
|
one_time_key_counts: db.users.count_one_time_keys(sender_user, sender_device)?,
|
||||||
@@ -84,7 +88,8 @@ pub async fn get_keys_route(
|
|||||||
&body.device_keys,
|
&body.device_keys,
|
||||||
|u| u == sender_user,
|
|u| u == sender_user,
|
||||||
&db,
|
&db,
|
||||||
)?;
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
Ok(response.into())
|
Ok(response.into())
|
||||||
}
|
}
|
||||||
@@ -98,9 +103,9 @@ pub async fn claim_keys_route(
|
|||||||
db: DatabaseGuard,
|
db: DatabaseGuard,
|
||||||
body: Ruma<claim_keys::Request>,
|
body: Ruma<claim_keys::Request>,
|
||||||
) -> ConduitResult<claim_keys::Response> {
|
) -> ConduitResult<claim_keys::Response> {
|
||||||
let response = claim_keys_helper(&body.one_time_keys, &db)?;
|
let response = claim_keys_helper(&body.one_time_keys, &db).await?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(response.into())
|
Ok(response.into())
|
||||||
}
|
}
|
||||||
@@ -141,15 +146,13 @@ pub async fn upload_signing_keys_route(
|
|||||||
return Err(Error::Uiaa(uiaainfo));
|
return Err(Error::Uiaa(uiaainfo));
|
||||||
}
|
}
|
||||||
// Success!
|
// Success!
|
||||||
} else {
|
} else if let Some(json) = body.json_body {
|
||||||
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
||||||
db.uiaa.create(
|
db.uiaa
|
||||||
&sender_user,
|
.create(&sender_user, &sender_device, &uiaainfo, &json)?;
|
||||||
&sender_device,
|
|
||||||
&uiaainfo,
|
|
||||||
&body.json_body.expect("body is json"),
|
|
||||||
)?;
|
|
||||||
return Err(Error::Uiaa(uiaainfo));
|
return Err(Error::Uiaa(uiaainfo));
|
||||||
|
} else {
|
||||||
|
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(master_key) = &body.master_key {
|
if let Some(master_key) = &body.master_key {
|
||||||
@@ -163,9 +166,9 @@ pub async fn upload_signing_keys_route(
|
|||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(upload_signing_keys::Response.into())
|
Ok(upload_signing_keys::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
@@ -224,9 +227,9 @@ pub async fn upload_signatures_route(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(upload_signatures::Response.into())
|
Ok(upload_signatures::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
@@ -280,7 +283,7 @@ pub async fn get_key_changes_route(
|
|||||||
.into())
|
.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_keys_helper<F: Fn(&UserId) -> bool>(
|
pub async fn get_keys_helper<F: Fn(&UserId) -> bool>(
|
||||||
sender_user: Option<&UserId>,
|
sender_user: Option<&UserId>,
|
||||||
device_keys_input: &BTreeMap<UserId, Vec<Box<DeviceId>>>,
|
device_keys_input: &BTreeMap<UserId, Vec<Box<DeviceId>>>,
|
||||||
allowed_signatures: F,
|
allowed_signatures: F,
|
||||||
@@ -291,7 +294,17 @@ pub fn get_keys_helper<F: Fn(&UserId) -> bool>(
|
|||||||
let mut user_signing_keys = BTreeMap::new();
|
let mut user_signing_keys = BTreeMap::new();
|
||||||
let mut device_keys = BTreeMap::new();
|
let mut device_keys = BTreeMap::new();
|
||||||
|
|
||||||
|
let mut get_over_federation = BTreeMap::new();
|
||||||
|
|
||||||
for (user_id, device_ids) in device_keys_input {
|
for (user_id, device_ids) in device_keys_input {
|
||||||
|
if user_id.server_name() != db.globals.server_name() {
|
||||||
|
get_over_federation
|
||||||
|
.entry(user_id.server_name())
|
||||||
|
.or_insert_with(Vec::new)
|
||||||
|
.push((user_id, device_ids));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
if device_ids.is_empty() {
|
if device_ids.is_empty() {
|
||||||
let mut container = BTreeMap::new();
|
let mut container = BTreeMap::new();
|
||||||
for device_id in db.users.all_device_ids(user_id) {
|
for device_id in db.users.all_device_ids(user_id) {
|
||||||
@@ -349,21 +362,60 @@ pub fn get_keys_helper<F: Fn(&UserId) -> bool>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let mut failures = BTreeMap::new();
|
||||||
|
|
||||||
|
for (server, vec) in get_over_federation {
|
||||||
|
let mut device_keys_input_fed = BTreeMap::new();
|
||||||
|
for (user_id, keys) in vec {
|
||||||
|
device_keys_input_fed.insert(user_id.clone(), keys.clone());
|
||||||
|
}
|
||||||
|
match db
|
||||||
|
.sending
|
||||||
|
.send_federation_request(
|
||||||
|
&db.globals,
|
||||||
|
server,
|
||||||
|
federation::keys::get_keys::v1::Request {
|
||||||
|
device_keys: device_keys_input_fed,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(response) => {
|
||||||
|
master_keys.extend(response.master_keys);
|
||||||
|
self_signing_keys.extend(response.self_signing_keys);
|
||||||
|
device_keys.extend(response.device_keys);
|
||||||
|
}
|
||||||
|
Err(_e) => {
|
||||||
|
failures.insert(server.to_string(), json!({}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Ok(get_keys::Response {
|
Ok(get_keys::Response {
|
||||||
master_keys,
|
master_keys,
|
||||||
self_signing_keys,
|
self_signing_keys,
|
||||||
user_signing_keys,
|
user_signing_keys,
|
||||||
device_keys,
|
device_keys,
|
||||||
failures: BTreeMap::new(),
|
failures,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn claim_keys_helper(
|
pub async fn claim_keys_helper(
|
||||||
one_time_keys_input: &BTreeMap<UserId, BTreeMap<Box<DeviceId>, DeviceKeyAlgorithm>>,
|
one_time_keys_input: &BTreeMap<UserId, BTreeMap<Box<DeviceId>, DeviceKeyAlgorithm>>,
|
||||||
db: &Database,
|
db: &Database,
|
||||||
) -> Result<claim_keys::Response> {
|
) -> Result<claim_keys::Response> {
|
||||||
let mut one_time_keys = BTreeMap::new();
|
let mut one_time_keys = BTreeMap::new();
|
||||||
|
|
||||||
|
let mut get_over_federation = BTreeMap::new();
|
||||||
|
|
||||||
for (user_id, map) in one_time_keys_input {
|
for (user_id, map) in one_time_keys_input {
|
||||||
|
if user_id.server_name() != db.globals.server_name() {
|
||||||
|
get_over_federation
|
||||||
|
.entry(user_id.server_name())
|
||||||
|
.or_insert_with(Vec::new)
|
||||||
|
.push((user_id, map));
|
||||||
|
}
|
||||||
|
|
||||||
let mut container = BTreeMap::new();
|
let mut container = BTreeMap::new();
|
||||||
for (device_id, key_algorithm) in map {
|
for (device_id, key_algorithm) in map {
|
||||||
if let Some(one_time_keys) =
|
if let Some(one_time_keys) =
|
||||||
@@ -378,6 +430,26 @@ pub fn claim_keys_helper(
|
|||||||
one_time_keys.insert(user_id.clone(), container);
|
one_time_keys.insert(user_id.clone(), container);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for (server, vec) in get_over_federation {
|
||||||
|
let mut one_time_keys_input_fed = BTreeMap::new();
|
||||||
|
for (user_id, keys) in vec {
|
||||||
|
one_time_keys_input_fed.insert(user_id.clone(), keys.clone());
|
||||||
|
}
|
||||||
|
// Ignore failures
|
||||||
|
let keys = db
|
||||||
|
.sending
|
||||||
|
.send_federation_request(
|
||||||
|
&db.globals,
|
||||||
|
server,
|
||||||
|
federation::keys::claim_keys::v1::Request {
|
||||||
|
one_time_keys: one_time_keys_input_fed,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
one_time_keys.extend(keys.one_time_keys);
|
||||||
|
}
|
||||||
|
|
||||||
Ok(claim_keys::Response {
|
Ok(claim_keys::Response {
|
||||||
failures: BTreeMap::new(),
|
failures: BTreeMap::new(),
|
||||||
one_time_keys,
|
one_time_keys,
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ pub async fn create_content_route(
|
|||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(create_content::Response {
|
Ok(create_content::Response {
|
||||||
content_uri: mxc.try_into().expect("Invalid mxc:// URI"),
|
content_uri: mxc.try_into().expect("Invalid mxc:// URI"),
|
||||||
|
|||||||
+211
-179
@@ -4,7 +4,6 @@ use crate::{
|
|||||||
pdu::{PduBuilder, PduEvent},
|
pdu::{PduBuilder, PduEvent},
|
||||||
server_server, utils, ConduitResult, Database, Error, Result, Ruma,
|
server_server, utils, ConduitResult, Database, Error, Result, Ruma,
|
||||||
};
|
};
|
||||||
use log::{debug, error, warn};
|
|
||||||
use member::{MemberEventContent, MembershipState};
|
use member::{MemberEventContent, MembershipState};
|
||||||
use rocket::futures;
|
use rocket::futures;
|
||||||
use ruma::{
|
use ruma::{
|
||||||
@@ -29,11 +28,12 @@ use ruma::{
|
|||||||
uint, EventId, RoomId, RoomVersionId, ServerName, UserId,
|
uint, EventId, RoomId, RoomVersionId, ServerName, UserId,
|
||||||
};
|
};
|
||||||
use std::{
|
use std::{
|
||||||
collections::{btree_map::Entry, BTreeMap, HashSet},
|
collections::{hash_map::Entry, BTreeMap, HashMap, HashSet},
|
||||||
convert::{TryFrom, TryInto},
|
convert::{TryFrom, TryInto},
|
||||||
sync::{Arc, RwLock},
|
sync::{Arc, RwLock},
|
||||||
time::{Duration, Instant},
|
time::{Duration, Instant},
|
||||||
};
|
};
|
||||||
|
use tracing::{debug, error, warn};
|
||||||
|
|
||||||
#[cfg(feature = "conduit_bin")]
|
#[cfg(feature = "conduit_bin")]
|
||||||
use rocket::{get, post};
|
use rocket::{get, post};
|
||||||
@@ -74,7 +74,7 @@ pub async fn join_room_by_id_route(
|
|||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
ret
|
ret
|
||||||
}
|
}
|
||||||
@@ -125,7 +125,7 @@ pub async fn join_room_by_id_or_alias_route(
|
|||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(join_room_by_id_or_alias::Response {
|
Ok(join_room_by_id_or_alias::Response {
|
||||||
room_id: join_room_response.0.room_id,
|
room_id: join_room_response.0.room_id,
|
||||||
@@ -146,7 +146,7 @@ pub async fn leave_room_route(
|
|||||||
|
|
||||||
db.rooms.leave_room(sender_user, &body.room_id, &db).await?;
|
db.rooms.leave_room(sender_user, &body.room_id, &db).await?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(leave_room::Response::new().into())
|
Ok(leave_room::Response::new().into())
|
||||||
}
|
}
|
||||||
@@ -164,8 +164,8 @@ pub async fn invite_user_route(
|
|||||||
|
|
||||||
if let invite_user::IncomingInvitationRecipient::UserId { user_id } = &body.recipient {
|
if let invite_user::IncomingInvitationRecipient::UserId { user_id } = &body.recipient {
|
||||||
invite_helper(sender_user, user_id, &body.room_id, &db, false).await?;
|
invite_helper(sender_user, user_id, &body.room_id, &db, false).await?;
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
Ok(invite_user::Response.into())
|
Ok(invite_user::Response {}.into())
|
||||||
} else {
|
} else {
|
||||||
Err(Error::BadRequest(ErrorKind::NotFound, "User not found."))
|
Err(Error::BadRequest(ErrorKind::NotFound, "User not found."))
|
||||||
}
|
}
|
||||||
@@ -203,15 +203,15 @@ pub async fn kick_user_route(
|
|||||||
event.membership = ruma::events::room::member::MembershipState::Leave;
|
event.membership = ruma::events::room::member::MembershipState::Leave;
|
||||||
// TODO: reason
|
// TODO: reason
|
||||||
|
|
||||||
let mutex = Arc::clone(
|
let mutex_state = Arc::clone(
|
||||||
db.globals
|
db.globals
|
||||||
.roomid_mutex
|
.roomid_mutex_state
|
||||||
.write()
|
.write()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.entry(body.room_id.clone())
|
.entry(body.room_id.clone())
|
||||||
.or_default(),
|
.or_default(),
|
||||||
);
|
);
|
||||||
let mutex_lock = mutex.lock().await;
|
let state_lock = mutex_state.lock().await;
|
||||||
|
|
||||||
db.rooms.build_and_append_pdu(
|
db.rooms.build_and_append_pdu(
|
||||||
PduBuilder {
|
PduBuilder {
|
||||||
@@ -224,12 +224,12 @@ pub async fn kick_user_route(
|
|||||||
&sender_user,
|
&sender_user,
|
||||||
&body.room_id,
|
&body.room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
drop(mutex_lock);
|
drop(state_lock);
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(kick_user::Response::new().into())
|
Ok(kick_user::Response::new().into())
|
||||||
}
|
}
|
||||||
@@ -261,6 +261,7 @@ pub async fn ban_user_route(
|
|||||||
avatar_url: db.users.avatar_url(&body.user_id)?,
|
avatar_url: db.users.avatar_url(&body.user_id)?,
|
||||||
is_direct: None,
|
is_direct: None,
|
||||||
third_party_invite: None,
|
third_party_invite: None,
|
||||||
|
blurhash: db.users.blurhash(&body.user_id)?,
|
||||||
}),
|
}),
|
||||||
|event| {
|
|event| {
|
||||||
let mut event = serde_json::from_value::<Raw<member::MemberEventContent>>(
|
let mut event = serde_json::from_value::<Raw<member::MemberEventContent>>(
|
||||||
@@ -274,15 +275,15 @@ pub async fn ban_user_route(
|
|||||||
},
|
},
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
let mutex = Arc::clone(
|
let mutex_state = Arc::clone(
|
||||||
db.globals
|
db.globals
|
||||||
.roomid_mutex
|
.roomid_mutex_state
|
||||||
.write()
|
.write()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.entry(body.room_id.clone())
|
.entry(body.room_id.clone())
|
||||||
.or_default(),
|
.or_default(),
|
||||||
);
|
);
|
||||||
let mutex_lock = mutex.lock().await;
|
let state_lock = mutex_state.lock().await;
|
||||||
|
|
||||||
db.rooms.build_and_append_pdu(
|
db.rooms.build_and_append_pdu(
|
||||||
PduBuilder {
|
PduBuilder {
|
||||||
@@ -295,12 +296,12 @@ pub async fn ban_user_route(
|
|||||||
&sender_user,
|
&sender_user,
|
||||||
&body.room_id,
|
&body.room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
drop(mutex_lock);
|
drop(state_lock);
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(ban_user::Response::new().into())
|
Ok(ban_user::Response::new().into())
|
||||||
}
|
}
|
||||||
@@ -336,15 +337,15 @@ pub async fn unban_user_route(
|
|||||||
|
|
||||||
event.membership = ruma::events::room::member::MembershipState::Leave;
|
event.membership = ruma::events::room::member::MembershipState::Leave;
|
||||||
|
|
||||||
let mutex = Arc::clone(
|
let mutex_state = Arc::clone(
|
||||||
db.globals
|
db.globals
|
||||||
.roomid_mutex
|
.roomid_mutex_state
|
||||||
.write()
|
.write()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.entry(body.room_id.clone())
|
.entry(body.room_id.clone())
|
||||||
.or_default(),
|
.or_default(),
|
||||||
);
|
);
|
||||||
let mutex_lock = mutex.lock().await;
|
let state_lock = mutex_state.lock().await;
|
||||||
|
|
||||||
db.rooms.build_and_append_pdu(
|
db.rooms.build_and_append_pdu(
|
||||||
PduBuilder {
|
PduBuilder {
|
||||||
@@ -357,12 +358,12 @@ pub async fn unban_user_route(
|
|||||||
&sender_user,
|
&sender_user,
|
||||||
&body.room_id,
|
&body.room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
drop(mutex_lock);
|
drop(state_lock);
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(unban_user::Response::new().into())
|
Ok(unban_user::Response::new().into())
|
||||||
}
|
}
|
||||||
@@ -380,7 +381,7 @@ pub async fn forget_room_route(
|
|||||||
|
|
||||||
db.rooms.forget(&body.room_id, &sender_user)?;
|
db.rooms.forget(&body.room_id, &sender_user)?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(forget_room::Response::new().into())
|
Ok(forget_room::Response::new().into())
|
||||||
}
|
}
|
||||||
@@ -485,15 +486,15 @@ async fn join_room_by_id_helper(
|
|||||||
) -> ConduitResult<join_room_by_id::Response> {
|
) -> ConduitResult<join_room_by_id::Response> {
|
||||||
let sender_user = sender_user.expect("user is authenticated");
|
let sender_user = sender_user.expect("user is authenticated");
|
||||||
|
|
||||||
let mutex = Arc::clone(
|
let mutex_state = Arc::clone(
|
||||||
db.globals
|
db.globals
|
||||||
.roomid_mutex
|
.roomid_mutex_state
|
||||||
.write()
|
.write()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.entry(room_id.clone())
|
.entry(room_id.clone())
|
||||||
.or_default(),
|
.or_default(),
|
||||||
);
|
);
|
||||||
let mutex_lock = mutex.lock().await;
|
let state_lock = mutex_state.lock().await;
|
||||||
|
|
||||||
// Ask a remote server if we don't have this room
|
// Ask a remote server if we don't have this room
|
||||||
if !db.rooms.exists(&room_id)? && room_id.server_name() != db.globals.server_name() {
|
if !db.rooms.exists(&room_id)? && room_id.server_name() != db.globals.server_name() {
|
||||||
@@ -510,7 +511,7 @@ async fn join_room_by_id_helper(
|
|||||||
federation::membership::create_join_event_template::v1::Request {
|
federation::membership::create_join_event_template::v1::Request {
|
||||||
room_id,
|
room_id,
|
||||||
user_id: sender_user,
|
user_id: sender_user,
|
||||||
ver: &[RoomVersionId::Version6],
|
ver: &[RoomVersionId::Version5, RoomVersionId::Version6],
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
@@ -525,7 +526,12 @@ async fn join_room_by_id_helper(
|
|||||||
let (make_join_response, remote_server) = make_join_response_and_server?;
|
let (make_join_response, remote_server) = make_join_response_and_server?;
|
||||||
|
|
||||||
let room_version = match make_join_response.room_version {
|
let room_version = match make_join_response.room_version {
|
||||||
Some(room_version) if room_version == RoomVersionId::Version6 => room_version,
|
Some(room_version)
|
||||||
|
if room_version == RoomVersionId::Version5
|
||||||
|
|| room_version == RoomVersionId::Version6 =>
|
||||||
|
{
|
||||||
|
room_version
|
||||||
|
}
|
||||||
_ => return Err(Error::BadServerResponse("Room version is not supported")),
|
_ => return Err(Error::BadServerResponse("Room version is not supported")),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -556,6 +562,7 @@ async fn join_room_by_id_helper(
|
|||||||
avatar_url: db.users.avatar_url(&sender_user)?,
|
avatar_url: db.users.avatar_url(&sender_user)?,
|
||||||
is_direct: None,
|
is_direct: None,
|
||||||
third_party_invite: None,
|
third_party_invite: None,
|
||||||
|
blurhash: db.users.blurhash(&sender_user)?,
|
||||||
})
|
})
|
||||||
.expect("event is valid, we just created it"),
|
.expect("event is valid, we just created it"),
|
||||||
);
|
);
|
||||||
@@ -605,7 +612,7 @@ async fn join_room_by_id_helper(
|
|||||||
let pdu = PduEvent::from_id_val(&event_id, join_event.clone())
|
let pdu = PduEvent::from_id_val(&event_id, join_event.clone())
|
||||||
.map_err(|_| Error::BadServerResponse("Invalid join event PDU."))?;
|
.map_err(|_| Error::BadServerResponse("Invalid join event PDU."))?;
|
||||||
|
|
||||||
let mut state = BTreeMap::new();
|
let mut state = HashMap::new();
|
||||||
let pub_key_map = RwLock::new(BTreeMap::new());
|
let pub_key_map = RwLock::new(BTreeMap::new());
|
||||||
|
|
||||||
for result in futures::future::join_all(
|
for result in futures::future::join_all(
|
||||||
@@ -685,6 +692,7 @@ async fn join_room_by_id_helper(
|
|||||||
avatar_url: db.users.avatar_url(&sender_user)?,
|
avatar_url: db.users.avatar_url(&sender_user)?,
|
||||||
is_direct: None,
|
is_direct: None,
|
||||||
third_party_invite: None,
|
third_party_invite: None,
|
||||||
|
blurhash: db.users.blurhash(&sender_user)?,
|
||||||
};
|
};
|
||||||
|
|
||||||
db.rooms.build_and_append_pdu(
|
db.rooms.build_and_append_pdu(
|
||||||
@@ -698,13 +706,13 @@ async fn join_room_by_id_helper(
|
|||||||
&sender_user,
|
&sender_user,
|
||||||
&room_id,
|
&room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
drop(mutex_lock);
|
drop(state_lock);
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(join_room_by_id::Response::new(room_id.clone()).into())
|
Ok(join_room_by_id::Response::new(room_id.clone()).into())
|
||||||
}
|
}
|
||||||
@@ -780,154 +788,165 @@ pub async fn invite_helper<'a>(
|
|||||||
db: &Database,
|
db: &Database,
|
||||||
is_direct: bool,
|
is_direct: bool,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let mutex = Arc::clone(
|
|
||||||
db.globals
|
|
||||||
.roomid_mutex
|
|
||||||
.write()
|
|
||||||
.unwrap()
|
|
||||||
.entry(room_id.clone())
|
|
||||||
.or_default(),
|
|
||||||
);
|
|
||||||
let mutex_lock = mutex.lock().await;
|
|
||||||
|
|
||||||
if user_id.server_name() != db.globals.server_name() {
|
if user_id.server_name() != db.globals.server_name() {
|
||||||
let prev_events = db
|
let (room_version_id, pdu_json, invite_room_state) = {
|
||||||
.rooms
|
let mutex_state = Arc::clone(
|
||||||
.get_pdu_leaves(room_id)?
|
db.globals
|
||||||
.into_iter()
|
.roomid_mutex_state
|
||||||
.take(20)
|
.write()
|
||||||
.collect::<Vec<_>>();
|
.unwrap()
|
||||||
|
.entry(room_id.clone())
|
||||||
let create_event = db
|
.or_default(),
|
||||||
.rooms
|
|
||||||
.room_state_get(room_id, &EventType::RoomCreate, "")?;
|
|
||||||
|
|
||||||
let create_event_content = create_event
|
|
||||||
.as_ref()
|
|
||||||
.map(|create_event| {
|
|
||||||
serde_json::from_value::<Raw<CreateEventContent>>(create_event.content.clone())
|
|
||||||
.expect("Raw::from_value always works.")
|
|
||||||
.deserialize()
|
|
||||||
.map_err(|_| Error::bad_database("Invalid PowerLevels event in db."))
|
|
||||||
})
|
|
||||||
.transpose()?;
|
|
||||||
|
|
||||||
let create_prev_event = if prev_events.len() == 1
|
|
||||||
&& Some(&prev_events[0]) == create_event.as_ref().map(|c| &c.event_id)
|
|
||||||
{
|
|
||||||
create_event
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
// If there was no create event yet, assume we are creating a version 6 room right now
|
|
||||||
let room_version_id = create_event_content
|
|
||||||
.map_or(RoomVersionId::Version6, |create_event| {
|
|
||||||
create_event.room_version
|
|
||||||
});
|
|
||||||
let room_version = RoomVersion::new(&room_version_id).expect("room version is supported");
|
|
||||||
|
|
||||||
let content = serde_json::to_value(MemberEventContent {
|
|
||||||
avatar_url: None,
|
|
||||||
displayname: None,
|
|
||||||
is_direct: Some(is_direct),
|
|
||||||
membership: MembershipState::Invite,
|
|
||||||
third_party_invite: None,
|
|
||||||
})
|
|
||||||
.expect("member event is valid value");
|
|
||||||
|
|
||||||
let state_key = user_id.to_string();
|
|
||||||
let kind = EventType::RoomMember;
|
|
||||||
|
|
||||||
let auth_events =
|
|
||||||
db.rooms
|
|
||||||
.get_auth_events(room_id, &kind, &sender_user, Some(&state_key), &content)?;
|
|
||||||
|
|
||||||
// Our depth is the maximum depth of prev_events + 1
|
|
||||||
let depth = prev_events
|
|
||||||
.iter()
|
|
||||||
.filter_map(|event_id| Some(db.rooms.get_pdu(event_id).ok()??.depth))
|
|
||||||
.max()
|
|
||||||
.unwrap_or_else(|| uint!(0))
|
|
||||||
+ uint!(1);
|
|
||||||
|
|
||||||
let mut unsigned = BTreeMap::new();
|
|
||||||
|
|
||||||
if let Some(prev_pdu) = db.rooms.room_state_get(room_id, &kind, &state_key)? {
|
|
||||||
unsigned.insert("prev_content".to_owned(), prev_pdu.content.clone());
|
|
||||||
unsigned.insert(
|
|
||||||
"prev_sender".to_owned(),
|
|
||||||
serde_json::to_value(&prev_pdu.sender).expect("UserId::to_value always works"),
|
|
||||||
);
|
);
|
||||||
}
|
let state_lock = mutex_state.lock().await;
|
||||||
|
|
||||||
let pdu = PduEvent {
|
let prev_events = db
|
||||||
event_id: ruma::event_id!("$thiswillbefilledinlater"),
|
.rooms
|
||||||
room_id: room_id.clone(),
|
.get_pdu_leaves(room_id)?
|
||||||
sender: sender_user.clone(),
|
.into_iter()
|
||||||
origin_server_ts: utils::millis_since_unix_epoch()
|
.take(20)
|
||||||
.try_into()
|
.collect::<Vec<_>>();
|
||||||
.expect("time is valid"),
|
|
||||||
kind,
|
let create_event = db
|
||||||
content,
|
.rooms
|
||||||
state_key: Some(state_key),
|
.room_state_get(room_id, &EventType::RoomCreate, "")?;
|
||||||
prev_events,
|
|
||||||
depth,
|
let create_event_content = create_event
|
||||||
auth_events: auth_events
|
.as_ref()
|
||||||
|
.map(|create_event| {
|
||||||
|
serde_json::from_value::<Raw<CreateEventContent>>(create_event.content.clone())
|
||||||
|
.expect("Raw::from_value always works.")
|
||||||
|
.deserialize()
|
||||||
|
.map_err(|_| Error::bad_database("Invalid PowerLevels event in db."))
|
||||||
|
})
|
||||||
|
.transpose()?;
|
||||||
|
|
||||||
|
let create_prev_event = if prev_events.len() == 1
|
||||||
|
&& Some(&prev_events[0]) == create_event.as_ref().map(|c| &c.event_id)
|
||||||
|
{
|
||||||
|
create_event
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
// If there was no create event yet, assume we are creating a version 6 room right now
|
||||||
|
let room_version_id = create_event_content
|
||||||
|
.map_or(RoomVersionId::Version6, |create_event| {
|
||||||
|
create_event.room_version
|
||||||
|
});
|
||||||
|
let room_version =
|
||||||
|
RoomVersion::new(&room_version_id).expect("room version is supported");
|
||||||
|
|
||||||
|
let content = serde_json::to_value(MemberEventContent {
|
||||||
|
avatar_url: None,
|
||||||
|
displayname: None,
|
||||||
|
is_direct: Some(is_direct),
|
||||||
|
membership: MembershipState::Invite,
|
||||||
|
third_party_invite: None,
|
||||||
|
blurhash: None,
|
||||||
|
})
|
||||||
|
.expect("member event is valid value");
|
||||||
|
|
||||||
|
let state_key = user_id.to_string();
|
||||||
|
let kind = EventType::RoomMember;
|
||||||
|
|
||||||
|
let auth_events = db.rooms.get_auth_events(
|
||||||
|
room_id,
|
||||||
|
&kind,
|
||||||
|
&sender_user,
|
||||||
|
Some(&state_key),
|
||||||
|
&content,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
// Our depth is the maximum depth of prev_events + 1
|
||||||
|
let depth = prev_events
|
||||||
.iter()
|
.iter()
|
||||||
.map(|(_, pdu)| pdu.event_id.clone())
|
.filter_map(|event_id| Some(db.rooms.get_pdu(event_id).ok()??.depth))
|
||||||
.collect(),
|
.max()
|
||||||
redacts: None,
|
.unwrap_or_else(|| uint!(0))
|
||||||
unsigned,
|
+ uint!(1);
|
||||||
hashes: ruma::events::pdu::EventHash {
|
|
||||||
sha256: "aaa".to_owned(),
|
let mut unsigned = BTreeMap::new();
|
||||||
},
|
|
||||||
signatures: BTreeMap::new(),
|
if let Some(prev_pdu) = db.rooms.room_state_get(room_id, &kind, &state_key)? {
|
||||||
|
unsigned.insert("prev_content".to_owned(), prev_pdu.content.clone());
|
||||||
|
unsigned.insert(
|
||||||
|
"prev_sender".to_owned(),
|
||||||
|
serde_json::to_value(&prev_pdu.sender).expect("UserId::to_value always works"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let pdu = PduEvent {
|
||||||
|
event_id: ruma::event_id!("$thiswillbefilledinlater"),
|
||||||
|
room_id: room_id.clone(),
|
||||||
|
sender: sender_user.clone(),
|
||||||
|
origin_server_ts: utils::millis_since_unix_epoch()
|
||||||
|
.try_into()
|
||||||
|
.expect("time is valid"),
|
||||||
|
kind,
|
||||||
|
content,
|
||||||
|
state_key: Some(state_key),
|
||||||
|
prev_events,
|
||||||
|
depth,
|
||||||
|
auth_events: auth_events
|
||||||
|
.iter()
|
||||||
|
.map(|(_, pdu)| pdu.event_id.clone())
|
||||||
|
.collect(),
|
||||||
|
redacts: None,
|
||||||
|
unsigned,
|
||||||
|
hashes: ruma::events::pdu::EventHash {
|
||||||
|
sha256: "aaa".to_owned(),
|
||||||
|
},
|
||||||
|
signatures: BTreeMap::new(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let auth_check = state_res::auth_check(
|
||||||
|
&room_version,
|
||||||
|
&Arc::new(pdu.clone()),
|
||||||
|
create_prev_event,
|
||||||
|
&auth_events,
|
||||||
|
None, // TODO: third_party_invite
|
||||||
|
)
|
||||||
|
.map_err(|e| {
|
||||||
|
error!("{:?}", e);
|
||||||
|
Error::bad_database("Auth check failed.")
|
||||||
|
})?;
|
||||||
|
|
||||||
|
if !auth_check {
|
||||||
|
return Err(Error::BadRequest(
|
||||||
|
ErrorKind::Forbidden,
|
||||||
|
"Event is not authorized.",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hash and sign
|
||||||
|
let mut pdu_json =
|
||||||
|
utils::to_canonical_object(&pdu).expect("event is valid, we just created it");
|
||||||
|
|
||||||
|
pdu_json.remove("event_id");
|
||||||
|
|
||||||
|
// Add origin because synapse likes that (and it's required in the spec)
|
||||||
|
pdu_json.insert(
|
||||||
|
"origin".to_owned(),
|
||||||
|
to_canonical_value(db.globals.server_name())
|
||||||
|
.expect("server name is a valid CanonicalJsonValue"),
|
||||||
|
);
|
||||||
|
|
||||||
|
ruma::signatures::hash_and_sign_event(
|
||||||
|
db.globals.server_name().as_str(),
|
||||||
|
db.globals.keypair(),
|
||||||
|
&mut pdu_json,
|
||||||
|
&room_version_id,
|
||||||
|
)
|
||||||
|
.expect("event is valid, we just created it");
|
||||||
|
|
||||||
|
let invite_room_state = db.rooms.calculate_invite_state(&pdu)?;
|
||||||
|
|
||||||
|
drop(state_lock);
|
||||||
|
|
||||||
|
(room_version_id, pdu_json, invite_room_state)
|
||||||
};
|
};
|
||||||
|
|
||||||
let auth_check = state_res::auth_check(
|
|
||||||
&room_version,
|
|
||||||
&Arc::new(pdu.clone()),
|
|
||||||
create_prev_event,
|
|
||||||
&auth_events,
|
|
||||||
None, // TODO: third_party_invite
|
|
||||||
)
|
|
||||||
.map_err(|e| {
|
|
||||||
error!("{:?}", e);
|
|
||||||
Error::bad_database("Auth check failed.")
|
|
||||||
})?;
|
|
||||||
|
|
||||||
if !auth_check {
|
|
||||||
return Err(Error::BadRequest(
|
|
||||||
ErrorKind::Forbidden,
|
|
||||||
"Event is not authorized.",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Hash and sign
|
|
||||||
let mut pdu_json =
|
|
||||||
utils::to_canonical_object(&pdu).expect("event is valid, we just created it");
|
|
||||||
|
|
||||||
pdu_json.remove("event_id");
|
|
||||||
|
|
||||||
// Add origin because synapse likes that (and it's required in the spec)
|
|
||||||
pdu_json.insert(
|
|
||||||
"origin".to_owned(),
|
|
||||||
to_canonical_value(db.globals.server_name())
|
|
||||||
.expect("server name is a valid CanonicalJsonValue"),
|
|
||||||
);
|
|
||||||
|
|
||||||
ruma::signatures::hash_and_sign_event(
|
|
||||||
db.globals.server_name().as_str(),
|
|
||||||
db.globals.keypair(),
|
|
||||||
&mut pdu_json,
|
|
||||||
&room_version_id,
|
|
||||||
)
|
|
||||||
.expect("event is valid, we just created it");
|
|
||||||
|
|
||||||
drop(mutex_lock);
|
|
||||||
|
|
||||||
let invite_room_state = db.rooms.calculate_invite_state(&pdu)?;
|
|
||||||
let response = db
|
let response = db
|
||||||
.sending
|
.sending
|
||||||
.send_federation_request(
|
.send_federation_request(
|
||||||
@@ -936,7 +955,7 @@ pub async fn invite_helper<'a>(
|
|||||||
create_invite::v2::Request {
|
create_invite::v2::Request {
|
||||||
room_id: room_id.clone(),
|
room_id: room_id.clone(),
|
||||||
event_id: ruma::event_id!("$receivingservershouldsetthis"),
|
event_id: ruma::event_id!("$receivingservershouldsetthis"),
|
||||||
room_version: RoomVersionId::Version6,
|
room_version: room_version_id,
|
||||||
event: PduEvent::convert_to_outgoing_federation_event(pdu_json),
|
event: PduEvent::convert_to_outgoing_federation_event(pdu_json),
|
||||||
invite_room_state,
|
invite_room_state,
|
||||||
},
|
},
|
||||||
@@ -999,6 +1018,16 @@ pub async fn invite_helper<'a>(
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let mutex_state = Arc::clone(
|
||||||
|
db.globals
|
||||||
|
.roomid_mutex_state
|
||||||
|
.write()
|
||||||
|
.unwrap()
|
||||||
|
.entry(room_id.clone())
|
||||||
|
.or_default(),
|
||||||
|
);
|
||||||
|
let state_lock = mutex_state.lock().await;
|
||||||
|
|
||||||
db.rooms.build_and_append_pdu(
|
db.rooms.build_and_append_pdu(
|
||||||
PduBuilder {
|
PduBuilder {
|
||||||
event_type: EventType::RoomMember,
|
event_type: EventType::RoomMember,
|
||||||
@@ -1008,6 +1037,7 @@ pub async fn invite_helper<'a>(
|
|||||||
avatar_url: db.users.avatar_url(&user_id)?,
|
avatar_url: db.users.avatar_url(&user_id)?,
|
||||||
is_direct: Some(is_direct),
|
is_direct: Some(is_direct),
|
||||||
third_party_invite: None,
|
third_party_invite: None,
|
||||||
|
blurhash: db.users.blurhash(&user_id)?,
|
||||||
})
|
})
|
||||||
.expect("event is valid, we just created it"),
|
.expect("event is valid, we just created it"),
|
||||||
unsigned: None,
|
unsigned: None,
|
||||||
@@ -1017,8 +1047,10 @@ pub async fn invite_helper<'a>(
|
|||||||
&sender_user,
|
&sender_user,
|
||||||
room_id,
|
room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
|
drop(state_lock);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,15 +28,15 @@ pub async fn send_message_event_route(
|
|||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
let sender_device = body.sender_device.as_deref();
|
let sender_device = body.sender_device.as_deref();
|
||||||
|
|
||||||
let mutex = Arc::clone(
|
let mutex_state = Arc::clone(
|
||||||
db.globals
|
db.globals
|
||||||
.roomid_mutex
|
.roomid_mutex_state
|
||||||
.write()
|
.write()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.entry(body.room_id.clone())
|
.entry(body.room_id.clone())
|
||||||
.or_default(),
|
.or_default(),
|
||||||
);
|
);
|
||||||
let mutex_lock = mutex.lock().await;
|
let state_lock = mutex_state.lock().await;
|
||||||
|
|
||||||
// Check if this is a new transaction id
|
// Check if this is a new transaction id
|
||||||
if let Some(response) =
|
if let Some(response) =
|
||||||
@@ -75,7 +75,7 @@ pub async fn send_message_event_route(
|
|||||||
&sender_user,
|
&sender_user,
|
||||||
&body.room_id,
|
&body.room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
db.transaction_ids.add_txnid(
|
db.transaction_ids.add_txnid(
|
||||||
@@ -85,9 +85,9 @@ pub async fn send_message_event_route(
|
|||||||
event_id.as_bytes(),
|
event_id.as_bytes(),
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
drop(mutex_lock);
|
drop(state_lock);
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(send_message_event::Response::new(event_id).into())
|
Ok(send_message_event::Response::new(event_id).into())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -75,5 +75,5 @@ pub const SESSION_ID_LENGTH: usize = 256;
|
|||||||
#[options("/<_..>")]
|
#[options("/<_..>")]
|
||||||
#[tracing::instrument]
|
#[tracing::instrument]
|
||||||
pub async fn options_route() -> ConduitResult<send_event_to_device::Response> {
|
pub async fn options_route() -> ConduitResult<send_event_to_device::Response> {
|
||||||
Ok(send_event_to_device::Response.into())
|
Ok(send_event_to_device::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,9 +41,9 @@ pub async fn set_presence_route(
|
|||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(set_presence::Response.into())
|
Ok(set_presence::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
use crate::{database::DatabaseGuard, pdu::PduBuilder, utils, ConduitResult, Error, Ruma};
|
use crate::{database::DatabaseGuard, pdu::PduBuilder, utils, ConduitResult, Error, Ruma};
|
||||||
use ruma::{
|
use ruma::{
|
||||||
api::client::{
|
api::{
|
||||||
error::ErrorKind,
|
client::{
|
||||||
r0::profile::{
|
error::ErrorKind,
|
||||||
get_avatar_url, get_display_name, get_profile, set_avatar_url, set_display_name,
|
r0::profile::{
|
||||||
|
get_avatar_url, get_display_name, get_profile, set_avatar_url, set_display_name,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
|
federation::{self, query::get_profile_information::v1::ProfileField},
|
||||||
},
|
},
|
||||||
events::EventType,
|
events::EventType,
|
||||||
serde::Raw,
|
serde::Raw,
|
||||||
@@ -29,9 +32,10 @@ pub async fn set_displayname_route(
|
|||||||
.set_displayname(&sender_user, body.displayname.clone())?;
|
.set_displayname(&sender_user, body.displayname.clone())?;
|
||||||
|
|
||||||
// Send a new membership event and presence update into all joined rooms
|
// Send a new membership event and presence update into all joined rooms
|
||||||
for (pdu_builder, room_id) in db
|
let all_rooms_joined = db.rooms.rooms_joined(&sender_user).collect::<Vec<_>>();
|
||||||
.rooms
|
|
||||||
.rooms_joined(&sender_user)
|
for (pdu_builder, room_id) in all_rooms_joined
|
||||||
|
.into_iter()
|
||||||
.filter_map(|r| r.ok())
|
.filter_map(|r| r.ok())
|
||||||
.map(|room_id| {
|
.map(|room_id| {
|
||||||
Ok::<_, Error>((
|
Ok::<_, Error>((
|
||||||
@@ -69,19 +73,19 @@ pub async fn set_displayname_route(
|
|||||||
})
|
})
|
||||||
.filter_map(|r| r.ok())
|
.filter_map(|r| r.ok())
|
||||||
{
|
{
|
||||||
let mutex = Arc::clone(
|
let mutex_state = Arc::clone(
|
||||||
db.globals
|
db.globals
|
||||||
.roomid_mutex
|
.roomid_mutex_state
|
||||||
.write()
|
.write()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.entry(room_id.clone())
|
.entry(room_id.clone())
|
||||||
.or_default(),
|
.or_default(),
|
||||||
);
|
);
|
||||||
let mutex_lock = mutex.lock().await;
|
let state_lock = mutex_state.lock().await;
|
||||||
|
|
||||||
let _ =
|
let _ =
|
||||||
db.rooms
|
db.rooms
|
||||||
.build_and_append_pdu(pdu_builder, &sender_user, &room_id, &db, &mutex_lock);
|
.build_and_append_pdu(pdu_builder, &sender_user, &room_id, &db, &state_lock);
|
||||||
|
|
||||||
// Presence update
|
// Presence update
|
||||||
db.rooms.edus.update_presence(
|
db.rooms.edus.update_presence(
|
||||||
@@ -106,9 +110,9 @@ pub async fn set_displayname_route(
|
|||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(set_display_name::Response.into())
|
Ok(set_display_name::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
@@ -120,6 +124,25 @@ pub async fn get_displayname_route(
|
|||||||
db: DatabaseGuard,
|
db: DatabaseGuard,
|
||||||
body: Ruma<get_display_name::Request<'_>>,
|
body: Ruma<get_display_name::Request<'_>>,
|
||||||
) -> ConduitResult<get_display_name::Response> {
|
) -> ConduitResult<get_display_name::Response> {
|
||||||
|
if body.user_id.server_name() != db.globals.server_name() {
|
||||||
|
let response = db
|
||||||
|
.sending
|
||||||
|
.send_federation_request(
|
||||||
|
&db.globals,
|
||||||
|
body.user_id.server_name(),
|
||||||
|
federation::query::get_profile_information::v1::Request {
|
||||||
|
user_id: &body.user_id,
|
||||||
|
field: Some(&ProfileField::DisplayName),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
return Ok(get_display_name::Response {
|
||||||
|
displayname: response.displayname,
|
||||||
|
}
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
|
||||||
Ok(get_display_name::Response {
|
Ok(get_display_name::Response {
|
||||||
displayname: db.users.displayname(&body.user_id)?,
|
displayname: db.users.displayname(&body.user_id)?,
|
||||||
}
|
}
|
||||||
@@ -140,10 +163,13 @@ pub async fn set_avatar_url_route(
|
|||||||
db.users
|
db.users
|
||||||
.set_avatar_url(&sender_user, body.avatar_url.clone())?;
|
.set_avatar_url(&sender_user, body.avatar_url.clone())?;
|
||||||
|
|
||||||
|
db.users.set_blurhash(&sender_user, body.blurhash.clone())?;
|
||||||
|
|
||||||
// Send a new membership event and presence update into all joined rooms
|
// Send a new membership event and presence update into all joined rooms
|
||||||
for (pdu_builder, room_id) in db
|
let all_joined_rooms = db.rooms.rooms_joined(&sender_user).collect::<Vec<_>>();
|
||||||
.rooms
|
|
||||||
.rooms_joined(&sender_user)
|
for (pdu_builder, room_id) in all_joined_rooms
|
||||||
|
.into_iter()
|
||||||
.filter_map(|r| r.ok())
|
.filter_map(|r| r.ok())
|
||||||
.map(|room_id| {
|
.map(|room_id| {
|
||||||
Ok::<_, Error>((
|
Ok::<_, Error>((
|
||||||
@@ -181,19 +207,19 @@ pub async fn set_avatar_url_route(
|
|||||||
})
|
})
|
||||||
.filter_map(|r| r.ok())
|
.filter_map(|r| r.ok())
|
||||||
{
|
{
|
||||||
let mutex = Arc::clone(
|
let mutex_state = Arc::clone(
|
||||||
db.globals
|
db.globals
|
||||||
.roomid_mutex
|
.roomid_mutex_state
|
||||||
.write()
|
.write()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.entry(room_id.clone())
|
.entry(room_id.clone())
|
||||||
.or_default(),
|
.or_default(),
|
||||||
);
|
);
|
||||||
let mutex_lock = mutex.lock().await;
|
let state_lock = mutex_state.lock().await;
|
||||||
|
|
||||||
let _ =
|
let _ =
|
||||||
db.rooms
|
db.rooms
|
||||||
.build_and_append_pdu(pdu_builder, &sender_user, &room_id, &db, &mutex_lock);
|
.build_and_append_pdu(pdu_builder, &sender_user, &room_id, &db, &state_lock);
|
||||||
|
|
||||||
// Presence update
|
// Presence update
|
||||||
db.rooms.edus.update_presence(
|
db.rooms.edus.update_presence(
|
||||||
@@ -218,9 +244,9 @@ pub async fn set_avatar_url_route(
|
|||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(set_avatar_url::Response.into())
|
Ok(set_avatar_url::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
@@ -232,8 +258,29 @@ pub async fn get_avatar_url_route(
|
|||||||
db: DatabaseGuard,
|
db: DatabaseGuard,
|
||||||
body: Ruma<get_avatar_url::Request<'_>>,
|
body: Ruma<get_avatar_url::Request<'_>>,
|
||||||
) -> ConduitResult<get_avatar_url::Response> {
|
) -> ConduitResult<get_avatar_url::Response> {
|
||||||
|
if body.user_id.server_name() != db.globals.server_name() {
|
||||||
|
let response = db
|
||||||
|
.sending
|
||||||
|
.send_federation_request(
|
||||||
|
&db.globals,
|
||||||
|
body.user_id.server_name(),
|
||||||
|
federation::query::get_profile_information::v1::Request {
|
||||||
|
user_id: &body.user_id,
|
||||||
|
field: Some(&ProfileField::AvatarUrl),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
return Ok(get_avatar_url::Response {
|
||||||
|
avatar_url: response.avatar_url,
|
||||||
|
blurhash: response.blurhash,
|
||||||
|
}
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
|
||||||
Ok(get_avatar_url::Response {
|
Ok(get_avatar_url::Response {
|
||||||
avatar_url: db.users.avatar_url(&body.user_id)?,
|
avatar_url: db.users.avatar_url(&body.user_id)?,
|
||||||
|
blurhash: db.users.blurhash(&body.user_id)?,
|
||||||
}
|
}
|
||||||
.into())
|
.into())
|
||||||
}
|
}
|
||||||
@@ -247,6 +294,27 @@ pub async fn get_profile_route(
|
|||||||
db: DatabaseGuard,
|
db: DatabaseGuard,
|
||||||
body: Ruma<get_profile::Request<'_>>,
|
body: Ruma<get_profile::Request<'_>>,
|
||||||
) -> ConduitResult<get_profile::Response> {
|
) -> ConduitResult<get_profile::Response> {
|
||||||
|
if body.user_id.server_name() != db.globals.server_name() {
|
||||||
|
let response = db
|
||||||
|
.sending
|
||||||
|
.send_federation_request(
|
||||||
|
&db.globals,
|
||||||
|
body.user_id.server_name(),
|
||||||
|
federation::query::get_profile_information::v1::Request {
|
||||||
|
user_id: &body.user_id,
|
||||||
|
field: None,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
return Ok(get_profile::Response {
|
||||||
|
displayname: response.displayname,
|
||||||
|
avatar_url: response.avatar_url,
|
||||||
|
blurhash: response.blurhash,
|
||||||
|
}
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
|
||||||
if !db.users.exists(&body.user_id)? {
|
if !db.users.exists(&body.user_id)? {
|
||||||
// Return 404 if this user doesn't exist
|
// Return 404 if this user doesn't exist
|
||||||
return Err(Error::BadRequest(
|
return Err(Error::BadRequest(
|
||||||
@@ -257,6 +325,7 @@ pub async fn get_profile_route(
|
|||||||
|
|
||||||
Ok(get_profile::Response {
|
Ok(get_profile::Response {
|
||||||
avatar_url: db.users.avatar_url(&body.user_id)?,
|
avatar_url: db.users.avatar_url(&body.user_id)?,
|
||||||
|
blurhash: db.users.blurhash(&body.user_id)?,
|
||||||
displayname: db.users.displayname(&body.user_id)?,
|
displayname: db.users.displayname(&body.user_id)?,
|
||||||
}
|
}
|
||||||
.into())
|
.into())
|
||||||
|
|||||||
+18
-18
@@ -81,7 +81,7 @@ pub async fn get_pushrule_route(
|
|||||||
.content
|
.content
|
||||||
.get(body.rule_id.as_str())
|
.get(body.rule_id.as_str())
|
||||||
.map(|rule| rule.clone().into()),
|
.map(|rule| rule.clone().into()),
|
||||||
RuleKind::_Custom(_) => None,
|
_ => None,
|
||||||
};
|
};
|
||||||
|
|
||||||
if let Some(rule) = rule {
|
if let Some(rule) = rule {
|
||||||
@@ -181,7 +181,7 @@ pub async fn set_pushrule_route(
|
|||||||
.into(),
|
.into(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
RuleKind::_Custom(_) => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
|
||||||
db.account_data.update(
|
db.account_data.update(
|
||||||
@@ -192,9 +192,9 @@ pub async fn set_pushrule_route(
|
|||||||
&db.globals,
|
&db.globals,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(set_pushrule::Response.into())
|
Ok(set_pushrule::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
@@ -245,10 +245,10 @@ pub async fn get_pushrule_actions_route(
|
|||||||
.content
|
.content
|
||||||
.get(body.rule_id.as_str())
|
.get(body.rule_id.as_str())
|
||||||
.map(|rule| rule.actions.clone()),
|
.map(|rule| rule.actions.clone()),
|
||||||
RuleKind::_Custom(_) => None,
|
_ => None,
|
||||||
};
|
};
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(get_pushrule_actions::Response {
|
Ok(get_pushrule_actions::Response {
|
||||||
actions: actions.unwrap_or_default(),
|
actions: actions.unwrap_or_default(),
|
||||||
@@ -314,7 +314,7 @@ pub async fn set_pushrule_actions_route(
|
|||||||
global.content.replace(rule);
|
global.content.replace(rule);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
RuleKind::_Custom(_) => {}
|
_ => {}
|
||||||
};
|
};
|
||||||
|
|
||||||
db.account_data.update(
|
db.account_data.update(
|
||||||
@@ -325,9 +325,9 @@ pub async fn set_pushrule_actions_route(
|
|||||||
&db.globals,
|
&db.globals,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(set_pushrule_actions::Response.into())
|
Ok(set_pushrule_actions::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
@@ -383,10 +383,10 @@ pub async fn get_pushrule_enabled_route(
|
|||||||
.iter()
|
.iter()
|
||||||
.find(|rule| rule.rule_id == body.rule_id)
|
.find(|rule| rule.rule_id == body.rule_id)
|
||||||
.map_or(false, |rule| rule.enabled),
|
.map_or(false, |rule| rule.enabled),
|
||||||
RuleKind::_Custom(_) => false,
|
_ => false,
|
||||||
};
|
};
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(get_pushrule_enabled::Response { enabled }.into())
|
Ok(get_pushrule_enabled::Response { enabled }.into())
|
||||||
}
|
}
|
||||||
@@ -454,7 +454,7 @@ pub async fn set_pushrule_enabled_route(
|
|||||||
global.content.insert(rule);
|
global.content.insert(rule);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
RuleKind::_Custom(_) => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
|
||||||
db.account_data.update(
|
db.account_data.update(
|
||||||
@@ -465,9 +465,9 @@ pub async fn set_pushrule_enabled_route(
|
|||||||
&db.globals,
|
&db.globals,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(set_pushrule_enabled::Response.into())
|
Ok(set_pushrule_enabled::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
@@ -523,7 +523,7 @@ pub async fn delete_pushrule_route(
|
|||||||
global.content.remove(&rule);
|
global.content.remove(&rule);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
RuleKind::_Custom(_) => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
|
||||||
db.account_data.update(
|
db.account_data.update(
|
||||||
@@ -534,9 +534,9 @@ pub async fn delete_pushrule_route(
|
|||||||
&db.globals,
|
&db.globals,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(delete_pushrule::Response.into())
|
Ok(delete_pushrule::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
@@ -570,7 +570,7 @@ pub async fn set_pushers_route(
|
|||||||
|
|
||||||
db.pusher.set_pusher(sender_user, pusher)?;
|
db.pusher.set_pusher(sender_user, pusher)?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(set_pusher::Response::default().into())
|
Ok(set_pusher::Response::default().into())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -75,9 +75,9 @@ pub async fn set_read_marker_route(
|
|||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(set_read_marker::Response.into())
|
Ok(set_read_marker::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
@@ -128,7 +128,7 @@ pub async fn create_receipt_route(
|
|||||||
&db.globals,
|
&db.globals,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(create_receipt::Response.into())
|
Ok(create_receipt::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,15 +20,15 @@ pub async fn redact_event_route(
|
|||||||
) -> ConduitResult<redact_event::Response> {
|
) -> ConduitResult<redact_event::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
|
|
||||||
let mutex = Arc::clone(
|
let mutex_state = Arc::clone(
|
||||||
db.globals
|
db.globals
|
||||||
.roomid_mutex
|
.roomid_mutex_state
|
||||||
.write()
|
.write()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.entry(body.room_id.clone())
|
.entry(body.room_id.clone())
|
||||||
.or_default(),
|
.or_default(),
|
||||||
);
|
);
|
||||||
let mutex_lock = mutex.lock().await;
|
let state_lock = mutex_state.lock().await;
|
||||||
|
|
||||||
let event_id = db.rooms.build_and_append_pdu(
|
let event_id = db.rooms.build_and_append_pdu(
|
||||||
PduBuilder {
|
PduBuilder {
|
||||||
@@ -44,12 +44,12 @@ pub async fn redact_event_route(
|
|||||||
&sender_user,
|
&sender_user,
|
||||||
&body.room_id,
|
&body.room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
drop(mutex_lock);
|
drop(state_lock);
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(redact_event::Response { event_id }.into())
|
Ok(redact_event::Response { event_id }.into())
|
||||||
}
|
}
|
||||||
|
|||||||
+93
-41
@@ -2,11 +2,10 @@ use crate::{
|
|||||||
client_server::invite_helper, database::DatabaseGuard, pdu::PduBuilder, ConduitResult, Error,
|
client_server::invite_helper, database::DatabaseGuard, pdu::PduBuilder, ConduitResult, Error,
|
||||||
Ruma,
|
Ruma,
|
||||||
};
|
};
|
||||||
use log::info;
|
|
||||||
use ruma::{
|
use ruma::{
|
||||||
api::client::{
|
api::client::{
|
||||||
error::ErrorKind,
|
error::ErrorKind,
|
||||||
r0::room::{self, create_room, get_room_event, upgrade_room},
|
r0::room::{self, aliases, create_room, get_room_event, upgrade_room},
|
||||||
},
|
},
|
||||||
events::{
|
events::{
|
||||||
room::{guest_access, history_visibility, join_rules, member, name, topic},
|
room::{guest_access, history_visibility, join_rules, member, name, topic},
|
||||||
@@ -16,6 +15,7 @@ use ruma::{
|
|||||||
RoomAliasId, RoomId, RoomVersionId,
|
RoomAliasId, RoomId, RoomVersionId,
|
||||||
};
|
};
|
||||||
use std::{cmp::max, collections::BTreeMap, convert::TryFrom, sync::Arc};
|
use std::{cmp::max, collections::BTreeMap, convert::TryFrom, sync::Arc};
|
||||||
|
use tracing::{info, warn};
|
||||||
|
|
||||||
#[cfg(feature = "conduit_bin")]
|
#[cfg(feature = "conduit_bin")]
|
||||||
use rocket::{get, post};
|
use rocket::{get, post};
|
||||||
@@ -33,15 +33,15 @@ pub async fn create_room_route(
|
|||||||
|
|
||||||
let room_id = RoomId::new(db.globals.server_name());
|
let room_id = RoomId::new(db.globals.server_name());
|
||||||
|
|
||||||
let mutex = Arc::clone(
|
let mutex_state = Arc::clone(
|
||||||
db.globals
|
db.globals
|
||||||
.roomid_mutex
|
.roomid_mutex_state
|
||||||
.write()
|
.write()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.entry(room_id.clone())
|
.entry(room_id.clone())
|
||||||
.or_default(),
|
.or_default(),
|
||||||
);
|
);
|
||||||
let mutex_lock = mutex.lock().await;
|
let state_lock = mutex_state.lock().await;
|
||||||
|
|
||||||
let alias = body
|
let alias = body
|
||||||
.room_alias_name
|
.room_alias_name
|
||||||
@@ -65,7 +65,19 @@ pub async fn create_room_route(
|
|||||||
let mut content = ruma::events::room::create::CreateEventContent::new(sender_user.clone());
|
let mut content = ruma::events::room::create::CreateEventContent::new(sender_user.clone());
|
||||||
content.federate = body.creation_content.federate;
|
content.federate = body.creation_content.federate;
|
||||||
content.predecessor = body.creation_content.predecessor.clone();
|
content.predecessor = body.creation_content.predecessor.clone();
|
||||||
content.room_version = RoomVersionId::Version6;
|
content.room_version = match body.room_version.clone() {
|
||||||
|
Some(room_version) => {
|
||||||
|
if room_version == RoomVersionId::Version5 || room_version == RoomVersionId::Version6 {
|
||||||
|
room_version
|
||||||
|
} else {
|
||||||
|
return Err(Error::BadRequest(
|
||||||
|
ErrorKind::UnsupportedRoomVersion,
|
||||||
|
"This server does not support that room version.",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => RoomVersionId::Version6,
|
||||||
|
};
|
||||||
|
|
||||||
// 1. The room create event
|
// 1. The room create event
|
||||||
db.rooms.build_and_append_pdu(
|
db.rooms.build_and_append_pdu(
|
||||||
@@ -79,7 +91,7 @@ pub async fn create_room_route(
|
|||||||
&sender_user,
|
&sender_user,
|
||||||
&room_id,
|
&room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
// 2. Let the room creator join
|
// 2. Let the room creator join
|
||||||
@@ -92,6 +104,7 @@ pub async fn create_room_route(
|
|||||||
avatar_url: db.users.avatar_url(&sender_user)?,
|
avatar_url: db.users.avatar_url(&sender_user)?,
|
||||||
is_direct: Some(body.is_direct),
|
is_direct: Some(body.is_direct),
|
||||||
third_party_invite: None,
|
third_party_invite: None,
|
||||||
|
blurhash: db.users.blurhash(&sender_user)?,
|
||||||
})
|
})
|
||||||
.expect("event is valid, we just created it"),
|
.expect("event is valid, we just created it"),
|
||||||
unsigned: None,
|
unsigned: None,
|
||||||
@@ -101,7 +114,7 @@ pub async fn create_room_route(
|
|||||||
&sender_user,
|
&sender_user,
|
||||||
&room_id,
|
&room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
// 3. Power levels
|
// 3. Power levels
|
||||||
@@ -113,7 +126,7 @@ pub async fn create_room_route(
|
|||||||
.unwrap_or_else(|| match &body.visibility {
|
.unwrap_or_else(|| match &body.visibility {
|
||||||
room::Visibility::Private => create_room::RoomPreset::PrivateChat,
|
room::Visibility::Private => create_room::RoomPreset::PrivateChat,
|
||||||
room::Visibility::Public => create_room::RoomPreset::PublicChat,
|
room::Visibility::Public => create_room::RoomPreset::PublicChat,
|
||||||
room::Visibility::_Custom(_) => create_room::RoomPreset::PrivateChat, // Room visibility should not be custom
|
_ => create_room::RoomPreset::PrivateChat, // Room visibility should not be custom
|
||||||
});
|
});
|
||||||
|
|
||||||
let mut users = BTreeMap::new();
|
let mut users = BTreeMap::new();
|
||||||
@@ -156,7 +169,7 @@ pub async fn create_room_route(
|
|||||||
&sender_user,
|
&sender_user,
|
||||||
&room_id,
|
&room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
// 4. Events set by preset
|
// 4. Events set by preset
|
||||||
@@ -183,7 +196,7 @@ pub async fn create_room_route(
|
|||||||
&sender_user,
|
&sender_user,
|
||||||
&room_id,
|
&room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
// 4.2 History Visibility
|
// 4.2 History Visibility
|
||||||
@@ -201,7 +214,7 @@ pub async fn create_room_route(
|
|||||||
&sender_user,
|
&sender_user,
|
||||||
&room_id,
|
&room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
// 4.3 Guest Access
|
// 4.3 Guest Access
|
||||||
@@ -227,15 +240,15 @@ pub async fn create_room_route(
|
|||||||
&sender_user,
|
&sender_user,
|
||||||
&room_id,
|
&room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
// 5. Events listed in initial_state
|
// 5. Events listed in initial_state
|
||||||
for event in &body.initial_state {
|
for event in &body.initial_state {
|
||||||
let pdu_builder = serde_json::from_str::<PduBuilder>(
|
let pdu_builder = PduBuilder::from(event.deserialize().map_err(|e| {
|
||||||
&serde_json::to_string(&event).expect("AnyInitialStateEvent::to_string always works"),
|
warn!("Invalid initial state event: {:?}", e);
|
||||||
)
|
Error::BadRequest(ErrorKind::InvalidParam, "Invalid initial state event.")
|
||||||
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid initial state event."))?;
|
})?);
|
||||||
|
|
||||||
// Silently skip encryption events if they are not allowed
|
// Silently skip encryption events if they are not allowed
|
||||||
if pdu_builder.event_type == EventType::RoomEncryption && !db.globals.allow_encryption() {
|
if pdu_builder.event_type == EventType::RoomEncryption && !db.globals.allow_encryption() {
|
||||||
@@ -243,7 +256,7 @@ pub async fn create_room_route(
|
|||||||
}
|
}
|
||||||
|
|
||||||
db.rooms
|
db.rooms
|
||||||
.build_and_append_pdu(pdu_builder, &sender_user, &room_id, &db, &mutex_lock)?;
|
.build_and_append_pdu(pdu_builder, &sender_user, &room_id, &db, &state_lock)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 6. Events implied by name and topic
|
// 6. Events implied by name and topic
|
||||||
@@ -251,12 +264,8 @@ pub async fn create_room_route(
|
|||||||
db.rooms.build_and_append_pdu(
|
db.rooms.build_and_append_pdu(
|
||||||
PduBuilder {
|
PduBuilder {
|
||||||
event_type: EventType::RoomName,
|
event_type: EventType::RoomName,
|
||||||
content: serde_json::to_value(
|
content: serde_json::to_value(name::NameEventContent::new(Some(name.clone())))
|
||||||
name::NameEventContent::new(name.clone()).map_err(|_| {
|
.expect("event is valid, we just created it"),
|
||||||
Error::BadRequest(ErrorKind::InvalidParam, "Name is invalid.")
|
|
||||||
})?,
|
|
||||||
)
|
|
||||||
.expect("event is valid, we just created it"),
|
|
||||||
unsigned: None,
|
unsigned: None,
|
||||||
state_key: Some("".to_owned()),
|
state_key: Some("".to_owned()),
|
||||||
redacts: None,
|
redacts: None,
|
||||||
@@ -264,7 +273,7 @@ pub async fn create_room_route(
|
|||||||
&sender_user,
|
&sender_user,
|
||||||
&room_id,
|
&room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -283,12 +292,12 @@ pub async fn create_room_route(
|
|||||||
&sender_user,
|
&sender_user,
|
||||||
&room_id,
|
&room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 7. Events implied by invite (and TODO: invite_3pid)
|
// 7. Events implied by invite (and TODO: invite_3pid)
|
||||||
drop(mutex_lock);
|
drop(state_lock);
|
||||||
for user_id in &body.invite {
|
for user_id in &body.invite {
|
||||||
let _ = invite_helper(sender_user, user_id, &room_id, &db, body.is_direct).await;
|
let _ = invite_helper(sender_user, user_id, &room_id, &db, body.is_direct).await;
|
||||||
}
|
}
|
||||||
@@ -304,7 +313,7 @@ pub async fn create_room_route(
|
|||||||
|
|
||||||
info!("{} created a room", sender_user);
|
info!("{} created a room", sender_user);
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(create_room::Response::new(room_id).into())
|
Ok(create_room::Response::new(room_id).into())
|
||||||
}
|
}
|
||||||
@@ -339,17 +348,47 @@ pub async fn get_room_event_route(
|
|||||||
|
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
feature = "conduit_bin",
|
feature = "conduit_bin",
|
||||||
post("/_matrix/client/r0/rooms/<_room_id>/upgrade", data = "<body>")
|
get("/_matrix/client/r0/rooms/<_>/aliases", data = "<body>")
|
||||||
|
)]
|
||||||
|
#[tracing::instrument(skip(db, body))]
|
||||||
|
pub async fn get_room_aliases_route(
|
||||||
|
db: DatabaseGuard,
|
||||||
|
body: Ruma<aliases::Request<'_>>,
|
||||||
|
) -> ConduitResult<aliases::Response> {
|
||||||
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
|
|
||||||
|
if !db.rooms.is_joined(sender_user, &body.room_id)? {
|
||||||
|
return Err(Error::BadRequest(
|
||||||
|
ErrorKind::Forbidden,
|
||||||
|
"You don't have permission to view this room.",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(aliases::Response {
|
||||||
|
aliases: db
|
||||||
|
.rooms
|
||||||
|
.room_aliases(&body.room_id)
|
||||||
|
.filter_map(|a| a.ok())
|
||||||
|
.collect(),
|
||||||
|
}
|
||||||
|
.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg_attr(
|
||||||
|
feature = "conduit_bin",
|
||||||
|
post("/_matrix/client/r0/rooms/<_>/upgrade", data = "<body>")
|
||||||
)]
|
)]
|
||||||
#[tracing::instrument(skip(db, body))]
|
#[tracing::instrument(skip(db, body))]
|
||||||
pub async fn upgrade_room_route(
|
pub async fn upgrade_room_route(
|
||||||
db: DatabaseGuard,
|
db: DatabaseGuard,
|
||||||
body: Ruma<upgrade_room::Request<'_>>,
|
body: Ruma<upgrade_room::Request<'_>>,
|
||||||
_room_id: String,
|
|
||||||
) -> ConduitResult<upgrade_room::Response> {
|
) -> ConduitResult<upgrade_room::Response> {
|
||||||
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
|
||||||
|
|
||||||
if !matches!(body.new_version, RoomVersionId::Version6) {
|
if !matches!(
|
||||||
|
body.new_version,
|
||||||
|
RoomVersionId::Version5 | RoomVersionId::Version6
|
||||||
|
) {
|
||||||
return Err(Error::BadRequest(
|
return Err(Error::BadRequest(
|
||||||
ErrorKind::UnsupportedRoomVersion,
|
ErrorKind::UnsupportedRoomVersion,
|
||||||
"This server does not support that room version.",
|
"This server does not support that room version.",
|
||||||
@@ -359,15 +398,15 @@ pub async fn upgrade_room_route(
|
|||||||
// Create a replacement room
|
// Create a replacement room
|
||||||
let replacement_room = RoomId::new(db.globals.server_name());
|
let replacement_room = RoomId::new(db.globals.server_name());
|
||||||
|
|
||||||
let mutex = Arc::clone(
|
let mutex_state = Arc::clone(
|
||||||
db.globals
|
db.globals
|
||||||
.roomid_mutex
|
.roomid_mutex_state
|
||||||
.write()
|
.write()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.entry(body.room_id.clone())
|
.entry(body.room_id.clone())
|
||||||
.or_default(),
|
.or_default(),
|
||||||
);
|
);
|
||||||
let mutex_lock = mutex.lock().await;
|
let state_lock = mutex_state.lock().await;
|
||||||
|
|
||||||
// Send a m.room.tombstone event to the old room to indicate that it is not intended to be used any further
|
// Send a m.room.tombstone event to the old room to indicate that it is not intended to be used any further
|
||||||
// Fail if the sender does not have the required permissions
|
// Fail if the sender does not have the required permissions
|
||||||
@@ -386,9 +425,21 @@ pub async fn upgrade_room_route(
|
|||||||
sender_user,
|
sender_user,
|
||||||
&body.room_id,
|
&body.room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
|
// Change lock to replacement room
|
||||||
|
drop(state_lock);
|
||||||
|
let mutex_state = Arc::clone(
|
||||||
|
db.globals
|
||||||
|
.roomid_mutex_state
|
||||||
|
.write()
|
||||||
|
.unwrap()
|
||||||
|
.entry(replacement_room.clone())
|
||||||
|
.or_default(),
|
||||||
|
);
|
||||||
|
let state_lock = mutex_state.lock().await;
|
||||||
|
|
||||||
// Get the old room federations status
|
// Get the old room federations status
|
||||||
let federate = serde_json::from_value::<Raw<ruma::events::room::create::CreateEventContent>>(
|
let federate = serde_json::from_value::<Raw<ruma::events::room::create::CreateEventContent>>(
|
||||||
db.rooms
|
db.rooms
|
||||||
@@ -427,7 +478,7 @@ pub async fn upgrade_room_route(
|
|||||||
sender_user,
|
sender_user,
|
||||||
&replacement_room,
|
&replacement_room,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
// Join the new room
|
// Join the new room
|
||||||
@@ -440,6 +491,7 @@ pub async fn upgrade_room_route(
|
|||||||
avatar_url: db.users.avatar_url(&sender_user)?,
|
avatar_url: db.users.avatar_url(&sender_user)?,
|
||||||
is_direct: None,
|
is_direct: None,
|
||||||
third_party_invite: None,
|
third_party_invite: None,
|
||||||
|
blurhash: db.users.blurhash(&sender_user)?,
|
||||||
})
|
})
|
||||||
.expect("event is valid, we just created it"),
|
.expect("event is valid, we just created it"),
|
||||||
unsigned: None,
|
unsigned: None,
|
||||||
@@ -449,7 +501,7 @@ pub async fn upgrade_room_route(
|
|||||||
sender_user,
|
sender_user,
|
||||||
&replacement_room,
|
&replacement_room,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
// Recommended transferable state events list from the specs
|
// Recommended transferable state events list from the specs
|
||||||
@@ -483,7 +535,7 @@ pub async fn upgrade_room_route(
|
|||||||
sender_user,
|
sender_user,
|
||||||
&replacement_room,
|
&replacement_room,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -527,12 +579,12 @@ pub async fn upgrade_room_route(
|
|||||||
sender_user,
|
sender_user,
|
||||||
&body.room_id,
|
&body.room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
drop(mutex_lock);
|
drop(state_lock);
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
// Return the replacement room id
|
// Return the replacement room id
|
||||||
Ok(upgrade_room::Response { replacement_room }.into())
|
Ok(upgrade_room::Response { replacement_room }.into())
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH};
|
use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH};
|
||||||
use crate::{database::DatabaseGuard, utils, ConduitResult, Error, Ruma};
|
use crate::{database::DatabaseGuard, utils, ConduitResult, Error, Ruma};
|
||||||
use log::info;
|
|
||||||
use ruma::{
|
use ruma::{
|
||||||
api::client::{
|
api::client::{
|
||||||
error::ErrorKind,
|
error::ErrorKind,
|
||||||
@@ -9,6 +8,7 @@ use ruma::{
|
|||||||
UserId,
|
UserId,
|
||||||
};
|
};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
use tracing::info;
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
struct Claims {
|
struct Claims {
|
||||||
@@ -143,7 +143,7 @@ pub async fn login_route(
|
|||||||
|
|
||||||
info!("{} logged in", user_id);
|
info!("{} logged in", user_id);
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(login::Response {
|
Ok(login::Response {
|
||||||
user_id,
|
user_id,
|
||||||
@@ -175,7 +175,7 @@ pub async fn logout_route(
|
|||||||
|
|
||||||
db.users.remove_device(&sender_user, sender_device)?;
|
db.users.remove_device(&sender_user, sender_device)?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(logout::Response::new().into())
|
Ok(logout::Response::new().into())
|
||||||
}
|
}
|
||||||
@@ -204,7 +204,7 @@ pub async fn logout_all_route(
|
|||||||
db.users.remove_device(&sender_user, &device_id)?;
|
db.users.remove_device(&sender_user, &device_id)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(logout_all::Response::new().into())
|
Ok(logout_all::Response::new().into())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ pub async fn send_state_event_for_key_route(
|
|||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(send_state_event::Response { event_id }.into())
|
Ok(send_state_event::Response { event_id }.into())
|
||||||
}
|
}
|
||||||
@@ -69,7 +69,7 @@ pub async fn send_state_event_for_empty_key_route(
|
|||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(send_state_event::Response { event_id }.into())
|
Ok(send_state_event::Response { event_id }.into())
|
||||||
}
|
}
|
||||||
@@ -259,15 +259,15 @@ pub async fn send_state_event_for_key_helper(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let mutex = Arc::clone(
|
let mutex_state = Arc::clone(
|
||||||
db.globals
|
db.globals
|
||||||
.roomid_mutex
|
.roomid_mutex_state
|
||||||
.write()
|
.write()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.entry(room_id.clone())
|
.entry(room_id.clone())
|
||||||
.or_default(),
|
.or_default(),
|
||||||
);
|
);
|
||||||
let mutex_lock = mutex.lock().await;
|
let state_lock = mutex_state.lock().await;
|
||||||
|
|
||||||
let event_id = db.rooms.build_and_append_pdu(
|
let event_id = db.rooms.build_and_append_pdu(
|
||||||
PduBuilder {
|
PduBuilder {
|
||||||
@@ -280,7 +280,7 @@ pub async fn send_state_event_for_key_helper(
|
|||||||
&sender_user,
|
&sender_user,
|
||||||
&room_id,
|
&room_id,
|
||||||
&db,
|
&db,
|
||||||
&mutex_lock,
|
&state_lock,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
Ok(event_id)
|
Ok(event_id)
|
||||||
|
|||||||
+33
-21
@@ -1,5 +1,4 @@
|
|||||||
use crate::{database::DatabaseGuard, ConduitResult, Database, Error, Result, Ruma, RumaResponse};
|
use crate::{database::DatabaseGuard, ConduitResult, Database, Error, Result, Ruma, RumaResponse};
|
||||||
use log::error;
|
|
||||||
use ruma::{
|
use ruma::{
|
||||||
api::client::r0::{sync::sync_events, uiaa::UiaaResponse},
|
api::client::r0::{sync::sync_events, uiaa::UiaaResponse},
|
||||||
events::{room::member::MembershipState, AnySyncEphemeralRoomEvent, EventType},
|
events::{room::member::MembershipState, AnySyncEphemeralRoomEvent, EventType},
|
||||||
@@ -7,12 +6,13 @@ use ruma::{
|
|||||||
DeviceId, RoomId, UserId,
|
DeviceId, RoomId, UserId,
|
||||||
};
|
};
|
||||||
use std::{
|
use std::{
|
||||||
collections::{btree_map::Entry, hash_map, BTreeMap, HashMap, HashSet},
|
collections::{hash_map::Entry, BTreeMap, HashMap, HashSet},
|
||||||
convert::{TryFrom, TryInto},
|
convert::{TryFrom, TryInto},
|
||||||
sync::Arc,
|
sync::Arc,
|
||||||
time::Duration,
|
time::Duration,
|
||||||
};
|
};
|
||||||
use tokio::sync::watch::Sender;
|
use tokio::sync::watch::Sender;
|
||||||
|
use tracing::{error, warn};
|
||||||
|
|
||||||
#[cfg(feature = "conduit_bin")]
|
#[cfg(feature = "conduit_bin")]
|
||||||
use rocket::{get, tokio};
|
use rocket::{get, tokio};
|
||||||
@@ -186,20 +186,22 @@ async fn sync_helper(
|
|||||||
.filter_map(|r| r.ok()),
|
.filter_map(|r| r.ok()),
|
||||||
);
|
);
|
||||||
|
|
||||||
for room_id in db.rooms.rooms_joined(&sender_user) {
|
let all_joined_rooms = db.rooms.rooms_joined(&sender_user).collect::<Vec<_>>();
|
||||||
|
for room_id in all_joined_rooms {
|
||||||
let room_id = room_id?;
|
let room_id = room_id?;
|
||||||
|
|
||||||
// Get and drop the lock to wait for remaining operations to finish
|
// Get and drop the lock to wait for remaining operations to finish
|
||||||
let mutex = Arc::clone(
|
// This will make sure the we have all events until next_batch
|
||||||
|
let mutex_insert = Arc::clone(
|
||||||
db.globals
|
db.globals
|
||||||
.roomid_mutex
|
.roomid_mutex_insert
|
||||||
.write()
|
.write()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.entry(room_id.clone())
|
.entry(room_id.clone())
|
||||||
.or_default(),
|
.or_default(),
|
||||||
);
|
);
|
||||||
let mutex_lock = mutex.lock().await;
|
let insert_lock = mutex_insert.lock().unwrap();
|
||||||
drop(mutex_lock);
|
drop(insert_lock);
|
||||||
|
|
||||||
let mut non_timeline_pdus = db
|
let mut non_timeline_pdus = db
|
||||||
.rooms
|
.rooms
|
||||||
@@ -262,8 +264,12 @@ async fn sync_helper(
|
|||||||
db.rooms
|
db.rooms
|
||||||
.pdu_shortstatehash(&pdu.1.event_id)
|
.pdu_shortstatehash(&pdu.1.event_id)
|
||||||
.transpose()
|
.transpose()
|
||||||
.expect("all pdus have state")
|
.ok_or_else(|| {
|
||||||
|
warn!("PDU without state: {}", pdu.1.event_id);
|
||||||
|
Error::bad_database("Found PDU without state")
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
.transpose()?
|
||||||
.transpose()?;
|
.transpose()?;
|
||||||
|
|
||||||
// Calculates joined_member_count, invited_member_count and heroes
|
// Calculates joined_member_count, invited_member_count and heroes
|
||||||
@@ -417,7 +423,10 @@ async fn sync_helper(
|
|||||||
|
|
||||||
let send_member_count = state_events
|
let send_member_count = state_events
|
||||||
.iter()
|
.iter()
|
||||||
.any(|event| event.kind == EventType::RoomMember);
|
.any(|event| event.kind == EventType::RoomMember)
|
||||||
|
|| timeline_pdus.iter().any(|(_, event)| {
|
||||||
|
event.state_key.is_some() && event.kind == EventType::RoomMember
|
||||||
|
});
|
||||||
|
|
||||||
if encrypted_room {
|
if encrypted_room {
|
||||||
for (user_id, current_member) in db
|
for (user_id, current_member) in db
|
||||||
@@ -622,10 +631,10 @@ async fn sync_helper(
|
|||||||
.presence_since(&room_id, since, &db.rooms, &db.globals)?
|
.presence_since(&room_id, since, &db.rooms, &db.globals)?
|
||||||
{
|
{
|
||||||
match presence_updates.entry(user_id) {
|
match presence_updates.entry(user_id) {
|
||||||
hash_map::Entry::Vacant(v) => {
|
Entry::Vacant(v) => {
|
||||||
v.insert(presence);
|
v.insert(presence);
|
||||||
}
|
}
|
||||||
hash_map::Entry::Occupied(mut o) => {
|
Entry::Occupied(mut o) => {
|
||||||
let p = o.get_mut();
|
let p = o.get_mut();
|
||||||
|
|
||||||
// Update existing presence event with more info
|
// Update existing presence event with more info
|
||||||
@@ -651,20 +660,21 @@ async fn sync_helper(
|
|||||||
}
|
}
|
||||||
|
|
||||||
let mut left_rooms = BTreeMap::new();
|
let mut left_rooms = BTreeMap::new();
|
||||||
for result in db.rooms.rooms_left(&sender_user) {
|
let all_left_rooms = db.rooms.rooms_left(&sender_user).collect::<Vec<_>>();
|
||||||
|
for result in all_left_rooms {
|
||||||
let (room_id, left_state_events) = result?;
|
let (room_id, left_state_events) = result?;
|
||||||
|
|
||||||
// Get and drop the lock to wait for remaining operations to finish
|
// Get and drop the lock to wait for remaining operations to finish
|
||||||
let mutex = Arc::clone(
|
let mutex_insert = Arc::clone(
|
||||||
db.globals
|
db.globals
|
||||||
.roomid_mutex
|
.roomid_mutex_insert
|
||||||
.write()
|
.write()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.entry(room_id.clone())
|
.entry(room_id.clone())
|
||||||
.or_default(),
|
.or_default(),
|
||||||
);
|
);
|
||||||
let mutex_lock = mutex.lock().await;
|
let insert_lock = mutex_insert.lock().unwrap();
|
||||||
drop(mutex_lock);
|
drop(insert_lock);
|
||||||
|
|
||||||
let left_count = db.rooms.get_left_count(&room_id, &sender_user)?;
|
let left_count = db.rooms.get_left_count(&room_id, &sender_user)?;
|
||||||
|
|
||||||
@@ -690,20 +700,21 @@ async fn sync_helper(
|
|||||||
}
|
}
|
||||||
|
|
||||||
let mut invited_rooms = BTreeMap::new();
|
let mut invited_rooms = BTreeMap::new();
|
||||||
for result in db.rooms.rooms_invited(&sender_user) {
|
let all_invited_rooms = db.rooms.rooms_invited(&sender_user).collect::<Vec<_>>();
|
||||||
|
for result in all_invited_rooms {
|
||||||
let (room_id, invite_state_events) = result?;
|
let (room_id, invite_state_events) = result?;
|
||||||
|
|
||||||
// Get and drop the lock to wait for remaining operations to finish
|
// Get and drop the lock to wait for remaining operations to finish
|
||||||
let mutex = Arc::clone(
|
let mutex_insert = Arc::clone(
|
||||||
db.globals
|
db.globals
|
||||||
.roomid_mutex
|
.roomid_mutex_insert
|
||||||
.write()
|
.write()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.entry(room_id.clone())
|
.entry(room_id.clone())
|
||||||
.or_default(),
|
.or_default(),
|
||||||
);
|
);
|
||||||
let mutex_lock = mutex.lock().await;
|
let insert_lock = mutex_insert.lock().unwrap();
|
||||||
drop(mutex_lock);
|
drop(insert_lock);
|
||||||
|
|
||||||
let invite_count = db.rooms.get_invite_count(&room_id, &sender_user)?;
|
let invite_count = db.rooms.get_invite_count(&room_id, &sender_user)?;
|
||||||
|
|
||||||
@@ -753,6 +764,7 @@ async fn sync_helper(
|
|||||||
leave: left_rooms,
|
leave: left_rooms,
|
||||||
join: joined_rooms,
|
join: joined_rooms,
|
||||||
invite: invited_rooms,
|
invite: invited_rooms,
|
||||||
|
knock: BTreeMap::new(), // TODO
|
||||||
},
|
},
|
||||||
presence: sync_events::Presence {
|
presence: sync_events::Presence {
|
||||||
events: presence_updates
|
events: presence_updates
|
||||||
|
|||||||
@@ -40,9 +40,9 @@ pub async fn update_tag_route(
|
|||||||
&db.globals,
|
&db.globals,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(create_tag::Response.into())
|
Ok(create_tag::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
@@ -74,9 +74,9 @@ pub async fn delete_tag_route(
|
|||||||
&db.globals,
|
&db.globals,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(delete_tag::Response.into())
|
Ok(delete_tag::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
|
|||||||
@@ -1,6 +1,12 @@
|
|||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
use crate::{database::DatabaseGuard, ConduitResult, Error, Ruma};
|
use crate::{database::DatabaseGuard, ConduitResult, Error, Ruma};
|
||||||
use ruma::{
|
use ruma::{
|
||||||
api::client::{error::ErrorKind, r0::to_device::send_event_to_device},
|
api::{
|
||||||
|
client::{error::ErrorKind, r0::to_device::send_event_to_device},
|
||||||
|
federation::{self, transactions::edu::DirectDeviceContent},
|
||||||
|
},
|
||||||
|
events::EventType,
|
||||||
to_device::DeviceIdOrAllDevices,
|
to_device::DeviceIdOrAllDevices,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -33,6 +39,28 @@ pub async fn send_event_to_device_route(
|
|||||||
|
|
||||||
for (target_user_id, map) in &body.messages {
|
for (target_user_id, map) in &body.messages {
|
||||||
for (target_device_id_maybe, event) in map {
|
for (target_device_id_maybe, event) in map {
|
||||||
|
if target_user_id.server_name() != db.globals.server_name() {
|
||||||
|
let mut map = BTreeMap::new();
|
||||||
|
map.insert(target_device_id_maybe.clone(), event.clone());
|
||||||
|
let mut messages = BTreeMap::new();
|
||||||
|
messages.insert(target_user_id.clone(), map);
|
||||||
|
|
||||||
|
db.sending.send_reliable_edu(
|
||||||
|
target_user_id.server_name(),
|
||||||
|
serde_json::to_vec(&federation::transactions::edu::Edu::DirectToDevice(
|
||||||
|
DirectDeviceContent {
|
||||||
|
sender: sender_user.clone(),
|
||||||
|
ev_type: EventType::from(&body.event_type),
|
||||||
|
message_id: body.txn_id.clone(),
|
||||||
|
messages,
|
||||||
|
},
|
||||||
|
))
|
||||||
|
.expect("DirectToDevice EDU can be serialized"),
|
||||||
|
)?;
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
match target_device_id_maybe {
|
match target_device_id_maybe {
|
||||||
DeviceIdOrAllDevices::DeviceId(target_device_id) => db.users.add_to_device_event(
|
DeviceIdOrAllDevices::DeviceId(target_device_id) => db.users.add_to_device_event(
|
||||||
sender_user,
|
sender_user,
|
||||||
@@ -67,7 +95,7 @@ pub async fn send_event_to_device_route(
|
|||||||
db.transaction_ids
|
db.transaction_ids
|
||||||
.add_txnid(sender_user, sender_device, &body.txn_id, &[])?;
|
.add_txnid(sender_user, sender_device, &body.txn_id, &[])?;
|
||||||
|
|
||||||
db.flush().await?;
|
db.flush()?;
|
||||||
|
|
||||||
Ok(send_event_to_device::Response.into())
|
Ok(send_event_to_device::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,5 +29,5 @@ pub fn create_typing_event_route(
|
|||||||
.typing_remove(&sender_user, &body.room_id, &db.globals)?;
|
.typing_remove(&sender_user, &body.room_id, &db.globals)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(create_typing_event::Response.into())
|
Ok(create_typing_event::Response {}.into())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,20 +25,22 @@ pub async fn search_users_route(
|
|||||||
avatar_url: db.users.avatar_url(&user_id).ok()?,
|
avatar_url: db.users.avatar_url(&user_id).ok()?,
|
||||||
};
|
};
|
||||||
|
|
||||||
if !user
|
let user_id_matches = user
|
||||||
.user_id
|
.user_id
|
||||||
.to_string()
|
.to_string()
|
||||||
.to_lowercase()
|
.to_lowercase()
|
||||||
.contains(&body.search_term.to_lowercase())
|
.contains(&body.search_term.to_lowercase());
|
||||||
&& user
|
|
||||||
.display_name
|
let user_displayname_matches = user
|
||||||
.as_ref()
|
.display_name
|
||||||
.filter(|name| {
|
.as_ref()
|
||||||
name.to_lowercase()
|
.filter(|name| {
|
||||||
.contains(&body.search_term.to_lowercase())
|
name.to_lowercase()
|
||||||
})
|
.contains(&body.search_term.to_lowercase())
|
||||||
.is_none()
|
})
|
||||||
{
|
.is_some();
|
||||||
|
|
||||||
|
if !user_id_matches && !user_displayname_matches {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+156
-84
@@ -17,24 +17,26 @@ pub mod users;
|
|||||||
use crate::{utils, Error, Result};
|
use crate::{utils, Error, Result};
|
||||||
use abstraction::DatabaseEngine;
|
use abstraction::DatabaseEngine;
|
||||||
use directories::ProjectDirs;
|
use directories::ProjectDirs;
|
||||||
use log::error;
|
|
||||||
use lru_cache::LruCache;
|
use lru_cache::LruCache;
|
||||||
use rocket::{
|
use rocket::{
|
||||||
futures::{channel::mpsc, stream::FuturesUnordered, StreamExt},
|
futures::{channel::mpsc, stream::FuturesUnordered, StreamExt},
|
||||||
outcome::IntoOutcome,
|
outcome::{try_outcome, IntoOutcome},
|
||||||
request::{FromRequest, Request},
|
request::{FromRequest, Request},
|
||||||
try_outcome, State,
|
Shutdown, State,
|
||||||
};
|
};
|
||||||
use ruma::{DeviceId, ServerName, UserId};
|
use ruma::{DeviceId, RoomId, ServerName, UserId};
|
||||||
use serde::{de::IgnoredAny, Deserialize};
|
use serde::{de::IgnoredAny, Deserialize};
|
||||||
use std::{
|
use std::{
|
||||||
collections::{BTreeMap, HashMap},
|
collections::{BTreeMap, HashMap},
|
||||||
|
convert::TryFrom,
|
||||||
fs::{self, remove_dir_all},
|
fs::{self, remove_dir_all},
|
||||||
io::Write,
|
io::Write,
|
||||||
ops::Deref,
|
ops::Deref,
|
||||||
sync::{Arc, RwLock},
|
path::Path,
|
||||||
|
sync::{Arc, Mutex, RwLock},
|
||||||
};
|
};
|
||||||
use tokio::sync::{OwnedRwLockReadGuard, RwLock as TokioRwLock, Semaphore};
|
use tokio::sync::{OwnedRwLockReadGuard, RwLock as TokioRwLock, Semaphore};
|
||||||
|
use tracing::{debug, error, warn};
|
||||||
|
|
||||||
use self::proxy::ProxyConfig;
|
use self::proxy::ProxyConfig;
|
||||||
|
|
||||||
@@ -42,16 +44,10 @@ use self::proxy::ProxyConfig;
|
|||||||
pub struct Config {
|
pub struct Config {
|
||||||
server_name: Box<ServerName>,
|
server_name: Box<ServerName>,
|
||||||
database_path: String,
|
database_path: String,
|
||||||
#[serde(default = "default_db_cache_capacity")]
|
#[serde(default = "default_db_cache_capacity_mb")]
|
||||||
db_cache_capacity: u32,
|
db_cache_capacity_mb: f64,
|
||||||
#[serde(default = "default_sqlite_read_pool_size")]
|
|
||||||
sqlite_read_pool_size: usize,
|
|
||||||
#[serde(default = "false_fn")]
|
|
||||||
sqlite_wal_clean_timer: bool,
|
|
||||||
#[serde(default = "default_sqlite_wal_clean_second_interval")]
|
#[serde(default = "default_sqlite_wal_clean_second_interval")]
|
||||||
sqlite_wal_clean_second_interval: u32,
|
sqlite_wal_clean_second_interval: u32,
|
||||||
#[serde(default = "default_sqlite_wal_clean_second_timeout")]
|
|
||||||
sqlite_wal_clean_second_timeout: u32,
|
|
||||||
#[serde(default = "default_max_request_size")]
|
#[serde(default = "default_max_request_size")]
|
||||||
max_request_size: u32,
|
max_request_size: u32,
|
||||||
#[serde(default = "default_max_concurrent_requests")]
|
#[serde(default = "default_max_concurrent_requests")]
|
||||||
@@ -64,6 +60,8 @@ pub struct Config {
|
|||||||
allow_federation: bool,
|
allow_federation: bool,
|
||||||
#[serde(default = "false_fn")]
|
#[serde(default = "false_fn")]
|
||||||
pub allow_jaeger: bool,
|
pub allow_jaeger: bool,
|
||||||
|
#[serde(default = "false_fn")]
|
||||||
|
pub tracing_flame: bool,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
proxy: ProxyConfig,
|
proxy: ProxyConfig,
|
||||||
jwt_secret: Option<String>,
|
jwt_secret: Option<String>,
|
||||||
@@ -86,12 +84,12 @@ impl Config {
|
|||||||
.keys()
|
.keys()
|
||||||
.filter(|key| DEPRECATED_KEYS.iter().any(|s| s == key))
|
.filter(|key| DEPRECATED_KEYS.iter().any(|s| s == key))
|
||||||
{
|
{
|
||||||
log::warn!("Config parameter {} is deprecated", key);
|
warn!("Config parameter {} is deprecated", key);
|
||||||
was_deprecated = true;
|
was_deprecated = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if was_deprecated {
|
if was_deprecated {
|
||||||
log::warn!("Read conduit documentation and check your configuration if any new configuration parameters should be adjusted");
|
warn!("Read conduit documentation and check your configuration if any new configuration parameters should be adjusted");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -104,20 +102,12 @@ fn true_fn() -> bool {
|
|||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_db_cache_capacity() -> u32 {
|
fn default_db_cache_capacity_mb() -> f64 {
|
||||||
1024 * 1024 * 1024
|
200.0
|
||||||
}
|
|
||||||
|
|
||||||
fn default_sqlite_read_pool_size() -> usize {
|
|
||||||
num_cpus::get().max(1)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_sqlite_wal_clean_second_interval() -> u32 {
|
fn default_sqlite_wal_clean_second_interval() -> u32 {
|
||||||
60
|
15 * 60 // every 15 minutes
|
||||||
}
|
|
||||||
|
|
||||||
fn default_sqlite_wal_clean_second_timeout() -> u32 {
|
|
||||||
2
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_max_request_size() -> u32 {
|
fn default_max_request_size() -> u32 {
|
||||||
@@ -135,12 +125,12 @@ fn default_log() -> String {
|
|||||||
#[cfg(feature = "sled")]
|
#[cfg(feature = "sled")]
|
||||||
pub type Engine = abstraction::sled::Engine;
|
pub type Engine = abstraction::sled::Engine;
|
||||||
|
|
||||||
#[cfg(feature = "rocksdb")]
|
|
||||||
pub type Engine = abstraction::rocksdb::Engine;
|
|
||||||
|
|
||||||
#[cfg(feature = "sqlite")]
|
#[cfg(feature = "sqlite")]
|
||||||
pub type Engine = abstraction::sqlite::Engine;
|
pub type Engine = abstraction::sqlite::Engine;
|
||||||
|
|
||||||
|
#[cfg(feature = "heed")]
|
||||||
|
pub type Engine = abstraction::heed::Engine;
|
||||||
|
|
||||||
pub struct Database {
|
pub struct Database {
|
||||||
_db: Arc<Engine>,
|
_db: Arc<Engine>,
|
||||||
pub globals: globals::Globals,
|
pub globals: globals::Globals,
|
||||||
@@ -170,8 +160,37 @@ impl Database {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn check_sled_or_sqlite_db(config: &Config) -> Result<()> {
|
||||||
|
#[cfg(feature = "backend_sqlite")]
|
||||||
|
{
|
||||||
|
let path = Path::new(&config.database_path);
|
||||||
|
|
||||||
|
let sled_exists = path.join("db").exists();
|
||||||
|
let sqlite_exists = path.join("conduit.db").exists();
|
||||||
|
if sled_exists {
|
||||||
|
if sqlite_exists {
|
||||||
|
// most likely an in-place directory, only warn
|
||||||
|
warn!("Both sled and sqlite databases are detected in database directory");
|
||||||
|
warn!("Currently running from the sqlite database, but consider removing sled database files to free up space")
|
||||||
|
} else {
|
||||||
|
error!(
|
||||||
|
"Sled database detected, conduit now uses sqlite for database operations"
|
||||||
|
);
|
||||||
|
error!("This database must be converted to sqlite, go to https://github.com/ShadowJonathan/conduit_toolbox#conduit_sled_to_sqlite");
|
||||||
|
return Err(Error::bad_config(
|
||||||
|
"sled database detected, migrate to sqlite",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Load an existing database or create a new one.
|
/// Load an existing database or create a new one.
|
||||||
pub async fn load_or_create(config: Config) -> Result<Arc<TokioRwLock<Self>>> {
|
pub async fn load_or_create(config: &Config) -> Result<Arc<TokioRwLock<Self>>> {
|
||||||
|
Self::check_sled_or_sqlite_db(&config)?;
|
||||||
|
|
||||||
let builder = Engine::open(&config)?;
|
let builder = Engine::open(&config)?;
|
||||||
|
|
||||||
if config.max_request_size < 1024 {
|
if config.max_request_size < 1024 {
|
||||||
@@ -187,6 +206,7 @@ impl Database {
|
|||||||
userid_password: builder.open_tree("userid_password")?,
|
userid_password: builder.open_tree("userid_password")?,
|
||||||
userid_displayname: builder.open_tree("userid_displayname")?,
|
userid_displayname: builder.open_tree("userid_displayname")?,
|
||||||
userid_avatarurl: builder.open_tree("userid_avatarurl")?,
|
userid_avatarurl: builder.open_tree("userid_avatarurl")?,
|
||||||
|
userid_blurhash: builder.open_tree("userid_blurhash")?,
|
||||||
userdeviceid_token: builder.open_tree("userdeviceid_token")?,
|
userdeviceid_token: builder.open_tree("userdeviceid_token")?,
|
||||||
userdeviceid_metadata: builder.open_tree("userdeviceid_metadata")?,
|
userdeviceid_metadata: builder.open_tree("userdeviceid_metadata")?,
|
||||||
userid_devicelistversion: builder.open_tree("userid_devicelistversion")?,
|
userid_devicelistversion: builder.open_tree("userid_devicelistversion")?,
|
||||||
@@ -230,6 +250,7 @@ impl Database {
|
|||||||
serverroomids: builder.open_tree("serverroomids")?,
|
serverroomids: builder.open_tree("serverroomids")?,
|
||||||
userroomid_joined: builder.open_tree("userroomid_joined")?,
|
userroomid_joined: builder.open_tree("userroomid_joined")?,
|
||||||
roomuserid_joined: builder.open_tree("roomuserid_joined")?,
|
roomuserid_joined: builder.open_tree("roomuserid_joined")?,
|
||||||
|
roomid_joinedcount: builder.open_tree("roomid_joinedcount")?,
|
||||||
roomuseroncejoinedids: builder.open_tree("roomuseroncejoinedids")?,
|
roomuseroncejoinedids: builder.open_tree("roomuseroncejoinedids")?,
|
||||||
userroomid_invitestate: builder.open_tree("userroomid_invitestate")?,
|
userroomid_invitestate: builder.open_tree("userroomid_invitestate")?,
|
||||||
roomuserid_invitecount: builder.open_tree("roomuserid_invitecount")?,
|
roomuserid_invitecount: builder.open_tree("roomuserid_invitecount")?,
|
||||||
@@ -248,11 +269,14 @@ impl Database {
|
|||||||
statehash_shortstatehash: builder.open_tree("statehash_shortstatehash")?,
|
statehash_shortstatehash: builder.open_tree("statehash_shortstatehash")?,
|
||||||
|
|
||||||
eventid_outlierpdu: builder.open_tree("eventid_outlierpdu")?,
|
eventid_outlierpdu: builder.open_tree("eventid_outlierpdu")?,
|
||||||
prevevent_parent: builder.open_tree("prevevent_parent")?,
|
referencedevents: builder.open_tree("referencedevents")?,
|
||||||
pdu_cache: RwLock::new(LruCache::new(10_000)),
|
pdu_cache: Mutex::new(LruCache::new(100_000)),
|
||||||
|
auth_chain_cache: Mutex::new(LruCache::new(100_000)),
|
||||||
|
shorteventid_cache: Mutex::new(LruCache::new(1_000_000)),
|
||||||
},
|
},
|
||||||
account_data: account_data::AccountData {
|
account_data: account_data::AccountData {
|
||||||
roomuserdataid_accountdata: builder.open_tree("roomuserdataid_accountdata")?,
|
roomuserdataid_accountdata: builder.open_tree("roomuserdataid_accountdata")?,
|
||||||
|
roomusertype_roomuserdataid: builder.open_tree("roomusertype_roomuserdataid")?,
|
||||||
},
|
},
|
||||||
media: media::Media {
|
media: media::Media {
|
||||||
mediaid_file: builder.open_tree("mediaid_file")?,
|
mediaid_file: builder.open_tree("mediaid_file")?,
|
||||||
@@ -267,8 +291,8 @@ impl Database {
|
|||||||
},
|
},
|
||||||
sending: sending::Sending {
|
sending: sending::Sending {
|
||||||
servername_educount: builder.open_tree("servername_educount")?,
|
servername_educount: builder.open_tree("servername_educount")?,
|
||||||
servernamepduids: builder.open_tree("servernamepduids")?,
|
servernameevent_data: builder.open_tree("servernameevent_data")?,
|
||||||
servercurrentevents: builder.open_tree("servercurrentevents")?,
|
servercurrentevent_data: builder.open_tree("servercurrentevent_data")?,
|
||||||
maximum_requests: Arc::new(Semaphore::new(config.max_concurrent_requests as usize)),
|
maximum_requests: Arc::new(Semaphore::new(config.max_concurrent_requests as usize)),
|
||||||
sender: sending_sender,
|
sender: sending_sender,
|
||||||
},
|
},
|
||||||
@@ -338,7 +362,7 @@ impl Database {
|
|||||||
if db.globals.database_version()? < 3 {
|
if db.globals.database_version()? < 3 {
|
||||||
// Move media to filesystem
|
// Move media to filesystem
|
||||||
for (key, content) in db.media.mediaid_file.iter() {
|
for (key, content) in db.media.mediaid_file.iter() {
|
||||||
if content.len() == 0 {
|
if content.is_empty() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -375,6 +399,45 @@ impl Database {
|
|||||||
|
|
||||||
println!("Migration: 3 -> 4 finished");
|
println!("Migration: 3 -> 4 finished");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if db.globals.database_version()? < 5 {
|
||||||
|
// Upgrade user data store
|
||||||
|
for (roomuserdataid, _) in db.account_data.roomuserdataid_accountdata.iter() {
|
||||||
|
let mut parts = roomuserdataid.split(|&b| b == 0xff);
|
||||||
|
let room_id = parts.next().unwrap();
|
||||||
|
let user_id = parts.next().unwrap();
|
||||||
|
let event_type = roomuserdataid.rsplit(|&b| b == 0xff).next().unwrap();
|
||||||
|
|
||||||
|
let mut key = room_id.to_vec();
|
||||||
|
key.push(0xff);
|
||||||
|
key.extend_from_slice(user_id);
|
||||||
|
key.push(0xff);
|
||||||
|
key.extend_from_slice(event_type);
|
||||||
|
|
||||||
|
db.account_data
|
||||||
|
.roomusertype_roomuserdataid
|
||||||
|
.insert(&key, &roomuserdataid)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
db.globals.bump_database_version(5)?;
|
||||||
|
|
||||||
|
println!("Migration: 4 -> 5 finished");
|
||||||
|
}
|
||||||
|
|
||||||
|
if db.globals.database_version()? < 6 {
|
||||||
|
// TODO update to 6
|
||||||
|
// Set room member count
|
||||||
|
for (roomid, _) in db.rooms.roomid_shortstatehash.iter() {
|
||||||
|
let room_id =
|
||||||
|
RoomId::try_from(utils::string_from_bytes(&roomid).unwrap()).unwrap();
|
||||||
|
|
||||||
|
db.rooms.update_joined_count(&room_id)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
db.globals.bump_database_version(6)?;
|
||||||
|
|
||||||
|
println!("Migration: 5 -> 6 finished");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let guard = db.read().await;
|
let guard = db.read().await;
|
||||||
@@ -390,11 +453,26 @@ impl Database {
|
|||||||
drop(guard);
|
drop(guard);
|
||||||
|
|
||||||
#[cfg(feature = "sqlite")]
|
#[cfg(feature = "sqlite")]
|
||||||
Self::start_wal_clean_task(&db, &config).await;
|
{
|
||||||
|
Self::start_wal_clean_task(Arc::clone(&db), &config).await;
|
||||||
|
}
|
||||||
|
|
||||||
Ok(db)
|
Ok(db)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "conduit_bin")]
|
||||||
|
pub async fn start_on_shutdown_tasks(db: Arc<TokioRwLock<Self>>, shutdown: Shutdown) {
|
||||||
|
use tracing::info;
|
||||||
|
|
||||||
|
tokio::spawn(async move {
|
||||||
|
shutdown.await;
|
||||||
|
|
||||||
|
info!(target: "shutdown-sync", "Received shutdown notification, notifying sync helpers...");
|
||||||
|
|
||||||
|
db.read().await.globals.rotate.fire();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn watch(&self, user_id: &UserId, device_id: &DeviceId) {
|
pub async fn watch(&self, user_id: &UserId, device_id: &DeviceId) {
|
||||||
let userid_bytes = user_id.as_bytes().to_vec();
|
let userid_bytes = user_id.as_bytes().to_vec();
|
||||||
let mut userid_prefix = userid_bytes.clone();
|
let mut userid_prefix = userid_bytes.clone();
|
||||||
@@ -421,6 +499,16 @@ impl Database {
|
|||||||
.watch_prefix(&userid_prefix),
|
.watch_prefix(&userid_prefix),
|
||||||
);
|
);
|
||||||
futures.push(self.rooms.userroomid_leftstate.watch_prefix(&userid_prefix));
|
futures.push(self.rooms.userroomid_leftstate.watch_prefix(&userid_prefix));
|
||||||
|
futures.push(
|
||||||
|
self.rooms
|
||||||
|
.userroomid_notificationcount
|
||||||
|
.watch_prefix(&userid_prefix),
|
||||||
|
);
|
||||||
|
futures.push(
|
||||||
|
self.rooms
|
||||||
|
.userroomid_highlightcount
|
||||||
|
.watch_prefix(&userid_prefix),
|
||||||
|
);
|
||||||
|
|
||||||
// Events for rooms we are in
|
// Events for rooms we are in
|
||||||
for room_id in self.rooms.rooms_joined(user_id).filter_map(|r| r.ok()) {
|
for room_id in self.rooms.rooms_joined(user_id).filter_map(|r| r.ok()) {
|
||||||
@@ -455,7 +543,7 @@ impl Database {
|
|||||||
|
|
||||||
futures.push(
|
futures.push(
|
||||||
self.account_data
|
self.account_data
|
||||||
.roomuserdataid_accountdata
|
.roomusertype_roomuserdataid
|
||||||
.watch_prefix(&roomuser_prefix),
|
.watch_prefix(&roomuser_prefix),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -465,7 +553,7 @@ impl Database {
|
|||||||
|
|
||||||
futures.push(
|
futures.push(
|
||||||
self.account_data
|
self.account_data
|
||||||
.roomuserdataid_accountdata
|
.roomusertype_roomuserdataid
|
||||||
.watch_prefix(&globaluserdata_prefix),
|
.watch_prefix(&globaluserdata_prefix),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -485,78 +573,62 @@ impl Database {
|
|||||||
futures.next().await;
|
futures.next().await;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn flush(&self) -> Result<()> {
|
#[tracing::instrument(skip(self))]
|
||||||
|
pub fn flush(&self) -> Result<()> {
|
||||||
let start = std::time::Instant::now();
|
let start = std::time::Instant::now();
|
||||||
|
|
||||||
let res = self._db.flush();
|
let res = self._db.flush();
|
||||||
|
|
||||||
log::debug!("flush: took {:?}", start.elapsed());
|
debug!("flush: took {:?}", start.elapsed());
|
||||||
|
|
||||||
res
|
res
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "sqlite")]
|
#[cfg(feature = "sqlite")]
|
||||||
|
#[tracing::instrument(skip(self))]
|
||||||
pub fn flush_wal(&self) -> Result<()> {
|
pub fn flush_wal(&self) -> Result<()> {
|
||||||
self._db.flush_wal()
|
self._db.flush_wal()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "sqlite")]
|
#[cfg(feature = "sqlite")]
|
||||||
pub async fn start_wal_clean_task(lock: &Arc<TokioRwLock<Self>>, config: &Config) {
|
#[tracing::instrument(skip(db, config))]
|
||||||
use tokio::{
|
pub async fn start_wal_clean_task(db: Arc<TokioRwLock<Self>>, config: &Config) {
|
||||||
select,
|
use tokio::time::interval;
|
||||||
signal::unix::{signal, SignalKind},
|
|
||||||
time::{interval, timeout},
|
|
||||||
};
|
|
||||||
|
|
||||||
use std::{
|
#[cfg(unix)]
|
||||||
sync::Weak,
|
use tokio::signal::unix::{signal, SignalKind};
|
||||||
time::{Duration, Instant},
|
use tracing::info;
|
||||||
};
|
|
||||||
|
|
||||||
let weak: Weak<TokioRwLock<Database>> = Arc::downgrade(&lock);
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
let lock_timeout = Duration::from_secs(config.sqlite_wal_clean_second_timeout as u64);
|
|
||||||
let timer_interval = Duration::from_secs(config.sqlite_wal_clean_second_interval as u64);
|
let timer_interval = Duration::from_secs(config.sqlite_wal_clean_second_interval as u64);
|
||||||
let do_timer = config.sqlite_wal_clean_timer;
|
|
||||||
|
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let mut i = interval(timer_interval);
|
let mut i = interval(timer_interval);
|
||||||
|
#[cfg(unix)]
|
||||||
let mut s = signal(SignalKind::hangup()).unwrap();
|
let mut s = signal(SignalKind::hangup()).unwrap();
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
select! {
|
#[cfg(unix)]
|
||||||
_ = i.tick(), if do_timer => {
|
tokio::select! {
|
||||||
log::info!(target: "wal-trunc", "Timer ticked")
|
_ = i.tick() => {
|
||||||
|
info!("wal-trunc: Timer ticked");
|
||||||
}
|
}
|
||||||
_ = s.recv() => {
|
_ = s.recv() => {
|
||||||
log::info!(target: "wal-trunc", "Received SIGHUP")
|
info!("wal-trunc: Received SIGHUP");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
{
|
||||||
|
i.tick().await;
|
||||||
|
info!("wal-trunc: Timer ticked")
|
||||||
|
}
|
||||||
|
|
||||||
if let Some(arc) = Weak::upgrade(&weak) {
|
let start = Instant::now();
|
||||||
log::info!(target: "wal-trunc", "Rotating sync helpers...");
|
if let Err(e) = db.read().await.flush_wal() {
|
||||||
// This actually creates a very small race condition between firing this and trying to acquire the subsequent write lock.
|
error!("wal-trunc: Errored: {}", e);
|
||||||
// Though it is not a huge deal if the write lock doesn't "catch", as it'll harmlessly time out.
|
|
||||||
arc.read().await.globals.rotate.fire();
|
|
||||||
|
|
||||||
log::info!(target: "wal-trunc", "Locking...");
|
|
||||||
let guard = {
|
|
||||||
if let Ok(guard) = timeout(lock_timeout, arc.write()).await {
|
|
||||||
guard
|
|
||||||
} else {
|
|
||||||
log::info!(target: "wal-trunc", "Lock failed in timeout, canceled.");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
log::info!(target: "wal-trunc", "Locked, flushing...");
|
|
||||||
let start = Instant::now();
|
|
||||||
if let Err(e) = guard.flush_wal() {
|
|
||||||
log::error!(target: "wal-trunc", "Errored: {}", e);
|
|
||||||
} else {
|
|
||||||
log::info!(target: "wal-trunc", "Flushed in {:?}", start.elapsed());
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
break;
|
info!("wal-trunc: Flushed in {:?}", start.elapsed());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -578,14 +650,14 @@ impl<'r> FromRequest<'r> for DatabaseGuard {
|
|||||||
type Error = ();
|
type Error = ();
|
||||||
|
|
||||||
async fn from_request(req: &'r Request<'_>) -> rocket::request::Outcome<Self, ()> {
|
async fn from_request(req: &'r Request<'_>) -> rocket::request::Outcome<Self, ()> {
|
||||||
let db = try_outcome!(req.guard::<State<'_, Arc<TokioRwLock<Database>>>>().await);
|
let db = try_outcome!(req.guard::<&State<Arc<TokioRwLock<Database>>>>().await);
|
||||||
|
|
||||||
Ok(DatabaseGuard(Arc::clone(&db).read_owned().await)).or_forward(())
|
Ok(DatabaseGuard(Arc::clone(&db).read_owned().await)).or_forward(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Into<DatabaseGuard> for OwnedRwLockReadGuard<Database> {
|
impl From<OwnedRwLockReadGuard<Database>> for DatabaseGuard {
|
||||||
fn into(self) -> DatabaseGuard {
|
fn from(val: OwnedRwLockReadGuard<Database>) -> Self {
|
||||||
DatabaseGuard(self)
|
Self(val)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,15 +3,15 @@ use crate::Result;
|
|||||||
|
|
||||||
use std::{future::Future, pin::Pin, sync::Arc};
|
use std::{future::Future, pin::Pin, sync::Arc};
|
||||||
|
|
||||||
#[cfg(feature = "rocksdb")]
|
|
||||||
pub mod rocksdb;
|
|
||||||
|
|
||||||
#[cfg(feature = "sled")]
|
#[cfg(feature = "sled")]
|
||||||
pub mod sled;
|
pub mod sled;
|
||||||
|
|
||||||
#[cfg(feature = "sqlite")]
|
#[cfg(feature = "sqlite")]
|
||||||
pub mod sqlite;
|
pub mod sqlite;
|
||||||
|
|
||||||
|
#[cfg(feature = "heed")]
|
||||||
|
pub mod heed;
|
||||||
|
|
||||||
pub trait DatabaseEngine: Sized {
|
pub trait DatabaseEngine: Sized {
|
||||||
fn open(config: &Config) -> Result<Arc<Self>>;
|
fn open(config: &Config) -> Result<Arc<Self>>;
|
||||||
fn open_tree(self: &Arc<Self>, name: &'static str) -> Result<Arc<dyn Tree>>;
|
fn open_tree(self: &Arc<Self>, name: &'static str) -> Result<Arc<dyn Tree>>;
|
||||||
@@ -22,23 +22,24 @@ pub trait Tree: Send + Sync {
|
|||||||
fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>>;
|
fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>>;
|
||||||
|
|
||||||
fn insert(&self, key: &[u8], value: &[u8]) -> Result<()>;
|
fn insert(&self, key: &[u8], value: &[u8]) -> Result<()>;
|
||||||
|
fn insert_batch<'a>(&self, iter: &mut dyn Iterator<Item = (Vec<u8>, Vec<u8>)>) -> Result<()>;
|
||||||
|
|
||||||
fn remove(&self, key: &[u8]) -> Result<()>;
|
fn remove(&self, key: &[u8]) -> Result<()>;
|
||||||
|
|
||||||
fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + Send + 'a>;
|
fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a>;
|
||||||
|
|
||||||
fn iter_from<'a>(
|
fn iter_from<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
from: &[u8],
|
from: &[u8],
|
||||||
backwards: bool,
|
backwards: bool,
|
||||||
) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + Send + 'a>;
|
) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a>;
|
||||||
|
|
||||||
fn increment(&self, key: &[u8]) -> Result<Vec<u8>>;
|
fn increment(&self, key: &[u8]) -> Result<Vec<u8>>;
|
||||||
|
|
||||||
fn scan_prefix<'a>(
|
fn scan_prefix<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
prefix: Vec<u8>,
|
prefix: Vec<u8>,
|
||||||
) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + Send + 'a>;
|
) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a>;
|
||||||
|
|
||||||
fn watch_prefix<'a>(&'a self, prefix: &[u8]) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
|
fn watch_prefix<'a>(&'a self, prefix: &[u8]) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,240 @@
|
|||||||
|
use super::super::Config;
|
||||||
|
use crossbeam::channel::{bounded, Sender as ChannelSender};
|
||||||
|
use threadpool::ThreadPool;
|
||||||
|
|
||||||
|
use crate::{Error, Result};
|
||||||
|
use std::{
|
||||||
|
collections::HashMap,
|
||||||
|
future::Future,
|
||||||
|
pin::Pin,
|
||||||
|
sync::{Arc, Mutex, RwLock},
|
||||||
|
};
|
||||||
|
use tokio::sync::oneshot::Sender;
|
||||||
|
|
||||||
|
use super::{DatabaseEngine, Tree};
|
||||||
|
|
||||||
|
type TupleOfBytes = (Vec<u8>, Vec<u8>);
|
||||||
|
|
||||||
|
pub struct Engine {
|
||||||
|
env: heed::Env,
|
||||||
|
iter_pool: Mutex<ThreadPool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct EngineTree {
|
||||||
|
engine: Arc<Engine>,
|
||||||
|
tree: Arc<heed::UntypedDatabase>,
|
||||||
|
watchers: RwLock<HashMap<Vec<u8>, Vec<Sender<()>>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn convert_error(error: heed::Error) -> Error {
|
||||||
|
Error::HeedError {
|
||||||
|
error: error.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DatabaseEngine for Engine {
|
||||||
|
fn open(config: &Config) -> Result<Arc<Self>> {
|
||||||
|
let mut env_builder = heed::EnvOpenOptions::new();
|
||||||
|
env_builder.map_size(1024 * 1024 * 1024 * 1024); // 1 Terabyte
|
||||||
|
env_builder.max_readers(126);
|
||||||
|
env_builder.max_dbs(128);
|
||||||
|
unsafe {
|
||||||
|
env_builder.flag(heed::flags::Flags::MdbWriteMap);
|
||||||
|
env_builder.flag(heed::flags::Flags::MdbMapAsync);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Arc::new(Engine {
|
||||||
|
env: env_builder
|
||||||
|
.open(&config.database_path)
|
||||||
|
.map_err(convert_error)?,
|
||||||
|
iter_pool: Mutex::new(ThreadPool::new(10)),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn open_tree(self: &Arc<Self>, name: &'static str) -> Result<Arc<dyn Tree>> {
|
||||||
|
// Creates the db if it doesn't exist already
|
||||||
|
Ok(Arc::new(EngineTree {
|
||||||
|
engine: Arc::clone(self),
|
||||||
|
tree: Arc::new(
|
||||||
|
self.env
|
||||||
|
.create_database(Some(name))
|
||||||
|
.map_err(convert_error)?,
|
||||||
|
),
|
||||||
|
watchers: RwLock::new(HashMap::new()),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flush(self: &Arc<Self>) -> Result<()> {
|
||||||
|
self.env.force_sync().map_err(convert_error)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EngineTree {
|
||||||
|
#[tracing::instrument(skip(self, tree, from, backwards))]
|
||||||
|
fn iter_from_thread(
|
||||||
|
&self,
|
||||||
|
tree: Arc<heed::UntypedDatabase>,
|
||||||
|
from: Vec<u8>,
|
||||||
|
backwards: bool,
|
||||||
|
) -> Box<dyn Iterator<Item = TupleOfBytes> + Send + Sync> {
|
||||||
|
let (s, r) = bounded::<TupleOfBytes>(100);
|
||||||
|
let engine = Arc::clone(&self.engine);
|
||||||
|
|
||||||
|
let lock = self.engine.iter_pool.lock().await;
|
||||||
|
if lock.active_count() < lock.max_count() {
|
||||||
|
lock.execute(move || {
|
||||||
|
iter_from_thread_work(tree, &engine.env.read_txn().unwrap(), from, backwards, &s);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
iter_from_thread_work(tree, &engine.env.read_txn().unwrap(), from, backwards, &s);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Box::new(r.into_iter())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(tree, txn, from, backwards))]
|
||||||
|
fn iter_from_thread_work(
|
||||||
|
tree: Arc<heed::UntypedDatabase>,
|
||||||
|
txn: &heed::RoTxn<'_>,
|
||||||
|
from: Vec<u8>,
|
||||||
|
backwards: bool,
|
||||||
|
s: &ChannelSender<(Vec<u8>, Vec<u8>)>,
|
||||||
|
) {
|
||||||
|
if backwards {
|
||||||
|
for (k, v) in tree.rev_range(txn, ..=&*from).unwrap().map(|r| r.unwrap()) {
|
||||||
|
if s.send((k.to_vec(), v.to_vec())).is_err() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if from.is_empty() {
|
||||||
|
for (k, v) in tree.iter(txn).unwrap().map(|r| r.unwrap()) {
|
||||||
|
if s.send((k.to_vec(), v.to_vec())).is_err() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (k, v) in tree.range(txn, &*from..).unwrap().map(|r| r.unwrap()) {
|
||||||
|
if s.send((k.to_vec(), v.to_vec())).is_err() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Tree for EngineTree {
|
||||||
|
#[tracing::instrument(skip(self, key))]
|
||||||
|
fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>> {
|
||||||
|
let txn = self.engine.env.read_txn().map_err(convert_error)?;
|
||||||
|
Ok(self
|
||||||
|
.tree
|
||||||
|
.get(&txn, &key)
|
||||||
|
.map_err(convert_error)?
|
||||||
|
.map(|s| s.to_vec()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, key, value))]
|
||||||
|
fn insert(&self, key: &[u8], value: &[u8]) -> Result<()> {
|
||||||
|
let mut txn = self.engine.env.write_txn().map_err(convert_error)?;
|
||||||
|
self.tree
|
||||||
|
.put(&mut txn, &key, &value)
|
||||||
|
.map_err(convert_error)?;
|
||||||
|
txn.commit().map_err(convert_error)?;
|
||||||
|
|
||||||
|
let watchers = self.watchers.read().unwrap();
|
||||||
|
let mut triggered = Vec::new();
|
||||||
|
|
||||||
|
for length in 0..=key.len() {
|
||||||
|
if watchers.contains_key(&key[..length]) {
|
||||||
|
triggered.push(&key[..length]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
drop(watchers);
|
||||||
|
|
||||||
|
if !triggered.is_empty() {
|
||||||
|
let mut watchers = self.watchers.write().unwrap();
|
||||||
|
for prefix in triggered {
|
||||||
|
if let Some(txs) = watchers.remove(prefix) {
|
||||||
|
for tx in txs {
|
||||||
|
let _ = tx.send(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, key))]
|
||||||
|
fn remove(&self, key: &[u8]) -> Result<()> {
|
||||||
|
let mut txn = self.engine.env.write_txn().map_err(convert_error)?;
|
||||||
|
self.tree.delete(&mut txn, &key).map_err(convert_error)?;
|
||||||
|
txn.commit().map_err(convert_error)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self))]
|
||||||
|
fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + Send + 'a> {
|
||||||
|
self.iter_from(&[], false)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, from, backwards))]
|
||||||
|
fn iter_from(
|
||||||
|
&self,
|
||||||
|
from: &[u8],
|
||||||
|
backwards: bool,
|
||||||
|
) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + Send> {
|
||||||
|
self.iter_from_thread(Arc::clone(&self.tree), from.to_vec(), backwards)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, key))]
|
||||||
|
fn increment(&self, key: &[u8]) -> Result<Vec<u8>> {
|
||||||
|
let mut txn = self.engine.env.write_txn().map_err(convert_error)?;
|
||||||
|
|
||||||
|
let old = self.tree.get(&txn, &key).map_err(convert_error)?;
|
||||||
|
let new =
|
||||||
|
crate::utils::increment(old.as_deref()).expect("utils::increment always returns Some");
|
||||||
|
|
||||||
|
self.tree
|
||||||
|
.put(&mut txn, &key, &&*new)
|
||||||
|
.map_err(convert_error)?;
|
||||||
|
|
||||||
|
txn.commit().map_err(convert_error)?;
|
||||||
|
|
||||||
|
Ok(new)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, prefix))]
|
||||||
|
fn scan_prefix<'a>(
|
||||||
|
&'a self,
|
||||||
|
prefix: Vec<u8>,
|
||||||
|
) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + Send + 'a> {
|
||||||
|
Box::new(
|
||||||
|
self.iter_from(&prefix, false)
|
||||||
|
.take_while(move |(key, _)| key.starts_with(&prefix)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, prefix))]
|
||||||
|
fn watch_prefix<'a>(&'a self, prefix: &[u8]) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
|
||||||
|
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||||
|
|
||||||
|
self.watchers
|
||||||
|
.write()
|
||||||
|
.unwrap()
|
||||||
|
.entry(prefix.to_vec())
|
||||||
|
.or_default()
|
||||||
|
.push(tx);
|
||||||
|
|
||||||
|
Box::pin(async move {
|
||||||
|
// Tx is never destroyed
|
||||||
|
rx.await.unwrap();
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,176 +0,0 @@
|
|||||||
use super::super::Config;
|
|
||||||
use crate::{utils, Result};
|
|
||||||
|
|
||||||
use std::{future::Future, pin::Pin, sync::Arc};
|
|
||||||
|
|
||||||
use super::{DatabaseEngine, Tree};
|
|
||||||
|
|
||||||
use std::{collections::BTreeMap, sync::RwLock};
|
|
||||||
|
|
||||||
pub struct Engine(rocksdb::DBWithThreadMode<rocksdb::MultiThreaded>);
|
|
||||||
|
|
||||||
pub struct RocksDbEngineTree<'a> {
|
|
||||||
db: Arc<Engine>,
|
|
||||||
name: &'a str,
|
|
||||||
watchers: RwLock<BTreeMap<Vec<u8>, Vec<tokio::sync::oneshot::Sender<()>>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DatabaseEngine for Engine {
|
|
||||||
fn open(config: &Config) -> Result<Arc<Self>> {
|
|
||||||
let mut db_opts = rocksdb::Options::default();
|
|
||||||
db_opts.create_if_missing(true);
|
|
||||||
db_opts.set_max_open_files(16);
|
|
||||||
db_opts.set_compaction_style(rocksdb::DBCompactionStyle::Level);
|
|
||||||
db_opts.set_compression_type(rocksdb::DBCompressionType::Snappy);
|
|
||||||
db_opts.set_target_file_size_base(256 << 20);
|
|
||||||
db_opts.set_write_buffer_size(256 << 20);
|
|
||||||
|
|
||||||
let mut block_based_options = rocksdb::BlockBasedOptions::default();
|
|
||||||
block_based_options.set_block_size(512 << 10);
|
|
||||||
db_opts.set_block_based_table_factory(&block_based_options);
|
|
||||||
|
|
||||||
let cfs = rocksdb::DBWithThreadMode::<rocksdb::MultiThreaded>::list_cf(
|
|
||||||
&db_opts,
|
|
||||||
&config.database_path,
|
|
||||||
)
|
|
||||||
.unwrap_or_default();
|
|
||||||
|
|
||||||
let mut options = rocksdb::Options::default();
|
|
||||||
options.set_merge_operator_associative("increment", utils::increment_rocksdb);
|
|
||||||
|
|
||||||
let db = rocksdb::DBWithThreadMode::<rocksdb::MultiThreaded>::open_cf_descriptors(
|
|
||||||
&db_opts,
|
|
||||||
&config.database_path,
|
|
||||||
cfs.iter()
|
|
||||||
.map(|name| rocksdb::ColumnFamilyDescriptor::new(name, options.clone())),
|
|
||||||
)?;
|
|
||||||
|
|
||||||
Ok(Arc::new(Engine(db)))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn open_tree(self: &Arc<Self>, name: &'static str) -> Result<Arc<dyn Tree>> {
|
|
||||||
let mut options = rocksdb::Options::default();
|
|
||||||
options.set_merge_operator_associative("increment", utils::increment_rocksdb);
|
|
||||||
|
|
||||||
// Create if it doesn't exist
|
|
||||||
let _ = self.0.create_cf(name, &options);
|
|
||||||
|
|
||||||
Ok(Arc::new(RocksDbEngineTree {
|
|
||||||
name,
|
|
||||||
db: Arc::clone(self),
|
|
||||||
watchers: RwLock::new(BTreeMap::new()),
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RocksDbEngineTree<'_> {
|
|
||||||
fn cf(&self) -> rocksdb::BoundColumnFamily<'_> {
|
|
||||||
self.db.0.cf_handle(self.name).unwrap()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Tree for RocksDbEngineTree<'_> {
|
|
||||||
fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>> {
|
|
||||||
Ok(self.db.0.get_cf(self.cf(), key)?)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn insert(&self, key: &[u8], value: &[u8]) -> Result<()> {
|
|
||||||
let watchers = self.watchers.read().unwrap();
|
|
||||||
let mut triggered = Vec::new();
|
|
||||||
|
|
||||||
for length in 0..=key.len() {
|
|
||||||
if watchers.contains_key(&key[..length]) {
|
|
||||||
triggered.push(&key[..length]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
drop(watchers);
|
|
||||||
|
|
||||||
if !triggered.is_empty() {
|
|
||||||
let mut watchers = self.watchers.write().unwrap();
|
|
||||||
for prefix in triggered {
|
|
||||||
if let Some(txs) = watchers.remove(prefix) {
|
|
||||||
for tx in txs {
|
|
||||||
let _ = tx.send(());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(self.db.0.put_cf(self.cf(), key, value)?)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn remove(&self, key: &[u8]) -> Result<()> {
|
|
||||||
Ok(self.db.0.delete_cf(self.cf(), key)?)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + Send + Sync + 'a> {
|
|
||||||
Box::new(
|
|
||||||
self.db
|
|
||||||
.0
|
|
||||||
.iterator_cf(self.cf(), rocksdb::IteratorMode::Start),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn iter_from<'a>(
|
|
||||||
&'a self,
|
|
||||||
from: &[u8],
|
|
||||||
backwards: bool,
|
|
||||||
) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a> {
|
|
||||||
Box::new(self.db.0.iterator_cf(
|
|
||||||
self.cf(),
|
|
||||||
rocksdb::IteratorMode::From(
|
|
||||||
from,
|
|
||||||
if backwards {
|
|
||||||
rocksdb::Direction::Reverse
|
|
||||||
} else {
|
|
||||||
rocksdb::Direction::Forward
|
|
||||||
},
|
|
||||||
),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn increment(&self, key: &[u8]) -> Result<Vec<u8>> {
|
|
||||||
let stats = rocksdb::perf::get_memory_usage_stats(Some(&[&self.db.0]), None).unwrap();
|
|
||||||
dbg!(stats.mem_table_total);
|
|
||||||
dbg!(stats.mem_table_unflushed);
|
|
||||||
dbg!(stats.mem_table_readers_total);
|
|
||||||
dbg!(stats.cache_total);
|
|
||||||
// TODO: atomic?
|
|
||||||
let old = self.get(key)?;
|
|
||||||
let new = utils::increment(old.as_deref()).unwrap();
|
|
||||||
self.insert(key, &new)?;
|
|
||||||
Ok(new)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn scan_prefix<'a>(
|
|
||||||
&'a self,
|
|
||||||
prefix: Vec<u8>,
|
|
||||||
) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + Send + 'a> {
|
|
||||||
Box::new(
|
|
||||||
self.db
|
|
||||||
.0
|
|
||||||
.iterator_cf(
|
|
||||||
self.cf(),
|
|
||||||
rocksdb::IteratorMode::From(&prefix, rocksdb::Direction::Forward),
|
|
||||||
)
|
|
||||||
.take_while(move |(k, _)| k.starts_with(&prefix)),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn watch_prefix<'a>(&'a self, prefix: &[u8]) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
|
|
||||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
|
||||||
|
|
||||||
self.watchers
|
|
||||||
.write()
|
|
||||||
.unwrap()
|
|
||||||
.entry(prefix.to_vec())
|
|
||||||
.or_default()
|
|
||||||
.push(tx);
|
|
||||||
|
|
||||||
Box::pin(async move {
|
|
||||||
// Tx is never destroyed
|
|
||||||
rx.await.unwrap();
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
use super::super::Config;
|
use super::super::Config;
|
||||||
use crate::{utils, Result};
|
use crate::{utils, Result};
|
||||||
use log::warn;
|
|
||||||
use std::{future::Future, pin::Pin, sync::Arc};
|
use std::{future::Future, pin::Pin, sync::Arc};
|
||||||
|
use tracing::warn;
|
||||||
|
|
||||||
use super::{DatabaseEngine, Tree};
|
use super::{DatabaseEngine, Tree};
|
||||||
|
|
||||||
@@ -14,7 +14,7 @@ impl DatabaseEngine for Engine {
|
|||||||
Ok(Arc::new(Engine(
|
Ok(Arc::new(Engine(
|
||||||
sled::Config::default()
|
sled::Config::default()
|
||||||
.path(&config.database_path)
|
.path(&config.database_path)
|
||||||
.cache_capacity(config.db_cache_capacity as u64)
|
.cache_capacity((config.db_cache_capacity_mb * 1024.0 * 1024.0) as u64)
|
||||||
.use_compression(true)
|
.use_compression(true)
|
||||||
.open()?,
|
.open()?,
|
||||||
)))
|
)))
|
||||||
@@ -39,12 +39,21 @@ impl Tree for SledEngineTree {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, iter))]
|
||||||
|
fn insert_batch<'a>(&self, iter: &mut dyn Iterator<Item = (Vec<u8>, Vec<u8>)>) -> Result<()> {
|
||||||
|
for (key, value) in iter {
|
||||||
|
self.0.insert(key, value)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
fn remove(&self, key: &[u8]) -> Result<()> {
|
fn remove(&self, key: &[u8]) -> Result<()> {
|
||||||
self.0.remove(key)?;
|
self.0.remove(key)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + Send + 'a> {
|
fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a> {
|
||||||
Box::new(
|
Box::new(
|
||||||
self.0
|
self.0
|
||||||
.iter()
|
.iter()
|
||||||
@@ -62,7 +71,7 @@ impl Tree for SledEngineTree {
|
|||||||
&self,
|
&self,
|
||||||
from: &[u8],
|
from: &[u8],
|
||||||
backwards: bool,
|
backwards: bool,
|
||||||
) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + Send> {
|
) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)>> {
|
||||||
let iter = if backwards {
|
let iter = if backwards {
|
||||||
self.0.range(..=from)
|
self.0.range(..=from)
|
||||||
} else {
|
} else {
|
||||||
@@ -95,7 +104,7 @@ impl Tree for SledEngineTree {
|
|||||||
fn scan_prefix<'a>(
|
fn scan_prefix<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
prefix: Vec<u8>,
|
prefix: Vec<u8>,
|
||||||
) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + Send + 'a> {
|
) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a> {
|
||||||
let iter = self
|
let iter = self
|
||||||
.0
|
.0
|
||||||
.scan_prefix(prefix)
|
.scan_prefix(prefix)
|
||||||
|
|||||||
+179
-265
@@ -1,94 +1,59 @@
|
|||||||
|
use super::{DatabaseEngine, Tree};
|
||||||
|
use crate::{database::Config, Result};
|
||||||
|
use parking_lot::{Mutex, MutexGuard, RwLock};
|
||||||
|
use rusqlite::{Connection, DatabaseName::Main, OptionalExtension};
|
||||||
use std::{
|
use std::{
|
||||||
collections::BTreeMap,
|
cell::RefCell,
|
||||||
|
collections::HashMap,
|
||||||
future::Future,
|
future::Future,
|
||||||
ops::Deref,
|
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
pin::Pin,
|
pin::Pin,
|
||||||
sync::Arc,
|
sync::Arc,
|
||||||
thread,
|
|
||||||
time::{Duration, Instant},
|
time::{Duration, Instant},
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::{database::Config, Result};
|
|
||||||
|
|
||||||
use super::{DatabaseEngine, Tree};
|
|
||||||
|
|
||||||
use log::debug;
|
|
||||||
|
|
||||||
use crossbeam::channel::{bounded, Sender as ChannelSender};
|
|
||||||
use parking_lot::{Mutex, MutexGuard, RwLock};
|
|
||||||
use rusqlite::{params, Connection, DatabaseName::Main, OptionalExtension};
|
|
||||||
|
|
||||||
use tokio::sync::oneshot::Sender;
|
use tokio::sync::oneshot::Sender;
|
||||||
|
use tracing::debug;
|
||||||
|
|
||||||
// const SQL_CREATE_TABLE: &str =
|
thread_local! {
|
||||||
// "CREATE TABLE IF NOT EXISTS {} {{ \"key\" BLOB PRIMARY KEY, \"value\" BLOB NOT NULL }}";
|
static READ_CONNECTION: RefCell<Option<&'static Connection>> = RefCell::new(None);
|
||||||
// const SQL_SELECT: &str = "SELECT value FROM {} WHERE key = ?";
|
}
|
||||||
// const SQL_INSERT: &str = "INSERT OR REPLACE INTO {} (key, value) VALUES (?, ?)";
|
|
||||||
// const SQL_DELETE: &str = "DELETE FROM {} WHERE key = ?";
|
|
||||||
// const SQL_SELECT_ITER: &str = "SELECT key, value FROM {}";
|
|
||||||
// const SQL_SELECT_PREFIX: &str = "SELECT key, value FROM {} WHERE key LIKE ?||'%' ORDER BY key ASC";
|
|
||||||
// const SQL_SELECT_ITER_FROM_FORWARDS: &str = "SELECT key, value FROM {} WHERE key >= ? ORDER BY ASC";
|
|
||||||
// const SQL_SELECT_ITER_FROM_BACKWARDS: &str =
|
|
||||||
// "SELECT key, value FROM {} WHERE key <= ? ORDER BY DESC";
|
|
||||||
|
|
||||||
struct Pool {
|
struct PreparedStatementIterator<'a> {
|
||||||
|
pub iterator: Box<dyn Iterator<Item = TupleOfBytes> + 'a>,
|
||||||
|
pub statement_ref: NonAliasingBox<rusqlite::Statement<'a>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Iterator for PreparedStatementIterator<'_> {
|
||||||
|
type Item = TupleOfBytes;
|
||||||
|
|
||||||
|
fn next(&mut self) -> Option<Self::Item> {
|
||||||
|
self.iterator.next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct NonAliasingBox<T>(*mut T);
|
||||||
|
impl<T> Drop for NonAliasingBox<T> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
unsafe { Box::from_raw(self.0) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Engine {
|
||||||
writer: Mutex<Connection>,
|
writer: Mutex<Connection>,
|
||||||
readers: Vec<Mutex<Connection>>,
|
|
||||||
spill_tracker: Arc<()>,
|
|
||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
|
cache_size_per_thread: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub const MILLI: Duration = Duration::from_millis(1);
|
impl Engine {
|
||||||
|
fn prepare_conn(path: &Path, cache_size_kb: u32) -> Result<Connection> {
|
||||||
|
let conn = Connection::open(&path)?;
|
||||||
|
|
||||||
enum HoldingConn<'a> {
|
conn.pragma_update(Some(Main), "page_size", &32768)?;
|
||||||
FromGuard(MutexGuard<'a, Connection>),
|
conn.pragma_update(Some(Main), "journal_mode", &"WAL")?;
|
||||||
FromOwned(Connection, Arc<()>),
|
conn.pragma_update(Some(Main), "synchronous", &"NORMAL")?;
|
||||||
}
|
conn.pragma_update(Some(Main), "cache_size", &(-i64::from(cache_size_kb)))?;
|
||||||
|
conn.pragma_update(Some(Main), "wal_autocheckpoint", &0)?;
|
||||||
impl<'a> Deref for HoldingConn<'a> {
|
|
||||||
type Target = Connection;
|
|
||||||
|
|
||||||
fn deref(&self) -> &Self::Target {
|
|
||||||
match self {
|
|
||||||
HoldingConn::FromGuard(guard) => guard.deref(),
|
|
||||||
HoldingConn::FromOwned(conn, _) => conn,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Pool {
|
|
||||||
fn new<P: AsRef<Path>>(path: P, num_readers: usize, cache_size: u32) -> Result<Self> {
|
|
||||||
let writer = Mutex::new(Self::prepare_conn(&path, Some(cache_size))?);
|
|
||||||
|
|
||||||
let mut readers = Vec::new();
|
|
||||||
|
|
||||||
for _ in 0..num_readers {
|
|
||||||
readers.push(Mutex::new(Self::prepare_conn(&path, Some(cache_size))?))
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Self {
|
|
||||||
writer,
|
|
||||||
readers,
|
|
||||||
spill_tracker: Arc::new(()),
|
|
||||||
path: path.as_ref().to_path_buf(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn prepare_conn<P: AsRef<Path>>(path: P, cache_size: Option<u32>) -> Result<Connection> {
|
|
||||||
let conn = Connection::open(path)?;
|
|
||||||
|
|
||||||
conn.pragma_update(Some(Main), "journal_mode", &"WAL".to_owned())?;
|
|
||||||
|
|
||||||
// conn.pragma_update(Some(Main), "wal_autocheckpoint", &250)?;
|
|
||||||
|
|
||||||
// conn.pragma_update(Some(Main), "wal_checkpoint", &"FULL".to_owned())?;
|
|
||||||
|
|
||||||
conn.pragma_update(Some(Main), "synchronous", &"OFF".to_owned())?;
|
|
||||||
|
|
||||||
if let Some(cache_kib) = cache_size {
|
|
||||||
conn.pragma_update(Some(Main), "cache_size", &(-Into::<i64>::into(cache_kib)))?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(conn)
|
Ok(conn)
|
||||||
}
|
}
|
||||||
@@ -97,102 +62,76 @@ impl Pool {
|
|||||||
self.writer.lock()
|
self.writer.lock()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_lock(&self) -> HoldingConn<'_> {
|
fn read_lock(&self) -> &'static Connection {
|
||||||
for r in &self.readers {
|
READ_CONNECTION.with(|cell| {
|
||||||
if let Some(reader) = r.try_lock() {
|
let connection = &mut cell.borrow_mut();
|
||||||
return HoldingConn::FromGuard(reader);
|
|
||||||
|
if (*connection).is_none() {
|
||||||
|
let c = Box::leak(Box::new(
|
||||||
|
Self::prepare_conn(&self.path, self.cache_size_per_thread).unwrap(),
|
||||||
|
));
|
||||||
|
**connection = Some(c);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
let spill_arc = self.spill_tracker.clone();
|
connection.unwrap()
|
||||||
let now_count = Arc::strong_count(&spill_arc) - 1 /* because one is held by the pool */;
|
})
|
||||||
|
|
||||||
log::warn!("read_lock: all readers locked, creating spillover reader...");
|
|
||||||
|
|
||||||
if now_count > 1 {
|
|
||||||
log::warn!("read_lock: now {} spillover readers exist", now_count);
|
|
||||||
}
|
|
||||||
|
|
||||||
let spilled = Self::prepare_conn(&self.path, None).unwrap();
|
|
||||||
|
|
||||||
return HoldingConn::FromOwned(spilled, spill_arc);
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Engine {
|
pub fn flush_wal(self: &Arc<Self>) -> Result<()> {
|
||||||
pool: Pool,
|
self.write_lock()
|
||||||
|
.pragma_update(Some(Main), "wal_checkpoint", &"TRUNCATE")?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DatabaseEngine for Engine {
|
impl DatabaseEngine for Engine {
|
||||||
fn open(config: &Config) -> Result<Arc<Self>> {
|
fn open(config: &Config) -> Result<Arc<Self>> {
|
||||||
let pool = Pool::new(
|
let path = Path::new(&config.database_path).join("conduit.db");
|
||||||
Path::new(&config.database_path).join("conduit.db"),
|
|
||||||
config.sqlite_read_pool_size,
|
|
||||||
config.db_cache_capacity / 1024, // bytes -> kb
|
|
||||||
)?;
|
|
||||||
|
|
||||||
pool.write_lock()
|
// calculates cache-size per permanent connection
|
||||||
.execute("CREATE TABLE IF NOT EXISTS _noop (\"key\" INT)", params![])?;
|
// 1. convert MB to KiB
|
||||||
|
// 2. divide by permanent connections
|
||||||
|
// 3. round down to nearest integer
|
||||||
|
let cache_size_per_thread: u32 =
|
||||||
|
((config.db_cache_capacity_mb * 1024.0) / (num_cpus::get().max(1) + 1) as f64) as u32;
|
||||||
|
|
||||||
let arc = Arc::new(Engine { pool });
|
let writer = Mutex::new(Self::prepare_conn(&path, cache_size_per_thread)?);
|
||||||
|
|
||||||
|
let arc = Arc::new(Engine {
|
||||||
|
writer,
|
||||||
|
path,
|
||||||
|
cache_size_per_thread,
|
||||||
|
});
|
||||||
|
|
||||||
Ok(arc)
|
Ok(arc)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn open_tree(self: &Arc<Self>, name: &str) -> Result<Arc<dyn Tree>> {
|
fn open_tree(self: &Arc<Self>, name: &str) -> Result<Arc<dyn Tree>> {
|
||||||
self.pool.write_lock().execute(format!("CREATE TABLE IF NOT EXISTS {} ( \"key\" BLOB PRIMARY KEY, \"value\" BLOB NOT NULL )", name).as_str(), [])?;
|
self.write_lock().execute(&format!("CREATE TABLE IF NOT EXISTS {} ( \"key\" BLOB PRIMARY KEY, \"value\" BLOB NOT NULL )", name), [])?;
|
||||||
|
|
||||||
Ok(Arc::new(SqliteTable {
|
Ok(Arc::new(SqliteTable {
|
||||||
engine: Arc::clone(self),
|
engine: Arc::clone(self),
|
||||||
name: name.to_owned(),
|
name: name.to_owned(),
|
||||||
watchers: RwLock::new(BTreeMap::new()),
|
watchers: RwLock::new(HashMap::new()),
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn flush(self: &Arc<Self>) -> Result<()> {
|
fn flush(self: &Arc<Self>) -> Result<()> {
|
||||||
self.pool
|
// we enabled PRAGMA synchronous=normal, so this should not be necessary
|
||||||
.write_lock()
|
Ok(())
|
||||||
.execute_batch(
|
|
||||||
"
|
|
||||||
PRAGMA synchronous=FULL;
|
|
||||||
BEGIN;
|
|
||||||
DELETE FROM _noop;
|
|
||||||
INSERT INTO _noop VALUES (1);
|
|
||||||
COMMIT;
|
|
||||||
PRAGMA synchronous=OFF;
|
|
||||||
",
|
|
||||||
)
|
|
||||||
.map_err(Into::into)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Engine {
|
|
||||||
pub fn flush_wal(self: &Arc<Self>) -> Result<()> {
|
|
||||||
self.pool
|
|
||||||
.write_lock()
|
|
||||||
.execute_batch(
|
|
||||||
"
|
|
||||||
PRAGMA synchronous=FULL; PRAGMA wal_checkpoint=TRUNCATE;
|
|
||||||
BEGIN;
|
|
||||||
DELETE FROM _noop;
|
|
||||||
INSERT INTO _noop VALUES (1);
|
|
||||||
COMMIT;
|
|
||||||
PRAGMA wal_checkpoint=PASSIVE; PRAGMA synchronous=OFF;
|
|
||||||
",
|
|
||||||
)
|
|
||||||
.map_err(Into::into)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct SqliteTable {
|
pub struct SqliteTable {
|
||||||
engine: Arc<Engine>,
|
engine: Arc<Engine>,
|
||||||
name: String,
|
name: String,
|
||||||
watchers: RwLock<BTreeMap<Vec<u8>, Vec<Sender<()>>>>,
|
watchers: RwLock<HashMap<Vec<u8>, Vec<Sender<()>>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
type TupleOfBytes = (Vec<u8>, Vec<u8>);
|
type TupleOfBytes = (Vec<u8>, Vec<u8>);
|
||||||
|
|
||||||
impl SqliteTable {
|
impl SqliteTable {
|
||||||
|
#[tracing::instrument(skip(self, guard, key))]
|
||||||
fn get_with_guard(&self, guard: &Connection, key: &[u8]) -> Result<Option<Vec<u8>>> {
|
fn get_with_guard(&self, guard: &Connection, key: &[u8]) -> Result<Option<Vec<u8>>> {
|
||||||
Ok(guard
|
Ok(guard
|
||||||
.prepare(format!("SELECT value FROM {} WHERE key = ?", self.name).as_str())?
|
.prepare(format!("SELECT value FROM {} WHERE key = ?", self.name).as_str())?
|
||||||
@@ -200,10 +139,11 @@ impl SqliteTable {
|
|||||||
.optional()?)
|
.optional()?)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, guard, key, value))]
|
||||||
fn insert_with_guard(&self, guard: &Connection, key: &[u8], value: &[u8]) -> Result<()> {
|
fn insert_with_guard(&self, guard: &Connection, key: &[u8], value: &[u8]) -> Result<()> {
|
||||||
guard.execute(
|
guard.execute(
|
||||||
format!(
|
format!(
|
||||||
"INSERT INTO {} (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
"INSERT OR REPLACE INTO {} (key, value) VALUES (?, ?)",
|
||||||
self.name
|
self.name
|
||||||
)
|
)
|
||||||
.as_str(),
|
.as_str(),
|
||||||
@@ -211,63 +151,18 @@ impl SqliteTable {
|
|||||||
)?;
|
)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn _iter_from_thread<F>(&self, f: F) -> Box<dyn Iterator<Item = TupleOfBytes> + Send>
|
|
||||||
where
|
|
||||||
F: (for<'a> FnOnce(&'a Connection, ChannelSender<TupleOfBytes>)) + Send + 'static,
|
|
||||||
{
|
|
||||||
let (s, r) = bounded::<TupleOfBytes>(5);
|
|
||||||
|
|
||||||
let engine = self.engine.clone();
|
|
||||||
|
|
||||||
thread::spawn(move || {
|
|
||||||
let _ = f(&engine.pool.read_lock(), s);
|
|
||||||
});
|
|
||||||
|
|
||||||
Box::new(r.into_iter())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
macro_rules! iter_from_thread {
|
|
||||||
($self:expr, $sql:expr, $param:expr) => {
|
|
||||||
$self._iter_from_thread(move |guard, s| {
|
|
||||||
let _ = guard
|
|
||||||
.prepare($sql)
|
|
||||||
.unwrap()
|
|
||||||
.query_map($param, |row| Ok((row.get_unwrap(0), row.get_unwrap(1))))
|
|
||||||
.unwrap()
|
|
||||||
.map(|r| r.unwrap())
|
|
||||||
.try_for_each(|bob| s.send(bob));
|
|
||||||
})
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Tree for SqliteTable {
|
impl Tree for SqliteTable {
|
||||||
|
#[tracing::instrument(skip(self, key))]
|
||||||
fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>> {
|
fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>> {
|
||||||
let guard = self.engine.pool.read_lock();
|
self.get_with_guard(&self.engine.read_lock(), key)
|
||||||
|
|
||||||
// let start = Instant::now();
|
|
||||||
|
|
||||||
let val = self.get_with_guard(&guard, key);
|
|
||||||
|
|
||||||
// debug!("get: took {:?}", start.elapsed());
|
|
||||||
// debug!("get key: {:?}", &key)
|
|
||||||
|
|
||||||
val
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, key, value))]
|
||||||
fn insert(&self, key: &[u8], value: &[u8]) -> Result<()> {
|
fn insert(&self, key: &[u8], value: &[u8]) -> Result<()> {
|
||||||
let guard = self.engine.pool.write_lock();
|
let guard = self.engine.write_lock();
|
||||||
|
|
||||||
let start = Instant::now();
|
|
||||||
|
|
||||||
self.insert_with_guard(&guard, key, value)?;
|
self.insert_with_guard(&guard, key, value)?;
|
||||||
|
|
||||||
let elapsed = start.elapsed();
|
|
||||||
if elapsed > MILLI {
|
|
||||||
debug!("insert: took {:012?} : {}", elapsed, &self.name);
|
|
||||||
}
|
|
||||||
|
|
||||||
drop(guard);
|
drop(guard);
|
||||||
|
|
||||||
let watchers = self.watchers.read();
|
let watchers = self.watchers.read();
|
||||||
@@ -295,69 +190,121 @@ impl Tree for SqliteTable {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn remove(&self, key: &[u8]) -> Result<()> {
|
#[tracing::instrument(skip(self, iter))]
|
||||||
let guard = self.engine.pool.write_lock();
|
fn insert_batch<'a>(&self, iter: &mut dyn Iterator<Item = (Vec<u8>, Vec<u8>)>) -> Result<()> {
|
||||||
|
let guard = self.engine.write_lock();
|
||||||
|
|
||||||
let start = Instant::now();
|
guard.execute("BEGIN", [])?;
|
||||||
|
for (key, value) in iter {
|
||||||
|
self.insert_with_guard(&guard, &key, &value)?;
|
||||||
|
}
|
||||||
|
guard.execute("COMMIT", [])?;
|
||||||
|
|
||||||
|
drop(guard);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, key))]
|
||||||
|
fn remove(&self, key: &[u8]) -> Result<()> {
|
||||||
|
let guard = self.engine.write_lock();
|
||||||
|
|
||||||
guard.execute(
|
guard.execute(
|
||||||
format!("DELETE FROM {} WHERE key = ?", self.name).as_str(),
|
format!("DELETE FROM {} WHERE key = ?", self.name).as_str(),
|
||||||
[key],
|
[key],
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
let elapsed = start.elapsed();
|
|
||||||
|
|
||||||
if elapsed > MILLI {
|
|
||||||
debug!("remove: took {:012?} : {}", elapsed, &self.name);
|
|
||||||
}
|
|
||||||
// debug!("remove key: {:?}", &key);
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = TupleOfBytes> + Send + 'a> {
|
#[tracing::instrument(skip(self))]
|
||||||
let name = self.name.clone();
|
fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = TupleOfBytes> + 'a> {
|
||||||
iter_from_thread!(
|
let guard = self.engine.read_lock();
|
||||||
self,
|
|
||||||
format!("SELECT key, value FROM {}", name).as_str(),
|
let statement = Box::leak(Box::new(
|
||||||
params![]
|
guard
|
||||||
)
|
.prepare(&format!(
|
||||||
|
"SELECT key, value FROM {} ORDER BY key ASC",
|
||||||
|
&self.name
|
||||||
|
))
|
||||||
|
.unwrap(),
|
||||||
|
));
|
||||||
|
|
||||||
|
let statement_ref = NonAliasingBox(statement);
|
||||||
|
|
||||||
|
let iterator = Box::new(
|
||||||
|
statement
|
||||||
|
.query_map([], |row| Ok((row.get_unwrap(0), row.get_unwrap(1))))
|
||||||
|
.unwrap()
|
||||||
|
.map(|r| r.unwrap()),
|
||||||
|
);
|
||||||
|
|
||||||
|
Box::new(PreparedStatementIterator {
|
||||||
|
iterator,
|
||||||
|
statement_ref,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, from, backwards))]
|
||||||
fn iter_from<'a>(
|
fn iter_from<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
from: &[u8],
|
from: &[u8],
|
||||||
backwards: bool,
|
backwards: bool,
|
||||||
) -> Box<dyn Iterator<Item = TupleOfBytes> + Send + 'a> {
|
) -> Box<dyn Iterator<Item = TupleOfBytes> + 'a> {
|
||||||
let name = self.name.clone();
|
let guard = self.engine.read_lock();
|
||||||
let from = from.to_vec(); // TODO change interface?
|
let from = from.to_vec(); // TODO change interface?
|
||||||
|
|
||||||
if backwards {
|
if backwards {
|
||||||
iter_from_thread!(
|
let statement = Box::leak(Box::new(
|
||||||
self,
|
guard
|
||||||
format!(
|
.prepare(&format!(
|
||||||
"SELECT key, value FROM {} WHERE key <= ? ORDER BY key DESC",
|
"SELECT key, value FROM {} WHERE key <= ? ORDER BY key DESC",
|
||||||
name
|
&self.name
|
||||||
)
|
))
|
||||||
.as_str(),
|
.unwrap(),
|
||||||
[from]
|
));
|
||||||
)
|
|
||||||
|
let statement_ref = NonAliasingBox(statement);
|
||||||
|
|
||||||
|
let iterator = Box::new(
|
||||||
|
statement
|
||||||
|
.query_map([from], |row| Ok((row.get_unwrap(0), row.get_unwrap(1))))
|
||||||
|
.unwrap()
|
||||||
|
.map(|r| r.unwrap()),
|
||||||
|
);
|
||||||
|
Box::new(PreparedStatementIterator {
|
||||||
|
iterator,
|
||||||
|
statement_ref,
|
||||||
|
})
|
||||||
} else {
|
} else {
|
||||||
iter_from_thread!(
|
let statement = Box::leak(Box::new(
|
||||||
self,
|
guard
|
||||||
format!(
|
.prepare(&format!(
|
||||||
"SELECT key, value FROM {} WHERE key >= ? ORDER BY key ASC",
|
"SELECT key, value FROM {} WHERE key >= ? ORDER BY key ASC",
|
||||||
name
|
&self.name
|
||||||
)
|
))
|
||||||
.as_str(),
|
.unwrap(),
|
||||||
[from]
|
));
|
||||||
)
|
|
||||||
|
let statement_ref = NonAliasingBox(statement);
|
||||||
|
|
||||||
|
let iterator = Box::new(
|
||||||
|
statement
|
||||||
|
.query_map([from], |row| Ok((row.get_unwrap(0), row.get_unwrap(1))))
|
||||||
|
.unwrap()
|
||||||
|
.map(|r| r.unwrap()),
|
||||||
|
);
|
||||||
|
|
||||||
|
Box::new(PreparedStatementIterator {
|
||||||
|
iterator,
|
||||||
|
statement_ref,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, key))]
|
||||||
fn increment(&self, key: &[u8]) -> Result<Vec<u8>> {
|
fn increment(&self, key: &[u8]) -> Result<Vec<u8>> {
|
||||||
let guard = self.engine.pool.write_lock();
|
let guard = self.engine.write_lock();
|
||||||
|
|
||||||
let start = Instant::now();
|
|
||||||
|
|
||||||
let old = self.get_with_guard(&guard, key)?;
|
let old = self.get_with_guard(&guard, key)?;
|
||||||
|
|
||||||
@@ -366,36 +313,18 @@ impl Tree for SqliteTable {
|
|||||||
|
|
||||||
self.insert_with_guard(&guard, key, &new)?;
|
self.insert_with_guard(&guard, key, &new)?;
|
||||||
|
|
||||||
let elapsed = start.elapsed();
|
|
||||||
|
|
||||||
if elapsed > MILLI {
|
|
||||||
debug!("increment: took {:012?} : {}", elapsed, &self.name);
|
|
||||||
}
|
|
||||||
// debug!("increment key: {:?}", &key);
|
|
||||||
|
|
||||||
Ok(new)
|
Ok(new)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn scan_prefix<'a>(
|
#[tracing::instrument(skip(self, prefix))]
|
||||||
&'a self,
|
fn scan_prefix<'a>(&'a self, prefix: Vec<u8>) -> Box<dyn Iterator<Item = TupleOfBytes> + 'a> {
|
||||||
prefix: Vec<u8>,
|
|
||||||
) -> Box<dyn Iterator<Item = TupleOfBytes> + Send + 'a> {
|
|
||||||
// let name = self.name.clone();
|
|
||||||
// iter_from_thread!(
|
|
||||||
// self,
|
|
||||||
// format!(
|
|
||||||
// "SELECT key, value FROM {} WHERE key BETWEEN ?1 AND ?1 || X'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF' ORDER BY key ASC",
|
|
||||||
// name
|
|
||||||
// )
|
|
||||||
// .as_str(),
|
|
||||||
// [prefix]
|
|
||||||
// )
|
|
||||||
Box::new(
|
Box::new(
|
||||||
self.iter_from(&prefix, false)
|
self.iter_from(&prefix, false)
|
||||||
.take_while(move |(key, _)| key.starts_with(&prefix)),
|
.take_while(move |(key, _)| key.starts_with(&prefix)),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, prefix))]
|
||||||
fn watch_prefix<'a>(&'a self, prefix: &[u8]) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
|
fn watch_prefix<'a>(&'a self, prefix: &[u8]) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
|
||||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||||
|
|
||||||
@@ -411,28 +340,13 @@ impl Tree for SqliteTable {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self))]
|
||||||
fn clear(&self) -> Result<()> {
|
fn clear(&self) -> Result<()> {
|
||||||
debug!("clear: running");
|
debug!("clear: running");
|
||||||
self.engine
|
self.engine
|
||||||
.pool
|
|
||||||
.write_lock()
|
.write_lock()
|
||||||
.execute(format!("DELETE FROM {}", self.name).as_str(), [])?;
|
.execute(format!("DELETE FROM {}", self.name).as_str(), [])?;
|
||||||
debug!("clear: ran");
|
debug!("clear: ran");
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO
|
|
||||||
// struct Pool<const NUM_READERS: usize> {
|
|
||||||
// writer: Mutex<Connection>,
|
|
||||||
// readers: [Mutex<Connection>; NUM_READERS],
|
|
||||||
// }
|
|
||||||
|
|
||||||
// // then, to pick a reader:
|
|
||||||
// for r in &pool.readers {
|
|
||||||
// if let Ok(reader) = r.try_lock() {
|
|
||||||
// // use reader
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// // none unlocked, pick the next reader
|
|
||||||
// pool.readers[pool.counter.fetch_add(1, Relaxed) % NUM_READERS].lock()
|
|
||||||
|
|||||||
@@ -12,10 +12,12 @@ use super::abstraction::Tree;
|
|||||||
|
|
||||||
pub struct AccountData {
|
pub struct AccountData {
|
||||||
pub(super) roomuserdataid_accountdata: Arc<dyn Tree>, // RoomUserDataId = Room + User + Count + Type
|
pub(super) roomuserdataid_accountdata: Arc<dyn Tree>, // RoomUserDataId = Room + User + Count + Type
|
||||||
|
pub(super) roomusertype_roomuserdataid: Arc<dyn Tree>, // RoomUserType = Room + User + Type
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AccountData {
|
impl AccountData {
|
||||||
/// Places one event in the account data of the user and removes the previous entry.
|
/// Places one event in the account data of the user and removes the previous entry.
|
||||||
|
#[tracing::instrument(skip(self, room_id, user_id, event_type, data, globals))]
|
||||||
pub fn update<T: Serialize>(
|
pub fn update<T: Serialize>(
|
||||||
&self,
|
&self,
|
||||||
room_id: Option<&RoomId>,
|
room_id: Option<&RoomId>,
|
||||||
@@ -33,15 +35,13 @@ impl AccountData {
|
|||||||
prefix.extend_from_slice(&user_id.as_bytes());
|
prefix.extend_from_slice(&user_id.as_bytes());
|
||||||
prefix.push(0xff);
|
prefix.push(0xff);
|
||||||
|
|
||||||
// Remove old entry
|
let mut roomuserdataid = prefix.clone();
|
||||||
if let Some((old_key, _)) = self.find_event(room_id, user_id, &event_type)? {
|
roomuserdataid.extend_from_slice(&globals.next_count()?.to_be_bytes());
|
||||||
self.roomuserdataid_accountdata.remove(&old_key)?;
|
roomuserdataid.push(0xff);
|
||||||
}
|
roomuserdataid.extend_from_slice(&event_type.as_bytes());
|
||||||
|
|
||||||
let mut key = prefix;
|
let mut key = prefix.clone();
|
||||||
key.extend_from_slice(&globals.next_count()?.to_be_bytes());
|
key.extend_from_slice(event_type.as_bytes());
|
||||||
key.push(0xff);
|
|
||||||
key.extend_from_slice(event_type.as_ref().as_bytes());
|
|
||||||
|
|
||||||
let json = serde_json::to_value(data).expect("all types here can be serialized"); // TODO: maybe add error handling
|
let json = serde_json::to_value(data).expect("all types here can be serialized"); // TODO: maybe add error handling
|
||||||
if json.get("type").is_none() || json.get("content").is_none() {
|
if json.get("type").is_none() || json.get("content").is_none() {
|
||||||
@@ -52,29 +52,58 @@ impl AccountData {
|
|||||||
}
|
}
|
||||||
|
|
||||||
self.roomuserdataid_accountdata.insert(
|
self.roomuserdataid_accountdata.insert(
|
||||||
&key,
|
&roomuserdataid,
|
||||||
&serde_json::to_vec(&json).expect("to_vec always works on json values"),
|
&serde_json::to_vec(&json).expect("to_vec always works on json values"),
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
|
let prev = self.roomusertype_roomuserdataid.get(&key)?;
|
||||||
|
|
||||||
|
self.roomusertype_roomuserdataid
|
||||||
|
.insert(&key, &roomuserdataid)?;
|
||||||
|
|
||||||
|
// Remove old entry
|
||||||
|
if let Some(prev) = prev {
|
||||||
|
self.roomuserdataid_accountdata.remove(&prev)?;
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Searches the account data for a specific kind.
|
/// Searches the account data for a specific kind.
|
||||||
|
#[tracing::instrument(skip(self, room_id, user_id, kind))]
|
||||||
pub fn get<T: DeserializeOwned>(
|
pub fn get<T: DeserializeOwned>(
|
||||||
&self,
|
&self,
|
||||||
room_id: Option<&RoomId>,
|
room_id: Option<&RoomId>,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
kind: EventType,
|
kind: EventType,
|
||||||
) -> Result<Option<T>> {
|
) -> Result<Option<T>> {
|
||||||
self.find_event(room_id, user_id, &kind)?
|
let mut key = room_id
|
||||||
.map(|(_, v)| {
|
.map(|r| r.to_string())
|
||||||
serde_json::from_slice(&v).map_err(|_| Error::bad_database("could not deserialize"))
|
.unwrap_or_default()
|
||||||
|
.as_bytes()
|
||||||
|
.to_vec();
|
||||||
|
key.push(0xff);
|
||||||
|
key.extend_from_slice(&user_id.as_bytes());
|
||||||
|
key.push(0xff);
|
||||||
|
key.extend_from_slice(kind.as_ref().as_bytes());
|
||||||
|
|
||||||
|
self.roomusertype_roomuserdataid
|
||||||
|
.get(&key)?
|
||||||
|
.and_then(|roomuserdataid| {
|
||||||
|
self.roomuserdataid_accountdata
|
||||||
|
.get(&roomuserdataid)
|
||||||
|
.transpose()
|
||||||
|
})
|
||||||
|
.transpose()?
|
||||||
|
.map(|data| {
|
||||||
|
serde_json::from_slice(&data)
|
||||||
|
.map_err(|_| Error::bad_database("could not deserialize"))
|
||||||
})
|
})
|
||||||
.transpose()
|
.transpose()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns all changes to the account data that happened after `since`.
|
/// Returns all changes to the account data that happened after `since`.
|
||||||
#[tracing::instrument(skip(self))]
|
#[tracing::instrument(skip(self, room_id, user_id, since))]
|
||||||
pub fn changes_since(
|
pub fn changes_since(
|
||||||
&self,
|
&self,
|
||||||
room_id: Option<&RoomId>,
|
room_id: Option<&RoomId>,
|
||||||
@@ -121,36 +150,4 @@ impl AccountData {
|
|||||||
|
|
||||||
Ok(userdata)
|
Ok(userdata)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn find_event(
|
|
||||||
&self,
|
|
||||||
room_id: Option<&RoomId>,
|
|
||||||
user_id: &UserId,
|
|
||||||
kind: &EventType,
|
|
||||||
) -> Result<Option<(Vec<u8>, Vec<u8>)>> {
|
|
||||||
let mut prefix = room_id
|
|
||||||
.map(|r| r.to_string())
|
|
||||||
.unwrap_or_default()
|
|
||||||
.as_bytes()
|
|
||||||
.to_vec();
|
|
||||||
prefix.push(0xff);
|
|
||||||
prefix.extend_from_slice(&user_id.as_bytes());
|
|
||||||
prefix.push(0xff);
|
|
||||||
|
|
||||||
let mut last_possible_key = prefix.clone();
|
|
||||||
last_possible_key.extend_from_slice(&u64::MAX.to_be_bytes());
|
|
||||||
|
|
||||||
let kind = kind.clone();
|
|
||||||
|
|
||||||
Ok(self
|
|
||||||
.roomuserdataid_accountdata
|
|
||||||
.iter_from(&last_possible_key, true)
|
|
||||||
.take_while(move |(k, _)| k.starts_with(&prefix))
|
|
||||||
.find(move |(k, _)| {
|
|
||||||
k.rsplit(|&b| b == 0xff)
|
|
||||||
.next()
|
|
||||||
.map(|current_event_type| current_event_type == kind.as_ref().as_bytes())
|
|
||||||
.unwrap_or(false)
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,13 +4,13 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use crate::{pdu::PduBuilder, Database};
|
use crate::{pdu::PduBuilder, Database};
|
||||||
use log::warn;
|
|
||||||
use rocket::futures::{channel::mpsc, stream::StreamExt};
|
use rocket::futures::{channel::mpsc, stream::StreamExt};
|
||||||
use ruma::{
|
use ruma::{
|
||||||
events::{room::message, EventType},
|
events::{room::message, EventType},
|
||||||
UserId,
|
UserId,
|
||||||
};
|
};
|
||||||
use tokio::sync::{MutexGuard, RwLock, RwLockReadGuard};
|
use tokio::sync::{MutexGuard, RwLock, RwLockReadGuard};
|
||||||
|
use tracing::warn;
|
||||||
|
|
||||||
pub enum AdminCommand {
|
pub enum AdminCommand {
|
||||||
RegisterAppservice(serde_yaml::Value),
|
RegisterAppservice(serde_yaml::Value),
|
||||||
@@ -84,15 +84,15 @@ impl Admin {
|
|||||||
tokio::select! {
|
tokio::select! {
|
||||||
Some(event) = receiver.next() => {
|
Some(event) = receiver.next() => {
|
||||||
let guard = db.read().await;
|
let guard = db.read().await;
|
||||||
let mutex = Arc::clone(
|
let mutex_state = Arc::clone(
|
||||||
guard.globals
|
guard.globals
|
||||||
.roomid_mutex
|
.roomid_mutex_state
|
||||||
.write()
|
.write()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.entry(conduit_room.clone())
|
.entry(conduit_room.clone())
|
||||||
.or_default(),
|
.or_default(),
|
||||||
);
|
);
|
||||||
let mutex_lock = mutex.lock().await;
|
let state_lock = mutex_state.lock().await;
|
||||||
|
|
||||||
match event {
|
match event {
|
||||||
AdminCommand::RegisterAppservice(yaml) => {
|
AdminCommand::RegisterAppservice(yaml) => {
|
||||||
@@ -106,17 +106,17 @@ impl Admin {
|
|||||||
count,
|
count,
|
||||||
appservices.into_iter().filter_map(|r| r.ok()).collect::<Vec<_>>().join(", ")
|
appservices.into_iter().filter_map(|r| r.ok()).collect::<Vec<_>>().join(", ")
|
||||||
);
|
);
|
||||||
send_message(message::MessageEventContent::text_plain(output), guard, &mutex_lock);
|
send_message(message::MessageEventContent::text_plain(output), guard, &state_lock);
|
||||||
} else {
|
} else {
|
||||||
send_message(message::MessageEventContent::text_plain("Failed to get appservices."), guard, &mutex_lock);
|
send_message(message::MessageEventContent::text_plain("Failed to get appservices."), guard, &state_lock);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
AdminCommand::SendMessage(message) => {
|
AdminCommand::SendMessage(message) => {
|
||||||
send_message(message, guard, &mutex_lock);
|
send_message(message, guard, &state_lock);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
drop(mutex_lock);
|
drop(state_lock);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+12
-11
@@ -49,22 +49,23 @@ impl Appservice {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn iter_ids(&self) -> Result<impl Iterator<Item = Result<String>> + Send + '_> {
|
pub fn iter_ids(&self) -> Result<impl Iterator<Item = Result<String>> + '_> {
|
||||||
Ok(self.id_appserviceregistrations.iter().map(|(id, _)| {
|
Ok(self.id_appserviceregistrations.iter().map(|(id, _)| {
|
||||||
utils::string_from_bytes(&id)
|
utils::string_from_bytes(&id)
|
||||||
.map_err(|_| Error::bad_database("Invalid id bytes in id_appserviceregistrations."))
|
.map_err(|_| Error::bad_database("Invalid id bytes in id_appserviceregistrations."))
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn iter_all(
|
pub fn all(&self) -> Result<Vec<(String, serde_yaml::Value)>> {
|
||||||
&self,
|
self.iter_ids()?
|
||||||
) -> Result<impl Iterator<Item = Result<(String, serde_yaml::Value)>> + '_ + Send> {
|
.filter_map(|id| id.ok())
|
||||||
Ok(self.iter_ids()?.filter_map(|id| id.ok()).map(move |id| {
|
.map(move |id| {
|
||||||
Ok((
|
Ok((
|
||||||
id.clone(),
|
id.clone(),
|
||||||
self.get_registration(&id)?
|
self.get_registration(&id)?
|
||||||
.expect("iter_ids only returns appservices that exist"),
|
.expect("iter_ids only returns appservices that exist"),
|
||||||
))
|
))
|
||||||
}))
|
})
|
||||||
|
.collect()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+34
-23
@@ -1,5 +1,4 @@
|
|||||||
use crate::{database::Config, utils, ConduitResult, Error, Result};
|
use crate::{database::Config, utils, ConduitResult, Error, Result};
|
||||||
use log::{error, info};
|
|
||||||
use ruma::{
|
use ruma::{
|
||||||
api::{
|
api::{
|
||||||
client::r0::sync::sync_events,
|
client::r0::sync::sync_events,
|
||||||
@@ -13,10 +12,11 @@ use std::{
|
|||||||
fs,
|
fs,
|
||||||
future::Future,
|
future::Future,
|
||||||
path::PathBuf,
|
path::PathBuf,
|
||||||
sync::{Arc, RwLock},
|
sync::{Arc, Mutex, RwLock},
|
||||||
time::{Duration, Instant},
|
time::{Duration, Instant},
|
||||||
};
|
};
|
||||||
use tokio::sync::{broadcast, Mutex, Semaphore};
|
use tokio::sync::{broadcast, watch::Receiver, Mutex as TokioMutex, Semaphore};
|
||||||
|
use tracing::{error, info};
|
||||||
use trust_dns_resolver::TokioAsyncResolver;
|
use trust_dns_resolver::TokioAsyncResolver;
|
||||||
|
|
||||||
use super::abstraction::Tree;
|
use super::abstraction::Tree;
|
||||||
@@ -26,6 +26,11 @@ pub const COUNTER: &[u8] = b"c";
|
|||||||
type WellKnownMap = HashMap<Box<ServerName>, (String, String)>;
|
type WellKnownMap = HashMap<Box<ServerName>, (String, String)>;
|
||||||
type TlsNameMap = HashMap<String, webpki::DNSName>;
|
type TlsNameMap = HashMap<String, webpki::DNSName>;
|
||||||
type RateLimitState = (Instant, u32); // Time if last failed try, number of failed tries
|
type RateLimitState = (Instant, u32); // Time if last failed try, number of failed tries
|
||||||
|
type SyncHandle = (
|
||||||
|
Option<String>, // since
|
||||||
|
Receiver<Option<ConduitResult<sync_events::Response>>>, // rx
|
||||||
|
);
|
||||||
|
|
||||||
pub struct Globals {
|
pub struct Globals {
|
||||||
pub actual_destination_cache: Arc<RwLock<WellKnownMap>>, // actual_destination, host
|
pub actual_destination_cache: Arc<RwLock<WellKnownMap>>, // actual_destination, host
|
||||||
pub tls_name_override: Arc<RwLock<TlsNameMap>>,
|
pub tls_name_override: Arc<RwLock<TlsNameMap>>,
|
||||||
@@ -36,20 +41,13 @@ pub struct Globals {
|
|||||||
dns_resolver: TokioAsyncResolver,
|
dns_resolver: TokioAsyncResolver,
|
||||||
jwt_decoding_key: Option<jsonwebtoken::DecodingKey<'static>>,
|
jwt_decoding_key: Option<jsonwebtoken::DecodingKey<'static>>,
|
||||||
pub(super) server_signingkeys: Arc<dyn Tree>,
|
pub(super) server_signingkeys: Arc<dyn Tree>,
|
||||||
pub bad_event_ratelimiter: Arc<RwLock<BTreeMap<EventId, RateLimitState>>>,
|
pub bad_event_ratelimiter: Arc<RwLock<HashMap<EventId, RateLimitState>>>,
|
||||||
pub bad_signature_ratelimiter: Arc<RwLock<BTreeMap<Vec<String>, RateLimitState>>>,
|
pub bad_signature_ratelimiter: Arc<RwLock<HashMap<Vec<String>, RateLimitState>>>,
|
||||||
pub servername_ratelimiter: Arc<RwLock<BTreeMap<Box<ServerName>, Arc<Semaphore>>>>,
|
pub servername_ratelimiter: Arc<RwLock<HashMap<Box<ServerName>, Arc<Semaphore>>>>,
|
||||||
pub roomid_mutex: RwLock<BTreeMap<RoomId, Arc<Mutex<()>>>>,
|
pub sync_receivers: RwLock<HashMap<(UserId, Box<DeviceId>), SyncHandle>>,
|
||||||
pub roomid_mutex_federation: RwLock<BTreeMap<RoomId, Arc<Mutex<()>>>>, // this lock will be held longer
|
pub roomid_mutex_insert: RwLock<HashMap<RoomId, Arc<Mutex<()>>>>,
|
||||||
pub sync_receivers: RwLock<
|
pub roomid_mutex_state: RwLock<HashMap<RoomId, Arc<TokioMutex<()>>>>,
|
||||||
BTreeMap<
|
pub roomid_mutex_federation: RwLock<HashMap<RoomId, Arc<TokioMutex<()>>>>, // this lock will be held longer
|
||||||
(UserId, Box<DeviceId>),
|
|
||||||
(
|
|
||||||
Option<String>,
|
|
||||||
tokio::sync::watch::Receiver<Option<ConduitResult<sync_events::Response>>>,
|
|
||||||
), // since, rx
|
|
||||||
>,
|
|
||||||
>,
|
|
||||||
pub rotate: RotationHandler,
|
pub rotate: RotationHandler,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,6 +57,7 @@ struct MatrixServerVerifier {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ServerCertVerifier for MatrixServerVerifier {
|
impl ServerCertVerifier for MatrixServerVerifier {
|
||||||
|
#[tracing::instrument(skip(self, roots, presented_certs, dns_name, ocsp_response))]
|
||||||
fn verify_server_cert(
|
fn verify_server_cert(
|
||||||
&self,
|
&self,
|
||||||
roots: &rustls::RootCertStore,
|
roots: &rustls::RootCertStore,
|
||||||
@@ -86,6 +85,9 @@ impl ServerCertVerifier for MatrixServerVerifier {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Handles "rotation" of long-polling requests. "Rotation" in this context is similar to "rotation" of log files and the like.
|
||||||
|
///
|
||||||
|
/// This is utilized to have sync workers return early and release read locks on the database.
|
||||||
pub struct RotationHandler(broadcast::Sender<()>, broadcast::Receiver<()>);
|
pub struct RotationHandler(broadcast::Sender<()>, broadcast::Receiver<()>);
|
||||||
|
|
||||||
impl RotationHandler {
|
impl RotationHandler {
|
||||||
@@ -108,6 +110,12 @@ impl RotationHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Default for RotationHandler {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl Globals {
|
impl Globals {
|
||||||
pub fn load(
|
pub fn load(
|
||||||
globals: Arc<dyn Tree>,
|
globals: Arc<dyn Tree>,
|
||||||
@@ -190,12 +198,13 @@ impl Globals {
|
|||||||
tls_name_override,
|
tls_name_override,
|
||||||
server_signingkeys,
|
server_signingkeys,
|
||||||
jwt_decoding_key,
|
jwt_decoding_key,
|
||||||
bad_event_ratelimiter: Arc::new(RwLock::new(BTreeMap::new())),
|
bad_event_ratelimiter: Arc::new(RwLock::new(HashMap::new())),
|
||||||
bad_signature_ratelimiter: Arc::new(RwLock::new(BTreeMap::new())),
|
bad_signature_ratelimiter: Arc::new(RwLock::new(HashMap::new())),
|
||||||
servername_ratelimiter: Arc::new(RwLock::new(BTreeMap::new())),
|
servername_ratelimiter: Arc::new(RwLock::new(HashMap::new())),
|
||||||
roomid_mutex: RwLock::new(BTreeMap::new()),
|
roomid_mutex_state: RwLock::new(HashMap::new()),
|
||||||
roomid_mutex_federation: RwLock::new(BTreeMap::new()),
|
roomid_mutex_insert: RwLock::new(HashMap::new()),
|
||||||
sync_receivers: RwLock::new(BTreeMap::new()),
|
roomid_mutex_federation: RwLock::new(HashMap::new()),
|
||||||
|
sync_receivers: RwLock::new(HashMap::new()),
|
||||||
rotate: RotationHandler::new(),
|
rotate: RotationHandler::new(),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -214,11 +223,13 @@ impl Globals {
|
|||||||
&self.reqwest_client
|
&self.reqwest_client
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self))]
|
||||||
pub fn next_count(&self) -> Result<u64> {
|
pub fn next_count(&self) -> Result<u64> {
|
||||||
utils::u64_from_bytes(&self.globals.increment(COUNTER)?)
|
utils::u64_from_bytes(&self.globals.increment(COUNTER)?)
|
||||||
.map_err(|_| Error::bad_database("Count has invalid bytes."))
|
.map_err(|_| Error::bad_database("Count has invalid bytes."))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self))]
|
||||||
pub fn current_count(&self) -> Result<u64> {
|
pub fn current_count(&self) -> Result<u64> {
|
||||||
self.globals.get(COUNTER)?.map_or(Ok(0_u64), |bytes| {
|
self.globals.get(COUNTER)?.map_or(Ok(0_u64), |bytes| {
|
||||||
utils::u64_from_bytes(&bytes)
|
utils::u64_from_bytes(&bytes)
|
||||||
|
|||||||
@@ -54,6 +54,7 @@ impl Media {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Uploads or replaces a file thumbnail.
|
/// Uploads or replaces a file thumbnail.
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
pub async fn upload_thumbnail(
|
pub async fn upload_thumbnail(
|
||||||
&self,
|
&self,
|
||||||
mxc: String,
|
mxc: String,
|
||||||
@@ -100,8 +101,8 @@ impl Media {
|
|||||||
prefix.extend_from_slice(&0_u32.to_be_bytes()); // Height = 0 if it's not a thumbnail
|
prefix.extend_from_slice(&0_u32.to_be_bytes()); // Height = 0 if it's not a thumbnail
|
||||||
prefix.push(0xff);
|
prefix.push(0xff);
|
||||||
|
|
||||||
let mut iter = self.mediaid_file.scan_prefix(prefix);
|
let first = self.mediaid_file.scan_prefix(prefix).next();
|
||||||
if let Some((key, _)) = iter.next() {
|
if let Some((key, _)) = first {
|
||||||
let path = globals.get_media_file(&key);
|
let path = globals.get_media_file(&key);
|
||||||
let mut file = Vec::new();
|
let mut file = Vec::new();
|
||||||
File::open(path).await?.read_to_end(&mut file).await?;
|
File::open(path).await?.read_to_end(&mut file).await?;
|
||||||
@@ -189,7 +190,9 @@ impl Media {
|
|||||||
original_prefix.extend_from_slice(&0_u32.to_be_bytes()); // Height = 0 if it's not a thumbnail
|
original_prefix.extend_from_slice(&0_u32.to_be_bytes()); // Height = 0 if it's not a thumbnail
|
||||||
original_prefix.push(0xff);
|
original_prefix.push(0xff);
|
||||||
|
|
||||||
if let Some((key, _)) = self.mediaid_file.scan_prefix(thumbnail_prefix).next() {
|
let first_thumbnailprefix = self.mediaid_file.scan_prefix(thumbnail_prefix).next();
|
||||||
|
let first_originalprefix = self.mediaid_file.scan_prefix(original_prefix).next();
|
||||||
|
if let Some((key, _)) = first_thumbnailprefix {
|
||||||
// Using saved thumbnail
|
// Using saved thumbnail
|
||||||
let path = globals.get_media_file(&key);
|
let path = globals.get_media_file(&key);
|
||||||
let mut file = Vec::new();
|
let mut file = Vec::new();
|
||||||
@@ -224,7 +227,7 @@ impl Media {
|
|||||||
content_type,
|
content_type,
|
||||||
file: file.to_vec(),
|
file: file.to_vec(),
|
||||||
}))
|
}))
|
||||||
} else if let Some((key, _)) = self.mediaid_file.scan_prefix(original_prefix).next() {
|
} else if let Some((key, _)) = first_originalprefix {
|
||||||
// Generate a thumbnail
|
// Generate a thumbnail
|
||||||
let path = globals.get_media_file(&key);
|
let path = globals.get_media_file(&key);
|
||||||
let mut file = Vec::new();
|
let mut file = Vec::new();
|
||||||
|
|||||||
+41
-20
@@ -1,6 +1,5 @@
|
|||||||
use crate::{Database, Error, PduEvent, Result};
|
use crate::{Database, Error, PduEvent, Result};
|
||||||
use bytes::BytesMut;
|
use bytes::BytesMut;
|
||||||
use log::{error, info, warn};
|
|
||||||
use ruma::{
|
use ruma::{
|
||||||
api::{
|
api::{
|
||||||
client::r0::push::{get_pushers, set_pusher, PusherKind},
|
client::r0::push::{get_pushers, set_pusher, PusherKind},
|
||||||
@@ -10,10 +9,13 @@ use ruma::{
|
|||||||
},
|
},
|
||||||
IncomingResponse, OutgoingRequest, SendAccessToken,
|
IncomingResponse, OutgoingRequest, SendAccessToken,
|
||||||
},
|
},
|
||||||
events::{room::power_levels::PowerLevelsEventContent, EventType},
|
events::{room::power_levels::PowerLevelsEventContent, AnySyncRoomEvent, EventType},
|
||||||
|
identifiers::RoomName,
|
||||||
push::{Action, PushConditionRoomCtx, PushFormat, Ruleset, Tweak},
|
push::{Action, PushConditionRoomCtx, PushFormat, Ruleset, Tweak},
|
||||||
uint, UInt, UserId,
|
serde::Raw,
|
||||||
|
uint, RoomId, UInt, UserId,
|
||||||
};
|
};
|
||||||
|
use tracing::{error, info, warn};
|
||||||
|
|
||||||
use std::{convert::TryFrom, fmt::Debug, mem, sync::Arc};
|
use std::{convert::TryFrom, fmt::Debug, mem, sync::Arc};
|
||||||
|
|
||||||
@@ -25,6 +27,7 @@ pub struct PushData {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl PushData {
|
impl PushData {
|
||||||
|
#[tracing::instrument(skip(self, sender, pusher))]
|
||||||
pub fn set_pusher(&self, sender: &UserId, pusher: set_pusher::Pusher) -> Result<()> {
|
pub fn set_pusher(&self, sender: &UserId, pusher: set_pusher::Pusher) -> Result<()> {
|
||||||
let mut key = sender.as_bytes().to_vec();
|
let mut key = sender.as_bytes().to_vec();
|
||||||
key.push(0xff);
|
key.push(0xff);
|
||||||
@@ -47,6 +50,7 @@ impl PushData {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, senderkey))]
|
||||||
pub fn get_pusher(&self, senderkey: &[u8]) -> Result<Option<get_pushers::Pusher>> {
|
pub fn get_pusher(&self, senderkey: &[u8]) -> Result<Option<get_pushers::Pusher>> {
|
||||||
self.senderkey_pusher
|
self.senderkey_pusher
|
||||||
.get(senderkey)?
|
.get(senderkey)?
|
||||||
@@ -57,6 +61,7 @@ impl PushData {
|
|||||||
.transpose()
|
.transpose()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, sender))]
|
||||||
pub fn get_pushers(&self, sender: &UserId) -> Result<Vec<get_pushers::Pusher>> {
|
pub fn get_pushers(&self, sender: &UserId) -> Result<Vec<get_pushers::Pusher>> {
|
||||||
let mut prefix = sender.as_bytes().to_vec();
|
let mut prefix = sender.as_bytes().to_vec();
|
||||||
prefix.push(0xff);
|
prefix.push(0xff);
|
||||||
@@ -70,6 +75,7 @@ impl PushData {
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, sender))]
|
||||||
pub fn get_pusher_senderkeys<'a>(
|
pub fn get_pusher_senderkeys<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
sender: &UserId,
|
sender: &UserId,
|
||||||
@@ -81,6 +87,7 @@ impl PushData {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(globals, destination, request))]
|
||||||
pub async fn send_request<T: OutgoingRequest>(
|
pub async fn send_request<T: OutgoingRequest>(
|
||||||
globals: &crate::database::globals::Globals,
|
globals: &crate::database::globals::Globals,
|
||||||
destination: &str,
|
destination: &str,
|
||||||
@@ -154,6 +161,7 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(user, unread, pusher, ruleset, pdu, db))]
|
||||||
pub async fn send_push_notice(
|
pub async fn send_push_notice(
|
||||||
user: &UserId,
|
user: &UserId,
|
||||||
unread: UInt,
|
unread: UInt,
|
||||||
@@ -165,7 +173,24 @@ pub async fn send_push_notice(
|
|||||||
let mut notify = None;
|
let mut notify = None;
|
||||||
let mut tweaks = Vec::new();
|
let mut tweaks = Vec::new();
|
||||||
|
|
||||||
for action in get_actions(user, &ruleset, pdu, db)? {
|
let power_levels: PowerLevelsEventContent = db
|
||||||
|
.rooms
|
||||||
|
.room_state_get(&pdu.room_id, &EventType::RoomPowerLevels, "")?
|
||||||
|
.map(|ev| {
|
||||||
|
serde_json::from_value(ev.content.clone())
|
||||||
|
.map_err(|_| Error::bad_database("invalid m.room.power_levels event"))
|
||||||
|
})
|
||||||
|
.transpose()?
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
for action in get_actions(
|
||||||
|
user,
|
||||||
|
&ruleset,
|
||||||
|
&power_levels,
|
||||||
|
&pdu.to_sync_room_event(),
|
||||||
|
&pdu.room_id,
|
||||||
|
db,
|
||||||
|
)? {
|
||||||
let n = match action {
|
let n = match action {
|
||||||
Action::DontNotify => false,
|
Action::DontNotify => false,
|
||||||
// TODO: Implement proper support for coalesce
|
// TODO: Implement proper support for coalesce
|
||||||
@@ -193,37 +218,31 @@ pub async fn send_push_notice(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(user, ruleset, pdu, db))]
|
||||||
pub fn get_actions<'a>(
|
pub fn get_actions<'a>(
|
||||||
user: &UserId,
|
user: &UserId,
|
||||||
ruleset: &'a Ruleset,
|
ruleset: &'a Ruleset,
|
||||||
pdu: &PduEvent,
|
power_levels: &PowerLevelsEventContent,
|
||||||
|
pdu: &Raw<AnySyncRoomEvent>,
|
||||||
|
room_id: &RoomId,
|
||||||
db: &Database,
|
db: &Database,
|
||||||
) -> Result<&'a [Action]> {
|
) -> Result<&'a [Action]> {
|
||||||
let power_levels: PowerLevelsEventContent = db
|
|
||||||
.rooms
|
|
||||||
.room_state_get(&pdu.room_id, &EventType::RoomPowerLevels, "")?
|
|
||||||
.map(|ev| {
|
|
||||||
serde_json::from_value(ev.content.clone())
|
|
||||||
.map_err(|_| Error::bad_database("invalid m.room.power_levels event"))
|
|
||||||
})
|
|
||||||
.transpose()?
|
|
||||||
.unwrap_or_default();
|
|
||||||
|
|
||||||
let ctx = PushConditionRoomCtx {
|
let ctx = PushConditionRoomCtx {
|
||||||
room_id: pdu.room_id.clone(),
|
room_id: room_id.clone(),
|
||||||
member_count: 10_u32.into(), // TODO: get member count efficiently
|
member_count: 10_u32.into(), // TODO: get member count efficiently
|
||||||
user_display_name: db
|
user_display_name: db
|
||||||
.users
|
.users
|
||||||
.displayname(&user)?
|
.displayname(&user)?
|
||||||
.unwrap_or_else(|| user.localpart().to_owned()),
|
.unwrap_or_else(|| user.localpart().to_owned()),
|
||||||
users_power_levels: power_levels.users,
|
users_power_levels: power_levels.users.clone(),
|
||||||
default_power_level: power_levels.users_default,
|
default_power_level: power_levels.users_default,
|
||||||
notification_power_levels: power_levels.notifications,
|
notification_power_levels: power_levels.notifications.clone(),
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(ruleset.get_actions(&pdu.to_sync_room_event(), &ctx))
|
Ok(ruleset.get_actions(pdu, &ctx))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(unread, pusher, tweaks, event, db))]
|
||||||
async fn send_notice(
|
async fn send_notice(
|
||||||
unread: UInt,
|
unread: UInt,
|
||||||
pusher: &get_pushers::Pusher,
|
pusher: &get_pushers::Pusher,
|
||||||
@@ -299,7 +318,9 @@ async fn send_notice(
|
|||||||
.rooms
|
.rooms
|
||||||
.room_state_get(&event.room_id, &EventType::RoomName, "")?
|
.room_state_get(&event.room_id, &EventType::RoomName, "")?
|
||||||
.map(|pdu| match pdu.content.get("name") {
|
.map(|pdu| match pdu.content.get("name") {
|
||||||
Some(serde_json::Value::String(s)) => Some(s.to_string()),
|
Some(serde_json::Value::String(s)) => {
|
||||||
|
Some(Box::<RoomName>::try_from(&**s).expect("room name is valid"))
|
||||||
|
}
|
||||||
_ => None,
|
_ => None,
|
||||||
})
|
})
|
||||||
.flatten();
|
.flatten();
|
||||||
|
|||||||
+384
-204
File diff suppressed because it is too large
Load Diff
@@ -116,6 +116,7 @@ impl RoomEdus {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Sets a private read marker at `count`.
|
/// Sets a private read marker at `count`.
|
||||||
|
#[tracing::instrument(skip(self, globals))]
|
||||||
pub fn private_read_set(
|
pub fn private_read_set(
|
||||||
&self,
|
&self,
|
||||||
room_id: &RoomId,
|
room_id: &RoomId,
|
||||||
@@ -421,7 +422,7 @@ impl RoomEdus {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Sets all users to offline who have been quiet for too long.
|
/// Sets all users to offline who have been quiet for too long.
|
||||||
pub fn presence_maintain(
|
fn presence_maintain(
|
||||||
&self,
|
&self,
|
||||||
rooms: &super::Rooms,
|
rooms: &super::Rooms,
|
||||||
globals: &super::super::globals::Globals,
|
globals: &super::super::globals::Globals,
|
||||||
@@ -496,7 +497,7 @@ impl RoomEdus {
|
|||||||
rooms: &super::Rooms,
|
rooms: &super::Rooms,
|
||||||
globals: &super::super::globals::Globals,
|
globals: &super::super::globals::Globals,
|
||||||
) -> Result<HashMap<UserId, PresenceEvent>> {
|
) -> Result<HashMap<UserId, PresenceEvent>> {
|
||||||
self.presence_maintain(rooms, globals)?;
|
//self.presence_maintain(rooms, globals)?;
|
||||||
|
|
||||||
let mut prefix = room_id.as_bytes().to_vec();
|
let mut prefix = room_id.as_bytes().to_vec();
|
||||||
prefix.push(0xff);
|
prefix.push(0xff);
|
||||||
|
|||||||
+94
-81
@@ -10,7 +10,6 @@ use crate::{
|
|||||||
appservice_server, database::pusher, server_server, utils, Database, Error, PduEvent, Result,
|
appservice_server, database::pusher, server_server, utils, Database, Error, PduEvent, Result,
|
||||||
};
|
};
|
||||||
use federation::transactions::send_transaction_message;
|
use federation::transactions::send_transaction_message;
|
||||||
use log::{error, warn};
|
|
||||||
use ring::digest;
|
use ring::digest;
|
||||||
use rocket::futures::{
|
use rocket::futures::{
|
||||||
channel::mpsc,
|
channel::mpsc,
|
||||||
@@ -34,6 +33,7 @@ use tokio::{
|
|||||||
select,
|
select,
|
||||||
sync::{RwLock, Semaphore},
|
sync::{RwLock, Semaphore},
|
||||||
};
|
};
|
||||||
|
use tracing::{error, warn};
|
||||||
|
|
||||||
use super::abstraction::Tree;
|
use super::abstraction::Tree;
|
||||||
|
|
||||||
@@ -45,6 +45,7 @@ pub enum OutgoingKind {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl OutgoingKind {
|
impl OutgoingKind {
|
||||||
|
#[tracing::instrument(skip(self))]
|
||||||
pub fn get_prefix(&self) -> Vec<u8> {
|
pub fn get_prefix(&self) -> Vec<u8> {
|
||||||
let mut prefix = match self {
|
let mut prefix = match self {
|
||||||
OutgoingKind::Appservice(server) => {
|
OutgoingKind::Appservice(server) => {
|
||||||
@@ -80,10 +81,10 @@ pub enum SendingEventType {
|
|||||||
pub struct Sending {
|
pub struct Sending {
|
||||||
/// The state for a given state hash.
|
/// The state for a given state hash.
|
||||||
pub(super) servername_educount: Arc<dyn Tree>, // EduCount: Count of last EDU sync
|
pub(super) servername_educount: Arc<dyn Tree>, // EduCount: Count of last EDU sync
|
||||||
pub(super) servernamepduids: Arc<dyn Tree>, // ServernamePduId = (+ / $)SenderKey / ServerName / UserId + PduId
|
pub(super) servernameevent_data: Arc<dyn Tree>, // ServernamEvent = (+ / $)SenderKey / ServerName / UserId + PduId / * (for edus), Data = EDU content
|
||||||
pub(super) servercurrentevents: Arc<dyn Tree>, // ServerCurrentEvents = (+ / $)ServerName / UserId + PduId / (*)EduEvent
|
pub(super) servercurrentevent_data: Arc<dyn Tree>, // ServerCurrentEvents = (+ / $)ServerName / UserId + PduId / * (for edus), Data = EDU content
|
||||||
pub(super) maximum_requests: Arc<Semaphore>,
|
pub(super) maximum_requests: Arc<Semaphore>,
|
||||||
pub sender: mpsc::UnboundedSender<Vec<u8>>,
|
pub sender: mpsc::UnboundedSender<(Vec<u8>, Vec<u8>)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
enum TransactionStatus {
|
enum TransactionStatus {
|
||||||
@@ -96,7 +97,7 @@ impl Sending {
|
|||||||
pub fn start_handler(
|
pub fn start_handler(
|
||||||
&self,
|
&self,
|
||||||
db: Arc<RwLock<Database>>,
|
db: Arc<RwLock<Database>>,
|
||||||
mut receiver: mpsc::UnboundedReceiver<Vec<u8>>,
|
mut receiver: mpsc::UnboundedReceiver<(Vec<u8>, Vec<u8>)>,
|
||||||
) {
|
) {
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let mut futures = FuturesUnordered::new();
|
let mut futures = FuturesUnordered::new();
|
||||||
@@ -108,16 +109,15 @@ impl Sending {
|
|||||||
|
|
||||||
let guard = db.read().await;
|
let guard = db.read().await;
|
||||||
|
|
||||||
for (key, outgoing_kind, event) in
|
for (key, outgoing_kind, event) in guard
|
||||||
guard
|
.sending
|
||||||
.sending
|
.servercurrentevent_data
|
||||||
.servercurrentevents
|
.iter()
|
||||||
.iter()
|
.filter_map(|(key, v)| {
|
||||||
.filter_map(|(key, _)| {
|
Self::parse_servercurrentevent(&key, v)
|
||||||
Self::parse_servercurrentevent(&key)
|
.ok()
|
||||||
.ok()
|
.map(|(k, e)| (key, k, e))
|
||||||
.map(|(k, e)| (key, k, e))
|
})
|
||||||
})
|
|
||||||
{
|
{
|
||||||
let entry = initial_transactions
|
let entry = initial_transactions
|
||||||
.entry(outgoing_kind.clone())
|
.entry(outgoing_kind.clone())
|
||||||
@@ -128,7 +128,7 @@ impl Sending {
|
|||||||
"Dropping some current events: {:?} {:?} {:?}",
|
"Dropping some current events: {:?} {:?} {:?}",
|
||||||
key, outgoing_kind, event
|
key, outgoing_kind, event
|
||||||
);
|
);
|
||||||
guard.sending.servercurrentevents.remove(&key).unwrap();
|
guard.sending.servercurrentevent_data.remove(&key).unwrap();
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -155,17 +155,17 @@ impl Sending {
|
|||||||
let guard = db.read().await;
|
let guard = db.read().await;
|
||||||
|
|
||||||
let prefix = outgoing_kind.get_prefix();
|
let prefix = outgoing_kind.get_prefix();
|
||||||
for (key, _) in guard.sending.servercurrentevents
|
for (key, _) in guard.sending.servercurrentevent_data
|
||||||
.scan_prefix(prefix.clone())
|
.scan_prefix(prefix.clone())
|
||||||
{
|
{
|
||||||
guard.sending.servercurrentevents.remove(&key).unwrap();
|
guard.sending.servercurrentevent_data.remove(&key).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find events that have been added since starting the last request
|
// Find events that have been added since starting the last request
|
||||||
let new_events = guard.sending.servernamepduids
|
let new_events = guard.sending.servernameevent_data
|
||||||
.scan_prefix(prefix.clone())
|
.scan_prefix(prefix.clone())
|
||||||
.map(|(k, _)| {
|
.filter_map(|(k, v)| {
|
||||||
SendingEventType::Pdu(k[prefix.len()..].to_vec())
|
Self::parse_servercurrentevent(&k, v).ok().map(|ev| (ev, k))
|
||||||
})
|
})
|
||||||
.take(30)
|
.take(30)
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
@@ -174,16 +174,10 @@ impl Sending {
|
|||||||
|
|
||||||
if !new_events.is_empty() {
|
if !new_events.is_empty() {
|
||||||
// Insert pdus we found
|
// Insert pdus we found
|
||||||
for event in &new_events {
|
for (e, key) in &new_events {
|
||||||
let mut current_key = prefix.clone();
|
let value = if let SendingEventType::Edu(value) = &e.1 { &**value } else { &[] };
|
||||||
match event {
|
guard.sending.servercurrentevent_data.insert(&key, value).unwrap();
|
||||||
SendingEventType::Pdu(b) |
|
guard.sending.servernameevent_data.remove(&key).unwrap();
|
||||||
SendingEventType::Edu(b) => {
|
|
||||||
current_key.extend_from_slice(&b);
|
|
||||||
guard.sending.servercurrentevents.insert(¤t_key, &[]).unwrap();
|
|
||||||
guard.sending.servernamepduids.remove(¤t_key).unwrap();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
drop(guard);
|
drop(guard);
|
||||||
@@ -191,7 +185,7 @@ impl Sending {
|
|||||||
futures.push(
|
futures.push(
|
||||||
Self::handle_events(
|
Self::handle_events(
|
||||||
outgoing_kind.clone(),
|
outgoing_kind.clone(),
|
||||||
new_events,
|
new_events.into_iter().map(|(event, _)| event.1).collect(),
|
||||||
Arc::clone(&db),
|
Arc::clone(&db),
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
@@ -211,8 +205,8 @@ impl Sending {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
Some(key) = receiver.next() => {
|
Some((key, value)) = receiver.next() => {
|
||||||
if let Ok((outgoing_kind, event)) = Self::parse_servercurrentevent(&key) {
|
if let Ok((outgoing_kind, event)) = Self::parse_servercurrentevent(&key, value) {
|
||||||
let guard = db.read().await;
|
let guard = db.read().await;
|
||||||
|
|
||||||
if let Ok(Some(events)) = Self::select_events(
|
if let Ok(Some(events)) = Self::select_events(
|
||||||
@@ -230,6 +224,7 @@ impl Sending {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(outgoing_kind, new_events, current_transaction_status, db))]
|
||||||
fn select_events(
|
fn select_events(
|
||||||
outgoing_kind: &OutgoingKind,
|
outgoing_kind: &OutgoingKind,
|
||||||
new_events: Vec<(SendingEventType, Vec<u8>)>, // Events we want to send: event and full key
|
new_events: Vec<(SendingEventType, Vec<u8>)>, // Events we want to send: event and full key
|
||||||
@@ -272,25 +267,33 @@ impl Sending {
|
|||||||
|
|
||||||
if retry {
|
if retry {
|
||||||
// We retry the previous transaction
|
// We retry the previous transaction
|
||||||
for (key, _) in db.sending.servercurrentevents.scan_prefix(prefix) {
|
for (key, value) in db.sending.servercurrentevent_data.scan_prefix(prefix) {
|
||||||
if let Ok((_, e)) = Self::parse_servercurrentevent(&key) {
|
if let Ok((_, e)) = Self::parse_servercurrentevent(&key, value) {
|
||||||
events.push(e);
|
events.push(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
for (e, full_key) in new_events {
|
for (e, full_key) in new_events {
|
||||||
db.sending.servercurrentevents.insert(&full_key, &[])?;
|
let value = if let SendingEventType::Edu(value) = &e {
|
||||||
|
&**value
|
||||||
|
} else {
|
||||||
|
&[][..]
|
||||||
|
};
|
||||||
|
db.sending
|
||||||
|
.servercurrentevent_data
|
||||||
|
.insert(&full_key, value)?;
|
||||||
|
|
||||||
// If it was a PDU we have to unqueue it
|
// If it was a PDU we have to unqueue it
|
||||||
// TODO: don't try to unqueue EDUs
|
// TODO: don't try to unqueue EDUs
|
||||||
db.sending.servernamepduids.remove(&full_key)?;
|
db.sending.servernameevent_data.remove(&full_key)?;
|
||||||
|
|
||||||
events.push(e);
|
events.push(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
if let OutgoingKind::Normal(server_name) = outgoing_kind {
|
if let OutgoingKind::Normal(server_name) = outgoing_kind {
|
||||||
if let Ok((select_edus, last_count)) = Self::select_edus(db, server_name) {
|
if let Ok((select_edus, last_count)) = Self::select_edus(db, server_name) {
|
||||||
events.extend_from_slice(&select_edus);
|
events.extend(select_edus.into_iter().map(SendingEventType::Edu));
|
||||||
|
|
||||||
db.sending
|
db.sending
|
||||||
.servername_educount
|
.servername_educount
|
||||||
.insert(server_name.as_bytes(), &last_count.to_be_bytes())?;
|
.insert(server_name.as_bytes(), &last_count.to_be_bytes())?;
|
||||||
@@ -301,7 +304,8 @@ impl Sending {
|
|||||||
Ok(Some(events))
|
Ok(Some(events))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn select_edus(db: &Database, server: &ServerName) -> Result<(Vec<SendingEventType>, u64)> {
|
#[tracing::instrument(skip(db, server))]
|
||||||
|
pub fn select_edus(db: &Database, server: &ServerName) -> Result<(Vec<Vec<u8>>, u64)> {
|
||||||
// u64: count of last edu
|
// u64: count of last edu
|
||||||
let since = db
|
let since = db
|
||||||
.sending
|
.sending
|
||||||
@@ -366,9 +370,7 @@ impl Sending {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
events.push(SendingEventType::Edu(
|
events.push(serde_json::to_vec(&federation_event).expect("json can be serialized"));
|
||||||
serde_json::to_vec(&federation_event).expect("json can be serialized"),
|
|
||||||
));
|
|
||||||
|
|
||||||
if events.len() >= 20 {
|
if events.len() >= 20 {
|
||||||
break 'outer;
|
break 'outer;
|
||||||
@@ -379,25 +381,36 @@ impl Sending {
|
|||||||
Ok((events, max_edu_count))
|
Ok((events, max_edu_count))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip(self))]
|
#[tracing::instrument(skip(self, pdu_id, senderkey))]
|
||||||
pub fn send_push_pdu(&self, pdu_id: &[u8], senderkey: Vec<u8>) -> Result<()> {
|
pub fn send_push_pdu(&self, pdu_id: &[u8], senderkey: Vec<u8>) -> Result<()> {
|
||||||
let mut key = b"$".to_vec();
|
let mut key = b"$".to_vec();
|
||||||
key.extend_from_slice(&senderkey);
|
key.extend_from_slice(&senderkey);
|
||||||
key.push(0xff);
|
key.push(0xff);
|
||||||
key.extend_from_slice(pdu_id);
|
key.extend_from_slice(pdu_id);
|
||||||
self.servernamepduids.insert(&key, b"")?;
|
self.servernameevent_data.insert(&key, &[])?;
|
||||||
self.sender.unbounded_send(key).unwrap();
|
self.sender.unbounded_send((key, vec![])).unwrap();
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip(self))]
|
#[tracing::instrument(skip(self, server, pdu_id))]
|
||||||
pub fn send_pdu(&self, server: &ServerName, pdu_id: &[u8]) -> Result<()> {
|
pub fn send_pdu(&self, server: &ServerName, pdu_id: &[u8]) -> Result<()> {
|
||||||
let mut key = server.as_bytes().to_vec();
|
let mut key = server.as_bytes().to_vec();
|
||||||
key.push(0xff);
|
key.push(0xff);
|
||||||
key.extend_from_slice(pdu_id);
|
key.extend_from_slice(pdu_id);
|
||||||
self.servernamepduids.insert(&key, b"")?;
|
self.servernameevent_data.insert(&key, &[])?;
|
||||||
self.sender.unbounded_send(key).unwrap();
|
self.sender.unbounded_send((key, vec![])).unwrap();
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, server, serialized))]
|
||||||
|
pub fn send_reliable_edu(&self, server: &ServerName, serialized: Vec<u8>) -> Result<()> {
|
||||||
|
let mut key = server.as_bytes().to_vec();
|
||||||
|
key.push(0xff);
|
||||||
|
key.push(b'*');
|
||||||
|
self.servernameevent_data.insert(&key, &serialized)?;
|
||||||
|
self.sender.unbounded_send((key, serialized)).unwrap();
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -408,13 +421,13 @@ impl Sending {
|
|||||||
key.extend_from_slice(appservice_id.as_bytes());
|
key.extend_from_slice(appservice_id.as_bytes());
|
||||||
key.push(0xff);
|
key.push(0xff);
|
||||||
key.extend_from_slice(pdu_id);
|
key.extend_from_slice(pdu_id);
|
||||||
self.servernamepduids.insert(&key, b"")?;
|
self.servernameevent_data.insert(&key, &[])?;
|
||||||
self.sender.unbounded_send(key).unwrap();
|
self.sender.unbounded_send((key, vec![])).unwrap();
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument]
|
#[tracing::instrument(skip(keys))]
|
||||||
fn calculate_hash(keys: &[&[u8]]) -> Vec<u8> {
|
fn calculate_hash(keys: &[&[u8]]) -> Vec<u8> {
|
||||||
// We only hash the pdu's event ids, not the whole pdu
|
// We only hash the pdu's event ids, not the whole pdu
|
||||||
let bytes = keys.join(&0xff);
|
let bytes = keys.join(&0xff);
|
||||||
@@ -422,7 +435,7 @@ impl Sending {
|
|||||||
hash.as_ref().to_owned()
|
hash.as_ref().to_owned()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip(db))]
|
#[tracing::instrument(skip(db, events, kind))]
|
||||||
async fn handle_events(
|
async fn handle_events(
|
||||||
kind: OutgoingKind,
|
kind: OutgoingKind,
|
||||||
events: Vec<SendingEventType>,
|
events: Vec<SendingEventType>,
|
||||||
@@ -444,7 +457,7 @@ impl Sending {
|
|||||||
(
|
(
|
||||||
kind.clone(),
|
kind.clone(),
|
||||||
Error::bad_database(
|
Error::bad_database(
|
||||||
"[Appservice] Event in servernamepduids not found in db.",
|
"[Appservice] Event in servernameevent_data not found in db.",
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
})?
|
})?
|
||||||
@@ -501,7 +514,7 @@ impl Sending {
|
|||||||
(
|
(
|
||||||
kind.clone(),
|
kind.clone(),
|
||||||
Error::bad_database(
|
Error::bad_database(
|
||||||
"[Push] Event in servernamepduids not found in db.",
|
"[Push] Event in servernamevent_datas not found in db.",
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
})?,
|
})?,
|
||||||
@@ -586,29 +599,25 @@ impl Sending {
|
|||||||
match event {
|
match event {
|
||||||
SendingEventType::Pdu(pdu_id) => {
|
SendingEventType::Pdu(pdu_id) => {
|
||||||
// TODO: check room version and remove event_id if needed
|
// TODO: check room version and remove event_id if needed
|
||||||
pdu_jsons.push(serde_json::from_str(
|
let raw = PduEvent::convert_to_outgoing_federation_event(
|
||||||
PduEvent::convert_to_outgoing_federation_event(
|
db.rooms
|
||||||
db.rooms
|
.get_pdu_json_from_id(&pdu_id)
|
||||||
.get_pdu_json_from_id(&pdu_id)
|
.map_err(|e| (OutgoingKind::Normal(server.clone()), e))?
|
||||||
.map_err(|e| (OutgoingKind::Normal(server.clone()), e))?
|
.ok_or_else(|| {
|
||||||
.ok_or_else(|| {
|
(
|
||||||
(
|
OutgoingKind::Normal(server.clone()),
|
||||||
OutgoingKind::Normal(server.clone()),
|
Error::bad_database(
|
||||||
Error::bad_database(
|
"[Normal] Event in servernamevent_datas not found in db.",
|
||||||
"[Normal] Event in servernamepduids not found in db.",
|
),
|
||||||
),
|
)
|
||||||
)
|
})?,
|
||||||
})?,
|
);
|
||||||
)
|
pdu_jsons.push(raw);
|
||||||
.json()
|
|
||||||
.get(),
|
|
||||||
)
|
|
||||||
.expect("Raw<..> is always valid"));
|
|
||||||
}
|
}
|
||||||
SendingEventType::Edu(edu) => {
|
SendingEventType::Edu(edu) => {
|
||||||
edu_jsons.push(
|
if let Ok(raw) = serde_json::from_slice(edu) {
|
||||||
serde_json::from_slice(edu).expect("Raw<..> is always valid"),
|
edu_jsons.push(raw);
|
||||||
);
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -654,7 +663,11 @@ impl Sending {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_servercurrentevent(key: &[u8]) -> Result<(OutgoingKind, SendingEventType)> {
|
#[tracing::instrument(skip(key))]
|
||||||
|
fn parse_servercurrentevent(
|
||||||
|
key: &[u8],
|
||||||
|
value: Vec<u8>,
|
||||||
|
) -> Result<(OutgoingKind, SendingEventType)> {
|
||||||
// Appservices start with a plus
|
// Appservices start with a plus
|
||||||
Ok::<_, Error>(if key.starts_with(b"+") {
|
Ok::<_, Error>(if key.starts_with(b"+") {
|
||||||
let mut parts = key[1..].splitn(2, |&b| b == 0xff);
|
let mut parts = key[1..].splitn(2, |&b| b == 0xff);
|
||||||
@@ -672,7 +685,7 @@ impl Sending {
|
|||||||
Error::bad_database("Invalid server string in server_currenttransaction")
|
Error::bad_database("Invalid server string in server_currenttransaction")
|
||||||
})?),
|
})?),
|
||||||
if event.starts_with(b"*") {
|
if event.starts_with(b"*") {
|
||||||
SendingEventType::Edu(event[1..].to_vec())
|
SendingEventType::Edu(value)
|
||||||
} else {
|
} else {
|
||||||
SendingEventType::Pdu(event.to_vec())
|
SendingEventType::Pdu(event.to_vec())
|
||||||
},
|
},
|
||||||
@@ -690,7 +703,7 @@ impl Sending {
|
|||||||
(
|
(
|
||||||
OutgoingKind::Push(user.to_vec(), pushkey.to_vec()),
|
OutgoingKind::Push(user.to_vec(), pushkey.to_vec()),
|
||||||
if event.starts_with(b"*") {
|
if event.starts_with(b"*") {
|
||||||
SendingEventType::Edu(event[1..].to_vec())
|
SendingEventType::Edu(value)
|
||||||
} else {
|
} else {
|
||||||
SendingEventType::Pdu(event.to_vec())
|
SendingEventType::Pdu(event.to_vec())
|
||||||
},
|
},
|
||||||
@@ -719,7 +732,7 @@ impl Sending {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip(self, globals))]
|
#[tracing::instrument(skip(self, globals, destination, request))]
|
||||||
pub async fn send_federation_request<T: OutgoingRequest>(
|
pub async fn send_federation_request<T: OutgoingRequest>(
|
||||||
&self,
|
&self,
|
||||||
globals: &crate::database::globals::Globals,
|
globals: &crate::database::globals::Globals,
|
||||||
@@ -736,7 +749,7 @@ impl Sending {
|
|||||||
response
|
response
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip(self, globals))]
|
#[tracing::instrument(skip(self, globals, registration, request))]
|
||||||
pub async fn send_appservice_request<T: OutgoingRequest>(
|
pub async fn send_appservice_request<T: OutgoingRequest>(
|
||||||
&self,
|
&self,
|
||||||
globals: &crate::database::globals::Globals,
|
globals: &crate::database::globals::Globals,
|
||||||
|
|||||||
+105
-7
@@ -8,6 +8,7 @@ use ruma::{
|
|||||||
DeviceId, DeviceKeyAlgorithm, DeviceKeyId, MilliSecondsSinceUnixEpoch, UInt, UserId,
|
DeviceId, DeviceKeyAlgorithm, DeviceKeyId, MilliSecondsSinceUnixEpoch, UInt, UserId,
|
||||||
};
|
};
|
||||||
use std::{collections::BTreeMap, convert::TryFrom, mem, sync::Arc};
|
use std::{collections::BTreeMap, convert::TryFrom, mem, sync::Arc};
|
||||||
|
use tracing::warn;
|
||||||
|
|
||||||
use super::abstraction::Tree;
|
use super::abstraction::Tree;
|
||||||
|
|
||||||
@@ -15,6 +16,7 @@ pub struct Users {
|
|||||||
pub(super) userid_password: Arc<dyn Tree>,
|
pub(super) userid_password: Arc<dyn Tree>,
|
||||||
pub(super) userid_displayname: Arc<dyn Tree>,
|
pub(super) userid_displayname: Arc<dyn Tree>,
|
||||||
pub(super) userid_avatarurl: Arc<dyn Tree>,
|
pub(super) userid_avatarurl: Arc<dyn Tree>,
|
||||||
|
pub(super) userid_blurhash: Arc<dyn Tree>,
|
||||||
pub(super) userdeviceid_token: Arc<dyn Tree>,
|
pub(super) userdeviceid_token: Arc<dyn Tree>,
|
||||||
pub(super) userdeviceid_metadata: Arc<dyn Tree>, // This is also used to check if a device exists
|
pub(super) userdeviceid_metadata: Arc<dyn Tree>, // This is also used to check if a device exists
|
||||||
pub(super) userid_devicelistversion: Arc<dyn Tree>, // DevicelistVersion = u64
|
pub(super) userid_devicelistversion: Arc<dyn Tree>, // DevicelistVersion = u64
|
||||||
@@ -33,11 +35,13 @@ pub struct Users {
|
|||||||
|
|
||||||
impl Users {
|
impl Users {
|
||||||
/// Check if a user has an account on this homeserver.
|
/// Check if a user has an account on this homeserver.
|
||||||
|
#[tracing::instrument(skip(self, user_id))]
|
||||||
pub fn exists(&self, user_id: &UserId) -> Result<bool> {
|
pub fn exists(&self, user_id: &UserId) -> Result<bool> {
|
||||||
Ok(self.userid_password.get(user_id.as_bytes())?.is_some())
|
Ok(self.userid_password.get(user_id.as_bytes())?.is_some())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Check if account is deactivated
|
/// Check if account is deactivated
|
||||||
|
#[tracing::instrument(skip(self, user_id))]
|
||||||
pub fn is_deactivated(&self, user_id: &UserId) -> Result<bool> {
|
pub fn is_deactivated(&self, user_id: &UserId) -> Result<bool> {
|
||||||
Ok(self
|
Ok(self
|
||||||
.userid_password
|
.userid_password
|
||||||
@@ -50,17 +54,20 @@ impl Users {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Create a new user account on this homeserver.
|
/// Create a new user account on this homeserver.
|
||||||
|
#[tracing::instrument(skip(self, user_id, password))]
|
||||||
pub fn create(&self, user_id: &UserId, password: Option<&str>) -> Result<()> {
|
pub fn create(&self, user_id: &UserId, password: Option<&str>) -> Result<()> {
|
||||||
self.set_password(user_id, password)?;
|
self.set_password(user_id, password)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the number of users registered on this server.
|
/// Returns the number of users registered on this server.
|
||||||
|
#[tracing::instrument(skip(self))]
|
||||||
pub fn count(&self) -> Result<usize> {
|
pub fn count(&self) -> Result<usize> {
|
||||||
Ok(self.userid_password.iter().count())
|
Ok(self.userid_password.iter().count())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Find out which user an access token belongs to.
|
/// Find out which user an access token belongs to.
|
||||||
|
#[tracing::instrument(skip(self, token))]
|
||||||
pub fn find_from_token(&self, token: &str) -> Result<Option<(UserId, String)>> {
|
pub fn find_from_token(&self, token: &str) -> Result<Option<(UserId, String)>> {
|
||||||
self.token_userdeviceid
|
self.token_userdeviceid
|
||||||
.get(token.as_bytes())?
|
.get(token.as_bytes())?
|
||||||
@@ -88,6 +95,7 @@ impl Users {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Returns an iterator over all users on this homeserver.
|
/// Returns an iterator over all users on this homeserver.
|
||||||
|
#[tracing::instrument(skip(self))]
|
||||||
pub fn iter(&self) -> impl Iterator<Item = Result<UserId>> + '_ {
|
pub fn iter(&self) -> impl Iterator<Item = Result<UserId>> + '_ {
|
||||||
self.userid_password.iter().map(|(bytes, _)| {
|
self.userid_password.iter().map(|(bytes, _)| {
|
||||||
UserId::try_from(utils::string_from_bytes(&bytes).map_err(|_| {
|
UserId::try_from(utils::string_from_bytes(&bytes).map_err(|_| {
|
||||||
@@ -98,6 +106,7 @@ impl Users {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the password hash for the given user.
|
/// Returns the password hash for the given user.
|
||||||
|
#[tracing::instrument(skip(self, user_id))]
|
||||||
pub fn password_hash(&self, user_id: &UserId) -> Result<Option<String>> {
|
pub fn password_hash(&self, user_id: &UserId) -> Result<Option<String>> {
|
||||||
self.userid_password
|
self.userid_password
|
||||||
.get(user_id.as_bytes())?
|
.get(user_id.as_bytes())?
|
||||||
@@ -109,6 +118,7 @@ impl Users {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Hash and set the user's password to the Argon2 hash
|
/// Hash and set the user's password to the Argon2 hash
|
||||||
|
#[tracing::instrument(skip(self, user_id, password))]
|
||||||
pub fn set_password(&self, user_id: &UserId, password: Option<&str>) -> Result<()> {
|
pub fn set_password(&self, user_id: &UserId, password: Option<&str>) -> Result<()> {
|
||||||
if let Some(password) = password {
|
if let Some(password) = password {
|
||||||
if let Ok(hash) = utils::calculate_hash(&password) {
|
if let Ok(hash) = utils::calculate_hash(&password) {
|
||||||
@@ -128,6 +138,7 @@ impl Users {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the displayname of a user on this homeserver.
|
/// Returns the displayname of a user on this homeserver.
|
||||||
|
#[tracing::instrument(skip(self, user_id))]
|
||||||
pub fn displayname(&self, user_id: &UserId) -> Result<Option<String>> {
|
pub fn displayname(&self, user_id: &UserId) -> Result<Option<String>> {
|
||||||
self.userid_displayname
|
self.userid_displayname
|
||||||
.get(user_id.as_bytes())?
|
.get(user_id.as_bytes())?
|
||||||
@@ -139,6 +150,7 @@ impl Users {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Sets a new displayname or removes it if displayname is None. You still need to nofify all rooms of this change.
|
/// Sets a new displayname or removes it if displayname is None. You still need to nofify all rooms of this change.
|
||||||
|
#[tracing::instrument(skip(self, user_id, displayname))]
|
||||||
pub fn set_displayname(&self, user_id: &UserId, displayname: Option<String>) -> Result<()> {
|
pub fn set_displayname(&self, user_id: &UserId, displayname: Option<String>) -> Result<()> {
|
||||||
if let Some(displayname) = displayname {
|
if let Some(displayname) = displayname {
|
||||||
self.userid_displayname
|
self.userid_displayname
|
||||||
@@ -150,7 +162,8 @@ impl Users {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get a the avatar_url of a user.
|
/// Get the avatar_url of a user.
|
||||||
|
#[tracing::instrument(skip(self, user_id))]
|
||||||
pub fn avatar_url(&self, user_id: &UserId) -> Result<Option<MxcUri>> {
|
pub fn avatar_url(&self, user_id: &UserId) -> Result<Option<MxcUri>> {
|
||||||
self.userid_avatarurl
|
self.userid_avatarurl
|
||||||
.get(user_id.as_bytes())?
|
.get(user_id.as_bytes())?
|
||||||
@@ -163,6 +176,7 @@ impl Users {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Sets a new avatar_url or removes it if avatar_url is None.
|
/// Sets a new avatar_url or removes it if avatar_url is None.
|
||||||
|
#[tracing::instrument(skip(self, user_id, avatar_url))]
|
||||||
pub fn set_avatar_url(&self, user_id: &UserId, avatar_url: Option<MxcUri>) -> Result<()> {
|
pub fn set_avatar_url(&self, user_id: &UserId, avatar_url: Option<MxcUri>) -> Result<()> {
|
||||||
if let Some(avatar_url) = avatar_url {
|
if let Some(avatar_url) = avatar_url {
|
||||||
self.userid_avatarurl
|
self.userid_avatarurl
|
||||||
@@ -174,7 +188,35 @@ impl Users {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get the blurhash of a user.
|
||||||
|
#[tracing::instrument(skip(self, user_id))]
|
||||||
|
pub fn blurhash(&self, user_id: &UserId) -> Result<Option<String>> {
|
||||||
|
self.userid_blurhash
|
||||||
|
.get(user_id.as_bytes())?
|
||||||
|
.map(|bytes| {
|
||||||
|
let s = utils::string_from_bytes(&bytes)
|
||||||
|
.map_err(|_| Error::bad_database("Avatar URL in db is invalid."))?;
|
||||||
|
|
||||||
|
Ok(s)
|
||||||
|
})
|
||||||
|
.transpose()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets a new avatar_url or removes it if avatar_url is None.
|
||||||
|
#[tracing::instrument(skip(self, user_id, blurhash))]
|
||||||
|
pub fn set_blurhash(&self, user_id: &UserId, blurhash: Option<String>) -> Result<()> {
|
||||||
|
if let Some(blurhash) = blurhash {
|
||||||
|
self.userid_blurhash
|
||||||
|
.insert(user_id.as_bytes(), blurhash.as_bytes())?;
|
||||||
|
} else {
|
||||||
|
self.userid_blurhash.remove(user_id.as_bytes())?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Adds a new device to a user.
|
/// Adds a new device to a user.
|
||||||
|
#[tracing::instrument(skip(self, user_id, device_id, token, initial_device_display_name))]
|
||||||
pub fn create_device(
|
pub fn create_device(
|
||||||
&self,
|
&self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
@@ -209,6 +251,7 @@ impl Users {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Removes a device from a user.
|
/// Removes a device from a user.
|
||||||
|
#[tracing::instrument(skip(self, user_id, device_id))]
|
||||||
pub fn remove_device(&self, user_id: &UserId, device_id: &DeviceId) -> Result<()> {
|
pub fn remove_device(&self, user_id: &UserId, device_id: &DeviceId) -> Result<()> {
|
||||||
let mut userdeviceid = user_id.as_bytes().to_vec();
|
let mut userdeviceid = user_id.as_bytes().to_vec();
|
||||||
userdeviceid.push(0xff);
|
userdeviceid.push(0xff);
|
||||||
@@ -239,6 +282,7 @@ impl Users {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Returns an iterator over all device ids of this user.
|
/// Returns an iterator over all device ids of this user.
|
||||||
|
#[tracing::instrument(skip(self, user_id))]
|
||||||
pub fn all_device_ids<'a>(
|
pub fn all_device_ids<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
@@ -261,6 +305,7 @@ impl Users {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Replaces the access token of one device.
|
/// Replaces the access token of one device.
|
||||||
|
#[tracing::instrument(skip(self, user_id, device_id, token))]
|
||||||
pub fn set_token(&self, user_id: &UserId, device_id: &DeviceId, token: &str) -> Result<()> {
|
pub fn set_token(&self, user_id: &UserId, device_id: &DeviceId, token: &str) -> Result<()> {
|
||||||
let mut userdeviceid = user_id.as_bytes().to_vec();
|
let mut userdeviceid = user_id.as_bytes().to_vec();
|
||||||
userdeviceid.push(0xff);
|
userdeviceid.push(0xff);
|
||||||
@@ -284,6 +329,14 @@ impl Users {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(
|
||||||
|
self,
|
||||||
|
user_id,
|
||||||
|
device_id,
|
||||||
|
one_time_key_key,
|
||||||
|
one_time_key_value,
|
||||||
|
globals
|
||||||
|
))]
|
||||||
pub fn add_one_time_key(
|
pub fn add_one_time_key(
|
||||||
&self,
|
&self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
@@ -320,7 +373,7 @@ impl Users {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip(self))]
|
#[tracing::instrument(skip(self, user_id))]
|
||||||
pub fn last_one_time_keys_update(&self, user_id: &UserId) -> Result<u64> {
|
pub fn last_one_time_keys_update(&self, user_id: &UserId) -> Result<u64> {
|
||||||
self.userid_lastonetimekeyupdate
|
self.userid_lastonetimekeyupdate
|
||||||
.get(&user_id.as_bytes())?
|
.get(&user_id.as_bytes())?
|
||||||
@@ -332,6 +385,7 @@ impl Users {
|
|||||||
.unwrap_or(Ok(0))
|
.unwrap_or(Ok(0))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, user_id, device_id, key_algorithm, globals))]
|
||||||
pub fn take_one_time_key(
|
pub fn take_one_time_key(
|
||||||
&self,
|
&self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
@@ -371,7 +425,7 @@ impl Users {
|
|||||||
.transpose()
|
.transpose()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip(self))]
|
#[tracing::instrument(skip(self, user_id, device_id))]
|
||||||
pub fn count_one_time_keys(
|
pub fn count_one_time_keys(
|
||||||
&self,
|
&self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
@@ -404,6 +458,7 @@ impl Users {
|
|||||||
Ok(counts)
|
Ok(counts)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, user_id, device_id, device_keys, rooms, globals))]
|
||||||
pub fn add_device_keys(
|
pub fn add_device_keys(
|
||||||
&self,
|
&self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
@@ -426,6 +481,14 @@ impl Users {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(
|
||||||
|
self,
|
||||||
|
master_key,
|
||||||
|
self_signing_key,
|
||||||
|
user_signing_key,
|
||||||
|
rooms,
|
||||||
|
globals
|
||||||
|
))]
|
||||||
pub fn add_cross_signing_keys(
|
pub fn add_cross_signing_keys(
|
||||||
&self,
|
&self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
@@ -526,6 +589,7 @@ impl Users {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, target_id, key_id, signature, sender_id, rooms, globals))]
|
||||||
pub fn sign_key(
|
pub fn sign_key(
|
||||||
&self,
|
&self,
|
||||||
target_id: &UserId,
|
target_id: &UserId,
|
||||||
@@ -569,7 +633,7 @@ impl Users {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip(self))]
|
#[tracing::instrument(skip(self, user_or_room_id, from, to))]
|
||||||
pub fn keys_changed<'a>(
|
pub fn keys_changed<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
user_or_room_id: &str,
|
user_or_room_id: &str,
|
||||||
@@ -582,9 +646,24 @@ impl Users {
|
|||||||
let mut start = prefix.clone();
|
let mut start = prefix.clone();
|
||||||
start.extend_from_slice(&(from + 1).to_be_bytes());
|
start.extend_from_slice(&(from + 1).to_be_bytes());
|
||||||
|
|
||||||
|
let to = to.unwrap_or(u64::MAX);
|
||||||
|
|
||||||
self.keychangeid_userid
|
self.keychangeid_userid
|
||||||
.iter_from(&start, false)
|
.iter_from(&start, false)
|
||||||
.take_while(move |(k, _)| k.starts_with(&prefix))
|
.take_while(move |(k, _)| {
|
||||||
|
k.starts_with(&prefix)
|
||||||
|
&& if let Some(current) = k.splitn(2, |&b| b == 0xff).nth(1) {
|
||||||
|
if let Ok(c) = utils::u64_from_bytes(current) {
|
||||||
|
c <= to
|
||||||
|
} else {
|
||||||
|
warn!("BadDatabase: Could not parse keychangeid_userid bytes");
|
||||||
|
false
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
warn!("BadDatabase: Could not parse keychangeid_userid");
|
||||||
|
false
|
||||||
|
}
|
||||||
|
})
|
||||||
.map(|(_, bytes)| {
|
.map(|(_, bytes)| {
|
||||||
UserId::try_from(utils::string_from_bytes(&bytes).map_err(|_| {
|
UserId::try_from(utils::string_from_bytes(&bytes).map_err(|_| {
|
||||||
Error::bad_database("User ID in devicekeychangeid_userid is invalid unicode.")
|
Error::bad_database("User ID in devicekeychangeid_userid is invalid unicode.")
|
||||||
@@ -593,6 +672,7 @@ impl Users {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, user_id, rooms, globals))]
|
||||||
fn mark_device_key_update(
|
fn mark_device_key_update(
|
||||||
&self,
|
&self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
@@ -624,6 +704,7 @@ impl Users {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, user_id, device_id))]
|
||||||
pub fn get_device_keys(
|
pub fn get_device_keys(
|
||||||
&self,
|
&self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
@@ -640,6 +721,7 @@ impl Users {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, user_id, allowed_signatures))]
|
||||||
pub fn get_master_key<F: Fn(&UserId) -> bool>(
|
pub fn get_master_key<F: Fn(&UserId) -> bool>(
|
||||||
&self,
|
&self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
@@ -667,6 +749,7 @@ impl Users {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, user_id, allowed_signatures))]
|
||||||
pub fn get_self_signing_key<F: Fn(&UserId) -> bool>(
|
pub fn get_self_signing_key<F: Fn(&UserId) -> bool>(
|
||||||
&self,
|
&self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
@@ -694,6 +777,7 @@ impl Users {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, user_id))]
|
||||||
pub fn get_user_signing_key(&self, user_id: &UserId) -> Result<Option<CrossSigningKey>> {
|
pub fn get_user_signing_key(&self, user_id: &UserId) -> Result<Option<CrossSigningKey>> {
|
||||||
self.userid_usersigningkeyid
|
self.userid_usersigningkeyid
|
||||||
.get(user_id.as_bytes())?
|
.get(user_id.as_bytes())?
|
||||||
@@ -706,6 +790,15 @@ impl Users {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(
|
||||||
|
self,
|
||||||
|
sender,
|
||||||
|
target_user_id,
|
||||||
|
target_device_id,
|
||||||
|
event_type,
|
||||||
|
content,
|
||||||
|
globals
|
||||||
|
))]
|
||||||
pub fn add_to_device_event(
|
pub fn add_to_device_event(
|
||||||
&self,
|
&self,
|
||||||
sender: &UserId,
|
sender: &UserId,
|
||||||
@@ -733,7 +826,7 @@ impl Users {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip(self))]
|
#[tracing::instrument(skip(self, user_id, device_id))]
|
||||||
pub fn get_to_device_events(
|
pub fn get_to_device_events(
|
||||||
&self,
|
&self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
@@ -756,7 +849,7 @@ impl Users {
|
|||||||
Ok(events)
|
Ok(events)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip(self))]
|
#[tracing::instrument(skip(self, user_id, device_id, until))]
|
||||||
pub fn remove_to_device_events(
|
pub fn remove_to_device_events(
|
||||||
&self,
|
&self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
@@ -791,6 +884,7 @@ impl Users {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, user_id, device_id, device))]
|
||||||
pub fn update_device_metadata(
|
pub fn update_device_metadata(
|
||||||
&self,
|
&self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
@@ -816,6 +910,7 @@ impl Users {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Get device metadata.
|
/// Get device metadata.
|
||||||
|
#[tracing::instrument(skip(self, user_id, device_id))]
|
||||||
pub fn get_device_metadata(
|
pub fn get_device_metadata(
|
||||||
&self,
|
&self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
@@ -834,6 +929,7 @@ impl Users {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, user_id))]
|
||||||
pub fn get_devicelist_version(&self, user_id: &UserId) -> Result<Option<u64>> {
|
pub fn get_devicelist_version(&self, user_id: &UserId) -> Result<Option<u64>> {
|
||||||
self.userid_devicelistversion
|
self.userid_devicelistversion
|
||||||
.get(user_id.as_bytes())?
|
.get(user_id.as_bytes())?
|
||||||
@@ -844,6 +940,7 @@ impl Users {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(self, user_id))]
|
||||||
pub fn all_devices_metadata<'a>(
|
pub fn all_devices_metadata<'a>(
|
||||||
&'a self,
|
&'a self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
@@ -860,6 +957,7 @@ impl Users {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Deactivate account
|
/// Deactivate account
|
||||||
|
#[tracing::instrument(skip(self, user_id))]
|
||||||
pub fn deactivate_account(&self, user_id: &UserId) -> Result<()> {
|
pub fn deactivate_account(&self, user_id: &UserId) -> Result<()> {
|
||||||
// Remove all associated devices
|
// Remove all associated devices
|
||||||
for device_id in self.all_device_ids(user_id) {
|
for device_id in self.all_device_ids(user_id) {
|
||||||
|
|||||||
+5
-7
@@ -1,4 +1,3 @@
|
|||||||
use log::{error, warn};
|
|
||||||
use ruma::{
|
use ruma::{
|
||||||
api::client::{
|
api::client::{
|
||||||
error::{Error as RumaError, ErrorKind},
|
error::{Error as RumaError, ErrorKind},
|
||||||
@@ -7,6 +6,7 @@ use ruma::{
|
|||||||
ServerName,
|
ServerName,
|
||||||
};
|
};
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
use tracing::warn;
|
||||||
|
|
||||||
#[cfg(feature = "conduit_bin")]
|
#[cfg(feature = "conduit_bin")]
|
||||||
use {
|
use {
|
||||||
@@ -17,6 +17,7 @@ use {
|
|||||||
Request,
|
Request,
|
||||||
},
|
},
|
||||||
ruma::api::client::r0::uiaa::UiaaResponse,
|
ruma::api::client::r0::uiaa::UiaaResponse,
|
||||||
|
tracing::error,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub type Result<T> = std::result::Result<T, Error>;
|
pub type Result<T> = std::result::Result<T, Error>;
|
||||||
@@ -29,18 +30,15 @@ pub enum Error {
|
|||||||
#[from]
|
#[from]
|
||||||
source: sled::Error,
|
source: sled::Error,
|
||||||
},
|
},
|
||||||
#[cfg(feature = "rocksdb")]
|
|
||||||
#[error("There was a problem with the connection to the rocksdb database: {source}")]
|
|
||||||
RocksDbError {
|
|
||||||
#[from]
|
|
||||||
source: rocksdb::Error,
|
|
||||||
},
|
|
||||||
#[cfg(feature = "sqlite")]
|
#[cfg(feature = "sqlite")]
|
||||||
#[error("There was a problem with the connection to the sqlite database: {source}")]
|
#[error("There was a problem with the connection to the sqlite database: {source}")]
|
||||||
SqliteError {
|
SqliteError {
|
||||||
#[from]
|
#[from]
|
||||||
source: rusqlite::Error,
|
source: rusqlite::Error,
|
||||||
},
|
},
|
||||||
|
#[cfg(feature = "heed")]
|
||||||
|
#[error("There was a problem with the connection to the heed database: {error}")]
|
||||||
|
HeedError { error: String },
|
||||||
#[error("Could not generate an image.")]
|
#[error("Could not generate an image.")]
|
||||||
ImageError {
|
ImageError {
|
||||||
#[from]
|
#[from]
|
||||||
|
|||||||
+2
-2
@@ -10,10 +10,10 @@ mod ruma_wrapper;
|
|||||||
pub mod server_server;
|
pub mod server_server;
|
||||||
mod utils;
|
mod utils;
|
||||||
|
|
||||||
pub use database::Database;
|
pub use database::{Config, Database};
|
||||||
pub use error::{Error, Result};
|
pub use error::{Error, Result};
|
||||||
pub use pdu::PduEvent;
|
pub use pdu::PduEvent;
|
||||||
pub use rocket::Config;
|
pub use rocket::Config as RocketConfig;
|
||||||
pub use ruma_wrapper::{ConduitResult, Ruma, RumaResponse};
|
pub use ruma_wrapper::{ConduitResult, Ruma, RumaResponse};
|
||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
|
|
||||||
|
|||||||
+75
-21
@@ -17,6 +17,7 @@ use std::sync::Arc;
|
|||||||
use database::Config;
|
use database::Config;
|
||||||
pub use database::Database;
|
pub use database::Database;
|
||||||
pub use error::{Error, Result};
|
pub use error::{Error, Result};
|
||||||
|
use opentelemetry::trace::Tracer;
|
||||||
pub use pdu::PduEvent;
|
pub use pdu::PduEvent;
|
||||||
pub use rocket::State;
|
pub use rocket::State;
|
||||||
use ruma::api::client::error::ErrorKind;
|
use ruma::api::client::error::ErrorKind;
|
||||||
@@ -31,8 +32,7 @@ use rocket::{
|
|||||||
routes, Request,
|
routes, Request,
|
||||||
};
|
};
|
||||||
use tokio::sync::RwLock;
|
use tokio::sync::RwLock;
|
||||||
use tracing::span;
|
use tracing_subscriber::{prelude::*, EnvFilter};
|
||||||
use tracing_subscriber::{prelude::*, Registry};
|
|
||||||
|
|
||||||
fn setup_rocket(config: Figment, data: Arc<RwLock<Database>>) -> rocket::Rocket<rocket::Build> {
|
fn setup_rocket(config: Figment, data: Arc<RwLock<Database>>) -> rocket::Rocket<rocket::Build> {
|
||||||
rocket::custom(config)
|
rocket::custom(config)
|
||||||
@@ -50,6 +50,7 @@ fn setup_rocket(config: Figment, data: Arc<RwLock<Database>>) -> rocket::Rocket<
|
|||||||
client_server::logout_all_route,
|
client_server::logout_all_route,
|
||||||
client_server::change_password_route,
|
client_server::change_password_route,
|
||||||
client_server::deactivate_route,
|
client_server::deactivate_route,
|
||||||
|
client_server::third_party_route,
|
||||||
client_server::get_capabilities_route,
|
client_server::get_capabilities_route,
|
||||||
client_server::get_pushrules_all_route,
|
client_server::get_pushrules_all_route,
|
||||||
client_server::set_pushrule_route,
|
client_server::set_pushrule_route,
|
||||||
@@ -60,6 +61,7 @@ fn setup_rocket(config: Figment, data: Arc<RwLock<Database>>) -> rocket::Rocket<
|
|||||||
client_server::set_pushrule_actions_route,
|
client_server::set_pushrule_actions_route,
|
||||||
client_server::delete_pushrule_route,
|
client_server::delete_pushrule_route,
|
||||||
client_server::get_room_event_route,
|
client_server::get_room_event_route,
|
||||||
|
client_server::get_room_aliases_route,
|
||||||
client_server::get_filter_route,
|
client_server::get_filter_route,
|
||||||
client_server::create_filter_route,
|
client_server::create_filter_route,
|
||||||
client_server::set_global_account_data_route,
|
client_server::set_global_account_data_route,
|
||||||
@@ -185,7 +187,7 @@ async fn main() {
|
|||||||
std::env::set_var("CONDUIT_LOG_LEVEL", "off");
|
std::env::set_var("CONDUIT_LOG_LEVEL", "off");
|
||||||
|
|
||||||
let raw_config =
|
let raw_config =
|
||||||
Figment::from(rocket::Config::release_default())
|
Figment::from(default_config())
|
||||||
.merge(
|
.merge(
|
||||||
Toml::file(Env::var("CONDUIT_CONFIG").expect(
|
Toml::file(Env::var("CONDUIT_CONFIG").expect(
|
||||||
"The CONDUIT_CONFIG env var needs to be set. Example: /etc/conduit.toml",
|
"The CONDUIT_CONFIG env var needs to be set. Example: /etc/conduit.toml",
|
||||||
@@ -200,32 +202,57 @@ async fn main() {
|
|||||||
.extract::<Config>()
|
.extract::<Config>()
|
||||||
.expect("It looks like your config is invalid. Please take a look at the error");
|
.expect("It looks like your config is invalid. Please take a look at the error");
|
||||||
|
|
||||||
let mut _span: Option<span::Span> = None;
|
let start = async {
|
||||||
let mut _enter: Option<span::Entered<'_>> = None;
|
config.warn_deprecated();
|
||||||
|
|
||||||
|
let db = Database::load_or_create(&config)
|
||||||
|
.await
|
||||||
|
.expect("config is valid");
|
||||||
|
|
||||||
|
let rocket = setup_rocket(raw_config, Arc::clone(&db))
|
||||||
|
.ignite()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
Database::start_on_shutdown_tasks(db, rocket.shutdown()).await;
|
||||||
|
|
||||||
|
rocket.launch().await.unwrap();
|
||||||
|
};
|
||||||
|
|
||||||
if config.allow_jaeger {
|
if config.allow_jaeger {
|
||||||
let (tracer, _uninstall) = opentelemetry_jaeger::new_pipeline()
|
let tracer = opentelemetry_jaeger::new_pipeline()
|
||||||
.with_service_name("conduit")
|
.with_service_name("conduit")
|
||||||
.install()
|
.install_simple()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let telemetry = tracing_opentelemetry::layer().with_tracer(tracer);
|
|
||||||
Registry::default().with(telemetry).try_init().unwrap();
|
|
||||||
|
|
||||||
_span = Some(span!(tracing::Level::INFO, "app_start", work_units = 2));
|
let span = tracer.start("conduit");
|
||||||
_enter = Some(_span.as_ref().unwrap().enter());
|
start.await;
|
||||||
|
drop(span);
|
||||||
} else {
|
} else {
|
||||||
std::env::set_var("RUST_LOG", &config.log);
|
std::env::set_var("RUST_LOG", &config.log);
|
||||||
tracing_subscriber::fmt::init();
|
|
||||||
|
let registry = tracing_subscriber::Registry::default();
|
||||||
|
if config.tracing_flame {
|
||||||
|
let (flame_layer, _guard) =
|
||||||
|
tracing_flame::FlameLayer::with_file("./tracing.folded").unwrap();
|
||||||
|
let flame_layer = flame_layer.with_empty_samples(false);
|
||||||
|
|
||||||
|
let filter_layer = EnvFilter::new("trace,h2=off");
|
||||||
|
|
||||||
|
let subscriber = registry.with(filter_layer).with(flame_layer);
|
||||||
|
tracing::subscriber::set_global_default(subscriber).unwrap();
|
||||||
|
start.await;
|
||||||
|
} else {
|
||||||
|
let fmt_layer = tracing_subscriber::fmt::Layer::new();
|
||||||
|
let filter_layer = EnvFilter::try_from_default_env()
|
||||||
|
.or_else(|_| EnvFilter::try_new("info"))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let subscriber = registry.with(filter_layer).with(fmt_layer);
|
||||||
|
tracing::subscriber::set_global_default(subscriber).unwrap();
|
||||||
|
start.await;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
config.warn_deprecated();
|
|
||||||
|
|
||||||
let db = Database::load_or_create(config)
|
|
||||||
.await
|
|
||||||
.expect("config is valid");
|
|
||||||
|
|
||||||
let rocket = setup_rocket(raw_config, db);
|
|
||||||
rocket.launch().await.unwrap();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[catch(404)]
|
#[catch(404)]
|
||||||
@@ -255,3 +282,30 @@ fn missing_token_catcher() -> Result<()> {
|
|||||||
fn bad_json_catcher() -> Result<()> {
|
fn bad_json_catcher() -> Result<()> {
|
||||||
Err(Error::BadRequest(ErrorKind::BadJson, "Bad json."))
|
Err(Error::BadRequest(ErrorKind::BadJson, "Bad json."))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn default_config() -> rocket::Config {
|
||||||
|
let mut config = rocket::Config::release_default();
|
||||||
|
|
||||||
|
{
|
||||||
|
let mut shutdown = &mut config.shutdown;
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use rocket::config::Sig;
|
||||||
|
|
||||||
|
shutdown.signals.insert(Sig::Term);
|
||||||
|
shutdown.signals.insert(Sig::Int);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Once shutdown is triggered, this is the amount of seconds before rocket
|
||||||
|
// will forcefully start shutting down connections, this gives enough time to /sync
|
||||||
|
// requests and the like (which havent gotten the memo, somehow) to still complete gracefully.
|
||||||
|
shutdown.grace = 35;
|
||||||
|
|
||||||
|
// After the grace period, rocket starts shutting down connections, and waits at least this
|
||||||
|
// many seconds before forcefully shutting all of them down.
|
||||||
|
shutdown.mercy = 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
config
|
||||||
|
}
|
||||||
|
|||||||
+19
-4
@@ -1,10 +1,9 @@
|
|||||||
use crate::Error;
|
use crate::Error;
|
||||||
use log::error;
|
|
||||||
use ruma::{
|
use ruma::{
|
||||||
events::{
|
events::{
|
||||||
pdu::EventHash, room::member::MemberEventContent, AnyEphemeralRoomEvent, AnyRoomEvent,
|
pdu::EventHash, room::member::MemberEventContent, AnyEphemeralRoomEvent,
|
||||||
AnyStateEvent, AnyStrippedStateEvent, AnySyncRoomEvent, AnySyncStateEvent, EventType,
|
AnyInitialStateEvent, AnyRoomEvent, AnyStateEvent, AnyStrippedStateEvent, AnySyncRoomEvent,
|
||||||
StateEvent,
|
AnySyncStateEvent, EventType, StateEvent,
|
||||||
},
|
},
|
||||||
serde::{CanonicalJsonObject, CanonicalJsonValue, Raw},
|
serde::{CanonicalJsonObject, CanonicalJsonValue, Raw},
|
||||||
state_res, EventId, MilliSecondsSinceUnixEpoch, RoomId, RoomVersionId, ServerName,
|
state_res, EventId, MilliSecondsSinceUnixEpoch, RoomId, RoomVersionId, ServerName,
|
||||||
@@ -13,6 +12,7 @@ use ruma::{
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use std::{cmp::Ordering, collections::BTreeMap, convert::TryFrom};
|
use std::{cmp::Ordering, collections::BTreeMap, convert::TryFrom};
|
||||||
|
use tracing::error;
|
||||||
|
|
||||||
#[derive(Clone, Deserialize, Serialize, Debug)]
|
#[derive(Clone, Deserialize, Serialize, Debug)]
|
||||||
pub struct PduEvent {
|
pub struct PduEvent {
|
||||||
@@ -328,6 +328,7 @@ pub(crate) fn gen_event_id_canonical_json(
|
|||||||
|
|
||||||
let event_id = EventId::try_from(&*format!(
|
let event_id = EventId::try_from(&*format!(
|
||||||
"${}",
|
"${}",
|
||||||
|
// Anything higher than version3 behaves the same
|
||||||
ruma::signatures::reference_hash(&value, &RoomVersionId::Version6)
|
ruma::signatures::reference_hash(&value, &RoomVersionId::Version6)
|
||||||
.expect("ruma can calculate reference hashes")
|
.expect("ruma can calculate reference hashes")
|
||||||
))
|
))
|
||||||
@@ -346,3 +347,17 @@ pub struct PduBuilder {
|
|||||||
pub state_key: Option<String>,
|
pub state_key: Option<String>,
|
||||||
pub redacts: Option<EventId>,
|
pub redacts: Option<EventId>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Direct conversion prevents loss of the empty `state_key` that ruma requires.
|
||||||
|
impl From<AnyInitialStateEvent> for PduBuilder {
|
||||||
|
fn from(event: AnyInitialStateEvent) -> Self {
|
||||||
|
Self {
|
||||||
|
event_type: EventType::from(event.event_type()),
|
||||||
|
content: serde_json::value::to_value(event.content())
|
||||||
|
.expect("AnyStateEventContent came from JSON and can thus turn back into JSON."),
|
||||||
|
unsigned: None,
|
||||||
|
state_key: Some(event.state_key().to_owned()),
|
||||||
|
redacts: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+24
-17
@@ -10,7 +10,6 @@ use std::ops::Deref;
|
|||||||
#[cfg(feature = "conduit_bin")]
|
#[cfg(feature = "conduit_bin")]
|
||||||
use {
|
use {
|
||||||
crate::server_server,
|
crate::server_server,
|
||||||
log::{debug, warn},
|
|
||||||
rocket::{
|
rocket::{
|
||||||
data::{self, ByteUnit, Data, FromData},
|
data::{self, ByteUnit, Data, FromData},
|
||||||
http::Status,
|
http::Status,
|
||||||
@@ -23,6 +22,7 @@ use {
|
|||||||
std::collections::BTreeMap,
|
std::collections::BTreeMap,
|
||||||
std::convert::TryFrom,
|
std::convert::TryFrom,
|
||||||
std::io::Cursor,
|
std::io::Cursor,
|
||||||
|
tracing::{debug, warn},
|
||||||
};
|
};
|
||||||
|
|
||||||
/// This struct converts rocket requests into ruma structs by converting them into http requests
|
/// This struct converts rocket requests into ruma structs by converting them into http requests
|
||||||
@@ -45,7 +45,11 @@ where
|
|||||||
{
|
{
|
||||||
type Error = ();
|
type Error = ();
|
||||||
|
|
||||||
async fn from_data(request: &'a Request<'_>, data: Data) -> data::Outcome<Self, Self::Error> {
|
#[tracing::instrument(skip(request, data))]
|
||||||
|
async fn from_data(
|
||||||
|
request: &'a Request<'_>,
|
||||||
|
data: Data<'a>,
|
||||||
|
) -> data::Outcome<'a, Self, Self::Error> {
|
||||||
let metadata = T::Incoming::METADATA;
|
let metadata = T::Incoming::METADATA;
|
||||||
let db = request
|
let db = request
|
||||||
.guard::<DatabaseGuard>()
|
.guard::<DatabaseGuard>()
|
||||||
@@ -71,9 +75,9 @@ where
|
|||||||
registration,
|
registration,
|
||||||
)) = db
|
)) = db
|
||||||
.appservice
|
.appservice
|
||||||
.iter_all()
|
.all()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.filter_map(|r| r.ok())
|
.iter()
|
||||||
.find(|(_id, registration)| {
|
.find(|(_id, registration)| {
|
||||||
registration
|
registration
|
||||||
.get("as_token")
|
.get("as_token")
|
||||||
@@ -102,7 +106,7 @@ where
|
|||||||
|
|
||||||
if !db.users.exists(&user_id).unwrap() {
|
if !db.users.exists(&user_id).unwrap() {
|
||||||
// Forbidden
|
// Forbidden
|
||||||
return Failure((Status::raw(580), ()));
|
return Failure((Status::new(580), ()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Check if appservice is allowed to be that user
|
// TODO: Check if appservice is allowed to be that user
|
||||||
@@ -117,7 +121,7 @@ where
|
|||||||
if let Some(token) = token {
|
if let Some(token) = token {
|
||||||
match db.users.find_from_token(&token).unwrap() {
|
match db.users.find_from_token(&token).unwrap() {
|
||||||
// Unknown Token
|
// Unknown Token
|
||||||
None => return Failure((Status::raw(581), ())),
|
None => return Failure((Status::new(581), ())),
|
||||||
Some((user_id, device_id)) => (
|
Some((user_id, device_id)) => (
|
||||||
Some(user_id),
|
Some(user_id),
|
||||||
Some(Box::<DeviceId>::from(device_id)),
|
Some(Box::<DeviceId>::from(device_id)),
|
||||||
@@ -127,7 +131,7 @@ where
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Missing Token
|
// Missing Token
|
||||||
return Failure((Status::raw(582), ()));
|
return Failure((Status::new(582), ()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
AuthScheme::ServerSignatures => {
|
AuthScheme::ServerSignatures => {
|
||||||
@@ -149,7 +153,7 @@ where
|
|||||||
warn!("No Authorization header");
|
warn!("No Authorization header");
|
||||||
|
|
||||||
// Forbidden
|
// Forbidden
|
||||||
return Failure((Status::raw(580), ()));
|
return Failure((Status::new(580), ()));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -159,7 +163,7 @@ where
|
|||||||
warn!("Invalid X-Matrix header origin field: {:?}", x_matrix);
|
warn!("Invalid X-Matrix header origin field: {:?}", x_matrix);
|
||||||
|
|
||||||
// Forbidden
|
// Forbidden
|
||||||
return Failure((Status::raw(580), ()));
|
return Failure((Status::new(580), ()));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -172,7 +176,7 @@ where
|
|||||||
);
|
);
|
||||||
|
|
||||||
// Forbidden
|
// Forbidden
|
||||||
return Failure((Status::raw(580), ()));
|
return Failure((Status::new(580), ()));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -182,7 +186,7 @@ where
|
|||||||
warn!("Invalid X-Matrix header key field: {:?}", x_matrix);
|
warn!("Invalid X-Matrix header key field: {:?}", x_matrix);
|
||||||
|
|
||||||
// Forbidden
|
// Forbidden
|
||||||
return Failure((Status::raw(580), ()));
|
return Failure((Status::new(580), ()));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -192,7 +196,7 @@ where
|
|||||||
warn!("Invalid X-Matrix header sig field: {:?}", x_matrix);
|
warn!("Invalid X-Matrix header sig field: {:?}", x_matrix);
|
||||||
|
|
||||||
// Forbidden
|
// Forbidden
|
||||||
return Failure((Status::raw(580), ()));
|
return Failure((Status::new(580), ()));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -243,7 +247,7 @@ where
|
|||||||
warn!("Failed to fetch signing keys: {}", e);
|
warn!("Failed to fetch signing keys: {}", e);
|
||||||
|
|
||||||
// Forbidden
|
// Forbidden
|
||||||
return Failure((Status::raw(580), ()));
|
return Failure((Status::new(580), ()));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -253,14 +257,17 @@ where
|
|||||||
match ruma::signatures::verify_json(&pub_key_map, &request_map) {
|
match ruma::signatures::verify_json(&pub_key_map, &request_map) {
|
||||||
Ok(()) => (None, None, Some(origin), false),
|
Ok(()) => (None, None, Some(origin), false),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
warn!("Failed to verify json request from {}: {}", origin, e);
|
warn!(
|
||||||
|
"Failed to verify json request from {}: {}\n{:?}",
|
||||||
|
origin, e, request_map
|
||||||
|
);
|
||||||
|
|
||||||
if request.uri().to_string().contains('@') {
|
if request.uri().to_string().contains('@') {
|
||||||
warn!("Request uri contained '@' character. Make sure your reverse proxy gives Conduit the raw uri (apache: use nocanon)");
|
warn!("Request uri contained '@' character. Make sure your reverse proxy gives Conduit the raw uri (apache: use nocanon)");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Forbidden
|
// Forbidden
|
||||||
return Failure((Status::raw(580), ()));
|
return Failure((Status::new(580), ()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -318,7 +325,7 @@ where
|
|||||||
Err(e) => {
|
Err(e) => {
|
||||||
warn!("{:?}", e);
|
warn!("{:?}", e);
|
||||||
// Bad Json
|
// Bad Json
|
||||||
Failure((Status::raw(583), ()))
|
Failure((Status::new(583), ()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -344,7 +351,7 @@ pub fn response<T: OutgoingResponse>(response: RumaResponse<T>) -> response::Res
|
|||||||
let mut response = rocket::response::Response::build();
|
let mut response = rocket::response::Response::build();
|
||||||
|
|
||||||
let status = http_response.status();
|
let status = http_response.status();
|
||||||
response.raw_status(status.into(), "");
|
response.status(Status::new(status.as_u16()));
|
||||||
|
|
||||||
for header in http_response.headers() {
|
for header in http_response.headers() {
|
||||||
response.raw_header(header.0.to_string(), header.1.to_str().unwrap().to_owned());
|
response.raw_header(header.0.to_string(), header.1.to_str().unwrap().to_owned());
|
||||||
|
|||||||
+348
-283
File diff suppressed because it is too large
Load Diff
+9
-10
@@ -9,6 +9,7 @@ use std::{
|
|||||||
time::{SystemTime, UNIX_EPOCH},
|
time::{SystemTime, UNIX_EPOCH},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
#[tracing::instrument]
|
||||||
pub fn millis_since_unix_epoch() -> u64 {
|
pub fn millis_since_unix_epoch() -> u64 {
|
||||||
SystemTime::now()
|
SystemTime::now()
|
||||||
.duration_since(UNIX_EPOCH)
|
.duration_since(UNIX_EPOCH)
|
||||||
@@ -16,15 +17,6 @@ pub fn millis_since_unix_epoch() -> u64 {
|
|||||||
.as_millis() as u64
|
.as_millis() as u64
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "rocksdb")]
|
|
||||||
pub fn increment_rocksdb(
|
|
||||||
_new_key: &[u8],
|
|
||||||
old: Option<&[u8]>,
|
|
||||||
_operands: &mut rocksdb::MergeOperands,
|
|
||||||
) -> Option<Vec<u8>> {
|
|
||||||
increment(old)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn increment(old: Option<&[u8]>) -> Option<Vec<u8>> {
|
pub fn increment(old: Option<&[u8]>) -> Option<Vec<u8>> {
|
||||||
let number = match old.map(|bytes| bytes.try_into()) {
|
let number = match old.map(|bytes| bytes.try_into()) {
|
||||||
Some(Ok(bytes)) => {
|
Some(Ok(bytes)) => {
|
||||||
@@ -48,16 +40,19 @@ pub fn generate_keypair() -> Vec<u8> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Parses the bytes into an u64.
|
/// Parses the bytes into an u64.
|
||||||
|
#[tracing::instrument(skip(bytes))]
|
||||||
pub fn u64_from_bytes(bytes: &[u8]) -> Result<u64, std::array::TryFromSliceError> {
|
pub fn u64_from_bytes(bytes: &[u8]) -> Result<u64, std::array::TryFromSliceError> {
|
||||||
let array: [u8; 8] = bytes.try_into()?;
|
let array: [u8; 8] = bytes.try_into()?;
|
||||||
Ok(u64::from_be_bytes(array))
|
Ok(u64::from_be_bytes(array))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parses the bytes into a string.
|
/// Parses the bytes into a string.
|
||||||
|
#[tracing::instrument(skip(bytes))]
|
||||||
pub fn string_from_bytes(bytes: &[u8]) -> Result<String, std::string::FromUtf8Error> {
|
pub fn string_from_bytes(bytes: &[u8]) -> Result<String, std::string::FromUtf8Error> {
|
||||||
String::from_utf8(bytes.to_vec())
|
String::from_utf8(bytes.to_vec())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(length))]
|
||||||
pub fn random_string(length: usize) -> String {
|
pub fn random_string(length: usize) -> String {
|
||||||
thread_rng()
|
thread_rng()
|
||||||
.sample_iter(&rand::distributions::Alphanumeric)
|
.sample_iter(&rand::distributions::Alphanumeric)
|
||||||
@@ -67,6 +62,7 @@ pub fn random_string(length: usize) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Calculate a new hash for the given password
|
/// Calculate a new hash for the given password
|
||||||
|
#[tracing::instrument(skip(password))]
|
||||||
pub fn calculate_hash(password: &str) -> Result<String, argon2::Error> {
|
pub fn calculate_hash(password: &str) -> Result<String, argon2::Error> {
|
||||||
let hashing_config = Config {
|
let hashing_config = Config {
|
||||||
variant: Variant::Argon2id,
|
variant: Variant::Argon2id,
|
||||||
@@ -77,6 +73,7 @@ pub fn calculate_hash(password: &str) -> Result<String, argon2::Error> {
|
|||||||
argon2::hash_encoded(password.as_bytes(), salt.as_bytes(), &hashing_config)
|
argon2::hash_encoded(password.as_bytes(), salt.as_bytes(), &hashing_config)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(iterators, check_order))]
|
||||||
pub fn common_elements(
|
pub fn common_elements(
|
||||||
mut iterators: impl Iterator<Item = impl Iterator<Item = Vec<u8>>>,
|
mut iterators: impl Iterator<Item = impl Iterator<Item = Vec<u8>>>,
|
||||||
check_order: impl Fn(&[u8], &[u8]) -> Ordering,
|
check_order: impl Fn(&[u8], &[u8]) -> Ordering,
|
||||||
@@ -104,6 +101,7 @@ pub fn common_elements(
|
|||||||
/// Fallible conversion from any value that implements `Serialize` to a `CanonicalJsonObject`.
|
/// Fallible conversion from any value that implements `Serialize` to a `CanonicalJsonObject`.
|
||||||
///
|
///
|
||||||
/// `value` must serialize to an `serde_json::Value::Object`.
|
/// `value` must serialize to an `serde_json::Value::Object`.
|
||||||
|
#[tracing::instrument(skip(value))]
|
||||||
pub fn to_canonical_object<T: serde::Serialize>(
|
pub fn to_canonical_object<T: serde::Serialize>(
|
||||||
value: T,
|
value: T,
|
||||||
) -> Result<CanonicalJsonObject, CanonicalJsonError> {
|
) -> Result<CanonicalJsonObject, CanonicalJsonError> {
|
||||||
@@ -117,6 +115,7 @@ pub fn to_canonical_object<T: serde::Serialize>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(deserializer))]
|
||||||
pub fn deserialize_from_str<
|
pub fn deserialize_from_str<
|
||||||
'de,
|
'de,
|
||||||
D: serde::de::Deserializer<'de>,
|
D: serde::de::Deserializer<'de>,
|
||||||
@@ -137,7 +136,7 @@ pub fn deserialize_from_str<
|
|||||||
where
|
where
|
||||||
E: serde::de::Error,
|
E: serde::de::Error,
|
||||||
{
|
{
|
||||||
v.parse().map_err(|e| serde::de::Error::custom(e))
|
v.parse().map_err(serde::de::Error::custom)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
deserializer.deserialize_str(Visitor(std::marker::PhantomData))
|
deserializer.deserialize_str(Visitor(std::marker::PhantomData))
|
||||||
|
|||||||
@@ -0,0 +1,101 @@
|
|||||||
|
const puppeteer = require('puppeteer');
|
||||||
|
|
||||||
|
run().then(() => console.log('Done')).catch(error => {
|
||||||
|
console.error("Registration test failed.");
|
||||||
|
console.error("There might be a screenshot of the failure in the artifacts.\n");
|
||||||
|
console.error(error);
|
||||||
|
process.exit(111);
|
||||||
|
});
|
||||||
|
|
||||||
|
async function run() {
|
||||||
|
|
||||||
|
const elementUrl = process.argv[process.argv.length - 2];
|
||||||
|
console.debug("Testing registration with ElementWeb hosted at "+ elementUrl);
|
||||||
|
|
||||||
|
const homeserverUrl = process.argv[process.argv.length - 1];
|
||||||
|
console.debug("Homeserver url: "+ homeserverUrl);
|
||||||
|
|
||||||
|
const username = "testuser" + String(Math.floor(Math.random() * 100000));
|
||||||
|
const password = "testpassword" + String(Math.floor(Math.random() * 100000));
|
||||||
|
console.debug("Testuser for this run:\n User: " + username + "\n Password: " + password);
|
||||||
|
|
||||||
|
const browser = await puppeteer.launch({
|
||||||
|
headless: true, args: [
|
||||||
|
"--no-sandbox"
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
const page = await browser.newPage();
|
||||||
|
await page.goto(elementUrl);
|
||||||
|
|
||||||
|
await page.screenshot({ path: '01-element-web-opened.png' });
|
||||||
|
|
||||||
|
console.debug("Click [Create Account] button");
|
||||||
|
await page.waitForSelector('a.mx_ButtonCreateAccount');
|
||||||
|
await page.click('a.mx_ButtonCreateAccount');
|
||||||
|
|
||||||
|
await page.screenshot({ path: '02-clicked-create-account-button.png' });
|
||||||
|
|
||||||
|
// The webapp should have loaded right now, if anything takes more than 5 seconds, something probably broke
|
||||||
|
page.setDefaultTimeout(5000);
|
||||||
|
|
||||||
|
console.debug("Click [Edit] to switch homeserver");
|
||||||
|
await page.waitForSelector('div.mx_ServerPicker_change');
|
||||||
|
await page.click('div.mx_ServerPicker_change');
|
||||||
|
|
||||||
|
await page.screenshot({ path: '03-clicked-edit-homeserver-button.png' });
|
||||||
|
|
||||||
|
console.debug("Type in local homeserver url");
|
||||||
|
await page.waitForSelector('input#mx_homeserverInput');
|
||||||
|
await page.click('input#mx_homeserverInput');
|
||||||
|
await page.click('input#mx_homeserverInput');
|
||||||
|
await page.keyboard.type(homeserverUrl);
|
||||||
|
|
||||||
|
await page.screenshot({ path: '04-typed-in-homeserver.png' });
|
||||||
|
|
||||||
|
console.debug("[Continue] with changed homeserver");
|
||||||
|
await page.waitForSelector("div.mx_ServerPickerDialog_continue");
|
||||||
|
await page.click('div.mx_ServerPickerDialog_continue');
|
||||||
|
|
||||||
|
await page.screenshot({ path: '05-back-to-enter-user-credentials.png' });
|
||||||
|
|
||||||
|
console.debug("Type in username");
|
||||||
|
await page.waitForSelector("input#mx_RegistrationForm_username");
|
||||||
|
await page.click('input#mx_RegistrationForm_username');
|
||||||
|
await page.keyboard.type(username);
|
||||||
|
|
||||||
|
await page.screenshot({ path: '06-typed-in-username.png' });
|
||||||
|
|
||||||
|
console.debug("Type in password");
|
||||||
|
await page.waitForSelector("input#mx_RegistrationForm_password");
|
||||||
|
await page.click('input#mx_RegistrationForm_password');
|
||||||
|
await page.keyboard.type(password);
|
||||||
|
|
||||||
|
await page.screenshot({ path: '07-typed-in-password-once.png' });
|
||||||
|
|
||||||
|
console.debug("Type in password again");
|
||||||
|
await page.waitForSelector("input#mx_RegistrationForm_passwordConfirm");
|
||||||
|
await page.click('input#mx_RegistrationForm_passwordConfirm');
|
||||||
|
await page.keyboard.type(password);
|
||||||
|
|
||||||
|
await page.screenshot({ path: '08-typed-in-password-twice.png' });
|
||||||
|
|
||||||
|
console.debug("Click on [Register] to finish the account creation");
|
||||||
|
await page.waitForSelector("input.mx_Login_submit");
|
||||||
|
await page.click('input.mx_Login_submit');
|
||||||
|
|
||||||
|
await page.screenshot({ path: '09-clicked-on-register-button.png' });
|
||||||
|
|
||||||
|
// Waiting for the app to login can take some time, so be patient.
|
||||||
|
page.setDefaultTimeout(10000);
|
||||||
|
|
||||||
|
console.debug("Wait for chat window to show up");
|
||||||
|
await page.waitForSelector("div.mx_HomePage_default_buttons");
|
||||||
|
console.debug("Apparently the registration worked.");
|
||||||
|
|
||||||
|
await page.screenshot({ path: '10-logged-in-homescreen.png' });
|
||||||
|
|
||||||
|
|
||||||
|
// Close the browser and exit the script
|
||||||
|
await browser.close();
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
[global]
|
||||||
|
|
||||||
|
# Server runs in same container as tests do, so localhost is fine
|
||||||
|
server_name = "localhost"
|
||||||
|
|
||||||
|
# With a bit of luck /tmp is a RAM disk, so that the file system does not become the bottleneck while testing
|
||||||
|
database_path = "/tmp"
|
||||||
|
|
||||||
|
# All the other settings are left at their defaults:
|
||||||
|
port = 6167
|
||||||
|
max_request_size = 20_000_000
|
||||||
|
allow_registration = true
|
||||||
|
trusted_servers = ["matrix.org"]
|
||||||
|
address = "127.0.0.1"
|
||||||
|
proxy = "none"
|
||||||
Reference in New Issue
Block a user