Compare commits

..
Author SHA1 Message Date
Morgan ea269d2761 ci: Compile arm64 natively on the ubuntu-arm64 runner
The arm64 build cross-compiled with the Rust target triple inside an
amd64 container and copied the binary out, deliberately avoiding Docker
emulation because arm64 emulation is unreliable on some BuildKit
instances.

A dedicated Ubuntu VM on an M4 Mac Mini is now available under the
ubuntu-arm64 label. Each matrix entry carries its own runner label and a
native flag, so builds can be moved between runners or between build
modes without changing the workflow structure.

Where native is set, the build-native action compiles on the host and
assembles the artefact tree, leaving Docker to package it. It builds
into a target directory outside the per-run workspace so cargo can reuse
artefacts between runs. The Dockerfile's ARTIFACTS argument selects
whether artefacts come from the builder stage or from out/ in the build
context; prepper and the final image are unchanged. Libraries are
resolved where the binary was linked, so arm64 images carry Ubuntu's
rather than Debian's.

Architecture flags are split into TARGET_MARCH, which feeds -march for
the C and C++ compilers, and TARGET_RUSTFLAGS, which is appended to
RUSTFLAGS. amd64 passes haswell to both as before; arm64 passes +crc,
which rustc does not enable by default. TARGET_CPU still drives the tag
and artefact suffix.
2026-10-04 22:31:28 +00:00
29 changed files with 290 additions and 654 deletions

No files matched your search

