mirror of
https://forgejo.ellis.link/continuwuation/continuwuity.git
synced 2026-11-28 03:17:32 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a2e294fa8d | ||
|
|
1e34bd2ed9 |
No files matched your search
@@ -1,149 +0,0 @@
|
||||
name: build-native
|
||||
description: |
|
||||
Compile the binary on the runner host rather than inside Docker, then assemble the
|
||||
artefact tree the Docker packaging stages expect.
|
||||
|
||||
Intended for runners whose architecture matches the target, where a persistent local
|
||||
sccache is available. Produces out/{sbin,sbom,libs,libs-root} for consumption as a
|
||||
named build context.
|
||||
|
||||
inputs:
|
||||
package:
|
||||
description: Cargo package to build
|
||||
required: false
|
||||
default: conduwuit
|
||||
profile:
|
||||
description: Cargo build profile (release or release-max-perf)
|
||||
required: true
|
||||
features:
|
||||
description: Comma-separated cargo features
|
||||
required: false
|
||||
default: default
|
||||
march:
|
||||
description: Value for -march passed to the C and C++ compilers
|
||||
required: false
|
||||
default: ''
|
||||
rust-cpu-flags:
|
||||
description: Architecture flags appended to RUSTFLAGS
|
||||
required: false
|
||||
default: ''
|
||||
llvm-version:
|
||||
description: LLVM major version the host toolchain must provide
|
||||
required: false
|
||||
default: '22'
|
||||
target-dir:
|
||||
description: Cargo target directory, defaults to one outside the per-run workspace
|
||||
required: false
|
||||
default: ''
|
||||
out-dir:
|
||||
description: Directory to assemble the artefact tree in
|
||||
required: false
|
||||
default: out
|
||||
|
||||
outputs:
|
||||
out-dir:
|
||||
description: Directory containing sbin/, sbom/, libs/ and libs-root/
|
||||
value: ${{ steps.assemble.outputs.dir }}
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Add cargo binaries to PATH
|
||||
shell: bash
|
||||
run: echo "${CARGO_HOME:-$HOME/.cargo}/bin" >> "$GITHUB_PATH"
|
||||
|
||||
- name: Verify host toolchain
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
fail=0
|
||||
for tool in clang clang++ ld.lld cargo sccache cargo-sbom lddtree; do
|
||||
if ! command -v "$tool" >/dev/null; then
|
||||
echo "missing: $tool"
|
||||
fail=1
|
||||
fi
|
||||
done
|
||||
[ "$fail" -eq 0 ] || { echo "host is not provisioned for native builds"; exit 1; }
|
||||
|
||||
# Must match the container's ARG LLVM_VERSION or the two paths diverge.
|
||||
got=$(clang --version | sed -n 's/.*clang version \([0-9]*\).*/\1/p' | head -1)
|
||||
if [ "$got" != "${{ inputs.llvm-version }}" ]; then
|
||||
echo "clang major version is $got, expected ${{ inputs.llvm-version }}"
|
||||
exit 1
|
||||
fi
|
||||
echo "clang $got, $(cargo --version), $(sccache --version)"
|
||||
|
||||
- name: Configure build environment
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Mirrors the values docker/Dockerfile writes into /etc/environment.
|
||||
cflags="-flto"
|
||||
if [ -n "${{ inputs.march }}" ]; then
|
||||
cflags="$cflags -march=${{ inputs.march }}"
|
||||
fi
|
||||
{
|
||||
echo "CARGO_INCREMENTAL=0"
|
||||
echo "CC=clang"
|
||||
echo "CXX=clang++"
|
||||
echo "CFLAGS=$cflags"
|
||||
echo "CXXFLAGS=$cflags"
|
||||
echo "RUSTC_WRAPPER=sccache"
|
||||
} >> "$GITHUB_ENV"
|
||||
|
||||
# Outside the per-run workspace, so cargo can reuse artefacts between runs.
|
||||
target_dir="${{ inputs.target-dir }}"
|
||||
[ -n "$target_dir" ] || target_dir="$HOME/.cache/continuwuity-target"
|
||||
echo "CARGO_TARGET_DIR=$target_dir" >> "$GITHUB_ENV"
|
||||
|
||||
# A fat LTO link runs for minutes without compiling, which would otherwise
|
||||
# idle the sccache server out and lose the statistics with it.
|
||||
echo "SCCACHE_IDLE_TIMEOUT=1800" >> "$GITHUB_ENV"
|
||||
|
||||
rustflags='-Clinker-plugin-lto -Clink-arg=-fuse-ld=lld'
|
||||
if [ -n "${{ inputs.rust-cpu-flags }}" ]; then
|
||||
rustflags="$rustflags ${{ inputs.rust-cpu-flags }}"
|
||||
fi
|
||||
echo "RUSTFLAGS=$rustflags" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Build
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
sccache --zero-stats >/dev/null 2>&1 || true
|
||||
cargo build --locked \
|
||||
--profile ${{ inputs.profile }} \
|
||||
--no-default-features --features ${{ inputs.features }} \
|
||||
-p ${{ inputs.package }}
|
||||
|
||||
- name: Assemble artefact tree
|
||||
id: assemble
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
out="${{ inputs.out-dir }}"
|
||||
rm -rf "$out"
|
||||
mkdir -p "$out/sbin" "$out/sbom" "$out/libs" "$out/libs-root"
|
||||
|
||||
profile_dir="${{ inputs.profile }}"
|
||||
[ "$profile_dir" = "dev" ] && profile_dir=debug
|
||||
target_dir=$(cargo metadata --no-deps --format-version 1 | jq -r '.target_directory')
|
||||
|
||||
cp "$target_dir/$profile_dir/${{ inputs.package }}" "$out/sbin/${{ inputs.package }}"
|
||||
cargo sbom --cargo-package ${{ inputs.package }} > "$out/sbom/${{ inputs.package }}.spdx.json"
|
||||
|
||||
# Resolved here, not in the container: these are the libraries linked against.
|
||||
for binary in "$out"/sbin/*; do
|
||||
resolved=$(lddtree "$binary" 2>/dev/null) || continue
|
||||
[ -n "$resolved" ] || continue
|
||||
echo "$resolved" | awk '{print $(NF-0) " " $1}' | sort -u -k 1,1 | \
|
||||
awk -v out="$out" '{dest = ($2 ~ /^\//) ? out "/libs-root" $2 : out "/libs/" $2; print $1 " " dest}' | \
|
||||
while read -r src dest; do install -D "$src" "$dest"; done
|
||||
done
|
||||
|
||||
echo "dir=$out" >> "$GITHUB_OUTPUT"
|
||||
find "$out" -type f -printf '%10s %P\n' | sort -k2
|
||||
|
||||
- name: Report cache statistics
|
||||
shell: bash
|
||||
run: sccache --show-stats || true
|
||||
@@ -30,7 +30,7 @@ env:
|
||||
jobs:
|
||||
build-release:
|
||||
name: "Build ${{ matrix.slug }} (release)"
|
||||
runs-on: ${{ matrix.runner }}
|
||||
runs-on: dind
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
@@ -41,29 +41,14 @@ jobs:
|
||||
include:
|
||||
- platform: "linux/amd64"
|
||||
slug: "linux-amd64"
|
||||
runner: "dind"
|
||||
march: ""
|
||||
rust_cpu_flags: ""
|
||||
- platform: "linux/arm64"
|
||||
slug: "linux-arm64"
|
||||
runner: "ubuntu-arm64"
|
||||
native: true
|
||||
march: "armv8-a+crc"
|
||||
rust_cpu_flags: "-C target-feature=+crc"
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Compile on the runner host
|
||||
if: matrix.native
|
||||
uses: ./.forgejo/actions/build-native
|
||||
with:
|
||||
profile: "release"
|
||||
features: "default"
|
||||
march: ${{ matrix.march }}
|
||||
rust-cpu-flags: ${{ matrix.rust_cpu_flags }}
|
||||
- name: Prepare Docker build environment
|
||||
id: prepare
|
||||
uses: ./.forgejo/actions/prepare-docker-build
|
||||
@@ -88,11 +73,8 @@ jobs:
|
||||
GIT_REMOTE_COMMIT_URL=${{github.event.head_commit.url }}
|
||||
CARGO_INCREMENTAL=${{ env.BUILDKIT_ENDPOINT != '' && '1' || '0' }}
|
||||
TARGET_CPU=
|
||||
TARGET_MARCH=${{ matrix.march }}
|
||||
TARGET_RUSTFLAGS=${{ matrix.rust_cpu_flags }}
|
||||
RUST_PROFILE=release
|
||||
CARGO_FEATURES=default
|
||||
ARTIFACTS=${{ matrix.native && 'artifacts-prebuilt' || 'artifacts-builder' }}
|
||||
platforms: ${{ matrix.platform }}
|
||||
labels: ${{ steps.prepare.outputs.metadata_labels }}
|
||||
annotations: ${{ steps.prepare.outputs.metadata_annotations }}
|
||||
@@ -133,7 +115,7 @@ jobs:
|
||||
|
||||
build-maxperf:
|
||||
name: "Build ${{ matrix.slug }} (max-perf)"
|
||||
runs-on: ${{ matrix.runner }}
|
||||
runs-on: dind
|
||||
needs: build-release
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -146,30 +128,15 @@ jobs:
|
||||
- platform: "linux/amd64"
|
||||
slug: "linux-amd64"
|
||||
target_cpu: "haswell"
|
||||
runner: "dind"
|
||||
march: "haswell"
|
||||
rust_cpu_flags: "-C target-cpu=haswell"
|
||||
- platform: "linux/arm64"
|
||||
slug: "linux-arm64"
|
||||
target_cpu: ""
|
||||
runner: "ubuntu-arm64"
|
||||
native: true
|
||||
march: "armv8-a+crc"
|
||||
rust_cpu_flags: "-C target-feature=+crc"
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Compile on the runner host
|
||||
if: matrix.native
|
||||
uses: ./.forgejo/actions/build-native
|
||||
with:
|
||||
profile: "release-max-perf"
|
||||
features: "default,release_max_log_level"
|
||||
march: ${{ matrix.march }}
|
||||
rust-cpu-flags: ${{ matrix.rust_cpu_flags }}
|
||||
- name: Prepare max-perf Docker build environment
|
||||
id: prepare
|
||||
uses: ./.forgejo/actions/prepare-docker-build
|
||||
@@ -194,11 +161,8 @@ jobs:
|
||||
GIT_REMOTE_COMMIT_URL=${{github.event.head_commit.url }}
|
||||
CARGO_INCREMENTAL=${{ env.BUILDKIT_ENDPOINT != '' && '1' || '0' }}
|
||||
TARGET_CPU=${{ matrix.target_cpu }}
|
||||
TARGET_MARCH=${{ matrix.march }}
|
||||
TARGET_RUSTFLAGS=${{ matrix.rust_cpu_flags }}
|
||||
RUST_PROFILE=release-max-perf
|
||||
CARGO_FEATURES=default,release_max_log_level
|
||||
ARTIFACTS=${{ matrix.native && 'artifacts-prebuilt' || 'artifacts-builder' }}
|
||||
platforms: ${{ matrix.platform }}
|
||||
labels: ${{ steps.prepare.outputs.metadata_labels }}
|
||||
annotations: ${{ steps.prepare.outputs.metadata_annotations }}
|
||||
|
||||
Generated
+1
@@ -950,6 +950,7 @@ dependencies = [
|
||||
"log",
|
||||
"resolvematrix",
|
||||
"ruma",
|
||||
"ruminuwuity",
|
||||
"serde-saphyr",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
|
||||
+8
-23
@@ -1,10 +1,6 @@
|
||||
ARG RUST_VERSION=1
|
||||
ARG DEBIAN_VERSION=trixie
|
||||
|
||||
# Source of compiled artefacts: the builder stage, or out/ from the build context
|
||||
# when the runner compiled natively.
|
||||
ARG ARTIFACTS=artifacts-builder
|
||||
|
||||
FROM --platform=$BUILDPLATFORM docker.io/tonistiigi/xx AS xx
|
||||
FROM --platform=$BUILDPLATFORM rust:${RUST_VERSION}-slim-${DEBIAN_VERSION} AS base
|
||||
FROM --platform=$BUILDPLATFORM rust:${RUST_VERSION}-slim-${DEBIAN_VERSION} AS toolchain
|
||||
@@ -122,19 +118,15 @@ EOF
|
||||
|
||||
# Apply CPU-specific optimizations if TARGET_CPU is provided
|
||||
ARG TARGET_CPU
|
||||
ARG TARGET_MARCH
|
||||
ARG TARGET_RUSTFLAGS
|
||||
|
||||
RUN <<EOF
|
||||
set -o allexport
|
||||
set -o xtrace
|
||||
. /etc/environment
|
||||
if [ -n "${TARGET_MARCH}" ]; then
|
||||
echo "CFLAGS='${CFLAGS} -march=${TARGET_MARCH}'" >> /etc/environment
|
||||
echo "CXXFLAGS='${CXXFLAGS} -march=${TARGET_MARCH}'" >> /etc/environment
|
||||
fi
|
||||
if [ -n "${TARGET_RUSTFLAGS}" ]; then
|
||||
echo "RUSTFLAGS='${RUSTFLAGS} ${TARGET_RUSTFLAGS}'" >> /etc/environment
|
||||
if [ -n "${TARGET_CPU}" ]; then
|
||||
echo "CFLAGS='${CFLAGS} -march=${TARGET_CPU}'" >> /etc/environment
|
||||
echo "CXXFLAGS='${CXXFLAGS} -march=${TARGET_CPU}'" >> /etc/environment
|
||||
echo "RUSTFLAGS='${RUSTFLAGS} -C target-cpu=${TARGET_CPU}'" >> /etc/environment
|
||||
fi
|
||||
EOF
|
||||
|
||||
@@ -253,13 +245,6 @@ RUN <<'DEPS_EOF'
|
||||
find /out/libs* -type f 2>/dev/null | sort || echo "No libraries found"
|
||||
DEPS_EOF
|
||||
|
||||
FROM scratch AS artifacts-prebuilt
|
||||
COPY out/ /out/
|
||||
|
||||
FROM builder AS artifacts-builder
|
||||
|
||||
FROM ${ARTIFACTS} AS artifacts
|
||||
|
||||
FROM ubuntu:latest AS prepper
|
||||
|
||||
# Create layer structure
|
||||
@@ -269,14 +254,14 @@ RUN mkdir -p /layer1/etc/ssl/certs \
|
||||
|
||||
# Copy SSL certs and root-path libraries to layer1 (ultra-stable)
|
||||
COPY --from=base /etc/ssl/certs /layer1/etc/ssl/certs
|
||||
COPY --from=artifacts /out/libs-root/ /layer1/
|
||||
COPY --from=builder /out/libs-root/ /layer1/
|
||||
|
||||
# Copy application libraries to layer2 (semi-stable)
|
||||
COPY --from=artifacts /out/libs/ /layer2/usr/lib/
|
||||
COPY --from=builder /out/libs/ /layer2/usr/lib/
|
||||
|
||||
# Copy binaries and SBOM to layer3 (volatile)
|
||||
COPY --from=artifacts /out/sbin/ /layer3/sbin/
|
||||
COPY --from=artifacts /out/sbom/ /layer3/sbom/
|
||||
COPY --from=builder /out/sbin/ /layer3/sbin/
|
||||
COPY --from=builder /out/sbom/ /layer3/sbom/
|
||||
|
||||
# Fix permissions after copying
|
||||
RUN chmod -R 755 /layer1 /layer2 /layer3
|
||||
|
||||
+40
-39
@@ -11,65 +11,65 @@ version.workspace = true
|
||||
[lib]
|
||||
path = "mod.rs"
|
||||
crate-type = [
|
||||
"rlib",
|
||||
# "dylib",
|
||||
"rlib",
|
||||
# "dylib",
|
||||
]
|
||||
|
||||
[features]
|
||||
brotli_compression = [
|
||||
"conduwuit-api/brotli_compression",
|
||||
"conduwuit-core/brotli_compression",
|
||||
"conduwuit-service/brotli_compression",
|
||||
"conduwuit-api/brotli_compression",
|
||||
"conduwuit-core/brotli_compression",
|
||||
"conduwuit-service/brotli_compression",
|
||||
]
|
||||
gzip_compression = [
|
||||
"conduwuit-api/gzip_compression",
|
||||
"conduwuit-core/gzip_compression",
|
||||
"conduwuit-service/gzip_compression",
|
||||
"conduwuit-api/gzip_compression",
|
||||
"conduwuit-core/gzip_compression",
|
||||
"conduwuit-service/gzip_compression",
|
||||
]
|
||||
io_uring = [
|
||||
"conduwuit-api/io_uring",
|
||||
"conduwuit-database/io_uring",
|
||||
"conduwuit-service/io_uring",
|
||||
"conduwuit-api/io_uring",
|
||||
"conduwuit-database/io_uring",
|
||||
"conduwuit-service/io_uring",
|
||||
]
|
||||
jemalloc = [
|
||||
"conduwuit-api/jemalloc",
|
||||
"conduwuit-core/jemalloc",
|
||||
"conduwuit-database/jemalloc",
|
||||
"conduwuit-service/jemalloc",
|
||||
"conduwuit-api/jemalloc",
|
||||
"conduwuit-core/jemalloc",
|
||||
"conduwuit-database/jemalloc",
|
||||
"conduwuit-service/jemalloc",
|
||||
]
|
||||
jemalloc_conf = [
|
||||
"conduwuit-api/jemalloc_conf",
|
||||
"conduwuit-core/jemalloc_conf",
|
||||
"conduwuit-database/jemalloc_conf",
|
||||
"conduwuit-service/jemalloc_conf",
|
||||
"conduwuit-api/jemalloc_conf",
|
||||
"conduwuit-core/jemalloc_conf",
|
||||
"conduwuit-database/jemalloc_conf",
|
||||
"conduwuit-service/jemalloc_conf",
|
||||
]
|
||||
jemalloc_prof = [
|
||||
"conduwuit-api/jemalloc_prof",
|
||||
"conduwuit-core/jemalloc_prof",
|
||||
"conduwuit-database/jemalloc_prof",
|
||||
"conduwuit-service/jemalloc_prof",
|
||||
"conduwuit-api/jemalloc_prof",
|
||||
"conduwuit-core/jemalloc_prof",
|
||||
"conduwuit-database/jemalloc_prof",
|
||||
"conduwuit-service/jemalloc_prof",
|
||||
]
|
||||
jemalloc_stats = [
|
||||
"conduwuit-api/jemalloc_stats",
|
||||
"conduwuit-core/jemalloc_stats",
|
||||
"conduwuit-database/jemalloc_stats",
|
||||
"conduwuit-service/jemalloc_stats",
|
||||
"conduwuit-api/jemalloc_stats",
|
||||
"conduwuit-core/jemalloc_stats",
|
||||
"conduwuit-database/jemalloc_stats",
|
||||
"conduwuit-service/jemalloc_stats",
|
||||
]
|
||||
release_max_log_level = [
|
||||
"conduwuit-api/release_max_log_level",
|
||||
"conduwuit-core/release_max_log_level",
|
||||
"conduwuit-database/release_max_log_level",
|
||||
"conduwuit-service/release_max_log_level",
|
||||
"tracing/max_level_trace",
|
||||
"tracing/release_max_level_info",
|
||||
"log/max_level_trace",
|
||||
"log/release_max_level_info",
|
||||
"conduwuit-api/release_max_log_level",
|
||||
"conduwuit-core/release_max_log_level",
|
||||
"conduwuit-database/release_max_log_level",
|
||||
"conduwuit-service/release_max_log_level",
|
||||
"tracing/max_level_trace",
|
||||
"tracing/release_max_level_info",
|
||||
"log/max_level_trace",
|
||||
"log/release_max_level_info",
|
||||
]
|
||||
zstd_compression = [
|
||||
"conduwuit-api/zstd_compression",
|
||||
"conduwuit-core/zstd_compression",
|
||||
"conduwuit-database/zstd_compression",
|
||||
"conduwuit-service/zstd_compression",
|
||||
"conduwuit-api/zstd_compression",
|
||||
"conduwuit-core/zstd_compression",
|
||||
"conduwuit-database/zstd_compression",
|
||||
"conduwuit-service/zstd_compression",
|
||||
]
|
||||
|
||||
[dependencies]
|
||||
@@ -86,6 +86,7 @@ futures.workspace = true
|
||||
lettre.workspace = true
|
||||
log.workspace = true
|
||||
ruma.workspace = true
|
||||
ruminuwuity.workspace = true
|
||||
serde_json.workspace = true
|
||||
serde-saphyr.workspace = true
|
||||
tokio.workspace = true
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::{
|
||||
};
|
||||
|
||||
use conduwuit::{
|
||||
Err, Result, at, debug_error, err, info,
|
||||
Err, Result, at, debug_error, debug_info, err, info,
|
||||
matrix::{
|
||||
Event, StateKey,
|
||||
pdu::{PduEvent, PduId, RawPduId},
|
||||
@@ -14,6 +14,7 @@ use conduwuit::{
|
||||
state_res::EventTypeExt,
|
||||
trace, utils,
|
||||
utils::{
|
||||
random_string,
|
||||
stream::{IterStream, ReadyExt},
|
||||
string::EMPTY,
|
||||
to_canonical_object,
|
||||
@@ -28,8 +29,8 @@ use resolvematrix::{
|
||||
};
|
||||
use ruma::{
|
||||
CanonicalJsonObject, CanonicalJsonValue, EventId, OwnedEventId, OwnedRoomId,
|
||||
OwnedRoomOrAliasId, OwnedServerName, RoomId, RoomVersionId, UInt,
|
||||
api::federation::event::get_room_state,
|
||||
OwnedRoomOrAliasId, OwnedServerName, RoomId, RoomVersionId, ServerName, UInt,
|
||||
api::{error::ErrorKind, federation::event::get_room_state},
|
||||
events::{AnyStateEvent, StateEventType},
|
||||
serde::Raw,
|
||||
};
|
||||
@@ -604,14 +605,60 @@ impl crate::Context<'_> {
|
||||
if server == self.services.globals.server_name() {
|
||||
return Err!("Not allowed to send federation requests to ourselves.");
|
||||
}
|
||||
let modern = self.modern_pingpong_ping(&server).await?;
|
||||
if let Some(w) = modern {
|
||||
self.write_str(&w).await
|
||||
} else {
|
||||
info!("{server} does not support msc4524, falling back to legacy ping");
|
||||
self.legacy_ping(&server).await
|
||||
}
|
||||
}
|
||||
|
||||
async fn modern_pingpong_ping(&self, server: &ServerName) -> Result<Option<String>> {
|
||||
let timer = tokio::time::Instant::now();
|
||||
let question = &random_string(64);
|
||||
|
||||
let response = self
|
||||
.services
|
||||
.sending
|
||||
.send_federation_request(
|
||||
server,
|
||||
ruminuwuity::api::federation::ping::unstable::Request::new(question.to_owned()),
|
||||
)
|
||||
.await;
|
||||
|
||||
let answer = match response {
|
||||
| Ok(resp) => resp.answer,
|
||||
| Err(e) =>
|
||||
return if e.is_not_found() && e.kind() == ErrorKind::Unrecognized {
|
||||
Ok(None)
|
||||
} else {
|
||||
Err!("Failed sending federation request to specified server:\n\n{e}")
|
||||
},
|
||||
};
|
||||
let recv = self
|
||||
.services
|
||||
.federation
|
||||
.register_ping_answer(answer.clone())?;
|
||||
debug_info!("Waiting for a pong for up to 60 seconds");
|
||||
let result = tokio::time::timeout(std::time::Duration::from_mins(1), recv).await;
|
||||
match result {
|
||||
| Err(e) => Err!(BadServerResponse("Remote did not answer the ping in time: {e:?}")),
|
||||
| Ok(Err(e)) =>
|
||||
Err!(BadServerResponse("Unexpectedly could not read from pong channel: {e:?}")),
|
||||
| Ok(Ok(())) =>
|
||||
Ok(Some(format!("Ping got a pong in {:?}: {answer}", timer.elapsed()))),
|
||||
}
|
||||
}
|
||||
|
||||
async fn legacy_ping(&self, server: &ServerName) -> Result {
|
||||
let timer = tokio::time::Instant::now();
|
||||
|
||||
match self
|
||||
.services
|
||||
.sending
|
||||
.send_unauthenticated_request(
|
||||
&server,
|
||||
server,
|
||||
ruma::api::federation::discovery::get_server_version::v1::Request::new(),
|
||||
)
|
||||
.await
|
||||
|
||||
@@ -267,11 +267,19 @@ pub(crate) async fn get_public_rooms_filtered_helper(
|
||||
summary.into()
|
||||
})
|
||||
.ready_filter_map(|chunk: PublicRoomsChunk| {
|
||||
if !filter.room_types.is_empty() && !filter.room_types.contains(&RoomTypeFilter::from(chunk.room_type.clone())) {
|
||||
if !filter.room_types.is_empty()
|
||||
&& !filter
|
||||
.room_types
|
||||
.contains(&RoomTypeFilter::from(chunk.room_type.clone()))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
if let Some(query) = filter.generic_search_term.as_ref().map(|q| q.to_lowercase()) {
|
||||
if let Some(query) = filter
|
||||
.generic_search_term
|
||||
.as_ref()
|
||||
.map(|q| q.to_lowercase())
|
||||
{
|
||||
if let Some(name) = &chunk.name {
|
||||
if name.to_lowercase().contains(&query) {
|
||||
return Some(chunk);
|
||||
|
||||
@@ -55,5 +55,8 @@ fn oauth_router() -> Router<crate::State> {
|
||||
.route(concat!("/", JWKS_URI_PATH), get(async || Json(json!({"keys": []}))))
|
||||
.route(concat!("/", TOKEN_PATH), post(token::token_route))
|
||||
.route(concat!("/", TOKEN_REVOKE_PATH), post(token::revoke_token_route))
|
||||
.route(concat!("/", DEVICE_AUTHORIZATION_PATH), post(device::device_authorization_route))
|
||||
.route(
|
||||
concat!("/", DEVICE_AUTHORIZATION_PATH),
|
||||
post(device::device_authorization_route),
|
||||
)
|
||||
}
|
||||
+17
-12
@@ -1563,20 +1563,25 @@ where
|
||||
// joined users
|
||||
device_list_changes.extend(
|
||||
services
|
||||
.rooms
|
||||
.state_cache
|
||||
.room_members(room_id)
|
||||
// Don't send key updates from the sender to the sender
|
||||
.ready_filter(|user_id| sender_user != *user_id)
|
||||
// Only send keys if the sender doesn't share an encrypted room with the target
|
||||
// already
|
||||
.filter_map(async |user_id| {
|
||||
share_encrypted_room(services, sender_user, &user_id, Some(room_id))
|
||||
.rooms
|
||||
.state_cache
|
||||
.room_members(room_id)
|
||||
// Don't send key updates from the sender to the sender
|
||||
.ready_filter(|user_id| sender_user != *user_id)
|
||||
// Only send keys if the sender doesn't share an encrypted room with
|
||||
// the target already
|
||||
.filter_map(async |user_id| {
|
||||
share_encrypted_room(
|
||||
services,
|
||||
sender_user,
|
||||
&user_id,
|
||||
Some(room_id),
|
||||
)
|
||||
.map(|res| res.or_some(user_id.clone()))
|
||||
.await
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.await,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.await,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+12
-7
@@ -21,7 +21,7 @@ use crate::{admin, client, server};
|
||||
pub fn build(router: Router<State>, state: State) -> Router<State> {
|
||||
let config = &state.server.config;
|
||||
let mut router = router
|
||||
.ruma_route(&client::appservice_ping)
|
||||
.ruma_route(&client::appservice_ping)
|
||||
.ruma_route(&client::get_supported_versions_route)
|
||||
.ruma_route(&client::get_register_available_route)
|
||||
.ruma_route(&client::register::register_route)
|
||||
@@ -61,8 +61,8 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
|
||||
.ruma_route(&client::get_global_account_data_route)
|
||||
.ruma_route(&client::get_room_account_data_route)
|
||||
.ruma_route(&client::get_profile_field_route)
|
||||
.ruma_route(&client::set_profile_field_route)
|
||||
.ruma_route(&client::delete_profile_field_route)
|
||||
.ruma_route(&client::set_profile_field_route)
|
||||
.ruma_route(&client::delete_profile_field_route)
|
||||
.ruma_route(&client::get_profile_route)
|
||||
.ruma_route(&client::set_presence_route)
|
||||
.ruma_route(&client::get_presence_route)
|
||||
@@ -112,14 +112,17 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
|
||||
.ruma_route(&client::search_users_route)
|
||||
.ruma_route(&client::get_member_events_route)
|
||||
.ruma_route(&client::get_protocols_route)
|
||||
.route("/_matrix/client/unstable/thirdparty/protocols",
|
||||
get(client::get_protocols_route_unstable))
|
||||
.route(
|
||||
"/_matrix/client/unstable/thirdparty/protocols",
|
||||
get(client::get_protocols_route_unstable),
|
||||
)
|
||||
.ruma_route(&client::send_message_event_route)
|
||||
.ruma_route(&client::send_state_event_for_key_route)
|
||||
.ruma_route(&client::get_state_events_route)
|
||||
.ruma_route(&client::get_state_event_for_key_route)
|
||||
// Ruma doesn't have support for multiple paths for a single endpoint yet, and these routes
|
||||
// share one Ruma request / response type pair with {get,send}_state_event_for_key_route
|
||||
// Ruma doesn't have support for multiple paths for a single endpoint yet, and these
|
||||
// routes share one Ruma request / response type pair with
|
||||
// {get,send}_state_event_for_key_route
|
||||
.route(
|
||||
"/_matrix/client/r0/rooms/{room_id}/state/{event_type}",
|
||||
get(client::get_state_events_for_empty_key_route)
|
||||
@@ -226,6 +229,8 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
|
||||
.ruma_route(&server::well_known_server)
|
||||
.ruma_route(&server::get_content_route)
|
||||
.ruma_route(&server::get_content_thumbnail_route)
|
||||
.ruma_route(&server::ping)
|
||||
.ruma_route(&server::pong)
|
||||
.route("/_continuwuity/local_user_count", get(client::continuwuity_local_user_count));
|
||||
} else {
|
||||
router = router
|
||||
|
||||
@@ -10,6 +10,8 @@ pub(super) mod make_knock;
|
||||
pub(super) mod make_leave;
|
||||
pub(super) mod media;
|
||||
pub(super) mod openid;
|
||||
pub(super) mod ping;
|
||||
pub(super) mod pong;
|
||||
pub(super) mod publicrooms;
|
||||
pub(super) mod query;
|
||||
pub(super) mod send;
|
||||
@@ -34,6 +36,8 @@ pub(super) use make_knock::*;
|
||||
pub(super) use make_leave::*;
|
||||
pub(super) use media::*;
|
||||
pub(super) use openid::*;
|
||||
pub(super) use ping::ping;
|
||||
pub(super) use pong::pong;
|
||||
pub(super) use publicrooms::*;
|
||||
pub(super) use query::*;
|
||||
pub(super) use send::*;
|
||||
@@ -45,6 +49,6 @@ pub(super) use state_ids::*;
|
||||
pub(super) use user::*;
|
||||
pub(super) use version::*;
|
||||
pub(super) use well_known::*;
|
||||
|
||||
mod utils;
|
||||
|
||||
use utils::AccessCheck;
|
||||
@@ -0,0 +1,55 @@
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use axum::extract::State;
|
||||
use conduwuit::{
|
||||
Result, info,
|
||||
utils::{random_string, time::jitter},
|
||||
warn,
|
||||
};
|
||||
use ruma::{OwnedServerName, api::error::ErrorKind};
|
||||
use ruminuwuity::api::federation::{
|
||||
ping::unstable::{Request, Response},
|
||||
pong,
|
||||
};
|
||||
|
||||
use crate::Ruma;
|
||||
|
||||
/// # `GET /_matrix/federation/unstable/uk.timedout.msc0000.tabletennis/ping`
|
||||
///
|
||||
/// Initiates a ping
|
||||
pub(crate) async fn ping(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<Request>,
|
||||
) -> Result<Response> {
|
||||
// TODO: rate-limiting
|
||||
// TODO: make answer stable based on question
|
||||
let answer = random_string(64);
|
||||
services.federation.register_ping_answer(answer.clone())?;
|
||||
services
|
||||
.server
|
||||
.runtime()
|
||||
.spawn(send_ping(Arc::new(services), body.identity, answer.clone()));
|
||||
Ok(Response::new(answer))
|
||||
}
|
||||
|
||||
async fn send_ping(services: Arc<crate::State>, target: OwnedServerName, answer: String) {
|
||||
tokio::time::sleep(jitter(Duration::from_secs(1), 1.0..=10.0)).await;
|
||||
info!(%answer, "Sending a federation pong to {target}");
|
||||
match services
|
||||
.sending
|
||||
.send_federation_request(&target, pong::unstable::Request::new(answer))
|
||||
.await
|
||||
{
|
||||
| Ok(_) => info!(%target, "Federation pong succeeded"),
|
||||
| Err(e) =>
|
||||
if e.is_not_found() {
|
||||
if e.kind() == ErrorKind::Unrecognized {
|
||||
warn!(%target, "Remote requested a ping but does not recognize the pong.");
|
||||
} else {
|
||||
info!(%target, "Ping expired by the time we ponged.");
|
||||
}
|
||||
} else {
|
||||
warn!(%target, "Pong failed");
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
use axum::extract::State;
|
||||
use conduwuit::Result;
|
||||
use ruminuwuity::api::federation::pong;
|
||||
|
||||
use crate::Ruma;
|
||||
|
||||
/// # `GET /_matrix/federation/unstable/uk.timedout.msc0000.tabletennis/pong`
|
||||
///
|
||||
/// Responds to a ping
|
||||
pub(crate) async fn pong(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<pong::unstable::Request>,
|
||||
) -> Result<pong::unstable::Response> {
|
||||
// TODO: verify incoming question is already registered
|
||||
services.federation.answer_ping(&body.question)?;
|
||||
Ok(pong::unstable::Response::default())
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod ping;
|
||||
pub mod pong;
|
||||
@@ -0,0 +1,43 @@
|
||||
//! `GET /_matrix/federation/*/ping`
|
||||
//!
|
||||
//! Initiate a federation ping
|
||||
pub mod unstable {
|
||||
use ruma::{
|
||||
OwnedServerName,
|
||||
api::{federation::authentication::ServerSignatures, request, response},
|
||||
metadata,
|
||||
};
|
||||
|
||||
metadata! {
|
||||
method: POST,
|
||||
rate_limited: true,
|
||||
authentication: ServerSignatures, // TODO: Needs to be optional
|
||||
path: "/_matrix/federation/unstable/uk.timedout.msc4524.tabletennis/ping"
|
||||
}
|
||||
|
||||
#[request]
|
||||
pub struct Request {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub origin: Option<OwnedServerName>,
|
||||
|
||||
pub question: String,
|
||||
}
|
||||
|
||||
#[response]
|
||||
pub struct Response {
|
||||
pub answer: String,
|
||||
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub details: Vec<String>,
|
||||
}
|
||||
|
||||
impl Request {
|
||||
#[must_use]
|
||||
pub fn new(question: String) -> Self { Self { question, origin: None } }
|
||||
}
|
||||
|
||||
impl Response {
|
||||
#[must_use]
|
||||
pub fn new(answer: String) -> Self { Self { answer, details: vec![] } }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
//! `GET /_matrix/federation/*/pong`
|
||||
//!
|
||||
//! Respond to a federation ping
|
||||
pub mod unstable {
|
||||
use ruma::{
|
||||
api::{federation::authentication::ServerSignatures, request, response},
|
||||
metadata,
|
||||
};
|
||||
|
||||
metadata! {
|
||||
method: POST,
|
||||
rate_limited: false,
|
||||
authentication: ServerSignatures,
|
||||
path: "/_matrix/federation/unstable/uk.timedout.msc4524.tabletennis/ping"
|
||||
}
|
||||
|
||||
#[request]
|
||||
pub struct Request {
|
||||
pub question: String,
|
||||
}
|
||||
|
||||
#[response]
|
||||
#[derive(Default)]
|
||||
pub struct Response;
|
||||
|
||||
impl Request {
|
||||
#[must_use]
|
||||
pub fn new(question: String) -> Self { Self { question } }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod federation;
|
||||
|
||||
pub use federation::*;
|
||||
@@ -6,3 +6,4 @@ pub mod invite_permission_config;
|
||||
pub mod meowlnir_antispam;
|
||||
pub mod policy;
|
||||
pub mod pushers;
|
||||
pub mod api;
|
||||
@@ -8,7 +8,7 @@ use std::{
|
||||
|
||||
use assign::assign;
|
||||
use async_trait::async_trait;
|
||||
use conduwuit::{Error, Result, Server, SyncRwLock, debug, utils::millis_since_unix_epoch};
|
||||
use conduwuit::{Err, Error, Result, Server, SyncRwLock, debug, err, error, utils::millis_since_unix_epoch};
|
||||
pub(crate) use execute::FederationPathBuilderInput;
|
||||
use http::StatusCode;
|
||||
use ruma::{
|
||||
@@ -22,6 +22,8 @@ pub struct Service {
|
||||
services: Services,
|
||||
pub remote_health: SyncRwLock<HashMap<OwnedServerName, (u32, u64)>>,
|
||||
pub stale_destinations: SyncRwLock<HashSet<OwnedServerName>>,
|
||||
/// A map of {answer: channel}
|
||||
pingpongs: SyncRwLock<HashMap<String, tokio::sync::oneshot::Sender<()>>>,
|
||||
}
|
||||
|
||||
struct Services {
|
||||
@@ -43,6 +45,7 @@ impl crate::Service for Service {
|
||||
},
|
||||
remote_health: SyncRwLock::new(HashMap::new()),
|
||||
stale_destinations: SyncRwLock::new(HashSet::new()),
|
||||
pingpongs: SyncRwLock::new(HashMap::new()),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -207,4 +210,35 @@ impl Service {
|
||||
pub fn stale_destinations(&self) -> HashSet<OwnedServerName> {
|
||||
self.stale_destinations.read().clone()
|
||||
}
|
||||
|
||||
/// Registers an outbound ping waiter based on the answer returned by the
|
||||
/// remote. Returns a channel that is written to when the remote pongs.
|
||||
pub fn register_ping_answer(
|
||||
&self,
|
||||
expected_answer: String,
|
||||
) -> Result<tokio::sync::oneshot::Receiver<()>> {
|
||||
let mut pingpongs = self.pingpongs.write();
|
||||
if pingpongs.contains_key(&expected_answer) {
|
||||
return Err!(Request(InvalidParam("Duplicate answer")));
|
||||
}
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
pingpongs.insert(expected_answer, tx);
|
||||
Ok(rx)
|
||||
}
|
||||
|
||||
/// "Answers" a registered outbound ping by sending an event to it. This is
|
||||
/// called when the remote server that was pinged calls /pong.
|
||||
///
|
||||
/// `M_NOT_FOUND` is returned if the answer is not recognised.
|
||||
pub fn answer_ping(&self, answer: &str) -> Result<()> {
|
||||
let mut pingpongs = self.pingpongs.write();
|
||||
let Some(tx) = pingpongs.remove(answer) else {
|
||||
return Err!(Request(NotFound("Unknown answer")));
|
||||
};
|
||||
tx.send(()).map_err(|e| {
|
||||
err!(BadServerResponse(error!(
|
||||
error=?e, "Failed to handle pong"
|
||||
)))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -571,7 +571,8 @@ impl Service {
|
||||
));
|
||||
}
|
||||
|
||||
let device_id = self.services
|
||||
let device_id = self
|
||||
.services
|
||||
.users
|
||||
.create_device(
|
||||
&authorizing_user,
|
||||
|
||||
@@ -72,7 +72,10 @@ impl std::fmt::Display for ValidTokenSource {
|
||||
|
||||
impl crate::Service for Service {
|
||||
fn build(args: crate::Args<'_>) -> Result<Arc<Self>> {
|
||||
let registration_tokens_from_file = args.server.config.registration_token_file
|
||||
let registration_tokens_from_file = args
|
||||
.server
|
||||
.config
|
||||
.registration_token_file
|
||||
.clone()
|
||||
// If the token file option was set, read the path it points to
|
||||
.map(std::fs::read_to_string)
|
||||
@@ -80,7 +83,8 @@ impl crate::Service for Service {
|
||||
.map_err(|err| err!("Failed to read registration token file: {err}"))
|
||||
.map(|tokens| {
|
||||
if let Some(tokens) = tokens {
|
||||
// If the token file option was set, return the file's lines as tokens
|
||||
// If the token file option was set, return the file's lines
|
||||
// as tokens
|
||||
tokens.lines().map(ToOwned::to_owned).collect()
|
||||
} else {
|
||||
// Otherwise, if the option wasn't set, return no tokens
|
||||
|
||||
@@ -164,12 +164,12 @@ impl Service {
|
||||
}
|
||||
|
||||
let mut children: Vec<_> = summary
|
||||
.children_state
|
||||
.iter()
|
||||
// Ignore deserialization failures
|
||||
.flat_map(Raw::deserialize)
|
||||
// Filter out non-suggested children if suggested_only is set
|
||||
.filter(|child| !suggested_only || child.content.suggested)
|
||||
.children_state
|
||||
.iter()
|
||||
// Ignore deserialization failures
|
||||
.flat_map(Raw::deserialize)
|
||||
// Filter out non-suggested children if suggested_only is set
|
||||
.filter(|child| !suggested_only || child.content.suggested)
|
||||
.collect();
|
||||
children.sort();
|
||||
let children = children
|
||||
@@ -323,43 +323,46 @@ impl Service {
|
||||
};
|
||||
|
||||
let (accessible_children, inaccessible_children) = children_state
|
||||
.iter()
|
||||
// Ignore deserialization failures
|
||||
.flat_map(Raw::deserialize)
|
||||
// Fetch summaries for the children in parallel
|
||||
.stream()
|
||||
.broad_then(async |child| {
|
||||
let summary = {
|
||||
if let Some(summary) = self.build_local_room_summary(&child.state_key).await {
|
||||
if self.server_may_see_summary(querying_server, &summary).await {
|
||||
Accessibility::Accessible(summary)
|
||||
} else {
|
||||
Accessibility::Inaccessible
|
||||
}
|
||||
} else {
|
||||
Accessibility::NotFound
|
||||
}
|
||||
};
|
||||
.iter()
|
||||
// Ignore deserialization failures
|
||||
.flat_map(Raw::deserialize)
|
||||
// Fetch summaries for the children in parallel
|
||||
.stream()
|
||||
.broad_then(async |child| {
|
||||
let summary = {
|
||||
if let Some(summary) = self.build_local_room_summary(&child.state_key).await {
|
||||
if self.server_may_see_summary(querying_server, &summary).await {
|
||||
Accessibility::Accessible(summary)
|
||||
} else {
|
||||
Accessibility::Inaccessible
|
||||
}
|
||||
} else {
|
||||
Accessibility::NotFound
|
||||
}
|
||||
};
|
||||
|
||||
(child.state_key, summary)
|
||||
})
|
||||
// Sort the children into two Vecs by accessibility
|
||||
.ready_fold_default(|(mut accessible_children, mut inaccessible_children): (Vec<_>, Vec<_>), (room_id, summary)| {
|
||||
match summary {
|
||||
Accessibility::Accessible(summary) => {
|
||||
accessible_children.push(summary);
|
||||
},
|
||||
Accessibility::Inaccessible => {
|
||||
inaccessible_children.push(room_id);
|
||||
},
|
||||
Accessibility::NotFound => {
|
||||
// Skip inaccessible children
|
||||
}
|
||||
}
|
||||
(child.state_key, summary)
|
||||
})
|
||||
// Sort the children into two Vecs by accessibility
|
||||
.ready_fold_default(
|
||||
|(mut accessible_children, mut inaccessible_children): (Vec<_>, Vec<_>),
|
||||
(room_id, summary)| {
|
||||
match summary {
|
||||
| Accessibility::Accessible(summary) => {
|
||||
accessible_children.push(summary);
|
||||
},
|
||||
| Accessibility::Inaccessible => {
|
||||
inaccessible_children.push(room_id);
|
||||
},
|
||||
| Accessibility::NotFound => {
|
||||
// Skip inaccessible children
|
||||
},
|
||||
}
|
||||
|
||||
(accessible_children, inaccessible_children)
|
||||
})
|
||||
.await;
|
||||
(accessible_children, inaccessible_children)
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
Accessibility::Accessible(assign!(
|
||||
get_hierarchy::v1::Response::new(SpaceHierarchyParentSummary::new(summary, children_state)),
|
||||
|
||||
@@ -449,7 +449,12 @@ impl super::Service {
|
||||
// Don't notify the sender of their own events, and don't send from ignored users
|
||||
.ready_filter(|user| *user != pdu.sender())
|
||||
.filter_map(|recipient_user| async move {
|
||||
(!self.services.users.user_is_ignored(pdu.sender(), &recipient_user).await).then_some(recipient_user)
|
||||
(!self
|
||||
.services
|
||||
.users
|
||||
.user_is_ignored(pdu.sender(), &recipient_user)
|
||||
.await)
|
||||
.then_some(recipient_user)
|
||||
})
|
||||
.collect()
|
||||
.await;
|
||||
@@ -806,7 +811,7 @@ impl super::Service {
|
||||
.read()
|
||||
.await
|
||||
.values()
|
||||
.map(ToOwned::to_owned) // TODO: is this to_owned expensive?
|
||||
.map(ToOwned::to_owned) // TODO: is this to_owned expensive?
|
||||
.collect::<Vec<_>>();
|
||||
interested_appservices
|
||||
.stream()
|
||||
|
||||
@@ -449,7 +449,12 @@ impl super::Service {
|
||||
.rooms_joined(user_id)
|
||||
// Don't send key updates to unencrypted rooms
|
||||
.filter_map(async |room_id| {
|
||||
if self.services.state_accessor.is_encrypted_room(&room_id).await {
|
||||
if self
|
||||
.services
|
||||
.state_accessor
|
||||
.is_encrypted_room(&room_id)
|
||||
.await
|
||||
{
|
||||
Some(room_id)
|
||||
} else {
|
||||
None
|
||||
|
||||
Reference in new issue
Block a user