mirror of
https://forgejo.ellis.link/continuwuation/continuwuity.git
synced 2026-11-23 17:07:32 +00:00
Compare commits
49
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5c07e7ae32 | ||
|
|
4a4c25843b | ||
|
|
9a3ed04eb6 | ||
|
|
c82aba6f5a | ||
|
|
14739ffaf7 | ||
|
|
733c25ce5a | ||
|
|
8c4a2d0ce9 | ||
|
|
c0f69f23dd | ||
|
|
c6b87fb033 | ||
|
|
635fccf11f | ||
|
|
def987f935 | ||
|
|
137805693e | ||
|
|
bd7450f52a | ||
|
|
66be5efeec | ||
|
|
33ed0a2e75 | ||
|
|
16f18f8516 | ||
|
|
4710c227db | ||
|
|
f5bd8d0a7c | ||
|
|
5ad6c35f0b | ||
|
|
17af942cbf | ||
|
|
9f7fb54bd4 | ||
|
|
21f3f0c1eb | ||
|
|
613bb1b2a8 | ||
|
|
a0d9e71eac | ||
|
|
d477417909 | ||
|
|
cd7910009a | ||
|
|
793c06c17b | ||
|
|
cf45dcffbb | ||
|
|
919fea9b97 | ||
|
|
5687847fe3 | ||
|
|
251086670f | ||
|
|
3379badbd4 | ||
|
|
cc28a01e49 | ||
|
|
95392ccc46 | ||
|
|
f3289f150c | ||
|
|
cbc089df1b | ||
|
|
0b738e835b | ||
|
|
5ad36c0914 | ||
|
|
7e678869ec | ||
|
|
9744a6e332 | ||
|
|
306be392ba | ||
|
|
66dd3e8e3e | ||
|
|
1dd572416b | ||
|
|
d74275bda1 | ||
|
|
65d25c77e8 | ||
|
|
95f925eaee | ||
|
|
becfc2454f | ||
|
|
b617e9fd5c | ||
|
|
ece207286a |
No files matched your search
@@ -49,6 +49,8 @@ jobs:
|
||||
run: npm ci
|
||||
|
||||
- name: Build Rspress documentation
|
||||
env:
|
||||
SITE_PATH: ${{ github.ref != 'refs/heads/main' && format('/pr/{0}/', '${{ forgejo.event.number }}') || '/' }}
|
||||
run: npm run docs:build
|
||||
|
||||
- name: Install Wrangler
|
||||
@@ -62,10 +64,16 @@ jobs:
|
||||
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
command: pages deploy ./doc_build --branch="main" --commit-dirty=true --project-name="${{ vars.CLOUDFLARE_PROJECT_NAME }}"
|
||||
|
||||
- name: Deploy to Cloudflare Pages (Preview)
|
||||
if: github.ref != 'refs/heads/main' && vars.CLOUDFLARE_PROJECT_NAME != ''
|
||||
uses: https://github.com/cloudflare/wrangler-action@953926a2e2182532811c01a25e53647d93bf07c0 # v4
|
||||
- name: Deploy to Grebedoc (Preview)
|
||||
if: github.ref != 'refs/heads/main'
|
||||
uses: actions/git-pages@v2
|
||||
with:
|
||||
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
command: pages deploy ./doc_build --branch="${{ github.head_ref || github.ref_name }}" --commit-dirty=true --project-name="${{ vars.CLOUDFLARE_PROJECT_NAME }}"
|
||||
site: https://preview.continuwuity.org
|
||||
path: "pr/${{ forgejo.event.number }}"
|
||||
server: grebedoc.dev
|
||||
token: ${{ forgejo.token }}
|
||||
source: doc_build/
|
||||
strict: true
|
||||
pretty-urls: true
|
||||
expires: 14
|
||||
comment: ${{ forgejo.sha }}
|
||||
@@ -43,7 +43,7 @@ jobs:
|
||||
name: Renovate
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: ghcr.io/renovatebot/renovate:44.241.0@sha256:22d22b4ca7d768b5b469309d34379783bf91cd94a58faecf1cd0f4528a65d21c
|
||||
image: ghcr.io/renovatebot/renovate:44.257.9@sha256:578179439fceea89646662dd583b27efdad8d1429e0cbd90681c40dde068589e
|
||||
options: --tmpfs /tmp:exec
|
||||
steps:
|
||||
- name: Checkout
|
||||
|
||||
Generated
+19
-29
@@ -497,7 +497,7 @@ dependencies = [
|
||||
"regex",
|
||||
"rustc-hash",
|
||||
"shlex",
|
||||
"syn 3.0.10",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -671,7 +671,7 @@ checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9"
|
||||
dependencies = [
|
||||
"semver",
|
||||
"serde",
|
||||
"toml 1.2.1+spec-1.1.0",
|
||||
"toml 1.2.2+spec-1.1.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -759,14 +759,14 @@ checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a"
|
||||
dependencies = [
|
||||
"glob",
|
||||
"libc",
|
||||
"libloading 0.8.9",
|
||||
"libloading",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.6.8"
|
||||
version = "4.6.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac230478587d0269d8d6998b82ae69ea51509d55df66d9e92edd1f986904cd4a"
|
||||
checksum = "844c5c0b65be192cb68d570cca1b21a6444431d24e39c084dc0336177015337c"
|
||||
dependencies = [
|
||||
"clap_builder",
|
||||
"clap_derive",
|
||||
@@ -784,9 +784,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap_derive"
|
||||
version = "4.6.8"
|
||||
version = "4.6.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "895c9d8d2ac2dd8b8a29f3724a14e72aaaa6debcf8c38c82f97305c6a172767a"
|
||||
checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
@@ -997,7 +997,6 @@ dependencies = [
|
||||
"ipaddress",
|
||||
"lettre",
|
||||
"libc",
|
||||
"libloading 0.9.1",
|
||||
"libmimalloc-sys",
|
||||
"lock_api 0.5.0",
|
||||
"maplit",
|
||||
@@ -1030,7 +1029,7 @@ dependencies = [
|
||||
"tikv-jemallocator",
|
||||
"tokio",
|
||||
"tokio-metrics",
|
||||
"toml 1.2.1+spec-1.1.0",
|
||||
"toml 1.2.2+spec-1.1.0",
|
||||
"tracing",
|
||||
"tracing-core",
|
||||
"tracing-subscriber",
|
||||
@@ -1128,6 +1127,7 @@ dependencies = [
|
||||
"log",
|
||||
"loole",
|
||||
"lru-cache",
|
||||
"mime",
|
||||
"nonzero_ext",
|
||||
"openidconnect",
|
||||
"opentelemetry",
|
||||
@@ -2105,9 +2105,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
||||
|
||||
[[package]]
|
||||
name = "form_urlencoded"
|
||||
version = "1.2.2"
|
||||
version = "1.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
|
||||
checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"
|
||||
dependencies = [
|
||||
"percent-encoding",
|
||||
]
|
||||
@@ -3241,16 +3241,6 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libloading"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a1832accd5a4ca2795ace4d05d15c4039be15b62d3b950eff99746a990e3cc10"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libm"
|
||||
version = "0.2.16"
|
||||
@@ -5146,7 +5136,7 @@ dependencies = [
|
||||
"ruma-identifiers-validation",
|
||||
"serde",
|
||||
"syn 3.0.10",
|
||||
"toml 1.2.1+spec-1.1.0",
|
||||
"toml 1.2.2+spec-1.1.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5652,7 +5642,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "969cde0349344dbbf58b5f9badbfb8f806db13969364eb8007c057ef687007d9"
|
||||
dependencies = [
|
||||
"annotate-snippets",
|
||||
"base64 0.22.1",
|
||||
"base64 0.23.1",
|
||||
"encoding_rs_io",
|
||||
"granit-parser",
|
||||
"nohash-hasher",
|
||||
@@ -6406,9 +6396,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "toml"
|
||||
version = "1.2.1+spec-1.1.0"
|
||||
version = "1.2.2+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7"
|
||||
checksum = "5426cb1b964690d913f6c5c1a1ae0b42f428ec506bb4d452876d7a209c9bca3b"
|
||||
dependencies = [
|
||||
"indexmap 2.14.2",
|
||||
"serde_core",
|
||||
@@ -6465,9 +6455,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "toml_parser"
|
||||
version = "1.1.5+spec-1.1.0"
|
||||
version = "1.1.6+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
|
||||
checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31"
|
||||
dependencies = [
|
||||
"winnow 1.0.5",
|
||||
]
|
||||
@@ -6864,9 +6854,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
|
||||
|
||||
[[package]]
|
||||
name = "url"
|
||||
version = "2.5.8"
|
||||
version = "2.5.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
|
||||
checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a"
|
||||
dependencies = [
|
||||
"form_urlencoded",
|
||||
"idna",
|
||||
|
||||
+3
-54
@@ -269,9 +269,6 @@ features = [
|
||||
[workspace.dependencies.tokio-metrics]
|
||||
version = "0.5.2"
|
||||
|
||||
[workspace.dependencies.libloading]
|
||||
version = "0.9.0"
|
||||
|
||||
[workspace.dependencies.wildmatch]
|
||||
version = "2.7.0"
|
||||
|
||||
@@ -592,6 +589,9 @@ version = "0.10.4"
|
||||
default-features = false
|
||||
features = ["std"]
|
||||
|
||||
[workspace.dependencies.mime]
|
||||
version = "0.3.18"
|
||||
|
||||
[workspace.dependencies.nonzero_ext]
|
||||
version = "0.3.0"
|
||||
|
||||
@@ -753,74 +753,23 @@ inherits = "release"
|
||||
# Developer profile
|
||||
#
|
||||
|
||||
# To enable hot-reloading:
|
||||
# 1. Uncomment all of the rustflags here.
|
||||
# 2. Uncomment crate-type=dylib in src/*/Cargo.toml
|
||||
#
|
||||
# opt-level, mir-opt-level, validate-mir are not known to interfere with reloading
|
||||
# and can be raised if build times are tolerable.
|
||||
|
||||
[profile.dev]
|
||||
debug = "full"
|
||||
opt-level = 0
|
||||
panic = "unwind"
|
||||
debug-assertions = true
|
||||
incremental = true
|
||||
#rustflags = [
|
||||
# '--cfg', 'conduwuit_mods',
|
||||
# '-Ztime-passes',
|
||||
# '-Zmir-opt-level=0',
|
||||
# '-Zvalidate-mir=false',
|
||||
# '-Ztls-model=global-dynamic',
|
||||
# '-Cprefer-dynamic=true',
|
||||
# '-Zstaticlib-prefer-dynamic=true',
|
||||
# '-Zstaticlib-allow-rdylib-deps=true',
|
||||
# '-Zpacked-bundled-libs=false',
|
||||
# '-Zplt=true',
|
||||
# '-Crpath=true',
|
||||
# '-Clink-arg=-Wl,--as-needed',
|
||||
# '-Clink-arg=-Wl,--allow-shlib-undefined',
|
||||
# '-Clink-arg=-Wl,-z,keep-text-section-prefix',
|
||||
# '-Clink-arg=-Wl,-z,lazy',
|
||||
#]
|
||||
|
||||
[profile.dev.package.conduwuit_core]
|
||||
inherits = "dev"
|
||||
[profile.dev.package.conduwuit]
|
||||
inherits = "dev"
|
||||
#rustflags = [
|
||||
# '--cfg', 'conduwuit_mods',
|
||||
# '-Ztime-passes',
|
||||
# '-Zmir-opt-level=0',
|
||||
# '-Zvalidate-mir=false',
|
||||
# '-Ztls-model=global-dynamic',
|
||||
# '-Cprefer-dynamic=true',
|
||||
# '-Zexport-executable-symbols=true',
|
||||
# '-Zplt=true',
|
||||
# '-Crpath=true',
|
||||
# '-Clink-arg=-Wl,--as-needed',
|
||||
# '-Clink-arg=-Wl,--allow-shlib-undefined',
|
||||
# '-Clink-arg=-Wl,--export-dynamic',
|
||||
# '-Clink-arg=-Wl,-z,lazy',
|
||||
#]
|
||||
|
||||
[profile.dev.package.'*']
|
||||
inherits = "dev"
|
||||
debug = 'limited'
|
||||
codegen-units = 1
|
||||
opt-level = 'z'
|
||||
#rustflags = [
|
||||
# '--cfg', 'conduwuit_mods',
|
||||
# '-Ztls-model=global-dynamic',
|
||||
# '-Cprefer-dynamic=true',
|
||||
# '-Zstaticlib-prefer-dynamic=true',
|
||||
# '-Zstaticlib-allow-rdylib-deps=true',
|
||||
# '-Zpacked-bundled-libs=true',
|
||||
# '-Zplt=true',
|
||||
# '-Clink-arg=-Wl,--as-needed',
|
||||
# '-Clink-arg=-Wl,-z,lazy',
|
||||
# '-Clink-arg=-Wl,-z,nodelete',
|
||||
#]
|
||||
|
||||
# primarily used for CI
|
||||
[profile.test]
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
Added the `GET /_matrix/client/v1/rooms/{roomId}/timestamp_to_event` endpoint as per MSC3030, letting clients find the event closest to a given timestamp. Contributed by @eleboucher.
|
||||
@@ -0,0 +1 @@
|
||||
URL previews no longer completely fail if downloading auxiliary content (images/videos/audio) fails. Contributed by @nex.
|
||||
@@ -0,0 +1 @@
|
||||
Network issues while refreshing an access token will no longer cause OAuth-compatible clients to be forcibly logged out. Contributed by @ginger.
|
||||
@@ -0,0 +1 @@
|
||||
Fix outgoing federation stalling after a sender worker panics. Contributed by @eleboucher.
|
||||
@@ -18,10 +18,5 @@
|
||||
"type": "file",
|
||||
"name": "testing",
|
||||
"label": "Testing"
|
||||
},
|
||||
{
|
||||
"type": "file",
|
||||
"name": "hot_reload",
|
||||
"label": "Hot Reloading"
|
||||
}
|
||||
]
|
||||
@@ -1,200 +0,0 @@
|
||||
# Hot Reloading ("Live" Development)
|
||||
|
||||
Note that hot reloading has not been refactored in quite a while and is not
|
||||
guaranteed to work at this time.
|
||||
|
||||
### Summary
|
||||
|
||||
When developing in debug-builds with the nightly toolchain, Continuwuity is modular
|
||||
using dynamic libraries and various parts of the application are hot-reloadable
|
||||
while the server is running: http api handlers, admin commands, services,
|
||||
database, etc. These are all split up into individual workspace crates as seen
|
||||
in the `src/` directory. Changes to sourcecode in a crate rebuild that crate and
|
||||
subsequent crates depending on it. Reloading then occurs for the changed crates.
|
||||
|
||||
Release builds still produce static binaries which are unaffected. Rust's
|
||||
soundness guarantees are in full force. Thus you cannot hot-reload release
|
||||
binaries.
|
||||
|
||||
### Requirements
|
||||
|
||||
Currently, this development setup only works on x86_64 and aarch64 Linux glibc.
|
||||
[musl explicitly does not support hot reloadable libraries, and does not
|
||||
implement `dlclose`][2]. macOS does not fully support our usage of `RTLD_GLOBAL`
|
||||
possibly due to some thread-local issues. [This Rust issue][3] may be of
|
||||
relevance, specifically [this comment][4]. It may be possible to get it working
|
||||
on only very modern macOS versions such as at least Sonoma, as currently loading
|
||||
dylibs is supported, but not unloading them in our setup, and the cited comment
|
||||
mentions an Apple WWDC confirming there have been TLS changes to somewhat make
|
||||
this possible.
|
||||
|
||||
As mentioned above this requires the nightly toolchain. This is due to reliance
|
||||
on various Cargo.toml features that are only available on nightly, most
|
||||
specifically `RUSTFLAGS` in Cargo.toml. Some of the implementation could also be
|
||||
simpler based on other various nightly features. We hope lots of nightly
|
||||
features start making it out of nightly sooner as there have been dozens of very
|
||||
helpful features that have been stuck in nightly ("unstable") for at least 5+
|
||||
years that would make this simpler. We encourage greater community consensus to
|
||||
move these features into stability.
|
||||
|
||||
This currently only works on x86_64/aarch64 Linux with a glibc C library. musl C
|
||||
library, macOS, and likely other host architectures are not supported (if other
|
||||
architectures work, feel free to let us know and/or make a PR updating this).
|
||||
This should work on GNU ld and lld (rust-lld) and gcc/clang, however if you
|
||||
happen to have linker issues it's recommended to try using `mold` or `gold`
|
||||
linkers, and please let us know in the [Continuwuity Matrix room][7] the linker
|
||||
error and what linker solved this issue so we can figure out a solution. Ideally
|
||||
there should be minimal friction to using this, and in the future a build script
|
||||
(`build.rs`) may be suitable to making this easier to use if the capabilities
|
||||
allow us.
|
||||
|
||||
### Usage
|
||||
|
||||
As of 19 May 2024, the instructions for using this are:
|
||||
|
||||
0. Have patience. Don't hesitate to join the [Continuwuity Matrix room][7] to
|
||||
receive help using this. As indicated by the various rustflags used and some
|
||||
of the interesting issues linked at the bottom, this is definitely not something
|
||||
the Rust ecosystem or toolchain is used to doing.
|
||||
|
||||
1. Install the nightly toolchain using rustup. You may need to use `rustup
|
||||
override set nightly` in your local Continuwuity directory, or use `cargo
|
||||
+nightly` for all actions.
|
||||
|
||||
2. Uncomment `cargo-features` at the top level / root Cargo.toml
|
||||
|
||||
3. Scroll down to the `# Developer profile` section and uncomment ALL the
|
||||
rustflags for each dev profile and their respective packages.
|
||||
|
||||
4. In each workspace crate's Cargo.toml (everything under `src/*` AND
|
||||
`deps/rust-rocksdb/Cargo.toml`), uncomment the `dylib` crate type under
|
||||
`[lib]`.
|
||||
|
||||
5. Due to [this rpath issue][5], you must export the `LD_LIBRARY_PATH`
|
||||
environment variable to your nightly Rust toolchain library directory. If
|
||||
using rustup (hopefully), use this: `export
|
||||
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/`
|
||||
|
||||
6. Start the server. You can use `cargo +nightly run` for this along with the
|
||||
standard.
|
||||
|
||||
7. Make some changes where you need to.
|
||||
|
||||
8. In a separate terminal window in the same directory (or using a terminal
|
||||
multiplexer like tmux), run the *build* Cargo command `cargo +nightly build`.
|
||||
Cargo should only rebuild what was changed / what's necessary, so it should
|
||||
not be rebuilding all the crates.
|
||||
|
||||
9. In your Continuwuity server terminal, hit/send `CTRL+C` signal. This will tell
|
||||
Continuwuity to find which libraries need to be reloaded, and reloads them as
|
||||
necessary.
|
||||
|
||||
10. If there were no errors, it will tell you it successfully reloaded `#`
|
||||
modules, and your changes should now be visible. Repeat 7 - 9 as needed.
|
||||
|
||||
To shutdown Continuwuity in this setup, hit/send `CTRL+\`. Normal builds still
|
||||
shutdown with `CTRL+C` as usual.
|
||||
|
||||
Steps 1 - 5 are the initial first-time steps for using this. To remove the hot
|
||||
reload setup, revert/comment all the Cargo.toml changes.
|
||||
|
||||
As mentioned in the requirements section, if you happen to have some linker
|
||||
issues, try using the `-fuse-ld=` rustflag and specify mold or gold in all the
|
||||
`rustflags` definitions in the top level Cargo.toml, and please let us know in
|
||||
the [Continuwuity Matrix room][7] the problem. mold can be installed typically
|
||||
through your distro, and gold is provided by the binutils package.
|
||||
|
||||
It's possible a helper script can be made to do all of this, or most preferably
|
||||
a specially made build script (build.rs). `cargo watch` support will be
|
||||
implemented soon which will eliminate the need to manually run `cargo build` all
|
||||
together.
|
||||
|
||||
### Addendum
|
||||
|
||||
Conduit was inherited as a single crate without modularity or reloading in its
|
||||
design. Reasonable partitioning and abstraction allowed a split into several
|
||||
crates, though many circular dependencies had to be corrected. The resulting
|
||||
crates now form a directed graph as depicted in figures below. The interfacing
|
||||
between these crates is still extremely broad which is not mitigable.
|
||||
|
||||
Initially [hot_lib_reload][6] was investigated but found appropriate for a
|
||||
project designed with modularity through limited interfaces, not a large and
|
||||
complex existing codebase. Instead a bespoke solution built directly on
|
||||
[libloading][8] satisfied our constraints. This required relatively minimal
|
||||
modifications and zero maintenance burden compared to what would be required
|
||||
otherwise. The technical difference lies with relocation processing: we leverage
|
||||
global bindings (`RTLD_GLOBAL`) in a very intentional way. Most libraries and
|
||||
off-the-shelf module systems (such as [hot_lib_reload][6]) restrict themselves
|
||||
to local bindings (`RTLD_LOCAL`). This allows them to release software to
|
||||
multiple platforms with much greater consistency, but at the cost of burdening
|
||||
applications to explicitly manage these bindings. In our case with an optional
|
||||
feature for developers, we shrug any such requirement to enjoy the cost/benefit
|
||||
on platforms where global relocations are properly cooperative.
|
||||
|
||||
To make use of `RTLD_GLOBAL` the application has to be oriented as a directed
|
||||
acyclic graph. The primary rule is simple and illustrated in the figure below:
|
||||
**no crate is allowed to call a function or use a variable from a crate below
|
||||
it.**
|
||||
|
||||

|
||||
|
||||
When a symbol is referenced between crates they become bound: **crates cannot be
|
||||
unloaded until their calling crates are first unloaded.** Thus we start the
|
||||
reloading process from the crate which has no callers. There is a small problem
|
||||
though: the first crate is called by the base executable itself! This is solved
|
||||
by using an `RTLD_LOCAL` binding for just one link between the main executable
|
||||
and the first crate, freeing the executable from all modules as no global
|
||||
binding ever occurs between them.
|
||||
|
||||

|
||||
|
||||
Proper resource management is essential for reliable reloading to occur. This is
|
||||
a very basic ask in RAII-idiomatic Rust and the exposure to reloading hazards is
|
||||
remarkably low, generally stemming from poor patterns and practices.
|
||||
Unfortunately static analysis doesn't enforce reload-safety programmatically
|
||||
(though it could one day), for now hazards can be avoided by knowing a few basic
|
||||
do's and dont's:
|
||||
|
||||
1. Understand that code is memory. Just like one is forbidden from referencing
|
||||
free'd memory, one must not transfer control to free'd code. Exposure to this
|
||||
is primarily from two things:
|
||||
|
||||
- Callbacks, which this project makes very little use of.
|
||||
- Async tasks, which are addressed below.
|
||||
|
||||
2. Tie all resources to a scope or object lifetime with greatest possible
|
||||
symmetry (locality). For our purposes this applies to code resources, which
|
||||
means async blocks and tokio tasks.
|
||||
|
||||
- **Never spawn a task without receiving and storing its JoinHandle**.
|
||||
- **Always wait on join handles** before leaving a scope or in another cleanup
|
||||
function called by an owning scope.
|
||||
|
||||
3. Know any minor specific quirks documented in code or here:
|
||||
|
||||
- Don't use `tokio::spawn`, instead use our `Handle` in `core/server.rs`, which
|
||||
is reachable in most of the codebase via `services()` or other state. This is
|
||||
due to some bugs or assumptions made in tokio, as it happens in `unsafe {}`
|
||||
blocks, which are mitigated by circumventing some thread-local variables. Using
|
||||
runtime handles is good practice in any case.
|
||||
|
||||
The initial implementation PR is available [here][1].
|
||||
|
||||
### Interesting related issues/bugs
|
||||
|
||||
- [DT_RUNPATH produced in binary with rpath = true is wrong (cargo)][5]
|
||||
- [Disabling MIR Optimization in Rust Compilation
|
||||
(cargo)](https://internals.rust-lang.org/t/disabling-mir-optimization-in-rust-compilation/19066/5)
|
||||
- [Workspace-level metadata
|
||||
(cargo-deb)](https://github.com/kornelski/cargo-deb/issues/68)
|
||||
|
||||
[1]: https://forgejo.ellis.link/continuwuation/continuwuity/pulls/387
|
||||
[2]: https://wiki.musl-libc.org/functional-differences-from-glibc.html#Unloading-libraries
|
||||
[3]: https://github.com/rust-lang/rust/issues/28794
|
||||
[4]: https://github.com/rust-lang/rust/issues/28794#issuecomment-368693049
|
||||
[5]: https://github.com/rust-lang/cargo/issues/12746
|
||||
[6]: https://crates.io/crates/hot-lib-reloader/
|
||||
[7]: https://matrix.to/#/#continuwuity:continuwuity.org?via=continuwuity.org&via=ellis.link&via=explodie.org&via=matrix.org
|
||||
[8]: https://crates.io/crates/libloading
|
||||
@@ -37,13 +37,6 @@ It is highly unlikely you will ever need to add a new workspace member, but if
|
||||
you truly find yourself needing to, we recommend reaching out to us in the
|
||||
Matrix room for discussions about it beforehand.
|
||||
|
||||
The primary inspiration for this design was apart of hot reloadable development,
|
||||
to support "Continuwuity as a library" where specific parts can simply be
|
||||
swapped out. There is evidence Conduit wanted to go this route too as `axum` is
|
||||
technically an optional feature in Conduit, and can be compiled without the
|
||||
binary or axum library for handling inbound web requests; but it was never
|
||||
completed or worked.
|
||||
|
||||
See the Rust documentation on [Workspaces][workspaces] for general questions and
|
||||
information on Cargo workspaces.
|
||||
|
||||
|
||||
@@ -71,6 +71,9 @@ Names below are as they appear in Prometheus. OTLP uses the dotted OpenTelemetry
|
||||
| `continuwuity_sender_events_total` | counter | `destination`, `kind`, `outcome` | PDUs and EDUs sent in outgoing transactions |
|
||||
| `continuwuity_sender_events_queued_total` | counter | `destination`, `kind` | PDUs and EDUs queued for sending |
|
||||
| `continuwuity_sender_queue_depth` | gauge | | Messages waiting for the sender workers |
|
||||
| `continuwuity_sender_requests` | gauge | `state` | Estimated outgoing requests stored as `queued` or `active` (in flight) |
|
||||
| `continuwuity_sender_workers` | gauge | | Running sender workers; below the configured count means a worker is restarting |
|
||||
| `continuwuity_sender_panics_total` | counter | `scope` | Panics caught in a single outgoing `transaction` or a whole sender `worker` |
|
||||
| `continuwuity_users` | gauge | `origin` | Known `local` users, including deactivated, and `remote` users |
|
||||
| `continuwuity_invites_total` | counter | `direction`, `destination`, `outcome` | Invites sent by local users or received over federation |
|
||||
| `continuwuity_media_write_size_bytes` | histogram | `origin` | Media files written, from local uploads or cached remote media |
|
||||
|
||||
@@ -36,10 +36,6 @@ List database backups
|
||||
|
||||
Send a message to the admin room
|
||||
|
||||
## `!admin server reload`
|
||||
|
||||
Hot-reload the server
|
||||
|
||||
## `!admin server restart`
|
||||
|
||||
Restart the server
|
||||
|
||||
Generated
+18
-38
@@ -11,7 +11,7 @@
|
||||
"devDependencies": {
|
||||
"@rspress/core": "^2.0.0",
|
||||
"@rspress/plugin-client-redirects": "^2.0.0",
|
||||
"@rspress/plugin-sitemap": "^2.0.0",
|
||||
"@types/node": "^26.6.6",
|
||||
"typescript": "^7.0.0"
|
||||
}
|
||||
},
|
||||
@@ -230,9 +230,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -247,9 +244,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -264,9 +258,6 @@
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -281,9 +272,6 @@
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -298,9 +286,6 @@
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -315,9 +300,6 @@
|
||||
"s390x"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -332,9 +314,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -349,9 +328,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -524,19 +500,6 @@
|
||||
"@rspress/core": "^2.1.0-beta.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@rspress/plugin-sitemap": {
|
||||
"version": "2.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@rspress/plugin-sitemap/-/plugin-sitemap-2.1.4.tgz",
|
||||
"integrity": "sha512-TObDTXgBKFAHEWEth47aehQSYtFfpIkqM4w14a0hUbPLkbu2AZ2cKnMzFTKK+W6I/3LN54scvfGYTL5CPQsDXw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@rspress/core": "^2.1.0-beta.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@rspress/shared": {
|
||||
"version": "2.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.1.4.tgz",
|
||||
@@ -770,6 +733,16 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "26.6.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz",
|
||||
"integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~8.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/react": {
|
||||
"version": "19.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz",
|
||||
@@ -3842,6 +3815,13 @@
|
||||
"@typescript/typescript-win32-x64": "7.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "8.9.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
|
||||
"integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/unhead": {
|
||||
"version": "2.1.17",
|
||||
"resolved": "https://registry.npmjs.org/unhead/-/unhead-2.1.17.tgz",
|
||||
|
||||
+2
-2
@@ -20,11 +20,11 @@
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"type": "commonjs",
|
||||
"type": "module",
|
||||
"devDependencies": {
|
||||
"@rspress/core": "^2.0.0",
|
||||
"@rspress/plugin-client-redirects": "^2.0.0",
|
||||
"@rspress/plugin-sitemap": "^2.0.0",
|
||||
"@types/node": "^26.6.6",
|
||||
"typescript": "^7.0.0"
|
||||
}
|
||||
}
|
||||
+8
-9
@@ -1,10 +1,13 @@
|
||||
import { defineConfig } from '@rspress/core';
|
||||
import { pluginSitemap } from '@rspress/plugin-sitemap';
|
||||
import { pluginClientRedirects } from '@rspress/plugin-client-redirects';
|
||||
|
||||
const sitePath: string = process.env.SITE_PATH ?? '/';
|
||||
|
||||
export default defineConfig({
|
||||
root: 'docs',
|
||||
title: 'Continuwuity',
|
||||
siteOrigin: sitePath != "/" ? "https://preview.continuwuity.org" : "https://continuwuity.org",
|
||||
base: sitePath,
|
||||
description: 'A community-driven Matrix homeserver',
|
||||
icon: '/assets/logo.svg',
|
||||
logo: {
|
||||
@@ -75,14 +78,10 @@ export default defineConfig({
|
||||
lastUpdated: true,
|
||||
enableContentAnimation: true,
|
||||
enableAppearanceAnimation: false,
|
||||
footer: {
|
||||
},
|
||||
footer: {},
|
||||
},
|
||||
|
||||
plugins: [pluginSitemap({
|
||||
siteUrl: 'https://continuwuity.org', // TODO: Set automatically in build pipeline
|
||||
}),
|
||||
pluginClientRedirects({
|
||||
plugins: [pluginClientRedirects({
|
||||
redirects: [{
|
||||
from: '^/config_reference$',
|
||||
to: '/reference/config'
|
||||
@@ -105,8 +104,8 @@ export default defineConfig({
|
||||
from: "^/source(|_code)$",
|
||||
to: "https://forgejo.ellis.link/continuwuation/continuwuity",
|
||||
}, {
|
||||
from: "^/(CONTRIBUTING.md|contributing)$",
|
||||
to: "/development/contributing"
|
||||
from: "^/(CONTRIBUTING.md|contributing)$",
|
||||
to: "/development/contributing"
|
||||
}
|
||||
]
|
||||
})],
|
||||
|
||||
@@ -34,9 +34,6 @@ pub(crate) use crate::{context::Context, utils::get_room_info};
|
||||
|
||||
pub(crate) const PAGE_SIZE: usize = 100;
|
||||
|
||||
conduwuit::mod_ctor! {}
|
||||
conduwuit::mod_dtor! {}
|
||||
|
||||
pub use crate::admin::AdminCommand;
|
||||
|
||||
/// Install the admin command processor
|
||||
|
||||
@@ -110,14 +110,6 @@ impl crate::Context<'_> {
|
||||
self.write_str("Notice was sent to #admins").await
|
||||
}
|
||||
|
||||
pub(super) async fn reload_mods(&self) -> Result {
|
||||
self.bail_restricted()?;
|
||||
|
||||
self.services.server.reload()?;
|
||||
|
||||
self.write_str("Reloading server...").await
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub(super) async fn restart(&self, force: bool) -> Result {
|
||||
use conduwuit::utils::sys::current_exe_deleted;
|
||||
|
||||
@@ -39,10 +39,6 @@ pub enum ServerCommand {
|
||||
message: Vec<String>,
|
||||
},
|
||||
|
||||
/// Hot-reload the server
|
||||
#[command(name = "reload", alias = "reload-mods")]
|
||||
ReloadMods,
|
||||
|
||||
#[cfg(unix)]
|
||||
/// Restart the server
|
||||
Restart {
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::time::Duration;
|
||||
|
||||
use axum::extract::State;
|
||||
use conduwuit::{
|
||||
Err, Result, err,
|
||||
Err, Result, debug, err,
|
||||
utils::{self, content_disposition::make_content_disposition, math::ruma_from_usize},
|
||||
};
|
||||
use conduwuit_core::error;
|
||||
@@ -219,10 +219,12 @@ pub(crate) async fn get_media_preview_route(
|
||||
)));
|
||||
}
|
||||
|
||||
debug!("Fetching a URL preview for {url} on behalf of {sender_user}");
|
||||
let preview = services
|
||||
.media
|
||||
.get_url_preview(&url)
|
||||
.await
|
||||
.inspect(|_| debug!(user=%sender_user, %url, "Finished fetching a URL preview"))
|
||||
.map_err(|error| {
|
||||
err!(Request(Unknown(
|
||||
debug_error!(%sender_user, %url, "Failed to fetch URL preview: {error}")
|
||||
|
||||
@@ -4,10 +4,12 @@ mod event;
|
||||
mod initial_sync;
|
||||
mod stripped_state;
|
||||
mod summary;
|
||||
mod timestamp_to_event;
|
||||
mod upgrade;
|
||||
|
||||
pub(crate) use self::{
|
||||
aliases::get_room_aliases_route, create::create_room_route, event::get_room_event_route,
|
||||
initial_sync::room_initial_sync_route, stripped_state::get_stripped_state_route,
|
||||
summary::get_room_summary, upgrade::upgrade_room_route,
|
||||
summary::get_room_summary, timestamp_to_event::get_event_by_timestamp_route,
|
||||
upgrade::upgrade_room_route,
|
||||
};
|
||||
@@ -0,0 +1,61 @@
|
||||
use axum::extract::State;
|
||||
use conduwuit::{Err, Event, Result, utils::stream::TryIgnore};
|
||||
use futures::{StreamExt, pin_mut};
|
||||
use ruma::api::client::room::get_event_by_timestamp;
|
||||
|
||||
use crate::Ruma;
|
||||
|
||||
const MAX_CANDIDATES: usize = 20;
|
||||
|
||||
/// # `GET /_matrix/client/v1/rooms/{roomId}/timestamp_to_event`
|
||||
///
|
||||
/// Gets the ID of the event closest to the given timestamp, in the direction
|
||||
/// specified by `dir`.
|
||||
pub(crate) async fn get_event_by_timestamp_route(
|
||||
State(ref services): State<crate::State>,
|
||||
body: Ruma<get_event_by_timestamp::v1::Request>,
|
||||
) -> Result<get_event_by_timestamp::v1::Response> {
|
||||
let sender_user = body.identity.expect_sender_user()?;
|
||||
let room_id = &body.room_id;
|
||||
|
||||
if !services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.user_can_see_state_events(sender_user, room_id)
|
||||
.await
|
||||
{
|
||||
return Err!(Request(Forbidden("You don't have permission to view this room.")));
|
||||
}
|
||||
|
||||
if !services.rooms.timeline.timestamp_index_ready().await {
|
||||
return Err!(FeatureDisabled("timestamp_to_event"));
|
||||
}
|
||||
|
||||
let candidates = services
|
||||
.rooms
|
||||
.timeline
|
||||
.pdus_by_timestamp(room_id, body.ts, body.dir)
|
||||
.ignore_err()
|
||||
.take(MAX_CANDIDATES);
|
||||
|
||||
pin_mut!(candidates);
|
||||
while let Some((_, pdu)) = candidates.next().await {
|
||||
if services
|
||||
.rooms
|
||||
.state_accessor
|
||||
.user_can_see_event(sender_user, room_id, pdu.event_id())
|
||||
.await
|
||||
{
|
||||
return Ok(get_event_by_timestamp::v1::Response::new(
|
||||
pdu.event_id().to_owned(),
|
||||
pdu.origin_server_ts(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Err!(Request(NotFound(
|
||||
"Unable to find event from {} in direction {:?}",
|
||||
body.ts.get(),
|
||||
body.dir
|
||||
)))
|
||||
}
|
||||
@@ -16,6 +16,3 @@ pub mod client_ip;
|
||||
pub mod admin;
|
||||
|
||||
pub(crate) use self::router::{Ruma, RumaResponse, State};
|
||||
|
||||
conduwuit::mod_ctor! {}
|
||||
conduwuit::mod_dtor! {}
|
||||
@@ -52,6 +52,7 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
|
||||
.ruma_route(&client::set_pushrule_actions_route)
|
||||
.ruma_route(&client::delete_pushrule_route)
|
||||
.ruma_route(&client::get_room_event_route)
|
||||
.ruma_route(&client::get_event_by_timestamp_route)
|
||||
.ruma_route(&client::get_room_aliases_route)
|
||||
.ruma_route(&client::get_filter_route)
|
||||
.ruma_route(&client::create_filter_route)
|
||||
|
||||
+22
-6
@@ -319,6 +319,19 @@ async fn check_access_token(
|
||||
));
|
||||
}
|
||||
|
||||
let session_info = services
|
||||
.oauth
|
||||
.get_session_info_for_device(&sender_user, &sender_device)
|
||||
.await;
|
||||
|
||||
if let Some(session_info) = &session_info {
|
||||
services.oauth.clear_previous_refresh_token(
|
||||
&sender_user,
|
||||
&sender_device,
|
||||
session_info,
|
||||
);
|
||||
}
|
||||
|
||||
// Locked users can only use /logout and /logout/all
|
||||
if services
|
||||
.users
|
||||
@@ -333,12 +346,6 @@ async fn check_access_token(
|
||||
}
|
||||
}
|
||||
|
||||
let session_info = services
|
||||
.oauth
|
||||
.get_session_info_for_device(&sender_user, &sender_device)
|
||||
.await
|
||||
.map(Box::new);
|
||||
|
||||
// Make sure the user has the right scopes to use the route
|
||||
let mut user_scopes = if let Some(session_info) = &session_info {
|
||||
session_info.scopes()
|
||||
@@ -416,6 +423,15 @@ async fn check_access_token(
|
||||
sender_device,
|
||||
appservice_info: Box::new(appservice_info),
|
||||
})
|
||||
} else if services.users.is_previous_token(token).await {
|
||||
// Return a soft-logout for previous tokens. This is necessary
|
||||
// to make token refreshing idempotent.
|
||||
|
||||
Err(Error::Request(
|
||||
ErrorKind::UnknownToken(assign!(UnknownTokenErrorData::new(), { soft_logout: true })),
|
||||
"This token has expired".into(),
|
||||
StatusCode::UNAUTHORIZED,
|
||||
))
|
||||
} else {
|
||||
Err(Error::Request(
|
||||
ErrorKind::UnknownToken(UnknownTokenErrorData::new()),
|
||||
|
||||
@@ -20,9 +20,6 @@ crate-type = [
|
||||
brotli_compression = [
|
||||
"reqwest/brotli",
|
||||
]
|
||||
conduwuit_mods = [
|
||||
"dep:libloading"
|
||||
]
|
||||
gzip_compression = [
|
||||
"reqwest/gzip",
|
||||
]
|
||||
@@ -85,8 +82,6 @@ http-body-util.workspace = true
|
||||
http.workspace = true
|
||||
ipaddress.workspace = true
|
||||
libc.workspace = true
|
||||
libloading.workspace = true
|
||||
libloading.optional = true
|
||||
lettre.workspace = true
|
||||
num-traits.workspace = true
|
||||
rand.workspace = true
|
||||
|
||||
+142
-85
@@ -1,8 +1,6 @@
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
ops::Deref,
|
||||
ptr,
|
||||
ptr::null_mut,
|
||||
ptr::NonNull,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicPtr, Ordering},
|
||||
@@ -10,119 +8,178 @@ use std::{
|
||||
};
|
||||
|
||||
use super::Config;
|
||||
use crate::Result;
|
||||
use crate::{Result, SyncMutex};
|
||||
|
||||
/// The configuration manager is an indirection to reload the configuration for
|
||||
/// the server while it is running. In order to not burden or clutter the many
|
||||
/// callsites which query for configuration items, this object implements Deref
|
||||
/// for the actively loaded configuration.
|
||||
///
|
||||
/// Every installed `Arc<Config>` is kept at a stable heap address in `retired`
|
||||
/// for the entire lifetime of `Manager` (intentionally retaining prior configs
|
||||
/// across the rare, admin-triggered reloads until shutdown). Because
|
||||
/// `Deref::deref(&self)` ties the returned `&Arc<Config>` lifetime to `&self`,
|
||||
/// readers can perform a single `Acquire` load with no locking, no TLS, and no
|
||||
/// risk of dangling or aliasing UB across reloads.
|
||||
pub struct Manager {
|
||||
active: AtomicPtr<Config>,
|
||||
active: AtomicPtr<Arc<Config>>,
|
||||
/// Append-only owner of every `Box<Arc<Config>>` ever published to
|
||||
/// `active` (including the currently active config). Entries are only
|
||||
/// freed when `Manager` itself is dropped (`&mut self`), guaranteeing that
|
||||
/// any `&Arc<Config>` returned by `Deref::deref` remains valid and
|
||||
/// immutable for the lifetime of `self`.
|
||||
retired: SyncMutex<Vec<PinnedConfig>>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static INDEX: Cell<usize> = 0.into();
|
||||
static HANDLE: RefCell<Handles> = const {
|
||||
RefCell::new([const { None }; HISTORY])
|
||||
};
|
||||
/// Heap-pinned `Arc<Config>` stored as a raw `NonNull` rather than `Box` so
|
||||
/// moving it (e.g., when `Vec` reallocates) never retags or invalidates raw
|
||||
/// pointers previously published to `Manager::active`.
|
||||
struct PinnedConfig(NonNull<Arc<Config>>);
|
||||
|
||||
// SAFETY: `Arc<Config>` is `Send + Sync`, and `PinnedConfig` uniquely owns the
|
||||
// `Box<Arc<Config>>` allocation until it is dropped in `Manager::drop`.
|
||||
unsafe impl Send for PinnedConfig {}
|
||||
|
||||
impl PinnedConfig {
|
||||
fn new(config: Config) -> Self {
|
||||
let ptr = Box::into_raw(Box::new(Arc::new(config)));
|
||||
Self(NonNull::new(ptr).expect("Box::into_raw returned null"))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
const fn as_ptr(&self) -> *mut Arc<Config> { self.0.as_ptr() }
|
||||
}
|
||||
|
||||
type Handle = Option<Arc<Config>>;
|
||||
type Handles = [Handle; HISTORY];
|
||||
|
||||
const HISTORY: usize = 8;
|
||||
impl Drop for PinnedConfig {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: `self.0` was created via `Box::into_raw` in
|
||||
// `PinnedConfig::new` and is only dropped when `Manager` itself is
|
||||
// dropped (`&mut self`), after all borrows derived from `Deref::deref`
|
||||
// have ended.
|
||||
unsafe {
|
||||
drop(Box::from_raw(self.0.as_ptr()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Manager {
|
||||
pub(crate) fn new(config: Config) -> Self {
|
||||
let config = Arc::new(config);
|
||||
let pinned = PinnedConfig::new(config);
|
||||
let ptr = pinned.as_ptr();
|
||||
Self {
|
||||
active: AtomicPtr::new(Arc::into_raw(config).cast_mut()),
|
||||
active: AtomicPtr::new(ptr),
|
||||
retired: SyncMutex::new(vec![pinned]),
|
||||
}
|
||||
}
|
||||
|
||||
/// Update the active configuration, returning prior configuration.
|
||||
#[tracing::instrument(skip_all, level = "info")]
|
||||
pub fn update(&self, config: Config) -> Result<Arc<Config>> {
|
||||
let config = Arc::new(config);
|
||||
let new = Arc::into_raw(config);
|
||||
let old = self.active.swap(new.cast_mut(), Ordering::AcqRel);
|
||||
let pinned = PinnedConfig::new(config);
|
||||
let new_ptr = pinned.as_ptr();
|
||||
|
||||
// SAFETY: The old active pointer was set using an Arc::into_raw().
|
||||
// We're obliged to reconstitute that into Arc otherwise it will leak.
|
||||
Ok(unsafe { Arc::from_raw(old) })
|
||||
}
|
||||
let mut retired = self.retired.lock();
|
||||
// Push before publishing to `active` so ownership is recorded even if
|
||||
// `Vec::push` were to unwind.
|
||||
retired.push(pinned);
|
||||
|
||||
fn load(&self, handle: &mut [Option<Arc<Config>>]) -> &'static Arc<Config> {
|
||||
let config = self.active.load(Ordering::Acquire);
|
||||
// `Release` publishes the initialized `Box<Arc<Config>>` to readers
|
||||
// performing `Acquire` loads in `Deref::deref`.
|
||||
let old_ptr = self.active.swap(new_ptr, Ordering::AcqRel);
|
||||
|
||||
// Branch taken after config reload or first access by this thread.
|
||||
if handle[INDEX.get()]
|
||||
.as_ref()
|
||||
.is_none_or(|handle| !ptr::eq(config, Arc::as_ptr(handle)))
|
||||
{
|
||||
INDEX.set(INDEX.get().wrapping_add(1).wrapping_rem(HISTORY));
|
||||
return load_miss(handle, INDEX.get(), config);
|
||||
}
|
||||
// SAFETY: `old_ptr` points to a `PinnedConfig` still owned by `retired`
|
||||
// and cannot be freed until `Manager` is dropped.
|
||||
let old = unsafe { Arc::clone(&*old_ptr) };
|
||||
|
||||
let config: &Arc<Config> = handle[INDEX.get()]
|
||||
.as_ref()
|
||||
.expect("handle was already cached for this thread");
|
||||
|
||||
// SAFETY: The caller should not hold multiple references at a time
|
||||
// directly into Config, as a subsequent reference might invalidate
|
||||
// the thread's cache causing another reference to dangle.
|
||||
//
|
||||
// This is a highly unusual pattern as most config values are copied by
|
||||
// value or used immediately without running overlap with another
|
||||
// value. Even if it does actually occur somewhere, the window of
|
||||
// danger is limited to the config being reloaded while the reference
|
||||
// is held and another access is made by the same thread into a
|
||||
// different config value. This is mitigated by creating a buffer
|
||||
// of old configs rather than discarding at the earliest opportunity;
|
||||
// the odds of this scenario are thus astronomical.
|
||||
unsafe { std::mem::transmute(config) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Manager {
|
||||
fn drop(&mut self) {
|
||||
let config = self.active.swap(null_mut(), Ordering::AcqRel);
|
||||
|
||||
// SAFETY: The active pointer was set using an Arc::into_raw(). We're
|
||||
// obliged to reconstitute that into Arc otherwise it will leak.
|
||||
unsafe { Arc::from_raw(config) };
|
||||
Ok(old)
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for Manager {
|
||||
type Target = Arc<Config>;
|
||||
|
||||
fn deref(&self) -> &Self::Target { HANDLE.with_borrow_mut(|handle| self.load(handle)) }
|
||||
#[inline]
|
||||
fn deref(&self) -> &Self::Target {
|
||||
let ptr = self.active.load(Ordering::Acquire);
|
||||
|
||||
// SAFETY: `ptr` was initialized in `Manager::new` or published via
|
||||
// `Ordering::AcqRel` in `Manager::update` and points to a
|
||||
// `PinnedConfig` in `self.retired`. Entries in `self.retired` are never
|
||||
// removed or mutated until `Manager` is dropped (`&mut self`), so the
|
||||
// returned `&'self Arc<Config>` remains valid and immutable for the
|
||||
// entire borrow of `self`.
|
||||
unsafe { &*ptr }
|
||||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument(
|
||||
name = "miss",
|
||||
level = "trace",
|
||||
skip_all,
|
||||
fields(%index, ?config)
|
||||
)]
|
||||
#[allow(clippy::transmute_ptr_to_ptr)]
|
||||
fn load_miss(
|
||||
handle: &mut [Option<Arc<Config>>],
|
||||
index: usize,
|
||||
config: *const Config,
|
||||
) -> &'static Arc<Config> {
|
||||
// SAFETY: The active pointer was set prior and always remains valid. We're
|
||||
// reconstituting the Arc here but as a new reference, so the count is
|
||||
// incremented. This instance will be cached in the thread-local.
|
||||
let config = unsafe {
|
||||
Arc::increment_strong_count(config);
|
||||
Arc::from_raw(config)
|
||||
};
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::thread;
|
||||
|
||||
// SAFETY: See the note on the transmute above. The caller should not hold
|
||||
// more than one reference at a time directly into Config, as the second
|
||||
// access might invalidate the thread's cache, dangling the reference to
|
||||
// the first.
|
||||
unsafe { std::mem::transmute(handle[index].insert(config)) }
|
||||
use super::*;
|
||||
|
||||
fn test_config(server_name: &str) -> Config {
|
||||
use figment::{
|
||||
Figment,
|
||||
providers::{Format, Toml},
|
||||
};
|
||||
|
||||
let raw = format!("server_name = \"{server_name}\"\ndatabase_path = \"/tmp\"\n");
|
||||
Figment::new()
|
||||
.merge(Toml::string(&raw))
|
||||
.extract()
|
||||
.expect("valid test config")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deref_survives_many_reloads() {
|
||||
let manager = Manager::new(test_config("initial.example"));
|
||||
let first: &Arc<Config> = &manager;
|
||||
let first_name: &str = first.server_name.as_str();
|
||||
|
||||
for i in 0..32 {
|
||||
let prev = manager
|
||||
.update(test_config(&format!("reload-{i}.example")))
|
||||
.expect("update succeeds");
|
||||
if i == 0 {
|
||||
assert_eq!(prev.server_name.as_str(), "initial.example");
|
||||
}
|
||||
}
|
||||
|
||||
// Original reference remains valid and unchanged after > HISTORY
|
||||
// reloads.
|
||||
assert_eq!(first_name, "initial.example");
|
||||
assert_eq!(manager.server_name.as_str(), "reload-31.example");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_reads_and_updates() {
|
||||
let manager = Manager::new(test_config("start.example"));
|
||||
|
||||
thread::scope(|s| {
|
||||
for _ in 0..4 {
|
||||
s.spawn(|| {
|
||||
for _ in 0..200 {
|
||||
let cfg: &Arc<Config> = &manager;
|
||||
assert!(cfg.server_name.as_str().ends_with(".example"));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
s.spawn(|| {
|
||||
for i in 0..32 {
|
||||
let _ = manager
|
||||
.update(test_config(&format!("iter-{i}.example")))
|
||||
.expect("update succeeds");
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_outlives_scoped_thread() {
|
||||
let manager = Manager::new(test_config("scoped.example"));
|
||||
let cfg_ref: &Arc<Config> = thread::scope(|s| s.spawn(|| &*manager).join().unwrap());
|
||||
assert_eq!(cfg_ref.server_name.as_str(), "scoped.example");
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ pub struct Instruments {
|
||||
pub sender_transaction_duration: Histogram<f64>,
|
||||
pub sender_events: Counter<u64>,
|
||||
pub sender_events_queued: Counter<u64>,
|
||||
pub sender_panics: Counter<u64>,
|
||||
|
||||
pub media_write_size: Histogram<u64>,
|
||||
pub media_read_size: Histogram<u64>,
|
||||
@@ -116,6 +117,11 @@ impl Instruments {
|
||||
.with_description("PDUs and EDUs queued for sending")
|
||||
.with_unit("{event}")
|
||||
.build(),
|
||||
sender_panics: meter
|
||||
.u64_counter("continuwuity.sender.panics")
|
||||
.with_description("Panics caught in outgoing transactions and sender workers")
|
||||
.with_unit("{panic}")
|
||||
.build(),
|
||||
|
||||
media_write_size: size(
|
||||
"continuwuity.media.write.size",
|
||||
|
||||
@@ -8,19 +8,6 @@ pub mod info;
|
||||
pub mod log;
|
||||
pub mod matrix;
|
||||
pub mod metrics;
|
||||
pub mod mods;
|
||||
|
||||
#[cfg(any(not(conduwuit_mods), not(feature = "conduwuit_mods")))]
|
||||
pub mod mods {
|
||||
#[macro_export]
|
||||
macro_rules! mod_ctor {
|
||||
() => {};
|
||||
}
|
||||
#[macro_export]
|
||||
macro_rules! mod_dtor {
|
||||
() => {};
|
||||
}
|
||||
}
|
||||
pub mod server;
|
||||
pub mod utils;
|
||||
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
use std::sync::atomic::{AtomicI32, Ordering};
|
||||
|
||||
const ORDERING: Ordering = Ordering::Relaxed;
|
||||
static STATIC_DTORS: AtomicI32 = AtomicI32::new(0);
|
||||
|
||||
/// Called by Module::unload() to indicate module is about to be unloaded and
|
||||
/// static destruction is intended. This will allow verifying it actually took
|
||||
/// place.
|
||||
pub(crate) fn prepare() {
|
||||
let count = STATIC_DTORS.fetch_sub(1, ORDERING);
|
||||
debug_assert!(count <= 0, "STATIC_DTORS should not be greater than zero.");
|
||||
}
|
||||
|
||||
/// Called by static destructor of a module. This call should only be found
|
||||
/// inside a mod_fini! macro. Do not call from anywhere else.
|
||||
#[inline(always)]
|
||||
pub fn report() { let _count = STATIC_DTORS.fetch_add(1, ORDERING); }
|
||||
|
||||
/// Called by Module::unload() (see check()) with action in case a check()
|
||||
/// failed. This can allow a stuck module to be noted while allowing for other
|
||||
/// independent modules to be diagnosed.
|
||||
pub(crate) fn check_and_reset() -> bool { STATIC_DTORS.swap(0, ORDERING) == 0 }
|
||||
|
||||
/// Called by Module::unload() after unload to verify static destruction took
|
||||
/// place. A call to prepare() must be made prior to Module::unload() and making
|
||||
/// this call.
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn check() -> bool { STATIC_DTORS.load(ORDERING) == 0 }
|
||||
@@ -1,44 +0,0 @@
|
||||
#[macro_export]
|
||||
macro_rules! mod_ctor {
|
||||
( $($body:block)? ) => {
|
||||
$crate::mod_init! {{
|
||||
$crate::debug_info!("Module loaded");
|
||||
$($body)?
|
||||
}}
|
||||
}
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! mod_dtor {
|
||||
( $($body:block)? ) => {
|
||||
$crate::mod_fini! {{
|
||||
$crate::debug_info!("Module unloading");
|
||||
$($body)?
|
||||
$crate::mods::canary::report();
|
||||
}}
|
||||
}
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! mod_init {
|
||||
($body:block) => {
|
||||
#[used]
|
||||
#[cfg_attr(target_family = "unix", unsafe(link_section = ".init_array"))]
|
||||
static MOD_INIT: unsafe extern "C" fn() = { _mod_init };
|
||||
|
||||
#[cfg_attr(target_family = "unix", unsafe(link_section = ".text.startup"))]
|
||||
unsafe extern "C" fn _mod_init() -> () $body
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! mod_fini {
|
||||
($body:block) => {
|
||||
#[used]
|
||||
#[cfg_attr(target_family = "unix", unsafe(link_section = ".fini_array"))]
|
||||
static MOD_FINI: unsafe extern "C" fn() = { _mod_fini };
|
||||
|
||||
#[cfg_attr(target_family = "unix", unsafe(link_section = ".text.startup"))]
|
||||
unsafe extern "C" fn _mod_fini() -> () $body
|
||||
};
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
#![cfg(all(conduwuit_mods, feature = "conduwuit_mods"))]
|
||||
|
||||
pub(crate) use libloading::os::unix::{Library, Symbol};
|
||||
|
||||
pub mod canary;
|
||||
pub mod macros;
|
||||
pub mod module;
|
||||
pub mod new;
|
||||
pub mod path;
|
||||
|
||||
pub use module::Module;
|
||||
@@ -1,75 +0,0 @@
|
||||
use std::{
|
||||
ffi::{CString, OsString},
|
||||
time::SystemTime,
|
||||
};
|
||||
|
||||
use super::{Library, Symbol, canary, new, path};
|
||||
use crate::{Result, error};
|
||||
|
||||
pub struct Module {
|
||||
handle: Option<Library>,
|
||||
loaded: SystemTime,
|
||||
path: OsString,
|
||||
}
|
||||
|
||||
impl Module {
|
||||
pub fn from_name(name: &str) -> Result<Self> { Self::from_path(path::from_name(name)?) }
|
||||
|
||||
pub fn from_path(path: OsString) -> Result<Self> {
|
||||
Ok(Self {
|
||||
handle: Some(new::from_path(&path)?),
|
||||
loaded: SystemTime::now(),
|
||||
path,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn unload(&mut self) {
|
||||
canary::prepare();
|
||||
self.close();
|
||||
if !canary::check_and_reset() {
|
||||
let name = self.name().expect("Module is named");
|
||||
error!("Module {name:?} is stuck and failed to unload.");
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn close(&mut self) {
|
||||
if let Some(handle) = self.handle.take() {
|
||||
handle.close().expect("Module handle closed");
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get<Prototype>(&self, name: &str) -> Result<Symbol<Prototype>> {
|
||||
let cname = CString::new(name.to_owned()).expect("terminated string from provided name");
|
||||
let handle = self
|
||||
.handle
|
||||
.as_ref()
|
||||
.expect("backing library loaded by this instance");
|
||||
|
||||
// SAFETY: Calls dlsym(3) on unix platforms. This might not have to be
|
||||
// unsafe if wrapped in libloading with_dlerror().
|
||||
let sym = unsafe { handle.get::<Prototype>(cname.as_bytes()) };
|
||||
let sym = sym.expect("symbol found; binding successful");
|
||||
|
||||
Ok(sym)
|
||||
}
|
||||
|
||||
pub fn deleted(&self) -> Result<bool> {
|
||||
let mtime = path::mtime(self.path())?;
|
||||
let res = mtime > self.loaded;
|
||||
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
pub fn name(&self) -> Result<String> { path::to_name(self.path()) }
|
||||
|
||||
#[must_use]
|
||||
pub fn path(&self) -> &OsString { &self.path }
|
||||
}
|
||||
|
||||
impl Drop for Module {
|
||||
fn drop(&mut self) {
|
||||
if self.handle.is_some() {
|
||||
self.unload();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
use std::ffi::OsStr;
|
||||
|
||||
use super::{Library, path};
|
||||
use crate::{Err, Result};
|
||||
|
||||
const OPEN_FLAGS: i32 = libloading::os::unix::RTLD_LAZY | libloading::os::unix::RTLD_GLOBAL;
|
||||
|
||||
pub fn from_name(name: &str) -> Result<Library> {
|
||||
let path = path::from_name(name)?;
|
||||
from_path(&path)
|
||||
}
|
||||
|
||||
pub fn from_path(path: &OsStr) -> Result<Library> {
|
||||
//SAFETY: Calls dlopen(3) on unix platforms. This might not have to be
|
||||
// unsafe if wrapped in with_dlerror.
|
||||
let lib = unsafe { Library::open(Some(path), OPEN_FLAGS) };
|
||||
if let Err(e) = lib {
|
||||
let name = path::to_name(path)?;
|
||||
return Err!("Loading module {name:?} failed: {e}");
|
||||
}
|
||||
|
||||
Ok(lib.expect("module loaded"))
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
use std::{
|
||||
env::current_exe,
|
||||
ffi::{OsStr, OsString},
|
||||
path::{Path, PathBuf},
|
||||
time::SystemTime,
|
||||
};
|
||||
|
||||
use libloading::library_filename;
|
||||
|
||||
use crate::Result;
|
||||
|
||||
pub fn from_name(name: &str) -> Result<OsString> {
|
||||
let root = PathBuf::new();
|
||||
let exe_path = current_exe()?;
|
||||
let exe_dir = exe_path.parent().unwrap_or(&root);
|
||||
let mut mod_path = exe_dir.to_path_buf();
|
||||
let mod_file = library_filename(name);
|
||||
mod_path.push(mod_file);
|
||||
|
||||
Ok(mod_path.into_os_string())
|
||||
}
|
||||
|
||||
pub fn to_name(path: &OsStr) -> Result<String> {
|
||||
let path = Path::new(path);
|
||||
let name = path
|
||||
.file_stem()
|
||||
.expect("path file stem")
|
||||
.to_str()
|
||||
.expect("name string");
|
||||
|
||||
let name = name.strip_prefix("lib").unwrap_or(name).to_owned();
|
||||
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
pub fn mtime(path: &OsStr) -> Result<SystemTime> {
|
||||
let meta = std::fs::metadata(path)?;
|
||||
let mtime = meta.modified()?;
|
||||
|
||||
Ok(mtime)
|
||||
}
|
||||
@@ -27,10 +27,6 @@ pub struct Server {
|
||||
/// observable used on shutdown and should not be modified.
|
||||
pub stopping: AtomicBool,
|
||||
|
||||
/// Reload/shutdown desired indicator; when false, shutdown is desired. This
|
||||
/// is an observable used on shutdown and modifying is not recommended.
|
||||
pub reloading: AtomicBool,
|
||||
|
||||
/// Restart desired; when true, restart it desired after shutdown.
|
||||
pub restarting: AtomicBool,
|
||||
|
||||
@@ -60,7 +56,6 @@ impl Server {
|
||||
config: config::Manager::new(config),
|
||||
started: SystemTime::now(),
|
||||
stopping: AtomicBool::new(false),
|
||||
reloading: AtomicBool::new(false),
|
||||
restarting: AtomicBool::new(false),
|
||||
runtime,
|
||||
signal: broadcast::channel::<&'static str>(1).0,
|
||||
@@ -69,25 +64,6 @@ impl Server {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reload(&self) -> Result<()> {
|
||||
if cfg!(any(not(conduwuit_mods), not(feature = "conduwuit_mods"))) {
|
||||
return Err!("Reloading not enabled");
|
||||
}
|
||||
|
||||
if self.reloading.swap(true, Ordering::AcqRel) {
|
||||
return Err!("Reloading already in progress");
|
||||
}
|
||||
|
||||
if self.stopping.swap(true, Ordering::AcqRel) {
|
||||
return Err!("Shutdown already in progress");
|
||||
}
|
||||
|
||||
self.signal("SIGINT").inspect_err(|_| {
|
||||
self.stopping.store(false, Ordering::Release);
|
||||
self.reloading.store(false, Ordering::Release);
|
||||
})
|
||||
}
|
||||
|
||||
pub fn restart(&self) -> Result {
|
||||
if self.restarting.swap(true, Ordering::AcqRel) {
|
||||
return Err!("Restart already in progress");
|
||||
@@ -146,9 +122,6 @@ impl Server {
|
||||
#[inline]
|
||||
pub fn is_stopping(&self) -> bool { self.stopping.load(Ordering::Relaxed) }
|
||||
|
||||
#[inline]
|
||||
pub fn is_reloading(&self) -> bool { self.reloading.load(Ordering::Relaxed) }
|
||||
|
||||
#[inline]
|
||||
pub fn is_restarting(&self) -> bool { self.restarting.load(Ordering::Relaxed) }
|
||||
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
//! Extended external extensions to futures::FutureExt
|
||||
|
||||
use std::marker::Unpin;
|
||||
|
||||
use futures::{
|
||||
Future, FutureExt,
|
||||
future::{select_ok, try_join, try_join_all, try_select},
|
||||
future::{try_join, try_join_all},
|
||||
};
|
||||
|
||||
pub trait BoolExt
|
||||
@@ -18,8 +16,8 @@ where
|
||||
|
||||
fn or<B>(self, b: B) -> impl Future<Output = bool> + Send
|
||||
where
|
||||
B: Future<Output = bool> + Send + Unpin,
|
||||
Self: Sized + Unpin;
|
||||
B: Future<Output = bool> + Send,
|
||||
Self: Sized;
|
||||
}
|
||||
|
||||
impl<Fut> BoolExt for Fut
|
||||
@@ -44,20 +42,20 @@ where
|
||||
#[inline]
|
||||
fn or<B>(self, b: B) -> impl Future<Output = bool> + Send
|
||||
where
|
||||
B: Future<Output = bool> + Send + Unpin,
|
||||
Self: Sized + Unpin,
|
||||
B: Future<Output = bool> + Send,
|
||||
Self: Sized,
|
||||
{
|
||||
type Result = crate::Result<(), ()>;
|
||||
|
||||
let a = self.map(|a| a.then_some(()).ok_or(Result::Err(())));
|
||||
let a = self.map(|a| (!a).then_some(()).ok_or(Result::Err(())));
|
||||
|
||||
let b = b.map(|b| b.then_some(()).ok_or(Result::Err(())));
|
||||
let b = b.map(|b| (!b).then_some(()).ok_or(Result::Err(())));
|
||||
|
||||
try_select(a, b).map(|result| result.is_ok())
|
||||
try_join(a, b).map(|result| result.is_err())
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn and<I, F>(args: I) -> impl Future<Output = bool> + Send
|
||||
pub fn and<I, F>(args: I) -> impl Future<Output = bool> + Send
|
||||
where
|
||||
I: Iterator<Item = F> + Send,
|
||||
F: Future<Output = bool> + Send,
|
||||
@@ -69,14 +67,80 @@ where
|
||||
try_join_all(args).map(|result| result.is_ok())
|
||||
}
|
||||
|
||||
pub async fn or<I, F>(args: I) -> impl Future<Output = bool> + Send
|
||||
pub fn or<I, F>(args: I) -> impl Future<Output = bool> + Send
|
||||
where
|
||||
I: Iterator<Item = F> + Send,
|
||||
F: Future<Output = bool> + Send + Unpin,
|
||||
F: Future<Output = bool> + Send,
|
||||
{
|
||||
type Result = crate::Result<(), ()>;
|
||||
|
||||
let args = args.map(|a| a.map(|a| a.then_some(()).ok_or(Result::Err(()))));
|
||||
let args = args.map(|a| a.map(|a| (!a).then_some(()).ok_or(Result::Err(()))));
|
||||
|
||||
select_ok(args).map(|result| result.is_ok())
|
||||
try_join_all(args).map(|result| result.is_err())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::pin::pin;
|
||||
|
||||
use futures::future;
|
||||
|
||||
use super::{BoolExt, and, or};
|
||||
|
||||
#[tokio::test]
|
||||
async fn bool_ext_truth_tables() {
|
||||
for a in [false, true] {
|
||||
for b in [false, true] {
|
||||
assert_eq!(future::ready(a).and(future::ready(b)).await, a && b, "and({a}, {b})");
|
||||
assert_eq!(future::ready(a).or(future::ready(b)).await, a || b, "or({a}, {b})");
|
||||
}
|
||||
}
|
||||
|
||||
assert!(
|
||||
future::ready(false)
|
||||
.or(future::ready(false))
|
||||
.or(future::ready(true))
|
||||
.await,
|
||||
"chained or with trailing true must return true"
|
||||
);
|
||||
assert!(
|
||||
!future::ready(false)
|
||||
.or(future::ready(false))
|
||||
.or(future::ready(false))
|
||||
.await,
|
||||
"chained or with all false must return false"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bool_ext_short_circuits() {
|
||||
let pend = pin!(future::pending::<bool>());
|
||||
assert!(
|
||||
future::ready(true).or(pend).await,
|
||||
"or must short-circuit on true without polling pending"
|
||||
);
|
||||
|
||||
let pend = pin!(future::pending::<bool>());
|
||||
assert!(
|
||||
!future::ready(false).and(pend).await,
|
||||
"and must short-circuit on false without polling pending"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn free_and_or() {
|
||||
assert!(and(std::iter::empty::<future::Ready<bool>>()).await, "empty and is true");
|
||||
assert!(!or(std::iter::empty::<future::Ready<bool>>()).await, "empty or is false");
|
||||
|
||||
assert!(and([future::ready(true), future::ready(true)].into_iter()).await, "all true");
|
||||
assert!(
|
||||
!and([future::ready(true), future::ready(false)].into_iter()).await,
|
||||
"and with false"
|
||||
);
|
||||
assert!(
|
||||
or([future::ready(false), future::ready(true)].into_iter()).await,
|
||||
"or with true"
|
||||
);
|
||||
assert!(!or([future::ready(false), future::ready(false)].into_iter()).await, "all false");
|
||||
}
|
||||
}
|
||||
+47
-3
@@ -62,14 +62,28 @@ macro_rules! validated {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[allow(clippy::as_conversions)]
|
||||
#[allow(clippy::as_conversions, clippy::cast_possible_truncation, clippy::cast_sign_loss)]
|
||||
pub fn usize_from_f64(val: f64) -> Result<usize, Error> {
|
||||
// Exclusive upper bound for values whose truncation fits in `usize`.
|
||||
// Note that `usize::MAX as f64` rounds up to 2^64 on 64-bit targets, so a
|
||||
// strict `<` check against 2^(usize::BITS) rejects all out-of-range values
|
||||
// on both 32-bit and 64-bit targets.
|
||||
#[allow(clippy::cast_precision_loss)]
|
||||
const MAX_USIZE_EXCLUSIVE: f64 = (1_u128 << usize::BITS) as f64;
|
||||
|
||||
if !val.is_finite() {
|
||||
return Err!(Arithmetic("Converting non-finite float to unsigned integer"));
|
||||
}
|
||||
|
||||
if val < 0.0 {
|
||||
return Err!(Arithmetic("Converting negative float to unsigned integer"));
|
||||
}
|
||||
|
||||
//SAFETY: <https://doc.rust-lang.org/std/primitive.f64.html#method.to_int_unchecked>
|
||||
Ok(unsafe { val.to_int_unchecked::<usize>() })
|
||||
if val >= MAX_USIZE_EXCLUSIVE {
|
||||
return Err!(Arithmetic("Converting out-of-range float to unsigned integer"));
|
||||
}
|
||||
|
||||
Ok(val as usize)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -111,3 +125,33 @@ fn try_into_err<Dst: TryFrom<Src>, Src>(e: <Dst as TryFrom<Src>>::Error) -> Erro
|
||||
|
||||
#[inline]
|
||||
pub fn clamp<T: Ord>(val: T, min: T, max: T) -> T { cmp::min(cmp::max(val, min), max) }
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn usize_from_f64_valid() {
|
||||
assert_eq!(usize_from_f64(0.0).unwrap(), 0);
|
||||
assert_eq!(usize_from_f64(-0.0).unwrap(), 0);
|
||||
assert_eq!(usize_from_f64(42.9).unwrap(), 42);
|
||||
assert_eq!(usize_from_f64(1_048_576.0).unwrap(), 1_048_576);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usize_from_f64_rejects_invalid() {
|
||||
usize_from_f64(-1.0).unwrap_err();
|
||||
usize_from_f64(-0.5).unwrap_err();
|
||||
usize_from_f64(f64::NAN).unwrap_err();
|
||||
usize_from_f64(f64::INFINITY).unwrap_err();
|
||||
usize_from_f64(f64::NEG_INFINITY).unwrap_err();
|
||||
usize_from_f64(1e30).unwrap_err();
|
||||
#[cfg(target_pointer_width = "64")]
|
||||
{
|
||||
// `usize::MAX as f64` rounds up to 2^64, which is out of range.
|
||||
#[allow(clippy::as_conversions, clippy::cast_precision_loss)]
|
||||
let rounded_max = usize::MAX as f64;
|
||||
usize_from_f64(rounded_max).unwrap_err();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
use std::convert::Infallible;
|
||||
|
||||
use super::{DebugInspect, Result};
|
||||
use crate::error;
|
||||
use super::Result;
|
||||
|
||||
pub trait UnwrapInfallible<T> {
|
||||
fn unwrap_infallible(self) -> T;
|
||||
@@ -10,8 +9,7 @@ pub trait UnwrapInfallible<T> {
|
||||
impl<T> UnwrapInfallible<T> for Result<T, Infallible> {
|
||||
#[inline]
|
||||
fn unwrap_infallible(self) -> T {
|
||||
// SAFETY: Branchless unwrap for errors that can never happen. In debug
|
||||
// mode this is asserted.
|
||||
unsafe { self.debug_inspect_err(error::infallible).unwrap_unchecked() }
|
||||
let Ok(val) = self;
|
||||
val
|
||||
}
|
||||
}
|
||||
@@ -32,11 +32,12 @@ impl<'a> From<&'a str> for &'a Unquoted {
|
||||
fn from(s: &'a str) -> &'a Unquoted {
|
||||
let s: &'a str = s.unquote_infallible();
|
||||
|
||||
//SAFETY: This is a pattern I lifted from ruma-identifiers for
|
||||
// strong-type strs by wrapping in a tuple-struct.
|
||||
#[allow(clippy::transmute_ptr_to_ptr)]
|
||||
// SAFETY: `Unquoted` is `#[repr(transparent)]` over `str`, so
|
||||
// `*const str` and `*const Unquoted` have identical layout and
|
||||
// metadata, and the returned reference preserves lifetime `'a`.
|
||||
#[allow(clippy::as_conversions)]
|
||||
unsafe {
|
||||
std::mem::transmute(s)
|
||||
&*(std::ptr::from_ref::<str>(s) as *const Unquoted)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,21 +120,13 @@ pub fn cores_available() -> impl Iterator<Item = Id> { from_mask(*CORES_AVAILABL
|
||||
pub fn getcpu() -> Result<usize> {
|
||||
use crate::{Error, utils::math};
|
||||
|
||||
// SAFETY: This is part of an interface with many low-level calls taking
|
||||
// many raw params, but it's unclear why this specific call is unsafe.
|
||||
// Nevertheless the value obtained here is semantically unsafe because it
|
||||
// can change on the instruction boundary trailing its own acquisition and
|
||||
// also any other time.
|
||||
// SAFETY: `sched_getcpu(2)` takes no pointers and has no preconditions.
|
||||
// Note that it may still return -1 with errno set (e.g. under seccomp
|
||||
// filters or kernels without getcpu support), so the error branch below
|
||||
// must remain live.
|
||||
let ret: i32 = unsafe { libc::sched_getcpu() };
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
// SAFETY: On modern linux systems with a vdso if we can optimize away the branch checking
|
||||
// for error (see getcpu(2)) then this system call becomes a memory access.
|
||||
unsafe {
|
||||
std::hint::assert_unchecked(ret >= 0);
|
||||
};
|
||||
|
||||
if ret == -1 {
|
||||
if ret < 0 {
|
||||
return Err(Error::from_errno());
|
||||
}
|
||||
|
||||
|
||||
@@ -472,17 +472,5 @@ impl<'a, 'de: 'a> de::MapAccess<'de> for &'a mut Deserializer<'de> {
|
||||
}
|
||||
}
|
||||
|
||||
// activate when stable; too soon now
|
||||
//#[cfg(debug_assertions)]
|
||||
#[inline]
|
||||
fn deserialize_str(input: &[u8]) -> Result<&str> { string::str_from_bytes(input) }
|
||||
|
||||
//#[cfg(not(debug_assertions))]
|
||||
#[cfg(disable)]
|
||||
#[inline]
|
||||
fn deserialize_str(input: &[u8]) -> Result<&str> {
|
||||
// SAFETY: Strings were written by the serializer to the database. Assuming
|
||||
// no database corruption, the string will be valid. Database corruption is
|
||||
// detected via rocksdb checksums.
|
||||
unsafe { std::str::from_utf8_unchecked(input) }
|
||||
}
|
||||
@@ -46,6 +46,10 @@ use crate::{Engine, watchers::Watchers};
|
||||
pub struct Map {
|
||||
name: &'static str,
|
||||
watchers: Watchers,
|
||||
/// SAFETY / DROP ORDER: `cf` holds a lifetime-erased RocksDB column family
|
||||
/// handle (see `open::open`) and MUST be declared before `db` so that the
|
||||
/// handle is destroyed before `Engine` (and the underlying RocksDB `DB`)
|
||||
/// can be dropped.
|
||||
cf: Arc<ColumnFamily>,
|
||||
db: Arc<Engine>,
|
||||
read_options: ReadOptions,
|
||||
|
||||
@@ -1,10 +1,24 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use rocksdb::ColumnFamily;
|
||||
use rocksdb::{BoundColumnFamily, ColumnFamily};
|
||||
|
||||
use crate::Engine;
|
||||
|
||||
pub(super) fn open(db: &Arc<Engine>, name: &str) -> Arc<ColumnFamily> {
|
||||
// Compile-time guard: `BoundColumnFamily` and `ColumnFamily` are both
|
||||
// `#[repr(Rust)]` in `rust-rocksdb`, so fail compilation if their size or
|
||||
// alignment ever diverge.
|
||||
const {
|
||||
assert!(
|
||||
size_of::<BoundColumnFamily<'_>>() == size_of::<ColumnFamily>(),
|
||||
"BoundColumnFamily and ColumnFamily must have identical size"
|
||||
);
|
||||
assert!(
|
||||
align_of::<BoundColumnFamily<'_>>() == align_of::<ColumnFamily>(),
|
||||
"BoundColumnFamily and ColumnFamily must have identical alignment"
|
||||
);
|
||||
}
|
||||
|
||||
let bounded_arc = db.cf(name);
|
||||
let bounded_ptr = Arc::into_raw(bounded_arc);
|
||||
let cf_ptr = bounded_ptr.cast::<ColumnFamily>();
|
||||
|
||||
@@ -12,6 +12,17 @@ impl super::Map {
|
||||
/// Iterate key-value entries in the map from the beginning.
|
||||
///
|
||||
/// - Result is deserialized
|
||||
///
|
||||
/// # Unsoundness
|
||||
/// Because Rust's `Stream` trait does not support lending items tied to
|
||||
/// `&mut self`, `stream::slice_longevity` unsafely extends the lifetime of
|
||||
/// raw RocksDB iterator slices to `'a` (the borrow of `Arc<Map>`). As a
|
||||
/// consequence, borrowed deserialized types (e.g. `&str`, `&UserId`,
|
||||
/// `&[u8]`) reference the underlying RocksDB cursor buffer and are
|
||||
/// invalidated on the next poll of the stream. Do not hold borrowed items
|
||||
/// across polls (e.g. via `collect()`, `ready_chunks()`, `peekable()`,
|
||||
/// `buffered()`, `buffer_unordered()`, `broadband`, or `wideband`) without
|
||||
/// converting them to owned values first.
|
||||
pub fn stream<'a, K, V>(
|
||||
self: &'a Arc<Self>,
|
||||
) -> impl Stream<Item = Result<KeyVal<'a, K, V>>> + Send
|
||||
|
||||
@@ -232,6 +232,10 @@ pub(super) static MAPS: &[Descriptor] = &[
|
||||
name: "roomsynctoken_shortstatehash",
|
||||
..descriptor::DROPPED
|
||||
},
|
||||
Descriptor {
|
||||
name: "roomts_pduid",
|
||||
..descriptor::SEQUENTIAL_SMALL
|
||||
},
|
||||
Descriptor {
|
||||
name: "roomuserdataid_accountdata",
|
||||
..descriptor::RANDOM_SMALL
|
||||
@@ -403,6 +407,10 @@ pub(super) static MAPS: &[Descriptor] = &[
|
||||
name: "userdeviceid_token",
|
||||
..descriptor::RANDOM_SMALL
|
||||
},
|
||||
Descriptor {
|
||||
name: "userdeviceid_previoustoken",
|
||||
..descriptor::RANDOM_SMALL
|
||||
},
|
||||
Descriptor {
|
||||
name: "userdevicesessionid_uiaainfo",
|
||||
..descriptor::RANDOM_SMALL
|
||||
|
||||
@@ -5,9 +5,6 @@ extern crate rust_rocksdb as rocksdb;
|
||||
|
||||
conduwuit_macros::introspect_crate! {}
|
||||
|
||||
conduwuit::mod_ctor! {}
|
||||
conduwuit::mod_dtor! {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod benches;
|
||||
mod cork;
|
||||
|
||||
+23
-11
@@ -54,8 +54,14 @@ pub(crate) struct Get {
|
||||
/// Note: only initial seek is supported at this time on the assumption rocksdb
|
||||
/// prefetching prevents mid-iteration polls from blocking on I/O.
|
||||
pub(crate) struct Seek {
|
||||
pub(crate) map: Arc<Map>,
|
||||
/// SAFETY / DROP ORDER: `state` wraps a RocksDB
|
||||
/// `DBRawIteratorWithThreadMode` referencing `map.db.db` whose lifetime has
|
||||
/// been erased to `'static`. `state` MUST be declared before `map` so the
|
||||
/// iterator is destroyed before `map` (and potentially the last
|
||||
/// `Arc<Engine>`) can be dropped if `Seek` is dropped early (e.g. on
|
||||
/// cancellation or queue closure).
|
||||
pub(crate) state: stream::State<'static>,
|
||||
pub(crate) map: Arc<Map>,
|
||||
pub(crate) dir: Direction,
|
||||
pub(crate) key: Option<KeyBuf>,
|
||||
pub(crate) res: Option<ResultSender<stream::State<'static>>>,
|
||||
@@ -416,24 +422,30 @@ impl Drop for Pool {
|
||||
}
|
||||
|
||||
fn into_send_get(result: BatchResult<'_>) -> BatchResult<'static> {
|
||||
// SAFETY: Necessary to send the Handle (rust_rocksdb::PinnableSlice)
|
||||
// through the channel. The lifetime on the handle is a device by
|
||||
// rust-rocksdb to associate a database lifetime with its assets. The
|
||||
// Handle must be dropped before the database is dropped.
|
||||
// SAFETY: Necessary to send `Handle` (which wraps
|
||||
// `rocksdb::DBPinnableSlice`) through the oneshot channel. The lifetime on
|
||||
// `Handle` ties it to the RocksDB `DB` instance; callers of `execute_get`
|
||||
// borrow `&self.db.pool` (which is owned by `Engine`), ensuring the
|
||||
// received `BatchResult<'_>` cannot outlive the database.
|
||||
unsafe { std::mem::transmute(result) }
|
||||
}
|
||||
|
||||
fn into_recv_get<'a>(result: BatchResult<'static>) -> BatchResult<'a> {
|
||||
// SAFETY: This is to receive the Handle from the channel.
|
||||
// SAFETY: Shrinking the erased `'static` lifetime back to `'a` (borrowed
|
||||
// from `&self.db.pool`). `SmallVec<A>` is invariant over `A`, so this
|
||||
// cannot be done via implicit covariance.
|
||||
unsafe { std::mem::transmute(result) }
|
||||
}
|
||||
|
||||
pub(crate) fn into_send_seek(result: stream::State<'_>) -> stream::State<'static> {
|
||||
// SAFETY: Necessary to send the State through the channel; see above.
|
||||
// SAFETY: Necessary to send `stream::State` through the pool channel.
|
||||
// While in flight on the queue, `Seek` owns an `Arc<Map>` (declared after
|
||||
// `state` so `state` drops first on early cancellation); once received back
|
||||
// from `execute_iter`, the lifetime is shrunk via `into_recv_seek` to the
|
||||
// caller's borrow of `&self.db.pool` (and `&'a Arc<Map>`), ensuring the
|
||||
// returned `stream::State<'_>` cannot outlive the database.
|
||||
unsafe { std::mem::transmute(result) }
|
||||
}
|
||||
|
||||
fn into_recv_seek(result: stream::State<'static>) -> stream::State<'static> {
|
||||
// SAFETY: This is to receive the State from the channel; see above.
|
||||
unsafe { std::mem::transmute(result) }
|
||||
}
|
||||
#[inline]
|
||||
const fn into_recv_seek<'a>(result: stream::State<'static>) -> stream::State<'a> { result }
|
||||
+14
-16
@@ -133,22 +133,20 @@ fn keyval_longevity<'a, 'b: 'a>(item: KeyVal<'a>) -> KeyVal<'b> {
|
||||
}
|
||||
|
||||
fn slice_longevity<'a, 'b: 'a>(item: &'a Slice) -> &'b Slice {
|
||||
// SAFETY: The lifetime of the data returned by the rocksdb cursor is only
|
||||
// valid between each movement of the cursor. It is hereby unsafely
|
||||
// extended to match the lifetime of the cursor itself. This is due to the
|
||||
// limitation of the Stream trait where the Item is incapable of conveying
|
||||
// a lifetime; this is due to GAT's being unstable during its development.
|
||||
// This unsafety can be removed as soon as this limitation is addressed by
|
||||
// an upcoming version.
|
||||
// SAFETY: the lifetime of the data returned by
|
||||
// the RocksDB cursor is only valid until the next movement of the cursor,
|
||||
// but is unsafely extended here to match the lifetime `'b` of the `Map`
|
||||
// borrow because `futures::Stream` is not a lending stream.
|
||||
//
|
||||
// We have done our best to mitigate the implications of this in conjunction
|
||||
// with the deserialization API such that borrows being held across
|
||||
// movements of the cursor do not happen accidentally. The compiler will
|
||||
// still error when values herein produced try to leave a closure passed to
|
||||
// a StreamExt API. But escapes can happen if you explicitly and
|
||||
// intentionally attempt it, and there will be no compiler error or
|
||||
// warning. This is primarily the case with calling collect() without a
|
||||
// preceding map(ToOwned::to_owned). A collection of references here is
|
||||
// illegal, but this will not be enforced by the compiler.
|
||||
// Callers MUST NOT hold borrowed items (or borrowed deserialized views such
|
||||
// as `&str`, `&UserId`, or `&[u8]`) across subsequent polls of the stream —
|
||||
// in particular, never call `collect()`, `ready_chunks()`, `peekable()`,
|
||||
// `buffered()`, `buffer_unordered()`, `broadband`, or `wideband` on a
|
||||
// stream yielding borrowed references without first converting items to
|
||||
// owned values (e.g. `map(ToOwned::to_owned)`). The compiler does NOT
|
||||
// reject such escapes when items borrow from `'b`.
|
||||
//
|
||||
// TODO: Fix this, it is old code and language changes may have made it
|
||||
// unnecessary
|
||||
unsafe { std::mem::transmute(item) }
|
||||
}
|
||||
@@ -1,28 +1,12 @@
|
||||
use conduwuit::Result;
|
||||
use rocksdb::{Direction, ErrorKind, IteratorMode};
|
||||
|
||||
//#[cfg(debug_assertions)]
|
||||
macro_rules! unhandled {
|
||||
($msg:literal) => {
|
||||
unimplemented!($msg)
|
||||
};
|
||||
}
|
||||
|
||||
// activate when stable; we're not ready for this yet
|
||||
#[cfg(disable)] // #[cfg(not(debug_assertions))]
|
||||
macro_rules! unhandled {
|
||||
($msg:literal) => {
|
||||
// SAFETY: Eliminates branches for serializing and deserializing types never
|
||||
// encountered in the codebase. This can promote optimization and reduce
|
||||
// codegen. The developer must verify for every invoking callsite that the
|
||||
// unhandled type is in no way involved and could not possibly be
|
||||
// encountered.
|
||||
unsafe {
|
||||
std::hint::unreachable_unchecked();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) use unhandled;
|
||||
|
||||
#[inline]
|
||||
|
||||
@@ -175,9 +175,6 @@ zstd_compression = [
|
||||
"conduwuit-router/zstd_compression",
|
||||
"conduwuit-service/zstd_compression",
|
||||
]
|
||||
conduwuit_mods = [
|
||||
"conduwuit-core/conduwuit_mods",
|
||||
]
|
||||
bindgen-static = [
|
||||
# "bindgen/static"
|
||||
# "clang-sys/static"
|
||||
|
||||
+2
-38
@@ -10,7 +10,6 @@ mod clap;
|
||||
mod deadlock;
|
||||
mod logging;
|
||||
mod metrics;
|
||||
mod mods;
|
||||
mod panic;
|
||||
mod restart;
|
||||
mod runtime;
|
||||
@@ -63,9 +62,8 @@ pub fn run_with_args(args: &Args) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Operate the server normally in release-mode static builds. This will start,
|
||||
/// run and stop the server within the asynchronous runtime.
|
||||
#[cfg(any(not(conduwuit_mods), not(feature = "conduwuit_mods")))]
|
||||
/// Operate the server. This will start, run and stop the server within the
|
||||
/// asynchronous runtime.
|
||||
#[tracing::instrument(
|
||||
name = "main",
|
||||
parent = None,
|
||||
@@ -114,37 +112,3 @@ async fn async_main(server: &Arc<Server>) -> Result<(), Error> {
|
||||
debug_info!("Exit runtime");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Operate the server in developer-mode dynamic builds. This will start, run,
|
||||
/// and hot-reload portions of the server as-needed before returning for an
|
||||
/// actual shutdown. This is not available in release-mode or static builds.
|
||||
#[cfg(all(conduwuit_mods, feature = "conduwuit_mods"))]
|
||||
async fn async_main(server: &Arc<Server>) -> Result<(), Error> {
|
||||
let mut starts = true;
|
||||
let mut reloads = true;
|
||||
while reloads {
|
||||
if let Err(error) = mods::open(server).await {
|
||||
error!("Loading router: {error}");
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
let result = mods::run(server, starts).await;
|
||||
if let Ok(result) = result {
|
||||
(starts, reloads) = result;
|
||||
}
|
||||
|
||||
let force = !reloads || result.is_err();
|
||||
if let Err(error) = mods::close(server, force).await {
|
||||
error!("Unloading router: {error}");
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
if let Err(error) = result {
|
||||
error!("{error}");
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
|
||||
debug_info!("Exit runtime");
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
#![cfg(all(conduwuit_mods, feature = "conduwuit_mods"))]
|
||||
|
||||
#[unsafe(no_link)]
|
||||
extern crate conduwuit_service;
|
||||
|
||||
use std::{
|
||||
future::Future,
|
||||
pin::Pin,
|
||||
sync::{Arc, atomic::Ordering},
|
||||
};
|
||||
|
||||
use conduwuit_core::{Error, Result, debug, error, mods};
|
||||
use conduwuit_service::Services;
|
||||
|
||||
use crate::Server;
|
||||
|
||||
type StartFuncResult = Pin<Box<dyn Future<Output = Result<Arc<Services>>> + Send>>;
|
||||
type StartFuncProto = fn(&Arc<conduwuit_core::Server>) -> StartFuncResult;
|
||||
|
||||
type RunFuncResult = Pin<Box<dyn Future<Output = Result<()>> + Send>>;
|
||||
type RunFuncProto = fn(&Arc<Services>) -> RunFuncResult;
|
||||
|
||||
type StopFuncResult = Pin<Box<dyn Future<Output = Result<()>> + Send>>;
|
||||
type StopFuncProto = fn(Arc<Services>) -> StopFuncResult;
|
||||
|
||||
const RESTART_THRESH: &str = "conduwuit_service";
|
||||
const MODULE_NAMES: &[&str] = &[
|
||||
//"conduwuit_core",
|
||||
"conduwuit_database",
|
||||
"conduwuit_service",
|
||||
"conduwuit_api",
|
||||
"conduwuit_admin",
|
||||
"conduwuit_router",
|
||||
];
|
||||
|
||||
#[cfg(panic_trap)]
|
||||
conduwuit_core::mod_init! {{
|
||||
conduwuit_core::debug::set_panic_trap();
|
||||
}}
|
||||
|
||||
pub(crate) async fn run(server: &Arc<Server>, starts: bool) -> Result<(bool, bool), Error> {
|
||||
let main_lock = server.mods.read().await;
|
||||
let main_mod = (*main_lock).last().expect("main module loaded");
|
||||
if starts {
|
||||
let start = main_mod.get::<StartFuncProto>("start")?;
|
||||
match start(&server.server).await {
|
||||
| Ok(services) => server.services.lock().await.insert(services),
|
||||
| Err(error) => {
|
||||
error!("Starting server: {error}");
|
||||
return Err(error);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
server.server.stopping.store(false, Ordering::Release);
|
||||
|
||||
let run = main_mod.get::<RunFuncProto>("run")?;
|
||||
if let Err(error) = run(server
|
||||
.services
|
||||
.lock()
|
||||
.await
|
||||
.as_ref()
|
||||
.expect("services initialized"))
|
||||
.await
|
||||
{
|
||||
error!("Running server: {error}");
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
let reloads = server.server.reloading.swap(false, Ordering::AcqRel);
|
||||
|
||||
let stops = !reloads || stale_from_mods(&main_lock)? <= restart_thresh();
|
||||
let starts = reloads && stops;
|
||||
if stops {
|
||||
let stop = main_mod.get::<StopFuncProto>("stop")?;
|
||||
if let Err(error) = stop(
|
||||
server
|
||||
.services
|
||||
.lock()
|
||||
.await
|
||||
.take()
|
||||
.expect("services initialized"),
|
||||
)
|
||||
.await
|
||||
{
|
||||
error!("Stopping server: {error}");
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
|
||||
Ok((starts, reloads))
|
||||
}
|
||||
|
||||
pub(crate) async fn open(server: &Arc<Server>) -> Result<usize, Error> {
|
||||
let mut mods_lock = server.mods.write().await;
|
||||
let mods: &mut Vec<mods::Module> = &mut mods_lock;
|
||||
debug!(
|
||||
available = %available(),
|
||||
loaded = %mods.len(),
|
||||
"Loading modules",
|
||||
);
|
||||
|
||||
for (i, name) in MODULE_NAMES.iter().enumerate() {
|
||||
if mods.get(i).is_none() {
|
||||
mods.push(mods::Module::from_name(name)?);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(mods.len())
|
||||
}
|
||||
|
||||
pub(crate) async fn close(server: &Arc<Server>, force: bool) -> Result<usize, Error> {
|
||||
let stale = stale_count(server).await;
|
||||
let mut mods_lock = server.mods.write().await;
|
||||
let mods: &mut Vec<mods::Module> = &mut mods_lock;
|
||||
debug!(
|
||||
available = %available(),
|
||||
loaded = %mods.len(),
|
||||
stale = %stale,
|
||||
force,
|
||||
"Unloading modules",
|
||||
);
|
||||
|
||||
while mods.last().is_some() {
|
||||
let module = &mods.last().expect("module");
|
||||
if force || module.deleted()? {
|
||||
mods.pop();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(mods.len())
|
||||
}
|
||||
|
||||
async fn stale_count(server: &Arc<Server>) -> usize {
|
||||
let watermark = stale(server).await.unwrap_or(available());
|
||||
available().saturating_sub(watermark)
|
||||
}
|
||||
|
||||
async fn stale(server: &Arc<Server>) -> Result<usize, Error> {
|
||||
let mods_lock = server.mods.read().await;
|
||||
stale_from_mods(&mods_lock)
|
||||
}
|
||||
|
||||
fn stale_from_mods(mods: &[mods::Module]) -> Result<usize, Error> {
|
||||
for (i, module) in mods.iter().enumerate() {
|
||||
if module.deleted()? {
|
||||
return Ok(i);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(mods.len())
|
||||
}
|
||||
|
||||
fn restart_thresh() -> usize {
|
||||
MODULE_NAMES
|
||||
.iter()
|
||||
.position(|&name| name.ends_with(RESTART_THRESH))
|
||||
.unwrap_or(MODULE_NAMES.len())
|
||||
}
|
||||
|
||||
const fn available() -> usize { MODULE_NAMES.len() }
|
||||
@@ -27,10 +27,6 @@ pub(crate) struct Server {
|
||||
|
||||
#[cfg(feature = "sentry_telemetry")]
|
||||
_sentry_guard: Option<::sentry::ClientInitGuard>,
|
||||
|
||||
#[cfg(all(conduwuit_mods, feature = "conduwuit_mods"))]
|
||||
// Module instances; TODO: move to mods::loaded mgmt vector
|
||||
pub(crate) mods: tokio::sync::RwLock<Vec<conduwuit_core::mods::Module>>,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
@@ -87,9 +83,6 @@ impl Server {
|
||||
|
||||
#[cfg(feature = "sentry_telemetry")]
|
||||
_sentry_guard: sentry_guard,
|
||||
|
||||
#[cfg(all(conduwuit_mods, feature = "conduwuit_mods"))]
|
||||
mods: tokio::sync::RwLock::new(Vec::new()),
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
+1
-4
@@ -12,7 +12,6 @@ pub(super) async fn signal(server: Arc<Server>) {
|
||||
use unix::SignalKind;
|
||||
|
||||
const CONSOLE: bool = cfg!(feature = "console");
|
||||
const RELOADING: bool = cfg!(all(conduwuit_mods, feature = "conduwuit_mods", not(CONSOLE)));
|
||||
|
||||
let mut quit = unix::signal(SignalKind::quit()).expect("SIGQUIT handler");
|
||||
let mut term = unix::signal(SignalKind::terminate()).expect("SIGTERM handler");
|
||||
@@ -30,9 +29,7 @@ pub(super) async fn signal(server: Arc<Server>) {
|
||||
}
|
||||
|
||||
warn!("Received {sig}");
|
||||
let result = if RELOADING && sig == "SIGINT" {
|
||||
server.server.reload()
|
||||
} else if matches!(sig, "SIGQUIT" | "SIGTERM") || (!CONSOLE && sig == "SIGINT") {
|
||||
let result = if matches!(sig, "SIGQUIT" | "SIGTERM") || (!CONSOLE && sig == "SIGINT") {
|
||||
server.server.shutdown()
|
||||
} else {
|
||||
server.server.signal(sig)
|
||||
|
||||
+3
-13
@@ -16,11 +16,7 @@ use conduwuit::{Error, Result, Server};
|
||||
use conduwuit_service::Services;
|
||||
use futures::{Future, FutureExt, TryFutureExt};
|
||||
|
||||
conduwuit::mod_ctor! {}
|
||||
conduwuit::mod_dtor! {}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "Rust" fn start(
|
||||
pub fn start(
|
||||
server: &Arc<Server>,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Arc<Services>>> + Send>> {
|
||||
AssertUnwindSafe(run::start(server.clone()))
|
||||
@@ -30,10 +26,7 @@ pub extern "Rust" fn start(
|
||||
.boxed()
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "Rust" fn stop(
|
||||
services: Arc<Services>,
|
||||
) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
|
||||
pub fn stop(services: Arc<Services>) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
|
||||
AssertUnwindSafe(run::stop(services))
|
||||
.catch_unwind()
|
||||
.map_err(Error::from_panic)
|
||||
@@ -41,10 +34,7 @@ pub extern "Rust" fn stop(
|
||||
.boxed()
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "Rust" fn run(
|
||||
services: &Arc<Services>,
|
||||
) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
|
||||
pub fn run(services: &Arc<Services>) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
|
||||
AssertUnwindSafe(run::run(services.clone()))
|
||||
.catch_unwind()
|
||||
.map_err(Error::from_panic)
|
||||
|
||||
@@ -8,7 +8,11 @@ use ruma::api::error::ErrorKind;
|
||||
|
||||
pub(crate) fn build(services: &Arc<Services>) -> (Router, Guard) {
|
||||
let router = Router::<state::State>::new();
|
||||
let (state, guard) = state::create(services.clone());
|
||||
// SAFETY: `guard` is returned alongside `router` and held in `serve()`
|
||||
// until the HTTP server has finished serving all requests and dropped
|
||||
// `router`, ensuring no `State` copy can be dereferenced after `Services`
|
||||
// is dropped.
|
||||
let (state, guard) = unsafe { state::create(services.clone()) };
|
||||
let router = conduwuit_api::router::build(router, state)
|
||||
.merge(conduwuit_web::build(services))
|
||||
.fallback(not_found)
|
||||
|
||||
@@ -105,6 +105,7 @@ itertools.workspace = true
|
||||
log.workspace = true
|
||||
loole.workspace = true
|
||||
lru-cache.workspace = true
|
||||
mime.workspace = true
|
||||
nonzero_ext.workspace = true
|
||||
p256.workspace = true
|
||||
regex.workspace = true
|
||||
|
||||
@@ -111,7 +111,7 @@ impl crate::Service for Service {
|
||||
.local_address(url_preview_bind_addr)
|
||||
.timeout(Duration::from_secs(config.url_preview_timeout))
|
||||
.redirect(redirect::Policy::limited(3))
|
||||
.user_agent(url_preview_user_agent)
|
||||
.user_agent(url_preview_user_agent.replace("<version>", conduwuit::version_ua()))
|
||||
.build()?,
|
||||
|
||||
external_resource: base(config, reqwest_dns_resolver.clone())?
|
||||
|
||||
@@ -223,6 +223,8 @@ impl Data {
|
||||
x => x,
|
||||
};*/
|
||||
|
||||
// TODO(nex): Oh my god this is awful when can we kill it
|
||||
|
||||
let title = match values
|
||||
.next()
|
||||
.and_then(|b| String::from_utf8(b.to_vec()).ok())
|
||||
@@ -321,6 +323,11 @@ impl Data {
|
||||
video_height,
|
||||
audio,
|
||||
audio_size,
|
||||
..Default::default() /* TODO(nex,silversys): This weird manual field
|
||||
* de/serialisation just needs replacing with JSON storage to
|
||||
* avoid this mess. This is consequently intentionally
|
||||
* dropping information added later (like image alt text).
|
||||
* I'll do it later. */
|
||||
})
|
||||
}
|
||||
}
|
||||
+345
-90
@@ -7,29 +7,79 @@
|
||||
|
||||
use std::time::SystemTime;
|
||||
|
||||
#[cfg(feature = "url_preview")]
|
||||
use conduwuit::info;
|
||||
use conduwuit::{Err, Result, debug, err, utils::response::LimitReadExt};
|
||||
use ipaddress::IPAddress;
|
||||
use mime::Mime;
|
||||
use ruma::OwnedMxcUri;
|
||||
use serde::Serialize;
|
||||
use serde::{Serialize, Serializer};
|
||||
use url::Url;
|
||||
|
||||
use super::Service;
|
||||
use crate::media::mxc::Mxc;
|
||||
|
||||
#[derive(Serialize, Default)]
|
||||
// serde `serialize_with` passes `&Option<T>` for `Option<T>` fields.
|
||||
#[allow(clippy::ref_option)]
|
||||
fn serialize_mime<S: Serializer>(mime: &Option<Mime>, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
match mime {
|
||||
| Some(m) => serializer.serialize_str(m.as_ref()),
|
||||
| None => serializer.serialize_none(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Default, Debug)]
|
||||
pub struct UrlPreviewData {
|
||||
// From https://ogp.me/
|
||||
/// The title of your object as it should appear within the graph
|
||||
/// "The Rock".
|
||||
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:title"))]
|
||||
pub title: Option<String>,
|
||||
|
||||
/// The type of your object, e.g., "video.movie".
|
||||
#[serde(skip_serializing_if = "String::is_empty", rename(serialize = "og:type"))]
|
||||
pub site_type: String,
|
||||
/// The canonical URL of your object that will be used as its permanent ID
|
||||
/// in the graph.
|
||||
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:url"))]
|
||||
pub url: Option<String>,
|
||||
/// A one to two sentence description of your object.
|
||||
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:description"))]
|
||||
pub description: Option<String>,
|
||||
/// The word that appears before this object's title in a sentence.
|
||||
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:determiner"))]
|
||||
pub determiner: Option<String>,
|
||||
/// The locale these tags are marked up in
|
||||
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:locale"))]
|
||||
pub locale: Option<String>,
|
||||
/// If your object is part of a larger web site, the name which should be
|
||||
/// displayed for the overall site.
|
||||
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:site_name"))]
|
||||
pub site_name: Option<String>,
|
||||
|
||||
/// An image URL which should represent your object within the graph.
|
||||
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image"))]
|
||||
pub image: Option<String>,
|
||||
/// A MIME type for this image.
|
||||
#[serde(
|
||||
skip_serializing_if = "Option::is_none",
|
||||
serialize_with = "serialize_mime",
|
||||
rename(serialize = "og:image:type")
|
||||
)]
|
||||
pub image_type: Option<Mime>,
|
||||
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "matrix:image:size"))]
|
||||
pub image_size: Option<usize>,
|
||||
/// The number of pixels wide.
|
||||
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image:width"))]
|
||||
pub image_width: Option<u32>,
|
||||
/// The number of pixels high.
|
||||
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image:height"))]
|
||||
pub image_height: Option<u32>,
|
||||
/// A description of what is in the image (not a caption).
|
||||
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image:alt"))]
|
||||
pub image_alt: Option<String>,
|
||||
|
||||
/// A URL to a video file that complements this object.
|
||||
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:video"))]
|
||||
pub video: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "matrix:video:size"))]
|
||||
@@ -38,6 +88,15 @@ pub struct UrlPreviewData {
|
||||
pub video_width: Option<u32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:video:height"))]
|
||||
pub video_height: Option<u32>,
|
||||
#[serde(
|
||||
skip_serializing_if = "Option::is_none",
|
||||
serialize_with = "serialize_mime",
|
||||
rename(serialize = "og:video:type")
|
||||
)]
|
||||
pub video_type: Option<Mime>,
|
||||
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:video:alt"))]
|
||||
pub video_alt: Option<String>,
|
||||
/// A URL to an audio file to accompany this object.
|
||||
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:audio"))]
|
||||
pub audio: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "matrix:audio:size"))]
|
||||
@@ -78,43 +137,39 @@ impl Service {
|
||||
}
|
||||
|
||||
async fn request_url_preview(&self, url: &Url) -> Result<UrlPreviewData> {
|
||||
if let Ok(ip) = IPAddress::parse(url.host_str().expect("URL previously validated")) {
|
||||
if !self.services.client.valid_cidr_range(&ip) {
|
||||
return Err!(Request(Forbidden("Requesting from this address is forbidden")));
|
||||
}
|
||||
}
|
||||
self.check_url_ip(url.as_str())?;
|
||||
|
||||
let client = &self.services.client.url_preview;
|
||||
let response = client.head(url.as_str()).send().await?;
|
||||
|
||||
debug!(%url, "URL preview response headers: {:?}", response.headers());
|
||||
|
||||
if let Some(remote_addr) = response.remote_addr() {
|
||||
debug!(%url, "URL preview response remote address: {:?}", remote_addr);
|
||||
|
||||
if let Ok(ip) = IPAddress::parse(remote_addr.ip().to_string()) {
|
||||
if !self.services.client.valid_cidr_range(&ip) {
|
||||
return Err!(Request(Forbidden("Requesting from this address is forbidden")));
|
||||
}
|
||||
}
|
||||
self.check_response_ip(&response)?;
|
||||
if !response.status().is_success() {
|
||||
return Err!(Request(Unknown(
|
||||
"URL preview request returned HTTP {}",
|
||||
response.status()
|
||||
)));
|
||||
}
|
||||
|
||||
let Some(content_type) = response.headers().get(reqwest::header::CONTENT_TYPE) else {
|
||||
return Err!(Request(Unknown("Unknown or invalid Content-Type header")));
|
||||
return Err!(Request(Unknown(
|
||||
"Response contains unknown, invalid, or missing Content-Type header"
|
||||
)));
|
||||
};
|
||||
|
||||
let content_type = content_type
|
||||
let content_type: Mime = content_type
|
||||
.to_str()
|
||||
.map_err(|e| err!(Request(Unknown("Unknown or invalid Content-Type header: {e}"))))?
|
||||
.parse()
|
||||
.map_err(|e| err!(Request(Unknown("Unknown or invalid Content-Type header: {e}"))))?;
|
||||
|
||||
let data = match content_type {
|
||||
| html if html.starts_with("text/html") => self.download_html(url.as_str()).await?,
|
||||
| img if img.starts_with("image/") => self.download_image(url.as_str(), None).await?,
|
||||
| video if video.starts_with("video/") =>
|
||||
self.download_video(url.as_str(), None).await?,
|
||||
| audio if audio.starts_with("audio/") =>
|
||||
self.download_audio(url.as_str(), None).await?,
|
||||
| _ => return Err!(Request(Unknown("Unsupported Content-Type"))),
|
||||
let data = match (content_type.type_(), content_type.subtype()) {
|
||||
| (mime::TEXT, mime::HTML) => self.download_html(url.as_str()).await?,
|
||||
| (mime::IMAGE, _) => self.download_image(url.as_str()).await?,
|
||||
| (mime::VIDEO, _) => self.download_video(url.as_str()).await?,
|
||||
| (mime::AUDIO, _) => self.download_audio(url.as_str()).await?,
|
||||
| _ => return Err!(Request(Unknown("Unsupported Content-Type: {content_type}"))),
|
||||
};
|
||||
|
||||
self.set_url_preview(url.as_str(), &data).await?;
|
||||
@@ -123,19 +178,16 @@ impl Service {
|
||||
}
|
||||
|
||||
#[cfg(feature = "url_preview")]
|
||||
pub async fn download_image(
|
||||
&self,
|
||||
url: &str,
|
||||
preview_data: Option<UrlPreviewData>,
|
||||
) -> Result<UrlPreviewData> {
|
||||
pub async fn download_image(&self, url: &str) -> Result<UrlPreviewData> {
|
||||
use conduwuit::utils::random_string;
|
||||
use image::ImageReader;
|
||||
|
||||
use crate::media::mxc::Mxc;
|
||||
let mut preview_data = UrlPreviewData::default();
|
||||
|
||||
let mut preview_data = preview_data.unwrap_or_default();
|
||||
self.check_url_ip(url)?;
|
||||
|
||||
let response = self.services.client.url_preview.get(url).send().await?;
|
||||
self.check_response_ip(&response)?;
|
||||
if !response.status().is_success() {
|
||||
return Err!(Request(Unknown("Image download returned HTTP {}", response.status())));
|
||||
}
|
||||
@@ -157,13 +209,13 @@ impl Service {
|
||||
.ok_or_else(|| err!(Request(Unknown("Downloaded file is not a supported image"))))?
|
||||
.to_mime_type();
|
||||
|
||||
if preview_data.image_height.is_none() || preview_data.image_width.is_none() {
|
||||
let (width, height) = reader.into_dimensions().map_err(|error| {
|
||||
err!(Request(Unknown("Failed to read preview image dimensions: {error}")))
|
||||
})?;
|
||||
preview_data.image_width.get_or_insert(width);
|
||||
preview_data.image_height.get_or_insert(height);
|
||||
}
|
||||
let (width, height) = reader.into_dimensions().map_err(|error| {
|
||||
err!(Request(Unknown("Failed to read preview image dimensions: {error}")))
|
||||
})?;
|
||||
preview_data.image_width = Some(width);
|
||||
preview_data.image_height = Some(height);
|
||||
preview_data.image_size = Some(image.len());
|
||||
preview_data.image_type = content_type.parse().ok();
|
||||
|
||||
let mxc = Mxc {
|
||||
server_name: self.services.globals.server_name(),
|
||||
@@ -179,12 +231,9 @@ impl Service {
|
||||
}
|
||||
|
||||
#[cfg(feature = "url_preview")]
|
||||
pub async fn download_video(
|
||||
&self,
|
||||
url: &str,
|
||||
preview_data: Option<UrlPreviewData>,
|
||||
) -> Result<UrlPreviewData> {
|
||||
let mut preview_data = preview_data.unwrap_or_default();
|
||||
#[tracing::instrument(skip(self))]
|
||||
pub async fn download_video(&self, url: &str) -> Result<UrlPreviewData> {
|
||||
let mut preview_data = UrlPreviewData::default();
|
||||
|
||||
if self.services.globals.url_preview_allow_audio_video() {
|
||||
let (url, size) = self.download_media(url).await?;
|
||||
@@ -196,12 +245,9 @@ impl Service {
|
||||
}
|
||||
|
||||
#[cfg(feature = "url_preview")]
|
||||
pub async fn download_audio(
|
||||
&self,
|
||||
url: &str,
|
||||
preview_data: Option<UrlPreviewData>,
|
||||
) -> Result<UrlPreviewData> {
|
||||
let mut preview_data = preview_data.unwrap_or_default();
|
||||
#[tracing::instrument(skip(self))]
|
||||
pub async fn download_audio(&self, url: &str) -> Result<UrlPreviewData> {
|
||||
let mut preview_data = UrlPreviewData::default();
|
||||
|
||||
if self.services.globals.url_preview_allow_audio_video() {
|
||||
let (url, size) = self.download_media(url).await?;
|
||||
@@ -212,11 +258,18 @@ impl Service {
|
||||
Ok(preview_data)
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(self))]
|
||||
pub async fn download_media(&self, url: &str) -> Result<(OwnedMxcUri, usize)> {
|
||||
use conduwuit::utils::random_string;
|
||||
use http::header::CONTENT_TYPE;
|
||||
|
||||
self.check_url_ip(url)?;
|
||||
|
||||
let response = self.services.client.url_preview.get(url).send().await?;
|
||||
self.check_response_ip(&response)?;
|
||||
if !response.status().is_success() {
|
||||
return Err!(Request(Unknown("Media download returned HTTP {}", response.status())));
|
||||
}
|
||||
let content_type = response.headers().get(CONTENT_TYPE).cloned();
|
||||
let media = response
|
||||
.limit_read(
|
||||
@@ -242,41 +295,32 @@ impl Service {
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "url_preview"))]
|
||||
pub async fn download_image(
|
||||
&self,
|
||||
_url: &str,
|
||||
_preview_data: Option<UrlPreviewData>,
|
||||
) -> Result<UrlPreviewData> {
|
||||
Err!(FeatureDisabled("url_preview"))
|
||||
pub fn download_image(&self, _url: &str) -> impl Future<Output = Result<UrlPreviewData>> {
|
||||
std::future::ready(Err!(FeatureDisabled("url_preview")))
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "url_preview"))]
|
||||
pub async fn download_video(
|
||||
&self,
|
||||
_url: &str,
|
||||
_preview_data: Option<UrlPreviewData>,
|
||||
) -> Result<UrlPreviewData> {
|
||||
Err!(FeatureDisabled("url_preview"))
|
||||
pub fn download_video(&self, _url: &str) -> impl Future<Output = Result<UrlPreviewData>> {
|
||||
std::future::ready(Err!(FeatureDisabled("url_preview")))
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "url_preview"))]
|
||||
pub async fn download_audio(
|
||||
&self,
|
||||
_url: &str,
|
||||
_preview_data: Option<UrlPreviewData>,
|
||||
) -> Result<UrlPreviewData> {
|
||||
Err!(FeatureDisabled("url_preview"))
|
||||
pub fn download_audio(&self, _url: &str) -> impl Future<Output = Result<UrlPreviewData>> {
|
||||
std::future::ready(Err!(FeatureDisabled("url_preview")))
|
||||
}
|
||||
|
||||
#[cfg(feature = "url_preview")]
|
||||
#[tracing::instrument(skip(self))]
|
||||
async fn download_html(&self, url: &str) -> Result<UrlPreviewData> {
|
||||
use webpage::HTML;
|
||||
|
||||
let client = &self.services.client.url_preview;
|
||||
let body = client
|
||||
.get(url)
|
||||
.send()
|
||||
.await?
|
||||
let response = client.get(url).send().await?;
|
||||
self.check_response_ip(&response)?;
|
||||
if !response.status().is_success() {
|
||||
return Err!(Request(Unknown("HTML download returned HTTP {}", response.status())));
|
||||
}
|
||||
let body = response
|
||||
.limit_read_text(
|
||||
self.services
|
||||
.server
|
||||
@@ -286,39 +330,138 @@ impl Service {
|
||||
.expect("u64 should fit in usize"),
|
||||
)
|
||||
.await?;
|
||||
let Ok(html) = HTML::from_string(body.clone(), Some(url.to_owned())) else {
|
||||
let Ok(html) = HTML::from_string(body, Some(url.to_owned()))
|
||||
.inspect_err(|e| debug!(error=?e, "Failed to parse HTML data"))
|
||||
else {
|
||||
return Err!(Request(Unknown("Failed to parse HTML")));
|
||||
};
|
||||
|
||||
let mut preview_data = UrlPreviewData::default();
|
||||
let mut preview_data = UrlPreviewData::from(&html.opengraph);
|
||||
debug!(parsed=?preview_data, deserialised=?html.opengraph, "Parsed opengraph data");
|
||||
|
||||
if let Some(obj) = html.opengraph.images.first() {
|
||||
preview_data = self.download_image(&obj.url, Some(preview_data)).await?;
|
||||
let base_url = Url::parse(url).ok();
|
||||
let resolve_asset_url = |asset_url: &str| -> String {
|
||||
base_url
|
||||
.as_ref()
|
||||
.and_then(|base| base.join(asset_url).ok())
|
||||
.map_or_else(|| asset_url.to_owned(), Into::into)
|
||||
};
|
||||
|
||||
if let Some(obj) = html
|
||||
.opengraph
|
||||
.images
|
||||
.first()
|
||||
.filter(|obj| !obj.url.is_empty())
|
||||
{
|
||||
let asset_url = resolve_asset_url(&obj.url);
|
||||
info!(%asset_url, "Downloading preview image");
|
||||
if let Ok(image_data) = self.download_image(&asset_url).await.inspect_err(
|
||||
|e| info!(error=?e, %asset_url, "Could not download URL preview image"),
|
||||
) {
|
||||
preview_data.image = image_data.image;
|
||||
preview_data.image_size = image_data.image_size;
|
||||
// Prioritise what the top-level site specified, falling back to
|
||||
// detected params.
|
||||
preview_data.image_width = preview_data.image_width.or(image_data.image_width);
|
||||
preview_data.image_height = preview_data.image_height.or(image_data.image_height);
|
||||
preview_data.image_type = preview_data.image_type.or(image_data.image_type);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(obj) = html.opengraph.videos.first() {
|
||||
preview_data = self.download_video(&obj.url, Some(preview_data)).await?;
|
||||
preview_data.video_width = obj.properties.get("width").and_then(|v| v.parse().ok());
|
||||
preview_data.video_height = obj.properties.get("height").and_then(|v| v.parse().ok());
|
||||
if let Some(obj) = html
|
||||
.opengraph
|
||||
.videos
|
||||
.first()
|
||||
.filter(|obj| !obj.url.is_empty())
|
||||
{
|
||||
let asset_url = resolve_asset_url(&obj.url);
|
||||
info!(%asset_url, "Downloading preview video");
|
||||
if let Ok(video_data) = self.download_video(&asset_url).await.inspect_err(
|
||||
|e| info!(error=?e, %asset_url, "Could not download URL preview video"),
|
||||
) {
|
||||
preview_data.video = video_data.video;
|
||||
preview_data.video_size = video_data.video_size;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(obj) = html.opengraph.audios.first() {
|
||||
preview_data = self.download_audio(&obj.url, Some(preview_data)).await?;
|
||||
if let Some(obj) = html
|
||||
.opengraph
|
||||
.audios
|
||||
.first()
|
||||
.filter(|obj| !obj.url.is_empty())
|
||||
{
|
||||
let asset_url = resolve_asset_url(&obj.url);
|
||||
info!(%asset_url, "Downloading URL preview audio");
|
||||
if let Ok(audio_data) = self.download_audio(&asset_url).await.inspect_err(
|
||||
|e| info!(error=?e, %asset_url, "Could not download URL preview audio"),
|
||||
) {
|
||||
preview_data.audio = audio_data.audio;
|
||||
preview_data.audio_size = audio_data.audio_size;
|
||||
}
|
||||
}
|
||||
|
||||
let props = html.opengraph.properties;
|
||||
// Provide defaults for some params
|
||||
preview_data.title = preview_data.title.or(html.title);
|
||||
preview_data.description = preview_data.description.or(html.description);
|
||||
preview_data.url = preview_data.url.or_else(|| Some(url.to_owned()));
|
||||
|
||||
/* use OpenGraph title/description, but fall back to HTML if not
|
||||
* available */
|
||||
preview_data.title = props.get("title").cloned().or(html.title);
|
||||
preview_data.description = props.get("description").cloned().or(html.description);
|
||||
// We remove og:image:*, og:video:*, and og:audio:* if their respective
|
||||
// prior-level properties are not present.
|
||||
// We do this here instead of in the From<> impl because we can't know
|
||||
// if we'll be able to fetch the media to convert it to an mxc that
|
||||
// point.
|
||||
if preview_data.image.is_none() {
|
||||
preview_data.image_type = None;
|
||||
preview_data.image_alt = None;
|
||||
preview_data.image_height = None;
|
||||
preview_data.image_width = None;
|
||||
preview_data.image_size = None;
|
||||
}
|
||||
if preview_data.video.is_none() {
|
||||
preview_data.video_type = None;
|
||||
preview_data.video_alt = None;
|
||||
preview_data.video_height = None;
|
||||
preview_data.video_width = None;
|
||||
preview_data.video_size = None;
|
||||
}
|
||||
if preview_data.audio.is_none() {
|
||||
preview_data.audio_size = None;
|
||||
}
|
||||
|
||||
Ok(preview_data)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "url_preview"))]
|
||||
async fn download_html(&self, _url: &str) -> Result<UrlPreviewData> {
|
||||
Err!(FeatureDisabled("url_preview"))
|
||||
#[allow(clippy::unused_self)]
|
||||
fn download_html(&self, _url: &str) -> impl Future<Output = Result<UrlPreviewData>> {
|
||||
std::future::ready(Err!(FeatureDisabled("url_preview")))
|
||||
}
|
||||
|
||||
fn check_url_ip(&self, url: &str) -> Result<()> {
|
||||
let parsed = Url::parse(url)
|
||||
.map_err(|e| err!(Request(InvalidParam("Requested URL is not valid: {e}"))))?;
|
||||
let Some(host) = parsed.host_str() else {
|
||||
return Err!(Request(InvalidParam("Requested URL does not have a host")));
|
||||
};
|
||||
if let Ok(ip) = IPAddress::parse(host) {
|
||||
if !self.services.client.valid_cidr_range(&ip) {
|
||||
return Err!(Request(Forbidden("Requesting from this address is forbidden")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_response_ip(&self, response: &reqwest::Response) -> Result<()> {
|
||||
if let Some(remote_addr) = response.remote_addr() {
|
||||
debug!(url = %response.url(), "URL preview response remote address: {:?}", remote_addr);
|
||||
|
||||
if let Ok(ip) = IPAddress::parse(remote_addr.ip().to_string()) {
|
||||
if !self.services.client.valid_cidr_range(&ip) {
|
||||
return Err!(Request(Forbidden("Requesting from this address is forbidden")));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn url_preview_allowed(&self, url: &Url) -> bool {
|
||||
@@ -443,3 +586,115 @@ impl Service {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "url_preview")]
|
||||
impl From<&webpage::Opengraph> for UrlPreviewData {
|
||||
fn from(og: &webpage::Opengraph) -> Self {
|
||||
Self {
|
||||
title: og.properties.get("title").cloned(),
|
||||
description: og.properties.get("description").cloned(),
|
||||
site_type: og.og_type.clone(),
|
||||
url: og.properties.get("url").cloned(),
|
||||
determiner: og.properties.get("determiner").cloned(),
|
||||
locale: og.properties.get("locale").cloned(),
|
||||
site_name: og.properties.get("site_name").cloned(),
|
||||
image_type: og
|
||||
.images
|
||||
.first()
|
||||
.and_then(|img| img.properties.get("type").and_then(|t| t.parse().ok())),
|
||||
image_width: og
|
||||
.images
|
||||
.first()
|
||||
.and_then(|img| img.properties.get("width").and_then(|w| w.parse().ok())),
|
||||
image_height: og
|
||||
.images
|
||||
.first()
|
||||
.and_then(|img| img.properties.get("height").and_then(|h| h.parse().ok())),
|
||||
image_alt: og
|
||||
.images
|
||||
.first()
|
||||
.and_then(|img| img.properties.get("alt").cloned()),
|
||||
video_type: og
|
||||
.videos
|
||||
.first()
|
||||
.and_then(|vid| vid.properties.get("type"))
|
||||
.and_then(|t| t.parse().ok()),
|
||||
video_width: og
|
||||
.videos
|
||||
.first()
|
||||
.and_then(|vid| vid.properties.get("width"))
|
||||
.and_then(|w| w.parse().ok()),
|
||||
video_height: og
|
||||
.videos
|
||||
.first()
|
||||
.and_then(|vid| vid.properties.get("height"))
|
||||
.and_then(|h| h.parse().ok()),
|
||||
video_alt: og
|
||||
.videos
|
||||
.first()
|
||||
.and_then(|vid| vid.properties.get("alt").cloned()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[cfg(feature = "url_preview")]
|
||||
#[test]
|
||||
fn test_urlpreviewdata_parses_correctly() {
|
||||
use webpage::HTML;
|
||||
|
||||
use super::UrlPreviewData;
|
||||
let html = r#"
|
||||
<html>
|
||||
<head>
|
||||
<meta property="og:title" content="Test Title" />
|
||||
<meta property="og:description" content="Test Description" />
|
||||
<meta property="og:image" content="https://example.com/image.png" />
|
||||
<meta property="og:url" content="https://example.com/index.html" />
|
||||
<meta property="og:type" content="org.continuwuity.other" />
|
||||
<meta property="og:site_name" content="Example Site" />
|
||||
<meta property="og:image:alt" content="An example image" />
|
||||
<meta property="og:image:type" content="image/png" />
|
||||
<meta property="og:image:height" content="69" />
|
||||
<meta property="og:image:width" content="420" />
|
||||
<meta property="og:video" content="https://example.com/video.mp4" />
|
||||
<meta property="og:audio" content="https://example.com/audio.ogg" />
|
||||
</head>
|
||||
<body></body>
|
||||
</html>
|
||||
"#;
|
||||
|
||||
let parsed_html =
|
||||
HTML::from_string(html.to_owned(), Some("https://example.com".to_owned()))
|
||||
.expect("Failed to parse HTML");
|
||||
|
||||
let data = UrlPreviewData::from(&parsed_html.opengraph);
|
||||
|
||||
assert_eq!(data.title, Some("Test Title".to_owned()));
|
||||
assert_eq!(data.description, Some("Test Description".to_owned()));
|
||||
assert_eq!(
|
||||
data.image, None,
|
||||
"UrlPreviewData should not inherit HTTP/S URL from URL preview"
|
||||
);
|
||||
assert_eq!(
|
||||
data.video, None,
|
||||
"UrlPreviewData should not inherit HTTP/S URL from URL preview"
|
||||
);
|
||||
assert_eq!(
|
||||
data.audio, None,
|
||||
"UrlPreviewData should not inherit HTTP/S URL from URL preview"
|
||||
);
|
||||
assert_eq!(data.url, Some("https://example.com/index.html".to_owned()));
|
||||
assert_eq!(data.site_type, "org.continuwuity.other".to_owned());
|
||||
assert_eq!(data.site_name, Some("Example Site".to_owned()));
|
||||
assert_eq!(data.image_alt, Some("An example image".to_owned()));
|
||||
assert_eq!(data.image_type, Some("image/png".parse().unwrap()));
|
||||
assert_eq!(data.image_height, Some(69));
|
||||
assert_eq!(data.image_width, Some(420));
|
||||
assert_eq!(data.image_size, None, "*_size must be None when pulling from opengraph");
|
||||
assert_eq!(data.video_size, None, "*_size must be None when pulling from opengraph");
|
||||
assert_eq!(data.audio_size, None, "*_size must be None when pulling from opengraph");
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,28 @@ impl Services {
|
||||
},
|
||||
);
|
||||
|
||||
self.gauge(
|
||||
"continuwuity.sender.requests",
|
||||
"Estimated outgoing requests stored as queued or in flight",
|
||||
"{request}",
|
||||
|services, observer| {
|
||||
for (state, count) in services.sending.db.request_counts() {
|
||||
if let Some(count) = count {
|
||||
observer.observe(count, &[KeyValue::new("state", state)]);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
self.gauge(
|
||||
"continuwuity.sender.workers",
|
||||
"Running sender workers",
|
||||
"{worker}",
|
||||
|services, observer| {
|
||||
observe(observer, services.sending.workers_alive(), &[]);
|
||||
},
|
||||
);
|
||||
|
||||
self.gauge(
|
||||
"continuwuity.federation.incoming.transactions.active",
|
||||
"Incoming federation transactions currently being processed",
|
||||
|
||||
@@ -18,11 +18,11 @@ use conduwuit::{
|
||||
},
|
||||
warn,
|
||||
};
|
||||
use database::{Deserialized, Ignore, Json};
|
||||
use database::{Database, Deserialized, Ignore, Json};
|
||||
use futures::{FutureExt, StreamExt, TryStreamExt};
|
||||
use itertools::Itertools;
|
||||
use ruma::{
|
||||
OwnedDeviceId, OwnedEventId, OwnedRoomId, OwnedUserId, UserId,
|
||||
MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedEventId, OwnedRoomId, OwnedUserId, UserId,
|
||||
api::OAuthClientScope,
|
||||
events::{
|
||||
AnyStrippedStateEvent, GlobalAccountDataEventType, StateEventType,
|
||||
@@ -32,9 +32,13 @@ use ruma::{
|
||||
push::Ruleset,
|
||||
serde::{Raw, from_raw_json_value},
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, value::to_raw_value};
|
||||
|
||||
use crate::{Services, media, rooms, rooms::short::ShortStateHash};
|
||||
use crate::{
|
||||
Services, media, rooms,
|
||||
rooms::{short::ShortStateHash, timeline::RawPduId},
|
||||
};
|
||||
|
||||
type MigrationFn =
|
||||
for<'a> fn(&'a Services) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;
|
||||
@@ -176,6 +180,36 @@ migration!(stringify!($name) => $name)
|
||||
// This is backwards compatible because old versions never read the
|
||||
// account data entries it removes.
|
||||
migration!(remove_replaced_account_data),
|
||||
// This is backwards compatible because old versions ignore the
|
||||
// `roomts_pduid` keyspace.
|
||||
Migration(rooms::timeline::TIMESTAMP_INDEX_MIGRATION, |services| {
|
||||
Box::pin(async {
|
||||
let global = &services.db["global"];
|
||||
if global
|
||||
.exists(rooms::timeline::TIMESTAMP_INDEX_MIGRATION)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let until = match global.get(ROOMTS_UNTIL).await.deserialized::<u64>() {
|
||||
| Ok(until) => until,
|
||||
| Err(_) => {
|
||||
let until = services.globals.current_count()?;
|
||||
global.insert(ROOMTS_UNTIL, until.to_be_bytes());
|
||||
until
|
||||
},
|
||||
};
|
||||
|
||||
services
|
||||
.server
|
||||
.runtime()
|
||||
.spawn(populate_roomts_pduid(services.db.clone(), until));
|
||||
|
||||
Ok(())
|
||||
})
|
||||
}),
|
||||
]
|
||||
};
|
||||
|
||||
@@ -961,6 +995,38 @@ async fn drop_server_signingkeys(services: &Services) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const ROOMTS_UNTIL: &str = "populate_roomts_pduid_until";
|
||||
|
||||
async fn populate_roomts_pduid(db: Arc<Database>, until: u64) {
|
||||
#[derive(Deserialize)]
|
||||
struct ExtractTs {
|
||||
origin_server_ts: MilliSecondsSinceUnixEpoch,
|
||||
}
|
||||
|
||||
info!("Starting background migration to index PDUs by timestamp.");
|
||||
let start = Instant::now();
|
||||
let roomts_pduid = db["roomts_pduid"].clone();
|
||||
|
||||
db["pduid_pdu"]
|
||||
.raw_stream()
|
||||
.ignore_err()
|
||||
.ready_for_each(|(key, val)| {
|
||||
let pdu_id = RawPduId::from(key);
|
||||
if matches!(pdu_id.pdu_count(), PduCount::Normal(count) if count > until) {
|
||||
return;
|
||||
}
|
||||
if let Ok(pdu) = serde_json::from_slice::<ExtractTs>(val) {
|
||||
roomts_pduid
|
||||
.insert(&rooms::timeline::roomts_key(&pdu_id, pdu.origin_server_ts), []);
|
||||
}
|
||||
})
|
||||
.await;
|
||||
|
||||
db["global"].insert(rooms::timeline::TIMESTAMP_INDEX_MIGRATION, []);
|
||||
db["global"].remove(ROOMTS_UNTIL);
|
||||
info!(elapsed = ?start.elapsed(), "Finished indexing PDUs by timestamp.");
|
||||
}
|
||||
|
||||
async fn fix_oauth_scope_names(services: &Services) -> Result {
|
||||
let db = &services.db;
|
||||
let userdeviceid_oauthsessioninfo = db["userdeviceid_oauthsessioninfo"].clone();
|
||||
|
||||
+5
-9
@@ -13,6 +13,8 @@ mod migrations;
|
||||
mod service;
|
||||
pub mod services;
|
||||
pub mod state;
|
||||
#[cfg(test)]
|
||||
mod test_utils;
|
||||
|
||||
pub mod account_data;
|
||||
pub mod admin;
|
||||
@@ -44,19 +46,13 @@ pub mod transactions;
|
||||
pub mod uiaa;
|
||||
pub mod users;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::{collections::BTreeMap, sync::LazyLock};
|
||||
|
||||
use conduwuit::matrix::versions::versions;
|
||||
use ruma::api::SupportedVersions;
|
||||
pub(crate) use service::{Args, Dep, Service};
|
||||
|
||||
pub use crate::services::Services;
|
||||
|
||||
conduwuit::mod_ctor! {}
|
||||
conduwuit::mod_dtor! {}
|
||||
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use conduwuit::matrix::versions::versions;
|
||||
use ruma::api::SupportedVersions;
|
||||
|
||||
pub static SUPPORTED_VERSIONS: LazyLock<SupportedVersions> =
|
||||
LazyLock::new(|| SupportedVersions::from_parts(&versions(), &BTreeMap::new()));
|
||||
+77
-10
@@ -1,5 +1,6 @@
|
||||
use std::{
|
||||
collections::{BTreeSet, HashMap},
|
||||
fmt::Write,
|
||||
sync::Arc,
|
||||
time::{Duration, SystemTime},
|
||||
};
|
||||
@@ -55,7 +56,7 @@ struct Services {
|
||||
config: Dep<config::Service>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct SessionInfo {
|
||||
pub client_id: String,
|
||||
#[serde(deserialize_with = "client_metadata::btreeset_skip_err")]
|
||||
@@ -64,6 +65,8 @@ pub struct SessionInfo {
|
||||
temporary_scopes: BTreeSet<OAuthClientScope>,
|
||||
#[serde(default)]
|
||||
current_refresh_token: String,
|
||||
#[serde(default)]
|
||||
previous_refresh_token: Option<String>,
|
||||
}
|
||||
|
||||
impl SessionInfo {
|
||||
@@ -71,6 +74,15 @@ impl SessionInfo {
|
||||
pub fn scopes(&self) -> BTreeSet<OAuthClientScope> {
|
||||
self.scopes.union(&self.temporary_scopes).cloned().collect()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn scope_string(&self, device_id: &DeviceId) -> String {
|
||||
let mut scopes = self.scopes().iter().join(" ");
|
||||
|
||||
let _ = write!(scopes, " urn:matrix:client:device:{device_id}");
|
||||
|
||||
scopes
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
@@ -246,6 +258,24 @@ impl Service {
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// Clear a session's previous refresh token, if it has one.
|
||||
pub fn clear_previous_refresh_token(
|
||||
&self,
|
||||
user_id: &UserId,
|
||||
device_id: &DeviceId,
|
||||
session_info: &SessionInfo,
|
||||
) {
|
||||
if session_info.previous_refresh_token.is_some() {
|
||||
let mut session_info = session_info.clone();
|
||||
|
||||
session_info.previous_refresh_token = None;
|
||||
|
||||
self.db
|
||||
.userdeviceid_oauthsessioninfo
|
||||
.put((user_id, device_id), Json(session_info));
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn request_authorization_code(
|
||||
&self,
|
||||
authorizing_user: OwnedUserId,
|
||||
@@ -645,6 +675,7 @@ impl Service {
|
||||
SessionInfo {
|
||||
client_id: client_id.clone(),
|
||||
current_refresh_token: Self::generate_token(),
|
||||
previous_refresh_token: None,
|
||||
scopes: requested_scopes.scopes,
|
||||
temporary_scopes: BTreeSet::new(),
|
||||
}
|
||||
@@ -702,15 +733,53 @@ impl Service {
|
||||
|
||||
assert_eq!(&client_id, &session_info.client_id, "session info client id mismatch");
|
||||
|
||||
// TODO: this doesn't include the device ID "scope", do any clients rely
|
||||
// on that?
|
||||
let scope = session_info.scopes.iter().join(" ");
|
||||
let new_refresh_token = Self::generate_token();
|
||||
|
||||
if refresh_token == session_info.current_refresh_token {
|
||||
// The client is refreshing with their current refresh token.
|
||||
// We need to generate a new refresh token and save this token as
|
||||
// the previous one.
|
||||
|
||||
session_info
|
||||
.current_refresh_token
|
||||
.clone_from(&new_refresh_token);
|
||||
|
||||
// Remove the old previous token if it's set. This can only happen
|
||||
// if the client decides to refresh twice in a row without using its
|
||||
// new access token, since we'll also do this when the new access
|
||||
// token is used for the first time.
|
||||
if let Some(previous_refresh_token) = session_info.previous_refresh_token {
|
||||
self.db
|
||||
.refreshtoken_refreshtokeninfo
|
||||
.remove(&previous_refresh_token);
|
||||
}
|
||||
|
||||
session_info.previous_refresh_token = Some(refresh_token);
|
||||
} else if Some(&refresh_token) == session_info.previous_refresh_token.as_ref() {
|
||||
// The client is refreshing with their previous refresh token,
|
||||
// probably because they didn't get the new one we made for them. We
|
||||
// need to make a second new one, but we don't touch the existing
|
||||
// previous one in case they don't get the second new one either.
|
||||
|
||||
// Wipe the current token, we're going to make a new one.
|
||||
self.db
|
||||
.refreshtoken_refreshtokeninfo
|
||||
.remove(&session_info.current_refresh_token);
|
||||
|
||||
session_info
|
||||
.current_refresh_token
|
||||
.clone_from(&new_refresh_token);
|
||||
} else {
|
||||
// The client is trying to use a refresh token that isn't their
|
||||
// current or previous one, but still has information in the
|
||||
// database. This is definitely not a legal state, so we need to
|
||||
// bail out.
|
||||
panic!("refresh token is not current or previous for its session");
|
||||
}
|
||||
|
||||
let scope = session_info.scope_string(&refresh_token_info.device_id);
|
||||
|
||||
let new_access_token = DeviceToken::new_random().with_max_age(Self::ACCESS_TOKEN_MAX_AGE);
|
||||
let new_refresh_token = Self::generate_token();
|
||||
session_info
|
||||
.current_refresh_token
|
||||
.clone_from(&new_refresh_token);
|
||||
|
||||
self.services
|
||||
.users
|
||||
@@ -729,8 +798,6 @@ impl Service {
|
||||
Json(session_info),
|
||||
);
|
||||
|
||||
self.db.refreshtoken_refreshtokeninfo.remove(&refresh_token);
|
||||
drop(refresh_token);
|
||||
self.db
|
||||
.refreshtoken_refreshtokeninfo
|
||||
.raw_put(&new_refresh_token, Json(refresh_token_info));
|
||||
|
||||
@@ -1,14 +1,10 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use conduwuit::{
|
||||
Config, PduEvent, Server,
|
||||
log::{Log, LogLevelReloadHandles},
|
||||
metrics::Metrics,
|
||||
};
|
||||
use conduwuit::PduEvent;
|
||||
use futures::StreamExt;
|
||||
use ruma::{RoomId, RoomVersionId, events::StateEventType};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::test_utils::test_services;
|
||||
|
||||
#[tokio::test]
|
||||
async fn admitted_joins_do_not_disappear_after_a_merge() {
|
||||
use conduwuit::matrix::PartialPdu;
|
||||
@@ -20,7 +16,7 @@ async fn admitted_joins_do_not_disappear_after_a_merge() {
|
||||
},
|
||||
};
|
||||
|
||||
let (services, path) = test_services().await;
|
||||
let (services, path, _database) = test_services().await;
|
||||
let alice = UserId::parse("@alice:test.example").unwrap();
|
||||
let bob = UserId::parse("@bob:bob.example").unwrap();
|
||||
let charlie = UserId::parse("@charlie:charlie.example").unwrap();
|
||||
@@ -212,35 +208,6 @@ async fn admitted_joins_do_not_disappear_after_a_merge() {
|
||||
assert_eq!(results, [true, true], "both joined users must be able to send messages");
|
||||
}
|
||||
|
||||
async fn test_services() -> (Arc<crate::Services>, std::path::PathBuf) {
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
let path = std::env::temp_dir()
|
||||
.join(format!("continuwuity-shared-state-{:016x}", rand::random::<u64>()));
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
let config: Config = serde_json::from_value(json!({
|
||||
"server_name": "test.example",
|
||||
"database_path": path,
|
||||
"db_cache_capacity_mb": 16.0,
|
||||
"rocksdb_write_buffer_capacity_mb": 4.0,
|
||||
"allow_local_presence": false,
|
||||
"dns_servers": ["127.0.0.1"],
|
||||
"allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure": true
|
||||
}))
|
||||
.unwrap();
|
||||
let runtime = tokio::runtime::Handle::current();
|
||||
let server = Arc::new(Server::new(
|
||||
config,
|
||||
Some(runtime.clone()),
|
||||
Log {
|
||||
reload: LogLevelReloadHandles::default(),
|
||||
capture: Arc::default(),
|
||||
},
|
||||
Metrics::new(Some(runtime), opentelemetry::global::meter("test"), None),
|
||||
));
|
||||
let services = crate::Services::build(server).await.unwrap();
|
||||
(services, path)
|
||||
}
|
||||
|
||||
fn cache_key(
|
||||
services: &crate::Services,
|
||||
server: &ruma::ServerName,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::{borrow::Borrow, fmt::Debug, mem::size_of_val, sync::Arc};
|
||||
use std::{borrow::Borrow, collections::HashMap, fmt::Debug, mem::size_of_val, sync::Arc};
|
||||
|
||||
pub use conduwuit::matrix::pdu::{ShortEventId, ShortId, ShortRoomId, ShortStateKey};
|
||||
use conduwuit::{
|
||||
@@ -72,14 +72,22 @@ impl Service {
|
||||
where
|
||||
I: Iterator<Item = &'a EventId> + Clone + Debug + Send + 'a,
|
||||
{
|
||||
let mut created: HashMap<OwnedEventId, ShortEventId> = HashMap::new();
|
||||
event_ids
|
||||
.clone()
|
||||
.stream()
|
||||
.get(&self.db.eventid_shorteventid)
|
||||
.zip(event_ids.into_iter().stream())
|
||||
.map(|(result, event_id)| match result {
|
||||
.map(move |(result, event_id)| match result {
|
||||
| Ok(ref short) => utils::u64_from_u8(short),
|
||||
| Err(_) => self.create_shorteventid(event_id),
|
||||
| Err(_) =>
|
||||
if let Some(&short) = created.get(event_id) {
|
||||
short
|
||||
} else {
|
||||
let short = self.create_shorteventid(event_id);
|
||||
created.insert(event_id.to_owned(), short);
|
||||
short
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -217,32 +225,24 @@ impl Service {
|
||||
.map(Deserialized::deserialized)
|
||||
}
|
||||
|
||||
/// Gets or creates a short state hash ID. The boolean indicates whether a
|
||||
/// new short ID was created.
|
||||
pub async fn get_or_create_shortstatehash(
|
||||
&self,
|
||||
state_hash: &[u8],
|
||||
) -> (ShortStateHash, bool) {
|
||||
const BUFSIZE: usize = size_of::<ShortStateHash>();
|
||||
|
||||
if let Ok(shortstatehash) = self
|
||||
.db
|
||||
/// Gets an existing short state hash ID without creating one.
|
||||
pub async fn get_shortstatehash(&self, state_hash: &[u8]) -> Result<ShortStateHash> {
|
||||
self.db
|
||||
.statehash_shortstatehash
|
||||
.get(state_hash)
|
||||
.await
|
||||
.deserialized()
|
||||
{
|
||||
return (shortstatehash, true);
|
||||
}
|
||||
}
|
||||
|
||||
let shortstatehash = self.services.globals.next_count().unwrap();
|
||||
/// Publishes the mapping from state hash to short state hash after the
|
||||
/// corresponding state diff has been written.
|
||||
pub fn set_shortstatehash(&self, state_hash: &[u8], shortstatehash: ShortStateHash) {
|
||||
const BUFSIZE: usize = size_of::<ShortStateHash>();
|
||||
debug_assert!(size_of_val(&shortstatehash) == BUFSIZE, "buffer requirement changed");
|
||||
|
||||
self.db
|
||||
.statehash_shortstatehash
|
||||
.raw_aput::<BUFSIZE, _, _>(state_hash, shortstatehash);
|
||||
|
||||
(shortstatehash, false)
|
||||
}
|
||||
|
||||
/// Gets a short room ID.
|
||||
|
||||
@@ -170,47 +170,50 @@ impl Service {
|
||||
|
||||
let state_hash = calculate_hash(state_ids_compressed.iter().map(|s| &s[..]));
|
||||
|
||||
let (shortstatehash, already_existed) = self
|
||||
.services
|
||||
.short
|
||||
.get_or_create_shortstatehash(&state_hash)
|
||||
.await;
|
||||
|
||||
if !already_existed {
|
||||
let states_parents = match previous_shortstatehash {
|
||||
| Ok(p) =>
|
||||
self.services
|
||||
.state_compressor
|
||||
.load_shortstatehash_info(p)
|
||||
.await?,
|
||||
| _ => Vec::new(),
|
||||
};
|
||||
|
||||
let (statediffnew, statediffremoved) =
|
||||
if let Some(parent_stateinfo) = states_parents.last() {
|
||||
let statediffnew: CompressedState = state_ids_compressed
|
||||
.difference(&parent_stateinfo.full_state)
|
||||
.copied()
|
||||
.collect();
|
||||
|
||||
let statediffremoved: CompressedState = parent_stateinfo
|
||||
.full_state
|
||||
.difference(&state_ids_compressed)
|
||||
.copied()
|
||||
.collect();
|
||||
|
||||
(Arc::new(statediffnew), Arc::new(statediffremoved))
|
||||
} else {
|
||||
(state_ids_compressed, Arc::new(CompressedState::new()))
|
||||
let shortstatehash =
|
||||
if let Ok(existing) = self.services.short.get_shortstatehash(&state_hash).await {
|
||||
existing
|
||||
} else {
|
||||
let states_parents = match previous_shortstatehash {
|
||||
| Ok(p) =>
|
||||
self.services
|
||||
.state_compressor
|
||||
.load_shortstatehash_info(p)
|
||||
.await?,
|
||||
| _ => Vec::new(),
|
||||
};
|
||||
self.services.state_compressor.save_state_from_diff(
|
||||
shortstatehash,
|
||||
statediffnew,
|
||||
statediffremoved,
|
||||
1_000_000, // high number because no state will be based on this one
|
||||
states_parents,
|
||||
)?;
|
||||
}
|
||||
|
||||
let (statediffnew, statediffremoved) =
|
||||
if let Some(parent_stateinfo) = states_parents.last() {
|
||||
let statediffnew: CompressedState = state_ids_compressed
|
||||
.difference(&parent_stateinfo.full_state)
|
||||
.copied()
|
||||
.collect();
|
||||
|
||||
let statediffremoved: CompressedState = parent_stateinfo
|
||||
.full_state
|
||||
.difference(&state_ids_compressed)
|
||||
.copied()
|
||||
.collect();
|
||||
|
||||
(Arc::new(statediffnew), Arc::new(statediffremoved))
|
||||
} else {
|
||||
(state_ids_compressed, Arc::new(CompressedState::new()))
|
||||
};
|
||||
|
||||
let new_shortstatehash = self.services.globals.next_count()?;
|
||||
self.services.state_compressor.save_state_from_diff(
|
||||
new_shortstatehash,
|
||||
statediffnew,
|
||||
statediffremoved,
|
||||
1_000_000, // high number because no state will be based on this one
|
||||
states_parents,
|
||||
)?;
|
||||
self.services
|
||||
.short
|
||||
.set_shortstatehash(&state_hash, new_shortstatehash);
|
||||
new_shortstatehash
|
||||
};
|
||||
|
||||
self.db
|
||||
.shorteventid_shortstatehash
|
||||
|
||||
@@ -18,7 +18,7 @@ use lru_cache::LruCache;
|
||||
use ruma::{EventId, RoomId};
|
||||
|
||||
use crate::{
|
||||
Dep, rooms,
|
||||
Dep, globals, rooms,
|
||||
rooms::short::{ShortEventId, ShortId, ShortStateHash, ShortStateKey},
|
||||
};
|
||||
|
||||
@@ -29,6 +29,7 @@ pub struct Service {
|
||||
}
|
||||
|
||||
struct Services {
|
||||
globals: Dep<globals::Service>,
|
||||
short: Dep<rooms::short::Service>,
|
||||
state: Dep<rooms::state::Service>,
|
||||
}
|
||||
@@ -78,6 +79,7 @@ impl crate::Service for Service {
|
||||
shortstatehash_statediff: args.db["shortstatehash_statediff"].clone(),
|
||||
},
|
||||
services: Services {
|
||||
globals: args.depend::<globals::Service>("globals"),
|
||||
short: args.depend::<rooms::short::Service>("rooms::short"),
|
||||
state: args.depend::<rooms::state::Service>("rooms::state"),
|
||||
},
|
||||
@@ -368,17 +370,17 @@ impl Service {
|
||||
let state_hash =
|
||||
utils::calculate_hash(new_state_ids_compressed.iter().map(|bytes| &bytes[..]));
|
||||
|
||||
let (new_shortstatehash, already_existed) = self
|
||||
let existing = self
|
||||
.services
|
||||
.short
|
||||
.get_or_create_shortstatehash(&state_hash)
|
||||
.await;
|
||||
.get_shortstatehash(&state_hash)
|
||||
.await
|
||||
.ok();
|
||||
|
||||
if Some(new_shortstatehash) == previous_shortstatehash {
|
||||
return Ok(HashSetCompressStateEvent {
|
||||
shortstatehash: new_shortstatehash,
|
||||
..Default::default()
|
||||
});
|
||||
if let Some(shortstatehash) = existing
|
||||
&& Some(shortstatehash) == previous_shortstatehash
|
||||
{
|
||||
return Ok(HashSetCompressStateEvent { shortstatehash, ..Default::default() });
|
||||
}
|
||||
|
||||
let states_parents = if let Some(p) = previous_shortstatehash {
|
||||
@@ -405,7 +407,10 @@ impl Service {
|
||||
(new_state_ids_compressed, Arc::new(CompressedState::new()))
|
||||
};
|
||||
|
||||
if !already_existed {
|
||||
let new_shortstatehash = if let Some(existing) = existing {
|
||||
existing
|
||||
} else {
|
||||
let new_shortstatehash = self.services.globals.next_count()?;
|
||||
self.save_state_from_diff(
|
||||
new_shortstatehash,
|
||||
statediffnew.clone(),
|
||||
@@ -413,7 +418,11 @@ impl Service {
|
||||
2, // every state change is 2 event changes on average
|
||||
states_parents,
|
||||
)?;
|
||||
}
|
||||
self.services
|
||||
.short
|
||||
.set_shortstatehash(&state_hash, new_shortstatehash);
|
||||
new_shortstatehash
|
||||
};
|
||||
|
||||
Ok(HashSetCompressStateEvent {
|
||||
shortstatehash: new_shortstatehash,
|
||||
@@ -437,7 +446,10 @@ impl Service {
|
||||
err!(Database("Failed to find StateDiff from short {shortstatehash:?}: {e}"))
|
||||
})?;
|
||||
|
||||
let parent = utils::u64_from_bytes(&value[0..size_of::<u64>()])
|
||||
let parent_bytes = value
|
||||
.get(0..size_of::<u64>())
|
||||
.ok_or_else(|| err!(Database("Truncated StateDiff for short {shortstatehash:?}")))?;
|
||||
let parent = utils::u64_from_bytes(parent_bytes)
|
||||
.ok()
|
||||
.take_if(|parent| *parent != 0);
|
||||
|
||||
@@ -472,10 +484,14 @@ impl Service {
|
||||
|
||||
/// Stores a new state diff with a shortstatehash.
|
||||
fn save_statediff(&self, shortstatehash: ShortStateHash, diff: &StateDiff) {
|
||||
const STRIDE: usize = size_of::<ShortStateHash>();
|
||||
|
||||
let mut value = Vec::<u8>::with_capacity(
|
||||
2_usize
|
||||
.saturating_add(diff.added.len())
|
||||
.saturating_add(diff.removed.len()),
|
||||
1_usize
|
||||
.saturating_add(usize::from(!diff.removed.is_empty()))
|
||||
.saturating_add(diff.added.len().saturating_mul(2))
|
||||
.saturating_add(diff.removed.len().saturating_mul(2))
|
||||
.saturating_mul(STRIDE),
|
||||
);
|
||||
|
||||
let parent = diff.parent.unwrap_or(0_u64);
|
||||
|
||||
@@ -349,7 +349,7 @@ impl super::Service {
|
||||
|
||||
// Insert pdu
|
||||
self.db
|
||||
.append_pdu(&pdu_id, pdu, room_id, &pdu_json, count2)
|
||||
.append_pdu(&pdu_id, pdu, room_id, &pdu_json, count2, pdu.origin_server_ts())
|
||||
.await;
|
||||
self.progress_extremities(pdu)
|
||||
.await
|
||||
|
||||
@@ -225,7 +225,8 @@ impl super::Service {
|
||||
.into();
|
||||
|
||||
// Insert pdu
|
||||
self.db.prepend_backfill_pdu(&pdu_id, &event_id, &value);
|
||||
self.db
|
||||
.prepend_backfill_pdu(&pdu_id, &event_id, &value, pdu.origin_server_ts());
|
||||
|
||||
drop(insert_lock);
|
||||
if pdu.kind == TimelineEventType::RoomMessage {
|
||||
|
||||
@@ -12,7 +12,9 @@ use database::{Database, Deserialized, Json, KeyVal, Map};
|
||||
use futures::{
|
||||
FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt, future::select_ok, pin_mut,
|
||||
};
|
||||
use ruma::{CanonicalJsonObject, EventId, OwnedUserId, RoomId, api::Direction};
|
||||
use ruma::{
|
||||
CanonicalJsonObject, EventId, MilliSecondsSinceUnixEpoch, OwnedUserId, RoomId, api::Direction,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::value::RawValue as RawJsonValue;
|
||||
|
||||
@@ -25,6 +27,7 @@ pub(super) struct Data {
|
||||
pduid_pdu: Arc<Map>,
|
||||
pduid_unredactedcontent: Arc<Map>,
|
||||
roomid_lasttimelinecount: Arc<Map>,
|
||||
roomts_pduid: Arc<Map>,
|
||||
userroomid_highlightcount: Arc<Map>,
|
||||
userroomid_notificationcount: Arc<Map>,
|
||||
pub(super) db: Arc<Database>,
|
||||
@@ -52,6 +55,7 @@ impl Data {
|
||||
pduid_pdu: db["pduid_pdu"].clone(),
|
||||
pduid_unredactedcontent: db["pduid_unredactedcontent"].clone(),
|
||||
roomid_lasttimelinecount: db["roomid_lasttimelinecount"].clone(),
|
||||
roomts_pduid: db["roomts_pduid"].clone(),
|
||||
userroomid_highlightcount: db["userroomid_highlightcount"].clone(),
|
||||
userroomid_notificationcount: db["userroomid_notificationcount"].clone(),
|
||||
db: args.db.clone(),
|
||||
@@ -213,10 +217,12 @@ impl Data {
|
||||
room_id: &RoomId,
|
||||
json: &CanonicalJsonObject,
|
||||
count: PduCount,
|
||||
index_ts: MilliSecondsSinceUnixEpoch,
|
||||
) {
|
||||
debug_assert!(matches!(count, PduCount::Normal(_)), "PduCount not Normal");
|
||||
|
||||
self.pduid_pdu.raw_put(pdu_id, Json(json));
|
||||
self.roomts_pduid.insert(&roomts_key(pdu_id, index_ts), []);
|
||||
self.eventid_pduid.insert(pdu.event_id.as_bytes(), pdu_id);
|
||||
self.eventid_outlierpdu.remove(pdu.event_id.as_bytes());
|
||||
self.roomid_lasttimelinecount
|
||||
@@ -228,8 +234,10 @@ impl Data {
|
||||
pdu_id: &RawPduId,
|
||||
event_id: &EventId,
|
||||
json: &CanonicalJsonObject,
|
||||
index_ts: MilliSecondsSinceUnixEpoch,
|
||||
) {
|
||||
self.pduid_pdu.raw_put(pdu_id, Json(json));
|
||||
self.roomts_pduid.insert(&roomts_key(pdu_id, index_ts), []);
|
||||
self.eventid_pduid.insert(event_id, pdu_id);
|
||||
self.eventid_outlierpdu.remove(event_id);
|
||||
}
|
||||
@@ -322,6 +330,49 @@ impl Data {
|
||||
.try_flatten_stream()
|
||||
}
|
||||
|
||||
pub(super) fn pdus_by_timestamp<'a>(
|
||||
&'a self,
|
||||
room_id: &'a RoomId,
|
||||
timestamp: MilliSecondsSinceUnixEpoch,
|
||||
dir: Direction,
|
||||
) -> impl Stream<Item = Result<PdusIterItem>> + Send + 'a {
|
||||
self.services
|
||||
.short
|
||||
.get_shortroomid(room_id)
|
||||
.map_err(move |e| err!(Request(NotFound("Room {room_id:?} not found: {e:?}"))))
|
||||
.map_ok(move |shortroomid| {
|
||||
let seek = |shorteventid| {
|
||||
roomts_key(&PduId { shortroomid, shorteventid }.into(), timestamp)
|
||||
};
|
||||
let keys = match dir {
|
||||
| Direction::Forward => self
|
||||
.roomts_pduid
|
||||
.raw_keys_from(&seek(PduCount::min()))
|
||||
.left_stream(),
|
||||
| Direction::Backward => self
|
||||
.roomts_pduid
|
||||
.rev_raw_keys_from(&seek(PduCount::max()))
|
||||
.right_stream(),
|
||||
};
|
||||
|
||||
keys.ready_try_take_while(move |key| {
|
||||
Ok(key.starts_with(&shortroomid.to_be_bytes()))
|
||||
})
|
||||
.map_ok(roomts_key_to_pdu_id)
|
||||
.and_then(async move |pdu_id| {
|
||||
Ok((pdu_id.pdu_count(), self.get_pdu_from_id(&pdu_id).await?))
|
||||
})
|
||||
})
|
||||
.try_flatten_stream()
|
||||
}
|
||||
|
||||
pub(super) async fn timestamp_index_ready(&self) -> bool {
|
||||
self.db["global"]
|
||||
.exists(TIMESTAMP_INDEX_MIGRATION)
|
||||
.await
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
fn from_json_slice((pdu_id, pdu): KeyVal<'_>) -> Result<PdusIterItem> {
|
||||
let pdu_id: RawPduId = pdu_id.into();
|
||||
|
||||
@@ -376,9 +427,52 @@ impl Data {
|
||||
}
|
||||
}
|
||||
|
||||
pub const TIMESTAMP_INDEX_MIGRATION: &str = "populate_roomts_pduid";
|
||||
|
||||
#[must_use]
|
||||
pub fn roomts_key(pdu_id: &RawPduId, ts: MilliSecondsSinceUnixEpoch) -> Vec<u8> {
|
||||
let count = pdu_id.pdu_count().into_signed().cast_unsigned() ^ (1 << 63);
|
||||
[pdu_id.shortroomid(), u64::from(ts.get()).to_be_bytes(), count.to_be_bytes()].concat()
|
||||
}
|
||||
|
||||
fn roomts_key_to_pdu_id(key: &[u8]) -> RawPduId {
|
||||
let shortroomid = u64::from_be_bytes(key[0..8].try_into().expect("roomts key shortroomid"));
|
||||
let count = u64::from_be_bytes(key[16..24].try_into().expect("roomts key count")) ^ (1 << 63);
|
||||
|
||||
PduId {
|
||||
shortroomid,
|
||||
shorteventid: PduCount::from_signed(count.cast_signed()),
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
//TODO: this is an ABA
|
||||
fn increment(db: &Arc<Map>, key: &[u8]) {
|
||||
let old = db.get_blocking(key);
|
||||
let new = utils::increment(old.ok().as_deref());
|
||||
db.insert(key, new);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use ruma::uint;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn roomts_key_orders_by_ts_then_count() {
|
||||
let ids = [
|
||||
(PduCount::Normal(9), uint!(1)),
|
||||
(PduCount::Backfilled(-5), uint!(2)),
|
||||
(PduCount::Normal(3), uint!(2)),
|
||||
(PduCount::Normal(1), uint!(3)),
|
||||
]
|
||||
.map(|(count, ts)| (RawPduId::from(PduId { shortroomid: 7, shorteventid: count }), ts));
|
||||
let keys = ids.map(|(id, ts)| roomts_key(&id, MilliSecondsSinceUnixEpoch(ts)));
|
||||
|
||||
assert!(keys.is_sorted());
|
||||
for ((id, _), key) in ids.iter().zip(&keys) {
|
||||
assert_eq!(roomts_key_to_pdu_id(key), *id);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,8 +21,8 @@ use conduwuit_core::{
|
||||
};
|
||||
use futures::{Future, Stream, TryStreamExt, pin_mut};
|
||||
use ruma::{
|
||||
CanonicalJsonObject, EventId, OwnedEventId, OwnedRoomId, RoomId,
|
||||
events::room::encrypted::Relation,
|
||||
CanonicalJsonObject, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, RoomId,
|
||||
api::Direction, events::room::encrypted::Relation,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use serde_json::value::RawValue as RawJsonValue;
|
||||
@@ -32,7 +32,10 @@ use tokio::{
|
||||
};
|
||||
|
||||
use self::data::Data;
|
||||
pub use self::{create::pdu_fits, data::PdusIterItem};
|
||||
pub use self::{
|
||||
create::pdu_fits,
|
||||
data::{PdusIterItem, TIMESTAMP_INDEX_MIGRATION, roomts_key},
|
||||
};
|
||||
use crate::{
|
||||
Dep, account_data, admin, appservice, config, globals, pusher, rooms, sending, server_keys,
|
||||
sync, users,
|
||||
@@ -307,6 +310,17 @@ impl Service {
|
||||
self.pdus(room_id, None).ignore_err()
|
||||
}
|
||||
|
||||
pub fn pdus_by_timestamp<'a>(
|
||||
&'a self,
|
||||
room_id: &'a RoomId,
|
||||
timestamp: MilliSecondsSinceUnixEpoch,
|
||||
dir: Direction,
|
||||
) -> impl Stream<Item = Result<PdusIterItem>> + Send + 'a {
|
||||
self.db.pdus_by_timestamp(room_id, timestamp, dir)
|
||||
}
|
||||
|
||||
pub async fn timestamp_index_ready(&self) -> bool { self.db.timestamp_index_ready().await }
|
||||
|
||||
/// Reverse iteration starting after `until`.
|
||||
#[tracing::instrument(skip(self), level = "debug")]
|
||||
pub fn pdus_rev<'a>(
|
||||
|
||||
+73
-27
@@ -3,6 +3,7 @@ use std::{fmt::Debug, sync::Arc};
|
||||
use conduwuit::{
|
||||
Error, Result, at, utils,
|
||||
utils::{ReadyExt, stream::TryIgnore},
|
||||
warn,
|
||||
};
|
||||
use database::{Database, Deserialized, Map};
|
||||
use futures::{Stream, StreamExt};
|
||||
@@ -169,6 +170,51 @@ impl Data {
|
||||
})
|
||||
}
|
||||
|
||||
/// Destinations with at least one queued request not yet in flight.
|
||||
///
|
||||
/// Seeks past each destination's key prefix so large per-destination
|
||||
/// backlogs are skipped in O(destinations) seeks rather than scanning
|
||||
/// every queued event.
|
||||
pub(super) async fn queued_destinations(&self) -> Vec<Destination> {
|
||||
let mut dests = Vec::new();
|
||||
let mut cursor = Vec::new();
|
||||
|
||||
while let Some(key) = self
|
||||
.servernameevent_data
|
||||
.raw_keys_from(&cursor)
|
||||
.ignore_err()
|
||||
.next()
|
||||
.await
|
||||
{
|
||||
match parse_destination(key) {
|
||||
| Ok((dest, _)) => {
|
||||
let prefix = dest.get_prefix();
|
||||
dests.push(dest);
|
||||
let Some(next) = next_prefix(&prefix) else {
|
||||
break;
|
||||
};
|
||||
cursor = next;
|
||||
},
|
||||
| Err(e) => {
|
||||
warn!(?key, "invalid queued request key: {e}");
|
||||
cursor = key.to_vec();
|
||||
cursor.push(0);
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
dests
|
||||
}
|
||||
|
||||
/// Estimated number of requests waiting to be sent and in flight.
|
||||
pub(crate) fn request_counts(&self) -> [(&'static str, Option<u64>); 2] {
|
||||
[
|
||||
("queued", &self.servernameevent_data),
|
||||
("active", &self.servercurrentevent_data),
|
||||
]
|
||||
.map(|(state, map)| (state, map.property_integer(c"rocksdb.estimate-num-keys").ok()))
|
||||
}
|
||||
|
||||
pub(super) fn set_latest_educount(&self, server_name: &ServerName, last_count: u64) {
|
||||
self.servername_educount.raw_put(server_name, last_count);
|
||||
}
|
||||
@@ -182,9 +228,17 @@ impl Data {
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_servercurrentevent(key: &[u8], value: &[u8]) -> Result<(Destination, SendingEvent)> {
|
||||
/// Smallest byte slice strictly greater than every key starting with `prefix`.
|
||||
fn next_prefix(prefix: &[u8]) -> Option<Vec<u8>> {
|
||||
let pos = prefix.iter().rposition(|&b| b < u8::MAX)?;
|
||||
let mut next = prefix[..=pos].to_vec();
|
||||
next[pos] = next[pos].saturating_add(1);
|
||||
Some(next)
|
||||
}
|
||||
|
||||
fn parse_destination(key: &[u8]) -> Result<(Destination, &[u8])> {
|
||||
// Appservices start with a plus
|
||||
Ok::<_, Error>(if key.starts_with(b"+") {
|
||||
if key.starts_with(b"+") {
|
||||
let mut parts = key[1..].splitn(2, |&b| b == 0xFF);
|
||||
|
||||
let server = parts.next().expect("splitn always returns one element");
|
||||
@@ -196,14 +250,7 @@ fn parse_servercurrentevent(key: &[u8], value: &[u8]) -> Result<(Destination, Se
|
||||
Error::bad_database("Invalid server bytes in server_currenttransaction")
|
||||
})?;
|
||||
|
||||
(
|
||||
Destination::Appservice(server),
|
||||
if value.is_empty() {
|
||||
SendingEvent::Pdu(event.into())
|
||||
} else {
|
||||
SendingEvent::Edu(value.into())
|
||||
},
|
||||
)
|
||||
Ok((Destination::Appservice(server), event))
|
||||
} else if key.starts_with(b"$") {
|
||||
let mut parts = key[1..].splitn(3, |&b| b == 0xFF);
|
||||
|
||||
@@ -223,15 +270,7 @@ fn parse_servercurrentevent(key: &[u8], value: &[u8]) -> Result<(Destination, Se
|
||||
.next()
|
||||
.ok_or_else(|| Error::bad_database("Invalid bytes in servercurrentpdus."))?;
|
||||
|
||||
(
|
||||
Destination::Push(user_id, pushkey_string),
|
||||
if value.is_empty() {
|
||||
SendingEvent::Pdu(event.into())
|
||||
} else {
|
||||
// I'm pretty sure this should never be called
|
||||
SendingEvent::Edu(value.into())
|
||||
},
|
||||
)
|
||||
Ok((Destination::Push(user_id, pushkey_string), event))
|
||||
} else {
|
||||
let mut parts = key.splitn(2, |&b| b == 0xFF);
|
||||
|
||||
@@ -244,15 +283,22 @@ fn parse_servercurrentevent(key: &[u8], value: &[u8]) -> Result<(Destination, Se
|
||||
Error::bad_database("Invalid server bytes in server_currenttransaction")
|
||||
})?;
|
||||
|
||||
(
|
||||
Ok((
|
||||
Destination::Federation(ServerName::parse(&server).map_err(|_| {
|
||||
Error::bad_database("Invalid server string in server_currenttransaction")
|
||||
})?),
|
||||
if value.is_empty() {
|
||||
SendingEvent::Pdu(event.into())
|
||||
} else {
|
||||
SendingEvent::Edu(value.into())
|
||||
},
|
||||
)
|
||||
})
|
||||
event,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_servercurrentevent(key: &[u8], value: &[u8]) -> Result<(Destination, SendingEvent)> {
|
||||
let (dest, event) = parse_destination(key)?;
|
||||
let event = if value.is_empty() {
|
||||
SendingEvent::Pdu(event.into())
|
||||
} else {
|
||||
SendingEvent::Edu(value.into())
|
||||
};
|
||||
|
||||
Ok((dest, event))
|
||||
}
|
||||
+114
-24
@@ -3,12 +3,19 @@ mod appservice;
|
||||
mod data;
|
||||
mod dest;
|
||||
mod sender;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fmt::Debug,
|
||||
hash::{DefaultHasher, Hash, Hasher},
|
||||
iter::once,
|
||||
sync::Arc,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
@@ -19,7 +26,7 @@ use conduwuit::{
|
||||
utils::{ReadyExt, TryReadyExt, available_parallelism, math::usize_from_u64_truncated},
|
||||
warn,
|
||||
};
|
||||
use futures::{FutureExt, Stream, StreamExt};
|
||||
use futures::{FutureExt, Stream, StreamExt, stream::FuturesUnordered};
|
||||
use ruma::{
|
||||
OwnedServerName, RoomId, ServerName, UserId,
|
||||
api::{
|
||||
@@ -27,7 +34,7 @@ use ruma::{
|
||||
federation::authentication::ServerSignatures, path_builder::PathBuilder,
|
||||
},
|
||||
};
|
||||
use tokio::{task, task::JoinSet};
|
||||
use tokio::{task, task::JoinSet, time::sleep};
|
||||
|
||||
use self::data::Data;
|
||||
pub use self::{
|
||||
@@ -49,6 +56,7 @@ pub struct Service {
|
||||
server: Arc<Server>,
|
||||
services: Services,
|
||||
channels: Vec<(loole::Sender<Msg>, loole::Receiver<Msg>)>,
|
||||
workers_alive: AtomicUsize,
|
||||
}
|
||||
|
||||
struct Services {
|
||||
@@ -87,6 +95,8 @@ pub type EduVec = SmallVec<[EduBuf; EDU_VEC_CAP]>;
|
||||
|
||||
const EDU_BUF_CAP: usize = 128;
|
||||
const EDU_VEC_CAP: usize = 1;
|
||||
const WORKER_RESTART_DELAY: Duration = Duration::from_millis(2500);
|
||||
const WORKER_RESTART_DELAY_MAX: Duration = Duration::from_secs(30);
|
||||
|
||||
#[async_trait]
|
||||
impl crate::Service for Service {
|
||||
@@ -111,36 +121,67 @@ impl crate::Service for Service {
|
||||
federation: args.depend::<federation::Service>("federation"),
|
||||
},
|
||||
channels: (0..num_senders).map(|_| loole::unbounded()).collect(),
|
||||
workers_alive: AtomicUsize::new(0),
|
||||
}))
|
||||
}
|
||||
|
||||
async fn worker(self: Arc<Self>) -> Result {
|
||||
let mut senders =
|
||||
self.channels
|
||||
.iter()
|
||||
.enumerate()
|
||||
.fold(JoinSet::new(), |mut joinset, (id, _)| {
|
||||
let self_ = self.clone();
|
||||
let worker = self_.sender(id);
|
||||
let worker = if self.unconstrained() {
|
||||
task::unconstrained(worker).boxed()
|
||||
} else {
|
||||
worker.boxed()
|
||||
if self.server.config.startup_netburst {
|
||||
self.dispatch_queued(None).await;
|
||||
}
|
||||
|
||||
let num_senders = self.channels.len();
|
||||
let mut senders = JoinSet::new();
|
||||
let mut shards = HashMap::new();
|
||||
let mut started = vec![Instant::now(); num_senders];
|
||||
let mut failures = vec![0_u32; num_senders];
|
||||
let mut restarts = FuturesUnordered::new();
|
||||
for id in 0..num_senders {
|
||||
self.spawn_sender(&mut senders, &mut shards, id, false);
|
||||
}
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
Some(ret) = senders.join_next_with_id() => {
|
||||
self.workers_alive.fetch_sub(1, Ordering::Relaxed);
|
||||
let (task_id, panicked) = match &ret {
|
||||
| Ok((task_id, _)) => (*task_id, false),
|
||||
| Err(error) => (error.id(), error.is_panic()),
|
||||
};
|
||||
let shard = shards.remove(&task_id).expect("sender worker has a shard");
|
||||
|
||||
let runtime = self.server.runtime();
|
||||
let _abort = joinset.spawn_on(worker, runtime);
|
||||
joinset
|
||||
});
|
||||
if panicked {
|
||||
self.server
|
||||
.metrics
|
||||
.instruments
|
||||
.sender_panics
|
||||
.add(1, &[KeyValue::new("scope", "worker")]);
|
||||
}
|
||||
|
||||
while let Some(ret) = senders.join_next_with_id().await {
|
||||
match ret {
|
||||
| Ok((id, error)) => {
|
||||
debug!(?id, ?error, "sender worker finished");
|
||||
if self.channels[shard].1.is_closed() || !self.server.running() {
|
||||
debug!(shard, ?ret, "sender worker finished");
|
||||
continue;
|
||||
}
|
||||
|
||||
// A worker that ran a while before failing starts over from
|
||||
// the shortest delay.
|
||||
failures[shard] = if started[shard].elapsed() > WORKER_RESTART_DELAY_MAX {
|
||||
1
|
||||
} else {
|
||||
failures[shard].saturating_add(1)
|
||||
};
|
||||
let delay = restart_delay(failures[shard]);
|
||||
error!(shard, ?ret, ?delay, "sender worker unexpectedly finished, restarting");
|
||||
restarts.push(sleep(delay).map(move |()| shard));
|
||||
},
|
||||
| Err(error) => {
|
||||
error!(id = ?error.id(), ?error, "sender worker failed");
|
||||
Some(shard) = restarts.next() => {
|
||||
if !self.channels[shard].1.is_closed() && self.server.running() {
|
||||
started[shard] = Instant::now();
|
||||
self.spawn_sender(&mut senders, &mut shards, shard, true);
|
||||
}
|
||||
},
|
||||
() = self.server.until_shutdown(), if !restarts.is_empty() => restarts.clear(),
|
||||
else => break,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,6 +202,25 @@ impl crate::Service for Service {
|
||||
}
|
||||
|
||||
impl Service {
|
||||
fn spawn_sender(
|
||||
self: &Arc<Self>,
|
||||
senders: &mut JoinSet<Result>,
|
||||
shards: &mut HashMap<task::Id, usize>,
|
||||
id: usize,
|
||||
restarted: bool,
|
||||
) {
|
||||
let worker = self.clone().sender(id, restarted);
|
||||
let worker = if crate::Service::unconstrained(&**self) {
|
||||
task::unconstrained(worker).boxed()
|
||||
} else {
|
||||
worker.boxed()
|
||||
};
|
||||
|
||||
let handle = senders.spawn_on(worker, self.server.runtime());
|
||||
shards.insert(handle.id(), id);
|
||||
self.workers_alive.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(self, pdu_id, user, pushkey), level = "debug")]
|
||||
pub fn send_pdu_push(&self, pdu_id: &RawPduId, user: &UserId, pushkey: String) -> Result {
|
||||
let dest = Destination::Push(user.to_owned(), pushkey);
|
||||
@@ -480,10 +540,32 @@ impl Service {
|
||||
sender.send(msg).map_err(|e| err!("{e}"))
|
||||
}
|
||||
|
||||
/// Wakes workers for every destination that has unsent queued requests, so
|
||||
/// a backlog with nothing in flight is drained without waiting for a new
|
||||
/// event. Uses `SendingEvent::Flush` so a message racing with already-
|
||||
/// buffered channel items cannot re-insert and duplicate a sent request.
|
||||
async fn dispatch_queued(&self, shard: Option<usize>) {
|
||||
for dest in self.db.queued_destinations().await {
|
||||
let id = self.shard_id(&dest);
|
||||
if shard.is_none_or(|shard| shard == id) {
|
||||
self.channels[id]
|
||||
.0
|
||||
.send(Msg {
|
||||
dest,
|
||||
event: SendingEvent::Flush,
|
||||
queue_id: Vec::new(),
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn queue_depth(&self) -> usize {
|
||||
self.channels.iter().map(|(sender, _)| sender.len()).sum()
|
||||
}
|
||||
|
||||
pub fn workers_alive(&self) -> usize { self.workers_alive.load(Ordering::Relaxed) }
|
||||
|
||||
pub(super) fn shard_id(&self, dest: &Destination) -> usize {
|
||||
if self.channels.len() <= 1 {
|
||||
return 0;
|
||||
@@ -519,3 +601,11 @@ fn num_senders(args: &crate::Args<'_>) -> usize {
|
||||
worker_count.clamp(MIN_SENDERS, max_senders)
|
||||
}
|
||||
}
|
||||
|
||||
/// Delay before restarting a worker after its `failures`-th consecutive
|
||||
/// failure, doubling each time.
|
||||
fn restart_delay(failures: u32) -> Duration {
|
||||
WORKER_RESTART_DELAY
|
||||
.saturating_mul(2_u32.saturating_pow(failures.saturating_sub(1)))
|
||||
.min(WORKER_RESTART_DELAY_MAX)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap, HashSet},
|
||||
fmt::Debug,
|
||||
panic::AssertUnwindSafe,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicU64, AtomicUsize, Ordering},
|
||||
@@ -55,11 +56,17 @@ use serde_json::value::{RawValue as RawJsonValue, to_raw_value};
|
||||
|
||||
use super::{Destination, EduBuf, EduVec, Msg, SendingEvent, Service, data::QueueItem};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[derive(Debug)]
|
||||
enum TransactionStatus {
|
||||
Running,
|
||||
Failed(u32, Instant), // number of times failed, time of last failure
|
||||
Retrying(u32), // number of times failed
|
||||
/// Number of times failed, time of last failure, and whether local backoff
|
||||
/// applies even for federation destinations (e.g. after a local panic when
|
||||
/// the remote was not marked unhealthy).
|
||||
Failed(u32, Instant, bool),
|
||||
Retrying(u32), // number of times failed
|
||||
}
|
||||
|
||||
type SendingError = (Destination, Box<Error>);
|
||||
@@ -78,12 +85,18 @@ pub const EDU_LIMIT: usize = 100;
|
||||
|
||||
impl Service {
|
||||
#[tracing::instrument(skip(self), level = "debug")]
|
||||
pub(super) async fn sender(self: Arc<Self>, id: usize) -> Result {
|
||||
pub(super) async fn sender(self: Arc<Self>, id: usize, restarted: bool) -> Result {
|
||||
let mut statuses: CurTransactionStatus = CurTransactionStatus::new();
|
||||
let mut futures: SendingFutures<'_> = FuturesUnordered::new();
|
||||
|
||||
// The previous worker of this shard may have dropped requests it had
|
||||
// taken from the channel.
|
||||
if restarted {
|
||||
self.dispatch_queued(Some(id)).await;
|
||||
}
|
||||
|
||||
info!(shard = id, "Running startup netburst");
|
||||
self.startup_netburst(id, &mut futures, &mut statuses)
|
||||
self.startup_netburst(id, restarted, &mut futures, &mut statuses)
|
||||
.boxed()
|
||||
.await;
|
||||
info!(shard = id, "Finished startup netburst");
|
||||
@@ -142,7 +155,12 @@ impl Service {
|
||||
) {
|
||||
match response {
|
||||
| Ok(dest) => self.handle_response_ok(&dest, futures, statuses).await,
|
||||
// A bug on our side, not the remote's fault: retry with local
|
||||
// backoff without marking the remote unhealthy.
|
||||
| Err((dest, e)) if e.is_panic() =>
|
||||
Self::handle_response_err(dest, statuses, &e, true),
|
||||
| Err((dest, e)) => {
|
||||
let mut local_backoff = false;
|
||||
if let Destination::Federation(dest) = &dest {
|
||||
if self.services.federation.should_mark_stale(&e)
|
||||
|| e.status_code() == StatusCode::NOT_FOUND
|
||||
@@ -153,22 +171,30 @@ impl Service {
|
||||
} else if e.status_code() != StatusCode::OK {
|
||||
debug!("{dest} is now unhealthy due to error response: {e:?}");
|
||||
self.services.federation.hit_unhealthy(dest.clone(), None);
|
||||
} else {
|
||||
local_backoff = true;
|
||||
}
|
||||
}
|
||||
Self::handle_response_err(dest, statuses, &e);
|
||||
Self::handle_response_err(dest, statuses, &e, local_backoff);
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles a response error, incrementing the backoff factor.
|
||||
fn handle_response_err(dest: Destination, statuses: &mut CurTransactionStatus, er: &Error) {
|
||||
fn handle_response_err(
|
||||
dest: Destination,
|
||||
statuses: &mut CurTransactionStatus,
|
||||
er: &Error,
|
||||
local_backoff: bool,
|
||||
) {
|
||||
debug!(dest = ?dest, "{er:?}");
|
||||
let dest2 = dest.clone();
|
||||
statuses.entry(dest).and_modify(|e| {
|
||||
*e = match e {
|
||||
| TransactionStatus::Running => TransactionStatus::Failed(1, Instant::now()),
|
||||
| TransactionStatus::Running =>
|
||||
TransactionStatus::Failed(1, Instant::now(), local_backoff),
|
||||
| &mut TransactionStatus::Retrying(ref n) =>
|
||||
TransactionStatus::Failed(n.saturating_add(1), Instant::now()),
|
||||
TransactionStatus::Failed(n.saturating_add(1), Instant::now(), local_backoff),
|
||||
| TransactionStatus::Failed(..) => {
|
||||
panic!(
|
||||
"Request to {dest2:?} that was not even running ({e:?}) failed: {er:?}"
|
||||
@@ -274,7 +300,8 @@ impl Service {
|
||||
}
|
||||
|
||||
/// Performs startup netburst, which sends any previously queued up but not
|
||||
/// yet sent requests immediately.
|
||||
/// yet sent requests immediately. A restarted worker always resends its
|
||||
/// shard's requests in flight.
|
||||
#[tracing::instrument(
|
||||
name = "netburst",
|
||||
level = "debug",
|
||||
@@ -285,9 +312,11 @@ impl Service {
|
||||
async fn startup_netburst<'a>(
|
||||
&'a self,
|
||||
id: usize,
|
||||
restarted: bool,
|
||||
futures: &mut SendingFutures<'a>,
|
||||
statuses: &mut CurTransactionStatus,
|
||||
) {
|
||||
let delivering = restarted || self.server.config.startup_netburst;
|
||||
let keep =
|
||||
usize::try_from(self.server.config.startup_netburst_keep).unwrap_or(usize::MAX);
|
||||
let mut txns = HashMap::<Destination, Vec<SendingEvent>>::new();
|
||||
@@ -302,7 +331,7 @@ impl Service {
|
||||
let over_budget =
|
||||
self.server.config.startup_netburst_keep >= 0 && entry.len() >= keep;
|
||||
|
||||
if over_budget && !self.survives_netburst_trim(&event).await {
|
||||
if over_budget && !self.survives_netburst_trim(&event, delivering).await {
|
||||
warn!(
|
||||
startup_netburst_keep = self.server.config.startup_netburst_keep,
|
||||
queue_size = entry.len(),
|
||||
@@ -315,8 +344,12 @@ impl Service {
|
||||
}
|
||||
}
|
||||
|
||||
if !delivering {
|
||||
return;
|
||||
}
|
||||
|
||||
for (dest, events) in txns {
|
||||
if self.server.config.startup_netburst && !events.is_empty() {
|
||||
if !events.is_empty() {
|
||||
statuses.insert(dest.clone(), TransactionStatus::Running);
|
||||
futures.push(self.send_events(dest, events));
|
||||
}
|
||||
@@ -324,10 +357,10 @@ impl Service {
|
||||
}
|
||||
|
||||
/// Whether this event skips the netburst budget, which MSC4354 asks of
|
||||
/// still-sticky events. Only netburst delivers this queue, so with it
|
||||
/// disabled there is nothing to keep the event for.
|
||||
async fn survives_netburst_trim(&self, event: &SendingEvent) -> bool {
|
||||
if !self.server.config.startup_netburst {
|
||||
/// still-sticky events. Only a delivering netburst drains this queue, so
|
||||
/// when nothing will deliver it there is nothing to keep the event for.
|
||||
async fn survives_netburst_trim(&self, event: &SendingEvent, delivering: bool) -> bool {
|
||||
if !delivering {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -425,12 +458,17 @@ impl Service {
|
||||
allow = false; // already running
|
||||
trace!("Transaction is already running for {dest:?}");
|
||||
},
|
||||
| TransactionStatus::Failed(tries, _) => {
|
||||
if allow {
|
||||
| TransactionStatus::Failed(tries, time, local_backoff) => {
|
||||
if *local_backoff
|
||||
&& time.elapsed() < self.server.config.sender_retry_backoff(*tries)
|
||||
{
|
||||
allow = false;
|
||||
trace!("{dest:?} is in local backoff, refusing send");
|
||||
} else {
|
||||
*e = TransactionStatus::Retrying(*tries);
|
||||
trace!("Previous transaction failed for {dest:?} ({e:?}), will retry");
|
||||
retry = true;
|
||||
}
|
||||
retry = true;
|
||||
},
|
||||
});
|
||||
|
||||
@@ -449,7 +487,7 @@ impl Service {
|
||||
statuses
|
||||
.entry(dest.clone())
|
||||
.and_modify(|e| match e {
|
||||
| TransactionStatus::Failed(tries, time) => {
|
||||
| TransactionStatus::Failed(tries, time, _) => {
|
||||
let retry_after = self.server.config.sender_retry_backoff(*tries);
|
||||
if time.elapsed() < retry_after {
|
||||
debug_warn!("Not retrying destination for another {retry_after:?}");
|
||||
@@ -772,6 +810,7 @@ impl Service {
|
||||
});
|
||||
|
||||
let start = Instant::now();
|
||||
let panic_dest = dest.clone();
|
||||
let send = match dest {
|
||||
| Destination::Federation(server) =>
|
||||
self.send_events_dest_federation(server, events).boxed(),
|
||||
@@ -780,24 +819,42 @@ impl Service {
|
||||
self.send_events_dest_push(user_id, pushkey, events).boxed(),
|
||||
};
|
||||
|
||||
send.inspect(move |result| {
|
||||
let instruments = &self.server.metrics.instruments;
|
||||
let outcome =
|
||||
KeyValue::new("outcome", if result.is_ok() { "success" } else { "failure" });
|
||||
instruments
|
||||
.sender_transaction_duration
|
||||
.record(start.elapsed().as_secs_f64(), &[destination.clone(), outcome.clone()]);
|
||||
for (kind, count) in [("pdu", pdus), ("edu", edus)] {
|
||||
if count > 0 {
|
||||
instruments.sender_events.add(count, &[
|
||||
AssertUnwindSafe(send)
|
||||
.catch_unwind()
|
||||
.map(move |result| {
|
||||
result.unwrap_or_else(|panic| {
|
||||
let error = Error::from_panic(panic);
|
||||
error!(dest = ?panic_dest, ?error, "Panicked while sending transaction");
|
||||
self.server
|
||||
.metrics
|
||||
.instruments
|
||||
.sender_panics
|
||||
.add(1, &[KeyValue::new("scope", "transaction")]);
|
||||
|
||||
Err((panic_dest, Box::new(error)))
|
||||
})
|
||||
})
|
||||
.inspect(move |result| {
|
||||
let instruments = &self.server.metrics.instruments;
|
||||
let outcome =
|
||||
KeyValue::new("outcome", if result.is_ok() { "success" } else { "failure" });
|
||||
instruments
|
||||
.sender_transaction_duration
|
||||
.record(start.elapsed().as_secs_f64(), &[
|
||||
destination.clone(),
|
||||
KeyValue::new("kind", kind),
|
||||
outcome.clone(),
|
||||
]);
|
||||
for (kind, count) in [("pdu", pdus), ("edu", edus)] {
|
||||
if count > 0 {
|
||||
instruments.sender_events.add(count, &[
|
||||
destination.clone(),
|
||||
KeyValue::new("kind", kind),
|
||||
outcome.clone(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.boxed()
|
||||
})
|
||||
.boxed()
|
||||
}
|
||||
|
||||
#[tracing::instrument(
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
use std::iter::once;
|
||||
|
||||
use conduwuit::{
|
||||
Error,
|
||||
matrix::{PartialPdu, pdu::sticky},
|
||||
};
|
||||
use futures::{StreamExt, stream::FuturesUnordered};
|
||||
use ruma::{RoomId, UserId, events::sticky::StickyDurationMs, server_name};
|
||||
use serde_json::{json, value::to_raw_value};
|
||||
|
||||
use super::{CurTransactionStatus, TransactionStatus};
|
||||
use crate::{
|
||||
sending::{Destination, EduBuf, SendingEvent},
|
||||
test_utils::{test_services, test_services_with},
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
async fn panicked_transaction_is_kept_for_retry_without_blaming_the_remote() {
|
||||
let (services, path, _database) = test_services().await;
|
||||
let sending = &services.sending;
|
||||
let server = server_name!("remote.example");
|
||||
let dest = Destination::Federation(server.to_owned());
|
||||
let event = SendingEvent::Edu(EduBuf::from_slice(br#"{"edu_type":"m.typing"}"#));
|
||||
|
||||
sending.db.queue_requests(once((&event, &dest)));
|
||||
let in_flight: Vec<_> = sending.db.queued_requests(&dest).collect().await;
|
||||
sending.db.mark_as_active(in_flight.iter());
|
||||
|
||||
let mut futures = FuturesUnordered::new();
|
||||
let mut statuses = CurTransactionStatus::from([(dest.clone(), TransactionStatus::Running)]);
|
||||
let panic = Error::from_panic(Box::new("boom"));
|
||||
sending
|
||||
.handle_response(Err((dest.clone(), Box::new(panic))), &mut futures, &mut statuses)
|
||||
.await;
|
||||
|
||||
let active: Vec<_> = sending
|
||||
.db
|
||||
.active_requests_for(&dest)
|
||||
.map(|(key, _)| key)
|
||||
.collect()
|
||||
.await;
|
||||
let retry_after = sending.services.federation.retry_after(server);
|
||||
let sending_next = futures.len();
|
||||
let failed = matches!(statuses.get(&dest), Some(TransactionStatus::Failed(1, _, true)));
|
||||
let immediate_retry = sending.should_attempt_send(&dest, &mut statuses).unwrap();
|
||||
|
||||
drop(futures);
|
||||
drop(services);
|
||||
std::fs::remove_dir_all(path).unwrap();
|
||||
assert_eq!(
|
||||
active,
|
||||
in_flight
|
||||
.into_iter()
|
||||
.map(|(key, _)| key)
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(sending_next, 0);
|
||||
assert!(failed);
|
||||
assert_eq!(immediate_retry, (false, false));
|
||||
assert_eq!(retry_after, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn restarted_worker_resends_trimmed_in_flight_requests() {
|
||||
let (services, path, _database) =
|
||||
test_services_with(json!({ "startup_netburst_keep": 1 })).await;
|
||||
let sending = &services.sending;
|
||||
let dest = Destination::Federation(server_name!("remote.example").to_owned());
|
||||
let event = SendingEvent::Edu(EduBuf::from_slice(br#"{"edu_type":"m.typing"}"#));
|
||||
|
||||
for _ in 0..3 {
|
||||
sending.db.queue_requests(once((&event, &dest)));
|
||||
}
|
||||
let queued: Vec<_> = sending.db.queued_requests(&dest).collect().await;
|
||||
sending.db.mark_as_active(queued.iter());
|
||||
|
||||
let id = sending.shard_id(&dest);
|
||||
let mut futures = FuturesUnordered::new();
|
||||
let mut statuses = CurTransactionStatus::new();
|
||||
sending
|
||||
.startup_netburst(id, true, &mut futures, &mut statuses)
|
||||
.await;
|
||||
let active = sending.db.active_requests_for(&dest).count().await;
|
||||
let sending_now = futures.len();
|
||||
|
||||
drop(futures);
|
||||
drop(services);
|
||||
std::fs::remove_dir_all(path).unwrap();
|
||||
assert_eq!(active, 1);
|
||||
assert_eq!(sending_now, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn restarted_worker_keeps_sticky_events_when_startup_netburst_is_disabled() {
|
||||
let (services, path, _database) =
|
||||
test_services_with(json!({ "startup_netburst": false, "startup_netburst_keep": 0 }))
|
||||
.await;
|
||||
let alice = UserId::parse("@alice:test.example").unwrap();
|
||||
let bootstrap = services
|
||||
.rooms
|
||||
.state
|
||||
.mutex
|
||||
.lock("!bootstrap:test.example")
|
||||
.await;
|
||||
let create_id = services
|
||||
.rooms
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
PartialPdu {
|
||||
event_type: "m.room.create".into(),
|
||||
content: to_raw_value(&json!({ "room_version": "12" })).unwrap(),
|
||||
state_key: Some("".into()),
|
||||
..Default::default()
|
||||
},
|
||||
&alice,
|
||||
None,
|
||||
&bootstrap,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
drop(bootstrap);
|
||||
|
||||
let room = RoomId::parse(create_id.as_str().replacen('$', "!", 1)).unwrap();
|
||||
let lock = services.rooms.state.mutex.lock(&room).await;
|
||||
services
|
||||
.rooms
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
PartialPdu {
|
||||
event_type: "m.room.member".into(),
|
||||
content: to_raw_value(&json!({ "membership": "join" })).unwrap(),
|
||||
state_key: Some(alice.as_str().into()),
|
||||
..Default::default()
|
||||
},
|
||||
&alice,
|
||||
Some(&room),
|
||||
&lock,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let sticky_id = services
|
||||
.rooms
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
PartialPdu {
|
||||
event_type: "m.room.message".into(),
|
||||
content: to_raw_value(&json!({ "msgtype": "m.text", "body": "sticky" })).unwrap(),
|
||||
sticky: Some(sticky::object(StickyDurationMs::new_clamped(600_000_u32))),
|
||||
..Default::default()
|
||||
},
|
||||
&alice,
|
||||
Some(&room),
|
||||
&lock,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
drop(lock);
|
||||
|
||||
let raw_pdu_id = services
|
||||
.rooms
|
||||
.timeline
|
||||
.get_pdu_id(&sticky_id)
|
||||
.await
|
||||
.unwrap();
|
||||
let sending = &services.sending;
|
||||
let dest = Destination::Federation(server_name!("remote.example").to_owned());
|
||||
let event = SendingEvent::Pdu(raw_pdu_id);
|
||||
|
||||
sending.db.queue_requests(once((&event, &dest)));
|
||||
let queued: Vec<_> = sending.db.queued_requests(&dest).collect().await;
|
||||
sending.db.mark_as_active(queued.iter());
|
||||
|
||||
let id = sending.shard_id(&dest);
|
||||
let mut futures = FuturesUnordered::new();
|
||||
let mut statuses = CurTransactionStatus::new();
|
||||
sending
|
||||
.startup_netburst(id, true, &mut futures, &mut statuses)
|
||||
.await;
|
||||
let active_after_restart = sending.db.active_requests_for(&dest).count().await;
|
||||
let sending_after_restart = futures.len();
|
||||
|
||||
drop(futures);
|
||||
let mut futures = FuturesUnordered::new();
|
||||
let mut statuses = CurTransactionStatus::new();
|
||||
sending
|
||||
.startup_netburst(id, false, &mut futures, &mut statuses)
|
||||
.await;
|
||||
let active_after_startup = sending.db.active_requests_for(&dest).count().await;
|
||||
let sending_after_startup = futures.len();
|
||||
|
||||
drop(futures);
|
||||
drop(services);
|
||||
std::fs::remove_dir_all(path).unwrap();
|
||||
assert_eq!(active_after_restart, 1);
|
||||
assert_eq!(sending_after_restart, 1);
|
||||
assert_eq!(active_after_startup, 0);
|
||||
assert_eq!(sending_after_startup, 0);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
use std::{iter::once, time::Duration};
|
||||
|
||||
use futures::StreamExt;
|
||||
use ruma::server_name;
|
||||
|
||||
use super::{Destination, EduBuf, SendingEvent, restart_delay};
|
||||
use crate::test_utils::test_services;
|
||||
|
||||
#[tokio::test]
|
||||
async fn queued_destinations_lists_each_destination_with_unsent_requests() {
|
||||
let (services, path, _database) = test_services().await;
|
||||
let db = &services.sending.db;
|
||||
let queued_sub = Destination::Federation(server_name!("queued.example.org").to_owned());
|
||||
let queued = Destination::Federation(server_name!("queued.example").to_owned());
|
||||
let appservice = Destination::Appservice("bridge".to_owned());
|
||||
let active = Destination::Federation(server_name!("active.example").to_owned());
|
||||
let event = SendingEvent::Edu(EduBuf::from_slice(br#"{"edu_type":"m.typing"}"#));
|
||||
|
||||
db.queue_requests(once((&event, &queued)));
|
||||
db.queue_requests(once((&event, &queued)));
|
||||
db.queue_requests(once((&event, &queued_sub)));
|
||||
db.queue_requests(once((&event, &appservice)));
|
||||
db.queue_requests(once((&event, &active)));
|
||||
let in_flight: Vec<_> = db.queued_requests(&active).collect().await;
|
||||
db.mark_as_active(in_flight.iter());
|
||||
|
||||
let dests = db.queued_destinations().await;
|
||||
|
||||
drop(services);
|
||||
std::fs::remove_dir_all(path).unwrap();
|
||||
assert_eq!(dests, [appservice, queued_sub, queued]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restart_delay_doubles_up_to_the_cap() {
|
||||
assert_eq!(restart_delay(1), Duration::from_millis(2500));
|
||||
assert_eq!(restart_delay(2), Duration::from_secs(5));
|
||||
assert_eq!(restart_delay(4), Duration::from_secs(20));
|
||||
assert_eq!(restart_delay(5), Duration::from_secs(30));
|
||||
assert_eq!(restart_delay(u32::MAX), Duration::from_secs(30));
|
||||
}
|
||||
@@ -11,7 +11,15 @@ pub struct Guard {
|
||||
services: Arc<Services>,
|
||||
}
|
||||
|
||||
pub fn create(services: Arc<Services>) -> (State, Guard) {
|
||||
/// Create a raw-pointer `State` handle paired with a `Guard` that keeps
|
||||
/// `Services` alive.
|
||||
///
|
||||
/// # Safety
|
||||
/// `State` is `Copy` and dereferences its raw pointer without reference
|
||||
/// counting. The caller must ensure that no `State` (nor any copy of it) is
|
||||
/// dereferenced after `Guard` and all other `Arc<Services>` clones have been
|
||||
/// dropped.
|
||||
pub unsafe fn create(services: Arc<Services>) -> (State, Guard) {
|
||||
let state = State {
|
||||
services: Arc::into_raw(services.clone()),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
use std::{path::PathBuf, sync::Arc};
|
||||
|
||||
use conduwuit::{
|
||||
Config, Server,
|
||||
log::{Log, LogLevelReloadHandles},
|
||||
metrics::Metrics,
|
||||
};
|
||||
use serde_json::json;
|
||||
use tokio::sync::{Mutex, MutexGuard};
|
||||
|
||||
/// RocksDB's default `Env` is shared by the whole process and closing a
|
||||
/// database stops its background threads, so tests must not keep databases
|
||||
/// open in parallel. Hold the returned guard until the services are dropped.
|
||||
static DATABASE: Mutex<()> = Mutex::const_new(());
|
||||
|
||||
type TestServices = (Arc<crate::Services>, PathBuf, MutexGuard<'static, ()>);
|
||||
|
||||
pub(crate) async fn test_services() -> TestServices { test_services_with(json!({})).await }
|
||||
|
||||
pub(crate) async fn test_services_with(overrides: serde_json::Value) -> TestServices {
|
||||
let guard = DATABASE.lock().await;
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
let path = std::env::temp_dir()
|
||||
.join(format!("continuwuity-shared-state-{:016x}", rand::random::<u64>()));
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
let mut config = json!({
|
||||
"server_name": "test.example",
|
||||
"database_path": path,
|
||||
"db_cache_capacity_mb": 16.0,
|
||||
"rocksdb_write_buffer_capacity_mb": 4.0,
|
||||
"allow_local_presence": false,
|
||||
"dns_servers": ["127.0.0.1"],
|
||||
"allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure": true
|
||||
});
|
||||
config
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.extend(overrides.as_object().unwrap().clone());
|
||||
let config: Config = serde_json::from_value(config).unwrap();
|
||||
let runtime = tokio::runtime::Handle::current();
|
||||
let server = Arc::new(Server::new(
|
||||
config,
|
||||
Some(runtime.clone()),
|
||||
Log {
|
||||
reload: LogLevelReloadHandles::default(),
|
||||
capture: Arc::default(),
|
||||
},
|
||||
Metrics::new(Some(runtime), opentelemetry::global::meter("test"), None),
|
||||
));
|
||||
let services = crate::Services::build(server).await.unwrap();
|
||||
(services, path, guard)
|
||||
}
|
||||
@@ -632,6 +632,12 @@ impl super::Service {
|
||||
}
|
||||
}
|
||||
|
||||
// Discard this device's previous token entry if the current token
|
||||
// isn't expired.
|
||||
self.db
|
||||
.userdeviceid_previoustoken
|
||||
.del((&user_id, &device_id));
|
||||
|
||||
Some((user_id, device_id, AccessTokenStatus::Valid))
|
||||
}
|
||||
|
||||
|
||||
@@ -184,8 +184,13 @@ impl super::Service {
|
||||
// Remove old token
|
||||
if let Ok(old_token) = self.db.userdeviceid_token.qry(&key).await {
|
||||
self.db.token_userdeviceid.remove(&old_token);
|
||||
self.db.userdeviceid_tokenexpires.remove(&old_token);
|
||||
// It will be removed from userdeviceid_token by the insert later
|
||||
|
||||
// Save the previous token only if we don't already have one saved
|
||||
// for this device.
|
||||
if !self.db.userdeviceid_previoustoken.contains(&key).await {
|
||||
self.db.userdeviceid_previoustoken.put_raw(key, &old_token);
|
||||
}
|
||||
}
|
||||
|
||||
// Assign token to user device combination
|
||||
@@ -207,6 +212,17 @@ impl super::Service {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns whether the provided token was previously used by a device
|
||||
/// before a token refresh, and therefore should cause a soft-logout.
|
||||
pub async fn is_previous_token(&self, token: &str) -> bool {
|
||||
self.db
|
||||
.userdeviceid_previoustoken
|
||||
.stream::<Ignore, String>()
|
||||
.ignore_err()
|
||||
.ready_any(|(_, previous_token)| previous_token == token)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Pushes a new to-device event into a device's inbox.
|
||||
pub async fn add_to_device_event(
|
||||
&self,
|
||||
|
||||
@@ -83,6 +83,7 @@ struct Data {
|
||||
userdeviceid_tokenexpires: Arc<Map>,
|
||||
userdeviceid_metadata: Arc<Map>,
|
||||
userdeviceid_token: Arc<Map>,
|
||||
userdeviceid_previoustoken: Arc<Map>,
|
||||
userfilterid_filter: Arc<Map>,
|
||||
userid_avatarurl: Arc<Map>,
|
||||
userid_deactivated: Arc<Map>,
|
||||
@@ -134,6 +135,7 @@ impl crate::Service for Service {
|
||||
remoteuserid_remoteuser: args.db["remoteuserid_remoteuser"].clone(),
|
||||
userdeviceid_metadata: args.db["userdeviceid_metadata"].clone(),
|
||||
userdeviceid_token: args.db["userdeviceid_token"].clone(),
|
||||
userdeviceid_previoustoken: args.db["userdeviceid_previoustoken"].clone(),
|
||||
userfilterid_filter: args.db["userfilterid_filter"].clone(),
|
||||
userid_avatarurl: args.db["userid_avatarurl"].clone(),
|
||||
userid_deactivated: args.db["userid_deactivated"].clone(),
|
||||
|
||||
Reference in new issue
Block a user