+149
View File
@@ -0,0 +1,149 @@
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
+38 -2
View File
@@ -30,7 +30,7 @@ env:
jobs:
build-release:
name: "Build ${{ matrix.slug }} (release)"
runs-on: dind
runs-on: ${{ matrix.runner }}
permissions:
contents: read
packages: write
@@ -41,14 +41,29 @@ 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
@@ -73,8 +88,11 @@ 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 }}
@@ -115,7 +133,7 @@ jobs:
build-maxperf:
name: "Build ${{ matrix.slug }} (max-perf)"
runs-on: dind
runs-on: ${{ matrix.runner }}
needs: build-release
permissions:
contents: read
@@ -128,15 +146,30 @@ 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
@@ -161,8 +194,11 @@ 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 }}
-3
View File
@@ -659,9 +659,6 @@ default-features = false
[workspace.dependencies.ruminuwuity]
package = "ruminuwuity"
path = "src/ruminuwuity"
features = [
"unstable-msc4484"
]
###############################################################################
#
+23 -8
View File
@@ -1,6 +1,10 @@
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
@@ -118,15 +122,19 @@ 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_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
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
fi
EOF
@@ -245,6 +253,13 @@ 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
@@ -254,14 +269,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=builder /out/libs-root/ /layer1/
COPY --from=artifacts /out/libs-root/ /layer1/
# Copy application libraries to layer2 (semi-stable)
COPY --from=builder /out/libs/ /layer2/usr/lib/
COPY --from=artifacts /out/libs/ /layer2/usr/lib/
# Copy binaries and SBOM to layer3 (volatile)
COPY --from=builder /out/sbin/ /layer3/sbin/
COPY --from=builder /out/sbom/ /layer3/sbom/
COPY --from=artifacts /out/sbin/ /layer3/sbin/
COPY --from=artifacts /out/sbom/ /layer3/sbom/
# Fix permissions after copying
RUN chmod -R 755 /layer1 /layer2 /layer3
-1
View File
@@ -1,2 +1 @@
pub mod rooms;
pub mod users;
+1 -1
View File
@@ -6,7 +6,7 @@ use ruminuwuity::admin::continuwuity::rooms;
use crate::{Ruma, client::leave_room};
/// # `PUT /_continuwuity/admin/v1/rooms/{roomID}/ban`
/// # `PUT /_continuwuity/admin/rooms/{roomID}/ban`
///
/// Bans or unbans a room.
pub(crate) async fn ban_room(
+1 -1
View File
@@ -6,7 +6,7 @@ use ruminuwuity::admin::continuwuity::rooms;
use crate::Ruma;
/// # `GET /_continuwuity/admin/v1/rooms/list`
/// # `GET /_continuwuity/admin/rooms/list`
///
/// Lists all rooms known to this server, excluding banned ones.
pub(crate) async fn list_rooms(
-69
View File
@@ -1,69 +0,0 @@
use axum::extract::State;
use conduwuit::{Err, error};
use ruma::{api::client::profile::PropagateTo, profile::ProfileFieldValue};
use ruminuwuity::admin::continuwuity::users::create::v1::{Request, Response};
use service::users::{HashedPassword, ProfileFieldChange};
use crate::router::Ruma;
/// # `POST /_continuwuity/admin/v1/users`
///
/// Creates a new user on the homeserver.
pub(crate) async fn create_user(
State(services): State<crate::State>,
body: Ruma<Request>,
) -> conduwuit::Result<Response> {
let sender_user = body.identity.expect_sender_user()?;
if !services.users.is_admin(sender_user).await {
return Err!(Request(Forbidden("Only server administrators can use this endpoint")));
}
if !services.globals.user_is_local(&body.user_id) {
return Err!(Request(InvalidParam("User ID does not belong to this server.")));
}
if services.users.status(&body.user_id).await.is_found() {
return Err!(Request(UserInUse("An account with this user ID already exists.")));
}
services
.users
.create_local_account(
&body.user_id,
body.password
.as_ref()
.and_then(|raw| HashedPassword::new(raw).ok()),
None,
None,
None,
)
.await?;
if body.locked {
services
.users
.lock_account(&body.user_id, sender_user)
.await;
}
if body.suspended {
services
.users
.suspend_account(&body.user_id, sender_user)
.await;
}
for (key, value) in body.profile.clone().unwrap_or_default() {
services
.users
.set_profile_field(
&body.user_id,
ProfileFieldChange::Set(ProfileFieldValue::new(&key, value)?),
PropagateTo::All,
)
.await
.inspect_err(|e| error!(error=?e, %key, "Failed to set profile field"))
.ok();
}
if body.admin {
services.admin.make_user_admin(&body.user_id).await?;
}
Ok(Response::default())
}
-99
View File
@@ -1,99 +0,0 @@
use std::collections::BTreeMap;
use axum::extract::State;
use conduwuit::{
Err,
utils::{TryFutureExtExt, stream::WidebandExt},
};
use futures::StreamExt;
use ruminuwuity::admin::continuwuity::users::list::v1::{QueryFilter, Request, Response, User};
use service::users::AccountStatus;
use crate::router::Ruma;
/// # `GET /_continuwuity/admin/v1/users`
///
/// Lists users on this homeserver
pub(crate) async fn list_users(
State(services): State<crate::State>,
body: Ruma<Request>,
) -> conduwuit::Result<Response> {
if !services
.users
.is_admin(body.identity.expect_sender_user()?)
.await
{
return Err!(Request(Forbidden("Only server administrators can use this endpoint")));
}
let limit = body.limit.unwrap_or(100);
let offset = limit.saturating_mul(body.page.unwrap_or_default());
let users = services
.users
.stream_local_users()
.wide_filter_map(|user_id| {
let body = &body;
async move {
let status = services.users.status(&user_id).await;
assert_ne!(
status,
AccountStatus::NotFound,
"Not found users should not appear in stream_local_users"
);
let (deactivated, locked, suspended, admin) = tokio::join!(
std::future::ready(status == AccountStatus::Deactivated),
services.users.is_locked(&user_id).unwrap_or_default(),
services.users.is_suspended(&user_id).unwrap_or_default(),
services.users.is_admin(&user_id),
);
// Exclude deactivated accounts by default
if !deactivated && body.active == Some(QueryFilter::Exclude) {
return None;
}
if deactivated
&& body
.deactivated
.as_ref()
.is_none_or(|d| *d == QueryFilter::Include)
{
return None;
}
// Exclude locked accounts by default
if locked && body.locked != Some(QueryFilter::Include) {
return None;
}
// Include suspended accounts by default
if suspended && body.suspended == Some(QueryFilter::Exclude) {
return None;
}
// Include admins by default
if admin && body.admin == Some(QueryFilter::Exclude) {
return None;
}
Some((user_id, deactivated, suspended, locked, admin))
}
})
.skip(offset)
.wide_then(|(user_id, deactivated, suspended, locked, admin)| async move {
let (displayname, avatar_url) = tokio::join!(
services.users.displayname(&user_id).ok(),
services.users.avatar_url(&user_id).ok(),
);
let user = User {
displayname,
avatar_url,
suspended,
locked,
deactivated,
admin,
};
(user_id, user)
})
.take(limit)
.collect::<BTreeMap<_, _>>()
.await;
Ok(Response::new(users))
}
-3
View File
@@ -1,3 +0,0 @@
pub mod create;
pub mod list;
pub mod rooms;
-134
View File
@@ -1,134 +0,0 @@
use axum::extract::State;
use conduwuit::{
Err, Event, at,
utils::{IterStream, ReadyExt, TryFutureExtExt, stream::WidebandExt},
};
use futures::StreamExt;
use ruma::events::room::member::MembershipState;
use ruminuwuity::admin::continuwuity::users::rooms::v1::{Request, Response, RoomInfo};
use serde::Deserialize;
use crate::router::Ruma;
/// # `GET /_continuwuity/admin/v1/users/{user_id}/rooms`
///
/// Lists the memberships of a user on this server.
pub(crate) async fn list_user_rooms(
State(services): State<crate::State>,
body: Ruma<Request>,
) -> conduwuit::Result<Response> {
if !services
.users
.is_admin(body.identity.expect_sender_user()?)
.await
{
return Err!(Request(Forbidden("Only server administrators can use this endpoint")));
}
let limit = body.limit.unwrap_or(100).try_into()?;
let offset = body
.limit
.unwrap_or(100)
.saturating_mul(body.page.unwrap_or_default())
.try_into()?;
let room_ids: Vec<_> = match body.state {
| MembershipState::Join =>
services
.rooms
.state_cache
.rooms_joined(&body.user_id)
.skip(offset)
.take(limit)
.collect()
.await,
| MembershipState::Invite =>
services
.rooms
.state_cache
.rooms_invited(&body.user_id)
.skip(offset)
.take(limit)
.map(at!(0))
.collect()
.await,
| MembershipState::Knock =>
services
.rooms
.state_cache
.rooms_knocked(&body.user_id)
.skip(offset)
.take(limit)
.map(at!(0))
.collect()
.await,
| MembershipState::Leave =>
services
.rooms
.state_cache
.rooms_left(&body.user_id)
.skip(offset)
.take(limit)
.ready_filter_map(|(room_id, pdu)| {
pdu.is_some_and(|pdu| {
pdu.get_content::<ExtractMembership>()
.expect("membership PDU must have a membership field")
.membership
== MembershipState::Leave
})
.then_some(room_id)
})
.collect()
.await,
| MembershipState::Ban =>
services
.rooms
.state_cache
.rooms_left(&body.user_id)
.skip(offset)
.take(limit)
.ready_filter_map(|(room_id, pdu)| {
pdu.is_some_and(|pdu| {
pdu.get_content::<ExtractMembership>()
.expect("membership PDU must have a membership field")
.membership
== MembershipState::Ban
})
.then_some(room_id)
})
.collect()
.await,
| _ => return Err!(Request(InvalidParam("Unknown membership kind: {:?}", body.state))),
};
let resp = room_ids
.into_iter()
.stream()
.wide_then(|room_id| async move {
let (name, avatar, alias, members) = tokio::join!(
services.rooms.state_accessor.get_name(&room_id).ok(),
services.rooms.state_accessor.get_avatar(&room_id),
services
.rooms
.state_accessor
.get_canonical_alias(&room_id)
.ok(),
services.rooms.state_cache.room_members(&room_id).count(),
);
(room_id, RoomInfo {
name,
avatar_url: avatar.into_option().and_then(|a| a.url),
canonical_alias: alias,
member_count: members.try_into().unwrap_or(0),
})
})
.collect()
.await;
Ok(Response::new(resp))
}
#[derive(Deserialize)]
struct ExtractMembership {
pub membership: MembershipState,
}
+2 -10
View File
@@ -267,19 +267,11 @@ 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);
+1 -4
View File
@@ -55,8 +55,5 @@ 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))
}
+12 -17
View File
@@ -1563,25 +1563,20 @@ 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,
);
}
}
+8 -14
View File
@@ -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,17 +112,14 @@ 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)
@@ -197,10 +194,7 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
.merge(client::oauth::router(state))
.route("/_continuwuity/server_version", get(client::continuwuity_server_version))
.ruma_route(&admin::rooms::ban::ban_room)
.ruma_route(&admin::rooms::list::list_rooms)
.ruma_route(&admin::users::list::list_users)
.ruma_route(&admin::users::create::create_user)
.ruma_route(&admin::users::rooms::list_user_rooms);
.ruma_route(&admin::rooms::list::list_rooms);
if config.allow_federation {
router = router
+1 -2
View File
@@ -11,14 +11,13 @@ version.workspace = true
path = "mod.rs"
[features]
default = ["client", "server", "unstable-msc4484"]
default = ["client", "server"]
client = []
server = []
unstable-exhaustive-types = []
unstable-msc3202 = []
unstable-msc4203 = []
unstable-msc4484 = ["ruma/unstable-msc4484"]
[dependencies]
assign.workspace = true
@@ -1,2 +1 @@
pub mod rooms;
pub mod users;
@@ -1,7 +1,7 @@
pub mod v1 {
use ruma::{
OwnedRoomAliasId, OwnedRoomId, OwnedUserId,
api::{OAuthClientScope, auth_scheme::AccessToken, request, response},
api::{auth_scheme::AccessToken, request, response},
metadata,
};
@@ -10,9 +10,8 @@ pub mod v1 {
rate_limited: false,
authentication: AccessToken,
history: {
1.0 => "/_continuwuity/admin/v1/rooms/{room_id}/ban",
},
required_client_scopes: [OAuthClientScope::ServerAdministration]
1.0 => "/_continuwuity/admin/rooms/{room_id}/ban",
}
}
#[request]
@@ -1,7 +1,7 @@
pub mod v1 {
use ruma::{
OwnedRoomId,
api::{OAuthClientScope, auth_scheme::AccessToken, request, response},
api::{auth_scheme::AccessToken, request, response},
metadata,
};
@@ -10,9 +10,8 @@ pub mod v1 {
rate_limited: false,
authentication: AccessToken,
history: {
1.0 => "/_continuwuity/admin/v1/rooms/list",
},
required_client_scopes: [OAuthClientScope::ServerAdministration]
1.0 => "/_continuwuity/admin/rooms/list",
}
}
#[request]
@@ -1,58 +0,0 @@
pub mod v1 {
use ruma::{
OwnedUserId,
api::{OAuthClientScope, auth_scheme::AccessToken, request, response},
metadata,
profile::UserProfile,
};
metadata! {
method: POST,
rate_limited: false,
authentication: AccessToken,
history: {
1.0 => "/_continuwuity/admin/v1/users",
},
required_client_scopes: [OAuthClientScope::ServerAdministration]
}
#[request]
pub struct Request {
/// The full user ID to create. Must belong to the server.
pub user_id: OwnedUserId,
/// The password to set for the new user.
///
/// If `None`, the user will not be able to log in.
#[serde(default, skip_serializing_if = "ruma::serde::is_default")]
pub password: Option<String>,
/// The profile fields to set for the user. This can be used to set the
/// new user's display name and profile picture.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub profile: Option<UserProfile>,
#[serde(default, skip_serializing_if = "ruma::serde::is_default")]
pub admin: bool,
#[serde(default, skip_serializing_if = "ruma::serde::is_default")]
pub suspended: bool,
#[serde(default, skip_serializing_if = "ruma::serde::is_default")]
pub locked: bool,
}
#[derive(Default)]
#[response]
pub struct Response;
impl Request {
#[must_use]
pub fn new(user_id: OwnedUserId) -> Self {
Self {
user_id,
password: None,
profile: None,
admin: false,
suspended: false,
locked: false,
}
}
}
}
@@ -1,84 +0,0 @@
pub mod v1 {
use std::collections::BTreeMap;
use ruma::{
OwnedMxcUri, OwnedUserId,
api::{OAuthClientScope, auth_scheme::AccessToken, request, response},
metadata,
};
use serde::{Deserialize, Serialize};
metadata! {
method: GET,
rate_limited: false,
authentication: AccessToken,
history: {
1.0 => "/_continuwuity/admin/v1/users",
},
required_client_scopes: [OAuthClientScope::ServerAdministration]
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq, Copy)]
pub enum QueryFilter {
/// Always include entities matching this criteria.
#[serde(rename = "include")]
Include,
/// Never include entities matching this criteria.
#[serde(rename = "exclude")]
Exclude,
}
#[derive(Default)]
#[request]
#[serde(default)]
pub struct Request {
#[ruma_api(query)]
#[serde(skip_serializing_if = "Option::is_none")]
pub active: Option<QueryFilter>,
#[ruma_api(query)]
#[serde(skip_serializing_if = "Option::is_none")]
pub deactivated: Option<QueryFilter>,
#[ruma_api(query)]
#[serde(skip_serializing_if = "Option::is_none")]
pub suspended: Option<QueryFilter>,
#[ruma_api(query)]
#[serde(skip_serializing_if = "Option::is_none")]
pub locked: Option<QueryFilter>,
#[ruma_api(query)]
#[serde(skip_serializing_if = "Option::is_none")]
pub admin: Option<QueryFilter>,
#[ruma_api(query)]
#[serde(skip_serializing_if = "Option::is_none")]
pub limit: Option<usize>,
#[ruma_api(query)]
#[serde(skip_serializing_if = "Option::is_none")]
pub page: Option<usize>,
}
#[derive(Default, Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
pub struct User {
#[serde(skip_serializing_if = "Option::is_none")]
pub displayname: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub avatar_url: Option<OwnedMxcUri>,
#[serde(skip_serializing_if = "ruma::serde::is_default")]
pub suspended: bool,
#[serde(skip_serializing_if = "ruma::serde::is_default")]
pub locked: bool,
#[serde(skip_serializing_if = "ruma::serde::is_default")]
pub deactivated: bool,
#[serde(skip_serializing_if = "ruma::serde::is_default")]
pub admin: bool,
}
#[response]
pub struct Response {
#[ruma_api(body)]
pub users: BTreeMap<OwnedUserId, User>,
}
impl Response {
#[must_use]
pub fn new(users: BTreeMap<OwnedUserId, User>) -> Self { Self { users } }
}
}
@@ -1,3 +0,0 @@
pub mod create;
pub mod list;
pub mod rooms;
@@ -1,66 +0,0 @@
pub mod v1 {
use std::collections::BTreeMap;
use ruma::{
OwnedMxcUri, OwnedRoomAliasId, OwnedRoomId, OwnedUserId,
api::{OAuthClientScope, auth_scheme::AccessToken, request, response},
events::room::member::MembershipState,
metadata,
};
use serde::{Deserialize, Serialize};
metadata! {
method: GET,
rate_limited: false,
authentication: AccessToken,
history: {
1.0 => "/_continuwuity/admin/v1/users/{user_id}/rooms",
},
required_client_scopes: [OAuthClientScope::ServerAdministration]
}
#[request]
pub struct Request {
#[ruma_api(path)]
pub user_id: OwnedUserId,
pub state: MembershipState,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub page: Option<u32>,
}
#[derive(Debug, Deserialize, Serialize, Default, Clone)]
pub struct RoomInfo {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub avatar_url: Option<OwnedMxcUri>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub canonical_alias: Option<OwnedRoomAliasId>,
pub member_count: u32,
}
#[response]
pub struct Response {
pub rooms: BTreeMap<OwnedRoomId, RoomInfo>,
}
impl Request {
#[must_use]
pub fn new(
user_id: OwnedUserId,
state: MembershipState,
limit: Option<u32>,
page: Option<u32>,
) -> Self {
Self { user_id, state, limit, page }
}
}
impl Response {
#[must_use]
pub fn new(rooms: BTreeMap<OwnedRoomId, RoomInfo>) -> Self { Self { rooms } }
}
}
+1 -2
View File
@@ -571,8 +571,7 @@ impl Service {
));
}
let device_id = self
.services
let device_id = self.services
.users
.create_device(
&authorizing_user,
+2 -6
View File
@@ -72,10 +72,7 @@ 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)
@@ -83,8 +80,7 @@ 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
+41 -44
View File
@@ -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,46 +323,43 @@ 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)),
+2 -7
View File
@@ -449,12 +449,7 @@ 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;
@@ -811,7 +806,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()
+1 -1
View File
@@ -37,7 +37,7 @@ pub enum AccessTokenStatus {
}
/// The status of a user account.
#[derive(Clone, Copy, PartialEq, Debug, Eq)]
#[derive(Clone, Copy)]
pub enum AccountStatus {
NotFound,
Active,
+1 -6
View File
@@ -449,12 +449,7 @@ 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