Compare commits

..
Author SHA1 Message Date
Renovate Bot ac7f8f6b9f chore(deps): update rust crate built to 0.9 2026-11-22 05:02:54 +00:00
Erwan Leboucher 919fea9b97 fix: Index remote events by origin_server_ts 2026-11-22 02:02:37 +00:00
Erwan Leboucher 5687847fe3 style: Address review nits on timestamp index 2026-11-22 02:02:37 +00:00
Erwan Leboucher 251086670f feat: Add timestamp to event endpoint backed by a timestamp index 2026-11-22 02:02:37 +00:00
Jade Ellis 3379badbd4 fix(service): Prevent potential corruption in state diffs
This fixes a non-atomicity issue. Also fixes incorrect
calculation of a buffer size that would result in
reallocation.
2026-11-22 01:02:59 +00:00
Jade Ellis cc28a01e49 fix(core): Fix BoolExt::or short-circuiting
This would mean that or would return false when one of the
inputs was true.

Also fix double futures in type signatures
2026-11-21 21:38:55 +00:00
Renovate Bot 95392ccc46 chore(deps): update rust-non-major 2026-11-21 20:14:56 +00:00
Julian Anderson f3289f150c ci(docs): Set Rspress config values based on prod/preview status 2026-11-21 14:15:26 -05:00
Julian Anderson cbc089df1b ci(docs): Expire preview doc deployments after 14 days 2026-11-21 13:27:50 -05:00
Julian Anderson 0b738e835b ci(docs): Replace preview docs workflow with Grebedoc 2026-11-21 13:27:47 -05:00
20 changed files with 486 additions and 172 deletions

No files matched your search

+14 -6
View File
@@ -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 }}
Generated
+17 -17
View File
@@ -574,9 +574,9 @@ dependencies = [
[[package]]
name = "built"
version = "0.8.1"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c0e531d93d39c34eef561e929e8a7f86d77a5af08aac4f6d6e39976c51858e9"
checksum = "6192709ebc97997197804bcbb092ef897b5a6a2f33e2c77779f694dbe90fec1e"
[[package]]
name = "bumpalo"
@@ -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]]
@@ -764,9 +764,9 @@ dependencies = [
[[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",
@@ -1029,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",
@@ -2104,9 +2104,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",
]
@@ -5135,7 +5135,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]]
@@ -6395,9 +6395,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",
@@ -6454,9 +6454,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",
]
@@ -6853,9 +6853,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",
@@ -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.
+18 -38
View File
@@ -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
View File
@@ -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
View File
@@ -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"
}
]
})],
+3 -1
View File
@@ -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,
};
+61
View File
@@ -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
)))
}
+1
View File
@@ -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)
+1 -1
View File
@@ -27,7 +27,7 @@ crate-type = [
[dependencies]
[build-dependencies]
built = { version = "0.8", features = [] }
built = { version = "0.9", features = [] }
cargo_metadata = { version = "0.23.1" }
[lints]
workspace = true
+79 -15
View File
@@ -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");
}
}
+4
View File
@@ -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
+69 -3
View File
@@ -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();
+19 -19
View File
@@ -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.
+43 -40
View File
@@ -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
+31 -15
View File
@@ -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);
+1 -1
View File
@@ -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
+2 -1
View File
@@ -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 {
+95 -1
View File
@@ -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);
}
}
}
+17 -3
View File
@@ -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>(